Example #1
0
    def h(self, node: Node):
        """ Função heuristica utilizada para a procura A*. """
        b = node.state.board

        simplified_problem = SimplifiedRicochetRobots(b)
        solution_node = recursive_best_first_search(simplified_problem)

        aux = 0
        counter = 0

        if solution_node != None:
            for s in solution_node.solution():
                if s[1] != aux:
                    aux = s[1]
                    counter += 1
        else:
            counter = 3
        return counter
Example #2
0
start = generate_random_init(city_num)
print(start)

tsp = TSPProblem(start, cities=generate_random_cities(city_num, 100))

# compare the execution time
start_time = time.time()
node_astar = astar_search(tsp)
depth = len(node_astar.path())
print("Execution time for A*: {}".format(time.time() - start_time))
print("Node number: {}".format(tsp.nodes_cnt))
print("Depth: {}".format(depth))
print("Effective branching factor: {}".format(effective_branching_factor(tsp.nodes_cnt, depth)))
tsp.nodes_cnt = 0
start_time = time.time()
node_rbfs = recursive_best_first_search(tsp)
depth = len(node_rbfs.path())
print("Execution time for RBFS: {}".format(time.time() - start_time))
print("Node number: {}".format(tsp.nodes_cnt))
print("Depth: {}".format(depth))
print("Effective branching factor: {}".format(effective_branching_factor(tsp.nodes_cnt, depth)))




print(node_astar.state)

xs = []
ys = []
for i in range(len(node_astar.state)):
    xs.append(tsp.cities[node_astar.state[i]][0])
           We are using the manhattan distance.
        '''
        distance = 0
        rows = string_to_list(self.state_str)
        for number in '12345678e':
            #print (node.state.index(number))
            row_n, col_n = find_location(rows, number)
            row_n_goal, col_n_goal = goal_positions[number]

            distance += abs(row_n - row_n_goal) + abs(col_n - col_n_goal)

        return distance

time1 = time.time()
# result = astar_search(EigthPuzzleProblem(INITIAL))
result = recursive_best_first_search(EigthPuzzleProblem(INITIAL))

# if you want to use the visual debugger, use this instead:
# result = astar(EigthPuzzleProblem(INITIAL), viewer=WebViewer())
time2 = time.time()
print('time cost: {}'.format(time2-time1))

step_count = 0
print (result.state)

for action in result.path():
    print ('\nMove {}'.format(action.action))
    print (action.state)
    step_count += 1
print('total steps is {}'.format(step_count))
Example #4
0
            cost = self.costs[0][self.nodes.index(ite)]
            if shortest_cost > cost:
                shortest_cost_starter = cost
        cs_idx_list = [self.nodes.index(x) for x in cs_list]

        mst_matrix = np.delete(self.costs, cs_idx_list, 0)
        mst_matrix = np.delete(mst_matrix, cs_idx_list, 1)
        X = csr_matrix(mst_matrix)
        Tcsr = minimum_spanning_tree(X)
        tcsr_matrix = Tcsr.toarray().astype(int)
        mst_cost_sum = np.sum(tcsr_matrix)
        return mst_cost_sum + shortest_cost + shortest_cost_starter

    def value(self, state):
        # print('state in value: {} \t initial: {}'.format(state, self.initial))
        return -1 * self.costs[self.nodes.index(
            self.state[-1])][self.nodes.index(state[-1])]
        #return len(self.state) - len(self.nodes)


# result = astar_search(TSPProblem(nodes, costs))
result = recursive_best_first_search(TSPProblem(nodes, costs))
step_count = 0

#print(result)
for action in result.path():
    print('\nMove {}'.format(action.action))
    print(action.state)
    step_count += 1
print('total steps is {}'.format(step_count))
Example #5
0
import search

romania_problem = search.GraphProblem('Arad', 'Craiova', search.romania_map)
#vacumm_world = search.GraphProblemStochastic('State_1', ['State_7', 'State_8'], vacumm_world)
#LRTA_problem = search.OnlineSearchProblem('State_3', 'State_5', one_dim_state_space)
eight_puzzle = search.EightPuzzle((1, 2, 3, 0, 4, 6, 7, 5, 8))
nqueens = search.NQueensProblem(8)

print("\nBest first Search")
print("\nSolution to Romania Problem Arad->Craiova")
print(search.recursive_best_first_search(romania_problem).solution())
print("\nSolution to Eight Puzzle (1, 2, 3, 0, 4, 6, 7, 5, 8)")
print(search.recursive_best_first_search(eight_puzzle).solution())
Example #6
0
                          b._barriers,
                          simplified=True)
        new_board.robot_action(action)

        return RRState(new_board)

    def h(self, node: Node):
        b = node.state.board
        robot_pos = b.robot_position(b.get_target()[0])
        target_pos = b.get_target()[1]

        return manhattan_distance(robot_pos, target_pos)


def output(node):
    print(len(node.solution()))

    for s in node.solution():
        print(f"{s[0]} {s[1]}")


if __name__ == "__main__":
    # Ler o ficheiro de input de sys.argv[1],
    board = parse_instance(sys.argv[1])

    problem = RicochetRobots(board)

    solution_node = recursive_best_first_search(problem)

    output(solution_node)
Example #7
0
eight_puzzle = EightPuzzleProblem(start, goal, random_h=False)

# compare the execution time
start_time = time.time()
node_astar = astar_search(eight_puzzle)
depth = len(node_astar.path())
print("Execution time for A*: {}".format(time.time() - start_time))
print("Node number: {}".format(eight_puzzle.nodes_cnt))
print("Depth: {}".format(depth))
print("Effective branching factor: {}".format(
    effective_branching_factor(eight_puzzle.nodes_cnt, depth)))

eight_puzzle.nodes_cnt = 0
start_time = time.time()
node_rbfs = recursive_best_first_search(eight_puzzle)
depth = len(node_rbfs.path())
print("Execution time for RBFS: {}".format(time.time() - start_time))
print("Node number: {}".format(eight_puzzle.nodes_cnt))
print("Depth: {}".format(depth))
print("Effective branching factor: {}".format(
    effective_branching_factor(eight_puzzle.nodes_cnt, depth)))

eight_puzzle = EightPuzzleProblem(start, goal, random_h=True)
eight_puzzle.nodes_cnt = 0
start_time = time.time()
node_rbfs = recursive_best_first_search(eight_puzzle)
depth = len(node_rbfs.path())
print("Execution time for RBFS with random number: {}".format(time.time() -
                                                              start_time))
print("Node number: {}".format(eight_puzzle.nodes_cnt))