-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenetic.cpp
346 lines (267 loc) · 9.63 KB
/
Genetic.cpp
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
//
// Created by Gianluca on 24/05/2019.
//
#include <memory>
#include <thread>
#include <iostream>
#include <time.h>
#include <sstream>
#include <cmath>
#include <ctime>
#include <chrono>
#include <algorithm>
#include "Genetic.h"
#include "AnalysisManager.h"
#include "IOManager.h"
#include "Utils.h"
Genetic::Genetic(int numPopulation, int nElite, int pressure, char *output_file) {
cpus_ = std::thread::hardware_concurrency();
numPopulation_ = numPopulation;
nElite_ = nElite;
pressure_ = pressure;
output_file_ = output_file;
bestSolution_ = std::make_shared<Solution>();
stop_ = false;
initializeGenerator();
}
Genetic::Genetic(int numPopulation, int nElite, int pressure, char *input_file, char *output_file) {
cpus_ = std::thread::hardware_concurrency();
numPopulation_ = numPopulation;
nElite_ = nElite;
pressure_ = pressure;
output_file_ = output_file;
bestSolution_ = std::make_shared<Solution>();
stop_ = false;
initializeGenerator();
//initialize solutions
try {
population_ = IOManager::readInput(input_file);
}
catch(...){
std::cout << "Error in reading from input file. Continuing with a new run" << std::endl;
population_.clear();
return;
}
for(auto &sol : population_)
checkAndSetBestSolution(sol);
//if population is more than numPopulation, delete the worst solutions
while(population_.size() > numPopulation)
population_.pop_back();
}
Genetic::~Genetic() {
//empty vectors of managers and write population to file
stop_ = true;
processManagers_.clear();
if(!init_) return;
//add best solution if not yet present
auto bestSol = getBestSolution();
auto result = std::find_if(population_.begin(), population_.end(),[bestSol](std::shared_ptr<Solution> sol)
{return Solution::equals(*bestSol, *sol);});
if(result == std::end(population_)){
population_.push_back(bestSol);
}
//sort array
sortPopulation();
//write to output file
try {
std::cout << "Writing to file.." << std::endl;
IOManager::writeOutput(output_file_, population_);
}
catch(...){
std::stringstream ss;
ss << "Error in writing to output file." << std::endl;
ss << "The best solution found so far is:" << std::endl;
ss << population_[0]->to_string() << std::endl;
ss << "Save it!" << std::endl;
std::cout << ss.str();
}
}
void Genetic::init(){
if(population_.size() >= numPopulation_){
init_ = true;
return;
}
auto timenow =
std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::cout << ctime(&timenow) << "Initializing.." << std::endl;
//create random solutions
addRandomSolutions(numPopulation_ - static_cast<int>(population_.size()));
//sort array
sortPopulation();
init_ = true;
timenow =
std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::cout << ctime(&timenow) << "Initial population generated" << std::endl;
std::cout << "Sleeping for 30 sec.." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(30));
}
void Genetic::run() {
if(population_.empty()){
std::cout << "You must call the init() method first!" << std::endl;
return;
}
int numGeneration = 1;
std::vector<std::shared_ptr<Solution>> children;
while(true){
auto timenow =
std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::cout << ctime(&timenow) << "Starting generation " << numGeneration << std::endl;
for(int i=0; i<nElite_; i++)
children.push_back(population_[i]);
for(int i=0; i<numPopulation_ - nElite_; i++){
//tournament selection
auto parent1 = tournamentSelection();
auto parent2 = tournamentSelection();
//combination (crossover, mutation, etc)
auto child = crossover(parent1, parent2);
mutation(child, getMutationRate(parent1, parent2));
//add to children
children.push_back(child);
}
//compute objf
std::cout << "Computing objective function for children" << std::endl;
for(auto child : children)
processManagers_.push_back(std::make_shared<AnalysisManager>(child, *this));
runPool();
//local search
timenow =
std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::cout << ctime(&timenow) << "Starting local search" << std::endl;
for(auto child : children)
processManagers_.push_back(std::make_shared<LocalSearchManager>(child, *this, randomGen_));
runPool();
//new population
population_ = children;
children.clear();
//sort
sortPopulation();
timenow =
std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::cout << ctime(&timenow) << "Generation " << numGeneration++ << " ended" << std::endl;
std::cout << "Best solution until now:" << std::endl;
std::cout << population_[0]->to_string() << std::endl;
std::cout << "Sleeping for 30 sec.." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(30));
}
}
void Genetic::addRandomSolutions(int number) {
//analysis..
for(int i=0; i<number; i++){
auto sol = std::make_shared<Solution>(generateRandomArray());
processManagers_.push_back(std::make_shared<AnalysisManager>(sol, *this));
population_.push_back(sol);
}
runPool();
}
std::array<bool, 20> Genetic::generateRandomArray() {
std::uniform_real_distribution<double> dist;
std::array<bool, 20> array{};
double probability = numColumns_ / 20.0;
for(int i=0; i<20; i++){
array[i] = dist(randomGen_) <= probability;
}
return array;
}
void Genetic::sortPopulation() {
std::sort(population_.begin(), population_.end(),
[](std::shared_ptr<Solution> a,std::shared_ptr<Solution> b)
{return Solution::compare(*a, *b);});
}
void Genetic::runPool(){
int cpus = getDimPool();
int nthreads = std::min(cpus, static_cast<int>(processManagers_.size()));
ctpl::thread_pool pool(nthreads);
for(auto &man : processManagers_){
pool.push(std::ref(*man));
}
//std::cout << "Running threads.." << std::endl;
pool.stop(true);
//std::cout << "Finished" << std::endl;
processManagers_.clear();
}
std::shared_ptr<Solution> Genetic::tournamentSelection() {
auto indexes = utils::genIndexedVector(numPopulation_);
std::shuffle(indexes.begin(), indexes.end(), randomGen_);
int best = -1;
for(int i=0; i<pressure_; i++){
int value = indexes[i];
if(best == -1 || value < best)
best = value;
}
return population_[best];
}
std::shared_ptr<Solution> Genetic::crossover(std::shared_ptr<Solution> p1, std::shared_ptr<Solution> p2) {
auto dist = std::uniform_int_distribution<int>(0,1);
std::array<bool, 20> array{};
for(int i=0; i<20; i++){
if(dist(randomGen_)){
array[i] = p1->getArrayValue(i);
}
else {
array[i] = p2->getArrayValue(i);
}
}
return std::make_shared<Solution>(array);
}
void Genetic::mutation(std::shared_ptr<Solution> child, double mutationRate) {
auto dist = std::uniform_real_distribution<double>(0,1);
for(int i=0; i<20; i++){
if(dist(randomGen_) < mutationRate)
child->flip(i);
}
}
double Genetic::getMutationRate(std::shared_ptr<Solution> p1, std::shared_ptr<Solution> p2) {
int equalGenes = 0;
int totalGenes = 0;
for(int i=0; i<20; i++){
if(p1->getArrayValue(i) && p2->getArrayValue(i))
equalGenes++;
if(p1->getArrayValue(i) || p2->getArrayValue(i))
totalGenes++;
}
double similarity = ((double) equalGenes) / totalGenes;
//std::cout << "EqualGenes: " << equalGenes << std::endl;
//std::cout << "TotalGenes: " << totalGenes << std::endl;
//std::cout << "Similarity: " << similarity << std::endl;
return similarity * 0.80; //TODO vedere questo valore
}
/*
void Genetic::test() {
//test tournament selection
auto par1 = tournamentSelection();
auto par2 = tournamentSelection();
std::cout << "Extracted:" << std::endl;
std::cout << par1->to_string() << std::endl;
std::cout << par2->to_string() << std::endl;
auto child = crossover(par1, par2);
std::cout << "Child:" << std::endl;
std::cout << child->to_string() << std::endl;
auto mRate = getMutationRate(par1, par2);
std::cout << "Mutation rate: " << mRate << std::endl;
mutation(child, mRate);
std::cout << "Child mutated:" << std::endl;
std::cout << child->to_string() << std::endl;
}
*/
void Genetic::initializeGenerator(){
randomGen_ = std::mt19937(static_cast<unsigned int>(time(nullptr)));
}
void Genetic::checkAndSetBestSolution(std::shared_ptr<Solution> sol) {
std::lock_guard<std::mutex> guard(mutex_);
if(sol->isFeasible() && Solution::compare(*sol, *bestSolution_)) {
bestSolution_ = std::make_shared<Solution>(sol->getObjectiveFunction(),sol->getArray(), sol->isFeasible());
std::cout << "New best solution!" << std::endl;
std::cout << bestSolution_->to_string() << std::endl;
}
}
std::shared_ptr<Solution> Genetic::getBestSolution() {
std::lock_guard<std::mutex> guard(mutex_);
return bestSolution_;
}
int Genetic::getDimPool() {
if(cpus_ > 10){
//sono sul server
return 75;
}
return cpus_ - 2 <= 0 ? 1 : cpus_ - 2;
}