|
| 1 | +"""Personalized PageRank (PPR) engine — zero-dependency, dict-based sparse implementation. |
| 2 | +
|
| 3 | +Power iteration: |
| 4 | + r(t+1) = (1 - damping) * personalization + damping * A_norm * r(t) |
| 5 | +
|
| 6 | +Where A_norm is a column-normalized adjacency matrix built from the graph edges. |
| 7 | +""" |
| 8 | + |
| 9 | +from __future__ import annotations |
| 10 | + |
| 11 | +from typing import TYPE_CHECKING |
| 12 | + |
| 13 | +if TYPE_CHECKING: |
| 14 | + from synaptic.protocols import StorageBackend |
| 15 | + |
| 16 | + |
| 17 | +async def personalized_pagerank( |
| 18 | + backend: StorageBackend, |
| 19 | + seed_scores: dict[str, float], |
| 20 | + *, |
| 21 | + damping: float = 0.85, |
| 22 | + max_iter: int = 50, |
| 23 | + tol: float = 1e-6, |
| 24 | + top_k: int = 20, |
| 25 | +) -> list[tuple[str, float]]: |
| 26 | + """Perform PPR and return top-k (node_id, score) pairs. |
| 27 | +
|
| 28 | + The graph is discovered incrementally via BFS from seed nodes so that |
| 29 | + only the reachable subgraph is materialized — no need to enumerate all |
| 30 | + nodes/edges in the backend. |
| 31 | +
|
| 32 | + Args: |
| 33 | + backend: Storage backend implementing the StorageBackend protocol. |
| 34 | + seed_scores: {node_id: weight} — search result scores as personalization. |
| 35 | + damping: Probability of following an edge (vs teleporting back to seeds). |
| 36 | + max_iter: Maximum power-iteration steps. |
| 37 | + tol: Convergence threshold (L1 norm of rank change). |
| 38 | + top_k: Number of top-ranked nodes to return. |
| 39 | +
|
| 40 | + Returns: |
| 41 | + List of (node_id, ppr_score) sorted descending by score. |
| 42 | + """ |
| 43 | + if not seed_scores: |
| 44 | + return [] |
| 45 | + |
| 46 | + # --- 1. BFS to discover the reachable subgraph (depth 2 from seeds) --- |
| 47 | + # adjacency: source -> [(target, weight), ...] |
| 48 | + adj: dict[str, list[tuple[str, float]]] = {} |
| 49 | + visited: set[str] = set() |
| 50 | + frontier = set(seed_scores.keys()) |
| 51 | + bfs_depth = 2 |
| 52 | + |
| 53 | + for _ in range(bfs_depth): |
| 54 | + if not frontier: |
| 55 | + break |
| 56 | + next_frontier: set[str] = set() |
| 57 | + for nid in frontier: |
| 58 | + if nid in visited: |
| 59 | + continue |
| 60 | + visited.add(nid) |
| 61 | + if nid not in adj: |
| 62 | + adj[nid] = [] |
| 63 | + edges = await backend.get_edges(nid, direction="both") |
| 64 | + for edge in edges: |
| 65 | + # Determine the neighbor |
| 66 | + if edge.source_id == nid: |
| 67 | + neighbor_id = edge.target_id |
| 68 | + else: |
| 69 | + neighbor_id = edge.source_id |
| 70 | + |
| 71 | + # Add edge in both directions (undirected for PPR spreading) |
| 72 | + adj[nid].append((neighbor_id, edge.weight)) |
| 73 | + if neighbor_id not in adj: |
| 74 | + adj[neighbor_id] = [] |
| 75 | + adj[neighbor_id].append((nid, edge.weight)) |
| 76 | + |
| 77 | + if neighbor_id not in visited: |
| 78 | + next_frontier.add(neighbor_id) |
| 79 | + frontier = next_frontier |
| 80 | + |
| 81 | + # Mark remaining frontier nodes as visited (leaf nodes with no outgoing expansion) |
| 82 | + visited.update(frontier) |
| 83 | + for nid in frontier: |
| 84 | + if nid not in adj: |
| 85 | + adj[nid] = [] |
| 86 | + |
| 87 | + all_nodes = set(adj.keys()) | set(seed_scores.keys()) |
| 88 | + |
| 89 | + # No edges at all — return seed scores directly (sorted) |
| 90 | + if not any(adj.values()): |
| 91 | + sorted_seeds = sorted(seed_scores.items(), key=lambda x: x[1], reverse=True) |
| 92 | + return sorted_seeds[:top_k] |
| 93 | + |
| 94 | + # --- 2. Build column-normalized adjacency (as sparse dicts) --- |
| 95 | + # out_weight[node] = sum of weights of outgoing edges |
| 96 | + out_weight: dict[str, float] = {} |
| 97 | + for src, neighbors in adj.items(): |
| 98 | + total = sum(w for _, w in neighbors) |
| 99 | + out_weight[src] = total if total > 0 else 1.0 |
| 100 | + |
| 101 | + # --- 3. Normalize personalization vector --- |
| 102 | + total_seed = sum(seed_scores.values()) |
| 103 | + if total_seed == 0: |
| 104 | + return [] |
| 105 | + personalization: dict[str, float] = { |
| 106 | + nid: s / total_seed for nid, s in seed_scores.items() |
| 107 | + } |
| 108 | + |
| 109 | + # --- 4. Power iteration --- |
| 110 | + # Initialize rank vector = personalization |
| 111 | + rank: dict[str, float] = {} |
| 112 | + for nid in all_nodes: |
| 113 | + rank[nid] = personalization.get(nid, 0.0) |
| 114 | + |
| 115 | + teleport_coeff = 1.0 - damping |
| 116 | + |
| 117 | + for _ in range(max_iter): |
| 118 | + new_rank: dict[str, float] = {} |
| 119 | + # Initialize with teleport (personalization) |
| 120 | + for nid in all_nodes: |
| 121 | + new_rank[nid] = teleport_coeff * personalization.get(nid, 0.0) |
| 122 | + |
| 123 | + # Distribute rank along edges |
| 124 | + for src, neighbors in adj.items(): |
| 125 | + if not neighbors: |
| 126 | + continue |
| 127 | + src_rank = rank[src] |
| 128 | + src_out = out_weight[src] |
| 129 | + for tgt, w in neighbors: |
| 130 | + # Column-normalized: edge_weight / total_out_weight * src_rank |
| 131 | + contribution = damping * src_rank * w / src_out |
| 132 | + new_rank[tgt] = new_rank.get(tgt, 0.0) + contribution |
| 133 | + |
| 134 | + # Check convergence (L1 norm) |
| 135 | + diff = sum(abs(new_rank.get(nid, 0.0) - rank.get(nid, 0.0)) for nid in all_nodes) |
| 136 | + rank = new_rank |
| 137 | + if diff < tol: |
| 138 | + break |
| 139 | + |
| 140 | + # --- 5. Return top-k --- |
| 141 | + sorted_results = sorted(rank.items(), key=lambda x: x[1], reverse=True) |
| 142 | + return sorted_results[:top_k] |
0 commit comments