Skip to main content

section_properties/mesh/
fem.rs

1//! Finite Element Method (FEM) solver for linear elastic analysis.
2//!
3//! Provides 2D plane stress/strain and plate bending elements,
4//! stiffness matrix assembly, displacement solution, and stress recovery.
5
6use crate::geometry::Point;
7use crate::material::Material;
8use crate::mesh::{Mesh, MeshParams};
9use crate::section::Section;
10use std::collections::HashMap;
11
12/// 2D element types.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum ElementType {
15    /// 3-node triangle (CST - Constant Strain Triangle)
16    Tri3,
17    /// 6-node triangle (quadratic)
18    Tri6,
19    /// 4-node quadrilateral (bilinear)
20    Quad4,
21    /// 8-node quadrilateral (quadratic)
22    Quad8,
23}
24
25/// Material properties for FEM (plane stress/strain).
26#[derive(Debug, Clone, Copy)]
27pub struct MaterialProps {
28    /// Young's modulus
29    pub youngs_modulus: f64,
30    /// Poisson's ratio
31    pub poissons_ratio: f64,
32    /// Shear modulus (G = E / (2(1+nu)))
33    pub shear_modulus: f64,
34    /// Density (for mass matrix)
35    pub density: f64,
36    /// Plane stress (true) or plane strain (false)
37    pub plane_stress: bool,
38    /// Shear correction factor (for plates)
39    pub shear_correction: f64,
40}
41
42impl MaterialProps {
43    /// Create from Material with plane stress assumption.
44    pub fn from_material(material: &Material, plane_stress: bool) -> Self {
45        Self {
46            youngs_modulus: material.youngs_modulus,
47            poissons_ratio: material.poissons_ratio,
48            shear_modulus: material.shear_modulus,
49            density: material.density,
50            plane_stress,
51            shear_correction: 5.0 / 6.0,
52        }
53    }
54
55    /// Create for plane strain.
56    pub fn plane_strain(material: &Material) -> Self {
57        Self::from_material(material, false)
58    }
59
60    /// Create for plane stress.
61    pub fn plane_stress(material: &Material) -> Self {
62        Self::from_material(material, true)
63    }
64
65    /// Constitutive matrix D for plane stress.
66    pub fn d_matrix_plane_stress(&self) -> [[f64; 3]; 3] {
67        let e = self.youngs_modulus;
68        let nu = self.poissons_ratio;
69        let factor = e / (1.0 - nu * nu);
70        [
71            [factor, factor * nu, 0.0],
72            [factor * nu, factor, 0.0],
73            [0.0, 0.0, factor * (1.0 - nu) / 2.0],
74        ]
75    }
76
77    /// Constitutive matrix D for plane strain.
78    pub fn d_matrix_plane_strain(&self) -> [[f64; 3]; 3] {
79        let e = self.youngs_modulus;
80        let nu = self.poissons_ratio;
81        let factor = e / ((1.0 + nu) * (1.0 - 2.0 * nu));
82        [
83            [factor * (1.0 - nu), factor * nu, 0.0],
84            [factor * nu, factor * (1.0 - nu), 0.0],
85            [0.0, 0.0, factor * (1.0 - 2.0 * nu) / 2.0],
86        ]
87    }
88
89    /// Get constitutive matrix D (3x3 for 2D).
90    pub fn d_matrix(&self) -> [[f64; 3]; 3] {
91        if self.plane_stress {
92            self.d_matrix_plane_stress()
93        } else {
94            self.d_matrix_plane_strain()
95        }
96    }
97}
98
99/// Stress/strain result at a point.
100#[derive(Debug, Clone, Copy)]
101pub struct StressResult {
102    /// Normal stress in x direction
103    pub sigma_x: f64,
104    /// Normal stress in y direction
105    pub sigma_y: f64,
106    /// Shear stress xy
107    pub tau_xy: f64,
108    /// Strain in x direction
109    pub epsilon_x: f64,
110    /// Strain in y direction
111    pub epsilon_y: f64,
112    /// Shear strain xy
113    pub gamma_xy: f64,
114    /// Von Mises stress
115    pub von_mises: f64,
116    /// Principal stress 1 (major)
117    pub sigma_1: f64,
118    /// Principal stress 2 (minor)
119    pub sigma_2: f64,
120    /// Principal angle (radians)
121    pub principal_angle: f64,
122}
123
124impl StressResult {
125    /// Create from stress components.
126    pub fn from_stress(sigma_x: f64, sigma_y: f64, tau_xy: f64) -> Self {
127        let sigma_avg = (sigma_x + sigma_y) * 0.5;
128        let r = ((sigma_x - sigma_y) * 0.5).powi(2) + tau_xy * tau_xy;
129        let r = r.sqrt();
130        let sigma_1 = sigma_avg + r;
131        let sigma_2 = sigma_avg - r;
132        let principal_angle = 0.5 * (2.0 * tau_xy).atan2(sigma_x - sigma_y);
133        let von_mises =
134            (sigma_x * sigma_x - sigma_x * sigma_y + sigma_y * sigma_y + 3.0 * tau_xy * tau_xy)
135                .sqrt();
136
137        Self {
138            sigma_x,
139            sigma_y,
140            tau_xy,
141            epsilon_x: 0.0,
142            epsilon_y: 0.0,
143            gamma_xy: 0.0,
144            von_mises,
145            sigma_1,
146            sigma_2,
147            principal_angle,
148        }
149    }
150
151    /// Create from strain components using material.
152    pub fn from_strain(
153        epsilon_x: f64,
154        epsilon_y: f64,
155        gamma_xy: f64,
156        props: &MaterialProps,
157    ) -> Self {
158        let d = props.d_matrix();
159        let sigma_x = d[0][0] * epsilon_x + d[0][1] * epsilon_y + d[0][2] * gamma_xy;
160        let sigma_y = d[1][0] * epsilon_x + d[1][1] * epsilon_y + d[1][2] * gamma_xy;
161        let tau_xy = d[2][0] * epsilon_x + d[2][1] * epsilon_y + d[2][2] * gamma_xy;
162
163        let mut result = Self::from_stress(sigma_x, sigma_y, tau_xy);
164        result.epsilon_x = epsilon_x;
165        result.epsilon_y = epsilon_y;
166        result.gamma_xy = gamma_xy;
167        result
168    }
169}
170
171/// FEM model containing mesh, materials, boundary conditions, and loads.
172#[derive(Debug, Clone)]
173pub struct FemModel {
174    pub mesh: Mesh,
175    pub materials: Vec<MaterialProps>,
176    /// Boundary conditions: (node_index, dof, value) where dof: 0=ux, 1=uy
177    pub dirichlet_bcs: Vec<(usize, usize, f64)>,
178    /// Nodal forces: (node_index, dof, value)
179    pub nodal_forces: Vec<(usize, usize, f64)>,
180    /// Distributed loads on elements: (element_index, load_vector)
181    pub element_loads: Vec<(usize, [f64; 3])>, // body force per unit area
182    /// Problem type
183    pub problem_type: ProblemType,
184}
185
186#[derive(Debug, Clone, Copy, PartialEq, Eq)]
187pub enum ProblemType {
188    PlaneStress,
189    PlaneStrain,
190    Axisymmetric,
191}
192
193impl FemModel {
194    /// Create a new FEM model from a mesh.
195    pub fn new(mesh: Mesh) -> Self {
196        Self {
197            mesh,
198            materials: Vec::new(),
199            dirichlet_bcs: Vec::new(),
200            nodal_forces: Vec::new(),
201            element_loads: Vec::new(),
202            problem_type: ProblemType::PlaneStress,
203        }
204    }
205
206    /// Add a material.
207    pub fn add_material(&mut self, props: MaterialProps) -> usize {
208        self.materials.push(props);
209        self.materials.len() - 1
210    }
211
212    /// Add Dirichlet boundary condition.
213    pub fn add_dirichlet_bc(&mut self, node: usize, dof: usize, value: f64) {
214        self.dirichlet_bcs.push((node, dof, value));
215    }
216
217    /// Fix a node completely (both DOFs).
218    pub fn fix_node(&mut self, node: usize) {
219        self.add_dirichlet_bc(node, 0, 0.0);
220        self.add_dirichlet_bc(node, 1, 0.0);
221    }
222
223    /// Add nodal force.
224    pub fn add_nodal_force(&mut self, node: usize, dof: usize, value: f64) {
225        self.nodal_forces.push((node, dof, value));
226    }
227
228    /// Add body force (gravity, etc.) to all elements.
229    pub fn add_body_force(&mut self, fx: f64, fy: f64) {
230        for i in 0..self.mesh.n_elements() {
231            self.element_loads.push((i, [fx, fy, 0.0]));
232        }
233    }
234
235    /// Set problem type.
236    pub fn set_problem_type(&mut self, ptype: ProblemType) {
237        self.problem_type = ptype;
238    }
239}
240
241/// FEM solver for linear static analysis.
242#[derive(Debug)]
243pub struct FemSolver {
244    /// Global stiffness matrix (sparse CSR format)
245    pub k_global: SprsMatrix,
246    /// Global force vector
247    pub f_global: Vec<f64>,
248    /// Displacement solution
249    pub u_global: Vec<f64>,
250    /// Number of DOFs
251    pub n_dof: usize,
252    /// DOF mapping: (node, dof) -> global_dof_index
253    pub dof_map: HashMap<(usize, usize), usize>,
254    /// Fixed DOFs
255    pub fixed_dofs: Vec<bool>,
256    /// Original (unmodified) global stiffness matrix, before any Dirichlet
257    /// boundary conditions are applied. Used to compute reaction forces as
258    /// `K_original * u`; `k_global` is mutated in place during assembly.
259    k_original: SprsMatrix,
260}
261
262impl FemSolver {
263    /// Create solver from FEM model.
264    pub fn from_model(model: &FemModel) -> Result<Self, FemError> {
265        let n_nodes = model.mesh.n_nodes();
266        let n_dof = n_nodes * 2; // 2 DOFs per node (ux, uy)
267
268        // Build DOF map
269        let mut dof_map = HashMap::new();
270        let mut dof_index = 0;
271        for node in 0..n_nodes {
272            for dof in 0..2 {
273                dof_map.insert((node, dof), dof_index);
274                dof_index += 1;
275            }
276        }
277
278        // Fixed DOFs
279        let mut fixed_dofs = vec![false; n_dof];
280        for (node, dof, _) in &model.dirichlet_bcs {
281            if let Some(&idx) = dof_map.get(&(*node, *dof)) {
282                fixed_dofs[idx] = true;
283            }
284        }
285
286        // Build sparse stiffness matrix
287        let mut k_global = SprsMatrix::new(n_dof);
288
289        // Assemble element stiffness matrices
290        for (elem_idx, element) in model.mesh.elements.iter().enumerate() {
291            let mat_idx = if elem_idx < model.mesh.element_materials.len() {
292                model.mesh.element_materials[elem_idx]
293            } else {
294                0
295            };
296            let props = &model.materials[mat_idx];
297
298            let ke = element_stiffness_tri3(&model.mesh, element, props);
299
300            // Assemble into global matrix
301            let mut dof_indices = [0; 6];
302            for (i, &node) in element.iter().enumerate() {
303                dof_indices[2 * i] = dof_map[&(node, 0)];
304                dof_indices[2 * i + 1] = dof_map[&(node, 1)];
305            }
306
307            for i in 0..6 {
308                for j in 0..6 {
309                    k_global.add(dof_indices[i], dof_indices[j], ke[i][j]);
310                }
311            }
312        }
313
314        // Build global force vector
315        let mut f_global = vec![0.0; n_dof];
316
317        // Nodal forces
318        for (node, dof, value) in &model.nodal_forces {
319            if let Some(&idx) = dof_map.get(&(*node, *dof)) {
320                f_global[idx] += value;
321            }
322        }
323
324        // Element body forces (consistent load vector)
325        for (elem_idx, load) in &model.element_loads {
326            let element = model.mesh.elements[*elem_idx];
327            let fe = element_body_force_tri3(&model.mesh, &element, load);
328
329            let mut dof_indices = [0; 6];
330            for (i, &node) in element.iter().enumerate() {
331                dof_indices[2 * i] = dof_map[&(node, 0)];
332                dof_indices[2 * i + 1] = dof_map[&(node, 1)];
333            }
334
335            for i in 0..6 {
336                f_global[dof_indices[i]] += fe[i];
337            }
338        }
339
340        // Apply Dirichlet BCs to force vector
341        for (node, dof, value) in &model.dirichlet_bcs {
342            if let Some(&idx) = dof_map.get(&(*node, *dof)) {
343                f_global[idx] = *value;
344            }
345        }
346
347        let mut k_original = k_global.clone();
348        k_original.finalize();
349
350        Ok(Self {
351            k_global,
352            f_global,
353            u_global: vec![0.0; n_dof],
354            n_dof,
355            dof_map,
356            fixed_dofs,
357            k_original,
358        })
359    }
360
361    /// Solve the linear system K*u = F.
362    pub fn solve(&mut self) -> Result<&[f64], FemError> {
363        // Apply boundary conditions to stiffness matrix
364        self.apply_boundary_conditions();
365
366        // Solve using Cholesky decomposition (for symmetric positive definite)
367        self.u_global = self
368            .k_global
369            .solve_cholesky(&self.f_global)
370            .ok_or(FemError::SingularMatrix)?;
371
372        Ok(&self.u_global)
373    }
374
375    /// Apply Dirichlet boundary conditions to stiffness matrix.
376    fn apply_boundary_conditions(&mut self) {
377        for i in 0..self.n_dof {
378            if self.fixed_dofs[i] {
379                // Zero out row and column, set diagonal to 1
380                self.k_global.zero_row_col(i);
381                self.k_global.set(i, i, 1.0);
382            }
383        }
384    }
385
386    /// Get displacement at a node.
387    pub fn displacement(&self, node: usize) -> Point {
388        let ux = self.u_global[self.dof_map[&(node, 0)]];
389        let uy = self.u_global[self.dof_map[&(node, 1)]];
390        Point::new(ux, uy)
391    }
392
393    /// Get stress at element centroid.
394    pub fn element_stress(&self, model: &FemModel, elem_idx: usize) -> StressResult {
395        let element = model.mesh.elements[elem_idx];
396        let props = &model.materials[model.mesh.element_materials[elem_idx]];
397
398        // Get element displacements
399        let mut u_elem = [0.0; 6];
400        for (i, &node) in element.iter().enumerate() {
401            u_elem[2 * i] = self.u_global[self.dof_map[&(node, 0)]];
402            u_elem[2 * i + 1] = self.u_global[self.dof_map[&(node, 1)]];
403        }
404
405        // Compute B matrix (strain-displacement)
406        let b = strain_displacement_matrix_tri3(&model.mesh, &element);
407
408        // Strain = B * u
409        let mut strain = [0.0; 3];
410        for i in 0..3 {
411            for j in 0..6 {
412                strain[i] += b[i][j] * u_elem[j];
413            }
414        }
415
416        // Stress = D * strain
417        let d = props.d_matrix();
418        let mut stress = [0.0; 3];
419        for i in 0..3 {
420            for j in 0..3 {
421                stress[i] += d[i][j] * strain[j];
422            }
423        }
424
425        StressResult::from_strain(strain[0], strain[1], strain[2], props)
426    }
427
428    /// Get stress at all element centroids.
429    pub fn all_element_stresses(&self, model: &FemModel) -> Vec<StressResult> {
430        (0..model.mesh.n_elements())
431            .map(|i| self.element_stress(model, i))
432            .collect()
433    }
434
435    /// Get nodal stresses by averaging from elements.
436    pub fn nodal_stresses(&self, model: &FemModel) -> Vec<StressResult> {
437        let n_nodes = model.mesh.n_nodes();
438        let mut stress_sum = vec![StressResult::from_stress(0.0, 0.0, 0.0); n_nodes];
439        let mut stress_count = vec![0; n_nodes];
440
441        for elem_idx in 0..model.mesh.n_elements() {
442            let stress = self.element_stress(model, elem_idx);
443            let element = model.mesh.elements[elem_idx];
444            for &node in &element {
445                stress_sum[node].sigma_x += stress.sigma_x;
446                stress_sum[node].sigma_y += stress.sigma_y;
447                stress_sum[node].tau_xy += stress.tau_xy;
448                stress_sum[node].von_mises += stress.von_mises;
449                stress_sum[node].sigma_1 += stress.sigma_1;
450                stress_sum[node].sigma_2 += stress.sigma_2;
451                stress_count[node] += 1;
452            }
453        }
454
455        let mut nodal_stresses = Vec::with_capacity(n_nodes);
456        for i in 0..n_nodes {
457            if stress_count[i] > 0 {
458                let c = stress_count[i] as f64;
459                let mut s = stress_sum[i];
460                s.sigma_x /= c;
461                s.sigma_y /= c;
462                s.tau_xy /= c;
463                s.von_mises /= c;
464                s.sigma_1 /= c;
465                s.sigma_2 /= c;
466                nodal_stresses.push(s);
467            } else {
468                nodal_stresses.push(StressResult::from_stress(0.0, 0.0, 0.0));
469            }
470        }
471        nodal_stresses
472    }
473
474    /// Compute reaction forces at fixed DOFs.
475    ///
476    /// Reactions are `K_original * u` evaluated at the fixed DOFs, using the
477    /// unmodified stiffness matrix (before Dirichlet conditions were applied)
478    /// so that the true support forces are recovered rather than the prescribed
479    /// displacement values.
480    pub fn reactions(&self, model: &FemModel) -> Vec<(usize, usize, f64)> {
481        let mut reactions = Vec::new();
482        for (node, dof, _) in &model.dirichlet_bcs {
483            if let Some(&idx) = self.dof_map.get(&(*node, *dof)) {
484                // Reaction = K_original * u
485                let mut reaction = 0.0;
486                for j in 0..self.n_dof {
487                    reaction += self.k_original.get(idx, j) * self.u_global[j];
488                }
489                reactions.push((*node, *dof, reaction));
490            }
491        }
492        reactions
493    }
494}
495
496/// Sparse matrix in CSR format (simplified for small problems).
497#[derive(Debug, Clone)]
498pub struct SprsMatrix {
499    n: usize,
500    /// Row pointers
501    row_ptr: Vec<usize>,
502    /// Column indices
503    col_idx: Vec<usize>,
504    /// Values
505    values: Vec<f64>,
506    /// Temporary storage for assembly (triplet format)
507    triplets: Vec<(usize, usize, f64)>,
508    /// Whether matrix is finalized
509    finalized: bool,
510}
511
512impl SprsMatrix {
513    pub fn new(n: usize) -> Self {
514        Self {
515            n,
516            row_ptr: vec![0; n + 1],
517            col_idx: Vec::new(),
518            values: Vec::new(),
519            triplets: Vec::new(),
520            finalized: false,
521        }
522    }
523
524    /// Add value to matrix (accumulates).
525    pub fn add(&mut self, row: usize, col: usize, value: f64) {
526        if value.abs() < 1e-15 {
527            return;
528        }
529        self.triplets.push((row, col, value));
530        self.finalized = false;
531    }
532
533    /// Set value (replaces existing).
534    pub fn set(&mut self, row: usize, col: usize, value: f64) {
535        self.finalize();
536        for i in self.row_ptr[row]..self.row_ptr[row + 1] {
537            if self.col_idx[i] == col {
538                self.values[i] = value;
539                return;
540            }
541        }
542        // Entry doesn't exist — need to insert into CSR
543        let pos = self.row_ptr[row + 1];
544        self.col_idx.insert(pos, col);
545        self.values.insert(pos, value);
546        for r in (row + 1)..=self.n {
547            self.row_ptr[r] += 1;
548        }
549    }
550
551    /// Get value.
552    pub fn get(&self, row: usize, col: usize) -> f64 {
553        if !self.finalized {
554            return 0.0; // Not valid until finalized
555        }
556        for i in self.row_ptr[row]..self.row_ptr[row + 1] {
557            if self.col_idx[i] == col {
558                return self.values[i];
559            }
560        }
561        0.0
562    }
563
564    /// Finalize matrix (convert to CSR).
565    fn finalize(&mut self) {
566        if self.finalized {
567            return;
568        }
569        // Sort triplets
570        self.triplets.sort_by_key(|&(r, c, _)| (r, c));
571
572        // Combine duplicates
573        let mut combined: Vec<(usize, usize, f64)> = Vec::new();
574        for (r, c, v) in self.triplets.drain(..) {
575            if let Some(last) = combined.last_mut() {
576                if last.0 == r && last.1 == c {
577                    last.2 += v;
578                } else {
579                    combined.push((r, c, v));
580                }
581            } else {
582                combined.push((r, c, v));
583            }
584        }
585
586        // Build CSR
587        self.row_ptr.fill(0);
588        for (r, _, _) in &combined {
589            self.row_ptr[*r + 1] += 1;
590        }
591        for i in 1..=self.n {
592            self.row_ptr[i] += self.row_ptr[i - 1];
593        }
594
595        self.col_idx = Vec::with_capacity(combined.len());
596        self.values = Vec::with_capacity(combined.len());
597        for (_, c, v) in combined {
598            self.col_idx.push(c);
599            self.values.push(v);
600        }
601
602        self.finalized = true;
603    }
604
605    /// Zero out row and column.
606    pub fn zero_row_col(&mut self, idx: usize) {
607        self.finalize();
608        let row_start = self.row_ptr[idx];
609        let row_end = self.row_ptr[idx + 1];
610        for i in row_start..row_end {
611            self.values[i] = 0.0;
612        }
613        // Also zero column entries
614        for r in 0..self.n {
615            let rs = self.row_ptr[r];
616            let re = self.row_ptr[r + 1];
617            for i in rs..re {
618                if self.col_idx[i] == idx {
619                    self.values[i] = 0.0;
620                }
621            }
622        }
623    }
624
625    /// Solve using Cholesky decomposition (simplified - uses dense for small systems).
626    pub fn solve_cholesky(&mut self, rhs: &[f64]) -> Option<Vec<f64>> {
627        self.finalize();
628
629        // For small systems, convert to dense and use Cholesky
630        if self.n <= 500 {
631            let mut a = vec![vec![0.0; self.n]; self.n];
632            for i in 0..self.n {
633                for j_idx in self.row_ptr[i]..self.row_ptr[i + 1] {
634                    let j = self.col_idx[j_idx];
635                    a[i][j] = self.values[j_idx];
636                }
637            }
638
639            // Cholesky decomposition
640            let mut l = vec![vec![0.0; self.n]; self.n];
641            for i in 0..self.n {
642                for j in 0..=i {
643                    let mut sum = a[i][j];
644                    for k in 0..j {
645                        sum -= l[i][k] * l[j][k];
646                    }
647                    if i == j {
648                        if sum <= 1e-12 {
649                            return None; // Not positive definite
650                        }
651                        l[i][j] = sum.sqrt();
652                    } else {
653                        l[i][j] = sum / l[j][j];
654                    }
655                }
656            }
657
658            // Forward substitution L*y = b
659            let mut y = vec![0.0; self.n];
660            for i in 0..self.n {
661                let mut sum = rhs[i];
662                for k in 0..i {
663                    sum -= l[i][k] * y[k];
664                }
665                y[i] = sum / l[i][i];
666            }
667
668            // Back substitution L^T*x = y
669            let mut x = vec![0.0; self.n];
670            for i in (0..self.n).rev() {
671                let mut sum = y[i];
672                for k in i + 1..self.n {
673                    sum -= l[k][i] * x[k];
674                }
675                x[i] = sum / l[i][i];
676            }
677
678            Some(x)
679        } else {
680            // For larger systems, would use iterative solver
681            None
682        }
683    }
684}
685
686/// Element stiffness matrix for 3-node triangle (CST).
687pub fn element_stiffness_tri3(
688    mesh: &Mesh,
689    element: &[usize; 3],
690    props: &MaterialProps,
691) -> [[f64; 6]; 6] {
692    let p1 = mesh.nodes[element[0]];
693    let p2 = mesh.nodes[element[1]];
694    let p3 = mesh.nodes[element[2]];
695
696    // Area
697    let area = 0.5 * ((p2.x - p1.x) * (p3.y - p1.y) - (p3.x - p1.x) * (p2.y - p1.y)).abs();
698
699    // B matrix (3x6)
700    let b = strain_displacement_matrix_tri3(mesh, element);
701
702    // D matrix
703    let d = props.d_matrix();
704
705    // ke = B^T * D * B * area * thickness (thickness = 1 for plane stress/strain)
706    let thickness = 1.0;
707    let mut ke = [[0.0; 6]; 6];
708
709    for i in 0..6 {
710        for j in 0..6 {
711            let mut sum = 0.0;
712            for k in 0..3 {
713                for l in 0..3 {
714                    sum += b[k][i] * d[k][l] * b[l][j];
715                }
716            }
717            ke[i][j] = sum * area * thickness;
718        }
719    }
720
721    ke
722}
723
724/// Strain-displacement matrix B for 3-node triangle (3x6).
725pub fn strain_displacement_matrix_tri3(mesh: &Mesh, element: &[usize; 3]) -> [[f64; 6]; 3] {
726    let p1 = mesh.nodes[element[0]];
727    let p2 = mesh.nodes[element[1]];
728    let p3 = mesh.nodes[element[2]];
729
730    let area2 = (p2.x - p1.x) * (p3.y - p1.y) - (p3.x - p1.x) * (p2.y - p1.y);
731    let _area = 0.5 * area2.abs();
732
733    // Shape function derivatives (constant for linear triangle)
734    let b1 = (p2.y - p3.y) / area2;
735    let c1 = (p3.x - p2.x) / area2;
736    let b2 = (p3.y - p1.y) / area2;
737    let c2 = (p1.x - p3.x) / area2;
738    let b3 = (p1.y - p2.y) / area2;
739    let c3 = (p2.x - p1.x) / area2;
740
741    [
742        [b1, 0.0, b2, 0.0, b3, 0.0],
743        [0.0, c1, 0.0, c2, 0.0, c3],
744        [c1, b1, c2, b2, c3, b3],
745    ]
746}
747
748/// Consistent body force vector for 3-node triangle.
749pub fn element_body_force_tri3(
750    mesh: &Mesh,
751    element: &[usize; 3],
752    body_force: &[f64; 3], // [fx, fy, fz] per unit volume
753) -> [f64; 6] {
754    let p1 = mesh.nodes[element[0]];
755    let p2 = mesh.nodes[element[1]];
756    let p3 = mesh.nodes[element[2]];
757
758    let area = 0.5 * ((p2.x - p1.x) * (p3.y - p1.y) - (p3.x - p1.x) * (p2.y - p1.y)).abs();
759    let thickness = 1.0;
760    let volume = area * thickness;
761
762    // Consistent load: N^T * b * volume, N = [1/3, 1/3, 1/3] for centroid
763    let factor = volume / 3.0;
764    [
765        body_force[0] * factor,
766        body_force[1] * factor,
767        body_force[0] * factor,
768        body_force[1] * factor,
769        body_force[0] * factor,
770        body_force[1] * factor,
771    ]
772}
773
774/// High-level function to solve a section under load.
775pub fn analyze_section(
776    section: &Section,
777    material: &Material,
778    params: MeshParams,
779    loads: &[LoadCase],
780) -> Result<AnalysisResults, FemError> {
781    let mesh = crate::mesh::mesh_section(section, params);
782
783    let mut model = FemModel::new(mesh);
784    let mat_props = MaterialProps::from_material(material, true); // plane stress
785    model.add_material(mat_props);
786    model.set_problem_type(ProblemType::PlaneStress);
787
788    // Apply loads
789    for load in loads {
790        match load {
791            LoadCase::NodalForce { node, fx, fy } => {
792                model.add_nodal_force(*node, 0, *fx);
793                model.add_nodal_force(*node, 1, *fy);
794            }
795            LoadCase::BodyForce { fx, fy } => {
796                model.add_body_force(*fx, *fy);
797            }
798            LoadCase::FixedNode { node } => {
799                model.fix_node(*node);
800            }
801            LoadCase::RollerX { node } => {
802                model.add_dirichlet_bc(*node, 0, 0.0);
803            }
804            LoadCase::RollerY { node } => {
805                model.add_dirichlet_bc(*node, 1, 0.0);
806            }
807        }
808    }
809
810    let mut solver = FemSolver::from_model(&model)?;
811    solver.solve()?;
812
813    Ok(AnalysisResults {
814        displacements: (0..model.mesh.n_nodes())
815            .map(|i| solver.displacement(i))
816            .collect(),
817        element_stresses: solver.all_element_stresses(&model),
818        nodal_stresses: solver.nodal_stresses(&model),
819        reactions: solver.reactions(&model),
820    })
821}
822
823/// Load cases for section analysis.
824#[derive(Debug, Clone)]
825pub enum LoadCase {
826    NodalForce { node: usize, fx: f64, fy: f64 },
827    BodyForce { fx: f64, fy: f64 },
828    FixedNode { node: usize },
829    RollerX { node: usize },
830    RollerY { node: usize },
831}
832
833/// Analysis results.
834#[derive(Debug, Clone)]
835pub struct AnalysisResults {
836    pub displacements: Vec<Point>,
837    pub element_stresses: Vec<StressResult>,
838    pub nodal_stresses: Vec<StressResult>,
839    pub reactions: Vec<(usize, usize, f64)>,
840}
841
842/// FEM errors.
843#[derive(Debug, Clone, PartialEq)]
844pub enum FemError {
845    SingularMatrix,
846    InvalidMesh,
847    MaterialNotFound,
848    ConvergenceFailed,
849    DegenerateElement,
850    InvalidElementOrientation,
851}
852
853impl std::fmt::Display for FemError {
854    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
855        match self {
856            FemError::SingularMatrix => write!(f, "Singular stiffness matrix"),
857            FemError::InvalidMesh => write!(f, "Invalid mesh"),
858            FemError::MaterialNotFound => write!(f, "Material not found"),
859            FemError::ConvergenceFailed => write!(f, "Solver did not converge"),
860            FemError::DegenerateElement => {
861                write!(f, "Degenerate element (zero or negative Jacobian)")
862            }
863            FemError::InvalidElementOrientation => write!(
864                f,
865                "Invalid element orientation (negative Jacobian, CW winding)"
866            ),
867        }
868    }
869}
870
871impl std::error::Error for FemError {}
872
873#[cfg(test)]
874mod tests {
875    use super::*;
876    use crate::geometry::Point;
877    use crate::material::presets::STEEL_S355;
878
879    #[test]
880    fn material_props_d_matrix() {
881        let props = MaterialProps::plane_stress(&STEEL_S355);
882        let d = props.d_matrix();
883        assert!(d[0][0] > 0.0);
884        assert!(d[1][1] > 0.0);
885        assert!(d[2][2] > 0.0);
886    }
887
888    #[test]
889    fn stress_result_von_mises() {
890        let stress = StressResult::from_stress(100.0, 50.0, 30.0);
891        let expected =
892            (100.0_f64.powi(2) - 100.0 * 50.0 + 50.0_f64.powi(2) + 3.0 * 30.0_f64.powi(2)).sqrt();
893        assert!((stress.von_mises - expected).abs() < 1e-6);
894    }
895
896    #[test]
897    fn tri3_stiffness() {
898        let mut mesh = Mesh::new();
899        mesh.nodes = vec![
900            Point::new(0.0, 0.0),
901            Point::new(1.0, 0.0),
902            Point::new(0.0, 1.0),
903        ];
904        mesh.elements = vec![[0, 1, 2]];
905
906        let props = MaterialProps::plane_stress(&STEEL_S355);
907        let ke = element_stiffness_tri3(&mesh, &[0, 1, 2], &props);
908
909        // Stiffness matrix should be symmetric
910        for i in 0..6 {
911            for j in 0..6 {
912                assert!((ke[i][j] - ke[j][i]).abs() < 1e-10);
913            }
914        }
915        // Diagonal should be positive
916        for i in 0..6 {
917            assert!(ke[i][i] > 0.0);
918        }
919    }
920
921    #[test]
922    fn simple_cantilever() {
923        // Simple cantilever beam: fixed at x=0, force at tip
924        let mut mesh = Mesh::new();
925        mesh.nodes = vec![
926            Point::new(0.0, 0.0), // 0 - fixed
927            Point::new(1.0, 0.0), // 1
928            Point::new(0.0, 0.1), // 2 - fixed
929            Point::new(1.0, 0.1), // 3 - tip load
930        ];
931        mesh.elements = vec![[0, 1, 2], [1, 3, 2]];
932
933        let mut model = FemModel::new(mesh);
934        let props = MaterialProps::plane_stress(&STEEL_S355);
935        model.add_material(props);
936
937        // Fix left end
938        model.fix_node(0);
939        model.fix_node(2);
940
941        // Apply vertical force at tip
942        model.add_nodal_force(3, 1, -1000.0);
943
944        let mut solver = FemSolver::from_model(&model).unwrap();
945        solver.solve().unwrap();
946
947        // Tip should deflect downward
948        let disp = solver.displacement(3);
949        assert!(disp.y < 0.0);
950    }
951
952    #[test]
953    fn reactions_balance_applied_load() {
954        // A single downward tip load on a cantilever must be balanced by
955        // upward reactions at the fixed support. This guards against the
956        // regression where reactions were computed from the already
957        // boundary-condition-modified stiffness matrix (returning ~0).
958        let mut mesh = Mesh::new();
959        mesh.nodes = vec![
960            Point::new(0.0, 0.0), // 0 - fixed
961            Point::new(1.0, 0.0), // 1
962            Point::new(0.0, 0.1), // 2 - fixed
963            Point::new(1.0, 0.1), // 3 - tip load
964        ];
965        mesh.elements = vec![[0, 1, 2], [1, 3, 2]];
966
967        let mut model = FemModel::new(mesh);
968        let props = MaterialProps::plane_stress(&STEEL_S355);
969        model.add_material(props);
970
971        model.fix_node(0);
972        model.fix_node(2);
973        model.add_nodal_force(3, 1, -1000.0);
974
975        let mut solver = FemSolver::from_model(&model).unwrap();
976        solver.solve().unwrap();
977
978        let reactions = solver.reactions(&model);
979
980        // Sum the vertical (dof 1) reactions at the two fixed nodes.
981        let mut vertical_reaction = 0.0;
982        for (node, dof, value) in &reactions {
983            assert!(node == &0 || node == &2, "reactions only at fixed nodes");
984            if *dof == 1 {
985                vertical_reaction += value;
986            }
987        }
988
989        // The fixed support must push up to balance the -1000 downward load.
990        assert!(
991            (vertical_reaction - 1000.0).abs() < 1e-6,
992            "vertical reactions should balance the applied load, got {vertical_reaction}"
993        );
994    }
995}