Skip to main content

qualia_core_db/specialized_libs/engineering_analysis/
structural.rs

1use super::*;
2
3/// Structural analyzer for structural engineering analysis
4pub struct StructuralAnalyzer {
5    pub(super) finite_element_solver: FiniteElementSolver,
6    structural_dynamics: StructuralDynamics,
7    buckling_analysis: BucklingAnalysis,
8    vibration_analysis: VibrationAnalysis,
9    model_store: HashMap<String, EngineeringModel>,
10    /// Phase 2 linear-algebra library used for FEA matrix assembly / solves.
11    linear_algebra: Option<Arc<Mutex<LinearAlgebraLibrary>>>,
12}
13
14/// Finite element solver
15pub struct FiniteElementSolver {
16    mesh_generator: MeshGenerator,
17    element_library: ElementLibrary,
18    solver_engine: SolverEngine,
19    post_processor: PostProcessor,
20    /// ZNS zone manager for zero-copy mesh / element storage.
21    zns_manager: Option<Arc<Mutex<ZnsZoneManager>>>,
22}
23
24/// Mesh generator
25pub struct MeshGenerator {
26    mesh_types: HashMap<String, MeshType>,
27    mesh_algorithms: HashMap<String, MeshAlgorithm>,
28    mesh_quality: MeshQuality,
29}
30
31/// Mesh types
32#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
33pub enum MeshType {
34    /// Triangular mesh
35    Triangular,
36    /// Quadrilateral mesh
37    Quadrilateral,
38    /// Tetrahedral mesh
39    Tetrahedral,
40    /// Hexahedral mesh
41    Hexahedral,
42    /// Mixed mesh
43    Mixed,
44    /// Structured mesh
45    Structured,
46    /// Unstructured mesh
47    Unstructured,
48}
49
50/// Mesh algorithms
51#[derive(Debug, Clone)]
52pub struct MeshAlgorithm {
53    pub algorithm_id: String,
54    pub algorithm_name: String,
55    pub algorithm_type: MeshAlgorithmType,
56    pub parameters: MeshAlgorithmParameters,
57}
58
59/// Mesh algorithm types
60#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
61pub enum MeshAlgorithmType {
62    Delaunay,
63    AdvancingFront,
64    Octree,
65    Cartesian,
66    Custom(String),
67}
68
69/// Mesh algorithm parameters
70#[derive(Debug, Clone, Serialize, Deserialize)]
71pub struct MeshAlgorithmParameters {
72    pub element_size: f64,
73    pub refinement_level: u32,
74    pub quality_criteria: Vec<QualityCriterion>,
75}
76
77/// Quality criteria
78#[derive(Debug, Clone, Serialize, Deserialize)]
79pub struct QualityCriterion {
80    pub criterion_name: String,
81    pub minimum_value: f64,
82    pub maximum_value: f64,
83}
84
85/// Mesh quality
86pub struct MeshQuality {
87    pub quality_metrics: HashMap<String, QualityMetric>,
88    pub quality_assessment: QualityAssessment,
89}
90
91/// Quality metrics
92#[derive(Debug, Clone)]
93pub struct QualityMetric {
94    pub metric_name: String,
95    pub metric_value: f64,
96    pub metric_type: MetricType,
97}
98
99/// Metric types
100#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
101pub enum MetricType {
102    AspectRatio,
103    Skewness,
104    Orthogonality,
105    Jacobian,
106}
107
108/// Quality assessment
109#[derive(Debug, Clone)]
110pub struct QualityAssessment {
111    pub overall_quality: f64,
112    pub quality_grade: QualityGrade,
113    pub recommendations: Vec<String>,
114}
115
116/// Quality grades
117#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
118pub enum QualityGrade {
119    Excellent,
120    Good,
121    Fair,
122    Poor,
123}
124
125/// Element library
126pub struct ElementLibrary {
127    elements: HashMap<String, Element>,
128    element_properties: HashMap<String, ElementProperties>,
129}
130
131/// Elements
132#[derive(Debug, Clone)]
133pub struct Element {
134    pub element_id: String,
135    pub element_name: String,
136    pub element_type: ElementType,
137    pub nodes: Vec<Node>,
138    pub properties: ElementProperties,
139}
140
141/// Element types
142#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
143pub enum ElementType {
144    /// 1D elements
145    Truss,
146    Beam,
147    Frame,
148    /// 2D elements
149    Shell,
150    Plate,
151    Membrane,
152    /// 3D elements
153    Solid,
154    Tetrahedron,
155    Hexahedron,
156    /// Special elements
157    Mass,
158    Spring,
159    Damper,
160}
161
162/// Nodes
163#[derive(Debug, Clone)]
164pub struct Node {
165    pub node_id: String,
166    pub coordinates: Vec<f64>,
167    pub degrees_of_freedom: Vec<DOF>,
168    pub constraints: Vec<Constraint>,
169}
170
171/// Degrees of freedom
172#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
173pub enum DOF {
174    UX,
175    UY,
176    UZ,
177    ROTX,
178    ROTY,
179    ROTZ,
180    Temperature,
181    Pressure,
182}
183
184/// Constraints
185#[derive(Debug, Clone)]
186pub struct Constraint {
187    pub constraint_id: String,
188    pub constraint_type: ConstraintType,
189    pub constraint_value: f64,
190}
191
192/// Constraint types
193#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
194pub enum ConstraintType {
195    Fixed,
196    Pinned,
197    Roller,
198    Displacement,
199    Rotation,
200    Temperature,
201}
202
203/// Element properties
204#[derive(Debug, Clone, Serialize, Deserialize)]
205pub struct ElementProperties {
206    pub material_properties: MaterialProperties,
207    pub geometric_properties: GeometricProperties,
208    pub section_properties: SectionProperties,
209}
210
211/// Material properties
212#[derive(Debug, Clone, Serialize, Deserialize)]
213pub struct MaterialProperties {
214    pub youngs_modulus: f64,
215    pub poissons_ratio: f64,
216    pub density: f64,
217    pub thermal_expansion: f64,
218    pub thermal_conductivity: f64,
219    pub specific_heat: f64,
220    pub yield_strength: f64,
221    pub ultimate_strength: f64,
222}
223
224/// Geometric properties
225#[derive(Debug, Clone, Serialize, Deserialize)]
226pub struct GeometricProperties {
227    pub area: f64,
228    pub volume: f64,
229    pub perimeter: f64,
230    pub surface_area: f64,
231}
232
233/// Section properties
234#[derive(Debug, Clone, Serialize, Deserialize)]
235pub struct SectionProperties {
236    pub moment_of_inertia: Vec<f64>,
237    pub torsional_constant: f64,
238    pub section_modulus: Vec<f64>,
239    pub shear_center: Vec<f64>,
240}
241
242/// Solver engine
243pub struct SolverEngine {
244    solvers: HashMap<String, Solver>,
245    solver_parameters: SolverParameters,
246    convergence_criteria: ConvergenceCriteria,
247}
248
249/// Solvers
250#[derive(Debug, Clone)]
251pub struct Solver {
252    pub solver_id: String,
253    pub solver_name: String,
254    pub solver_type: SolverType,
255    pub capabilities: SolverCapabilities,
256}
257
258/// Solver types
259#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
260pub enum SolverType {
261    Direct,
262    Iterative,
263    Eigenvalue,
264    Transient,
265    Nonlinear,
266}
267
268/// Solver capabilities
269#[derive(Debug, Clone)]
270pub struct SolverCapabilities {
271    pub max_dof: u64,
272    pub supported_element_types: Vec<ElementType>,
273    pub analysis_types: Vec<AnalysisType>,
274}
275
276/// Analysis types
277#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
278pub enum AnalysisType {
279    LinearStatic,
280    NonlinearStatic,
281    LinearDynamic,
282    NonlinearDynamic,
283    Thermal,
284    Buckling,
285    Vibration,
286}
287
288/// Solver parameters
289#[derive(Debug, Clone, Serialize, Deserialize)]
290pub struct SolverParameters {
291    pub tolerance: f64,
292    pub max_iterations: u32,
293    pub convergence_acceleration: ConvergenceAcceleration,
294}
295
296/// Convergence acceleration
297#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
298pub enum ConvergenceAcceleration {
299    None,
300    Jacobi,
301    GaussSeidel,
302    SOR,
303    Multigrid,
304}
305
306/// Convergence criteria
307pub struct ConvergenceCriteria {
308    pub criteria_type: ConvergenceType,
309    pub tolerance: f64,
310    pub max_iterations: u32,
311}
312
313/// Convergence types
314#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
315pub enum ConvergenceType {
316    Residual,
317    Energy,
318    Displacement,
319    Force,
320}
321
322/// Post processor
323pub struct PostProcessor {
324    result_extractors: HashMap<String, ResultExtractor>,
325    visualization_engine: VisualizationEngine,
326    report_generator: ReportGenerator,
327}
328
329/// Result extractors
330#[derive(Debug, Clone)]
331pub struct ResultExtractor {
332    pub extractor_id: String,
333    pub extractor_name: String,
334    pub result_type: ResultType,
335    pub extraction_method: ExtractionMethod,
336}
337
338/// Result types
339#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
340pub enum ResultType {
341    Displacement,
342    Stress,
343    Strain,
344    Force,
345    Reaction,
346    Energy,
347    Temperature,
348    HeatFlux,
349}
350
351/// Extraction methods
352#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
353pub enum ExtractionMethod {
354    Nodal,
355    Elemental,
356    Gaussian,
357    Custom(String),
358}
359
360/// Visualization engine
361#[derive(Debug, Clone)]
362pub struct VisualizationEngine {
363    visualization_types: HashMap<String, VisualizationType>,
364    rendering_engine: RenderingEngine,
365}
366
367/// Visualization types
368#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
369pub enum VisualizationType {
370    Contour,
371    Vector,
372    Deformed,
373    Animation,
374    Custom(String),
375}
376
377/// Rendering engine
378#[derive(Debug, Clone)]
379pub struct RenderingEngine {
380    pub engine_type: RenderingEngineType,
381    pub rendering_options: RenderingOptions,
382}
383
384/// Rendering engine types
385#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
386pub enum RenderingEngineType {
387    OpenGL,
388    Vulkan,
389    DirectX,
390    Software,
391}
392
393/// Rendering options
394#[derive(Debug, Clone, Serialize, Deserialize)]
395pub struct RenderingOptions {
396    pub color_map: String,
397    pub scale_factor: f64,
398    pub line_width: f64,
399    pub transparency: f64,
400}
401
402/// Report generator
403pub struct ReportGenerator {
404    report_templates: HashMap<String, ReportTemplate>,
405    export_formats: Vec<ExportFormat>,
406}
407
408/// Report templates
409#[derive(Debug, Clone)]
410pub struct ReportTemplate {
411    pub template_id: String,
412    pub template_name: String,
413    pub template_type: TemplateType,
414    pub sections: Vec<ReportSection>,
415}
416
417/// Template types
418#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
419pub enum TemplateType {
420    Summary,
421    Detailed,
422    Technical,
423    Executive,
424}
425
426/// Report sections
427#[derive(Debug, Clone)]
428pub struct ReportSection {
429    pub section_id: String,
430    pub section_name: String,
431    pub section_content: SectionContent,
432}
433
434/// Section content
435#[derive(Debug, Clone)]
436pub struct SectionContent {
437    pub content_type: ContentType,
438    pub data: Vec<u8>,
439    pub format: ContentFormat,
440}
441
442/// Content types
443#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
444pub enum ContentType {
445    Text,
446    Table,
447    Chart,
448    Image,
449}
450
451/// Content formats
452#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
453pub enum ContentFormat {
454    Text,
455    HTML,
456    PDF,
457    CSV,
458}
459
460/// Export formats
461#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
462pub enum ExportFormat {
463    PDF,
464    HTML,
465    CSV,
466    JSON,
467    XML,
468}
469// Supporting implementations
470
471impl StructuralAnalyzer {
472    /// Creates a `StructuralAnalyzer` with empty registries / default configuration.
473    pub fn new() -> Self {
474        Self {
475            finite_element_solver: FiniteElementSolver::new(),
476            structural_dynamics: StructuralDynamics::new(),
477            buckling_analysis: BucklingAnalysis::new(),
478            vibration_analysis: VibrationAnalysis::new(),
479            model_store: HashMap::new(),
480            linear_algebra: None,
481        }
482    }
483
484    /// Attach the Phase 2 linear-algebra library for FEA matrix operations.
485    pub fn attach_linear_algebra(&mut self, lib: Option<Arc<Mutex<LinearAlgebraLibrary>>>) {
486        self.linear_algebra = lib;
487    }
488
489    /// Stores the model in the in-memory registry keyed by `model_id`.
490    pub fn store_model(&mut self, model: EngineeringModel) {
491        self.model_store.insert(model.model_id.clone(), model);
492    }
493
494    /// Readies `StructuralAnalyzer`; initializes any owned sub-engines (no-op for leaf structs).
495    pub fn initialize(&mut self) -> Result<(), EngineeringError> {
496        self.finite_element_solver.initialize()?;
497        self.structural_dynamics.initialize()?;
498        Ok(())
499    }
500
501    /// Checks the model has at least geometry dimensions; `ValidationError` otherwise.
502    pub fn validate_model(&self, model: &EngineeringModel) -> Result<(), EngineeringError> {
503        if model.geometry.dimensions.is_empty() {
504            return Err(EngineeringError::ValidationError(
505                "Model must have dimensions".to_string(),
506            ));
507        }
508        Ok(())
509    }
510
511    /// First-principles axial strength-of-materials analysis: `σ = F/A`,
512    /// `ε = σ/E`, `δ = F·L/(A·E)`, factor of safety `σ_yield/|σ|`. Dispatches
513    /// `Thermal` to `ThermalAnalyzer` and `Vibration` to a single-element
514    /// `solve_modal_eigen`. Missing materials/geometry/loads return
515    /// `InsufficientData` — never a fabricated constant.
516    pub fn analyze(
517        &mut self,
518        model: &EngineeringModel,
519        analysis_type: AnalysisType,
520    ) -> Result<AnalysisResults, EngineeringError> {
521        // REAL first-principles axial strength-of-materials (a real member analysis, not full FEA):
522        //   stress σ = F / A,  strain ε = σ / E,  axial deflection δ = F·L / (A·E),
523        //   factor of safety FoS = σ_yield / |σ|.
524        // The safety_factor is GENUINELY COMPUTED from the material yield strength and the applied
525        // stress — never a fabricated constant (previously a hardcoded 2.5). Missing inputs are
526        // reported as InsufficientData, not silently defaulted.
527        let material = model.materials.values().next().ok_or_else(|| {
528            EngineeringError::InsufficientData(
529                "model has no material; cannot compute stress / factor of safety".to_string(),
530            )
531        })?;
532        let mp = &material.material_properties;
533        let e = mp.youngs_modulus;
534        let sy = mp.yield_strength;
535        let density = mp.density;
536
537        let dims = &model.geometry.dimensions;
538        if dims.len() < 2 || dims.iter().take(2).any(|&d| !(d > 0.0)) {
539            return Err(EngineeringError::InsufficientData(
540                "geometry needs at least two positive cross-section dimensions to form an area"
541                    .to_string(),
542            ));
543        }
544        let area = dims[0] * dims[1]; // cross-sectional area (m²)
545        let length = dims.get(2).copied().filter(|&l| l > 0.0).unwrap_or(dims[0]); // member length (m)
546
547        if model.loads.is_empty() {
548            return Err(EngineeringError::InsufficientData(
549                "model has no loads; cannot compute stress".to_string(),
550            ));
551        }
552        let force: f64 = model.loads.iter().map(|l| l.load_magnitude).sum(); // total axial load (N)
553
554        let stress = force / area; // Pa
555        let strain = if e > 0.0 { stress / e } else { 0.0 };
556        let displacement = if e > 0.0 {
557            force * length / (area * e)
558        } else {
559            f64::INFINITY
560        };
561        let safety_factor = if stress.abs() > 0.0 && sy > 0.0 {
562            sy / stress.abs()
563        } else if stress.abs() == 0.0 {
564            f64::INFINITY // no load ⇒ unbounded margin
565        } else {
566            0.0 // no yield strength supplied ⇒ no defined margin
567        };
568
569        match analysis_type {
570            AnalysisType::LinearStatic => Ok(AnalysisResults {
571                results_id: "structural_axial".to_string(),
572                analysis_type,
573                displacement_field: vec![displacement],
574                stress_field: vec![stress],
575                strain_field: vec![strain],
576                reaction_forces: vec![-force], // static equilibrium reaction
577                safety_factor,
578                temperature_field: Vec::new(), // mechanical analysis — no thermal output
579                heat_flux_field: Vec::new(),
580            }),
581            AnalysisType::Buckling => {
582                // Euler elastic critical buckling of the same prismatic member,
583                // weak-axis second moment of area I = min(b·h³, h·b³)/12 from the
584                // two cross-section dimensions, pinned–pinned effective length K=1:
585                //   P_cr = π²·E·I / (K·L)².
586                // The reported `safety_factor` is the buckling LOAD FACTOR
587                // λ = P_cr / |P_applied| — the multiplier on the axial load at
588                // which the member buckles (this is exactly the physical margin
589                // against buckling, so it fits the `safety_factor` field). The
590                // critical load itself is exposed via
591                // `BucklingAnalysis::analyze_from_model`.
592                let b = dims[0];
593                let h = dims[1];
594                let i_weak = (b * h * h * h).min(h * b * b * b) / 12.0;
595                let k_factor = 1.0_f64;
596                let le = k_factor * length;
597                let p_cr = std::f64::consts::PI.powi(2) * e * i_weak / (le * le);
598                let load_factor = if force.abs() > 0.0 {
599                    p_cr / force.abs()
600                } else {
601                    f64::INFINITY
602                };
603                Ok(AnalysisResults {
604                    results_id: "structural_buckling_euler".to_string(),
605                    analysis_type,
606                    displacement_field: vec![displacement],
607                    stress_field: vec![stress],
608                    strain_field: vec![strain],
609                    reaction_forces: vec![-force],
610                    safety_factor: load_factor,
611                    temperature_field: Vec::new(),
612                    heat_flux_field: Vec::new(),
613                })
614            }
615            AnalysisType::NonlinearStatic => {
616                // Geometrically-nonlinear axial member (Green–Lagrange strain), fixed–
617                // free, solved by Newton–Raphson (`fem::GeoNonlinearBar`). Reduces to
618                // the linear δ = F·L/(A·E) for small loads and stiffens geometrically
619                // for large loads. Real assembly + iterative solve — no closed form.
620                let ea = e * area;
621                let bar = fem::GeoNonlinearBar { ea, length };
622                let u = bar.solve_static(force, 1e-10, 200)?;
623                let eps = bar.strain(u); // Green–Lagrange axial strain
624                let sigma = e * eps;
625                let sf = if sigma.abs() > 0.0 && sy > 0.0 {
626                    sy / sigma.abs()
627                } else if sigma.abs() == 0.0 {
628                    f64::INFINITY
629                } else {
630                    0.0
631                };
632                Ok(AnalysisResults {
633                    results_id: "structural_nonlinear_static_geom_bar".to_string(),
634                    analysis_type,
635                    displacement_field: vec![u],
636                    stress_field: vec![sigma],
637                    strain_field: vec![eps],
638                    reaction_forces: vec![-bar.internal_force(u)],
639                    safety_factor: sf,
640                    temperature_field: Vec::new(),
641                    heat_flux_field: Vec::new(),
642                })
643            }
644            AnalysisType::LinearDynamic => {
645                // Transient response of the axial member (SDOF: stiffness k = EA/L,
646                // lumped free-node mass m = ½ρAL) to a SUDDENLY-APPLIED constant axial
647                // load, integrated by Newmark-β (avg-acceleration). The reported field
648                // is the PEAK dynamic displacement over the response — for an undamped
649                // step load this is the classic dynamic amplification (→ 2× static).
650                if !(density > 0.0) {
651                    return Err(EngineeringError::InsufficientData(
652                        "dynamic analysis needs a positive material density".to_string(),
653                    ));
654                }
655                let k = e * area / length;
656                let m = density * area * length / 2.0;
657                let omega = (k / m).sqrt();
658                let period = 2.0 * std::f64::consts::PI / omega;
659                let dt = period / 200.0;
660                let nsteps = 260; // > half a period, captures the peak at ωt = π
661                let res = fem::newmark_linear(
662                    &[m],
663                    &[0.0],
664                    &[k],
665                    1,
666                    |_t| vec![force],
667                    &[0.0],
668                    &[0.0],
669                    dt,
670                    nsteps,
671                    0.25,
672                    0.5,
673                )?;
674                let u_peak = res.peak_abs(0);
675                let sigma = e * (u_peak / length); // peak axial stress
676                let sf = if sigma.abs() > 0.0 && sy > 0.0 {
677                    sy / sigma.abs()
678                } else if sigma.abs() == 0.0 {
679                    f64::INFINITY
680                } else {
681                    0.0
682                };
683                Ok(AnalysisResults {
684                    results_id: "structural_linear_dynamic_newmark".to_string(),
685                    analysis_type,
686                    displacement_field: vec![u_peak],
687                    stress_field: vec![sigma],
688                    strain_field: vec![u_peak / length],
689                    reaction_forces: vec![-k * u_peak], // peak base reaction
690                    safety_factor: sf,
691                    temperature_field: Vec::new(),
692                    heat_flux_field: Vec::new(),
693                })
694            }
695            AnalysisType::NonlinearDynamic => {
696                // As LinearDynamic, but the member is the geometrically-nonlinear bar,
697                // integrated by Newmark-β with an inner Newton–Raphson iteration each
698                // step (`fem::newmark_nonlinear`). Reports the peak dynamic response.
699                if !(density > 0.0) {
700                    return Err(EngineeringError::InsufficientData(
701                        "dynamic analysis needs a positive material density".to_string(),
702                    ));
703                }
704                let ea = e * area;
705                let bar = fem::GeoNonlinearBar { ea, length };
706                let k0 = ea / length; // small-strain stiffness for the period estimate
707                let m = density * area * length / 2.0;
708                let omega = (k0 / m).sqrt();
709                let period = 2.0 * std::f64::consts::PI / omega;
710                let dt = period / 200.0;
711                let nsteps = 260;
712                let res = fem::newmark_nonlinear(
713                    &[m],
714                    &[0.0],
715                    1,
716                    |u| vec![bar.internal_force(u[0])],
717                    |u| vec![bar.tangent(u[0])],
718                    |_t| vec![force],
719                    &[0.0],
720                    &[0.0],
721                    dt,
722                    nsteps,
723                    0.25,
724                    0.5,
725                    1e-10,
726                    100,
727                )?;
728                let u_peak = res.peak_abs(0);
729                let eps = bar.strain(u_peak);
730                let sigma = e * eps;
731                let sf = if sigma.abs() > 0.0 && sy > 0.0 {
732                    sy / sigma.abs()
733                } else if sigma.abs() == 0.0 {
734                    f64::INFINITY
735                } else {
736                    0.0
737                };
738                Ok(AnalysisResults {
739                    results_id: "structural_nonlinear_dynamic_newmark_newton".to_string(),
740                    analysis_type,
741                    displacement_field: vec![u_peak],
742                    stress_field: vec![sigma],
743                    strain_field: vec![eps],
744                    reaction_forces: vec![-bar.internal_force(u_peak)],
745                    safety_factor: sf,
746                    temperature_field: Vec::new(),
747                    heat_flux_field: Vec::new(),
748                })
749            }
750            AnalysisType::Thermal => {
751                let mut thermal = ThermalAnalyzer::new();
752                thermal.analyze(model, analysis_type)
753            }
754            AnalysisType::Vibration => {
755                if !(density > 0.0) {
756                    return Err(EngineeringError::InsufficientData(
757                        "vibration analysis needs a positive material density".to_string(),
758                    ));
759                }
760                let k = e * area / length;
761                let m = (density * area * length / 2.0).max(1e-12);
762                let modes = solve_modal_eigen(&[k], &[m], 1)?;
763                let omega = modes.first().map(|(w, _)| *w).unwrap_or(0.0);
764                let freq_hz = omega / (2.0 * std::f64::consts::PI);
765                let mode_vector = modes.into_iter().next().map(|(_, phi)| phi).unwrap_or_default();
766                Ok(AnalysisResults {
767                    results_id: "structural_vibration_modal".to_string(),
768                    analysis_type,
769                    displacement_field: vec![freq_hz], // fundamental natural frequency (Hz)
770                    stress_field: vec![omega],         // angular frequency (rad/s)
771                    strain_field: Vec::new(),
772                    reaction_forces: mode_vector,
773                    safety_factor: 1.0,
774                    temperature_field: Vec::new(),
775                    heat_flux_field: Vec::new(),
776                })
777            }
778        }
779    }
780
781    /// Real finite-element linear-static solve of an explicit [`fem::FeModel`]
782    /// (assemble `K u = F`, apply displacement BCs, solve via LU, recover reactions
783    /// and element axial forces). This is the direct FE entry point (the abstract
784    /// `analyze` facade interprets a prismatic member; this takes a full mesh).
785    pub fn fem_static(
786        &self,
787        model: &fem::FeModel,
788    ) -> Result<fem::FeStaticResult, EngineeringError> {
789        fem::solve_static(model)
790    }
791
792    /// Lists the supported analysis types (LinearStatic…Buckling).
793    pub fn list_analysis_types(&self) -> Vec<String> {
794        vec![
795            "LinearStatic".to_string(),
796            "NonlinearStatic".to_string(),
797            "LinearDynamic".to_string(),
798            "NonlinearDynamic".to_string(),
799            "Buckling".to_string(),
800        ]
801    }
802
803    /// Returns a clone of the stored model, or `None` if absent.
804    pub fn get_model(&self, model_id: &str) -> Option<EngineeringModel> {
805        self.model_store.get(model_id).cloned()
806    }
807
808    /// Returns a snapshot of the analyzer's performance metrics.
809    pub fn get_performance_metrics(&self) -> EngineeringPerformanceMetrics {
810        EngineeringPerformanceMetrics::new()
811    }
812
813    /// Borrow the buckling-analysis sub-analyzer.
814    pub fn buckling_analysis(&self) -> &BucklingAnalysis {
815        &self.buckling_analysis
816    }
817
818    /// Mutably borrow the buckling-analysis sub-analyzer.
819    pub fn buckling_analysis_mut(&mut self) -> &mut BucklingAnalysis {
820        &mut self.buckling_analysis
821    }
822
823    /// Borrow the vibration-analysis sub-analyzer.
824    pub fn vibration_analysis(&self) -> &VibrationAnalysis {
825        &self.vibration_analysis
826    }
827
828    /// Mutably borrow the vibration-analysis sub-analyzer.
829    pub fn vibration_analysis_mut(&mut self) -> &mut VibrationAnalysis {
830        &mut self.vibration_analysis
831    }
832}
833
834impl FiniteElementSolver {
835    /// Creates a `FiniteElementSolver` with empty registries / default configuration.
836    pub fn new() -> Self {
837        Self {
838            mesh_generator: MeshGenerator::new(),
839            element_library: ElementLibrary::new(),
840            solver_engine: SolverEngine::new(),
841            post_processor: PostProcessor::new(),
842            zns_manager: None,
843        }
844    }
845
846    /// Attach a ZNS zone manager for zero-copy mesh / element storage.
847    pub fn attach_zns_manager(&mut self, manager: Option<Arc<Mutex<ZnsZoneManager>>>) {
848        self.zns_manager = manager;
849    }
850
851    /// Readies `FiniteElementSolver`; initializes any owned sub-engines (no-op for leaf structs).
852    pub fn initialize(&mut self) -> Result<(), EngineeringError> {
853        self.mesh_generator.initialize()?;
854        self.element_library.initialize()?;
855        self.solver_engine.initialize()?;
856        self.post_processor.initialize()?;
857        Ok(())
858    }
859}
860
861impl MeshGenerator {
862    /// Creates a `MeshGenerator` with empty registries / default configuration.
863    pub fn new() -> Self {
864        Self {
865            mesh_types: HashMap::new(),
866            mesh_algorithms: HashMap::new(),
867            mesh_quality: MeshQuality::new(),
868        }
869    }
870
871    /// Populate the mesh-type and mesh-algorithm registries with the standard
872    /// engineering set. The `MeshType` enum exposes Triangular, Quadrilateral,
873    /// Tetrahedral, Hexahedral, Mixed, Structured and Unstructured (there are no
874    /// Prism/Pyramid variants, so those two requested topologies are represented
875    /// by the closest available enum members — Mixed for prism/pyramid hybrid
876    /// meshes).
877    pub fn initialize(&mut self) -> Result<(), EngineeringError> {
878        self.mesh_types
879            .insert("triangular".to_string(), MeshType::Triangular);
880        self.mesh_types
881            .insert("quadrilateral".to_string(), MeshType::Quadrilateral);
882        self.mesh_types
883            .insert("tetrahedral".to_string(), MeshType::Tetrahedral);
884        self.mesh_types
885            .insert("hexahedral".to_string(), MeshType::Hexahedral);
886        self.mesh_types.insert("prism".to_string(), MeshType::Mixed);
887        self.mesh_types
888            .insert("pyramid".to_string(), MeshType::Mixed);
889        self.mesh_types.insert("mixed".to_string(), MeshType::Mixed);
890        self.mesh_types
891            .insert("structured".to_string(), MeshType::Structured);
892        self.mesh_types
893            .insert("unstructured".to_string(), MeshType::Unstructured);
894
895        let default_params = MeshAlgorithmParameters {
896            element_size: 1.0,
897            refinement_level: 1,
898            quality_criteria: Vec::new(),
899        };
900        self.mesh_algorithms.insert(
901            "delaunay".to_string(),
902            MeshAlgorithm {
903                algorithm_id: "algo_delaunay".to_string(),
904                algorithm_name: "Delaunay Triangulation".to_string(),
905                algorithm_type: MeshAlgorithmType::Delaunay,
906                parameters: default_params.clone(),
907            },
908        );
909        self.mesh_algorithms.insert(
910            "advancing_front".to_string(),
911            MeshAlgorithm {
912                algorithm_id: "algo_advancing_front".to_string(),
913                algorithm_name: "Advancing Front".to_string(),
914                algorithm_type: MeshAlgorithmType::AdvancingFront,
915                parameters: default_params.clone(),
916            },
917        );
918        self.mesh_algorithms.insert(
919            "octree".to_string(),
920            MeshAlgorithm {
921                algorithm_id: "algo_octree".to_string(),
922                algorithm_name: "Octree Decomposition".to_string(),
923                algorithm_type: MeshAlgorithmType::Octree,
924                parameters: default_params.clone(),
925            },
926        );
927        self.mesh_algorithms.insert(
928            "structured".to_string(),
929            MeshAlgorithm {
930                algorithm_id: "algo_structured".to_string(),
931                algorithm_name: "Structured Grid".to_string(),
932                algorithm_type: MeshAlgorithmType::Custom("Structured".to_string()),
933                parameters: default_params.clone(),
934            },
935        );
936        self.mesh_algorithms.insert(
937            "unstructured".to_string(),
938            MeshAlgorithm {
939                algorithm_id: "algo_unstructured".to_string(),
940                algorithm_name: "Unstructured Mesh".to_string(),
941                algorithm_type: MeshAlgorithmType::Custom("Unstructured".to_string()),
942                parameters: default_params,
943            },
944        );
945
946        Ok(())
947    }
948
949    /// Look up a registered mesh type by name.
950    pub fn get_mesh_type(&self, name: &str) -> Option<&MeshType> {
951        self.mesh_types.get(name)
952    }
953
954    /// Look up a registered mesh algorithm by name.
955    pub fn get_algorithm(&self, name: &str) -> Option<&MeshAlgorithm> {
956        self.mesh_algorithms.get(name)
957    }
958
959    /// List the names of all registered mesh types.
960    pub fn list_mesh_types(&self) -> Vec<String> {
961        let mut names: Vec<String> = self.mesh_types.keys().cloned().collect();
962        names.sort();
963        names
964    }
965
966    /// List the names of all registered mesh algorithms.
967    pub fn list_algorithms(&self) -> Vec<String> {
968        let mut names: Vec<String> = self.mesh_algorithms.keys().cloned().collect();
969        names.sort();
970        names
971    }
972
973    /// Borrow the mesh-quality sub-component.
974    pub fn mesh_quality(&self) -> &MeshQuality {
975        &self.mesh_quality
976    }
977
978    /// Mutably borrow the mesh-quality sub-component.
979    pub fn mesh_quality_mut(&mut self) -> &mut MeshQuality {
980        &mut self.mesh_quality
981    }
982}
983
984impl MeshQuality {
985    /// Creates a `MeshQuality` with empty registries / default configuration.
986    pub fn new() -> Self {
987        Self {
988            quality_metrics: HashMap::new(),
989            quality_assessment: QualityAssessment::new(),
990        }
991    }
992
993    /// Register a quality metric under `metric.metric_name`.
994    pub fn add_metric(&mut self, metric: QualityMetric) {
995        self.quality_metrics
996            .insert(metric.metric_name.clone(), metric);
997    }
998
999    /// Look up a registered quality metric by name.
1000    pub fn get_metric(&self, name: &str) -> Option<&QualityMetric> {
1001        self.quality_metrics.get(name)
1002    }
1003
1004    /// List the names of all registered quality metrics.
1005    pub fn list_metrics(&self) -> Vec<String> {
1006        let mut names: Vec<String> = self.quality_metrics.keys().cloned().collect();
1007        names.sort();
1008        names
1009    }
1010
1011    /// Borrow the quality-assessment summary.
1012    pub fn quality_assessment(&self) -> &QualityAssessment {
1013        &self.quality_assessment
1014    }
1015}
1016
1017impl QualityAssessment {
1018    /// Creates a `QualityAssessment` with empty registries / default configuration.
1019    pub fn new() -> Self {
1020        Self {
1021            overall_quality: 0.95,
1022            quality_grade: QualityGrade::Excellent,
1023            recommendations: Vec::new(),
1024        }
1025    }
1026}
1027
1028impl ElementLibrary {
1029    /// Creates a `ElementLibrary` with empty registries / default configuration.
1030    pub fn new() -> Self {
1031        Self {
1032            elements: HashMap::new(),
1033            element_properties: HashMap::new(),
1034        }
1035    }
1036
1037    /// Populate the library with the standard finite-element types used in
1038    /// structural / mechanical FEA. Each element is registered with a default
1039    /// isotropic material (steel-like), unit geometry, and the DOF set appropriate
1040    /// to its kinematics.
1041    pub fn initialize(&mut self) -> Result<(), EngineeringError> {
1042        // Shared default properties (steel-like, unit section).
1043        let default_props = ElementProperties {
1044            material_properties: MaterialProperties {
1045                youngs_modulus: 200_000.0,
1046                poissons_ratio: 0.3,
1047                density: 7850.0,
1048                thermal_expansion: 1.2e-5,
1049                thermal_conductivity: 50.0,
1050                specific_heat: 500.0,
1051                yield_strength: 250.0,
1052                ultimate_strength: 400.0,
1053            },
1054            geometric_properties: GeometricProperties {
1055                area: 1.0,
1056                volume: 1.0,
1057                perimeter: 4.0,
1058                surface_area: 6.0,
1059            },
1060            section_properties: SectionProperties {
1061                moment_of_inertia: vec![1.0 / 12.0, 1.0 / 12.0, 1.0 / 12.0],
1062                torsional_constant: 1.0 / 12.0,
1063                section_modulus: vec![1.0 / 6.0, 1.0 / 6.0, 1.0 / 6.0],
1064                shear_center: vec![0.0, 0.0, 0.0],
1065            },
1066        };
1067
1068        // Helper: build `count` nodes each carrying `dofs` degrees of freedom.
1069        let make_nodes = |count: usize, dofs: &[DOF]| -> Vec<Node> {
1070            (0..count)
1071                .map(|i| Node {
1072                    node_id: format!("n{i}"),
1073                    coordinates: vec![i as f64, 0.0, 0.0],
1074                    degrees_of_freedom: dofs.to_vec(),
1075                    constraints: Vec::new(),
1076                })
1077                .collect()
1078        };
1079
1080        // truss_2node: 2 nodes, 2 DOF/node (UX, UY)
1081        let truss = Element {
1082            element_id: "truss_2node".to_string(),
1083            element_name: "2-Node Truss".to_string(),
1084            element_type: ElementType::Truss,
1085            nodes: make_nodes(2, &[DOF::UX, DOF::UY]),
1086            properties: default_props.clone(),
1087        };
1088        self.elements.insert("truss_2node".to_string(), truss);
1089        self.element_properties
1090            .insert("truss_2node".to_string(), default_props.clone());
1091
1092        // beam_2node: 2 nodes, 3 DOF/node (UX, UY, ROTZ)
1093        let beam = Element {
1094            element_id: "beam_2node".to_string(),
1095            element_name: "2-Node Beam".to_string(),
1096            element_type: ElementType::Beam,
1097            nodes: make_nodes(2, &[DOF::UX, DOF::UY, DOF::ROTZ]),
1098            properties: default_props.clone(),
1099        };
1100        self.elements.insert("beam_2node".to_string(), beam);
1101        self.element_properties
1102            .insert("beam_2node".to_string(), default_props.clone());
1103
1104        // quad_4node: quadrilateral shell, 4 nodes, 2 DOF/node (UX, UY)
1105        let quad = Element {
1106            element_id: "quad_4node".to_string(),
1107            element_name: "4-Node Quadrilateral Shell".to_string(),
1108            element_type: ElementType::Shell,
1109            nodes: make_nodes(4, &[DOF::UX, DOF::UY]),
1110            properties: default_props.clone(),
1111        };
1112        self.elements.insert("quad_4node".to_string(), quad);
1113        self.element_properties
1114            .insert("quad_4node".to_string(), default_props.clone());
1115
1116        // hex_8node: hexahedral solid, 8 nodes, 3 DOF/node (UX, UY, UZ)
1117        let hex = Element {
1118            element_id: "hex_8node".to_string(),
1119            element_name: "8-Node Hexahedral Solid".to_string(),
1120            element_type: ElementType::Hexahedron,
1121            nodes: make_nodes(8, &[DOF::UX, DOF::UY, DOF::UZ]),
1122            properties: default_props.clone(),
1123        };
1124        self.elements.insert("hex_8node".to_string(), hex);
1125        self.element_properties
1126            .insert("hex_8node".to_string(), default_props.clone());
1127
1128        // tet_4node: tetrahedral solid, 4 nodes, 3 DOF/node (UX, UY, UZ)
1129        let tet = Element {
1130            element_id: "tet_4node".to_string(),
1131            element_name: "4-Node Tetrahedral Solid".to_string(),
1132            element_type: ElementType::Tetrahedron,
1133            nodes: make_nodes(4, &[DOF::UX, DOF::UY, DOF::UZ]),
1134            properties: default_props.clone(),
1135        };
1136        self.elements.insert("tet_4node".to_string(), tet);
1137        self.element_properties
1138            .insert("tet_4node".to_string(), default_props.clone());
1139
1140        // shell_8node: shell element, 8 nodes, 6 DOF/node (UX, UY, UZ, ROTX, ROTY, ROTZ)
1141        let shell = Element {
1142            element_id: "shell_8node".to_string(),
1143            element_name: "8-Node Shell".to_string(),
1144            element_type: ElementType::Shell,
1145            nodes: make_nodes(
1146                8,
1147                &[DOF::UX, DOF::UY, DOF::UZ, DOF::ROTX, DOF::ROTY, DOF::ROTZ],
1148            ),
1149            properties: default_props.clone(),
1150        };
1151        self.elements.insert("shell_8node".to_string(), shell);
1152        self.element_properties
1153            .insert("shell_8node".to_string(), default_props);
1154
1155        Ok(())
1156    }
1157
1158    /// Look up a registered element definition by name.
1159    pub fn get_element(&self, name: &str) -> Option<&Element> {
1160        self.elements.get(name)
1161    }
1162
1163    /// Look up the properties registered for an element by name.
1164    pub fn get_properties(&self, name: &str) -> Option<&ElementProperties> {
1165        self.element_properties.get(name)
1166    }
1167
1168    /// List the names of all registered elements.
1169    pub fn list_elements(&self) -> Vec<String> {
1170        let mut names: Vec<String> = self.elements.keys().cloned().collect();
1171        names.sort();
1172        names
1173    }
1174}
1175
1176impl SolverEngine {
1177    /// Creates a `SolverEngine` with empty registries / default configuration.
1178    pub fn new() -> Self {
1179        Self {
1180            solvers: HashMap::new(),
1181            solver_parameters: SolverParameters::new(),
1182            convergence_criteria: ConvergenceCriteria::new(),
1183        }
1184    }
1185
1186    /// Readies `SolverEngine`; initializes any owned sub-engines (no-op for leaf structs).
1187    pub fn initialize(&mut self) -> Result<(), EngineeringError> {
1188        Ok(())
1189    }
1190
1191    /// Register a solver under `solver.solver_id`.
1192    pub fn add_solver(&mut self, solver: Solver) {
1193        self.solvers.insert(solver.solver_id.clone(), solver);
1194    }
1195
1196    /// Look up a registered solver by id.
1197    pub fn get_solver(&self, id: &str) -> Option<&Solver> {
1198        self.solvers.get(id)
1199    }
1200
1201    /// List the ids of all registered solvers.
1202    pub fn list_solvers(&self) -> Vec<String> {
1203        let mut ids: Vec<String> = self.solvers.keys().cloned().collect();
1204        ids.sort();
1205        ids
1206    }
1207
1208    /// Borrow the solver parameters.
1209    pub fn solver_parameters(&self) -> &SolverParameters {
1210        &self.solver_parameters
1211    }
1212
1213    /// Mutably borrow the solver parameters.
1214    pub fn solver_parameters_mut(&mut self) -> &mut SolverParameters {
1215        &mut self.solver_parameters
1216    }
1217
1218    /// Borrow the convergence criteria.
1219    pub fn convergence_criteria(&self) -> &ConvergenceCriteria {
1220        &self.convergence_criteria
1221    }
1222
1223    /// Mutably borrow the convergence criteria.
1224    pub fn convergence_criteria_mut(&mut self) -> &mut ConvergenceCriteria {
1225        &mut self.convergence_criteria
1226    }
1227}
1228
1229impl SolverParameters {
1230    /// Creates a `SolverParameters` with empty registries / default configuration.
1231    pub fn new() -> Self {
1232        Self {
1233            tolerance: 1e-6,
1234            max_iterations: 1000,
1235            convergence_acceleration: ConvergenceAcceleration::None,
1236        }
1237    }
1238}
1239
1240impl ConvergenceCriteria {
1241    /// Creates a `ConvergenceCriteria` with empty registries / default configuration.
1242    pub fn new() -> Self {
1243        Self {
1244            criteria_type: ConvergenceType::Residual,
1245            tolerance: 1e-6,
1246            max_iterations: 1000,
1247        }
1248    }
1249}
1250
1251impl PostProcessor {
1252    /// Creates a `PostProcessor` with empty registries / default configuration.
1253    pub fn new() -> Self {
1254        Self {
1255            result_extractors: HashMap::new(),
1256            visualization_engine: VisualizationEngine::new(),
1257            report_generator: ReportGenerator::new(),
1258        }
1259    }
1260
1261    /// Readies `PostProcessor`; initializes any owned sub-engines (no-op for leaf structs).
1262    pub fn initialize(&mut self) -> Result<(), EngineeringError> {
1263        self.visualization_engine.initialize()?;
1264        self.report_generator.initialize()?;
1265        Ok(())
1266    }
1267
1268    /// Register a result extractor under `extractor.extractor_id`.
1269    pub fn add_extractor(&mut self, extractor: ResultExtractor) {
1270        self.result_extractors
1271            .insert(extractor.extractor_id.clone(), extractor);
1272    }
1273
1274    /// Look up a registered result extractor by id.
1275    pub fn get_extractor(&self, id: &str) -> Option<&ResultExtractor> {
1276        self.result_extractors.get(id)
1277    }
1278
1279    /// List the ids of all registered result extractors.
1280    pub fn list_extractors(&self) -> Vec<String> {
1281        let mut ids: Vec<String> = self.result_extractors.keys().cloned().collect();
1282        ids.sort();
1283        ids
1284    }
1285}
1286
1287impl VisualizationEngine {
1288    /// Creates a `VisualizationEngine` with empty registries / default configuration.
1289    pub fn new() -> Self {
1290        Self {
1291            visualization_types: HashMap::new(),
1292            rendering_engine: RenderingEngine::new(),
1293        }
1294    }
1295
1296    /// Readies `VisualizationEngine`; initializes any owned sub-engines (no-op for leaf structs).
1297    pub fn initialize(&mut self) -> Result<(), EngineeringError> {
1298        Ok(())
1299    }
1300
1301    /// Register a visualization type under `name`.
1302    pub fn add_visualization_type(&mut self, name: impl Into<String>, vtype: VisualizationType) {
1303        self.visualization_types.insert(name.into(), vtype);
1304    }
1305
1306    /// Look up a registered visualization type by name.
1307    pub fn get_visualization_type(&self, name: &str) -> Option<&VisualizationType> {
1308        self.visualization_types.get(name)
1309    }
1310
1311    /// List the names of all registered visualization types.
1312    pub fn list_visualization_types(&self) -> Vec<String> {
1313        let mut names: Vec<String> = self.visualization_types.keys().cloned().collect();
1314        names.sort();
1315        names
1316    }
1317
1318    /// Borrow the rendering engine.
1319    pub fn rendering_engine(&self) -> &RenderingEngine {
1320        &self.rendering_engine
1321    }
1322
1323    /// Mutably borrow the rendering engine.
1324    pub fn rendering_engine_mut(&mut self) -> &mut RenderingEngine {
1325        &mut self.rendering_engine
1326    }
1327}
1328
1329impl RenderingEngine {
1330    /// Creates a `RenderingEngine` with empty registries / default configuration.
1331    pub fn new() -> Self {
1332        Self {
1333            engine_type: RenderingEngineType::OpenGL,
1334            rendering_options: RenderingOptions::new(),
1335        }
1336    }
1337}
1338
1339impl RenderingOptions {
1340    /// Creates a `RenderingOptions` with empty registries / default configuration.
1341    pub fn new() -> Self {
1342        Self {
1343            color_map: "jet".to_string(),
1344            scale_factor: 1.0,
1345            line_width: 1.0,
1346            transparency: 0.0,
1347        }
1348    }
1349}
1350
1351impl ReportGenerator {
1352    /// Creates a `ReportGenerator` with empty registries / default configuration.
1353    pub fn new() -> Self {
1354        Self {
1355            report_templates: HashMap::new(),
1356            export_formats: vec![ExportFormat::PDF, ExportFormat::HTML],
1357        }
1358    }
1359
1360    /// Readies `ReportGenerator`; initializes any owned sub-engines (no-op for leaf structs).
1361    pub fn initialize(&mut self) -> Result<(), EngineeringError> {
1362        Ok(())
1363    }
1364
1365    /// Register a report template under `template.template_id`.
1366    pub fn add_template(&mut self, template: ReportTemplate) {
1367        self.report_templates
1368            .insert(template.template_id.clone(), template);
1369    }
1370
1371    /// Look up a registered report template by id.
1372    pub fn get_template(&self, id: &str) -> Option<&ReportTemplate> {
1373        self.report_templates.get(id)
1374    }
1375
1376    /// List the ids of all registered report templates.
1377    pub fn list_templates(&self) -> Vec<String> {
1378        let mut ids: Vec<String> = self.report_templates.keys().cloned().collect();
1379        ids.sort();
1380        ids
1381    }
1382
1383    /// Borrow the supported export formats.
1384    pub fn export_formats(&self) -> &[ExportFormat] {
1385        &self.export_formats
1386    }
1387
1388    /// Add a supported export format.
1389    pub fn add_export_format(&mut self, format: ExportFormat) {
1390        if !self.export_formats.contains(&format) {
1391            self.export_formats.push(format);
1392        }
1393    }
1394}