예제 #1
0
 def aStar2Move(self):
     self.updatePercepts()
     if self.stoppingcriterion():
         return 'Explored'
     if len(self.path) > 0: # If there's a path planned
         nextMove = self.path.pop(0)
         ##print nextMove
         direction = (nextMove[0]-self.xmapposition,nextMove[1]-self.ymapposition)
         if abs(direction[0])>1 or abs(direction[1])>1:
             self.path = []
         else:
             if self.move(direction): # If can follow the plan
                 # robots, self.currentPercept = self.world.getsubmap(self)
                 # ##print robotslist
                 # if len(robots) > 0:
                 #     for relativepos,robot in robots:
                 #         self.stitchmaps(relativepos,robot)
                 return
     # If there's no plan or plan cannot be executed:
     self.path = []
     self.updateExploringTargets()
     for target in self.migfrontiers: # Orderly go through  targets until a path is made
         astar = astar2.Astar2(self.perceptmap,self.currentPercept,(self.xmapposition,self.ymapposition),target)
         path = astar.search()
         if path:
             self.path = path
             ##print path
             break;
         else:
             goal = target[1]
             for i in range(-1,2):
                 for j in range(-1,2):
                     if i!=0 or j!=0:
                         if self.perceptmap[goal[0]+i,goal[1]+j] == utils.MAPREP.EMPTY:
                             target =(target[0], (goal[0]+i,goal[1]+j))
                             break
                 else:
                     continue
                 break
             astar = astar2.Astar2(self.perceptmap,self.currentPercept,(self.xmapposition,self.ymapposition),target)
             path = astar.search()
             if path:
                 self.path = path
                 nextMove = self.path.pop(0)
                 ##print nextMove
                 direction = (nextMove[0]-self.xmapposition,nextMove[1]-self.ymapposition)
                 self.move(direction)
                 ##print path
                 break;
     if len(self.path) == 0: #no possible move for any target, move randomly
         return False
예제 #2
0
 def __init__(self, a, b, map):
     self.a = a
     self.b = b
     self.directions = ["N", "E", "S", "W"]
     self.cost = 0
     self.path, self.cost = astar.search(self.a.x, self.a.y, self.b.x,
                                         self.b.y, self.directions, map)
예제 #3
0
파일: p6.py 프로젝트: ppegusii/cs683-hw1
def part3(args):
    np.random.seed(args.seed)
    # solLength = np.zeros(args.iter)
    cityCnts = np.zeros(args.iter)
    expanded = np.zeros(args.iter)
    compTime = np.zeros(args.iter)
    cityCnt = args.cities
    for i in xrange(args.iter):
        if args.random:
            cityCnt = np.random.randint(1, high=args.cities+1)
        print('i: {}'.format(i))
        print('cityCnt: {}'.format(cityCnt))
        visitedList = [0]
        # G = pd.DataFrame(np.random.rand(cityCnt, 2), columns=['x', 'y'])
        G = generateProblem(cityCnt)
        # print(G)
        cost = 0
        t = TspNode(visitedList, G, cost, H[args.heuristic])
        start = dt.datetime.now()
        path, e = astar.search(t)
        # print('solution path: {}'.format(path))
        compTime[i] = (dt.datetime.now()-start).total_seconds()
        print('compTime: {}'.format(compTime[i]))
        # solLength[i] = path.shape[0]
        expanded[i] = e
        cityCnts[i] = cityCnt
        G = None
        t = None
        gc.collect()
    # print('solLength: {}'.format(solLength))
    print('cityCnts: {}'.format(cityCnts))
    print('expanded: {}'.format(expanded))
    print('compTime: {}'.format(compTime))
    plot(args.heuristic, cityCnts, args.random, expanded, compTime, args.cities,
         args.iter, args.seed, args.dir)
예제 #4
0
 def goTo(self, endy, endx):
     if(int(map[int(endy)][int(endx)])>0):
         agentPositionx = self.rect.x / self.size
         agentPositiony = self.rect.y / self.size
         self.actions, distance = astar.search(
             agentPositionx, agentPositiony, endx, endy, self.directions, map)
         #print("distance: ", distance)
     else:
         self.actions = []
예제 #5
0
async def agv_work(uid: int,
                   port: Port,
                   position: tuple,
                   targets: list,
                   speed=1,
                   load_duration=3):
    current_position = position
    for target in targets:
        road = np.copy(port.road)
        road[target[0]][target[1]] = 0
        path = astar.search(road, current_position, target)
        if path is None:
            raise Exception("AGV %s deadlock" % uid)
        port.assigned_paths[uid] = path
        print("(%.3f) AGV %s current position %s, next target is %s" %
              (time.time(), uid, current_position, target))
        i = 0
        while current_position != target:
            if not port.check_conflict([current_position, path[i + 1]]):
                i += 1
                async with port.cell_lock[path[i][0]][path[i][1]]:
                    port.road[path[i][0]][path[i][1]] = uid
                    port.display(uid)
                    await asyncio.sleep(
                        astar.dist_func(path[i], path[i - 1]) / speed)
                    port.road[path[i - 1][0]][path[i - 1][1]] = 0
                    port.display(uid)
                    current_position = path[i]
            else:
                print("(%.3f) AGV %s path conflict, recalculating" %
                      (time.time(), uid))
                road = np.copy(port.road)
                road[target[0]][target[1]] = 0
                change_path = astar.search(road, current_position, target)
                if change_path is None:
                    raise Exception("AGV %s deadlock" % uid)
                path[i:] = change_path
                port.assigned_paths[uid] = path
        print("(%.3f) AGV %s shifting container" % (time.time(), uid))
        await asyncio.sleep(load_duration)
예제 #6
0
파일: robot.py 프로젝트: noskill/maze
 def on_map_change():
     initial = ((0, 0), ((1, 0), (0,1)))
     is_goal = lambda ((x, y), ori): self.is_goal(x, y)
     #heuristic = lambda (pos, ori): sum(numpy.abs(np.asarray(pos) - self.pos)) / 3.0
     heuristic = lambda (pos, ori): self.map[pos] / 3.0
     actions_with_turn = lambda (pos, ori): self.possible_actions(pos, ori, rotate_and_move=True)
     self.path = astar.search(initial, is_goal, heuristic, actions_with_turn)
     logger.info("New path: ", self.path)
     self.to_explore = []
     for item in self.path:
         pos = item[1][0]
         if not(pos in self.visited or pos in self.to_explore):
             self.to_explore.append(pos)
예제 #7
0
def test_multi():
    vault = MultiVault.from_lines(
        textwrap.dedent("""\
        #######
        #a.#Cd#
        ##...##
        ##.@.##
        ##...##
        #cB#Ab#
        #######
        """).splitlines())
    walked = search(MultiSearchState(vault), log=1)
    assert walked == 8
예제 #8
0
def key_Astar(event, data):
    if (event.keysym == "s"):
        data.start = data.selectedCell
    elif (event.keysym == "e"):
        data.end = data.selectedCell
    elif (event.keysym == "space"):
        data.path, data.gridInfo = astar.search(data.grid, data.start,
                                                data.end)
        # data.path, data.gridInfo = astar.searchWithHeading(data.grid, data.start, data.end, 3 * pi / 2)
    elif (event.keysym == "Tab"):
        data.gridInfo = []
    elif (event.keysym == "c"):
        data.grid = createArray(False, data.gridWidth, data.gridHeight)
예제 #9
0
파일: robot.py 프로젝트: noskill/maze
 def on_map_change():
     initial = ((0, 0), ((1, 0), (0, 1)))
     is_goal = lambda ((x, y), ori): self.is_goal(x, y)
     #heuristic = lambda (pos, ori): sum(numpy.abs(np.asarray(pos) - self.pos)) / 3.0
     heuristic = lambda (pos, ori): self.map[pos] / 3.0
     actions_with_turn = lambda (pos, ori): self.possible_actions(
         pos, ori, rotate_and_move=True)
     self.path = astar.search(initial, is_goal, heuristic,
                              actions_with_turn)
     logger.info("New path: ", self.path)
     self.to_explore = []
     for item in self.path:
         pos = item[1][0]
         if not (pos in self.visited or pos in self.to_explore):
             self.to_explore.append(pos)
예제 #10
0
def test_multi2():
    vault = MultiVault.from_lines(
        textwrap.dedent("""\
        #############
        #g#f.D#..h#l#
        #F###e#E###.#
        #dCba...BcIJ#
        #####.@.#####
        #nK.L...G...#
        #M###N#H###.#
        #o#m..#i#jk.#
        #############
        """).splitlines())
    walked = search(MultiSearchState(vault), log=1)
    assert walked == 72
예제 #11
0
def solve_maze(method='bfs'):
    mazes = fmazereader.read_mazes()
    for m in mazes:
        if m is None:
            continue
        print("Original : ",'\n',m)
        start, goal = mazeutils.scan(m)
        graph = mazeutils.convert_maze_to_graph(m)
        path_bfs = bfs.bfs(graph,start,goal)
        solved_bfs = mazeutils.mark_path(m, path_bfs)
        path_astar = astar.search(graph,start,goal,1)
        solved_astar = mazeutils.mark_path(m, path_astar)
        for x in range(3):
            print('\n')
        print("Solved using Breadth-First-Search : ",'\n',solved_bfs)
        print("\n\nSolved using A* algorithm :",'\n', solved_astar)
예제 #12
0
파일: robot.py 프로젝트: noskill/maze
    def explore_run(self, sensors):
        """
        Explore potentially optimal paths from start position to the goal
        using a-star algorithm
        """
        self.process_sensors(sensors)

        def on_map_change():
            initial = ((0, 0), ((1, 0), (0, 1)))
            is_goal = lambda ((x, y), ori): self.is_goal(x, y)
            #heuristic = lambda (pos, ori): sum(numpy.abs(np.asarray(pos) - self.pos)) / 3.0
            heuristic = lambda (pos, ori): self.map[pos] / 3.0
            actions_with_turn = lambda (pos, ori): self.possible_actions(
                pos, ori, rotate_and_move=True)
            self.path = astar.search(initial, is_goal, heuristic,
                                     actions_with_turn)
            logger.info("New path: ", self.path)
            self.to_explore = []
            for item in self.path:
                pos = item[1][0]
                if not (pos in self.visited or pos in self.to_explore):
                    self.to_explore.append(pos)

        if self.path is None:
            on_map_change()
        self.call_on_map_change = on_map_change
        logger.info("To explore: ", self.to_explore)
        logger.info("Pos: ", self.pos)

        if len(self.to_explore) and all(self.pos == self.to_explore[-1]):
            self.to_explore.pop(-1)

        if len(self.to_explore) == 0:
            self.run += 1
            self.reset()
            return 'Reset', 'Reset'

        next_point = self.to_explore[-1]
        initial = tuplify(self.pos), tuplify(self.ori)
        is_goal = lambda (
            (x, y), ori), target=next_point: x == target[0] and y == target[1]
        heuristic = lambda (pos, ori): sum(
            numpy.abs(np.asarray(pos) - self.pos)) / 3.0
        actions = lambda (pos, ori): self.possible_actions(pos, ori)
        path = astar.search(initial, is_goal, heuristic, actions)
        return path[-1][0]
예제 #13
0
파일: robot.py 프로젝트: noskill/maze
    def explore_run(self, sensors):
        """
        Explore potentially optimal paths from start position to the goal
        using a-star algorithm
        """
        self.process_sensors(sensors)
        def on_map_change():
            initial = ((0, 0), ((1, 0), (0,1)))
            is_goal = lambda ((x, y), ori): self.is_goal(x, y)
            #heuristic = lambda (pos, ori): sum(numpy.abs(np.asarray(pos) - self.pos)) / 3.0
            heuristic = lambda (pos, ori): self.map[pos] / 3.0
            actions_with_turn = lambda (pos, ori): self.possible_actions(pos, ori, rotate_and_move=True)
            self.path = astar.search(initial, is_goal, heuristic, actions_with_turn)
            logger.info("New path: ", self.path)
            self.to_explore = []
            for item in self.path:
                pos = item[1][0]
                if not(pos in self.visited or pos in self.to_explore):
                    self.to_explore.append(pos)
        if self.path is None:
            on_map_change()
        self.call_on_map_change = on_map_change
        logger.info("To explore: ", self.to_explore)
        logger.info("Pos: ", self.pos)

        if len(self.to_explore) and all(self.pos == self.to_explore[-1]):
            self.to_explore.pop(-1)

        if len(self.to_explore) == 0:
            self.run += 1
            self.reset()
            return 'Reset', 'Reset'

        next_point = self.to_explore[-1]
        initial = tuplify(self.pos), tuplify(self.ori)
        is_goal = lambda ((x, y), ori), target=next_point: x == target[0] and y == target[1]
        heuristic = lambda (pos, ori): sum(numpy.abs(np.asarray(pos) - self.pos)) / 3.0
        actions = lambda (pos, ori): self.possible_actions(pos, ori)
        path = astar.search(initial, is_goal, heuristic, actions)
        return path[-1][0]
예제 #14
0
파일: p6.py 프로젝트: ppegusii/cs683-hw1
def part6(args):
    np.random.seed(args.seed)
    cityCnts = np.zeros(args.iter)
    compTimeA = np.zeros(args.iter)
    compTimeL = np.zeros(args.iter)
    tourLengthA = np.zeros(args.iter)
    tourLengthL = np.zeros(args.iter)
    cityCnt = args.cities
    for i in xrange(args.iter):
        if args.random:
            cityCnt = np.random.randint(1, high=args.cities+1)
        print('i: {}'.format(i))
        print('cityCnt: {}'.format(cityCnt))
        visitedList = [0]
        G = generateProblem(cityCnt)
        d = spd.squareform(spd.pdist(G.values))
        cost = 0
        t = TspNode(visitedList, G, cost, H[args.heuristic])
        start = dt.datetime.now()
        path, e = astar.search(t)
        path = path.index
        compTimeA[i] = (dt.datetime.now()-start).total_seconds()
        tourLengthA[i] = sum([d[path[i], path[i+1]]
                              for i in xrange(len(path)-1)])
        start = dt.datetime.now()
        path = localSearch(G)
        compTimeL[i] = (dt.datetime.now()-start).total_seconds()
        tourLengthL[i] = sum([d[path[i], path[i+1]]
                              for i in xrange(len(path)-1)])
        cityCnts[i] = cityCnt
        G = None
        t = None
        gc.collect()
    plotLocal(args.heuristic, cityCnts, args.random, compTimeA, compTimeL,
              tourLengthA, tourLengthL, args.cities, args.iter, args.seed,
              args.dir)
예제 #15
0
def shortest_path(lines, log=None):
    vault = Vault.from_lines(lines)
    walked = search(SearchState(vault), log=log)
    return walked
예제 #16
0
def test_search():
    test_cave = Cave(510, 10, 10)
    time = search(CaveState(test_cave), log=1)
    assert time == 45
예제 #17
0
        return (
            f"at {(self.x, self.y)} with {self.tool}, "
            f"cave has {len(self.cave.regions):,d} regions"
            )

    def next_states(self, cost):
        # Maybe we can move, takes 1 minute
        for nx, ny in neighbors(self.x, self.y):
            there = self.cave.risk_level(nx, ny)
            if is_valid_tool(self.tool, there):
                nstate = self.__class__(self.cave, nx, ny, self.tool)
                yield nstate, cost + MOVE_COST

        # Maybe we can change our tool, takes 7 minutes
        for tool in TOOLS:
            if tool != self.tool:
                here = self.cave.risk_level(self.x, self.y)
                if is_valid_tool(tool, here):
                    nstate = self.__class__(self.cave, self.x, self.y, tool)
                    yield nstate, cost + TOOL_COST

def test_search():
    test_cave = Cave(510, 10, 10)
    time = search(CaveState(test_cave), log=1)
    assert time == 45

if __name__ == "__main__":
    cave = Cave(4080, 14, 785)
    time = search(CaveState(cave), log=.1)
    print(f"Part 2: fewest minutes to reach target is {time}")
예제 #18
0
fin = Crafting.Goal()

maximums, max_consumes, max_produces = Crafting.Maximums(init, fin)

start = make_initial_state(init)
end = make_initial_state(fin)
is_goal = make_goal_checker(fin)

full_path = []
total_cost = 0

# Create subgoals for the planner to search
# First goal, get all necessary tools
if file_name == "crafting.json":
    is_goal = make_tool_goal_checker(fin)
    cost, path = astar.search(Crafting.Graph(), start, is_goal, 1000,
                              make_RIKLS_heuristic(init, fin))
    full_path.extend(path)
    total_cost += cost
    start = astar.end_state

    # Look for one item at a time
    subgoal = Counter()
    for item in fin:
        amount = fin[item]
        chunk = max_produces[item]
        while amount > 0:
            subgoal[item] += chunk
            print "Searching for subgoal: ", subgoal
            is_goal = make_goal_checker(subgoal)
            cost, path = astar.search(Crafting.Graph(), start, is_goal, 1000,
                                      make_RIKLS_heuristic(init, subgoal))
예제 #19
0
import astar

t_initial = 'a'
t_limit = 20
edges = {'a': {'b':1, 'c':10}, 'b':{'c':1}}

def t_graph(state):
	for next_state, cost in edges[state].items():
		yield ((state, next_state), next_state, cost)

def t_is_goal(state):
	return state == 'c'

def null_heuristic(state):
	return 0

print astar.search(t_graph, t_initial, t_is_goal, null_heuristic)
예제 #20
0
import astar

t_initial = 'a'
t_limit = 20
edges = {'a': {'b': 1, 'c': 10}, 'b': {'c': 1}}


def t_graph(state):
    for next_state, cost in edges[state].items():
        yield ((state, next_state), next_state, cost)


def t_is_goal(state):
    return state == 'c'


def null_heuristic(state):
    return 0


print astar.search(t_graph, t_initial, t_is_goal, null_heuristic)
예제 #21
0
    def loop(self):
        self.screen.fill(Drawer.GRAY)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.done = True
                break
            elif event.type == pygame.MOUSEBUTTONDOWN:
                self.mouseDown = True
                gridX, gridY = self.getCellIndex()

                # set the brush mode to the opposite of the selected cell
                self.brushMode = not self.grid[gridY, gridX, 0]
            elif event.type == pygame.MOUSEBUTTONUP:
                self.mouseDown = False

            elif event.type == pygame.MOUSEMOTION:
                self.offset = list(self.getCellIndex())
                self.offset[0] -= self.window[0] / 2
                self.offset[1] -= self.window[1] / 2

                if self.offset[0] + self.window[0] >= self.gridWidth:
                    self.offset[0] = self.gridWidth - self.window[0]
                if self.offset[1] + self.window[1] >= self.gridHeight:
                    self.offset[1] = self.gridHeight - self.window[1]

                if self.offset[0] < 0:
                    self.offset[0] = 0
                if self.offset[1] < 0:
                    self.offset[1] = 0
                self.updateVisible()

            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    if len(self.waypoints) == 0:
                        self.path, self.gridInfo, plotTime = astar.search(
                            self.grid, self.start,
                            self.end)  # find a path between the start and end
                    else:
                        self.path, self.gridInfo, plotTime = astar.searchWaypoints(
                            self.grid,
                            [self.start] + self.waypoints + [self.end]
                        )  # find a path between the start, waypoints, and the end

                    print "a* time:", plotTime

                # change the brush size (only squares)
                elif event.key == pygame.K_EQUALS:
                    self.brushSize += 1
                    print(self.brushSize)

                elif event.key == pygame.K_MINUS:
                    self.brushSize -= 1
                    if self.brushSize < 1:
                        self.brushSize = 1
                    print(self.brushSize)

                # if key is a numbered key, change brush size to that key
                elif 0 <= event.key - ord('0') <= 9:
                    self.brushSize = int(event.key - ord('0'))
                    if self.brushSize < 1:
                        self.brushSize = 1
                    print(self.brushSize)

                # set start position to the position of the mouse
                elif event.key == pygame.K_s:
                    self.start = self.getCellIndex()
                    self.grid[self.start[1], self.start[0], 0] = 0

                # set end position to the position of the mouse
                elif event.key == pygame.K_e:
                    self.end = self.getCellIndex()
                    self.grid[self.end[1], self.end[0], 0] = 0

                elif event.key == pygame.K_ESCAPE or event.key == pygame.K_q:
                    self.done = True
                    break

                # change the visible window by self.delOffset depending on the direction of arrow keys
                # elif pygame.K_UP <= event.key <= pygame.K_LEFT:
                #     if event.key == pygame.K_UP:
                #         self.offset[1] -= self.delOffset[1]
                #         if self.offset[1] < 0:
                #             self.offset[1] = 0
                #     elif event.key == pygame.K_DOWN:
                #         self.offset[1] += self.delOffset[1]
                #         if self.offset[1] + self.window[1] >= self.gridHeight:
                #             self.offset[1] = self.gridHeight - self.window[1]
                #     elif event.key == pygame.K_LEFT:
                #         self.offset[0] -= self.delOffset[0]
                #         if self.offset[0] < 0:
                #             self.offset[0] = 0
                #     elif event.key == pygame.K_RIGHT:
                #         self.offset[0] += self.delOffset[0]
                #         if self.offset[0] + self.window[0] >= self.gridWidth:
                #             self.offset[0] = self.gridWidth - self.window[0]
                #     self.updateVisible()

                # Fill the entire grid
                elif event.key == pygame.K_f:
                    self.grid = numpy.ones(
                        (self.gridHeight, self.gridWidth, 2))
                    self.grid[:, :, 1] = 0
                    self.grid[self.start[1], self.start[0], 0] = 0
                    self.grid[self.end[1], self.end[0], 0] = 0
                    self.updateVisible()

                # reveal the entire grid
                elif event.key == pygame.K_TAB:
                    self.showFull = True

                # reset grid to initial state
                elif event.key == pygame.K_c:
                    self.grid = numpy.zeros(
                        (self.gridHeight, self.gridWidth, 2))
                    self.path = []
                    self.waypoints = []
                    self.gridInfo = {}
                    self.updateVisible()

                # add a waypoint to current mouse position
                elif event.key == pygame.K_w:
                    cellX, cellY = self.getCellIndex()
                    self.waypoints.append((cellX, cellY))

                # delete waypoint nearest to mouse
                elif event.key == 8:  # delete key
                    cellX, cellY = self.getCellIndex()
                    closestPoint = 0
                    shorestDist = None

                    for index, (wpY, wpX) in enumerate(self.waypoints):
                        distance = Drawer.pythagoreanDist(
                            wpX, wpY, cellX, cellY)
                        if distance < shorestDist or shorestDist is None:
                            shorestDist = distance
                            closestPoint = index

                    print self.waypoints.pop(closestPoint)

                # save map data to text file or load map data from text file if map is empty
                elif event.key == pygame.K_RETURN:
                    if numpy.all(self.grid[:, :, 0] == 0):
                        self.grid, self.start, self.end = mapmaker.read()
                        self.initGridDisplay(self.grid.shape[1],
                                             self.grid.shape[0])
                        self.updateVisible()
                    else:
                        mapmaker.write(self.grid, self.start, self.end)

                elif pygame.K_i <= event.key <= pygame.K_l:
                    if event.key == pygame.K_i:
                        self.particleAccel[1] -= 1
                    elif event.key == pygame.K_j:
                        self.particleAccel[0] -= 1
                    elif event.key == pygame.K_k:
                        self.particleAccel[1] += 1
                    elif event.key == pygame.K_l:
                        self.particleAccel[0] += 1

            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_TAB:
                    self.showFull = False

            if self.mouseDown == True:
                clickedX, clickedY = self.getCellIndex()
                radius = int(round(float(self.brushSize) / 2))
                for gridY in xrange(
                        max(clickedY - radius + self.brushSize % 2, 0),
                        min(clickedY + radius, self.gridHeight)):
                    for gridX in xrange(
                            max(clickedX - radius + self.brushSize % 2, 0),
                            min(clickedX + radius, self.gridWidth)):
                        self.grid[gridY, gridX, 0] = self.brushMode

                self.updateVisible()

        for (cellY, cellX), element in self.enumerateGrid():
            if self.showFull == False:
                cellX += self.offset[0]
                cellY += self.offset[1]
            color = Drawer.WHITE
            if element == 1:
                color = Drawer.GREEN

            self.drawCell(cellX, cellY, color)

        self.drawCell(self.start[0], self.start[1], Drawer.RED)
        self.drawCell(self.end[0], self.end[1], Drawer.BLUE)

        for (cellX, cellY) in self.waypoints:
            self.drawCell(cellX, cellY, Drawer.BLACK)

        for (cellY, cellX), element in self.enumerateGrid():
            if self.showFull == False:
                cellX += self.offset[0]
                cellY += self.offset[1]
            if len(self.gridInfo) > 0:
                parent = self.gridInfo[(cellX, cellY)].parent
                if parent is not None:
                    self.connectCells(cellX, cellY, parent[0], parent[1],
                                      Drawer.RED, 1)
        for index in xrange(1, len(self.path)):
            self.connectCells(self.path[index - 1][0], self.path[index - 1][1],
                              self.path[index][0], self.path[index][1])
        for (x, y) in zip(self.bezierXvals, self.bezierYvals):
            self.screen.fill(Drawer.BLUE,
                             ((self.cellSize * (x + 0.5), self.cellSize *
                               (y + 0.5)), (1, 1)))

        pygame.draw.rect(self.screen, Drawer.BLACK, [
            0, 0, self.cellSize * self.gridWidth,
            self.cellSize * self.gridHeight
        ], 1)
예제 #22
0
if __name__ == "__main__":
    import astar
    import draw
    from matplotlib import pyplot as plt

    grid, start, end = mapmaker.make(30, 30), (0, 0), (5, 5)
    height, width = grid.shape[0:2]

    drawer = draw.Drawer(width, height, 700, 700, start, end, grid)

    while drawer.done == False:
        drawer.loop()
        drawer.update()
    drawer.deinit()
    path, pathInfo, plotTime = astar.search(grid, start, end)

    points = path[:5]

    xpoints = [p[0] for p in points]
    ypoints = [p[1] for p in points]

    xvals, yvals = bezier_curve(points, nTimes=1000)
    print(xvals, yvals)

    plt.plot(xvals, yvals)
    plt.plot(xpoints, ypoints, "ro")
    for nr in range(len(points)):
        plt.text(points[nr][0], points[nr][1], nr)

    plt.show()
예제 #23
0
def plot(binSize, thresholdPct, start, end):
    shape = gp.read_file('Assignment1/crime_dt.shp')
    bounds = shape.total_bounds
    [xmin, ymin, xmax, ymax] = bounds
    dim = int(np.ceil((xmax - xmin) / binSize))
    X = []
    Y = []
    bins = [dim, dim]

    for point in shape.geometry:
        X.append(point.x)
        Y.append(point.y)

    hist = plt.hist2d(X, Y, bins)
    val = hist[0]
    xE = hist[1]
    yE = hist[2]

    thres = getThreshold(thresholdPct, sorted(hist[0].flatten()))
    cmap, norm = getCmap(thres)

    hist = plt.hist2d(X, Y, bins, cmap=cmap, norm=norm)

    #converting bins to points on bottom left
    xedges = hist[1]
    yedges = hist[2]
    nx = len(xedges)
    ny = len(yedges)
    start_x = xmin
    start_y = ymin
    coords1d = []
    coords2d = np.empty((nx, ny), dtype=object)
    for i in range(0, nx):
        current_x = xedges[i]
        for j in range(0, ny):
            current_y = yedges[j]
            coords1d.append((current_x, current_y))
            coords2d[i][j] = (current_x, current_y)

    #adding values on the plot
    for (x, xi) in zip(xE, range(0, len(xE) - 1)):
        for (y, yi) in zip(yE, range(0, len(yE) - 1)):
            ax = plt.gca()
            ax.text(x + binSize / 2,
                    y + binSize / 2,
                    str(val[xi][yi]),
                    fontdict=dict(fontsize=5, ha='center', va='center'))

    ax = plt.gca()
    ax.set_title(
        f'Threshold_pct: {thresholdPct} Threshold_val: {thres} '.format(
            thres, thresholdPct))

    path = search(hist, start, end, thres)
    path_as_points = [coords2d[xi][yi] for (xi, yi) in path]

    plt.plot([p[0] for p in path_as_points], [p[1] for p in path_as_points],
             color='white')
    plt.hist2d(X, Y, bins, cmap=cmap, norm=norm)

    plt.show()
예제 #24
0
파일: p5.py 프로젝트: jtsommers/craftly
fin = Crafting.Goal()

maximums, max_consumes, max_produces = Crafting.Maximums(init, fin)

start = make_initial_state(init)
end = make_initial_state(fin)
is_goal = make_goal_checker(fin)

full_path = []
total_cost = 0

# Create subgoals for the planner to search
# First goal, get all necessary tools
if file_name == "crafting.json":
	is_goal = make_tool_goal_checker(fin)
	cost, path = astar.search(Crafting.Graph(), start, is_goal, 1000, make_RIKLS_heuristic(init, fin))
	full_path.extend(path)
	total_cost += cost
	start = astar.end_state

	# Look for one item at a time
	subgoal = Counter()
	for item in fin:
		amount = fin[item]
		chunk = max_produces[item]
		while amount > 0:
			subgoal[item] += chunk
			print "Searching for subgoal: ", subgoal
			is_goal = make_goal_checker(subgoal)
			cost, path = astar.search(Crafting.Graph(), start, is_goal, 1000, make_RIKLS_heuristic(init, subgoal))
			if cost > 1000:
예제 #25
0
파일: p5.py 프로젝트: ppegusii/cs683-hw1
def main():
    args = parseArgs(sys.argv)
    # print(args)
    '''
    k = KnightNode(np.array([1, 1]), None, np.array([3, 2]))
    for s in k.successors():
        print('s.xy: {}'.format(s.xy))
        print('s.sXy: {}'.format(s.sXy))
        print('s.isGoal(): {}\n'.format(s.isGoal()))
    print('Solution: {}'.format(astar.search(k)))
    k = KnightNode(np.array([-3, 3]), None, np.array([-1, 1]))
    print('Solution: {}'.format(astar.search(k)))
    e = np.array([1, 1])
    k = KnightNode(np.array([0, 0]), None, e)
    print('{} solution: {}'.format(e, astar.search(k)))
    e = np.array([0, 1])
    k = KnightNode(np.array([0, 0]), None, e)
    print('{} solution: {}'.format(e, astar.search(k)))
    e = np.array([0, 2])
    k = KnightNode(np.array([0, 0]), None, e)
    print('{} solution: {}'.format(e, astar.search(k)))
    e = np.array([2, 2])
    k = KnightNode(np.array([0, 0]), None, e)
    print('{} solution: {}'.format(e, astar.search(k)))
    e = np.array([3, 1])
    k = KnightNode(np.array([0, 0]), None, e)
    print('{} solution: {}'.format(e, astar.search(k)))
    e = np.array([3, 3])
    k = KnightNode(np.array([0, 0]), None, e)
    print('{} solution: {}'.format(e, astar.search(k)))
    e = np.array([10, 9])
    k = KnightNode(np.array([0, 0]), None, e)
    print('{} solution: {}'.format(e, astar.search(k)))
    '''

    '''
    e = np.array([3, 0])
    k = KnightNode(np.array([0, 0]), None, e, H[0])
    print('{} solution: {}'.format(e, astar.search(k)))
    e = np.array([3, 2])
    k = KnightNode(np.array([0, 0]), None, e, H[0])
    print('{} solution: {}'.format(e, astar.search(k)))
    sys.exit(0)
    '''

    random.seed(args.seed)
    solLength = np.zeros(args.iter)
    expanded = np.zeros(args.iter)
    compTime = np.zeros(args.iter)
    for i in xrange(args.iter):
        goal = np.array(
            [
                random.randrange(args.max*-1, args.max+1, 1),
                random.randrange(args.max*-1, args.max+1, 1),
            ]
        )
        k = KnightNode(np.array([0, 0]), None, None, goal, H[args.heuristic])
        print(goal)
        start = dt.datetime.now()
        path, e = astar.search(k)
        compTime[i] = (dt.datetime.now()-start).total_seconds()
        solLength[i] = path.shape[0]
        expanded[i] = e
        k = None
        gc.collect()
    print('solLength: {}'.format(solLength))
    print('expanded: {}'.format(expanded))
    print('compTime: {}'.format(compTime))
    plot(args.heuristic, solLength, expanded, compTime, args.max, args.iter,
         args.seed, args.dir)
예제 #26
0
        ##...##
        #cB#Ab#
        #######
        """).splitlines())
    walked = search(MultiSearchState(vault), log=1)
    assert walked == 8


def test_multi2():
    vault = MultiVault.from_lines(
        textwrap.dedent("""\
        #############
        #g#f.D#..h#l#
        #F###e#E###.#
        #dCba...BcIJ#
        #####.@.#####
        #nK.L...G...#
        #M###N#H###.#
        #o#m..#i#jk.#
        #############
        """).splitlines())
    walked = search(MultiSearchState(vault), log=1)
    assert walked == 72


if __name__ == "__main__" and "2" in sys.argv:
    with open("day18_input.txt") as f:
        vault = MultiVault.from_lines(f)
    walked = search(MultiSearchState(vault), debug=True)
    print(f"Part 2: the shortest path is {walked}")