-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathParallelEvaluator.hpp
1633 lines (1433 loc) · 66.8 KB
/
ParallelEvaluator.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
//
// ParallelEvaluator.hpp
// NSGA-Parallel-Backend
//
// Created by a1091793 on 8/12/2015.
//
//
#ifndef ParallelEvaluator_h
#define ParallelEvaluator_h
#include <ctime>
#include <chrono>
#include <thread>
#include <boost/mpi.hpp>
#include "Evaluation.hpp"
#include <boost/serialization/string.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/utility.hpp>
#include "serialize-tuple-master/serialize_tuple.h"
#include <boost/date_time.hpp>
#include <functional>
#include <queue>
#include <set>
#include <unordered_map>
#include "Selection.hpp"
#include "Crossover.hpp"
#include "Mutation.hpp"
#include <boost/asio.hpp>
//namespace{
//
//inline std::ostream& operator << (std::ostream& os, const std::tuple<int, std::vector<double>, std::vector<int> >& v)
//{
// os << "[";
// for (std::vector<double>::const_iterator ii = std::get<1>(v).begin(); ii != std::get<1>(v).end(); ++ii)
// {
// os << " " << *ii;
// }
// os << "; ";
// for (std::vector<int>::const_iterator ii = std::get<2>(v).begin(); ii != std::get<2>(v).end(); ++ii)
// {
// os << " " << *ii;
// }
// os << " ] : Gen " << std::get<0>(v);
// return os;
//}
//
//inline std::ostream& operator << (std::ostream& os, const std::tuple<std::vector<double>, std::vector<double>, int, std::vector<double>, std::vector<int> >& v)
//{
// os << "(";
// for (std::vector<double>::const_iterator ii = std::get<0>(v).begin(); ii != std::get<0>(v).end(); ++ii)
// {
// os << " " << *ii;
// }
// os << "; ";
// for (std::vector<double>::const_iterator ii = std::get<1>(v).begin(); ii != std::get<1>(v).end(); ++ii)
// {
// os << " " << *ii;
// }
// os << " ) <- ";
//
// os << "[";
// for (std::vector<double>::const_iterator ii = std::get<3>(v).begin(); ii != std::get<3>(v).end(); ++ii)
// {
// os << " " << *ii;
// }
// os << "; ";
// for (std::vector<int>::const_iterator ii = std::get<4>(v).begin(); ii != std::get<4>(v).end(); ++ii)
// {
// os << " " << *ii;
// }
// os << " ] : Gen " << std::get<2>(v);
// return os;
//}
//
//
//
//
//}
struct EvaluatedIndividualDataT
{
typedef ProblemDefinitions::RealDVsT RealDVsT;
typedef ProblemDefinitions::UnorderedDVsT UnorderedDVsT;
typedef ProblemDefinitions::OrderedDVsT OrderedDVsT;
typedef ProblemDefinitions::ObjectivesT ObjectivesT;
typedef ProblemDefinitions::ConstraintsT ConstraintsT;
RealDVsT real_dvs;
UnorderedDVsT unordered_dvs;
OrderedDVsT ordered_dvs;
ObjectivesT objectives;
ConstraintsT constraints;
int gen_number;
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive& ar, const unsigned int version)
{
ar& real_dvs;
ar& unordered_dvs;
ar& ordered_dvs;
ar& objectives;
ar& constraints;
ar& gen_number;
}
std::ostream& operator << (std::ostream& os) const
{
os << "(";
std::for_each(real_dvs.begin(), real_dvs.end(), [&os](double i)->void {os << i << " "; }); os << "; ";
std::for_each(unordered_dvs.begin(), unordered_dvs.end(), [&os](int i)->void {os << i << " "; }); os << "; ";
std::for_each(ordered_dvs.begin(), ordered_dvs.end(), [&os](int i)->void {os << i << " "; });
os << ") -> [";
std::for_each(objectives.begin(), objectives.end(), [&os](double i)->void {os << i << " "; }); os << "; ";
std::for_each(constraints.begin(), constraints.end(), [&os](double i)->void {os << i << " "; });
os << "] : Gen " << gen_number;
return os;
}
void initialise(ProblemDefinitionsSPtr prob_defs)
{
real_dvs = ObjectivesT(prob_defs->minimise_or_maximise.size(), 0.0);
unordered_dvs = ConstraintsT(prob_defs->number_constraints, 0.0);
gen_number = 0;
real_dvs = RealDVsT(prob_defs->real_lowerbounds.size(), 0.0);
unordered_dvs = UnorderedDVsT(prob_defs->unordered_lowerbounds.size(), 0);
ordered_dvs = OrderedDVsT(prob_defs->ordered_lowerbounds.size(), 0);
}
};
struct EvaledJobDataT
{
EvaluatedIndividualDataT individual_dat;
int job_number;
boost::mpi::request request;
};
struct UnevaledIndividualDataT
{
typedef ProblemDefinitions::RealDVsT RealDVsT;
typedef ProblemDefinitions::UnorderedDVsT UnorderedDVsT;
typedef ProblemDefinitions::OrderedDVsT OrderedDVsT;
RealDVsT real_dvs;
UnorderedDVsT unordered_dvs;
OrderedDVsT ordered_dvs;
int gen_number;
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive& ar, const unsigned int version)
{
ar& real_dvs;
ar& unordered_dvs;
ar& ordered_dvs;
ar& gen_number;
}
std::ostream& operator << (std::ostream& os) const
{
os << "(";
std::for_each(real_dvs.begin(), real_dvs.end(), [&os](double i)->void {os << i << " "; }); os << "; ";
std::for_each(unordered_dvs.begin(), unordered_dvs.end(), [&os](int i)->void {os << i << " "; }); os << "; ";
std::for_each(ordered_dvs.begin(), ordered_dvs.end(), [&os](int i)->void {os << i << " "; });
os << ") : Gen " << gen_number;
return os;
}
void initialise(ProblemDefinitionsSPtr prob_defs)
{
gen_number = 0;
real_dvs = RealDVsT(prob_defs->real_lowerbounds.size(), 0.0);
unordered_dvs = UnorderedDVsT(prob_defs->unordered_lowerbounds.size(), 0);
ordered_dvs = OrderedDVsT(prob_defs->ordered_lowerbounds.size(), 0);
}
};
struct GenerationDataT
{
int gen_number;
std::string save_dir;
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive& ar, const unsigned int version)
{
ar& gen_number;
ar& save_dir;
}
std::ostream& operator << (std::ostream& os) const
{
os << "Save -> \"" << save_dir << "\" : Gen " << gen_number;
return os;
}
};
class ParallelEvaluatorBase
{
public:
enum Log{OFF, LVL1, LVL2, LVL3};
protected:
boost::mpi::environment & mpi_env;
boost::mpi::communicator & world;
ProblemDefinitionsSPtr problem_defs;
unsigned int number_processes;
unsigned int number_clients;
// std::pair<std::vector<double>, std::vector<int> > decision_vars;
// std::tuple<std::vector<double>, std::vector<int>, std::vector<int> > decision_vars2;
// std::pair<std::vector<double>, std::vector<double> > objs_and_constraints;
EvaluatedIndividualDataT uneval_ind_dat;
//std::tuple<std::vector<double>, std::vector<double>, unsigned int, std::vector<double>, std::vector<int> > uneval_ind_dat;
UnevaledIndividualDataT eval_ind_dat;
//std::tuple<unsigned int, std::vector<double>, std::vector<int> > eval_ind_dat;
typedef ProblemDefinitions::ObjectivesAndConstraintsT ObjectivesAndConstraintsT;
ObjectivesAndConstraintsT worst_objs_and_constraints;
GenerationDataT save_dir_gen_nmbr;
//std::pair<std::string, unsigned int> save_dir_gen_nmbr;
// boost::mpi::content dv_c;
// boost::mpi::content oc_c;
// boost::mpi::content ocgndv_c;
// boost::mpi::content gndv_c;
unsigned int max_tag;
int do_log;
unsigned int gen_num = 0;
boost::filesystem::path log_directory;
bool delete_previous_logfile = true;
boost::filesystem::path previous_log_file = "";
boost::filesystem::path log_file = "";
// std::ofstream log_stream;
double timeout_time;
const std::string NO_SAVE = "no_save";
const std::string TERMINATE = "terminate";
public:
ParallelEvaluatorBase(boost::mpi::environment & _mpi_env, boost::mpi::communicator & _world, ProblemDefinitionsSPtr _problem_defs)
: mpi_env(_mpi_env),
world(_world),
problem_defs(_problem_defs),
number_processes(world.size()),
number_clients(number_processes - 1),
max_tag(unsigned int(mpi_env.max_tag())),
do_log(this->OFF)
{
worst_objs_and_constraints.first.resize(problem_defs->minimise_or_maximise.size());
for (int i = 0; i < worst_objs_and_constraints.first.size(); ++i)
{
if (problem_defs->minimise_or_maximise.at(i) == ProblemDefinitions::MINIMISATION ) worst_objs_and_constraints.first.at(i) = std::numeric_limits<double>::max();
else worst_objs_and_constraints.first.at(i) = std::numeric_limits<double>::min();
}
worst_objs_and_constraints.second.resize(problem_defs->number_constraints);
BOOST_FOREACH(double & constraint, worst_objs_and_constraints.second)
{
constraint = std::numeric_limits<double>::max();
}
eval_ind_dat.initialise(problem_defs);
uneval_ind_dat.initialise(problem_defs);
}
void
log(boost::filesystem::path _log_directory, int _val = LVL1)
{
this->do_log = _val;
this->log_directory= _log_directory;
}
void
makeLogFile(std::ofstream &logging_file, std::string & base_log_file_name, int _gen_count, std::string subdir_name)
{
std::string file_name = base_log_file_name;
if (_gen_count >= 0) file_name = file_name + "_Gen" + std::to_string(
_gen_count);
file_name = file_name + "_" + boost::asio::ip::host_name() + "_Rank" + std::to_string(world.rank()) + ".log";
log_file = log_directory / subdir_name;
if (!(exists(log_file)))
{
try
{
create_directories(log_file);
// std::cout << "path " << path.first << " did not exist, so created\n";
}
catch(boost::filesystem::filesystem_error& e)
{
std::cout << "Attempted to create " << log_file.string().c_str() << " but was unable\n";
std::cout << e.what() << "\n";
// this->do_log = false;
log_file = log_directory;
}
}
log_file = log_file / file_name;
logging_file.open(log_file.string().c_str(), std::ios_base::out | std::ios_base::app);
if (!logging_file.is_open()) do_log = OFF;
}
void
deletePreviousLog(std::string & base_log_file_name, int _gen_count, std::string subdir_name)
{
std::string file_name = base_log_file_name;
if (_gen_count >= 0) file_name = file_name + "_Gen" + std::to_string(
_gen_count);
file_name = file_name + "_" + boost::asio::ip::host_name() + "_Rank" + std::to_string(world.rank()) + ".log";
previous_log_file = log_directory / subdir_name /file_name ;
if (this->delete_previous_logfile && !this->previous_log_file.empty())
{
if (exists(previous_log_file)) boost::filesystem::remove_all(previous_log_file);
}
}
};
class ParallelEvaluatorClientBase : public ParallelEvaluatorBase
{
public:
ParallelEvaluatorClientBase(boost::mpi::environment & _mpi_env, boost::mpi::communicator & _world, ProblemDefinitionsSPtr _problem_defs)
: ParallelEvaluatorBase(_mpi_env, _world, _problem_defs)
{
// std::cout << "receiving broadcast skeleton" << std::endl;
#ifdef USE_MPI_SKELETONS
//Send skeleton of decision variable to make sending dvs to clients/slaves more efficient
// boost::mpi::broadcast(world, boost::mpi::skeleton(decision_vars),0);
` // boost::mpi::broadcast(world, boost::mpi::skeleton(objs_and_constraints),0);
boost::mpi::broadcast(world, boost::mpi::skeleton(uneval_ind_dat),0);
boost::mpi::broadcast(world, boost::mpi::skeleton(eval_ind_dat),0);
#else
// std::cout << "Getting content for skeleton" << std::endl;
// dv_c = boost::mpi::get_content(decision_vars);
// oc_c = boost::mpi::get_content(objs_and_constraints);
//ocgndv_c = boost::mpi::get_content(uneval_ind_dat);
//gndv_c = boost::mpi::get_content(eval_ind_dat);
#endif //USE_MPI_SKELETONS
// std::cout << "Completed initialisation Client" << std::endl;
}
virtual void operator()()=0;
};
class ParallelEvaluatorServerBase : public ParallelEvaluatorBase, public EvaluatePopulationBase
{
private:
//typedef std::tuple<int, std::vector<double>, std::vector<int> > JobsSentInfo; //first is gen number, then DVs.
typedef std::list<EvaledJobDataT> JobsSentList; //First is mpi_request, 2nd is job number, 3rd is tuple of objs, constraints, gen_num and decision vars
JobsSentList jobs_sending;
const int MAX_JOB_NUM = std::numeric_limits<int>::max()-2;
public:
ParallelEvaluatorServerBase(boost::mpi::environment & _mpi_env, boost::mpi::communicator & _world, ProblemDefinitionsSPtr _problem_defs, double _timeout_time = 1800)
: ParallelEvaluatorBase(_mpi_env, _world, _problem_defs)
{
this->timeout_time = _timeout_time;
//Send skeleton of decision variable to make sending dvs to clients/slaves more efficient
//Send skeleton of decision variable to make sending dvs to clients/slaves more efficient
// std::cout << "Real DVs: " << problem_defs->real_lowerbounds.size() << std::endl;
// std::cout << "Int DVs: " << problem_defs->int_lowerbounds.size() << std::endl;
// std::cout << "Objs: " << problem_defs->minimise_or_maximise.size() << std::endl;
// std::cout << "Constraints: " << problem_defs->number_constraints << std::endl;
// std::get<0>(decision_vars
// decision_vars = std::pair<std::vector<double>, std::vector<int> >
// ( std::piecewise_construct,
// std::forward_as_tuple(std::vector<double>(problem_defs->real_lowerbounds.size(), 0.0)),
// std::forward_as_tuple(std::vector<int>(problem_defs->int_lowerbounds.size(), 0))
// );
//
// objs_and_constraints = std::pair<std::vector<double>, std::vector<double> >
// ( std::piecewise_construct,
// std::forward_as_tuple(std::vector<double>(problem_defs->minimise_or_maximise.size(), 0.0)),
// std::forward_as_tuple(std::vector<double>(problem_defs->number_constraints, 0.0))
// );
// std::cout << "Broadcasting skeleton" << std::endl;
#ifdef USE_MPI_SKELETONS
// boost::mpi::broadcast(world, boost::mpi::skeleton(decision_vars),0);
// boost::mpi::broadcast(world, boost::mpi::skeleton(objs_and_constraints),0);
boost::mpi::broadcast(world, boost::mpi::skeleton(uneval_ind_dat),0);
boost::mpi::broadcast(world, boost::mpi::skeleton(eval_ind_dat),0);
#else
// std::cout << "Getting content for skeleton" << std::endl;
//dv_c = boost::mpi::get_content(decision_vars);
// oc_c = boost::mpi::get_content(objs_and_constraints);
//ocgndv_c = boost::mpi::get_content(uneval_ind_dat);
//gndv_c = boost::mpi::get_content(eval_ind_dat);
#endif // USE_MPI_SKELETONS
// std::cout << "Completed initialisation Server" << std::endl;
}
void
terminate()
{
std::string base_log_file_name = "ParallelEvaluatePopServer_Termination";
std::string log_subdir = "ParallelEvaluateServerLogs";
std::ofstream logging_file;
if (this->do_log)
{
makeLogFile(logging_file, base_log_file_name, -1, log_subdir);
}
// Send signal to slaves to indicate shutdown.
// std::cout << "In destructor" << std::endl;
std::vector<boost::mpi::request> term_msg_rqsts;
for (unsigned int i = 1; i <= number_clients; ++i)
{
if (this->do_log > this->OFF) logging_file << world.rank() << ": " << boost::posix_time::second_clock::local_time() << " sending terminate to " << i << std::endl;
term_msg_rqsts.push_back(world.isend(i, max_tag, TERMINATE));
}
boost::mpi::wait_all(term_msg_rqsts.begin(), term_msg_rqsts.end());
deleteAllJobs(logging_file);
if (this->do_log > this->OFF)
{
if (logging_file.is_open()) logging_file.close();
}
}
void
sendJob(unsigned int _gen_num, const std::vector<double> & real_dvs, const std::vector<int>& int_dvs, unsigned int & job_num, int client_id, std::ofstream & logging_file)
{
job_num += 1;
std::get<0>(eval_ind_dat) = _gen_num;
std::get<1>(eval_ind_dat) = real_dvs;
std::get<2>(eval_ind_dat) = int_dvs;
if (this->do_log > this->OFF) logging_file << world.rank() << ": " << boost::posix_time::second_clock::local_time() << " sending to " << client_id << " individual/job num " << job_num << " with " << real_dvs.size() << ", " << int_dvs.size() << " DVS: " << eval_ind_dat << std::endl;
boost::mpi::request rq;
jobs_sending.push_front(std::make_tuple(rq, job_num, eval_ind_dat));
std::tuple<boost::mpi::request, int, JobsSentInfo> & job = jobs_sending.front();
#ifdef USE_MPI_SKELETONS
std::get<0>(job) = world.isend(client_id, std::get<1>(job), boost::mpi::get_content(std::get<2>(job)));
#else
std::get<0>(job) = world.isend(client_id, std::get<1>(job), std::get<2>(job));
#endif // USE_MPI_SKELETONS
if (job_num > max_tag - 3) job_num = 0;
}
void
checkJobsSent(std::ofstream & logging_file)
{
// Test sends back, and remove those completed.
boost::optional<boost::mpi::status> os;
do{
os = boost::optional<boost::mpi::status>();
if (!jobs_sending.empty())
{
std::tuple<boost::mpi::request, int, JobsSentInfo> & job_sending = jobs_sending.back();
os = std::get<0>(job_sending).test();
if (os)
{
if (this->do_log > this->OFF)
logging_file << world.rank() << ": " << boost::posix_time::second_clock::local_time()
<< " individual/job number " << std::get<1>(job_sending) << " now sent" << std::endl;
jobs_sending.pop_back();
}
}
} while (os);
}
void
deleteOldJobs(std::ofstream & logging_file, int old_gen_number)
{
// Test sends back, and remove those completed.
boost::optional<boost::mpi::status> os;
bool do_continue = false;
do{
do_continue = false;
if (!jobs_sending.empty())
{
std::tuple<boost::mpi::request, int, JobsSentInfo> & job_sending = jobs_sending.back();
os = std::get<0>(job_sending).test();
if (os)
{
if (this->do_log > this->OFF)
logging_file << world.rank() << ": " << boost::posix_time::second_clock::local_time()
<< " individual/job number " << std::get<1>(job_sending) << "now sent" << std::endl;
jobs_sending.pop_back();
do_continue = true;
}
else
{
if (std::get<0>(std::get<2>(job_sending)) < old_gen_number)
{
if (this->do_log > this->OFF) logging_file << world.rank() << " " << boost::posix_time::second_clock::local_time() << ": Cancelling job " << std::get<1>(job_sending) << " from generation " << std::get<0>(std::get<2>(job_sending)) << ". Job is too old." << std::endl;
std::get<0>(job_sending).cancel();
jobs_sending.pop_back();
do_continue = true;
}
}
}
} while (do_continue);
}
void
deleteAllJobs(std::ofstream & logging_file)
{
if (this->do_log > this->OFF) logging_file << world.rank() << " " << boost::posix_time::second_clock::local_time() << ": Clearing previously sent jobs" << std::endl;
for(std::tuple<boost::mpi::request, int, JobsSentInfo> & job: jobs_sending)
{
// Failed jobs.
boost::optional<boost::mpi::status> oss = std::get<0>(job).test();
if (!oss)
{
std::get<0>(job).cancel();
}
else
{
if (this->do_log > this->OFF)
logging_file << world.rank() << ": " << boost::posix_time::second_clock::local_time()
<< " individual/job number " << std::get<1>(job) << "now sent" << std::endl;
}
}
jobs_sending.clear();
}
boost::optional<boost::mpi::status>
waitForJobToFinish(std::ofstream & logging_file, int job_id = boost::mpi::any_tag)
{
//start a receive request, non-blocking
#ifdef USE_MPI_SKELETONS
boost::mpi::request r = world.irecv(boost::mpi::any_source, job_id, boost::mpi::get_content(uneval_ind_dat));
#else
boost::mpi::request r = world.irecv(boost::mpi::any_source, job_id, uneval_ind_dat);
#endif
//get start time
std::time_t start_time, end_time;
std::time(&start_time);
double elapsed_time = 0;
boost::optional<boost::mpi::status> osr;
// test if we have made a receive.
do
{
std::time(&end_time);
elapsed_time = std::difftime(end_time, start_time);
osr = r.test();
}
while(!osr && elapsed_time < this->timeout_time);
//By now we either have received the data, or taken too long, so...
if (!osr)
{
//we must have timed out
if (this->do_log > this->OFF) logging_file << world.rank() << " " << boost::posix_time::second_clock::local_time() << ": Cancelling job " << job_id << " after waiting " << elapsed_time << " seconds." << std::endl;
r.cancel();
}
return osr;
}
void
evalAndSavePopImpl(PopulationSPtr population, const boost::filesystem::path & save_dir, unsigned int _gen_num)
{
std::ofstream logging_file;
std::string base_log_file_name = "ParallelEvaluatePopServer_EvalSave";
std::string log_subdir = "ParallelEvaluateServerLogs";
if (this->do_log)
{
makeLogFile(logging_file, base_log_file_name, _gen_num, log_subdir);
}
if (this->do_log > this->OFF) logging_file << world.rank() << " " << boost::posix_time::second_clock::local_time() << ": Eval (and save) population" << std::endl;
save_dir_gen_nmbr.first = save_dir.string();
save_dir_gen_nmbr.second = _gen_num;
std::vector<boost::mpi::request> save_dir_msg_rqsts;
for (unsigned int i = 1; i <= number_clients; ++i)
{
if (this->do_log > this->OFF) logging_file << world.rank() << ": " << boost::posix_time::second_clock::local_time() << " sending to " << i << " save directory: " << save_dir << " and generational number: " << _gen_num << std::endl;
save_dir_msg_rqsts.push_back(world.isend(i, max_tag, save_dir_gen_nmbr));
}
if (this->do_log > this->OFF) logging_file << "First defaulting obj and constraints of all population members to worse case values" << std::endl;
for (IndividualSPtr ind: *population)
{
ind->setObjectives(this->worst_objs_and_constraints.first);
ind->setConstraints(this->worst_objs_and_constraints.second);
}
if (this->do_log > this->OFF) logging_file << "Evaluating population with size: " << population->size() << std::endl;
//Sanity check - that we can represent each individual by an mpi tag.
if (population->populationSize() > (max_tag -1))
{
if (this->do_log > this->OFF) logging_file << "problem: max tag too small, population too large for mpi" << std::endl;
}
deleteAllJobs(logging_file);
unsigned int individual = 0;
// std::vector<boost::mpi::request> reqs_out(number_clients);
unsigned int num_initial_jobs = number_clients;
if (num_initial_jobs > population->populationSize()) num_initial_jobs = unsigned int(population->populationSize());
for (; individual < num_initial_jobs; )
{
// sendJob increments 'indivudal'
int client_id = individual + 1;
sendJob(_gen_num, (*population)[individual]->getRealDVVector(), (*population)[individual]->getUnorderedDVVector(), individual, client_id, logging_file);
}
//Check messages have all been sent
boost::mpi::wait_all(save_dir_msg_rqsts.begin(), save_dir_msg_rqsts.end());
save_dir_msg_rqsts.clear();
checkJobsSent(logging_file);
int results_received = 0;
while (individual < population->populationSize())
{
//start a receive request, non-blocking
#ifdef USE_MPI_SKELETONS
boost::mpi::request r_results = world.irecv(boost::mpi::any_source, boost::mpi::any_tag, boost::mpi::get_content(uneval_ind_dat));
#else
boost::mpi::request r_results = world.irecv(boost::mpi::any_source, boost::mpi::any_tag, uneval_ind_dat);
#endif // USE_MPI_SKELETONS
boost::mpi::status s_results = r_results.wait();
int client_id = s_results.source();
if (this->do_log > this->OFF) logging_file << world.rank() << ": " << boost::posix_time::second_clock::local_time() << " received from " << client_id << " individual/job number " << s_results.tag() << " with " << uneval_ind_dat << std::endl;
// Send out new job.
sendJob(_gen_num, (*population)[individual]->getRealDVVector(), (*population)[individual]->getUnorderedDVVector(), individual, client_id, logging_file);
//Process received job
if (s_results.tag() < population->size())
{
if ( ((*population)[s_results.tag() - 1]->getRealDVVector() == std::get<3>(uneval_ind_dat))
&& ((*population)[s_results.tag() - 1]->getUnorderedDVVector() == std::get<4>(uneval_ind_dat)) )
// we -1 in pop index as vectors are indexed from 0, while the tag is the ind. number indexed from 1.
{
(*population)[s_results.tag() - 1]->setObjectives(std::get<0>(uneval_ind_dat));
(*population)[s_results.tag() - 1]->setConstraints(std::get<1>(uneval_ind_dat));
results_received += 1;
}
}
// sendJob increments 'indivudal'
// ++individual;
checkJobsSent(logging_file);
}
//Try and get a receive from remaining jobs still running
boost::optional<boost::mpi::status> os;
do
{
if (results_received >= population->size()) break;
os = waitForJobToFinish(logging_file);
if (os)
{
boost::mpi::status s_results = os.get();
if (this->do_log > this->OFF) logging_file << world.rank() << ": " << boost::posix_time::second_clock::local_time() << " received from " << s_results.source() << " individual/job number " << s_results.tag() << " with " << uneval_ind_dat << std::endl;
//Process received job
if ( ((*population)[s_results.tag() - 1]->getRealDVVector() == std::get<3>(uneval_ind_dat))
&& ((*population)[s_results.tag() - 1]->getUnorderedDVVector() == std::get<4>(uneval_ind_dat)) )
// we -1 in pop index as vectors are indexed from 0, while the tag is the ind. number indexed from 1.
{
(*population)[s_results.tag()-1]->setObjectives(std::get<0>(uneval_ind_dat));
(*population)[s_results.tag()-1]->setConstraints(std::get<1>(uneval_ind_dat));
results_received += 1;
}
}
} while (os);
for (int j = 0; j < results_received; ++j)
{
//start a receive request, non-blocking
}
deleteAllJobs(logging_file);
if (this->do_log)
{
if (logging_file.is_open()) logging_file.close();
}
if (this->do_log)
{
if (_gen_num>3) deletePreviousLog(base_log_file_name, _gen_num-3, log_subdir);
}
}
};
class ParallelEvaluatePopServerNonBlocking : public ParallelEvaluatorServerBase
{
public:
ParallelEvaluatePopServerNonBlocking(boost::mpi::environment & _mpi_env, boost::mpi::communicator & _world, ProblemDefinitionsSPtr _problem_defs, double _timeout_time = 1800)
: ParallelEvaluatorServerBase(_mpi_env, _world, _problem_defs)
{
}
~ParallelEvaluatePopServerNonBlocking()
{
terminate();
}
void
evalPop(PopulationSPtr population, boost::filesystem::path save_dir)
{
++gen_num;
evalAndSavePopImpl(population, save_dir, gen_num);
}
void
operator()(PopulationSPtr population)
{
this->evalPop(population, NO_SAVE);
}
void
operator()(PopulationSPtr population, const boost::filesystem::path & save_dir)
{
this->evalPop(population, save_dir);
}
};
template <typename RNG_PE = std::mt19937>
class ParallelEvaluatePopServerNonBlockingContinuousEvolution : public ParallelEvaluatorServerBase
{
private:
std::queue<IndividualSPtr> jobs;
// std::unordered_map<int, std::pair<boost::mpi::request, IndividualSPtr> > jobs_running;
const int CLIENT_QUEUE_SIZE = 2;
// const bool addOffspring2Selection = true;
bool add_offspring_2_mating_pool = true;
int generational_reproduction_size;
TournamentSelectionContinuousEvolution<RNG_PE> & selection;
CombinedRealIntCrossover<RNG_PE> & crossover;
CombinedRealIntMutation<RNG_PE> & mutation;
unsigned int job_num = 0;
// int gen_num = 0;
// int breed_and_eval_count = 0;
// int eval_and_save_count = 0;
public:
ParallelEvaluatePopServerNonBlockingContinuousEvolution(boost::mpi::environment & _mpi_env,
boost::mpi::communicator & _world,
ProblemDefinitionsSPtr _problem_defs,
TournamentSelectionContinuousEvolution<RNG_PE> & _selection,
CombinedRealIntCrossover<RNG_PE> & _crossover,
CombinedRealIntMutation<RNG_PE> & _mutation,
double _timeout_time = 1800)
: ParallelEvaluatorServerBase(_mpi_env, _world, _problem_defs), selection(_selection), crossover(_crossover), mutation(_mutation)
{
}
~ParallelEvaluatePopServerNonBlockingContinuousEvolution()
{
terminate();
}
void
makeJobsApplyEAOperators(int num_jobs_made)
{
PopulationSPtr sub_pop = selection(num_jobs_made);
// std::cout << "Sub pop for selection" << std::endl;
// std::cout << sub_pop << std::endl;
crossover(sub_pop);
mutation(sub_pop);
for(IndividualSPtr ind: *sub_pop)
{
jobs.push(ind);
}
}
PopulationSPtr
breedAndEvalPop(PopulationSPtr population)
{
return(breedAndEvalPop(population, NO_SAVE));
}
PopulationSPtr
breedAndEvalPop(PopulationSPtr population, const boost::filesystem::path & save_dir)
{
std::string base_log_file_name = "ParallelEvaluatePopServer_BreedEval";
std::string log_subdir = "ParallelEvaluateServerLogs";
std::ofstream logging_file;
// breed_and_eval_count += 1;
gen_num += 1;
if (this->do_log)
{
makeLogFile(logging_file, base_log_file_name, gen_num, log_subdir);
}
if (this->do_log > this->OFF) logging_file << world.rank() << " " << boost::posix_time::second_clock::local_time() << ": Breed (and eval) population" << std::endl;
// std::cout << "Broadcasting skeleton" << std::endl;
// std::cout << "Real DVs: " << population->front()->numberOfRealDecisionVariables() << std::endl;
// std::cout << "Int DVs: " << problem_defs->int_lowerbounds.size() << std::endl;
// std::cout << "Objs: " << problem_defs->minimise_or_maximise.size() << std::endl;
// std::cout << "Constraints: " << problem_defs->number_constraints << std::endl;
generational_reproduction_size = population->size();
selection.resetBreedingPop(population);
PopulationSPtr offspring(new Population);
save_dir_gen_nmbr.first = save_dir.string();
save_dir_gen_nmbr.second = gen_num;
std::vector<boost::mpi::request> save_dir_msg_rqsts;
for (int i = 1; i <= number_clients; ++i)
{
if (this->do_log > this->OFF) logging_file << world.rank() << ": " << boost::posix_time::second_clock::local_time() << " sending to " << i << " save directory: " << save_dir << " and generational number: " << gen_num << std::endl;
save_dir_msg_rqsts.push_back(world.isend(i, max_tag, save_dir_gen_nmbr));
}
// boost::mpi::broadcast(world, save_dir_s,0);
if (this->do_log > this->OFF) logging_file << "Start of evolution and evaluation for generation " << gen_num << std::endl;
// typedef std::pair<const int, boost::mpi::request> JobRunningT;
// std::map<int, boost::mpi::request> jobs_running;
for (int j = 0; j < CLIENT_QUEUE_SIZE; ++j)
{
for (unsigned int k = 0; k < number_clients; ++k)
{
if (jobs.size() == 0) makeJobsApplyEAOperators(2);
int client_id = k + 1;
sendJob(gen_num, jobs.front()->getRealDVVector(), jobs.front()->getUnorderedDVVector(), job_num, client_id, logging_file);
jobs.pop();
}
}
boost::mpi::wait_all(save_dir_msg_rqsts.begin(), save_dir_msg_rqsts.end());
save_dir_msg_rqsts.clear();
//Check jobs sent.
checkJobsSent(logging_file);
//
int results_received = 0;
while (results_received < generational_reproduction_size)
{
//start a receive request, non-blocking
#ifdef USE_MPI_SKELETONS
boost::mpi::request r_results = world.irecv(boost::mpi::any_source, boost::mpi::any_tag, boost::mpi::get_content(uneval_ind_dat));
#else
boost::mpi::request r_results = world.irecv(boost::mpi::any_source, boost::mpi::any_tag, uneval_ind_dat);
#endif // USE_MPI_SKELETONS
boost::mpi::status s_results = r_results.wait();
int client_id = s_results.source();
if (this->do_log > this->OFF) logging_file << world.rank() << ": " << boost::posix_time::second_clock::local_time() << " received from " << client_id << " individual/job number " << s_results.tag() << " with " << uneval_ind_dat << std::endl;
// Send out new job.
if (jobs.size() == 0) makeJobsApplyEAOperators(2);
sendJob(gen_num, jobs.front()->getRealDVVector(), jobs.front()->getUnorderedDVVector(), job_num, client_id, logging_file);
jobs.pop();
//process results
IndividualSPtr ind(new Individual(this->problem_defs));
ind->setRealDVs(std::get<3>(uneval_ind_dat));
ind->setUnorderedDVs(std::get<4>(uneval_ind_dat));
ind->setObjectives(std::get<0>(uneval_ind_dat));
ind->setConstraints(std::get<1>(uneval_ind_dat));
offspring->push_back(ind);
if (add_offspring_2_mating_pool) selection.add2BreedingPop(ind);
++results_received;
//Check jobs sent.
checkJobsSent(logging_file);
}
deleteOldJobs(logging_file, gen_num - 2);
if (this->do_log)
{
if (logging_file.is_open()) logging_file.close();
}
if (this->do_log)
{
if (gen_num>3) deletePreviousLog(base_log_file_name, gen_num-3, log_subdir);
}
return(offspring);
}
void
evalPop(PopulationSPtr population)
{
evalAndSavePop(population, NO_SAVE);
}
void
evalAndSavePop(PopulationSPtr population, const boost::filesystem::path & save_dir)
{
evalAndSavePopImpl(population, save_dir, -1);
}
void
operator()(PopulationSPtr population)
{
evalAndSavePop(population, NO_SAVE);
}
void
operator()(PopulationSPtr population, const boost::filesystem::path & save_dir)
{
evalAndSavePop(population, save_dir);
}
};
class ParallelEvaluatePopClientNonBlocking : public ParallelEvaluatorClientBase
{
ObjectivesAndConstraintsBase & eval;
// std::queue< std::tuple< int, int, std::pair<std::vector<double>, std::vector<int> > > > jobs;
struct Jobs2DoCompare {
typedef std::pair< int, std::tuple<int, std::vector<double>, std::vector<int> > > JobInfo;
bool operator() (const JobInfo& x, const JobInfo& y) const
{
return (std::get<0>(x.second)) > (std::get<0>(y.second));
}
typedef std::tuple< int, int, std::tuple<int, std::vector<double>, std::vector<int> > > first_argument_type;
typedef std::tuple< int, int, std::tuple<int, std::vector<double>, std::vector<int> > > second_argument_type;
typedef bool result_type;
};
Jobs2DoCompare jobs_sort;
typedef std::pair< int, std::tuple<int, std::vector<double>, std::vector<int> > > Job2DoInfo; //First is job number, third tuple of gen number then decision variables
typedef std::multiset< Job2DoInfo, Jobs2DoCompare > Jobs2DoMultiSet;
Jobs2DoMultiSet jobs_2_do;
typedef std::tuple<std::vector<double>, std::vector<double>, int, std::vector<double>, std::vector<int> > JobsDoneInfo;
typedef std::list<std::tuple<boost::mpi::request, int, JobsDoneInfo> > JobsDoneList; //First is mpi_request, 2nd is job number, 3rd is tuple of objs, constraints, gen_num and decision vars
JobsDoneList jobs_done;
const int MAX_JOBS_ON_QUEUE = 20;
const int DELAY_REPEAT_PROBE = 1;
// int gen_number;
public:
ParallelEvaluatePopClientNonBlocking(boost::mpi::environment & _mpi_env, boost::mpi::communicator & _world, ProblemDefinitionsSPtr _problem_defs, ObjectivesAndConstraintsBase & _eval)
: ParallelEvaluatorClientBase(_mpi_env, _world, _problem_defs), eval(_eval), jobs_2_do(jobs_sort)
{
}
void
operator()()
{
std::ofstream logging_file;
std::string log_file_base_name = "ParallelEvaluatePopClientNonBlocking";
std::string log_subdir_name = "ParallelEvaluateClientLogs";