Exemple #1
0

ga.mutate_function = mutate


#Рулеточная селекция
def selection(population):
    return random.choice(population)


ga.selection_function = selection


#Реализация функции приспособленности
#Ищет такой х, при котором значение функции максимально
def fitness(individual, data):
    fitness = -float("inf")
    x = -4
    for item in individual:
        if item != 1:
            x += 0.01
        else:
            fitness = 1 / x
            break
    return fitness


ga.fitness_function = fitness
ga.run()
print(ga.best_individual())  #Выводит самую приспособленную особь
Exemple #2
0
    individual[0] = individual[0] + rnd


ga.mutate_function = mutate


# Функция селекции / турнирный отбор
def selection(population):
    ind1 = random.choice(population)
    ind2 = random.choice(population)
    if ind1.fitness < ind2.fitness:
        return ind1
    else:
        return ind2


ga.selection_function = selection


def fitness(individual, data):  #Целевая функция
    return individual[0] * individual[0] + 4  #Значение целевой функции


ga.fitness_function = fitness
ga.run()
# Вывод лучшей особи популяции (Наше решение)
print("\nBest individual: ", ga.best_individual(), "\n")

# Вывод всех особей популяции в последнем поколении
for individual in ga.last_generation():
    print(individual)
Exemple #3
0
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
Exemple #4
0
ga.mutate_function = mutate


def selection(population):
    r = random.choice(population)
    print("***SELECTION***")
    print(r)
    return r


ga.selection_function = selection


def fitness(individual, data):
    fitness = 0
    if individual.count(1) == 2:
        for (selected, (fruit, profit)) in zip(individual, data):
            if selected:
                fitness += profit
    print("***FITNESS***")
    print(fitness)
    return fitness


ga.fitness_function = fitness
ga.run()
print ga.best_individual()

for individual in ga.last_generation():
    print individual
    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

	for rowIndex in range(np.shape(individual_np)[0]):
		for colIndex in range(np.shape(individual_np)[1]):
Exemple #6
0
ga.mutate_function = mutate


# Рулеточная селекция
def selection(population):
    return random.choice(population)


ga.selection_function = selection


# Функция приспособленности
# Ищет такой х, при котором значение функции минимально
def fitness(individual, data):
    fitness = float("inf")
    x = -2
    for item in individual:
        if item != 1:
            x += 0.01
        else:
            fitness = x**2 + 4
            break
    return fitness


ga.fitness_function = fitness
ga.run()
# Вывод самой приспособленной особи
print(ga.best_individual())
Exemple #7
0
    rnd = np.random.normal(0, 0.5)
    if rnd < -0.5:
        rnd = -0.5
    elif rnd > 0.5:
        rnd = 0.5
    individual[0] = individual[0] + rnd

ga.mutate_function = mutate

def selection(population): #Функция селекции (турнирный отбор)
    ind1 = random.choice(population)
    ind2 = random.choice(population)
    if ind1.fitness > ind2.fitness:
        return ind1
    else:
        return ind2

ga.selection_function = selection

def fitness (individual, data): #Целевая функция
    if individual[0] < -4.0: #Ограничения переменных ЦФ
        individual[0] = -4.0
    if individual[0] >= 0:
        individual[0] = 1e-10
    return 1 / individual[0] #Значение целевой функции 
    
ga.fitness_function = fitness
ga.run() #Запуск ГА
print("\nBest individual: ", ga.best_individual(), "\n") #Вывод лучшей особи популяции (Решение)
for individual in ga.last_generation(): #Вывод всех особей популяции в последнем поколении
  print(individual)
Exemple #8
0
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
ga.mutate_function = mutate


def fitness(individual, data):
    f = 0
    if is_repetition(individual):
        return -math.inf
    else:
        for i in range(individual.shape[0]):
            if i == individual.shape[0] - 1:
                if adj_mat[individual[i]][individual[0]] == 0:
                    return -math.inf
                else:
                    f += adj_mat[individual[i]][individual[0]]
                    break
            if adj_mat[individual[i]][individual[i + 1]] == 0:
                return -math.inf
            else:
                f -= adj_mat[individual[i]][individual[i + 1]]
    return f


ga.fitness_function = fitness
ga.run()

best = ga.best_individual()

print("Optimális út:")
print(best[1])
print("Út hossza: ", -best[0])
Exemple #10
0
    materiasSelec = []

    if individual.count(
            1
    ) <= 5:  #con esto controlo cuantas materias selecciono de data. (ahora me quedo solo con individuos que tienen 6 materias MAX)
        for (selected, (materia)) in zip(individual, data):
            if selected:  #con esto veo unicamente las materias seleccionadas (una por una)

                materiasSelec.append(materia)

        fitness += restricciones(materiasSelec)

    ac.append(fitness)
    return fitness


#ga.selection_function = ga.random_selection

ga.fitness_function = fitness
ga.run()

print(ga.best_individual())

print(ga.last_generation())

for index, materia in enumerate(ga.best_individual()[1]):
    if materia == 1:
        print(data[index])

#print(ac)