def bfs(self, src: NodeData, list_i: [NodeData], in_or_out: bool): """ Implementation of bfs algorithm. :param src: NodeData the source node :param list_i: list[NodeData] A list that we wish to add all the available nodes from the source node :param in_or_out: bool if True then the traversal is on the original graph, else the traversal is on the opposite direction :return:None """ if src in self.get_graph().get_all_v().values(): q = [] src.set_info('Visited') q.append(src) list_i.append(src) while len(q) > 0: temp = q.pop() if in_or_out: nodes_ni_list = self.get_graph().get_node_list(self.get_graph().all_out_edges_of_node(temp.get_key()).keys()) else: nodes_ni_list = self.get_graph().get_node_list(self.get_graph().all_in_edges_of_node(temp.get_key()).keys()) for neighbor in nodes_ni_list: if neighbor.get_info() != 'Visited': neighbor.set_info('Visited') q.append(neighbor) list_i.append(neighbor)
def load_from_json(self, file_name: str) -> bool: """This function loads a graph to graph algorithm from JSON format file. If the file was successfully loaded - the graph will be changed, If graph was not loaded the original graph should remain "as is". @param file_name - file name @return true - if the graph was successfully loaded.""" try: self.my_g = DiGraph() fp = open(file_name, 'r') temp_graph = json.load(fp) edges_dic = temp_graph.get('Edges') nodes_dic = temp_graph.get('Nodes') for i in nodes_dic: if i.get('pos') is not None: pos_i = i['pos'] pos_list = pos_i.split(sep=",", maxsplit=2) temp_id = i.get('id') self.my_g.add_node(node_id=NodeData(temp_id).id, pos=(float(pos_list[0]), float(pos_list[1]), float(pos_list[2]))) else: temp_id = i.get('id') self.my_g.add_node(node_id=NodeData(temp_id).id) for j in edges_dic: weight = j.get('w') src = j.get('src') dest = j.get('dest') self.my_g.add_edge(src, dest, weight) fp.close() except FileExistsError: return False return True
def load_from_json(self, file_name): try: with open(file_name,"r") as file: d=json.load(file) g=DiGraph() temp={} nodes=d["Nodes"] edges=d["Edges"] for i in nodes: n=NodeData(i["id"]) a={} c=0; for s in i["pos"].split(","): a[c]=s c+=1 n.setLocation(a[0],a[1],a[2]) g.add_node(n.key,n.geo) for j in edges: g.add_edge(j["src"],j["dest"],j["w"]) self.graph=g print(2>1) except IOError as e: print(e) return 0
def setUp(self): global g g = DiGraph() g.add_node(NodeData(-101).id) g.add_node(NodeData(-15).id) g.add_node(NodeData(-1).id) g.add_node(NodeData(0).id) g.add_node(NodeData(3).id) g.add_node(NodeData(13).id) g.add_node(NodeData(53).id) g.add_node(NodeData(66).id) g.add_node(NodeData(555).id) g.add_edge(53, 13, 6.0) g.add_edge(53, 555, 2.1) g.add_edge(13, 3, 8.9) g.add_edge(3, 13, 8.9) g.add_edge(3, -15, 0.1) g.add_edge(-15, -1, 10) g.add_edge(-1, -101, 20) g.add_edge(-101, 3, 7.6) g.add_edge(-101, 0, 12) g.add_edge(0, -101, 21) g.add_edge(0, 555, 3.2) g.add_edge(555, 66, 2) g.add_edge(66, 0, 3.3)
def add_node(self, node_id, pos=0): if (node_id in self.graph): return (2 < 1) else: n = NodeData(node_id) n.geo = pos self.graph[node_id] = n self.mc += 1 return (2 > 1)
def add_node(self, node_id: int, pos: tuple = None) -> bool: if node_id in self._nodes: return False self._nodes[node_id] = NodeData(node_id, pos) # pos in default = None self._mc += 1 self._num_of_nodes += 1 return True
def add_node(self, node_id: int, pos: tuple = None) -> bool: if self._graph.get(node_id) is None: self._graph[node_id] = NodeData(key=node_id, pos=pos) self._edge_src[node_id] = dict() self._edge_dest[node_id] = dict() self._mc += 1 return True return False
def bfs_to(self, starting_node: NodeData) -> list: queue = [starting_node] connected_to = [starting_node.get_key()] visited = {} for node_key in self._graph.get_all_v(): visited[node_key] = False visited[starting_node.get_key()] = True while len(queue): # while the queue is not empty node_from_queue = queue.pop() for edge_to_node_key in node_from_queue.get_all_edges_to_node(): if not visited[edge_to_node_key]: queue.insert(0, self._graph.get_node(edge_to_node_key)) connected_to.append(edge_to_node_key) visited[edge_to_node_key] = True return connected_to
def add_node(self, node_id: int, pos: tuple = None) -> bool: if node_id not in self.NodeMap: node = NodeData(node_id, pos) self.NodeMap[node_id] = node self.MC = self.MC + 1 return True else: return False
def test_add_node_neg(self): temp1 = g.v_size() g.add_node(NodeData(-60).id) temp2 = g.v_size() self.assertEqual(-60, g.get_node(-60).id, "add_node didn't add a positive node") self.assertEqual(temp1 + 1, temp2, "add_node didn't add a positive node")
def bfs(u, v) -> list: api = datamuse.Datamuse() SFMap = {} q = deque() q.append(u) SFMap[u.title] = NodeData(0, None) lst = createList(v, api) while q: u = q.popleft() print("Popping " + u.title + "...") if u == v: return pathify(SFMap, v) for pageTitle in u.links: if (len(list) == 1 or pageTitle.lower() in lst): try: wikiPage = wikipedia.page(pageTitle, auto_suggest=False) except wikipedia.DisambiguationError: continue except wikipedia.PageError: continue pageDist = 1 + SFMap.get(u.title).dist if (wikiPage.title not in SFMap): print("Adding " + pageTitle + "...") SFMap[wikiPage.title] = NodeData(pageDist, u) q.append(wikiPage) if (len(q) % 100 == 0): print("Queue Size: " + str(len(q)) + " articles!") print("\n") #if (pageTitle == v.title): if (wikipage == v): q.appendleft(wikiPage) break return []
def add_node(self, node_id: int, pos: tuple = None) -> bool: """Add a new node to the graph with the node_id that was received. @param node_id @param pos @return true if success.""" if node_id in self.vertices: return False self.vertices[node_id] = NodeData(node_id, 0, pos) if len(self.vertices) == self.node_size + 1: self.node_size = self.node_size + 1 self.mc = self.mc + 1 return True
def add_node(self, node_id: int, pos: tuple = None) -> bool: """ Adds a node to the graph. @param node_id: The node ID @param pos: The position of the node @return: True if the node was added successfully, False o.w. Note: if the node id already exists the node will not be added """ if node_id not in self.my_graph.keys(): self.my_graph[node_id] = NodeData(node_id, pos) self.mc += 1 return True
def add_node(self, node_id: int, pos: tuple = None) -> bool: """ This function add a vertex to the given graph :param node_id: the key of the node :param pos: the location of the node :return: boolean->true if the node was added to the graph, else false """ if node_id in self.nodes.keys( ): # if the given node_id is in the graph return false return False self.MC_counter += 1 v = NodeData(node_id, pos) # defining new vertex self.nodes[ node_id] = v # update add the given key to the dictionary vertices and if it exist return True
def add_node(self, node_id: int, pos: tuple = None) -> bool: """ Adds a node to the graph. @param node_id: The node ID @param pos: The position of the node @return: True if the node was added successfully, False o.w. Note: if the node id already exists the node will not be added """ if self.__vertices.get(node_id) is None: self.__vertices[node_id] = NodeData(node_id, pos) self.__neighbors_in[node_id] = {} self.__neighbors_out[node_id] = {} self.__mc += 1 return True return False
def add_node(self, node_id: int, pos: tuple = None): """ Add a new node to the graph, if there is already a node with the given key on the graph then the function will do nothing. :param node_id: int the id of the node we want to add to the graph :param pos: float the position we want to place the node :return: bool True if succeed, else False """ if node_id not in self.__nodes_in_graph: tmp = NodeData(node_id, pos) self.__nodes_in_graph[node_id] = tmp self.__neighbors[node_id] = {} self.__pointers[node_id] = {} self.__mc_counter = self.__mc_counter + 1 return True else: return False
def createNode(self, node_name, domain_name=None): """ :return: new empty node and links it to DialogData.NodeData, extends _domains if domainName is not in yet :return: None if node of the name already exists """ # Update domain structure, add node to corresponding domain if domain_name is not None: # make sure the domain is registered if domain_name not in self._domains: self._domains[domain_name] = [] # make sure the nodeName is remembered within the domain # if node_name not in self._nodes[domain_name]: if node_name not in self._domains[domain_name]: self._domains[domain_name].append(node_name) # Update nodes structure, if node is not there yet - add it if node_name not in self._nodes: self._nodes[node_name] = NodeData() return self._nodes[node_name] else: logger.info('Node of given name already exists. node_name=%s', node_name) return None
def test_save_and_loads(self): g = DiGraph() g.add_node(NodeData(0).id, pos=(1, 1, 2)) g.add_node(NodeData(3).id) g.add_node(NodeData(13).id) g.add_edge(0, 13, 8.9) g.add_edge(3, 13, 8.9) ga = GraphAlgo(g) g1 = DiGraph() g1.add_node(NodeData(0).id, pos=(1, 1, 2)) g1.add_node(NodeData(3).id) g1.add_node(NodeData(13).id) g1.add_edge(0, 13, 8.9) g1.add_edge(3, 13, 8.9) ga.save_to_json("save_test.json") ga1 = GraphAlgo(None) ga1.load_from_json("save_test.json") g2 = ga1.get_graph() self.assertEqual(g1.__str__(), g2.__str__(), "load return different graph")
def test_v_size_after_add_node(self): g.add_node(NodeData(10).id) g.add_node(NodeData(16).id) g.add_node(NodeData(3).id) self.assertEqual(11, g.v_size(), "v_size didn't update the nodeSize after adding")
def create_node(self, node_id, node_code): if ((node_id not in self.node_dict)): nodedata = NodeData(node_id, node_code, self) self.node_dict.update({node_id: nodedata})
def test_shortest_path_dist_no_dist(self): g.add_node(NodeData(16).id) self.assertEqual(-1, ga.shortest_path_dist(0, 16), "shortest_path_dist returns uncorrected dist")
return (2 < 1) def remove_edge(self, node_id1, node_id2): if (node_id1 in self.graph and node_id2 in self.graph): if (node_id2 in self.graph[node_id1].neighbors): self.graph[node_id1].neighbors.pop(node_id2) self.edgeSize -= 1 self.mc += 1 return (2 > 1) else: return (2 < 1) else: return (2 < 1) if __name__ == "__main__": t = DiGraph() t2 = NodeData(1, 7) t.graph[1] = t2 t3 = NodeData(2, 99) t2.createEdge(1, 2, 9) t.graph[2] = t3 t4 = NodeData(3, 4) t4.createEdge(3, 2, 8) t.graph[3] = t4 #print(t.all_out_edges_of_node(1)) #print(t.add_node()) #print(t.add_edge(3,3,9)) print(t.remove_edge(1, 2))
def __init__(self): Node.nodes.append(NodeData()) self.id = Node.unique_id Node.unique_id += 1
def __init__(self, r=-1, c=-1, n=-1): self.data = NodeData(r,c,n) self.left = self self.right = self self.up = self self.down = self
def test_get_mc_after_add_node(self): g.add_node(NodeData(10).id) g.add_node(NodeData(16).id) g.add_node(NodeData(0).id) self.assertEqual(24, g.get_mc(), "get_mc didn't update MC after adding the node")
xy=(self.graph.graph[key].geo.x, self.graph.graph[key].geo.y)) for kei in self.graph.graph[key].neighbors.keys(): plt.annotate(key, xy=(self.graph.graph[kei].geo.x, self.graph.graph[kei].geo.y), xycoords='data', xytext=(self.graph.graph[key].geo.x, self.graph.graph[key].geo.y), textcoords='data', arrowprops=dict(facecolor='g')) plt.legend(loc='upper left') plt.title("Graph") plt.show() if __name__ == "__main__": g4 = DiGraph() for i in range(4): g4.add_node(i) g4.graph[i].geo=NodeData.Location() g4.graph[i].geo.x=random.uniform(0.0,4) g4.graph[i].geo.y = random.uniform(0.0, 3) g4.add_edge(0, 1, 0); g4.add_edge(2, 3, 0); g4.add_edge(1, 3, 0); g=GraphAlgo() g.graph=g4 g.plot_graph()