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()
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)
def main(): pop_size, gen_count, mutation = 10, 30, 0.4 #solve_methods = ["keras", "svm", "logistic", "naivebayes", \ # "randomforest", "lda"] solve_methods = ["keras"] accuracy_fname = "accuracy_keras.txt" with open(accuracy_fname, "w") as fp: for dataset in loadData(): fp.write("===================================\n") fp.write("Filename: %s\n" % dataset['fname']) Organism.data = dataset Organism.count = dataset['X'].shape[1] fp.write("Num Features: %d\n" % Organism.count) fp.write("\n------------------------------------\n") for solve_method in solve_methods: print "Using solve method: ", solve_method fp.write("Using solve method: %s\n" % solve_method) full_accuracy = GA.full_accuracy(solve_method) print "Accuracy using all features: ", full_accuracy.fitness fp.write("Accuracy using all features: %f\n" % full_accuracy.fitness) solver = GA(gen_count, pop_size, mutation, solve_method) finalPop = solver.search() print "Best Accuracy: ", finalPop[0].fitness print "Subset of features used: ", finalPop[0].feature_subset fp.write("Pop Size: %d; Generation Count: %d; Mutation Rate: %f\n" % (pop_size, gen_count, mutation)) fp.write("Best Accuracy: %f\n" % finalPop[0].fitness) fp.write("Subset of features used: " + str(finalPop[0].feature_subset)) fp.write("\n------------------------------------\n\n")
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")
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()
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]
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")
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 consoleGA(self): ''' Run non-interactive GA. ''' from ga import GA ga = GA(self.params) ga.run()
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'))
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)
def exe(): ga = GA() metrics = ga.get_metrics() slack = Slack(metrics) slack.post() return metrics
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)
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')
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)
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))
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')
def main_test(): chromosome_size = 24 population_size = 4 constraint = 5000 prop_crossover = 0.9 prob_mutation = 0.01 max_generations = 3 solver = GA(chromosome_size,population_size,constraint,prop_crossover,prob_mutation,max_generations) chromosome = np.random.choice([0,1],(chromosome_size,population_size)) print(solver.calculate_fitness())
def test_sortbydist(): ga = GA(3) p1 = [ga.e3 * 1.0] p2 = [ga.e3 * 2.0] rs = ex.sortbydist(ga, [p1, p2], B = ga.e12, q = ga.vector(), ) assert rs == [p2, p1], str(rs)
def test_pproj(): from random import random 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) for _ in range(100): t = ga.vector(random()*100.0, random()*100.0, (random()-1.0)*100.0) x = pproj(t, eye, B, q) assert x._mv[3] - 0.5 < 0.0000000000001, (str(x), x._mv[3])
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')
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')
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')
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')
def __init__(self): self.Training_Done = 0 self.Trading_Required = 0 self.System_Date = datetime(2011, 1, 1, 00, 00) self.popSize = 10 self.i = 0 self.cash_bal = 10000000 self.asset_bal = 0 self.TradingInfo = pd.DataFrame() #to hold back testing results self.BackTestingInfo = pd.DataFrame() #to hold back testing results self.train_dict = None self.test_dict = None self.FCPO = None self.j = 0 self.initMarketRates() self.ga = GA() print("in init")
def main(argv): args = parse_args() if (args.pop_size % 2 != 0): print("Error: Population size needs to be an even number.") exit() if not os.path.exists(args.folder): os.mkdir(args.folder) #seed = random.randint(0, 16384) random.seed(args.seed) device = 'cuda' if torch.cuda.is_available() else 'cpu' print(device) ga = GA(args.timelimit, args.pop_size, device) ga.run(args.generations, args.folder, args.ga_id, args.ga_init_solution_id)
def extend_search(mutation_options): """Picks one graph from the metapopulation and runs the G.A. for it.""" level, values = choose_level(mutation_options["start_graph"]) #values = eval(get_graphs_from_redis(level, mutation_options["start_graph"])) #print("got graphs") values.sort(key=lambda x: x[2]) values[0][2] += 20 set_graphs_to_redis(values) genetic_alg1 = GA(FUN.fit, curry_add_vertex_and_mutate(mutation_options), None, 0.0, mutation_options["meta_elite_percent"], pop_size=mutation_options["meta_pop"], make_unique=mutation_options["make_unique"]) pop = [values[0][0]] genetic_alg1.run(pop, 2, meta_select_proc=True)
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')
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
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
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)
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"] = ""
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')
def train_ga(self): if self.mode == '4D': J = 6 input_dim = 3 else: J = 8 input_dim = 5 iteration_times = int(self.it.get()) populations_size = int(self.ps.get()) mutation_prob = int(self.mp.get()) / 100 crossover_prob = int(self.cp.get()) / 100 print(iteration_times, populations_size, mutation_prob, crossover_prob) self.GA = GA(iteration_times=iteration_times, populations_size=populations_size, mutation_prob=mutation_prob, crossover_prob=crossover_prob, J=J, input_dim=input_dim, dataset_path=self.dataset_path) self.GA.train()
def runGA(): myWorld = World([ [0, 0, 0, 0, 1, 0, 1, 3, 1], [1, 0, 1, 1, 1, 0, 2, 3, 1], [1, 0, 0, 1, 3, 3, 3, 3, 1], [3, 3, 3, 1, 3, 1, 1, 0, 1], [3, 1, 3, 3, 3, 1, 1, 0, 0], [3, 3, 1, 1, 1, 1, 0, 1, 1], [1, 3, 0, 1, 3, 3, 3, 3, 3], [0, 3, 1, 1, 3, 1, 0, 1, 3], [1, 3, 3, 3, 3, 1, 1, 1, 4], ]) ga = GA(20, 0.05, 0.9, 2, 10) population = ga.initPopulation(128) ga.evalPopulation(population, myWorld) # Keep track of current generation generation = 1 while ga.isTerminationConditionMet(generation, maxGenerations) == False: # Print fittest individual from population fittest = population.getFittest(0) print("G" + str(generation) + " Best solution (" + str(fittest.getFitness()) + "): " + fittest.toString()) # Apply crossover population = ga.crossoverPopulation(population) # Apply mutation population = ga.mutatePopulation(population) # Evaluate population ga.evalPopulation(population, myWorld) # Increment the current generation generation += 1 print("Stopped after " + str(maxGenerations) + " generations.") fittest = population.getFittest(0) print("Best solution (" + str(fittest.getFitness()) + "): " + fittest.toString())
class Model(object): def __init__(self): self.ga = GA(3, [1.0, 1.0, 1.0]) #self.circ = circle(self.ga, 1.5, 20, 1.0, 2) self.circ = circle(self.ga, 1.5, 20) def update(self, dt): R = self.ga.rotor(self.ga.e13, pi/210.0) R = R * 0.999 Rr = R.rev() self.circ = [R*p*Rr for p in self.circ[0]], self.circ[1] def __iter__(self): yield self.circ
def random_blade(n=3): x = GA(n).scalar(0) i = random.randint(0, 2**n - 1) x._data[i] = 1.0 return x
def test_rotor(): ga = GA(3) doctest(ga.rotor(), '1.0') doctest(ga.rotor(ga.e1^ga.e2, 0.0), '1.0')
def test_zero(): ga = GA(0) assert ga.zero() == ga.MV([0.0])
def test_one(): ga = GA(0) assert ga.one() == ga.MV([1.0])
from ga import GA import random arr = [[(-1 if random.randint(0, 1) == 0 else 1) for i in range(30)] for i in range(100)] data = [] for row in arr : decision = -1 if random.randint(0, 1) == 0 else 1 row[0] = decision data.append( (True if decision==1 else False, row) ) print(data) ###### host = GA(data=data, poolSize=10) best = host.evolve(stableFactor=100, breedRate=0.3, mutateRate=0.2, mutationDegree=0.05, mutationComplexity=0.3) print(best)
def __init__(self): self.ga = GA(3, [1.0, 1.0, 1.0]) #self.circ = circle(self.ga, 1.5, 20, 1.0, 2) self.circ = circle(self.ga, 1.5, 20)
#!/usr/bin/env python3 import sys sys.path.append('./py') from tests.test import * from tests.random import * from ga import GA from multivector import MultiVector ga = GA(3) assert ga.n == 3 x = 4 + 3*ga[1] + 4*ga[2] + 5*ga[1,2] y = 3 + 2*ga[1] + 3*ga[2] + 4*ga[1,2] z = 10 + 16*ga[1] + 26*ga[2] + 32*ga[1,2] assert x*y == z ga2 = GA(2) xx =ga2.coerce_multivector(x) assert x != xx assert xx == ga2.scalar(4) + ga2.blade(3, 1) + ga2.blade(4, 2) + ga2.blade(5, 1, 2) e1 = ga[1] e2 = ga[2] e3 = ga[3] assert e1.cross_product(e2) == e3 assert e2.cross_product(e3) == e1
def __init__(self, f, **args): GA.__init__(self, f, **args) self.initLinkageMatrix() self.averageFitness = 0 self.parentFitnesses = None