MCP_Res / mcp /graph_metrics.py
mgbam's picture
Create graph_metrics.py
3f06a92 verified
raw
history blame
939 Bytes
# mcp/graph_metrics.py
"""
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)