|
From: <mor...@us...> - 2009-02-11 05:50:55
|
Revision: 3403
http://ecell.svn.sourceforge.net/ecell/?rev=3403&view=rev
Author: moriyoshi
Date: 2009-02-11 05:50:49 +0000 (Wed, 11 Feb 2009)
Log Message:
-----------
* Eliminate usage of string module.
Modified Paths:
--------------
ecell3/branches/ecell-3.1/doc/samples/ga/ga.py
ecell3/branches/ecell-3.1/ecell/frontend/session-monitor/ecell/ui/osogo/MainWindow.py
ecell3/branches/ecell-3.1/ecell/pyecell/ecell/analysis/Elasticity.py
ecell3/branches/ecell-3.1/ecell/pyecell/ecell/analysis/PathwayProxy.py
ecell3/branches/ecell-3.1/ecell/pyecell/ecell/analysis/SBMLExporter.py
ecell3/branches/ecell-3.1/ecell/pyecell/ecell/analysis/SBMLImporter.py
ecell3/branches/ecell-3.1/ecell/pyecell/ecell/analysis/ecdsupport.py
ecell3/branches/ecell-3.1/ecell/pyecell/ecell/analysis/emlsupport.py
ecell3/branches/ecell-3.1/ecell/pyecell/ecell/analysis/sbmlsupport.py
ecell3/branches/ecell-3.1/ecell/pyecell/ecell/analysis/util.py
ecell3/branches/ecell-3.1/ecell/pyecell/ecell/emparser.py
ecell3/branches/ecell-3.1/ecell/pyecell/ecell/expressionparser.py
ecell3/branches/ecell-3.1/ecell/pyecell/ecell/session_manager/LSFProxy.py
ecell3/branches/ecell-3.1/ecell/pyecell/ecell3-em2eml.in
ecell3/branches/ecell-3.1/ecell/pyecell/ecell3-eml2em.in
ecell3/branches/ecell-3.1/ecell/pyecell/ecell3-eml2sbml.in
ecell3/branches/ecell-3.1/ecell/pyecell/ecell3-sbml2eml.in
ecell3/branches/ecell-3.1/ecell/pyecell/ecell3-session-manager.in
ecell3/branches/ecell-3.1/ecell/pyecell/ecell3-session.in
Modified: ecell3/branches/ecell-3.1/doc/samples/ga/ga.py
===================================================================
--- ecell3/branches/ecell-3.1/doc/samples/ga/ga.py 2009-02-11 04:39:44 UTC (rev 3402)
+++ ecell3/branches/ecell-3.1/doc/samples/ga/ga.py 2009-02-11 05:50:49 UTC (rev 3403)
@@ -1,6 +1,5 @@
# a sample of Genetic Algorithm on SessionManager
-from string import *
from ConfigParser import *
import sys
import shutil
@@ -41,2104 +40,2104 @@
# ###################################################################################
class RCGA:
- '''Real Coded Genetic Algorithm
- '''
+ '''Real Coded Genetic Algorithm
+ '''
- # ------------------------------------------------------------------
- def __init__(self, aSetting):
- '''Constructor
- aSetting -- a Setting instance (Setting)
+ # ------------------------------------------------------------------
+ def __init__(self, aSetting):
+ '''Constructor
+ aSetting -- a Setting instance (Setting)
- '''
- self.theSetting = aSetting
+ '''
+ self.theSetting = aSetting
- # Initialize parameters
- self.theCurrentGeneration = 0
- self.theIndividualList = []
- self.theErFileList = None
- self.theEliteIndividual = None
- self.theParameterMap = None
- self.theMutationRatio = None
- self.theEliteImprovedFlag = False
+ # Initialize parameters
+ self.theCurrentGeneration = 0
+ self.theIndividualList = []
+ self.theErFileList = None
+ self.theEliteIndividual = None
+ self.theParameterMap = None
+ self.theMutationRatio = None
+ self.theEliteImprovedFlag = False
- # end of __init__
+ # end of __init__
- # ------------------------------------------------------------------
- def initialize( self ):
- '''executs initizalize strategy of GA as bellow.
- - initialize random generator
- - sets up parameter
- - generates population
- - write gnuplot file
+ # ------------------------------------------------------------------
+ def initialize( self ):
+ '''executs initizalize strategy of GA as bellow.
+ - initialize random generator
+ - sets up parameter
+ - generates population
+ - write gnuplot file
- Return None
- '''
+ Return None
+ '''
- print START_MESSAGE
+ print START_MESSAGE
- # ----------------------------------------------------------
- # initialize random generator
- # ----------------------------------------------------------
-
- random.seed(self.theSetting['RANDOM SEED'] )
-
- # ----------------------------------------------------------
- # sets up parameter
- # ----------------------------------------------------------
- self.theParameterMap = {}
- for aParameterLine in self.theSetting['PARAMETER']:
- anElementList = aParameterLine
- aParameter = anElementList[0]
- aMin = atof(anElementList[1])
- aMax = atof(anElementList[2])
- aType = anElementList[3]
- if aType == 'int':
- aMin = int(aMin)
- aMax = int(aMax)
- self.theParameterMap[aParameter] = [ aMin, aMax, aType ]
+ # ----------------------------------------------------------
+ # initialize random generator
+ # ----------------------------------------------------------
+
+ random.seed(self.theSetting['RANDOM SEED'] )
+
+ # ----------------------------------------------------------
+ # sets up parameter
+ # ----------------------------------------------------------
+ self.theParameterMap = {}
+ for aParameterLine in self.theSetting['PARAMETER']:
+ anElementList = aParameterLine
+ aParameter = anElementList[0]
+ aMin = float(anElementList[1])
+ aMax = float(anElementList[2])
+ aType = anElementList[3]
+ if aType == 'int':
+ aMin = int(aMin)
+ aMax = int(aMax)
+ self.theParameterMap[aParameter] = [ aMin, aMax, aType ]
- # ----------------------------------------------------------
- # generates population
- # ----------------------------------------------------------
- for anIndex in xrange(0,self.theSetting['POPULATION']):
+ # ----------------------------------------------------------
+ # generates population
+ # ----------------------------------------------------------
+ for anIndex in xrange(0,self.theSetting['POPULATION']):
- aCode = RealCodedIndividual( self.theSetting )
- self.theIndividualList.append( aCode )
+ aCode = RealCodedIndividual( self.theSetting )
+ self.theIndividualList.append( aCode )
- # set parameter map
- self.theIndividualList[0].setParameterMap( self.theParameterMap )
+ # set parameter map
+ self.theIndividualList[0].setParameterMap( self.theParameterMap )
- # generate population
- for anIndividual in self.theIndividualList:
- anIndividual.constructRandomly()
+ # generate population
+ for anIndividual in self.theIndividualList:
+ anIndividual.constructRandomly()
- # ----------------------------------------------------------
- # resume
- # ----------------------------------------------------------
+ # ----------------------------------------------------------
+ # resume
+ # ----------------------------------------------------------
- # when resume file is specified, read resume file
- if self.theSetting['RESUME FILE'] != None:
+ # when resume file is specified, read resume file
+ if self.theSetting['RESUME FILE'] != None:
- sys.stdout.write( "Reading resume file ... %s\n" \
- %self.theSetting['RESUME FILE'] )
+ sys.stdout.write( "Reading resume file ... %s\n" \
+ %self.theSetting['RESUME FILE'] )
- # read resume data
- aGenoType = self.readResumeFile( self.theSetting['RESUME FILE'] )
+ # read resume data
+ aGenoType = self.readResumeFile( self.theSetting['RESUME FILE'] )
- # set resume data to first individual
- self.theIndividualList[0].setGenoType(aGenoType)
+ # set resume data to first individual
+ self.theIndividualList[0].setGenoType(aGenoType)
- # ----------------------------------------------------------
- # write gnuplot file
- # ----------------------------------------------------------
- # evaluate
- aContents = "set ylabel \"Evaluated Value\"\n"
- aContents += "set xlabel \"Generation\"\n"
- aContents += "plot \"%s\" with linespoints\n" \
- %self.theSetting['EVALUATED VALUE FILE']
- aContents += "pause -1"
+ # ----------------------------------------------------------
+ # write gnuplot file
+ # ----------------------------------------------------------
+ # evaluate
+ aContents = "set ylabel \"Evaluated Value\"\n"
+ aContents += "set xlabel \"Generation\"\n"
+ aContents += "plot \"%s\" with linespoints\n" \
+ %self.theSetting['EVALUATED VALUE FILE']
+ aContents += "pause -1"
- open(self.theSetting['EVALUATED VALUE GNUPLOT'],'w').write(aContents)
+ open(self.theSetting['EVALUATED VALUE GNUPLOT'],'w').write(aContents)
- # mutation
- aContents = "set ylabel \"Mutation ratio %\"\n"
- aContents += "set xlabel \"Generation\"\n"
- aContents += "plot \"%s\" with linespoints\n" \
- %self.theSetting['MUTATION VALUE FILE']
- aContents += "pause -1"
+ # mutation
+ aContents = "set ylabel \"Mutation ratio %\"\n"
+ aContents += "set xlabel \"Generation\"\n"
+ aContents += "plot \"%s\" with linespoints\n" \
+ %self.theSetting['MUTATION VALUE FILE']
+ aContents += "pause -1"
- open(self.theSetting['MUTATION VALUE GNUPLOT'],'w').write(aContents)
+ open(self.theSetting['MUTATION VALUE GNUPLOT'],'w').write(aContents)
- # ------------------------------------------------------------------
- def readResumeFile( self, aFile ):
- '''read resume file
- Return resume data (dict)
+ # ------------------------------------------------------------------
+ def readResumeFile( self, aFile ):
+ '''read resume file
+ Return resume data (dict)
key is parameter symbol
value is parameter value
- '''
+ '''
- aGenoType = {}
- aSearch = re.compile('^(\S)+\s+=\s+(\S+)')
+ aGenoType = {}
+ aSearch = re.compile('^(\S)+\s+=\s+(\S+)')
- aCounter = 0
+ aCounter = 0
- for aLine in open(aFile,'r').readlines():
+ for aLine in open(aFile,'r').readlines():
- # delete comment after #
- anIndex = find( aLine, '#' )
- if anIndex != -1:
- aLine = aLine[:anIndex]
+ # delete comment after #
+ anIndex = aLine.find( '#' )
+ if anIndex != -1:
+ aLine = aLine[:anIndex]
- # get parameter symbol and value
- aResult = aSearch.match(aLine)
- if aResult != None:
- aParam, anEqual, aValue = split( aResult.group() )
- aValue = atof( aValue )
- aMessage = " [%s] <--- [%s]\n" %(aParam,aValue)
- sys.stdout.write(aMessage)
- sys.stdout.flush()
+ # get parameter symbol and value
+ aResult = aSearch.match(aLine)
+ if aResult != None:
+ aParam, anEqual, aValue = aResult.group().split()
+ aValue = float( aValue )
+ aMessage = " [%s] <--- [%s]\n" %(aParam,aValue)
+ sys.stdout.write(aMessage)
+ sys.stdout.flush()
- aCounter += 1
- aGenoType[aParam] = aValue
+ aCounter += 1
+ aGenoType[aParam] = aValue
- if aCounter != len(aGenoType):
- aMessage = "%s : same parameter is found in resume input file.\n" %(ERROR)
- sys.stdout.write(aMessage)
- sys.stdout.flush()
- sys.exit(RESUMEFILE_EXIT)
+ if aCounter != len(aGenoType):
+ aMessage = "%s : same parameter is found in resume input file.\n" %(ERROR)
+ sys.stdout.write(aMessage)
+ sys.stdout.flush()
+ sys.exit(RESUMEFILE_EXIT)
- # validate resume file.
- aParameterMap = {}
- copy.deepcopy( Individual.theParameterMap, aParameterMap )
+ # validate resume file.
+ aParameterMap = {}
+ copy.deepcopy( Individual.theParameterMap, aParameterMap )
- aKeyDict = copy.deepcopy( Individual.theParameterMap )
+ aKeyDict = copy.deepcopy( Individual.theParameterMap )
- for aType in aGenoType.keys():
- try:
- del aKeyDict[aType]
- except KeyError:
- aMessage = "%s : %s no such parameter resume input file.\n" %(ERROR, aType)
- sys.stdout.write(aMessage)
- sys.stdout.flush()
- sys.exit(RESUMEFILE_EXIT)
-
+ for aType in aGenoType.keys():
+ try:
+ del aKeyDict[aType]
+ except KeyError:
+ aMessage = "%s : %s no such parameter resume input file.\n" %(ERROR, aType)
+ sys.stdout.write(aMessage)
+ sys.stdout.flush()
+ sys.exit(RESUMEFILE_EXIT)
+
- if len(aKeyDict)!=0:
- aMessage = "%s : %s must be set in resume input file.\n" \
- %(ERROR, str(aKeyDict.keys()))
- sys.stdout.write(aMessage)
- sys.stdout.flush()
- sys.exit(RESUMEFILE_EXIT)
+ if len(aKeyDict)!=0:
+ aMessage = "%s : %s must be set in resume input file.\n" \
+ %(ERROR, str(aKeyDict.keys()))
+ sys.stdout.write(aMessage)
+ sys.stdout.flush()
+ sys.exit(RESUMEFILE_EXIT)
- return aGenoType
+ return aGenoType
- # ------------------------------------------------------------------
- def run( self ):
- '''run a main loop of estimation
- Return : None
- '''
+ # ------------------------------------------------------------------
+ def run( self ):
+ '''run a main loop of estimation
+ Return : None
+ '''
- while(True):
+ while(True):
- self.theCurrentGeneration += 1
- self.__executeEvaluateStrategy()
- self.__executeEliteStrategy()
+ self.theCurrentGeneration += 1
+ self.__executeEvaluateStrategy()
+ self.__executeEliteStrategy()
- # clear all jobs
- clearJob(jobid=-1)
+ # clear all jobs
+ clearJob(jobid=-1)
- print "[%s]\t%s" %(self.theCurrentGeneration, \
- self.theEliteIndividual.getEvaluatedValue())
+ print "[%s]\t%s" %(self.theCurrentGeneration, \
+ self.theEliteIndividual.getEvaluatedValue())
- #if atoi(self.theSetiting['MAX GENERATION']) <= self.theCurrentGeneration:
- if self.theSetting['MAX GENERATION'] <= self.theCurrentGeneration:
- print "reached max generation"
- break
+ #if int(self.theSetiting['MAX GENERATION']) <= self.theCurrentGeneration:
+ if self.theSetting['MAX GENERATION'] <= self.theCurrentGeneration:
+ print "reached max generation"
+ break
- if self.theEliteIndividual.getEvaluatedValue() <= self.theSetting['FINISH CONDITION']:
- print "fufilled finish condition"
- break
+ if self.theEliteIndividual.getEvaluatedValue() <= self.theSetting['FINISH CONDITION']:
+ print "fufilled finish condition"
+ break
- self.__executeSelectionStrategy()
- self.__executeCrossoverStrategy()
- self.__executeMutationStrategy()
+ self.__executeSelectionStrategy()
+ self.__executeCrossoverStrategy()
+ self.__executeMutationStrategy()
- # ------------------------------------------------------------------
- def report( self ):
- '''Display the results of GA
+ # ------------------------------------------------------------------
+ def report( self ):
+ '''Display the results of GA
- Return None
- '''
+ Return None
+ '''
- print "----------------------------------------"
- print "| Result |"
- print "----------------------------------------"
- sys.stdout.write( "%s" %self.theEliteIndividual )
+ print "----------------------------------------"
+ print "| Result |"
+ print "----------------------------------------"
+ sys.stdout.write( "%s" %self.theEliteIndividual )
- # ------------------------------------------------------------------
- def __executeEvaluateStrategy( self ):
- '''Execute evaluate strategy
+ # ------------------------------------------------------------------
+ def __executeEvaluateStrategy( self ):
+ '''Execute evaluate strategy
- [1] Register ess files to SessionManager
- [2] Run ess files using SessionManager
- [3] Wait until all ess files finish
- [4] Read evaluated values
+ [1] Register ess files to SessionManager
+ [2] Run ess files using SessionManager
+ [3] Wait until all ess files finish
+ [4] Read evaluated values
- Return None
- '''
+ Return None
+ '''
- # -----------------------------------------------------
- # [1] Register ess files to SessionManager
- # -----------------------------------------------------
- anIndex = 0
- aParameterMapList = []
- aValueList = []
+ # -----------------------------------------------------
+ # [1] Register ess files to SessionManager
+ # -----------------------------------------------------
+ anIndex = 0
+ aParameterMapList = []
+ aValueList = []
- for anIndividual in self.theIndividualList:
+ for anIndividual in self.theIndividualList:
- #aParameterMap = anIndividual.getGenoType()
+ #aParameterMap = anIndividual.getGenoType()
- aJobIDList = []
+ aJobIDList = []
- for anIndex in xrange(0, len(self.theSetting['EXTRA DIRS']) ):
+ for anIndex in xrange(0, len(self.theSetting['EXTRA DIRS']) ):
- anEssFile = self.theSetting['ESS FILE']
- anExtraFiles = [ self.theSetting['EXTRA DIRS'][anIndex],
- self.theSetting['EML FILES'][anIndex] ]
+ anEssFile = self.theSetting['ESS FILE']
+ anExtraFiles = [ self.theSetting['EXTRA DIRS'][anIndex],
+ self.theSetting['EML FILES'][anIndex] ]
- #if self.theCurrentGeneration == 1:
- # if self.theSetting['RESUME FILE'] != None:
+ #if self.theCurrentGeneration == 1:
+ # if self.theSetting['RESUME FILE'] != None:
- #sys.exit(0)
+ #sys.exit(0)
- anArgument = {}
+ anArgument = {}
- for aKey in anIndividual.getGenoType().keys():
- anArgument[aKey] = anIndividual.getGenoType()[aKey]
+ for aKey in anIndividual.getGenoType().keys():
+ anArgument[aKey] = anIndividual.getGenoType()[aKey]
- #print anArgument
+ #print anArgument
- anArgument[self.theSetting['EML KEY']] = self.theSetting['EML FILES'][anIndex]
- anArgument[self.theSetting['DIR KEY']] = self.theSetting['EXTRA DIRS'][anIndex]
+ anArgument[self.theSetting['EML KEY']] = self.theSetting['EML FILES'][anIndex]
+ anArgument[self.theSetting['DIR KEY']] = self.theSetting['EXTRA DIRS'][anIndex]
- aJobID = registerEcellSession( anEssFile, anArgument, anExtraFiles )
+ aJobID = registerEcellSession( anEssFile, anArgument, anExtraFiles )
- aJobIDList.append( aJobID )
- anIndividual.setJobIDList( aJobIDList )
+ aJobIDList.append( aJobID )
+ anIndividual.setJobIDList( aJobIDList )
- aJobNumber = len(getQueuedJobList())
+ aJobNumber = len(getQueuedJobList())
- # -----------------------------------------------------
- # [2] Run ess files using SessionManager
- # -----------------------------------------------------
- run(block=False)
+ # -----------------------------------------------------
+ # [2] Run ess files using SessionManager
+ # -----------------------------------------------------
+ run(block=False)
- # -----------------------------------------------------
- # [3] Wait until all ess files finish
- # -----------------------------------------------------
- aLoopCounter = 0
+ # -----------------------------------------------------
+ # [3] Wait until all ess files finish
+ # -----------------------------------------------------
+ aLoopCounter = 0
- while(True):
+ while(True):
- update()
- time.sleep(1)
+ update()
+ time.sleep(1)
- sys.stdout.write("\r")
- sys.stdout.write("(%s/%s)" %(len(getFinishedJobList()),aJobNumber))
+ sys.stdout.write("\r")
+ sys.stdout.write("(%s/%s)" %(len(getFinishedJobList()),aJobNumber))
- if aLoopCounter % 6 == 1:
- sys.stdout.write(" . ")
- elif aLoopCounter % 6 == 2:
- sys.stdout.write(" .. ")
- elif aLoopCounter % 6 == 3:
- sys.stdout.write(" ... ")
- elif aLoopCounter % 6 == 4:
- sys.stdout.write(" .... ")
- elif aLoopCounter % 6 == 5:
- sys.stdout.write(" .....")
- else:
- sys.stdout.write(" ")
+ if aLoopCounter % 6 == 1:
+ sys.stdout.write(" . ")
+ elif aLoopCounter % 6 == 2:
+ sys.stdout.write(" .. ")
+ elif aLoopCounter % 6 == 3:
+ sys.stdout.write(" ... ")
+ elif aLoopCounter % 6 == 4:
+ sys.stdout.write(" .... ")
+ elif aLoopCounter % 6 == 5:
+ sys.stdout.write(" .....")
+ else:
+ sys.stdout.write(" ")
- sys.stdout.flush()
- aLoopCounter += 1
+ sys.stdout.flush()
+ aLoopCounter += 1
- if isFinished() == True:
- sys.stdout.write("\r")
- sys.stdout.write("(%s/%s)" %(len(getFinishedJobList()),aJobNumber))
- sys.stdout.write(" .....")
- break
+ if isFinished() == True:
+ sys.stdout.write("\r")
+ sys.stdout.write("(%s/%s)" %(len(getFinishedJobList()),aJobNumber))
+ sys.stdout.write(" .....")
+ break
- # -----------------------------------------------------
- # [4] Read evaluated values
- # -----------------------------------------------------
- for anIndividual in self.theIndividualList:
+ # -----------------------------------------------------
+ # [4] Read evaluated values
+ # -----------------------------------------------------
+ for anIndividual in self.theIndividualList:
- anEvaluatedValue = 0
+ anEvaluatedValue = 0
- for aJobID in anIndividual.getJobList():
+ for aJobID in anIndividual.getJobList():
- #print aJobID
+ #print aJobID
- #print getJobDirectory(aJobID)
- aResultFile = "%s%sresult.dat" %(getJobDirectory(aJobID), os.sep)
+ #print getJobDirectory(aJobID)
+ aResultFile = "%s%sresult.dat" %(getJobDirectory(aJobID), os.sep)
- if os.access(aResultFile,os.R_OK) == False:
- sys.stdout.flush()
- sys.stderr.write("\n%s: could not find %s. \n%s must write %s.\n" \
- %(ERROR,
- str(aResultFile),
- getSessionProxy(aJobID).getScriptFileName(),
- str(aResultFile)))
- sys.stderr.write("see %s%s%s.\n"
- %(getJobDirectory(aJobID),
- os.sep,
- getStderrFileName()))
- sys.stderr.write("If you set \'TMP REMOVABLE\' is True, change it to False and try again.\n")
- sys.stderr.flush()
-
- sys.exit(SCRIPTFILE_EXIT)
-
- aResult = open( aResultFile, 'r').read()
- aResult = atof(aResult)
- anEvaluatedValue += aResult
+ if os.access(aResultFile,os.R_OK) == False:
+ sys.stdout.flush()
+ sys.stderr.write("\n%s: could not find %s. \n%s must write %s.\n" \
+ %(ERROR,
+ str(aResultFile),
+ getSessionProxy(aJobID).getScriptFileName(),
+ str(aResultFile)))
+ sys.stderr.write("see %s%s%s.\n"
+ %(getJobDirectory(aJobID),
+ os.sep,
+ getStderrFileName()))
+ sys.stderr.write("If you set \'TMP REMOVABLE\' is True, change it to False and try again.\n")
+ sys.stderr.flush()
+
+ sys.exit(SCRIPTFILE_EXIT)
+
+ aResult = open( aResultFile, 'r').read()
+ aResult = float(aResult)
+ anEvaluatedValue += aResult
- anEvaluatedValue /= len(anIndividual.getJobList())
- anIndividual.setEvaluatedValue(anEvaluatedValue)
+ anEvaluatedValue /= len(anIndividual.getJobList())
+ anIndividual.setEvaluatedValue(anEvaluatedValue)
- # ------------------------------------------------------------------
- def __executeEliteStrategy( self ):
- '''Execute elite strategy
+ # ------------------------------------------------------------------
+ def __executeEliteStrategy( self ):
+ '''Execute elite strategy
- [1] Find the inidividual who has best evaluated value as elite
- [2] Save elite individual
- Return None
- '''
+ [1] Find the inidividual who has best evaluated value as elite
+ [2] Save elite individual
+ Return None
+ '''
- # --------------------------------------------------------------
- # [1] Find the inidividual who has best evaluated value as elite
- # --------------------------------------------------------------
- aValueList = []
- for anIndividual in self.theIndividualList:
- aValueList.append(anIndividual.getEvaluatedValue())
+ # --------------------------------------------------------------
+ # [1] Find the inidividual who has best evaluated value as elite
+ # --------------------------------------------------------------
+ aValueList = []
+ for anIndividual in self.theIndividualList:
+ aValueList.append(anIndividual.getEvaluatedValue())
- self.theIndividualList.sort()
- aMinValue = self.theIndividualList[0].getEvaluatedValue()
+ self.theIndividualList.sort()
+ aMinValue = self.theIndividualList[0].getEvaluatedValue()
- aMinIndex = 0
- for aValue in aValueList:
- if aValue == aMinValue:
- break
- else:
- pass
- aMinIndex += 1
+ aMinIndex = 0
+ for aValue in aValueList:
+ if aValue == aMinValue:
+ break
+ else:
+ pass
+ aMinIndex += 1
- # --------------------------------------------------------------
- # [2] Save elite individual
- # --------------------------------------------------------------
- # First generation,
- if type(self.theEliteIndividual) == type(None):
+ # --------------------------------------------------------------
+ # [2] Save elite individual
+ # --------------------------------------------------------------
+ # First generation,
+ if type(self.theEliteIndividual) == type(None):
- # -----------------------------------------------------
- # save elite individual
- # -----------------------------------------------------
- self.theEliteIndividual = copy.deepcopy( self.theIndividualList[0] )
- self.theEliteImprovedFlag = True
+ # -----------------------------------------------------
+ # save elite individual
+ # -----------------------------------------------------
+ self.theEliteIndividual = copy.deepcopy( self.theIndividualList[0] )
+ self.theEliteImprovedFlag = True
- # -----------------------------------------------------
- # copy the directories related to elite individual
- # -----------------------------------------------------
- for aJobID in self.theEliteIndividual.getJobList():
- aSrcDir = getSessionProxy(aJobID).getJobDirectory()
+ # -----------------------------------------------------
+ # copy the directories related to elite individual
+ # -----------------------------------------------------
+ for aJobID in self.theEliteIndividual.getJobList():
+ aSrcDir = getSessionProxy(aJobID).getJobDirectory()
- aDstDir = "%s%s%s" %(self.theSetting['ELITE DIR'],\
- os.sep,\
- os.path.basename(aSrcDir[:-len(os.sep)]))
- shutil.copytree(aSrcDir,aDstDir)
+ aDstDir = "%s%s%s" %(self.theSetting['ELITE DIR'],\
+ os.sep,\
+ os.path.basename(aSrcDir[:-len(os.sep)]))
+ shutil.copytree(aSrcDir,aDstDir)
- # Second generation or after
- else:
+ # Second generation or after
+ else:
- # -----------------------------------------------------
- # When the best individual is better than the elite,
- # save best evaluation value as the elite's value
- # -----------------------------------------------------
- if self.theIndividualList[0] < self.theEliteIndividual:
+ # -----------------------------------------------------
+ # When the best individual is better than the elite,
+ # save best evaluation value as the elite's value
+ # -----------------------------------------------------
+ if self.theIndividualList[0] < self.theEliteIndividual:
- # ---------------------
- # save elite individual
- # ---------------------
- self.theEliteIndividual = copy.deepcopy( self.theIndividualList[0] )
- self.theEliteImprovedFlag = True
+ # ---------------------
+ # save elite individual
+ # ---------------------
+ self.theEliteIndividual = copy.deepcopy( self.theIndividualList[0] )
+ self.theEliteImprovedFlag = True
- # ---------------------
- # delete elite directory
- # ---------------------
- #print os.listdir(self.theSetting['ELITE DIR'])
- for aDir in os.listdir(self.theSetting['ELITE DIR']):
- if aDir == '.' or aDir == '..':
- continue
- aDir = "%s%s%s" %(self.theSetting['ELITE DIR'],
- os.sep,
- aDir)
- shutil.rmtree(aDir)
+ # ---------------------
+ # delete elite directory
+ # ---------------------
+ #print os.listdir(self.theSetting['ELITE DIR'])
+ for aDir in os.listdir(self.theSetting['ELITE DIR']):
+ if aDir == '.' or aDir == '..':
+ continue
+ aDir = "%s%s%s" %(self.theSetting['ELITE DIR'],
+ os.sep,
+ aDir)
+ shutil.rmtree(aDir)
- # ---------------------
- # copy the directories related to elite individual
- # ---------------------
- for aJobID in self.theEliteIndividual.getJobList():
- aSrcDir = getSessionProxy(aJobID).getJobDirectory()
- aDstDir = "%s%s%s" %(self.theSetting['ELITE DIR'],\
- os.sep,\
- os.path.basename(aSrcDir[:-len(os.sep)]))
- shutil.copytree(aSrcDir,aDstDir)
+ # ---------------------
+ # copy the directories related to elite individual
+ # ---------------------
+ for aJobID in self.theEliteIndividual.getJobList():
+ aSrcDir = getSessionProxy(aJobID).getJobDirectory()
+ aDstDir = "%s%s%s" %(self.theSetting['ELITE DIR'],\
+ os.sep,\
+ os.path.basename(aSrcDir[:-len(os.sep)]))
+ shutil.copytree(aSrcDir,aDstDir)
- # -----------------------------------------------------
- # When the elite is better than the best individual,
- # replace worst individual with elite
- # -----------------------------------------------------
- else:
- self.theIndividualList[len(self.theIndividualList)-1] = \
- copy.deepcopy( self.theEliteIndividual )
- self.theEliteImprovedFlag = False
+ # -----------------------------------------------------
+ # When the elite is better than the best individual,
+ # replace worst individual with elite
+ # -----------------------------------------------------
+ else:
+ self.theIndividualList[len(self.theIndividualList)-1] = \
+ copy.deepcopy( self.theEliteIndividual )
+ self.theEliteImprovedFlag = False
- # -----------------------------------------------------------------------
- # Write evaluated value
- # -----------------------------------------------------------------------
- aContents = "%s\t%s\n" %(self.theCurrentGeneration,
- self.theEliteIndividual.getEvaluatedValue())
+ # -----------------------------------------------------------------------
+ # Write evaluated value
+ # -----------------------------------------------------------------------
+ aContents = "%s\t%s\n" %(self.theCurrentGeneration,
+ self.theEliteIndividual.getEvaluatedValue())
- if self.theCurrentGeneration == 1:
- open( self.theSetting['EVALUATED VALUE FILE'], 'w').write(aContents)
- else:
- open( self.theSetting['EVALUATED VALUE FILE'], 'a').write(aContents)
+ if self.theCurrentGeneration == 1:
+ open( self.theSetting['EVALUATED VALUE FILE'], 'w').write(aContents)
+ else:
+ open( self.theSetting['EVALUATED VALUE FILE'], 'a').write(aContents)
- # -----------------------------------------------------------------------
- # Write elite individual
- # -----------------------------------------------------------------------
- aContents = "[ %s ]-----------------------------------\n" %(self.theCurrentGeneration)
- aContents += str(self.theEliteIndividual)
+ # -----------------------------------------------------------------------
+ # Write elite individual
+ # -----------------------------------------------------------------------
+ aContents = "[ %s ]-----------------------------------\n" %(self.theCurrentGeneration)
+ aContents += str(self.theEliteIndividual)
- if self.theCurrentGeneration == 1:
- open( self.theSetting['ELITE FILE'], 'w').write(aContents)
- else:
- open( self.theSetting['ELITE FILE'], 'a').write(aContents)
+ if self.theCurrentGeneration == 1:
+ open( self.theSetting['ELITE FILE'], 'w').write(aContents)
+ else:
+ open( self.theSetting['ELITE FILE'], 'a').write(aContents)
- #sys.stdout.write(aContents)
- #sys.stdout.flush()
+ #sys.stdout.write(aContents)
+ #sys.stdout.flush()
- #self.theEcellSessionManager.saveEliteDirectory(anIndexOfElite)
+ #self.theEcellSessionManager.saveEliteDirectory(anIndexOfElite)
- #print "[GAEstimator.executeEliteStrategy]---------------------------------e"
+ #print "[GAEstimator.executeEliteStrategy]---------------------------------e"
- # ------------------------------------------------------------------
- def __executeSelectionStrategy( self ):
- '''Sxecute selection strategy
+ # ------------------------------------------------------------------
+ def __executeSelectionStrategy( self ):
+ '''Sxecute selection strategy
- This strategy is executed according to the following procedures.
- [1] eliminate the specific case
- [2] calculate selection probability
- [3] copy individuals according to selection probability
+ This strategy is executed according to the following procedures.
+ [1] eliminate the specific case
+ [2] calculate selection probability
+ [3] copy individuals according to selection probability
- Return None
- '''
+ Return None
+ '''
- # --------------------------------------------------------------
- # [1] eliminate the specific case
- # --------------------------------------------------------------
+ # --------------------------------------------------------------
+ # [1] eliminate the specific case
+ # --------------------------------------------------------------
- # When the intdividual is < 2, this strategy is meaningless.
- # Then do nothing.
- if len(self.theIndividualList) < 2:
- return None
+ # When the intdividual is < 2, this strategy is meaningless.
+ # Then do nothing.
+ if len(self.theIndividualList) < 2:
+ return None
- # --------------------------------------------------------------
- # [2] calculate selection probability
- # --------------------------------------------------------------
+ # --------------------------------------------------------------
+ # [2] calculate selection probability
+ # --------------------------------------------------------------
- # initialize a list of Pi (selection probability)
- aCopyNumberList = []
+ # initialize a list of Pi (selection probability)
+ aCopyNumberList = []
- # calculate copy numbers
- for anIndex in xrange(0,len(self.theIndividualList)):
- aP = self.theSetting['ETA PLUS']
- aP = aP-(self.theSetting['ETA PLUS']-self.theSetting['ETA MINUS'])*anIndex/(len(self.theIndividualList)-1)
- aP = int(round(aP))
- aCopyNumberList.append(aP)
-
- # --------------------------------------------------------------
- # [3] copy individuals according to selection probability
- # --------------------------------------------------------------
+ # calculate copy numbers
+ for anIndex in xrange(0,len(self.theIndividualList)):
+ aP = self.theSetting['ETA PLUS']
+ aP = aP-(self.theSetting['ETA PLUS']-self.theSetting['ETA MINUS'])*anIndex/(len(self.theIndividualList)-1)
+ aP = int(round(aP))
+ aCopyNumberList.append(aP)
+
+ # --------------------------------------------------------------
+ # [3] copy individuals according to selection probability
+ # --------------------------------------------------------------
- # inidialize individual list buffer
- anIndividualListBuffer = []
-
- # copy individuals
- anIndex = 0
- for aCopyNumber in aCopyNumberList:
- for aDummy in xrange(0,aCopyNumber):
- anIndividualListBuffer.append( copy.deepcopy(self.theIndividualList[anIndex]) )
- anIndex += 1
+ # inidialize individual list buffer
+ anIndividualListBuffer = []
+
+ # copy individuals
+ anIndex = 0
+ for aCopyNumber in aCopyNumberList:
+ for aDummy in xrange(0,aCopyNumber):
+ anIndividualListBuffer.append( copy.deepcopy(self.theIndividualList[anIndex]) )
+ anIndex += 1
- # replace individual list
- self.theIndividualList = anIndividualListBuffer
+ # replace individual list
+ self.theIndividualList = anIndividualListBuffer
- # ------------------------------------------------------------------
- def __executeCrossoverStrategy( self ):
- '''Execute crossover strategy
- This sample support only SPX crossover method.
+ # ------------------------------------------------------------------
+ def __executeCrossoverStrategy( self ):
+ '''Execute crossover strategy
+ This sample support only SPX crossover method.
- Return None
- '''
+ Return None
+ '''
- # call spx
- self.__spx()
+ # call spx
+ self.__spx()
- # ------------------------------------------------------------------
- def __spx(self):
- '''Simplex crossover
+ # ------------------------------------------------------------------
+ def __spx(self):
+ '''Simplex crossover
- This strategy is executed according to the following procedures.
- [1] Choose m parents Pk (i=1,2,...,m) according to the generational
- model used and calculate their center of gravity G, see (5).
- [2] Generate random number rk, see (6)
- [3] Calculate xk, see (7)
- [4] Calculate Ck, see (8)
- [5] Generate an offspring C, see (9)
+ This strategy is executed according to the following procedures.
+ [1] Choose m parents Pk (i=1,2,...,m) according to the generational
+ model used and calculate their center of gravity G, see (5).
+ [2] Generate random number rk, see (6)
+ [3] Calculate xk, see (7)
+ [4] Calculate Ck, see (8)
+ [5] Generate an offspring C, see (9)
- Return None
- '''
+ Return None
+ '''
- aM = self.theSetting['M']
- anUpsilon = atof(self.theSetting['UPSILON'])
- aChildrenList = []
+ aM = self.theSetting['M']
+ anUpsilon = float(self.theSetting['UPSILON'])
+ aChildrenList = []
- for anIndividual in self.theIndividualList:
+ for anIndividual in self.theIndividualList:
- # ---------------------------------------------------------------------
- # [1] Choose m parents Pk (i=1,2,...,m) according to the generational
- # model used and calculate their center of gravity G, see (5).
- # ---------------------------------------------------------------------
+ # ---------------------------------------------------------------------
+ # [1] Choose m parents Pk (i=1,2,...,m) according to the generational
+ # model used and calculate their center of gravity G, see (5).
+ # ---------------------------------------------------------------------
- aParentList = []
+ aParentList = []
- for anIndex in xrange(0,aM):
- aRandomIndex = random.randint(0,len(self.theIndividualList)-1)
- aParentList.append( self.theIndividualList[aRandomIndex] )
+ for anIndex in xrange(0,aM):
+ aRandomIndex = random.randint(0,len(self.theIndividualList)-1)
+ aParentList.append( self.theIndividualList[aRandomIndex] )
- aG ={}
- aParent = aParentList[0]
- for aFullID in aParent.getGenoType().keys():
- aG[aFullID] = aParent.getGenoType()[aFullID]
+ aG ={}
+ aParent = aParentList[0]
+ for aFullID in aParent.getGenoType().keys():
+ aG[aFullID] = aParent.getGenoType()[aFullID]
- for aParent in aParentList[1:]:
- for aFullID in aParent.getGenoType().keys():
- aG[aFullID] += aParent.getGenoType()[aFullID]
+ for aParent in aParentList[1:]:
+ for aFullID in aParent.getGenoType().keys():
+ aG[aFullID] += aParent.getGenoType()[aFullID]
- for aFullID in aParent.getGenoType():
- aG[aFullID] /= len(aParentList)
+ for aFullID in aParent.getGenoType():
+ aG[aFullID] /= len(aParentList)
- # ---------------------------------------------------------------------
- # [2] Generate random number rk, see (6)
- # ---------------------------------------------------------------------
- anU = random.random()
- aR = []
+ # ---------------------------------------------------------------------
+ # [2] Generate random number rk, see (6)
+ # ---------------------------------------------------------------------
+ anU = random.random()
+ aR = []
- for aK in xrange(0,aM-1):
- aR.append( pow(anU,1.0/(aK+1.0)) )
+ for aK in xrange(0,aM-1):
+ aR.append( pow(anU,1.0/(aK+1.0)) )
- # ---------------------------------------------------------------------
- # [3] Calculate xk, see (7)
- # ---------------------------------------------------------------------
- aX = []
+ # ---------------------------------------------------------------------
+ # [3] Calculate xk, see (7)
+ # ---------------------------------------------------------------------
+ aX = []
- for aK in xrange(0,aM):
- aXk = {}
- for aFullID in aParentList[aK].getGenoType().keys():
- aXk[aFullID] = aG[aFullID] + \
- anUpsilon * ( aParentList[aK].getGenoType()[aFullID] - aG[aFullID] )
- aX.append(aXk)
+ for aK in xrange(0,aM):
+ aXk = {}
+ for aFullID in aParentList[aK].getGenoType().keys():
+ aXk[aFullID] = aG[aFullID] + \
+ anUpsilon * ( aParentList[aK].getGenoType()[aFullID] - aG[aFullID] )
+ aX.append(aXk)
- # ---------------------------------------------------------------------
- # [4] Calculate Ck, see (8)
- # ---------------------------------------------------------------------
- aC = []
+ # ---------------------------------------------------------------------
+ # [4] Calculate Ck, see (8)
+ # ---------------------------------------------------------------------
+ aC = []
- aCk0 = {}
- for aFullID in aParentList[0].getGenoType().keys():
- aCk0[aFullID] = 0.0
+ aCk0 = {}
+ for aFullID in aParentList[0].getGenoType().keys():
+ aCk0[aFullID] = 0.0
- aC.append(aCk0)
+ aC.append(aCk0)
- for aK in xrange(1,aM):
- aCk = {}
- for aFullID in aParentList[aK].getGenoType().keys():
- aCk[aFullID] = aR[aK-1] * ( aX[aK-1][aFullID] - aX[aK][aFullID] + aC[aK-1][aFullID] )
-
- aC.append(aCk)
+ for aK in xrange(1,aM):
+ aCk = {}
+ for aFullID in aParentList[aK].getGenoType().keys():
+ aCk[aFullID] = aR[aK-1] * ( aX[aK-1][aFullID] - aX[aK][aFullID] + aC[aK-1][aFullID] )
+
+ aC.append(aCk)
- # ---------------------------------------------------------------------
- # [5] Generate an offspring C, see (9)
- # ---------------------------------------------------------------------
- for aK in xrange(0,aM):
- aCk = {}
- for aFullID in aParentList[aK].getGenoType().keys():
- aCk[aFullID] = aX[aK][aFullID] + aC[aK][aFullID]
+ # ---------------------------------------------------------------------
+ # [5] Generate an offspring C, see (9)
+ # ---------------------------------------------------------------------
+ for aK in xrange(0,aM):
+ aCk = {}
+ for aFullID in aParentList[aK].getGenoType().keys():
+ aCk[aFullID] = aX[aK][aFullID] + aC[aK][aFullID]
- aChild = copy.deepcopy( self.theIndividualList[0] )
- aChild.setGenoType( aCk )
- aChild.setEvaluatedValue( None )
- aChildrenList.append( aChild )
+ aChild = copy.deepcopy( self.theIndividualList[0] )
+ aChild.setGenoType( aCk )
+ aChild.setEvaluatedValue( None )
+ aChildrenList.append( aChild )
- if len(aChildrenList) == len(self.theIndividualList):
- break
+ if len(aChildrenList) == len(self.theIndividualList):
+ break
- if len(aChildrenList) == len(self.theIndividualList):
- break
+ if len(aChildrenList) == len(self.theIndividualList):
+ break
- anIndex = 0
- for aChild in self.theIndividualList:
- anIndex +=1
- anIndex = 0
- for aChild in aChildrenList:
- anIndex +=1
- self.theIndividualList = aChildrenList
+ anIndex = 0
+ for aChild in self.theIndividualList:
+ anIndex +=1
+ anIndex = 0
+ for aChild in aChildrenList:
+ anIndex +=1
+ self.theIndividualList = aChildrenList
- # ------------------------------------------------------------------
- def __executeMutationStrategy( self ):
- '''Execute mutation strategy
- Mutate all individuals according to a probability.
- At first the M0 is used as the initial mutation value.
- When the best evaluated value is not changed compared to previous one,
- the mutation ratio is raised by multiplying constantk k(>1.0).
- The mutation ration is fixed MMAX, when it reaches upper limit.
- When the best evaluated value is improved, it is changed to M0.
- '''
+ # ------------------------------------------------------------------
+ def __executeMutationStrategy( self ):
+ '''Execute mutation strategy
+ Mutate all individuals according to a probability.
+ At first the M0 is used as the initial mutation value.
+ When the best evaluated value is not changed compared to previous one,
+ the mutation ratio is raised by multiplying constantk k(>1.0).
+ The mutation ration is fixed MMAX, when it reaches upper limit.
+ When the best evaluated value is improved, it is changed to M0.
+ '''
- # When first generation
- if self.theMutationRatio == None:
+ # When first generation
+ if self.theMutationRatio == None:
- # save initial value to instance attribute
- self.theMutationRatio = self.theSetting['M0']
+ # save initial value to instance attribute
+ self.theMutationRatio = self.theSetting['M0']
- # Second generation and after
- else:
+ # Second generation and after
+ else:
- # When the elite value is improved, set mutation rate
- # as initial value m0
- if self.theEliteImprovedFlag == True:
- self.theMutationRatio = self.theSetting['M0']
+ # When the elite value is improved, set mutation rate
+ # as initial value m0
+ if self.theEliteImprovedFlag == True:
+ self.theMutationRatio = self.theSetting['M0']
- # When the elite value is not improved, multiple
- # mutation rate by k
- else:
+ # When the elite value is not improved, multiple
+ # mutation rate by k
+ else:
- self.theMutationRatio *= self.theSetting['K']
-
- # When the mutation ratio > the maximum,
- # set it as the maximum mmax
- if self.theMutationRatio > self.theSetting['MMAX']:
- self.theMutationRatio = self.theSetting['MMAX']
+ self.theMutationRatio *= self.theSetting['K']
+
+ # When the mutation ratio > the maximum,
+ # set it as the maximum mmax
+ if self.theMutationRatio > self.theSetting['MMAX']:
+ self.theMutationRatio = self.theSetting['MMAX']
- for anIndividual in self.theIndividualList:
- anIndividual.mutate(self.theMutationRatio)
+ for anIndividual in self.theIndividualList:
+ anIndividual.mutate(self.theMutationRatio)
- # -----------------------------------------------------------------------
- # Write mutation value to file
- # -----------------------------------------------------------------------
- aContents = "%s\t%s\n" %(self.theCurrentGeneration,
- self.theMutationRatio)
+ # -----------------------------------------------------------------------
+ # Write mutation value to file
+ # -----------------------------------------------------------------------
+ aContents = "%s\t%s\n" %(self.theCurrentGeneration,
+ self.theMutationRatio)
- if self.theCurrentGeneration == 1:
- open( self.theSetting['MUTATION VALUE FILE'], 'w').write(aContents)
- else:
- open( self.theSetting['MUTATION VALUE FILE'], 'a').write(aContents)
+ if self.theCurrentGeneration == 1:
+ open( self.theSetting['MUTATION VALUE FILE'], 'w').write(aContents)
+ else:
+ open( self.theSetting['MUTATION VALUE FILE'], 'a').write(aContents)
# ###################################################################################
class Individual:
- '''Individual class
- has geno type, evaluated value and job ID list.
- '''
+ '''Individual class
+ has geno type, evaluated value and job ID list.
+ '''
- theParameterMap = None # parameter map
- theSetting = None # Setting instance
+ theParameterMap = None # parameter map
+ theSetting = None # Setting instance
- # ----------------------------------------------------------
- def __init__( self, aSetting ):
- '''Constructor
+ # ----------------------------------------------------------
+ def __init__( self, aSetting ):
+ '''Constructor
- aSetting -- Setting instance
- '''
+ aSetting -- Setting instance
+ '''
- Individual.theSetting = aSetting
- self.theGenoType = None
- self.theEvaluatedValue = None
- self.theJobIDList = None
+ Individual.theSetting = aSetting
+ self.theGenoType = None
+ self.theEvaluatedValue = None
+ self.theJobIDList = None
- # ----------------------------------------------------------
- def __cmp__(self,other):
- '''Overwrite __cmp__ method
- The instances of this class are compared according to
- the evaluated value
+ # ----------------------------------------------------------
+ def __cmp__(self,other):
+ '''Overwrite __cmp__ method
+ The instances of this class are compared according to
+ the evaluated value
- other -- Individual instance
+ other -- Individual instance
- Return boolean : the result of comparison
- '''
+ Return boolean : the result of comparison
+ '''
- try:
- return cmp(self.theEvaluatedValue,other.theEvaluatedValue)
- except:
- return False
+ try:
+ return cmp(self.theEvaluatedValue,other.theEvaluatedValue)
+ except:
+ return False
- # ----------------------------------------------------------
- def setJobIDList( self, aJobIDList ):
- '''set a job id list
+ # ----------------------------------------------------------
+ def setJobIDList( self, aJobIDList ):
+ '''set a job id list
- aJobIDList -- a list of lib id (list)
+ aJobIDList -- a list of lib id (list)
- Return None
- '''
+ Return None
+ '''
- # set job id list
- self.theJobIDList = aJobIDList
+ # set job id list
+ self.theJobIDList = aJobIDList
- # ----------------------------------------------------------
- def getJobList( self ):
- '''get the job id list
+ # ----------------------------------------------------------
+ def getJobList( self ):
+ '''get the job id list
- Return list of int : job id list
- '''
+ Return list of int : job id list
+ '''
- # return job id
- return self.theJobIDList
+ # return job id
+ return self.theJobIDList
- # ----------------------------------------------------------
- def setParameterMap( self, aParameterMap ):
- '''Class Method
- Set parameter map
+ # ----------------------------------------------------------
+ def setParameterMap( self, aParameterMap ):
+ '''Class Method
+ Set parameter map
- aParameterMap -- a parameter map (dict)
+ aParameterMap -- a parameter map (dict)
- Return None
- '''
+ Return None
+ '''
- # set parameter map
- Individual.theParameterMap = aParameterMap
+ # set parameter map
+ Individual.theParameterMap = aParameterMap
- # register class method
- setParameterMap = classmethod(setParameterMap)
+ # register class method
+ setParameterMap = classmethod(setParameterMap)
- # ----------------------------------------------------------
- def getParameterMap( self ):
- '''Class Method
- Retunr parameter map
+ # ----------------------------------------------------------
+ def getParameterMap( self ):
+ '''Class Method
+ Retunr parameter map
- Return dict : parameter map
- '''
+ Return dict : parameter map
+ '''
- return Individual.theParameterMap
+ return Individual.theParameterMap
- # register class method
- getParameterMap = classmethod(getParameterMap)
+ # register class method
+ getParameterMap = classmethod(getParameterMap)
- # ----------------------------------------------------------
- def constructRandomly( self ):
- '''ABSTRACT : This method must be overwrote in subclass
- initialize genotype randomly
- raise NotImplementedError
- '''
+ # ----------------------------------------------------------
+ def constructRandomly( self ):
+ '''ABSTRACT : This method must be overwrote in subclass
+ initialize genotype randomly
+ raise NotImplementedError
+ '''
- # When this method is not implemented in sub class,
- # raise NotImplementedError
- import inspect
- caller = inspect.getouterframes(inspect.currentframe())[0][3]
- raise NotImplementedError(caller + ' must be implemented in subclass')
+ # When this method is not implemented in sub class,
+ # raise NotImplementedError
+ import inspect
+ caller = inspect.getouterframes(inspect.currentframe())[0][3]
+ raise NotImplementedError(caller + ' must be implemented in subclass')
- # ----------------------------------------------------------
- def getGenoType(self):
- '''Return genotype
+ # ----------------------------------------------------------
+ def getGenoType(self):
+ '''Return genotype
- Return dict : genotype
- '''
+ Return dict : genotype
+ '''
- # return the genotype
- return self.theGenoType
+ # return the genotype
+ return self.theGenoType
- # ----------------------------------------------------------
- def setEvaluatedValue(self,anEvaluatedValue):
- '''Set evaluated value
+ # ----------------------------------------------------------
+ def setEvaluatedValue(self,anEvaluatedValue):
+ '''Set evaluated value
- anEvaluatedValue -- an evaluated value (float)
+ anEvaluatedValue -- an evaluated value (float)
- Return None
- '''
+ Return None
+ '''
- # set an evaluated value
- self.theEvaluatedValue = anEvaluatedValue
+ # set an evaluated value
+ self.theEvaluatedValue = anEvaluatedValue
- # ----------------------------------------------------------
- def getEvaluatedValue(self):
- '''Return evaluated value
+ # ----------------------------------------------------------
+ def getEvaluatedValue(self):
+ '''Return evaluated value
- Return float : the evaluated value
- '''
+ Return float : the evaluated value
+ '''
- # return the evaluated value
- return self.theEvaluatedValue
+ # return the evaluated value
+ return self.theEvaluatedValue
# ###################################################################################
class RealCodedIndividual(Individual):
- '''Individual for Real Coded GA
- '''
+ '''Individual for Real Coded GA
+ '''
- # ----------------------------------------------------------
- def __init__( self, aSetting ):
- '''Constructor
- '''
+ # ----------------------------------------------------------
+ def __init__( self, aSetting ):
+ '''Constructor
+ '''
- # call superclass's constructor
- Individual.__init__(self,aSetting)
+ # call superclass's constructor
+ Individual.__init__(self,aSetting)
- # ----------------------------------------------------------
- def constructRandomly( self ):
- '''initialize genotype randomly
+ # ----------------------------------------------------------
+ def constructRandomly( self ):
+ '''initialize genotype randomly
- [1] Generate random number between minimum limit and
- maximum one.
- [2] If the type of genotype is integer, round it.
- [3] Save it.
+ [1] Generate random number between minimum limit and
+ maximum one.
+ [2] If the type of genotype is integer, round it.
+ [3] Save it.
- Return None
- '''
+ Return None
+ '''
- # initialize genotype dictonary
- self.theGenoType = {}
+ # initialize genotype dictonary
+ self.theGenoType = {}
- for aFullID in Individual.theParameterMap.keys():
-
- # --------------------------------------------------
- # [1] Generate random number between minimum limit and
- # maximum one.
- # --------------------------------------------------
- aRandomNumber = random.random()
- aMax = Individual.theParameterMap[aFullID][MAX]
- aMin = Individual.theParameterMap[aFullID][MIN]
- aRandomNumber = (aMax-aMin)*aRandomNumber+aMin
- aType = Individual.theParameterMap[aFullID][TYPE]
+ fo...
[truncated message content] |