This file is indexed.

/usr/lib/python2.7/dist-packages/pyevolve/DBAdapters.py is in python-pyevolve 0.6~rc1+svn398+dfsg-6.

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
"""
:mod:`DBAdapters` -- database adapters for statistics
=====================================================================

.. warning:: the use the of a DB Adapter can reduce the performance of the
             Genetic Algorithm.

Pyevolve have a feature in which you can save the statistics of every
generation in a database, file or call an URL with the statistics as param.
You can use the database to plot evolution statistics graphs later. In this
module, you'll find the adapters above cited.

.. seealso::

   Method :meth:`GSimpleGA.GSimpleGA.setDBAdapter`
      DB Adapters are set in the GSimpleGA Class.

"""

from pyevolve import __version__
import Consts
import Util
import logging
import types
import datetime
import Statistics


class DBBaseAdapter:
   """ DBBaseAdapter Class - The base class for all DB Adapters

   If you want to create your own DB Adapter, you must subclass this
   class.

   :param frequency: the the generational dump frequency

   .. versionadded:: 0.6
      Added the :class:`DBBaseAdapter` class.
   """
   def __init__(self, frequency, identify):
      """ The class constructor """
      self.statsGenFreq = frequency

      if identify is None:
         self.identify = datetime.datetime.strftime(datetime.datetime.now(), "%d/%m/%y-%H:%M")
      else:
         self.identify = identify

   def setIdentify(self, identify):
      """ Sets the identify of the statistics
      
      :param identify: the id string
      """
      if identify is None:
         self.identify = datetime.datetime.strftime(datetime.datetime.now(), "%d/%m/%y-%H:%M")
      else:
         self.identify = identify

   def getIdentify(self):
      """ Return the statistics identify
      
      :rtype: identify string
      """
      return self.identify

   def getStatsGenFreq(self):
      """ Returns the frequency of statistical dump
      
      :rtype: the generation interval of statistical dump
      """
      return self.statsGenFreq

   def setStatsGenFreq(self, statsGenFreq):
      """ Set the frequency of statistical dump
      
      :param statsGenFreq: the generation interval of statistical dump
      """
      self.statsGenFreq = statsGenFreq

   def open(self, ga_engine):
      """ This method is called one time to do the initialization of
      the DB Adapter

      :param ga_engine: the GA Engine
      """
      pass

   def commitAndClose(self):
      """ This method is called at the end of the evolution, to closes the
      DB Adapter and commit the changes """
      pass

   def insert(self, ga_engine):
      """ Insert the stats

      :param ga_engine: the GA Engine
      """
      Util.raiseException("This method is not implemented on the ABC", NotImplementedError)

class DBFileCSV(DBBaseAdapter):
   """ DBFileCSV Class - Adapter to dump statistics in CSV format

   Inheritance diagram for :class:`DBAdapters.DBFileCSV`:

   .. inheritance-diagram:: DBAdapters.DBFileCSV

   Example:
      >>> adapter = DBFileCSV(filename="file.csv", identify="run_01",
                              frequency = 1, reset = True)

      :param filename: the CSV filename
      :param identify: the identify of the run
      :param frequency: the generational dump frequency
      :param reset: if is True, the file old data will be overwrite with the new

   .. versionadded:: 0.6
      Removed the stub methods and subclassed the :class:`DBBaseAdapter` class.

   """
   def __init__(self, filename=Consts.CDefCSVFileName, identify=None,
                frequency = Consts.CDefCSVFileStatsGenFreq, reset=True):
      """ The creator of DBFileCSV Class """

      DBBaseAdapter.__init__(self, frequency, identify)
      
      self.csvmod = None

      self.filename = filename
      self.csvWriter = None
      self.fHandle = None
      self.reset = reset

   def __repr__(self):
      """ The string representation of adapter """
      ret = "DBFileCSV DB Adapter [File='%s', identify='%s']" % (self.filename, self.getIdentify())
      return ret

   def open(self, ga_engine):
      """ Open the CSV file or creates a new file

      :param ga_engine: the GA Engine

      .. versionchanged:: 0.6
         The method now receives the *ga_engine* parameter.
      """
      if self.csvmod is None:
         logging.debug("Loading the csv module...")
         self.csvmod = Util.importSpecial("csv")

      logging.debug("Opening the CSV file to dump statistics [%s]", self.filename)
      if self.reset: open_mode = "w"
      else: open_mode = "a"
      self.fHandle = open(self.filename, open_mode)
      self.csvWriter = self.csvmod.writer(self.fHandle, delimiter=';')

   def close(self):
      """ Closes the CSV file handle """
      logging.debug("Closing the CSV file [%s]", self.filename)
      if self.fHandle:
         self.fHandle.close()

   def commitAndClose(self):
      """ Commits and closes """
      self.close()

   def insert(self, ga_engine):
      """ Inserts the stats into the CSV file

      :param ga_engine: the GA Engine

      .. versionchanged:: 0.6
         The method now receives the *ga_engine* parameter.
      """
      stats = ga_engine.getStatistics()
      generation = ga_engine.getCurrentGeneration()
      line = [self.getIdentify(), generation]
      line.extend(stats.asTuple())
      self.csvWriter.writerow(line)

class DBURLPost(DBBaseAdapter):
   """ DBURLPost Class - Adapter to call an URL with statistics

   Inheritance diagram for :class:`DBAdapters.DBURLPost`:

   .. inheritance-diagram:: DBAdapters.DBURLPost

   Example:
      >>> dbadapter = DBURLPost(url="http://localhost/post.py", identify="test")

   The parameters that will be sent is all the statistics described in the :class:`Statistics.Statistics`
   class, and the parameters:
   
   **generation**
      The generation of the statistics

   **identify**
      The id specified by user

   .. note:: see the :class:`Statistics.Statistics` documentation.

   :param url: the URL to be used
   :param identify: the identify of the run
   :param frequency: the generational dump frequency
   :param post: if True, the POST method will be used, otherwise GET will be used.

   .. versionadded:: 0.6
      Removed the stub methods and subclassed the :class:`DBBaseAdapter` class.
   """
   
   def __init__(self, url, identify=None,
                frequency = Consts.CDefURLPostStatsGenFreq, post=True):
      """ The creator of the DBURLPost Class. """

      DBBaseAdapter.__init__(self, frequency, identify)
      self.urllibmod = None

      self.url = url
      self.post = post

   def __repr__(self):
      """ The string representation of adapter """
      ret = "DBURLPost DB Adapter [URL='%s', identify='%s']" % (self.url, self.getIdentify())
      return ret

   def open(self, ga_engine):
      """ Load the modules needed

      :param ga_engine: the GA Engine

      .. versionchanged:: 0.6
         The method now receives the *ga_engine* parameter.
      """
      if self.urllibmod is None:
         logging.debug("Loading urllib module...")
         self.urllibmod = Util.importSpecial("urllib")

   def insert(self, ga_engine):
      """ Sends the data to the URL using POST or GET

      :param ga_engine: the GA Engine

      .. versionchanged:: 0.6
         The method now receives the *ga_engine* parameter.
      """
      logging.debug("Sending http request to %s.", self.url)
      stats = ga_engine.getStatistics()
      response = None
      params = stats.internalDict.copy()
      params["generation"] = ga_engine.getCurrentGeneration()
      params["identify"] = self.getIdentify()
      if self.post: # POST
         response = self.urllibmod.urlopen(self.url, self.urllibmod.urlencode(params))
      else: # GET
         response = self.urllibmod.urlopen(self.url + "?%s" % (self.urllibmod.urlencode(params)))
      if response: response.close()

class DBSQLite(DBBaseAdapter):
   """ DBSQLite Class - Adapter to dump data in SQLite3 database format
   
   Inheritance diagram for :class:`DBAdapters.DBSQLite`:

   .. inheritance-diagram:: DBAdapters.DBSQLite

   Example:
      >>> dbadapter = DBSQLite(identify="test")

   When you run some GA for the first time, you need to create the database, for this, you
   must use the *resetDB* parameter:

      >>> dbadapter = DBSQLite(identify="test", resetDB=True)

   This parameter will erase all the database tables and will create the new ones.
   The *resetDB* parameter is different from the *resetIdentify* parameter, the *resetIdentify*
   only erases the rows with the same "identify" name.   

   :param dbname: the database filename
   :param identify: the identify if the run
   :param resetDB: if True, the database structure will be recreated
   :param resetIdentify: if True, the identify with the same name will be overwrite with new data
   :param frequency: the generational dump frequency
   :param commit_freq: the commit frequency
   """

   def __init__(self, dbname=Consts.CDefSQLiteDBName, identify=None, resetDB=False,
                resetIdentify=True, frequency=Consts.CDefSQLiteStatsGenFreq,
                commit_freq=Consts.CDefSQLiteStatsCommitFreq):
      """ The creator of the DBSQLite Class """

      DBBaseAdapter.__init__(self, frequency, identify)

      self.sqlite3mod = None
      self.connection = None
      self.resetDB = resetDB
      self.resetIdentify = resetIdentify
      self.dbName = dbname
      self.typeDict = { types.FloatType : "real" }
      self.cursorPool = None
      self.commitFreq = commit_freq

   def __repr__(self):
      """ The string representation of adapter """
      ret = "DBSQLite DB Adapter [File='%s', identify='%s']" % (self.dbName, self.getIdentify())
      return ret

   def open(self, ga_engine):
      """ Open the database connection

      :param ga_engine: the GA Engine

      .. versionchanged:: 0.6
         The method now receives the *ga_engine* parameter.
      """
      if self.sqlite3mod is None:
         logging.debug("Loading sqlite3 module...")
         self.sqlite3mod = Util.importSpecial("sqlite3")

      logging.debug("Opening database, dbname=%s", self.dbName)
      self.connection = self.sqlite3mod.connect(self.dbName)

      temp_stats = Statistics.Statistics()

      if self.resetDB:
         self.resetStructure(Statistics.Statistics())

      self.createStructure(temp_stats)

      if self.resetIdentify:
         self.resetTableIdentify()

   def commitAndClose(self):
      """ Commit changes on database and closes connection """
      self.commit()
      self.close()

   def close(self):
      """ Close the database connection """
      logging.debug("Closing database.")
      if self.cursorPool:
         self.cursorPool.close()
         self.cursorPool = None
      self.connection.close()

   def commit(self):
      """ Commit changes to database """
      logging.debug("Commiting changes to database.")
      self.connection.commit()

   def getCursor(self):
      """ Return a cursor from the pool

      :rtype: the cursor

      """
      if not self.cursorPool:
         logging.debug("Creating new cursor for database...")
         self.cursorPool = self.connection.cursor()
         return self.cursorPool
      else:
         return self.cursorPool

   def createStructure(self, stats):
      """ Create table using the Statistics class structure

      :param stats: the statistics object

      """
      c = self.getCursor()
      pstmt = "create table if not exists %s(identify text, generation integer, " % (Consts.CDefSQLiteDBTable)
      for k, v in stats.items():
         pstmt += "%s %s, " % (k, self.typeDict[type(v)])
      pstmt = pstmt[:-2] + ")"
      logging.debug("Creating table %s: %s.", Consts.CDefSQLiteDBTable, pstmt)
      c.execute(pstmt)

      pstmt = """create table if not exists %s(identify text, generation integer,
              individual integer, fitness real, raw real)""" % (Consts.CDefSQLiteDBTablePop)
      logging.debug("Creating table %s: %s.", Consts.CDefSQLiteDBTablePop, pstmt)
      c.execute(pstmt)
      self.commit()

   def resetTableIdentify(self):
      """ Delete all records on the table with the same Identify """
      c = self.getCursor()
      stmt  = "delete from %s where identify = ?" % (Consts.CDefSQLiteDBTable)
      stmt2 = "delete from %s where identify = ?" % (Consts.CDefSQLiteDBTablePop)

      logging.debug("Erasing data from the tables with the identify = %s", self.getIdentify())
      try:
         c.execute(stmt, (self.getIdentify(),))
         c.execute(stmt2, (self.getIdentify(),))
      except self.sqlite3mod.OperationalError, expt:
         if str(expt).find("no such table") >= 0:
            print "\n ## The DB Adapter can't find the tables ! Consider enable the parameter resetDB ! ##\n"

      self.commit()


   def resetStructure(self, stats):
      """ Deletes de current structure and calls createStructure

      :param stats: the statistics object

      """
      logging.debug("Reseting structure, droping table and creating new empty table.")
      c = self.getCursor()
      c.execute("drop table if exists %s" % (Consts.CDefSQLiteDBTable,))
      c.execute("drop table if exists %s" % (Consts.CDefSQLiteDBTablePop,))
      self.commit()
      self.createStructure(stats)
      
   def insert(self, ga_engine):
      """ Inserts the statistics data to database

      :param ga_engine: the GA Engine

      .. versionchanged:: 0.6
         The method now receives the *ga_engine* parameter.
      """
      stats      = ga_engine.getStatistics()
      population = ga_engine.getPopulation()
      generation = ga_engine.getCurrentGeneration()

      c = self.getCursor()
      pstmt = "insert into %s values (?, ?, " % (Consts.CDefSQLiteDBTable)
      for i in xrange(len(stats)):
         pstmt += "?, "
      pstmt = pstmt[:-2] + ")" 
      c.execute(pstmt, (self.getIdentify(), generation) + stats.asTuple())

      pstmt = "insert into %s values(?, ?, ?, ?, ?)" % (Consts.CDefSQLiteDBTablePop,)
      tups = []
      for i in xrange(len(population)):
         ind = population[i]
         tups.append((self.getIdentify(), generation, i, ind.fitness, ind.score))

      c.executemany(pstmt, tups)
      if (generation % self.commitFreq == 0):
         self.commit()

class DBXMLRPC(DBBaseAdapter):
   """ DBXMLRPC Class - Adapter to dump statistics to a XML Remote Procedure Call

   Inheritance diagram for :class:`DBAdapters.DBXMLRPC`:

   .. inheritance-diagram:: DBAdapters.DBXMLRPC

   Example:
      >>> adapter = DBXMLRPC(url="http://localhost:8000/", identify="run_01",
                             frequency = 1)

      :param url: the URL of the XML RPC
      :param identify: the identify of the run
      :param frequency: the generational dump frequency


   .. note:: The XML RPC Server must implement the *insert* method, wich receives
             a python dictionary as argument.
   
   Example of an server in Python: ::

      import xmlrpclib
      from SimpleXMLRPCServer import SimpleXMLRPCServer

      def insert(l):
          print "Received statistics: %s" % l

      server = SimpleXMLRPCServer(("localhost", 8000), allow_none=True)
      print "Listening on port 8000..."
      server.register_function(insert, "insert")
      server.serve_forever()

   .. versionadded:: 0.6
      The :class:`DBXMLRPC` class.

   """
   def __init__(self, url, identify=None, frequency = Consts.CDefXMLRPCStatsGenFreq):
      """ The creator of DBXMLRPC Class """

      DBBaseAdapter.__init__(self, frequency, identify)
      self.xmlrpclibmod = None

      self.url = url
      self.proxy = None

   def __repr__(self):
      """ The string representation of adapter """
      ret = "DBXMLRPC DB Adapter [URL='%s', identify='%s']" % (self.url, self.getIdentify())
      return ret

   def open(self, ga_engine):
      """ Open the XML RPC Server proxy

      :param ga_engine: the GA Engine

      .. versionchanged:: 0.6
         The method now receives the *ga_engine* parameter.
      """
      if self.xmlrpclibmod is None:
         logging.debug("Loding the xmlrpclib module...")
         self.xmlrpclibmod = Util.importSpecial("xmlrpclib")

      logging.debug("Opening the XML RPC Server Proxy on %s", self.url)
      self.proxy = self.xmlrpclibmod.ServerProxy(self.url, allow_none=True)

   def insert(self, ga_engine):
      """ Calls the XML RPC procedure

      :param ga_engine: the GA Engine

      .. versionchanged:: 0.6
         The method now receives the *ga_engine* parameter.
      """
      stats = ga_engine.getStatistics()
      generation = ga_engine.getCurrentGeneration()
      di = stats.internalDict.copy()
      di.update({"identify": self.getIdentify(), "generation": generation})
      self.proxy.insert(di)

class DBVPythonGraph(DBBaseAdapter):
   """ The DBVPythonGraph Class - A DB Adapter for real-time visualization using VPython

   Inheritance diagram for :class:`DBAdapters.DBVPythonGraph`:

   .. inheritance-diagram:: DBAdapters.DBVPythonGraph

   .. note:: to use this DB Adapter, you **must** install VPython first.

   Example:
      >>> adapter = DBAdapters.DBVPythonGraph(identify="run_01", frequency = 1)
      >>> ga_engine.setDBAdapter(adapter)
   
   :param identify: the identify of the run
   :param genmax: use the generations as max value for x-axis, default False
   :param frequency: the generational dump frequency

   .. versionadded:: 0.6
      The *DBVPythonGraph* class.
   """

   def __init__(self, identify=None, frequency = 20, genmax=False):
      DBBaseAdapter.__init__(self, frequency, identify)
      self.genmax = genmax
      self.vtkGraph = None
      self.curveMin = None
      self.curveMax = None
      self.curveDev = None
      self.curveAvg = None

   def makeDisplay(self, title_sec, x, y, ga_engine):
      """ Used internally to create a new display for VPython.
      
      :param title_sec: the title of the window
      :param x: the x position of the window
      :param y: the y position of the window
      :param ga_engine: the GA Engine

      :rtype: the window (the return of gdisplay call)
      """
      title = "Pyevolve v.%s - %s - id [%s]" % (__version__, title_sec, self.identify)
      if self.genmax:
         disp = self.vtkGraph.gdisplay(title=title, xtitle='Generation', ytitle=title_sec,
                                    xmax=ga_engine.getGenerations(), xmin=0., width=500,
                                    height=250, x=x, y=y)
      else:
         disp = self.vtkGraph.gdisplay(title=title, xtitle='Generation', ytitle=title_sec,
                                    xmin=0., width=500, height=250, x=x, y=y)
         return disp

   def open(self, ga_engine):
      """ Imports the VPython module and creates the four graph windows

      :param ga_engine: the GA Engine
      """
      logging.debug("Loading visual.graph (VPython) module...")
      if self.vtkGraph is None:
         self.vtkGraph = Util.importSpecial("visual.graph").graph

      display_rawmin = self.makeDisplay("Raw Score (min)",       0,   0,   ga_engine)
      display_rawmax = self.makeDisplay("Raw Score (max)",       0,   250, ga_engine)
      display_rawdev = self.makeDisplay("Raw Score (std. dev.)", 500, 0,   ga_engine)
      display_rawavg = self.makeDisplay("Raw Score (avg)",       500, 250, ga_engine)

      self.curveMin = self.vtkGraph.gcurve(color=self.vtkGraph.color.red,    gdisplay=display_rawmin)
      self.curveMax = self.vtkGraph.gcurve(color=self.vtkGraph.color.green,  gdisplay=display_rawmax)
      self.curveDev = self.vtkGraph.gcurve(color=self.vtkGraph.color.blue,   gdisplay=display_rawdev)
      self.curveAvg = self.vtkGraph.gcurve(color=self.vtkGraph.color.orange, gdisplay=display_rawavg)

   def insert(self, ga_engine):
      """ Plot the current statistics to the graphs

      :param ga_engine: the GA Engine
      """
      stats = ga_engine.getStatistics()
      generation = ga_engine.getCurrentGeneration()

      self.curveMin.plot(pos=(generation, stats["rawMin"]))
      self.curveMax.plot(pos=(generation, stats["rawMax"]))
      self.curveDev.plot(pos=(generation, stats["rawDev"]))
      self.curveAvg.plot(pos=(generation, stats["rawAve"]))
      
class DBMySQLAdapter(DBBaseAdapter):
   """ DBMySQLAdapter Class - Adapter to dump data in MySql database server

   Inheritance diagram for :class:`DBAdapters.DBMySQLAdapter`:

   .. inheritance-diagram:: DBAdapters.DBMySQLAdapter

   Example:
      >>> dbadapter = DBMySQLAdapter("pyevolve_username", "password", identify="run1")

   or

      >>> dbadapter = DBMySQLAdapter(user="username", passwd="password",
      ...                            host="mysqlserver.com.br", port=3306, db="pyevolve_db")

   When you run some GA for the first time, you need to create the database, for this, you
   must use the *resetDB* parameter as True.

   This parameter will erase all the database tables and will create the new ones.
   The *resetDB* parameter is different from the *resetIdentify* parameter, the *resetIdentify*
   only erases the rows with the same "identify" name, and *resetDB* will drop and recreate
   the tables.

   :param user: mysql username (must have permission to create, drop, insert, etc.. on tables
   :param passwd: the user password on MySQL server
   :param host: the hostname, default is "localhost"
   :param port: the port, default is 3306
   :param db: the database name, default is "pyevolve"
   :param identify: the identify if the run
   :param resetDB: if True, the database structure will be recreated
   :param resetIdentify: if True, the identify with the same name will be overwrite with new data
   :param frequency: the generational dump frequency
   :param commit_freq: the commit frequency
   """

   def __init__(self, user, passwd, host=Consts.CDefMySQLDBHost, port=Consts.CDefMySQLDBPort,
                db=Consts.CDefMySQLDBName, identify=None, resetDB=False, resetIdentify=True,
                frequency=Consts.CDefMySQLStatsGenFreq, commit_freq=Consts.CDefMySQLStatsCommitFreq):
      """ The creator of the DBSQLite Class """

      DBBaseAdapter.__init__(self, frequency, identify)

      self.mysqldbmod = None
      self.connection = None
      self.resetDB = resetDB
      self.resetIdentify = resetIdentify
      self.db = db
      self.host = host
      self.port = port
      self.user = user
      self.passwd = passwd
      self.typeDict = { types.FloatType : "DOUBLE(14,6)" }
      self.cursorPool = None
      self.commitFreq = commit_freq

   def __repr__(self):
      """ The string representation of adapter """
      ret = "DBMySQLAdapter DB Adapter [identify='%s', host='%s', username='%s', db='%s']" % (self.getIdentify(),
            self.host, self.user, self.db)
      return ret

   def open(self, ga_engine):
      """ Open the database connection

      :param ga_engine: the GA Engine

      .. versionchanged:: 0.6
         The method now receives the *ga_engine* parameter.
      """
      if self.mysqldbmod is None:
         logging.debug("Loading MySQLdb module...")
         self.mysqldbmod = Util.importSpecial("MySQLdb")

      logging.debug("Opening database, host=%s", self.host)
      self.connection = self.mysqldbmod.connect(host=self.host, user=self.user,
                                                passwd=self.passwd, db=self.db,
                                                port=self.port)
      temp_stats = Statistics.Statistics()
      self.createStructure(temp_stats)

      if self.resetDB:
         self.resetStructure(Statistics.Statistics())

      if self.resetIdentify:
         self.resetTableIdentify()

   def commitAndClose(self):
      """ Commit changes on database and closes connection """
      self.commit()
      self.close()

   def close(self):
      """ Close the database connection """
      logging.debug("Closing database.")
      if self.cursorPool:
         self.cursorPool.close()
         self.cursorPool = None
      self.connection.close()

   def commit(self):
      """ Commit changes to database """
      logging.debug("Commiting changes to database.")
      self.connection.commit()

   def getCursor(self):
      """ Return a cursor from the pool

      :rtype: the cursor

      """
      if not self.cursorPool:
         logging.debug("Creating new cursor for database...")
         self.cursorPool = self.connection.cursor()
         return self.cursorPool
      else:
         return self.cursorPool

   def createStructure(self, stats):
      """ Create table using the Statistics class structure

      :param stats: the statistics object

      """
      c = self.getCursor()
      pstmt = "create table if not exists %s(identify VARCHAR(80), generation INTEGER, " % (Consts.CDefMySQLDBTable)
      for k, v in stats.items():
         pstmt += "%s %s, " % (k, self.typeDict[type(v)])
      pstmt = pstmt[:-2] + ")"
      logging.debug("Creating table %s: %s.", Consts.CDefSQLiteDBTable, pstmt)
      c.execute(pstmt)

      pstmt = """create table if not exists %s(identify VARCHAR(80), generation INTEGER,
              individual INTEGER, fitness DOUBLE(14,6), raw DOUBLE(14,6))""" % (Consts.CDefMySQLDBTablePop)
      logging.debug("Creating table %s: %s.", Consts.CDefMySQLDBTablePop, pstmt)
      c.execute(pstmt)
      self.commit()

   def resetTableIdentify(self):
      """ Delete all records on the table with the same Identify """
      c = self.getCursor()
      stmt  = "delete from %s where identify = '%s'" % (Consts.CDefMySQLDBTable, self.getIdentify())
      stmt2 = "delete from %s where identify = '%s'" % (Consts.CDefMySQLDBTablePop, self.getIdentify())

      logging.debug("Erasing data from the tables with the identify = %s", self.getIdentify())
      c.execute(stmt)
      c.execute(stmt2)

      self.commit()


   def resetStructure(self, stats):
      """ Deletes de current structure and calls createStructure

      :param stats: the statistics object

      """
      logging.debug("Reseting structure, droping table and creating new empty table.")
      c = self.getCursor()
      c.execute("drop table if exists %s" % (Consts.CDefMySQLDBTable,))
      c.execute("drop table if exists %s" % (Consts.CDefMySQLDBTablePop,))
      self.commit()
      self.createStructure(stats)
      
   def insert(self, ga_engine):
      """ Inserts the statistics data to database

      :param ga_engine: the GA Engine

      .. versionchanged:: 0.6
         The method now receives the *ga_engine* parameter.
      """
      stats      = ga_engine.getStatistics()
      population = ga_engine.getPopulation()
      generation = ga_engine.getCurrentGeneration()

      c = self.getCursor()
      pstmt = "insert into " + Consts.CDefMySQLDBTable + " values (%s, %s, "
      for i in xrange(len(stats)):
         pstmt += "%s, "
      pstmt = pstmt[:-2] + ")" 
      c.execute(pstmt, (self.getIdentify(), generation) + stats.asTuple())

      pstmt = "insert into " + Consts.CDefMySQLDBTablePop + " values(%s, %s, %s, %s, %s)"

      tups = []
      for i in xrange(len(population)):
         ind = population[i]
         tups.append((self.getIdentify(), generation, i, ind.fitness, ind.score))

      c.executemany(pstmt, tups)
      if (generation % self.commitFreq == 0):
         self.commit()