Skip to main content

rust_igraph/algorithms/properties/
pagerank.rs

1//! `PageRank` centrality (ALGO-PR-011).
2//!
3//! Counterpart of `igraph_pagerank()` from
4//! `references/igraph/src/centrality/pagerank.c` (the
5//! `IGRAPH_PAGERANK_ALGO_POWER` branch). Implemented as standard power
6//! iteration:
7//!
8//! `PR_new[v] = (1 - d) / N + d * (Σ_{u → v} PR[u] / out_deg(u) +
9//!              Σ_{sink} PR[sink] / N)`
10//!
11//! where the second sum handles "dangling" vertices (out-degree 0) by
12//! distributing their rank uniformly across the graph.
13//!
14//! For undirected graphs every edge counts as bidirectional, so
15//! `out_deg(u) == deg(u)` and the in-neighbour iteration is symmetric.
16//!
17//! Phase-1 minimal slice: undirected / `IGRAPH_OUT`, unweighted, damping
18//! `0.85`, `eps = 1e-10`, `max_iter = 1000`. Configurable parameters and
19//! ARPACK-based variants ship later.
20
21use crate::core::{Graph, IgraphResult};
22
23const DEFAULT_DAMPING: f64 = 0.85;
24const DEFAULT_EPS: f64 = 1e-10;
25const DEFAULT_MAX_ITER: usize = 1000;
26
27/// `PageRank` scores via power iteration with damping `0.85`.
28///
29/// Returns a `Vec<f64>` summing approximately to 1. For graphs with
30/// `vcount = 0` returns an empty vector.
31///
32/// Counterpart of
33/// `igraph_pagerank(_, IGRAPH_PAGERANK_ALGO_POWER, _, _, vss_all(),
34/// /*directed=*/g.is_directed(), 0.85, NULL_weights, NULL_options)`
35/// with default convergence parameters.
36///
37/// # Examples
38///
39/// ```
40/// use rust_igraph::{Graph, pagerank};
41///
42/// // Triangle: every vertex has identical PageRank ≈ 1/3.
43/// let mut g = Graph::with_vertices(3);
44/// g.add_edge(0, 1).unwrap();
45/// g.add_edge(1, 2).unwrap();
46/// g.add_edge(2, 0).unwrap();
47/// let pr = pagerank(&g).unwrap();
48/// assert!((pr[0] - 1.0/3.0).abs() < 1e-10);
49/// assert!((pr[1] - 1.0/3.0).abs() < 1e-10);
50/// assert!((pr[2] - 1.0/3.0).abs() < 1e-10);
51/// ```
52pub fn pagerank(graph: &Graph) -> IgraphResult<Vec<f64>> {
53    let n = graph.vcount();
54    let n_us = n as usize;
55    if n == 0 {
56        return Ok(Vec::new());
57    }
58    if n == 1 {
59        return Ok(vec![1.0]);
60    }
61
62    let directed = graph.is_directed();
63
64    // Pre-compute per-vertex out-degree and in-neighbour adjacency:
65    //   in_adj[v] = list of (u, 1/out_deg(u)) for each in-edge u → v.
66    // For undirected graphs we use the symmetric `neighbors()` iteration
67    // (each edge contributes both directions).
68    let n_f = f64::from(n);
69    let mut out_deg = vec![0u64; n_us];
70    for v in 0..n {
71        out_deg[v as usize] = graph.neighbors_iter(v)?.len() as u64;
72    }
73
74    // Build the in-adjacency: for each edge u → v (or u-v undirected, both
75    // u→v and v→u), append u to in_adj[v].
76    let mut in_adj: Vec<Vec<u32>> = vec![Vec::new(); n_us];
77    if directed {
78        // Iterate every edge once and record u → v.
79        let m = u32::try_from(graph.ecount())
80            .map_err(|_| crate::core::IgraphError::Internal("ecount overflows u32"))?;
81        for e in 0..m {
82            let (u, v) = graph.edge(e)?;
83            in_adj[v as usize].push(u);
84        }
85    } else {
86        // Undirected: each (u, v) edge appears once; record both directions.
87        let m = u32::try_from(graph.ecount())
88            .map_err(|_| crate::core::IgraphError::Internal("ecount overflows u32"))?;
89        for e in 0..m {
90            let (u, v) = graph.edge(e)?;
91            // Self-loop in undirected has degree 2 contribution so we add
92            // both directions.
93            if u == v {
94                in_adj[v as usize].push(u);
95                in_adj[v as usize].push(u);
96            } else {
97                in_adj[u as usize].push(v);
98                in_adj[v as usize].push(u);
99            }
100        }
101    }
102
103    // Initial uniform distribution.
104    let mut pr = vec![1.0 / n_f; n_us];
105    let mut pr_new = vec![0.0_f64; n_us];
106
107    for _ in 0..DEFAULT_MAX_ITER {
108        // Compute total dangling-vertex rank for redistribution.
109        let mut dangling_sum: f64 = 0.0;
110        for v in 0..n_us {
111            if out_deg[v] == 0 {
112                dangling_sum += pr[v];
113            }
114        }
115
116        let teleport = (1.0 - DEFAULT_DAMPING) / n_f;
117        let dangling_share = DEFAULT_DAMPING * dangling_sum / n_f;
118
119        for v in 0..n_us {
120            let mut incoming: f64 = 0.0;
121            for &u in &in_adj[v] {
122                #[allow(clippy::cast_precision_loss)]
123                let denom = out_deg[u as usize] as f64;
124                if denom > 0.0 {
125                    incoming += pr[u as usize] / denom;
126                }
127            }
128            pr_new[v] = teleport + dangling_share + DEFAULT_DAMPING * incoming;
129        }
130
131        // Convergence: L1 norm of the change.
132        let mut diff: f64 = 0.0;
133        for v in 0..n_us {
134            diff += (pr_new[v] - pr[v]).abs();
135        }
136        std::mem::swap(&mut pr, &mut pr_new);
137        if diff < DEFAULT_EPS {
138            break;
139        }
140    }
141
142    Ok(pr)
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148
149    fn close(actual: &[f64], expected: &[f64], tol: f64) {
150        assert_eq!(actual.len(), expected.len(), "length mismatch");
151        for (i, (a, e)) in actual.iter().zip(expected.iter()).enumerate() {
152            assert!((a - e).abs() < tol, "vertex {i}: actual={a} expected={e}");
153        }
154    }
155
156    #[test]
157    fn empty_graph_yields_empty() {
158        let g = Graph::with_vertices(0);
159        assert!(pagerank(&g).unwrap().is_empty());
160    }
161
162    #[test]
163    fn singleton_yields_one() {
164        let g = Graph::with_vertices(1);
165        assert_eq!(pagerank(&g).unwrap(), vec![1.0]);
166    }
167
168    #[test]
169    fn isolated_vertices_uniform() {
170        // No edges: all vertices are dangling. The dangling-redistribution
171        // term keeps the distribution uniform → 1/n each.
172        let g = Graph::with_vertices(4);
173        let pr = pagerank(&g).unwrap();
174        close(&pr, &[0.25, 0.25, 0.25, 0.25], 1e-9);
175    }
176
177    #[test]
178    fn triangle_uniform_one_third() {
179        let mut g = Graph::with_vertices(3);
180        g.add_edge(0, 1).unwrap();
181        g.add_edge(1, 2).unwrap();
182        g.add_edge(2, 0).unwrap();
183        let pr = pagerank(&g).unwrap();
184        close(&pr, &[1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0], 1e-9);
185    }
186
187    #[test]
188    fn directed_4cycle_uniform_quarter() {
189        let mut g = Graph::new(4, true).unwrap();
190        for i in 0..4u32 {
191            g.add_edge(i, (i + 1) % 4).unwrap();
192        }
193        let pr = pagerank(&g).unwrap();
194        close(&pr, &[0.25, 0.25, 0.25, 0.25], 1e-9);
195    }
196
197    #[test]
198    fn pagerank_sums_to_one() {
199        // K4 minus an edge — verify normalization.
200        let mut g = Graph::with_vertices(4);
201        g.add_edge(0, 1).unwrap();
202        g.add_edge(0, 2).unwrap();
203        g.add_edge(1, 2).unwrap();
204        g.add_edge(1, 3).unwrap();
205        g.add_edge(2, 3).unwrap();
206        let pr = pagerank(&g).unwrap();
207        let total: f64 = pr.iter().sum();
208        assert!((total - 1.0).abs() < 1e-9, "sum {total} != 1.0");
209    }
210
211    #[test]
212    fn star_centre_has_higher_pagerank_than_leaves() {
213        let mut g = Graph::with_vertices(4);
214        for v in 1..4 {
215            g.add_edge(0, v).unwrap();
216        }
217        let pr = pagerank(&g).unwrap();
218        // Centre receives from 3 leaves, each leaf only from centre → centre > leaf.
219        for &leaf in &pr[1..4] {
220            assert!(pr[0] > leaf, "centre {} not > leaf {}", pr[0], leaf);
221        }
222        // Symmetry among leaves.
223        close(&pr[1..4], &[pr[1], pr[1], pr[1]], 1e-9);
224    }
225
226    #[test]
227    fn pagerank_dangling_node_distributes() {
228        // Directed: 0 → 1, vertex 1 is dangling. Power iteration plus
229        // dangling-redistribution keeps PR finite and summing to 1.
230        let mut g = Graph::new(2, true).unwrap();
231        g.add_edge(0, 1).unwrap();
232        let pr = pagerank(&g).unwrap();
233        let total: f64 = pr.iter().sum();
234        assert!((total - 1.0).abs() < 1e-9);
235        // Vertex 1 receives flow from 0 and the dangling-redistribution.
236        // Vertex 0 only receives the teleport + dangling-redistribution.
237        // → pr[1] > pr[0].
238        assert!(pr[1] > pr[0]);
239    }
240}