Skip to main content

section_properties/
composite.rs

1//! Elastic composite section analysis using the modular-ratio (transformed-
2//! section) method.
3//!
4//! # Overview
5//!
6//! For a multi-material cross-section, each component's geometric properties
7//! are transformed to an equivalent single-material section by multiplying
8//! area and moments of inertia by the **modular ratio**:
9//!
10//! ```text
11//! n_i = E_i / E_ref
12//! ```
13//!
14//! where `E_i` is the Young's modulus of component *i* and `E_ref` is the
15//! Young's modulus of a chosen reference material.  The transformed section
16//! is then analysed as a homogeneous section to obtain composite area,
17//! centroid, and second moments of area.
18//!
19//! # Coordinate convention
20//!
21//! This module follows the same convention as the rest of the crate:
22//!
23//! * `x` — horizontal axis (positive right)
24//! * `y` — vertical axis (positive up)
25//! * `Ix` — second moment of area about the centroidal x-axis (`∫y² dA`)
26//! * `Iy` — second moment of area about the centroidal y-axis (`∫x² dA`)
27//! * `Ixy` — product of inertia (`∫xy dA`, signed)
28//! * Principal angle `phi` — CCW positive, `½ atan2(2·Ixy, Ix − Iy)`
29//!
30//! # Limitations
31//!
32//! This module implements **elastic transformed-section analysis** only.
33//! It does **not** implement:
34//!
35//! * EN 1994 composite design (plastic resistance, shear connection)
36//! * Creep or shrinkage of concrete
37//! * Cracked-section analysis
38//! * Construction-stage analysis
39//! * Fire design
40//! * Plastic composite analysis
41//! * Stress recovery across material interfaces
42//!
43//! # Quick start
44//!
45//! ```rust
46//! use section_properties::composite::*;
47//! use section_properties::material::presets::*;
48//! use section_properties::{Point, Polygon, Section};
49//!
50//! // Concrete slab 0.3 m × 0.15 m
51//! let slab = Section::new(
52//!     Polygon::new(vec![
53//!         Point::new(0.0, 0.0),
54//!         Point::new(0.3, 0.0),
55//!         Point::new(0.3, 0.15),
56//!         Point::new(0.0, 0.15),
57//!     ]),
58//!     Vec::new(),
59//! );
60//!
61//! // Steel plate 0.2 m × 0.01 m on top
62//! let plate = Section::new(
63//!     Polygon::new(vec![
64//!         Point::new(0.05, 0.15),
65//!         Point::new(0.25, 0.15),
66//!         Point::new(0.25, 0.16),
67//!         Point::new(0.05, 0.16),
68//!     ]),
69//!     Vec::new(),
70//! );
71//!
72//! let composite = ElasticComposite::new(vec![
73//!     CompositeComponent::new(slab, CONCRETE_C30_37).unwrap(),
74//!     CompositeComponent::new(plate, STEEL_S355).unwrap(),
75//! ]).unwrap();
76//!
77//! // Analyse with concrete as the reference material
78//! let result = composite.analyze(&CONCRETE_C30_37).unwrap();
79//! assert!(result.area > 0.0);
80//! assert!(result.ix > 0.0);
81//! ```
82
83use crate::geometry::Point;
84use crate::material::Material;
85use crate::section::Section;
86use crate::section_properties::SectionProperties;
87use thiserror::Error;
88
89/// Errors that can occur during composite section construction or analysis.
90#[derive(Debug, Clone, PartialEq, Error)]
91pub enum CompositeError {
92    /// Young's modulus is zero, negative, NaN, or infinite.
93    #[error("invalid Young's modulus for material '{name}': E={value}")]
94    InvalidModulus { name: String, value: f64 },
95
96    /// Section geometry is degenerate (zero or near-zero net area).
97    #[error("degenerate section geometry in component {index}: {detail}")]
98    InvalidGeometry { index: usize, detail: String },
99
100    /// No components were provided.
101    #[error("composite section must contain at least one component")]
102    NoComponents,
103
104    /// The transformed section has zero or near-zero net area.
105    #[error("transformed section net area is zero or near-zero")]
106    ZeroTransformedArea,
107
108    /// The reference material modulus is invalid.
109    #[error("invalid reference material modulus: E={value}")]
110    InvalidReferenceModulus { value: f64 },
111
112    /// The modular ratio `E_i / E_ref` is not finite (overflow).
113    #[error(
114        "non-finite modular ratio for component {index}: E={e_component:.6e} / E_ref={e_ref:.6e}"
115    )]
116    NonFiniteModularRatio {
117        index: usize,
118        e_component: f64,
119        e_ref: f64,
120    },
121}
122
123/// A geometric section component paired with a material.
124///
125/// The section geometry is owned (cloned) so that the original user data
126/// is never mutated.  The transformed section is an analytical
127/// representation only — the original geometry remains recoverable.
128#[derive(Debug, Clone)]
129pub struct CompositeComponent {
130    /// The geometric section (outer boundary + optional holes).
131    pub section: Section,
132    /// The isotropic linear-elastic material assigned to this component.
133    pub material: Material,
134}
135
136impl CompositeComponent {
137    /// Create a new composite component from a section and a material.
138    ///
139    /// Returns `Err` if the Young's modulus is not a positive, finite value
140    /// or if the section geometry is degenerate.
141    pub fn new(section: Section, material: Material) -> Result<Self, CompositeError> {
142        validate_modulus(material.youngs_modulus, material.name)?;
143        let area = section.area();
144        if area.abs() <= f64::EPSILON {
145            return Err(CompositeError::InvalidGeometry {
146                index: 0,
147                detail: format!("net area = {area:.6e} (too small)"),
148            });
149        }
150        if !area.is_finite() {
151            return Err(CompositeError::InvalidGeometry {
152                index: 0,
153                detail: format!("net area = {area} (not finite)"),
154            });
155        }
156        Ok(Self { section, material })
157    }
158
159    /// The Young's modulus of this component's material.
160    pub fn youngs_modulus(&self) -> f64 {
161        self.material.youngs_modulus
162    }
163
164    /// The net geometric area of this component's section.
165    pub fn area(&self) -> f64 {
166        self.section.area()
167    }
168}
169
170fn validate_modulus(e: f64, name: &str) -> Result<(), CompositeError> {
171    if !e.is_finite() || e <= 0.0 {
172        return Err(CompositeError::InvalidModulus {
173            name: name.to_string(),
174            value: e,
175        });
176    }
177    Ok(())
178}
179
180/// Per-component result of a composite section analysis.
181///
182/// Retains enough information to recover the original material properties,
183/// the modular ratio used, and the original vs transformed area.
184#[derive(Debug, Clone)]
185pub struct ComponentAnalysis {
186    /// The original material assigned to this component.
187    pub material: Material,
188    /// Modular ratio `n = E_i / E_ref` used for this component.
189    pub modular_ratio: f64,
190    /// Original (geometric) net area of the component \[m²\].
191    pub original_area: f64,
192    /// Transformed area `n × A_original` \[m²\].
193    pub transformed_area: f64,
194    /// Centroid of the component in global coordinates.
195    pub centroid: Point,
196}
197
198/// Result of an elastic composite section analysis.
199///
200/// Contains the transformed section properties (equivalent homogeneous
201/// section in the reference material) plus per-component analysis data.
202#[derive(Debug, Clone)]
203pub struct CompositeAnalysisResult {
204    /// Transformed area `Σ(n_i · A_i)` \[m²\].
205    pub area: f64,
206    /// Centroid of the transformed section in global coordinates.
207    pub centroid: Point,
208    /// Transformed second moment of area about the centroidal x-axis \[m⁴\].
209    ///
210    /// This is the **reference-material transformed** value `I'_x`, not the
211    /// physical inertia.  The physical bending stiffness is `E_ref · I'_x`.
212    pub ix: f64,
213    /// Transformed second moment of area about the centroidal y-axis \[m⁴\].
214    ///
215    /// This is the **reference-material transformed** value `I'_y`, not the
216    /// physical inertia.  The physical bending stiffness is `E_ref · I'_y`.
217    pub iy: f64,
218    /// Transformed product of inertia about the centroidal axes \[m⁴\].
219    ///
220    /// This is the **reference-material transformed** value `I'_xy`.
221    /// The physical value is `E_ref · I'_xy`.
222    pub ixy: f64,
223    /// Major principal second moment of area \[m⁴\].
224    pub principal_i11: f64,
225    /// Minor principal second moment of area \[m⁴\].
226    pub principal_i22: f64,
227    /// Principal angle from centroidal x-axis to axis 11, CCW positive \[rad\].
228    pub principal_phi: f64,
229    /// The reference material used for the transformation.
230    pub reference_material: Material,
231    /// Per-component analysis data.
232    pub components: Vec<ComponentAnalysis>,
233}
234
235/// A multi-material composite section for elastic transformed-section analysis.
236///
237/// Components are stored in insertion order.  The original geometry is
238/// never mutated — [`analyze`](Self::analyze) produces an analytical
239/// transformed representation only.
240///
241/// # Component semantics
242///
243/// Each component represents a **distinct physical material region**.
244/// Components are summed algebraically — if two components overlap
245/// geometrically, the overlapping region is **double-counted** in the
246/// transformed section.  No Boolean union is performed.  Callers are
247/// responsible for ensuring components represent disjoint regions.
248#[derive(Debug, Clone)]
249pub struct ElasticComposite {
250    components: Vec<CompositeComponent>,
251}
252
253impl ElasticComposite {
254    /// Create a new composite section from a list of components.
255    ///
256    /// Returns `Err` if the list is empty or if any component has invalid
257    /// material or geometry.
258    pub fn new(components: Vec<CompositeComponent>) -> Result<Self, CompositeError> {
259        if components.is_empty() {
260            return Err(CompositeError::NoComponents);
261        }
262        Ok(Self { components })
263    }
264
265    /// Number of components.
266    pub fn n_components(&self) -> usize {
267        self.components.len()
268    }
269
270    /// Borrow the component at `index`.
271    pub fn component(&self, index: usize) -> Option<&CompositeComponent> {
272        self.components.get(index)
273    }
274
275    /// Analyse the composite section using the transformed-section method.
276    ///
277    /// # Arguments
278    ///
279    /// * `reference_material` — the reference material whose Young's modulus
280    ///   `E_ref` defines the modular ratio `n_i = E_i / E_ref`.  Must have
281    ///   a positive, finite Young's modulus.
282    ///
283    /// The reference material **need not** be one of the component materials.
284    /// Any positive, finite modulus produces a valid transformed section.
285    /// The physical stiffnesses `E_ref · A'`, `E_ref · I'_x`, etc. are
286    /// invariant to the choice of reference material.
287    ///
288    /// # Algorithm
289    ///
290    /// 1. For each component, compute geometric properties (area, centroid,
291    ///    centroidal moments) via [`SectionProperties`].
292    /// 2. Transfer centroidal moments to global axes using the parallel-axis
293    ///    theorem.
294    /// 3. Multiply each component's contribution by its modular ratio `n_i`.
295    /// 4. Sum to obtain the transformed section's global moments.
296    /// 5. Compute the transformed centroid and transfer back to centroidal
297    ///    axes.
298    /// 6. Compute principal axes via Mohr's circle.
299    ///
300    /// # Errors
301    ///
302    /// Returns `Err` if:
303    /// * the reference material modulus is invalid,
304    /// * any component's geometry is degenerate,
305    /// * the transformed net area is zero or near-zero.
306    pub fn analyze(
307        &self,
308        reference_material: &Material,
309    ) -> Result<CompositeAnalysisResult, CompositeError> {
310        validate_modulus(reference_material.youngs_modulus, reference_material.name).map_err(
311            |_| CompositeError::InvalidReferenceModulus {
312                value: reference_material.youngs_modulus,
313            },
314        )?;
315
316        let e_ref = reference_material.youngs_modulus;
317
318        // Accumulators (global axes, transformed).
319        let mut total_area = 0.0_f64;
320        let mut first_x = 0.0_f64;
321        let mut first_y = 0.0_f64;
322        let mut ix_global = 0.0_f64;
323        let mut iy_global = 0.0_f64;
324        let mut ixy_global = 0.0_f64;
325
326        let mut component_results: Vec<ComponentAnalysis> =
327            Vec::with_capacity(self.components.len());
328
329        for (i, comp) in self.components.iter().enumerate() {
330            let props = SectionProperties::try_from_section(&comp.section)
331                .map_err(|detail| CompositeError::InvalidGeometry { index: i, detail })?;
332
333            let n = comp.material.youngs_modulus / e_ref;
334            if !n.is_finite() {
335                return Err(CompositeError::NonFiniteModularRatio {
336                    index: i,
337                    e_component: comp.material.youngs_modulus,
338                    e_ref,
339                });
340            }
341            let area = props.area;
342            let cx = props.centroid.x;
343            let cy = props.centroid.y;
344
345            // Centroidal → global via parallel-axis theorem:
346            //   I_x,global = I_x,c + A · cy²
347            //   I_y,global = I_y,c + A · cx²
348            //   I_xy,global = I_xy,c + A · cx · cy
349            let ix_g = props.ix + area * cy * cy;
350            let iy_g = props.iy + area * cx * cx;
351            let ixy_g = props.ixy + area * cx * cy;
352
353            // Apply modular ratio.
354            let n_area = n * area;
355            if !n_area.is_finite() {
356                return Err(CompositeError::NonFiniteModularRatio {
357                    index: i,
358                    e_component: comp.material.youngs_modulus,
359                    e_ref,
360                });
361            }
362            total_area += n_area;
363            first_x += n_area * cx;
364            first_y += n_area * cy;
365            ix_global += n * ix_g;
366            iy_global += n * iy_g;
367            ixy_global += n * ixy_g;
368
369            component_results.push(ComponentAnalysis {
370                material: comp.material,
371                modular_ratio: n,
372                original_area: area,
373                transformed_area: n_area,
374                centroid: props.centroid,
375            });
376        }
377
378        if total_area.abs() <= f64::EPSILON {
379            return Err(CompositeError::ZeroTransformedArea);
380        }
381        if !total_area.is_finite()
382            || !first_x.is_finite()
383            || !first_y.is_finite()
384            || !ix_global.is_finite()
385            || !iy_global.is_finite()
386            || !ixy_global.is_finite()
387        {
388            return Err(CompositeError::NonFiniteModularRatio {
389                index: self.components.len(),
390                e_component: f64::NAN,
391                e_ref,
392            });
393        }
394
395        // Transformed centroid.
396        let centroid = Point::new(first_x / total_area, first_y / total_area);
397
398        // Global → centroidal via parallel-axis theorem:
399        //   I_x,c = I_x,global − A · ȳ²
400        //   I_y,c = I_y,global − A · x̄²
401        //   I_xy,c = I_xy,global − A · x̄ · ȳ
402        let ix_c = ix_global - total_area * centroid.y * centroid.y;
403        let iy_c = iy_global - total_area * centroid.x * centroid.x;
404        let ixy_c = ixy_global - total_area * centroid.x * centroid.y;
405
406        // Principal axes (Mohr's circle, same convention as SectionProperties).
407        let avg = (ix_c + iy_c) * 0.5;
408        let diff = (ix_c - iy_c) * 0.5;
409        let radius = (diff * diff + ixy_c * ixy_c).sqrt();
410        let i11 = avg + radius;
411        let i22 = avg - radius;
412        let phi = 0.5 * (2.0 * ixy_c).atan2(ix_c - iy_c);
413
414        Ok(CompositeAnalysisResult {
415            area: total_area,
416            centroid,
417            ix: ix_c,
418            iy: iy_c,
419            ixy: ixy_c,
420            principal_i11: i11,
421            principal_i22: i22,
422            principal_phi: phi,
423            reference_material: *reference_material,
424            components: component_results,
425        })
426    }
427
428    /// Convenience: analyse using the first component's material as reference.
429    ///
430    /// # Errors
431    ///
432    /// Same as [`analyze`](Self::analyze).
433    pub fn analyze_with_first_reference(&self) -> Result<CompositeAnalysisResult, CompositeError> {
434        let ref_mat = self
435            .components
436            .first()
437            .map(|c| c.material)
438            .ok_or(CompositeError::NoComponents)?;
439        self.analyze(&ref_mat)
440    }
441}
442
443#[cfg(test)]
444mod tests {
445    use super::*;
446    use crate::material::presets::*;
447    use crate::{Point, Polygon};
448
449    fn rect_section(x0: f64, y0: f64, w: f64, h: f64) -> Section {
450        Section::new(
451            Polygon::new(vec![
452                Point::new(x0, y0),
453                Point::new(x0 + w, y0),
454                Point::new(x0 + w, y0 + h),
455                Point::new(x0, y0 + h),
456            ]),
457            Vec::new(),
458        )
459    }
460
461    #[test]
462    fn single_material_degeneration() {
463        let sec = rect_section(0.0, 0.0, 0.3, 0.5);
464        let comp = ElasticComposite::new(vec![
465            CompositeComponent::new(sec.clone(), CONCRETE_C30_37).unwrap(),
466        ])
467        .unwrap();
468
469        let result = comp.analyze(&CONCRETE_C30_37).unwrap();
470        let homogeneous = SectionProperties::from_section(&sec);
471
472        let tol = 1e-10;
473        assert!((result.area - homogeneous.area).abs() < tol);
474        assert!((result.ix - homogeneous.ix).abs() < tol);
475        assert!((result.iy - homogeneous.iy).abs() < tol);
476        assert!((result.ixy - homogeneous.ixy).abs() < tol);
477    }
478
479    #[test]
480    fn two_material_rectangular_analytical() {
481        // Two stacked rectangles:
482        //   bottom: 0.2 × 0.1, E = 30 GPa, centroid (0.1, 0.05)
483        //   top:    0.2 × 0.1, E = 60 GPa, centroid (0.1, 0.15)
484        // Reference: E_ref = 30 GPa → n_bottom = 1, n_top = 2
485
486        let e_ref = 30e9;
487        let e_bottom = 30e9;
488        let e_top = 60e9;
489
490        let mat_ref = Material::new(e_ref, 0.2, 2400.0, "ref");
491        let mat_bottom = Material::new(e_bottom, 0.2, 2400.0, "bottom");
492        let mat_top = Material::new(e_top, 0.2, 2400.0, "top");
493
494        let bottom = rect_section(0.0, 0.0, 0.2, 0.1);
495        let top = rect_section(0.0, 0.1, 0.2, 0.1);
496
497        let comp = ElasticComposite::new(vec![
498            CompositeComponent::new(bottom, mat_bottom).unwrap(),
499            CompositeComponent::new(top, mat_top).unwrap(),
500        ])
501        .unwrap();
502
503        let result = comp.analyze(&mat_ref).unwrap();
504
505        // Analytical:
506        // A' = 1·(0.02) + 2·(0.02) = 0.06
507        let a_bottom = 0.2 * 0.1_f64;
508        let a_top = 0.2 * 0.1_f64;
509        let n_bottom = e_bottom / e_ref;
510        let n_top = e_top / e_ref;
511        let a_transformed = n_bottom * a_bottom + n_top * a_top;
512        assert!((result.area - a_transformed).abs() < 1e-12);
513
514        // y_bar = (1·0.02·0.05 + 2·0.02·0.15) / 0.06
515        let y_bar = (n_bottom * a_bottom * 0.05 + n_top * a_top * 0.15) / a_transformed;
516        assert!((result.centroid.y - y_bar).abs() < 1e-12);
517        assert!((result.centroid.x - 0.1).abs() < 1e-12);
518
519        // Ix about centroidal:
520        // Ix_bottom,c = b·h³/12 + A·(cy - y_bar)²
521        let ix_bottom_local = 0.2 * 0.1_f64.powi(3) / 12.0;
522        let ix_top_local = 0.2 * 0.1_f64.powi(3) / 12.0;
523        let ix_analytical = n_bottom * (ix_bottom_local + a_bottom * (0.05 - y_bar).powi(2))
524            + n_top * (ix_top_local + a_top * (0.15 - y_bar).powi(2));
525        assert!((result.ix - ix_analytical).abs() < 1e-12);
526
527        // Iy about centroidal (both rectangles have same x-centroid = 0.1):
528        let iy_bottom_local = 0.1 * 0.2_f64.powi(3) / 12.0;
529        let iy_top_local = 0.1 * 0.2_f64.powi(3) / 12.0;
530        let iy_analytical = n_bottom * iy_bottom_local + n_top * iy_top_local;
531        assert!((result.iy - iy_analytical).abs() < 1e-12);
532
533        // Ixy = 0 (symmetric about x = 0.1)
534        assert!(result.ixy.abs() < 1e-12);
535    }
536
537    #[test]
538    fn steel_concrete_composite() {
539        let slab = rect_section(0.0, 0.0, 0.3, 0.15);
540        let steel = rect_section(0.05, 0.15, 0.2, 0.01);
541
542        let comp = ElasticComposite::new(vec![
543            CompositeComponent::new(slab, CONCRETE_C30_37).unwrap(),
544            CompositeComponent::new(steel, STEEL_S355).unwrap(),
545        ])
546        .unwrap();
547
548        // Reference: concrete
549        let result = comp.analyze(&CONCRETE_C30_37).unwrap();
550
551        let n_steel = STEEL_S355.youngs_modulus / CONCRETE_C30_37.youngs_modulus;
552        let n_conc = 1.0_f64;
553
554        // Check modular ratios in component results
555        assert!((result.components[0].modular_ratio - n_conc).abs() < 1e-10);
556        assert!((result.components[1].modular_ratio - n_steel).abs() < 1e-10);
557
558        // Transformed area = A_conc + n_steel * A_steel
559        let a_conc = 0.3 * 0.15;
560        let a_steel = 0.2 * 0.01;
561        let expected_area = n_conc * a_conc + n_steel * a_steel;
562        assert!((result.area - expected_area).abs() / expected_area < 1e-10);
563
564        // Original areas preserved
565        assert!((result.components[0].original_area - a_conc).abs() < 1e-12);
566        assert!((result.components[1].original_area - a_steel).abs() < 1e-12);
567
568        // Transformed areas
569        assert!((result.components[0].transformed_area - n_conc * a_conc).abs() < 1e-12);
570        assert!((result.components[1].transformed_area - n_steel * a_steel).abs() < 1e-12);
571    }
572
573    #[test]
574    fn reference_material_reversal() {
575        // Use an asymmetric section so Iy and Ixy are non-trivial.
576        // Slab offset left, steel plate offset right → non-zero Ixy.
577        let slab = rect_section(0.0, 0.0, 0.3, 0.15);
578        let steel = rect_section(0.15, 0.15, 0.2, 0.01);
579
580        let comp = ElasticComposite::new(vec![
581            CompositeComponent::new(slab, CONCRETE_C30_37).unwrap(),
582            CompositeComponent::new(steel, STEEL_S355).unwrap(),
583        ])
584        .unwrap();
585
586        let r_conc = comp.analyze(&CONCRETE_C30_37).unwrap();
587        let r_steel = comp.analyze(&STEEL_S355).unwrap();
588
589        // Physical stiffnesses are reference-independent.
590        // EA = E_ref * A'
591        let ea_conc = CONCRETE_C30_37.youngs_modulus * r_conc.area;
592        let ea_steel = STEEL_S355.youngs_modulus * r_steel.area;
593        assert!((ea_conc - ea_steel).abs() / ea_conc < 1e-10);
594
595        // EIx = E_ref * Ix'
596        let ei_conc = CONCRETE_C30_37.youngs_modulus * r_conc.ix;
597        let ei_steel = STEEL_S355.youngs_modulus * r_steel.ix;
598        assert!((ei_conc - ei_steel).abs() / ei_conc < 1e-10);
599
600        // EIy = E_ref * Iy'
601        let eiy_conc = CONCRETE_C30_37.youngs_modulus * r_conc.iy;
602        let eiy_steel = STEEL_S355.youngs_modulus * r_steel.iy;
603        assert!((eiy_conc - eiy_steel).abs() / eiy_conc < 1e-10);
604
605        // EIxy = E_ref * Ixy' (use absolute tolerance — Ixy can be near zero)
606        let eixy_conc = CONCRETE_C30_37.youngs_modulus * r_conc.ixy;
607        let eixy_steel = STEEL_S355.youngs_modulus * r_steel.ixy;
608        assert!((eixy_conc - eixy_steel).abs() < 1e-3);
609
610        // Centroid must be the same (physical location)
611        assert!((r_conc.centroid.x - r_steel.centroid.x).abs() < 1e-10);
612        assert!((r_conc.centroid.y - r_steel.centroid.y).abs() < 1e-10);
613    }
614
615    #[test]
616    fn symmetric_composite() {
617        // Two identical rectangles symmetric about y-axis:
618        //   left:  0.1 × 0.2 at x = [-0.15, -0.05], E = 30 GPa
619        //   right: 0.1 × 0.2 at x = [0.05, 0.15],  E = 200 GPa
620        // Despite different materials, geometry is symmetric → x_bar = 0
621        // but the centroid shifts towards the stiffer side.
622        //
623        // Actually with different E, the *transformed* centroid shifts.
624        // For a true symmetry test we need same material on both sides.
625
626        let left = rect_section(-0.15, -0.1, 0.1, 0.2);
627        let right = rect_section(0.05, -0.1, 0.1, 0.2);
628
629        let mat = Material::new(30e9, 0.2, 2400.0, "same");
630
631        let comp = ElasticComposite::new(vec![
632            CompositeComponent::new(left, mat).unwrap(),
633            CompositeComponent::new(right, mat).unwrap(),
634        ])
635        .unwrap();
636
637        let result = comp.analyze(&mat).unwrap();
638
639        // Symmetric → centroid at origin
640        assert!(result.centroid.x.abs() < 1e-12);
641        assert!(result.centroid.y.abs() < 1e-12);
642
643        // Ixy = 0 for doubly-symmetric section
644        assert!(result.ixy.abs() < 1e-12);
645    }
646
647    #[test]
648    fn material_position_sensitivity() {
649        // Two scenarios:
650        //   A: stiff material on top, soft on bottom
651        //   B: stiff material on bottom, soft on top
652        // The centroid must move towards the stiff material.
653
654        let e_soft = 30e9;
655        let e_stiff = 200e9;
656        let mat_soft = Material::new(e_soft, 0.2, 2400.0, "soft");
657        let mat_stiff = Material::new(e_stiff, 0.2, 2400.0, "stiff");
658
659        let bottom = rect_section(0.0, 0.0, 0.2, 0.1);
660        let top = rect_section(0.0, 0.1, 0.2, 0.1);
661
662        // Scenario A: stiff on top
663        let comp_a = ElasticComposite::new(vec![
664            CompositeComponent::new(bottom.clone(), mat_soft).unwrap(),
665            CompositeComponent::new(top.clone(), mat_stiff).unwrap(),
666        ])
667        .unwrap();
668        let result_a = comp_a.analyze(&mat_soft).unwrap();
669
670        // Scenario B: stiff on bottom
671        let comp_b = ElasticComposite::new(vec![
672            CompositeComponent::new(bottom, mat_stiff).unwrap(),
673            CompositeComponent::new(top, mat_soft).unwrap(),
674        ])
675        .unwrap();
676        let result_b = comp_b.analyze(&mat_soft).unwrap();
677
678        // Geometric centroid of the two stacked rectangles is at y = 0.1.
679        // In A, stiff on top → transformed centroid shifts above 0.1.
680        assert!(
681            result_a.centroid.y > 0.1,
682            "centroid should shift towards stiff top"
683        );
684        // In B, stiff on bottom → transformed centroid shifts below 0.1.
685        assert!(
686            result_b.centroid.y < 0.1,
687            "centroid should shift towards stiff bottom"
688        );
689
690        // The two centroids must be different
691        assert!((result_a.centroid.y - result_b.centroid.y).abs() > 0.01);
692
693        // Ix is identical by the y ↔ (0.2 − y) symmetry of the geometry.
694        assert!((result_a.ix - result_b.ix).abs() < 1e-10);
695
696        // The result is not merely based on total transformed area:
697        // a single-material section with the same total transformed area
698        // and same overall bounding box would have a different Ix.
699        let total_transformed_area = result_a.area;
700        let single_mat_ix = 0.2 * 0.2_f64.powi(3) / 12.0 * (total_transformed_area / (0.2 * 0.2));
701        assert!((result_a.ix - single_mat_ix).abs() > 1e-6);
702    }
703
704    #[test]
705    fn geometric_scaling() {
706        let e1 = 30e9;
707        let e2 = 200e9;
708        let mat1 = Material::new(e1, 0.2, 2400.0, "m1");
709        let mat2 = Material::new(e2, 0.3, 7850.0, "m2");
710
711        let alpha = 2.5_f64;
712
713        // Original
714        let s1 = rect_section(0.0, 0.0, 0.2, 0.1);
715        let s2 = rect_section(0.1, 0.1, 0.1, 0.05);
716
717        let comp_orig = ElasticComposite::new(vec![
718            CompositeComponent::new(s1.clone(), mat1).unwrap(),
719            CompositeComponent::new(s2.clone(), mat2).unwrap(),
720        ])
721        .unwrap();
722        let r_orig = comp_orig.analyze(&mat1).unwrap();
723
724        // Scaled by alpha
725        let s1_scaled = rect_section(0.0, 0.0, 0.2 * alpha, 0.1 * alpha);
726        let s2_scaled = rect_section(0.1 * alpha, 0.1 * alpha, 0.1 * alpha, 0.05 * alpha);
727
728        let comp_scaled = ElasticComposite::new(vec![
729            CompositeComponent::new(s1_scaled, mat1).unwrap(),
730            CompositeComponent::new(s2_scaled, mat2).unwrap(),
731        ])
732        .unwrap();
733        let r_scaled = comp_scaled.analyze(&mat1).unwrap();
734
735        // A ~ α²
736        assert!((r_scaled.area / r_orig.area - alpha * alpha).abs() < 1e-10);
737        // centroid ~ α
738        assert!((r_scaled.centroid.x / r_orig.centroid.x - alpha).abs() < 1e-10);
739        assert!((r_scaled.centroid.y / r_orig.centroid.y - alpha).abs() < 1e-10);
740        // Ix, Iy, Ixy ~ α⁴
741        assert!((r_scaled.ix / r_orig.ix - alpha.powi(4)).abs() < 1e-10);
742        assert!((r_scaled.iy / r_orig.iy - alpha.powi(4)).abs() < 1e-10);
743        assert!((r_scaled.ixy / r_orig.ixy - alpha.powi(4)).abs() < 1e-10);
744    }
745
746    #[test]
747    fn invalid_modulus_zero() {
748        let sec = rect_section(0.0, 0.0, 0.1, 0.1);
749        let mat = Material::new(0.0, 0.2, 2400.0, "zero E");
750        assert!(CompositeComponent::new(sec, mat).is_err());
751    }
752
753    #[test]
754    fn invalid_modulus_negative() {
755        let sec = rect_section(0.0, 0.0, 0.1, 0.1);
756        let mat = Material::new(-1e9, 0.2, 2400.0, "negative E");
757        assert!(CompositeComponent::new(sec, mat).is_err());
758    }
759
760    #[test]
761    fn invalid_modulus_nan() {
762        let sec = rect_section(0.0, 0.0, 0.1, 0.1);
763        let mat = Material::new(f64::NAN, 0.2, 2400.0, "NaN E");
764        assert!(CompositeComponent::new(sec, mat).is_err());
765    }
766
767    #[test]
768    fn invalid_modulus_infinity() {
769        let sec = rect_section(0.0, 0.0, 0.1, 0.1);
770        let mat = Material::new(f64::INFINITY, 0.2, 2400.0, "inf E");
771        assert!(CompositeComponent::new(sec, mat).is_err());
772    }
773
774    #[test]
775    fn invalid_reference_material() {
776        let sec = rect_section(0.0, 0.0, 0.1, 0.1);
777        let mat = Material::new(200e9, 0.3, 7850.0, "steel");
778        let comp = ElasticComposite::new(vec![CompositeComponent::new(sec, mat).unwrap()]).unwrap();
779
780        let bad_ref = Material::new(0.0, 0.2, 2400.0, "zero");
781        assert!(comp.analyze(&bad_ref).is_err());
782
783        let nan_ref = Material::new(f64::NAN, 0.2, 2400.0, "nan");
784        assert!(comp.analyze(&nan_ref).is_err());
785    }
786
787    #[test]
788    fn empty_components_rejected() {
789        let result = ElasticComposite::new(Vec::new());
790        assert!(result.is_err());
791    }
792
793    #[test]
794    fn original_geometry_preserved() {
795        let sec = rect_section(0.0, 0.0, 0.3, 0.5);
796        let sec_clone = sec.clone();
797        let mat = Material::new(30e9, 0.2, 2400.0, "concrete");
798
799        let comp = ElasticComposite::new(vec![CompositeComponent::new(sec, mat).unwrap()]).unwrap();
800
801        let _ = comp.analyze(&mat).unwrap();
802
803        // Original geometry in the component must be unchanged
804        let stored = comp.component(0).unwrap();
805        assert_eq!(stored.section.area(), sec_clone.area());
806        assert_eq!(stored.section.centroid().x, sec_clone.centroid().x);
807        assert_eq!(stored.section.centroid().y, sec_clone.centroid().y);
808    }
809
810    // ---- Phase 33 additional tests ----
811
812    #[test]
813    fn composite_with_holes() {
814        // Hollow rectangular section as a single component with a hole.
815        let outer = Polygon::new(vec![
816            Point::new(0.0, 0.0),
817            Point::new(0.4, 0.0),
818            Point::new(0.4, 0.3),
819            Point::new(0.0, 0.3),
820        ]);
821        let hole = Polygon::new(vec![
822            Point::new(0.1, 0.05),
823            Point::new(0.3, 0.05),
824            Point::new(0.3, 0.25),
825            Point::new(0.1, 0.25),
826        ]);
827        let section = Section::new(outer, vec![hole]);
828        let mat = Material::new(200e9, 0.3, 7850.0, "steel");
829
830        let comp =
831            ElasticComposite::new(vec![CompositeComponent::new(section.clone(), mat).unwrap()])
832                .unwrap();
833        let result = comp.analyze(&mat).unwrap();
834        let homogeneous = SectionProperties::from_section(&section);
835
836        // Single material → transformed == homogeneous
837        let tol = 1e-10;
838        assert!((result.area - homogeneous.area).abs() < tol);
839        assert!((result.ix - homogeneous.ix).abs() < tol);
840        assert!((result.iy - homogeneous.iy).abs() < tol);
841        assert!((result.ixy - homogeneous.ixy).abs() < tol);
842
843        // Net area = 0.12 - 0.04 = 0.08
844        assert!((result.area - 0.08).abs() < 1e-10);
845    }
846
847    #[test]
848    fn three_material_components() {
849        // Three stacked rectangles with different materials.
850        let mat1 = Material::new(30e9, 0.2, 2400.0, "concrete");
851        let mat2 = Material::new(200e9, 0.3, 7850.0, "steel");
852        let mat3 = Material::new(70e9, 0.33, 2700.0, "aluminum");
853
854        let s1 = rect_section(0.0, 0.0, 0.3, 0.1);
855        let s2 = rect_section(0.0, 0.1, 0.2, 0.05);
856        let s3 = rect_section(0.0, 0.15, 0.25, 0.08);
857
858        let comp = ElasticComposite::new(vec![
859            CompositeComponent::new(s1, mat1).unwrap(),
860            CompositeComponent::new(s2, mat2).unwrap(),
861            CompositeComponent::new(s3, mat3).unwrap(),
862        ])
863        .unwrap();
864
865        assert_eq!(comp.n_components(), 3);
866
867        let result = comp.analyze(&mat1).unwrap();
868        assert!(result.area > 0.0);
869        assert!(result.ix > 0.0);
870        assert_eq!(result.components.len(), 3);
871
872        // Modular ratios
873        assert!((result.components[0].modular_ratio - 1.0).abs() < 1e-10);
874        assert!((result.components[1].modular_ratio - 200.0 / 30.0).abs() < 1e-10);
875        assert!((result.components[2].modular_ratio - 70.0 / 30.0).abs() < 1e-10);
876
877        // Transformed area = Σ n_i * A_i
878        let expected_area =
879            1.0 * (0.3 * 0.1) + (200.0 / 30.0) * (0.2 * 0.05) + (70.0 / 30.0) * (0.25 * 0.08);
880        assert!((result.area - expected_area).abs() / expected_area < 1e-10);
881
882        // Physical stiffness is reference-invariant
883        let r2 = comp.analyze(&mat2).unwrap();
884        let ea1 = mat1.youngs_modulus * result.area;
885        let ea2 = mat2.youngs_modulus * r2.area;
886        assert!((ea1 - ea2).abs() / ea1 < 1e-10);
887    }
888
889    #[test]
890    fn reference_not_present_in_components() {
891        // Reference material not among component materials — mathematically valid.
892        let mat1 = Material::new(30e9, 0.2, 2400.0, "concrete");
893        let mat2 = Material::new(200e9, 0.3, 7850.0, "steel");
894        let mat_ref = Material::new(100e9, 0.25, 5000.0, "reference");
895
896        let s1 = rect_section(0.0, 0.0, 0.2, 0.1);
897        let s2 = rect_section(0.0, 0.1, 0.2, 0.1);
898
899        let comp = ElasticComposite::new(vec![
900            CompositeComponent::new(s1, mat1).unwrap(),
901            CompositeComponent::new(s2, mat2).unwrap(),
902        ])
903        .unwrap();
904
905        let result = comp.analyze(&mat_ref).unwrap();
906
907        // n1 = 30/100 = 0.3, n2 = 200/100 = 2.0
908        assert!((result.components[0].modular_ratio - 0.3).abs() < 1e-10);
909        assert!((result.components[1].modular_ratio - 2.0).abs() < 1e-10);
910
911        // Physical EA must still be reference-invariant
912        let r_conc = comp.analyze(&mat1).unwrap();
913        let ea_ref = mat_ref.youngs_modulus * result.area;
914        let ea_conc = mat1.youngs_modulus * r_conc.area;
915        assert!((ea_ref - ea_conc).abs() / ea_conc < 1e-10);
916    }
917
918    #[test]
919    fn asymmetric_principal_axes() {
920        // L-shaped asymmetric section with two materials.
921        // Vertical leg: 0.02 × 0.2, E = 200 GPa
922        // Horizontal leg: 0.1 × 0.02, E = 30 GPa
923        let vert = rect_section(0.0, 0.0, 0.02, 0.2);
924        let horiz = rect_section(0.0, 0.0, 0.1, 0.02);
925
926        let mat_steel = Material::new(200e9, 0.3, 7850.0, "steel");
927        let mat_conc = Material::new(30e9, 0.2, 2400.0, "concrete");
928
929        let comp = ElasticComposite::new(vec![
930            CompositeComponent::new(vert, mat_steel).unwrap(),
931            CompositeComponent::new(horiz, mat_conc).unwrap(),
932        ])
933        .unwrap();
934
935        let result = comp.analyze(&mat_steel).unwrap();
936
937        // For an asymmetric section, Ixy should be non-zero.
938        assert!(
939            result.ixy.abs() > 1e-8,
940            "Ixy should be non-zero for asymmetric section"
941        );
942
943        // Principal moments must satisfy I11 >= I22
944        assert!(result.principal_i11 >= result.principal_i22);
945
946        // Principal moments must satisfy the invariant:
947        // I11 + I22 = Ix + Iy
948        let sum_principal = result.principal_i11 + result.principal_i22;
949        let sum_centroidal = result.ix + result.iy;
950        assert!((sum_principal - sum_centroidal).abs() < 1e-10);
951
952        // Principal angle must be non-zero for asymmetric section
953        assert!(
954            result.principal_phi.abs() > 1e-6,
955            "principal angle should be non-zero"
956        );
957
958        // Verify principal angle convention matches SectionProperties:
959        // phi = 0.5 * atan2(2*Ixy, Ix - Iy)
960        let expected_phi = 0.5 * (2.0 * result.ixy).atan2(result.ix - result.iy);
961        assert!((result.principal_phi - expected_phi).abs() < 1e-10);
962    }
963
964    // ---- Phase 35 boundary tests ----
965
966    #[test]
967    fn translation_invariance() {
968        // Centroidal properties (Ix, Iy, Ixy, I11, I22) must be invariant
969        // under translation.  Centroid must shift by the translation vector.
970        let mat1 = Material::new(30e9, 0.2, 2400.0, "concrete");
971        let mat2 = Material::new(200e9, 0.3, 7850.0, "steel");
972
973        let s1 = rect_section(0.0, 0.0, 0.3, 0.15);
974        let s2 = rect_section(0.05, 0.15, 0.2, 0.01);
975
976        let comp_orig = ElasticComposite::new(vec![
977            CompositeComponent::new(s1, mat1).unwrap(),
978            CompositeComponent::new(s2, mat2).unwrap(),
979        ])
980        .unwrap();
981        let r_orig = comp_orig.analyze(&mat1).unwrap();
982
983        // Translate all geometry by (dx, dy).
984        let dx = 1.7;
985        let dy = -0.4;
986
987        let s1_t = rect_section(dx, dy, 0.3, 0.15);
988        let s2_t = rect_section(0.05 + dx, 0.15 + dy, 0.2, 0.01);
989
990        let comp_t = ElasticComposite::new(vec![
991            CompositeComponent::new(s1_t, mat1).unwrap(),
992            CompositeComponent::new(s2_t, mat2).unwrap(),
993        ])
994        .unwrap();
995        let r_t = comp_t.analyze(&mat1).unwrap();
996
997        // Centroid shifts by (dx, dy).
998        assert!((r_t.centroid.x - (r_orig.centroid.x + dx)).abs() < 1e-10);
999        assert!((r_t.centroid.y - (r_orig.centroid.y + dy)).abs() < 1e-10);
1000
1001        // Centroidal properties are translation-invariant.
1002        assert!((r_t.ix - r_orig.ix).abs() < 1e-10);
1003        assert!((r_t.iy - r_orig.iy).abs() < 1e-10);
1004        assert!((r_t.ixy - r_orig.ixy).abs() < 1e-10);
1005        assert!((r_t.principal_i11 - r_orig.principal_i11).abs() < 1e-10);
1006        assert!((r_t.principal_i22 - r_orig.principal_i22).abs() < 1e-10);
1007    }
1008
1009    #[test]
1010    fn multi_component_identical_material_degeneration() {
1011        // Multiple components with the same material must produce the same
1012        // result as a single SectionProperties of the combined geometry.
1013        let mat = Material::new(200e9, 0.3, 7850.0, "steel");
1014
1015        // Two disjoint rectangles.
1016        let s1 = rect_section(0.0, 0.0, 0.2, 0.1);
1017        let s2 = rect_section(0.3, 0.0, 0.15, 0.1);
1018
1019        let comp = ElasticComposite::new(vec![
1020            CompositeComponent::new(s1.clone(), mat).unwrap(),
1021            CompositeComponent::new(s2.clone(), mat).unwrap(),
1022        ])
1023        .unwrap();
1024        let r_comp = comp.analyze(&mat).unwrap();
1025
1026        // Build a CompoundGeometry with both rectangles for SectionProperties.
1027        use crate::geometry::{CompoundGeometry, Geometry};
1028        let g1 = Geometry::new(s1.outer, s1.holes);
1029        let g2 = Geometry::new(s2.outer, s2.holes);
1030        let compound = CompoundGeometry::new(vec![g1, g2]);
1031        let r_homogeneous = SectionProperties::from_compound(&compound);
1032
1033        let tol = 1e-10;
1034        assert!((r_comp.area - r_homogeneous.area).abs() < tol);
1035        assert!((r_comp.centroid.x - r_homogeneous.centroid.x).abs() < tol);
1036        assert!((r_comp.centroid.y - r_homogeneous.centroid.y).abs() < tol);
1037        assert!((r_comp.ix - r_homogeneous.ix).abs() < tol);
1038        assert!((r_comp.iy - r_homogeneous.iy).abs() < tol);
1039        assert!((r_comp.ixy - r_homogeneous.ixy).abs() < tol);
1040        assert!((r_comp.principal_i11 - r_homogeneous.principal.i11).abs() < tol);
1041        assert!((r_comp.principal_i22 - r_homogeneous.principal.i22).abs() < tol);
1042    }
1043
1044    #[test]
1045    fn reference_modulus_scaling() {
1046        // E_ref → k·E_ref  ⟹  A' → A'/k, I' → I'/k, EA/EI invariant.
1047        let mat1 = Material::new(30e9, 0.2, 2400.0, "concrete");
1048        let mat2 = Material::new(200e9, 0.3, 7850.0, "steel");
1049
1050        let s1 = rect_section(0.0, 0.0, 0.3, 0.15);
1051        let s2 = rect_section(0.05, 0.15, 0.2, 0.01);
1052
1053        let comp = ElasticComposite::new(vec![
1054            CompositeComponent::new(s1, mat1).unwrap(),
1055            CompositeComponent::new(s2, mat2).unwrap(),
1056        ])
1057        .unwrap();
1058
1059        let r1 = comp.analyze(&mat1).unwrap();
1060
1061        // Scale reference by k.
1062        let k = 1e6;
1063        let mat_scaled = Material::new(mat1.youngs_modulus * k, 0.2, 2400.0, "scaled");
1064        let r2 = comp.analyze(&mat_scaled).unwrap();
1065
1066        // A' → A'/k
1067        assert!((r2.area * k - r1.area).abs() / r1.area < 1e-10);
1068        // I' → I'/k
1069        assert!((r2.ix * k - r1.ix).abs() / r1.ix < 1e-10);
1070        assert!((r2.iy * k - r1.iy).abs() / r1.iy < 1e-10);
1071
1072        // EA and EI are invariant.
1073        let ea1 = mat1.youngs_modulus * r1.area;
1074        let ea2 = mat_scaled.youngs_modulus * r2.area;
1075        assert!((ea1 - ea2).abs() / ea1 < 1e-10);
1076
1077        let ei1 = mat1.youngs_modulus * r1.ix;
1078        let ei2 = mat_scaled.youngs_modulus * r2.ix;
1079        assert!((ei1 - ei2).abs() / ei1 < 1e-10);
1080
1081        // Centroid is reference-invariant.
1082        assert!((r1.centroid.x - r2.centroid.x).abs() < 1e-10);
1083        assert!((r1.centroid.y - r2.centroid.y).abs() < 1e-10);
1084    }
1085
1086    #[test]
1087    fn near_identical_materials_continuity() {
1088        // Two materials with E2 = E1*(1+ε) should produce results close to
1089        // the single-material case.  No catastrophic cancellation.
1090        let e = 200e9;
1091        let mat_base = Material::new(e, 0.3, 7850.0, "base");
1092
1093        let s1 = rect_section(0.0, 0.0, 0.2, 0.1);
1094        let s2 = rect_section(0.0, 0.1, 0.2, 0.1);
1095
1096        // Single material baseline.
1097        let comp_single = ElasticComposite::new(vec![
1098            CompositeComponent::new(s1.clone(), mat_base).unwrap(),
1099            CompositeComponent::new(s2.clone(), mat_base).unwrap(),
1100        ])
1101        .unwrap();
1102        let r_single = comp_single.analyze(&mat_base).unwrap();
1103
1104        // Near-identical: E2 = E1 * (1 + 1e-12).
1105        let eps = 1e-12;
1106        let mat_near = Material::new(e * (1.0 + eps), 0.3, 7850.0, "near");
1107        let comp_near = ElasticComposite::new(vec![
1108            CompositeComponent::new(s1, mat_base).unwrap(),
1109            CompositeComponent::new(s2, mat_near).unwrap(),
1110        ])
1111        .unwrap();
1112        let r_near = comp_near.analyze(&mat_base).unwrap();
1113
1114        // Results should be very close (continuity).
1115        assert!((r_near.area - r_single.area).abs() / r_single.area < 1e-10);
1116        assert!((r_near.ix - r_single.ix).abs() / r_single.ix < 1e-10);
1117        assert!((r_near.centroid.y - r_single.centroid.y).abs() < 1e-10);
1118    }
1119
1120    #[test]
1121    fn p1_01_reproduce_modular_ratio_overflow() {
1122        let sec = rect_section(0.0, 0.0, 0.3, 0.5);
1123        let mat_huge = Material::new(1e308, 0.3, 7850.0, "huge");
1124        let mat_tiny = Material::new(1e-308, 0.3, 7850.0, "tiny");
1125        let comp =
1126            ElasticComposite::new(vec![CompositeComponent::new(sec, mat_huge).unwrap()]).unwrap();
1127        let result = comp.analyze(&mat_tiny);
1128        match result {
1129            Ok(r) => panic!(
1130                "P1-01 NOT fixed: expected Err but got Ok with area={}, ix={}",
1131                r.area, r.ix
1132            ),
1133            Err(e) => println!("P1-01 confirmed: got Err = {:?}", e),
1134        }
1135    }
1136
1137    #[test]
1138    fn p1_01_large_but_finite_modular_ratio() {
1139        let sec = rect_section(0.0, 0.0, 0.3, 0.5);
1140        let mat_huge = Material::new(1e200, 0.3, 7850.0, "huge");
1141        let mat_tiny = Material::new(1e-100, 0.3, 7850.0, "tiny");
1142        let comp =
1143            ElasticComposite::new(vec![CompositeComponent::new(sec, mat_huge).unwrap()]).unwrap();
1144        let result = comp.analyze(&mat_tiny).unwrap();
1145        assert!(result.area.is_finite(), "area should be finite");
1146        assert!(result.ix.is_finite(), "ix should be finite");
1147    }
1148}