-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLocalSearchManager.cpp
80 lines (65 loc) · 2.42 KB
/
LocalSearchManager.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
//
// Created by Gianluca on 24/05/2019.
//
#include "LocalSearchManager.h"
#include <iostream>
#include <algorithm>
#include "Utils.h"
#include "Genetic.h"
#include "ProcessManager.h"
#include "Solution.h"
LocalSearchManager::LocalSearchManager(std::shared_ptr<Solution> sol, Genetic &gen, std::mt19937 &randomGen) :
ProcessManager(sol, gen),
randomGen_(randomGen){}
LocalSearchManager::~LocalSearchManager() {
//std::cout << "destroying LocalSearchManager" << std::endl;
}
void LocalSearchManager::operator()(int id) {
setFolderName(id);
auto solTemp = std::make_shared<Solution>(solution_->getObjectiveFunction(), solution_->getArray(), solution_->isFeasible());
//first improvement: create random ordered sequence from 0 to 20
//and according to that ordering, change the value of the index in array
//after that, recompute the objf, and if it's an improvement "jump" to that solTemp, and repeat
auto indexes = utils::genIndexedVector(20);
std::pair<double, bool> pair;
try {
createDirectory();
}
catch(...){
return;
}
for(int nRuns=0; nRuns<RUNS; nRuns++){
std::shuffle(indexes.begin(), indexes.end(), randomGen_);
auto fitness = solTemp->getFitness();
for(int i=0; i<ITERATIONS; i++){
//change value
solTemp->flip(indexes[i]);
//analysis..
try {
pair = runAnalysis();
//std::cout << "[" << id << "] analysis completed: " << pair.first << " " << pair.second << std::endl;
}
catch(...){
//std::cout << "[" << id << "] analysis failed" << std::endl;
solTemp->flip(indexes[i]);
continue;
}
if(solTemp->computeFitness(pair.first) < fitness){
solTemp->setObjectiveFunction(pair.first);
solTemp->setFeasible(pair.second);
solTemp->setFitness();
gen_.checkAndSetBestSolution(solTemp);
break;
}
//no improvement, restore index
solTemp->flip(indexes[i]);
}
//if no improvement at all, exit
if(fitness >= solTemp->getFitness())
break;
}
solution_->setFeasible(solTemp->isFeasible());
solution_->setObjectiveFunction(solTemp->getObjectiveFunction());
solution_->setArray(solTemp->getArray());
solution_->setFitness();
}