Skip to main content

feral_amd/
lib.rs

1//! Approximate Minimum Degree (AMD) fill-reducing ordering.
2//!
3//! Standalone implementation of the in-place quotient-graph AMD
4//! algorithm (Amestoy, Davis & Duff 1996, 2004). See the crate
5//! README and `dev/plans/ordering-amd-upgrade.md` for scope and
6//! references.
7//!
8//! Slice B is complete: mass elimination (Commit 9) and
9//! supervariable detection (Commit 10) are both live, so the
10//! ordering matches SuiteSparse / faer on the full oracle
11//! fixture suite.
12//!
13//! The public surface conforms to the FERAL ordering-crate
14//! contract (`dev/plans/ordering-crate-contract.md`). `CscPattern`,
15//! `OrderingStats`, `OrderingError`, and `CONTRACT_VERSION` are
16//! re-exported from `feral-ordering-core`.
17
18#![forbid(unsafe_code)]
19#![deny(missing_docs)]
20
21mod stats;
22
23pub use feral_ordering_core::interrupt::Interrupt;
24pub use feral_ordering_core::{CscPattern, OrderingError, OrderingStats, CONTRACT_VERSION};
25pub use stats::AmdStats;
26
27use feral_ordering_core::quotient_graph::{
28    finalize_permutation, order, run_elimination, MinDegree, Workspace, WorkspaceOptions,
29};
30use std::time::Instant;
31
32/// Tunable parameters for AMD ordering.
33///
34/// Defaults match faer / SuiteSparse: `aggressive = true`,
35/// `dense_alpha = 10.0`.
36#[derive(Debug, Clone)]
37pub struct AmdOptions {
38    /// Enable aggressive element absorption in the Pass-2 degree
39    /// loop (faer `amd.rs:404-407`).
40    pub aggressive: bool,
41    /// Dense-row threshold multiplier. A variable with initial
42    /// degree exceeding `min(max(16, floor(dense_alpha * sqrt(n))), n)`
43    /// is deferred to the end of the ordering — the `max(16)` floor is
44    /// applied before the `min(n)` cap, matching faer `amd.rs:173-179`
45    /// / SuiteSparse AMD (the order matters: it guarantees the
46    /// threshold is `<= n`). A negative value uses a raw threshold of
47    /// `n - 2` in place of `dense_alpha * sqrt(n)`, with the same
48    /// `max(16)`/`min(n)` clamps; for `n >= 18` that is exactly
49    /// `n - 2`, suppressing deferral for all but true hubs of degree
50    /// `n - 1`.
51    pub dense_alpha: f64,
52}
53
54impl Default for AmdOptions {
55    fn default() -> Self {
56        Self {
57            aggressive: true,
58            dense_alpha: 10.0,
59        }
60    }
61}
62
63/// Compute a fill-reducing AMD ordering.
64///
65/// Returns a permutation `perm` (new-to-old) such that factoring
66/// `P·A·Pᵀ` with `P[k] = perm[k]` produces less fill than the
67/// natural ordering. The input must be the full symmetric pattern
68/// (both halves present).
69pub fn amd_order(pattern: &CscPattern<'_>) -> Result<Vec<i32>, OrderingError> {
70    amd_order_opts(pattern, &AmdOptions::default()).map(|(perm, _)| perm)
71}
72
73/// Compute an AMD ordering and return the crate-specific diagnostic
74/// counters.
75///
76/// See [`amd_order`] and [`AmdStats`]. Callers that also need the
77/// shared [`OrderingStats`] (wall time, fill estimate) should use
78/// [`amd_order_full`] instead.
79pub fn amd_order_with_stats(
80    pattern: &CscPattern<'_>,
81) -> Result<(Vec<i32>, AmdStats), OrderingError> {
82    amd_order_opts(pattern, &AmdOptions::default())
83}
84
85/// Compute an AMD ordering with explicit options.
86///
87/// Returns `(perm, amd_stats)`. See [`amd_order_full`] for the
88/// contract-conforming three-tuple return.
89pub fn amd_order_opts(
90    pattern: &CscPattern<'_>,
91    opts: &AmdOptions,
92) -> Result<(Vec<i32>, AmdStats), OrderingError> {
93    amd_order_full(pattern, opts).map(|(perm, _, amd_stats)| (perm, amd_stats))
94}
95
96/// [`amd_order_full`] that stops with [`OrderingError::Interrupted`] once
97/// `interrupt` triggers (its deadline passes or its cancel flag is set)
98/// (feral issue #246). The check runs at safe points inside the ordering,
99/// so the overshoot past a deadline is bounded by one of them rather than
100/// by the whole ordering. With [`Interrupt::none`] the result is identical
101/// to [`amd_order_full`].
102pub fn amd_order_interruptible(
103    pattern: &CscPattern<'_>,
104    opts: &AmdOptions,
105    interrupt: &Interrupt,
106) -> Result<(Vec<i32>, OrderingStats, AmdStats), OrderingError> {
107    feral_ordering_core::interrupt::scope(interrupt, || amd_order_full(pattern, opts))
108}
109
110/// Contract-conforming ordering producer.
111///
112/// Signature matches the shape every FERAL ordering crate must
113/// expose per `dev/plans/ordering-crate-contract.md`: input is a
114/// full-symmetric [`CscPattern`] and options; output is a
115/// three-tuple of `(perm, OrderingStats, crate-stats)`, with
116/// errors in [`OrderingError`].
117///
118/// `OrderingStats.time_us` is the wall-clock time of this call.
119/// `fill_estimate` and `flop_estimate` are left as `None` for AMD —
120/// the per-crate [`AmdStats`] carries `ndiv` / `nms_lu` / `nms_ldl`
121/// flop counters that may be surfaced here in a future revision
122/// without bumping the contract.
123pub fn amd_order_full(
124    pattern: &CscPattern<'_>,
125    opts: &AmdOptions,
126) -> Result<(Vec<i32>, OrderingStats, AmdStats), OrderingError> {
127    let t0 = Instant::now();
128    let ws_opts = WorkspaceOptions {
129        dense_alpha: opts.dense_alpha,
130    };
131    let (perm, diag) = order::<MinDegree>(pattern, &ws_opts, opts.aggressive)?;
132    let amd_stats = AmdStats {
133        ncmpa: diag.ncmpa,
134        n_clear_flag: 0,
135        n_mass_elim: diag.n_mass_elim,
136        n_supervar_merge: diag.n_supervar_merge,
137        n_dense_deferred: diag.ndense.max(0) as u32,
138        ndiv: diag.flops.ndiv.max(0.0) as u64,
139        nms_lu: diag.flops.nms_lu.max(0.0) as u64,
140        nms_ldl: diag.flops.nms_ldl.max(0.0) as u64,
141    };
142    let ordering_stats = OrderingStats {
143        time_us: t0.elapsed().as_micros() as u64,
144        fill_estimate: None,
145        flop_estimate: None,
146    };
147    Ok((perm, ordering_stats, amd_stats))
148}
149
150/// Per-sub-stage wall-clock breakdown of one AMD call.
151///
152/// Returned by [`amd_order_substages`] alongside the permutation.
153/// All fields are wall-clock microseconds for that single call.
154/// Sum is approximately equal to the total time reported by
155/// [`amd_order_full`]'s [`OrderingStats::time_us`], modulo a few
156/// hundred ns of `Instant::now()` overhead.
157///
158/// Used by the small-n diagnostic probe
159/// `feral::bin::diag_amd_substages` to attribute the per-call AMD
160/// cost between workspace allocation, the main elimination loop,
161/// and permutation finalisation. See
162/// `dev/plans/phase-2.13-tail-diagnostic.md` step 5.
163#[derive(Debug, Clone, Copy, Default)]
164pub struct AmdSubstages {
165    /// Time spent in `AmdWorkspace::new`: input ingest, vector
166    /// allocations, initial degree lists, dense-row deferral.
167    pub workspace_new_us: u64,
168    /// Time spent in the main pivot/eliminate/finalize loop
169    /// (`select_pivot` + `create_element` + `finalize_step`).
170    pub run_elimination_us: u64,
171    /// Time spent in the assembly-tree postorder and final
172    /// permutation emission.
173    pub finalize_permutation_us: u64,
174}
175
176/// Compute an AMD ordering and report a per-sub-stage timing
177/// breakdown.
178///
179/// Behaves identically to [`amd_order_full`] but additionally
180/// returns an [`AmdSubstages`] split of the wall-clock time across
181/// `workspace::new`, `run_elimination`, and `finalize_permutation`.
182/// Diagnostic-only — production callers should keep using
183/// [`amd_order`] / [`amd_order_full`]. The `Instant::now()` calls
184/// add at most ~100 ns vs the un-profiled path, but the API surface
185/// is intentionally separate to avoid polluting the stable
186/// contract-conforming function.
187pub fn amd_order_substages(
188    pattern: &CscPattern<'_>,
189    opts: &AmdOptions,
190) -> Result<(Vec<i32>, AmdSubstages), OrderingError> {
191    let t = Instant::now();
192    let ws_opts = WorkspaceOptions {
193        dense_alpha: opts.dense_alpha,
194    };
195    let mut ws = Workspace::new(pattern, &ws_opts)?;
196    let workspace_new_us = t.elapsed().as_micros() as u64;
197
198    let t = Instant::now();
199    let _flops = run_elimination(&mut ws, opts.aggressive)?;
200    let run_elimination_us = t.elapsed().as_micros() as u64;
201
202    let t = Instant::now();
203    let perm = finalize_permutation(&mut ws);
204    let finalize_permutation_us = t.elapsed().as_micros() as u64;
205
206    Ok((
207        perm,
208        AmdSubstages {
209            workspace_new_us,
210            run_elimination_us,
211            finalize_permutation_us,
212        },
213    ))
214}