本文整理汇总了Python中GPopulation.GPopulation类的典型用法代码示例。如果您正苦于以下问题:Python GPopulation类的具体用法?Python GPopulation怎么用?Python GPopulation使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了GPopulation类的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
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)
示例2: step
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):
#re-evaluate before being sure this is the best
self.internalPop.bestRaw(i).evaluate()
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):
#re-evaluate before being sure this is the best
self.internalPop.bestRaw(i).evaluate()
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)
示例3: your_func
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:
#.........这里部分代码省略.........
示例4: step
def step(self):
""" Just do one step in evolution, one generation """
genomeMom = None
genomeDad = None
newPop = GPopulation(self.internalPop)
if (MPI.COMM_WORLD.Get_rank() == 0): ### assumes WE are on top of hierarchy!
popsize = len(self.internalPop)
numAdded = 0
maxTries = 1000
numTries = 0
crossover_empty = self.select(popID=self.currentGeneration).crossover.isEmpty()
###TODO: enforce constraints!###
while numAdded < popsize:
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()
# logging.debug("done cloning")
sister.mutate(pmut=self.pMutation, ga_engine=self)
brother.mutate(pmut=self.pMutation, ga_engine=self)
if (numTries > maxTries or self.owner.eval_constraints(sister)):
newPop.internalPop.append(sister)
numAdded += 1
print "successfully added sister"
if (numAdded < popsize and (numTries > maxTries or self.owner.eval_constraints(brother))):
newPop.internalPop.append(brother)
print "successfully added brother"
numAdded += 1
numTries += 1
#end rank0 onlye
# print "rank %d start eval pop" % MPI.COMM_WORLD.Get_rank()
logging.debug("Evaluating the newly created population.")
newPop.evaluate()
# print "rank %d done eval pop" % MPI.COMM_WORLD.Get_rank()
# if (MPI.COMM_WORLD.Get_rank() == 0):
# print "after eval, new pop's positions are:"
# for p in newPop:
# print p.wt_positions
if (MPI.COMM_WORLD.Get_rank() == 0): ### assumes WE are on top of hierarchy!
if self.elitism:
logging.debug("Doing elitism, %d" % self.nElitismReplacement)
if self.getMinimax() == Consts.minimaxType["maximize"]:
for i in xrange(self.nElitismReplacement):
#re-evaluate before being sure this is the best
# self.internalPop.bestRaw(i).evaluate()
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):
#re-evaluate before being sure this is the best
# self.internalPop.bestRaw(i).evaluate()
if self.internalPop.bestRaw(i).score < newPop.bestRaw(i).score:
newPop[len(newPop)-1-i] = self.internalPop.bestRaw(i)
self.internalPop = newPop
if (MPI.COMM_WORLD.Get_rank() == 0): ### assumes WE are on top of hierarchy!
self.internalPop.sort()
# if (MPI.COMM_WORLD.Get_rank() == 0):
# print "after sort, internal pop's positions are:"
# for p in self.internalPop:
# print p.wt_positions
logging.debug("The generation %d was finished.", self.currentGeneration)
self.currentGeneration += 1
if (MPI.COMM_WORLD.Get_rank() == 0): ### assumes WE are on top of hierarchy!
self.saveState ()
return (self.currentGeneration == self.nGenerations)
示例5: step
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
#Check on the crossover function by picking a random individual - is it empty?
crossover_empty = self.select(popID=self.currentGeneration).crossover.isEmpty()
for i in xrange(0, size_iterate, 2):
#Ok, we select 2 parents using the selector (RouletteWheel, etc.)
genomeMom = self.select(popID=self.currentGeneration)
genomeDad = self.select(popID=self.currentGeneration)
if not crossover_empty and self.pCrossover >= 1.0:
#Crossover all of them
for it in genomeMom.crossover.applyFunctions(mom=genomeMom, dad=genomeDad, count=2):
(sister, brother) = it
else:
#Filp a coin each time to determine if you should crossover
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()
#And "pre" mutate them
sister.premutate(pmut=self.pPreMutation, ga_engine=self)
brother.premutate(pmut=self.pPreMutation, ga_engine=self)
#Now each offspring is mutated
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:
#Odd-numbered population
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()
#Do the 2 mutations
sister.premutate(pmut=self.pPreMutation, ga_engine=self)
sister.mutate(pmut=self.pMutation, ga_engine=self)
newPop.internalPop.append(sister)
#---- Evaluate fitness ------
logging.debug("Evaluating the new created population.")
newPop.evaluate()
#Niching methods- Petrowski's clearing
self.clear()
if self.elitism:
#Avoid too much elitism
if self.nElitismReplacement >= len(self.internalPop):
self.nElitismReplacement = len(self.internalPop)-1
logging.debug("Doing elitism.")
if self.getMinimax() == Consts.minimaxType["maximize"]:
#Replace the n-th worst new ones with the nth best old ones
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)