Пример #1
0
    def createNextGeneration(self, generation):
        if generation == None:
            nextGeneration = Generation(0)

            while nextGeneration.getSize() < self.noOfChromosomesPerGeneration:
                chromosome = Chromosome(nextGeneration.getNo(),
                                        nextGeneration.getSize())

                chromosome.seed()

                nextGeneration.addChromosome(chromosome)
        else:
            generation.sortAccordingToFitness()

            nextGeneration = Generation(generation.getNo() + 1)

            while nextGeneration.getSize() < self.noOfChromosomesPerGeneration:
                i1 = int(math.fabs(math.ceil(random.gauss(0, 0.1) * 199)))
                parent1 = generation.getChromosomeAt(i1)
                i2 = i1

                while i2 == i1:
                    i2 = int(math.fabs(math.ceil(random.gauss(0, 0.1) * 199)))

                parent2 = generation.getChromosomeAt(i2)

                children = parent1.mate(nextGeneration.getNo(),
                                        nextGeneration.getSize(), parent2)

                for child in children:
                    child.mutate()

                    nextGeneration.addChromosome(child)

        return nextGeneration
Пример #2
0
    def next_generation(self, prev_generation):
        new_generation = []

        for i in range(len(prev_generation.genomes)):
            new_generation.append(self.tournament(prev_generation))

        return Generation(new_generation, self.answer)
Пример #3
0
 def initial_generation(self):
     initial_genomes = []
     for i in range(self.population):
         g = Genome()
         g.solution = random_solution(self.genome_length)
         initial_genomes.append(g)
     return Generation(initial_genomes, self.answer)
def simulate():
    populationSize = 150

    ga = Generation(populationSize, weight, nrCities)
    ga.initializePopulation()
    print('________________generation 1______________')
    sol = ga.bestIndividual()
    print('Best fitness this generation: ' +
          str(sol.__getattribute__("fitness")))
    print('Best fitness: ' + str(sol.__getattribute__("fitness")))
    bestFitnessEver = sol.__getattribute__("fitness")
    bestFor = 1
    genNo = 2
    while bestFor != 100:
        ga.evolveElite()
        sol = ga.bestIndividual()
        if sol.__getattribute__("fitness") < bestFitnessEver:
            bestFitnessEver = sol.__getattribute__("fitness")
            bestFor = 1
        else:
            bestFor += 1
        print('________________generation ' + str(genNo + 1) +
              '______________')
        print('Best fitness this generation: ' +
              str(sol.__getattribute__("fitness")))
        print('Best fitness: ' + str(bestFitnessEver))
        genNo += 1

    print(nrCities)
    solution = sol.__getattribute__("repres")
    for i in range(len(solution)):
        print(solution[i] + 1, end=' ')
    print()
    print(str(sol.__getattribute__("fitness")))
Пример #5
0
 def __init__(self,
              conditions: Conditions,
              simulation: Simulation,
              load_file=None,
              screen=None):
     """
     The Neat Application runs the Neat algorithm on a simulation, using the given conditions
     :param conditions: The conditions to use when running the algorithm
     :param simulation: The simulation Neat will be running
     :param load_file: A file to load previous data from
     """
     self.simulation: Simulation = simulation
     self.conditions: Conditions = conditions
     self.past: List[Generation] = []
     self.screen = screen
     self.log_file = "scores/score_%d.csv" % time()
     if load_file is None:
         gene_pool = GenePool(0, simulation.get_data_size() + 1, {})
         genomes = self.start_genomes(gene_pool, conditions)
         population = Population([])
         population.add_all_genomes(genomes, conditions)
         population.clear_empty_species()
         self.current_generation: Generation = Generation(
             0, population, gene_pool.next())
     else:
         raise NotImplementedError("Saving is coming soon")
Пример #6
0
def supply_generation_one_basic_genome():
    generation = Generation([])

    nodes = make_node_list(1, 0, 1)
    cons = [ConnectionGene(nodes[0], nodes[1], np.random.uniform(), 1, 0)]
    genome = Genome(nodes, cons, generation)
    generation.genomes.append(genome)
    return generation
Пример #7
0
 def reset(self):
     g = Generation()
     self._task_list = g.generate_tasks(self._total_af * self._load_ratio)
     #print 'Number of tasks:'+str(len(self._task_list))
     tempP = copy.deepcopy(self._partition_list)
     tempT = copy.deepcopy(self._task_list)
     self._model = Model()
     return self._model.reset(tempT, tempP)
Пример #8
0
def run_simulation(setup, savefile):
    """
    A helper function that will run the simulation.
    :param setup: An object containing all variables that will be used in the simulation.
    :param savefile: The file where we want to save the results to.
    :return: averaged payoffs per generation, number of times the target was reached per generation 
        and the averaged contributions per round per generation (GxR matrix)
    """
    generations_avg_payoffs = []
    generations_targets_reached = []
    generations_rounds_contributions_counts = []
    generations_behaviors_counts = []

    generation = Generation(setup)
    for i in range(setup.num_generations):
        setup.risk += setup.risk_cont
        print("Generation " + str(i))
        targets_reached, avg_payoff, rounds_contributions_counts, behaviors_counts = generation.play(
        )
        generations_avg_payoffs.append(avg_payoff)
        generations_targets_reached.append(np.sum(targets_reached))
        generations_rounds_contributions_counts.append(
            rounds_contributions_counts.tolist())
        generations_behaviors_counts.append(behaviors_counts.tolist())
        print("Targets reached: ", np.sum(targets_reached))
        print("With an average payoff of " + str(avg_payoff))
        print("Behavior counts: ")
        print(behaviors_counts)
        print("Rounds contributions counts: ")
        print(rounds_contributions_counts)
        generation.evolve()
        # If we are investigating the robustness of strategies we return the number of generations it has survived.
        if setup.strategy is not None:
            if generation.frequency < setup.population_size / 2:
                return i

    # If we are investigating the robustness of strategies we return the number of generations it has survived.
    if setup.strategy is not None:
        return setup.num_generations

    print(generations_targets_reached)

    # We place everything inside a dictionary and then in a data frame.
    results = {
        "avg_payoffs": generations_avg_payoffs,
        "targets_reached": generations_targets_reached,
        "rounds_contributions_counts": generations_rounds_contributions_counts,
        "behaviors_counts": generations_behaviors_counts
    }
    results_df = pd.DataFrame(results)

    # We write the results to a file.
    results_df.to_csv(savefile,
                      sep=',',
                      mode='w',
                      header=True,
                      index=False,
                      encoding="ascii")
Пример #9
0
def test_crossover_basic(supply_generation_two_basic_genomes):
    generation = supply_generation_two_basic_genomes
    g1 = generation.genomes[0]
    g2 = generation.genomes[1]

    inno_num = 2  # This is the highest inno num of any gene in g1 and g2
    new_generation = Generation([])

    g3 = crossover(g1, g2, new_generation)
Пример #10
0
    def next_generation(self):
        if len(self.gens) == 0:
            # Need to create first generation.
            return False

        last_generation = self.gens[len(self.gens) - 1]
        gen = last_generation.generate_next_generation()
        self.gens.append(Generation(self.neuro_options))
        return gen
Пример #11
0
    def first_generation(self):
        out = []
        network = self.neuro_options.options['network']
        for i in range(self.neuro_options.options['population']):
            # Generate the Network and save it.
            nn = Network(self.neuro_options)
            nn.perceptron_generation(network[0], network[1], network[2])
            out.append(nn.get_save())

        self.gens.append(Generation(self.neuro_options))
        return out
Пример #12
0
def supply_generation_two_basic_genomes():
    generation = Generation([])

    nodes = make_node_list(1, 1, 2)
    cons1 = [
        ConnectionGene(nodes[0], nodes[1], np.random.uniform(), 1, 0),
        ConnectionGene(nodes[1], nodes[2], np.random.uniform(), 1, 1)
    ]
    genome1 = Genome(nodes, cons1, generation)

    cons2 = [
        ConnectionGene(nodes[0], nodes[1], np.random.uniform(), 1, 0),
        ConnectionGene(nodes[2], nodes[3], np.random.uniform(), 1, 2)
    ]
    genome2 = Genome(nodes.copy(), cons2, generation)

    generation.genomes.extend([genome1, genome2])
    return generation
Пример #13
0
def main():
    parser = argparse.ArgumentParser()

    parser.add_argument('--threshold', type=int, default=0)
    parser.add_argument('--population_size', type=int, default=50)
    parser.add_argument('--n_simulations', type=int, default=10)
    parser.add_argument('--mutation_chance', type=float, default=0.01)
    parser.add_argument('--selection_rate', type=float, default=0.4)
    args = parser.parse_args()

    Chromosome.set_globals(
        args.n_simulations,
        args.mutation_chance)  # initialize macro for N and q
    population = Generation(
        [Chromosome.random()
         for i in range(args.population_size)], args.selection_rate,
        args.threshold)  # initialize macro for p and stopping_criteria
    fittest = population.run()
    print('Fittest member: {}'.format(fittest))
Пример #14
0
def generatePopulation(size, print_progress=False):
    roomsByFeatures = buildRoomTree()
    events = ProblemData.events
    population = []

    for i in range(size):
        if (print_progress):
            printProgress(i / size)
        slotsOccupied = createSlotMatrix()
        solution = []
        for event in events:
            slot = roomsByFeatures[tuple(event.features)].getRoomRecursively(
                event, slotsOccupied)
            solution.append(slot)
        randomizeNone(solution)
        if i != size - 1:
            for key in roomsByFeatures:
                roomsByFeatures[key].reset()
        population.append(Solution(solution))
    if (print_progress):
        printProgress(1, carriage_return=False)
    return Generation(population)
Пример #15
0
def main():
    x, y = get_data('generator1data_3.txt')


    #x= [1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0]
    #y = [-2.0,1.0,6.0,13.0,22.0,33.0,46.0,61.0,78.0,97.0]
    #x^2 - 3


    population_size = 300
    print 'Population size: ' + str(population_size)
    max_depth = 10
    reproduction_rate = 0.01
    mutation_rate = 0.1
    num_generations = 10
    for i in range(10):
        print 'RUNNING TRIAL ' + str(i)
        gen = Generation(population_size, max_depth, x, y)
        gen.evolution(num_generations)
        best_tree = gen.generation.pop(0)
        print 'AFTER 10 GENERATIONS: '
        print best_tree.print_expression()
        print 'error: ' + str(best_tree.fitness)
Пример #16
0
    def __init__(self, the_packet_area, iserver):
        Gtk.Box.__init__(self, spacing=10, orientation=Gtk.Orientation.VERTICAL)
        self.set_homogeneous(False)

        # components of the MessageTypeArea
        self.msgtype_view = MessageType(iserver, the_packet_area)
        self.dependency_view = Dependency(iserver, the_packet_area)
        self.page_num = 0

        title = Gtk.Label()
        title.set_markup("<u><b><big> Message Type Area </big></b></u>")
        title.set_xalign(0.05)
        self.pack_start(title, True, True, 0)

        notebook = Gtk.Notebook()
        notebook.connect("switch_page", self.update_page)
        pages = [('New/Modify', self.msgtype_view),
                 ('Dependency', self.dependency_view),
                 ('Template', Template()),
                 ('Equivalency', Equivalency()),
                 ('Generation', Generation())]
        self.append_pages(notebook, pages)
        self.pack_start(notebook, True, True, 0)
def gen_25k_graph(O, names=None):
    error = 0.05

    G = nx.Graph(O)
    test25 = Estimation()
    gen25 = Generation()
    test25.load_graph("", graph=G)
    test25.calcfull_CCK()
    test25.calcfull_JDD()
    gen25.set_JDD(test25.get_JDD('full'))
    gen25.set_KTRI(test25.get_KTRI('full'))
    gen25.construct_triangles_2K()
    gen25.mcmc_improved_2_5_K(error_threshold=error)

    H = gen25.G
    for i in range(len(O.nodes())-len(H.nodes())):
        H.add_node(len(H.nodes()))
    if names:
        dknames = H.nodes()
        mapping = {dknames[i]: names[i] for i in range(len(names))}
        H = nx.relabel_nodes(H, mapping)

    assert(len(H.nodes()) == len(O.nodes()))
    return H
Пример #18
0
    print("Number Of Individuals:" + str(gnr.NUM_OF_INDIVIDUALS))
    print("\nMost Eaten Food      :" + str(gnr.individuals[0].eaten_food))
    print("Best Fitness         :" + str(gnr.individuals[0].fitness))
    print("Average Eaten Fodd   :" + str(gnr.average))
    print("Average Fitness      :" + str(gnr.average_fitness))
    if gnr_count % paint_mode == 0:
        print("\n\nBOARD\n")
        print_array_colored(world.map, world_color_map)

        middle_index = int(len(gnr.individuals) / 2)

        print_travel_maps(
            build_travel_array(gnr.individuals[0].positions, world),
            build_travel_array(gnr.individuals[middle_index].positions, world),
            build_travel_array(gnr.individuals[-1].positions, world),
            travel_color_map)
        getch()


world = World()
gnr = Generation(world)
gnr_count = 0
print_generation_information(world, gnr, gnr_count, 50)

while gnr.individuals[0].eaten_food < World.NUM_OF_FOOD and gnr_count < 2000:
    gnr = Generation(world=world, ancestor_individuals=gnr)
    gnr_count += 1
    print_generation_information(world, gnr, gnr_count, 50)

print_generation_information(world, gnr, gnr_count, gnr_count)
Пример #19
0
        if self.epsilon > self.epsilon_min:
            self.epsilon *= self.epsilon_decay

    def load(self, name):
        self.model.load_weights(name)

    def save(self, name):
        self.model.save_weights(name)


if __name__ == "__main__":
    env = TMSimEnv()
    partition_list = {}
    # for i in range(3):
    #     partition_list[i]=Partition(i, 0.2*(i+1))
    g = Generation()
    partition_list =g.generate_partitions(20)
    print 'Number of partitions:'+str(len(partition_list))
    env.make(partition_list, 0.6)
    state_size = env.get_state_size()
    action_size = env.get_action_size()
    agent = DQNAgent(state_size, action_size)
    # agent.load("./save/cartpole-dqn.h5")
    done = False
    batch_size = 32



    wFile = open('Result_Diff_Task.txt','w')
    for e in range(EPISODES):
        state = env.reset()
Пример #20
0
 def __init__(self, neuro_options):
     self.gens = []
     self.neuro_options = neuro_options
     self.current_generation = Generation(self.neuro_options)
Пример #21
0
def csv_test_unparallel():
    eg.__eigen_info = True
    print("Strategy," + "Graph," + str("EigErr") + "," + str("DegCorr") + "," +
          str("ClustRatio") + "," + str("EigVErr") + "," +
          str("NodeDistCorr") + "," + str("DegBetCorr") + "," +
          str("KCoreCorr") + "," + str("CommNeighDist") + "," +
          str("PartRatio") + "," + str("AvgNeighDegCorr") + "," +
          str("Connected"),
          file=sys.stderr)
    for filo in os.listdir("/home/baldo/tmp/graph_generator/PL200/"):
        with open("/home/baldo/tmp/graph_generator/PL200/" + filo, "r") as net:
            eg.info(filo)
            eg.info("Loading graph..")
            G = nx.read_weighted_edgelist(net)  # , delimiter=":")
            # G = read_graphml(net)
            A = nx.to_numpy_matrix(G)
            n = nm.shape(A)[0]
            joint_degrees = nx.algorithms.mixing.degree_mixing_dict(G)
            eg.info("Computing centrality..")
            x, l = eg.eigen_centrality(A)

            for i in range(10):
                eg.info("Run: " + str(i))

                eg.info("Building JDM graph..")
                H = joint_degree_graph(joint_degrees)
                B = nx.to_numpy_matrix(H)
                write_statistics(A, B, "2k", filo, x, l)

                eg.info("Building degree sequence graph..")
                H = nx.random_degree_sequence_graph((nx.degree(G).values()))
                B = nx.to_numpy_matrix(H)
                write_statistics(A, B, "1k", filo, x, l)

                precision = 0.01
                eg.info("Building eigen " + str(precision) + " graph..")
                B = eg.build_matrix(x, l, precision)
                write_statistics(A, B, "eig" + str(precision), filo, x, l)

                precision = 0.001
                eg.info("Building eigen " + str(precision) + " graph..")
                B = eg.build_matrix(x, l, precision)
                write_statistics(A, B, "eig" + str(precision), filo, x, l)

                precision = 0.0001
                eg.info("Building eigen " + str(precision) + " graph..")
                B = eg.build_matrix(x, l, precision)
                write_statistics(A, B, "eig" + str(precision), filo, x, l)

                m = 0.25
                eg.info("Building spectral " + str(m) + " graph..")
                B = eg.sample_simm_matrix(A, int(round(n * m)))
                write_statistics(A, B, "spectre" + str(m), filo, x, l)

                m = 0.5
                eg.info("Building spectral " + str(m) + " graph..")
                B = eg.sample_simm_matrix(A, int(round(n * m)))
                write_statistics(A, B, "spectre" + str(m), filo, x, l)

                m = 0.75
                eg.info("Building spectral " + str(m) + " graph..")
                B = eg.sample_simm_matrix(A, int(round(n * m)))
                write_statistics(A, B, "spectre" + str(m), filo, x, l)

                m = 0.9
                eg.info("Building spectral " + str(m) + " graph..")
                B = eg.sample_simm_matrix(A, int(round(n * m)))
                write_statistics(A, B, "spectre" + str(m), filo, x, l)

                m = 0.95
                eg.info("Building spectral " + str(m) + " graph..")
                B = eg.sample_simm_matrix(A, int(round(n * m)))
                write_statistics(A, B, "spectre" + str(m), filo, x, l)

                eg.info("Building D2.5 graph..")
                test25 = Estimation()
                gen25 = Generation()
                test25.load_graph("", graph=G)
                test25.calcfull_CCK()
                test25.calcfull_JDD()
                gen25.set_JDD(test25.get_JDD('full'))
                gen25.set_KTRI(test25.get_KTRI('full'))
                gen25.construct_triangles_2K()
                gen25.mcmc_improved_2_5_K(error_threshold=0.05)
                H = gen25.G
                B = nx.to_numpy_matrix(H)
                write_statistics(A, B, "25k", filo, x, l)
Пример #22
0
def graph_worker_oneshot(inputlist, queue, print_queue):
    for duty in inputlist:
        name = duty[0]
        G = duty[1]
        algo = duty[2]
        param = duty[3]

        A = nx.to_numpy_matrix(G)
        # x, l = eg.eigen_centrality(A)

        eg.info("Setup completed")
        start_time = time.time()

        if algo == "1k":
            H = nx.random_degree_sequence_graph((nx.degree(G).values()))
            # B = nx.to_numpy_matrix(H)

        elif algo == "2k":
            joint_degrees = nx.algorithms.mixing.degree_mixing_dict(G)
            H = joint_degree_graph(joint_degrees)
            # B = nx.to_numpy_matrix(H)

        elif algo == "eig":
            precision = float(param)
            # B = eg.build_matrix(x, l, precision)
            B = eg.generate_matrix(x, l * x, precision, gu.get_degrees(A))
            H = None
            algo += str(precision)

        elif algo == "modeig":
            precision = float(param)
            B = eg.synthetic_modularity_matrix(A, precision)
            H = None
            algo += str(precision)

        elif algo == "spectre":
            m = float(param)
            n = nm.shape(A)[0]
            B = eg.sample_simm_matrix2(A, int(round(n * m)))
            H = gu.simm_matrix_2_graph(B)
            while nx.is_isomorphic(G, H):
                B = eg.sample_simm_matrix2(A, int(round(n * m)))
                H = gu.simm_matrix_2_graph(B)
            algo += str(m)

        elif algo == "laplacian":
            m = float(param)
            n = nm.shape(A)[0]
            B = eg.laplacian_clone_matrix(A, int(round(n * m)))
            H = gu.simm_matrix_2_graph(B)
            while nx.is_isomorphic(G, H):
                B = eg.sample_simm_matrix2(A, int(round(n * m)))
                H = gu.simm_matrix_2_graph(B)
            algo += str(m)

        elif algo == "modspec":
            m = float(param)
            n = nm.shape(A)[0]
            B = eg.modspec_clone_matrix(A, int(round(n * m)))
            H = None
            algo += str(m)

        elif algo == "franky":
            m = float(param)
            n = nm.shape(A)[0]
            B = eg.franky_clone_matrix(A, int(round(n * m)))
            H = None
            algo += str(m)

        elif algo == "modularity":
            m = float(param)
            n = nm.shape(A)[0]
            B = eg.modularity_clone_matrix(A, int(round(n * m)))
            H = gu.simm_matrix_2_graph(B)
            while nx.is_isomorphic(G, H):
                B = eg.modularity_clone_matrix(A, int(round(n * m)))
                H = gu.simm_matrix_2_graph(B)
            algo += str(m)

        elif algo == "25k":
            test25 = Estimation()
            gen25 = Generation()
            test25.load_graph("", graph=G)
            test25.calcfull_CCK()
            test25.calcfull_JDD()
            gen25.set_JDD(test25.get_JDD('full'))
            gen25.set_KTRI(test25.get_KTRI('full'))
            gen25.construct_triangles_2K()
            gen25.mcmc_improved_2_5_K(error_threshold=0.05)
            H = gen25.G
            # B = nx.to_numpy_matrix(H)

        eg.info("Graph Generated")

        stat = get_statistics1(G, H, time.time() - start_time)
        s = algo + "," + name + "," + str(len(G.nodes()))
        for el in stat:
            s += "," + str(el)
        print_queue.put(s)
        print_queue.put("\n")
        gc.collect()
Пример #23
0
def graph_worker(inputlist, queue, print_queue):
    for filo in inputlist:
        if filo.split(".")[-1] == "graphml":
            G = read_graphml(filo)
        else:
            G = nx.read_weighted_edgelist(filo)

        A = nx.to_numpy_matrix(G)
        n = nm.shape(A)[0]
        joint_degrees = nx.algorithms.mixing.degree_mixing_dict(G)
        x, l = eg.eigen_centrality(A)

        H = nx.random_degree_sequence_graph((nx.degree(G).values()))
        B = nx.to_numpy_matrix(H)
        print_queue.put(write_statistics(A, B, "1k", filo, x, l, output=False))
        print_queue.put("\n")

        H = joint_degree_graph(joint_degrees)
        B = nx.to_numpy_matrix(H)
        print_queue.put(write_statistics(A, B, "2k", filo, x, l, output=False))
        print_queue.put("\n")

        precision = 0.01
        B = eg.build_matrix(x, l, precision)
        print_queue.put(
            write_statistics(A,
                             B,
                             "eig" + str(precision),
                             filo,
                             x,
                             l,
                             output=False))
        print_queue.put("\n")

        precision = 0.001
        B = eg.build_matrix(x, l, precision)
        print_queue.put(
            write_statistics(A,
                             B,
                             "eig" + str(precision),
                             filo,
                             x,
                             l,
                             output=False))
        print_queue.put("\n")

        precision = 0.0001
        B = eg.build_matrix(x, l, precision)
        print_queue.put(
            write_statistics(A,
                             B,
                             "eig" + str(precision),
                             filo,
                             x,
                             l,
                             output=False))
        print_queue.put("\n")

        m = 0.25
        B = eg.sample_simm_matrix(A, int(round(n * m)))
        print_queue.put(
            write_statistics(A,
                             B,
                             "spectre" + str(m),
                             filo,
                             x,
                             l,
                             output=False))
        print_queue.put("\n")

        m = 0.5
        B = eg.sample_simm_matrix(A, int(round(n * m)))
        print_queue.put(
            write_statistics(A,
                             B,
                             "spectre" + str(m),
                             filo,
                             x,
                             l,
                             output=False))
        print_queue.put("\n")

        m = 0.75
        B = eg.sample_simm_matrix(A, int(round(n * m)))
        print_queue.put(
            write_statistics(A,
                             B,
                             "spectre" + str(m),
                             filo,
                             x,
                             l,
                             output=False))
        print_queue.put("\n")

        m = 0.9
        B = eg.sample_simm_matrix(A, int(round(n * m)))
        print_queue.put(
            write_statistics(A,
                             B,
                             "spectre" + str(m),
                             filo,
                             x,
                             l,
                             output=False))
        print_queue.put("\n")

        m = 0.95
        B = eg.sample_simm_matrix(A, int(round(n * m)))
        print_queue.put(
            write_statistics(A,
                             B,
                             "spectre" + str(m),
                             filo,
                             x,
                             l,
                             output=False))
        print_queue.put("\n")

        test25 = Estimation()
        gen25 = Generation()
        test25.load_graph("", graph=G)
        test25.calcfull_CCK()
        test25.calcfull_JDD()
        gen25.set_JDD(test25.get_JDD('full'))
        gen25.set_KTRI(test25.get_KTRI('full'))
        gen25.construct_triangles_2K()
        gen25.mcmc_improved_2_5_K(error_threshold=0.05)
        H = gen25.G
        B = nx.to_numpy_matrix(H)
        print_queue.put(write_statistics(A, B, "25k", filo, x, l,
                                         output=False))
        print_queue.put("\n")
Пример #24
0
    #fname = "web-NotreDame.edges.gz"
    #fname = "web-Google.edges.gz"
    #fname = "wiki-Talk.edges.gz"
    run_case = 1
    error_threshold = 0.05

    ###### Full graph - 2K with triangles + Improved MCMC
    if run_case == 1:
        myest = Estimation()
        myest.load_graph(fname)

        myest.calcfull_CCK()
        myest.calcfull_JDD()
        myest.estimation_summary()

        mygen = Generation()
        mygen.set_JDD(myest.get_JDD('full'))
        mygen.set_KTRI(myest.get_KTRI('full'))

        mygen.construct_triangles_2K()
        mygen.mcmc_improved_2_5_K(error_threshold=error_threshold)
        mygen.save_graphs('%s_2KT+ImpMCMC_Full' % fname)
    #######################################################
    ###### Full graph - 2K simple +  MCMC
    elif run_case == 2:
        myest = Estimation()
        myest.load_graph(fname)

        myest.calcfull_CCK()
        myest.calcfull_JDD()
        myest.estimation_summary()
Пример #25
0
def launcher():
    with Generation() as gen:
        with PyQtToolBox.App(style=qdarkstyle.load_stylesheet_pyqt5(),
                             excepthook=True):
            launcher = WindowLauncher(gen)
        launcher.close_all()
Пример #26
0
import pyglet
from pyglet.window import Window
from pyglet.window import key
from pyglet import shapes

import math

from Generation import Generation

from track import tracklines

window = Window(960, 700)
pyglet.gl.glClearColor(1, 1, 1, 1)

gen = Generation()

for car in gen.players:
    window.push_handlers(car.key_handler)


@window.event
def on_draw():
    window.clear()
    gen.draw()
    for line in tracklines:
        line.draw()

    # for car in gen.players:
    #     car.draw()

    # for car in gen.players:
Пример #27
0
 def _create_first_generation(self):
     first_generation = Generation()
     first_generation.create_first_generation()
     return first_generation
Пример #28
0
 def _create_next_generation(self, offspring):
     next_generation = Generation()
     next_generation.create_next_generation(offspring)
     return next_generation
Пример #29
0
 def __init__(self, directory, experimentNumber):
     
     self.generationStats = [None] * 100 # 100 generations per experiment
     
     #array for avgComplexity over generations 
     self.avgComplexityArray = [None] *100
     #array for avgFitness over generations 
     self.avgFitnessArray = [None] *100
     
     # array of the average highest fitness individuals for each generation over the ten repeats
     self.avgHighestFitnessArray = [None] * 100
     # array of the average complexity of the individuals with the highest fitness at each generation over the ten repeats
     self.avgHighestComplexityArray = [None] * 100
     
     self.maxComplexityArray = [None] *100
     
     #highest fitness and associated complexity at generation 100 for each of the repeats
     self.highestFitnessPerRepeat = [None] * 10
     self.highestComplexityPerRepeat = [None] * 10
     #average fitness and average complexity at generation 100 for each of the repeats
     self.averageFitnessPerRepeat = [None] * 10
     self.averageComplexityPerRepeat = [None] * 10
     
     # complexity of individual that achieved the highest fitness 
     self.highestComplexityExperiment = 0.0
     # largest fitness score achieved over all repeats and all generations
     self.highestFitnessExperiment = 0.0   
     
     self.lowestFitnessExperiment = 100.0
     
     # 100 generations per run
     for generationNumber in range(1,101):
         complexity = 0.0
         fitness = 0.0
         highestFitness = 0.0
         highestComplexity =0.0
         
         lowestFitness = 100.0
         
         totalMaxComplexity = 0.0
         
         totalHighestFitness = 0.0
         totalHighestComplexity = 0.0 
         
         # ten repeats for each experiment    
         for repeat in range(10):
             genStats = Generation(directory,experimentNumber,repeat,generationNumber)
             complexity = complexity + genStats.averageComplexity
             fitness = fitness + genStats.averageFitness
             
             totalHighestComplexity += genStats.highestComplexity
             totalHighestFitness += genStats.highestFitness
             
             if(genStats.highestFitness>highestFitness):
                 highestFitness = genStats.highestFitness
                 highestComplexity = genStats.highestComplexity
     
             if(genStats.lowestFitness<lowestFitness):
                 lowestFitness = genStats.lowestFitness
                 
             totalMaxComplexity += genStats.maxComplexity
             
             if(generationNumber==100):
                 self.highestFitnessPerRepeat[repeat] = genStats.highestFitness
                 self.highestComplexityPerRepeat[repeat] = genStats.highestComplexity
                 self.averageFitnessPerRepeat[repeat] = genStats.averageFitness
                 self.averageComplexityPerRepeat[repeat] = genStats.averageComplexity
             
         # generations labeled from 1 but indexing from 0
         # average over all repeats for avg of pop at given generation 
         averageComplexity = complexity/10
         self.avgComplexityArray[generationNumber-1] = averageComplexity
         averageFitness = fitness/10
         self.avgFitnessArray[generationNumber-1] = averageFitness
         
         self.maxComplexityArray[generationNumber-1] = totalMaxComplexity/10
         
         averageHighestComplexity = totalHighestComplexity/10
         self.avgHighestComplexityArray[generationNumber-1] = averageHighestComplexity
         averageHighestFitness = totalHighestFitness/10
         self.avgHighestFitnessArray[generationNumber-1] = averageHighestFitness
         
         self.generationStats[generationNumber-1] = GenStats(averageComplexity,averageFitness,averageHighestFitness, averageHighestComplexity, highestComplexity,highestFitness)
         
         if(highestFitness > self.highestFitnessExperiment):
             self.highestFitnessExperiment = highestFitness
         if(highestComplexity > self.highestComplexityExperiment):
             self.highestComplexityExperiment = highestComplexity
             
         if(lowestFitness<self.lowestFitnessExperiment):
             self.lowestFitnessExperiment = lowestFitness