Example #1
0
    def keypress(self, event):
        if event.keysym == 'Left':
            self.move('Left')
        if event.keysym == 'Right':
            self.move('Right')
        if event.keysym == 'Up':
            self.move('Up')
        if event.keysym == 'Down':
            self.move('Down')

        self.update()

        s = None
        if event.char == 'b':
            print "Breitensuche"
            s = BFS({'depth' : 0, 'values' : self.values, 'parent' : None}, self.goal)
        if event.char == 'd':
            print "Tiefensuche"
            s = DFS({'depth' : 0, 'values' : self.values, 'parent' : None}, self.goal)
        if event.char == 'i':
            print "Iterative Tiefensuche"
            s = IDDFS({'depth' : 0, 'values' : self.values, 'parent' : None}, self.goal)
        if event.char == 'a':
            print "A* Suche"
            s = AStar({'depth' : 0, 'values' : self.values, 'parent' : None}, self.goal)

        if s:
            steps = []
            while s.solution['parent']:
                steps.append(s.solution['values'])
                s.solution = s.solution['parent']

            while len(steps) > 0:
                print steps.pop()
def edmond_karp(G, probNum, origGraph):
	
	# Flow matrix to keep track of residual and used capacities
	n = len(G.keys()) #number of nodes
	F = [[0] * n for i in xrange(n)] #Flow, reverse edges 
	
	#create key-value pairs for nodes and Flow matrix idx
	idx = {} #node_idx_map
	for i, node in enumerate(G.keys()):	
		idx[node] = int(i)

	max_flow = 0
	RG = G

	# Update the flow matrix with minimum assumed flow
	if origGraph is not None:
		#print 'Orig Graph:'
		#for k, v in sorted(origGraph.items()):
        	#	print k, origGraph[k]

		for x in origGraph:
			for y in origGraph[x]:
				minval = origGraph[x][y]['min']
				F[idx[x]][idx[y]] = minval
		 
	
	#Find all paths using BFS
	while True:
		if origGraph is not None:
			path = BFS.bfs(G, F, 'SS', 'TT', idx)
			# print 'path: %s' % path
		else: 
			path = BFS.bfs(G, F, 'S', 'T', idx)
	 	
		if not path: 
			break

		#compute flow allowable for the current path
		path_flow = min(G[u][v]['max'] - F[idx[u]][idx[v]] for u,v in path) #Total Capacity - used capacity
		
		#modify the flow matrix with current path's flow
		for u,v in path:
			F[idx[u]][idx[v]] += path_flow
			F[idx[v]][idx[u]] -= path_flow

			#Create a new residual graph to output assignments
			RG[u][v]['max'] = int(RG[u][v]['max']) - path_flow

		max_flow += path_flow
		#print 'path: '
		#print path, path_flow, F

	#Print assignemnts only if its not 6.3
	if probNum != '6.3':
		file_result = open('Result_File_6.1.txt', 'ab')
		assign_task_workers(RG, file_result)

	return max_flow, F, idx, RG
def edmond_karp(G, origraph):

    # Flow matrix n * n to keep track of flow
    n = len(G.keys())  # number of nodes
    F = [[0] * n for i in xrange(n)]  # Flow, reverse edges

    # create key-value pairs for nodes and Flow matrix idx
    idx = {}
    for i, node in enumerate(G.keys()):
        idx[node] = int(i)

    max_flow = 0
    RG = G

    # Find paths from 'SS' to 'TT' to satisfy minimum number of assignments
    while True:
        path = BFS.bfs(G, F, "SS", "TT", idx)
        # print 'path: %s' % path
        if not path:
            break
            # compute flow allowable for the current path
        path_flow = min(int(G[u][v]["max"]) - F[idx[u]][idx[v]] for u, v in path)  # Total Capacity - used capacity

        # modify the flow matrix with current path's flow
        for u, v in path:
            F[idx[u]][idx[v]] += path_flow
            F[idx[v]][idx[u]] -= path_flow

            # Create a new residual graph for 6.3
            RG[u][v]["max"] = int(RG[u][v]["max"]) - path_flow

        max_flow += path_flow

        # Find paths from 'S' to 'T' to get maximum possible assignments
    while True:
        path = BFS.bfs(G, F, "S", "T", idx)
        # print 'path from ss to t: %s' % path
        if not path:
            break
            # compute flow allowable for the current path
        path_flow = min(int(G[u][v]["max"]) - F[idx[u]][idx[v]] for u, v in path)  # Total Capacity - used capacity

        # modify the flow matrix with current path's flow
        for u, v in path:
            F[idx[u]][idx[v]] += path_flow
            F[idx[v]][idx[u]] -= path_flow

            # Create a new residual graph for 6.3
            RG[u][v]["max"] = int(RG[u][v]["max"]) - path_flow

        max_flow += path_flow

        # Print assignments
    assign_task_workers(RG, F, idx)

    return max_flow, F, idx, RG
Example #4
0
 def __init__(self,grid):
     self.running = True
     self.OnInit()
     g = Graph(grid)
     #self.search = Search(g,'A','T')
     self.search = BFS(g,'L','N')
     self.search.reset()
Example #5
0
class App:
    def __init__(self,grid):
        self.running = True
        self.OnInit()
        g = Graph(grid)
        #self.search = Search(g,'A','T')
        self.search = BFS(g,'L','N')
        self.search.reset()
    def OnInit(self):
        pygame.init()
        resolution = 640,480
        self.screen = pygame.display.set_mode(resolution)
        self.screen.fill(bgcolor)
        self.clock = pygame.time.Clock()
    def onEvent(self,event):
        if event.type == pygame.QUIT or event.type==pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            self.running = False
            return
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                self.search.step()
            if event.key == pygame.K_r:
                self.search.reset()
            if event.key == pygame.K_RETURN:
                print 'return Pressed'
                self.search.run()
    def cleanUp(self):
        pygame.quit()
    def render(self,seconds):
        #self.screen.fill(bgcolor)
        self.search.draw(self.screen)
        pygame.display.flip()
    def mainloop(self):
        fps = 60
        while self.running:
            seconds = self.clock.tick(fps)
            for event in pygame.event.get():
                self.onEvent(event)
            self.render(seconds)
        self.cleanUp()
Example #6
0
    def test_correctly_identify_shortest_path(self):
        """ Is the shortest path correctly identified? """

        # Adjacency List of graph G
        G = {}
        G[0] = [1, 2]
        G[1] = [0, 3]
        G[2] = [0, 3, 4]
        G[3] = [1, 2, 4, 5]
        G[4] = [2, 3, 5]
        G[5] = [4, 5]

        # Start node
        s = 0

        dist = BFS.BFSShortestPath(G, s)
        expDist = {0: 0, 1: 1, 2: 1, 3: 2, 4: 2, 5: 3}

        self.assertEqual(expDist, dist)
    def getFeatureCapsule(factors, features, pacman, state, old_pac_pos=None):
        capsules = []
        for i in range(len(factors["capsule_locs"])):
            capsules.append([
                float(len(BFS.BFS(pacman, factors["capsule_locs"][i], state))),
                factors["capsule_locs"][i]
            ])
        capsules.sort()
        if len(capsules) > 0:
            farthest_consideration = 15
            for i in range(min(int(capsules[0][0]), farthest_consideration)):
                features["closest-capsule-" + str(farthest_consideration - i) +
                         "-away"] = 1

            if old_pac_pos is not None:
                features["towards-capsule"] = \
                    directional(factors["capsule_locs"][0],
                                old_pac_pos,
                                pacman,
                                state)
Example #8
0
def BFS_solution(estado_inicial, estado_objetivo):

    time_init = time()
    busca = BFS.BFS_algorithmcs(list_action_function=listarAcoes,
                                execute_action_function=executarAcao,
                                hash_function=funcao_hash,
                                cmp_function=comparar_estados)

    N = len(estado_inicial)
    estado_inicial = encoding(estado_inicial)
    estado_objetivo = encoding(estado_objetivo)

    solution = busca.BFS(estado_inicial, estado_objetivo)
    solution.E0 = decoding(estado_inicial)
    solution.Ef = decoding(estado_objetivo)
    solution.states = [decoding(x) for x in solution.states]
    solution.duration = time() - time_init
    solution.deepth = busca.graph.branching_factor()
    solution.width = busca.graph.deepth_factor()

    return solution
Example #9
0
def DFSFunc(map):
    parents = []           # bien luu lai cac diem truoc do
    for i in range(1, map.space[0]):
        for j in range(1, map.space[1]):
            parents.append(((i, j), None))
    parents = dict(parents)

    def DFSRecursion(start):  # de quy DFS
        neighbours = BFS.getNeighbours(start, map.space, map.obstacles)
        for neighbour in neighbours:        # xet cac diem xung quanh
            if parents[neighbour] == None:  # neu chua di qua diem nay
                parents[neighbour] = start  # luu lai duong di
                if neighbour == map.end:
                    return True
                elif DFSRecursion(neighbour):
                    return True
        return False

    if (DFSRecursion(map.start)):
        return BFS.drawPath(parents, map.start, map.end)
    else:
        return None, None
Example #10
0
    def __prepareH(self):
        """
        Make the B0 independent Hamiltonian (i.e. HShift needs to be multiplied by B0).
        The Hamiltonian is defined as a series of independent blocks.

        Returns
        -------
        list of blockCls elements:
            A list of all teh Hamiltonian blocks
        """
        HShiftFull = self.__MakeShiftH()
        HJzFull, Lines, Orders = self.__MakeJLines()
        Connect, JconnectList, JposList, JSizeList, TotalSpinConnect = bfs.getConnections(Lines, Orders, self.MatrixSize, self.TotalSpin)
        Blocks = []
        for x, Pos in enumerate(Connect):
            Jconnect = JconnectList[x]
            Jpos = JposList[Jconnect]
            Jval = JSizeList[Jconnect]
            Shift = HShiftFull[Pos]
            HJz = HJzFull[Pos]
            Blocks.append(blockCls(Jpos, Jval, Pos, Shift, HJz, TotalSpinConnect[x]))
        return Blocks
Example #11
0
def main():
	#load image
	print("Loading Image ...")
	im = Image.open("1.png")
	
	# creating maze
	t0 = time.time()
	print("creating maze ...")

	maze = MazeCR.Maze(im)
	
	print("Maze created ...")
	t1 = time.time()
	
	print("Time elapsed : ",(t1-t0))
	
	path = BFS.solve(maze)
	
	print("Saving Image ...")
	im = im.convert('RGB')  #converts to rgb image
	impixels = im.load()	#loads pixels of the image
	length = len(path)
	
	for i in range(0,length-1):
		a = path[i]
		b = path[i+1]
		
		r = int((i / length) * 255)   #creating a random value for r
		#print(r)
		px = (255-r,0,r)     #setting the pixel's value
		if a[0] == b[0]:
			for x in range(min(a[1],b[1]), max(a[1],b[1])):
				impixels[x,a[0]] = px
		elif a[1] == b[1]:
			for y in range(min(a[0],b[0]), max(a[0],b[0]) + 1):
				impixels[a[1],y] = px

	im.save("ans.png")     #saving the image
	im.show()       #outputs the image
Example #12
0
def distanceDiff(cur_state, next_state, obj_loc, ghosts=False, scared_list=None):
    diff = []
    cur_pac = cur_state.getPacmanPosition()
    next_pac = next_state.getPacmanPosition()

    # Creates tuple for each object w/ absolute distance and direction
    for i in range(len(obj_loc)):
        cur_loc = (int(obj_loc[i][0]), int(obj_loc[i][1]))
        # Non-scared ghost
        if ghosts and scared_list[i][0] == 1:
            # Find all potential moves for ghost
            legal_ghost_actions = cur_state.getLegalActions(i + 1)
            legal_ghost_moves = []
            for action in legal_ghost_actions:
                next_state = cur_state.generateSuccessor(i + 1, action)
                legal_ghost_moves.append(next_state.getGhostPosition(i + 1))

            possible_actions = game.Actions.getLegalNeighbors(cur_state.getGhostPosition(i + 1), cur_state.getWalls())

            # Find all places the ghost cannot move
            illegal_moves = []
            for possible_action in possible_actions:
                if possible_action not in legal_ghost_moves:
                    illegal_moves.append(possible_action)

            path = BFS.BFS(cur_pac, cur_loc, cur_state, illegal_moves)

            # Finds current distance. Check for edge case where ghost is in house
            if path is []:
                cur_dist = len(BFS.BFS(cur_pac, cur_loc, cur_state))
                next_dist = len(BFS.BFS(next_pac, cur_loc, cur_state))

            # Normal case. Illegal moves excluded
            else:
                cur_dist = len(path)
                next_dist = len(BFS.BFS(next_pac, cur_loc, cur_state, illegal_moves))

        else:
            cur_dist = len(BFS.BFS(cur_pac, cur_loc, cur_state))
            next_dist = len(BFS.BFS(next_pac, cur_loc, next_state))

        if next_dist - cur_dist >= 0:
            diff.append((next_dist, 1))
        else:
            diff.append((next_dist, -1))
    return diff
Example #13
0
    def testBFS(self):
        G = graph()
        G.addEdge('v', 'r')
        G.addEdge('s', 'r')
        G.addEdge('s', 'w')
        G.addEdge('t', 'w')
        G.addEdge('x', 'w')
        G.addEdge('x', 't')
        G.addEdge('u', 't')
        G.addEdge('x', 'y')
        G.addEdge('x', 'u')
        G.addEdge('y', 'u')

        BFS.BFS(G, 's')

        self.assertEqual(G.distance['s'], 0)
        self.assertEqual(G.distance['w'], 1)
        self.assertEqual(G.distance['r'], 1)
        self.assertEqual(G.distance['v'], 2)
        self.assertEqual(G.distance['t'], 2)
        self.assertEqual(G.distance['x'], 2)
        self.assertEqual(G.distance['u'], 3)
        self.assertEqual(G.distance['y'], 3)
Example #14
0
def getIsolateSys(spinList, Jmatrix):
    """
    Checks the input spins and Jmatrix to find isolated systems.
    It returns these systems with their own Jmatrix. This is usually not
    needed, if the user does its work properly (and runs Jellyfish for the
    separate systems in the first place). But this check is very quick, so why
    not do it.

    Parameters
    ----------
    spinList: list of list
        List with each spin information (e.g. ['1H',0,3,True], for [Isotope,Shift,Multiplicity,Detect]
    Jmatrix: ndarray
        2D matrix with the J-coupling information for the spin system.

    Returns
    -------
    list of lists:
        Each element contains [list of spin information, Jmatrix]
    """
    Pos1, Pos2 = np.where(Jmatrix != 0.0)
    Length = len(spinList)
    Adj = np.ones((Length, len(Pos1)*2), dtype=int) * np.arange(Length)[:, np.newaxis]
    for x, _ in enumerate(Pos1):
        Adj[Pos1[x], x*2] = Pos2[x]
        Adj[Pos2[x], x*2+1] = Pos1[x]
    #Do a connection search (bfs) for all elements
    Connect = bfs.connectionSearch(Adj)
    isoSpins = []
    for con in Connect:
        spinTemp = [spinList[x] for x in con]
        jtmp = np.triu(Jmatrix)
        jtmp = jtmp + np.transpose(jtmp)
        jtmp = jtmp[con, :]
        jtmp = jtmp[:, con]
        isoSpins.append([spinTemp, np.triu(jtmp)])
    return isoSpins
Example #15
0
def aplica_todos():
    if sys.version_info[0] < 3:
        pathDoArquivo = tk.Open().show()
    else:
        pathDoArquivo = filedialog.askopenfilename()
    G = nx.read_gexf(pathDoArquivo)
    M = krl.Kruskal(G)
    pathDoArquivoNovo = pathDoArquivo.replace(".gexf", "_MST_Kruskal.gexf")
    nx.write_gexf(M, pathDoArquivoNovo)
    M = pr.Prim(G, G.nodes()[0])
    pathDoArquivoNovo = pathDoArquivo.replace(".gexf", "_MST_Prim.gexf")
    nx.write_gexf(G, pathDoArquivoNovo)
    M = bfs.BFS(G, G.nodes()[0])
    pathDoArquivoNovo = pathDoArquivo.replace(".gexf", "_BFS.gexf")
    nx.write_gexf(M, pathDoArquivoNovo)
    M = dfs.DFS(G, G.nodes()[0])
    pathDoArquivoNovo = pathDoArquivo.replace(".gexf", "_DFS.gexf")
    nx.write_gexf(M, pathDoArquivoNovo)
    M = dks.Dijkstra(G, G.nodes()[0])
    pathDoArquivoNovo = pathDoArquivo.replace(".gexf", "_Dijkstra.gexf")
    nx.write_gexf(M, pathDoArquivoNovo)
    M = wp.WelshPowell(G, G.nodes()[0])
    pathDoArquivoNovo = pathDoArquivo.replace(".gexf", "_WelshPowell.gexf")
    nx.write_gexf(M, pathDoArquivoNovo)
Example #16
0
 def setUp(self):
     self.init = 4
     self.goal = 5
     self.actions = KnuthActions
     self.search = BFS(self.init, self.goal, self.actions)
Example #17
0
 def test_BFS_fail(self):
     self.init = 0
     self.goal = 1
     self.search = BFS(self.init, self.goal, self.actions)
     self.assertEqual(self.search.start(), BFS.error_message)
Example #18
0
 def test_is_goal(self):
     self.search = BFS(self.init, self.goal, self.actions)
     self.assertEqual(self.search.is_goal(self.goal), True)
Example #19
0
                if ButtonRun.pressed(pos):

                    print("Minimum Spanning Tree Is:")

                    print(kruskal.kruskal(Graph))

                    print("Topological Sort")

                    print(topsort.dfs_topsort(Graph))

                    print("Breadth First Search")

                    answer = inputbox.ask(window, "Enter Node for BFS")
                    answer = ord(answer) - ord('1')
                    print(BFS.BFS(Graph, Graph.vertexList[answer]))

                    print("Dijkstra Tree")

                    answer = inputbox.ask(window,
                                          "Enter Node for Dijkstra Tree")
                    answer = ord(answer) - ord('1')
                    d, p = dijkstra.dijkstra(Graph, Graph.vertexList[answer])

                    print("Distances:")
                    print d
                    print("Parents:")
                    print p

    pygame.display.update()  #Refreshes the Display
Example #20
0
# -----------------------------------------------------------#
#              BFS + Shortest Path Algorithm                 #
#                                                            #
#              (C) 2020, LABANI SAID, France                 #
#                                                            #
#               @: [email protected]                   #
# -----------------------------------------------------------#

from Graph import *
from BFS import *
from FindShortestPath import *

#Building The Graph Object
GraphTest = Graph('TestGraph', 'a,b,c,d,e', ['b,c', 'd,c', 'd,e', 'e', ''])

#Creating the BFS Graph (Launching The BFS Algorithm)
BFS(GraphTest, GraphTest.Vertices["a"])

#Finding the shortest path from noed "a" to noeud "e"
ShortestPath = FindShortestPath(GraphTest.Vertices["a"],
                                GraphTest.Vertices["e"])

#Printing The Shortest Path
print(StringPath(ShortestPath))
Example #21
0
       ##grid1 = gridObj1.generate_grid(n,size)
       #gridObj2 = GridGenerator(Matrix,"AStar Euclidean")
       #grid2 = gridObj2.generate_grid(n,size)
       #gridObj3 = GridGenerator(Matrix,"AStar Manhatten")
       #grid3 = gridObj3.generate_grid(n,size)
       #print(Matrix)
       print("DFS")
       dfsNodesExp=[]
       analyseDFS=DFS(Matrix, startX, startY ,n-1,n-1,grid,n,size,p).solve().to_dict()
       if(analyseDFS['Maze Solved']==True):
            print("Maze solved DFS: ",analyseDFS['Maze Solved'])
            plist.append(analyseDFS['Probability'])
            dfsNodesExp.append(analyseDFS['Nodes Explored'])
            analyzerObjectDFS.append(analyseDFS)
       bfsNodesExp = []
       analyseBFS = BFS(Matrix, startX, startY, n - 1, n - 1, grid, n, size, p, False).solve().to_dict()
       if (analyseBFS['Maze Solved'] == True):
          print("Maze solved DFS: ", analyseBFS['Maze Solved'])

          bfsNodesExp.append(analyseBFS['Nodes Explored'])
          analyzerObjectBFS.append(analyseBFS)
       #nodesExpDFS=[]
       #nodesExpDFS.append(DFS(Matrix, startX, startY ,n-1,n-1,grid,n,size,p).solve().to_dict()['Nodes Explored'])
       #print("BFS")
       #analyzerObjectDFS.append(BFS(Matrix, startX, startY ,n-1,n-1,grid,n,size,p).solve().to_dict())
       #print("ASTAR EU")
       aStarNodesExp = []
       analyseAStar = AStar(Matrix, startX, startY ,n-1,n-1,grid,n,size,p,"Euclidean").solve().to_dict()
       if (analyseAStar['Maze Solved'] == True):
          print("Maze solved AStar: ", analyseAStar['Maze Solved'])
          aStarNodesExp.append(analyseAStar['Nodes Explored'])
Example #22
0
def search(init, goal):
    algo = BFS(init, goal, KnuthActions)
    print(algo.start(verbose=True))
if (result_node is None):
    print("No path found using graph search!")
else:
    print("Path:", result_node.path())
    print("Path Cost:", result_node.path_cost)
    print("Solution:", result_node.solution())
print("Nodes searched with graph search:", myGraphSearch.nodesSearched)
print("Time Spent with graph search:", myGraphSearch.timeSpent)

print("==============")

print("BREADTH FIRST SEARCH")

# search using BFS Search
myBFSSearch = BFS(eight_puzzle)
result_node = myBFSSearch.search()

if (result_node is None):
    print("No path found using tree search!")
else:
    print("Path:", result_node.path())
    print("Path Cost:", result_node.path_cost)
    print("Solution:", result_node.solution())
print("Nodes searched with BFS:", myBFSSearch.nodesSearched)

print("Time Spent with BFS:", myBFSSearch.timeSpent)

print("==============")
print("DEPTH FIRST SEARCH")
print("\x1b[0;30;41m" + "NOTE -- NEEDS TO BE IMPLEMENTED -- CURRENTLY BFS" +
from Digraph import *
from BFS import *
from OEIS import *
import sys

if __name__ == '__main__':
    oeis = OEIS(sys.argv[1], sys.argv[2])
    graph = oeis.graph
    vertices = [127892 - 1, 181085 - 1]
    bfs = BFS(graph, vertices[0])
    path = bfs.pathTo(vertices[1])
    print "longest path", [ele + 1 for ele in path]
    bfsSeq = BFS(graph, path)
    while True:
        sink = int(raw_input()) - 1
        if bfsSeq.hasPathTo(sink):
            for v in bfs.pathTo(sink):
                print "%d %s" % (v + 1, oeis.getTitle(v))
        else:
            print "Not connected"
print('subgraph: #node='+str(num_sub_node)+', #edge='+str(num_sub_edge));

#compute unigram factor value
print('\nbuild unigram factors...');

with open('uniFactor','w') as f:
    f.write(str(num_sub_node)+' '+str(num_node)+'\n');
    for node in adj_list_subgraph.keys():
        f.write(str(node)+' ');
        for node2 in adj_list_graph.keys():
            f.write( str(node2)+":"+str(dot(node_fea_map[node], node_fea_map[node2]))+' ' );
        f.write('\n');
        print('.',end=''); sys.stdout.flush();

#compute bigram factor values
print('\nbuild bigram factors...');

with open('biFactor','w') as f:
    f.write(str(num_node)+' '+str(num_node)+'\n');
    for node in adj_list_graph.keys():
        dist_map = BFS.bfs_dist(num_node, adj_list_graph, node);
        f.write(str(node)+' ');
        for (n,d) in dist_map.items():
            if n != node:
                f.write(str(n)+':'+str(bifactor_weight/d)+' ');
            else:
                f.write(str(n)+':-1e300 ');
        f.write('\n');
        print('.',end=''); sys.stdout.flush();
print();
Example #26
0
from Digraph import *
from BFS import *
from OEIS import *
import sys

if __name__ == '__main__':
    oeis = OEIS(sys.argv[1], sys.argv[2])
    graph = oeis.graph
    source = int(sys.argv[3]) - 1
    bfs = BFS(graph, source)
    freq = {}
    for i in range(graph.numOfVertices()):
        if bfs.hasPathTo(i):
            dist = bfs.distanceTo(i)
            freq[dist] = freq.get(dist, 0) + 1
    total = 0
    product = 0
    for key, value in freq.items():
        total += value
        product += key * value
        print key, value
    print "%d of %d is reachable" %(total, graph.numOfVertices())
    print "average distance is %.2f"%(product / float(total))
    while True:
        sink = int(raw_input()) - 1
        if bfs.hasPathTo(sink):
            print "%d %d (%d)" % (source, sink, bfs.distanceTo(sink))
            for v in bfs.pathTo(sink):
                print "%d %s" % (v + 1, oeis.getTitle(v))
        else:
            print "Not connected"
from BFS import *
from Dijkstra import *

print("Итоговый путь: ", BFS())
print()
print("Итоговый путь: ", Djikstra())
print()
    def getFeatureGhostsSeperate(factors, features, pacman, state):
        for i in range(len(factors["ghost_locs"])):
            cur_distance = len(BFS.BFS(pacman, factors["ghost_locs"][i],
                                       state))
            if factors["scared"][i] > 0:
                features["ghost " + str(i) + " scared dist"] = min(
                    cur_distance, 7)
            else:
                features["ghost " + str(i) + " dist"] = min(cur_distance, 7)
        for i in range(len(factors["ghost_locs"])):
            # Ghost is scared
            if factors["scared"][i] > 0:
                cur_distance = len(
                    BFS.BFS(pacman, factors["ghost_locs"][i], state))
                # Scared ghost values
                if cur_distance <= 7:
                    features["ghost " + str(i) + " (scared) 7 away"] = 1
                    if cur_distance <= 5:
                        features["ghost " + str(i) + " (scared) 5 away"] = 1
                        if cur_distance <= 3:
                            features["ghost " + str(i) +
                                     " (scared) 3 away"] = 1
                            if cur_distance <= 2:
                                features["ghost " + str(i) +
                                         " (scared) 2 away"] = 1
                                if cur_distance <= 1:
                                    features["ghost " + str(i) +
                                             " (scared) 1 away"] = 1
                                    if cur_distance <= 0:
                                        features["ghost " + str(i) +
                                                 " (scared) 0 away"] = 1

            # Ghost is not scared
            # Need to determine if ghost is facing/is a threat to pacman
            else:
                # Find all potential moves for ghost
                legal_ghost_actions = state.getLegalActions(i + 1)
                legal_ghost_moves = []
                for action in legal_ghost_actions:
                    next_state = state.generateSuccessor(i + 1, action)
                    legal_ghost_moves.append(next_state.getGhostPosition(i +
                                                                         1))

                possible_actions = Actions.getLegalNeighbors(
                    state.getGhostPosition(i + 1), state.getWalls())

                # Find all non-potential moves for a ghost
                illegal_moves = []
                for possible_action in possible_actions:
                    if possible_action not in legal_ghost_moves:
                        illegal_moves.append(possible_action)

                # Runs BFS without the spots behind the current ghosts (ghosts can't go backward)
                cur_distance = len(
                    BFS.BFS(pacman, factors["ghost_locs"][i], state,
                            illegal_moves))

                # Ghost values
                if cur_distance <= 7:
                    features["ghost " + str(i) + " 7 away"] = 1
                    if cur_distance <= 5:
                        features["ghost " + str(i) + " 5 away"] = 1
                        if cur_distance <= 3:
                            features["ghost " + str(i) + " 3 away"] = 1
                            if cur_distance <= 2:
                                features["ghost " + str(i) + " 2 away"] = 1
                                if cur_distance <= 1:
                                    features["ghost " + str(i) + " 1 away"] = 1
Example #29
0
def PartialCubeEdgeLabeling(G):
    """
    Label edges of G by their equivalence classes in a partial cube structure.

    We follow the algorithm of arxiv:0705.1025, in which a number of
    equivalence classes equal to the maximum degree of G can be found
    simultaneously by a single breadth first search, using bitvectors.
    However, in order to avoid deep recursions (problematic in Python)
    we use a union-find data structure to keep track of edge identifications
    discovered so far. That is, we repeatedly contract our initial graph,
    maintaining as we do the property that G[v][w] points to a union-find
    set representing edges in the original graph that have been contracted
    to the single edge v-w.
    """

    # Some simple sanity checks
    if not isUndirected(G):
        raise Medium.MediumError("graph is not undirected")
    L = list(StronglyConnectedComponents(G))
    if len(L) != 1:
        raise Medium.MediumError("graph is not connected")

    # Set up data structures for algorithm:
    # - UF: union find data structure representing known edge equivalences
    # - CG: contracted graph at current stage of algorithm
    # - LL: limit on number of remaining available labels
    UF = UnionFind()
    CG = dict([(v, dict([(w, (v, w)) for w in G[v]])) for v in G])
    NL = len(CG) - 1

    # Initial sanity check: are there few enough edges?
    # Needed so that we don't try to use union-find on a dense
    # graph and incur superquadratic runtimes.
    n = len(CG)
    m = sum([len(CG[v]) for v in CG])
    if 1 << (m // n) > n:
        raise Medium.MediumError("graph has too many edges")

    # Main contraction loop in place of the original algorithm's recursion
    while len(CG) > 1:
        if not isBipartite(CG):
            raise Medium.MediumError("graph is not bipartite")

        # Find max degree vertex in G, and update label limit
        deg, root = max([(len(CG[v]), v) for v in CG])
        if deg > NL:
            raise Medium.MediumError("graph has too many equivalence classes")
        NL -= deg

        # Set up bitvectors on vertices
        bitvec = dict([(v, 0) for v in CG])
        neighbors = {}
        i = 0
        for neighbor in CG[root]:
            bitvec[neighbor] = 1 << i
            neighbors[1 << i] = neighbor
            i += 1

        # Breadth first search to propagate bitvectors to the rest of the graph
        for LG in BFS.BreadthFirstLevels(CG, root):
            for v in LG:
                for w in LG[v]:
                    bitvec[w] |= bitvec[v]

        # Make graph of labeled edges and union them together
        labeled = dict([(v, set()) for v in CG])
        for v in CG:
            for w in CG[v]:
                diff = bitvec[v] ^ bitvec[w]
                if not diff or bitvec[w] & ~bitvec[v] == 0:
                    continue  # zero edge or wrong direction
                if diff not in neighbors:
                    raise Medium.MediumError("multiply-labeled edge")
                neighbor = neighbors[diff]
                UF.union(CG[v][w], CG[root][neighbor])
                UF.union(CG[w][v], CG[neighbor][root])
                labeled[v].add(w)
                labeled[w].add(v)

        # Map vertices to components of labeled-edge graph
        component = {}
        compnum = 0
        for SCC in StronglyConnectedComponents(labeled):
            for v in SCC:
                component[v] = compnum
            compnum += 1

        # generate new compressed subgraph
        NG = dict([(i, {}) for i in range(compnum)])
        for v in CG:
            for w in CG[v]:
                if bitvec[v] == bitvec[w]:
                    vi = component[v]
                    wi = component[w]
                    if vi == wi:
                        raise Medium.MediumError(
                            "self-loop in contracted graph")
                    if wi in NG[vi]:
                        UF.union(NG[vi][wi], CG[v][w])
                    else:
                        NG[vi][wi] = CG[v][w]

        CG = NG

    # Here with all edge equivalence classes represented by UF.
    # Turn them into a labeled graph and return it.
    return dict([(v, dict([(w, UF[v, w]) for w in G[v]])) for v in G])
Example #30
0
from Node import *
from DFS import *
from BFS import *
from config import originate, target
import time

if __name__ == '__main__':
    Node1 = Node(None, originate, 0)
    Node2 = Node(None, target, 0)
    DFS = DFS(Node1, Node2, 10, 3)
    BFS = BFS(Node1, Node2, 10, 3)
    a_star = a_star(Node1, Node2, 10, 3)

    #深度优先
    start_d = time.time()
    flag_d = DFS.search()
    end_d = time.time()
    cost_d = end_d - start_d

    #广度优先
    start_b = time.time()
    flag_b = BFS.search()
    end_b = time.time()
    cost_b = end_b - start_b

    if (flag_d):
        print('The result of DFS')
        DFS.showLine()
        print('Spent time:%f s\n\n' % (cost_d))
    else:
        print('error')
Example #31
0
def is_connected(G):
    BFS(G, v[0])
    for i in G:
        if i.distance == INFINITY:
            return False
    return True
Example #32
0
 def collidecheck(self):
     for o in self.obstacle:
         if BFS.collide(o, self.robot):
             print("collide!")
         else:
             print("nope!")
Example #33
0
import BFS
import numpy as np
A = np.mat('3,2,2;1,2,1;2,2,3')
BFS.operator(A, 3, 0, 2)
Example #34
0
import sys
import Start

if __name__ == "__main__":
    print "script_name", sys.argv[0]
    for i in range(1, len(sys.argv)):
        print "argument", i, sys.argv[i]
    print('start initialize')
    # set the size and density of this matrix
    size = 10
    start = Start.Start(size, 0.3)
    # start.print_matrix()
    start.paint_random()
    # init all the algorithm
    dfs = DFS.DFS()
    bfs = BFS.BFS()
    a_mht = ASTAR_MHT.ASTAR()
    a_euc = ASTAR_EUC.ASTAR()
    print('start run')
    print "DIM, T_DFS, T_BFS, T_MHT, T_EUC"
    while 1:
        print size,
        start = Start.Start(size, 0.3)
        start.paint_random()
        while dfs.dfs_route(start.get_matrix(), size)[0] == 0:
            start.paint_random()
        # set timer for each algorithm
        start_time = time.clock()
        #DFS
        dfs.dfs_route(start.get_matrix(), size)
        T_DFS = (time.clock() - start_time)
initialstate = [[1, 4, 5], [7, 2, 8], [6, 0, 3]]

# initialstate = [[1,2,3],[7,8,0],[4,5,6]]

initialstate = [[1, 3, 0], [4, 2, 5], [7, 8, 6]]
# initialstate = [[4,1,2],[0,5,3],[7,8,6]]
# initialstate = [[1,3,0],[4,2,5],[7,8,6]]
# initialstate = [[0,1,2],[4,5,3],[7,8,6]]
# initialstate = [[1,2,3],[4,0,5],[7,8,6]]
# initialstate = [[1,2,3],[0,4,5],[7,8,6]]

goalstate = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]

print("initialstate : ")
BFS.printlist(initialstate)
print("goalstate : ")
BFS.printlist(goalstate)

with open("output.txt", "w") as outfile:
    outfile.write("initial state : " + "\n")
BFS.writelist(initialstate, "output.txt")
with open("output.txt", "a") as outfile:
    outfile.write("\n" + "\n")
# with open("output.txt","a") as outfile :
# 	outfile.write("\n"+"\n")
with open("output.txt", "a") as outfile:
    outfile.write("\n" + "goal state : " + "\n")
BFS.writelist(goalstate, "output.txt")
with open("output.txt", "a") as outfile:
    outfile.write("\n" + "\n")
#!/usr/bin/python

from Node import Node
import BFS

node1 = Node("A")
node2 = Node("B")
node3 = Node("C")
node4 = Node("D")
node5 = Node("E")

node1.adjacenciesList.append(node2)
node1.adjacenciesList.append(node3)
node2.adjacenciesList.append(node4)
node4.adjacenciesList.append(node5)

BFS.bfs(node1)
Example #37
0
#--Compara igualdade de estados
# **** É possivel associar um inteiro a cada estado e
# **** assim a comparação seria direta
def cmpEstados(Ea, Eb):

    return Ea[0] == Eb[0]


#------------------------------------------------


def funcaoHash(Ea):
    return int(ord(Ea[0])) % 30


busca1 = BFS.BFS_algorithmics(list_action_function=listarAcoes, execute_action_function=executarAcao, \
                           hash_function = funcaoHash, cmp_function = cmpEstados)


busca2 = DFSIterative.DFS_algorithmcs(list_action_function=listarAcoes, execute_action_function=executarAcao, \
                           hash_function = funcaoHash, cmp_function = cmpEstados)

busca3 = AStar.A_Star_algorithmics(list_action_function=listarAcoes, execute_action_function=executarAcao, \
                           hash_function = funcaoHash, cmp_function = cmpEstados)

#print("Algoritmo: BFS")
#print("Borda/Iteração:")
#solution = busca1.BFS(E0, Eobj)
#print("Solução:")
#start_time = time.time()
#for step in solution:
#    print("mover-se para " + str(step.action) + ", ", end=' ')
    def getFeatureGhosts(factors, features, pacman, state, old_pac_pos=None):
        for i in range(len(factors["ghost_locs"])):
            # Ghost is scared
            if factors["scared"][i] > 0:
                farthest_consideration = 15
                cur_distance = min(
                    len(BFS.BFS(pacman, factors["ghost_locs"][i], state)),
                    farthest_consideration)

                # Distance booleans
                for j in range(farthest_consideration - cur_distance):
                    features["scared-ghost-" + str(i) + "-" +
                             str(farthest_consideration - j) + "-away"] = 1

                # Directional information
                if old_pac_pos is not None:
                    features["scared-ghost-" + str(i) + "-towards"] = \
                        directional(factors["ghost_locs"][i],
                                    old_pac_pos,
                                    pacman,
                                    state)

            # Ghost is not scared
            # Need to determine if ghost is facing/is a threat to pacman
            else:
                # Find all potential moves for ghost
                legal_ghost_actions = state.getLegalActions(i + 1)
                legal_ghost_moves = []
                for action in legal_ghost_actions:
                    next_state = state.generateSuccessor(i + 1, action)
                    legal_ghost_moves.append(next_state.getGhostPosition(i +
                                                                         1))

                possible_actions = Actions.getLegalNeighbors(
                    state.getGhostPosition(i + 1), state.getWalls())

                # Find all non-potential moves for a ghost
                illegal_moves = []
                for possible_action in possible_actions:
                    if possible_action not in legal_ghost_moves:
                        illegal_moves.append(possible_action)

                # Runs BFS without the spots behind the current ghosts (ghosts can't go backward)
                farthest_consideration = 15
                path = BFS.BFS(pacman, factors["ghost_locs"][i], state,
                               illegal_moves)

                # Finds current distance. Check for edge case where ghost is in house
                if path is []:
                    cur_distance = min(
                        len(BFS.BFS(pacman, factors["ghost_locs"][i], state)),
                        farthest_consideration)

                # Normal case. Illegal moves excluded
                else:
                    cur_distance = min(len(path), farthest_consideration)

                # Distance booleans
                for j in range(farthest_consideration - cur_distance):
                    features["ghost-" + str(i) + "-" +
                             str(farthest_consideration - j) + "-away"] = 1

                # Directional information
                if old_pac_pos is not None:
                    features["ghost " + str(i) + " towards"] = \
                        directional(factors["ghost_locs"][i],
                                    old_pac_pos,
                                    pacman,
                                    state)
plt.plot(range(len(network_graph)+1), resilience_upa, label="UPA network(n=1239, m=2)")
plt.plot(range(len(network_graph)+1),resilience_er, label="ER network(n=1239, p=0.004)")
plt.title("computer resillience diagram")
plt.xlabel("number of attacked computer")
plt.ylabel("size of the largest connect component")
plt.legend(loc="upper right")
plt.show()
'''

##################Q4#######################
# compute resilience

NETWORK_URL = "http://storage.googleapis.com/codeskulptor-alg/alg_rf7.txt"
network_graph = graph_generator.load_graph(NETWORK_URL)
attack_order_original = attack_generator.fast_targeted_order(network_graph)
resilience_original = BFS.compute_resilience(network_graph,attack_order_original)

UPA_network = graph_generator.UPA(1239, 2)
attack_order_upa = attack_generator.fast_targeted_order(UPA_network)
resilience_upa = BFS.compute_resilience(UPA_network,attack_order_upa)


ER_network = graph_generator.ER_undirected(1239, 0.004)
attack_order_er = attack_generator.fast_targeted_order(ER_network)
resilience_er = BFS.compute_resilience(ER_network,attack_order_er)

############################################
# plotting

plt.plot(range(len(network_graph)+1), resilience_original, label="computer network")
plt.plot(range(len(network_graph)+1), resilience_upa, label="UPA network(n=1239, m=2)")