本文整理汇总了Python中Population.Population类的典型用法代码示例。如果您正苦于以下问题:Python Population类的具体用法?Python Population怎么用?Python Population使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Population类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
def main():
#Get the sequence to be searched using
FitnessCalculator.set_solution(str(raw_input("SEQUENCE: ")))
#Define the population
pop_size = int(raw_input("Enter population size: "))
elite_option = str(raw_input("Elitism enabled?(y/n): "))
#Elite switch
if elite_option == 'y':
elitism_enabled = True
else:
elitism_enabled = False
#Create a starting popultation
population = Population(pop_size, True)
#Generation count
generation = 0
evolution = Evolution(elitism_enabled)
#Loop until we dont have a solution
while population.get_fittest().get_fitness() < FitnessCalculator.get_max_fitness():
generation += 1
print "GENERATION : " + str(generation) + " FITTEST: " + str(population.get_fittest().get_fitness())
#Evolve the population
population = evolution.evolve(population)
print "SOLUTION FOUND..."
print "GENERATION: " + str(generation)
print "GENES: " + population.get_fittest().get_string()
return
示例2: loadCoords
def loadCoords(self,f=None):
"""loads Coords, creates the corresponding UI elements
and the circles for plotting
"""
default_cluster = self.d.default_cluster
self.reset_sample_list()
if f is None:
f = tkFileDialog.askopenfile(mode='r',initialfile="coords.txt")
print f
else:
f = open( f )
for i,line in enumerate(f):
p = Population()
p.load_line(line)
self.d.add_pop(p)
sUI = SampleUIWPop(pop=p, master=self.sample_frame,
config = self.c, data=self.d,
cluster=default_cluster)
sUI.grid(column=0,row=i, sticky="ew")
#create plotting circles and register events
self.canvas['H'].panel.add_artist( sUI.circH )
self.canvas['Psi'].panel.add_artist( sUI.circP )
sUI.circH.connect()
sUI.circP.connect()
self.add_sample( sUI )
self.nCoords = len( self.d.sList )
self.activeCanvas.redraw()
示例3: main
def main(self):
herd = Population(30)
selection = SelectionStrategies()
recombination = RecombinationStrategies()
reinsertion = ReinsertionStrategies()
herd.main()
generations = 100
# Display the first generation
print "Generation 1"
# for individual in range(1, len(herd.population)):
# print '--> ' .join(herd.population[individual]),
# print ' = ',herd.objective_values[individual], 'km'
x = herd.objective_values
population = herd.population
for count in range(generations):
population,x = selection.sort_by_fitness(population,x)
parent1, parent2 = selection.tournament(population, x)
child1,child2 = recombination.crossover(parent1, parent2)
fitness_of_child1 = herd.get_total_distance(child1, herd.city_names, herd.routes)
fitness_of_child2 = herd.get_total_distance(child2, herd.city_names, herd.routes)
population,x = reinsertion.tournament(child1, child2, population, x, fitness_of_child1, fitness_of_child2)
print "Generation ",count +2
for individual in range(len(herd.population)):
# print '--> ' .join(population[individual]),
# print ' = ',x[individual], 'km'
print ' ',x[individual],
print
示例4: evolve_population
def evolve_population(population_passed):
print("Evolving population...")
new_population = Population(population_passed.size(), False)
# If Elitism is enabled then copy the best scoring individual to the next generation
if Algorithm.Elitism:
new_population.individuals.append(population_passed.get_fittest())
elitism_off_set = 1
else:
elitism_off_set = 0
#Do crossover over the entire population
for i in range(elitism_off_set, population_passed.size()):
individual1 = Algorithm.tournament_selection(population_passed)
individual2 = Algorithm.tournament_selection(population_passed)
new_individual = Algorithm.crossover(individual1, individual2)
new_population.individuals.append(new_individual)
#Do mutation randomly
for i in range(elitism_off_set, population_passed.size()):
Algorithm.mutate(new_population.get_individual(i))
#Repair any individuals broken by crossover or mutation
for individual in new_population.individuals:
individual.genes = fpl.repairteam(individual.genes)
for i in range(population_passed.size()):
new_population.get_individual(i).reset_score()
return new_population
示例5: make
def make(self, population, newPopulationSize):
"""
Process population.
Winner of a single tournament is excluded from next ones.
:param population:
:param newPopulationSize:
:return: list of selected Units
"""
units = population.units[:]
newUnits = []
for i in range(self.elitismFactor):
elite = population.bestUnit(i)
newUnits.append(elite)
#TODO: verify if this works
units.remove(elite)
while len(newUnits) < newPopulationSize and len(units):
tournamentPopulation = Population()
while tournamentPopulation.size < self.tournamentSize and len(units):
unit = random.choice(units)
tournamentPopulation.addUnitAndExpand(unit)
selectedUnit = tournamentPopulation.bestUnit()
units.remove(selectedUnit)
newUnits.append(selectedUnit)
return newUnits
示例6: load_pop
def load_pop(file, wrapped_dict):
if file == '/dev/null':
pop = None
else:
pop = Population()
pop.from_wrapped_dict(wrapped_dict)
return pop
示例7: __init__
def __init__(self, label='Confirmed', **kwargs):
'''Initialize a population of Known planets, from the NASA Exoplanet archive.'''
# set up the population
Population.__init__(self, label=label, **kwargs)
correct(self)
self.saveStandard()
# defing some plotting parameters
self.color = 'black'
self.zorder = -1
示例8: __init__
def __init__(self, label='KOI', **kwargs):
'''Initialize a population of KOI's, from Exoplanet archive.'''
# set up the population
Population.__init__(self, label=label, **kwargs)
correct(self)
self.saveStandard()
# defing some plotting parameters
self.color = 'gray'
self.zorder = -1
示例9: routineTo
def routineTo(sf, cf):
gen = Genetic(sf, cf)
fen = fenetre()
food = Food(fen)
#newFen = newFenTop()
#texts = addScoreOnTopWindows(newFen, int(Params.p['sizePop']))
pop = Population(fen, food)
pop.setInitialPositions()
for i in range(int(Params.p['nbEvol'])):
popName = "pop_" + str(i)
if i > 0:
gen.createNewPopulation(pop)
food = Food(fen)
pop.setFood(food)
pop.setInitialPositions()
#newFen[1].itemconfig(newFen[2], text=popName)
t = time.time()
#while time.time() - t < Params.p['lifeTime']:
j = 0
while j < Params.p['lifeTime']:
#refreshScores(newFen, texts, pop)
pop.routineForPopulation()
fen.refreshScreen()
j += 1
timeGen = time.time() - t
print("Execution time: ", timeGen)
savePop(pop, popName = popName)
fen.fen.destroy()
示例10: tournament_selection
def tournament_selection(self, population):
# Create a new tournament population
tournament_population = Population(self.tournament_size, False)
for i in range(0, self.tournament_size):
# Select a random individual from the pool for breeding qualification
index = random.randint(0, population.get_size() - 1)
tournament_population.save_individual(i, population.get_individual(index))
# Return the fittest individual from the tournament for breeding
return tournament_population.get_fittest()
示例11: routine2
def routine2():
for i in range(int(Params.p['nbEvol'])):
popName = "pop_" + str(i)
fen = fenetre()
food = Food(fen)
pop = Population(fen, food)
t = time.time()
while time.time() - t < Params.p['lifeTime']:
pop.routineForPopulation()
fen.refreshScreen()
fen.fen.destroy()
savePop(pop, popName = popName)
示例12: tournament_selection
def tournament_selection(population_passed):
#Tournament pool
tournament = Population(Algorithm.Tournament_size, False)
""" Tournament selection technique.
How it works: The algorithm choose randomly five
individuals from the population and returns the fittest one """
for i in range(Algorithm.Tournament_size):
random_id = int(random() * population_passed.size())
tournament.individuals.append(population_passed.get_individual(random_id))
fittest = tournament.get_fittest()
return fittest
示例13: routine
def routine():
#create the windows
fen = fenetre()
#create the food
food = Food(fen)
#create the population
pop = Population(fen, food)
t = time.time()
while time.time() - t < Params.p['lifeTime']:
#time.sleep(0.01)
pop.routineForPopulation()
fen.refreshScreen()
fen.fen.destroy()
savePop(pop)
示例14: pos_dict
def pos_dict(gd_indivs_file, input_type):
rv = {}
p = Population()
p.from_population_file(gd_indivs_file)
for tag in p.tag_list():
column, name = tag.split(':')
column = int(column) - 1
if input_type == 'gd_genotype':
column -= 2
rv[name] = column
return rv
示例15: __init__
def __init__(self, simNum):
self.simNum = simNum
self.numTimePeriods = 100
self.logInteractions = True
self.popSize = 100 #Size of the population
self.minFam = 2
self.maxFam = 6
self.igConnectLow = 2
self.igConnectHigh = 5
self.xConnects = round(.2 * self.popSize)
self.intsPerTime = .2 # interactions as a proportion of the population per time period
self.meanPosVal = 5 #Mean value of an interaction
self.meanAvoidVal = 0 #Mean value of avoiding an interaction
self.disRisk = .05 #Probability of being a disease carrier at the start of the simulation)
self.immuneProb = .05 #Probability of being immune to disease at the start of the simulation
self.newDisease = Disease()
self.newPop = Population(self.popSize, self.disRisk, self.immuneProb, self.newDisease, self.xConnects, self.minFam, self.maxFam, self.igConnectLow, self.igConnectHigh)
self.intLog = []
self.totalInts = 0
self.timeLog = []
self.startTime = None
self.endTime = None
self.timePerInt = None
self.runTime = None
self.runVals = None