section-properties 0.4.0

Structural cross-section properties: geometric/principal moments, section moduli, warping/torsion FEM, plastic, cold-formed, and fire analysis.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
use crate::geometry::{Point, Polygon, segments_interact};

/// A section can consist of an outer polygon and zero or more hole polygons.
#[derive(Debug, Clone)]
pub struct Section {
    /// Outer boundary (must be CCW for positive area)
    pub outer: Polygon,
    /// Hole boundaries (each must be CW so that their signed area is negative)
    pub holes: Vec<Polygon>,
}

impl Section {
    /// Create a new section from an outer polygon and optional holes.
    ///
    /// The outer boundary is normalised to counter-clockwise orientation
    /// and each hole to clockwise orientation.
    pub fn new(mut outer: Polygon, mut holes: Vec<Polygon>) -> Self {
        // Section owns the orientation convention:
        // outer boundary -> CCW
        // holes -> CW

        if outer.signed_area() < 0.0 {
            outer.vertices.reverse();
        }

        for hole in &mut holes {
            if hole.signed_area() > 0.0 {
                hole.vertices.reverse();
            }
        }

        Self { outer, holes }
    }

    /// Net area of the section (outer area minus hole areas).
    pub fn area(&self) -> f64 {
        let mut a = self.outer.area();
        for h in &self.holes {
            a -= h.area();
        }
        a
    }

    /// Centroid of the section using the composite area formula.
    ///
    /// # Panics
    ///
    /// Panics if the net section area (outer minus holes) is zero or
    /// near-zero.  Use [`try_centroid`](Self::try_centroid) for a fallible
    /// version that returns `None` instead of panicking.
    pub fn centroid(&self) -> Point {
        self.try_centroid()
            .expect("Section area is too small to compute centroid")
    }

    /// Fallible centroid: returns `None` if the net section area is zero or
    /// near-zero (degenerate section where outer area equals total hole area).
    pub fn try_centroid(&self) -> Option<Point> {
        let mut sum_x = 0.0;
        let mut sum_y = 0.0;
        let mut total_area = 0.0;

        // Outer contour (positive area)
        let outer_c = self.outer.centroid();
        let outer_a = self.outer.area();
        sum_x += outer_c.x * outer_a;
        sum_y += outer_c.y * outer_a;
        total_area += outer_a;

        // Holes (negative area)
        for h in &self.holes {
            let a = h.area(); // positive magnitude
            let c = h.centroid();
            sum_x -= c.x * a;
            sum_y -= c.y * a;
            total_area -= a;
        }

        if total_area.abs() <= f64::EPSILON {
            return None;
        }

        Some(Point::new(sum_x / total_area, sum_y / total_area))
    }

    /// Bounding box of the section: (min_x, max_x, min_y, max_y)
    pub fn bounds(&self) -> (f64, f64, f64, f64) {
        let mut min_x = f64::INFINITY;
        let mut max_x = f64::NEG_INFINITY;
        let mut min_y = f64::INFINITY;
        let mut max_y = f64::NEG_INFINITY;

        for v in &self.outer.vertices {
            min_x = min_x.min(v.x);
            max_x = max_x.max(v.x);
            min_y = min_y.min(v.y);
            max_y = max_y.max(v.y);
        }
        for hole in &self.holes {
            for v in &hole.vertices {
                min_x = min_x.min(v.x);
                max_x = max_x.max(v.x);
                min_y = min_y.min(v.y);
                max_y = max_y.max(v.y);
            }
        }
        (min_x, max_x, min_y, max_y)
    }

    /// Width of the section (max_x - min_x)
    pub fn width(&self) -> f64 {
        let (min_x, max_x, _, _) = self.bounds();
        max_x - min_x
    }

    /// Height of the section (max_y - min_y)
    pub fn height(&self) -> f64 {
        let (_, _, min_y, max_y) = self.bounds();
        max_y - min_y
    }

    /// Check if a point is inside the section (including holes).
    pub fn contains_point(&self, point: Point) -> bool {
        // Check outer polygon
        if !self.outer.contains_point(point) {
            return false;
        }
        // Check holes
        for hole in &self.holes {
            if hole.contains_point(point) {
                return false;
            }
        }
        true
    }

    /// Perimeter of the section (outer + holes).
    pub fn perimeter(&self) -> f64 {
        let mut p = self.outer.perimeter();
        for hole in &self.holes {
            p += hole.perimeter();
        }
        p
    }

    /// Frame properties for beam/frame analysis (matches Python's calculate_frame_properties).
    ///
    /// Returns tuple: `(area, ixx, iyy, ixy, j, phi)`
    ///
    /// - `area`: cross-sectional area `m²`
    /// - `ixx`: second moment of area about x-axis `m⁴`
    /// - `iyy`: second moment of area about y-axis `m⁴`
    /// - `ixy`: product of inertia `m⁴`
    /// - `j`: St. Venant torsion constant `m⁴`
    /// - `phi`: angle from centroidal x-axis to major principal axis (11),
    ///   CCW positive, radians.  `phi = ½ atan2(2·Ixy, Ixx − Iyy)`.
    pub fn frame_properties(&self, nu: f64) -> (f64, f64, f64, f64, f64, f64) {
        use crate::plastic::warping::WarpingProperties;
        use crate::section_properties::SectionProperties;

        let props = SectionProperties::from_section(self);
        let warping = WarpingProperties::from_section(self, nu);
        let principal = props.principal_properties();

        (
            props.area,
            props.ix,
            props.iy,
            props.ixy,
            warping.j,
            principal.phi,
        )
    }

    /// Frame properties with transformed-section analysis for a homogeneous
    /// material.
    ///
    /// Returns effective stiffnesses E·A, E·I, G·J and the mass per unit
    /// length. The geometric properties are identical to
    /// [`frame_properties_full`](Self::frame_properties_full) because a
    /// single-material section has modular ratio n = 1 everywhere.
    ///
    /// # Errors
    /// [`MaterialError::InvalidMaterial`] when the material fails validation.
    ///
    /// For multi-material (genuinely composite) sections use
    /// [`CompositeSection::transformed_properties`](crate::section_library::CompositeSection::transformed_properties),
    /// which applies per-group modular ratios.
    pub fn frame_properties_with_material(
        &self,
        material: &crate::material::Material,
    ) -> Result<TransformedFrameProperties, MaterialError> {
        if !material.is_valid() {
            return Err(MaterialError::InvalidMaterial(format!(
                "E={}, G={}, nu={}, rho={}",
                material.youngs_modulus,
                material.shear_modulus,
                material.poissons_ratio,
                material.density
            )));
        }

        let fp = self.frame_properties_full(material.poissons_ratio);
        let e = material.youngs_modulus;
        let g = material.shear_modulus;

        Ok(TransformedFrameProperties {
            e_ref: e,
            area: fp.area,
            ea: e * fp.area,
            ei_xx: e * fp.ixx,
            ei_yy: e * fp.iyy,
            ei_w: e * fp.iw,
            gj: g * fp.j,
            mass_per_length: material.density * fp.area,
            geometric: fp,
        })
    }
}

/// Full frame (beam) analysis results, mirroring the 11-value tuple returned
/// by Python `Section.calculate_frame_properties()`.
#[derive(Debug, Clone, Copy)]
pub struct FrameProperties {
    /// Cross-sectional area.
    pub area: f64,
    /// Centroidal second moment about x.
    pub ixx: f64,
    /// Centroidal second moment about y.
    pub iyy: f64,
    /// Centroidal product of inertia.
    pub ixy: f64,
    /// St. Venant torsion constant.
    pub j: f64,
    /// Principal axis angle (radians, CCW from x).
    pub phi: f64,
    /// Major principal second moment.
    pub i11: f64,
    /// Minor principal second moment.
    pub i22: f64,
    /// Shear centre x-coordinate (global axes).
    pub delta_x: f64,
    /// Shear centre y-coordinate (global axes).
    pub delta_y: f64,
    /// Warping constant.
    pub iw: f64,
}

/// Error returned when a material cannot be used for transformed-section
/// analysis.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MaterialError {
    /// Material properties failed validation (non-positive E or G, invalid
    /// Poisson's ratio, negative density).
    InvalidMaterial(String),
}

impl std::fmt::Display for MaterialError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MaterialError::InvalidMaterial(reason) => {
                write!(f, "invalid material: {reason}")
            }
        }
    }
}

impl std::error::Error for MaterialError {}

/// Effective (E-weighted) frame properties from transformed-section analysis
/// with a single homogeneous material.
///
/// The geometric quantities (`area`, `ixx`, ...) are unchanged; the stiffness
/// terms carry the material modulus:
/// `ea = E·A`, `ei_x = E·Ixx`, ..., `ej = G·J` where `G` is the material's
/// `shear_modulus` (equal to `E / 2(1+nu)` only for isotropic materials).
///
/// For multi-material sections use
/// [`CompositeSection::transformed_properties`](crate::section_library::CompositeSection::transformed_properties)
/// which applies per-group modular ratios.
#[derive(Debug, Clone, Copy)]
pub struct TransformedFrameProperties {
    /// Reference modulus used for the transformation (= material's E).
    pub e_ref: f64,
    /// Geometric area (unchanged by the transformation for n=1).
    pub area: f64,
    /// Effective axial stiffness E·A.
    pub ea: f64,
    /// Effective bending stiffness about x, E·Ixx.
    pub ei_xx: f64,
    /// Effective bending stiffness about y, E·Iyy.
    pub ei_yy: f64,
    /// Effective warping stiffness, E·Iw.
    pub ei_w: f64,
    /// Effective torsional stiffness G·J using the material's shear modulus.
    pub gj: f64,
    /// Mass per unit length rho·A.
    pub mass_per_length: f64,
    /// Underlying geometric frame properties.
    pub geometric: FrameProperties,
}

impl Section {
    /// Full frame properties including shear centre and warping constant.
    ///
    /// Mirrors Python `Section.calculate_frame_properties()` (without the FEA
    /// shear areas, see `mesh` module for those).
    pub fn frame_properties_full(&self, nu: f64) -> FrameProperties {
        use crate::plastic::warping::WarpingProperties;
        use crate::section_properties::SectionProperties;

        let props = SectionProperties::from_section(self);
        let principal = props.principal_properties();
        let warping = WarpingProperties::from_section(self, nu);

        FrameProperties {
            area: props.area,
            ixx: props.ix,
            iyy: props.iy,
            ixy: props.ixy,
            j: warping.j,
            phi: principal.phi,
            i11: principal.i11,
            i22: principal.i22,
            delta_x: warping.shear_center.x,
            delta_y: warping.shear_center.y,
            iw: warping.iw,
        }
    }

    /// Validate hole topology.
    ///
    /// Checks (all relative to the section's oriented polygons):
    /// 1. All hole vertices lie inside the outer polygon (boundary-touching is
    ///    accepted, matching [`Polygon::contains_point`] on-edge semantics).
    /// 2. No hole edge interacts with the outer boundary (crosses, touches, or
    ///    overlaps).  Boundary-touching by a hole **edge** is rejected even
    ///    though a hole **vertex** on the boundary is accepted in step 1.
    /// 3. No two holes overlap (area overlap) or nest (one contains another).
    /// 4. Holes are oriented CW (negative signed area).
    ///
    /// Returns `Ok(())` if valid, or `Err(description)` on failure.
    pub fn validate(&self) -> Result<(), String> {
        // 1. All hole vertices inside outer
        for (hi, hole) in self.holes.iter().enumerate() {
            for v in &hole.vertices {
                if !self.outer.contains_point(*v) {
                    return Err(format!(
                        "Hole {} vertex {:?} lies outside outer boundary",
                        hi, v
                    ));
                }
            }

            // 2. Hole edge does not cross outer boundary
            for i in 0..hole.vertices.len() {
                let h1 = hole.vertices[i];
                let h2 = hole.vertices[(i + 1) % hole.vertices.len()];
                for j in 0..self.outer.vertices.len() {
                    let o1 = self.outer.vertices[j];
                    let o2 = self.outer.vertices[(j + 1) % self.outer.vertices.len()];
                    if segments_interact(h1, h2, o1, o2) {
                        return Err(format!(
                            "Hole {} edge ({:?}-{:?}) intersects outer boundary",
                            hi, h1, h2
                        ));
                    }
                }
            }
        }

        // 3. Hole-hole: no overlap, no nesting
        let n = self.holes.len();
        for i in 0..n {
            for j in (i + 1)..n {
                let hi = &self.holes[i];
                let hj = &self.holes[j];

                // Check nesting: one hole fully contains another
                let i_contains_j = hj.vertices.iter().all(|v| hi.contains_point(*v));
                let j_contains_i = hi.vertices.iter().all(|v| hj.contains_point(*v));

                if i_contains_j || j_contains_i {
                    return Err(format!(
                        "Holes {} and {} are nested (one contains the other)",
                        i, j
                    ));
                }

                // Check area overlap: if both contain each other's vertices partially,
                // or edges intersect
                for a in 0..hi.vertices.len() {
                    let h1 = hi.vertices[a];
                    let h2 = hi.vertices[(a + 1) % hi.vertices.len()];
                    for b in 0..hj.vertices.len() {
                        let h3 = hj.vertices[b];
                        let h4 = hj.vertices[(b + 1) % hj.vertices.len()];
                        if segments_interact(h1, h2, h3, h4) {
                            return Err(format!("Holes {} and {} have intersecting edges", i, j));
                        }
                    }
                }
            }
        }

        // 4. Orientation check (already enforced by new(), but double-check)
        if self.outer.signed_area() < 0.0 {
            return Err("Outer boundary must be CCW (positive area)".into());
        }
        for (hi, hole) in self.holes.iter().enumerate() {
            if hole.signed_area() > 0.0 {
                return Err(format!("Hole {} must be CW (negative area)", hi));
            }
        }

        Ok(())
    }

    /// Create a section with full topology validation.
    ///
    /// Validates (see [`Section::validate`]):
    /// - All hole vertices lie inside the outer boundary (boundary-touching accepted)
    /// - No two holes overlap or nest (no hole-within-hole)
    /// - No hole edge interacts with the outer boundary (crosses, touches, or
    ///   overlaps); edge-level boundary-touching is rejected
    /// - Orientation is normalised to outer CCW / holes CW
    ///
    /// Returns `Err` with a descriptive message if validation fails.
    pub fn new_validated(outer: Polygon, holes: Vec<Polygon>) -> Result<Self, String> {
        let section = Self::new(outer, holes);
        section.validate()?;
        Ok(section)
    }
}

impl crate::section_library::ParametricSection for Section {
    fn build(&self) -> Section {
        self.clone()
    }

    fn designation(&self) -> String {
        "Section".to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::section_library::ParametricSection;

    #[test]
    fn frame_properties_full_i_section() {
        let i = crate::section_library::steel::ISection::from_designation("IPE300").unwrap();
        let sec = i.build();
        let fp = sec.frame_properties_full(0.3);
        assert!(fp.area > 0.0);
        assert!(fp.iw.abs() > 0.0, "I-section must have warping constant");
        // Doubly symmetric: shear centre at centroid (mesh-level tolerance)
        let c = sec.centroid();
        assert!((fp.delta_x - c.x).abs() < 5e-3);
        assert!((fp.delta_y - c.y).abs() < 5e-3);
        assert!((fp.j / (fp.area * 1e6)).abs() < 1e3); // sanity
    }

    #[test]
    fn geometry_from_points_rectangle() {
        let pts = vec![
            Point::new(0.0, 0.0),
            Point::new(0.2, 0.0),
            Point::new(0.2, 0.1),
            Point::new(0.0, 0.1),
        ];
        let g = crate::geometry::Geometry::from_points(pts, vec![]);
        assert!((g.area() - 0.02).abs() < 1e-12);

        let outer = vec![
            Point::new(0.0, 0.0),
            Point::new(4.0, 0.0),
            Point::new(4.0, 4.0),
            Point::new(0.0, 4.0),
        ];
        let hole = vec![
            Point::new(1.0, 1.0),
            Point::new(3.0, 1.0),
            Point::new(3.0, 3.0),
            Point::new(1.0, 3.0),
        ];
        let g2 = crate::geometry::Geometry::from_points(outer, vec![hole]);
        assert!((g2.area() - 12.0).abs() < 1e-12);
    }

    #[test]
    fn frame_properties_with_material_rejects_invalid() {
        let sec = crate::section_library::primitive::RectangularSection::new(0.1, 0.2).build();
        let mut bad = crate::material::Material::default();
        bad.youngs_modulus = -1.0;
        assert!(sec.frame_properties_with_material(&bad).is_err());
    }

    #[test]
    fn transformed_frame_properties_scale_with_e() {
        let sec = crate::section_library::primitive::RectangularSection::new(0.1, 0.2).build();
        let geo = sec.frame_properties_full(0.3);

        let steel = crate::material::presets::STEEL_S355;
        let t_steel = sec.frame_properties_with_material(&steel).unwrap();
        assert!((t_steel.ea - steel.youngs_modulus * t_steel.area).abs() < 1e-6);
        assert!((t_steel.ei_xx - steel.youngs_modulus * geo.ixx).abs() < 1e-9);
        // G = material.shear_modulus (independent for orthotropic materials)
        let g_expected = steel.shear_modulus;
        assert!((t_steel.gj - g_expected * geo.j).abs() < 1e-3);

        // Aluminium: E roughly 1/3 of steel -> EI scales proportionally.
        let alu = crate::material::Material::new(69e9, 0.33, 2700.0, "alu");
        let t_alu = sec.frame_properties_with_material(&alu).unwrap();
        let ratio = t_alu.ei_xx / t_steel.ei_xx;
        assert!((ratio - alu.youngs_modulus / steel.youngs_modulus).abs() < 1e-9);
        // Mass uses density
        assert!((t_alu.mass_per_length - 2700.0 * t_alu.area).abs() < 1e-9);
    }

    #[test]
    fn section_new_validated_rejects_hole_outside_outer() {
        let outer = crate::geometry::Polygon::new(vec![
            Point::new(0.0, 0.0),
            Point::new(10.0, 0.0),
            Point::new(10.0, 10.0),
            Point::new(0.0, 10.0),
        ]);
        let hole = crate::geometry::Polygon::new(vec![
            Point::new(11.0, 11.0),
            Point::new(12.0, 11.0),
            Point::new(12.0, 12.0),
            Point::new(11.0, 12.0),
        ]);
        let err = Section::new_validated(outer, vec![hole]).unwrap_err();
        assert!(err.contains("outside outer boundary"));
    }

    #[test]
    fn section_new_validated_rejects_nested_holes() {
        let outer = crate::geometry::Polygon::new(vec![
            Point::new(0.0, 0.0),
            Point::new(10.0, 0.0),
            Point::new(10.0, 10.0),
            Point::new(0.0, 10.0),
        ]);
        let hole_outer = crate::geometry::Polygon::new(vec![
            Point::new(1.0, 1.0),
            Point::new(9.0, 1.0),
            Point::new(9.0, 9.0),
            Point::new(1.0, 9.0),
        ]);
        let hole_inner = crate::geometry::Polygon::new(vec![
            Point::new(3.0, 3.0),
            Point::new(5.0, 3.0),
            Point::new(5.0, 5.0),
            Point::new(3.0, 5.0),
        ]);
        let err = Section::new_validated(outer, vec![hole_outer, hole_inner]).unwrap_err();
        assert!(err.contains("nested"));
    }

    #[test]
    fn section_new_validated_rejects_overlapping_holes() {
        let outer = crate::geometry::Polygon::new(vec![
            Point::new(0.0, 0.0),
            Point::new(10.0, 0.0),
            Point::new(10.0, 10.0),
            Point::new(0.0, 10.0),
        ]);
        let hole_a = crate::geometry::Polygon::new(vec![
            Point::new(1.0, 1.0),
            Point::new(5.0, 1.0),
            Point::new(5.0, 5.0),
            Point::new(1.0, 5.0),
        ]);
        let hole_b = crate::geometry::Polygon::new(vec![
            Point::new(3.0, 3.0),
            Point::new(7.0, 3.0),
            Point::new(7.0, 7.0),
            Point::new(3.0, 7.0),
        ]);
        let err = Section::new_validated(outer, vec![hole_a, hole_b]).unwrap_err();
        assert!(err.contains("intersecting edges") || err.contains("nested"));
    }

    #[test]
    fn section_new_validated_accepts_valid_section() {
        let outer = crate::geometry::Polygon::new(vec![
            Point::new(0.0, 0.0),
            Point::new(10.0, 0.0),
            Point::new(10.0, 10.0),
            Point::new(0.0, 10.0),
        ]);
        let hole_a = crate::geometry::Polygon::new(vec![
            Point::new(1.0, 1.0),
            Point::new(4.0, 1.0),
            Point::new(4.0, 4.0),
            Point::new(1.0, 4.0),
        ]);
        let hole_b = crate::geometry::Polygon::new(vec![
            Point::new(6.0, 6.0),
            Point::new(9.0, 6.0),
            Point::new(9.0, 9.0),
            Point::new(6.0, 9.0),
        ]);
        let section = Section::new_validated(outer, vec![hole_a, hole_b]).unwrap();
        assert_eq!(section.holes.len(), 2);
    }

    // -------------------------------------------------------------------------
    // Phase 18.5: GJ must use Material::shear_modulus, not E/(2(1+ν)).
    // -------------------------------------------------------------------------

    /// Helper: build a rectangle and get its frame properties with a material.
    fn rect_frame_props(mat: &crate::material::Material) -> TransformedFrameProperties {
        let sec = crate::section_library::primitive::RectangularSection::new(0.1, 0.2).build();
        sec.frame_properties_with_material(mat).unwrap()
    }

    /// Test A — TIMBER_GL24H GJ regression: GJ must use the stored
    /// `shear_modulus` (0.725 GPa), NOT the isotropic relation E/(2(1+ν))
    /// which would give 4.296 GPa (~5.9× too large).
    #[test]
    fn gj_uses_material_shear_modulus_timber() {
        use crate::material::presets::TIMBER_GL24H;

        let t = rect_frame_props(&TIMBER_GL24H);
        let fp = {
            let sec = crate::section_library::primitive::RectangularSection::new(0.1, 0.2).build();
            sec.frame_properties_full(TIMBER_GL24H.poissons_ratio)
        };

        // GJ must equal material.shear_modulus * J.
        let gj_expected = TIMBER_GL24H.shear_modulus * fp.j;
        assert!(
            (t.gj - gj_expected).abs() < 1e-3,
            "GJ ({:.6e}) must use shear_modulus * J ({:.6e})",
            t.gj,
            gj_expected
        );

        // GJ must NOT equal the isotropic G * J.
        let g_iso = TIMBER_GL24H.youngs_modulus / (2.0 * (1.0 + TIMBER_GL24H.poissons_ratio));
        let gj_iso = g_iso * fp.j;
        assert!(
            (t.gj - gj_iso).abs() > 1e3,
            "GJ ({:.6e}) must NOT use isotropic G * J ({:.6e})",
            t.gj,
            gj_iso
        );
    }

    /// Test B — Custom independent-G material: Material::with_all() with
    /// deliberately non-isotropic E/G/ν must produce GJ = G * J.
    #[test]
    fn gj_uses_independent_shear_modulus() {
        let mat = crate::material::Material::with_all(
            100e9, // E
            10e9,  // G (deliberately non-isotropic: E/(2(1+0.3)) = 38.46 GPa)
            0.30,  // ν
            5000.0, 0.0, 0.0, 0.0, "custom",
        );

        let t = rect_frame_props(&mat);
        let fp = {
            let sec = crate::section_library::primitive::RectangularSection::new(0.1, 0.2).build();
            sec.frame_properties_full(mat.poissons_ratio)
        };

        let gj_expected = mat.shear_modulus * fp.j;
        assert!(
            (t.gj - gj_expected).abs() < 1e-3,
            "GJ ({:.6e}) must use independent G * J ({:.6e})",
            t.gj,
            gj_expected
        );
    }

    /// Test C — Isotropic materials unchanged: for steel/aluminum/concrete
    /// where G ≈ E/(2(1+ν)), GJ results remain the same as before the fix.
    #[test]
    fn gj_isotropic_materials_unchanged() {
        use crate::material::presets::*;

        for mat in &[STEEL_S355, ALUMINUM_6061_T6, CONCRETE_C25_30] {
            let t = rect_frame_props(mat);
            let fp = {
                let sec =
                    crate::section_library::primitive::RectangularSection::new(0.1, 0.2).build();
                sec.frame_properties_full(mat.poissons_ratio)
            };

            // For isotropic materials, shear_modulus ≈ E/(2(1+ν)),
            // so GJ should match both.
            let gj_from_stored = mat.shear_modulus * fp.j;
            let g_iso = mat.youngs_modulus / (2.0 * (1.0 + mat.poissons_ratio));
            let gj_from_iso = g_iso * fp.j;

            assert!(
                (t.gj - gj_from_stored).abs() < 1e-3,
                "{}: GJ ({:.6e}) must use stored G * J ({:.6e})",
                mat.name,
                t.gj,
                gj_from_stored
            );
            // For truly isotropic materials, the two are close.
            assert!(
                (t.gj - gj_from_iso).abs() / gj_from_stored.abs() < 0.01,
                "{}: GJ should be close to isotropic (stored={:.6e}, iso={:.6e})",
                mat.name,
                gj_from_stored,
                gj_from_iso
            );
        }
    }

    /// Test D - Regression guard: no production path may silently recompute
    /// `G` from `E` and `nu` once the material supplies `shear_modulus`.
    ///
    /// Every preset must satisfy `gj == material.shear_modulus * J` to within
    /// round-off. Any path re-deriving `G` from the isotropic relation fails
    /// this for the orthotropic presets (e.g. TIMBER_GL24H).
    #[test]
    fn gj_never_recomputed_from_e_and_nu() {
        use crate::material::presets::*;

        let mats = [
            STEEL_S235,
            STEEL_S275,
            STEEL_S355,
            STEEL_S460,
            STAINLESS_304,
            STAINLESS_316,
            ALUMINUM_6061_T6,
            ALUMINUM_6063_T5,
            ALUMINUM_7075_T6,
            CONCRETE_C25_30,
            CONCRETE_C30_37,
            CONCRETE_C40_50,
            TIMBER_GL24H,
            TITANIUM_GR5,
        ];

        for mat in mats {
            let t = rect_frame_props(&mat);
            let j = t.geometric.j;
            assert!(
                j > 0.0 && j.is_finite(),
                "{}: J must be finite and > 0, got {j}",
                mat.name
            );

            let expected = mat.shear_modulus * j;
            let rel = (t.gj - expected).abs() / expected.abs();
            assert!(
                rel < 1e-12,
                "{}: gj={:.6e} but shear_modulus*J={:.6e} (rel={:.3e}); G was recomputed from E and nu",
                mat.name,
                t.gj,
                expected,
                rel
            );
        }
    }

    /// Test D2 - For a fixed independent `G`, GJ must not depend on `nu`:
    /// the isotropic relation would scale G by 1/(2(1+nu)) and break this.
    #[test]
    fn gj_independent_of_nu_for_fixed_shear_modulus() {
        for nu in [0.2, 0.3, 0.35] {
            let mat = crate::material::Material::with_all(
                200e9,
                1e9,
                nu,
                7850.0,
                1.2e-5,
                355e6,
                510e6,
                "synthetic-g",
            );
            assert!(mat.is_valid(), "synthetic material must be valid");

            let t = rect_frame_props(&mat);
            let expected = mat.shear_modulus * t.geometric.j;
            let rel = (t.gj - expected).abs() / expected.abs();
            assert!(
                rel < 1e-12,
                "nu={nu}: gj={:.6e} but G*J={:.6e} (rel={:.3e})",
                t.gj,
                expected,
                rel
            );
        }
    }
}