-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathea_main.cpp
296 lines (228 loc) · 10.3 KB
/
ea_main.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
#include <iostream>
#include <sstream>
#include <fstream>
#include <nlohmann/json.hpp> //external dependency included here
#include <thread>
#include <util/enumutils.h>
#include <fitness/ObjectiveFunction.h>
#include <fitness/BinaryEncodedContinuousObjectiveFunction.h>
#include <problem/discrete/binary/onemax/OneMax.h>
#include <problem/continuous/Rastrigin.h>
#include <problem/continuous/Rosenbrock.h>
#include <problem/continuous/Sphere.h>
#include <problem/continuous/Ackley.h>
#include <statistics/DiversityMeasure.h>
#include <statistics/EntropyDiversity.h>
#include <config/EAConfiguration.h>
#include <base/EvolutionaryAlgorithm.h>
#include <statistics/VarianceDiversity.h>
using json = nlohmann::json;
ENUM(enumObjectiveFunctionType, int, ONEMAX, TRAP, MMDP, LEADING_ONES, TSP, LOP, SPHERE, BIN_SPHERE, ES_ESPHERE, ACKLEY, RASTRIGIN, ROSENBROCK)
std::shared_ptr<ea::ObjectiveFunction> create(std::string &problem, const int & arg1, const double & arg2 ) {
size_t found = problem.find('-', 0);
if (found != std::string::npos)
problem.replace(found, 1, "_");
switch (enumObjectiveFunctionType::_from_string_nocase(problem.c_str())) {
case enumObjectiveFunctionType::ONEMAX:
return std::make_shared <ea::OneMax>(arg1);
case enumObjectiveFunctionType::ACKLEY:
return std::make_shared <ea::Ackley>(arg1, arg2);
case enumObjectiveFunctionType::RASTRIGIN:
return std::make_shared <ea::Rastrigin>(arg1, arg2);
case enumObjectiveFunctionType::ROSENBROCK:
return std::make_shared <ea::Rosenbrock>(arg1, arg2);
case enumObjectiveFunctionType::SPHERE:
return std::make_shared <ea::Sphere>(arg1, arg2);
/*
case enumObjectiveFunctionType::TRAP:
return new DeceptiveTrap(Integer.parseInt(problem.get(1)), Integer.parseInt(problem.get(2)));
case enumObjectiveFunctionType::MMDP:
return new MMDP(Integer.parseInt(problem.get(1)));
case enumObjectiveFunctionType::LEADING-ONES:
return new LeadingOnes(Integer.parseInt(problem.get(1)));
case enumObjectiveFunctionType::TSP:
ATSP atsp = new ATSP(Integer.parseInt(problem.get(1)));
return new TSPObjectiveFunction(atsp);
case enumObjectiveFunctionType::LOP:
LinearOrderingProblem lop = new LinearOrderingProblem(Integer.parseInt(problem.get(1)));
return new LOPObjectiveFunction(lop);
case enumObjectiveFunctionType::BIN-SPHERE:
return new BinaryEncodedContinuousObjectiveFunction(Integer.parseInt(problem.get(3)), new Sphere(Integer.parseInt(problem.get(1)), Double.parseDouble(problem.get(2))));
case enumObjectiveFunctionType::ES-SPHERE:
return new ESObjectiveFunction(new Sphere(Integer.parseInt(problem.get(1)), Double.parseDouble(problem.get(2))));
*/
default:
return nullptr;
}
}
/**
* Creates a diversity measure for a given problem
* @param problem name of the objective function
* @return a diversity measure suited to the objective function indicated
*/
/*
ENUM(enumDiversityMeasureType, int, ONEMAX, TRAP, MMDP, LEADING_ONES, TSP, LOP, SPHERE, BIN_SPHERE, ES_ESPHERE)
std::unique_ptr<ea::DiversityMeasure> createMeasure(std::string& problem) {
size_t found = problem.find('-', 0);
if (found != std::string::npos)
problem.replace(found, 1, "_");
switch (enumDiversityMeasureType::_from_string_nocase(problem.c_str())) {
case enumDiversityMeasureType::ONEMAX:
case enumDiversityMeasureType::TRAP:
case enumDiversityMeasureType::MMDP:
case enumDiversityMeasureType::LEADING_ONES:
case enumDiversityMeasureType::TSP:
case enumDiversityMeasureType::LOP:
case enumDiversityMeasureType::BIN_SPHERE:
return std::make_unique<ea::EntropyDiversity>();
case enumDiversityMeasureType::ES_SPHERE:
case enumDiversityMeasureType::SPHERE:
return std::make_unique<ea::VarianceDiversity>();
default:
return nullptr;
}
}
*/
/*
//MAIN BÁSICO:
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cerr << "ERROR: Configuration filename must be provided\n";
return 1;
}
try {
//lee el json
json j;
std::ifstream ifs(argv[1]);
if (ifs.fail()) {
std::cerr << "ERROR when opening " << argv[1] << "\n";
return 1;
}
else
j = json::parse(ifs);
config::EAConfiguration conf = j.get<config::EAConfiguration>();
std::cout << conf.toString();
int numruns = conf.numruns;
std::vector<std::string> problem = conf.getExtendedConfigurationValue("problem");
std::vector<std::string> rest = conf.getExtendedConfigurationValue("sleep");
long sleepTime = 0;
if (rest.size() > 0)
sleepTime = std::strtol(rest[0].c_str(), nullptr, 0);
ea::EvolutionaryAlgorithm myEA{ conf };
myEA.setObjectiveFunction(create(problem));
myEA.stats.setDiversityMeasure(createMeasure(problem[0]));
for (int i = 0; i < numruns; i++) {
myEA.run();
std::cout << "\nRun " << i << ": " <<
myEA.stats.getTime(i) << "s\t" << myEA.stats.getBest(i).getFitness();
if (sleepTime > 0) {
std::cout << "Sleeping...\n";
std::this_thread::sleep_for(std::chrono::seconds{ sleepTime });
}
}
std::ofstream file("stats.json");
file << myEA.stats.toJSON();
file.close();
}
catch (std::exception& e) { std::cout << e.what(); }
}
*/
//MAIN AVANZADO
struct Experiment {
int maxruns;
std::string problem;
int numvars;
float range;
int numbits;
};
void from_json(const json& j, Experiment & e) {
j.at("numruns").get_to(e.maxruns);
j.at("problem").get_to(e.problem);
j.at("numvars").get_to(e.numvars);
j.at("range").get_to(e.range);
j.at("numbits").get_to(e.numbits);
}
int main(int argc, char* argv[]) {
std::string expName = (argc < 2) ? "experiment.json" : argv[1];
//std::string expName = "experiment.json";
try {
//lee el json
std::ifstream expReader(expName);
if (expReader.fail()) {
std::cerr << "ERROR when opening " << expName << "\n";
return 1;
}
json je = json::parse(expReader);
expReader.close();
Experiment experiment = je.get<Experiment>();
std::cout << /* experiment.toString(); */ je.dump();
std::string configf = (experiment.numbits > 0) ? "bitstring.json" : "numeric.json";
std::ifstream reader(configf);
if (reader.fail()) {
std::cerr << "ERROR when opening " << configf << "\n";
return 1;
}
json jc = json::parse(reader);
reader.close();
config::EAConfiguration conf = jc.get<config::EAConfiguration>();
long seed;
std::ifstream lastseedf("lastseed.txt");
if(lastseedf.fail()){
seed = conf.seed;
}
else {
lastseedf >> seed;
conf.seed = seed + 1; //JES: que pasa con el escannner ¿actualiza el valor del fichero tambien? OJO
}
lastseedf.close();
int numruns = conf.numruns;
std::cout << conf.toString();
ea::EvolutionaryAlgorithm myEA(conf);
auto cf = create(experiment.problem, experiment.numvars, experiment.range);
if (experiment.numbits > 0) {
auto cf_cast = std::dynamic_pointer_cast<ea::ContinuousObjectiveFunction>(cf);
myEA.setObjectiveFunction(std::make_shared<ea::BinaryEncodedContinuousObjectiveFunction>(experiment.numbits, cf_cast));
myEA.stats.setDiversityMeasure(std::make_unique<ea::EntropyDiversity>());
}
else {
myEA.setObjectiveFunction(cf);
myEA.stats.setDiversityMeasure(std::make_unique<ea::VarianceDiversity>());
}
std::cout << "-------------------------------------------------------------------------------------\n";
std::cout << "Running the EA on " << experiment.problem << "(" << experiment.numvars << ", " << experiment.range << ")";
if (experiment.numbits > 0) {
std::cout << " binarized with " << experiment.numbits << " bits per variable\n";
}
else {
std::cout << " on a continuous domain\n";
}
std::cout << "-------------------------------------------------------------------------------------\n";
for (int i = 0; i < numruns; i++) {
myEA.run();
std::cout << "\nRun " << i << ": " <<
myEA.stats.getTime(i) << "s\t" << myEA.stats.getBest(i).getFitness();
}
std::string statsfilename = std::format("{}-{}-{}-stats.json", experiment.problem, experiment.numvars, seed);
std::ofstream file(statsfilename);
file << myEA.stats.toJSON();
file.close();
seed += numruns - 1;
if (seed < experiment.maxruns) {
std::ofstream seedFile("lastseed.txt");
seedFile << seed;
seedFile.close();
}
else {
std::remove("lastseed.txt");
}
}
catch (std::exception& e) { std::cout << e.what(); }
}
// Ejecutar programa: Ctrl + F5 o menú Depurar > Iniciar sin depurar
// Depurar programa: F5 o menú Depurar > Iniciar depuración
// Sugerencias para primeros pasos: 1. Use la ventana del Explorador de soluciones para agregar y administrar archivos
// 2. Use la ventana de Team Explorer para conectar con el control de código fuente
// 3. Use la ventana de salida para ver la salida de compilación y otros mensajes
// 4. Use la ventana Lista de errores para ver los errores
// 5. Vaya a Proyecto > Agregar nuevo elemento para crear nuevos archivos de código, o a Proyecto > Agregar elemento existente para agregar archivos de código existentes al proyecto
// 6. En el futuro, para volver a abrir este proyecto, vaya a Archivo > Abrir > Proyecto y seleccione el archivo .sln