|
18 | 18 |
|
19 | 19 | from gqlalchemy.exceptions import raise_if_not_imported |
20 | 20 | import gqlalchemy.memgraph_constants as mg_consts |
| 21 | +import networkx as nx |
| 22 | +import json |
| 23 | +import re |
| 24 | +from collections import defaultdict |
| 25 | +from typing import Any, Dict |
21 | 26 |
|
22 | 27 | try: |
23 | 28 | from gqlalchemy.transformations.translators.dgl_translator import DGLTranslator |
|
31 | 36 | except ModuleNotFoundError: |
32 | 37 | PyGTranslator = None |
33 | 38 |
|
| 39 | +try: |
| 40 | + import pydot |
| 41 | +except ModuleNotFoundError: |
| 42 | + pydot = None |
| 43 | + |
34 | 44 |
|
35 | 45 | class GraphImporter(Importer): |
36 | 46 | """Imports dgl, pyg or networkx graph representations to Memgraph. |
@@ -69,8 +79,142 @@ def __init__( |
69 | 79 | def translate(self, graph) -> None: |
70 | 80 | """Gets cypher queries using the underlying translator and then inserts all queries to Memgraph DB. |
71 | 81 | Args: |
72 | | - graph: dgl, pytorch geometric or nx graph instance. |
| 82 | + graph: dgl, pytorch geometric, dot or nx graph instance. |
73 | 83 | """ |
74 | 84 | memgraph = Memgraph() |
75 | 85 | for query in self.translator.to_cypher_queries(graph): |
76 | 86 | memgraph.execute(query) |
| 87 | + |
| 88 | + def translate_dot_file(self, path: str) -> None: |
| 89 | + """Parses a DOT file to a NetworkX graph and imports it to Memgraph.""" |
| 90 | + self._raise_if_not_nx_importer() |
| 91 | + raise_if_not_imported(dependency=pydot, dependency_name="pydot") |
| 92 | + |
| 93 | + pydot_graphs = pydot.graph_from_dot_file(path) |
| 94 | + if not pydot_graphs: |
| 95 | + raise ValueError("Unable to parse DOT file.") |
| 96 | + |
| 97 | + graph = self._normalize_dot_graph(self._graph_from_pydot(pydot_graphs[0])) |
| 98 | + self.translate(graph) |
| 99 | + |
| 100 | + def translate_dot_data(self, dot_data: str) -> None: |
| 101 | + """Parses DOT content to a NetworkX graph and imports it to Memgraph.""" |
| 102 | + self._raise_if_not_nx_importer() |
| 103 | + raise_if_not_imported(dependency=pydot, dependency_name="pydot") |
| 104 | + |
| 105 | + pydot_graphs = pydot.graph_from_dot_data(dot_data) |
| 106 | + if not pydot_graphs: |
| 107 | + raise ValueError("Unable to parse DOT data.") |
| 108 | + |
| 109 | + graph = self._normalize_dot_graph(self._graph_from_pydot(pydot_graphs[0])) |
| 110 | + self.translate(graph) |
| 111 | + |
| 112 | + def _raise_if_not_nx_importer(self) -> None: |
| 113 | + if self.graph_type != GraphType.NX.name: |
| 114 | + raise ValueError("DOT import is supported only for NetworkX graph importer.") |
| 115 | + |
| 116 | + def _normalize_dot_graph(self, graph: nx.Graph) -> nx.Graph: |
| 117 | + """Enriches raw DOT graphs with stable, Cypher-friendly metadata.""" |
| 118 | + normalized_graph = graph.__class__() |
| 119 | + edge_ids = defaultdict(int) |
| 120 | + sequence = 0 |
| 121 | + |
| 122 | + for node_id, data in graph.nodes(data=True): |
| 123 | + node_properties = self._normalize_dot_properties(data) |
| 124 | + node_properties["dot_type"] = "node" |
| 125 | + node_properties["display_name"] = node_properties.get("attributes_label", str(node_id)) |
| 126 | + node_properties["source_graph"] = "dot" |
| 127 | + node_properties["sequence"] = sequence |
| 128 | + sequence += 1 |
| 129 | + if "id" not in node_properties: |
| 130 | + node_properties["id"] = self._normalize_dot_value(node_id) |
| 131 | + normalized_graph.add_node(node_id, **node_properties) |
| 132 | + |
| 133 | + for source, dest, data in graph.edges(data=True): |
| 134 | + edge_properties = self._normalize_dot_properties(data) |
| 135 | + edge_properties["dot_type"] = "edge" |
| 136 | + edge_properties["type"] = "DOT_EDGE" |
| 137 | + edge_key = f"{source}->{dest}" |
| 138 | + edge_index = edge_ids[edge_key] |
| 139 | + edge_ids[edge_key] += 1 |
| 140 | + edge_id = edge_key if edge_index == 0 else f"{edge_key}#{edge_index}" |
| 141 | + edge_properties["id"] = self._normalize_dot_value(edge_id) |
| 142 | + edge_properties["points"] = [self._normalize_dot_value(source), self._normalize_dot_value(dest)] |
| 143 | + edge_properties["sequence"] = sequence |
| 144 | + sequence += 1 |
| 145 | + normalized_graph.add_edge(source, dest, **edge_properties) |
| 146 | + |
| 147 | + return normalized_graph |
| 148 | + |
| 149 | + def _graph_from_pydot(self, dot_graph) -> nx.MultiDiGraph: |
| 150 | + """Builds a MultiDiGraph from a pydot graph.""" |
| 151 | + graph = nx.MultiDiGraph() |
| 152 | + |
| 153 | + def _walk(current_graph) -> None: |
| 154 | + for node in current_graph.get_nodes(): |
| 155 | + node_id = self._normalize_dot_value(node.get_name()) |
| 156 | + # Ignore pydot/graphviz pseudo-nodes used for defaults. |
| 157 | + if node_id in {"", "node", "edge", "graph"}: |
| 158 | + continue |
| 159 | + |
| 160 | + properties = self._normalize_dot_attributes(node.get_attributes() or {}) |
| 161 | + if node_id in graph.nodes: |
| 162 | + graph.nodes[node_id].update(properties) |
| 163 | + else: |
| 164 | + graph.add_node(node_id, **properties) |
| 165 | + |
| 166 | + for edge in current_graph.get_edges(): |
| 167 | + source = self._normalize_dot_value(edge.get_source()) |
| 168 | + dest = self._normalize_dot_value(edge.get_destination()) |
| 169 | + if not source or not dest: |
| 170 | + continue |
| 171 | + |
| 172 | + properties = self._normalize_dot_attributes(edge.get_attributes() or {}) |
| 173 | + graph.add_edge(source, dest, **properties) |
| 174 | + |
| 175 | + for subgraph in current_graph.get_subgraphs(): |
| 176 | + _walk(subgraph) |
| 177 | + |
| 178 | + _walk(dot_graph) |
| 179 | + |
| 180 | + return graph |
| 181 | + |
| 182 | + def _normalize_dot_properties(self, properties: Dict[str, Any]) -> Dict[str, Any]: |
| 183 | + normalized_attributes = self._normalize_dot_attributes(properties) |
| 184 | + normalized_properties: Dict[str, Any] = dict(normalized_attributes) |
| 185 | + normalized_properties["attributes_json"] = json.dumps(normalized_attributes, sort_keys=True) |
| 186 | + |
| 187 | + for key, value in normalized_attributes.items(): |
| 188 | + prefixed_key = f"attributes_{key}" |
| 189 | + while prefixed_key in normalized_properties: |
| 190 | + prefixed_key = f"{prefixed_key}_attribute" |
| 191 | + normalized_properties[prefixed_key] = value |
| 192 | + |
| 193 | + return normalized_properties |
| 194 | + |
| 195 | + def _normalize_dot_attributes(self, attributes: Dict[str, Any]) -> Dict[str, Any]: |
| 196 | + normalized_attributes: Dict[str, Any] = {} |
| 197 | + for key, value in attributes.items(): |
| 198 | + sanitized_key = self._sanitize_property_key(key) |
| 199 | + unique_key = self._resolve_key_collision(sanitized_key, normalized_attributes) |
| 200 | + normalized_attributes[unique_key] = self._normalize_dot_value(value) |
| 201 | + return normalized_attributes |
| 202 | + |
| 203 | + @staticmethod |
| 204 | + def _resolve_key_collision(base_key: str, properties: Dict[str, Any]) -> str: |
| 205 | + unique_key = base_key |
| 206 | + suffix = 1 |
| 207 | + while unique_key in properties: |
| 208 | + unique_key = f"{base_key}_{suffix}" |
| 209 | + suffix += 1 |
| 210 | + return unique_key |
| 211 | + |
| 212 | + @staticmethod |
| 213 | + def _normalize_dot_value(value: Any) -> Any: |
| 214 | + if isinstance(value, str): |
| 215 | + return value.strip().strip('"') |
| 216 | + return value |
| 217 | + |
| 218 | + @staticmethod |
| 219 | + def _sanitize_property_key(key: str) -> str: |
| 220 | + return re.sub(r"[^0-9A-Za-z_]", "_", key) |
0 commit comments