Skip to main content

section_properties/
frame.rs

1//! 2D frame façade over the verified Beam FEM core (Phase 13).
2//!
3//! This module adds **no mechanics**. Every element stiffness, coordinate
4//! transformation, load vector, static-condensation step, end-force recovery
5//! and solver call is delegated to [`BeamModel`] / [`BeamSolver`]. What it adds
6//! is a frame-shaped surface:
7//!
8//! * typed [`NodeHandle`] / [`MemberHandle`] addressing instead of positional
9//!   indices;
10//! * connectivity validation (orphan nodes, disconnected components, duplicate
11//!   and zero-length members) with *targeted* diagnostics that replace the
12//!   opaque "singular matrix" error;
13//! * a support vocabulary ([`FrameModel::fix`], [`FrameModel::pin`],
14//!   [`FrameModel::roller_y`], [`FrameModel::roller_x`],
15//!   [`FrameModel::restrain`]);
16//! * frame-level result access and a global equilibrium report.
17//!
18//! # Conventions (frozen - identical to `docs/beam_fem.md`)
19//!
20//! ```text
21//! DOFs              [ux, uy, rz] per node (global), rz counter-clockwise positive
22//! nodal loads       GLOBAL   (add via FrameModel::nodal_load / nodal_moment)
23//! member loads      LOCAL    (add via FrameModel::member_udl / member_point_load)
24//! member end forces f_end = f_equiv - K_e u_e   (element-on-node, LOCAL axes)
25//! reactions         R = K_original u - f_global (global)
26//! constraints       static condensation K_ff u_f = f_f - K_fc u_c (no penalties)
27//! ```
28//!
29//! A member point load at `xi = 0` or `xi = 1` acts at a node and is **not**
30//! double counted.
31//!
32//! # Current limitations (documented, not defects)
33//!
34//! * Parallel members between the same node pair are **not** supported: the
35//!   second one is rejected as a duplicate. Rigid offsets / releases are not
36//!   modelled.
37//! * A single connected structural system is required; multiple independent
38//!   substructures are rejected as disconnected.
39//! * Member loads are uniform (single `(qx, qy)` per member per call; repeated
40//!   calls accumulate, matching the core behaviour).
41//!
42//! # Example
43//!
44//! ```rust
45//! use section_properties::frame::FrameModel;
46//! use section_properties::{BeamSection, Dof, Material};
47//!
48//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
49//! let mut frame = FrameModel::new();
50//! let base = frame.add_node(0.0, 0.0)?;
51//! let tip = frame.add_node(2.0, 0.0)?;
52//! frame.add_member(base, tip, Material::new(200e9, 0.3, 7850.0, "Steel"),
53//!                   BeamSection::new(5e-3, 2e-5))?;
54//! frame.fix(base)?;
55//! frame.nodal_load(tip, 0.0, -1.0e4)?;
56//!
57//! let result = frame.solve()?;
58//! // v = -P L^3 / 3EI
59//! let uy = result.displacement(tip, Dof::Uy)?;
60//! assert!((uy + 1.0e4 * 2.0f64.powi(3) / (3.0 * 200e9 * 2e-5)).abs() < 1e-12);
61//! assert!(result.equilibrium().is_balanced());
62//! # Ok(())
63//! # }
64//! ```
65
66use crate::SolverSelection;
67use crate::beam_fem::{
68    BeamElement, BeamModel, BeamNode, BeamSection, BeamSolver, Dof, FemError, ReducedSystem,
69};
70use crate::fea::mechanism::diagnose_reduced;
71use crate::material::Material;
72
73use std::collections::VecDeque;
74
75pub use crate::fea::mechanism::StructuralDiagnostic;
76
77// ---------------------------------------------------------------------------
78// Handles
79// ---------------------------------------------------------------------------
80
81/// Handle to a node of a [`FrameModel`].
82///
83/// Handles are produced by [`FrameModel::add_node`] and are only valid for the
84/// model that created them. They are deliberately distinct from raw DOF
85/// indices so a node reference cannot be confused with a degree of freedom.
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
87pub struct NodeHandle(usize);
88
89impl NodeHandle {
90    /// The zero-based index of the node inside the model.
91    pub fn index(self) -> usize {
92        self.0
93    }
94
95    /// Build a handle from a raw index.
96    ///
97    /// The handle is **not** validated here; validity is checked when it is
98    /// used against a model (returning [`FemError::InvalidNode`]). Prefer
99    /// [`FrameModel::add_node`] in normal use.
100    pub fn from_index(index: usize) -> Self {
101        Self(index)
102    }
103}
104
105/// Handle to a member (two-node frame element) of a [`FrameModel`].
106///
107/// Produced by [`FrameModel::add_member`].
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
109pub struct MemberHandle(usize);
110
111impl MemberHandle {
112    /// The zero-based index of the member inside the model.
113    pub fn index(self) -> usize {
114        self.0
115    }
116
117    /// Build a handle from a raw index.
118    ///
119    /// The handle is **not** validated here; validity is checked when it is
120    /// used against a model (returning [`FemError::InvalidMember`]). Prefer
121    /// [`FrameModel::add_member`] in normal use.
122    pub fn from_index(index: usize) -> Self {
123        Self(index)
124    }
125}
126
127// ---------------------------------------------------------------------------
128// Equilibrium report
129// ---------------------------------------------------------------------------
130
131/// Relative equilibrium tolerance: residuals are compared against the analysed
132/// system's **own** force and moment magnitudes, never against an absolute
133/// floor, so the verdict is invariant under a change of units (N/m ↔ kN/mm).
134const EQUILIBRIUM_REL_TOL: f64 = 1e-6;
135
136/// Conditioning-relief coefficient for [`EquilibriumReport::is_balanced`].
137///
138/// A Euler–Bernoulli frame's stiffness matrix is ill-conditioned when its
139/// transverse/axial stiffness ratio grows: for an element the dominant
140/// conditioning driver is `A·L²/I = (L/r)²`, the square of the slenderness
141/// ratio `L/r` (with `r² = I/A` the radius of gyration). The forward error of a
142/// direct solve is `O((L/r)² · ε)`, so equilibrium residuals — which inherit
143/// that error through the recovered reactions — can legitimately reach the same
144/// relative magnitude at large slenderness. A fixed `EQUILIBRIUM_REL_TOL` would
145/// then flag a physically balanced frame as unbalanced (catastrophic
146/// cancellation of large opposing reactions).
147///
148/// `effective_rel_tol = max(EQUILIBRIUM_REL_TOL, C · λ²_max · ε)` recovers the
149/// correct verdict: `λ²_max = max_elements(L²·A/I)` is a **dimensionless** and
150/// **unit-invariant** element-level slenderness/conditioning proxy (a consistent
151/// change of the length/area/inertia units multiplies numerator and denominator
152/// by the same power, leaving the ratio unchanged), so the tolerance itself is
153/// dimensionless and unit-invariant. It is not a strict bound on the full
154/// assembled stiffness matrix condition number — the global conditioning may be
155/// worse — but it captures the dominant per-element driver and biases the
156/// tolerance toward being tight rather than loose.
157///
158/// `C = 1e-2` is an **empirically calibrated** safety factor, not a rigorous
159/// error upper bound. It was calibrated against the measured residual of a
160/// large-scale symmetric hyperstatic portal regression case (`λ² ≈ 2.5e14`,
161/// measured residual `~1.7e-3 · λ² · ε`); the coefficient is ≪ 1 because
162/// reaction cancellation reduces the residual far below the pessimistic
163/// forward-error bound. The calibration is based on this specific topology and
164/// load pattern; other frame configurations may exhibit different cancellation
165/// behaviour. Below `λ² ≈ 4.5e9` (span ≈ 42 km for the reference section) the
166/// term stays below `EQUILIBRIUM_REL_TOL` and the tolerance is exactly `1e-6`,
167/// unchanged.
168const EQUILIBRIUM_COND_FACTOR: f64 = 1e-2;
169
170/// Result of the global equilibrium check, summed **about the global origin
171/// `(0, 0)`**.
172///
173/// Residuals are `applied + reaction` and should be zero for a solved,
174/// properly restrained frame. Both the residuals and the contributing totals
175/// are exposed so a caller can diagnose which component is out of balance
176/// instead of receiving a single boolean.
177#[derive(Debug, Clone, Copy, PartialEq)]
178pub struct EquilibriumReport {
179    /// Residual of `ΣFx` (applied + reaction).
180    pub fx_residual: f64,
181    /// Residual of `ΣFy` (applied + reaction).
182    pub fy_residual: f64,
183    /// Residual of `ΣMz` about the global origin (applied + reaction).
184    pub mz_residual: f64,
185    /// Total applied horizontal load (global nodal, plus member load resultants).
186    pub applied_fx: f64,
187    /// Total applied vertical load.
188    pub applied_fy: f64,
189    /// Total applied moment about the origin, including force moments `x·Fy − y·Fx`.
190    pub applied_mz: f64,
191    /// Sum of support reaction forces in X.
192    pub reaction_fx: f64,
193    /// Sum of support reaction forces in Y.
194    pub reaction_fy: f64,
195    /// Sum of reaction moments about the origin, including `x·Ry − y·Rx`.
196    pub reaction_mz: f64,
197    /// Absolute **force** tolerance applied by [`Self::is_balanced`], equal to
198    /// `effective_rel_tol · force_scale` (see [`Self::force_tolerance`]). The
199    /// moment tolerance is **not** stored in this field; use
200    /// [`Self::moment_tolerance`] to obtain it. Using `tolerance` to
201    /// threshold `mz_residual` gives a wrong verdict when `l_char != 1`.
202    pub tolerance: f64,
203    /// Σ of the absolute applied and reaction **force** magnitudes actually
204    /// present (per load term, not per resultant — a self-cancelling load pair
205    /// must not collapse the scale to zero). Private: it only feeds
206    /// [`Self::is_balanced`].
207    f_mag: f64,
208    /// Σ of the absolute applied and reaction **moment** magnitudes actually
209    /// present, again per term. Private, as above.
210    m_mag: f64,
211    /// Characteristic length of the structure: the largest absolute nodal
212    /// coordinate (see [`characteristic_length`]). Private, as above.
213    l_char: f64,
214    /// Conditioning-relief relative floor `C · λ²_max · ε`, where `λ²_max` is
215    /// the maximum element slenderness squared `L²·A/I` (dimensionless,
216    /// unit-invariant). `0.0` when the frame has no element. Private: it only
217    /// feeds [`Self::is_balanced`]; see [`EQUILIBRIUM_COND_FACTOR`].
218    cond_rel_floor: f64,
219}
220
221/// The two scale factors behind [`EquilibriumReport::is_balanced`]:
222/// `(force_scale, moment_scale)`.
223///
224/// Both are built **only** from magnitudes the analysed system actually carries,
225/// so a pure change of units (N/m ↔ kN/mm) leaves the verdict unchanged:
226///
227/// * `force_scale = Σ|F| + Σ|M| / l_char` — the force magnitudes present
228///   (applied plus recovered reactions) plus the equivalent force of the moments
229///   present, so a pure-moment system still has a positive force scale.
230/// * `moment_scale = Σ|M| + Σ|F| · l_char` — the moment magnitudes present plus
231///   the moment the forces produce through their largest lever arm `l_char`.
232///   The `Σ|F| · l_char` term is what keeps the moment check sensitive for a load
233///   system that is symmetric about the origin (`applied_mz == 0`): the scale
234///   then reflects the real force × length magnitudes rather than collapsing to
235///   a constant.
236///
237/// `Σ|F|` and `Σ|M|` are sums of absolute **per-term** magnitudes (`f_mag`,
238/// `m_mag`), so equal-and-opposite terms that cancel in the resultant still keep
239/// the scale positive; `l_char` is the largest absolute nodal coordinate. All
240/// three are zero only for a model with no load and no reactions, in which case
241/// both scales are zero and the check degenerates to "the residual must be
242/// exactly zero".
243fn equilibrium_scales(f_mag: f64, m_mag: f64, l_char: f64) -> (f64, f64) {
244    if l_char > 0.0 {
245        (f_mag + m_mag / l_char, m_mag + f_mag * l_char)
246    } else {
247        (f_mag, m_mag)
248    }
249}
250
251impl EquilibriumReport {
252    /// Whether all three residuals are within a tolerance **relative** to the
253    /// analysed system's own magnitudes (see `equilibrium_scales`).
254    ///
255    /// The force residuals (`fx`, `fy`) are compared against `force_scale` and
256    /// the moment residual (`mz`) against `moment_scale`, both scaled by the
257    /// conditioning-aware effective relative tolerance
258    /// `Self::effective_rel_tol`. At normal slenderness this is exactly
259    /// `EQUILIBRIUM_REL_TOL` (`1e-6`); for highly slender frames it is raised
260    /// by a dimensionless element-level conditioning proxy (see
261    /// `EQUILIBRIUM_COND_FACTOR`) so that pure solver round-off is not
262    /// mistaken for a physical imbalance. The verdict is invariant under a
263    /// change of units and the moment check stays sensitive even when a load
264    /// system is symmetric about the origin (`applied_mz == 0`). There is no
265    /// absolute floor: if every relevant magnitude is zero the scale is zero
266    /// and the residual must then be **exactly** zero for the frame to be
267    /// balanced.
268    pub fn is_balanced(&self) -> bool {
269        let (f_scale, m_scale) = equilibrium_scales(self.f_mag, self.m_mag, self.l_char);
270        let rel = self.effective_rel_tol();
271        self.fx_residual.abs() <= rel * f_scale
272            && self.fy_residual.abs() <= rel * f_scale
273            && self.mz_residual.abs() <= rel * m_scale
274    }
275
276    /// Effective relative tolerance: at least [`EQUILIBRIUM_REL_TOL`], relaxed
277    /// by the conditioning floor for a slender frame so pure solver round-off
278    /// is not mistaken for a physical imbalance.
279    fn effective_rel_tol(&self) -> f64 {
280        EQUILIBRIUM_REL_TOL.max(self.cond_rel_floor)
281    }
282
283    /// Force tolerance used by [`Self::is_balanced`]: `effective_rel_tol *
284    /// force_scale`, where `force_scale = Σ|F| + Σ|M| / l_char` (see
285    /// `equilibrium_scales`). The force residuals `fx_residual` and
286    /// `fy_residual` are compared against this value.
287    ///
288    /// This is identical to the [`Self::tolerance`] field, exposed as a
289    /// method for clarity and symmetry with [`Self::moment_tolerance`].
290    pub fn force_tolerance(&self) -> f64 {
291        let (f_scale, _) = equilibrium_scales(self.f_mag, self.m_mag, self.l_char);
292        self.effective_rel_tol() * f_scale
293    }
294
295    /// Moment tolerance used by [`Self::is_balanced`]: `effective_rel_tol *
296    /// moment_scale`, where `moment_scale = Σ|M| + Σ|F| * l_char` (see
297    /// `equilibrium_scales`). The moment residual `mz_residual` is
298    /// compared against this value.
299    ///
300    /// This is generally **not** equal to [`Self::tolerance`] (which is the
301    /// force tolerance); using `tolerance` to threshold `mz_residual` would
302    /// give a wrong verdict for structures with `l_char != 1`.
303    pub fn moment_tolerance(&self) -> f64 {
304        let (_, m_scale) = equilibrium_scales(self.f_mag, self.m_mag, self.l_char);
305        self.effective_rel_tol() * m_scale
306    }
307}
308
309// ---------------------------------------------------------------------------
310// FrameModel
311// ---------------------------------------------------------------------------
312
313/// A 2D frame: nodes, members, supports and loads.
314///
315/// Wraps the existing [`BeamModel`] and delegates all mechanics to it; supports
316/// arbitrary planar connectivity (not just a straight beam), per-DOF
317/// constraints and prescribed displacements.
318#[derive(Debug, Clone)]
319pub struct FrameModel {
320    inner: BeamModel,
321}
322
323impl Default for FrameModel {
324    fn default() -> Self {
325        Self::new()
326    }
327}
328
329impl FrameModel {
330    /// Create an empty frame.
331    pub fn new() -> Self {
332        Self {
333            inner: BeamModel::new(),
334        }
335    }
336
337    /// Number of nodes.
338    pub fn n_nodes(&self) -> usize {
339        self.inner.nodes.len()
340    }
341
342    /// Number of members.
343    pub fn n_members(&self) -> usize {
344        self.inner.elements.len()
345    }
346
347    /// Add a node at global `(x, y)` and return its handle.
348    ///
349    /// # Errors
350    ///
351    /// [`FemError::InvalidInput`] if either coordinate is not finite.
352    pub fn add_node(&mut self, x: f64, y: f64) -> Result<NodeHandle, FemError> {
353        if !x.is_finite() || !y.is_finite() {
354            return Err(FemError::InvalidInput(format!(
355                "node coordinates must be finite, got ({x}, {y})"
356            )));
357        }
358        let idx = self.inner.nodes.len();
359        self.inner.add_node(BeamNode::new(idx, x, y));
360        Ok(NodeHandle(idx))
361    }
362
363    /// Add a member between two existing nodes.
364    ///
365    /// The member stiffness uses `EA` (axial) and `EI` (bending) from the given
366    /// material and section, exactly as the Beam FEM core does.
367    ///
368    /// # Errors
369    ///
370    /// * [`FemError::InvalidNode`] if either handle is not valid for this model;
371    /// * [`FemError::ZeroLengthMember`] if the two nodes coincide;
372    /// * [`FemError::DuplicateMember`] if a member already connects the same
373    ///   node pair (in either order) - parallel members are not supported;
374    /// * [`FemError::InvalidInput`] if `E`, `A` or `I` is non-finite or
375    ///   non-positive (the same predicate the solver applies at assembly time).
376    pub fn add_member(
377        &mut self,
378        a: NodeHandle,
379        b: NodeHandle,
380        material: Material,
381        section: BeamSection,
382    ) -> Result<MemberHandle, FemError> {
383        let ia = self.check_node(a)?;
384        let ib = self.check_node(b)?;
385        if ia == ib {
386            return Err(FemError::ZeroLengthMember(format!(
387                "member connects node {ia} to itself"
388            )));
389        }
390        let (pa, pb) = (self.inner.nodes[ia].point(), self.inner.nodes[ib].point());
391        let (dx, dy) = (pb.x - pa.x, pb.y - pa.y);
392        if !dx.is_finite() || !dy.is_finite() || dx * dx + dy * dy <= 0.0 {
393            return Err(FemError::ZeroLengthMember(format!(
394                "nodes {ia} and {ib} coincide at ({}, {})",
395                pa.x, pa.y
396            )));
397        }
398
399        let (e, area, inertia) = (material.youngs_modulus, section.area, section.second_moment);
400        if !e.is_finite() || e <= 0.0 {
401            return Err(FemError::InvalidInput(format!(
402                "Young's modulus must be finite and positive, got {e}"
403            )));
404        }
405        if !area.is_finite() || area <= 0.0 {
406            return Err(FemError::InvalidInput(format!(
407                "cross-section area must be finite and positive, got {area}"
408            )));
409        }
410        if !inertia.is_finite() || inertia <= 0.0 {
411            return Err(FemError::InvalidInput(format!(
412                "second moment of area must be finite and positive, got {inertia}"
413            )));
414        }
415
416        let (lo, hi) = if ia < ib { (ia, ib) } else { (ib, ia) };
417        for existing in &self.inner.elements {
418            let (elo, ehi) = if existing.node_i < existing.node_j {
419                (existing.node_i, existing.node_j)
420            } else {
421                (existing.node_j, existing.node_i)
422            };
423            if elo == lo && ehi == hi {
424                return Err(FemError::DuplicateMember(format!(
425                    "a member already connects nodes {lo} and {hi}; parallel members are not supported"
426                )));
427            }
428        }
429
430        let element = BeamElement::new(ia, ib, material, section)?;
431        self.inner.add_element(element);
432        Ok(MemberHandle(self.inner.elements.len() - 1))
433    }
434
435    /// Fully fix a node (`ux = uy = rz = 0`).
436    ///
437    /// # Errors
438    ///
439    /// [`FemError::InvalidNode`] if the handle is not valid.
440    pub fn fix(&mut self, node: NodeHandle) -> Result<(), FemError> {
441        let i = self.check_node(node)?;
442        self.inner.try_fix_node(i)
443    }
444
445    /// Pin a node: restrain `ux` and `uy`, leave the rotation free.
446    pub fn pin(&mut self, node: NodeHandle) -> Result<(), FemError> {
447        let i = self.check_node(node)?;
448        self.inner.try_fix_dof(i, Dof::Ux.index(), 0.0)?;
449        self.inner.try_fix_dof(i, Dof::Uy.index(), 0.0)
450    }
451
452    /// Roller restraining the vertical translation (`uy = 0`), horizontal free.
453    pub fn roller_y(&mut self, node: NodeHandle) -> Result<(), FemError> {
454        let i = self.check_node(node)?;
455        self.inner.try_fix_dof(i, Dof::Uy.index(), 0.0)
456    }
457
458    /// Roller restraining the horizontal translation (`ux = 0`), vertical free.
459    pub fn roller_x(&mut self, node: NodeHandle) -> Result<(), FemError> {
460        let i = self.check_node(node)?;
461        self.inner.try_fix_dof(i, Dof::Ux.index(), 0.0)
462    }
463
464    /// Prescribe a DOF to an arbitrary finite value (e.g. a support settlement).
465    ///
466    /// Applied through the existing static condensation
467    /// (`K_ff u_f = f_f - K_fc u_c`); no penalty constraints are used.
468    ///
469    /// If the DOF was previously constrained (e.g. by [`fix`](Self::fix)),
470    /// the existing prescription is **replaced** — this allows the common
471    /// workflow of fixing a support node and then applying a settlement.
472    pub fn restrain(&mut self, node: NodeHandle, dof: Dof, value: f64) -> Result<(), FemError> {
473        let i = self.check_node(node)?;
474        self.inner.try_override(i, dof, value)
475    }
476
477    /// Apply a **global** nodal force `(fx, fy)`.
478    ///
479    /// # Errors
480    ///
481    /// [`FemError::InvalidNode`] if the handle is not valid, or
482    /// [`FemError::InvalidInput`] if either component is non-finite. Both
483    /// components are validated **before** either is recorded, so a rejected
484    /// call leaves the model unchanged (no half-applied load).
485    pub fn nodal_load(&mut self, node: NodeHandle, fx: f64, fy: f64) -> Result<(), FemError> {
486        let i = self.check_node(node)?;
487        if !fx.is_finite() {
488            return Err(FemError::InvalidInput(format!(
489                "nodal force Fx must be finite, got {fx}"
490            )));
491        }
492        if !fy.is_finite() {
493            return Err(FemError::InvalidInput(format!(
494                "nodal force Fy must be finite, got {fy}"
495            )));
496        }
497        self.inner.try_add_nodal_force(i, Dof::Ux.index(), fx)?;
498        self.inner.try_add_nodal_force(i, Dof::Uy.index(), fy)
499    }
500
501    /// Apply a **global** nodal moment `mz` (counter-clockwise positive).
502    pub fn nodal_moment(&mut self, node: NodeHandle, mz: f64) -> Result<(), FemError> {
503        let i = self.check_node(node)?;
504        self.inner.add_applied_moment(i, mz)
505    }
506
507    /// Apply a uniform distributed load in the member's **local** axes.
508    ///
509    /// `qy > 0` is upward in local +y; `qx > 0` is tensile (towards `node_j`).
510    /// Repeated calls accumulate on the same member.
511    pub fn member_udl(&mut self, member: MemberHandle, qx: f64, qy: f64) -> Result<(), FemError> {
512        let i = self.check_member(member)?;
513        self.inner.add_distributed_load(i, qx, qy)
514    }
515
516    /// Apply a point load in the member's **local** axes at normalised position
517    /// `xi in [0, 1]`.
518    ///
519    /// `xi = 0` / `xi = 1` places the load at a node; it is applied exactly once
520    /// (no double counting).
521    pub fn member_point_load(
522        &mut self,
523        member: MemberHandle,
524        xi: f64,
525        fx: f64,
526        fy: f64,
527        mz: f64,
528    ) -> Result<(), FemError> {
529        let i = self.check_member(member)?;
530        self.inner.add_point_load(i, xi, fx, fy, mz)
531    }
532
533    /// Solve with automatic solver selection.
534    ///
535    /// Equivalent to `self.solve_with(SolverSelection::Auto)`. The registry
536    /// inspects the condensed stiffness matrix and picks a backend (dense for
537    /// small systems, skyline LDLᵀ for symmetric positive-definite, sparse LU
538    /// otherwise). The selected solver is used exactly once; if it fails the
539    /// error is returned directly — there is no automatic retry with a
540    /// different backend.
541    pub fn solve(&self) -> Result<FrameAnalysisResult, FemError> {
542        self.solve_with(SolverSelection::Auto)
543    }
544
545    /// Solve with an explicit backend selection.
546    ///
547    /// Validates the model (see [`Self::validate`]) before assembling, so
548    /// structural modelling errors are reported as targeted diagnostics rather
549    /// than as a matrix singularity.
550    ///
551    /// **Solver semantics**:
552    /// - [`SolverSelection::Auto`] — the registry inspects the matrix and
553    ///   selects a backend. The chosen solver is used exactly once; if it
554    ///   fails, the error is returned directly (no automatic retry with a
555    ///   different backend).
556    /// - [`SolverSelection::Named`] — the requested solver is used **only**;
557    ///   no silent fallback. If the solver is unavailable or fails, the error
558    ///   is returned directly. Use the convenience constructors
559    ///   [`SolverSelection::dense`], [`SolverSelection::skyline_ldlt`],
560    ///   [`SolverSelection::sparse_lu`], [`SolverSelection::cg`],
561    ///   [`SolverSelection::iccg`] for typed selection.
562    ///
563    /// After solving, [`FrameAnalysisResult::solver_name`] reports which
564    /// backend was actually used.
565    pub fn solve_with(&self, selection: SolverSelection) -> Result<FrameAnalysisResult, FemError> {
566        FrameSolver::new(self).with_selection(selection).solve()
567    }
568
569    /// A solver builder for this frame (configure a backend, then solve).
570    pub fn solver(&self) -> FrameSolver<'_> {
571        FrameSolver::new(self)
572    }
573
574    /// Validate the structural model.
575    ///
576    /// Checks, in order:
577    ///
578    /// 1. the model is not empty (at least one node and one member);
579    /// 2. no **orphan nodes** - every node is used by at least one member;
580    /// 3. the members form a **single connected component**.
581    ///
582    /// Per-element checks (zero length, duplicate connectivity, invalid
583    /// material/section) are enforced when the member is added.
584    ///
585    /// Insufficient restraint is *not* diagnosed here: [`Self::diagnostic`]
586    /// classifies the boundary-conditioned system separately, without
587    /// rejecting the model, and [`FrameSolver::solve`] attaches that
588    /// classification to the solver error when the solve fails.
589    pub fn validate(&self) -> Result<(), FemError> {
590        let inner = &self.inner;
591        if inner.nodes.is_empty() {
592            return Err(FemError::InvalidModel(
593                "frame has no nodes; add at least one node and one member".to_string(),
594            ));
595        }
596        if inner.elements.is_empty() {
597            return Err(FemError::InvalidModel(
598                "frame has no members; add at least one member".to_string(),
599            ));
600        }
601
602        let mut used = vec![false; inner.nodes.len()];
603        for e in &inner.elements {
604            used[e.node_i] = true;
605            used[e.node_j] = true;
606        }
607        if let Some(i) = used.iter().position(|u| !u) {
608            let p = inner.nodes[i].point();
609            return Err(FemError::OrphanNode(format!(
610                "node {i} at ({}, {}) is not connected to any member",
611                p.x, p.y
612            )));
613        }
614
615        let components = count_components(inner.nodes.len(), &inner.elements);
616        if components > 1 {
617            return Err(FemError::DisconnectedStructure(format!(
618                "frame has {components} disconnected components; a single connected \
619                 structural system is required"
620            )));
621        }
622        Ok(())
623    }
624
625    /// Diagnose the **boundary-conditioned** (reduced) system without solving
626    /// it: is this structure stable, under-restrained (rigid-body mechanism),
627    /// internally rank deficient (mechanism), or merely numerically
628    /// ill-conditioned?
629    ///
630    /// The diagnosis reads the reduced free-free stiffness block `K_ff` that
631    /// the **actual solve path** condenses (`BeamSolver::condense`) — the exact
632    /// matrix a solve factorises, not a second assembly — and classifies it with
633    /// relative, scale-invariant probes (see [`crate::fea::mechanism`] for the
634    /// criterion and its limits). It never assembles with penalties, never
635    /// perturbs the matrix and never fabricates displacements, and it does not
636    /// run as part of a successful [`Self::solve`].
637    ///
638    /// The verdict is a property of the **structure**, not of the loads: the
639    /// load vector is not consulted, so scaling or omitting the loads cannot
640    /// change the result.
641    ///
642    /// # Errors
643    ///
644    /// The same model errors as [`Self::solve`]: [`Self::validate`] plus the
645    /// construction checks [`BeamSolver::from_model`] performs (its error
646    /// surface is slightly wider than `validate` alone).
647    pub fn diagnostic(&self) -> Result<StructuralDiagnostic, FemError> {
648        self.validate()?;
649        let mut beam = BeamSolver::from_model(&self.inner)?;
650        Ok(self.classify(beam.condense()))
651    }
652
653    /// Classify a reduced (boundary-conditioned) stiffness system using this
654    /// model's geometry: the global rigid-body motions are built in *reduced*
655    /// order from the solver's own free-DOF map, so no independent reassembly
656    /// of `K_ff` is involved.
657    fn classify(&self, reduced: &ReducedSystem) -> StructuralDiagnostic {
658        let rigid = self.rigid_candidates(reduced.free_to_global());
659        diagnose_reduced(reduced.k_ff(), &rigid)
660    }
661
662    /// The three global rigid-body motions (Tx, Ty, Rz) restricted to the free
663    /// DOFs, laid out in reduced order.
664    ///
665    /// `free_to_global[r]` is the global DOF (`3 * node + dof`) of reduced index
666    /// `r`; constrained entries are dropped, not displaced. Rotation by `theta`
667    /// about the global origin is `ux = -theta*y`, `uy = theta*x`, `rz = theta`.
668    fn rigid_candidates(&self, free_to_global: &[usize]) -> Vec<Vec<f64>> {
669        let n_free = free_to_global.len();
670        let mut tx = vec![0.0; n_free];
671        let mut ty = vec![0.0; n_free];
672        let mut rz = vec![0.0; n_free];
673        for (r, &global) in free_to_global.iter().enumerate() {
674            let point = self.inner.nodes[global / 3].point();
675            match global % 3 {
676                0 => {
677                    tx[r] = 1.0;
678                    rz[r] = -point.y;
679                }
680                1 => {
681                    ty[r] = 1.0;
682                    rz[r] = point.x;
683                }
684                _ => rz[r] = 1.0,
685            }
686        }
687        vec![tx, ty, rz]
688    }
689
690    /// Handle of the node with the given index.
691    ///
692    /// # Errors
693    ///
694    /// [`FemError::InvalidNode`] if the index is out of range.
695    pub fn node_handle(&self, index: usize) -> Result<NodeHandle, FemError> {
696        if index >= self.inner.nodes.len() {
697            return Err(FemError::InvalidNode(format!(
698                "node index {index} is out of range (max: {})",
699                self.inner.nodes.len().saturating_sub(1)
700            )));
701        }
702        Ok(NodeHandle(index))
703    }
704
705    /// Handle of the member with the given index.
706    ///
707    /// # Errors
708    ///
709    /// [`FemError::InvalidMember`] if the index is out of range.
710    pub fn member_handle(&self, index: usize) -> Result<MemberHandle, FemError> {
711        if index >= self.inner.elements.len() {
712            return Err(FemError::InvalidMember(format!(
713                "member index {index} is out of range (max: {})",
714                self.inner.elements.len().saturating_sub(1)
715            )));
716        }
717        Ok(MemberHandle(index))
718    }
719
720    fn check_node(&self, node: NodeHandle) -> Result<usize, FemError> {
721        if node.0 >= self.inner.nodes.len() {
722            return Err(FemError::InvalidNode(format!(
723                "node handle {} is not valid for this frame (max: {})",
724                node.0,
725                self.inner.nodes.len().saturating_sub(1)
726            )));
727        }
728        Ok(node.0)
729    }
730
731    fn check_member(&self, member: MemberHandle) -> Result<usize, FemError> {
732        if member.0 >= self.inner.elements.len() {
733            return Err(FemError::InvalidMember(format!(
734                "member handle {} is not valid for this frame (max: {})",
735                member.0,
736                self.inner.elements.len().saturating_sub(1)
737            )));
738        }
739        Ok(member.0)
740    }
741}
742
743/// Number of connected components of the member connectivity graph.
744fn count_components(n_nodes: usize, elements: &[BeamElement]) -> usize {
745    let mut adj: Vec<Vec<usize>> = vec![Vec::new(); n_nodes];
746    for e in elements {
747        adj[e.node_i].push(e.node_j);
748        adj[e.node_j].push(e.node_i);
749    }
750    let mut seen = vec![false; n_nodes];
751    let mut components = 0;
752    for start in 0..n_nodes {
753        if seen[start] || adj[start].is_empty() {
754            continue;
755        }
756        components += 1;
757        seen[start] = true;
758        let mut queue = VecDeque::from([start]);
759        while let Some(u) = queue.pop_front() {
760            for &v in &adj[u] {
761                if !seen[v] {
762                    seen[v] = true;
763                    queue.push_back(v);
764                }
765            }
766        }
767    }
768    components
769}
770
771// ---------------------------------------------------------------------------
772// FrameSolver
773// ---------------------------------------------------------------------------
774
775/// Solves a [`FrameModel`]; configure the backend, then [`FrameSolver::solve`].
776pub struct FrameSolver<'a> {
777    model: &'a FrameModel,
778    selection: SolverSelection,
779}
780
781impl<'a> FrameSolver<'a> {
782    /// Create a solver for `model` using automatic backend selection.
783    pub fn new(model: &'a FrameModel) -> Self {
784        Self {
785            model,
786            selection: SolverSelection::Auto,
787        }
788    }
789
790    /// Choose an explicit backend (or [`SolverSelection::Auto`]).
791    pub fn with_selection(mut self, selection: SolverSelection) -> Self {
792        self.selection = selection;
793        self
794    }
795
796    /// Set the backend (builder-style alternative to [`Self::with_selection`]).
797    pub fn set_solver(&mut self, selection: SolverSelection) {
798        self.selection = selection;
799    }
800
801    /// Validate, assemble and solve the frame.
802    ///
803    /// A successful solve runs **no** diagnostic and its numerical path is
804    /// unchanged (see [`FrameModel::diagnostic`] for the on-demand API). Only a
805    /// *failed* solve additionally classifies the reduced system, and appends
806    /// that classification to the error message so an under-restrained or
807    /// rank-deficient frame is not reported as an opaque "singular matrix".
808    ///
809    /// # Errors
810    ///
811    /// Model-structure errors from [`FrameModel::validate`] plus any
812    /// [`FemError::SolverError`] from the linear solver (e.g. insufficient
813    /// restraint, or a conditioning limit at extreme scales). The variant is
814    /// unchanged; the message carries the diagnosis.
815    pub fn solve(&self) -> Result<FrameAnalysisResult, FemError> {
816        self.model.validate()?;
817        let mut beam = BeamSolver::from_model(&self.model.inner)?;
818        beam.set_solver(self.selection.clone());
819        if let Err(e) = beam.solve_configured() {
820            // The solver condensed the boundary conditions before attempting any
821            // backend, so its retained reduced system is the exact matrix the
822            // failed factorisation saw - no second assembly.
823            let diagnosis = beam.reduced_system().map(|rs| self.model.classify(rs));
824            return Err(with_structural_diagnosis(e, diagnosis));
825        }
826        Ok(FrameAnalysisResult {
827            beam,
828            model: self.model.clone(),
829        })
830    }
831}
832
833/// Record the structural diagnosis of a failed solve in the error message.
834///
835/// The error **variant** is deliberately preserved (`SolverError` stays
836/// `SolverError`): the diagnosis is extra information, not a re-typing of the
837/// failure, so no existing caller or exhaustive match changes meaning. A
838/// `Stable` diagnosis adds nothing - the failure was not structural - and a
839/// missing diagnosis (`None`, i.e. no reduced system was available) leaves the
840/// error untouched.
841fn with_structural_diagnosis(err: FemError, diagnosis: Option<StructuralDiagnostic>) -> FemError {
842    match (err, diagnosis) {
843        (FemError::SolverError { source, message }, Some(d))
844            if !matches!(d, StructuralDiagnostic::Stable) =>
845        {
846            FemError::SolverError {
847                source,
848                message: format!("{message}; structural diagnosis: {d}"),
849            }
850        }
851        (other, _) => other,
852    }
853}
854
855// ---------------------------------------------------------------------------
856// FrameAnalysisResult
857// ---------------------------------------------------------------------------
858
859/// Solved frame: frame-level access to displacements, reactions, member end
860/// forces and global equilibrium.
861///
862/// All values come from the existing [`BeamSolver`]; nothing is recomputed with
863/// a second formulation.
864pub struct FrameAnalysisResult {
865    beam: BeamSolver,
866    model: FrameModel,
867}
868
869impl std::fmt::Debug for FrameAnalysisResult {
870    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
871        f.debug_struct("FrameAnalysisResult")
872            .field("nodes", &self.model.n_nodes())
873            .field("members", &self.model.n_members())
874            .field("solver", &self.beam.solver_name())
875            .finish_non_exhaustive()
876    }
877}
878
879impl FrameAnalysisResult {
880    /// Name of the backend used by the successful solve.
881    pub fn solver_name(&self) -> Option<&str> {
882        self.beam.solver_name()
883    }
884
885    /// Number of nodes in the solved frame.
886    pub fn n_nodes(&self) -> usize {
887        self.model.n_nodes()
888    }
889
890    /// Number of members in the solved frame.
891    pub fn n_members(&self) -> usize {
892        self.model.n_members()
893    }
894
895    /// Full global displacement vector, laid out `[ux, uy, rz]` per node.
896    pub fn displacements(&self) -> &[f64] {
897        self.beam.displacements()
898    }
899
900    /// Global support reactions, laid out `[Rx, Ry, Mz]` per node.
901    pub fn reactions(&self) -> Vec<f64> {
902        self.beam.reactions()
903    }
904
905    /// Displacement of a DOF at a node (global).
906    ///
907    /// # Errors
908    ///
909    /// [`FemError::InvalidNode`] if the handle is not valid for this frame.
910    pub fn displacement(&self, node: NodeHandle, dof: Dof) -> Result<f64, FemError> {
911        self.check_node(node)?;
912        self.beam.displacement_dof(node.index(), dof)
913    }
914
915    /// Support reaction of a DOF at a node (global).
916    ///
917    /// Free DOFs report the raw (round-off) residual, exactly as
918    /// [`BeamSolver::reaction_dof`] does.
919    ///
920    /// # Errors
921    ///
922    /// [`FemError::InvalidNode`] if the handle is not valid for this frame.
923    pub fn reaction(&self, node: NodeHandle, dof: Dof) -> Result<f64, FemError> {
924        self.check_node(node)?;
925        self.beam.reaction_dof(node.index(), dof)
926    }
927
928    /// Member end forces in **local** axes:
929    /// `[N_i, V_i, M_i, N_j, V_j, M_j]`.
930    ///
931    /// These are element-on-node forces, `f_end = f_equiv - K_e u_e`, exactly as
932    /// documented in `docs/beam_fem.md`; the sign convention is **not** inverted
933    /// for the frame API.
934    ///
935    /// # Errors
936    ///
937    /// [`FemError::InvalidMember`] if the handle is not valid for this frame.
938    pub fn member_end_forces(&self, member: MemberHandle) -> Result<[f64; 6], FemError> {
939        let i = self.check_member(member)?;
940        let all = self.beam.element_end_forces()?;
941        all.get(i)
942            .copied()
943            .ok_or_else(|| FemError::InvalidMember(format!("member handle {} is out of range", i)))
944    }
945
946    /// Member end forces transformed to **global** axes
947    /// (`f_global = Tᵀ f_local`).
948    ///
949    /// # Errors
950    ///
951    /// [`FemError::InvalidMember`] if the handle is not valid for this frame.
952    pub fn member_end_forces_global(&self, member: MemberHandle) -> Result<[f64; 6], FemError> {
953        let i = self.check_member(member)?;
954        let all = self.beam.element_end_forces_global()?;
955        all.get(i)
956            .copied()
957            .ok_or_else(|| FemError::InvalidMember(format!("member handle {} is out of range", i)))
958    }
959
960    /// Global equilibrium check about the origin `(0, 0)`.
961    ///
962    /// Combines support reactions, global nodal loads and moments, and the
963    /// global resultants of member distributed and point loads (transformed from
964    /// member-local axes and applied at their true global locations).
965    /// See [`EquilibriumReport`].
966    pub fn equilibrium(&self) -> EquilibriumReport {
967        let m = &self.model.inner;
968        let mut applied_fx = 0.0;
969        let mut applied_fy = 0.0;
970        let mut applied_mz = 0.0;
971        // Absolute per-term magnitudes (not resultants): a load pair that cancels
972        // in the sum must still contribute to the equilibrium scale.
973        let mut applied_f_mag = 0.0;
974        let mut applied_m_mag = 0.0;
975
976        // Global nodal loads and moments.
977        for (node, dof, v) in &m.nodal_forces {
978            let p = m.nodes[*node].point();
979            match *dof {
980                0 => {
981                    applied_fx += v;
982                    applied_mz += -p.y * v;
983                    applied_f_mag += v.abs();
984                }
985                1 => {
986                    applied_fy += v;
987                    applied_mz += p.x * v;
988                    applied_f_mag += v.abs();
989                }
990                _ => {
991                    applied_mz += v;
992                    applied_m_mag += v.abs();
993                }
994            }
995        }
996        for am in &m.applied_moments {
997            applied_mz += am.value;
998            applied_m_mag += am.value.abs();
999        }
1000
1001        // Member load resultants, rotated from local to global.
1002        for (elem_idx, dl) in m.distributed_loads.iter().enumerate() {
1003            let _ = elem_idx;
1004            let Some((pi, pj)) = member_points(m, dl.element_idx) else {
1005                continue;
1006            };
1007            let (dx, dy) = (pj.x - pi.x, pj.y - pi.y);
1008            let len = (dx * dx + dy * dy).sqrt();
1009            let (c, s) = (dx / len, dy / len);
1010            let (lfx, lfy) = (dl.qx * len, dl.qy * len);
1011            let (gx, gy) = (c * lfx - s * lfy, s * lfx + c * lfy);
1012            let (xm, ym) = (pi.x + 0.5 * dx, pi.y + 0.5 * dy);
1013            applied_fx += gx;
1014            applied_fy += gy;
1015            applied_mz += xm * gy - ym * gx;
1016            applied_f_mag += gx.abs() + gy.abs();
1017        }
1018        for pl in &m.point_loads {
1019            let Some((pi, _)) = member_points(m, pl.element_idx) else {
1020                continue;
1021            };
1022            let el = &m.elements[pl.element_idx];
1023            let pj = m.nodes[el.node_j].point();
1024            let (dx, dy) = (pj.x - pi.x, pj.y - pi.y);
1025            let len = (dx * dx + dy * dy).sqrt();
1026            let (c, s) = (dx / len, dy / len);
1027            let (gx, gy) = (c * pl.fx - s * pl.fy, s * pl.fx + c * pl.fy);
1028            let (xp, yp) = (pi.x + pl.position * dx, pi.y + pl.position * dy);
1029            applied_fx += gx;
1030            applied_fy += gy;
1031            applied_mz += xp * gy - yp * gx + pl.mz;
1032            applied_f_mag += gx.abs() + gy.abs();
1033            applied_m_mag += pl.mz.abs();
1034        }
1035
1036        // Support reactions, per node.
1037        let reactions = self.beam.reactions();
1038        let mut reaction_fx = 0.0;
1039        let mut reaction_fy = 0.0;
1040        let mut reaction_mz = 0.0;
1041        let mut reaction_f_mag = 0.0;
1042        let mut reaction_m_mag = 0.0;
1043        for (idx, node) in m.nodes.iter().enumerate() {
1044            let p = node.point();
1045            let rx = reactions.get(3 * idx).copied().unwrap_or(0.0);
1046            let ry = reactions.get(3 * idx + 1).copied().unwrap_or(0.0);
1047            let rz = reactions.get(3 * idx + 2).copied().unwrap_or(0.0);
1048            reaction_fx += rx;
1049            reaction_fy += ry;
1050            reaction_mz += p.x * ry - p.y * rx + rz;
1051            reaction_f_mag += rx.abs() + ry.abs();
1052            reaction_m_mag += rz.abs();
1053        }
1054
1055        // Characteristic length of the structure: the largest absolute nodal
1056        // coordinate. Positive for any solvable model (a zero-length member is
1057        // rejected). It is what makes the moment scale `Σ|F|·l_char` reflect the
1058        // structure rather than a constant.
1059        let l_char = characteristic_length(m);
1060        let f_mag = applied_f_mag + reaction_f_mag;
1061        let m_mag = applied_m_mag + reaction_m_mag;
1062        let cond_rel_floor = EQUILIBRIUM_COND_FACTOR * max_element_slenderness_sq(m) * f64::EPSILON;
1063        let rel = EQUILIBRIUM_REL_TOL.max(cond_rel_floor);
1064        let (f_scale, _m_scale) = equilibrium_scales(f_mag, m_mag, l_char);
1065
1066        EquilibriumReport {
1067            fx_residual: applied_fx + reaction_fx,
1068            fy_residual: applied_fy + reaction_fy,
1069            mz_residual: applied_mz + reaction_mz,
1070            applied_fx,
1071            applied_fy,
1072            applied_mz,
1073            reaction_fx,
1074            reaction_fy,
1075            reaction_mz,
1076            tolerance: rel * f_scale,
1077            f_mag,
1078            m_mag,
1079            l_char,
1080            cond_rel_floor,
1081        }
1082    }
1083
1084    fn check_node(&self, node: NodeHandle) -> Result<(), FemError> {
1085        if node.index() >= self.model.n_nodes() {
1086            return Err(FemError::InvalidNode(format!(
1087                "node handle {} is not valid for this result (max: {})",
1088                node.index(),
1089                self.model.n_nodes().saturating_sub(1)
1090            )));
1091        }
1092        Ok(())
1093    }
1094
1095    fn check_member(&self, member: MemberHandle) -> Result<usize, FemError> {
1096        if member.index() >= self.model.n_members() {
1097            return Err(FemError::InvalidMember(format!(
1098                "member handle {} is not valid for this result (max: {})",
1099                member.index(),
1100                self.model.n_members().saturating_sub(1)
1101            )));
1102        }
1103        Ok(member.index())
1104    }
1105}
1106
1107/// End-point coordinates of a member, or `None` if the index is out of range.
1108fn member_points(
1109    model: &BeamModel,
1110    member: usize,
1111) -> Option<(crate::geometry::Point, crate::geometry::Point)> {
1112    let el = model.elements.get(member)?;
1113    Some((
1114        model.nodes[el.node_i].point(),
1115        model.nodes[el.node_j].point(),
1116    ))
1117}
1118
1119/// Characteristic length of the model: the largest absolute nodal coordinate.
1120///
1121/// The equilibrium moments are summed **about the origin**, so the length that
1122/// relates the force and moment scales must be measured from the origin too —
1123/// not a translation-invariant span. `0.0` for an empty model.
1124fn characteristic_length(model: &BeamModel) -> f64 {
1125    let mut l_char: f64 = 0.0;
1126    for node in &model.nodes {
1127        let p = node.point();
1128        l_char = l_char.max(p.x.abs()).max(p.y.abs());
1129    }
1130    l_char
1131}
1132
1133/// Maximum element slenderness squared `λ² = L²·A/I` over all members.
1134///
1135/// This is a dimensionless element-level conditioning proxy for an
1136/// Euler–Bernoulli stiffness matrix: the forward error of a direct solve is
1137/// `O(λ²·ε)`, and the recovered reactions inherit that error, so equilibrium
1138/// residuals of a physically balanced frame can legitimately reach the same
1139/// relative magnitude. It is not a strict bound on the full assembled frame
1140/// stiffness matrix condition number.
1141///
1142/// Only elements with `I > 0` contribute to the maximum; elements with
1143/// non-positive `second_moment` are skipped (defensive guard, since
1144/// `BeamSection::new` does not validate `I`). Returns `0.0` for an empty model
1145/// or when no element has `I > 0`.
1146///
1147/// **Dimensionless and unit-invariant**: `L²·A/I` has units `m²·m²/m⁴ = 1`, and
1148/// a consistent change of length/area/inertia units multiplies numerator and
1149/// denominator by the same power, leaving the ratio unchanged. This is what
1150/// lets the conditioning floor feed a *relative* tolerance without breaking
1151/// unit invariance of the verdict.
1152fn max_element_slenderness_sq(model: &BeamModel) -> f64 {
1153    let mut lambda_sq: f64 = 0.0;
1154    for el in &model.elements {
1155        let p_i = model.nodes[el.node_i].point();
1156        let p_j = model.nodes[el.node_j].point();
1157        let l = el.length(p_i, p_j);
1158        let i = el.section.second_moment;
1159        if i > 0.0 {
1160            lambda_sq = lambda_sq.max(l * l * el.section.area / i);
1161        }
1162    }
1163    lambda_sq
1164}
1165
1166// ---------------------------------------------------------------------------
1167// Single-source guarantee: the diagnostic reads the solver's condensed system
1168// ---------------------------------------------------------------------------
1169//
1170// These are in-crate tests on purpose: `tests/*.rs` are integration tests and
1171// cannot see `pub(crate)` items such as `BeamSolver::condense` /
1172// `FrameModel::classify`, so this guarantee is not testable from there.
1173#[cfg(test)]
1174mod reduced_system_single_source_tests {
1175    use super::*;
1176    use crate::fea::SparseMatrix;
1177
1178    fn steel() -> Material {
1179        Material::new(200e9, 0.3, 7850.0, "Steel")
1180    }
1181
1182    fn sec() -> BeamSection {
1183        BeamSection::new(5e-3, 2e-5)
1184    }
1185
1186    /// The diagnostic must classify exactly the system the solver's own
1187    /// condensation produced: reading the live solver and the public API must
1188    /// agree on every structure in the battery.
1189    fn assert_agrees(f: &FrameModel, label: &str) -> Result<(), FemError> {
1190        let mut beam = BeamSolver::from_model(&f.inner)?;
1191        let from_solver = f.classify(beam.condense());
1192        assert_eq!(
1193            from_solver,
1194            f.diagnostic()?,
1195            "{label}: diagnostic disagrees with the solver's condensed system"
1196        );
1197        Ok(())
1198    }
1199
1200    /// Two-column portal: `base1 - top1 - top2 - base2`, with the given supports
1201    /// on the two base nodes.
1202    fn portal(base_1: &[Dof], base_2: &[Dof]) -> Result<FrameModel, FemError> {
1203        let mut f = FrameModel::new();
1204        let b1 = f.add_node(0.0, 0.0)?;
1205        let t1 = f.add_node(0.0, 3.0)?;
1206        let t2 = f.add_node(4.0, 3.0)?;
1207        let b2 = f.add_node(4.0, 0.0)?;
1208        f.add_member(b1, t1, steel(), sec())?;
1209        f.add_member(t1, t2, steel(), sec())?;
1210        f.add_member(b2, t2, steel(), sec())?;
1211        for dof in base_1 {
1212            f.restrain(b1, *dof, 0.0)?;
1213        }
1214        for dof in base_2 {
1215            f.restrain(b2, *dof, 0.0)?;
1216        }
1217        Ok(f)
1218    }
1219
1220    #[test]
1221    fn diagnostic_classifies_the_solver_condensed_system() -> Result<(), FemError> {
1222        // Completely free beam - three rigid-body modes.
1223        let mut free = FrameModel::new();
1224        let a = free.add_node(0.0, 0.0)?;
1225        let b = free.add_node(2.0, 0.0)?;
1226        free.add_member(a, b, steel(), sec())?;
1227        assert_agrees(&free, "free beam")?;
1228
1229        // One DOF restrained - still under-constrained.
1230        let mut one = FrameModel::new();
1231        let a = one.add_node(0.0, 0.0)?;
1232        let b = one.add_node(2.0, 0.0)?;
1233        one.add_member(a, b, steel(), sec())?;
1234        one.restrain(a, Dof::Ux, 0.0)?;
1235        assert_agrees(&one, "one-DOF-restrained beam")?;
1236
1237        // Stable cantilever.
1238        let mut cant = FrameModel::new();
1239        let base = cant.add_node(0.0, 0.0)?;
1240        let tip = cant.add_node(2.0, 0.0)?;
1241        cant.add_member(base, tip, steel(), sec())?;
1242        cant.fix(base)?;
1243        assert_agrees(&cant, "stable cantilever")?;
1244
1245        // Portal with several support sets, stable and deficient.
1246        let fixed = portal(&[Dof::Ux, Dof::Uy, Dof::Rz], &[Dof::Ux, Dof::Uy, Dof::Rz])?;
1247        assert_agrees(&fixed, "portal, both bases fixed")?;
1248        let pinned = portal(&[Dof::Ux, Dof::Uy], &[Dof::Ux, Dof::Uy])?;
1249        assert_agrees(&pinned, "portal, both bases pinned")?;
1250        let roller = portal(&[Dof::Ux, Dof::Uy, Dof::Rz], &[Dof::Uy])?;
1251        assert_agrees(&roller, "portal, fixed base + roller")?;
1252        let mechanism = portal(&[Dof::Ux, Dof::Uy], &[])?;
1253        assert_agrees(&mechanism, "portal, single pin (mechanism)")?;
1254
1255        Ok(())
1256    }
1257
1258    #[test]
1259    fn diagnostic_uses_the_supplied_matrix_not_a_copy() -> Result<(), FemError> {
1260        let mut f = FrameModel::new();
1261        let base = f.add_node(0.0, 0.0)?;
1262        let tip = f.add_node(2.0, 0.0)?;
1263        f.add_member(base, tip, steel(), sec())?;
1264        f.fix(base)?;
1265
1266        let mut beam = BeamSolver::from_model(&f.inner)?;
1267        let real = beam.condense().clone();
1268        let stable = f.classify(&real);
1269        assert_eq!(
1270            stable,
1271            StructuralDiagnostic::Stable,
1272            "control must be stable"
1273        );
1274
1275        // Forge a reduced system with the first free DOF (tip `ux`) removed. If
1276        // `classify` reassembled its own matrix instead of reading its argument,
1277        // this forgery would have no effect at all.
1278        let n = real.k_ff().n;
1279        let mut forged_k = SparseMatrix::new(n);
1280        for i in 0..n {
1281            for j in 0..n {
1282                let v = real.k_ff().get(i, j);
1283                if i != 0 && j != 0 && v != 0.0 {
1284                    forged_k.add(i, j, v);
1285                }
1286            }
1287        }
1288        forged_k.compress();
1289        let forged = ReducedSystem::new(forged_k, real.free_to_global().to_vec());
1290
1291        let verdict = f.classify(&forged);
1292        assert_ne!(
1293            verdict, stable,
1294            "classify must read the supplied matrix: zeroing a free DOF changed nothing"
1295        );
1296        // The public diagnostic still reads the untouched, real system.
1297        assert_eq!(f.diagnostic()?, stable);
1298        Ok(())
1299    }
1300
1301    /// The failed-solve diagnostic must be driven by the solver's **retained**
1302    /// `K_ff`, not by a reassembly: the frame solve's error carries exactly the
1303    /// verdict that classifying the retained system produces.
1304    #[test]
1305    fn failed_solve_diagnosis_reads_the_solver_retained_system() -> Result<(), FemError> {
1306        // A free beam has the three rigid-body modes and cannot be solved.
1307        let mut f = FrameModel::new();
1308        let a = f.add_node(0.0, 0.0)?;
1309        let b = f.add_node(2.0, 0.0)?;
1310        f.add_member(a, b, steel(), sec())?;
1311
1312        let expected = StructuralDiagnostic::RigidBodyMode {
1313            n_free: 6,
1314            rank: 3,
1315            rigid_modes: 3,
1316        };
1317
1318        // (a) the frame solve fails as a `SolverError` that carries the verdict.
1319        let err = f.solve().expect_err("a free beam must not solve");
1320        match &err {
1321            FemError::SolverError { message, .. } => assert!(
1322                message.contains("structural diagnosis") && message.contains(&expected.to_string()),
1323                "expected the retained-system diagnosis in the error, got {message:?}"
1324            ),
1325            other => panic!("expected SolverError, got {other:?}"),
1326        }
1327
1328        // (b) the verdict is exactly what the solver's retained reduced system
1329        // classifies to: run the identical solve path on a `BeamSolver` built the
1330        // same way, and classify the matrix that failed solve retained.
1331        let mut beam = BeamSolver::from_model(&f.inner)?;
1332        assert!(
1333            beam.solve_configured().is_err(),
1334            "the identical solve must also fail"
1335        );
1336        let retained = beam
1337            .reduced_system()
1338            .expect("a failed solve still retains the condensed system it factorised");
1339        assert_eq!(
1340            f.classify(retained),
1341            expected,
1342            "the diagnosis must come from the solver's retained K_ff"
1343        );
1344        Ok(())
1345    }
1346
1347    /// A diagnosis that adds nothing (`Stable`) or is absent leaves the solver
1348    /// error byte-for-byte unchanged; only a mechanism annotates it. This covers
1349    /// the "failure before condensation leaves the error untouched" case: a
1350    /// missing diagnosis (`None`) is a no-op.
1351    #[test]
1352    fn diagnosis_only_annotates_mechanism_errors() {
1353        use crate::fea::solver::SolverError;
1354        let err = || FemError::from(SolverError::SingularMatrix("singular matrix".to_string()));
1355        let untouched = err().to_string();
1356        assert_eq!(
1357            with_structural_diagnosis(err(), None).to_string(),
1358            untouched
1359        );
1360        assert_eq!(
1361            with_structural_diagnosis(err(), Some(StructuralDiagnostic::Stable)).to_string(),
1362            untouched
1363        );
1364        let mechanism = StructuralDiagnostic::Mechanism { n_free: 4, rank: 3 };
1365        let annotated = with_structural_diagnosis(err(), Some(mechanism));
1366        assert!(
1367            matches!(annotated, FemError::SolverError { .. }),
1368            "the error variant must be preserved"
1369        );
1370        assert_eq!(
1371            annotated.to_string(),
1372            format!("{untouched}; structural diagnosis: {mechanism}")
1373        );
1374    }
1375
1376    /// A model with **every** DOF restrained condenses to a 0x0 reduced system.
1377    /// The verdict is `Stable` (no free DOF means no mechanism) and the probe
1378    /// must not panic on the empty matrix / zero scale.
1379    #[test]
1380    fn fully_restrained_model_is_stable_and_does_not_panic() -> Result<(), FemError> {
1381        let mut f = FrameModel::new();
1382        let a = f.add_node(0.0, 0.0)?;
1383        let b = f.add_node(2.0, 0.0)?;
1384        f.add_member(a, b, steel(), sec())?;
1385        f.fix(a)?;
1386        f.fix(b)?;
1387
1388        let mut beam = BeamSolver::from_model(&f.inner)?;
1389        let reduced = beam.condense();
1390        assert_eq!(reduced.k_ff().n, 0, "every DOF is restrained");
1391        assert!(reduced.free_to_global().is_empty());
1392        assert_eq!(f.classify(reduced), StructuralDiagnostic::Stable);
1393
1394        // The public diagnostic agrees, and the fully prescribed solve is a
1395        // clean success - no panic, no mechanism claim.
1396        assert_eq!(f.diagnostic()?, StructuralDiagnostic::Stable);
1397        let result = f.solve()?;
1398        assert_eq!(result.displacement(a, Dof::Ux)?, 0.0);
1399        assert_eq!(result.displacement(b, Dof::Rz)?, 0.0);
1400        Ok(())
1401    }
1402
1403    /// `condense()` is idempotent: repeated calls return the already-retained
1404    /// system (the same object, no re-condensation). `BeamSolver` has no mutator
1405    /// that can change the assembled system, so the cache cannot go stale.
1406    #[test]
1407    fn condense_is_idempotent_and_retained() -> Result<(), FemError> {
1408        let mut f = FrameModel::new();
1409        let base = f.add_node(0.0, 0.0)?;
1410        let tip = f.add_node(2.0, 0.0)?;
1411        f.add_member(base, tip, steel(), sec())?;
1412        f.fix(base)?;
1413
1414        let mut beam = BeamSolver::from_model(&f.inner)?;
1415        assert!(beam.reduced_system().is_none(), "nothing condensed yet");
1416
1417        let first = beam.condense() as *const ReducedSystem;
1418        let second = beam.condense() as *const ReducedSystem;
1419        assert_eq!(
1420            first, second,
1421            "repeated condense() must return the retained system, not rebuild it"
1422        );
1423
1424        // A solve refreshes the retained system in place; after it, `condense()`
1425        // returns that retained object rather than re-condensing.
1426        beam.solve_configured()?;
1427        let after_k = beam
1428            .reduced_system()
1429            .expect("retained after a successful solve")
1430            .k_ff()
1431            .clone();
1432        let after_ptr = beam.reduced_system().unwrap() as *const ReducedSystem;
1433        assert_eq!(after_k.n, 3, "cantilever tip has 3 free DOFs");
1434        assert_eq!(
1435            beam.condense() as *const ReducedSystem,
1436            after_ptr,
1437            "condense() after a solve still returns the retained system"
1438        );
1439
1440        // `set_solver` only chooses a backend; it cannot invalidate `K_ff`. The
1441        // retained content is unchanged across it.
1442        beam.set_solver(SolverSelection::Auto);
1443        let again = beam.condense();
1444        assert_eq!(again.k_ff().n, after_k.n);
1445        for i in 0..after_k.n {
1446            for j in 0..after_k.n {
1447                assert_eq!(
1448                    again.k_ff().get(i, j),
1449                    after_k.get(i, j),
1450                    "K_ff entry ({i},{j}) changed without a model change"
1451                );
1452            }
1453        }
1454        Ok(())
1455    }
1456}
1457
1458// ---------------------------------------------------------------------------
1459// Equilibrium tolerance: relative, scale/unit invariant, never absolute
1460// ---------------------------------------------------------------------------
1461#[cfg(test)]
1462mod equilibrium_tolerance_tests {
1463    use super::*;
1464
1465    /// Build a report with the given residuals and raw magnitudes. The
1466    /// conditioning floor is left at `0.0`, so the effective tolerance is
1467    /// exactly `EQUILIBRIUM_REL_TOL`: these tests exercise the scale/unit
1468    /// behaviour, not the conditioning relief (which has its own module below).
1469    fn report(
1470        fx_residual: f64,
1471        fy_residual: f64,
1472        mz_residual: f64,
1473        f_mag: f64,
1474        m_mag: f64,
1475        l_char: f64,
1476    ) -> EquilibriumReport {
1477        let (f_scale, _) = equilibrium_scales(f_mag, m_mag, l_char);
1478        EquilibriumReport {
1479            fx_residual,
1480            fy_residual,
1481            mz_residual,
1482            applied_fx: 0.0,
1483            applied_fy: 0.0,
1484            applied_mz: 0.0,
1485            reaction_fx: 0.0,
1486            reaction_fy: 0.0,
1487            reaction_mz: 0.0,
1488            tolerance: EQUILIBRIUM_REL_TOL * f_scale,
1489            f_mag,
1490            m_mag,
1491            l_char,
1492            cond_rel_floor: 0.0,
1493        }
1494    }
1495
1496    #[test]
1497    fn force_and_moment_scales_are_unit_invariant() {
1498        // Same physical state: 2e6 N of force, 5e2 m lever arm, zero net moment.
1499        let (f_si, m_si) = equilibrium_scales(2.0e6, 0.0, 5.0e2);
1500        assert_eq!(f_si, 2.0e6);
1501        assert_eq!(m_si, 1.0e9);
1502        // kN / mm: force 2e3 kN, lever arm 5e5 mm.
1503        let (f_kmm, m_kmm) = equilibrium_scales(2.0e3, 0.0, 5.0e5);
1504        assert_eq!(f_kmm, 2.0e3);
1505        // 1e9 kN·mm == 1e9 N·m: the moment scale is the same physical quantity.
1506        assert_eq!(m_kmm, m_si);
1507    }
1508
1509    #[test]
1510    fn moment_scale_is_non_degenerate_with_zero_applied_moment() {
1511        // Forces present but `applied_mz == 0`: the moment scale must not
1512        // collapse to a constant (the old `|applied_mz|`-only definition did).
1513        let (_, m_scale) = equilibrium_scales(2.0e6, 0.0, 5.0e2);
1514        assert_eq!(m_scale, 2.0e6 * 5.0e2);
1515        assert!(m_scale > 0.0);
1516    }
1517
1518    #[test]
1519    fn scales_vanish_only_when_nothing_is_present() {
1520        assert_eq!(equilibrium_scales(0.0, 0.0, 5.0e2), (0.0, 0.0));
1521        assert_eq!(equilibrium_scales(0.0, 0.0, 0.0), (0.0, 0.0));
1522    }
1523
1524    #[test]
1525    fn unloaded_report_is_balanced_only_with_exact_zero_residual() {
1526        assert!(report(0.0, 0.0, 0.0, 0.0, 0.0, 5.0e2).is_balanced());
1527        assert!(!report(0.0, 0.0, f64::MIN_POSITIVE, 0.0, 0.0, 5.0e2).is_balanced());
1528        assert!(!report(f64::MIN_POSITIVE, 0.0, 0.0, 0.0, 0.0, 5.0e2).is_balanced());
1529    }
1530
1531    #[test]
1532    fn corrupted_reaction_is_still_rejected() {
1533        // No over-relaxation: the relative bound must still reject a genuine
1534        // imbalance, while accepting round-off.
1535        let (f_scale, m_scale) = equilibrium_scales(1.0e6, 0.0, 5.0e2);
1536        assert!(
1537            report(
1538                1e-15 * f_scale,
1539                1e-15 * f_scale,
1540                1e-15 * m_scale,
1541                1.0e6,
1542                0.0,
1543                5.0e2
1544            )
1545            .is_balanced()
1546        );
1547        assert!(
1548            !report(
1549                1e-3 * f_scale,
1550                1e-3 * f_scale,
1551                1e-3 * m_scale,
1552                1.0e6,
1553                0.0,
1554                5.0e2
1555            )
1556            .is_balanced()
1557        );
1558    }
1559
1560    /// Build a report with an explicit conditioning floor, so the anti-masking
1561    /// test can exercise `cond_rel_floor > 0` directly.
1562    fn report_with_cond(
1563        fx_residual: f64,
1564        fy_residual: f64,
1565        mz_residual: f64,
1566        f_mag: f64,
1567        m_mag: f64,
1568        l_char: f64,
1569        cond_rel_floor: f64,
1570    ) -> EquilibriumReport {
1571        let (f_scale, _) = equilibrium_scales(f_mag, m_mag, l_char);
1572        let rel = EQUILIBRIUM_REL_TOL.max(cond_rel_floor);
1573        EquilibriumReport {
1574            fx_residual,
1575            fy_residual,
1576            mz_residual,
1577            applied_fx: 0.0,
1578            applied_fy: 0.0,
1579            applied_mz: 0.0,
1580            reaction_fx: 0.0,
1581            reaction_fy: 0.0,
1582            reaction_mz: 0.0,
1583            tolerance: rel * f_scale,
1584            f_mag,
1585            m_mag,
1586            l_char,
1587            cond_rel_floor,
1588        }
1589    }
1590
1591    #[test]
1592    fn conditioning_floor_accepts_roundoff_rejects_genuine_imbalance() {
1593        // A slender frame: λ² ≈ 2.5e14, so the conditioning floor dominates.
1594        // cond_floor = 1e-2 · 2.5e14 · ε ≈ 5.55e-4.
1595        let lambda_sq = 2.5e14;
1596        let cond_floor = EQUILIBRIUM_COND_FACTOR * lambda_sq * f64::EPSILON;
1597        assert!(
1598            cond_floor > EQUILIBRIUM_REL_TOL,
1599            "this test needs a floor above the base tolerance"
1600        );
1601
1602        let (f_scale, m_scale) = equilibrium_scales(1.0e12, 0.0, 5.0e5);
1603
1604        // (a) Residual at 10% of the conditioning floor: pure round-off,
1605        //     must be accepted.
1606        assert!(
1607            report_with_cond(
1608                0.1 * cond_floor * f_scale,
1609                0.1 * cond_floor * f_scale,
1610                0.1 * cond_floor * m_scale,
1611                1.0e12,
1612                0.0,
1613                5.0e5,
1614                cond_floor
1615            )
1616            .is_balanced(),
1617            "round-off below the conditioning floor must be accepted"
1618        );
1619
1620        // (b) Residual at 10× the conditioning floor: a genuine imbalance,
1621        //     must be rejected — the floor must not mask it.
1622        assert!(
1623            !report_with_cond(
1624                10.0 * cond_floor * f_scale,
1625                10.0 * cond_floor * f_scale,
1626                10.0 * cond_floor * m_scale,
1627                1.0e12,
1628                0.0,
1629                5.0e5,
1630                cond_floor
1631            )
1632            .is_balanced(),
1633            "imbalance above the conditioning floor must be rejected"
1634        );
1635    }
1636
1637    #[test]
1638    fn conditioning_floor_is_dimensionless_and_unit_invariant() {
1639        // λ² = L²·A/I is dimensionless: the same physical element expressed in
1640        // SI (m, m², m⁴) and kN/mm (mm, mm², mm⁴) gives the same λ².
1641        let l_si = 1.0e6_f64;
1642        let a_si = 5.0e-3_f64;
1643        let i_si = 2.0e-5_f64;
1644        let lambda_sq_si = l_si * l_si * a_si / i_si;
1645
1646        let l_kmm = 1.0e9_f64; // 1e6 m = 1e9 mm
1647        let a_kmm = 5.0e3_f64; // 5e-3 m² = 5e3 mm²
1648        let i_kmm = 2.0e7_f64; // 2e-5 m⁴ = 2e7 mm⁴
1649        let lambda_sq_kmm = l_kmm * l_kmm * a_kmm / i_kmm;
1650
1651        // The two values differ only by round-off in the multiplications.
1652        let avg = 0.5 * (lambda_sq_si + lambda_sq_kmm);
1653        assert!(
1654            (lambda_sq_si - lambda_sq_kmm).abs() <= 10.0 * f64::EPSILON * avg,
1655            "λ² must be unit-invariant (SI={}, kN/mm={})",
1656            lambda_sq_si,
1657            lambda_sq_kmm
1658        );
1659    }
1660}