def test_edges(self): json_graph = {"label": "my graph", "graph": {"A": ["B"], "B": []}} graph = Graph(input_graph=json.dumps(json_graph)) self.assertEqual(json_graph['label'], graph.get_label()) self.assertEqual(False, graph.is_directed()) self.assertEqual(json_graph['graph'], graph.get_graph()) self.assertEqual([Edge('A', 'B')], graph.edges())
def test_read_graph_from_file(self): json_graph = {"label": "my graph", "graph": {"A": ["B"], "B": []}} with open(path.join(self.test_dir, 'test.txt'), 'w') as out_file: out_file.write(json.dumps(json_graph)) graph = Graph(input_file=str(path.join(self.test_dir, 'test.txt'))) self.assertEqual(json_graph["label"], graph.get_label()) self.assertEqual(False, graph.is_directed()) self.assertEqual(json_graph["graph"], graph.get_graph())
def save_to_dot(graph: Graph, out_dir: str): """ :param graph: the graph to render in dot :param out_dir: the absolute path of the gv file to write :return: """ if not graph.is_directed(): dot = GraphViz(comment=graph.get_label()) for node in graph: dot.node(node, node) for edge in graph[node]: dot.edge(node, edge) dot.render(path.join(out_dir, f"{graph.get_label()}.gv"), view=False)
def save_to_json(graph: Graph, out_dir): """ :param graph: the graph to write to json :param out_dir: the absolute path to the dir to write the file :return: """ g_dict = { "label": graph.get_label(), "directed": graph.is_directed(), "graph": graph.get_graph() } with open(path.join(out_dir, f"{graph.get_label()}.json"), 'w', encoding="utf8") as out: out.write(json.dumps(g_dict))
def is_complete(graph: Graph) -> bool: """ Checks that each vertex has V(V-1) / 2 edges and that each vertex is connected to V - 1 others. runtime: O(n^2) :param graph: :return: true or false """ V = len(graph.vertices()) max_edges = (V**2 - V) if not graph.is_directed(): max_edges //= 2 E = len(graph.edges()) if E != max_edges: return False for vertex in graph: if len(graph[vertex]) != V - 1: return False return True