feral_metis/lib.rs
1//! Multilevel nested-dissection fill-reducing ordering.
2//!
3//! Clean-room Rust implementation of the algorithm described in
4//! Karypis & Kumar, "A Fast and High Quality Multilevel Scheme for
5//! Partitioning Irregular Graphs" (SIAM J. Sci. Comput., 1998), and
6//! George, "Nested Dissection of a Regular Finite Element Mesh"
7//! (SIAM J. Numer. Anal., 1973).
8//!
9//! The public surface conforms to the FERAL ordering-crate contract
10//! (`dev/plans/ordering-crate-contract.md`): `CscPattern`,
11//! `OrderingStats`, `OrderingError`, and `CONTRACT_VERSION` are
12//! re-exported from `feral-ordering-core`.
13//!
14//! **Status: M1–M7 complete.** `metis_order_full` coarsens the graph
15//! (SHEM + 2-hop), picks the best of `niparts` initial bisections
16//! scored on their post-FM cut, uncoarsens with FM refinement, turns
17//! the final edge bisection into a node separator via min vertex
18//! cover (König's theorem), and recursively orders the two sides —
19//! handing off to AMD on subgraphs no larger than
20//! `nd_to_amd_switch`. M8 (integration into the main solver) is
21//! tracked separately in `dev/plans/ordering-metis.md`.
22
23#![forbid(unsafe_code)]
24#![deny(missing_docs)]
25
26// Modules are exercised only by `metis_order_full` once all
27// milestones land; until then, dead-code lint is suppressed at the
28// module root for internal helpers.
29#[doc(hidden)]
30#[allow(dead_code, missing_docs)]
31pub mod coarsen;
32#[doc(hidden)]
33#[allow(dead_code, missing_docs)]
34pub mod fm_refine;
35#[doc(hidden)]
36#[allow(dead_code, missing_docs)]
37pub mod graph;
38#[doc(hidden)]
39#[allow(dead_code, missing_docs)]
40pub mod initial_partition;
41mod node_nd;
42#[doc(hidden)]
43#[allow(dead_code, missing_docs)]
44pub mod rng;
45#[doc(hidden)]
46#[allow(dead_code, missing_docs)]
47pub mod separator;
48
49/// Crate-internal infrastructure exposed for sibling ordering
50/// crates (notably `feral-scotch`) that share the multilevel
51/// coarsening, initial-bisection, and FM-refinement plumbing.
52///
53/// **Not part of the stable public API.** No semver guarantees on
54/// signatures inside `internals`; consumers re-export it at their
55/// own risk. This module exists solely so feral-scotch does not
56/// have to clone the multilevel framework.
57#[doc(hidden)]
58pub mod internals {
59 pub use crate::coarsen;
60 pub use crate::fm_refine;
61 pub use crate::graph;
62 pub use crate::initial_partition;
63 pub use crate::rng;
64 pub use crate::separator;
65}
66
67pub use feral_ordering_core::interrupt::Interrupt;
68pub use feral_ordering_core::{CscPattern, OrderingError, OrderingStats, CONTRACT_VERSION};
69
70/// Tunable parameters for METIS nested-dissection ordering.
71///
72/// Defaults mirror METIS 5.2.0's `METIS_NodeND` defaults as documented
73/// in `dev/plans/ordering-metis.md` audit (MUMPS uses stock METIS
74/// defaults for KKT problems: `METIS_OPTION_NUMBERING = 1`, all other
75/// options at library default).
76#[derive(Debug, Clone)]
77pub struct MetisOptions {
78 /// Deterministic RNG seed. Defaults to 1. Two runs with the same
79 /// seed on the same input must produce the same permutation.
80 pub seed: u64,
81 /// Number of initial-bisection trials at the coarsest level
82 /// (METIS 5.2.0 default: 7). Each trial alternates GGP and random
83 /// BFS and is scored on its post-FM cut.
84 pub niparts: u32,
85 /// Stop coarsening when the graph has fewer than this many
86 /// vertices (METIS 5.2.0 default: 120).
87 pub coarsen_floor: u32,
88 /// Switch from recursive ND to AMD on uncoarsened subproblems of
89 /// at most this many vertices (METIS 5.2.0 default: 200).
90 pub nd_to_amd_switch: u32,
91 /// Reduction-ratio threshold below which SHEM falls back to
92 /// 2-hop matching (METIS 5.2.0 default: 0.85).
93 pub two_hop_ratio_threshold: f64,
94 /// Maximum partition imbalance factor (`ufactor` in METIS terms,
95 /// encoded as a fraction here). METIS 5.2.0 uses 200, which
96 /// corresponds to 1.20 load balance tolerance; expressed as the
97 /// fractional deviation 0.20.
98 pub max_imbalance: f64,
99 /// Number of FM passes at each uncoarsening level (METIS 5.2.0
100 /// default: 10).
101 pub fm_passes: u32,
102 /// Carry the **node separator** through uncoarsening and refine it
103 /// with FM at every level (METIS's `Refine2WayNode` /
104 /// `FM_2WayNodeRefine1Sided`), instead of refining the edge cut
105 /// through uncoarsening and converting to a separator once at the
106 /// finest level.
107 ///
108 /// **Default: `true`.** The two paths share coarsening and initial
109 /// bisection; they differ only in what the uncoarsening loop
110 /// optimises. Measured against MA57's bundled real METIS as the
111 /// oracle (`dev/research/feral-metis-node-separator-fm-2026-09-17.md`),
112 /// on the six matrices in this repo large enough for nested
113 /// dissection to engage, `node_refine` cuts the elimination flop
114 /// count by 2.4-3.5x on collocation KKTs. It is **not a uniform
115 /// win**: measured in wall-clock on grid Laplacians (min over 3
116 /// runs of 5 pairs each, non-overlapping), a 40^3 grid factors
117 /// 12.8% *faster* while a 300x300 grid factors 5.8% **slower**
118 /// despite 10.3% less fill — one more case of fill not predicting
119 /// speed. On every other matrix measured (seven real IPM families
120 /// up to n=607,500, and 37 of 38 parity matrices) the permutation
121 /// is bit-identical, so there is nothing to win or lose.
122 ///
123 /// Set to `false` to recover the pre-2026-09-17 edge-cut
124 /// behaviour.
125 pub node_refine: bool,
126 /// Pull near-dense columns out of the ND graph before recursive
127 /// bisection and append them at the *end* of the returned
128 /// permutation.
129 ///
130 /// **Default: `false`.** The technique was implemented to mimic
131 /// what we believed MUMPS's `ICNTL(6)` and SSIDS did, but expert
132 /// review of the MUMPS and SPRAL sources (2026-04-27) found:
133 /// (a) `ICNTL(6)` is MC64 matching, not dense-row removal;
134 /// (b) MUMPS handles dense rows *inside* its AMD/AMF
135 /// (`MUMPS_QAMD` in `ana_orderings.F:5226+` with the `THRESM`
136 /// parameter and `HEAD(N)` quasi-dense list); and
137 /// (c) SSIDS does not special-case dense rows at all — it relies
138 /// on METIS placing them in the top separator and supernodal
139 /// amalgamation collapsing the resulting chain into one dense
140 /// BLAS-3 root frontal. Neither solver pre-strips the graph.
141 /// Empirically, on ORBIT2_0000 (n=4795, one column of off-degree
142 /// 1794) Fix A *increased* `nnz_L` from 1.54M to 2.25M because
143 /// removing the dense column destroys the structural signal that
144 /// makes it the natural top separator. The opt-in path is kept
145 /// for diagnostic experimentation; the correct fix lives in
146 /// `feral-amd` (a QAMD-style deferral, future work).
147 ///
148 /// References (kept for the opt-in code path):
149 /// - Davis & Hager, "Dynamic supernodes in sparse Cholesky
150 /// update/downdate and triangular solves" (2009), §3.2.
151 /// - Davis (1996) AMD paper, §5 ("dense rows / `Alpha` parameter").
152 /// - MUMPS source: `ana_orderings.F:5226-5650` (QAMD).
153 pub dense_quotient_enabled: bool,
154 /// Override the off-diagonal-degree threshold above which a column
155 /// is treated as quasi-dense.
156 ///
157 /// When `None` (the default) the threshold is computed as
158 /// `max(40, ceil(10 * sqrt(n)))` per Davis & Hager / AMD §5. Set
159 /// to `Some(usize::MAX)` to effectively disable the quotient
160 /// without flipping `dense_quotient_enabled` (useful for
161 /// regression sweeps).
162 pub dense_quotient_threshold: Option<usize>,
163}
164
165impl Default for MetisOptions {
166 fn default() -> Self {
167 Self {
168 seed: 1,
169 niparts: 7,
170 coarsen_floor: 120,
171 nd_to_amd_switch: 200,
172 two_hop_ratio_threshold: 0.85,
173 max_imbalance: 0.20,
174 fm_passes: 10,
175 node_refine: true,
176 dense_quotient_enabled: false,
177 dense_quotient_threshold: None,
178 }
179 }
180}
181
182/// Crate-specific diagnostic counters for METIS nested dissection.
183///
184/// Populated per call to [`metis_order_full`]. Callers that only need
185/// the permutation should use [`metis_order`]; callers that need the
186/// shared [`OrderingStats`] (wall time) should use
187/// [`metis_order_full`].
188#[derive(Debug, Default, Clone, PartialEq, Eq)]
189pub struct MetisStats {
190 /// Number of coarsening levels built.
191 pub n_levels: u32,
192 /// Number of top-level connected components encountered.
193 pub n_components: u32,
194 /// Number of vertices assigned to a separator at any level.
195 pub n_separator_vertices: u32,
196 /// Number of FM passes executed across all levels.
197 pub n_fm_passes: u32,
198 /// Number of times SHEM fell through to the 2-hop matching path.
199 pub n_two_hop_fallbacks: u32,
200 /// Number of subgraphs handed off to the AMD leaf solver (when
201 /// `nd_to_amd_switch` triggers).
202 pub n_amd_leaf_calls: u32,
203}
204
205/// Compute a fill-reducing METIS nested-dissection ordering.
206///
207/// Thin wrapper over [`metis_order_full`] that discards the
208/// diagnostic stats. Returns a permutation `perm` (new-to-old).
209pub fn metis_order(pattern: &CscPattern<'_>) -> Result<Vec<i32>, OrderingError> {
210 metis_order_full(pattern, &MetisOptions::default()).map(|(perm, _, _)| perm)
211}
212
213/// [`metis_order_full`] that stops with [`OrderingError::Interrupted`] once
214/// `interrupt` triggers (its deadline passes or its cancel flag is set)
215/// (feral issue #246). The check runs at safe points inside the ordering,
216/// so the overshoot past a deadline is bounded by one of them rather than
217/// by the whole ordering. With [`Interrupt::none`] the result is identical
218/// to [`metis_order_full`].
219pub fn metis_order_interruptible(
220 pattern: &CscPattern<'_>,
221 opts: &MetisOptions,
222 interrupt: &Interrupt,
223) -> Result<(Vec<i32>, OrderingStats, MetisStats), OrderingError> {
224 feral_ordering_core::interrupt::scope(interrupt, || metis_order_full(pattern, opts))
225}
226
227/// Contract-conforming ordering producer.
228///
229/// Signature matches the shape every FERAL ordering crate must expose
230/// per `dev/plans/ordering-crate-contract.md`: input is a
231/// full-symmetric [`CscPattern`] and options; output is a three-tuple
232/// of `(perm, OrderingStats, crate-stats)`, with errors in
233/// [`OrderingError`].
234///
235/// `OrderingStats.time_us` is the wall-clock time of this call.
236/// `fill_estimate` and `flop_estimate` stay `None` — METIS does not
237/// produce them at the ordering boundary; they belong to a downstream
238/// symbolic analysis.
239///
240/// Runs the M1–M7 pipeline: coarsen, initial bisection, FM, separator
241/// construction, and recursive nested dissection with an AMD leaf
242/// fallback for subgraphs of at most `nd_to_amd_switch` vertices.
243pub fn metis_order_full(
244 pattern: &CscPattern<'_>,
245 opts: &MetisOptions,
246) -> Result<(Vec<i32>, OrderingStats, MetisStats), OrderingError> {
247 if pattern.col_ptr.len() != pattern.n + 1 {
248 return Err(OrderingError::MalformedInput);
249 }
250 let t0 = std::time::Instant::now();
251 let mut stats = MetisStats::default();
252
253 // Fix A — quasi-dense column quotient.
254 //
255 // Pull columns with off-diagonal degree above the
256 // `dense_quotient_threshold` (default `max(40, 10*sqrt(n))`) out
257 // of the ND input graph, run M1–M7 ND on the *sparse-induced*
258 // subgraph, and append the dense columns at the end of the
259 // returned permutation. This was originally modelled on a belief
260 // that HSL_MC68 / MUMPS ICNTL(6) / SSIDS pre-strip dense rows, but
261 // a 2026-04-27 audit of the MUMPS and SPRAL sources found that
262 // belief wrong: ICNTL(6) is MC64 matching, MUMPS defers dense rows
263 // inside QAMD, and SSIDS does not special-case them — neither
264 // pre-strips the graph. See `MetisOptions::dense_quotient_enabled`
265 // for the full finding. The path is kept opt-in (default off) for
266 // diagnostic use only.
267 let (sparse_pat_storage, dense_cols, sparse_to_orig) =
268 if opts.dense_quotient_enabled && pattern.n > 0 {
269 split_dense_columns(pattern, opts)?
270 } else {
271 (None, Vec::new(), Vec::new())
272 };
273
274 let perm = if let Some((cp, ri, sub_n)) = sparse_pat_storage.as_ref().map(|s| {
275 let (cp, ri, sub_n) = s;
276 (cp.as_slice(), ri.as_slice(), *sub_n)
277 }) {
278 // Run ND on the sparse-induced subgraph.
279 let sub_pat = CscPattern::new(sub_n, cp, ri).ok_or(OrderingError::MalformedInput)?;
280 let sub_perm = node_nd::nd_order(&sub_pat, opts, &mut stats)?;
281 // Lift sub-perm back to original indices and append dense
282 // columns at the end (in descending degree order — Davis &
283 // Hager 2009 §3.2 ordering choice; ties broken by ascending
284 // original index).
285 let mut perm: Vec<i32> = Vec::with_capacity(pattern.n);
286 for &local in &sub_perm {
287 let idx = local as usize;
288 if idx >= sparse_to_orig.len() {
289 return Err(OrderingError::Internal(
290 "dense-quotient: subgraph perm index out of range",
291 ));
292 }
293 perm.push(sparse_to_orig[idx]);
294 }
295 for &c in &dense_cols {
296 perm.push(c);
297 }
298 if perm.len() != pattern.n {
299 return Err(OrderingError::Internal(
300 "dense-quotient: assembled perm has wrong length",
301 ));
302 }
303 perm
304 } else {
305 node_nd::nd_order(pattern, opts, &mut stats)?
306 };
307
308 let ordering_stats = OrderingStats {
309 time_us: t0.elapsed().as_micros() as u64,
310 fill_estimate: None,
311 flop_estimate: None,
312 };
313 Ok((perm, ordering_stats, stats))
314}
315
316/// Resolve the dense-column threshold for an `n`-vertex graph.
317///
318/// `max(40, ceil(10 * sqrt(n)))` per Davis & Hager 2009 §3.2 and
319/// MUMPS `ICNTL(6)` defaults. Honours the caller's override when
320/// `opts.dense_quotient_threshold` is `Some(_)`.
321fn resolve_dense_threshold(n: usize, opts: &MetisOptions) -> usize {
322 if let Some(t) = opts.dense_quotient_threshold {
323 return t;
324 }
325 let computed = (10.0 * (n as f64).sqrt()).ceil() as usize;
326 computed.max(40)
327}
328
329/// Partition `pattern`'s columns into "dense" and "sparse" sets using
330/// off-diagonal degree, and produce the CSC pattern of the
331/// sparse-induced subgraph.
332///
333/// Returns:
334/// - `Some((col_ptr, row_idx, sub_n))` carrying the induced
335/// sub-pattern, plus the dense column list (in descending degree
336/// order) and the `sparse_local → original` mapping. When the
337/// dense set is empty, returns `(None, Vec::new(), Vec::new())` so
338/// the caller can fast-path to the original pattern.
339type DenseSplit = (Option<(Vec<i32>, Vec<i32>, usize)>, Vec<i32>, Vec<i32>);
340fn split_dense_columns(
341 pattern: &CscPattern<'_>,
342 opts: &MetisOptions,
343) -> Result<DenseSplit, OrderingError> {
344 let n = pattern.n;
345 let thresh = resolve_dense_threshold(n, opts);
346
347 // Off-diagonal degree per column. The pattern is full-symmetric
348 // with the diagonal optionally present; we count entries `r != c`.
349 let mut deg: Vec<usize> = vec![0; n];
350 for (c, d) in deg.iter_mut().enumerate() {
351 let lo = pattern.col_ptr[c] as usize;
352 let hi = pattern.col_ptr[c + 1] as usize;
353 if hi < lo || hi > pattern.row_idx.len() {
354 return Err(OrderingError::MalformedInput);
355 }
356 let mut acc: usize = 0;
357 for r in pattern.row_idx[lo..hi].iter().map(|&x| x as usize) {
358 if r != c {
359 acc += 1;
360 }
361 }
362 *d = acc;
363 }
364
365 // Collect dense columns.
366 let mut dense: Vec<i32> = (0..n)
367 .filter(|&c| deg[c] > thresh)
368 .map(|c| c as i32)
369 .collect();
370
371 // No-op fast path: dense set empty.
372 if dense.is_empty() {
373 return Ok((None, Vec::new(), Vec::new()));
374 }
375
376 // Sort dense columns by *descending* degree, ties by ascending
377 // original index — Davis & Hager 2009 §3.2: "eliminate the densest
378 // last".
379 dense.sort_by(|&a, &b| {
380 deg[b as usize]
381 .cmp(°[a as usize])
382 .then_with(|| a.cmp(&b))
383 });
384
385 // Build the local-id maps for the sparse subgraph.
386 //
387 // `sparse_to_orig[local] = original`
388 // `orig_to_local[original] = sparse local id, or -1 if dense`.
389 let mut is_dense = vec![false; n];
390 for &c in &dense {
391 is_dense[c as usize] = true;
392 }
393 let mut sparse_to_orig: Vec<i32> = Vec::with_capacity(n - dense.len());
394 let mut orig_to_local: Vec<i32> = vec![-1; n];
395 for c in 0..n {
396 if !is_dense[c] {
397 orig_to_local[c] = sparse_to_orig.len() as i32;
398 sparse_to_orig.push(c as i32);
399 }
400 }
401 let sub_n = sparse_to_orig.len();
402
403 // Build the induced CSC pattern. Re-include the diagonal entry so
404 // downstream consumers (Graph::from_csc_pattern, AMD leaf) see a
405 // well-formed pattern. Row indices stay sorted because we walk
406 // each original column in ascending row order.
407 let mut col_ptr: Vec<i32> = Vec::with_capacity(sub_n + 1);
408 let mut row_idx: Vec<i32> = Vec::new();
409 col_ptr.push(0);
410 for &orig in &sparse_to_orig {
411 let c = orig as usize;
412 let lo = pattern.col_ptr[c] as usize;
413 let hi = pattern.col_ptr[c + 1] as usize;
414 let mut diag_inserted = false;
415 let local_c = orig_to_local[c];
416 for r in pattern.row_idx[lo..hi].iter().map(|&x| x as usize) {
417 if r == c {
418 // Diagonal handled below; skip here so we control its
419 // placement (input may or may not carry the diagonal).
420 continue;
421 }
422 let lr = orig_to_local[r];
423 if lr < 0 {
424 // Edge crosses into the dense set — drop it from the
425 // sparse-induced subgraph; the dense column carries
426 // that coupling and is eliminated at the end.
427 continue;
428 }
429 if !diag_inserted && lr > local_c {
430 row_idx.push(local_c);
431 diag_inserted = true;
432 }
433 row_idx.push(lr);
434 }
435 if !diag_inserted {
436 row_idx.push(local_c);
437 }
438 col_ptr.push(row_idx.len() as i32);
439 }
440
441 Ok((Some((col_ptr, row_idx, sub_n)), dense, sparse_to_orig))
442}
443
444#[cfg(test)]
445mod tests {
446 use super::*;
447
448 fn trivial_pattern() -> (Vec<i32>, Vec<i32>) {
449 // Diagonal n=3: col_ptr=[0,1,2,3], row_idx=[0,1,2]
450 (vec![0, 1, 2, 3], vec![0, 1, 2])
451 }
452
453 #[test]
454 fn options_defaults_match_metis_5_2_0() {
455 let o = MetisOptions::default();
456 assert_eq!(o.niparts, 7);
457 assert_eq!(o.coarsen_floor, 120);
458 assert_eq!(o.nd_to_amd_switch, 200);
459 assert_eq!(o.seed, 1);
460 }
461
462 #[test]
463 fn stats_default_is_zeros() {
464 let s = MetisStats::default();
465 assert_eq!(s.n_levels, 0);
466 assert_eq!(s.n_components, 0);
467 assert_eq!(s.n_separator_vertices, 0);
468 assert_eq!(s.n_fm_passes, 0);
469 assert_eq!(s.n_two_hop_fallbacks, 0);
470 assert_eq!(s.n_amd_leaf_calls, 0);
471 }
472
473 #[test]
474 fn diagonal_pattern_yields_permutation() {
475 let (cp, ri) = trivial_pattern();
476 let pat = CscPattern::new(3, &cp, &ri).unwrap();
477 let (perm, ostats, _mstats) = metis_order_full(&pat, &MetisOptions::default()).expect("ok");
478 assert_eq!(perm.len(), 3);
479 let mut seen = [false; 3];
480 for &p in &perm {
481 assert!((0..3).contains(&p));
482 seen[p as usize] = true;
483 }
484 assert!(seen.iter().all(|&s| s));
485 // time_us is populated; fill/flop remain None.
486 assert!(ostats.fill_estimate.is_none());
487 assert!(ostats.flop_estimate.is_none());
488 }
489
490 #[test]
491 fn convenience_wrapper_returns_permutation() {
492 let (cp, ri) = trivial_pattern();
493 let pat = CscPattern::new(3, &cp, &ri).unwrap();
494 let perm = metis_order(&pat).expect("ok");
495 assert_eq!(perm.len(), 3);
496 }
497
498 #[test]
499 fn contract_version_matches_core() {
500 assert_eq!(CONTRACT_VERSION, feral_ordering_core::CONTRACT_VERSION);
501 }
502}