Skip to main content

section_properties/
section_properties.rs

1use crate::geometry::{BoundaryExtrema, CompoundGeometry, Geometry, Point};
2use crate::section::Section;
3use std::ops::Deref;
4
5/// Basic geometric properties about the centroidal and global axes.
6#[derive(Debug, Clone, Copy)]
7pub struct GeometricProperties {
8    /// Cross-sectional area (outer minus holes, signed) \[m²\].
9    pub area: f64,
10
11    /// Centroid of the section in global coordinates.
12    pub centroid: Point,
13
14    /// Second moment of area about the centroidal x-axis.
15    pub ix: f64,
16
17    /// Second moment of area about the centroidal y-axis.
18    pub iy: f64,
19
20    /// Product of inertia about the centroidal axes.
21    pub ixy: f64,
22
23    /// Maximum distance from the centroid to the section boundary along Y.
24    pub max_fiber_distance_y: f64,
25
26    /// Maximum distance from the centroid to the section boundary along X.
27    pub max_fiber_distance_x: f64,
28
29    /// Section modulus about x-axis for positive extreme fibre (Ix / y_max).
30    pub zxx_plus: f64,
31    /// Section modulus about x-axis for negative extreme fibre (Ix / |y_min|).
32    pub zxx_minus: f64,
33    /// Section modulus about y-axis for positive extreme fibre (Iy / x_max).
34    pub zyy_plus: f64,
35    /// Section modulus about y-axis for negative extreme fibre (Iy / |x_min|).
36    pub zyy_minus: f64,
37
38    /// Cross-sectional perimeter (outer + holes).
39    pub perimeter: f64,
40
41    /// First moment of area about the global x-axis (∫y dA).
42    pub qx: f64,
43    /// First moment of area about the global y-axis (∫x dA).
44    pub qy: f64,
45
46    /// Second moment of area about the global x-axis.
47    pub ixx_g: f64,
48    /// Second moment of area about the global y-axis.
49    pub iyy_g: f64,
50    /// Product of inertia about the global xy-axis.
51    pub ixy_g: f64,
52}
53
54impl Default for GeometricProperties {
55    fn default() -> Self {
56        Self {
57            area: 0.0,
58            centroid: Point::new(0.0, 0.0),
59            ix: 0.0,
60            iy: 0.0,
61            ixy: 0.0,
62            max_fiber_distance_y: 0.0,
63            max_fiber_distance_x: 0.0,
64            zxx_plus: 0.0,
65            zxx_minus: 0.0,
66            zyy_plus: 0.0,
67            zyy_minus: 0.0,
68            perimeter: 0.0,
69            qx: 0.0,
70            qy: 0.0,
71            ixx_g: 0.0,
72            iyy_g: 0.0,
73            ixy_g: 0.0,
74        }
75    }
76}
77
78/// Principal-axis properties: moments of inertia, angle, and section moduli
79/// about the principal 11-22 axes.
80///
81/// # Convention (matches standard Mohr's circle, diverges from Python)
82///
83/// This library uses the **standard structural-engineering convention** for
84/// principal axes, consistent with Timoshenko, Pilkey, and most FEA codes:
85///
86/// ```text
87///                    y (centroidal)
88///                    |
89///                    |     ╱ axis 11 (i11, major)
90///                    |    ╱
91///                    | φ ╱    φ = angle from x to axis 11 (CCW positive)
92///                    |  ╱
93///                    | ╱
94///                    |╱─────────── x (centroidal)
95///                   ╱|
96///                  ╱ |
97///     axis 22 ───╱  |    axis 22 is perpendicular to axis 11
98///    (i22, minor)    |
99/// ```
100///
101/// | Symbol | Meaning | Formula |
102/// |--------|---------|---------|
103/// | `phi` | Angle from centroidal x-axis to axis 11, CCW positive | `½ atan2(2·I_xy, I_xx − I_yy)` |
104/// | `i11` | Major principal moment (largest) | `(I_xx+I_yy)/2 + Δ` |
105/// | `i22` | Minor principal moment (smallest) | `(I_xx+I_yy)/2 − Δ` |
106/// | `z11` | Section modulus about axis 11 | `i11 / max(|y₂|)` |
107/// | `z22` | Section modulus about axis 22 | `i22 / max(|x₁|)` |
108///
109/// **Coordinate transformation** (global → principal):
110/// ```text
111/// x₁ = (x − x_c) cos φ + (y − y_c) sin φ    // along axis 11
112/// y₂ = −(x − x_c) sin φ + (y − y_c) cos φ   // along axis 22
113/// ```
114///
115/// **Section moduli** use the *perpendicular* distance from each axis:
116/// - `z11 = i11 / |y₂|_max` (y₂ is perpendicular to axis 11)
117/// - `z22 = i22 / |x₁|_max` (x₁ is perpendicular to axis 22)
118///
119/// ## Divergence from Python `sectionproperties`
120///
121/// Python computes `phi_py = atan2(I_xx − i11, I_xy)`, which equals
122/// `−φ` (our phi).  Python's coordinate transform then projects onto
123/// `(cos(−φ), sin(−φ))`, placing its "x11" axis along the *minor*
124/// principal direction when `I_xx > I_yy` and `I_xy > 0`.  Despite this,
125/// Python's `z11 = i11 / |y22_max|` still produces correct section
126/// moduli because the perpendicular distance from the opposite axis is
127/// the same after taking absolute values — but the **sign of phi** and
128/// the **direction of x11/y22** differ.
129///
130/// To convert between conventions: `phi_python = −phi_rust`.
131#[derive(Debug, Clone, Copy)]
132pub struct PrincipalProperties {
133    /// Major principal second moment of area (centroidal). Always `≥ i22`.
134    pub i11: f64,
135
136    /// Minor principal second moment of area (centroidal). Always `≤ i11`.
137    pub i22: f64,
138
139    /// Angle from the centroidal x-axis to axis 11 (major), measured
140    /// **counter-clockwise positive** in radians.  Range: `[−π, π]`.
141    ///
142    /// Computed as `½ atan2(2·I_xy, I_xx − I_yy)` (standard Mohr's circle).
143    pub phi: f64,
144
145    /// Section modulus about axis 11 for positive extreme fibre.
146    /// `z11_plus = i11 / |y₂_max|` where `y₂_max > 0`.
147    pub z11_plus: f64,
148    /// Section modulus about axis 11 for negative extreme fibre.
149    /// `z11_minus = i11 / |y₂_min|` where `y₂_min < 0`.
150    pub z11_minus: f64,
151    /// Section modulus about axis 22 for positive extreme fibre.
152    /// `z22_plus = i22 / |x₁_max|` where `x₁_max > 0`.
153    pub z22_plus: f64,
154    /// Section modulus about axis 22 for negative extreme fibre.
155    /// `z22_minus = i22 / |x₁_min|` where `x₁_min < 0`.
156    pub z22_minus: f64,
157}
158
159impl Default for PrincipalProperties {
160    fn default() -> Self {
161        Self {
162            i11: 0.0,
163            i22: 0.0,
164            phi: 0.0,
165            z11_plus: 0.0,
166            z11_minus: 0.0,
167            z22_plus: 0.0,
168            z22_minus: 0.0,
169        }
170    }
171}
172
173/// Radii of gyration about the centroidal and principal axes.
174#[derive(Debug, Clone, Copy)]
175pub struct GyrationProperties {
176    /// Radius of gyration about the centroidal x-axis.
177    pub rx: f64,
178
179    /// Radius of gyration about the centroidal y-axis.
180    pub ry: f64,
181
182    /// Radius of gyration about the principal 11-axis.
183    pub r11: f64,
184
185    /// Radius of gyration about the principal 22-axis.
186    pub r22: f64,
187
188    /// Polar radius of gyration.
189    pub polar: f64,
190}
191
192impl Default for GyrationProperties {
193    fn default() -> Self {
194        Self {
195            rx: 0.0,
196            ry: 0.0,
197            r11: 0.0,
198            r22: 0.0,
199            polar: 0.0,
200        }
201    }
202}
203
204/// Composite section properties: geometric + principal + gyration.
205///
206/// Field access is split across three sub-structs:
207/// - [`GeometricProperties`] (via `Deref`: `props.area`, `props.ix`, …)
208/// - [`PrincipalProperties`] (via `props.principal.i11`, `props.principal.phi`, …)
209/// - [`GyrationProperties`] (via `props.gyration.rx`, `props.gyration.r11`, …)
210#[derive(Debug, Clone, Copy, Default)]
211pub struct SectionProperties {
212    pub geometric: GeometricProperties,
213    pub principal: PrincipalProperties,
214    pub gyration: GyrationProperties,
215}
216
217impl Deref for SectionProperties {
218    type Target = GeometricProperties;
219    fn deref(&self) -> &GeometricProperties {
220        &self.geometric
221    }
222}
223
224impl SectionProperties {
225    /// Compute section properties from a `CompoundGeometry` (one or more
226    /// independent regions, each with an outer boundary and optional holes).
227    ///
228    /// Regions are aggregated using the composite-area (parallel-axis) method:
229    /// each polygon contributes its signed area, first moments, and second
230    /// moments about the global axes; the global centroid is then found and
231    /// centroidal properties are obtained via the parallel-axis theorem.
232    ///
233    /// # Panics
234    ///
235    /// Panics if the net section area is zero or near-zero.  Use
236    /// [`try_from_compound`](Self::try_from_compound) for a fallible version
237    /// that returns `Err` instead of panicking.
238    pub fn from_compound(compound: &CompoundGeometry) -> Self {
239        Self::try_from_compound(compound).expect("Section area is too small to compute properties")
240    }
241
242    /// Fallible version of [`from_compound`](Self::from_compound).
243    ///
244    /// Returns `Err` if the net section area is zero or near-zero
245    /// (degenerate geometry where outer area equals total hole area).
246    pub fn try_from_compound(compound: &CompoundGeometry) -> Result<Self, String> {
247        let polygons: Vec<crate::geometry::Polygon> = compound.polygons();
248
249        // Pick a reference point near the geometry (first vertex of first polygon).
250        // All computations use coordinates shifted by this point to avoid
251        // precision loss in the shoelace formula for sections far from the origin.
252        let (x0, y0) = if let Some(first) = polygons.first() {
253            if let Some(v) = first.vertices.first() {
254                (v.x, v.y)
255            } else {
256                (0.0, 0.0)
257            }
258        } else {
259            (0.0, 0.0)
260        };
261
262        // --- Pass 1: area and first moments (shifted) ---
263        let mut area = 0.0;
264        let mut qx_shifted = 0.0; // Σ A_i * (cx_i - x0)
265        let mut qy_shifted = 0.0; // Σ A_i * (cy_i - y0)
266
267        for poly in &polygons {
268            for i in 0..poly.vertices.len() {
269                let p1 = poly.vertices[i];
270                let p2 = poly.vertices[(i + 1) % poly.vertices.len()];
271
272                let x1 = p1.x - x0;
273                let y1 = p1.y - y0;
274                let x2 = p2.x - x0;
275                let y2 = p2.y - y0;
276
277                let cross = x1 * y2 - x2 * y1;
278
279                area += cross;
280                qx_shifted += (x1 + x2) * cross;
281                qy_shifted += (y1 + y2) * cross;
282            }
283        }
284        area *= 0.5;
285        qx_shifted /= 6.0;
286        qy_shifted /= 6.0;
287
288        if area.abs() <= f64::EPSILON {
289            return Err("Section area is too small to compute properties".into());
290        }
291
292        // Composite centroid: cx = x0 + qx_shifted / area, etc.
293        let centroid = Point::new(x0 + qx_shifted / area, y0 + qy_shifted / area);
294
295        // --- Pass 2: centroidal inertia via direct integration about centroid ---
296        // Shift all vertices relative to the composite centroid before computing
297        // moments.  This avoids catastrophic cancellation that occurs when
298        // subtracting large `Ix_global - A * cy²` values for sections far from
299        // the origin.
300        let mut ix_c = 0.0;
301        let mut iy_c = 0.0;
302        let mut ixy_c = 0.0;
303        for poly in &polygons {
304            for i in 0..poly.vertices.len() {
305                let p1 = poly.vertices[i];
306                let p2 = poly.vertices[(i + 1) % poly.vertices.len()];
307
308                let x1 = p1.x - centroid.x;
309                let y1 = p1.y - centroid.y;
310                let x2 = p2.x - centroid.x;
311                let y2 = p2.y - centroid.y;
312
313                let cross = x1 * y2 - x2 * y1;
314
315                ix_c += (y1 * y1 + y1 * y2 + y2 * y2) * cross;
316                iy_c += (x1 * x1 + x1 * x2 + x2 * x2) * cross;
317                ixy_c += (x1 * y2 + 2.0 * x1 * y1 + 2.0 * x2 * y2 + x2 * y1) * cross;
318            }
319        }
320        ix_c /= 12.0;
321        iy_c /= 12.0;
322        ixy_c /= 24.0;
323
324        // Global inertia (for struct fields) via reverse parallel-axis.
325        // This is addition, not subtraction — no cancellation.
326        let ix = ix_c + area * centroid.y * centroid.y;
327        let iy = iy_c + area * centroid.x * centroid.x;
328        let ixy = ixy_c + area * centroid.x * centroid.y;
329
330        // Maximum fiber distances measure from the centroid to the extreme
331        // boundary of the section (used for elastic section modulus).
332        // Track positive and negative extremes separately (Python convention).
333        let all_boundary: Vec<&dyn BoundaryExtrema> =
334            polygons.iter().map(|p| p as &dyn BoundaryExtrema).collect();
335        let (y_min, y_max) = all_boundary
336            .iter()
337            .map(|b| b.extreme_y(centroid))
338            .fold((f64::INFINITY, f64::NEG_INFINITY), |(mn, mx), (lo, hi)| {
339                (mn.min(lo), mx.max(hi))
340            });
341        let (x_min, x_max) = all_boundary
342            .iter()
343            .map(|b| b.extreme_x(centroid))
344            .fold((f64::INFINITY, f64::NEG_INFINITY), |(mn, mx), (lo, hi)| {
345                (mn.min(lo), mx.max(hi))
346            });
347
348        let max_fiber_y = y_max.abs().max(y_min.abs());
349        let max_fiber_x = x_max.abs().max(x_min.abs());
350
351        // Section moduli about centroidal axes (positive/negative fibres)
352        let zxx_plus = if y_max.abs() > 1e-15 {
353            ix_c / y_max.abs()
354        } else {
355            0.0
356        };
357        let zxx_minus = if y_min.abs() > 1e-15 {
358            ix_c / y_min.abs()
359        } else {
360            0.0
361        };
362        let zyy_plus = if x_max.abs() > 1e-15 {
363            iy_c / x_max.abs()
364        } else {
365            0.0
366        };
367        let zyy_minus = if x_min.abs() > 1e-15 {
368            iy_c / x_min.abs()
369        } else {
370            0.0
371        };
372
373        // Principal axis properties (standard Mohr's circle convention).
374        //
375        // φ = ½ atan2(2·I_xy, I_xx − I_yy)
376        //
377        // This gives the angle from the centroidal x-axis to axis 11
378        // (major principal axis), measured CCW positive.
379        //
380        // Coordinate transformation (global → principal):
381        //   x₁ = dx·cos(φ) + dy·sin(φ)   // along axis 11
382        //   y₂ = −dx·sin(φ) + dy·cos(φ)  // along axis 22 (⊥ to axis 11)
383        //
384        // Section moduli use perpendicular distances:
385        //   z11 = i11 / |y₂|_max   (y₂ is distance from axis 11)
386        //   z22 = i22 / |x₁|_max   (x₁ is distance from axis 22)
387        let principal = {
388            let avg = (ix_c + iy_c) * 0.5;
389            let diff = (ix_c - iy_c) * 0.5;
390            let radius = (diff * diff + ixy_c * ixy_c).sqrt();
391            let i11 = avg + radius;
392            let i22 = avg - radius;
393            let phi = 0.5 * (2.0 * ixy_c).atan2(ix_c - iy_c);
394            (i11, i22, phi)
395        };
396        let (i11, i22, phi) = principal;
397        let cos_phi = phi.cos();
398        let sin_phi = phi.sin();
399
400        // Project extreme boundary points onto principal axes.
401        //
402        // dir_11 = (cos φ, sin φ)  — unit vector along axis 11 (major)
403        // dir_22 = (−sin φ, cos φ) — unit vector along axis 22 (minor, ⊥ to 11)
404        //
405        // x₁ = dot(P − centroid, dir_11)  — signed distance along axis 11
406        // y₂ = dot(P − centroid, dir_22)  — signed distance along axis 22
407        let dir_11 = Point::new(cos_phi, sin_phi);
408        let dir_22 = Point::new(-sin_phi, cos_phi);
409        let (x1_min, x1_max) = all_boundary
410            .iter()
411            .map(|b| b.extreme_distances(centroid, dir_11))
412            .fold((f64::INFINITY, f64::NEG_INFINITY), |(mn, mx), (lo, hi)| {
413                (mn.min(lo), mx.max(hi))
414            });
415        let (y2_min, y2_max) = all_boundary
416            .iter()
417            .map(|b| b.extreme_distances(centroid, dir_22))
418            .fold((f64::INFINITY, f64::NEG_INFINITY), |(mn, mx), (lo, hi)| {
419                (mn.min(lo), mx.max(hi))
420            });
421
422        // Section moduli: z = I / c
423        //
424        // For axis 11: c₁ = max|y₂| (perpendicular distance from axis 11)
425        // For axis 22: c₂ = max|x₁| (perpendicular distance from axis 22)
426        //
427        // z11 = i11 / c₁, z22 = i22 / c₂
428        let z11_plus = if y2_max.abs() > 1e-15 {
429            i11 / y2_max.abs()
430        } else {
431            0.0
432        };
433        let z11_minus = if y2_min.abs() > 1e-15 {
434            i11 / y2_min.abs()
435        } else {
436            0.0
437        };
438        let z22_plus = if x1_max.abs() > 1e-15 {
439            i22 / x1_max.abs()
440        } else {
441            0.0
442        };
443        let z22_minus = if x1_min.abs() > 1e-15 {
444            i22 / x1_min.abs()
445        } else {
446            0.0
447        };
448
449        // Perimeter (sum of outer + holes across all regions)
450        let perimeter = polygons.iter().map(|p| p.perimeter()).sum::<f64>();
451
452        // Radii of gyration
453        let rx = (ix_c / area).sqrt();
454        let ry = (iy_c / area).sqrt();
455        let r11 = (i11 / area).sqrt();
456        let r22 = (i22 / area).sqrt();
457
458        Ok(Self {
459            geometric: GeometricProperties {
460                area,
461                centroid,
462                ix: ix_c,
463                iy: iy_c,
464                ixy: ixy_c,
465                max_fiber_distance_y: max_fiber_y,
466                max_fiber_distance_x: max_fiber_x,
467                zxx_plus,
468                zxx_minus,
469                zyy_plus,
470                zyy_minus,
471                perimeter,
472                qx: area * centroid.y,
473                qy: area * centroid.x,
474                ixx_g: ix,
475                iyy_g: iy,
476                ixy_g: ixy,
477            },
478            principal: PrincipalProperties {
479                i11,
480                i22,
481                phi,
482                z11_plus,
483                z11_minus,
484                z22_plus,
485                z22_minus,
486            },
487            gyration: GyrationProperties {
488                rx,
489                ry,
490                r11,
491                r22,
492                polar: ((ix_c + iy_c) / area).sqrt(),
493            },
494        })
495    }
496
497    /// Compute section properties from a single `Geometry` (one region with
498    /// optional holes and transforms).
499    ///
500    /// # Panics
501    ///
502    /// Panics if the net section area is zero or near-zero.  Use
503    /// [`try_from_geometry`](Self::try_from_geometry) for a fallible version.
504    pub fn from_geometry(geometry: &Geometry) -> Self {
505        Self::from_compound(&CompoundGeometry::new(vec![geometry.clone()]))
506    }
507
508    /// Fallible version of [`from_geometry`](Self::from_geometry).
509    ///
510    /// Returns `Err` if the net section area is zero or near-zero.
511    pub fn try_from_geometry(geometry: &Geometry) -> Result<Self, String> {
512        Self::try_from_compound(&CompoundGeometry::new(vec![geometry.clone()]))
513    }
514
515    /// Compute section properties from a `Section` (outer boundary + holes).
516    ///
517    /// This is a convenience wrapper that delegates to [`from_compound`](Self::from_compound); the
518    /// section is treated as a single-region compound geometry.
519    ///
520    /// # Panics
521    ///
522    /// Panics if the net section area is zero or near-zero.  Use
523    /// [`try_from_section`](Self::try_from_section) for a fallible version.
524    ///
525    /// # Example
526    ///
527    /// ```rust
528    /// use section_properties::{Point, Polygon, Section, SectionProperties};
529    ///
530    /// let outer = Polygon::new(vec![
531    ///     Point::new(0.0, 0.0),
532    ///     Point::new(10.0, 0.0),
533    ///     Point::new(10.0, 5.0),
534    ///     Point::new(0.0, 5.0),
535    /// ]);
536    /// let section = Section::new(outer, Vec::new());
537    /// let props = SectionProperties::from_section(&section);
538    /// assert!((props.area - 50.0).abs() < 1e-10);
539    /// ```
540    pub fn from_section(section: &Section) -> Self {
541        Self::from_compound(&CompoundGeometry::from(section.clone()))
542    }
543
544    /// Fallible version of [`from_section`](Self::from_section).
545    ///
546    /// Returns `Err` if the net section area is zero or near-zero
547    /// (degenerate section where outer area equals total hole area).
548    pub fn try_from_section(section: &Section) -> Result<Self, String> {
549        Self::try_from_compound(&CompoundGeometry::from(section.clone()))
550    }
551
552    /// Returns `(i11, i22, phi)`.
553    ///
554    /// - `i11`: major (largest) principal second moment of area.
555    /// - `i22`: minor (smallest) principal second moment of area.
556    /// - `phi`: angle from centroidal x-axis to axis 11, CCW positive, radians.
557    pub fn principal_moments(&self) -> (f64, f64, f64) {
558        (self.principal.i11, self.principal.i22, self.principal.phi)
559    }
560
561    pub fn principal_properties(&self) -> PrincipalProperties {
562        self.principal
563    }
564
565    /// Radius of gyration about centroidal axes: (rx, ry, polar).
566    pub fn radius_of_gyration(&self) -> (f64, f64, f64) {
567        (self.gyration.rx, self.gyration.ry, self.gyration.polar)
568    }
569
570    pub fn gyration_properties(&self) -> GyrationProperties {
571        self.gyration
572    }
573
574    /// Maximum fiber distance from centroid in Y direction (for section modulus).
575    pub fn max_fiber_distance_y(&self) -> f64 {
576        self.geometric.max_fiber_distance_y
577    }
578
579    /// Maximum fiber distance from centroid in X direction (for section modulus).
580    pub fn max_fiber_distance_x(&self) -> f64 {
581        self.geometric.max_fiber_distance_x
582    }
583
584    /// Elastic section modulus about the x-axis (minimum of plus/minus).
585    pub fn section_modulus_x(&self) -> f64 {
586        self.geometric.zxx_plus.min(self.geometric.zxx_minus)
587    }
588
589    /// Elastic section modulus about the y-axis (minimum of plus/minus).
590    pub fn section_modulus_y(&self) -> f64 {
591        self.geometric.zyy_plus.min(self.geometric.zyy_minus)
592    }
593
594    /// Section modulus about the 11-axis (minimum of plus/minus).
595    pub fn section_modulus_11(&self) -> f64 {
596        self.principal.z11_plus.min(self.principal.z11_minus)
597    }
598
599    /// Section modulus about the 22-axis (minimum of plus/minus).
600    pub fn section_modulus_22(&self) -> f64 {
601        self.principal.z22_plus.min(self.principal.z22_minus)
602    }
603
604    /// Format all computed properties as an aligned text table.
605    ///
606    /// Mirrors Python `Section.print_results()` (geometric + frame sections).
607    pub fn format_results(&self) -> String {
608        let mut s = String::new();
609        let row = |s: &mut String, name: &str, value: f64| {
610            s.push_str(&format!("  {:<24}{:>14.6e}\n", name, value));
611        };
612
613        s.push_str("Section Properties:\n");
614        s.push_str("===================\n");
615        row(&mut s, "Area", self.area);
616        row(&mut s, "Perimeter", self.perimeter);
617        s.push('\n');
618
619        s.push_str("Centroid:\n");
620        row(&mut s, "cx", self.centroid.x);
621        row(&mut s, "cy", self.centroid.y);
622        s.push('\n');
623
624        s.push_str("Second Moments of Area:\n");
625        row(&mut s, "Ixx (about cx)", self.ix);
626        row(&mut s, "Iyy (about cy)", self.iy);
627        row(&mut s, "Ixy", self.ixy);
628        s.push('\n');
629        s.push_str("Principal Axes:\n");
630        row(&mut s, "I11 (major)", self.principal.i11);
631        row(&mut s, "I22 (minor)", self.principal.i22);
632        let phi_deg = self.principal.phi.to_degrees();
633        row(&mut s, "Phi (x→11, CCW°)", phi_deg);
634        s.push('\n');
635
636        s.push_str("Section Moduli:\n");
637        row(&mut s, "Zxx+", self.zxx_plus);
638        row(&mut s, "Zxx-", self.zxx_minus);
639        row(&mut s, "Zyy+", self.zyy_plus);
640        row(&mut s, "Zyy-", self.zyy_minus);
641        row(&mut s, "Z11+", self.principal.z11_plus);
642        row(&mut s, "Z11-", self.principal.z11_minus);
643        row(&mut s, "Z22+", self.principal.z22_plus);
644        row(&mut s, "Z22-", self.principal.z22_minus);
645        s.push('\n');
646
647        s.push_str("Radii of Gyration:\n");
648        row(&mut s, "rx", self.gyration.rx);
649        row(&mut s, "ry", self.gyration.ry);
650        row(&mut s, "r11", self.gyration.r11);
651        row(&mut s, "r22", self.gyration.r22);
652        row(&mut s, "rp (polar)", self.gyration.polar);
653
654        s
655    }
656
657    /// Mass per unit length: area * density [kg/m].
658    ///
659    /// Mirrors Python `Section.get_mass()`.
660    pub fn mass(&self, density: f64) -> f64 {
661        self.area * density
662    }
663    /// Print the properties table to stdout.
664    ///
665    /// Mirrors Python `Section.print_results()`.
666    pub fn print_results(&self) {
667        print!("{}", self.format_results());
668    }
669}
670
671#[cfg(test)]
672mod tests {
673    use super::*;
674    use crate::geometry::{Point, Polygon};
675
676    fn rectangle(width: f64, height: f64) -> Section {
677        let hw = width * 0.5;
678        let hh = height * 0.5;
679        let poly = Polygon::new(vec![
680            Point::new(-hw, -hh),
681            Point::new(hw, -hh),
682            Point::new(hw, hh),
683            Point::new(-hw, hh),
684        ]);
685        Section::new(poly, vec![])
686    }
687
688    fn tee_section() -> Section {
689        // T-section: flange 0.2 x 0.02 at top, web 0.02 x 0.08 below.
690        let poly = Polygon::new(vec![
691            Point::new(-0.1, 0.10),
692            Point::new(0.1, 0.10),
693            Point::new(0.1, 0.08),
694            Point::new(0.01, 0.08),
695            Point::new(0.01, 0.0),
696            Point::new(-0.01, 0.0),
697            Point::new(-0.01, 0.08),
698            Point::new(-0.1, 0.08),
699        ]);
700        Section::new(poly, vec![])
701    }
702
703    #[test]
704    fn symmetric_section_equal_plus_minus_moduli() {
705        let props = SectionProperties::from_section(&rectangle(0.1, 0.2));
706        assert!(
707            (props.zxx_plus - props.zxx_minus).abs() < 1e-12,
708            "symmetric section should have zxx_plus == zxx_minus"
709        );
710        assert!(
711            (props.zyy_plus - props.zyy_minus).abs() < 1e-12,
712            "symmetric section should have zyy_plus == zyy_minus"
713        );
714    }
715
716    #[test]
717    fn format_results_contains_sections() {
718        let props = SectionProperties::from_section(&rectangle(0.1, 0.2));
719        let table = props.format_results();
720        assert!(table.contains("Section Properties:"));
721        assert!(table.contains("Second Moments of Area:"));
722        assert!(table.contains("Radii of Gyration:"));
723        // area row present with scientific notation
724        assert!(table.contains("Area"));
725    }
726    #[test]
727    fn rectangular_section_modulus_values() {
728        let b = 0.1_f64;
729        let h = 0.2_f64;
730        let props = SectionProperties::from_section(&rectangle(b, h));
731        let ix = b * h.powi(3) / 12.0;
732        let z_expected = ix / (h * 0.5);
733        assert!((props.zxx_plus - z_expected).abs() / z_expected < 1e-10);
734        assert!((props.zxx_minus - z_expected).abs() / z_expected < 1e-10);
735        assert!((props.section_modulus_x() - z_expected).abs() / z_expected < 1e-10);
736    }
737
738    #[test]
739    fn asymmetric_section_unequal_plus_minus_moduli() {
740        let props = SectionProperties::from_section(&tee_section());
741        assert!(
742            (props.zxx_plus - props.zxx_minus).abs() > 1e-6,
743            "T-section should have zxx_plus != zxx_minus"
744        );
745        // Flange is at top (y > centroid), web extends downward.
746        // y_max (positive) is smaller than |y_min| (negative), so zxx_plus > zxx_minus.
747        assert!(
748            props.zxx_plus > props.zxx_minus,
749            "T-section: zxx_plus should exceed zxx_minus (top fibre closer to centroid)"
750        );
751    }
752
753    #[test]
754    fn section_modulus_x_is_min_of_plus_minus() {
755        let props = SectionProperties::from_section(&tee_section());
756        let z_min = props.zxx_plus.min(props.zxx_minus);
757        assert!((props.section_modulus_x() - z_min).abs() < 1e-12);
758    }
759
760    #[test]
761    fn principal_moduli_match_centroidal_for_symmetric_section() {
762        let props = SectionProperties::from_section(&rectangle(0.1, 0.2));
763        assert!((props.principal.z11_plus - props.zxx_plus).abs() / props.zxx_plus < 1e-10);
764        assert!((props.principal.z11_minus - props.zxx_minus).abs() / props.zxx_minus < 1e-10);
765        assert!((props.principal.z22_plus - props.zyy_plus).abs() / props.zyy_plus < 1e-10);
766        assert!((props.principal.z22_minus - props.zyy_minus).abs() / props.zyy_minus < 1e-10);
767    }
768
769    #[test]
770    fn tee_section_modulus_analytical_check() {
771        let props = SectionProperties::from_section(&tee_section());
772        // Area = 0.2*0.02 + 0.02*0.08 = 0.0056
773        let area = 0.0056_f64;
774        // Centroid y (from bottom): (0.004*0.09 + 0.0016*0.04) / 0.0056
775        let yc = (0.004 * 0.09 + 0.0016 * 0.04) / area;
776        // Ix about centroid (parallel-axis theorem)
777        let ix_flange = 0.2 * 0.02_f64.powi(3) / 12.0 + 0.004 * (0.09 - yc).powi(2);
778        let ix_web = 0.02 * 0.08_f64.powi(3) / 12.0 + 0.0016 * (0.04 - yc).powi(2);
779        let ix = ix_flange + ix_web;
780        let y_top = 0.10 - yc;
781        let y_bot = yc;
782        let z_plus = ix / y_top;
783        let z_minus = ix / y_bot;
784        assert!((props.zxx_plus - z_plus).abs() / z_plus < 1e-6);
785        assert!((props.zxx_minus - z_minus).abs() / z_minus < 1e-6);
786        assert!((props.area - area).abs() / area < 1e-10);
787    }
788
789    #[test]
790    fn perimeter_rectangular() {
791        let props = SectionProperties::from_section(&rectangle(0.1, 0.2));
792        let expected = 2.0 * (0.1 + 0.2);
793        assert!((props.perimeter - expected).abs() / expected < 1e-10);
794    }
795
796    #[test]
797    fn global_moments_and_first_moments() {
798        // Rectangle offset from origin
799        let poly = Polygon::new(vec![
800            Point::new(1.0, 2.0),
801            Point::new(1.1, 2.0),
802            Point::new(1.1, 2.2),
803            Point::new(1.0, 2.2),
804        ]);
805        let section = Section::new(poly, vec![]);
806        let props = SectionProperties::from_section(&section);
807
808        let b = 0.1_f64;
809        let h = 0.2_f64;
810        let cx = 1.05_f64;
811        let cy = 2.1_f64;
812        let area = b * h;
813
814        // First moments about global axes
815        assert!((props.qx - area * cy).abs() / (area * cy) < 1e-10);
816        assert!((props.qy - area * cx).abs() / (area * cx) < 1e-10);
817
818        // Global second moments
819        let ixx_g_expected = b * h.powi(3) / 12.0 + area * cy.powi(2);
820        let iyy_g_expected = h * b.powi(3) / 12.0 + area * cx.powi(2);
821        let ixy_g_expected = area * cx * cy; // Ixy_c=0 + A*cx*cy
822        assert!((props.ixx_g - ixx_g_expected).abs() / ixx_g_expected < 1e-10);
823        assert!((props.iyy_g - iyy_g_expected).abs() / iyy_g_expected < 1e-10);
824        assert!((props.ixy_g - ixy_g_expected).abs() / ixy_g_expected < 1e-10);
825    }
826
827    #[test]
828    fn principal_and_gyration_fields() {
829        let props = SectionProperties::from_section(&rectangle(0.1, 0.2));
830        let area = 0.1 * 0.2;
831
832        // For rectangle: I11 = Ix (if h > b), I22 = Iy
833        let i11_expected = 0.1 * 0.2_f64.powi(3) / 12.0;
834        let i22_expected = 0.2 * 0.1_f64.powi(3) / 12.0;
835        assert!((props.principal.i11 - i11_expected).abs() / i11_expected < 1e-10);
836        assert!((props.principal.i22 - i22_expected).abs() / i22_expected < 1e-10);
837
838        // Principal angle ~ 0 for doubly-symmetric section
839        assert!(props.principal.phi.abs() < 1e-10);
840
841        // Radii of gyration
842        assert!((props.gyration.rx - (props.ix / area).sqrt()).abs() < 1e-12);
843        assert!((props.gyration.ry - (props.iy / area).sqrt()).abs() < 1e-12);
844        assert!((props.gyration.r11 - (props.principal.i11 / area).sqrt()).abs() < 1e-12);
845        assert!((props.gyration.r22 - (props.principal.i22 / area).sqrt()).abs() < 1e-12);
846    }
847
848    // ---- CompoundGeometry / multi-region tests ----
849
850    use crate::geometry::{CompoundGeometry, Geometry};
851
852    fn rect_polygon(width: f64, height: f64, cx: f64, cy: f64) -> Polygon {
853        let hw = width * 0.5;
854        let hh = height * 0.5;
855        Polygon::new(vec![
856            Point::new(cx - hw, cy - hh),
857            Point::new(cx + hw, cy - hh),
858            Point::new(cx + hw, cy + hh),
859            Point::new(cx - hw, cy + hh),
860        ])
861    }
862
863    #[test]
864    fn from_section_and_from_compound_agree_for_single_region() {
865        let section = rectangle(0.1, 0.2);
866        let props_section = SectionProperties::from_section(&section);
867        let compound = CompoundGeometry::from(section.clone());
868        let props_compound = SectionProperties::from_compound(&compound);
869        assert!((props_section.area - props_compound.area).abs() < 1e-15);
870        assert!((props_section.ix - props_compound.ix).abs() < 1e-15);
871        assert!((props_section.iy - props_compound.iy).abs() < 1e-15);
872        assert!((props_section.ixy - props_compound.ixy).abs() < 1e-15);
873        assert!((props_section.centroid.x - props_compound.centroid.x).abs() < 1e-15);
874        assert!((props_section.centroid.y - props_compound.centroid.y).abs() < 1e-15);
875    }
876
877    #[test]
878    fn from_geometry_matches_from_section() {
879        let section = rectangle(0.1, 0.2);
880        let props_section = SectionProperties::from_section(&section);
881        let geometry = Geometry::from_section(&section);
882        let props_geometry = SectionProperties::from_geometry(&geometry);
883        assert!((props_section.area - props_geometry.area).abs() < 1e-15);
884        assert!((props_section.ix - props_geometry.ix).abs() < 1e-15);
885        assert!((props_section.iy - props_geometry.iy).abs() < 1e-15);
886    }
887
888    #[test]
889    fn two_disjoint_rectangles_area_and_centroid() {
890        // Two 0.1 x 0.2 rectangles side by side, gap 0.05.
891        // Left centroid at x=-0.075, right at x=+0.075.
892        let g1 = Geometry::new(rect_polygon(0.1, 0.2, -0.075, 0.0), vec![]);
893        let g2 = Geometry::new(rect_polygon(0.1, 0.2, 0.075, 0.0), vec![]);
894        let compound = CompoundGeometry::new(vec![g1, g2]);
895        let props = SectionProperties::from_compound(&compound);
896
897        let area_each = 0.1 * 0.2;
898        assert!((props.area - 2.0 * area_each).abs() / (2.0 * area_each) < 1e-12);
899        // Symmetric about y-axis => centroid at origin
900        assert!(props.centroid.x.abs() < 1e-12);
901        assert!(props.centroid.y.abs() < 1e-12);
902    }
903
904    #[test]
905    fn two_disjoint_rectangles_moment_of_inertia() {
906        // Two 0.1 x 0.2 rectangles, centroids at x = ±0.075.
907        // Iy_total = 2 * (Iy_local + A * d²) where d = 0.075.
908        let g1 = Geometry::new(rect_polygon(0.1, 0.2, -0.075, 0.0), vec![]);
909        let g2 = Geometry::new(rect_polygon(0.1, 0.2, 0.075, 0.0), vec![]);
910        let compound = CompoundGeometry::new(vec![g1, g2]);
911        let props = SectionProperties::from_compound(&compound);
912
913        let b = 0.1_f64;
914        let h = 0.2_f64;
915        let a = b * h;
916        let d = 0.075_f64;
917        let iy_local = h * b.powi(3) / 12.0;
918        let iy_expected = 2.0 * (iy_local + a * d * d);
919        assert!((props.iy - iy_expected).abs() / iy_expected < 1e-10);
920
921        // Ix: both share same y-centroid (0), so Ix = 2 * Ix_local
922        let ix_local = b * h.powi(3) / 12.0;
923        let ix_expected = 2.0 * ix_local;
924        assert!((props.ix - ix_expected).abs() / ix_expected < 1e-10);
925    }
926
927    #[test]
928    fn compound_with_hole_in_one_region() {
929        // Region 1: solid 0.2 x 0.2 square centred at origin.
930        // Region 2: 0.2 x 0.2 square with a 0.1 x 0.1 hole, centred at (0.3, 0).
931        let outer1 = rect_polygon(0.2, 0.2, 0.0, 0.0);
932        let g1 = Geometry::new(outer1, vec![]);
933
934        let outer2 = rect_polygon(0.2, 0.2, 0.3, 0.0);
935        let hole2 = rect_polygon(0.1, 0.1, 0.3, 0.0);
936        let g2 = Geometry::new(outer2, vec![hole2]);
937
938        let compound = CompoundGeometry::new(vec![g1, g2]);
939        let props = SectionProperties::from_compound(&compound);
940
941        let area_expected = 0.2 * 0.2 + (0.2 * 0.2 - 0.1 * 0.1);
942        assert!((props.area - area_expected).abs() / area_expected < 1e-10);
943
944        // Centroid: region 1 area 0.04 at x=0, region 2 net area 0.03 at x=0.3
945        let cx_expected = (0.04 * 0.0 + 0.03 * 0.3) / 0.07;
946        assert!((props.centroid.x - cx_expected).abs() < 1e-12);
947        assert!(props.centroid.y.abs() < 1e-12);
948    }
949
950    #[test]
951    fn compound_with_transform_translate() {
952        // A 0.1 x 0.2 rectangle built at origin, then translated to (1.0, 2.0).
953        let mut g = Geometry::new(rect_polygon(0.1, 0.2, 0.0, 0.0), vec![]);
954        g.transforms
955            .push(crate::geometry::Transform::Translate { dx: 1.0, dy: 2.0 });
956        let compound = CompoundGeometry::new(vec![g]);
957        let props = SectionProperties::from_compound(&compound);
958
959        assert!((props.centroid.x - 1.0).abs() < 1e-12);
960        assert!((props.centroid.y - 2.0).abs() < 1e-12);
961        assert!((props.area - 0.1 * 0.2).abs() < 1e-15);
962    }
963
964    #[test]
965    fn compound_with_transform_rotate_preserves_area_and_ix() {
966        // Rotating a square about its centroid preserves area and Ix == Iy.
967        let mut g = Geometry::new(rect_polygon(0.2, 0.2, 0.0, 0.0), vec![]);
968        g.transforms
969            .push(crate::geometry::Transform::Rotate { angle: 0.3 });
970        let compound = CompoundGeometry::new(vec![g]);
971        let props = SectionProperties::from_compound(&compound);
972
973        assert!((props.area - 0.04).abs() < 1e-15);
974        // For a square, Ix == Iy regardless of rotation.
975        assert!((props.ix - props.iy).abs() / props.ix < 1e-10);
976    }
977
978    #[test]
979    fn compound_built_up_section_parallel_axis() {
980        // Built-up section: two flanges 0.2 x 0.02 at y = ±0.09,
981        // web 0.02 x 0.16 at x = 0.  This forms an I-section.
982        let flange_top = Geometry::new(rect_polygon(0.2, 0.02, 0.0, 0.09), vec![]);
983        let flange_bot = Geometry::new(rect_polygon(0.2, 0.02, 0.0, -0.09), vec![]);
984        let web = Geometry::new(rect_polygon(0.02, 0.16, 0.0, 0.0), vec![]);
985        let compound = CompoundGeometry::new(vec![flange_top, flange_bot, web]);
986        let props = SectionProperties::from_compound(&compound);
987
988        // Total area
989        let area_expected = 2.0 * (0.2 * 0.02) + 0.02 * 0.16;
990        assert!((props.area - area_expected).abs() / area_expected < 1e-12);
991
992        // Doubly symmetric => centroid at origin
993        assert!(props.centroid.x.abs() < 1e-12);
994        assert!(props.centroid.y.abs() < 1e-12);
995
996        // Ix via parallel-axis theorem
997        let ix_flange = 0.2 * 0.02_f64.powi(3) / 12.0 + 0.2 * 0.02 * 0.09_f64.powi(2);
998        let ix_web = 0.02 * 0.16_f64.powi(3) / 12.0;
999        let ix_expected = 2.0 * ix_flange + ix_web;
1000        assert!((props.ix - ix_expected).abs() / ix_expected < 1e-10);
1001    }
1002
1003    // ---- L / T / I / rotation / multi-hole test suite ----
1004
1005    fn l_section() -> Section {
1006        // L-section: 0.1 x 0.1 square with top-right 0.08 x 0.08 removed.
1007        // Horizontal leg: 0.1 x 0.02 at bottom.
1008        // Vertical leg: 0.02 x 0.1 at left.
1009        let poly = Polygon::new(vec![
1010            Point::new(0.0, 0.0),
1011            Point::new(0.1, 0.0),
1012            Point::new(0.1, 0.02),
1013            Point::new(0.02, 0.02),
1014            Point::new(0.02, 0.1),
1015            Point::new(0.0, 0.1),
1016        ]);
1017        Section::new(poly, vec![])
1018    }
1019
1020    fn i_section() -> Section {
1021        // I-section: flanges 0.2 x 0.02 at y=±0.09, web 0.02 x 0.16.
1022        let poly = Polygon::new(vec![
1023            Point::new(-0.1, 0.10),
1024            Point::new(0.1, 0.10),
1025            Point::new(0.1, 0.08),
1026            Point::new(0.01, 0.08),
1027            Point::new(0.01, -0.08),
1028            Point::new(0.1, -0.08),
1029            Point::new(0.1, -0.10),
1030            Point::new(-0.1, -0.10),
1031            Point::new(-0.1, -0.08),
1032            Point::new(-0.01, -0.08),
1033            Point::new(-0.01, 0.08),
1034            Point::new(-0.1, 0.08),
1035        ]);
1036        Section::new(poly, vec![])
1037    }
1038
1039    #[test]
1040    fn l_section_area_and_centroid() {
1041        let props = SectionProperties::from_section(&l_section());
1042        // Area = 0.1*0.02 + 0.02*0.08 = 0.0036
1043        let area_expected = 0.1 * 0.02 + 0.02 * 0.08;
1044        assert!((props.area - area_expected).abs() / area_expected < 1e-10);
1045
1046        // Centroid by composite method:
1047        // horizontal leg (0.1 x 0.02): A=0.002, cx=0.05, cy=0.01
1048        // vertical leg  (0.02 x 0.08): A=0.0016, cx=0.01, cy=0.06
1049        let cx = (0.002 * 0.05 + 0.0016 * 0.01) / area_expected;
1050        let cy = (0.002 * 0.01 + 0.0016 * 0.06) / area_expected;
1051        assert!((props.centroid.x - cx).abs() < 1e-12);
1052        assert!((props.centroid.y - cy).abs() < 1e-12);
1053    }
1054
1055    #[test]
1056    fn l_section_has_nonzero_ixy_and_rotated_principal_axes() {
1057        let props = SectionProperties::from_section(&l_section());
1058        // L-section is asymmetric => Ixy != 0
1059        assert!(
1060            props.ixy.abs() > 1e-8,
1061            "L-section should have non-zero Ixy, got {}",
1062            props.ixy
1063        );
1064        // Principal angle should be non-zero and not 90°
1065        let phi = props.principal.phi;
1066        assert!(
1067            phi.abs() > 1e-8,
1068            "L-section principal angle should be non-zero"
1069        );
1070        assert!(
1071            (phi.abs() - std::f64::consts::FRAC_PI_2).abs() > 1e-8,
1072            "L-section principal angle should not be 90°"
1073        );
1074    }
1075
1076    #[test]
1077    fn l_section_principal_invariants() {
1078        let props = SectionProperties::from_section(&l_section());
1079        // Invariant: I11 + I22 = Ix + Iy
1080        let sum_centroidal = props.ix + props.iy;
1081        let sum_principal = props.principal.i11 + props.principal.i22;
1082        assert!((sum_principal - sum_centroidal).abs() / sum_centroidal < 1e-10);
1083
1084        // Invariant: I11 * I22 = Ix * Iy - Ixy²
1085        let det_centroidal = props.ix * props.iy - props.ixy.powi(2);
1086        let det_principal = props.principal.i11 * props.principal.i22;
1087        assert!((det_principal - det_centroidal).abs() / det_centroidal.abs() < 1e-10);
1088
1089        // I11 >= I22
1090        assert!(props.principal.i11 >= props.principal.i22);
1091    }
1092
1093    #[test]
1094    fn t_section_single_symmetric_ixy_zero() {
1095        let props = SectionProperties::from_section(&tee_section());
1096        // T-section is symmetric about y-axis => Ixy = 0
1097        assert!(props.ixy.abs() < 1e-12);
1098
1099        // zxx_plus != zxx_minus (not symmetric about x)
1100        assert!((props.zxx_plus - props.zxx_minus).abs() > 1e-6);
1101
1102        // zyy_plus == zyy_minus (symmetric about y)
1103        assert!((props.zyy_plus - props.zyy_minus).abs() < 1e-12);
1104
1105        // Ixy = 0 => principal angle is 0 (if Ix > Iy) or π/2 (if Iy > Ix).
1106        // For this T-section, Iy > Ix (flange is wide in x), so phi ≈ π/2.
1107        let phi = props.principal.phi;
1108        assert!(
1109            phi.abs() < 1e-10 || (phi.abs() - std::f64::consts::FRAC_PI_2).abs() < 1e-10,
1110            "phi should be 0 or π/2 for Ixy=0, got {}",
1111            phi
1112        );
1113    }
1114
1115    #[test]
1116    fn i_section_doubly_symmetric() {
1117        let props = SectionProperties::from_section(&i_section());
1118
1119        // Centroid at origin
1120        assert!(props.centroid.x.abs() < 1e-12);
1121        assert!(props.centroid.y.abs() < 1e-12);
1122
1123        // Ixy = 0
1124        assert!(props.ixy.abs() < 1e-12);
1125
1126        // Symmetric => zxx_plus == zxx_minus, zyy_plus == zyy_minus
1127        assert!((props.zxx_plus - props.zxx_minus).abs() / props.zxx_plus < 1e-10);
1128        assert!((props.zyy_plus - props.zyy_minus).abs() / props.zyy_plus < 1e-10);
1129
1130        // Principal angle ~ 0
1131        assert!(props.principal.phi.abs() < 1e-10);
1132
1133        // Principal moments == centroidal moments (Ixy = 0)
1134        assert!((props.principal.i11 - props.ix).abs() / props.ix < 1e-10);
1135        assert!((props.principal.i22 - props.iy).abs() / props.iy < 1e-10);
1136    }
1137
1138    #[test]
1139    fn i_section_area_and_ix_analytical() {
1140        let props = SectionProperties::from_section(&i_section());
1141        let area_expected = 2.0 * (0.2 * 0.02) + 0.02 * 0.16;
1142        assert!((props.area - area_expected).abs() / area_expected < 1e-10);
1143
1144        // Ix = 2 * (bf*tf³/12 + bf*tf*d²) + tw*hw³/12
1145        let ix_flange = 0.2 * 0.02_f64.powi(3) / 12.0 + 0.2 * 0.02 * 0.09_f64.powi(2);
1146        let ix_web = 0.02 * 0.16_f64.powi(3) / 12.0;
1147        let ix_expected = 2.0 * ix_flange + ix_web;
1148        assert!((props.ix - ix_expected).abs() / ix_expected < 1e-10);
1149    }
1150
1151    #[test]
1152    fn rotated_rectangle_principal_angle() {
1153        // Rectangle 0.2 x 0.1 rotated by 30°.
1154        // After rotation, Ixy != 0 and principal angle ≈ 30°.
1155        let angle = std::f64::consts::PI / 6.0; // 30°
1156        let (s, c) = angle.sin_cos();
1157        let hw = 0.1_f64;
1158        let hh = 0.05_f64;
1159        let rotate = |x: f64, y: f64| Point::new(x * c - y * s, x * s + y * c);
1160        let poly = Polygon::new(vec![
1161            rotate(-hw, -hh),
1162            rotate(hw, -hh),
1163            rotate(hw, hh),
1164            rotate(-hw, hh),
1165        ]);
1166        let section = Section::new(poly, vec![]);
1167        let props = SectionProperties::from_section(&section);
1168
1169        // Ixy should be non-zero after rotation
1170        assert!(
1171            props.ixy.abs() > 1e-6,
1172            "rotated rectangle should have Ixy != 0"
1173        );
1174
1175        // Principal angle should be ≈ ±30° (or ±30° + 90°)
1176        let phi = props.principal.phi;
1177        let deg = phi.to_degrees();
1178        let deg_abs = deg.abs();
1179        // phi could be 30° or -60° (atan2 ambiguity), both valid
1180        assert!(
1181            (deg_abs - 30.0).abs() < 1.0 || (deg_abs - 60.0).abs() < 1.0,
1182            "principal angle should be near 30° or 60°, got {}°",
1183            deg
1184        );
1185    }
1186
1187    #[test]
1188    fn rotated_square_ix_equals_iy() {
1189        // A square rotated by any angle has Ix == Iy.
1190        let angle: f64 = 0.4; // arbitrary
1191        let (s, c) = angle.sin_cos();
1192        let hw = 0.1_f64;
1193        let rotate = |x: f64, y: f64| Point::new(x * c - y * s, x * s + y * c);
1194        let poly = Polygon::new(vec![
1195            rotate(-hw, -hw),
1196            rotate(hw, -hw),
1197            rotate(hw, hw),
1198            rotate(-hw, hw),
1199        ]);
1200        let section = Section::new(poly, vec![]);
1201        let props = SectionProperties::from_section(&section);
1202
1203        assert!((props.ix - props.iy).abs() / props.ix < 1e-10);
1204        // Ixy should be ~0 for a square (I11 == I22 => Ixy doesn't matter)
1205        // Actually for a square Ixy may not be zero after rotation, but I11==I22
1206        assert!((props.principal.i11 - props.principal.i22).abs() / props.principal.i11 < 1e-10);
1207    }
1208
1209    #[test]
1210    fn multi_hole_section_area() {
1211        // 0.4 x 0.4 square with two 0.05 x 0.05 square holes
1212        // at (±0.1, 0).
1213        let outer = rect_polygon(0.4, 0.4, 0.0, 0.0);
1214        let hole1 = rect_polygon(0.05, 0.05, 0.1, 0.0);
1215        let hole2 = rect_polygon(0.05, 0.05, -0.1, 0.0);
1216        let section = Section::new(outer, vec![hole1, hole2]);
1217        let props = SectionProperties::from_section(&section);
1218
1219        let area_expected = 0.4 * 0.4 - 2.0 * 0.05 * 0.05;
1220        assert!((props.area - area_expected).abs() / area_expected < 1e-10);
1221    }
1222
1223    #[test]
1224    fn multi_hole_section_centroid_at_origin() {
1225        // Symmetric placement of holes => centroid at origin.
1226        let outer = rect_polygon(0.4, 0.4, 0.0, 0.0);
1227        let hole1 = rect_polygon(0.05, 0.05, 0.1, 0.0);
1228        let hole2 = rect_polygon(0.05, 0.05, -0.1, 0.0);
1229        let section = Section::new(outer, vec![hole1, hole2]);
1230        let props = SectionProperties::from_section(&section);
1231
1232        assert!(props.centroid.x.abs() < 1e-12);
1233        assert!(props.centroid.y.abs() < 1e-12);
1234    }
1235
1236    #[test]
1237    fn multi_hole_section_ix_parallel_axis() {
1238        // Ix = Ix_outer - 2 * (Ix_hole_local + A_hole * d²)
1239        // where d = 0 (holes on x-axis), so Ix = Ix_outer - 2 * Ix_hole_local
1240        let outer = rect_polygon(0.4, 0.4, 0.0, 0.0);
1241        let hole1 = rect_polygon(0.05, 0.05, 0.1, 0.0);
1242        let hole2 = rect_polygon(0.05, 0.05, -0.1, 0.0);
1243        let section = Section::new(outer, vec![hole1, hole2]);
1244        let props = SectionProperties::from_section(&section);
1245
1246        let ix_outer = 0.4 * 0.4_f64.powi(3) / 12.0;
1247        let ix_hole = 0.05 * 0.05_f64.powi(3) / 12.0;
1248        let ix_expected = ix_outer - 2.0 * ix_hole;
1249        assert!((props.ix - ix_expected).abs() / ix_expected < 1e-10);
1250    }
1251
1252    #[test]
1253    fn multi_hole_section_iy_parallel_axis() {
1254        // Iy = Iy_outer - 2 * (Iy_hole_local + A_hole * d²)
1255        // where d = 0.1 (holes at x = ±0.1)
1256        let outer = rect_polygon(0.4, 0.4, 0.0, 0.0);
1257        let hole1 = rect_polygon(0.05, 0.05, 0.1, 0.0);
1258        let hole2 = rect_polygon(0.05, 0.05, -0.1, 0.0);
1259        let section = Section::new(outer, vec![hole1, hole2]);
1260        let props = SectionProperties::from_section(&section);
1261
1262        let iy_outer = 0.4 * 0.4_f64.powi(3) / 12.0;
1263        let iy_hole_local = 0.05 * 0.05_f64.powi(3) / 12.0;
1264        let a_hole = 0.05 * 0.05;
1265        let iy_expected = iy_outer - 2.0 * (iy_hole_local + a_hole * 0.1_f64.powi(2));
1266        assert!((props.iy - iy_expected).abs() / iy_expected < 1e-10);
1267    }
1268
1269    #[test]
1270    fn multi_hole_section_perimeter() {
1271        // Perimeter = outer + 2 * hole
1272        let outer = rect_polygon(0.4, 0.4, 0.0, 0.0);
1273        let hole1 = rect_polygon(0.05, 0.05, 0.1, 0.0);
1274        let hole2 = rect_polygon(0.05, 0.05, -0.1, 0.0);
1275        let section = Section::new(outer, vec![hole1, hole2]);
1276        let props = SectionProperties::from_section(&section);
1277
1278        let p_expected = 4.0 * 0.4 + 2.0 * 4.0 * 0.05;
1279        assert!((props.perimeter - p_expected).abs() / p_expected < 1e-10);
1280    }
1281
1282    #[test]
1283    fn compound_l_plus_rectangle_two_regions() {
1284        // An L-section built as two disjoint rectangles (no shared edge).
1285        // Horizontal leg: 0.1 x 0.02 at (0.05, 0.01)
1286        // Vertical leg: 0.02 x 0.08 at (0.01, 0.06)
1287        let g1 = Geometry::new(rect_polygon(0.1, 0.02, 0.05, 0.01), vec![]);
1288        let g2 = Geometry::new(rect_polygon(0.02, 0.08, 0.01, 0.06), vec![]);
1289        let compound = CompoundGeometry::new(vec![g1, g2]);
1290        let props = SectionProperties::from_compound(&compound);
1291
1292        // Compare with the single-polygon L-section
1293        let l_props = SectionProperties::from_section(&l_section());
1294
1295        assert!((props.area - l_props.area).abs() / l_props.area < 1e-10);
1296        assert!((props.centroid.x - l_props.centroid.x).abs() < 1e-12);
1297        assert!((props.centroid.y - l_props.centroid.y).abs() < 1e-12);
1298        assert!((props.ix - l_props.ix).abs() / l_props.ix < 1e-10);
1299        assert!((props.iy - l_props.iy).abs() / l_props.iy < 1e-10);
1300        assert!((props.ixy - l_props.ixy).abs() / props.ixy.abs() < 1e-10);
1301    }
1302
1303    /// Non-symmetric hole: rectangle 200×100mm with 40×30mm hole at (120, 65).
1304    ///
1305    /// ```text
1306    /// ┌───────────────────┐
1307    /// │                   │
1308    /// │         ┌──┐      │
1309    /// │         │  │      │
1310    /// │         └──┘      │
1311    /// └───────────────────┘
1312    /// ```
1313    ///
1314    /// Hand-computed in SI (metres, m⁴) — verified against Python
1315    /// `sectionproperties` output.  This exercises centroid shift, Ixy ≠ 0,
1316    /// and a principal angle near −90°.
1317    #[test]
1318    fn non_symmetric_hole_all_properties() {
1319        let outer = Polygon::new(vec![
1320            Point::new(0.0, 0.0),
1321            Point::new(0.2, 0.0),
1322            Point::new(0.2, 0.1),
1323            Point::new(0.0, 0.1),
1324        ]);
1325        // Hole: 40 mm × 30 mm, centered at (120, 65)
1326        let hole = Polygon::new(vec![
1327            Point::new(0.10, 0.05),
1328            Point::new(0.14, 0.05),
1329            Point::new(0.14, 0.08),
1330            Point::new(0.10, 0.08),
1331        ]);
1332        let section = Section::new(outer, vec![hole]);
1333        let props = SectionProperties::from_section(&section);
1334
1335        // --- Area ---
1336        // A = 0.2×0.1 − 0.04×0.03 = 0.0188
1337        let a_expected = 0.0188_f64;
1338        assert!(
1339            (props.area - a_expected).abs() / a_expected < 1e-12,
1340            "area: got {}, expected {}",
1341            props.area,
1342            a_expected
1343        );
1344
1345        // --- Centroid ---
1346        // Qx = 0.02·0.05 − 0.0012·0.065 = 0.001 − 7.8e-5 = 9.22e-4
1347        // Qy = 0.02·0.1  − 0.0012·0.12  = 0.002 − 1.44e-4 = 1.856e-3
1348        // cx = Qy / A = 1.856e-3 / 0.0188 ≈ 0.098723
1349        // cy = Qx / A = 9.22e-4  / 0.0188 ≈ 0.049043
1350        let cx_exp = 0.001_856 / a_expected;
1351        let cy_exp = 0.000_922 / a_expected;
1352        assert!(
1353            (props.centroid.x - cx_exp).abs() < 1e-12,
1354            "cx: got {}, expected {}",
1355            props.centroid.x,
1356            cx_exp
1357        );
1358        assert!(
1359            (props.centroid.y - cy_exp).abs() < 1e-12,
1360            "cy: got {}, expected {}",
1361            props.centroid.y,
1362            cy_exp
1363        );
1364
1365        // --- Centroidal second moments (parallel-axis theorem) ---
1366        //
1367        // Outer (centroid at (0.1, 0.05)):
1368        //   Ixx_g = 0.2·0.1³/12 + 0.02·0.05² = 1.6667e-5 + 5e-5
1369        //   Iyy_g = 0.1·0.2³/12 + 0.02·0.1²  = 6.6667e-5 + 2e-4
1370        //   Ixy_g = 0 + 0.02·0.1·0.05          = 1e-4
1371        //
1372        // Hole (centroid at (0.12, 0.065)):
1373        //   Ixx_g = 0.04·0.03³/12 + 0.0012·0.065² = 9e-8 + 5.07e-6
1374        //   Iyy_g = 0.03·0.04³/12 + 0.0012·0.12²  = 1.6e-7 + 1.728e-5
1375        //   Ixy_g = 0 + 0.0012·0.12·0.065           = 9.36e-6
1376        //
1377        // Net global:
1378        let ixx_g = 6.666666666666667e-5_f64 - 5.160000000000000e-6;
1379        let iyy_g = 2.666666666666667e-4_f64 - 1.744000000000000e-5;
1380        let ixy_g = 1.000000000000000e-4_f64 - 9.360000000000000e-6;
1381        // Shift to centroid:
1382        let cx = props.centroid.x;
1383        let cy = props.centroid.y;
1384        let ixx_c = ixx_g - a_expected * cy * cy;
1385        let iyy_c = iyy_g - a_expected * cx * cx;
1386        let ixy_c = ixy_g - a_expected * cx * cy;
1387
1388        assert!(
1389            (props.ix - ixx_c).abs() / ixx_c.abs() < 1e-10,
1390            "Ixx: got {}, expected {}",
1391            props.ix,
1392            ixx_c
1393        );
1394        assert!(
1395            (props.iy - iyy_c).abs() / iyy_c.abs() < 1e-10,
1396            "Iyy: got {}, expected {}",
1397            props.iy,
1398            iyy_c
1399        );
1400        assert!(
1401            (props.ixy - ixy_c).abs() / ixy_c.abs().max(1e-15) < 1e-6,
1402            "Ixy: got {}, expected {}",
1403            props.ixy,
1404            ixy_c
1405        );
1406
1407        // --- Principal moments ---
1408        let avg = (ixx_c + iyy_c) * 0.5;
1409        let diff = (ixx_c - iyy_c) * 0.5;
1410        let delta = (diff * diff + ixy_c * ixy_c).sqrt();
1411        let i11_exp = avg + delta;
1412        let i22_exp = avg - delta;
1413
1414        assert!(
1415            (props.principal.i11 - i11_exp).abs() / i11_exp < 1e-10,
1416            "I11: got {}, expected {}",
1417            props.principal.i11,
1418            i11_exp
1419        );
1420        assert!(
1421            (props.principal.i22 - i22_exp).abs() / i22_exp < 1e-10,
1422            "I22: got {}, expected {}",
1423            props.principal.i22,
1424            i22_exp
1425        );
1426
1427        // --- Invariants ---
1428        // I11 + I22 == Ixx + Iyy
1429        let sum_c = ixx_c + iyy_c;
1430        let sum_p = props.principal.i11 + props.principal.i22;
1431        assert!(
1432            (sum_p - sum_c).abs() / sum_c < 1e-10,
1433            "invariant sum: got {}, expected {}",
1434            sum_p,
1435            sum_c
1436        );
1437        // I11 · I22 == Ixx·Iyy − Ixy²
1438        let det_c = ixx_c * iyy_c - ixy_c * ixy_c;
1439        let det_p = props.principal.i11 * props.principal.i22;
1440        assert!(
1441            (det_p - det_c).abs() / det_c.abs() < 1e-10,
1442            "invariant product: got {}, expected {}",
1443            det_p,
1444            det_c
1445        );
1446
1447        // --- Principal angle ---
1448        // phi = 0.5 · atan2(2·Ixy, Ixx − Iyy)
1449        //     ≈ −89.56° (nearly vertical principal axis due to wide flange)
1450        let phi_exp = 0.5 * (2.0 * ixy_c).atan2(ixx_c - iyy_c);
1451        assert!(
1452            (props.principal.phi - phi_exp).abs() < 1e-12,
1453            "phi: got {} rad ({}°), expected {} rad ({}°)",
1454            props.principal.phi,
1455            props.principal.phi.to_degrees(),
1456            phi_exp,
1457            phi_exp.to_degrees()
1458        );
1459        // Cross-check: phi ≈ −π/2 (within 1°)
1460        assert!(
1461            (props.principal.phi + std::f64::consts::FRAC_PI_2).abs() < (1.0_f64).to_radians(),
1462            "phi should be near −π/2, got {}°",
1463            props.principal.phi.to_degrees()
1464        );
1465    }
1466}