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    /// [`FemError::ConflictingPrescribedDisplacement`] if any of the node's
441    /// DOFs already has a conflicting prescribed value.
442    pub fn fix(&mut self, node: NodeHandle) -> Result<(), FemError> {
443        let i = self.check_node(node)?;
444        self.inner.try_fix_node(i)
445    }
446
447    /// Pin a node: restrain `ux` and `uy`, leave the rotation free.
448    ///
449    /// # Errors
450    ///
451    /// [`FemError::InvalidNode`] if the handle is not valid.
452    /// [`FemError::ConflictingPrescribedDisplacement`] if either `ux` or `uy`
453    /// already has a conflicting prescribed value.
454    pub fn pin(&mut self, node: NodeHandle) -> Result<(), FemError> {
455        let i = self.check_node(node)?;
456        self.inner.try_fix_dof(i, Dof::Ux.index(), 0.0)?;
457        self.inner.try_fix_dof(i, Dof::Uy.index(), 0.0)
458    }
459
460    /// Roller restraining the vertical translation (`uy = 0`), horizontal free.
461    ///
462    /// # Errors
463    ///
464    /// [`FemError::InvalidNode`] if the handle is not valid.
465    /// [`FemError::ConflictingPrescribedDisplacement`] if `uy` already has a
466    /// conflicting prescribed value.
467    pub fn roller_y(&mut self, node: NodeHandle) -> Result<(), FemError> {
468        let i = self.check_node(node)?;
469        self.inner.try_fix_dof(i, Dof::Uy.index(), 0.0)
470    }
471
472    /// Roller restraining the horizontal translation (`ux = 0`), vertical free.
473    ///
474    /// # Errors
475    ///
476    /// [`FemError::InvalidNode`] if the handle is not valid.
477    /// [`FemError::ConflictingPrescribedDisplacement`] if `ux` already has a
478    /// conflicting prescribed value.
479    pub fn roller_x(&mut self, node: NodeHandle) -> Result<(), FemError> {
480        let i = self.check_node(node)?;
481        self.inner.try_fix_dof(i, Dof::Ux.index(), 0.0)
482    }
483
484    /// Prescribe a DOF to an arbitrary finite value (e.g. a support settlement).
485    ///
486    /// Applied through the existing static condensation
487    /// (`K_ff u_f = f_f - K_fc u_c`); no penalty constraints are used.
488    ///
489    /// If the DOF was previously constrained (e.g. by [`fix`](Self::fix)),
490    /// the existing prescription is **replaced** — this allows the common
491    /// workflow of fixing a support node and then applying a settlement.
492    ///
493    /// # Errors
494    ///
495    /// [`FemError::InvalidNode`] if the handle is not valid.
496    /// [`FemError::InvalidInput`] if `value` is not finite.
497    pub fn restrain(&mut self, node: NodeHandle, dof: Dof, value: f64) -> Result<(), FemError> {
498        let i = self.check_node(node)?;
499        self.inner.try_override(i, dof, value)
500    }
501
502    /// Apply a **global** nodal force `(fx, fy)`.
503    ///
504    /// # Errors
505    ///
506    /// [`FemError::InvalidNode`] if the handle is not valid, or
507    /// [`FemError::InvalidInput`] if either component is non-finite. Both
508    /// components are validated **before** either is recorded, so a rejected
509    /// call leaves the model unchanged (no half-applied load).
510    pub fn nodal_load(&mut self, node: NodeHandle, fx: f64, fy: f64) -> Result<(), FemError> {
511        let i = self.check_node(node)?;
512        if !fx.is_finite() {
513            return Err(FemError::InvalidInput(format!(
514                "nodal force Fx must be finite, got {fx}"
515            )));
516        }
517        if !fy.is_finite() {
518            return Err(FemError::InvalidInput(format!(
519                "nodal force Fy must be finite, got {fy}"
520            )));
521        }
522        self.inner.try_add_nodal_force(i, Dof::Ux.index(), fx)?;
523        self.inner.try_add_nodal_force(i, Dof::Uy.index(), fy)
524    }
525
526    /// Apply a **global** nodal moment `mz` (counter-clockwise positive).
527    ///
528    /// # Errors
529    ///
530    /// [`FemError::InvalidNode`] if the handle is not valid.
531    pub fn nodal_moment(&mut self, node: NodeHandle, mz: f64) -> Result<(), FemError> {
532        let i = self.check_node(node)?;
533        self.inner.add_applied_moment(i, mz)
534    }
535
536    /// Apply a uniform distributed load in the member's **local** axes.
537    ///
538    /// `qy > 0` is upward in local +y; `qx > 0` is tensile (towards `node_j`).
539    /// Repeated calls accumulate on the same member.
540    ///
541    /// # Errors
542    ///
543    /// [`FemError::InvalidMember`] if the handle is not valid.
544    pub fn member_udl(&mut self, member: MemberHandle, qx: f64, qy: f64) -> Result<(), FemError> {
545        let i = self.check_member(member)?;
546        self.inner.add_distributed_load(i, qx, qy)
547    }
548
549    /// Apply a point load in the member's **local** axes at normalised position
550    /// `xi in [0, 1]`.
551    ///
552    /// `xi = 0` / `xi = 1` places the load at a node; it is applied exactly once
553    /// (no double counting).
554    ///
555    /// # Errors
556    ///
557    /// [`FemError::InvalidMember`] if the handle is not valid.
558    pub fn member_point_load(
559        &mut self,
560        member: MemberHandle,
561        xi: f64,
562        fx: f64,
563        fy: f64,
564        mz: f64,
565    ) -> Result<(), FemError> {
566        let i = self.check_member(member)?;
567        self.inner.add_point_load(i, xi, fx, fy, mz)
568    }
569
570    /// Solve with automatic solver selection.
571    ///
572    /// Equivalent to `self.solve_with(SolverSelection::Auto)`. The registry
573    /// inspects the condensed stiffness matrix and picks a backend (dense for
574    /// small systems, skyline LDLᵀ for symmetric positive-definite, sparse LU
575    /// otherwise). The selected solver is used exactly once; if it fails the
576    /// error is returned directly — there is no automatic retry with a
577    /// different backend.
578    pub fn solve(&self) -> Result<FrameAnalysisResult, FemError> {
579        self.solve_with(SolverSelection::Auto)
580    }
581
582    /// Solve with an explicit backend selection.
583    ///
584    /// Validates the model (see [`Self::validate`]) before assembling, so
585    /// structural modelling errors are reported as targeted diagnostics rather
586    /// than as a matrix singularity.
587    ///
588    /// **Solver semantics**:
589    /// - [`SolverSelection::Auto`] — the registry inspects the matrix and
590    ///   selects a backend. The chosen solver is used exactly once; if it
591    ///   fails, the error is returned directly (no automatic retry with a
592    ///   different backend).
593    /// - [`SolverSelection::Named`] — the requested solver is used **only**;
594    ///   no silent fallback. If the solver is unavailable or fails, the error
595    ///   is returned directly. Use the convenience constructors
596    ///   [`SolverSelection::dense`], [`SolverSelection::skyline_ldlt`],
597    ///   [`SolverSelection::sparse_lu`], [`SolverSelection::cg`],
598    ///   [`SolverSelection::iccg`] for typed selection.
599    ///
600    /// After solving, [`FrameAnalysisResult::solver_name`] reports which
601    /// backend was actually used.
602    pub fn solve_with(&self, selection: SolverSelection) -> Result<FrameAnalysisResult, FemError> {
603        FrameSolver::new(self).with_selection(selection).solve()
604    }
605
606    /// A solver builder for this frame (configure a backend, then solve).
607    pub fn solver(&self) -> FrameSolver<'_> {
608        FrameSolver::new(self)
609    }
610
611    /// Validate the structural model.
612    ///
613    /// Checks, in order:
614    ///
615    /// 1. the model is not empty (at least one node and one member);
616    /// 2. no **orphan nodes** - every node is used by at least one member;
617    /// 3. the members form a **single connected component**.
618    ///
619    /// Per-element checks (zero length, duplicate connectivity, invalid
620    /// material/section) are enforced when the member is added.
621    ///
622    /// Insufficient restraint is *not* diagnosed here: [`Self::diagnostic`]
623    /// classifies the boundary-conditioned system separately, without
624    /// rejecting the model, and [`FrameSolver::solve`] attaches that
625    /// classification to the solver error when the solve fails.
626    pub fn validate(&self) -> Result<(), FemError> {
627        let inner = &self.inner;
628        if inner.nodes.is_empty() {
629            return Err(FemError::InvalidModel(
630                "frame has no nodes; add at least one node and one member".to_string(),
631            ));
632        }
633        if inner.elements.is_empty() {
634            return Err(FemError::InvalidModel(
635                "frame has no members; add at least one member".to_string(),
636            ));
637        }
638
639        let mut used = vec![false; inner.nodes.len()];
640        for e in &inner.elements {
641            used[e.node_i] = true;
642            used[e.node_j] = true;
643        }
644        if let Some(i) = used.iter().position(|u| !u) {
645            let p = inner.nodes[i].point();
646            return Err(FemError::OrphanNode(format!(
647                "node {i} at ({}, {}) is not connected to any member",
648                p.x, p.y
649            )));
650        }
651
652        let components = count_components(inner.nodes.len(), &inner.elements);
653        if components > 1 {
654            return Err(FemError::DisconnectedStructure(format!(
655                "frame has {components} disconnected components; a single connected \
656                 structural system is required"
657            )));
658        }
659        Ok(())
660    }
661
662    /// Diagnose the **boundary-conditioned** (reduced) system without solving
663    /// it: is this structure stable, under-restrained (rigid-body mechanism),
664    /// internally rank deficient (mechanism), or merely numerically
665    /// ill-conditioned?
666    ///
667    /// The diagnosis reads the reduced free-free stiffness block `K_ff` that
668    /// the **actual solve path** condenses (`BeamSolver::condense`) — the exact
669    /// matrix a solve factorises, not a second assembly — and classifies it with
670    /// relative, scale-invariant probes (see [`crate::fea::mechanism`] for the
671    /// criterion and its limits). It never assembles with penalties, never
672    /// perturbs the matrix and never fabricates displacements, and it does not
673    /// run as part of a successful [`Self::solve`].
674    ///
675    /// The verdict is a property of the **structure**, not of the loads: the
676    /// load vector is not consulted, so scaling or omitting the loads cannot
677    /// change the result.
678    ///
679    /// # Errors
680    ///
681    /// The same model errors as [`Self::solve`]: [`Self::validate`] plus the
682    /// construction checks [`BeamSolver::from_model`] performs (its error
683    /// surface is slightly wider than `validate` alone).
684    pub fn diagnostic(&self) -> Result<StructuralDiagnostic, FemError> {
685        self.validate()?;
686        let mut beam = BeamSolver::from_model(&self.inner)?;
687        Ok(self.classify(beam.condense()))
688    }
689
690    /// Classify a reduced (boundary-conditioned) stiffness system using this
691    /// model's geometry: the global rigid-body motions are built in *reduced*
692    /// order from the solver's own free-DOF map, so no independent reassembly
693    /// of `K_ff` is involved.
694    fn classify(&self, reduced: &ReducedSystem) -> StructuralDiagnostic {
695        let rigid = self.rigid_candidates(reduced.free_to_global());
696        diagnose_reduced(reduced.k_ff(), &rigid)
697    }
698
699    /// The three global rigid-body motions (Tx, Ty, Rz) restricted to the free
700    /// DOFs, laid out in reduced order.
701    ///
702    /// `free_to_global[r]` is the global DOF (`3 * node + dof`) of reduced index
703    /// `r`; constrained entries are dropped, not displaced. Rotation by `theta`
704    /// about the global origin is `ux = -theta*y`, `uy = theta*x`, `rz = theta`.
705    fn rigid_candidates(&self, free_to_global: &[usize]) -> Vec<Vec<f64>> {
706        let n_free = free_to_global.len();
707        let mut tx = vec![0.0; n_free];
708        let mut ty = vec![0.0; n_free];
709        let mut rz = vec![0.0; n_free];
710        for (r, &global) in free_to_global.iter().enumerate() {
711            let point = self.inner.nodes[global / 3].point();
712            match global % 3 {
713                0 => {
714                    tx[r] = 1.0;
715                    rz[r] = -point.y;
716                }
717                1 => {
718                    ty[r] = 1.0;
719                    rz[r] = point.x;
720                }
721                _ => rz[r] = 1.0,
722            }
723        }
724        vec![tx, ty, rz]
725    }
726
727    /// Handle of the node with the given index.
728    ///
729    /// # Errors
730    ///
731    /// [`FemError::InvalidNode`] if the index is out of range.
732    pub fn node_handle(&self, index: usize) -> Result<NodeHandle, FemError> {
733        if index >= self.inner.nodes.len() {
734            return Err(FemError::InvalidNode(format!(
735                "node index {index} is out of range (max: {})",
736                self.inner.nodes.len().saturating_sub(1)
737            )));
738        }
739        Ok(NodeHandle(index))
740    }
741
742    /// Handle of the member with the given index.
743    ///
744    /// # Errors
745    ///
746    /// [`FemError::InvalidMember`] if the index is out of range.
747    pub fn member_handle(&self, index: usize) -> Result<MemberHandle, FemError> {
748        if index >= self.inner.elements.len() {
749            return Err(FemError::InvalidMember(format!(
750                "member index {index} is out of range (max: {})",
751                self.inner.elements.len().saturating_sub(1)
752            )));
753        }
754        Ok(MemberHandle(index))
755    }
756
757    fn check_node(&self, node: NodeHandle) -> Result<usize, FemError> {
758        if node.0 >= self.inner.nodes.len() {
759            return Err(FemError::InvalidNode(format!(
760                "node handle {} is not valid for this frame (max: {})",
761                node.0,
762                self.inner.nodes.len().saturating_sub(1)
763            )));
764        }
765        Ok(node.0)
766    }
767
768    fn check_member(&self, member: MemberHandle) -> Result<usize, FemError> {
769        if member.0 >= self.inner.elements.len() {
770            return Err(FemError::InvalidMember(format!(
771                "member handle {} is not valid for this frame (max: {})",
772                member.0,
773                self.inner.elements.len().saturating_sub(1)
774            )));
775        }
776        Ok(member.0)
777    }
778}
779
780/// Number of connected components of the member connectivity graph.
781fn count_components(n_nodes: usize, elements: &[BeamElement]) -> usize {
782    let mut adj: Vec<Vec<usize>> = vec![Vec::new(); n_nodes];
783    for e in elements {
784        adj[e.node_i].push(e.node_j);
785        adj[e.node_j].push(e.node_i);
786    }
787    let mut seen = vec![false; n_nodes];
788    let mut components = 0;
789    for start in 0..n_nodes {
790        if seen[start] || adj[start].is_empty() {
791            continue;
792        }
793        components += 1;
794        seen[start] = true;
795        let mut queue = VecDeque::from([start]);
796        while let Some(u) = queue.pop_front() {
797            for &v in &adj[u] {
798                if !seen[v] {
799                    seen[v] = true;
800                    queue.push_back(v);
801                }
802            }
803        }
804    }
805    components
806}
807
808// ---------------------------------------------------------------------------
809// FrameSolver
810// ---------------------------------------------------------------------------
811
812/// Solves a [`FrameModel`]; configure the backend, then [`FrameSolver::solve`].
813pub struct FrameSolver<'a> {
814    model: &'a FrameModel,
815    selection: SolverSelection,
816}
817
818impl<'a> FrameSolver<'a> {
819    /// Create a solver for `model` using automatic backend selection.
820    pub fn new(model: &'a FrameModel) -> Self {
821        Self {
822            model,
823            selection: SolverSelection::Auto,
824        }
825    }
826
827    /// Choose an explicit backend (or [`SolverSelection::Auto`]).
828    pub fn with_selection(mut self, selection: SolverSelection) -> Self {
829        self.selection = selection;
830        self
831    }
832
833    /// Set the backend (builder-style alternative to [`Self::with_selection`]).
834    pub fn set_solver(&mut self, selection: SolverSelection) {
835        self.selection = selection;
836    }
837
838    /// Validate, assemble and solve the frame.
839    ///
840    /// A successful solve runs **no** diagnostic and its numerical path is
841    /// unchanged (see [`FrameModel::diagnostic`] for the on-demand API). Only a
842    /// *failed* solve additionally classifies the reduced system, and appends
843    /// that classification to the error message so an under-restrained or
844    /// rank-deficient frame is not reported as an opaque "singular matrix".
845    ///
846    /// # Errors
847    ///
848    /// Model-structure errors from [`FrameModel::validate`] plus any
849    /// [`FemError::SolverError`] from the linear solver (e.g. insufficient
850    /// restraint, or a conditioning limit at extreme scales). The variant is
851    /// unchanged; the message carries the diagnosis.
852    pub fn solve(&self) -> Result<FrameAnalysisResult, FemError> {
853        self.model.validate()?;
854        let mut beam = BeamSolver::from_model(&self.model.inner)?;
855        beam.set_solver(self.selection.clone());
856        if let Err(e) = beam.solve_configured() {
857            // The solver condensed the boundary conditions before attempting any
858            // backend, so its retained reduced system is the exact matrix the
859            // failed factorisation saw - no second assembly.
860            let diagnosis = beam.reduced_system().map(|rs| self.model.classify(rs));
861            return Err(with_structural_diagnosis(e, diagnosis));
862        }
863        Ok(FrameAnalysisResult {
864            beam,
865            model: self.model.clone(),
866        })
867    }
868}
869
870/// Record the structural diagnosis of a failed solve in the error message.
871///
872/// The error **variant** is deliberately preserved (`SolverError` stays
873/// `SolverError`): the diagnosis is extra information, not a re-typing of the
874/// failure, so no existing caller or exhaustive match changes meaning. A
875/// `Stable` diagnosis adds nothing - the failure was not structural - and a
876/// missing diagnosis (`None`, i.e. no reduced system was available) leaves the
877/// error untouched.
878fn with_structural_diagnosis(err: FemError, diagnosis: Option<StructuralDiagnostic>) -> FemError {
879    match (err, diagnosis) {
880        (FemError::SolverError { source, message }, Some(d))
881            if !matches!(d, StructuralDiagnostic::Stable) =>
882        {
883            FemError::SolverError {
884                source,
885                message: format!("{message}; structural diagnosis: {d}"),
886            }
887        }
888        (other, _) => other,
889    }
890}
891
892// ---------------------------------------------------------------------------
893// FrameAnalysisResult
894// ---------------------------------------------------------------------------
895
896/// Solved frame: frame-level access to displacements, reactions, member end
897/// forces and global equilibrium.
898///
899/// All values come from the existing [`BeamSolver`]; nothing is recomputed with
900/// a second formulation.
901pub struct FrameAnalysisResult {
902    beam: BeamSolver,
903    model: FrameModel,
904}
905
906impl std::fmt::Debug for FrameAnalysisResult {
907    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
908        f.debug_struct("FrameAnalysisResult")
909            .field("nodes", &self.model.n_nodes())
910            .field("members", &self.model.n_members())
911            .field("solver", &self.beam.solver_name())
912            .finish_non_exhaustive()
913    }
914}
915
916impl FrameAnalysisResult {
917    /// Name of the backend used by the successful solve.
918    pub fn solver_name(&self) -> Option<&str> {
919        self.beam.solver_name()
920    }
921
922    /// Number of nodes in the solved frame.
923    pub fn n_nodes(&self) -> usize {
924        self.model.n_nodes()
925    }
926
927    /// Number of members in the solved frame.
928    pub fn n_members(&self) -> usize {
929        self.model.n_members()
930    }
931
932    /// Full global displacement vector, laid out `[ux, uy, rz]` per node.
933    pub fn displacements(&self) -> &[f64] {
934        self.beam.displacements()
935    }
936
937    /// Global support reactions, laid out `[Rx, Ry, Mz]` per node.
938    pub fn reactions(&self) -> Vec<f64> {
939        self.beam.reactions()
940    }
941
942    /// Displacement of a DOF at a node (global).
943    ///
944    /// # Errors
945    ///
946    /// [`FemError::InvalidNode`] if the handle is not valid for this frame.
947    pub fn displacement(&self, node: NodeHandle, dof: Dof) -> Result<f64, FemError> {
948        self.check_node(node)?;
949        self.beam.displacement_dof(node.index(), dof)
950    }
951
952    /// Support reaction of a DOF at a node (global).
953    ///
954    /// Free DOFs report the raw (round-off) residual, exactly as
955    /// [`BeamSolver::reaction_dof`] does.
956    ///
957    /// # Errors
958    ///
959    /// [`FemError::InvalidNode`] if the handle is not valid for this frame.
960    pub fn reaction(&self, node: NodeHandle, dof: Dof) -> Result<f64, FemError> {
961        self.check_node(node)?;
962        self.beam.reaction_dof(node.index(), dof)
963    }
964
965    /// Member end forces in **local** axes:
966    /// `[N_i, V_i, M_i, N_j, V_j, M_j]`.
967    ///
968    /// These are element-on-node forces, `f_end = f_equiv - K_e u_e`, exactly as
969    /// documented in `docs/beam_fem.md`; the sign convention is **not** inverted
970    /// for the frame API.
971    ///
972    /// # Errors
973    ///
974    /// [`FemError::InvalidMember`] if the handle is not valid for this frame.
975    pub fn member_end_forces(&self, member: MemberHandle) -> Result<[f64; 6], FemError> {
976        let i = self.check_member(member)?;
977        let all = self.beam.element_end_forces()?;
978        all.get(i)
979            .copied()
980            .ok_or_else(|| FemError::InvalidMember(format!("member handle {} is out of range", i)))
981    }
982
983    /// Member end forces transformed to **global** axes
984    /// (`f_global = Tᵀ f_local`).
985    ///
986    /// # Errors
987    ///
988    /// [`FemError::InvalidMember`] if the handle is not valid for this frame.
989    pub fn member_end_forces_global(&self, member: MemberHandle) -> Result<[f64; 6], FemError> {
990        let i = self.check_member(member)?;
991        let all = self.beam.element_end_forces_global()?;
992        all.get(i)
993            .copied()
994            .ok_or_else(|| FemError::InvalidMember(format!("member handle {} is out of range", i)))
995    }
996
997    /// Global equilibrium check about the origin `(0, 0)`.
998    ///
999    /// Combines support reactions, global nodal loads and moments, and the
1000    /// global resultants of member distributed and point loads (transformed from
1001    /// member-local axes and applied at their true global locations).
1002    /// See [`EquilibriumReport`].
1003    pub fn equilibrium(&self) -> EquilibriumReport {
1004        let m = &self.model.inner;
1005        let mut applied_fx = 0.0;
1006        let mut applied_fy = 0.0;
1007        let mut applied_mz = 0.0;
1008        // Absolute per-term magnitudes (not resultants): a load pair that cancels
1009        // in the sum must still contribute to the equilibrium scale.
1010        let mut applied_f_mag = 0.0;
1011        let mut applied_m_mag = 0.0;
1012
1013        // Global nodal loads and moments.
1014        for (node, dof, v) in &m.nodal_forces {
1015            let p = m.nodes[*node].point();
1016            match *dof {
1017                0 => {
1018                    applied_fx += v;
1019                    applied_mz += -p.y * v;
1020                    applied_f_mag += v.abs();
1021                }
1022                1 => {
1023                    applied_fy += v;
1024                    applied_mz += p.x * v;
1025                    applied_f_mag += v.abs();
1026                }
1027                _ => {
1028                    applied_mz += v;
1029                    applied_m_mag += v.abs();
1030                }
1031            }
1032        }
1033        for am in &m.applied_moments {
1034            applied_mz += am.value;
1035            applied_m_mag += am.value.abs();
1036        }
1037
1038        // Member load resultants, rotated from local to global.
1039        for (elem_idx, dl) in m.distributed_loads.iter().enumerate() {
1040            let _ = elem_idx;
1041            let Some((pi, pj)) = member_points(m, dl.element_idx) else {
1042                continue;
1043            };
1044            let (dx, dy) = (pj.x - pi.x, pj.y - pi.y);
1045            let len = (dx * dx + dy * dy).sqrt();
1046            let (c, s) = (dx / len, dy / len);
1047            let (lfx, lfy) = (dl.qx * len, dl.qy * len);
1048            let (gx, gy) = (c * lfx - s * lfy, s * lfx + c * lfy);
1049            let (xm, ym) = (pi.x + 0.5 * dx, pi.y + 0.5 * dy);
1050            applied_fx += gx;
1051            applied_fy += gy;
1052            applied_mz += xm * gy - ym * gx;
1053            applied_f_mag += gx.abs() + gy.abs();
1054        }
1055        for pl in &m.point_loads {
1056            let Some((pi, _)) = member_points(m, pl.element_idx) else {
1057                continue;
1058            };
1059            let el = &m.elements[pl.element_idx];
1060            let pj = m.nodes[el.node_j].point();
1061            let (dx, dy) = (pj.x - pi.x, pj.y - pi.y);
1062            let len = (dx * dx + dy * dy).sqrt();
1063            let (c, s) = (dx / len, dy / len);
1064            let (gx, gy) = (c * pl.fx - s * pl.fy, s * pl.fx + c * pl.fy);
1065            let (xp, yp) = (pi.x + pl.position * dx, pi.y + pl.position * dy);
1066            applied_fx += gx;
1067            applied_fy += gy;
1068            applied_mz += xp * gy - yp * gx + pl.mz;
1069            applied_f_mag += gx.abs() + gy.abs();
1070            applied_m_mag += pl.mz.abs();
1071        }
1072
1073        // Support reactions, per node.
1074        let reactions = self.beam.reactions();
1075        let mut reaction_fx = 0.0;
1076        let mut reaction_fy = 0.0;
1077        let mut reaction_mz = 0.0;
1078        let mut reaction_f_mag = 0.0;
1079        let mut reaction_m_mag = 0.0;
1080        for (idx, node) in m.nodes.iter().enumerate() {
1081            let p = node.point();
1082            let rx = reactions.get(3 * idx).copied().unwrap_or(0.0);
1083            let ry = reactions.get(3 * idx + 1).copied().unwrap_or(0.0);
1084            let rz = reactions.get(3 * idx + 2).copied().unwrap_or(0.0);
1085            reaction_fx += rx;
1086            reaction_fy += ry;
1087            reaction_mz += p.x * ry - p.y * rx + rz;
1088            reaction_f_mag += rx.abs() + ry.abs();
1089            reaction_m_mag += rz.abs();
1090        }
1091
1092        // Characteristic length of the structure: the largest absolute nodal
1093        // coordinate. Positive for any solvable model (a zero-length member is
1094        // rejected). It is what makes the moment scale `Σ|F|·l_char` reflect the
1095        // structure rather than a constant.
1096        let l_char = characteristic_length(m);
1097        let f_mag = applied_f_mag + reaction_f_mag;
1098        let m_mag = applied_m_mag + reaction_m_mag;
1099        let cond_rel_floor = EQUILIBRIUM_COND_FACTOR * max_element_slenderness_sq(m) * f64::EPSILON;
1100        let rel = EQUILIBRIUM_REL_TOL.max(cond_rel_floor);
1101        let (f_scale, _m_scale) = equilibrium_scales(f_mag, m_mag, l_char);
1102
1103        EquilibriumReport {
1104            fx_residual: applied_fx + reaction_fx,
1105            fy_residual: applied_fy + reaction_fy,
1106            mz_residual: applied_mz + reaction_mz,
1107            applied_fx,
1108            applied_fy,
1109            applied_mz,
1110            reaction_fx,
1111            reaction_fy,
1112            reaction_mz,
1113            tolerance: rel * f_scale,
1114            f_mag,
1115            m_mag,
1116            l_char,
1117            cond_rel_floor,
1118        }
1119    }
1120
1121    fn check_node(&self, node: NodeHandle) -> Result<(), FemError> {
1122        if node.index() >= self.model.n_nodes() {
1123            return Err(FemError::InvalidNode(format!(
1124                "node handle {} is not valid for this result (max: {})",
1125                node.index(),
1126                self.model.n_nodes().saturating_sub(1)
1127            )));
1128        }
1129        Ok(())
1130    }
1131
1132    fn check_member(&self, member: MemberHandle) -> Result<usize, FemError> {
1133        if member.index() >= self.model.n_members() {
1134            return Err(FemError::InvalidMember(format!(
1135                "member handle {} is not valid for this result (max: {})",
1136                member.index(),
1137                self.model.n_members().saturating_sub(1)
1138            )));
1139        }
1140        Ok(member.index())
1141    }
1142}
1143
1144/// End-point coordinates of a member, or `None` if the index is out of range.
1145fn member_points(
1146    model: &BeamModel,
1147    member: usize,
1148) -> Option<(crate::geometry::Point, crate::geometry::Point)> {
1149    let el = model.elements.get(member)?;
1150    Some((
1151        model.nodes[el.node_i].point(),
1152        model.nodes[el.node_j].point(),
1153    ))
1154}
1155
1156/// Characteristic length of the model: the largest absolute nodal coordinate.
1157///
1158/// The equilibrium moments are summed **about the origin**, so the length that
1159/// relates the force and moment scales must be measured from the origin too —
1160/// not a translation-invariant span. `0.0` for an empty model.
1161fn characteristic_length(model: &BeamModel) -> f64 {
1162    let mut l_char: f64 = 0.0;
1163    for node in &model.nodes {
1164        let p = node.point();
1165        l_char = l_char.max(p.x.abs()).max(p.y.abs());
1166    }
1167    l_char
1168}
1169
1170/// Maximum element slenderness squared `λ² = L²·A/I` over all members.
1171///
1172/// This is a dimensionless element-level conditioning proxy for an
1173/// Euler–Bernoulli stiffness matrix: the forward error of a direct solve is
1174/// `O(λ²·ε)`, and the recovered reactions inherit that error, so equilibrium
1175/// residuals of a physically balanced frame can legitimately reach the same
1176/// relative magnitude. It is not a strict bound on the full assembled frame
1177/// stiffness matrix condition number.
1178///
1179/// Only elements with `I > 0` contribute to the maximum; elements with
1180/// non-positive `second_moment` are skipped (defensive guard, since
1181/// `BeamSection::new` does not validate `I`). Returns `0.0` for an empty model
1182/// or when no element has `I > 0`.
1183///
1184/// **Dimensionless and unit-invariant**: `L²·A/I` has units `m²·m²/m⁴ = 1`, and
1185/// a consistent change of length/area/inertia units multiplies numerator and
1186/// denominator by the same power, leaving the ratio unchanged. This is what
1187/// lets the conditioning floor feed a *relative* tolerance without breaking
1188/// unit invariance of the verdict.
1189fn max_element_slenderness_sq(model: &BeamModel) -> f64 {
1190    let mut lambda_sq: f64 = 0.0;
1191    for el in &model.elements {
1192        let p_i = model.nodes[el.node_i].point();
1193        let p_j = model.nodes[el.node_j].point();
1194        let l = el.length(p_i, p_j);
1195        let i = el.section.second_moment;
1196        if i > 0.0 {
1197            lambda_sq = lambda_sq.max(l * l * el.section.area / i);
1198        }
1199    }
1200    lambda_sq
1201}
1202
1203// ---------------------------------------------------------------------------
1204// Single-source guarantee: the diagnostic reads the solver's condensed system
1205// ---------------------------------------------------------------------------
1206//
1207// These are in-crate tests on purpose: `tests/*.rs` are integration tests and
1208// cannot see `pub(crate)` items such as `BeamSolver::condense` /
1209// `FrameModel::classify`, so this guarantee is not testable from there.
1210#[cfg(test)]
1211mod reduced_system_single_source_tests {
1212    use super::*;
1213    use crate::fea::SparseMatrix;
1214
1215    fn steel() -> Material {
1216        Material::new(200e9, 0.3, 7850.0, "Steel")
1217    }
1218
1219    fn sec() -> BeamSection {
1220        BeamSection::new(5e-3, 2e-5)
1221    }
1222
1223    /// The diagnostic must classify exactly the system the solver's own
1224    /// condensation produced: reading the live solver and the public API must
1225    /// agree on every structure in the battery.
1226    fn assert_agrees(f: &FrameModel, label: &str) -> Result<(), FemError> {
1227        let mut beam = BeamSolver::from_model(&f.inner)?;
1228        let from_solver = f.classify(beam.condense());
1229        assert_eq!(
1230            from_solver,
1231            f.diagnostic()?,
1232            "{label}: diagnostic disagrees with the solver's condensed system"
1233        );
1234        Ok(())
1235    }
1236
1237    /// Two-column portal: `base1 - top1 - top2 - base2`, with the given supports
1238    /// on the two base nodes.
1239    fn portal(base_1: &[Dof], base_2: &[Dof]) -> Result<FrameModel, FemError> {
1240        let mut f = FrameModel::new();
1241        let b1 = f.add_node(0.0, 0.0)?;
1242        let t1 = f.add_node(0.0, 3.0)?;
1243        let t2 = f.add_node(4.0, 3.0)?;
1244        let b2 = f.add_node(4.0, 0.0)?;
1245        f.add_member(b1, t1, steel(), sec())?;
1246        f.add_member(t1, t2, steel(), sec())?;
1247        f.add_member(b2, t2, steel(), sec())?;
1248        for dof in base_1 {
1249            f.restrain(b1, *dof, 0.0)?;
1250        }
1251        for dof in base_2 {
1252            f.restrain(b2, *dof, 0.0)?;
1253        }
1254        Ok(f)
1255    }
1256
1257    #[test]
1258    fn diagnostic_classifies_the_solver_condensed_system() -> Result<(), FemError> {
1259        // Completely free beam - three rigid-body modes.
1260        let mut free = FrameModel::new();
1261        let a = free.add_node(0.0, 0.0)?;
1262        let b = free.add_node(2.0, 0.0)?;
1263        free.add_member(a, b, steel(), sec())?;
1264        assert_agrees(&free, "free beam")?;
1265
1266        // One DOF restrained - still under-constrained.
1267        let mut one = FrameModel::new();
1268        let a = one.add_node(0.0, 0.0)?;
1269        let b = one.add_node(2.0, 0.0)?;
1270        one.add_member(a, b, steel(), sec())?;
1271        one.restrain(a, Dof::Ux, 0.0)?;
1272        assert_agrees(&one, "one-DOF-restrained beam")?;
1273
1274        // Stable cantilever.
1275        let mut cant = FrameModel::new();
1276        let base = cant.add_node(0.0, 0.0)?;
1277        let tip = cant.add_node(2.0, 0.0)?;
1278        cant.add_member(base, tip, steel(), sec())?;
1279        cant.fix(base)?;
1280        assert_agrees(&cant, "stable cantilever")?;
1281
1282        // Portal with several support sets, stable and deficient.
1283        let fixed = portal(&[Dof::Ux, Dof::Uy, Dof::Rz], &[Dof::Ux, Dof::Uy, Dof::Rz])?;
1284        assert_agrees(&fixed, "portal, both bases fixed")?;
1285        let pinned = portal(&[Dof::Ux, Dof::Uy], &[Dof::Ux, Dof::Uy])?;
1286        assert_agrees(&pinned, "portal, both bases pinned")?;
1287        let roller = portal(&[Dof::Ux, Dof::Uy, Dof::Rz], &[Dof::Uy])?;
1288        assert_agrees(&roller, "portal, fixed base + roller")?;
1289        let mechanism = portal(&[Dof::Ux, Dof::Uy], &[])?;
1290        assert_agrees(&mechanism, "portal, single pin (mechanism)")?;
1291
1292        Ok(())
1293    }
1294
1295    #[test]
1296    fn diagnostic_uses_the_supplied_matrix_not_a_copy() -> Result<(), FemError> {
1297        let mut f = FrameModel::new();
1298        let base = f.add_node(0.0, 0.0)?;
1299        let tip = f.add_node(2.0, 0.0)?;
1300        f.add_member(base, tip, steel(), sec())?;
1301        f.fix(base)?;
1302
1303        let mut beam = BeamSolver::from_model(&f.inner)?;
1304        let real = beam.condense().clone();
1305        let stable = f.classify(&real);
1306        assert_eq!(
1307            stable,
1308            StructuralDiagnostic::Stable,
1309            "control must be stable"
1310        );
1311
1312        // Forge a reduced system with the first free DOF (tip `ux`) removed. If
1313        // `classify` reassembled its own matrix instead of reading its argument,
1314        // this forgery would have no effect at all.
1315        let n = real.k_ff().n;
1316        let mut forged_k = SparseMatrix::new(n);
1317        for i in 0..n {
1318            for j in 0..n {
1319                let v = real.k_ff().get(i, j);
1320                if i != 0 && j != 0 && v != 0.0 {
1321                    forged_k.add(i, j, v);
1322                }
1323            }
1324        }
1325        forged_k.compress();
1326        let forged = ReducedSystem::new(forged_k, real.free_to_global().to_vec());
1327
1328        let verdict = f.classify(&forged);
1329        assert_ne!(
1330            verdict, stable,
1331            "classify must read the supplied matrix: zeroing a free DOF changed nothing"
1332        );
1333        // The public diagnostic still reads the untouched, real system.
1334        assert_eq!(f.diagnostic()?, stable);
1335        Ok(())
1336    }
1337
1338    /// The failed-solve diagnostic must be driven by the solver's **retained**
1339    /// `K_ff`, not by a reassembly: the frame solve's error carries exactly the
1340    /// verdict that classifying the retained system produces.
1341    #[test]
1342    fn failed_solve_diagnosis_reads_the_solver_retained_system() -> Result<(), FemError> {
1343        // A free beam has the three rigid-body modes and cannot be solved.
1344        let mut f = FrameModel::new();
1345        let a = f.add_node(0.0, 0.0)?;
1346        let b = f.add_node(2.0, 0.0)?;
1347        f.add_member(a, b, steel(), sec())?;
1348
1349        let expected = StructuralDiagnostic::RigidBodyMode {
1350            n_free: 6,
1351            rank: 3,
1352            rigid_modes: 3,
1353        };
1354
1355        // (a) the frame solve fails as a `SolverError` that carries the verdict.
1356        let err = f.solve().expect_err("a free beam must not solve");
1357        match &err {
1358            FemError::SolverError { message, .. } => assert!(
1359                message.contains("structural diagnosis") && message.contains(&expected.to_string()),
1360                "expected the retained-system diagnosis in the error, got {message:?}"
1361            ),
1362            other => panic!("expected SolverError, got {other:?}"),
1363        }
1364
1365        // (b) the verdict is exactly what the solver's retained reduced system
1366        // classifies to: run the identical solve path on a `BeamSolver` built the
1367        // same way, and classify the matrix that failed solve retained.
1368        let mut beam = BeamSolver::from_model(&f.inner)?;
1369        assert!(
1370            beam.solve_configured().is_err(),
1371            "the identical solve must also fail"
1372        );
1373        let retained = beam
1374            .reduced_system()
1375            .expect("a failed solve still retains the condensed system it factorised");
1376        assert_eq!(
1377            f.classify(retained),
1378            expected,
1379            "the diagnosis must come from the solver's retained K_ff"
1380        );
1381        Ok(())
1382    }
1383
1384    /// A diagnosis that adds nothing (`Stable`) or is absent leaves the solver
1385    /// error byte-for-byte unchanged; only a mechanism annotates it. This covers
1386    /// the "failure before condensation leaves the error untouched" case: a
1387    /// missing diagnosis (`None`) is a no-op.
1388    #[test]
1389    fn diagnosis_only_annotates_mechanism_errors() {
1390        use crate::fea::solver::SolverError;
1391        let err = || FemError::from(SolverError::SingularMatrix("singular matrix".to_string()));
1392        let untouched = err().to_string();
1393        assert_eq!(
1394            with_structural_diagnosis(err(), None).to_string(),
1395            untouched
1396        );
1397        assert_eq!(
1398            with_structural_diagnosis(err(), Some(StructuralDiagnostic::Stable)).to_string(),
1399            untouched
1400        );
1401        let mechanism = StructuralDiagnostic::Mechanism { n_free: 4, rank: 3 };
1402        let annotated = with_structural_diagnosis(err(), Some(mechanism));
1403        assert!(
1404            matches!(annotated, FemError::SolverError { .. }),
1405            "the error variant must be preserved"
1406        );
1407        assert_eq!(
1408            annotated.to_string(),
1409            format!("{untouched}; structural diagnosis: {mechanism}")
1410        );
1411    }
1412
1413    /// A model with **every** DOF restrained condenses to a 0x0 reduced system.
1414    /// The verdict is `Stable` (no free DOF means no mechanism) and the probe
1415    /// must not panic on the empty matrix / zero scale.
1416    #[test]
1417    fn fully_restrained_model_is_stable_and_does_not_panic() -> Result<(), FemError> {
1418        let mut f = FrameModel::new();
1419        let a = f.add_node(0.0, 0.0)?;
1420        let b = f.add_node(2.0, 0.0)?;
1421        f.add_member(a, b, steel(), sec())?;
1422        f.fix(a)?;
1423        f.fix(b)?;
1424
1425        let mut beam = BeamSolver::from_model(&f.inner)?;
1426        let reduced = beam.condense();
1427        assert_eq!(reduced.k_ff().n, 0, "every DOF is restrained");
1428        assert!(reduced.free_to_global().is_empty());
1429        assert_eq!(f.classify(reduced), StructuralDiagnostic::Stable);
1430
1431        // The public diagnostic agrees, and the fully prescribed solve is a
1432        // clean success - no panic, no mechanism claim.
1433        assert_eq!(f.diagnostic()?, StructuralDiagnostic::Stable);
1434        let result = f.solve()?;
1435        assert_eq!(result.displacement(a, Dof::Ux)?, 0.0);
1436        assert_eq!(result.displacement(b, Dof::Rz)?, 0.0);
1437        Ok(())
1438    }
1439
1440    /// `condense()` is idempotent: repeated calls return the already-retained
1441    /// system (the same object, no re-condensation). `BeamSolver` has no mutator
1442    /// that can change the assembled system, so the cache cannot go stale.
1443    #[test]
1444    fn condense_is_idempotent_and_retained() -> Result<(), FemError> {
1445        let mut f = FrameModel::new();
1446        let base = f.add_node(0.0, 0.0)?;
1447        let tip = f.add_node(2.0, 0.0)?;
1448        f.add_member(base, tip, steel(), sec())?;
1449        f.fix(base)?;
1450
1451        let mut beam = BeamSolver::from_model(&f.inner)?;
1452        assert!(beam.reduced_system().is_none(), "nothing condensed yet");
1453
1454        let first = beam.condense() as *const ReducedSystem;
1455        let second = beam.condense() as *const ReducedSystem;
1456        assert_eq!(
1457            first, second,
1458            "repeated condense() must return the retained system, not rebuild it"
1459        );
1460
1461        // A solve refreshes the retained system in place; after it, `condense()`
1462        // returns that retained object rather than re-condensing.
1463        beam.solve_configured()?;
1464        let after_k = beam
1465            .reduced_system()
1466            .expect("retained after a successful solve")
1467            .k_ff()
1468            .clone();
1469        let after_ptr = beam.reduced_system().unwrap() as *const ReducedSystem;
1470        assert_eq!(after_k.n, 3, "cantilever tip has 3 free DOFs");
1471        assert_eq!(
1472            beam.condense() as *const ReducedSystem,
1473            after_ptr,
1474            "condense() after a solve still returns the retained system"
1475        );
1476
1477        // `set_solver` only chooses a backend; it cannot invalidate `K_ff`. The
1478        // retained content is unchanged across it.
1479        beam.set_solver(SolverSelection::Auto);
1480        let again = beam.condense();
1481        assert_eq!(again.k_ff().n, after_k.n);
1482        for i in 0..after_k.n {
1483            for j in 0..after_k.n {
1484                assert_eq!(
1485                    again.k_ff().get(i, j),
1486                    after_k.get(i, j),
1487                    "K_ff entry ({i},{j}) changed without a model change"
1488                );
1489            }
1490        }
1491        Ok(())
1492    }
1493}
1494
1495// ---------------------------------------------------------------------------
1496// Equilibrium tolerance: relative, scale/unit invariant, never absolute
1497// ---------------------------------------------------------------------------
1498#[cfg(test)]
1499mod equilibrium_tolerance_tests {
1500    use super::*;
1501
1502    /// Build a report with the given residuals and raw magnitudes. The
1503    /// conditioning floor is left at `0.0`, so the effective tolerance is
1504    /// exactly `EQUILIBRIUM_REL_TOL`: these tests exercise the scale/unit
1505    /// behaviour, not the conditioning relief (which has its own module below).
1506    fn report(
1507        fx_residual: f64,
1508        fy_residual: f64,
1509        mz_residual: f64,
1510        f_mag: f64,
1511        m_mag: f64,
1512        l_char: f64,
1513    ) -> EquilibriumReport {
1514        let (f_scale, _) = equilibrium_scales(f_mag, m_mag, l_char);
1515        EquilibriumReport {
1516            fx_residual,
1517            fy_residual,
1518            mz_residual,
1519            applied_fx: 0.0,
1520            applied_fy: 0.0,
1521            applied_mz: 0.0,
1522            reaction_fx: 0.0,
1523            reaction_fy: 0.0,
1524            reaction_mz: 0.0,
1525            tolerance: EQUILIBRIUM_REL_TOL * f_scale,
1526            f_mag,
1527            m_mag,
1528            l_char,
1529            cond_rel_floor: 0.0,
1530        }
1531    }
1532
1533    #[test]
1534    fn force_and_moment_scales_are_unit_invariant() {
1535        // Same physical state: 2e6 N of force, 5e2 m lever arm, zero net moment.
1536        let (f_si, m_si) = equilibrium_scales(2.0e6, 0.0, 5.0e2);
1537        assert_eq!(f_si, 2.0e6);
1538        assert_eq!(m_si, 1.0e9);
1539        // kN / mm: force 2e3 kN, lever arm 5e5 mm.
1540        let (f_kmm, m_kmm) = equilibrium_scales(2.0e3, 0.0, 5.0e5);
1541        assert_eq!(f_kmm, 2.0e3);
1542        // 1e9 kN·mm == 1e9 N·m: the moment scale is the same physical quantity.
1543        assert_eq!(m_kmm, m_si);
1544    }
1545
1546    #[test]
1547    fn moment_scale_is_non_degenerate_with_zero_applied_moment() {
1548        // Forces present but `applied_mz == 0`: the moment scale must not
1549        // collapse to a constant (the old `|applied_mz|`-only definition did).
1550        let (_, m_scale) = equilibrium_scales(2.0e6, 0.0, 5.0e2);
1551        assert_eq!(m_scale, 2.0e6 * 5.0e2);
1552        assert!(m_scale > 0.0);
1553    }
1554
1555    #[test]
1556    fn scales_vanish_only_when_nothing_is_present() {
1557        assert_eq!(equilibrium_scales(0.0, 0.0, 5.0e2), (0.0, 0.0));
1558        assert_eq!(equilibrium_scales(0.0, 0.0, 0.0), (0.0, 0.0));
1559    }
1560
1561    #[test]
1562    fn unloaded_report_is_balanced_only_with_exact_zero_residual() {
1563        assert!(report(0.0, 0.0, 0.0, 0.0, 0.0, 5.0e2).is_balanced());
1564        assert!(!report(0.0, 0.0, f64::MIN_POSITIVE, 0.0, 0.0, 5.0e2).is_balanced());
1565        assert!(!report(f64::MIN_POSITIVE, 0.0, 0.0, 0.0, 0.0, 5.0e2).is_balanced());
1566    }
1567
1568    #[test]
1569    fn corrupted_reaction_is_still_rejected() {
1570        // No over-relaxation: the relative bound must still reject a genuine
1571        // imbalance, while accepting round-off.
1572        let (f_scale, m_scale) = equilibrium_scales(1.0e6, 0.0, 5.0e2);
1573        assert!(
1574            report(
1575                1e-15 * f_scale,
1576                1e-15 * f_scale,
1577                1e-15 * m_scale,
1578                1.0e6,
1579                0.0,
1580                5.0e2
1581            )
1582            .is_balanced()
1583        );
1584        assert!(
1585            !report(
1586                1e-3 * f_scale,
1587                1e-3 * f_scale,
1588                1e-3 * m_scale,
1589                1.0e6,
1590                0.0,
1591                5.0e2
1592            )
1593            .is_balanced()
1594        );
1595    }
1596
1597    /// Build a report with an explicit conditioning floor, so the anti-masking
1598    /// test can exercise `cond_rel_floor > 0` directly.
1599    fn report_with_cond(
1600        fx_residual: f64,
1601        fy_residual: f64,
1602        mz_residual: f64,
1603        f_mag: f64,
1604        m_mag: f64,
1605        l_char: f64,
1606        cond_rel_floor: f64,
1607    ) -> EquilibriumReport {
1608        let (f_scale, _) = equilibrium_scales(f_mag, m_mag, l_char);
1609        let rel = EQUILIBRIUM_REL_TOL.max(cond_rel_floor);
1610        EquilibriumReport {
1611            fx_residual,
1612            fy_residual,
1613            mz_residual,
1614            applied_fx: 0.0,
1615            applied_fy: 0.0,
1616            applied_mz: 0.0,
1617            reaction_fx: 0.0,
1618            reaction_fy: 0.0,
1619            reaction_mz: 0.0,
1620            tolerance: rel * f_scale,
1621            f_mag,
1622            m_mag,
1623            l_char,
1624            cond_rel_floor,
1625        }
1626    }
1627
1628    #[test]
1629    fn conditioning_floor_accepts_roundoff_rejects_genuine_imbalance() {
1630        // A slender frame: λ² ≈ 2.5e14, so the conditioning floor dominates.
1631        // cond_floor = 1e-2 · 2.5e14 · ε ≈ 5.55e-4.
1632        let lambda_sq = 2.5e14;
1633        let cond_floor = EQUILIBRIUM_COND_FACTOR * lambda_sq * f64::EPSILON;
1634        assert!(
1635            cond_floor > EQUILIBRIUM_REL_TOL,
1636            "this test needs a floor above the base tolerance"
1637        );
1638
1639        let (f_scale, m_scale) = equilibrium_scales(1.0e12, 0.0, 5.0e5);
1640
1641        // (a) Residual at 10% of the conditioning floor: pure round-off,
1642        //     must be accepted.
1643        assert!(
1644            report_with_cond(
1645                0.1 * cond_floor * f_scale,
1646                0.1 * cond_floor * f_scale,
1647                0.1 * cond_floor * m_scale,
1648                1.0e12,
1649                0.0,
1650                5.0e5,
1651                cond_floor
1652            )
1653            .is_balanced(),
1654            "round-off below the conditioning floor must be accepted"
1655        );
1656
1657        // (b) Residual at 10× the conditioning floor: a genuine imbalance,
1658        //     must be rejected — the floor must not mask it.
1659        assert!(
1660            !report_with_cond(
1661                10.0 * cond_floor * f_scale,
1662                10.0 * cond_floor * f_scale,
1663                10.0 * cond_floor * m_scale,
1664                1.0e12,
1665                0.0,
1666                5.0e5,
1667                cond_floor
1668            )
1669            .is_balanced(),
1670            "imbalance above the conditioning floor must be rejected"
1671        );
1672    }
1673
1674    #[test]
1675    fn conditioning_floor_is_dimensionless_and_unit_invariant() {
1676        // λ² = L²·A/I is dimensionless: the same physical element expressed in
1677        // SI (m, m², m⁴) and kN/mm (mm, mm², mm⁴) gives the same λ².
1678        let l_si = 1.0e6_f64;
1679        let a_si = 5.0e-3_f64;
1680        let i_si = 2.0e-5_f64;
1681        let lambda_sq_si = l_si * l_si * a_si / i_si;
1682
1683        let l_kmm = 1.0e9_f64; // 1e6 m = 1e9 mm
1684        let a_kmm = 5.0e3_f64; // 5e-3 m² = 5e3 mm²
1685        let i_kmm = 2.0e7_f64; // 2e-5 m⁴ = 2e7 mm⁴
1686        let lambda_sq_kmm = l_kmm * l_kmm * a_kmm / i_kmm;
1687
1688        // The two values differ only by round-off in the multiplications.
1689        let avg = 0.5 * (lambda_sq_si + lambda_sq_kmm);
1690        assert!(
1691            (lambda_sq_si - lambda_sq_kmm).abs() <= 10.0 * f64::EPSILON * avg,
1692            "λ² must be unit-invariant (SI={}, kN/mm={})",
1693            lambda_sq_si,
1694            lambda_sq_kmm
1695        );
1696    }
1697}