Example #1
0
def test():
    population_size = 10
    my_registers = read_registries()
    initial_population = []

    #establishing a population with non-negative fitness
    for i in range(0, population_size):
        myInd = Individual()
        while myInd.fitness <= 0:
            myInd.randomize(my_registers)
            Genetic.fitness(myInd)

        initial_population.append(myInd)

    #print_all_gen(initial_population)
    #print("----------------")

    print(
        "\n/////////////////////////////////////////////GENERATION: {}".format(
            0))
    new_gen = Genetic.breed(initial_population, my_registers)
    for i in range(1, 50):
        print("\n/////////////////////////////////////////////GENERATION: {}".
              format(i))
        new_gen = Genetic.breed(new_gen, my_registers)
Example #2
0
def main():

    population_size = 10
    my_registers = read_registries()
    initial_population = []

    #establishing a population with non-negative fitness
    for i in range(0, population_size):
        myInd = Individual()
        while myInd.fitness <= 0:
            myInd.randomize(my_registers)
            Genetic.fitness(myInd)

        initial_population.append(myInd)

    new_gen = Genetic.breed(initial_population, my_registers)

    #evaluating till we get top == 100
    top_fitness = 0
    try:
        while top_fitness < 100:

            if top_fitness != 0:
                new_gen = Genetic.breed(new_gen, my_registers)

            for item in new_gen:
                if item.fitness > top_fitness:
                    top_fitness = item.fitness
                    #print("{} broke to: {}".format(item, top_fitness))

        print_all_gen(new_gen)
    except KeyboardInterrupt:
        print_all_gen(new_gen)
class TestIndividual(TestCase):
    p = random.randint(2, 10)
    G = get_graph('../data/SJC1.dat')
    i1 = Individual(p, G)
    i2 = Individual(p, G)

    def testMutation(self):
        i3 = mutate(self.i1, self.G)
        intersection = self.i1.chromosome.intersection(i3.chromosome)
        self.assertEqual(len(i3.chromosome), self.p)
        self.assertEqual(len(intersection), self.p - 1)
        self.assertNotEqual(self.i1, i3)

    def testCrossover(self):
        (i3, i4) = crossover(self.i1, self.i2)
        union1 = self.i1.chromosome.union(self.i2.chromosome)
        union2 = i3.chromosome.union(i4.chromosome)
        self.assertEqual(union1, union2)
        self.assertEqual(len(i3.chromosome), self.p)
        self.assertEqual(len(i4.chromosome), self.p)

    def testCrossoverSameIndividuals(self):
        (i3, i4) = crossover(self.i1, self.i1)
        self.assertEqual(i3, self.i1)
        self.assertEqual(i4, None)

    def testCrossoverDiffIndividuals(self):
        (i3, i4) = crossover(self.i1, self.i2, c=3)
        self.assertNotEqual(i3, i4)
        union1 = self.i1.chromosome.union(self.i2.chromosome)
        union2 = i3.chromosome.union(i4.chromosome)
        self.assertEqual(union1, union2)
        self.assertEqual(len(i3.chromosome), self.p)
        self.assertEqual(len(i4.chromosome), self.p)
Example #4
0
    def __ramped_half_and_half(self, population_size, max_depth, funcs, terms):
        """Creates a population with Ramped half-and-half initialization

        Arguments:
            population_size {int} -- Size of the population.
            max_depth {int} -- Max depth of a tree contained in an individual
            funcs {[object]} -- List of functions to be used in individual
                                creation
            terms {[string]} -- List of terminals to be used in individual
                                creation

        Returns:
            [Individual] -- List of individual, i.e., the population.
        """
        pop = []
        group = (population_size / (max_depth - 1))
        full = True

        for i in range(2, max_depth + 1):
            for j in range(int(group)):
                pop.append(
                    Individual(self.__gen_rnd_expr(funcs, terms, i, full)))
                full = not full

        for i in range(population_size % (max_depth - 1)):
            pop.append(
                Individual(self.__gen_rnd_expr(funcs, terms, max_depth, full)))

        return pop
    def mate(a: Individual, b: Individual):
        if random.random() < .9:
            min_len = (min(len(a.dna), len(b.dna)))
            cross_point = random.randrange(1, min_len)

            acopy = []
            bcopy = []

            for x in a.dna:
                acopy.append(x)

            for x in b.dna:
                bcopy.append(x)

            new_a_dna = acopy[:cross_point] + bcopy[cross_point:]
            new_b_dna = bcopy[:cross_point] + acopy[cross_point:]

            for x in range(0, min_len):
                if random.random() < .5:
                    new_a_dna[x] = new_a_dna[x][0], int(
                        round((new_a_dna[x][1] + new_a_dna[x][1] +
                               new_b_dna[x][1]) / 3))

            return Individual(new_a_dna), Individual(new_b_dna)
        else:
            return a, b
Example #6
0
    def orderOneCrossover(self, amountOfCrossovers, regionLength):
        previousPairs = []
        for i in range(0, amountOfCrossovers):
            space1 = randint(0, len(self.individuals) - 1)
            space2 = randint(0, len(self.individuals) - 1)
            while (str(space1) + str(space2) in previousPairs
                   or space1 == space2):
                space1 = randint(0, len(self.individuals) - 1)
                space2 = randint(0, len(self.individuals) - 1)
            previousPairs.append(str(space1) + str(space2))

            P1 = self.individuals[space1]
            P2 = self.individuals[space2]

            childRep = ''
            loc = randint(0, len(P1.representation) - 1)
            region = P1.representation[loc:loc + regionLength]

            right = ''
            left = ''

            for c in P2.representation[loc + regionLength:]:
                if (c not in region):
                    right = right + c
            for c in P2.representation[:loc + regionLength]:
                if (c not in region):
                    left = left + c

            childRep = left + region + right
            mInd = Individual()
            mInd.setRepresentation(childRep)
            self.individuals.append(mInd)
Example #7
0
    def crossover(self):
        new_generation = [self.fittest()]
        for index in range(len(self.individuals) - 1):
            rnd = random.random()
            if rnd <= Population.cp:
                child = crossovers.aox(self.individuals[index].chromosome,
                                       self.individuals[index + 1].chromosome)
                new_generation.append(Individual(child))
            else:
                if rnd <= 0.5:
                    new_generation.append(self.individuals[index])
                else:
                    new_generation.append(self.individuals[index + 1])
        rnd = random.random()

        # crossover du dernier et premier
        if rnd <= Population.cp:
            child = crossovers.aox(self.individuals[-1].chromosome,
                                   self.individuals[0].chromosome)
            new_generation.append(Individual(child))
        else:
            if rnd <= 0.5:
                new_generation.append(self.individuals[-1])
            else:
                new_generation.append(self.individuals[0])

        self.individuals = new_generation
Example #8
0
    def f(parents):
        # Don't modify parents
        individuals = [parent.copy() for parent in parents]
        np.random.shuffle(individuals)
        intermediate_pool = []

        while len(intermediate_pool) < len(individuals):
            i = len(intermediate_pool)
            if np.random.uniform() < p_m:
                p = mutate_program(individuals[i].program.copy())
                intermediate_pool.append(
                    Individual(program=p.copy(), max_depth=p.max_depth))
            else:
                # Wrap around if at end
                a_index = i
                b_index = i + 1 if i != len(individuals) - 1 else 0

                p_a, p_b = crossover_program(
                    individuals[a_index].program.copy(),
                    individuals[b_index].program.copy())

                intermediate_pool.append(
                    Individual(program=p_a.copy(), max_depth=p_a.max_depth))
                intermediate_pool.append(
                    Individual(program=p_b.copy(), max_depth=p_b.max_depth))
        return intermediate_pool
Example #9
0
def oneChildCrossover(p1, p2, crossfuncs, crossparams):
    """
		Crossover all the chromosomes in the two individuals.
		The crossover function for each pair of  corresponding chromosomes is the the corresponding element in crossfuncs, 
		called with the corresponding tuple in crossparams.
		
		Note that it is assumed that each crossover function in crossfuncs returns one child chromosome
		
		pre:
			isinstance(p1, Individual)
			isinstance(p2, Individual)
			len(p1) == len(p2)
			len(p1) == len(crossfuncs)
			len(crossfuncs) == len(crossparams)
		
		post:
			__old__.p1 is p1
			__old__.p2 is p2
			__old__.p1 == p1
			__old__.p2 == p2
			
			len(__return__) == 1
			isinstance(__return__, Individual)
			len(__return__)==len(p1)
			all(len(c)==len(p1[i]) for i,c in enumerate(__return__.chromosomes))
			all(len(c)==len(p1[i]) for i,c in enumerate(__return__.chromosomes))
	"""
    answer = Individual([])
    for i, (crossfunc, crossparams) in enumerate(zip(crossfuncs, crossparams)):
        answer.append(crossfunc(p1[i], p2[i], *crossparams))

    return answer
Example #10
0
    def init_pop(self):
        self.individuals = []

        for _ in range(0, self.nindiv):
            individual = Individual(self.size_indiv, self.mutation_rate)
            individual.init_chromosome()
            self.individuals.append(individual)
Example #11
0
def genPop(N, chromGenfuncs, chromGenParams):
    """ Return a population (list) of N unique individuals.
        Each individual has len(chromgGenFuncs) chromosomes.
        For each individual, chromosome_i is generated by calling chromGenFuncs_i(chromeGenParams_i)

        pre:
            N >= 0
            isinstance(chromGenfuncs, list)
            isinstance(chromGenParams, list)
            len(chromGenfuncs) == len(chromGenParams)

        post:
            isinstance(__return__, list)
            len(__return__) == N
            forall(__return__, lambda indiv: __return__.count(indiv) == 1)

        post[chromGenfuncs, chromGenParams]:
            __old__.chromGenfuncs == chromGenfuncs
            __old__.chromGenParams == chromGenParams
    """

    answer = set()
    chromGens = zip(chromGenfuncs, chromGenParams)
    while len(answer) < N:
        indiv = Individual([])
        for genfunc, genparams in chromGens:
            indiv.append(genfunc(*genparams))
        answer.add(indiv)
    return list(answer)
 def crossover(population):
     #assumes individuals are shuffled
     new_pop = []
     for i in range(0, population.size >> 1):
         individual1 = population.individuals[i]
         individual2 = population.individuals[population.size - i - 1]
         if (random.uniform() < population.parameters['p.crossover']):
             type = population.parameters['crossover.type'] \
             if (population.parameters['crossover.type'] \
             != 'permutation.all.operators') else \
             np.random.choice(GeneticOperators.keys)
             children = GeneticOperators.permutation_crossover_individuals(\
             individual1,individual2,type) \
             if(population.parameters['type']=='permutation') else \
             GeneticOperators.crossover_individuals(\
             individual1,individual2)
         else:
             children = [\
             Individual(individual1.genotype,\
             np.array(individual1.phenotype)),\
             Individual(individual2.genotype,\
             np.array(individual2.phenotype))]
         new_pop = new_pop + children
     return \
     Population(population.environment, population.parameters,new_pop)
class TestIndividual(TestCase):
    def setUp(self) -> None:
        self.items = []
        for i in range(5):
            item = Item(random.randint(1, 10), random.randint(0, 75))
            self.items.append(item)
        weight = 0
        for i in range(5):
            weight += self.items[i].weight
        print(weight)
        max_weight = round(weight / 2)
        self.ind = Individual(self.items, max_weight)

    def test_generate_genotype(self):
        self.ind.generate_genotype()
        self.assertEqual(len(self.ind.genotype), len(self.items))

    def test_correct_genotype(self):
        self.ind.generate_genotype()
        self.ind.correct_genotype()
        self.assertLessEqual(self.ind.weight_used, self.ind.max_weight)

    def test_breeding(self):
        ind2 = Individual(self.items, self.ind.max_weight)
        ind3 = ind2
        self.ind.generate_genotype()
        ind2.generate_genotype()
        self.ind.correct_genotype()
        ind2.correct_genotype()
        ind3.breeding(self.ind, ind2)
        self.assertLessEqual(ind3.weight_used, ind3.max_weight)
Example #14
0
 def __init__(self, probability_handler, max_individual_size = 10):
     self.probability_handler = probability_handler
     self.max_individual_size = max_individual_size
     self.population = []
     self.values_handler = Values_Handler(probability_handler)
     self.individual = Individual(self.probability_handler.max_feature_number, self.max_individual_size, self.values_handler)
     self.mh = Mutation_Handler(self.probability_handler, self.values_handler)
	def __init__(self, populationSize):
		self.individuals = []

		for i in range(populationSize):
			i = Individual()
			i.generateIndividual()
			self.individuals.append(i)
Example #16
0
 def __init__(self, num_pops):
     self.num_pops = num_pops
     self.pops = []
     for i in range(num_pops):
         indi = Individual()
         indi.initialize()
         self.pops.append(indi)
Example #17
0
    def onePoint(self, parents, n, gene_size, crate):
        """
        One point crossover

        [imagine]
        parent1: [0, 1, 1]
                            => crossover => child: [1(p1), 0(p2), 0(p2)]
        parent2: [1, 1, 0] 
        
        [example]
        Crossover.Onepoint(list.parents, 5) => [crossover the parents for individuals size]

        :param list[Individual] parents: Selected parents
        :param int n: Size of individuals
        :param int gene_size: Size of gene
        :param int crate:     Probability of crossover
        :returns: Children
        :rtype:   list[Individual]
        """
        children = []
        idx = [i for i in range(gene_size)]
        for i in range(n):
            child = Individual()
            parent1, parent2 = npr.choice(parents, 2, replace=False)
            gene1 = copy.copy(parent1.getGene())
            gene2 = parent2.getGene()
            point = npr.choice(idx, 1)[0]
            if (crate > npr.random()):
                gene1[point:] = gene2[point:]
            child.setGene(gene1)
            children.append(child)
        return (children)
	def execute(self):
		Individual.nMachines = self.nMachines
		Individual.nTasks = self.nTasks
		Individual.tasks = file_manager.load_tasks(self.filename, self.nTasks, self.nMachines)
		Individual.crossoverMask = Individual.generate_crossover_mask(self.nTasks)

		makespanPopulation = Population.generate(self.populationSize, Individual.tasks)

		for i in range(self.maxIterations):
			currentMakespan = makespanPopulation.makespan_sum()
			# SELECTION
			parents = makespanPopulation.select_parents(self.crossoverFactor)

			# CROSSOVER
			childs = []
			childs = Individual.crossover_two_point(parents, i+1, currentMakespan)
			
			# MUTATION
			for child in childs:
				child.apply_mutation_simple(self.mutationFactor, currentMakespan)
				makespanPopulation.insert_individual(child)

			# INSERTION
			newPopulationIndividuals = makespanPopulation.update_population(self.elitismFactor)

			# LOGGING
			if(i % 100 == 0):
				self.save_log_information(i, makespanPopulation)

		return makespanPopulation.best_individual(), self.logs_generations, self.logs_average, self.logs_makespan, self.logs_flowtime
Example #19
0
    def randomPoints(self, parents, n, gene_size, crate):
        """
        Random points crossover

        [imagine]
        parent1: [0, 1, 1, 1]
                               => crossover => child: [1(p2), 1(p1), 1(p1), 1(p2)]
        parent2: [1, 1, 0, 1]

        [example]
        Crossover.Twopoints(list.parents) => [crossover the parents for individuals size]

        :param list[Individual] parents: Selected parents
        :param int n: Size of individuals
        :param int gene_size: Size of gene
        :param int crate:     Probability of crossover
        :returns: Children
        :rtype:   list[Individual]
        """
        children = []
        idx = [i for i in range(gene_size)]
        n_random = npr.randint(1, gene_size + 1)
        for i in range(n):
            child = Individual()
            parent1, parent2 = npr.choice(parents, 2, replace=False)
            gene1 = copy.copy(parent1.getGene())
            gene2 = parent2.getGene()
            points = npr.choice(idx, n_random, replace=False)

            if (crate > npr.random()):
                for j in points:
                    gene1[j] = gene2[j]
            child.setGene(gene1)
            children.append(child)
        return (children)
Example #20
0
def mutation(childs, pmut, fit, center, limit, mutation_f):
    mutation_list = list(filter(lambda individual: np.random.rand() < pmut, childs[:int(len(childs) * pmut)]))
    for i, individual in enumerate(mutation_list):
        mutated = mutation_f(Individual.getQ(individual[0]), limit)
        sol = newton.newton(mutated, a_par, b_par, c_par)
        mutation_list[i] = (Individual(mutated, sol), fit(center, sol))
    return mutation_list
Example #21
0
 def createPopulation(self, functions, constants, n_ind, n_gene,
                      n_register):
     self.p = []
     for i in range(n_ind):
         ind = Individual(functions, constants, n_register)
         ind.createGene(random.randint(1, n_gene))
         self.p.append(ind)
    def ox_crossover(individual1,individual2):
        n,i,f,i_central,i_sides= PermutationCrossover.mapping_sections(\
        individual1,individual2)
        
        p1_central = set(individual1.phenotype[i_central])
        p2_central = set(individual2.phenotype[i_central])
        centrals = p1_central.union(p2_central)
        
        rest_1 = list(filter(lambda x:x[1] not in centrals, \
        enumerate(individual1.phenotype)))
        rest_2 = list(filter(lambda x:x[1] not in centrals, \
        enumerate(individual2.phenotype)))
        
        rest_1 = np.array([x[1] for x in \
        list(filter(lambda x:x[0]>=f,rest_1))+\
        (list(filter(lambda x:x[0]<i,rest_1)))])

        rest_2 = np.array([x[1] for x in \
        list(filter(lambda x:x[0]>=f,rest_2))+\
        (list(filter(lambda x:x[0]<i,rest_2)))])
        
        head_1 = np.array(list(filter(lambda x:x not in p2_central,\
        individual1.phenotype[i_central])))
        
        head_2 = np.array(list(filter(lambda x:x not in p1_central,\
        individual2.phenotype[i_central])))
        
        child1 = PermutationCrossover.build_child(\
        head_1,individual2.phenotype[i_central],rest_1)
        
        child2= PermutationCrossover.build_child(\
        head_2,individual1.phenotype[i_central],rest_2)
         
        return [Individual(phenotype=child1),Individual(phenotype=child2)]
Example #23
0
    def simulated_annealing(self):
        currentResult = self.initialize()
        currentValue = Individual(self.graph, currentResult)
        bestValue = Individual(self.graph, currentResult)

        for i in range(1, self.nIterations):
            j = self.invert(currentResult)
            newValue = Individual(self.graph, currentResult)
            if newValue.fitness < currentValue.fitness:
                currentValue = Individual(self.graph, newValue.code)
            else:
                p = 1.0 / i**0.5
                q = random.uniform(0, 1)
                if p > q:
                    currentValue = Individual(self.graph, newValue.code)
                else:
                    self.restore(j, currentResult)

            if newValue.fitness < bestValue.fitness:
                bestValue = Individual(self.graph, newValue.code)

            if bestValue.fitness == 0:
                break
        bestValue.getSubgraphs()
        return bestValue
Example #24
0
    def update_velocity(self, neighbour):
        """
            Updates the particle's velocity and moves it by one iteration
            self.velocity = (w_inertia * v) + (w_mem * (histpos - pos) + (wg * (neihg - pos)))
            self.pos = self.pos + self.vel
            returns amount of change in velocity
        """
        self.p['Neighbour'] = neighbour.p['Coordinate']

        # Switch to update velocity
        def updatev(row):
            if ((row['Neighbour'] - row['Coordinate']) == 0):
                ret = (
                    (self.w_inertia * row['Velocity']) +
                    (self.w_memory * (row['HBest'] - row['Coordinate'])) +
                    self.__generateCoord({
                        'min': 0.00001,
                        'max': 0.0001
                    })
                )  # Add a pinch of randomness to make sure that velocities are different
            elif (row['HBest'] - row['Coordinate']) == 0:
                ret = ((self.w_inertia * row['Velocity']) + (self.w_memory) +
                       (self.w_neigh * (row['Neighbour'] - row['Coordinate'])))
            elif row['Velocity'] == 0:
                ret = ((self.w_inertia) +
                       (self.w_memory * (row['HBest'] - row['Coordinate'])) +
                       (self.w_neigh * (row['Neighbour'] - row['Coordinate'])))
            else:
                ret = ((self.w_inertia * row['Velocity']) +
                       (self.w_memory * (row['HBest'] - row['Coordinate'])) +
                       (self.w_neigh * (row['Neighbour'] - row['Coordinate'])))
            return ret

        def move(row):
            return row['Coordinate'] + row['Velocity']

        previous_vel = self.p['Velocity']
        self.p['Velocity'] = self.p.apply(updatev, axis=1)
        self.__clampV()
        self.p['Coordinate'] = self.p.apply(move, axis=1)
        self.__clampPos()

        # Update fitness
        self.current_fit = self.ff.fitness(
            Individual.factory("Coordinate", self.n_thresholds, self.p))

        # Reset particle while its fitness is not valid
        while (self.current_fit.value == 0):
            self.__reset()

        # Replace your historical best if you've defeated it
        hfit = self.ff.fitness(
            Individual.factory("HBest", self.n_thresholds, self.p))
        if (hfit.value < self.current_fit.value):
            hfit = self.current_fit
            self.p['HBest'] = self.p['Coordinate']
        self.iteration += 1

        diff_in_v = self.p['Velocity'] - previous_vel
        return diff_in_v
Example #25
0
    def reproduction(self):

        self.generationCount += 1
        # do for every individual in a population
        for i in range(self.capacity):

            # crossover event
            parent1, parent2 = self.selection()
            child = parent1

            # evenly split "DNA" between two parents
            for j in range(floor(self.length / 2) - 1):
                child[j * 2] = parent2[j * 2]

            # mutation event
            final = Individual(self.mutation(child, self.mutRate), self.length,
                               self.phrase)

            # replace currently highest fitness individual
            if final.getFitness() > self.currentHigh:
                self.bestMatch = final.getName()

            # insert individual into new population
            self.nextPop.append(final)
        self.pop = self.nextPop  # set next gen population to current population
        self.currentHigh = max(self.nextPop)
        return "Generation count: " + str(self.generationCount)
    def crossover_population(self, population):
        new_population = Population(population.size, population.dataset,
                                    population.chromosome_size)

        cut_index = int(random() * population.chromosome_size)

        for i in range(population.size):
            parent1 = population.get_fittest(i)
            parent2 = Individual(population.chromosome_size,
                                 population.dataset)

            offspring = parent1

            if i > self.elitism_count and self.crossover_rate > random(
            ) and i >= cut_index:
                for j in range(parent2.chromosome_size):
                    adiconado = False
                    while not adiconado:
                        if not self.isContained(parent2.chromosome[j],
                                                offspring):
                            offspring.chromosome[j] = parent2.chromosome[j]
                            adiconado = True
                        else:
                            parent2 = Individual(population.chromosome_size,
                                                 population.dataset)

            new_population.individuals[i] = offspring

        return new_population
Example #27
0
def make_next_generation(population, pizza):
    mating_pool = population[:int(c_par * P)]

    next_generation = []
    for _ in range(int(c_rec * P) // 2):
        A, B = random.sample(mating_pool, 2)
        C, D = A.recombine(B, pizza)
        next_generation += [C, D]

    next_generation += mating_pool

    for _ in range(int(c_mut * P)):
        # A = random.choice(next_generation)
        A = mating_pool[0]
        B = A.copy()
        levels = random.choice([1, 2, 3])
        B.mutate(pizza, levels)
        next_generation.append(B)

    for _ in range(int(c_ran * P)):
        A = Individual({}, slices, n_col, n_row, L, H)
        A.fill_layout(pizza)
        next_generation.append(A)

    next_generation.sort(key=lambda x: x.efficiency(), reverse=True)
    return next_generation
    def __init__(self,
                 initial_pop,
                 layer_types,
                 layer_shapes,
                 conv_layer_types=None,
                 population=None):
        self.pop_size = initial_pop
        self.layer_types = layer_types
        self.layer_shapes = layer_shapes
        self.conv_layer_types = conv_layer_types

        if population is not None:
            self.population = population

            # If not enough members, create random ones
            if initial_pop < len(population):
                while initial_pop < len(population):
                    self.population.append(
                        Individual(layer_types, layer_shapes,
                                   conv_layer_types))
            else:
                self.pop_size = len(population)

            self.fitness = zip(np.zeros(self.pop_size), range(self.pop_size))
        else:
            self.fitness = zip(np.zeros(initial_pop), range(initial_pop))

            self.population = []
            for i in range(initial_pop):
                self.population.append(
                    Individual(layer_types, layer_shapes, conv_layer_types))
Example #29
0
def recombination(parent1, parent2):
    child1 = Individual(chromosome=np.append(parent1[:crossPoint],
                                             parent2[crossPoint:]), )
    child2 = Individual(chromosome=np.append(parent2[:crossPoint],
                                             parent1[crossPoint:]), )

    return [child1, child2]
    def gen_n_individuals(n, samples):
        individuals = list()

        while len(individuals) < n:
            # avoid full empty weights
            candidate = None
            while True:
                lw = np.random.choice([0, 1], 1)

                pw_len = random.randint(1, 10)
                pw = np.array(
                    [Population.is_set(x + 1, pw_len) for x in range(10)])

                prw_len = random.randint(1, 10)
                prw = np.array(
                    [Population.is_set(x + 1, prw_len) for x in range(10)])

                params = SVRParams()

                candidate = Individual(samples=samples,
                                       linear_weight=lw,
                                       prev_weights=pw,
                                       prev_residual_weights=prw,
                                       params=params)
                if candidate.hash() > 0:
                    break

            individuals.append(candidate)

        return individuals
 def __init__(self, size, initialize=False):
     self.individuals = []
     
     if initialize:
         for i in range(0, size):
             individual = Individual()
             individual.generate_individual()
             self.individuals.append(individual)
 def test_fight(self):
     ind1 = Individual("01101110")
     ind2 = Individual("00111000")
     fight1 = ind2.fight(ind1)
     self.assertEqual(ind1.fitness, 1)
     self.assertEqual(ind2.fitness, 0)
     fight2 = ind1.fight(ind2)
     self.assertEqual(fight1, False)
     self.assertEqual(fight2, False)
 def crossover_pt(self, individual_1, individual_2):
     crossover_individual = Individual()
     
     uniform_rate = uniform(3, 7) * .1
     crossover_point =  int(uniform_rate * len(crossover_individual.genes))
     
     crossover_individual.genes = individual_1.genes[0:crossover_point]
     crossover_individual.genes += individual_2.genes[crossover_point:]
     
     return crossover_individual
class TestEvaluateAgainst:
    def setup(self):
        self.individual_a = Individual('0123456789')

    def test_identical(self):
        chars = self.individual_a.chars
        assert_true(self.individual_a.evaluate_against(chars) == len(chars))

    def test_no_similarity(self):
        assert_true(self.individual_a.evaluate_against('a tallship') == 0)
 def crossover_random(self, individual_1, individual_2):
     crossover_individual = Individual()
     
     for i in range(0, len(crossover_individual.genes)):
         # crossover
         if random() <= self.uniform_rate:
             crossover_individual.genes[i] = individual_1.genes[i]
         else:
             crossover_individual.genes[i] = individual_2.genes[i]
     
     return crossover_individual
Example #36
0
 def run_once(self):
     newpop = []
     # Elitism, keep the best chromosome to the next generation
     newpop = self.population[:3]
     for i in range(3, self.popsize):
         tmpchrom = Individual(mother=self.__my_choice(), father=self.__my_choice())
         tmpchrom.mutate()
         newpop.append(tmpchrom)
     self.population = newpop
     self.evaluate_all()
     self.randomize_duplicates()
     self.apply_max()
     self.evaluate_all()
     self.population.sort(key=attrgetter("fitness"), reverse=True)
     self.inc_mutation_rate(MUTATION_RATE_INC)
Example #37
0
    def init_children_test(self, num_children):

        self.clear_test_state()
        player1 = Individual()
        testee = player1.get_robot()
        testee.location = constants.testee_loc
        self.robots = [testee]
        self.gamestate.add_robot(testee.location, testee.player_id)
        
        # Force the prime rule to be the move rule so direction is returned
        while testee.eval_order[0].action != 'move':
            random.shuffle(testee.eval_order)
        
        rule = self.robots[0].eval_order[0]
        rule.insert_random_parent()
        for x in range(num_children):
            self.insert_random_root_child(rule)
Example #38
0
 def setUp(self):
     self.indi = Individual()
     self.indi.addID('@I2@')
     self.indi.addName('John Rivas')
     self.indi.addSex('M')
     self.indi.addBirt('9 MAY 1978')
     self.indi.addDeat('12 APR 2013')
     self.indi.addFams('@F2@')
     self.indi.addFamc('@F1@')
 def __init__(self, size):
     self.size = size
     self.pop = []
     self.selected = []
     self.selected_indexes = []
     self.fitness_table = []
     Individual.mutation_factor = 5
     for i in xrange(size):
         self.pop.append(Individual.random_ind())
Example #40
0
def make_json_record(case_name=CASE_NAME, seed=0, lineage=0, age=0):
    input_filepath = os.path.join(RESULT_DIR, case_name)
    output_file = os.path.join(
        ensure_exists(os.path.join(ANALYSIS_DIR, case_name, "seed-{}".format(seed))), "game.json"
    )

    params = load("params", input_filepath, seed)

    TASKS = [(task[0], int(task[1][::-1], 2)) for task in params["TASKS"]]
    hit_multipliers, patterns = zip(*TASKS)

    lineages = load("lineages", input_filepath, seed)

    def i2s(i):
        return tuple((i >> n) & 1 for n in range(params["NUM_NODES"]))

    ind = Individual(lineages[lineage][age].genome)
    transitions = ind.play_game(hit_multipliers, patterns)
    states = [
        ps[: params["NUM_SENSORS"]] + cs[params["NUM_SENSORS"] :]
        for ps, cs in zip(map(i2s, transitions[0]), map(i2s, transitions[1]))
    ]

    trial_length = params["WORLD_HEIGHT"]

    block_sizes = []
    for pattern in patterns:
        block_sizes += [sum(i2s(pattern))] * int(params["NUM_TRIALS"] / len(patterns))

    json_dict = {
        "generation": params["NGEN"] - age,
        "connectivityMatrix": ind.cm.T.tolist(),
        "nodeTypes": {"sensors": [0, 1], "hidden": [2, 3, 4, 5], "motors": [6, 7]},
        "blockSize": block_sizes,
        "Trial": [
            {"trialNum": i, "lifeTable": states[(i * trial_length) : ((i + 1) * trial_length)]}
            for i in range(params["NUM_TRIALS"])
        ],
    }
    with open(output_file, "w") as f:
        json.dump(json_dict, f)
    print("Saved game representation to `{}`.".format(output_file))

    return json_dict
Example #41
0
 def __init__(
     self, data, expected_result, popsize=50, mut_rate=20, GA_printers=None
 ):
     Individual.expected_result = {"rowdata": expected_result}
     Individual.mutation_rate = mut_rate
     Individual.data = data
     self.popsize = popsize
     self.population = []
     for i in range(0, popsize):
         c = Individual()
         c.randomize()
         self.population.append(c)
     self.population.sort(key=attrgetter("fitness"), reverse=True)
     self.GA_printers = GA_printers
     self.generation = 0
     self.wheel_size = sum(range(1, popsize + 1))
     self.wheel = []
     self.__init_wheel()
     self.test = [0 for i in range(0, self.popsize)]
Example #42
0
 def test_addSex(self):
     indi = Individual()
     value = "M"
     indi.addSex(value)
     self.assertEqual(indi.getSex(), value)  
     
     value = "F"
     indi.addSex(value)
     self.assertEqual(indi.getSex(), value)      
Example #43
0
def mutate(indiv: individual.Individual):
    # for i in range(individual.Individual.gene_length):
        # if elitism and i == 0:
            # continue
        # if random.random() <= mutation_rate:
            # indiv.genes[i // 8] ^= 1 << (i % 8)
    for i, _ in enumerate(indiv.genes):
        # if elitism and i == 0:
            # continue
        if random.random() <= mutation_rate:
            indiv.genes[i] = random.randint(0, 255)
Example #44
0
    def init_node_type_test(self):
        """Puts Test in known state for Node type tests."""

        self.clear_test_state()
        player1 = Individual()
        player2 = Individual()
        testee = player1.get_robot()
        testee.location = constants.testee_loc
        ally = player1.get_robot()
        ally.location = constants.ally_loc
        enemy = player2.get_robot()
        enemy.location = constants.enemy_loc
        enemy.player_id = 1
        self.robots = [testee, ally, enemy]
        for bot in self.robots:
            self.gamestate.add_robot(bot.location, bot.player_id)
            
        # I use the default 'guard' action to determine when a rule evaluates 
        #     False, so the test rule must not be the guard rule
        while testee.eval_order[0].action == 'guard':
            random.shuffle(testee.eval_order)
        testee.eval_order[0].insert_random_parent()
Example #45
0
    def setUp(self):
        self.indi = Individual()
        self.indi.addID('@I2@')
        self.indi.addName('John Rivas')
        self.indi.addSex('M')
        self.indi.addBirt('9 MAY 1978')
        self.indi.addDeat('12 APR 2013')
        self.indi.addFams('@F2@')
        self.indi.addFamc('@F1@')
        
        self.fam1 = Family()
        self.fam1.addFamID('@F2@')
        self.fam1.addHusb('@I2@')
        self.fam1.addWife('@I2@')
        self.fam1.addChil('@I2@')
        self.fam1.addChil('@I2@')

        self.individuals =  dict()
        self.individuals["one"] = self.indi
                
        self.families =  dict()
        self.families["one"] = self.fam1
Example #46
0
class OutputTest(unittest.TestCase):

    def setUp(self):
        self.indi = Individual()
        self.indi.addID('@I2@')
        self.indi.addName('John Rivas')
        self.indi.addSex('M')
        self.indi.addBirt('9 MAY 1978')
        self.indi.addDeat('12 APR 2013')
        self.indi.addFams('@F2@')
        self.indi.addFamc('@F1@')
        
        self.fam1 = Family()
        self.fam1.addFamID('@F2@')
        self.fam1.addHusb('@I2@')
        self.fam1.addWife('@I2@')
        self.fam1.addChil('@I2@')
        self.fam1.addChil('@I2@')

        self.individuals =  dict()
        self.individuals["one"] = self.indi
                
        self.families =  dict()
        self.families["one"] = self.fam1
        
    def test_outputIndiSummary(self):
        outputIndiSummary(self.individuals)

    def test_outputFamSummary(self):
        outputFamSummary(self.families, self.individuals)
Example #47
0
from individual import Individual
from mutator import Mutator

num_tries = 0
num_moves = 0

TARGET = "Methinks it is like a weasel"
mutator = Mutator(2)
ind = Individual(len(TARGET))
fitness = ind.evaluate_against(TARGET)
while fitness < len(TARGET):
	new_ind = mutator.reproduce_asexually(ind)
	new_fitness = new_ind.evaluate_against(TARGET)
	num_tries = num_tries + 1
	if new_fitness > fitness:
		ind = new_ind
		fitness = new_fitness
		num_moves = num_moves + 1
		print(new_ind)

print("Found in",num_tries,"tries and",num_moves,"moves.")
Example #48
0
def build_lists_from_file(filename):
    """Parses the Ged file and builds the Family and Individual objects.
    Returns a touple of dictionaries, in the for ({},{}), where the first is
    the list of families (indexed by family ID) and the second is the list of
    individuals (indexed by the individual ID).
    """
    load_valid_tags()
    lines = open(filename, "r").readlines()
    individuals = {}
    families = {}

    def generateUntilLevelZero(seq):
        """Creates a list of GedLine objects until the given sequence has a 
        GedLine with level zero. This is useful for retrieving a sequence of 
        lines of a single object (family of individual)
        """
        for e in seq:
            line = GedLine(e)
            if line.level() != 0:
                yield line
            else:
                break

    index = 0  # line index
    while index < len(lines)-1:
        line = GedLine(lines[index])

        if line.level() == 0 and line.content() == "INDI":
            # Create Individual
            ind = Individual(line.tag())  # Tag is the ID
            individual_lines = generateUntilLevelZero(lines[index+1:])
            for l in individual_lines:
                if l.tag() == "NAME":
                    ind.name = l.content()
                elif l.tag() == "GIVN":
                    ind.givenname = l.content()
                elif l.tag() == "SURN":
                    ind.surname = l.content()
                elif l.tag() == "SEX":
                    ind.sex = l.content()
                elif l.tag() == "NOTE":
                    ind.note = l.content()
                elif l.tag() == "BIRT":
                    ind.setbirthday(individual_lines.next().content())
                elif l.tag() == "DEAT":
                    ind.setdeathday(individual_lines.next().content())
            individuals[ind.id] = ind

        elif line.level() == 0 and line.content() == "FAM":
            # Create Family
            fam = Family(line.tag())  # Tag is the ID
            family_lines = generateUntilLevelZero(lines[index+1:])

            for l in family_lines:
                if l.tag() == "HUSB":
                    fam.husband = l.content()
                elif l.tag() == "WIFE":
                    fam.wife = l.content()
                elif l.tag() == "CHIL":
                    fam.children.append(l.content())
                elif l.tag() == "MARR":
                    fam.setmarrydate(family_lines.next().content())
            families[fam.id] = fam

        index += 1

    return families, individuals
Example #49
0
 def test_getName(self):
     NAME = 'John Rivas'
     self.assertEqual(self.indi.getName(), NAME)
     
     indi = Individual()
     self.assertEqual(indi.getName(), None)
Example #50
0
 def test_getBirt(self):
     BIRT = '9 MAY 1978'
     self.assertEqual(self.indi.getBirt(), BIRT)
     
     indi = Individual()
     self.assertEqual(indi.getBirt(), None)
Example #51
0
 def test_getSex(self):
     SEX = 'M'
     self.assertEqual(self.indi.getSex(), SEX)
     
     indi = Individual()
     self.assertEqual(indi.getSex(), None)
Example #52
0
class GedcomTest(unittest.TestCase):
    def setUp(self):
        self.indi1 = Individual()
        self.indi1.addID('@I1@')
        self.indi1.addName('John Rivas')
        self.indi1.addSex('M')
        self.indi1.addBirt('9 MAY 1978')
        self.indi1.addDeat('12 APR 2013')
        self.indi2 = Individual()
        self.indi2.addID('@I2@')
        self.indi2.addName('Mary Rivas')
        self.indi2.addSex('F')
        self.indi2.addBirt('21 APR 1980')
        self.indi2.addDeat('12 SEP 1990')
        self.indi3 = Individual()
        self.indi3.addID('@I3@')
        self.indi3.addName('Mary Rivas')
        self.indi3.addSex('F')
        self.indi3.addBirt('21 APR 1980')
        self.indi3.addDeat('12 SEP 2014')
        self.indi4 = Individual()
        self.indi4.addID('@I4@')
        self.indi4.addName('Mike Rivas')
        self.indi4.addSex('M')
        self.indi4.addBirt('21 APR 1976')
        self.indi5 = Individual()
        self.indi5.addID('@I5@')
        self.indi5.addName('Mike Rivas')
        self.indi5.addSex('M')
        self.indi5.addBirt('21 APR 2012')
        self.indi6 = Individual()
        self.indi6.addID('@I6@')
        self.indi6.addName('Mike Rivas')
        self.indi6.addSex('M')
        self.indi6.addBirt('21 APR 1988')
        self.indi6.addFamc('@F8@')
        self.indi7 = Individual()
        self.indi7.addID('@I7@')
        self.indi7.addName('Laura Rivas')
        self.indi7.addSex('F')
        self.indi7.addBirt('21 APR 1990')
        self.indi7.addFamc('@F8@')
        self.indi8 = Individual()
        self.indi8.addID('@I8@')
        self.indi8.addName('Laura Rivas')
        self.indi8.addSex('F')
        self.indi8.addBirt('21 APR 1990')
        self.indi8.addFamc('@F9@')


        self.individuals = dict()
        self.individuals['1'] = self.indi1
        self.individuals['2'] = self.indi2
        self.individuals['3'] = self.indi3
        self.individuals['4'] = self.indi4
        self.individuals['5'] = self.indi5
        self.individuals['6'] = self.indi6
        self.individuals['7'] = self.indi7
        self.individuals['8'] = self.indi8

        
        self.fam1 = Family()
        self.fam1.addFamID('@F2@')
        self.fam1.addHusb('@I1@')
        self.fam1.addWife('@I2@')
        self.fam1.addChil('@I4@')
        self.fam1.addChil('@I5@')
        self.fam1.addMarr('5 OCT 1999')
        self.fam1.addDiv('12 JUN 2012')
        self.fam2 = Family()
        self.fam2.addFamID('@F3@')
        self.fam2.addHusb('@I3@')
        self.fam2.addWife('@I3@')
        self.fam3 = Family()
        self.fam3.addFamID('@F3@')
        self.fam3.addHusb('@I1@')
        self.fam3.addWife('@I2@')
        self.fam3.addChil('@I4@')
        self.fam3.addChil('@I5@')
        self.fam3.addMarr('5 OCT 1999')
        self.fam3.addDiv('12 JUN 2012')
        self.fam4 = Family()
        self.fam4.addFamID('@F4@')
        self.fam4.addHusb('@I1@')
        self.fam4.addWife('@I3@')
        self.fam4.addChil('@I4@')
        self.fam4.addMarr('5 OCT 1999')
        self.fam4.addDiv('12 JUN 2012')
        self.fam5 = Family()
        self.fam5.addFamID('@F5@')
        self.fam5.addHusb('@I1@')
        self.fam5.addWife('@I3@')
        self.fam5.addChil('@I5@')
        self.fam5.addMarr('5 OCT 1999')
        self.fam5.addDiv('12 JUN 2012')
        


    def test_checkSameHusbWife(self):
        self.assertTrue(checkSameHusbWife(self.fam2))
        self.assertFalse(checkSameHusbWife(self.fam1))
        
    def test_checkDeathBeforeBirth(self):
        self.indi1.addBirt('9 MAY 1978')
        self.indi1.addDeat('9 MAY 1913')
        self.assertTrue(checkDeathBeforeBirth(self.indi1))
        
        self.indi1.addDeat('9 MAY 1978')
        self.assertFalse(checkDeathBeforeBirth(self.indi1))     

        self.indi1.addDeat('12 APR 2013')
        self.assertFalse(checkDeathBeforeBirth(self.indi1))    
        
        self.indi1.addDeat(None)
        self.assertFalse(checkDeathBeforeBirth(self.indi1))

    def test_checkMarryDead(self):
        self.assertTrue(checkMarryDead(self.fam3, self.individuals))
        self.assertFalse(checkMarryDead(self.fam4, self.individuals))

    def test_checkChildBeforeParents(self):
        self.assertTrue(checkChildBeforeParents(self.fam4, self.individuals))
        self.assertFalse(checkChildBeforeParents(self.fam5, self.individuals))

    def test_checkWifeIsMale(self):
        self.fam1.addWife('@I1@')
        self.assertTrue(checkWifeIsMale(self.fam1, self.individuals))
        self.fam1.addWife('@I2@')
        self.assertFalse(checkWifeIsMale(self.fam1, self.individuals))   
        
    def test_checkHusbandIsFemale(self):
        self.fam1.addHusb('@I2@')
        self.assertTrue(checkHusbandIsFemale(self.fam1, self.individuals))
        self.fam1.addHusb('@Ii@')
        self.assertFalse(checkHusbandIsFemale(self.fam1, self.individuals))  
    
    def test_marriedBeforeBirth(self):      
        self.indi1.addBirt('9 MAY 1915')
        self.indi2.addBirt('21 APR 1980')
        self.fam1.addMarr('9 MAY 1914')
        self.assertTrue(marriedBeforeBirth(self.fam1, self.individuals))
        self.indi1.addBirt('9 MAY 1800')
        self.indi2.addBirt('21 APR 1980')
        self.fam1.addMarr('9 MAY 1994')
        self.assertFalse(marriedBeforeBirth(self.fam1, self.individuals))

        
    def test_marriedTooYoung(self):      
        self.indi1.addBirt('9 MAY 1900')
        self.indi2.addBirt('21 APR 1900')
        self.fam1.addMarr('9 MAY 1912')
        self.assertTrue(marriedTooYoung(self.fam1, self.individuals))
        self.indi1.addBirt('9 MAY 1800')
        self.indi2.addBirt('21 APR 1980')
        self.fam1.addMarr('9 MAY 1994')
        self.assertFalse(marriedTooYoung(self.fam1, self.individuals))
        self.indi1.addBirt('9 MAY 1800')
        self.indi2.addBirt('21 APR 1980')
        self.fam1.addMarr('9 MAY 1600')
        self.assertFalse(marriedTooYoung(self.fam1, self.individuals))
        
    def test_deathBeforeMarriage(self):
        self.indi1.addDeat('9 MAY 2013')
        self.indi2.addDeat('12 SEP 1990')
        self.fam1.addMarr('9 MAY 2014')
        self.assertTrue(deathBeforeMarriage(self.fam1, self.individuals))
        self.indi1.addDeat('9 MAY 1800')
        self.indi2.addDeat('12 SEP 1990')
        self.fam1.addMarr('9 MAY 1800')
        self.assertFalse(deathBeforeMarriage(self.fam1, self.individuals))
        self.indi1.addDeat('9 MAY 2015')
        self.indi2.addDeat('12 SEP 1990')
        self.fam1.addMarr('9 MAY 1800')
        self.assertFalse(deathBeforeMarriage(self.fam1, self.individuals))
        self.assertTrue(checkMarryDead(self.fam3, self.individuals))
        self.assertFalse(checkMarryDead(self.fam4, self.individuals))

    def test_divorceBeforeMarriage(self):
        self.fam1.addMarr('9 MAY 1914')
        self.fam1.addDiv('9 MAY 1900')
        self.assertTrue(divorceBeforeMarriage(self.fam1, self.individuals))
        self.fam1.addMarr('9 MAY 1914')
        self.fam1.addDiv('9 MAY 1925')
        self.assertFalse(divorceBeforeMarriage(self.fam1, self.individuals))
        self.assertFalse(divorceBeforeMarriage(self.fam2, self.individuals))
        
    def test_tooManyChildren(self):
        self.assertFalse(tooManyChildren(self.fam1))
        famT = Family()
        self.assertFalse(tooManyChildren(famT))
        famT.addChil("1")
        famT.addChil("2")
        famT.addChil("3")
        famT.addChil("4")
        famT.addChil("5")
        self.assertTrue(tooManyChildren(famT))
        
    def test_tooOldParent(self):
        self.assertFalse(tooOldParent(self.fam1, self.individuals))
        self.indi1.addBirt('9 MAY 1578')
        self.assertTrue(tooOldParent(self.fam1, self.individuals))
        self.indi1.addBirt('9 MAY 1978')
        self.indi4.addBirt('21 APR 2076')
        self.assertTrue(tooOldParent(self.fam1, self.individuals))
        
    def test_marriedMoreThanOnePerson(self):
        self.families = dict()
        self.famA = Family()
        self.famA.addFamID('@A1@')
        self.famA.addHusb('@H1@')
        self.famA.addWife('@W1@')
        self.families['1'] = self.famA
        self.assertFalse(marriedMoreThanOnePerson(self.families))   

        self.famB = Family()
        self.famB.addFamID('@B1@')
        self.famB.addHusb('@H2@')
        self.famB.addWife('@W2@')
        self.families['2'] = self.famB
        self.assertFalse(marriedMoreThanOnePerson(self.families))
        
        self.famB.addWife('@W1@')
        self.assertTrue(marriedMoreThanOnePerson(self.families))
        
        self.famA.addDiv('12 JUN 2012')
        self.famB.addWife('@W1@')
        self.assertFalse(marriedMoreThanOnePerson(self.families))

    def test_marriedToSiblings(self):
        self.famA = Family()
        self.famA.addFamID('@F6@')
        self.famA.addHusb('@I6@')
        self.famA.addWife('@I7@')
        self.famA.addMarr('5 OCT 1999')
        self.assertTrue(marriedToSiblings(self.famA, self.individuals))
        self.famB = Family()
        self.famB.addFamID('@F6@')
        self.famB.addHusb('@I6@')
        self.famB.addWife('@I8@')
        self.famB.addMarr('5 OCT 1999')
        self.assertFalse(marriedToSiblings(self.famB, self.individuals))
Example #53
0
    def test_getDeat(self):
        DEAT = '12 APR 2013'
        self.assertEqual(self.indi.getDeat(), DEAT)

        indi = Individual()
        self.assertEqual(indi.getDeat(), None)
 def test_random(self):
     ind1 = Individual.random_ind()
     ind2 = Individual.random_ind(20)
     self.assertEqual(len(ind1.genome), 15)
     self.assertEqual(len(ind2.genome), 20)
     self.assertEqual(ind1.fitness, 0)
def evolve(G, p, popsize, gener, mutprob, coprob, tsize, elitism=None):
    nodes_ordered_by_demand = sorted(G.node.items(),
                                     key=lambda t: t[1]['demand'],
                                     reverse=True)
    t1 = clock()
    pop = []
    # generating first population, which will be random
    for i in range(popsize):
        individual = Individual(p, G)
        individual.calculate_fitness(G, nodes_ordered_by_demand)
        pop.append(individual)

    rank_population(pop)
    report = {
        'worst_i': pop[-1].fitness,
        'best_i': pop[0].fitness,
        'generation': 0,
        'better_sons': 0,
        'total_sons': 0,
        'best_i_hist': [pop[0].fitness],
        'mean_fitness_hist': [sum([i.fitness for i in pop]) / popsize],
        'repeated_i_hist': [popsize - unique_individuals(pop)]
    }
    for generation in range(gener):
        # applying elitism if relevant
        if elitism:
            topelite = int(ceil(elitism * popsize))
            new_pop = pop[0:topelite]
        else:  # if no elitism specified, simply create a new population
            new_pop = []

        # while the population is not complete
        while len(new_pop) < popsize:
            random_number = random()
            subpop = sample(pop, tsize)  # tournament individuals
            if random_number < mutprob:  # mutating
                new_pop.append(mutate(subpop[0], G))
                new_pop[-1].calculate_fitness(G, nodes_ordered_by_demand)
            elif random_number < coprob:  # doing crossover
                mean_fitness = (subpop[0].fitness + subpop[1].fitness) / 2.0
                i1, i2 = crossover(subpop[0], subpop[1])
                i1.calculate_fitness(G, nodes_ordered_by_demand)
                if i1.fitness > mean_fitness:
                    report['better_sons'] += 1
                report['total_sons'] += 1
                new_pop.append(i1)
                if i2 is not None:
                    i2.calculate_fitness(G, nodes_ordered_by_demand)
                    if i2.fitness > mean_fitness:
                        report['better_sons'] += 1
                    new_pop.append(i2)
                    report['total_sons'] += 1
            else:  # if no mutation or crossover, insert the best individual
                new_pop.append(deepcopy(subpop[0]))
            if len(new_pop) > popsize:
                new_pop.pop()
                report['total_sons'] -= 1
        pop = rank_population(new_pop)
        report['best_i_hist'].append(pop[0].fitness)
        report['mean_fitness_hist'].append(sum([i.fitness for i in pop]) /
                                                  popsize)
        report['repeated_i_hist'].append(popsize - unique_individuals(pop))
        if report['best_i'] > pop[0].fitness:
            report['best_i'] = pop[0].fitness
            report['generation'] = generation
        if report['worst_i'] < pop[-1].fitness:
            report['worst_i'] = pop[-1].fitness

    t2 = clock()
    report['time'] = round(t2 - t1, 3)
    report['gener_per_s'] = gener / report['time']
    return report
 def test_mutation_decision(self):
     self.assertIn(Individual.decide_if_mutate(), [True, False])
 def test_breeding(self):
     ind1 = Individual("111")
     ind2 = Individual("111")
     child1, child2 = ind1.breed_with(ind2)
     self.assertEqual(child1.genome, child2.genome)
 def test_mutation(self):
     ind1 = Individual.random_ind()
     mutated_gene_index, mutated_value = ind1.mutate_random_gene()
     self.assertEqual(ind1.genome[mutated_gene_index], mutated_value)

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
console_handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
logger.addHandler(console_handler)

parser = argparse.ArgumentParser(description = "Individual prac runner")
parser.add_argument('-d')
parser.add_argument('-p')
args = parser.parse_args()
part = args.p
user_id = re.search("([a-z]){6}([0-9]){3}", args.d).group(0)
submitter = Individual(user_id = user_id,
              logger = logger.getChild('manual_marker'))
submitter.directory = args.d
submitter.submission_directory = args.d

tester_module = importlib.import_module("prac_exam_2_part_{n}_tests".format(n = part))
TesterClass = getattr(tester_module, "PracExam2Part{n}Tests".format(n = part))
#tester_module = importlib.import_module("prac_exam_0_tests".format(n = part))
#TesterClass = getattr(tester_module, "PracExam0Tests".format(n = part))

tester = TesterClass(submitter, logger.getChild('pe2'))
tester.catalogue_submission_files()
tester.build()
tester.run_tests()
logger.info("Final Mark: {m:g}".format(m = float(submitter.mark)))
Example #60
0
    def setUp(self):
        self.indi1 = Individual()
        self.indi1.addID('@I1@')
        self.indi1.addName('John Rivas')
        self.indi1.addSex('M')
        self.indi1.addBirt('9 MAY 1978')
        self.indi1.addDeat('12 APR 2013')
        self.indi2 = Individual()
        self.indi2.addID('@I2@')
        self.indi2.addName('Mary Rivas')
        self.indi2.addSex('F')
        self.indi2.addBirt('21 APR 1980')
        self.indi2.addDeat('12 SEP 1990')
        self.indi3 = Individual()
        self.indi3.addID('@I3@')
        self.indi3.addName('Mary Rivas')
        self.indi3.addSex('F')
        self.indi3.addBirt('21 APR 1980')
        self.indi3.addDeat('12 SEP 2014')
        self.indi4 = Individual()
        self.indi4.addID('@I4@')
        self.indi4.addName('Mike Rivas')
        self.indi4.addSex('M')
        self.indi4.addBirt('21 APR 1976')
        self.indi5 = Individual()
        self.indi5.addID('@I5@')
        self.indi5.addName('Mike Rivas')
        self.indi5.addSex('M')
        self.indi5.addBirt('21 APR 2012')
        self.indi6 = Individual()
        self.indi6.addID('@I6@')
        self.indi6.addName('Mike Rivas')
        self.indi6.addSex('M')
        self.indi6.addBirt('21 APR 1988')
        self.indi6.addFamc('@F8@')
        self.indi7 = Individual()
        self.indi7.addID('@I7@')
        self.indi7.addName('Laura Rivas')
        self.indi7.addSex('F')
        self.indi7.addBirt('21 APR 1990')
        self.indi7.addFamc('@F8@')
        self.indi8 = Individual()
        self.indi8.addID('@I8@')
        self.indi8.addName('Laura Rivas')
        self.indi8.addSex('F')
        self.indi8.addBirt('21 APR 1990')
        self.indi8.addFamc('@F9@')


        self.individuals = dict()
        self.individuals['1'] = self.indi1
        self.individuals['2'] = self.indi2
        self.individuals['3'] = self.indi3
        self.individuals['4'] = self.indi4
        self.individuals['5'] = self.indi5
        self.individuals['6'] = self.indi6
        self.individuals['7'] = self.indi7
        self.individuals['8'] = self.indi8

        
        self.fam1 = Family()
        self.fam1.addFamID('@F2@')
        self.fam1.addHusb('@I1@')
        self.fam1.addWife('@I2@')
        self.fam1.addChil('@I4@')
        self.fam1.addChil('@I5@')
        self.fam1.addMarr('5 OCT 1999')
        self.fam1.addDiv('12 JUN 2012')
        self.fam2 = Family()
        self.fam2.addFamID('@F3@')
        self.fam2.addHusb('@I3@')
        self.fam2.addWife('@I3@')
        self.fam3 = Family()
        self.fam3.addFamID('@F3@')
        self.fam3.addHusb('@I1@')
        self.fam3.addWife('@I2@')
        self.fam3.addChil('@I4@')
        self.fam3.addChil('@I5@')
        self.fam3.addMarr('5 OCT 1999')
        self.fam3.addDiv('12 JUN 2012')
        self.fam4 = Family()
        self.fam4.addFamID('@F4@')
        self.fam4.addHusb('@I1@')
        self.fam4.addWife('@I3@')
        self.fam4.addChil('@I4@')
        self.fam4.addMarr('5 OCT 1999')
        self.fam4.addDiv('12 JUN 2012')
        self.fam5 = Family()
        self.fam5.addFamID('@F5@')
        self.fam5.addHusb('@I1@')
        self.fam5.addWife('@I3@')
        self.fam5.addChil('@I5@')
        self.fam5.addMarr('5 OCT 1999')
        self.fam5.addDiv('12 JUN 2012')