Transformer fundamentals
 
Loading...
Searching...
No Matches
load_dot_file.py
Go to the documentation of this file.
1import os
2import sys
3
4import matplotlib.pyplot as plt
5import networkx as nx
6import pydot
7from graph_utils import Graph
8
9
10def direct_load_dot(dot_file_path):
11 """
12 @brief Load a DOT file directly with pydot, bypassing NetworkX's parser.
13
14 @param dot_file_path: Path to the DOT file
15
16 @return A NetworkX DiGraph object
17 """
18 try:
19 print("Attempting to load DOT file directly with pydot...")
20 graphs = pydot.graph_from_dot_file(dot_file_path)
21
22 if not graphs:
23 print("No graphs found in the DOT file.")
24 return None
25
26 dot_graph = graphs[0]
27 print(f"DOT graph loaded successfully. Type: {dot_graph.get_type()}")
28
29 # Convert to NetworkX graph
30 if dot_graph.get_type() == "graph":
31 graph = nx.Graph()
32 else:
33 graph = nx.DiGraph()
34
35 # Manual conversion without using nx_pydot
36 # Add nodes
37 for node in dot_graph.get_nodes():
38 node_name = node.get_name().strip('"')
39 attrs = {
40 k.strip('"'): v.strip('"') for k, v in node.get_attributes().items()
41 }
42 graph.add_node(node_name, **attrs)
43
44 # Add edges
45 for edge in dot_graph.get_edges():
46 source = edge.get_source().strip('"')
47 target = edge.get_destination().strip('"')
48 attrs = {
49 k.strip('"'): v.strip('"') for k, v in edge.get_attributes().items()
50 }
51 graph.add_edge(source, target, **attrs)
52
53 print(
54 f"Converted to NetworkX graph with {graph.number_of_nodes()} nodes and {graph.number_of_edges()} edges"
55 )
56 return graph
57
58 except Exception as e:
59 print(f"Error in direct_load_dot: {e}")
60 import traceback
61
62 traceback.print_exc()
63 return None
64
65
66def load_and_display_dot_file(dot_file_path):
67 """
68 Load a .dot file and display it using both GraphViz and Matplotlib.
69
70 Args:
71 dot_file_path: Path to the .dot file
72 """
73 # Run debug to check package versions
74
75 # Create output directory if it doesn't exist
76 os.makedirs("graph_output", exist_ok=True)
77
78 # Get the base filename without extension
79 base_name = os.path.splitext(os.path.basename(dot_file_path))[0]
80
81 # Try to load the graph directly with pydot first
82 graph = direct_load_dot(dot_file_path)
83
84 if graph:
85 print(f"\nGraph Information:")
86 print(f"Nodes: {graph.number_of_nodes()}")
87 print(f"Edges: {graph.number_of_edges()}")
88
89 # Save visualizations
90 print("\nSaving visualizations to files:")
91
92 try:
93 # Try to save with pydot directly first
94 print("Saving with pydot...")
95 pydot_graph = nx.drawing.nx_pydot.to_pydot(graph)
96
97 # GraphViz with dot layout
98 output_file = f"graph_output/{base_name}_dot.png"
99 pydot_graph.write_png(output_file, prog="dot")
100 print(f"GraphViz dot visualization saved to {output_file}")
101
102 # GraphViz with neato layout
103 output_file = f"graph_output/{base_name}_neato.png"
104 pydot_graph.write_png(output_file, prog="neato")
105 print(f"GraphViz neato visualization saved to {output_file}")
106
107 except Exception as e:
108 print(f"Error saving with pydot: {e}")
109
110 try:
111 # Matplotlib
112 print("Saving with matplotlib...")
113 output_file = f"graph_output/{base_name}_matplotlib.png"
114 plt.figure(figsize=(12, 10))
115 pos = nx.spring_layout(graph, seed=42)
116 nx.draw(
117 graph,
118 pos,
119 with_labels=True,
120 node_color="lightblue",
121 node_size=1500,
122 arrows=True if nx.is_directed(graph) else False,
123 arrowsize=20,
124 edge_color="gray",
125 )
126 plt.savefig(output_file)
127 plt.close()
128 print(f"Matplotlib visualization saved to {output_file}")
129
130 except Exception as e:
131 print(f"Error saving with matplotlib: {e}")
132
133 print(f"\nAll available visualizations saved to 'graph_output' directory.")
134 else:
135 print(f"Failed to load {dot_file_path}")
136
137 # Try with your original Graph class as a fallback
138 print("\nTrying with original Graph class...")
139 try:
140 g = Graph()
141 if g.load_from_dot(dot_file_path):
142 print(f"\nGraph Information:")
143 print(f"Nodes: {g.get_node_count()}")
144 print(f"Edges: {g.get_edge_count()}")
145
146 # Save visualizations with different layouts
147 print("\nSaving visualizations to files:")
148
149 # GraphViz with dot layout
150 output_file = f"graph_output/{base_name}_dot.png"
151 g.display_with_graphviz(layout="dot", output_file=output_file)
152
153 # GraphViz with neato layout
154 output_file = f"graph_output/{base_name}_neato.png"
155 g.display_with_graphviz(layout="neato", output_file=output_file)
156
157 # Matplotlib
158 output_file = f"graph_output/{base_name}_matplotlib.png"
159 g.display_with_matplotlib(output_file=output_file)
160
161 print(f"\nAll visualizations saved to 'graph_output' directory.")
162 else:
163 print(f"Failed to load {dot_file_path} with Graph class")
164 except Exception as e:
165 print(f"Error with Graph class: {e}")
166 import traceback
167
168 traceback.print_exc()
169
170
171if __name__ == "__main__":
172 # Check if a file path was provided as an argument
173 if len(sys.argv) > 1:
174 dot_file_path = sys.argv[1]
175 load_and_display_dot_file(dot_file_path)
176 else:
177 # Use the sample graph if no argument provided
178 if os.path.exists("sample_graph.dot"):
179 print("No .dot file specified. Using 'sample_graph.dot'.")
180 load_and_display_dot_file("sample_graph.dot")
181 else:
182 print("No .dot file specified and sample_graph.dot doesn't exist.")
183 print("Please provide a .dot file path as an argument.")
Attempting to create a custom Graph class that can load, manipulate, and visualize graphs from ....
load_and_display_dot_file(dot_file_path)
Load a .dot file and display it using both GraphViz and Matplotlib.
direct_load_dot(dot_file_path)
Load a DOT file directly with pydot, bypassing NetworkX's parser.