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