Skip to main content

qualia_core_db/specialized_libs/engineering_analysis/
mechanical.rs

1use super::*;
2
3/// Mechanical analyzer for mechanical engineering analysis
4pub struct MechanicalAnalyzer {
5    kinematics: Kinematics,
6    dynamics: Dynamics,
7    mechanism_analysis: MechanismAnalysis,
8    machine_design: MachineDesign,
9    /// Phase 2 physics-simulation library for coupled mechanical dynamics.
10    physics_simulation: Option<Arc<Mutex<PhysicsSimulationLibrary>>>,
11}
12
13/// Results of a kinematic time-history analysis (constant acceleration).
14/// Positions, velocities and accelerations are evaluated at each requested time
15/// step using the standard SUVAT equations.
16#[derive(Debug, Clone, PartialEq)]
17pub struct KinematicsResults {
18    /// Position x(t) = x₀ + v₀·t + ½·a·t² at each time step.
19    pub positions: Vec<f64>,
20    /// Velocity v(t) = v₀ + a·t at each time step.
21    pub velocities: Vec<f64>,
22    /// Acceleration a(t) = a (constant) at each time step.
23    pub accelerations: Vec<f64>,
24    /// The time steps the analysis was evaluated at.
25    pub time_steps: Vec<f64>,
26}
27
28/// Results of a dynamics time-history analysis (Newton's second law, F = m·a).
29/// Energy is reported in the constant-applied-force potential convention so that
30/// total mechanical energy is conserved: `PE = −F·x` and
31/// `KE + PE = ½·m·v₀²` (constant).
32#[derive(Debug, Clone, PartialEq)]
33pub struct DynamicsResults {
34    /// Position x(t) = ½·a·t² + v₀·t at each time step.
35    pub positions: Vec<f64>,
36    /// Velocity v(t) = v₀ + a·t at each time step.
37    pub velocities: Vec<f64>,
38    /// Acceleration a = F/m (constant) at each time step.
39    pub accelerations: Vec<f64>,
40    /// Kinetic energy ½·m·v² at the final time step (J).
41    pub kinetic_energy: f64,
42    /// Potential energy −F·x at the final time step (J), in the constant-force
43    /// field convention so that KE + PE is conserved.
44    pub potential_energy: f64,
45    /// Total mechanical energy = KE + PE (J), conserved across the history.
46    pub total_energy: f64,
47    /// The time steps the analysis was evaluated at.
48    pub time_steps: Vec<f64>,
49}
50
51/// Kinematics
52pub struct Kinematics {
53    position_analysis: PositionAnalysis,
54    velocity_analysis: VelocityAnalysis,
55    acceleration_analysis: AccelerationAnalysis,
56}
57
58/// Position analysis
59#[derive(Debug, Clone)]
60pub struct PositionAnalysis {
61    pub mechanism_type: MechanismType,
62    pub joint_coordinates: Vec<f64>,
63    pub link_lengths: Vec<f64>,
64}
65
66/// Mechanism types
67#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
68pub enum MechanismType {
69    FourBar,
70    SliderCrank,
71    CamFollower,
72    GearTrain,
73    Custom(String),
74}
75
76/// Velocity analysis
77#[derive(Debug, Clone)]
78pub struct VelocityAnalysis {
79    pub angular_velocities: Vec<f64>,
80    pub linear_velocities: Vec<f64>,
81    pub velocity_ratios: Vec<f64>,
82}
83
84/// Acceleration analysis
85#[derive(Debug, Clone)]
86pub struct AccelerationAnalysis {
87    pub angular_accelerations: Vec<f64>,
88    pub linear_accelerations: Vec<f64>,
89    pub jerk: Vec<f64>,
90}
91
92/// Dynamics
93pub struct Dynamics {
94    force_analysis: ForceAnalysis,
95    inertia_analysis: InertiaAnalysis,
96    energy_analysis: EnergyAnalysis,
97}
98
99/// Force analysis
100#[derive(Debug, Clone)]
101pub struct ForceAnalysis {
102    pub applied_forces: Vec<f64>,
103    pub reaction_forces: Vec<f64>,
104    pub internal_forces: Vec<f64>,
105}
106
107/// Inertia analysis
108#[derive(Debug, Clone)]
109pub struct InertiaAnalysis {
110    pub masses: Vec<f64>,
111    pub moments_of_inertia: Vec<f64>,
112    pub products_of_inertia: Vec<f64>,
113}
114
115/// Energy analysis
116#[derive(Debug, Clone)]
117pub struct EnergyAnalysis {
118    pub kinetic_energy: f64,
119    pub potential_energy: f64,
120    pub total_energy: f64,
121    pub power: f64,
122}
123
124/// Mechanism analysis
125pub struct MechanismAnalysis {
126    synthesis: MechanismSynthesis,
127    analysis: MechanismAnalysisEngine,
128    optimization: MechanismOptimization,
129}
130
131/// Mechanism synthesis
132#[derive(Debug, Clone)]
133pub struct MechanismSynthesis {
134    pub synthesis_type: SynthesisType,
135    pub design_parameters: Vec<f64>,
136    pub constraints: Vec<Constraint>,
137}
138
139/// Synthesis types
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141pub enum SynthesisType {
142    FunctionGeneration,
143    PathGeneration,
144    MotionGeneration,
145}
146
147/// Mechanism analysis engine
148#[derive(Debug, Clone)]
149pub struct MechanismAnalysisEngine {
150    pub analysis_type: AnalysisType,
151    pub analysis_method: AnalysisMethod,
152}
153
154/// Analysis methods
155#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
156pub enum AnalysisMethod {
157    Graphical,
158    Analytical,
159    Numerical,
160}
161
162/// Mechanism optimization
163#[derive(Debug, Clone)]
164pub struct MechanismOptimization {
165    pub optimization_algorithm: OptimizationAlgorithm,
166    pub objective_function: ObjectiveFunction,
167    pub design_variables: Vec<DesignVariable>,
168}
169
170/// Optimization algorithms
171#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
172pub enum OptimizationAlgorithm {
173    GeneticAlgorithm,
174    ParticleSwarm,
175    SimulatedAnnealing,
176    GradientDescent,
177}
178
179/// Objective functions
180#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
181pub enum ObjectiveFunction {
182    MinimizeError,
183    MaximizeEfficiency,
184    MinimizeWeight,
185    MaximizeStiffness,
186}
187
188/// Design variables
189#[derive(Debug, Clone)]
190pub struct DesignVariable {
191    pub variable_name: String,
192    pub variable_type: VariableType,
193    pub bounds: (f64, f64),
194}
195
196/// Variable types
197#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
198pub enum VariableType {
199    Length,
200    Angle,
201    Mass,
202    Stiffness,
203}
204
205/// Machine design
206pub struct MachineDesign {
207    component_design: ComponentDesign,
208    assembly_design: AssemblyDesign,
209    tolerance_analysis: ToleranceAnalysis,
210}
211
212/// Component design
213#[derive(Debug, Clone)]
214pub struct ComponentDesign {
215    pub component_type: ComponentType,
216    pub design_parameters: HashMap<String, f64>,
217    pub material_selection: MaterialSelection,
218}
219
220/// Component types
221#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
222pub enum ComponentType {
223    Shaft,
224    Bearing,
225    Gear,
226    Spring,
227    Fastener,
228    Custom(String),
229}
230
231/// Material selection
232#[derive(Debug, Clone)]
233pub struct MaterialSelection {
234    pub material_id: String,
235    pub material_name: String,
236    pub selection_criteria: Vec<SelectionCriterion>,
237}
238
239/// Selection criteria
240#[derive(Debug, Clone)]
241pub struct SelectionCriterion {
242    pub criterion_name: String,
243    pub criterion_weight: f64,
244    pub required_value: f64,
245}
246
247/// Assembly design
248#[derive(Debug, Clone)]
249pub struct AssemblyDesign {
250    pub assembly_type: AssemblyType,
251    pub components: Vec<Component>,
252    pub assembly_constraints: Vec<AssemblyConstraint>,
253}
254
255/// Assembly types
256#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
257pub enum AssemblyType {
258    Fixed,
259    Floating,
260    Kinematic,
261    Overconstrained,
262}
263
264/// Components
265#[derive(Debug, Clone)]
266pub struct Component {
267    pub component_id: String,
268    pub component_name: String,
269    pub component_type: ComponentType,
270    pub position: Vec<f64>,
271    pub orientation: Vec<f64>,
272}
273
274/// Assembly constraints
275#[derive(Debug, Clone)]
276pub struct AssemblyConstraint {
277    pub constraint_id: String,
278    pub constraint_type: ConstraintType,
279    pub constraint_parameters: HashMap<String, f64>,
280}
281
282/// Tolerance analysis
283pub struct ToleranceAnalysis {
284    pub tolerance_stackup: ToleranceStackup,
285    pub statistical_tolerance: StatisticalTolerance,
286    pub geometric_tolerance: GeometricTolerance,
287}
288
289/// Tolerance stackup
290#[derive(Debug, Clone)]
291pub struct ToleranceStackup {
292    pub tolerance_type: ToleranceType,
293    pub tolerance_values: Vec<f64>,
294    pub stackup_result: f64,
295}
296
297/// Tolerance types
298#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
299pub enum ToleranceType {
300    WorstCase,
301    Statistical,
302    RootSumSquare,
303}
304
305/// Statistical tolerance
306#[derive(Debug, Clone)]
307pub struct StatisticalTolerance {
308    pub distribution_type: DistributionType,
309    pub mean: f64,
310    pub standard_deviation: f64,
311}
312
313/// Distribution types
314#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
315pub enum DistributionType {
316    Normal,
317    Uniform,
318    Triangular,
319}
320
321/// Geometric tolerance
322#[derive(Debug, Clone)]
323pub struct GeometricTolerance {
324    pub tolerance_type: GeometricToleranceType,
325    pub tolerance_value: f64,
326    pub reference_features: Vec<String>,
327}
328
329/// Geometric tolerance types
330#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
331pub enum GeometricToleranceType {
332    Flatness,
333    Straightness,
334    Circularity,
335    Cylindricity,
336    Perpendicularity,
337    Angularity,
338    Parallelism,
339    Position,
340    Concentricity,
341    Symmetry,
342}
343impl MechanicalAnalyzer {
344    /// Construct a `MechanicalAnalyzer` with default field values.
345    pub fn new() -> Self {
346        Self {
347            kinematics: Kinematics::new(),
348            dynamics: Dynamics::new(),
349            mechanism_analysis: MechanismAnalysis::new(),
350            machine_design: MachineDesign::new(),
351            physics_simulation: None,
352        }
353    }
354
355    /// Attach the Phase 2 physics-simulation library for coupled dynamics.
356    pub fn attach_physics_simulation(&mut self, lib: Option<Arc<Mutex<PhysicsSimulationLibrary>>>) {
357        self.physics_simulation = lib;
358    }
359
360    /// Initialize `MechanicalAnalyzer`; `Ok` when ready.
361    pub fn initialize(&mut self) -> Result<(), EngineeringError> {
362        self.kinematics.initialize()?;
363        self.dynamics.initialize()?;
364        self.mechanism_analysis.initialize()?;
365        self.machine_design.initialize()?;
366        Ok(())
367    }
368
369    /// Structural validation: rejects models with no dimensions.
370    pub fn validate_model(&self, model: &EngineeringModel) -> Result<(), EngineeringError> {
371        if model.geometry.dimensions.is_empty() {
372            return Err(EngineeringError::ValidationError(
373                "Model must have dimensions".to_string(),
374            ));
375        }
376        Ok(())
377    }
378
379    /// Performs mechanical/structural analysis across the model.
380    ///
381    /// Delegates to [`StructuralAnalyzer::analyze`] which executes real first-principles
382    /// strength-of-materials and finite-element solves (`LinearStatic`, `Buckling`,
383    /// `NonlinearStatic`, `LinearDynamic`, `NonlinearDynamic`).
384    pub fn analyze(
385        &mut self,
386        model: &EngineeringModel,
387        analysis_type: AnalysisType,
388    ) -> Result<AnalysisResults, EngineeringError> {
389        self.validate_model(model)?;
390        let mut structural = StructuralAnalyzer::new();
391        structural.analyze(model, analysis_type)
392    }
393
394    /// Real finite-element linear-static solve of an explicit [`fem::FeModel`].
395    pub fn fem_static(
396        &self,
397        model: &fem::FeModel,
398    ) -> Result<fem::FeStaticResult, EngineeringError> {
399        fem::solve_static(model)
400    }
401
402    /// Basic kinematic time-history analysis with constant acceleration.
403    ///
404    /// For each time step `t`:
405    /// - position(t) = x₀ + v₀·t + ½·a·t²
406    /// - velocity(t) = v₀ + a·t
407    /// - acceleration(t) = a (constant)
408    pub fn analyze_kinematics(
409        &mut self,
410        initial_position: f64,
411        initial_velocity: f64,
412        acceleration: f64,
413        time_steps: &[f64],
414    ) -> Result<KinematicsResults, EngineeringError> {
415        if time_steps.is_empty() {
416            return Err(EngineeringError::InsufficientData(
417                "time_steps must contain at least one value".to_string(),
418            ));
419        }
420
421        let mut positions = Vec::with_capacity(time_steps.len());
422        let mut velocities = Vec::with_capacity(time_steps.len());
423        let mut accelerations = Vec::with_capacity(time_steps.len());
424
425        for &t in time_steps {
426            positions.push(initial_position + initial_velocity * t + 0.5 * acceleration * t * t);
427            velocities.push(initial_velocity + acceleration * t);
428            accelerations.push(acceleration);
429        }
430
431        Ok(KinematicsResults {
432            positions,
433            velocities,
434            accelerations,
435            time_steps: time_steps.to_vec(),
436        })
437    }
438
439    /// Dynamics time-history analysis from Newton's second law (F = m·a).
440    ///
441    /// - acceleration a = force / mass (constant)
442    /// - velocity(t) = v₀ + a·t
443    /// - position(t) = ½·a·t² + v₀·t
444    ///
445    /// Energy is reported in the constant-applied-force potential convention
446    /// (`PE = −F·x`) so that the total mechanical energy `KE + PE = ½·m·v₀²` is
447    /// conserved across the whole history (verifiable in tests).
448    pub fn analyze_dynamics(
449        &mut self,
450        mass: f64,
451        force: f64,
452        initial_velocity: f64,
453        time_steps: &[f64],
454    ) -> Result<DynamicsResults, EngineeringError> {
455        if mass <= 0.0 {
456            return Err(EngineeringError::ValidationError(
457                "mass must be positive".to_string(),
458            ));
459        }
460        if time_steps.is_empty() {
461            return Err(EngineeringError::InsufficientData(
462                "time_steps must contain at least one value".to_string(),
463            ));
464        }
465
466        let acceleration = force / mass;
467        let mut positions = Vec::with_capacity(time_steps.len());
468        let mut velocities = Vec::with_capacity(time_steps.len());
469        let mut accelerations = Vec::with_capacity(time_steps.len());
470
471        for &t in time_steps {
472            positions.push(0.5 * acceleration * t * t + initial_velocity * t);
473            velocities.push(initial_velocity + acceleration * t);
474            accelerations.push(acceleration);
475        }
476
477        // Final-step energies. With PE = −F·x, KE + PE = ½·m·v₀² (conserved).
478        let v_final = *velocities.last().unwrap();
479        let x_final = *positions.last().unwrap();
480        let kinetic_energy = 0.5 * mass * v_final * v_final;
481        let potential_energy = -force * x_final;
482        let total_energy = kinetic_energy + potential_energy;
483
484        Ok(DynamicsResults {
485            positions,
486            velocities,
487            accelerations,
488            kinetic_energy,
489            potential_energy,
490            total_energy,
491            time_steps: time_steps.to_vec(),
492        })
493    }
494}
495
496impl Kinematics {
497    /// Construct a `Kinematics` with default field values.
498    pub fn new() -> Self {
499        Self {
500            position_analysis: PositionAnalysis::new(),
501            velocity_analysis: VelocityAnalysis::new(),
502            acceleration_analysis: AccelerationAnalysis::new(),
503        }
504    }
505
506    /// Initialize `Kinematics`; `Ok` when ready.
507    pub fn initialize(&mut self) -> Result<(), EngineeringError> {
508        Ok(())
509    }
510
511    /// Borrow the position-analysis sub-component.
512    pub fn position_analysis(&self) -> &PositionAnalysis {
513        &self.position_analysis
514    }
515
516    /// Mutably borrow the position-analysis sub-component.
517    pub fn position_analysis_mut(&mut self) -> &mut PositionAnalysis {
518        &mut self.position_analysis
519    }
520
521    /// Borrow the velocity-analysis sub-component.
522    pub fn velocity_analysis(&self) -> &VelocityAnalysis {
523        &self.velocity_analysis
524    }
525
526    /// Mutably borrow the velocity-analysis sub-component.
527    pub fn velocity_analysis_mut(&mut self) -> &mut VelocityAnalysis {
528        &mut self.velocity_analysis
529    }
530
531    /// Borrow the acceleration-analysis sub-component.
532    pub fn acceleration_analysis(&self) -> &AccelerationAnalysis {
533        &self.acceleration_analysis
534    }
535
536    /// Mutably borrow the acceleration-analysis sub-component.
537    pub fn acceleration_analysis_mut(&mut self) -> &mut AccelerationAnalysis {
538        &mut self.acceleration_analysis
539    }
540}
541
542impl PositionAnalysis {
543    /// Construct a `PositionAnalysis` with default field values.
544    pub fn new() -> Self {
545        Self {
546            mechanism_type: MechanismType::FourBar,
547            joint_coordinates: Vec::new(),
548            link_lengths: Vec::new(),
549        }
550    }
551}
552
553impl VelocityAnalysis {
554    /// Construct a `VelocityAnalysis` with default field values.
555    pub fn new() -> Self {
556        Self {
557            angular_velocities: Vec::new(),
558            linear_velocities: Vec::new(),
559            velocity_ratios: Vec::new(),
560        }
561    }
562}
563
564impl AccelerationAnalysis {
565    /// Construct a `AccelerationAnalysis` with default field values.
566    pub fn new() -> Self {
567        Self {
568            angular_accelerations: Vec::new(),
569            linear_accelerations: Vec::new(),
570            jerk: Vec::new(),
571        }
572    }
573}
574
575impl Dynamics {
576    /// Construct a `Dynamics` with default field values.
577    pub fn new() -> Self {
578        Self {
579            force_analysis: ForceAnalysis::new(),
580            inertia_analysis: InertiaAnalysis::new(),
581            energy_analysis: EnergyAnalysis::new(),
582        }
583    }
584
585    /// Initialize `Dynamics`; `Ok` when ready.
586    pub fn initialize(&mut self) -> Result<(), EngineeringError> {
587        Ok(())
588    }
589
590    /// Borrow the force-analysis sub-component.
591    pub fn force_analysis(&self) -> &ForceAnalysis {
592        &self.force_analysis
593    }
594
595    /// Mutably borrow the force-analysis sub-component.
596    pub fn force_analysis_mut(&mut self) -> &mut ForceAnalysis {
597        &mut self.force_analysis
598    }
599
600    /// Borrow the inertia-analysis sub-component.
601    pub fn inertia_analysis(&self) -> &InertiaAnalysis {
602        &self.inertia_analysis
603    }
604
605    /// Mutably borrow the inertia-analysis sub-component.
606    pub fn inertia_analysis_mut(&mut self) -> &mut InertiaAnalysis {
607        &mut self.inertia_analysis
608    }
609
610    /// Borrow the energy-analysis sub-component.
611    pub fn energy_analysis(&self) -> &EnergyAnalysis {
612        &self.energy_analysis
613    }
614
615    /// Mutably borrow the energy-analysis sub-component.
616    pub fn energy_analysis_mut(&mut self) -> &mut EnergyAnalysis {
617        &mut self.energy_analysis
618    }
619}
620
621impl ForceAnalysis {
622    /// Construct a `ForceAnalysis` with default field values.
623    pub fn new() -> Self {
624        Self {
625            applied_forces: Vec::new(),
626            reaction_forces: Vec::new(),
627            internal_forces: Vec::new(),
628        }
629    }
630}
631
632impl InertiaAnalysis {
633    /// Construct a `InertiaAnalysis` with default field values.
634    pub fn new() -> Self {
635        Self {
636            masses: Vec::new(),
637            moments_of_inertia: Vec::new(),
638            products_of_inertia: Vec::new(),
639        }
640    }
641}
642
643impl EnergyAnalysis {
644    /// Construct a `EnergyAnalysis` with default field values.
645    pub fn new() -> Self {
646        Self {
647            kinetic_energy: 0.0,
648            potential_energy: 0.0,
649            total_energy: 0.0,
650            power: 0.0,
651        }
652    }
653}
654
655impl MechanismAnalysis {
656    /// Construct a `MechanismAnalysis` with default field values.
657    pub fn new() -> Self {
658        Self {
659            synthesis: MechanismSynthesis::new(),
660            analysis: MechanismAnalysisEngine::new(),
661            optimization: MechanismOptimization::new(),
662        }
663    }
664
665    /// Initialize `MechanismAnalysis`; `Ok` when ready.
666    pub fn initialize(&mut self) -> Result<(), EngineeringError> {
667        Ok(())
668    }
669
670    /// Borrow the mechanism-synthesis sub-component.
671    pub fn synthesis(&self) -> &MechanismSynthesis {
672        &self.synthesis
673    }
674
675    /// Mutably borrow the mechanism-synthesis sub-component.
676    pub fn synthesis_mut(&mut self) -> &mut MechanismSynthesis {
677        &mut self.synthesis
678    }
679
680    /// Borrow the mechanism-analysis-engine sub-component.
681    pub fn analysis(&self) -> &MechanismAnalysisEngine {
682        &self.analysis
683    }
684
685    /// Mutably borrow the mechanism-analysis-engine sub-component.
686    pub fn analysis_mut(&mut self) -> &mut MechanismAnalysisEngine {
687        &mut self.analysis
688    }
689
690    /// Borrow the mechanism-optimization sub-component.
691    pub fn optimization(&self) -> &MechanismOptimization {
692        &self.optimization
693    }
694
695    /// Mutably borrow the mechanism-optimization sub-component.
696    pub fn optimization_mut(&mut self) -> &mut MechanismOptimization {
697        &mut self.optimization
698    }
699}
700
701impl MechanismSynthesis {
702    /// Construct a `MechanismSynthesis` with default field values.
703    pub fn new() -> Self {
704        Self {
705            synthesis_type: SynthesisType::FunctionGeneration,
706            design_parameters: Vec::new(),
707            constraints: Vec::new(),
708        }
709    }
710}
711
712impl MechanismAnalysisEngine {
713    /// Construct a `MechanismAnalysisEngine` with default field values.
714    pub fn new() -> Self {
715        Self {
716            analysis_type: AnalysisType::LinearStatic,
717            analysis_method: AnalysisMethod::Numerical,
718        }
719    }
720}
721
722impl MechanismOptimization {
723    /// Construct a `MechanismOptimization` with default field values.
724    pub fn new() -> Self {
725        Self {
726            optimization_algorithm: OptimizationAlgorithm::GeneticAlgorithm,
727            objective_function: ObjectiveFunction::MinimizeError,
728            design_variables: Vec::new(),
729        }
730    }
731}
732
733impl DesignVariable {
734    /// Construct a `DesignVariable` with default field values.
735    pub fn new() -> Self {
736        Self {
737            variable_name: "length".to_string(),
738            variable_type: VariableType::Length,
739            bounds: (0.1, 10.0),
740        }
741    }
742}
743
744impl MachineDesign {
745    /// Construct a `MachineDesign` with default field values.
746    pub fn new() -> Self {
747        Self {
748            component_design: ComponentDesign::new(),
749            assembly_design: AssemblyDesign::new(),
750            tolerance_analysis: ToleranceAnalysis::new(),
751        }
752    }
753
754    /// Initialize `MachineDesign`; `Ok` when ready.
755    pub fn initialize(&mut self) -> Result<(), EngineeringError> {
756        Ok(())
757    }
758
759    /// Borrow the component-design sub-component.
760    pub fn component_design(&self) -> &ComponentDesign {
761        &self.component_design
762    }
763
764    /// Mutably borrow the component-design sub-component.
765    pub fn component_design_mut(&mut self) -> &mut ComponentDesign {
766        &mut self.component_design
767    }
768
769    /// Borrow the assembly-design sub-component.
770    pub fn assembly_design(&self) -> &AssemblyDesign {
771        &self.assembly_design
772    }
773
774    /// Mutably borrow the assembly-design sub-component.
775    pub fn assembly_design_mut(&mut self) -> &mut AssemblyDesign {
776        &mut self.assembly_design
777    }
778
779    /// Borrow the tolerance-analysis sub-component.
780    pub fn tolerance_analysis(&self) -> &ToleranceAnalysis {
781        &self.tolerance_analysis
782    }
783
784    /// Mutably borrow the tolerance-analysis sub-component.
785    pub fn tolerance_analysis_mut(&mut self) -> &mut ToleranceAnalysis {
786        &mut self.tolerance_analysis
787    }
788}
789
790impl ComponentDesign {
791    /// Construct a `ComponentDesign` with default field values.
792    pub fn new() -> Self {
793        Self {
794            component_type: ComponentType::Shaft,
795            design_parameters: HashMap::new(),
796            material_selection: MaterialSelection::new(),
797        }
798    }
799}
800
801impl MaterialSelection {
802    /// Construct a `MaterialSelection` with default field values.
803    pub fn new() -> Self {
804        Self {
805            material_id: "steel_1".to_string(),
806            material_name: "Steel".to_string(),
807            selection_criteria: Vec::new(),
808        }
809    }
810}
811
812impl AssemblyDesign {
813    /// Construct a `AssemblyDesign` with default field values.
814    pub fn new() -> Self {
815        Self {
816            assembly_type: AssemblyType::Fixed,
817            components: Vec::new(),
818            assembly_constraints: Vec::new(),
819        }
820    }
821}
822
823impl Component {
824    /// Construct a `Component` with default field values.
825    pub fn new() -> Self {
826        Self {
827            component_id: "comp_1".to_string(),
828            component_name: "Component".to_string(),
829            component_type: ComponentType::Shaft,
830            position: vec![0.0; 3],
831            orientation: vec![0.0; 3],
832        }
833    }
834}
835
836impl AssemblyConstraint {
837    /// Construct a `AssemblyConstraint` with default field values.
838    pub fn new() -> Self {
839        Self {
840            constraint_id: "constraint_1".to_string(),
841            constraint_type: ConstraintType::Fixed,
842            constraint_parameters: HashMap::new(),
843        }
844    }
845}
846
847impl ToleranceAnalysis {
848    /// Construct a `ToleranceAnalysis` with default field values.
849    pub fn new() -> Self {
850        Self {
851            tolerance_stackup: ToleranceStackup::new(),
852            statistical_tolerance: StatisticalTolerance::new(),
853            geometric_tolerance: GeometricTolerance::new(),
854        }
855    }
856
857    /// Initialize `ToleranceAnalysis`; `Ok` when ready.
858    pub fn initialize(&mut self) -> Result<(), EngineeringError> {
859        Ok(())
860    }
861}
862
863impl ToleranceStackup {
864    /// Construct a `ToleranceStackup` with default field values.
865    pub fn new() -> Self {
866        Self {
867            tolerance_type: ToleranceType::WorstCase,
868            tolerance_values: Vec::new(),
869            stackup_result: 0.0,
870        }
871    }
872}
873
874impl StatisticalTolerance {
875    /// Construct a `StatisticalTolerance` with default field values.
876    pub fn new() -> Self {
877        Self {
878            distribution_type: DistributionType::Normal,
879            mean: 0.0,
880            standard_deviation: 0.1,
881        }
882    }
883}
884
885impl GeometricTolerance {
886    /// Construct a `GeometricTolerance` with default field values.
887    pub fn new() -> Self {
888        Self {
889            tolerance_type: GeometricToleranceType::Flatness,
890            tolerance_value: 0.01,
891            reference_features: Vec::new(),
892        }
893    }
894}
895
896#[cfg(test)]
897mod tests {
898    use super::*;
899
900    fn test_model(load: f64) -> EngineeringModel {
901        let mut model = EngineeringModel::new();
902        model.geometry.dimensions = vec![0.1, 0.1, 2.0];
903        model.materials.insert("steel".to_string(), Material::new());
904        model.loads.push(Load {
905            load_id: "F".to_string(),
906            load_type: LoadType::Force,
907            load_magnitude: load,
908            load_direction: vec![1.0, 0.0, 0.0],
909            application_point: vec![0.0, 0.0, 0.0],
910        });
911        model
912    }
913
914    #[test]
915    fn mechanical_analyzer_linear_static_real_solve() {
916        let mut analyzer = MechanicalAnalyzer::new();
917        analyzer.initialize().unwrap();
918        let res = analyzer.analyze(&test_model(200.0), AnalysisType::LinearStatic).unwrap();
919        // u = F*L / (A*E) = 200 * 2 / (0.01 * 200000) = 0.2
920        assert!((res.displacement_field[0] - 0.2).abs() < 1e-9);
921        assert!(res.safety_factor > 0.0);
922    }
923
924    #[test]
925    fn mechanical_analyzer_buckling_real_solve() {
926        let mut analyzer = MechanicalAnalyzer::new();
927        analyzer.initialize().unwrap();
928        let res = analyzer.analyze(&test_model(200.0), AnalysisType::Buckling).unwrap();
929        assert!(res.safety_factor > 0.0);
930    }
931}