-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcagenetic.pas
1568 lines (1378 loc) · 42.5 KB
/
cagenetic.pas
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
unit caGenetic;
{$INCLUDE ca.inc}
{$DEFINE USE_POINTER_ARRAY}
interface
uses
// Standard Delphi units
Windows,
Classes,
SysUtils,
Math,
// ca units
caClasses,
caUtils,
caVector,
caLog,
caTypes,
caRandom;
const
cOneHundred = 100;
type
TcaPercentage = 0..cOneHundred;
TcaFitnessResolution = (frOneDecPlace, frTwoDecPlaces, frThreeDecPlaces, frFourDecPlaces);
PnnGeneArray = ^TcaGeneArray;
TcaGeneArray = array[0..0] of Double;
TcaOrganism = class;
TcaAddChildOrganismEvent = procedure(Sender: TObject; AChildOrganism: TcaOrganism; var AAccept: Boolean) of object;
TcaApplyConstraintsEvent = procedure(Sender: TObject; AOrganism: TcaOrganism) of object;
TcaEvaluateOrganismEvent = procedure(Sender: TObject; AOrganism: TcaOrganism; var AFitness: Double) of object;
//---------------------------------------------------------------------------
// TcaChromozome
//---------------------------------------------------------------------------
TcaChromozome = class(TObject)
private
{$IFDEF USE_POINTER_ARRAY}
FGenes: PnnGeneArray;
{$ELSE}
FGenes: TcaDoubleVector;
{$ENDIF}
FSize: Integer;
// Property methods
function GetGene(Index: Integer): Double;
function GetSize: Integer;
procedure SetGene(Index: Integer; const Value: Double);
procedure SetSize(const Value: Integer);
// Private methods
{$IFDEF USE_POINTER_ARRAY}
procedure FreeGenesArray;
{$ENDIF}
procedure ResizeGenesArray;
public
constructor Create;
destructor Destroy; override;
// Properties
property Genes[Index: Integer]: Double read GetGene write SetGene;
property Size: Integer read GetSize write SetSize;
end;
//---------------------------------------------------------------------------
// TcaOrganism
//---------------------------------------------------------------------------
TcaPopulation = class;
TcaOrganismGroup = class;
TcaOrganism = class(TObject)
private
// Private fields
FChromozome: TcaChromozome;
FDateOfBirth: Integer;
FOrganismGroup: TcaOrganismGroup;
FPopulation: TcaPopulation;
FParent1: TcaOrganism;
FParent2: TcaOrganism;
// Property fields
FEvalParam: Double;
FEvalResult: Double;
FFitness: Double;
// Property methods
function GetAsString: String;
function GetAverageGene: Double;
function GetChromozomeSize: Integer;
function GetEvalParam: Double;
function GetEvalResult: Double;
function GetFitness: Double;
function GetGene(Index: Integer): Double;
function GetOrganismGroup: TcaOrganismGroup;
procedure SetEvalParam(const Value: Double);
procedure SetEvalResult(const Value: Double);
procedure SetFitness(const Value: Double);
procedure SetGene(Index: Integer; const Value: Double);
procedure SetOrganismGroup(const Value: TcaOrganismGroup);
// Private methods
function HasParents: Boolean;
function IsClone: Boolean;
procedure CopyChromozomeFromOriginal;
procedure CopyStateFromOriginal;
procedure CreateChromozomeFromParents;
procedure CreateRandomChromozome;
public
// Public virtual methods
constructor Create(APopulation: TcaPopulation; AParent1: TcaOrganism = nil; AParent2: TcaOrganism = nil);
destructor Destroy; override;
// Public methods
function Clone: TcaOrganism;
procedure Initialize;
procedure Mutate;
procedure ProduceChildren(APartner: TcaOrganism);
// Properties
property AsString: String read GetAsString;
property AverageGene: Double read GetAverageGene;
property ChromozomeSize: Integer read GetChromozomeSize;
property EvalParam: Double read GetEvalParam write SetEvalParam;
property EvalResult: Double read GetEvalResult write SetEvalResult;
property Fitness: Double read GetFitness write SetFitness;
property Genes[Index: Integer]: Double read GetGene write SetGene;
property OrganismGroup: TcaOrganismGroup read GetOrganismGroup write SetOrganismGroup;
end;
//---------------------------------------------------------------------------
// TcaOrganismGroup
//---------------------------------------------------------------------------
TcaRankedGroups = class;
TcaOrganismGroup = class(TObject)
private
// Private fields
FList: TList;
// Property fields
FFitness: Integer;
FPopulation: TcaPopulation;
FRankedGroups: TcaRankedGroups;
FSortDirection: TcaSortDirection;
// Property methods
function GetCount: Integer;
function GetFitness: Integer;
function GetItem(Index: Integer): TcaOrganism;
function GetRankedGroups: TcaRankedGroups;
function GetSortDirection: TcaSortDirection;
procedure SetFitness(const Value: Integer);
procedure SetRankedGroups(const Value: TcaRankedGroups);
public
constructor Create(APopulation: TcaPopulation);
destructor Destroy; override;
// Public methods
function FitnessExists(AFitness: Double): Boolean;
function RandomChoice: TcaOrganism;
procedure Add(AOrganism: TcaOrganism);
procedure DeleteOrganism(AIndex: Integer);
procedure Sort(ASortDirection: TcaSortDirection);
// Log methods
procedure SendToLog(const AMsg: String; AClearLog: Boolean = False);
// Properties
property Count: Integer read GetCount;
property Fitness: Integer read GetFitness write SetFitness;
property Items[Index: Integer]: TcaOrganism read GetItem; default;
property RankedGroups: TcaRankedGroups read GetRankedGroups write SetRankedGroups;
property SortDirection: TcaSortDirection read GetSortDirection;
end;
//---------------------------------------------------------------------------
// TcaRankedGroups
//---------------------------------------------------------------------------
TcaRankedGroups = class(TObject)
private
// Private fields
FList: TList;
// Property fields
FPopulation: TcaPopulation;
FSortDirection: TcaSortDirection;
// Property methods
function GetCount: Integer;
function GetItem(Index: Integer): TcaOrganismGroup;
function GetSortDirection: TcaSortDirection;
public
constructor Create(APopulation: TcaPopulation);
destructor Destroy; override;
// Interface methods
function FindGroup(AFitness: Integer): TcaOrganismGroup;
function RandomChoice: TcaOrganismGroup;
procedure AddGroup(AGroup: TcaOrganismGroup);
procedure Clear;
procedure DeleteGroup(AIndex: Integer);
procedure Sort(ASortDirection: TcaSortDirection; ASortOrganisms: Boolean = False);
// Properties
property Count: Integer read GetCount;
property Items[Index: Integer]: TcaOrganismGroup read GetItem; default;
property SortDirection: TcaSortDirection read GetSortDirection;
end;
//---------------------------------------------------------------------------
// TcaPopulation
//---------------------------------------------------------------------------
TcaPopulation = class(TObject)
private
// Private fields
FMathUtils: IcaMathUtils;
FNextIndex: Int64;
FPopulationCount: Integer;
FRandom: IcaRandom;
// Property fields
FAllowDuplicates: Boolean;
FFitnessGroups: TcaRankedGroups;
FTolerance: Double;
// Parameter property fields
FAlienExtent: TcaPercentage;
FAlienRate: TcaPercentage;
FChildCount: Integer;
FChromozomeSize: Integer;
FCrossoverRate: TcaPercentage;
FFitnessResolution: TcaFitnessResolution;
FGeneMaxValue: Double;
FGeneMinValue: Double;
FGenerationCount: Integer;
FMaxGenerations: Integer;
FMaxPopulation: Integer;
FMutationExtent: TcaPercentage;
FMutationRate: TcaPercentage;
FRandSeed: Byte;
FTargetFitness: Integer;
// Event property fields
FOnAddChild: TcaAddChildOrganismEvent;
FOnApplyConstraints: TcaApplyConstraintsEvent;
FOnEvaluate: TcaEvaluateOrganismEvent;
FOnGenerationCompleted: TNotifyEvent;
FOnPopulationInitialized: TNotifyEvent;
// Logging property fields
FLogging: Boolean;
// Private methods
function InsertOrganism(AOrganism: TcaOrganism): Boolean;
procedure AddUnparentedOrganism;
procedure ApplyNaturalSelection;
procedure CreateNewGeneration;
procedure CreateRandomNumberGenerator;
procedure Evolve;
procedure EvolveOneGeneration;
procedure InitializePopulation;
procedure SetDefaultValues;
// Property methods
function GetAllowDuplicates: Boolean;
function GetBestOrganism: TcaOrganism;
function GetFitnessGroups: TcaRankedGroups;
function GetMathUtils: IcaMathUtils;
function GetTolerance: Double;
procedure SetAllowDuplicates(const Value: Boolean);
procedure SetTolerance(const Value: Double);
// Parameter property methods
function GetAlienExtent: TcaPercentage;
function GetAlienRate: TcaPercentage;
function GetChildCount: Integer;
function GetChromozomeSize: Integer;
function GetCrossoverRate: TcaPercentage;
function GetFitnessResolution: TcaFitnessResolution;
function GetGeneMaxValue: Double;
function GetGeneMinValue: Double;
function GetGenerationCount: Integer;
function GetMaxGenerations: Integer;
function GetMaxPopulation: Integer;
function GetMutationExtent: TcaPercentage;
function GetMutationRate: TcaPercentage;
function GetRandom: IcaRandom;
function GetRandSeed: Byte;
function GetTargetFitness: Integer;
procedure SetAlienExtent(const Value: TcaPercentage);
procedure SetAlienRate(const Value: TcaPercentage);
procedure SetChildCount(const Value: Integer);
procedure SetChromozomeSize(const Value: Integer);
procedure SetCrossoverRate(const Value: TcaPercentage);
procedure SetFitnessResolution(const Value: TcaFitnessResolution);
procedure SetGeneMaxValue(const Value: Double);
procedure SetGeneMinValue(const Value: Double);
procedure SetMaxGenerations(const Value: Integer);
procedure SetMaxPopulation(const Value: Integer);
procedure SetMutationExtent(const Value: TcaPercentage);
procedure SetMutationRate(const Value: TcaPercentage);
procedure SetRandSeed(const Value: Byte);
procedure SetTargetFitness(const Value: Integer);
// Event property methods
function GetOnAddChild: TcaAddChildOrganismEvent;
function GetOnApplyConstraints: TcaApplyConstraintsEvent;
function GetOnEvaluate: TcaEvaluateOrganismEvent;
function GetOnGenerationCompleted: TNotifyEvent;
function GetOnPopulationInitialized: TNotifyEvent;
procedure SetOnAddChild(const Value: TcaAddChildOrganismEvent);
procedure SetOnApplyConstraints(const Value: TcaApplyConstraintsEvent);
procedure SetOnEvaluate(const Value: TcaEvaluateOrganismEvent);
procedure SetOnGenerationCompleted(const Value: TNotifyEvent);
procedure SetOnPopulationInitialized(const Value: TNotifyEvent);
// Log property methods
function GetLogging: Boolean;
procedure SetLogging(const Value: Boolean);
protected
// Protected static methods
function Evaluate(AOrganism: TcaOrganism): Double;
procedure AddChild(AChildOrganism: TcaOrganism);
// Protected virtual methods
procedure DoAddChild(AChildOrganism: TcaOrganism; var AAccept: Boolean); virtual;
procedure DoApplyConstraints(AOrganism: TcaOrganism); virtual;
procedure DoEvaluate(AOrganism: TcaOrganism; var AFitness: Double); virtual;
procedure DoGenerationCompleted; virtual;
procedure DoPopulationInitialized; virtual;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
// Interface methods
function NextIndex: Integer;
procedure RebuildFitnessGroups;
procedure Run;
// Log methods
procedure LogWithGenerationCount;
procedure SendToLog(const AMsg: String; AClearLog: Boolean = False);
// Properties
property FitnessGroups: TcaRankedGroups read GetFitnessGroups;
property MathUtils: IcaMathUtils read GetMathUtils;
property Tolerance: Double read GetTolerance write SetTolerance;
// Parameter properties
property AlienExtent: TcaPercentage read GetAlienExtent write SetAlienExtent;
property AlienRate: TcaPercentage read GetAlienRate write SetAlienRate;
property AllowDuplicates: Boolean read GetAllowDuplicates write SetAllowDuplicates;
property BestOrganism: TcaOrganism read GetBestOrganism;
property ChildCount: Integer read GetChildCount write SetChildCount;
property ChromozomeSize: Integer read GetChromozomeSize write SetChromozomeSize;
property CrossoverRate: TcaPercentage read GetCrossoverRate write SetCrossoverRate;
property FitnessResolution: TcaFitnessResolution read GetFitnessResolution write SetFitnessResolution;
property GeneMaxValue: Double read GetGeneMaxValue write SetGeneMaxValue;
property GeneMinValue: Double read GetGeneMinValue write SetGeneMinValue;
property GenerationCount: Integer read GetGenerationCount;
property MaxGenerations: Integer read GetMaxGenerations write SetMaxGenerations;
property MaxPopulation: Integer read GetMaxPopulation write SetMaxPopulation;
property MutationExtent: TcaPercentage read GetMutationExtent write SetMutationExtent;
property MutationRate: TcaPercentage read GetMutationRate write SetMutationRate;
property Random: IcaRandom read GetRandom;
property RandSeed: Byte read GetRandSeed write SetRandSeed;
property TargetFitness: Integer read GetTargetFitness write SetTargetFitness;
// Logging options
property Logging: Boolean read GetLogging write SetLogging;
// Event properties
property OnAddChild: TcaAddChildOrganismEvent read GetOnAddChild write SetOnAddChild;
property OnApplyConstraints: TcaApplyConstraintsEvent read GetOnApplyConstraints write SetOnApplyConstraints;
property OnEvaluate: TcaEvaluateOrganismEvent read GetOnEvaluate write SetOnEvaluate;
property OnGenerationCompleted: TNotifyEvent read GetOnGenerationCompleted write SetOnGenerationCompleted;
property OnPopulationInitialized: TNotifyEvent read GetOnPopulationInitialized write SetOnPopulationInitialized;
end;
implementation
//---------------------------------------------------------------------------
// TcaChromozome
//---------------------------------------------------------------------------
constructor TcaChromozome.Create;
begin
inherited;
{$IFDEF USE_POINTER_ARRAY}
{$ELSE}
FGenes := TcaDoubleVector.Create;
{$ENDIF}
end;
destructor TcaChromozome.Destroy;
begin
{$IFDEF USE_POINTER_ARRAY}
FreeGenesArray;
{$ELSE}
FGenes.Free;
{$ENDIF}
inherited;
end;
// Private methods
{$IFDEF USE_POINTER_ARRAY}
procedure TcaChromozome.FreeGenesArray;
begin
if FGenes <> nil then FreeMem(FGenes);
end;
{$ENDIF}
procedure TcaChromozome.ResizeGenesArray;
begin
{$IFDEF USE_POINTER_ARRAY}
FreeGenesArray;
GetMem(FGenes, FSize * SizeOf(TcaGeneArray));
{$ELSE}
FGenes.Clear;
FGenes.GrowBy(FSize);
{$ENDIF}
end;
// Property methods
function TcaChromozome.GetGene(Index: Integer): Double;
begin
{$IFDEF USE_POINTER_ARRAY}
Result := FGenes^[Index];
{$ELSE}
Assert(Index < FGenes.Count);
Result := FGenes[Index];
{$ENDIF}
end;
function TcaChromozome.GetSize: Integer;
begin
Result := FSize;
end;
procedure TcaChromozome.SetGene(Index: Integer; const Value: Double);
begin
{$IFDEF USE_POINTER_ARRAY}
FGenes^[Index] := Value;
{$ELSE}
Assert(Index < FGenes.Count);
FGenes[Index] := Value;
{$ENDIF}
end;
procedure TcaChromozome.SetSize(const Value: Integer);
begin
if Value <> FSize then
begin
FSize := Value;
ResizeGenesArray;
end;
end;
//---------------------------------------------------------------------------
// TcaOrganism
//---------------------------------------------------------------------------
constructor TcaOrganism.Create(APopulation: TcaPopulation; AParent1: TcaOrganism = nil; AParent2: TcaOrganism = nil);
begin
inherited Create;
FChromozome := TcaChromozome.Create;
FPopulation := APopulation;
FParent1 := AParent1;
FParent2 := AParent2;
end;
destructor TcaOrganism.Destroy;
begin
FChromozome.Free;
inherited;
end;
// Public methods
function TcaOrganism.Clone: TcaOrganism;
begin
Result := TcaOrganism.Create(FPopulation, Self, Self);
Result.Initialize;
end;
procedure TcaOrganism.Initialize;
begin
FDateOfBirth := FPopulation.GenerationCount;
FChromozome.Size := FPopulation.ChromozomeSize;
if HasParents then
CreateChromozomeFromParents
else
begin
if IsClone then
begin
CopyChromozomeFromOriginal;
CopyStateFromOriginal;
end
else
CreateRandomChromozome;
end;
end;
procedure TcaOrganism.Mutate;
var
GeneIndex: Integer;
Index: Integer;
MutationCount: Integer;
Random: IcaRandom;
begin
Random := FPopulation.Random;
Random.LowerIntBound := 0;
Random.UpperIntBound := cOneHundred;
if FPopulation.MutationRate > Random.AsInteger then
begin
MutationCount := Round(FPopulation.ChromozomeSize * FPopulation.MutationExtent / cOneHundred);
for Index := 0 to Pred(MutationCount) do
begin
// Find random gene to mutate
Random.LowerIntBound := 0;
Random.UpperIntBound := FPopulation.ChromozomeSize - 1;
GeneIndex := Random.AsInteger;
// Put random value into selected gene
Random.LowerBound := FPopulation.GeneMinValue;
Random.UpperBound := FPopulation.GeneMaxValue;
FChromozome.Genes[GeneIndex] := Random.AsDouble;
end;
end;
end;
procedure TcaOrganism.ProduceChildren(APartner: TcaOrganism);
var
Child: TcaOrganism;
Index: Integer;
begin
for Index := 0 to Pred(FPopulation.ChildCount) do
begin
Child := TcaOrganism.Create(FPopulation, Self, APartner);
Child.Initialize;
Child.Mutate;
FPopulation.AddChild(Child);
end;
end;
// Private methods
function TcaOrganism.HasParents: Boolean;
begin
Result := (FParent1 <> nil) and (FParent2 <> nil) and (FParent1 <> FParent2);
end;
function TcaOrganism.IsClone: Boolean;
begin
Result := (FParent1 <> nil) and (FParent2 <> nil) and (FParent1 = FParent2);
end;
procedure TcaOrganism.CopyChromozomeFromOriginal;
var
GeneIndex: Integer;
begin
for GeneIndex := 0 to Pred(FChromozome.Size) do
SetGene(GeneIndex, FParent1.Genes[GeneIndex]);
end;
procedure TcaOrganism.CopyStateFromOriginal;
begin
FEvalParam := FParent1.EvalParam;
FEvalResult := FParent1.EvalResult;
FFitness := FParent1.Fitness;
end;
procedure TcaOrganism.CreateChromozomeFromParents;
var
Index: Integer;
Random: IcaRandom;
begin
Random := FPopulation.Random;
Random.LowerBound := 0;
Random.UpperBound := 1;
for Index := 0 to Pred(FPopulation.ChromozomeSize) do
begin
if Random.AsDouble < 0.5 then
FChromozome.Genes[Index] := FParent1.Genes[Index]
else
FChromozome.Genes[Index] := FParent2.Genes[Index];
end;
end;
procedure TcaOrganism.CreateRandomChromozome;
var
Index: Integer;
Random: IcaRandom;
begin
Random := FPopulation.Random;
Random.LowerBound := FPopulation.GeneMinValue;
Random.UpperBound := FPopulation.GeneMaxValue;
for Index := 0 to Pred(FPopulation.ChromozomeSize) do
FChromozome.Genes[Index] := Random.AsDouble;
end;
// Property methods
function TcaOrganism.GetAsString: String;
begin
Result := Format('(DOB: %d), (Fitness: %f), (Parent1: %d), (Parent1: %d)',
[FDateOfBirth, FFitness, Integer(FParent1), Integer(FParent2)]);
end;
function TcaOrganism.GetAverageGene: Double;
var
Index: Integer;
begin
Result := 0;
if FChromozome.Size > 0 then
begin
for Index := 0 to Pred(FChromozome.Size) do
Result := Result + FChromozome.Genes[Index];
Result := Result / FChromozome.Size;
end;
end;
function TcaOrganism.GetChromozomeSize: Integer;
begin
Result := FPopulation.ChromozomeSize;
end;
function TcaOrganism.GetEvalParam: Double;
begin
Result := FEvalParam;
end;
function TcaOrganism.GetEvalResult: Double;
begin
Result := FEvalResult;
end;
function TcaOrganism.GetFitness: Double;
begin
Result := FFitness;
end;
function TcaOrganism.GetGene(Index: Integer): Double;
begin
Result := FChromozome.Genes[Index];
end;
function TcaOrganism.GetOrganismGroup: TcaOrganismGroup;
begin
Result := FOrganismGroup;
end;
procedure TcaOrganism.SetEvalParam(const Value: Double);
begin
FEvalParam := Value;
end;
procedure TcaOrganism.SetEvalResult(const Value: Double);
begin
FEvalResult := Value;
end;
procedure TcaOrganism.SetFitness(const Value: Double);
begin
FFitness := Value;
end;
procedure TcaOrganism.SetGene(Index: Integer; const Value: Double);
begin
FChromozome.Genes[Index] := Value;
end;
procedure TcaOrganism.SetOrganismGroup(const Value: TcaOrganismGroup);
begin
FOrganismGroup := Value;
end;
//---------------------------------------------------------------------------
// TcaOrganismGroup
//---------------------------------------------------------------------------
constructor TcaOrganismGroup.Create(APopulation: TcaPopulation);
begin
inherited Create;
FPopulation := APopulation;
FList := TList.Create;
end;
destructor TcaOrganismGroup.Destroy;
var
Index: Integer;
begin
for Index := 0 to Pred(FList.Count) do
TObject(FList[Index]).Free;
FList.Free;
FPopulation := nil;
inherited;
end;
// Public methods
function TcaOrganismGroup.FitnessExists(AFitness: Double): Boolean;
var
Index: Integer;
Organism: TcaOrganism;
begin
// TODO: Use binary search
Result := False;
for Index := 0 to Pred(GetCount) do
begin
Organism := GetItem(Index);
if FPopulation.MathUtils.IsEq(Organism.Fitness, AFitness) then
begin
Result := True;
Break;
end;
end;
end;
function TcaOrganismGroup.RandomChoice: TcaOrganism;
var
Random: IcaRandom;
begin
Random := FPopulation.Random;
Random.LowerIntBound := 0;
Random.UpperIntBound := Pred(FList.Count);
Result := TcaOrganism(FList[Random.AsInteger]);
end;
procedure TcaOrganismGroup.Add(AOrganism: TcaOrganism);
begin
FList.Add(AOrganism);
AOrganism.OrganismGroup := Self;
end;
procedure TcaOrganismGroup.DeleteOrganism(AIndex: Integer);
begin
TObject(FList[AIndex]).Free;
FList.Delete(AIndex);
end;
function TcaOrganismGroup_Sort(Item1, Item2: Pointer): Integer;
var
Diff: Double;
Organism1: TcaOrganism;
Organism2: TcaOrganism;
OrganismGroup: TcaOrganismGroup;
begin
Diff := 0;
Organism1 := TcaOrganism(Item1);
Organism2 := TcaOrganism(Item2);
OrganismGroup := Organism1.OrganismGroup;
case OrganismGroup.SortDirection of
sdAscending: Diff := Organism1.Fitness - Organism2.Fitness;
sdDescending: Diff := Organism2.Fitness - Organism1.Fitness;
end;
if Diff < 0 then Result := -1 else if Diff > 0 then Result := 1 else Result := 0;
end;
procedure TcaOrganismGroup.Sort(ASortDirection: TcaSortDirection);
begin
FSortDirection := ASortDirection;
FList.Sort(TcaOrganismGroup_Sort);
end;
// Log methods
procedure TcaOrganismGroup.SendToLog(const AMsg: String; AClearLog: Boolean = False);
var
Index: Integer;
Organism: TcaOrganism;
begin
if AClearLog then Log.Clear;
if AMsg <> '' then Log.Send(AMsg);
for Index := 0 to Pred(GetCount) do
begin
Organism := GetItem(Index);
Log.Send('Organism', Index);
Log.Send('Fitness', Organism.Fitness);
end;
Log.Send(' ');
end;
// Property methods
function TcaOrganismGroup.GetCount: Integer;
begin
Result := FList.Count;
end;
function TcaOrganismGroup.GetFitness: Integer;
begin
Result := FFitness;
end;
function TcaOrganismGroup.GetItem(Index: Integer): TcaOrganism;
begin
Result := TcaOrganism(FList[Index]);
end;
function TcaOrganismGroup.GetRankedGroups: TcaRankedGroups;
begin
Result := FRankedGroups;
end;
function TcaOrganismGroup.GetSortDirection: TcaSortDirection;
begin
Result := FSortDirection;
end;
procedure TcaOrganismGroup.SetFitness(const Value: Integer);
begin
FFitness := Value;
end;
procedure TcaOrganismGroup.SetRankedGroups(const Value: TcaRankedGroups);
begin
FRankedGroups := Value;
end;
//---------------------------------------------------------------------------
// TcaRankedGroups
//---------------------------------------------------------------------------
constructor TcaRankedGroups.Create(APopulation: TcaPopulation);
begin
inherited Create;
FPopulation := APopulation;
FList := TList.Create;
end;
destructor TcaRankedGroups.Destroy;
var
Index: Integer;
begin
for Index := 0 to Pred(FList.Count) do
TObject(FList[Index]).Free;
FList.Free;
FPopulation := nil;
inherited;
end;
// Interface methods
function TcaRankedGroups.FindGroup(AFitness: Integer): TcaOrganismGroup;
var
ACompare: Integer;
AHigh: Integer;
AIndex: Integer;
ALow: Integer;
Item: TcaOrganismGroup;
begin
Sort(sdAscending);
Result := nil;
ALow := 0;
AHigh := Pred(FList.Count);
while ALow <= AHigh do
begin
AIndex := (ALow + AHigh) shr 1;
Item := TcaOrganismGroup(FList.List^[AIndex]);
ACompare := Item.Fitness - AFitness;
if ACompare < 0 then
ALow := AIndex + 1
else
begin
AHigh := AIndex - 1;
if ACompare = 0 then
begin
Result := Item;
ALow := AIndex;
end;
end;
end;
end;
function TcaRankedGroups.RandomChoice: TcaOrganismGroup;
var
Random: IcaRandom;
begin
Random := FPopulation.Random;
Random.LowerIntBound := 0;
Random.UpperIntBound := Pred(FList.Count);
Result := TcaOrganismGroup(FList[Random.AsInteger]);
end;
procedure TcaRankedGroups.AddGroup(AGroup: TcaOrganismGroup);
begin
AGroup.RankedGroups := Self;
FList.Add(AGroup);
end;
procedure TcaRankedGroups.Clear;
begin
while GetCount > 0 do
DeleteGroup(0);
end;
procedure TcaRankedGroups.DeleteGroup(AIndex: Integer);
begin
TObject(FList[AIndex]).Free;
FList.Delete(AIndex);
end;
function TcaRankedGroups_Sort(Item1, Item2: Pointer): Integer;
var
Group1: TcaOrganismGroup;
Group2: TcaOrganismGroup;
RankedGroups: TcaRankedGroups;
begin
Result := 0;
Group1 := TcaOrganismGroup(Item1);
Group2 := TcaOrganismGroup(Item2);
RankedGroups := Group1.RankedGroups;
case RankedGroups.SortDirection of
sdAscending: Result := Group1.Fitness - Group2.Fitness;
sdDescending: Result := Group2.Fitness - Group1.Fitness;
end;
end;
procedure TcaRankedGroups.Sort(ASortDirection: TcaSortDirection; ASortOrganisms: Boolean = False);
var
Group: TcaOrganismGroup;
GroupIndex: Integer;
begin
FSortDirection := ASortDirection;
FList.Sort(TcaRankedGroups_Sort);
if ASortOrganisms then
begin
for GroupIndex := 0 to Pred(GetCount) do
begin
Group := GetItem(GroupIndex);
Group.Sort(sdAscending);
end;
end;
end;
// Property methods
function TcaRankedGroups.GetCount: Integer;
begin
Result := FList.Count;
end;
function TcaRankedGroups.GetItem(Index: Integer): TcaOrganismGroup;
begin
Result := TcaOrganismGroup(FList[Index]);
end;
function TcaRankedGroups.GetSortDirection: TcaSortDirection;
begin
Result := FSortDirection;
end;
//---------------------------------------------------------------------------
// TcaPopulation
//---------------------------------------------------------------------------
// Public virtual methods
procedure TcaPopulation.AfterConstruction;
begin
inherited;
FLogging := False;
FMathUtils := Utils as IcaMathUtils;
SetDefaultValues;
CreateRandomNumberGenerator;
FFitnessGroups := TcaRankedGroups.Create(Self);
end;
procedure TcaPopulation.BeforeDestruction;
begin
inherited;
FFitnessGroups.Free;
end;
// Public methods
function TcaPopulation.NextIndex: Integer;
begin
Inc(FNextIndex);
Result := FNextIndex;
end;
procedure TcaPopulation.RebuildFitnessGroups;
var
SavedOrganisms: TList;
Group: TcaOrganismGroup;
GroupIndex: Integer;
Organism: TcaOrganism;
OrganismIndex: Integer;
begin
SavedOrganisms := TList.Create;
try
// Clone every organism and save in temp list
for GroupIndex := 0 to Pred(FFitnessGroups.Count) do
begin
Group := FFitnessGroups[GroupIndex];
for OrganismIndex := 0 to Pred(Group.Count) do
begin
Organism := Group[OrganismIndex];
SavedOrganisms.Add(Organism.Clone);
end;
end;
// Empty out everything
FitnessGroups.Clear;
FPopulationCount := 0;
// Insert saved organisms back into groups
for OrganismIndex := 0 to Pred(SavedOrganisms.Count) do
InsertOrganism(TcaOrganism(SavedOrganisms[OrganismIndex]));
finally
SavedOrganisms.Free;
end;
end;