#Импортим генетический алгоритм from pyeasyga.pyeasyga import GeneticAlgorithm import random import numpy as np #Представление данных #Данные представляют из себя множество нулей с одной единицей на какой-либо позиции #Это позиция отражает положение x на оси абсцисс от -4 до 0 seed_data = [0] * 399 seed_data.append(1) #Иницилизируем генетический алгоритм с заданными данными, а также размером #популяции, количеством поколений, шансом на кроссинговер и мутацию ga = GeneticAlgorithm(seed_data, 400, 200, 0.7, 0.05, True, True) #Представляем отдельную особь как случайное положение х def create_individual(data): individual = data[:] random.shuffle(individual) return individual ga.create_individual = create_individual #Одноточечный кроссинговер def crossover(parent_1, parent_2): crossover_index = random.randrange(1, len(parent_1)) child_1a = parent_1[:crossover_index] child_1b = [i for i in parent_2 if i not in child_1a]
def Genetic_al(model, data, i, stud1): ga = GeneticAlgorithm(data, population_size=100, generations=100, crossover_probability=0.01, mutation_probability=0.01, elitism=False, maximise_fitness=False) def create_individual(data): return [ float(1.0 + 5.0 * random.uniform(0, 1)), # Drop time actual float(1.0 + 15.0 * random.uniform(0, 1)), # Drop time actual_EWMA float(1.0 + 15.0 * random.uniform(0, 1)), # Drop time difference float(1.0 + 15.0 * random.uniform(0, 1)), # Drop time difference_EWMA # float((random.randint(300, 4000) + random.uniform(0, 1))),# Energy # float((random.randint(300, 4000) + random.uniform(0, 1))), # Energy_EWMA float(1.0 + 2.0 * random.uniform(0, 1)), # Lift Height actual float(1.0 + 2.0 * random.uniform(0, 1)), # Lift Height actual_EWMA # float((random.randint(0, 2) + random.uniform(0, 1))), # lift height ref # float((random.randint(0, 2) + random.uniform(0, 1))), # lift height ref_EWMA float(15.0 + 40.0 * random.uniform(0, 1)), # Main Weldcurrent voltage actual float(15.0 + 4.0 * random.uniform(0, 1) ), # Main Weldcurrent voltage actual_EWMA # ((random.randint(25, 50) + random.uniform(0, 1))),# Main Weldcurrent voltage Max # ((random.randint(25, 50) + random.uniform(0, 1))), # Main Weldcurrent voltage Max_EWMA # ((random.randint(8, 28) + random.uniform(0, 1))), # Main Weldcurrent voltage Min # ((random.randint(8, 28) + random.uniform(0, 1))), # Main Weldcurrent voltage Min_EWMA # (-(random.randint(1, 3) + random.uniform(0, 1))), # Penetration Max # (-(random.randint(1, 3) + random.uniform(0, 1))), # Penetration Max_EWMA # (-(random.randint(0, 3) + random.uniform(0, 1))), # Penetration Min # (-(random.randint(0, 3) + random.uniform(0, 1))), # Penetration Min_EWMA # (-(random.randint(0, 3) + random.uniform(0, 1))),# Penetratiom Ref # (-(random.randint(0, 3) + random.uniform(0, 1))), # Penetratiom Ref_EWMA float(8.0 + 35.0 * random.uniform(0, 1)), # Pilot Weldcurrent Arc Voltage Act float(8.0 + 35.0 * random.uniform(0, 1) ), # Pilot Weldcurrent Arc Voltage Act_EWMA # ((random.randint(20, 50) + random.uniform(0, 1))),# Pilot Weldcurrent Arc Voltage Max # ((random.randint(20, 50) + random.uniform(0, 1))), # Pilot Weldcurrent Arc Voltage Max_EWMA # ((random.randint(5, 20) + random.uniform(0, 1))),# Pilot Weldcurrent Arc Voltage Min # ((random.randint(5, 20) + random.uniform(0, 1))), # Pilot Weldcurrent Arc Voltage Min_EWMA float(1.5 + 8.0 * random.uniform(0, 1)), # Stickout float(1.5 + 8.0 * random.uniform(0, 1)), # Stickout_EWMA float(500.0 + 1000.0 * random.uniform(0, 1)), # Weldcurrent actual Positive float(500.0 + 1000.0 * random.uniform(0, 1)), # Weldcurrent actual Positive_EWMA float(-1500.0 + 1500.0 * random.uniform(0, 1)), # Weldcurrent actual Negative float(-1500.0 + 1500.0 * random.uniform(0, 1)), # Weldcurrent actual Negative_EWMA float(10.0 + 100.0 * random.uniform(0, 1)), # Weld time actual float(10.0 + 100.0 * random.uniform(0, 1)) ] # Weld time actual_EWMA # ((random.randint(10, 100) + random.uniform(0, 1))), # Weldtime ref # ((random.randint(10, 100) + random.uniform(0, 1)))] # Weldtime ref_EWMA ga.create_individual = create_individual def eval_fitness(individual, data): array = np.array(individual)[np.newaxis] error_array = [] error = (model.predict(array, batch_size=1) + 2)**2 error_array.append(individual) print('Evaluating... error: ' + str(error)) return error ga.fitness_function = eval_fitness ga.run() Gen1 = pd.DataFrame(ga.last_generation()) filepath = "C:\\Users\PHLEGRA\Desktop\MASTER\Data_intersection\Prescribed_parameters\\new" filename = str(stud1) + "_" + str(i) + '_predictions.csv' Gen1.to_csv(filepath + '\\' + filename, index=False) print('Please see file. Process Complete')
def generate(target_params, insert_aa_seq, population_size=100, mutation_probability=0.3, max_gens_since_improvement=50, genetic_code=11, verbose=False): # back translate to an initial seq insert = "" for aa in insert_aa_seq: try: insert += Bio.Data.CodonTable.unambiguous_dna_by_id[ genetic_code].back_table[aa] except: if aa == "*": insert += Bio.Data.CodonTable.unambiguous_dna_by_id[ genetic_code].back_table[None] # create the genetic algorithm instance ga = GeneticAlgorithm(dna_to_vector(insert), crossover_probability=0, maximise_fitness=False, population_size=population_size, mutation_probability=mutation_probability) # get the target values of k k = list(target_params.keys()) # generate the target vector from the input dict target = np.array([]) for _k in sorted([x for x in k if x != "codons"]): target = np.concatenate((target, [ x[1] for x in sorted(target_params[_k].items(), key=lambda x: x[0]) ])) if "codons" in k: target = np.concatenate((target, [ x[1] for x in sorted(target_params["codons"].items(), key=lambda x: x[0]) ])) def vector(seq): output = k_mer_frequencies(seq, [x for x in k if x != "codons"], include_missing=True, vector=True) if "codons" in k: output = np.concatenate((output, [ x[1] for x in sorted(codon_frequencies(seq, genetic_code).items(), key=lambda x: x[0]) ])) return output def fitness(individual, data): individual = vector_to_dna(individual) # fitness = np.linalg.norm(target - vector(individual)) fitness = jensen_shannon_divergence([ dit.ScalarDistribution(target), dit.ScalarDistribution(vector(individual)) ]) return fitness ga.fitness_function = fitness synonymous_codons = _synonymous_codons(genetic_codes[genetic_code]) def mutate(individual): while True: # choose a random codon codon_idx = np.random.randint(len(individual) / 6) * 6 # figure out which codon it is codon = vector_to_dna(individual[codon_idx:codon_idx + 6]) # ensure that mutations actually change the sequence if len(synonymous_codons[codon]) != 1: break # choose a new one at random for the AA new_codon = dna_to_vector( np.random.choice( [x for x in synonymous_codons[codon] if x != codon])) # replace it in the individual individual[codon_idx:codon_idx + 6] = new_codon return individual ga.mutate_function = mutate def create_individual(seed_data): individual = vector_to_dna(seed_data) new = "" for codon in [ individual[i:i + 3] for i in range(0, len(individual), 3) ]: if len(synonymous_codons[codon]) == 1: new += codon continue new += np.random.choice( [x for x in synonymous_codons[codon] if x != codon]) return dna_to_vector(new) ga.create_individual = create_individual # set up for GA run ga.create_first_generation() gens_since_improvement = 0 best_indv_fitness = ga.best_individual()[0] counter = 1 # run the GA while gens_since_improvement < max_gens_since_improvement: ga.create_next_generation() if ga.best_individual()[0] < best_indv_fitness: best_indv_fitness = ga.best_individual()[0] gens_since_improvement = 0 else: gens_since_improvement += 1 if verbose: print( "Gen: %s\tSince Improvement: %s/%s\tFitness: %s".expandtabs(15) % (counter, gens_since_improvement, max_gens_since_improvement, ga.best_individual()[0]), end="\r") counter += 1 if verbose: print() best_seq = vector_to_dna(ga.best_individual()[1]) best_freqs = vector(best_seq) return best_seq
if not existenDatosInvalidos(individual) and not existenDatosDuplicados( individual): fitness += britanicoCasaRoja(individual) fitness += suecoTienePerro(individual) fitness += danesTomaTe(individual) fitness += casaVerdeIzqACasaBlanca(individual) fitness += casaVerdeTomaTe(individual) fitness += fumaPallMallTienePajaro(individual) fitness += casaAmarillaFumaDunhill(individual) fitness += casaDelCentroTomaLeche(individual) fitness += noruegoEnPrimeraCasa(individual) fitness += fumaBrendsYVecinoTieneGato(individual) fitness += tieneCaballoYVecinoFumaDunhill(individual) fitness += fumaBluemastersYBebeCerveza(individual) fitness += alemanFumaPrince(individual) fitness += noruegoJuntoACasaAzul(individual) fitness += fumaBrendsYVecinoTomaAgua(individual) resultantes.append({'fitness': fitness, 'individual': individual}) return fitness ga = GeneticAlgorithm(datos, population_size=2000) ga.create_individual = create_individual ga.fitness_function = fitness ga.run() last = resultantes.pop() print(last.get('individual'))
parser.add_argument('--adaptive_mutation_factor', default=1.3, type=float, help='enter a decimal value for how much to multiply mutation rate per generation') parser.add_argument('--clipping_threshold', default=0.9, type=float, help='enter a decimal between 0 and 1 at which clipping is performed') parser.add_argument('--turbines', default=2, type=int, help='enter an integer number of turbines to start with') parser.add_argument('--grid_size', default=36, type=int, help='enter an perfect square integer representing grid size (e.g. 6x6 is 36)') args = parser.parse_args() given_crossover_probability = args.crossover_probability given_mutation_probability = args.starting_mutation_probability given_adaptive_mutation_factor = args.adaptive_mutation_factor given_clipping_threshold = args.clipping_threshold given_turbines = args.turbines grid_size= args.grid_size input_data = [0]*grid_size # length of this list is the # of grid cells in layout easyga = GeneticAlgorithm(input_data, crossover_probability =given_crossover_probability , mutation_probability=given_mutation_probability, adaptive_mutation_factor = given_adaptive_mutation_factor, clipping_threshold = given_clipping_threshold, num_turbines = given_turbines) easyga.fitness_function = fitness easyga.run() print(easyga.best_individual()) def fitness (individual, data): freestream_velocity = 15 individual_2D_list = [[individual[0], individual[1]],[individual[2], individual[3]]] individual_np = np.asarray(individual_2D_list) velocities = np.zeros(individual_np.shape) alpha = .9 # entrainment constant x = 150 # distance between perpendicular turbine centers r = 40 # radius of turbine
from pyeasyga.pyeasyga import GeneticAlgorithm import random import numpy as np # Формат задания значений (y(x), [x]) data = (4.0, [-2.0]) # Параметры работы генетического алгоритма # (начальные данные, кол-во особей в популяции, кол-во генераций, вероятность применения оператора скрещивания, вероятность применения мутации к гену, вкл. выбор лучшей особи, максимизация целевой функции) ga = GeneticAlgorithm(data, 20, 30, 0.7, 0.01, True, False) # Функция создания начальной популяции def create_individual(data): # Вещественное кодирование ind = [random.uniform(-4.0, 4.0)] # Вывод начальной популяции на экран print(ind[0] * ind[0] + 4, ind) return ind #[random.uniform(-4.0, 4.0) for _ in range(len(data))] ga.create_individual = create_individual # Функция кроссинговера ГА (арифметический кроссинговер, lambda = 0.2) def crossover(parent_1, parent_2): child_1 = [parent_1[0] * 0.2 + parent_2[0] * 0.8] child_2 = [parent_2[0] * 0.2 + parent_1[0] * 0.8] return child_1, child_2
from pyeasyga.pyeasyga import GeneticAlgorithm import random data = [('pear', 50), ('apple', 35), ('banana', 40)] ga = GeneticAlgorithm(data, 20, 50, 0.8, 0.2, True, True) def create_individual(data): print("***CREATE INDIVIDUAL***") ind = [random.randint(0, 1) for _ in xrange(len(data))] print(ind) return ind ga.create_individual = create_individual def crossover(parent_1, parent_2): crossover_index = random.randrange(1, len(parent_1)) child_1 = parent_1[:crossover_index] + parent_2[crossover_index:] child_2 = parent_2[:crossover_index] + parent_1[crossover_index:] print("***HERENCIA***") print(child_1) print(child_2) return child_1, child_2 ga.crossover_function = crossover def mutate(individual):
from pyeasyga.pyeasyga import GeneticAlgorithm from random import random data = [('pear', 50), ('apple', 35), ('banana', 40)] ga = GeneticAlgorithm(data, population_size=40, generations=20, crossover_probability=0.8, mutation_probability=0.9, elitism=True, maximise_fitness=True) def fitness (individual, data): fitness = 0 if individual.count(1) == 3: for (selected, (fruit, profit)) in zip(individual, data): if selected: fitness += profit return fitness ga.fitness_function = fitness ga.run() print (ga.best_individual()) for individual in ga.last_generation(): print (individual)
def generate(target_params, insert_aa_seq, population_size=100, mutation_probability=0.3, crossover_probability=0.8, max_gens_since_improvement=50, genetic_code=11, verbose=False): '''Generate a sequence matching :math:`k`-mer usage. Args: target_params (dict): The parameters to optimize towards. Should be of the format {:math:`k_n`: {:math:`k_{n1}`: 0.2, :math:`k_{n2}`: 0.3,...}...} insert_aa_seq (str): The amino acid sequence for the optimized sequence. population_size (int, optional): The size of the population for the genetic algorithm. Defaults to 100. mutation_probability (float, optional): The likelihood of changing each member of each generation. Defaults to 0.3. crossover_probability (float, optional): The likelihood of each member of the population undergoing crossover. Defaults to 0.8. max_gens_since_improvement (int, optional): The number of generations of no improvement after which to stop optimization. Defaults to 50. genetic_code (int, optional): The genetic code to use. Defaults to 11, the standard genetic code. verbose (bool, optional): Whether to print the generation number, generations since improvement, and fitness. Defaults to false. Returns: str: The generated sequence. ''' # back translate to an initial seq insert = "" for aa in insert_aa_seq: try: insert += Bio.Data.CodonTable.unambiguous_dna_by_id[genetic_code].back_table[aa] except: if aa == "*": insert += Bio.Data.CodonTable.unambiguous_dna_by_id[genetic_code].back_table[None] # create the genetic algorithm instance ga = GeneticAlgorithm(dna_to_vector(insert), crossover_probability=crossover_probability, maximise_fitness=False, population_size=population_size, mutation_probability=mutation_probability) # get the target values of k k = list(target_params.keys()) # generate the target vector from the input dict target = np.array([]) for _k in sorted([x for x in k if x != "codons"]): target = np.concatenate((target, [x[1] for x in sorted(target_params[_k].items(), key=lambda x: x[0])])) if "codons" in k: target = np.concatenate((target, [x[1] for x in sorted(target_params["codons"].items(), key=lambda x: x[0])])) def vector(seq): output = k_mer_frequencies(seq, [x for x in k if x != "codons"], include_missing=True, vector=True) if "codons" in k: output = np.concatenate((output, [x[1] for x in sorted(codon_frequencies(seq, genetic_code).items(), key=lambda x: x[0])])) return output def fitness(individual, data): individual = vector_to_dna(individual) # fitness = np.linalg.norm(target - vector(individual)) fitness = jensen_shannon_divergence([dit.ScalarDistribution(target), dit.ScalarDistribution(vector(individual))]) return fitness ga.fitness_function = fitness synonymous_codons = _synonymous_codons(genetic_codes[genetic_code]) def mutate(individual): while True: # choose a random codon codon_idx = np.random.randint(len(individual) / 6) * 6 # figure out which codon it is codon = vector_to_dna(individual[codon_idx:codon_idx+6]) # ensure that mutations actually change the sequence if len(synonymous_codons[codon]) != 1: break # choose a new one at random for the AA new_codon = dna_to_vector(np.random.choice([x for x in synonymous_codons[codon] if x != codon])) # replace it in the individual individual[codon_idx:codon_idx+6] = new_codon return individual ga.mutate_function = mutate def crossover(parent_1, parent_2): parent_1, parent_2 = list(parent_1), list(parent_2) index = random.randrange(1, len(parent_1) / 6) * 6 child_1 = parent_1[:index] + parent_2[index:] child_2 = parent_2[:index] + parent_1[index:] return child_1, child_2 ga.crossover_function = crossover def create_individual(seed_data): individual = vector_to_dna(seed_data) new = "" for codon in [individual[i:i+3] for i in range(0, len(individual), 3)]: if len(synonymous_codons[codon]) == 1: new += codon continue new += np.random.choice([x for x in synonymous_codons[codon] if x != codon]) return dna_to_vector(new) ga.create_individual = create_individual # set up for GA run ga.create_first_generation() gens_since_improvement = 0 best_indv_fitness = ga.best_individual()[0] counter = 1 # run the GA try: while gens_since_improvement < max_gens_since_improvement: ga.create_next_generation() if ga.best_individual()[0] < best_indv_fitness: best_indv_fitness = ga.best_individual()[0] gens_since_improvement = 0 else: gens_since_improvement += 1 if verbose: print("Gen: %s\tSince Improvement: %s/%s\tFitness: %s".expandtabs(15) % (counter, gens_since_improvement, max_gens_since_improvement, ga.best_individual()[0]), end="\r") counter += 1 except KeyboardInterrupt: print("\nStopping early...") if verbose: print() best_seq = vector_to_dna(ga.best_individual()[1]) best_freqs = vector(best_seq) assert Seq(best_seq).translate(genetic_code) == Seq(insert).translate(genetic_code) return best_seq
print(iterations) matriz_gerada = list() i = 0 while (i < len(iterations)): matriz_gerada.insert(i, iterations[i]['node_count']) i += 1 # Ready CSV arq = open("casos_sj.csv") sirSjCsv = csv.DictReader(arq, fieldnames=["R", "I"]) sirSj = list() sirI = list() sirR = list() i = 0 for row in sirSjCsv: sirSj.insert(i, {"I": row['I'], "R": row['R']}) sirI.append(row['I']) sirR.append(row['R']) i += 1 print(sirSj) data = sirSj ga = GeneticAlgorithm(data) print(data[1, "R"]) print(type(data))
i = np.random.randint(N) j = np.random.randint(N) if i != j: adj_mat[i, j] = 0 adj_mat[j, i] = 0 return adj_mat N = 10 adj_mat = generate_adj_mat(N) print("Szombszédsági mátrix:") print(adj_mat) ga = GeneticAlgorithm(list(range(N)), 500, 200) def create_individual(data): return np.random.randint(0, N, len(data)) ga.create_individual = create_individual def crossover(parent1, parent2): c_idx = random.randrange(1, parent1.shape[0]) child_1 = np.append(parent1[:c_idx], parent2[c_idx:]) child_2 = np.append(parent2[:c_idx], parent1[c_idx:]) return child_1, child_2