Skip to main content

sublinear_solver/temporal_nexus/quantum/
physics_validation.rs

1//! Physics Constants and Computational Bounds Validation
2//!
3//! This module provides comprehensive validation of physical constants
4//! and computational bounds used throughout the quantum validation framework.
5//! It ensures that all constants are within accepted ranges and that
6//! computational algorithms are numerically stable.
7
8use super::constants;
9use std::f64::consts::PI;
10
11/// Physics constants validation report
12#[derive(Debug, Clone)]
13pub struct PhysicsValidationReport {
14    pub constants_valid: bool,
15    pub computational_bounds_valid: bool,
16    pub numerical_stability_valid: bool,
17    pub issues: Vec<String>,
18    pub warnings: Vec<String>,
19    pub recommendations: Vec<String>,
20}
21
22/// Comprehensive physics validation suite
23pub struct PhysicsValidator;
24
25impl PhysicsValidator {
26    /// Validate all physics constants against known values
27    pub fn validate_constants() -> PhysicsValidationReport {
28        let mut report = PhysicsValidationReport {
29            constants_valid: true,
30            computational_bounds_valid: true,
31            numerical_stability_valid: true,
32            issues: Vec::new(),
33            warnings: Vec::new(),
34            recommendations: Vec::new(),
35        };
36
37        // Validate fundamental constants
38        Self::validate_planck_constants(&mut report);
39        Self::validate_boltzmann_constant(&mut report);
40        Self::validate_speed_of_light(&mut report);
41        Self::validate_electron_volt_conversion(&mut report);
42        Self::validate_derived_constants(&mut report);
43        Self::validate_consciousness_constants(&mut report);
44        Self::validate_computational_bounds(&mut report);
45        Self::validate_numerical_stability(&mut report);
46
47        report
48    }
49
50    /// Validate Planck constants
51    fn validate_planck_constants(report: &mut PhysicsValidationReport) {
52        // CODATA 2018 values
53        let expected_h = 6.626_070_15e-34;
54        let expected_hbar = expected_h / (2.0 * PI);
55
56        // Validate Planck constant
57        if (constants::PLANCK_H - expected_h).abs() > 1e-42 {
58            report.issues.push(format!(
59                "Planck constant deviation: expected {:.10e}, got {:.10e}",
60                expected_h,
61                constants::PLANCK_H
62            ));
63            report.constants_valid = false;
64        }
65
66        // Validate reduced Planck constant
67        if (constants::PLANCK_HBAR - expected_hbar).abs() > 1e-42 {
68            report.issues.push(format!(
69                "Reduced Planck constant deviation: expected {:.10e}, got {:.10e}",
70                expected_hbar,
71                constants::PLANCK_HBAR
72            ));
73            report.constants_valid = false;
74        }
75
76        // Validate the relationship ℏ = h/(2π). The absolute tolerance was
77        // 1e-50 — five orders of magnitude tighter than f64 can represent
78        // at these scales (ULP at ~1e-34 is ≈ 2e-50, but the stored ℏ has
79        // only ~10 significant digits, so realistic error is ~6e-44).
80        // Use a relative tolerance instead, matched to the precision of
81        // the stored constant.
82        let calculated_hbar = constants::PLANCK_H / (2.0 * PI);
83        let rel_err = (constants::PLANCK_HBAR - calculated_hbar).abs() / calculated_hbar;
84        if rel_err > 1e-9 {
85            report.issues.push(format!(
86                "Planck constant relationship violated: ℏ ≠ h/(2π), relative error = {:.2e}",
87                rel_err
88            ));
89            report.constants_valid = false;
90        }
91
92        // Validate positivity
93        if constants::PLANCK_H <= 0.0 || constants::PLANCK_HBAR <= 0.0 {
94            report
95                .issues
96                .push("Planck constants must be positive".to_string());
97            report.constants_valid = false;
98        }
99    }
100
101    /// Validate Boltzmann constant
102    fn validate_boltzmann_constant(report: &mut PhysicsValidationReport) {
103        let expected_kb = 1.380_649e-23; // CODATA 2018
104
105        if (constants::BOLTZMANN_K - expected_kb).abs() > 1e-31 {
106            report.issues.push(format!(
107                "Boltzmann constant deviation: expected {:.10e}, got {:.10e}",
108                expected_kb,
109                constants::BOLTZMANN_K
110            ));
111            report.constants_valid = false;
112        }
113
114        if constants::BOLTZMANN_K <= 0.0 {
115            report
116                .issues
117                .push("Boltzmann constant must be positive".to_string());
118            report.constants_valid = false;
119        }
120    }
121
122    /// Validate speed of light
123    fn validate_speed_of_light(report: &mut PhysicsValidationReport) {
124        let expected_c = 299_792_458.0; // Exact by definition
125
126        if (constants::SPEED_OF_LIGHT - expected_c).abs() > 1e-6 {
127            report.issues.push(format!(
128                "Speed of light deviation: expected {:.1}, got {:.1}",
129                expected_c,
130                constants::SPEED_OF_LIGHT
131            ));
132            report.constants_valid = false;
133        }
134
135        if constants::SPEED_OF_LIGHT <= 0.0 {
136            report
137                .issues
138                .push("Speed of light must be positive".to_string());
139            report.constants_valid = false;
140        }
141    }
142
143    /// Validate electron volt conversion
144    fn validate_electron_volt_conversion(report: &mut PhysicsValidationReport) {
145        let expected_ev_to_j = 1.602_176_634e-19; // CODATA 2018
146
147        if (constants::EV_TO_JOULES - expected_ev_to_j).abs() > 1e-27 {
148            report.issues.push(format!(
149                "eV to Joules conversion deviation: expected {:.10e}, got {:.10e}",
150                expected_ev_to_j,
151                constants::EV_TO_JOULES
152            ));
153            report.constants_valid = false;
154        }
155
156        if constants::EV_TO_JOULES <= 0.0 {
157            report
158                .issues
159                .push("eV to Joules conversion must be positive".to_string());
160            report.constants_valid = false;
161        }
162    }
163
164    /// Validate derived constants
165    fn validate_derived_constants(report: &mut PhysicsValidationReport) {
166        // Validate room temperature (should be reasonable)
167        if constants::ROOM_TEMPERATURE_K < 250.0 || constants::ROOM_TEMPERATURE_K > 350.0 {
168            report.warnings.push(format!(
169                "Room temperature seems unusual: {:.1} K",
170                constants::ROOM_TEMPERATURE_K
171            ));
172        }
173
174        // Validate thermal energy at room temperature
175        let thermal_energy = constants::BOLTZMANN_K * constants::ROOM_TEMPERATURE_K;
176        let thermal_energy_ev = thermal_energy / constants::EV_TO_JOULES;
177
178        if thermal_energy_ev < 0.020 || thermal_energy_ev > 0.030 {
179            report.warnings.push(format!(
180                "Room temperature thermal energy unusual: {:.3} eV (expected ~0.025 eV)",
181                thermal_energy_ev
182            ));
183        }
184
185        // Validate minimum uncertainty product
186        let min_uncertainty = constants::PLANCK_HBAR / 2.0;
187        if min_uncertainty <= 0.0 {
188            report
189                .issues
190                .push("Minimum uncertainty product must be positive".to_string());
191            report.constants_valid = false;
192        }
193    }
194
195    /// Validate consciousness-specific constants
196    fn validate_consciousness_constants(report: &mut PhysicsValidationReport) {
197        // Validate attosecond energy requirement
198        if constants::ATTOSECOND_ENERGY_KEV <= 0.0 {
199            report
200                .issues
201                .push("Attosecond energy requirement must be positive".to_string());
202            report.constants_valid = false;
203        }
204
205        if constants::ATTOSECOND_ENERGY_KEV < 0.5 || constants::ATTOSECOND_ENERGY_KEV > 5.0 {
206            report.warnings.push(format!(
207                "Attosecond energy requirement seems unusual: {:.2} keV",
208                constants::ATTOSECOND_ENERGY_KEV
209            ));
210        }
211
212        // Validate consciousness scale
213        if constants::CONSCIOUSNESS_SCALE_NS != 1e-9 {
214            report.issues.push(format!(
215                "Consciousness scale incorrect: expected 1e-9, got {:.2e}",
216                constants::CONSCIOUSNESS_SCALE_NS
217            ));
218            report.constants_valid = false;
219        }
220
221        // Validate that attosecond operation requires substantial energy
222        let attosecond_energy_j =
223            constants::ATTOSECOND_ENERGY_KEV * 1000.0 * constants::EV_TO_JOULES;
224        let thermal_energy_j = constants::BOLTZMANN_K * constants::ROOM_TEMPERATURE_K;
225        let energy_ratio = attosecond_energy_j / thermal_energy_j;
226
227        if energy_ratio < 1000.0 {
228            report.warnings.push(format!(
229                "Attosecond energy only {:.0}x thermal energy (expected >1000x)",
230                energy_ratio
231            ));
232        }
233    }
234
235    /// Validate computational bounds
236    fn validate_computational_bounds(report: &mut PhysicsValidationReport) {
237        // Test Margolus-Levitin bound calculation
238        let test_energy = 1e-15; // 1 fJ
239        let min_time = constants::PLANCK_H / (4.0 * test_energy);
240
241        if min_time <= 0.0 || !min_time.is_finite() {
242            report
243                .issues
244                .push("Margolus-Levitin calculation produces invalid result".to_string());
245            report.computational_bounds_valid = false;
246        }
247
248        if min_time > 1e-15 {
249            report.warnings.push(format!(
250                "Margolus-Levitin time seems large for 1 fJ: {:.2e} s",
251                min_time
252            ));
253        }
254
255        // Test uncertainty principle calculation
256        let uncertainty_product = test_energy * min_time;
257        let min_uncertainty = constants::PLANCK_HBAR / 2.0;
258
259        if uncertainty_product < min_uncertainty {
260            report.issues.push(format!(
261                "Uncertainty principle violation in test: ΔE·Δt = {:.2e} < ℏ/2 = {:.2e}",
262                uncertainty_product, min_uncertainty
263            ));
264            report.computational_bounds_valid = false;
265        }
266
267        // Test energy scale boundaries
268        let max_reasonable_energy = 1e-12; // 1 pJ
269        let min_reasonable_energy = 1e-21; // 1 zJ
270
271        if constants::PLANCK_H / (4.0 * max_reasonable_energy) > 1e-18 {
272            report
273                .warnings
274                .push("Maximum energy bound may be too restrictive".to_string());
275        }
276
277        if constants::PLANCK_H / (4.0 * min_reasonable_energy) < 1e-15 {
278            report
279                .warnings
280                .push("Minimum energy bound may be too permissive".to_string());
281        }
282    }
283
284    /// Validate numerical stability
285    fn validate_numerical_stability(report: &mut PhysicsValidationReport) {
286        // Test precision at extreme scales
287        let very_small = 1e-30;
288        let very_large = 1e30;
289
290        // Test that calculations don't overflow/underflow
291        let product: f64 = very_small * very_large;
292        if !product.is_finite() || product == 0.0 {
293            report
294                .issues
295                .push("Numerical instability in extreme scale calculations".to_string());
296            report.numerical_stability_valid = false;
297        }
298
299        // Test floating point precision near physical constants
300        let h_plus_epsilon = constants::PLANCK_H + 1e-50;
301        if h_plus_epsilon == constants::PLANCK_H {
302            report
303                .warnings
304                .push("Limited floating point precision near Planck constant".to_string());
305        }
306
307        // Test reciprocal calculations
308        let energy = 1e-15;
309        let time1 = constants::PLANCK_H / (4.0 * energy);
310        let energy_back = constants::PLANCK_H / (4.0 * time1);
311        let relative_error = (energy - energy_back).abs() / energy;
312
313        if relative_error > 1e-14 {
314            report.warnings.push(format!(
315                "Numerical precision loss in reciprocal calculations: {:.2e} relative error",
316                relative_error
317            ));
318        }
319
320        // Test trigonometric precision in hbar calculation
321        let hbar_calculated = constants::PLANCK_H / (2.0 * PI);
322        let relative_error_hbar =
323            (constants::PLANCK_HBAR - hbar_calculated).abs() / constants::PLANCK_HBAR;
324
325        if relative_error_hbar > 1e-15 {
326            report.warnings.push(format!(
327                "Numerical precision loss in ℏ calculation: {:.2e} relative error",
328                relative_error_hbar
329            ));
330        }
331    }
332
333    /// Generate physics validation summary
334    pub fn generate_summary(report: &PhysicsValidationReport) -> String {
335        let mut summary = String::new();
336
337        summary.push_str("🔬 Physics Constants & Computational Bounds Validation\\n");
338        summary.push_str("=====================================================\\n\\n");
339
340        // Overall status
341        if report.constants_valid
342            && report.computational_bounds_valid
343            && report.numerical_stability_valid
344        {
345            summary.push_str("✅ Overall Status: PASS\\n");
346        } else {
347            summary.push_str("❌ Overall Status: FAIL\\n");
348        }
349
350        summary.push_str(&format!(
351            "   Constants Valid: {}\\n",
352            if report.constants_valid { "✅" } else { "❌" }
353        ));
354        summary.push_str(&format!(
355            "   Computational Bounds Valid: {}\\n",
356            if report.computational_bounds_valid {
357                "✅"
358            } else {
359                "❌"
360            }
361        ));
362        summary.push_str(&format!(
363            "   Numerical Stability Valid: {}\\n\\n",
364            if report.numerical_stability_valid {
365                "✅"
366            } else {
367                "❌"
368            }
369        ));
370
371        // Issues
372        if !report.issues.is_empty() {
373            summary.push_str("🚨 Issues:\\n");
374            for issue in &report.issues {
375                summary.push_str(&format!("   • {}\\n", issue));
376            }
377            summary.push_str("\\n");
378        }
379
380        // Warnings
381        if !report.warnings.is_empty() {
382            summary.push_str("⚠️  Warnings:\\n");
383            for warning in &report.warnings {
384                summary.push_str(&format!("   • {}\\n", warning));
385            }
386            summary.push_str("\\n");
387        }
388
389        // Recommendations
390        if !report.recommendations.is_empty() {
391            summary.push_str("💡 Recommendations:\\n");
392            for rec in &report.recommendations {
393                summary.push_str(&format!("   • {}\\n", rec));
394            }
395            summary.push_str("\\n");
396        }
397
398        // Physical constant values
399        summary.push_str("📏 Physical Constants:\\n");
400        summary.push_str(&format!(
401            "   Planck constant (h): {:.10e} J⋅s\\n",
402            constants::PLANCK_H
403        ));
404        summary.push_str(&format!(
405            "   Reduced Planck (ℏ): {:.10e} J⋅s\\n",
406            constants::PLANCK_HBAR
407        ));
408        summary.push_str(&format!(
409            "   Boltzmann (kB): {:.10e} J/K\\n",
410            constants::BOLTZMANN_K
411        ));
412        summary.push_str(&format!(
413            "   Speed of light (c): {:.0} m/s\\n",
414            constants::SPEED_OF_LIGHT
415        ));
416        summary.push_str(&format!(
417            "   eV to Joules: {:.10e}\\n",
418            constants::EV_TO_JOULES
419        ));
420        summary.push_str(&format!(
421            "   Room temperature: {:.1} K\\n",
422            constants::ROOM_TEMPERATURE_K
423        ));
424        summary.push_str(&format!(
425            "   Attosecond energy: {:.2} keV\\n",
426            constants::ATTOSECOND_ENERGY_KEV
427        ));
428        summary.push_str(&format!(
429            "   Consciousness scale: {:.0e} s\\n",
430            constants::CONSCIOUSNESS_SCALE_NS
431        ));
432
433        // Computational bounds
434        summary.push_str("\\n🧮 Computational Bounds:\\n");
435        let test_energy = 1e-15;
436        let min_time = constants::PLANCK_H / (4.0 * test_energy);
437        let min_uncertainty = constants::PLANCK_HBAR / 2.0;
438        let thermal_energy = constants::BOLTZMANN_K * constants::ROOM_TEMPERATURE_K;
439
440        summary.push_str(&format!("   Min time (1 fJ): {:.2e} s\\n", min_time));
441        summary.push_str(&format!(
442            "   Min uncertainty: {:.2e} J⋅s\\n",
443            min_uncertainty
444        ));
445        summary.push_str(&format!(
446            "   Thermal energy: {:.2e} J ({:.1} meV)\\n",
447            thermal_energy,
448            thermal_energy / constants::EV_TO_JOULES * 1000.0
449        ));
450
451        summary
452    }
453
454    /// Quick validation check for runtime use
455    pub fn quick_check() -> bool {
456        // Essential checks that must pass
457        constants::PLANCK_H > 0.0
458            && constants::PLANCK_HBAR > 0.0
459            && constants::BOLTZMANN_K > 0.0
460            && constants::SPEED_OF_LIGHT > 0.0
461            && constants::EV_TO_JOULES > 0.0
462            && (constants::PLANCK_HBAR - constants::PLANCK_H / (2.0 * PI)).abs() < 1e-40
463            && constants::CONSCIOUSNESS_SCALE_NS == 1e-9
464    }
465}
466
467#[cfg(test)]
468mod tests {
469    use super::*;
470
471    #[test]
472    fn test_physics_validation() {
473        let report = PhysicsValidator::validate_constants();
474
475        // Print full report for debugging
476        if !report.constants_valid
477            || !report.computational_bounds_valid
478            || !report.numerical_stability_valid
479        {
480            println!("{}", PhysicsValidator::generate_summary(&report));
481        }
482
483        assert!(report.constants_valid, "Physics constants must be valid");
484        assert!(
485            report.computational_bounds_valid,
486            "Computational bounds must be valid"
487        );
488        assert!(
489            report.numerical_stability_valid,
490            "Numerical calculations must be stable"
491        );
492    }
493
494    #[test]
495    fn test_quick_check() {
496        assert!(
497            PhysicsValidator::quick_check(),
498            "Quick physics check must pass"
499        );
500    }
501
502    #[test]
503    fn test_constant_relationships() {
504        // Test fundamental relationships
505        let calculated_hbar = constants::PLANCK_H / (2.0 * PI);
506        assert!((constants::PLANCK_HBAR - calculated_hbar).abs() < 1e-40);
507
508        // Test unit conversions
509        let one_ev_in_joules = constants::EV_TO_JOULES;
510        assert!(one_ev_in_joules > 1e-20 && one_ev_in_joules < 1e-18);
511
512        // Test energy scales
513        let thermal_energy = constants::BOLTZMANN_K * constants::ROOM_TEMPERATURE_K;
514        let thermal_ev = thermal_energy / constants::EV_TO_JOULES;
515        assert!(thermal_ev > 0.02 && thermal_ev < 0.03); // ~25 meV
516
517        // Test attosecond energy
518        let attosecond_energy_j =
519            constants::ATTOSECOND_ENERGY_KEV * 1000.0 * constants::EV_TO_JOULES;
520        assert!(attosecond_energy_j > thermal_energy * 1000.0);
521    }
522
523    #[test]
524    fn test_numerical_precision() {
525        // Test that we can distinguish small differences
526        let base = constants::PLANCK_H;
527        let epsilon = base * 1e-15;
528        assert!(base + epsilon > base);
529
530        // Test reciprocal precision
531        let energy = 1e-15;
532        let time = constants::PLANCK_H / (4.0 * energy);
533        let energy_back = constants::PLANCK_H / (4.0 * time);
534        let relative_error = (energy - energy_back).abs() / energy;
535        assert!(relative_error < 1e-12);
536    }
537
538    #[test]
539    fn test_physical_reasonableness() {
540        // Test that calculated times are physically reasonable
541        let femtojoule = 1e-15;
542        let min_time = constants::PLANCK_H / (4.0 * femtojoule);
543        assert!(min_time > 1e-25); // Much larger than Planck time
544        assert!(min_time < 1e-15); // Much smaller than femtosecond
545
546        // Test that uncertainty product is reasonable
547        let uncertainty_product = femtojoule * min_time;
548        let min_uncertainty = constants::PLANCK_HBAR / 2.0;
549        assert!(uncertainty_product >= min_uncertainty);
550
551        // Test consciousness time scale
552        assert_eq!(constants::CONSCIOUSNESS_SCALE_NS, 1e-9);
553        let ns_energy = constants::PLANCK_H / (4.0 * constants::CONSCIOUSNESS_SCALE_NS);
554        let ns_energy_ev = ns_energy / constants::EV_TO_JOULES;
555        assert!(ns_energy_ev < 1.0); // Should be sub-eV
556    }
557}