Esempio n. 1
0
    def test_will_activate(self):
        chrms = [
            Chromosome(1, 3, [0.5, 1, 0.4], None, constitutive_origins=None),
            Chromosome(3, 2, [0.0, 0.4], None, constitutive_origins=None)
        ]

        chrms[0].base_is_replicated = MagicMock(return_value=False)
        chrms[1].base_is_replicated = MagicMock(return_value=True)

        gen_loc_1 = GenomicLocation(1, chrms[0])
        gen_loc_2 = GenomicLocation(1, chrms[1])
        gen_loc_3 = GenomicLocation(0, chrms[1])

        times_true = 0
        for i in range(50000):
            self.assertTrue(
                gen_loc_1.will_activate(use_constitutive_origins=False,
                                        origins_range=0))
            self.assertFalse(
                gen_loc_3.will_activate(use_constitutive_origins=False,
                                        origins_range=0))
            if gen_loc_2.will_activate(use_constitutive_origins=False,
                                       origins_range=0):
                times_true += 1

        # Compares the number of times it was activated with its activation
        # probability.
        self.assertAlmostEqual(times_true / 50000, 0.4, 2)
Esempio n. 2
0
 def test_is_replicated(self):
     chrms = [Chromosome(1, 3, [0.2, 0.5, 0.6], None, constitutive_origins=None),
              Chromosome(3, 2, [0.1, 0.9], None, constitutive_origins=None)]
     chrms[0].is_replicated = MagicMock(return_value=True)
     chrms[1].is_replicated = MagicMock(return_value=False)
     gen = Genome(chrms)
     self.assertFalse(gen.is_replicated())
     chrms[1].is_replicated = MagicMock(return_value=True)
     self.assertTrue(gen.is_replicated())
    def generate_population(self):
        """
        Generate the population of Chromosomes.

        """
        for i in range(self.population_size):
            new_chromosome = Chromosome(self.ind_vars, self.dep_vars)
            # Grow the equation.
            new_chromosome.grow_equation_tree()
            self.population.append(new_chromosome)
Esempio n. 4
0
 def test_random_genomic_location(self):
     times = 500
     chrms = [Chromosome(1, 3, [0.2, 0.5, 0.6], None, constitutive_origins=None),
              Chromosome(3, 2, [0.1, 0.9], None, constitutive_origins=None)]
     gen = Genome(chrms)
     for i in range(times):
         gen_loc = gen.random_genomic_location()
         self.assertTrue(gen_loc.chromosome in chrms)
         self.assertLess(gen_loc.base, len(gen_loc.chromosome))
         self.assertGreaterEqual(gen_loc.base, 0)
Esempio n. 5
0
 def test_is_replicated(self):
     chrm_1 = Chromosome(1,
                         3, [1, 0.7, 0.5],
                         None,
                         constitutive_origins=None)
     chrm_2 = Chromosome(2, 2, [0.7, 0.5], None, constitutive_origins=None)
     chrm_2.strand = [1, 1]
     chrm_2.number_of_replicated_bases = 2
     chrm_1.strand = [0, 1, 1]
     chrm_1.number_of_replicated_bases = 2
     self.assertTrue(chrm_2.is_replicated())
     self.assertFalse(chrm_1.is_replicated())
Esempio n. 6
0
 def natural_population(self, list_of_genes, amount_of_chroms):
     """
     makes new population with given set genes and desired size for the population
     :param list_of_genes: list of ints, the items (0: weight, 1: value)
     :param amount_of_chroms: int, number of chromosomes
     :return:
     """
     population = []
     for i in range(amount_of_chroms):
         inst = Chromosome(self.max_weight, self.logger)
         population.append(inst.create_chromosome(list_of_genes))
     self.logger.debug('population: %s' % population)
     self.logger.debug('length of population: %s' % len(population))
     return population
Esempio n. 7
0
    def test_constructor(self):
        chrms = [
            Chromosome(1, 3, [0.5, 1, 0.4], None, constitutive_origins=None),
            Chromosome(3, 2, [0.0, 0.4], None, constitutive_origins=None)
        ]

        gen_loc_1 = GenomicLocation(2, chrms[0])
        gen_loc_2 = GenomicLocation(2, chrms[1])
        gen_loc_3 = GenomicLocation(3, chrms[1])

        self.assertEqual(gen_loc_1.base, 2)
        self.assertEqual(gen_loc_3.base, 3)
        self.assertEqual(gen_loc_2.chromosome, chrms[1])
        self.assertEqual(gen_loc_1.chromosome, chrms[0])
Esempio n. 8
0
    def __init__(self, last_name):

        self.size = config['size']
        self.color = config['color']
        self.speed = config['speed']
        self.first_name = config['first_name']
        self.name = "%s_%s" % (self.first_name, last_name)
        self.alive = True

        screen_size = game['screen_size']

        Chromosome.__init__(self)
        self.coord = self.generate_random_position(screen_size)
        self.direction = 0
        self.prev_direction = 4
def crossover(a, b):
    candidate1 = [0] * Chromosome.numTasks
    candidate2 = [0] * Chromosome.numTasks
    for i in range(0, len(a.schedule)):
        for j in range(0, len(a.schedule[i])):
            candidate1[Chromosome.data[j - 1]['key']] = i
    for i in range(0, len(b.schedule)):
        for j in range(0, len(b.schedule[i])):
            candidate2[Chromosome.data[j - 1]['key']] = i
    r = randrange(1, Chromosome.numTasks)
    new1 = candidate1[:r] + candidate2[r:]
    new2 = candidate2[:r] + candidate1[r:]
    tempChromosome = Chromosome()
    temp2 = Chromosome()
    for i in range(0, len(new1)):
        tempChromosome.schedule[new1[i]].append(Chromosome.data[i])
        temp2.schedule[new2[i]].append(Chromosome.data[i])
    return tempChromosome, temp2
Esempio n. 10
0
    def test_attach(self):
        rep_fork = ReplicationFork(Mock(), 1)
        rep_fork.base = 1
        # Assert throws exception
        with self.assertRaises(ValueError):
            rep_fork.attach(Mock(), None, None)

        chrms = [
            Chromosome(1, 3, [0.2, 0.5, 0.6], None, constitutive_origins=None),
            Chromosome(3, 2, [0.1, 0.9], None, constitutive_origins=None)
        ]
        chrms[0].replicate = MagicMock(return_value=True)

        gen = Genome(chrms)
        gen_loc = Mock(base=1, chromosome=chrms[0])
        rep_fork = ReplicationFork(gen, 2)
        rep_fork.attach(gen_loc, 1, 3)

        chrms[0].replicate.assert_called_with(start=1, end=1, time=3)
Esempio n. 11
0
    def test_is_replicated(self):
        chrms = [
            Chromosome(1, 3, [0.5, 1, 0.4], None, constitutive_origins=None),
            Chromosome(3, 2, [0.0, 0.4], None, constitutive_origins=None)
        ]

        chrms[0].base_is_replicated = MagicMock(return_value=False)
        chrms[1].base_is_replicated = MagicMock(return_value=True)

        gen_loc_1 = GenomicLocation(2, chrms[0])
        gen_loc_2 = GenomicLocation(2, chrms[1])

        self.assertTrue(gen_loc_2.is_replicated())
        self.assertFalse(gen_loc_1.is_replicated())

        chrms[0].base_is_replicated = MagicMock(return_value=True)

        self.assertTrue(gen_loc_1.is_replicated())
        self.assertTrue(gen_loc_2.is_replicated())
Esempio n. 12
0
    def test_advance(self):
        chrms = [
            Chromosome(1, 3, [0.2, 0.5, 0.6], None, constitutive_origins=None),
            Chromosome(3, 2, [0.1, 0.9], None, constitutive_origins=None)
        ]
        chrms[0].replicate = MagicMock(return_value=True)

        gen = Genome(chrms)
        gen_loc = Mock(base=1, chromosome=chrms[0])
        rep_fork = ReplicationFork(gen, 2)
        rep_fork.base = gen_loc.base
        rep_fork.chromosome = gen_loc.chromosome
        rep_fork.direction = 1
        self.assertTrue(rep_fork.advance(4))
        chrms[0].replicate.assert_called_with(start=gen_loc.base,
                                              end=gen_loc.base + 2,
                                              time=4)

        chrms[0].replicate = MagicMock(return_value=False)
        self.assertFalse(rep_fork.advance(4))
Esempio n. 13
0
 def test_constructor(self):
     chrm_1 = Chromosome(1,
                         3, [1, 0.7, 0.5],
                         None,
                         constitutive_origins=None)
     self.assertIsInstance(chrm_1, Chromosome)
     self.assertEqual(chrm_1.code, 1)
     self.assertEqual(chrm_1.length, 3)
     self.assertEqual(chrm_1.number_of_replicated_bases, 0)
     self.assertEqual(chrm_1.number_of_origins, 0)
     self.assertEqual(chrm_1.activation_probabilities, [1, 0.7, 0.5])
Esempio n. 14
0
    def new_population(self, best, list_of_genes):
        """
        creates improved population:
         1. takes the 50% best chromosomes from previous population and divide them by half:
         1.a half of the best are parent - each couple will create one child
         1.b half of the best will be mutated and continue to the second population
         2. the rest will be new neutral chromosomes from the entire list of genes to return to the
         the given size of population (we keep population size as constant
        :param best: list of best chromosomes in the population
        :param list_of_genes: list of extra genes to insert to chromosome
        :return:
        """
        new_population = self.create_new_population(best, list_of_genes)
        parents, mutants = Population.create_parents_and_mutants(best)

        # new children (mix of parents)
        for i in range(0, len(parents) - 1, cnf.CUT_BY):
            inst = Chromosome(self.max_weight, self.logger)
            new_population.append(inst.crossover(parents[i], parents[i + 1]))

        # new mutations size of whats is left of the best after allocation of parents
        for mutant in mutants:
            inst = Chromosome(self.max_weight, self.logger)
            new_population.append(inst.mutation(mutant, list_of_genes))
        self.logger.debug('new population: %s' % new_population)
        return new_population
Esempio n. 15
0
 def test_activation_probability(self):
     chrm_1 = Chromosome(1,
                         3, [1, 0.7, 0.5],
                         None,
                         constitutive_origins=None)
     chrm_2 = Chromosome(2, 2, [0.4, 0.8], None, constitutive_origins=None)
     self.assertAlmostEqual(chrm_2.activation_probability(0), 0.4)
     self.assertAlmostEqual(chrm_2.activation_probability(1), 0.8)
     self.assertAlmostEqual(chrm_1.activation_probability(0), 1)
     self.assertAlmostEqual(chrm_1.activation_probability(1), 0.7)
     self.assertAlmostEqual(chrm_1.activation_probability(2), 0.5)
Esempio n. 16
0
def main():
    temp = Chromosome(0)

    creator.create("FitnessMin", base.Fitness, weights=(-1.0, ))
    creator.create("Individual", list, fitness=creator.FitnessMin)

    MU = 20
    NGEN = 100
    CXPB = 0.95

    toolbox = base.Toolbox()
    toolbox.register("individual", initialisation, creator.Individual)
    toolbox.register("population", tools.initRepeat, list, toolbox.individual)
    toolbox.register("evaluate", calculateFitness)
    toolbox.register("select", tools.selNSGA2)
    toolbox.register("mate", tools.cxOnePoint)
    toolbox.register("mutate", tools.mutShuffleIndexes, indpb=0.05)

    pop = toolbox.population(n=MU)
    fitnesses = list(map(toolbox.evaluate, pop))
    for ind, fit in zip(pop, fitnesses):
        ind.fitness.values = fit

    plotter = []
    for i in range(NGEN):
        pop = toolbox.select(pop, len(pop))
        offspring = tools.selTournamentDCD(pop, len(pop))
        offspring = [toolbox.clone(ind) for ind in offspring]

        for ind1, ind2 in zip(offspring[::2], offspring[1::2]):
            if random.random() <= CXPB:
                toolbox.mate(ind1, ind2)

            toolbox.mutate(ind1)
            toolbox.mutate(ind2)
            del ind1.fitness.values, ind2.fitness.values

        # Evaluate the individuals with an invalid fitness
        invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
        fitnesses = toolbox.map(toolbox.evaluate, invalid_ind)
        for ind, fit in zip(invalid_ind, fitnesses):
            ind.fitness.values = fit

        # Select the next generation population
        pop = toolbox.select(pop + offspring, MU)
        plotter.append(mean([k.fitness.values[0] for k in pop]))

    plt.plot(plotter)
    plt.xlabel('Number of iterations')
    plt.ylabel('Fitness of the population')
    plt.show()
Esempio n. 17
0
def initialisation():
    # a temporary chromosome to be manipulated before adding to the population
    tempChromosome = Chromosome()
    for i in range(0, 100000):
        for j in range(0, tempChromosome.numTasks):
            k = randrange(0, tempChromosome.numProcs)
            tempChromosome.schedule[k].append(j)
        for j in range(0, tempChromosome.numProcs):
            tempChromosome.schedule[j].sort()
        # tempChromosome.schedule.sort(key=tempChromosome.schedule.itemgetter(0))
        tempChromosome.calculateFitness()
        population.append(tempChromosome)
        tempChromosome = Chromosome()
Esempio n. 18
0
 def test_set_dormant_origin_activation_probability(self):
     chrm_size = 300000
     chrm_1 = Chromosome(1,
                         chrm_size, [0.5] * chrm_size,
                         None,
                         constitutive_origins=None)
     chrm_2 = Chromosome(1,
                         chrm_size, [0.9] * chrm_size,
                         None,
                         constitutive_origins=None)
     chrm_1.set_dormant_origin_activation_probability(
         (int)((chrm_size - 1) / 2))
     chrm_2.set_dormant_origin_activation_probability((int)(chrm_size / 9))
     self.assertGreater(sum(chrm_1.activation_probabilities, 0),
                        chrm_size * 0.5)
     self.assertLessEqual(sum(chrm_1.activation_probabilities, 0),
                          chrm_size)
     self.assertGreater(sum(chrm_2.activation_probabilities, 0),
                        chrm_size * 0.9)
     self.assertLessEqual(sum(chrm_2.activation_probabilities, 0),
                          chrm_size)
def initialisation(populationSize):  # done
    population = []  # a list of chromosomes
    tempChromosome = Chromosome()
    # a temporary chromosome to be manipulated before adding to the population
    for i in range(0, populationSize):
        for j in Chromosome.data:
            k = randrange(0, Chromosome.numProcs)
            tempChromosome.schedule[k].append(j)
        for j in range(0, Chromosome.numProcs):
            tempChromosome.schedule[j].sort(key=cmp_to_key(compare))
        tempChromosome.calculateFitness()
        population.append(tempChromosome)
        tempChromosome = Chromosome()
    return population
Esempio n. 20
0
 def test_replicate(self):
     chrm_1 = Chromosome(1,
                         6, [1, 0.7, 0.5, 0.3, 0.8, 0.2],
                         None,
                         constitutive_origins=None)
     chrm_1.replicate(0, 4, 1)
     for i in range(6):
         if i in range(0, 5):
             self.assertNotEqual(chrm_1.strand[i], 0)
         else:
             self.assertEqual(chrm_1.strand[i], 0)
     self.assertEqual(chrm_1.number_of_replicated_bases, 5)
     chrm_1.replicate(4, 5, 1)
     self.assertEqual(chrm_1.length, chrm_1.number_of_replicated_bases)
Esempio n. 21
0
def main(size, gen, crossover):
    t = Chromosome(0, size)
    # low coupling, high cohesion
    creator.create('FitnessMinMax', base.Fitness, weights=(1.0, -1.0))
    creator.create('Individual', list, fitness=creator.FitnessMinMax)

    MU = size
    NGEN = gen
    CXPB = crossover

    toolbox = base.Toolbox()
    toolbox.register("individual", initialisation, creator.Individual)
    toolbox.register("population", tools.initRepeat, list, toolbox.individual)
    toolbox.register("evaluate", calculateFitness,
                     myChromosome=creator.Individual)
    toolbox.register("select", tools.selNSGA2)
    toolbox.register("mate", crossoverSwapComponentSequences,
                     myChromosome=creator.Individual)
    toolbox.register("mutate", mutateSplitMergeProbabilistic, probSplit=0.6,
                     probMerge=0.4, myChromosome=creator.Individual)

    pop = toolbox.population(n=MU)

    invalid_ind = [ind for ind in pop if not ind.fitness.valid]
    fitnesses = toolbox.map(toolbox.evaluate, invalid_ind)
    for ind, fit in zip(invalid_ind, fitnesses):
        ind.fitness.values = fit

    pop = toolbox.select(pop, len(pop))

    plotCohesion = []
    plotCoupling = []
    for gen in range(0, NGEN):
        offspring = tools.selTournamentDCD(pop, 2)
        offspring = [toolbox.clone(ind) for ind in offspring]
        print('Iteration %d' % gen)

        for ind1, ind2 in zip(offspring[::2], offspring[1::2]):
            if random.random() <= CXPB:
                toolbox.mate(ind1, ind2)

            toolbox.mutate(ind1)
            toolbox.mutate(ind2)
            del ind1.fitness.values, ind2.fitness.values

        invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
        fitnesses = toolbox.map(toolbox.evaluate, invalid_ind)
        for ind, fit in zip(invalid_ind, fitnesses):
            ind.fitness.values = fit

        pop = toolbox.select(pop + offspring, MU)
        plotCohesion.append(mean([i.fitness.values[0] for i in pop]))
        plotCoupling.append(mean([i.fitness.values[1] for i in pop]))

    plt.plot(plotCohesion)
    plt.xlabel('Number of iterations')
    plt.ylabel('Mean cohesion of the population')
    s = 'cohesion.svg'
    plt.savefig(s, format='svg')
    plt.gcf().clear()

    plt.plot(plotCoupling)
    plt.xlabel('Number of iterations')
    plt.ylabel('Mean coupling of the population')
    s = 'coupling.svg'
    plt.savefig(s, format='svg')
    plt.gcf().clear()
    return pop
Esempio n. 22
0

class LoggerMock:
    def __init__(self):
        return

    def debug(self, text):
        pass

    def info(self, test):
        pass


# initialize for all tests
logger = LoggerMock()
inst = Chromosome(5, logger)


def test_create_chromosome():
    chromosome = inst.create_chromosome(
        np.array([[6, 6], [2, 2], [3, 3], [7, 7]]))
    assert np.array_equal(chromosome, np.array(
        [[2, 2], [3, 3]])) or np.array_equal(chromosome,
                                             np.array([[3, 3], [2, 2]]))


def test_crossover():
    child = inst.crossover(np.array([[7, 7], [3, 3]]),
                           np.array([[2, 2], [8, 8]]))
    assert np.array_equal(child, np.array([[2, 2], [3, 3]])) or np.array_equal(
        child, np.array([[3, 3], [2, 2]]))
Esempio n. 23
0
 def test_constructor(self):
     chrms = [Chromosome(1, 3, [0.2, 0.5, 0.6], None, constitutive_origins=None),
              Chromosome(3, 2, [0.1, 0.9], None, constitutive_origins=None)]
     gen = Genome(chrms)
     self.assertEqual(gen.chromosomes, chrms)