示例#1
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)
示例#2
0
def test():
    population_size = 10
    my_registers = read_registries()
    initial_population = []

    #establishing a population with non-negative fitness
    for i in range(0, population_size):
        myInd = Individual()
        while myInd.fitness <= 0:
            myInd.randomize(my_registers)
            Genetic.fitness(myInd)

        initial_population.append(myInd)

    #print_all_gen(initial_population)
    #print("----------------")

    print(
        "\n/////////////////////////////////////////////GENERATION: {}".format(
            0))
    new_gen = Genetic.breed(initial_population, my_registers)
    for i in range(1, 50):
        print("\n/////////////////////////////////////////////GENERATION: {}".
              format(i))
        new_gen = Genetic.breed(new_gen, my_registers)
示例#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
def test_mutate():
    g = Genetic()
    for i in range(100):
        a = Individual()

        o = g.mutate(a)
        assert not o.dna.__contains__(None)
示例#5
0
def main():

    population_size = 10
    my_registers = read_registries()
    initial_population = []

    #establishing a population with non-negative fitness
    for i in range(0, population_size):
        myInd = Individual()
        while myInd.fitness <= 0:
            myInd.randomize(my_registers)
            Genetic.fitness(myInd)

        initial_population.append(myInd)

    new_gen = Genetic.breed(initial_population, my_registers)

    #evaluating till we get top == 100
    top_fitness = 0
    try:
        while top_fitness < 100:

            if top_fitness != 0:
                new_gen = Genetic.breed(new_gen, my_registers)

            for item in new_gen:
                if item.fitness > top_fitness:
                    top_fitness = item.fitness
                    #print("{} broke to: {}".format(item, top_fitness))

        print_all_gen(new_gen)
    except KeyboardInterrupt:
        print_all_gen(new_gen)
示例#6
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()
示例#7
0
def test_mate():
    g = Genetic()
    for i in range(100):
        a = Individual()
        b = Individual()

        o = g.mate(a, b)
        assert not o[0].dna.__contains__(None)
        assert not o[1].dna.__contains__(None)
示例#8
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
示例#9
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)
示例#10
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
示例#11
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)
示例#12
0
 def __init__(self, p, n, log='log', vis=0, al=0):  # al - plot analyze
     # pu.db
     s = """ Keyboard:
         Space - show
         Up - log now
         Down - stop"""
     print s
     self.WD = FIELD_SIZE[0] * TILE_WIDTH + INFO[0] * TILE_WIDTH * 2
     self.HG = FIELD_SIZE[1] * TILE_WIDTH + INFO[0] * TILE_WIDTH * 2
     # self.WD = 1024
     # self.HG = 768
     self.al = al
     self.vis = vis
     size = FIELD_SIZE
     self.timestamp = reduce(lambda x, y: str(x) + '_' + str(y), [i for i in dt.now().timetuple()][0:6])
     self.foldername = 'Logs'
     self.full_folder = self.foldername + os.sep + self.timestamp + os.sep
     self.logfile = str(p) + '_' + str(n) + '_' + str(DEFAULT_TYPE) + log
     self.mousex, self.mousey = 0, 0
     self.Field = Field(size)
     self.MainWindow = None
     self.mousexy = pygame.mouse.get_pos()
     self.fpsClock = pygame.time.Clock()
     if self.vis:
         pygame.display.set_mode((self.WD, self.HG), pygame.NOFRAME)
         self.MainWindow = Window(self.Field, self.WD, self.HG)
     self.g = Genetic(p, n, field_size=size, delta=-0.5)
     self.pos = [2, 2]
     self.a = None
     self.b = None
     self.his = None
     self.show = 0
     self.run = 1
     self.ep_num = 0
     self.log_now = 0
示例#13
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()
示例#14
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()
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()
示例#16
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)
示例#17
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)
示例#18
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;
示例#19
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)
示例#20
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)
示例#21
0
 def test_select_best_too_much(self):
     pop = [-1, 2, 0]
     res = Genetic.select_best(lambda pop: [i for i in pop], 'min', pop, 4)
     self.assertEqual(pop, res)
示例#22
0
 def test_select_best_zero(self):
     res = Genetic.select_best(lambda pop: [i for i in pop], 'min', [-1, 2, 0], 0)
     self.assertEqual([], res)
示例#23
0
 def test_mutate2(self):
     point, mutations = Genetic.mutate((1, 0), 0, 0.5, 0.5)
     self.assertEqual((1, 0), point)
     self.assertEqual(0, mutations)
示例#24
0
 def test_mutate(self):
     point, mutations = Genetic.mutate((1, 0), 1, 0.5, 0.5)
     self.assertNotEqual((1, 0), point)
     self.assertEqual(2, mutations)
示例#25
0
 def __handle_button_pressed(self):
     print("clicked")
     algorithm_config = self.__get_variable_configurations()
     self.__genetic = Genetic(algorithm_config)
     self.__print_result(self.__genetic)
示例#26
0
 def test_normalize_fitness_equals_all_best(self):
     res = Genetic.normalize_fitness([1, 1, 1], 'max')
     self.assertEqual([1, 1, 1], res)
示例#27
0
 def test_normalize_fitness_min(self):
     res = Genetic.normalize_fitness([1, 2, 4, 1], 'min')
     self.assertEqual([0.375, 0.25, 0.0, 0.375], res)
示例#28
0
 def test_normalize_fitness_sum_is_1(self):
     res = Genetic.normalize_fitness([1, 1, 2, 5, 1, 3], 'max')
     self.assertEqual(1, fsum(res))
示例#29
0
class Optymalizacja(QtGui.QMainWindow):
    LIMIT_X = [-5, 5]
    LIMIT_Y = [-5, 5]

    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = MainForm()
        self.ui.setupUi(self)
        self.genetic = None
        self.epochNumber = 0
        self.steps = []
        self.function = None
        self.range = []
        self.chance = 10
        self.m = 2
        QtCore.QObject.connect(self.ui.calculateButton, QtCore.SIGNAL("clicked()"), self.calculate)
        QtCore.QObject.connect(self.ui.stepButton, QtCore.SIGNAL("clicked()"), self.epoch)
        QtCore.QObject.connect(self.ui.drawButton, QtCore.SIGNAL("clicked()"), self.draw)
        QtCore.QObject.connect(self.ui.complate, QtCore.SIGNAL("clicked()"), self.complate)
        QtCore.QObject.connect(self.ui.complate_without_draw, QtCore.SIGNAL("clicked()"), self.complate_without_draw)
        QtCore.QObject.connect(self.ui.points, QtCore.SIGNAL("clicked()"), self.points)

    def calculate(self, draw=True):
        # Cross
        if self.ui.cross_simple_2.isChecked():
            crossing = mix_simple
        elif self.ui.cross_artmetic_2.isChecked():
            crossing = aritmic_selection
        else:
            raise TypeError('Not selected crossing')
        # Mutation
        if self.ui.mutation_unity_2.isChecked():
            fmutation = mutation
        elif self.ui.mutation_nonunity_2.isChecked():
            fmutation = mutation_nonlinear
        elif self.ui.mutacion_gradient_2.isChecked():
            fmutation = None
        else:
            raise TypeError('Not selected mutattion')
        # Function
        if self.ui.function_rosenbrock_2.isChecked():
            self.function = rosenbrock
        elif self.ui.function_akley_2.isChecked():
            self.function = ackley
        elif self.ui.function_gem_2.isChecked():
            self.function = geem
        elif self.ui.function_golstein_2.isChecked():
            self.function = goldstein
        elif self.ui.function_rastring_2.isChecked():
            self.function = restring
        else:
            tmp_function = self.ui.function_recipce.toPlainText()
            self.function = lambda *x: eval(tmp_function)
            m = re.findall("x\[\d\]", tmp_function)
            chop = lambda x: int(x[2:-1])
            self.m = max(list(map(chop, m))) + 1
        if self.ui.strategy_genetic.isChecked():
            strategy = 'genetic'
        elif self.ui.strategy_two.isChecked():
            strategy = 'two'
        elif self.ui.strategy_milambda.isChecked():
            strategy = 'mi_lambda'
        elif self.ui.strategy_mipluslambda.isChecked():
            strategy = 'mi_plus_lambda'
        #limit
        try:
            tmp = self.ui.range.toPlainText()
            tmp = tmp.split(";")
            self.range = [list(map(float, t.split())) for t in tmp]
        except:
            self.range = [self.LIMIT_X, self.LIMIT_Y]
        try:
            self.chance = float(self.ui.proc_mutation.toPlainText().split(';')[0])
        except:
            self.chance = 10
        if draw:
            f = paint_function(self.range, self.function)
            scene = QtGui.QGraphicsScene()
            scene.addPixmap(QtGui.QPixmap(f.name))
            self.ui.graphicsView_2.setScene(scene)
            f.close()
            os.unlink(f.name)

        mi = int(self.ui.mi.toPlainText())
        lambd = int(self.ui.lambd.toPlainText())
        self.genetic = Genetic(self.function, crossing, fmutation, strategy, mi, lambd, self.range, self.m, self.chance)
        self.steps = []
        self.ui.graphicsView_2.setViewport(QtOpenGL.QGLWidget())
        self.epochNumber = 0

    def epoch(self):
        self.genetic.sort()
        self.genetic.newEpoch(self.epochNumber)
        self.epochNumber += 1
        self.ui.epochNumber.display(self.epochNumber)
        self.genetic.sort()
        self.ui.targetLabel.setText(str(round(self.genetic.population[0].cost, 7)))
        self.ui.coordsLabel.setText("Rozwiązanie: x: {0} y: {1}".format(round(self.genetic.population[0].getValue(self.range[0][0], self.range[0][1], 0), 7),
                                                                        round(self.genetic.population[0].getValue(self.range[1][0], self.range[1][1], 1), 7)))
        self.steps.append((round(self.genetic.population[0].getValue(self.range[0][0], self.range[0][1], 0), 7),
                           round(self.genetic.population[0].getValue(self.range[1][0], self.range[1][1], 1), 7)))

    def complate(self):
        n = int(self.ui.n.toPlainText())
        if not n:
            raise TypeError('Nie podano warunku zakończenia')
        for i in range(n):
            self.genetic.sort()
            self.genetic.newEpoch(self.epochNumber)
            self.epochNumber += 1
            self.ui.epochNumber.display(self.epochNumber)
            self.genetic.sort()
            self.steps.append((round(self.genetic.population[0].getValue(self.range[0][0], self.range[0][1], 0), 7),
                           round(self.genetic.population[0].getValue(self.range[1][0], self.range[1][1], 1), 7)))
        self.ui.targetLabel.setText(str(round(self.genetic.population[0].cost, 7)))
        self.ui.coordsLabel.setText("Rozwiązanie: x: {0} y: {1}".format(round(self.genetic.population[0].getValue(self.range[0][0], self.range[0][1], 0), 7),
                                                                        round(self.genetic.population[0].getValue(self.range[1][0], self.range[1][1], 1), 7)))

    def complate_without_draw(self):
        self.calculate(False)
        n = int(self.ui.n.toPlainText())
        if not n:
            raise TypeError('Nie podano warunku zakończenia')
        for i in range(n):
            self.genetic.sort()
            self.genetic.newEpoch(self.epochNumber)
            self.epochNumber += 1
            self.ui.epochNumber.display(self.epochNumber)
            self.genetic.sort()
            self.steps.append(self.genetic.population[0].getValues(self.range))
        self.ui.targetLabel.setText(str(round(self.genetic.population[0].cost, 7)))
        result = self.genetic.population[0].getValues(self.range)
        tmp = "Rozwiazanie: "
        i = 1
        for r in result:
            tmp += "x{0} = {1} ".format(i, round(r, 6))
            if i % 4 == 0:
                tmp += '\n'
            i += 1
        self.ui.coordsLabel.setText(tmp)

    def draw(self):
        f = paint_function(self.range, self.function, self.steps)
        scene = QtGui.QGraphicsScene()
        scene.addPixmap(QtGui.QPixmap(f.name))
        self.ui.graphicsView_2.setScene(scene)
        f.close()
        os.unlink(f.name)

    def points(self):
        with open('points.txt', 'w') as f:
            for point in self.steps:
                f.write("{0} : {1}\n".format(str(point), self.function(*point)))
        pass
示例#30
0
    def calculate(self, draw=True):
        # Cross
        if self.ui.cross_simple_2.isChecked():
            crossing = mix_simple
        elif self.ui.cross_artmetic_2.isChecked():
            crossing = aritmic_selection
        else:
            raise TypeError('Not selected crossing')
        # Mutation
        if self.ui.mutation_unity_2.isChecked():
            fmutation = mutation
        elif self.ui.mutation_nonunity_2.isChecked():
            fmutation = mutation_nonlinear
        elif self.ui.mutacion_gradient_2.isChecked():
            fmutation = None
        else:
            raise TypeError('Not selected mutattion')
        # Function
        if self.ui.function_rosenbrock_2.isChecked():
            self.function = rosenbrock
        elif self.ui.function_akley_2.isChecked():
            self.function = ackley
        elif self.ui.function_gem_2.isChecked():
            self.function = geem
        elif self.ui.function_golstein_2.isChecked():
            self.function = goldstein
        elif self.ui.function_rastring_2.isChecked():
            self.function = restring
        else:
            tmp_function = self.ui.function_recipce.toPlainText()
            self.function = lambda *x: eval(tmp_function)
            m = re.findall("x\[\d\]", tmp_function)
            chop = lambda x: int(x[2:-1])
            self.m = max(list(map(chop, m))) + 1
        if self.ui.strategy_genetic.isChecked():
            strategy = 'genetic'
        elif self.ui.strategy_two.isChecked():
            strategy = 'two'
        elif self.ui.strategy_milambda.isChecked():
            strategy = 'mi_lambda'
        elif self.ui.strategy_mipluslambda.isChecked():
            strategy = 'mi_plus_lambda'
        #limit
        try:
            tmp = self.ui.range.toPlainText()
            tmp = tmp.split(";")
            self.range = [list(map(float, t.split())) for t in tmp]
        except:
            self.range = [self.LIMIT_X, self.LIMIT_Y]
        try:
            self.chance = float(self.ui.proc_mutation.toPlainText().split(';')[0])
        except:
            self.chance = 10
        if draw:
            f = paint_function(self.range, self.function)
            scene = QtGui.QGraphicsScene()
            scene.addPixmap(QtGui.QPixmap(f.name))
            self.ui.graphicsView_2.setScene(scene)
            f.close()
            os.unlink(f.name)

        mi = int(self.ui.mi.toPlainText())
        lambd = int(self.ui.lambd.toPlainText())
        self.genetic = Genetic(self.function, crossing, fmutation, strategy, mi, lambd, self.range, self.m, self.chance)
        self.steps = []
        self.ui.graphicsView_2.setViewport(QtOpenGL.QGLWidget())
        self.epochNumber = 0
示例#31
0
        for model_file in glob.glob(os.path.join(models_dir,'*.poly')):
            model_tmp = np.loadtxt(model_file, dtype=[('x',float),('y',float)])
            model = interp1d(model_tmp['x'], model_tmp['y'])
            chi2.append(np.sum((model(self._x)-self._y)**2))
            name = model_file.split('/')[-1].replace('.poly','')
            model_name.append(name)

            fig = mpl.figure()
            ax = fig.add_subplot(111)
            ax.scatter(self._x, self._y)
            ax.plot(model_tmp['x'], model_tmp['y'])
            fig.savefig(plots_dir + name + '.png')

        t = atpy.Table()
        t.add_column('model_name', model_name, dtype='|S30')
        t.add_column('chi2', chi2)
        t.write(output_file)

poly_model = os.path.abspath('run_poly_model.py')
model_fitter = PolyFitter('data_example_serial_file')

g = Genetic(100, 'models_example_serial_file', 'template.par', 'example_serial_file.conf', existing=False, mode='serial_file')

for generation in range(1,50):

    g.initialize(generation)
    g.make_par_table(generation)
    g.make_par_indiv(generation, parser)
    g.compute_models(generation, poly_model)
    g.compute_fits(generation, model_fitter)
示例#32
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()

# То, что мы называем особью, ещё называют хромосомой.
示例#33
0
 def test_sorted_normed_fitness(self):
     res = Genetic.sorted_normed_fitness(lambda pop: [sum(i) for i in pop], 'max', [(1, 0), (3, 4)])
     self.assertEqual([(1, 1.0), (0, 0.0)], res)
示例#34
0
from genetic import Genetic

g = Genetic('data.xml')
g.__main__()
示例#35
0
 def test_sorted_normed_fitness2(self):
     res = Genetic.sorted_normed_fitness(lambda pop: [i for i in pop], 'min', [-1, 2, 0])
     self.assertEqual([(0, 0.6), (2, 0.4), (1, 0.0)], res)
示例#36
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)
示例#37
0
class Game(object):
    def __init__(self, p, n, log='log', vis=0, al=0):  # al - plot analyze
        # pu.db
        s = """ Keyboard:
            Space - show
            Up - log now
            Down - stop"""
        print s
        self.WD = FIELD_SIZE[0] * TILE_WIDTH + INFO[0] * TILE_WIDTH * 2
        self.HG = FIELD_SIZE[1] * TILE_WIDTH + INFO[0] * TILE_WIDTH * 2
        # self.WD = 1024
        # self.HG = 768
        self.al = al
        self.vis = vis
        size = FIELD_SIZE
        self.timestamp = reduce(lambda x, y: str(x) + '_' + str(y), [i for i in dt.now().timetuple()][0:6])
        self.foldername = 'Logs'
        self.full_folder = self.foldername + os.sep + self.timestamp + os.sep
        self.logfile = str(p) + '_' + str(n) + '_' + str(DEFAULT_TYPE) + log
        self.mousex, self.mousey = 0, 0
        self.Field = Field(size)
        self.MainWindow = None
        self.mousexy = pygame.mouse.get_pos()
        self.fpsClock = pygame.time.Clock()
        if self.vis:
            pygame.display.set_mode((self.WD, self.HG), pygame.NOFRAME)
            self.MainWindow = Window(self.Field, self.WD, self.HG)
        self.g = Genetic(p, n, field_size=size, delta=-0.5)
        self.pos = [2, 2]
        self.a = None
        self.b = None
        self.his = None
        self.show = 0
        self.run = 1
        self.ep_num = 0
        self.log_now = 0

    def mouse_button_up(self, GameMap):
        pass

    def do_update(self, i, be):
        if not i % 100:
            self.log_now = 1
        self.MainWindow.loading(i, WD=self.WD, HG=self.HG, EN=self.g.epoch_num, BE=be)
        pygame.display.update()
        self.user_action()
        self.fpsClock.tick(1)
        if self.log_now:
            l = Logger(None, self.g.score_history, self.g.time, self.logfile + str(i), folder=self.full_folder)
            l2 = Logger(None, self.g.best_ever[0], self.g.time, self.logfile + 'BE' + str(i), folder=self.full_folder)
            l.log()
            l2.log()
            self.log_now = 0
        return self.run

    def do_genetic(self):
        try:
            self.ep_num = self.g.start(f=self.do_update)
        except Exception, e:
            print 'Error in genetic ' + str(e)
        self.a = self.g.get_score()
        self.b = self.g.best_ever[1]
        # print self.a
        # self.Field = self.a[2]
        # pers = self.a[-2]
        # self.his = pers.history
        l = Logger(self.a, self.g.score_history, self.g.time, self.logfile, folder=self.full_folder)
        l2 = Logger(self.b, self.g.best_ever[0], self.g.time, self.logfile + 'BE', folder=self.full_folder)
        l.log()
        l2.log()