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