Skip to main content

feral_kahip/
lib.rs

1//! KaHIP-style flow-based nested-dissection fill-reducing ordering.
2//!
3//! **Status: phases K1-K6 complete.**
4//! [`kahip_order`] produces a contract-conforming permutation via the
5//! full pipeline: K1 data reduction (degree-1 / degree-2 / twin /
6//! subset), then K2-K6 multilevel flow-based nested dissection on the
7//! reduced graph (coarsen → initial bisect → uncoarsen with K3 flow
8//! refinement → K4 boundary-bipartite node separator → recurse), then
9//! K1 expansion to lift the reduced-graph permutation back to original
10//! indices.
11//!
12//! **Plan.** `dev/plans/ordering-kahip.md` tracks the six
13//! implementation phases:
14//!   - K1: Data reduction (degree-1 / degree-2 / twin / neighborhood-
15//!     subset rules, fixed-point loop, expansion permutation stack).
16//!   - K2: Push-relabel max-flow (with gap relabeling).
17//!   - K3: Flow-based edge refinement (band extraction, super-source/
18//!     sink construction, Most Balanced Min Cut).
19//!   - K4: Flow-based node separator (vertex-capacitated max-flow).
20//!   - K5: V-cycle / F-cycle controller (cut-edge-preserving
21//!     re-coarsening for monotone quality improvement).
22//!   - K6: Driver and Fast / Eco / Strong modes.
23//!
24//! **Reference papers** (published, public-domain algorithms — the
25//! implementation must be clean-room from these sources, not from
26//! KaHIP's C++ codebase):
27//!   - Sanders & Schulz, "Engineering Multilevel Graph Partitioning
28//!     Algorithms" (2011) — the kaffpa framework.
29//!   - Ost, Schulz & Strash, "Engineering Data Reduction for Nested
30//!     Dissection" (2021) — the K1 reduction rules.
31//!
32//! The public surface conforms to the FERAL ordering-crate contract
33//! (`dev/plans/ordering-crate-contract.md`): `CscPattern`,
34//! `OrderingStats`, `OrderingError`, and `CONTRACT_VERSION` are
35//! re-exported from `feral-ordering-core`.
36
37#![forbid(unsafe_code)]
38#![deny(missing_docs)]
39
40pub use feral_ordering_core::interrupt::Interrupt;
41pub use feral_ordering_core::{CscPattern, OrderingError, OrderingStats, CONTRACT_VERSION};
42
43// Phase K1: data reduction (Ost-Schulz-Strash 2021). Wired into the
44// K6 driver (see `node_nd::kahip_nd_order`) as a fixed-point pre-pass
45// that shrinks the graph via degree-1 / degree-2 / twin / subset rules
46// before multilevel partitioning. Eliminated vertices are expanded
47// back into the final permutation via `expand_permutation`. See
48// `dev/plans/ordering-kahip.md` and `dev/research/ordering-kahip-k1.md`.
49mod data_reduction;
50
51// Phase K2: push-relabel max-flow / min-cut (Goldberg-Tarjan 1988 +
52// Cherkassky-Goldberg 1995 gap relabeling). Internal until K3 (flow-
53// based edge refinement) consumes it; see
54// `dev/plans/ordering-kahip.md` and `dev/research/ordering-kahip-k2.md`.
55#[allow(dead_code)]
56mod flow;
57
58// Phase K3 scaffolding: shared undirected-graph type (CSR) used by
59// K3/K4/K5/K6, and flow-based edge refinement of a bisection.
60// Internal until K5/K6 consume them; see
61// `dev/plans/ordering-kahip.md` and `dev/research/ordering-kahip-k3.md`.
62#[allow(dead_code)]
63mod flow_refine;
64#[allow(dead_code)]
65mod graph;
66
67// Phase K4: flow-based node separator via boundary-bipartite vertex
68// cover (König's theorem reduction). Internal until K5/K6 consume
69// it; see `dev/plans/ordering-kahip.md` and
70// `dev/research/ordering-kahip-k4.md`.
71#[allow(dead_code)]
72mod node_separator;
73
74// Phase K5 (multilevel bisection controller) and K6 (recursive ND
75// driver). K5 reuses feral-metis's coarsening / initial-partition / FM
76// plumbing and plugs in K3 flow refinement at each uncoarsening level.
77// K6 walks connected components, recurses on each, and layers K4 on top
78// of K5 to produce a node separator at every internal level.
79mod cycle;
80mod node_nd;
81
82/// Crate-specific diagnostic statistics.
83///
84/// Populated by [`kahip_order_full`] once the implementation lands;
85/// zeroed while the crate is in its scaffold state.
86#[derive(Debug, Default, Clone)]
87pub struct KahipStats {
88    /// Number of vertices after data-reduction preprocessing.
89    /// `reduced_n == 0` indicates the reduction phase has not run
90    /// (scaffold state).
91    pub reduced_n: usize,
92    /// Largest max-flow subproblem size, in vertices, encountered
93    /// during flow-based refinement. `0` while scaffolded.
94    pub max_flow_vertices: usize,
95    /// Number of multilevel bisections performed — one per node-separator
96    /// computation across the nested-dissection tree. Each is a single
97    /// V-cycle (one coarsen followed by one uncoarsen). `0` while
98    /// scaffolded.
99    pub cycles: usize,
100    /// Number of top-level connected components encountered by the
101    /// nested-dissection driver. `0` while scaffolded. Matches the
102    /// `n_components` field on `MetisStats` / `ScotchStats`.
103    pub n_components: u32,
104}
105
106/// Quality / speed tradeoff modes for the KaHIP driver.
107///
108/// The exact tuning of each mode is fixed once phase K6 lands. Until
109/// then the enum is reserved so that callers can encode intent
110/// without the crate compiling the mapping.
111#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
112pub enum KahipMode {
113    /// METIS-comparable wall-clock; single multilevel pass.
114    #[default]
115    Fast,
116    /// 2-3× Fast; one V-cycle with flow refinement at the finest
117    /// level.
118    Eco,
119    /// 5-10× Fast; F-cycle with flow refinement at every level.
120    Strong,
121}
122
123/// Tunable parameters for KaHIP nested-dissection ordering.
124///
125/// Kept intentionally narrow while the crate is a scaffold —
126/// defaults will match KaHIP's library defaults (seed=0, mode=Fast)
127/// once phase K6 is implemented.
128#[derive(Debug, Clone)]
129pub struct KahipOptions {
130    /// Deterministic RNG seed. Two runs with the same seed on the
131    /// same input must produce the same permutation.
132    pub seed: u64,
133    /// Quality / speed tradeoff. See [`KahipMode`].
134    pub mode: KahipMode,
135    /// Carry the **node separator** through uncoarsening and refine it
136    /// at every level, instead of refining the 2-way bisection and
137    /// lifting to a separator once at the finest level.
138    ///
139    /// The old path optimised the wrong objective at every level:
140    /// minimum edge cut and minimum vertex separator are different
141    /// problems. `feral-metis` and `feral-scotch` had the identical
142    /// defect. KaHIP's flow lift (`flow_node_separator`) is a max-flow
143    /// vertex-cover reduction, too expensive to rerun per level, so the
144    /// lift happens once at the *coarsest* level and the separator is
145    /// then FM-refined down the hierarchy. Evidence in
146    /// `dev/research/scotch-kahip-node-separator-2026-09-18.md`.
147    pub node_refine: bool,
148}
149
150impl Default for KahipOptions {
151    fn default() -> Self {
152        Self {
153            seed: 1,
154            mode: KahipMode::default(),
155            node_refine: true,
156        }
157    }
158}
159
160/// Compute a fill-reducing KaHIP nested-dissection ordering.
161///
162/// Thin wrapper over [`kahip_order_full`] that discards the
163/// diagnostic stats. Returns a permutation `perm` (new-to-old).
164///
165/// Runs the K2-K6 pipeline with default options; see
166/// [`kahip_order_full`] for the tunable entry point.
167pub fn kahip_order(pattern: &CscPattern<'_>) -> Result<Vec<i32>, OrderingError> {
168    kahip_order_full(pattern, &KahipOptions::default()).map(|(perm, _, _)| perm)
169}
170
171/// [`kahip_order_full`] that stops with [`OrderingError::Interrupted`] once
172/// `interrupt` triggers (its deadline passes or its cancel flag is set)
173/// (feral issue #246). The check runs at safe points inside the ordering,
174/// so the overshoot past a deadline is bounded by one of them rather than
175/// by the whole ordering. With [`Interrupt::none`] the result is identical
176/// to [`kahip_order_full`].
177pub fn kahip_order_interruptible(
178    pattern: &CscPattern<'_>,
179    opts: &KahipOptions,
180    interrupt: &Interrupt,
181) -> Result<(Vec<i32>, OrderingStats, KahipStats), OrderingError> {
182    feral_ordering_core::interrupt::scope(interrupt, || kahip_order_full(pattern, opts))
183}
184
185/// Contract-conforming ordering producer.
186///
187/// Signature matches the shape every FERAL ordering crate must expose
188/// per `dev/plans/ordering-crate-contract.md`: input is a
189/// full-symmetric [`CscPattern`] and options; output is a three-tuple
190/// of `(perm, OrderingStats, crate-stats)`, with errors in
191/// [`OrderingError`].
192///
193/// Runs the K2-K6 pipeline: K5 multilevel edge bisection (coarsen,
194/// initial bisect, uncoarsen with K3 flow refinement at each level),
195/// K4 boundary-bipartite vertex cover to lift the bisection to a node
196/// separator, and recursive nested dissection with an AMD leaf
197/// fallback for subgraphs below the mode-dependent switch.
198///
199/// `OrderingStats.time_us` is the wall-clock time of this call.
200/// `fill_estimate` and `flop_estimate` stay `None` — KaHIP does not
201/// produce them at the ordering boundary; they belong to a downstream
202/// symbolic analysis.
203pub fn kahip_order_full(
204    pattern: &CscPattern<'_>,
205    opts: &KahipOptions,
206) -> Result<(Vec<i32>, OrderingStats, KahipStats), OrderingError> {
207    if pattern.col_ptr.len() != pattern.n + 1 {
208        return Err(OrderingError::MalformedInput);
209    }
210    let t0 = std::time::Instant::now();
211    let mut stats = KahipStats::default();
212    let perm = node_nd::kahip_nd_order(pattern, opts, &mut stats)?;
213    let ordering_stats = OrderingStats {
214        time_us: t0.elapsed().as_micros() as u64,
215        fill_estimate: None,
216        flop_estimate: None,
217    };
218    Ok((perm, ordering_stats, stats))
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224
225    #[test]
226    fn scaffold_rejects_malformed_input() {
227        let col_ptr = [0i32, 0];
228        let row_idx: [i32; 0] = [];
229        let pattern = CscPattern::new(5, &col_ptr, &row_idx);
230        assert!(pattern.is_none(), "malformed pattern must fail validation");
231    }
232
233    #[test]
234    fn diagonal_pattern_yields_valid_permutation() {
235        let col_ptr = [0i32, 1, 2, 3];
236        let row_idx = [0i32, 1, 2];
237        let pattern = CscPattern::new(3, &col_ptr, &row_idx).expect("valid pattern");
238        let perm = kahip_order(&pattern).expect("ordering ok");
239        assert_eq!(perm.len(), 3);
240        let mut seen = [false; 3];
241        for &p in &perm {
242            assert!((0..3).contains(&p));
243            seen[p as usize] = true;
244        }
245        assert!(seen.iter().all(|&s| s));
246    }
247
248    #[test]
249    fn scaffold_propagates_malformed_input_to_caller() {
250        // Caller-side malformed check: col_ptr len mismatch.
251        // We have to construct this manually since CscPattern::new
252        // refuses it — so build the struct through a sibling-crate
253        // pattern then corrupt through direct field access is not
254        // possible. Instead, test the same invariant via public API.
255        let col_ptr = [0i32, 2];
256        let row_idx = [0i32, 1];
257        let pattern = CscPattern::new(1, &col_ptr, &row_idx);
258        assert!(
259            pattern.is_none(),
260            "n=1 but col_ptr suggests 1 column with 2 rows"
261        );
262    }
263}