コード例 #1
0
def genetic():
    ITERATIONS = 30
    POP_SIZE = 40
    CROSSOVER_RATE = 0.5
    MUTATION_RATE = 0.01
    TOURNAMENT_SIZE = 6
    task = read('generatedTaskFile.csv')
    print("Here it goes...")
    population = init_population(task.numberOfObjects, POP_SIZE, task)
    i = 0
    while i < ITERATIONS:
        print("New iteration")
        j = 0
        new_population = Population(task)
        new_population.listOfIndividuals = []
        while j < POP_SIZE:
            parent1 = tournament(population, TOURNAMENT_SIZE, task)
            parent2 = tournament(population, TOURNAMENT_SIZE, task)
            child = Individual()
            child.itemsTaken = crossover(parent1, parent2, CROSSOVER_RATE)
            mutate(child, MUTATION_RATE)
            new_population.addIndividualToPopulation(child)
            j += 1
        population = new_population
        i += 1
    return population.best()
コード例 #2
0
def crossover_onepoint(p1, p2, mu, crossover_rate, passes):
    c1 = copy.deepcopy(p1)
    c2 = copy.deepcopy(p2)

    #    alpha=0.3

    count = 0
    point = np.random.randint(0, 32)
    for list1, list2 in zip(p1['table'], p2['table']):
        if (count >= point):
            c1['table'][count][1] = list2[1]
            c2['table'][count][1] = list1[1]
        count = count + 1
        if (count >= 32):
            break

    c1m = mutate.mutate(c1, mu)
    c2m = mutate.mutate(c2, mu)

    fs.finalState(c1m, passes)
    fit.calculate_fitness(c1m)

    fs.finalState(c1m, passes)
    fit.calculate_fitness(c1m)

    return c1m, c2m
コード例 #3
0
def test_mutate_substitutions():
    an_instance = genome.Genome()
    an_instance.expand(n=10)
    a_sequence = copy_genome(an_instance.sequence_A)
    mutate.mutate(an_instance, {'singles': 50, 'expansions': 0, 'deletions': 0})
    set_A = set(an_instance.sequence_A)
    set_B = set(a_sequence)
    assert len(set_A.intersection(set_B)) < len(a_sequence)  # overlap
コード例 #4
0
def test_mutate_expansions():
    an_instance = genome.Genome()
    an_instance.expand(n=10)
    a_sequence = copy_genome(an_instance.sequence_A)
    mutate.mutate(an_instance, {
        'singles': 0.0,
        'expansions': 50.0,
        'deletions': 0.0}
    )
    assert len(an_instance.sequence_A) > len(a_sequence)
コード例 #5
0
    def nextGen(self):
        self.save()
        totalAvgFit = 0
        remaining = 0
        avgPopFit = 0
        for spec in self.populationSpecies:
            remaining += spec.removeHalf()
            tmp = spec.calcAvgFitness()
            totalAvgFit += tmp
            avgPopFit += (tmp * len(spec.subpopulation))
        children = []
        #self.removeStale()
        self.removeWeak()

        print()
        print("Generation", self.generationNumber)
        print("Max Fitness:", self.maxFitness)
        print("Innovation Number:", self.globalInnovationNumber)
        print("No. of Species:", len(self.populationSpecies))
        print("Avg pop fitness:", avgPopFit / remaining)
        print("Total Population:", self.index - 1)

        for spec in self.populationSpecies:
            n = math.floor(
                spec.avgFitness / totalAvgFit) * self.numberOfIndividuals - 1
            for i in range(n):
                ch = spec.getChild()
                if ch:
                    self.globalInnovationNumber, ch = mutate.mutate(
                        ch, self.globalInnovationNumber)
                    children.append(ch)
            spec.removeAllExceptOne()

        while self.numberOfIndividuals > len(children) + len(
                self.populationSpecies):
            spec = self.populationSpecies[random.randrange(
                0, len(self.populationSpecies))]
            ch = spec.getChild()
            if ch:
                self.globalInnovationNumber, ch = mutate.mutate(
                    ch, self.globalInnovationNumber)
                children.append(ch)

        M = self.numberOfIndividuals - len(self.populationSpecies)
        for i in range(0, M):
            self.addChromosome(children[i])
        print("Children produced:", M)
        print()

        self.generationNumber += 1
        self.index = 0
        self.maxFitness = 0
コード例 #6
0
 def next_generation(self, mutation_setup):
     """ Swap current population with new individuals
     """
     # matching individuals
     # sorted by fitness
     self.individuals.sort(key=lambda x: x.fitness)
     for i, m_individual in enumerate(self.individuals):
         if m_individual.paired_with != -1:
             continue  # skip already matched individuals
         # for now: match next one
         m_try = i + 1 if i < len(self.individuals) else i - randint(1, 3)
         # safechecks
         if m_try < 0 or m_try >= len(self.individuals):
             continue
         if m_try == i:
             continue
         if self.individuals[m_try].paired_with != -1:
             continue
         # assign mate
         m_individual.paired_with = m_try
         self.individuals[m_try].paired_with = i
     # mutations
     for i, _ in enumerate(self.individuals):
         mutate(self.individuals[i].genome, mutation_setup)
     # crossing overs
     for i, _ in enumerate(self.individuals):
         if self.individuals[i].paired_with == -1:
             continue
         crossover(self.individuals[i].genome, events=1)
     # offspring
     new_individuals = []
     for i, o_individual in enumerate(self.individuals):
         if o_individual.paired_with == -1:
             continue  # skip lone individuals
         # probability of offspring dictated by fitness
         # algorithm: 100% for every full 1, probability
         #   0.1=10% for all other
         offspring_to_make = o_individual.fitness
         while offspring_to_make > 0.01:
             if offspring_to_make < 1:
                 if randint(0, 100) > offspring_to_make * 100:
                     break  # under 1 -> no more offspring
             offspring_to_make -= 1
             new_individuals.append(
                 Individual(genome=Genome(
                     cod_seqA=o_individual.genome.haploid(),
                     cod_seqB=self.individuals[
                         o_individual.paired_with].genome.haploid(),
                 ), ))
     # finish line
     self.individuals = new_individuals
コード例 #7
0
def SetupNextGen(gl: Global, evals: List[Evaluation], scores: List[Evaluation],
                 args):
    gl.individuals = selection.reproduce(evals, gl.nIndividuals)
    scores.sort(reverse=True)
    if not args.trainingmode:
        Simulate(gl, scores[0].individual)
    print("BestScore: " + str(scores[0].score))
    sumVal = 0
    for ev in scores:
        sumVal += ev.score
    print("Average Score: " + str(sumVal / gl.nIndividuals))
    gl.bestIndi = scores[0].individual
    for indi in gl.individuals:
        mutate.mutate(indi, gl, 2, 0.1, 0.1, 0.2, 0.6)
コード例 #8
0
ファイル: main.py プロジェクト: foofaraw/machine-learning
def get_best_from_population(population):
    result = np.empty(ITERATIONS)
    for i in range(ITERATIONS):
        new_population = Population()
        while new_population.population_size < POPULATION_SIZE:
            parent1 = tournament(population, TOURNAMENT_SIZE)
            parent2 = tournament(population, TOURNAMENT_SIZE)
            child = crossover(parent1, parent2, CROSSOVER_RATE)
            mutate(child, MUTATION_RATE)
            new_population.add_individual(child)
            print('.', end='')
        population = new_population
        result[i] = population.get_best_individual().evaluate()
        print('-', end='')
    return result
コード例 #9
0
def runGeneticAlgorithim(populationsize, generations):
    firstGen = ab.genPool(populationsize, int(sys.argv[5]))
    for gen in range(generations):
        if gen == 0:
            lastGen = ab.breed(firstGen, gen, float(sys.argv[4]))
            for x in range(len(lastGen)):
                lastGen[x] = mt.mutate(lastGen[x])
        else:
            for x in range(len(lastGen)):
                lastGen[x] = mt.mutate(lastGen[x])
            lastGen = ab.breed(lastGen, gen, float(sys.argv[4]))
        for aptamer in lastGen:
            if hp.hairpin(aptamer[1]) != 0:
                lastGen.remove(aptamer)
    return [firstGen, lastGen]
コード例 #10
0
ファイル: minion.py プロジェクト: chopper6/TopologyEvolution
def evolve_minion(worker_file, gen, rank, output_dir):
    t_start = time.time()

    worker_ID, seed, pop_size, num_return, randSeed, advice, BD_table, biases, configs = load_worker_file(worker_file)
    output_dir, fitness_direction, population = init_minion(configs, randSeed, seed, pop_size)

    for p in range(pop_size):
        mutate.mutate(configs, population[p].net, biases=biases)
        pressurize.pressurize(configs, population[p], None, advice)  # None: don't write instances to file

    population = sort_popn(population, fitness_direction)
    write_out_worker(output_dir + "/to_master/" + str(gen) + "/" + str(rank), population, num_return)
    report_timing(t_start, rank, gen, output_dir)

    return len(population[0].net.nodes())
コード例 #11
0
ファイル: GA-soap.py プロジェクト: wjm41/CovidGenetic
def reproduce(population, fitness, mutation_rate):
    """
    Generates next generation of population by probabilistically choosing mating pool based on fitness, then
    probabilistically reproducing molecules in the mating pool and randomly mutating the children

    :param population: list of RDKit molecules
    :param fitness: probability distribution of same length as population, returned by pop_fitness
    :param mutation_rate: hyperparameter determining the likelihood of mutations occuring

    :return: new_population
    """
    mating_pool = []
    for i in range(len(population)):
        mating_pool.append(np.random.choice(population, p=fitness))

    new_population = []
    for n in range(len(population)):
        parent_A = random.choice(mating_pool)
        parent_B = random.choice(mating_pool)
        # print Chem.MolToSmiles(parent_A),Chem.MolToSmiles(parent_B)
        new_child = co.crossover(parent_A, parent_B)
        # print new_child
        if new_child is not None:
            new_child = mu.mutate(new_child, mutation_rate)
            # print("after mutation",new_child)
            if new_child is not None:
                new_population.append(new_child)

    return new_population
コード例 #12
0
 def initializePopulation(self):
     for i in range(self.numberOfIndividuals):
         temp = deepcopy(chromosome())
         #for j in range(100):
         self.globalInnovationNumber, temp = mutate.mutate(
             temp, self.globalInnovationNumber)
         self.addChromosome(temp)
コード例 #13
0
def crossover(p1, p2, mu, crossover_rate):
    c1 = copy.deepcopy(p1)
    c2 = copy.deepcopy(p2)

    #    alpha=0.3

    count = 0
    for l1, l2 in zip(p1, p2):
        if (np.random.uniform(0, 1) <= crossover_rate):
            c1[count] = l2
            c2[count] = l1
        count = count + 1

    c1m = mutate.mutate(c1, mu)
    c2m = mutate.mutate(c2, mu)
    return c1m, c2m
コード例 #14
0
ファイル: genetic.py プロジェクト: LSaldyt/firma
def genetic(f):
    N = 1000
    x = 2
    select_p = 0.5
    mutate_chance = 0.01

    inputs = list(range(6))
    outputs = [f(x) for x in inputs]
    population = [generate() for i in range(N)]
    #results = [interpret(code)(x) for code in population]
    #pprint(results)

    while True:
        scores = [evaluate(code, inputs, outputs) for code in population]
        size = len(scores)
        selected_indices = list(sorted(range(size), key=lambda t : scores[t]))[:int(select_p * size)]
        selected = [population[i] for i in selected_indices]
        selected_scores = [scores[i] for i in selected_indices]
        if 0.0 in selected_scores:
            print('Selected:')
            pprint(selected[0])
            break
        crossover(selected)
        mutated = [mutate(code) if random.random() < mutate_chance else code for code in selected]
        population = [generate() for i in range(N)]
コード例 #15
0
ファイル: genetic.py プロジェクト: Ogurecher/ML_Lab2
def genetic(parameters):
    train_losses, test_losses = [], []
    training_object_count, feature_count, training_features, training_labels, test_features, test_labels\
        = prepare_data.read_from_file(filename)

    num_generations = parameters['num_generations']
    num_chromosomes = parameters['num_chromosomes']
    num_parents = int(num_chromosomes * parameters['parent_proportion'])
    num_children = num_chromosomes - num_parents
    num_genes = feature_count

    chromosomes_shape = (num_chromosomes, num_genes + 1)
    chromosomes = np.random.uniform(low=-parameters['random_gene_amplitude'],
                                    high=parameters['random_gene_amplitude'],
                                    size=chromosomes_shape)

    for generation in range(num_generations):
        parents = choose_parents(chromosomes, training_features,
                                 training_labels, num_parents,
                                 parameters['regularization_strength'])
        children = reproduce(parents, num_children, num_parents, num_genes + 1)

        children = mutate(children, parameters['mutation_amplitude'])
        chromosomes = np.concatenate((parents, children), axis=0)

        train_loss = nrmse(predict(training_features, parents[0]),
                           training_labels)
        train_losses.append(train_loss)
        test_losses.append(
            nrmse(predict(test_features, parents[0]), test_labels))
        print('Train NRMSE: {}'.format(train_loss))

    return train_losses, test_losses, parameters
コード例 #16
0
    def geneticVRP(self):
        cus_num = len(self.dis_cus_cus)
        zonglines = []  #用于存储历代所有种群
        lines = [[0 for i in range(cus_num)] for j in range(self.popSize)]
        R = lines[0]  # 一个随机个体
        R2 = R
        R_len = [0 for i in range(self.popSize)]  # 用来存储每条路径长度

        t = 1
        while t <= self.NGen:
            print "第 %d 次迭代:" % (t)

            #生成随机初始路径
            for i in range(self.popSize):
                line = random.sample(range(1, cus_num + 1), cus_num)
                lines[i] = line

            #交叉
            farm = lines
            farm2 = farm
            for i in range(0, self.popSize, 2):
                if random.random() < self.cxPb and i < self.popSize:
                    route1 = farm[i]
                    route2 = farm[i + 1]
                    route1, route2 = intercross.intercross(route1, route2)
                    farm[i] = route1
                    farm[i + 1] = route2

            #变异
            for i in range(0, self.popSize):
                if random.random() <= self.mutPb:
                    farm[i] = mutate.mutate(farm[i])

            #群体的选择和更新
            FARM = [[0 for i in range(cus_num)] for j in range(self.popSize)]
            fitness_value, Cost, R = fitness.fitness(
                self.dis_cus_cus, self.dis_sta_cus, self.min_dis_depot,
                self.min_dis_station, self.time_win, self.tolerate_time_win,
                self.demand, farm)
            rank = [
                index
                for index, value in sorted(list(enumerate(fitness_value)),
                                           key=lambda x: x[1])
            ]
            for i in range(0, self.popSize):
                FARM[i] = farm[rank[i]]
            fitness_value_s = sorted(fitness_value)
            zonglines.append(fitness_value_s[0])
            R = FARM[0]  #更新最短路径

            t += 1

            print "最佳路径为:"
            for i in range(0, len(FARM[0])):
                print "%d," % (FARM[0][i]),

        return zonglines, R
コード例 #17
0
 def __hill_climbing(self, n_hill_climb):
     for point in self.points:
         for nn in range(n_hill_climb):
             new_point = mutate(point)
             d = Point.pareto_dominance(new_point, point)
             if d > 0:
                 self.remove_value(point)
                 self.add(new_point)
                 break
コード例 #18
0
ファイル: bio.py プロジェクト: AaronParsons/alife
 def _run(self):
     signal.signal(signal.SIGINT, signal.SIG_IGN)
     while not self._quit.is_set():
         try: d = self.dna_q.get_nowait()
         except(mpq.Empty): continue
         self.critters = self.clean(self.critters, self.max)
         try: pid = critter.hashtxt(dna.dna2txt(d))
         except(KeyError,TypeError): continue
         if random.random() < .5:
         #if False:
             try: mutate.mutate(d)
             except(TypeError,KeyError): pass
         try:
             c = critter.Critter(d)
             c.run() # run has to precede append, otherwise not threadsafe
             self.critters.append(c)
             if pid != c.my_id:
                 self.logging_q.put((self.name, pid, c.my_id))
         except: pass
コード例 #19
0
def runGeneticAlgorithim(aptamerData, generations):
    firstGen = ab.getAptamers(aptamerData)
    model = load_model(str(sys.argv[5]))  #saved trained keras model
    for gen in range(generations):
        if gen == 0:
            lastGen = ab.breed(firstGen, gen, model, float(sys.argv[4]))
            print("finished breeding")
            for x in range(len(lastGen)):
                lastGen[x] = mt.mutate(lastGen[x], model)
            print("finished mutating")
        else:
            for x in range(len(lastGen)):
                lastGen[x] = mt.mutate(lastGen[x], model)
            print("finished mutating")
            lastGen = ab.breed(lastGen, gen, model, float(sys.argv[4]))
            print("finished breeding")
        for aptamer in lastGen:
            if hp.hairpin(aptamer[1]) == True:
                lastGen.remove(aptamer)
        print("Finished gen " + str(gen + 1))
    return [firstGen, lastGen]
コード例 #20
0
ファイル: GB_GA.py プロジェクト: leelasdSI/GB-GA
def reproduce(mating_pool, population_size, mutation_rate):
    new_population = []
    while len(new_population) < population_size:
        parent_A = random.choice(mating_pool)
        parent_B = random.choice(mating_pool)
        new_child = co.crossover(parent_A, parent_B)
        if new_child != None:
            new_child = mu.mutate(new_child, mutation_rate)
            if new_child != None:
                new_population.append(new_child)

    return new_population
コード例 #21
0
ファイル: GB_GA.py プロジェクト: roysh/GB-GA
def reproduce(mating_pool, population_size, mutation_rate):
    new_population = []
    while len(new_population) < population_size:
        parent_A = random.choice(mating_pool)
        parent_B = random.choice(mating_pool)
        new_child = co.crossover(parent_A, parent_B)
        if new_child != None:
            mutated_child = mu.mutate(new_child, mutation_rate)
            if mutated_child != None:
                #print(','.join([Chem.MolToSmiles(mutated_child),Chem.MolToSmiles(new_child),Chem.MolToSmiles(parent_A),Chem.MolToSmiles(parent_B)]))
                new_population.append(mutated_child)

    return new_population
コード例 #22
0
ファイル: GB_GA.py プロジェクト: jcheminform/MolScore
def reproduce(mating_pool, mutation_rate):
    """
    Args:
        mating_pool: list of RDKit Mol
        mutation_rate: rate of mutation
    Returns:
    """
    parent_a = random.choice(mating_pool)
    parent_b = random.choice(mating_pool)
    new_child = co.crossover(parent_a, parent_b)
    if new_child is not None:
        new_child = mu.mutate(new_child, mutation_rate)
    return new_child
コード例 #23
0
def pso(dm,population_size=40):

    df=dm.copy(deep=True)

    X=df.iloc[:,:-1]
    X=np.array(X,dtype=float)
    X_=preprocessing(X)
    X=X_.copy()
    y=df.iloc[:,len(df.columns)-1]
    y=np.array(y,dtype=int)

    population_size=40
    population=population_initialisation(len(df.columns)-1,population_size=40,no_population_slots=4)

    fitness=np.zeros(population_size,dtype=float)
    historical_fitness=np.zeros(population_size,dtype=float)
    historical_position=population.copy()
    global_fitness=999999
    global_position=np.zeros(len(df.columns)-1,dtype=int)
    for i in range(0,population_size):
    	historical_fitness[i]=999999

    k=0

    while(k!=100):
        
        print('\n',k+1,'th generation in process...')
        for i in range(0,population_size):
            fitness[i]=svm_fitness(X,y,population[i])
            if(str(fitness[i])!=str(historical_fitness[i])):
                f=[fitness[i],historical_fitness[i]]
                if(f.index(min(f))==0):
                    historical_fitness[i]=(fitness[i]).copy()
                    historical_position[i]=(population[i]).copy()
            
        
            if(str(historical_fitness[i])!=str(global_fitness)):
                f=[historical_fitness[i],global_fitness]
                if(f.index(min(f))==0):
                    global_fitness=(historical_fitness[i]).copy()
                    global_position=(population[i]).copy()
        
        for i in range(0,population_size):
            population[i]=(tpmbx(population[i],global_position,historical_position[i])).copy()
            population[i]=(mutate(population[i])).copy()
        k=k+1

    features_best=list(*(np.where(global_position==1)))
    acc=svm_fitness(X,y,global_position,1,1)

    return [features_best,acc]
コード例 #24
0
def crossover(p1, p2, mu, crossover_rate, passes):
    c1 = copy.deepcopy(p1)
    c2 = copy.deepcopy(p2)

    #    alpha=0.3

    count = 0
    for list1, list2 in zip(p1['table'], p2['table']):
        if (np.random.uniform(0, 1) <= crossover_rate):
            c1['table'][count][1] = list2[1]
            c2['table'][count][1] = list1[1]
        count = count + 1

    c1m = mutate.mutate(c1, mu)
    c2m = mutate.mutate(c2, mu)

    fs.finalState(c1m, passes)
    fit.calculate_fitness(c1m)

    fs.finalState(c2m, passes)
    fit.calculate_fitness(c2m)

    return c1m, c2m
コード例 #25
0
ファイル: GB-GA.py プロジェクト: ncfirth/GB-GA
def reproduce(mating_pool, population_size, mutation_rate):
    new_population = []
    for n in range(population_size):
        parent_A = random.choice(mating_pool)
        parent_B = random.choice(mating_pool)
        #print Chem.MolToSmiles(parent_A),Chem.MolToSmiles(parent_B)
        new_child = co.crossover(parent_A, parent_B)
        #print new_child
        if new_child != None:
            new_child = mu.mutate(new_child, mutation_rate)
            #print "after mutation",new_child
            if new_child != None:
                new_population.append(new_child)

    return new_population
コード例 #26
0
 def test_mutation(self):
     room_ids = list(ROOM_INFO_DICT_1)
     chromosome = CHROMOSOME_1
     copy_chromosome = copy.deepcopy(chromosome)
     self.assertEqual(chromosome, copy_chromosome)
     chromosome = mutator.mutate(chromosome, room_ids, 1)
     self.assertNotEqual(chromosome, copy_chromosome)
     for gene in chromosome.values():
         gene_len = len(gene)
         timeslot_len = len(gene[1])
         self.assertTrue(gene_len == 3)  # 3 things in gene
         self.assertTrue(timeslot_len == 2)  # 2 elements in timeslot
         self.assertTrue(gene[1][0] >= 0)  # first timeslot 0 or more
         # second timeslot less than max timeslot
         self.assertTrue(gene[1][1] <= MAX_TIMESLOT)
         self.assertTrue(gene[1][0] < gene[1][1])  # ending after begining
コード例 #27
0
        def traverse(node):
            """DFS visit nodes from tree"""

            if node.is_root():
                sequence = Tree369.rand_seq(L)
                node.set_sequence(sequence)
            else:
                branch_length = node.get_parent().get_height(
                ) - node.get_height()
                parent_sequence = node.get_parent().get_sequence()
                mutated_sequence = mutate(parent_sequence, branch_length, mu)
                node.set_sequence(mutated_sequence)

            seq_list.append((int(node.get_label()), node.get_sequence()))
            if node.is_leaf():
                return

            traverse(node.get_children()[0])
            traverse(node.get_children()[1])
コード例 #28
0
ファイル: GB_GA.py プロジェクト: pdj196/Bachelor-project
def reproduce(mating_pool, population_size, mutation_rate):
    new_population = []
    count = 0
    while len(new_population) < population_size:
        parent_A = random.choice(mating_pool)
        parent_B = random.choice(mating_pool)
        #print Chem.MolToSmiles(parent_A),Chem.MolToSmiles(parent_B)
        new_child = co.crossover(parent_A, parent_B)
        #print new_child
        if new_child != None:
            new_child = mu.mutate(new_child, mutation_rate)
            #print "after mutation",new_child
            if new_child != None:
                mol = co.mol_OK(new_child)
                if mol != True:
                    count += 1
                else:
                    new_population.append(new_child)
            else:
                count += 1
        else:
            count += 1

    return new_population, count
コード例 #29
0
def nearly_equal(word, word2):
    if word2 in mutate.mutate(word):
        return True
コード例 #30
0
 def test_mutate_int(self):
     for _ in range(10):
         x = mutate.mutate(0)
         self.assertIn(x, [-1, 1])
コード例 #31
0
ファイル: model.py プロジェクト: Shaan-B/languagelearner
def runModel():
    lexs = [sampleLexicon(), sampleLexicon()]
    scores = [posteriorScore(lexs[0], corpus), posteriorScore(lexs[1], corpus)]
    names = ['sticky', 'MH']
    numAccepted = [0, 0]

    interval = 50

    print "alpha:", params.alpha
    print "gamma:", params.gamma
    print "kappa:", params.kappa
    print "num_iterations:", num_iterations

    print "Initial score:", scores[0]
    print "Initial lexicon:"
    utils.printLex(lexs[0])

    bestLex = lexs[0]
    bestScore = scores[0]
    icons = ['\\', '|', '/', '-']
    iconIdx = 0
    lastPrinted = bestLex

    sys.stdout.write(icons[iconIdx])
    for i in range(num_iterations):
        iconIdx = (iconIdx+1)%4
        sys.stdout.write('\b')
        sys.stdout.write(icons[iconIdx])
        sys.stdout.flush()

        if i%300==0:
            lexs[0] = bestLex
            scores[0] = bestScore

        if i%interval==0:
            sys.stdout.write('\b')
            print "Reached iteration\t", i
            print "\tsticky \tscore:", scores[0], "\tlen:", lexs[0].getLen(), "\tnum accepted:", numAccepted[0], "/", interval
            print "\tMH \tscore:", scores[1], "\tlen:", lexs[1].getLen(), "\tnum accepted:", numAccepted[1], "/", interval
            numAccepted = [0, 0]
            if i%250==0 and cmp(lastPrinted, bestLex) != 0:
                print "Current best lexicon (score = %d, len = %d):"%(bestScore, bestLex.getLen())
                print "F-score: %f, precision: %f, recall: %f"%utils.fScore(bestLex)
                utils.printLex(bestLex)
                lastPrinted = bestLex

        for j in range(len(lexs)):
            lex = lexs[j]
            score = scores[j]
            temp = 6000

            newLex = mutate(lex)
            newScore = posteriorScore(newLex, corpus)

            prob = np.exp(newScore - score) if newScore<score else 1 # Scores are in log space
            sys.stdout.write('\b')
            if bool(Bernoulli(probs=prob).sample()):
                numAccepted[j] += 1
                lexs[j] = newLex
                scores[j] = newScore
                if newScore > bestScore:
                    diff = newScore-bestScore
                    bestLex = newLex
                    bestScore = newScore
                    sys.stdout.write('\b')
                    print "New high score!\t", bestScore
                    print "\tdiscovered by:\t", names[j], "\tlen:", bestLex.getLen(), "\tscore diff\t", diff, "\titeration:",i
                    print "\tF-score: %f, precision: %f, recall: %f"%utils.fScore(bestLex)
                    if i>100:
                        utils.printLex(bestLex)
                    if j != 0:
                        lexs[0] = bestLex
                        scores[0] = bestScore

    return (bestLex, bestScore)
コード例 #32
0
 def test_mutation_rate(self):
     mutate.mutation_rate = 0.0
     for _ in range(10):
         x = mutate.mutate(0)
         self.assertEqual(x, 0)
     mutate.mutation_rate = 1.0
コード例 #33
0
 def mutate(self):
     """
     Returns a Colicin with an id shifted by one
     """
     new_id = mutate(self.id)
     return Colicin(new_id)
コード例 #34
0
ファイル: minion.py プロジェクト: chopper6/cluster_net_evo
def evolve_minion(worker_file, gen, rank, output_dir):
    t_start = time.time()

    with open(str(worker_file), 'rb') as file:
        worker_ID, seed, worker_gens, pop_size, num_return, randSeed, curr_gen, configs = pickle.load(
            file)
        file.close()

    survive_fraction = float(configs['worker_percent_survive']) / 100
    num_survive = math.ceil(survive_fraction * pop_size)
    output_dir = configs['output_directory'].replace(
        "v4nu_minknap_1X_both_reverse/", '')
    #output_dir += str(worker_ID)
    max_gen = int(configs['max_generations'])
    control = configs['control']
    if (control == "None"): control = None
    fitness_direction = str(configs['fitness_direction'])

    node_edge_ratio = float(configs['edge_to_node_ratio'])

    random.seed(randSeed)
    population = gen_population_from_seed(seed, pop_size)
    start_size = len(seed.net.nodes())
    pressurize_time = 0
    mutate_time = 0

    for g in range(worker_gens):
        gen_percent = float(curr_gen / max_gen)
        if (g != 0):
            for p in range(num_survive, pop_size):
                population[p] = population[p % num_survive].copy()
                #assert (population[p] != population[p%num_survive])
                #assert (population[p].net != population[p % num_survive].net)

        for p in range(pop_size):
            t0 = ptime()
            mutate.mutate(configs, population[p].net, gen_percent,
                          node_edge_ratio)
            t1 = ptime()
            mutate_time += t1 - t0

            if (control == None):
                pressure_results = pressurize.pressurize(
                    configs, population[p].net, None
                )  # false: don't track node fitness, None: don't write instances to file
                population[p].fitness_parts[0], population[p].fitness_parts[
                    1], population[p].fitness_parts[2] = pressure_results[
                        0], pressure_results[1], pressure_results[2]

            else:
                util.cluster_print(
                    output_dir, "ERROR in minion(): unknown control config: " +
                    str(control))

        old_popn = population
        population = fitness.eval_fitness(old_popn, fitness_direction)
        del old_popn
        #debug(population,worker_ID, output_dir)
        curr_gen += 1
    write_out_worker(output_dir + "/to_master/" + str(gen) + "/" + str(rank),
                     population, num_return)

    # some output, probably outdated
    if (worker_ID == 0):
        orig_dir = configs['output_directory']
        end_size = len(population[0].net.nodes())
        growth = end_size - start_size
        output.minion_csv(orig_dir, pressurize_time, growth, end_size)
        #debug(population, worker_ID, output_dir)
        #if (worker_ID==0): util.cluster_print(output_dir,"Pressurizing took " + str(pressurize_time) + " secs, while mutate took " + str(mutate_time) + " secs.")

    t_end = time.time()
    time_elapsed = t_end - t_start
    if (rank == 1 or rank == 32 or rank == 63):
        util.cluster_print(
            output_dir, "Worker #" + str(rank) + " finishing after " +
            str(time_elapsed) + " seconds")
コード例 #35
0
ファイル: hw_ev.py プロジェクト: b7500af1/HWev
aa = 0					# a counter
max_score = 0			# keep track of the max score achieved by a strain
counter = 0				# another counter

# Do While: stop condition is when a circuit that fulfills the truth table is found
while (temp_string[0][0][0] < (100*len(tt_out[0])*len(tt_in)+2-100)):

    for xx in range (0, keep_top_X_strains):
        bit_string[xx] = copy.deepcopy(temp_string[xx])		# Copy "elite" strains to bit_string
    for xx in range (keep_top_X_strains, crossover_X_strains+keep_top_X_strains):
        bit_string[xx] = copy.deepcopy(temp_string[0])		# Copy "elite" strains to bit_string
    for xx in range (keep_top_X_strains, crossover_X_strains+keep_top_X_strains):
        mt.crossover(bit_string[xx][1], temp_string[xx][1], rows, crossover_percent_elite)	# Crossover 
    for xx in range(1, crossover_X_strains+keep_top_X_strains):
        mt.mutate(bit_string[xx][1], num_of_bits_to_mutate)		# Mutation of strains (excluding the best strain)

	## Simulate each strain and assign a fitness
    for xx in range(0, num_of_strains):
        bit_string[xx][0][0] = cs.sim(bit_string[xx][1],tt_in,tt_out,rows,cells_per_row, bits_per_cell)
        # Because I use python's "sort" function, I added a random number to the start of each strain.
        # This avoids sorting the strains by fitness, and then the input of the first logic gate (bias)
        bit_string[xx][0][1] = rnd.randint(0,900)

	# Sort strains with best (highest) fitness first
    bit_string.sort(reverse=True)


    temp_string = []
    for xx in range (0, crossover_X_strains+keep_top_X_strains+1):
        temp_string.append(bit_string[xx])		#Copy the best XX strains to temp_string
コード例 #36
0
 def mutate(self):
     """
     Returns an immunity instance shifted by one
     (Binding range unchanged)
     """
     return Immunity(mutate(self.id), self.binding_range)
コード例 #37
0
def nearlyEqual(s1, s2):
    mutated_list = mutate.mutate(s2)
    return s1 in mutated_list