Skip to main content

feral_scotch/
lib.rs

1//! SCOTCH-style nested-dissection fill-reducing ordering.
2//!
3//! Clean-room pure-Rust implementation of the algorithms described in
4//! Pellegrini, "SCOTCH: A software package for static mapping by dual
5//! recursive bipartitioning of process and architecture graphs"
6//! (HPCN Europe, 1996), §3. This crate provides an alternative to
7//! [`feral_metis`](../feral_metis) with:
8//!
9//! - Graph compression (supervariable merging before partitioning).
10//! - Direct vertex-separator FM (tighter separators than edge-cut
11//!   conversion on structured meshes).
12//! - Adaptive refinement (boundary / halo FM). A band-FM refiner
13//!   (`band_fm`) is implemented and unit-tested but is not yet wired
14//!   into the default ND driver.
15//!
16//! The public surface conforms to the FERAL ordering-crate contract
17//! (`dev/plans/ordering-crate-contract.md`): [`CscPattern`],
18//! [`OrderingStats`], [`OrderingError`], and [`CONTRACT_VERSION`] are
19//! re-exported from `feral-ordering-core`.
20//!
21//! **Status: S1–S5 complete.** [`scotch_order`] and
22//! [`scotch_order_full`] run the full pipeline — graph compression,
23//! connected-component split, multilevel coarsening, best-of-
24//! `n_sep_trials` initial bisection, halo-FM uncoarsening, direct
25//! vertex separator, and recursive ND with an AMD leaf fallback.
26//!
27//! ## Clean-room provenance
28//!
29//! No code is copied or paraphrased from SCOTCH's C source
30//! (`libscotch/`, CeCILL-C). Algorithms are reconstructed from
31//! Pellegrini 1996 §3 and the research notes under `dev/research/`.
32//! Constants, data layouts, and hash choices are independently
33//! justified and documented per-module.
34
35#![forbid(unsafe_code)]
36#![deny(missing_docs)]
37
38#[allow(dead_code)]
39mod band_fm;
40#[allow(dead_code)]
41mod compress;
42#[allow(dead_code)]
43mod graph;
44#[allow(dead_code)]
45mod halo_fm;
46mod node_nd;
47#[allow(dead_code)]
48mod vertex_separator;
49
50#[cfg(test)]
51mod test_util;
52
53pub use feral_ordering_core::interrupt::Interrupt;
54pub use feral_ordering_core::{CscPattern, OrderingError, OrderingStats, CONTRACT_VERSION};
55
56/// Tunable parameters for SCOTCH nested-dissection ordering.
57///
58/// Defaults mirror SCOTCH 7.0's vertex-separation ordering defaults as
59/// documented in the audit of `dev/plans/ordering-scotch.md`:
60/// `cmin = 100` (coarsening floor), `amd_switch = 120`,
61/// `n_sep_trials = 5`, `fm_move_cap = 200`, `bal = 0.05`,
62/// `compress_ratio = 0.7`, `seed = 0xDEAD_BEEF`.
63///
64/// **S1 status:** only [`compress`](Self::compress) and
65/// [`compress_ratio`](Self::compress_ratio) are consumed by shipped
66/// code. The remaining fields are defined at the S1 boundary so that
67/// the public type does not drift between milestones.
68#[derive(Debug, Clone)]
69pub struct ScotchOptions {
70    /// Apply graph compression before partitioning.
71    pub compress: bool,
72    /// Compress only if `n_compressed / n < compress_ratio` (i.e.,
73    /// compress only when compression saves at least
74    /// `(1 - compress_ratio) * 100` % of vertices). SCOTCH uses 0.75;
75    /// we follow the plan's slightly more aggressive 0.7.
76    pub compress_ratio: f64,
77    /// Switch from recursive ND to AMD on subproblems with at most
78    /// this many vertices (SCOTCH default: 120).
79    pub amd_switch: u32,
80    /// Stop coarsening when the graph has fewer than this many
81    /// vertices (SCOTCH `cmin` = 100 for vertex-separation contexts).
82    pub coarsen_floor: u32,
83    /// Number of separator trials at each recursion level (SCOTCH
84    /// default: 5).
85    pub n_sep_trials: u32,
86    /// FM refinement: per-pass move cap (SCOTCH default: 200).
87    pub fm_move_cap: u32,
88    /// FM refinement: per-call pass cap. SCOTCH's default is "passes
89    /// until no improvement"; we clamp at 32 for bounded runtime.
90    pub fm_pass_cap: u32,
91    /// Imbalance tolerance (SCOTCH default: 0.05).
92    pub max_imbalance: f64,
93    /// Carry the **node separator** through uncoarsening and refine it
94    /// at every level, instead of refining the 2-way bisection with
95    /// halo FM and building the separator once at the finest level.
96    ///
97    /// The old path optimised the wrong objective at every level: halo
98    /// FM minimises an edge cut, and minimum edge cut and minimum
99    /// vertex separator are different problems. `feral-metis` had the
100    /// identical defect and fixing it there was worth 3.1x on a
101    /// collocation KKT; the same measurement for this crate is in
102    /// `dev/research/scotch-kahip-node-separator-2026-09-18.md`.
103    pub node_refine: bool,
104    /// Deterministic RNG seed for coarsening matching.
105    pub seed: u64,
106}
107
108impl Default for ScotchOptions {
109    fn default() -> Self {
110        Self {
111            compress: true,
112            compress_ratio: 0.7,
113            amd_switch: 120,
114            coarsen_floor: 100,
115            n_sep_trials: 5,
116            fm_move_cap: 200,
117            fm_pass_cap: 32,
118            max_imbalance: 0.05,
119            node_refine: true,
120            seed: 0xDEAD_BEEF,
121        }
122    }
123}
124
125/// Crate-specific diagnostic counters for SCOTCH nested dissection.
126///
127/// Zero-initialized at the start of each ordering call and filled in
128/// as the pipeline runs. S1 only touches the compression counters.
129#[derive(Debug, Default, Clone, PartialEq, Eq)]
130pub struct ScotchStats {
131    /// Number of vertices dropped by compression at the top level
132    /// (`n_original - n_compressed`). Zero if compression was
133    /// attempted but returned `None`, or if compression is disabled.
134    pub n_compressed_out: u32,
135    /// Number of coarsening levels built. Unused until S2.
136    pub n_levels: u32,
137    /// Number of top-level connected components encountered. Unused
138    /// until S5.
139    pub n_components: u32,
140    /// Number of vertices assigned to a separator at any level.
141    /// Unused until S5.
142    pub n_separator_vertices: u32,
143    /// Number of FM passes executed across all levels. Unused until
144    /// S3/S4.
145    pub n_fm_passes: u32,
146    /// Number of times the recursion bottomed out in the AMD leaf
147    /// fallback. Unused until S5.
148    pub n_amd_leaf_calls: u32,
149}
150
151/// Compute a fill-reducing SCOTCH nested-dissection ordering.
152///
153/// Thin wrapper over [`scotch_order_full`] that discards the
154/// diagnostic stats. Returns a permutation `perm` (new-to-old).
155pub fn scotch_order(pattern: &CscPattern<'_>) -> Result<Vec<i32>, OrderingError> {
156    scotch_order_full(pattern, &ScotchOptions::default()).map(|(perm, _, _)| perm)
157}
158
159/// [`scotch_order_full`] that stops with [`OrderingError::Interrupted`] once
160/// `interrupt` triggers (its deadline passes or its cancel flag is set)
161/// (feral issue #246). The check runs at safe points inside the ordering,
162/// so the overshoot past a deadline is bounded by one of them rather than
163/// by the whole ordering. With [`Interrupt::none`] the result is identical
164/// to [`scotch_order_full`].
165pub fn scotch_order_interruptible(
166    pattern: &CscPattern<'_>,
167    opts: &ScotchOptions,
168    interrupt: &Interrupt,
169) -> Result<(Vec<i32>, OrderingStats, ScotchStats), OrderingError> {
170    feral_ordering_core::interrupt::scope(interrupt, || scotch_order_full(pattern, opts))
171}
172
173/// Contract-conforming ordering producer.
174///
175/// Signature matches the shape every FERAL ordering crate must expose
176/// per `dev/plans/ordering-crate-contract.md`: input is a
177/// full-symmetric [`CscPattern`] and options; output is a three-tuple
178/// of `(perm, OrderingStats, crate-stats)`, with errors in
179/// [`OrderingError`].
180///
181/// `OrderingStats.time_us` is the wall-clock time of this call.
182/// `fill_estimate` and `flop_estimate` stay `None` — SCOTCH does not
183/// produce them at the ordering boundary; they belong to a downstream
184/// symbolic analysis.
185///
186/// Runs the S1–S5 pipeline: optional graph compression, connected-
187/// component split, multilevel coarsening, best-of-`n_sep_trials`
188/// initial bisection, halo-FM uncoarsening refinement, direct
189/// vertex-separator via two-sided FM, recursion on each side with an
190/// AMD leaf fallback at `amd_switch`.
191pub fn scotch_order_full(
192    pattern: &CscPattern<'_>,
193    opts: &ScotchOptions,
194) -> Result<(Vec<i32>, OrderingStats, ScotchStats), OrderingError> {
195    if pattern.col_ptr.len() != pattern.n + 1 {
196        return Err(OrderingError::MalformedInput);
197    }
198    let t0 = std::time::Instant::now();
199    let mut stats = ScotchStats::default();
200    let perm = node_nd::scotch_nd_order(pattern, opts, &mut stats)?;
201    let ordering_stats = OrderingStats {
202        time_us: t0.elapsed().as_micros() as u64,
203        fill_estimate: None,
204        flop_estimate: None,
205    };
206    Ok((perm, ordering_stats, stats))
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212
213    #[test]
214    fn options_defaults_match_plan() {
215        let o = ScotchOptions::default();
216        assert!(o.compress);
217        assert_eq!(o.compress_ratio, 0.7);
218        assert_eq!(o.amd_switch, 120);
219        assert_eq!(o.coarsen_floor, 100);
220        assert_eq!(o.n_sep_trials, 5);
221        assert_eq!(o.fm_move_cap, 200);
222        assert_eq!(o.fm_pass_cap, 32);
223        assert_eq!(o.max_imbalance, 0.05);
224        assert_eq!(o.seed, 0xDEAD_BEEF);
225    }
226
227    #[test]
228    fn stats_default_is_zeros() {
229        let s = ScotchStats::default();
230        assert_eq!(s.n_compressed_out, 0);
231        assert_eq!(s.n_levels, 0);
232        assert_eq!(s.n_components, 0);
233        assert_eq!(s.n_separator_vertices, 0);
234        assert_eq!(s.n_fm_passes, 0);
235        assert_eq!(s.n_amd_leaf_calls, 0);
236    }
237
238    #[test]
239    fn contract_version_matches_core() {
240        assert_eq!(CONTRACT_VERSION, feral_ordering_core::CONTRACT_VERSION);
241    }
242
243    #[test]
244    fn scotch_order_trivial_diagonal() {
245        let cp = vec![0i32, 1, 2, 3];
246        let ri = vec![0i32, 1, 2];
247        let pat = CscPattern::new(3, &cp, &ri).unwrap();
248        let perm = scotch_order(&pat).expect("trivial 3-vertex diagonal orders");
249        assert_eq!(perm.len(), 3);
250        let mut seen = [false; 3];
251        for &p in &perm {
252            assert!((0..3).contains(&p));
253            seen[p as usize] = true;
254        }
255        assert!(seen.iter().all(|&s| s));
256    }
257
258    #[test]
259    fn scotch_order_full_populates_time_us() {
260        let cp = vec![0i32, 1, 2, 3];
261        let ri = vec![0i32, 1, 2];
262        let pat = CscPattern::new(3, &cp, &ri).unwrap();
263        let (_perm, ostats, _sstats) =
264            scotch_order_full(&pat, &ScotchOptions::default()).expect("ok");
265        // time_us is populated; fill/flop remain None.
266        assert!(ostats.fill_estimate.is_none());
267        assert!(ostats.flop_estimate.is_none());
268    }
269
270    #[test]
271    fn scotch_order_rejects_malformed_col_ptr() {
272        // col_ptr length must equal n + 1. Construct a well-formed
273        // CscPattern for n = 3, then pass it to scotch_order_full
274        // with an options struct and a lying n via a fresh pattern
275        // that fails the upstream validator.
276        let cp = vec![0i32, 1];
277        let ri: Vec<i32> = Vec::new();
278        // CscPattern::new with n=2 and col_ptr of length 2 rejects at
279        // construction; go through the public API by constructing a
280        // valid n=0 pattern and mutating — since we don't have public
281        // mutation, simply verify that CscPattern::new rejects the
282        // malformed case (the scotch_order_full guard is a defence-
283        // in-depth and is covered by tests in node_nd).
284        assert!(CscPattern::new(2, &cp, &ri).is_none());
285    }
286}