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