-
Notifications
You must be signed in to change notification settings - Fork 5
/
Common.pas
742 lines (639 loc) · 22.1 KB
/
Common.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
{
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 Common; ////////////////////////////////////////////////////////////////////////
{
>> Version: 0.9
>> Description
Common routines and types used by various metaheuristics.
>> Author
Peter Karpov
Email : PeterKarpov@inversed.ru
Homepage : inversed.ru
GitHub : inversed-ru
Twitter : @inversed_ru
>> ToDo
? Split move lists and extended move lists sections into separate unit
? Use SignMinimize / SignMaximize instead of NormDeltaScore
? Rewrite NormDeltaScore using SignMinimize / SignMaximize
>> Changelog
0.9 : 2019.10.01 + Multirun statistics section
0.8 : 2019.05.21 ~ Renamed IsMinimize to Minimization
0.7 : 2018.09.18 ~ FreePascal compatibility
~ Renamed TScoreRelation to TScoreComparison
+ Missing routine comments
0.6 : 2015.09.14 + SwapSols procedure
0.5 : 2012.12.21 + DistToNearest function
0.4 : 2012.02.22 + Extra move list functions
0.1 : 2011.06.08 - Split 'SolutionList' into separate unit
0.0 : 2011.03.28 + Initial version
Notation: + added, - removed, * fixed, ~ changed
}
{$MINENUMSIZE 4}
interface ///////////////////////////////////////////////////////////////////////////
uses
Arrays,
Problem,
Messages;
type
TMetaheuristic =
(mhGA, mhSA, mhLS, mhTS, mhCTS);
PSolution = ^TSolution;
PSolutions = ^TSolutions;
TBasicStatus =
record
IterStatus : Integer;
SaveBest : Boolean;
ShowMessage : ProcMessage;
end;
TRunStats =
record
NFEfull,
NFEpartial : Int64;
Iters : Integer;
end;
const
ShortNames : array [TMetaheuristic] of AnsiString =
('GA', 'SA', 'LS', 'TS', 'CTS');
NoStatus : TBasicStatus =
(IterStatus: 0; SaveBest: False; ShowMessage: nil);
EmptyStats : TRunStats = (NFEfull: 0; NFEpartial: 0; Iters: 0);
SignMinimize = 2 * Ord(Minimization) - 1;
SignMaximize = -SignMinimize;
{-----------------------<< Scores >>------------------------------------------------}
type
TScoreComparison = (scoreWorse, scoreBetter, scoreEqual);
// Return a comparison between two scores taking IsMinimize flag into account.
// LongInt arguments are converted into doubles without loss of information.
function CompareScores(
Score1, Score2 : Real
) : TScoreComparison;
overload;
function CompareScores(
const Solution1,
Solution2 : TSolution
) : TScoreComparison;
overload;
// Normalized score difference between A and B: Result > 0 <=> A is better than B
function NormDeltaScore(
const A, B : TSolution
) : TScore;
overload;
// Normalized score difference between A and B: Result > 0 <=> A is better than B
function NormDeltaScore(
AScore,
BScore : Real
) : Real;
overload;
{-----------------------<< Multirun statistics >>-----------------------------------}
type
TMultirunStats =
record
Header : array of AnsiString;
NVars,
NSamples,
IdNextSample : Integer;
_ : array of array of TRealArrayN;
end;
// Initialized multirun statistics with a given number of variables
procedure InitMultirunStats(
var MultirunStats : TMultirunStats;
NVars : Integer);
// Prepare MultirunStats for the next run data collection
procedure PrepareNextRun(
var MultirunStats : TMultirunStats);
// Add statistical Data to MultirunStats
procedure AddSample(
var MultirunStats : TMultirunStats;
const Data : TRealArray);
// Save MultirunStats to a text file at Path, return operation status
function SaveStats(
const Path : AnsiString;
const MultirunStats : TMultirunStats
) : Boolean;
{-----------------------<< Solutions >>---------------------------------------------}
// Swap the solutions A and B
procedure SwapSols(
var A, B : TSolution);
// Replace Solution by Trial if the latter is better,
// return whether the replacement took place
function ReplaceIfBetter(
var Solution : TSolution;
const Trial : TSolution
) : Boolean;
// Try updating the Best solution with a Trial one,
// display a message via ShowMessage if successful
function TryUpdateBest(
var Best : TSolution;
const Trial : TSolution;
ShowMessage : ProcMessage
) : Boolean;
// Try saving a Solution to the specified Path, return whether the attempt
// was successful. Errors are displayed via ShowMessage.
function TrySaveSolution(
const Path : AnsiString;
const Solution : TSolution;
ShowMessage : ProcMessage
) : Boolean;
// Try loading a Solution from the specified Path, return whether the attempt
// was successful. Errors are displayed via ShowMessage.
function TryLoadSolution(
var Solution : TSolution;
const Path : AnsiString;
ShowMessage : ProcMessage
) : Boolean;
// Return which solution (0 or 1) is closer to the Base solution.
// Ties are broken at random.
function SimilarSolution(
const Base, Sol0, Sol1 : TSolution
) : Integer;
// Return the minimal distance from X to A and B
function DistToNearest(
const X, A, B : TSolution
) : Real;
// Create the Child by calling crossover with the order of parent arguments chosen
// at random. Recalc indicates whether the score recalculation is necessary.
procedure SymmetricCrossover(
var Child : TSolution;
const Parent1,
Parent2 : TSolution;
Recalc : Boolean);
{-----------------------<< Move lists >>--------------------------------------------}
// Initialize the MoveList, must be called before use
procedure InitMoveList(
var MoveList : TMoveList);
// MLTo := MLFrom
procedure AssignMoveList(
var MLTo : TMoveList;
var MLFrom : TMoveList);
// Set the length of MoveList to the actual number of stored moves
procedure SetTrueLength(
var MoveList : TMoveList);
// Add a Move to the MoveList
procedure AddMove(
var MoveList : TMoveList;
const Move : TMove);
// Delete a move defined by its Index from the MoveList
procedure DelMove(
var MoveList : TMoveList;
Index : Integer);
{-----------------------<< Extended Move lists >>-----------------------------------}
type
TExtMove =
record
Move : TMove;
Score : TScore;
Index : Integer;
end;
TExtMoveList =
record
N, Worst : Integer;
_ : array of TExtMove;
end;
// Initialize the MoveList with maximal length N, must be called before use
procedure InitExtMoveList(
var MoveList : TExtMoveList;
N : Integer);
// Try adding a Move with a given Score and Index to an extended move list. The move
// is added if there is free space or it is better than the worst move in the list.
procedure TryAddExtMove(
var MoveList : TExtMoveList;
const Move : TMove;
Score : TScore;
Index : Integer);
{-----------------------<< Files >>-------------------------------------------------}
// Try opening a text file F located at Path for writing, return operation
// status. Display an error message Msg via ShowMessage on failure.
function TryOpenWrite(
var F : Text;
const Path : AnsiString;
ShowMessage : ProcMessage;
Msg : AnsiString = ErrorOpenFile
) : Boolean;
// Try opening a text file F located at Path for reading, return operation
// status. Display an error message Msg via ShowMessage on failure.
function TryOpenRead(
var F : Text;
const Path : AnsiString;
ShowMessage : ProcMessage;
Msg : AnsiString = ErrorOpenFile
) : Boolean;
implementation //////////////////////////////////////////////////////////////////////
uses
InvSys,
Math, // Used: Power
SpecFuncs,
Statistics,
RandVars;
{-----------------------<< Scores >>------------------------------------------------}
procedure InvertScoreRelation(
var ScoreRel : TScoreComparison);
begin
if ScoreRel = scoreWorse then
ScoreRel := scoreBetter
else if ScoreRel = scoreBetter then
ScoreRel := scoreWorse;
end;
// Return a comparison between two scores taking IsMinimize flag into account.
// LongInt arguments are converted into doubles without loss of information.
function CompareScores(
Score1, Score2 : Real
) : TScoreComparison;
overload;
begin
if Score1 > Score2 then
Result := scoreBetter
else if Score1 < Score2 then
Result := scoreWorse
else
Result := scoreEqual;
if Minimization then
InvertScoreRelation(Result);
end;
function CompareScores(
const Solution1,
Solution2 : TSolution
) : TScoreComparison;
overload;
begin
if Solution1.Score > Solution2.Score then
Result := scoreBetter
else if Solution1.Score < Solution2.Score then
Result := scoreWorse
else
Result := scoreEqual;
if Minimization then
InvertScoreRelation(Result);
end;
// Normalized score difference between A and B: Result > 0 <=> A is better than B
function NormDeltaScore(
const A, B : TSolution
) : TScore;
overload;
begin
if Minimization then
Result := B.Score - A.Score else
Result := A.Score - B.Score;
end;
// Normalized score difference between A and B: Result > 0 <=> A is better than B
function NormDeltaScore(
AScore,
BScore : Real
) : Real;
overload;
begin
if Minimization then
Result := BScore - AScore else
Result := AScore - BScore;
end;
{-----------------------<< Multirun statistics >>-----------------------------------}
// Initialized multirun statistics with a given number of variables
procedure InitMultirunStats(
var MultirunStats : TMultirunStats;
NVars : Integer);
begin
SetLength(MultirunStats.Header, NVars);
SetLength(MultirunStats._, NVars);
MultirunStats.NVars := NVars;
MultirunStats.NSamples := 0;
MultirunStats.IdNextSample := 0;
end;
// Prepare MultirunStats for the next run data collection
procedure PrepareNextRun(
var MultirunStats : TMultirunStats);
begin
MultirunStats.IdNextSample := 0;
end;
// Add statistical Data to MultirunStats
procedure AddSample(
var MultirunStats : TMultirunStats;
const Data : TRealArray);
var
i : Integer;
begin
Assert(Length(Data) = MultirunStats.NVars);
with MultirunStats do
begin
// Resize the arrays if necessary
if IdNextSample = NSamples then
Inc(NSamples);
if Length(MultirunStats._[0]) < NSamples then
for i := 0 to NVars - 1 do
begin
SetLength(MultirunStats._[i], 2 * NSamples);
InitArrayN(MultirunStats._[i, NSamples - 1]);
end;
// Append the data
for i := 0 to NVars - 1 do
Append(MultirunStats._[i, IdNextSample], Data[i]);
Inc(IdNextSample);
end;
end;
// Save MultirunStats to a text file at Path, return operation status
function SaveStats(
const Path : AnsiString;
const MultirunStats : TMultirunStats
) : Boolean;
var
i, j, k, N : Integer;
Q : Real;
X : TRealArray;
FileStats : Text;
SingleRun : Boolean;
const
NStats = 4;
StatNames : array [1 .. NStats] of AnsiString
= ('_M', '_SD', '_SE', '_Md');
Sep : array [Boolean] of AnsiString = (Tab, '');
begin
Result := OpenWrite(FileStats, Path);
if (Result = Success) and (MultirunStats.NSamples > 0) then with MultirunStats do
begin
// Write the header
SingleRun := MultirunStats._[0, 0].N = 1;
if not SingleRun then
Write(FileStats, 'N');
for j := 0 to NVars - 1 do
if SingleRun then
Write(FileStats, Sep[j = 0], Header[j])
else
for k := 1 to NStats do
Write(FileStats, Tab, Header[j] + StatNames[k]);
WriteLn(FileStats);
// Write the data
for i := 0 to NSamples - 1 do
begin
N := MultirunStats._[0, i].N;
if not SingleRun then
Write(FileStats, N);
for j := 0 to NVars - 1 do
if SingleRun then
Write(FileStats, Sep[j = 0], MultirunStats._[j, i]._[0])
else
begin
X := Copy(MultirunStats._[j, i]._, 0, N);
for k := 1 to NStats do
begin
case k of
1: Q := Mean(X);
2: Q := StandDev(X);
3: Q := StandDev(X) / Sqrt(Max(1, N - 1));
4: Q := Median(X);
else
Assert(False);
Q := 0;
end;
Write(FileStats, Tab, Q);
end;
end;
WriteLn(FileStats);
end;
Close(FileStats);
end;
end;
{-----------------------<< Solutions >>---------------------------------------------}
// Swap the solutions A and B
procedure SwapSols(
var A, B : TSolution);
var
C : TSolution;
begin
AssignSolution(C, A);
AssignSolution(A, B);
AssignSolution(B, C);
end;
// Replace Solution by Trial if the latter is better,
// return whether the replacement took place
function ReplaceIfBetter(
var Solution : TSolution;
const Trial : TSolution
) : Boolean;
begin
if CompareScores(Trial, Solution) = scoreBetter then
begin
AssignSolution(Solution, Trial);
Result := Success;
end
else
Result := Fail;
end;
// Try updating the Best solution with a Trial one,
// display a message via ShowMessage if successful
function TryUpdateBest(
var Best : TSolution;
const Trial : TSolution;
ShowMessage : ProcMessage
) : Boolean;
begin
Result := ReplaceIfBetter(Best, Trial);
if Result = Success then
ShowNewBestScore(Best, ShowMessage);
end;
// Try saving a Solution to the specified Path, return whether the attempt
// was successful. Errors are displayed via ShowMessage.
function TrySaveSolution(
const Path : AnsiString;
const Solution : TSolution;
ShowMessage : ProcMessage
) : Boolean;
var
fileSol : Text;
const
ErrorSave = 'Failed to save Solution ';
begin
Result := TryOpenWrite(
fileSol, Path + '.' + FileExtension, ShowMessage, ErrorSave);
if Result = Success then
begin
SaveSolution(fileSol, Solution);
Close(fileSol);
Result := Success;
end;
end;
// Try loading a Solution from the specified Path, return whether the attempt
// was successful. Errors are displayed via ShowMessage.
function TryLoadSolution(
var Solution : TSolution;
const Path : AnsiString;
ShowMessage : ProcMessage
) : Boolean;
var
fileSol : Text;
const
ErrorLoad = 'Failed to load Solution ';
begin
Result := TryOpenRead(
fileSol, Path + '.' + FileExtension, ShowMessage, ErrorLoad);
if Result = Success then
begin
LoadSolution(Solution, fileSol);
Close(fileSol);
Result := Success;
end;
end;
// Return which solution (0 or 1) is closer to the Base solution.
// Ties are broken at random.
function SimilarSolution(
const Base, Sol0, Sol1 : TSolution
) : Integer;
var
Dist0, Dist1 : TSolutionDistance;
begin
Dist0 := Distance(Base, Sol0);
Dist1 := Distance(Base, Sol1);
if Dist0 < Dist1 then
Result := 0
else if Dist0 > Dist1 then
Result := 1
else
Result := Random(2);
end;
// Return the minimal distance from X to A and B
function DistToNearest(
const X, A, B : TSolution
) : Real;
begin
Result := Min(Distance(X, A), Distance(X, B));
end;
// Create the Child by calling crossover with the order of parent arguments chosen
// at random. Recalc indicates whether the score recalculation is necessary.
procedure SymmetricCrossover(
var Child : TSolution;
const Parent1,
Parent2 : TSolution;
Recalc : Boolean);
begin
if RandBool then
Crossover(Child, Parent1, Parent2, Recalc) else
Crossover(Child, Parent2, Parent1, Recalc);
end;
{-----------------------<< Move lists >>--------------------------------------------}
// Initialize the MoveList, must be called before use
procedure InitMoveList(
var MoveList : TMoveList);
begin
with MoveList do
begin
N := 0;
SetLength(Moves, 0);
end;
end;
// MLTo := MLFrom
procedure AssignMoveList(
var MLTo : TMoveList;
var MLFrom : TMoveList);
begin
MLTo.N := MLFrom.N;
MLTo.Moves := Copy(MLFrom.Moves, 0, MLFrom.N);
end;
// Set the length of MoveList to the actual number of stored moves
procedure SetTrueLength(
var MoveList : TMoveList);
begin
with MoveList do
SetLength(Moves, N);
end;
{.$RANGECHECKS OFF} {.$OVERFLOWCHECKS OFF}
// Add a Move to the MoveList
procedure AddMove(
var MoveList : TMoveList;
const Move : TMove);
begin
with MoveList do
begin
Inc(N);
if N > Length(Moves) then
SetLength(Moves, 2 * N);
Moves[N - 1] := Move;
end;
end;
{.$RANGECHECKS ON} {.$OVERFLOWCHECKS ON}
// Delete a move defined by its Index from the MoveList
procedure DelMove(
var MoveList : TMoveList;
Index : Integer);
begin
with MoveList do
begin
Dec(N);
Moves[Index] := Moves[N];
end;
end;
{-----------------------<< Extended Move lists >>-----------------------------------}
// Initialize the MoveList with maximal length N, must be called before use
procedure InitExtMoveList(
var MoveList : TExtMoveList;
N : Integer);
begin
MoveList.N := 0;
SetLength(MoveList._, N);
end;
// Try adding a Move with a given Score and Index to an extended move list. The move
// is added if there is free space or it is better than the worst move in the list.
procedure TryAddExtMove(
var MoveList : TExtMoveList;
const Move : TMove;
Score : TScore;
Index : Integer);
var
i : Integer;
Order : TIntArray;
begin
with MoveList do
if N < Length(MoveList._) then
begin
// Add move if there is free space
MoveList._[N].Move := Move;
MoveList._[N].Score := Score;
MoveList._[N].Index := Index;
if (N = 0) or (CompareScores(Score, MoveList._[Worst].Score) = scoreWorse) then
Worst := N;
Inc(N);
end
else if CompareScores(Score, MoveList._[Worst].Score) = scoreBetter then
begin
// Replace worst move
MoveList._[Worst].Move := Move;
MoveList._[Worst].Score := Score;
MoveList._[Worst].Index := Index;
// Find new worst move
RandPerm(Order, N, {Base:} 0);
for i := 0 to N - 1 do
if CompareScores(
MoveList._[Order[i]].Score,
MoveList._[ Worst].Score) = scoreWorse then
Worst := Order[i];
end;
end;
{-----------------------<< Files >>-------------------------------------------------}
// Try opening a text file F located at Path for writing, return operation
// status. Display an error message Msg via ShowMessage on failure.
function TryOpenWrite(
var F : Text;
const Path : AnsiString;
ShowMessage : ProcMessage;
Msg : AnsiString = ErrorOpenFile
) : Boolean;
begin
Result := OpenWrite(F, Path);
if Result = Fail then
ShowError(Msg + Path, ShowMessage);
end;
// Try opening a text file F located at Path for reading, return operation
// status. Display an error message Msg via ShowMessage on failure.
function TryOpenRead(
var F : Text;
const Path : AnsiString;
ShowMessage : ProcMessage;
Msg : AnsiString = ErrorOpenFile
) : Boolean;
begin
Result := OpenRead(F, Path);
if Result = Fail then
ShowError(Msg + Path, ShowMessage);
end;
end.