Ejemplo n.º 1
0
    def goThread(self):
        # get params
        filename = self.getTraincomboBox.currentText()
        num_iter, num_neuron = self.iterTimesSpinBox.value(
        ), self.num_nSpinBox.value()
        population = self.populationSpinBox.value()
        p_c = self.p_cdoubleSpinBox.value()
        p_m = self.p_mDoubleSpinBox.value()
        self.errorNumLabel.setText('Inf')
        # print(filename, num_iter, num_neuron, population, p_c, p_m)

        # ga
        self.stop_threads = False
        self.g = ga.GA(num_iter, population, p_m, p_c, num_neuron, filename,
                       self.wheel.isChecked())
        for i in range(num_iter):
            if self.stop_threads:
                break
            self.IterNumLabel.setText(str(i + 1))
            self.g.evolution()
            if self.g.BestRBFN:
                self.errorNumLabel.setText('{:2.2f}'.format(
                    self.g.BestRBFN.error))
            QtWidgets.QApplication.processEvents()
        # print(self.g.BestRBFN.mu)
        self.g.BestRBFN.saveParams()
        # reset getParamcomboBox
        self.getParamcomboBox.clear()
        comboList = os.listdir(parent + '/weights/')
        self.getParamcomboBox.addItems(comboList)
        self.Go.setEnabled(True)
Ejemplo n.º 2
0
def main():

    while True:
        file = createdata.choose_file(os.getcwd() + '\\instances')
        # file = ''.join((os.getcwd(), '\\instances\\bier127.txt'))
        if createdata.check_file(file):
            matrix = createdata.create_matrix(file)
            break
        else:
            print("Choose another file or use a generator.")

    pygame.init()
    pygame.display.set_caption("TSP Genetic Algorithm")
    clock = pygame.time.Clock()
    font = pygame.font.SysFont('Calibri', 25)
    run = True
    win = pygame.display.set_mode((WIDTH, HEIGHT))
    colour = (127, 0, 127)
    # start_time = time.time()

    genetic = ga.GA(matrix)
    genetic.create_first_generation()
    elements = create_list(file)
    max_x, max_y = calculate_scale(elements)
    elements = refactor_lis(elements, max_x, max_y)
    while run:
        win.fill((0, 0, 0))
        clock.tick(30)

        for click in pygame.event.get():
            if click.type == pygame.QUIT:
                run = False

        # draw points on the surface
        for x, y in elements:
            pygame.draw.circle(win, colour, (x, y), 5)

        # get and draw the currently shortest route
        route = genetic.run()
        for i in range(len(route)):
            pygame.draw.line(win, colour,
                             (elements[route[i]][0], elements[route[i]][1]),
                             (elements[route[(i + 1) % (len(route))]][0],
                              elements[route[(i + 1) % (len(route))]][1]))

        # print information about algorithm results
        num_gen_txt = font.render(
            'Number of generation: ' + str(genetic.number_of_generation),
            False, colour)
        route_len_txt = font.render(
            'Length of the shortest route: ' + str(genetic.shortest_distance),
            False, colour)
        win.blit(num_gen_txt, (0, 0))
        win.blit(route_len_txt, (0, 30))

        pygame.display.update()
    pygame.quit()
Ejemplo n.º 3
0
def main():

    #If user wanted to specify own parameters retrieve them from command line
    if len(sys.argv) == 6:
        networkType = sys.argv[1]
        numIterations = int(sys.argv[2])
        populationSize = int(sys.argv[3])
        selection = sys.argv[4]
        crossover = sys.argv[5]
        crossoverProb = float(sys.argv[6])
        mutationProb = float(sys.argv[7])

    #If not specifed then these are default parameters
    else:
        networkType = "cnn"
        numIterations = 1
        populationSize = 2
        selection = "rs"
        crossover = "uc"
        crossoverProb = 0.8
        mutationProb = 0.2

    #Will define the choice of parameters for neral network
    if (networkType == "nn"):

        #Dictionary of parameters
        nnParams = {
            "epochs": [10],
            "learningRate": [1, 0.5, 0.1],
            "hiddenInfo": [[], [300], [150, 100]],
            "startWeights": [0, 1, 0.15, 0.2, 0.25],
        }

    #Will define the choice of parameters for convolutional neural network
    else:
        #Dictionary of possible paramaters
        nnParams = {
            "epochs": [1],
            "dropout": [True, False],
            "batch_size": [32],
            "optimizer": ['sgd', 'rmsprop', 'adam'],
            "data_augmentation": [False],
            "convActivation": ['relu', 'elu', 'sigmoid'],
            "denseActivation": ['softmax', 'tanh', 'sigmoid']
        }

    #Run the ga algorithm to find optimal set of parameters
    geneticAlg = ga.GA(networkType, numIterations, populationSize, selection,
                       crossover, crossoverProb, mutationProb, nnParams)
    geneticAlg.runGA()
Ejemplo n.º 4
0
def run_experiment(id_: int):
    # Starting genetic algorithm
    gene_pool = ga.GA(popu_size=settings['experiment']['population'],
                      n_survivors=settings['experiment']['survivors'],
                      n_champions=settings['experiment']['champions'])

    for i in range(settings['experiment']['generations']):
        worker_async_results = [
            rq_worker.run.delay(seeds) for seeds in gene_pool.genomes
        ]

        scores = wait_for_results(worker_async_results)

        survivors_scores, survivors_genomes = gene_pool.step(scores)

        np.savez("out_" + str(id_) + "/" + str(i) + ".npz",
                 scores=survivors_scores,
                 genomes=survivors_genomes)

        print("=== ID", id_, "Generation", i, "===\n", "Best scores:",
              list(reversed(survivors_scores)), "\n")
Ejemplo n.º 5
0
import ga

engine = ga.GA(items_cnt=1)
# размеры картинок
objs = [[60, 30], [50, 70], [30, 20], [40, 20], [30, 20], [20, 40]]
engine.initialisation(objs)
Ejemplo n.º 6
0
def debug(func, *args):
    if DEBUG:
        func(*args)


measurement_id = 17

db = dbm.DBExporter(dbtype='sqlite', dbname='vut_db.sqlite')
measured_data = db.columns_from_datatable(measurement_id)
#
# tenzometric = pd.read_csv('data/44 t.asc', sep='\t', header=0, skiprows=[1])
# t1 = tenzometric['T1']
# t2 = tenzometric['T2']
# t_avg = (t1 + t2) / 2 + 63
#
# measured_data = pd.DataFrame(zip(tenzometric['x'], -t_avg), columns=['x_axis', 'y_axis'])
# print(measured_data)

# model = models.Model('dynamic_single_winkler')
# model = models.Model('dynamic_single_winkler')
model = models.Model('dynamic_double_pasternak', False)

for i in range(20):
    gen_algs = ga.GA(model, measured_data, 500, 20)
    gen_algs.run_optimization(i)

end = time.time()

print(f'Time: {int(end - start)}')
Ejemplo n.º 7
0
def main():
    # argument parsing
    parser = argparse.ArgumentParser()
    parser.add_argument('data',
                        type=str,
                        default="rl11849.tsp",
                        help="Data file name  ex)rl11849.tsp")
    parser.add_argument('-p', type=int, default=200, help="Population size")
    parser.add_argument('-f',
                        type=int,
                        default=250,
                        help="Total number of fitness evaluations")
    parser.add_argument('-e',
                        type=int,
                        default=50,
                        help="The size of the elite population")
    parser.add_argument('-m',
                        type=float,
                        default=0.01,
                        help="Probability of the mutation")
    parser.add_argument('-plot',
                        type=str,
                        default='n',
                        choices=['n', 'y'],
                        help="Plot the distance-generation graph (y)es/(n)o")
    args = parser.parse_args()

    data_name = args.data
    pop_size = args.p
    generations = args.f
    elite_size = args.e
    mutation_rate = args.m
    is_plot = args.plot

    city_list = tsp_parser.parser(data_name)

    print("data: " + data_name)
    print("population size: " + str(pop_size))
    print("total generations: " + str(generations))
    print("elite size: " + str(elite_size))
    print("mutation_rate: " + str(mutation_rate))

    # declare model
    model = ga.GA(cityList=city_list,
                  popSize=pop_size,
                  eliteSize=elite_size,
                  mutationRate=mutation_rate,
                  generations=generations)
    progress = []
    progress.append(1 / model.rank_routes(model.population)[0][1])

    for i in tqdm(range(0, model.generations), desc="Evolving now..."):
        model.nextGeneration()
        progress.append(1 / model.rank_routes(model.population)[0][1])

    best_route = model.population[model.rank_routes(model.population)[0][0]]

    print("Final distance: " +
          str(1 / model.rank_routes(model.population)[0][1]))

    # plot the progress graph if argument plot is 'y'
    if is_plot == "y":
        plt.plot(progress)
        plt.ylabel('Distance')
        plt.xlabel('Generation')
        plt.show()

    # write solution file with best_route
    f = open('solution.csv', 'w', newline='')
    wr = csv.writer(f)
    for i in range(len(best_route)):
        wr.writerow([best_route[i]])

    f.close()
Ejemplo n.º 8
0
import numpy as np
import ga, pdb
from matplotlib import pyplot as plt

func0 = lambda x, y: x + y
func1 = lambda x: np.sin(10 * x) * x + np.cos(2 * x) * x

func2 = lambda x, y: x * np.cos(2 * np.pi * y) + y * np.sin(2 * np.pi * x)

func4 = lambda x, y, z, h: x * np.sin(10 * z) + y * np.cos(
    2 * np.pi * x) * np.sin(5 * np.pi * h) - h * np.cos(y * h)

nums1 = [[np.random.rand() * 5] for _ in range(100)]
nums2 = list(zip(np.arange(-4, 4, 0.4), np.arange(-4, 4, 0.4)))
#nums4 = list(zip(np.arange(-5, 5, 0.5), np.arange(-5, 5, 0.5), np.arange(-5, 5, 0.5), np.arange(-5, 5, 0.5)))
nums4 = ((np.random.rand(500, 4) - 0.5) * 10).tolist()
bound1 = [(0, 5)]
bound2 = [(-4, 4), (-4, 4)]
bound4 = [(-5, 5), (-5, 5), (-5, 5), (-5, 5)]

#pdb.set_trace()
ga = ga.GA(nums4, bound4, func4, DNA_SIZE=30, cross_rate=0.8, mutation=0.005)
iter_time = 200
ga.plot_in_jupyter_1d(iter_time)

plt.plot(ga.best_fit)
plt.xlabel("Iteration")
plt.ylabel("Fitness")
plt.savefig('result.png')
plt.show()
Ejemplo n.º 9
0
        file_path = os.path.join(dir_name, filename)
        try:
            shutil.rmtree(file_path)
        except OSError:
            os.remove(file_path)


remove_folder_content('log')
remove_folder_content('plots')

# pd.set_option('display.max_columns', None)

tenzometric = pd.read_csv('data/44t.asc', sep='\t', header=0, skiprows=[1])
t1 = tenzometric['T1']
t2 = tenzometric['T2']

epsilon = ((t1 + t2) + 125) / 1000000
E = 210e9
W = 330e-6
M = E * W * epsilon

measured_data = pd.DataFrame(zip(tenzometric['x'], -M), columns=['x_axis', 'y_axis'])

man = dtm.Manipulator(measured_data)
man.get_significant_points()
new_measured_data = man.get_measured_data()

model = models.Model('dynamic_double_pasternak')
gen_algs = ga.GA(model, new_measured_data, 640, 5, man)
gen_algs.run_optimization()
Ejemplo n.º 10
0
Archivo: main.py Proyecto: Alex9702/AG
import ga
import population

# Create GA object
g = ga.GA(100, 0.001, 0.95, 2)
# Initialize population
p = g.initPopulation(50)

# Evaluate population
g.evalPopulation(p)

# Keep track of current generation
generation = 1

# Start the evolution loop
#
# Every genetic algorithm problem has different criteria for finishing.
# In this case, we know what a perfect solution looks like (we don't
# always!), so our isTerminationConditionMet method is very
# straightforward: if there's a member of the population whose
# chromosome is all ones, we're done!

while g.isTerminationConditionMet(p) == False:
    # Print fittest individual from population
    print('Best solution: {}'.format(p.getFittest(0).toString()))

    #Apply crossover
    p = g.crossoverPopulation(p)

    # Apply mutation
    p = g.mutatePopulation(p)
Ejemplo n.º 11
0
def main():
    utils.Update_Console()
    testGA = ga.GA()
    testGA.Evolve()
Ejemplo n.º 12
0
                                      sheet_name='small_cars_terminal')
    Terminal = Structures.Terminal(data_car_terminal)
    #print('Возможности филиального транспорта: ', Terminal.terminal_count_car_dct)

    count_subblock = len(SUBBLOCK.subblock_index_dct)
    count_route_block = len(RB.routeblock_index_dct)

    for count_day in range(7, 8):
        print(count_day)
        alloc = Model.Allocation(
            SUBBLOCK.subblock_index_dct, SUBBLOCK.subblock_terminal_dct,
            SUBBLOCK.block_subblock_dct, RB.routeblock_index_dct,
            RB.routeblock_terminal_dct, RB.routeblock_distance_dct,
            RB.routeblock_volume_dct, RB.routeblock_adjacency_matrix,
            Terminal.terminal_count_car_dct, count_day)
        genetic = ga.GA(count_subblock * count_day, count_route_block)
        best_person, best_fitness = genetic.optimize(
            alloc.get_fitness_glob, genetic.initial_population)

        routeblock_day, routeblock_subblock, block_subblock = alloc.form_shedule(
            best_person)

        df_new = df.copy()
        df_new['day'] = df_new['Route_block'].replace(routeblock_day)
        df_new['subblock'] = df_new['Route_block'].replace(routeblock_subblock)
        df_new['block'] = df_new['subblock'].replace(block_subblock)
        write_result(df_new, 'Количество дней {}'.format(count_day))

        alloc.finale_check(best_person)

        print()
Ejemplo n.º 13
0
# Equation inputs.
function_inputs = [4, -2, 3.5, 5, -11, -4.7]
# Equation output.
function_output = 44

sol_per_pop = 8  # Number of solutions in the population.
num_parents_mating = 4  # Number of solutions to be selected as parents in the mating pool.
num_generations = 50  # Number of generations.

# Parameters of the mutation operation.
mutation_percent_genes = 10  # Percentage of genes to mutate.

# Creating an instance of the GA class inside the ga module. Some parameters are initialized within the constructor.
ga_instance = ga.GA(num_generations=num_generations,
                    sol_per_pop=sol_per_pop,
                    num_parents_mating=num_parents_mating,
                    function_inputs=function_inputs,
                    function_output=function_output,
                    mutation_percent_genes=10)

# Training the GA to optimize the parameters of the function.
ga_instance.train()

# After the generations complete, some plots are showed that summarize the how the outputs/fitenss values evolve over generations.
ga_instance.plot_result()

# Returning the details of the best solution.
best_solution, best_solution_fitness = ga_instance.best_solution()
print("Parameters of the best solution :", best_solution)
print("Fitness value of the best solution :", best_solution_fitness)
Ejemplo n.º 14
0
    return np.array(cost_avg), np.array(cost_std)


num_trails = 30
N = 50
max_iter = 160
sel_mode = 'TS'
population_size = 800
for sel_mode in ['TS', 'FPS']:
    ga_cost = []
    aver_cost, aver_runtime, num_succ = [], [], 0
    for i in (range(num_trails)):
        prob = problem.N_QueenProblem(N)
        ga = GA.GA(prob,
                   max_iter=max_iter,
                   mut_mode='SWAP',
                   sel_mode=sel_mode,
                   population_size=population_size)
        ga.loop()
        sol, runtime, final_cost, cost_his = ga.result()
        aver_runtime.append(runtime)
        aver_cost.append(final_cost)
        if final_cost == 0:
            num_succ += 1
        del prob, ga
        ga_cost.append(cost_his)

    print('    Genetic Algorithm')
    print('\tAverage Runtime :', np.average(aver_runtime))
    print('\tAverage Number of Attacks :', np.average(aver_cost))
    print('\tSuccess Rate :', num_succ / num_trails)
Ejemplo n.º 15
0
# numero de geracoes
ngen = 200

# probabilidade de difusao
p = 0.01

# probabilidade de mutacao
pm = 0.05

# carregando as sementes
df = pd.read_pickle(seeds_path + name + '.pkl')

# colunas do Dataframe: '0_degree', '1_betweennes', '2_pagerank', '3_closeness', '4_eigenvector', '5_pca', 'random'
seeds = list(df['0_degree'][:genes])

ag = ga.GA()

# configurando o AG
ag.properties(g,
              seeds,
              genes,
              population,
              random_seeds,
              model=model,
              selection=selection,
              iterations=it,
              ngen=ngen,
              p=p,
              pm=pm)

# executando o AG para um conjunto de sementes
Ejemplo n.º 16
0
RIGHT = 1
UP = 2
LEFT = 3

pygame.init()
pygame.font.init()
smaller_font = pygame.font.SysFont("Roboto", 45)
width, height = 900, 850
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("2048")
fps = 60
fps_clock = pygame.time.Clock()
running = True
simulating = False
avg, alive = -1, -1
ga = genetic_alg.GA(75 + 1)
speed = 1
amt_to_show = 1


def main():
    global running, simulating, avg, alive, width, speed, amt_to_show

    while running:
        screen.fill((0, 0, 0))

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
Ejemplo n.º 17
0
total_eval = 0  #总运行次数


def eval_fun(para):  #测试评价函数
    global total_eval
    total_eval += 1
    x = para_2_x(para[0])
    y = x * math.sin(3 * x)  #评价函数本身
    return y


population = []
for x in range(15):
    t = ga.DNAbase()
    population.append(t)
ga = ga.GA(population, 1, eval_fun)
ga.ini()
plt.scatter([para_2_x(x.para[0]) for x in ga.population],
            [x.score for x in ga.population],
            c=(1, 1, 0),
            s=50,
            marker='*')
for x in range(7):
    #fig=plt.figure()
    #plt.subplot(111,axisbg=(0.5,0.5,0.5))
    #plt.plot([x/10.0 for x in img_x],img_y,label="$xsin(3x)$",color=(1,0,0),linewidth=1)
    #plt.scatter([para_2_x(x.para[0]) for x in ga.population],[x.score for x in ga.population],c=(1,1,0),s=50,marker='*')
    ga.run()
    print(x, end='	')  #代数
    for y in ga.population:
        print('%.3f' % y.score, end=',[')
Ejemplo n.º 18
0
print('Problem (1): 8-queen problem (n = 8)')
print('    Hill Climbing')
print('\tAverage Runtime :', np.average(aver_runtime))
print('\tAverage Number of Attacks :', np.average(aver_cost))
print('\tSuccess Rate :', num_succ / num_trails)
hc_avg, hc_std = statics(hc_cost)
x_range = np.arange(len(hc_avg))
plt.rcParams["figure.figsize"] = [8, 4.5]
plt.plot(x_range, hc_avg, label='Hill Climbing')
plt.fill_between(x_range, hc_avg + hc_std, hc_avg - hc_std, alpha=0.15)

ga_cost = []
aver_cost, aver_runtime, num_succ = [], [], 0
for i in range(num_trails):
    prob = problem.N_QueenProblem(8)
    ga = GA.GA(prob, max_iter=25)
    ga.loop()
    sol, runtime, final_cost, cost_his = ga.result()
    aver_runtime.append(runtime)
    aver_cost.append(final_cost)
    if final_cost == 0:
        num_succ += 1
    del prob, ga
    ga_cost.append(cost_his)

print('    Genetic Algorithm')
print('\tAverage Runtime :', np.average(aver_runtime))
print('\tAverage Number of Attacks :', np.average(aver_cost))
print('\tSuccess Rate :', num_succ / num_trails)
ga_avg, ga_std = statics(ga_cost)
x_range = np.arange(len(ga_avg))
Ejemplo n.º 19
0
# coding: utf-8
import ga

def PrintPopulation( D ):
	print( "Population:" )
	i=0
	while i<D._pop :
		print( D.Pop1[i], D.vfobj1[i] )
		i += 1

# An instance of GA
Data = ga.GA()

# Set GA parameters:
#    1 population size
#    2 number of generations
#    3 number of variables
#    4 crossover probability
#    5 mutation probability
# Data.SetParameters( 10, 5, 1, 0.7, 0.1  ) 
Data.SetParameters( 20, 30, 1, 0.7, 0.1  )

# Args: list with the size in bits for each variable
Data.SetSizes( [10] ) 

# Two lists to set the minimum and maximun values for each
# variable
Data.SetLimits( [0.0], [7.0] ) 

Data.Initialize( )
Data.EvaluatePopulation()
Ejemplo n.º 20
0
parent_selection_type = "tournament" # Type of parent selection.

crossover_type = "two_points" # Type of the crossover operator.

mutation_type = "scramble" # Type of the mutation operator.

keep_parents = 1 # Number of parents to keep in the next population. -1 means keep all parents and 0 means keep nothing.

# Creating an instance of the GA class inside the ga module. Some parameters are initialized within the constructor.
ga_instance = ga.GA(num_generations=num_generations, 
          sol_per_pop=sol_per_pop, 
          num_parents_mating=num_parents_mating, 
          function_inputs=function_inputs,
          function_output=function_output,
          mutation_percent_genes=mutation_percent_genes,
          mutation_num_genes=mutation_num_genes,
          parent_selection_type=parent_selection_type,
          crossover_type=crossover_type,
          mutation_type=mutation_type,
          keep_parents=keep_parents,
          K_tournament=3)

# Running the GA to optimize the parameters of the function.
ga_instance.run()

# After the generations complete, some plots are showed that summarize the how the outputs/fitenss values evolve over generations.
ga_instance.plot_result()

# Returning the details of the best solution.
best_solution, best_solution_fitness = ga_instance.best_solution()
print("Parameters of the best solution :", best_solution)