def runn(newnet):
    global p, f, c, totalTime
    for n in range(len(newnet)):
        startTime = time.time()
        # import IPython;
        # IPython.embed(); 
        start = newnet[n][0]
        target = newnet[n][1]

        print '\nNewnet: ' + str(newnet)
        
        # Allow connections to target gate (but only from non-gates and from
        # vertices without a pre-existing path.
        connectVertex(g, target)

        message = 'Find path between ' + str(start) + ' and ' + str(target) + ' ' + str(p)
        print(message.rjust(27)),

        # Use algorithm to compute a path between start and target.
        algorithm(g, g.vertDict[start], g.vertDict[target])

        # Extract the previously computed path from graph g
        path = []
        path.append(target)
        tracePath(g, g.vertDict[target], path)

        # Disconnect connections to the vertices in path
        disconnectVertex(g, path)

        # Assign all vertices in the path (not the gates) the path id 
        for i in path[1:-1]:
            g.vertDict[i].path = p
            pathsvert[i].append(p)
        

        if len(path) > 1:
            print path
            f += 1
            # c += len(path) - 1
        else:
            print '          PATH NOT FOUND '
            for v in range(len(pathsvert)):
                if (pathsvert[v] == [p-1]):
                    pathsvert[v] = []
                    # grid[(v % SURF) / WIDTH][v % WIDTH][v / SURF] = 0

            if (n ==  0):
                random.shuffle(newnet)
            else:
                newnet = newnet[(n-1):]
                random.shuffle(newnet)            
                p -= 1
            return runn(newnet)
            
        p += 1

        # Prepare graph for next search.
        for v in g:
            v.previous = None

        elapsedTime = time.time() - startTime
        totalTime += elapsedTime
예제 #2
0
SOLVE
"""
for n in newnet:
    startTime = time.time()
    start = n[0]
    target = n[1]
    
    # Allow connections to target gate (but only from non-gates and from
    # vertices without a pre-existing path.
    connectVertex(g, target)

    message = 'Find path between ' + str(n[0] + 1) + ' and ' + str(n[1] + 1)
    print(message.rjust(27)),

    # Use algorithm to compute a path between start and target.
    algorithm(g, g.vertDict[start], g.vertDict[target])

    # Extract the previously computed path from graph g
    path = []
    path.append(target)
    tracePath(g, g.vertDict[target], path)

    # Disconnect connections to the vertices in path
    disconnectVertex(g, path)

    # Assign all vertices in the path (not the gates) the path id 
    for i in path[1:-1]:
        g.vertDict[i].path = p
    p += 1

    if len(path) > 1:
def main(win, width):
    running = True
    rows = 40  # No. of rows and columns
    start_node = 0
    end_node = 0

    # To make blocks on the screen
    grid = make_grid(win, width, rows)

    while running:
        draw(win, rows, width, grid)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

            # Mouse left click event
            if pygame.mouse.get_pressed()[0]:
                row, col = get_mouse_pos(grid, win, width, rows)
                spot = grid[row][col]

                if start_node == 0 and spot.color == WHITE:
                    spot.add_start()
                    start_node = 1

                if end_node == 0 and spot.color == WHITE:
                    spot.add_end()
                    end_node = 1

                if spot.color == RED:
                    spot.add_end()

                if spot.color == BLUE:
                    spot.add_start()

                if spot.color == WHITE:
                    spot.add_black()

            # Mouse right click event
            if pygame.mouse.get_pressed()[2]:
                row, col = get_mouse_pos(grid, win, width, rows)
                spot = grid[row][col]

                if spot.color == BLUE:
                    spot.remove_color()
                    start_node = 0
                elif spot.color == RED:
                    spot.remove_color()
                    end_node = 0
                else:
                    spot.remove_color()

            # To start the algorithm
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    for row in grid:
                        for block in row:
                            block.update_neighbors(grid)
                    algorithm(grid, win, lambda: draw(win, width, rows, grid))

        pygame.display.update()

    pygame.quit()
예제 #4
0
def TravelingSalesman():
    # Create list of city coordinates
    """
    coords_list = [(1, 1), (4, 2), (5, 2), (6, 4), (4, 4), (3, 6), (1, 5), (2, 3), (10, 10), (15, 22), (2, 7), (19, 15), (11, 13),
                    (33, 24), (12, 17), (29, 2), (2, 5), (5, 19), (11, 36), (21, 37), (57, 22), (36, 12), (19, 20), (13, 19), (13, 54), (0, 5),
                    (44, 14), (45, 45), (23, 20), (16, 2), (3, 29), (21, 59), (18, 29), (2, 2), (19, 17), (39, 14), (9, 9), (48, 14), (59, 59), (29, 1)]
    """
    weights = [
        10, 5, 2, 8, 15, 20, 5, 2, 1, 20, 8, 6, 14, 22, 50, 5, 10, 12, 12, 18,
        26, 32, 4, 8, 10, 5, 22, 10, 5, 2, 8, 15, 20, 5, 2, 1, 20, 8, 6, 14,
        22, 50, 5, 10, 12, 12, 18, 26, 32, 4, 8, 10, 5, 22, 10, 5, 2, 8, 15,
        20, 5, 2, 1, 20, 8, 6, 14, 22, 50, 5, 10, 12, 12, 18, 26, 32, 4, 8, 10,
        5, 22
    ]
    values = [
        1, 2, 3, 4, 5, 2, 5, 10, 1, 4, 10, 2, 2, 8, 100, 5, 15, 24, 8, 14, 36,
        10, 5, 2, 120, 4, 8, 1, 2, 3, 4, 5, 2, 5, 10, 1, 4, 10, 2, 2, 8, 100,
        5, 15, 24, 8, 14, 36, 10, 5, 2, 120, 4, 8, 1, 2, 3, 4, 5, 2, 5, 10, 1,
        4, 10, 2, 2, 8, 100, 5, 15, 24, 8, 14, 36, 10, 5, 2, 120, 4, 8
    ]
    max_weight_pct = 0.6

    #n = len(coords_list)
    n = len(weights)

    # Initialize fitness function object using coords_list
    #fitness_coords = mlrose.TravellingSales(coords = coords_list)
    fitness = mlrose.Knapsack(weights, values, max_weight_pct)

    # Define optimization problem object
    problem = mlrose.DiscreteOpt(length=n, fitness_fn=fitness, maximize=True)

    best_state, best_fitness, score_curves, runtime = algorithm(
        problem=problem, max_attempts=500, max_iters=100)

    def plot_solution(algorithm_type: str, solution: list) -> None:
        """Given a solution, plot it and save the result to disk."""
        fig = plt.figure()
        ax = fig.add_subplot(111, aspect='equal')
        ax.set_xlim((0, n))
        ax.set_ylim((0, n))

        count = 0
        for queen in solution:
            ax.add_patch(patches.Rectangle((queen, count), 1, 1))
            count += 1
        fig.savefig(algorithm_type + '_' +
                    ''.join([str(a) for a in solution]) + '.png',
                    dpi=150,
                    bbox_inches='tight')
        plt.close(fig)

    for key, value in best_state.items():
        plot_solution(key, value)

    def PlotData(x, y, x2, y2, x3, y3, x4, y4):
        plt.figure()
        plt.plot(x, y, 'r', x2, y2, 'g', x3, y3, 'b', x4, y4, 'c', alpha=0.5)
        plt.xlabel('Iteration')
        plt.ylabel('Fitness')

        red_patch = patches.Patch(color='red', label='Genetic Algorithms')
        green_patch = patches.Patch(color='green', label='Simulated Annealing')
        blue_patch = patches.Patch(color='blue', label='MIMIC')
        cyan_patch = patches.Patch(color='cyan', label='Randomized Hill Climb')
        plt.legend(handles=[red_patch, green_patch, blue_patch, cyan_patch])

        plt.show()

    PlotData(list(range(len(score_curves['genetic algorithm']))),
             score_curves['genetic algorithm'],
             list(range(len(score_curves['simulated annealing']))),
             score_curves['simulated annealing'],
             list(range(len(score_curves['mimic']))), score_curves['mimic'],
             list(range(len(score_curves['randomized hill climbing']))),
             score_curves['randomized hill climbing'])

    return best_state, best_fitness, score_curves, runtime
예제 #5
0
def MaxKColoring():
    # edges = [(0, 1), (0, 2), (0, 4), (1, 3), (2, 0), (2, 3), (3, 4)]
    state = np.array([
        1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1,
        1, 0, 0, 0, 0, 0, 0, 0, 0
    ])
    n = len(state)

    #fitness = mlrose.MaxKColor(edges)
    fitness = mlrose.FourPeaks(t_pct=0.15)

    # Define optimization problem object
    #problem = mlrose.DiscreteOpt(length = n, fitness_fn = fitness, maximize = False, max_val = n)
    problem = mlrose.DiscreteOpt(length=n,
                                 fitness_fn=fitness,
                                 maximize=True,
                                 max_val=2)

    best_state, best_fitness, score_curves, runtime = algorithm(
        problem=problem, max_attempts=500, max_iters=50)

    def plot_solution(algorithm_type: str, solution: list) -> None:
        """Given a solution, plot it and save the result to disk."""
        fig = plt.figure()
        ax = fig.add_subplot(111, aspect='equal')
        ax.set_xlim((0, n))
        ax.set_ylim((0, n))

        count = 0
        for queen in solution:
            ax.add_patch(patches.Rectangle((queen, count), 1, 1))
            count += 1
        fig.savefig(algorithm_type + '_' +
                    ''.join([str(a) for a in solution]) + '.png',
                    dpi=150,
                    bbox_inches='tight')
        plt.close(fig)

    for key, value in best_state.items():
        plot_solution(key, value)

    def PlotData(x, y, x2, y2, x3, y3, x4, y4):
        plt.figure()
        plt.plot(x, y, 'r', x2, y2, 'g', x3, y3, 'b', x4, y4, 'c', alpha=0.5)
        plt.xlabel('Iteration')
        plt.ylabel('Fitness')

        plt.xticks(np.arange(0, 51, 3.0))
        #plt.yticks(np.arange(-5, 5, 1))

        red_patch = patches.Patch(color='red', label='Genetic Algorithms')
        green_patch = patches.Patch(color='green', label='Simulated Annealing')
        blue_patch = patches.Patch(color='blue', label='MIMIC')
        cyan_patch = patches.Patch(color='cyan', label='Randomized Hill Climb')
        plt.legend(handles=[red_patch, green_patch, blue_patch, cyan_patch])

        plt.show()

    PlotData(list(range(len(score_curves['genetic algorithm']))),
             score_curves['genetic algorithm'],
             list(range(len(score_curves['simulated annealing']))),
             score_curves['simulated annealing'],
             list(range(len(score_curves['mimic']))), score_curves['mimic'],
             list(range(len(score_curves['randomized hill climbing']))),
             score_curves['randomized hill climbing'])

    return best_state, best_fitness, score_curves, runtime
예제 #6
0
def computeNQueens(n=8):
    num_queens = n

    # Define alternative N-Queens fitness function for maximization problem
    def queens_max(state):
        # Initialize counter
        fitness_cnt = 0
        # For all pairs of queens
        for i in range(len(state) - 1):
            for j in range(i + 1, len(state)):
                # Check for horizontal, diagonal-up and diagonal-down attacks
                if (state[j] != state[i]) \
                and (state[j] != state[i] + (j - i)) \
                and (state[j] != state[i] - (j - i)):
                    # If no attacks, then increment counter
                    fitness_cnt += 1
        return fitness_cnt

    # Initialize custom fitness function object
    fitness_cust = mlrose.CustomFitness(queens_max)

    problem = mlrose.DiscreteOpt(length=num_queens,
                                 fitness_fn=fitness_cust,
                                 maximize=True,
                                 max_val=num_queens)

    best_state, best_fitness, score_curves, runtime = algorithm(
        problem=problem, max_attempts=500, max_iters=100)

    def plot_solution(algorithm_type: str, solution: list) -> None:
        """Given a solution, plot it and save the result to disk."""
        fig = plt.figure()
        ax = fig.add_subplot(111, aspect='equal')
        ax.set_xlim((0, num_queens))
        ax.set_ylim((0, num_queens))

        count = 0
        for queen in solution:
            ax.add_patch(patches.Rectangle((queen, count), 1, 1))
            count += 1
        fig.savefig(algorithm_type + '_' +
                    ''.join([str(a) for a in solution]) + '.png',
                    dpi=150,
                    bbox_inches='tight')
        plt.close(fig)

    for key, value in best_state.items():
        plot_solution(key, value)

    def PlotData(x, y, x2, y2, x3, y3, x4, y4, alpha=0.5):
        plt.figure()
        plt.plot(x, y, 'r', x2, y2, 'g', x3, y3, 'b', x4, y4, 'c')
        plt.xlabel('Iteration')
        plt.ylabel('Fitness')

        red_patch = patches.Patch(color='red', label='Genetic Algorithms')
        green_patch = patches.Patch(color='green', label='Simulated Annealing')
        blue_patch = patches.Patch(color='blue', label='MIMIC')
        cyan_patch = patches.Patch(color='cyan', label='Randomized Hill Climb')
        plt.legend(handles=[red_patch, green_patch, blue_patch, cyan_patch])

        plt.show()

    PlotData(list(range(len(score_curves['genetic algorithm']))),
             score_curves['genetic algorithm'],
             list(range(len(score_curves['simulated annealing']))),
             score_curves['simulated annealing'],
             list(range(len(score_curves['mimic']))), score_curves['mimic'],
             list(range(len(score_curves['randomized hill climbing']))),
             score_curves['randomized hill climbing'])

    return best_state, best_fitness, score_curves, runtime