def create_first_gen(self): pop = list() for each in range(self.get_initial_pop_size()): genotype = Genotype() genotype.create_initial_genotype(each) pop.append(self.species(genotype)) return pop
def generate_offspring(genotype1, genotype2, **kwargs): """ Use the crossover and mutation operators to produce an offspring from 2 genotypes. The mutation operator is always applied, but the probability that a given bit is mutated is determined by mutation_probability. Similarly, the crossover operator is applied to each generator with probability crossover_probability. Args: - genotype1, genotype2 (Genotype objects): the genotypes to be combined Returns: - offspring (Genotype object) """ crossover_probability = kwargs.get('crossover_probability') mutation_probability = kwargs.get('mutation_probability') swap_window_probability = kwargs.get('swap_window_probability') window_mutation_probability = kwargs.get('window_mutation_probability') init_status = kwargs.get('init_status') binary_schedule1 = convert_to_binary(genotype1.schedule) binary_schedule2 = convert_to_binary(genotype2.schedule) # Apply crossover offspring_binary_schedule1, offspring_binary_schedule2 = crossover( binary_schedule1, binary_schedule2, crossover_probability) # Apply mutation offspring_binary_schedule1 = mutate(offspring_binary_schedule1, mutation_probability) offspring_binary_schedule2 = mutate(offspring_binary_schedule2, mutation_probability) # Apply swap window operator r1, r2 = np.random.uniform(0, 1, size=2) if r1 < swap_window_probability: offspring_binary_schedule1 = swap_window(offspring_binary_schedule1) if r2 < swap_window_probability: offspring_binary_schedule2 = swap_window(offspring_binary_schedule2) # Apply window mutation operator r1, r2 = np.random.uniform(0, 1, size=2) if r1 < window_mutation_probability: offspring_binary_schedule1 = window_mutation( offspring_binary_schedule1) if r2 < window_mutation_probability: offspring_binary_schedule2 = window_mutation( offspring_binary_schedule2) # Convert to integer offspring_integer_schedule1 = convert_to_integer( offspring_binary_schedule1, init_status) offspring_integer_schedule2 = convert_to_integer( offspring_binary_schedule2, init_status) # Initialise genotype offspring1 = Genotype(offspring_integer_schedule1, **kwargs) offspring2 = Genotype(offspring_integer_schedule2, **kwargs) return offspring1, offspring2
def calculate(loci, father, mother, child, alleged, quiet): if alleged == 'both': af = Parent(Genotype(loci, Allele(father[0]), Allele(father[1])), sex=1, if_alleged=True) am = Parent(Genotype(loci, Allele(mother[0]), Allele(mother[1])), sex=0, if_alleged=True) ch = Child(Genotype(loci, Allele(child[0]), Allele(child[1]))) test = PaternityTest(af, am, ch) x = test.GetX() y = test.GetY() pi = test.getPaternityIndex(x, y) if not quiet: click.echo(' Loci: ' + loci) click.echo(' Father: ' + str(father)) click.echo(' Mother: ' + str(mother)) click.echo(' Child: ' + str(child)) click.echo('Alleged: ' + alleged) click.echo() hypotheses = test.mutation_hypotheses click.echo('Mutation Hypotheses:') for h in hypotheses: p = test.getProbability(h) click.echo(f'\t{str(h)}\tP = {float(p):.15f}') click.echo(' X = ' + str(x)) click.echo(' Y = ' + str(y)) click.echo('PI = ' + str(pi))
def cross_by_choosing_the_best_values(specimenA, specimenB, coin_chosen_to_save, coin_quantity): temp_specimen = Genotype() for k in range(22): if abs(specimenA.genotype_matrix[rows_encoder[coin_chosen_to_save]][k] - coin_quantity) > abs(specimenB.genotype_matrix[rows_encoder[coin_chosen_to_save]][k] - coin_quantity): for m in range(8): temp_specimen.genotype_matrix[m][k] = specimenB.genotype_matrix[m][k] else: for m in range(8): temp_specimen.genotype_matrix[m][k] = specimenA.genotype_matrix[m][k] return temp_specimen
def crossover_individuals(individual1, individual2, type='single'): genotype1 = individual1.genotype genotype2 = individual2.genotype crossp = randint(1, genotype1.n - 1) mask1 = ((1 << (genotype1.n - crossp)) - 1) << crossp mask2 = (1 << crossp) - 1 ch1 = mask1 & genotype1.chromosome | mask2 & genotype2.chromosome ch2 = mask1 & genotype2.chromosome | mask2 & genotype1.chromosome child1 = Genotype(genotype1.n, ch1) child2 = Genotype(genotype1.n, ch2) return [Individual(child1), Individual(child2)]
def cross_mc(specimen_a, specimen_b, coin_chosen_to_save, coin_quantity): specimen_c = Genotype() rows = 8 col = 22 for i in range(rows): for j in range(int(col / 2)): specimen_c.genotype_matrix[i][j] = specimen_a.genotype_matrix[i][j] for i in range(rows): for j in range(int(col / 2), col): specimen_c.genotype_matrix[i][j] = specimen_b.genotype_matrix[i][j] return specimen_c
def cross_mc(specimen_a, specimen_b): specimen_c = Genotype() rows = 6 col = 18 for i in range(rows): for j in range(int(col / 2)): specimen_c.genotype_matrix[i][j] = specimen_a.genotype_matrix[i][j] for i in range(rows): for j in range(int(col / 2), col): specimen_c.genotype_matrix[i][j] = specimen_b.genotype_matrix[i][j] return specimen_c
def add_elite_children(self): for i in range(self.elitism): self.genotype_pool.append( Genotype(self.genotype_length, dna_vector=copy( self.phenotype_adult_pool[i].parent.dna_vector), symbol_set_size=self.symbol_set_size))
def initialize_genotypes(self): self.genotype_pool = [ Genotype(length=self.genotype_length, initial_config=True, symbol_set_size=self.symbol_set_size) for _ in range(self.genotype_pool_size) ]
def __init__(self, quantity, statistical_day): self.quantity = quantity self.statistical_day = statistical_day self.population = [Genotype() for _ in range(quantity)] self.sorted_population = [] self.cost_matrix = [] self.rows_encoder = {1: 0, 2: 1, 5: 2, 10: 3, 20: 4, 50: 5}
def get_gene(self): geno_parser = GenoParser(self.n_nodes) gene_normal = geno_parser.parse(tf.nn.softmax(self.alphas_normal).numpy()) gene_reduce = geno_parser.parse(tf.nn.softmax(self.alphas_reduce).numpy()) return Genotype(normal=gene_normal, reduce=gene_reduce)
def get_gene(self): geno_parser = GenoParser(self.n_nodes) gene_normal = geno_parser.parse(F.softmax(self.alphas_normal, dim=-1).detach().cpu().numpy()) gene_reduce = geno_parser.parse(F.softmax(self.alphas_reduce, dim=-1).detach().cpu().numpy()) return Genotype(normal=gene_normal, reduce=gene_reduce)
def construct_color_map(self, filename): file = open(filename, 'r') genes_dict = defaultdict(list) line = file.readline().strip() while(line != [''] and line != ''): gene = Genotype(line) genes_dict[gene.phenotype].append(gene) line = file.readline() return genes_dict
def test_crossover(self): size = 6 g1 = Genotype(size) g2 = Genotype(size) g1.dna = [False, False, False, False, False, False] g2.dna = [True, True, True, True, True, True] g1.crossover(g2) self.assertTrue(False in g1.dna) self.assertTrue(True in g1.dna) self.assertEqual(len(g1.dna), size)
def mate_parents(self, parent1, parent2): r = random() if r <= self.crossover_rate: child1_dna_vector, child2_dna_vector = parent1.parent.create_crossover_dna_vector(parent2.parent, self.points_of_crossover) child1 = Genotype(self.genotype_length, dna_vector=copy(child1_dna_vector), symbol_set_size=self.symbol_set_size) child2 = Genotype(self.genotype_length, dna_vector=copy(child2_dna_vector), symbol_set_size=self.symbol_set_size) else: child1 = Genotype(self.genotype_length, dna_vector=copy(parent1.parent.dna_vector), symbol_set_size=self.symbol_set_size) child2 = Genotype(self.genotype_length, dna_vector=copy(parent2.parent.dna_vector), symbol_set_size=self.symbol_set_size) child1.mutate(mutation_rate=self.mutation_rate, mutation_protocol=self.mutation_protocol) child2.mutate(mutation_rate=self.mutation_rate, mutation_protocol=self.mutation_protocol) return child1, child2
def __init__(self, quantity, statistical_day, coins_to_save, cross_function, mutate_function, mutation, expected_quantity_of_coins): self.quantity = quantity self.statistical_day = statistical_day self.population = [Genotype() for _ in range(quantity)] self.sorted_population = [] self.coins_to_save = coins_to_save self.cost_matrix = [10000] self.cross_function = cross_function self.mutation_function = mutate_function self.mutation = mutation self.expected_quantity_of_coins = expected_quantity_of_coins
def create_individual(self): if (self.parameters['type'] == 'permutation'): phen = \ np.array(list(range(0,self.environment.get_chromosome_length()))) random.shuffle(phen) individual = \ Individual(phenotype=phen) else: individual = \ Individual(Genotype(self.environment.get_chromosome_length())) return individual
def get_gene(self): geno_parser = GenoParser(self.n_nodes) gene_down = geno_parser.parse( F.softmax(self.alpha1_down, dim=-1).detach().cpu().numpy(), F.softmax(self.alpha2_down, dim=-1).detach().cpu().numpy()) gene_up = geno_parser.parse(F.softmax(self.alpha1_up, dim=-1).detach().cpu().numpy(), F.softmax(self.alpha2_up, dim=-1).detach().cpu().numpy(), downward=False) return Genotype(down=gene_down, up=gene_up)
def next_generation(self): self.world.stop() self.population.evaluate() new_pop = Population(rank_probability=self.RANK_PROBABILITY_CONSTANT, reverse_sort=False) for _ in xrange(self.RANDOM_ACTORS_NUMBER): new_pop.append(self.create_actor()) for _ in xrange(self.POP_SIZE - self.RANDOM_ACTORS_NUMBER): new_genotype = Genotype.reproduce(self.population.select_by_rank().genotype, self.population.select_by_rank().genotype) new_pop.append(self.create_actor(genotype=new_genotype)) self.population = new_pop self.current_generation += 1 self.world.start()
def visit(self, node): genes_list = self.get_genotypes_for_phenotype(node.color) if (node.dam) and (node.sire): combos = self.combine_parent_alleles(node.sire, node.dam) valid_combos = self.remove_invalid_combos_for_phenotype( combos, node) full_genos = self.create_full_genotypes(valid_combos, node) self.poss_geneotypes[node] = (full_genos) genotypes = [] for line in full_genos: genotypes.append(Genotype(line)) self.poss_genes[node] = genotypes else: self.poss_genes[node] = genes_list self.poss_geneotypes[node] = (genes_list)
def cross(self, another_parent) -> list: if not self.ifParentsDiffSexes(another_parent): print(Fore.YELLOW + 'Parents have the same sex' + Style.RESET_ALL) exit(1) if not self.ifParentsSameLoci(another_parent): print(Fore.YELLOW + 'Parents have different locus' + Style.RESET_ALL) exit(1) zygotes=[] for allele in self.genotype.alleles: for another_allele in another_parent.genotype.alleles: zygote_genotype = Genotype(loci=self.genotype.loci, first_allele=Allele(allele_type=allele.type, from_parent=self.sex), second_allele=Allele(allele_type=another_allele.type, from_parent=another_parent.sex)) zygotes.append(zygote_genotype) return zygotes
def main(): g = Genotype(number_inputs=3, number_outputs=1) for gene in g.node_genes: print(gene) for gene in g.connection_genes: print(gene) g.split_connection(innov=2) print() for gene in g.node_genes: print(gene) for gene in g.connection_genes: print(gene) g.add_connection(in_node=1, out_node=5) print() for gene in g.node_genes: print(gene) for gene in g.connection_genes: print(gene)
class Individual: def __init__(self, id, chromosome_size, trajectory): self.id = id self.fitness = 0.0 self.genotype = Genotype() self.genotype.randomize(chromosome_size, trajectory) self.chromosome_size = chromosome_size def individualID(self): return self.id """ TWO POINT CROSSOVER """ def crossover(self, otherInd): #print("Individual " + str(self.id) + " is doing the crossover with Individual " + str(otherInd.id)) #2-point-crossover lower_bound = random.randint(0, len(self.genotype.chromosomes) - 1) higher_bound = random.randint(lower_bound, len(self.genotype.chromosomes) - 1) offsprings = [] offsprings.append(copy.deepcopy(self)) offsprings.append(copy.deepcopy(otherInd)) for i in range(lower_bound, higher_bound + 1): offsprings[0].getGenotype().chromosomes[i] = otherInd.getGenotype( ).chromosomes[i] offsprings[1].getGenotype().chromosomes[i] = self.getGenotype( ).chromosomes[i] #Check for validity of the world world_validity = World(offsprings[0].getPhenotype().level) if world_validity.validate_trajectory( offsprings[0].getGenotype().trajectory) == False: offsprings[0] = copy.deepcopy(self) if world_validity.validate_trajectory( offsprings[1].getGenotype().trajectory) == False: offsprings[1] = copy.deepcopy(otherInd) return offsprings """ Mutate an individual chromosome! (called from the algorithm!) """ def mutate(self, mutation_probability): possible_tiles = [0, 1, 5, 6, 7, 8] tries = 10 #print("Individual " + str(self.id) + " is MUTATING") while tries > 0: tries -= 1 mutated_individual = copy.deepcopy(self) if random.uniform(0, 1) < mutation_probability: mutated_individual.genotype.chromosomes[random.randint( 0, len(self.genotype.chromosomes) - 1)] = possible_tiles[random.randint( 0, len(possible_tiles) - 1)] world_validity = World(mutated_individual.getPhenotype().level) if world_validity.validate_trajectory( mutated_individual.getGenotype().trajectory) == True: self.genotype = copy.deepcopy(mutated_individual.genotype) return """ Test each chromosome for mutation """ def mutateAll(self, mutation_probability): possible_tiles = [0, 1, 5, 6, 7, 8] chromosome_size = len(self.genotype.chromosomes) mutated_individual = copy.deepcopy(self) for i in range(chromosome_size): if random.uniform(0, 1) < mutation_probability: mutated_individual.genotype.chromosomes[i] = possible_tiles[ random.randint(0, len(possible_tiles) - 1)] world_validity = World(mutated_individual.getPhenotype().level) if world_validity.validate_trajectory( mutated_individual.getGenotype().trajectory) == True: self.genotype = copy.deepcopy(mutated_individual.genotype) def setFitness(self, fitness): self.fitness = fitness def getFitness(self): return self.fitness def getGenotype(self): return self.genotype def getPhenotype(self): return self.genotype.getPhenotype()
def mate_parents(self, parent1, parent2): r = random() if r <= self.crossover_rate: child1_dna_vector, child2_dna_vector = parent1.parent.create_crossover_dna_vector( parent2.parent, self.points_of_crossover) child1 = Genotype(self.genotype_length, dna_vector=copy(child1_dna_vector), symbol_set_size=self.symbol_set_size) child2 = Genotype(self.genotype_length, dna_vector=copy(child2_dna_vector), symbol_set_size=self.symbol_set_size) else: child1 = Genotype(self.genotype_length, dna_vector=copy(parent1.parent.dna_vector), symbol_set_size=self.symbol_set_size) child2 = Genotype(self.genotype_length, dna_vector=copy(parent2.parent.dna_vector), symbol_set_size=self.symbol_set_size) child1.mutate(mutation_rate=self.mutation_rate, mutation_protocol=self.mutation_protocol) child2.mutate(mutation_rate=self.mutation_rate, mutation_protocol=self.mutation_protocol) return child1, child2
def test_mutation(self): g1 = Genotype(6) g1.dna = [False, False, False, False, False, False] g1.mutate() self.assertNotEqual(g1.dna, [False, False, False, False, False, False])
def run_genetic_algorithm(number_of_generations, seed_schedules, **kwargs): """ Run the genetic algorithm. Args: - seed schedules (array): this should be an array of dimension pop_size*T*num_gen, comprising pop_size random binary schedules. """ # Retrieve variables init_status = kwargs.get('init_status') pop_size = kwargs.get('pop_size') swap_window_hc_probability = kwargs.get('swap_window_hc_probability') # Initialise parent population parent_population = Population(pop_size) # Population with seed_schedules (typically random) for i in range(pop_size): g = Genotype(convert_to_integer(seed_schedules[i], init_status), **kwargs) parent_population.add_genotype(g) # Get best genotype best_genotype1 = parent_population.best_two_genotypes()[0] # Initialise results list results = [] for g in range(number_of_generations): # Initialise new population new_population = Population(pop_size) # Increase the value of the penalty new_penalty = kwargs.get('max_penalty') * (g + 1) / number_of_generations kwargs.update({'constraint_penalty': new_penalty}) # Always add the best genotype new_population.add_genotype(best_genotype1) while new_population.num_used < new_population.size: # Roulette wheel selection g1, g2 = parent_population.select_two_genotypes() # Create a new offspring offspring1, offspring2 = generate_offspring(g1, g2, **kwargs) new_population.add_genotype(offspring1) new_population.add_genotype(offspring2) # Get best genotype and apply hill-climb operators # Also update best genotypes. best_genotype1, best_genotype2 = new_population.best_two_genotypes() new_population.remove_genotype(best_genotype1) # Apply swap mutation operator best_binary_schedule = convert_to_binary(best_genotype1.schedule) best_binary_schedule = swap_mutation_operator(best_binary_schedule, **kwargs) # Apply swam window hill climb operator (with probability swap_window_hc_probability) random = np.random.uniform(0, 1) if random < swap_window_hc_probability: best_binary_schedule = swap_window_hc_operator( best_binary_schedule, **kwargs) # Convert back to integer best_integer_schedule = convert_to_integer(best_binary_schedule, init_status) best_genotype1 = Genotype(best_integer_schedule, **kwargs) # Return best schedule to new_population new_population.add_genotype(best_genotype1) # Make new_population the parent_population parent_population = new_population # Best fitness, add to results best_fitness = best_genotype1.fitness results.append(best_fitness) print("Best fitness at iteration {0}: {1}".format(g, best_fitness)) return best_genotype1, results, new_population
def main() : parser = argparse.ArgumentParser(\ description='ASPRIN: Allele Specific Protein-RNA Interaction') group = parser.add_argument_group('required arguments') group.add_argument("-g", metavar="Genotype file", dest="genotype") group.add_argument("-c", metavar="CLIP-seq mapped reads file", dest="clipseq") group.add_argument("-r", metavar="RNA-seq mapped reads file", dest="rnaseq") parser.add_argument("-o", metavar="output file (default: std)", dest="output_file") parser.add_argument("-s", metavar="dbSNP VCF file", dest="dbsnp") parser.add_argument("-e", metavar="RADAR RNA editing database file", \ dest="radar") parser.add_argument("-t", type=int, default=25, dest="nthreads", \ metavar="Number of threads (default: 25)") parser.add_argument("-a", default="False", help="Use all the variants", \ action="store_true", dest="allvariants") args = parser.parse_args() if len(sys.argv) == 1 : parser.print_help() else : if (not args.genotype): sys.stderr.write("ASPRIN: -g genotype file is required\n") sys.exit() elif (not args.clipseq): sys.stderr.write("ASPRIN: -c CLIP-seq mapped reads file is required\n") sys.exit() elif (not args.rnaseq): sys.stderr.write("ASPRIN: -r RNA-seq mapped reads file is required\n") sys.exit() else : if (not args.dbsnp): dbsnp_fn = "" else : dbsnp_fn = args.dbsnp if (not args.radar): radar_fn = "" else : radar_fn = args.radar if (args.output_file): sys.stdout = open(args.output_file, 'w') minimum_coverage = 10 x = Coverage(args.clipseq, args.rnaseq, minimum_coverage) sys.stderr.write('Loading genotype information: ' + args.genotype +' \n') is_variant_id = False if ((radar_fn == "" and dbsnp_fn == "") or (args.allvariants==True)): is_variant_id = True x.genotype_info, x.snp_counter = Genotype().read_genotype_info(args.genotype, is_variant_id) if (radar_fn != ""): sys.stderr.write('Readig RADAR editing events: ' + radar_fn + '\n') x.genotype_info, x.radar_counter = Genotype().apply_RADAR(radar_fn, x.genotype_info) if (dbsnp_fn != ""): sys.stderr.write('Reading dbSNP SNPs: ' + dbsnp_fn + '\n') x.genotype_info, x.dbsnp_counter = Genotype().apply_dbSNP(dbsnp_fn, x.genotype_info) x.initialize_tables() sys.stderr.write('Reading CLIP-seq mapped reads file from: ' + \ str(args.clipseq) + '\n') x.clipseq_reads_coverage(args.nthreads) sys.stderr.write('Reading RNA-seq mapped reads file from: ' + \ str(args.rnaseq) + '\n') x.rnaseq_reads_coverage(args.nthreads) asprin_qvalues, asprin_odds_ratio = \ Model(minimum_coverage).perform_test(x.genotype_info, \ x.clip_reads, \ x.clip_coverage, \ x.rna_reads, \ x.rna_coverage) write_output(x.genotype_info, x.clip_reads, x.clip_coverage, \ x.rna_reads, x.rna_coverage, asprin_qvalues, \ asprin_odds_ratio, minimum_coverage) sys.stderr.write('\n')
available_values = [1, 2, 5, 10, 20, 50] statistical_day = np.random.random_integers(99, size=(10)) coin_to_save = [2, 5] quantity_of_coins = 2 #rozmiar coin_to_save expected_quantity_of_coins = [ 1, 2 ] #oczekiwana ilosc wydanych nominalow ktore chcemy zachowac population = Population(amount_of_species, statistical_day) population.calculate_changes_for_specimens(available_values) population.rank() population.calculate_cost(coin_to_save, quantity_of_coins, expected_quantity_of_coins) population.show_sorted_population_and_cost() print("\n\n") spec = Genotype() spec = cross_mc(population.population[0], population.population[1]) print(spec.genotype_matrix) for i in range(10): population.cross(coin_to_save, amount_of_species) population.calculate_cost(coin_to_save, quantity_of_coins, expected_quantity_of_coins) population.rank() population.calculate_cost_matrix_for_sorted_population() print("Iteration ", i) print(min(population.cost_matrix)) population.show_sorted_population_and_cost()
def give_birth(self, couple): new_born_genotype = Genotype() new_born_genotype.mix_parents_dna(couple) new_born = self.species(new_born_genotype) return new_born
def __init__(self, id, chromosome_size, trajectory): self.id = id self.fitness = 0.0 self.genotype = Genotype() self.genotype.randomize(chromosome_size, trajectory) self.chromosome_size = chromosome_size