本文整理汇总了Python中FunctionSlot.FunctionSlot类的典型用法代码示例。如果您正苦于以下问题:Python FunctionSlot类的具体用法?Python FunctionSlot怎么用?Python FunctionSlot使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了FunctionSlot类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
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
示例2: __init__
def __init__(self):
""" Particle Constructor """
self.evaluator = FunctionSlot("Evaluator")
self.position_initializator = FunctionSlot("Position Initializator")
self.velocity_initializator = FunctionSlot(" Velocity Initializator")
self.position_communicator = FunctionSlot("Position Communicator")
self.information_communicator = FunctionSlot("Information Communicator")
self.allSlots = [self.evaluator, self.position_initializator,
self.velocity_initializator, self.position_communicator, self.information_communicator]
self.internalParams = {}
self.fitness = 0.0
self.ownBestFitness = 0.0
示例3: __init__
def __init__(self):
self.selector = FunctionSlot("Selector")
self.GAEngine = None
self.nMigrationRate = Consts.CDefGenMigrationRate
self.nIndividuals = Consts.CDefMigrationNIndividuals
self.nReplacement = Consts.CDefGenMigrationReplacement
self.networkCompression = 9
示例4: __init__
def __init__(self):
"""Genome Constructor"""
self.evaluator = FunctionSlot("Evaluator")
self.initializator = FunctionSlot("Initializator")
self.mutator = FunctionSlot("Mutator")
self.crossover = FunctionSlot("Crossover")
###
self.list_dic={}
self.list_margin={}
self.totalmoney=0
#my_set
self.internalParams = {}
self.score = 0.0
self.fitness = 0.0
示例5: __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)
示例6: __init__
def __init__(self, host, port, group_name):
self.myself = None
self.groupName = group_name
self.selector = FunctionSlot("Selector")
self.setMyself(host, port)
self.GAEngine = None
self.nMigrationRate = Consts.CDefGenMigrationRate
self.nIndividuals = Consts.CDefMigrationNIndividuals
self.nReplacement = Consts.CDefGenMigrationReplacement
self.networkCompression = 9
示例7: __init__
def __init__(self, genome):
""" The GPopulation Class creator """
if isinstance(genome, GPopulation):
self.oneSelfGenome = genome.oneSelfGenome
self.internalPop = []
self.internalPopRaw = []
self.popSize = genome.popSize
self.sortType = genome.sortType
self.sorted = False
self.minimax = genome.minimax
self.scaleMethod = genome.scaleMethod
self.allSlots = [self.scaleMethod]
self.evaluator = FunctionSlot("Evaluator")
self.internalParams = genome.internalParams
self.multiProcessing = genome.multiProcessing
self.statted = False
self.stats = Statistics()
return
logging.debug("New population instance, %s class genomes.", genome.__class__.__name__)
self.oneSelfGenome = genome
self.internalPop = []
self.internalPopRaw = []
self.popSize = 0
self.sortType = Consts.CDefPopSortType
self.sorted = False
self.minimax = Consts.CDefPopMinimax
self.scaleMethod = FunctionSlot("Scale Method")
self.scaleMethod.set(Consts.CDefPopScale)
self.allSlots = [self.scaleMethod]
self.evaluator = FunctionSlot("Evaluator")
self.internalParams = {}
self.multiProcessing = (False, False)
# Statistics
self.statted = False
self.stats = Statistics()
示例8: __init__
def __init__(self,topology,seed=None,interactiveMode=True):
""" Initializator of PSO """
#random seed
random.seed(seed)
#Pso type used by the particle
self.psoType = Consts.CDefPsoType
#Topology used
self.topology = topology
#Set the population size
self.setSwarmSize(Consts.CDefSwarmSize)
#Cognitive and Social Coefficients
self.C1,self.C2 = Consts.CDefCoefficients
#Time steps
self.timeSteps = Consts.CDefSteps
#Interactive Mode (True or False)
self.interactiveMode = interactiveMode
#Current step
self.currentStep = 0
#Inertia Factor Minus
self.inertiaFactorMinus = None
#Inertia coefficient
self.inertiaFactor = None
#Time initial
self.time_init = None
#Optimization type
self.minimax = Consts.minimaxType["minimize"]
#Report file adapter
self.reportAdapter = None
#Step Callback
self.stepCallback = FunctionSlot("Step Callback")
#Termination Criteria
self.terminationCriteria = FunctionSlot("Termination Criteria")
#All slots
self.allSlots = [self.stepCallback, self.terminationCriteria]
print "A PSO Engine was created, timeSteps=% d" % ( self.timeSteps, )
示例9: __init__
def __init__(self, genome):
""" The GPopulation Class creator """
logging.debug("New population instance, %s class genomes.", genome.__class__.__name__)
self.oneSelfGenome = genome
self.internalPop = []
self.popSize = 0
self.sortType = Consts.CDefPopSortType
self.sorted = False
self.minimax = Consts.CDefPopMinimax
self.scaleMethod = FunctionSlot("Scale Method")
self.scaleMethod.set(Consts.CDefPopScale)
self.allSlots = [self.scaleMethod]
# Statistics
self.statted = False
self.stats = Statistics()
示例10: __init__
def __init__(self):
self.myself = None
self.selector = FunctionSlot("Selector")
self.GAEngine = None
self.nMigrationRate = Consts.CDefGenMigrationRate
self.nIndividuals = Consts.CDefMigrationNIndividuals
self.nReplacement = Consts.CDefGenMigrationReplacement
self.comm = MPI.COMM_WORLD
self.pid = self.comm.rank
self.best_selector = Selectors.GRankSelector
#now this is fixed
if self.pid == 0:
self.source = self.comm.size - 1
else:
self.source = self.comm.rank - 1
self.dest = (self.comm.rank +1) % (self.comm.size)
self.all_stars = None
示例11: GenomeBase
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
#.........这里部分代码省略.........
示例12: 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:
#.........这里部分代码省略.........
示例13: SimplePSO
class SimplePSO(object):
""" SimplePSO Engine Class - The PSO Algorithm Core
Example:
>>> topology = Topology.GlobalTopology(particle_rep)
>>> pso = PSO.SimplePSO(topology)
>>> pso.setSteps(120)
:param topology: the :term:`Sample Topology``
:param interactiveMode: this flag enables the Interactive Mode
:param seed: the random seed value
.. note:: if you see the same random seed, all the runs of the algorithm will be the same.
"""
stepCallBack = None
""" This is the the :term: `step callback function` slot,
if you want to set the function, you must do this: ::
def your_func(pso_engine):
#Here you have access to the PSO Engine
return False
pso_engine.stepCallback.set(your_func)
now *"your_func"* will be called every step.
When this function returns True, the PSO 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 mus do this: ::
pso_engine.terminationCriteria.set(your_func)
Now, when you run your PSO, it will stop when terminationCriteria be satisfied.
To create your own termination function, you must put at least one parameter
which is the PSO Engine, follows an example: ::
def ConvergenceCriteria(pso_engine):
swarm = pso_engine.getSwarm()
return swarm[0] == swarm[len(swarm)-1]
When this function returns True, the Pso Engine will stop the evolution and show
a warning. If is False, the evolution continues, this function is called every
step.
"""
def __init__(self,topology,seed=None,interactiveMode=True):
""" Initializator of PSO """
#random seed
random.seed(seed)
#Pso type used by the particle
self.psoType = Consts.CDefPsoType
#Topology used
self.topology = topology
#Set the population size
self.setSwarmSize(Consts.CDefSwarmSize)
#Cognitive and Social Coefficients
self.C1,self.C2 = Consts.CDefCoefficients
#Time steps
self.timeSteps = Consts.CDefSteps
#Interactive Mode (True or False)
self.interactiveMode = interactiveMode
#Current step
self.currentStep = 0
#Inertia Factor Minus
self.inertiaFactorMinus = None
#Inertia coefficient
self.inertiaFactor = None
#Time initial
self.time_init = None
#Optimization type
self.minimax = Consts.minimaxType["minimize"]
#Report file adapter
self.reportAdapter = None
#Step Callback
self.stepCallback = FunctionSlot("Step Callback")
#Termination Criteria
self.terminationCriteria = FunctionSlot("Termination Criteria")
#All slots
self.allSlots = [self.stepCallback, self.terminationCriteria]
print "A PSO Engine was created, timeSteps=% d" % ( self.timeSteps, )
def __repr__(self):
""" The String representation of the PSO Engine """
ret = "- PSO-%s-%s Execution\n" % (self.getTopologyType(),self.getPsoType())
ret += "\tSwarm Size:\t %d\n" % (self.topology.swarmSize,)
ret += "\tTime Steps:\t %d\n" % (self.timeSteps,)
ret += "\tCurrent Step:\t %d\n" % (self.currentStep,)
ret += "\tMinimax Type:\t %s\n" % (Consts.minimaxType.keys()[Consts.minimaxType.values().index(self.minimax)].capitalize(),)
ret += "\tReport Adapter:\t %s\n" % (self.reportAdapter,)
for slot in self.allSlots:
ret += "\t" + slot.__repr__()
#.........这里部分代码省略.........
示例14: xrange
class GPopulation:
""" GPopulation Class - The container for the population
**Examples**
Get the population from the :class:`GSimpleGA.GSimpleGA` (GA Engine) instance
>>> pop = ga_engine.getPopulation()
Get the best fitness individual
>>> bestIndividual = pop.bestFitness()
Get the best raw individual
>>> bestIndividual = pop.bestRaw()
Get the statistics from the :class:`Statistics.Statistics` instance
>>> stats = pop.getStatistics()
>>> print stats["rawMax"]
10.4
Iterate, get/set individuals
>>> for ind in pop:
>>> print ind
(...)
>>> for i in xrange(len(pop)):
>>> print pop[i]
(...)
>>> pop[10] = newGenome
>>> pop[10].fitness
12.5
:param genome: the :term:`Sample genome`, or a GPopulation object, when cloning.
"""
def __init__(self, genome):
""" The GPopulation Class creator """
if isinstance(genome, GPopulation):
#Cloning a population?
self.oneSelfGenome = genome.oneSelfGenome
self.internalPop = []
self.internalPopRaw = []
self.popSize = genome.popSize
self.sortType = genome.sortType
self.sorted = False
self.minimax = genome.minimax
self.scaleMethod = genome.scaleMethod
self.allSlots = [self.scaleMethod]
self.internalParams = genome.internalParams
self.multiProcessing = genome.multiProcessing
self.statted = False
self.stats = Statistics()
self.proc_pool = genome.proc_pool
return
logging.debug("New population instance, %s class genomes.", genome.__class__.__name__)
self.oneSelfGenome = genome
self.internalPop = []
self.internalPopRaw = []
self.popSize = 0
self.proc_pool = None
self.sortType = Consts.CDefPopSortType
self.sorted = False
self.minimax = Consts.CDefPopMinimax
self.scaleMethod = FunctionSlot("Scale Method")
self.scaleMethod.set(Consts.CDefPopScale)
self.allSlots = [self.scaleMethod]
self.internalParams = {}
self.multiProcessing = (False, False)
# Statistics
self.statted = False
self.stats = Statistics()
#---------------------------------------------------------------------------------
def setMultiProcessing(self, flag=True, full_copy=False, number_of_processes=None):
""" Sets the flag to enable/disable the use of python multiprocessing module.
Use this option when you have more than one core on your CPU and when your
evaluation function is very slow.
The parameter "full_copy" defines where the individual data should be copied back
after the evaluation or not. This parameter is useful when you change the
individual in the evaluation function.
:param flag: True (default) or False
:param full_copy: True or False (default)
:param number_of_processes: None = use the default, or specify the number
.. warning:: Use this option only when your evaluation function is slow, se you
will get a good tradeoff between the process communication speed and the
parallel evaluation.
"""
#Save the parameters
old_settings = self.multiProcessing
self.multiProcessing = (flag, full_copy, number_of_processes)
#Re-initialize if anything changed.
if (old_settings != self.multiProcessing):
#.........这里部分代码省略.........
示例15: MPIMigrator
class MPIMigrator(object):
selector = None
""" This is the function slot for the selection method
if you want to change the default selector, you must do this: ::
migration_scheme.selector.set(Selectors.GRouletteWheel) """
def __init__(self):
self.myself = None
self.selector = FunctionSlot("Selector")
self.GAEngine = None
self.nMigrationRate = Consts.CDefGenMigrationRate
self.nIndividuals = Consts.CDefMigrationNIndividuals
self.nReplacement = Consts.CDefGenMigrationReplacement
self.comm = MPI.COMM_WORLD
self.pid = self.comm.rank
self.best_selector = Selectors.GRankSelector
#now this is fixed
if self.pid == 0:
self.source = self.comm.size - 1
else:
self.source = self.comm.rank - 1
self.dest = (self.comm.rank +1) % (self.comm.size)
self.all_stars = None
def isReady(self):
""" Returns true if is time to migrate """
if self.GAEngine.getCurrentGeneration() == 0:
return False
if self.GAEngine.getCurrentGeneration() % self.nMigrationRate == 0:
return True
else:
return False
def getNumReplacement(self):
""" Return the number of individuals that will be
replaced in the migration process """
return self.nReplacement
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.
"""
#.........这里部分代码省略.........