feral_ordering_core/quotient_graph/workspace.rs
1//! Quotient-graph workspace and initialization, shared by AMD-family
2//! bottom-up orderings.
3//!
4//! All arrays follow the faer / SuiteSparse naming convention and use
5//! signed `i32` so we can reserve negative values for sentinels via
6//! [`flip`]: `flip(x) = -2 - x`. The input pattern is also `i32`-
7//! indexed (per the ordering-crate contract), so workspace ingestion
8//! converts to `usize` only for Rust slice addressing.
9//!
10//! Builds the workspace arrays from a full-symmetric CSC pattern,
11//! runs the two initialization fast paths (zero-degree
12//! pre-elimination and dense-deferred bucket), and seats the
13//! remaining variables into degree-indexed linked lists ready for
14//! the elimination loop.
15//!
16//! Migrated from `feral-amd` in 2026-04-27 to host the shared
17//! machinery for the planned `feral-amf` crate; the AMD-vs-AMF
18//! delta lives entirely in the elimination metric (see
19//! `dev/research/amf-clean-room.md`).
20//
21// Items are consumed by the elimination loop in subsequent commits
22// (Commit 4 onwards). Until then several fields and helpers are
23// intentionally unused.
24#![allow(dead_code)]
25
26use super::WorkspaceOptions;
27use crate::{CscPattern, OrderingError};
28
29/// Sentinel for "no index" in the `i32` arrays.
30pub const NONE: i32 = -1;
31
32/// Sentinel encoding used by the quotient graph: `flip(x) = -2 - x`.
33/// Used to mark absorbed elements (`pe[e] < 0` ⇒ `flip(parent)`) and
34/// as a tag on `elen` for freshly eliminated zero-degree variables.
35#[inline(always)]
36pub fn flip(x: i32) -> i32 {
37 -2 - x
38}
39
40/// Reset the generation counter `wflg` without visiting `iw`.
41///
42/// Called when `wflg` would overflow the `wbig` ceiling, or when it
43/// drops below 2 (which should not happen in practice, but matches
44/// SuiteSparse AMD's defensive check). All nonzero entries in `w`
45/// are clamped to `1`, and `2` is returned as the fresh counter.
46///
47/// Reference: `amd.rs:130-143`.
48#[inline]
49pub fn clear_flag(wflg: i32, wbig: i32, w: &mut [i32]) -> i32 {
50 if wflg < 2 || wflg >= wbig {
51 for x in w.iter_mut() {
52 if *x != 0 {
53 *x = 1;
54 }
55 }
56 return 2;
57 }
58 wflg
59}
60
61/// In-memory workspace for one AMD run.
62///
63/// The fields mirror faer's `amd_2` locals. Ownership of every buffer
64/// is held here so the elimination loop can borrow them concurrently
65/// through split borrows without reallocation.
66#[derive(Debug)]
67pub struct Workspace {
68 pub n: usize,
69 pub iwlen: usize,
70 pub pfree: usize,
71 pub iw: Vec<i32>,
72
73 pub pe: Vec<i32>,
74 pub len: Vec<i32>,
75 pub nv: Vec<i32>,
76 pub elen: Vec<i32>,
77 pub degree: Vec<i32>,
78 pub w: Vec<i32>,
79 pub head: Vec<i32>,
80 pub next: Vec<i32>,
81 pub last: Vec<i32>,
82 /// Per-supervariable / per-element fill-score scratch used by the
83 /// AMF inner loop only. Length `n`. Ignored by the AMD path
84 /// (`feral-amd` never reads or writes it). For variable indices
85 /// `i`, holds the running quantized RMF score; for element indices
86 /// `e`, holds the lazily-cached `dext * (2*deg(e) - dext - 1)`
87 /// surface contribution (sentinel `0` = "first touch this iter").
88 ///
89 /// `i64` (not `i32`): the un-quantized surface contribution has
90 /// both factors `O(n)`, so it reaches ~`n^2` and overflows `i32`
91 /// for `n` ≳ 46k before being consumed as `f64` in the RMF score
92 /// (O1, `dev/research/repo-review-2026-06-09.md`). MUMPS computes
93 /// the RMF in DBLE for the same reason. The post-quantization RMF
94 /// score stored here later is the exact rounded score, bounded by
95 /// `AMF_SCORE_CAP` (1e18; issue #246 dropped MUMPS's non-monotone
96 /// `i32` quantization).
97 pub wf: Vec<i64>,
98
99 /// Generation counter for the mark array `w`.
100 pub wflg: i32,
101 /// Overflow ceiling for `wflg`: `i32::MAX - n`.
102 pub wbig: i32,
103 /// Largest element size encountered so far — used by supervariable
104 /// detection (Slice B) to bump `wflg` safely.
105 pub lemax: i32,
106 /// Lower bound on the next pivot's degree. Monotone non-decreasing.
107 pub mindeg: usize,
108 /// Number of garbage-collection compactions so far.
109 pub ncmpa: u32,
110 /// Supervariables eliminated so far (pivoted OR dense-deferred).
111 pub nel: usize,
112 /// Dense-deferred supervariable count.
113 pub ndense: i32,
114 /// Variables folded into a concurrent pivot by mass elimination.
115 pub n_mass_elim: u32,
116 /// Supervariable merges detected during indistinguishable-variable
117 /// consolidation.
118 pub n_supervar_merge: u32,
119}
120
121impl Workspace {
122 /// Build a workspace from a full-symmetric CSC pattern and run
123 /// initialization. On return, all variables have been classified
124 /// into one of three buckets:
125 ///
126 /// 1. **Zero-degree** (`deg == 0`) — pre-eliminated. `pe[i] = NONE`,
127 /// `elen[i] = flip(1)`, `w[i] = 0`, `nel` incremented.
128 /// 2. **Dense-deferred** (`deg > dense`) — moved to the dense tail.
129 /// `pe[i] = NONE`, `nv[i] = 0`, `elen[i] = NONE`, `nel` incremented.
130 /// 3. **Live** — inserted LIFO into the degree-indexed linked list
131 /// headed by `head[deg]`, threaded through `next`/`last`.
132 ///
133 /// `pattern` must be the full-symmetric graph (both halves). The
134 /// diagonal is ignored if present.
135 pub fn new(
136 pattern: &CscPattern<'_>,
137 opts: &WorkspaceOptions,
138 ) -> Result<Workspace, OrderingError> {
139 Self::new_with_n_buckets(pattern, opts, pattern.n)
140 }
141
142 /// Variant of [`Workspace::new`] that allocates `head` with the
143 /// caller-supplied bucket count. Used by AMF, where the quantized
144 /// fill score can exceed `n` and the head array must extend up to
145 /// `NBBUCK + 1 = 2 * n + 1`. AMD always passes `pattern.n`, which
146 /// makes this byte-equivalent to [`Workspace::new`].
147 ///
148 /// `n_buckets` must be at least `n` so the init insertion at
149 /// `head[deg]` (with `deg ≤ dense ≤ n`) is in range.
150 pub fn new_with_n_buckets(
151 pattern: &CscPattern<'_>,
152 opts: &WorkspaceOptions,
153 n_buckets: usize,
154 ) -> Result<Workspace, OrderingError> {
155 let n = pattern.n;
156 debug_assert!(n_buckets >= n, "n_buckets must cover deg ∈ [0, n)");
157
158 // i32 addressing requires n < i32::MAX. The algorithm also
159 // stores `pfree` as i32 via `pe[i]`, so iwlen must fit.
160 if n >= i32::MAX as usize {
161 return Err(OrderingError::IndexOverflow);
162 }
163
164 // Count off-diagonal entries per column.
165 let mut len: Vec<i32> = vec![0; n];
166 let mut nzaat: usize = 0;
167 #[allow(clippy::needless_range_loop)]
168 for j in 0..n {
169 let j_i32 = j as i32;
170 let start = pattern.col_ptr[j] as usize;
171 let end = pattern.col_ptr[j + 1] as usize;
172 let mut cnt: usize = 0;
173 for &r in &pattern.row_idx[start..end] {
174 if r != j_i32 {
175 cnt += 1;
176 }
177 }
178 len[j] = cnt as i32;
179 nzaat += cnt;
180 }
181
182 // iwlen = nzaat + nzaat/5 + n (plan A1 / faer amd.rs:921-924).
183 let iwlen = nzaat
184 .checked_add(nzaat / 5)
185 .and_then(|s| s.checked_add(n))
186 .ok_or(OrderingError::IndexOverflow)?;
187 if iwlen > i32::MAX as usize {
188 return Err(OrderingError::IndexOverflow);
189 }
190 // iw needs at least one slot even when n==0 so `pfree` is
191 // addressable; we allocate exactly iwlen.
192 let mut iw: Vec<i32> = vec![0; iwlen];
193
194 // pe[j] = start of j's adjacency list in iw; fill iw with
195 // off-diagonals, in the order they appear in the CSC pattern.
196 let mut pe: Vec<i32> = vec![0; n];
197 let mut pfree: usize = 0;
198 #[allow(clippy::needless_range_loop)]
199 for j in 0..n {
200 pe[j] = pfree as i32;
201 let j_i32 = j as i32;
202 let start = pattern.col_ptr[j] as usize;
203 let end = pattern.col_ptr[j + 1] as usize;
204 for &r in &pattern.row_idx[start..end] {
205 if r != j_i32 {
206 iw[pfree] = r;
207 pfree += 1;
208 }
209 }
210 }
211 debug_assert_eq!(pfree, nzaat);
212
213 // Dense threshold. alpha < 0 disables dense deferral.
214 let dense = if opts.dense_alpha < 0.0 {
215 n.saturating_sub(2)
216 } else {
217 (opts.dense_alpha * (n as f64).sqrt()) as usize
218 };
219 let dense = dense.max(16).min(n);
220
221 // Fixed-value arrays.
222 let mut nv: Vec<i32> = vec![1; n];
223 let mut elen: Vec<i32> = vec![0; n];
224 let mut w: Vec<i32> = vec![1; n];
225 let degree: Vec<i32> = len.clone();
226 let mut head: Vec<i32> = vec![NONE; n_buckets];
227 let mut next: Vec<i32> = vec![NONE; n];
228 let mut last: Vec<i32> = vec![NONE; n];
229 let mut wf: Vec<i64> = vec![0; n];
230
231 let wbig = i32::MAX - n as i32;
232 let wflg = 0; // clear_flag will lift to 2 on first use.
233
234 let mut nel: usize = 0;
235 let mut ndense: i32 = 0;
236
237 // Classify each variable.
238 for i in 0..n {
239 let deg = degree[i] as usize;
240 if deg == 0 {
241 // Zero-degree fast path — pre-eliminated.
242 elen[i] = flip(1);
243 nel += 1;
244 pe[i] = NONE;
245 w[i] = 0;
246 } else if deg > dense {
247 // Dense-deferred fast path.
248 ndense += 1;
249 nv[i] = 0;
250 elen[i] = NONE;
251 pe[i] = NONE;
252 nel += 1;
253 } else {
254 // LIFO head-insert at head[deg]. The AMF metric's
255 // `bucket(deg, n)` is identity for `deg ≤ n`, so the
256 // index `deg` is the right slot for both AMD and AMF
257 // at init time. Seed the AMF fill score so the AMF
258 // path can compute `bucket(wf[i], n)` consistently.
259 let inext = head[deg];
260 if inext != NONE {
261 last[inext as usize] = i as i32;
262 }
263 next[i] = inext;
264 head[deg] = i as i32;
265 wf[i] = deg as i64;
266 }
267 }
268
269 Ok(Workspace {
270 n,
271 iwlen,
272 pfree,
273 iw,
274 pe,
275 len,
276 nv,
277 elen,
278 degree,
279 w,
280 head,
281 next,
282 last,
283 wf,
284 wflg,
285 wbig,
286 lemax: 0,
287 mindeg: 0,
288 ncmpa: 0,
289 nel,
290 ndense,
291 n_mass_elim: 0,
292 n_supervar_merge: 0,
293 })
294 }
295}
296
297#[cfg(test)]
298mod tests {
299 use super::*;
300
301 fn pat<'a>(n: usize, cp: &'a [i32], ri: &'a [i32]) -> CscPattern<'a> {
302 CscPattern::new(n, cp, ri).expect("valid test pattern")
303 }
304
305 #[test]
306 fn flip_involution() {
307 for x in [-100i32, -1, 0, 1, 17, 1000] {
308 assert_eq!(flip(flip(x)), x);
309 }
310 }
311
312 #[test]
313 fn clear_flag_resets_on_overflow() {
314 let mut w = [0, 3, 5, 7, 0];
315 // wflg >= wbig triggers reset.
316 let wflg = clear_flag(100, 100, &mut w);
317 assert_eq!(wflg, 2);
318 assert_eq!(w, [0, 1, 1, 1, 0]);
319 }
320
321 #[test]
322 fn clear_flag_passthrough() {
323 let mut w = [1, 2, 3];
324 let wflg = clear_flag(5, 100, &mut w);
325 assert_eq!(wflg, 5);
326 assert_eq!(w, [1, 2, 3]);
327 }
328
329 /// Diagonal 4x4: every variable has degree 0. All four are
330 /// pre-eliminated by the zero-degree fast path; none are
331 /// inserted into any degree list.
332 #[test]
333 fn diag_4_zero_degree_fast_path() {
334 let cp = [0, 1, 2, 3, 4];
335 let ri = [0, 1, 2, 3];
336 let p = pat(4, &cp, &ri);
337 let ws = Workspace::new(&p, &WorkspaceOptions::default()).unwrap();
338
339 assert_eq!(ws.n, 4);
340 assert_eq!(ws.nel, 4, "all four pre-eliminated");
341 assert_eq!(ws.ndense, 0, "no dense deferral");
342 for i in 0..4 {
343 assert_eq!(ws.elen[i], flip(1));
344 assert_eq!(ws.pe[i], NONE);
345 assert_eq!(ws.w[i], 0);
346 assert_eq!(ws.degree[i], 0);
347 }
348 for (d, &head) in ws.head[..4].iter().enumerate() {
349 assert_eq!(head, NONE, "degree {d} bucket empty");
350 }
351 }
352
353 /// Tridiagonal 5x5 full-symmetric: var 0 has deg 1, 4 has deg 1,
354 /// interior vars have deg 2. No dense deferral (max deg 2 < 16).
355 /// All five enter degree lists.
356 #[test]
357 fn tridiag_5_populates_degree_lists() {
358 // Full-symmetric tridiag of size 5.
359 // column j contains diagonal + off-diagonals j-1 and j+1.
360 let cp = [0, 2, 5, 8, 11, 13];
361 let ri = [0, 1, 0, 1, 2, 1, 2, 3, 2, 3, 4, 3, 4];
362 let p = pat(5, &cp, &ri);
363 let ws = Workspace::new(&p, &WorkspaceOptions::default()).unwrap();
364
365 assert_eq!(ws.n, 5);
366 assert_eq!(ws.nel, 0, "no fast-path eliminations");
367 assert_eq!(ws.ndense, 0);
368 assert_eq!(ws.degree, vec![1, 2, 2, 2, 1]);
369 assert_eq!(ws.len, vec![1, 2, 2, 2, 1]);
370
371 // LIFO insertion: the last variable inserted into deg list d
372 // is at head[d]. For deg=1, vars 0 and 4 hit the bucket;
373 // last in is 4. For deg=2, vars 1,2,3; last in is 3.
374 assert_eq!(ws.head[1], 4);
375 assert_eq!(ws.next[4], 0);
376 assert_eq!(ws.next[0], NONE);
377 assert_eq!(ws.last[0], 4);
378
379 assert_eq!(ws.head[2], 3);
380 assert_eq!(ws.next[3], 2);
381 assert_eq!(ws.next[2], 1);
382 assert_eq!(ws.next[1], NONE);
383 assert_eq!(ws.last[1], 2);
384 assert_eq!(ws.last[2], 3);
385 assert_eq!(ws.last[3], NONE);
386
387 // iwlen = nzaat + nzaat/5 + n.
388 // nzaat = sum(len) = 1+2+2+2+1 = 8.
389 // iwlen = 8 + 1 + 5 = 14.
390 assert_eq!(ws.iwlen, 14);
391 assert_eq!(ws.pfree, 8);
392 }
393
394 /// Arrow(5): hub at 0 has deg 4, spokes have deg 1. Dense
395 /// threshold for n=5 is min(n, max(16, 10*sqrt(5))) = 5; deg 4
396 /// < 5, so nothing is deferred. Hub enters head[4].
397 #[test]
398 fn arrow_5_all_live() {
399 let cp = [0, 5, 7, 9, 11, 13];
400 let ri = [0, 1, 2, 3, 4, 0, 1, 0, 2, 0, 3, 0, 4];
401 let p = pat(5, &cp, &ri);
402 let ws = Workspace::new(&p, &WorkspaceOptions::default()).unwrap();
403
404 assert_eq!(ws.degree, vec![4, 1, 1, 1, 1]);
405 assert_eq!(ws.nel, 0);
406 assert_eq!(ws.ndense, 0);
407 assert_eq!(ws.head[4], 0, "hub at deg-4 bucket");
408 assert_eq!(ws.head[1], 4, "last spoke inserted");
409 }
410
411 /// Arrow(200): hub has deg 199. Dense threshold = max(16,
412 /// floor(10*sqrt(200))) = max(16, 141) = 141, min(141, 200) =
413 /// 141. 199 > 141 so the hub is deferred. Spokes (deg 1) live.
414 #[test]
415 fn arrow_200_hub_deferred() {
416 let n = 200usize;
417 let mut cp: Vec<i32> = Vec::with_capacity(n + 1);
418 let mut ri: Vec<i32> = Vec::new();
419 cp.push(0);
420 // col 0: diagonal + all spokes 1..n
421 ri.push(0);
422 for r in 1..n {
423 ri.push(r as i32);
424 }
425 cp.push(ri.len() as i32);
426 // cols 1..n: diagonal + hub
427 for j in 1..n {
428 ri.push(0);
429 ri.push(j as i32);
430 cp.push(ri.len() as i32);
431 }
432 let p = pat(n, &cp, &ri);
433 let ws = Workspace::new(&p, &WorkspaceOptions::default()).unwrap();
434
435 assert_eq!(ws.degree[0], (n - 1) as i32);
436 assert_eq!(ws.nel, 1, "hub only");
437 assert_eq!(ws.ndense, 1);
438 assert_eq!(ws.nv[0], 0, "hub marked deferred");
439 assert_eq!(ws.pe[0], NONE);
440 assert_eq!(ws.elen[0], NONE);
441 // Spokes all land in head[1] — LIFO, last in is n-1.
442 assert_eq!(ws.head[1], (n - 1) as i32);
443 }
444
445 /// With `dense_alpha < 0`, the threshold is set to `n - 2`
446 /// (faer amd.rs:173-177). A variable with degree `n - 1` (only
447 /// possible for a true hub) is still deferred; everything else
448 /// stays live. This matches SuiteSparse AMD semantics exactly.
449 #[test]
450 fn dense_alpha_negative_uses_n_minus_2() {
451 // Band(20, 5): max degree = 10, well under n - 2 = 18.
452 let n = 20usize;
453 let b = 5usize;
454 let mut cp: Vec<i32> = vec![0];
455 let mut ri: Vec<i32> = Vec::new();
456 for j in 0..n {
457 let lo = j.saturating_sub(b);
458 let hi = (j + b + 1).min(n);
459 for r in lo..hi {
460 ri.push(r as i32);
461 }
462 cp.push(ri.len() as i32);
463 }
464 let p = pat(n, &cp, &ri);
465 let opts = WorkspaceOptions { dense_alpha: -1.0 };
466 let ws = Workspace::new(&p, &opts).unwrap();
467 assert_eq!(ws.ndense, 0, "nothing deferred below n - 2");
468 assert_eq!(ws.nel, 0);
469 }
470
471 #[test]
472 fn empty_pattern_ok() {
473 let cp = [0i32];
474 let ri: [i32; 0] = [];
475 let p = pat(0, &cp, &ri);
476 let ws = Workspace::new(&p, &WorkspaceOptions::default()).unwrap();
477 assert_eq!(ws.n, 0);
478 assert_eq!(ws.nel, 0);
479 assert_eq!(ws.iwlen, 0);
480 }
481
482 /// Diagonal entries in the input are ignored when computing
483 /// adjacency lists — only off-diagonal neighbors contribute to
484 /// `len`, `degree`, and `iw`.
485 #[test]
486 fn diagonal_entries_skipped() {
487 // 3x3 with diagonal only.
488 let cp = [0, 1, 2, 3];
489 let ri = [0, 1, 2];
490 let p = pat(3, &cp, &ri);
491 let ws = Workspace::new(&p, &WorkspaceOptions::default()).unwrap();
492 assert_eq!(ws.len, vec![0, 0, 0]);
493 assert_eq!(ws.pfree, 0);
494 assert_eq!(ws.nel, 3);
495 }
496}