Ejemplo n.º 1
0
 def __init__(self, inputState, goalState, isManhattanDistance):
     Astar.__init__(self, inputState)
     self.NodesGenerated = 0
     self.goalState = goalState
     self.dimension = 3
     self.isManhattanDistance = isManhattanDistance
     n = self.createNode()
     heapq.heappush(self.fringe, (n.f, n))
def construct_training_set(n_try):
    '''
    Build a tranining set which is sampled from the instances of 8-puzzle.

    :param int n_try: the number of 8-puzzle instances to be solved.
    '''
    start = time.time()
    print('Total:', n_try)
    puzzle_l = np.arange(9)
    # get all the possible states of 8-puzzle
    perms = list(permutations(puzzle_l))
    # shuffel the permutations
    shuffle(perms)
    data = dict()
    count = 0  # count the number of tries when the puzzle is solvable
    for _ in range(len(perms)):
        if count % 100 == 0:
            print('Current process:', count)
        if count == n_try: break
        element = perms.pop()  # get an initial state of 8 puzzle
        if check_solvable(element):
            count += 1
            puzzle = np.array(element).reshape([3, 3])
            root = Node(puzzle)
            solution = Astar(root)[0]
            if solution != None:
                # record the path cost of the solution
                full_cost = solution.g
                while (solution.parent != None):
                    # record the features of the states of the solution path
                    solution = solution.parent
                    sum_of_mattan_dis = solution.get_H1()
                    number_of_misplaced = solution.get_H2()
                    if data.get((sum_of_mattan_dis, number_of_misplaced)):
                        if len(data[(sum_of_mattan_dis,
                                     number_of_misplaced)]) > 20:
                            continue
                    cost = full_cost - solution.g
                    try:
                        data[(sum_of_mattan_dis,
                              number_of_misplaced)].append(cost)
                    except:
                        data[(sum_of_mattan_dis, number_of_misplaced)] = [cost]
    # get the average cost of same initial heuristic values
    for key, value in data.items():
        data[key] = np.average(value)
    print(data)
    # save the dataset as a dictionary
    with open('dataset', 'wb') as f:
        pickle.dump(data, f)
    print(len(data.keys()))
    print('Dataset completed! Time elapsed: %.2f s' % (time.time() - start))
Ejemplo n.º 3
0
    def search(self,
               init,
               limitexp=2000,
               limitdepth=10,
               tickets=[math.inf, math.inf, math.inf],
               anyorder=False):

        size = len(init)

        longestPath = 0

        solutionSet = []

        if anyorder:
            self.arrangePursuitOder(init)

        for i in range(size):
            solution = Astar(self.model, self.auxheur, init[i], self.goal[i],
                             limitexp, limitdepth, tickets, solutionSet, False,
                             0)
            if len(solution) > longestPath:
                longestPath = len(solution)
            solutionSet.append(solution)
            tickets = updateTickets(tickets, solutionSet, i, 1)
            print(solution)

        solutionSet = self.fixOffset(size, init, solutionSet, longestPath,
                                     limitexp, limitdepth, tickets)

        outputSolution = formatOutput(solutionSet)

        return outputSolution
Ejemplo n.º 4
0
class PathPlanner:
    def __init__(self, nest_info: NestInfo,
                 delivery_sites: typing.List["DeliverySite"]):
        self.nest_info: NestInfo = nest_info
        self.delivery_sites: typing.List["DeliverySite"] = delivery_sites
        self.astar = Astar(nest_info.nest_coord, nest_info.maximum_range,
                           nest_info.risk_zones)

    def plan_paths(self):
        """
        This is the function you should re-write. It is expected to mutate the list of
        delivery_sites by calling each DeliverySite's set_path() with the resulting
        path as an argument.

        The default construction shows this format, and should produce 10 invalid paths.
        """
        # path_coords = self.astar.find_path_to(self.delivery_sites[0].coord)
        # for p in path_coords:
        #     print(p, "  ", )
        # print("\n")

        for site in self.delivery_sites:
            print("[{}]".format(site.coord))
            path_coords = self.astar.find_path_to(site.coord)
            # Once you have a solution for the site - populate it like this:
            site.set_path(path_coords)
Ejemplo n.º 5
0
 def getNeighbors(self, current: MstarNode):
     """Get the neighbors of a MstarNode"""
     neighbors = []
     options = []
     # Loop over all the agents
     for i in range(self.n_agents):
         node: Node = current.nodes[i]
         options_i = []
         if i in current.collision_set:
             # If the agent in the collision set we add the current node as well as all possible nodes
             options_i.append(node)
             (x, y) = node.position
             moves = {0: (x - 1, y), 90: (x, y + 1), 180: (x + 1, y), 270: (x, y - 1)}
             options_i.append(Node(node.position, node, node.rotation + 90, node.h))
             options_i.append(Node(node.position, node, node.rotation - 90, node.h))
             if self.grid[moves[node.rotation][0]][moves[node.rotation][1]] == 0:
                 options_i.append(Node(moves[node.rotation], node, node.rotation,
                                       self.heuristic(i, moves[node.rotation], node.rotation)))
         else:
             # If the agent is not in the collision set we add only the optimal following node
             if (node, self.goal.nodes[i]) in self.policy:
                 nextPos = self.policy[(node, self.goal.nodes[i])]
             else:
                 nextPos = Astar(self.grid, node, self.goal.nodes[i]).solve()
                 self.policy[(node, self.goal.nodes[i])] = nextPos
             if isinstance(nextPos, str):
                 print(node, self.goal.nodes[i])
             options_i.append(Node(nextPos[0], node, nextPos[1], self.heuristic(i, nextPos[0], nextPos[1])))
         options.append(options_i)
     # Take the cartesian product to get all options
     for element in itertools.product(*options):
         neighbors.append(list(element))
     return neighbors
Ejemplo n.º 6
0
 def UpdateOptimalPath(self):
     self.path=Astar(self.detected_obstacle,self.start_position,self.end_position)
     if self.path is not None:
         # reverse the OPTIMAL PATH
         self.path=self.path[::-1]
     else:
         return 1
Ejemplo n.º 7
0
def RUN(_time, _heuristic):
    total_time = 0
    count = 0
    total_steps = 0
    i = 1

    my_DBs = {}
    with open("puzzles.txt") as fh:
        puzzle = fh.readline()
        while puzzle:
            p = Board(puzzle.rstrip('\n'))
            n = len(p.VehicleHash)
            if n not in my_DBs:
                my_DBs[n] = DataBase()

            AObj = Astar(p)
            results = AObj.solve(_time, _heuristic, my_DBs[n])

            if results is None:
                print("-E- Could not solve puzzle number ", i, " due to time limit\n"
                      "==========================================")

            else:
                solution_path = results[0]
                steps = results[1]
                current_time = results[2]

                print("For puzzle number ", i, ":\n"
                      "Time - ", current_time, "\n"
                      "Steps - ", steps, "\n"
                      "Solution path - ", solution_path, "\n"
                      "==========================================")

                total_time += current_time
                count += 1
                total_steps += steps
            i += 1
            puzzle = fh.readline()
        fh.close()

    print("==========================================\n"
          "SUMMARY\n"
          "Solved ", count, " out of ", i - 1, " puzzles with heuristic number ", _heuristic, " with time limit of  ",_time, "\n"
          "Total time - ", total_time, "\n"
           "Average time for one puzzle - ", total_time / count, "\n"
           "Average steps for one puzzle - ", total_steps / count, "\n")
Ejemplo n.º 8
0
 def main(self, options, h_type):
     self.set_dico(options)
     self.set_visu(options.visual)
     if self.dico["solvable"] == "True":
         Astar(self.get_dico(), h_type, self.get_visu(), options)
     elif self.dico["solvable"] == "False":
         print("This puzzle is not solvable, stopping now.")
         sys.exit()
def find_path(maze, start, end, heat_map=None):
    if heat_map is not None:
        # run custom code here, for dual code support
        ASTAR = Astar(MAX_HEAT_MAP_VALUE=MAX_HEAT_MAP_VALUE,
                      HEAT_MAP_WEIGHT=MAX_HEAT_MAP_WEIGHT)
        map_grid, sNode, eNode = ASTAR.genMap(maze,
                                              start,
                                              end,
                                              PATH_VALUE=1,
                                              heat_map=heat_map)
        sNode.printSelf()
        eNode.printSelf()
        print('--- RESULT ---')
        path = ASTAR.findPath(map_grid, sNode, eNode, ALLOW_DIAG=False)
        pathArray = []
        if path is not None:
            if len(path) > 1:
                pathArray = ASTAR.extractPath(path)
                ASTAR.printMaze(map_grid, pathArray)
            else:
                print("[ERROR] --X Custom Astar Cannot Compute Path")
        else:
            print("[ERROR] --X Custom Astar Cannot Compute Path")
        return pathArray
    else:
        print('Ima end these coordinates')
        print(start, end)
        pathA = PathA()
        return pathA.getPath(maze, start, end)
Ejemplo n.º 10
0
def run_algorithm(algorithm, board, board_size):

    logic = GameLogic(State(board), board_size)
    if algorithm == 1:
        ids = IDS(State(board), logic)
        chosen = ids.run_search()
    elif algorithm == 2:
        bfs = BFS(State(board), logic)
        chosen = bfs.run_search()
    elif algorithm == 3:
        a_star = Astar(State(board), logic)
        chosen = a_star.run_search()
    else:
        raise Exception("No algorithm was chosen")
    if chosen is not None:
        to_print = ' '.join(map(str, chosen))
        with open('output.txt', 'w') as output_file:
            output_file.write(to_print)
def realtime_search(objects):
    """ Path finding with realtime Astar algorithm
    return command at each step and the original Astar path solution"""

    decider = Decider(False)
    # plot the original path
    jetbot_pos, jetbot_size = objects['Jetbot'][0], objects['Jetbot'][-4:]
    grab_pos = objects['Grabber'][0]
    decider.reinit(jetbot_pos, grab_pos)

    obstacle_ls = objects['Obstacle']
    s_start = objects['Jetbot'][0]
    s_goal = objects['Target'][0]
    if type(obstacle_ls[0]) == type(()):  # if there is only one obstacle:
        obstacle_ls = [obstacle_ls]

    global Ratio
    Path_Found = False
    while not Path_Found:  # Error might take place when scale changes
        try:
            astar = Astar(s_start, s_goal, obstacle_ls, jetbot_size, Ratio)
            Original_path, visited = astar.searching()
            Path_Found = True
        except UnboundLocalError:
            Ratio -= 0.1
            print('Error, try change the size, ratio = ', Ratio)

    plot = plotting.Plotting(s_start, s_goal, obstacle_ls)
    plot.animation(Original_path, visited, 'AStar')

    # define path and obstacle set
    path = Original_path
    obs_set = get_obs_set(obstacle_ls, jetbot_size)

    # start iteration
    while len(path) > decider.Horizon:
        decider.jetbot_step(path, obs_set)
        path = Astar_search(objects, decider)

    # get the result
    trajectory = decider.get_trajectory()
    print('Terminate, Total number of movements is: %d' % len(trajectory))
    plot.plot_traj(Original_path, trajectory)
    return decider.cmd_record, Original_path
Ejemplo n.º 12
0
 def search(self, search_type, problem):
     if (search_type == 'bfs'):
         return BreadthFirst().breadth_first_tree_search(problem)  #node
     elif search_type == 'unicost':
         return UniCost().uniform_cost_search(problem)  #node
     elif search_type == 'iddfs':
         return IDDFS().Iterative_Deepening_Search(problem)  #node
     elif search_type == 'greedy':
         return Greedy().greedy_cost_search(problem)
     elif search_type == 'astar':
         return Astar().astar_cost_search(problem)
Ejemplo n.º 13
0
    def fixOffset(self, size, init, solutionSet, longestPath, limitexp,
                  limitdepth, tickets):

        incompletePath = None

        fixedOffset = True

        for i in range(len(solutionSet)):
            if len(solutionSet[i]) != longestPath:
                fixedOffset = False
                break

        while not fixedOffset and size > 1:
            alreadyDone = []

            for i in range(len(solutionSet)):
                if len(solutionSet[i]) < longestPath:
                    incompletePath = solutionSet[i]
                    offsetIndex = i

            for j in solutionSet:
                if len(j) == longestPath:
                    alreadyDone.append(j)

            if incompletePath:
                tickets = updateTickets(tickets, solutionSet, offsetIndex, 2)
                offsetPath = Astar(self.model, self.auxheur, init[offsetIndex],
                                   self.goal[offsetIndex], limitexp,
                                   limitdepth, tickets, alreadyDone, True,
                                   longestPath)

                if offsetPath == []:  #quer dizer que nao existe um path naquele numero de steps
                    longestPath += 1
                    continue
                solutionSet.pop(offsetIndex)

                for k in range(size):
                    if [init[k]] == offsetPath[0][1]:  #para ter o id do start
                        index = k
                        break

                solutionSet = solutionSet[0:index] + [offsetPath
                                                      ] + solutionSet[index:]
                tickets = updateTickets(tickets, solutionSet, index, 1)
                fixedOffset = True

                for path in solutionSet:
                    if len(path) != longestPath:
                        fixedOffset = False
                        break

            incompletePath = None
            offsetPath = []
        return solutionSet
def Astar_search(objects, decider):
    """ Searching conducting
    :return: path points """
    obstacle_ls = objects['Obstacle']
    s_start = decider.get_position()
    s_goal = objects['Target'][0]
    jetbot_size = objects['Jetbot'][-4:]
    if type(obstacle_ls[0]) == type(()):  # if there is only one obstacle:
        obstacle_ls = [obstacle_ls]

    global Ratio
    Path_Found = False
    while not Path_Found:  # Error might take place when scale changes
        try:
            astar = Astar(s_start, s_goal, obstacle_ls, jetbot_size, Ratio)
            path_sol, visited = astar.searching()
            Path_Found = True
        except UnboundLocalError:
            Ratio -= 0.1
            print('Error, try change the size, ratio = ', Ratio)
    return path_sol
def main(empty):
    finnished = False
    rate = rospy.Rate(5)  # Hz
   
    getNextGoal()   # Get the new goal, closest aruco marker.
    
    # Using Astar to navigate. 
    nav = Astar(jsonfile,  0.05)
    nav.start = [pos.pose.position.x, pos.pose.position.y, 0.4] # pos.pose.position.z
    
    nav.goal = GOAL #[2.7, 1, 0.4]
    nav.getPath()

    while not finnished:
        id = 0
        for goal in nav.droneWayPoints: # Publish path to rviz
            publish_path(goal, id=id)
            id += 1
            rate.sleep()

        id = 0
        for goal in nav.droneWayPoints: # Publish waypoints to hover.
            publish_path(goal, color=[1.0, 0.0, 0.0], id=id)
            id += 1
            tol = 0.2
            while math.sqrt( (pos.pose.position.x - goal[0])**2 + (pos.pose.position.y - goal[1])**2 + (pos.pose.position.z - goal[2])**2 ) > tol:
                publish_hover(goal)
                rate.sleep()
        finnished = True
    return EmptyResponse()
    def __init__(self, start, goal, obs, bot_size, ratio):
        self.decider = Decider()
        self.decider.reinit(start, goal)
        self.astar = Astar(start, goal, obs, bot_size, ratio)
        self.plot = plotting.Plotting(start, goal, obs)
        # self.astar_sol = self.astar.searching()[0]

        # self.REWARD_STEP = 0.01
        self.REWARD_REACH = 100
        self.REWARD_BOUND = -10
        self.REWARD_CRASH = -10
        self.REWARD_OVERRUN = -10
        self.MAX_STEPS = 100
        self.BOUNDS = [1000,800]  # tune according to the environment
        self.TOTAL_DISTANCE = self.count_distance()  # the Original distance between goal and start 
Ejemplo n.º 17
0
    def startPathFinding(threadName, game):
        pygame.mixer.music.load(
            os.path.normcase("soundtrack/pegasus_fantasy_basic.mp3"))
        pygame.mixer.music.play(-1)

        initial_knights = utils.get_knights()
        knights_list = []
        weaker_knight = ['', 9999999, 0]
        for kn in initial_knights:
            if (kn[1] < weaker_knight[1]):
                weaker_knight = kn
            knights_list.append(AstarFight.Knight(kn))

        for knight in knights_list:
            if (knight.kn_name == weaker_knight[0]):
                knight.lives = knight.lives - 1  #reduzindo uma vida do mais fraco apenas para o a*

        houses_list = utils.get_houses()

        print "Deciding battle plan"
        fightingPlan = AstarFight.path_search(knights_list, houses_list)
        i = 1
        for knight_comb in fightingPlan[0]:
            print i
            for knight_in_comb in knight_comb:
                print knight_in_comb
            i += 1

        game.battleCost = fightingPlan[1]
        game.fightingPlan = fightingPlan[0]

        print "Deciding path to traverse"
        returnedValue = Astar.path_search(game.background,
                                          game.background.startCoordenate,
                                          game.background.endCoordenate)
        print returnedValue
        for step in returnedValue:
            game.accCost += game.background.getTerrainCost(
                game.agent.y, game.agent.x)
            game.background.render(game.screen)
            game.agent.move(step, game.screen)
            pygame.display.update()
            game.fpsClock.tick(game.FPS)
            time.sleep(0.1)

        print "AccCost: " + str(game.accCost)
        print "BattleCost: " + str(fightingPlan[1])
        game.semaphore = False  #Semaphore DOWN
def main():
    global pos
    rate = rospy.Rate(20)  # Hz
    nav = Astar(
        "/home/robot/dd2419_ws/src/project_packages/milestone_2_pkg/src/worlds/test.world.json",
        0.1)
    nav.start = [
        pos.pose.position.x, pos.pose.position.y, pos.pose.position.z + 0.4
    ]
    nav.goal = [2.7, 1, 0.4]
    nav.getPath()

    path_ok = 0

    while not rospy.is_shutdown():
        id = 0
        if path_ok == 0:
            for goal in nav.droneWayPoints:
                publish_path(goal, id=id)
                id += 1
                rate.sleep()

        id = 0
        if path_ok != 1:
            path_ok = input('Is the path ok (y=1/n=0)?: ')

        if path_ok == 1:
            for goal in nav.droneWayPoints:
                publish_path(goal, color=[1.0, 0.0, 0.0], id=id)
                id += 1
                tol = 0.2
                while math.sqrt((pos.pose.position.x - goal[0])**2 +
                                (pos.pose.position.y - goal[1])**2 +
                                (pos.pose.position.z - goal[2])**2) > tol:
                    publish_cmd(goal)
                    rate.sleep()
            nav.droneWayPoints = []
            publish_cmd(goal)
            rate.sleep()
Ejemplo n.º 19
0
import numpy as np
import math
from util import Coord, Distance, Node, Euclidean
import os
import json
import pickle
from Astar import Astar
import re
from fuzzywuzzy import fuzz
import time

d = Distance()
e = Euclidean()
astar = Astar()
nodes = []
APIs = None
with open('API', 'r') as file:
    APIs = file.read().split('\n')
    print('{} APIs successfully read'.format(len(APIs)))
child_count = 7
places = []


def generateGraph(outfile, cc=child_count):
    global nodes, places

    d.setAPI(APIs[0])
    usedApi = APIs.pop(0)
    APIs.append(usedApi)
    outfile = open(outfile, 'r')
    outdata = outfile.read().split('\n')
Ejemplo n.º 20
0
from Routenetwork import Routenetwork
from preprocess import init, distanceList
from Astar import Astar
from Latlong import ShowNodesOnMap

data = init()
nodes = data[0]
edges = data[1]
nodedict = data[2]

g = Routenetwork()
for item in edges:
    g.addEdge(item)

g_edges = g.getEdges()
distances = distanceList(nodes, nodedict, g_edges)
for items in nodes:
    distances[(items, items)] = 0
start = 'Birla Institute of Technology Hyderabad'
end = 'RGIA'

path = Astar(g, nodedict, distances, start, end)

print('Final Route :')
print('****Start****')
for item in path:
    print(item)
print('****End****')
ShowNodesOnMap(path, nodedict)
Ejemplo n.º 21
0
    # nonrandom start and finish
#     start = Cell(1, 1)
#     end = Cell(size-2, size-2)
    maze = Grid(size).get_grid()
    # special test modificiation
#     maze[5, 4] = 1
#     maze[4,4] = 1
#     maze[4,3] = 1
#     maze[3,4] = 1
#     maze[3,3] = 1
#     maze[2,3] = 1
    maze2 = np.copy(maze)
    maze3 = np.copy(maze)
    maze4 = np.copy(maze)
    # Repeated Forward
    alg1 = Astar(size, start, end, maze)
    grid = alg1.get_grid()
    Maze(size, grid)
    # Repeated Forward favoring small g
    alg2 = AstarGsmall(size, start, end, maze2)
    grid2 = alg2.get_grid()
    Maze(size, grid2)
    # Repeated Backward
    alg3 = AstarB(size, end, start, maze3)
    grid3 = alg3.get_grid()
    Maze(size, grid3)
    # Adaptive A*
    alg4 = AAstar(size, start, end, maze4)
    grid4 = alg4.get_grid()
    Maze(size, grid4)
    
Ejemplo n.º 22
0
 def search_path(self, handles, goalconfig, type="4-connected"):
     path = Astar(self.robot, goalconfig, self.env, handles, type)
     path = flip(path, 0)
     return path
Ejemplo n.º 23
0
 def __init__(self, nest_info: NestInfo,
              delivery_sites: typing.List["DeliverySite"]):
     self.nest_info: NestInfo = nest_info
     self.delivery_sites: typing.List["DeliverySite"] = delivery_sites
     self.astar = Astar(nest_info.nest_coord, nest_info.maximum_range,
                        nest_info.risk_zones)
Ejemplo n.º 24
0
import sys

from Astar import Astar
from BKTree import BKTree

from BrokenPhone import BrokenPhone

bk_tree = BKTree()
file = open(sys.argv[1], 'r')
print("Start loading file!")
for word in file:
    bk_tree.insert(word.rstrip())
print("End loading file!")

astar = Astar()
astar.search(bk_tree, "life", "death")

for item in astar.getChain():
    print(item)
Ejemplo n.º 25
0
            finalState = srs.doSearch()
            srs.m_solution.reverse()
            print("Solution steps : %d" % len(srs.m_solution))
            print("Generated nodes: %d" % srs.nGenerated)
            print("Visited nodes: %d" % srs.nVisited)
            print("Expanded nodes: %d" % srs.nExpanded)
        elif algo == algos[4]:
            srs = Greedy(state, seed2)
            finalState = srs.doSearch()
            srs.m_solution.reverse()
            print("Solution steps : %d" % len(srs.m_solution))
            print("Generated nodes: %d" % srs.nGenerated)
            print("Visited nodes: %d" % srs.nVisited)
            print("Expanded nodes: %d" % srs.nExpanded)
        elif algo == algos[5]:
            srs = Astar(state, seed2)
            finalState = srs.doSearch()
            srs.m_solution.reverse()
            print("Solution steps : %d" % len(srs.m_solution))
            print("Generated nodes: %d" % srs.nGenerated)
            print("Visited nodes: %d" % srs.nVisited)
            print("Expanded nodes: %d" % srs.nExpanded)

        if srs.m_finalState == None:
            print("\nSorry, no solution found ....")
        else:
            print("Solution length: %d" % len(srs.m_solution))
            print("Solution cost:   %f" % srs.m_cost)

            print("Solution:\n")
            for i in range(len(srs.m_solution)):
Ejemplo n.º 26
0
        for each in range(10):
            for each_other in range(10):
                density = 0.5
                state = Utils.getProblemInstance(size, density, each, agent)
                if algo == algos[0]:
                    srs = SimpleRandomSearch(state, each_other)
                elif algo == algos[1]:
                    srs = BreadthFirst(state, each_other)
                elif algo == algos[2]:
                    srs = DepthFirst(state, each_other)
                elif algo == algos[3]:
                    srs = UniformCost(state, each_other)
                elif algo == algos[4]:
                    srs = Greedy(state, each_other)
                elif algo == algos[5]:
                    srs = Astar(state, each_other)
                # the algorithm itself
                finalState = srs.doSearch()
                piece_data.append(finalState.m_agent)
                size_data.append(finalState.m_boardSize)
                prob_data.append(density)
                steps_sol.append(len(srs.m_solution))
                cost_sol.append(srs.m_cost)
                generated_nodes.append(srs.nGenerated)
                explored_nodes.append(srs.nVisited)
                expanded_nodes.append(srs.nExpanded)

    df = pandas.DataFrame({
        "Piece(nr)": piece_data,
        "Size(board)": size_data,
        "Density": prob_data,
Ejemplo n.º 27
0
 def openAstar(self):
     if self.f1 != None:
         self.f1.close()
     self.f1 = Astar()
Ejemplo n.º 28
0
import time

from Astar import Astar
from Bruteforce import Bruteforce
from Greedy import Greedy
from NetworkParser import NetworkParser

if __name__ == "__main__":
    parser = NetworkParser()
    graph = parser.load_graph_from_txt("links_big.txt")
    # graph = parser.load_graph_from_xml("janos-us.xml")

    astar = Astar()
    bruteforce = Bruteforce()
    greedy = Greedy()

    start_greedy = time.time()
    greedy.solve(graph, list(graph.nodes)[0])
    end_greedy = time.time()
    print("greedy time", end_greedy - start_greedy, '\n')

    start_astar = time.time()
    astar.solve(graph, parser.sorted_costs)
    end_astar = time.time()
    print("A* time", end_astar - start_astar, '\n')

    start_brute = time.time()
    bruteforce.solve(graph, list(graph.nodes)[0])
    end_brute = time.time()
    print("bruteforce time", end_brute - start_brute, '\n')
Ejemplo n.º 29
0
    response = input(
        "Do you want to use the minimum distance heuristic OR the minimum # of cities heuristic? enter d/c"
    )
    if response == 'c':
        mode[1] = True
    elif response == 'd':
        mode[1] = False
    else:
        print("Invalid response")

if I not in adjList or F not in adjList:
    exit("One of the vertices you entered is not in the graph")

print("The initial vertex is: " + I + " and the final vertex is: " + F)

pathMap = Astar(adjList, location, I, F, mode, noVisitList)

if pathMap != False:  #if dfs succeeded
    curr = F  #start at the target node
    output = []  #the path will be backwards so store in a list first
    while (curr != I):
        output.append(curr)
        curr = pathMap[
            curr]  #and use the path map to trace back the steps taken
    output.append(I)  #add the starting point separately
else:
    exit("A path to the final vertex was not found")

#print formatted output
if mode[1] == False:
    print("The path from", I, "to", F, "is:")
import numpy as np
import random
import scipy.interpolate
from Astar import Astar, total_dist_fun


#Loading poses from the ground truth file
def load_poses(pose_gt_file):
    pose_gt = np.loadtxt(pose_gt_file, delimiter=",")
    return pose_gt[1:, 1:3]


poses = load_poses('../dataset/ground_truth/groundtruth_2012-01-08.csv')

#construct A* instance
astar = Astar(poses)

#Test A*
start_idx = np.random.randint(poses.shape[0])
goal_idx = np.random.randint(poses.shape[0])

path, optimal = astar.find_path(start_idx, goal_idx, sparseness=10, k=50)

np.save('path.npy', path)

#Plot computed path
plt.figure(figsize=(16, 9))
plt.scatter(poses[:, 1], poses[:, 0], s=1)
plt.scatter(poses[path, 1], poses[path, 0], c='y', s=20)
plt.scatter(poses[start_idx, 1],
            poses[start_idx, 0],
Ejemplo n.º 31
0
# -*- coding: utf-8 -*-
"""
Created on Mon Jul  1 09:57:25 2019

@author: toprak.kesgin
"""

import random
import matplotlib.pyplot as plt
import copy
from Environment import Environment
from Astar import Astar
from State import State
import time

harita = Environment(30, 30)
harita.randomMap()
start = [2, 5]
end = [25, 29]
harita.showMap()

astar = Astar(start, end, harita, 100)
aStarYol = astar.astar()
astar.ShowMap(aStarYol)