Skip to main content

section_properties/
stress.rs

1//! Cross-section stress analysis.
2//!
3//! Mirrors Python `sectionproperties.post.stress_post.StressPost`:
4//! computes stress distributions from design actions (N, Vx, Vy, Mxx, Myy, M11, M22, Mzz)
5//! using analytical formulas (no FEM mesh required).
6
7use crate::geometry::Point;
8use crate::material::Material;
9use crate::section::Section;
10use crate::section_properties::SectionProperties;
11
12/// Design actions applied to a cross-section.
13#[derive(Debug, Clone, Copy)]
14pub struct SectionLoads {
15    /// Axial force `N` (positive = tension)
16    pub n: f64,
17    /// Shear force in x-direction `N`
18    pub vx: f64,
19    /// Shear force in y-direction `N`
20    pub vy: f64,
21    /// Bending moment about centroidal x-axis [N·m]
22    pub mxx: f64,
23    /// Bending moment about centroidal y-axis [N·m]
24    pub myy: f64,
25    /// Bending moment about principal 11-axis [N·m]
26    pub m11: f64,
27    /// Bending moment about principal 22-axis [N·m]
28    pub m22: f64,
29    /// Torsion moment about z-axis [N·m]
30    pub mzz: f64,
31}
32
33impl SectionLoads {
34    /// Create a zero load case.
35    pub fn zero() -> Self {
36        Self {
37            n: 0.0,
38            vx: 0.0,
39            vy: 0.0,
40            mxx: 0.0,
41            myy: 0.0,
42            m11: 0.0,
43            m22: 0.0,
44            mzz: 0.0,
45        }
46    }
47
48    /// Pure axial load.
49    pub fn axial(n: f64) -> Self {
50        Self { n, ..Self::zero() }
51    }
52
53    /// Pure bending about x-axis.
54    pub fn bending_x(mxx: f64) -> Self {
55        Self {
56            mxx,
57            ..Self::zero()
58        }
59    }
60
61    /// Pure bending about y-axis.
62    pub fn bending_y(myy: f64) -> Self {
63        Self {
64            myy,
65            ..Self::zero()
66        }
67    }
68
69    /// Pure shear in y-direction.
70    pub fn shear_y(vy: f64) -> Self {
71        Self { vy, ..Self::zero() }
72    }
73
74    /// Pure torsion.
75    pub fn torsion(mzz: f64) -> Self {
76        Self {
77            mzz,
78            ..Self::zero()
79        }
80    }
81}
82
83impl Default for SectionLoads {
84    fn default() -> Self {
85        Self::zero()
86    }
87}
88
89/// Stress state at a point in the cross-section, with breakdown by load component.
90#[derive(Debug, Clone, Copy)]
91pub struct StressAtPoint {
92    /// x-coordinate `m`
93    pub x: f64,
94    /// y-coordinate `m`
95    pub y: f64,
96    /// Normal stress σ_z from axial force N `Pa`
97    pub sig_zz_n: f64,
98    /// Normal stress σ_z from Mxx `Pa`
99    pub sig_zz_mxx: f64,
100    /// Normal stress σ_z from Myy `Pa`
101    pub sig_zz_myy: f64,
102    /// Normal stress σ_z from M11 `Pa`
103    pub sig_zz_m11: f64,
104    /// Normal stress σ_z from M22 `Pa`
105    pub sig_zz_m22: f64,
106    /// Shear stress τ_xz from Vx `Pa`
107    pub sig_zx_vx: f64,
108    /// Shear stress τ_yz from Vx `Pa`
109    pub sig_zy_vx: f64,
110    /// Shear stress τ_xz from Vy `Pa`
111    pub sig_zx_vy: f64,
112    /// Shear stress τ_yz from Vy `Pa`
113    pub sig_zy_vy: f64,
114    /// Shear stress τ_xz from Mzz (torsion) `Pa`
115    pub sig_zx_mzz: f64,
116    /// Shear stress τ_yz from Mzz (torsion) `Pa`
117    pub sig_zy_mzz: f64,
118    /// Combined normal stress from all bending moments `Pa`
119    pub sig_zz_m: f64,
120    /// Resultant shear stress from torsion Mzz `Pa`
121    pub sig_zxy_mzz: f64,
122    /// Resultant shear stress from Vx `Pa`
123    pub sig_zxy_vx: f64,
124    /// Resultant shear stress from Vy `Pa`
125    pub sig_zxy_vy: f64,
126    /// Combined shear stress τ_xz from all shear forces `Pa`
127    pub sig_zx_v: f64,
128    /// Combined shear stress τ_yz from all shear forces `Pa`
129    pub sig_zy_v: f64,
130    /// Resultant shear stress from all shear forces `Pa`
131    pub sig_zxy_v: f64,
132    /// Combined normal stress σ_z `Pa`
133    pub sigma_z: f64,
134    /// Combined shear stress τ_xz `Pa`
135    pub tau_xz: f64,
136    /// Combined shear stress τ_yz `Pa`
137    pub tau_yz: f64,
138    /// Resultant shear stress τ_zxy `Pa`
139    pub tau_zxy: f64,
140    /// von Mises stress `Pa`
141    pub von_mises: f64,
142    /// Major principal stress `Pa`
143    pub sigma_1: f64,
144    /// Minor principal stress `Pa`
145    pub sigma_2: f64,
146}
147
148/// Overall stress analysis results for a cross-section.
149#[derive(Debug, Clone)]
150pub struct StressAnalysisResult {
151    /// Stress at each evaluated point (section boundary vertices).
152    pub point_stresses: Vec<StressAtPoint>,
153    /// Maximum normal stress σ_z `Pa`
154    pub max_sigma_z: f64,
155    /// Minimum normal stress σ_z `Pa`
156    pub min_sigma_z: f64,
157    /// Maximum von Mises stress `Pa`
158    pub max_von_mises: f64,
159    /// Maximum shear stress `Pa`
160    pub max_tau: f64,
161    /// Location of max von Mises (x, y)
162    pub max_vm_location: Point,
163    /// Applied loads
164    pub loads: SectionLoads,
165    /// Section area `m²`
166    pub area: f64,
167}
168
169/// Analytical stress analysis for a cross-section.
170///
171/// Computes stress distributions from design actions using closed-form expressions:
172/// - Normal stress: σ_z = N/A + Mxx·y/Ixx − Myy·x/Iyy + M11·y22/I11 − M22·x11/I22
173/// - Shear stress: τ ≈ V/A_shear (simplified uniform distribution)
174/// - Torsional stress: τ_t ≈ Mzz·t/J (thin-walled approximation)
175pub struct StressAnalysis {
176    section: Section,
177    material: Material,
178    props: SectionProperties,
179}
180
181impl StressAnalysis {
182    /// Create a new stress analysis for a section with given material.
183    pub fn new(section: Section, material: Material) -> Self {
184        let props = SectionProperties::from_section(&section);
185        Self {
186            section,
187            material,
188            props,
189        }
190    }
191
192    /// Calculate stress distribution for the given load case.
193    ///
194    /// Uses FEM Tri6 element stress analysis (mirroring Python `stress_post.py`).
195    /// Falls back to analytical formulas if FEM mesh generation fails.
196    pub fn calculate_stress(&self, loads: SectionLoads) -> StressAnalysisResult {
197        let area = self.props.area;
198
199        // Try FEM Tri6 stress analysis first
200        let fem_points = match crate::stress_fem::calculate_stress_fem(
201            &self.section,
202            &self.props,
203            loads,
204            self.material.poissons_ratio,
205        ) {
206            Ok(points) => Some(points),
207            Err(_) => None,
208        };
209
210        if let Some(fem_points) = fem_points {
211            let mut max_sigma_z = f64::NEG_INFINITY;
212            let mut min_sigma_z = f64::INFINITY;
213            let mut max_von_mises = 0.0;
214            let mut max_tau = 0.0;
215            let mut max_vm_loc = Point::new(0.0, 0.0);
216
217            for p in &fem_points {
218                if p.sigma_z > max_sigma_z {
219                    max_sigma_z = p.sigma_z;
220                }
221                if p.sigma_z < min_sigma_z {
222                    min_sigma_z = p.sigma_z;
223                }
224                if p.von_mises > max_von_mises {
225                    max_von_mises = p.von_mises;
226                    max_vm_loc = Point::new(p.x, p.y);
227                }
228                if p.tau_zxy > max_tau {
229                    max_tau = p.tau_zxy;
230                }
231            }
232
233            return StressAnalysisResult {
234                point_stresses: fem_points,
235                max_sigma_z,
236                min_sigma_z,
237                max_von_mises,
238                max_tau,
239                max_vm_location: max_vm_loc,
240                loads,
241                area,
242            };
243        }
244
245        // Analytical fallback
246        let cx = self.props.centroid.x;
247        let cy = self.props.centroid.y;
248        let ix = self.props.ix;
249        let iy = self.props.iy;
250        let ixy = self.props.ixy;
251
252        let principal = self.props.principal_properties();
253        let phi = principal.phi;
254        let i11 = principal.i11;
255        let i22 = principal.i22;
256
257        let warping = crate::plastic::warping::WarpingProperties::from_section(
258            &self.section,
259            self.material.poissons_ratio,
260        );
261        let ay = warping.ay.max(1e-12);
262        let az = warping.az.max(1e-12);
263        let j = warping.j.max(1e-12);
264
265        let cos_phi = phi.cos();
266        let sin_phi = phi.sin();
267
268        let denom = ix * iy - ixy * ixy;
269
270        let mut point_stresses: Vec<StressAtPoint> = Vec::new();
271        let mut max_sigma_z = f64::NEG_INFINITY;
272        let mut min_sigma_z = f64::INFINITY;
273        let mut max_von_mises = 0.0;
274        let mut max_tau = 0.0;
275        let mut max_vm_loc = Point::new(0.0, 0.0);
276
277        let vertices: Vec<Point> = self
278            .section
279            .outer
280            .vertices
281            .iter()
282            .chain(self.section.holes.iter().flat_map(|h| h.vertices.iter()))
283            .cloned()
284            .collect();
285
286        for v in &vertices {
287            let dx = v.x - cx;
288            let dy = v.y - cy;
289
290            let x11 = dx * cos_phi + dy * sin_phi;
291            let y22 = -dx * sin_phi + dy * cos_phi;
292
293            // Stress breakdown by load component (mirrors Python StressResult)
294            // σ_z = Mxx*(Iyy*y - Ixy*x)/denom + Myy*(Ixy*y - Ixx*x)/denom
295            let sig_zz_n = loads.n / area;
296
297            let (sig_zz_mxx, sig_zz_myy) = if denom.abs() > 1e-15 {
298                (
299                    loads.mxx * (iy * dy - ixy * dx) / denom,
300                    loads.myy * (ixy * dy - ix * dx) / denom,
301                )
302            } else {
303                (0.0, 0.0)
304            };
305
306            let sig_zz_m11 = if i11 > 1e-15 {
307                loads.m11 * y22 / i11
308            } else {
309                0.0
310            };
311            let sig_zz_m22 = if i22 > 1e-15 {
312                -loads.m22 * x11 / i22
313            } else {
314                0.0
315            };
316
317            // Shear stress breakdown
318            let sig_zx_vx = loads.vx / ay;
319            let sig_zy_vx = 0.0; // Vx y-component (simplified)
320            let sig_zx_vy = 0.0; // Vy x-component (simplified)
321            let sig_zy_vy = loads.vy / az;
322
323            let t_max = self.estimate_max_thickness();
324            let sig_zx_mzz = 0.0; // Torsion x-component (simplified)
325            let sig_zy_mzz = loads.mzz * t_max / j;
326
327            // Combined stresses (mirrors Python StressResult.calculate_combined_stresses)
328            let sig_zz_m = sig_zz_mxx + sig_zz_myy + sig_zz_m11 + sig_zz_m22;
329            let sig_zxy_mzz = (sig_zx_mzz * sig_zx_mzz + sig_zy_mzz * sig_zy_mzz).sqrt();
330            let sig_zxy_vx = (sig_zx_vx * sig_zx_vx + sig_zy_vx * sig_zy_vx).sqrt();
331            let sig_zxy_vy = (sig_zx_vy * sig_zx_vy + sig_zy_vy * sig_zy_vy).sqrt();
332            let sig_zx_v = sig_zx_vx + sig_zx_vy;
333            let sig_zy_v = sig_zy_vx + sig_zy_vy;
334            let sig_zxy_v = (sig_zx_v * sig_zx_v + sig_zy_v * sig_zy_v).sqrt();
335
336            let sigma_z = sig_zz_n + sig_zz_m;
337            let tau_xz = sig_zx_mzz + sig_zx_v;
338            let tau_yz = sig_zy_mzz + sig_zy_v;
339            let tau_zxy = (tau_xz * tau_xz + tau_yz * tau_yz).sqrt();
340
341            let von_mises = (sigma_z * sigma_z + 3.0 * tau_zxy * tau_zxy).sqrt();
342
343            let half = sigma_z / 2.0;
344            let disc = (half * half + tau_zxy * tau_zxy).sqrt();
345            let sigma_1 = half + disc;
346            let sigma_2 = half - disc;
347
348            let sap = StressAtPoint {
349                x: v.x,
350                y: v.y,
351                sig_zz_n,
352                sig_zz_mxx,
353                sig_zz_myy,
354                sig_zz_m11,
355                sig_zz_m22,
356                sig_zx_vx,
357                sig_zy_vx,
358                sig_zx_vy,
359                sig_zy_vy,
360                sig_zx_mzz,
361                sig_zy_mzz,
362                sig_zz_m,
363                sig_zxy_mzz,
364                sig_zxy_vx,
365                sig_zxy_vy,
366                sig_zx_v,
367                sig_zy_v,
368                sig_zxy_v,
369                sigma_z,
370                tau_xz,
371                tau_yz,
372                tau_zxy,
373                von_mises,
374                sigma_1,
375                sigma_2,
376            };
377
378            if sigma_z > max_sigma_z {
379                max_sigma_z = sigma_z;
380            }
381            if sigma_z < min_sigma_z {
382                min_sigma_z = sigma_z;
383            }
384            if von_mises > max_von_mises {
385                max_von_mises = von_mises;
386                max_vm_loc = *v;
387            }
388            if tau_zxy > max_tau {
389                max_tau = tau_zxy;
390            }
391
392            point_stresses.push(sap);
393        }
394
395        if point_stresses.is_empty() {
396            max_sigma_z = 0.0;
397            min_sigma_z = 0.0;
398        }
399
400        StressAnalysisResult {
401            point_stresses,
402            max_sigma_z,
403            min_sigma_z,
404            max_von_mises,
405            max_tau,
406            max_vm_location: max_vm_loc,
407            loads,
408            area,
409        }
410    }
411
412    /// Estimate maximum wall thickness for torsional stress calculation.
413    fn estimate_max_thickness(&self) -> f64 {
414        let bounds = self.section.bounds();
415        let h = bounds.3 - bounds.2;
416        let b = bounds.1 - bounds.0;
417        let bbox_peri = 2.0 * (h + b);
418        let actual_peri = self.section.perimeter();
419        if actual_peri > 1e-12 {
420            bbox_peri * (1.0 - actual_peri / (2.0 * (h + b))) / 4.0 + (h * b / (h + b))
421        } else {
422            h.min(b) / 2.0
423        }
424    }
425
426    /// Get the section properties used by this analysis.
427    pub fn properties(&self) -> &SectionProperties {
428        &self.props
429    }
430
431    /// Get the material.
432    pub fn material(&self) -> &Material {
433        &self.material
434    }
435
436    /// Check if the section yields under the given loads.
437    pub fn check_yield(&self, loads: SectionLoads) -> YieldCheckResult {
438        let result = self.calculate_stress(loads);
439        let fy = self.material.yield_strength;
440
441        YieldCheckResult {
442            max_stress: result.max_von_mises,
443            yield_strength: fy,
444            utilization: result.max_von_mises / fy,
445            yielded: result.max_von_mises > fy,
446        }
447    }
448}
449
450/// Result of a yield check.
451#[derive(Debug, Clone, Copy)]
452pub struct YieldCheckResult {
453    /// Maximum stress (von Mises) `Pa`
454    pub max_stress: f64,
455    /// Yield strength `Pa`
456    pub yield_strength: f64,
457    /// Utilization ratio (max_stress / yield_strength)
458    pub utilization: f64,
459    /// Whether the section has yielded
460    pub yielded: bool,
461}
462
463#[cfg(test)]
464mod tests {
465    use super::*;
466    use crate::geometry::{Point, Polygon};
467    use crate::material::presets::STEEL_S355;
468    use crate::section_library::ParametricSection;
469
470    #[test]
471    fn stress_pure_axial() {
472        let poly = Polygon::new(vec![
473            Point::new(-0.05, -0.05),
474            Point::new(0.05, -0.05),
475            Point::new(0.05, 0.05),
476            Point::new(-0.05, 0.05),
477        ]);
478        let section = Section::new(poly, vec![]);
479        let analysis = StressAnalysis::new(section, STEEL_S355);
480
481        let n = 100e3;
482        let result = analysis.calculate_stress(SectionLoads::axial(n));
483
484        let area = 0.1 * 0.1;
485        let expected_sigma = n / area;
486
487        assert!((result.max_sigma_z - expected_sigma).abs() / expected_sigma < 0.01);
488        assert!((result.min_sigma_z - expected_sigma).abs() / expected_sigma < 0.01);
489    }
490
491    #[test]
492    fn stress_pure_bending() {
493        let poly = Polygon::new(vec![
494            Point::new(-0.05, -0.05),
495            Point::new(0.05, -0.05),
496            Point::new(0.05, 0.05),
497            Point::new(-0.05, 0.05),
498        ]);
499        let section = Section::new(poly, vec![]);
500        let analysis = StressAnalysis::new(section, STEEL_S355);
501
502        let mxx = 10e3;
503        let result = analysis.calculate_stress(SectionLoads::bending_x(mxx));
504
505        let ix = 0.1 * 0.1_f64.powi(3) / 12.0;
506        let y_max = 0.05;
507        let expected_sigma = mxx * y_max / ix;
508
509        assert!((result.max_sigma_z - expected_sigma).abs() / expected_sigma < 0.01);
510        assert!((result.min_sigma_z + expected_sigma).abs() / expected_sigma < 0.01);
511    }
512
513    #[test]
514    fn stress_yield_check() {
515        let poly = Polygon::new(vec![
516            Point::new(-0.05, -0.05),
517            Point::new(0.05, -0.05),
518            Point::new(0.05, 0.05),
519            Point::new(-0.05, 0.05),
520        ]);
521        let section = Section::new(poly, vec![]);
522        let analysis = StressAnalysis::new(section, STEEL_S355);
523
524        let area = 0.1 * 0.1;
525        let n_yield = STEEL_S355.yield_strength * area * 0.5;
526        let check = analysis.check_yield(SectionLoads::axial(n_yield));
527
528        assert!(!check.yielded);
529        assert!(check.utilization < 1.0);
530        assert!((check.utilization - 0.5).abs() < 0.05);
531    }
532
533    #[test]
534    fn stress_i_section_bending() {
535        let i = crate::section_library::steel::ISection::new(0.3, 0.15, 0.007, 0.01, 0.012);
536        let section = i.build();
537        let analysis = StressAnalysis::new(section, STEEL_S355);
538
539        let mxx = 50e3;
540        let result = analysis.calculate_stress(SectionLoads::bending_x(mxx));
541
542        assert!(result.max_sigma_z > 0.0);
543        assert!(result.min_sigma_z < 0.0);
544        assert!(result.max_von_mises > 0.0);
545    }
546
547    #[test]
548    fn stress_combined_loads() {
549        let poly = Polygon::new(vec![
550            Point::new(-0.05, -0.05),
551            Point::new(0.05, -0.05),
552            Point::new(0.05, 0.05),
553            Point::new(-0.05, 0.05),
554        ]);
555        let section = Section::new(poly, vec![]);
556        let analysis = StressAnalysis::new(section, STEEL_S355);
557
558        let loads = SectionLoads {
559            n: 50e3,
560            vx: 5e3,
561            vy: 10e3,
562            mxx: 5e3,
563            myy: 3e3,
564            m11: 0.0,
565            m22: 0.0,
566            mzz: 1e3,
567        };
568        let result = analysis.calculate_stress(loads);
569
570        assert!(result.max_von_mises > 0.0);
571        assert!(result.max_tau > 0.0);
572        assert!(result.point_stresses.len() >= 4);
573    }
574
575    #[test]
576    fn stress_principal_bending() {
577        let angle = crate::section_library::steel::AngleSection::new(0.1, 0.075, 0.008, 0.0, 0.0);
578        let section = angle.build();
579        let analysis = StressAnalysis::new(section, STEEL_S355);
580
581        let m11 = 10e3;
582        let loads = SectionLoads {
583            m11,
584            ..SectionLoads::zero()
585        };
586        let result = analysis.calculate_stress(loads);
587
588        assert!(result.max_sigma_z > 0.0);
589        assert!(result.min_sigma_z < 0.0);
590    }
591
592    #[test]
593    fn stress_breakdown_axial() {
594        // Pure axial: sig_zz_n should equal N/A, all other components zero
595        let poly = Polygon::new(vec![
596            Point::new(-0.05, -0.05),
597            Point::new(0.05, -0.05),
598            Point::new(0.05, 0.05),
599            Point::new(-0.05, 0.05),
600        ]);
601        let section = Section::new(poly, vec![]);
602        let analysis = StressAnalysis::new(section, STEEL_S355);
603
604        let n = 100e3;
605        let result = analysis.calculate_stress(SectionLoads::axial(n));
606
607        let area = 0.1 * 0.1;
608        let expected = n / area;
609
610        for s in &result.point_stresses {
611            assert!((s.sig_zz_n - expected).abs() / expected < 1e-6);
612            assert!(s.sig_zz_mxx.abs() < 1e-6);
613            assert!(s.sig_zz_myy.abs() < 1e-6);
614            assert!(s.sig_zz_m11.abs() < 1e-6);
615            assert!(s.sig_zz_m22.abs() < 1e-6);
616        }
617    }
618
619    #[test]
620    fn stress_breakdown_bending() {
621        // Pure Mxx: sig_zz_mxx should be non-zero, sig_zz_n zero
622        let poly = Polygon::new(vec![
623            Point::new(-0.05, -0.05),
624            Point::new(0.05, -0.05),
625            Point::new(0.05, 0.05),
626            Point::new(-0.05, 0.05),
627        ]);
628        let section = Section::new(poly, vec![]);
629        let analysis = StressAnalysis::new(section, STEEL_S355);
630
631        let mxx = 10e3;
632        let result = analysis.calculate_stress(SectionLoads::bending_x(mxx));
633
634        // FEM evaluates at mesh nodes, some near neutral axis where σ ≈ 0.
635        // Check that the maximum bending stress is non-zero.
636        let max_mxx = result
637            .point_stresses
638            .iter()
639            .map(|s| s.sig_zz_mxx.abs())
640            .fold(0.0_f64, f64::max);
641        assert!(max_mxx > 1e-3);
642        for s in &result.point_stresses {
643            assert!(s.sig_zz_n.abs() < 1e-6);
644        }
645    }
646
647    #[test]
648    fn stress_breakdown_shear() {
649        // Pure shear: sig_zx_vx and sig_zy_vy should be non-zero
650        let poly = Polygon::new(vec![
651            Point::new(-0.05, -0.05),
652            Point::new(0.05, -0.05),
653            Point::new(0.05, 0.05),
654            Point::new(-0.05, 0.05),
655        ]);
656        let section = Section::new(poly, vec![]);
657        let analysis = StressAnalysis::new(section, STEEL_S355);
658
659        let loads = SectionLoads {
660            vx: 5e3,
661            vy: 10e3,
662            ..SectionLoads::zero()
663        };
664        let result = analysis.calculate_stress(loads);
665
666        // Shear components must be non-zero somewhere (individual sample
667        // points on symmetry lines can legitimately be zero).
668        let max_zx_vx = result
669            .point_stresses
670            .iter()
671            .map(|s| s.sig_zx_vx.abs())
672            .fold(0.0_f64, f64::max);
673        let max_zy_vy = result
674            .point_stresses
675            .iter()
676            .map(|s| s.sig_zy_vy.abs())
677            .fold(0.0_f64, f64::max);
678        assert!(max_zx_vx > 0.0);
679        assert!(max_zy_vy > 0.0);
680        for s in &result.point_stresses {
681            assert!(s.sig_zz_n.abs() < 1e-6);
682        }
683    }
684
685    #[test]
686    fn stress_breakdown_combination() {
687        // Combined loads: sigma_z should equal sum of components
688        let poly = Polygon::new(vec![
689            Point::new(-0.05, -0.05),
690            Point::new(0.05, -0.05),
691            Point::new(0.05, 0.05),
692            Point::new(-0.05, 0.05),
693        ]);
694        let section = Section::new(poly, vec![]);
695        let analysis = StressAnalysis::new(section, STEEL_S355);
696
697        let loads = SectionLoads {
698            n: 50e3,
699            mxx: 5e3,
700            myy: 3e3,
701            ..SectionLoads::zero()
702        };
703        let result = analysis.calculate_stress(loads);
704
705        for s in &result.point_stresses {
706            let sum = s.sig_zz_n + s.sig_zz_mxx + s.sig_zz_myy + s.sig_zz_m11 + s.sig_zz_m22;
707            assert!((sum - s.sigma_z).abs() < 1e-3);
708        }
709    }
710
711    #[test]
712    fn stress_combined_components_pure_axial() {
713        let poly = Polygon::new(vec![
714            Point::new(-0.05, -0.05),
715            Point::new(0.05, -0.05),
716            Point::new(0.05, 0.05),
717            Point::new(-0.05, 0.05),
718        ]);
719        let section = Section::new(poly, vec![]);
720        let analysis = StressAnalysis::new(section, STEEL_S355);
721        let result = analysis.calculate_stress(SectionLoads::axial(100e3));
722
723        for s in &result.point_stresses {
724            // Pure axial: no bending or shear combined components
725            assert!(s.sig_zz_m.abs() < 1e-6);
726            assert!(s.sig_zxy_mzz.abs() < 1e-6);
727            assert!(s.sig_zxy_vx.abs() < 1e-6);
728            assert!(s.sig_zxy_vy.abs() < 1e-6);
729            assert!(s.sig_zx_v.abs() < 1e-6);
730            assert!(s.sig_zy_v.abs() < 1e-6);
731            assert!(s.sig_zxy_v.abs() < 1e-6);
732        }
733    }
734
735    #[test]
736    fn stress_combined_components_pure_bending() {
737        let poly = Polygon::new(vec![
738            Point::new(-0.05, -0.05),
739            Point::new(0.05, -0.05),
740            Point::new(0.05, 0.05),
741            Point::new(-0.05, 0.05),
742        ]);
743        let section = Section::new(poly, vec![]);
744        let analysis = StressAnalysis::new(section, STEEL_S355);
745        let result = analysis.calculate_stress(SectionLoads::bending_x(10e3));
746
747        for s in &result.point_stresses {
748            // sig_zz_m should equal sig_zz_mxx (only Mxx applied)
749            assert!((s.sig_zz_m - s.sig_zz_mxx).abs() < 1e-3);
750            // sigma_z should equal sig_zz_n + sig_zz_m = 0 + sig_zz_mxx
751            assert!((s.sigma_z - s.sig_zz_m).abs() < 1e-3);
752        }
753    }
754
755    #[test]
756    fn stress_combined_components_pure_shear() {
757        let poly = Polygon::new(vec![
758            Point::new(-0.05, -0.05),
759            Point::new(0.05, -0.05),
760            Point::new(0.05, 0.05),
761            Point::new(-0.05, 0.05),
762        ]);
763        let section = Section::new(poly, vec![]);
764        let analysis = StressAnalysis::new(section, STEEL_S355);
765        let loads = SectionLoads {
766            vx: 10e3,
767            ..SectionLoads::zero()
768        };
769        let result = analysis.calculate_stress(loads);
770
771        for s in &result.point_stresses {
772            // FEM shear from Vx has both x and y components.
773            // With Vy=0: sig_zx_v ≈ sig_zx_vx, sig_zy_v ≈ sig_zy_vx
774            assert!(
775                (s.sig_zx_v - s.sig_zx_vx).abs() < 1e-6,
776                "sig_zx_v mismatch at ({}, {})",
777                s.x,
778                s.y
779            );
780            assert!(
781                (s.sig_zy_v - s.sig_zy_vx).abs() < 1e-6,
782                "sig_zy_v mismatch at ({}, {})",
783                s.x,
784                s.y
785            );
786            // No torsion: tau_xz ≈ sig_zx_v
787            assert!(
788                (s.tau_xz - s.sig_zx_v).abs() < 1e-6,
789                "tau_xz mismatch at ({}, {})",
790                s.x,
791                s.y
792            );
793        }
794    }
795
796    #[test]
797    fn stress_combined_components_pure_torsion() {
798        let poly = Polygon::new(vec![
799            Point::new(-0.05, -0.05),
800            Point::new(0.05, -0.05),
801            Point::new(0.05, 0.05),
802            Point::new(-0.05, 0.05),
803        ]);
804        let section = Section::new(poly, vec![]);
805        let analysis = StressAnalysis::new(section, STEEL_S355);
806        let loads = SectionLoads {
807            mzz: 5e3,
808            ..SectionLoads::zero()
809        };
810        let result = analysis.calculate_stress(loads);
811
812        for s in &result.point_stresses {
813            // FEM torsion has both x and y components.
814            // No shear: tau_xz ≈ sig_zx_mzz, tau_yz ≈ sig_zy_mzz
815            assert!(
816                (s.tau_xz - s.sig_zx_mzz).abs() < 1e-3,
817                "tau_xz mismatch at ({}, {})",
818                s.x,
819                s.y
820            );
821            assert!(
822                (s.tau_yz - s.sig_zy_mzz).abs() < 1e-3,
823                "tau_yz mismatch at ({}, {})",
824                s.x,
825                s.y
826            );
827        }
828    }
829
830    #[test]
831    fn stress_unsymmetric_section_bending_formula() {
832        // Angle section (ixy != 0): verify bending stress formula
833        // σ_z = Mxx*(Iyy*y - Ixy*x)/denom + Myy*(Ixy*y - Ixx*x)/denom
834        let angle = crate::section_library::steel::AngleSection::new(0.1, 0.075, 0.008, 0.0, 0.0);
835        let section = angle.build();
836        let props = crate::section_properties::SectionProperties::from_section(&section);
837        let analysis = StressAnalysis::new(section, STEEL_S355);
838
839        let mxx = 5e3;
840        let result = analysis.calculate_stress(SectionLoads::bending_x(mxx));
841
842        let ix = props.ix;
843        let iy = props.iy;
844        let ixy = props.ixy;
845        let denom = ix * iy - ixy * ixy;
846        let cx = props.centroid.x;
847        let cy = props.centroid.y;
848
849        // Verify at each point that sig_zz_mxx matches the formula
850        for s in &result.point_stresses {
851            let dx = s.x - cx;
852            let dy = s.y - cy;
853            let expected = mxx * (iy * dy - ixy * dx) / denom;
854            assert!(
855                (s.sig_zz_mxx - expected).abs() / expected.abs().max(1e-3) < 0.01,
856                "sig_zz_mxx = {}, expected {} at ({}, {})",
857                s.sig_zz_mxx,
858                expected,
859                s.x,
860                s.y
861            );
862        }
863    }
864
865    // -------------------------------------------------------------------------
866    // Poisson ratio propagation (Phase 18.1)
867    // -------------------------------------------------------------------------
868    //
869    // `calculate_stress_fem` previously hard-coded ν = 0.3, so non-steel
870    // materials (aluminium ν=0.33, concrete ν=0.20, timber ν=0.35) got
871    // silently wrong shear/torsion stress. These tests verify that the
872    // material's ν is now propagated.
873
874    /// Build a rectangular section for stress tests.
875    fn rect_section() -> Section {
876        let poly = Polygon::new(vec![
877            Point::new(-0.05, -0.05),
878            Point::new(0.05, -0.05),
879            Point::new(0.05, 0.05),
880            Point::new(-0.05, 0.05),
881        ]);
882        Section::new(poly, vec![])
883    }
884
885    /// A load case that exercises ν-dependent shear stress terms (vx, vy, mzz).
886    /// Pure axial or pure bending (mxx/myy) do not depend on ν.
887    fn shear_loads() -> SectionLoads {
888        SectionLoads {
889            n: 0.0,
890            vx: 5e3,
891            vy: 10e3,
892            mxx: 0.0,
893            myy: 0.0,
894            m11: 0.0,
895            m22: 0.0,
896            mzz: 1e3,
897        }
898    }
899
900    /// Test A — non-steel ν differential: changing ν must change shear stress.
901    ///
902    /// ν enters the warping/shear FEM via shear load vectors, shear area
903    /// `δ_s = 2(1+ν)·C`, shear centre, and shear coefficients. A load case
904    /// with transverse shear (vx, vy) or torsion (mzz) must therefore produce
905    /// different stress results for different ν.
906    #[test]
907    fn fem_stress_depends_on_poissons_ratio() {
908        let section = rect_section();
909        let loads = shear_loads();
910
911        let mat_030 = Material::new(200e9, 0.30, 7850.0, "nu030");
912        let mat_033 = Material::new(200e9, 0.33, 7850.0, "nu033");
913        let mat_020 = Material::new(200e9, 0.20, 7850.0, "nu020");
914
915        let r_030 = StressAnalysis::new(section.clone(), mat_030).calculate_stress(loads);
916        let r_033 = StressAnalysis::new(section.clone(), mat_033).calculate_stress(loads);
917        let r_020 = StressAnalysis::new(section.clone(), mat_020).calculate_stress(loads);
918
919        // Shear stress (max_tau) must differ — it flows through the ν-dependent
920        // shear area and shear coefficients.
921        assert!(
922            (r_030.max_tau - r_033.max_tau).abs() > 1e-6,
923            "ν=0.30 vs ν=0.33: max_tau should differ ({} vs {})",
924            r_030.max_tau,
925            r_033.max_tau
926        );
927        assert!(
928            (r_030.max_tau - r_020.max_tau).abs() > 1e-6,
929            "ν=0.30 vs ν=0.20: max_tau should differ ({} vs {})",
930            r_030.max_tau,
931            r_020.max_tau
932        );
933
934        // Von Mises also changes because it includes shear stress.
935        assert!(
936            (r_030.max_von_mises - r_033.max_von_mises).abs() > 1e-6,
937            "ν=0.30 vs ν=0.33: max_von_mises should differ ({} vs {})",
938            r_030.max_von_mises,
939            r_033.max_von_mises
940        );
941    }
942
943    /// Test B — steel regression: ν=0.30 through the new API path must give
944    /// the same results as before the fix (when 0.3 was hard-coded).
945    #[test]
946    fn fem_stress_steel_nu_030_unchanged() {
947        let section = rect_section();
948        let loads = shear_loads();
949
950        // Through public API with STEEL_S355 (ν=0.30).
951        let r_api = StressAnalysis::new(section.clone(), STEEL_S355).calculate_stress(loads);
952
953        // Through internal helper with explicit ν=0.30.
954        let props = SectionProperties::from_section(&section);
955        let r_internal =
956            crate::stress_fem::calculate_stress_fem(&section, &props, loads, 0.30).unwrap();
957
958        // Max sigma_z and max_tau must match (same ν, same computation path).
959        let internal_max_sigma_z = r_internal
960            .iter()
961            .fold(f64::NEG_INFINITY, |a, p| a.max(p.sigma_z));
962        let internal_max_tau = r_internal.iter().fold(0.0f64, |a, p| a.max(p.tau_zxy));
963
964        assert!(
965            (r_api.max_sigma_z - internal_max_sigma_z).abs() < 1e-6,
966            "steel regression: max_sigma_z API={} internal={}",
967            r_api.max_sigma_z,
968            internal_max_sigma_z
969        );
970        assert!(
971            (r_api.max_tau - internal_max_tau).abs() < 1e-6,
972            "steel regression: max_tau API={} internal={}",
973            r_api.max_tau,
974            internal_max_tau
975        );
976    }
977
978    /// Test C — public API propagation: `StressAnalysis::new(section, material)`
979    /// must pass `material.poissons_ratio` to the FEM, not a hard-coded value.
980    ///
981    /// We verify this by comparing the public API result against an internal
982    /// call with the material's explicit ν. If the public API were still
983    /// hard-coding 0.3, this test would fail for aluminium (ν=0.33).
984    #[test]
985    fn public_api_propagates_material_poissons_ratio() {
986        let section = rect_section();
987        let loads = shear_loads();
988
989        // Aluminium: ν=0.33, E=70e9.
990        let aluminium = Material::new(70e9, 0.33, 2700.0, "Aluminium");
991        let nu = aluminium.poissons_ratio;
992
993        // Through public API.
994        let r_api = StressAnalysis::new(section.clone(), aluminium).calculate_stress(loads);
995
996        // Through internal helper with the same explicit ν.
997        let props = SectionProperties::from_section(&section);
998        let r_internal =
999            crate::stress_fem::calculate_stress_fem(&section, &props, loads, nu).unwrap();
1000
1001        let internal_max_tau = r_internal.iter().fold(0.0f64, |a, p| a.max(p.tau_zxy));
1002
1003        assert!(
1004            (r_api.max_tau - internal_max_tau).abs() < 1e-6,
1005            "public API must propagate ν: max_tau API={} internal(ν={})={}",
1006            r_api.max_tau,
1007            nu,
1008            internal_max_tau
1009        );
1010
1011        // Sanity: the result must also differ from steel (ν=0.30).
1012        let r_steel = StressAnalysis::new(section, STEEL_S355).calculate_stress(loads);
1013        assert!(
1014            (r_api.max_tau - r_steel.max_tau).abs() > 1e-6,
1015            "aluminium (ν=0.33) and steel (ν=0.30) must give different shear stress"
1016        );
1017    }
1018}