121 lines
2.9 KiB
Python
121 lines
2.9 KiB
Python
import random
|
|
|
|
|
|
class Individual_Interface(object):
|
|
'''
|
|
an Individual in genteic algorithm problem
|
|
|
|
the value (or genome) of an indal is a sequence (e.g string or list) of a fixed size
|
|
|
|
an individual has a fitness score
|
|
'''
|
|
|
|
|
|
def __init__(self, size):
|
|
'''
|
|
create an Individual object, its genome value is randomly built. Initially score is not set.
|
|
|
|
:param size: size of the genome
|
|
:type size: int
|
|
'''
|
|
self.__score = None
|
|
self.__size = size
|
|
self.__value = self.init_value()
|
|
|
|
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
|
|
'''
|
|
return None
|
|
|
|
def get_size(self):
|
|
'''
|
|
:return: the size of self's genome
|
|
:rtype: int
|
|
'''
|
|
|
|
return self.__size
|
|
|
|
def get_score(self):
|
|
'''
|
|
:return: the fitness score of self
|
|
:rtype: number
|
|
'''
|
|
return self.__score
|
|
|
|
def set_score(self, new_score):
|
|
'''
|
|
change the fitness score of self
|
|
|
|
:param new_score: the new fitness score
|
|
:type new_score: number
|
|
'''
|
|
self.__score = new_score
|
|
|
|
def __str__(self):
|
|
return "{} ({})".format(self.__value, self.__score)
|
|
|
|
def __repr__(self):
|
|
return self.__str__()
|
|
|
|
def get_value(self):
|
|
'''
|
|
:return: the genome of self
|
|
:rtype: sequence
|
|
'''
|
|
return self.__value
|
|
|
|
def set_value(self, new_value):
|
|
'''
|
|
change the genome value of self
|
|
|
|
:param new_score: the new genome value
|
|
:type new_score: sequence
|
|
'''
|
|
self.__value = new_value
|
|
|
|
def init_value(self):
|
|
'''
|
|
randomly initialize the genome value of self
|
|
'''
|
|
return None
|
|
|
|
def evaluate(self,problem):
|
|
'''
|
|
set the fitness score with the fitness computed by problem for self
|
|
|
|
:param problem: the problem
|
|
:type problem: a Problem object
|
|
'''
|
|
self.set_score(problem.evaluate_fitness(self))
|
|
|
|
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 croww with
|
|
:type other: an Idnividual object
|
|
:return: the two new Individuals built by 1 point crossover operation
|
|
:rtype: 2-uple of individuals
|
|
'''
|
|
pass
|
|
|
|
|
|
def mutate(self, probability):
|
|
'''
|
|
apply mutation operation to self : each element of the geome 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[
|
|
'''
|
|
pass
|
|
|
|
def mutate_gene(self, gene):
|
|
pass
|