Exemplo n.º 1
0
def runProblems(numProbs, probFolder, probFile, probExtension):
    problemGraphs = {}
    problemScores = {}
    for num in range(numProbs):
        print "Problem: " + str(num+1) + "\n"
        
        problemGraphs[num+1] = generateGraph(probFolder + "/" + probFile + str(num+1) + "." + probExtension)

        searcher = Searcher(problemGraphs[num+1])
        res = []
        res.append(searcher.AStarSearch())

        res.append(searcher.BreadthFirstSearch())

        res.append(searcher.DepthFirstSearch())

        res.append(searcher.UniformCostSearch())

        ProbScore = ProblemScore(res)
        problemScores[num+1] = ProbScore
        ProbScore.printScores()
        scores = ProbScore.GetScores()
        resDict = ProbScore.GetResultDict()

        GA = GeneticAlgorithm(100, scores, resDict)

        gaRes = GA.PerformAlgorithm()

        print "Results: "
        gaRes.printResult()

        print ""
def generateTable():
    global logGens
    logGens = ""
    generationNumber = 1
    logGens += "\n> Generation # " + str(generationNumber) + "\n"
    population = Population.Population(POPULATION_SIZE)
    population.get_schedules().sort(key=lambda x: x.get_fitness(),
                                    reverse=True)
    logGens += str(displayMgr.print_generation(population))
    logGens += str(
        displayMgr.print_schedule_as_table(population.get_schedules()[0]))
    geneticAlgorithm = GeneticAlgorithm.GeneticAlgorithm()
    while (population.get_schedules()[0].get_fitness() != 1.0):
        generationNumber += 1
        logGens += "\n> Generation # " + str(generationNumber) + "\n"
        population = geneticAlgorithm.evolve(population)
        population.get_schedules().sort(key=lambda x: x.get_fitness(),
                                        reverse=True)
        logGens += str(displayMgr.print_generation(population))
        logGens += str(
            displayMgr.print_schedule_as_table(population.get_schedules()[0]))
    print("\n\n")

    root.destroy()
    last_gen = displayMgr.get_generated(population.get_schedules()[0])
    Generated_Table(last_gen)
Exemplo n.º 3
0
    def __init__(self, screen):
        self.recordDistance = 1000000000
        self.bestEver = []
        self.currentDistance = 100000000
        self.currentBest = []

        pygame.init()

        self.create_cities_and_order()
        self.calculate_symmetric_points()
        self.create_random_population()

        ga = GeneticAlgorithm.GeneticAlgorithm(cities, fitness, population)

        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

            screen.fill(BLACK)
            self.create_city_figures()
            self.create_symmetrical_city_figures()

            # Calculate best path accord a population
            self.bestEver, self.recordDistance, self.currentBest, self.currentDistance = \
                ga.calculateFitness(self.bestEver, self.recordDistance, self.currentDistance, self.currentBest)
            ga.normalize_fitness()
            self.draw(cities, self.bestEver, city_figures)
            self.draw(symmetric_cities, self.currentBest,
                      symmetric_city_figures)

            # Generate a distinct population
            ga.next_generation()
            pygame.display.update()
Exemplo n.º 4
0
 def calcByGA(self, population_num, geneRange, mutateVar):
     
     if self.type == "LINEAR":
         chromoLen = self.dim + 1
     elif self.type == "NEURAL_NET":
         chromoLen = self.nn.weight_num + self.nn.bias_num
     
     self.ga = GeneticAlgorithm(population_num, geneRange, chromoLen, self.calcFitness, mutateVar)
     
     self.trainFitnessVal = []
     for t in range(self.runCnt):
         self.ga.next()
         self.trainFitnessVal.append(self.ga.population[0].fitness)
         print str(t) + " : " + str(self.ga.population[0].fitness)
         
     self.betas = np.array(self.ga.population[0].genes)
     if self.type == "LINEAR":
         delta = self.trainY - np.dot(self.trainX, self.betas)
     elif self.type == "NEURAL_NET":
         nY = []
         for i in range(self.trainDataSize):
             x = self.trainX[i,:]
             nY.append(self.nn.calcFunc(self.betas, x)[0])
         delta = self.trainY - np.array(nY)    
         
     self.trainMSE = np.dot(delta.T, delta) / self.trainDataSize
Exemplo n.º 5
0
def main():
    ga = GeneticAlgorithm(number_of_generations=500,
                          population_size=250,
                          chromosome_length=20,
                          mutation_rate=0.005,
                          chromosome_csv_path='data/data 20 (circle).csv')
    ga.solve()
    print(ga.best_chromosome)
Exemplo n.º 6
0
def GA():

    with open("GAoutput1.csv", "wb") as f:
        writer = csv.writer(f)

        maxGenerations = 3000
        #sectionSize = [50, 100, 150, 200, 250, 300]
        #mutationRate = [0.03, 0.05, 0.07, 0.09]
        populationSize = [250, 500, 750]
        mutationRate = [0.07, 0.09, 0.11]
        nVals = [5, 6, 7]

        writer.writerow([
            "Section Size", "Changing Mutation Rate",
            "Generations till Solution"
        ])
        for m in mutationRate:
            s = 250
            n = 6
            game = Game.Game(n, "EPD", None)
            ga = GeneticAlgorithm.GeneticAlgorithm(n, maxGenerations, s, m,
                                                   game)
            print(ga.idealFitness)
            generations = ga.runGA()
            game.resetGame()

            result = [str(s), str(m), str(generations)]
            writer.writerow(result)

        writer.writerow([
            "Changing Section Size", "Mutation Rate",
            "Generations till Solution"
        ])
        for s in populationSize:
            m = 0.09
            n = 6
            game = Game.Game(n, "EPD", None)
            ga = GeneticAlgorithm.GeneticAlgorithm(n, maxGenerations, s, m,
                                                   game)
            print(ga.idealFitness)
            generations = ga.runGA()
            game.resetGame()

            result = [str(s), str(m), str(generations)]
            writer.writerow(result)
Exemplo n.º 7
0
def main():
    coins =  [ 1, 20,  5,  1,  2,  5,  5,  1,  5,  2,  2,  1, 10,  5, 10,  5, 20, 20, 20,  5,  1,  1, 20, 20,  1, 10,  2, 10,  5,  2, 10,  1, 20,  1, 20, 10,  5,  5, 20,  2, 10,  1,  2,  5, 10, 20, 10,  2,  5,  5, 20, 1,  1,  5, 10, 10, 10,  1,  5,  2,  1,  2, 10, 20,  2, 10, 10, 20, 5, 10,  1,  2,  1,  5, 20,  2,  5,  1,  5, 10,  2,  5, 10,  2,  1, 1,  1, 10, 20, 10, 20,  2,  2, 10, 20, 10,  1,  1,  5,  2]
    coins_problem = Coins.Coins(coins)
    allels = len(coins)
    population_size = 32
    generations = 200000
    mutation_rate = 0.1
    ag = GeneticAlgorithm.GeneticAlgorithm(population_size, allels, generations, mutation_rate, coins_problem)
    ag.run()
Exemplo n.º 8
0
def main():
    print("####### Current time at start = " + str(datetime.datetime.now()))
    algo = GeneticAlgorithm.GeneticAlgorithm(
        GeneticAlgorithm.OnePointCrossover(), 0.9,
        GeneticAlgorithm.RandomCharMutation(), 0.03,
        GeneticAlgorithm.TournamentSelection(2))
    initialPop = getInitialPopulation()
    finalPopulation = algo.evolve(initialPop,
                                  GeneticAlgorithm.FitnessCondition(-30))
    best = finalPopulation.getFittestChromosome()
    print("####### Current time at end = " + str(datetime.datetime.now()))
Exemplo n.º 9
0
def loadGn(newPop, popSize, path, lbl2):
    global gn
    gn = GeneticAlgorithm()

    if newPop:
        gn.create_population(popSize)
    else:
        gn.load_network(path)

    lbl2.destroy()

    return 
Exemplo n.º 10
0
def generate_ga_detectors(num_gen, individual_sample, p_mutation, p_crossover,
                          self_distance_tree, self_radius):
    ga_instance = GeneticAlgorithm.GeneticAlgorithm()
    pop = individual_sample
    #z=pop
    print "performing GA..."
    print "Initial population"
    #print z
    num_pop = len(individual_sample)
    for i in range(0, num_gen):
        print "Generation", i

        for j in range(0, num_pop):
            print "generation", i
            parent1, parent2 = random.sample(
                pop, 2)  #np.array(random.sample(pop,2))
            l1 = pop.index(parent1)
            l2 = pop.index(parent2)
            print "parent1", parent1
            print "parent2", parent2
            child_pair = ga_instance.crossover(parent1, parent2, 1,
                                               p_crossover)
            print "cross_child", child_pair
            children = ga_instance.mutate1(child_pair, p_mutation)
            print "mutat_child", children

            d0 = ais_instance1.euclidean(children[0], parent1)
            print "d0=", d0
            d1 = ais_instance1.euclidean(children[1], parent2)
            print "d1=", d1
            f0 = ga_instance.fitnesstest(children[0], self_distance_tree,
                                         self_radius)
            print "f0=", f0
            f1 = ga_instance.fitnesstest(children[1], self_distance_tree,
                                         self_radius)
            print "f1=", f1
            f2 = ga_instance.fitnesstest(parent1, self_distance_tree,
                                         self_radius)
            print "f2=", f2
            f3 = ga_instance.fitnesstest(parent2, self_distance_tree,
                                         self_radius)
            print "f3=", f3
            if (d0 > self_radius) and (f0 > f2):
                print "replacing parent1 with child 1"
                pop[l1] = children[0]
            if (d1 > self_radius) and (f1 > f3):
                print "replacing parent2 with child 2"
                pop[l2] = children[1]
            #print '\n'
    return pop  #print pop1
Exemplo n.º 11
0
    def calcByGA(self, population_num, geneRange):
        chromoLen = self.dim + 1

        ga = GeneticAlgorithm(population_num, geneRange, chromoLen,
                              self.calcFitness)

        self.fitnessVal = []
        for t in range(self.runCnt):
            ga.next()
            self.fitnessVal.append(ga.population[0].fitness)
            print str(t) + " : " + str(ga.population[0].fitness)

        self.betas = np.array(ga.population[0].genes)
        delta = self.Y - np.dot(self.X, self.betas)

        self.mse = np.dot(delta.T, delta) / self.dataSize
Exemplo n.º 12
0
def main():
    try:
        G2 = ler_instancia(sys.argv[1])
        populationSize = int(sys.argv[2])
        maxIter = int(sys.argv[3])
        try:
            seed = int(sys.argv[4])
        except:
            seed = None
        restrictions = PMSPRestrictions(len(G2[0][0]), len(G2[0]), G2)
        ga = GeneticAlgorithm.GeneticAlgorithm(restrictions, populationSize,
                                               seed)
        pop = ga.run(maxIter)
        print("Best: ", pop.fitness, 'Solution: ', pop.order_of_tasks)
    except:
        print(
            'Sintaxe invalida: python3 PMSPMain.py <arquivo de instancia> <tamanho da populacao> <max iteracoes> <seed/opcional>'
        )
Exemplo n.º 13
0
def main():
    param = sys.argv[1:]
    if len(param) == 3:
        pathInput = "./testes/"
        pathOutput = "./saida/"
        array = readFile(pathInput + param[0])
        itens = []
        itens, size = arrayItem(array)
        x = GeneticAlgorithm(itens, int(size), 0.5)
        best = x.run(int(param[2]))
        with open(pathOutput + param[1], 'w', newline='') as csvfile:
            spamwriter = csv.writer(csvfile, delimiter='\n')
            for i in range(len(best)):
                spamwriter.writerow(str(best[i]))
    else:
        print(
            "Argumento Faltando! -> nome do arquivo de entrada, nome do arquivo de saida, quantidade de gerações"
        )
Exemplo n.º 14
0
    def calcByGA(self, population_num, geneRange):
        chromoLen = self.nn.weight_num + self.nn.bias_num

        self.ga = GeneticAlgorithm(population_num, geneRange, chromoLen,
                                   self.calcFitness)

        self.fitnessVal = []
        for t in range(self.runCnt):
            self.ga.next()
            self.fitnessVal.append(self.ga.population[0].fitness)
            print str(t) + " : " + str(self.ga.population[0].fitness)

        self.betas = np.array(self.ga.population[0].genes)
        nY = []
        for i in range(self.dataSize):
            x = self.X[i, :]
            nY.append(self.nn.calcFunc(self.betas, x)[0])
        delta = self.Y - np.array(nY)
        self.mse = np.dot(delta.T, delta) / self.dataSize
Exemplo n.º 15
0
def findRoutes():
    start_time = time()
    body = None
    body = request.get_json(force=True)
    lista = list(body)
    if len(lista) < 2:
        return []
    destinations = []
    for i in lista:
        destinations.append(Coordinate(i['lat'], i['lng'], 'A'))
    #TODO
    ga = None
    ga = GeneticAlgorithm.GeneticAlgorithm(destinations, 0.5, 10)
    ga.generations(2000)
    best = ga.getBestIndividuo()
    response = []
    for i in best:
        response.append({'lat': i.lat, 'lng': i.long})
    elapsed_time = time() - start_time
    print("Elapsed time: %0.10f seconds." % elapsed_time)
    return jsonify(response)
Exemplo n.º 16
0
    def calcByGA(self, population_num, geneRange):
        chromoLen = self.rbf.beta_num

        #self.X = np.hstack((np.ones((self.dataSize,1)), np.array(self.inputs).T))
        #self.Y = np.array(self.outputs).T

        ga = GeneticAlgorithm(population_num, geneRange, chromoLen,
                              self.calcFitness)

        self.fitnessVal = []
        for t in range(self.runCnt):
            ga.next()
            self.fitnessVal.append(ga.population[0].fitness)
            print str(t) + " : " + str(ga.population[0].fitness)

        self.betas = np.array(ga.population[0].genes)
        nY = []
        for i in range(self.dataSize):
            x = self.X[i, :]
            nY.append(self.rbf.calcFunc(self.betas, x)[0])
        delta = self.Y - np.array(nY)
        self.mle = np.dot(delta.T, delta) / self.dataSize
Exemplo n.º 17
0
    def __create_window(self):

        pygame.init()
        screen = pygame.display.set_mode((self.__WIDTH, self.__HEIGHT))

        pygame.display.set_caption('BomberTEC')
        board = Board.get_instance(self.__WIDTH, self.__HEIGHT)
        board.enemies.update()
        genetic_algorithm = GeneticAlgorithm()
        #board.matrix.enemy0.update()
        #board.matrix.enemy1.update()

        while not self.__done:
            screen.blit(self.__bg_image, (0, 0))
            board.check_alive_players()
            if not board.end_game:
                board.draw_base(screen)
                board.draw_board(screen)
                board.draw_stats(screen)
                board.draw_titles(screen)
                actual_time = pygame.time.get_ticks()
                board.create_power_up(actual_time)
                genetic_algorithm.crossover(actual_time)  # executes crossover
                board.change_velocity(actual_time)
                board.change_detonation_time(actual_time)
                board.users.update()

            else:
                board.draw_end_window(board.winner_player, screen)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

            pygame.display.flip()
Exemplo n.º 18
0
def main():
    sphere_problem = sphere.Sphere()
    rastrigin_problem = rastrigin.Rastrigin()
    quartic_problem = quartic.Quartic()
    rosenbrock_problem = rosenbrock.Rosenbrock()
    # allels = 2
    population_size = 16
    generations = 2000
    mutation_rate = 0.1
    for allels in [2, 4, 8]:
        raw_sets = []
        for i in range(5):
            ag = GeneticAlgorithm.GeneticAlgorithm(population_size, allels,
                                                   generations, mutation_rate,
                                                   rastrigin_problem)

            raw_sets.append(ag.run())
        print(zip_average(raw_sets), allels)
        plt.plot(range(100, generations + 100, 100),
                 zip_average(raw_sets),
                 label=str(allels))
    # plt.legend(['2', '4', '8'])
    plt.legend()
    plt.show()
Exemplo n.º 19
0
from DTLZ1 import DTLZ1
from hypervolume_runner import HyperVolume_wrapper

models = [DTLZ1, DTLZ3, DTLZ5, DTLZ7]
objs = [2, 4, 6, 8]
decs = [10, 20, 40]
i = 0
iterations = 0
while iterations < 1:
    for model in models:
        print model
        print '\n\n'
        for x in decs:
            print '\t\t\t', x, '\t\t\t',
        print
        for j in objs:
            print j,
            for k in decs:
                #modelName=model+'('+str(j)+','str(k)+')'
                #print modelName
                #print model(j,k)

                fileName = 'DTLZ-PF' + str(i) + '.txt'
                GeneticAlgorithm(model(j, k), fileName)
                HyperVolume_wrapper()
                os.remove('./Pareto_Fronts/' + fileName)
                i += 1
            print

    iterations = iterations + 1
Exemplo n.º 20
0
                exit()
        elif opt == '-r':
                cityPositions = generateRandomCities(citiesN, width, height)
        elif opt == '-i':
                mapFile = value

if cityPositions == []:
        cityPositions = parseCities(args)

if cityPositions == []:
        usage()
        exit(1)
        
generator = RandomRouteFactory(cityPositions)
ga = GeneticAlgorithm.GeneticAlgorithm(generator,
                                       crossoverChance,
                                       mutationChance,
                                       population)
print "Generation\tAvg\tShortest"
for i in range(generations):
        # create a new generation
	ga.evolve()

        # Calculate the lengths of the routes
	lengths = [route.getLength() for route in ga.getSolutions()]
        
        # Print the avg length and the length of the shortest route
	print i + 1,"\t", \
            int(sum(lengths) / len(lengths)),"\t", \
            int(min(lengths))

shortest = ga.getBestSolution()
Exemplo n.º 21
0
    testing_pctg = 0.5

    #In-sample period
    dates = [dt.datetime(2017, 1, 1), dt.datetime(2018, 4, 4)]
    strategy = manstratt.ManualStrategyTicktoTick()

    # Get data
    df = util.get_all_data(symbol, dates)

    pos = int(len(df.index) * testing_pctg)
    split_date = df.index[pos]

    # Use GeneticAlgorithm to optimize signal weights
    params = False
    gen_alg = ga.GeneticAlgorithm(symbol=symbol,
                                  dates=[dates[0], split_date],
                                  start_val=start_val,
                                  verbose=True)
    params, sharpe_ratio = gen_alg.start_ga()

    #pdb.set_trace()

    ft = FakeTicker(symbol, df, testing_pctg)
    #print (ft.get_training_data().shape)
    prices_df = ft.get_training_data()['Adj Close']
    ohlc = ind.get_ohlc(ft.get_training_data())

    trades = []
    ctr = 0
    while not ft.is_end_ticker():
        start = time.time()
        # Get tick data
Exemplo n.º 22
0
#Calculating Fading (TBD)

#Minimum Output Power (ETSI TS 136 101 V14.3.0 (2017-04))
p_min = -40 #dBm

allocatingPilotSequence(K, 10)


# ------GA------
# setupGA = SetupGA(10,10,5, 60.02)
generationNumber = 30
rateMutation = 0.07

individual = Individual()

ga = GeneticAlgorithm()
ga.runGA(phi, generationNumber, rateMutation, beta, N0*Bmax)
# ga.inicializePopulation(phi)
# for i in range(len(ga.population)):
#     for j in range(len(ga.population[i])):
#         ga.population[i][j].fnFitness()

# ga.printPopulation()
# print("TSTES %s" % ga.population[0][1].chromosome)

finihed = time.time()
print("------------------------------")
print("Tempo de execucao: ", finihed-start)
print("------------------------------")
plt.show()
Exemplo n.º 23
0
def RunGeneticAlgorithm(dimension=20,numberOfMazesInAPopulation=500,probabilityObstruction=0.4,dfs_percentileVisitedNodeLevel=80,bfs_percentileVisitedNodeLevel=20,astarE_percentileLevel=50,astarM_percentileLevel=50,retryGeneratingHardMazeInMinutes=1):
    N = dimension # dimension
    #listofprobability = np.arange(0.4, 1.0, 0.1) # probability from 0.2 to 0.9
    percentileLevel= dfs_percentileVisitedNodeLevel #80
    percentilelevelbfs= bfs_percentileVisitedNodeLevel#20 # has to be lower because for 75 it doesnt find anything
    percentilelevelAstarE= astarE_percentileLevel
    percentilelevelAstarM= astarM_percentileLevel
    mazePopulation = []
    bfsMazePopulation = []
    astarEMazePopulation=[]
    astarMMazePopulation=[]
    bfsmazesProbabiltyOfVisitedNodes = []
    mazesProbabiltyOfVisitedNodes = []
    astaremazesProbabiltyOfVisitedNodes=[]
    astarmmazesProbabiltyOfVisitedNodes =[]
    mazeNumberOfVisitedNodes = []
    bfsmazeNumberOfVisitedNodes = []
    astarEmazeNumberOfVisitedNodes  =[]
    astarMmazeNumberOfVisitedNodes =[]
    mazeNumberOfObstacleNodes=[]
    bfsmazeNumberOfObstacleNodes=[]
    astaremazeNumberOfObstacleNodes =[]
    astarMmazeNumberOfObstacleNodes =[]
    #for i in listofprobability:
    for j in range(0, numberOfMazesInAPopulation):
        print("Maze #" + str(j + 1) + ' generated for ' + str(probabilityObstruction) + ' probability')
        print("---------------------------------------------------------")
        maze_matrix = np.zeros((N, N))
        noOfOccupiedBlocks = int(np.floor(N * N * probabilityObstruction) - 2)
        if noOfOccupiedBlocks > 0:
            occ_Indices = random.sample(range(1, (N * N) - 1), noOfOccupiedBlocks)
            occ_Indices = np.unravel_index(occ_Indices, (N, N))
            maze_matrix[occ_Indices] = 1

        print(maze_matrix)
        maze_dict = buildMazeDict((maze_matrix))
        maze_matrix_visited_dfs = DFS(maze_dict, N, maze_matrix)
        maze_matrix_visited_bfs = BFS(maze_dict, N, maze_matrix)
        maze_matrix_visited_astarE = Astar(maze_dict, N, maze_matrix, 'euclidean')
        maze_matrix_visited_astarM = Astar(maze_dict, N, maze_matrix, 'manhattan')


        if (maze_matrix_visited_dfs[N - 1, N - 1] == 3):
            mazePopulation.append(maze_dict)
            unique, counts = np.unique(maze_matrix_visited_dfs, return_counts=True)
            mazestatus = dict(zip(unique, counts))
            numberofvisitednodes = mazestatus[3]
            mazeNumberOfObstacleNodes.append(mazestatus[1])
            mazeNumberOfVisitedNodes.append(numberofvisitednodes)

        if (maze_matrix_visited_bfs[N - 1, N - 1] == 3):
            bfsMazePopulation.append(maze_dict)
            unique, counts = np.unique(maze_matrix_visited_bfs, return_counts=True)
            mazestatus = dict(zip(unique, counts))
            numberofvisitednodes = mazestatus[3]
            bfsmazeNumberOfObstacleNodes.append(mazestatus[1])
            bfsmazeNumberOfVisitedNodes.append(numberofvisitednodes)

        if (maze_matrix_visited_astarE[N - 1, N - 1] == 3):
            astarEMazePopulation.append(maze_dict)
            unique, counts = np.unique(maze_matrix_visited_astarE, return_counts=True)
            mazestatus = dict(zip(unique, counts))
            numberofvisitednodes = mazestatus[3]
            astaremazeNumberOfObstacleNodes.append(mazestatus[1])
            astarEmazeNumberOfVisitedNodes.append(numberofvisitednodes)
        if (maze_matrix_visited_astarM[N - 1, N - 1] == 3):
            astarMMazePopulation.append(maze_dict)
            unique, counts = np.unique(maze_matrix_visited_astarM, return_counts=True)
            mazestatus = dict(zip(unique, counts))
            numberofvisitednodes = mazestatus[3]
            astarMmazeNumberOfObstacleNodes.append(mazestatus[1])
            astarMmazeNumberOfVisitedNodes.append(numberofvisitednodes)


    totalNumberVisitedNodes = sum(mazeNumberOfVisitedNodes)
    bfstotalNumberVisitedNodes = sum(bfsmazeNumberOfVisitedNodes)
    astaretotalNumberVisitedNodes = sum(astarEmazeNumberOfVisitedNodes)
    astarMtotalNumberVisitedNodes = sum(astarMmazeNumberOfVisitedNodes)
    totalProbabilty = 0.0
    for i in range(len(mazePopulation)):
        previousProbabiltiy = totalProbabilty
        #get the probability distribution for each maze
        totalProbabilty = totalProbabilty + (mazeNumberOfVisitedNodes[i] / totalNumberVisitedNodes)
        mazesProbabiltyOfVisitedNodes.append((previousProbabiltiy, totalProbabilty))
    totalProbabilty = 0.0
    for i in range(len(bfsMazePopulation)):
        previousProbabiltiy = totalProbabilty
        # get the probability distribution for each maze
        totalProbabilty = totalProbabilty + (bfsmazeNumberOfVisitedNodes[i] / bfstotalNumberVisitedNodes)
        bfsmazesProbabiltyOfVisitedNodes.append((previousProbabiltiy, totalProbabilty))
    totalProbabilty = 0.0
    for i in range(len(astarEMazePopulation)):
        previousProbabiltiy = totalProbabilty
        #get the probability distribution for each maze
        totalProbabilty = totalProbabilty + (astarEmazeNumberOfVisitedNodes[i] / astaretotalNumberVisitedNodes)
        astaremazesProbabiltyOfVisitedNodes.append((previousProbabiltiy, totalProbabilty))
    totalProbabilty = 0.0
    for i in range(len(astarMMazePopulation)):
        previousProbabiltiy = totalProbabilty
        #get the probability distribution for each maze
        totalProbabilty = totalProbabilty + (astarMmazeNumberOfVisitedNodes[i] / astarMtotalNumberVisitedNodes)
        astarmmazesProbabiltyOfVisitedNodes.append((previousProbabiltiy, totalProbabilty))


    if(len(mazePopulation)==0):
        print("No Solvable Maze for",probabilityObstruction,"probability")
        return False
    timeToRetry = 60 * (retryGeneratingHardMazeInMinutes)
    print(len(mazeNumberOfVisitedNodes) )
    percentiledfs = np.percentile(mazeNumberOfVisitedNodes, percentileLevel)
    percentilebfs = np.percentile(bfsmazeNumberOfVisitedNodes, percentilelevelbfs)
    percentileastare = np.percentile(bfsmazeNumberOfVisitedNodes, percentilelevelAstarE)
    percentileastarm = np.percentile(bfsmazeNumberOfVisitedNodes, percentilelevelAstarM)
    averageObstacle=sum(mazeNumberOfObstacleNodes)/float(len(mazeNumberOfObstacleNodes))
    bfsaverageObstacle=sum(bfsmazeNumberOfObstacleNodes)/float(len(bfsmazeNumberOfObstacleNodes))
    astareaverageObstacle=sum(astaremazeNumberOfObstacleNodes)/float(len(astaremazeNumberOfObstacleNodes))
    astarmsaverageObstacle=sum(astarMmazeNumberOfObstacleNodes)/float(len(astarMmazeNumberOfObstacleNodes))

    hardest_maze_so_far,dfs_hardest_maze_matrix_so_far,max_visited_nodes_so_far, latest_percentile, latest_averageObstacle= GeneticAlgorithm.GeneticAlgorithm(mazePopulation, timeToRetry, mazesProbabiltyOfVisitedNodes,percentiledfs, percentileLevel,averageObstacle,DFS, "",N)
    bfs_hardest_maze_so_far, bfs_hardest_maze_matrix_so_far ,bfs_max_visited_nodes_so_far, bfs_latest_percentile, bfs_latest_averageObstacle =GeneticAlgorithm.GeneticAlgorithm(bfsMazePopulation, timeToRetry, bfsmazesProbabiltyOfVisitedNodes,percentilebfs, percentilelevelbfs,bfsaverageObstacle,BFS,"", N)
    astare_hardest_maze_so_far, astare_hardest_maze_matrix_so_far ,astare_max_visited_nodes_so_far, astare_latest_percentile, astare_latest_averageObstacle =GeneticAlgorithm.GeneticAlgorithm(astarEMazePopulation, timeToRetry, astaremazesProbabiltyOfVisitedNodes,percentileastare, percentilelevelAstarE,astareaverageObstacle,Astar,"euclidean", N)
    astarm_hardest_maze_so_far, astarm_hardest_maze_matrix_so_far ,astarm_max_visited_nodes_so_far, astarm_latest_percentile, astarm_latest_averageObstacle =GeneticAlgorithm.GeneticAlgorithm(astarMMazePopulation, timeToRetry, astarmmazesProbabiltyOfVisitedNodes,percentileastarm, percentilelevelAstarM,astarmsaverageObstacle,Astar,"manhattan", N)

    #max visited node means longest path
    print("DSF Before Run GA Average Obstacle : ", averageObstacle)
    print("DFS Before Run GA Percentile Longest Path : ", percentiledfs)
    print("DFS Maximum Longest Path: ", max_visited_nodes_so_far)
    print("DSF Average Obstacle : ", latest_averageObstacle)
    print("DFS Latest Percentile Longest Path : ", latest_percentile)
    print("DFS Hardest Maze")
    print("-----------------")
    print(dfs_hardest_maze_matrix_so_far)
    print("BFS Before Run GA Average Obstacle : ", bfsaverageObstacle)
    print("BFS Before Run GA Percentile Longest Path : ", percentilebfs)
    print("BFS Maximum Longest Path : ", bfs_max_visited_nodes_so_far)
    print("BFS Average Obstacle : ", bfs_latest_averageObstacle)
    print("BFS Latest Percentile Longest Path: ", bfs_latest_percentile)
    print("BFS Hardest Maze")
    print("-----------------")
    print(bfs_hardest_maze_matrix_so_far)

    print("A Star Euclidean Before Run GA Average Obstacle : ", astareaverageObstacle)
    print("A Star Euclidean Before Run GA Percentile Longest Path : ", percentileastare)
    print("A Star Euclidean Maximum Longest Path : ", astare_max_visited_nodes_so_far)
    print("A Star Euclidean Average Obstacle : ", astare_latest_averageObstacle)
    print("A Star Euclidean Latest Percentile Longest Path: ", astare_latest_percentile)
    print("A Star Euclidean Hardest Maze")
    print("------------------------------")
    print(astare_hardest_maze_matrix_so_far)
    print("A Star Manhattan Before Run GA Average Obstacle : ", astarmsaverageObstacle)
    print("A Star Manhattan Before Run GA Percentile Longest Path : ", percentileastarm)
    print("A Star Manhattan Maximum Longest Path : ", astarm_max_visited_nodes_so_far)
    print("A Star Manhattan Average Obstacle : ", astarm_latest_averageObstacle)
    print("A Star Manhattan Latest Percentile Longest Path: ", astarm_latest_percentile)
    print("A Star Manhattan Hardest Maze")
    print("-----------------------------")
    print(astarm_hardest_maze_matrix_so_far)

    return dfs_hardest_maze_matrix_so_far, bfs_hardest_maze_matrix_so_far, astare_hardest_maze_matrix_so_far, astarm_hardest_maze_matrix_so_far
Exemplo n.º 24
0
    #weights.append([0.3, 0.4])
    #weights.append([0.1, 0.9])
    for w1 in np.arange(0.1, 1.0, 0.1):
        for w2 in np.arange(0.1, 1.0, 0.1):
            weights.append([w1, w2])

    chi = 0.4
    phi_p = 1.2
    phi_g = 1.2

    initRange = [0.0, 1.0]

    pareto_set = []
    for weight in weights:
        print weight
        ga = GeneticAlgorithm(500, initRange, 30, calcFitness, weight, 0.1,
                              0.1)

        for i in range(5000):
            ga.next()

        pareto_set.append(ga.population[0].genes)

    x_p = []
    y_p = []
    for ps in pareto_set:
        val = zdt1(ps)
        x_p.append(val[0])
        y_p.append(val[1])

    pf1 = np.arange(0.0, 1.0, 0.01)
    pf2 = 1.0 - np.sqrt(pf1)
Exemplo n.º 25
0
    result_savePath = log_name.split('.')[0] + '.npz'
    
    cross_rate = 0.5
    mutate_rate = 0.01 # initial num: 0.01
    n_generations = 200 # initial num: 150
    optim_dict = {}
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    neural_network = Net1().to(device)
#    neural_network.load_state_dict(torch.load(cnn_path, map_location='cpu')) # For local laptop
    neural_network.load_state_dict(torch.load(cnn_path)) # For psc
    
    
    # Generating initial dataset
    GDF.generateData_Figure(directory, targetFolder, contourFolder, figFolder, txtFolder, dictFolder)
    # Create genetic algorithm project
    GA = GenAlg.GeneticAlgorithm(cross_rate, mutate_rate, pop_npzPath, n_generations)
    GA.pickForBezier() # Pick the controlling points for Bezier curve fitting. 
    
    # Set a array for storing best fitness value. 
    best_fitness_length = 5
    best_fitness = np.zeros(best_fitness_length)
    informLines = []
    
    initial_best_fitness = 0
    initial_best_airfoil = None
    global_best_fitness = 0
    global_best_airfoil = None
    generation_list = []
    fitness_list = []
    
    for gen in range(n_generations):
def TrainMultipleTrack(setting,settingPrint,settingNewGen=None,filenameLoadGen=None,filenameSaveGen=None):
    filenameMapL = setting[0]
    nbgeneration = setting[1]
    nbParents = setting[2]
    mutationRate = setting[3]
    listM = []
    nbTracks = len(filenameMapL) # number of circuits used
    
    # Generation of the markers
    for i in range(nbTracks):
        BM.GenerateMarkers(filenameMapL[i],'markers/markers.txt',8,21)
        listM.append(EF.loadMarkers('markers/markers.txt'))
    ga = GA.GeneticAlgorithm(nbgeneration,0,nbParents,mutationRate)
    posInit = EF.startingPoint(listM[0],30)
    
    # Load generation
    if(filenameLoadGen != None):
        cars = ga.loadGeneration(filenameLoadGen,posInit)
    elif(settingNewGen != None):
        ga.speedBool = settingNewGen[1]
        cars = []
        for i in range(0,settingNewGen[0]):
            cars.append(Car.Car(posInit,settingNewGen[2],settingNewGen[3]))
    else:
        print('Arguments not valid')
        return
    
    # Fitness contains the score of cars (the minimum of scores on each 
    # circuits), markerIndex is the equivalent list of position of marker
    # reached and bestIndexMarker is the higher markerIndex
    fitness = []
    markerIndex = []
    bestIndexMarker = []
    for i in range(len(cars)):
        fitness.append(math.inf)
        markerIndex.append(math.inf)
    for gen in range(0,ga.nbgenerations):
        for i in range(nbTracks):
            posInit = EF.startingPoint(listM[i],30)
            for j in range(len(cars)):
                cars[j].rinit(posInit)
            trainCircuit(cars,filenameMapL[i],listM[i],ga,settingPrint)
            ga.Tours = 0
            for j in range(len(cars)):
                fitness[j] = min(fitness[j],cars[j].fitness)
                markerIndex[j] = min(markerIndex[j],cars[j].markerCount)
        bestIndexMarker.append(max(markerIndex))
        # Initialisation of fitness and makerIndex
        for j in range(len(cars)):
            cars[j].fitness = fitness[j]
            fitness[j] = math.inf
            markerIndex[j] = math.inf
        
        # Update of genetic algorithm
        cars = ga.updateGeneticAlgorithmState(cars)
        print("generation: "+str(gen))
        print("maxMarker: "+str(bestIndexMarker[-1])+"\n")
    
    # Saving generation    
    if(filenameSaveGen != None):
        ga.saveGeneration(filenameSaveGen,cars)
    # Display
    if(settingPrint[0] == 1):
        cv2.waitKey(0)
        cv2.destroyAllWindows()
    return bestIndexMarker
Exemplo n.º 27
0
import GeneticAlgorithm

####################################################################################
bounds = [[0, 67], [0, 3]]  #[[speed range], [actions]]
mutationProb = 0.4  # mutation rate
crossoverProb = 0.4  # crossover rate
popSize = 4
numOfNpc = 2
numOfTimeSlice = 5
maxGen = 100
####################################################################################

ge = GeneticAlgorithm.GeneticAlgorithm(bounds, mutationProb, crossoverProb,
                                       popSize, numOfNpc, numOfTimeSlice,
                                       maxGen)
#ge.set_checkpoint('GaCheckpoints/last_gen.obj')
ge.ga()
Exemplo n.º 28
0
# (  -8394.41, 2666.40    ),
# (  -5041.91, 3013.26    ),
# (  -7222.55, 2307.80    ),
# (  -5375.64, 2483.28    ),
# (  -7547.32, 2873.69    ),
# (  -6156.40, 2920.67    ),
# (  -5362.51, 2982.15    ),
# (  -6388.57, 3041.59    ),
# (  -5523.51, 2575.20    ),
# (  -5351.44, 2593.85    ),
# (  -5865.51, 2752.08    ),
# (  -7744.91, 2678.84    ),
# (  -6178.52, 3153.51    ),
# (  -8278.33, 2730.66    ),
# (  -7230.86, 3483.78    ),
# (  -8446.23, 2776.26    ),
# (  -5246.43, 2786.63    ),
# (  -5613.31, 2843.96    )]

G = FullyConnectedGraph(random_nodes)
if N > 50:
    mutation_rate = .3
else:
    mutation_rate = .5
ga = GeneticAlgorithm(G,
                      num_chromosomes=1000,
                      depth=10000000,
                      mutation_rate=mutation_rate,
                      crossover_rate=1)
winner = ga.run()
            pd.to_datetime("20100101", format="%Y%m%d"),
            pd.to_datetime("20101231", format="%Y%m%d"),
        ]
    ),
)
_lstm_instance.prepare_complete_data_set()


_ga_1 = GeneticAlgorithm(
    training_set_ga=_lstm_instance.training_set,
    testing_set_ga=_lstm_instance.testing_set,
    network_architecture=OrderedDict(
        [
            ("Layer1", [2, 43, 5]),
            ("Layer2", [1, 42, 4]),
            ("Layer3", [0, 21, 3]),
            ("Layer4", [0, 21, 4]),
        ]
    ),
    learning_rate=[0.001, 0.062, 0.02],
    initial_population_source_external=True,
    build_grid_scenarios=False,
)

_ga_1.run_complete_genetic_algorithm(number_of_generations=20)

result = _ga_1.initial_population

result.to_csv(
    folder_structure.output_GridSearch
    + "/"
Exemplo n.º 30
0
from Algorithms import Searcher
from Utility import *
from GeneticAlgorithm import *

graph = generateGraph("Test_Problems/prob15.map")

searcher = Searcher(graph)
res = []
res.append(searcher.AStarSearch())

res.append(searcher.BreadthFirstSearch())

res.append(searcher.DepthFirstSearch())

res.append(searcher.UniformCostSearch())

ProbScore = ProblemScore(res)
ProbScore.printScores()
scores = ProbScore.GetScores()
resDict = ProbScore.GetResultDict()

GA = GeneticAlgorithm(50, scores, resDict)

gaRes = GA.PerformAlgorithm()

gaRes.printResult()