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, `value`
1147    /// is not finite, or the DOF already has a conflicting prescribed value
1148    /// (programmer error). Use [`Self::try_fix_dof`] for a 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), a
1156    /// non-finite prescribed value, or a conflicting existing prescribed
1157    /// displacement on the same DOF, instead of panicking.
1158    pub fn try_fix_dof(&mut self, node_idx: usize, dof: usize, value: f64) -> Result<(), FemError> {
1159        if node_idx >= self.nodes.len() {
1160            return Err(FemError::InvalidInput(format!(
1161                "Invalid node index: {} (max: {})",
1162                node_idx,
1163                self.nodes.len().saturating_sub(1)
1164            )));
1165        }
1166        if dof >= 3 {
1167            return Err(FemError::InvalidInput(format!(
1168                "Invalid DOF: {} (must be 0, 1, or 2)",
1169                dof
1170            )));
1171        }
1172        if !value.is_finite() {
1173            return Err(FemError::InvalidInput(format!(
1174                "Prescribed value must be finite, got {}",
1175                value
1176            )));
1177        }
1178        for &(n, d, v) in &self.fixed_dofs {
1179            if n == node_idx && d == dof {
1180                let scale = (v.abs() + value.abs()).max(1.0);
1181                if (v - value).abs() > 1e-12 * scale {
1182                    return Err(FemError::ConflictingPrescribedDisplacement {
1183                        node_idx,
1184                        dof,
1185                        first_value: v,
1186                        conflicting_value: value,
1187                    });
1188                }
1189                return Ok(());
1190            }
1191        }
1192        self.fixed_dofs.push((node_idx, dof, value));
1193        Ok(())
1194    }
1195
1196    /// Override (upsert) a prescribed displacement: if `(node_idx, dof)` is
1197    /// already constrained, replace its value; otherwise add a new constraint.
1198    ///
1199    /// Unlike [`Self::try_fix_dof`], this does **not** detect conflicting
1200    /// values — it silently replaces the previous prescription.  Use this when
1201    /// the caller explicitly intends to override (e.g. applying a support
1202    /// settlement after a full fix).
1203    pub fn try_override_dof(
1204        &mut self,
1205        node_idx: usize,
1206        dof: usize,
1207        value: f64,
1208    ) -> Result<(), FemError> {
1209        if node_idx >= self.nodes.len() {
1210            return Err(FemError::InvalidInput(format!(
1211                "Invalid node index: {} (max: {})",
1212                node_idx,
1213                self.nodes.len().saturating_sub(1)
1214            )));
1215        }
1216        if dof >= 3 {
1217            return Err(FemError::InvalidInput(format!(
1218                "Invalid DOF: {} (must be 0, 1, or 2)",
1219                dof
1220            )));
1221        }
1222        if !value.is_finite() {
1223            return Err(FemError::InvalidInput(format!(
1224                "Prescribed value must be finite, got {}",
1225                value
1226            )));
1227        }
1228        for entry in &mut self.fixed_dofs {
1229            if entry.0 == node_idx && entry.1 == dof {
1230                entry.2 = value;
1231                return Ok(());
1232            }
1233        }
1234        self.fixed_dofs.push((node_idx, dof, value));
1235        Ok(())
1236    }
1237
1238    /// Fix a node completely (all 3 DOFs to 0).
1239    ///
1240    /// Panics if `node_idx` is out of bounds or any DOF already has a
1241    /// conflicting prescribed value (programmer error). Use
1242    /// [`Self::try_fix_node`] for a fallible version.
1243    pub fn fix_node(&mut self, node_idx: usize) {
1244        self.try_fix_node(node_idx)
1245            .unwrap_or_else(|e| panic!("{}", e));
1246    }
1247
1248    /// Fallible counterpart of [`Self::fix_node`]: returns a structured error
1249    /// for an out-of-bounds node index or a conflicting existing prescribed
1250    /// displacement on any of the node's DOFs, instead of panicking.
1251    ///
1252    /// # Errors
1253    ///
1254    /// [`FemError::InvalidInput`] if `node_idx` is out of bounds.
1255    /// [`FemError::ConflictingPrescribedDisplacement`] if any DOF already
1256    /// has a conflicting prescribed value.
1257    pub fn try_fix_node(&mut self, node_idx: usize) -> Result<(), FemError> {
1258        if node_idx >= self.nodes.len() {
1259            return Err(FemError::InvalidInput(format!(
1260                "Invalid node index: {} (max: {})",
1261                node_idx,
1262                self.nodes.len().saturating_sub(1)
1263            )));
1264        }
1265        self.try_fix_dof(node_idx, 0, 0.0)?;
1266        self.try_fix_dof(node_idx, 1, 0.0)?;
1267        self.try_fix_dof(node_idx, 2, 0.0)?;
1268        Ok(())
1269    }
1270
1271    /// Typed counterpart of [`Self::try_fix_dof`]: constrain `(node_idx, dof)`
1272    /// to `value`.
1273    ///
1274    /// ```text
1275    /// model.try_fix(0, Dof::Uy, 0.0)?;   // == model.try_fix_dof(0, 1, 0.0)?
1276    /// ```
1277    ///
1278    /// `dof` is always a **global** DOF; there is no local DOF variant. This
1279    /// delegates to [`Self::try_fix_dof`] and therefore shares the same
1280    /// boundary-condition storage, validation and static-condensation path.
1281    ///
1282    /// # Errors
1283    ///
1284    /// [`FemError::InvalidInput`] for an out-of-bounds node index or a
1285    /// non-finite prescribed value.
1286    /// [`FemError::ConflictingPrescribedDisplacement`] if the DOF already
1287    /// has a conflicting prescribed value.
1288    pub fn try_fix(&mut self, node_idx: usize, dof: Dof, value: f64) -> Result<(), FemError> {
1289        self.try_fix_dof(node_idx, dof.index(), value)
1290    }
1291
1292    /// Typed counterpart of [`Self::try_override_dof`]: override (upsert) the
1293    /// prescribed displacement for `(node_idx, dof)` to `value`.
1294    ///
1295    /// Unlike [`Self::try_fix`], this silently replaces any existing
1296    /// constraint on the same DOF instead of returning
1297    /// [`FemError::ConflictingPrescribedDisplacement`].
1298    pub fn try_override(&mut self, node_idx: usize, dof: Dof, value: f64) -> Result<(), FemError> {
1299        self.try_override_dof(node_idx, dof.index(), value)
1300    }
1301
1302    /// Constrain all three DOFs of a node to the given prescribed values.
1303    ///
1304    /// Use this for a prescribed displacement/rotation (e.g. a support
1305    /// settlement such as `try_fix_node_with_values(0, 0.0, -0.01, 0.0)`); a
1306    /// fully fixed node is `try_fix_node_with_values(i, 0.0, 0.0, 0.0)`, which
1307    /// is what [`Self::try_fix_node`] does.
1308    ///
1309    /// This is a convenience wrapper: it delegates to [`Self::try_override_dof`]
1310    /// for `ux`, `uy` and `rz`, so it uses the same boundary-condition storage
1311    /// and the same static-condensation path. It does not add a second BC
1312    /// representation and does not change reaction recovery.  Any existing
1313    /// constraint on the same DOF is **replaced**.
1314    ///
1315    /// # Override vs conflict semantics
1316    ///
1317    /// Unlike [`Self::try_fix_node`], which delegates to [`Self::try_fix_dof`]
1318    /// and returns [`FemError::ConflictingPrescribedDisplacement`] when a DOF
1319    /// already has a different prescribed value, this method **silently
1320    /// replaces** the existing constraint.  This is intentional: the typical
1321    /// use case is applying a support settlement after an initial full fix
1322    /// (`try_fix_node(i)` → `try_fix_node_with_values(i, 0.0, -0.01, 0.0)`),
1323    /// where the override is the desired behaviour.
1324    ///
1325    /// # Errors
1326    ///
1327    /// [`FemError::InvalidInput`] for an out-of-bounds node index or any
1328    /// non-finite prescribed value. All inputs are validated **before** any
1329    /// boundary condition is recorded, so a rejected call leaves the model
1330    /// unchanged (no partially fixed node).
1331    pub fn try_fix_node_with_values(
1332        &mut self,
1333        node_idx: usize,
1334        ux: f64,
1335        uy: f64,
1336        rz: f64,
1337    ) -> Result<(), FemError> {
1338        if node_idx >= self.nodes.len() {
1339            return Err(FemError::InvalidInput(format!(
1340                "Invalid node index: {} (max: {})",
1341                node_idx,
1342                self.nodes.len().saturating_sub(1)
1343            )));
1344        }
1345        for (dof, value) in [(Dof::Ux, ux), (Dof::Uy, uy), (Dof::Rz, rz)] {
1346            if !value.is_finite() {
1347                return Err(FemError::InvalidInput(format!(
1348                    "Prescribed value for {} must be finite, got {}",
1349                    dof.name(),
1350                    value
1351                )));
1352            }
1353        }
1354        self.try_override_dof(node_idx, Dof::Ux.index(), ux)?;
1355        self.try_override_dof(node_idx, Dof::Uy.index(), uy)?;
1356        self.try_override_dof(node_idx, Dof::Rz.index(), rz)?;
1357        Ok(())
1358    }
1359
1360    /// Add a distributed load on an element (in LOCAL coordinates)
1361    /// element_idx is the index in the elements Vec (0, 1, 2, ...)
1362    pub fn add_distributed_load(
1363        &mut self,
1364        element_idx: usize,
1365        qx: f64,
1366        qy: f64,
1367    ) -> Result<(), FemError> {
1368        if element_idx >= self.elements.len() {
1369            return Err(FemError::InvalidInput(format!(
1370                "Invalid element index: {} (max: {})",
1371                element_idx,
1372                self.elements.len().saturating_sub(1)
1373            )));
1374        }
1375        if !qx.is_finite() || !qy.is_finite() {
1376            return Err(FemError::InvalidInput(format!(
1377                "Distributed load must be finite, got qx = {}, qy = {}",
1378                qx, qy
1379            )));
1380        }
1381        self.distributed_loads
1382            .push(DistributedLoad::new(element_idx, qx, qy));
1383        Ok(())
1384    }
1385
1386    /// Add a point load on an element (in LOCAL coordinates)
1387    /// element_idx is the index in the elements Vec (0, 1, 2, ...)
1388    /// position is measured from node_i (0.0) to node_j (1.0)
1389    pub fn add_point_load(
1390        &mut self,
1391        element_idx: usize,
1392        position: f64,
1393        fx: f64,
1394        fy: f64,
1395        mz: f64,
1396    ) -> Result<(), FemError> {
1397        if element_idx >= self.elements.len() {
1398            return Err(FemError::InvalidInput(format!(
1399                "Invalid element index: {} (max: {})",
1400                element_idx,
1401                self.elements.len().saturating_sub(1)
1402            )));
1403        }
1404        if !(0.0..=1.0).contains(&position) {
1405            return Err(FemError::InvalidInput(format!(
1406                "Point load position must be in [0, 1], got {}",
1407                position
1408            )));
1409        }
1410        if !fx.is_finite() || !fy.is_finite() || !mz.is_finite() {
1411            return Err(FemError::InvalidInput(format!(
1412                "Point load must be finite, got fx = {}, fy = {}, mz = {}",
1413                fx, fy, mz
1414            )));
1415        }
1416        self.point_loads
1417            .push(PointLoad::new(element_idx, position, fx, fy, mz));
1418        Ok(())
1419    }
1420
1421    /// Add a point force only (transverse or axial) on an element.
1422    ///
1423    /// Components are **LOCAL** to the element (local x from `node_i` to
1424    /// `node_j`, local y transverse, positive up). Use
1425    /// [`BeamElement::to_local_force`] to convert global input data. `position`
1426    /// must be in `[0, 1]`.
1427    ///
1428    /// # Errors
1429    ///
1430    /// [`FemError::InvalidInput`] for an out-of-bounds element, a `position`
1431    /// outside `[0, 1]`, or a non-finite component.
1432    pub fn add_point_force(
1433        &mut self,
1434        element_idx: usize,
1435        position: f64,
1436        fx: f64,
1437        fy: f64,
1438    ) -> Result<(), FemError> {
1439        self.add_point_load(element_idx, position, fx, fy, 0.0)
1440    }
1441
1442    /// Add a point moment only on an element.
1443    ///
1444    /// `mz` is **LOCAL** to the element (`mz > 0` counter-clockwise) and
1445    /// `position` must be in `[0, 1]`. This is an element load, distinct from
1446    /// [`Self::add_applied_moment`], which is a nodal (global) moment that is
1447    /// never part of an element's equivalent load vector.
1448    ///
1449    /// # Errors
1450    ///
1451    /// [`FemError::InvalidInput`] for an out-of-bounds element, a `position`
1452    /// outside `[0, 1]`, or a non-finite value.
1453    pub fn add_point_moment(
1454        &mut self,
1455        element_idx: usize,
1456        position: f64,
1457        mz: f64,
1458    ) -> Result<(), FemError> {
1459        self.add_point_load(element_idx, position, 0.0, 0.0, mz)
1460    }
1461
1462    /// Add an applied moment at a node (in GLOBAL coordinates).
1463    ///
1464    /// This is a nodal external load applied to the global `theta` DOF
1465    /// (`value > 0` counter-clockwise). It is **not** an element load: it never
1466    /// enters an element's equivalent nodal-load vector, so element end forces
1467    /// are unaffected by it except through the displacement field.
1468    ///
1469    /// # Errors
1470    ///
1471    /// [`FemError::InvalidInput`] for an out-of-bounds node index or a
1472    /// non-finite value.
1473    pub fn add_applied_moment(&mut self, node_idx: usize, value: f64) -> Result<(), FemError> {
1474        if node_idx >= self.nodes.len() {
1475            return Err(FemError::InvalidInput(format!(
1476                "Invalid node index: {} (max: {})",
1477                node_idx,
1478                self.nodes.len().saturating_sub(1)
1479            )));
1480        }
1481        if !value.is_finite() {
1482            return Err(FemError::InvalidInput(format!(
1483                "Applied moment must be finite, got {}",
1484                value
1485            )));
1486        }
1487        self.applied_moments
1488            .push(AppliedMoment::new(node_idx, value));
1489        Ok(())
1490    }
1491
1492    /// Get total number of DOFs
1493    pub fn n_dof(&self) -> usize {
1494        self.nodes.len() * 3
1495    }
1496
1497    /// Map (node_idx, dof) to global DOF index.
1498    ///
1499    /// Note: node_idx must be the index in the nodes Vec (0, 1, 2, ...).
1500    /// This is NOT an arbitrary user-defined ID. Node IDs are implicitly their
1501    /// position in the nodes vector.
1502    pub(crate) fn dof_index(&self, node_idx: usize, dof: usize) -> usize {
1503        node_idx * 3 + dof
1504    }
1505}
1506
1507/// The condensed (boundary-conditioned) free-free stiffness system of a
1508/// [`BeamSolver`]: `K_ff` plus the reduced-index -> global-DOF map.
1509///
1510/// This is the **single** representation of the system that static
1511/// condensation produces and that the linear solver factorises. It is retained
1512/// so that structural diagnostics read the exact same matrix the solve path
1513/// built, rather than reassembling an identical-looking second copy: two
1514/// independent assemblies are mathematically equal but not necessarily
1515/// bit-identical, and a rank probe sitting at a relative tolerance floor is
1516/// exactly the kind of consumer that a ULP difference can flip.
1517///
1518/// Crate-internal on purpose - this is not part of the public surface. Its
1519/// fields are private: consumers read `K_ff` and the DOF map through the
1520/// read-only accessors so the retained system cannot be mutated from outside.
1521#[derive(Debug, Clone)]
1522pub(crate) struct ReducedSystem {
1523    /// The free-free stiffness block `K_ff` (already compressed).
1524    k_ff: SparseMatrix,
1525    /// Reduced DOF index -> global DOF index (`3 * node + dof`).
1526    free_to_global: Vec<usize>,
1527}
1528
1529impl ReducedSystem {
1530    /// Retain a condensed system from an already-built `K_ff` and DOF map.
1531    pub(crate) fn new(k_ff: SparseMatrix, free_to_global: Vec<usize>) -> Self {
1532        Self {
1533            k_ff,
1534            free_to_global,
1535        }
1536    }
1537
1538    /// The retained free-free stiffness block `K_ff`.
1539    pub(crate) fn k_ff(&self) -> &SparseMatrix {
1540        &self.k_ff
1541    }
1542
1543    /// The retained reduced-index -> global-DOF map (`3 * node + dof`).
1544    pub(crate) fn free_to_global(&self) -> &[usize] {
1545        &self.free_to_global
1546    }
1547}
1548
1549/// Beam FEM solver using the unified LinearSolver abstraction.
1550///
1551/// # Complete workflow
1552///
1553/// ```rust
1554/// use section_properties::beam_fem::{BeamElement, BeamModel, BeamNode, BeamSection, BeamSolver, Dof};
1555/// use section_properties::material::Material;
1556///
1557/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1558/// // 1. model: unit cantilever (E = A = I = 1, L = 1)
1559/// let mut model = BeamModel::new();
1560/// model.add_node(BeamNode::new(0, 0.0, 0.0));
1561/// model.add_node(BeamNode::new(1, 1.0, 0.0));
1562/// model.add_element(BeamElement::new(
1563///     0,
1564///     1,
1565///     Material::new(1.0, 0.3, 1.0, "unit"),
1566///     BeamSection::new(1.0, 1.0),
1567/// )?);
1568///
1569/// // 2. boundary condition: clamp node 0 (typed DOF API)
1570/// model.try_fix_node_with_values(0, 0.0, 0.0, 0.0)?;
1571///
1572/// // 3. load: global transverse force at the tip
1573/// model.add_nodal_force(1, 1, -100.0);
1574///
1575/// // 4. solve
1576/// let mut solver = BeamSolver::from_model(&model)?;
1577/// solver.solve_configured()?;
1578///
1579/// // 5. post-process: typed displacement and reaction access
1580/// let uy = solver.displacement_dof(1, Dof::Uy)?; // -P L^3 / 3EI
1581/// let rz = solver.displacement_dof(1, Dof::Rz)?; // -P L^2 / 2EI
1582/// let ry = solver.reaction_dof(0, Dof::Uy)?; // +P
1583///
1584/// assert!((uy + 100.0 / 3.0).abs() < 1e-9);
1585/// assert!((rz + 50.0).abs() < 1e-9);
1586/// assert!((ry - 100.0).abs() < 1e-9);
1587/// # Ok(())
1588/// # }
1589/// ```
1590pub struct BeamSolver {
1591    /// Global stiffness matrix
1592    k_global: SparseMatrix,
1593    /// Global force vector
1594    f_global: Vec<f64>,
1595    /// Displacement solution
1596    u_global: Vec<f64>,
1597    /// Fixed DOFs (true if constrained)
1598    fixed_dofs: Vec<bool>,
1599    /// Prescribed values for constrained DOFs (None = 0.0, Some(value) = prescribed)
1600    prescribed_values: Vec<Option<f64>>,
1601    /// Original stiffness matrix (for reaction computation)
1602    k_original: SparseMatrix,
1603    /// Number of DOFs
1604    n_dof: usize,
1605    /// Model reference
1606    model: BeamModel,
1607    /// Configured solver selection (defaults to [`SolverSelection::Auto`]).
1608    solver_selection: SolverSelection,
1609    /// Name of the backend used by the most recent successful solve, if any.
1610    solver_name: Option<String>,
1611    /// The condensed free-free system retained by
1612    /// [`Self::apply_boundary_conditions`], if it has run. Populated before any
1613    /// backend is created or factorisation attempted, so it is available even
1614    /// after a failed solve.
1615    reduced: Option<ReducedSystem>,
1616}
1617
1618impl BeamSolver {
1619    /// Create a new BeamSolver from a BeamModel
1620    pub fn from_model(model: &BeamModel) -> Result<Self, FemError> {
1621        let n_dof = model.n_dof();
1622        if n_dof == 0 {
1623            return Err(FemError::InvalidModel("Model has no nodes".to_string()));
1624        }
1625
1626        // Validate element node indices
1627        for (elem_idx, element) in model.elements.iter().enumerate() {
1628            if element.node_i >= model.nodes.len() {
1629                return Err(FemError::InvalidModel(format!(
1630                    "Element {}: node_i index {} out of bounds (max: {})",
1631                    elem_idx,
1632                    element.node_i,
1633                    model.nodes.len().saturating_sub(1)
1634                )));
1635            }
1636            if element.node_j >= model.nodes.len() {
1637                return Err(FemError::InvalidModel(format!(
1638                    "Element {}: node_j index {} out of bounds (max: {})",
1639                    elem_idx,
1640                    element.node_j,
1641                    model.nodes.len().saturating_sub(1)
1642                )));
1643            }
1644            if element.node_i == element.node_j {
1645                return Err(FemError::InvalidModel(format!(
1646                    "Element {}: node_i and node_j cannot be the same",
1647                    elem_idx
1648                )));
1649            }
1650        }
1651
1652        // Validate node coordinates are finite.
1653        for (idx, node) in model.nodes.iter().enumerate() {
1654            if !node.x.is_finite() || !node.y.is_finite() {
1655                return Err(FemError::InvalidModel(format!(
1656                    "Node {} has non-finite coordinates: ({}, {})",
1657                    idx, node.x, node.y
1658                )));
1659            }
1660        }
1661
1662        // Validate material and section parameters (finite and positive). These
1663        // have no fallible constructor, so this is the authoritative boundary;
1664        // it also covers elements built via struct literal.
1665        for (elem_idx, element) in model.elements.iter().enumerate() {
1666            let e = element.material.youngs_modulus;
1667            let a = element.section.area;
1668            let i = element.section.second_moment;
1669            if !e.is_finite() || e <= 0.0 {
1670                return Err(FemError::InvalidModel(format!(
1671                    "Element {}: Young's modulus must be finite and positive, got {}",
1672                    elem_idx, e
1673                )));
1674            }
1675            if !a.is_finite() || a <= 0.0 {
1676                return Err(FemError::InvalidModel(format!(
1677                    "Element {}: cross-section area must be finite and positive, got {}",
1678                    elem_idx, a
1679                )));
1680            }
1681            if !i.is_finite() || i <= 0.0 {
1682                return Err(FemError::InvalidModel(format!(
1683                    "Element {}: second moment of area must be finite and positive, got {}",
1684                    elem_idx, i
1685                )));
1686            }
1687        }
1688
1689        // Validate that every load and prescribed value is finite. Model fields
1690        // are public, so this cannot be delegated solely to the add_* helpers.
1691        for (node_id, dof, value) in &model.nodal_forces {
1692            if !value.is_finite() {
1693                return Err(FemError::InvalidModel(format!(
1694                    "Nodal force at node {} DOF {} is non-finite: {}",
1695                    node_id, dof, value
1696                )));
1697            }
1698        }
1699        for dl in &model.distributed_loads {
1700            if !dl.qx.is_finite() || !dl.qy.is_finite() {
1701                return Err(FemError::InvalidModel(format!(
1702                    "Distributed load on element {} is non-finite: qx = {}, qy = {}",
1703                    dl.element_idx, dl.qx, dl.qy
1704                )));
1705            }
1706        }
1707        for pl in &model.point_loads {
1708            if !pl.fx.is_finite() || !pl.fy.is_finite() || !pl.mz.is_finite() {
1709                return Err(FemError::InvalidModel(format!(
1710                    "Point load on element {} is non-finite: fx = {}, fy = {}, mz = {}",
1711                    pl.element_idx, pl.fx, pl.fy, pl.mz
1712                )));
1713            }
1714        }
1715        for am in &model.applied_moments {
1716            if !am.value.is_finite() {
1717                return Err(FemError::InvalidModel(format!(
1718                    "Applied moment at node {} is non-finite: {}",
1719                    am.node_idx, am.value
1720                )));
1721            }
1722        }
1723        for (node_id, dof, value) in &model.fixed_dofs {
1724            if !value.is_finite() {
1725                return Err(FemError::InvalidModel(format!(
1726                    "Prescribed value at node {} DOF {} is non-finite: {}",
1727                    node_id, dof, value
1728                )));
1729            }
1730        }
1731
1732        // Build global stiffness matrix
1733        let mut k_global = SparseMatrix::new(n_dof);
1734
1735        // Assemble element stiffness matrices
1736        for element in &model.elements {
1737            let node_i = model.nodes[element.node_i].point();
1738            let node_j = model.nodes[element.node_j].point();
1739
1740            // Check for zero-length beam
1741            let dx = node_j.x - node_i.x;
1742            let dy = node_j.y - node_i.y;
1743            let L = (dx * dx + dy * dy).sqrt();
1744            if L <= 0.0 {
1745                return Err(FemError::InvalidModel(format!(
1746                    "Beam element has zero or negative length (nodes {} and {} at same position)",
1747                    element.node_i, element.node_j
1748                )));
1749            }
1750
1751            let k_global_elem = element.global_stiffness(node_i, node_j);
1752
1753            // Map element DOFs to global DOFs
1754            let dof_map = [
1755                model.dof_index(element.node_i, 0), // u_i
1756                model.dof_index(element.node_i, 1), // v_i
1757                model.dof_index(element.node_i, 2), // θ_i
1758                model.dof_index(element.node_j, 0), // u_j
1759                model.dof_index(element.node_j, 1), // v_j
1760                model.dof_index(element.node_j, 2), // θ_j
1761            ];
1762
1763            // Assemble into global matrix
1764            for a in 0..6 {
1765                for b in 0..6 {
1766                    let val = k_global_elem[a][b];
1767                    k_global.add(dof_map[a], dof_map[b], val);
1768                }
1769            }
1770        }
1771
1772        // Build force vector
1773        let mut f_global = vec![0.0; n_dof];
1774        for (node_id, dof, value) in &model.nodal_forces {
1775            if *node_id >= model.nodes.len() {
1776                return Err(FemError::InvalidModel(format!(
1777                    "Nodal force: node index {} out of bounds (max: {})",
1778                    node_id,
1779                    model.nodes.len().saturating_sub(1)
1780                )));
1781            }
1782            if *dof >= 3 {
1783                return Err(FemError::InvalidModel(format!(
1784                    "Nodal force: DOF {} invalid (must be 0, 1, or 2)",
1785                    dof
1786                )));
1787            }
1788            let idx = model.dof_index(*node_id, *dof);
1789            f_global[idx] += value;
1790        }
1791
1792        // Assemble distributed loads
1793        for dl in &model.distributed_loads {
1794            if dl.element_idx >= model.elements.len() {
1795                return Err(FemError::InvalidModel(format!(
1796                    "Distributed load: element index {} out of bounds (max: {})",
1797                    dl.element_idx,
1798                    model.elements.len().saturating_sub(1)
1799                )));
1800            }
1801            let element = &model.elements[dl.element_idx];
1802            let node_i = model.nodes[element.node_i].point();
1803            let node_j = model.nodes[element.node_j].point();
1804
1805            // Check for zero-length beam
1806            let dx = node_j.x - node_i.x;
1807            let dy = node_j.y - node_i.y;
1808            let L = (dx * dx + dy * dy).sqrt();
1809            if L <= 0.0 {
1810                return Err(FemError::InvalidModel(format!(
1811                    "Distributed load: beam element has zero or negative length (nodes {} and {} at same position)",
1812                    element.node_i, element.node_j
1813                )));
1814            }
1815
1816            // Compute consistent nodal load in local coordinates
1817            let f_local = element.consistent_nodal_load(node_i, node_j, dl.qx, dl.qy)?;
1818
1819            // Get transformation matrix
1820            let T = element.transformation_matrix(node_i, node_j);
1821
1822            // Transform to global coordinates: f_global_elem = T^T * f_local
1823            let mut f_global_elem = [0.0; 6];
1824            for i in 0..6 {
1825                for j in 0..6 {
1826                    f_global_elem[i] += T[j][i] * f_local[j];
1827                }
1828            }
1829
1830            // Map element DOFs to global DOFs
1831            let dof_map = [
1832                model.dof_index(element.node_i, 0), // u_i
1833                model.dof_index(element.node_i, 1), // v_i
1834                model.dof_index(element.node_i, 2), // θ_i
1835                model.dof_index(element.node_j, 0), // u_j
1836                model.dof_index(element.node_j, 1), // v_j
1837                model.dof_index(element.node_j, 2), // θ_j
1838            ];
1839
1840            // Assemble into global force vector
1841            for a in 0..6 {
1842                f_global[dof_map[a]] += f_global_elem[a];
1843            }
1844        }
1845
1846        // Assemble point loads
1847        for pl in &model.point_loads {
1848            if pl.element_idx >= model.elements.len() {
1849                return Err(FemError::InvalidModel(format!(
1850                    "Point load: element index {} out of bounds (max: {})",
1851                    pl.element_idx,
1852                    model.elements.len().saturating_sub(1)
1853                )));
1854            }
1855            let element = &model.elements[pl.element_idx];
1856            let node_i = model.nodes[element.node_i].point();
1857            let node_j = model.nodes[element.node_j].point();
1858
1859            // Check for zero-length beam
1860            let dx = node_j.x - node_i.x;
1861            let dy = node_j.y - node_i.y;
1862            let L = (dx * dx + dy * dy).sqrt();
1863            if L <= 0.0 {
1864                return Err(FemError::InvalidModel(format!(
1865                    "Point load: beam element has zero or negative length (nodes {} and {} at same position)",
1866                    element.node_i, element.node_j
1867                )));
1868            }
1869
1870            // Compute consistent nodal load in local coordinates
1871            let f_local = element.consistent_nodal_load_point(
1872                node_i,
1873                node_j,
1874                pl.position,
1875                pl.fx,
1876                pl.fy,
1877                pl.mz,
1878            )?;
1879
1880            // Get transformation matrix
1881            let T = element.transformation_matrix(node_i, node_j);
1882
1883            // Transform to global coordinates: f_global_elem = T^T * f_local
1884            let mut f_global_elem = [0.0; 6];
1885            for i in 0..6 {
1886                for j in 0..6 {
1887                    f_global_elem[i] += T[j][i] * f_local[j];
1888                }
1889            }
1890
1891            // Map element DOFs to global DOFs
1892            let dof_map = [
1893                model.dof_index(element.node_i, 0), // u_i
1894                model.dof_index(element.node_i, 1), // v_i
1895                model.dof_index(element.node_i, 2), // θ_i
1896                model.dof_index(element.node_j, 0), // u_j
1897                model.dof_index(element.node_j, 1), // v_j
1898                model.dof_index(element.node_j, 2), // θ_j
1899            ];
1900
1901            // Assemble into global force vector
1902            for a in 0..6 {
1903                f_global[dof_map[a]] += f_global_elem[a];
1904            }
1905        }
1906
1907        // Assemble applied moments (already in global coordinates)
1908        for am in &model.applied_moments {
1909            if am.node_idx >= model.nodes.len() {
1910                return Err(FemError::InvalidModel(format!(
1911                    "Applied moment: node index {} out of bounds (max: {})",
1912                    am.node_idx,
1913                    model.nodes.len().saturating_sub(1)
1914                )));
1915            }
1916            // Applied moment is in global coordinates, DOF 2 = θ
1917            let idx = model.dof_index(am.node_idx, 2);
1918            f_global[idx] += am.value;
1919        }
1920
1921        // Fixed DOFs and prescribed values
1922        let mut fixed_dofs = vec![false; n_dof];
1923        let mut prescribed_values = vec![None; n_dof];
1924        for (node_id, dof, value) in &model.fixed_dofs {
1925            if *node_id >= model.nodes.len() {
1926                return Err(FemError::InvalidModel(format!(
1927                    "Fixed DOF: node index {} out of bounds (max: {})",
1928                    node_id,
1929                    model.nodes.len().saturating_sub(1)
1930                )));
1931            }
1932            if *dof >= 3 {
1933                return Err(FemError::InvalidModel(format!(
1934                    "Fixed DOF: DOF {} invalid (must be 0, 1, or 2)",
1935                    dof
1936                )));
1937            }
1938            let idx = model.dof_index(*node_id, *dof);
1939            fixed_dofs[idx] = true;
1940            prescribed_values[idx] = Some(*value);
1941        }
1942
1943        // Store original matrix for reaction computation
1944        let k_original = k_global.clone();
1945
1946        Ok(Self {
1947            k_global,
1948            f_global,
1949            u_global: vec![0.0; n_dof],
1950            fixed_dofs,
1951            prescribed_values,
1952            k_original,
1953            n_dof,
1954            model: model.clone(),
1955            solver_selection: SolverSelection::Auto,
1956            solver_name: None,
1957            reduced: None,
1958        })
1959    }
1960
1961    /// Apply boundary conditions using static condensation (exact enforcement)
1962    /// and retain the condensed system in `self.reduced`.
1963    ///
1964    /// Returns `(f_reduced, constrained_indices, constrained_values)`. The
1965    /// condensed stiffness `K_ff` and the free-DOF map are **moved** into
1966    /// `self.reduced` (no clone): diagnostics read that retained system, and
1967    /// the solve path factorises a bit-identical copy of it (the single deep
1968    /// copy on the solve path) rather than a second, independently assembled
1969    /// matrix.
1970    fn apply_boundary_conditions(&mut self) -> (Vec<f64>, Vec<usize>, Vec<f64>) {
1971        let n = self.n_dof;
1972        let fixed = &self.fixed_dofs;
1973        let prescribed = &self.prescribed_values;
1974
1975        // Identify free and constrained DOFs
1976        let mut free_dofs = Vec::new();
1977        let mut constrained_dofs = Vec::new();
1978        let mut constrained_values = Vec::new();
1979        let mut free_to_global = Vec::new();
1980        let mut global_to_free = vec![None; n];
1981
1982        for i in 0..n {
1983            if !fixed[i] {
1984                global_to_free[i] = Some(free_dofs.len());
1985                free_dofs.push(i);
1986                free_to_global.push(i);
1987            } else {
1988                let _constrained_idx = constrained_dofs.len();
1989                constrained_dofs.push(i);
1990                constrained_values.push(prescribed[i].unwrap_or(0.0));
1991            }
1992        }
1993
1994        let n_free = free_dofs.len();
1995        if n_free == 0 {
1996            // All DOFs fixed - retain and return an empty system.
1997            self.reduced = Some(ReducedSystem::new(SparseMatrix::new(0), Vec::new()));
1998            return (Vec::new(), constrained_dofs, constrained_values);
1999        }
2000
2001        // Extract free-free submatrix K_ff and force vector f_f
2002        let mut k_ff = SparseMatrix::new(n_free);
2003        let mut f_f = vec![0.0; n_free];
2004
2005        // Compress original matrix to access CSR data
2006        let mut k_orig = self.k_global.clone();
2007        k_orig.compress();
2008
2009        // Extract K_ff and compute K_fc * U_c directly
2010        let mut kfc_uc = vec![0.0; n_free];
2011
2012        for (free_idx, &global_i) in free_dofs.iter().enumerate() {
2013            // Force vector
2014            f_f[free_idx] = self.f_global[global_i];
2015
2016            // Stiffness matrix row
2017            let row_ptr = k_orig.row_ptr();
2018            let csr_cols = k_orig.csr_cols();
2019            let csr_vals = k_orig.csr_vals();
2020
2021            for idx in row_ptr[global_i]..row_ptr[global_i + 1] {
2022                let global_j = csr_cols[idx];
2023                let val = csr_vals[idx];
2024
2025                if let Some(free_j) = global_to_free[global_j] {
2026                    // free-free
2027                    k_ff.add(free_idx, free_j, val);
2028                } else if fixed[global_j] {
2029                    // free-constrained: accumulate K_fc * U_c directly
2030                    let constr_idx = constrained_dofs
2031                        .iter()
2032                        .position(|&x| x == global_j)
2033                        .unwrap();
2034                    kfc_uc[free_idx] += val * constrained_values[constr_idx];
2035                }
2036            }
2037        }
2038
2039        k_ff.compress();
2040
2041        // Compute reduced RHS: F_reduced = F_f - K_fc * U_c
2042        let mut f_reduced = f_f;
2043        for free_idx in 0..n_free {
2044            f_reduced[free_idx] -= kfc_uc[free_idx];
2045        }
2046
2047        // Retain the condensed system for the solve path and read-only
2048        // diagnostics by *moving* the freshly built matrix and map (no clone).
2049        self.reduced = Some(ReducedSystem::new(k_ff, free_to_global));
2050
2051        (f_reduced, constrained_dofs, constrained_values)
2052    }
2053
2054    /// The condensed free-free system most recently built by
2055    /// [`Self::apply_boundary_conditions`]/[`Self::condense`], if it has run.
2056    ///
2057    /// The matrix is the exact one the solve path assembled and factorised -
2058    /// diagnostics must read this, never reassemble their own copy. `None` only
2059    /// before any condensation has happened on this solver.
2060    pub(crate) fn reduced_system(&self) -> Option<&ReducedSystem> {
2061        self.reduced.as_ref()
2062    }
2063
2064    /// Copy the retained reduced system out for its one consuming use (the
2065    /// factorisation). This is the only deep copy of `K_ff` on the solve path;
2066    /// the retained original stays in `self.reduced` for diagnostics.
2067    ///
2068    /// Panics only if called before the system has been condensed, which the
2069    /// solve paths never do (`apply_boundary_conditions` runs first).
2070    fn retained_system_copy(&self) -> (SparseMatrix, Vec<usize>) {
2071        let retained = self
2072            .reduced
2073            .as_ref()
2074            .expect("apply_boundary_conditions retains the condensed system");
2075        (retained.k_ff().clone(), retained.free_to_global().to_vec())
2076    }
2077
2078    /// Condense the boundary conditions and return the retained reduced system
2079    /// for read-only inspection.
2080    ///
2081    /// Semantics: the returned system is condensed from the solver's current
2082    /// model state. The **first** call runs the identical static-condensation
2083    /// code the solve path runs, so the returned matrix is bit-identical to the
2084    /// one a solve would factorise. A `BeamSolver` exposes no mutator that can
2085    /// change the assembled system (loads, supports and geometry are fixed in
2086    /// the `BeamModel` at construction; only the backend selection is settable,
2087    /// which does not affect `K_ff`), so repeated calls are **idempotent**:
2088    /// they return the already-retained system without re-condensing. It never
2089    /// panics.
2090    pub(crate) fn condense(&mut self) -> &ReducedSystem {
2091        if self.reduced.is_none() {
2092            self.apply_boundary_conditions();
2093        }
2094        self.reduced
2095            .as_ref()
2096            .expect("apply_boundary_conditions always retains the condensed system")
2097    }
2098
2099    #[allow(dead_code)]
2100    fn find_diagonal_index(&self, matrix: &SparseMatrix, row: usize) -> Option<usize> {
2101        let row_ptr = matrix.row_ptr();
2102        let csr_cols = matrix.csr_cols();
2103        for idx in row_ptr[row]..row_ptr[row + 1] {
2104            if csr_cols[idx] == row {
2105                return Some(idx);
2106            }
2107        }
2108        None
2109    }
2110
2111    /// Configure the solver selection used by [`Self::solve_configured`].
2112    ///
2113    /// Defaults to [`SolverSelection::Auto`]. Explicit selections are
2114    /// authoritative: if the requested backend cannot handle the condensed
2115    /// stiffness matrix, [`Self::solve_configured`] returns an error and does
2116    /// **not** substitute another backend.
2117    pub fn set_solver(&mut self, selection: SolverSelection) {
2118        self.solver_selection = selection;
2119    }
2120
2121    /// The configured solver selection.
2122    pub fn solver_selection(&self) -> &SolverSelection {
2123        &self.solver_selection
2124    }
2125
2126    /// Name of the backend used by the most recent **successful** solve.
2127    ///
2128    /// Semantics: the value describes the solution currently held by this
2129    /// solver. It is cleared before each solve attempt and set only when the
2130    /// solve completes successfully, so it is `None`:
2131    ///
2132    /// * before any solve;
2133    /// * after a failed solve attempt (no stale claim from an earlier run);
2134    /// * when the model was fully constrained and no linear system was solved.
2135    pub fn solver_name(&self) -> Option<&str> {
2136        self.solver_name.as_deref()
2137    }
2138
2139    /// Factorize and expand a condensed system into the global solution.
2140    ///
2141    /// `k_ff`/`free_to_global` are the solver's retained system copied out for
2142    /// this one use - the only deep copy of `K_ff` on the solve path (the
2143    /// retained copy lives in `self.reduced` for diagnostics and is never
2144    /// duplicated again).
2145    fn factor_and_expand(
2146        &mut self,
2147        solver: &mut dyn LinearSolver,
2148        mut k_ff: SparseMatrix,
2149        f_reduced: Vec<f64>,
2150        free_to_global: Vec<usize>,
2151        constrained_dofs: Vec<usize>,
2152        constrained_values: Vec<f64>,
2153    ) -> Result<(), FemError> {
2154        if k_ff.n == 0 {
2155            // All DOFs fixed - just set prescribed values
2156            self.u_global = vec![0.0; self.n_dof];
2157            for (i, &global_idx) in constrained_dofs.iter().enumerate() {
2158                self.u_global[global_idx] = constrained_values[i];
2159            }
2160            return Ok(());
2161        }
2162
2163        k_ff.compress();
2164        solver.factor(&k_ff).map_err(FemError::from)?;
2165
2166        let u_free = solver.solve(&f_reduced).map_err(FemError::from)?;
2167
2168        // Expand solution back to full DOF space
2169        self.u_global = vec![0.0; self.n_dof];
2170        for (free_idx, &global_idx) in free_to_global.iter().enumerate() {
2171            self.u_global[global_idx] = u_free[free_idx];
2172        }
2173        for (i, &global_idx) in constrained_dofs.iter().enumerate() {
2174            self.u_global[global_idx] = constrained_values[i];
2175        }
2176        Ok(())
2177    }
2178
2179    /// Solve the system using the provided LinearSolver.
2180    ///
2181    /// The caller owns solver construction; [`Self::solve_configured`] instead
2182    /// uses the configured [`SolverSelection`].
2183    ///
2184    /// [`Self::solver_name`] is cleared at the start of this call and set only
2185    /// after the solve succeeds, so a failed solve never leaves stale
2186    /// observability implying a backend produced the current solution.
2187    pub fn solve(&mut self, solver: &mut dyn LinearSolver) -> Result<(), FemError> {
2188        self.solver_name = None;
2189        let (f_reduced, constrained_dofs, constrained_values) = self.apply_boundary_conditions();
2190        let (k_ff, free_to_global) = self.retained_system_copy();
2191        self.factor_and_expand(
2192            solver,
2193            k_ff,
2194            f_reduced,
2195            free_to_global,
2196            constrained_dofs,
2197            constrained_values,
2198        )?;
2199        self.solver_name = Some(solver.name().to_string());
2200        Ok(())
2201    }
2202
2203    /// Solve using the configured [`SolverSelection`] (default [`Auto`]).
2204    ///
2205    /// The backend is chosen via [`SolverRegistry`] against the **condensed**
2206    /// (boundary-conditioned) stiffness matrix — the matrix that is actually
2207    /// factorized. Capability validation therefore sees the real system.
2208    ///
2209    /// # Errors
2210    ///
2211    /// All solver errors propagate as [`FemError::SolverError`]; an explicit
2212    /// invalid selection (e.g. a non-symmetric system with `skyline_ldlt`, or a
2213    /// matrix larger than the backend's `max_size`) returns an error and never
2214    /// silently switches backend.
2215    ///
2216    /// [`Self::solver_name`] is cleared before the solve is attempted and set
2217    /// only once it fully succeeds, so a failed attempt never leaves stale
2218    /// observability claiming the failed backend produced a solution.
2219    ///
2220    /// [`Auto`]: SolverSelection::Auto
2221    pub fn solve_configured(&mut self) -> Result<(), FemError> {
2222        self.solver_name = None;
2223        let (f_reduced, constrained_dofs, constrained_values) = self.apply_boundary_conditions();
2224
2225        let n_free = self.reduced.as_ref().map_or(0, |r| r.k_ff().n);
2226        if n_free == 0 {
2227            self.u_global = vec![0.0; self.n_dof];
2228            for (i, &global_idx) in constrained_dofs.iter().enumerate() {
2229                self.u_global[global_idx] = constrained_values[i];
2230            }
2231            return Ok(());
2232        }
2233
2234        // The single copy of the retained matrix: the backend is selected
2235        // against it and it is the matrix the factorisation consumes (no
2236        // separate probe copy).
2237        let (k_ff, free_to_global) = self.retained_system_copy();
2238
2239        let registry = SolverRegistry::default();
2240        let mut solver = registry
2241            .create_selected(&k_ff, &self.solver_selection)
2242            .map_err(FemError::from)?;
2243        let name = solver.name().to_string();
2244
2245        self.factor_and_expand(
2246            &mut *solver,
2247            k_ff,
2248            f_reduced,
2249            free_to_global,
2250            constrained_dofs,
2251            constrained_values,
2252        )?;
2253        self.solver_name = Some(name);
2254        Ok(())
2255    }
2256
2257    /// Displacement of a global DOF at a node (raw-index accessor).
2258    ///
2259    /// `dof` is a raw index in the **global** system: `0 = ux`, `1 = uy`,
2260    /// `2 = rz`; the assembled slot is `3*node_idx + dof`
2261    /// (`3*node_idx + dof`).
2262    ///
2263    /// # Errors
2264    ///
2265    /// [`FemError::InvalidInput`] if `dof` is not 0, 1, or 2.  Previously
2266    /// `dof >= 3` silently aliased into the following node's DOF slot; this
2267    /// is now rejected.  Prefer the typed [`Self::displacement_dof`] with
2268    /// [`Dof`] for compile-time safety.
2269    ///
2270    /// [`FemError::InvalidInput`] if `node_idx` is out of bounds.  Previously
2271    /// out-of-range node indices silently returned `Ok(0.0)`; this is now
2272    /// rejected for consistency with [`Self::displacement_dof`].
2273    ///
2274    /// Before a successful solve the whole displacement vector is zero, so
2275    /// a valid query returns `Ok(0.0)`.
2276    pub fn displacement(&self, node_idx: usize, dof: usize) -> Result<f64, FemError> {
2277        if dof >= 3 {
2278            return Err(FemError::InvalidInput(format!(
2279                "Invalid DOF index: {} (must be 0=Ux, 1=Uy, 2=Rz)",
2280                dof
2281            )));
2282        }
2283        if node_idx >= self.model.nodes.len() {
2284            return Err(FemError::InvalidInput(format!(
2285                "Invalid node index: {} (max: {})",
2286                node_idx,
2287                self.model.nodes.len().saturating_sub(1)
2288            )));
2289        }
2290        let idx = self.model.dof_index(node_idx, dof);
2291        if idx < self.u_global.len() {
2292            Ok(self.u_global[idx])
2293        } else {
2294            Ok(0.0)
2295        }
2296    }
2297
2298    /// Typed counterpart of [`Self::displacement`]: displacement of `dof` at
2299    /// `node_idx`, in the **global** system.
2300    ///
2301    /// This is a direct extraction from the global displacement vector — no
2302    /// recalculation, so the value is exactly what [`Self::displacement`]
2303    /// returns for the corresponding raw index. Reading before a successful
2304    /// solve yields `0.0` (the displacement vector is initialised to zero).
2305    ///
2306    /// # Errors
2307    ///
2308    /// [`FemError::InvalidInput`] if `node_idx` is out of bounds. (With a typed
2309    /// [`Dof`] an out-of-range DOF is impossible.)
2310    ///
2311    /// # Examples
2312    ///
2313    /// ```rust
2314    /// use section_properties::beam_fem::{BeamElement, BeamModel, BeamNode, BeamSection, BeamSolver, Dof};
2315    /// use section_properties::material::Material;
2316    ///
2317    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
2318    /// let mut model = BeamModel::new();
2319    /// model.add_node(BeamNode::new(0, 0.0, 0.0));
2320    /// model.add_node(BeamNode::new(1, 1.0, 0.0));
2321    /// model.add_element(BeamElement::new(
2322    ///     0,
2323    ///     1,
2324    ///     Material::new(1.0, 0.3, 1.0, "unit"),
2325    ///     BeamSection::new(1.0, 1.0),
2326    /// )?);
2327    /// model.fix_node(0);
2328    /// model.add_nodal_force(1, 1, -100.0);
2329    ///
2330    /// let mut solver = BeamSolver::from_model(&model)?;
2331    /// solver.solve_configured()?;
2332    ///
2333    /// // tip deflection = -P L^3 / 3EI = -33.333...
2334    /// let uy = solver.displacement_dof(1, Dof::Uy)?;
2335    /// assert!((uy + 100.0 / 3.0).abs() < 1e-9);
2336    /// // identical to the raw-index accessor
2337    /// assert_eq!(uy, solver.displacement(1, 1)?);
2338    /// assert!(matches!(solver.displacement_dof(9, Dof::Uy), Err(_)));
2339    /// # Ok(())
2340    /// # }
2341    /// ```
2342    pub fn displacement_dof(&self, node_idx: usize, dof: Dof) -> Result<f64, FemError> {
2343        if node_idx >= self.model.nodes.len() {
2344            return Err(FemError::InvalidInput(format!(
2345                "Invalid node index: {} (max: {})",
2346                node_idx,
2347                self.model.nodes.len().saturating_sub(1)
2348            )));
2349        }
2350        let idx = self.model.dof_index(node_idx, dof.index());
2351        if idx < self.u_global.len() {
2352            Ok(self.u_global[idx])
2353        } else {
2354            Ok(0.0)
2355        }
2356    }
2357
2358    /// The full **global** displacement vector (borrowed, not copied).
2359    ///
2360    /// Laid out as `[ux0, uy0, rz0, ux1, uy1, rz1, ...]`, i.e. slot
2361    /// `3*node + dof` with `dof` = `0/1/2` = `ux/uy/rz`
2362    /// (`3*node_idx + dof`). Before a successful solve every entry is
2363    /// `0.0`.
2364    pub fn displacements(&self) -> &[f64] {
2365        &self.u_global
2366    }
2367
2368    /// Compute the global external support reactions.
2369    ///
2370    /// `R = K_original · u - f_global`, evaluated on the **unconstrained**
2371    /// (assembled) system after the full displacement vector has been
2372    /// reconstructed from static condensation:
2373    ///
2374    /// - at a constrained DOF, `R` is the support reaction;
2375    /// - at a free DOF, `R` is numerically zero.
2376    ///
2377    /// Together with the applied loads the reactions satisfy global
2378    /// equilibrium (`ΣF = 0`, `ΣM = 0`). They are **not** element end forces;
2379    /// see [`Self::element_end_forces`] for those.
2380    ///
2381    /// # Pre-solve behaviour
2382    ///
2383    /// Before a successful solve the displacement vector is zero, so this
2384    /// returns the raw algebraic quantity `K·0 - f = -f` — **not** physical
2385    /// support reactions. Check [`Self::solver_name`] (`Some(..)` only after a
2386    /// successful solve), or use [`Self::results`], whose reaction snapshot
2387    /// sets free DOFs to exactly `0.0`.
2388    pub fn reactions(&self) -> Vec<f64> {
2389        // R = K_original * u - f_global
2390        let mut reactions = vec![0.0; self.n_dof];
2391
2392        // Compute K_original * u using public API
2393        let mut k_orig = self.k_original.clone();
2394        k_orig.compress();
2395        for i in 0..self.n_dof {
2396            let mut sum = 0.0;
2397            let row_ptr = k_orig.row_ptr();
2398            let csr_cols = k_orig.csr_cols();
2399            let csr_vals = k_orig.csr_vals();
2400            for idx in row_ptr[i]..row_ptr[i + 1] {
2401                let j = csr_cols[idx];
2402                sum += csr_vals[idx] * self.u_global[j];
2403            }
2404            reactions[i] = sum - self.f_global[i];
2405        }
2406
2407        reactions
2408    }
2409
2410    /// Get reaction at a specific DOF
2411    ///
2412    /// Raw-index accessor for the **global** reaction at `3*node_idx + dof`
2413    /// (`0 = ux` → `Fx`, `1 = uy` → `Fy`, `2 = rz` → `Mz`).
2414    ///
2415    /// # Errors
2416    ///
2417    /// [`FemError::InvalidInput`] if `dof` is not 0, 1, or 2.  Previously
2418    /// `dof >= 3` silently aliased into the following node's DOF slot; this
2419    /// is now rejected.  Prefer the typed [`Self::reaction_dof`] with [`Dof`]
2420    /// for compile-time safety.
2421    ///
2422    /// [`FemError::InvalidInput`] if `node_idx` is out of bounds.  Previously
2423    /// out-of-range node indices silently returned `Ok(0.0)`; this is now
2424    /// rejected for consistency with [`Self::reaction_dof`].
2425    ///
2426    /// Before a successful solve this returns the raw `K·0 - f` value, which
2427    /// is not a physical support reaction (see [`Self::reactions`]).
2428    pub fn reaction(&self, node_idx: usize, dof: usize) -> Result<f64, FemError> {
2429        if dof >= 3 {
2430            return Err(FemError::InvalidInput(format!(
2431                "Invalid DOF index: {} (must be 0=Ux, 1=Uy, 2=Rz)",
2432                dof
2433            )));
2434        }
2435        if node_idx >= self.model.nodes.len() {
2436            return Err(FemError::InvalidInput(format!(
2437                "Invalid node index: {} (max: {})",
2438                node_idx,
2439                self.model.nodes.len().saturating_sub(1)
2440            )));
2441        }
2442        let idx = self.model.dof_index(node_idx, dof);
2443        if idx < self.reactions().len() {
2444            Ok(self.reactions()[idx])
2445        } else {
2446            Ok(0.0)
2447        }
2448    }
2449
2450    /// Typed counterpart of [`Self::reaction`]: **global** support reaction of
2451    /// `dof` at `node_idx`.
2452    ///
2453    /// - `Dof::Ux` → translational X reaction;
2454    /// - `Dof::Uy` → translational Y reaction;
2455    /// - `Dof::Rz` → rotational reaction about Z (counter-clockwise positive).
2456    ///
2457    /// Delegates to the same [`Self::reactions`] vector, so the value is
2458    /// exactly what [`Self::reaction`] returns for the corresponding raw index;
2459    /// only a single reaction evaluation is performed. At a free DOF the value
2460    /// is numerically zero.
2461    ///
2462    /// # Errors
2463    ///
2464    /// [`FemError::InvalidInput`] if `node_idx` is out of bounds.
2465    ///
2466    /// # Examples
2467    ///
2468    /// ```rust
2469    /// use section_properties::beam_fem::{BeamElement, BeamModel, BeamNode, BeamSection, BeamSolver, Dof};
2470    /// use section_properties::material::Material;
2471    ///
2472    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
2473    /// let mut model = BeamModel::new();
2474    /// model.add_node(BeamNode::new(0, 0.0, 0.0));
2475    /// model.add_node(BeamNode::new(1, 1.0, 0.0));
2476    /// model.add_element(BeamElement::new(
2477    ///     0,
2478    ///     1,
2479    ///     Material::new(1.0, 0.3, 1.0, "unit"),
2480    ///     BeamSection::new(1.0, 1.0),
2481    /// )?);
2482    /// model.fix_node(0);
2483    /// model.add_nodal_force(1, 1, -100.0);
2484    ///
2485    /// let mut solver = BeamSolver::from_model(&model)?;
2486    /// solver.solve_configured()?;
2487    ///
2488    /// // Support reactions: Ry = +P, Rz = +P·L
2489    /// let ry = solver.reaction_dof(0, Dof::Uy)?;
2490    /// let rz = solver.reaction_dof(0, Dof::Rz)?;
2491    /// assert!((ry - 100.0).abs() < 1e-9);
2492    /// assert!((rz - 100.0).abs() < 1e-9);
2493    /// assert_eq!(ry, solver.reaction(0, 1)?);
2494    /// # Ok(())
2495    /// # }
2496    /// ```
2497    pub fn reaction_dof(&self, node_idx: usize, dof: Dof) -> Result<f64, FemError> {
2498        if node_idx >= self.model.nodes.len() {
2499            return Err(FemError::InvalidInput(format!(
2500                "Invalid node index: {} (max: {})",
2501                node_idx,
2502                self.model.nodes.len().saturating_sub(1)
2503            )));
2504        }
2505        let reactions = self.reactions();
2506        let idx = self.model.dof_index(node_idx, dof.index());
2507        if idx < reactions.len() {
2508            Ok(reactions[idx])
2509        } else {
2510            Ok(0.0)
2511        }
2512    }
2513
2514    /// Access the original (unconstrained) global stiffness matrix.
2515    ///
2516    /// This is exposed crate-internally for debugging and diagnostics; it is
2517    /// not part of the public API surface.
2518    #[allow(dead_code)]
2519    pub(crate) fn stiffness_matrix(&self) -> &SparseMatrix {
2520        &self.k_original
2521    }
2522
2523    /// Compute element end forces in LOCAL coordinates.
2524    ///
2525    /// Returns a vector of 6 forces per element in local coordinates:
2526    /// `[N_i, V_i, M_i, N_j, V_j, M_j]`, where `N` is axial force, `V` is
2527    /// transverse shear force, and `M` is bending moment.
2528    ///
2529    /// # Sign convention
2530    ///
2531    /// These are the forces the ELEMENT applies to its end NODES (reaction
2532    /// sense), i.e. `f_end = f_equiv - K_local·u_local`. Positive `N` is
2533    /// tension on the node, positive `V` is upward on the node, and positive
2534    /// `M` is counter-clockwise on the node.
2535    ///
2536    /// Applied moments at nodes are external concentrated loads whose effect is
2537    /// carried by the displacement field `u` (through the global force vector),
2538    /// so no separate correction is needed here. Recovered end moments therefore
2539    /// automatically satisfy nodal moment equilibrium:
2540    ///
2541    /// - free-end node with applied moment `M`: `M_element_j + M ≈ 0`;
2542    /// - internal node with applied moment `M` shared by two elements:
2543    ///   `M_left_j + M_right_i + M ≈ 0`.
2544    ///
2545    /// # Scope: nodal end forces, NOT section internal forces
2546    ///
2547    /// This method returns the *element-on-node* nodal equilibrium forces at
2548    /// `ξ = 0` and `ξ = 1` only. It is **not** a beam-section internal-force
2549    /// diagram, and the two are not interchangeable when the element carries a
2550    /// distributed load, an interior point force, or an interior point moment:
2551    /// the end values here include the consistent-load contributions and say
2552    /// nothing about `N(x)`, `V(x)`, `M(x)` *inside* the element.
2553    ///
2554    /// For the internal resultants at an arbitrary `ξ`, use
2555    /// [`Self::element_section_forces`], which recovers `N(x)`, `V(x)`, `M(x)`
2556    /// from equilibrium (including the correct jumps across point loads and
2557    /// moments). Do not overload this method to mean both.
2558    ///
2559    /// # Errors
2560    ///
2561    /// Propagates any error from the equivalent point-load recovery
2562    /// (see `Self::element_equivalent_nodal_forces`); a failed recovery is
2563    /// never silently replaced by a zero load.
2564    pub fn element_end_forces(&self) -> Result<Vec<[f64; 6]>, FemError> {
2565        let mut results = Vec::with_capacity(self.model.elements.len());
2566        for elem_idx in 0..self.model.elements.len() {
2567            results.push(self.element_on_node_end_forces_local(elem_idx)?);
2568        }
2569        Ok(results)
2570    }
2571
2572    /// Local element displacement vector `[u_i, v_i, θ_i, u_j, v_j, θ_j]`.
2573    ///
2574    /// Returns the element's nodal displacements transformed from global to
2575    /// local coordinates (`u_local = T · u_global`).
2576    ///
2577    /// # Errors
2578    ///
2579    /// Returns [`FemError::InvalidInput`] if `element_idx` is out of bounds.
2580    fn element_local_displacement(&self, element_idx: usize) -> Result<[f64; 6], FemError> {
2581        let element = self.model.elements.get(element_idx).ok_or_else(|| {
2582            FemError::InvalidInput(format!(
2583                "Invalid element index: {} (max: {})",
2584                element_idx,
2585                self.model.elements.len().saturating_sub(1)
2586            ))
2587        })?;
2588        let node_i = self.model.nodes[element.node_i].point();
2589        let node_j = self.model.nodes[element.node_j].point();
2590
2591        let dof_map = [
2592            self.model.dof_index(element.node_i, 0), // u_i
2593            self.model.dof_index(element.node_i, 1), // v_i
2594            self.model.dof_index(element.node_i, 2), // θ_i
2595            self.model.dof_index(element.node_j, 0), // u_j
2596            self.model.dof_index(element.node_j, 1), // v_j
2597            self.model.dof_index(element.node_j, 2), // θ_j
2598        ];
2599        let u_global_elem = [
2600            self.u_global[dof_map[0]],
2601            self.u_global[dof_map[1]],
2602            self.u_global[dof_map[2]],
2603            self.u_global[dof_map[3]],
2604            self.u_global[dof_map[4]],
2605            self.u_global[dof_map[5]],
2606        ];
2607
2608        // Transform to local coordinates: u_local = T * u_global.
2609        let t = element.transformation_matrix(node_i, node_j);
2610        let mut u_local = [0.0; 6];
2611        for i in 0..6 {
2612            for j in 0..6 {
2613                u_local[i] += t[i][j] * u_global_elem[j];
2614            }
2615        }
2616        Ok(u_local)
2617    }
2618
2619    /// Element-on-node end forces in LOCAL coordinates for a single element:
2620    /// `f_end = f_equiv - K_local · u_local`, ordered
2621    /// `[N_i, V_i, M_i, N_j, V_j, M_j]`.
2622    ///
2623    /// # Errors
2624    ///
2625    /// Propagates errors from [`Self::element_local_displacement`] and
2626    /// [`Self::element_equivalent_nodal_forces`].
2627    fn element_on_node_end_forces_local(&self, element_idx: usize) -> Result<[f64; 6], FemError> {
2628        let element = self.model.elements.get(element_idx).ok_or_else(|| {
2629            FemError::InvalidInput(format!(
2630                "Invalid element index: {} (max: {})",
2631                element_idx,
2632                self.model.elements.len().saturating_sub(1)
2633            ))
2634        })?;
2635        let node_i = self.model.nodes[element.node_i].point();
2636        let node_j = self.model.nodes[element.node_j].point();
2637
2638        let u_local = self.element_local_displacement(element_idx)?;
2639
2640        // Internal nodal force: f_stiffness = K_local * u_local.
2641        let k_local = element.local_stiffness(node_i, node_j);
2642        let mut f_stiffness = [0.0; 6];
2643        for i in 0..6 {
2644            for j in 0..6 {
2645                f_stiffness[i] += k_local[i][j] * u_local[j];
2646            }
2647        }
2648
2649        // Equivalent nodal forces from distributed and point loads on this
2650        // element. Applied moments at nodes are external concentrated loads,
2651        // excluded from the equivalent element loads.
2652        let f_equiv = Self::element_equivalent_nodal_forces(
2653            &self.model,
2654            element_idx,
2655            element,
2656            node_i,
2657            node_j,
2658        )?;
2659
2660        // Element-on-node end forces: f_end = f_equiv - f_stiffness.
2661        let mut end_forces = [0.0; 6];
2662        for i in 0..6 {
2663            end_forces[i] = f_equiv[i] - f_stiffness[i];
2664        }
2665        Ok(end_forces)
2666    }
2667
2668    /// Compute equivalent nodal forces (in LOCAL coordinates) for an element
2669    /// from DISTRIBUTED and POINT loads (NOT including applied moments at
2670    /// nodes, which are external concentrated loads handled in the global
2671    /// force vector).
2672    ///
2673    /// Returns `[N_i, V_i, M_i, N_j, V_j, M_j]` in local coordinates.
2674    ///
2675    /// # Errors
2676    ///
2677    /// Propagates any error from [`BeamElement::consistent_nodal_load_point`]
2678    /// (for example a zero-length element). Point-load positions are validated
2679    /// when the load is added via [`BeamModel::add_point_load`], so in normal
2680    /// use this succeeds; the error path exists so that a failed equivalent-load
2681    /// computation can never be silently turned into a zero load.
2682    fn element_equivalent_nodal_forces(
2683        model: &BeamModel,
2684        elem_idx: usize,
2685        element: &BeamElement,
2686        node_i: Point,
2687        node_j: Point,
2688    ) -> Result<[f64; 6], FemError> {
2689        let mut f_equiv = [0.0; 6];
2690
2691        // Distributed loads on this element.
2692        for dl in &model.distributed_loads {
2693            if dl.element_idx == elem_idx {
2694                let f_local = element.consistent_nodal_load(node_i, node_j, dl.qx, dl.qy)?;
2695                for i in 0..6 {
2696                    f_equiv[i] += f_local[i];
2697                }
2698            }
2699        }
2700
2701        // Point loads on this element.
2702        for pl in &model.point_loads {
2703            if pl.element_idx == elem_idx {
2704                let f_local = element.consistent_nodal_load_point(
2705                    node_i,
2706                    node_j,
2707                    pl.position,
2708                    pl.fx,
2709                    pl.fy,
2710                    pl.mz,
2711                )?;
2712                for i in 0..6 {
2713                    f_equiv[i] += f_local[i];
2714                }
2715            }
2716        }
2717
2718        Ok(f_equiv)
2719    }
2720
2721    /// Compute element end forces in GLOBAL coordinates
2722    ///
2723    /// Returns a vector of 6 forces per element in global coordinates:
2724    /// [Fx_i, Fy_i, Mz_i, Fx_j, Fy_j, Mz_j]
2725    ///
2726    /// # Errors
2727    ///
2728    /// Propagates any error from [`Self::element_end_forces`].
2729    pub fn element_end_forces_global(&self) -> Result<Vec<[f64; 6]>, FemError> {
2730        let local_forces = self.element_end_forces()?;
2731        let mut results = Vec::new();
2732
2733        for (idx, forces) in local_forces.iter().enumerate() {
2734            let element = &self.model.elements[idx];
2735            let node_i = self.model.nodes[element.node_i].point();
2736            let node_j = self.model.nodes[element.node_j].point();
2737
2738            let T = element.transformation_matrix(node_i, node_j);
2739
2740            // Transform local forces to global: f_global = T^T * f_local
2741            let mut f_global_elem = [0.0; 6];
2742            for i in 0..6 {
2743                for j in 0..6 {
2744                    f_global_elem[i] += T[j][i] * forces[j];
2745                }
2746            }
2747
2748            results.push(f_global_elem);
2749        }
2750
2751        Ok(results)
2752    }
2753
2754    /// Compute the internal section forces `N`, `V`, `M` at normalized position
2755    /// `xi` along element `element_idx`, in LOCAL coordinates.
2756    ///
2757    /// `xi = 0` at `node_i` and `xi = 1` at `node_j`; the physical position is
2758    /// `x = xi · L`.
2759    ///
2760    /// # What this returns
2761    ///
2762    /// True beam-section internal resultants at the cut (see [`SectionForces`]
2763    /// for the sign convention):
2764    /// - `axial` (`N`): tension positive,
2765    /// - `shear` (`V`): satisfies `d(moment)/dx = shear`,
2766    /// - `moment` (`M`): sagging positive.
2767    ///
2768    /// These are beam-LOCAL quantities (not transformed to global axes). They
2769    /// are deliberately distinct from [`Self::element_end_forces`], which
2770    /// returns the element-on-node *nodal equilibrium* forces at the two ends
2771    /// only.
2772    ///
2773    /// # Method (equilibrium recovery)
2774    ///
2775    /// The result is obtained by enforcing equilibrium of the element segment
2776    /// `[0, x]` using the recovered i-end element-on-node force and the actual
2777    /// distributed / point loads — **not** by linearly interpolating the end
2778    /// forces. With the local axes of this module (+x from `node_i` to
2779    /// `node_j`, +y transverse with upward load `qy > 0`, `θ` CCW) and the
2780    /// i-end force `f_i = [N_i, V_i, M_i]` from [`Self::element_end_forces`]:
2781    ///
2782    /// ```text
2783    /// N(x) = N_i - qx·x - Σ_{x_p < x} fx_p
2784    /// V(x) = -V_i + qy·x + Σ_{x_p < x} fy_p
2785    /// M(x) = M_i - x·V_i + qy·x²/2 - Σ_{x_p < x} [(x_p - x)·fy_p + mz_p]
2786    /// ```
2787    ///
2788    /// This is the equilibrium-consistent extension of the Euler–Bernoulli
2789    /// relations: for an element with no span load (no distributed load and no
2790    /// interior point load) it reduces to the classical `N = E·A·du/dx` and
2791    /// `M = E·I·v''` implied by the element's cubic Hermite field, while
2792    /// additionally satisfying
2793    ///
2794    /// ```text
2795    /// dN/dx = -qx
2796    /// dV/dx =  qy          (qy = upward load intensity; = -q_down)
2797    /// dM/dx =  V
2798    /// ```
2799    ///
2800    /// and reproducing the correct jumps at interior point forces / moments.
2801    /// For statically determinate loadings the section forces are exact.
2802    ///
2803    /// # Discontinuities (point loads inside the element)
2804    ///
2805    /// A load at `x_p = xi_p · L` introduces a jump with this convention:
2806    ///
2807    /// ```text
2808    /// N(xi_p⁺) - N(xi_p⁻) = -fx_p
2809    /// V(xi_p⁺) - V(xi_p⁻) = +fy_p
2810    /// M(xi_p⁺) - M(xi_p⁻) = -mz_p
2811    /// ```
2812    ///
2813    /// Evaluating exactly at `xi = xi_p` returns the **left limit**
2814    /// (`x -> xi_p⁻`): loads located strictly before `xi` are included and a
2815    /// load exactly at `xi` is excluded. Evaluate at `xi_p ± ε` (or on the
2816    /// adjacent elements) to obtain the right-hand value.
2817    ///
2818    /// # Relation to element end forces
2819    ///
2820    /// At the element ends the section forces agree with
2821    /// [`Self::element_end_forces`] up to the sign factors of the
2822    /// internal-force convention:
2823    ///
2824    /// ```text
2825    /// xi = 0:  N = +N_i,  V = -V_i,  M = +M_i
2826    /// xi = 1:  N = -N_j,  V = +V_j,  M = -M_j
2827    /// ```
2828    ///
2829    /// # Nodal applied moments vs. interior point moments
2830    ///
2831    /// Two different moment-load mechanisms exist and must not be conflated:
2832    ///
2833    /// - [`BeamModel::add_point_load`] / [`BeamModel::add_point_moment`] stores
2834    ///   a moment *inside* an element (`0 < xi_p < 1`). It is a span load and
2835    ///   produces the interior jump `M(xi_p⁺) - M(xi_p⁻) = -mz_p` above.
2836    /// - [`BeamModel::add_applied_moment`] stores a concentrated moment at a
2837    ///   *mesh node*. It is **not** a span load: it enters the global force
2838    ///   vector (the θ DOF) and is therefore already carried by the
2839    ///   element-on-node end forces from which this recovery is built, so no
2840    ///   separate term is added here. (Adding one would double-count it.)
2841    ///
2842    /// For an internal node shared by elements `e` and `e+1` carrying an
2843    /// applied nodal moment `M_ext`, the recovered section moments on the two
2844    /// sides satisfy the nodal moment equilibrium
2845    ///
2846    /// ```text
2847    /// M(e+1, xi=0) - M(e, xi=1) + M_ext = 0
2848    /// ```
2849    ///
2850    /// which is the section-force form of the element-on-node end-force
2851    /// equilibrium `M_j(e) + M_i(e+1) + M_ext = 0` under the boundary relations
2852    /// above. Equivalently, the internal moment jumps by `-M_ext` across the
2853    /// node — the same sign as an interior point moment of equal value. A nodal
2854    /// moment applied at a free end yields a constant `+M_ext` along the
2855    /// element.
2856    ///
2857    /// ## Internal-node limits
2858    ///
2859    /// The "exact evaluation returns the left limit" rule applies to interior
2860    /// point loads with `0 < xi_p < 1`. A nodal applied moment is not evaluated
2861    /// from within one element; the meaningful statement is the two-sided
2862    /// equilibrium relation above between `element_section_forces(e, 1.0)` and
2863    /// `element_section_forces(e+1, 0.0)`.
2864    ///
2865    /// # Errors
2866    ///
2867    /// Returns [`FemError::InvalidInput`] if `element_idx` is out of bounds,
2868    /// if `xi` is outside `[0, 1]`, or if the element has zero length.
2869    pub fn element_section_forces(
2870        &self,
2871        element_idx: usize,
2872        xi: f64,
2873    ) -> Result<SectionForces, FemError> {
2874        let element = self.model.elements.get(element_idx).ok_or_else(|| {
2875            FemError::InvalidInput(format!(
2876                "Invalid element index: {} (max: {})",
2877                element_idx,
2878                self.model.elements.len().saturating_sub(1)
2879            ))
2880        })?;
2881        if !(0.0..=1.0).contains(&xi) {
2882            return Err(FemError::InvalidInput(format!(
2883                "Section position xi must be in [0, 1], got {}",
2884                xi
2885            )));
2886        }
2887        let node_i = self.model.nodes[element.node_i].point();
2888        let node_j = self.model.nodes[element.node_j].point();
2889        let length = element.length(node_i, node_j);
2890        if length <= 0.0 {
2891            return Err(FemError::InvalidInput(
2892                "Beam element has zero or negative length for section-force recovery".to_string(),
2893            ));
2894        }
2895
2896        let x = xi * length;
2897
2898        // Anchor at the i-end element-on-node force (LOCAL): [N_i, V_i, M_i, ...].
2899        let f_end = self.element_on_node_end_forces_local(element_idx)?;
2900        let n_i = f_end[0];
2901        let v_i = f_end[1];
2902        let m_i = f_end[2];
2903
2904        // Uniform distributed load on this element (LOCAL), summed if repeated.
2905        let mut qx = 0.0;
2906        let mut qy = 0.0;
2907        for dl in &self.model.distributed_loads {
2908            if dl.element_idx == element_idx {
2909                qx += dl.qx;
2910                qy += dl.qy;
2911            }
2912        }
2913
2914        // Point loads strictly to the left of x (left-limit convention).
2915        let mut sum_fx = 0.0;
2916        let mut sum_fy = 0.0;
2917        let mut sum_moment = 0.0;
2918        for pl in &self.model.point_loads {
2919            if pl.element_idx != element_idx {
2920                continue;
2921            }
2922            let x_p = pl.position * length;
2923            if x_p < x {
2924                sum_fx += pl.fx;
2925                sum_fy += pl.fy;
2926                sum_moment += (x_p - x) * pl.fy + pl.mz;
2927            }
2928        }
2929
2930        let axial = n_i - qx * x - sum_fx;
2931        let shear = -v_i + qy * x + sum_fy;
2932        let moment = m_i - x * v_i + 0.5 * qy * x * x - sum_moment;
2933
2934        Ok(SectionForces::new(axial, shear, moment))
2935    }
2936
2937    /// Beam arclength from the start of element 0 to the start (`xi = 0`) of
2938    /// `element_index`, accumulated in model order.
2939    ///
2940    /// Private helper shared by the sampling APIs. `element_index` is assumed
2941    /// already validated; indices `>= elements.len()` simply sum all elements.
2942    fn element_start_distance(&self, element_index: usize) -> f64 {
2943        self.model
2944            .elements
2945            .iter()
2946            .take(element_index)
2947            .map(|e| {
2948                let ni = self.model.nodes[e.node_i].point();
2949                let nj = self.model.nodes[e.node_j].point();
2950                e.length(ni, nj)
2951            })
2952            .sum()
2953    }
2954
2955    /// Sample the internal-force diagram of a single element at `n` uniformly
2956    /// spaced points, including both endpoints.
2957    ///
2958    /// Samples `xi = k / (n - 1)` for `k = 0..=n-1` (i.e. `k = 0, 1, …, n-1`),
2959    /// so `xi = 0` and `xi = 1` are always included. Each sample delegates to
2960    /// [`Self::element_section_forces`] — the N/V/M values are **not**
2961    /// interpolated or recomputed here.
2962    ///
2963    /// # Arguments
2964    ///
2965    /// - `element_index`: element index in `BeamModel::elements` order.
2966    /// - `n`: number of samples, must be `>= 2`.
2967    ///
2968    /// The returned samples carry the global beam arclength `x` (see
2969    /// [`BeamForceSample`]), measured from the start of element 0, so a sample
2970    /// on element `e` starts at `Σ_{k < e} length(k)`.
2971    ///
2972    /// # Discontinuities
2973    ///
2974    /// If a uniform `xi` lands exactly on an interior point load, the value is
2975    /// the existing **left-limit** result of
2976    /// [`Self::element_section_forces`]. No epsilon sampling is applied.
2977    ///
2978    /// # Errors
2979    ///
2980    /// Returns [`FemError::InvalidInput`] if `n < 2`, if `element_index` is out
2981    /// of bounds, or if the element has zero length.
2982    pub fn sample_element_forces(
2983        &self,
2984        element_index: usize,
2985        n: usize,
2986    ) -> Result<Vec<BeamForceSample>, FemError> {
2987        if n < 2 {
2988            return Err(FemError::InvalidInput(format!(
2989                "Number of samples n must be >= 2, got {}",
2990                n
2991            )));
2992        }
2993        if element_index >= self.model.elements.len() {
2994            return Err(FemError::InvalidInput(format!(
2995                "Invalid element index: {} (max: {})",
2996                element_index,
2997                self.model.elements.len().saturating_sub(1)
2998            )));
2999        }
3000
3001        let element = &self.model.elements[element_index];
3002        let node_i = self.model.nodes[element.node_i].point();
3003        let node_j = self.model.nodes[element.node_j].point();
3004        let length = element.length(node_i, node_j);
3005        let start = self.element_start_distance(element_index);
3006
3007        let mut samples = Vec::with_capacity(n);
3008        for k in 0..n {
3009            let xi = k as f64 / (n - 1) as f64;
3010            // Delegates to the authoritative recovery (also validates a
3011            // zero-length element via its existing error path).
3012            let section_forces = self.element_section_forces(element_index, xi)?;
3013            samples.push(BeamForceSample {
3014                element_index,
3015                xi,
3016                x: start + xi * length,
3017                section_forces,
3018            });
3019        }
3020        Ok(samples)
3021    }
3022
3023    /// Sample the internal-force diagram of the whole beam at `n_per_element`
3024    /// uniformly spaced points per element.
3025    ///
3026    /// Elements are traversed in `BeamModel::elements` order. Global `x` is the
3027    /// physical beam arclength accumulated over the true element lengths (equal
3028    /// lengths are NOT assumed):
3029    /// `x = Σ_{k < e} length(k) + xi · length(e)`.
3030    ///
3031    /// # Shared boundaries are duplicated on purpose
3032    ///
3033    /// The last sample of element `e` (`xi = 1`) and the first sample of
3034    /// element `e+1` (`xi = 0`) share the same `x`. Both are returned:
3035    ///
3036    /// - when the internal force is continuous, the two values agree;
3037    /// - at a point force / moment discontinuity they differ and represent the
3038    ///   two one-sided limits.
3039    ///
3040    /// Duplicate `x` coordinates are **never** deduplicated — doing so would
3041    /// destroy discontinuities for a future plotting layer.
3042    ///
3043    /// # Errors
3044    ///
3045    /// Returns [`FemError::InvalidInput`] if `n_per_element < 2`, or for any
3046    /// per-element error from [`Self::sample_element_forces`].
3047    pub fn sample_beam_forces(
3048        &self,
3049        n_per_element: usize,
3050    ) -> Result<Vec<BeamForceSample>, FemError> {
3051        if n_per_element < 2 {
3052            return Err(FemError::InvalidInput(format!(
3053                "Number of samples per element must be >= 2, got {}",
3054                n_per_element
3055            )));
3056        }
3057        let mut samples = Vec::with_capacity(n_per_element * self.model.elements.len());
3058        for element_index in 0..self.model.elements.len() {
3059            samples.extend(self.sample_element_forces(element_index, n_per_element)?);
3060        }
3061        Ok(samples)
3062    }
3063
3064    /// Sample the whole beam and wrap the result in a [`BeamForceDiagram`].
3065    ///
3066    /// Equivalent to [`Self::sample_beam_forces`] plus a container. No
3067    /// interpolation is performed.
3068    ///
3069    /// # Errors
3070    ///
3071    /// Same as [`Self::sample_beam_forces`].
3072    pub fn beam_force_diagram(&self, n_per_element: usize) -> Result<BeamForceDiagram, FemError> {
3073        Ok(BeamForceDiagram::new(
3074            self.sample_beam_forces(n_per_element)?,
3075        ))
3076    }
3077
3078    /// Build a unified, read-only [`BeamAnalysisResult`] view of this solver.
3079    ///
3080    /// This does **not** run the solver: it is a cheap, infallible view over the
3081    /// current displacement state, so call [`Self::solve`] first. The reaction
3082    /// vector is snapshotted once here (masking unconstrained DOFs to exactly
3083    /// zero); everything else is delegated lazily to the solver.
3084    pub fn results(&self) -> BeamAnalysisResult<'_> {
3085        let mut reactions = self.reactions();
3086        for (i, reaction) in reactions.iter_mut().enumerate() {
3087            if !self.fixed_dofs[i] {
3088                *reaction = 0.0;
3089            }
3090        }
3091        BeamAnalysisResult {
3092            solver: self,
3093            reactions,
3094        }
3095    }
3096}
3097
3098/// FemError for beam FEM
3099#[derive(Debug, Clone, thiserror::Error)]
3100pub enum FemError {
3101    #[error("Invalid model: {0}")]
3102    InvalidModel(String),
3103    #[error("Solver error: {message}")]
3104    SolverError {
3105        /// The structured solver error that caused the failure.
3106        source: SolverError,
3107        /// Human-readable message, potentially including structural diagnosis.
3108        message: String,
3109    },
3110    #[error("Invalid input: {0}")]
3111    InvalidInput(String),
3112    // ---- frame-level structural diagnostics (see `crate::frame`) ----------
3113    #[error("Invalid node: {0}")]
3114    InvalidNode(String),
3115    #[error("Invalid member: {0}")]
3116    InvalidMember(String),
3117    #[error("Zero-length member: {0}")]
3118    ZeroLengthMember(String),
3119    #[error("Duplicate member: {0}")]
3120    DuplicateMember(String),
3121    #[error("Orphan node: {0}")]
3122    OrphanNode(String),
3123    #[error("Disconnected structure: {0}")]
3124    DisconnectedStructure(String),
3125    #[error(
3126        "Conflicting prescribed displacement at node {node_idx}, DOF {dof}: \
3127             first value {first_value}, conflicting value {conflicting_value}"
3128    )]
3129    ConflictingPrescribedDisplacement {
3130        node_idx: usize,
3131        dof: usize,
3132        first_value: f64,
3133        conflicting_value: f64,
3134    },
3135}
3136
3137impl FemError {
3138    /// Return the structured [`SolverError`] if this is a `SolverError` variant.
3139    pub fn solver_error(&self) -> Option<&SolverError> {
3140        match self {
3141            FemError::SolverError { source, .. } => Some(source),
3142            _ => None,
3143        }
3144    }
3145}
3146
3147impl From<SolverError> for FemError {
3148    fn from(e: SolverError) -> Self {
3149        FemError::SolverError {
3150            message: e.to_string(),
3151            source: e,
3152        }
3153    }
3154}
3155
3156/// High-level API for beam analysis
3157pub struct BeamAnalysis;
3158
3159impl BeamAnalysis {
3160    /// Analyze a cantilever beam with tip load
3161    pub fn cantilever_tip_load(L: f64, E: f64, _A: f64, I: f64, P: f64) -> (f64, f64, f64) {
3162        // Analytical solutions for cantilever with tip load P at free end
3163        // Fixed at x=0, load P downward (transverse) at x=L
3164        let u_tip = 0.0; // No axial displacement for transverse load
3165        let v_tip = P * L.powi(3) / (3.0 * E * I); // Transverse deflection
3166        let theta_tip = P * L.powi(2) / (2.0 * E * I); // Rotation
3167
3168        (u_tip, v_tip, theta_tip)
3169    }
3170
3171    /// Analyze a simply supported beam with central point load
3172    pub fn simply_supported_central_load(L: f64, E: f64, I: f64, P: f64) -> (f64, f64) {
3173        // Central deflection and rotation at support
3174        let v_mid = P * L.powi(3) / (48.0 * E * I);
3175        let theta_support = P * L.powi(2) / (16.0 * E * I);
3176        (v_mid, theta_support)
3177    }
3178}
3179
3180#[cfg(test)]
3181mod tests {
3182    use super::*;
3183    use crate::material::Material;
3184
3185    #[test]
3186    fn test_beam_section_creation() {
3187        let sec = BeamSection::new(1.0, 1.0);
3188        assert_eq!(sec.area, 1.0);
3189        assert_eq!(sec.second_moment, 1.0);
3190
3191        let rect = BeamSection::rectangle(0.1, 0.2);
3192        assert!((rect.area - 0.02).abs() < 1e-10);
3193        assert!((rect.second_moment - 0.1 * 0.2_f64.powi(3) / 12.0).abs() < 1e-10);
3194
3195        let circ = BeamSection::circle(0.05);
3196        assert!((circ.area - std::f64::consts::PI * 0.0025).abs() < 1e-10);
3197    }
3198
3199    #[test]
3200    fn test_local_stiffness() {
3201        let material = Material::new(200e9, 0.3, 7850.0, "Steel");
3202        let section = BeamSection::new(0.01, 8.333e-6);
3203        let element = BeamElement::new(0, 1, material, section).unwrap();
3204
3205        let node_i = Point::new(0.0, 0.0);
3206        let node_j = Point::new(1.0, 0.0);
3207
3208        let k = element.local_stiffness(node_i, node_j);
3209
3210        // Check symmetry
3211        for i in 0..6 {
3212            for j in 0..6 {
3213                assert!(
3214                    (k[i][j] - k[j][i]).abs() < 1e-10,
3215                    "Matrix not symmetric at ({},{})",
3216                    i,
3217                    j
3218                );
3219            }
3220        }
3221
3222        // Check axial terms
3223        let E: f64 = 200e9;
3224        let A: f64 = 0.01;
3225        let L: f64 = 1.0;
3226        let EA_L = E * A / L;
3227        assert!((k[0][0] - EA_L).abs() < 1e-6);
3228        assert!((k[0][3] + EA_L).abs() < 1e-6);
3229        assert!((k[3][3] - EA_L).abs() < 1e-6);
3230
3231        // Check bending terms
3232        let I: f64 = 8.333e-6;
3233        let EI_L3 = E * I / L.powi(3);
3234        let EI_L2 = E * I / L.powi(2);
3235        let EI_L = E * I / L;
3236
3237        assert!((k[1][1] - 12.0 * EI_L3).abs() < 1e-6);
3238        assert!((k[1][2] - 6.0 * EI_L2).abs() < 1e-6);
3239        assert!((k[2][2] - 4.0 * EI_L).abs() < 1e-6);
3240        assert!((k[4][4] - 12.0 * EI_L3).abs() < 1e-6);
3241        assert!((k[5][5] - 4.0 * EI_L).abs() < 1e-6);
3242    }
3243
3244    #[test]
3245    fn test_transformation_matrix() {
3246        let material = Material::new(200e9, 0.3, 7850.0, "Steel");
3247        let section = BeamSection::new(0.01, 8.333e-6);
3248        let element = BeamElement::new(0, 1, material, section).unwrap();
3249
3250        // Horizontal beam
3251        let node_i = Point::new(0.0, 0.0);
3252        let node_j = Point::new(1.0, 0.0);
3253        let T = element.transformation_matrix(node_i, node_j);
3254
3255        // For horizontal beam: c=1, s=0
3256        assert!((T[0][0] - 1.0).abs() < 1e-10);
3257        assert!((T[1][1] - 1.0).abs() < 1e-10);
3258        assert!((T[2][2] - 1.0).abs() < 1e-10);
3259        assert!((T[3][3] - 1.0).abs() < 1e-10);
3260        assert!((T[4][4] - 1.0).abs() < 1e-10);
3261        assert!((T[5][5] - 1.0).abs() < 1e-10);
3262
3263        // Vertical beam
3264        let node_i = Point::new(0.0, 0.0);
3265        let node_j = Point::new(0.0, 1.0);
3266        let T = element.transformation_matrix(node_i, node_j);
3267
3268        // For vertical beam: c=0, s=1
3269        assert!((T[0][0] - 0.0).abs() < 1e-10); // c
3270        assert!((T[0][1] - 1.0).abs() < 1e-10); // s
3271        assert!((T[1][0] - -1.0).abs() < 1e-10); // -s
3272        assert!((T[1][1] - 0.0).abs() < 1e-10); // c
3273    }
3274
3275    #[test]
3276    fn test_global_stiffness_horizontal() {
3277        let material = Material::new(200e9, 0.3, 7850.0, "Steel");
3278        let section = BeamSection::new(0.01, 8.333e-6);
3279        let element = BeamElement::new(0, 1, material, section).unwrap();
3280
3281        let node_i = Point::new(0.0, 0.0);
3282        let node_j = Point::new(1.0, 0.0);
3283
3284        let k_global = element.global_stiffness(node_i, node_j);
3285        let k_local = element.local_stiffness(node_i, node_j);
3286
3287        // For horizontal beam, global should equal local
3288        for i in 0..6 {
3289            for j in 0..6 {
3290                assert!((k_global[i][j] - k_local[i][j]).abs() < 1e-10);
3291            }
3292        }
3293    }
3294
3295    #[test]
3296    fn test_global_stiffness_vertical() {
3297        let material = Material::new(200e9, 0.3, 7850.0, "Steel");
3298        let section = BeamSection::new(0.01, 8.333e-6);
3299        let element = BeamElement::new(0, 1, material, section).unwrap();
3300
3301        let node_i = Point::new(0.0, 0.0);
3302        let node_j = Point::new(0.0, 1.0);
3303
3304        let k_global = element.global_stiffness(node_i, node_j);
3305
3306        // Check symmetry
3307        for i in 0..6 {
3308            for j in 0..6 {
3309                assert!((k_global[i][j] - k_global[j][i]).abs() < 1e-10);
3310            }
3311        }
3312    }
3313
3314    #[test]
3315    fn test_cantilever_analytical() {
3316        let L = 1.0;
3317        let E = 200e9;
3318        let A = 0.01;
3319        let I = 8.333e-6;
3320        let P = 1000.0;
3321
3322        let (u_tip, v_tip, theta_tip) = BeamAnalysis::cantilever_tip_load(L, E, A, I, P);
3323
3324        // For tip load P downward: axial = 0, v = PL³/3EI, θ = PL²/2EI
3325        let expected_v = P * L.powi(3) / (3.0 * E * I);
3326        let expected_theta = P * L.powi(2) / (2.0 * E * I);
3327
3328        assert!((v_tip - expected_v).abs() < 1e-10);
3329        assert!((theta_tip - expected_theta).abs() < 1e-10);
3330        assert!(u_tip.abs() < 1e-10); // No axial load in this case
3331    }
3332
3333    #[test]
3334    fn test_beam_model() {
3335        let mut model = BeamModel::new();
3336
3337        model.add_node(BeamNode::new(0, 0.0, 0.0));
3338        model.add_node(BeamNode::new(1, 1.0, 0.0));
3339
3340        let material = Material::new(200e9, 0.3, 7850.0, "Steel");
3341        let section = BeamSection::new(0.01, 8.333e-6);
3342        model.add_element(BeamElement::new(0, 1, material, section).unwrap());
3343
3344        model.fix_node(0);
3345        model.add_nodal_force(1, 1, -1000.0); // Downward force at tip
3346
3347        assert_eq!(model.n_dof(), 6);
3348        assert_eq!(model.dof_index(0, 0), 0);
3349        assert_eq!(model.dof_index(0, 1), 1);
3350        assert_eq!(model.dof_index(0, 2), 2);
3351        assert_eq!(model.dof_index(1, 0), 3);
3352        assert_eq!(model.dof_index(1, 1), 4);
3353        assert_eq!(model.dof_index(1, 2), 5);
3354    }
3355
3356    #[test]
3357    fn p1_02_reproduce_conflicting_prescribed_displacement() {
3358        let mut model = BeamModel::new();
3359        model.add_node(BeamNode::new(0, 0.0, 0.0));
3360        model.add_node(BeamNode::new(1, 1.0, 0.0));
3361        model.try_fix_dof(0, 1, 0.0).unwrap();
3362        let result = model.try_fix_dof(0, 1, 0.01);
3363        match result {
3364            Ok(()) => {
3365                panic!("P1-02 NOT fixed: conflicting prescribed displacement silently accepted")
3366            }
3367            Err(e) => println!("P1-02 confirmed: got Err = {:?}", e),
3368        }
3369    }
3370
3371    #[test]
3372    fn p1_02_same_prescribed_value_is_idempotent() {
3373        let mut model = BeamModel::new();
3374        model.add_node(BeamNode::new(0, 0.0, 0.0));
3375        model.add_node(BeamNode::new(1, 1.0, 0.0));
3376        model.try_fix_dof(0, 1, 0.005).unwrap();
3377        model.try_fix_dof(0, 1, 0.005).unwrap();
3378        assert_eq!(model.fixed_dofs.len(), 1);
3379    }
3380
3381    #[test]
3382    fn p1_02_different_dofs_are_independent() {
3383        let mut model = BeamModel::new();
3384        model.add_node(BeamNode::new(0, 0.0, 0.0));
3385        model.add_node(BeamNode::new(1, 1.0, 0.0));
3386        model.try_fix_dof(0, 0, 0.0).unwrap();
3387        model.try_fix_dof(0, 1, 0.01).unwrap();
3388        model.try_fix_dof(0, 2, 0.02).unwrap();
3389    }
3390
3391    #[test]
3392    fn p1_02_different_nodes_are_independent() {
3393        let mut model = BeamModel::new();
3394        model.add_node(BeamNode::new(0, 0.0, 0.0));
3395        model.add_node(BeamNode::new(1, 1.0, 0.0));
3396        model.try_fix_dof(0, 0, 0.0).unwrap();
3397        model.try_fix_dof(1, 0, 0.01).unwrap();
3398    }
3399
3400    #[test]
3401    fn p1_02_override_after_fix_allows_settlement() {
3402        let mut model = BeamModel::new();
3403        model.add_node(BeamNode::new(0, 0.0, 0.0));
3404        model.add_node(BeamNode::new(1, 1.0, 0.0));
3405        model.try_fix_node(0).unwrap();
3406        model.try_override_dof(0, 1, -0.005).unwrap();
3407        assert_eq!(model.fixed_dofs.len(), 3);
3408        let uy = model
3409            .fixed_dofs
3410            .iter()
3411            .find(|&&(n, d, _)| n == 0 && d == 1)
3412            .map(|&(_, _, v)| v)
3413            .unwrap();
3414        assert_eq!(uy, -0.005);
3415    }
3416
3417    #[test]
3418    fn p1_02_override_replaces_existing_value() {
3419        let mut model = BeamModel::new();
3420        model.add_node(BeamNode::new(0, 0.0, 0.0));
3421        model.add_node(BeamNode::new(1, 1.0, 0.0));
3422        model.try_override_dof(0, 1, 0.01).unwrap();
3423        model.try_override_dof(0, 1, 0.02).unwrap();
3424        assert_eq!(model.fixed_dofs.len(), 1);
3425        assert_eq!(model.fixed_dofs[0].2, 0.02);
3426    }
3427}