本文整理汇总了Python中FunctionSlot.FunctionSlot.applyFunctions方法的典型用法代码示例。如果您正苦于以下问题:Python FunctionSlot.applyFunctions方法的具体用法?Python FunctionSlot.applyFunctions怎么用?Python FunctionSlot.applyFunctions使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类FunctionSlot.FunctionSlot
的用法示例。
在下文中一共展示了FunctionSlot.applyFunctions方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: MPIMigrator
# 需要导入模块: from FunctionSlot import FunctionSlot [as 别名]
# 或者: from FunctionSlot.FunctionSlot import applyFunctions [as 别名]
#.........这里部分代码省略.........
self.nMigrationRate = generations
def getMigrationRate(self):
""" Return the the generation frequency supposed to migrate
and receive individuals
:rtype: the number of generations
"""
return self.nMigrationRate
def setGAEngine(self, ga_engine):
""" Sets the GA Engine handler """
self.GAEngine = ga_engine
def start(self):
""" Initializes the migration scheme """
pass
def stop(self):
""" Stops the migration engine """
pass
def getGroupName(self):
""" Gets the group name
.. note:: all islands of evolution which are supposed to exchange
individuals, must have the same group name.
"""
return self.groupName
def setGroupName(self, name):
""" Sets the group name
:param name: the group name
.. note:: all islands of evolution which are supposed to exchange
individuals, must have the same group name.
"""
self.groupName = name
def select(self):
""" Pickes an individual from population using specific selection method
:rtype: an individual object
"""
if self.selector.isEmpty():
return self.GAEngine.select(popID=self.GAEngine.currentGeneration)
else:
for it in self.selector.applyFunctions(self.GAEngine.internalPop,
popID=self.GAEngine.currentGeneration):
return it
def selectPool(self, num_individuals):
""" Select num_individuals number of individuals and return a pool
:param num_individuals: the number of individuals to select
:rtype: list with individuals
"""
pool = [self.select() for _ in xrange(num_individuals)]
return pool
def gather_bests(self):
'''
Collect all the best individuals from the various populations. The
result is stored in process 0
'''
best_guy = self.best_selector(self.GAEngine.internalPop,
popID=self.GAEngine.currentGeneration)
self.all_stars = self.comm.gather(sendobj = best_guy, root = 0)
def exchange(self):
""" This is the main method, is where the individuals
are exchanged """
if not self.isReady():
return
pool_to_send = self.selectPool(self.getNumIndividuals())
pool_received = self.comm.sendrecv(sendobj=pool_to_send,
dest=self.dest,
sendtag=0,
recvobj=None,
source=self.source,
recvtag=0)
population = self.GAEngine.getPopulation()
pool = pool_received
for i in xrange(self.getNumReplacement()):
if len(pool) <= 0:
break
choice = rand_choice(pool)
pool.remove(choice)
# replace the worst
population[len(population)-1-i] = choice
self.gather_bests()
示例2: __init__
# 需要导入模块: from FunctionSlot import FunctionSlot [as 别名]
# 或者: from FunctionSlot.FunctionSlot import applyFunctions [as 别名]
#.........这里部分代码省略.........
the same instance of this dict.
:param args: this params will saved in every chromosome for genetic op. use
"""
self.internalParams.update(args)
def getParam(self, key, nvl=None):
""" Gets an internal parameter
Example:
>>> genome.getParam("rangemax")
100
.. note:: All the individuals of the population shares this parameters and uses
the same instance of this dict.
:param key: the key of param
:param nvl: if the key doesn't exist, the nvl will be returned
"""
return self.internalParams.get(key, nvl)
def resetStats(self):
""" Clear score and fitness of genome """
self.score = 0.0
self.fitness = 0.0
def evaluate(self, **args):
""" Called to evaluate genome
:param args: this parameters will be passes to the evaluator
"""
self.resetStats()
for it in self.evaluator.applyFunctions(self, **args):
self.score += it
def initialize(self, **args):
""" Called to initialize genome
:param args: this parameters will be passed to the initializator
"""
for it in self.initializator.applyFunctions(self, **args):
pass
def mutate(self, **args):
""" Called to mutate the genome
:param args: this parameters will be passed to the mutator
:rtype: the number of mutations returned by mutation operator
"""
nmuts = 0
for it in self.mutator.applyFunctions(self, **args):
nmuts+=it
return nmuts
def premutate(self, **args):
""" Called to pre-mutate the genome
:param args: this parameters will be passed to the premutator
:rtype: the number of mutations returned by mutation operator
"""
nmuts = 0
for it in self.premutator.applyFunctions(self, **args):
nmuts+=it
return nmuts
def copy(self, g):
""" Copy the current GenomeBase to 'g'
:param g: the destination genome
.. note:: If you are planning to create a new chromosome representation, you
**must** implement this method on your class.
"""
g.score = self.score
g.fitness = self.fitness
g.evaluator = self.evaluator
g.initializator = self.initializator
g.mutator = self.mutator
g.premutator = self.premutator
g.crossover = self.crossover
#g.internalParams = self.internalParams.copy()
g.internalParams = self.internalParams
def clone(self):
""" Clone this GenomeBase
:rtype: the clone genome
.. note:: If you are planning to create a new chromosome representation, you
**must** implement this method on your class.
"""
newcopy = GenomeBase()
self.copy(newcopy)
return newcopy
示例3: __init__
# 需要导入模块: from FunctionSlot import FunctionSlot [as 别名]
# 或者: from FunctionSlot.FunctionSlot import applyFunctions [as 别名]
#.........这里部分代码省略.........
def setNumReplacement(self, num_individuals):
""" Return the number of individuals that will be
replaced in the migration process
:param num_individuals: the number of individuals to be replaced
"""
self.nReplacement = num_individuals
def getNumIndividuals(self):
""" Return the number of individuals that will migrate
:rtype: the number of individuals to be replaced
"""
return self.nIndividuals
def setNumIndividuals(self, num_individuals):
""" Set the number of individuals that will migrate
:param num_individuals: the number of individuals
"""
self.nIndividuals = num_individuals
def setMigrationRate(self, generations):
""" Sets the generation frequency supposed to migrate
and receive individuals.
:param generations: the number of generations
"""
self.nMigrationRate = generations
def getMigrationRate(self):
""" Return the the generation frequency supposed to migrate
and receive individuals
:rtype: the number of generations
"""
return self.nMigrationRate
def setGAEngine(self, ga_engine):
""" Sets the GA Engine handler """
self.GAEngine = ga_engine
def start(self):
""" Initializes the migration scheme """
pass
def stop(self):
""" Stops the migration engine """
pass
def getGroupName(self):
""" Gets the group name
.. note:: all islands of evolution which are supposed to exchange
individuals, must have the same group name.
"""
return self.groupName
def setGroupName(self, name):
""" Sets the group name
:param name: the group name
.. note:: all islands of evolution which are supposed to exchange
individuals, must have the same group name.
"""
self.groupName = name
def setMyself(self, host, port):
""" Which interface you will use to send/receive data
:param host: your hostname
:param port: your port
"""
self.myself = (host, port)
def select(self):
""" Pickes an individual from population using specific selection method
:rtype: an individual object
"""
if self.selector.isEmpty():
return self.GAEngine.select(popID=self.GAEngine.currentGeneration)
else:
for it in self.selector.applyFunctions(self.GAEngine.internalPop, popID=self.GAEngine.currentGeneration):
return it
def selectPool(self, num_individuals):
""" Select num_individuals number of individuals and return a pool
:param num_individuals: the number of individuals to select
:rtype: list with individuals
"""
pool = [self.select() for i in xrange(num_individuals)]
return pool
def exchange(self):
""" Exchange individuals """
pass
示例4: your_func
# 需要导入模块: from FunctionSlot import FunctionSlot [as 别名]
# 或者: from FunctionSlot.FunctionSlot import applyFunctions [as 别名]
#.........这里部分代码省略.........
:rtype: the population (:class:`GPopulation.GPopulation`)
"""
return self.internalPop
def getStatistics(self):
""" Gets the Statistics class instance of current generation
:rtype: the statistics instance (:class:`Statistics.Statistics`)
"""
return self.internalPop.getStatistics()
def step(self):
""" Just do one step in evolution, one generation """
genomeMom = None
genomeDad = None
newPop = GPopulation(self.internalPop)
logging.debug("Population was cloned.")
size_iterate = len(self.internalPop)
# Odd population size
if size_iterate % 2 != 0: size_iterate -= 1
crossover_empty = self.select(popID=self.currentGeneration).crossover.isEmpty()
for i in xrange(0, size_iterate, 2):
genomeMom = self.select(popID=self.currentGeneration)
genomeDad = self.select(popID=self.currentGeneration)
if not crossover_empty and self.pCrossover >= 1.0:
for it in genomeMom.crossover.applyFunctions(mom=genomeMom, dad=genomeDad, count=2):
(sister, brother) = it
else:
if not crossover_empty and Util.randomFlipCoin(self.pCrossover):
for it in genomeMom.crossover.applyFunctions(mom=genomeMom, dad=genomeDad, count=2):
(sister, brother) = it
else:
sister = genomeMom.clone()
brother = genomeDad.clone()
sister.mutate(pmut=self.pMutation, ga_engine=self)
brother.mutate(pmut=self.pMutation, ga_engine=self)
newPop.internalPop.append(sister)
newPop.internalPop.append(brother)
if len(self.internalPop) % 2 != 0:
genomeMom = self.select(popID=self.currentGeneration)
genomeDad = self.select(popID=self.currentGeneration)
if Util.randomFlipCoin(self.pCrossover):
for it in genomeMom.crossover.applyFunctions(mom=genomeMom, dad=genomeDad, count=1):
(sister, brother) = it
else:
sister = random.choice([genomeMom, genomeDad])
sister = sister.clone()
sister.mutate(pmut=self.pMutation, ga_engine=self)
newPop.internalPop.append(sister)
logging.debug("Evaluating the new created population.")
newPop.evaluate()
示例5: xrange
# 需要导入模块: from FunctionSlot import FunctionSlot [as 别名]
# 或者: from FunctionSlot.FunctionSlot import applyFunctions [as 别名]
#.........这里部分代码省略.........
:param args: this params are passed to the evaluation function
"""
# We have multiprocessing
if self.multiProcessing[0] and MULTI_PROCESSING:
logging.debug("Evaluating the population using the multiprocessing method")
#Make sure we have a process pool.
if self.proc_pool is None:
self.initializeMultiProcessing()
# Multiprocessing full_copy parameter
if self.multiProcessing[1]:
results = self.proc_pool.map(multiprocessing_eval_full, self.internalPop)
for i in xrange(len(self.internalPop)):
self.internalPop[i] = results[i]
else:
results = self.proc_pool.map(multiprocessing_eval, self.internalPop)
for individual, score in zip(self.internalPop, results):
individual.score = score
else:
#Direct evaluation (no multiprocessing)
for ind in self.internalPop:
ind.evaluate(**args)
self.clearFlags()
def scale(self, **args):
""" Scale the population using the scaling method
:param args: this parameter is passed to the scale method
"""
for it in self.scaleMethod.applyFunctions(self, **args):
pass
fit_sum = 0
for ind in xrange(len(self)):
fit_sum += self[ind].fitness
self.stats["fitMax"] = max(self, key=key_fitness_score).fitness
self.stats["fitMin"] = min(self, key=key_fitness_score).fitness
self.stats["fitAve"] = fit_sum / float(len(self))
self.sorted = False
def printStats(self):
""" Print statistics of the current population """
message = ""
if self.sortType == Consts.sortType["scaled"]:
message = "Max/Min/Avg Fitness(Raw) [%(fitMax).2f(%(rawMax).2f)/%(fitMin).2f(%(rawMin).2f)/%(fitAve).2f(%(rawAve).2f)]" % self.stats
else:
message = "Max/Min/Avg Raw [%(rawMax).2f/%(rawMin).2f/%(rawAve).2f]" % self.stats
logging.info(message)
print message
return message
def copy(self, pop):
""" Copy current population to 'pop'
:param pop: the destination population
.. warning:: this method do not copy the individuals, only the population logic
"""
pop.popSize = self.popSize
示例6: ParticleBase
# 需要导入模块: from FunctionSlot import FunctionSlot [as 别名]
# 或者: from FunctionSlot.FunctionSlot import applyFunctions [as 别名]
#.........这里部分代码省略.........
ret += "\t"+ slot.__repr__()
ret += "\n"
return ret
def setOwnBestFitness(self,fitness):
""" Set the best fitness of the particle
:param fitness: the best fitness of the particle
"""
self.ownBestFitness = fitness
def setParams(self, **args):
"""Set the initializator params"
Example:
>>> particle.setParams(rangemin=0, rangeMax=100,dimmensions=4)
:param args: this params will saved in every particle for swarm op. use
"""
self.internalParams.update(args)
def getParam(self,key,nvl=None):
""" Gets an initialization parameter
Example:
>>> particle.getParam("rangemax")
100
:param key: the key of parma
:param nvl: if the key doesn't exist, the nvl will be returned
"""
return self.internalParams.get(key,nvl)
def resetStats(self):
"""Clear fitness of the particle """
self.fitness = 0.0
def evaluate(self, **args):
""" Called to evaluate the particle
:param args: these parameters will be passed to the evaluator
"""
self.resetStats()
for it in self.evaluator.applyFunctions(self, **args):
self.fitness += it
def initializePosition(self, **args):
"""Called to initialize the particle position
:param args: these parameters will be passed to the initializator
"""
for it in self.position_initializator.applyFunctions(self, **args):
pass
def initializeVelocity(self, **args):
"""Called to initialize the particle velocity
:param args: these parameters will be passed to the initializator
"""
for it in self.velocity_initializator.applyFunctions(self,**args):
pass
def copy(self, other):
""" Copy the current GenomeBase to 'g'
:param other: the destination particle
"""
other.fitness = self.fitness
other.ownBestFitness = self.ownBestFitness
other.evaluator = self.evaluator
other.position_initializator = self.position_initializator
other.velocity_initializator = self.velocity_initializator
other.position_communicator = self.position_communicator
other.information_communicator = self.information_communicator
other.allSlots = self.allSlots[:]
other.internalParams = self.internalParams.copy()
def clone(self):
""" Clone this ParticleBase
:rtype: the clone particle
"""
newcopy = ParticleBase()
self.copy(newcopy)
return newcopy
示例7: SimplePSO
# 需要导入模块: from FunctionSlot import FunctionSlot [as 别名]
# 或者: from FunctionSlot.FunctionSlot import applyFunctions [as 别名]
#.........这里部分代码省略.........
"""
return self.topology.getStatistics()
def dumpStatsReport(self):
""" Dumps the current statistics to the report adapter """
self.topology.statistics()
self.reportAdapter.insert(self.getStatistics(),self.topology,self.currentStep)
def printStats(self):
""" Print swarm statistics"""
percent = self.currentStep * 100 / float(self.timeSteps)
message = "Step: %d (%.2f%%):" % (self.currentStep, percent)
print message
self.topology.statistics()
self.topology.printStats()
def printTimeElapsed(self):
""" Shows the time elapsed since the beginning of the solution construction """
print "Total time elapsed: %.3f seconds." % (time()-self.time_init)
def initialize(self):
""" Initializes the PSO Engine. Create and initialize the swarm """
self.topology.create(minimax=self.minimax)
self.topology.initialize()
print "The PSO Engine was initialized !"
def constructSolution(self):
""" Just do one step in execution, one step."""
for it in self.topology.position_updater.applyFunctions(self):
pass
for it in self.topology.information_updater.applyFunctions(self):
pass
if self.psoType == Consts.psoType["INERTIA"]:
self.updateInertiaFactor()
self.currentStep += 1
return (self.currentStep == self.timeSteps)
def execute(self, freq_stats=0):
""" Do all the steps until the termination criteria or time Steps achieved,
accepts the freq_stats (default is 0) to dump statistics at n-step
Example:
>>> pso_engine.evolve(freq_stats=10)
(...)
:param freq_stats: if greater than 0, the statistics will be
printed every freq_stats step.
"""
#Start time
self.time_init = time()
#Creates a new report if reportAdapter is not None.
if self.reportAdapter: self.reportAdapter.open()
示例8: GenomeBase
# 需要导入模块: from FunctionSlot import FunctionSlot [as 别名]
# 或者: from FunctionSlot.FunctionSlot import applyFunctions [as 别名]
class GenomeBase(object):
""" GenomeBase Class - The base of all chromosome representation """
__slots__ = ["evaluator", "initializator", "mutator", "crossover", "internalParams", "score", "fitness"]
def __init__(self):
"""Genome Constructor"""
self.evaluator = FunctionSlot("Evaluator")
self.initializator = FunctionSlot("Initializator")
self.mutator = FunctionSlot("Mutator")
self.crossover = FunctionSlot("Crossover")
self.internalParams = {}
self.score = 0.0
self.fitness = 0.0
def getRawScore(self):
""" Get the Raw Score of the genome
:rtype: genome raw score
"""
return self.score
def getFitnessScore(self):
""" Get the Fitness Score of the genome
:rtype: genome fitness score
"""
return self.fitness
def __repr__(self):
"""String representation of Genome"""
allSlots = [self.evaluator, self.initializator, self.mutator,
self.crossover]
ret = "- GenomeBase\n"
ret += "\tScore:\t\t\t %.6f\n" % (self.score,)
ret += "\tFitness:\t\t %.6f\n\n" % (self.fitness,)
ret += "\tParams:\t\t %s\n\n" % (self.internalParams,)
for slot in allSlots:
ret += "\t" + slot.__repr__()
ret += "\n"
return ret
def setParams(self, **args):
""" Set the internal params
Example:
>>> genome.setParams(rangemin=0, rangemax=100, gauss_mu=0, gauss_sigma=1)
.. note:: All the individuals of the population shares this parameters and uses
the same instance of this dict.
:param args: this params will saved in every chromosome for genetic op. use
"""
self.internalParams.update(args)
def getParam(self, key, nvl=None):
""" Gets an internal parameter
Example:
>>> genome.getParam("rangemax")
100
.. note:: All the individuals of the population shares this parameters and uses
the same instance of this dict.
:param key: the key of param
:param nvl: if the key doesn't exist, the nvl will be returned
"""
return self.internalParams.get(key, nvl)
def resetStats(self):
""" Clear score and fitness of genome """
self.score = 0.0
self.fitness = 0.0
def evaluate(self, **args):
""" Called to evaluate genome
:param args: this parameters will be passes to the evaluator
"""
self.resetStats()
for it in self.evaluator.applyFunctions(self, **args):
self.score += it
def initialize(self, **args):
""" Called to initialize genome
:param args: this parameters will be passed to the initializator
"""
for it in self.initializator.applyFunctions(self, **args):
pass
#.........这里部分代码省略.........
示例9: xrange
# 需要导入模块: from FunctionSlot import FunctionSlot [as 别名]
# 或者: from FunctionSlot.FunctionSlot import applyFunctions [as 别名]
#.........这里部分代码省略.........
def setPopulationSize(self, size):
""" Set the population size
:param size: the population size
"""
self.popSize = size
def setSortType(self, sort_type):
""" Sets the sort type
Example:
>>> pop.setSortType(Consts.sortType["scaled"])
:param sort_type: the Sort Type
"""
self.sortType = sort_type
def create(self, **args):
""" Clone the example genome to fill the population """
self.clear()
self.minimax = args["minimax"]
for i in xrange(self.popSize):
self.internalPop.append(self.oneSelfGenome.clone())
self.__clear_flags()
def initialize(self):
""" Initialize all individuals of population,
this calls the initialize() of individuals """
for gen in self.internalPop:
gen.initialize()
self.__clear_flags()
def evaluate(self, **args):
""" Evaluate all individuals in population, calls the evaluate() method of individuals
:param args: this params are passed to the evaluation function
"""
for ind in self.internalPop:
ind.evaluate(**args)
self.__clear_flags()
def scale(self, **args):
""" Scale the population using the scaling method
:param args: this parameter is passed to the scale method
"""
for it in self.scaleMethod.applyFunctions(self, **args):
pass
fit_sum = 0
for ind in xrange(len(self)):
fit_sum += self[ind].fitness
self.stats["fitMax"] = max(self, key=key_fitness_score).fitness
self.stats["fitMin"] = min(self, key=key_fitness_score).fitness
self.stats["fitAve"] = fit_sum / float(len(self))
self.sorted = False
def printStats(self):
""" Print statistics of the current population """
message = ""
if self.sortType == Consts.sortType["scaled"]:
message = "Max/Min/Avg Fitness(Raw) [%.2f(%.2f)/%.2f(%.2f)/%.2f(%.2f)]" % (self.stats["fitMax"], self.stats["rawMax"], self.stats["fitMin"], self.stats["rawMin"], self.stats["fitAve"], self.stats["rawAve"])
else:
message = "Max/Min/Avg Raw [%.2f/%.2f/%.2f]" % (self.stats["rawMax"], self.stats["rawMin"], self.stats["rawAve"])
logging.info(message)
print message
return message
def copy(self, pop):
""" Copy current population to 'pop'
:param pop: the destination population
.. warning:: this method do not copy the individuals, only the population logic
"""
pop.popSize = self.popSize
pop.sortType = self.sortType
pop.sorted = self.sorted
pop.statted = self.statted
pop.minimax = self.minimax
pop.scaleMethod = self.scaleMethod
def clear(self):
""" Remove all individuals from population """
del self.internalPop[:]
self.__clear_flags()
def clone(self):
""" Return a brand-new cloned population """
newpop = GPopulation(self.oneSelfGenome.clone())
self.copy(newpop)
return newpop