-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGeneticAlgorithm.cpp
More file actions
342 lines (265 loc) · 9.54 KB
/
GeneticAlgorithm.cpp
File metadata and controls
342 lines (265 loc) · 9.54 KB
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
#include "GeneticAlgorithm.h"
using namespace std;
GeneticAlgorithm::GeneticAlgorithm() {
bestWorst[0] = 0;
bestWorst[1] = 1;
bestWorst[2] = 2;
bestWorst[3] = 3;
}
GeneticAlgorithm::~GeneticAlgorithm() {
}
void GeneticAlgorithm::iniciar(){
myfile.open ("cromosomas.txt");
//Crear Poblacion Inicial
vector<Cromosoma> poblacion;
//PROCESO DE INICIALIZACION DE POBLACION
double fitnessLocal;
for(int i=0; i<TAMANO_POBLACION;i++){
//Inicializar poblacion de individuos aleatorios
poblacion.push_back( Cromosoma(LONGITUD, 3) );
b vvvxxxpoblacion.at(i).inicializarPoblacion(LIMITEMINAUTOS, LIMITEMAXAUTOS, LIMITEMINKM, LIMITEMAXKM, LIMITEMINCO2, LIMITEMAXCO2);
//Evaluar los fitness de cada Cromosoma
poblacion.at(i).fitnessCromosoma();
}
//EVALUAR MEJOR Y PEORES DE LA poblacion
//Ordenar el arreglo de MejoresPeores
this->ordernarBestWorst( &poblacion);
//Evaluar el mejor Elemento de la poblacion
this->evaluarMejorPeorPoblacion(&poblacion);
//Mientras no se acabae las iteracciones
int count = 0;
while(count < ITERACIONES){
myfile<< "Iteracion: " << count+1<< " \n";
//creacion de receptores de descendientes
vector<Cromosoma> hijos;
//Seleccionar los dos mejores cromosomas
Cromosoma best1 = poblacion.at(bestWorst[0]);
Cromosoma best2 = poblacion.at(bestWorst[1]);
//Cruzar estos dos mejores cromosomas
hijos = cruzaUniforme(best1, best2);
// cout <<"Padres"<<endl;
// cout <<fixed<< best1.getValorFitness()/1000000 << endl;
// cout <<fixed<< best2.getValorFitness() /1000000<< endl;
//
//
// cout <<"Hijos"<<endl;
// cout <<fixed<< hijos.at(0).getValorFitness() /1000000<< endl;
// cout <<fixed<< hijos.at(1).getValorFitness() /1000000<< endl;
//
//Mutar cada hijo
// cout <<"Hijos normales" << endl;
//
// cout <<fixed << hijos.at(0).getValorFitness()/1000000<<endl;
// cout <<fixed << hijos.at(1).getValorFitness()/1000000;
//
// cout << endl;
mutacion(&hijos.at(0));
mutacion(&hijos.at(1));
//Se inicializan los nuevos valores de fitness
hijos.at(0).fitnessCromosoma();
hijos.at(1).fitnessCromosoma();
// cout <<"Hijos mutados" << endl;
// cout <<fixed << hijos.at(0).getValorFitness()/1000000<<endl;
// cout <<fixed << hijos.at(1).getValorFitness()/1000000;
//
// cout << endl;
//
// cout << "=============================";
// cout << endl << endl;
//
//cout <<"Mutaciones"<<endl;
//cout <<fixed<< mut1.getValorFitness() /1000000<< endl;
//cout <<fixed<< mut2.getValorFitness() /1000000<< endl;
//Obtener los dos peores resultados de la poblacion y compararlo con el resultado de los hijos
Cromosoma worst1 = poblacion.at(bestWorst[3]);
Cromosoma worst2 = poblacion.at(bestWorst[2]);
//cout <<"Peores"<<endl;
//cout <<fixed<< worst1.getValorFitness()/1000000 << endl;
//cout <<fixed<< worst2.getValorFitness() /1000000<< endl;
//Si los hijos son peores que los peores (MAYOR VALOR)se eliminan
if( hijos.at(1).getValorFitness() > worst1.getValorFitness() ){
hijos.erase(hijos.begin() +1);
}
else if( hijos.at(1).getValorFitness() > worst2.getValorFitness() ){
hijos.erase(hijos.begin()+1);
}
if( hijos.at(0).getValorFitness() > worst1.getValorFitness() ){
hijos.erase(hijos.begin());
}
else if( hijos.at(0).getValorFitness() > worst2.getValorFitness() ){
hijos.erase(hijos.begin());
}
//Si sobrevivieorn lso dos hijos, se eliminan los peores y se insertan los hijos
int pocision;
if(hijos.size()==2){
poblacion.at(bestWorst[2]) = hijos.at(0);
poblacion.at(bestWorst[3]) = hijos.at(1);
}
else if(hijos.size()==1){
//El mejor individuo es el menos peor (no el peor peor)
poblacion.at(bestWorst[2]) = hijos.at(0);
}
this->ordernarBestWorst(&poblacion);
this->evaluarMejorPeorPoblacion(&poblacion);
//cout <<"========================="<<endl;
count++;
myfile<<fixed<< "Mejor Cromosoma: " << " FITNESS-> "<< poblacion.at(bestWorst[0]).getValorFitness()/1000000 << " toneladas CO2\n";
myfile<<fixed<< "Peor Cromosoma: " << " FITNESS-> "<< poblacion.at(bestWorst[3]).getValorFitness()/1000000 << " toneladas CO2\n";
}
// cout<<"El mejor de la corrida"<<endl;
myfile<<fixed<< "El mejor de la corrida: " << " FITNESS-> "<< poblacion.at(bestWorst[0]).getValorFitness()/1000000 << " toneladas CO2\n";
poblacion.at(bestWorst[0]).visualizacionCompleta(myfile);
myfile.close();
}
//Imprimir el mejor y el peor cromosomas de la iteracion
//Imprimir el mejor cromosomas de la iteracion
// Pocision Mejor Peor
void GeneticAlgorithm::actualizarPocisionMejorPeor(int pocisionEliminada, int opcionPeor){
if(opcionPeor==3){
if(pocisionEliminada < bestWorst[0])
bestWorst[0]--;
if(pocisionEliminada < bestWorst[1])
bestWorst[1]--;
if(pocisionEliminada < bestWorst[2])
bestWorst[2]--;
}
else if(opcionPeor==2){
if(pocisionEliminada < bestWorst[0])
bestWorst[0]--;
if(pocisionEliminada < bestWorst[1])
bestWorst[1]--;
if(pocisionEliminada < bestWorst[3])
bestWorst[3]--;
}
}
//FUNCIONES DE RANDOM
int GeneticAlgorithm::randBin() {
static thread_local std::mt19937 binarioRand;
std::uniform_int_distribution<int> bin(0,1); // guaranteed unbiased
return bin(binarioRand);
}
int GeneticAlgorithm::randMascara() {
static thread_local std::mt19937 binarioMasc;
std::uniform_int_distribution<int> binM(0,LONGITUD-1); // guaranteed unbiased
return binM(binarioMasc);
}
vector<Cromosoma> GeneticAlgorithm::cruzaUniforme(Cromosoma padre, Cromosoma madre){
//Crear Mascara de CRUZA
int* mascaraCruza = crearMascara();
//Creacion de dos hijos vacios
vector<Cromosoma> hijos;
hijos.push_back( Cromosoma(LONGITUD,3));
hijos.push_back( Cromosoma(LONGITUD,3));
//Seteo de hijos
for(int i=0; i<LONGITUD; i++){
if(mascaraCruza[i] == 1){
hijos.at(0).cambiarElemento(i,padre.obtenerElemento(i,0) ,0);
hijos.at(0).cambiarElemento(i,padre.obtenerElemento(i,1) ,1);
hijos.at(1).cambiarElemento(i,madre.obtenerElemento(i,0) ,0);
hijos.at(1).cambiarElemento(i,madre.obtenerElemento(i,1) ,1);
}
else{
hijos.at(0).cambiarElemento(i,madre.obtenerElemento(i,0) ,0);
hijos.at(0).cambiarElemento(i,madre.obtenerElemento(i,1) ,1);
hijos.at(1).cambiarElemento(i,padre.obtenerElemento(i,0) ,0);
hijos.at(1).cambiarElemento(i,padre.obtenerElemento(i,1) ,1);
}
}
hijos.at(0).fitnessCromosoma();
hijos.at(1).fitnessCromosoma();
return hijos;
}
int* GeneticAlgorithm::crearMascara(){
//Se crea la mascara deacuerdo a la longitud del arreglo
int* mascaraCruza = new int[LONGITUD]();
//Se obtienve el numero de bits activos
int bitActivos = round(LONGITUD*CRUZA);
//Mientras no se haya acompletado la cantida de bits activos
// obtener aleatoriamente un indice del arreglo y convertirlo a 1
//asi hasta obtener el numero de bits activos
while(bitActivos > 0){
int ind = randMascara();
if( mascaraCruza[ind] == 0){
mascaraCruza[ind] = 1;
bitActivos--;
}
}
return mascaraCruza;
}
bool yaCambiado(vector<int> &indexes,int index);
int randMutIndx(int min,int max);
void GeneticAlgorithm::mutacion(Cromosoma *especimen) {
/*
*Mutar binarios
*/
int tamArr = especimen->getTam();
int index = randMutIndx(0,tamArr);
vector<int> indexes;
for(int i =0 ; i < (int) round(MUTACION * LONGITUD); i++){
int index = randMutIndx(0,tamArr);
// if(i != 0){
// while(yaCambiado(indexes,index)){
// index = randMutIndx(0,tamArr);
// }
// }
indexes.push_back(index);
int val = abs(especimen->getBinarioAt(index) - 1);
especimen->cambiaBinario(index,val);
}
}
//Evaluar si el indice obtenido ya se ha cambiado
bool yaCambiado(vector<int> &indexes,int index) {
for (std::vector<int>::iterator it = indexes.begin() ; it != indexes.end(); ++it){
if(index == *it)
return true;
}
return false;
}
//Aleatorios para mutación
int randMutIndx(int min,int max) {
static thread_local std::mt19937 realRand;
std::uniform_int_distribution<int> indx(min,max); // guaranteed unbiased
return indx(realRand);
}
//Ordernar Mejores y Peores
void GeneticAlgorithm::ordernarBestWorst( vector<Cromosoma> *poblacion ){
//ordernar bestWosrt de menor a mayor
int aux = 0;
for(int i=1;i< 4;i++){
for(int j=0;j< (4-i);j++){
if(poblacion->at(bestWorst[j]).getValorFitness() > poblacion->at(bestWorst[j+1]).getValorFitness()){
aux = bestWorst[j];
bestWorst[j] = bestWorst[j+1];
bestWorst[j+1] = aux;
}
}
}
}
//Evaluar si la poblacion tiene
void GeneticAlgorithm::evaluarMejorPeorPoblacion( vector<Cromosoma> *poblacion){
for(int i=4; i< TAMANO_POBLACION; i++){
double inFitness = poblacion->at(i).getValorFitness();
//Si es mejor que el primero de los bestWorst, se vuelve el mejor, el mejor se vuelve el segundo mejor
if(inFitness < poblacion->at(bestWorst[0]).getValorFitness())
{
bestWorst[1] = bestWorst[0];
bestWorst[0] = i;
}
else if(inFitness < poblacion->at(bestWorst[1]).getValorFitness() && inFitness > poblacion->at(bestWorst[0]).getValorFitness() )
bestWorst[1] = i;
else if(inFitness > poblacion->at(bestWorst[3]).getValorFitness())
{
bestWorst[2] = bestWorst[3];
bestWorst[3] = i;
}
else if(inFitness > poblacion->at(bestWorst[2]).getValorFitness() && inFitness < poblacion->at(bestWorst[3]).getValorFitness() )
bestWorst[2] = i;
//
// cout <<fixed<< poblacion->at(bestWorst[0]).getValorFitness()/1000 <<endl;
// cout <<fixed<< poblacion->at(bestWorst[1]).getValorFitness()/1000 <<endl;
// cout <<fixed<< poblacion->at(bestWorst[2]).getValorFitness()/1000 <<endl;
// cout <<fixed<< poblacion->at(bestWorst[3]).getValorFitness()/1000 <<endl;
//
// cout << endl;
}
}