def doMutation(self, chromosomeBeforeM, generationAfterM, flagMutation, fitnessList, i): Pm = self.Pm dice = [] length = len(chromosomeBeforeM.genes) chromosome = Chromosome([], length) geneFlag = [] for j in range(length): dice.append(float('%.2f' % random.uniform(0.0, 1.0))) if dice[j] > Pm: chromosome.genes.append(chromosomeBeforeM.genes[j]) geneFlag.append(0) if dice[j] <= Pm: chromosome.genes.append( float('%.2f' % random.uniform(0.0, 1.0))) geneFlag.append(1) check = sum(geneFlag) if check == 0: flagMutation[i] = 0 chromosome.fitness = fitnessList[i] else: flagMutation[i] = 1 #---clustering---- clustering = Clustering(chromosomeBeforeM, self.data, self.kmax) chromosome = clustering.calcChildFit( chromosome) #------------------ generationAfterM.chromosomes.append(chromosome) return generationAfterM
def _initial_population(self): for i in range(self._m): random_gene = self._random_gene_generator(self._n) chromosome = Chromosome(random_gene, 0) chromosome.fitness = self._evaluator(chromosome) self._evaluation_counter += 1 self._population.append(chromosome)
def random(): c = Chromosome(self._data.dimension) # Avoid duplicates while c in self._population: c = Chromosome(self._data.dimension) c.dist = self._data.tour_dist(c.tour) return c
def download_chromosome(self, name): chromosome = Chromosome(name, self.assembly) path = chromosome.path() directory = os.path.dirname(chromosome.path()) if not os.path.isdir(directory): os.makedirs(directory) self.log('Created directory {}'.format(directory), True) uri = URI + chromosome.filename() self.log('Downloading from {} to {}'.format(uri, path), True) r = requests.get(uri, stream=True) # TODO can we do this in fewer than 3 passes? with open(path, 'wb') as fd: for chunk in r.iter_content(chunk_size=1024): fd.write(chunk) with open(path, 'r') as f: header = f.readline() content = f.read().replace('\n', '') with open(path, 'w') as f: f.write(header) f.write(content) f.write('\n') self.log('...Complete', True)
def download_chromosome(self, name): chromosome = Chromosome(name, self.assembly) path = chromosome.path() directory = os.path.dirname(chromosome.path()) if not os.path.isdir(directory): os.makedirs(directory) self.log('Created directory {}'.format(directory), True) uri = URI + chromosome.filename() self.log( 'Downloading from {} to {}'.format(uri, path), True) r = requests.get(uri, stream=True) # TODO can we do this in fewer than 3 passes? with open(path, 'wb') as fd: for chunk in r.iter_content(chunk_size=1024): fd.write(chunk) with open(path, 'r') as f: header = f.readline() content = f.read().replace('\n', '') with open(path, 'w') as f: f.write(header) f.write(content) f.write('\n') self.log('...Complete', True)
def multi_points_crossover(parent1, parent2, parameters={'prob': 0.4, 'points_count': 'middle'}): """ :param parameters: dictionary of parameters that key = parameter name and value = parameter value :param parent1: First parent chromosome, Gene, np.array with len [n^2,1] :param parent2: Second parent chromosome, Gene, np.array with len [n^2,1] :return: return two chromosome for each children, Chromosome """ if str(parameters['points_count']) == 'middle': return default_cross_over(parent1, parent2) if parameters['points_count'] > len(parent1.genotype) or parameters['points_count'] <= 0: warnings.warn('points must be between 1 and size of genotype. parents will be returned', stacklevel=3) return parent1, parent2 crossover_points = np.sort( np.random.choice(np.arange(len(parent1.genotype)), replace=False, size=parameters['points_count'])) crossover_points = np.append(crossover_points, len(parent1.genotype)) # print('cross over points', crossover_points) first_idx = 0 gen1, gen2 = np.zeros(len(parent1.genotype)), np.zeros(len(parent1.genotype)) for last_idx in crossover_points: if np.random.random() <= parameters['prob']: gen2[first_idx: last_idx] = parent2.genotype[first_idx: last_idx] gen1[first_idx: last_idx] = parent1.genotype[first_idx: last_idx] # print('same') else: gen1[first_idx: last_idx] = parent2.genotype[first_idx: last_idx] gen2[first_idx: last_idx] = parent1.genotype[first_idx: last_idx] # print('not same') # print(gen1) # print(gen2) first_idx = last_idx chromosome1, chromosome2 = Chromosome(gen1, 0), Chromosome(gen2, 0) return chromosome1, chromosome2
def insert_transposition(chromosome: c.Chromosome) -> c.Chromosome: """ :param chromosome: :return: """ inserted_gene_index, source_gene_genotype, inserted_gene_genotype = \ random_select_transposition(chromosome) segment_length = rd.randint(1, Parameter.IS_elements_length) pre_index = rd.randint(0, Parameter.gene_length - segment_length) post_index = pre_index + segment_length insert_index = rd.randint(0, Parameter.IS_elements_length - 1) modified_length = post_index - pre_index + insert_index if modified_length <= Parameter.head_length: inserted_gene_genotype = \ inserted_gene_genotype[0: insert_index] + source_gene_genotype[pre_index: post_index] + \ inserted_gene_genotype[modified_length:] else: over_length = modified_length - Parameter.head_length inserted_gene_genotype = \ inserted_gene_genotype[0: insert_index] + source_gene_genotype[pre_index: post_index - over_length] + \ inserted_gene_genotype[Parameter.head_length:] chromosome.genes[inserted_gene_index].genotype = inserted_gene_genotype chromosome.update() return chromosome
def test_crossover_at_given_index_longer_chromosomes( self, first_chromosome_seed: str, second_chromosome_seed: str, crossover_index: int, first_chromosome_crossed_seed: str, second_chromosome_crossed_seed: str): first_chromosome = Chromosome(first_chromosome_seed) second_chromosome = Chromosome(second_chromosome_seed) first_chromosome_crossed = CrossedChromosomes(first_chromosome, second_chromosome, crossover_index).first() second_chromosome_crossed = CrossedChromosomes( first_chromosome, second_chromosome, crossover_index).second() self.assertEqual( first_chromosome_crossed, Chromosome(first_chromosome_crossed_seed), f"crossed: {first_chromosome_crossed.to_string()}, seed: {first_chromosome_crossed_seed}" ) self.assertEqual( second_chromosome_crossed, Chromosome(second_chromosome_crossed_seed), f"crossed: {second_chromosome_crossed.to_string()}, seed: {second_chromosome_crossed_seed}" )
def test_mutate(self, chromosome_seed: str, mutated_seed: str, injected_random_number: "List"): chromosome = Chromosome(chromosome_seed) chromosome_mutated = chromosome.mutate(injected_random_number) self.assertEqual(chromosome_mutated, Chromosome(mutated_seed))
def start(self, gen_max, pop_size): """ :param gen_max: maximum number of generations :param pop_size: initial population size :return: best solution found """ self.population = [] self.population_size = 0 # self.results = [] self.best = None gen = 1 # from first generation self.generate_population(pop_size) # generate initial population self.population_size = pop_size if not quite: pretty_print('Initital:') self.print_chromosomes(self.population) while gen <= gen_max: gen += 1 # p = 1 new_population = list() for p in range(self.population_size): parents = random.sample(range(self.population_size), 2) newbie = self.crossover(self.population[parents[0]], self.population[parents[1]]) # TODO check child? # newbie.mutate() fit = self.fitness(newbie) # self.results.append((newbie, fit)) new_population.append(newbie) if self.best is None or self.best[1] > fit: self.best = (newbie, fit) if not quite: pretty_print('%dth generation (after crossover): ' % gen) self.print_chromosomes(new_population) self.selection(self.population, new_population) if not quite: pretty_print('After selection (after crossover): ') self.print_chromosomes(self.population) mutants = [] for chrom in self.population: new_v = [] new_v.extend(chrom.get()) new_chrom = Chromosome(new_v) new_chrom.mutate() fit = self.fitness(new_chrom) mutants.append(new_chrom) if self.best is None or self.best[1] > fit: self.best = (chrom, fit) if not quite: pretty_print('%dth generation (after mutations): ' % gen) self.print_chromosomes(mutants) self.selection(self.population, mutants) if not quite: pretty_print('After selection (after mutations): ') self.print_chromosomes(self.population) return self.best
def gene_transposition(chromosome: c.Chromosome) -> c.Chromosome: pre_gene_index = rd.randint(0, Parameter.num_of_genes - 1) post_gene_index = rd.randint(0, Parameter.num_of_genes - 1) chromosome.genes[pre_gene_index], chromosome.genes[post_gene_index]\ = chromosome.genes[post_gene_index], chromosome.genes[pre_gene_index] chromosome.update() return chromosome
def nwox_crossover(parent1, parent2, parameters=None): """ Non-Wrapping Order Crossover (NWOX) - (Cicirello 2006) :param parent1: First parent chromosome, Gene, np.array with len [n^2,1] :param parent2: Second parent chromosome, Gene, np.array with len [n^2,1] :return: return two chromosome for each children, Chromosome """ crossover_points = np.sort(np.random.choice(np.arange(len(parent1.genotype)), replace=False, size=2)) gen1, gen2 = np.copy(parent1.genotype), np.copy(parent2.genotype) # First, all those bits are left as hole which are presenting within the cut-points in other parent gen1 = np.setdiff1d(gen1, parent2.genotype[crossover_points[0]: crossover_points[1] + 1], assume_unique=True) gen2 = np.setdiff1d(gen2, parent1.genotype[crossover_points[0]: crossover_points[1] + 1], assume_unique=True) gen1 = np.concatenate((gen1[:crossover_points[0]], parent2.genotype[crossover_points[0]: crossover_points[1] + 1], gen1[crossover_points[0]:])) gen2 = np.concatenate((gen2[:crossover_points[0]], parent1.genotype[crossover_points[0]: crossover_points[1] + 1], gen2[crossover_points[0]:])) chromosome1, chromosome2 = Chromosome(gen1, 0), Chromosome(gen2, 0) return chromosome1, chromosome2
def order_one_crossover(parent1, parent2, parameters=None): """ :param parent1: First parent chromosome, Gene, np.array with shape = (1,len(parent)) :param parent2: Second parent chromosome, Gene, np.array with shape = (1,len(parent)) :return """ parent1 = parent1.genotype() parent2 = parent2.genotype() n = len(parent1.genotype) start_substr = random.randint(0, n - 2) end_substr = random.randint(start_substr + 1, n) child1 = parent1.copy() child2 = parent2.copy() j = end_substr i = end_substr while j != start_substr: if not parent1[i] in child2[start_substr:end_substr]: child2[j] = parent1[i] j = (j + 1) % n i = (i + 1) % n j = end_substr i = end_substr while j != start_substr: if not parent2[i] in child1[start_substr:end_substr]: child1[j] = parent2[i] j = (j + 1) % n i = (i + 1) % n return Chromosome(child1, 0), Chromosome(child2, 0)
def time_to_procreate(): selected_index = [] for i in range(0, len(population)): random_number = uniform(0, 1.0) if random_number < crossover_rate: selected_index.append(i) for in_list_index, first_parent_index in enumerate(selected_index): second_parent_index = 0 if in_list_index == len(selected_index) - 1: second_parent_index = selected_index[0] else: second_parent_index = selected_index[in_list_index + 1] first_parent = population[first_parent_index] second_parent = population[second_parent_index] random_point_genes = 2 first_parent_genes = first_parent.give_group_of_gens( random_point_genes) second_parent_genes = second_parent.data second_parent_genes.pop(random_point_genes) second_parent_genes.insert(random_point_genes, first_parent_genes) son = Chromosome(second_parent_genes, fitness_function_procedure) # Checamos si el hijo supera al padre en fitness son.calculate_value() if son.result > first_parent.result: population.pop(first_parent_index) population.insert(first_parent_index, son)
def elite_evaluation(new_population, old_population, problem): # Verify if crossover returned better individuals new_population.sort( key=lambda x: Chromosome.compute_makespan(x, problem)) old_population.sort( key=lambda x: Chromosome.compute_makespan(x, problem)) min_value_op = Chromosome.compute_makespan(new_population[0], problem) min_value_np = Chromosome.compute_makespan(old_population[0], problem) if min_value_np < min_value_op: return new_population else: elite_population = [] # elite selection define_10 = int(len(old_population) * 0.1) best_10 = old_population[0:define_10] # This takes only 90% of the best best_90_sel = new_population[:-define_10] elite_population.extend(best_10) elite_population.extend(best_90_sel) assert len(elite_population) == len(new_population) return elite_population
def initialisation(self): for _ in range(0, self.__param['popSize']): c = Chromosome(self.__problParam) path = c.repres shuffle(path) c.repres = path self.__population.append(c)
def _mate_one(pair): mother, father = pair n = len(mother) inv1 = inversion(list(mother.genes)) inv2 = inversion(list(father.genes)) line = randint(0, n - 1) new_inv1 = inv1[0:line] + inv2[line:n] new_inv2 = inv2[0:line] + inv1[line:n] # line1 = randint(0, n - 1) # line2 = randint(0, n - 1) # # if line1 > line2: # line1, line2 = line2, line1 # # new_inv1 = inv2[0:line1] + inv1[line1:line2] + inv2[line2:n] # new_inv2 = inv1[0:line1] + inv2[line1:line2] + inv1[line2:n] child1 = permutation(new_inv1) child2 = permutation(new_inv2) child1_chrome = Chromosome(child1) child2_chrome = Chromosome(child2) return child1_chrome, child2_chrome
def doCrossover(self, generation, i, index): chromo = generation.chromosomes length = chromo[0].length cut = random.randint(1, length - 1) parent1 = chromo[index[i]] parent2 = chromo[index[i + 1]] genesChild1 = parent1.genes[0:cut] + parent2.genes[cut:length] genesChild2 = parent1.genes[cut:length] + parent2.genes[0:cut] child1 = Chromosome(genesChild1, len(genesChild1)) child2 = Chromosome(genesChild2, len(genesChild2)) # ----clustering---- clustering = Clustering(generation, self.data, self.kmax) child1 = clustering.calcChildFit(child1) child2 = clustering.calcChildFit(child2) # ------------------- listA = [] listA.append(parent1) listA.append(parent2) listA.append(child1) listA.append(child2) # sort parent and child by fitness / dec listA = sorted(listA, reverse=True, key=lambda elem: elem.fitness) generation.chromosomes[index[i]] = listA[0] generation.chromosomes[index[i + 1]] = listA[1] return generation
def __init__(self, parent1_id, parent2_id, num_nodes, level=2, gene_type='MOTIF'): Chromosome.__init__(parent1_id, parent2_id, gene_type) if level < 2: raise ValueError('Invalid level value') self._size = num_nodes self._level = level self._genes = None self._num_params = 0
def _generate_random_population(self): self.chromosomes = [] for _ in range(POP_SIZE): c = Chromosome(self.goal) c.calculate_fitness(self.graph, self.removed_graph) self.chromosomes.append(c) # sort population self.chromosomes = sorted(self.chromosomes, key=lambda x: x.fitness)
def crossover(first_parent, second_parent): crossover_point = np.random.randint(1, 3) first_parent = copy.deepcopy(first_parent.get_genes()) second_parent = copy.deepcopy(second_parent.get_genes()) first_child = Chromosome(first_parent[:crossover_point]+second_parent[crossover_point:]) second_child = Chromosome((second_parent[:crossover_point] + first_parent[crossover_point:])) return [first_child, second_child]
def initialisation(self): for _ in range(0, self.pop_size): r = [i for i in range(1, self.max_value)] shuffle(r) r = [0] + r r.append(0) cr = Chromosome(self.min_value, self.max_value, self.dim) cr.repres = r self.population.append(cr)
def single_point_crossover(first_parent, second_parent, crossover_point): first_parent = first_parent.get_genes() second_parent = second_parent.get_genes() first_child = Chromosome(first_parent[:crossover_point] + second_parent[crossover_point:]) second_child = Chromosome( (second_parent[:crossover_point] + first_parent[crossover_point:])) return [first_child, second_child]
def position_based_crossover(parent1, parent2, parameters=None): """ :param parameters: dictionary of parameters that key = parameter name and value = parameter value :param parent1: First parent chromosome, Gene, np.array with size [1,n] :param parent2: Second parent chromosome, Gene, np.array with size [1,n] :return: return two chromosome for each children, Chromosome """ def find_cycle(parent1, parent2, cycle, first): ind = np.where(parent2 == cycle[-1])[0][0] cycle.append(parent1[ind]) if parent1[ind] == first: return cycle return find_cycle(parent1, parent2, cycle, first) par_size = len(parent1.genotype) points = np.random.choice(par_size, 3, replace=False) gen1, gen2 = np.zeros(par_size, dtype=np.int), np.zeros(par_size, dtype=np.int) for i in range(len(points)): gen1[points[i]], gen2[points[i]] = parent2.genotype[points[i]], parent1.genotype[points[i]] cycle_index = [] for i in range(par_size): if i not in points: cycle = [parent2.genotype[i]] cycle_index.append(find_cycle(parent1.genotype, parent2.genotype, cycle, parent2.genotype[i])) else: cycle_index.append([]) for i in range(par_size): if i not in points: cycle = cycle_index[i] for j in range(1, len(cycle)): if cycle[j] not in gen1: gen1[i] = cycle[j] break cycle_index = [] for i in range(par_size): if i not in points: cycle = [parent1.genotype[i]] cycle_index.append(find_cycle(parent2.genotype, parent1.genotype, cycle, parent1.genotype[i])) else: cycle_index.append([]) for i in range(par_size): if i not in points: cycle = cycle_index[i] for j in range(1, len(cycle)): if cycle[j] not in gen2: gen2[i] = cycle[j] break chromosome1, chromosome2 = Chromosome(gen1, 0), Chromosome(gen2, 0) return chromosome1, chromosome2
def test_optional_threshold(self, chromosome_seed: str, mutated_seed: str, injected_random_number: "List", threshold: float): chromosome = Chromosome(chromosome_seed) chromosome_mutated = chromosome.mutate(injected_random_number, threshold=threshold) self.assertEqual(chromosome_mutated, Chromosome(mutated_seed))
def Mutation(chrom, alphabet, mutation_amount): for i in range(mutation_amount): char_to_replace = random.choice(chrom.Get_Value()) new_char = random.choice(alphabet) chrom = Chromosome(chrom.Get_Value().replace(char_to_replace, new_char, 1)) return chrom
def crossover(c1, c2): '''Takes as input 2 chromosomes and returns a new chromosome which is a mix of the first 2''' c_new = Chromosome(len(advertisements)) for i in range(len(advertisements)): if i % 2 == 0: c_new.array[i] = c1.array[i] else: c_new.array[i] = c2.array[i] return c_new
def initialPopulation(self, variable_config): pop = [] chrom = Chromosome(variable_config) for i in range(variable_config.D * variable_config.Np): pop.append(chrom.initialChromosome(variable_config)) pop = np.array(pop) pop = pop.reshape( (variable_config.Np, (variable_config.D * variable_config.n))) return pop
def ga(pixel_arr, constraints, pop_size=100, g_max=40, p_c=0.6, p_m=0.4, verbose=True): start_time = time.time() num_rows, num_cols = pixel_arr.shape[0], pixel_arr.shape[1] population = [Chromosome(pixel_arr) for i in range(pop_size)] avg_fitness = sum(c.fitness for c in population) best_ind = max(population, key=lambda c: c.fitness) if verbose: print("Generation 0:") print("Best fitness:", best_ind.fitness, "Avg fitness:", avg_fitness) print("Number of segmentations:", max(best_ind.segments)) print("Edge value:", best_ind.edge_value) print("Connectivity:", best_ind.connectivity) print("Deviation:", best_ind.deviation) print(f"Initial generation time: {time.time() - start_time}\n", flush=True) for g in range(1, g_max+1): start_time = time.time() offspring = [] for i in range(pop_size//2): p1 = parent_selection(population) p2 = parent_selection(population) if random() < p_c: cutoff = randint(0, len(p1.genotype)-1) c1_geno = crossover(p1.genotype, p2.genotype, cutoff) c2_geno = crossover(p2.genotype, p1.genotype, cutoff) else: c1_geno = p1.genotype c2_geno = p2.genotype if random() < p_m: c1_geno = mutate(c1_geno, num_rows, num_cols, arr, constraints) if random() < p_m: c2_geno = mutate(c2_geno, num_rows, num_cols, arr, constraints) c1 = Chromosome(pixel_arr, c1_geno) c2 = Chromosome(pixel_arr, c2_geno) offspring.append(c1) offspring.append(c2) population = elitist_replacement(population, offspring) avg_fitness = sum(c.fitness for c in population) best_ind = max(population, key=lambda c: c.fitness) if verbose: print(f"Generation {g}:") print("Best fitness:", best_ind.fitness, "Avg fitness:", avg_fitness) print("Number of segmentations:", max(best_ind.segments)) print("Edge value:", best_ind.edge_value) print("Connectivity:", best_ind.connectivity) print("Deviation:", best_ind.deviation) print(f"Time elapsed: {time.time() - start_time}\n", flush=True) return best_ind
def test_exe(self): p1 = Chromosome("111100111100120000000013") p2 = Chromosome("000012131313111112001112") crossover_point = 4 children = OnePoint().exe(p1, p2, crossover_point) expected_1 = Chromosome("111112131313111112001112") expected_2 = Chromosome("000000111100120000000013") self.assertEqual(children[0].solution, expected_1.solution) self.assertEqual(children[1].solution, expected_2.solution)
def tournament_pair(self): mother = self.getByTournament() father = self.getByTournament() # create larger population size = self.params["NumChromes"] mothers = [Chromosome(str(mother)) for i in range(0, size/2)] fathers = [Chromosome(str(father)) for i in range(0, size/2)] return zip(mothers, fathers)
def testRecombinate(): first = Chromosome() second = Chromosome() print(first.dnArray) print(second.dnArray) print(first.arithmeticArray) print(second.arithmeticArray) first.recombinate(second) print(first.dnArray) print(second.dnArray) print(first.arithmeticArray)
def populate(self, size, chromosome_blueprint): self.size = size self.gene_count = len(chromosome_blueprint) for n in range(0, size): c = Chromosome.construct(chromosome_blueprint) self.chromosomes.append(c)
def crossover(parent1, parent2, p_crossover): ''' Performs crossover with the parents to produce the offspring :param parent1: :param parent2: :param p_crossover: :param p_mutation: :return: tuple (child1, child2) ''' #par1_chromo = parent1['chromosome'] #par2_chromo = parent2['chromosome'] #child1_chromo = copy.deepcopy(par1_chromo) #child2_chromo = copy.deepcopy(par2_chromo) #gets the arrays with values to perform the exchange p1_array = parent1['chromosome'].to_array() p2_array = parent2['chromosome'].to_array() #initially, children are copies of parents c1_array = copy.copy(p1_array) c2_array = copy.copy(p2_array) assert len(c1_array) == len(c2_array) length = len(c1_array) if random.random() < p_crossover: #select crossover point xover_point = random.randint(1, length - 1) #print type(par1_chromo._genes), type(child1_chromo._genes) #performs one-point exchange around the xover point c1_array[0: xover_point] = p1_array[0: xover_point] c1_array[xover_point: length] = p2_array[xover_point: length] c2_array[0: xover_point] = p2_array[0: xover_point] c2_array[xover_point: length] = p1_array[xover_point: length] #builds new chromosomes from the (possibly crossovered) arrays child1_chromo = Chromosome.from_array(c1_array) child2_chromo = Chromosome.from_array(c2_array) return ( {'chromosome': child1_chromo, 'fitness': 0, 'reliability': 0}, {'chromosome': child2_chromo, 'fitness': 0, 'reliability': 0} )
def get_missing_chromosomes(self): missing_chromosomes = [] for name, length in Chromosome.sorted_chromosome_length_tuples(self.assembly): chromosome = Chromosome(name, self.assembly) filepath = chromosome.path() if not os.path.isfile(filepath): missing_chromosomes.append(name) else: expected_size = length + len(chromosome.header()) + 1 size = os.path.getsize(filepath) if size != expected_size: missing_chromosomes.append(name) os.remove(filepath) return missing_chromosomes
def multiply(self): """Generate offspring until we're back to the right population size. """ while len(self.chromosomes) < self.size: x = random.choice(self.chromosomes) y = random.choice(self.chromosomes) chromosome = Chromosome.offspring(x, y, self.crossover_rate, self.mutation_rate) self.chromosomes.append(chromosome)
def generate_new_population(M, seed=True): chrs=[] if seed: # Seeding one chromosome with one # minmin chromosome for _ in itertools.repeat(None, P_SIZE-1): chrs.append(Chromosome(M)) # Seed min-min ch = Chromosome(M, tabu_list=None, empty=True) mapping = minmin.run(M) if DEBUG: print mapping, mapping.makespan() for t in range(mapping._model.ntasks): ch.map.assign(t, mapping.machine(t)) chrs.append(ch) print "Seeded chromosome value:", ch.value() else: # No seeding happens here for _ in itertools.repeat(None, P_SIZE): chrs.append(Chromosome(M)) return chrs
def download_chromosomes(self): to_download = self.get_missing_chromosomes() self.log("Downloading {} chromosomes".format(len(to_download))) for name in to_download: chromosome = Chromosome(name, self.assembly) self.log(chromosome.path()) path = chromosome.path() directory = os.path.dirname(chromosome.path()) if not os.path.isdir(directory): os.makedirs(directory) self.log('created directory {}'.format(directory), True) self.log('Downloading {} to {}'.format(self.uri + chromosome.filename(), path)) r = requests.get(self.uri + chromosome.filename(), stream=True) with open(path, 'wb') as fd: for chunk in r.iter_content(chunk_size=1024): fd.write(chunk) self.log('Complete') run_build_test_suite(self.assembly)
def setUp(self): self.chromosome_manager = ChromosomeManager(42) self.chromosome = Chromosome(self.chromosome_manager)
class ChromosomeTestCase(unittest.TestCase): chromosome = None def setUp(self): self.chromosome_manager = ChromosomeManager(42) self.chromosome = Chromosome(self.chromosome_manager) def test_str(self): self.chromosome.binary_string = '010111000011101100101010011111010100' self.assertEqual(str(self.chromosome), '010111000011101100101010011111010100') def test_evaluation_with_correct_data(self): self.chromosome.binary_string = '010111000011101100101010011111010100' self.chromosome.evaluate(5) self.assertEqual(self.chromosome.result, 5) self.assertEqual(self.chromosome.score, 1e18) def test_evaluation_with_incorrect_data(self): self.chromosome.binary_string = '111111111111111111111111111111111111' self.chromosome.evaluate(20) self.assertEqual(self.chromosome.result, 0) self.assertEqual(self.chromosome.score, 0.05) def test_evaluation_with_correct_and_incorrect_data(self): self.chromosome.binary_string = '011011100001101010110101100110111100' self.chromosome.evaluate(10) self.assertEqual(self.chromosome.result, 11) self.assertEqual(self.chromosome.score, 1) def test_evaluation_with_zero_division(self): self.chromosome.binary_string = '001011111111111111111111110111110000' self.chromosome.evaluate(5) self.assertEqual(self.chromosome.result, 2) self.assertEqual(self.chromosome.score, 1 / 3) def test_fill_with_random_values(self): self.chromosome.fill_with_random_values() self.assertEqual(len(self.chromosome.binary_string), 36) for char in self.chromosome.binary_string: self.assertTrue(0 <= int(char) <= 1) def test_mutate(self): original_binary_string = '010111000011101100101010011111010100' self.chromosome.binary_string = original_binary_string mutated_chars = self.chromosome.mutate(0.1) levenshtein_distance = self._get_levenshtein_distance(original_binary_string, self.chromosome.binary_string) self.assertEqual(mutated_chars, levenshtein_distance) def test_mutate_full(self): original_binary_string = '010111000011101100101010011111010100' reversed_string = '101000111100010011010101100000101011' self.chromosome.binary_string = original_binary_string mutated_chars = self.chromosome.mutate(1) self.assertEqual(mutated_chars, 36) self.assertEqual(self.chromosome.binary_string, reversed_string) def _get_levenshtein_distance(self, string1, string2): self.assertEqual(len(string1), len(string2)) length = len(string1) different_chars_count = 0 for i in range(0, length): if string1[i] != string2[i]: different_chars_count += 1 return different_chars_count
def testComputeSum(): first = Chromosome() print(toRealExpression(first.arithmeticArray)) first.computeSum()
def prepare_chromosomes(size): Chromosome._possible_splits = Chromosome.generate_possible_splits(size) CircularChromosome._possible_splits = CircularChromosome.generate_possible_splits(size)