Bonjour,

J'essaie actuellement d'apprendre à me servir du framework JGAP pour faire du GP. C'est pourquoi j'essaie de découvrir la fonction y=a+b-c a partir d'une population de vecteurs [a,b,c,y]. Mais après deux jours je ne n'arrive à rien. Le programme compile. Il crée une population initiale mais celle-ci n'évolue pas. Je crains de ne pas pouvoir trouver la solution seule.

Code : Sélectionner tout - Visualiser dans une fenêtre à part
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
 
package main;
 
import org.apache.log4j.Logger;
import org.jgap.InvalidConfigurationException;
import org.jgap.event.GeneticEvent;
import org.jgap.event.GeneticEventListener;
import org.jgap.gp.CommandGene;
import org.jgap.gp.GPFitnessFunction;
import org.jgap.gp.GPProblem;
import org.jgap.gp.IGPProgram;
import org.jgap.gp.function.Add;
import org.jgap.gp.function.Multiply;
import org.jgap.gp.function.ReadTerminal;
import org.jgap.gp.function.Subtract;
import org.jgap.gp.impl.DeltaGPFitnessEvaluator;
import org.jgap.gp.impl.GPConfiguration;
import org.jgap.gp.impl.GPGenotype;
import org.jgap.gp.impl.TournamentSelector;
import org.jgap.gp.terminal.Variable;
import org.jgap.util.SystemKit;
 
public class Main
extends GPProblem
{
 
	private transient static Logger LOGGER = Logger.getLogger(Main.class);
 
	static Variable va;
	static Variable vb;
	static Variable vc;
	static Variable vy;
 
	static final int NUMBER=50;
	static int initData[][]=new int[NUMBER][4];
 
	public Main(GPConfiguration config) throws InvalidConfigurationException
	{
		super(config);
	}
 
 
 
	public static void main(String[] args) throws Exception
	{
 
		System.out.println("Program to discover: a+b-c");
 
		// configuration standard pour un GP
		GPConfiguration config = new GPConfiguration();
 
		// Une evaluateur de fitness qui prends en entree le delta des 
		// valeurs. Plus le delta est petit plus le fitness est bon.
		// TODO: voir les autres Fitness, [l'influence des parametres]
		config.setGPFitnessEvaluator(new DeltaGPFitnessEvaluator());
 
		// Un tournoi de selection pour GP. Le gagnant est determine
		// en faisant s'opposer le nombre en parametre d'opposant entre
		// eux.
		// TODO: voir les autres Selector, l'influence des parametres
		config.setSelectionMethod(new TournamentSelector(4));
 
		// Taille de la population
		int popSize = 200;
 
		System.out.println("Using population size of " + popSize);
 
		// SUPPOSE: profondeur maximale d'une expresion a l'initialisation
		config.setMaxInitDepth(10);
 
		// Affecte la taille de la population
		config.setPopulationSize(popSize);
 
		// Definit la fonction fitness qui est contenu dans une classe
		// heritant de GPFitnessFunction s'appelle evaluate(IGPProgram):
		// double
		// 
		// La classe Formula.. est incluse dans Main.
		/*
		 * Dans notre cas on veut decouvrir  "a+b-c" donc il faut 3
		 * variables avec un jeux de données et Deux opérateurs.
		 * On applique l'algorithme trouver qui retourne le delta entre
		 * la y=a+b-c et y' de GP. 
		 */
		config.setFitnessFunction(new Main.FormulaFitnessFunction());
 
		// Si true declenche une exception si une function ou un terminal
		// d'un certain type est requis n'est pas disponible.
		config.setStrictProgramCreation(false);
 
		// ?? Pas documenter
		config.setProgramCreationMaxTries(3);
 
		// ?? Pas documenter
		config.setMaxCrossoverDepth(5);
 
		config.setReproductionProb(1f);
		config.setMutationProb(1f);
 
		// Set a node validator to demonstrate speedup when something is known
		// about the solution (see FibonacciNodeValidator).
		// -------------------------------------------------------------------
		/* config.setNodeValidator(new FibonacciNodeValidator()); */
 
		// Ative le cache des programmes GP => Les valeurs de fitness seront
		// mis en cache pour tous les evolutions de programmes équivalents
		// aux anciens.
		config.setUseProgramCache(true);
 
		// creer la classe probleme a partir de la config
		final GPProblem problem = new Main(config);
 
		// Creer un genotype a partir de la config.
		GPGenotype gp = problem.create();
 
		// ??
		gp.setVerboseOutput(true);
 
		// lance le traitement par thread
		final Thread t = new Thread(gp);
 
		/*
		 * On implémente le run après le lancement du thread. Etrange.
		 */
 
		// Simple implementation of running evolution in a thread.
		// -------------------------------------------------------
		config
		.getEventManager()
		.addEventListener(
				GeneticEvent.
				GPGENOTYPE_EVOLVED_EVENT,
				new GeneticEventListener()
				{
					@SuppressWarnings({ "deprecation", "static-access" })
					public void geneticEventFired
					(GeneticEvent a_firedEvent)
					{
						GPGenotype genotype = (GPGenotype)
						a_firedEvent.getSource();
						int evno = genotype	.getGPConfiguration()
											.getGenerationNr();
						double freeMem = SystemKit.getFreeMemoryMB();
						if (evno % 50 == 0)
						{
							IGPProgram best = genotype.getAllTimeBest();
							double allBestFitness = best.getFitnessValue();
							LOGGER.info("Evolving generation " + evno
									+ ", all-time-best fitness: " 
									+ allBestFitness
									+ ", memory free: " 
									+ freeMem + " MB");
							genotype.outputSolution(best);
						}
						if (evno > 3000)
						{
							t.stop();
						}
						else
						{
							try {
								// Collect garbage if memory low.
								// ------------------------------
								if (freeMem < 50)
								{
									System.gc();
									t.sleep(500);
								}
								else
								{
									// Avoid 100% CPU load.
									// --------------------
									t.sleep(30);
								}
							}
							catch (InterruptedException iex) 
							{
								iex.printStackTrace();
								System.exit(1);
							}
						}
					}
				});
 
		config.getEventManager().addEventListener(GeneticEvent.
				GPGENOTYPE_NEW_BEST_SOLUTION, new GeneticEventListener()
		{
			/**
			 * New best solution found.
			 *
			 * @param a_firedEvent GeneticEvent
			 */
			@SuppressWarnings("deprecation")
			public void geneticEventFired(GeneticEvent a_firedEvent) {
				GPGenotype genotype = (GPGenotype) a_firedEvent.getSource();
				int evno = genotype.getGPConfiguration().getGenerationNr();
				String indexString = "" + evno;
				while (indexString.length() < 5) {
					indexString = "0" + indexString;
				}
				String filename = "function_" + indexString + ".png";
				IGPProgram best = genotype.getAllTimeBest();
				try {
					problem.showTree(best, filename);
				} catch (InvalidConfigurationException iex) {
					iex.printStackTrace();
				}
				double bestFitness = genotype.getFittestProgram().
				getFitnessValue();
				if (bestFitness < 0.001) {
					genotype.outputSolution(best);
					t.stop();
					System.exit(0);
				}
			}
		});
		t.start();
	} 
 
	public static class FormulaFitnessFunction
	extends GPFitnessFunction
	{
		private static final long serialVersionUID = 1L;
 
		protected double evaluate(final IGPProgram a_subject)
		{
			return computeRawFitness(a_subject);	
		}
 
	}
 
	public static double computeRawFitness(final IGPProgram a_program)
	{
		Object[] noargs = new Object[0];
 
		// On vide la pile et la memoire du programme
		// ------------------------
		a_program.getGPConfiguration().clearStack();
		a_program.getGPConfiguration().clearMemory();
 
		// On calcule son fitness
		// ---------------------------------
		double result = 0.0d;
		for(int i=0;i<NUMBER;i++)
		{
			va.set(initData[i][0]);
			vb.set(initData[i][1]);
			vc.set(initData[i][2]);
			// On execute dans l'ordre chaque instruction du programme.
 
			try {
 
				try {
 
					// Quand on arrive a la fin des instructions du
					// programmes on recupere le resultat finale comme
					// resultat finale
					// -------------------------------------------------------------
					result += a_program.execute_int(0, noargs);
						return Math.abs(initData[i][3]-result);
					}
					catch (IllegalStateException iex)
					{
					result = GPFitnessFunction.MAX_FITNESS_VALUE;
					}
			}
			catch (ArithmeticException ex)
			{
				System.out.println("(y,result) = (" +initData[i][3]+","+result+")");
				System.out.println(a_program.getChromosome(0));
				throw ex;
			}
		}
		if (a_program.getGPConfiguration().stackSize() > 0) {
			result = GPFitnessFunction.MAX_FITNESS_VALUE;
		}
		if (result < 0.000001) {
			result = 0.0d;
		}
		else if (result < GPFitnessFunction.MAX_FITNESS_VALUE) {
			/**@todo add penalty for longer solutions*/
		}
		return result;
	}
 
	/**
	 * Sets up the functions to use and other parameters. Then creates the
	 * initial genotype.
	 *
	 * @return the genotype created
	 * @throws InvalidConfigurationException
	 *
	 * @author Klaus Meffert
	 * @since 3.0
	 */
	@SuppressWarnings("unchecked")
	public GPGenotype create()
	throws InvalidConfigurationException {
 
		// Define return types of sub programs (see nodeSets).
		// The first entry in types corresponds with the first entry in nodeSets,
		// etc.
		Class[] types ={
				CommandGene.IntegerClass
				};
 
		// The following is only relevant for ADF's and not used here.
		Class[][] argTypes = { {} };
 
		// Configure desired minimum number of nodes per sub program.
		// Same as with types: First entry here corresponds with first entry in
		// nodeSets.
		int[] minDepths = new int[] {5};
 
		// Configure desired maximum number of nodes per sub program.
		// First entry here corresponds with first entry in nodeSets.
		int[] maxDepths = new int[] {10};
 
		GPConfiguration conf = getGPConfiguration();
		/**@todo allow to optionally preset a static program in each chromosome*/
 
		/*
		 *  Il s'agit d'un tableau d'operateur a 2 dimensions. La premiere est
		 *  le chromosome dans sa longeur. La deuxieme sont les different 
		 *  operateurs possible pour cette allele du chromosome.
		 */
		va = Variable.create(conf, "A", CommandGene.IntegerClass);
		vb = Variable.create(conf, "B", CommandGene.IntegerClass);
		vc = Variable.create(conf, "C", CommandGene.IntegerClass);
		vy = Variable.create(conf, "C", CommandGene.IntegerClass);
 
		CommandGene[][] nodeSets =
		{ 
			{
				new ReadTerminal	(conf,CommandGene.IntegerClass, "A"),
				new ReadTerminal	(conf,CommandGene.IntegerClass, "B"),
				new ReadTerminal	(conf,CommandGene.IntegerClass, "C"),
				new ReadTerminal	(conf,CommandGene.IntegerClass, "Y"),
				new Add				(conf,CommandGene.IntegerClass),
				new Subtract		(conf,CommandGene.IntegerClass),
				new Multiply		(conf,CommandGene.IntegerClass)
			}
		};
 
		// Add commands working with internal memory.
		// ------------------------------------------
 
/*	
  		nodeSets[2] = 	CommandFactory.createReadOnlyCommands(nodeSets[2],
						conf,
						CommandGene.IntegerClass, "mem", 1, 2, !true);
*/
 
		// Randomly initialize function data (X-Y table) for Fib(x).
		// ---------------------------------------------------------
		for(int i=0;i<NUMBER;i++)
		{
			initData[i][0]=(int)(Math.random()*Integer.MAX_VALUE);
			initData[i][1]=(int)(Math.random()*Integer.MAX_VALUE);
			initData[i][2]=(int)(Math.random()*Integer.MAX_VALUE);
			initData[i][3]=initData[i][0]+initData[i][1]-initData[i][2];
		}
 
		// Create genotype with initial population.
		// ----------------------------------------
		// new boolean[] {!true, !true, false} 
		// a_fullModeAllowed - array of boolean values.
		// For each chromosome there is one value indicating 
		// whether the full mode for creating chromosome generations
		// during evolution is allowed (true) or not (false)
 
		return GPGenotype.randomInitialGenotype(
				conf, types, argTypes, nodeSets,
				minDepths, maxDepths, 20,
				new boolean[] {true},
//				new boolean[] {!true, !true, !true, false},
//				new boolean[] {true, true, true, !false},
				true);
 
	}
 
}

merci d'avance de vos réponses.