Skip to main content

feral_amf/
lib.rs

1//! Approximate Minimum Fill (AMF / HAMF4) fill-reducing ordering.
2//!
3//! Standalone clean-room implementation of the AMF quotient-graph
4//! algorithm (Amestoy 1999 habilitation thesis, MUMPS HAMF4
5//! variant). The metric is approximate fill rather than approximate
6//! degree — the per-variable score is
7//!
8//! ```text
9//! RMF(i) = ( deg(i) * (deg(i) - 1 + 2*degme) - WF(i) ) / (nv(i) + 1)
10//! ```
11//!
12//! quantized into a `2N + 2` head-array with a coarse stride above
13//! `N`. The inner loop, including the lazy `WF(e)` element cache,
14//! the supervariable max-merge of `WF`, and the saturated/regular
15//! RMF branch, lives in `feral-ordering-core` behind the `MinFill`
16//! `Metric` impl.
17//!
18//! The public surface conforms to the FERAL ordering-crate
19//! contract (`dev/plans/ordering-crate-contract.md`). `CscPattern`,
20//! `OrderingStats`, `OrderingError`, and `CONTRACT_VERSION` are
21//! re-exported from `feral-ordering-core`.
22//!
23//! HAMF4 always aggressively absorbs elements, so [`AmfOptions`]
24//! does not expose an `aggressive` knob; the `dense_alpha` knob
25//! lives in the shared workspace and behaves identically to
26//! `feral-amd`'s.
27
28#![forbid(unsafe_code)]
29#![deny(missing_docs)]
30
31mod stats;
32
33pub use feral_ordering_core::interrupt::Interrupt;
34pub use feral_ordering_core::{CscPattern, OrderingError, OrderingStats, CONTRACT_VERSION};
35pub use stats::AmfStats;
36
37use feral_ordering_core::quotient_graph::{order, MinFill, WorkspaceOptions};
38use std::time::Instant;
39
40/// Tunable parameters for AMF ordering.
41///
42/// Defaults: `dense_alpha = 10.0`. HAMF4 always aggressively
43/// absorbs absorbed elements during the inner Pass-2 loop, so
44/// there is no `aggressive` knob.
45#[derive(Debug, Clone)]
46pub struct AmfOptions {
47    /// Dense-row threshold multiplier. A variable with initial
48    /// degree exceeding `min(max(16, floor(dense_alpha * sqrt(n))), n)`
49    /// is deferred to the end of the ordering — the `max(16)` floor is
50    /// applied before the `min(n)` cap, matching faer `amd.rs:173-179`.
51    /// A negative value uses a raw threshold of `n - 2` with the same
52    /// clamps; for `n >= 18` that is exactly `n - 2`, suppressing
53    /// deferral for all but true hubs of degree `n - 1`.
54    pub dense_alpha: f64,
55}
56
57impl Default for AmfOptions {
58    fn default() -> Self {
59        Self { dense_alpha: 10.0 }
60    }
61}
62
63/// Compute a fill-reducing AMF 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 amf_order(pattern: &CscPattern<'_>) -> Result<Vec<i32>, OrderingError> {
70    amf_order_opts(pattern, &AmfOptions::default()).map(|(perm, _)| perm)
71}
72
73/// Compute an AMF ordering and return the crate-specific diagnostic
74/// counters.
75///
76/// See [`amf_order`] and [`AmfStats`]. Callers that also need the
77/// shared [`OrderingStats`] (wall time, fill estimate) should use
78/// [`amf_order_full`] instead.
79pub fn amf_order_with_stats(
80    pattern: &CscPattern<'_>,
81) -> Result<(Vec<i32>, AmfStats), OrderingError> {
82    amf_order_opts(pattern, &AmfOptions::default())
83}
84
85/// Compute an AMF ordering with explicit options.
86///
87/// Returns `(perm, amf_stats)`. See [`amf_order_full`] for the
88/// contract-conforming three-tuple return.
89pub fn amf_order_opts(
90    pattern: &CscPattern<'_>,
91    opts: &AmfOptions,
92) -> Result<(Vec<i32>, AmfStats), OrderingError> {
93    amf_order_full(pattern, opts).map(|(perm, _, amf_stats)| (perm, amf_stats))
94}
95
96/// [`amf_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 [`amf_order_full`].
102pub fn amf_order_interruptible(
103    pattern: &CscPattern<'_>,
104    opts: &AmfOptions,
105    interrupt: &Interrupt,
106) -> Result<(Vec<i32>, OrderingStats, AmfStats), OrderingError> {
107    feral_ordering_core::interrupt::scope(interrupt, || amf_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 AMF —
120/// the per-crate [`AmfStats`] 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 amf_order_full(
124    pattern: &CscPattern<'_>,
125    opts: &AmfOptions,
126) -> Result<(Vec<i32>, OrderingStats, AmfStats), OrderingError> {
127    let t0 = Instant::now();
128    let ws_opts = WorkspaceOptions {
129        dense_alpha: opts.dense_alpha,
130    };
131    // HAMF4 always aggressively absorbs; pass `aggressive = true`
132    // unconditionally. The flag only gates the AMD-specific
133    // `(p3 == pn) && (elen[i] == 1)` mass-elimination branch which
134    // the AMF loop reuses with the same semantics.
135    let (perm, diag) = order::<MinFill>(pattern, &ws_opts, true)?;
136    let amf_stats = AmfStats {
137        ncmpa: diag.ncmpa,
138        n_clear_flag: 0,
139        n_mass_elim: diag.n_mass_elim,
140        n_supervar_merge: diag.n_supervar_merge,
141        n_dense_deferred: diag.ndense.max(0) as u32,
142        ndiv: diag.flops.ndiv.max(0.0) as u64,
143        nms_lu: diag.flops.nms_lu.max(0.0) as u64,
144        nms_ldl: diag.flops.nms_ldl.max(0.0) as u64,
145    };
146    let ordering_stats = OrderingStats {
147        time_us: t0.elapsed().as_micros() as u64,
148        fill_estimate: None,
149        flop_estimate: None,
150    };
151    Ok((perm, ordering_stats, amf_stats))
152}