Skip to main content

section_properties/
beam_fem.rs

1//! 2D Euler-Bernoulli Beam FEM
2//!
3//! Implements a 2D frame/beam element with 3 DOF per node: [u, v, θ]
4//! where u = axial displacement, v = transverse displacement, θ = rotation.
5//!
6//! The element has 6 DOF total: [u_i, v_j, θ_i, u_j, v_j, θ_j]
7//!
8//! Uses engineering-mnemonic local variable names (`L`, `E`, `A`, `I`, `P`,
9//! `T`, `N1`..`N4`, etc.) throughout, so `non_snake_case` is allowed here.
10#![allow(non_snake_case)]
11
12use crate::fea::{
13    SparseMatrix,
14    solver::{LinearSolver, SolverError, SolverRegistry, SolverSelection},
15};
16use crate::geometry::Point;
17use crate::material::Material;
18
19/// Beam cross-section properties for 2D Euler-Bernoulli beam
20#[derive(Debug, Clone, Copy)]
21pub struct BeamSection {
22    /// Cross-sectional area `m²`
23    pub area: f64,
24    /// Second moment of area about local z-axis (bending in local x-y plane) `m⁴`
25    pub second_moment: f64,
26}
27
28impl BeamSection {
29    /// Create a new beam section
30    pub fn new(area: f64, second_moment: f64) -> Self {
31        Self {
32            area,
33            second_moment,
34        }
35    }
36
37    /// Create from a rectangle section
38    pub fn rectangle(width: f64, height: f64) -> Self {
39        let area = width * height;
40        let second_moment = width * height.powi(3) / 12.0;
41        Self {
42            area,
43            second_moment,
44        }
45    }
46
47    /// Create from a circular section
48    pub fn circle(radius: f64) -> Self {
49        let area = std::f64::consts::PI * radius * radius;
50        let second_moment = std::f64::consts::PI * radius.powi(4) / 4.0;
51        Self {
52            area,
53            second_moment,
54        }
55    }
56
57    /// Create from a circular hollow section
58    pub fn circle_hollow(outer_radius: f64, inner_radius: f64) -> Self {
59        let area =
60            std::f64::consts::PI * (outer_radius * outer_radius - inner_radius * inner_radius);
61        let second_moment =
62            std::f64::consts::PI * (outer_radius.powi(4) - inner_radius.powi(4)) / 4.0;
63        Self {
64            area,
65            second_moment,
66        }
67    }
68
69    /// Create from [`crate::SectionProperties`] for a beam aligned with the
70    /// **global x-axis**.
71    ///
72    /// The second moment of area is `props.ix = ∫y² dA`, which resists
73    /// bending in the global x-y plane about the z-axis — the correct
74    /// inertia for a horizontal member whose local x coincides with global x.
75    ///
76    /// For a vertical member (local x = global y), use
77    /// [`Self::from_section_properties_y`] instead. A blind
78    /// `From<SectionProperties>` implementation is intentionally **not**
79    /// provided because choosing the wrong axis produces silently incorrect
80    /// results.
81    pub fn from_section_properties_x(props: &crate::section_properties::SectionProperties) -> Self {
82        Self {
83            area: props.area,
84            second_moment: props.ix,
85        }
86    }
87
88    /// Create from [`crate::SectionProperties`] for a beam aligned with the
89    /// **global y-axis**.
90    ///
91    /// The second moment of area is `props.iy = ∫x² dA`, which resists
92    /// bending in the global x-y plane about the z-axis — the correct
93    /// inertia for a vertical member whose local x coincides with global y.
94    ///
95    /// For a horizontal member (local x = global x), use
96    /// [`Self::from_section_properties_x`] instead.
97    pub fn from_section_properties_y(props: &crate::section_properties::SectionProperties) -> Self {
98        Self {
99            area: props.area,
100            second_moment: props.iy,
101        }
102    }
103}
104
105/// Internal section forces `N`, `V`, `M` at a point along a beam element.
106///
107/// All quantities below are expressed in the element's LOCAL coordinate
108/// system (see [`BeamElement::local_stiffness`] for the local axes and DOF
109/// ordering).
110///
111/// # Sign convention
112///
113/// - [`axial`](Self::axial): axial internal force, **tension positive** —
114///   positive pulls the material apart along +x, the `node_i -> node_j`
115///   direction.
116/// - [`shear`](Self::shear): transverse shear internal force, defined so that
117///   `d(moment)/dx = shear` and `d(shear)/dx = q`, where `q` is the local
118///   transverse load intensity (positive upward, i.e. local +y). Equivalently,
119///   with `q_down` = downward load per length, `d(shear)/dx = -q_down`.
120/// - [`moment`](Self::moment): bending moment, **sagging positive**
121///   (`moment = E·I·v''` for a horizontal element with local +y up).
122///
123/// These are internal *resultants at a section*, and are a different concept
124/// from the element-on-node equilibrium forces returned by
125/// [`BeamSolver::element_end_forces`]. At the element ends the two are related
126/// by explicit sign factors documented on
127/// [`BeamSolver::element_section_forces`].
128#[derive(Debug, Clone, Copy, PartialEq)]
129pub struct SectionForces {
130    /// Axial internal force (tension positive) `N`
131    pub axial: f64,
132    /// Transverse shear internal force `N`; satisfies `d(moment)/dx = shear`
133    pub shear: f64,
134    /// Bending moment (sagging positive) `Nm`
135    pub moment: f64,
136}
137
138impl SectionForces {
139    /// Create a section-force triple
140    pub fn new(axial: f64, shear: f64, moment: f64) -> Self {
141        Self {
142            axial,
143            shear,
144            moment,
145        }
146    }
147}
148
149/// One sampled point of a beam internal-force diagram.
150///
151/// Produced by [`BeamSolver::sample_element_forces`] and
152/// [`BeamSolver::sample_beam_forces`]. The sample is a thin record over
153/// [`SectionForces`]; the diagram API samples
154/// [`BeamSolver::element_section_forces`] and never interpolates nodal forces.
155///
156/// # Coordinates
157///
158/// - [`element_index`](Self::element_index): element index in the model
159///   (`BeamModel::elements` order).
160/// - [`xi`](Self::xi): element-local normalized coordinate in `[0, 1]`
161///   (`xi = 0` at the element's `node_i`, `xi = 1` at `node_j`).
162/// - [`x`](Self::x): beam arclength measured from the start of element 0
163///   (element 0's `node_i`), accumulated in model order:
164///   `x = Σ_{e < element_index} length(e) + xi · length(element_index)`.
165///   This is a physical beam distance, not an element-local coordinate, so
166///   adjacent elements produce **duplicate** `x` values at a shared node
167///   (element `i` at `xi = 1` and element `i+1` at `xi = 0`). Duplicates are
168///   intentional and are never removed.
169///
170/// # Section forces
171///
172/// [`section_forces`](Self::section_forces) are the beam-LOCAL `N`, `V`, `M`
173/// from [`SectionForces`] (same sign convention; not transformed to global
174/// axes). At an interior point load they follow the existing left-limit
175/// convention of [`BeamSolver::element_section_forces`].
176#[derive(Debug, Clone, Copy, PartialEq)]
177pub struct BeamForceSample {
178    /// Element index in model order.
179    pub element_index: usize,
180    /// Element-local normalized coordinate, `0` at `node_i`, `1` at `node_j`.
181    pub xi: f64,
182    /// Beam arclength from the start of element 0 (see type docs).
183    pub x: f64,
184    /// Local section forces `N`, `V`, `M` at this sample.
185    pub section_forces: SectionForces,
186}
187
188/// A sampled beam internal-force diagram (recoverable via
189/// [`BeamSolver::beam_force_diagram`]).
190///
191/// This is a plain container of [`BeamForceSample`] points in model order. It
192/// deliberately performs **no** interpolation, and exposes no plotting or GUI
193/// functionality; a future visualization layer consumes [`samples`](Self::samples)
194/// (each carrying its own `x` coordinate) directly.
195#[derive(Debug, Clone)]
196pub struct BeamForceDiagram {
197    /// Samples in model order, element by element.
198    pub samples: Vec<BeamForceSample>,
199}
200
201impl BeamForceDiagram {
202    /// Create a diagram from pre-computed samples.
203    pub fn new(samples: Vec<BeamForceSample>) -> Self {
204        Self { samples }
205    }
206
207    /// Axial force `N` at every sample, in `samples` order.
208    pub fn axial(&self) -> Vec<f64> {
209        self.samples
210            .iter()
211            .map(|s| s.section_forces.axial)
212            .collect()
213    }
214
215    /// Shear force `V` at every sample, in `samples` order.
216    pub fn shear(&self) -> Vec<f64> {
217        self.samples
218            .iter()
219            .map(|s| s.section_forces.shear)
220            .collect()
221    }
222
223    /// Bending moment `M` at every sample, in `samples` order.
224    pub fn moment(&self) -> Vec<f64> {
225        self.samples
226            .iter()
227            .map(|s| s.section_forces.moment)
228            .collect()
229    }
230
231    /// Beam arclength `x` at every sample, in `samples` order.
232    pub fn x(&self) -> Vec<f64> {
233        self.samples.iter().map(|s| s.x).collect()
234    }
235}
236
237/// Nodal displacement of a beam node, in the GLOBAL coordinate system.
238///
239/// DOF ordering follows the rest of the beam module: `ux` (global x),
240/// `uy` (global y), `rz` (rotation about global z, counter-clockwise
241/// positive). Values are given in the user's consistent unit system. They are
242/// **not** rotated into element-local axes.
243#[derive(Debug, Clone, Copy, PartialEq)]
244pub struct BeamNodalDisplacement {
245    /// Displacement along global +x.
246    pub ux: f64,
247    /// Displacement along global +y.
248    pub uy: f64,
249    /// Rotation about global +z (counter-clockwise positive).
250    pub rz: f64,
251}
252
253/// External support reaction at a constrained beam node, in the GLOBAL
254/// coordinate system.
255///
256/// A reaction is the force/moment the support supplies to hold a constrained
257/// DOF. It is a different concept from an element-on-node end force
258/// ([`BeamSolver::element_end_forces`]) and from a section internal force
259/// ([`SectionForces`]).
260///
261/// Only constrained DOFs contribute a reaction; unconstrained DOFs are
262/// reported as exactly `0.0` (see [`BeamAnalysisResult::reaction`]). Signs are
263/// such that, at global equilibrium, `Σ reactions + Σ applied loads = 0`.
264#[derive(Debug, Clone, Copy, PartialEq)]
265pub struct BeamReaction {
266    /// Reaction force along global +x.
267    pub fx: f64,
268    /// Reaction force along global +y.
269    pub fy: f64,
270    /// Reaction moment about global +z (counter-clockwise positive).
271    pub mz: f64,
272}
273
274/// Unified, read-only result view of an already-solved [`BeamSolver`].
275///
276/// Create one with [`BeamSolver::results`]. It is a thin **aggregation /
277/// delegation layer**: every quantity is produced by the existing solver
278/// methods, and none of the FEM mathematics is reimplemented here.
279///
280/// # When the solve happens
281///
282/// Constructing a `BeamAnalysisResult` does **not** solve anything. Call
283/// [`BeamSolver::solve`] first; the result reflects the solver's current
284/// displacement state.
285///
286/// # The three force concepts (kept distinct on purpose)
287///
288/// 1. **Support reaction** — [`BeamReaction`] / [`Self::reaction`]: the
289///    external force supplied by a *support* at a constrained DOF (global
290///    coordinates).
291/// 2. **Element-on-node end force** — [`Self::element_end_forces`]: the 6
292///    element equilibrium forces `[N_i, V_i, M_i, N_j, V_j, M_j]` acting at an
293///    element's two nodes (local coordinates).
294/// 3. **Section internal force** — [`Self::section_forces`]: the internal
295///    resultants `N`, `V`, `M` at an arbitrary point `xi` inside an element
296///    (local coordinates).
297///
298/// These are intentionally exposed through different types/methods and must
299/// not be conflated.
300///
301/// # Ownership / cost
302///
303/// The result borrows the solver (`&BeamSolver`) and snapshots the reaction
304/// vector once at construction; it never copies stiffness matrices. Accessors
305/// are cheap: displacements are O(1), reactions are O(1) lookups into the
306/// snapshot, and element/section/sampling calls delegate to the solver (they
307/// perform the same work as the corresponding solver methods).
308#[derive(Clone)]
309pub struct BeamAnalysisResult<'a> {
310    solver: &'a BeamSolver,
311    /// Global reaction snapshot, length `n_dof`, with unconstrained DOFs set
312    /// to exactly zero.
313    reactions: Vec<f64>,
314}
315
316impl std::fmt::Debug for BeamAnalysisResult<'_> {
317    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
318        f.debug_struct("BeamAnalysisResult")
319            .field("nodes", &self.solver.model.nodes.len())
320            .field("elements", &self.solver.model.elements.len())
321            .finish_non_exhaustive()
322    }
323}
324
325impl<'a> BeamAnalysisResult<'a> {
326    /// Number of nodes in the analysed model.
327    pub fn n_nodes(&self) -> usize {
328        self.solver.model.nodes.len()
329    }
330
331    /// Number of elements in the analysed model.
332    pub fn n_elements(&self) -> usize {
333        self.solver.model.elements.len()
334    }
335
336    /// Name of the linear-solver backend used by the solve that produced this
337    /// result (`"dense"`, `"skyline_ldlt"`, `"sparse_lu"`, `"cg"`, `"iccg"`,
338    /// ...), or `None` if no linear system was solved (e.g. fully constrained).
339    pub fn solver_name(&self) -> Option<&str> {
340        self.solver.solver_name()
341    }
342
343    /// Raw global displacement vector, DOF-ordered
344    /// `[ux0, uy0, rz0, ux1, uy1, rz1, ...]`.
345    ///
346    /// This is a borrowed view into the solver (no copy).
347    pub fn displacements(&self) -> &[f64] {
348        &self.solver.u_global
349    }
350
351    /// Nodal displacement (GLOBAL) at `node_index`.
352    ///
353    /// # Errors
354    ///
355    /// [`FemError::InvalidInput`] if `node_index` is out of bounds.
356    pub fn displacement(&self, node_index: usize) -> Result<BeamNodalDisplacement, FemError> {
357        if node_index >= self.solver.model.nodes.len() {
358            return Err(FemError::InvalidInput(format!(
359                "Invalid node index: {} (max: {})",
360                node_index,
361                self.solver.model.nodes.len().saturating_sub(1)
362            )));
363        }
364        Ok(BeamNodalDisplacement {
365            ux: self.solver.displacement(node_index, 0)?,
366            uy: self.solver.displacement(node_index, 1)?,
367            rz: self.solver.displacement(node_index, 2)?,
368        })
369    }
370
371    /// Support reaction (GLOBAL) at `node_index`.
372    ///
373    /// Only constrained DOFs carry a value; unconstrained DOFs are reported as
374    /// exactly `0.0` (the raw residual `K·u - f` at a free DOF is numerical
375    /// round-off and is not a physical support reaction). At a node that is not
376    /// a support, all three components are therefore `0.0`.
377    ///
378    /// # Errors
379    ///
380    /// [`FemError::InvalidInput`] if `node_index` is out of bounds.
381    pub fn reaction(&self, node_index: usize) -> Result<BeamReaction, FemError> {
382        if node_index >= self.solver.model.nodes.len() {
383            return Err(FemError::InvalidInput(format!(
384                "Invalid node index: {} (max: {})",
385                node_index,
386                self.solver.model.nodes.len().saturating_sub(1)
387            )));
388        }
389        let base = self.solver.model.dof_index(node_index, 0);
390        Ok(BeamReaction {
391            fx: self.reactions[base],
392            fy: self.reactions[base + 1],
393            mz: self.reactions[base + 2],
394        })
395    }
396
397    /// Element-on-node end forces in LOCAL coordinates for `element_index`:
398    /// `[N_i, V_i, M_i, N_j, V_j, M_j]`.
399    ///
400    /// Delegates to the same recovery used by
401    /// [`BeamSolver::element_end_forces`].
402    ///
403    /// # Errors
404    ///
405    /// [`FemError::InvalidInput`] if `element_index` is out of bounds.
406    pub fn element_end_forces(&self, element_index: usize) -> Result<[f64; 6], FemError> {
407        self.solver.element_on_node_end_forces_local(element_index)
408    }
409
410    /// Section internal forces `N`, `V`, `M` (LOCAL) at `(element_index, xi)`.
411    ///
412    /// Thin delegation to [`BeamSolver::element_section_forces`] (single
413    /// source of truth for the N/V/M equations).
414    ///
415    /// # Errors
416    ///
417    /// Same as [`BeamSolver::element_section_forces`].
418    pub fn section_forces(&self, element_index: usize, xi: f64) -> Result<SectionForces, FemError> {
419        self.solver.element_section_forces(element_index, xi)
420    }
421
422    /// Whole-beam force samples (Phase 2.5).
423    ///
424    /// Delegates to [`BeamSolver::sample_beam_forces`].
425    ///
426    /// # Errors
427    ///
428    /// Same as [`BeamSolver::sample_beam_forces`].
429    pub fn sample_forces(&self, n_per_element: usize) -> Result<Vec<BeamForceSample>, FemError> {
430        self.solver.sample_beam_forces(n_per_element)
431    }
432
433    /// Whole-beam force diagram (Phase 2.5).
434    ///
435    /// Delegates to [`BeamSolver::beam_force_diagram`].
436    ///
437    /// # Errors
438    ///
439    /// Same as [`BeamSolver::beam_force_diagram`].
440    pub fn diagram(&self, n_per_element: usize) -> Result<BeamForceDiagram, FemError> {
441        self.solver.beam_force_diagram(n_per_element)
442    }
443}
444
445/// 2D Euler–Bernoulli beam element between two nodes.
446///
447/// Local axes: x from `node_i` to `node_j`, y transverse (positive up), with
448/// counter-clockwise rotation. Element end forces are ordered
449/// `[N_i, V_i, M_i, N_j, V_j, M_j]` in these local axes; see
450/// [`BeamSolver::element_end_forces`] for the recovery formula.
451#[derive(Debug, Clone)]
452pub struct BeamElement {
453    /// Node i index
454    pub node_i: usize,
455    /// Node j index
456    pub node_j: usize,
457    /// Material
458    pub material: Material,
459    /// Cross-section properties
460    pub section: BeamSection,
461}
462
463impl BeamElement {
464    /// Create a new beam element
465    pub fn new(
466        node_i: usize,
467        node_j: usize,
468        material: Material,
469        section: BeamSection,
470    ) -> Result<Self, FemError> {
471        if node_i == node_j {
472            return Err(FemError::InvalidModel(
473                "Beam element cannot have same start and end node".to_string(),
474            ));
475        }
476        Ok(Self {
477            node_i,
478            node_j,
479            material,
480            section,
481        })
482    }
483
484    /// Get element length from node coordinates
485    pub fn length(&self, node_i: Point, node_j: Point) -> f64 {
486        let dx = node_j.x - node_i.x;
487        let dy = node_j.y - node_i.y;
488        (dx * dx + dy * dy).sqrt()
489    }
490
491    /// Compute local stiffness matrix (6x6) in local coordinates
492    ///
493    /// Local DOF ordering: [u_i, v_i, θ_i, u_j, v_j, θ_j]
494    ///
495    /// Returns a 6x6 matrix in row-major order (`Vec<Vec<f64>>`)
496    pub fn local_stiffness(&self, node_i: Point, node_j: Point) -> [[f64; 6]; 6] {
497        let L = self.length(node_i, node_j);
498        if L <= 0.0 {
499            return [[0.0; 6]; 6];
500        }
501
502        let E = self.material.youngs_modulus;
503        let A = self.section.area;
504        let I = self.section.second_moment;
505
506        let EA_L = E * A / L;
507        let EI_L3 = E * I / L.powi(3);
508        let EI_L2 = E * I / L.powi(2);
509        let EI_L = E * I / L;
510
511        // Standard 2D Euler-Bernoulli beam stiffness matrix
512        // DOF order: [u_i, v_i, θ_i, u_j, v_j, θ_j]
513        let mut k = [[0.0; 6]; 6];
514
515        // Axial terms
516        k[0][0] = EA_L;
517        k[0][3] = -EA_L;
518        k[3][0] = -EA_L;
519        k[3][3] = EA_L;
520
521        // Bending terms
522        // v_i terms
523        k[1][1] = 12.0 * EI_L3;
524        k[1][2] = 6.0 * EI_L2;
525        k[1][4] = -12.0 * EI_L3;
526        k[1][5] = 6.0 * EI_L2;
527
528        // θ_i terms
529        k[2][1] = 6.0 * EI_L2;
530        k[2][2] = 4.0 * EI_L;
531        k[2][4] = -6.0 * EI_L2;
532        k[2][5] = 2.0 * EI_L;
533
534        // v_j terms
535        k[4][1] = -12.0 * EI_L3;
536        k[4][2] = -6.0 * EI_L2;
537        k[4][4] = 12.0 * EI_L3;
538        k[4][5] = -6.0 * EI_L2;
539
540        // θ_j terms
541        k[5][1] = 6.0 * EI_L2;
542        k[5][2] = 2.0 * EI_L;
543        k[5][4] = -6.0 * EI_L2;
544        k[5][5] = 4.0 * EI_L;
545
546        k
547    }
548
549    /// Compute coordinate transformation matrix (6x6)
550    ///
551    /// Transforms from local to global coordinates
552    /// Local DOF: [u_i, v_i, θ_i, u_j, v_j, θ_j]
553    /// Global DOF: [U_i, V_i, Θ_i, U_j, V_j, Θ_j]
554    pub fn transformation_matrix(&self, node_i: Point, node_j: Point) -> [[f64; 6]; 6] {
555        let dx = node_j.x - node_i.x;
556        let dy = node_j.y - node_i.y;
557        let L = (dx * dx + dy * dy).sqrt();
558
559        if L <= 0.0 {
560            return [[0.0; 6]; 6];
561        }
562
563        let c = dx / L;
564        let s = dy / L;
565
566        // Transformation matrix T (6x6)
567        // [ c  s  0  0  0  0 ]
568        // [-s  c  0  0  0  0 ]
569        // [ 0  0  1  0  0  0 ]
570        // [ 0  0  0  c  s  0 ]
571        // [ 0  0  0 -s  c  0 ]
572        // [ 0  0  0  0  0  1 ]
573        let mut T = [[0.0; 6]; 6];
574
575        // Node i block
576        T[0][0] = c;
577        T[0][1] = s;
578        T[1][0] = -s;
579        T[1][1] = c;
580        T[2][2] = 1.0;
581
582        // Node j block
583        T[3][3] = c;
584        T[3][4] = s;
585        T[4][3] = -s;
586        T[4][4] = c;
587        T[5][5] = 1.0;
588
589        T
590    }
591
592    /// Rotate a **global** force (or load-intensity) vector into this element's
593    /// **local** axes.
594    ///
595    /// Distributed loads and point loads are specified in LOCAL coordinates
596    /// (local x along `node_i -> node_j`, local y transverse), while nodal
597    /// forces are global — see `docs/beam_fem.md`. Use this helper when your
598    /// input data is global, e.g.
599    ///
600    /// ```text
601    /// let (qx, qy) = element.to_local_force(ni, nj, gx, gy)?;
602    /// model.add_distributed_load(elem, qx, qy)?;
603    /// ```
604    ///
605    /// A load intensity (N/m) transforms exactly like a force (N), so the same
606    /// helper applies to both. This is a pure coordinate rotation: it changes
607    /// no FEM convention and performs no calculation on the model.
608    pub fn to_local_force(&self, node_i: Point, node_j: Point, gx: f64, gy: f64) -> (f64, f64) {
609        let t = self.transformation_matrix(node_i, node_j);
610        // u_local = T · u_global, restricted to the translational block:
611        //   fx_local =  c·gx + s·gy
612        //   fy_local = -s·gx + c·gy
613        (t[0][0] * gx + t[0][1] * gy, t[1][0] * gx + t[1][1] * gy)
614    }
615
616    /// Element stiffness matrix (6x6) in **GLOBAL** coordinates.
617    ///
618    /// `k_global = Tᵀ · k_local · T`, with the DOF order
619    /// `[ux_i, uy_i, rz_i, ux_j, uy_j, rz_j]` (global axes).
620    pub fn global_stiffness(&self, node_i: Point, node_j: Point) -> [[f64; 6]; 6] {
621        let k_local = self.local_stiffness(node_i, node_j);
622        let T = self.transformation_matrix(node_i, node_j);
623
624        // k_global = T^T * k_local * T
625        let mut k_global = [[0.0; 6]; 6];
626
627        for i in 0..6 {
628            for j in 0..6 {
629                let mut sum = 0.0;
630                for k in 0..6 {
631                    for l in 0..6 {
632                        sum += T[k][i] * k_local[k][l] * T[l][j];
633                    }
634                }
635                k_global[i][j] = sum;
636            }
637        }
638
639        k_global
640    }
641
642    /// Compute consistent nodal load vector for uniform distributed load (6 DOF) in LOCAL coordinates
643    ///
644    /// Local DOF ordering: [u_i, v_i, θ_i, u_j, v_j, θ_j]
645    /// Sign convention:
646    /// - qx > 0: tensile axial load (pulling beam in +x direction)
647    /// - qy > 0: upward transverse load (in +y direction)
648    ///
649    /// Returns a 6-element vector in local coordinates
650    pub fn consistent_nodal_load(
651        &self,
652        node_i: Point,
653        node_j: Point,
654        qx: f64,
655        qy: f64,
656    ) -> Result<[f64; 6], FemError> {
657        let L = self.length(node_i, node_j);
658        if L <= 0.0 {
659            return Err(FemError::InvalidInput(
660                "Beam element has zero or negative length for distributed load".to_string(),
661            ));
662        }
663
664        // Consistent nodal load vector for uniform distributed load
665        // Axial (qx): linear shape functions
666        // f_u_i = qx * L / 2, f_u_j = qx * L / 2
667        //
668        // Transverse (qy): Hermite cubic shape functions
669        // f_v_i = qy * L / 2
670        // f_θ_i = qy * L^2 / 12  (positive = counterclockwise in local coords)
671        // f_v_j = qy * L / 2
672        // f_θ_j = -qy * L^2 / 12 (negative = clockwise in local coords)
673        //
674        // Note: Local v is positive upward, local θ is positive counterclockwise
675        let qx_L2 = qx * L / 2.0;
676        let qy_L2 = qy * L / 2.0;
677        let qy_L2_12 = qy * L * L / 12.0;
678
679        Ok([
680            qx_L2,     // u_i: axial
681            qy_L2,     // v_i: transverse
682            qy_L2_12,  // θ_i: moment (CCW positive)
683            qx_L2,     // u_j: axial
684            qy_L2,     // v_j: transverse
685            -qy_L2_12, // θ_j: moment (CW negative)
686        ])
687    }
688
689    /// Compute consistent nodal load vector for a point load at given position (6 DOF) in LOCAL coordinates
690    ///
691    /// Local DOF ordering: [u_i, v_i, θ_i, u_j, v_j, θ_j]
692    /// Position is measured from node_i (0.0) to node_j (1.0)
693    /// Sign convention:
694    /// - fx > 0: tensile axial force (pulling in +x direction)
695    /// - fy > 0: upward transverse force (in +y direction)
696    /// - mz > 0: counterclockwise moment about z-axis (positive θ direction)
697    ///
698    /// Uses shape functions:
699    /// - Axial: linear shape functions N1 = 1-ξ, N2 = ξ
700    /// - Transverse: Hermite cubic shape functions
701    /// - Moment: shape functions for moment
702    pub fn consistent_nodal_load_point(
703        &self,
704        node_i: Point,
705        node_j: Point,
706        position: f64,
707        fx: f64,
708        fy: f64,
709        mz: f64,
710    ) -> Result<[f64; 6], FemError> {
711        let L = self.length(node_i, node_j);
712        if L <= 0.0 {
713            return Err(FemError::InvalidInput(
714                "Beam element has zero or negative length for point load".to_string(),
715            ));
716        }
717        if !(0.0..=1.0).contains(&position) {
718            return Err(FemError::InvalidInput(format!(
719                "Point load position must be in [0, 1], got {}",
720                position
721            )));
722        }
723
724        let xi = position; // normalized position
725        let one_minus_xi = 1.0 - xi;
726
727        // Axial: linear shape functions
728        // N1 = 1-ξ, N2 = ξ
729        // f_u_i = fx * (1-ξ), f_u_j = fx * ξ
730        let f_u_i = fx * one_minus_xi;
731        let f_u_j = fx * xi;
732
733        // Transverse: Hermite cubic shape functions
734        // N1 = 1 - 3ξ² + 2ξ³
735        // N2 = L(ξ - 2ξ² + ξ³)
736        // N3 = 3ξ² - 2ξ³
737        // N4 = L(-ξ² + ξ³)
738        let xi2 = xi * xi;
739        let xi3 = xi2 * xi;
740
741        let N1 = 1.0 - 3.0 * xi2 + 2.0 * xi3;
742        let N2 = L * (xi - 2.0 * xi2 + xi3);
743        let N3 = 3.0 * xi2 - 2.0 * xi3;
744        let N4 = L * (-xi2 + xi3);
745
746        // f_v_i = fy * N1, f_θ_i = fy * N2
747        // f_v_j = fy * N3, f_θ_j = fy * N4
748        let f_v_i = fy * N1;
749        let f_theta_i = fy * N2;
750        let f_v_j = fy * N3;
751        let f_theta_j = fy * N4;
752
753        // Moment: shape functions for applied moment (from virtual work: δW = M * δθ(x_p))
754        // Rotation shape functions: θ(x) = dN1/dx * v_i + dN2/dx * θ_i + dN3/dx * v_j + dN4/dx * θ_j
755        // M1 = dN1/dx = (6/L)(ξ² - ξ) = -(6/L)ξ(1-ξ)
756        // M2 = dN2/dx = 1 - 4ξ + 3ξ²
757        // M3 = dN3/dx = (6/L)(ξ - ξ²) = (6/L)ξ(1-ξ)
758        // M4 = dN4/dx = -2ξ + 3ξ²
759        // For a point moment mz at ξ, the equivalent nodal loads are:
760        // f_v_i = mz * M1 = -6mz/L * ξ(1-ξ)
761        // f_θ_i = mz * M2 = mz * (1 - 4ξ + 3ξ²)
762        // f_v_j = mz * M3 = 6mz/L * ξ(1-ξ)
763        // f_θ_j = mz * M4 = mz * (-2ξ + 3ξ²)
764        let one_minus_xi = 1.0 - xi;
765        let f_v_i_moment = mz * (-6.0 * xi * one_minus_xi / L); // M1 = -(6/L)ξ(1-ξ)
766        let f_theta_i_moment = mz * (1.0 - 4.0 * xi + 3.0 * xi2); // M2 = 1 - 4ξ + 3ξ²
767        let f_v_j_moment = mz * (6.0 * xi * one_minus_xi / L); // M3 = (6/L)ξ(1-ξ)
768        let f_theta_j_moment = mz * (-2.0 * xi + 3.0 * xi2); // M4 = -2ξ + 3ξ²
769
770        Ok([
771            f_u_i,                        // u_i: axial
772            f_v_i + f_v_i_moment,         // v_i: transverse + moment
773            f_theta_i + f_theta_i_moment, // θ_i: rotation + moment
774            f_u_j,                        // u_j: axial
775            f_v_j + f_v_j_moment,         // v_j: transverse + moment
776            f_theta_j + f_theta_j_moment, // θ_j: rotation + moment
777        ])
778    }
779}
780
781/// Beam node with 3 DOF: [u, v, θ]
782#[derive(Debug, Clone, Copy)]
783pub struct BeamNode {
784    /// Node index
785    pub id: usize,
786    /// X coordinate
787    pub x: f64,
788    /// Y coordinate
789    pub y: f64,
790}
791
792impl BeamNode {
793    pub fn new(id: usize, x: f64, y: f64) -> Self {
794        Self { id, x, y }
795    }
796
797    pub fn point(&self) -> Point {
798        Point::new(self.x, self.y)
799    }
800}
801
802/// Distributed load on a beam element in LOCAL coordinates
803///
804/// Local coordinate system:
805/// - x axis: along beam from node_i to node_j (axial direction)
806/// - y axis: transverse direction (positive v)
807/// - z axis: out of plane (rotation θ about z)
808///
809/// Sign convention:
810/// - qx > 0: tensile axial load (pulling beam in +x direction)
811/// - qy > 0: upward transverse load (in +y direction)
812#[derive(Debug, Clone, Copy)]
813pub struct DistributedLoad {
814    /// Element index (index in elements Vec)
815    pub element_idx: usize,
816    /// Uniform axial load per unit length [N/m] in local x direction
817    pub qx: f64,
818    /// Uniform transverse load per unit length [N/m] in local y direction
819    pub qy: f64,
820}
821
822impl DistributedLoad {
823    /// Create a new distributed load on an element
824    pub fn new(element_idx: usize, qx: f64, qy: f64) -> Self {
825        Self {
826            element_idx,
827            qx,
828            qy,
829        }
830    }
831
832    /// Uniform transverse load only (`qy`), in **LOCAL** element coordinates
833    /// (`qy > 0` upward in local +y).
834    pub fn transverse(element_idx: usize, qy: f64) -> Self {
835        Self {
836            element_idx,
837            qx: 0.0,
838            qy,
839        }
840    }
841
842    /// Uniform axial load only (`qx`), in **LOCAL** element coordinates
843    /// (`qx > 0` tensile, towards `node_j`).
844    pub fn axial(element_idx: usize, qx: f64) -> Self {
845        Self {
846            element_idx,
847            qx,
848            qy: 0.0,
849        }
850    }
851}
852
853/// Point load applied at a specific position along an element in LOCAL coordinates
854///
855/// Local coordinate system:
856/// - x axis: along beam from node_i to node_j (axial direction)
857/// - y axis: transverse direction (positive v)
858/// - z axis: out of plane (rotation θ about z)
859///
860/// Position is measured from node_i (x=0) to node_j (x=L)
861///
862/// Sign convention:
863/// - fx > 0: tensile axial force (pulling in +x direction)
864/// - fy > 0: upward transverse force (in +y direction)
865/// - mz > 0: counterclockwise moment about z-axis (positive θ direction)
866#[derive(Debug, Clone, Copy)]
867pub struct PointLoad {
868    /// Element index (index in elements Vec)
869    pub element_idx: usize,
870    /// Position along element from node_i (0.0 = node_i, 1.0 = node_j)
871    pub position: f64,
872    /// Axial force `N` in local x direction
873    pub fx: f64,
874    /// Transverse force `N` in local y direction
875    pub fy: f64,
876    /// Moment `Nm` about local z axis (positive = CCW)
877    pub mz: f64,
878}
879
880impl PointLoad {
881    /// Create a new point load on an element
882    pub fn new(element_idx: usize, position: f64, fx: f64, fy: f64, mz: f64) -> Self {
883        Self {
884            element_idx,
885            position,
886            fx,
887            fy,
888            mz,
889        }
890    }
891
892    /// Create a transverse point force only, in **LOCAL** element coordinates
893    /// (`fy > 0` upward in local +y).
894    pub fn transverse_force(element_idx: usize, position: f64, fy: f64) -> Self {
895        Self {
896            element_idx,
897            position,
898            fx: 0.0,
899            fy,
900            mz: 0.0,
901        }
902    }
903
904    /// Create an axial point force only, in **LOCAL** element coordinates
905    /// (`fx > 0` tensile, towards `node_j`).
906    pub fn axial_force(element_idx: usize, position: f64, fx: f64) -> Self {
907        Self {
908            element_idx,
909            position,
910            fx,
911            fy: 0.0,
912            mz: 0.0,
913        }
914    }
915
916    /// Create a point moment only, in **LOCAL** element coordinates
917    /// (`mz > 0` counter-clockwise).
918    pub fn moment(element_idx: usize, position: f64, mz: f64) -> Self {
919        Self {
920            element_idx,
921            position,
922            fx: 0.0,
923            fy: 0.0,
924            mz,
925        }
926    }
927}
928
929/// Applied moment at a specific node (in GLOBAL coordinates)
930///
931/// Sign convention:
932/// - value > 0: counterclockwise moment (positive θ direction)
933#[derive(Debug, Clone, Copy)]
934pub struct AppliedMoment {
935    /// Node index (index in nodes Vec)
936    pub node_idx: usize,
937    /// Moment value `Nm` in global coordinates (positive = CCW)
938    pub value: f64,
939}
940
941impl AppliedMoment {
942    pub fn new(node_idx: usize, value: f64) -> Self {
943        Self { node_idx, value }
944    }
945}
946
947/// A single degree of freedom of a beam node.
948///
949/// Ergonomic typed alternative to the raw `0/1/2` DOF indices used by
950/// [`BeamModel::dof_index`] and [`BeamModel::try_fix_dof`]. The mapping is
951/// fixed by the frozen Beam FEM contract (`docs/beam_fem.md`):
952///
953/// ```text
954/// Dof::Ux -> 0   global translation along X
955/// Dof::Uy -> 1   global translation along Y
956/// Dof::Rz -> 2   global rotation about Z, counter-clockwise positive
957/// ```
958///
959/// This is a naming layer only: the internal representation remains
960/// `[ux, uy, rz]` in that order.
961///
962/// # Examples
963///
964/// ```rust
965/// use section_properties::beam_fem::{BeamModel, BeamNode, Dof};
966///
967/// // Explicit, checked DOF references instead of raw 0/1/2 indices:
968/// let mut model = BeamModel::new();
969/// model.add_node(BeamNode::new(0, 0.0, 0.0));
970/// model.try_fix(0, Dof::Uy, 0.0).unwrap();
971///
972/// assert_eq!(Dof::Ux.index(), 0);
973/// assert_eq!(Dof::Uy.index(), 1);
974/// assert_eq!(Dof::Rz.index(), 2);
975/// assert_eq!(Dof::ALL, [Dof::Ux, Dof::Uy, Dof::Rz]);
976/// ```
977#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
978pub enum Dof {
979    /// Global translation along X (`ux`).
980    Ux,
981    /// Global translation along Y (`uy`).
982    Uy,
983    /// Global rotation about Z (`rz`), counter-clockwise positive.
984    Rz,
985}
986
987impl Dof {
988    /// All three DOFs in the canonical ordering `[ux, uy, rz]`.
989    pub const ALL: [Dof; 3] = [Dof::Ux, Dof::Uy, Dof::Rz];
990
991    /// Raw index of this DOF inside a node: `dof(node, d) = 3*node + d`.
992    pub const fn index(self) -> usize {
993        match self {
994            Self::Ux => 0,
995            Self::Uy => 1,
996            Self::Rz => 2,
997        }
998    }
999
1000    /// Human-readable name (`"ux"`, `"uy"`, `"rz"`).
1001    pub const fn name(self) -> &'static str {
1002        match self {
1003            Self::Ux => "ux",
1004            Self::Uy => "uy",
1005            Self::Rz => "rz",
1006        }
1007    }
1008}
1009
1010impl From<Dof> for usize {
1011    fn from(dof: Dof) -> Self {
1012        dof.index()
1013    }
1014}
1015
1016impl TryFrom<usize> for Dof {
1017    type Error = FemError;
1018
1019    /// Convert a raw DOF index into a [`Dof`].
1020    ///
1021    /// # Errors
1022    ///
1023    /// [`FemError::InvalidInput`] if `value` is not 0, 1 or 2.
1024    fn try_from(value: usize) -> Result<Self, FemError> {
1025        match value {
1026            0 => Ok(Self::Ux),
1027            1 => Ok(Self::Uy),
1028            2 => Ok(Self::Rz),
1029            other => Err(FemError::InvalidInput(format!(
1030                "Invalid DOF: {} (must be 0, 1, or 2)",
1031                other
1032            ))),
1033        }
1034    }
1035}
1036
1037/// Beam model with nodes, elements, loads, and boundary conditions.
1038///
1039/// # Conventions
1040///
1041/// - Each node has three **global** DOFs `[ux, uy, rz]`, ordered
1042///   `dof(node, d) = 3*node + d`; `rz` is counter-clockwise positive.
1043/// - Element local x runs from `node_i` to `node_j`, local y is transverse
1044///   (positive up so that local rotation is counter-clockwise).
1045/// - Load coordinate systems differ by kind: [`add_nodal_force`] is global,
1046///   [`add_distributed_load`] and [`add_point_load`] are **local**,
1047///   [`add_applied_moment`] is a **global** `theta` load.
1048///
1049/// # Snapshot semantics
1050///
1051/// [`BeamSolver::from_model`] clones the model and assembles the global
1052/// stiffness matrix and force vector once. Mutating a `BeamModel` after a
1053/// solver has been built does not affect that solver; build a new solver to
1054/// pick up changes. See `docs/beam_fem.md` for the full contract.
1055///
1056/// [`add_nodal_force`]: Self::add_nodal_force
1057/// [`add_distributed_load`]: Self::add_distributed_load
1058/// [`add_point_load`]: Self::add_point_load
1059/// [`add_applied_moment`]: Self::add_applied_moment
1060#[derive(Debug, Clone)]
1061pub struct BeamModel {
1062    /// Nodes
1063    pub nodes: Vec<BeamNode>,
1064    /// Elements
1065    pub elements: Vec<BeamElement>,
1066    /// Nodal forces: (node_idx, dof, value)
1067    /// dof: 0=u, 1=v, 2=θ
1068    /// node_idx is the index in the nodes Vec (0, 1, 2, ...)
1069    pub nodal_forces: Vec<(usize, usize, f64)>,
1070    /// Distributed loads on elements (in LOCAL coordinates)
1071    pub distributed_loads: Vec<DistributedLoad>,
1072    /// Point loads on elements (in LOCAL coordinates)
1073    pub point_loads: Vec<PointLoad>,
1074    /// Applied moments at nodes (in GLOBAL coordinates)
1075    pub applied_moments: Vec<AppliedMoment>,
1076    /// Fixed DOFs: (node_idx, dof, value) - value is the prescribed displacement (usually 0.0)
1077    /// node_idx is the index in the nodes Vec (0, 1, 2, ...)
1078    pub fixed_dofs: Vec<(usize, usize, f64)>,
1079}
1080
1081impl BeamModel {
1082    pub fn new() -> Self {
1083        Self {
1084            nodes: Vec::new(),
1085            elements: Vec::new(),
1086            nodal_forces: Vec::new(),
1087            distributed_loads: Vec::new(),
1088            point_loads: Vec::new(),
1089            applied_moments: Vec::new(),
1090            fixed_dofs: Vec::new(),
1091        }
1092    }
1093
1094    pub fn add_node(&mut self, node: BeamNode) {
1095        self.nodes.push(node);
1096    }
1097
1098    pub fn add_element(&mut self, element: BeamElement) {
1099        self.elements.push(element);
1100    }
1101
1102    /// Add nodal force.
1103    ///
1104    /// Panics if `node_idx` is out of bounds, `dof` is not 0/1/2, or `value`
1105    /// is not finite (programmer error). Use [`Self::try_add_nodal_force`] for
1106    /// a fallible version.
1107    pub fn add_nodal_force(&mut self, node_idx: usize, dof: usize, value: f64) {
1108        self.try_add_nodal_force(node_idx, dof, value)
1109            .unwrap_or_else(|e| panic!("{}", e));
1110    }
1111
1112    /// Fallible counterpart of [`Self::add_nodal_force`]: returns a structured
1113    /// error for an out-of-bounds node index, an invalid DOF (must be 0, 1 or 2),
1114    /// or a non-finite force value, instead of panicking.
1115    pub fn try_add_nodal_force(
1116        &mut self,
1117        node_idx: usize,
1118        dof: usize,
1119        value: f64,
1120    ) -> Result<(), FemError> {
1121        if node_idx >= self.nodes.len() {
1122            return Err(FemError::InvalidInput(format!(
1123                "Invalid node index: {} (max: {})",
1124                node_idx,
1125                self.nodes.len().saturating_sub(1)
1126            )));
1127        }
1128        if dof >= 3 {
1129            return Err(FemError::InvalidInput(format!(
1130                "Invalid DOF: {} (must be 0, 1, or 2)",
1131                dof
1132            )));
1133        }
1134        if !value.is_finite() {
1135            return Err(FemError::InvalidInput(format!(
1136                "Nodal force must be finite, got {}",
1137                value
1138            )));
1139        }
1140        self.nodal_forces.push((node_idx, dof, value));
1141        Ok(())
1142    }
1143
1144    /// Fix a single DOF to a prescribed value.
1145    ///
1146    /// Panics if `node_idx` is out of bounds, `dof` is not 0/1/2, or `value`
1147    /// is not finite (programmer error). Use [`Self::try_fix_dof`] for a
1148    /// fallible version.
1149    pub fn fix_dof(&mut self, node_idx: usize, dof: usize, value: f64) {
1150        self.try_fix_dof(node_idx, dof, value)
1151            .unwrap_or_else(|e| panic!("{}", e));
1152    }
1153
1154    /// Fallible counterpart of [`Self::fix_dof`]: returns a structured error for
1155    /// an out-of-bounds node index, an invalid DOF (must be 0, 1 or 2), or a
1156    /// non-finite prescribed value, instead of panicking.
1157    pub fn try_fix_dof(&mut self, node_idx: usize, dof: usize, value: f64) -> Result<(), FemError> {
1158        if node_idx >= self.nodes.len() {
1159            return Err(FemError::InvalidInput(format!(
1160                "Invalid node index: {} (max: {})",
1161                node_idx,
1162                self.nodes.len().saturating_sub(1)
1163            )));
1164        }
1165        if dof >= 3 {
1166            return Err(FemError::InvalidInput(format!(
1167                "Invalid DOF: {} (must be 0, 1, or 2)",
1168                dof
1169            )));
1170        }
1171        if !value.is_finite() {
1172            return Err(FemError::InvalidInput(format!(
1173                "Prescribed value must be finite, got {}",
1174                value
1175            )));
1176        }
1177        for &(n, d, v) in &self.fixed_dofs {
1178            if n == node_idx && d == dof {
1179                let scale = (v.abs() + value.abs()).max(1.0);
1180                if (v - value).abs() > 1e-12 * scale {
1181                    return Err(FemError::ConflictingPrescribedDisplacement {
1182                        node_idx,
1183                        dof,
1184                        first_value: v,
1185                        conflicting_value: value,
1186                    });
1187                }
1188                return Ok(());
1189            }
1190        }
1191        self.fixed_dofs.push((node_idx, dof, value));
1192        Ok(())
1193    }
1194
1195    /// Override (upsert) a prescribed displacement: if `(node_idx, dof)` is
1196    /// already constrained, replace its value; otherwise add a new constraint.
1197    ///
1198    /// Unlike [`Self::try_fix_dof`], this does **not** detect conflicting
1199    /// values — it silently replaces the previous prescription.  Use this when
1200    /// the caller explicitly intends to override (e.g. applying a support
1201    /// settlement after a full fix).
1202    pub fn try_override_dof(
1203        &mut self,
1204        node_idx: usize,
1205        dof: usize,
1206        value: f64,
1207    ) -> Result<(), FemError> {
1208        if node_idx >= self.nodes.len() {
1209            return Err(FemError::InvalidInput(format!(
1210                "Invalid node index: {} (max: {})",
1211                node_idx,
1212                self.nodes.len().saturating_sub(1)
1213            )));
1214        }
1215        if dof >= 3 {
1216            return Err(FemError::InvalidInput(format!(
1217                "Invalid DOF: {} (must be 0, 1, or 2)",
1218                dof
1219            )));
1220        }
1221        if !value.is_finite() {
1222            return Err(FemError::InvalidInput(format!(
1223                "Prescribed value must be finite, got {}",
1224                value
1225            )));
1226        }
1227        for entry in &mut self.fixed_dofs {
1228            if entry.0 == node_idx && entry.1 == dof {
1229                entry.2 = value;
1230                return Ok(());
1231            }
1232        }
1233        self.fixed_dofs.push((node_idx, dof, value));
1234        Ok(())
1235    }
1236
1237    /// Fix a node completely (all 3 DOFs to 0).
1238    ///
1239    /// Panics if `node_idx` is out of bounds (programmer error). Use
1240    /// [`Self::try_fix_node`] for a fallible version.
1241    pub fn fix_node(&mut self, node_idx: usize) {
1242        self.try_fix_node(node_idx)
1243            .unwrap_or_else(|e| panic!("{}", e));
1244    }
1245
1246    /// Fallible counterpart of [`Self::fix_node`]: returns a structured error
1247    /// for an out-of-bounds node index instead of panicking.
1248    pub fn try_fix_node(&mut self, node_idx: usize) -> Result<(), FemError> {
1249        if node_idx >= self.nodes.len() {
1250            return Err(FemError::InvalidInput(format!(
1251                "Invalid node index: {} (max: {})",
1252                node_idx,
1253                self.nodes.len().saturating_sub(1)
1254            )));
1255        }
1256        self.try_fix_dof(node_idx, 0, 0.0)?;
1257        self.try_fix_dof(node_idx, 1, 0.0)?;
1258        self.try_fix_dof(node_idx, 2, 0.0)?;
1259        Ok(())
1260    }
1261
1262    /// Typed counterpart of [`Self::try_fix_dof`]: constrain `(node_idx, dof)`
1263    /// to `value`.
1264    ///
1265    /// ```text
1266    /// model.try_fix(0, Dof::Uy, 0.0)?;   // == model.try_fix_dof(0, 1, 0.0)?
1267    /// ```
1268    ///
1269    /// `dof` is always a **global** DOF; there is no local DOF variant. This
1270    /// delegates to [`Self::try_fix_dof`] and therefore shares the same
1271    /// boundary-condition storage, validation and static-condensation path.
1272    ///
1273    /// # Errors
1274    ///
1275    /// [`FemError::InvalidInput`] for an out-of-bounds node index or a
1276    /// non-finite prescribed value.
1277    pub fn try_fix(&mut self, node_idx: usize, dof: Dof, value: f64) -> Result<(), FemError> {
1278        self.try_fix_dof(node_idx, dof.index(), value)
1279    }
1280
1281    /// Typed counterpart of [`Self::try_override_dof`]: override (upsert) the
1282    /// prescribed displacement for `(node_idx, dof)` to `value`.
1283    ///
1284    /// Unlike [`Self::try_fix`], this silently replaces any existing
1285    /// constraint on the same DOF instead of returning
1286    /// [`FemError::ConflictingPrescribedDisplacement`].
1287    pub fn try_override(&mut self, node_idx: usize, dof: Dof, value: f64) -> Result<(), FemError> {
1288        self.try_override_dof(node_idx, dof.index(), value)
1289    }
1290
1291    /// Constrain all three DOFs of a node to the given prescribed values.
1292    ///
1293    /// Use this for a prescribed displacement/rotation (e.g. a support
1294    /// settlement such as `try_fix_node_with_values(0, 0.0, -0.01, 0.0)`); a
1295    /// fully fixed node is `try_fix_node_with_values(i, 0.0, 0.0, 0.0)`, which
1296    /// is what [`Self::try_fix_node`] does.
1297    ///
1298    /// This is a convenience wrapper: it delegates to [`Self::try_override_dof`]
1299    /// for `ux`, `uy` and `rz`, so it uses the same boundary-condition storage
1300    /// and the same static-condensation path. It does not add a second BC
1301    /// representation and does not change reaction recovery.  Any existing
1302    /// constraint on the same DOF is **replaced**.
1303    ///
1304    /// # Errors
1305    ///
1306    /// [`FemError::InvalidInput`] for an out-of-bounds node index or any
1307    /// non-finite prescribed value. All inputs are validated **before** any
1308    /// boundary condition is recorded, so a rejected call leaves the model
1309    /// unchanged (no partially fixed node).
1310    pub fn try_fix_node_with_values(
1311        &mut self,
1312        node_idx: usize,
1313        ux: f64,
1314        uy: f64,
1315        rz: f64,
1316    ) -> Result<(), FemError> {
1317        if node_idx >= self.nodes.len() {
1318            return Err(FemError::InvalidInput(format!(
1319                "Invalid node index: {} (max: {})",
1320                node_idx,
1321                self.nodes.len().saturating_sub(1)
1322            )));
1323        }
1324        for (dof, value) in [(Dof::Ux, ux), (Dof::Uy, uy), (Dof::Rz, rz)] {
1325            if !value.is_finite() {
1326                return Err(FemError::InvalidInput(format!(
1327                    "Prescribed value for {} must be finite, got {}",
1328                    dof.name(),
1329                    value
1330                )));
1331            }
1332        }
1333        self.try_override_dof(node_idx, Dof::Ux.index(), ux)?;
1334        self.try_override_dof(node_idx, Dof::Uy.index(), uy)?;
1335        self.try_override_dof(node_idx, Dof::Rz.index(), rz)?;
1336        Ok(())
1337    }
1338
1339    /// Add a distributed load on an element (in LOCAL coordinates)
1340    /// element_idx is the index in the elements Vec (0, 1, 2, ...)
1341    pub fn add_distributed_load(
1342        &mut self,
1343        element_idx: usize,
1344        qx: f64,
1345        qy: f64,
1346    ) -> Result<(), FemError> {
1347        if element_idx >= self.elements.len() {
1348            return Err(FemError::InvalidInput(format!(
1349                "Invalid element index: {} (max: {})",
1350                element_idx,
1351                self.elements.len().saturating_sub(1)
1352            )));
1353        }
1354        if !qx.is_finite() || !qy.is_finite() {
1355            return Err(FemError::InvalidInput(format!(
1356                "Distributed load must be finite, got qx = {}, qy = {}",
1357                qx, qy
1358            )));
1359        }
1360        self.distributed_loads
1361            .push(DistributedLoad::new(element_idx, qx, qy));
1362        Ok(())
1363    }
1364
1365    /// Add a point load on an element (in LOCAL coordinates)
1366    /// element_idx is the index in the elements Vec (0, 1, 2, ...)
1367    /// position is measured from node_i (0.0) to node_j (1.0)
1368    pub fn add_point_load(
1369        &mut self,
1370        element_idx: usize,
1371        position: f64,
1372        fx: f64,
1373        fy: f64,
1374        mz: f64,
1375    ) -> Result<(), FemError> {
1376        if element_idx >= self.elements.len() {
1377            return Err(FemError::InvalidInput(format!(
1378                "Invalid element index: {} (max: {})",
1379                element_idx,
1380                self.elements.len().saturating_sub(1)
1381            )));
1382        }
1383        if !(0.0..=1.0).contains(&position) {
1384            return Err(FemError::InvalidInput(format!(
1385                "Point load position must be in [0, 1], got {}",
1386                position
1387            )));
1388        }
1389        if !fx.is_finite() || !fy.is_finite() || !mz.is_finite() {
1390            return Err(FemError::InvalidInput(format!(
1391                "Point load must be finite, got fx = {}, fy = {}, mz = {}",
1392                fx, fy, mz
1393            )));
1394        }
1395        self.point_loads
1396            .push(PointLoad::new(element_idx, position, fx, fy, mz));
1397        Ok(())
1398    }
1399
1400    /// Add a point force only (transverse or axial) on an element.
1401    ///
1402    /// Components are **LOCAL** to the element (local x from `node_i` to
1403    /// `node_j`, local y transverse, positive up). Use
1404    /// [`BeamElement::to_local_force`] to convert global input data. `position`
1405    /// must be in `[0, 1]`.
1406    ///
1407    /// # Errors
1408    ///
1409    /// [`FemError::InvalidInput`] for an out-of-bounds element, a `position`
1410    /// outside `[0, 1]`, or a non-finite component.
1411    pub fn add_point_force(
1412        &mut self,
1413        element_idx: usize,
1414        position: f64,
1415        fx: f64,
1416        fy: f64,
1417    ) -> Result<(), FemError> {
1418        self.add_point_load(element_idx, position, fx, fy, 0.0)
1419    }
1420
1421    /// Add a point moment only on an element.
1422    ///
1423    /// `mz` is **LOCAL** to the element (`mz > 0` counter-clockwise) and
1424    /// `position` must be in `[0, 1]`. This is an element load, distinct from
1425    /// [`Self::add_applied_moment`], which is a nodal (global) moment that is
1426    /// never part of an element's equivalent load vector.
1427    ///
1428    /// # Errors
1429    ///
1430    /// [`FemError::InvalidInput`] for an out-of-bounds element, a `position`
1431    /// outside `[0, 1]`, or a non-finite value.
1432    pub fn add_point_moment(
1433        &mut self,
1434        element_idx: usize,
1435        position: f64,
1436        mz: f64,
1437    ) -> Result<(), FemError> {
1438        self.add_point_load(element_idx, position, 0.0, 0.0, mz)
1439    }
1440
1441    /// Add an applied moment at a node (in GLOBAL coordinates).
1442    ///
1443    /// This is a nodal external load applied to the global `theta` DOF
1444    /// (`value > 0` counter-clockwise). It is **not** an element load: it never
1445    /// enters an element's equivalent nodal-load vector, so element end forces
1446    /// are unaffected by it except through the displacement field.
1447    ///
1448    /// # Errors
1449    ///
1450    /// [`FemError::InvalidInput`] for an out-of-bounds node index or a
1451    /// non-finite value.
1452    pub fn add_applied_moment(&mut self, node_idx: usize, value: f64) -> Result<(), FemError> {
1453        if node_idx >= self.nodes.len() {
1454            return Err(FemError::InvalidInput(format!(
1455                "Invalid node index: {} (max: {})",
1456                node_idx,
1457                self.nodes.len().saturating_sub(1)
1458            )));
1459        }
1460        if !value.is_finite() {
1461            return Err(FemError::InvalidInput(format!(
1462                "Applied moment must be finite, got {}",
1463                value
1464            )));
1465        }
1466        self.applied_moments
1467            .push(AppliedMoment::new(node_idx, value));
1468        Ok(())
1469    }
1470
1471    /// Get total number of DOFs
1472    pub fn n_dof(&self) -> usize {
1473        self.nodes.len() * 3
1474    }
1475
1476    /// Map (node_idx, dof) to global DOF index
1477    ///
1478    /// Note: node_idx must be the index in the nodes Vec (0, 1, 2, ...).
1479    /// This is NOT an arbitrary user-defined ID. Node IDs are implicitly their
1480    /// position in the nodes vector.
1481    pub fn dof_index(&self, node_idx: usize, dof: usize) -> usize {
1482        node_idx * 3 + dof
1483    }
1484}
1485
1486/// The condensed (boundary-conditioned) free-free stiffness system of a
1487/// [`BeamSolver`]: `K_ff` plus the reduced-index -> global-DOF map.
1488///
1489/// This is the **single** representation of the system that static
1490/// condensation produces and that the linear solver factorises. It is retained
1491/// so that structural diagnostics read the exact same matrix the solve path
1492/// built, rather than reassembling an identical-looking second copy: two
1493/// independent assemblies are mathematically equal but not necessarily
1494/// bit-identical, and a rank probe sitting at a relative tolerance floor is
1495/// exactly the kind of consumer that a ULP difference can flip.
1496///
1497/// Crate-internal on purpose - this is not part of the public surface. Its
1498/// fields are private: consumers read `K_ff` and the DOF map through the
1499/// read-only accessors so the retained system cannot be mutated from outside.
1500#[derive(Debug, Clone)]
1501pub(crate) struct ReducedSystem {
1502    /// The free-free stiffness block `K_ff` (already compressed).
1503    k_ff: SparseMatrix,
1504    /// Reduced DOF index -> global DOF index (`3 * node + dof`).
1505    free_to_global: Vec<usize>,
1506}
1507
1508impl ReducedSystem {
1509    /// Retain a condensed system from an already-built `K_ff` and DOF map.
1510    pub(crate) fn new(k_ff: SparseMatrix, free_to_global: Vec<usize>) -> Self {
1511        Self {
1512            k_ff,
1513            free_to_global,
1514        }
1515    }
1516
1517    /// The retained free-free stiffness block `K_ff`.
1518    pub(crate) fn k_ff(&self) -> &SparseMatrix {
1519        &self.k_ff
1520    }
1521
1522    /// The retained reduced-index -> global-DOF map (`3 * node + dof`).
1523    pub(crate) fn free_to_global(&self) -> &[usize] {
1524        &self.free_to_global
1525    }
1526}
1527
1528/// Beam FEM solver using the unified LinearSolver abstraction.
1529///
1530/// # Complete workflow
1531///
1532/// ```rust
1533/// use section_properties::beam_fem::{BeamElement, BeamModel, BeamNode, BeamSection, BeamSolver, Dof};
1534/// use section_properties::material::Material;
1535///
1536/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1537/// // 1. model: unit cantilever (E = A = I = 1, L = 1)
1538/// let mut model = BeamModel::new();
1539/// model.add_node(BeamNode::new(0, 0.0, 0.0));
1540/// model.add_node(BeamNode::new(1, 1.0, 0.0));
1541/// model.add_element(BeamElement::new(
1542///     0,
1543///     1,
1544///     Material::new(1.0, 0.3, 1.0, "unit"),
1545///     BeamSection::new(1.0, 1.0),
1546/// )?);
1547///
1548/// // 2. boundary condition: clamp node 0 (typed DOF API)
1549/// model.try_fix_node_with_values(0, 0.0, 0.0, 0.0)?;
1550///
1551/// // 3. load: global transverse force at the tip
1552/// model.add_nodal_force(1, 1, -100.0);
1553///
1554/// // 4. solve
1555/// let mut solver = BeamSolver::from_model(&model)?;
1556/// solver.solve_configured()?;
1557///
1558/// // 5. post-process: typed displacement and reaction access
1559/// let uy = solver.displacement_dof(1, Dof::Uy)?; // -P L^3 / 3EI
1560/// let rz = solver.displacement_dof(1, Dof::Rz)?; // -P L^2 / 2EI
1561/// let ry = solver.reaction_dof(0, Dof::Uy)?; // +P
1562///
1563/// assert!((uy + 100.0 / 3.0).abs() < 1e-9);
1564/// assert!((rz + 50.0).abs() < 1e-9);
1565/// assert!((ry - 100.0).abs() < 1e-9);
1566/// # Ok(())
1567/// # }
1568/// ```
1569pub struct BeamSolver {
1570    /// Global stiffness matrix
1571    k_global: SparseMatrix,
1572    /// Global force vector
1573    f_global: Vec<f64>,
1574    /// Displacement solution
1575    u_global: Vec<f64>,
1576    /// Fixed DOFs (true if constrained)
1577    fixed_dofs: Vec<bool>,
1578    /// Prescribed values for constrained DOFs (None = 0.0, Some(value) = prescribed)
1579    prescribed_values: Vec<Option<f64>>,
1580    /// Original stiffness matrix (for reaction computation)
1581    k_original: SparseMatrix,
1582    /// Number of DOFs
1583    n_dof: usize,
1584    /// Model reference
1585    model: BeamModel,
1586    /// Configured solver selection (defaults to [`SolverSelection::Auto`]).
1587    solver_selection: SolverSelection,
1588    /// Name of the backend used by the most recent successful solve, if any.
1589    solver_name: Option<String>,
1590    /// The condensed free-free system retained by
1591    /// [`Self::apply_boundary_conditions`], if it has run. Populated before any
1592    /// backend is created or factorisation attempted, so it is available even
1593    /// after a failed solve.
1594    reduced: Option<ReducedSystem>,
1595}
1596
1597impl BeamSolver {
1598    /// Create a new BeamSolver from a BeamModel
1599    pub fn from_model(model: &BeamModel) -> Result<Self, FemError> {
1600        let n_dof = model.n_dof();
1601        if n_dof == 0 {
1602            return Err(FemError::InvalidModel("Model has no nodes".to_string()));
1603        }
1604
1605        // Validate element node indices
1606        for (elem_idx, element) in model.elements.iter().enumerate() {
1607            if element.node_i >= model.nodes.len() {
1608                return Err(FemError::InvalidModel(format!(
1609                    "Element {}: node_i index {} out of bounds (max: {})",
1610                    elem_idx,
1611                    element.node_i,
1612                    model.nodes.len().saturating_sub(1)
1613                )));
1614            }
1615            if element.node_j >= model.nodes.len() {
1616                return Err(FemError::InvalidModel(format!(
1617                    "Element {}: node_j index {} out of bounds (max: {})",
1618                    elem_idx,
1619                    element.node_j,
1620                    model.nodes.len().saturating_sub(1)
1621                )));
1622            }
1623            if element.node_i == element.node_j {
1624                return Err(FemError::InvalidModel(format!(
1625                    "Element {}: node_i and node_j cannot be the same",
1626                    elem_idx
1627                )));
1628            }
1629        }
1630
1631        // Validate node coordinates are finite.
1632        for (idx, node) in model.nodes.iter().enumerate() {
1633            if !node.x.is_finite() || !node.y.is_finite() {
1634                return Err(FemError::InvalidModel(format!(
1635                    "Node {} has non-finite coordinates: ({}, {})",
1636                    idx, node.x, node.y
1637                )));
1638            }
1639        }
1640
1641        // Validate material and section parameters (finite and positive). These
1642        // have no fallible constructor, so this is the authoritative boundary;
1643        // it also covers elements built via struct literal.
1644        for (elem_idx, element) in model.elements.iter().enumerate() {
1645            let e = element.material.youngs_modulus;
1646            let a = element.section.area;
1647            let i = element.section.second_moment;
1648            if !e.is_finite() || e <= 0.0 {
1649                return Err(FemError::InvalidModel(format!(
1650                    "Element {}: Young's modulus must be finite and positive, got {}",
1651                    elem_idx, e
1652                )));
1653            }
1654            if !a.is_finite() || a <= 0.0 {
1655                return Err(FemError::InvalidModel(format!(
1656                    "Element {}: cross-section area must be finite and positive, got {}",
1657                    elem_idx, a
1658                )));
1659            }
1660            if !i.is_finite() || i <= 0.0 {
1661                return Err(FemError::InvalidModel(format!(
1662                    "Element {}: second moment of area must be finite and positive, got {}",
1663                    elem_idx, i
1664                )));
1665            }
1666        }
1667
1668        // Validate that every load and prescribed value is finite. Model fields
1669        // are public, so this cannot be delegated solely to the add_* helpers.
1670        for (node_id, dof, value) in &model.nodal_forces {
1671            if !value.is_finite() {
1672                return Err(FemError::InvalidModel(format!(
1673                    "Nodal force at node {} DOF {} is non-finite: {}",
1674                    node_id, dof, value
1675                )));
1676            }
1677        }
1678        for dl in &model.distributed_loads {
1679            if !dl.qx.is_finite() || !dl.qy.is_finite() {
1680                return Err(FemError::InvalidModel(format!(
1681                    "Distributed load on element {} is non-finite: qx = {}, qy = {}",
1682                    dl.element_idx, dl.qx, dl.qy
1683                )));
1684            }
1685        }
1686        for pl in &model.point_loads {
1687            if !pl.fx.is_finite() || !pl.fy.is_finite() || !pl.mz.is_finite() {
1688                return Err(FemError::InvalidModel(format!(
1689                    "Point load on element {} is non-finite: fx = {}, fy = {}, mz = {}",
1690                    pl.element_idx, pl.fx, pl.fy, pl.mz
1691                )));
1692            }
1693        }
1694        for am in &model.applied_moments {
1695            if !am.value.is_finite() {
1696                return Err(FemError::InvalidModel(format!(
1697                    "Applied moment at node {} is non-finite: {}",
1698                    am.node_idx, am.value
1699                )));
1700            }
1701        }
1702        for (node_id, dof, value) in &model.fixed_dofs {
1703            if !value.is_finite() {
1704                return Err(FemError::InvalidModel(format!(
1705                    "Prescribed value at node {} DOF {} is non-finite: {}",
1706                    node_id, dof, value
1707                )));
1708            }
1709        }
1710
1711        // Build global stiffness matrix
1712        let mut k_global = SparseMatrix::new(n_dof);
1713
1714        // Assemble element stiffness matrices
1715        for element in &model.elements {
1716            let node_i = model.nodes[element.node_i].point();
1717            let node_j = model.nodes[element.node_j].point();
1718
1719            // Check for zero-length beam
1720            let dx = node_j.x - node_i.x;
1721            let dy = node_j.y - node_i.y;
1722            let L = (dx * dx + dy * dy).sqrt();
1723            if L <= 0.0 {
1724                return Err(FemError::InvalidModel(format!(
1725                    "Beam element has zero or negative length (nodes {} and {} at same position)",
1726                    element.node_i, element.node_j
1727                )));
1728            }
1729
1730            let k_global_elem = element.global_stiffness(node_i, node_j);
1731
1732            // Map element DOFs to global DOFs
1733            let dof_map = [
1734                model.dof_index(element.node_i, 0), // u_i
1735                model.dof_index(element.node_i, 1), // v_i
1736                model.dof_index(element.node_i, 2), // θ_i
1737                model.dof_index(element.node_j, 0), // u_j
1738                model.dof_index(element.node_j, 1), // v_j
1739                model.dof_index(element.node_j, 2), // θ_j
1740            ];
1741
1742            // Assemble into global matrix
1743            for a in 0..6 {
1744                for b in 0..6 {
1745                    let val = k_global_elem[a][b];
1746                    k_global.add(dof_map[a], dof_map[b], val);
1747                }
1748            }
1749        }
1750
1751        // Build force vector
1752        let mut f_global = vec![0.0; n_dof];
1753        for (node_id, dof, value) in &model.nodal_forces {
1754            if *node_id >= model.nodes.len() {
1755                return Err(FemError::InvalidModel(format!(
1756                    "Nodal force: node index {} out of bounds (max: {})",
1757                    node_id,
1758                    model.nodes.len().saturating_sub(1)
1759                )));
1760            }
1761            if *dof >= 3 {
1762                return Err(FemError::InvalidModel(format!(
1763                    "Nodal force: DOF {} invalid (must be 0, 1, or 2)",
1764                    dof
1765                )));
1766            }
1767            let idx = model.dof_index(*node_id, *dof);
1768            f_global[idx] += value;
1769        }
1770
1771        // Assemble distributed loads
1772        for dl in &model.distributed_loads {
1773            if dl.element_idx >= model.elements.len() {
1774                return Err(FemError::InvalidModel(format!(
1775                    "Distributed load: element index {} out of bounds (max: {})",
1776                    dl.element_idx,
1777                    model.elements.len().saturating_sub(1)
1778                )));
1779            }
1780            let element = &model.elements[dl.element_idx];
1781            let node_i = model.nodes[element.node_i].point();
1782            let node_j = model.nodes[element.node_j].point();
1783
1784            // Check for zero-length beam
1785            let dx = node_j.x - node_i.x;
1786            let dy = node_j.y - node_i.y;
1787            let L = (dx * dx + dy * dy).sqrt();
1788            if L <= 0.0 {
1789                return Err(FemError::InvalidModel(format!(
1790                    "Distributed load: beam element has zero or negative length (nodes {} and {} at same position)",
1791                    element.node_i, element.node_j
1792                )));
1793            }
1794
1795            // Compute consistent nodal load in local coordinates
1796            let f_local = element.consistent_nodal_load(node_i, node_j, dl.qx, dl.qy)?;
1797
1798            // Get transformation matrix
1799            let T = element.transformation_matrix(node_i, node_j);
1800
1801            // Transform to global coordinates: f_global_elem = T^T * f_local
1802            let mut f_global_elem = [0.0; 6];
1803            for i in 0..6 {
1804                for j in 0..6 {
1805                    f_global_elem[i] += T[j][i] * f_local[j];
1806                }
1807            }
1808
1809            // Map element DOFs to global DOFs
1810            let dof_map = [
1811                model.dof_index(element.node_i, 0), // u_i
1812                model.dof_index(element.node_i, 1), // v_i
1813                model.dof_index(element.node_i, 2), // θ_i
1814                model.dof_index(element.node_j, 0), // u_j
1815                model.dof_index(element.node_j, 1), // v_j
1816                model.dof_index(element.node_j, 2), // θ_j
1817            ];
1818
1819            // Assemble into global force vector
1820            for a in 0..6 {
1821                f_global[dof_map[a]] += f_global_elem[a];
1822            }
1823        }
1824
1825        // Assemble point loads
1826        for pl in &model.point_loads {
1827            if pl.element_idx >= model.elements.len() {
1828                return Err(FemError::InvalidModel(format!(
1829                    "Point load: element index {} out of bounds (max: {})",
1830                    pl.element_idx,
1831                    model.elements.len().saturating_sub(1)
1832                )));
1833            }
1834            let element = &model.elements[pl.element_idx];
1835            let node_i = model.nodes[element.node_i].point();
1836            let node_j = model.nodes[element.node_j].point();
1837
1838            // Check for zero-length beam
1839            let dx = node_j.x - node_i.x;
1840            let dy = node_j.y - node_i.y;
1841            let L = (dx * dx + dy * dy).sqrt();
1842            if L <= 0.0 {
1843                return Err(FemError::InvalidModel(format!(
1844                    "Point load: beam element has zero or negative length (nodes {} and {} at same position)",
1845                    element.node_i, element.node_j
1846                )));
1847            }
1848
1849            // Compute consistent nodal load in local coordinates
1850            let f_local = element.consistent_nodal_load_point(
1851                node_i,
1852                node_j,
1853                pl.position,
1854                pl.fx,
1855                pl.fy,
1856                pl.mz,
1857            )?;
1858
1859            // Get transformation matrix
1860            let T = element.transformation_matrix(node_i, node_j);
1861
1862            // Transform to global coordinates: f_global_elem = T^T * f_local
1863            let mut f_global_elem = [0.0; 6];
1864            for i in 0..6 {
1865                for j in 0..6 {
1866                    f_global_elem[i] += T[j][i] * f_local[j];
1867                }
1868            }
1869
1870            // Map element DOFs to global DOFs
1871            let dof_map = [
1872                model.dof_index(element.node_i, 0), // u_i
1873                model.dof_index(element.node_i, 1), // v_i
1874                model.dof_index(element.node_i, 2), // θ_i
1875                model.dof_index(element.node_j, 0), // u_j
1876                model.dof_index(element.node_j, 1), // v_j
1877                model.dof_index(element.node_j, 2), // θ_j
1878            ];
1879
1880            // Assemble into global force vector
1881            for a in 0..6 {
1882                f_global[dof_map[a]] += f_global_elem[a];
1883            }
1884        }
1885
1886        // Assemble applied moments (already in global coordinates)
1887        for am in &model.applied_moments {
1888            if am.node_idx >= model.nodes.len() {
1889                return Err(FemError::InvalidModel(format!(
1890                    "Applied moment: node index {} out of bounds (max: {})",
1891                    am.node_idx,
1892                    model.nodes.len().saturating_sub(1)
1893                )));
1894            }
1895            // Applied moment is in global coordinates, DOF 2 = θ
1896            let idx = model.dof_index(am.node_idx, 2);
1897            f_global[idx] += am.value;
1898        }
1899
1900        // Fixed DOFs and prescribed values
1901        let mut fixed_dofs = vec![false; n_dof];
1902        let mut prescribed_values = vec![None; n_dof];
1903        for (node_id, dof, value) in &model.fixed_dofs {
1904            if *node_id >= model.nodes.len() {
1905                return Err(FemError::InvalidModel(format!(
1906                    "Fixed DOF: node index {} out of bounds (max: {})",
1907                    node_id,
1908                    model.nodes.len().saturating_sub(1)
1909                )));
1910            }
1911            if *dof >= 3 {
1912                return Err(FemError::InvalidModel(format!(
1913                    "Fixed DOF: DOF {} invalid (must be 0, 1, or 2)",
1914                    dof
1915                )));
1916            }
1917            let idx = model.dof_index(*node_id, *dof);
1918            fixed_dofs[idx] = true;
1919            prescribed_values[idx] = Some(*value);
1920        }
1921
1922        // Store original matrix for reaction computation
1923        let k_original = k_global.clone();
1924
1925        Ok(Self {
1926            k_global,
1927            f_global,
1928            u_global: vec![0.0; n_dof],
1929            fixed_dofs,
1930            prescribed_values,
1931            k_original,
1932            n_dof,
1933            model: model.clone(),
1934            solver_selection: SolverSelection::Auto,
1935            solver_name: None,
1936            reduced: None,
1937        })
1938    }
1939
1940    /// Apply boundary conditions using static condensation (exact enforcement)
1941    /// and retain the condensed system in `self.reduced`.
1942    ///
1943    /// Returns `(f_reduced, constrained_indices, constrained_values)`. The
1944    /// condensed stiffness `K_ff` and the free-DOF map are **moved** into
1945    /// `self.reduced` (no clone): diagnostics read that retained system, and
1946    /// the solve path factorises a bit-identical copy of it (the single deep
1947    /// copy on the solve path) rather than a second, independently assembled
1948    /// matrix.
1949    fn apply_boundary_conditions(&mut self) -> (Vec<f64>, Vec<usize>, Vec<f64>) {
1950        let n = self.n_dof;
1951        let fixed = &self.fixed_dofs;
1952        let prescribed = &self.prescribed_values;
1953
1954        // Identify free and constrained DOFs
1955        let mut free_dofs = Vec::new();
1956        let mut constrained_dofs = Vec::new();
1957        let mut constrained_values = Vec::new();
1958        let mut free_to_global = Vec::new();
1959        let mut global_to_free = vec![None; n];
1960
1961        for i in 0..n {
1962            if !fixed[i] {
1963                global_to_free[i] = Some(free_dofs.len());
1964                free_dofs.push(i);
1965                free_to_global.push(i);
1966            } else {
1967                let _constrained_idx = constrained_dofs.len();
1968                constrained_dofs.push(i);
1969                constrained_values.push(prescribed[i].unwrap_or(0.0));
1970            }
1971        }
1972
1973        let n_free = free_dofs.len();
1974        if n_free == 0 {
1975            // All DOFs fixed - retain and return an empty system.
1976            self.reduced = Some(ReducedSystem::new(SparseMatrix::new(0), Vec::new()));
1977            return (Vec::new(), constrained_dofs, constrained_values);
1978        }
1979
1980        // Extract free-free submatrix K_ff and force vector f_f
1981        let mut k_ff = SparseMatrix::new(n_free);
1982        let mut f_f = vec![0.0; n_free];
1983
1984        // Compress original matrix to access CSR data
1985        let mut k_orig = self.k_global.clone();
1986        k_orig.compress();
1987
1988        // Extract K_ff and compute K_fc * U_c directly
1989        let mut kfc_uc = vec![0.0; n_free];
1990
1991        for (free_idx, &global_i) in free_dofs.iter().enumerate() {
1992            // Force vector
1993            f_f[free_idx] = self.f_global[global_i];
1994
1995            // Stiffness matrix row
1996            let row_ptr = k_orig.row_ptr();
1997            let csr_cols = k_orig.csr_cols();
1998            let csr_vals = k_orig.csr_vals();
1999
2000            for idx in row_ptr[global_i]..row_ptr[global_i + 1] {
2001                let global_j = csr_cols[idx];
2002                let val = csr_vals[idx];
2003
2004                if let Some(free_j) = global_to_free[global_j] {
2005                    // free-free
2006                    k_ff.add(free_idx, free_j, val);
2007                } else if fixed[global_j] {
2008                    // free-constrained: accumulate K_fc * U_c directly
2009                    let constr_idx = constrained_dofs
2010                        .iter()
2011                        .position(|&x| x == global_j)
2012                        .unwrap();
2013                    kfc_uc[free_idx] += val * constrained_values[constr_idx];
2014                }
2015            }
2016        }
2017
2018        k_ff.compress();
2019
2020        // Compute reduced RHS: F_reduced = F_f - K_fc * U_c
2021        let mut f_reduced = f_f;
2022        for free_idx in 0..n_free {
2023            f_reduced[free_idx] -= kfc_uc[free_idx];
2024        }
2025
2026        // Retain the condensed system for the solve path and read-only
2027        // diagnostics by *moving* the freshly built matrix and map (no clone).
2028        self.reduced = Some(ReducedSystem::new(k_ff, free_to_global));
2029
2030        (f_reduced, constrained_dofs, constrained_values)
2031    }
2032
2033    /// The condensed free-free system most recently built by
2034    /// [`Self::apply_boundary_conditions`]/[`Self::condense`], if it has run.
2035    ///
2036    /// The matrix is the exact one the solve path assembled and factorised -
2037    /// diagnostics must read this, never reassemble their own copy. `None` only
2038    /// before any condensation has happened on this solver.
2039    pub(crate) fn reduced_system(&self) -> Option<&ReducedSystem> {
2040        self.reduced.as_ref()
2041    }
2042
2043    /// Copy the retained reduced system out for its one consuming use (the
2044    /// factorisation). This is the only deep copy of `K_ff` on the solve path;
2045    /// the retained original stays in `self.reduced` for diagnostics.
2046    ///
2047    /// Panics only if called before the system has been condensed, which the
2048    /// solve paths never do (`apply_boundary_conditions` runs first).
2049    fn retained_system_copy(&self) -> (SparseMatrix, Vec<usize>) {
2050        let retained = self
2051            .reduced
2052            .as_ref()
2053            .expect("apply_boundary_conditions retains the condensed system");
2054        (retained.k_ff().clone(), retained.free_to_global().to_vec())
2055    }
2056
2057    /// Condense the boundary conditions and return the retained reduced system
2058    /// for read-only inspection.
2059    ///
2060    /// Semantics: the returned system is condensed from the solver's current
2061    /// model state. The **first** call runs the identical static-condensation
2062    /// code the solve path runs, so the returned matrix is bit-identical to the
2063    /// one a solve would factorise. A `BeamSolver` exposes no mutator that can
2064    /// change the assembled system (loads, supports and geometry are fixed in
2065    /// the `BeamModel` at construction; only the backend selection is settable,
2066    /// which does not affect `K_ff`), so repeated calls are **idempotent**:
2067    /// they return the already-retained system without re-condensing. It never
2068    /// panics.
2069    pub(crate) fn condense(&mut self) -> &ReducedSystem {
2070        if self.reduced.is_none() {
2071            self.apply_boundary_conditions();
2072        }
2073        self.reduced
2074            .as_ref()
2075            .expect("apply_boundary_conditions always retains the condensed system")
2076    }
2077
2078    #[allow(dead_code)]
2079    fn find_diagonal_index(&self, matrix: &SparseMatrix, row: usize) -> Option<usize> {
2080        let row_ptr = matrix.row_ptr();
2081        let csr_cols = matrix.csr_cols();
2082        for idx in row_ptr[row]..row_ptr[row + 1] {
2083            if csr_cols[idx] == row {
2084                return Some(idx);
2085            }
2086        }
2087        None
2088    }
2089
2090    /// Configure the solver selection used by [`Self::solve_configured`].
2091    ///
2092    /// Defaults to [`SolverSelection::Auto`]. Explicit selections are
2093    /// authoritative: if the requested backend cannot handle the condensed
2094    /// stiffness matrix, [`Self::solve_configured`] returns an error and does
2095    /// **not** substitute another backend.
2096    pub fn set_solver(&mut self, selection: SolverSelection) {
2097        self.solver_selection = selection;
2098    }
2099
2100    /// The configured solver selection.
2101    pub fn solver_selection(&self) -> &SolverSelection {
2102        &self.solver_selection
2103    }
2104
2105    /// Name of the backend used by the most recent **successful** solve.
2106    ///
2107    /// Semantics: the value describes the solution currently held by this
2108    /// solver. It is cleared before each solve attempt and set only when the
2109    /// solve completes successfully, so it is `None`:
2110    ///
2111    /// * before any solve;
2112    /// * after a failed solve attempt (no stale claim from an earlier run);
2113    /// * when the model was fully constrained and no linear system was solved.
2114    pub fn solver_name(&self) -> Option<&str> {
2115        self.solver_name.as_deref()
2116    }
2117
2118    /// Factorize and expand a condensed system into the global solution.
2119    ///
2120    /// `k_ff`/`free_to_global` are the solver's retained system copied out for
2121    /// this one use - the only deep copy of `K_ff` on the solve path (the
2122    /// retained copy lives in `self.reduced` for diagnostics and is never
2123    /// duplicated again).
2124    fn factor_and_expand(
2125        &mut self,
2126        solver: &mut dyn LinearSolver,
2127        mut k_ff: SparseMatrix,
2128        f_reduced: Vec<f64>,
2129        free_to_global: Vec<usize>,
2130        constrained_dofs: Vec<usize>,
2131        constrained_values: Vec<f64>,
2132    ) -> Result<(), FemError> {
2133        if k_ff.n == 0 {
2134            // All DOFs fixed - just set prescribed values
2135            self.u_global = vec![0.0; self.n_dof];
2136            for (i, &global_idx) in constrained_dofs.iter().enumerate() {
2137                self.u_global[global_idx] = constrained_values[i];
2138            }
2139            return Ok(());
2140        }
2141
2142        k_ff.compress();
2143        solver.factor(&k_ff).map_err(FemError::from)?;
2144
2145        let u_free = solver.solve(&f_reduced).map_err(FemError::from)?;
2146
2147        // Expand solution back to full DOF space
2148        self.u_global = vec![0.0; self.n_dof];
2149        for (free_idx, &global_idx) in free_to_global.iter().enumerate() {
2150            self.u_global[global_idx] = u_free[free_idx];
2151        }
2152        for (i, &global_idx) in constrained_dofs.iter().enumerate() {
2153            self.u_global[global_idx] = constrained_values[i];
2154        }
2155        Ok(())
2156    }
2157
2158    /// Solve the system using the provided LinearSolver.
2159    ///
2160    /// The caller owns solver construction; [`Self::solve_configured`] instead
2161    /// uses the configured [`SolverSelection`].
2162    ///
2163    /// [`Self::solver_name`] is cleared at the start of this call and set only
2164    /// after the solve succeeds, so a failed solve never leaves stale
2165    /// observability implying a backend produced the current solution.
2166    pub fn solve(&mut self, solver: &mut dyn LinearSolver) -> Result<(), FemError> {
2167        self.solver_name = None;
2168        let (f_reduced, constrained_dofs, constrained_values) = self.apply_boundary_conditions();
2169        let (k_ff, free_to_global) = self.retained_system_copy();
2170        self.factor_and_expand(
2171            solver,
2172            k_ff,
2173            f_reduced,
2174            free_to_global,
2175            constrained_dofs,
2176            constrained_values,
2177        )?;
2178        self.solver_name = Some(solver.name().to_string());
2179        Ok(())
2180    }
2181
2182    /// Solve using the configured [`SolverSelection`] (default [`Auto`]).
2183    ///
2184    /// The backend is chosen via [`SolverRegistry`] against the **condensed**
2185    /// (boundary-conditioned) stiffness matrix — the matrix that is actually
2186    /// factorized. Capability validation therefore sees the real system.
2187    ///
2188    /// # Errors
2189    ///
2190    /// All solver errors propagate as [`FemError::SolverError`]; an explicit
2191    /// invalid selection (e.g. a non-symmetric system with `skyline_ldlt`, or a
2192    /// matrix larger than the backend's `max_size`) returns an error and never
2193    /// silently switches backend.
2194    ///
2195    /// [`Self::solver_name`] is cleared before the solve is attempted and set
2196    /// only once it fully succeeds, so a failed attempt never leaves stale
2197    /// observability claiming the failed backend produced a solution.
2198    ///
2199    /// [`Auto`]: SolverSelection::Auto
2200    pub fn solve_configured(&mut self) -> Result<(), FemError> {
2201        self.solver_name = None;
2202        let (f_reduced, constrained_dofs, constrained_values) = self.apply_boundary_conditions();
2203
2204        let n_free = self.reduced.as_ref().map_or(0, |r| r.k_ff().n);
2205        if n_free == 0 {
2206            self.u_global = vec![0.0; self.n_dof];
2207            for (i, &global_idx) in constrained_dofs.iter().enumerate() {
2208                self.u_global[global_idx] = constrained_values[i];
2209            }
2210            return Ok(());
2211        }
2212
2213        // The single copy of the retained matrix: the backend is selected
2214        // against it and it is the matrix the factorisation consumes (no
2215        // separate probe copy).
2216        let (k_ff, free_to_global) = self.retained_system_copy();
2217
2218        let registry = SolverRegistry::default();
2219        let mut solver = registry
2220            .create_selected(&k_ff, &self.solver_selection)
2221            .map_err(FemError::from)?;
2222        let name = solver.name().to_string();
2223
2224        self.factor_and_expand(
2225            &mut *solver,
2226            k_ff,
2227            f_reduced,
2228            free_to_global,
2229            constrained_dofs,
2230            constrained_values,
2231        )?;
2232        self.solver_name = Some(name);
2233        Ok(())
2234    }
2235
2236    /// Displacement of a global DOF at a node (raw-index accessor).
2237    ///
2238    /// `dof` is a raw index in the **global** system: `0 = ux`, `1 = uy`,
2239    /// `2 = rz`; the assembled slot is `3*node_idx + dof`
2240    /// ([`BeamModel::dof_index`]).
2241    ///
2242    /// # Errors
2243    ///
2244    /// [`FemError::InvalidInput`] if `dof` is not 0, 1, or 2.  Previously
2245    /// `dof >= 3` silently aliased into the following node's DOF slot; this
2246    /// is now rejected.  Prefer the typed [`Self::displacement_dof`] with
2247    /// [`Dof`] for compile-time safety.
2248    ///
2249    /// Out-of-range node indices return `Ok(0.0)` (no panic). Before a
2250    /// successful solve the whole displacement vector is zero, so this also
2251    /// returns `Ok(0.0)`.
2252    pub fn displacement(&self, node_idx: usize, dof: usize) -> Result<f64, FemError> {
2253        if dof >= 3 {
2254            return Err(FemError::InvalidInput(format!(
2255                "Invalid DOF index: {} (must be 0=Ux, 1=Uy, 2=Rz)",
2256                dof
2257            )));
2258        }
2259        let idx = self.model.dof_index(node_idx, dof);
2260        if idx < self.u_global.len() {
2261            Ok(self.u_global[idx])
2262        } else {
2263            Ok(0.0)
2264        }
2265    }
2266
2267    /// Typed counterpart of [`Self::displacement`]: displacement of `dof` at
2268    /// `node_idx`, in the **global** system.
2269    ///
2270    /// This is a direct extraction from the global displacement vector — no
2271    /// recalculation, so the value is exactly what [`Self::displacement`]
2272    /// returns for the corresponding raw index. Reading before a successful
2273    /// solve yields `0.0` (the displacement vector is initialised to zero).
2274    ///
2275    /// # Errors
2276    ///
2277    /// [`FemError::InvalidInput`] if `node_idx` is out of bounds. (With a typed
2278    /// [`Dof`] an out-of-range DOF is impossible.)
2279    ///
2280    /// # Examples
2281    ///
2282    /// ```rust
2283    /// use section_properties::beam_fem::{BeamElement, BeamModel, BeamNode, BeamSection, BeamSolver, Dof};
2284    /// use section_properties::material::Material;
2285    ///
2286    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
2287    /// let mut model = BeamModel::new();
2288    /// model.add_node(BeamNode::new(0, 0.0, 0.0));
2289    /// model.add_node(BeamNode::new(1, 1.0, 0.0));
2290    /// model.add_element(BeamElement::new(
2291    ///     0,
2292    ///     1,
2293    ///     Material::new(1.0, 0.3, 1.0, "unit"),
2294    ///     BeamSection::new(1.0, 1.0),
2295    /// )?);
2296    /// model.fix_node(0);
2297    /// model.add_nodal_force(1, 1, -100.0);
2298    ///
2299    /// let mut solver = BeamSolver::from_model(&model)?;
2300    /// solver.solve_configured()?;
2301    ///
2302    /// // tip deflection = -P L^3 / 3EI = -33.333...
2303    /// let uy = solver.displacement_dof(1, Dof::Uy)?;
2304    /// assert!((uy + 100.0 / 3.0).abs() < 1e-9);
2305    /// // identical to the raw-index accessor
2306    /// assert_eq!(uy, solver.displacement(1, 1)?);
2307    /// assert!(matches!(solver.displacement_dof(9, Dof::Uy), Err(_)));
2308    /// # Ok(())
2309    /// # }
2310    /// ```
2311    pub fn displacement_dof(&self, node_idx: usize, dof: Dof) -> Result<f64, FemError> {
2312        if node_idx >= self.model.nodes.len() {
2313            return Err(FemError::InvalidInput(format!(
2314                "Invalid node index: {} (max: {})",
2315                node_idx,
2316                self.model.nodes.len().saturating_sub(1)
2317            )));
2318        }
2319        let idx = self.model.dof_index(node_idx, dof.index());
2320        if idx < self.u_global.len() {
2321            Ok(self.u_global[idx])
2322        } else {
2323            Ok(0.0)
2324        }
2325    }
2326
2327    /// The full **global** displacement vector (borrowed, not copied).
2328    ///
2329    /// Laid out as `[ux0, uy0, rz0, ux1, uy1, rz1, ...]`, i.e. slot
2330    /// `3*node + dof` with `dof` = `0/1/2` = `ux/uy/rz`
2331    /// ([`BeamModel::dof_index`]). Before a successful solve every entry is
2332    /// `0.0`.
2333    pub fn displacements(&self) -> &[f64] {
2334        &self.u_global
2335    }
2336
2337    /// Compute the global external support reactions.
2338    ///
2339    /// `R = K_original · u - f_global`, evaluated on the **unconstrained**
2340    /// (assembled) system after the full displacement vector has been
2341    /// reconstructed from static condensation:
2342    ///
2343    /// - at a constrained DOF, `R` is the support reaction;
2344    /// - at a free DOF, `R` is numerically zero.
2345    ///
2346    /// Together with the applied loads the reactions satisfy global
2347    /// equilibrium (`ΣF = 0`, `ΣM = 0`). They are **not** element end forces;
2348    /// see [`Self::element_end_forces`] for those.
2349    ///
2350    /// # Pre-solve behaviour
2351    ///
2352    /// Before a successful solve the displacement vector is zero, so this
2353    /// returns the raw algebraic quantity `K·0 - f = -f` — **not** physical
2354    /// support reactions. Check [`Self::solver_name`] (`Some(..)` only after a
2355    /// successful solve), or use [`Self::results`], whose reaction snapshot
2356    /// sets free DOFs to exactly `0.0`.
2357    pub fn reactions(&self) -> Vec<f64> {
2358        // R = K_original * u - f_global
2359        let mut reactions = vec![0.0; self.n_dof];
2360
2361        // Compute K_original * u using public API
2362        let mut k_orig = self.k_original.clone();
2363        k_orig.compress();
2364        for i in 0..self.n_dof {
2365            let mut sum = 0.0;
2366            let row_ptr = k_orig.row_ptr();
2367            let csr_cols = k_orig.csr_cols();
2368            let csr_vals = k_orig.csr_vals();
2369            for idx in row_ptr[i]..row_ptr[i + 1] {
2370                let j = csr_cols[idx];
2371                sum += csr_vals[idx] * self.u_global[j];
2372            }
2373            reactions[i] = sum - self.f_global[i];
2374        }
2375
2376        reactions
2377    }
2378
2379    /// Get reaction at a specific DOF
2380    ///
2381    /// Raw-index accessor for the **global** reaction at `3*node_idx + dof`
2382    /// (`0 = ux` → `Fx`, `1 = uy` → `Fy`, `2 = rz` → `Mz`).
2383    ///
2384    /// # Errors
2385    ///
2386    /// [`FemError::InvalidInput`] if `dof` is not 0, 1, or 2.  Previously
2387    /// `dof >= 3` silently aliased into the following node's DOF slot; this
2388    /// is now rejected.  Prefer the typed [`Self::reaction_dof`] with [`Dof`]
2389    /// for compile-time safety.
2390    ///
2391    /// Out-of-range node indices return `Ok(0.0)` (no panic). Before a
2392    /// successful solve this returns the raw `K·0 - f` value, which is not
2393    /// a physical support reaction (see [`Self::reactions`]).
2394    pub fn reaction(&self, node_idx: usize, dof: usize) -> Result<f64, FemError> {
2395        if dof >= 3 {
2396            return Err(FemError::InvalidInput(format!(
2397                "Invalid DOF index: {} (must be 0=Ux, 1=Uy, 2=Rz)",
2398                dof
2399            )));
2400        }
2401        let idx = self.model.dof_index(node_idx, dof);
2402        if idx < self.reactions().len() {
2403            Ok(self.reactions()[idx])
2404        } else {
2405            Ok(0.0)
2406        }
2407    }
2408
2409    /// Typed counterpart of [`Self::reaction`]: **global** support reaction of
2410    /// `dof` at `node_idx`.
2411    ///
2412    /// - `Dof::Ux` → translational X reaction;
2413    /// - `Dof::Uy` → translational Y reaction;
2414    /// - `Dof::Rz` → rotational reaction about Z (counter-clockwise positive).
2415    ///
2416    /// Delegates to the same [`Self::reactions`] vector, so the value is
2417    /// exactly what [`Self::reaction`] returns for the corresponding raw index;
2418    /// only a single reaction evaluation is performed. At a free DOF the value
2419    /// is numerically zero.
2420    ///
2421    /// # Errors
2422    ///
2423    /// [`FemError::InvalidInput`] if `node_idx` is out of bounds.
2424    ///
2425    /// # Examples
2426    ///
2427    /// ```rust
2428    /// use section_properties::beam_fem::{BeamElement, BeamModel, BeamNode, BeamSection, BeamSolver, Dof};
2429    /// use section_properties::material::Material;
2430    ///
2431    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
2432    /// let mut model = BeamModel::new();
2433    /// model.add_node(BeamNode::new(0, 0.0, 0.0));
2434    /// model.add_node(BeamNode::new(1, 1.0, 0.0));
2435    /// model.add_element(BeamElement::new(
2436    ///     0,
2437    ///     1,
2438    ///     Material::new(1.0, 0.3, 1.0, "unit"),
2439    ///     BeamSection::new(1.0, 1.0),
2440    /// )?);
2441    /// model.fix_node(0);
2442    /// model.add_nodal_force(1, 1, -100.0);
2443    ///
2444    /// let mut solver = BeamSolver::from_model(&model)?;
2445    /// solver.solve_configured()?;
2446    ///
2447    /// // Support reactions: Ry = +P, Rz = +P·L
2448    /// let ry = solver.reaction_dof(0, Dof::Uy)?;
2449    /// let rz = solver.reaction_dof(0, Dof::Rz)?;
2450    /// assert!((ry - 100.0).abs() < 1e-9);
2451    /// assert!((rz - 100.0).abs() < 1e-9);
2452    /// assert_eq!(ry, solver.reaction(0, 1)?);
2453    /// # Ok(())
2454    /// # }
2455    /// ```
2456    pub fn reaction_dof(&self, node_idx: usize, dof: Dof) -> Result<f64, FemError> {
2457        if node_idx >= self.model.nodes.len() {
2458            return Err(FemError::InvalidInput(format!(
2459                "Invalid node index: {} (max: {})",
2460                node_idx,
2461                self.model.nodes.len().saturating_sub(1)
2462            )));
2463        }
2464        let reactions = self.reactions();
2465        let idx = self.model.dof_index(node_idx, dof.index());
2466        if idx < reactions.len() {
2467            Ok(reactions[idx])
2468        } else {
2469            Ok(0.0)
2470        }
2471    }
2472
2473    /// Access the original (unconstrained) global stiffness matrix.
2474    ///
2475    /// This is exposed crate-internally for debugging and diagnostics; it is
2476    /// not part of the public API surface.
2477    #[allow(dead_code)]
2478    pub(crate) fn stiffness_matrix(&self) -> &SparseMatrix {
2479        &self.k_original
2480    }
2481
2482    /// Compute element end forces in LOCAL coordinates.
2483    ///
2484    /// Returns a vector of 6 forces per element in local coordinates:
2485    /// `[N_i, V_i, M_i, N_j, V_j, M_j]`, where `N` is axial force, `V` is
2486    /// transverse shear force, and `M` is bending moment.
2487    ///
2488    /// # Sign convention
2489    ///
2490    /// These are the forces the ELEMENT applies to its end NODES (reaction
2491    /// sense), i.e. `f_end = f_equiv - K_local·u_local`. Positive `N` is
2492    /// tension on the node, positive `V` is upward on the node, and positive
2493    /// `M` is counter-clockwise on the node.
2494    ///
2495    /// Applied moments at nodes are external concentrated loads whose effect is
2496    /// carried by the displacement field `u` (through the global force vector),
2497    /// so no separate correction is needed here. Recovered end moments therefore
2498    /// automatically satisfy nodal moment equilibrium:
2499    ///
2500    /// - free-end node with applied moment `M`: `M_element_j + M ≈ 0`;
2501    /// - internal node with applied moment `M` shared by two elements:
2502    ///   `M_left_j + M_right_i + M ≈ 0`.
2503    ///
2504    /// # Scope: nodal end forces, NOT section internal forces
2505    ///
2506    /// This method returns the *element-on-node* nodal equilibrium forces at
2507    /// `ξ = 0` and `ξ = 1` only. It is **not** a beam-section internal-force
2508    /// diagram, and the two are not interchangeable when the element carries a
2509    /// distributed load, an interior point force, or an interior point moment:
2510    /// the end values here include the consistent-load contributions and say
2511    /// nothing about `N(x)`, `V(x)`, `M(x)` *inside* the element.
2512    ///
2513    /// For the internal resultants at an arbitrary `ξ`, use
2514    /// [`Self::element_section_forces`], which recovers `N(x)`, `V(x)`, `M(x)`
2515    /// from equilibrium (including the correct jumps across point loads and
2516    /// moments). Do not overload this method to mean both.
2517    ///
2518    /// # Errors
2519    ///
2520    /// Propagates any error from the equivalent point-load recovery
2521    /// (see `Self::element_equivalent_nodal_forces`); a failed recovery is
2522    /// never silently replaced by a zero load.
2523    pub fn element_end_forces(&self) -> Result<Vec<[f64; 6]>, FemError> {
2524        let mut results = Vec::with_capacity(self.model.elements.len());
2525        for elem_idx in 0..self.model.elements.len() {
2526            results.push(self.element_on_node_end_forces_local(elem_idx)?);
2527        }
2528        Ok(results)
2529    }
2530
2531    /// Local element displacement vector `[u_i, v_i, θ_i, u_j, v_j, θ_j]`.
2532    ///
2533    /// Returns the element's nodal displacements transformed from global to
2534    /// local coordinates (`u_local = T · u_global`).
2535    ///
2536    /// # Errors
2537    ///
2538    /// Returns [`FemError::InvalidInput`] if `element_idx` is out of bounds.
2539    fn element_local_displacement(&self, element_idx: usize) -> Result<[f64; 6], FemError> {
2540        let element = self.model.elements.get(element_idx).ok_or_else(|| {
2541            FemError::InvalidInput(format!(
2542                "Invalid element index: {} (max: {})",
2543                element_idx,
2544                self.model.elements.len().saturating_sub(1)
2545            ))
2546        })?;
2547        let node_i = self.model.nodes[element.node_i].point();
2548        let node_j = self.model.nodes[element.node_j].point();
2549
2550        let dof_map = [
2551            self.model.dof_index(element.node_i, 0), // u_i
2552            self.model.dof_index(element.node_i, 1), // v_i
2553            self.model.dof_index(element.node_i, 2), // θ_i
2554            self.model.dof_index(element.node_j, 0), // u_j
2555            self.model.dof_index(element.node_j, 1), // v_j
2556            self.model.dof_index(element.node_j, 2), // θ_j
2557        ];
2558        let u_global_elem = [
2559            self.u_global[dof_map[0]],
2560            self.u_global[dof_map[1]],
2561            self.u_global[dof_map[2]],
2562            self.u_global[dof_map[3]],
2563            self.u_global[dof_map[4]],
2564            self.u_global[dof_map[5]],
2565        ];
2566
2567        // Transform to local coordinates: u_local = T * u_global.
2568        let t = element.transformation_matrix(node_i, node_j);
2569        let mut u_local = [0.0; 6];
2570        for i in 0..6 {
2571            for j in 0..6 {
2572                u_local[i] += t[i][j] * u_global_elem[j];
2573            }
2574        }
2575        Ok(u_local)
2576    }
2577
2578    /// Element-on-node end forces in LOCAL coordinates for a single element:
2579    /// `f_end = f_equiv - K_local · u_local`, ordered
2580    /// `[N_i, V_i, M_i, N_j, V_j, M_j]`.
2581    ///
2582    /// # Errors
2583    ///
2584    /// Propagates errors from [`Self::element_local_displacement`] and
2585    /// [`Self::element_equivalent_nodal_forces`].
2586    fn element_on_node_end_forces_local(&self, element_idx: usize) -> Result<[f64; 6], FemError> {
2587        let element = self.model.elements.get(element_idx).ok_or_else(|| {
2588            FemError::InvalidInput(format!(
2589                "Invalid element index: {} (max: {})",
2590                element_idx,
2591                self.model.elements.len().saturating_sub(1)
2592            ))
2593        })?;
2594        let node_i = self.model.nodes[element.node_i].point();
2595        let node_j = self.model.nodes[element.node_j].point();
2596
2597        let u_local = self.element_local_displacement(element_idx)?;
2598
2599        // Internal nodal force: f_stiffness = K_local * u_local.
2600        let k_local = element.local_stiffness(node_i, node_j);
2601        let mut f_stiffness = [0.0; 6];
2602        for i in 0..6 {
2603            for j in 0..6 {
2604                f_stiffness[i] += k_local[i][j] * u_local[j];
2605            }
2606        }
2607
2608        // Equivalent nodal forces from distributed and point loads on this
2609        // element. Applied moments at nodes are external concentrated loads,
2610        // excluded from the equivalent element loads.
2611        let f_equiv = Self::element_equivalent_nodal_forces(
2612            &self.model,
2613            element_idx,
2614            element,
2615            node_i,
2616            node_j,
2617        )?;
2618
2619        // Element-on-node end forces: f_end = f_equiv - f_stiffness.
2620        let mut end_forces = [0.0; 6];
2621        for i in 0..6 {
2622            end_forces[i] = f_equiv[i] - f_stiffness[i];
2623        }
2624        Ok(end_forces)
2625    }
2626
2627    /// Compute equivalent nodal forces (in LOCAL coordinates) for an element
2628    /// from DISTRIBUTED and POINT loads (NOT including applied moments at
2629    /// nodes, which are external concentrated loads handled in the global
2630    /// force vector).
2631    ///
2632    /// Returns `[N_i, V_i, M_i, N_j, V_j, M_j]` in local coordinates.
2633    ///
2634    /// # Errors
2635    ///
2636    /// Propagates any error from [`BeamElement::consistent_nodal_load_point`]
2637    /// (for example a zero-length element). Point-load positions are validated
2638    /// when the load is added via [`BeamModel::add_point_load`], so in normal
2639    /// use this succeeds; the error path exists so that a failed equivalent-load
2640    /// computation can never be silently turned into a zero load.
2641    fn element_equivalent_nodal_forces(
2642        model: &BeamModel,
2643        elem_idx: usize,
2644        element: &BeamElement,
2645        node_i: Point,
2646        node_j: Point,
2647    ) -> Result<[f64; 6], FemError> {
2648        let mut f_equiv = [0.0; 6];
2649
2650        // Distributed loads on this element.
2651        for dl in &model.distributed_loads {
2652            if dl.element_idx == elem_idx {
2653                let f_local = element.consistent_nodal_load(node_i, node_j, dl.qx, dl.qy)?;
2654                for i in 0..6 {
2655                    f_equiv[i] += f_local[i];
2656                }
2657            }
2658        }
2659
2660        // Point loads on this element.
2661        for pl in &model.point_loads {
2662            if pl.element_idx == elem_idx {
2663                let f_local = element.consistent_nodal_load_point(
2664                    node_i,
2665                    node_j,
2666                    pl.position,
2667                    pl.fx,
2668                    pl.fy,
2669                    pl.mz,
2670                )?;
2671                for i in 0..6 {
2672                    f_equiv[i] += f_local[i];
2673                }
2674            }
2675        }
2676
2677        Ok(f_equiv)
2678    }
2679
2680    /// Compute element end forces in GLOBAL coordinates
2681    ///
2682    /// Returns a vector of 6 forces per element in global coordinates:
2683    /// [Fx_i, Fy_i, Mz_i, Fx_j, Fy_j, Mz_j]
2684    ///
2685    /// # Errors
2686    ///
2687    /// Propagates any error from [`Self::element_end_forces`].
2688    pub fn element_end_forces_global(&self) -> Result<Vec<[f64; 6]>, FemError> {
2689        let local_forces = self.element_end_forces()?;
2690        let mut results = Vec::new();
2691
2692        for (idx, forces) in local_forces.iter().enumerate() {
2693            let element = &self.model.elements[idx];
2694            let node_i = self.model.nodes[element.node_i].point();
2695            let node_j = self.model.nodes[element.node_j].point();
2696
2697            let T = element.transformation_matrix(node_i, node_j);
2698
2699            // Transform local forces to global: f_global = T^T * f_local
2700            let mut f_global_elem = [0.0; 6];
2701            for i in 0..6 {
2702                for j in 0..6 {
2703                    f_global_elem[i] += T[j][i] * forces[j];
2704                }
2705            }
2706
2707            results.push(f_global_elem);
2708        }
2709
2710        Ok(results)
2711    }
2712
2713    /// Compute the internal section forces `N`, `V`, `M` at normalized position
2714    /// `xi` along element `element_idx`, in LOCAL coordinates.
2715    ///
2716    /// `xi = 0` at `node_i` and `xi = 1` at `node_j`; the physical position is
2717    /// `x = xi · L`.
2718    ///
2719    /// # What this returns
2720    ///
2721    /// True beam-section internal resultants at the cut (see [`SectionForces`]
2722    /// for the sign convention):
2723    /// - `axial` (`N`): tension positive,
2724    /// - `shear` (`V`): satisfies `d(moment)/dx = shear`,
2725    /// - `moment` (`M`): sagging positive.
2726    ///
2727    /// These are beam-LOCAL quantities (not transformed to global axes). They
2728    /// are deliberately distinct from [`Self::element_end_forces`], which
2729    /// returns the element-on-node *nodal equilibrium* forces at the two ends
2730    /// only.
2731    ///
2732    /// # Method (equilibrium recovery)
2733    ///
2734    /// The result is obtained by enforcing equilibrium of the element segment
2735    /// `[0, x]` using the recovered i-end element-on-node force and the actual
2736    /// distributed / point loads — **not** by linearly interpolating the end
2737    /// forces. With the local axes of this module (+x from `node_i` to
2738    /// `node_j`, +y transverse with upward load `qy > 0`, `θ` CCW) and the
2739    /// i-end force `f_i = [N_i, V_i, M_i]` from [`Self::element_end_forces`]:
2740    ///
2741    /// ```text
2742    /// N(x) = N_i - qx·x - Σ_{x_p < x} fx_p
2743    /// V(x) = -V_i + qy·x + Σ_{x_p < x} fy_p
2744    /// M(x) = M_i - x·V_i + qy·x²/2 - Σ_{x_p < x} [(x_p - x)·fy_p + mz_p]
2745    /// ```
2746    ///
2747    /// This is the equilibrium-consistent extension of the Euler–Bernoulli
2748    /// relations: for an element with no span load (no distributed load and no
2749    /// interior point load) it reduces to the classical `N = E·A·du/dx` and
2750    /// `M = E·I·v''` implied by the element's cubic Hermite field, while
2751    /// additionally satisfying
2752    ///
2753    /// ```text
2754    /// dN/dx = -qx
2755    /// dV/dx =  qy          (qy = upward load intensity; = -q_down)
2756    /// dM/dx =  V
2757    /// ```
2758    ///
2759    /// and reproducing the correct jumps at interior point forces / moments.
2760    /// For statically determinate loadings the section forces are exact.
2761    ///
2762    /// # Discontinuities (point loads inside the element)
2763    ///
2764    /// A load at `x_p = xi_p · L` introduces a jump with this convention:
2765    ///
2766    /// ```text
2767    /// N(xi_p⁺) - N(xi_p⁻) = -fx_p
2768    /// V(xi_p⁺) - V(xi_p⁻) = +fy_p
2769    /// M(xi_p⁺) - M(xi_p⁻) = -mz_p
2770    /// ```
2771    ///
2772    /// Evaluating exactly at `xi = xi_p` returns the **left limit**
2773    /// (`x -> xi_p⁻`): loads located strictly before `xi` are included and a
2774    /// load exactly at `xi` is excluded. Evaluate at `xi_p ± ε` (or on the
2775    /// adjacent elements) to obtain the right-hand value.
2776    ///
2777    /// # Relation to element end forces
2778    ///
2779    /// At the element ends the section forces agree with
2780    /// [`Self::element_end_forces`] up to the sign factors of the
2781    /// internal-force convention:
2782    ///
2783    /// ```text
2784    /// xi = 0:  N = +N_i,  V = -V_i,  M = +M_i
2785    /// xi = 1:  N = -N_j,  V = +V_j,  M = -M_j
2786    /// ```
2787    ///
2788    /// # Nodal applied moments vs. interior point moments
2789    ///
2790    /// Two different moment-load mechanisms exist and must not be conflated:
2791    ///
2792    /// - [`BeamModel::add_point_load`] / [`BeamModel::add_point_moment`] stores
2793    ///   a moment *inside* an element (`0 < xi_p < 1`). It is a span load and
2794    ///   produces the interior jump `M(xi_p⁺) - M(xi_p⁻) = -mz_p` above.
2795    /// - [`BeamModel::add_applied_moment`] stores a concentrated moment at a
2796    ///   *mesh node*. It is **not** a span load: it enters the global force
2797    ///   vector (the θ DOF) and is therefore already carried by the
2798    ///   element-on-node end forces from which this recovery is built, so no
2799    ///   separate term is added here. (Adding one would double-count it.)
2800    ///
2801    /// For an internal node shared by elements `e` and `e+1` carrying an
2802    /// applied nodal moment `M_ext`, the recovered section moments on the two
2803    /// sides satisfy the nodal moment equilibrium
2804    ///
2805    /// ```text
2806    /// M(e+1, xi=0) - M(e, xi=1) + M_ext = 0
2807    /// ```
2808    ///
2809    /// which is the section-force form of the element-on-node end-force
2810    /// equilibrium `M_j(e) + M_i(e+1) + M_ext = 0` under the boundary relations
2811    /// above. Equivalently, the internal moment jumps by `-M_ext` across the
2812    /// node — the same sign as an interior point moment of equal value. A nodal
2813    /// moment applied at a free end yields a constant `+M_ext` along the
2814    /// element.
2815    ///
2816    /// ## Internal-node limits
2817    ///
2818    /// The "exact evaluation returns the left limit" rule applies to interior
2819    /// point loads with `0 < xi_p < 1`. A nodal applied moment is not evaluated
2820    /// from within one element; the meaningful statement is the two-sided
2821    /// equilibrium relation above between `element_section_forces(e, 1.0)` and
2822    /// `element_section_forces(e+1, 0.0)`.
2823    ///
2824    /// # Errors
2825    ///
2826    /// Returns [`FemError::InvalidInput`] if `element_idx` is out of bounds,
2827    /// if `xi` is outside `[0, 1]`, or if the element has zero length.
2828    pub fn element_section_forces(
2829        &self,
2830        element_idx: usize,
2831        xi: f64,
2832    ) -> Result<SectionForces, FemError> {
2833        let element = self.model.elements.get(element_idx).ok_or_else(|| {
2834            FemError::InvalidInput(format!(
2835                "Invalid element index: {} (max: {})",
2836                element_idx,
2837                self.model.elements.len().saturating_sub(1)
2838            ))
2839        })?;
2840        if !(0.0..=1.0).contains(&xi) {
2841            return Err(FemError::InvalidInput(format!(
2842                "Section position xi must be in [0, 1], got {}",
2843                xi
2844            )));
2845        }
2846        let node_i = self.model.nodes[element.node_i].point();
2847        let node_j = self.model.nodes[element.node_j].point();
2848        let length = element.length(node_i, node_j);
2849        if length <= 0.0 {
2850            return Err(FemError::InvalidInput(
2851                "Beam element has zero or negative length for section-force recovery".to_string(),
2852            ));
2853        }
2854
2855        let x = xi * length;
2856
2857        // Anchor at the i-end element-on-node force (LOCAL): [N_i, V_i, M_i, ...].
2858        let f_end = self.element_on_node_end_forces_local(element_idx)?;
2859        let n_i = f_end[0];
2860        let v_i = f_end[1];
2861        let m_i = f_end[2];
2862
2863        // Uniform distributed load on this element (LOCAL), summed if repeated.
2864        let mut qx = 0.0;
2865        let mut qy = 0.0;
2866        for dl in &self.model.distributed_loads {
2867            if dl.element_idx == element_idx {
2868                qx += dl.qx;
2869                qy += dl.qy;
2870            }
2871        }
2872
2873        // Point loads strictly to the left of x (left-limit convention).
2874        let mut sum_fx = 0.0;
2875        let mut sum_fy = 0.0;
2876        let mut sum_moment = 0.0;
2877        for pl in &self.model.point_loads {
2878            if pl.element_idx != element_idx {
2879                continue;
2880            }
2881            let x_p = pl.position * length;
2882            if x_p < x {
2883                sum_fx += pl.fx;
2884                sum_fy += pl.fy;
2885                sum_moment += (x_p - x) * pl.fy + pl.mz;
2886            }
2887        }
2888
2889        let axial = n_i - qx * x - sum_fx;
2890        let shear = -v_i + qy * x + sum_fy;
2891        let moment = m_i - x * v_i + 0.5 * qy * x * x - sum_moment;
2892
2893        Ok(SectionForces::new(axial, shear, moment))
2894    }
2895
2896    /// Beam arclength from the start of element 0 to the start (`xi = 0`) of
2897    /// `element_index`, accumulated in model order.
2898    ///
2899    /// Private helper shared by the sampling APIs. `element_index` is assumed
2900    /// already validated; indices `>= elements.len()` simply sum all elements.
2901    fn element_start_distance(&self, element_index: usize) -> f64 {
2902        self.model
2903            .elements
2904            .iter()
2905            .take(element_index)
2906            .map(|e| {
2907                let ni = self.model.nodes[e.node_i].point();
2908                let nj = self.model.nodes[e.node_j].point();
2909                e.length(ni, nj)
2910            })
2911            .sum()
2912    }
2913
2914    /// Sample the internal-force diagram of a single element at `n` uniformly
2915    /// spaced points, including both endpoints.
2916    ///
2917    /// Samples `xi = k / (n - 1)` for `k = 0..=n-1` (i.e. `k = 0, 1, …, n-1`),
2918    /// so `xi = 0` and `xi = 1` are always included. Each sample delegates to
2919    /// [`Self::element_section_forces`] — the N/V/M values are **not**
2920    /// interpolated or recomputed here.
2921    ///
2922    /// # Arguments
2923    ///
2924    /// - `element_index`: element index in `BeamModel::elements` order.
2925    /// - `n`: number of samples, must be `>= 2`.
2926    ///
2927    /// The returned samples carry the global beam arclength `x` (see
2928    /// [`BeamForceSample`]), measured from the start of element 0, so a sample
2929    /// on element `e` starts at `Σ_{k < e} length(k)`.
2930    ///
2931    /// # Discontinuities
2932    ///
2933    /// If a uniform `xi` lands exactly on an interior point load, the value is
2934    /// the existing **left-limit** result of
2935    /// [`Self::element_section_forces`]. No epsilon sampling is applied.
2936    ///
2937    /// # Errors
2938    ///
2939    /// Returns [`FemError::InvalidInput`] if `n < 2`, if `element_index` is out
2940    /// of bounds, or if the element has zero length.
2941    pub fn sample_element_forces(
2942        &self,
2943        element_index: usize,
2944        n: usize,
2945    ) -> Result<Vec<BeamForceSample>, FemError> {
2946        if n < 2 {
2947            return Err(FemError::InvalidInput(format!(
2948                "Number of samples n must be >= 2, got {}",
2949                n
2950            )));
2951        }
2952        if element_index >= self.model.elements.len() {
2953            return Err(FemError::InvalidInput(format!(
2954                "Invalid element index: {} (max: {})",
2955                element_index,
2956                self.model.elements.len().saturating_sub(1)
2957            )));
2958        }
2959
2960        let element = &self.model.elements[element_index];
2961        let node_i = self.model.nodes[element.node_i].point();
2962        let node_j = self.model.nodes[element.node_j].point();
2963        let length = element.length(node_i, node_j);
2964        let start = self.element_start_distance(element_index);
2965
2966        let mut samples = Vec::with_capacity(n);
2967        for k in 0..n {
2968            let xi = k as f64 / (n - 1) as f64;
2969            // Delegates to the authoritative recovery (also validates a
2970            // zero-length element via its existing error path).
2971            let section_forces = self.element_section_forces(element_index, xi)?;
2972            samples.push(BeamForceSample {
2973                element_index,
2974                xi,
2975                x: start + xi * length,
2976                section_forces,
2977            });
2978        }
2979        Ok(samples)
2980    }
2981
2982    /// Sample the internal-force diagram of the whole beam at `n_per_element`
2983    /// uniformly spaced points per element.
2984    ///
2985    /// Elements are traversed in `BeamModel::elements` order. Global `x` is the
2986    /// physical beam arclength accumulated over the true element lengths (equal
2987    /// lengths are NOT assumed):
2988    /// `x = Σ_{k < e} length(k) + xi · length(e)`.
2989    ///
2990    /// # Shared boundaries are duplicated on purpose
2991    ///
2992    /// The last sample of element `e` (`xi = 1`) and the first sample of
2993    /// element `e+1` (`xi = 0`) share the same `x`. Both are returned:
2994    ///
2995    /// - when the internal force is continuous, the two values agree;
2996    /// - at a point force / moment discontinuity they differ and represent the
2997    ///   two one-sided limits.
2998    ///
2999    /// Duplicate `x` coordinates are **never** deduplicated — doing so would
3000    /// destroy discontinuities for a future plotting layer.
3001    ///
3002    /// # Errors
3003    ///
3004    /// Returns [`FemError::InvalidInput`] if `n_per_element < 2`, or for any
3005    /// per-element error from [`Self::sample_element_forces`].
3006    pub fn sample_beam_forces(
3007        &self,
3008        n_per_element: usize,
3009    ) -> Result<Vec<BeamForceSample>, FemError> {
3010        if n_per_element < 2 {
3011            return Err(FemError::InvalidInput(format!(
3012                "Number of samples per element must be >= 2, got {}",
3013                n_per_element
3014            )));
3015        }
3016        let mut samples = Vec::with_capacity(n_per_element * self.model.elements.len());
3017        for element_index in 0..self.model.elements.len() {
3018            samples.extend(self.sample_element_forces(element_index, n_per_element)?);
3019        }
3020        Ok(samples)
3021    }
3022
3023    /// Sample the whole beam and wrap the result in a [`BeamForceDiagram`].
3024    ///
3025    /// Equivalent to [`Self::sample_beam_forces`] plus a container. No
3026    /// interpolation is performed.
3027    ///
3028    /// # Errors
3029    ///
3030    /// Same as [`Self::sample_beam_forces`].
3031    pub fn beam_force_diagram(&self, n_per_element: usize) -> Result<BeamForceDiagram, FemError> {
3032        Ok(BeamForceDiagram::new(
3033            self.sample_beam_forces(n_per_element)?,
3034        ))
3035    }
3036
3037    /// Build a unified, read-only [`BeamAnalysisResult`] view of this solver.
3038    ///
3039    /// This does **not** run the solver: it is a cheap, infallible view over the
3040    /// current displacement state, so call [`Self::solve`] first. The reaction
3041    /// vector is snapshotted once here (masking unconstrained DOFs to exactly
3042    /// zero); everything else is delegated lazily to the solver.
3043    pub fn results(&self) -> BeamAnalysisResult<'_> {
3044        let mut reactions = self.reactions();
3045        for (i, reaction) in reactions.iter_mut().enumerate() {
3046            if !self.fixed_dofs[i] {
3047                *reaction = 0.0;
3048            }
3049        }
3050        BeamAnalysisResult {
3051            solver: self,
3052            reactions,
3053        }
3054    }
3055}
3056
3057/// FemError for beam FEM
3058#[derive(Debug, Clone, thiserror::Error)]
3059pub enum FemError {
3060    #[error("Invalid model: {0}")]
3061    InvalidModel(String),
3062    #[error("Solver error: {message}")]
3063    SolverError {
3064        /// The structured solver error that caused the failure.
3065        source: SolverError,
3066        /// Human-readable message, potentially including structural diagnosis.
3067        message: String,
3068    },
3069    #[error("Invalid input: {0}")]
3070    InvalidInput(String),
3071    #[error("Singular matrix: {0}")]
3072    SingularMatrix(String),
3073    // ---- frame-level structural diagnostics (see `crate::frame`) ----------
3074    #[error("Invalid node: {0}")]
3075    InvalidNode(String),
3076    #[error("Invalid member: {0}")]
3077    InvalidMember(String),
3078    #[error("Zero-length member: {0}")]
3079    ZeroLengthMember(String),
3080    #[error("Duplicate member: {0}")]
3081    DuplicateMember(String),
3082    #[error("Orphan node: {0}")]
3083    OrphanNode(String),
3084    #[error("Disconnected structure: {0}")]
3085    DisconnectedStructure(String),
3086    #[error(
3087        "Conflicting prescribed displacement at node {node_idx}, DOF {dof}: \
3088             first value {first_value}, conflicting value {conflicting_value}"
3089    )]
3090    ConflictingPrescribedDisplacement {
3091        node_idx: usize,
3092        dof: usize,
3093        first_value: f64,
3094        conflicting_value: f64,
3095    },
3096}
3097
3098impl FemError {
3099    /// Return the structured [`SolverError`] if this is a `SolverError` variant.
3100    pub fn solver_error(&self) -> Option<&SolverError> {
3101        match self {
3102            FemError::SolverError { source, .. } => Some(source),
3103            _ => None,
3104        }
3105    }
3106}
3107
3108impl From<SolverError> for FemError {
3109    fn from(e: SolverError) -> Self {
3110        FemError::SolverError {
3111            message: e.to_string(),
3112            source: e,
3113        }
3114    }
3115}
3116
3117/// High-level API for beam analysis
3118pub struct BeamAnalysis;
3119
3120impl BeamAnalysis {
3121    /// Analyze a cantilever beam with tip load
3122    pub fn cantilever_tip_load(L: f64, E: f64, _A: f64, I: f64, P: f64) -> (f64, f64, f64) {
3123        // Analytical solutions for cantilever with tip load P at free end
3124        // Fixed at x=0, load P downward (transverse) at x=L
3125        let u_tip = 0.0; // No axial displacement for transverse load
3126        let v_tip = P * L.powi(3) / (3.0 * E * I); // Transverse deflection
3127        let theta_tip = P * L.powi(2) / (2.0 * E * I); // Rotation
3128
3129        (u_tip, v_tip, theta_tip)
3130    }
3131
3132    /// Analyze a simply supported beam with central point load
3133    pub fn simply_supported_central_load(L: f64, E: f64, I: f64, P: f64) -> (f64, f64) {
3134        // Central deflection and rotation at support
3135        let v_mid = P * L.powi(3) / (48.0 * E * I);
3136        let theta_support = P * L.powi(2) / (16.0 * E * I);
3137        (v_mid, theta_support)
3138    }
3139}
3140
3141#[cfg(test)]
3142mod tests {
3143    use super::*;
3144    use crate::material::Material;
3145
3146    #[test]
3147    fn test_beam_section_creation() {
3148        let sec = BeamSection::new(1.0, 1.0);
3149        assert_eq!(sec.area, 1.0);
3150        assert_eq!(sec.second_moment, 1.0);
3151
3152        let rect = BeamSection::rectangle(0.1, 0.2);
3153        assert!((rect.area - 0.02).abs() < 1e-10);
3154        assert!((rect.second_moment - 0.1 * 0.2_f64.powi(3) / 12.0).abs() < 1e-10);
3155
3156        let circ = BeamSection::circle(0.05);
3157        assert!((circ.area - std::f64::consts::PI * 0.0025).abs() < 1e-10);
3158    }
3159
3160    #[test]
3161    fn test_local_stiffness() {
3162        let material = Material::new(200e9, 0.3, 7850.0, "Steel");
3163        let section = BeamSection::new(0.01, 8.333e-6);
3164        let element = BeamElement::new(0, 1, material, section).unwrap();
3165
3166        let node_i = Point::new(0.0, 0.0);
3167        let node_j = Point::new(1.0, 0.0);
3168
3169        let k = element.local_stiffness(node_i, node_j);
3170
3171        // Check symmetry
3172        for i in 0..6 {
3173            for j in 0..6 {
3174                assert!(
3175                    (k[i][j] - k[j][i]).abs() < 1e-10,
3176                    "Matrix not symmetric at ({},{})",
3177                    i,
3178                    j
3179                );
3180            }
3181        }
3182
3183        // Check axial terms
3184        let E: f64 = 200e9;
3185        let A: f64 = 0.01;
3186        let L: f64 = 1.0;
3187        let EA_L = E * A / L;
3188        assert!((k[0][0] - EA_L).abs() < 1e-6);
3189        assert!((k[0][3] + EA_L).abs() < 1e-6);
3190        assert!((k[3][3] - EA_L).abs() < 1e-6);
3191
3192        // Check bending terms
3193        let I: f64 = 8.333e-6;
3194        let EI_L3 = E * I / L.powi(3);
3195        let EI_L2 = E * I / L.powi(2);
3196        let EI_L = E * I / L;
3197
3198        assert!((k[1][1] - 12.0 * EI_L3).abs() < 1e-6);
3199        assert!((k[1][2] - 6.0 * EI_L2).abs() < 1e-6);
3200        assert!((k[2][2] - 4.0 * EI_L).abs() < 1e-6);
3201        assert!((k[4][4] - 12.0 * EI_L3).abs() < 1e-6);
3202        assert!((k[5][5] - 4.0 * EI_L).abs() < 1e-6);
3203    }
3204
3205    #[test]
3206    fn test_transformation_matrix() {
3207        let material = Material::new(200e9, 0.3, 7850.0, "Steel");
3208        let section = BeamSection::new(0.01, 8.333e-6);
3209        let element = BeamElement::new(0, 1, material, section).unwrap();
3210
3211        // Horizontal beam
3212        let node_i = Point::new(0.0, 0.0);
3213        let node_j = Point::new(1.0, 0.0);
3214        let T = element.transformation_matrix(node_i, node_j);
3215
3216        // For horizontal beam: c=1, s=0
3217        assert!((T[0][0] - 1.0).abs() < 1e-10);
3218        assert!((T[1][1] - 1.0).abs() < 1e-10);
3219        assert!((T[2][2] - 1.0).abs() < 1e-10);
3220        assert!((T[3][3] - 1.0).abs() < 1e-10);
3221        assert!((T[4][4] - 1.0).abs() < 1e-10);
3222        assert!((T[5][5] - 1.0).abs() < 1e-10);
3223
3224        // Vertical beam
3225        let node_i = Point::new(0.0, 0.0);
3226        let node_j = Point::new(0.0, 1.0);
3227        let T = element.transformation_matrix(node_i, node_j);
3228
3229        // For vertical beam: c=0, s=1
3230        assert!((T[0][0] - 0.0).abs() < 1e-10); // c
3231        assert!((T[0][1] - 1.0).abs() < 1e-10); // s
3232        assert!((T[1][0] - -1.0).abs() < 1e-10); // -s
3233        assert!((T[1][1] - 0.0).abs() < 1e-10); // c
3234    }
3235
3236    #[test]
3237    fn test_global_stiffness_horizontal() {
3238        let material = Material::new(200e9, 0.3, 7850.0, "Steel");
3239        let section = BeamSection::new(0.01, 8.333e-6);
3240        let element = BeamElement::new(0, 1, material, section).unwrap();
3241
3242        let node_i = Point::new(0.0, 0.0);
3243        let node_j = Point::new(1.0, 0.0);
3244
3245        let k_global = element.global_stiffness(node_i, node_j);
3246        let k_local = element.local_stiffness(node_i, node_j);
3247
3248        // For horizontal beam, global should equal local
3249        for i in 0..6 {
3250            for j in 0..6 {
3251                assert!((k_global[i][j] - k_local[i][j]).abs() < 1e-10);
3252            }
3253        }
3254    }
3255
3256    #[test]
3257    fn test_global_stiffness_vertical() {
3258        let material = Material::new(200e9, 0.3, 7850.0, "Steel");
3259        let section = BeamSection::new(0.01, 8.333e-6);
3260        let element = BeamElement::new(0, 1, material, section).unwrap();
3261
3262        let node_i = Point::new(0.0, 0.0);
3263        let node_j = Point::new(0.0, 1.0);
3264
3265        let k_global = element.global_stiffness(node_i, node_j);
3266
3267        // Check symmetry
3268        for i in 0..6 {
3269            for j in 0..6 {
3270                assert!((k_global[i][j] - k_global[j][i]).abs() < 1e-10);
3271            }
3272        }
3273    }
3274
3275    #[test]
3276    fn test_cantilever_analytical() {
3277        let L = 1.0;
3278        let E = 200e9;
3279        let A = 0.01;
3280        let I = 8.333e-6;
3281        let P = 1000.0;
3282
3283        let (u_tip, v_tip, theta_tip) = BeamAnalysis::cantilever_tip_load(L, E, A, I, P);
3284
3285        // For tip load P downward: axial = 0, v = PL³/3EI, θ = PL²/2EI
3286        let expected_v = P * L.powi(3) / (3.0 * E * I);
3287        let expected_theta = P * L.powi(2) / (2.0 * E * I);
3288
3289        assert!((v_tip - expected_v).abs() < 1e-10);
3290        assert!((theta_tip - expected_theta).abs() < 1e-10);
3291        assert!(u_tip.abs() < 1e-10); // No axial load in this case
3292    }
3293
3294    #[test]
3295    fn test_beam_model() {
3296        let mut model = BeamModel::new();
3297
3298        model.add_node(BeamNode::new(0, 0.0, 0.0));
3299        model.add_node(BeamNode::new(1, 1.0, 0.0));
3300
3301        let material = Material::new(200e9, 0.3, 7850.0, "Steel");
3302        let section = BeamSection::new(0.01, 8.333e-6);
3303        model.add_element(BeamElement::new(0, 1, material, section).unwrap());
3304
3305        model.fix_node(0);
3306        model.add_nodal_force(1, 1, -1000.0); // Downward force at tip
3307
3308        assert_eq!(model.n_dof(), 6);
3309        assert_eq!(model.dof_index(0, 0), 0);
3310        assert_eq!(model.dof_index(0, 1), 1);
3311        assert_eq!(model.dof_index(0, 2), 2);
3312        assert_eq!(model.dof_index(1, 0), 3);
3313        assert_eq!(model.dof_index(1, 1), 4);
3314        assert_eq!(model.dof_index(1, 2), 5);
3315    }
3316
3317    #[test]
3318    fn p1_02_reproduce_conflicting_prescribed_displacement() {
3319        let mut model = BeamModel::new();
3320        model.add_node(BeamNode::new(0, 0.0, 0.0));
3321        model.add_node(BeamNode::new(1, 1.0, 0.0));
3322        model.try_fix_dof(0, 1, 0.0).unwrap();
3323        let result = model.try_fix_dof(0, 1, 0.01);
3324        match result {
3325            Ok(()) => {
3326                panic!("P1-02 NOT fixed: conflicting prescribed displacement silently accepted")
3327            }
3328            Err(e) => println!("P1-02 confirmed: got Err = {:?}", e),
3329        }
3330    }
3331
3332    #[test]
3333    fn p1_02_same_prescribed_value_is_idempotent() {
3334        let mut model = BeamModel::new();
3335        model.add_node(BeamNode::new(0, 0.0, 0.0));
3336        model.add_node(BeamNode::new(1, 1.0, 0.0));
3337        model.try_fix_dof(0, 1, 0.005).unwrap();
3338        model.try_fix_dof(0, 1, 0.005).unwrap();
3339        assert_eq!(model.fixed_dofs.len(), 1);
3340    }
3341
3342    #[test]
3343    fn p1_02_different_dofs_are_independent() {
3344        let mut model = BeamModel::new();
3345        model.add_node(BeamNode::new(0, 0.0, 0.0));
3346        model.add_node(BeamNode::new(1, 1.0, 0.0));
3347        model.try_fix_dof(0, 0, 0.0).unwrap();
3348        model.try_fix_dof(0, 1, 0.01).unwrap();
3349        model.try_fix_dof(0, 2, 0.02).unwrap();
3350    }
3351
3352    #[test]
3353    fn p1_02_different_nodes_are_independent() {
3354        let mut model = BeamModel::new();
3355        model.add_node(BeamNode::new(0, 0.0, 0.0));
3356        model.add_node(BeamNode::new(1, 1.0, 0.0));
3357        model.try_fix_dof(0, 0, 0.0).unwrap();
3358        model.try_fix_dof(1, 0, 0.01).unwrap();
3359    }
3360
3361    #[test]
3362    fn p1_02_override_after_fix_allows_settlement() {
3363        let mut model = BeamModel::new();
3364        model.add_node(BeamNode::new(0, 0.0, 0.0));
3365        model.add_node(BeamNode::new(1, 1.0, 0.0));
3366        model.try_fix_node(0).unwrap();
3367        model.try_override_dof(0, 1, -0.005).unwrap();
3368        assert_eq!(model.fixed_dofs.len(), 3);
3369        let uy = model
3370            .fixed_dofs
3371            .iter()
3372            .find(|&&(n, d, _)| n == 0 && d == 1)
3373            .map(|&(_, _, v)| v)
3374            .unwrap();
3375        assert_eq!(uy, -0.005);
3376    }
3377
3378    #[test]
3379    fn p1_02_override_replaces_existing_value() {
3380        let mut model = BeamModel::new();
3381        model.add_node(BeamNode::new(0, 0.0, 0.0));
3382        model.add_node(BeamNode::new(1, 1.0, 0.0));
3383        model.try_override_dof(0, 1, 0.01).unwrap();
3384        model.try_override_dof(0, 1, 0.02).unwrap();
3385        assert_eq!(model.fixed_dofs.len(), 1);
3386        assert_eq!(model.fixed_dofs[0].2, 0.02);
3387    }
3388}