5import matplotlib.pyplot
as plt
9from IPython.display
import Image, display
14 @brief Attempting to create a custom Graph class that can load, manipulate, and visualize graphs from .dot files
15 these are basic graphs right now
20 @brief Initalize an empty graph
22 @param self: the current graph object
28 @brief Loads a graph from a .dot file.
30 @param file_path: Path to the .dot file
32 @return bool: True if successful, False if fails for any reason
36 graphs = pydot.graph_from_dot_file(file_path)
38 print(
"No graphs was found in the .dot file (check the file maybe?)")
42 if dot_graph.get_type() ==
"graph":
43 self.
graph = nx.Graph(nx.drawing.nx_pydot.from_pydot(dot_graph))
45 self.
graph = nx.DiGraph(nx.drawing.nx_pydot.from_pydot(dot_graph))
47 f
"Success: Graph with {len(list(self.graph.nodes()))} nodes and {len(self.graph.edges())} edges"
51 except Exception
as e:
52 print(f
"Error loading .dot file: {e}")
57 @brief Add a node to the current graph
59 @param self: the current graph object
60 @param node_id: tage for the node
61 @param **attributes: optional node features
67 @brief Add an edge to the graph
69 @param self: the current graph object
70 @param start: The node to start at
71 @param dest: the node to end at
72 @param **attributes: optional edge features
78 @brief Save the current graph to a .dot file
80 @param self: the current graph object
81 @param file_path: output file path
82 @return bool: True if success, false if something failed
86 pydot_graph = nx.drawing.nx_pydot.to_pydot(self.
graph)
88 pydot_graph.write_dot(file_path)
89 print(f
"Graph saved to {file_path}")
91 except Exception
as e:
92 print(f
"Error saving graph to .dot file: {e}")
96 self, layout="dot", format="png", show=True, output_file=None
99 @brief Visualize with GraphViz by creating a png
101 @param layout: GraphViz layout type ('dot', 'neato', 'fdp', 'sfdp', 'twopi', 'circo')
102 @param format: Output format ('png', 'svg', 'pdf', etc.)
103 @param show: Display the graph (if true) or return the image data (false)
104 @return bytes or None: Image data if show=False, otherwise None
108 pydot_graph = nx.drawing.nx_pydot.to_pydot(self.
graph)
111 pydot_graph.set_layout(layout)
115 pydot_graph.write(output_file, format=format)
116 print(f
"Graph visualization saved to {output_file}")
120 with tempfile.NamedTemporaryFile(suffix=f
".{format}", delete=
False)
as tmp:
124 pydot_graph.write(temp_name, format=format)
129 img = Image(filename=temp_name)
131 except (NameError, ImportError):
133 print(f
"Graph saved to temporary file: {temp_name}")
135 "(Note: Interactive display not available in terminal environment)"
140 with open(temp_name,
"rb")
as f:
145 except Exception
as e:
146 print(f
"Error displaying graph: {e}")
153 node_color="skyblue",
161 @brief Trying and seeing how visualization of graphs with Matplotlib looks like.
163 @param layout: the layout algorithm used
164 @param node_size: size of nodes
165 @param node_color: color of nodes
166 @param edge_color: color of edges
167 @param with_labels: whether to display node labels
168 @param font_size: size of node labels
169 @param figsize: figure size
173 fig = plt.figure(figsize=figsize)
178 if nx.is_directed(self.
graph):
179 pos = nx.spring_layout(self.
graph)
183 pos = nx.kamada_kawai_layout(self.
graph)
185 pos = nx.spring_layout(self.
graph)
188 pos = layout(self.
graph)
194 with_labels=with_labels,
196 node_color=node_color,
197 edge_color=edge_color,
202 plt.gca().set_axis_off()
209 plt.savefig(output_file)
211 print(f
"Matplotlib visualization saved to {output_file}")
216 except Exception
as e:
218 temp_file = f
"graph_matplotlib_{int(time.time())}.png"
219 plt.savefig(temp_file)
221 print(f
"Matplotlib visualization saved to {temp_file}")
223 "(Note: Interactive display not available in terminal environment)"
226 except Exception
as e:
227 print(f
"Error displaying graph with matplotlib: {e}")
230 traceback.print_exc()
234 @brief return the number of nodes in the graph.
235 @return num of nodes in graph
237 return len(list(self.
graph.nodes()))
241 @brief return the number of edges in the graph.
242 @return num of edges in graph
244 return len(self.
graph.edges())
248 @brief return the list of nodes in the graph
249 @return list of nodes in graph
251 return list(self.
graph.nodes())
255 @brief return the list of edges in the graph
256 @return list of edges in graph
258 return list(self.
graph.edges())
262 @brief return successors of a node
263 @param node: the node which will be check for successor
264 @return list of successors from node
266 return list(self.
graph.successors(node))
270 @brief reutrn the predessors of a node
271 @param node: the node which predecessors will be checked from
272 @return list of predecessors from node
274 return list(self.
graph.predecessors(node))
278 @brief return the adjacency matrix of the graph
280 @param weight: Edge data weight. If none, all adges have weight 1. If a
281 string, the edge attribute. If a function, the value
282 returned by the function is used
283 @return numpy array: the adjacency matrix of the graph. Rows and columns
284 are ordred according to the node list obtained by
285 self.get_nodes(). Non-existent edges are represented by zeroes
288 adj_matrix = nx.to_numpy_array(
293 except Exception
as e:
294 print(f
"Error generating adjacency matrix: {e}")
297 traceback.print_exc()
306 node_to_idx = {node: i
for i, node
in enumerate(nodes)}
309 adj_matrix = np.zeros((n, n))
312 for u, v, data
in self.
graph.edges(data=
True):
313 i, j = node_to_idx[u], node_to_idx[v]
318 elif callable(weight):
320 adj_matrix[i, j] = weight(data)
323 adj_matrix[i, j] = float(data[weight])
329 if not nx.is_directed(self.
graph):
330 adj_matrix[j, i] = adj_matrix[i, j]
334 except Exception
as e:
335 print(f
"Fallback adjacency matrix calculation failed: {e}")
336 traceback.print_exc()
Attempting to create a custom Graph class that can load, manipulate, and visualize graphs from ....
display_with_matplotlib(self, layout=None, node_size=300, node_color="skyblue", edge_color="black", with_labels=True, font_size=10, figsize=(8, 6), output_file=None)
Trying and seeing how visualization of graphs with Matplotlib looks like.
get_adjacency_matrix(self, weight=None)
return the adjacency matrix of the graph
add_node(self, node_id, **attributes)
Add a node to the current graph.
get_successors(self, node)
return successors of a node
get_nodes(self)
return the list of nodes in the graph
get_predecessors(self, node)
reutrn the predessors of a node
__init__(self)
Initalize an empty graph.
get_edge_count(self)
return the number of edges in the graph.
save_to_dot(self, file_path)
Save the current graph to a .dot file.
add_edge(self, start, dest, **attributes)
Add an edge to the graph.
get_edges(self)
return the list of edges in the graph
load_from_dot(self, file_path)
Loads a graph from a .dot file.
get_node_count(self)
return the number of nodes in the graph.
display_with_graphviz(self, layout="dot", format="png", show=True, output_file=None)
Visualize with GraphViz by creating a png.