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