Skip to main content

section_properties/plastic/
warping.rs

1//! Warping torsion analysis.
2//!
3//! Provides St. Venant torsion constant (J), warping constant (Iw),
4//! shear center coordinates, and torsional-warping section properties.
5
6use super::warping_fem::{compute_fem_solution, compute_fem_warping_properties};
7use crate::geometry::Point;
8use crate::section::Section;
9use crate::section_properties::SectionProperties;
10
11/// Warping torsion properties for open and closed sections.
12#[derive(Debug, Clone)]
13pub struct WarpingProperties {
14    /// St. Venant torsion constant [m^4]
15    pub j: f64,
16    /// Warping constant [m^6]
17    pub iw: f64,
18    /// Shear center coordinates relative to centroid `m`
19    pub shear_center: Point,
20    /// Torsional radius of gyration `m`
21    pub r_t: f64,
22    /// Warping radius of gyration `m`
23    pub r_w: f64,
24    /// Section area [m^2]
25    pub area: f64,
26    /// Polar moment of inertia about centroid [m^4]
27    pub ip: f64,
28    /// Monosymmetry constant about x-axis `m`
29    pub beta_x: f64,
30    /// Monosymmetry constant about y-axis `m`
31    pub beta_y: f64,
32    /// Shear area in y-direction (for Vx shear) [m^2]
33    pub ay: f64,
34    /// Shear area in z-direction (for Vy shear) [m^2]
35    pub az: f64,
36    /// Shear center 11-coordinate (principal axis) `m`
37    pub shear_center_11: f64,
38    /// Shear center 22-coordinate (principal axis) `m`
39    pub shear_center_22: f64,
40    /// Monosymmetry constant about 11 (major principal) axis `m`
41    pub beta_11: f64,
42    /// Monosymmetry constant about 22 (minor principal) axis `m`
43    pub beta_22: f64,
44    /// Shear area about 11 (major principal) axis [m^2]
45    pub a_s11: f64,
46    /// Shear area about 22 (minor principal) axis [m^2]
47    pub a_s22: f64,
48    /// Shear area about the xy-axis (cross-coupling) [m^2]
49    ///
50    /// Zero for sections with at least one axis of symmetry. Requires finite-element
51    /// analysis for general sections; approximated as zero here.
52    pub a_sxy: f64,
53    /// Shear deformation parameter delta_s = 2*(1+nu)*(Ix*Iy - Ixy^2)
54    pub delta_s: f64,
55    /// Principal axis angle `rad`
56    pub principal_angle: f64,
57    /// Trefftz shear center coordinates relative to centroid `m`
58    ///
59    /// For open thin-walled sections, the Trefftz approach yields the same shear
60    /// center as the elasticity approach. For closed/solid sections the Trefftz
61    /// shear center requires a finite-element solution of the Laplace equation;
62    /// in that case we fall back to the elasticity-based shear center as an
63    /// approximation.
64    pub shear_center_trefftz: Point,
65    /// Monosymmetry constant for positive bending about x-axis `m`
66    pub beta_x_plus: f64,
67    /// Monosymmetry constant for negative bending about x-axis `m`
68    pub beta_x_minus: f64,
69    /// Monosymmetry constant for positive bending about y-axis `m`
70    pub beta_y_plus: f64,
71    /// Monosymmetry constant for negative bending about y-axis `m`
72    pub beta_y_minus: f64,
73    /// Monosymmetry constant for positive bending about 11-axis `m`
74    pub beta_11_plus: f64,
75    /// Monosymmetry constant for negative bending about 11-axis `m`
76    pub beta_11_minus: f64,
77    /// Monosymmetry constant for positive bending about 22-axis `m`
78    pub beta_22_plus: f64,
79    /// Monosymmetry constant for negative bending about 22-axis `m`
80    pub beta_22_minus: f64,
81    /// Maximum warping coordinate |ω| from FEM solution
82    pub omega_max: f64,
83    /// Maximum St. Venant shear stress (unit torque) from FEM solution
84    pub tau_sv_max_unit: f64,
85}
86
87impl WarpingProperties {
88    /// Compute warping properties for a section using FEM.
89    ///
90    /// Mirrors Python `sectionproperties.analysis.section.Section.calculate_warping_properties`:
91    /// Uses FEM as the core method to compute J, Iw, shear center, shear areas,
92    /// and monosymmetry constants about both centroidal (x/y) and principal (11/22) axes.
93    ///
94    /// Analytical formulas are available for validation/testing but are NOT used as fallbacks.
95    ///
96    /// `nu` is the Poisson's ratio of the material (e.g., 0.3 for steel).
97    ///
98    /// # Panics
99    ///
100    /// Panics if the underlying FEM analysis fails (e.g., invalid section geometry
101    /// or mesh generation failure). For a fallible version, use [`try_from_section`].
102    ///
103    /// [`try_from_section`]: WarpingProperties::try_from_section
104    pub fn from_section(section: &Section, nu: f64) -> Self {
105        Self::try_from_section(section, nu).expect(
106            "FEM warping analysis failed. This should not happen for valid sections. \
107             Check mesh generation and section validity.",
108        )
109    }
110
111    /// Fallible version of [`from_section`] that propagates FEM errors instead of panicking.
112    ///
113    /// Returns `Err` if mesh generation or the FEM solve fails for the given section.
114    ///
115    /// [`from_section`]: WarpingProperties::from_section
116    pub fn try_from_section(
117        section: &Section,
118        nu: f64,
119    ) -> Result<Self, crate::mesh::fem::FemError> {
120        let props = SectionProperties::from_section(section);
121        let area = props.area;
122
123        // Use FEM as the primary method for ALL sections
124        // This matches Python sectionproperties which uses FEM as the core method
125        let fem = compute_fem_warping_properties(section, &props, nu)?;
126
127        // Also compute the full FEM solution to get tau_sv_max for unit torque
128        let fem_solution = compute_fem_solution(section, &props, nu)?;
129
130        // FEM solves in centroidal coordinates; report in global axes
131        // (Python convention: shear centre in section coordinates).
132        let shear_center = Point::new(
133            fem.shear_center.x + props.centroid.x,
134            fem.shear_center.y + props.centroid.y,
135        );
136        let shear_center_trefftz = shear_center;
137        let beta_x = fem.beta_x_plus;
138        let beta_y = fem.beta_y_plus;
139        let iw = fem.iw;
140        let j = fem.j;
141
142        // FEM shear areas directly (Python sectionproperties uses the FEM
143        // values without an analytical fallback guess).
144        let (ay, az) = (fem.a_sx, fem.a_sy);
145
146        let ip = props.ix + props.iy;
147        let r_t = (j / area).sqrt();
148        let r_w = if iw > 0.0 { (iw / area).sqrt() } else { 0.0 };
149
150        let principal = props.principal_properties();
151        let phi = principal.phi;
152
153        let (sc_11, sc_22) = if phi.abs() < 1e-10 {
154            (shear_center.x, shear_center.y)
155        } else {
156            let cos_phi = phi.cos();
157            let sin_phi = phi.sin();
158            (
159                shear_center.x * cos_phi + shear_center.y * sin_phi,
160                -shear_center.x * sin_phi + shear_center.y * cos_phi,
161            )
162        };
163
164        // Principal axis shear areas from tensor rotation (Python method)
165        // Use the FEM-computed rotated values directly if available, otherwise rotate
166        let (a_s11, a_s22) = if phi.abs() < 1e-10 {
167            (ay, az)
168        } else if fem.a_s11 > 0.0 && fem.a_s22 > 0.0 {
169            (fem.a_s11, fem.a_s22)
170        } else {
171            // Tensor rotation of shear area tensor (no additional FEM run needed)
172            let cos_phi = phi.cos();
173            let sin_phi = phi.sin();
174            let alpha_xx = area / ay;
175            let alpha_yy = area / az;
176            let alpha_xy = 0.0; // Cross-coupling in centroidal axes
177
178            let rot_00 = cos_phi * (cos_phi * alpha_xx + sin_phi * alpha_xy)
179                + sin_phi * (cos_phi * alpha_xy + sin_phi * alpha_yy);
180            let rot_11 = (-sin_phi) * (-sin_phi * alpha_xx + cos_phi * alpha_xy)
181                + cos_phi * (-sin_phi * alpha_xy + cos_phi * alpha_yy);
182
183            let a_s11 = if rot_00.abs() > 1e-15 {
184                area / rot_00
185            } else {
186                ay
187            };
188            let a_s22 = if rot_11.abs() > 1e-15 {
189                area / rot_11
190            } else {
191                az
192            };
193            (a_s11, a_s22)
194        };
195
196        // Principal-axis monosymmetry constants via direct integration in
197        // rotated coordinates (Python formula) computed by the FEM analysis,
198        // not by rotating the centroidal beta values.
199        let beta_11 = fem.beta_11_plus;
200        let beta_22 = fem.beta_22_plus;
201        let beta_11_plus = fem.beta_11_plus;
202        let beta_11_minus = fem.beta_11_minus;
203        let beta_22_plus = fem.beta_22_plus;
204        let beta_22_minus = fem.beta_22_minus;
205
206        let delta_s = 2.0 * (1.0 + nu) * (props.ix * props.iy - props.ixy * props.ixy);
207
208        // Use FEM-computed centroidal monosymmetry constants. AS4100 /
209        // Python sectionproperties convention: beta_x_minus = -beta_x_plus.
210        let beta_x_plus = fem.beta_x_plus;
211        let beta_x_minus = fem.beta_x_minus;
212        let beta_y_plus = fem.beta_y_plus;
213        let beta_y_minus = fem.beta_y_minus;
214
215        // Max St. Venant shear stress for unit torque from FEM
216        let tau_sv_max_unit = fem_solution.tau_sv_max;
217
218        Ok(Self {
219            j,
220            iw,
221            shear_center,
222            r_t,
223            r_w,
224            area,
225            ip,
226            beta_x,
227            beta_y,
228            ay,
229            az,
230            shear_center_11: sc_11,
231            shear_center_22: sc_22,
232            beta_11,
233            beta_22,
234            a_s11,
235            a_s22,
236            a_sxy: fem.a_sxy,
237            delta_s,
238            principal_angle: phi,
239            shear_center_trefftz,
240            beta_x_plus,
241            beta_x_minus,
242            beta_y_plus,
243            beta_y_minus,
244            beta_11_plus,
245            beta_11_minus,
246            beta_22_plus,
247            beta_22_minus,
248            omega_max: fem.omega_max,
249            tau_sv_max_unit,
250        })
251    }
252
253    /// Torsional stiffness (GJ).
254    pub fn torsional_stiffness(&self, shear_modulus: f64) -> f64 {
255        shear_modulus * self.j
256    }
257
258    /// Warping stiffness (E*Iw).
259    pub fn warping_stiffness(&self, youngs_modulus: f64) -> f64 {
260        youngs_modulus * self.iw
261    }
262
263    /// Characteristic length for warping (sqrt(E*Iw/G*J)).
264    pub fn warping_length(&self, youngs_modulus: f64, shear_modulus: f64) -> f64 {
265        if self.j > 0.0 && self.iw > 0.0 {
266            (youngs_modulus * self.iw / (shear_modulus * self.j)).sqrt()
267        } else {
268            0.0
269        }
270    }
271}
272
273/// Check if a section is thin-walled (open profile heuristic).
274///
275/// A section is considered thin-walled when its material area is a small
276/// fraction of its bounding box (< 15% solid).
277pub trait ThinWalledCheck {
278    fn is_thin_walled(&self) -> bool;
279}
280
281impl ThinWalledCheck for Section {
282    fn is_thin_walled(&self) -> bool {
283        // Heuristic: check if area is much smaller than bounding box
284        let props = SectionProperties::from_section(self);
285        let bounds = self.bounds();
286        let bbox_area = (bounds.1 - bounds.0) * (bounds.3 - bounds.2);
287        // 20% threshold captures I, Channel, and Angle sections
288        props.area / bbox_area < 0.20
289    }
290}
291
292/// Torsional constant beta for rectangle (h/b ratio).
293pub fn torsional_constant_beta(ratio: f64) -> f64 {
294    // From Roark's formulas
295    match ratio {
296        r if r >= 10.0 => 1.0 / 3.0,
297        r if r >= 5.0 => 0.291,
298        r if r >= 3.0 => 0.263,
299        r if r >= 2.0 => 0.229,
300        r if r >= 1.5 => 0.196,
301        r if r >= 1.25 => 0.166,
302        r if r >= 1.0 => 0.141,
303        _ => torsional_constant_beta(1.0 / ratio), // Symmetric
304    }
305}
306
307/// Torsion analysis results.
308#[derive(Debug, Clone)]
309pub struct TorsionAnalysis {
310    pub properties: WarpingProperties,
311    /// St. Venant shear stress from torque T
312    pub tau_sv_max: f64,
313    /// Warping normal stress from bimoment B
314    pub sigma_w_max: f64,
315    /// Total angle of twist per unit length
316    pub theta_prime: f64,
317    /// Warping displacement
318    pub warping_displacement: f64,
319}
320
321impl TorsionAnalysis {
322    /// Analyze section under pure torsion.
323    pub fn pure_torsion(
324        section: &Section,
325        torque: f64,
326        material: &crate::material::Material,
327    ) -> Self {
328        let nu = material.poissons_ratio;
329        let props = WarpingProperties::from_section(section, nu);
330
331        // St. Venant shear stress from FEM solution (not farthest-point formula)
332        // τ_sv_max = torque * tau_sv_max_unit where tau_sv_max_unit is max shear stress for unit torque
333        let tau_sv_max = torque * props.tau_sv_max_unit.max(1e-12);
334
335        // Angle of twist per unit length: θ' = T / (G*J)
336        let theta_prime = torque / (material.shear_modulus * props.j.max(1e-12));
337
338        Self {
339            properties: props,
340            tau_sv_max,
341            sigma_w_max: 0.0, // No warping in pure St. Venant torsion
342            theta_prime,
343            warping_displacement: 0.0,
344        }
345    }
346
347    /// Analyze section under torsion + warping (constrained torsion).
348    pub fn constrained_torsion(
349        section: &Section,
350        torque: f64,
351        bimoment: f64, // Bimoment (warping moment)
352        material: &crate::material::Material,
353    ) -> Self {
354        let nu = material.poissons_ratio;
355        let props = WarpingProperties::from_section(section, nu);
356
357        // St. Venant component from FEM
358        let tau_sv_max = torque * props.tau_sv_max_unit.max(1e-12);
359
360        // Warping component
361        // σ_w = B * ω_max / Iw where ω_max is the maximum warping coordinate from FEM
362        let omega_max = props.omega_max;
363
364        let sigma_w_max = if props.iw > 0.0 {
365            bimoment * omega_max / props.iw
366        } else {
367            0.0
368        };
369
370        // Total twist
371        let theta_prime = torque / (material.shear_modulus * props.j.max(1e-12));
372
373        // Warping displacement (simplified)
374        let warping_displacement = if props.iw > 0.0 {
375            bimoment / (material.youngs_modulus * props.iw)
376        } else {
377            0.0
378        };
379
380        Self {
381            properties: props,
382            tau_sv_max,
383            sigma_w_max,
384            theta_prime,
385            warping_displacement,
386        }
387    }
388}
389
390/// Exact warping analysis using sectorial coordinates.
391pub mod trefftz {
392    use super::*;
393    use crate::geometry::Point;
394    use crate::mesh::{Mesh, MeshParams, mesh_section};
395
396    /// Sectorial coordinate (warping function) computation using Trefftz method.
397    ///
398    /// NOTE: this is a legacy, approximate sectorial-coordinate solver kept for
399    /// reference. The boundary integral in `apply_sectorial_bc` is a pointwise
400    /// approximation (not a proper edge integration) and `compute_sectorial_properties`
401    /// averages `omega` over elements, so results are only qualitatively useful.
402    /// Prefer the FEM warping path in `warping_fem`.
403    pub fn compute_sectorial_coordinates(section: &Section) -> SectorialProperties {
404        // Use FEM to solve for the sectorial coordinate (warping function)
405        // ∇²�?= 0 with boundary condition: ∂�?∂n = y*n_x - x*n_y on boundary
406        // This is the exact Trefftz method for shear center and warping analysis.
407
408        let mesh = mesh_section(
409            section,
410            MeshParams {
411                target_size: 0.005,
412                max_size: 0.01,
413                min_size: 0.001,
414                quality_threshold: 0.3,
415                use_delaunay: true,
416                max_iterations: 10,
417                max_nodes: 20000,
418            },
419        );
420
421        let n_nodes = mesh.n_nodes();
422        let n_dof = n_nodes; // 1 DOF per node (ω)
423
424        // Build DOF map
425        let mut dof_map = std::collections::HashMap::new();
426        for node in 0..n_nodes {
427            dof_map.insert(node, node);
428        }
429
430        // Build global stiffness matrix for Laplace equation ∇²�?= 0
431        // ke = �?B^T * B dA where B = [∂N/∂x, ∂N/∂y]
432        let mut k_global = SprsMatrix::new(n_dof);
433
434        for element in &mesh.elements {
435            let ke = sectorial_stiffness_tri3(&mesh, element);
436
437            let mut dof_indices = [0; 3];
438            for (i, &node) in element.iter().enumerate() {
439                dof_indices[i] = dof_map[&node];
440            }
441
442            for i in 0..3 {
443                for j in 0..3 {
444                    k_global.add(dof_indices[i], dof_indices[j], ke[i][j]);
445                }
446            }
447        }
448
449        // Build force vector from boundary condition
450        // ∂�?∂n = y*n_x - x*n_y on boundary
451        let mut f_global = vec![0.0; n_dof];
452
453        // Apply boundary condition: ∂�?∂n = y*n_x - x*n_y
454        // This is applied via Neumann BC in FEM
455        apply_sectorial_bc(&mesh, &mut f_global);
456
457        // Fix one point to remove rigid body mode (ω = 0 at shear center)
458        // We need to find shear center first - use iterative approach
459        // For now, fix ω = 0 at centroid as reference
460        let centroid = SectionProperties::from_section(section).centroid;
461        let mut ref_node = 0;
462        let mut min_dist = f64::INFINITY;
463        for node in 0..n_nodes {
464            let p = mesh.nodes[node];
465            let dist = (p.x - centroid.x).hypot(p.y - centroid.y);
466            if dist < min_dist {
467                min_dist = dist;
468                ref_node = node;
469            }
470        }
471
472        // Apply Dirichlet BC: ω = 0 at reference node
473        let ref_dof = dof_map[&ref_node];
474        k_global.zero_row_col(ref_dof);
475        k_global.set(ref_dof, ref_dof, 1.0);
476        f_global[ref_dof] = 0.0;
477
478        // Solve
479        k_global.finalize();
480        let omega = k_global
481            .solve_cholesky(&f_global)
482            .unwrap_or(vec![0.0; n_dof]);
483
484        // Compute sectorial static moments and shear center
485        let (_shear_center, iw, q_omega_x, q_omega_y) =
486            compute_sectorial_properties(&mesh, &omega, &dof_map);
487
488        // Shear center relative to centroid:
489        // x_sc = -Q_ωy / I_x, y_sc = Q_ωx / I_x
490        let props = SectionProperties::from_section(section);
491        let shear_center = Point::new(
492            -q_omega_y / props.ix.max(1e-12),
493            q_omega_x / props.ix.max(1e-12),
494        );
495
496        SectorialProperties {
497            shear_center,
498            omega_coords: omega,
499            iw,
500        }
501    }
502
503    /// Sectorial stiffness matrix for Tri3 element (3x3).
504    fn sectorial_stiffness_tri3(mesh: &Mesh, element: &[usize; 3]) -> [[f64; 3]; 3] {
505        let p1 = mesh.nodes[element[0]];
506        let p2 = mesh.nodes[element[1]];
507        let p3 = mesh.nodes[element[2]];
508
509        let area2 = (p2.x - p1.x) * (p3.y - p1.y) - (p3.x - p1.x) * (p2.y - p1.y);
510        let area = 0.5 * area2.abs();
511
512        // Shape function derivatives
513        let b1 = (p2.y - p3.y) / area2;
514        let c1 = (p3.x - p2.x) / area2;
515        let b2 = (p3.y - p1.y) / area2;
516        let c2 = (p1.x - p3.x) / area2;
517        let b3 = (p1.y - p2.y) / area2;
518        let c3 = (p2.x - p1.x) / area2;
519
520        let mut ke = [[0.0; 3]; 3];
521        for i in 0..3 {
522            for j in 0..3 {
523                let bi = [b1, b2, b3][i];
524                let ci = [c1, c2, c3][i];
525                let bj = [b1, b2, b3][j];
526                let cj = [c1, c2, c3][j];
527                ke[i][j] = (bi * bj + ci * cj) * area;
528            }
529        }
530        ke
531    }
532
533    /// Apply Neumann BC for sectorial coordinate: ∂�?∂n = y*n_x - x*n_y on boundary.
534    fn apply_sectorial_bc(mesh: &Mesh, f_global: &mut [f64]) {
535        // For each boundary edge, compute integral of (y*n_x - x*n_y) * N dS
536        // This is the Neumann BC for the warping function
537        for &node in &mesh.boundary_nodes {
538            let p = mesh.nodes[node];
539            // Approximate contribution from boundary integral
540            // In a full implementation, this would integrate over boundary edges
541            // For now, use pointwise approximation
542            f_global[node] = p.y * 1.0 - p.x * 0.0; // Simplified
543        }
544    }
545
546    /// Compute sectorial properties from FEM solution.
547    fn compute_sectorial_properties(
548        mesh: &Mesh,
549        omega: &[f64],
550        dof_map: &std::collections::HashMap<usize, usize>,
551    ) -> (Point, f64, f64, f64) {
552        // Q_ωx = �?ω * y dA, Q_ωy = �?ω * x dA
553        let mut q_omega_x = 0.0;
554        let mut q_omega_y = 0.0;
555        let mut iw = 0.0;
556
557        for element in &mesh.elements {
558            let p1 = mesh.nodes[element[0]];
559            let p2 = mesh.nodes[element[1]];
560            let p3 = mesh.nodes[element[2]];
561
562            let area = 0.5 * ((p2.x - p1.x) * (p3.y - p1.y) - (p3.x - p1.x) * (p2.y - p1.y)).abs();
563            let centroid = Point::new((p1.x + p2.x + p3.x) / 3.0, (p1.y + p2.y + p3.y) / 3.0);
564
565            // Average omega over element
566            let omega_elem = (omega[dof_map[&element[0]]]
567                + omega[dof_map[&element[1]]]
568                + omega[dof_map[&element[2]]])
569                / 3.0;
570
571            q_omega_x += omega_elem * centroid.y * area;
572            q_omega_y += omega_elem * centroid.x * area;
573            iw += omega_elem * omega_elem * area;
574        }
575
576        (Point::new(0.0, 0.0), iw, q_omega_x, q_omega_y)
577    }
578
579    #[derive(Debug, Clone)]
580    pub struct SectorialProperties {
581        pub shear_center: Point,
582        pub omega_coords: Vec<f64>,
583        pub iw: f64,
584    }
585
586    // Sparse matrix for sectorial analysis
587    #[derive(Debug, Clone)]
588    pub struct SprsMatrix {
589        n: usize,
590        row_ptr: Vec<usize>,
591        col_idx: Vec<usize>,
592        values: Vec<f64>,
593        triplets: Vec<(usize, usize, f64)>,
594        finalized: bool,
595    }
596
597    impl SprsMatrix {
598        pub fn new(n: usize) -> Self {
599            Self {
600                n,
601                row_ptr: vec![0; n + 1],
602                col_idx: Vec::new(),
603                values: Vec::new(),
604                triplets: Vec::new(),
605                finalized: false,
606            }
607        }
608
609        pub fn add(&mut self, row: usize, col: usize, value: f64) {
610            if value.abs() < 1e-15 {
611                return;
612            }
613            self.triplets.push((row, col, value));
614            self.finalized = false;
615        }
616
617        pub fn set(&mut self, row: usize, col: usize, value: f64) {
618            self.finalize();
619            for i in self.row_ptr[row]..self.row_ptr[row + 1] {
620                if self.col_idx[i] == col {
621                    self.values[i] = value;
622                    return;
623                }
624            }
625            let pos = self.row_ptr[row + 1];
626            self.col_idx.insert(pos, col);
627            self.values.insert(pos, value);
628            for r in (row + 1)..=self.n {
629                self.row_ptr[r] += 1;
630            }
631        }
632
633        fn finalize(&mut self) {
634            if self.finalized {
635                return;
636            }
637            self.triplets.sort_by_key(|&(r, c, _)| (r, c));
638
639            let mut combined: Vec<(usize, usize, f64)> = Vec::new();
640            for (r, c, v) in self.triplets.drain(..) {
641                if let Some(last) = combined.last_mut() {
642                    if last.0 == r && last.1 == c {
643                        last.2 += v;
644                    } else {
645                        combined.push((r, c, v));
646                    }
647                } else {
648                    combined.push((r, c, v));
649                }
650            }
651
652            self.row_ptr.fill(0);
653            for (r, _, _) in &combined {
654                self.row_ptr[r + 1] += 1;
655            }
656            for i in 1..=self.n {
657                self.row_ptr[i] += self.row_ptr[i - 1];
658            }
659
660            self.col_idx = Vec::with_capacity(combined.len());
661            self.values = Vec::with_capacity(combined.len());
662            for (_, c, v) in combined {
663                self.col_idx.push(c);
664                self.values.push(v);
665            }
666
667            self.finalized = true;
668        }
669
670        pub fn zero_row_col(&mut self, idx: usize) {
671            self.finalize();
672            let row_start = self.row_ptr[idx];
673            let row_end = self.row_ptr[idx + 1];
674            for i in row_start..row_end {
675                self.values[i] = 0.0;
676            }
677            for r in 0..self.n {
678                let rs = self.row_ptr[r];
679                let re = self.row_ptr[r + 1];
680                for i in rs..re {
681                    if self.col_idx[i] == idx {
682                        self.values[i] = 0.0;
683                    }
684                }
685            }
686        }
687
688        pub fn solve_cholesky(&mut self, rhs: &[f64]) -> Option<Vec<f64>> {
689            self.finalize();
690
691            if self.n <= 500 {
692                let mut a = vec![vec![0.0; self.n]; self.n];
693                for i in 0..self.n {
694                    for j_idx in self.row_ptr[i]..self.row_ptr[i + 1] {
695                        let j = self.col_idx[j_idx];
696                        a[i][j] = self.values[j_idx];
697                    }
698                }
699
700                let mut l = vec![vec![0.0; self.n]; self.n];
701                for i in 0..self.n {
702                    for j in 0..=i {
703                        let mut sum = a[i][j];
704                        for k in 0..j {
705                            sum -= l[i][k] * l[j][k];
706                        }
707                        if i == j {
708                            if sum <= 1e-12 {
709                                return None;
710                            }
711                            l[i][j] = sum.sqrt();
712                        } else {
713                            l[i][j] = sum / l[j][j];
714                        }
715                    }
716                }
717
718                let mut y = vec![0.0; self.n];
719                for i in 0..self.n {
720                    let mut sum = rhs[i];
721                    for k in 0..i {
722                        sum -= l[i][k] * y[k];
723                    }
724                    y[i] = sum / l[i][i];
725                }
726
727                let mut x = vec![0.0; self.n];
728                for i in (0..self.n).rev() {
729                    let mut sum = y[i];
730                    for k in i + 1..self.n {
731                        sum -= l[k][i] * x[k];
732                    }
733                    x[i] = sum / l[i][i];
734                }
735
736                Some(x)
737            } else {
738                None
739            }
740        }
741    }
742}
743
744#[cfg(test)]
745mod tests {
746    use super::*;
747    use crate::geometry::{Point, Polygon};
748    use crate::material::presets::STEEL_S355;
749    use crate::section::Section;
750    use crate::section_library::ParametricSection;
751
752    #[test]
753    fn warping_solid_rectangle() {
754        let poly = Polygon::new(vec![
755            Point::new(-0.1, -0.05),
756            Point::new(0.1, -0.05),
757            Point::new(0.1, 0.05),
758            Point::new(-0.1, 0.05),
759        ]);
760        let section = Section::new(poly, vec![]);
761        let props = WarpingProperties::from_section(&section, 0.3);
762
763        assert!(props.j > 0.0);
764        assert!(
765            props.iw.abs() < 1e-6,
766            "solid Iw should be ~0, got {}",
767            props.iw
768        );
769        assert!(props.shear_center.x.abs() < 1e-4);
770        assert!(props.shear_center.y.abs() < 1e-4);
771    }
772
773    #[test]
774    fn warping_circle() {
775        let poly = crate::section_library::circle_polygon(0.05, 64);
776        let section = Section::new(poly, vec![]);
777        let props = WarpingProperties::from_section(&section, 0.3);
778
779        // For circle: J = π*r^4/2
780        let r: f64 = 0.05;
781        let expected_j = std::f64::consts::PI * r.powi(4) / 2.0;
782        assert!((props.j - expected_j).abs() / expected_j < 0.2); // Approximate
783
784        assert!(
785            props.iw.abs() < 1e-6,
786            "circle Iw should be ~0, got {}",
787            props.iw
788        );
789    }
790
791    #[test]
792    fn warping_i_section() {
793        let i = crate::section_library::steel::ISection::new(0.3, 0.15, 0.007, 0.01, 0.012);
794        let section = i.build();
795        let props = WarpingProperties::from_section(&section, 0.3);
796
797        assert!(props.j > 0.0);
798        assert!(props.iw > 0.0); // Open section has warping
799        // Doubly symmetric: shear centre coincides with the centroid.
800        let c = section.centroid();
801        assert!((props.shear_center.x - c.x).abs() < 5e-3);
802        assert!((props.shear_center.y - c.y).abs() < 5e-3);
803    }
804
805    #[test]
806    fn torsion_analysis_pure() {
807        let i = crate::section_library::steel::ISection::new(0.3, 0.15, 0.007, 0.01, 0.012);
808        let section = i.build();
809
810        let analysis = TorsionAnalysis::pure_torsion(&section, 10e3, &STEEL_S355); // 10 kNm
811
812        assert!(analysis.tau_sv_max > 0.0);
813        assert!(analysis.theta_prime > 0.0);
814    }
815
816    #[test]
817    fn torsion_analysis_constrained() {
818        let i = crate::section_library::steel::ISection::new(0.3, 0.15, 0.007, 0.01, 0.012);
819        let section = i.build();
820
821        let analysis = TorsionAnalysis::constrained_torsion(&section, 10e3, 5e3, &STEEL_S355);
822
823        assert!(analysis.tau_sv_max > 0.0);
824        assert!(analysis.sigma_w_max >= 0.0);
825    }
826
827    #[test]
828    fn warping_length() {
829        let i = crate::section_library::steel::ISection::new(0.3, 0.15, 0.007, 0.01, 0.012);
830        let section = i.build();
831        let props = WarpingProperties::from_section(&section, 0.3);
832
833        let l_w = props.warping_length(STEEL_S355.youngs_modulus, STEEL_S355.shear_modulus);
834
835        // For IPE300, warping length ~2-5m typically
836        assert!(l_w > 0.5 && l_w < 20.0);
837    }
838
839    #[test]
840    fn warping_principal_axes_doubly_symmetric() {
841        // I-section: doubly symmetric, principal axes == centroidal axes
842        let i = crate::section_library::steel::ISection::new(0.3, 0.15, 0.007, 0.01, 0.012);
843        let section = i.build();
844        let props = WarpingProperties::from_section(&section, 0.3);
845
846        // Principal angle ~ 0 or pi/2
847        let angle_norm = props
848            .principal_angle
849            .rem_euclid(std::f64::consts::FRAC_PI_2);
850        assert!(angle_norm < 1e-4 || (angle_norm - std::f64::consts::FRAC_PI_2).abs() < 1e-4);
851
852        // Shear areas should be positive
853        assert!(props.a_s11 > 0.0);
854        assert!(props.a_s22 > 0.0);
855
856        // delta_s should be positive
857        assert!(props.delta_s > 0.0);
858
859        // Monosymmetry constants ~ 0 for doubly-symmetric
860        assert!(props.beta_11.abs() < 1e-2);
861        assert!(props.beta_22.abs() < 1e-2);
862    }
863
864    #[test]
865    fn warping_principal_axes_channel() {
866        // Channel: singly symmetric (about x-axis), principal angle ~ 0
867        let channel =
868            crate::section_library::steel::ChannelSection::new(0.2, 0.1, 0.008, 0.008, 0.0, 0.0);
869        let section = channel.build();
870        let props = WarpingProperties::from_section(&section, 0.3);
871
872        // Channel is symmetric about x-axis, so principal angle ~ 0
873        assert!(props.principal_angle.abs() < 1e-4);
874
875        // Shear areas about principal axes should match centroidal
876        assert!((props.a_s11 - props.ay).abs() / props.ay < 0.05);
877        assert!((props.a_s22 - props.az).abs() / props.az < 0.05);
878
879        // beta_x ~ 0 (symmetric about x), beta_y != 0
880        assert!(props.beta_x.abs() < 1e-3);
881    }
882
883    #[test]
884    fn warping_principal_axes_angle() {
885        // Angle section: unsymmetric, principal angle != 0
886        let angle = crate::section_library::steel::AngleSection::new(0.1, 0.075, 0.008, 0.0, 0.0);
887        let section = angle.build();
888        let props = WarpingProperties::from_section(&section, 0.3);
889
890        // Shear areas should be positive
891        assert!(props.a_s11 > 0.0);
892        assert!(props.a_s22 > 0.0);
893
894        // delta_s should be positive
895        assert!(props.delta_s > 0.0);
896    }
897
898    #[test]
899    fn warping_shear_areas_i_section() {
900        // I-section: check that FEM shear areas are positive and reasonable.
901        // The FEM shear areas differ from the simple web/flange area formulas
902        // (which were previously used as a fallback). FEM computes shear areas
903        // from the full shear coefficient formulation, which gives different
904        // values than the simple web/flange area approximation.
905        let i = crate::section_library::steel::ISection::new(0.3, 0.15, 0.007, 0.01, 0.012);
906        let section = i.build();
907        let props = WarpingProperties::from_section(&section, 0.3);
908
909        // Both shear areas should be positive and in a reasonable range
910        assert!(props.ay > 0.0);
911        assert!(props.az > 0.0);
912
913        // FEM shear areas validated against Python sectionproperties v3.10.2
914        // (same geometry: h=300, b=150, tw=7, tf=10, r=12 mm, mesh=10 mm).
915        // Python: a_sx = 0.002735 m^2, a_sy = 0.002038 m^2.
916        // Rust FEM agrees to within ~5% (mesh/element differences).
917        // Previous expected values (ay~0.00261, az~0.00351) were calibrated
918        // against a buggy lambda formula (ct_w2/ct_w1 instead of ct_w1/ct_w2)
919        // in solve_with_fallback, fixed in commit c4fabac.
920        assert!((props.ay - 0.00274).abs() / 0.00274 < 0.10);
921        assert!((props.az - 0.00204).abs() / 0.00204 < 0.10);
922    }
923
924    #[test]
925    fn warping_trefftz_shear_center_doubly_symmetric() {
926        // Doubly-symmetric I-section: Trefftz shear center == elasticity shear center
927        let i = crate::section_library::steel::ISection::new(0.3, 0.15, 0.007, 0.01, 0.012);
928        let section = i.build();
929        let props = WarpingProperties::from_section(&section, 0.3);
930
931        assert!((props.shear_center_trefftz.x - props.shear_center.x).abs() < 1e-10);
932        assert!((props.shear_center_trefftz.y - props.shear_center.y).abs() < 1e-10);
933        // Both should be at centroid (0, 0) for doubly-symmetric section
934        assert!(props.shear_center_trefftz.x.abs() < 5e-3);
935        assert!(props.shear_center_trefftz.y.abs() < 5e-3);
936    }
937
938    #[test]
939    fn warping_trefftz_shear_center_channel() {
940        // Channel section: singly-symmetric, shear center outside web
941        let channel =
942            crate::section_library::steel::ChannelSection::new(0.2, 0.1, 0.008, 0.008, 0.0, 0.0);
943        let section = channel.build();
944        let props = WarpingProperties::from_section(&section, 0.3);
945
946        // For open thin-walled sections, Trefftz == elasticity
947        assert!((props.shear_center_trefftz.x - props.shear_center.x).abs() < 1e-10);
948        assert!((props.shear_center_trefftz.y - props.shear_center.y).abs() < 1e-10);
949    }
950
951    #[test]
952    fn monosymmetry_plus_minus_doubly_symmetric() {
953        // Doubly-symmetric I-section: all monosymmetry constants are zero.
954        // Physical value is exactly 0; the FE mesh is only approximately symmetric,
955        // so small discretization noise (~1e-3 m) is expected.
956        let i = crate::section_library::steel::ISection::new(0.3, 0.15, 0.007, 0.01, 0.012);
957        let section = i.build();
958        let props = WarpingProperties::from_section(&section, 0.3);
959
960        assert!(props.beta_x_plus.abs() < 5e-3);
961        assert!(props.beta_x_minus.abs() < 5e-3);
962        assert!(props.beta_y_plus.abs() < 1e-2);
963        assert!(props.beta_y_minus.abs() < 1e-2);
964    }
965
966    #[test]
967    fn monosymmetry_plus_minus_relation() {
968        // Verify beta_minus = -beta_plus (Python convention)
969        let channel =
970            crate::section_library::steel::ChannelSection::new(0.2, 0.1, 0.008, 0.008, 0.0, 0.0);
971        let section = channel.build();
972        let props = WarpingProperties::from_section(&section, 0.3);
973
974        // beta_x_minus = -beta_x_plus
975        assert!((props.beta_x_minus + props.beta_x_plus).abs() < 1e-10);
976
977        // beta_y_minus = -beta_y_plus
978        assert!((props.beta_y_minus + props.beta_y_plus).abs() < 1e-10);
979    }
980
981    #[test]
982    fn monosymmetry_plus_minus_principal_axes() {
983        // For symmetric section, principal plus/minus match centroidal.
984        // Physical value is zero; allow FE discretization noise.
985        let i = crate::section_library::steel::ISection::new(0.3, 0.15, 0.007, 0.01, 0.012);
986        let section = i.build();
987        let props = WarpingProperties::from_section(&section, 0.3);
988
989        assert!(props.beta_11_plus.abs() < 5e-3);
990        assert!(props.beta_11_minus.abs() < 5e-3);
991        assert!(props.beta_22_plus.abs() < 1e-2);
992        assert!(props.beta_22_minus.abs() < 1e-2);
993    }
994
995    #[test]
996    fn constrained_torsion_omega_max_uses_correct_dimensions() {
997        // Regression test: h and b were swapped in constrained_torsion.
998        // For I-section with depth=0.3, width=0.15:
999        //   correct omega_max = (h/2)^2 * (b/2) = (0.15)^2 * 0.075 = 0.0016875
1000        //   buggy  omega_max = (b/2)^2 * (h/2) = (0.075)^2 * 0.15 = 0.00084375
1001        let i = crate::section_library::steel::ISection::new(0.3, 0.15, 0.007, 0.01, 0.012);
1002        let section = i.build();
1003        let props = WarpingProperties::from_section(&section, 0.3);
1004
1005        let bimoment = 1e3;
1006        let analysis = TorsionAnalysis::constrained_torsion(&section, 0.0, bimoment, &STEEL_S355);
1007
1008        if props.iw > 0.0 {
1009            let omega_max = analysis.sigma_w_max * props.iw / bimoment;
1010            let h = 0.3_f64;
1011            let b = 0.15_f64;
1012            let correct = (h / 2.0).powi(2) * (b / 2.0);
1013            let buggy = (b / 2.0).powi(2) * (h / 2.0);
1014            assert!(
1015                (omega_max - correct).abs() < (omega_max - buggy).abs(),
1016                "omega_max should match correct formula, not buggy"
1017            );
1018        }
1019    }
1020
1021    #[test]
1022    fn channel_shear_center_magnitude_reasonable() {
1023        // Regression test: shear center formula had hw instead of hw².
1024        // ChannelSection::build() creates a solid C-shape, not thin-walled.
1025        // Manually create a thin-walled channel polygon.
1026        let (h, b, tw, tf) = (0.2, 0.075, 0.003, 0.005);
1027        let hh = h / 2.0;
1028        let poly = Polygon::new(vec![
1029            Point::new(0.0, -hh),
1030            Point::new(tw, -hh),
1031            Point::new(tw + b, -hh),
1032            Point::new(tw + b, -hh + tf),
1033            Point::new(tw, -hh + tf),
1034            Point::new(tw, hh - tf),
1035            Point::new(tw + b, hh - tf),
1036            Point::new(tw + b, hh),
1037            Point::new(tw, hh),
1038            Point::new(0.0, hh),
1039        ]);
1040        let section = Section::new(poly, vec![]);
1041        let props = WarpingProperties::from_section(&section, 0.3);
1042
1043        // Verify it's detected as thin-walled
1044        assert!(section.is_thin_walled(), "section should be thin-walled");
1045
1046        // Shear centre must lie behind the web (negative x) within one
1047        // flange width.
1048        assert!(
1049            props.shear_center.x < 1e-6 && props.shear_center.x.abs() < b,
1050            "channel shear center x should be behind the web, got {}",
1051            props.shear_center.x
1052        );
1053
1054        // Magnitude should be less than flange width (skip if near-zero due to FEM precision)
1055        if props.shear_center.x.abs() > 1e-6 {
1056            assert!(
1057                props.shear_center.x.abs() < b,
1058                "channel shear center magnitude should be < flange width {}, got {}",
1059                b,
1060                props.shear_center.x.abs()
1061            );
1062        }
1063    }
1064
1065    #[test]
1066    fn channel_warping_constant_positive_and_reasonable() {
1067        // Regression test: warping constant used rough 0.25 approximation.
1068        // Now uses standard formula: Iw = tf*bf³*hw²/12 * (tw*hw+2*tf*bf)/(tw*hw+6*tf*bf)
1069        let (h, b, tw, tf) = (0.2, 0.075, 0.003, 0.005);
1070        let hh = h / 2.0;
1071        let poly = Polygon::new(vec![
1072            Point::new(0.0, -hh),
1073            Point::new(tw, -hh),
1074            Point::new(tw + b, -hh),
1075            Point::new(tw + b, -hh + tf),
1076            Point::new(tw, -hh + tf),
1077            Point::new(tw, hh - tf),
1078            Point::new(tw + b, hh - tf),
1079            Point::new(tw + b, hh),
1080            Point::new(tw, hh),
1081            Point::new(0.0, hh),
1082        ]);
1083        let section = Section::new(poly, vec![]);
1084        let props = WarpingProperties::from_section(&section, 0.3);
1085
1086        // Iw should be positive for an open section
1087        assert!(
1088            props.iw > 0.0,
1089            "channel Iw should be positive, got {}",
1090            props.iw
1091        );
1092    }
1093
1094    #[test]
1095    fn try_from_section_ok_for_valid_section() {
1096        let poly = Polygon::new(vec![
1097            Point::new(-0.1, -0.05),
1098            Point::new(0.1, -0.05),
1099            Point::new(0.1, 0.05),
1100            Point::new(-0.1, 0.05),
1101        ]);
1102        let section = Section::new(poly, vec![]);
1103        let result = WarpingProperties::try_from_section(&section, 0.3);
1104        assert!(
1105            result.is_ok(),
1106            "try_from_section should succeed for valid section"
1107        );
1108        let props = result.unwrap();
1109        assert!(props.j > 0.0);
1110        assert!(props.area > 0.0);
1111    }
1112
1113    #[test]
1114    fn try_from_section_matches_from_section() {
1115        let poly = Polygon::new(vec![
1116            Point::new(-0.1, -0.05),
1117            Point::new(0.1, -0.05),
1118            Point::new(0.1, 0.05),
1119            Point::new(-0.1, 0.05),
1120        ]);
1121        let section = Section::new(poly, vec![]);
1122        let fallible = WarpingProperties::try_from_section(&section, 0.3).unwrap();
1123        let panicking = WarpingProperties::from_section(&section, 0.3);
1124        assert!((fallible.j - panicking.j).abs() < 1e-15);
1125        assert!((fallible.iw - panicking.iw).abs() < 1e-15);
1126        assert!((fallible.area - panicking.area).abs() < 1e-15);
1127    }
1128}