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    /// A derived section property (centroid, centroidal inertia, or principal-axis
123    /// quantity) is not finite even though all input components were finite.
124    ///
125    /// This indicates that the combination of coordinates, areas, and modular
126    /// ratios causes an intermediate arithmetic overflow (e.g. `diff * diff`
127    /// in the Mohr's-circle principal-axis calculation) or a catastrophic
128    /// cancellation that produces `Inf` or `NaN`.
129    #[error("non-finite derived section property at stage '{stage}': {detail}")]
130    NonFiniteDerivedProperty { stage: &'static str, detail: String },
131}
132
133/// A geometric section component paired with a material.
134///
135/// The section geometry is owned (cloned) so that the original user data
136/// is never mutated.  The transformed section is an analytical
137/// representation only — the original geometry remains recoverable.
138///
139/// Fields are private; construction is only possible through
140/// [`new`](Self::new), which validates the material via
141/// [`Material::is_valid`](crate::material::Material::is_valid).  This
142/// guarantees that every `CompositeComponent` instance has a physically
143/// admissible material.
144#[derive(Debug, Clone)]
145pub struct CompositeComponent {
146    section: Section,
147    material: Material,
148}
149
150impl CompositeComponent {
151    /// Create a new composite component from a section and a material.
152    ///
153    /// Returns `Err` if the Young's modulus is not a positive, finite value
154    /// or if the section geometry is degenerate.
155    ///
156    /// The material is also checked via [`Material::is_valid`](crate::material::Material::is_valid),
157    /// which verifies that `E`, `G`, `ν`, and `ρ` are all finite and within
158    /// their physically admissible ranges.
159    pub fn new(section: Section, material: Material) -> Result<Self, CompositeError> {
160        validate_modulus(material.youngs_modulus, material.name)?;
161        if !material.is_valid() {
162            return Err(CompositeError::InvalidModulus {
163                name: material.name.to_string(),
164                value: material.youngs_modulus,
165            });
166        }
167        let area = section.area();
168        if area.abs() <= f64::EPSILON {
169            return Err(CompositeError::InvalidGeometry {
170                index: 0,
171                detail: format!("net area = {area:.6e} (too small)"),
172            });
173        }
174        if !area.is_finite() {
175            return Err(CompositeError::InvalidGeometry {
176                index: 0,
177                detail: format!("net area = {area} (not finite)"),
178            });
179        }
180        Ok(Self { section, material })
181    }
182
183    /// The Young's modulus of this component's material.
184    pub fn youngs_modulus(&self) -> f64 {
185        self.material.youngs_modulus
186    }
187
188    /// The net geometric area of this component's section.
189    pub fn area(&self) -> f64 {
190        self.section.area()
191    }
192
193    /// Borrow the geometric section.
194    pub fn section(&self) -> &Section {
195        &self.section
196    }
197
198    /// Borrow the material.
199    pub fn material(&self) -> &Material {
200        &self.material
201    }
202}
203
204fn validate_modulus(e: f64, name: &str) -> Result<(), CompositeError> {
205    if !e.is_finite() || e <= 0.0 {
206        return Err(CompositeError::InvalidModulus {
207            name: name.to_string(),
208            value: e,
209        });
210    }
211    Ok(())
212}
213
214/// Per-component result of a composite section analysis.
215///
216/// Retains enough information to recover the original material properties,
217/// the modular ratio used, and the original vs transformed area.
218#[derive(Debug, Clone)]
219pub struct ComponentAnalysis {
220    /// The original material assigned to this component.
221    pub material: Material,
222    /// Modular ratio `n = E_i / E_ref` used for this component.
223    pub modular_ratio: f64,
224    /// Original (geometric) net area of the component \[m²\].
225    pub original_area: f64,
226    /// Transformed area `n × A_original` \[m²\].
227    pub transformed_area: f64,
228    /// Centroid of the component in global coordinates.
229    pub centroid: Point,
230}
231
232/// Result of an elastic composite section analysis.
233///
234/// Contains the transformed section properties (equivalent homogeneous
235/// section in the reference material) plus per-component analysis data.
236#[derive(Debug, Clone)]
237pub struct CompositeAnalysisResult {
238    /// Transformed area `Σ(n_i · A_i)` \[m²\].
239    pub area: f64,
240    /// Centroid of the transformed section in global coordinates.
241    pub centroid: Point,
242    /// Transformed second moment of area about the centroidal x-axis \[m⁴\].
243    ///
244    /// This is the **reference-material transformed** value `I'_x`, not the
245    /// physical inertia.  The physical bending stiffness is `E_ref · I'_x`.
246    pub ix: f64,
247    /// Transformed second moment of area about the centroidal y-axis \[m⁴\].
248    ///
249    /// This is the **reference-material transformed** value `I'_y`, not the
250    /// physical inertia.  The physical bending stiffness is `E_ref · I'_y`.
251    pub iy: f64,
252    /// Transformed product of inertia about the centroidal axes \[m⁴\].
253    ///
254    /// This is the **reference-material transformed** value `I'_xy`.
255    /// The physical value is `E_ref · I'_xy`.
256    pub ixy: f64,
257    /// Major principal second moment of area \[m⁴\].
258    pub principal_i11: f64,
259    /// Minor principal second moment of area \[m⁴\].
260    pub principal_i22: f64,
261    /// Principal angle from centroidal x-axis to axis 11, CCW positive \[rad\].
262    pub principal_phi: f64,
263    /// The reference material used for the transformation.
264    pub reference_material: Material,
265    /// Per-component analysis data.
266    pub components: Vec<ComponentAnalysis>,
267}
268
269/// A multi-material composite section for elastic transformed-section analysis.
270///
271/// Components are stored in insertion order.  The original geometry is
272/// never mutated — [`analyze`](Self::analyze) produces an analytical
273/// transformed representation only.
274///
275/// # Component semantics
276///
277/// Each component represents a **distinct physical material region**.
278/// Components are summed algebraically — if two components overlap
279/// geometrically, the overlapping region is **double-counted** in the
280/// transformed section.  No Boolean union is performed.  Callers are
281/// responsible for ensuring components represent disjoint regions.
282#[derive(Debug, Clone)]
283pub struct ElasticComposite {
284    components: Vec<CompositeComponent>,
285}
286
287impl ElasticComposite {
288    /// Create a new composite section from a list of components.
289    ///
290    /// Returns `Err` if the list is empty. Individual component validation
291    /// (material/geometry) is performed by [`CompositeComponent::new`] and
292    /// [`Self::analyze`].
293    pub fn new(components: Vec<CompositeComponent>) -> Result<Self, CompositeError> {
294        if components.is_empty() {
295            return Err(CompositeError::NoComponents);
296        }
297        Ok(Self { components })
298    }
299
300    /// Number of components.
301    pub fn n_components(&self) -> usize {
302        self.components.len()
303    }
304
305    /// Borrow the component at `index`.
306    pub fn component(&self, index: usize) -> Option<&CompositeComponent> {
307        self.components.get(index)
308    }
309
310    /// Analyse the composite section using the transformed-section method.
311    ///
312    /// # Arguments
313    ///
314    /// * `reference_material` — the reference material whose Young's modulus
315    ///   `E_ref` defines the modular ratio `n_i = E_i / E_ref`.  Must have
316    ///   a positive, finite Young's modulus.
317    ///
318    /// The reference material **need not** be one of the component materials.
319    /// Any positive, finite modulus produces a valid transformed section.
320    /// The physical stiffnesses `E_ref · A'`, `E_ref · I'_x`, etc. are
321    /// invariant to the choice of reference material.
322    ///
323    /// # Algorithm
324    ///
325    /// 1. For each component, compute geometric properties (area, centroid,
326    ///    centroidal moments) via [`SectionProperties`].
327    /// 2. Transfer centroidal moments to global axes using the parallel-axis
328    ///    theorem.
329    /// 3. Multiply each component's contribution by its modular ratio `n_i`.
330    /// 4. Sum to obtain the transformed section's global moments.
331    /// 5. Compute the transformed centroid and transfer back to centroidal
332    ///    axes.
333    /// 6. Compute principal axes via Mohr's circle.
334    ///
335    /// # Errors
336    ///
337    /// Returns `Err` if:
338    /// * the reference material modulus is invalid,
339    /// * any component's material fails [`Material::is_valid`](crate::material::Material::is_valid)
340    ///   (defense-in-depth — components are validated at construction),
341    /// * any component's geometry is degenerate,
342    /// * the transformed net area is zero or near-zero.
343    pub fn analyze(
344        &self,
345        reference_material: &Material,
346    ) -> Result<CompositeAnalysisResult, CompositeError> {
347        validate_modulus(reference_material.youngs_modulus, reference_material.name).map_err(
348            |_| CompositeError::InvalidReferenceModulus {
349                value: reference_material.youngs_modulus,
350            },
351        )?;
352
353        // Defense-in-depth: re-validate each component's material.
354        // CompositeComponent fields are private (v0.2.0), so construction
355        // via CompositeComponent::new is the only public path and it
356        // validates.  This guard is retained as a safety net.
357        for comp in &self.components {
358            if !comp.material.is_valid() {
359                return Err(CompositeError::InvalidModulus {
360                    name: comp.material.name.to_string(),
361                    value: comp.material.youngs_modulus,
362                });
363            }
364        }
365
366        let e_ref = reference_material.youngs_modulus;
367
368        // --- Pass 1: composite centroid ---
369        // Accumulate transformed area and first moments only.
370        // Per-component inertia data is stored for Pass 2.
371        let mut total_area = 0.0_f64;
372        let mut first_x = 0.0_f64;
373        let mut first_y = 0.0_f64;
374
375        let mut component_results: Vec<ComponentAnalysis> =
376            Vec::with_capacity(self.components.len());
377
378        // (n, area, cx, cy, ix, iy, ixy) for each component
379        let mut comp_data: Vec<(f64, f64, f64, f64, f64, f64, f64)> =
380            Vec::with_capacity(self.components.len());
381
382        for (i, comp) in self.components.iter().enumerate() {
383            let props = SectionProperties::try_from_section(&comp.section)
384                .map_err(|detail| CompositeError::InvalidGeometry { index: i, detail })?;
385
386            let n = comp.material.youngs_modulus / e_ref;
387            if !n.is_finite() {
388                return Err(CompositeError::NonFiniteModularRatio {
389                    index: i,
390                    e_component: comp.material.youngs_modulus,
391                    e_ref,
392                });
393            }
394            let area = props.area;
395            let cx = props.centroid.x;
396            let cy = props.centroid.y;
397
398            let n_area = n * area;
399            if !n_area.is_finite() {
400                return Err(CompositeError::NonFiniteModularRatio {
401                    index: i,
402                    e_component: comp.material.youngs_modulus,
403                    e_ref,
404                });
405            }
406            total_area += n_area;
407            first_x += n_area * cx;
408            first_y += n_area * cy;
409
410            comp_data.push((n, area, cx, cy, props.ix, props.iy, props.ixy));
411            component_results.push(ComponentAnalysis {
412                material: comp.material,
413                modular_ratio: n,
414                original_area: area,
415                transformed_area: n_area,
416                centroid: props.centroid,
417            });
418        }
419
420        if total_area.abs() <= f64::EPSILON {
421            return Err(CompositeError::ZeroTransformedArea);
422        }
423        if !total_area.is_finite() || !first_x.is_finite() || !first_y.is_finite() {
424            return Err(CompositeError::NonFiniteDerivedProperty {
425                stage: "weighted_accumulation",
426                detail: format!(
427                    "total_area={}, first_x={}, first_y={}",
428                    total_area, first_x, first_y
429                ),
430            });
431        }
432
433        // Transformed centroid.
434        let centroid = Point::new(first_x / total_area, first_y / total_area);
435        if !centroid.x.is_finite() || !centroid.y.is_finite() {
436            return Err(CompositeError::NonFiniteDerivedProperty {
437                stage: "centroid",
438                detail: format!(
439                    "centroid = ({}, {}) from first_x={}, first_y={}, total_area={}",
440                    centroid.x, centroid.y, first_x, first_y, total_area
441                ),
442            });
443        }
444
445        // --- Pass 2: direct centroidal accumulation ---
446        // Accumulate inertia directly about the composite centroid using
447        // the parallel-axis theorem with (y_i - cy) offsets.  This avoids
448        // the catastrophic cancellation that occurs when subtracting
449        // large `ix_global - total_area * cy^2` values.
450        let mut ix_c = 0.0_f64;
451        let mut iy_c = 0.0_f64;
452        let mut ixy_c = 0.0_f64;
453        for &(n, area, cx, cy, ix_i, iy_i, ixy_i) in &comp_data {
454            let dx = cx - centroid.x;
455            let dy = cy - centroid.y;
456            ix_c += n * (ix_i + area * dy * dy);
457            iy_c += n * (iy_i + area * dx * dx);
458            ixy_c += n * (ixy_i + area * dx * dy);
459        }
460        if !ix_c.is_finite() || !iy_c.is_finite() || !ixy_c.is_finite() {
461            return Err(CompositeError::NonFiniteDerivedProperty {
462                stage: "centroidal_inertia",
463                detail: format!(
464                    "ix_c={}, iy_c={}, ixy_c={} (centroid=({}, {}), total_area={})",
465                    ix_c, iy_c, ixy_c, centroid.x, centroid.y, total_area
466                ),
467            });
468        }
469
470        // Principal axes (Mohr's circle, same convention as SectionProperties).
471        let avg = (ix_c + iy_c) * 0.5;
472        let diff = (ix_c - iy_c) * 0.5;
473        let radius = (diff * diff + ixy_c * ixy_c).sqrt();
474        let i11 = avg + radius;
475        let i22 = avg - radius;
476        let phi = 0.5 * (2.0 * ixy_c).atan2(ix_c - iy_c);
477        if !i11.is_finite() || !i22.is_finite() || !phi.is_finite() {
478            return Err(CompositeError::NonFiniteDerivedProperty {
479                stage: "principal_axes",
480                detail: format!(
481                    "i11={}, i22={}, phi={} (ix_c={}, iy_c={}, ixy_c={})",
482                    i11, i22, phi, ix_c, iy_c, ixy_c
483                ),
484            });
485        }
486
487        Ok(CompositeAnalysisResult {
488            area: total_area,
489            centroid,
490            ix: ix_c,
491            iy: iy_c,
492            ixy: ixy_c,
493            principal_i11: i11,
494            principal_i22: i22,
495            principal_phi: phi,
496            reference_material: *reference_material,
497            components: component_results,
498        })
499    }
500
501    /// Convenience: analyse using the first component's material as reference.
502    ///
503    /// # Errors
504    ///
505    /// Same as [`analyze`](Self::analyze).
506    pub fn analyze_with_first_reference(&self) -> Result<CompositeAnalysisResult, CompositeError> {
507        let ref_mat = self
508            .components
509            .first()
510            .map(|c| c.material)
511            .ok_or(CompositeError::NoComponents)?;
512        self.analyze(&ref_mat)
513    }
514}
515
516#[cfg(test)]
517mod tests {
518    use super::*;
519    use crate::material::presets::*;
520    use crate::{Point, Polygon};
521
522    fn rect_section(x0: f64, y0: f64, w: f64, h: f64) -> Section {
523        Section::new(
524            Polygon::new(vec![
525                Point::new(x0, y0),
526                Point::new(x0 + w, y0),
527                Point::new(x0 + w, y0 + h),
528                Point::new(x0, y0 + h),
529            ]),
530            Vec::new(),
531        )
532    }
533
534    #[test]
535    fn single_material_degeneration() {
536        let sec = rect_section(0.0, 0.0, 0.3, 0.5);
537        let comp = ElasticComposite::new(vec![
538            CompositeComponent::new(sec.clone(), CONCRETE_C30_37).unwrap(),
539        ])
540        .unwrap();
541
542        let result = comp.analyze(&CONCRETE_C30_37).unwrap();
543        let homogeneous = SectionProperties::from_section(&sec);
544
545        let tol = 1e-10;
546        assert!((result.area - homogeneous.area).abs() < tol);
547        assert!((result.ix - homogeneous.ix).abs() < tol);
548        assert!((result.iy - homogeneous.iy).abs() < tol);
549        assert!((result.ixy - homogeneous.ixy).abs() < tol);
550    }
551
552    #[test]
553    fn two_material_rectangular_analytical() {
554        // Two stacked rectangles:
555        //   bottom: 0.2 × 0.1, E = 30 GPa, centroid (0.1, 0.05)
556        //   top:    0.2 × 0.1, E = 60 GPa, centroid (0.1, 0.15)
557        // Reference: E_ref = 30 GPa → n_bottom = 1, n_top = 2
558
559        let e_ref = 30e9;
560        let e_bottom = 30e9;
561        let e_top = 60e9;
562
563        let mat_ref = Material::new(e_ref, 0.2, 2400.0, "ref");
564        let mat_bottom = Material::new(e_bottom, 0.2, 2400.0, "bottom");
565        let mat_top = Material::new(e_top, 0.2, 2400.0, "top");
566
567        let bottom = rect_section(0.0, 0.0, 0.2, 0.1);
568        let top = rect_section(0.0, 0.1, 0.2, 0.1);
569
570        let comp = ElasticComposite::new(vec![
571            CompositeComponent::new(bottom, mat_bottom).unwrap(),
572            CompositeComponent::new(top, mat_top).unwrap(),
573        ])
574        .unwrap();
575
576        let result = comp.analyze(&mat_ref).unwrap();
577
578        // Analytical:
579        // A' = 1·(0.02) + 2·(0.02) = 0.06
580        let a_bottom = 0.2 * 0.1_f64;
581        let a_top = 0.2 * 0.1_f64;
582        let n_bottom = e_bottom / e_ref;
583        let n_top = e_top / e_ref;
584        let a_transformed = n_bottom * a_bottom + n_top * a_top;
585        assert!((result.area - a_transformed).abs() < 1e-12);
586
587        // y_bar = (1·0.02·0.05 + 2·0.02·0.15) / 0.06
588        let y_bar = (n_bottom * a_bottom * 0.05 + n_top * a_top * 0.15) / a_transformed;
589        assert!((result.centroid.y - y_bar).abs() < 1e-12);
590        assert!((result.centroid.x - 0.1).abs() < 1e-12);
591
592        // Ix about centroidal:
593        // Ix_bottom,c = b·h³/12 + A·(cy - y_bar)²
594        let ix_bottom_local = 0.2 * 0.1_f64.powi(3) / 12.0;
595        let ix_top_local = 0.2 * 0.1_f64.powi(3) / 12.0;
596        let ix_analytical = n_bottom * (ix_bottom_local + a_bottom * (0.05 - y_bar).powi(2))
597            + n_top * (ix_top_local + a_top * (0.15 - y_bar).powi(2));
598        assert!((result.ix - ix_analytical).abs() < 1e-12);
599
600        // Iy about centroidal (both rectangles have same x-centroid = 0.1):
601        let iy_bottom_local = 0.1 * 0.2_f64.powi(3) / 12.0;
602        let iy_top_local = 0.1 * 0.2_f64.powi(3) / 12.0;
603        let iy_analytical = n_bottom * iy_bottom_local + n_top * iy_top_local;
604        assert!((result.iy - iy_analytical).abs() < 1e-12);
605
606        // Ixy = 0 (symmetric about x = 0.1)
607        assert!(result.ixy.abs() < 1e-12);
608    }
609
610    #[test]
611    fn steel_concrete_composite() {
612        let slab = rect_section(0.0, 0.0, 0.3, 0.15);
613        let steel = rect_section(0.05, 0.15, 0.2, 0.01);
614
615        let comp = ElasticComposite::new(vec![
616            CompositeComponent::new(slab, CONCRETE_C30_37).unwrap(),
617            CompositeComponent::new(steel, STEEL_S355).unwrap(),
618        ])
619        .unwrap();
620
621        // Reference: concrete
622        let result = comp.analyze(&CONCRETE_C30_37).unwrap();
623
624        let n_steel = STEEL_S355.youngs_modulus / CONCRETE_C30_37.youngs_modulus;
625        let n_conc = 1.0_f64;
626
627        // Check modular ratios in component results
628        assert!((result.components[0].modular_ratio - n_conc).abs() < 1e-10);
629        assert!((result.components[1].modular_ratio - n_steel).abs() < 1e-10);
630
631        // Transformed area = A_conc + n_steel * A_steel
632        let a_conc = 0.3 * 0.15;
633        let a_steel = 0.2 * 0.01;
634        let expected_area = n_conc * a_conc + n_steel * a_steel;
635        assert!((result.area - expected_area).abs() / expected_area < 1e-10);
636
637        // Original areas preserved
638        assert!((result.components[0].original_area - a_conc).abs() < 1e-12);
639        assert!((result.components[1].original_area - a_steel).abs() < 1e-12);
640
641        // Transformed areas
642        assert!((result.components[0].transformed_area - n_conc * a_conc).abs() < 1e-12);
643        assert!((result.components[1].transformed_area - n_steel * a_steel).abs() < 1e-12);
644    }
645
646    #[test]
647    fn reference_material_reversal() {
648        // Use an asymmetric section so Iy and Ixy are non-trivial.
649        // Slab offset left, steel plate offset right → non-zero Ixy.
650        let slab = rect_section(0.0, 0.0, 0.3, 0.15);
651        let steel = rect_section(0.15, 0.15, 0.2, 0.01);
652
653        let comp = ElasticComposite::new(vec![
654            CompositeComponent::new(slab, CONCRETE_C30_37).unwrap(),
655            CompositeComponent::new(steel, STEEL_S355).unwrap(),
656        ])
657        .unwrap();
658
659        let r_conc = comp.analyze(&CONCRETE_C30_37).unwrap();
660        let r_steel = comp.analyze(&STEEL_S355).unwrap();
661
662        // Physical stiffnesses are reference-independent.
663        // EA = E_ref * A'
664        let ea_conc = CONCRETE_C30_37.youngs_modulus * r_conc.area;
665        let ea_steel = STEEL_S355.youngs_modulus * r_steel.area;
666        assert!((ea_conc - ea_steel).abs() / ea_conc < 1e-10);
667
668        // EIx = E_ref * Ix'
669        let ei_conc = CONCRETE_C30_37.youngs_modulus * r_conc.ix;
670        let ei_steel = STEEL_S355.youngs_modulus * r_steel.ix;
671        assert!((ei_conc - ei_steel).abs() / ei_conc < 1e-10);
672
673        // EIy = E_ref * Iy'
674        let eiy_conc = CONCRETE_C30_37.youngs_modulus * r_conc.iy;
675        let eiy_steel = STEEL_S355.youngs_modulus * r_steel.iy;
676        assert!((eiy_conc - eiy_steel).abs() / eiy_conc < 1e-10);
677
678        // EIxy = E_ref * Ixy' (use absolute tolerance — Ixy can be near zero)
679        let eixy_conc = CONCRETE_C30_37.youngs_modulus * r_conc.ixy;
680        let eixy_steel = STEEL_S355.youngs_modulus * r_steel.ixy;
681        assert!((eixy_conc - eixy_steel).abs() < 1e-3);
682
683        // Centroid must be the same (physical location)
684        assert!((r_conc.centroid.x - r_steel.centroid.x).abs() < 1e-10);
685        assert!((r_conc.centroid.y - r_steel.centroid.y).abs() < 1e-10);
686    }
687
688    #[test]
689    fn symmetric_composite() {
690        // Two identical rectangles symmetric about y-axis:
691        //   left:  0.1 × 0.2 at x = [-0.15, -0.05], E = 30 GPa
692        //   right: 0.1 × 0.2 at x = [0.05, 0.15],  E = 200 GPa
693        // Despite different materials, geometry is symmetric → x_bar = 0
694        // but the centroid shifts towards the stiffer side.
695        //
696        // Actually with different E, the *transformed* centroid shifts.
697        // For a true symmetry test we need same material on both sides.
698
699        let left = rect_section(-0.15, -0.1, 0.1, 0.2);
700        let right = rect_section(0.05, -0.1, 0.1, 0.2);
701
702        let mat = Material::new(30e9, 0.2, 2400.0, "same");
703
704        let comp = ElasticComposite::new(vec![
705            CompositeComponent::new(left, mat).unwrap(),
706            CompositeComponent::new(right, mat).unwrap(),
707        ])
708        .unwrap();
709
710        let result = comp.analyze(&mat).unwrap();
711
712        // Symmetric → centroid at origin
713        assert!(result.centroid.x.abs() < 1e-12);
714        assert!(result.centroid.y.abs() < 1e-12);
715
716        // Ixy = 0 for doubly-symmetric section
717        assert!(result.ixy.abs() < 1e-12);
718    }
719
720    #[test]
721    fn material_position_sensitivity() {
722        // Two scenarios:
723        //   A: stiff material on top, soft on bottom
724        //   B: stiff material on bottom, soft on top
725        // The centroid must move towards the stiff material.
726
727        let e_soft = 30e9;
728        let e_stiff = 200e9;
729        let mat_soft = Material::new(e_soft, 0.2, 2400.0, "soft");
730        let mat_stiff = Material::new(e_stiff, 0.2, 2400.0, "stiff");
731
732        let bottom = rect_section(0.0, 0.0, 0.2, 0.1);
733        let top = rect_section(0.0, 0.1, 0.2, 0.1);
734
735        // Scenario A: stiff on top
736        let comp_a = ElasticComposite::new(vec![
737            CompositeComponent::new(bottom.clone(), mat_soft).unwrap(),
738            CompositeComponent::new(top.clone(), mat_stiff).unwrap(),
739        ])
740        .unwrap();
741        let result_a = comp_a.analyze(&mat_soft).unwrap();
742
743        // Scenario B: stiff on bottom
744        let comp_b = ElasticComposite::new(vec![
745            CompositeComponent::new(bottom, mat_stiff).unwrap(),
746            CompositeComponent::new(top, mat_soft).unwrap(),
747        ])
748        .unwrap();
749        let result_b = comp_b.analyze(&mat_soft).unwrap();
750
751        // Geometric centroid of the two stacked rectangles is at y = 0.1.
752        // In A, stiff on top → transformed centroid shifts above 0.1.
753        assert!(
754            result_a.centroid.y > 0.1,
755            "centroid should shift towards stiff top"
756        );
757        // In B, stiff on bottom → transformed centroid shifts below 0.1.
758        assert!(
759            result_b.centroid.y < 0.1,
760            "centroid should shift towards stiff bottom"
761        );
762
763        // The two centroids must be different
764        assert!((result_a.centroid.y - result_b.centroid.y).abs() > 0.01);
765
766        // Ix is identical by the y ↔ (0.2 − y) symmetry of the geometry.
767        assert!((result_a.ix - result_b.ix).abs() < 1e-10);
768
769        // The result is not merely based on total transformed area:
770        // a single-material section with the same total transformed area
771        // and same overall bounding box would have a different Ix.
772        let total_transformed_area = result_a.area;
773        let single_mat_ix = 0.2 * 0.2_f64.powi(3) / 12.0 * (total_transformed_area / (0.2 * 0.2));
774        assert!((result_a.ix - single_mat_ix).abs() > 1e-6);
775    }
776
777    #[test]
778    fn geometric_scaling() {
779        let e1 = 30e9;
780        let e2 = 200e9;
781        let mat1 = Material::new(e1, 0.2, 2400.0, "m1");
782        let mat2 = Material::new(e2, 0.3, 7850.0, "m2");
783
784        let alpha = 2.5_f64;
785
786        // Original
787        let s1 = rect_section(0.0, 0.0, 0.2, 0.1);
788        let s2 = rect_section(0.1, 0.1, 0.1, 0.05);
789
790        let comp_orig = ElasticComposite::new(vec![
791            CompositeComponent::new(s1.clone(), mat1).unwrap(),
792            CompositeComponent::new(s2.clone(), mat2).unwrap(),
793        ])
794        .unwrap();
795        let r_orig = comp_orig.analyze(&mat1).unwrap();
796
797        // Scaled by alpha
798        let s1_scaled = rect_section(0.0, 0.0, 0.2 * alpha, 0.1 * alpha);
799        let s2_scaled = rect_section(0.1 * alpha, 0.1 * alpha, 0.1 * alpha, 0.05 * alpha);
800
801        let comp_scaled = ElasticComposite::new(vec![
802            CompositeComponent::new(s1_scaled, mat1).unwrap(),
803            CompositeComponent::new(s2_scaled, mat2).unwrap(),
804        ])
805        .unwrap();
806        let r_scaled = comp_scaled.analyze(&mat1).unwrap();
807
808        // A ~ α²
809        assert!((r_scaled.area / r_orig.area - alpha * alpha).abs() < 1e-10);
810        // centroid ~ α
811        assert!((r_scaled.centroid.x / r_orig.centroid.x - alpha).abs() < 1e-10);
812        assert!((r_scaled.centroid.y / r_orig.centroid.y - alpha).abs() < 1e-10);
813        // Ix, Iy, Ixy ~ α⁴
814        assert!((r_scaled.ix / r_orig.ix - alpha.powi(4)).abs() < 1e-10);
815        assert!((r_scaled.iy / r_orig.iy - alpha.powi(4)).abs() < 1e-10);
816        assert!((r_scaled.ixy / r_orig.ixy - alpha.powi(4)).abs() < 1e-10);
817    }
818
819    #[test]
820    fn invalid_modulus_zero() {
821        let sec = rect_section(0.0, 0.0, 0.1, 0.1);
822        let mat = Material::new(0.0, 0.2, 2400.0, "zero E");
823        assert!(CompositeComponent::new(sec, mat).is_err());
824    }
825
826    #[test]
827    fn invalid_modulus_negative() {
828        let sec = rect_section(0.0, 0.0, 0.1, 0.1);
829        let mat = Material::new(-1e9, 0.2, 2400.0, "negative E");
830        assert!(CompositeComponent::new(sec, mat).is_err());
831    }
832
833    #[test]
834    fn invalid_modulus_nan() {
835        let sec = rect_section(0.0, 0.0, 0.1, 0.1);
836        let mat = Material::new(f64::NAN, 0.2, 2400.0, "NaN E");
837        assert!(CompositeComponent::new(sec, mat).is_err());
838    }
839
840    #[test]
841    fn invalid_modulus_infinity() {
842        let sec = rect_section(0.0, 0.0, 0.1, 0.1);
843        let mat = Material::new(f64::INFINITY, 0.2, 2400.0, "inf E");
844        assert!(CompositeComponent::new(sec, mat).is_err());
845    }
846
847    #[test]
848    fn invalid_reference_material() {
849        let sec = rect_section(0.0, 0.0, 0.1, 0.1);
850        let mat = Material::new(200e9, 0.3, 7850.0, "steel");
851        let comp = ElasticComposite::new(vec![CompositeComponent::new(sec, mat).unwrap()]).unwrap();
852
853        let bad_ref = Material::new(0.0, 0.2, 2400.0, "zero");
854        assert!(comp.analyze(&bad_ref).is_err());
855
856        let nan_ref = Material::new(f64::NAN, 0.2, 2400.0, "nan");
857        assert!(comp.analyze(&nan_ref).is_err());
858    }
859
860    #[test]
861    fn empty_components_rejected() {
862        let result = ElasticComposite::new(Vec::new());
863        assert!(result.is_err());
864    }
865
866    #[test]
867    fn original_geometry_preserved() {
868        let sec = rect_section(0.0, 0.0, 0.3, 0.5);
869        let sec_clone = sec.clone();
870        let mat = Material::new(30e9, 0.2, 2400.0, "concrete");
871
872        let comp = ElasticComposite::new(vec![CompositeComponent::new(sec, mat).unwrap()]).unwrap();
873
874        let _ = comp.analyze(&mat).unwrap();
875
876        // Original geometry in the component must be unchanged
877        let stored = comp.component(0).unwrap();
878        assert_eq!(stored.section.area(), sec_clone.area());
879        assert_eq!(stored.section.centroid().x, sec_clone.centroid().x);
880        assert_eq!(stored.section.centroid().y, sec_clone.centroid().y);
881    }
882
883    // ---- Phase 33 additional tests ----
884
885    #[test]
886    fn composite_with_holes() {
887        // Hollow rectangular section as a single component with a hole.
888        let outer = Polygon::new(vec![
889            Point::new(0.0, 0.0),
890            Point::new(0.4, 0.0),
891            Point::new(0.4, 0.3),
892            Point::new(0.0, 0.3),
893        ]);
894        let hole = Polygon::new(vec![
895            Point::new(0.1, 0.05),
896            Point::new(0.3, 0.05),
897            Point::new(0.3, 0.25),
898            Point::new(0.1, 0.25),
899        ]);
900        let section = Section::new(outer, vec![hole]);
901        let mat = Material::new(200e9, 0.3, 7850.0, "steel");
902
903        let comp =
904            ElasticComposite::new(vec![CompositeComponent::new(section.clone(), mat).unwrap()])
905                .unwrap();
906        let result = comp.analyze(&mat).unwrap();
907        let homogeneous = SectionProperties::from_section(&section);
908
909        // Single material → transformed == homogeneous
910        let tol = 1e-10;
911        assert!((result.area - homogeneous.area).abs() < tol);
912        assert!((result.ix - homogeneous.ix).abs() < tol);
913        assert!((result.iy - homogeneous.iy).abs() < tol);
914        assert!((result.ixy - homogeneous.ixy).abs() < tol);
915
916        // Net area = 0.12 - 0.04 = 0.08
917        assert!((result.area - 0.08).abs() < 1e-10);
918    }
919
920    #[test]
921    fn three_material_components() {
922        // Three stacked rectangles with different materials.
923        let mat1 = Material::new(30e9, 0.2, 2400.0, "concrete");
924        let mat2 = Material::new(200e9, 0.3, 7850.0, "steel");
925        let mat3 = Material::new(70e9, 0.33, 2700.0, "aluminum");
926
927        let s1 = rect_section(0.0, 0.0, 0.3, 0.1);
928        let s2 = rect_section(0.0, 0.1, 0.2, 0.05);
929        let s3 = rect_section(0.0, 0.15, 0.25, 0.08);
930
931        let comp = ElasticComposite::new(vec![
932            CompositeComponent::new(s1, mat1).unwrap(),
933            CompositeComponent::new(s2, mat2).unwrap(),
934            CompositeComponent::new(s3, mat3).unwrap(),
935        ])
936        .unwrap();
937
938        assert_eq!(comp.n_components(), 3);
939
940        let result = comp.analyze(&mat1).unwrap();
941        assert!(result.area > 0.0);
942        assert!(result.ix > 0.0);
943        assert_eq!(result.components.len(), 3);
944
945        // Modular ratios
946        assert!((result.components[0].modular_ratio - 1.0).abs() < 1e-10);
947        assert!((result.components[1].modular_ratio - 200.0 / 30.0).abs() < 1e-10);
948        assert!((result.components[2].modular_ratio - 70.0 / 30.0).abs() < 1e-10);
949
950        // Transformed area = Σ n_i * A_i
951        let expected_area =
952            1.0 * (0.3 * 0.1) + (200.0 / 30.0) * (0.2 * 0.05) + (70.0 / 30.0) * (0.25 * 0.08);
953        assert!((result.area - expected_area).abs() / expected_area < 1e-10);
954
955        // Physical stiffness is reference-invariant
956        let r2 = comp.analyze(&mat2).unwrap();
957        let ea1 = mat1.youngs_modulus * result.area;
958        let ea2 = mat2.youngs_modulus * r2.area;
959        assert!((ea1 - ea2).abs() / ea1 < 1e-10);
960    }
961
962    #[test]
963    fn reference_not_present_in_components() {
964        // Reference material not among component materials — mathematically valid.
965        let mat1 = Material::new(30e9, 0.2, 2400.0, "concrete");
966        let mat2 = Material::new(200e9, 0.3, 7850.0, "steel");
967        let mat_ref = Material::new(100e9, 0.25, 5000.0, "reference");
968
969        let s1 = rect_section(0.0, 0.0, 0.2, 0.1);
970        let s2 = rect_section(0.0, 0.1, 0.2, 0.1);
971
972        let comp = ElasticComposite::new(vec![
973            CompositeComponent::new(s1, mat1).unwrap(),
974            CompositeComponent::new(s2, mat2).unwrap(),
975        ])
976        .unwrap();
977
978        let result = comp.analyze(&mat_ref).unwrap();
979
980        // n1 = 30/100 = 0.3, n2 = 200/100 = 2.0
981        assert!((result.components[0].modular_ratio - 0.3).abs() < 1e-10);
982        assert!((result.components[1].modular_ratio - 2.0).abs() < 1e-10);
983
984        // Physical EA must still be reference-invariant
985        let r_conc = comp.analyze(&mat1).unwrap();
986        let ea_ref = mat_ref.youngs_modulus * result.area;
987        let ea_conc = mat1.youngs_modulus * r_conc.area;
988        assert!((ea_ref - ea_conc).abs() / ea_conc < 1e-10);
989    }
990
991    #[test]
992    fn asymmetric_principal_axes() {
993        // L-shaped asymmetric section with two materials.
994        // Vertical leg: 0.02 × 0.2, E = 200 GPa
995        // Horizontal leg: 0.1 × 0.02, E = 30 GPa
996        let vert = rect_section(0.0, 0.0, 0.02, 0.2);
997        let horiz = rect_section(0.0, 0.0, 0.1, 0.02);
998
999        let mat_steel = Material::new(200e9, 0.3, 7850.0, "steel");
1000        let mat_conc = Material::new(30e9, 0.2, 2400.0, "concrete");
1001
1002        let comp = ElasticComposite::new(vec![
1003            CompositeComponent::new(vert, mat_steel).unwrap(),
1004            CompositeComponent::new(horiz, mat_conc).unwrap(),
1005        ])
1006        .unwrap();
1007
1008        let result = comp.analyze(&mat_steel).unwrap();
1009
1010        // For an asymmetric section, Ixy should be non-zero.
1011        assert!(
1012            result.ixy.abs() > 1e-8,
1013            "Ixy should be non-zero for asymmetric section"
1014        );
1015
1016        // Principal moments must satisfy I11 >= I22
1017        assert!(result.principal_i11 >= result.principal_i22);
1018
1019        // Principal moments must satisfy the invariant:
1020        // I11 + I22 = Ix + Iy
1021        let sum_principal = result.principal_i11 + result.principal_i22;
1022        let sum_centroidal = result.ix + result.iy;
1023        assert!((sum_principal - sum_centroidal).abs() < 1e-10);
1024
1025        // Principal angle must be non-zero for asymmetric section
1026        assert!(
1027            result.principal_phi.abs() > 1e-6,
1028            "principal angle should be non-zero"
1029        );
1030
1031        // Verify principal angle convention matches SectionProperties:
1032        // phi = 0.5 * atan2(2*Ixy, Ix - Iy)
1033        let expected_phi = 0.5 * (2.0 * result.ixy).atan2(result.ix - result.iy);
1034        assert!((result.principal_phi - expected_phi).abs() < 1e-10);
1035    }
1036
1037    // ---- Phase 35 boundary tests ----
1038
1039    #[test]
1040    fn translation_invariance() {
1041        // Centroidal properties (Ix, Iy, Ixy, I11, I22) must be invariant
1042        // under translation.  Centroid must shift by the translation vector.
1043        let mat1 = Material::new(30e9, 0.2, 2400.0, "concrete");
1044        let mat2 = Material::new(200e9, 0.3, 7850.0, "steel");
1045
1046        let s1 = rect_section(0.0, 0.0, 0.3, 0.15);
1047        let s2 = rect_section(0.05, 0.15, 0.2, 0.01);
1048
1049        let comp_orig = ElasticComposite::new(vec![
1050            CompositeComponent::new(s1, mat1).unwrap(),
1051            CompositeComponent::new(s2, mat2).unwrap(),
1052        ])
1053        .unwrap();
1054        let r_orig = comp_orig.analyze(&mat1).unwrap();
1055
1056        // Translate all geometry by (dx, dy).
1057        let dx = 1.7;
1058        let dy = -0.4;
1059
1060        let s1_t = rect_section(dx, dy, 0.3, 0.15);
1061        let s2_t = rect_section(0.05 + dx, 0.15 + dy, 0.2, 0.01);
1062
1063        let comp_t = ElasticComposite::new(vec![
1064            CompositeComponent::new(s1_t, mat1).unwrap(),
1065            CompositeComponent::new(s2_t, mat2).unwrap(),
1066        ])
1067        .unwrap();
1068        let r_t = comp_t.analyze(&mat1).unwrap();
1069
1070        // Centroid shifts by (dx, dy).
1071        assert!((r_t.centroid.x - (r_orig.centroid.x + dx)).abs() < 1e-10);
1072        assert!((r_t.centroid.y - (r_orig.centroid.y + dy)).abs() < 1e-10);
1073
1074        // Centroidal properties are translation-invariant.
1075        assert!((r_t.ix - r_orig.ix).abs() < 1e-10);
1076        assert!((r_t.iy - r_orig.iy).abs() < 1e-10);
1077        assert!((r_t.ixy - r_orig.ixy).abs() < 1e-10);
1078        assert!((r_t.principal_i11 - r_orig.principal_i11).abs() < 1e-10);
1079        assert!((r_t.principal_i22 - r_orig.principal_i22).abs() < 1e-10);
1080    }
1081
1082    #[test]
1083    fn multi_component_identical_material_degeneration() {
1084        // Multiple components with the same material must produce the same
1085        // result as a single SectionProperties of the combined geometry.
1086        let mat = Material::new(200e9, 0.3, 7850.0, "steel");
1087
1088        // Two disjoint rectangles.
1089        let s1 = rect_section(0.0, 0.0, 0.2, 0.1);
1090        let s2 = rect_section(0.3, 0.0, 0.15, 0.1);
1091
1092        let comp = ElasticComposite::new(vec![
1093            CompositeComponent::new(s1.clone(), mat).unwrap(),
1094            CompositeComponent::new(s2.clone(), mat).unwrap(),
1095        ])
1096        .unwrap();
1097        let r_comp = comp.analyze(&mat).unwrap();
1098
1099        // Build a CompoundGeometry with both rectangles for SectionProperties.
1100        use crate::geometry::{CompoundGeometry, Geometry};
1101        let g1 = Geometry::new(s1.outer, s1.holes);
1102        let g2 = Geometry::new(s2.outer, s2.holes);
1103        let compound = CompoundGeometry::new(vec![g1, g2]);
1104        let r_homogeneous = SectionProperties::from_compound(&compound);
1105
1106        let tol = 1e-10;
1107        assert!((r_comp.area - r_homogeneous.area).abs() < tol);
1108        assert!((r_comp.centroid.x - r_homogeneous.centroid.x).abs() < tol);
1109        assert!((r_comp.centroid.y - r_homogeneous.centroid.y).abs() < tol);
1110        assert!((r_comp.ix - r_homogeneous.ix).abs() < tol);
1111        assert!((r_comp.iy - r_homogeneous.iy).abs() < tol);
1112        assert!((r_comp.ixy - r_homogeneous.ixy).abs() < tol);
1113        assert!((r_comp.principal_i11 - r_homogeneous.principal.i11).abs() < tol);
1114        assert!((r_comp.principal_i22 - r_homogeneous.principal.i22).abs() < tol);
1115    }
1116
1117    #[test]
1118    fn reference_modulus_scaling() {
1119        // E_ref → k·E_ref  ⟹  A' → A'/k, I' → I'/k, EA/EI invariant.
1120        let mat1 = Material::new(30e9, 0.2, 2400.0, "concrete");
1121        let mat2 = Material::new(200e9, 0.3, 7850.0, "steel");
1122
1123        let s1 = rect_section(0.0, 0.0, 0.3, 0.15);
1124        let s2 = rect_section(0.05, 0.15, 0.2, 0.01);
1125
1126        let comp = ElasticComposite::new(vec![
1127            CompositeComponent::new(s1, mat1).unwrap(),
1128            CompositeComponent::new(s2, mat2).unwrap(),
1129        ])
1130        .unwrap();
1131
1132        let r1 = comp.analyze(&mat1).unwrap();
1133
1134        // Scale reference by k.
1135        let k = 1e6;
1136        let mat_scaled = Material::new(mat1.youngs_modulus * k, 0.2, 2400.0, "scaled");
1137        let r2 = comp.analyze(&mat_scaled).unwrap();
1138
1139        // A' → A'/k
1140        assert!((r2.area * k - r1.area).abs() / r1.area < 1e-10);
1141        // I' → I'/k
1142        assert!((r2.ix * k - r1.ix).abs() / r1.ix < 1e-10);
1143        assert!((r2.iy * k - r1.iy).abs() / r1.iy < 1e-10);
1144
1145        // EA and EI are invariant.
1146        let ea1 = mat1.youngs_modulus * r1.area;
1147        let ea2 = mat_scaled.youngs_modulus * r2.area;
1148        assert!((ea1 - ea2).abs() / ea1 < 1e-10);
1149
1150        let ei1 = mat1.youngs_modulus * r1.ix;
1151        let ei2 = mat_scaled.youngs_modulus * r2.ix;
1152        assert!((ei1 - ei2).abs() / ei1 < 1e-10);
1153
1154        // Centroid is reference-invariant.
1155        assert!((r1.centroid.x - r2.centroid.x).abs() < 1e-10);
1156        assert!((r1.centroid.y - r2.centroid.y).abs() < 1e-10);
1157    }
1158
1159    #[test]
1160    fn near_identical_materials_continuity() {
1161        // Two materials with E2 = E1*(1+ε) should produce results close to
1162        // the single-material case.  No catastrophic cancellation.
1163        let e = 200e9;
1164        let mat_base = Material::new(e, 0.3, 7850.0, "base");
1165
1166        let s1 = rect_section(0.0, 0.0, 0.2, 0.1);
1167        let s2 = rect_section(0.0, 0.1, 0.2, 0.1);
1168
1169        // Single material baseline.
1170        let comp_single = ElasticComposite::new(vec![
1171            CompositeComponent::new(s1.clone(), mat_base).unwrap(),
1172            CompositeComponent::new(s2.clone(), mat_base).unwrap(),
1173        ])
1174        .unwrap();
1175        let r_single = comp_single.analyze(&mat_base).unwrap();
1176
1177        // Near-identical: E2 = E1 * (1 + 1e-12).
1178        let eps = 1e-12;
1179        let mat_near = Material::new(e * (1.0 + eps), 0.3, 7850.0, "near");
1180        let comp_near = ElasticComposite::new(vec![
1181            CompositeComponent::new(s1, mat_base).unwrap(),
1182            CompositeComponent::new(s2, mat_near).unwrap(),
1183        ])
1184        .unwrap();
1185        let r_near = comp_near.analyze(&mat_base).unwrap();
1186
1187        // Results should be very close (continuity).
1188        assert!((r_near.area - r_single.area).abs() / r_single.area < 1e-10);
1189        assert!((r_near.ix - r_single.ix).abs() / r_single.ix < 1e-10);
1190        assert!((r_near.centroid.y - r_single.centroid.y).abs() < 1e-10);
1191    }
1192
1193    #[test]
1194    fn p1_01_reproduce_modular_ratio_overflow() {
1195        let sec = rect_section(0.0, 0.0, 0.3, 0.5);
1196        let mat_huge = Material::new(1e308, 0.3, 7850.0, "huge");
1197        let mat_tiny = Material::new(1e-308, 0.3, 7850.0, "tiny");
1198        let comp =
1199            ElasticComposite::new(vec![CompositeComponent::new(sec, mat_huge).unwrap()]).unwrap();
1200        let result = comp.analyze(&mat_tiny);
1201        match result {
1202            Ok(r) => panic!(
1203                "P1-01 NOT fixed: expected Err but got Ok with area={}, ix={}",
1204                r.area, r.ix
1205            ),
1206            Err(e) => println!("P1-01 confirmed: got Err = {:?}", e),
1207        }
1208    }
1209
1210    #[test]
1211    fn p1_01_large_but_finite_modular_ratio() {
1212        let sec = rect_section(0.0, 0.0, 0.3, 0.5);
1213        let mat_huge = Material::new(1e20, 0.3, 7850.0, "huge");
1214        let mat_tiny = Material::new(1e-10, 0.3, 7850.0, "tiny");
1215        let comp =
1216            ElasticComposite::new(vec![CompositeComponent::new(sec, mat_huge).unwrap()]).unwrap();
1217        let result = comp.analyze(&mat_tiny).unwrap();
1218        assert!(result.area.is_finite(), "area should be finite");
1219        assert!(result.ix.is_finite(), "ix should be finite");
1220        assert!(result.principal_i11.is_finite(), "i11 should be finite");
1221        assert!(result.principal_i22.is_finite(), "i22 should be finite");
1222    }
1223
1224    #[test]
1225    fn p0_01_reproduce_principal_axis_overflow() {
1226        let mat = Material::new(1.0, 0.0, 1.0, "unit");
1227        let s1 = rect_section(0.0, 1e100, 0.1, 1e90);
1228        let s2 = rect_section(0.0, -1e100, 0.1, 1e90);
1229        let comp = ElasticComposite::new(vec![
1230            CompositeComponent::new(s1, mat).unwrap(),
1231            CompositeComponent::new(s2, mat).unwrap(),
1232        ])
1233        .unwrap();
1234        let result = comp.analyze(&mat);
1235        match result {
1236            Ok(r) => panic!(
1237                "P0-01 NOT fixed: expected Err but got Ok with i11={}, i22={}",
1238                r.principal_i11, r.principal_i22
1239            ),
1240            Err(CompositeError::NonFiniteDerivedProperty { stage, .. }) => {
1241                println!("P0-01 confirmed: stage = {stage}");
1242                assert!(stage == "principal_axes" || stage == "centroidal_inertia");
1243            }
1244            Err(e) => panic!("P0-01 unexpected error: {e:?}"),
1245        }
1246    }
1247
1248    #[test]
1249    fn p0_01_normal_composite_not_rejected() {
1250        let mat = Material::new(1.0, 0.0, 1.0, "unit");
1251        let s1 = rect_section(0.0, 1e10, 0.1, 0.1);
1252        let s2 = rect_section(0.0, -1e10, 0.1, 0.1);
1253        let comp = ElasticComposite::new(vec![
1254            CompositeComponent::new(s1, mat).unwrap(),
1255            CompositeComponent::new(s2, mat).unwrap(),
1256        ])
1257        .unwrap();
1258        let result = comp.analyze(&mat).unwrap();
1259        assert!(result.area.is_finite());
1260        assert!(result.ix.is_finite());
1261        assert!(result.iy.is_finite());
1262        assert!(result.ixy.is_finite());
1263        assert!(result.principal_i11.is_finite());
1264        assert!(result.principal_i22.is_finite());
1265        assert!(result.principal_phi.is_finite());
1266        assert!(result.centroid.x.is_finite());
1267        assert!(result.centroid.y.is_finite());
1268    }
1269
1270    #[test]
1271    fn p0_02_all_finite_results_invariant() {
1272        let mat1 = Material::new(30e9, 0.2, 2400.0, "concrete");
1273        let mat2 = Material::new(200e9, 0.3, 7850.0, "steel");
1274        let s1 = rect_section(0.0, 0.0, 0.3, 0.5);
1275        let s2 = rect_section(0.1, 0.1, 0.05, 0.3);
1276        let comp = ElasticComposite::new(vec![
1277            CompositeComponent::new(s1, mat1).unwrap(),
1278            CompositeComponent::new(s2, mat2).unwrap(),
1279        ])
1280        .unwrap();
1281        let r = comp.analyze(&mat1).unwrap();
1282        assert!(r.area.is_finite());
1283        assert!(r.centroid.x.is_finite());
1284        assert!(r.centroid.y.is_finite());
1285        assert!(r.ix.is_finite());
1286        assert!(r.iy.is_finite());
1287        assert!(r.ixy.is_finite());
1288        assert!(r.principal_i11.is_finite());
1289        assert!(r.principal_i22.is_finite());
1290        assert!(r.principal_phi.is_finite());
1291    }
1292
1293    #[test]
1294    fn p2_01_case_a_modular_ratio_overflow_variant() {
1295        let sec = rect_section(0.0, 0.0, 0.3, 0.5);
1296        let mat_huge = Material::new(1e308, 0.3, 7850.0, "huge");
1297        let mat_tiny = Material::new(1e-308, 0.3, 7850.0, "tiny");
1298        let comp =
1299            ElasticComposite::new(vec![CompositeComponent::new(sec, mat_huge).unwrap()]).unwrap();
1300        let result = comp.analyze(&mat_tiny);
1301        assert!(
1302            matches!(result, Err(CompositeError::NonFiniteModularRatio { .. })),
1303            "Case A: expected NonFiniteModularRatio, got {:?}",
1304            result
1305        );
1306    }
1307
1308    #[test]
1309    fn p2_01_case_b_accumulation_overflow_variant() {
1310        let mat = Material::new(1.0, 0.0, 1.0, "unit");
1311        let s = rect_section(0.0, 1e200, 1e-10, 1e190);
1312        let comp = ElasticComposite::new(vec![CompositeComponent::new(s, mat).unwrap()]).unwrap();
1313        let result = comp.analyze(&mat);
1314        assert!(
1315            matches!(
1316                result,
1317                Err(CompositeError::NonFiniteDerivedProperty {
1318                    stage: "weighted_accumulation",
1319                    ..
1320                })
1321            ),
1322            "Case B: expected NonFiniteDerivedProperty {{ stage: \"weighted_accumulation\" }}, got {:?}",
1323            result
1324        );
1325    }
1326
1327    #[test]
1328    fn p2_01_case_c_finite_input_ok() {
1329        let mat1 = Material::new(30e9, 0.2, 2400.0, "concrete");
1330        let mat2 = Material::new(200e9, 0.3, 7850.0, "steel");
1331        let s1 = rect_section(0.0, 0.0, 0.3, 0.5);
1332        let s2 = rect_section(0.1, 0.1, 0.05, 0.3);
1333        let comp = ElasticComposite::new(vec![
1334            CompositeComponent::new(s1, mat1).unwrap(),
1335            CompositeComponent::new(s2, mat2).unwrap(),
1336        ])
1337        .unwrap();
1338        let result = comp.analyze(&mat1);
1339        assert!(
1340            matches!(result, Ok(_)),
1341            "Case C: expected Ok for finite inputs, got {:?}",
1342            result
1343        );
1344    }
1345
1346    /// Analytical centroidal Ix for a rectangle: b*h^3/12
1347    fn rect_ix_local(b: f64, h: f64) -> f64 {
1348        b * h * h * h / 12.0
1349    }
1350
1351    /// Analytical centroidal Iy for a rectangle: h*b^3/12
1352    fn rect_iy_local(b: f64, h: f64) -> f64 {
1353        h * b * b * b / 12.0
1354    }
1355
1356    #[test]
1357    fn composite_centroidal_inertia_stable_at_large_translation() {
1358        let b = 0.1_f64;
1359        let h = 0.1_f64;
1360        let ix_true = rect_ix_local(b, h);
1361        let iy_true = rect_iy_local(b, h);
1362        let mat = Material::new(1.0, 0.0, 1.0, "unit");
1363
1364        let scales: [f64; 7] = [1e0, 1e2, 1e4, 1e6, 1e8, 1e10, 1e12];
1365
1366        for &y in &scales {
1367            let sec = rect_section(0.0, y, b, h);
1368            let comp =
1369                ElasticComposite::new(vec![CompositeComponent::new(sec, mat).unwrap()]).unwrap();
1370            let r = comp.analyze(&mat).unwrap();
1371
1372            let ix_relerr = (r.ix - ix_true).abs() / ix_true;
1373            let iy_relerr = (r.iy - iy_true).abs() / iy_true;
1374
1375            assert!(
1376                r.ix.is_finite() && r.ix > 0.0,
1377                "Y={:.0e}: Ix={} should be finite and positive",
1378                y,
1379                r.ix
1380            );
1381            assert!(
1382                r.iy.is_finite() && r.iy > 0.0,
1383                "Y={:.0e}: Iy={} should be finite and positive",
1384                y,
1385                r.iy
1386            );
1387
1388            let tol = if y <= 1e8 { 1e-3 } else { 1e-1 };
1389            assert!(
1390                ix_relerr < tol,
1391                "Y={:.0e}: Ix relative error {:.2e} should be < {:.0e}",
1392                y,
1393                ix_relerr,
1394                tol
1395            );
1396            assert!(
1397                iy_relerr < tol,
1398                "Y={:.0e}: Iy relative error {:.2e} should be < {:.0e}",
1399                y,
1400                iy_relerr,
1401                tol
1402            );
1403        }
1404    }
1405
1406    #[test]
1407    fn composite_translation_invariance_at_large_scales() {
1408        let b = 0.1_f64;
1409        let h = 0.1_f64;
1410        let mat = Material::new(1.0, 0.0, 1.0, "unit");
1411
1412        let s1_base = rect_section(0.0, 0.0, b, h);
1413        let s2_base = rect_section(0.05, 0.05, b, h);
1414        let comp_base = ElasticComposite::new(vec![
1415            CompositeComponent::new(s1_base, mat).unwrap(),
1416            CompositeComponent::new(s2_base, mat).unwrap(),
1417        ])
1418        .unwrap();
1419        let r_base = comp_base.analyze(&mat).unwrap();
1420
1421        for &dy in &[1e4, 1e6, 1e8] {
1422            let s1 = rect_section(0.0, dy, b, h);
1423            let s2 = rect_section(0.05, dy + 0.05, b, h);
1424            let comp = ElasticComposite::new(vec![
1425                CompositeComponent::new(s1, mat).unwrap(),
1426                CompositeComponent::new(s2, mat).unwrap(),
1427            ])
1428            .unwrap();
1429            let r = comp.analyze(&mat).unwrap();
1430
1431            let ix_relerr = (r.ix - r_base.ix).abs() / r_base.ix;
1432            let iy_relerr = (r.iy - r_base.iy).abs() / r_base.iy;
1433
1434            let tol = if dy <= 1e6 { 1e-6 } else { 1e-3 };
1435            assert!(
1436                ix_relerr < tol,
1437                "dy={:.0e}: Ix relative error {:.2e} should be < {:.0e}",
1438                dy,
1439                ix_relerr,
1440                tol
1441            );
1442            assert!(
1443                iy_relerr < tol,
1444                "dy={:.0e}: Iy relative error {:.2e} should be < {:.0e}",
1445                dy,
1446                iy_relerr,
1447                tol
1448            );
1449        }
1450    }
1451
1452    #[test]
1453    fn composite_symmetric_pair_at_large_scales() {
1454        let b = 0.1_f64;
1455        let h = 0.1_f64;
1456        let area = b * h;
1457        let ix_local = rect_ix_local(b, h);
1458        let mat = Material::new(1.0, 0.0, 1.0, "unit");
1459
1460        for &y in &[1e4, 1e8, 1e12] {
1461            let s1 = rect_section(0.0, y, b, h);
1462            let s2 = rect_section(0.0, -y - h, b, h);
1463            let comp = ElasticComposite::new(vec![
1464                CompositeComponent::new(s1, mat).unwrap(),
1465                CompositeComponent::new(s2, mat).unwrap(),
1466            ])
1467            .unwrap();
1468            let r = comp.analyze(&mat).unwrap();
1469
1470            assert!(
1471                r.centroid.y.abs() < 1e-6,
1472                "Y={:.0e}: centroid.y={} should be ~0",
1473                y,
1474                r.centroid.y
1475            );
1476            assert!(
1477                r.ix > 0.0 && r.iy > 0.0,
1478                "Y={:.0e}: Ix={} and Iy={} should be positive",
1479                y,
1480                r.ix,
1481                r.iy
1482            );
1483
1484            let d = y + h / 2.0;
1485            let ix_ref = 2.0 * (ix_local + area * d * d);
1486            let ix_relerr = (r.ix - ix_ref).abs() / ix_ref;
1487            let tol = if y <= 1e8 { 1e-6 } else { 1e-3 };
1488            assert!(
1489                ix_relerr < tol,
1490                "Y={:.0e}: Ix relative error {:.2e} should be < {:.0e}",
1491                y,
1492                ix_relerr,
1493                tol
1494            );
1495        }
1496    }
1497
1498    #[test]
1499    fn composite_independent_reference_comparison() {
1500        let b = 0.1_f64;
1501        let h = 0.1_f64;
1502        let area = b * h;
1503        let ix_local = rect_ix_local(b, h);
1504        let iy_local = rect_iy_local(b, h);
1505        let mat = Material::new(1.0, 0.0, 1.0, "unit");
1506
1507        for &y in &[1e0, 1e4, 1e8, 1e12] {
1508            let sec = rect_section(0.0, y, b, h);
1509            let comp =
1510                ElasticComposite::new(vec![CompositeComponent::new(sec, mat).unwrap()]).unwrap();
1511            let r = comp.analyze(&mat).unwrap();
1512
1513            let total_area_ref = area;
1514
1515            let area_tol = if y <= 1e6 {
1516                1e-10
1517            } else if y <= 1e10 {
1518                1e-6
1519            } else {
1520                1e-3
1521            };
1522            assert!(
1523                (total_area_ref - r.area).abs() / total_area_ref < area_tol,
1524                "Y={:.0e}: area mismatch: r.area={:.6e} vs ref={:.6e}",
1525                y,
1526                r.area,
1527                total_area_ref
1528            );
1529
1530            let ix_relerr = (r.ix - ix_local).abs() / ix_local;
1531            let iy_relerr = (r.iy - iy_local).abs() / iy_local;
1532            let tol = if y <= 1e8 { 1e-3 } else { 1e-1 };
1533            assert!(
1534                ix_relerr < tol,
1535                "Y={:.0e}: Ix relerr {:.2e} vs analytical {:.6e}",
1536                y,
1537                ix_relerr,
1538                ix_local
1539            );
1540            assert!(
1541                iy_relerr < tol,
1542                "Y={:.0e}: Iy relerr {:.2e} vs analytical {:.6e}",
1543                y,
1544                iy_relerr,
1545                iy_local
1546            );
1547        }
1548    }
1549}