|
|
|
""" |
|
Basic graph-analytics helpers (pure CPU, no heavy maths): |
|
β’ build_nx β convert agraph nodes/edges β NetworkX graph |
|
β’ get_top_hubs β return top-k nodes by degree-centrality |
|
β’ get_density β overall graph density |
|
""" |
|
|
|
from typing import List, Dict, Tuple |
|
import networkx as nx |
|
|
|
|
|
def build_nx(nodes: List[Dict], edges: List[Dict]) -> nx.Graph: |
|
G = nx.Graph() |
|
for n in nodes: |
|
G.add_node(n["id"], label=n.get("label", n["id"])) |
|
for e in edges: |
|
G.add_edge(e["source"], e["target"]) |
|
return G |
|
|
|
|
|
def get_top_hubs(G: nx.Graph, k: int = 5) -> List[Tuple[str, float]]: |
|
""" |
|
Return [(node_id, centrality)] sorted desc. |
|
""" |
|
dc = nx.degree_centrality(G) |
|
return sorted(dc.items(), key=lambda x: x[1], reverse=True)[:k] |
|
|
|
|
|
def get_density(G: nx.Graph) -> float: |
|
return nx.density(G) |
|
|