pyrucast 0.13.2

Finite-element library in Rust, inspired by cast3m, exposed to Python
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
//! Unilateral (inequality) constraint solve by the **active-set** (status)
//! method — the path of [`super::solve`] for a matrix whose relation rows carry
//! a non-equality [`RelationSense`].
//!
//! A unilateral relation `Σₖ aₖ·u(nodeₖ,varₖ) ≥ g` (or `≤ g`) obeys the KKT
//! complementarity conditions instead of a plain equation: either the relation
//! is **active** (it holds as an equality and its multiplier `λ` carries the
//! reaction) or it is **inactive** (the gap `C·u − g` is on the feasible side
//! and `λ = 0`). Which relations are active is not known in advance; the status
//! method iterates on it:
//!
//! 1. start from a trial active set (every inequality active, or the previous
//!    converged status when cached — a *warm start*);
//! 2. solve the saddle-point system with the **inactive** constraint rows
//!    replaced by `d_r·λ_r = 0` (the matrix keeps its size; only values
//!    change), `d_r` the size of the relation's own coefficients;
//! 3. check the signs: an active relation whose `λ` pulls (sign infeasible for
//!    its sense) is released; an inactive relation whose gap penetrates is
//!    activated;
//! 4. no status change ⇒ converged (the finite loop of the classical status
//!    method); otherwise refactorize and repeat.
//!
//! # Sign convention
//!
//! The assembled saddle-point reads `K·u + Cᵀ·λ = f`, `C·u = g` (see
//! [`constraint_block_pair`](crate::models)); against the KKT multiplier `μ ≥ 0`
//! of a `≥` constraint (`K·u − Cᵀ·μ = f`) this gives `λ = −μ`. Hence, in the
//! solution field (same convention as the Lagrange path):
//!
//! - `GreaterEqual` — an active relation has `λ ≤ 0`; released when `λ > tol`;
//! - `LessEqual` — an active relation has `λ ≥ 0`; released when `λ < −tol`.
//!
//! An inactive relation reports `λ = 0` exactly. Its row is `d_r·λ_r = 0`,
//! with a pivot `d_r` of the size of the relation's coefficients: a `1` among
//! coefficients of `10¹²` would leave `λ_r` at the round-off of the solve, and
//! that round-off, times `Cᵀ`, would push the structure. The `λ_r` the solve
//! returns is then set to `0`.
//!
//! # Input
//!
//! Everything is read from the matrix ([`relation_rows`]): an inequality is a
//! relation row whose block declares a sense, its coefficients are the row, its
//! multiplier the column of the same node. Equality relations are left untouched
//! (their rows are always enforced). [`super::solve`] only comes here when the
//! matrix carries an inequality.

use crate::atoms::NodeId;
use crate::containers::matrix::Matrix;
use crate::containers::node_field::NodeField;
use crate::error::{PyrucastError, Result};
use crate::interrupt::Cancel;
use crate::models::RelationSense;
use nalgebra::{DMatrix, DVector};
use parking_lot::Mutex;
use std::collections::HashMap;
use std::sync::Arc;

use super::lu::{self, factorize_csc_arrays, lu_solve_vec, SparseLu};
use super::relations::relation_rows;
use super::scaling::RelationScaling;
use super::SolveOptions;

type NamedDof = (NodeId, String);

/// How the active-set loop factorizes each status's system.
///
/// Both variants explore the **same** status trajectory (identical KKT checks,
/// same converged result) — they differ only in how the linear system of a
/// status is factorized.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::node_field::NodeField;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::RelationSense;
/// # use pyrucast::named::Named;
/// # use pyrucast::ops::{element_field, matrix, mesh, model, solver};
/// # use pyrucast::ops::solver::{ActiveSetMethod, SolveOptions};
/// # let coords = Handle::new(Coords::new(1).unwrap());
/// # let n: Vec<Node> = (0..3)
/// #     .map(|i| Node::create_in(coords.clone(), &[i as f64 / 2.0]).unwrap())
/// #     .collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
/// # for i in 0..2 { sm.add_cell(&[n[i].id(), n[i + 1].id()]).unwrap(); }
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let barre = model::heat_conduction(&fes, MaterialSymmetry::Isotropic)?;
/// # let modele = barre.union(&model::dirichlet(&impose, &barre, "T", RelationSense::GreaterEqual)?)?;
/// # let materiaux = element_field::material_field(&modele, &[("k", 1.0)])?;
/// # let k = matrix::stiffness(&modele, &materiaux)?;
/// # let charge = NodeField::from_submesh(&modele.multiplier_mesh()?.get(0)?,
/// #                                      vec!["imposed".into()])?;
/// # charge.get(0)?.write().add_to_component("imposed", 100.0)?;
/// assert_eq!(ActiveSetMethod::parse("refactorize")?, ActiveSetMethod::Refactorize);
/// // Both variants walk the **same** status trajectory and converge to the
/// // same result; only the way of factorizing differs.
/// let lire = |active_set| -> f64 {
///     let o = SolveOptions { active_set, cache: false, ..Default::default() };
///     solver::solve_with_options(&k, &charge, &o).unwrap().value(n[2].id(), "T").unwrap()
/// };
/// assert!((lire(ActiveSetMethod::SchurComplement) - lire(ActiveSetMethod::Refactorize)).abs() < 1e-9);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ActiveSetMethod {
    /// Factorize the **inequality-free base** `A` (every unilateral relation
    /// released) **once**, cache it on the matrix, and obtain each status by a
    /// dense Schur/Woodbury update (the *Delassus* operator) — no sparse
    /// refactorization per status change. Falls back automatically to
    /// [`Refactorize`](Self::Refactorize) when `A` is singular (a structure that
    /// does not hold without contact, e.g. a body merely resting on a support).
    #[default]
    SchurComplement,
    /// Refactorize the full sparse saddle-point at each status change. The
    /// original method: robust to a singular base, but pays one sparse
    /// factorization per iteration.
    Refactorize,
}

impl crate::named::Named for ActiveSetMethod {
    const LABEL: &'static str = "active-set method";
    const VALUES: &'static [Self] = &[
        ActiveSetMethod::SchurComplement,
        ActiveSetMethod::Refactorize,
    ];

    fn name(self) -> &'static str {
        match self {
            ActiveSetMethod::SchurComplement => "schur",
            ActiveSetMethod::Refactorize => "refactorize",
        }
    }
}

/// One inequality relation, resolved against the numbering of the system the
/// loop runs on — the assembled saddle-point, or the system an elimination
/// reduced it to.
pub(super) struct Inequality {
    /// Row index of the relation.
    pub(super) row: usize,
    /// Column index of its multiplier.
    pub(super) lambda_col: usize,
    /// `(column, coefficient)` of every term — evaluates the gap `C·u − g`.
    pub(super) term_cols: Vec<(usize, f64)>,
    /// `GreaterEqual` or `LessEqual` (equalities are not collected).
    pub(super) sense: RelationSense,
    /// The factors the system scaled this relation by (see
    /// [`super::scaling`]): its multiplier column's and its row's, `1` when the
    /// system is unscaled. The sign tests read them to keep their tolerance in
    /// the original units — a reaction in newtons, a gap in metres.
    pub(super) lambda_scale: f64,
    pub(super) row_scale: f64,
    /// The pivot that stands for the relation's row while it is released,
    /// `d·λ = 0`: the size of the relation's own (scaled) coefficients, so that
    /// `λ = 0` is solved as accurately as the rest. A `1` next to coefficients
    /// of `10¹²` leaves `λ` at the round-off of the solve, and that round-off,
    /// times `Cᵀ`, pushes the structure.
    pub(super) release_pivot: f64,
}

/// The release pivot of a relation of coefficients `term_cols`: their largest
/// magnitude, `1` for a relation with none.
pub(super) fn release_pivot(term_cols: &[(usize, f64)]) -> f64 {
    let largest = term_cols.iter().fold(0.0_f64, |m, &(_, a)| m.max(a.abs()));
    if largest > 0.0 {
        largest
    } else {
        1.0
    }
}

/// Report `λ = 0` exactly for every released relation of `status`: its row
/// solved `d·λ = 0` to round-off only.
fn zero_released(inequalities: &[Inequality], status: &[bool], x: &mut [f64]) {
    for (ineq, &active) in inequalities.iter().zip(status) {
        if !active {
            x[ineq.lambda_col] = 0.0;
        }
    }
}

/// The Schur/Delassus artifacts cached across solves (matrix-invariant): the LU
/// of the inequality-free base `A` and, built lazily, the columns
/// `xᵣ = A⁻¹·e_row(r)` needed to update `A` for each active relation.
struct SchurCache {
    /// LU of the base `A` (all unilateral relations released).
    base: Arc<SparseLu>,
    /// `xᵣ = A⁻¹·e_row(r)`, keyed by the inequality's constraint-row index;
    /// filled on first use of relation `r` and reused by later solves.
    columns: HashMap<usize, Arc<Vec<f64>>>,
    /// Last converged status, reused as the Schur path's warm start.
    warm: Option<Vec<bool>>,
}

/// The Schur base's lifecycle on a given matrix: not yet attempted, established
/// singular (⇒ the Schur path permanently falls back), or ready with its cache.
enum SchurSlot {
    Untried,
    Singular,
    Ready(SchurCache),
}

/// The active-set loop over one system: its inequalities and, per method, the
/// warm start and the cached factors. Kept with whatever is cached on the
/// matrix — the Lagrange state below, or the elimination's condensation — so
/// that a re-solve warm-starts.
pub(super) struct ActiveSet {
    /// The resolved inequality relations, in row order (deterministic).
    inequalities: Vec<Inequality>,
    /// [`Refactorize`](ActiveSetMethod::Refactorize) warm start: last converged
    /// status (`true` = active, one per inequality) and the LU of its system.
    last: Mutex<Option<(Vec<bool>, Arc<SparseLu>)>>,
    /// [`SchurComplement`](ActiveSetMethod::SchurComplement) base + columns cache.
    schur: Mutex<SchurSlot>,
}

impl ActiveSet {
    /// The loop over `inequalities`, nothing cached yet.
    pub(super) fn new(inequalities: Vec<Inequality>) -> Self {
        Self {
            inequalities,
            last: Mutex::new(None),
            schur: Mutex::new(SchurSlot::Untried),
        }
    }

    /// Run the loop on the system `csc` with the right-hand side `b_full` (the
    /// imposed values at the relation rows): the solution, in the system's
    /// column numbering, inactive relations reporting a zero multiplier.
    pub(super) fn run(
        &self,
        csc: &nalgebra_sparse::CscMatrix<f64>,
        b_full: &[f64],
        options: &SolveOptions,
        cancel: &dyn Cancel,
    ) -> Result<Vec<f64>> {
        // The Schur path reuses one base factorization; it falls back to the
        // refactorizing path (Ok(None)) when the base is singular.
        if options.active_set == ActiveSetMethod::SchurComplement
            && let Some(x) = solve_schur(self, csc, b_full, options, cancel)?
        {
            return Ok(x);
        }
        solve_refactorize(self, csc, b_full, options, cancel)
    }
}

/// The active-set state of the Lagrange path, cached transparently on the
/// [`Matrix`] (cleared on any matrix mutation): the row layout the right-hand
/// side is gathered on, and the loop.
struct ActiveSetState {
    /// The matrix row layout (gathers the rhs; the solution is wrapped by
    /// [`Matrix::field_from_col_values`], which reads the column layout from
    /// the assembled matrix itself).
    row_dofs: Vec<NamedDof>,
    /// The loop over the matrix's inequality relations — their coefficients
    /// already scaled when `scaling` is set.
    set: ActiveSet,
    /// The relations brought to the structure's scale (see
    /// [`super::scaling`]); `None` when nothing is scaled.
    scaling: Option<RelationScaling>,
}

/// The active-set path of [`super::solve`], for a matrix that carries
/// inequality relations.
pub(super) fn solve(
    matrix: &Matrix,
    rhs: &NodeField,
    options: &SolveOptions,
    cancel: &dyn Cancel,
) -> Result<NodeField> {
    // `options.method` does not apply here: the system of a status is never
    // symmetric — see `factorize_status`.
    cancel.check()?;

    // ── Step 1 — obtain the active-set state (cached or fresh) ─────────
    let state: Arc<ActiveSetState> = if options.cache {
        match matrix.cached_factorization::<ActiveSetState>() {
            Some(s) => s,
            None => {
                let s = Arc::new(build_state(matrix)?);
                matrix.store_factorization(s.clone());
                s
            }
        }
    } else {
        Arc::new(build_state(matrix)?)
    };

    // A block declared a sense on rows it does not hold: nothing to decide.
    if state.set.inequalities.is_empty() {
        return lu::solve(matrix, rhs, options, cancel);
    }
    cancel.check()?;

    // ── Step 2 — full rhs (g at the constraint rows) + base CSC, both at
    //    the structure's scale when the relations are scaled ────────────
    let mut b_full = rhs.gather(&state.row_dofs)?;
    let mut csc = matrix.to_csc()?;
    if let Some(scale) = &state.scaling {
        let (col_offsets, row_indices, values) = csc.csc_data_mut();
        scale.scale_csc(col_offsets, row_indices, values);
        scale.scale_rhs(&mut b_full);
    }

    // ── Step 3 — the loop; the solution wrapped on the blocks' own column
    //    supports (`x` is in the assembled column order) ────────────────
    let mut x = state.set.run(&csc, &b_full, options, cancel)?;
    if let Some(scale) = &state.scaling {
        scale.unscale_solution(&mut x);
    }
    matrix.field_from_col_values(&x)
}

/// The KKT sign test on one status's solution `x`: release every active relation
/// whose multiplier `λ` would make its reaction `−λ` pull, activate every
/// inactive one whose gap penetrates.
/// Returns whether the status changed. Shared by both active-set methods.
fn update_status(
    inequalities: &[Inequality],
    status: &mut [bool],
    x: &[f64],
    b_full: &[f64],
    tol: f64,
) -> bool {
    let mut changed = false;
    for (ineq, active) in inequalities.iter().zip(status.iter_mut()) {
        if *active {
            // Active: the reaction −λ must not pull. λ = −μ (see module doc). On a
            // scaled system `x` holds λ / lambda_scale: the tolerance follows.
            let lambda = x[ineq.lambda_col];
            let tol_lambda = tol / ineq.lambda_scale;
            let release = match ineq.sense {
                RelationSense::GreaterEqual => lambda > tol_lambda,
                RelationSense::LessEqual => lambda < -tol_lambda,
                RelationSense::Equality => unreachable!("equalities are not collected"),
            };
            if release {
                *active = false;
                changed = true;
            }
        } else {
            // Inactive: the gap C·u − g must stay on the feasible side.
            // On a scaled system the row, hence the gap, carries row_scale.
            let cu: f64 = ineq.term_cols.iter().map(|&(c, a)| a * x[c]).sum();
            let gap = cu - b_full[ineq.row];
            let tol_gap = tol * ineq.row_scale;
            let violated = match ineq.sense {
                RelationSense::GreaterEqual => gap < -tol_gap,
                RelationSense::LessEqual => gap > tol_gap,
                RelationSense::Equality => unreachable!("equalities are not collected"),
            };
            if violated {
                *active = true;
                changed = true;
            }
        }
    }
    changed
}

/// The original method: refactorize the full sparse saddle-point at each status
/// change, warm-started from the cached converged status + its LU.
fn solve_refactorize(
    state: &ActiveSet,
    csc: &nalgebra_sparse::CscMatrix<f64>,
    b_full: &[f64],
    options: &SolveOptions,
    cancel: &dyn Cancel,
) -> Result<Vec<f64>> {
    // Initial status: warm start (status + its factorization) or all-active.
    let (mut status, mut lu_current): (Vec<bool>, Option<Arc<SparseLu>>) =
        match state.last.lock().as_ref() {
            Some((s, f)) => (s.clone(), Some(f.clone())),
            None => (vec![true; state.inequalities.len()], None),
        };

    let n = csc.nrows();
    for _iter in 0..options.max_iter {
        cancel.check()?;

        // Factorize the current status's system (reused when warm-started).
        let lu = match lu_current.take() {
            Some(f) => f,
            None => Arc::new(factorize_status(csc, &state.inequalities, &status)?),
        };

        // Solve with g zeroed at the inactive constraint rows (λ_r = 0).
        let mut b = b_full.to_vec();
        for (ineq, &active) in state.inequalities.iter().zip(&status) {
            if !active {
                b[ineq.row] = 0.0;
            }
        }
        let mut x = lu_solve_vec(&lu, &b);
        if x.iter().any(|v| !v.is_finite()) {
            return Err(PyrucastError::Message(
                "solve: LU failed (matrix is singular — check that the \
                 structure is supported when every unilateral relation releases)"
                    .into(),
            ));
        }
        cancel.check()?;

        if !update_status(&state.inequalities, &mut status, &x, b_full, options.tol) {
            zero_released(&state.inequalities, &status, &mut x);
            // Converged: remember the status + factors for the next warm start.
            if options.cache {
                *state.last.lock() = Some((status, lu));
            }
            debug_assert_eq!(x.len(), n);
            return Ok(x);
        }
    }

    Err(PyrucastError::Message(format!(
        "solve: the active set did not converge in {} iterations \
         (cycling — try a looser tol, or check the model)",
        options.max_iter
    )))
}

/// The Schur/Delassus method: factorize the inequality-free base `A` once, then
/// obtain each status by a dense Woodbury update, reusing `A`'s factors and the
/// cached columns `A⁻¹·e_row(r)`.
///
/// Returns `Ok(None)` (asking the caller to fall back to
/// [`solve_refactorize`]) when the base is singular or any base solve goes
/// non-finite; `Ok(Some(x))` on a converged solution.
fn solve_schur(
    state: &ActiveSet,
    csc: &nalgebra_sparse::CscMatrix<f64>,
    b_full: &[f64],
    options: &SolveOptions,
    cancel: &dyn Cancel,
) -> Result<Option<Vec<f64>>> {
    let n = csc.nrows();

    // ── Base `A` (all relations released), factorized once and cached ──
    let mut slot = state.schur.lock();
    match &*slot {
        SchurSlot::Singular => return Ok(None),
        SchurSlot::Ready(_) => {}
        SchurSlot::Untried => {
            let all_inactive = vec![false; state.inequalities.len()];
            // A singular base is a legitimate outcome (the structure needs
            // contact to hold): mark it and let the caller refactorize. faer's
            // pivoted LU may factor a singular matrix into *finite* garbage
            // without erroring, so a round-trip solve confirms non-singularity.
            match factorize_status(csc, &state.inequalities, &all_inactive) {
                Ok(base) if base_is_nonsingular(&base, csc, &state.inequalities, n) => {
                    *slot = SchurSlot::Ready(SchurCache {
                        base: Arc::new(base),
                        columns: HashMap::new(),
                        warm: None,
                    });
                }
                _ => {
                    *slot = SchurSlot::Singular;
                    return Ok(None);
                }
            }
        }
    }
    let cache = match &mut *slot {
        SchurSlot::Ready(c) => c,
        _ => unreachable!("base just established Ready"),
    };
    let base = cache.base.clone();

    // Warm start from the last converged status (else all-active).
    let mut status = cache
        .warm
        .clone()
        .unwrap_or_else(|| vec![true; state.inequalities.len()]);

    for _iter in 0..options.max_iter {
        cancel.check()?;

        let Some(mut x) = schur_status_solve(
            &base,
            &mut cache.columns,
            &state.inequalities,
            &status,
            b_full,
            n,
        ) else {
            // A non-finite base/Woodbury solve ⇒ fall back to refactorization.
            return Ok(None);
        };
        cancel.check()?;

        if !update_status(&state.inequalities, &mut status, &x, b_full, options.tol) {
            zero_released(&state.inequalities, &status, &mut x);
            if options.cache {
                cache.warm = Some(status);
            }
            return Ok(Some(x));
        }
    }

    Err(PyrucastError::Message(format!(
        "solve: the active set did not converge in {} iterations \
         (cycling — try a looser tol, or check the model)",
        options.max_iter
    )))
}

/// `A·x`, where `A` is the released base: the assembled matrix `csc` with every
/// inequality row replaced by its release pivot on its multiplier column
/// (`dᵣ·λᵣ = 0`).
fn base_matvec(
    csc: &nalgebra_sparse::CscMatrix<f64>,
    inequalities: &[Inequality],
    x: &[f64],
) -> Vec<f64> {
    let mut y = vec![0.0; csc.nrows()];
    let col_offsets = csc.col_offsets();
    let row_indices = csc.row_indices();
    let values = csc.values();
    for col in 0..csc.ncols() {
        let xc = x[col];
        if xc != 0.0 {
            for k in col_offsets[col]..col_offsets[col + 1] {
                y[row_indices[k]] += values[k] * xc;
            }
        }
    }
    // The base row of every inequality is its release pivot at its λ column.
    for ineq in inequalities {
        y[ineq.row] = ineq.release_pivot * x[ineq.lambda_col];
    }
    y
}

/// Whether the released base `A` is non-singular, by a round-trip solve:
/// `A⁻¹·(A·1)` must recover `1`. A rigid mode (the structure floats without
/// contact) makes `A` singular; faer then returns a solution off by a large
/// multiple of the null vector, which this catches (finite garbage included).
fn base_is_nonsingular(
    base: &SparseLu,
    csc: &nalgebra_sparse::CscMatrix<f64>,
    inequalities: &[Inequality],
    n: usize,
) -> bool {
    let ones = vec![1.0; n];
    let b = base_matvec(csc, inequalities, &ones);
    let y = lu_solve_vec(base, &b);
    y.iter().all(|v| v.is_finite()) && y.iter().all(|&v| (v - 1.0).abs() < 1e-6)
}

/// The cached Schur column `xᵣ = A⁻¹·e_row(r)`, computed on first use.
fn schur_column(
    base: &SparseLu,
    columns: &mut HashMap<usize, Arc<Vec<f64>>>,
    row: usize,
    n: usize,
) -> Arc<Vec<f64>> {
    if let Some(x) = columns.get(&row) {
        return x.clone();
    }
    let mut e = vec![0.0; n];
    e[row] = 1.0;
    let x = Arc::new(lu_solve_vec(base, &e));
    columns.insert(row, x.clone());
    x
}

/// Solve one status's saddle-point system by the Woodbury identity around the
/// released base `A`. In `A` a released relation carries the row
/// `dᵣ·λᵣ = 0` (its release pivot at its multiplier column `λcol`); activating
/// it restores the
/// real constraint row `Cᵣ`. That is a rank-`k` row update
/// `A + Σ e_row(r)·(Cᵣ − e_λcol(r))ᵀ`, so
///
/// ```text
/// x = A⁻¹·b − X·(I + Vᵀ X)⁻¹·(Vᵀ A⁻¹ b)
/// ```
///
/// with `X = [A⁻¹·e_row(r)]` (cached columns) and `Vᵣ = Cᵣ − dᵣ·e_λcol(r)` (so
/// `Vᵣᵀ v = Cᵣ·v − dᵣ·v[λcol]`). The `k×k` system (`I + Vᵀ X` — the active
/// Delassus operator) is dense.
///
/// Returns `None` when a solve is non-finite (⇒ the caller falls back).
fn schur_status_solve(
    base: &SparseLu,
    columns: &mut HashMap<usize, Arc<Vec<f64>>>,
    inequalities: &[Inequality],
    status: &[bool],
    b_full: &[f64],
    n: usize,
) -> Option<Vec<f64>> {
    // b with g zeroed at the inactive constraint rows (λ_r = 0).
    let mut b = b_full.to_vec();
    for (ineq, &active) in inequalities.iter().zip(status) {
        if !active {
            b[ineq.row] = 0.0;
        }
    }
    let y0 = lu_solve_vec(base, &b);
    if y0.iter().any(|v| !v.is_finite()) {
        return None;
    }

    let active: Vec<usize> = (0..inequalities.len()).filter(|&i| status[i]).collect();
    let k = active.len();
    if k == 0 {
        return Some(y0);
    }

    // Cache the columns of the active relations.
    let xs: Vec<Arc<Vec<f64>>> = active
        .iter()
        .map(|&i| schur_column(base, columns, inequalities[i].row, n))
        .collect();
    if xs.iter().any(|x| x.iter().any(|v| !v.is_finite())) {
        return None;
    }

    // Dense G = I + Vᵀ X and small rhs = Vᵀ y0, with Vᵢ = Cᵢ − dᵢ·e_λcol(i).
    let mut g = DMatrix::<f64>::zeros(k, k);
    let mut rhs_small = DVector::<f64>::zeros(k);
    for (i, &ai) in active.iter().enumerate() {
        let ineq_i = &inequalities[ai];
        let d_i = ineq_i.release_pivot;
        // Vᵢᵀ v = Cᵢ·v − dᵢ·v[λcolᵢ] (the pivot the base carries at λcolᵢ).
        let ci_y0: f64 = ineq_i.term_cols.iter().map(|&(c, a)| a * y0[c]).sum();
        rhs_small[i] = ci_y0 - d_i * y0[ineq_i.lambda_col];
        for (j, xj) in xs.iter().enumerate() {
            let ci_xj: f64 = ineq_i.term_cols.iter().map(|&(c, a)| a * xj[c]).sum();
            let mut v = ci_xj - d_i * xj[ineq_i.lambda_col];
            if i == j {
                v += 1.0;
            }
            g[(i, j)] = v;
        }
    }

    let d = g.lu().solve(&rhs_small)?;
    if d.iter().any(|v| !v.is_finite()) {
        return None;
    }

    // x = y0 − Σⱼ dⱼ·xⱼ.
    let mut x = y0;
    for (j, xj) in xs.iter().enumerate() {
        let dj = d[j];
        for (xi, &xij) in x.iter_mut().zip(xj.iter()) {
            *xi -= dj * xij;
        }
    }
    Some(x)
}

/// The inequality relations of the matrix, resolved against its DOF layout.
/// Equality relations are skipped (their rows are always enforced as-is).
fn build_state(matrix: &Matrix) -> Result<ActiveSetState> {
    let row_dofs = matrix.row_dofs()?;
    let n_cols = matrix.col_dof_keys()?.len();
    if row_dofs.len() != n_cols {
        return Err(PyrucastError::Message(format!(
            "solve: matrix must be square; got {}×{}",
            row_dofs.len(),
            n_cols
        )));
    }
    let vars = matrix.dof_vars();
    let (row_keys, col_keys) = matrix.dof_key_orders()?;
    let (offsets, cols, vals) = matrix.csr_arrays()?;
    let scaling = RelationScaling::of(&vars, &row_keys, &col_keys, offsets, cols, vals);
    // The coefficients of a relation follow the system they are read against:
    // scaled with it, each test keeping its two factors.
    let row_of = |r: usize| scaling.as_ref().map_or(1.0, |s| s.row(r));
    let col_of = |c: usize| scaling.as_ref().map_or(1.0, |s| s.col(c));
    let inequalities = relation_rows(matrix)?
        .into_iter()
        .filter(|r| r.sense != RelationSense::Equality)
        .map(|r| {
            let row_scale = row_of(r.row);
            let term_cols: Vec<(usize, f64)> = r
                .terms
                .into_iter()
                .map(|(c, a)| (c, row_scale * a * col_of(c)))
                .collect();
            Inequality {
                row: r.row,
                lambda_col: r.lambda_col,
                release_pivot: release_pivot(&term_cols),
                term_cols,
                sense: r.sense,
                lambda_scale: col_of(r.lambda_col),
                row_scale,
            }
        })
        .collect();
    Ok(ActiveSetState {
        row_dofs,
        set: ActiveSet::new(inequalities),
        scaling,
    })
}

/// Test-only counter of sparse saddle-point factorizations, used to assert that
/// the Schur path factorizes the base **once** where the refactorizing path pays
/// one per status iteration.
#[cfg(test)]
pub(crate) static FACTORIZE_CALLS: std::sync::atomic::AtomicUsize =
    std::sync::atomic::AtomicUsize::new(0);

/// Factorize the system of one status: the base saddle-point with, for every
/// **inactive** inequality, its constraint row replaced by its release pivot on
/// the multiplier DOF (`d_r·λ_r = 0`). The `Cᵀ` column needs no clearing —
/// `λ_r = 0` zeroes its contribution, and the pivot `d_r`, of the size of the
/// column, keeps the solve from leaving round-off there.
fn factorize_status(
    csc: &nalgebra_sparse::CscMatrix<f64>,
    inequalities: &[Inequality],
    status: &[bool],
) -> Result<SparseLu> {
    #[cfg(test)]
    FACTORIZE_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let n = csc.nrows();
    // Rows to blank: the constraint rows of the inactive inequalities — and,
    // for each, the release pivot that replaces that row.
    let mut blanked = vec![false; n];
    let mut inserted: Vec<(usize, usize, f64)> = Vec::new();
    for (ineq, &active) in inequalities.iter().zip(status) {
        if !active {
            blanked[ineq.row] = true;
            inserted.push((ineq.lambda_col, ineq.row, ineq.release_pivot));
        }
    }
    // By column then row: each column then meets its own in the order a CSC
    // column wants them.
    inserted.sort_unstable_by_key(|&(col, row, _)| (col, row));

    let col_offsets = csc.col_offsets();
    let row_indices = csc.row_indices();
    let values = csc.values();

    // The modified system is written **straight into CSC arrays**, rather than
    // unfolded into triplets for faer to sort back into columns. The survivors
    // of a column come out of the base CSC already sorted, and the entries put
    // back are sorted above, so the two merge in one pass — there is nothing
    // left for a sort to do. This runs once per active-set status, so what it
    // saves, it saves as many times.
    let mut col_ptr = vec![0usize; n + 1];
    for col in 0..n {
        col_ptr[col + 1] = (col_offsets[col]..col_offsets[col + 1])
            .filter(|&k| !blanked[row_indices[k]])
            .count();
    }
    for &(col, _, _) in &inserted {
        col_ptr[col + 1] += 1;
    }
    for col in 0..n {
        col_ptr[col + 1] += col_ptr[col];
    }

    let mut row_idx = vec![0usize; col_ptr[n]];
    let mut vals = vec![0.0f64; col_ptr[n]];
    let (mut w, mut seen) = (0usize, 0usize);
    for col in 0..n {
        // This column's inserted rows: a contiguous run of `inserted`.
        let start = seen;
        while seen < inserted.len() && inserted[seen].0 == col {
            seen += 1;
        }
        let mut ins = start;
        for k in col_offsets[col]..col_offsets[col + 1] {
            let row = row_indices[k];
            if blanked[row] {
                continue;
            }
            // A blanked row is gone from *every* column, so an inserted entry
            // can never collide with a survivor — only precede it.
            while ins < seen && inserted[ins].1 < row {
                row_idx[w] = inserted[ins].1;
                vals[w] = inserted[ins].2;
                w += 1;
                ins += 1;
            }
            row_idx[w] = row;
            vals[w] = values[k];
            w += 1;
        }
        while ins < seen {
            row_idx[w] = inserted[ins].1;
            vals[w] = inserted[ins].2;
            w += 1;
            ins += 1;
        }
    }
    factorize_csc_arrays(n, &col_ptr, &row_idx, &vals)
}

// ─── Unit tests ────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::aggregate::Aggregate;
    use crate::atoms::{ElementType, Node};
    use crate::containers::element_field::{ElementField, SubElementField};
    use crate::containers::field::SubField;
    use crate::containers::finite_element_space::FiniteElementSpace;
    use crate::containers::matrix::Matrix;
    use crate::containers::mesh::{Mesh, SubMesh};
    use crate::containers::model::{Model, SubModel};
    use crate::containers::node_field::SubNodeField;
    use crate::coords::Coords;
    use crate::handle::Handle;
    use crate::models::symmetry::MaterialSymmetry;
    use crate::ops::matrix::stiffness;

    use std::sync::atomic::Ordering;

    /// A 2-element heat bar on `[0, 1]` (`k = 1`) with `T(0) = 0` (equality) and
    /// **two loose lower bounds** `T(x₁) ≥ −10`, `T(x₂) ≥ −20`, driven by a
    /// positive flux `q` at the right end. The unconstrained solution `T = q·x`
    /// is positive, so **both bounds release** — a two-status-iteration problem
    /// starting from the all-active warm start.
    fn two_loose_bounds(q: f64) -> (Matrix, NodeField, Vec<Node>) {
        let coords = Handle::new(Coords::new(1).unwrap());
        let nodes: Vec<Node> = (0..=2)
            .map(|i| Node::create_in(coords.clone(), &[i as f64 * 0.5]).unwrap())
            .collect();
        let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
        mesh.add_cell(&[nodes[0].id(), nodes[1].id()]).unwrap();
        mesh.add_cell(&[nodes[1].id(), nodes[2].id()]).unwrap();
        let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
        let sub = fes.get(0).unwrap();

        let mut mat = SubElementField::new(sub.clone(), vec!["k".into()]).unwrap();
        mat.set_uniform("k", 1.0).unwrap();
        let mut materials = ElementField::empty();
        materials.add_sub(Handle::new(mat)).unwrap();

        let mut model = Model::empty();
        model
            .add_sub(Handle::new(
                SubModel::heat_conduction(sub, MaterialSymmetry::Isotropic).unwrap(),
            ))
            .unwrap();

        let poi1 = |n: &Node| {
            Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(n)).unwrap())
        };

        // Equality T(0) = 0.
        let imp0 = poi1(&nodes[0]);
        let dir = SubModel::dirichlet(&imp0, &model, "T", Default::default()).unwrap();
        let dir_mult = dir.multiplier_nodes()[0];
        model.add_sub(Handle::new(dir)).unwrap();

        // Two loose lower bounds at nodes 1 and 2.
        let mut bound_mults = Vec::new();
        for node in [&nodes[1], &nodes[2]] {
            let imp = poi1(node);
            let b = SubModel::dirichlet(&imp, &model, "T", RelationSense::GreaterEqual).unwrap();
            bound_mults.push(b.multiplier_nodes()[0]);
            model.add_sub(Handle::new(b)).unwrap();
        }

        // rhs: flux q at the right node, imposed values at every multiplier slot.
        let mut rhs_sm = SubMesh::new(coords, ElementType::POI1);
        rhs_sm.add_cell(&[nodes[2].id()]).unwrap();
        rhs_sm.add_cell(&[dir_mult]).unwrap();
        rhs_sm.add_cell(&[bound_mults[0]]).unwrap();
        rhs_sm.add_cell(&[bound_mults[1]]).unwrap();
        let rhs_sm = Handle::new(rhs_sm);
        let mut rhs = SubNodeField::from_poi1(&rhs_sm, vec!["q".into(), "imposed".into()]).unwrap();
        rhs.set_value(nodes[2].id(), "q", q).unwrap();
        rhs.set_value(dir_mult, "imposed", 0.0).unwrap();
        rhs.set_value(bound_mults[0], "imposed", -10.0).unwrap();
        rhs.set_value(bound_mults[1], "imposed", -20.0).unwrap();
        let rhs = NodeField::from_sub(rhs);

        let k = stiffness(&model, &materials).unwrap();
        (k, rhs, nodes)
    }

    fn opts(active_set: ActiveSetMethod) -> SolveOptions {
        SolveOptions {
            active_set,
            ..Default::default()
        }
    }

    /// Serialize the tests that read the process-global [`FACTORIZE_CALLS`]
    /// counter (the default test harness runs them on parallel threads).
    static COUNT_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// The Schur path factorizes the base **once**, where the refactorizing path
    /// pays one sparse factorization per status iteration (here two: all-active,
    /// then all-inactive). Both reach the same solution.
    #[test]
    fn schur_factorizes_the_base_once() {
        let _guard = COUNT_LOCK.lock().unwrap();
        // Refactorize: fresh matrix, count the factorizations (all-active +
        // all-inactive = 2).
        let (k_ref, rhs, nodes) = two_loose_bounds(5.0);
        FACTORIZE_CALLS.store(0, Ordering::Relaxed);
        let sol_ref = crate::ops::solver::solve_with_options(
            &k_ref,
            &rhs,
            &opts(ActiveSetMethod::Refactorize),
        )
        .unwrap();
        let n_ref = FACTORIZE_CALLS.load(Ordering::Relaxed);
        assert!(
            n_ref >= 2,
            "refactorize pays one factorization per iteration, got {n_ref}"
        );

        // Schur: fresh matrix, only the base is factorized (1 call).
        let (k_schur, rhs_s, _n2) = two_loose_bounds(5.0);
        FACTORIZE_CALLS.store(0, Ordering::Relaxed);
        let sol_schur = crate::ops::solver::solve_with_options(
            &k_schur,
            &rhs_s,
            &opts(ActiveSetMethod::SchurComplement),
        )
        .unwrap();
        let n_schur = FACTORIZE_CALLS.load(Ordering::Relaxed);
        assert_eq!(n_schur, 1, "schur factorizes only the inequality-free base");

        // Both agree with the analytical T = 5·x (both bounds released).
        for (i, node) in nodes.iter().enumerate() {
            let expected = 5.0 * i as f64 * 0.5;
            let a = sol_ref.value(node.id(), "T").unwrap();
            let b = sol_schur.value(node.id(), "T").unwrap();
            assert!((a - expected).abs() < 1e-10);
            assert!((a - b).abs() < 1e-12, "schur and refactorize must agree");
        }
    }

    /// A re-solve on the same matrix reuses the cached base — **zero**
    /// factorization the second time — and warm-starts to the same solution.
    #[test]
    fn schur_resolve_reuses_the_cached_base() {
        let _guard = COUNT_LOCK.lock().unwrap();
        let (k, rhs, nodes) = two_loose_bounds(5.0);
        FACTORIZE_CALLS.store(0, Ordering::Relaxed);
        let first = crate::ops::solver::solve_with_options(
            &k,
            &rhs,
            &opts(ActiveSetMethod::SchurComplement),
        )
        .unwrap();
        assert_eq!(FACTORIZE_CALLS.load(Ordering::Relaxed), 1);

        // Second solve: base cached on the matrix, nothing refactorized.
        let again = crate::ops::solver::solve_with_options(
            &k,
            &rhs,
            &opts(ActiveSetMethod::SchurComplement),
        )
        .unwrap();
        assert_eq!(
            FACTORIZE_CALLS.load(Ordering::Relaxed),
            1,
            "the cached base must be reused (no new factorization)"
        );
        for node in &nodes {
            assert_eq!(
                first.value(node.id(), "T").unwrap(),
                again.value(node.id(), "T").unwrap()
            );
        }
    }
}