Skip to main content

section_properties/
section.rs

1use crate::geometry::{Point, Polygon, segments_interact};
2
3/// A section can consist of an outer polygon and zero or more hole polygons.
4#[derive(Debug, Clone)]
5pub struct Section {
6    /// Outer boundary (must be CCW for positive area)
7    pub outer: Polygon,
8    /// Hole boundaries (each must be CW so that their signed area is negative)
9    pub holes: Vec<Polygon>,
10}
11
12impl Section {
13    /// Create a new section from an outer polygon and optional holes.
14    ///
15    /// The outer boundary is normalised to counter-clockwise orientation
16    /// and each hole to clockwise orientation.
17    pub fn new(mut outer: Polygon, mut holes: Vec<Polygon>) -> Self {
18        // Section owns the orientation convention:
19        // outer boundary -> CCW
20        // holes -> CW
21
22        if outer.signed_area() < 0.0 {
23            outer.vertices.reverse();
24        }
25
26        for hole in &mut holes {
27            if hole.signed_area() > 0.0 {
28                hole.vertices.reverse();
29            }
30        }
31
32        Self { outer, holes }
33    }
34
35    /// Net area of the section (outer area minus hole areas).
36    pub fn area(&self) -> f64 {
37        let mut a = self.outer.area();
38        for h in &self.holes {
39            a -= h.area();
40        }
41        a
42    }
43
44    /// Centroid of the section using the composite area formula.
45    ///
46    /// # Panics
47    ///
48    /// Panics if the net section area (outer minus holes) is zero or
49    /// near-zero.  Use [`try_centroid`](Self::try_centroid) for a fallible
50    /// version that returns `None` instead of panicking.
51    pub fn centroid(&self) -> Point {
52        self.try_centroid()
53            .expect("Section area is too small to compute centroid")
54    }
55
56    /// Fallible centroid: returns `None` if the net section area is zero or
57    /// near-zero (degenerate section where outer area equals total hole area).
58    pub fn try_centroid(&self) -> Option<Point> {
59        let mut sum_x = 0.0;
60        let mut sum_y = 0.0;
61        let mut total_area = 0.0;
62
63        // Outer contour (positive area)
64        let outer_c = self.outer.centroid();
65        let outer_a = self.outer.area();
66        sum_x += outer_c.x * outer_a;
67        sum_y += outer_c.y * outer_a;
68        total_area += outer_a;
69
70        // Holes (negative area)
71        for h in &self.holes {
72            let a = h.area(); // positive magnitude
73            let c = h.centroid();
74            sum_x -= c.x * a;
75            sum_y -= c.y * a;
76            total_area -= a;
77        }
78
79        if total_area.abs() <= f64::EPSILON {
80            return None;
81        }
82
83        Some(Point::new(sum_x / total_area, sum_y / total_area))
84    }
85
86    /// Bounding box of the section: (min_x, max_x, min_y, max_y)
87    pub fn bounds(&self) -> (f64, f64, f64, f64) {
88        let mut min_x = f64::INFINITY;
89        let mut max_x = f64::NEG_INFINITY;
90        let mut min_y = f64::INFINITY;
91        let mut max_y = f64::NEG_INFINITY;
92
93        for v in &self.outer.vertices {
94            min_x = min_x.min(v.x);
95            max_x = max_x.max(v.x);
96            min_y = min_y.min(v.y);
97            max_y = max_y.max(v.y);
98        }
99        for hole in &self.holes {
100            for v in &hole.vertices {
101                min_x = min_x.min(v.x);
102                max_x = max_x.max(v.x);
103                min_y = min_y.min(v.y);
104                max_y = max_y.max(v.y);
105            }
106        }
107        (min_x, max_x, min_y, max_y)
108    }
109
110    /// Width of the section (max_x - min_x)
111    pub fn width(&self) -> f64 {
112        let (min_x, max_x, _, _) = self.bounds();
113        max_x - min_x
114    }
115
116    /// Height of the section (max_y - min_y)
117    pub fn height(&self) -> f64 {
118        let (_, _, min_y, max_y) = self.bounds();
119        max_y - min_y
120    }
121
122    /// Check if a point is inside the section (including holes).
123    pub fn contains_point(&self, point: Point) -> bool {
124        // Check outer polygon
125        if !self.outer.contains_point(point) {
126            return false;
127        }
128        // Check holes
129        for hole in &self.holes {
130            if hole.contains_point(point) {
131                return false;
132            }
133        }
134        true
135    }
136
137    /// Perimeter of the section (outer + holes).
138    pub fn perimeter(&self) -> f64 {
139        let mut p = self.outer.perimeter();
140        for hole in &self.holes {
141            p += hole.perimeter();
142        }
143        p
144    }
145
146    /// Frame properties for beam/frame analysis (matches Python's calculate_frame_properties).
147    ///
148    /// Returns tuple: `(area, ixx, iyy, ixy, j, phi)`
149    ///
150    /// - `area`: cross-sectional area `m²`
151    /// - `ixx`: second moment of area about x-axis `m⁴`
152    /// - `iyy`: second moment of area about y-axis `m⁴`
153    /// - `ixy`: product of inertia `m⁴`
154    /// - `j`: St. Venant torsion constant `m⁴`
155    /// - `phi`: angle from centroidal x-axis to major principal axis (11),
156    ///   CCW positive, radians.  `phi = ½ atan2(2·Ixy, Ixx − Iyy)`.
157    pub fn frame_properties(&self, nu: f64) -> (f64, f64, f64, f64, f64, f64) {
158        use crate::plastic::warping::WarpingProperties;
159        use crate::section_properties::SectionProperties;
160
161        let props = SectionProperties::from_section(self);
162        let warping = WarpingProperties::from_section(self, nu);
163        let principal = props.principal_properties();
164
165        (
166            props.area,
167            props.ix,
168            props.iy,
169            props.ixy,
170            warping.j,
171            principal.phi,
172        )
173    }
174
175    /// Frame properties with transformed-section analysis for a homogeneous
176    /// material.
177    ///
178    /// Returns effective stiffnesses E·A, E·I, G·J and the mass per unit
179    /// length. The geometric properties are identical to
180    /// [`frame_properties_full`](Self::frame_properties_full) because a
181    /// single-material section has modular ratio n = 1 everywhere.
182    ///
183    /// # Errors
184    /// [`MaterialError::InvalidMaterial`] when the material fails validation.
185    ///
186    /// For multi-material (genuinely composite) sections use
187    /// [`CompositeSection::transformed_properties`](crate::section_library::CompositeSection::transformed_properties),
188    /// which applies per-group modular ratios.
189    pub fn frame_properties_with_material(
190        &self,
191        material: &crate::material::Material,
192    ) -> Result<TransformedFrameProperties, MaterialError> {
193        if !material.is_valid() {
194            return Err(MaterialError::InvalidMaterial(format!(
195                "E={}, G={}, nu={}, rho={}",
196                material.youngs_modulus,
197                material.shear_modulus,
198                material.poissons_ratio,
199                material.density
200            )));
201        }
202
203        let fp = self.frame_properties_full(material.poissons_ratio);
204        let e = material.youngs_modulus;
205        let g = material.shear_modulus;
206
207        Ok(TransformedFrameProperties {
208            e_ref: e,
209            area: fp.area,
210            ea: e * fp.area,
211            ei_xx: e * fp.ixx,
212            ei_yy: e * fp.iyy,
213            ei_w: e * fp.iw,
214            gj: g * fp.j,
215            mass_per_length: material.density * fp.area,
216            geometric: fp,
217        })
218    }
219}
220
221/// Full frame (beam) analysis results, mirroring the 11-value tuple returned
222/// by Python `Section.calculate_frame_properties()`.
223#[derive(Debug, Clone, Copy)]
224pub struct FrameProperties {
225    /// Cross-sectional area.
226    pub area: f64,
227    /// Centroidal second moment about x.
228    pub ixx: f64,
229    /// Centroidal second moment about y.
230    pub iyy: f64,
231    /// Centroidal product of inertia.
232    pub ixy: f64,
233    /// St. Venant torsion constant.
234    pub j: f64,
235    /// Principal axis angle (radians, CCW from x).
236    pub phi: f64,
237    /// Major principal second moment.
238    pub i11: f64,
239    /// Minor principal second moment.
240    pub i22: f64,
241    /// Shear centre x-coordinate (global axes).
242    pub delta_x: f64,
243    /// Shear centre y-coordinate (global axes).
244    pub delta_y: f64,
245    /// Warping constant.
246    pub iw: f64,
247}
248
249/// Error returned when a material cannot be used for transformed-section
250/// analysis.
251#[derive(Debug, Clone, PartialEq, Eq)]
252pub enum MaterialError {
253    /// Material properties failed validation (non-positive E or G, invalid
254    /// Poisson's ratio, negative density).
255    InvalidMaterial(String),
256}
257
258impl std::fmt::Display for MaterialError {
259    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
260        match self {
261            MaterialError::InvalidMaterial(reason) => {
262                write!(f, "invalid material: {reason}")
263            }
264        }
265    }
266}
267
268impl std::error::Error for MaterialError {}
269
270/// Effective (E-weighted) frame properties from transformed-section analysis
271/// with a single homogeneous material.
272///
273/// The geometric quantities (`area`, `ixx`, ...) are unchanged; the stiffness
274/// terms carry the material modulus:
275/// `ea = E·A`, `ei_x = E·Ixx`, ..., `ej = G·J` where `G` is the material's
276/// `shear_modulus` (equal to `E / 2(1+nu)` only for isotropic materials).
277///
278/// For multi-material sections use
279/// [`CompositeSection::transformed_properties`](crate::section_library::CompositeSection::transformed_properties)
280/// which applies per-group modular ratios.
281#[derive(Debug, Clone, Copy)]
282pub struct TransformedFrameProperties {
283    /// Reference modulus used for the transformation (= material's E).
284    pub e_ref: f64,
285    /// Geometric area (unchanged by the transformation for n=1).
286    pub area: f64,
287    /// Effective axial stiffness E·A.
288    pub ea: f64,
289    /// Effective bending stiffness about x, E·Ixx.
290    pub ei_xx: f64,
291    /// Effective bending stiffness about y, E·Iyy.
292    pub ei_yy: f64,
293    /// Effective warping stiffness, E·Iw.
294    pub ei_w: f64,
295    /// Effective torsional stiffness G·J using the material's shear modulus.
296    pub gj: f64,
297    /// Mass per unit length rho·A.
298    pub mass_per_length: f64,
299    /// Underlying geometric frame properties.
300    pub geometric: FrameProperties,
301}
302
303impl Section {
304    /// Full frame properties including shear centre and warping constant.
305    ///
306    /// Mirrors Python `Section.calculate_frame_properties()` (without the FEA
307    /// shear areas, see `mesh` module for those).
308    pub fn frame_properties_full(&self, nu: f64) -> FrameProperties {
309        use crate::plastic::warping::WarpingProperties;
310        use crate::section_properties::SectionProperties;
311
312        let props = SectionProperties::from_section(self);
313        let principal = props.principal_properties();
314        let warping = WarpingProperties::from_section(self, nu);
315
316        FrameProperties {
317            area: props.area,
318            ixx: props.ix,
319            iyy: props.iy,
320            ixy: props.ixy,
321            j: warping.j,
322            phi: principal.phi,
323            i11: principal.i11,
324            i22: principal.i22,
325            delta_x: warping.shear_center.x,
326            delta_y: warping.shear_center.y,
327            iw: warping.iw,
328        }
329    }
330
331    /// Validate hole topology.
332    ///
333    /// Checks (all relative to the section's oriented polygons):
334    /// 1. All hole vertices lie inside the outer polygon (boundary-touching is
335    ///    accepted, matching [`Polygon::contains_point`] on-edge semantics).
336    /// 2. No hole edge interacts with the outer boundary (crosses, touches, or
337    ///    overlaps).  Boundary-touching by a hole **edge** is rejected even
338    ///    though a hole **vertex** on the boundary is accepted in step 1.
339    /// 3. No two holes overlap (area overlap) or nest (one contains another).
340    /// 4. Holes are oriented CW (negative signed area).
341    ///
342    /// Returns `Ok(())` if valid, or `Err(description)` on failure.
343    pub fn validate(&self) -> Result<(), String> {
344        // 1. All hole vertices inside outer
345        for (hi, hole) in self.holes.iter().enumerate() {
346            for v in &hole.vertices {
347                if !self.outer.contains_point(*v) {
348                    return Err(format!(
349                        "Hole {} vertex {:?} lies outside outer boundary",
350                        hi, v
351                    ));
352                }
353            }
354
355            // 2. Hole edge does not cross outer boundary
356            for i in 0..hole.vertices.len() {
357                let h1 = hole.vertices[i];
358                let h2 = hole.vertices[(i + 1) % hole.vertices.len()];
359                for j in 0..self.outer.vertices.len() {
360                    let o1 = self.outer.vertices[j];
361                    let o2 = self.outer.vertices[(j + 1) % self.outer.vertices.len()];
362                    if segments_interact(h1, h2, o1, o2) {
363                        return Err(format!(
364                            "Hole {} edge ({:?}-{:?}) intersects outer boundary",
365                            hi, h1, h2
366                        ));
367                    }
368                }
369            }
370        }
371
372        // 3. Hole-hole: no overlap, no nesting
373        let n = self.holes.len();
374        for i in 0..n {
375            for j in (i + 1)..n {
376                let hi = &self.holes[i];
377                let hj = &self.holes[j];
378
379                // Check nesting: one hole fully contains another
380                let i_contains_j = hj.vertices.iter().all(|v| hi.contains_point(*v));
381                let j_contains_i = hi.vertices.iter().all(|v| hj.contains_point(*v));
382
383                if i_contains_j || j_contains_i {
384                    return Err(format!(
385                        "Holes {} and {} are nested (one contains the other)",
386                        i, j
387                    ));
388                }
389
390                // Check area overlap: if both contain each other's vertices partially,
391                // or edges intersect
392                for a in 0..hi.vertices.len() {
393                    let h1 = hi.vertices[a];
394                    let h2 = hi.vertices[(a + 1) % hi.vertices.len()];
395                    for b in 0..hj.vertices.len() {
396                        let h3 = hj.vertices[b];
397                        let h4 = hj.vertices[(b + 1) % hj.vertices.len()];
398                        if segments_interact(h1, h2, h3, h4) {
399                            return Err(format!("Holes {} and {} have intersecting edges", i, j));
400                        }
401                    }
402                }
403            }
404        }
405
406        // 4. Orientation check (already enforced by new(), but double-check)
407        if self.outer.signed_area() < 0.0 {
408            return Err("Outer boundary must be CCW (positive area)".into());
409        }
410        for (hi, hole) in self.holes.iter().enumerate() {
411            if hole.signed_area() > 0.0 {
412                return Err(format!("Hole {} must be CW (negative area)", hi));
413            }
414        }
415
416        Ok(())
417    }
418
419    /// Create a section with full topology validation.
420    ///
421    /// Validates (see [`Section::validate`]):
422    /// - All hole vertices lie inside the outer boundary (boundary-touching accepted)
423    /// - No two holes overlap or nest (no hole-within-hole)
424    /// - No hole edge interacts with the outer boundary (crosses, touches, or
425    ///   overlaps); edge-level boundary-touching is rejected
426    /// - Orientation is normalised to outer CCW / holes CW
427    ///
428    /// Returns `Err` with a descriptive message if validation fails.
429    pub fn new_validated(outer: Polygon, holes: Vec<Polygon>) -> Result<Self, String> {
430        let section = Self::new(outer, holes);
431        section.validate()?;
432        Ok(section)
433    }
434}
435
436impl crate::section_library::ParametricSection for Section {
437    fn build(&self) -> Section {
438        self.clone()
439    }
440
441    fn designation(&self) -> String {
442        "Section".to_string()
443    }
444}
445
446#[cfg(test)]
447mod tests {
448    use super::*;
449    use crate::section_library::ParametricSection;
450
451    #[test]
452    fn frame_properties_full_i_section() {
453        let i = crate::section_library::steel::ISection::from_designation("IPE300").unwrap();
454        let sec = i.build();
455        let fp = sec.frame_properties_full(0.3);
456        assert!(fp.area > 0.0);
457        assert!(fp.iw.abs() > 0.0, "I-section must have warping constant");
458        // Doubly symmetric: shear centre at centroid (mesh-level tolerance)
459        let c = sec.centroid();
460        assert!((fp.delta_x - c.x).abs() < 5e-3);
461        assert!((fp.delta_y - c.y).abs() < 5e-3);
462        assert!((fp.j / (fp.area * 1e6)).abs() < 1e3); // sanity
463    }
464
465    #[test]
466    fn geometry_from_points_rectangle() {
467        let pts = vec![
468            Point::new(0.0, 0.0),
469            Point::new(0.2, 0.0),
470            Point::new(0.2, 0.1),
471            Point::new(0.0, 0.1),
472        ];
473        let g = crate::geometry::Geometry::from_points(pts, vec![]);
474        assert!((g.area() - 0.02).abs() < 1e-12);
475
476        let outer = vec![
477            Point::new(0.0, 0.0),
478            Point::new(4.0, 0.0),
479            Point::new(4.0, 4.0),
480            Point::new(0.0, 4.0),
481        ];
482        let hole = vec![
483            Point::new(1.0, 1.0),
484            Point::new(3.0, 1.0),
485            Point::new(3.0, 3.0),
486            Point::new(1.0, 3.0),
487        ];
488        let g2 = crate::geometry::Geometry::from_points(outer, vec![hole]);
489        assert!((g2.area() - 12.0).abs() < 1e-12);
490    }
491
492    #[test]
493    fn frame_properties_with_material_rejects_invalid() {
494        let sec = crate::section_library::primitive::RectangularSection::new(0.1, 0.2).build();
495        let mut bad = crate::material::Material::default();
496        bad.youngs_modulus = -1.0;
497        assert!(sec.frame_properties_with_material(&bad).is_err());
498    }
499
500    #[test]
501    fn transformed_frame_properties_scale_with_e() {
502        let sec = crate::section_library::primitive::RectangularSection::new(0.1, 0.2).build();
503        let geo = sec.frame_properties_full(0.3);
504
505        let steel = crate::material::presets::STEEL_S355;
506        let t_steel = sec.frame_properties_with_material(&steel).unwrap();
507        assert!((t_steel.ea - steel.youngs_modulus * t_steel.area).abs() < 1e-6);
508        assert!((t_steel.ei_xx - steel.youngs_modulus * geo.ixx).abs() < 1e-9);
509        // G = material.shear_modulus (independent for orthotropic materials)
510        let g_expected = steel.shear_modulus;
511        assert!((t_steel.gj - g_expected * geo.j).abs() < 1e-3);
512
513        // Aluminium: E roughly 1/3 of steel -> EI scales proportionally.
514        let alu = crate::material::Material::new(69e9, 0.33, 2700.0, "alu");
515        let t_alu = sec.frame_properties_with_material(&alu).unwrap();
516        let ratio = t_alu.ei_xx / t_steel.ei_xx;
517        assert!((ratio - alu.youngs_modulus / steel.youngs_modulus).abs() < 1e-9);
518        // Mass uses density
519        assert!((t_alu.mass_per_length - 2700.0 * t_alu.area).abs() < 1e-9);
520    }
521
522    #[test]
523    fn section_new_validated_rejects_hole_outside_outer() {
524        let outer = crate::geometry::Polygon::new(vec![
525            Point::new(0.0, 0.0),
526            Point::new(10.0, 0.0),
527            Point::new(10.0, 10.0),
528            Point::new(0.0, 10.0),
529        ]);
530        let hole = crate::geometry::Polygon::new(vec![
531            Point::new(11.0, 11.0),
532            Point::new(12.0, 11.0),
533            Point::new(12.0, 12.0),
534            Point::new(11.0, 12.0),
535        ]);
536        let err = Section::new_validated(outer, vec![hole]).unwrap_err();
537        assert!(err.contains("outside outer boundary"));
538    }
539
540    #[test]
541    fn section_new_validated_rejects_nested_holes() {
542        let outer = crate::geometry::Polygon::new(vec![
543            Point::new(0.0, 0.0),
544            Point::new(10.0, 0.0),
545            Point::new(10.0, 10.0),
546            Point::new(0.0, 10.0),
547        ]);
548        let hole_outer = crate::geometry::Polygon::new(vec![
549            Point::new(1.0, 1.0),
550            Point::new(9.0, 1.0),
551            Point::new(9.0, 9.0),
552            Point::new(1.0, 9.0),
553        ]);
554        let hole_inner = crate::geometry::Polygon::new(vec![
555            Point::new(3.0, 3.0),
556            Point::new(5.0, 3.0),
557            Point::new(5.0, 5.0),
558            Point::new(3.0, 5.0),
559        ]);
560        let err = Section::new_validated(outer, vec![hole_outer, hole_inner]).unwrap_err();
561        assert!(err.contains("nested"));
562    }
563
564    #[test]
565    fn section_new_validated_rejects_overlapping_holes() {
566        let outer = crate::geometry::Polygon::new(vec![
567            Point::new(0.0, 0.0),
568            Point::new(10.0, 0.0),
569            Point::new(10.0, 10.0),
570            Point::new(0.0, 10.0),
571        ]);
572        let hole_a = crate::geometry::Polygon::new(vec![
573            Point::new(1.0, 1.0),
574            Point::new(5.0, 1.0),
575            Point::new(5.0, 5.0),
576            Point::new(1.0, 5.0),
577        ]);
578        let hole_b = crate::geometry::Polygon::new(vec![
579            Point::new(3.0, 3.0),
580            Point::new(7.0, 3.0),
581            Point::new(7.0, 7.0),
582            Point::new(3.0, 7.0),
583        ]);
584        let err = Section::new_validated(outer, vec![hole_a, hole_b]).unwrap_err();
585        assert!(err.contains("intersecting edges") || err.contains("nested"));
586    }
587
588    #[test]
589    fn section_new_validated_accepts_valid_section() {
590        let outer = crate::geometry::Polygon::new(vec![
591            Point::new(0.0, 0.0),
592            Point::new(10.0, 0.0),
593            Point::new(10.0, 10.0),
594            Point::new(0.0, 10.0),
595        ]);
596        let hole_a = crate::geometry::Polygon::new(vec![
597            Point::new(1.0, 1.0),
598            Point::new(4.0, 1.0),
599            Point::new(4.0, 4.0),
600            Point::new(1.0, 4.0),
601        ]);
602        let hole_b = crate::geometry::Polygon::new(vec![
603            Point::new(6.0, 6.0),
604            Point::new(9.0, 6.0),
605            Point::new(9.0, 9.0),
606            Point::new(6.0, 9.0),
607        ]);
608        let section = Section::new_validated(outer, vec![hole_a, hole_b]).unwrap();
609        assert_eq!(section.holes.len(), 2);
610    }
611
612    // -------------------------------------------------------------------------
613    // Phase 18.5: GJ must use Material::shear_modulus, not E/(2(1+ν)).
614    // -------------------------------------------------------------------------
615
616    /// Helper: build a rectangle and get its frame properties with a material.
617    fn rect_frame_props(mat: &crate::material::Material) -> TransformedFrameProperties {
618        let sec = crate::section_library::primitive::RectangularSection::new(0.1, 0.2).build();
619        sec.frame_properties_with_material(mat).unwrap()
620    }
621
622    /// Test A — TIMBER_GL24H GJ regression: GJ must use the stored
623    /// `shear_modulus` (0.725 GPa), NOT the isotropic relation E/(2(1+ν))
624    /// which would give 4.296 GPa (~5.9× too large).
625    #[test]
626    fn gj_uses_material_shear_modulus_timber() {
627        use crate::material::presets::TIMBER_GL24H;
628
629        let t = rect_frame_props(&TIMBER_GL24H);
630        let fp = {
631            let sec = crate::section_library::primitive::RectangularSection::new(0.1, 0.2).build();
632            sec.frame_properties_full(TIMBER_GL24H.poissons_ratio)
633        };
634
635        // GJ must equal material.shear_modulus * J.
636        let gj_expected = TIMBER_GL24H.shear_modulus * fp.j;
637        assert!(
638            (t.gj - gj_expected).abs() < 1e-3,
639            "GJ ({:.6e}) must use shear_modulus * J ({:.6e})",
640            t.gj,
641            gj_expected
642        );
643
644        // GJ must NOT equal the isotropic G * J.
645        let g_iso = TIMBER_GL24H.youngs_modulus / (2.0 * (1.0 + TIMBER_GL24H.poissons_ratio));
646        let gj_iso = g_iso * fp.j;
647        assert!(
648            (t.gj - gj_iso).abs() > 1e3,
649            "GJ ({:.6e}) must NOT use isotropic G * J ({:.6e})",
650            t.gj,
651            gj_iso
652        );
653    }
654
655    /// Test B — Custom independent-G material: Material::with_all() with
656    /// deliberately non-isotropic E/G/ν must produce GJ = G * J.
657    #[test]
658    fn gj_uses_independent_shear_modulus() {
659        let mat = crate::material::Material::with_all(
660            100e9, // E
661            10e9,  // G (deliberately non-isotropic: E/(2(1+0.3)) = 38.46 GPa)
662            0.30,  // ν
663            5000.0, 0.0, 0.0, 0.0, "custom",
664        );
665
666        let t = rect_frame_props(&mat);
667        let fp = {
668            let sec = crate::section_library::primitive::RectangularSection::new(0.1, 0.2).build();
669            sec.frame_properties_full(mat.poissons_ratio)
670        };
671
672        let gj_expected = mat.shear_modulus * fp.j;
673        assert!(
674            (t.gj - gj_expected).abs() < 1e-3,
675            "GJ ({:.6e}) must use independent G * J ({:.6e})",
676            t.gj,
677            gj_expected
678        );
679    }
680
681    /// Test C — Isotropic materials unchanged: for steel/aluminum/concrete
682    /// where G ≈ E/(2(1+ν)), GJ results remain the same as before the fix.
683    #[test]
684    fn gj_isotropic_materials_unchanged() {
685        use crate::material::presets::*;
686
687        for mat in &[STEEL_S355, ALUMINUM_6061_T6, CONCRETE_C25_30] {
688            let t = rect_frame_props(mat);
689            let fp = {
690                let sec =
691                    crate::section_library::primitive::RectangularSection::new(0.1, 0.2).build();
692                sec.frame_properties_full(mat.poissons_ratio)
693            };
694
695            // For isotropic materials, shear_modulus ≈ E/(2(1+ν)),
696            // so GJ should match both.
697            let gj_from_stored = mat.shear_modulus * fp.j;
698            let g_iso = mat.youngs_modulus / (2.0 * (1.0 + mat.poissons_ratio));
699            let gj_from_iso = g_iso * fp.j;
700
701            assert!(
702                (t.gj - gj_from_stored).abs() < 1e-3,
703                "{}: GJ ({:.6e}) must use stored G * J ({:.6e})",
704                mat.name,
705                t.gj,
706                gj_from_stored
707            );
708            // For truly isotropic materials, the two are close.
709            assert!(
710                (t.gj - gj_from_iso).abs() / gj_from_stored.abs() < 0.01,
711                "{}: GJ should be close to isotropic (stored={:.6e}, iso={:.6e})",
712                mat.name,
713                gj_from_stored,
714                gj_from_iso
715            );
716        }
717    }
718
719    /// Test D - Regression guard: no production path may silently recompute
720    /// `G` from `E` and `nu` once the material supplies `shear_modulus`.
721    ///
722    /// Every preset must satisfy `gj == material.shear_modulus * J` to within
723    /// round-off. Any path re-deriving `G` from the isotropic relation fails
724    /// this for the orthotropic presets (e.g. TIMBER_GL24H).
725    #[test]
726    fn gj_never_recomputed_from_e_and_nu() {
727        use crate::material::presets::*;
728
729        let mats = [
730            STEEL_S235,
731            STEEL_S275,
732            STEEL_S355,
733            STEEL_S460,
734            STAINLESS_304,
735            STAINLESS_316,
736            ALUMINUM_6061_T6,
737            ALUMINUM_6063_T5,
738            ALUMINUM_7075_T6,
739            CONCRETE_C25_30,
740            CONCRETE_C30_37,
741            CONCRETE_C40_50,
742            TIMBER_GL24H,
743            TITANIUM_GR5,
744        ];
745
746        for mat in mats {
747            let t = rect_frame_props(&mat);
748            let j = t.geometric.j;
749            assert!(
750                j > 0.0 && j.is_finite(),
751                "{}: J must be finite and > 0, got {j}",
752                mat.name
753            );
754
755            let expected = mat.shear_modulus * j;
756            let rel = (t.gj - expected).abs() / expected.abs();
757            assert!(
758                rel < 1e-12,
759                "{}: gj={:.6e} but shear_modulus*J={:.6e} (rel={:.3e}); G was recomputed from E and nu",
760                mat.name,
761                t.gj,
762                expected,
763                rel
764            );
765        }
766    }
767
768    /// Test D2 - For a fixed independent `G`, GJ must not depend on `nu`:
769    /// the isotropic relation would scale G by 1/(2(1+nu)) and break this.
770    #[test]
771    fn gj_independent_of_nu_for_fixed_shear_modulus() {
772        for nu in [0.2, 0.3, 0.35] {
773            let mat = crate::material::Material::with_all(
774                200e9,
775                1e9,
776                nu,
777                7850.0,
778                1.2e-5,
779                355e6,
780                510e6,
781                "synthetic-g",
782            );
783            assert!(mat.is_valid(), "synthetic material must be valid");
784
785            let t = rect_frame_props(&mat);
786            let expected = mat.shear_modulus * t.geometric.j;
787            let rel = (t.gj - expected).abs() / expected.abs();
788            assert!(
789                rel < 1e-12,
790                "nu={nu}: gj={:.6e} but G*J={:.6e} (rel={:.3e})",
791                t.gj,
792                expected,
793                rel
794            );
795        }
796    }
797}