Create graph_metrics.py
Browse files- mcp/graph_metrics.py +31 -0
mcp/graph_metrics.py
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# mcp/graph_metrics.py
|
2 |
+
"""
|
3 |
+
Basic graph-analytics helpers (pure CPU, no heavy maths):
|
4 |
+
β’ build_nx β convert agraph nodes/edges β NetworkX graph
|
5 |
+
β’ get_top_hubs β return top-k nodes by degree-centrality
|
6 |
+
β’ get_density β overall graph density
|
7 |
+
"""
|
8 |
+
|
9 |
+
from typing import List, Dict, Tuple
|
10 |
+
import networkx as nx
|
11 |
+
|
12 |
+
# ----------------------------------------------------------------------
|
13 |
+
def build_nx(nodes: List[Dict], edges: List[Dict]) -> nx.Graph:
|
14 |
+
G = nx.Graph()
|
15 |
+
for n in nodes:
|
16 |
+
G.add_node(n["id"], label=n.get("label", n["id"]))
|
17 |
+
for e in edges:
|
18 |
+
G.add_edge(e["source"], e["target"])
|
19 |
+
return G
|
20 |
+
|
21 |
+
|
22 |
+
def get_top_hubs(G: nx.Graph, k: int = 5) -> List[Tuple[str, float]]:
|
23 |
+
"""
|
24 |
+
Return [(node_id, centrality)] sorted desc.
|
25 |
+
"""
|
26 |
+
dc = nx.degree_centrality(G)
|
27 |
+
return sorted(dc.items(), key=lambda x: x[1], reverse=True)[:k]
|
28 |
+
|
29 |
+
|
30 |
+
def get_density(G: nx.Graph) -> float:
|
31 |
+
return nx.density(G)
|