76 lines
2.2 KiB
Python
76 lines
2.2 KiB
Python
from individual_interface import *
|
|
from random import *
|
|
from math import *
|
|
|
|
CHIFFRE = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
|
|
|
|
|
|
class Combinaison(Individual_Interface):
|
|
|
|
|
|
def copy(self):
|
|
'''
|
|
build a copy of self, the genome is a copy of self's genome
|
|
|
|
:return: a new Individual which is a "clone" of self
|
|
:rtype: an Individual object
|
|
'''
|
|
copy = Combinaison(self.get_size())
|
|
copy.set_value(self.get_value())
|
|
return copy
|
|
|
|
|
|
def init_value(self):
|
|
'''
|
|
randomly initialize the genome value of self
|
|
'''
|
|
|
|
return [choice(CHIFFRE) for _ in range (self.get_size())]
|
|
|
|
|
|
def cross_with(self, other):
|
|
'''
|
|
perform a 1 point crossover between self and other, two new built individuals are returned
|
|
|
|
:param other: the individual to cross with
|
|
:type other: an Individual object
|
|
:return: the two new Individuals built by 1 point crossover operation
|
|
:rtype: 2-uple of individuals
|
|
'''
|
|
value = self.get_value()
|
|
other_value = other.get_value()
|
|
|
|
pivot = randint (0, self.get_size())
|
|
|
|
test_1, test_2 = Combinaison(self.get_size()), Combinaison(self.get_size())
|
|
|
|
test_1.set_value(value[:pivot] + other_value[pivot:])
|
|
test_2.set_value(other_value[:pivot] + value[pivot:])
|
|
|
|
return (test_1, test_2)
|
|
|
|
|
|
def mutate(self, probability):
|
|
'''
|
|
apply mutation operation to self : each element of the genome sequence is randomly changed with given probabiliy
|
|
|
|
side effect : self's genome is modified
|
|
|
|
:param probability: the probability of mutation for every gene
|
|
:type probability: float
|
|
:UC: probability in [0,1[
|
|
'''
|
|
for gene in range(len(self.get_value())):
|
|
proba = uniform(0, 1)
|
|
if proba < probability :
|
|
self.mutate_gene(gene)
|
|
|
|
def mutate_gene(self, gene):
|
|
temp = self.get_value()
|
|
self.set_value(temp[:gene] + [choice(CHIFFRE)] + temp [gene+1:])
|
|
|
|
|
|
|
|
|
|
|