/
gaga.hpp
1346 lines (1225 loc) · 47.9 KB
/
gaga.hpp
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
// Gaga: lightweight simple genetic algorithm library
// Copyright (c) Jean Disset 2021, All rights reserved.
// This library is free software; you can redistribute it and/or
//
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library.
/******************************************************************************************
* GAGA LIBRARY
*****************************************************************************************/
// This file contains :
// 1 - the Individual class template : an individual's generic representation, with its
// dna, fitnesses and other infos
// 2 - the main GA class template
#ifndef GAMULTI_HPP
#define GAMULTI_HPP
#include <assert.h>
#include <sys/stat.h>
#include <algorithm>
#include <chrono>
#include <cstring>
#include <deque>
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <random>
#include <sstream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include "third_party/json.hpp"
#include "tinypool.hpp"
#ifdef GAGA_COLOR_DISABLED
#define GAGA_COLOR_PURPLE ""
#define GAGA_COLOR_PURPLEBOLD ""
#define GAGA_COLOR_BLUE ""
#define GAGA_COLOR_BLUEBOLD ""
#define GAGA_COLOR_GREY ""
#define GAGA_COLOR_GREYBOLD ""
#define GAGA_COLOR_YELLOW ""
#define GAGA_COLOR_YELLOWBOLD ""
#define GAGA_COLOR_RED ""
#define GAGA_COLOR_REDBOLD ""
#define GAGA_COLOR_CYAN ""
#define GAGA_COLOR_CYANBOLD ""
#define GAGA_COLOR_GREEN ""
#define GAGA_COLOR_GREENBOLD ""
#define GAGA_COLOR_NORMAL ""
#else
#define GAGA_COLOR_PURPLE "\033[35m"
#define GAGA_COLOR_PURPLEBOLD "\033[1;35m"
#define GAGA_COLOR_BLUE "\033[34m"
#define GAGA_COLOR_BLUEBOLD "\033[1;34m"
#define GAGA_COLOR_GREY "\033[30m"
#define GAGA_COLOR_GREYBOLD "\033[1;30m"
#define GAGA_COLOR_YELLOW "\033[33m"
#define GAGA_COLOR_YELLOWBOLD "\033[1;33m"
#define GAGA_COLOR_RED "\033[31m"
#define GAGA_COLOR_REDBOLD "\033[1;31m"
#define GAGA_COLOR_CYAN "\033[36m"
#define GAGA_COLOR_CYANBOLD "\033[1;36m"
#define GAGA_COLOR_GREEN "\033[32m"
#define GAGA_COLOR_GREENBOLD "\033[1;32m"
#define GAGA_COLOR_NORMAL "\033[0m"
#endif
#ifdef GAGA_TESTING
#define GAGA_PROTECTED_TESTABLE public
#else
#define GAGA_PROTECTED_TESTABLE protected
#endif
namespace GAGA {
namespace fs = std::filesystem;
using std::cerr;
using std::cout;
using std::endl;
using std::string;
using std::unordered_map;
using std::unordered_set;
using json = nlohmann::json;
using std::chrono::high_resolution_clock;
using std::chrono::milliseconds;
using std::chrono::system_clock;
template <typename T, typename U>
std::ostream &operator<<(std::ostream &out, const std::pair<T, U> &p) {
out << "{" << p.first << ", " << p.second << "}";
return out;
}
template <typename... Args> std::string concat(Args &&... parts) {
std::stringstream ss;
(ss << ... << std::forward<Args>(parts));
return ss.str();
}
/*****************************************************************************
* INDIVIDUAL CLASS
* **************************************************************************/
// - wrapper for a dna
// - stores fitness
// - stores various infos (stats, lineage, custom infos)
//
// **************************************************************************
// A valid DNA class MUST have:
// ----------------------------
// string serialize() # MANDATORY
// constructor from serialized string # MANDATORY
//
// A DNA class SHOULD have:
// ------------------------
// DNA mutate() # optional (but you won't do much without it)
// DNA crossover(DNA& other) # optional for mutation only search
//
// A DNA class CAN have:
// ---------------------
// void reset() # if exists, will be used between each reuse of the same dna
//
// **************************************************************************
template <typename DNA> struct Individual {
using id_t = std::pair<size_t, size_t>;
DNA dna;
std::map<std::string, double>
fitnesses; // std::map {"fitnessCriterName" -> "fitnessValue"}
bool evaluated = false;
bool wasAlreadyEvaluated = false;
double evalTime = 0.0;
id_t id{0u, 0u}; // gen id , ind id
std::string infos; // custom infos, description, whatever... filled by user
std::map<string, double> stats; // custom stats, filled by user
// ancestry & lineage
std::vector<std::pair<size_t, size_t>>
parents; // vector of {{ generation id, individual id }}
std::string inheritanceType =
"exnihilo"; // inheritance type : mutation, crossover, copy, exnihilo
// Individual() {}
explicit Individual(const DNA &d) : dna(d) {}
explicit Individual(const json &o) {
assert(o.count("dna"));
dna = DNA(o.at("dna").get<std::string>());
if (o.count("fitnesses")) fitnesses = o.at("fitnesses").get<decltype(fitnesses)>();
if (o.count("infos")) infos = o.at("infos");
if (o.count("evaluated")) evaluated = o.at("evaluated");
if (o.count("alreadyEval")) wasAlreadyEvaluated = o.at("alreadyEval");
if (o.count("evalTime")) evalTime = o.at("evalTime");
if (o.count("stats")) stats = o.at("stats").get<decltype(stats)>();
if (o.count("parents")) parents = o.at("parents").get<decltype(parents)>();
if (o.count("inheritanceType")) inheritanceType = o.at("inheritanceType");
if (o.count("id")) id = o.at("id").get<decltype(id)>();
}
// Exports individual to json
json toJSON() const {
json o;
o["dna"] = dna.serialize();
o["fitnesses"] = fitnesses;
o["infos"] = infos;
o["evaluated"] = evaluated;
o["alreadyEval"] = wasAlreadyEvaluated;
o["evalTime"] = evalTime;
o["stats"] = stats;
o["parents"] = parents;
o["inheritanceType"] = inheritanceType;
o["id"] = id;
return o;
}
// Exports a std::vector of individual to json
template <typename Ind_t> static json popToJSON(const std::vector<Ind_t> &p) {
json o;
json popArray;
for (auto &i : p) popArray.push_back(i.toJSON());
o["population"] = popArray;
return o;
}
// Loads a std::vector of individual from json
template <typename Ind_t> static std::vector<Ind_t> loadPopFromJSON(const json &o) {
assert(o.count("population"));
std::vector<Ind_t> res;
json popArray = o.at("population");
for (auto &ind : popArray) res.push_back(Ind_t(ind));
return res;
}
};
template <typename DNA, typename Ind> void to_json(nlohmann::json &j, const Ind &i) {
j = i.toJSON();
}
template <typename DNA, typename Ind> void from_json(const nlohmann::json &j, Ind &i) {
i = Ind(j);
}
/*********************************************************************************
* GA CLASS
********************************************************************************/
enum class SelectionMethod { paretoTournament, randomObjTournament };
template <typename DNA, typename Ind = Individual<DNA>> class GA {
public:
using Ind_t = Ind;
using Iptr = Ind_t *;
using DNA_t = DNA;
GAGA_PROTECTED_TESTABLE :
/*********************************************************************************
* MAIN GA SETTINGS
********************************************************************************/
unsigned int verbosity = 2; // 0 = silent; 1 = generations stats;
// 2 = individuals stats + warnings; 3 = debug
size_t popSize = 500; // nb of individuals in the population
size_t nbElites = 1; // nb of elites to keep accross generations
size_t nbSavedElites = 1; // nb of elites to save
size_t tournamentSize = 5; // nb of competitors in tournament
bool savePopEnabled = true; // save the whole population
unsigned int savePopInterval = 1; // interval between 2 whole population saves
unsigned int saveGenInterval = 1; // interval between 2 elites/pareto saves
fs::path folder = "evos/"; // where to save the results
string evaluatorName; // name of the given evaluator func
double crossoverRate = 0.2; // crossover probability
double mutationRate = 0.5; // mutation probablility
bool evaluateAllIndividuals = false; // force evaluation of every individual
bool doSaveParetoFront = true; // save the pareto front
bool doSaveGenStats = true; // save generations stats to csv file
bool doSaveIndStats = false; // save individuals stats to csv file
bool saveAllPreviousGenerations = true; // save all previous generations in memory
// (might cause mem bloat if individuals contains LOTS of data)
SelectionMethod selecMethod = SelectionMethod::paretoTournament;
// thread pool (feel free to use it for your own computations)
unsigned int nbThreads = 1;
TinyPool::ThreadPool tp{nbThreads};
/********************************************************************************
* SETTERS
********************************************************************************/
public:
void enablePopulationSave() { savePopEnabled = true; }
void disablePopulationSave() { savePopEnabled = false; }
void setVerbosity(unsigned int lvl) { verbosity = lvl <= 3 ? (lvl >= 0 ? lvl : 0) : 3; }
void setPopSize(size_t s) { popSize = s; }
size_t getPopSize() const { return popSize; }
void setNbElites(size_t n) { nbElites = n; }
size_t getNbElites() const { return nbElites; }
void setNbSavedElites(size_t n) { nbSavedElites = n; }
void setTournamentSize(size_t n) { tournamentSize = n; }
void setPopSaveInterval(unsigned int n) { savePopInterval = n; }
void setGenSaveInterval(unsigned int n) { saveGenInterval = n; }
void setSaveFolder(std::string s) { folder = s; }
fs::path getSaveFolder() const { return folder; }
void setNbThreads(unsigned int n) {
if (n == 0) printWarning("Can't use 0 threads! Using 1 instead.");
nbThreads = std::max(1u, n);
tp.reset(nbThreads);
}
void setCrossoverRate(double p) {
crossoverRate = p <= 1.0 ? (p >= 0.0 ? p : 0.0) : 1.0;
}
double getCrossoverRate() const { return crossoverRate; }
void setMutationRate(double p) { mutationRate = p <= 1.0 ? (p >= 0.0 ? p : 0.0) : 1.0; }
int getVerbosity() const { return verbosity; }
double getMutationRate() const { return mutationRate; }
void setEvaluator(std::function<void(Ind_t &, int)> e,
std::string ename = "anonymousEvaluator") {
evaluator = e;
evaluatorName = ename;
for (auto &i : population) {
i.evaluated = false;
i.wasAlreadyEvaluated = false;
}
}
std::string getEvaluatorName() const { return evaluatorName; }
void setMutateMethod(std::function<void(DNA_t &)> m) { mutate = m; }
void setCrossoverMethod(std::function<DNA_t(const DNA_t &, const DNA_t &)> m) {
crossover = m;
}
void setNewGenerationFunction(std::function<void(void)> f) {
newGenerationFunction = f;
} // called before evaluating the current population
void setEvaluateFunction(std::function<void(void)> f) {
evaluate = f;
} // evaluation of the whole population
void setNextGenerationFunction(std::function<void(void)> f) {
nextGeneration = f;
} // evaluation and next generation
void setIsBetterMethod(std::function<bool(double, double)> f) { isBetter = f; }
void setSelectionMethod(const SelectionMethod &sm) { selecMethod = sm; }
using objList_t = std::unordered_set<std::string>;
template <typename S> std::function<Iptr(S &, const objList_t &)> getSelectionMethod() {
switch (selecMethod) {
case SelectionMethod::paretoTournament:
return [this](S &subPop, const objList_t &objectives) {
return paretoTournament(subPop, objectives);
};
case SelectionMethod::randomObjTournament:
default:
return [this](S &subPop, const objList_t &objectives) {
return randomObjTournament(subPop, objectives);
};
}
}
bool getEvaluateAllIndividuals() { return evaluateAllIndividuals; }
void setEvaluateAllIndividuals(bool m) { evaluateAllIndividuals = m; }
void setSaveParetoFront(bool m) { doSaveParetoFront = m; }
void setSaveGenStats(bool m) { doSaveGenStats = m; }
void setSaveIndStats(bool m) { doSaveIndStats = m; }
// main current and previous population containers
void disableGenerationHistory() { saveAllPreviousGenerations = false; }
void enableGenerationHistory() { saveAllPreviousGenerations = true; }
std::vector<Ind_t> population; // current population
std::vector<std::vector<Ind_t>> previousGenerations; // previous generations. Contains
// at least the most recent one.
size_t getCurrentGenerationNumber() const { return currentGeneration; }
// genStats will be populated with some basic generation stats
std::vector<std::map<std::string, std::map<std::string, double>>> genStats;
////////////////////////////////////////////////////////////////////////////////////
static std::mt19937_64 &globalRand() {
std::random_device rd;
static thread_local std::mt19937_64 r(rd());
return r;
};
GAGA_PROTECTED_TESTABLE :
size_t currentGeneration = 0;
bool customInit = false;
int nbProcs = 1;
// default mutate and crossover are taken from the DNA_t class, if they are defined.
template <class D> auto defaultMutate(D &d) -> decltype(d.mutate()) {
return d.mutate();
}
template <class D, class... SFINAE> void defaultMutate(D &, SFINAE...) {
printLn(3, "WARNING: no mutate method specified");
}
template <class D>
auto defaultCrossover(const D &d1, const D &d2) -> decltype(d1.crossover(d2)) {
return d1.crossover(d2);
}
template <class D, class... SFINAE> D defaultCrossover(const D &d1, SFINAE...) {
printLn(3, "WARNING: no crossover method specified");
return d1;
}
// default reset method taken from the DNA_t class, if defined.
template <class D> auto defaultReset(D &d) -> decltype(d.reset()) { return d.reset(); }
template <class D, class... SFINAE> void defaultReset(D &, SFINAE...) {
printLn(3, "WARNING: no reset method specified");
}
// crossover and mutate are 2 lambdas that call defaultMutate and defaultCrossover. It
// shouldn't be needed for most use cases, but for advanced usage and logging, the user
// can override these methods. Change at your own risks.
std::function<DNA_t(const DNA_t &, const DNA_t &)> crossover =
[this](const DNA_t &d1, const DNA_t &d2) { return defaultCrossover(d1, d2); };
std::function<void(DNA_t &)> mutate = [this](DNA_t &d) { defaultMutate(d); };
// wrapper around mutate that updates lineage stats
Ind_t mutatedIndividual(const Ind_t &i) {
Ind_t offspring(i.dna);
mutate(offspring.dna);
offspring.parents.clear();
offspring.parents.push_back(i.id);
offspring.inheritanceType = "mutation";
offspring.evaluated = false;
return offspring;
}
// wrapper around crossover that updates lineage stats
Ind_t crossoverIndividual(const Ind_t &a, const Ind_t &b) {
Ind_t offspring(crossover(a.dna, b.dna));
offspring.parents.clear();
offspring.parents.push_back(a.id);
offspring.parents.push_back(b.id);
offspring.inheritanceType = "crossover";
offspring.evaluated = false;
return offspring;
}
std::function<void(Ind_t &, int)> evaluator;
std::function<void(void)> newGenerationFunction = []() {};
std::function<void(void)> nextGeneration = [this]() { classicNextGen(); };
std::function<void(void)> evaluate = [this]() { defaultEvaluate(); };
std::function<bool(double, double)> isBetter = [](double a, double b) { return a > b; };
// returns a reference (transforms pointer into reference)
template <typename T> inline T &ref(T &obj) { return obj; }
template <typename T> inline T &ref(T *obj) { return *obj; }
template <typename T> inline const T &ref(const T &obj) { return obj; }
template <typename T> inline const T &ref(const T *obj) { return *obj; }
// HOOKS (for extensions)
// pre / post Evaluation
std::vector<std::function<void(GA &)>> preEvaluation_hooks;
std::vector<std::function<void(GA &)>> postEvaluation_hooks;
// enabled objectives hooks is meant to allow extensions to manipulate the list of
// objectives.
// "disabled" objectives are not deleted, they just don't appear in the list
// of enabled ones
std::vector<std::function<void(GA &, std::unordered_set<std::string> &)>>
enabledObjectives_hooks;
// save pop
std::vector<std::function<void(GA &)>> savePop_hooks;
// printStart : prints stuff at startup
std::vector<std::function<void(const GA &)>> printStart_hooks;
// printIndividual: prints stuff for each individual, usually after eval
std::vector<std::function<std::string(const GA &, const Ind_t &)>>
printIndividual_hooks;
// register an extension with this method:
// evaluation is the main step of the evaluation phase. It can be extended using the pre
// and postEvaluation hooks
void evaluation() {
for (auto &f : preEvaluation_hooks) f(*this);
evaluate();
for (auto &f : postEvaluation_hooks) f(*this);
}
public:
/*********************************************************************************
* CONSTRUCTOR
********************************************************************************/
GA() {}
// EXTENSIONS & HOOKS
template <typename E> void useExtension(E &e) { e.onRegister(*this); }
template <typename H> void addPreEvaluationMethod(const H &&h) {
preEvaluation_hooks.emplace_back(h);
}
template <typename H> void addPostEvaluationMethod(const H &&h) {
postEvaluation_hooks.emplace_back(h);
}
template <typename H> void addEnabledObjectivesMethod(const H &&h) {
enabledObjectives_hooks.emplace_back(h);
}
template <typename H> void addSavePopMethod(const H &&h) {
savePop_hooks.emplace_back(h);
}
template <typename H> void addPrintStartMethod(const H &&h) {
printStart_hooks.emplace_back(h);
}
template <typename H> void addPrintIndividualMethod(const H &&h) {
printIndividual_hooks.emplace_back(h);
}
void setPopulation(const std::vector<Ind_t> &p) {
population = p;
popSize = population.size();
setPopulationId(population, currentGeneration);
}
void initPopulation(const std::function<DNA()> &f) {
population.clear();
population.reserve(popSize);
for (size_t i = 0; i < popSize; ++i) {
population.push_back(Ind_t(f()));
population[population.size() - 1].evaluated = false;
}
setPopulationId(population, currentGeneration);
}
void defaultEvaluate() { // uses evaluator
// on avg, each thread will receive pop/NBATCH_PER_THREAD evaluations
const double NBATCH_PER_THREAD = 4;
if (!evaluator) throw std::invalid_argument("No evaluator specified");
tp.autoChunksId_work(
0, population.size(),
[this](size_t i, size_t procId) {
if (evaluateAllIndividuals || !population[i].evaluated) {
printLn(3, "Going to evaluate ind ");
auto t0 = high_resolution_clock::now();
defaultReset(population[i].dna);
evaluator(population[i], procId);
auto t1 = high_resolution_clock::now();
population[i].evaluated = true;
double indTime = std::chrono::duration<double>(t1 - t0).count();
population[i].evalTime = indTime;
population[i].wasAlreadyEvaluated = false;
} else {
population[i].evalTime = 0.0;
population[i].wasAlreadyEvaluated = true;
}
if (verbosity >= 2) printIndividualStats(population[i], procId);
},
NBATCH_PER_THREAD);
tp.waitAll();
}
// "Vroum vroum"
void step(int nbGeneration = 1) {
tp.reset(nbThreads);
if (currentGeneration == 0) {
createFolder(folder);
if (verbosity >= 1) printStart();
}
for (int nbg = 0; nbg < nbGeneration; ++nbg) {
newGenerationFunction();
auto tg0 = high_resolution_clock::now();
nextGeneration();
assert(previousGenerations.back().size());
if (population.size() != popSize)
throw std::invalid_argument("Population doesn't match the popSize param");
auto tg1 = high_resolution_clock::now();
double totalTime = std::chrono::duration<double>(tg1 - tg0).count();
auto tnp0 = high_resolution_clock::now();
if (savePopInterval > 0 && currentGeneration % savePopInterval == 0) {
if (savePopEnabled) savePop();
for (auto &f : savePop_hooks) f(*this);
}
if (saveGenInterval > 0 && currentGeneration % saveGenInterval == 0) {
if (doSaveParetoFront) {
saveParetoFront();
} else {
if (nbSavedElites > 0) saveBests(nbSavedElites);
}
}
updateStats(totalTime);
if (verbosity >= 1) printGenStats(currentGeneration);
if (doSaveGenStats) saveGenStats();
if (doSaveIndStats) saveIndStats();
auto tnp1 = high_resolution_clock::now();
double tnp = std::chrono::duration<double>(tnp1 - tnp0).count();
printInfos("Time for save operations = ", tnp, "s");
++currentGeneration;
}
}
// helper that returns the unordered list of all objectives currently in an individual
template <typename I>
static std::unordered_set<std::string> getAllObjectives(const I &i) {
std::unordered_set<std::string> objs;
for (const auto &o : i.fitnesses) objs.insert(o.first);
return objs;
}
template <typename I> std::unordered_set<std::string> getEnabledObjectives(const I &i) {
auto objectives = getAllObjectives(i);
for (auto &f : enabledObjectives_hooks) f(*this, objectives); // hook
return objectives;
}
/*********************************************************************************
* NEXT POP GETTING READY
********************************************************************************/
// Simple next generation routine:
void classicNextGen() {
assert(population.size() > 0);
evaluation(); // 1 - evaluation
// 2- create next generation with select/mutate/cross
auto objectives = getEnabledObjectives(population[0]);
auto nextGen = produceNOffsprings(popSize, population, nbElites, objectives);
// 3 - save old gen, next gen becomes current one,.
savePopToPreviousGenerations(population);
population = nextGen;
setPopulationId(population, currentGeneration + 1);
printDbg("Next generation ready");
}
void setPopulationId(std::vector<Ind_t> &p, size_t genId) {
// reinitialize individuals' id to a pair {genId , 0 to N}
for (size_t i = 0; i < p.size(); ++i) p[i].id = std::make_pair(genId, i);
}
template <typename I> // I is ither Ind_t or Ind_t*
std::vector<Ind_t> produceNOffsprings(
size_t n, std::vector<I> &popu, size_t nElites,
const std::unordered_set<std::string> objectives) {
assert(popu.size() >= nElites);
assert(objectives.size() > 0);
printDbg("Going to produce ", n, " offsprings out of ", popu.size(), " individuals");
std::uniform_real_distribution<double> d(0.0, 1.0);
std::vector<Ind_t> nextGen;
nextGen.reserve(n);
// Elites are placed at the begining
if (nElites > 0) {
auto elites = getElites(nElites, popu);
printDbg("retrieved ", elites.size(), " elites");
for (auto &e : elites)
for (auto i : e.second) {
i.parents.clear();
i.parents.push_back(i.id);
i.inheritanceType = "copy";
nextGen.push_back(i);
}
}
auto selection = getSelectionMethod<std::vector<I>>();
auto s = nextGen.size();
size_t nCross = crossoverRate * (n - s);
size_t nMut = mutationRate * (n - s);
std::vector<std::vector<Ind_t>> nextGen_perThread; // to avoid mutexes
nextGen_perThread.resize(nbThreads);
for (auto &ng : nextGen_perThread) ng.reserve(1.5 * (nCross + nMut) / nbThreads);
printDbg("Going to proceed to ", nCross, " crossovers");
for (size_t i = s; i < nCross + s; ++i) {
tp.push_work([&](size_t threadId) {
nextGen_perThread[threadId].emplace_back(crossoverIndividual(
*selection(popu, objectives), *selection(popu, objectives)));
});
}
printDbg("Going to proceed to ", nMut, " mutations");
for (size_t i = nCross + s; i < nMut + nCross + s; ++i) {
tp.push_work([&](size_t threadId) {
nextGen_perThread[threadId].emplace_back(
mutatedIndividual(*selection(popu, objectives)));
});
}
tp.waitAll();
for (auto &ng : nextGen_perThread) {
nextGen.insert(nextGen.end(), std::make_move_iterator(ng.begin()),
std::make_move_iterator(ng.end()));
}
while (nextGen.size() < n) { // filling up the rest with copy
auto i = *selection(popu, objectives);
i.parents.clear();
i.parents.push_back(i.id);
i.inheritanceType = "copy";
nextGen.push_back(i);
printDbg("Filling pop with an extra individual copy");
}
printDbg("nextGen.size(): ", nextGen.size());
assert(nextGen.size() == n);
return nextGen;
}
// PARETO HELPERS
bool paretoDominates(const Ind_t &a, const Ind_t &b,
const std::unordered_set<std::string> &objectives) const {
for (const auto &o : objectives) {
assert(a.fitnesses.count(o));
assert(b.fitnesses.count(o));
if (!isBetter(a.fitnesses.at(o), b.fitnesses.at(o))) return false;
}
return true;
}
size_t getParetoRank(const std::vector<Ind_t *> &inds, size_t i,
const std::unordered_set<std::string> &objectives) {
return getParetoRank_recursiveImpl(inds, inds[i], objectives, 0);
}
size_t getParetoRank_recursiveImpl(const std::vector<Ind_t *> &inds, Ind_t *i,
const std::unordered_set<std::string> &objectives,
size_t d) {
if (std::find(inds.begin(), inds.end(), i) == inds.end()) {
return d;
} else
return getParetoRank_recursiveImpl(removeParetoFront(inds, objectives), i,
objectives, d + 1);
}
std::vector<Ind_t *> removeParetoFront(
const std::vector<Ind_t *> &ind,
const std::unordered_set<std::string> &objectives) const {
// removes the pareto front and returns the rest
auto paretoFront = getParetoFront(ind, objectives);
std::vector<Ind_t *> res;
res.reserve(ind.size() - paretoFront.size());
for (auto i : ind) {
if (std::find(paretoFront.begin(), paretoFront.end(), i) ==
paretoFront.end()) // not in pareto front
res.push_back(i);
}
return res;
}
std::vector<Ind_t *> getParetoFront(const std::vector<Ind_t *> &ind) const {
assert(ind.size() > 0);
std::unordered_set<std::string> objs;
for (const auto &o : ind[0]->fitnesses) objs.insert(o.first);
return getParetoFront(ind, objs);
}
std::vector<Ind_t *> getParetoFront(
const std::vector<Ind_t *> &ind,
const std::unordered_set<std::string> &objectives) const {
// naive algorithm. Should be ok for small ind.size()
assert(ind.size() > 0);
std::vector<Ind_t *> pareto;
for (size_t i = 0; i < ind.size(); ++i) {
bool dominated = false;
for (auto &j : pareto) {
// is i dominated by any individual already on the pareto front?
if (paretoDominates(*j, *ind[i], objectives)) {
dominated = true;
break;
}
}
if (!dominated) {
for (size_t j = i + 1; j < ind.size(); ++j) {
// or by any other point ?
if (paretoDominates(*ind[j], *ind[i], objectives)) {
dominated = true;
break;
}
}
if (!dominated) {
pareto.push_back(ind[i]);
}
}
}
return pareto;
}
template <typename I>
Ind_t *paretoTournament(std::vector<I> &subPop,
const std::unordered_set<std::string> &objectives) {
assert(subPop.size() > 0);
assert(objectives.size() > 0);
std::uniform_int_distribution<size_t> dint(0, subPop.size() - 1);
std::vector<Ind_t *> participants;
for (size_t i = 0; i < tournamentSize; ++i)
participants.push_back(&ref(subPop[dint(globalRand())]));
auto pf = getParetoFront(participants, objectives);
assert(pf.size() > 0);
std::uniform_int_distribution<size_t> dpf(0, pf.size() - 1);
return pf[dpf(globalRand())];
}
template <typename I>
Ind_t *randomObjTournament(std::vector<I> &subPop,
const std::unordered_set<std::string> &objectives) {
assert(subPop.size() > 0);
assert(objectives.size() > 0);
if (verbosity >= 3) cerr << "random obj tournament called" << endl;
std::uniform_int_distribution<size_t> dint(0, subPop.size() - 1);
std::vector<Ind_t *> participants;
for (size_t i = 0; i < tournamentSize; ++i)
participants.push_back(&ref(subPop[dint(globalRand())]));
auto champion = participants[0];
// we pick the objective randomly
std::string obj;
if (objectives.size() == 1) {
obj = *(objectives.begin());
} else {
std::uniform_int_distribution<int> dObj(0, static_cast<int>(objectives.size()) - 1);
auto it = objectives.begin();
std::advance(it, dObj(globalRand()));
obj = *it;
}
for (size_t i = 1; i < tournamentSize; ++i) {
assert(participants[i]->fitnesses.count(obj));
if (isBetter(participants[i]->fitnesses.at(obj), champion->fitnesses.at(obj)))
champion = participants[i];
}
if (verbosity >= 3) cerr << "champion found" << endl;
return champion;
}
// getELites methods : returns a std::vector of N best individuals in the specified
// subPopulations, for the specified fitnesses.
// elites indivuduals are not ordered.
unordered_map<string, std::vector<Ind_t>> getElites(size_t n) {
std::vector<string> obj;
for (auto &o : population[0].fitnesses) obj.push_back(o.first);
return getElites(obj, n, population);
}
template <typename I>
unordered_map<string, std::vector<Ind_t>> getElites(size_t n,
const std::vector<I> &popVec) {
std::vector<string> obj;
for (auto &o : ref(popVec[0]).fitnesses) obj.push_back(o.first);
return getElites(obj, n, popVec);
}
unordered_map<string, std::vector<Ind_t>> getLastGenElites(size_t n) {
std::vector<string> obj;
for (auto &o : population[0].fitnesses) obj.push_back(o.first);
return getElites(obj, n, previousGenerations.back());
}
template <typename I>
unordered_map<string, std::vector<Ind_t>> getElites(const std::vector<string> &obj,
size_t n,
const std::vector<I> &popVec) {
if (verbosity >= 3) {
cerr << "getElites : nbObj = " << obj.size() << " n = " << n << endl;
}
unordered_map<string, std::vector<Ind_t>> elites;
for (auto &o : obj) {
elites[o] = std::vector<Ind_t>();
elites[o].push_back(ref(popVec[0]));
size_t worst = 0;
for (size_t i = 1; i < n && i < popVec.size(); ++i) {
elites[o].push_back(ref(popVec[i]));
if (isBetter(elites[o][worst].fitnesses.at(o), ref(popVec[i]).fitnesses.at(o)))
worst = i;
}
for (size_t i = n; i < popVec.size(); ++i) {
if (isBetter(ref(popVec[i]).fitnesses.at(o), elites[o][worst].fitnesses.at(o))) {
elites[o][worst] = ref(popVec[i]);
for (size_t j = 0; j < n; ++j) {
if (isBetter(elites[o][worst].fitnesses.at(o), elites[o][j].fitnesses.at(o)))
worst = j;
}
}
}
}
return elites;
}
/*********************************************************************************
* STATS, LOGS & PRINTING
********************************************************************************/
template <typename... Args> void printError(Args &&... a) const {
const size_t ERROR_VERBOSITY_LVL = 1;
printLn_stderr(ERROR_VERBOSITY_LVL, GAGA_COLOR_RED, "[ERROR] ", GAGA_COLOR_NORMAL,
std::forward<Args>(a)...);
}
template <typename... Args> void printWarning(Args &&... a) const {
const size_t WARNING_VERBOSITY_LVL = 2;
printLn(WARNING_VERBOSITY_LVL, GAGA_COLOR_YELLOW, "[WARNING] ", GAGA_COLOR_NORMAL,
std::forward<Args>(a)...);
}
template <typename... Args> void printInfos(Args &&... a) const {
const size_t WARNING_VERBOSITY_LVL = 2;
printLn(WARNING_VERBOSITY_LVL, GAGA_COLOR_GREYBOLD, "[INFO] ", GAGA_COLOR_NORMAL,
std::forward<Args>(a)...);
}
template <typename... Args> void printDbg(Args &&... a) const {
const size_t DEBUG_VERBOSITY_LVL = 3;
printLn_stderr(DEBUG_VERBOSITY_LVL, GAGA_COLOR_BLUE, "[DBG] ", GAGA_COLOR_NORMAL,
std::forward<Args>(a)...);
}
template <typename... Args> void printLn_stderr(size_t lvl, Args &&... a) const {
if (verbosity >= lvl) {
std::ostringstream output;
subPrint(output, std::forward<Args>(a)...);
std::cerr << output.str();
}
}
template <typename... Args> void printLn(size_t lvl, Args &&... a) const {
if (verbosity >= lvl) {
std::ostringstream output;
subPrint(output, std::forward<Args>(a)...);
std::cout << output.str();
}
}
template <typename T, typename... Args>
void subPrint(std::ostringstream &output, const T &t, Args &&... a) const {
output << t;
subPrint(output, std::forward<Args>(a)...);
}
void subPrint(std::ostringstream &output) const { output << std::endl; }
void printStart() const {
int nbCol = 55;
std::cout << std::endl << GAGA_COLOR_GREY;
#ifndef GAGA_UTF8_DEBUG_PRINT_DISABLED
auto lineChar = "━";
#else
auto lineChar = "━";
#endif
for (int i = 0; i < nbCol - 1; ++i) std::cout << lineChar;
std::cout << std::endl;
std::cout << GAGA_COLOR_YELLOW << " ☀ " << GAGA_COLOR_NORMAL
<< " Starting GAGA " << GAGA_COLOR_YELLOW << " ☀ " << GAGA_COLOR_NORMAL;
std::cout << std::endl;
#ifndef GAGA_UTF8_DEBUG_PRINT_DISABLED
std::cout << GAGA_COLOR_BLUE << " ¯\\_ಠ ᴥ ಠ_/¯" << std::endl
<< GAGA_COLOR_GREY;
#endif
for (int i = 0; i < nbCol - 1; ++i) std::cout << "┄";
std::cout << std::endl << GAGA_COLOR_NORMAL;
std::cout << " - population size = " << GAGA_COLOR_BLUE << popSize
<< GAGA_COLOR_NORMAL << std::endl;
std::cout << " - nb of elites = " << GAGA_COLOR_BLUE << nbElites << GAGA_COLOR_NORMAL
<< std::endl;
std::cout << " - nb of tournament competitors = " << GAGA_COLOR_BLUE
<< tournamentSize << GAGA_COLOR_NORMAL << std::endl;
std::cout << " - selection = " << GAGA_COLOR_BLUE
<< selectMethodToString(selecMethod) << GAGA_COLOR_NORMAL << std::endl;
std::cout << " - mutation rate = " << GAGA_COLOR_BLUE << mutationRate
<< GAGA_COLOR_NORMAL << std::endl;
std::cout << " - crossover rate = " << GAGA_COLOR_BLUE << crossoverRate
<< GAGA_COLOR_NORMAL << std::endl;
std::cout << " - writing results in " << GAGA_COLOR_BLUE << folder.u8string()
<< GAGA_COLOR_NORMAL << std::endl;
for (int i = 0; i < nbCol - 1; ++i) std::cout << lineChar;
std::cout << std::endl;
for (auto &f : printStart_hooks) f(*this);
std::cout << GAGA_COLOR_GREY;
for (int i = 0; i < nbCol - 1; ++i) std::cout << lineChar;
std::cout << GAGA_COLOR_NORMAL << std::endl;
}
void updateStats(double totalTime) {
// stats organisations :
// "global" -> {"genTotalTime", "indTotalTime", "maxTime", "nEvals", "nObjs"}
// "obj_i" -> {"avg", "worst", "best"}
assert(previousGenerations.size());
auto &lastGen = previousGenerations.back();
std::map<std::string, std::map<std::string, double>> currentGenStats;
currentGenStats["global"]["genTotalTime"] = totalTime;
double indTotalTime = 0.0, maxTime = 0.0;
int nEvals = 0;
int nObjs = static_cast<int>(lastGen[0].fitnesses.size());
for (const auto &o : lastGen[0].fitnesses) {
currentGenStats[o.first] = {
{{"avg", 0.0}, {"worst", o.second}, {"best", o.second}}};
}
// computing min, avg, max from custom individual stats
auto customStatsNames = lastGen[0].stats;
std::map<string, std::tuple<double, double, double>> customStats;
for (auto &csn : customStatsNames)
customStats[csn.first] = std::make_tuple<double, double, double>(
std::numeric_limits<double>::max(), 0.0, std::numeric_limits<double>::min());
for (auto &ind : lastGen) {
for (auto &cs : customStats) {
double v = ind.stats.at(cs.first);
if (v < std::get<0>(cs.second)) std::get<0>(cs.second) = v;
if (v > std::get<2>(cs.second)) std::get<2>(cs.second) = v;
std::get<1>(cs.second) += v / static_cast<double>(lastGen.size());
}
}
for (auto &cs : customStats) {
{
std::ostringstream n;
n << cs.first << "_min";
currentGenStats["custom"][n.str()] = std::get<0>(cs.second);
}
{
std::ostringstream n;
n << cs.first << "_avg";
currentGenStats["custom"][n.str()] = std::get<1>(cs.second);
}
{
std::ostringstream n;
n << cs.first << "_max";
currentGenStats["custom"][n.str()] = std::get<2>(cs.second);
}
}
for (const auto &ind : lastGen) {
indTotalTime += ind.evalTime;
for (const auto &o : ind.fitnesses) {
currentGenStats[o.first].at("avg") +=
(o.second / static_cast<double>(lastGen.size()));
if (isBetter(o.second, currentGenStats[o.first].at("best")))
currentGenStats[o.first].at("best") = o.second;
if (!isBetter(o.second, currentGenStats[o.first].at("worst")))
currentGenStats[o.first].at("worst") = o.second;
}