def test():
    datasetfile = ['Email-Enron']#['com-dblp.ungraph', 'Email-Enron', 'facebook_combined']
    order = ['bfs', 'dfs', 'rand']
    ksize = [4,8,12]
    ba,ch,dg,ha,rg,tr=[],[],[],[],[],[]
    Edges_constant = [1049866,367662,88234]  #edges of each datasets
    for dataname in datasetfile:
        txt2p.txt2p(dataname)
        rand.Rand(dataname)
        dfs.dfs(dataname)
        bfs.bfs(dataname)
    for dataname in datasetfile:
        for od in order:
            for k in ksize:
                ba.append(Balanced.Balanced(dataname, k, od))
                ch.append(Chunking.Chunking(dataname, k, od))
                dg.append(DGreedy.DGreedy(dataname, k, od))
                ha.append(Hashing.Hashing(dataname, k, od))
                rg.append(RGreedy.RGreedy(dataname, k, od))
                tr.append(Triangles.Triangles(dataname, k, od))
                
    print 'ba',ba
    print 'ch',ch
    print 'dg',dg
    print 'ha',ha
    print 'rg',rg
    print 'tr',tr
Ejemplo n.º 2
0
def execute_bfs(points, walls, selected_grid):
    start_rect = points[0]
    end_rect = points[1]
    wall_list = []
    for row in all_rects:
        for item in row:
            rect, _ = item
            if rect == start_rect:
                si = all_rects.index(row)
                sj = row.index(item)
            if rect == end_rect:
                ei = all_rects.index(row)
                ej = row.index(item)
            for wall in walls:
                if rect == wall:
                    wi = all_rects.index(row)
                    wj = row.index(item)
                    wall_list.append([wi, wj])


    start_point = [si, sj]
    end_point = [ei, ej]
    maze = Matrix(selected_grid[0], start_point, end_point, wall_list)
    bfs(maze, start_point)
    return maze
Ejemplo n.º 3
0
def run(maze, flammability):
    start = (0, 0)
    end = (maze.height - 1, maze.width - 1)

    # setup the fire
    fire.add_fire(maze, flammability)

    # calculate the first path
    path = []
    bfs.bfs(path, maze, start, end)
    if len(path) == 0:  # No path found
        return None

    # step on the path, spread fire, then create a new path
    while True:
        # if we stepped into fire, fail
        if maze.maze[path[1][0]][path[1][1]] != 0:
            return False

        # if we reached the end, pass
        if path[1] == end:
            return True

        # spread the fire
        fire.advance_fire_one_step(maze)

        # if fire moved onto us, fail
        if maze.maze[path[1][0]][path[1][1]] != 0:
            return False

        # recalculate path
        bfs.bfs(path, maze, path[1], end)
        if len(path) == 0:  # No path found
            return False
    return
Ejemplo n.º 4
0
def connected_components(graph):
    """
    Given a graph (directed or undirected) return its connected components.

    Input: A graph object.
    Output: A dictionary with the nodes as keys and the component index for 
            that node as the value.
    """
    class CCTraversal(bfs.Traversal):
        def __init__(self, graph):
            bfs.Traversal.__init__(self, graph)
            self.components = {}
            self.curr_component = 0

        def children_queued(self, node):
            self.components[node] = self.curr_component

    traversal = CCTraversal(graph)
    for node in graph.nodes:
        if node not in traversal.components:
            # Node has already been assigned a component so dont bother with this
            bfs.bfs(node, traversal)
            traversal.curr_component += 1

    return traversal.components
Ejemplo n.º 5
0
def drawer():
    win = pygcurse.PygcurseWindow(config['board']['w'], config['board']['h'], fgcolor='black')
    win.setscreencolors(None, 'white', clear=True)
    drag = False
    startEnd = []
    while len(startEnd) < 2:
        for event in pygame.event.get():
            if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                pygame.quit()
                sys.exit()
            if event.type == pygame.MOUSEBUTTONUP:
                coordinate = win.getcoordinatesatpixel(event.pos)
                win.write('@', *coordinate)
                startEnd.append(coordinate)

    walls = set()
    while True:
        for event in pygame.event.get():
            if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                pygame.quit()
                sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                drag = True
            elif event.type == pygame.MOUSEBUTTONUP:
                drag = False
            elif event.type == pygame.MOUSEMOTION:
                if drag:
                    coordinate = win.getcoordinatesatpixel(event.pos)
                    win.write('#', *coordinate)
                    walls.add(coordinate)
            elif event.type == pygame.KEYDOWN:
                if config['algo'] == 'bfs':
                    bfs(win, startEnd, walls)
Ejemplo n.º 6
0
def main():

    bfs.shuffler()
    initialState = bfs.initial_state
    print initialState
    bfs.bfs(initialState)
    moves = bfs.backtrace()
    print moves

    return render_template('index.html', initial=initialState, moves=moves)
Ejemplo n.º 7
0
def connectedComponents(G):
	components = []
	c = 0
	visited = set()
	for v in G:
		if v.key not in visited:
			components.append(set())
			bfs.bfs(G,v.key, discover_function = lambda x : visited.add(x), process_function = lambda x : components[c].add(x))
			c += 1
	return components
Ejemplo n.º 8
0
    def test_bfs_int_vertices_negaitve(self):

        graph = Graph()

        graph.add_edge(Edge(Vertex(1), Vertex(2), 1))
        graph.add_edge(Edge(Vertex(1), Vertex(4), 1))
        graph.add_edge(Edge(Vertex(3), Vertex(4), 1))
        graph.add_edge(Edge(Vertex(4), Vertex(2), 1))

        self.assertEqual(bfs(graph, Vertex(5), Vertex(0)), float("inf"))
        self.assertEqual(bfs(graph, Vertex(1), Vertex(5)), float("inf"))
def main():

    bfs.shuffler()
    initialState = bfs.initial_state
    randomizedState = bfs.randomized_state
    print("initial state: " + str(initialState))
    bfs.bfs(initialState)
    moves = bfs.backtrace()
    print(moves)

    return render_template('index.html', initial=initialState, moves=moves)
Ejemplo n.º 10
0
	def testBfs(self):
		G = graph.Graph()
		G.addEdge(1,2)
		G.addEdge(2,3)
		G.addEdge(4,1)
		G.addEdge(5,1)
		G.addEdge(6,1)
		G.addEdge(7,6)
		G.addEdge(3,1)
		G.addEdge(8,7)
		G.addEdge(9,8)
		processingOrder = []
		processFun = lambda v: processingOrder.append(v)
		bfs.bfs(G, 1, lambda v : v, processFun)
		self.failUnlessEqual(processingOrder, [1,2,3,4,5,6,7,8,9])
Ejemplo n.º 11
0
def ford_fulkerson(graph, source, sink):
    """ Run the Ford Fulkerson method using BFS for shortest path
    :param graph:
    :param source:
    :param sink:
    :return:
        Once BFS can no longer find any shortest direct path between source and sink,
        return the residual graph with the updated capacities.
    """
    path = bfs(graph, source, sink)
    while path:
        flow_path = zip(path[:-1], path[1:])
        graph = augment_flow(graph, flow_path)
        path = bfs(graph, source, sink)
    return graph
Ejemplo n.º 12
0
def SearchUSA(search_type, src_city, dst_city, filename='roads.txt'):
    "This function searches for a path from source city to destination city using given search algorithm"

    import bfs, dfs, astar, Roadmap
    from HelperFunctions import ReadFileToMap

    #Initializing empty map which uses adjacency list data structure to store map information
    my_map = Roadmap.Roadmap()

    #Loading map from the text file
    ReadFileToMap(filename, my_map)

    success = False

    print("\nApplying '{0}' Algorithm to search path from {1} to {2}\n".format(
        search_type.upper(), src_city.upper(), dst_city.upper()))

    if (search_type == 'bfs'):
        #		print("\n{}".format("BFS SEARCH".center(80,'$')))
        success = bfs.bfs(src_city, dst_city, my_map)
    elif (search_type == 'dfs'):
        #		print("\n{}".format("DFS SEARCH".center(80,'$')))
        success = dfs.dfs(src_city, dst_city, my_map)
    elif (search_type == 'astar'):
        #		print("\n{}".format("ASTAR SEARCH".center(80,'$')))
        success = astar.astar(src_city, dst_city, my_map)
    else:
        print("\nInvalid Search Type: Please Try Again.\n")

    if (success):
        pass
        # print("{}\n".format("SUCESS".center(400,'*')))
    else:
        print("{}\n".format("FAILURE".center(400, '*')))
Ejemplo n.º 13
0
	def __init__(self, typeOfAlgo , location, heading,goal_bounds, mazeDim, exploreAfterGoalReached):

		"""
		taking type of algo
		"""
		print((typeOfAlgo , location, heading,goal_bounds, mazeDim))
		self.algoType = typeOfAlgo
		self.mazeDim = mazeDim
		self.algoObj = None
		self.location =  location
		self.heading = heading
		self.goal_bounds = goal_bounds
		self.exploreAfterGoalReached=exploreAfterGoalReached
		#self.graphAdjacencyMatrix=self.buildAdjacencyGraph(self.mazeObj)
		if self.algoType == "Djskitra":
			self.algoObj = Djkistra(location, heading, goal_bounds, self.mazeDim ,exploreAfterGoalReached  )
		elif self.algoType == "floodfill":
			self.algoObj =  floodFill(location, heading, goal_bounds, self.mazeDim ,exploreAfterGoalReached)	
		elif self.algoType == "dfs":
			self.algoObj =  dfs(location, heading, goal_bounds, self.mazeDim ,exploreAfterGoalReached)	
		elif self.algoType == "bfs":
			self.algoObj =  bfs(location, heading, goal_bounds, self.mazeDim ,exploreAfterGoalReached)	
		elif self.algoType == "random":
			self.algoObj= None
		else:
			print("No specific  algorithm  mentioned")
Ejemplo n.º 14
0
def connected_components(graph):
    """
	computes the set of connected components of a graph 

	Arguments: 
	graph -- input graph

	Return: 
	a list of sets, where each set contains 
	the nodes belonging to that connected component
	"""
    # initialize remaining nodes set
    remainingNodes = set()
    for node in graph:
        remainingNodes.add(node)

    # initialize
    CC = []

    while len(remainingNodes) != 0:
        i = random.sample(remainingNodes, 1)[0]
        d = bfs.bfs(graph, i)
        W = set()
        for u in remainingNodes:
            if d[u] != float('inf'):
                W.add(u)
        CC.append(W)
        for node in W:
            remainingNodes.remove(node)
    return CC
Ejemplo n.º 15
0
def main():
    print("\n\n\nEnter the maze number that you want to solve.")
    mazeNumber = int(input("[1]. maze1.txt \t 2. maze2.txt \t 3. maze3.txt\n"))

    print("\n\nEnter algorithm number you would like to use.")
    algoPref = int(
        input(
            "[1]. Djikstra's \n 2. Breadth First Searh \n 3. Depth First Search \n 4. Backtracking\n"
        ))

    print("\n\nDo you want to get the output in color?")
    color = input("[Y]es\t\tNo\n")

    maze, start, end = mazes(mazeNumber)

    if algoPref == 4:
        path = backtracking(maze, start)
    elif algoPref == 3:
        path = dfs(maze, start)
    elif algoPref == 2:
        path = bfs(maze, start)
    else:
        path = djikstras(maze, start)

    # Printing the maze with the solution for the respective path finding algorithm
    currNode = end
    while currNode != (0, 1):
        nextNode = path[currNode]
        connectTwoCells(maze, currNode, nextNode)
        currNode = nextNode
    if color == "Y" or color == "y" or color.capitalize() == "Yes":
        printMazeInColor(maze)
    else:
        printMaze(maze)
Ejemplo n.º 16
0
 def test_no_path(self):
     self.assertEqual(None,
                      bfs("A", "C", {
                          "A": ["B"],
                          "B": ["D"],
                          "F": ["C"]
                      }))
Ejemplo n.º 17
0
def main():
    try:
        with open(sys.argv[1],"r") as f: #membaca nama file sebagai argumen program
            mat = [[int(num) for num in line if num!="\n"] for line in f]
        f.close()
        xawal, yawal = map(int, input("Masukkan point awal maze (format= x <spasi> y): ").split())
        xakhir, yakhir = map(int, input("Masukkan point akhir maze (format= x <spasi> y): ").split())
        mazemat = copy.deepcopy(mat)

        print("\nMatriks yang diinput: ")
        bfs.out(mat)
        print("\n\nDengan BFS: ")
        bobot = bfs.bfs(xawal,yawal,xakhir,yakhir,mat)
        bfs.out(mat)
        print("\nJalur yang ditempuh: ")
        bfs.jalur(bobot,xawal,yawal,xakhir,yakhir,mat)
        for i in range(len(mat)):
            for j in range(len(mat[i])):
                if (mat[i][j]==8):
                    print(0, end=" ")
                elif (mat[i][j]==5):
                    print(" ", end=" ")
                else:
                    print(mat[i][j], end=" ")
            print()
        print("\nAda sebanyak",bfs.jumlah(mat),"langkah")

        print("\n\nDengan A*: ")
        ast.aStar(mazemat,xawal,yawal,xakhir,yakhir)
    except IndexError:
        print("Tidak ditemukan jalur yang tepat\nStarting point ataupun ending point salah")
    except FileNotFoundError:
        print("File not found")
Ejemplo n.º 18
0
def findRoute(org, dst, flight_data):
    response = {}

    airlines_info_dic, airports_info_dic, connections_dic = flight_data

    if org == dst:
        response["type"] = "Error"
        response["message"] = "Origin and Destination must be different:" + org
        return response

    if not airports_info_dic.has_key(org):
        response["type"] = "Error"
        response["message"] = "Invalid Origin:" + org
        return response

    if not airports_info_dic.has_key(dst):
        response["type"] = "Error"
        response["message"] = "Invalid Destination:" + dst
        return response

    # use bfs to determine the mimimum connection route;
    route = bfs(org, dst, connections_dic)

    if len(route) == 0:
        response["type"] = "Failure"
        response["message"] = "No Route Exists"
    else:
        response["type"] = "Success"
        response["message"] = "Route Found"
        response["route"] = route

        response["detailedRoute"] = getFlightOptionsForRoute(
            route, connections_dic, airlines_info_dic, airports_info_dic)

    return response
Ejemplo n.º 19
0
def start():
    print("enter choice 1.bfs 2.dfs 3.uniform cost search 4.astart")
    x=input()
    if x=="1":
        graph={}
        print("enter number  nodes")
        nodes=int(input())
        for i in range(0,nodes):
            print("enter nodes connected to node with spaces:"+str(i))
            x=list(input().split())
            x = [int(i) for i in x]
            graph[i]=x
        goal=int(input("enter goal state"))
        print('bfs ' +bfs.bfs(graph,0,goal))
    if x=="2":
        graph=[]
        print("enter number  nodes")
        nodes = int(input())
        for i in range(0, nodes):
            print("enter nodes connected to node with spaces:" + str(i))
            x = list(input().split())
            x = [int(i) for i in x]
            graph.append(x)
        goal = int(input("enter goal state"))
        print(dfs.dfs(graph, 0,goal))
    if x=="3":
        djikstra.start1()

    if x=="4":
        astardynamic.start()
Ejemplo n.º 20
0
def segmentation(img_in_path, img_out_path):
    count = 0
    img_in = cv2.imread(img_in_path, 0)
    hei, wid = img_in.shape[:2]
    img_out = np.zeros((hei, wid))

    print("Segmentando imagem...")
    for i in range(hei):
        for j in range(wid):
            if img_in[i, j] > 0 and img_out[i, j] == 0:
                count += 1
                img_out[i, j] = count
                bfs(img_in, img_out, i, j, count)

    get_histogram(img_out, img_out_path)
    cv2.imwrite(img_out_path + "output.png", color_objects(img_out, count))
    print(f"Saída salva em: {img_out_path}")
Ejemplo n.º 21
0
def get_bfs():
    queue = deque()
    if (bfs(maze, 0, 0, queue, path, visited, draw_maze) == False):
        canvas.create_text(100,
                           100,
                           font=("Times New Roman", 20, "bold"),
                           fill='pink',
                           text="no solution")
Ejemplo n.º 22
0
 def steps_to_reach(cls):
     """ how many inventions neccessary to reach dragon """
     Logger.debug(
         "steps_to_reach(): cls.available_elnames=%s, dest='dragon'",
         cls.available_elnames)
     ret = bfs.bfs(cls.available_elnames, 'dragon')
     Logger.debug("returned %s", ret)
     return ret
Ejemplo n.º 23
0
    def test_bfs_str_vertices_negative(self):
        graph = Graph()

        graph.add_edge(Edge(Vertex("A"), Vertex("D"), 2))
        graph.add_edge(Edge(Vertex("A"), Vertex("G"), 3))
        graph.add_edge(Edge(Vertex("A"), Vertex("B"), 1))
        graph.add_edge(Edge(Vertex("B"), Vertex("E"), 6))
        graph.add_edge(Edge(Vertex("B"), Vertex("F"), 7))
        graph.add_edge(Edge(Vertex("F"), Vertex("D"), 10))
        graph.add_edge(Edge(Vertex("F"), Vertex("C"), 12))
        graph.add_edge(Edge(Vertex("E"), Vertex("G"), 9))

        self.assertEqual(bfs(graph, Vertex("A"), Vertex("C")), 20)
        self.assertEqual(bfs(graph, Vertex("A"), Vertex("F")), 8)
        self.assertEqual(bfs(graph, Vertex("B"), Vertex("G")), 15)
        self.assertEqual(bfs(graph, Vertex("E"), Vertex("A")), float("inf"))
        self.assertEqual(bfs(graph, Vertex("C"), Vertex("D")), float("inf"))
def choose_algo(start, end, grid, algorithm):
    if algorithm == 'bfs':
        return bfs(start, end, grid)
    elif algorithm == 'dfs':
        return dfs(start, end, grid)
    elif algorithm == 'dijkstra':
        return dijkstra(start, end, grid)
    elif algorithm == 'astar':
        return astar(start, end, grid)
Ejemplo n.º 25
0
def move(start, target, grid, algorithm):
    if algorithm == "astar":
        return astar(start, target, grid)
    elif algorithm == "dijkstra":
        return dijkstra(start, target, grid)
    elif algorithm == "bfs":
        return bfs(start, target, grid)
    elif algorithm == "dfs":
        return dfs(start, target, grid)
Ejemplo n.º 26
0
def main():
    with open("input.txt") as f:
        algo = f.readline().strip("\n").lstrip(" ").rstrip(" ")

        sec_line = f.readline().strip("\n").lstrip(" ").rstrip(" ").split(" ")
        no_of_columns = int(sec_line[0])
        no_of_rows = int(sec_line[1])

        third_line = f.readline().strip("\n").lstrip(" ").rstrip(" ").split(
            " ")
        landing_col = int(third_line[0])
        landing_row = int(third_line[1])

        threshold = int(f.readline().strip("\n").lstrip(" ").rstrip(" "))

        no_of_targets = int(f.readline().strip("\n").lstrip(" ").rstrip(" "))

        targets_list = [
            tuple(
                map(
                    int,
                    f.readline().strip("\n").lstrip(" ").rstrip(" ").split(
                        " "))) for target in range(no_of_targets)
        ]

        z_index_matrix = [
            list(
                map(
                    int,
                    re.sub(" +", " ",
                           f.readline().strip("\n").lstrip(" ").rstrip(
                               " ")).split(" "))) for rows in range(no_of_rows)
        ]

        if algo == "BFS":
            shortest_target_paths = bfs.bfs(z_index_matrix,
                                            (landing_col, landing_row),
                                            targets_list, threshold,
                                            no_of_columns, no_of_rows)
        elif algo == "UCS":
            shortest_target_paths = ucs.ucs(z_index_matrix,
                                            (landing_col, landing_row),
                                            targets_list, threshold,
                                            no_of_columns, no_of_rows)
        elif algo == "A*":
            shortest_target_paths = {}
            index = 0
            for target in targets_list:
                shortest_target_path = astar.astar(z_index_matrix,
                                                   (landing_col, landing_row),
                                                   [target], threshold,
                                                   no_of_columns, no_of_rows)
                shortest_target_paths[index] = shortest_target_path[0]
                index += 1

        write_to_output(shortest_target_paths)
Ejemplo n.º 27
0
    def test1(self):
        """test bfs"""
        self.assertEqual((1,2) in bfs.bfs(3,[(1,2),(1,3),(1,2)],1), True)
        self.assertEqual((1,3) in bfs.bfs(3,[(1,2),(1,3),(1,2)],1), True)
        self.assertEqual((2,3) in bfs.bfs(3,[(1,2),(1,3),(1,2)],1), False)
        self.assertEqual((1,4) in bfs.bfs(4,[(1,2),(1,3),(1,2),(3,4)],1), False)
        self.assertEqual((3,4) in bfs.bfs(4,[(1,2),(1,3),(1,2),(3,4)],1), True)
        self.assertEqual((1,6) in bfs.bfs(8,self.edges_cc(4),1), False)
        self.assertEqual((5,6) in bfs.bfs(6,[(1,2),(1,3),(1,2),(3,4),(5,6)],1), False)

        linegraph = [ (i,i+1) for i in range(1,10) ]
        self.assertEqual(linegraph, bfs.bfs(20,linegraph,1))

        linegraph.extend( [ (i,i+10) for i in range(1,10) ])
        self.assertEqual(set(linegraph), set(bfs.bfs(20,linegraph,1)))
Ejemplo n.º 28
0
def bfSearch():
    global endX
    global endY
    grid, x, y = buildGrid()
    path, seen = bfs.bfs(grid, (x, y))
    path.remove(path[0])
    path.remove(path[-1])
    seen.remove(seen[0])
    seen.remove((endX, endY))
    colourBoard(seen, path)
Ejemplo n.º 29
0
def main():
    # Init ROS node
    rospy.init_node('task', anonymous=True)

    # Create subscriber for position, goal, boost points, and obstacles
    rospy.Subscriber('/goal', Pose, goal_callback)
    rospy.Subscriber('/boost', PoseArray, boost_callback)
    rospy.Subscriber("/dynamic_obstacles", PoseArray,
                     dynamic_obstacles_callback)

    # Wait for resources to become active
    goal = rospy.wait_for_message("/goal", Pose).position
    boosts = rospy.wait_for_message("/boost", PoseArray).poses
    obstacles = rospy.wait_for_message("/dynamic_obstacles", PoseArray).poses

    # Create map service client
    getMap = rospy.ServiceProxy('/GlobalMap', GlobalMap)
    rospy.wait_for_service('/GlobalMap')

    try:
        raw_map = getMap()
    except rospy.ServiceException as e:
        print("Map service error: " + str(e))
        return

    # Get map as 2D list
    world_map = util.parse_map(raw_map)

    shortest_path = bfs.bfs(world_map, (0, 0), (goal.y, goal.x))

    # Print resources
    print("Wall layout:")
    util.print_map(world_map)
    print("Boost points:")
    util.print_positions(boosts)
    print("Obstacles at start:")
    util.print_positions(obstacles)

    # Initialize drone
    drone = Drone()
    drone.takeoff()

    # -- For example code --
    target_x = 0
    target_y = 0
    drone.set_target(target_x, target_y)

    rate = rospy.Rate(30)
    print('there is a test')
    i = 0
    targets = [[0, 0], [1, 0], [1, 7], [2, 7], [16, 7], [17, 7], [19, 7],
               [19, 20]]

    for t in targets:
        goto(t[0], t[1], rospy, rate, drone)
Ejemplo n.º 30
0
    def test_cyclical_graph(self):
        graph = {'A': ['B', 'C', 'D'],
                 'B': ['E', 'A'],
                 'C': ['E', 'A'],
                 'D': ['E', 'A'],
                 'E': []
                }
        start = 'A'
        out_visited = ['A', 'B', 'C', 'D', 'E']

        self.assertEqual(bfs(graph, start), out_visited)
Ejemplo n.º 31
0
def main():
    global start, goal, goal_found, start_found

    # load map
    pic("dartmouth_map.png")

    # draw each vertex & the connect-y line things in blue
    for location in vertex_dict:
        vertex_dict[location].draw_vertex(0, 0, 1)
        vertex_dict[location].draw_edges(0, 0, 1)

    # if the mouse is pressed
    if is_mouse_pressed():

        # loop through vertex_dict
        for location in vertex_dict:

            # if the mouse is in the square that inscribes a vertex circle
            if vertex_dict[location].select_vertex(mouse_x(), mouse_y()):

                start = vertex_dict[location] # start = the vertex you click on
                start.draw_vertex(1, 0, 0) # make vertex red
                start_found = True # start has now been found
                break # stop loop

    # once start is found, find goal
    if start_found:

        # loop through vertex dictionary
        for location in vertex_dict:
            # if it's the same vertex, continue
            if vertex_dict[location] == start:
                continue
            # if the mouse is in the square around the vertex, that vertex = goal
            if vertex_dict[location].select_vertex(mouse_x(), mouse_y()):

                goal = vertex_dict[location] # goal = whatever vertex your mouse is hovering over
                goal.draw_vertex(1, 0, 0) # draw in red
                goal_found = True # goal has been found
                break # stop loop

    # once the goal and start have been found, implement breadth-first search
    if start_found and goal_found:
        # extra credit: show vertex names in black
        start.start_show_name(0, 0, 0)
        goal.goal_show_name(0, 0, 0)
        path = bfs(start, goal) # path = bfs from start to goal
        goal = path[0] # goal = first element of path
        previous = goal
        # draw path from start to goal in red
        for vertex in path:
            vertex.draw_vertex(1, 0, 0)
            vertex.draw_path(previous, 1, 0, 0)
            previous = vertex
 def testIterativeDeepening(self):
     for i in range(50):
         adjList = self.randG.randomGnmGraph(n=50,
                                             M=1000,
                                             isWeighted=False,
                                             isDirected=False)
         src = random.choice(adjList.keys())
         dest = random.choice(adjList.keys())
         dist1, prev1 = bfs(adjList, src)
         dist2, prev2 = iterative_deepening(adjList, src, dest)
         self.assertEqual(dist1[dest], dist2[dest])
 def testBidirectional(self):
     for i in range(50):
         adjList = self.randG.randomGnmGraph(n=50,
                                             M=1000,
                                             isWeighted=False,
                                             isDirected=False)
         src = random.choice(adjList.keys())
         dest = random.choice(adjList.keys())
         dist1, prev1 = bfs(adjList, src)
         dist2, prev2 = bidirectional(adjList, src, dest)
         self.assertEqual(dist1[dest], dist2)
 def testUnweighted(self):
     for i in range(50):
         adjList = self.randG.randomGnmGraph(n=50,
                                             M=1000,
                                             isWeighted=False,
                                             isDirected=False)
         src = random.choice(list(adjList.keys()))
         dist1, prev1 = bfs(adjList, src)
         adjList = self.randG.toWeighted(adjList)
         dist3, prev3 = dijkstra(adjList, src)
         self.assertEqual(dist1, dist3)
def neighbourhood_all(g, depth):
	'''
	set neighbourhood of each node to BFS of depth "depth"
	todo: this should probably be in "graph.py"
	'''
	iteration = 0
	for auth_id, auth_t in g.authors.iteritems():
		if (iteration%250 == 0):
			print "computing neighbourhood %d out of %d"%(iteration, len(g.authors))
		iteration += 1
		pickle.dump(bfs.bfs(g, depth, auth_id), open("neighbourhood/%d"%auth_id, 'wb')) # we actually dump the neighbourhood to a file, can't save all of this in memory. It enables easy enough access from code, but not very efficient.
Ejemplo n.º 36
0
    def test_connected_graph(self):
        graph = {'A': ['B', 'C'],
                 'B': ['F', 'D'],
                 'C': ['D', 'E'],
                 'D': [],
                 'E': [],
                 'F': []
                }
        start = 'A'
        out_visited = ['A', 'B', 'C', 'F', 'D', 'E']

        self.assertEqual(bfs(graph, start), out_visited)
Ejemplo n.º 37
0
def main():
    # Start and goal vertices for BFS.
    start = None
    goal = None
    
    vertex_dict = load_graph("dartmouth_graph.txt") # dictionary of vertices
    image = load_image("dartmouth_map.png")         # image of map_plot
    
    enable_smoothing()
    
    while not window_closed():
        draw_image(image, 0, 0)     # draw the map
        
        # Draw each vertex and the edges between each vertex and its neighbors.
        for key in vertex_dict:
            vertex_dict[key].draw_neighbor_edges(0, 0, 1)   # draw in blue
            vertex_dict[key].draw(0, 0, 1)
                  
        # Find a vertex near the current mouse location.
        found = None 
        for key in vertex_dict:
            if vertex_dict[key].is_point_near_vertex(mouse_x(), mouse_y()):
                found = vertex_dict[key]
                break # we've found the vertex, so we don't need to keep going through the loop
        
        # If the mouse button is down, change the start vertex to whatever is found;
        # could be None.
        if mouse_down(): 
            start = found
        
        # If there is a start vertex has a value, draw it in red, and set the goal
        # (goal could be None!)  
        if start != None:
            start.draw(1, 0, 0)     # draw in red
            goal = found
    
        if start != None and goal != None:  # we have a genuine search!
            path = bfs(start, goal)
            
            # Draw the path from the goal back to the start in blue.
            previous = goal
            for vertex in path:
                vertex.draw(1, 0, 0)
                vertex.draw_edge(previous, 1, 0, 0) 
                previous = vertex
                
            # Show the names of the start and goal vertices in purple.
            # (Extra-credit feature.)
            start.show_name(0.5, 0, 1)
            goal.show_name(0.5, 0, 1)
                
        request_redraw()
        sleep(.02)
def noga_alon_projection(g, depth):
	'''
	Remove all nodes in g that are not close enough to noga alon (see in code what is "close enough")
	Note that depth 4 ~= 400,000 nodes. depth 5 ~= 800,000. Higher than that seems to converge to ~1000000
	So, if we run with depth=4 we get a 400,000 node graph.
	todo: this should probably be in "graph.py"
	'''
	noga_id = 1653815 # he has other IDs, but this is clearly his primary one (with 330 cooperations as opposed to <10 for the rest)
	noga_projection = bfs.bfs(g, depth, noga_id) # 
	
	authors_to_remove = [author for author in g.authors.keys() if author not in noga_projection]

	remove_authors(g, authors_to_remove)
Ejemplo n.º 39
0
def main():
    img = load_image("dartmouth_map")
    draw_image(img, 0, 0)
    
    start = None
    goal = None
    
    #initialize map with blue vertices
    for key in vertices:
        vertices[key].draw_vertex(0,0,1)
        for adjacent_vertex in vertices[key].list:
            vertices[key].draw_edge(adjacent_vertex, 0, 0, 1)
    
    while not window_closed(): 
        
        for key in vertices:
            if vertices[key].is_touched() and mouse_down():
                #reset map every time new starting vertex selected
                for generic_vertex in vertices:
                    vertices[generic_vertex].draw_vertex(0,0,1)
                    for adjacent_vertex in vertices[generic_vertex].list:
                        vertices[generic_vertex].draw_edge(adjacent_vertex, 0, 0, 1)
                
                #draw starting vertex        
                vertices[key].draw_vertex(1, 0, 0)
            
                start = key
                
        #check if start vertex selected        
        if start != None:        
            for key in vertices:
                if vertices[key].is_touched() and not vertices[start].is_touched():
                    goal = key
            
                    #start and goal vertices selected and start is not goal
                    if goal != None and start != goal:
                        for key in vertices:
                            vertices[key].draw_vertex(0,0,1)
                            for adjacent_vertex in vertices[key].list:
                                vertices[key].draw_edge(adjacent_vertex, 0, 0, 1)
                        path = bfs(start, goal)
                        if path != None:
                            for vertex in path:
                                if vertex != goal and vertex.back_pointer != None:
                                    vertex.draw_edge(vertex.back_pointer, 1, 0, 0)
                                    vertex.draw_vertex(1, 0, 0)
                        
        request_redraw()
        sleep(.02)
def main():
    
    #creates vertex object dictionary from load graph function
    vertex_dictionary=load_graph("dartmouth_graph.txt")
    
    #initialize start and goal vertex variables
    start_vertex=None
    goal_vertex= None
    
    while not window_closed():
        
        #draw the background
        draw_background(vertex_dictionary)
        
        for key in vertex_dictionary:
            
            #if mouse clicks on a vertex make it the starting vertex
            if vertex_dictionary[key].in_box(mouse_x(), mouse_y()) and mouse_down() and start_vertex!=goal_vertex:
                start_vertex=vertex_dictionary[key]
               
                
            #if mouse hovers over another vertex make that the goal vertex
            if vertex_dictionary[key].in_box(mouse_x(), mouse_y()) and vertex_dictionary[key]!=start_vertex:
                goal_vertex=vertex_dictionary[key]
                
                
        
        #performs bfs for start and goal vertices once declared
        if start_vertex!= None and goal_vertex!=None:
            #pathway is list of vertices from goal to start vertex created from bfs
            pathway= bfs(start_vertex, goal_vertex)
            
            #print names of start and goal above their respective vertex
            start_vertex.print_name()
            goal_vertex.print_name()
            
            for i in range(len(pathway)):
                #draw each vertex in pathway
                pathway[i].draw_vertex(1,0,0)
                #draw each edge in pathway
                if i<len(pathway)-1:
                    pathway[i].draw_edge(pathway[i+1],1,0,0)  
        
        
        #update the window and nap
        request_redraw()
        sleep(NAP)
Ejemplo n.º 41
0
def _testWithoutHeuristicCostEstimate():
    number_of_vertices = 100
    for test in range(1000):
        graph = _getRandomGraph(number_of_vertices)

        distance = bfs(0, graph)
        error_text = "Error on test: _testWithoutHeuristicCostEstimate"
        try:
            path = findWayByAStar(0, lambda x: x == number_of_vertices - 1, lambda x, y: 1, lambda x: graph[x],
                                  lambda x: 0)
        except:
            if distance[number_of_vertices - 1] != "Inf":
                raise Exception(error_text)
        else:
            if len(path) != distance[number_of_vertices - 1]:
                raise Exception(error_text)
            _checkPath(0, number_of_vertices - 1, path, graph, error_text)
Ejemplo n.º 42
0
  def resolve(self, src, sink):
    """
    Returns path from 'src' to 'sink' in cause-effect graph.

    Arguments:
      src  <str> : Source node concept (start).
      sink <str> : Sink node concept (goal).

    Returns:
      <(bool, str|[ConceptNode,])> - first item denotes whether an error occurred
      or not, the second item corresponds to an error message or a list of concept
      nodes representing the path from 'src' to 'sink' in the cause-effect graph.
    """
    if src not in self.nodes:
      return (False, 'Source %s not in Cause-Effect Graph.' % (src))
    elif sink not in self.nodes:
      return (False, 'Sink %s not in Cause-Effect Graph.' % (sink))
    else:
      return (True, bfs(self.nodes[src], self.nodes[sink]))
def limited_infection(graph, victim, new_version, preference, number_of_users):
    """
    :param graph: An array of all users in the system.
    :param victim: Who will be 'patient zero'. Must be a User.
    :param new_version: The new version to update users with.
    :param preference: Selection of the strings "child" and "parent" to choose which direction to favor.
    :param number_of_users: How many users we want to infect.
    """

    # If the input supplied is not indicative of a direction to traverse, we throw an error.
    if preference not in ["child", "parent"]:
        raise ValueError, "Invalid preference. Choose from 'parent' or 'child'."

    # The result of the disbursement of infections is supplied through the modified bfs function.
    result = bfs(victim, preference, number_of_users)

    # Because we used deepcopy to preserve the integrity of our data structure in bfs, we must update the users
    # supplied to us in the graph because those are the original users that we want to infect.
    for user in graph:
        for item in result:
            if item.get_username() == user.get_username() and user.get_version() != new_version:
                user.update_version(new_version)
        if user.get_version() == new_version:
            print user.get_username(), "has been infected."
Ejemplo n.º 44
0
def successive_possible_containers(a_node):
	return bfs.bfs(a_node,lambda x: x.those_can_be_within())
Ejemplo n.º 45
0
def map_dartmouth():

    # Loading the map
    graph = load_image("dartmouth_map.png")
    draw_image(graph, 0, 0)
    foco = load_image("53atdusk.jpg")

    # Initializing some variables. When nothing is clicked, the vertices will register as not found.
    start_found = False
    goal_found = False
    start_vertex_name = None
    end_vertex_name = None

    draw_facts()

    # Main graphics loop.
    while not window_closed():

        draw_facts()
        # Looping through all of the vertices in the dictionary.
        for vertex in dictionary:
            draw_facts()
            # Making the name of the vertex show up when you pass your mouse over it.
            set_font_size(15)
            enable_smoothing()

            if dictionary[vertex].on_vertex(mouse_x(), mouse_y()):
                dictionary[vertex].print_name(int(dictionary[vertex].x), int(dictionary[vertex].y) - Y_SHIFT)

            dictionary[vertex].draw(0, 0, 1)
            dictionary[vertex].draw_ad_list(0, 0, 1)

            # Finding the start vertex, conditions being that the mouse is on top of it and clicking.
            if dictionary[vertex].on_vertex(mouse_x(), mouse_y()) and mouse_down():

                # Assigning two variables: one stores the name of the vertex (so it can be used to index dictionaries) and
                # the other stores the actual vertex object.
                start_vertex_name = dictionary[vertex].name
                start = dictionary[vertex]

                # Drawing the relevant start vertex and assigning a Boolean saying that a start vertex has been picked.
                dictionary[start_vertex_name].draw(1, 0, 0)
                start_found = True
                draw_facts()

            # This keeps all of the vertices other than the start vertex red and the start vertex blue.
            if start_found == True and vertex != start_vertex_name:

                dictionary[start_vertex_name].draw(1, 0, 0)  # Red
                dictionary[vertex].draw(0, 0, 1)  # Blue
                draw_facts()

            # Same thing, but for the goal vertex. The goal vertex will only be chosen if a start vertex has been chosen.
            if start_found == True and dictionary[vertex].on_vertex(mouse_x(), mouse_y()):

                end_vertex_name = dictionary[vertex].name
                goal = dictionary[vertex]
                dictionary[end_vertex_name].draw(1, 0, 0)

                goal_found = True

            # So that the goal vertex will stay blue and the rest of the vertices will stay red.
            if goal_found == True and vertex != end_vertex_name:
                dictionary[end_vertex_name].draw(1, 0, 0)
                dictionary[vertex].draw(0, 0, 1)

            # Initializing a counter that I will use to loop through
            counter = 1

            # If both the start vertex and the end vertex have been found, then call BFS on the assigned
            # start and end (goal) vertices.

            if start_found == True and goal_found == True:

                # Making a list out of the start and end points, calling BFS.
                path = bfs(start, goal)

                # Going through all of the vertices of the path list, created by BFS.
                for vertex in path[:-1]:

                    # Draw the vertex and the edges. Have to increment the edges so they draw properly.
                    vertex.draw(1, 0, 0)
                    vertex.draw_edge(path[counter], 1, 0, 0)
                    counter = counter + 1

                draw_facts()
                enable_smoothing()
                d = PIXEL_FOOT_CONVERSION * int(distance(int(start.x), int(goal.x), int(start.y), int(goal.y)))
                draw_text(str(d) + " ft", 100, 20)
                draw_text(str(int(d / FEET_PER_MINUTE)) + " min", 135, 40)
                draw_text("Path: " + str(start.name) + " to " + str(goal.name), 10, 60)

                if dictionary[goal.name] == dictionary["Foco"] and not dictionary[start.name] == dictionary["Foco"]:
                    clear()
                    draw_image(foco, 75, 95)
                    set_font_size(40)
                    draw_text("You've arrived at Foco!", 100, 80)

        # Standard graphics stuff
        request_redraw()
        sleep(NAPTIME)
Ejemplo n.º 46
0
 def is_connected(self):
     m, d, p = bfs.bfs(self, 1) 
     for a in self.adj:
         if not m[a]:
             return False
     return True
Ejemplo n.º 47
0
from input import parseTree
from dfs import *
from bfs import bfs

print "Tree:"
nodes, edges = parseTree()
print "Test dfs"
print "Preorder"
print map(lambda x: nodes[x], preorder(edges, 0))
print "Inorder"
print map(lambda x: nodes[x], inorder(edges, 0))
print "Postorder"
print map(lambda x: nodes[x], postorder(edges, 0))
print "Test bfs"
print map(lambda x: nodes[x], bfs(edges, 0))
Ejemplo n.º 48
0
from bfs import bfs
d={}
g=Graph()
def buildGraph(list):
    for word in list:
        for i in range(len(word)):
            bucket=word[:i]+"_"+word[i+1:]
            if bucket in d:
                d[bucket].append(word)
            else: d[bucket]=[word]
    for bucket in d.keys():
        for word1 in d[bucket]:
            for word2 in d[bucket]:
                if (word1!=word2):
                    g.addEdge(word1,word2)


'''
buildGraph(["hit","hot","dot","dog","lot","log","cog"])
for v in g:
   for w in v.getConnections():
       print("( %s , %s )" % (v.getId(), w.getId()))

bfs(g,g.getVertex("hit"),"cog")
'''

buildGraph(["fool","foul","foil","fail","fall","cool","pool",
"poll","pall","pole","pope","pale","sale","sage","page"])

bfs(g,g.getVertex("fool"),"sage")
Ejemplo n.º 49
0
def map_DM():
    
    # Loading the map
    map1 = load_image("dartmouth_map.png")
    draw_image(map1, 0, 0)
    
    # Initializing some variables. When nothing is clicked, the vertices will register as not found.
    start_found = False # start_found and goal_found are Booleans that will check if a start or goal has been chosen.
    goal_found = False
    start = None # These will store the actual vertex objects.
    goal = None
    
    
    #Main graphics loop.
    while not window_closed():
        
        # Looping through all of the vertices in the dictionary.
        for vertex in dictionary:
            
            # Drawing all of the vertices and edges between them.
            # Didn't want to make another function to do this, as it's only two lines.
            dictionary[vertex].draw(0, 0, 1)
            dictionary[vertex].draw_ad_list(0, 0, 1)
            
            # Finding the start vertex, conditions being that the mouse is on top of it and clicking.
            if dictionary[vertex].on_vertex(mouse_x(), mouse_y()) and mouse_down():
                    
                # Assigning two variables: one stores the name of the vertex (so it can be used to index dictionaries) and 
                # the other stores the actual vertex object.
                start_vertex_name = dictionary[vertex].name
                start = dictionary[vertex]
                
                # Drawing the relevant start vertex and assigning a Boolean saying that a start vertex has been picked.
                dictionary[start_vertex_name].draw(1, 0, 0)
                start_found = True
            
            # This keeps all of the vertices other than the start vertex red and the start vertex blue.
            if start_found == True and vertex != start_vertex_name:
                
                dictionary[start_vertex_name].draw(1, 0, 0) # Red
                dictionary[vertex].draw(0, 0, 1) # Blue

            
            # Same thing, but for the goal vertex. The goal vertex will only be chosen if a start vertex has been chosen.
            if start_found == True and dictionary[vertex].on_vertex(mouse_x(), mouse_y()):
                
                end_vertex_name = dictionary[vertex].name
                goal = dictionary[vertex]
                dictionary[end_vertex_name].draw(1, 0, 0)

                goal_found = True
            
            # So that the goal vertex will stay blue and the rest of the vertices will stay red.
            if goal_found == True and vertex != end_vertex_name:
                dictionary[end_vertex_name].draw(1, 0, 0)
                dictionary[vertex].draw(0, 0, 1)

            
            # Initializing a counter that I will use to loop through 
            counter = 1
            
            # If both the start vertex and the end vertex have been found, then call BFS on the assigned
            # start and end (goal) vertices. 
            if start_found == goal_found == True:
                
                # Making a list out of the start and end points, calling BFS.
                path = bfs(start, goal)
        
                # Going through all of the vertices of the path list, created by BFS.
                for vertex in path[:-1]:
                    
                    # Draw the vertex and the edges. Have to increment the edges so they draw properly.
                    vertex.draw(1, 0, 0)
                    vertex.draw_edge(path[counter], 1, 0, 0)
                    counter = counter + 1

        # Standard graphics stuff
        request_redraw()
        sleep(NAPTIME)
Ejemplo n.º 50
0
u1 v1
u2 v2
u3 v3
.
.
.
un vn
"""

# no of edges
n = int(input())

# for undirected graph
adj = {}
for i in range(n):
	key, val = map(int, input().split(' '))
	if key not in adj:
		adj[key] = [val]
	else:
		adj[key].append(val)

	if val not in adj:
		adj[val] = [key]
	else:
		adj[val].append(key)

# Vertex from which bfs has to start
print(adj)
v = int(input())
bfs(adj, v)
Ejemplo n.º 51
0
def main():
    signal_handeling.prepareToFindJesus()
    print(bfs.bfs("http://en.wikipedia.org/wiki/Special:Random"))
    signal_handeling.jesusFound()
Ejemplo n.º 52
0
def doBfs(map, startNode, goalNode):	
	print('BFS algorithm')

	# Start the search
	map, numberOfOpenNodes, numberOfClosedNodes = bfs(map, startNode, goalNode)
	printMap(map, numberOfOpenNodes, numberOfClosedNodes)
Ejemplo n.º 53
0
 def bfs(self, source):
   """docstring for bfs"""
   return bfs(source)