Monyzik's picture
Stage frozen training inputs privately for owner review
651b674 verified
Raw History Blame Contribute Delete
1.11 kB
"""Optional NetworkX bridge for algorithms on the portable graph snapshot."""
from copy import deepcopy
from typing import TYPE_CHECKING
from compact_fact_extraction.graph import validate_graph
if TYPE_CHECKING:
from networkx import MultiDiGraph
def to_networkx(graph: dict) -> "MultiDiGraph":
"""Keep IDs, directed parallel edges and provenance when adapting to NetworkX."""
validate_graph(graph)
try:
import networkx as nx
except ImportError as exc:
raise ImportError('Install the optional graph extra: pip install -e ".[graph]"') from exc
result = nx.MultiDiGraph(
graph_id=graph["graph_id"],
format_version=graph["format_version"],
metadata=deepcopy(graph["metadata"]),
sources=deepcopy(graph["sources"]),
)
for node in graph["nodes"]:
result.add_node(node["id"], **deepcopy(node))
for edge in graph["edges"]:
attributes = deepcopy(edge)
source, target = attributes.pop("source"), attributes.pop("target")
result.add_edge(source, target, key=edge["id"], **attributes)
return result