-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGeneticAlg.pas
1357 lines (1231 loc) · 45.8 KB
/
GeneticAlg.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
{
Copyright (c) Peter Karpov 2010 - 2018.
Usage of the works is permitted provided that this instrument is retained with
the works, so that any entity that uses the works is notified of this instrument.
DISCLAIMER: THE WORKS ARE WITHOUT WARRANTY.
}
{$IFDEF FPC} {$MODE DELPHI} {$ENDIF}
unit GeneticAlg; ////////////////////////////////////////////////////////////////////
{
>> Version: 3.0
>> Description
Implementation of a steady state genetic algorithm featuring various selection
and replacement methods.
>> Author
Peter Karpov
Email : [email protected]
Homepage : inversed.ru
GitHub : inversed-ru
Twitter : @inversed_ru
>> How to use
The user must supply mutation, crossover and solution distance routines via the
problem definition module.
>> ToDo
- More stopping criteria:
- Automatic convergence detection
- No improvement of best or average score for some N of generations
- Score standard deviation < threshold
- Average population distance < threshold
- Small rate of improvements
- Correlation measures for mutation and crossover operators - corelation between
the parents' scores and the child's score
>> Changelog
3.0 : 2019.12.01 + Huge amount of new selection, replacement and acceptance
options
+ Multirun statistics collection
2.1 : 2018.09.27 * NFE initialization
2.0 : 2018.09.16 - Many experimental and untested features
~ Cleaned up
~ Freepascal compatibility
1.5 : 2018.08.24 + Mixed, mixed compound and time dependent inverse rank
replacement options
+ Thermal child acceptance option
~ Selection option instead of the linear topology flag
+ Fitness-uniform selection
1.4 : 2015.08.11 + GA2, generational version of the genetic algorithm
1.3 : 2011.08.28 - Split dimorphic GA into a separate unit
1.2 : 2011.08.24 + Test implementation of a dimorphic GA
~ Modified reproduction
1.1 : 2011.08.08 + New reproduction and replacement types
1.0 : 2011.03.28 ~ Added unit header
~ Slightly reorganized
0.0 : 2010.11.14 + Initial version
Notation: + added, - removed, * fixed, ~ changed
}
{$MINENUMSIZE 4}
interface ///////////////////////////////////////////////////////////////////////////
uses
Math,
InvSys,
Arrays,
Sorting,
Statistics,
StringUtils,
Formatting,
Common,
SolutionLists,
Acceptance,
Problem,
Messages;
type
TSelection = (
// Score-based
selRankProp = 0, selFitUniform, selNearRank,
// Distance-based
selDist, selDistToBest,
// Topology-based
selRing, selLeakyRing, selLeakyRingTD, selTorus, selSegment,
selSegmentTD, selCrescent, selVarDegreeTD, selHalo, selDirHalo,
selThreadedRings, selInterconRings, selThreadedIsles, selBridgedIsles,
selChainedIsles, selInterconIsles, selRandNearConRings, selRandFarConRings,
selRandNearConIsles, selRandFarConIsles, selDisconIslesTD);
TReplacement = (
// Score-based
repWorst = 0, repWorstParent, repRandParent, repInvRank, repInvRankLn, repInvRankTD,
// Distance-based
repSimParent, repCenParent,
repSimWorseParent, repCenWorseParent,
repNoveltySim, repNoveltyCen,
repCompoundSimSD, repCompoundCenSD,
repCompoundSimRD, repCompoundCenRD,
repCompoundSimTD, repCompoundCenTD,
repCompSoftSimSD, repCompSoftCenSD,
repCompSoftSimRD, repCompSoftCenRD,
repCompSoftSimTD, repCompSoftCenTD,
// New solution injection
repInfluxRare, repInfluxRD, repInfluxSD, repInfluxTD,
// Topology-based
repDigraph
);
TGAAcceptance = (
gaaElitist = 0, gaaUnconditional,
gaaThreshold, gaaThresholdTD, gaaThresholdSD,
gaaDistToBestTD, gaaDistToBestSD, gaaDistToBestRD,
gaaDistToParentTD, gaaDistToParentSD, gaaDistToParentRD);
TStoppingCriterion = (scGenerations = 0, scNFE, scScore);
TGAParameters =
record
PopSize : Integer;
ReplaceP,
SelectP : Real;
Selection : TSelection;
MutationRate : Real;
Replacement : TReplacement;
Acceptance : TGAAcceptance;
Stopping : TStoppingCriterion;
MaxGens, MaxNFE : Integer;
ScoreToReach : TScore;
end;
TGAStatus =
record
GenSave,
GenStatus : Integer;
ShowMessage : ProcMessage;
end;
const
NoGAStatus : TGAStatus =
( GenSave : 0;
GenStatus : 0;
ShowMessage : nil;
);
// Run the genetic algorithm with specified Params, return the Best solution found
// and the search Stats, update MultirunStats
procedure GeneticAlgorithm(
var Best : TSolution;
var Stats : TRunStats;
var MultirunStats : TMultirunStats;
const Params : TGAParameters;
const Status : TGAStatus);
implementation //////////////////////////////////////////////////////////////////////
uses
ExtraMath,
RandVars,
IniConfigs,
StringLists;
type
TSolutionInfo =
record
BirthNFE,
NOps,
Dominated : Integer;
BirthGen,
DistToBest : Real;
end;
TPopulation =
record
SolList : TSolutionList;
SolutionsInfo : array of TSolutionInfo;
NFE,
NFEPrevGen,
Generation,
GenLastUpdate,
Improvements : Integer;
TMax, TMin : Real;
end;
TReprodInfo =
record
Parent1,
Parent2 : TSolutionIndex;
IsNew : Boolean;
end;
TPopParam = (
ppN, ppIteration, ppGeneration, ppLastUpdate, ppImprovements);
const
PopParamName : array [TPopParam] of AnsiString =
('Size', 'NFE', 'Generation', 'LastUpdate', 'Accepted');
PathPopParam = 'Parameters.txt';
PathInfo = 'Info.txt';
NameBest = 'GA_Best';
DirPopulation = 'Population';
{-----------------------<< Population operations >>---------------------------------}
// Initialize the Population with given Params
procedure InitPopulation(
var Population : TPopulation;
const Params : TGAParameters);
var
i : Integer;
begin
with Population, Params do
begin
// Create initial population, initialize solution info
NewSolList(SolList, PopSize);
SetLength(SolutionsInfo, PopSize);
for i := 0 to PopSize - 1 do
with SolutionsInfo[i] do
begin
BirthNFE := 0;
BirthGen := 0;
NOps := 0;
end;
// Initialize parameters
NFE := PopSize;
NFEPrevGen := PopSize;
Generation := 0;
GenLastUpdate := 0;
Improvements := 0;
end;
end;
// Return the normalized time or 0 if stopping criterion is scScore
function NormalizedTime(
const Population : TPopulation;
const Params : TGAParameters
) : Real;
begin
case Params.Stopping of
scGenerations: Result := Population.Generation / Params.MaxGens;
scNFE: Result := Population.NFE / Params.MaxNFE;
scScore: Result := 0;
else
Assert(False);
Result := 0;
end;
end;
{-----------------------<< Population save / load >>--------------------------------}
// Write a population Parameter with a given Value to fileParam
procedure WriteParameter(
var fileParam : Text;
Parameter : TPopParam;
Value : Integer);
const
ParamFormat = '{<16}= {}';
begin
WriteLn( fileParam, Format(ParamFormat, [PopParamName[Parameter], Value]) );
end;
// Return the path to the solution with a given Index located in Dir
function SolutionPath(
Index : Integer;
const Dir : AnsiString
) : AnsiString;
const
IndFormat = '{}{>08}';
begin
Result := Format(IndFormat, [Dir, Index + 1]);
end;
// Save the Population to Dir, show any messages via ShowMessage procedure
function SavePopulation(
Dir : AnsiString;
const Population : TPopulation;
ShowMessage : ProcMessage
) : Boolean;
var
i, j : TSolutionIndex;
fileParams,
fileInfo : Text;
const
MsgSaved = 'Population saved';
ErrorSave = 'Failed to save population';
begin
Result := Fail;
while True do with Population, SolList do
begin
// Save the best solution
if TrySaveSolution(NameBest, Best, ShowMessage) = Fail then
{<} break;
// Save the population parameters
EnforceDirSep(Dir);
if OpenWrite(fileParams, Dir + PathPopParam) = Success then
begin
WriteParameter(fileParams, ppN, N);
WriteParameter(fileParams, ppIteration, NFE);
WriteParameter(fileParams, ppGeneration, Generation);
WriteParameter(fileParams, ppLastUpdate, GenLastUpdate);
WriteParameter(fileParams, ppImprovements, Improvements);
Close(fileParams);
end
else
{<} break;
// Save Solution info
if OpenWrite(fileInfo, Dir + PathInfo) = Success then
begin
WriteLn(fileInfo, 'Index', Tab, 'Score', Tab, 'Age');
for i := 0 to N - 1 do
begin
j := RankIndex[i];
WriteLn(fileInfo,
i + 1, Tab,
SolList._[j].Score, Tab,
SolutionsInfo[j].BirthNFE, Tab,
SolutionsInfo[j].NOps, Tab);
end;
Close(fileInfo);
end
else
{<} break;
// Save all Solutions
Result := Success;
for i := 0 to N - 1 do
if TrySaveSolution(
SolutionPath(i, Dir), SolList._[ RankIndex[i] ], ShowMessage
) = Fail then
begin
Result := Fail;
{<} break;
end;
{<}break;
end;
// Display the status message
if Result = Success then
TryShowMessage(MsgSaved, ShowMessage) else
ShowError(ErrorSave, ShowMessage);
end;
// Load the Population from Dir, show any messages via ShowMessage procedure
function LoadPopulation(
var Population : TPopulation;
Dir : AnsiString;
ShowMessage : ProcMessage
) : Boolean;
var
fileInfo : Text;
i,
DummyIndex : Integer;
DummyScore : TScore;
LT : TLoadTable;
Errors : TStringList;
const
MsgLoaded = 'Population loaded';
ErrorLoad = 'Failed to load population';
begin
Result := Fail;
while True do with Population, SolList do
begin
// Read the population parameters
InitLoadTable(LT);
AddLoadParam(LT, N, PopParamName[ppN], nil);
AddLoadParam(LT, NFE, PopParamName[ppIteration], nil);
AddLoadParam(LT, Generation, PopParamName[ppGeneration], nil);
AddLoadParam(LT, GenLastUpdate, PopParamName[ppLastUpdate], nil);
AddLoadParam(LT, Improvements, PopParamName[ppImprovements], nil);
EnforceDirSep(Dir);
LoadFromConfig(LT, Dir + PathPopParam, Errors);
if Errors.N <> 0 then
{<} break;
// Load Solution info
if OpenRead(fileInfo, Dir + PathInfo) = Success then
begin
ReadLn(fileInfo);
for i := 0 to N - 1 do
begin
ReadLn(fileInfo,
DummyIndex,
DummyScore,
SolutionsInfo[i].BirthNFE,
SolutionsInfo[i].NOps);
SolutionsInfo[i].BirthGen := SolutionsInfo[i].BirthNFE / N;
end;
Close(fileInfo);
end
else
break;
// Load the population
Result := Success;
InitSolList(SolList, N);
for i := 0 to N - 1 do
if TryLoadSolution(
SolList._[i], SolutionPath(i, Dir), ShowMessage
) = Fail then
begin
Result := Fail;
{<} break;
end;
if Result = Success then
SetRanking(SolList);
{<}break;
end;
// Display the status message
if Result = Success then
TryShowMessage(MsgLoaded, ShowMessage) else
ShowError(ErrorLoad, ShowMessage);
end;
{-----------------------<< Reproduction >>------------------------------------------}
function WorstParent(
const Population : TPopulation;
const ReprodInfo : TReprodInfo
) : TSolutionIndex;
forward;
// Return the index of a random solution selected from Population
// via rank power law with parameter P
function RandPopIndex(
const Population : TPopulation;
const P : Real
) : TSolutionIndex;
begin
Result := RandSolIndex(Population.SolList, P);
end;
// Return two indices of distinct random solutions selected from Population
// according to the selection setting in Params
procedure TwoRandPopIndices(
var i1, i2 : TSolutionIndex;
const Population : TPopulation;
const Params : TGAParameters);
var
i, j, k,
M, L, H : Integer;
A : TIntArrayN;
D, BestD, t : Real;
DistToBest : TRealArray;
Order : TIntArray;
OldScore : TScore;
Undo : TSAUndo;
// Return the maximal number of step from vertex i
// on a crescent graph of size N
function CrescentRadius(
i, N : Integer
) : Integer;
begin
Result := Floor(Power(N / 2, 2 * Min(i, N - i) / N));
end;
begin
t := NormalizedTime(Population, Params);
case Params.Selection of
selRankProp:
TwoRandSolIndices(i1, i2, Population.SolList, Params.SelectP);
selFitUniform:
TwoRandFitUniformIndices(i1, i2, Population.SolList);
selNearRank:
with Population.SolList do
begin
k := Random(N - 1);
i1 := RankIndex[k];
i2 := RankIndex[k + 1];
end;
selDist:
begin
InitArrayN(A);
M := Max(2, Round(Abs(Params.SelectP)));
repeat
k := Random(Population.SolList.N);
AppendUnique(A, k);
until A.N = M;
i1 := A._[0];
i2 := A._[1];
BestD := Distance(
Population.SolList._[i1],
Population.SolList._[i2]);
for i := 2 to A.N - 1 do
for j := 0 to i - 1 do
begin
D := Distance(
Population.SolList._[ A._[i] ],
Population.SolList._[ A._[j] ]);
if ((Params.SelectP > 0) and (D > BestD)) or
((Params.SelectP < 0) and (D < BestD)) then
begin
BestD := D;
i1 := A._[i];
i2 := A._[j];
end;
end;
end;
selDistToBest:
begin
// #COPYPASTA
InitArrayN(A);
M := Max(2, Round(Abs(Params.SelectP)));
repeat
k := Random(Population.SolList.N);
AppendUnique(A, k);
until A.N = M;
InitArray(DistToBest, {Len:} M, {Value:} 0);
for i := 0 to M - 1 do
DistToBest[i] := Distance(
Population.SolList._[ A._[i] ],
Population.SolList.Best);
if Params.SelectP > 0 then
OrderRealArray(Order, DistToBest, soDescending) else
OrderRealArray(Order, DistToBest, soAscending);
i1 := A._[ Order[0] ];
i2 := A._[ Order[1] ];
end;
selRing:
with Population.SolList do
begin
i1 := Random(N);
i2 := (i1 + 1) mod N;
end;
selLeakyRing:
with Population.SolList do
begin
i1 := Random(N);
if Random(N) < 1 then
i2 := (i1 + 1 + Random(N - 1)) mod N else
i2 := (i1 + 1) mod N;
end;
selLeakyRingTD:
with Population.SolList do
begin
i1 := Random(N);
if Random < Power(t, Ln(N) + 1) then
i2 := (i1 + 1 + Random(N - 1)) mod N else
i2 := (i1 + 1) mod N;
end;
selTorus:
with Population.SolList do
begin
M := Round(Sqrt(N));
Assert(Sqr(M) = N);
i1 := Random(N);
if RandBool then
i2 := M * (i1 div M) + (i1 + 1) mod M else
i2 := (i1 + M) mod N;
end;
selSegment, selSegmentTD:
with Population.SolList do
begin
i1 := Random(N);
if Params.Selection = selSegment then
M := N div 2 else
M := Floor(N * (1 - t));
if i1 < M then
i2 := Modulo(i1 + RandSign, N)
else if (i1 = M ) and (Random(N - M - 1) < 1) then
i2 := Modulo(M - 1, N)
else if (i1 = N - 1) and (Random(N - M - 1) < 1) then
i2 := 0
else
i2 := M + (i1 - M + 1 + Random(N - M - 1)) mod (N - M);
end;
selCrescent:
with Population.SolList do
begin
i1 := Random(N);
repeat
i2 := Modulo(i1 + RandSign * RandRange(1, CrescentRadius(i1, N)), N);
until ModuloDistance(i1, i2, N) <= CrescentRadius(i2, N);
end;
selVarDegreeTD:
with Population.SolList do
begin
i1 := Random(N);
i2 := (i1 + 1 + Random(Floor(Power(N - 1, t)))) mod N;
end;
selHalo:
with Population.SolList do
begin
M := N div 2;
i1 := Random(N);
if i1 < M then
if Random(M) < 1 then
i2 := RandRange(M, N - 1) else
i2 := Modulo(i1 + RandSign, M)
else
i2 := M + (i1 - M + 1 + Random(N - M - 1)) mod (N - M);
end;
selDirHalo:
with Population.SolList do
begin
M := N div 2;
case Random(3) of
0: begin
i1 := Random(M);
i2 := Modulo(i1 + 1, M)
end;
1: begin
i1 := Random(M);
i2 := RandRange(M, N - 1);
end;
2: repeat
i1 := RandRange(M, N - 1);
i2 := RandRange(M, N - 1);
until i1 <> i2;
end;
if ((i1 >= M) or (i2 < M)) and
(CompareScores(
Population.SolList._[i2],
Population.SolList._[i1]) = scoreBetter) then
Swap(i1, i2);
end;
selThreadedRings:
with Population.SolList do
begin
M := Round(Sqrt(N));
Assert(Sqr(M) = N);
i1 := Random(N);
if (i1 mod M = 0) and RandBool then
i2 := Modulo(i1 + RandSign * M, N) else
i2 := M * (i1 div M) + Modulo(i1 + RandSign, M);
end;
selInterconRings:
with Population.SolList do
begin
M := Round(Sqrt(N));
Assert(Sqr(M) = N);
i1 := Random(N);
if (i1 mod M = 0) and (Random(1 + M) < M - 1) then
i2 := ( i1 + M * ( 1 + Random(M - 1) ) ) mod N else
i2 := M * (i1 div M) + Modulo(i1 + RandSign, M);
end;
selThreadedIsles:
with Population.SolList do
begin
M := Round(Sqrt(N));
Assert(Sqr(M) = N);
i1 := Random(N);
if (i1 mod M = 0) and (Random(1 + M) < 2) then
i2 := Modulo(i1 + RandSign * M, N) else
i2 := M * (i1 div M) + (i1 + 1 + Random(M - 1)) mod M;
end;
selBridgedIsles:
with Population.SolList do
begin
M := Round(Sqrt(N));
Assert(Sqr(M) = N);
i1 := Random(N);
if (i1 mod M = 0 ) and (Random(M) < 1) then
i2 := Modulo(i1 - 1, N)
else if (i1 mod M = (M - 1)) and (Random(M) < 1) then
i2 := Modulo(i1 + 1, N)
else
i2 := M * (i1 div M) + (i1 + 1 + Random(M - 1)) mod M;
end;
selChainedIsles:
with Population.SolList do
begin
M := Round(Sqrt(N));
Assert(Sqr(M) = N);
i1 := Random(N);
if i1 mod M = 0 then
i2 := Modulo(i1 + RandSign * (1 + Random(M)), N)
else
repeat
i2 := RandRange(M * (i1 div M), M * (1 + i1 div M)) mod N;
until i2 <> i1;
end;
selInterconIsles:
with Population.SolList do
begin
M := Round(Sqrt(N));
Assert(Sqr(M) = N);
i1 := Random(N);
if (i1 mod M = 0) and (Random(2) < 1) then
i2 := Modulo(i1 + (1 + Random(M - 1)) * M, N) else
i2 := M * (i1 div M) + (i1 + 1 + Random(M - 1)) mod M;
end;
selRandNearConRings, selRandFarConRings,
selRandNearConIsles, selRandFarConIsles:
with Population.SolList do
begin
M := Round(Sqrt(N));
Assert(Sqr(M) = N);
i1 := Random(N);
k := M * (i1 div M);
if Random(M) < 1 then
if Params.Selection in [selRandNearConRings, selRandNearConIsles] then
i2 := Modulo(k + RandSign * M + Random(M), N) else
i2 := Modulo(k + RandRange(M, N - 1), N)
else
if Params.Selection in [selRandNearConRings, selRandFarConRings] then
i2 := k + Modulo(i1 + RandSign, M) else
i2 := k + Modulo(i1 + RandRange(1, M - 1), M);
end;
selDisconIslesTD:
begin
M := Floor(Blend(Sqrt(Params.Popsize) + Ord(t > 0), 1, t));
k := Random(M);
L := ( k * Params.Popsize) div M;
H := ((k + 1) * Params.Popsize) div M - 1;
repeat
i1 := RandRange(L, H);
i2 := RandRange(L, H);
until i1 <> i2;
end;
else
Assert(False);
end;
end;
// Create the Child via crossover of two distinct random solutions
// selected from Population according to the selection setting in Params
// or anew in case of influx replacement, update ReprodInfo.
procedure Reproduce(
var Child : TSolution;
var ReprodInfo : TReprodInfo;
const Population : TPopulation;
const Params : TGAParameters);
var
i, j, k, dp : Integer;
x : Real;
begin
with ReprodInfo, Population do
begin
// Decide whether the child should be created from scratch
TwoRandPopIndices(Parent1, Parent2, Population, Params);
case Params.Replacement of
repInfluxRD:
begin
i := WorstParent(Population, ReprodInfo);
x := SolList.IndexRank[i] / (Params.PopSize - 1);
dp := 0;
end;
repInfluxSD:
begin
i := WorstParent(Population, ReprodInfo);
if Params.Selection = selTorus then
begin
k := Round(Sqrt(Params.PopSize));
j := i div k;
x := ModuloDistance(j, 0, k) / (k div 2);
end
else
x := i / (Params.PopSize - 1);
dp := 1;
end;
repInfluxTD:
begin
x := 1 - NormalizedTime(Population, Params);
dp := 1;
end;
end;
if Params.Replacement in [repInfluxRD, repInfluxSD, repInfluxTD] then
IsNew := Random < Power(x, Ln(Params.PopSize) + dp) else
IsNew := False;
// Create the child
if IsNew then
NewSolution(Child)
else
begin
Crossover(
Child, SolList._[Parent1], SolList._[Parent2], {RecalcScore:} False);
Mutate(Child);
Inc(SolutionsInfo[Parent1].NOps);
Inc(SolutionsInfo[Parent2].NOps);
end;
end;
end;
{-----------------------<< Replacement >>-------------------------------------------}
// Replace a solution with a given Index in the Population by the Child,
// update BestSoFar, display a message via ShowMessage in case of a new best score.
procedure ReplaceInPopulation(
var Population : TPopulation;
var BestSoFar : TSolution;
Index : TSolutionIndex;
const Child : TSolution;
ShowMessage : ProcMessage);
begin
with Population do
begin
with SolutionsInfo[Index] do
begin
NOps := 0;
BirthNFE := NFE;
BirthGen := BirthNFE / SolList.N;
end;
if CompareScores(Child, SolList._[Index]) = scoreBetter then
Inc(Improvements);
ReplaceSolution(SolList, Index, Child, {IfBetter:} False, nil);
end;
TryUpdateBest(BestSoFar, Child, ShowMessage);
end;
// Return the index of a random parent listed in ReprodInfo
function RandomParent(
const ReprodInfo : TReprodInfo
) : TSolutionIndex;
begin
if RandBool then
Result := ReprodInfo.Parent1 else
Result := ReprodInfo.Parent2
end;
// Return the index of the worst parent listed in ReprodInfo,
// break ties randomly
function WorstParent(
const Population : TPopulation;
const ReprodInfo : TReprodInfo
) : TSolutionIndex;
var
Comparison : TScoreComparison;
begin
with Population, ReprodInfo do
begin
Comparison := CompareScores(SolList._[Parent1], SolList._[Parent2]);
if Comparison = scoreWorse then
Result := Parent1
else if Comparison = scoreBetter then
Result := Parent2
else
Result := RandomParent(ReprodInfo);
end;
end;
// Return the index of the parent listed in ReprodInfo most similar to Child
function SimilarParent(
const Population : TPopulation;
const ReprodInfo : TReprodInfo;
const Child : TSolution
) : TSolutionIndex;
begin
with Population, ReprodInfo do
case SimilarSolution(Child, SolList._[Parent1], SolList._[Parent2]) of
0: Result := Parent1;
1: Result := Parent2;
else Result := -1;
Assert(False);
end;
end;
// Return the index of the parent listed in ReprodInfo
// closest to the best in population
function CentralParent(
const Population : TPopulation;
const ReprodInfo : TReprodInfo
) : TSolutionIndex;
var
D1, D2 : TSolutionDistance;
begin
with Population, ReprodInfo do
begin
D1 := Distance(SolList.Best, SolList._[Parent1]);
D2 := Distance(SolList.Best, SolList._[Parent2]);
if D1 < D2 then
Result := Parent1
else if D1 > D2 then
Result := Parent2
else
Result := WorstParent(Population, ReprodInfo);
end;
end;
// Return the index of IdParent's partner from ReprodInfo
function OtherParent(
const ReprodInfo : TReprodInfo;
IdParent : TSolutionIndex
) : TSolutionIndex;
begin
with ReprodInfo do
if IdParent = Parent1 then
Result := Parent2
else if IdParent = Parent2 then
Result := Parent1
else
begin
Result := -1;
Assert(False);
end;
end;
// Try replacing a solution from the Population by a Child provided its ReprodInfo.
// Which solution is replaced and whether the replacement actually takes place is
// determined by Params. Update BestSoFar, display a message via ShowMessage in
// case of a new best score.
procedure Replacement(
var Population : TPopulation;
var BestSoFar : TSolution;
const Child : TSolution;
const ReprodInfo : TReprodInfo;
const Params : TGAParameters;
ShowMessage : ProcMessage);
var
ReplaceIndex,
ReplaceNew : TSolutionIndex;
WorkSol : TSolution;
Accept : Boolean;
D1, D2,
OldD, NewD : TSolutionDistance;
t, x, dp : Real;
k, m, Tier,
IdMedian,
IdWorstParent,
IdBestParent,
IdSimParent : Integer;
Cmp1, Cmp2 : TScoreComparison;
begin
with Population, SolList, ReprodInfo do
begin
// Determine whom to replace
t := NormalizedTime(Population, Params);
IdMedian := RankIndex[N div 2];
case Params.Replacement of
// Worst in population
repWorst:
ReplaceIndex := RankIndex[N - 1];
// Inverse rank-proportional
repInvRank:
ReplaceIndex := RandPopIndex(Population, -Params.ReplaceP);
repInvRankLn:
ReplaceIndex := RandPopIndex(Population, -(Ln(Params.PopSize) + 1));
// Time-dependent inverse rank-proportional
repInvRankTD:
// P(0) = 1, P(1 / 2) = Ln(PopSize) + 1, P(1) = PopSize
ReplaceIndex := RandPopIndex(
Population,
- Exp(
Ln(Params.PopSize) *
Power(
t,
-Log2(
Ln(Ln(Params.PopSize) + 1) /
Ln(Params.PopSize)
)
)
)
);
// Random parent
repRandParent:
ReplaceIndex := RandomParent(ReprodInfo);
// Worst parent
repWorstParent, repInfluxRD, repInfluxSD, repInfluxTD:
ReplaceIndex := WorstParent(Population, ReprodInfo);
// Similar parent
repSimParent:
ReplaceIndex := SimilarParent(Population, ReprodInfo, Child);
// Central parent