Debian Codegraph @

doc/Extensions.html

raw
1 <html><head><title>GAlib: Extensions</title>
2
3 <!-- by matthew wall all rights reserved -->
4 <!-- Copyright (c) 1995-1996 Massachusetts Institute of Technology -->
5 <!-- Copyright (c) 1996-1999 Matthew Wall -->
6
7 </head>
8 <body bgcolor="efefef" text="000000">
9
10 <strong>Customizing <a href="GAlib.html">GAlib</a></strong><br>
11 <i>version 2.4</i>
12 <p>
13 This document describes how to extend GAlib's capabilities by defining your own genomes and genetic operators. The best way to customize the behavior of an object is to derive a new class. If you do not want to do that much work, GAlib is designed to let you replace behaviors of existing objects by defining new functions.
14 </p>
15 <p>
16 see also: <i><a href="Overview.html">library overview</a>, <a href="ClassHierarchy.html">class hierarchy</a>, <a href="API.html">programming interface</a></i>
17 </p>
18
19 <p>
20 <strong>Table of contents</strong><br>
21 <hr>
22 <br>
23 </p>
24
25 <table>
26 <tr valign=baseline>
27 <td width=220>
28 <ul>
29 <strong>Genome</strong>
30 <li><a href="#genome">Deriving a new Genome</a>
31 <li><a href="#genome_testing">Testing a new Genome</a>
32 <li><a href="#genome_initialization">Initialization</a>
33 <li><a href="#genome_mutation">Mutation</a>
34 <li><a href="#genome_crossover">Crossover</a>
35 <li><a href="#genome_comparison">Comparison</a>
36 <li><a href="#genome_evaluation">Evaluation</a>
37 </ul>
38 </td>
39
40 <td width=6></td>
41
42 <td width=180>
43 <ul>
44 <strong>Population</strong>
45 <li><a href="#pop_initialization">Initialization</a>
46 <li><a href="#pop_evaluation">Evaluation</a>
47 <li><a href="#pop_scaling">Scaling</a>
48 <li><a href="#pop_selection">Selection</a>
49 </ul>
50 </td>
51
52 <td width=6></td>
53
54 <td width=220>
55 <ul>
56 <strong>Genetic Algorithm</strong>
57 <li><a href="#ga">Deriving a new Algorithm</a>
58 <li><a href="#termination">Termination</a>
59 </ul>
60 </td>
61 </tr>
62 </table>
63
64
65
66
67
68
69
70 <br>
71 <br>
72 <br>
73 <a name="genome">
74 <br><strong>Deriving your own genome class</strong><br></a>
75 <hr>
76 You can create your own genome class by multiply-inheriting from the base genome class and your own data type. For example, if you have already have an object defined, say MyObject, then you would derive a new genome class called MyGenome, whose class definition looks like this:
77 <pre>
78 // Class definition for the new genome object, including statically defined
79 // declarations for default evaluation, initialization, mutation, and
80 // comparison methods for this genome class.
81 class MyGenome : public MyObject, public GAGenome {
82 public:
83 GADefineIdentity("MyGenome", 201);
84 static void Init(GAGenome&amp;);
85 static int Mutate(GAGenome&amp;, float);
86 static float Compare(const GAGenome&amp;, const GAGenome&amp;);
87 static float Evaluate(GAGenome&amp;);
88 static int Cross(const GAGenome&amp;, const GAGenome&amp;, GAGenome*, GAGenome*);
89
90 public:
91 MyGenome() : GAGenome(Init, Mutate, Compare) {
92 evaluator(Evaluate);
93 crossover(Cross);
94 }
95 MyGenome(const MyGenome&amp; orig) { copy(orig); }
96 virtual ~MyGenome() {}
97 MyGenome&amp; operator=(const GAGenome&amp; orig){
98 if(&amp;orig != this) copy(orig);
99 return *this;
100 }
101
102 virtual GAGenome* clone(CloneMethod) const {return new MyGenome(*this);}
103 virtual void copy(const GAGenome&amp; orig) {
104 GAGenome::copy(orig); // this copies all of the base genome parts
105 // copy any parts of MyObject here
106 // copy any parts of MyGenome here
107 }
108
109 // any data/member functions specific to this new class
110 };
111
112 void
113 MyGenome::Init(GAGenome&amp;){
114 // your initializer here
115 }
116
117 int
118 MyGenome::Mutate(GAGenome&amp;, float){
119 // your mutator here
120 }
121
122 float
123 MyGenome::Compare(const GAGenome&amp;, const GAGenome&amp;){
124 // your comparison here
125 }
126
127 float
128 MyGenome::Evaluate(GAGenome&amp;){
129 // your evaluation here
130 }
131
132 int
133 MyGenome::Cross(const GAGenome&amp; mom, const GAGenome&amp; dad,
134 GAGenome* sis, GAGenome* bro){
135 // your crossover here
136 }
137 </pre>
138 <p>
139 By convention, one of the arguments to a derived genome constructor is the objective function. Alternatively (as illustrated in this example), you can hard code a default objective function into your genome - just call the <b>evaluator</b> member somewhere in your constructor and pass the function you want used as the default.
140 </p>
141 <p>
142 Once you have defined your genome class, you should define the <a href="#genome_initialization">intialization</a>, <a href="#genome_mutation">mutation</a>, <a href="#genome_comparison">comparison</a>, and <a href="#genome_crossover">crossover</a> operators for it. The comparison operator is optional, but if you do not define it you will not be able to use the diversity measures in the genetic algorithms and/or populations.
143 </p>
144 <p>
145 Note that the genetic comparator is not necessarily the same as the boolean operator== and operator!= comparators. The genetic comparator returns 0 if the two individuals are the same, -1 if the comparison fails for some reason, and a real number greater than 0 indicating the degree of difference if the individuals are not identical but can be compared. It may be based on genotype or phenotype. The boolean comparators, on the other hand, indicate only whether or not two individuals are identical. In most cases, the boolean comparator can simply call the genetic comparator, but in some cases it is more efficient to define different operators (the boolean comparators are called much more often than the genetic comparators, especially if no diversity is being measured).
146 </p>
147 <p>
148 To work properly with the GAlib, you <i>must</i> define the following:
149 </p>
150 <pre>
151 MyGenome( -default-args-for-your-genome-constructor )
152 MyGenome(const MyGenome&amp;)
153 virtual GAGenome* clone(GAGenome::CloneMethod) const
154 </pre>
155 If your genome adds any non-trivial member data, you must define these:
156 <pre>
157 virtual ~MyGenome()
158 virtual copy(const GAGenome&amp;)
159 virtual int equal(const GAGenome&amp;) const
160 </pre>
161 To enable streams-based reading and writing of your genome, you should define these:
162 <pre>
163 virtual int read(istream&amp;)
164 virtual int write(ostream&amp;) const
165 </pre>
166 When you derive a genome, don't forget to use the _evaluated flag to
167 indicate when the state of the genome has changed and an evaluation is
168 needed. If a member function changes the state of your genome, that member
169 function should set the _evaluated flag to gaFalse.
170 <p>
171 Assign a default crossover, mutation, initialization, and comparison
172 method so that users don't have to assign one unless they want to.
173 </p>
174 <p>
175 It is a good idea to define an identity for your genome (especially if you will be using it in an environment with multiple genome types running around). Use the DefineIdentity macro (defined in id.h) to do this in your class definition. The DefineIdentity macro sets a class ID number and the name that will be used in error messages for the class. You can use any number above 200 for the ID, but be sure to use a different number for each of your classes.
176 </p>
177 <p>
178 When run-time type information (RTTI) has stabilized across compilers, GAlib will probably use that instead of the Define/Declare identity macros.
179 </p>
180
181
182
183
184
185
186
187
188
189
190
191 <br>
192 <br>
193 <br>
194 <a name="genome_testing">
195 <br><strong>Genome Testing</strong><br></a>
196 <hr>
197 Use the following program to test your genome. The basic idea here is to test incrementally in order to isolate problems as they arise. If your genome works with a small test program such as this one, it will function properly with any genetic algorithm in GAlib. (This is no guarantee, however, that your genome will help you find the solution to your problem. That is another matter entirely.)
198 <pre>
199 int
200 main() {
201 MyGenome genome; // test default constructor (if we have one)
202 cout &lt;&lt; "genome after creation:\n" &lt;&lt; genome &lt;&lt; endl;
203
204 genome.initialize(); // test the initializer
205 cout &lt;&lt; "genome after initialization:\n" &lt;&lt; genome &lt;&lt; endl;
206
207 genome.mutate(); // test the mutator
208 cout &lt;&lt; "genome after mutation:\n" &lt;&lt; genome &lt;&lt; endl;
209
210 MyGenome* a = new MyGenome(genome); // test copy constructor
211 MyGenome* b = new MyGenome(genome);
212
213 MyGenome* c = genome.clone(GAGenome::CONTENTS);
214 cout &lt;&lt; "clone contents:\n" &lt;&lt; *c &lt;&lt; "\n";
215 MyGenome* d = genome.clone(GAGenome::ATTRIBUTES);
216 cout &lt;&lt; "clone attributes:\n" &lt;&lt; *d &lt;&lt; "\n";
217
218 a->initialize();
219 b->initialize();
220 cout &lt;&lt; "parents:\n" &lt;&lt; *a &lt;&lt; "\n" &lt;&lt; *b &lt;&lt; "\n";
221
222 MyGenome::DefaultCrossover(*a, *b, c, d); // test two child crossover
223 cout &lt;&lt; "children of crossover:\n" &lt;&lt; *c &lt;&lt; "\n" &lt;&lt; *d &lt;&lt; "\n";
224 MyGenome::DefaultCrossover(*a, *b, c, 0); // test single child crossover
225 cout &lt;&lt; "child of crossover:\n" &lt;&lt; *c &lt;&lt; "\n";
226
227 a->compare(*b); // test the comparator
228
229 delete a;
230 delete b;
231 delete c;
232 delete d;
233
234 return 0;
235 }
236 </pre>
237
238
239
240
241
242
243
244
245
246
247 <br>
248 <br>
249 <br>
250 <a name="genome_initialization">
251 <br><strong>Genome Initialization</strong><br></a>
252 <hr>
253 The initializer takes a single argument: the genome to be initialized. The genome has already been allocated; the intializer only needs to populate it with appropriate contents.
254 <p>
255 Here is the implementation of an initializer for the GATreeGenome&lt;int&gt; class.
256 </p>
257 <pre>
258 void
259 TreeInitializer(GAGenome &amp; c)
260 {
261 GATreeGenome&lt;int&gt; &amp;child=(GATreeGenome&lt;int&gt; &amp;)c;
262
263 // destroy any pre-existing tree
264 child.root();
265 child.destroy();
266
267 // Create a new tree with depth of 'depth' and each eldest node containing
268 // 'n' children (the other siblings have none).
269 int depth=2, n=3, count=0;
270 child.insert(count++,GATreeBASE::ROOT);
271
272 for(int i=0; i&lt;depth; i++){
273 child.eldest();
274 child.insert(count++);
275 for(int j=0; j&lt;n; j++)
276 child.insert(count++,GATreeBASE::AFTER);
277 }
278 }
279 </pre>
280
281
282
283
284
285
286
287
288
289
290
291
292
293 <br>
294 <br>
295 <br>
296 <a name="genome_mutation">
297 <br><strong>Genome Mutation</strong><br></a>
298 <hr>
299 The genome mutator takes two arguments: the genome that will receive the mutation(s) and a mutation probability. The exact meaning of the mutation probability is up to the designer of the mutation operator. The mutator should return the number of mutations that occured.
300 <p>
301 Most genetic algorithms invoke the mutation method on each newly generated offspring. So your mutation operator should base its actions on the value of the mutation probability. For example, an array of floats could flip a <i>pmut</i>-biased coin for each element in the array. If the coin toss returns true, the element gets a Gaussian mutation. If it returns false, the element is left unchanged. Alternatively, a single biased coin toss could be used to determine whether or not the <i>entire</i> genome should be mutated.
302 </p>
303 <p>
304 Here is an implementation of the flip mutator for the GA1DBinaryString class. This mutator flips a biased coin for each bit in the string.
305 </p>
306 <pre>
307 int
308 GA1DBinStrFlipMutator(GAGenome &amp; c, float pmut)
309 {
310 GA1DBinaryStringGenome &amp;child=(GA1DBinaryStringGenome &amp;)c;
311 if(pmut &lt;= 0.0) return(0);
312
313 int nMut=0;
314 for(int i=child.length()-1; i&gt;=0; i--){
315 if(GAFlipCoin(pmut)){
316 child.gene(i, ((child.gene(i) == 0) ? 1 : 0));
317 nMut++;
318 }
319 }
320 return nMut;
321 }
322 </pre>
323
324
325
326
327
328
329
330
331
332
333
334 <br>
335 <br>
336 <br>
337 <a name="genome_crossover">
338 <br><strong>Genome Crossover</strong><br></a>
339 <hr>
340 The crossover method is used by the genetic algorithm to mate individuals from the population to form new offspring. Each genome should define a default crossover method for the genetic algorithms to use. The <b>sexual</b> and <b>asexual</b> member functions return a pointer to the preferred sexual and asexual mating methods, respectively. The <b>crossover</b> member function is used to change the preferred mating method. The genome does not have a member function to invoke the crossover; only the genetic algorithm can actually perform the crossover.
341 <p>
342 Some genetic algorithms use sexual mating, others use asexual mating. If possible, define both so that your genome will work with either kind of genetic algorithm. If your derived class does not define a cross method, an error message will be posted whenever crossover is attempted.
343 </p>
344 <p>
345 Sexual crossover takes four arguments: two parents and two children. If one child is nil, the operator should be able to generate a single child. The genomes have already been allocated, so the crossover operator should simply modify the contents of the child genome as appropriate. The crossover function should return the number of crossovers that occurred. Your crossover function should be able to operate on one or two children, so be sure to test the child pointers to see if the genetic algorithm is asking you to create one or two children.
346 </p>
347 <p>
348 Here is an implementation of the two-parent/one-or-two-child single point crossover operator for fixed-length genomes of the GA1DBinaryStringGenome class.
349 </p>
350 <pre>
351 int
352 SinglePointCrossover(const GAGenome&amp; p1, const GAGenome&amp; p2, GAGenome* c1, GAGenome* c2){
353 GA1DBinaryStringGenome &amp;mom=(GA1DBinaryStringGenome &amp;)p1;
354 GA1DBinaryStringGenome &amp;dad=(GA1DBinaryStringGenome &amp;)p2;
355
356 int n=0;
357 unsigned int site = GARandomInt(0, mom.length());
358 unsigned int len = mom.length() - site;
359
360 if(c1){
361 GA1DBinaryStringGenome &amp;sis=(GA1DBinaryStringGenome &amp;)*c1;
362 sis.copy(mom, 0, 0, site);
363 sis.copy(dad, site, site, len);
364 n++;
365 }
366 if(c2){
367 GA1DBinaryStringGenome &amp;bro=(GA1DBinaryStringGenome &amp;)*c2;
368 bro.copy(dad, 0, 0, site);
369 bro.copy(mom, site, site, len);
370 n++;
371 }
372
373 return n;
374 }
375 </pre>
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391 <br>
392 <br>
393 <br>
394 <a name="genome_comparison">
395 <br><strong>Genome Comparison</strong><br></a>
396 <hr>
397 The comparison method is used for diversity calculations. It compares two genomes and returns a number that is greater than or equal to zero. A value of 0 means that the two genomes are identical (no diversity). There is no maximum value for the return value from the comparator. A value of -1 indicates that the diversity could not be calculated.
398 <p>
399 Here is the comparator for the binary string genomes. It simply counts up the number of bits that both genomes share. In this example, we return a -1 if the genomes are not the same length.
400 </p>
401
402 <pre>
403 float
404 GA1DBinStrComparator(const GAGenome&amp; a, const GAGenome&amp; b){
405 GA1DBinaryStringGenome &amp;sis=(GA1DBinaryStringGenome &amp;)a;
406 GA1DBinaryStringGenome &amp;bro=(GA1DBinaryStringGenome &amp;)b;
407 if(sis.length() != bro.length()) return -1;
408 float count = 0.0;
409 for(int i=sis.length()-1; i&gt;=0; i--)
410 count += ((sis.gene(i) == bro.gene(i)) ? 0 : 1);
411 return count/sis.length();
412 }
413 </pre>
414
415
416
417
418
419
420
421
422
423
424
425
426 <br>
427 <br>
428 <br>
429 <a name="genome_evaluation">
430 <br><strong>Genome Evaluation</strong><br></a>
431 <hr>
432 The genome evaluator is the objective function for your problem. It takes a single genome as its argument. The evaluator returns a number that indicates how good or bad the genome is. You must cast the generic genome to the genome type that you are using. If your objective function works with different genome types, then use the genome object's <b>className</b> and/or <b>classID</b> member functions to determine the genome class before you do the casts.
433 <p>
434 Here is a simple evaluation function for a real number genome with a single element. The function tries to maximize a sinusoidal.
435 </p>
436
437 <pre>
438 float
439 Objective(GAGenome&amp; g){
440 GARealGenome&amp; genome = (GARealGenome &amp;)g;
441 return 1 + sin(genome.gene(0)*2*M_PI);
442 }
443 </pre>
444
445
446
447
448
449
450
451
452
453
454
455
456
457 <br>
458 <br>
459 <br>
460 <a name="pop_initialization">
461 <br><strong>Population Initialization</strong><br></a>
462 <hr>
463 This method is invoked when the population is initialized.
464 <p>
465 Here is an implemenation that invokes the initializer for each genome in the population.
466 </p>
467
468 <pre>
469 void
470 PopInitializer(GAPopulation &amp; p){
471 for(int i=0; i&lt;p.size(); i++)
472 p.individual(i).initialize();
473 }
474 </pre>
475
476
477
478
479
480
481
482
483
484
485
486
487 <br>
488 <br>
489 <br>
490 <a name="pop_evaluation">
491 <br><strong>Population Evaluation</strong><br></a>
492 <hr>
493 This method is invoked when the population is evaluated. If your objective is population-based, you can use this method to set the score for each genome rather than invoking an evaluator for each genome.
494 <p>
495 Here is an implementation that invokes the evaluation method for each genome in the population.
496 </p>
497
498 <pre>
499 void
500 PopEvaluator(GAPopulation &amp; p){
501 for(int i=0; i&lt;p.size(); i++)
502 p.individual(i).evaluate();
503 }
504 </pre>
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519 <br>
520 <br>
521 <br>
522 <a name="pop_scaling">
523 <br><strong>Scaling Scheme</strong><br></a>
524 <hr>
525 The scaling object does the transformation from raw (objective) scores to scaled (fitness) scores. The most important member function you will have to define for a new scaling object is the <b>evaluate</b> member function. This function calculates the fitness scores based on the objective scores in the population that is passed to it.
526 <p>
527 The GAScalingScheme class is a pure virtual (abstract) class and cannot be instantiated. To make your derived class non-virtual, you <i>must</i> define the <b>clone</b> and <b>evaluate</b> functions. You should also define the <b>copy</b> method if your derived class introduces any additional data members that require non-trivial copy.
528 </p>
529 <p>
530 The scaling class is polymorphic, so you should define the object's identity using the GADefineIdentity macro. This macro sets a class ID number and the name that will be used in error messages for the class. You can use any number above 200 for the ID, but be sure to use a different number for each of your objects.
531 </p>
532 <p>
533 Here is an implementation of sigma truncation scaling.
534 </p>
535 <pre>
536 class SigmaTruncationScaling : public GAScalingScheme {
537 public:
538 GADefineIdentity("SigmaTruncationScaling", 286);
539
540 SigmaTruncationScaling(float m=gaDefSigmaTruncationMultiplier) : c(m) {}
541 SigmaTruncationScaling(const SigmaTruncationScaling &amp; arg){copy(arg);}
542 SigmaTruncationScaling &amp; operator=(const GAScalingScheme &amp; arg)
543 { copy(arg); return *this; }
544 virtual ~SigmaTruncationScaling() {}
545 virtual GAScalingScheme * clone() const
546 { return new SigmaTruncationScaling(*this); }
547 virtual void evaluate(const GAPopulation &amp; p);
548 virtual void copy(const GAScalingScheme &amp; arg){
549 if(&amp;arg != this &amp;&amp; sameClass(arg)){
550 GAScalingScheme::copy(arg);
551 c=((SigmaTruncationScaling&amp;)arg).c;
552 }
553 }
554 float multiplier(float fm) { return c=fm; }
555 float multiplier() const { return c; }
556 protected:
557 float c; // std deviation multiplier
558 };
559
560
561 void
562 SigmaTruncationScaling::evaluate(const GAPopulation &amp; p) {
563 float f;
564 for(int i=0; i&lt;p.size(); i++){
565 f = p.individual(i).score() - p.ave() + c * p.dev();
566 if(f &lt; 0) f = 0;
567 p.individual(i).fitness(f);
568 }
569 }
570 </pre>
571
572
573
574
575
576
577
578
579
580
581
582
583
584 <br>
585 <br>
586 <br>
587 <a name="pop_selection">
588 <br><strong>Selection Scheme</strong><br></a>
589 <hr>
590 The selection object is used to pick individuals from the population. Before a selection occurs, the <b>update</b> method is called. You can use this method to do any pre-selection data transformations for your selection scheme. When a selection is requested, the <b>select</b> method is called. The <b>select</b> method should return a reference to a single individual from the population.
591 <p>
592 A selector may make its selections based either on the scaled (fitness) scores or on the raw (objective) scores of the individuals in the population. Note also that a population may be sorted either low-to-high or high-to-low, depending on which sort order was chosen. Your selector should be able to handle either order (this way it will work with genetic algorithms that maximize or minimize).
593 </p>
594 <p>
595 The selection scheme class is polymorphic, so you should define the object's identity using the GADefineIdentity macro. This macro sets a class ID number and the name that will be used in error messages for the class. You can use any number above 200 for the ID, but be sure to use a different number for each of your objects.
596 </p>
597 <p>
598 Here is an implementation of a tournament selector. It is based on the roulette wheel selector and shares some of the roulette wheel selector's functionality. In particular, this tournament selector uses the roulette wheel selector's <b>update</b> method, so it does not define its own. The <b>select</b> method does two fitness-proportionate selections then returns the individual with better score.
599 </p>
600 <pre>
601 class TournamentSelector : public GARouletteWheelSelector {
602 public:
603 GADefineIdentity("TournamentSelector", 255);
604
605 TournamentSelector(int w=GASelectionScheme::FITNESS) :
606 GARouletteWheelSelector(w) {}
607 TournamentSelector(const TournamentSelector&amp; orig) { copy(orig); }
608 TournamentSelector&amp; operator=(const GASelectionScheme&amp; orig)
609 { if(&amp;orig != this) copy(orig); return *this; }
610 virtual ~TournamentSelector() {}
611 virtual GASelectionScheme* clone() const
612 { return new TournamentSelector; }
613 virtual GAGenome&amp; select() const;
614 };
615
616
617 GAGenome &amp;
618 TournamentSelector::select() const {
619 int picked=0;
620 float cutoff;
621 int i, upper, lower;
622
623 cutoff = GARandomFloat();
624 lower = 0; upper = pop-&gt;size()-1;
625 while(upper &gt;= lower){
626 i = lower + (upper-lower)/2;
627 if(psum[i] &gt; cutoff)
628 upper = i-1;
629 else
630 lower = i+1;
631 }
632 lower = Min(pop-&gt;size()-1, lower);
633 lower = Max(0, lower);
634 picked = lower;
635
636 cutoff = GARandomFloat();
637 lower = 0; upper = pop-&gt;size()-1;
638 while(upper &gt;= lower){
639 i = lower + (upper-lower)/2;
640 if(psum[i] &gt; cutoff)
641 upper = i-1;
642 else
643 lower = i+1;
644 }
645 lower = Min(pop-&gt;size()-1, lower);
646 lower = Max(0, lower);
647
648 GAPopulation::SortBasis basis =
649 (which == FITNESS ? GAPopulation::SCALED : GAPopulation::RAW);
650 if(pop-&gt;order() == GAPopulation::LOW_IS_BEST){
651 if(pop-&gt;individual(lower,basis).score() &lt;
652 pop-&gt;individual(picked,basis).score())
653 picked = lower;
654 }
655 else{
656 if(pop-&gt;individual(lower,basis).score() &gt;
657 pop-&gt;individual(picked,basis).score())
658 picked = lower;
659 }
660
661 return pop-&gt;individual(picked,basis);
662 }
663 </pre>
664
665
666
667
668
669
670
671
672
673
674
675
676
677 <br>
678 <br>
679 <br>
680 <a name="ga">
681 <br><strong>Genetic Algorithm</strong><br></a>
682 <hr>
683 Here is a sample derived class that does restricted mating. In this example, one of the parents is selected as usual. The second individual is select as the first, but it is used only if it is similar to the first individual. If not, we make another selection. If enough selections fail, we take what we can get.
684
685 <pre>
686 class RestrictedMatingGA : public GASteadyStateGA {
687 public:
688 GADefineIdentity("RestrictedMatingGA", 288);
689 RestrictedMatingGA(const GAGenome&amp; g) : GASteadyStateGA(g) {}
690 virtual ~RestrictedMatingGA() {}
691 virtual void step();
692 RestrictedMatingGA &amp; operator++() { step(); return *this; }
693 };
694
695 void
696 RestrictedMatingGA::step()
697 {
698 int i, k;
699 for(i=0; i&lt;tmpPop-&gt;size()-; i++){
700 mom = &amp;(pop-&gt;select());
701 k=0;
702 do { k++; dad = &amp;(pop-&gt;select()); }
703 while(mom-&gt;compare(*dad) &lt; THRESHOLD &amp;&amp; k&lt;pop-&gt;size());
704 stats.numsel += 2;
705 if(GAFlipCoin(pCrossover()))
706 stats.numcro += (*scross)(*mom, *dad, &amp;tmpPop-&gt;individual(i), 0);
707 else
708 tmpPop-&gt;individual(i).copy(*mom);
709 stats.nummut += tmpPop-&gt;individual(i).mutate(pMutation());
710 }
711
712 for(i=0; i&lt;tmpPop-&gt;size(); i++)
713 pop-&gt;add(tmpPop-&gt;individual(i));
714
715 pop-&gt;evaluate(); // get info about current pop for next time
716 pop-&gt;scale(); // remind the population to do its scaling
717
718 for(i=0; i&lt;tmpPop-&gt;size(); i++)
719 pop-&gt;destroy(GAPopulation::WORST, GAPopulation::SCALED);
720
721 stats.update(*pop); // update the statistics by one generation
722 }
723 </pre>
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743 <br>
744 <br>
745 <br>
746 <a name="termination">
747 <br><strong>Termination Function</strong><br></a>
748 <hr>
749 The termination function determines when the genetic algorithm should stop evolving. It takes a genetic algorithm as its argument and returns gaTrue if the genetic algorithm should stop or gaFalse if the algorithm should continue.
750 <p>
751 Here are three examples of termination functions. The first compares the current generation to the desired number of generations. If the current generation is less than the desired number of generations, it returns gaFalse to signify that the GA is not yet complete.
752 </p>
753 <pre>
754 GABoolean
755 GATerminateUponGeneration(GAGeneticAlgorithm &amp; ga){
756 return(ga.generation() &lt; ga.nGenerations() ? gaFalse : gaTrue);
757 }
758 </pre>
759 The second example compares the average score in the current population with the score of the best individual in the current population. If the ratio of these exceeds a specified threshhold, it returns gaTrue to signify that the GA should stop. Basically this means that the entire population has converged to a 'good' score.
760 <pre>
761 const float desiredRatio = 0.95; // stop when pop average is 95% of best
762
763 GABoolean
764 GATerminateUponScoreConvergence(GAGeneticAlgorithm &amp; ga){
765 if(ga.statistics().current(GAStatistics::Mean) /
766 ga.statistics().current(GAStatistics::Maximum) &gt; desiredRatio)
767 return gaTrue;
768 else
769 return gaFalse;
770 }
771 </pre>
772 The third uses the population diversity as the criterion for stopping. If the diversity drops below a specified threshhold, the genetic algorithm will stop.
773 <pre>
774 const float thresh = 0.01; // stop when population diversity is below this
775
776 GABoolean
777 StopWhenNoDiversity(GAGeneticAlgorithm &amp; ga){
778 if(ga.statistics().current(GAStatistics::Diversity) &lt; thresh)
779 return gaTrue;
780 else
781 return gaFalse;
782 }
783 </pre>
784 A faster method of doing a nearly equivalent termination is to use the population's standard deviation as the stopping criterion (this method does not require comparisons of each individual). Notice that this judges diversity based upon the genome scores rather than their actual genetic diversity.
785 <pre>
786 const float thresh = 0.01; // stop when population deviation is below this
787
788 GABoolean
789 StopWhenNoDeviation(GAGeneticAlgorithm &amp; ga){
790 if(ga.statistics().current(GAStatistics::Deviation) &lt; thresh)
791 return gaTrue;
792 else
793 return gaFalse;
794 }
795 </pre>
796
797
798
799
800
801
802
803
804
805
806 <hr>
807 <small><i>Matthew Wall, 23 March 1996</i></small>
808
809 </body></html>