Skip to main content

cimview/
layout.rs

1//! The grid view's automatic layout (Cytoscape's `cose` is quadratic in the
2//! nodes on every iteration: RealGrid's 4875 substations do not finish).
3//!
4//! Each connected component is projected by PivotMDS, which keeps graph
5//! distances (a force layout alone, even multilevel, leaves a large grid
6//! folded), then refined by local forces — Fruchterman–Reingold with
7//! repulsion only between nodes in neighbouring cells, so a step is linear —
8//! which pull apart what the projection put on top of each other. Linear in
9//! nodes and edges times the pivots, and deterministic on one target: the same
10//! grid, the same layout. Between targets `sin`, `cos` and `powf` round
11//! differently, and the steps amplify it: RealGrid on wasm is the same picture
12//! as natively, each node a fifth of a line's length or so away.
13
14use std::collections::VecDeque;
15
16use cimmodel::base::FastMap;
17
18/// The ideal distance between neighbours.
19const K: f64 = 1.0;
20/// Steps of local forces after the projection.
21const REFINE_ITERATIONS: usize = 80;
22
23/// A graph: its node count, and its edges without loops or repeats.
24struct Graph {
25    n: usize,
26    edges: Vec<(usize, usize)>,
27}
28
29impl Graph {
30    fn len(&self) -> usize {
31        self.n
32    }
33
34    fn adjacency(&self) -> Vec<Vec<usize>> {
35        let mut adjacent = vec![Vec::new(); self.len()];
36        for &(a, b) in &self.edges {
37            adjacent[a].push(b);
38            adjacent[b].push(a);
39        }
40        adjacent
41    }
42}
43
44/// Positions for `n` nodes joined by `edges`, in units of [`K`]: each
45/// connected component by [`pivot_mds`], refined by local forces, the
46/// components packed in rows, the largest first.
47pub fn force(n: usize, edges: &[(usize, usize)]) -> Vec<(f64, f64)> {
48    let g = Graph {
49        n,
50        edges: simple(edges.iter().copied()),
51    };
52    let adjacent = g.adjacency();
53    // The components, largest first.
54    let mut component = vec![usize::MAX; n];
55    let mut members: Vec<Vec<usize>> = Vec::new();
56    for s in 0..n {
57        if component[s] != usize::MAX {
58            continue;
59        }
60        let c = members.len();
61        component[s] = c;
62        let mut queue = VecDeque::from([s]);
63        let mut held = Vec::new();
64        while let Some(i) = queue.pop_front() {
65            held.push(i);
66            for &j in &adjacent[i] {
67                if component[j] == usize::MAX {
68                    component[j] = c;
69                    queue.push_back(j);
70                }
71            }
72        }
73        members.push(held);
74    }
75    members.sort_by_key(|m| std::cmp::Reverse(m.len()));
76
77    let mut pos = vec![(0.0, 0.0); n];
78    let total_area: f64 = members.iter().map(|m| m.len() as f64).sum::<f64>() * 4.0 * K * K;
79    let row_width = total_area.sqrt() * 1.3;
80    let (mut x, mut y, mut row_height) = (0.0_f64, 0.0_f64, 0.0_f64);
81    for held in &members {
82        // The component on its own: local numbering.
83        let local: FastMap<usize, usize> = held.iter().enumerate().map(|(i, &v)| (v, i)).collect();
84        let sub = Graph {
85            n: held.len(),
86            edges: g
87                .edges
88                .iter()
89                .filter_map(|(a, b)| Some((*local.get(a)?, *local.get(b)?)))
90                .collect(),
91        };
92        let mut p = pivot_mds(&sub);
93        refine(&mut p, &sub, REFINE_ITERATIONS, 1.0 * K);
94        let (min_x, max_x) = p
95            .iter()
96            .fold((f64::MAX, f64::MIN), |a, q| (a.0.min(q.0), a.1.max(q.0)));
97        let (min_y, max_y) = p
98            .iter()
99            .fold((f64::MAX, f64::MIN), |a, q| (a.0.min(q.1), a.1.max(q.1)));
100        let (w, h) = (max_x - min_x, max_y - min_y);
101        if x > 0.0 && x + w > row_width {
102            (x, y, row_height) = (0.0, y + row_height + 2.0 * K, 0.0);
103        }
104        for (i, &v) in held.iter().enumerate() {
105            pos[v] = (x + p[i].0 - min_x, y + p[i].1 - min_y);
106        }
107        x += w + 2.0 * K;
108        row_height = row_height.max(h);
109    }
110    pos
111}
112
113/// How many pivots [`pivot_mds`] measures from.
114const PIVOTS: usize = 50;
115
116/// PivotMDS (Brandes & Pich 2006) of a connected graph: breadth-first
117/// distances from a few pivots, each the farthest from those before; the
118/// double-centred squared distances' two main directions, by power
119/// iteration on their k × k Gram matrix; scaled to edges of length [`K`].
120fn pivot_mds(g: &Graph) -> Vec<(f64, f64)> {
121    let n = g.len();
122    if n <= 2 {
123        return (0..n).map(|i| (i as f64 * K, 0.0)).collect();
124    }
125    let adjacent = g.adjacency();
126    let bfs = |s: usize| {
127        let mut d = vec![f64::MAX; n];
128        d[s] = 0.0;
129        let mut queue = VecDeque::from([s]);
130        while let Some(i) = queue.pop_front() {
131            for &j in &adjacent[i] {
132                if d[j] == f64::MAX {
133                    d[j] = d[i] + 1.0;
134                    queue.push_back(j);
135                }
136            }
137        }
138        d
139    };
140    let k = PIVOTS.min(n);
141    // Pivots: max-min, from the best connected node.
142    let first = (0..n)
143        .max_by_key(|&i| (adjacent[i].len(), std::cmp::Reverse(i)))
144        .unwrap_or(0);
145    let mut columns: Vec<Vec<f64>> = vec![bfs(first)];
146    let mut nearest = columns[0].clone();
147    while columns.len() < k {
148        let next = (0..n)
149            .max_by(|&a, &b| nearest[a].total_cmp(&nearest[b]).then(b.cmp(&a)))
150            .unwrap();
151        if nearest[next] == 0.0 {
152            break;
153        }
154        let d = bfs(next);
155        for (m, v) in nearest.iter_mut().zip(&d) {
156            *m = m.min(*v);
157        }
158        columns.push(d);
159    }
160    let k = columns.len();
161    // C: −½ of the squared distances, double-centred (n × k).
162    let mut c: Vec<Vec<f64>> = columns
163        .iter()
164        .map(|col| col.iter().map(|d| d * d).collect())
165        .collect();
166    let col_mean: Vec<f64> = c
167        .iter()
168        .map(|col| col.iter().sum::<f64>() / n as f64)
169        .collect();
170    let row_mean: Vec<f64> = (0..n)
171        .map(|i| c.iter().map(|col| col[i]).sum::<f64>() / k as f64)
172        .collect();
173    let all = col_mean.iter().sum::<f64>() / k as f64;
174    for (j, col) in c.iter_mut().enumerate() {
175        for (i, v) in col.iter_mut().enumerate() {
176            *v = -0.5 * (*v - row_mean[i] - col_mean[j] + all);
177        }
178    }
179    // B = CᵀC (k × k), and its two leading eigenvectors.
180    let b: Vec<Vec<f64>> = (0..k)
181        .map(|p| {
182            (0..k)
183                .map(|q| c[p].iter().zip(&c[q]).map(|(x, y)| x * y).sum())
184                .collect()
185        })
186        .collect();
187    let mut vectors: Vec<Vec<f64>> = Vec::new();
188    for axis in 0..2 {
189        // A deterministic start, apart from the first axis.
190        let mut v: Vec<f64> = (0..k)
191            .map(|i| if (i + axis) % 2 == 0 { 1.0 } else { 0.5 })
192            .collect();
193        for _ in 0..200 {
194            let mut w: Vec<f64> = (0..k)
195                .map(|p| b[p].iter().zip(&v).map(|(x, y)| x * y).sum())
196                .collect();
197            for u in &vectors {
198                let dot: f64 = w.iter().zip(u).map(|(x, y)| x * y).sum();
199                w.iter_mut().zip(u).for_each(|(x, y)| *x -= dot * y);
200            }
201            let norm = w.iter().map(|x| x * x).sum::<f64>().sqrt();
202            if norm < 1e-12 {
203                break;
204            }
205            v = w.into_iter().map(|x| x / norm).collect();
206        }
207        vectors.push(v);
208    }
209    let mut pos: Vec<(f64, f64)> = (0..n)
210        .map(|i| {
211            let along = |v: &Vec<f64>| (0..k).map(|p| c[p][i] * v[p]).sum::<f64>();
212            (along(&vectors[0]), along(&vectors[1]))
213        })
214        .collect();
215    // Edges of length K, on average.
216    let mean = g
217        .edges
218        .iter()
219        .map(|&(a, b)| ((pos[a].0 - pos[b].0).powi(2) + (pos[a].1 - pos[b].1).powi(2)).sqrt())
220        .sum::<f64>()
221        / g.edges.len().max(1) as f64;
222    let scale = if mean > 1e-12 { K / mean } else { 1.0 };
223    // Nodes alike in their distances (the boundary points between the same
224    // two substations) project onto one point, where no force parts them:
225    // apart a little, each its own way.
226    pos.iter_mut().enumerate().for_each(|(i, p)| {
227        let a = i as f64 * 2.399_963;
228        *p = (
229            p.0 * scale + 0.05 * K * a.cos(),
230            p.1 * scale + 0.05 * K * a.sin(),
231        );
232    });
233    pos
234}
235
236/// `edges` without loops or repeats, each as (smaller, larger).
237fn simple(edges: impl Iterator<Item = (usize, usize)>) -> Vec<(usize, usize)> {
238    let mut out: Vec<(usize, usize)> = edges
239        .filter(|(a, b)| a != b)
240        .map(|(a, b)| (a.min(b), a.max(b)))
241        .collect();
242    out.sort_unstable();
243    out.dedup();
244    out
245}
246
247/// `iterations` steps of Fruchterman–Reingold from `pos`, the step at most
248/// `t`, cooling: repulsion k² / d from the nodes in neighbouring cells, and
249/// attraction d² / k along the edges.
250fn refine(pos: &mut [(f64, f64)], g: &Graph, iterations: usize, mut t: f64) {
251    let n = pos.len();
252    let cell = 2.0 * K;
253    let mut disp = vec![(0.0, 0.0); n];
254    let mut cells: FastMap<(i64, i64), Vec<usize>> = FastMap::default();
255    let cool = (0.02 * K / t)
256        .powf(1.0 / iterations.max(1) as f64)
257        .min(0.99);
258    for _ in 0..iterations {
259        disp.iter_mut().for_each(|d| *d = (0.0, 0.0));
260        cells.values_mut().for_each(Vec::clear);
261        let key = |p: (f64, f64)| ((p.0 / cell).floor() as i64, (p.1 / cell).floor() as i64);
262        for (i, &p) in pos.iter().enumerate() {
263            cells.entry(key(p)).or_default().push(i);
264        }
265        for (i, &p) in pos.iter().enumerate() {
266            let (cx, cy) = key(p);
267            for dx in -1..=1 {
268                for dy in -1..=1 {
269                    let Some(near) = cells.get(&(cx + dx, cy + dy)) else {
270                        continue;
271                    };
272                    for &j in near {
273                        if j <= i {
274                            continue;
275                        }
276                        let (x, y) = (p.0 - pos[j].0, p.1 - pos[j].1);
277                        let d2 = (x * x + y * y).max(1e-4);
278                        if d2 > cell * cell {
279                            continue;
280                        }
281                        let f = K * K / d2;
282                        disp[i].0 += x * f;
283                        disp[i].1 += y * f;
284                        disp[j].0 -= x * f;
285                        disp[j].1 -= y * f;
286                    }
287                }
288            }
289        }
290        for &(a, b) in &g.edges {
291            let (x, y) = (pos[a].0 - pos[b].0, pos[a].1 - pos[b].1);
292            let f = (x * x + y * y).sqrt() / K;
293            disp[a].0 -= x * f;
294            disp[a].1 -= y * f;
295            disp[b].0 += x * f;
296            disp[b].1 += y * f;
297        }
298        for (i, p) in pos.iter_mut().enumerate() {
299            let (x, y) = disp[i];
300            let len = (x * x + y * y).sqrt();
301            if len > 0.0 {
302                let step = len.min(t);
303                p.0 += x / len * step;
304                p.1 += y / len * step;
305            }
306        }
307        t *= cool;
308    }
309}
310
311#[cfg(test)]
312mod tests {
313    use super::*;
314
315    /// How well the layout keeps graph distances: the correlation of hops and
316    /// distance from a few nodes to all the others they reach.
317    fn faithfulness(n: usize, edges: &[(usize, usize)], pos: &[(f64, f64)]) -> f64 {
318        let g = Graph {
319            n,
320            edges: simple(edges.iter().copied()),
321        };
322        let adjacent = g.adjacency();
323        let (mut xs, mut ys) = (Vec::new(), Vec::new());
324        for s in (0..n).step_by(n / 7 + 1) {
325            let mut hops = vec![usize::MAX; n];
326            hops[s] = 0;
327            let mut queue = VecDeque::from([s]);
328            while let Some(i) = queue.pop_front() {
329                for &j in &adjacent[i] {
330                    if hops[j] == usize::MAX {
331                        hops[j] = hops[i] + 1;
332                        queue.push_back(j);
333                    }
334                }
335            }
336            for j in (0..n).filter(|&j| j != s && hops[j] != usize::MAX) {
337                xs.push(hops[j] as f64);
338                ys.push(((pos[s].0 - pos[j].0).powi(2) + (pos[s].1 - pos[j].1).powi(2)).sqrt());
339            }
340        }
341        let m = xs.len() as f64;
342        let (mx, my) = (xs.iter().sum::<f64>() / m, ys.iter().sum::<f64>() / m);
343        let cov: f64 = xs.iter().zip(&ys).map(|(x, y)| (x - mx) * (y - my)).sum();
344        let (vx, vy): (f64, f64) = (
345            xs.iter().map(|x| (x - mx).powi(2)).sum(),
346            ys.iter().map(|y| (y - my).powi(2)).sum(),
347        );
348        cov / (vx * vy).sqrt()
349    }
350
351    fn overlapping(pos: &[(f64, f64)]) -> usize {
352        let n = pos.len();
353        let d = |a: usize, b: usize| {
354            ((pos[a].0 - pos[b].0).powi(2) + (pos[a].1 - pos[b].1).powi(2)).sqrt()
355        };
356        (0..n)
357            .step_by(7)
358            .map(|i| (0..n).filter(|&j| i != j && d(i, j) < 0.1 * K).count())
359            .sum()
360    }
361
362    /// A ring of 2000 nodes: spread, neighbours near, distances kept.
363    #[test]
364    fn lays_out_a_ring() {
365        let n = 2000;
366        let edges: Vec<(usize, usize)> = (0..n).map(|i| (i, (i + 1) % n)).collect();
367        let t = std::time::Instant::now();
368        let pos = force(n, &edges);
369        assert!(t.elapsed().as_secs_f64() < 2.0, "{:?}", t.elapsed());
370        assert!(overlapping(&pos) < 10);
371        let f = faithfulness(n, &edges, &pos);
372        assert!(f > 0.95, "{f}");
373    }
374
375    /// A 60 × 60 lattice, which a force layout leaves folded: unfolded.
376    #[test]
377    fn unfolds_a_lattice() {
378        let side = 60;
379        let n = side * side;
380        let mut edges = Vec::new();
381        for r in 0..side {
382            for c in 0..side {
383                let i = r * side + c;
384                if c + 1 < side {
385                    edges.push((i, i + 1));
386                }
387                if r + 1 < side {
388                    edges.push((i, i + side));
389                }
390            }
391        }
392        let t = std::time::Instant::now();
393        let pos = force(n, &edges);
394        assert!(t.elapsed().as_secs_f64() < 3.0, "{:?}", t.elapsed());
395        assert!(overlapping(&pos) < 20);
396        let f = faithfulness(n, &edges, &pos);
397        assert!(f > 0.95, "{f}");
398    }
399
400    /// Three nodes between the same two (MicroGrid's border points): parted.
401    #[test]
402    fn parts_nodes_alike() {
403        let edges = [(0, 2), (1, 2), (0, 3), (1, 3), (0, 4), (1, 4)];
404        let pos = force(5, &edges);
405        for (a, b) in [(2, 3), (2, 4), (3, 4)] {
406            let d = ((pos[a].0 - pos[b].0).powi(2) + (pos[a].1 - pos[b].1).powi(2)).sqrt();
407            assert!(d > 0.3 * K, "{a} and {b} at {d}");
408        }
409    }
410}