Exemple #1
0
def natselect(popn, iteration):
    tpopn = list()
    while len(tpopn) < POPULATION_SIZE * 8:
        if random.random() < .5:
            child = indermediary_recomb(parentselect(popn))
            mutate(child, iteration)
            tpopn.append(individual(child, fitness(child)))
        else:
            child = discrete_recomb(parentselect(popn))
            mutate(child, iteration)
            tpopn.append(individual(child, fitness(child)))
    return survivorselect(tpopn)
#### selection.py
from functions import fitness, individual, partmapcrossover, swapmutate, invmutate
import random

globmin = individual([], 10000000000)


# selects best individual in a tournament
# population is a list of individual objects
# size is a int representing the size of the tournament
# selects for either winners or losers
def tournament(population, size, winners):
    global globmin
    s = []
    # generates random members of the tournament
    while len(s) < size:
        s.append(random.randint(0, len(population) - 1))
    sublist = [population[i] for i in s]
    best = sublist[0]
    if winners:
        for sub in sublist:
            if sub.fitness < best.fitness and random.random() < .9: best = sub
        if best.fitness <= globmin.fitness: globmin = best
    else:
        for sub in sublist:
            if sub.fitness > best.fitness and random.random() < .6: best = sub
    return best


def natselect(population, tournsize):
    global globmin
Exemple #3
0
from functions import mutate, indermediary_recomb, discrete_recomb, individual, fitness, initfun
import random

POPULATION_SIZE = 0
globbest = individual([], 10000)


def init(popsize, indlength, xrang, yrang):
    global POPULATION_SIZE
    POPULATION_SIZE = popsize
    return initfun(popsize, indlength, xrang, yrang)


def natselect(popn, iteration):
    tpopn = list()
    while len(tpopn) < POPULATION_SIZE * 8:
        if random.random() < .5:
            child = indermediary_recomb(parentselect(popn))
            mutate(child, iteration)
            tpopn.append(individual(child, fitness(child)))
        else:
            child = discrete_recomb(parentselect(popn))
            mutate(child, iteration)
            tpopn.append(individual(child, fitness(child)))
    return survivorselect(tpopn)


# uniform random selection for parent
def parentselect(popn):
    return [random.choice(popn), random.choice(popn)]