File size: 1,112 Bytes
651b674
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
"""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