示例#1
0
文件: Population.py 项目: nahu/lgp
def tournament_with_mutation(competitors):
    choosen = competitors[0]
    
    for i in range(1, len(competitors)):
        if Individual.compare(choosen, competitors[i]) == -1:
            choosen = competitors[i]
        
    '''
    Se hacen copias temporales para reemplazar luego a los perdedores del torneo
    '''
    winner = choosen.clone()
    
    '''
    Se realizan la macro y micro mutación según probabilidades
    '''
    try:
        if Util.random_flip_coin(Parameters.p_macro_mutation):
            winner = macro_mutation(winner)
            Individual.check_destination_register(winner)
        if not check_out_register(winner):
            print "La macro mató"
    except:
        print "La macro matOOOó"
    
    try:
        if Util.random_flip_coin(Parameters.p_micro_mutation):
            winner = micro_mutation(winner)
            Individual.check_destination_register(winner)
           
        if not check_out_register(winner):
            print "La miiicro mató"
    except:
        print "La miiicro mató"
        
    return list([winner, choosen])
示例#2
0
 def evolve(self, goal):
     for child in self.individuals:
         parent1 = FC.getFittest(self.selectForBreeding(), goal, self.fitnessCalc)
         parent2 = FC.getFittest(self.selectForBreeding(), goal, self.fitnessCalc)
         if (parent1 is not parent2):
             Individual.breed2(parent1, parent2, child)
     self.mutate()
示例#3
0
    def run_family1(self):
        self.setup2()

        # 3.1 Test family #1

        family1 = FamilyTree()
        family1.set_family_name('The Incredibles')

        family1.add_individual(self.girl)
        family1.add_individual(self.boy)
        family1.add_individual(self.mom)
        family1.add_individual(self.dad)
        family1.add_individual(
            Individual(first='Jack-Jack',
                       last='Parr',
                       gender='male',
                       dob='2005-09-10'))

        self.boy2 = family1.individual('Jack-Jack')
        if self.boy2:  # this is false is boy2==tuple(), true if boy2 contains Individual objects
            self.boy2[0].add_parent(self.mom)
            self.boy2[0].add_parent(self.dad)

        print(family1)

        family1.tree_print()
    def initPopulation(self):
        """
        Creating random individuals in the population
        """

        for i in range(0, self.popSize):
            individual = Individual(self.genSize, self.data)
            individual.computeFitness()
            self.population.append(individual)
#            print("Parent{}:{}\nFitness:{}\n".format(i+1,individual.genes[:],individual.fitness))

        self.best = self.population[0].copy()
        for ind_i in self.population:
            if self.best.getFitness() > ind_i.getFitness():
                self.best = ind_i.copy()
        print("Best initial sol: ", self.best.getFitness())
    def apply(self, anEA):

        self.use_count += 1

        # Select the parents from the population
        parent1_index = parent2_index = anEA.selection_operator.select(
            anEA.current_solution_set)

        # Make sure parent 1 is different from parent2
        i = 0
        while parent2_index == parent1_index and i < 10:
            parent2_index = anEA.selection_operator.select(
                anEA.current_solution_set)
            i += 1

        # Perform the crossover
        child_gene = []

        for p1_gene, p2_gene in zip(
                anEA.current_solution_set[parent1_index].parameter_set,
                anEA.current_solution_set[parent2_index].parameter_set):

            alpha = self.system_random.uniform(0.0, 1.0)
            child_gene.append(alpha * p1_gene + (1.0 - alpha) * p2_gene)

        child = IND.Individual(
            anEA.current_solution_set[parent1_index].objective_function,
            child_gene)

        # Mutate the child
        if self.mutation_operator != None:
            self.mutation_operator.mutate(child)

        return child
    def initPopulation(self):
        """
        Creating random individuals in the population
        """
        for i in range(0, self.popSize):
            individual = Individual(
                self.genSize, self.data, self.choice
            )  # Passing choice as paramter to choose between Random/Heurostic
            individual.computeFitness()
            self.population.append(individual)

        self.best = self.population[0].copy()
        for ind_i in self.population:
            if self.best.getFitness() > ind_i.getFitness():
                self.best = ind_i.copy()
        print("Best initial sol: ", self.best.getFitness())
    def run_with_crossover(self, number_of_generation, mut_probs, mut_bp,
                           nbjobs):
        #tuple of all parallel python servers to connect with
        ppservers = ()
        job_server = pp.Server(nbjobs, ppservers=ppservers)

        tasks = range(nbjobs)
        result = numpy.array([Individual.Individual("", "", 0, 0)])
        #Parallel evolution for every lamda value
        print "Start running jog"
        jobs = [(task,
                 job_server.submit(self.EA_with_crossover, (
                     number_of_generation,
                     mut_probs,
                     task,
                     mut_bp,
                 ), (
                     self.fitness_proportion_selection,
                     self.mutateAll,
                     self.mutateOne,
                     self.crossover,
                 ), ("numpy", "Individual", "RNA", "random", "Logger",
                     "pandas", "os", "Initializer", "Landscape")))
                for task in tasks]

        for task, job in jobs:
            gen = job()
            result = numpy.insert(result, 0, numpy.array(gen)[:10])

        print "End of jobs"

        return result
    def initPopulation(self):
        """
        Creating random individuals in the population
        """
        for i in range(0, self.popSize):
            individual = Individual(self.genSize, self.data)
            individual.computeFitness()
            print("fitness>>",individual.fitness)
            print("chromosome>>",individual.genes)
            self.population.append(individual)

        self.best = self.population[0].copy()
        #print("best>", self.best.__dict__)
        for ind_i in self.population:
            if self.best.getFitness() > ind_i.getFitness():
                self.best = ind_i.copy()
示例#9
0
    def mutateOne(self, individual, mut_p, mut_bp):
        base_paire = ["AU", "UA", "GU", "GC", "UG", "CG"]
        nucluotides = ["A", "G", "U", "C"]

        RNA_seq = []
        for i in range(len(individual.RNA_seq)):
            r = random.uniform(0, 1)

            if r < mut_p[i]:
                selct = numpy.random.choice(nucluotides, size=1)
                RNA_seq.append(selct[0])
            else:
                RNA_seq.append(individual.RNA_seq[i])
        pos = individual.get_bp_position(self.initializer.target_structure)

        for bp_cord in pos:
            r = random.uniform(0, 1)
            if r < mut_bp:
                bp = numpy.random.choice(base_paire,
                                         1,
                                         p=[0.1, 0.2, 0.2, 0.2, 0.2, 0.1])
                RNA_seq[bp_cord[0]] = bp[0][0]
                RNA_seq[bp_cord[1]] = bp[0][1]

        (RNA_strc, mef) = RNA.fold(''.join(RNA_seq))
        return Individual.Individual(''.join(RNA_seq), RNA_strc,
                                     self.fitness(RNA_strc), mef)
示例#10
0
    def apply(self, anEA):

        self.use_count += 1;

        # Select the parents from the population
        parent1_index = parent2_index = anEA.selection_operator.select(anEA.current_solution_set)

        # Make sure parent 1 is different from parent2
        while parent2_index == parent1_index:
            parent2_index = anEA.selection_operator.select(anEA.current_solution_set);

        # Perform the crossover
        child_gene = [];

        for p1_gene, p2_gene in zip(anEA.current_solution_set[parent1_index].genes, anEA.current_solution_set[parent2_index].genes):

            alpha = self.system_random.uniform(0.0, 1.0);
            child_gene.append(alpha * p1_gene + (1.0 - alpha) * p2_gene);

        child = IND.Individual(
                len(child_gene),
                anEA.current_solution_set[parent1_index].boundary_set,
                anEA.current_solution_set[parent1_index].fitness_function,
                child_gene
        );

        # Mutate the child
        if self.mutation_operator != None:
            self.mutation_operator.mutate(child)

        return child;
 def __init__(self, populationSize):
     """
     Population constructor
     """
     self.population = []
     for i in range(populationSize):
         self.population.append(Individual())
示例#12
0
    def apply(self, anEA):

        self.use_count += 1

        # Return a new individual whose genes are randomly
        # generated using a uniform distribution
        return (IND.Individual(anEA.objective_function,
                               anEA.objective_function.initialRandomGuess()))
示例#13
0
def calc_obj_value(pop):
    obj_value = []
    for individual in pop:
        solution = IDV.individual_to_solution(individual)
        X = solution[0]
        Y = solution[1]
        obj_value.append(lsq.calc_area(Y, X))
    return obj_value
示例#14
0
文件: Population.py 项目: nahu/lgp
 def best_training(self):
     best = self.internal_pop[0]
     
     for i in range(1, self.pop_size):
         if (Individual.compare(self.internal_pop[i], best) == 1):
             best = self.internal_pop[i]
     
     return best
示例#15
0
def getIndividuals(population_size, log_file):

    population = []
    dataFrame = pandas.read_csv(log_file, sep=",")
    for ind in (dataFrame.values)[:population_size + 1, 1:]:
        population.append(Individual.Individual(ind[0], ind[1], ind[3],
                                                ind[2]))

    return population
    def apply(self, anEA):

        self.use_count += 1

        # Return a new individual whose genes are randomly
        # generated using a uniform distribution
        return (IND.Individual(anEA.objective_function.number_of_dimensions,
                               anEA.objective_function.boundary_set,
                               anEA.objective_function))
示例#17
0
def main():
    numberOfFolds = 10
    numberOfOutputRegisters = 2
    ArithmeticRegisterRatio = 0.5
    ps = 1000  # population size
    ips = 20  # initial population length
    op = ['add', 'sub', 'mul', 'div', 'if']  # avaliable operations
    ts = 1000  # tournament size
    ft = 'acc'  # fitness type
    pc = 0.5  #crossover probability
    pm = 0.2  #mutation probability
    ng = 6000  #number of generation
    dm = ['max', 'ave', 'min']

    # ---- Process ----

    df = pd.read_csv('spambase.csv')
    data_feature = df.iloc[:, :len(df.columns) - 1]
    data_label = df.iloc[:, len(df.columns) - 1]

    # ---- split train ----
    foldSize = int(len(data_label) / numberOfFolds)
    selector = [False] * foldSize
    selector = selector + [True] * (len(data_label) - foldSize)
    random.shuffle(selector)
    data_feature_test = data_feature[selector]
    data_label_test = data_label[selector]
    data_feature_train = data_feature[[not i for i in selector]]
    data_label_train = data_label[[not i for i in selector]]

    # ---- preperation ----
    r_out = ['R_O_' + str(i) for i in range(numberOfOutputRegisters)]
    r_fea = ['R_F_' + str(i) for i in range(len(data_feature.columns))]
    r_ari = [
        'R_A_' + str(i)
        for i in range(int(len(r_fea) * ArithmeticRegisterRatio))
    ]

    # ---- call algorithm ----
    opt_program = Algorithms.AlgTwoPointOne(PopulationSize=ps,
                                            InitialProgramLength=ips,
                                            Reg_output=r_out,
                                            Reg_arit=r_ari,
                                            Reg_feat=r_fea,
                                            operations=op,
                                            TournamentSize=ts,
                                            fitnessType=ft,
                                            numOfGenerations=ng,
                                            Prob_cross=pc,
                                            Prob_mutation=pm,
                                            dtf=data_feature_train,
                                            dtl=data_label_train,
                                            dvf=data_feature_test,
                                            dvl=data_label_test,
                                            resultDisplay=dm)
    print(id.printProgram(opt_program))
    def crossover(self, genotype1, genotype2, number_of_bit=1):
        vect1 = map(str, genotype1.RNA_seq)
        vect2 = map(str, genotype2.RNA_seq)

        r = numpy.random.randint(0, len(vect1))
        swap = vect1[:r]
        vect1[:r] = vect2[:r]
        vect2[:r] = swap

        (child1_structure, mef_child1) = RNA.fold(''.join(vect1))
        (child2_structure, mef_child2) = RNA.fold(''.join(vect2))
        child1 = Individual.Individual(
            ''.join(vect1), child1_structure,
            self.landscape.fitness(child1_structure), mef_child1)
        child2 = Individual.Individual(
            ''.join(vect2), child2_structure,
            self.landscape.fitness(child2_structure), mef_child2)

        return child1, child2
示例#19
0
 def initPop(self):
     for i in range(self.popSize):
         newInd = Individual.Individual(self.networkStructure, self.classification)
         newInd.setFitness(self.trainSet, self.trainClass)
         # find best fit
         if newInd.fitness > self.bestIndivdiualFitness:
             self.bestIndivdiual = copy.deepcopy(newInd)
             self.bestIndivdiualFitness = newInd.fitness
         # add individual to population
         self.population.append(newInd)
示例#20
0
    def setup_matrix_and_initialize_positions_of_individuals(self, matrix, free_space_size):
        self.matrix = matrix
        self.free_space_size = free_space_size
        self.individuals = []
        for _ in range(int(NUMBER_OF_INDIVIDUALS)):
            matrix = (copy.deepcopy(self.matrix))
            self.individuals.append(Individual.Individual(matrix, self.free_space_size))

        for individual in self.individuals:
            individual.initialize_cargo_list_with_random_positions(warehouse.CARGO_LIST)
 def generation_change(self, Bear_N, Kill_N):
     DNAs, parents_address = self.Bear(Bear_N)
     empty_address = self.Kill(Kill_N)
     born_space = self.manhattan_squeeze(parents_address, empty_address)
     Avg, Std = self.Get_Wealth_Statistics()
     self.Agent_List.extend([
         Individual.Individual(born_space[i], DNAs[i], Avg, Std)
         for i in range(Bear_N)
     ])
     """
 def Reset(self, name, mapside, Avg, Std):
     self.Name = name
     self.Size = mapside**2
     #self.ID_Map = [[x + x*y for x in range(mapside)] for y in range(mapside)]  # 看怎麼定義比較好,目前是用二維的,裡面放每個Individual的ID
     #self.Agent_List = [Individual.Individual(i, random.gauss(Avg, Std)) for i in range(self.Size)]  # 第n格表示ID為n的Individual
     self.Agent_List = [
         Individual.Individual([i // mapside, i % mapside],
                               random.gauss(Avg, Std))
         for i in range(self.Size)
     ]
示例#23
0
    def resetPopulation(self, aParameterSet):
        self.current_solution_set = [];

        for i in range(int(len(aParameterSet) / self.objective_function.number_of_dimensions)):
            gene_set = [];
            for j in range(self.objective_function.number_of_dimensions):
                gene_set.append(aParameterSet[i * self.objective_function.number_of_dimensions + j]);

            self.current_solution_set.append(IND.Individual(self.objective_function, gene_set));

        self.evaluateGlobalFitness(True);
示例#24
0
 def __init__(self, size, length):
     """
     count: the number of individuals in the population
     length: the number of values per individual
     vmin: the minimum possible value
     vmax: the maximum possible value
     """
     self.__size = size
     self.__pop = [
         Individual(Problem.generateIndividual(length)) for x in range(size)
     ]
示例#25
0
	def __init__(self):
		self.individuals = []
		for i in range(PopulationSize):
			self.individuals.append(Individual())
		self.tempIndividuals = []
		self.solitaryIndexList = list(range(PopulationSize))
		self.pairedIndexList = []
		self._nbOfSolitaryIndividuals = PopulationSize
		self._nbOfPairedIndividuals = 0
		self._nbOfEncounters = 0
		self._nbOfInteractions = 0
		self._rateOfAcceptation = 0
示例#26
0
    def initPopulation(self):
        """
        Creating random/heuristic individuals in the population
        self.initialSolution == 0 implies the initial population is generated using Random selection Approach
        self.initialSolution == 1 implies the initial population is generated using Heuristic Approach
        """

        for i in range(0, self.popSize):
            individual = Individual(self.genSize, self.data, self.initialSolution)
            individual.computeFitness()
            self.population.append(individual)

        self.best = self.population[0].copy()
        for ind_i in self.population:
            if self.best.getFitness() > ind_i.getFitness():
                self.best = ind_i.copy()
        print("Best initial sol: ", self.best.getFitness())

        # Writing the details into a file.
        file.write(f'Best initial sol: {self.best.getFitness()}')
        file.write('\n')
示例#27
0
    def initialize(self):
        """
        randomly generate NP individuals with value ranges xMin xMax
        """

        pop = list()
        for i in range(self.NP):
            pop.append(
                Individual(
                    np.random.rand(self.xMin.size) * (self.xMax - self.xMin) +
                    self.xMin, self.problem))
        if not all([Problem.validate(individual) for individual in pop]):
            raise ValueError("No valid initialization of population!")
        return pop
示例#28
0
def crossOver2(ref_strc, ind1, ind2, cross_prob):
    child1 = []
    child2 = []

    for i in range(len(ind1.RNA_seq)):
        child1.append(ind1.RNA_seq[i])
        child2.append(ind2.RNA_seq[i])

    if random.uniform(0, 1) < cross_prob:
        single_point = random.randint(1, len(ind1.RNA_seq) - 1)
        cross_part = child1[single_point:]
        child1[single_point:] = child2[single_point:]
        child2[single_point:] = cross_part

    (child1_strc, child1_mef) = RNA.fold(''.join(child1))
    (child2_strc, child2_mef) = RNA.fold(''.join(child2))

    new_ind1 = Individual(''.join(child1), child1_strc,
                          RNAEvolution.fitness(ref_strc, child1_strc))
    new_ind2 = Individual(''.join(child2), child2_strc,
                          RNAEvolution.fitness(ref_strc, child2_strc))

    return new_ind1, new_ind2
示例#29
0
    def introduce_new_individuals(self):
        for i in range(0, int(NUMBER_OF_INDIVIDUALS/2)):
            k = int(NUMBER_OF_INDIVIDUALS/2) + i
            self.individuals[k] = Individual.Individual(copy.copy(self.matrix), self.free_space_size)

            # znajdzmy matke i ojca dla osobnika
            father_index = random.randrange(0, 50, 1)
            mother_index = random.randrange(0, 50, 1)

            while father_index == mother_index:
                mother_index = random.randrange(0, 50, 1)

            self.cross_mother_and_father(self.individuals[father_index], self.individuals[mother_index],
                                         self.individuals[k])
            self.individuals[k].calculate_coverage()
        self.mutate()
示例#30
0
文件: Population.py 项目: nahu/lgp
 def best_validation(self):
     '''
     Se establece el atributo validation error de los individuos de la población
     '''
     for i in self.internal_pop:
         i.eval_validation()
         
     best = self.internal_pop[0]
     
     '''
     Se busca el de menor error
     '''
     for i in range(1, self.pop_size):
         if (Individual.compare_validation_error(self.internal_pop[i], best) == -1):
             best = self.internal_pop[i]
     
     return best
示例#31
0
    def mitosis(self, aMutationOperator, anUpdateIndividualLocalFitnessFlag):

        # Duplicate the population
        for i in range(self.getNumberOfIndividuals()):
            self.current_solution_set.append(aMutationOperator.mutate(IND.Individual(self.objective_function, self.current_solution_set[i].parameter_set)));

            self.number_created_children += 1;

        # Update the global and local fitness values
        if self.global_fitness_function != 0 and self.global_fitness_function != None:

            # Evaluate the global fitness
            self.evaluateGlobalFitness(anUpdateIndividualLocalFitnessFlag);

        # Store the best individual
        else:
            self.saveBestIndividual();
示例#32
0
    def __init__(self, limits, size, eliminate, mate, probmutate, vsize):
        'seeds the population'
        'limits is a tuple holding the lower and upper limits of the cofs'
        'size is the size of the seed population'
        self.populous = []
        self.eliminate = eliminate
        self.size = size
        self.mate = mate
        self.probmutate = probmutate
        self.fitness = []

        # Seeds = [np.linspace(a[0], a[1], a[2]) for a in limits]
        # for cofs in itertools.product(*Seeds):
        # self.populous.append(Individual.Individual(cofs))

        for i in range(size):
            SeedCofs = [random.uniform(a[0], a[1]) for a in limits]
            self.populous.append(Individual.Individual(SeedCofs))
示例#33
0
    def initPopulation(self):
        """
        Creating random individuals in the population
        """
        for i in range(0, self.popSize):
            individual = Individual(self.genSize, self.data, self.initialSolutionType)
            self.population.append(individual)

        """
        Setting the initial best solution to first individual in the population
        """
        self.best = self.population[0].copy()

        """
        converting the population to priority queue. First element has always the smallest fitness
        """
        heapq.heapify(self.population)

        print ("Best initial sol: ", self.best.getFitness())
示例#34
0
    def stochasticUniversalSampling(self, ind):
        """
        Your stochastic universal sampling Selection Implementation
        """
        self.selectedchildren = []
        individuals = []
        for i in range(0, len(ind)):
            individual = Individual(self.genSize, self.data)
            individual.setGene(ind[i])
            individual.computeFitness()
            individuals.append(individual)
            print("individuals>>>", individuals[i].fitness)
        #F is the sum of the fitness values of all chromosomes in the population
        F = 0

        # N is the number of parents to select
        N = self.popSize

        #P is the distance between successive points
        P = 0
        Pointers = []
        Ruler = []
        point = 0
        pickedpop = []

        fractionOfTotal = 0
        #calculate total fitness of the population
        for i in range(0,len(individuals)):
            F = F + individuals[i].fitness

        Ruler.append(fractionOfTotal)
        for i in range(0, len(individuals)):            
            fractionOfTotal = fractionOfTotal + individuals[i].fitness/F
            Ruler.append(fractionOfTotal)
        print("ruler", Ruler)              

        P = 1/N
        print("P___",P)

        point = random.uniform(0,P)


        for i in range(0, N):
            for j in range(0, len(Ruler)):
                if point >= Ruler[j] and point <= Ruler[j+1]:
                    self.selectedchildren.append(individuals[j].genes)
            point = point + P
            print("point>>>",point)
 
        print("picked pop>", self.selectedchildren)
示例#35
0
文件: Population.py 项目: nahu/lgp
def macro_mutation(genome):
    """Agrega o quita instrucciones  -- Alg. 6.1 -- p_ins > p_del """
    insertion = Util.random_flip_coin(Parameters.p_ins)
    mutation_point = random.randint(0, genome.height - 2)
        
    if genome.height < Parameters.num_max_instructions and \
    (insertion or genome.height == Parameters.num_min_instructions):
        ''' Si no supera la max. cant. de instrucciones y es insercion o 
        tiene el numero minimo de instrucciones'''
        new_instruction = Individual.create_new_instruction()
        reg_eff, to_mutate = genome.get_effective_registers(mutation_point)       
        while not reg_eff: 
            """
            se da en el caso de que el punto de mutación esté por debajo de la última
            instrucción efectiva y ésta sea unaria con un operando constante
            """
            #cambiar el registro constante del operador unario por uno variable
            genome.genomeList[to_mutate][3] = random.randint(Parameters.var_min, Parameters.var_max)
            reg_eff, to_mutate = genome.get_effective_registers(mutation_point)
        
        new_instruction[1] = random.choice(reg_eff)
        genome.genomeList.insert(mutation_point, new_instruction)
        genome.height += 1
        
        
    elif genome.height > Parameters.num_min_instructions and \
    (not insertion or genome.height == Parameters.num_max_instructions):
        ''' Si es mayor a la  min. cant. de instrucciones y  no es insercion o
            tiene el numero maximo de instrucciones'''
        del genome.genomeList[mutation_point]
        genome.height -= 1
            
    genome.set_altered()
    
    if genome.height > Parameters.num_max_instructions:
        print "superado el número maximo de instrucciones MACRO"
        print genome.height > Parameters.num_max_instructions
    return genome
示例#36
0
文件: Population.py 项目: nahu/lgp
def micro_mutation(genome):
    """
    Muta las instrucciones efectivas internamente
    p_regmut = probabilidad de mutar un registro 
    p_opermut = probabilidad de mutar una operación
    p_constmut = probabilidad de mutar una constante efectiva
    """
    
    eff, indices = genome.get_effective_instructions_with_indices()
    index = random.randint(0, len(indices) - 1)
    instruction = eff[index]
    mutation_point = indices[index]
    
    type = select_micro_mutacion_type(random.random())

    if (type == "constantes"):
        constants_indices = genome.get_effective_constant_indices()
        if constants_indices:
            ins_with_constant_index = random.choice(constants_indices)
            register_mutation_index = genome.genomeList[ins_with_constant_index][3]
            genome.r_all[register_mutation_index] += ((-1)**(random.randint(0, 1)) * random.uniform(0, Parameters.step_size_const))
            
        else: #no hay instrucciones efectivas con registros constantes variables
            type = select_micro_mutacion_type(random.random()) #si vuelve a salir constante, se elige mutación de registro o operaciones con igual probabilidad
            if (type == "constantes"):
                type = "registros" if Util.random_flip_coin(0.5) else "operaciones"
                
                
    if (type == "registros"):
        if len(eff) == 1: #una sola instrucción efectiva, no se puede cambiar r[0]
            if (instruction[0] < 5):
                pos_to_replace = random.randint(2, 3)
            else: #operación unaria, cambiar el segundo operando
                pos_to_replace = 3
        else:
            if (instruction[0] < 5):
                pos_to_replace = random.randint(1, 3)
            else: #operación unaria, cambiar el segundo operando o el destino
                pos_to_replace = 1 if Util.random_flip_coin(0.5) else 3
        
        if pos_to_replace == 1:
            #si no es el último índice, la última 
            if (index + 1) < len(indices):
                '''
                Se obtiene la lista de registros efectivos en esa posición, para reemplazar
                en la instrucción y permitir que siga siendo efectiva
                '''
                reg_eff, to_mutate = genome.get_effective_registers(indices[index + 1])
                
                if reg_eff:
                    reg_eff.remove(instruction[1]) #remover el registro destino de los registros efectivos
                    
                op, pos_to_replace = Individual.get_random_register(pos_to_replace, reg_eff, instruction)
            else: #el punto de mutación es la última instrucción con el r[0]
                if (instruction[0] < 5): 
                    pos_to_replace = random.randint(2, 3)
                else: #operación unaria, cambiar el segundo operando
                    pos_to_replace = 3
                    
                op, pos_to_replace = Individual.get_random_register(pos_to_replace)
        else: #para los casos de operandos 1 y 2
            op, pos_to_replace = Individual.get_random_register(pos_to_replace)
            
        instruction[pos_to_replace] = op
            
        genome.genomeList[mutation_point] = instruction
        
    if (type == "operaciones"):
        diff_op = random.randint(Parameters.op_min, Parameters.op_max)
        
        while instruction[0] == diff_op:
            diff_op = random.randint(Parameters.op_min, Parameters.op_max)
            
        instruction[0] = diff_op
        
        genome.genomeList[mutation_point] = instruction
    
    genome.set_altered()
    return genome
示例#37
0
文件: LgpMain.py 项目: nahu/lgp
def deme_evolve(population):
    """Se reinician los indices, para hacer coincidir cada individuo.index con su posicion en internal_pop"""
    population = resetIndex(population)
    for gen in range(Parameters.gen_to_migrate):
        to_tournament = []
        """Se seleccionan pool_size*2 diferentes posiciones en la poblacion para el torneo"""
        selected_indices = population.indices_selection(Parameters.pool_size * 2)

        to_tournament_indices = []
        to_tournament_indices.append(selected_indices[: Parameters.pool_size])
        to_tournament_indices.append(selected_indices[Parameters.pool_size :])
        to_tournament.append(population.selection_from_indices(to_tournament_indices[0]))
        to_tournament.append(population.selection_from_indices(to_tournament_indices[1]))

        # iter_result = population.pool.imap(Population.tournament_with_mutation, to_tournament, Parameters.chunk_size)
        winners = []
        """ ********************************* MUTACION  *********************************"""
        for i in range(2):
            """ Se retorna una lista de la siguiente forma: [modificado, no_modificado] """
            result = Population.tournament_with_mutation(to_tournament[i])
            winners.append(result)
            # winners.append(iter_result.next())

        """ ********************************* CROSSOVER *********************************"""
        if Util.random_flip_coin(Parameters.p_crossover):
            sister, brother = Population.crossover(winners[0][0], winners[1][0])
            Individual.check_destination_register(sister)
            Individual.check_destination_register(brother)

            if not sister.index == winners[0][0].index:
                winners[0][0] = brother
                winners[1][0] = sister

            if not Population.check_out_register(winners[0][0]) or not Population.check_out_register(winners[1][0]):
                print "ERROR: [LgpMain.deme_evolve]: El crossover dejo individuos sin registros de salida."

        for i in range(2):
            """ Se elimina de la lista de participantes del torneo al ganador, para remplazar a los perdedores"""
            try:
                del to_tournament_indices[i][to_tournament[i].index(winners[i][1])]
            except:
                print "ERROR: [LgpMain.deme_evolve]: Error al eliminar el indice del ganador del torneo " + str(i)

            """ best_replace = index_of_best([modificado, no_modificado])"""
            best_replace = 0 if Individual.compare(winners[i][0], winners[i][1]) == 1 else 1
            worst_replace = 1 if best_replace == 0 else 0

            """ Se remplaza los perdedores por el mejor entre (ganador modificado, ganador NO modificado)
            y se actualizan los indices dentro de la población """
            for l in to_tournament_indices[i]:
                indice = population.internal_pop[l].index
                population.internal_pop[l] = winners[i][best_replace].clone()
                population.internal_pop[l].index = indice
            """
            Como ya se remplazo a los perdedores por el mejor, se remplaza al ganador por el peor. Hay mas copias del mejor.
            """
            population.internal_pop[winners[i][0].index] = (
                winners[i][worst_replace].clone().set_index(winners[i][0].index)
            )

    """Se ordena la población de mayor a menor, según el error promedio o la desviación típica
    según una cierta probabilidad"""
    if Util.random_flip_coin(Parameters.p_migration_criteria):
        (population.internal_pop).sort(cmp=Individual.compare_error_prom, reverse=True)
    else:
        (population.internal_pop).sort(cmp=Individual.compare_deviation_in_error, reverse=True)

    for i in population.internal_pop:
        if not i.evaluated:
            print "ERROR: METODO DE ORDENACION FALLO."

    return population