def main():
    # Run 'breeding'
    pop = toolbox.population(n=300)
    hof = tools.HallOfFame(1)
    orig_stdout = sys.stdout
    f = open('ga_history.txt', 'w')
    sys.stdout = f
    print('stats')
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("avg", numpy.mean)
    stats.register("std", numpy.std)
    stats.register("min", numpy.min)
    stats.register("max", numpy.max)
    algorithms.eaSimple(pop, toolbox, 0.5, 0.2, 40, stats, halloffame=hof)
    expr = gp.genFull(pset, min_=1, max_=3)
    tree = gp.PrimitiveTree(expr)
    print('Tree')
    print(str(tree))
    # print 'Eligible moves: ', self.eligible_moves()
    #print('Pits: ', self.pits)
    #print('Board: ', self.board.textify_board())
    # print(pop, hof, stats)
    f.close()
    sys.stdout = orig_stdout
    # function = gp.compile(hof, pset)
    # print(function)
    print("done")
    # print(pop, hof, stats)
    return pop, hof, stats
def pruebaIndividuo():

    pset = configuraIndividuo()
    # Realiza una incialización completa con profundida entre 1 y 3
    expr = gp.genFull(pset, min_=1, max_=3)
    # Obtiene el arbol correspondiente
    tree = gp.PrimitiveTree(expr)
    # Se visualiza como una lista de operaciones
    print(tree)
Example #3
0
def txt_to_individual(file_path, pset):
    file = open(file_path, 'r')
    string = file.read()
    file.close()

    string.replace('div', 'pdiv')
    string.replace('sqrt', 'psqrt')
    string.replace('log', 'plog')
    expr = gp.genFull(pset, min_=1, max_=3)
    tree = gp.PrimitiveTree(expr)
    individual = tree.from_string(string, pset)
    return individual
def pruebaIndividuo():
    
    pset = configuraIndividuo()
    # Realiza una incialización completa con profundida entre 1 y 3
    # Performs a full initialisation with depth between 1 and 3
    expr = gp.genFull(pset, min_=1, max_=3) 
    # Obtiene el arbol correspondiente
    # Extracts the corresponding tree
    tree = gp.PrimitiveTree(expr)
    # Se visualiza como una lista de operaciones
    # Displayed as a list of operations
    print(tree)
Example #5
0
    def test_pickle_tree_input(self):
        pset = gp.PrimitiveSetTyped("MAIN", [int], int, "IN")
        pset.addPrimitive(operator.add, [int, int], int)

        expr = gp.genFull(pset, min_=1, max_=1)
        ind = creator.IndTree(expr)
        ind.fitness.values = (1.0,)
        ind_s = pickle.dumps(ind, pickle.HIGHEST_PROTOCOL)
        ind_l = pickle.loads(ind_s)
        msg =  "Unpickled individual %s != pickled individual %s" % (str(ind), str(ind_l))
        self.assertEqual(ind, ind_l, msg)
        msg =  "Unpickled fitness %s != pickled fitness %s" % (str(ind.fitness), str(ind_l.fitness))
        self.assertEqual(ind.fitness, ind_l.fitness, msg)
    def test_pickle_tree_input(self):
        pset = gp.PrimitiveSetTyped("MAIN", [int], int, "IN")
        pset.addPrimitive(operator.add, [int, int], int)

        expr = gp.genFull(pset, min_=1, max_=1)
        ind = creator.IndTree(expr)
        ind.fitness.values = (1.0,)
        ind_s = pickle.dumps(ind, pickle.HIGHEST_PROTOCOL)
        ind_l = pickle.loads(ind_s)
        msg = "Unpickled individual %s != pickled individual %s" % (str(ind), str(ind_l))
        self.assertEqual(ind, ind_l, msg)
        msg = "Unpickled fitness %s != pickled fitness %s" % (str(ind.fitness), str(ind_l.fitness))
        self.assertEqual(ind.fitness, ind_l.fitness, msg)
Example #7
0
from deap import base, creator, gp
import operator

pset = gp.PrimitiveSet("main", 3)
pset.addPrimitive(max, 2)
pset.addPrimitive(operator.add, 2)
pset.addPrimitive(operator.mul, 2)
pset.addTerminal(3)
pset.addPrimitive(operator.neg, 1)

pset.renameArguments(ARG0="x")
pset.renameArguments(ARG1="y")
pset.renameArguments(ARG2="z")

expr = gp.genFull(pset, min_=1, max_=3)
tree = gp.PrimitiveTree(expr)

print(tree)
def generate_offspring(toolbox, population, nchildren):
    offspring = []
    toolbox.max_raw_error = max([ind.fam.raw_error for ind in population])
    toolbox.debug_pp_str = ""
    toolbox.offspring_families_set = set()
    for index, _inds in toolbox.current_families_dict.items():
        toolbox.offspring_families_set.add(index)
    do_default_cx = True
    if population[0].fam.raw_error <= toolbox.near_solution_threshold:
        if not toolbox.in_near_solution_area:
            toolbox.in_near_solution_area = True
            for index, _inds in toolbox.current_families_dict.items():
                if toolbox.families_list[
                        index].raw_error <= toolbox.max_raw_error_for_family_db:
                    toolbox.near_solution_families_set.add(index)

            toolbox.parents_keep_fraction[
                toolbox.parachute_level] = 1.0  # 3.0 / 4.0
            toolbox.pop_size[
                toolbox.parachute_level] = toolbox.near_solution_pop_size
            toolbox.max_individual_size = toolbox.near_solution_max_individual_size
            if not toolbox.params["use_one_random_seed"]:
                random.seed(toolbox.params["seed2"])

            toolbox.cx_count = dict()
            toolbox.cx_child_count = dict()
            if False:
                toolbox.pp_str_to_family_index_dict = dict()
                toolbox.family_list = []
                toolbox.new_families_list = []
                new_dict = dict()
                for new_index, (_old_index, inds) in enumerate(
                        toolbox.current_families_dict.items()):
                    fam = inds[0].fam
                    toolbox.family_list.append(fam)
                    toolbox.new_families_list.append(fam)
                    fam.family_index = new_index
                    new_dict[new_index] = inds
                toolbox.current_families_dict = new_dict
        # toolbox.pcrossover = 0.3
        if False:
            do_default_cx = False
            n = len(toolbox.current_families_dict)
            toolbox.f.write(f"Start {n}x{n} search\n")
            offspring = search_for_solution(
                toolbox, population, round(nchildren * toolbox.pcrossover))
            toolbox.f.write(
                f"    {n}x{n} search found {len(offspring)} improvements\n")

    expr_mut = lambda pset, type_: gp.genFull(pset=pset,
                                              min_=toolbox.mut_min_height,
                                              max_=toolbox.mut_max_height,
                                              type_=type_)
    retry_count = 0
    prepare_combinations_families_with_cx_count_zero(toolbox, population)
    while len(offspring) < nchildren:
        op_choice = random.random()
        if op_choice < toolbox.pcrossover and do_default_cx:  # Apply crossover
            parent1, parent2 = select_parents(toolbox, population)
            if toolbox.parachute_level == 0:
                child, pp_str = cxOnePoint(toolbox, parent1, parent2)
            else:
                child, pp_str = crossover_with_local_search(
                    toolbox, parent1, parent2)
        else:  # Apply mutation
            parent = best_of_n(population, toolbox.best_of_n_mut)
            if toolbox.parachute_level == 0:
                child, pp_str = mutUniform(toolbox,
                                           parent,
                                           expr=expr_mut,
                                           pset=toolbox.pset)
            else:
                if toolbox.use_family_representatives_for_mutation:
                    family = random.choice(toolbox.families_list)
                    mutation = family.representative
                    raise RuntimeError(
                        f"DEBUG 228 : option use_family_representatives_for_mutation may not be used"
                    )  # can be removed when debugging is done
                else:
                    mutation = gp.genFull(pset=toolbox.pset,
                                          min_=toolbox.mut_min_height,
                                          max_=toolbox.mut_max_height)
                    mutation = gp.PrimitiveTree(mutation)
                    mutation.fam = None
                if toolbox.use_crossover_for_mutations:
                    child, pp_str = crossover_with_local_search(
                        toolbox, parent, mutation)
                else:
                    child, pp_str = replace_subtree_at_best_location(
                        toolbox, parent, mutation)
        if child is None:
            if retry_count < toolbox.child_creation_retries:
                retry_count += 1
                continue
            else:
                break
        retry_count = 0
        assert child.fam is not None
        toolbox.ind_str_set.add(pp_str)
        toolbox.offspring_families_set.add(child.fam.family_index)
        offspring.append(child)
    return offspring
    else:
        print(f'fail')
    print(result)
    return result,


toolbox.register("evaluate", eval)
toolbox.register("select", tools.selAutomaticEpsilonLexicase)
toolbox.register("mate", gp.cxOnePoint)
toolbox.register("expr_mut", gp.genFull, min_=0, max_=2)
toolbox.register("mutate", gp.mutUniform, expr=toolbox.expr_mut, pset=pset)

pop = toolbox.population(n=10)
hof = tools.HallOfFame(1)


# test out mod on x_train
p = gp.genFull(pset, min_=1, max_=2)
tree = PrimitiveTree(p)
print(tree)
funct = gp.compile(tree, pset)
t = funct
print(f't is {t}')
print(f'd.data[0] is {d.data[0]}')
print(f'mod_x = {d.data[0][funct]}')
mod_x = get_mod_x(d.data, funct)



pop, log = algorithms.eaSimple(pop, toolbox, cxpb=0.5, mutpb=0.1, ngen=4, halloffame=hof, verbose=True)