/** * Sparse MNA backend: pattern-persistent stamp slots compiled to CSC, a * quotient-graph approximate-minimum-degree column preorder (amd-ordering.ts), * and left-looking Gilbert-Peierls LU with threshold partial pivoting on the * equilibrated matrix. * * Observable semantics (lastSolveInfo fields, factorization counters, * base/overlay behavior, singular handling, RangeError message, residual * validation in original units) mirror the dense `MNA` class; the shared * contract lives in linear-system.ts. Numeric results may differ from dense * by roundoff because the elimination order differs — both backends validate * against the original unscaled matrix, so `relativeResidual` is the * cross-backend equivalence oracle. * * Value-only restamps (every Newton iteration) take a numeric-only * refactorization fast path: while the pattern is unchanged and the previous * factorization was clean (threshold pivoting, full rank, growth under the * limit), the stored pivot order and L/U column patterns are replayed with no * reachability DFS. Guards inside the replay (pivot tolerance, degradation * against the fresh column maximum, running element growth) abandon it and * rerun the full pass with fresh pivoting, so the fast path can only trade * time, never stability. The AMD preorder replaced an earlier greedy * minimum-degree ordering that materialised fill edges explicitly — quadratic * around hub vertices and dependent on work budgets; the quotient graph * represents cliques implicitly, which handles hub and expander-like patterns * (the random long-range chords in benchmark-linear-scale.ts) without budgets. */ import type { LinearSystem } from "./linear-system.js"; import { type MnaSolveInfo } from "./mna.js"; export declare class SparseMNA implements LinearSystem { readonly size: number; readonly backend: "sparse"; /** Diagnostics for the most recently factorised matrix. */ lastSolveInfo: MnaSolveInfo; /** Monotonic diagnostic counters; never affect factorization validity. */ factorizationCount: number; factorizationReuseCount: number; /** * Numeric-only refactorizations completed — always a subset of * factorizationCount, which keeps counting every numeric pass either way. * SparseMNA-only diagnostic, deliberately outside the LinearSystem * contract: the dense backend has no equivalent fast path, and backends * may expose extras beyond the shared interface (MNA does the same). */ refactorizationCount: number; private readonly slotIndex; private slotRow; private slotCol; private values; private slotCount; private readonly b; /** True when a slot was appended since the last symbolic analysis. */ private patternDirty; /** True when any value/clear/reset touched the matrix since factorization. */ private matrixDirty; private baseSlotCount; private baseValues; private baseRhs; private readonly colPtr; private cscRowIdx; /** slot -> CSC position, so each factorization scatters values in O(nnz). */ private slotToCsc; private cscVal; /** colOrder[k] = original column eliminated at step k (bijective). */ private readonly colOrder; private hasFactorization; /** * True when the stored L/U came from a clean threshold-pivoted pass (full * rank, growth under the limit, no fallback) over the current symbolic * pattern — the preconditions for replaying its pivot order on new values. */ private refactorEligible; private readonly rowScale; private readonly colScale; /** prow[k] = original row pivotal at step k, or -1 for a singular step. */ private readonly prow; /** pinv[row] = pivot step of an original row during factorization, else -1. */ private readonly pinv; private readonly lColPtr; private lRows; private lVals; private lCount; private readonly uColPtr; private uRows; private uVals; private uCount; private readonly uDiag; private fRank; private fMinScaledPivot; /** Exact numeric guard: a stale LU can never be reused on a changed matrix. */ private lastFactorizedValues; private readonly mark; private markGen; private readonly dfsNode; private readonly dfsEdge; private readonly reach; private readonly xWork; private readonly solveW; private readonly solveY; private readonly axScratch; constructor(size: number); /** * Zero values and RHS but KEEP the discovered pattern: dropping it would * rebuild the symbolic analysis every Newton iteration even though the * restamped pattern is identical. */ clear(): void; add(row: number, col: number, val: number): void; addB(row: number, val: number): void; /** Save the current matrix/RHS as the immutable per-topology stamp base. */ captureBase(): void; /** Append-only slot watermark; see LinearSystem.patternCheckpoint. */ patternCheckpoint(): number; /** * Drop every slot appended after the checkpoint. Exact because slots are * append-only and never reorder: the trailing region is precisely what the * exploratory sequence discovered. The symbolic analysis and any stored * factorization refer to the enlarged pattern, so both are invalidated; * the next solve rebuilds them over the restored pattern and every later * factorization is bit-identical to a backend that never saw the dropped * positions. */ restorePatternCheckpoint(checkpoint: number): void; /** Drop pivot-replay and exact-values reuse memory; see LinearSystem. */ invalidateFactorization(): void; /** * Restore the compiled base before adding dynamic/nonlinear overlays. * * Overlay slots appended after `captureBase` stay in the pattern with a * zero value: the pattern is append-only, so the base region is exactly * the first `baseSlotCount` slots, and keeping the overlay slots means the * per-iteration restamp hits existing slots instead of re-growing. */ resetToBase(): void; solve(): Float64Array; /** Solve G·x = rhs, reusing the latest factorisation when G is unchanged. */ solveRhs(rhs: ArrayLike): Float64Array; /** * Element-wise value comparison against the matrix that was factorized. * NaN is treated as matching NaN so a NaN-poisoned matrix does not force an * endless refactorization loop, exactly like the dense guard. Slots * appended since the factorization are numerically neutral while they hold * an exact zero, so the LU stays valid and the reuse decision matches * dense (which sees an unchanged numeric matrix); the symbolic rebuild is * deferred until one of them actually carries a value. */ private matrixMatchesFactorized; /** * Compile the slot pattern to CSC and compute a fill-reducing column * preorder. Runs only when a slot was appended since the last analysis; * value-only restamps (every Newton iteration) skip it entirely. */ private rebuildSymbolic; /** * Fill-reducing column preorder: build the deduplicated symmetric pattern * of A + A^T without self-edges and delegate to the quotient-graph AMD * ordering. The symmetrization matters because Gilbert-Peierls pivots by * row within the preordered column — an order computed on the unsymmetric * pattern would ignore half the fill paths threshold pivoting can take. */ private computeColumnOrder; /** Bump the DFS visit generation, recycling marks before Int32 overflow. */ private nextMarkGen; /** * Depth-first reachability over the partially built L from one root of * A(:,j), appending finished vertices topologically into `reach` from * `reachTop` downward. Explicit stacks: recursion would overflow on long * dependency chains at n around 50k. */ private dfsReach; /** * Numeric factorization: equilibrate exactly like the dense backend, then * either replay the stored pivot order on the new values (refactorization * fast path) or run the threshold-pivoted elimination, rerunning it with * pure partial pivoting when element growth shows the diagonal preference * destabilised the factors. */ private factorize; /** * Shared prologue of every numeric pass: recompute the equilibration * scales for the current values and scatter the equilibrated matrix into * the symbolic CSC positions. Split out because the refactorization fast * path needs fresh scales too — the values changed, so reusing stale * scales would silently change which pivots the guards compare against. */ private equilibrateAndScatter; /** * Numeric-only refactorization: replay the stored pivot sequence over the * stored L/U column patterns, recomputing values with no reachability DFS * and no pivot search. Valid because the update order stored in U per * column is exactly the topological order the discovery DFS produced, so * replaying it on the same pattern performs the same arithmetic as the * full pass would with the same pivot choices — column k only consumes L * columns of earlier steps, which this loop has already rewritten. * * Returns false to abandon (caller reruns the full pass with fresh * pivoting; the arrays are fully rewritten there, so a partial replay * leaves no residue). Abandon triggers: * - pivot at or below PIVOT_TOLERANCE, or non-finite: the step would be * singular under the stored order even though the matrix may not be; * - pivot below REFACTOR_PIVOT_DEGRADATION of the fresh column maximum: * value drift demoted the stored pivot relative to what fresh partial * pivoting would now elect; * - running element growth above GROWTH_LIMIT: same honest-signal bound * as the full pass, checked online so a destabilised replay stops * before wasting the remaining columns. */ private refactor; /** * One left-looking Gilbert-Peierls pass over the preordered columns of the * equilibrated matrix in cscVal. Every rejected pivot marks a singular * step whose variable back-substitutes to zero; accepted pivots drive rank * and minScaledPivot like dense. Returns the largest intermediate column * magnitude — the classical element-growth factor, since equilibration * normalises the input to O(1) — so the caller can detect when threshold * pivoting destabilised the factors. With `preferDiagonal` false the pivot * is always the largest reachable candidate (pure partial pivoting). */ private eliminate; }