def main(): warnings.simplefilter('ignore') ga = GA(gaParam, problParam) ga.initialisation() ga.evaluation() inProgress = True g = -1 while (inProgress and g < gaParam['noGen']): g += 1 ga.oneGeneration() bestChromosome = ga.bestChromosome() data = getData(bestChromosome.repres) print('------------------------------------------') print('Generation ' + str(g) + '\nFitness: ' + str(bestChromosome.fitness) + ' ' + '\nNo of comunities:' + str(len(data))) A = np.matrix(net["mat"]) G = nx.from_numpy_matrix(A) pos = nx.spring_layout(G) plt.figure(figsize=(8, 8)) nx.draw_networkx_nodes(G, pos, node_size=200, cmap=plt.cm.RdYlBu, node_color=ga.population[0].repres) nx.draw_networkx_edges(G, pos, alpha=0.3) plt.show()
def ejercicio_2(): print("~ Ejercicio 2") genome_size = 30 codification = [(0, 1)] * genome_size g_a = GA(codification, pop_size=100, mtn_prob=0.01, rmb_prob=0.7) p_0 = g_a.initial_population() simulaciones = 20 stats_e2(simulaciones, g_a, p_0)
def do_int_run(pop_size=100, chrom_len=10, co_rate=0.6, mut_rate=0.01, num_gens=5000, fit_thresh=1000000, fit_fun=None): population = Population(0) for i in range(pop_size): population.add_chromosome(make_random_int_chromosome(fit_fun, chrom_len)) myga = GA(population, num_gens, co_rate, mut_rate, fit_thresh, make_random_int_chromosome) return myga.evolve()
def __init__(self): pop = self.create_population() self.GA = GA.GA(pop, self.end_condition, self.fitness, crossover_probability=0.3, mutation_probability=0.2) self.last_max_val = None
def main(): print("HP model training using Genetic Algorithms\nRun commencing...\n...") # parameters, remember to set these!! population_size = 500 monomer_length = 150 number_h = 75 generations = 3000 iterations = 1 start = time.time() algo = GA(population_size, monomer_length, number_h) best_conformation = algo.run(generations) print(best_conformation.get_representation()) print(best_conformation.get_fitness()) for iteration in range(1, iterations): algo = GA(population_size, monomer_length, number_h) # run the algorithm and return the best monomer which is then written to file current_conformation = algo.run(generations) print(current_conformation.get_representation()) print(current_conformation.get_fitness()) if best_conformation.get_fitness() > current_conformation.get_fitness( ): best_conformation = current_conformation end = time.time() time_elapsed = end - start print("Time elapsed for " + str(iterations) + " runs/trials with " + str(generations) + ": " + str(time_elapsed)) f = open('HPMoleculeResult.txt', 'w') f.write('Molecule Direction\n') molecule = best_conformation.get_molecule() best_conformation = best_conformation.get_representation() for i in range(monomer_length): if i == 0: f.write(molecule[0] + '\n') elif i < monomer_length - 1: f.write(molecule[i] + '\t' + best_conformation[i] + '\n') else: f.write(molecule[i] + '\t' + best_conformation[i]) f.close()
def initGA(): print 'Starting genetic sequence' ga = GA() # strating the random population objType = 'cube' ga.createRandomPopulation(10) for i in range(0, len(ga.Population)): createNewObject(objType) translate3d_t(pointer3d, (4, 0, 0)) obj = _object_sequence_[len(_object_sequence_) - 1] ga.Population[i].objectId = obj[0] return ga
def main(): net = {} net = Repository.loadHard("hardE.txt") #net = Repository.loadData("mediumF.txt") # print(net['mat']) dim = net['noCit'] # print(dim) matrix = net['mat'] # totalCost =0; # cr=[1,2,4,3] # mat = [[0, 6, 12, 10], [6, 0, 8, 4], [12, 8, 0, 15], [10, 4, 15, 0]] # for i in range(0, len(mat)-1): # # print(matrix[c.repres[i]][c.repres[i+1]]) # totalCost += matrix[cr[i] - 1][cr[i+1] - 1] # totalCost += matrix[cr[-1] - 1][cr[0] - 1] # print(totalCost) problParams = {'noNodes': dim, 'mat': matrix, 'function': getDistance} gaParams = {'popSize': 100, 'noGen': 250} # representation = [1 for _ in range(0, dim*dim)] # for i in range(1, dim*dim): # number = 0 # number = randint(2, dim*dim) # if number not in representation: # representation[i] = number # elif number in representation: # while number in representation: # number = randint(2,dim*dim) # representation[i] = number # print(representation) ga = GA(problParams, gaParams) ga.initialisation() ga.evaluation() for generation in range(gaParams['noGen']): #ga.oneGenerationElitism() ga.oneGenerationSteadyState() bestChromo = ga.bestChromosome() print('Cel mai bun crom din generatia ' + str(generation + 1) + ' : x = ' + str(bestChromo.repres) + ' cu distanta = ' + str(bestChromo.fitness)) print( "--------------------------------------------------------------------------------------" ) bestChromo = ga.bestChromosome() print("\n\n") print('Cel mai bun crom : x = ' + str(bestChromo.repres) + ' cu distanta = ' + str(bestChromo.fitness))
def ejercicio_3(): print("~ Ejericio 3A") genome_size = 10 codification = [(0, 1)] * genome_size pop_size = 30 max_its = 100 g_a = GA(codification, pop_size=pop_size, mtn_prob=0.01, rmb_prob=0.7) p_0 = g_a.initial_population() (f_best, best) = g_a.evolve(p_0, max_its=max_its, cost_fun=fitness_fun) print("Best: %s" % best) ejercicio_3B(g_a, max_its, pop_size) ejercicio_3C(g_a)
def lets_go(self): Plan.grid = self.plan Plan.groups = self.groups Plan.constraints = self.constraints print("GA STARTS!\n" + "NB_GENERATION = " + str(self.NB_GENERATION) + " - " + "NB_PLANS = " + str(self.NB_PLANS) + " - " + "PROB_MUTATIONS = " + str(self.PROB_MUTATIONS) + " - " + "NB_REPRODUCTION = " + str(self.NB_REPRODUCTION)) time_start = time.time() # INIT list_plans = [] ' on crée des plans random, on calcule les scores ' for i in range(self.NB_PLANS): plan = Plan() plan.gen_random() plan.calculate_score() list_plans.append(plan) ga = GA(list_plans, self.NB_REPRODUCTION, self.PROB_MUTATIONS) best_score = -1 best_at = 0 total = 0 for i in range(self.NB_GENERATION): ga.reproduce() ga.keep_only(self.NB_PLANS) ga.mutate() ga.sort_plans() current_score = ga.list_plans[0].score total += 1 if current_score > best_score: best_score = current_score best_at = total ga.sort_plans() if self.conn is not None: self.conn.send(str.encode(str(ga.list_plans[0]))) time_end = time.time() best_plan = ga.list_plans[0] # print(best_plan) # print("[SCORE: " + str(best_plan.score) + "]") # print("EXECUTED IN " + str(round(time_end - time_start, 3)) + " seconds") return best_plan, round(time_end - time_start, 3), best_at, total
def selector(algo, func_details, popSize, Iterasyon): function_name = func_details[0] lb = func_details[1] ub = func_details[2] dim = func_details[3] x = hho.HHO(getattr(functions, function_name), lb, ub, dim, popSize, Iterasyon) # Algoritma listesi if (algo == 0): x = hho.HHO(getattr(functions, function_name), lb, ub, dim, popSize, Iterasyon) if (algo == 1): x = ga.GA(getattr(functions, function_name), lb, ub, dim, popSize, Iterasyon) return x
def main(self): ############ generate model from data ################## data = earthquakedata.dataremodel() path = 'data.dat' ######## map setting ####### data.longitudemax = 145 data.longitudemin = 140 data.latitudemax = 35 data.latitudemin = 30 data.Interval = 0.5 data.datareader(path) ######## setting end ###### data.selectyear = 2010 data.selectmonths = 1 data.selectmonthe = 12 data.setnum() data.findhappentimes() #data.setmodel() best = -100000 GAf = GA.GA() for i in range(0, 200 * 200): rf = randommodel.generatemodel(self.latitudenum, self.longitudebinnum) intPopulation = np.zeros((data.latitudenum, data.longitudebinnum), float) intPopulation = randommodel.intergermodel(rf, self.latitudenum, self.longitudebinnum) score = GAf.Evalate(intPopulation, data) if score > best: best = score print "R best = ", best return best
def greedySolve(system): g = ga.GA(system) chromosome = {} chromosome['vmmsMatrix'] = [] chromosome['vminstances'] = [] vm, microserviceList = getNewVm(system, None, chromosome, g, 1) chromosome['vmmsMatrix'].append(microserviceList) chromosome['vminstances'].append(vm) #hemos creado una primera vm con ningun ms asignado #creamos una instancia de cada uno de los ms for msId in range(0, system.numberMicroServices): allocateMs(system, msId, chromosome, g, 1) #creamos aleatoriamente una instancia de cada uno de los ms y también aleatorio si es store o running, y así hasta que empeoremos el fitness vmLoads = g.calculateVmsWorkload(chromosome) fitness = normalizationMia( g.calculateCost(chromosome, vmLoads)) + normalizationMia( g.calculateMttr(chromosome)) + normalizationMia( g.calculateLatency(chromosome)) newfitness = fitness tempchromosome = chromosome for i in range(0, 1000): msId = random.randint(0, system.numberMicroServices - 1) tempchromosome = copy.deepcopy(tempchromosome) msState = random.randint(0, 1) allocateMs(system, msId, tempchromosome, g, msState) vmLoads = g.calculateVmsWorkload(tempchromosome) newfitness = normalizationMia(g.calculateCost( tempchromosome, vmLoads)) + normalizationMia( g.calculateMttr(tempchromosome)) + normalizationMia( g.calculateLatency(tempchromosome)) if newfitness <= fitness: print "improved to " + str(newfitness) tempchromosome fitness = newfitness chromosome = tempchromosome return chromosome
def funGA_single(fp_tuple_combOfInsRuns): local_state = np.random.RandomState() print("Begin: ins ") print("Running......") cpuStart = time.process_time() # 调用GA求解 GeneticAlgo = GA.GA(listGAParameters, fp_tuple_combOfInsRuns[0], local_state) finalPop, listGenNum, listfBestIndFitness = GeneticAlgo.funGA_main() cpuEnd = time.process_time() cpuTime = cpuEnd - cpuStart print("End") # 记录最终种群中最好个体的fitness和目标函数值,累加 if listfBestIndFitness[-1] != 1/finalPop[0]['objectValue']: print("Wrong. Please check GA.") # 为绘图准备 new_listfBestIndFitness = [fitness * 1000 for fitness in listfBestIndFitness] return cpuTime, listfBestIndFitness[-1], finalPop[0]['objectValue'], new_listfBestIndFitness
def run(network, populationSize, gen): fcEval = routeFitness gaParam = {'popSize': populationSize, 'noGen': gen} problParam = {'function': fcEval, 'network': network} ga = GA(gaParam, problParam) ga.initialisation() ga.evaluation() bestChromo = None for g in range(gaParam['noGen']): #ga.oneGeneration() ga.oneGenerationElitism() #ga.oneGenerationSteadyState() bestChromo = ga.bestChromosome() print('Best solution in generation ' + str(g + 1) + ' is: x = ' + str(bestChromo.repres) + ' f(x) = ' + str(bestChromo.fitness)) print("Solution is: ", bestChromo)