def search (self, initialState): states = [] open = [] new_n = Node(initialState, None) open.append((new_n, new_n.f())) while (len(open) > 0): #list sorted by f() open.sort(key = sortFunction, reverse = True) n = open.pop()[0] logging.debug(n.state.env()+" -- "+str(n.f())+" -- "+str(n.h())) if (n.state.is_goal()): return n for i in n.state.sucessors(): new_n = Node(i,n) # eh necessario descrever o conteudo do estado # para verificar se ele já foi instanciado ou nao if (new_n.state.env() not in states): open.append((new_n,new_n.f())) # nao eh adiciona o estado ao vetor. # eh adicionado o conteudo states.append(new_n.state.env()) logging.debug(len(states)) else: logging.debug('nao entrou') return None
def test_walk_tree(): a = Node.Node('a') b = Node.Node('b') c = Node.Node('c') d = Node.Node('d') e = Node.Node('e') a.dependsOn(b) a.dependsOn(d) a.dependsOn(c) b.dependsOn(c) b.dependsOn(e) c.dependsOn(d) c.dependsOn(e) print("\nDependency Tree:") resolved = [] a.resolve_dependencies(a, resolved) print("Dependencies: ", end='') for item in resolved: print(item.name, end=' => ') print("|\n") expected_result = ['d', 'e', 'c', 'b', 'a'] for result, expected in zip(resolved, expected_result): assert result.name == expected
def readGFA(gfaFile): gfa = open(gfaFile).read().split('\n')[:-1] nodesSeq = dict() edges = list() for line in gfa: if line[0] == 'S': fields = line.split('\t') nodesSeq[fields[1]] = fields[2] elif line[0] == 'L': fields = line.split('\t') node1 = fields[1] node1dir = fields[2] node2 = fields[3] node2dir = fields[4] ovlp = int(fields[5][:-1]) edges.append((node1, node1dir, node2, node2dir, ovlp)) G = Graph() for node1, node1dir, node2, node2dir, ovlp in edges: if node1 not in G.nodemap: n1_seq = nodesSeq[node1] n1 = Node(node1, len(n1_seq), n1_seq) else: n1 = G.nodemap[node1] if node2 not in G.nodemap: n2_seq = nodesSeq[node2] n2 = Node(node2, len(n2_seq), n2_seq) else: n2 = G.nodemap[node2] G.addEdge(n1, node1dir, n2, node2dir, ovlp) return G
def astar_search(graph, heuristics, src, dest): open = [] explored = [] # Create the start node and the goal node start = Node(src, None) goal = Node(dest, None) # Add the first node to the open list open.append(start) # Loop until the list is empty while len(open) > 0: # Keep the list sorted so we extract only the smallest element open.sort() # Get the node with the lowest cost current_node = open.pop(0) # Add the current node to the explored nodes list explored.append(current_node) # Check if the current node is the goal node # If we reached the goal, return the path if current_node == goal: # Store the path from destination node to the source node path = [] while current_node != start: path.append(current_node.name) current_node = current_node.parent path.append(src) # Return reversed path return path[::-1] # Get neighbors neighbors = graph.get(current_node.name) # Loop through neighbors for key, value in neighbors.items(): # Create a neighbor node neighbor = Node(key, current_node) # Check if the neighbor is in the closed list if(neighbor in explored): continue # Calculate full path cost neighbor.g = current_node.g + graph.get(current_node.name, neighbor.name) neighbor.h = heuristics[neighbor.name] neighbor.f = neighbor.g + neighbor.h # Check if neighbor is in open list and if it has a lower f value if(add_to_open(open, neighbor) == True): # Everything is green, add neighbor to open list open.append(neighbor) # Return None if no path is found return None
def test_addNode(): tree = Tree.Tree() tree.addNode(Node.Node('a')) tree.addNode(Node.Node('b')) with pytest.raises(RuntimeError): tree.addNode(Node.Node('a'))
def Main(): host = '127.0.0.1' port = 5000 s = socket.socket() s.bind((host, port)) print('Server started') s.listen(5) c, addr = s.accept() while True: print('client connected ip: ' + str(addr) + '>') string = c.recv(1024).decode('utf-8') if not string: break if '[' in string: string = string.replace('[', '') if ']' in string: string = string.replace(']', '') L = string.split(',') source = int(L[0]) target = int(L[1]) g = Graph() V = [Node(1), Node(2), Node(3), Node(4), Node(5), \ Node(6), Node(7), Node(8), Node(9), Node(10)] E = [[1, 2, 1], \ [1, 3, 3], \ [1, 4, 3], \ [2, 3, 1], \ [2, 5, 1], \ [2, 6, 8], \ [3, 4, 1], \ [3, 5, 1], \ [3, 6, 1], \ [3, 7, 2], \ [4, 6, 2], \ [4, 7, 3], \ [4, 8, 1], \ [5, 9, 1], \ [6, 9, 1], \ [6, 10, 7], \ [7, 9, 3], \ [7, 10, 2],\ [8, 10, 4]] g.addVertices(V) g.addEdges(E) path = DijkstrasAlgorithm(g, source, target) path_string = ','.join(str(e) for e in path) c.send(path_string.encode('utf-8')) s.close()
def search (self, initialState): #Creating a Queue open = deque() open.append(Node(initialState, None)) while (len(open) > 0): n = open.popleft() if (n.state.is_goal()): return n for i in n.state.sucessors(): open.append(Node(i,n)) return None
def test(): pathOfCollection = '.\\data\\test.csv' # 解析文件 # 读取csv文件,转为二维数组 collection = pd.read_csv(pathOfCollection) collectionList = collection.values.tolist() # 对图上的点和边进行插入 graph = Graph() for i in range(len(collectionList)): node_A = Node(collectionList[i][0], collectionList[i][1], collectionList[i][2]) if collectionList[i][0] in graph.G_node_dict: node_A = graph.G_node_dict[collectionList[i][0]] elif collectionList[i][0] in graph.H_node_dict: node_A = graph.H_node_dict[collectionList[i][0]] elif collectionList[i][0] in graph.J_node_dict: node_A = graph.J_node_dict[collectionList[i][0]] node_B = Node(collectionList[i][3], collectionList[i][4], collectionList[i][5]) if collectionList[i][3] in graph.G_node_dict: node_B = graph.G_node_dict[collectionList[i][3]] elif collectionList[i][3] in graph.H_node_dict: node_B = graph.H_node_dict[collectionList[i][3]] elif collectionList[i][3] in graph.J_node_dict: node_B = graph.J_node_dict[collectionList[i][3]] graph.insert_node(node_A) graph.insert_node(node_B) graph.add_edge(node_A, node_B) print(len(graph.G_node_dict)) print(len(graph.H_node_dict)) print(len(graph.J_node_dict)) print("文件阅读完毕。。。") # 生成所有的链路 topology_link_dict = graph.gen_all_topology_link() print(len(topology_link_dict)) print("带有主链路的链路解析完毕。。。") topology_link_list = list(topology_link_dict.values()) # 展示一个链路 # topology_link_list[0].show_main_link() # 打印链路 f = open(".\\data\\topology_link.txt", 'w+') for topology_link in topology_link_list: f.write(topology_link.main_link.hashcode_1 + "\n") print(1)
def addExtraneousPoint(extraneousPoint, minY=None, maxY=None): x1 = extraneousPoint[0] startSides = [] if x1 < xCoordsFreeEdges[0]: startSides.append(xCoordsFreeEdges[0]) elif x1 > xCoordsFreeEdges[-1]: startSides.append(xCoordsFreeEdges[-1]) else: pt = bisect.bisect_left(xCoordsFreeEdges, x1) startSides.append(xCoordsFreeEdges[pt - 1]) startSides.append(xCoordsFreeEdges[pt]) returnNode = None for x2 in startSides: for edge in freeEdges[x2]: y1 = extraneousPoint[1] y2 = int((edge[0] + edge[1]) / 2.0) if str((x1, y1)) not in nodes: if minY is None: minY = y1 if maxY is None: maxY = y1 nodes[str((x1, y1))] = Node(data=str((x1, y1, minY, maxY))) returnNode = nodes[str((x1, y1))] if str((x2, y2)) not in nodes: nodes[str( (x2, y2))] = Node(data=str((x2, y2, min(edge), max(edge)))) if x1 > x2: _x1, _x2 = x2, x1 else: _x1, _x2 = x1, x2 if not containObstacle(_x1, _x2, y1, y2): if DIST_FUNC == 0: distance = abs(x2 - x1) # Only x-dist else: distance = math.sqrt( (x2 - x1)**2 + (y2 - y1)**2) # x and y dist edges.append((nodes[str((x1, y1))], nodes[str( (x2, y2))], distance)) cv2.line(map, (x1, y1), (x2, y2), (255, 0, 255), 1) cv2.circle(map, (x1, y1), 8, (255, 0, 255), -1) cv2.circle(map, (x2, y2), 8, (255, 0, 255), -1) return returnNode
def search (self, initialState, m): #Using list as stack open = [] open.append(Node(initialState, None)) while (len(open) > 0): n = open.pop() if (n.state.is_goal()): return n if (n.depth < m): for i in n.state.sucessors(): open.append(Node(i,n)) return None
def search (self, initialState): open = [] new_n = Node(initialState, None) open.append((new_n, new_n.h())) while (len(open) > 0): #list sorted by h() open.sort(key = sortFunction, reverse = True) n = open.pop()[0] if (n.state.is_goal()): return n for i in n.state.sucessors(): new_n = Node(i,n) open.append((new_n, new_n.h())) return None
def __init__(self, numNodes, adjacencyMatrix=None): self.numNodes = numNodes self.nodes = [Node(data=i) for i in range(numNodes)] self.adjacencyMatrix = np.zeros((numNodes, numNodes)) if adjacencyMatrix is not None: for i in range(numNodes): for j in range(numNodes): self.adjacencyMatrix[i][j] = adjacencyMatrix[i][j]
def ruleN(self, parent, debug=False): if debug: self.indentOut() if parent != None: node = Node(parent) else: node = Node() self.ruleS(node, debug=debug) self.ruleL(node, debug=debug) self.ruleH(node, debug=debug) self.ruleA(node, parent, debug=debug) self.ruleB(node, debug=debug) if debug: print return node
def test_circular_dep(): a = Node.Node('a') b = Node.Node('b') c = Node.Node('c') d = Node.Node('d') e = Node.Node('e') a.dependsOn(b) a.dependsOn(d) b.dependsOn(c) b.dependsOn(e) c.dependsOn(d) c.dependsOn(e) d.dependsOn(b) resolved = [] with pytest.raises(RuntimeError): a.resolve_dependencies(a, resolved)
def __init__(self, width, height, occupancyGrid=None): self.width = width self.height = height self.numNodes = width * height self.occupancyGrid = occupancyGrid if self.occupancyGrid is None: self.occupancyGrid = np.zeros((height, width)) self.nodes = [[Node(data=str((y, x))) for x in range(width)] for y in range(height)]
def __init__(self): """ Accept the grpah using the Graph Module and initialize the required lists """ self.graph = Graph() self.graph.accept() """ list of nodes """ self.nodes = [Node(i) for i in range(0,self.graph.total_nodes)] self.open = [] #To keep track of expanded nodes self.closed = [] #To keep track of visited nodes self.in_open = [0]*self.graph.total_nodes #To keep track of nodes already present in open list
def PRM(world): # Number of nodes N = 2000 # Number of neighbors per node k = 5 # Maximum distance for a neighbor d = 15 # The graph is created here and the start and goal nodes are created Roadmap = Graph() start_node = Node(start) goal_node = Node(goal) # Adding start and goal nodes to the graph Roadmap.add_node(start_node) Roadmap.add_node(goal_node) # Samples the world space for N nodes while len(Roadmap.nodes) != N: # Sampling random points on the graph x = random.randint(0, x_upper - 1) y = random.randint(0, y_upper - 1) z = random.randint(0, z_upper - 1) # Adding sampled points to the graph if world[x, y, z] != -1 and [x, y, z] not in Roadmap.nodes: Roadmap.add_node(Node([x, y, z])) # Links all the nodes in the graph print("\nCreating and Linking all Nodes:") for node in tqdm(Roadmap.nodes): neighbors = Roadmap.get_neighbors(node, k, d) for neighbor in neighbors: if collision_free(world, node, neighbor): if Roadmap.edge_exists(node, neighbor) == False: Roadmap.add_edge(node, neighbor) # Here dijkstras algorithm is called on the graph returning a stack holding # the path from the start to the goal node print("\nFinding Shortest Path From Start to Goal....") return Roadmap.dijkstra(start_node, goal_node)
def cloneGraph(self, node): if not node: return node if node in self.visited: return self.visited[node] clone_node = Node(node.val, []) self.visited[node] = clone_node if node.neighbors: clone_node.neighbors = [self.cloneGraph(n) for n in node.neighbors] return clone_node
def MST(G): ''' 图G ''' V = G.V E = G.Adjlist MSTV = set() MSTE = {} Ds = DisjointSet(V) for v in V: MSTE[v] = Linklist() for u in MSTE.keys(): curList = E[u] curNode = curList.head while (curNode != 0): v = curNode.data #使用并查集判断是否生成环 #------------------------------------ parentu = Ds.find(u) parentv = Ds.find(v) if parentu != parentv: #不会生成环 MSTV.add(u) MSTV.add(v) MSTE[u].pushback(Node(v, curNode.weight)) MSTE[v].pushback(Node(u, curNode.weight)) #合并两并查集 Ds.union(parentu, parentv) else: #加入该边会生成环 MaxWeightEdge = getMaxWeightEdge(MSTV, MSTE, u, v) if curNode.weight < MaxWeightEdge.w: MSTE[MaxWeightEdge.u].remove(MaxWeightEdge.v) MSTE[MaxWeightEdge.v].remove(MaxWeightEdge.u) MSTE[u].pushback(Node(v, curNode.weight)) MSTE[v].pushback(Node(u, curNode.weight)) #合并 Ds.union(parentu, parentv) curNode = curNode.next return Graph(MSTV, None, MSTE, kind='nodirect')
def createLinkedList(n): graph = Graph() nodeList = [] for i in range(n): tempNode = Node(n, []) nodeList.append(tempNode) for i in range(1, len(nodeList)): nodeList[i - 1].neigh.append(nodeList[i]) for node in nodeList: graph.addNode(node) return graph
def readGFA(gfaFile): gfa = open(gfaFile).read().split('\n')[:-1] nodesSeq = dict() edges = list() for line in gfa: if line[0] == 'S': fields = line.split('\t') nodesSeq[fields[1]] = fields[2] elif line[0] == 'L': fields = line.split('\t') node1 = fields[1] node1dir = fields[2] node2 = fields[3] node2dir = fields[4] ovlp = int(fields[5][:-1]) node1len = int(fields[6]) node2len = int(fields[7]) edges.append((node1, node1dir, node2, node2dir, ovlp, node1len, node2len)) G = Graph() nxg = nx.Graph() for node1, node1dir, node2, node2dir, ovlp, node1len, node2len in edges: if node1 not in G.nodemap: n1_seq = nodesSeq[node1] assert(len(n1_seq) == node1len) n1 = Node(node1, node1len, n1_seq) else: n1 = G.nodemap[node1] if node2 not in G.nodemap: n2_seq = nodesSeq[node2] assert(len(n2_seq) == node2len) n2 = Node(node2, node1len, n2_seq) else: n2 = G.nodemap[node2] G.addEdge(n1, node1dir, n2, node2dir, ovlp) nxg.add_node(node1) nxg.add_node(node2) nxg.add_edge(node1, node2) return G, nxg
def createRandomUnweightedGraphIter(n): graph = Graph() for i in range(n): temp = Node(n, []) graph.addNode(temp) myAdjacnyList = graph.adjancyList nodes = [] random.shuffle(nodes) for node in myAdjacnyList: nodes.append(node) for i in range(1, len(nodes)): graph.addUndirectedEdge(nodes[i], nodes[i - 1]) return graph
def createRandomDAGIter(n): graph = DirectedGraph(dict()) myNodes = dict() for i in range(n+1): myNodes[i] = Node(i,[]) #Random add the nodes nodesAdded = 0 while nodesAdded <n: numb1 = random.randint(0, n) numb2 = random.randint(0,n) graph.addDirectedEdge(myNodes[numb1],myNodes[numb2]) nodesAdded = len(graph.adjancyList) return graph
def test_find_root(): a = Node.Node('a') b = Node.Node('b') c = Node.Node('c') d = Node.Node('d') e = Node.Node('e') a.dependsOn(b) a.dependsOn(d) b.dependsOn(c) b.dependsOn(e) c.dependsOn(d) c.dependsOn(e) for node in [a, b, c, d, e]: print(node.name + " parents: " + str([item.name for item in node.parents])) print("\n\n") root = [] a.find_root(e, root) assert len(root) == 1 assert root[0] == a
def __expand(self, node): directions = np.array([[-1, 0], [1, 0], [0, -1], [0, 1]]) new_nodes = [] for direction in directions: new_indizes = tuple(node.indizes + direction) if self.__occupancy_map.get_tile(new_indizes) != MapState.BLOCKED: new_node = Node(new_indizes, self.__occupancy_map.get_tile(new_indizes), [node]) new_nodes.append(new_node) pass return new_nodes pass
def test_path(n, p): nodes = [] for x in range(1, n): nodes.append(Node(x)) print 'nodes made' g = RandomGraph(nodes, []) print 'nodes added' g.add_random_edges(p) print 'edges added' start = g.nodes()[random.randrange(0, len(nodes) - 1)] dest = g.nodes()[random.randrange(0, len(nodes) - 1)] optDest = g.bfsOpt(start, dest) return g.path(optDest)
def test_is_connected(n, p): nodes = [] for x in range(0, n): n = Node(x) nodes.append(n) g = RandomGraph(nodes, []) g1 = RandomGraph(nodes, []) g1.add_all_edges() g.add_random_edges(p) # print 'number of random edges ' + `len(g.edges())` # print 'number of possible edges ' + `len(g1.edges())` return g.is_connected()
def createGrid(polygons, borders): grid = [] i = borders['top_y'] c = 0 while i <= borders['bottom_y']: row = [] j = borders['left_x'] while j <= borders['right_x']: c += 1 point = Point(j + step_x / 2.0, i + step_y / 2.0) row.append(Node(c, point, 0)) j += step_x grid.append(row) i += step_y return grid
def main(script, n='25', *args): # create n Vertices n = int(n) labels = string.ascii_lowercase + string.ascii_uppercase vs = [Node(c) for c in labels[:n]] # create a graph and a layout g = SmallWorldGraph(vs) # g.add_random_edges(.2) # g.add_all_edges() g.add_regular_edges(4) g.rewire(.20) layout = CircleLayout(g) # draw the graph gw = GraphWorld() gw.show_graph(g, layout) gw.mainloop()
def interpolate_graph(graph: Graph, interval_dist: float = 20) -> Graph: """ Linearly Interpolate the connections in the given graph, inserting nodes every interval_dist. """ interp_graph = Graph(graph.world) interp_graph.nodes = dict(graph.nodes) new_node_id = max([node_id for node_id in graph.nodes]) + 1 for connection in graph.connections: # calculate no. of intervals to next node start_node, end_node = connection.fromNode, connection.toNode start_pos, end_pos = Vector2(start_node.position), Vector2(end_node.position) node_dist = distance(start_pos, end_pos) n_intervals = int(node_dist // interval_dist) # add interval points between prev and next nnodes prev_node = start_node # interpolation exclusive of both start and end pos for i_interval in range(1, n_intervals): interp_pos = start_pos.lerp(end_pos, i_interval / n_intervals) # create interpolated node interp_node = Node( interp_graph, new_node_id, int(interp_pos[0]), int(interp_pos[1]) ) new_node_id += 1 interp_graph.nodes[new_node_id] = interp_node # create connection to interpolated node interp_graph.addConnection( prev_node, interp_node, distance(prev_node.position, interp_node.position), ) prev_node = interp_node # create connection to end node interp_graph.addConnection( prev_node, end_node, distance(prev_node.position, interp_node.position) ) return interp_graph