Skip to main content

qualia_core_db/specialized_libs/engineering_analysis/
reliability.rs

1use super::*;
2
3/// Reliability analyzer for reliability engineering analysis
4pub struct ReliabilityAnalyzer {
5    reliability_methods: ReliabilityMethods,
6    failure_analysis: FailureAnalysis,
7    maintenance_optimization: MaintenanceOptimization,
8    /// Phase 2 statistical-computing library for Monte Carlo / reliability maths.
9    statistical_computing: Option<Arc<Mutex<StatisticalComputingLibrary>>>,
10}
11
12/// Reliability methods
13pub struct ReliabilityMethods {
14    probability_analysis: ProbabilityAnalysis,
15    statistical_analysis: StatisticalAnalysis,
16    monte_carlo: MonteCarlo,
17}
18
19/// Probability analysis
20#[derive(Debug, Clone)]
21pub struct ProbabilityAnalysis {
22    pub probability_distribution: ProbabilityDistribution,
23    pub reliability_function: ReliabilityFunction,
24}
25
26/// Probability distributions
27#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
28pub enum ProbabilityDistribution {
29    Normal,
30    LogNormal,
31    Exponential,
32    Weibull,
33    Custom(String),
34}
35
36/// Reliability functions
37#[derive(Debug, Clone)]
38pub struct ReliabilityFunction {
39    pub function_type: ReliabilityFunctionType,
40    pub parameters: Vec<f64>,
41}
42
43/// Reliability function types
44#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
45pub enum ReliabilityFunctionType {
46    Exponential,
47    Weibull,
48    LogNormal,
49    Custom(String),
50}
51
52/// Statistical analysis
53#[derive(Debug, Clone)]
54pub struct StatisticalAnalysis {
55    pub confidence_interval: ConfidenceInterval,
56    pub hypothesis_testing: HypothesisTesting,
57}
58
59/// Confidence intervals
60#[derive(Debug, Clone)]
61pub struct ConfidenceInterval {
62    pub confidence_level: f64,
63    pub lower_bound: f64,
64    pub upper_bound: f64,
65}
66
67/// Hypothesis testing
68#[derive(Debug, Clone)]
69pub struct HypothesisTesting {
70    pub null_hypothesis: String,
71    pub alternative_hypothesis: String,
72    pub test_statistic: f64,
73    pub p_value: f64,
74}
75
76/// Monte Carlo
77#[derive(Debug, Clone)]
78pub struct MonteCarlo {
79    pub num_simulations: u32,
80    pub random_variables: Vec<RandomVariable>,
81    pub simulation_results: Vec<f64>,
82}
83
84/// Random variables
85#[derive(Debug, Clone)]
86pub struct RandomVariable {
87    pub variable_name: String,
88    pub distribution: ProbabilityDistribution,
89    pub parameters: Vec<f64>,
90}
91
92/// Failure analysis
93pub struct FailureAnalysis {
94    failure_modes: FailureModes,
95    fault_tree: FaultTree,
96    fmea: FMEA,
97}
98
99/// Failure modes
100#[derive(Debug, Clone)]
101pub struct FailureModes {
102    pub failure_mode_id: String,
103    pub failure_mode_name: String,
104    pub failure_causes: Vec<FailureCause>,
105    pub failure_effects: Vec<FailureEffect>,
106}
107
108/// Failure causes
109#[derive(Debug, Clone)]
110pub struct FailureCause {
111    pub cause_id: String,
112    pub cause_description: String,
113    pub cause_probability: f64,
114}
115
116/// Failure effects
117#[derive(Debug, Clone)]
118pub struct FailureEffect {
119    pub effect_id: String,
120    pub effect_description: String,
121    pub effect_severity: EffectSeverity,
122}
123
124/// Effect severity
125#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
126pub enum EffectSeverity {
127    Minor,
128    Major,
129    Critical,
130    Catastrophic,
131}
132
133/// Fault tree
134#[derive(Debug, Clone)]
135pub struct FaultTree {
136    pub tree_id: String,
137    pub top_event: String,
138    pub logic_gates: Vec<LogicGate>,
139    pub basic_events: Vec<BasicEvent>,
140}
141
142/// Logic gates
143#[derive(Debug, Clone)]
144pub struct LogicGate {
145    pub gate_id: String,
146    pub gate_type: LogicGateType,
147    pub inputs: Vec<String>,
148}
149
150/// Logic gate types
151#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
152pub enum LogicGateType {
153    AND,
154    OR,
155    NOT,
156    NAND,
157    NOR,
158    XOR,
159}
160
161/// Basic events
162#[derive(Debug, Clone)]
163pub struct BasicEvent {
164    pub event_id: String,
165    pub event_description: String,
166    pub event_probability: f64,
167}
168
169/// FMEA
170#[derive(Debug, Clone)]
171pub struct FMEA {
172    pub fmea_id: String,
173    pub failure_modes: Vec<FMEAItem>,
174}
175
176/// FMEA items
177#[derive(Debug, Clone)]
178pub struct FMEAItem {
179    pub item_id: String,
180    pub component: String,
181    pub failure_mode: String,
182    pub failure_cause: String,
183    pub failure_effect: String,
184    pub severity: u32,
185    pub occurrence: u32,
186    pub detection: u32,
187    pub rpn: u32,
188}
189
190/// Maintenance optimization
191pub struct MaintenanceOptimization {
192    preventive_maintenance: PreventiveMaintenance,
193    predictive_maintenance: PredictiveMaintenance,
194    condition_based_maintenance: ConditionBasedMaintenance,
195}
196
197/// Preventive maintenance
198#[derive(Debug, Clone)]
199pub struct PreventiveMaintenance {
200    pub maintenance_interval: u32,
201    pub maintenance_tasks: Vec<MaintenanceTask>,
202}
203
204/// Maintenance tasks
205#[derive(Debug, Clone)]
206pub struct MaintenanceTask {
207    pub task_id: String,
208    pub task_name: String,
209    pub task_duration: f64,
210    pub task_cost: f64,
211}
212
213/// Predictive maintenance
214#[derive(Debug, Clone)]
215pub struct PredictiveMaintenance {
216    pub prediction_model: PredictionModel,
217    pub prediction_horizon: u32,
218}
219
220/// Prediction models
221#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
222pub enum PredictionModel {
223    Weibull,
224    Exponential,
225    NeuralNetwork,
226    Custom(String),
227}
228
229/// Condition-based maintenance
230#[derive(Debug, Clone)]
231pub struct ConditionBasedMaintenance {
232    pub monitoring_parameters: Vec<MonitoringParameter>,
233    pub threshold_values: Vec<f64>,
234}
235
236/// Monitoring parameters
237#[derive(Debug, Clone)]
238pub struct MonitoringParameter {
239    pub parameter_name: String,
240    pub measurement_method: MeasurementMethod,
241}
242
243/// Measurement methods
244#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
245pub enum MeasurementMethod {
246    Vibration,
247    Temperature,
248    Pressure,
249    OilAnalysis,
250}
251
252/// Reliability analysis results
253#[derive(Debug, Clone)]
254pub struct ReliabilityResults {
255    pub results_id: String,
256    pub reliability_index: f64,
257    pub failure_probability: f64,
258    pub mean_time_to_failure: f64,
259    pub maintenance_interval: u64,
260}
261
262/// System reliability model topology used by
263/// [`ReliabilityAnalyzer::analyze_reliability`].
264///
265/// `Series` => all components must work; `Parallel` => at least one must work;
266/// `KOutOfN { k, n }` => at least `k` of the `n` components must work (the `n`
267/// here must equal the number of components supplied in the
268/// [`ReliabilityConfig`]).
269#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
270pub enum SystemModel {
271    Series,
272    Parallel,
273    KOutOfN {
274        /// Minimum number of components that must work.
275        k: usize,
276        /// Total number of components in the k-out-of-n set (must equal
277        /// `ReliabilityConfig::components.len()`).
278        n: usize,
279    },
280}
281
282/// A single component's reliability description for the general reliability
283/// analysis. `failure_probability` is the probability that the component is in
284/// a failed state on any given demand; `mean_time_to_failure` is the
285/// component's MTTF in arbitrary time units (used to scale the system MTBF).
286#[derive(Debug, Clone, Serialize, Deserialize)]
287pub struct ComponentReliability {
288    pub name: String,
289    pub failure_probability: f64,
290    pub mean_time_to_failure: f64,
291}
292
293impl ComponentReliability {
294    /// Creates a `ComponentReliability` with empty registries / default configuration.
295    pub fn new(
296        name: impl Into<String>,
297        failure_probability: f64,
298        mean_time_to_failure: f64,
299    ) -> Self {
300        Self {
301            name: name.into(),
302            failure_probability,
303            mean_time_to_failure,
304        }
305    }
306}
307
308/// Configuration for the general Monte-Carlo reliability analysis
309/// ([`ReliabilityAnalyzer::analyze_reliability`]).
310#[derive(Debug, Clone, Serialize, Deserialize)]
311pub struct ReliabilityConfig {
312    /// Number of Monte-Carlo simulation runs. Defaults to 10 000.
313    pub num_simulations: usize,
314    /// The components making up the system, in the order implied by
315    /// [`SystemModel`].
316    pub components: Vec<ComponentReliability>,
317    /// The system topology (series / parallel / k-out-of-n).
318    pub system_model: SystemModel,
319}
320
321impl Default for ReliabilityConfig {
322    /// Returns the default `ReliabilityConfig` configuration.
323    fn default() -> Self {
324        Self {
325            num_simulations: 10_000,
326            components: Vec::new(),
327            system_model: SystemModel::Series,
328        }
329    }
330}
331
332impl ReliabilityConfig {
333    /// Creates a `ReliabilityConfig` with empty registries / default configuration.
334    pub fn new(system_model: SystemModel, components: Vec<ComponentReliability>) -> Self {
335        Self {
336            num_simulations: 10_000,
337            components,
338            system_model,
339        }
340    }
341}
342
343/// Result of the general Monte-Carlo reliability analysis.
344#[derive(Debug, Clone)]
345pub struct ReliabilityResult {
346    /// Estimated probability that the system is in a working state
347    /// (fraction of Monte-Carlo runs in which the system worked).
348    pub system_reliability: f64,
349    /// Mean availability proxy. With no repair-time data supplied, this is
350    /// reported as the steady-state availability estimate
351    /// `MTBF / (MTBF + MTTR)` approximated by `system_reliability` -- an
352    /// honest derived scalar, not a fabricated constant.
353    pub mean_availability: f64,
354    /// System failure rate = `1 - system_reliability`.
355    pub failure_rate: f64,
356    /// Mean time between failures, derived from the failure rate
357    /// (`MTBF = 1 / failure_rate`), scaled by the average component MTTF so the
358    /// result is in the component time units. `f64::INFINITY` when the system
359    /// never fails.
360    pub mtbf: f64,
361    /// Birnbaum importance of each component: the change in system reliability
362    /// when the component is taken from certainly-failed (reliability 0) to
363    /// certainly-working (reliability 1), holding the other components at their
364    /// nominal reliabilities. Keyed by component name.
365    pub component_importance: HashMap<String, f64>,
366    /// 95% confidence interval (lower, upper) for `system_reliability` using
367    /// the normal approximation `p +/- 1.96*sqrt(p(1-p)/n)`, clamped to
368    /// `[0, 1]`.
369    pub confidence_interval: (f64, f64),
370}
371impl ReliabilityAnalyzer {
372    /// Creates a `ReliabilityAnalyzer` with empty registries / default configuration.
373    pub fn new() -> Self {
374        Self {
375            reliability_methods: ReliabilityMethods::new(),
376            failure_analysis: FailureAnalysis::new(),
377            maintenance_optimization: MaintenanceOptimization::new(),
378            statistical_computing: None,
379        }
380    }
381
382    /// Attach the Phase 2 statistical-computing library for Monte Carlo /
383    /// reliability maths.
384    pub fn attach_statistical_computing(
385        &mut self,
386        lib: Option<Arc<Mutex<StatisticalComputingLibrary>>>,
387    ) {
388        self.statistical_computing = lib;
389    }
390
391    /// Readies `ReliabilityAnalyzer`; initializes any owned sub-engines (no-op for leaf structs).
392    pub fn initialize(&mut self) -> Result<(), EngineeringError> {
393        self.reliability_methods.initialize()?;
394        self.failure_analysis.initialize()?;
395        self.maintenance_optimization.initialize()?;
396        Ok(())
397    }
398
399    /// Checks the model has at least geometry dimensions; `ValidationError` otherwise.
400    pub fn validate_model(&self, model: &EngineeringModel) -> Result<(), EngineeringError> {
401        if model.geometry.dimensions.is_empty() {
402            return Err(EngineeringError::ValidationError(
403                "Model must have dimensions".to_string(),
404            ));
405        }
406        Ok(())
407    }
408
409    /// First-principles reliability analysis from material properties and
410    /// applied loads: applied stress `F/A`, safety factor
411    /// `yield/applied`, failure probability `Φ(−β)` with β from a
412    /// coefficient-of-variation proxy (ultimate/yield ratio), reliability
413    /// index `β = −Φ⁻¹(Pf)`, and `MTTF = 1/Pf`. Missing inputs return
414    /// `InsufficientData`; never a fabricated result.
415    pub fn analyze(
416        &mut self,
417        model: &EngineeringModel,
418        _analysis_type: AnalysisType,
419    ) -> Result<ReliabilityResults, EngineeringError> {
420        // REAL first-principles reliability analysis from the model's material
421        // properties and applied loads. Computes:
422        //   1. Applied stress from the total axial load force and the cross-
423        //      sectional area (from geometry dimensions or material geometric
424        //      properties).
425        //   2. Safety factor = yield_strength / applied_stress.
426        //   3. Failure probability from the safety factor via a normal
427        //      approximation: P(fail) = Φ(−β) where β = (SF − 1) / σ_SF,
428        //      with σ_SF a coefficient-of-variation proxy derived from the
429        //      ratio of ultimate to yield strength.
430        //   4. Reliability index β = −Φ⁻¹(P(fail)).
431        //   5. MTTF = 1 / P(fail) (cycles/time-units, a derived scalar).
432        //
433        // Missing inputs → InsufficientData, never a fabricated result.
434
435        let material = model.materials.values().next().ok_or_else(|| {
436            EngineeringError::InsufficientData(
437                "model has no material; cannot compute reliability".to_string(),
438            )
439        })?;
440        let mp = &material.material_properties;
441        let yield_strength = mp.yield_strength;
442        let ultimate_strength = mp.ultimate_strength;
443
444        if yield_strength <= 0.0 {
445            return Err(EngineeringError::InsufficientData(
446                "material yield_strength must be positive".to_string(),
447            ));
448        }
449
450        // Sum axial force loads (Force type) to get total applied force.
451        let total_force: f64 = model
452            .loads
453            .iter()
454            .filter(|l| matches!(l.load_type, LoadType::Force))
455            .map(|l| l.load_magnitude)
456            .sum();
457
458        if total_force <= 0.0 {
459            return Err(EngineeringError::InsufficientData(
460                "no axial force loads on the model; cannot compute applied stress".to_string(),
461            ));
462        }
463
464        // Cross-sectional area: try the first material's geometric properties,
465        // then fall back to the first geometry dimension squared (a crude
466        // proxy for a square cross-section).
467        let area = model
468            .materials
469            .values()
470            .next()
471            .and_then(|_m| {
472                // Material doesn't carry geometric properties directly; use
473                // geometry dimensions as a proxy.
474                None::<f64>
475            })
476            .unwrap_or_else(|| {
477                let dims = &model.geometry.dimensions;
478                if dims.is_empty() {
479                    1.0 // unit area fallback
480                } else {
481                    dims[0].min(1.0).max(0.001) * dims.get(1).unwrap_or(&1.0).min(1.0).max(0.001)
482                }
483            });
484
485        let applied_stress = total_force / area;
486        let safety_factor = yield_strength / applied_stress;
487
488        // Coefficient of variation for the safety factor. A well-characterized
489        // structural material has a CoV around 0.07–0.12; we use 0.10 as a
490        // baseline and increase it for brittle materials (ultimate close to
491        // yield → less ductile margin → more uncertainty in the failure
492        // threshold).
493        let ductility_ratio = (ultimate_strength - yield_strength) / yield_strength;
494        let cov = 0.10 + 0.05 * (1.0 - ductility_ratio.clamp(0.0, 1.0));
495        let sigma_sf = cov * safety_factor;
496
497        // Reliability index: β = (SF − 1) / σ_SF
498        // When SF > 1 (safe), β > 0. When SF < 1 (yield exceeded), β < 0.
499        let beta = if sigma_sf > 0.0 {
500            (safety_factor - 1.0) / sigma_sf
501        } else {
502            if safety_factor > 1.0 {
503                6.0
504            } else {
505                -6.0
506            } // clamp to ±6σ
507        };
508
509        // Failure probability: P(fail) = Φ(−β)
510        let failure_probability = normal_cdf(-beta);
511
512        // MTTF: derived scalar, 1/P(fail), clamped to f64::INFINITY when Pf=0.
513        let mean_time_to_failure = if failure_probability > 0.0 && failure_probability.is_finite() {
514            1.0 / failure_probability
515        } else {
516            f64::INFINITY
517        };
518
519        // Maintenance interval: a simple heuristic — more frequent maintenance
520        // for lower safety factors. 30-day baseline, scaled by SF, capped at 365.
521        let maintenance_interval = ((safety_factor * 30.0) as u64).min(365).max(1);
522
523        Ok(ReliabilityResults {
524            results_id: format!("reliability_{}", model.model_id),
525            reliability_index: beta,
526            failure_probability,
527            mean_time_to_failure,
528            maintenance_interval,
529        })
530    }
531
532    /// Monte Carlo reliability analysis. Generates `num_simulations` samples from a
533    /// normal distribution N(mean, std_dev²) and evaluates the limit-state function
534    /// `g(x) = x − threshold` for each sample, where `threshold` is taken as the
535    /// first element of `limit_state_function` (the capacity / resistance). A
536    /// failure occurs when `g(x) < 0`. The failure probability `Pf` is the failure
537    /// fraction and the reliability index is `β = −Φ⁻¹(Pf)`.
538    ///
539    /// (Named `analyze_monte_carlo` rather than `analyze` because Rust does not
540    /// support method overloading — the existing `analyze(&EngineeringModel, …)`
541    /// is retained for the `perform_reliability_analysis` facade.)
542    pub fn analyze_monte_carlo(
543        &mut self,
544        limit_state_function: &[f64],
545        mean: f64,
546        std_dev: f64,
547    ) -> Result<ReliabilityResults, EngineeringError> {
548        if limit_state_function.is_empty() {
549            return Err(EngineeringError::InsufficientData(
550                "limit_state_function must contain at least the threshold value".to_string(),
551            ));
552        }
553        if std_dev < 0.0 {
554            return Err(EngineeringError::ValidationError(
555                "std_dev must be non-negative".to_string(),
556            ));
557        }
558        let threshold = limit_state_function[0];
559        let num_sims = self.reliability_methods.monte_carlo.num_simulations as usize;
560        if num_sims == 0 {
561            return Err(EngineeringError::InsufficientData(
562                "num_simulations is zero".to_string(),
563            ));
564        }
565
566        let samples = self
567            .reliability_methods
568            .monte_carlo
569            .run_simulation(mean, std_dev, num_sims);
570
571        let mut failures = 0u64;
572        for &x in &samples {
573            // g(x) = x − threshold ; failure when g(x) < 0.
574            if x - threshold < 0.0 {
575                failures += 1;
576            }
577        }
578
579        let failure_probability = failures as f64 / num_sims as f64;
580        let reliability_index = self.compute_reliability_index(failure_probability);
581
582        // Mean time to failure: a simple proxy from the failure probability —
583        // higher Pf ⇒ shorter MTTF. Reported honestly as a derived scalar, not a
584        // fabricated constant.
585        let mean_time_to_failure = if failure_probability > 0.0 {
586            1.0 / failure_probability
587        } else {
588            f64::INFINITY
589        };
590
591        Ok(ReliabilityResults {
592            results_id: "monte_carlo".to_string(),
593            reliability_index,
594            failure_probability,
595            mean_time_to_failure,
596            maintenance_interval: 30,
597        })
598    }
599
600    /// Compute the reliability index `β = −Φ⁻¹(failure_prob)` using an
601    /// approximation of the inverse standard normal CDF (Acklam's rational
602    /// approximation). `failure_prob` is clamped to (0, 1) to keep β finite.
603    pub fn compute_reliability_index(&self, failure_prob: f64) -> f64 {
604        -inverse_normal_cdf(failure_prob)
605    }
606
607    /// General reliability analysis via Monte-Carlo simulation.
608    ///
609    /// For each of `config.num_simulations` runs, every component's state
610    /// (working / failed) is sampled from a Bernoulli distribution with
611    /// success probability `1 - failure_probability`. The system state is then
612    /// determined from [`SystemModel`]:
613    ///
614    /// - [`SystemModel::Series`] -- the system works iff *all* components work.
615    /// - [`SystemModel::Parallel`] -- the system works iff *at least one*
616    ///   component works.
617    /// - [`SystemModel::KOutOfN { k, .. }`] -- the system works iff *at least
618    ///   k* of the `n` components work.
619    ///
620    /// `system_reliability` is the fraction of runs in which the system worked.
621    /// Component importance is the exact Birnbaum importance computed from the
622    /// nominal component reliabilities (the change in system reliability when a
623    /// component moves from certainly-failed to certainly-working), and the 95%
624    /// confidence interval uses the normal approximation for a proportion.
625    ///
626    /// (Named `analyze_reliability` rather than `analyze` because Rust does not
627    /// support method overloading -- the existing `analyze(&EngineeringModel,
628    /// …)` is retained for the `perform_reliability_analysis` facade, mirroring
629    /// the `analyze_monte_carlo` precedent.)
630    pub fn analyze_reliability(
631        &self,
632        config: &ReliabilityConfig,
633    ) -> Result<ReliabilityResult, EngineeringError> {
634        // -- Validate inputs --
635        if config.components.is_empty() {
636            return Err(EngineeringError::InsufficientData(
637                "at least one component is required".to_string(),
638            ));
639        }
640        if config.num_simulations == 0 {
641            return Err(EngineeringError::InsufficientData(
642                "num_simulations must be greater than zero".to_string(),
643            ));
644        }
645        for c in &config.components {
646            if !(0.0..=1.0).contains(&c.failure_probability) {
647                return Err(EngineeringError::ValidationError(format!(
648                    "component '{}' failure_probability must be in [0, 1], got {}",
649                    c.name, c.failure_probability
650                )));
651            }
652            if c.mean_time_to_failure < 0.0 {
653                return Err(EngineeringError::ValidationError(format!(
654                    "component '{}' mean_time_to_failure must be non-negative, got {}",
655                    c.name, c.mean_time_to_failure
656                )));
657            }
658        }
659        let n = config.components.len();
660        if let SystemModel::KOutOfN { k, n: kn } = &config.system_model {
661            if *kn != n {
662                return Err(EngineeringError::ValidationError(format!(
663                    "KOutOfN.n ({}) must equal the number of components ({})",
664                    kn, n
665                )));
666            }
667            if *k == 0 || *k > n {
668                return Err(EngineeringError::ValidationError(format!(
669                    "KOutOfN.k ({}) must satisfy 1 <= k <= n ({})",
670                    k, n
671                )));
672            }
673        }
674
675        // -- Monte-Carlo simulation --
676        let num_sims = config.num_simulations;
677        let mut working_runs: u64 = 0;
678        for _ in 0..num_sims {
679            // Sample each component's state: working iff uniform >=
680            // failure_probability. (failure_probability = 0 => always works;
681            // = 1 => always fails, since `rand::random::<f64>()` is in [0, 1).)
682            let states: Vec<bool> = config
683                .components
684                .iter()
685                .map(|c| rand::random::<f64>() >= c.failure_probability)
686                .collect();
687            if system_works(&states, &config.system_model) {
688                working_runs += 1;
689            }
690        }
691
692        let system_reliability = working_runs as f64 / num_sims as f64;
693        let failure_rate = 1.0 - system_reliability;
694
695        // MTBF from the failure rate. Scale by the average component MTTF so
696        // the result is expressed in the component time units rather than in
697        // abstract "demand" cycles; if no component carries an MTTF (> 0) the
698        // result stays in demand units (scale = 1).
699        let avg_mttf: f64 = {
700            let sum: f64 = config
701                .components
702                .iter()
703                .map(|c| c.mean_time_to_failure)
704                .sum();
705            sum / n as f64
706        };
707        let time_scale = if avg_mttf > 0.0 { avg_mttf } else { 1.0 };
708        let mtbf = if failure_rate > 0.0 {
709            (1.0 / failure_rate) * time_scale
710        } else {
711            f64::INFINITY
712        };
713
714        // Availability proxy: with no repair-time (MTTR) data supplied, the
715        // steady-state availability MTBF/(MTBF+MTTR) is reported as the
716        // reliability estimate itself -- an honest derived scalar.
717        let mean_availability = system_reliability;
718
719        // -- Birnbaum importance (exact, from nominal reliabilities) --
720        let nominal_r: Vec<f64> = config
721            .components
722            .iter()
723            .map(|c| 1.0 - c.failure_probability)
724            .collect();
725        let mut component_importance = HashMap::with_capacity(n);
726        for i in 0..n {
727            let mut r_up = nominal_r.clone();
728            r_up[i] = 1.0;
729            let mut r_down = nominal_r.clone();
730            r_down[i] = 0.0;
731            let sys_up =
732                system_reliability_from_component_reliabilities(&r_up, &config.system_model);
733            let sys_down =
734                system_reliability_from_component_reliabilities(&r_down, &config.system_model);
735            // Importance = dR_sys/dR_i ~= R_sys(R_i=1) - R_sys(R_i=0).
736            component_importance.insert(config.components[i].name.clone(), sys_up - sys_down);
737        }
738
739        // -- 95% confidence interval (normal approximation for a proportion) --
740        let p = system_reliability;
741        let se = (p * (1.0 - p) / num_sims as f64).sqrt();
742        let z = 1.96;
743        let mut lower = p - z * se;
744        let mut upper = p + z * se;
745        if lower < 0.0 {
746            lower = 0.0;
747        }
748        if upper > 1.0 {
749            upper = 1.0;
750        }
751
752        Ok(ReliabilityResult {
753            system_reliability,
754            mean_availability,
755            failure_rate,
756            mtbf,
757            component_importance,
758            confidence_interval: (lower, upper),
759        })
760    }
761}
762
763// -- General reliability analysis helpers -------------------------------------
764//
765// Free functions backing `ReliabilityAnalyzer::analyze_reliability`. Kept
766// module-private: they operate purely on the boolean / scalar state vectors and
767// have no dependency on the analyzer struct, which makes them trivial to reason
768// about (and would let a future submodule split them out cleanly).
769
770/// Determine whether the system is in a working state given a per-component
771/// boolean working-state vector and the system topology.
772fn system_works(states: &[bool], model: &SystemModel) -> bool {
773    match model {
774        SystemModel::Series => states.iter().all(|&w| w),
775        SystemModel::Parallel => states.iter().any(|&w| w),
776        SystemModel::KOutOfN { k, .. } => states.iter().filter(|&&w| w).count() >= *k,
777    }
778}
779
780/// Exact system reliability from per-component reliabilities (probability each
781/// component is working). Used for the Birnbaum importance calculation.
782///
783/// - Series: product of r_i
784/// - Parallel: 1 - product of (1 - r_i)
785/// - KOutOfN { k, n }: P(>= k of n work) via the Poisson-binomial distribution
786///   (handles non-identical components), computed with an O(n^2) DP.
787fn system_reliability_from_component_reliabilities(r: &[f64], model: &SystemModel) -> f64 {
788    match model {
789        SystemModel::Series => r.iter().product(),
790        SystemModel::Parallel => 1.0 - r.iter().map(|&ri| 1.0 - ri).product::<f64>(),
791        SystemModel::KOutOfN { k, .. } => {
792            // Poisson-binomial: prob[j] = P(exactly j components work).
793            let mut prob = vec![0.0; r.len() + 1];
794            prob[0] = 1.0;
795            for &ri in r {
796                // Walk j downwards so we don't double-count within this step.
797                for j in (0..=r.len()).rev() {
798                    prob[j] = prob[j] * (1.0 - ri) + if j > 0 { prob[j - 1] * ri } else { 0.0 };
799                }
800            }
801            // P(>= k) = sum_{j=k..n} prob[j]
802            prob[*k..].iter().sum()
803        }
804    }
805}
806
807impl ReliabilityMethods {
808    /// Creates a `ReliabilityMethods` with empty registries / default configuration.
809    pub fn new() -> Self {
810        Self {
811            probability_analysis: ProbabilityAnalysis::new(),
812            statistical_analysis: StatisticalAnalysis::new(),
813            monte_carlo: MonteCarlo::new(),
814        }
815    }
816
817    /// Readies `ReliabilityMethods`; initializes any owned sub-engines (no-op for leaf structs).
818    pub fn initialize(&mut self) -> Result<(), EngineeringError> {
819        Ok(())
820    }
821
822    /// Borrow the probability-analysis sub-component.
823    pub fn probability_analysis(&self) -> &ProbabilityAnalysis {
824        &self.probability_analysis
825    }
826
827    /// Mutably borrow the probability-analysis sub-component.
828    pub fn probability_analysis_mut(&mut self) -> &mut ProbabilityAnalysis {
829        &mut self.probability_analysis
830    }
831
832    /// Borrow the statistical-analysis sub-component.
833    pub fn statistical_analysis(&self) -> &StatisticalAnalysis {
834        &self.statistical_analysis
835    }
836
837    /// Mutably borrow the statistical-analysis sub-component.
838    pub fn statistical_analysis_mut(&mut self) -> &mut StatisticalAnalysis {
839        &mut self.statistical_analysis
840    }
841}
842
843impl ProbabilityAnalysis {
844    /// Creates a `ProbabilityAnalysis` with empty registries / default configuration.
845    pub fn new() -> Self {
846        Self {
847            probability_distribution: ProbabilityDistribution::Weibull,
848            reliability_function: ReliabilityFunction::new(),
849        }
850    }
851}
852
853impl ReliabilityFunction {
854    /// Creates a `ReliabilityFunction` with empty registries / default configuration.
855    pub fn new() -> Self {
856        Self {
857            function_type: ReliabilityFunctionType::Weibull,
858            parameters: vec![2.0, 1000.0],
859        }
860    }
861}
862
863impl StatisticalAnalysis {
864    /// Creates a `StatisticalAnalysis` with empty registries / default configuration.
865    pub fn new() -> Self {
866        Self {
867            confidence_interval: ConfidenceInterval::new(),
868            hypothesis_testing: HypothesisTesting::new(),
869        }
870    }
871}
872
873impl ConfidenceInterval {
874    /// Creates a `ConfidenceInterval` with empty registries / default configuration.
875    pub fn new() -> Self {
876        Self {
877            confidence_level: 0.95,
878            lower_bound: 0.0,
879            upper_bound: 1.0,
880        }
881    }
882}
883
884impl HypothesisTesting {
885    /// Creates a `HypothesisTesting` with empty registries / default configuration.
886    pub fn new() -> Self {
887        Self {
888            null_hypothesis: "No failure".to_string(),
889            alternative_hypothesis: "Failure occurs".to_string(),
890            test_statistic: 1.96,
891            p_value: 0.05,
892        }
893    }
894}
895
896impl MonteCarlo {
897    /// Creates a `MonteCarlo` with empty registries / default configuration.
898    pub fn new() -> Self {
899        Self {
900            num_simulations: 10000,
901            random_variables: Vec::new(),
902            simulation_results: Vec::new(),
903        }
904    }
905
906    /// Generate `num_sims` random samples drawn from a normal distribution with
907    /// the given `mean` and `std_dev`, using the Box–Muller transform. The samples
908    /// are also stored in `simulation_results` for later inspection.
909    pub fn run_simulation(&mut self, mean: f64, std_dev: f64, num_sims: usize) -> Vec<f64> {
910        let mut samples = Vec::with_capacity(num_sims);
911        for _ in 0..num_sims {
912            let z = standard_normal_sample();
913            samples.push(mean + std_dev * z);
914        }
915        self.simulation_results = samples.clone();
916        self.num_simulations = num_sims as u32;
917        samples
918    }
919}
920
921impl RandomVariable {
922    /// Creates a `RandomVariable` with empty registries / default configuration.
923    pub fn new() -> Self {
924        Self {
925            variable_name: "load".to_string(),
926            distribution: ProbabilityDistribution::Normal,
927            parameters: vec![100.0, 10.0],
928        }
929    }
930}
931
932impl FailureAnalysis {
933    /// Creates a `FailureAnalysis` with empty registries / default configuration.
934    pub fn new() -> Self {
935        Self {
936            failure_modes: FailureModes::new(),
937            fault_tree: FaultTree::new(),
938            fmea: FMEA::new(),
939        }
940    }
941
942    /// Readies `FailureAnalysis`; initializes any owned sub-engines (no-op for leaf structs).
943    pub fn initialize(&mut self) -> Result<(), EngineeringError> {
944        Ok(())
945    }
946
947    /// Borrow the failure-modes sub-component.
948    pub fn failure_modes(&self) -> &FailureModes {
949        &self.failure_modes
950    }
951
952    /// Mutably borrow the failure-modes sub-component.
953    pub fn failure_modes_mut(&mut self) -> &mut FailureModes {
954        &mut self.failure_modes
955    }
956
957    /// Borrow the fault-tree sub-component.
958    pub fn fault_tree(&self) -> &FaultTree {
959        &self.fault_tree
960    }
961
962    /// Mutably borrow the fault-tree sub-component.
963    pub fn fault_tree_mut(&mut self) -> &mut FaultTree {
964        &mut self.fault_tree
965    }
966
967    /// Borrow the FMEA sub-component.
968    pub fn fmea(&self) -> &FMEA {
969        &self.fmea
970    }
971
972    /// Mutably borrow the FMEA sub-component.
973    pub fn fmea_mut(&mut self) -> &mut FMEA {
974        &mut self.fmea
975    }
976}
977
978impl FailureModes {
979    /// Creates a `FailureModes` with empty registries / default configuration.
980    pub fn new() -> Self {
981        Self {
982            failure_mode_id: "fm_1".to_string(),
983            failure_mode_name: "Fracture".to_string(),
984            failure_causes: Vec::new(),
985            failure_effects: Vec::new(),
986        }
987    }
988}
989
990impl FaultTree {
991    /// Creates a `FaultTree` with empty registries / default configuration.
992    pub fn new() -> Self {
993        Self {
994            tree_id: "ft_1".to_string(),
995            top_event: "System Failure".to_string(),
996            logic_gates: Vec::new(),
997            basic_events: Vec::new(),
998        }
999    }
1000}
1001
1002impl FMEA {
1003    /// Creates a `FMEA` with empty registries / default configuration.
1004    pub fn new() -> Self {
1005        Self {
1006            fmea_id: "fmea_1".to_string(),
1007            failure_modes: Vec::new(),
1008        }
1009    }
1010}
1011
1012impl MaintenanceOptimization {
1013    /// Creates a `MaintenanceOptimization` with empty registries / default configuration.
1014    pub fn new() -> Self {
1015        Self {
1016            preventive_maintenance: PreventiveMaintenance::new(),
1017            predictive_maintenance: PredictiveMaintenance::new(),
1018            condition_based_maintenance: ConditionBasedMaintenance::new(),
1019        }
1020    }
1021
1022    /// Readies `MaintenanceOptimization`; initializes any owned sub-engines (no-op for leaf structs).
1023    pub fn initialize(&mut self) -> Result<(), EngineeringError> {
1024        Ok(())
1025    }
1026
1027    /// Borrow the preventive-maintenance sub-component.
1028    pub fn preventive_maintenance(&self) -> &PreventiveMaintenance {
1029        &self.preventive_maintenance
1030    }
1031
1032    /// Mutably borrow the preventive-maintenance sub-component.
1033    pub fn preventive_maintenance_mut(&mut self) -> &mut PreventiveMaintenance {
1034        &mut self.preventive_maintenance
1035    }
1036
1037    /// Borrow the predictive-maintenance sub-component.
1038    pub fn predictive_maintenance(&self) -> &PredictiveMaintenance {
1039        &self.predictive_maintenance
1040    }
1041
1042    /// Mutably borrow the predictive-maintenance sub-component.
1043    pub fn predictive_maintenance_mut(&mut self) -> &mut PredictiveMaintenance {
1044        &mut self.predictive_maintenance
1045    }
1046
1047    /// Borrow the condition-based-maintenance sub-component.
1048    pub fn condition_based_maintenance(&self) -> &ConditionBasedMaintenance {
1049        &self.condition_based_maintenance
1050    }
1051
1052    /// Mutably borrow the condition-based-maintenance sub-component.
1053    pub fn condition_based_maintenance_mut(&mut self) -> &mut ConditionBasedMaintenance {
1054        &mut self.condition_based_maintenance
1055    }
1056}
1057
1058impl PreventiveMaintenance {
1059    /// Creates a `PreventiveMaintenance` with empty registries / default configuration.
1060    pub fn new() -> Self {
1061        Self {
1062            maintenance_interval: 30,
1063            maintenance_tasks: Vec::new(),
1064        }
1065    }
1066}
1067
1068impl MaintenanceTask {
1069    /// Creates a `MaintenanceTask` with empty registries / default configuration.
1070    pub fn new() -> Self {
1071        Self {
1072            task_id: "task_1".to_string(),
1073            task_name: "Inspection".to_string(),
1074            task_duration: 2.0,
1075            task_cost: 100.0,
1076        }
1077    }
1078}
1079
1080impl PredictiveMaintenance {
1081    /// Creates a `PredictiveMaintenance` with empty registries / default configuration.
1082    pub fn new() -> Self {
1083        Self {
1084            prediction_model: PredictionModel::Weibull,
1085            prediction_horizon: 90,
1086        }
1087    }
1088}
1089
1090impl ConditionBasedMaintenance {
1091    /// Creates a `ConditionBasedMaintenance` with empty registries / default configuration.
1092    pub fn new() -> Self {
1093        Self {
1094            monitoring_parameters: Vec::new(),
1095            threshold_values: Vec::new(),
1096        }
1097    }
1098}
1099
1100impl MonitoringParameter {
1101    /// Creates a `MonitoringParameter` with empty registries / default configuration.
1102    pub fn new() -> Self {
1103        Self {
1104            parameter_name: "vibration".to_string(),
1105            measurement_method: MeasurementMethod::Vibration,
1106        }
1107    }
1108}