Skip to main content

feral_ordering_core/quotient_graph/
algo.rs

1//! AMD elimination-loop primitives: pivot selection and element
2//! construction (plus standard absorption).
3//!
4//! This module lands Commit 4 of the Slice A plan. It ports faer's
5//! `amd.rs:220-365` line-by-line:
6//!
7//! - [`select_pivot`]: linear scan from `mindeg`, LIFO unlink.
8//! - [`create_element`]: both the in-place (`elenme == 0`) and
9//!   out-of-place (`elenme > 0`) branches, plus standard absorption
10//!   fired at the end of each `knt1` iter (faer `amd.rs:355-358`),
11//!   and the final bookkeeping write-back to `pe[me]/len[me]/elen[me]`
12//!   with the post-step `clear_flag` call.
13//!
14//! Inline garbage collection (faer `amd.rs:289-338`) fires inside
15//! the out-of-place branch when `pfree >= iwlen`. See
16//! [`create_element`] for the full save → mark → compact → restore
17//! dance.
18//!
19//! Pass-1 `w[e]` seeding (`amd.rs:366-385`), Pass-2 approximate
20//! degree (`amd.rs:386-465`), aggressive absorption, monotone
21//! degree cap, and re-insertion into degree lists (`amd.rs:516-546`)
22//! live in [`finalize_step`]. Mass elimination and supervariable
23//! detection are Slice B (Commits 9-10).
24
25#![allow(dead_code)]
26
27use super::workspace::{clear_flag, flip, Workspace, NONE};
28use crate::OrderingError;
29
30/// Flop-counter deltas produced by a single elimination step.
31/// Matches faer's `amd.rs:547-557` accounting so `AmdStats` can
32/// accumulate consistent `ndiv` / `nms_ldl` / `nms_lu` totals.
33#[derive(Debug, Clone, Copy, Default)]
34pub struct StepFlops {
35    pub ndiv: f64,
36    pub nms_lu: f64,
37    pub nms_ldl: f64,
38}
39
40impl StepFlops {
41    fn accumulate(&mut self, other: StepFlops) {
42        self.ndiv += other.ndiv;
43        self.nms_lu += other.nms_lu;
44        self.nms_ldl += other.nms_ldl;
45    }
46}
47
48/// Scan `head` from `ws.mindeg` upward and return the first
49/// non-empty degree-list head. Unlink the chosen variable. Returns
50/// `None` if no bucket in `[ws.mindeg, ws.n)` is non-empty (i.e.
51/// all remaining supervariables have been dense-deferred and the
52/// main loop should stop).
53///
54/// Side effects: `ws.mindeg` advances to the degree of the chosen
55/// pivot. `head[deg]` is advanced to the next element. `last[next]`
56/// is cleared if a successor exists.
57///
58/// Reference: faer `amd.rs:220-235`.
59pub fn select_pivot(ws: &mut Workspace) -> Option<usize> {
60    let n = ws.n;
61    let mut deg = ws.mindeg;
62    let mut me_signed: i32 = NONE;
63    while deg < n {
64        let h = ws.head[deg];
65        if h != NONE {
66            me_signed = h;
67            break;
68        }
69        deg += 1;
70    }
71    if me_signed == NONE {
72        return None;
73    }
74    ws.mindeg = deg;
75    let me = me_signed as usize;
76    let inext = ws.next[me];
77    if inext != NONE {
78        ws.last[inext as usize] = NONE;
79    }
80    ws.head[deg] = inext;
81    Some(me)
82}
83
84/// Build the new element `me` by merging the (variable) tail of
85/// `me`'s list with every element `e` already in `me`'s list.
86///
87/// On success returns `(pme1, pme2_excl, nvpiv, degme)`:
88/// - `pme1..pme2_excl` is the contiguous region in `ws.iw` holding
89///   the new element's **variable** members (supervariables, listed
90///   once each). Exclusive end so the empty case (`pme2_excl ==
91///   pme1`) is representable in `usize` without underflow.
92/// - `nvpiv` is the supervariable count of the pivot.
93/// - `degme` is the tentative new element's external degree (sum of
94///   `nv[i]` over the assembled variables, before any absorption
95///   correction made by Pass-2).
96///
97/// Post-conditions also persisted on the workspace:
98/// - `nv[me] = -nvpiv` (marker — Pass-2 will flip sign back via
99///   `-nv[i]`).
100/// - `nv[i] = -nv[i]` for every `i` assembled into the new element
101///   (ditto — marker for Pass-2's w-seed walk).
102/// - `pe[me] = pme1`, `len[me] = pme2 - pme1 + 1`, `elen[me] =
103///   flip(nvpiv + degme)` (dead-variable sentinel carrying the
104///   pivot-front size for the postorder phase).
105/// - `degree[me] = degme` (temporary; Pass-2 overwrites).
106/// - For every absorbed element `e != me` in the elenme>0 branch:
107///   `pe[e] = flip(me)`, `w[e] = 0`. This is **standard absorption**
108///   (faer `amd.rs:355-358`) — it fires unconditionally at each
109///   `knt1` iter's end. Aggressive absorption (Pass-2 only) lands
110///   in Commit 5.
111/// - `ws.wflg` bumped via `clear_flag`.
112/// - `ws.nel` incremented by `nvpiv`.
113///
114/// Reference: faer `amd.rs:236-366` (incl. inline GC at 289-338).
115pub fn create_element(
116    ws: &mut Workspace,
117    me: usize,
118) -> Result<(usize, usize, i32, usize), OrderingError> {
119    let elenme = ws.elen[me];
120    let nvpiv = ws.nv[me];
121    ws.nel += nvpiv as usize;
122    ws.nv[me] = -nvpiv;
123    let mut degme: usize = 0;
124    let pme1: usize;
125    let pme2: i32;
126
127    if elenme == 0 {
128        // In-place: me has no elements in its list — just variables.
129        // Compact them at pe[me]: advance pme2 to the final position,
130        // overwriting absorbed entries in-place.
131        let pme1_s = ws.pe[me];
132        pme1 = pme1_s as usize;
133        let list_start = pme1;
134        let list_end = list_start + ws.len[me] as usize;
135        let mut pme2_s = pme1_s - 1;
136        for p in list_start..list_end {
137            let i = ws.iw[p] as usize;
138            let nvi = ws.nv[i];
139            if nvi > 0 {
140                degme += nvi as usize;
141                ws.nv[i] = -nvi;
142                pme2_s += 1;
143                ws.iw[pme2_s as usize] = i as i32;
144                // Unlink i from its degree list.
145                let ilast = ws.last[i];
146                let inext = ws.next[i];
147                if inext != NONE {
148                    ws.last[inext as usize] = ilast;
149                }
150                if ilast != NONE {
151                    ws.next[ilast as usize] = inext;
152                } else {
153                    ws.head[ws.degree[i] as usize] = inext;
154                }
155            }
156        }
157        pme2 = pme2_s;
158    } else {
159        // Out-of-place: start a new region at pfree. Walk every
160        // element e in me's list (first `elenme` entries of me's
161        // adjacency), then walk the variable tail (remaining
162        // `slenme` entries) with `knt1 = elenme + 1` as the flag.
163        let mut p = ws.pe[me] as usize;
164        let mut pme1_rw: usize = ws.pfree;
165        let slenme = (ws.len[me] - elenme) as usize;
166        let elenme_u = elenme as usize;
167        for knt1 in 1..=elenme_u + 1 {
168            let e: usize;
169            let mut pj: usize;
170            let ln: usize;
171            if knt1 > elenme_u {
172                // Variable tail of me's own list.
173                e = me;
174                pj = p;
175                ln = slenme;
176            } else {
177                e = ws.iw[p] as usize;
178                p += 1;
179                pj = ws.pe[e] as usize;
180                ln = ws.len[e] as usize;
181            }
182            for knt2 in 1..=ln {
183                let i = ws.iw[pj] as usize;
184                pj += 1;
185                let nvi = ws.nv[i];
186                if nvi > 0 {
187                    if ws.pfree >= ws.iwlen {
188                        // Inline garbage collection (faer
189                        // amd.rs:289-338). Save partial state so
190                        // the surviving elements can be compacted
191                        // down, then restore local cursors.
192                        ws.pe[me] = p as i32;
193                        ws.len[me] -= knt1 as i32;
194                        if ws.len[me] == 0 {
195                            ws.pe[me] = NONE;
196                        }
197                        ws.pe[e] = pj as i32;
198                        ws.len[e] = (ln - knt2) as i32;
199                        if ws.len[e] == 0 {
200                            ws.pe[e] = NONE;
201                        }
202                        ws.ncmpa += 1;
203                        // Mark each live list's head: save iw[pe[j]]
204                        // into pe[j] and write flip(j) at the old
205                        // head position so the compact sweep can
206                        // recognise list starts.
207                        for j in 0..ws.n {
208                            let pn = ws.pe[j];
209                            if pn >= 0 {
210                                let pn_u = pn as usize;
211                                ws.pe[j] = ws.iw[pn_u];
212                                ws.iw[pn_u] = flip(j as i32);
213                            }
214                        }
215                        // Sweep [0, pme1_rw), reconstructing every
216                        // marked list contiguously at pdst.
217                        let mut psrc = 0usize;
218                        let mut pdst = 0usize;
219                        let pend = pme1_rw;
220                        while psrc < pend {
221                            let j_marker = flip(ws.iw[psrc]);
222                            psrc += 1;
223                            if j_marker >= 0 {
224                                let j = j_marker as usize;
225                                ws.iw[pdst] = ws.pe[j];
226                                ws.pe[j] = pdst as i32;
227                                pdst += 1;
228                                let lenj = ws.len[j] as usize;
229                                if lenj > 0 {
230                                    ws.iw.copy_within(psrc..psrc + lenj - 1, pdst);
231                                    psrc += lenj - 1;
232                                    pdst += lenj - 1;
233                                }
234                            }
235                        }
236                        // Slide the new element's accumulated prefix
237                        // [pme1_rw, pfree) down to the new pdst.
238                        let p1 = pdst;
239                        ws.iw.copy_within(pme1_rw..ws.pfree, pdst);
240                        pdst += ws.pfree - pme1_rw;
241                        pme1_rw = p1;
242                        ws.pfree = pdst;
243                        // Restore local cursors from the relocated
244                        // heads of e's and me's lists.
245                        pj = ws.pe[e] as usize;
246                        p = ws.pe[me] as usize;
247                    }
248                    degme += nvi as usize;
249                    ws.nv[i] = -nvi;
250                    ws.iw[ws.pfree] = i as i32;
251                    ws.pfree += 1;
252                    // Unlink i from its degree list.
253                    let ilast = ws.last[i];
254                    let inext = ws.next[i];
255                    if inext != NONE {
256                        ws.last[inext as usize] = ilast;
257                    }
258                    if ilast != NONE {
259                        ws.next[ilast as usize] = inext;
260                    } else {
261                        ws.head[ws.degree[i] as usize] = inext;
262                    }
263                }
264            }
265            // Standard absorption (amd.rs:355-358): every element e
266            // that was in me's list is now absorbed by me.
267            if e != me {
268                ws.pe[e] = flip(me as i32);
269                ws.w[e] = 0;
270            }
271        }
272        pme1 = pme1_rw;
273        pme2 = (ws.pfree - 1) as i32;
274    }
275
276    ws.degree[me] = degme as i32;
277    ws.pe[me] = pme1 as i32;
278    ws.len[me] = pme2 - pme1 as i32 + 1;
279    ws.elen[me] = flip(nvpiv + degme as i32);
280    ws.wflg = clear_flag(ws.wflg, ws.wbig, &mut ws.w);
281
282    // Convert the inclusive `pme2` (which is `pme1 - 1` when the
283    // pivot's variable list ended up empty — every neighbour was
284    // already absorbed) to an exclusive end so downstream loops can
285    // use a `usize` half-open range without the wrap-around bug
286    // `(-1i32) as usize == usize::MAX`.
287    let pme2_excl: usize = if pme2 < pme1 as i32 {
288        pme1
289    } else {
290        (pme2 + 1) as usize
291    };
292    Ok((pme1, pme2_excl, nvpiv, degme))
293}
294
295/// Finish the elimination step whose create-element phase produced
296/// `(pme1, pme2_excl, nvpiv, degme)` and left `nv[me] = -nvpiv` and
297/// `nv[i] = -nv[i]` for every variable `i ∈ iw[pme1..pme2_excl]`.
298///
299/// Does, in order:
300/// 1. **Pass-1 w-seeding** (faer `amd.rs:366-385`). For each
301///    variable `i` in the new element, walk its element list and
302///    lazily seed `w[e]`: first touch sets `w[e] = degree[e] +
303///    (wflg - nvi)`, subsequent touches do `w[e] -= nvi`.
304/// 2. **Pass-2 approximate external degree** (`amd.rs:386-462`).
305///    For each variable `i` in the new element: walk its element
306///    list computing `dext = w[e] - wflg`, then its variable list
307///    accumulating `nv[j]` for live neighbours. Under `aggressive`,
308///    dead elements (`dext == 0`) are absorbed on the spot. The
309///    updated degree is clamped by `min(degree[i], deg)`
310///    ("monotone cap"). The element list is re-ordered so `me` sits
311///    at position `p1`.
312/// 3. **Mass elimination** (`amd.rs:436-444`). A member `i` whose
313///    only remaining element is `me` (`elen[i] == 1`) and whose
314///    surviving variable neighbourhood is empty (`p3 == pn`) will
315///    pivot concurrently with `me`. Fold its supervariable count
316///    into `nvpiv` / `nel` and deduct from `degme`.
317/// 4. **Hash-bucket insertion** (`amd.rs:452-460`): each still-
318///    marked member is placed into a hash bucket threaded through
319///    `head`/`next`/`last` via sign-bit encoding.
320/// 5. Bump `degree[me] = degme`, `lemax = max(lemax, degme)`,
321///    `wflg += lemax`, `wflg = clear_flag(...)`.
322/// 6. **Supervariable detection** (`amd.rs:467-515`): for each
323///    hash chain whose anchor is still marked, walk the chain and
324///    merge indistinguishable followers into the head.
325/// 7. **Re-insert** (`amd.rs:516-537`): each surviving variable's
326///    updated degree is pushed back onto `head[deg]` LIFO and
327///    `mindeg` is lowered if needed.
328/// 8. **Me bookkeeping** (`amd.rs:538-546`): restore `nv[me] =
329///    nvpiv`, compact `me`'s var list to `[pme1, p)`, trim `pfree`.
330/// 9. **Flop counters** (`amd.rs:547-557`).
331#[allow(clippy::too_many_arguments)]
332pub fn finalize_step(
333    ws: &mut Workspace,
334    me: usize,
335    pme1: usize,
336    pme2_excl: usize,
337    nvpiv: i32,
338    degme: usize,
339    elenme: i32,
340    aggressive: bool,
341) -> StepFlops {
342    let mut degme = degme;
343    let mut nvpiv = nvpiv;
344
345    // Pass 1: seed w[e] for every element in each member's list.
346    for pme in pme1..pme2_excl {
347        let i = ws.iw[pme] as usize;
348        let eln = ws.elen[i];
349        if eln > 0 {
350            let nvi = -ws.nv[i];
351            let wnvi = ws.wflg - nvi;
352            let pi = ws.pe[i] as usize;
353            for k in 0..eln as usize {
354                let e = ws.iw[pi + k] as usize;
355                let mut we = ws.w[e];
356                if we >= ws.wflg {
357                    we -= nvi;
358                } else if we != 0 {
359                    we = ws.degree[e] + wnvi;
360                }
361                ws.w[e] = we;
362            }
363        }
364    }
365
366    // Pass 2: approximate degree, (optionally) aggressive absorption,
367    // mass elimination (faer amd.rs:436-444), and hash-bucket
368    // insertion for supervariable detection (amd.rs:451-460). `degme`
369    // and `nvpiv` are mutated when mass-elim fires; the post-loop
370    // degree/flop bookkeeping uses the updated values.
371    for pme in pme1..pme2_excl {
372        let i = ws.iw[pme] as usize;
373        let p1 = ws.pe[i] as usize;
374        let p2 = p1 + ws.elen[i] as usize;
375        let mut pn = p1;
376        let mut deg: usize = 0;
377        // Hash accumulator for supervariable detection (faer
378        // amd.rs:419,433). Both elements AND variables in the kept
379        // neighbourhood contribute.
380        let mut hash: usize = 0;
381
382        // Element sub-pass.
383        if aggressive {
384            for p in p1..p2 {
385                let e = ws.iw[p] as usize;
386                let we = ws.w[e];
387                if we != 0 {
388                    let dext = we - ws.wflg;
389                    if dext > 0 {
390                        deg += dext as usize;
391                        ws.iw[pn] = e as i32;
392                        pn += 1;
393                        hash = hash.wrapping_add(e);
394                    } else {
395                        // Aggressive absorption: dead element folded
396                        // into me right here (faer amd.rs:404-407).
397                        ws.pe[e] = flip(me as i32);
398                        ws.w[e] = 0;
399                    }
400                }
401            }
402        } else {
403            for p in p1..p2 {
404                let e = ws.iw[p] as usize;
405                let we = ws.w[e];
406                if we != 0 {
407                    // Invariant (O4): a live element in the non-aggressive pass
408                    // always has `we >= ws.wflg`, so the difference is
409                    // non-negative. Guard the unchecked `as usize` cast — a
410                    // future regression that broke the invariant would
411                    // sign-extend a negative difference to ~2^64 here.
412                    debug_assert!(
413                        we >= ws.wflg,
414                        "stale mark: w[e]={we} < wflg={} would wrap as usize",
415                        ws.wflg
416                    );
417                    let dext = (we - ws.wflg) as usize;
418                    deg += dext;
419                    ws.iw[pn] = e as i32;
420                    pn += 1;
421                    hash = hash.wrapping_add(e);
422                }
423            }
424        }
425
426        // Record number-of-elements + 1 (the +1 reserves the slot
427        // for `me` which we insert at p1 below).
428        ws.elen[i] = (pn - p1 + 1) as i32;
429        let p3 = pn;
430        let p4 = p1 + ws.len[i] as usize;
431        // Variable sub-pass.
432        for p in p2..p4 {
433            let j = ws.iw[p] as usize;
434            let nvj = ws.nv[j];
435            if nvj > 0 {
436                deg += nvj as usize;
437                ws.iw[pn] = j as i32;
438                pn += 1;
439                hash = hash.wrapping_add(j);
440            }
441        }
442
443        if ws.elen[i] == 1 && p3 == pn {
444            // Mass elimination: i's only element is `me` and it has
445            // no surviving outside variables, so it will pivot
446            // concurrently with me. Fold its supervariable count
447            // into nvpiv / nel and drop it from degme.
448            ws.pe[i] = flip(me as i32);
449            let nvi = -ws.nv[i];
450            debug_assert!(nvi >= 0);
451            degme -= nvi as usize;
452            nvpiv += nvi;
453            ws.nel += nvi as usize;
454            ws.nv[i] = 0;
455            ws.elen[i] = NONE;
456            ws.n_mass_elim += 1;
457        } else {
458            ws.degree[i] = ws.degree[i].min(deg as i32);
459            // Swap-dance to put `me` at the head of i's element list.
460            if p1 != pn {
461                ws.iw[pn] = ws.iw[p3];
462            }
463            if p3 != p1 {
464                ws.iw[p3] = ws.iw[p1];
465            }
466            ws.iw[p1] = me as i32;
467            ws.len[i] = (pn - p1 + 1) as i32;
468
469            // Insert i into a hash bucket threaded through
470            // head/next/last via sign-bit encoding (faer
471            // amd.rs:452-460). `head[hash] <= NONE` distinguishes
472            // two cases:
473            //  * NONE (-1) or flip(prev_head)<=-2 mean the bucket
474            //    is either empty or already a flip-encoded bucket
475            //    chain: next[i]=flip(old), head[hash]=flip(i).
476            //  * j>=0 means head[hash] still holds an unrelated
477            //    degree-list head. Hijack last[j] to chain
478            //    bucket members (last[j] is NONE for a list head,
479            //    so no information is destroyed).
480            let h = hash % ws.n;
481            let j = ws.head[h];
482            if j <= NONE {
483                ws.next[i] = flip(j);
484                ws.head[h] = flip(i as i32);
485            } else {
486                ws.next[i] = ws.last[j as usize];
487                ws.last[j as usize] = i as i32;
488            }
489            ws.last[i] = h as i32;
490        }
491    }
492
493    // Step bookkeeping (amd.rs:463-466). degme may have been reduced
494    // by mass elimination above.
495    let degme_i32 = degme as i32;
496    ws.degree[me] = degme_i32;
497    if degme_i32 > ws.lemax {
498        ws.lemax = degme_i32;
499    }
500    ws.wflg += ws.lemax;
501    ws.wflg = clear_flag(ws.wflg, ws.wbig, &mut ws.w);
502
503    // Supervariable detection (faer amd.rs:467-515). For each hash
504    // chain anchored at a still-marked member (nv[i] < 0), walk the
505    // chain marking i's variable neighbourhood with `wflg`, then
506    // compare each follower j to i: if len/elen agree AND every
507    // variable neighbour of j is also marked, merge j into i.
508    //
509    // head / next / last are being reused here as hash-bucket
510    // storage; they are restored to NONE at the heads involved so
511    // the subsequent degree-list re-insertion pass can rebuild the
512    // degree buckets cleanly.
513    for pme in pme1..pme2_excl {
514        let i_anchor = ws.iw[pme] as usize;
515        if ws.nv[i_anchor] >= 0 {
516            continue; // already restored / mass-elim'd
517        }
518        let h = ws.last[i_anchor] as usize;
519        let j_head = ws.head[h];
520        let mut i: i32 = if j_head == NONE {
521            NONE
522        } else if j_head < NONE {
523            // Bucket was flip-encoded: flip(j_head) is the head.
524            ws.head[h] = NONE;
525            flip(j_head)
526        } else {
527            // Bucket chained via last[j_head]; restore last[j_head].
528            let chain_start = ws.last[j_head as usize];
529            ws.last[j_head as usize] = NONE;
530            chain_start
531        };
532        while i != NONE && ws.next[i as usize] != NONE {
533            let i_u = i as usize;
534            let ln = ws.len[i_u];
535            let eln = ws.elen[i_u];
536            let pi = ws.pe[i_u];
537            // Mark i's neighbourhood (everything past slot pe[i]=me).
538            for p in (pi + 1) as usize..(pi + ln) as usize {
539                ws.w[ws.iw[p] as usize] = ws.wflg;
540            }
541            let mut jlast = i_u;
542            let mut jp = ws.next[i_u];
543            while jp != NONE {
544                let jj = jp as usize;
545                let mut ok = ws.len[jj] == ln && ws.elen[jj] == eln;
546                if ok {
547                    let pj = ws.pe[jj];
548                    for p in (pj + 1) as usize..(pj + ln) as usize {
549                        if ws.w[ws.iw[p] as usize] != ws.wflg {
550                            ok = false;
551                            break;
552                        }
553                    }
554                }
555                if ok {
556                    // Merge j into i: j becomes a degree-0 ghost
557                    // pointing at i via pe[j] = flip(i).
558                    ws.pe[jj] = flip(i);
559                    ws.nv[i_u] += ws.nv[jj];
560                    ws.nv[jj] = 0;
561                    ws.elen[jj] = NONE;
562                    jp = ws.next[jj];
563                    ws.next[jlast] = jp;
564                    ws.n_supervar_merge += 1;
565                } else {
566                    jlast = jj;
567                    jp = ws.next[jj];
568                }
569            }
570            // Bump wflg to reset marks for the next chain head.
571            ws.wflg += 1;
572            i = ws.next[i_u];
573        }
574    }
575
576    // Re-insertion (amd.rs:516-537): every surviving var in the new
577    // element list gets its new degree, is pushed onto head[deg]
578    // LIFO, and me's own list is compacted down to just the
579    // survivors.
580    let mut p_write = pme1;
581    let nleft = ws.n - ws.nel;
582    for pme in pme1..pme2_excl {
583        let i = ws.iw[pme] as usize;
584        let nvi = -ws.nv[i];
585        if nvi > 0 {
586            ws.nv[i] = nvi;
587            let mut d = ws.degree[i] as usize + degme_i32 as usize - nvi as usize;
588            let cap = nleft - nvi as usize;
589            if d > cap {
590                d = cap;
591            }
592            let inext = ws.head[d];
593            if inext != NONE {
594                ws.last[inext as usize] = i as i32;
595            }
596            ws.next[i] = inext;
597            ws.last[i] = NONE;
598            ws.head[d] = i as i32;
599            if d < ws.mindeg {
600                ws.mindeg = d;
601            }
602            ws.degree[i] = d as i32;
603            ws.iw[p_write] = i as i32;
604            p_write += 1;
605        }
606    }
607
608    // Me bookkeeping (amd.rs:538-546).
609    ws.nv[me] = nvpiv;
610    ws.len[me] = (p_write as i32) - pme1 as i32;
611    if ws.len[me] == 0 {
612        ws.pe[me] = NONE;
613        ws.w[me] = 0;
614    }
615    if elenme != 0 {
616        ws.pfree = p_write;
617    }
618
619    // Flop counters (amd.rs:547-557).
620    let f = nvpiv as f64;
621    let r = degme_i32 as f64 + ws.ndense as f64;
622    let lnzme = f * r + (f - 1.0) * f / 2.0;
623    let s = f * r * r + r * (f - 1.0) * f + (f - 1.0) * f * (2.0 * f - 1.0) / 6.0;
624
625    StepFlops {
626        ndiv: lnzme,
627        nms_lu: s,
628        nms_ldl: (s + lnzme) / 2.0,
629    }
630}
631
632/// AMF bucket index for a quantized fill score (`MinFill::bucket`).
633///
634/// Mirrors the metric trait's `MinFill::bucket` but is duplicated as a
635/// free function here so `algo.rs` does not need a back-edge to
636/// `metric.rs` (which itself imports from `algo`). Inlined.
637#[inline(always)]
638fn amf_bucket_of(score: i64, n: usize) -> usize {
639    if score <= 0 {
640        return 0;
641    }
642    let s = score as usize;
643    if s <= n {
644        return s;
645    }
646    let pas = (n / 8).max(1);
647    let nbbuck = 2 * n;
648    ((s - n) / pas + n).min(nbbuck)
649}
650
651/// AMF working-fill *surface contribution* of an element with current
652/// external degree `dext` and total degree `degree`:
653/// `dext * (2*degree - dext - 1)` (Amestoy 1999 thesis; MUMPS
654/// `ana_orderings.F:4810`).
655///
656/// Computed in `i64`: both factors are `O(n)`, so the product reaches
657/// ~`n^2` and overflows `i32` for `n` ≳ 46k (`i32::MAX` is
658/// 2_147_483_647 and `46342 * 46341 = 2_147_534_622` already exceeds
659/// it). In release the old `i32` form wrapped silently, feeding garbage
660/// into the RMF pivot score; in debug it panicked. The value is later
661/// consumed as `f64`, so widening loses no precision (O1,
662/// `dev/research/repo-review-2026-06-09.md`).
663#[inline(always)]
664fn amf_wf_surface(dext: i64, degree: i64) -> i64 {
665    dext * (2 * degree - dext - 1)
666}
667
668/// AMF per-supervariable working-fill accumulation
669/// `wf4 + 2 * nvi * wf3` (Amestoy 1999 eq. for the B3 contribution;
670/// MUMPS `ana_orderings.F:4810`). Computed in `i64` for the same
671/// `O(n^2)` overflow reason as [`amf_wf_surface`]: `nvi` (supervariable
672/// size) and `wf3` (sum of neighbour supervariable sizes) are each
673/// `O(n)` (O1, `dev/research/repo-review-2026-06-09.md`).
674#[inline(always)]
675fn amf_wf_combine(wf4: i64, nvi: i64, wf3: i64) -> i64 {
676    wf4 + 2 * nvi * wf3
677}
678
679/// Saturation cap for the quantized AMF score (issue #246).
680///
681/// Far below `i64::MAX` (~9.2e18) so the supervariable max-merge and the
682/// bucket arithmetic in [`amf_bucket_of`] cannot overflow, and far above
683/// any score that can still discriminate pivots: every key above the
684/// coarse range already shares bucket `NBBUCK`, where
685/// [`select_pivot_amf`] compares exact keys.
686const AMF_SCORE_CAP: i64 = 1_000_000_000_000_000_000;
687
688/// Quantize the AMF approximate-fill score `RMF` (already divided by
689/// `nv + 1`) into the integer bucket key stored in `wf[i]`:
690/// `clamp(round(rmf), 1, AMF_SCORE_CAP)`.
691///
692/// **Deliberate deviation from MUMPS** (issue #246,
693/// `dev/research/issue-246-amf-quantization.md`). MUMPS 5.8.2 HAMF4
694/// (`ana_orderings.F:4985-4994`) stores the key in a 32-bit `INTEGER`
695/// and, for `RMF >= huge-1`, falls through to `round(RMF / N)`. That map
696/// is not monotone: at `n = 1.9M` a score of 3e9 is stored as ~1.6e3,
697/// below a score of 2e9, so near-dense variables are filed as cheap and
698/// eliminated early. On the fhnw-binschedule1 KKT that inflated nnz(L)
699/// 76× (1.39e10 vs 1.84e8). `wf` is `i64` here, so the exact rounded
700/// score fits and the key is monotone in `RMF`. Below `2^31` the result
701/// is bit-identical to MUMPS (including the `max(1, ·)` floor).
702#[inline]
703fn amf_quantize_score(rmf: f64) -> i64 {
704    // `f64 as i64` saturates (and maps NaN to 0), so the clamp below is
705    // total on every input.
706    (rmf.round() as i64).clamp(1, AMF_SCORE_CAP)
707}
708
709/// AMF analogue of [`select_pivot`]. Linear-scans coarse buckets
710/// (`idx > n`) for the entry with the smallest exact score; takes the
711/// head for fine buckets.
712///
713/// Side effects: `ws.mindeg` advances to the chosen bucket index. The
714/// chosen `me` is unlinked from its degree-list chain (head update for
715/// fine buckets, doubly-linked unlink for coarse buckets).
716///
717/// Reference: `ana_orderings.F:4392-4427`.
718pub fn select_pivot_amf(ws: &mut Workspace) -> Option<usize> {
719    let n = ws.n;
720    let nbuck = ws.head.len();
721    let mut deg = ws.mindeg;
722    while deg < nbuck && ws.head[deg] == NONE {
723        deg += 1;
724    }
725    if deg >= nbuck {
726        return None;
727    }
728    ws.mindeg = deg;
729    let head_me = ws.head[deg] as usize;
730
731    let me;
732    if deg > n {
733        // Coarse bucket: linear scan for the minimum-score entry.
734        let mut best = head_me;
735        let mut best_score = ws.wf[best];
736        let mut j = ws.next[best];
737        while j != NONE {
738            let ju = j as usize;
739            if ws.wf[ju] < best_score {
740                best_score = ws.wf[ju];
741                best = ju;
742            }
743            j = ws.next[ju];
744        }
745        me = best;
746        // Doubly-linked unlink (best may be mid-chain).
747        let ilast = ws.last[me];
748        let inext = ws.next[me];
749        if inext != NONE {
750            ws.last[inext as usize] = ilast;
751        }
752        if ilast != NONE {
753            ws.next[ilast as usize] = inext;
754        } else {
755            ws.head[deg] = inext;
756        }
757    } else {
758        me = head_me;
759        let inext = ws.next[me];
760        if inext != NONE {
761            ws.last[inext as usize] = NONE;
762        }
763        ws.head[deg] = inext;
764    }
765    Some(me)
766}
767
768/// AMF analogue of [`create_element`]. Identical structure; differs
769/// only in the bucket-index used when unlinking absorbed neighbours
770/// from their degree lists. AMD reads `degree[i]` (which doubles as
771/// the bucket index because AMD's bucket is identity); AMF computes
772/// `amf_bucket_of(wf[i], n)` because the AMF score and running degree
773/// are stored in distinct fields (`wf` vs `degree`).
774pub fn create_element_amf(
775    ws: &mut Workspace,
776    me: usize,
777) -> Result<(usize, usize, i32, usize), OrderingError> {
778    let n = ws.n;
779    let elenme = ws.elen[me];
780    let nvpiv = ws.nv[me];
781    ws.nel += nvpiv as usize;
782    ws.nv[me] = -nvpiv;
783    let mut degme: usize = 0;
784    let pme1: usize;
785    let pme2: i32;
786
787    if elenme == 0 {
788        let pme1_s = ws.pe[me];
789        pme1 = pme1_s as usize;
790        let list_start = pme1;
791        let list_end = list_start + ws.len[me] as usize;
792        let mut pme2_s = pme1_s - 1;
793        for p in list_start..list_end {
794            let i = ws.iw[p] as usize;
795            let nvi = ws.nv[i];
796            if nvi > 0 {
797                degme += nvi as usize;
798                ws.nv[i] = -nvi;
799                pme2_s += 1;
800                ws.iw[pme2_s as usize] = i as i32;
801                let ilast = ws.last[i];
802                let inext = ws.next[i];
803                if inext != NONE {
804                    ws.last[inext as usize] = ilast;
805                }
806                if ilast != NONE {
807                    ws.next[ilast as usize] = inext;
808                } else {
809                    let h_idx = amf_bucket_of(ws.wf[i], n);
810                    ws.head[h_idx] = inext;
811                }
812            }
813        }
814        pme2 = pme2_s;
815    } else {
816        let mut p = ws.pe[me] as usize;
817        let mut pme1_rw: usize = ws.pfree;
818        let slenme = (ws.len[me] - elenme) as usize;
819        let elenme_u = elenme as usize;
820        for knt1 in 1..=elenme_u + 1 {
821            let e: usize;
822            let mut pj: usize;
823            let ln: usize;
824            if knt1 > elenme_u {
825                e = me;
826                pj = p;
827                ln = slenme;
828            } else {
829                e = ws.iw[p] as usize;
830                p += 1;
831                pj = ws.pe[e] as usize;
832                ln = ws.len[e] as usize;
833            }
834            for knt2 in 1..=ln {
835                let i = ws.iw[pj] as usize;
836                pj += 1;
837                let nvi = ws.nv[i];
838                if nvi > 0 {
839                    if ws.pfree >= ws.iwlen {
840                        ws.pe[me] = p as i32;
841                        ws.len[me] -= knt1 as i32;
842                        if ws.len[me] == 0 {
843                            ws.pe[me] = NONE;
844                        }
845                        ws.pe[e] = pj as i32;
846                        ws.len[e] = (ln - knt2) as i32;
847                        if ws.len[e] == 0 {
848                            ws.pe[e] = NONE;
849                        }
850                        ws.ncmpa += 1;
851                        for j in 0..ws.n {
852                            let pn = ws.pe[j];
853                            if pn >= 0 {
854                                let pn_u = pn as usize;
855                                ws.pe[j] = ws.iw[pn_u];
856                                ws.iw[pn_u] = flip(j as i32);
857                            }
858                        }
859                        let mut psrc = 0usize;
860                        let mut pdst = 0usize;
861                        let pend = pme1_rw;
862                        while psrc < pend {
863                            let j_marker = flip(ws.iw[psrc]);
864                            psrc += 1;
865                            if j_marker >= 0 {
866                                let j = j_marker as usize;
867                                ws.iw[pdst] = ws.pe[j];
868                                ws.pe[j] = pdst as i32;
869                                pdst += 1;
870                                let lenj = ws.len[j] as usize;
871                                if lenj > 0 {
872                                    ws.iw.copy_within(psrc..psrc + lenj - 1, pdst);
873                                    psrc += lenj - 1;
874                                    pdst += lenj - 1;
875                                }
876                            }
877                        }
878                        let p1 = pdst;
879                        ws.iw.copy_within(pme1_rw..ws.pfree, pdst);
880                        pdst += ws.pfree - pme1_rw;
881                        pme1_rw = p1;
882                        ws.pfree = pdst;
883                        pj = ws.pe[e] as usize;
884                        p = ws.pe[me] as usize;
885                    }
886                    degme += nvi as usize;
887                    ws.nv[i] = -nvi;
888                    ws.iw[ws.pfree] = i as i32;
889                    ws.pfree += 1;
890                    let ilast = ws.last[i];
891                    let inext = ws.next[i];
892                    if inext != NONE {
893                        ws.last[inext as usize] = ilast;
894                    }
895                    if ilast != NONE {
896                        ws.next[ilast as usize] = inext;
897                    } else {
898                        let h_idx = amf_bucket_of(ws.wf[i], n);
899                        ws.head[h_idx] = inext;
900                    }
901                }
902            }
903            if e != me {
904                ws.pe[e] = flip(me as i32);
905                ws.w[e] = 0;
906            }
907        }
908        pme1 = pme1_rw;
909        pme2 = (ws.pfree - 1) as i32;
910    }
911
912    ws.degree[me] = degme as i32;
913    ws.pe[me] = pme1 as i32;
914    ws.len[me] = pme2 - pme1 as i32 + 1;
915    ws.elen[me] = flip(nvpiv + degme as i32);
916    ws.wflg = clear_flag(ws.wflg, ws.wbig, &mut ws.w);
917
918    let pme2_excl: usize = if pme2 < pme1 as i32 {
919        pme1
920    } else {
921        (pme2 + 1) as usize
922    };
923    Ok((pme1, pme2_excl, nvpiv, degme))
924}
925
926/// AMF analogue of [`finalize_step`]. The Pass-1 element seeding,
927/// hash-bucket detection, and supervariable-merge structure mirror
928/// AMD; the per-iteration accumulator carries the AMF triple
929/// `(deg, wf3, wf4)` (Amestoy 1999 thesis), and the re-insertion
930/// computes the quantized RMF score and inserts at
931/// `head[amf_bucket_of(wf[i], n)]`.
932///
933/// Six metric-specific sites compared to AMD (numbered per
934/// `dev/research/amf-clean-room.md` Section 6):
935/// 1. Pass-1 also resets `wf[e] = 0` on the first touch of each
936///    element (lazy cache sentinel).
937/// 2. Pass-2 element walk caches `wf[e] = dext * (2*deg(e) - dext - 1)`
938///    on first encounter and accumulates `wf4 += wf[e]`.
939/// 3. Pass-2 variable walk accumulates `wf3 += nv[j]`.
940/// 4. Loose-degree special case zeroes `wf3 = wf4 = 0`; the kept
941///    `degree[i]` cannot have a meaningful WF-subtraction so the
942///    AMF score is reset.
943/// 5. Supervariable merge takes `wf[i] = max(wf[i], wf[j])`.
944/// 6. Re-insertion uses the saturated/regular RMF formula, quantizes
945///    monotonically via [`amf_quantize_score`] (issue #246: no MUMPS
946///    `RMF / N` fall-through), buckets via `bucket(wf[i], n)`, and
947///    threads through `head` of length `2 * n + 2`.
948///
949/// Reference: `ana_orderings.F:4660-5025`.
950#[allow(clippy::too_many_arguments)]
951pub fn finalize_step_amf(
952    ws: &mut Workspace,
953    me: usize,
954    pme1: usize,
955    pme2_excl: usize,
956    nvpiv: i32,
957    degme: usize,
958    elenme: i32,
959    aggressive: bool,
960) -> StepFlops {
961    let n = ws.n;
962    let mut degme = degme;
963    let mut nvpiv = nvpiv;
964
965    // Pass 1: seed w[e] for every element in each member's list, and
966    // reset wf[e] = 0 on the first touch (lazy cache for Pass-2).
967    for pme in pme1..pme2_excl {
968        let i = ws.iw[pme] as usize;
969        let eln = ws.elen[i];
970        if eln > 0 {
971            let nvi = -ws.nv[i];
972            let wnvi = ws.wflg - nvi;
973            let pi = ws.pe[i] as usize;
974            for k in 0..eln as usize {
975                let e = ws.iw[pi + k] as usize;
976                let mut we = ws.w[e];
977                if we >= ws.wflg {
978                    we -= nvi;
979                } else if we != 0 {
980                    we = ws.degree[e] + wnvi;
981                    // O21 (repo-review-2026-06-09): `wf[e] = 0` is the
982                    // lazy-cache "surface not yet computed this iteration"
983                    // sentinel for Pass-2 below. It is intentionally NOT
984                    // distinct from a genuine surface contribution of 0:
985                    // `amf_wf_surface(dext, deg) = dext*(2*deg - dext - 1)`
986                    // is 0 for a live element whenever `dext == 2*deg(e)-1`
987                    // (e.g. dext=1, deg=1). When that happens `wf[e]` stays
988                    // 0, so the Pass-2 `if wf[e] == 0` check re-treats it as
989                    // uncached and recomputes the surface for every member
990                    // that touches `e`. This is benign: `amf_wf_surface` is
991                    // pure in (dext, degree[e]) — both stable across one
992                    // Pass-2 — so the recompute yields the same 0 and the
993                    // accumulated `wf4` (hence the RMF score and the
994                    // permutation) is unchanged; only a few integer multiplies
995                    // are redundant. A distinguishing sentinel (e.g. -1) was
996                    // rejected: `wf` is reused for variable scores
997                    // (supervariable-merge `max`, re-insertion bucket
998                    // quantization), so -1 would have to be proven never to
999                    // leak into either across the AMD and AMF paths — added
1000                    // correctness risk for a handful of saved ops.
1001                    // "Correctness before performance." See
1002                    // dev/tried-and-rejected.md (O21).
1003                    ws.wf[e] = 0;
1004                }
1005                ws.w[e] = we;
1006            }
1007        }
1008    }
1009
1010    // Pass 2: AMF triple-accumulator (deg, wf3, wf4), aggressive
1011    // absorption on dext == 0, mass elimination, hash-bucket insert.
1012    for pme in pme1..pme2_excl {
1013        let i = ws.iw[pme] as usize;
1014        let p1 = ws.pe[i] as usize;
1015        let p2 = p1 + ws.elen[i] as usize;
1016        let mut pn = p1;
1017        let mut deg: usize = 0;
1018        let mut hash: usize = 0;
1019        let mut wf3: i64 = 0;
1020        let mut wf4: i64 = 0;
1021        let nvi = -ws.nv[i];
1022
1023        // Element sub-pass.
1024        if aggressive {
1025            for p in p1..p2 {
1026                let e = ws.iw[p] as usize;
1027                let we = ws.w[e];
1028                if we != 0 {
1029                    let dext = we - ws.wflg;
1030                    if dext > 0 {
1031                        // `wf[e] == 0` means "uncached this iter" OR a genuine
1032                        // 0 surface (O21) — recompute on the latter is benign
1033                        // (same value). See the Pass-1 reset comment above.
1034                        if ws.wf[e] == 0 {
1035                            // First touch this iter: cache the surface
1036                            // contribution dext*(2*deg(e) - dext - 1).
1037                            ws.wf[e] = amf_wf_surface(dext as i64, ws.degree[e] as i64);
1038                        }
1039                        wf4 += ws.wf[e];
1040                        deg += dext as usize;
1041                        ws.iw[pn] = e as i32;
1042                        pn += 1;
1043                        hash = hash.wrapping_add(e);
1044                    } else {
1045                        // Aggressive absorption.
1046                        ws.pe[e] = flip(me as i32);
1047                        ws.w[e] = 0;
1048                    }
1049                }
1050            }
1051        } else {
1052            for p in p1..p2 {
1053                let e = ws.iw[p] as usize;
1054                let we = ws.w[e];
1055                if we != 0 {
1056                    let dext = we - ws.wflg;
1057                    // Invariant (O4): non-aggressive pass keeps `we >= ws.wflg`,
1058                    // so `dext >= 0`. Guard the `dext as usize` cast below
1059                    // against a future regression wrapping a negative dext to
1060                    // ~2^64.
1061                    debug_assert!(
1062                        dext >= 0,
1063                        "stale mark: w[e]={we} < wflg={} would wrap as usize",
1064                        ws.wflg
1065                    );
1066                    // `wf[e] == 0` means "uncached this iter" OR a genuine 0
1067                    // surface (O21) — recompute on the latter is benign (same
1068                    // value). See the Pass-1 reset comment above.
1069                    if ws.wf[e] == 0 {
1070                        ws.wf[e] = amf_wf_surface(dext as i64, ws.degree[e] as i64);
1071                    }
1072                    wf4 += ws.wf[e];
1073                    deg += dext as usize;
1074                    ws.iw[pn] = e as i32;
1075                    pn += 1;
1076                    hash = hash.wrapping_add(e);
1077                }
1078            }
1079        }
1080
1081        ws.elen[i] = (pn - p1 + 1) as i32;
1082        let p3 = pn;
1083        let p4 = p1 + ws.len[i] as usize;
1084        // Variable sub-pass.
1085        for p in p2..p4 {
1086            let j = ws.iw[p] as usize;
1087            let nvj = ws.nv[j];
1088            if nvj > 0 {
1089                deg += nvj as usize;
1090                wf3 += nvj as i64;
1091                ws.iw[pn] = j as i32;
1092                pn += 1;
1093                hash = hash.wrapping_add(j);
1094            }
1095        }
1096
1097        if ws.elen[i] == 1 && p3 == pn {
1098            // Mass elimination (equivalent to MUMPS DEG==0 in
1099            // aggressive / non-halo mode).
1100            ws.pe[i] = flip(me as i32);
1101            let nvi_sv = -ws.nv[i];
1102            debug_assert!(nvi_sv >= 0);
1103            degme -= nvi_sv as usize;
1104            nvpiv += nvi_sv;
1105            ws.nel += nvi_sv as usize;
1106            ws.nv[i] = 0;
1107            ws.elen[i] = NONE;
1108            ws.n_mass_elim += 1;
1109        } else {
1110            // Loose-degree special case: if the prior degree estimate
1111            // is already tighter, keep it but the WF accumulator is
1112            // not subtraction-safe — zero it.
1113            if ws.degree[i] < deg as i32 {
1114                wf3 = 0;
1115                wf4 = 0;
1116            } else {
1117                ws.degree[i] = deg as i32;
1118            }
1119            // wf[i] = wf4 + 2 * nvi * wf3 (Amestoy 1999 eq. for B3
1120            // contribution; see ana_orderings.F:4810).
1121            ws.wf[i] = amf_wf_combine(wf4, nvi as i64, wf3);
1122
1123            // Swap-dance to put `me` at the head of i's element list.
1124            if p1 != pn {
1125                ws.iw[pn] = ws.iw[p3];
1126            }
1127            if p3 != p1 {
1128                ws.iw[p3] = ws.iw[p1];
1129            }
1130            ws.iw[p1] = me as i32;
1131            ws.len[i] = (pn - p1 + 1) as i32;
1132
1133            // Hash-bucket insertion (sign-bit encoding identical to
1134            // AMD; head reuse is safe because hash mod n falls in
1135            // the fine bucket region [0, n)).
1136            let h = hash % n;
1137            let j = ws.head[h];
1138            if j <= NONE {
1139                ws.next[i] = flip(j);
1140                ws.head[h] = flip(i as i32);
1141            } else {
1142                ws.next[i] = ws.last[j as usize];
1143                ws.last[j as usize] = i as i32;
1144            }
1145            ws.last[i] = h as i32;
1146        }
1147    }
1148
1149    let degme_i32 = degme as i32;
1150    ws.degree[me] = degme_i32;
1151    if degme_i32 > ws.lemax {
1152        ws.lemax = degme_i32;
1153    }
1154    ws.wflg += ws.lemax;
1155    ws.wflg = clear_flag(ws.wflg, ws.wbig, &mut ws.w);
1156
1157    // Supervariable detection. Identical to AMD except merge updates
1158    // wf[i] = max(wf[i], wf[j]).
1159    for pme in pme1..pme2_excl {
1160        let i_anchor = ws.iw[pme] as usize;
1161        if ws.nv[i_anchor] >= 0 {
1162            continue;
1163        }
1164        let h = ws.last[i_anchor] as usize;
1165        let j_head = ws.head[h];
1166        let mut i: i32 = if j_head == NONE {
1167            NONE
1168        } else if j_head < NONE {
1169            ws.head[h] = NONE;
1170            flip(j_head)
1171        } else {
1172            let chain_start = ws.last[j_head as usize];
1173            ws.last[j_head as usize] = NONE;
1174            chain_start
1175        };
1176        while i != NONE && ws.next[i as usize] != NONE {
1177            let i_u = i as usize;
1178            let ln = ws.len[i_u];
1179            let eln = ws.elen[i_u];
1180            let pi = ws.pe[i_u];
1181            for p in (pi + 1) as usize..(pi + ln) as usize {
1182                ws.w[ws.iw[p] as usize] = ws.wflg;
1183            }
1184            let mut jlast = i_u;
1185            let mut jp = ws.next[i_u];
1186            while jp != NONE {
1187                let jj = jp as usize;
1188                let mut ok = ws.len[jj] == ln && ws.elen[jj] == eln;
1189                if ok {
1190                    let pj = ws.pe[jj];
1191                    for p in (pj + 1) as usize..(pj + ln) as usize {
1192                        if ws.w[ws.iw[p] as usize] != ws.wflg {
1193                            ok = false;
1194                            break;
1195                        }
1196                    }
1197                }
1198                if ok {
1199                    ws.pe[jj] = flip(i);
1200                    // AMF merge: wf takes the max of the two scores.
1201                    let wf_j = ws.wf[jj];
1202                    if wf_j > ws.wf[i_u] {
1203                        ws.wf[i_u] = wf_j;
1204                    }
1205                    ws.nv[i_u] += ws.nv[jj];
1206                    ws.nv[jj] = 0;
1207                    ws.elen[jj] = NONE;
1208                    jp = ws.next[jj];
1209                    ws.next[jlast] = jp;
1210                    ws.n_supervar_merge += 1;
1211                } else {
1212                    jlast = jj;
1213                    jp = ws.next[jj];
1214                }
1215            }
1216            ws.wflg += 1;
1217            i = ws.next[i_u];
1218        }
1219    }
1220
1221    // Re-insertion: AMF saturated/regular RMF, quantize, bucket.
1222    let mut p_write = pme1;
1223    let nleft = ws.n - ws.nel;
1224    for pme in pme1..pme2_excl {
1225        let i = ws.iw[pme] as usize;
1226        let nvi = -ws.nv[i];
1227        if nvi > 0 {
1228            ws.nv[i] = nvi;
1229            let degme_i = degme_i32;
1230            let nvi_i = nvi;
1231            let deg_i = ws.degree[i];
1232            let rmf: f64 = if (deg_i as usize) + (degme_i as usize) > nleft {
1233                // Saturated branch. RMF1 uses original DEG.
1234                let deg_f = deg_i as f64;
1235                let rmf1 = deg_f * (deg_f - 1.0 + 2.0 * degme_i as f64) - ws.wf[i] as f64;
1236                let new_deg = (nleft as i32) - nvi_i;
1237                ws.degree[i] = new_deg;
1238                let nd = new_deg as f64;
1239                let rmf_new =
1240                    nd * (nd - 1.0) - (degme_i - nvi_i) as f64 * (degme_i - nvi_i - 1) as f64;
1241                rmf_new.min(rmf1)
1242            } else {
1243                let deg_f = deg_i as f64;
1244                ws.degree[i] = deg_i + degme_i - nvi_i;
1245                deg_f * (deg_f - 1.0 + 2.0 * degme_i as f64) - ws.wf[i] as f64
1246            };
1247            let rmf = rmf / (nvi_i as f64 + 1.0);
1248            ws.wf[i] = amf_quantize_score(rmf);
1249
1250            let d = amf_bucket_of(ws.wf[i], n);
1251            let inext = ws.head[d];
1252            if inext != NONE {
1253                ws.last[inext as usize] = i as i32;
1254            }
1255            ws.next[i] = inext;
1256            ws.last[i] = NONE;
1257            ws.head[d] = i as i32;
1258            if d < ws.mindeg {
1259                ws.mindeg = d;
1260            }
1261            ws.iw[p_write] = i as i32;
1262            p_write += 1;
1263        }
1264    }
1265
1266    // Me bookkeeping (same as AMD).
1267    ws.nv[me] = nvpiv;
1268    ws.len[me] = (p_write as i32) - pme1 as i32;
1269    if ws.len[me] == 0 {
1270        ws.pe[me] = NONE;
1271        ws.w[me] = 0;
1272    }
1273    if elenme != 0 {
1274        ws.pfree = p_write;
1275    }
1276
1277    // Flop counters (identical to AMD).
1278    let f = nvpiv as f64;
1279    let r = degme_i32 as f64 + ws.ndense as f64;
1280    let lnzme = f * r + (f - 1.0) * f / 2.0;
1281    let s = f * r * r + r * (f - 1.0) * f + (f - 1.0) * f * (2.0 * f - 1.0) / 6.0;
1282
1283    StepFlops {
1284        ndiv: lnzme,
1285        nms_lu: s,
1286        nms_ldl: (s + lnzme) / 2.0,
1287    }
1288}
1289
1290/// Pivots between interrupt polls in the elimination loops (issue #246).
1291/// A poll is a thread-local read plus, with a deadline set, one
1292/// `Instant::now()` (~25 ns), so a stride of 64 keeps the overhead far below
1293/// a pivot's cost while bounding the overshoot to 64 pivots.
1294const INTERRUPT_POLL_STRIDE: usize = 64;
1295
1296/// AMF analogue of [`run_elimination`].
1297pub fn run_elimination_amf(
1298    ws: &mut Workspace,
1299    aggressive: bool,
1300) -> Result<StepFlops, OrderingError> {
1301    let mut flops = StepFlops::default();
1302    // Issue #246: poll the active interrupt every `INTERRUPT_POLL_STRIDE`
1303    // pivots, starting with the first. The workspace is abandoned on
1304    // `Err`, so stopping between pivots is always safe.
1305    let mut since_poll = 0usize;
1306    while ws.nel < ws.n {
1307        if since_poll == 0 {
1308            crate::interrupt::check()?;
1309        }
1310        since_poll = (since_poll + 1) % INTERRUPT_POLL_STRIDE;
1311        let me = match select_pivot_amf(ws) {
1312            Some(m) => m,
1313            None => break,
1314        };
1315        let elenme = ws.elen[me];
1316        let (pme1, pme2, nvpiv, degme) = create_element_amf(ws, me)?;
1317        flops.accumulate(finalize_step_amf(
1318            ws, me, pme1, pme2, nvpiv, degme, elenme, aggressive,
1319        ));
1320    }
1321    let f = ws.ndense as f64;
1322    let lnzme = (f - 1.0) * f / 2.0;
1323    let s = (f - 1.0) * f * (2.0 * f - 1.0) / 6.0;
1324    flops.ndiv += lnzme;
1325    flops.nms_lu += s;
1326    flops.nms_ldl += (s + lnzme) / 2.0;
1327    Ok(flops)
1328}
1329
1330/// Run the main AMD elimination loop until every live supervariable
1331/// has been either pivoted or dense-deferred. Returns the
1332/// accumulated flop counts.
1333///
1334/// Mass elimination and supervariable detection are absent (Slice
1335/// B). Inline garbage collection is live; fixtures whose working
1336/// set transiently exceeds `iwlen` recover via in-place compaction
1337/// and bump `ws.ncmpa`.
1338///
1339/// At exit: `ws.nel == ws.n`, every `pe[i]` either points to a
1340/// live parent (to be path-compressed by the postorder phase) or
1341/// is `NONE` / `flip(parent)`.
1342pub fn run_elimination(ws: &mut Workspace, aggressive: bool) -> Result<StepFlops, OrderingError> {
1343    let mut flops = StepFlops::default();
1344    // Issue #246: poll the active interrupt every `INTERRUPT_POLL_STRIDE`
1345    // pivots, starting with the first. The workspace is abandoned on
1346    // `Err`, so stopping between pivots is always safe.
1347    let mut since_poll = 0usize;
1348    while ws.nel < ws.n {
1349        if since_poll == 0 {
1350            crate::interrupt::check()?;
1351        }
1352        since_poll = (since_poll + 1) % INTERRUPT_POLL_STRIDE;
1353        let me = match select_pivot(ws) {
1354            Some(m) => m,
1355            None => break, // only dense-deferred survivors remain
1356        };
1357        let elenme = ws.elen[me];
1358        let (pme1, pme2, nvpiv, degme) = create_element(ws, me)?;
1359        flops.accumulate(finalize_step(
1360            ws, me, pme1, pme2, nvpiv, degme, elenme, aggressive,
1361        ));
1362    }
1363    // Dense-phase flop contribution (amd.rs:559-566).
1364    let f = ws.ndense as f64;
1365    let lnzme = (f - 1.0) * f / 2.0;
1366    let s = (f - 1.0) * f * (2.0 * f - 1.0) / 6.0;
1367    flops.ndiv += lnzme;
1368    flops.nms_lu += s;
1369    flops.nms_ldl += (s + lnzme) / 2.0;
1370    Ok(flops)
1371}
1372
1373/// Consume the post-elimination state and produce the final
1374/// permutation.
1375///
1376/// On entry `ws` must have completed [`run_elimination`]. Performs,
1377/// in order:
1378/// 1. Un-flip `pe` and `elen` (faer `amd.rs:567-572`) so `pe[i]`
1379///    holds the parent pivot and `elen[i]` holds the frontal size.
1380/// 2. Path compression (`amd.rs:573-590`): each absorbed
1381///    supervariable `i` (`nv[i] == 0`) has its `pe` chain walked
1382///    until a pivot is found, then all intermediates are rewritten
1383///    to point at that pivot directly. Inert in Slice A — becomes
1384///    active once supervariable detection (Slice B) lands.
1385/// 3. Assembly-tree postorder with big-child-last heuristic
1386///    (`amd.rs:5-49`, `amd.rs:51-124`, `amd.rs:593-599`). Reuses
1387///    `head`/`next`/`last` as child/sibling/stack scratch; writes
1388///    the postorder index into `w`.
1389/// 4. Invert `w` into `head[k] = pivot at postorder k`
1390///    (`amd.rs:600-606`).
1391/// 5. Assign starting positions to each pivot's block
1392///    (`amd.rs:607-615`): `next[e] = nel`, then `nel += nv[e]`.
1393/// 6. Expand absorbed supervariables + place dense-deferred variables
1394///    at the tail (`amd.rs:617-629`).
1395/// 7. Emit `perm`: `perm[next[i]] = i` for every `i`
1396///    (`amd.rs:631-633`).
1397///
1398/// Returns a permutation `perm` of length `n` where `perm[k]` is the
1399/// column of the original matrix to be eliminated at step `k`.
1400pub fn finalize_permutation(ws: &mut Workspace) -> Vec<i32> {
1401    let n = ws.n;
1402    if n == 0 {
1403        return Vec::new();
1404    }
1405
1406    // Step 1: un-flip.
1407    for x in ws.pe.iter_mut() {
1408        *x = flip(*x);
1409    }
1410    for x in ws.elen.iter_mut() {
1411        *x = flip(*x);
1412    }
1413
1414    // Step 2: path-compress absorbed supervariables.
1415    for i in 0..n {
1416        if ws.nv[i] == 0 {
1417            let head_i = ws.pe[i];
1418            if head_i == NONE {
1419                continue;
1420            }
1421            let mut j = head_i as usize;
1422            while ws.nv[j] == 0 {
1423                j = ws.pe[j] as usize;
1424            }
1425            let e = j as i32;
1426            let mut j = i;
1427            while ws.nv[j] == 0 {
1428                let jnext = ws.pe[j];
1429                ws.pe[j] = e;
1430                j = jnext as usize;
1431            }
1432        }
1433    }
1434
1435    // Step 3: assembly-tree postorder. Writes postorder index into w.
1436    assembly_tree_postorder(ws);
1437
1438    // Step 4: invert w into head.
1439    for x in ws.head.iter_mut() {
1440        *x = NONE;
1441    }
1442    for e in 0..n {
1443        let k = ws.w[e];
1444        if k != NONE {
1445            ws.head[k as usize] = e as i32;
1446        }
1447    }
1448
1449    // Step 5: pivot-block starting positions.
1450    for x in ws.next.iter_mut() {
1451        *x = NONE;
1452    }
1453    let mut nel: i32 = 0;
1454    for &e in ws.head.iter() {
1455        if e == NONE {
1456            break;
1457        }
1458        let eu = e as usize;
1459        ws.next[eu] = nel;
1460        nel += ws.nv[eu];
1461    }
1462
1463    // Step 6: expand absorbed supervars + place dense-deferred at tail.
1464    for i in 0..n {
1465        if ws.nv[i] == 0 {
1466            let e = ws.pe[i];
1467            if e != NONE {
1468                let eu = e as usize;
1469                ws.next[i] = ws.next[eu];
1470                ws.next[eu] += 1;
1471            } else {
1472                ws.next[i] = nel;
1473                nel += 1;
1474            }
1475        }
1476    }
1477
1478    // Step 7: emit perm.
1479    let mut perm = vec![0i32; n];
1480    for i in 0..n {
1481        perm[ws.next[i] as usize] = i as i32;
1482    }
1483    perm
1484}
1485
1486/// Build the assembly tree from `pe` (parent pointers) + `nv`
1487/// (`> 0` selects pivots), apply the big-child-last heuristic, and
1488/// run an iterative DFS postorder. Result indexes go into `ws.w`
1489/// (NONE for non-pivot nodes).
1490fn assembly_tree_postorder(ws: &mut Workspace) {
1491    let n = ws.n;
1492    // Repurpose head/next/last as child/sibling/stack scratch.
1493    for x in ws.head.iter_mut() {
1494        *x = NONE;
1495    }
1496    for x in ws.next.iter_mut() {
1497        *x = NONE;
1498    }
1499    // Link each pivot as a child of its parent. Reverse order so that
1500    // after building, child lists are in ascending index order.
1501    for j in (0..n).rev() {
1502        if ws.nv[j] > 0 {
1503            let parent = ws.pe[j];
1504            if parent >= 0 && (parent as usize) < n {
1505                let pu = parent as usize;
1506                ws.next[j] = ws.head[pu];
1507                ws.head[pu] = j as i32;
1508            }
1509        }
1510    }
1511    // Big-child-last heuristic: move the child with the largest
1512    // `elen` (frontal size) to the end of the sibling list so the
1513    // deepest-recursion subtree is visited last.
1514    for i in 0..n {
1515        if ws.nv[i] > 0 && ws.head[i] != NONE {
1516            let child0 = ws.head[i];
1517            let mut fprev: i32 = NONE;
1518            let mut bigfprev: i32 = NONE;
1519            let mut bigf: i32 = NONE;
1520            let mut maxfrsize: i32 = NONE;
1521            let mut f = child0;
1522            while f != NONE {
1523                let fu = f as usize;
1524                let frsize = ws.elen[fu];
1525                if frsize >= maxfrsize {
1526                    maxfrsize = frsize;
1527                    bigfprev = fprev;
1528                    bigf = f;
1529                }
1530                fprev = f;
1531                f = ws.next[fu];
1532            }
1533            let bigfu = bigf as usize;
1534            let fnext = ws.next[bigfu];
1535            if fnext != NONE {
1536                if bigfprev != NONE {
1537                    ws.next[bigfprev as usize] = fnext;
1538                } else {
1539                    ws.head[i] = fnext;
1540                }
1541                ws.next[bigfu] = NONE;
1542                ws.next[fprev as usize] = bigf;
1543            }
1544        }
1545    }
1546    // Iterative DFS postorder from each pivot root.
1547    for x in ws.w.iter_mut() {
1548        *x = NONE;
1549    }
1550    let mut k: usize = 0;
1551    for i in 0..n {
1552        if ws.pe[i] == NONE && ws.nv[i] > 0 {
1553            k = post_tree_dfs(ws, i, k);
1554        }
1555    }
1556}
1557
1558/// Iterative DFS of one assembly-tree root. Stack lives in `last`,
1559/// child list in `head`, sibling links in `next`. Writes postorder
1560/// indices into `w`. Returns the next postorder index to assign.
1561fn post_tree_dfs(ws: &mut Workspace, root: usize, k_start: usize) -> usize {
1562    let mut k = k_start;
1563    let mut top: usize = 1;
1564    ws.last[0] = root as i32;
1565    while top > 0 {
1566        let i = ws.last[top - 1] as usize;
1567        let child0 = ws.head[i];
1568        if child0 != NONE {
1569            // Count children.
1570            let mut count = 0usize;
1571            let mut f = child0;
1572            while f != NONE {
1573                count += 1;
1574                f = ws.next[f as usize];
1575            }
1576            // Push children into stack slots [top, top+count) with the
1577            // first child at the highest position (popped first).
1578            let new_top = top + count;
1579            let mut t = new_top;
1580            let mut f = child0;
1581            loop {
1582                t -= 1;
1583                ws.last[t] = f;
1584                let nf = ws.next[f as usize];
1585                if nf == NONE {
1586                    break;
1587                }
1588                f = nf;
1589            }
1590            top = new_top;
1591            ws.head[i] = NONE; // mark visited
1592        } else {
1593            top -= 1;
1594            ws.w[i] = k as i32;
1595            k += 1;
1596        }
1597    }
1598    k
1599}
1600
1601#[cfg(test)]
1602mod tests {
1603    use super::*;
1604    use crate::quotient_graph::WorkspaceOptions;
1605    use crate::CscPattern;
1606
1607    fn ws_for<'a>(n: usize, cp: &'a [i32], ri: &'a [i32]) -> Workspace {
1608        let p = CscPattern::new(n, cp, ri).unwrap();
1609        Workspace::new(&p, &WorkspaceOptions::default()).unwrap()
1610    }
1611
1612    /// O1 (repo-review-2026-06-09.md): the AMF working-fill kernels must
1613    /// be computed in `i64`. Both factors are `O(n)`, so for `n` ≳ 46k
1614    /// the products exceed `i32::MAX` (2_147_483_647) and wrap silently
1615    /// in release / panic in debug, feeding garbage into the RMF pivot
1616    /// score. Oracle: the exact hand-computed `i64` value of the
1617    /// Amestoy 1999 formulas (`ana_orderings.F:4810`).
1618    #[test]
1619    fn amf_wf_kernels_do_not_overflow_i32() {
1620        // Surface contribution dext*(2*degree - dext - 1).
1621        // dext = degree = 46342  ->  46342 * 46341 = 2_147_534_622,
1622        // which is 50_975 above i32::MAX. Hand-computed external oracle.
1623        assert!(2_147_534_622_i64 > i32::MAX as i64);
1624        assert_eq!(amf_wf_surface(46342, 46342), 2_147_534_622_i64);
1625        // Small-value sanity: dext=3, degree=4 -> 3*(8-3-1) = 12.
1626        assert_eq!(amf_wf_surface(3, 4), 12);
1627
1628        // Combine wf4 + 2*nvi*wf3.
1629        // nvi = wf3 = 46342, wf4 = 0  ->  2 * 46342 * 46342
1630        // = 4_295_161_928, which exceeds both i32::MAX and u32::MAX.
1631        assert!(4_295_161_928_i64 > u32::MAX as i64);
1632        assert_eq!(amf_wf_combine(0, 46342, 46342), 4_295_161_928_i64);
1633        // Small-value sanity: 5 + 2*3*4 = 29.
1634        assert_eq!(amf_wf_combine(5, 3, 4), 29);
1635    }
1636
1637    #[test]
1638    fn select_pivot_empty() {
1639        // diag_4: every var pre-eliminated, no degree bucket populated.
1640        let cp = [0, 1, 2, 3, 4];
1641        let ri = [0, 1, 2, 3];
1642        let mut ws = ws_for(4, &cp, &ri);
1643        assert_eq!(select_pivot(&mut ws), None);
1644    }
1645
1646    #[test]
1647    fn select_pivot_lifo_on_tridiag() {
1648        // Tridiag 5: head[1] contains 4 -> 0 (LIFO).
1649        let cp = [0, 2, 5, 8, 11, 13];
1650        let ri = [0, 1, 0, 1, 2, 1, 2, 3, 2, 3, 4, 3, 4];
1651        let mut ws = ws_for(5, &cp, &ri);
1652        assert_eq!(select_pivot(&mut ws), Some(4));
1653        assert_eq!(ws.mindeg, 1);
1654        // Head of deg-1 list now points to the remaining spoke (0).
1655        assert_eq!(ws.head[1], 0);
1656        assert_eq!(ws.last[0], NONE, "new head has no predecessor");
1657
1658        assert_eq!(select_pivot(&mut ws), Some(0));
1659        assert_eq!(ws.head[1], NONE, "deg-1 bucket drained");
1660
1661        // Next call scans from mindeg=1 upward; only deg-2 non-empty.
1662        assert_eq!(select_pivot(&mut ws), Some(3));
1663        assert_eq!(ws.mindeg, 2);
1664    }
1665
1666    #[test]
1667    fn create_element_elenme_zero_on_arrow_5_hub() {
1668        // Arrow 5: hub has deg 4, but it's dense-deferred? Let's check.
1669        // For n=5 default, dense = max(16, min(5, 10*sqrt(5))) = 5.
1670        // deg 4 < 5, so hub is LIVE and sits in head[4].
1671        // Spokes (deg 1) all share head[1]. The min-degree pivot is a
1672        // spoke. Let's pick spoke 4 (LIFO head of deg-1).
1673        let cp = [0, 5, 7, 9, 11, 13];
1674        let ri = [0, 1, 2, 3, 4, 0, 1, 0, 2, 0, 3, 0, 4];
1675        let mut ws = ws_for(5, &cp, &ri);
1676        let me = select_pivot(&mut ws).unwrap();
1677        assert_eq!(me, 4, "first pivot is the LIFO head of deg-1");
1678        // elen[4] == 0 (no elements yet).
1679        assert_eq!(ws.elen[4], 0);
1680        let (pme1, pme2_excl, nvpiv, degme) = create_element(&mut ws, me).unwrap();
1681        assert_eq!(nvpiv, 1, "singleton supervariable");
1682        assert_eq!(degme, 1, "only neighbor is the hub (nv=1)");
1683        // The new element's var list contains {hub} = {0}.
1684        assert_eq!(pme2_excl - pme1, 1);
1685        assert_eq!(ws.iw[pme1], 0);
1686        assert_eq!(ws.pe[4], pme1 as i32);
1687        assert_eq!(ws.len[4], 1);
1688        assert_eq!(ws.elen[4], flip(1 + 1), "flip(nvpiv + degme)");
1689        assert_eq!(ws.nv[4], -1, "pivot marker");
1690        assert_eq!(ws.nv[0], -1, "hub marked");
1691        // Hub was in head[4] with no siblings; it was removed.
1692        assert_eq!(ws.head[4], NONE);
1693        // nel advanced by nvpiv.
1694        assert_eq!(ws.nel, 1);
1695    }
1696
1697    #[test]
1698    fn create_element_elenme_zero_unlinks_from_degree_list() {
1699        // Tridiag 5: pivot var 4 (deg 1), neighbor var 3 (deg 2).
1700        // var 3 should be unlinked from head[2], which currently
1701        // threads 3 -> 2 -> 1.
1702        let cp = [0, 2, 5, 8, 11, 13];
1703        let ri = [0, 1, 0, 1, 2, 1, 2, 3, 2, 3, 4, 3, 4];
1704        let mut ws = ws_for(5, &cp, &ri);
1705        let me = select_pivot(&mut ws).unwrap();
1706        assert_eq!(me, 4);
1707        let (_, _, _, _) = create_element(&mut ws, me).unwrap();
1708        // After unlinking 3 (head of deg-2), head[2] -> 2.
1709        assert_eq!(ws.head[2], 2);
1710        assert_eq!(ws.last[2], NONE);
1711        // Unlinked var's last/next are stale but the list is valid.
1712        assert_eq!(ws.nv[3], -1);
1713    }
1714
1715    #[test]
1716    fn create_element_skips_absorbed_neighbors() {
1717        // Construct a workspace where one neighbor is already absorbed
1718        // (nv == 0 or nv < 0). That neighbor must NOT contribute.
1719        let cp = [0, 2, 5, 8, 11, 13];
1720        let ri = [0, 1, 0, 1, 2, 1, 2, 3, 2, 3, 4, 3, 4];
1721        let mut ws = ws_for(5, &cp, &ri);
1722        // Mark var 0 as already-absorbed (nv <= 0).
1723        ws.nv[0] = 0;
1724        let me = select_pivot(&mut ws).unwrap();
1725        assert_eq!(me, 4);
1726        let (_, _, nvpiv, degme) = create_element(&mut ws, me).unwrap();
1727        // Only neighbor 3 counts; not 0 (absorbed) and not the diagonal
1728        // (skipped by init).
1729        assert_eq!(nvpiv, 1);
1730        assert_eq!(degme, 1);
1731    }
1732
1733    /// Drive the full loop on diag_4 — every var pre-eliminated,
1734    /// loop terminates immediately.
1735    #[test]
1736    fn run_elimination_diag_4() {
1737        let cp = [0, 1, 2, 3, 4];
1738        let ri = [0, 1, 2, 3];
1739        let mut ws = ws_for(4, &cp, &ri);
1740        let flops = run_elimination(&mut ws, true).unwrap();
1741        assert_eq!(ws.nel, 4);
1742        assert_eq!(flops.ndiv, 0.0);
1743    }
1744
1745    /// Arrow 5: no dense deferral. Loop eliminates all 5 vars.
1746    /// Verify `nel == n` and pivot supervariable count matches nv[me]
1747    /// after the step (restored to positive).
1748    #[test]
1749    fn run_elimination_arrow_5() {
1750        let cp = [0, 5, 7, 9, 11, 13];
1751        let ri = [0, 1, 2, 3, 4, 0, 1, 0, 2, 0, 3, 0, 4];
1752        let mut ws = ws_for(5, &cp, &ri);
1753        run_elimination(&mut ws, true).unwrap();
1754        assert_eq!(ws.nel, 5);
1755        // Every var was pivoted exactly once ⇒ nv[i] > 0 everywhere
1756        // (the pivot restores nv to +nvpiv).
1757        for (i, &nv) in ws.nv[..5].iter().enumerate() {
1758            assert!(nv >= 0, "nv[{}] = {}", i, nv);
1759        }
1760    }
1761
1762    /// Tridiag 10 full-symmetric: loop should terminate cleanly.
1763    /// Oracle lnz = 9 — verified indirectly by the flop counter.
1764    #[test]
1765    fn run_elimination_tridiag_10() {
1766        let n = 10usize;
1767        let mut cp: Vec<i32> = vec![0];
1768        let mut ri: Vec<i32> = Vec::new();
1769        for j in 0..n {
1770            if j > 0 {
1771                ri.push((j - 1) as i32);
1772            }
1773            ri.push(j as i32);
1774            if j + 1 < n {
1775                ri.push((j + 1) as i32);
1776            }
1777            cp.push(ri.len() as i32);
1778        }
1779        let p = CscPattern::new(n, &cp, &ri).unwrap();
1780        let mut ws = Workspace::new(&p, &WorkspaceOptions::default()).unwrap();
1781        run_elimination(&mut ws, true).unwrap();
1782        assert_eq!(ws.nel, n);
1783    }
1784
1785    /// Grid 7x7: five-point stencil. Faer's oracle reports
1786    /// `ncmpa == 0`, but Slice A lacks mass elimination and
1787    /// supervariable detection, so it consumes more `iw` space and
1788    /// may trip the inline GC. With Commit 6 the loop terminates
1789    /// cleanly regardless of how many compactions are needed.
1790    #[test]
1791    fn run_elimination_grid_7x7() {
1792        let m = 7usize;
1793        let n = 7usize;
1794        let total = m * n;
1795        let mut cp: Vec<i32> = vec![0];
1796        let mut ri: Vec<i32> = Vec::new();
1797        use std::collections::BTreeSet;
1798        let idx = |r: usize, c: usize| r * n + c;
1799        for c in 0..total {
1800            let r0 = c / n;
1801            let c0 = c % n;
1802            let mut neigh: BTreeSet<usize> = BTreeSet::new();
1803            neigh.insert(c);
1804            if r0 > 0 {
1805                neigh.insert(idx(r0 - 1, c0));
1806            }
1807            if r0 + 1 < m {
1808                neigh.insert(idx(r0 + 1, c0));
1809            }
1810            if c0 > 0 {
1811                neigh.insert(idx(r0, c0 - 1));
1812            }
1813            if c0 + 1 < n {
1814                neigh.insert(idx(r0, c0 + 1));
1815            }
1816            for &r in &neigh {
1817                ri.push(r as i32);
1818            }
1819            cp.push(ri.len() as i32);
1820        }
1821        let p = CscPattern::new(total, &cp, &ri).unwrap();
1822        let mut ws = Workspace::new(&p, &WorkspaceOptions::default()).unwrap();
1823        run_elimination(&mut ws, true).unwrap();
1824        assert_eq!(ws.nel, total);
1825    }
1826
1827    /// Band(20,3) triggers garbage collection in faer (oracle
1828    /// ncmpa=1). Commit 6 must run the compaction and finish the
1829    /// elimination; verify both.
1830    #[test]
1831    fn run_elimination_band_20_3_triggers_gc() {
1832        let n = 20usize;
1833        let b = 3usize;
1834        let mut cp: Vec<i32> = vec![0];
1835        let mut ri: Vec<i32> = Vec::new();
1836        for j in 0..n {
1837            let lo = j.saturating_sub(b);
1838            let hi = (j + b + 1).min(n);
1839            for r in lo..hi {
1840                ri.push(r as i32);
1841            }
1842            cp.push(ri.len() as i32);
1843        }
1844        let p = CscPattern::new(n, &cp, &ri).unwrap();
1845        let mut ws = Workspace::new(&p, &WorkspaceOptions::default()).unwrap();
1846        run_elimination(&mut ws, true).unwrap();
1847        assert_eq!(ws.nel, n);
1848        assert!(
1849            ws.ncmpa >= 1,
1850            "expected at least one compaction on band(20,3), got ncmpa={}",
1851            ws.ncmpa
1852        );
1853    }
1854
1855    /// Arrow 200: hub dense-deferred in init; spokes get pivoted
1856    /// one by one; loop terminates with ndense=1 survivor.
1857    #[test]
1858    fn run_elimination_arrow_200() {
1859        let n = 200usize;
1860        let mut cp: Vec<i32> = vec![0];
1861        let mut ri: Vec<i32> = Vec::new();
1862        ri.push(0);
1863        for r in 1..n {
1864            ri.push(r as i32);
1865        }
1866        cp.push(ri.len() as i32);
1867        for j in 1..n {
1868            ri.push(0);
1869            ri.push(j as i32);
1870            cp.push(ri.len() as i32);
1871        }
1872        let p = CscPattern::new(n, &cp, &ri).unwrap();
1873        let mut ws = Workspace::new(&p, &WorkspaceOptions::default()).unwrap();
1874        run_elimination(&mut ws, true).unwrap();
1875        assert_eq!(ws.ndense, 1);
1876        assert_eq!(ws.nel, n);
1877    }
1878
1879    /// Arrow 200 hub is dense-deferred; first pivot is a spoke with
1880    /// no elements in its list, so the elenme==0 path is exercised
1881    /// on a larger graph. Smoke test that the path completes without
1882    /// indexing out of bounds.
1883    #[test]
1884    fn arrow_200_first_pivot_smoke() {
1885        let n = 200usize;
1886        let mut cp: Vec<i32> = vec![0];
1887        let mut ri: Vec<i32> = Vec::new();
1888        ri.push(0);
1889        for r in 1..n {
1890            ri.push(r as i32);
1891        }
1892        cp.push(ri.len() as i32);
1893        for j in 1..n {
1894            ri.push(0);
1895            ri.push(j as i32);
1896            cp.push(ri.len() as i32);
1897        }
1898        let p = CscPattern::new(n, &cp, &ri).unwrap();
1899        let mut ws = Workspace::new(&p, &WorkspaceOptions::default()).unwrap();
1900        // Hub (var 0) is dense-deferred; its nv was set to 0 during
1901        // init. So when a spoke's list references 0, it's skipped.
1902        let me = select_pivot(&mut ws).unwrap();
1903        let (_, _, nvpiv, degme) = create_element(&mut ws, me).unwrap();
1904        assert_eq!(nvpiv, 1);
1905        assert_eq!(degme, 0, "spoke's only neighbor (hub) is deferred");
1906        // Exactly one var (the pivot itself) has been eliminated plus
1907        // the deferred hub that init already counted.
1908        assert_eq!(ws.nel, 2, "1 deferred hub + 1 pivot");
1909    }
1910
1911    fn is_permutation(perm: &[i32]) -> bool {
1912        let n = perm.len();
1913        let mut seen = vec![false; n];
1914        for &p in perm {
1915            if p < 0 {
1916                return false;
1917            }
1918            let pu = p as usize;
1919            if pu >= n || seen[pu] {
1920                return false;
1921            }
1922            seen[pu] = true;
1923        }
1924        true
1925    }
1926
1927    /// diag_4: every variable is pre-eliminated at init as a
1928    /// zero-degree singleton. Each is a tree root; postorder visits
1929    /// them in ascending index order, giving perm = [0,1,2,3].
1930    #[test]
1931    fn permutation_diag_4() {
1932        let cp = [0, 1, 2, 3, 4];
1933        let ri = [0, 1, 2, 3];
1934        let mut ws = ws_for(4, &cp, &ri);
1935        run_elimination(&mut ws, true).unwrap();
1936        let perm = finalize_permutation(&mut ws);
1937        assert_eq!(perm.len(), 4);
1938        assert!(is_permutation(&perm));
1939        assert_eq!(perm, vec![0, 1, 2, 3]);
1940    }
1941
1942    /// Arrow 5 with hub live: LIFO spoke pivots first, then hub and
1943    /// remaining spoke chain through aggressive absorption. The exact
1944    /// root depends on pivot order and absorption choices; just
1945    /// verify a valid permutation.
1946    #[test]
1947    fn permutation_arrow_5_valid() {
1948        let cp = [0, 5, 7, 9, 11, 13];
1949        let ri = [0, 1, 2, 3, 4, 0, 1, 0, 2, 0, 3, 0, 4];
1950        let mut ws = ws_for(5, &cp, &ri);
1951        run_elimination(&mut ws, true).unwrap();
1952        let perm = finalize_permutation(&mut ws);
1953        assert_eq!(perm.len(), 5);
1954        assert!(is_permutation(&perm));
1955    }
1956
1957    /// Tridiag 10: valid permutation of 0..10. No structural
1958    /// oracle here — just bijection + length checks.
1959    #[test]
1960    fn permutation_tridiag_10() {
1961        let n = 10usize;
1962        let mut cp: Vec<i32> = vec![0];
1963        let mut ri: Vec<i32> = Vec::new();
1964        for j in 0..n {
1965            if j > 0 {
1966                ri.push((j - 1) as i32);
1967            }
1968            ri.push(j as i32);
1969            if j + 1 < n {
1970                ri.push((j + 1) as i32);
1971            }
1972            cp.push(ri.len() as i32);
1973        }
1974        let p = CscPattern::new(n, &cp, &ri).unwrap();
1975        let mut ws = Workspace::new(&p, &WorkspaceOptions::default()).unwrap();
1976        run_elimination(&mut ws, true).unwrap();
1977        let perm = finalize_permutation(&mut ws);
1978        assert_eq!(perm.len(), n);
1979        assert!(is_permutation(&perm));
1980    }
1981
1982    /// Arrow 200 with a dense-deferred hub. The hub (var 0, nv=0,
1983    /// pe=NONE) is placed at the tail by the expand phase. All 199
1984    /// spokes are pivots; permutation is still a bijection of 0..200.
1985    #[test]
1986    fn permutation_arrow_200_hub_deferred() {
1987        let n = 200usize;
1988        let mut cp: Vec<i32> = vec![0];
1989        let mut ri: Vec<i32> = Vec::new();
1990        ri.push(0);
1991        for r in 1..n {
1992            ri.push(r as i32);
1993        }
1994        cp.push(ri.len() as i32);
1995        for j in 1..n {
1996            ri.push(0);
1997            ri.push(j as i32);
1998            cp.push(ri.len() as i32);
1999        }
2000        let p = CscPattern::new(n, &cp, &ri).unwrap();
2001        let mut ws = Workspace::new(&p, &WorkspaceOptions::default()).unwrap();
2002        run_elimination(&mut ws, true).unwrap();
2003        let perm = finalize_permutation(&mut ws);
2004        assert_eq!(perm.len(), n);
2005        assert!(is_permutation(&perm));
2006        assert_eq!(
2007            perm[n - 1],
2008            0,
2009            "dense-deferred hub lands at the tail of the permutation"
2010        );
2011    }
2012
2013    /// Grid 7x7: ensure the permutation survives GC-triggered runs.
2014    #[test]
2015    fn permutation_grid_7x7() {
2016        let m = 7usize;
2017        let n = 7usize;
2018        let total = m * n;
2019        let mut cp: Vec<i32> = vec![0];
2020        let mut ri: Vec<i32> = Vec::new();
2021        use std::collections::BTreeSet;
2022        let idx = |r: usize, c: usize| r * n + c;
2023        for c in 0..total {
2024            let r0 = c / n;
2025            let c0 = c % n;
2026            let mut neigh: BTreeSet<usize> = BTreeSet::new();
2027            neigh.insert(c);
2028            if r0 > 0 {
2029                neigh.insert(idx(r0 - 1, c0));
2030            }
2031            if r0 + 1 < m {
2032                neigh.insert(idx(r0 + 1, c0));
2033            }
2034            if c0 > 0 {
2035                neigh.insert(idx(r0, c0 - 1));
2036            }
2037            if c0 + 1 < n {
2038                neigh.insert(idx(r0, c0 + 1));
2039            }
2040            for &r in &neigh {
2041                ri.push(r as i32);
2042            }
2043            cp.push(ri.len() as i32);
2044        }
2045        let p = CscPattern::new(total, &cp, &ri).unwrap();
2046        let mut ws = Workspace::new(&p, &WorkspaceOptions::default()).unwrap();
2047        run_elimination(&mut ws, true).unwrap();
2048        let perm = finalize_permutation(&mut ws);
2049        assert_eq!(perm.len(), total);
2050        assert!(is_permutation(&perm));
2051    }
2052
2053    /// Band(20, 3) with GC: permutation remains a valid bijection
2054    /// even after ncmpa >= 1 compactions.
2055    #[test]
2056    fn permutation_band_20_3() {
2057        let n = 20usize;
2058        let b = 3usize;
2059        let mut cp: Vec<i32> = vec![0];
2060        let mut ri: Vec<i32> = Vec::new();
2061        for j in 0..n {
2062            let lo = j.saturating_sub(b);
2063            let hi = (j + b + 1).min(n);
2064            for r in lo..hi {
2065                ri.push(r as i32);
2066            }
2067            cp.push(ri.len() as i32);
2068        }
2069        let p = CscPattern::new(n, &cp, &ri).unwrap();
2070        let mut ws = Workspace::new(&p, &WorkspaceOptions::default()).unwrap();
2071        run_elimination(&mut ws, true).unwrap();
2072        let perm = finalize_permutation(&mut ws);
2073        assert_eq!(perm.len(), n);
2074        assert!(is_permutation(&perm));
2075    }
2076
2077    /// Empty pattern (n == 0) round-trips to an empty permutation.
2078    #[test]
2079    fn permutation_empty() {
2080        let cp = [0i32];
2081        let ri: [i32; 0] = [];
2082        let p = CscPattern::new(0, &cp, &ri).unwrap();
2083        let mut ws = Workspace::new(&p, &WorkspaceOptions::default()).unwrap();
2084        run_elimination(&mut ws, true).unwrap();
2085        let perm = finalize_permutation(&mut ws);
2086        assert!(perm.is_empty());
2087    }
2088
2089    // Issue #246: the RMF -> bucket-key quantization must be monotone.
2090    // Oracle: hand arithmetic. The MUMPS-verbatim `RMF / N` fall-through
2091    // maps 3e9 to round(3e9 / 1_914_525) = 1_567 at fhnw's n, below 2e9.
2092    #[test]
2093    fn amf_quantize_score_is_exact_below_and_above_i32_max() {
2094        assert_eq!(amf_quantize_score(2.0e9), 2_000_000_000);
2095        assert_eq!(amf_quantize_score(3.0e9), 3_000_000_000);
2096        assert_eq!(amf_quantize_score(2_147_483_647.0), 2_147_483_647);
2097    }
2098
2099    #[test]
2100    fn amf_quantize_score_and_bucket_are_monotone_across_i32_max() {
2101        let n = 1_914_525usize;
2102        let xs = [
2103            1.0, 1.0e3, 1.0e6, 1.0e9, 2.0e9, 2.2e9, 3.0e9, 1.0e12, 1.0e15, 1.0e17,
2104        ];
2105        for w in xs.windows(2) {
2106            let (a, b) = (amf_quantize_score(w[0]), amf_quantize_score(w[1]));
2107            assert!(a < b, "key({}) = {a} !< key({}) = {b}", w[0], w[1]);
2108            assert!(
2109                amf_bucket_of(a, n) <= amf_bucket_of(b, n),
2110                "bucket not monotone between rmf {} and {}",
2111                w[0],
2112                w[1]
2113            );
2114        }
2115    }
2116
2117    #[test]
2118    fn amf_quantize_score_floor_and_cap() {
2119        assert_eq!(amf_quantize_score(0.4), 1);
2120        assert_eq!(amf_quantize_score(-5.0), 1);
2121        assert_eq!(amf_quantize_score(1.0e30), AMF_SCORE_CAP);
2122        assert_eq!(amf_quantize_score(f64::INFINITY), AMF_SCORE_CAP);
2123    }
2124}