Esempio n. 1
0
def test_inv():
    ga = GA(3)

    doctest(ga._1.inv(), '1.0')
    doctest(ga.e1.inv(), 'e1')
    doctest(ga.e12.inv(), '-e12')  # rev(e12) / (e12|e12) == -e12 / -1
    doctest(ga.I.inv(), '-I')
Esempio n. 2
0
def search_with_vanguard(options):
    """maintains a list of extended_graphs. Each extended graph is mutated,
    and the best {shape[0]} mutants are kept. We maintain a tree structure of nested lists of graphs.
    This structure is called the 'vanguard,' the lowest-level lists are called 'platoons.'
    We 'retreat' the vanguard so that no more than {shape[1]} levels are present.
    This allows us to use a form of backtracking, which mitigates the loss of genetic diversity
    encountered when we mutate the vertices one-at-a-time.
    options = branch_factor, meta_pop, pop_per_mu, iterations_per_mu,
             elite_percent, crossover_percent, meta_elite_percent, make_unique,meta_select_proc
    """
    pop_size = options["meta_pop"]
    #independence_number =3
    #g = ExtendedGraph([(i,i+1) for i in range(4)] + [(4,0),(5,4),(5,2)])
    g = options["start_graph"]
    pop = [g]
    mutation_options = {
        "branch_factor": options["branch_factor"],
        "pop_per_mu": options["pop_per_mu"],
        "iterations_per_mu": options["iterations_per_mu"],
        "elite_percent": options["elite_percent"],
        "crossover_percent": options["crossover_percent"]
    }
    genetic_alg1 = GA(FUN.fit,
                      curry_add_vertex_and_mutate(mutation_options),
                      None,
                      0.0,
                      options["meta_elite_percent"],
                      pop_size=options["meta_pop"],
                      make_unique=options["make_unique"])
    #pop = [g]
    results = genetic_alg1.run(pop, 31, meta_select_proc=True)
    print([FUN.fit(r) for r in results])
    #return sorted(results, key=FUN.fit, reverse = True)[0]
    return results[0]
Esempio n. 3
0
    def find_tsp_solution(self, fitness_function, dist_function, pop_size, gen,
                          m_rate, elite):
        min_value = 1
        max_value = self.repository.num_nodes
        dim = self.repository.num_nodes + 1

        ga = GA(fitness_function, min_value, max_value, dim, pop_size, elite,
                m_rate)
        ga.initialisation()
        ga.evaluation()

        overall_best = ga.best_chromosome()
        progress = []
        for g in range(gen):
            best_chromosome = ga.best_chromosome()
            progress.append(dist_function(best_chromosome.repres))
            ga.next_generation_pool()
            best_chromosome = ga.best_chromosome()
            if best_chromosome.fitness > overall_best.fitness:
                overall_best = best_chromosome
            print('Best solution in generation ' + str(g) + ' is: x = ' +
                  str(best_chromosome.repres) + ' f(x) = ' +
                  str(best_chromosome.fitness))

        print[i + 1 for i in overall_best.repres]
        print dist_function(overall_best.repres)

        self.repository.write_network("data/graph_out.txt",
                                      overall_best.repres,
                                      dist_function(overall_best.repres))

        plt.plot(progress)
        plt.ylabel('Distance')
        plt.xlabel('Generation')
        plt.show()
Esempio n. 4
0
    def birdCheckCollision(bird):
        ''' Handles collision for the birds and updates game messages '''
        if (bird.x + bird.radius) > (self.pipes[0].x + 75) and self.pipes[0].z == 0:
            bird.score += 1

            # Handles the case in which a new high score is set
            if bird.score > self.highscore:
                self.bestBirdBrain = bird.brain
                self.foundBestBird = True
                self.highscore = bird.score
                self.pipes[0].z = 1
            
            # Handles wall or pipe collision by adding and removing birds from the lists
            if bird.collidingWall() or bird.collidingPipe():
                self.savedBirds.append(bird)
                self.birds.remove(bird)

                # Handles the death of the last bird
                if len(self.birds) == 0:
                    self.gameDisplay.blit(self.image, [0, 0])
                    self.pipes = []
                    self.counter = 0
                    ga = GA(self)
                    ga.nextGeneration()
                    self.generation += 1
                    self.gameLoop()
Esempio n. 5
0
def process(oil_data, freight_outward_data, freight_homeward_data,
            exchange_data, demand_data, supply_data, newbuilding_data,
            secondhand_data, actionlist):
    ga = GA(oil_data, freight_outward_data, freight_homeward_data,
            exchange_data, demand_data, supply_data, newbuilding_data,
            secondhand_data, actionlist)
    return ga.execute_GA()
def run_ga(n):
    ga = GA(n)
    ga.GA_main()
    result_programs = ga.memory_best_fit_program
    result_fits = ga.memory_best_fit
    json.dump(result_programs, open("result_programs", 'w'))
    json.dump(result_fits, open("result_fits", 'w'))
Esempio n. 7
0
def mutation_data():

    # Plot parameters
    data_source = "data/sequences/"
    gens = 450
    chromosomes = 250
    mutations = [
        0.01, 0.015, 0.02, 0.025, 0.03, 0.035, 0.04, 0.045, 0.05, 0.055, 0.06,
        0.065, 0.07, 0.075, 0.08, 0.085, 0.09, 0.095, 0.1
    ]

    # Create output file
    with open("data/output_data2.csv", 'w') as output_file:
        output_file.write("mutation, result\n")

    # Get files in the data source
    files = glob.glob(data_source + "*.txt")

    # Generate data
    for mutation in mutations:
        results = []
        print("Running for mutation rate = " + str(mutation))

        for file in files:
            with Utils.suppress_stdout():
                genetic_algorithm = GA(chromosomes, gens, gens, mutation)
                result = genetic_algorithm.run_ga(file)
                results.append(result)

        # Calc median
        median = np.median(results)

        # Write data to file
        with open("data/output_data2.csv", 'a') as output_file:
            output_file.write(str(mutation) + ", " + str(median) + "\n")
Esempio n. 8
0
def main():

    # Create the input parser
    parser = argparse.ArgumentParser(
        description="Mine pull requests from GitHub's open repositories.")

    parser.add_argument("-input", metavar='-i', type=str, help="Input path")
    parser.add_argument("-chromosomes",
                        metavar='-c',
                        type=int,
                        help="Number of chromosomes")
    parser.add_argument("-gens",
                        metavar='-gen',
                        type=int,
                        help="Number of generations")
    parser.add_argument("-min_gens",
                        metavar='-min',
                        type=int,
                        help="Minimum number of generations before stopping")
    parser.add_argument("-mutation_rate",
                        metavar='-mut',
                        type=float,
                        help="Mutation rate")

    # Parse args
    args = parser.parse_args()

    # Run the GA
    start = time.time()
    genetic_algorithm = GA(args.chromosomes, args.gens, args.min_gens,
                           args.mutation_rate)
    genetic_algorithm.run_ga(args.input)
    end = time.time()
    print("\nRunning time: " + str(end - start) + " seconds")
Esempio n. 9
0
def testIrisReplacement(trainfile, testfile, attrfile):
    iris_train = pd.read_csv(trainfile, header=None)
    iris_test = pd.read_csv(testfile, header=None)
    iris_attr = pd.read_csv(attrfile, header=None)
    input, output, input_test, output_test = digitalize(iris_train, iris_test, iris_attr,"iris")
    input = input.astype(np.float)
    input = np.concatenate((input, output), axis=1)
    test_input = np.concatenate((input_test, output_test), axis=1)
    replaceRate = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
    strategies = ['fitness-proportional', 'tournament', 'rank']
    cor_list = []
    strategy_list = []
    for j in range (len(strategies)):
        print ('Strategy: ' + strategies[j])
        for i10 in range(1, 10, 1):
            i = i10 / 10
            print('Replacement rate: ' + str(i))
            ga = GA(100, 6, 48, 3, i, 0.1, 1, 1, 30, strategies[j], 'iris') 
            cor, bestHypo = ga.fit(input)
            testAcc = ga.predict(bestHypo, test_input)
            print("Accuracy: " + str(testAcc) +"\n" )
            cor_list.append(testAcc)
        cor_array = np.array(cor_list)
        strategy_list.append(cor_array)
        cor_list = []
    print ('correct rate for fitness-proportional, tournament, rank strategy at vary replacement rate are')
    print (strategy_list)
Esempio n. 10
0
def main():
    graph = read_graph_from_file(input_file)

    gaParams = GAParams(populationSize=20, noOfGenerations=1000, crossoverProb=0.7, mutationProb=0.15)
    problemParams = ProblemParams(network=graph, dim=len(graph), function=calculate_route_length)

    ga = GA(gaParams, problemParams)
    ga.initialisation()
    ga.evaluation()

    allBestFitnesses = []
    generationsBest = []
    overallBest = Chromosome(problemParams)

    for generation in range(gaParams.noOfGenerations):
        ga.oneGenerationSteadyState()

        bestChromo = ga.bestChromosome()
        print('Best solution in generation ' + str(generation) + ' f(x) = ' + str(bestChromo.fitness))
        allBestFitnesses.append(bestChromo.fitness)
        generationsBest.append(bestChromo)
        if bestChromo.fitness < overallBest.fitness:
            overallBest = bestChromo

    print(overallBest.representation)
    print(calculate_route_length(overallBest.representation, problemParams.network))
Esempio n. 11
0
File: tsp.py Progetto: Seraphli/ga
def ga_p(city_list):
    cfg = GACfg(gene_len=25,
                gene_size=25,
                pop_size=1000,
                elite_size=50,
                tournament_num=50,
                tournament_size=100,
                mutation_rate=0.03,
                repeatable=False)
    ga = GA(fitness_func, cfg)
    ga.prepare_kwargs(city_list=city_list)
    ga.init_population()
    progress = []
    progress.append(1 / ga.cal_fitness()[0][1])
    for _ in range(100):
        early_stop = ga.evolve()
        progress.append(1 / ga.cal_fitness()[0][1])
        if early_stop:
            break

    print("Final distance: " + str(1 / ga.cal_fitness()[0][1]))
    plt.plot(progress)
    plt.ylabel('Distance')
    plt.xlabel('Generation')
    plt.show()
Esempio n. 12
0
def eval_ga(row, arguments, fit_val):
	start=time.time()

	args=arguments

	path_old = row[2]
	xpath_old = row[4]
	path_new = row[3]
	xpath_new = row[5]

	fit_val_temp=fit_val # *, tag, position, class, id
	ga = GA(
		pop_size=args.p,
		eval_lim=args.f,
		mut_rate=args.r,
		mut_k=args.k,
		crossover_rate=args.c,
		tournament_k=args.t,
		use_elitism=args.e,
		use_lin_ranking=args.l,
		dom_filepath=path_old.strip(),
		xpath=xpath_old,
		fitness_values=fit_val_temp,
		verbose=args.s
		)
	ga.select_parents()
	ga.evolve()

	xpath_robust = ga.optimum.xpath
	xpath_fitness = ga.optimum.fitness
	end=time.time()
	# print("{} seconds elapsed.".format(round(end-start,2)))
	return xpath_robust, xpath_fitness
Esempio n. 13
0
def test_run_ga():
    """Runs the genetic algorithm with various mutation and crossover functions to make
    sure that nothing errors out."""
    n = 10  # graph size
    pop_size = 100
    threshold = 0.130
    pop = [
        FUN.rand_graph(n, randint(n,
                                  n * (n - 1) / 2 + 1))
        for _ in range(pop_size)
    ]
    ga1 = GA(FUN.fit, FUN.mutate_add_then_remove_edges, FUN.cr6, 0.3, 0.2)
    results1 = ga1.run(pop, 20, threshold)
    ga2 = GA(FUN.fit_with_regularity, FUN.mu, FUN.cr7, 0.3, 0.2)
    results2 = ga2.run(pop, 20, threshold)
    ga3 = GA(FUN.fit, FUN.mutate_avoid_large_subgraph, FUN.cr5, 0.3, 0.2)
    results3 = ga3.run(pop, 20, threshold)
Esempio n. 14
0
def test_left():
    ga = GA(3)

    doctest(ga.e2 << ga.e12, '-e1')
    doctest(ga.e3 << ga.e12, '0.0')
    doctest(ga.e12 << ga.e1, '0.0')
    doctest(ga._1 << ga.e1, 'e1')
    doctest(ga.e1 << ga._1, '0.0')
Esempio n. 15
0
def test_has_symbols():
    ga = GA(2)
    assert hasattr(ga, '_0')
    assert hasattr(ga, '_1')
    assert hasattr(ga, 'e1')
    assert hasattr(ga, 'e2')
    assert hasattr(ga, 'e12')
    assert hasattr(ga, 'I')
Esempio n. 16
0
def test_bb_mul():
    ga = GA(3)

    doctest(ga.e1 * ga.e2, 'e12')
    doctest(ga.e1 * ga.e2 * ga.e3, 'I')
    doctest(ga.e2 * ga.e1, '-e12')
    doctest(2.0 * ga.e1, '2.0e1')
    doctest(ga.e12 * 2.0, '2.0e12')
Esempio n. 17
0
def exe():
    ga = GA()
    metrics = ga.get_metrics()

    slack = Slack(metrics)
    slack.post()

    return metrics
Esempio n. 18
0
def test_bb_add():
    ga = GA(3)

    doctest(ga._1 + ga.e1 + ga.e2, '1.0+e1+e2')
    doctest(ga.e1 + ga.e12, 'e1+e12')

    doctest(2.0 + ga.I, '2.0+I')
    doctest(ga.I + 2.0, '2.0+I')
Esempio n. 19
0
def test_symbol_values():
    ga = GA(2, [1., 1.])
    assert ga._0 == ga.MV([0.0, 0.0, 0.0, 0.0])
    assert ga._1 == ga.MV([1.0, 0.0, 0.0, 0.0])
    assert ga.e1 == ga.MV([0.0, 1.0, 0.0, 0.0])
    assert ga.e2 == ga.MV([0.0, 0.0, 1.0, 0.0])
    assert ga.I == ga.MV([0.0, 0.0, 0.0, 1.0])
    assert ga.e12 == ga.MV([0.0, 0.0, 0.0, 1.0])
Esempio n. 20
0
def test_itp():
    ga = GA(3)

    x = ga.MV([1., 2., 3., 4., 5., 6., 7., 8.])

    assert tuple(x.itp(-1)) == ()
    assert tuple(x.itp(0)) == (1.0, )
    assert tuple(x.itp(1)) == (2.0, 3.0, 4.0)
Esempio n. 21
0
def compare_methods(N):
    """
    Compare different optimization methods
    :param N: dimensionality of quantum system
    :return: a dictionary of results
    """
    # generate a random system
    sys = get_rand_unitary_sys(N)

    max_cost_func = sys["max_cost_func"]

    # we wrap the propagator to track how many calls each method makes
    propagator = sys["propagator"] = counted(sys["propagator"])

    # initialize the dictionary where results are stored
    results = dict(max_cost_func=max_cost_func, N=N)

    # ###################### Dynamical programming ######################
    results["dp_max"] = QStochDynProg(
        **sys).make_rounds(21).max_cost() / max_cost_func

    # save number of calls made during optimization
    results["dp_calls"] = propagator.calls

    # reset the count
    propagator.calls = 0

    ################ Hybrid monte-carlo tree seach and dynamical programming #############
    results["mcdp_max"] = MTCDynProg(nsteps=10, **sys).make_rounds(
        2**13).max_cost() / max_cost_func

    # save number of calls made during optimization
    results["mcdp_calls"] = propagator.calls

    # reset the count
    propagator.calls = 0

    ###################### Monte-Carlo tree search ######################
    results["mcts_max"] = MCTreeSearch(nsteps=2**10, **sys).make_rounds(
        2**13).max_cost() / max_cost_func

    # save number of calls made during optimization
    results["mcts_calls"] = propagator.calls

    # reset the count
    propagator.calls = 0

    ###################### Genetic algorithm ######################
    results["ga_max"] = GA(nsteps=2**11, pop_size=2**7, **sys).make_rounds(
        2**9).max_cost() / max_cost_func

    # save number of calls made during optimization
    results["ga_calls"] = propagator.calls

    # reset the count
    propagator.calls = 0

    return results
Esempio n. 22
0
 def select_dataset_file(self):
     try:
         filename = askopenfilename()
         self.td["text"] = filename
         self.dataset_path = filename
         self.ga = GA(dataset_path=filename)
     except Exception as e:
         print(e)
         self.td["text"] = ""
Esempio n. 23
0
def test_eq():
    ga = GA(2)

    assert ga._1 == ga._1
    assert ga.e1 == ga.e1
    assert ga.I == ga.I

    assert not (ga.e2 == ga.e1)
    assert not (ga.e1 == ga.e2)
Esempio n. 24
0
def create_ga_test(population_size=10):
    X, X_test, y, y_test, column_names = create_data()
    ga = GA(X=X,
            X_test=X_test,
            y=y,
            y_test=y_test,
            column_names=column_names,
            output_path='test')
    return ga
Esempio n. 25
0
def test_pproj():
    from ga import GA
    ga = GA(3, [1., 1., 1.])
    t = ga.vector(1., 0., 0.)
    eye = ga.vector(0., 0., 1.0)
    B = ga.e1 ^ ga.e2
    q = ga.vector(0., 0., 0.5)

    x = pproj(t, eye, B, q)
    assert x == ga.vector(0.5, 0.0, 0.5), str(x)
Esempio n. 26
0
def one_rule_example(actionlist):
    oil_data, freight_outward_data, freight_homeward_data, exchange_data, demand_data, supply_data, newbuilding_data, secondhand_data = load_generated_sinario(
        TRAIN_DATA_SET)
    ga = GA(oil_data, freight_outward_data, freight_homeward_data,
            exchange_data, demand_data, supply_data, newbuilding_data,
            secondhand_data, actionlist)
    p = []
    p.append(ga.execute_GA())
    print(p)
    export_rules_csv(p, 1)
Esempio n. 27
0
def test_rev():
    ga = GA(3)

    doctest(ga._1.rev(), '1.0')
    doctest(ga.e1.rev(), 'e1')

    doctest(ga.e12.rev(), '-e12')
    doctest(ga.e12.rev().rev(), 'e12')
    doctest(ga.I.rev(), '-I')
    doctest(ga.I.rev().rev(), 'I')
Esempio n. 28
0
def test_format():
    ga = GA(3)

    doctest(ga.MV([0., -0., 0., -0., 0., -0., 0., -0.]), '0.0')
    doctest(
        ga.MV([1., -1., 1., -1., 1., -1., 1., -1.]),
        '1.0-e1+e2-e3+e12-e13+e23-I',
    )
    doctest(ga.MV([2., -2., 2., -2., 2., -2., 2., -2.]),
            '2.0-2.0e1+2.0e2-2.0e3+2.0e12-2.0e13+2.0e23-2.0I')
Esempio n. 29
0
    def start_ga(self):
        """ Функция, запускающая оптимизацию с помощью генетического алгоритма """
        ga = GA()

        # Принимаем первым родителем тестируемый интерфейс, вторым - его мутированную версию
        other_parent = copy.deepcopy(self.garnet_blocks.optimized_tree)
        ga.mutation(other_parent, MUTATE_CHANCE)

        # Выполняем скрещивание выбранных родителей и получаем 3 новых варианта
        three_parents = ga.crossing_over(self.garnet_blocks.optimized_tree,
                                         other_parent)

        # Сохраняем изображения на диск, если требуется
        heatmap_number = 1
        if SAVE_HEATMAP:
            self.save_generation_heatmaps(three_parents, heatmap_number)
        heatmap_number += 1

        # Получаем 3 новых варианта дочерних деревьев из 3-х с помощью ГА
        new_parents = ga.evolution(
            three_parents, self.garnet_blocks.optimized_scale_x,
            self.garnet_blocks.optimized_scale_y,
            self.garnet_blocks.ui.optimizedView.width(),
            self.garnet_blocks.ui.optimizedView.height(),
            self.garnet_blocks.destination_heatmap, heatmap_number)
        if SAVE_HEATMAP:
            self.save_generation_heatmaps(new_parents, heatmap_number)
        heatmap_number += 1
        self.garnet_blocks.optimized_tree = new_parents[0]
        self.garnet_blocks.events.generation_completed.emit("ga")

        # Продолжаем эволюцию, пока не выполнится одно из условий окончиния:
        # 1. Превышено максимальное количество итераций
        # 2. Превышено максимальное количество итераций, в течение которых результат не улучшился
        # 3. Найден результат с допустимым значением фитнесс-функции
        while self.garnet_blocks.count_iterations < MAX_COUNT_ITERATIONS and \
                self.garnet_blocks.count_useless_iterations < MAX_COUNT_USELESS_ITERATIONS and \
                self.garnet_blocks.best_ff_value > MAX_FF_DIFFERENCE:
            # Получаем 3 новых варианта дочерних деревьев из 3-х с помощью ГА
            new_parents = ga.evolution(
                three_parents, self.garnet_blocks.optimized_scale_x,
                self.garnet_blocks.optimized_scale_y,
                self.garnet_blocks.ui.optimizedView.width(),
                self.garnet_blocks.ui.optimizedView.height(),
                self.garnet_blocks.destination_heatmap, heatmap_number)
            if SAVE_HEATMAP:
                self.save_generation_heatmaps(new_parents, heatmap_number)
            heatmap_number += 1
            self.garnet_blocks.optimized_tree = new_parents[0]
            self.garnet_blocks.events.generation_completed.emit("ga")

        # Показываем лучший из найденных
        self.garnet_blocks.optimized_tree = copy.deepcopy(
            self.garnet_blocks.best_tree)
        self.garnet_blocks.events.generation_completed.emit("ga")
Esempio n. 30
0
def test_part():
    ga = GA(3)

    x = ga.MV([1., 2., 3., 4., 5., 6., 7., 8.])

    doctest(x.part(-1), '0.0')
    doctest(x.part(0), '1.0')
    doctest(x.part(1), '2.0e1+3.0e2+4.0e3')
    doctest(x.part(2), '5.0e12+6.0e13+7.0e23')
    doctest(x.part(3), '8.0I')
    doctest(x.part(4), '0.0')