예제 #1
0
 def crossover(self, ind1: Individual, ind2: Individual) -> Tuple[Individual, Individual]:
     point = random.randint(1, self.dna_length-1)
     str1 = self.mutate(ind1.dna[:point]+ind2.dna[point:])
     str2 = self.mutate(ind2.dna[:point]+ind1.dna[point:])
     ind3 = Individual(self.test, str1)
     ind4 = Individual(self.test, str2)
     return ind3, ind4
예제 #2
0
    def crossover(par0, par1):
        """
            Mixes genotype of 2 individuals and returns
            new individuals
            :param par0: first parent
            :param par1: second parent
            :return: tuple of two new individuals
        """
        son0 = Individual()
        son1 = Individual()
        son0.genotype.clear()
        son1.genotype.clear()
        first = random.randint(0, 4)
        second = random.randint(first, 4)
        gen_par0 = list(par0.genotype)
        gen_par1 = list(par1.genotype)
        for i in range(first):
            son0.genotype.append(gen_par0[i])
            son1.genotype.append(gen_par1[i])

        for i in range(first, second):
            son0.genotype.append(gen_par0[i])
            son1.genotype.append(gen_par1[i])

        for i in range(second, 5):
            son0.genotype.append(gen_par0[i])
            son1.genotype.append(gen_par1[i])

        son0.mutation()
        son1.mutation()
        son0.repair()
        son1.repair()
        return son0, son1
 def test_firstCousinsMarried_us19(self):
     from Individual import Individual
     from Family import Family
     list1 = {
         'A1': Individual('A1', childFamily='B1'),
         'A2': Individual('A1'),
         'A3': Individual('A3', childFamily='B1', spouseFamily='B3'),
         'A4': Individual('A4', childFamily='B2', spouseFamily='B4')
     }
     #Married to first cousin
     list2 = {
         'B1': Family('B1'),
         'B2': Family('B2', husband='A1', wife='A2'),
         'B3': Family('B3', husband='A3'),
         'B4': Family('B4', husband='A4', wife='A5')
     }
     children = ['A1', 'A3']
     for child in children:
         list2['B1'].setChildren(child)
     list2['B2'].setChildren('A4')
     cousins = ['A5', 'A6']
     for cousin in cousins:
         list2['B3'].setChildren(cousin)
     self.assertTrue(firstCousinsMarried_us19(list1['A4'], list1, list2))
     #Not married to first cousin
     list3 = {
         'B1': Family('B1'),
         'B2': Family('B2', husband='A1', wife='A2'),
         'B3': Family('B3'),
         'B4': Family('B4', husband='A4', wife='A7')
     }
     self.assertFalse(firstCousinsMarried_us19(list1['A4'], list1, list3))
예제 #4
0
def crossover(ind1, ind2):
    crossing_odds = random.randint(0, 100)
    # return references to one of parents if not crossing
    if crossing_odds > ap.CROSSING_PROBABILITY:
        parent = return_random_parent(ind1, ind2)
        return parent
    # if crossing
    else:
        paths_child_1 = []
        paths_child_2 = []
        for x in range(len(ind1.paths)):
            gene_change_odds = random.randint(0, 100)
            # swap genes, deep copy - to avoid changing the parent
            if gene_change_odds < ap.GENE_CHANGE_PROBABILITY:
                paths_child_1.append(pickle.loads(pickle.dumps(ind2.paths[x])))
                paths_child_2.append(pickle.loads(pickle.dumps(ind1.paths[x])))
            # else original genes
            else:
                paths_child_1.append(pickle.loads(pickle.dumps(ind1.paths[x])))
                paths_child_2.append(pickle.loads(pickle.dumps(ind2.paths[x])))

        # new children
        child_1 = Individual(ind1.pcb)
        child_1.paths = paths_child_1

        child_2 = Individual(ind1.pcb)
        child_2.paths = paths_child_2

        return child_1, child_2
예제 #5
0
파일: Algorithm.py 프로젝트: jimmysitu/GeST
 def __onePoint_crossover__(self, individual1,
                            individual2):  #creates two new individuals
     #newIndiv=Individual(); TODO find out this weird bug.. for some reason the newIndiv wasn't reinitialized;;;This is the default behaviour of python when I use a muttable object for optional parameter # Solved look here for the answer http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument
     loop_code1 = []
     loop_code2 = []
     crossover_point = self.rand.choice(range(int(self.loopSize) - 1))
     for i in range(int(self.loopSize)):
         if (i > crossover_point):
             #do crossover
             loop_code1.append(individual2.getInstruction(i).copy())
             loop_code2.append(individual1.getInstruction(i).copy())
         else:  #keep instruction as it is
             loop_code1.append(individual1.getInstruction(i).copy())
             loop_code2.append(individual2.getInstruction(i).copy())
     children = []
     children.append(
         Individual(sequence=loop_code1,
                    generation=self.populationsExamined))
     children.append(
         Individual(sequence=loop_code2,
                    generation=self.populationsExamined))
     children[0].setParents(individual1, individual2)
     ##the first parent is the code that remains the same.. the second parent is the code that came after crossover
     children[1].setParents(individual2, individual1)
     return children
 def __init__(self):
     self.ind = []
     self.nextInd = []
     for _ in range(Individual.POP_SIZE):
         self.ind.append(Individual())
         self.nextInd.append(Individual())
     self.evaluate()
 def test_list_multipe_births_US32(self):
     from Individual import Individual
     list1 = {
         'A1': Individual('A1', birthday='1960-03-12'),
         'A2': Individual('A2', birthday='1960-03-12')
     }
     self.assertFalse(list_multipe_births_US32(list1, list1['A1']))
예제 #8
0
    def crossing_over(self):
        '''
        Genes of the population undergo crossing over
        '''

        for individual in range(0, self.pop_size - 1, 2):
            child_one = []
            child_two = []
            split_point = np.random.randint(0, self.rectangles * self.alleles)
            for i in range(0, split_point):
                child_one.append(self.population[individual].gray_encoding[i])
                child_two.append(self.population[individual +
                                                 1].gray_encoding[i])
            for i in range(split_point, self.rectangles * self.alleles):
                child_one.append(self.population[individual +
                                                 1].gray_encoding[i])
                child_two.append(self.population[individual].gray_encoding[i])
            child_one = "".join(child_one)
            child_two = "".join(child_two)
            brother = Individual(self.rectangles, child_one, self.pixel_x,
                                 self.pixel_y)
            sister = Individual(self.rectangles, child_two, self.pixel_x,
                                self.pixel_y)
            self.population.append(brother)
            self.population.append(sister)
 def __init__(self, cities):
     self.ind = []
     self.nextInd = []
     self.cities = cities
     for _ in range(Individual.POP_SIZE):
         self.ind.append(Individual(cities))
         self.nextInd.append(Individual(cities))
     self.evaluate()
 def test_recent_death_us36(self):
     from Individual import Individual
     self.assertEqual(
         recent_deaths_us36(Individual(self, 10, death='2017-11-11')),
         False)
     self.assertFalse(
         recent_deaths_us36(Individual(self, 10, death='1845-10-05')))
     self.assertFalse(
         recent_deaths_us36(Individual(self, 10, death='2017-10-10')))
def test_getIndividual(standartinput):
    genIndividual = Individual("random individual", standartinput[0],
                               standartinput[1], standartinput[2])
    genfisher = Individual("random fisher", standartinput[3], standartinput[5],
                           standartinput[4])
    genIsland = Island("Generic Island")
    assert genIsland.addIndividual(genIndividual) == 1
    assert genIsland.addIndividual(genfisher) == 1
    assert genIsland.getIndividual(genIndividual.getName()) == genIndividual
    assert genIsland.getIndividual(genfisher.getName()) == genfisher
    def test_List_upcoming_birthdsy_US38(self):
        from Individual import Individual
        from Family import Family
        list1 = {
            'A1': Individual('A1', birthday='1960-12-10'),
            'A2': Individual('A1', birthday='1960-12-11'),
            'A3': Individual('A1', birthday='1993-12-09')
        }

        self.assertFalse(List_upcoming_birthdsy_US38(list1['A1']))
 def test_siblingSpacing_us13(self):
     from Individual import Individual
     from Family import Family
     list1 = {'B1': Family('B1')}
     children = ['A3', 'A4', 'A5']
     for child in children:
         list1['B1'].setChildren(child)
     #Spacing violated by less than 8 months condition
     list2 = {
         'A3': Individual('A1', birthday='1980-01-01'),
         'A4': Individual('A2', birthday='1987-02-05'),
         'A5': Individual('A3', birthday='1980-07-01')
     }
     self.assertTrue(siblingSpacing_us13(list1['B1'], list2))
     #Spacing violated by more than 2 days condition
     list3 = {
         'A3': Individual('A1', birthday='1980-01-01'),
         'A4': Individual('A2', birthday='1987-02-05'),
         'A5': Individual('A3', birthday='1980-01-03')
     }
     self.assertTrue(siblingSpacing_us13(list1['B1'], list2))
     #Spacing not violated
     list4 = {
         'A3': Individual('A1', birthday='1980-01-01'),
         'A4': Individual('A2', birthday='1987-02-05'),
         'A5': Individual('A3', birthday='1984-01-03')
     }
     self.assertFalse(siblingSpacing_us13(list1['B1'], list4))
    def test_List_large_age_difference_US34(self):
        from Individual import Individual
        from Family import Family
        list1 = {
            'A1': Individual('A1', age='106'),
            'A2': Individual('A1', age='39')
        }

        list2 = {'B1': Family('B1', husband='A1', wife='A2')}

        self.assertFalse(List_large_age_difference_US34(list1, list2))
 def test_lessThan150Years_US07(self):
     #from Individual import birthBeforeMarriage
     from Individual import Individual
     self.assertEqual(
         lessThan150Years_US07(Individual(self, 10, birthday='1945-01-05')),
         True)
     self.assertFalse(
         lessThan150Years_US07(Individual(self, 10, birthday='1845-10-05')))
     self.assertFalse(
         lessThan150Years_US07(
             Individual(self, 10, birthday='1845-10-05',
                        death='2010-10-05')))
 def test_checkBirthBeforeMarriageOfParents_us08(self):
     from Family import Family
     from Individual import Individual
     self.assertEqual(
         checkBirthBeforeMarriageOfParents_us08(
             Family(self, 10, marriage='1945-10-05'),
             Individual(self, 10, birthday='1915-10-05')), False)
     self.assertTrue(
         checkBirthBeforeMarriageOfParents_us08(
             Family(self, 10, marriage='1945-10-05', divorce='1955-10-05'),
             Individual(self, 10, birthday='1947-10-05',
                        death='1975-03-10')))
 def test_orderSiblings_us28(self):
     from Family import Family
     from Individual import Individual
     list1 = {
         'A1': Individual('A1', childFamily='B1', age='48'),
         'A2': Individual('A2', childFamily='B1', age='31'),
         'A3': Individual('A3', childFamily='B1', age='37')
     }
     list2 = {'B1': Family('B1')}
     children = ['A1', 'A2', 'A3']
     for child in children:
         list2['B1'].setChildren(child)
     self.assertEqual(orderSiblings_us28(list2['B1'], list1), 'B1 A1 A3 A2')
예제 #18
0
    def create_offsprings(self, parent_1, parent_2, crosspoint):
        parent_1_part_1 = parent_1.genotype[:crosspoint]
        parent_1_part_2 = parent_1.genotype[crosspoint:]

        parent_2_part_1 = parent_2.genotype[:crosspoint]
        parent_2_part_2 = parent_2.genotype[crosspoint:]

        offspring_1 = Individual(
            np.concatenate((parent_1_part_1, parent_2_part_2)))
        offspring_2 = Individual(
            np.concatenate((parent_2_part_1, parent_1_part_2)))

        return (offspring_1, offspring_2)
 def test_List_orphans_US33(self):
     from Individual import Individual
     from Family import Family
     list1 = {
         'A1': Individual('A1', death='1960-12-10'),
         'A2': Individual('A1', death='1960-12-11'),
         'A3': Individual('A1', birthday='1993-12-09')
     }
     list2 = {'B1': Family('B1', husband='A1', wife='A2')}
     children = ['A3']
     for child in children:
         list2['B1'].setChildren(child)
     self.assertFalse(List_orphans_US33(list1, list2))
 def test_Recent_surviors_US37(self):
     from Individual import Individual
     from Family import Family
     list1 = {
         'A1': Individual('A1', death='2017-10-29'),
         'A2': Individual('A1', birthday='1960-03-12'),
         'A3': Individual('A1', birthday='1993-03-12')
     }
     list2 = {'B1': Family('B1', husband='A1', wife='A2')}
     children = ['A3']
     for child in children:
         list2['B1'].setChildren(child)
     self.assertFalse(Recent_surviors_US37(list1, list2))
예제 #21
0
    def init(self):
        ind = Individual()
        ind.init_with_parameter(self.rule_base, self.data_base, self.w1)
        ind.reset()
        self.population_array.append(ind)
        for i in range(1, self.pop_size):
            ind = Individual()
            ind.init_with_parameter(self.rule_base, self.data_base, self.w1)
            ind.random_values()
            self.population_array.append(ind)

        self.best_fitness = 0.0
        self.ntrials = 0
예제 #22
0
 def __init__(self, pop):
     self.numberOfIndividuals = pop
     self.population = Population(pop)
     self.generationCount = 0
     self.fittest = Individual(0, 0, 0, 0, 0, 0, 0)
     self.secondFittest = Individual(0, 0, 0, 0, 0, 0, 0)
     self.place = Individual(0, 0, 0, 0, 0, 0, 0)
     self.init = InitClass()
     self.maxfit = 0
     self.numberofGenes = 6
     self.all = []
     for individual in (self.population.getIndividuals()):
         self.all.append(individual)
예제 #23
0
    def initialize_from_csv(self, path):

        dataFrame = pandas.read_csv(path, sep=",")

        ref_ind = Individual(
            (dataFrame.values)[0, 1:][0], (dataFrame.values)[0, 1:][1],
            (dataFrame.values)[0, 1:][3], (dataFrame.values)[0, 1:][2])
        print("RNA_ref = " + ref_ind.RNA_structure)

        init_pop = []
        for ind in (dataFrame.values)[1:self.population_size + 1, 1:]:
            init_pop.append(Individual(ind[0], ind[1], ind[3], ind[2]))

        return init_pop
 def test_individualAge_us27(self):
     from Individual import Individual
     self.assertEqual(
         individualAge_us27(Individual(self, 10, birthday='1977-10-14')),
         40)
     self.assertEqual(
         individualAge_us27(Individual(self, 10, birthday='1977-01-29')),
         40)
     self.assertEqual(
         individualAge_us27(Individual(self, 10, birthday='1977-09-14')),
         40)
     self.assertEqual(
         individualAge_us27(Individual(self, 10, birthday='1977-12-17')),
         39)
예제 #25
0
 def init_from_old_generation(old_generation, world):
     """It generates new generation with given old one.
     Mutation needs to be given after this method.
     """
     new_generation = []
     for i in range(0, Generation.NUM_OF_INDIVIDUALS, 2):
         first_parent, second_parent = old_generation.select_two_parents()
         first_child_steps, second_child_steps = Generation.cross_over(
             first_parent, second_parent)
         new_generation.append(Individual(world, first_child_steps))
         new_generation.append(Individual(world, second_child_steps))
     return sorted(np.array(new_generation),
                   key=lambda ind: ind.fitness,
                   reverse=True)
예제 #26
0
 def run(self):
     state = Individual(self.__size, self.__setS, self.__setT)
     final = deepcopy(state)
     while self.__crtIter in range(self.__nrIter) and state.fitness() != 0:
         neighbors = self.getNeighbours(state)
         bestN = self.bestNeighbor(neighbors)
         if state.fitness() > bestN.fitness():
             state = bestN
         else:
             state = Individual(self.__size, self.__setS, self.__setT)
         self.__crtIter += 1
         # if self.__crtIter % 1000 == 0: print(self.__crtIter)
     final = state
     return final
예제 #27
0
    def __crossover(individual1_passed, individual2_passed):
        child1 = dict.fromkeys(string.ascii_lowercase, 0)
        child2 = dict.fromkeys(string.ascii_lowercase, 0)
        used_alphabet_child1 = []
        used_alphabet_child2 = []

        for letter in string.ascii_lowercase:
            if random.uniform(0, 1) < 0.5:
                temp = individual1_passed
                individual1_passed = individual2_passed
                individual2_passed = temp
            if individual1_passed.mapped_alphabet[letter] not in child1.values(
            ):
                child1[letter] = individual1_passed.mapped_alphabet[letter]
                used_alphabet_child1.append(
                    individual1_passed.mapped_alphabet[letter])
            else:
                child1[letter] = 'None'
            if individual2_passed.mapped_alphabet[letter] not in child2.values(
            ):
                child2[letter] = individual2_passed.mapped_alphabet[letter]
                used_alphabet_child2.append(
                    individual2_passed.mapped_alphabet[letter])
            else:
                child2[letter] = 'None'

        unused_alphabet_child1 = list(
            set(string.ascii_lowercase) - set(used_alphabet_child1))
        unused_alphabet_child2 = list(
            set(string.ascii_lowercase) - set(used_alphabet_child2))
        # i = 0
        # j = 0
        for alphabet in string.ascii_lowercase:
            if child1[alphabet] == 'None':
                random_letter = random.randint(0,
                                               len(unused_alphabet_child1) - 1)
                child1[alphabet] = unused_alphabet_child1[random_letter]
                unused_alphabet_child1.remove(
                    unused_alphabet_child1[random_letter])
                # i += 1
            if child2[alphabet] == 'None':
                random_letter = random.randint(0,
                                               len(unused_alphabet_child2) - 1)
                child2[alphabet] = unused_alphabet_child2[random_letter]
                unused_alphabet_child2.remove(
                    unused_alphabet_child2[random_letter])
                # j += 1
        return Individual(list(child1.values())), Individual(
            list(child2.values()))
예제 #28
0
    def init(self):
        self.logger=Logger.set_logger()
        ind = Individual()
        ind.init_with_parameter(self.rule_base, self.data_base, self.w1)
        ind.reset()
        self.population_array.append(ind)
        for i in range(1, self.pop_size):
            ind = Individual()
            ind.init_with_parameter(self.rule_base, self.data_base, self.w1)
            ind.random_values(self.seed_value)
            self.population_array.append(ind)
            print(" the init loop  method added "+ str(i)+"individuals ")

        self.best_fitness = 0.0
        self.ntrials = 0
예제 #29
0
def crossover_b(parent_a, parent_b):
    (x, y) = parent_a.phenotype.shape
    child_a = Individual(0, 1, x, y)
    child_b = Individual(0, 1, x, y)
    t = True
    for i in range(0, x):
        if t:
            child_a.phenotype[i, :] = parent_a.phenotype[i, :]
            child_b.phenotype[i, :] = parent_b.phenotype[i, :]
            t = False
        else:
            child_a.phenotype[i, :] = parent_b.phenotype[i, :]
            child_b.phenotype[i, :] = parent_a.phenotype[i, :]
            t = True
    return child_a, child_b
예제 #30
0
    def init(self):
        pos = self.get_bp_position()
        nucleotides = ["A", "U", "G", "C"]
        base_paire = ["AU", "UA", "GU", "GC", "UG", "CG"]
        pop = []
        i = 0
        while i < self.population_size:

            if i < 4:
                arn = numpy.random.choice(nucleotides[i:i + 1],
                                          len(self.landscape.target_structure))
            else:
                arn = numpy.random.choice(nucleotides,
                                          len(self.landscape.target_structure))

            for bp_cord in pos:
                bp = numpy.random.choice(base_paire, 1)
                arn[bp_cord[0]] = bp[0][0]
                arn[bp_cord[1]] = bp[0][1]
            pop.append(''.join(arn))
            i = len(set(pop))

        pop = numpy.array(list(set(pop)))

        init_pop = []
        for seq in pop:
            strc, mfe = RNA.fold(seq)
            init_pop.append(
                Individual(seq, strc, mfe, self.landscape.fitness(strc)))

        return init_pop