コード例 #1
0
def main():
    print_run_info()
    generation = Generation(POPULATION, ELITE, CROSSOVER, MUTATE)
    generation_avg_fitness_list = [generation.avg_solution_fitness]
    run_count = 1

    print('{}, {}'.format(run_count, generation.avg_solution_fitness))

    for i in range(1, 3):
        solution_data = []
        solution_data = solution_data + generation.elites + generation.untouched
        mutated_solutions = []
        crossedover_solutions = []

        for item in generation.mutations:
            mutated_solutions.append(item.mutate())

        for i in range(0, int(len(generation.crossovers) / 2)):
            item = generation.crossovers[i]
            other_item = generation.crossovers[len(generation.crossovers) - i -
                                               1]

            for new_item in item.crossover(other_item):
                crossedover_solutions.append(new_item)

        solution_data = solution_data + mutated_solutions + crossedover_solutions
        generation = Generation(POPULATION, ELITE, CROSSOVER, MUTATE,
                                solution_data)
        run_count = run_count + 1
        generation_avg_fitness_list.append(generation.avg_solution_fitness)
        print('{}, {}'.format(run_count, generation.avg_solution_fitness))
コード例 #2
0
 def test_generation_for_equality(self):
     mock_population = Mock(spec=Population)
     mock_population.__eq__ = Mock(return_value=True)
     mock_population.__hash__ = Mock(return_value=1)
     generation1 = Generation(1, mock_population)
     generation2 = Generation(1, mock_population)
     self.assertEquals(generation2, generation1)
     self.assertEquals(generation1.__hash__(), generation2.__hash__())
コード例 #3
0
ファイル: evolution.py プロジェクト: memsing/TrollEvolution
 def doEvolve(self):
     evolGeneration = Generation(self.parentGeneration, self.goal,
                                 self.possibleAttributes)
     while not self.evolutionFinish:
         survivors = evolGeneration.sortTrolls()
         evolGeneration = Generation(survivors, self.goal,
                                     self.possibleAttributes)
         for Troll in survivors:
             if (Troll.look == self.goal.look) and (Troll.sex
                                                    == self.goal.sex):
                 print("The requested Troll was born!")
                 print("fix me: name is missing " + str(Troll.look) +
                       str(Troll.sex))
                 self.evolutionFinish = True
                 break
コード例 #4
0
def main():
    gencount = 100

    #dimensions
    d = 1053.7
    ff = 0.5904
    tline = 589.0957
    tslab = 296.6
    tstep = 10.5036


    g0 = NIRZCG((d, ff, tline, tslab, tstep),(1750, 2250, 1001), target = 2000)
    g0.evaluate()
    oldbest = g0
    genbest = list(zip(*g0.trans))
    print(str(dt.time(dt.now())).split('.')[0],colored("seed:", 'cyan'),g0)

    gen = Generation(25, g0)
    for i in range(gencount): 
        #str(dt.time(dt.now())).split('.')[0],colored("gen "+str(i), 'cyan')
        gen._evaluate(progress_txt = (str(dt.time(dt.now())).split('.')[0]+colored(" gen "+str(i), 'cyan')))
        gen = gen.progeny()
        genbest.append([t for wl,t in gen.best.trans])
        if gen.best.fom > oldbest.fom:
            print(colored("new best grating\n", 'green')+str(gen.best))
            oldbest = gen.best

    writecsv("iter_best.csv",list(zip(*genbest)),tuple(["wl",0]+list(range(1,gencount+1))))
コード例 #5
0
    def run(self):
        max_unit = 0
        for i in range(self.ran):
            print("Generation ", i)
            gen = Generation(self.p)
            #gen.hand.print_cards()
            gen.assign_unit_value(0)
            #gen.print_stats()
            gen.calc_fitness(self.step, 0)

            #for i in range(p.size):
            #    print(gen.population.units[i].fitness)

            if (i == self.ran - 1):
                break

            max_val = 0
            for i in range(gen.population.size):
                if (gen.population.units[i].fitness > max_val):
                    max_unit = gen.population.units[i]
                    max_val = gen.population.units[i].fitness

            print(max_unit.fitness)
            s = Step(gen)
            gen.population.units = s.generate_mating_pool()

        max_val = 0
        max_unit = 0
        for i in range(gen.population.size):
            if (gen.population.units[i].fitness > max_val):
                max_unit = gen.population.units[i]
                max_val = gen.population.units[i].fitness

        print(max_unit.weights)
        return max_unit.weights
コード例 #6
0
    def __init__(self, representation="pool", L=12, shared_core=False):
        super(GQN, self).__init__()

        # Number of generative layers
        self.L = L

        self.shared_core = shared_core

        # Representation network
        self.representation = representation
        if representation == "pyramid":
            self.phi = Pyramid()
        elif representation == "tower":
            self.phi = Tower()
        elif representation == "pool":
            self.phi = Pool()

        # Generation network
        if shared_core:
            self.inference_core = InferenceCore()
            self.generation_core = GenerationCore()
        else:
            self.inference_core = nn.ModuleList(
                [InferenceCore() for _ in range(L)])
            self.generation_core = nn.ModuleList(
                [GenerationCore() for _ in range(L)])

        # Distribution
        self.pi = Prior()
        self.q = Inference()
        self.g = Generation()
コード例 #7
0
    def __init__(self, parser, truecase_model):
        """
        Perform syntactic simplification rules.
        @param parser: parser server.
        @param truecase_model: truecase model.
        """
        #self.sentences = open(doc, "r").read().strip().split("\n")
        ## markers are separated by their most used sense
        self.time = ['cuando', 'despues', 'antes', 'before', 'once']
        self.concession = ['aunque', 'pero', 'sino', 'however', 'whereas']
        self.justify = ['so', 'mientras']
        self.condition = ['si']
        self.condition2 = ['o']
        self.addition = ['y']

        ## list of all markers for analysis purposes
        self.cc = self.time + self.concession + self.justify + self.condition + self.addition + self.condition2

        ## list of relative pronouns
        self.relpron = ['que', 'whose', 'which', 'who']

        ## initiates parser server
        self.parser = parser

        ## Generation class instance
        self.generation = Generation(self.time, self.concession, self.justify,
                                     self.condition, self.condition2,
                                     self.addition, self.cc, self.relpron,
                                     truecase_model)
    def testDone(self):
        """"Test the Done method.

    Produce a generation with a set of tasks. Set the cost of the task one by
    one and verify that the Done method returns false before setting the cost
    for all the tasks. After the costs of all the tasks are set, the Done method
    should return true.
    """

        random.seed(0)

        testing_tasks = range(NUM_TASKS)

        # The tasks for the generation to be tested.
        tasks = [IdentifierMockTask(TEST_STAGE, t) for t in testing_tasks]

        gen = Generation(set(tasks), None)

        # Permute the list.
        permutation = [(t * STRIDE) % NUM_TASKS for t in range(NUM_TASKS)]
        permuted_tasks = [testing_tasks[index] for index in permutation]

        # The Done method of the Generation should return false before all the tasks
        # in the permuted list are set.
        for testing_task in permuted_tasks:
            assert not gen.Done()

            # Mark a task as done by calling the UpdateTask method of the generation.
            # Send the generation the task as well as its results.
            gen.UpdateTask(IdentifierMockTask(TEST_STAGE, testing_task))

        # The Done method should return true after all the tasks in the permuted
        # list is set.
        assert gen.Done()
コード例 #9
0
  def __init__(self):
    pygame.init()

    self.generation = Generation()

    self.population = self.generation.population

    self.gamespeed = 4
    self.max_gamespeed = 10
    self.high_score = 0
    self.n_gen = 0
    self.current_gen_score = 0

    self.dinos = None
    self.genomes = []

    self.screen = pygame.display.set_mode(scr_size)
    self.clock = pygame.time.Clock()
    pygame.display.set_caption('Genetic T-Rex Rush')

    self.jump_sound = pygame.mixer.Sound('sprites/jump.wav')
    self.die_sound = pygame.mixer.Sound('sprites/die.wav')
    self.checkPoint_sound = pygame.mixer.Sound('sprites/checkPoint.wav')

    self.scores = []
    self.fig = plt.figure(figsize=(int(width/100), 5))
    self.ax = plt.axes()
    plt.xlabel('Generation', fontsize=18)
    plt.ylabel('Score', fontsize=16)
    plt.show(block=False)
コード例 #10
0
ファイル: simplify.py プロジェクト: gazzola/simpatico_ss
    def __init__(self, doc):
        """
        Perform syntactic simplification rules.
        @param doc: document to be simplified.
        """
        self.sentences = open(doc, "r").read().strip().split("\n")

        ## markers are separated by their most used sense
        self.time = ['when', 'after', 'since', 'before', 'once']
        self.concession = ['although', 'though', 'but', 'however', 'whereas']
        self.justify = ['because', 'so', 'while']
        self.condition = ['if']
        self.condition2 = ['or']
        self.addition = ['and']

        ## list of all markers for analysis purposes
        self.cc = self.time + self.concession + self.justify + self.condition + self.addition + self.condition2

        ## list of relative pronouns
        self.relpron = ['whom', 'whose', 'which', 'who']

        ## initiates parser server
        self.parser = Parser()

        ## Generation class instance
        self.generation = Generation(self.time, self.concession, self.justify,
                                     self.condition, self.condition2,
                                     self.addition, self.cc, self.relpron)
コード例 #11
0
    def __init__(self, parser, truecase_model):
        """
        Perform syntactic simplification rules for Galician (this code is based on the one available at simpatico_ss/simplify.py for English).
        TODO: Relative and conjoint clauses are not supported by the Galician parser. Functions for these cases were left here as examples for feature implementations.
        @param parser: parser server.
        @truecase_model: truecase model
        """

        ## markers are separated by their most used sense
        self.time = ['when', 'after', 'since', 'before', 'once']
        self.concession = ['although', 'though', 'but', 'however', 'whereas']
        self.justify = ['because', 'so', 'while']
        self.condition = ['if']
        self.condition2 = ['or']
        self.addition = ['and']

        ## list of all markers for analysis purposes
        self.cc = self.time + self.concession + self.justify + self.condition + self.addition + self.condition2

        ## list of relative pronouns
        self.relpron = ['whom', 'whose', 'which', 'who']

        ## initiates parser server
        self.parser = parser

        ## Generation class instance
        self.generation = Generation(self.time, self.concession, self.justify,
                                     self.condition, self.condition2,
                                     self.addition, self.cc, self.relpron,
                                     truecase_model)
コード例 #12
0
 def test_generation_to_retrun_best_fit_people(self):
     best = Mock(spec=DNA)
     fitness = 5
     mock_population = Mock(spec=Population)
     mock_population.best_fit = Mock(return_value=(best, fitness))
     generation = Generation(1, mock_population)
     self.assertEquals((best, fitness), generation.best_fit())
コード例 #13
0
    def __init__(self, rows, cols):
        """Creates a game object."""
        #self._board = Board(8, 8)

        self._rows = rows
        self._cols = cols
        self._current_generation = Generation(rows, cols)
コード例 #14
0
ファイル: main.py プロジェクト: patricknaughton01/tron
def main():
    generation = Generation(100, [11, 11, 4, 4], 0.5, 10)
    print("Starting the program at generation 0")
    while True:
        try:
            command = input("Enter a command (sbs, asap, alap): ")
            if command == "sbs":
                generation.do_generation(render=True)
                print("That was generation {}.".format(str(generation.age -
                                                           1)))
            elif command == "asap":
                generation.do_generation()
                print("Just did generation {} as fast as possible.".format(
                    str(generation.age - 1)))
            elif command == "alap":
                print(
                    "Doing generations for as long as possible starting at generation {}."
                    .format(str(generation.age)))
                print("Type Ctrl-C to exit the alaping")
                while True:
                    try:
                        generation.do_generation()
                        print("Just did generation {}".format(
                            str(generation.age - 1)))
                    except KeyboardInterrupt:
                        print("Exiting alap")
                        break
            else:
                print("Not a valid command")
        except KeyboardInterrupt:
            print("Thanks for playing")
            print("Exiting now")
            sys.exit()
コード例 #15
0
 def __init__(self, island_model, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self._island_model = island_model
     # Assume existing members of the tree are a part of the founders
     if len(island_model.individuals) > 0:
         assert len(self._generations) is 0
         self._generations.append(Generation(island_model.individuals))
コード例 #16
0
def main():

    generation = Generation()

    while True:
        generation.execute()
        generation.keep_best_genomes()
        generation.mutations()
コード例 #17
0
 def _initialise(self, target_string):
     target_length = len(target_string)
     nucleotides = Nucleotides(string.printable)
     DNA.nucleotides = nucleotides
     population_initialise = PopulationInitialise(nucleotides)
     first_population = population_initialise.create(
         population_size=self.population_size, structure_size=target_length)
     first_generation = Generation(1, first_population)
     return [first_generation]
コード例 #18
0
ファイル: ai.py プロジェクト: Immortalv5/Dino
def main():
    generation = Generation()
    while True:
        generation.execute()
        print("Done")
        generation.keep_best_genomes()
        print("Storing")
        generation.mutations()
        print("Mutated")
コード例 #19
0
 def test_generation_to_generate_next_generation(self):
     mock_population1 = Mock(spec=Population)
     mock_population2 = Mock(spec=Population)
     mock_population1.next_population = Mock(return_value=mock_population2)
     mock_target_DNA = Mock(spec=DNA)
     generation1 = Generation(1, mock_population1)
     generation2 = generation1.next_generation(mock_target_DNA)
     self.assertEquals(generation2.number, 2)
     self.assertEquals(generation2.population, mock_population2)
コード例 #20
0
def main():
    generation = Generation()
    i=0
    while True:
        print("Generation "+str(i)+":")
        i += 1
        generation.execute()
        generation.keep_best_genomes()
        generation.mutations()
コード例 #21
0
ファイル: test_generation.py プロジェクト: lsommerer/life2018
    def test_count_living(self):
        rows = 2
        columns = 4
        g = Generation(rows, columns)
        g.assign_neighbors()
        g._cells[0][0].live()
        self.assertEqual(g.count_living(), 1)

        g._cells[1][3].live()
        self.assertEqual(g.count_living(), 2)
コード例 #22
0
def main():
    g = Generation(size=100,
                   elite=0.05,
                   mutate=0.10,
                   tournament=10,
                   mood=raw_input())
    g.run(100, desired_length=13)
    g.best.info()
    lilypond.printPiece(g.best, 'best.ly')
    lilypond.printPiece(g.worst, 'worst.ly')
コード例 #23
0
def main():
    generation = Generation()
    lx, ly, rx, ry = get_location()
    epoch = 0
    while True:
        epoch = epoch + 1
        print("Geracao {}".format(epoch))
        generation.execute(lx, ly, rx, ry, epoch)
        generation.keep_best_genomes()
        generation.mutations()
コード例 #24
0
def createNewGeneration(generation, scorePerChild, ppid, pid):
    if(generation.generation_i >= 10300):
        growth = int(1*(generation.generation_i / 300))
    else:
        growth = 0


    n_random = 6 + growth
    n_elite = 2 + growth
    n_mutated_elite = 2 + growth

    #Crossover Rates
    n_crossover_mutated_elite = 2 + growth
    n_crossover_mutated_random = 2  + growth
    n_crossover_unmutated_elite =  2 + growth
    n_crossover_unmutated_random =  2 + growth

    #Gets indices of the elite children of population
    idxs_elite = heapq.nlargest(n_elite, range(len(scorePerChild)), key=scorePerChild.__getitem__)
    idxs_elite = np.array(idxs_elite)

    #print information about the best elite
    if(generation.generation_i % 20 == 0):
        print(str(scorePerChild[idxs_elite[0]]) + "/" + str(generation.num_clauses), generation.generation_i, len(generation.children), ppid, pid)

    #Create children
    elite_children = np.array(generation.children[idxs_elite])
    random_children = np.array(createRandomChildren(n_random, generation.num_variables))

    if(n_mutated_elite > len(elite_children)):
        print("n_mutated_elite > elite_children")
        n_mutated_elite = len(elite_children)
    mutate_elite = np.array([mutate(elite_children[i]) for i in (0, n_mutated_elite-1)])

    #Create Crossovers
    crossover_unmutated_random  = np.array(createCrossOvers(elite_children, random_children, n_crossover_unmutated_random))
    crossover_unmutated_elite   = np.array(createCrossOvers(elite_children, elite_children, n_crossover_unmutated_elite))
    crossover_mutated_random    = np.array(createCrossOvers(mutate_elite, random_children, n_crossover_mutated_random))
    crossover_mutated_elite     = np.array(createCrossOvers(elite_children, elite_children, n_crossover_mutated_elite))

    # @todo make this more clean
    temp = np.array([])
    temp = np.append(temp, elite_children)
    temp = np.append(temp,random_children)
    temp = np.append(temp,mutate_elite)
    temp = np.append(temp,crossover_unmutated_random)
    temp = np.append(temp,crossover_unmutated_elite)
    temp = np.append(temp,crossover_mutated_random)
    temp = np.append(temp,crossover_mutated_elite)
    temp = np.array(temp)
    temp = temp.reshape(int(len(temp)/729), 729)

    children = np.array(temp)
    return Generation(generation, children, generation.num_clauses, generation.num_variables)
コード例 #25
0
def main():
    knapsack, items_number = read_input()
    generation = Generation(items_number * 10, items_number)
    process_generation(generation, knapsack)
    for i in range(1, 11):
        print("Before iteration {0} best individual is: {1}".format(
            i,
            generation.get_best().fitness))
        generation.update_generation()
        process_generation(generation, knapsack)
    print("Final result is: {}".format(generation.get_best().fitness))
コード例 #26
0
def parse_trial(trial_path):
    with open(trial_path,'rb') as input_file:
        trial_result = json.load(input_file)
        generation_list = list()
        for gen in trial_result['generationalData']:
            individual_list = list()
            for indi in gen['individualList']:
                individual_list.append(
                    Individual(indi['UUID'], indi['parentUUID'], indi['switch'], indi['lightFirst'], indi['fitness']))

            generation_list.append(Generation(gen['generationNumber'], individual_list))

        trial = Trial(trial_result['config'], generation_list)
    return trial
コード例 #27
0
def main():
    driver = webdriver.Chrome()
    #driver.get('chrome://settings/clearBrowserData')
    #driver.find_element_by_xpath('//settings-ui').send_keys(Keys.ENTER)
    driver.get('chrome://dino')
    generation = Generation(driver)
    iteration = 0
    while True:
        iteration += 1
        print('++++++++++++++++++++++++++++++++++++++++++++++++++')
        print('                  iteration:{0}'.format(iteration))
        print('++++++++++++++++++++++++++++++++++++++++++++++++++')
        generation.execute()
        generation.keep_best_genomes()
        generation.mutations()
コード例 #28
0
ファイル: robogen.py プロジェクト: andrewgailey/robogen
def load_generation(filename):
    if len(filename) <= 2 or filename[len(filename) - 2:len(filename)] != ".p":
        filename = filename + ".p"
    try:
        generation = pickle.load(open(filename, "rb"))
        print "Resuming from", filename
        print "Last Generation Processed:", generation.num
        score_str = "Sorted Scores"
        for individual in generation.population:
            score_str = score_str + " : {0}".format(individual.score)
        print score_str
        return generation
    except IOError:
        print "Could not open", filename + ",", "returning new Generation"
        generation = Generation()
        generation.populate()
        return generation
コード例 #29
0
ファイル: test_generation.py プロジェクト: lsommerer/life2018
    def test_next_generation_block(self):
        l = Cell.liveChar
        d = Cell.deadChar
        n = '\n'
        state1 = n + l + l + \
                 n + l + l

        g = Generation(2, 2)
        g.assign_neighbors()
        g._cells[0][0].live()
        g._cells[0][1].live()
        g._cells[1][0].live()
        g._cells[1][1].live()

        self.assertEqual(state1, str(g))
        g = g.next_generation()
        self.assertEqual(state1, str(g))
        g = g.next_generation()
        self.assertEqual(state1, str(g))
コード例 #30
0
ファイル: run.py プロジェクト: benoitRodde/AnimalSurvivor
def generation_iterator(environment_type: str, env_carac: List[int],
                        nb_animals: List[int], nb_generation: int) -> List:
    """ Retourne un tableau des moyennes par génération """

    animal_evolution = Generation(environment_type, env_carac, nb_animals)
    nb_generation = int(nb_generation)
    result = []
    result.append(animal_evolution.calc_moyenne())

    for generation in range(nb_generation):
        survivors = animal_evolution.natural_selection(
            animal_evolution.animals)
        sorted_animals = animal_evolution.sort_by_fitness(survivors)
        animal_evolution.animals = animal_evolution.reproduction(
            sorted_animals)

        result.append(animal_evolution.calc_moyenne())

    return result