コード例 #1
0
ファイル: main.py プロジェクト: antlev/python_tsp
def main():
    """ Main function. """
    target = "Hello, World !"
    pop_size = 10
    best_pourcentage = 0.30
    crossover_rate = 0.70
    mutation_rate = 0.5
    gen = Genetic(target, pop_size, best_pourcentage, crossover_rate,
                  mutation_rate)

    iterations = 1000
    best_fitness_exp = 0
    gen.start(iterations, best_fitness_exp)
コード例 #2
0
ファイル: neugen.py プロジェクト: wsgan001/junk
def revolution():
    """
	Renew the neural networks in all environments:
	 * Combine neural networks from all environments
	 * Define the value of fitness funtion for every network
	 * Run genetic algorithm and produce new neural networks
	"""
    global evolution_num

    # Neural networks ant their efficiency
    neurals = [env[i].export2vector() for i in range(CNT_ENV)]
    results = [env[i].get_result() for i in range(CNT_ENV)]

    # Run genetic algorythm on neural networks
    population = Genetic.Population(neurals, results)
    neurals = population.evolution(3)

    # The result is imported into existing environments
    for i in range(CNT_ENV):
        env[i].import_vector(neurals[i])

    # Bring info to user: plot, label, sound
    draw_chart(evolution_num, results)
    evolution_num += 1
    evolution_label.text = 'Evolution = ' + str(evolution_num)
    evolution_sound.play()
コード例 #3
0
def simple_genetic_run(args):
  problem, seed, contest_size, cross_rate, mutate_rate, size, epochs, max_time, best_solve = args
  print('Genetic Started: Problem: ', problem.instance_name)
  genetic = Genetic(problem, seed)
  parameters:dict = {
    "contest_size":contest_size,
    "cross_rate": cross_rate,
    "mutate_rate": mutate_rate,
    "size": size,
    "epochs": epochs,
    "max_time": max_time,
    "start_solve":best_solve
    }
  start_time = time.time()
  genetic_tour, step = genetic.run(parameters)
  end_time = time.time()
  genetic_cost = problem.evaluate(genetic_tour)
  print('Genetic Done: Problem: ', problem.instance_name)
  return pd.DataFrame([[problem.instance_name, seed, genetic_cost, end_time-start_time, step]], columns=['Problem', 'Seed', 'Cost', 'Time', 'Steps'])
コード例 #4
0
from ImportFormCSV import importCSV
from Fitness import Fitness
from Genetic import Genetic
import datetime
people = importCSV()
fitness = Fitness(people)
bigs, littles = fitness.bigs, fitness.littles
genetic = Genetic(bigs, littles, fitness)

# IMPORT CSV
# print('PEOPLE', people)
#
# # CREATE FITNESS
# print('BIGS:', bigs)
# print('LITTLES: ', littles)
# print('AUTO MATCHED', fitness.get_automatches())
#
#
# # GENERATE A SAMPLE
# print(genetic.generate_sample(5))
#
#
# CROSSOVER
# a = ['a', 'b', 'f', 'e', 'd', 'c']
# b = ['c', 'b', 'e', 'a', 'd', 'f']
# print('BEFORE')
# print(a)
# print(b)
# print('AFTER')
# crossed = genetic.crossover(a, b)
# for cross in crossed:
コード例 #5
0
ファイル: main.py プロジェクト: joshuamitchell192/N-Queens
from random import randint
n = int(input("What is the number of queens: "))

while n < 4 :
    print("Solution cannot be found for a number less than 4.\nEnter another number")
    n = int(input("What is the number of queens: "))
print("\n1. Hill Climbing\n2. Random Restart Hill Climbing\n3. Simulated Annealing\n4. Genetic\n")
algorithm = int(input("Select which algorithm you would like to use: "))

queens = list([randint(0, n - 1) for x in range(n)])
#print(queens)

if algorithm == 1:

    result = HillClimbing(queens, n, 30)

elif algorithm == 2:

    result = RandomRestartHC(queens, n, int(np.log(n**7)))

elif algorithm == 3:

    result = SimulatedAnnealing(queens, n)

elif algorithm == 4:

    result = Genetic(n)



コード例 #6
0
        problem.distance_matrix[line, line] = 0

    random_tour = problem.random_solve(seed)
    print('random tour:', random_tour)
    print('random tour cost:', problem.evaluate(random_tour))

    local_search = LocalSearch(problem)
    local_search_tour = local_search.search(random_tour, 1)
    print('local_search tour:', local_search_tour)
    print('local_search tour cost:', problem.evaluate(local_search_tour))

    greed_tour = GreedSearch.search(problem)
    print('greed tour:', greed_tour)
    print('greed tour cost:', problem.evaluate(greed_tour)) 

    vns = VariableNeighborhoodSearch(problem, None, seed)
    vns_tour, step, last_update = vns.run(3, 100, 10, max_exec_time_per_run_in_seconds, greed_tour)
    print('vns tour cost:', problem.evaluate(vns_tour))
    print('total steps', step)
    print('last update', last_update)

    grasp = GRASP(problem, None, seed)
    grasp_tour, step, last_update = grasp.run(0.0, 2, 100, 50, 5, max_exec_time_per_run_in_seconds, greed_tour)
    print('grasp tour cost:', problem.evaluate(grasp_tour))
    print('total steps', step)
    print('last update', last_update)

    genetic = Genetic(problem, seed)
    genetic_tour, step = genetic.run(2, 0.8, 0.1, 50, 100, max_exec_time_per_run_in_seconds, greed_tour)
    print('genetic tour cost:', problem.evaluate(genetic_tour))
    print('total steps', step)
コード例 #7
0
        )
        print("O nome do algoritmo a ser usado no GridSearch")
        print(
            "O arquivo com as configurações possiveis do algoritmo a ser usado no GridSearch"
        )
        print("O número máximo de execuções que podem rodar em paralelo")
        print("O nome do arquivo de saida com os resultados")
        sys.exit(1)

    with open(sys.argv[1]) as f:
        config = json.load(f)
    with open(sys.argv[3]) as f:
        parameters = json.load(f)

    if sys.argv[2] == "genetic":
        alg = Genetic(None, None)
    elif sys.argv[2] == "vns":
        alg = VariableNeighborhoodSearch(None, None, None)
    elif sys.argv[2] == "grasp":
        alg = GRASP(None, None, None)
    else:
        print(
            "O nome do algoritmo informado é inválido, escolhar entre: 'genetic', 'vns' e 'grasp'"
        )
        sys.exit(1)

    n_cores = int(sys.argv[4])
    result_file_name = sys.argv[5]

    Problem.files_path = '30 selected instances/'
コード例 #8
0
from ImportFormCSV import importCSV
from Fitness import Fitness
from Genetic import Genetic
import datetime
# import time

people = importCSV()

fitness = Fitness(people)
bigs, littles = fitness.bigs, fitness.littles

now = datetime.datetime.now()
delta = datetime.timedelta(seconds=2)
# print(now)
# while datetime.datetime.now() < now + delta:
genetic = Genetic(bigs, littles, fitness)
genetic.best(now + delta)
# sample = genetic.generate_sample(50)
# print(sample)
# cull, min = genetic.cull(sample)
# print('CULL')
# print(cull)
# print('BREED')
# print(genetic.breed(cull))
# print(cull)
# crossed = genetic.crossover(a, b)
# for cross in crossed:
#     print(cross)
#
# print(genetic.duplicate(b))
コード例 #9
0
from Genetic import Genetic

# my_func = lambda x: (x ** 2) + 10 * x + 1
my_func = lambda x: (x ** 2)
gen = Genetic(my_func)
for i in range(1000):
    gen.run()
    print('created gen is: ', gen.gen_produced)

print('Number of times mutated', gen.mutation_counter)
print("best answer is :")
print(gen.answers[0])
print("in binary mode x is ........", gen.population[0])
print('in decimal mode x is .......', gen.binary_to_decimal(gen.population[0]))
コード例 #10
0
    parametros_tamanho_populacao = [10, 20, 30]
    parametros_taxa_crossover = [0.75, 0.85, 0.95]
    parametros_taxa_mutacao = [0.10, 0.20, 0.30]

    treino_csv = open("problemas/treino.csv")
    entradas = list(DictReader(treino_csv, delimiter=";"))

    resultados = open("resultados/treino_genetic.csv", "w")
    resultados.write("nome;tamanho_populacao;taxa_crossover;taxa_mutacao;tempo;estado;valor;tamanho\n")

    for tamanho_populacao in parametros_tamanho_populacao:
        for taxa_crossover in parametros_taxa_crossover:
            for taxa_mutacao in parametros_taxa_mutacao:
                for entrada in entradas:
                    nome, t, vt = entrada["nome"], float(entrada["t"]), eval(entrada["vt"])
                    estado, valor, tamanho, tempo = Genetic(t, vt, 120, 100, tamanho_populacao, taxa_crossover, taxa_mutacao)

                    resultados.write(f"{nome};{tamanho_populacao};{taxa_crossover};{taxa_mutacao};{tempo};{estado};{valor};{tamanho}\n")

if algoritmo == 'GR' or run_all:
    parametros_iteracoes = [50, 100, 200, 350, 500]
    parametros_m = [2, 5, 10, 15]

    treino_csv = open("problemas/treino.csv")
    entradas = list(DictReader(treino_csv, delimiter=";"))

    resultados = open("resultados/treino_grasp.csv", "w")
    resultados.write("nome;iteracoes;m;tempo;estado;valor;tamanho\n")

    for iteracoes in parametros_iteracoes:
        for m in parametros_m:
コード例 #11
0
def doSolution(N,K,distanceObject,rep):
    sting = ''
    if K==2:
        sting += 'Kolmo'
        lengthFloat = writeToKolmogorov()
        raw_input("Execute the minimum cost maximum matching algorithm. Press Enter when the algorithm is finished...")
        print "Continue"
        sting += obtainKolmogorov('solution.txt',distanceObject,lengthFloat,title='KolmogorovRND' + str(len(N))+ '-' + str(rep) )
        sting+= '\n'
    
# Functionality to find the least distance `matching' of length K (or least distance T using the genetic notation) 
#     time1=time.time()
#     solution =  LinProg.bestPossibleTrips( N,K, distanceObject)
#     time2=time.time()
#     dif=time2-time1
#     sting += 'bestPossibleTrips got %s, took %0.3f s' % (solution[-1],(dif))
#     showSolutionEdgesLp(solution,distanceObject,N,title='bestPossibleTrips' + str(len(N)) +' time'+str(dif))
    
    time1=time.time()
    lpiterations = 9
    solution =executeLP(K,N,distanceObject, lpiterations, 'lpK_sets')
    depots = '&'.join(['%.5f' %(depot) for depot in solution[0]])
    time2=time.time()
    dif=time2-time1
    sting += 'lpK_sets & %s & %s & %s & %.6f & %.4f depots %s \n' %(str(len(N)),str(lpiterations),str(rep),solution[-1], dif, depots)
    title = 'lpK_sets%s-%s time %.4f depots %s' %(str(len(N)),str(rep), dif, depots)
    showSolution(solution,N,distanceObject,title)
    
    time1=time.time()
    lpiterations = 1
    solution = executeLP(K,N,distanceObject, lpiterations, 'lpK_edges')
    depots = '&'.join(['%.5f' %(depot) for depot in solution[0]])
    time2=time.time()
    dif=time2-time1
    sting += 'lpK_edges & %s & %s & %s & %.6f & %.4f depots %s \n' %(str(len(N)),str(lpiterations),str(rep),solution[-1], dif, depots)
    title = 'lpK_edges%s-%s time %.4f depots %s' %(str(len(N)),str(rep), dif, depots)
    showSolutionEdgesLp(solution,distanceObject,N, title)
      
    time1=time.time()
    lpiterations = 9
    solution = executeLP(K,N,distanceObject, lpiterations, 'lpK_flow')
    time2=time.time()
    dif=time2-time1
    depots = '&'.join(['%.5f' %(depot) for depot in solution[0]])
    sting += 'lpK_flow & %s & %s & %s & %.6f & %.4f depots %s \n' %(str(len(N)),str(lpiterations),str(rep),solution[-1], dif, depots)  
    title = 'lpK_flow%s-%s time %.4f depots %s' %(str(len(N)),str(rep), dif, depots)
    showSolutionEdgesLp(solution,distanceObject,N, title)
     
    time1=time.time()
    solution = executeLP(K,N,distanceObject, 5, 'lpK_DoubleEdges')
    depots = '-'.join([str(depot) for depot in solution[0]])
    time2=time.time()
    dif=time2-time1
    sting += 'lpK_DoubleEdges got %s, took %0.3f s' % (solution[-1],(dif))
    title = 'lpK_DoubleEdges%s time %.4f depots %s' %(str(len(N)), dif, depots)
    showSolutionEdgesLp(solution,distanceObject,N, title)
     
    time1=time.time()
    solution = geneticMore.doGenetic(N,h,l,distanceObject,K)
    depots = '&'.join(['%.5f' %(depot) for depot in solution[0]])
    time2=time.time()
    dif=time2-time1
    sting += 'genetic & %s & %s  & %.6f & %.4f depots %s \n' %(str(len(N)),str(rep),solution[-1], dif, depots)  
    title = 'genetic%s-%s time %.4f depots %s' %(str(len(N)), str(rep),dif, depots)
    showSolution(solution, N, distanceObject, title)
    
    return sting
コード例 #12
0
from DataSet import DataSet
import shelve
from Genome import Genome
from Genetic import Genetic
from UnitOfWork import UnitOfWork

if __name__ == "__main__":
    UOF=UnitOfWork()
    genetic=Genetic(UOF._iteration,UOF._popSize,UOF._perMut,UOF._genomes)
    print(genetic.Run())

    
コード例 #13
0
 def __init__(self):
     super()
     self.engine = Genetic.Engine("Best")
コード例 #14
0
# Autores: Davi Boberg e Renato Böhler
from Genetic import Genetic
import Busca_Largura
from RobotControl import RobotControl

initial_position = (9, 9, 'W')
final_position = (8, 2, 'S')
maximum_generations = 50

genetic = Genetic(initial_position,
                  final_position,
                  population_size=20,
                  mutation_probability=0.01,
                  map_size=10,
                  with_elitism=True)

for i in range(maximum_generations):
    next_generation = genetic.generateNextGeneration()
    # print(genetic.best_score)
    # print(genetic.best_chromosome)

print("Melhor cromossomo: {best_chromosome}".format(
    best_chromosome=genetic.best_chromosome))
print("Avaliação: {best_score}".format(best_score=genetic.best_score))
print()

print("Primeira parte do caminho:")
first_path_segment = Busca_Largura.search(initial_position,
                                          genetic.best_chromosome)

print("Parte final do caminho:")