File: tasources.pas

package info (click to toggle)
lazarus 2.0.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 214,460 kB
  • sloc: pascal: 1,862,622; xml: 265,709; cpp: 56,595; sh: 3,008; java: 609; makefile: 535; perl: 297; sql: 222; ansic: 137
file content (1392 lines) | stat: -rw-r--r-- 36,583 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
{

 *****************************************************************************
  See the file COPYING.modifiedLGPL.txt, included in this distribution,
  for details about the license.
 *****************************************************************************

  Authors: Alexander Klenin

}

unit TASources;

{$H+}

interface

uses
  Classes, Types, TAChartUtils, TACustomSource;

type
  { TListChartSource }

  TListChartSource = class(TCustomChartSource)
  private
    FData: TFPList;
    FDataPoints: TStrings;
    FSorted: Boolean;

    procedure AddAt(
      APos: Integer; AX, AY: Double; const ALabel: String; AColor: TChartColor);
    procedure ClearCaches;
    function NewItem: PChartDataItem;
    procedure SetDataPoints(AValue: TStrings);
    procedure SetSorted(AValue: Boolean);
    procedure UpdateCachesAfterAdd(AX, AY: Double);
  protected
    function GetCount: Integer; override;
    function GetItem(AIndex: Integer): PChartDataItem; override;
    procedure SetXCount(AValue: Cardinal); override;
    procedure SetYCount(AValue: Cardinal); override;
  public
    type
      EYListEmptyError = class(EChartError);
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  public
    function Add(
      AX, AY: Double; const ALabel: String = '';
      AColor: TChartColor = clTAColor): Integer;
    function AddXYList(
      AX: Double; const AY: array of Double; const ALabel: String = '';
      AColor: TChartColor = clTAColor): Integer;
    procedure Clear;
    procedure CopyFrom(ASource: TCustomChartSource);
    procedure Delete(AIndex: Integer);
    function IsSorted: Boolean; override;

    procedure SetColor(AIndex: Integer; AColor: TChartColor);
    procedure SetText(AIndex: Integer; AValue: String);
    function SetXValue(AIndex: Integer; AValue: Double): Integer;
    procedure SetXList(AIndex: Integer; const AXList: array of Double);
    procedure SetYList(AIndex: Integer; const AYList: array of Double);
    procedure SetYValue(AIndex: Integer; AValue: Double);

    procedure Sort;
  published
    property DataPoints: TStrings read FDataPoints write SetDataPoints;
    property Sorted: Boolean read FSorted write SetSorted default false;
    property XErrorBarData;
    property YErrorBarData;
    property YCount;
  end;

  { TMWCRandomGenerator }

  // Mutliply-with-carry random number generator.
  // Algorithm by George Marsaglia.
  // A generator is incapsulated in a class to allow using many simultaneous
  // random sequences, each determined by its own seed.
  TMWCRandomGenerator = class
  strict private
    FHistory: array [0..4] of LongWord;
    procedure SetSeed(AValue: Integer);
  public
    function Get: LongWord;
    function GetInRange(AMin, AMax: Integer): Integer;
    property Seed: Integer write SetSeed;
  end;

  { TRandomChartSource }

  TRandomChartSource = class(TCustomChartSource)
  strict private
    FPointsNumber: Integer;
    FRandomX: Boolean;
    FRandSeed: Integer;
    FXMax: Double;
    FXMin: Double;
    FYMax: Double;
    FYMin: Double;
    FYNanPercent: TPercent;
  strict private
    FCurIndex: Integer;
    FCurItem: TChartDataItem;
    FRNG: TMWCRandomGenerator;

    procedure Reset;
    procedure SetPointsNumber(AValue: Integer);
    procedure SetRandomX(AValue: Boolean);
    procedure SetRandSeed(AValue: Integer);
    procedure SetXMax(AValue: Double);
    procedure SetXMin(AValue: Double);
    procedure SetYMax(AValue: Double);
    procedure SetYMin(AValue: Double);
    procedure SetYNanPercent(AValue: TPercent);
  protected
    procedure ChangeErrorBars(Sender: TObject); override;
    function GetCount: Integer; override;
    function GetItem(AIndex: Integer): PChartDataItem; override;
    procedure SetXCount(AValue: Cardinal); override;
    procedure SetYCount(AValue: Cardinal); override;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  public
    function IsSorted: Boolean; override;
  published
    property PointsNumber: Integer
      read FPointsNumber write SetPointsNumber default 0;
    property RandomX: Boolean read FRandomX write SetRandomX default false;
    property RandSeed: Integer read FRandSeed write SetRandSeed;
    property XCount;
    property XMax: Double read FXMax write SetXMax;
    property XMin: Double read FXMin write SetXMin;
    property YCount;
    property YMax: Double read FYMax write SetYMax;
    property YMin: Double read FYMin write SetYMin;
    property YNanPercent: TPercent read FYNanPercent write SetYNanPercent default 0;
    property XErrorBarData;
    property YErrorBarData;
  end;

  TUserDefinedChartSource = class;

  TGetChartDataItemEvent = procedure (
    ASource: TUserDefinedChartSource; AIndex: Integer;
    var AItem: TChartDataItem) of object;

  { TUserDefinedChartSource }

  TUserDefinedChartSource = class(TCustomChartSource)
  strict private
    FItem: TChartDataItem;
    FOnGetChartDataItem: TGetChartDataItemEvent;
    FPointsNumber: Integer;
    FSorted: Boolean;
    procedure SetOnGetChartDataItem(AValue: TGetChartDataItemEvent);
    procedure SetPointsNumber(AValue: Integer);
  protected
    function GetCount: Integer; override;
    function GetItem(AIndex: Integer): PChartDataItem; override;
    procedure SetXCount(AValue: Cardinal); override;
    procedure SetYCount(AValue: Cardinal); override;
  public
    procedure EndUpdate; override;
    function IsSorted: Boolean; override;
    procedure Reset; inline;
  published
    property OnGetChartDataItem: TGetChartDataItemEvent
      read FOnGetChartDataItem write SetOnGetChartDataItem;
    property PointsNumber: Integer
      read FPointsNumber write SetPointsNumber default 0;
    property Sorted: Boolean read FSorted write FSorted default false;
    property XErrorBarData;
    property YErrorBarData;
  end;

  TChartAccumulationMethod = (
    camNone, camSum, camAverage, camDerivative, camSmoothDerivative);
  TChartAccumulationDirection = (cadBackward, cadForward, cadCenter);

  { TCalculatedChartSource }

  TCalculatedChartSource = class(TCustomChartSource)
  strict private
    FAccumulationDirection: TChartAccumulationDirection;
    FAccumulationMethod: TChartAccumulationMethod;
    FAccumulationRange: Cardinal;
    FHistory: TChartSourceBuffer;
    FIndex: Integer;
    FItem: TChartDataItem;
    FListener: TListener;
    FOrigin: TCustomChartSource;
    FOriginYCount: Cardinal;
    FPercentage: Boolean;
    FReorderYList: String;
    FYOrder: array of Integer;

    procedure CalcAccumulation(AIndex: Integer);
    procedure CalcDerivative(AIndex: Integer);
    procedure CalcPercentage;
    procedure Changed(ASender: TObject);
    function EffectiveAccumulationRange: Cardinal;
    procedure ExtractItem(AIndex: Integer);
    function IsDerivative: Boolean; inline;
    procedure RangeAround(AIndex: Integer; out ALeft, ARight: Integer);
    procedure SetAccumulationDirection(AValue: TChartAccumulationDirection);
    procedure SetAccumulationMethod(AValue: TChartAccumulationMethod);
    procedure SetAccumulationRange(AValue: Cardinal);
    procedure SetOrigin(AValue: TCustomChartSource);
    procedure SetPercentage(AValue: Boolean);
    procedure SetReorderYList(const AValue: String);
    procedure UpdateYOrder;
  protected
    function GetCount: Integer; override;
    function GetItem(AIndex: Integer): PChartDataItem; override;
    procedure SetXCount(AValue: Cardinal); override;
    procedure SetYCount(AValue: Cardinal); override;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;

    function IsSorted: Boolean; override;
  published
    property AccumulationDirection: TChartAccumulationDirection
      read FAccumulationDirection write SetAccumulationDirection
      default cadBackward;
    property AccumulationMethod: TChartAccumulationMethod
      read FAccumulationMethod write SetAccumulationMethod default camNone;
    property AccumulationRange: Cardinal
      read FAccumulationRange write SetAccumulationRange default 2;

    property Origin: TCustomChartSource read FOrigin write SetOrigin;
    property Percentage: Boolean
      read FPercentage write SetPercentage default false;
    property ReorderYList: String read FReorderYList write SetReorderYList;
  end;

procedure Register;

implementation

uses
  Math, StrUtils, SysUtils, TAMath;

type

  { TListChartSourceStrings }

  TListChartSourceStrings = class(TStrings)
  strict private
    FSource: TListChartSource;
    procedure Parse(AString: String; ADataItem: PChartDataItem);
  protected
    function Get(Index: Integer): String; override;
    function GetCount: Integer; override;
    procedure Put(Index: Integer; const S: String); override;
    procedure SetUpdateState(AUpdating: Boolean); override;
  public
    constructor Create(ASource: TListChartSource);
    procedure Clear; override;
    procedure Delete(Index: Integer); override;
    procedure Insert(Index: Integer; const S: String); override;
  end;

procedure Register;
begin
  RegisterComponents(
    CHART_COMPONENT_IDE_PAGE, [
      TListChartSource, TRandomChartSource, TUserDefinedChartSource,
      TCalculatedChartSource
    ]);
end;

{ TListChartSourceStrings }

procedure TListChartSourceStrings.Clear;
begin
  FSource.Clear;
end;

constructor TListChartSourceStrings.Create(ASource: TListChartSource);
begin
  inherited Create;
  FSource := ASource;
end;

procedure TListChartSourceStrings.Delete(Index: Integer);
begin
  FSource.Delete(Index);
end;

function TListChartSourceStrings.Get(Index: Integer): String;
var
  i: Integer;
  fs: TFormatSettings;
begin
  fs := DefaultFormatSettings;
  fs.DecimalSeparator := '.';
  with FSource[Index]^ do begin
    Result := Format('%g', [X], fs);
    if FSource.YCount > 0 then
      Result += Format('|%g', [Y], fs);
    for i := 0 to High(YList) do
      Result += Format('|%g', [YList[i]], fs);
    Result += Format('|%s|%s', [IntToColorHex(Color), Text]);
  end;
end;

function TListChartSourceStrings.GetCount: Integer;
begin
  Result := FSource.Count;
end;

procedure TListChartSourceStrings.Insert(Index: Integer; const S: String);
var
  item: PChartDataItem;
begin
  item := FSource.NewItem;
  FSource.FData.Insert(Index, item);
  Parse(S, item);
  FSource.UpdateCachesAfterAdd(item^.X, item^.Y);
end;

procedure TListChartSourceStrings.Parse(
  AString: String; ADataItem: PChartDataItem);
var
  p: Integer = 0;
  parts: TStrings;

  function NextPart: String;
  begin
    if p < parts.Count then
      Result := parts[p]
    else
      Result := '';
    p += 1;
  end;

var
  i: Integer;
begin
  parts := Split(AString);
  try
    if FSource.YCount + 3 < Cardinal(parts.Count) then
      FSource.YCount := parts.Count - 3;
    with ADataItem^ do begin
      X := StrToFloatOrDateTimeDef(NextPart);
      if FSource.YCount > 0 then begin
        Y := StrToFloatOrDateTimeDef(NextPart);
        for i := 0 to High(YList) do
          YList[i] := StrToFloatOrDateTimeDef(NextPart);
      end;
      Color := StrToIntDef(NextPart, clTAColor);
      Text := NextPart;
    end;
  finally
    parts.Free;
  end;
end;

procedure TListChartSourceStrings.Put(Index: Integer; const S: String);
begin
  FSource.BeginUpdate;
  try
  Parse(S, FSource[Index]);
  finally
    FSource.EndUpdate;
  end;
end;

procedure TListChartSourceStrings.SetUpdateState(AUpdating: Boolean);
begin
  if AUpdating then
    FSource.BeginUpdate
  else
    FSource.EndUpdate;
end;

{ TListChartSource }

function TListChartSource.Add(
  AX, AY: Double; const ALabel: String; AColor: TChartColor): Integer;
begin
  Result := FData.Count;
  if Sorted then
    // Keep data points ordered by X coordinate.
    // Note that this leads to O(N^2) time except
    // for the case of adding already ordered points.
    // So, is the user wants to add many (>10000) points to a graph,
    // he should pre-sort them to avoid performance penalty.
    while (Result > 0) and (Item[Result - 1]^.X > AX) do
      Dec(Result);
  AddAt(Result, AX, AY, ALabel, AColor);
end;

procedure TListChartSource.AddAt(
  APos: Integer; AX, AY: Double; const ALabel: String; AColor: TChartColor);
var
  pcd: PChartDataItem;
begin
  pcd := NewItem;
  pcd^.X := AX;
  pcd^.Y := AY;
  pcd^.Color := AColor;
  pcd^.Text := ALabel;
  FData.Insert(APos, pcd);
  UpdateCachesAfterAdd(AX, AY);
end;

function TListChartSource.AddXYList(
  AX: Double; const AY: array of Double;
  const ALabel: String; AColor: TChartColor): Integer;
begin
  if Length(AY) = 0 then
    raise EYListEmptyError.Create('AddXYList: Y List is empty');
  Result := Add(AX, AY[0], ALabel, AColor);
  if Length(AY) > 1 then
    SetYList(Result, AY[1..High(AY)]);
end;

procedure TListChartSource.Clear; inline;
var
  i: Integer;
begin
  for i := 0 to FData.Count - 1 do
    Dispose(Item[i]);
  FData.Clear;
  ClearCaches;
  Notify;
end;

procedure TListChartSource.ClearCaches;
begin
  FExtent := EmptyExtent;
  FExtentIsValid := true;
  FValuesTotal := 0;
  FValuesTotalIsValid := true;
end;

procedure TListChartSource.CopyFrom(ASource: TCustomChartSource);
var
  i: Integer;
begin
  BeginUpdate;
  try
    Clear;
    YCount := ASource.YCount;
    for i := 0 to ASource.Count - 1 do
      with ASource[i]^ do begin
        AddAt(FData.Count, X, Y, Text, Color);
        SetYList(FData.Count - 1, YList);
      end;
    if Sorted and not ASource.IsSorted then Sort;
  finally
    EndUpdate;
  end;
end;

constructor TListChartSource.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FData := TFPList.Create;
  FDataPoints := TListChartSourceStrings.Create(Self);
  FYCount := 1;
  ClearCaches;
end;

procedure TListChartSource.Delete(AIndex: Integer);
begin
  with Item[AIndex]^ do begin
    FExtentIsValid := FExtentIsValid and
      (FExtent.a.X < X) and (X < FExtent.b.X) and
      (FExtent.a.Y < Y) and (Y < FExtent.b.Y);
    if FValuesTotalIsValid then
      FValuesTotal -= NumberOr(Y);
  end;
  Dispose(Item[AIndex]);
  FData.Delete(AIndex);
  Notify;
end;

destructor TListChartSource.Destroy;
begin
  Clear;
  FreeAndNil(FDataPoints);
  FreeAndNil(FData);
  inherited;
end;

function TListChartSource.GetCount: Integer;
begin
  Result := FData.Count;
end;

function TListChartSource.GetItem(AIndex: Integer): PChartDataItem;
begin
  Result := PChartDataItem(FData.Items[AIndex]);
end;

function TListChartSource.IsSorted: Boolean;
begin
  Result := Sorted;
end;

function TListChartSource.NewItem: PChartDataItem;
begin
  New(Result);
  SetLength(Result^.XList, Max(XCount - 1, 0));
  SetLength(Result^.YList, Max(YCount - 1, 0));
end;

procedure TListChartSource.SetColor(AIndex: Integer; AColor: TChartColor);
begin
  with Item[AIndex]^ do begin
    if Color = AColor then exit;
    Color := AColor;
  end;
  Notify;
end;

procedure TListChartSource.SetDataPoints(AValue: TStrings);
begin
  if FDataPoints = AValue then exit;
  BeginUpdate;
  try
    FDataPoints.Assign(AValue);
    if Sorted then Sort;
  finally
    EndUpdate;
  end;
end;

procedure TListChartSource.SetSorted(AValue: Boolean);
begin
  if FSorted = AValue then exit;
  FSorted := AValue;
  if Sorted then begin
    Sort;
    Notify;
  end;
end;

procedure TListChartSource.SetText(AIndex: Integer; AValue: String);
begin
  with Item[AIndex]^ do begin
    if Text = AValue then exit;
    Text := AValue;
  end;
  Notify;
end;

procedure TListChartSource.SetXCount(AValue: Cardinal);
var
  i: Integer;
begin
  if AValue = FXCount then exit;
  FXCount := AValue;
  for i := 0 to Count - 1 do
    SetLength(Item[i]^.XList, Max(FXCount - 1, 0));
end;

procedure TListChartSource.SetXList(
  AIndex: Integer; const AXList: array of Double);
var
  i: Integer;
begin
  with Item[AIndex]^ do
    for i := 0 to Min(High(AXList), High(XList)) do
      XList[i] := AXList[i];
  // wp: Update x extent here ?
end;

function TListChartSource.SetXValue(AIndex: Integer; AValue: Double): Integer;
var
  oldX: Double;

  procedure UpdateExtent;
  var
    it: PChartDataItem;
  begin
    if not FExtentIsValid then exit;

    if not IsNan(AValue) then begin
      if AValue <= FExtent.a.X then
        FExtent.a.X := AValue
      else if AValue >= FExtent.b.X then
        FExtent.b.X := AValue;
    end;

    if IsNan(oldX) then exit;
    if oldX = FExtent.b.X then begin
      FExtent.b.X := NegInfinity;
      for it in Self do
        if not IsNan(it^.X) then
          FExtent.b.X := Max(FExtent.b.X, it^.X);
    end;
    if oldX = FExtent.a.X then begin
      FExtent.a.X := SafeInfinity;
      for it in Self do
        if not IsNan(it^.X) then
          FExtent.a.X := Min(FExtent.a.X, it^.X);
    end;
  end;

begin
  oldX := Item[AIndex]^.X;
  Result := AIndex;
  if IsEquivalent(oldX, AValue) then exit;
  Item[AIndex]^.X := AValue;
  UpdateExtent;
  if Sorted then begin
    if IsNan(AValue) then
      raise EChartError.Create('X = NaN in a sorted source');
    if AValue > oldX then
      while (Result < Count - 1) and (Item[Result + 1]^.X < AValue) do
        Inc(Result)
    else
      while (Result > 0) and (Item[Result - 1]^.X > AValue) do
        Dec(Result);
    if Result <> AIndex then
      FData.Move(AIndex, Result);
  end;
  Notify;
end;

procedure TListChartSource.SetYCount(AValue: Cardinal);
var
  i: Integer;
begin
  if AValue = FYCount then exit;
  FYCount := AValue;
  for i := 0 to Count - 1 do
    SetLength(Item[i]^.YList, Max(FYCount - 1, 0));
end;

procedure TListChartSource.SetYList(
  AIndex: Integer; const AYList: array of Double);
var
  i: Integer;
begin
  with Item[AIndex]^ do
    for i := 0 to Min(High(AYList), High(YList)) do
      YList[i] := AYList[i];
end;

procedure TListChartSource.SetYValue(AIndex: Integer; AValue: Double);
var
  oldY: Double;

  procedure UpdateExtent;
  var
    it: PChartDataItem;
  begin
    if not FExtentIsValid then exit;

    if not IsNan(AValue) then begin
      if AValue <= FExtent.a.Y then
        FExtent.a.Y := AValue
      else if AValue >= FExtent.b.Y then
        FExtent.b.Y := AValue;
    end;

    if IsNan(oldY) then exit;
    if oldY = FExtent.b.Y then begin
      FExtent.b.Y := NegInfinity;
      for it in Self do
        if not IsNan(it^.Y) then
          FExtent.b.Y := Max(FExtent.b.Y, it^.Y);
    end;
    if oldY = FExtent.a.Y then begin
      FExtent.a.Y := SafeInfinity;
      for it in Self do
        if not IsNan(it^.Y) then
          FExtent.a.Y := Min(FExtent.a.Y, it^.Y);
    end;
  end;

begin
  oldY := Item[AIndex]^.Y;
  if IsEquivalent(oldY, AValue) then exit;
  Item[AIndex]^.Y := AValue;
  if FValuesTotalIsValid then
    FValuesTotal += NumberOr(AValue) - NumberOr(oldY);
  UpdateExtent;
  Notify;
end;

function CompareDataItemX(AItem1, AItem2: Pointer): Integer;
var
  i: Integer;
  item1, item2: PChartDataItem;
begin
  item1 := PChartDataItem(AItem1);
  item2 := PChartDataItem(AItem2);
  Result := Sign(item1^.X - item2^.X);          // wp: why "sign" ???

//  Result := Sign(PChartDataItem(AItem1)^.X - PChartDataItem(AItem2)^.X);

  if Result = 0 then
    for i := 0 to Min(High(item1^.XList), High(item2^.XList)) do begin
      Result := Sign(item1^.XList[i] - item2^.XList[i]);
      if Result <> 0 then
        exit;
    end;
end;

procedure TListChartSource.Sort;
begin
  FData.Sort(@CompareDataItemX);
end;

procedure TListChartSource.UpdateCachesAfterAdd(AX, AY: Double);
begin
  if FExtentIsValid then begin
    UpdateMinMax(AX, FExtent.a.X, FExtent.b.X);
    UpdateMinMax(AY, FExtent.a.Y, FExtent.b.Y);
  end;
  if FValuesTotalIsValid then
    FValuesTotal += NumberOr(AY);
  Notify;
end;

{ TMWCRandomGenerator }

function TMWCRandomGenerator.Get: LongWord;
const
  MULT: array [0..4] of UInt64 = (5115, 1776, 1492, 2111111111, 1);
var
  i: Integer;
  s: UInt64;
begin
  s := 0;
  for i := 0 to High(FHistory) do
    s += MULT[i] * FHistory[i];
  FHistory[3] := FHistory[2];
  FHistory[2] := FHistory[1];
  FHistory[1] := FHistory[0];
  FHistory[4] := Hi(s);
  FHistory[0] := Lo(s);
  Result := FHistory[0];
end;

function TMWCRandomGenerator.GetInRange(AMin, AMax: Integer): Integer;
var
  m: UInt64;
begin
  m := AMax - AMin + 1;
  m *= Get;
  // m is now equidistributed on [0, (2^32-1) * range],
  // so its upper double word is equidistributed on [0, range].
  Result := Integer(Hi(m)) + AMin;
end;

procedure TMWCRandomGenerator.SetSeed(AValue: Integer);
var
  i: Integer;
begin
  FHistory[0] := AValue;
  // Use trivial LCG for seeding
  for i := 1 to High(FHistory) do
    FHistory[i] := Lo(Int64(FHistory[i - 1]) * 29943829 - 1);
  // Skip some initial values to increase randomness.
  for i := 1 to 20 do
    Get;
end;

{ TRandomChartSource }

constructor TRandomChartSource.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FCurItem.Color := clTAColor;
  FRNG := TMWCRandomGenerator.Create;
  FYCount := 1;
  RandSeed := Trunc(Frac(Now) * MaxInt);
end;

destructor TRandomChartSource.Destroy;
begin
  FreeAndNil(FRNG);
  inherited;
end;

procedure TRandomChartSource.ChangeErrorBars(Sender: TObject);
begin
  Unused(Sender);
  Reset;
end;

function TRandomChartSource.GetCount: Integer;
begin
  Result := FPointsNumber;
end;

function TRandomChartSource.GetItem(AIndex: Integer): PChartDataItem;

  function GetRandomX: Double;
  begin
    Result := FRNG.Get / High(LongWord) * (XMax - XMin) + XMin;
  end;

  function GetRandomY: Double;
  begin
    if (YNanPercent > 0) and (FRNG.GetInRange(0, 100) <= YNanPercent) then
      Result := SafeNan
    else if YMax <= YMin then
      Result := YMin
    else
      Result := FRNG.Get / High(LongWord) * (YMax - YMin) + YMin;
  end;

var
  i: Integer;
  fp, fn: Double;
begin
  if FCurIndex > AIndex then begin
    FRNG.Seed := FRandSeed;
    FCurIndex := -1;
  end;
  while FCurIndex < AIndex do begin
    FCurIndex += 1;
    if XCount > 0 then begin
      SetLength(FCurItem.XList, Max(XCount - 1, 0));
      if (XMax <= XMin) or (Count = 1) then begin
        FCurItem.X := XMin;
        for i := 0 to XCount - 2 do FCurItem.XList[i] := XMin;
      end else begin
        if FRandomX then begin
          FCurItem.X := GetRandomX;
          for i := 0 to XCount - 2 do
            FCurItem.XList[i] := GetRandomX;
        end else begin
          FCurItem.X := FCurIndex / (Count - 1) * (XMax - XMin) + XMin;
          for i := 0 to XCount - 2 do
            FCurItem.XList[i] := FCurItem.X;
        end;
      end;
      // Make sure that x values belonging to an error bar are random and
      // multiplied by the percentage given by ErrorBarData.Pos/NegDelta.
      fp := XErrorBarData.ValuePlus * PERCENT;
      if XErrorBarData.ValueMinus = -1 then fn := fp else fn := XErrorBarData.ValueMinus * PERCENT;
      for i := 0 to XCount - 2 do
        if (XErrorBarData.Kind = ebkChartSource) then begin
          if (i+1 = XErrorBarData.IndexPlus) then FCurItem.XList[i] := GetRandomX * fp;
          if (i+1 = XErrorBarData.IndexMinus) then FCurItem.XList[i] := GetRandomX * fn;
        end;
    end;
    if YCount > 0 then begin
      FCurItem.Y := GetRandomY;
      SetLength(FCurItem.YList, Max(YCount - 1, 0));
      for i := 0 to YCount - 2 do begin
        FCurItem.YList[i] := GetRandomY;
        // If this y value is that of an error bar assume that the error is
        // a percentage of the y value calculated. The percentage is the
        // ErrorBarData.Pos/NegDelta.
        fp := YErrorBarData.ValuePlus * PERCENT;
        if YErrorBarData.ValueMinus = -1 then fn := fp else fn := YErrorBarData.ValueMinus * PERCENT;
        if (YErrorBarData.Kind = ebkChartSource) then begin
          if (i+1 = YErrorBarData.IndexPlus) then FCurItem.YList[i] := GetRandomY * fp;
          if (i+1 = YErrorBarData.IndexMinus) then FCurItem.YList[i] := GetRandomY * fn;
        end;
      end;
    end;
  end;
  Result := @FCurItem;
end;

function TRandomChartSource.IsSorted: Boolean;
begin
  Result := not RandomX;
end;

procedure TRandomChartSource.Reset;
begin
  FCurIndex := -1;
  InvalidateCaches;
  Notify;
end;

procedure TRandomChartSource.SetPointsNumber(AValue: Integer);
begin
  if FPointsNumber = AValue then exit;
  FPointsNumber := AValue;
  Reset;
end;

procedure TRandomChartSource.SetRandomX(AValue: Boolean);
begin
  if FRandomX = AValue then exit;
  FRandomX := AValue;
  Reset;
end;

procedure TRandomChartSource.SetRandSeed(AValue: Integer);
begin
  if FRandSeed = AValue then exit;
  FRandSeed := AValue;
  FRNG.Seed := AValue;
  Reset;
end;

procedure TRandomChartSource.SetXCount(AValue: Cardinal);
begin
  if XCount = AValue then exit;
  FXCount := AValue;
  Reset;
end;

procedure TRandomChartSource.SetXMax(AValue: Double);
begin
  if FXMax = AValue then exit;
  FXMax := AValue;
  Reset;
end;

procedure TRandomChartSource.SetXMin(AValue: Double);
begin
  if FXMin = AValue then exit;
  FXMin := AValue;
  Reset;
end;

procedure TRandomChartSource.SetYCount(AValue: Cardinal);
begin
  if YCount = AValue then exit;
  FYCount := AValue;
  Reset;
end;

procedure TRandomChartSource.SetYMax(AValue: Double);
begin
  if FYMax = AValue then exit;
  FYMax := AValue;
  InvalidateCaches;
  Notify;
end;

procedure TRandomChartSource.SetYMin(AValue: Double);
begin
  if FYMin = AValue then exit;
  FYMin := AValue;
  Reset;
end;

procedure TRandomChartSource.SetYNanPercent(AValue: TPercent);
begin
  if FYNanPercent = AValue then exit;
  FYNanPercent := AValue;
  Reset;
end;

{ TUserDefinedChartSource }

procedure TUserDefinedChartSource.EndUpdate;
begin
  // There is no way to detect if the extent changed --
  // so call Reset to be a bit safer, but a bit slower.
  Reset;
  inherited EndUpdate;
end;

function TUserDefinedChartSource.GetCount: Integer;
begin
  Result := FPointsNumber;
end;

function TUserDefinedChartSource.GetItem(AIndex: Integer): PChartDataItem;
begin
  SetDataItemDefaults(FItem);
  if Assigned(FOnGetChartDataItem) then
    FOnGetChartDataItem(Self, AIndex, FItem);
  Result := @FItem;
end;

function TUserDefinedChartSource.IsSorted: Boolean;
begin
  Result := Sorted;
end;

procedure TUserDefinedChartSource.Reset;
begin
  InvalidateCaches;
  Notify;
end;

procedure TUserDefinedChartSource.SetOnGetChartDataItem(
  AValue: TGetChartDataItemEvent);
begin
  if TMethod(FOnGetChartDataItem) = TMethod(AValue) then exit;
  FOnGetChartDataItem := AValue;
  Reset;
end;

procedure TUserDefinedChartSource.SetPointsNumber(AValue: Integer);
begin
  if FPointsNumber = AValue then exit;
  FPointsNumber := AValue;
  Reset;
end;

procedure TUserDefinedChartSource.SetXCount(AValue: Cardinal);
begin
  if FXCount = AValue then exit;
  FXCount := AValue;
  SetLength(FItem.XList, Max(XCount - 1, 0));
  Reset;
end;

procedure TUserDefinedChartSource.SetYCount(AValue: Cardinal);
begin
  if FYCount = AValue then exit;
  FYCount := AValue;
  SetLength(FItem.YList, Max(YCount - 1, 0));
  Reset;
end;

{ TCalculatedChartSource }

procedure TCalculatedChartSource.CalcAccumulation(AIndex: Integer);
var
  lastItemIndex: Integer = -1;

  function GetOriginItem(AItemIndex: Integer): PChartDataItem;
  begin
    Result := @FItem;
    if lastItemIndex = AItemIndex then exit;
    ExtractItem(AItemIndex);
    lastItemIndex := AItemIndex;
  end;

var
  i, oldLeft, oldRight, newLeft, newRight: Integer;
begin
  if AccumulationDirection = cadCenter then
    FHistory.Capacity := EffectiveAccumulationRange * 2
  else
    FHistory.Capacity := EffectiveAccumulationRange;
  RangeAround(FIndex, oldLeft, oldRight);
  RangeAround(AIndex, newLeft, newRight);
  if
    (FIndex < 0) or (Abs(oldLeft - newLeft) > 1) or
    (Abs(oldRight - newRight) > 1)
  then begin
    FHistory.Clear;
    for i := newLeft to newRight do
      FHistory.AddLast(GetOriginItem(i)^);
  end
  else begin
    if FHistory.Capacity = 0 then
      for i := oldLeft to newLeft - 1 do
        FHistory.RemoveValue(GetOriginItem(i)^)
    else
      for i := oldLeft to newLeft - 1 do
        FHistory.RemoveFirst;
    if FHistory.Capacity = 0 then
      for i := oldRight downto newRight + 1 do
        FHistory.RemoveValue(GetOriginItem(i)^)
    else
      for i := oldRight downto newRight + 1 do
        FHistory.RemoveLast;
    for i := oldLeft - 1 downto newLeft do
      FHistory.AddFirst(GetOriginItem(i)^);
    for i := oldRight + 1 to newRight do
      FHistory.AddLast(GetOriginItem(i)^);
  end;
  GetOriginItem(AIndex);
  case AccumulationMethod of
    camSum:
      FHistory.GetSum(FItem);
    camAverage: begin
      FHistory.GetSum(FItem);
      FItem.MultiplyY(1 / (newRight - newLeft + 1));
    end;
    camDerivative, camSmoothDerivative:
      CalcDerivative(AIndex);
  end;
  FIndex := AIndex;
end;

procedure TCalculatedChartSource.CalcDerivative(AIndex: Integer);

  procedure WeightedSum(const ACoeffs: array of Double; ADir, ACount: Integer);
  var
    i, j: Integer;
    prevItem: PChartDataItem;
  begin
    for j := 0 to ACount - 1 do begin
      prevItem := FHistory.GetPtr(AIndex + ADir * j);
      FItem.Y += prevItem^.Y * ADir * ACoeffs[j];
      for i := 0 to High(FItem.YList) do
        FItem.YList[i] += prevItem^.YList[i] * ADir * ACoeffs[j];
    end;
  end;

// Derivative is approximated by finite differences
// with accuracy order of (AccumulationRange - 1).
// Smoothed derivative coefficients are based on work
// by Pavel Holoborodko (http://www.holoborodko.com/pavel/).
const
  COEFFS_BF: array [Boolean, 2..7, 0..6] of Double = (
    ( (     -1, 1,     0,    0,     0,   0,    0),
      (   -3/2, 2,  -1/2,    0,     0,   0,    0),
      (  -11/6, 3,  -3/2,  1/3,     0,   0,    0),
      ( -25/12, 4,    -3,  4/3,  -1/4,   0,    0),
      (-137/60, 5,    -5, 10/3,  -5/4, 1/5,    0),
      ( -49/20, 6, -15/2, 20/3, -15/4, 6/5, -1/6)
    ),
    ( (   -1,     1,     0,   0,    0,    0,    0),
      ( -1/2,     0,   1/2,   0,    0,    0,    0),
      ( -1/4,  -1/4,   1/4, 1/4,    0,    0,    0),
      ( -1/8,  -1/4,     0, 1/4,  1/8,    0,    0),
      (-1/16, -3/16,  -1/8, 1/8, 3/16, 1/16,    0),
      (-1/32,  -1/8, -5/32,   0, 5/32,  1/8, 1/32)
    ));
  COEFFS_C: array [Boolean, 2..5, 0..4] of Double = (
    ( (0,  1/2,     0,     0,      0),
      (0,  2/3, -1/12,     0,      0),
      (0,  3/4, -3/20,  1/60,      0),
      (0,  4/5,  -1/5, 4/105, -1/280)
    ),
    ( (0,  1/2,    0,    0,     0),
      (0,  1/4,  1/8,    0,     0),
      (0, 5/32,  1/8, 1/32,     0),
      (0, 7/64, 7/64, 3/64, 1/128)
    ));
var
  ar, iLeft, iRight, dir: Integer;
  isSmooth: Boolean;
  dx: Double;
begin
  RangeAround(AIndex, iLeft, iRight);
  case CASE_OF_TWO[iLeft = AIndex, iRight = AIndex] of
    cotNone: begin
      dx := Max(
        FItem.X - FHistory.GetPtr(AIndex - iLeft - 1)^.X,
        FHistory.GetPtr(AIndex - iLeft + 1)^.X - FItem.X);
      ar := Min(Min(AIndex - iLeft, iRight - AIndex) + 1, High(COEFFS_C[false]));
      dir := 0;
    end;
    cotFirst: begin
      dx := FHistory.GetPtr(1)^.X - FItem.X;
      ar := Min(iRight - AIndex + 1, High(COEFFS_BF[false]));
      dir := 1;
    end;
    cotSecond: begin
      dx := FItem.X - FHistory.GetPtr(AIndex - iLeft - 1)^.X;
      ar := Min(AIndex - iLeft + 1, High(COEFFS_BF[false]));
      dir := -1;
    end;
    cotBoth: begin
      FItem.SetY(SafeNan);
      exit;
    end
  end;
  if dx = 0 then begin
    FItem.SetY(SafeNan);
    exit;
  end;
  FItem.SetY(0.0);
  AIndex -= iLeft;
  isSmooth := AccumulationMethod = camSmoothDerivative;
  if dir = 0 then begin
    WeightedSum(COEFFS_C[isSmooth][ar], -1, ar);
    WeightedSum(COEFFS_C[isSmooth][ar], +1, ar);
  end
  else
    WeightedSum(COEFFS_BF[isSmooth][ar], dir, ar);
  FItem.MultiplyY(1 / dx);
end;

procedure TCalculatedChartSource.CalcPercentage;
var
  s: Double;
begin
  if not Percentage then exit;
  s := (FItem.Y + Sum(FItem.YList)) * PERCENT;
  if s = 0 then exit;
  FItem.MultiplyY(1 / s);
end;

procedure TCalculatedChartSource.Changed(ASender: TObject);
begin
  if
    (FOrigin <> nil) and (ASender = FOrigin) and
    (FOrigin.YCount <> FOriginYCount)
  then begin
    UpdateYOrder;
    exit;
  end;
  FIndex := -1;
  InvalidateCaches;
  Notify;
end;

constructor TCalculatedChartSource.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FAccumulationRange := 2;
  FIndex := -1;
  FHistory := TChartSourceBuffer.Create;
  FListener := TListener.Create(@FOrigin, @Changed);
end;

destructor TCalculatedChartSource.Destroy;
begin
  FreeAndNil(FHistory);
  FreeAndNil(FListener);
  inherited;
end;

function TCalculatedChartSource.EffectiveAccumulationRange: Cardinal;
const
  MAX_DERIVATIVE_RANGE = 10;
begin
  if IsDerivative and (AccumulationRange = 0) then
    Result := MAX_DERIVATIVE_RANGE
  else
    Result := AccumulationRange;
end;

procedure TCalculatedChartSource.ExtractItem(AIndex: Integer);

  function YByOrder(AOrderIndex: Integer): Double;
  begin
    if AOrderIndex = 0 then
      Result := FItem.Y
    else
      Result := FItem.YList[AOrderIndex - 1];
  end;

var
  t: TDoubleDynArray;
  i: Integer;
begin
  FItem := Origin[AIndex]^;
  SetLength(t, High(FYOrder));
  for i := 1 to High(FYOrder) do
    t[i - 1] := YByOrder(FYOrder[i]);
  FItem.Y := YByOrder(FYOrder[0]);
  FItem.YList := t;
end;

function TCalculatedChartSource.GetCount: Integer;
begin
  if Origin <> nil then
    Result := Origin.Count
  else
    Result := 0;
end;

function TCalculatedChartSource.GetItem(AIndex: Integer): PChartDataItem;
begin
  if Origin = nil then exit(nil);
  Result := @FItem;
  if FIndex = AIndex then exit;
  if (AccumulationMethod = camNone) or (AccumulationRange = 1) then
    ExtractItem(AIndex)
  else
    CalcAccumulation(AIndex);
  CalcPercentage;
end;

function TCalculatedChartSource.IsDerivative: Boolean;
begin
  Result := AccumulationMethod in [camDerivative, camSmoothDerivative];
end;

function TCalculatedChartSource.IsSorted: Boolean;
begin
  if Origin <> nil then
    Result := Origin.IsSorted
  else
    Result := false;
end;

procedure TCalculatedChartSource.RangeAround(
  AIndex: Integer; out ALeft, ARight: Integer);
var
  ar: Integer;
begin
  ar := EffectiveAccumulationRange;
  ar := IfThen(ar = 0, MaxInt div 2, ar - 1);
  ALeft := AIndex - IfThen(AccumulationDirection = cadForward, 0, ar);
  ARight := AIndex + IfThen(AccumulationDirection = cadBackward, 0, ar);
  ALeft := EnsureRange(ALeft, 0, Count - 1);
  ARight := EnsureRange(ARight, 0, Count - 1);
end;

procedure TCalculatedChartSource.SetAccumulationDirection(
  AValue: TChartAccumulationDirection);
begin
  if FAccumulationDirection = AValue then exit;
  FAccumulationDirection := AValue;
  Changed(nil);
end;

procedure TCalculatedChartSource.SetAccumulationMethod(
  AValue: TChartAccumulationMethod);
begin
  if FAccumulationMethod = AValue then exit;
  FAccumulationMethod := AValue;
  Changed(nil);
end;

procedure TCalculatedChartSource.SetAccumulationRange(AValue: Cardinal);
begin
  if FAccumulationRange = AValue then exit;
  FAccumulationRange := AValue;
  Changed(nil);
end;

procedure TCalculatedChartSource.SetOrigin(AValue: TCustomChartSource);
begin
  if AValue = Self then
      AValue := nil;
  if FOrigin = AValue then exit;
  if FOrigin <> nil then
    FOrigin.Broadcaster.Unsubscribe(FListener);
  FOrigin := AValue;
  if FOrigin <> nil then
    FOrigin.Broadcaster.Subscribe(FListener);
  UpdateYOrder;
end;

procedure TCalculatedChartSource.SetPercentage(AValue: Boolean);
begin
  if FPercentage = AValue then exit;
  FPercentage := AValue;
  Changed(nil);
end;

procedure TCalculatedChartSource.SetReorderYList(const AValue: String);
begin
  if FReorderYList = AValue then exit;
  FReorderYList := AValue;
  UpdateYOrder;
end;

procedure TCalculatedChartSource.SetXCount(AValue: Cardinal);
begin
  Unused(AValue);
  raise EXCountError.Create('Cannot set XCount');
end;

procedure TCalculatedChartSource.SetYCount(AValue: Cardinal);
begin
  Unused(AValue);
  raise EYCountError.Create('Cannot set YCount');
end;

procedure TCalculatedChartSource.UpdateYOrder;
var
  order: TStringList;
  i: Integer;
begin
  if FOrigin = nil then begin
    FOriginYCount := 0;
    FYCount := 0;
    FYOrder := nil;
    FItem.YList := nil;
    Changed(nil);
    exit;
  end;

  FOriginYCount := FOrigin.YCount;
  if ReorderYList = '' then begin
    SetLength(FYOrder,  FOriginYCount);
    for i := 0 to High(FYOrder) do
      FYOrder[i] := i;
  end
  else begin
    order := TStringList.Create;
    try
      order.CommaText := ReorderYList;
      SetLength(FYOrder, order.Count);
      for i := 0 to High(FYOrder) do
        FYOrder[i] := EnsureRange(StrToIntDef(order[i], 0), 0, FOriginYCount - 1);
    finally
      order.Free;
    end;
  end;
  FYCount := Length(FYOrder);

  SetLength(FItem.YList, Max(High(FYOrder), 0));
  Changed(nil);
end;

end.