-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathJCell.java
More file actions
executable file
·494 lines (382 loc) · 17.7 KB
/
Copy pathJCell.java
File metadata and controls
executable file
·494 lines (382 loc) · 17.7 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
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
/**
* @author Bernabe Dorronsoro
*
* Description
* This file contains the main process for running JCell
* It requires a configuration file. Some examples are
* given in cfg directory.
*
* For more information:
* https://gforge.uni.lu
* http://neo.lcc.uma.es/Software/JCell/index.htm
*
*/
import gui.CGADisplay;
import jcell.*;
import MO.*;
import adaptiveCGA.*;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Date;
import ExceptionHandlers.*;
public class JCell implements GenerationListener
{
// Default population shape
static int x = 10;
static int y = 10;
static int longitCrom ;
static int numberOfFuncts ;
// Default maximum number of function evaluations
static int evaluationsLimit = 30000;
protected static boolean showDisplay = false;
protected double lastRatio = -1.0;
protected boolean verbose = true;
private static EvolutionaryAlg ea;
private static FileWriter fstream;
private static BufferedWriter out;
public static void main (String args[]) throws Exception
{
int nVehicles = 0;
/*Utilizar este c—digo comentado (tem de ser adaptado ˆ inclus‹o do TOP_TW no JCell) caso seja passado o nœmero de muta›es a realizar por cromossoma por par‰metro */
/* if (args.length != 5)
{
System.out.println("Error. Try java JCell <ConfigFile> <DataFile> <GenerationLimit> <TestFlag> <mutationsPerChromosome>");
System.exit(-1);
}
*/
if (args.length != 4 && args.length != 5)
{
System.out.println("Error. Try:");
System.out.println("1: java JCell <ConfigFile> <DataFile> <GenerationLimit> <TestFlag>");
System.out.println("2: java JCell <ConfigFile> <DataFile> <GenerationLimit> <TestFlag> <nVehicles> (TOP-TW)");
System.exit(-1);
}
//Random r = new Random(3816L); // seed for the random number generator
Random r = new Random(); // seed for the random number generator
long inicio, fin; // starting and ending time
JCell sel = new JCell();
if(args.length == 5)
nVehicles = Integer.parseInt(args[4]);
ReadConf conf = new ReadConf(args[0], args[1], nVehicles, r);
ea = conf.getParameters(args[1], Integer.parseInt(args[2]));
Problem prob = (Problem)ea.getParam(CellularGA.PARAM_PROBLEM);
// se se tratar de uma execu‹o de teste
if( Boolean.parseBoolean((args[3])) ) // activar a flag respetiva
prob.setTesting(Boolean.parseBoolean((args[3])));
else // se n‹o se tratar de uma execu‹o de teste
System.out.println(prob.toString());
/*Utilizar este c—digo comentado caso seja passado o nœmero de muta›es a realizar por cromossoma por par‰metro */
// definir o nœmero de muta›es a realizar por cromossoma, caso esse valor seja passado
// ea.setParam(CellularGA.PARAM_MUTATIONS_PER_CHROMOSOME, Integer.parseInt(args[4]));
Population popAux = (Population) ea.getParam(CellularGA.PARAM_POPULATION);
if(conf.getProperties().getProperty("Algorithm").equalsIgnoreCase("generational") && conf.getProportion()!=0)
popAux.setPopSize( (int) (prob.getVariables()*conf.getProportion()) );
else
if(conf.getProperties().getProperty("Algorithm").equalsIgnoreCase("cellular") && conf.getProportion()!=0) {
int aux;
if(conf.getModeFlag()) { // se a popula‹o estiver no formato sqrt(V)
aux = (int) Math.round( (Math.sqrt(prob.getVariables() * conf.getProportion())) );
((PopGrid)popAux).setDimension(aux, aux);
popAux.setPopSize(aux*aux);
}
else {
aux = (int) Math.round(prob.getVariables() * conf.getProportion());
((PopGrid)popAux).setDimension(((PopGrid)popAux).getDimX(), aux);
popAux.setPopSize(((PopGrid)popAux).getDimX() * aux);
}
((FixedRandomSweep)ea.getParam(CellularGA.PARAM_CELL_UPDATE)).setPermutationIndividual(popAux.getPopSize());
}
// Set the Individual
String indiv = conf.getProperties().getProperty("Individual");
if (indiv == null)
throw new MissedPropertyException("Individual");
Class c = Class.forName(indiv);
Individual individual = null; // The individual is initialized here.
individual = (Individual) c.newInstance();
individual.setMinMaxAlleleValue(true, prob.getMinAllowedValues());
individual.setMinMaxAlleleValue(false, prob.getMaxAllowedValues());
individual.setLength(prob.getVariables());
individual.setNumberOfFuncts(prob.numberOfObjectives());
popAux.setTopPop(individual, prob.getVariables()); // initialization of the initial population
ea.setParam(CellularGA.PARAM_POPULATION, popAux);
longitCrom = prob.getVariables();
numberOfFuncts = prob.numberOfObjectives();
ea.setParam(CellularGA.PARAM_LISTENER, sel);
ea.setParam(CellularGA.PARAM_FEEDBACK, new Integer(4));
int displaySteps = ((Integer)ea.getParam(CellularGA.PARAM_DISPLAY_STEPS)).intValue();
showDisplay = (ea.getParam(CellularGA.PARAM_DISPLAY) != null);
if(((Boolean)ea.getParam(CellularGA.PARAM_VERBOSE)).booleanValue()) {
// inicializar as vari‡veis para a escrita em ficheiro
try{
// Create file
fstream = new FileWriter("cromossomas.txt");
out = new BufferedWriter(fstream);
}
catch (Exception e) { //Catch exception if any
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
inicio = (new Date()).getTime();
// generation cycles are performed in the next method
ea.experiment();
if(((Boolean)ea.getParam(CellularGA.PARAM_VERBOSE)).booleanValue()) {
try{
fstream.close();
out.close();
}
catch (Exception e) { //Catch exception if any
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
fin = (new Date()).getTime();
// output best solution
if (showDisplay && (((Integer)ea.getParam(CellularGA.PARAM_GENERATION_NUMBER)).intValue()%displaySteps==0)) {
CGADisplay display1 = (CGADisplay) ea.getParam(CellularGA.PARAM_DISPLAY);
CGADisplay display2 = (CGADisplay) ea.getParam(CellularGA.PARAM_DISPLAY2);
if (ea.getParam(CellularGA.PARAM_DISPLAY) != null)
display1.step();
if (ea.getParam(CellularGA.PARAM_DISPLAY2) != null)
display2.step();
}
//last step
/*xfig SNAPSHOT
PopGrid tmppop = (PopGrid) cea.getPopulation();
for (int i = 0; i < x*y; i++) {
Individual tmpind = tmppop.getIndividual(i);
int fitVal = (int) (256*((tmpind.getFitness()-(maxFitness/4))/(3*maxFitness/4)));
if (fitVal < 0) fitVal=0;
String hex = Integer.toHexString(fitVal);
if (fitVal < 16) hex = "0"+hex;
System.out.println( "0 " + (i+32) + " #" + hex + hex + hex + " " + tmpind.getFitness());
}
*/
if (prob.numberOfObjectives()>1) // The multiobjective case
{
System.out.println("Evaluations: " + ((Problem)ea.getParam(CellularGA.PARAM_PROBLEM)).getNEvals() +" Time: "+(fin-inicio));
System.out.println("Number of solutions in the Pareto front: " + ((Archive) ea.getParam(CellularGA.PARAM_SOLUTION_FRONT)).getNumStoredSols());
((Archive) ea.getParam(CellularGA.PARAM_SOLUTION_FRONT)).printFile(prob.getClass().getName(),prob);
}
else
{
Double best = null;
int contig = 0;
if (Target.maximize)
best = (Double) ((Statistic) ea.getParam(CellularGA.PARAM_STATISTIC)).getStat(SimpleStats.MAX_FIT_VALUE);
else
best = (Double) ((Statistic) ea.getParam(CellularGA.PARAM_STATISTIC)).getStat(SimpleStats.MIN_FIT_VALUE);
int evals = ((Problem) (ea.getParam(CellularGA.PARAM_PROBLEM))).getNEvals();
// Writes: best found solution, number of generations, elapsed time (mseconds)
if(prob.getClass().getName().equalsIgnoreCase("problems.Combinatorial.DNAFragmentAssembling"))
{
// Get the best Individual
int pos = ((Integer)((Statistic)ea.getParam(EvolutionaryAlg.PARAM_STATISTIC)).getStat(SimpleStats.MAX_FIT_POS)).intValue();
Individual bestInd = ((Population) ea.getParam(EvolutionaryAlg.PARAM_POPULATION)).getIndividual(pos);
// Evaluate it without weights
problems.Combinatorial.DNAFragmentAssembling dna = (problems.Combinatorial.DNAFragmentAssembling) (ea.getParam(CellularGA.PARAM_PROBLEM));
contig = dna.evalContigs(bestInd);
//System.out.println("Number of contig: " + contig);
}
// In the case of SAT problem, we should compute the best fitness without weights:
else if(prob.getClass().getName().equalsIgnoreCase("problems.Combinatorial.SAT"))
{
// Get the best Individual
int pos = ((Integer)((Statistic)ea.getParam(EvolutionaryAlg.PARAM_STATISTIC)).getStat(SimpleStats.MAX_FIT_POS)).intValue();
Individual bestInd = ((Population) ea.getParam(EvolutionaryAlg.PARAM_POPULATION)).getIndividual(pos);
// Evaluate it without weights
problems.Combinatorial.SAT sat = (problems.Combinatorial.SAT) (ea.getParam(CellularGA.PARAM_PROBLEM));
best = new Double(sat.evalCount(bestInd));
}
if (((Boolean)ea.getParam(EvolutionaryAlg.PARAM_VERBOSE)).booleanValue())
System.out.println("Solution: Best Generations Evaluations Time (ms) Problem");
if(prob.getClass().getName().equalsIgnoreCase("problems.Combinatorial.DNAFragmentAssembling"))
{
System.out.println(best + " " + contig + " " + (Integer) ea.getParam(CellularGA.PARAM_GENERATION_NUMBER)+" "+ evals +" "+(fin-inicio) + " "
+ ((Problem) ea.getParam(CellularGA.PARAM_PROBLEM)).getClass().getName());
// Get the best Individual
int pos = ((Integer)((Statistic)ea.getParam(EvolutionaryAlg.PARAM_STATISTIC)).getStat(SimpleStats.MAX_FIT_POS)).intValue();
PermutationIndividual bestInd = (PermutationIndividual) ((Population) ea.getParam(EvolutionaryAlg.PARAM_POPULATION)).getIndividual(pos);
int len = bestInd.getLength();
for (int i=0; i<len; i++)
System.out.print(bestInd.getIntegerAllele(i) + " ");
System.out.println();
}
else
if (!prob.testing()) // se n‹o estiver a ser executada uma inst‰ncia de teste
System.out.println(best + " " + (Integer) ea.getParam(CellularGA.PARAM_GENERATION_NUMBER) + " " + evals + " " + (fin-inicio) + " "
+ ((Problem) ea.getParam(CellularGA.PARAM_PROBLEM)).getClass().getName());
if( prob.testing() & prob.getClass().getName().startsWith("problems.Combinatorial.TOP")) {
System.out.format("%d;%d; ", ((problems.Combinatorial.TOP)prob).getCollected(), ((problems.Combinatorial.TOP)prob).getIteration());
int nVertices = 0;
ArrayList<Integer>[] bestTrip = ((problems.Combinatorial.TOP)prob).getBestTrip();
for(int i=0 ; i < ((problems.Combinatorial.TOP)prob).getT() ; i++)
nVertices += bestTrip[i].size();
System.out.print("#" + nVertices + "#");
for(int i=0 ; i < ((problems.Combinatorial.TOP)prob).getT() ; i++) {
for (int h=0 ; h < bestTrip[i].size() ; h++)
System.out.print(" " + bestTrip[i].get(h));
System.out.print(" #");
}
}
}
}
private void writeLine(String line)
{
if (verbose) {
try{
out.write(line + "\n");
out.flush();
}
catch (Exception e) { //Catch exception if any
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
public void generation(EvolutionaryAlg ea)
{
//CellularGA cea = (CellularGA) ea;
verbose = ((Boolean) ea.getParam(CellularGA.PARAM_VERBOSE)).booleanValue();
if ((!ea.getParam(EvolutionaryAlg.PARAM_POPULATION).getClass().getName().equalsIgnoreCase("distributedGA")) &&
(((Population)ea.getParam(EvolutionaryAlg.PARAM_POPULATION)).getPopSize() != 1))
{
// Get the best Individual
int pos = ((Integer)((Statistic)ea.getParam(EvolutionaryAlg.PARAM_STATISTIC)).getStat(SimpleStats.MAX_FIT_POS)).intValue();
Individual bestInd = ((Population) ea.getParam(EvolutionaryAlg.PARAM_POPULATION)).getIndividual(pos);
Problem prob = (Problem)ea.getParam(EvolutionaryAlg.PARAM_PROBLEM);
if (prob.numberOfObjectives() == 1) {
if( prob.getClass().getName().startsWith("problems.Combinatorial.TOP") ) {
((problems.Combinatorial.TOP)prob).setIteration((Integer) ea.getParam(CellularGA.PARAM_GENERATION_NUMBER));
writeLine("Generation: " + (Integer) ea.getParam(CellularGA.PARAM_GENERATION_NUMBER) + "; Best individual: " + ((TopIndividual) bestInd).toString() + "\n");
}
else
writeLine("Generation: " + (Integer) ea.getParam(CellularGA.PARAM_GENERATION_NUMBER) + "; Best individual: " + ((BinaryIndividual) bestInd).toString() + "\n");
}
else
writeLine("Generation: " + (Integer) ea.getParam(CellularGA.PARAM_GENERATION_NUMBER));
}
/* Population population = (Population) cea.getParam(CellularGA.PARAM_POPULATION);
for (int i=0; i<25; i++)
writeLine(((Double[])population.getIndividual(i).getFitness())[0].doubleValue() + ", " + ((Double[])population.getIndividual(i).getFitness())[1].doubleValue());
writeLine();*/
// La realimentación aquí
int displaySteps = ((Integer)ea.getParam(CellularGA.PARAM_DISPLAY_STEPS)).intValue();
if ((showDisplay)&& (((Integer)ea.getParam(CellularGA.PARAM_GENERATION_NUMBER)).intValue()%displaySteps==0)) {
CGADisplay display = (CGADisplay) ea.getParam(CellularGA.PARAM_DISPLAY);
CGADisplay display2 = (CGADisplay) ea.getParam(CellularGA.PARAM_DISPLAY2);
if (display != null)
display.step();
if (display2 != null)
display2.step();
}
/*xfig SNAPSHOT
if (((Integer)cea.getParam(CellularGA.PARAM_GENERATION_NUMBER)).intValue()%displaySteps==0) {
PopGrid tmppop = (PopGrid) cea.getPopulation();
for (int i = 0; i < x*y; i++) {
Individual tmpind = tmppop.getIndividual(i);
int fitVal = (int) (256*((tmpind.getFitness()-(maxFitness/4))/(3*maxFitness/4)));
if (fitVal < 0) fitVal=0;
String hex = Integer.toHexString(fitVal);
if (fitVal < 16) hex = "0"+hex;
System.out.println( "0 " + (i+32) + " #" + hex + hex + hex + " " + tmpind.getFitness());
}
}
*/
// For the adaptive population case
int n = ((Integer)ea.getParam(CellularGA.PARAM_GENERATION_NUMBER)).intValue();
//Problem problem = (Problem) ea.getParam(CellularGA.PARAM_PROBLEM);
//Population pop = (Population) ea.getParam(CellularGA.PARAM_POPULATION);
// Adaptive population
if (((ea.getParam(CellularGA.PARAM_POP_ADAPTATION))!=null) &&
// each delta steps
((n%AdaptivePop.delta) == 0))
{
double ratio = 0.0;
// change the pop shape (if needed)
if ((ratio = ((AdaptivePop)ea.getParam(CellularGA.PARAM_POP_ADAPTATION)).evalChange()) != -1.0)
{
if (ratio != lastRatio)
{
lastRatio = ratio;
if (showDisplay)
{
CGADisplay display = (CGADisplay) ea.getParam(CellularGA.PARAM_DISPLAY);
CGADisplay display2 = (CGADisplay) ea.getParam(CellularGA.PARAM_DISPLAY2);
if (display != null)
{
//display.resize(((PopGrid)pop).getDimX(), ((PopGrid)pop).getDimY());
display.resize();
display.step();
//display = new CGADisplay(cea, problem.getMaxFitness(),CGADisplay.NO_TEXT + CGADisplay.DISPLAY_VALUE);
//cea.setParam(CellularGA.PARAM_DISPLAY, display);
}
if (display2 != null)
{
display2.resize();
display2.step();
//display2.resize(((PopGrid)pop).getDimX(), ((PopGrid)pop).getDimY());
//display2 = new CGADisplay(cea, problem.numberOfVariables(),CGADisplay.NO_TEXT + CGADisplay.DISPLAY_BESTDISTANCE);
//cea.setParam(CellularGA.PARAM_DISPLAY, display2);
}
}
writeLine("New ratio: " + ratio);
}
}
}
// For the adaptive population case
// Adaptive anisotropic selection
//if (((ea.getParam(CellularGA.PARAM_POP_ADAPTATION))!=null) &&
// // each delta steps
// ((n%AdaptivePop.delta) == 0))
double alpha;
// For the island distributed population
// Migration occurs here:
if (ea.getParam(EvolutionaryAlg.PARAM_POPULATION).getClass().getName().equalsIgnoreCase("distributedGA"))
{
int evals = ((Problem) (ea.getParam(CellularGA.PARAM_PROBLEM))).getNEvals();
PopIsland pop = (PopIsland)(ea.getParam(CellularGA.PARAM_POPULATION));
//if (evals >= ea.getParam(ea.PARAM_MIGRATION_FREQUENCY))
Individual ind0, ind1;
int j;
int freq = ((Integer)ea.getParam(EvolutionaryAlg.PARAM_MIGRATION_FREQUENCY)).intValue();
int islands = ((DistributedGA)ea).getPopulation().getNumberIslands();
int islandSize = ((DistributedGA)ea).getPopulation().getSizeIslands();
if (((double)evals/(double)freq >= 1) && (evals%(freq*islands)==0))
{
writeLine("Evaluaciones: " + evals);
for (int i=0; i<islands; i++)
{
ind0 = pop.getIndividual(i,((DistributedGA)ea).bestInds[i]);
if (i==islands-1)
j = 0;
else
j = i+1;
ind1 = pop.getIndividual(j,((DistributedGA)ea).worstInds[j]);
if (Target.isBetter(ind0, ind1))
{
pop.setIndividual(j,((DistributedGA)ea).worstInds[j],ind0);
if (Target.isBetter(ind0, pop.getIndividual(j, ((DistributedGA)ea).bestInds[j])))
((DistributedGA)ea).bestInds[j] = ((DistributedGA)ea).worstInds[j];
for(int k=0; k<islandSize; k++)
if (Target.isWorse(pop.getIndividual(j,k), pop.getIndividual(j, ((DistributedGA)ea).worstInds[j])))
((DistributedGA)ea).worstInds[j] = k;
}
}
}
}
// For the island distributed population
Population pop = (Population)(ea.getParam(CellularGA.PARAM_POPULATION));
}
public EvolutionaryAlg getEA()
{
return ea;
}
public void setEA(EvolutionaryAlg ea)
{
this.ea = ea;
}
}