Exemplo n.º 1
0
    def runTest(self):
        self.p = 0
        while self.p < self.maxP:  # loop over p values, step up by predefined amount
            solvedMazes = 0
            for x in range(0, self.mazePerP):  # make this number of mazes
                m = maze.Maze(self.dim, self.p)
                d = dfs.Dfs(m)
                result = d.search()  # run dfs
                if (result is not None
                    ):  # add one to counter for each solved maze
                    solvedMazes += 1
            self.ploty.append(
                solvedMazes / self.mazePerP
            )  # divide number of solvable mazes by total number of mazes generated.
            self.p += self.step

        self.ploty = np.array(self.ploty)
        print(self.plotx)
        print(self.ploty)
        plt.title("Density VS. Maze solvability for graph of size " +
                  str(self.dim))
        plt.xlabel("Density")
        plt.ylabel("Solvability")
        plt.plot(self.plotx, self.ploty)  # plot using pyplot

        plt.show()
Exemplo n.º 2
0
	def runTest(self):
		self.p = 0
		while self.p < self.maxP: # loop over p values up to max
			totalPathLength = 0
			x = 0
			while x <self.mazePerP: # generate the right number of graphs per p
				m = maze.Maze(self.dim, self.p)
				a = AStarManhatten.AStarManhatten(m)
				path = a.search()
				if path is not None: # only count path if it is not none.
					totalPathLength += len(path)
					x+=1
			self.ploty.append(totalPathLength / self.mazePerP) # add the average length

			self.p += self.step

		self.ploty = np.array(self.ploty)
		print(self.plotx)
		print(self.ploty)
		plt.title("Density VS. Expected path length for graph of size " + str(self.dim))
		plt.xlabel("Density")
		plt.ylabel("Expected Path Length")
		plt.plot(self.plotx, self.ploty)  # plot using pyplot

		plt.show()
Exemplo n.º 3
0
    def runTest(self):
        i = 0
        while i < self.noMazes:
            m = maze.Maze(self.dim, self.p)
            man = AStarManhatten.AStarManhatten(m)
            resman = man.search()
            if (resman is not None):
                self.manhattenData[
                    0] = self.manhattenData[0] + man.getMaxFringe()
                self.manhattenData[
                    1] = self.manhattenData[1] + man.getNodesExplored()
                self.manhattenData[2] = self.manhattenData[2] + len(
                    resman)  # add data from the last run

                euclid = AStarEuclid.AStarEuclid(m)
                reseuclid = euclid.search()
                self.euclidData[0] = self.euclidData[0] + euclid.getMaxFringe()
                self.euclidData[
                    1] = self.euclidData[1] + euclid.getNodesExplored()
                self.euclidData[2] = self.euclidData[2] + len(
                    reseuclid)  # add data from the last run
                i += 1
        self.manhattenData = np.array(self.manhattenData)
        self.euclidData = np.array(self.euclidData)

        # Most of this bar chart code comes from here:
        #https://matplotlib.org/3.1.0/gallery/lines_bars_and_markers/barchart.html#sphx-glr-gallery-lines-bars-and-markers-barchart-py
        # it is not related to AI so I just reuse.

        ind = np.arange(len(
            self.manhattenData))  # the x locations for the groups
        width = 0.35  # the width of the bars

        fig, ax = plt.subplots()
        rects1 = ax.bar(ind - width / 2,
                        self.manhattenData,
                        width,
                        label='Manhatten')
        rects2 = ax.bar(ind + width / 2,
                        self.euclidData,
                        width,
                        label='Euclid')

        # Add some text for labels, title and custom x-axis tick labels, etc.
        ax.set_ylabel('Resource usage')
        ax.set_title('Manhatten vs Euclid')
        ax.set_xticks(ind)
        ax.set_xticklabels(('Sum max fringe size', 'Sum of all nodes explored',
                            'Sum of path length'))
        ax.legend()

        self.autolabel(ax, rects1, "left")
        self.autolabel(ax, rects2, "right")

        fig.tight_layout()

        plt.show()
Exemplo n.º 4
0
 def __init__(self, noMazes: int, dim: int):
     self.imnumber = 0
     self.dim = dim
     self.type = True  # true for bfs, false for ASTAR
     self.mazes = []
     self.noMazes = noMazes
     self.changeThreshhold = 1
     self.stopAfterBeingUnderThresholdThisManyTimes = 25
     x = 0
     while (x < noMazes):  # make our mazes to start with
         m = maze.Maze(dim, .2)
         if self.type:
             if self.rankDFS(m) != 0:
                 self.mazes.append(m)
                 x += 1
         else:
             if self.rankAstar(m) != 0:
                 self.mazes.append(m)
                 x += 1
     self.running = True
     heapq.heapify(self.mazes)
Exemplo n.º 5
0
import qOne.AStar as AStar
import qOne.AStar as AStar
import qOne.maze as maze

class AStarManhatten(AStar.AStar):
	def __init__(self, maze):
		super(AStarManhatten, self).__init__(maze)

	def heuristic(self, item:tuple) ->float:
		return abs(item[0] - self.maze.getDim()+ 1) + abs(item[1] - self.maze.getDim() +1 ) # return the dis. +1 is off by one error due to 0 indexing of arrays.

if __name__=='__main__':
	m = maze.Maze(100,0)
	A = AStarManhatten(m)
	path = A.search()
	m.print_with_temp_path(path)
Exemplo n.º 6
0
if __name__ == "__main__":

    # 100 because its sufficiently hard enough for BFS
    MAZE_SIZE = 100

    # run each algorithm on the list of mazes, get avg times
    algos_map = {
        "astareuclid": AStarEuclid.AStarEuclid,
        "astarmanhattan": AStarManhatten.AStarManhatten,
        "bfs": bfs.Bfs,
        "bibfs": bibfs.BiDirectionalBFS,
        "dfs": dfs.Dfs
    }

    # run for each maze
    m = maze.Maze(MAZE_SIZE, 0.2)

    for algo_name, algo in algos_map.items():

        a = algo(m)
        path = a.search()

        while True:
            if path is not None:
                break
            else:
                m.clear_grid()
                m.generateGrid()
                path = a.search()

        m.gen_and_save_graphs_with_temp_path(path, "bulletTwo",
Exemplo n.º 7
0
    # A = AStarEuclid.AStarEuclid(m)
    # path = A.search()
    # m.print_with_temp_path(path)

    # 100 because its sufficiently hard enough for BFS
    MAZE_SIZE = 10
    TIMES_TO_RUN_INNER_LOOP = 10

    # range of p_values
    p_values = range(1, 8, 1)

    # generate a maze for each p_val
    mazes = list()
    for p in p_values:
        cur_p = p / 20  # steps of .05, .1, .15, ..., .4
        cur_m = maze.Maze(MAZE_SIZE, cur_p)
        cur_m.generateGrid()
        mazes.append(cur_m)

    # run each algorithm on the list of mazes, get avg times

    time_algo_map = dict(astareuclid=dict(algo=AStarEuclid.AStarEuclid,
                                          times=list()),
                         astarmanhattan=dict(
                             algo=AStarManhatten.AStarManhatten, times=list()),
                         bfs=dict(algo=bfs.Bfs, times=list()),
                         bibfs=dict(algo=bibfs.BiDirectionalBFS, times=list()),
                         dfs=dict(algo=dfs.Dfs, times=list()))

    # run for each maze
    for cur_maze in mazes:
Exemplo n.º 8
0
from qOne import bibfs
from qOne import AStarManhatten
from qOne import maze

if __name__ == "__main__":
    m = maze.Maze(100, 0.2)
    astar = AStarManhatten.AStarManhatten(m)
    bdbfs = bibfs.BiDirectionalBFS(m)

    astar_path = astar.search()
    bdbfs_path = bdbfs.search()

    m.gen_and_save_graphs_with_temp_path(astar_path,
                                         fname="a.png",
                                         graph_title="AStar")
    m.gen_and_save_graphs_with_temp_path(bdbfs_path,
                                         fname="bd.png",
                                         graph_title="BiBFS")
Exemplo n.º 9
0
        # left
        if j - 1 != -1 and (grid[i][j - 1] == 0 or grid[i][j - 1]
                            == 'g') and self.prev[i][j - 1] is None:
            ret.append((i, j - 1))

        # down
        if i + 1 < len(grid) and (grid[i + 1][j] == 0 or grid[i + 1][j]
                                  == 'g') and self.prev[i + 1][j] is None:
            ret.append((i + 1, j))

        # to the right. If it is not outside of the maze, is a free spot, and has not been visited yet, we pass this check.
        if j + 1 < len(grid) and (grid[i][j + 1] == 0 or grid[i][j + 1]
                                  == 'g') and self.prev[i][j + 1] is None:
            ret.append((i, j + 1))

        # item above. If it is not outside of the maze, is a free spot, and has not been visited yet, we pass this check.
        if i - 1 != -1 and (grid[i - 1][j] == 0 or grid[i - 1][j]
                            == 'g') and self.prev[i - 1][j] is None:
            ret.append((i - 1, j))
        return ret


if __name__ == '__main__':

    m = maze.Maze(100, .2)

    d = Dfs(m)
    path = d.search()

    m.print_with_temp_path(path)
Exemplo n.º 10
0
				b = self.back_previous[b]

		f_path.reverse()
		# start b_path from 1 instead of 0 since they both contain same node
		# we could also do f_path[:-1]
		if self.single_mode:
			res = f_path
		else:
			res = f_path + b_path[1:]

		return res


if __name__ == "__main__":

	myM = maze.Maze(100, 0.1)
	doB = BiDirectionalBFS(myM, single_mode=True)
	p = doB.search()
	myM.print_with_temp_path(p)
	print(p)