1use super::*;
2
3pub struct MechanicalAnalyzer {
5 kinematics: Kinematics,
6 dynamics: Dynamics,
7 mechanism_analysis: MechanismAnalysis,
8 machine_design: MachineDesign,
9 physics_simulation: Option<Arc<Mutex<PhysicsSimulationLibrary>>>,
11}
12
13#[derive(Debug, Clone, PartialEq)]
17pub struct KinematicsResults {
18 pub positions: Vec<f64>,
20 pub velocities: Vec<f64>,
22 pub accelerations: Vec<f64>,
24 pub time_steps: Vec<f64>,
26}
27
28#[derive(Debug, Clone, PartialEq)]
33pub struct DynamicsResults {
34 pub positions: Vec<f64>,
36 pub velocities: Vec<f64>,
38 pub accelerations: Vec<f64>,
40 pub kinetic_energy: f64,
42 pub potential_energy: f64,
45 pub total_energy: f64,
47 pub time_steps: Vec<f64>,
49}
50
51pub struct Kinematics {
53 position_analysis: PositionAnalysis,
54 velocity_analysis: VelocityAnalysis,
55 acceleration_analysis: AccelerationAnalysis,
56}
57
58#[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
68pub enum MechanismType {
69 FourBar,
70 SliderCrank,
71 CamFollower,
72 GearTrain,
73 Custom(String),
74}
75
76#[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#[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
92pub struct Dynamics {
94 force_analysis: ForceAnalysis,
95 inertia_analysis: InertiaAnalysis,
96 energy_analysis: EnergyAnalysis,
97}
98
99#[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#[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#[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
124pub struct MechanismAnalysis {
126 synthesis: MechanismSynthesis,
127 analysis: MechanismAnalysisEngine,
128 optimization: MechanismOptimization,
129}
130
131#[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141pub enum SynthesisType {
142 FunctionGeneration,
143 PathGeneration,
144 MotionGeneration,
145}
146
147#[derive(Debug, Clone)]
149pub struct MechanismAnalysisEngine {
150 pub analysis_type: AnalysisType,
151 pub analysis_method: AnalysisMethod,
152}
153
154#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
156pub enum AnalysisMethod {
157 Graphical,
158 Analytical,
159 Numerical,
160}
161
162#[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
172pub enum OptimizationAlgorithm {
173 GeneticAlgorithm,
174 ParticleSwarm,
175 SimulatedAnnealing,
176 GradientDescent,
177}
178
179#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
181pub enum ObjectiveFunction {
182 MinimizeError,
183 MaximizeEfficiency,
184 MinimizeWeight,
185 MaximizeStiffness,
186}
187
188#[derive(Debug, Clone)]
190pub struct DesignVariable {
191 pub variable_name: String,
192 pub variable_type: VariableType,
193 pub bounds: (f64, f64),
194}
195
196#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
198pub enum VariableType {
199 Length,
200 Angle,
201 Mass,
202 Stiffness,
203}
204
205pub struct MachineDesign {
207 component_design: ComponentDesign,
208 assembly_design: AssemblyDesign,
209 tolerance_analysis: ToleranceAnalysis,
210}
211
212#[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#[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#[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#[derive(Debug, Clone)]
241pub struct SelectionCriterion {
242 pub criterion_name: String,
243 pub criterion_weight: f64,
244 pub required_value: f64,
245}
246
247#[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
257pub enum AssemblyType {
258 Fixed,
259 Floating,
260 Kinematic,
261 Overconstrained,
262}
263
264#[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#[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
282pub struct ToleranceAnalysis {
284 pub tolerance_stackup: ToleranceStackup,
285 pub statistical_tolerance: StatisticalTolerance,
286 pub geometric_tolerance: GeometricTolerance,
287}
288
289#[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
299pub enum ToleranceType {
300 WorstCase,
301 Statistical,
302 RootSumSquare,
303}
304
305#[derive(Debug, Clone)]
307pub struct StatisticalTolerance {
308 pub distribution_type: DistributionType,
309 pub mean: f64,
310 pub standard_deviation: f64,
311}
312
313#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
315pub enum DistributionType {
316 Normal,
317 Uniform,
318 Triangular,
319}
320
321#[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#[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 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 pub fn attach_physics_simulation(&mut self, lib: Option<Arc<Mutex<PhysicsSimulationLibrary>>>) {
357 self.physics_simulation = lib;
358 }
359
360 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 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 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 pub fn fem_static(
396 &self,
397 model: &fem::FeModel,
398 ) -> Result<fem::FeStaticResult, EngineeringError> {
399 fem::solve_static(model)
400 }
401
402 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 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 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 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 pub fn initialize(&mut self) -> Result<(), EngineeringError> {
508 Ok(())
509 }
510
511 pub fn position_analysis(&self) -> &PositionAnalysis {
513 &self.position_analysis
514 }
515
516 pub fn position_analysis_mut(&mut self) -> &mut PositionAnalysis {
518 &mut self.position_analysis
519 }
520
521 pub fn velocity_analysis(&self) -> &VelocityAnalysis {
523 &self.velocity_analysis
524 }
525
526 pub fn velocity_analysis_mut(&mut self) -> &mut VelocityAnalysis {
528 &mut self.velocity_analysis
529 }
530
531 pub fn acceleration_analysis(&self) -> &AccelerationAnalysis {
533 &self.acceleration_analysis
534 }
535
536 pub fn acceleration_analysis_mut(&mut self) -> &mut AccelerationAnalysis {
538 &mut self.acceleration_analysis
539 }
540}
541
542impl PositionAnalysis {
543 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 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 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 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 pub fn initialize(&mut self) -> Result<(), EngineeringError> {
587 Ok(())
588 }
589
590 pub fn force_analysis(&self) -> &ForceAnalysis {
592 &self.force_analysis
593 }
594
595 pub fn force_analysis_mut(&mut self) -> &mut ForceAnalysis {
597 &mut self.force_analysis
598 }
599
600 pub fn inertia_analysis(&self) -> &InertiaAnalysis {
602 &self.inertia_analysis
603 }
604
605 pub fn inertia_analysis_mut(&mut self) -> &mut InertiaAnalysis {
607 &mut self.inertia_analysis
608 }
609
610 pub fn energy_analysis(&self) -> &EnergyAnalysis {
612 &self.energy_analysis
613 }
614
615 pub fn energy_analysis_mut(&mut self) -> &mut EnergyAnalysis {
617 &mut self.energy_analysis
618 }
619}
620
621impl ForceAnalysis {
622 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 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 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 pub fn new() -> Self {
658 Self {
659 synthesis: MechanismSynthesis::new(),
660 analysis: MechanismAnalysisEngine::new(),
661 optimization: MechanismOptimization::new(),
662 }
663 }
664
665 pub fn initialize(&mut self) -> Result<(), EngineeringError> {
667 Ok(())
668 }
669
670 pub fn synthesis(&self) -> &MechanismSynthesis {
672 &self.synthesis
673 }
674
675 pub fn synthesis_mut(&mut self) -> &mut MechanismSynthesis {
677 &mut self.synthesis
678 }
679
680 pub fn analysis(&self) -> &MechanismAnalysisEngine {
682 &self.analysis
683 }
684
685 pub fn analysis_mut(&mut self) -> &mut MechanismAnalysisEngine {
687 &mut self.analysis
688 }
689
690 pub fn optimization(&self) -> &MechanismOptimization {
692 &self.optimization
693 }
694
695 pub fn optimization_mut(&mut self) -> &mut MechanismOptimization {
697 &mut self.optimization
698 }
699}
700
701impl MechanismSynthesis {
702 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 pub fn new() -> Self {
715 Self {
716 analysis_type: AnalysisType::LinearStatic,
717 analysis_method: AnalysisMethod::Numerical,
718 }
719 }
720}
721
722impl MechanismOptimization {
723 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 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 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 pub fn initialize(&mut self) -> Result<(), EngineeringError> {
756 Ok(())
757 }
758
759 pub fn component_design(&self) -> &ComponentDesign {
761 &self.component_design
762 }
763
764 pub fn component_design_mut(&mut self) -> &mut ComponentDesign {
766 &mut self.component_design
767 }
768
769 pub fn assembly_design(&self) -> &AssemblyDesign {
771 &self.assembly_design
772 }
773
774 pub fn assembly_design_mut(&mut self) -> &mut AssemblyDesign {
776 &mut self.assembly_design
777 }
778
779 pub fn tolerance_analysis(&self) -> &ToleranceAnalysis {
781 &self.tolerance_analysis
782 }
783
784 pub fn tolerance_analysis_mut(&mut self) -> &mut ToleranceAnalysis {
786 &mut self.tolerance_analysis
787 }
788}
789
790impl ComponentDesign {
791 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 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 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 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 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 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 pub fn initialize(&mut self) -> Result<(), EngineeringError> {
859 Ok(())
860 }
861}
862
863impl ToleranceStackup {
864 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 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 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 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}