Пример #1
0
def main():
    in_data = input()
    vector = list(map(int, in_data.split()))
    time = vector[0]
    vector.pop(0)

    multiset = []
    values = {}

    for i in range(vector[0]):
        in_data = input()
        x = list(map(str, in_data.split()))
        multiset.append(x[0])
        values[x[0]] = int(x[1])

    start_sol = []

    for i in range(vector[1]):
        in_data = input().replace("\r", "")
        start_sol.append(in_data)

    Searcher = Genetic('dict.txt', values, multiset, 100)
    Searcher.find_maxima(start_sol, time)

    print(Searcher.best_value())
    print(Searcher.best_argument(), file=sys.stderr)
Пример #2
0
def main():
    pop = init.initPop(300)
    itera = 100  #迭代次数
    each = 30  #每轮迭代的遗传计算次数
    tplt = "{:8}\t{:8}\t{:8}"
    gen = Genetic()
    bests = []  #用以存储每代最优值
    print(tplt.format("Gen", "Avg", "Best"))
    for i in range(1, itera):
        pop = gen.evaluate(pop)
        bests.append(gen.printGen(pop, i))
        for j in range(1, each):
            rand = random.random()
            if rand < 0.7:  #变异率设为0.3
                ind = gen.select(pop)
                pop.remove(ind)
                ind.mark = 2
                ind.gene = gen.mutate(ind.gene, 4)
                pop.append(ind)
            else:
                pop = gen.mate(pop)
    res = numpy.array(bests)
    x = numpy.arange(1, 99)
    y = res[x]
    pyplot.title('GP result')
    pyplot.xlabel('Gen')
    pyplot.ylabel('Best')
    pyplot.plot(x, y)
    pyplot.show()
Пример #3
0
def test_genetic():
    genetic = Genetic(chromosome_gen_prob=0.4,
                      population_size=100,
                      generation_limit=500,
                      crossover_rate=1,
                      mutation_rate=0.1)
    genetic.run()
Пример #4
0
Файл: ui.py Проект: sm-g/genetic
    def OnGoClick(self, e):
        if self.function.Value:
            if self.clear_chk.IsChecked():
                self.log.Clear()

            g = Genetic(f_xy=self.function.Value.encode('ascii', 'ignore'),
                        extremum=self.extremum_rbox.GetStringSelection(),
                        cp=float(self.cross_p.Value),
                        mp=float(self.mut_p.Value),
                        size=int(self.size.Value),
                        search_field=(float(self.minx.Value),
                                      float(self.miny.Value),
                                      float(self.maxx.Value),
                                      float(self.maxy.Value)),
                        sampling=self.sampling_rbox.GetSelection(),
                        crossover=self.crossover_rbox.GetSelection(),
                        elite=int(self.elite.Value),
                        max_generations=int(self.maxgen.Value),
                        alpha=float(self.blx.Value))
            history = g.start(show_plot=False,
                              print_stats=self.stats_chk.IsChecked(),
                              print_rate=self.rate_chk.IsChecked())

            elites = g.elites(history)
            sol = g.solution(elites)

            print u'Найден экстремум\nF(x,y) = {}'.format(sol[1])
            print u'x = {}\ny = {}'.format(sol[0][0], sol[0][1])

            if self.plot_chk.IsChecked():
                genetic.draw_plot(g.fit_population, history, elites)
Пример #5
0
    def __init__(self):
        '''A genetic algorithm to Travelling Salesman Problem.

        '''
        print('''*******************Genetic algorithm*********************
              * Authors: Oraldo Jacinto Simon
              *          Marco Emanuel Casavantes Moreno
              * ***********************************************************
               ''')

        obj_graph = Graph()
        fichero = open("cities/five_d.txt", 'r')
        matrix_adjacency = np.loadtxt(fichero)
        for i, row in enumerate(matrix_adjacency):
            for j, item in enumerate(row):
                graph = obj_graph.addEdge(i + 1, j + 1, item, directed=False)
        fichero.close()
        pop_size = 100
        epochs = 80
        # Can be cities or nodes
        elite = 80
        obj_genetic = Genetic(pop_size,
                              epochs,
                              graph,
                              elite,
                              rate_mutation=0.5,
                              selection_type='tourney_probabilistic')
        path = obj_genetic.run()

        #Draw graph
        G = nx.DiGraph()
        for vertex in graph.__iter__():
            for v, w in vertex.adjacency.items():
                G.add_edge(str(vertex.id), str(v), weight=w)

        val_map = {'A': 1.0, 'D': 0.5714285714285714, 'H': 0.0}

        values = [val_map.get(node, 0.45) for node in G.nodes()]
        node_labels = {n: str(n) for n in G.nodes()}
        edge_labels = dict([((
            u,
            v,
        ), d['weight']) for u, v, d in G.edges(data=True)])
        red_edges = [(str(e), str(path[index + 1]))
                     for index, e in enumerate(path[:-1])]
        edge_colors = [
            'gray' if not edge in red_edges else 'red' for edge in G.edges()
        ]
        pos = nx.spring_layout(G)
        nx.draw_networkx_labels(G, pos, labels=node_labels)
        nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
        nx.draw(G,
                pos,
                node_color=values,
                node_size=1500,
                edge_color=edge_colors,
                edge_cmap=plt.cm.Reds)
        pylab.show()
Пример #6
0
 def test_stohastic(self):
     g = Genetic(TestGenetic.f, size=11, cp=1)
     population = [(0.2, 0.5), (-0.2, 1), (0.2, 0.2), (-1, 0.3), (0.4, 0.8)]
     fit = g.fit_population(population)
     g.start()
     print population
     print_with_score(population, g.fit_population(population))
     print 'avg fitness = ' + str(sum(fit) / float(len(fit)))
     print Sampling.stochastic_sampling(g.fit_population, g.extremum, population)
Пример #7
0
    def _load(self, filename):
        """ Loads the layer from file. For use by ModelHandler.
            Note: The node ID in the file is ignored
        """
        with open(filename, 'r') as f:
            data = f.read()

        loadme = next(iter(eval(data).values()))
        ID = self._nodeID
        node = Genetic(ID, 2, 0, 0, 0, 0, 0, CONSOLE_OUT, False)  # skeleton
        node._load(loadme, not_file=True)
        self._node = node
Пример #8
0
def main(show):
    level = logging.getLevelName(LOG_LEVEL.upper())

    print(f"Set log level to {level}")

    logging.basicConfig(level=level)

    target_image = get_image(TARGET_IMAGE, SIZE)

    g = Genetic(target_image)

    g.run(show)
Пример #9
0
def genetic(coords, generations=500, population_size=100, elite_size=10, mutation_rate=0.01):
    genetic = Genetic(coords, population_size=population_size, elitist_factor=elite_size, mutation_rate=mutation_rate)

    population = genetic.initial_population()
    steps = []
    for i in range(generations):
        population = genetic.next_generation(population)
        best_solution = genetic.best_solution(population)
        steps.append(best_solution)

    best_fitness = fitness(coords, best_solution)

    return best_fitness, best_solution, steps
Пример #10
0
def generate(generations, population, nn_param_chices, dataset):
    genetic = Genetic(nn_param_chices)
    gans = genetic.create_population(population)

    for i in range(generations):
        train_gan(gans, dataset)

        average_accuracy = get_average_accuracy(gans)

        if i != generations - 1:
            gans = genetic.evolve(gans)

    gans = sorted(gans, key=lambda x: x.accuracy, reverse=True)
Пример #11
0
def main():
    in_dir = args.in_dir
    seed = args.seed
    method = args.method
    
    random.seed(seed)
    np.random.seed(seed)
    Position = load_data(in_dir)
    
    method = 'annealing'
    if method=='local' or method=='annealing':
        ans, Route = LocalSearch(Position, method=method)
    elif method=='genetic':
        ans, Route = Genetic(Position)
    print(ans)
Пример #12
0
def main(argv):

    if len(sys.argv) < 3:
        print(
            'Please provide 3 command line arguments (e.g. input_filename, output_filename, n_results'
        )
        exit(-1)

    in_filename = ''
    out_filename = ''
    niteration = 0

    in_filename = sys.argv[1]
    out_filename = sys.argv[2]
    niteration = int(sys.argv[3])

    c = Constraint(in_filename)
    v = c.get_example()
    print(v)
    n = c.get_ndim()  #this is the chromosome size for each population
    print(n)
    # print(c.apply([0.5, 1.0, 0.0, 0.5]))

    s = 300  #population size

    ga = Genetic(
        s, n, in_filename
    )  #initializes ga type object with populaton size, chromosome size, input file name

    p = ga.get_population()
    print(p)
    print(ga.cal_pop_fitness())

    temp_solution = ga.eval_ga(niteration)
    # print(temp_solution)
    # write result to the output
    with open(out_filename, 'w') as filehandle:
        for item in temp_solution:
            s = "   ".join(str(e) for e in item)
            # print(s)
            l = s
            # l = item
            print(l)
            filehandle.write('%s\n' % l)

    filehandle.close()
def test(repeats,
         generations,
         populations,
         cross_probs,
         mutat_probs,
         choice=1,
         path="/matrixes/large"):
    files = [
        f for f in listdir(path) if isfile(join(get_script_path() + path, f))
    ]

    print(files)
    for f in files:
        graph = Graph(f, choice)
        print("Wczytano graf " + graph.file_name + " z " +
              str(graph.number_of_cities) + " wierzchołkami")
        for generation in generations:
            for population in populations:
                for cross_prob in cross_probs:
                    for mutat_prob in mutat_probs:
                        for a in range(repeats):
                            ga = Genetic(graph)

                            start = timer()
                            ga.start(generation, population, cross_prob,
                                     mutat_prob)
                            end = timer()
                            time = format((end - start), '.8f')
                            text = (str(generation) + "\t" + str(population) +
                                    "\t" + str(cross_prob) + "\t" +
                                    str(mutat_prob) + "\t" + time + "\t" +
                                    str(ga.best_cycle_cost) + "\n").replace(
                                        '.', ',')
                            print(text)
                            with open(
                                    "./measurements/ga/" +
                                    f.rsplit(".", 1)[0] + ".txt",
                                    'a+') as the_file:
                                the_file.write(text)
    print_to_continue()
Пример #14
0
    def __init__(self, ID, size, mem_depth):
        """ Accepts:
                ID (str)            : This layers unique ID
                size (int)          : Num input terminals
                mem_depth (int)     : Num prev inputs to keep in memory
        """
        self.ID = ID
        self._size = size
        self._mem_depth = mem_depth
        self._node = None  # The gentic programming (GP) obj
        self._nodeID = ID + '_node'  # GP node's unique ID

        # Init the layer's node - a genetically evolving tree of expressions
        self._node = Genetic(ID=self._nodeID,
                             kernel=L2_KERNEL_MODE,
                             max_pop=L2_MAX_POP,
                             max_depth=L2_MAX_DEPTH,
                             max_inputs=self._size,
                             mem_depth=self._mem_depth,
                             tourn_sz=L2_POOLSZ,
                             console_out=CONSOLE_OUT,
                             persist=False)

        # Set default node mutation ratios (overwritten if loading from file)
        self._node.set_mratio(repro=L2_MUT_REPRO,
                              point=L2_MUT_POINT,
                              branch=L2_MUT_BRANCH,
                              cross=L2_MUT_CROSS)

        # Init the model handler
        f_save = "self._save('MODEL_FILE')"
        f_load = "self._load('MODEL_FILE')"
        self.model = ModelHandler(self,
                                  CONSOLE_OUT,
                                  PERSIST,
                                  model_ext=L2_EXT,
                                  save_func=f_save,
                                  load_func=f_load)
Пример #15
0
def main():

    C = Configuration('conf.json')

    debug = Debug(debug=C.debug, info=C.showInfo)

    saver = TestSaver('out.txt')
    executorObject = Executor(srcPath=C.srcPath, whatToConsider = C.whatToConsider, testSaver=saver, debugger = debug);

    geneticObject = Genetic(populationSize=C.populationSize,  # Population pop_size
              chromosomeSize=C.chromosomeSize,  # size of chromosome (can be bytes, size of a number, size of a string...)
              parentsNumber=C.parentsNumber,  # How many chromosomes are entering crossover
              mutationRate=C.mutationRate,  # selfexplanatory
              generationsCount=C.generationsCount,  # Number of generations (iterations)
              geneTypeList=C.geneTypeList, #list of
              executor=executorObject,
              debugger=debug)

    geneticObject.start_evolution();

    saver.export_to_file()

    return 0;
Пример #16
0
from genetic import Genetic

genetic = Genetic()

genetic.generation_gen()


def normalize(datas, max_height, max_width):
    def compute(val, max, min): return (val - min) / max - min
    for data in datas:
        data.rocket_top = compute(data.rocket_top, max_height, 0)
        data.wall_left = compute(data.wall_left, max_width, 0)
        data.wall_length = compute(data.wall_left, max_height, 0)
        if data.wall_direction > 1:
            data.wall_direction = 1
        if data.wall_direction < 0:
            data.wall_direction = 0


def ask_model(datas, max_height, max_width):
    normalize(datas, max_height, max_width)
    for output in genetic.generation_train(datas):
        print(output)
        yield output > 0.5


def step_generation(final_datas):
    normalize(final_datas)
    genetic.generation_crossover(final_datas)
Пример #17
0
 def test_f(self):
     g = Genetic('x*y+y')
     res = g.f(1, 1)
     self.assertEqual(2, res)
Пример #18
0
# Load data
data = load_data()
params = load_params()

# Init base gene chain
base_gene_chain = GeneChain()
for column in data:
    dtype = data[column].dtype
    min_value = min(data[column])
    max_value = max(data[column])
    base_gene_chain.add(Gene(dtype.type, max_value, min_value, -1))

for index, row in params.iterrows():
    dtype = np.dtype(row["TYPE"])
    min_value = dtype.type(row["MIN"])
    max_value = dtype.type(row["MAX"])
    base_gene_chain.add(Gene(dtype.type, max_value, min_value, -1))\

# Init genetic algorithm
genetic = Genetic(max_generations=20,
                  start_population=10,
                  base_gene_chain=base_gene_chain,
                  crosser=RandomGeneCrosser(),
                  selector=TopNSelector(3),
                  mutator=RandomGeneChainMutator(10))

# Run
genetic.run()

for i, gene in enumerate(genetic.best()):
    print(i, gene)
    one_hot[y] = 1
    oh_teY.append(one_hot)

oh_trY = np.array(oh_trY)
oh_teY = np.array(oh_teY)

trY = trY.reshape((-1, 1))
teY = teY.reshape((-1, 1))

seed = random.randint(0, 1000)
random.seed(seed)
print("random seed", seed)
is_classifier = True

genetic = Genetic(make_default_eval(trX[:int(len(trX)*0.75)], oh_trY[:int(len(trX)*0.75)], trX[int(len(trX)*0.75):], oh_trY[int(len(trX)*0.75):]), 60, 10, make_default_base_initialize(classifier=is_classifier), 
                make_joint_crossover([make_boost_crossover(is_classifier), make_simple_stack_crossover(is_classifier),bag_crossover], [1/3, 1/3, 1/3]),
                make_mutator(mutate_prob=0.05, classifier=is_classifier), make_random_child_generator([2,3,4], [1/3, 1/3, 1/3]), run_name='test' )
ens = genetic.run(3, add_simple=True)[0]

trY = trY.reshape((-1, ))
teY = teY.reshape((-1, ))

# Baseline: random forest
rf = RandomForestClassifier(n_estimators=100)
rf.fit(trX, trY)
rf_acc = sum(teY == rf.predict(teX))/len(teY)

# Baseline: logistic regression
logreg = LogisticRegression()
logreg.fit(trX, trY)
logreg_acc = sum(teY == logreg.predict(teX)) / len(teY)
def main():
    filename = newFile()
    simu = []
    for x in range(MAX_PARALLEL):
        simu.append(Multi())
        simu[-1].multi_start()
    joints_seg = simu[0].parent_pipe.recv()
    #simulation.setup()
    #################### genetic
    #fitness odleglosc od zrodka (x albo y) plus 10x za kazda noge na ziemi minus[kat podst - aktualny] - x3(xyx)

    #10*sim_data[1][1] - (0 - abs(sim_data[2][1])) - (0 - abs(sim_data[2][2])) + [10*x for x in sim_data[0]]
    genetica = Genetic(POPILATION_SIZE, CHROMOSOME_SIZE, GAIT_STEPS, MAX_MIN,
                       joints_seg, BEST_SAMPLES, LUCKY_FEW, TOURNAMENT,
                       MUTATION_CHANCE)
    #resetBasePositionAndOrientation
    population = []
    population = genetica.gen_population()
    #print(population)
    #population[0] = convertToSim(ppp[0])
    #population[1] = convertToSim(ppp[1])

    pop_data = []
    pop_fitness = [0, 0]
    for generation in range(GENERATIONS):
        print("Generation:",
              str(generation) + " previous 2 best fitness: ",
              str(pop_fitness[0]), str(pop_fitness[1]))
        weighted_population = []

        slicedd = slicePop(population)
        #print(len(slicedd))
        for slic in slicedd:
            #print('.',end=" ",flush=True)
            #sys.stdout.flush()
            #sys.stdout.write('.')
            #sys.stdout.flush()

            for idx, individual in enumerate(slic):
                #print('lel')
                #print(individual)
                #print('pop')
                #print(len(population))
                #print('simu')
                #print(len(simu))
                #print(idx)
                simu[idx].indi = individual
                simu[idx].parent_pipe.send(individual)

            #print('lel2')
            t = 0
            while True:
                #print('in loop1')
                try:
                    for sim in simu:
                        #print('in loop1 lel')
                        if sim.simok == False:
                            rec = sim.parent_pipe.recv()
                            if rec == "simok":
                                sim.simok = True
                                t += 1
                    if t == MAX_PARALLEL:
                        t = 0
                        break
                except:
                    continue
            #print('lel3')
            while True:
                #print('in loop2')
                try:
                    for sim in simu:
                        rec = sim.parent_pipe.recv()
                        contact, base_pos, base_angle = rec[-1]
                        if len(contact) == 6 and len(base_pos) == 3 and len(
                                base_angle) == 3:
                            sim.data = rec
                            sim.parent_pipe.send('dataok')
                            t += 1
                    if t == MAX_PARALLEL:
                        t = 0
                        break
                except:
                    continue

            for sim in simu:
                sim.simok = False
                sim.parent_pipe.send('reset')
            #print('lel4')
            while True:
                #print('in loop3')
                try:
                    for sim in simu:
                        rec = sim.parent_pipe.recv()
                        if rec == "resok":
                            t += 1
                    if t == MAX_PARALLEL:
                        t = 0
                        break
                except:
                    continue

            for sim in simu:
                #fitness_val = genetica.fitness(sim.data[0],sim.data[1],sim.data[2])
                dd = 0
                for x in sim.data:
                    #print(dd)
                    #print(len(sim.data))
                    if x == sim.data[-1]:
                        dd += genetica.fitness(x[0], x[1], x[2])
                    else:
                        dd += genetica.stability(x[0], x[1], x[2])
                fitness_val = dd
                #print("lelelee")
                #print(sim.indi)
                individual = convertToGen(sim.indi)
                #print("lvggjvjhg")
                #print(len(individual))
                pair = (individual, fitness_val)
                weighted_population.append(pair)

        population = []
        #for x in range(GAIT_STEPS)
        pop_sorted, pop_fitness = genetica.sort_pop(weighted_population)
        #print(pop_sorted[0])
        print(pop_fitness)
        #saveToFile(str(generation)+" best fitness: " + str(pop_fitness[0]), [pop_sorted + pop_fitness])
        saveToFile(
            filename, "Generation: " + str(generation) + " best fitness: " +
            str(pop_fitness[0]), [pop_fitness[:15], pop_sorted[:15]])
        #print("saved to file")

        #2 parents survive
        a = convertToSim(pop_sorted[0])
        b = convertToSim(pop_sorted[1])
        population = [a, b]
        #print("D-1")
        #print(a)
        #print("D0")
        #print(b)
        #print("D1")
        #print(population)
        #nn = [genetica.mutate(a,1,1), genetica.mutate(a,1,1), genetica.mutate(b,1,1)]
        y = 0
        while y < 2:
            z = genetica.mutate(a, 1, 1)
            if z not in population:
                population.append(z)
                y += 1
        #print("D2")
        #print(z)
        y = 0
        while y < 2:
            z = genetica.mutate(b, 1, 1)
            if z not in population:
                population.append(z)
                y += 1
        #print("D3")
        #print(z)
        #population = [a, b, genetica.mutate(a,1,1), genetica.mutate(a,1,1), genetica.mutate(b,1,1)]

        old_sel = genetica.select_population(pop_sorted)
        #print("old_sel")
        #print(old_sel[0])
        #for ind in old_sel:
        #    population.append(convertToSim(ind))
        #old_sel = genetica.tournamen(old_s el)
        #print(len(old_sel[0]))
        #print(old_sel)

        children = genetica.get_children(old_sel, len(population))

        #for x in range(TOURNAMENT):
        #    population.append(genetica.gen_chromosome())

        for indiv in children:
            #print("D4x")
            #print(indiv)
            while True:
                #print('child loop2')
                #print("D4445")
                #print(indiv)
                #print('size')
                #print(len(indiv))
                ind = convertToSim(indiv)
                #print("D5")
                #print(indiv)
                mu = genetica.mutate(ind)
                if mu not in population:
                    population.append(mu)
                    break

        #print("lele2")
        #print("population size")
        #print(len(population))
        #print(population)
    print("end")
    for sim in simu:
        sim.multi_stop()
Пример #21
0
from classic import Classic
from genetic import Genetic

if __name__ == "__main__":
    a = Classic(2, -5, 47, -3, 4, 0)
    a.run()
    b = Genetic(2, -5, 47, -3, 4, a.f_max, a.f_min, 0)
    b.run()
Пример #22
0
 def __handle_button_pressed(self):
     print("clicked")
     algorithm_config = self.__get_variable_configurations()
     self.__genetic = Genetic(algorithm_config)
     self.__print_result(self.__genetic)
Пример #23
0
#!/usr/bin/env python3

#from prepa import prepa
from genetic import Genetic
import json

source_file_name = 'settings.json'
#source_file_name = 'settings_2.json'

with open(source_file_name) as json_data:
    settings = json.load(json_data)
    print(settings)
engine = Genetic(settings)

engine.generate_first_population()
engine.show_population(True)

engine.cross()
engine.show_population()

#engine.mutate()

#engine.selection()
#engine.show_population(True)

#engine.loop(15)

#engine.solve()

# То, что мы называем особью, ещё называют хромосомой.
Пример #24
0
def main():
    genetic = Genetic(200, 200, 50, 0.1, [(130, 130, 200, 150)])
    genetic.simulate_with_graphics()
Пример #25
0
def main():
    graph = Graph()

    while 1:
        clear()
        print(
            "Program do wyznaczania optymalnego cyklu Hamiltiona dla problemu komiwojażera\n"
        )

        if graph.number_of_cities != 0:
            print("Liczba wierzchołków aktualnie wczytanego grafu: " +
                  str(graph.number_of_cities) + "\n")
        else:
            print("Aktualnie nie wczytano żadnego grafu\n")
        print("Wybierz funkcjonalność")
        print("1. Wczytaj małą macierz grafu")
        print("2. Wczytaj dużą macierz grafu")
        print("3. Wyświetl macierz kosztów")
        print("4. Brute Force")
        print("5. Programowanie dynamiczne")
        print("6. Symulowane wyżarzanie")
        print("7. Algorytm genetyczny")
        print("8. Przeprowadź testy seryjne")
        print("9. Zakończ działanie programu")
        choice = input("\nPodaj numer: ")
        if choice == '1':
            clear()
            print("Lista dostępnych plików:\n-----------")
            print(*listdir(get_script_path() + "/matrixes/small/"), sep='\n')
            print("-----------")
            file_name = input("Podaj nazwę pliku z małym grafem: ")
            graph = Graph(file_name, 0)
            print("Wczytano graf z " + str(graph.number_of_cities) +
                  " wierzchołkami\nAby kontynuwać wciśnij dowolny "
                  "klawisz")
            choice = 0
            input()

        if choice == '2':
            clear()
            print("Podaj nazwę pliku z dużym grafem")
            print(*listdir(get_script_path() + "/matrixes/large/"), sep='\n')
            file_name = input()
            graph = Graph(file_name, 1)
            print("Wczytano graf z " + str(graph.number_of_cities) +
                  " wierzchołkami")
            print_to_continue()
            choice = 0

        if choice == '3':
            clear()
            if graph.number_of_cities != 0:
                graph.display_cost_matrix()
            else:
                print("Nie wczytano żadnego grafu")
            print_to_continue()

        if choice == '4':
            if graph.file_name != "":
                bf = BruteForce(graph)
                bf.starting_vertex = 0
                bf.start(0)
                print("Najlepszy cykl ma wagę: " + str(bf.best_cycle_cost))
                print("Optymalny cykl: ")
                bf.display_optimal_route()
            else:
                print("Nie wczytano żadnego grafu")
            print_to_continue()

        if choice == '5':
            if graph.file_name != "":
                dp = DynamicProgramming(graph)
                dp.start(0)
                print("Najlepszy cykl ma wagę: " + str(dp.best_cycle_cost))
                print("Optymalny cykl: ")
                dp.display_optimal_route()
            else:
                print("Nie wczytano żadnego grafu")
            print_to_continue()

        if choice == '6':
            if graph.file_name != "":
                t_0 = float(input("Temperatura początkowa wyżarzania: "))
                t_min = float(input("Temperatura minimalna wyżarzania: "))
                t_coefficient = float(
                    input("Współczynnik wyżarzania z zakresu (0,1): "))
                sa = SimulatedAnnealing(graph)
                start = timer()
                sa.start(t_0, t_min, t_coefficient)
                end = timer()
                time = format(end - start, '.8f')
                print(time)
                print("Najlepszy cykl ma wagę: " + str(sa.best_cycle_cost))
                print("Optymalny cykl: ")
                sa.display_optimal_route()
            else:
                print("Nie wczytano żadnego grafu")
            print_to_continue()

        if choice == '7':
            if graph.file_name != "":
                size_of_population = int(
                    input("Podaj początkową liczebność populacji: "))
                number_of_generations = int(
                    input("Podaj liczbę pokoleń, która ma się urodzić: "))
                cross_probability = float(
                    input("Podaj prawdopodobieństwo krzyżowania: "))
                mutation_probability = float(
                    input("Podaj prawdopodobieństwo mutacji: "))
                # size_of_population = 10
                # number_of_generations = 150
                # cross_probability = 0.6
                # mutation_probability = 0.2
                gen = Genetic(graph)
                start = timer()
                gen.start(size_of_population, number_of_generations,
                          cross_probability, mutation_probability)
                end = timer()
                time = format(end - start, '.8f')
                print(time)
                print("Najlepszy cykl ma wagę: " + str(gen.best_cycle_cost))
                print("Optymalny cykl: ")
                gen.display_optimal_route()
            else:
                print("Nie wczytano żadnego grafu")
            print_to_continue()

        if choice == '8':
            if graph.file_name != "":
                test(graph)
            else:
                print("Nie wczytano żadnego grafu")
            print_to_continue()

        if choice == '9':
            print_to_continue()
            clear()
            return
Пример #26
0
 def __init__(self):
     #self.hill_climbing = HillClimbing()
     #self.mcmc = MCMC()
     self.genetic = Genetic()
     self.coordinate_descent = CoordinateDescent()
     return None
Пример #27
0
from genetic import Genetic

g = Genetic('data.xml')
g.__main__()
Пример #28
0
def main():
    print "Witaj Swiecie!"
    weryfikujacy = generateNumbers(LENDANE, X, Y)  #ile, przedzial-przedzial
    print "Stworzono ciag weryfikacyjny"
    print "Wyrzucenie danych"
    Genetic(weryfikujacy, LENPOLUATION, X, Y).run()
Пример #29
0
    #-------------------------------------------------------#
    # 							main 						#
    #-------------------------------------------------------#
    print('Setting Generation Class')
    initial = Generation(numOfInd, 0)
    print('Generating random initial chromosomes')
    initial.randomGenerateChromosomes(
        chromosome_length)  # initial generate chromosome

    print('Setting Clustering Class')
    clustering = Clustering(initial, data, kmax)  # eval fit of chromosomes

    # ------------------calc fitness------------------#
    print('Calculating initial fitness')
    generation = clustering.calcChromosomesFit()

    # ------------------------GA----------------------#
    print('Looping through each generation')
    while generationCount <= budget:
        print('Generation ' + str(generationCount) + ':')
        print('\tSetting up Genetic class')
        GA = Genetic(numOfInd, Ps, Pm, Pc, budget, data, generationCount, kmax)
        print('\tExecuting genetic process')
        generation, generationCount = GA.geneticProcess(generation)
        iBest = generation.chromosomes[0]
        clustering.printIBest(iBest)

    # ------------------output result-------------------#
    clustering.output_result(iBest, data)
def NumberCombinations():
    gen = Genetic("nums.txt", 20, 0.3)
    o = gen.compute_member_output("00100110001110101001")