Build a NetworkX graph from graphify node/edge dicts. Preserves original edge direction as _src/_tgt attributes so that display functions can show relationships in the correct direction, even though the graph is undirected for structural analysis.
(nodes: list[dict], edges: list[dict])
| 4 | |
| 5 | |
| 6 | def build_graph(nodes: list[dict], edges: list[dict]) -> nx.Graph: |
| 7 | """Build a NetworkX graph from graphify node/edge dicts. |
| 8 | |
| 9 | Preserves original edge direction as _src/_tgt attributes so that |
| 10 | display functions can show relationships in the correct direction, |
| 11 | even though the graph is undirected for structural analysis. |
| 12 | """ |
| 13 | G = nx.Graph() |
| 14 | for n in nodes: |
| 15 | G.add_node(n["id"], **{k: v for k, v in n.items() if k != "id"}) |
| 16 | for e in edges: |
| 17 | attrs = {k: v for k, v in e.items() if k not in ("source", "target")} |
| 18 | attrs["_src"] = e["source"] |
| 19 | attrs["_tgt"] = e["target"] |
| 20 | G.add_edge(e["source"], e["target"], **attrs) |
| 21 | return G |
| 22 | |
| 23 | _MAX_COMMUNITY_FRACTION = 0.25 # communities larger than 25% of graph get split |
| 24 | _MIN_SPLIT_SIZE = 10 # only split if community has at least this many nodes |