This file is indexed.

/usr/share/pyshared/pyevolve/GSimpleGA.py is in python-pyevolve 0.6~rc1+svn398+dfsg-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
"""

:mod:`GSimpleGA` -- the genetic algorithm by itself
=====================================================================

This module contains the GA Engine, the GA Engine class is responsible
for all the evolutionary process. It contains the GA Engine related
funtions, like the Termination Criteria functions for convergence analysis, etc.

Default Parameters
-------------------------------------------------------------

*Number of Generations*
  
   Default is 100 generations

*Mutation Rate*
   
   Default is 0.02, which represents 0.2%

*Crossover Rate*

   Default is 0.9, which represents 90%

*Elitism Replacement*

   Default is 1 individual

*Population Size*

   Default is 80 individuals

*Minimax*

   >>> Consts.minimaxType["maximize"]

   Maximize the evaluation function

*DB Adapter*

   Default is **None**

*Migration Adapter*

   Default is **None**
   
*Interactive Mode*

   Default is **True**

*Selector (Selection Method)*

   :func:`Selectors.GRankSelector`

   The Rank Selection method

Class
-------------------------------------------------------------

"""

from GPopulation  import GPopulation
from FunctionSlot import FunctionSlot
from Migration    import MigrationScheme
from GenomeBase   import GenomeBase
from DBAdapters   import DBBaseAdapter

import Consts
import Util

import random
import logging

from time  import time
from types import BooleanType
from sys   import platform as sys_platform
from sys   import stdout as sys_stdout

import code
import pyevolve

# Platform dependant code for the Interactive Mode
if sys_platform[:3] == "win":
   import msvcrt

def RawScoreCriteria(ga_engine):
   """ Terminate the evolution using the **bestrawscore** and **rounddecimal**
   parameter obtained from the individual

   Example:
      >>> genome.setParams(bestrawscore=0.00, rounddecimal=2)
      (...)
      >>> ga_engine.terminationCriteria.set(GSimpleGA.RawScoreCriteria)

   """
   ind = ga_engine.bestIndividual()
   bestRawScore = ind.getParam("bestrawscore")
   roundDecimal = ind.getParam("rounddecimal")

   if bestRawScore is None:
      Util.raiseException("you must specify the bestrawscore parameter", ValueError)

   if ga_engine.getMinimax() == Consts.minimaxType["maximize"]:
      if roundDecimal is not None:
         return round(bestRawScore, roundDecimal) <= round(ind.score, roundDecimal)
      else:
         return bestRawScore <= ind.score
   else:
      if roundDecimal is not None:
         return round(bestRawScore, roundDecimal) >= round(ind.score, roundDecimal)
      else:
         return bestRawScore >= ind.score

def ConvergenceCriteria(ga_engine):
   """ Terminate the evolution when the population have converged

   Example:
      >>> ga_engine.terminationCriteria.set(GSimpleGA.ConvergenceCriteria)

   """
   pop = ga_engine.getPopulation()
   return pop[0] == pop[len(pop)-1]
   
def RawStatsCriteria(ga_engine):
   """ Terminate the evolution based on the raw stats

   Example:
      >>> ga_engine.terminationCriteria.set(GSimpleGA.RawStatsCriteria)

   """
   stats = ga_engine.getStatistics()
   if stats["rawMax"] == stats["rawMin"]:
      if stats["rawAve"] == stats["rawMax"]:
         return True
   return False

def FitnessStatsCriteria(ga_engine):
   """ Terminate the evoltion based on the fitness stats

   Example:
      >>> ga_engine.terminationCriteria.set(GSimpleGA.FitnessStatsCriteria)


   """
   stats = ga_engine.getStatistics()
   if stats["fitMax"] == stats["fitMin"]:
      if stats["fitAve"] == stats["fitMax"]:
         return True
   return False

class GSimpleGA:
   """ GA Engine Class - The Genetic Algorithm Core

   Example:
      >>> ga = GSimpleGA.GSimpleGA(genome)
      >>> ga.selector.set(Selectors.GRouletteWheel)
      >>> ga.setGenerations(120)
      >>> ga.terminationCriteria.set(GSimpleGA.ConvergenceCriteria)

   :param genome: the :term:`Sample Genome`
   :param interactiveMode: this flag enables the Interactive Mode, the default is True
   :param seed: the random seed value

   .. note:: if you use the same random seed, all the runs of algorithm will be the same

   """

   selector = None
   """ This is the function slot for the selection method
   if you want to change the default selector, you must do this: ::

      ga_engine.selector.set(Selectors.GRouletteWheel) """

   stepCallback = None
   """ This is the :term:`step callback function` slot,
   if you want to set the function, you must do this: ::
      
      def your_func(ga_engine):
         # Here you have access to the GA Engine
         return False

      ga_engine.stepCallback.set(your_func)
      
   now *"your_func"* will be called every generation.
   When this function returns True, the GA Engine will stop the evolution and show
   a warning, if is False, the evolution continues.
   """

   terminationCriteria = None
   """ This is the termination criteria slot, if you want to set one
   termination criteria, you must do this: ::

      ga_engine.terminationCriteria.set(GSimpleGA.ConvergenceCriteria)
      
   Now, when you run your GA, it will stop when the population converges.

   There are those termination criteria functions: :func:`GSimpleGA.RawScoreCriteria`, :func:`GSimpleGA.ConvergenceCriteria`, :func:`GSimpleGA.RawStatsCriteria`, :func:`GSimpleGA.FitnessStatsCriteria`

   But you can create your own termination function, this function receives
   one parameter which is the GA Engine, follows an example: ::

      def ConvergenceCriteria(ga_engine):
         pop = ga_engine.getPopulation()
         return pop[0] == pop[len(pop)-1]

   When this function returns True, the GA Engine will stop the evolution and show
   a warning, if is False, the evolution continues, this function is called every
   generation.
   """

   def __init__(self, genome, seed=None, interactiveMode=True):
      """ Initializator of GSimpleGA """
      if seed: random.seed(seed)

      if type(interactiveMode) != BooleanType:
         Util.raiseException("Interactive Mode option must be True or False", TypeError)
      
      if not isinstance(genome, GenomeBase):
         Util.raiseException("The genome must be a GenomeBase subclass", TypeError)

      self.internalPop  = GPopulation(genome)
      self.nGenerations = Consts.CDefGAGenerations
      self.pMutation    = Consts.CDefGAMutationRate
      self.pCrossover   = Consts.CDefGACrossoverRate
      self.nElitismReplacement = Consts.CDefGAElitismReplacement
      self.setPopulationSize(Consts.CDefGAPopulationSize)
      self.minimax      = Consts.minimaxType["maximize"]
      self.elitism      = True

      # Adapters
      self.dbAdapter        = None
      self.migrationAdapter = None
      
      self.time_init       = None
      self.interactiveMode = interactiveMode
      self.interactiveGen  = -1
      self.GPMode = False

      self.selector            = FunctionSlot("Selector")
      self.stepCallback        = FunctionSlot("Generation Step Callback")
      self.terminationCriteria = FunctionSlot("Termination Criteria")
      self.selector.set(Consts.CDefGASelector)
      self.allSlots            = [ self.selector, self.stepCallback, self.terminationCriteria ]

      self.internalParams = {}

      self.currentGeneration = 0

      # GP Testing
      for classes in Consts.CDefGPGenomes:
         if  isinstance(self.internalPop.oneSelfGenome, classes):
            self.setGPMode(True)
            break
      
      logging.debug("A GA Engine was created, nGenerations=%d", self.nGenerations)

   def setGPMode(self, bool_value):
      """ Sets the Genetic Programming mode of the GA Engine
      
      :param bool_value: True or False
      """
      self.GPMode = bool_value

   def getGPMode(self):
      """ Get the Genetic Programming mode of the GA Engine
      
      :rtype: True or False
      """
      return self.GPMode

   def __call__(self, *args, **kwargs):
      """ A method to implement a callable object

      Example:
         >>> ga_engine(freq_stats=10)
         
      .. versionadded:: 0.6
         The callable method.
      """
      if kwargs.get("freq_stats", None):
         return self.evolve(kwargs.get("freq_stats"))
      else:
         return self.evolve()

   def setParams(self, **args):
      """ Set the internal params

      Example:
         >>> ga.setParams(gp_terminals=['x', 'y'])


      :param args: params to save

      ..versionaddd:: 0.6
         Added the *setParams* method.
      """
      self.internalParams.update(args)
   
   def getParam(self, key, nvl=None):
      """ Gets an internal parameter

      Example:
         >>> ga.getParam("gp_terminals")
         ['x', 'y']

      :param key: the key of param
      :param nvl: if the key doesn't exist, the nvl will be returned

      ..versionaddd:: 0.6
         Added the *getParam* method.
      """
      return self.internalParams.get(key, nvl)

   def setInteractiveGeneration(self, generation):
      """ Sets the generation in which the GA must enter in the
      Interactive Mode
      
      :param generation: the generation number, use "-1" to disable

      .. versionadded::0.6
         The *setInteractiveGeneration* method.
      """
      if generation < -1:
         Util.raiseException("Generation must be >= -1", ValueError)
      self.interactiveGen = generation

   def getInteractiveGeneration(self):
      """ returns the generation in which the GA must enter in the
      Interactive Mode
      
      :rtype: the generation number or -1 if not set

      .. versionadded::0.6
         The *getInteractiveGeneration* method.
      """
      return self.interactiveGen

   def setElitismReplacement(self, numreplace):
      """ Set the number of best individuals to copy to the next generation on the elitism

      :param numreplace: the number of individuals
      
      .. versionadded:: 0.6
         The *setElitismReplacement* method.

      """
      if numreplace < 1:
         Util.raiseException("Replacement number must be >= 1", ValueError)
      self.nElitismReplacement = numreplace


   def setInteractiveMode(self, flag=True):
      """ Enable/disable the interactive mode
      
      :param flag: True or False

      .. versionadded: 0.6
         The *setInteractiveMode* method.
      
      """
      if type(flag) != BooleanType:
         Util.raiseException("Interactive Mode option must be True or False", TypeError)
      self.interactiveMode = flag


   def __repr__(self):
      """ The string representation of the GA Engine """
      ret =  "- GSimpleGA\n"
      ret += "\tGP Mode:\t\t %s\n" % self.getGPMode()
      ret += "\tPopulation Size:\t %d\n" % (self.internalPop.popSize,)
      ret += "\tGenerations:\t\t %d\n" % (self.nGenerations,)
      ret += "\tCurrent Generation:\t %d\n" % (self.currentGeneration,)
      ret += "\tMutation Rate:\t\t %.2f\n" % (self.pMutation,)
      ret += "\tCrossover Rate:\t\t %.2f\n" % (self.pCrossover,)
      ret += "\tMinimax Type:\t\t %s\n" % (Consts.minimaxType.keys()[Consts.minimaxType.values().index(self.minimax)].capitalize(),)
      ret += "\tElitism:\t\t %s\n" % (self.elitism,)
      ret += "\tElitism Replacement:\t %d\n" % (self.nElitismReplacement,)
      ret += "\tDB Adapter:\t\t %s\n" % (self.dbAdapter,)
      for slot in self.allSlots:
         ret+= "\t" + slot.__repr__()
      ret+="\n"
      return ret
   
   def setMultiProcessing(self, flag=True, full_copy=False):
      """ Sets the flag to enable/disable the use of python multiprocessing module.
      Use this option when you have more than one core on your CPU and when your
      evaluation function is very slow.

      Pyevolve will automaticly check if your Python version has **multiprocessing**
      support and if you have more than one single CPU core. If you don't have support
      or have just only one core, Pyevolve will not use the **multiprocessing**
      feature.

      Pyevolve uses the **multiprocessing** to execute the evaluation function over
      the individuals, so the use of this feature will make sense if you have a
      truly slow evaluation function (which is commom in GAs).      

      The parameter "full_copy" defines where the individual data should be copied back
      after the evaluation or not. This parameter is useful when you change the
      individual in the evaluation function.
      
      :param flag: True (default) or False
      :param full_copy: True or False (default)

      .. warning:: Use this option only when your evaluation function is slow, so you'll
                   get a good tradeoff between the process communication speed and the
                   parallel evaluation. The use of the **multiprocessing** doesn't means
                   always a better performance.

      .. note:: To enable the multiprocessing option, you **MUST** add the *__main__* check
                on your application, otherwise, it will result in errors. See more on the
                `Python Docs <http://docs.python.org/library/multiprocessing.html#multiprocessing-programming>`__
                site.

      .. versionadded:: 0.6
         The `setMultiProcessing` method.

      """
      if type(flag) != BooleanType:
         Util.raiseException("Multiprocessing option must be True or False", TypeError)

      if type(full_copy) != BooleanType:
         Util.raiseException("Multiprocessing 'full_copy' option must be True or False", TypeError)

      self.internalPop.setMultiProcessing(flag, full_copy)

   def setMigrationAdapter(self, migration_adapter=None):
      """ Sets the Migration Adapter

      .. versionadded:: 0.6
         The `setMigrationAdapter` method.
      """
      if (migration_adapter is not None) and (not isinstance(migration_adapter, MigrationScheme)):
         Util.raiseException("The Migration Adapter must be a MigrationScheme subclass", TypeError)

      self.migrationAdapter = migration_adapter
      if self.migrationAdapter is not None:
         self.migrationAdapter.setGAEngine(self)

   def setDBAdapter(self, dbadapter=None):
      """ Sets the DB Adapter of the GA Engine
      
      :param dbadapter: one of the :mod:`DBAdapters` classes instance

      .. warning:: the use the of a DB Adapter can reduce the speed performance of the
                   Genetic Algorithm.
      """
      if (dbadapter is not None) and (not isinstance(dbadapter, DBBaseAdapter)):
         Util.raiseException("The DB Adapter must be a DBBaseAdapter subclass", TypeError)
      self.dbAdapter = dbadapter

   def setPopulationSize(self, size):
      """ Sets the population size, calls setPopulationSize() of GPopulation

      :param size: the population size

      .. note:: the population size must be >= 2

      """
      if size < 2:
         Util.raiseException("population size must be >= 2", ValueError)
      self.internalPop.setPopulationSize(size)

   def setSortType(self, sort_type):
      """ Sets the sort type, Consts.sortType["raw"]/Consts.sortType["scaled"]

      Example:
         >>> ga_engine.setSortType(Consts.sortType["scaled"])

      :param sort_type: the Sort Type

      """
      if sort_type not in Consts.sortType.values():
         Util.raiseException("sort type must be a Consts.sortType type", TypeError)
      self.internalPop.sortType = sort_type

   def setMutationRate(self, rate):
      """ Sets the mutation rate, between 0.0 and 1.0

      :param rate: the rate, between 0.0 and 1.0

      """
      if (rate>1.0) or (rate<0.0):
         Util.raiseException("Mutation rate must be >= 0.0 and <= 1.0", ValueError)
      self.pMutation = rate

   def setCrossoverRate(self, rate):
      """ Sets the crossover rate, between 0.0 and 1.0

      :param rate: the rate, between 0.0 and 1.0

      """
      if (rate>1.0) or (rate<0.0):
         Util.raiseException("Crossover rate must be >= 0.0 and <= 1.0", ValueError)
      self.pCrossover = rate

   def setGenerations(self, num_gens):
      """ Sets the number of generations to evolve

      :param num_gens: the number of generations

      """
      if num_gens < 1:
         Util.raiseException("Number of generations must be >= 1", ValueError)
      self.nGenerations = num_gens

   def getGenerations(self):
      """ Return the number of generations to evolve

      :rtype: the number of generations

      .. versionadded:: 0.6
         Added the *getGenerations* method
      """
      return self.nGenerations

   def getMinimax(self):
      """ Gets the minimize/maximize mode

      :rtype: the Consts.minimaxType type

      """
      return self.minimax

   def setMinimax(self, mtype):
      """ Sets the minimize/maximize mode, use Consts.minimaxType

      :param mtype: the minimax mode, from Consts.minimaxType

      """
      if mtype not in Consts.minimaxType.values():
         Util.raiseException("Minimax must be maximize or minimize", TypeError)
      self.minimax = mtype

   def getCurrentGeneration(self):
      """ Gets the current generation

      :rtype: the current generation

      """
      return self.currentGeneration

   def setElitism(self, flag):
      """ Sets the elitism option, True or False

      :param flag: True or False

      """
      if type(flag) != BooleanType:
         Util.raiseException("Elitism option must be True or False", TypeError)
      self.elitism = flag

   def getDBAdapter(self):
      """ Gets the DB Adapter of the GA Engine

      :rtype: a instance from one of the :mod:`DBAdapters` classes

      """
      return self.dbAdapter

   def bestIndividual(self):
      """ Returns the population best individual

      :rtype: the best individual

      """
      return self.internalPop.bestRaw()

   def __gp_catch_functions(self, prefix):
      """ Internally used to catch functions with some specific prefix
      as non-terminals of the GP core """
      import __main__ as mod_main

      function_set = {}

      main_dict = mod_main.__dict__
      for obj, addr in main_dict.items():
         if obj[0:len(prefix)] == prefix:
            try:
               op_len = addr.func_code.co_argcount
            except:
               continue
            function_set[obj] = op_len

      if len(function_set) <= 0:
         Util.raiseException("No function set found using function prefix '%s' !" % prefix, ValueError)

      self.setParams(gp_function_set=function_set)

   def initialize(self):
      """ Initializes the GA Engine. Create and initialize population """
      self.internalPop.create(minimax=self.minimax)
      self.internalPop.initialize(ga_engine=self)
      logging.debug("The GA Engine was initialized !")      

   def getPopulation(self):
      """ Return the internal population of GA Engine

      :rtype: the population (:class:`GPopulation.GPopulation`)

      """
      return self.internalPop
   
   def getStatistics(self):
      """ Gets the Statistics class instance of current generation

      :rtype: the statistics instance (:class:`Statistics.Statistics`)

      """
      return self.internalPop.getStatistics()

   def step(self):
      """ Just do one step in evolution, one generation """
      genomeMom = None
      genomeDad = None

      newPop = GPopulation(self.internalPop)
      logging.debug("Population was cloned.")
      
      size_iterate = len(self.internalPop)

      # Odd population size
      if size_iterate % 2 != 0: size_iterate -= 1

      crossover_empty = self.select(popID=self.currentGeneration).crossover.isEmpty()
      
      for i in xrange(0, size_iterate, 2):
         genomeMom = self.select(popID=self.currentGeneration)
         genomeDad = self.select(popID=self.currentGeneration)
         
         if not crossover_empty and self.pCrossover >= 1.0:
            for it in genomeMom.crossover.applyFunctions(mom=genomeMom, dad=genomeDad, count=2):
               (sister, brother) = it
         else:
            if not crossover_empty and Util.randomFlipCoin(self.pCrossover):
               for it in genomeMom.crossover.applyFunctions(mom=genomeMom, dad=genomeDad, count=2):
                  (sister, brother) = it
            else:
               sister = genomeMom.clone()
               brother = genomeDad.clone()

         sister.mutate(pmut=self.pMutation, ga_engine=self)
         brother.mutate(pmut=self.pMutation, ga_engine=self)

         newPop.internalPop.append(sister)
         newPop.internalPop.append(brother)

      if len(self.internalPop) % 2 != 0:
         genomeMom = self.select(popID=self.currentGeneration)
         genomeDad = self.select(popID=self.currentGeneration)

         if Util.randomFlipCoin(self.pCrossover):
            for it in genomeMom.crossover.applyFunctions(mom=genomeMom, dad=genomeDad, count=1):
               (sister, brother) = it
         else:
            sister = random.choice([genomeMom, genomeDad])
            sister = sister.clone()
            sister.mutate(pmut=self.pMutation, ga_engine=self)

         newPop.internalPop.append(sister)

      logging.debug("Evaluating the new created population.")
      newPop.evaluate()

      if self.elitism:
         logging.debug("Doing elitism.")
         if self.getMinimax() == Consts.minimaxType["maximize"]:
            for i in xrange(self.nElitismReplacement):
               if self.internalPop.bestRaw(i).score > newPop.bestRaw(i).score:
                  newPop[len(newPop)-1-i] = self.internalPop.bestRaw(i)
         elif self.getMinimax() == Consts.minimaxType["minimize"]:
            for i in xrange(self.nElitismReplacement):
               if self.internalPop.bestRaw(i).score < newPop.bestRaw(i).score:
                  newPop[len(newPop)-1-i] = self.internalPop.bestRaw(i)

      self.internalPop = newPop
      self.internalPop.sort()

      logging.debug("The generation %d was finished.", self.currentGeneration)

      self.currentGeneration += 1

      return (self.currentGeneration == self.nGenerations)
   
   def printStats(self):
      """ Print generation statistics

      :rtype: the printed statistics as string

      .. versionchanged:: 0.6
         The return of *printStats* method.
      """
      percent = self.currentGeneration * 100 / float(self.nGenerations)
      message = "Gen. %d (%.2f%%):" % (self.currentGeneration, percent)
      logging.info(message)
      print message,
      sys_stdout.flush()
      self.internalPop.statistics()
      stat_ret = self.internalPop.printStats()
      return message + stat_ret

   def printTimeElapsed(self):
      """ Shows the time elapsed since the begin of evolution """
      total_time = time()-self.time_init
      print "Total time elapsed: %.3f seconds." % total_time
      return total_time
   
   def dumpStatsDB(self):
      """ Dumps the current statistics to database adapter """
      logging.debug("Dumping stats to the DB Adapter")
      self.internalPop.statistics()
      self.dbAdapter.insert(self)

   def evolve(self, freq_stats=0):
      """ Do all the generations until the termination criteria, accepts
      the freq_stats (default is 0) to dump statistics at n-generation

      Example:
         >>> ga_engine.evolve(freq_stats=10)
         (...)

      :param freq_stats: if greater than 0, the statistics will be
                         printed every freq_stats generation.
      :rtype: returns the best individual of the evolution

      .. versionadded:: 0.6
         the return of the best individual

      """

      stopFlagCallback = False
      stopFlagTerminationCriteria = False

      self.time_init = time()

      logging.debug("Starting the DB Adapter and the Migration Adapter if any")
      if self.dbAdapter: self.dbAdapter.open(self)
      if self.migrationAdapter: self.migrationAdapter.start()


      if self.getGPMode():
         gp_function_prefix = self.getParam("gp_function_prefix")
         if gp_function_prefix is not None:
            self.__gp_catch_functions(gp_function_prefix)

      self.initialize()
      self.internalPop.evaluate()
      self.internalPop.sort()
      logging.debug("Starting loop over evolutionary algorithm.")

      try:      
         while True:
            if self.migrationAdapter:
               logging.debug("Migration adapter: exchange")
               self.migrationAdapter.exchange()
               self.internalPop.clearFlags()
               self.internalPop.sort()

            if not self.stepCallback.isEmpty():
               for it in self.stepCallback.applyFunctions(self):
                  stopFlagCallback = it

            if not self.terminationCriteria.isEmpty():
               for it in self.terminationCriteria.applyFunctions(self):
                  stopFlagTerminationCriteria = it

            if freq_stats:
               if (self.currentGeneration % freq_stats == 0) or (self.getCurrentGeneration() == 0):
                  self.printStats()

            if self.dbAdapter:
               if self.currentGeneration % self.dbAdapter.getStatsGenFreq() == 0:
                  self.dumpStatsDB()

            if stopFlagTerminationCriteria:
               logging.debug("Evolution stopped by the Termination Criteria !")
               if freq_stats:
                  print "\n\tEvolution stopped by Termination Criteria function !\n"
               break

            if stopFlagCallback:
               logging.debug("Evolution stopped by Step Callback function !")
               if freq_stats:
                  print "\n\tEvolution stopped by Step Callback function !\n"
               break

            if self.interactiveMode:
               if sys_platform[:3] == "win":
                  if msvcrt.kbhit():
                     if ord(msvcrt.getch()) == Consts.CDefESCKey:
                        print "Loading modules for Interactive Mode...",
                        logging.debug("Windows Interactive Mode key detected ! generation=%d", self.getCurrentGeneration())
                        from pyevolve import Interaction
                        print " done !"
                        interact_banner = "## Pyevolve v.%s - Interactive Mode ##\nPress CTRL-Z to quit interactive mode." % (pyevolve.__version__,)
                        session_locals = { "ga_engine"  : self,
                                           "population" : self.getPopulation(),
                                           "pyevolve"   : pyevolve,
                                           "it"         : Interaction}
                        print
                        code.interact(interact_banner, local=session_locals)

               if (self.getInteractiveGeneration() >= 0) and (self.getInteractiveGeneration() == self.getCurrentGeneration()):
                        print "Loading modules for Interactive Mode...",
                        logging.debug("Manual Interactive Mode key detected ! generation=%d", self.getCurrentGeneration())
                        from pyevolve import Interaction
                        print " done !"
                        interact_banner = "## Pyevolve v.%s - Interactive Mode ##" % (pyevolve.__version__,)
                        session_locals = { "ga_engine"  : self,
                                           "population" : self.getPopulation(),
                                           "pyevolve"   : pyevolve,
                                           "it"         : Interaction}
                        print
                        code.interact(interact_banner, local=session_locals)

            if self.step(): break

      except KeyboardInterrupt:
         logging.debug("CTRL-C detected, finishing evolution.")
         if freq_stats: print "\n\tA break was detected, you have interrupted the evolution !\n"

      if freq_stats != 0:
         self.printStats()
         self.printTimeElapsed()

      if self.dbAdapter:
         logging.debug("Closing the DB Adapter")
         if not (self.currentGeneration % self.dbAdapter.getStatsGenFreq() == 0):
            self.dumpStatsDB()
         self.dbAdapter.commitAndClose()
   
      if self.migrationAdapter:
         logging.debug("Closing the Migration Adapter")
         if freq_stats: print "Stopping the migration adapter... ",
         self.migrationAdapter.stop()
         if freq_stats: print "done !"

      return self.bestIndividual()

   def select(self, **args):
      """ Select one individual from population

      :param args: this parameters will be sent to the selector

      """
      for it in self.selector.applyFunctions(self.internalPop, **args):
         return it