Skip to main content

qualia_core_db/specialized_libs/engineering_analysis/
dynamics.rs

1use super::*;
2
3/// Structural dynamics
4pub struct StructuralDynamics {
5    modal_analysis: ModalAnalysis,
6    transient_analysis: TransientAnalysis,
7    harmonic_analysis: HarmonicAnalysis,
8}
9
10/// Modal analysis
11pub struct ModalAnalysis {
12    eigenvalue_solver: EigenvalueSolver,
13    mode_shapes: Vec<ModeShape>,
14    modal_parameters: ModalParameters,
15}
16
17/// Eigenvalue solver
18#[derive(Debug, Clone)]
19pub struct EigenvalueSolver {
20    pub solver_type: EigenvalueSolverType,
21    pub num_modes: u32,
22    pub frequency_range: (f64, f64),
23}
24
25/// Eigenvalue solver types
26#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
27pub enum EigenvalueSolverType {
28    Lanczos,
29    Subspace,
30    Power,
31    QR,
32}
33
34/// Mode shapes
35#[derive(Debug, Clone)]
36pub struct ModeShape {
37    pub mode_number: u32,
38    pub natural_frequency: f64,
39    pub damping_ratio: f64,
40    pub mode_shape_vector: Vec<f64>,
41}
42
43/// Modal parameters
44#[derive(Debug, Clone, Serialize, Deserialize)]
45pub struct ModalParameters {
46    pub mass_normalization: bool,
47    pub participation_factors: Vec<f64>,
48    pub effective_mass: Vec<f64>,
49}
50
51/// Transient analysis
52pub struct TransientAnalysis {
53    time_integration: TimeIntegration,
54    loading_history: LoadingHistory,
55    response_calculation: ResponseCalculation,
56}
57
58/// Time integration
59#[derive(Debug, Clone)]
60pub struct TimeIntegration {
61    pub integration_method: IntegrationMethod,
62    pub time_step: f64,
63    pub total_time: f64,
64}
65
66/// Integration methods
67#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
68pub enum IntegrationMethod {
69    CentralDifference,
70    Newmark,
71    WilsonTheta,
72    HilberHughesTaylor,
73}
74
75/// Loading history
76#[derive(Debug, Clone)]
77pub struct LoadingHistory {
78    pub time_points: Vec<f64>,
79    pub load_values: Vec<f64>,
80    pub load_type: LoadType,
81}
82
83/// Load types
84#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
85pub enum LoadType {
86    Force,
87    Displacement,
88    Acceleration,
89    Pressure,
90    Point,
91}
92
93/// Response calculation
94#[derive(Debug, Clone)]
95pub struct ResponseCalculation {
96    pub response_types: Vec<ResponseType>,
97    pub calculation_method: CalculationMethod,
98}
99
100/// Response types
101#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
102pub enum ResponseType {
103    Displacement,
104    Velocity,
105    Acceleration,
106    Stress,
107    Strain,
108}
109
110/// Calculation methods
111#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
112pub enum CalculationMethod {
113    Direct,
114    Modal,
115    FrequencyDomain,
116}
117
118/// Harmonic analysis
119pub struct HarmonicAnalysis {
120    frequency_response: FrequencyResponse,
121    resonance_detection: ResonanceDetection,
122}
123
124/// Frequency response
125#[derive(Debug, Clone)]
126pub struct FrequencyResponse {
127    pub frequencies: Vec<f64>,
128    pub response_amplitudes: Vec<f64>,
129    pub response_phases: Vec<f64>,
130}
131
132/// Resonance detection
133#[derive(Debug, Clone)]
134pub struct ResonanceDetection {
135    pub resonance_frequencies: Vec<f64>,
136    pub resonance_amplitudes: Vec<f64>,
137    pub quality_factors: Vec<f64>,
138}
139impl StructuralDynamics {
140    /// Creates dynamics state with default modal/transient/harmonic subsystems.
141    pub fn new() -> Self {
142        Self {
143            modal_analysis: ModalAnalysis::new(),
144            transient_analysis: TransientAnalysis::new(),
145            harmonic_analysis: HarmonicAnalysis::new(),
146        }
147    }
148
149    /// Initializes subsystems; `EngineeringError` propagates.
150    pub fn initialize(&mut self) -> Result<(), EngineeringError> {
151        Ok(())
152    }
153
154    /// Borrow the modal-analysis sub-component.
155    pub fn modal_analysis(&self) -> &ModalAnalysis {
156        &self.modal_analysis
157    }
158
159    /// Mutably borrow the modal-analysis sub-component.
160    pub fn modal_analysis_mut(&mut self) -> &mut ModalAnalysis {
161        &mut self.modal_analysis
162    }
163
164    /// Borrow the transient-analysis sub-component.
165    pub fn transient_analysis(&self) -> &TransientAnalysis {
166        &self.transient_analysis
167    }
168
169    /// Mutably borrow the transient-analysis sub-component.
170    pub fn transient_analysis_mut(&mut self) -> &mut TransientAnalysis {
171        &mut self.transient_analysis
172    }
173
174    /// Borrow the harmonic-analysis sub-component.
175    pub fn harmonic_analysis(&self) -> &HarmonicAnalysis {
176        &self.harmonic_analysis
177    }
178
179    /// Mutably borrow the harmonic-analysis sub-component.
180    pub fn harmonic_analysis_mut(&mut self) -> &mut HarmonicAnalysis {
181        &mut self.harmonic_analysis
182    }
183
184    /// Genuine transient time-history analysis for a 1-DOF system (m, c, k) driven
185    /// by the configured `loading_history`. Uses explicit integration with `time_step`
186    /// up to `total_time` from the `time_integration` configuration.
187    pub fn analyze_transient(
188        &self,
189        mass: f64,
190        stiffness: f64,
191        damping: f64,
192    ) -> Result<DynamicsResults, EngineeringError> {
193        if mass <= 0.0 {
194            return Err(EngineeringError::ValidationError(
195                "mass must be positive".to_string(),
196            ));
197        }
198        let ti = &self.transient_analysis.time_integration;
199        let lh = &self.transient_analysis.loading_history;
200        if ti.time_step <= 0.0 || ti.total_time <= 0.0 {
201            return Err(EngineeringError::ValidationError(
202                "time_step and total_time must be positive".to_string(),
203            ));
204        }
205
206        let num_steps = (ti.total_time / ti.time_step).ceil() as usize;
207        let mut positions = Vec::with_capacity(num_steps + 1);
208        let mut velocities = Vec::with_capacity(num_steps + 1);
209        let mut accelerations = Vec::with_capacity(num_steps + 1);
210
211        let mut pos = 0.0;
212        let mut vel = 0.0;
213        let dt = ti.time_step;
214
215        for i in 0..=num_steps {
216            let t = i as f64 * dt;
217
218            // Interpolate force from loading history
219            let mut force = 0.0;
220            if !lh.time_points.is_empty() && lh.time_points.len() == lh.load_values.len() {
221                if t <= lh.time_points[0] {
222                    force = lh.load_values[0];
223                } else if t >= *lh.time_points.last().unwrap() {
224                    force = *lh.load_values.last().unwrap();
225                } else {
226                    for j in 0..lh.time_points.len() - 1 {
227                        if t >= lh.time_points[j] && t <= lh.time_points[j + 1] {
228                            let dt_int = lh.time_points[j + 1] - lh.time_points[j];
229                            let df = lh.load_values[j + 1] - lh.load_values[j];
230                            let frac = (t - lh.time_points[j]) / dt_int;
231                            force = lh.load_values[j] + df * frac;
232                            break;
233                        }
234                    }
235                }
236            }
237
238            let acc = (force - damping * vel - stiffness * pos) / mass;
239
240            positions.push(pos);
241            velocities.push(vel);
242            accelerations.push(acc);
243
244            // Symplectic Euler step
245            vel += acc * dt;
246            pos += vel * dt;
247        }
248
249        let final_pos = positions.last().copied().unwrap_or(0.0);
250        let final_vel = velocities.last().copied().unwrap_or(0.0);
251        let ke = 0.5 * mass * final_vel * final_vel;
252        let pe = 0.5 * stiffness * final_pos * final_pos;
253        Ok(DynamicsResults {
254            positions,
255            velocities,
256            accelerations,
257            kinetic_energy: ke,
258            potential_energy: pe,
259            total_energy: ke + pe,
260            time_steps: (0..=num_steps).map(|i| i as f64 * dt).collect(),
261        })
262    }
263}
264
265impl ModalAnalysis {
266    /// Creates modal-analysis state with default eigenvalue solver and parameters.
267    pub fn new() -> Self {
268        Self {
269            eigenvalue_solver: EigenvalueSolver::new(),
270            mode_shapes: Vec::new(),
271            modal_parameters: ModalParameters::new(),
272        }
273    }
274
275    /// Borrow the eigenvalue solver configuration.
276    pub fn eigenvalue_solver(&self) -> &EigenvalueSolver {
277        &self.eigenvalue_solver
278    }
279
280    /// Mutably borrow the eigenvalue solver configuration.
281    pub fn eigenvalue_solver_mut(&mut self) -> &mut EigenvalueSolver {
282        &mut self.eigenvalue_solver
283    }
284
285    /// Append a computed mode shape to the results.
286    pub fn add_mode_shape(&mut self, mode: ModeShape) {
287        self.mode_shapes.push(mode);
288    }
289
290    /// Borrow the computed mode shapes.
291    pub fn mode_shapes(&self) -> &[ModeShape] {
292        &self.mode_shapes
293    }
294
295    /// Borrow the modal parameters.
296    pub fn modal_parameters(&self) -> &ModalParameters {
297        &self.modal_parameters
298    }
299
300    /// Mutably borrow the modal parameters.
301    pub fn modal_parameters_mut(&mut self) -> &mut ModalParameters {
302        &mut self.modal_parameters
303    }
304
305    /// Undamped modal analysis: solves the generalized eigenproblem
306    /// `K φ = ω² M φ` for a symmetric stiffness matrix `stiffness` (row-major
307    /// `num_dofs × num_dofs`) and a lumped (diagonal) mass matrix `mass_diag`
308    /// (`num_dofs` positive entries), wired to the crate's symmetric Jacobi
309    /// eigensolver via `solve_modal_eigen`. Returns one [`ModeShape`] per DOF,
310    /// ordered by ascending **natural angular frequency ω (rad/s)** (stored in
311    /// `ModeShape::natural_frequency`), with zero damping (undamped) and the
312    /// mass-normalized mode-shape vector (unit maximum component). The result is
313    /// also cached in `self.mode_shapes`.
314    pub fn analyze_modal(
315        &mut self,
316        stiffness: &[f64],
317        mass_diag: &[f64],
318        num_dofs: usize,
319    ) -> Result<Vec<ModeShape>, EngineeringError> {
320        let modes = solve_modal_eigen(stiffness, mass_diag, num_dofs)?;
321        let shapes: Vec<ModeShape> = modes
322            .into_iter()
323            .enumerate()
324            .map(|(i, (omega, phi))| ModeShape {
325                mode_number: (i + 1) as u32,
326                natural_frequency: omega,
327                damping_ratio: 0.0,
328                mode_shape_vector: phi,
329            })
330            .collect();
331        self.mode_shapes = shapes.clone();
332        Ok(shapes)
333    }
334}
335
336impl EigenvalueSolver {
337    /// Creates a default `EigenvalueSolver` descriptor.
338    pub fn new() -> Self {
339        Self {
340            solver_type: EigenvalueSolverType::Lanczos,
341            num_modes: 10,
342            frequency_range: (0.0, 1000.0),
343        }
344    }
345}
346
347impl ModalParameters {
348    /// Creates default `ModalParameters`.
349    pub fn new() -> Self {
350        Self {
351            mass_normalization: true,
352            participation_factors: Vec::new(),
353            effective_mass: Vec::new(),
354        }
355    }
356}
357
358impl TransientAnalysis {
359    /// Creates transient-analysis state with default time integration and loading history.
360    pub fn new() -> Self {
361        Self {
362            time_integration: TimeIntegration::new(),
363            loading_history: LoadingHistory::new(),
364            response_calculation: ResponseCalculation::new(),
365        }
366    }
367
368    /// Borrow the time-integration configuration.
369    pub fn time_integration(&self) -> &TimeIntegration {
370        &self.time_integration
371    }
372
373    /// Mutably borrow the time-integration configuration.
374    pub fn time_integration_mut(&mut self) -> &mut TimeIntegration {
375        &mut self.time_integration
376    }
377
378    /// Borrow the loading history.
379    pub fn loading_history(&self) -> &LoadingHistory {
380        &self.loading_history
381    }
382
383    /// Mutably borrow the loading history.
384    pub fn loading_history_mut(&mut self) -> &mut LoadingHistory {
385        &mut self.loading_history
386    }
387
388    /// Borrow the response-calculation configuration.
389    pub fn response_calculation(&self) -> &ResponseCalculation {
390        &self.response_calculation
391    }
392
393    /// Mutably borrow the response-calculation configuration.
394    pub fn response_calculation_mut(&mut self) -> &mut ResponseCalculation {
395        &mut self.response_calculation
396    }
397}
398
399impl TimeIntegration {
400    /// Creates a default `TimeIntegration` scheme descriptor.
401    pub fn new() -> Self {
402        Self {
403            integration_method: IntegrationMethod::Newmark,
404            time_step: 0.01,
405            total_time: 10.0,
406        }
407    }
408}
409
410impl LoadingHistory {
411    /// Creates an empty `LoadingHistory`.
412    pub fn new() -> Self {
413        Self {
414            time_points: Vec::new(),
415            load_values: Vec::new(),
416            load_type: LoadType::Force,
417        }
418    }
419}
420
421impl ResponseCalculation {
422    /// Creates a default `ResponseCalculation` descriptor.
423    pub fn new() -> Self {
424        Self {
425            response_types: vec![ResponseType::Displacement, ResponseType::Stress],
426            calculation_method: CalculationMethod::Modal,
427        }
428    }
429}
430
431impl HarmonicAnalysis {
432    /// Creates harmonic-analysis state with default frequency response and resonance detection.
433    pub fn new() -> Self {
434        Self {
435            frequency_response: FrequencyResponse::new(),
436            resonance_detection: ResonanceDetection::new(),
437        }
438    }
439
440    /// Borrow the frequency-response data.
441    pub fn frequency_response(&self) -> &FrequencyResponse {
442        &self.frequency_response
443    }
444
445    /// Mutably borrow the frequency-response data.
446    pub fn frequency_response_mut(&mut self) -> &mut FrequencyResponse {
447        &mut self.frequency_response
448    }
449
450    /// Borrow the resonance-detection data.
451    pub fn resonance_detection(&self) -> &ResonanceDetection {
452        &self.resonance_detection
453    }
454
455    /// Mutably borrow the resonance-detection data.
456    pub fn resonance_detection_mut(&mut self) -> &mut ResonanceDetection {
457        &mut self.resonance_detection
458    }
459}
460
461impl FrequencyResponse {
462    /// Creates a default `FrequencyResponse` descriptor.
463    pub fn new() -> Self {
464        Self {
465            frequencies: Vec::new(),
466            response_amplitudes: Vec::new(),
467            response_phases: Vec::new(),
468        }
469    }
470}
471
472impl ResonanceDetection {
473    /// Creates a default `ResonanceDetection` descriptor.
474    pub fn new() -> Self {
475        Self {
476            resonance_frequencies: Vec::new(),
477            resonance_amplitudes: Vec::new(),
478            quality_factors: Vec::new(),
479        }
480    }
481}