|
2 | 2 | A multi-domain network connecting entities across social, geographical, and commercial dimensions. |
3 | 3 | """ |
4 | 4 |
|
| 5 | +import os |
5 | 6 | from typing import Optional |
6 | 7 | import networkx as nx |
7 | 8 | import random |
@@ -318,3 +319,35 @@ def generate_graph( |
318 | 319 | ) |
319 | 320 | else: |
320 | 321 | raise ValueError(f"Unknown source '{source}'. Use 'random' or 'osm'.") |
| 322 | + |
| 323 | + def export_graph(self, G: nx.Graph = None, path: str = "graph.graphml"): |
| 324 | + """ |
| 325 | + Export the graph to a GraphML format. |
| 326 | +
|
| 327 | + args: |
| 328 | + G: Optional Networkx graph. If None, uses self.G. |
| 329 | + path: Destination file path for .graphml output. |
| 330 | + |
| 331 | + Notes: |
| 332 | + GraphML is useful for visualization in tools like G.V(), Gephi or Cytoscape. |
| 333 | + It supports node and edge attributes but may not handle complex types like tuples. |
| 334 | + """ |
| 335 | + import os |
| 336 | + |
| 337 | + if G is None: |
| 338 | + G = self.G |
| 339 | + if G is None: |
| 340 | + raise ValueError("No graph available to export.") |
| 341 | + |
| 342 | + # Sanitize attributes that are not GraphML-friendly |
| 343 | + for _, data in G.nodes(data=True): |
| 344 | + if 'coordinates' in data and isinstance(data['coordinates'], tuple): |
| 345 | + lat, lon = data['coordinates'] |
| 346 | + data['coordinates'] = f"{lat},{lon}" |
| 347 | + |
| 348 | + # Ensure directory exists |
| 349 | + abs_path = os.path.abspath(path) |
| 350 | + os.makedirs(os.path.dirname(abs_path) or ".", exist_ok=True) |
| 351 | + |
| 352 | + nx.write_graphml(G, path) |
| 353 | + print(f"✅ Graph exported to: {path}") |
0 commit comments