示例#1
0
def solve():
    """
        Solve the puzzle by getting the required parameters from the request args.
    """
    algorithm = request.args['algorithm']
    arr = list(map(int, request.args['input[]'][1:-1].split(',')))
    print(algorithm)
    agent = None
    if algorithm == "BFS":
        agent = BFS()
    elif algorithm == "DFS":
        agent = DFS()
    elif algorithm == "A start (Euclidean)":
        agent = AStar(Euclidean)
    elif algorithm == "A start (Manhatten)":
        agent = AStar(Manhatten)
    else:
        return arr

    start = timeit.default_timer()
    res = agent.search(arr)
    end = timeit.default_timer()

    res['time'] = end - start

    ret = jsonify(res)
    return ret
示例#2
0
    def __init__(self, number, initState, goalState, wallStates, game):
        """

        :param number: int
                    number of the player in the players list
        :param initState: list
                    the initial position of the player
        :param goalState: list
                    the goal position of the player
        :param wallStates: list of lists
                    the walls position
        :param game: game object
                    the game (the map with all informations like the walls...)

        """

        self.initState = initState
        self.goalState = goalState
        self.number = number
        self.game = game
        self.index = 1
        self.astar = AStar(initState, goalState, wallStates,
                           game.spriteBuilder.rowsize,
                           game.spriteBuilder.colsize)
        self.path = (self.astar.run()).trace()
        self.move = True
        self.walls = wallStates
        self.astarForTrueDist = AStar(goalState, initState, wallStates,
                                      game.spriteBuilder.rowsize,
                                      game.spriteBuilder.colsize)
示例#3
0
def main():
    row, column = list(map(int, input().split()))
    table = Table(row, column)
    table.parseInput()

    # for test:
    # for i in range(row):
    #     for j in range(column):
    #         print(table.matrix[i][j], end=" ")
    #     print()
    # print(table.xyRobot)
    # print(table.xyButters)
    # print(table.xyPersons)
    # print(table.matrix)

    # bbfs
    bbfs = BidirectionalBFS(table)
    startT = time.time()
    bbfs.calcPathAndCost()
    endT = time.time()

    if not bbfs.path:
        print("Can't pass the butter")
    else:
        print("path:   ", bbfs.path)
        print("cost:   ", bbfs.cost)
        print("depthForward:  ", bbfs.forwardLastNode.depth)
        print("depthBackward: ", len(bbfs.path2))
        print("sum of depth: ", len(bbfs.path))

    print("Execution time in seconds: ", endT - startT)
    print("Expanded Nodes: ", bbfs.numVisitedNodes)
    print("Generated Nodes: ", bbfs.numAllNodes)
    # #Draw
    # draw = DrawBoard(table, bbfs.path)
    # draw.draw()

    # aStar
    aStar = AStar(table)

    startT = time.time()
    aStar.calcPathAndCost()
    endT = time.time()

    if not aStar.path:
        print("Can't pass the butter")
    else:
        print("path:   ", aStar.path)
        print("cost:   ", aStar.cost)
        print("depth: ", aStar.lastNode.depth)

    print("Execution time in seconds: ", endT - startT)
    print("Expanded Nodes: ", aStar.numVisitedNodes)
    print("Generated Nodes: ", aStar.numAllNodes)
示例#4
0
    def run_tests(self):

        file = open(self.file, "w")

        inc = 1
        a = AStar()
        for i in range(5):
            time = a.run(i * inc)
            print str(i * inc) + " " + str(time)
            file.write(str(i * inc) + " " + str(time) + "\n")

        file.close()
示例#5
0
文件: router.py 项目: 4sp1r3/monad
 def __init__(self, omsfilepath):
     self.omsfile = omsfilepath
     self.astar = AStar(standardSpeed)
     self.handler = RouteHandler()
     self.nodes = {}
     self.busStopList = []
     self.edges = {}
     self.roadNodes = []
 def findPath(self, start, goal) :
     """ start : (float,float), goal : (float,float,float) or (float,float)
         uses the AStar class to find the shortest path between 'start' and 'goal'
         then simplifies the path to obtain straight lines as long as possible
     """
     if len(goal) == 2 :
         goal = goal + (0,)  # default value of 'goalRadius' is 0
     a = AStar(start, goal, self.thresholdMap)
     print "Résultat de A*: " + str(a.aStar())
     p = a.buildPath()
     if p == None :
         self.path == None
     else :
         l = len(p)
         current = l-1
         self.path = [p[current]]
         while current > 0:
             i = 0
             while i+1 < current and not self.isLineClear(p[current], p[i]) :
                 i += 1
             current = i
             self.path.insert(0,p[current])
示例#7
0
 def findPath(self, start, goal):
     """ start : (float,float), goal : (float,float,float) or (float,float)
         uses the AStar class to find the shortest path between 'start' and 'goal'
         then simplifies the path to obtain straight lines as long as possible
     """
     if len(goal) == 2:
         goal = goal + (0, )  # default value of 'goalRadius' is 0
     a = AStar(start, goal, self.thresholdMap)
     print "Résultat de A*: " + str(a.aStar())
     p = a.buildPath()
     if p == None:
         self.path == None
     else:
         l = len(p)
         current = l - 1
         self.path = [p[current]]
         while current > 0:
             i = 0
             while i + 1 < current and not self.isLineClear(
                     p[current], p[i]):
                 i += 1
             current = i
             self.path.insert(0, p[current])
示例#8
0
class PlayerPath:
    """

        Class that represents a player and the path that he will use to get the goal

    """
    def __init__(self, number, initState, goalState, wallStates, game):
        """

        :param number: int
                    number of the player in the players list
        :param initState: list
                    the initial position of the player
        :param goalState: list
                    the goal position of the player
        :param wallStates: list of lists
                    the walls position
        :param game: game object
                    the game (the map with all informations like the walls...)

        """

        self.initState = initState
        self.goalState = goalState
        self.number = number
        self.game = game
        self.index = 1
        self.astar = AStar(initState, goalState, wallStates,
                           game.spriteBuilder.rowsize,
                           game.spriteBuilder.colsize)
        self.path = (self.astar.run()).trace()
        self.move = True
        self.walls = wallStates
        self.astarForTrueDist = AStar(goalState, initState, wallStates,
                                      game.spriteBuilder.rowsize,
                                      game.spriteBuilder.colsize)

    def canMove(self):
        """
        tests of the player is at the goal state or not

        :return:
                False if the player is at the goal, True otherwise
        """

        if self.index == len(self.path):
            self.move = False
        return self.move

    def movee(self):
        """

        Moves a player if he can move

        :return: the next move of the player

        """

        #return the initial state if he cant move and he's in the initial state
        if not self.move and self.index == 0:
            return self.path[self.index]

        #return the goal state if he's at the goal state
        if self.index == len(self.path):
            return self.path[-1]

        #return the next move and increments the index attribute
        nextMove = self.path[self.index]
        self.index += 1

        return nextMove

    def getNext(self):
        """

        :return: the next move of the player

        """
        # if the player is at the goal state his next move will be to stay on that state
        if self.index == len(self.path):
            return self.path[-1]
        return self.path[self.index]

    def getPrevious(self):
        """

        :return: the previous move of the player or None if he's at his initial state

        """
        if self.index is 1:
            return None
        return self.path[self.index - 1]

    def removeNextMove(self):
        """

        Removes the next move of the player

        """
        self.path.remove(self.path[self.index])

    def insertNewPath(self, newPath):
        """

        add the new path in the position the index attribute

        :param newPath: list of lists
                    the new path of the player

        """

        indice = self.index
        for state in newPath:
            self.path.insert(indice, state)
            indice += 1

    def onGoal(self):
        """

        Tests if the player is at his goal

        :return:
                True if the player is at his goal, False otherwise

        """
        return self.index == len(self.path)
示例#9
0
文件: router.py 项目: 4sp1r3/monad
class Map:
    """
    The main class for the routing.

    """

    def __init__(self, omsfilepath):
        self.omsfile = omsfilepath
        self.astar = AStar(standardSpeed)
        self.handler = RouteHandler()
        self.nodes = {}
        self.busStopList = []
        self.edges = {}
        self.roadNodes = []

    def parsData(self):
        """
        Called when it is time to pars the osm map file. The map is supplied
        when initializing the class.
        """
        self.handler = RouteHandler()
        parser = make_parser()
        parser.setContentHandler(self.handler)
        parser.parse(self.omsfile)
        self.handler.nodes = None

        self.busStopList = self.handler.busStops
        self.edges = self.handler.roadMapGraph

    def checkCoordinateList(self, coordinatesList):
        """

        :param coordinatesList: [(longitude, latitude)]
        :return:
        """

        for idx, coordinates in enumerate(coordinatesList):
            if not self.inEdgeList(coordinates):
                coordinatesList[idx] = self.closestRoadCoordinate(coordinates)

        return coordinatesList

    def closestRoadCoordinate(self, coordinates):
        """

        :param coordinates:
        :return:
        """
        coordinates = coordinate.closestTo(coordinates, self.handler.roadMapGraph.keys())

        return coordinates

    def findBusStopName(self, lon, lat):
        """

        :param lon:
        :param lat:
        :return:
        """
        for nd in self.busStopList:
            if nd.longitude == lon and nd.latitude == lat:
                return nd.name
        return None

    def findBusStopPosition(self, name):
        """

        :param name:
        :return:
        """
        name = name.decode('utf-8').lower()
        for nd in self.busStopList:
            if nd.name.lower() == name:
                return nd.coordinates
        return None

    def findClosestBusStopFromCoordinates(self, lon, lat):
        """
        Finds the closest bus stop to the position of (lon, lat).

        :param lon: longitude
        :param lat: latitude
        :return: BusStop object
        """
        stop = self.busStopList[0]
        position = Coordinate(latitude=lat, longitude=lon)
        dist = coordinate.measure(stop, position)

        for _stop in self.busStopList:
            _dist = coordinate.measure(_stop, position)
            if _dist < dist:
                stop = _stop
                dist = _dist

        return stop

    def findBusStopsFromCoordinates(self, lon, lat, distance):
        """
        Find the bus stops to the position of (lon, lat) and that is in the
        radius of distance.

        :param lon: longitude float
        :param lat: latitude float
        :param distance: meters float
        :return: list of tuples [(name, coordinates, distance)]
        """

        position = Coordinate(longitude=lon, latitude=lat)
        busStops = []

        for _stop in self.busStopList:
            _dist = coordinate.measure(_stop, position)
            if _dist <= distance:
                busStops.append((_stop.name, _stop.coordinates, _dist))

        if not busStops:
            _closest = self.findClosestBusStopFromCoordinates(lon, lat)
            _cdist = coordinate.measure(_closest, position)
            busStops.append((_closest.name, _closest.coordinates, _cdist))
        return busStops

    def findCoordinatesFromAdress(self, address, number=None):
        """
        Translates an address into coordinates.
        """
        address = address.decode('utf-8').lower()
        if address in self.handler.addresses:
            if number is None:
                coordinateList = self.handler.addresses[address].coordinates
                center = coordinate.center(coordinateList)
                return center

            else:
                if number in self.handler.addresses[address].numbers:
                    noCoord = self.handler.addresses[address].numbers[number]
                    return noCoord
                else:
                    return self.findCoordinatesFromAdress(address)
        else:
            return None

    def findRoute(self, startCoord, endCoord):
        """
        Finds a route between two points in the map. Uses the A* algorithm to
        find this path.

        :param startCoord: id of the starting node
        :param endCoord: id of the ending node
        :return: a path between the start and ending point and the to take that
                path
        """

        if not self.inEdgeList(startCoord):
            startCoord = self.closestRoadCoordinate(startCoord)

        if not self.inEdgeList(endCoord):
            print "NOOO!"

        path, cost = self.astar.findPath(self.edges, startCoord, endCoord)

        travelTime = cost[endCoord][0]
        return path, travelTime

    def findRouteFromCoordinateList(self, coordinateList):
        """
        Finds the paths path between points in a list of coordinates. The path
        through an increasing order of indexes. Index 0 is the starting point
        and N-1 is the end point where N is the length of the list.

        Coordinates are represented as a tuple with (longitude, latitude)

        :param coordinateList: [coordinates]
        :return:
        """
        # Get the node IDs of the coordinates.
        coordList = self.checkCoordinateList(coordinateList)

        path = []
        cost = [0]

        if len(coordList) == 1:
            path.append(coordList[0])
        elif len(coordList) > 1:
            path.append(coordList[0])
            for n in range(0, len(coordList) - 1):
                _path, _cost = self.findRoute(coordList[n], coordList[n + 1])
                [path.append(x) for x in _path[1:]]
                cost.append(_cost)

        return path, cost

    def findWayPoints(self, startNode, endNode):
        """
        Finds path and way points between two nodes. Used for finding the route
        between two points (nodes) in the road map. The points have to be
        located on the road.
        """
        route = self.findRoute(startNode, endNode)
        return route, self.getWayPointsFromPath(route)

    def findWayPointsFromList(self, nodeList):
        """
        Finds the path and way points between multiple points (intermediate
        points). The path will go from N to N+1. list[0] is the starting point
        the last element of the list will be the ending point.
        """
        path = []
        waypoints = []
        if len(nodeList) > 1:
            path.append(nodeList[0])
            for n in range(0, len(nodeList) - 1):
                nPath, _ = self.findRoute(nodeList[n], nodeList[n + 1])
                [path.append(x) for x in nPath[1:]]
            waypoints = self.getWayPointsFromPath(path)

        return path, waypoints

    def getWayPointsFromPath(self, path):
        """
        Given a path it will return the way points on that path.
        """
        nodeList = []
        for n in range(1, len(path) - 2):

            roadIDfrom = ([item for item in self.edges[path[n - 1]]
                           if item[0] == path[n]][0][3])
            roadIDto = ([item for item in self.edges[path[n]]
                         if item[0] == path[n + 1]][0][3])

            if roadIDfrom != roadIDto:
                nodeList.append(path[n])
        return nodeList

    def inEdgeList(self, sid):
        """

        """
        return sid in self.handler.roadMapGraph
示例#10
0
 def test_AStar_Manhatten(self):
     agent = AStar(Manhatten)
     steps = agent.search([1, 2, 5, 3, 4, 0, 6, 7, 8])
     print("Solved in {} steps".format(len(steps)))
     print(steps)