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, constants::PLANCK_H
61            ));
62            report.constants_valid = false;
63        }
64
65        // Validate reduced Planck constant
66        if (constants::PLANCK_HBAR - expected_hbar).abs() > 1e-42 {
67            report.issues.push(format!(
68                "Reduced Planck constant deviation: expected {:.10e}, got {:.10e}",
69                expected_hbar, constants::PLANCK_HBAR
70            ));
71            report.constants_valid = false;
72        }
73
74        // Validate relationship
75        let calculated_hbar = constants::PLANCK_H / (2.0 * PI);
76        if (constants::PLANCK_HBAR - calculated_hbar).abs() > 1e-50 {
77            report.issues.push(format!(
78                "Planck constant relationship violated: ℏ ≠ h/(2π), error = {:.2e}",
79                (constants::PLANCK_HBAR - calculated_hbar).abs()
80            ));
81            report.constants_valid = false;
82        }
83
84        // Validate positivity
85        if constants::PLANCK_H <= 0.0 || constants::PLANCK_HBAR <= 0.0 {
86            report.issues.push("Planck constants must be positive".to_string());
87            report.constants_valid = false;
88        }
89    }
90
91    /// Validate Boltzmann constant
92    fn validate_boltzmann_constant(report: &mut PhysicsValidationReport) {
93        let expected_kb = 1.380_649e-23; // CODATA 2018
94
95        if (constants::BOLTZMANN_K - expected_kb).abs() > 1e-31 {
96            report.issues.push(format!(
97                "Boltzmann constant deviation: expected {:.10e}, got {:.10e}",
98                expected_kb, constants::BOLTZMANN_K
99            ));
100            report.constants_valid = false;
101        }
102
103        if constants::BOLTZMANN_K <= 0.0 {
104            report.issues.push("Boltzmann constant must be positive".to_string());
105            report.constants_valid = false;
106        }
107    }
108
109    /// Validate speed of light
110    fn validate_speed_of_light(report: &mut PhysicsValidationReport) {
111        let expected_c = 299_792_458.0; // Exact by definition
112
113        if (constants::SPEED_OF_LIGHT - expected_c).abs() > 1e-6 {
114            report.issues.push(format!(
115                "Speed of light deviation: expected {:.1}, got {:.1}",
116                expected_c, constants::SPEED_OF_LIGHT
117            ));
118            report.constants_valid = false;
119        }
120
121        if constants::SPEED_OF_LIGHT <= 0.0 {
122            report.issues.push("Speed of light must be positive".to_string());
123            report.constants_valid = false;
124        }
125    }
126
127    /// Validate electron volt conversion
128    fn validate_electron_volt_conversion(report: &mut PhysicsValidationReport) {
129        let expected_ev_to_j = 1.602_176_634e-19; // CODATA 2018
130
131        if (constants::EV_TO_JOULES - expected_ev_to_j).abs() > 1e-27 {
132            report.issues.push(format!(
133                "eV to Joules conversion deviation: expected {:.10e}, got {:.10e}",
134                expected_ev_to_j, constants::EV_TO_JOULES
135            ));
136            report.constants_valid = false;
137        }
138
139        if constants::EV_TO_JOULES <= 0.0 {
140            report.issues.push("eV to Joules conversion must be positive".to_string());
141            report.constants_valid = false;
142        }
143    }
144
145    /// Validate derived constants
146    fn validate_derived_constants(report: &mut PhysicsValidationReport) {
147        // Validate room temperature (should be reasonable)
148        if constants::ROOM_TEMPERATURE_K < 250.0 || constants::ROOM_TEMPERATURE_K > 350.0 {
149            report.warnings.push(format!(
150                "Room temperature seems unusual: {:.1} K",
151                constants::ROOM_TEMPERATURE_K
152            ));
153        }
154
155        // Validate thermal energy at room temperature
156        let thermal_energy = constants::BOLTZMANN_K * constants::ROOM_TEMPERATURE_K;
157        let thermal_energy_ev = thermal_energy / constants::EV_TO_JOULES;
158
159        if thermal_energy_ev < 0.020 || thermal_energy_ev > 0.030 {
160            report.warnings.push(format!(
161                "Room temperature thermal energy unusual: {:.3} eV (expected ~0.025 eV)",
162                thermal_energy_ev
163            ));
164        }
165
166        // Validate minimum uncertainty product
167        let min_uncertainty = constants::PLANCK_HBAR / 2.0;
168        if min_uncertainty <= 0.0 {
169            report.issues.push("Minimum uncertainty product must be positive".to_string());
170            report.constants_valid = false;
171        }
172    }
173
174    /// Validate consciousness-specific constants
175    fn validate_consciousness_constants(report: &mut PhysicsValidationReport) {
176        // Validate attosecond energy requirement
177        if constants::ATTOSECOND_ENERGY_KEV <= 0.0 {
178            report.issues.push("Attosecond energy requirement must be positive".to_string());
179            report.constants_valid = false;
180        }
181
182        if constants::ATTOSECOND_ENERGY_KEV < 0.5 || constants::ATTOSECOND_ENERGY_KEV > 5.0 {
183            report.warnings.push(format!(
184                "Attosecond energy requirement seems unusual: {:.2} keV",
185                constants::ATTOSECOND_ENERGY_KEV
186            ));
187        }
188
189        // Validate consciousness scale
190        if constants::CONSCIOUSNESS_SCALE_NS != 1e-9 {
191            report.issues.push(format!(
192                "Consciousness scale incorrect: expected 1e-9, got {:.2e}",
193                constants::CONSCIOUSNESS_SCALE_NS
194            ));
195            report.constants_valid = false;
196        }
197
198        // Validate that attosecond operation requires substantial energy
199        let attosecond_energy_j = constants::ATTOSECOND_ENERGY_KEV * 1000.0 * constants::EV_TO_JOULES;
200        let thermal_energy_j = constants::BOLTZMANN_K * constants::ROOM_TEMPERATURE_K;
201        let energy_ratio = attosecond_energy_j / thermal_energy_j;
202
203        if energy_ratio < 1000.0 {
204            report.warnings.push(format!(
205                "Attosecond energy only {:.0}x thermal energy (expected >1000x)",
206                energy_ratio
207            ));
208        }
209    }
210
211    /// Validate computational bounds
212    fn validate_computational_bounds(report: &mut PhysicsValidationReport) {
213        // Test Margolus-Levitin bound calculation
214        let test_energy = 1e-15; // 1 fJ
215        let min_time = constants::PLANCK_H / (4.0 * test_energy);
216
217        if min_time <= 0.0 || !min_time.is_finite() {
218            report.issues.push("Margolus-Levitin calculation produces invalid result".to_string());
219            report.computational_bounds_valid = false;
220        }
221
222        if min_time > 1e-15 {
223            report.warnings.push(format!(
224                "Margolus-Levitin time seems large for 1 fJ: {:.2e} s",
225                min_time
226            ));
227        }
228
229        // Test uncertainty principle calculation
230        let uncertainty_product = test_energy * min_time;
231        let min_uncertainty = constants::PLANCK_HBAR / 2.0;
232
233        if uncertainty_product < min_uncertainty {
234            report.issues.push(format!(
235                "Uncertainty principle violation in test: ΔE·Δt = {:.2e} < ℏ/2 = {:.2e}",
236                uncertainty_product, min_uncertainty
237            ));
238            report.computational_bounds_valid = false;
239        }
240
241        // Test energy scale boundaries
242        let max_reasonable_energy = 1e-12; // 1 pJ
243        let min_reasonable_energy = 1e-21; // 1 zJ
244
245        if constants::PLANCK_H / (4.0 * max_reasonable_energy) > 1e-18 {
246            report.warnings.push("Maximum energy bound may be too restrictive".to_string());
247        }
248
249        if constants::PLANCK_H / (4.0 * min_reasonable_energy) < 1e-15 {
250            report.warnings.push("Minimum energy bound may be too permissive".to_string());
251        }
252    }
253
254    /// Validate numerical stability
255    fn validate_numerical_stability(report: &mut PhysicsValidationReport) {
256        // Test precision at extreme scales
257        let very_small = 1e-30;
258        let very_large = 1e30;
259
260        // Test that calculations don't overflow/underflow
261        let product: f64 = very_small * very_large;
262        if !product.is_finite() || product == 0.0 {
263            report.issues.push("Numerical instability in extreme scale calculations".to_string());
264            report.numerical_stability_valid = false;
265        }
266
267        // Test floating point precision near physical constants
268        let h_plus_epsilon = constants::PLANCK_H + 1e-50;
269        if h_plus_epsilon == constants::PLANCK_H {
270            report.warnings.push("Limited floating point precision near Planck constant".to_string());
271        }
272
273        // Test reciprocal calculations
274        let energy = 1e-15;
275        let time1 = constants::PLANCK_H / (4.0 * energy);
276        let energy_back = constants::PLANCK_H / (4.0 * time1);
277        let relative_error = (energy - energy_back).abs() / energy;
278
279        if relative_error > 1e-14 {
280            report.warnings.push(format!(
281                "Numerical precision loss in reciprocal calculations: {:.2e} relative error",
282                relative_error
283            ));
284        }
285
286        // Test trigonometric precision in hbar calculation
287        let hbar_calculated = constants::PLANCK_H / (2.0 * PI);
288        let relative_error_hbar = (constants::PLANCK_HBAR - hbar_calculated).abs() / constants::PLANCK_HBAR;
289
290        if relative_error_hbar > 1e-15 {
291            report.warnings.push(format!(
292                "Numerical precision loss in ℏ calculation: {:.2e} relative error",
293                relative_error_hbar
294            ));
295        }
296    }
297
298    /// Generate physics validation summary
299    pub fn generate_summary(report: &PhysicsValidationReport) -> String {
300        let mut summary = String::new();
301
302        summary.push_str("🔬 Physics Constants & Computational Bounds Validation\\n");
303        summary.push_str("=====================================================\\n\\n");
304
305        // Overall status
306        if report.constants_valid && report.computational_bounds_valid && report.numerical_stability_valid {
307            summary.push_str("✅ Overall Status: PASS\\n");
308        } else {
309            summary.push_str("❌ Overall Status: FAIL\\n");
310        }
311
312        summary.push_str(&format!("   Constants Valid: {}\\n",
313                                 if report.constants_valid { "✅" } else { "❌" }));
314        summary.push_str(&format!("   Computational Bounds Valid: {}\\n",
315                                 if report.computational_bounds_valid { "✅" } else { "❌" }));
316        summary.push_str(&format!("   Numerical Stability Valid: {}\\n\\n",
317                                 if report.numerical_stability_valid { "✅" } else { "❌" }));
318
319        // Issues
320        if !report.issues.is_empty() {
321            summary.push_str("🚨 Issues:\\n");
322            for issue in &report.issues {
323                summary.push_str(&format!("   • {}\\n", issue));
324            }
325            summary.push_str("\\n");
326        }
327
328        // Warnings
329        if !report.warnings.is_empty() {
330            summary.push_str("⚠️  Warnings:\\n");
331            for warning in &report.warnings {
332                summary.push_str(&format!("   • {}\\n", warning));
333            }
334            summary.push_str("\\n");
335        }
336
337        // Recommendations
338        if !report.recommendations.is_empty() {
339            summary.push_str("💡 Recommendations:\\n");
340            for rec in &report.recommendations {
341                summary.push_str(&format!("   • {}\\n", rec));
342            }
343            summary.push_str("\\n");
344        }
345
346        // Physical constant values
347        summary.push_str("📏 Physical Constants:\\n");
348        summary.push_str(&format!("   Planck constant (h): {:.10e} J⋅s\\n", constants::PLANCK_H));
349        summary.push_str(&format!("   Reduced Planck (ℏ): {:.10e} J⋅s\\n", constants::PLANCK_HBAR));
350        summary.push_str(&format!("   Boltzmann (kB): {:.10e} J/K\\n", constants::BOLTZMANN_K));
351        summary.push_str(&format!("   Speed of light (c): {:.0} m/s\\n", constants::SPEED_OF_LIGHT));
352        summary.push_str(&format!("   eV to Joules: {:.10e}\\n", constants::EV_TO_JOULES));
353        summary.push_str(&format!("   Room temperature: {:.1} K\\n", constants::ROOM_TEMPERATURE_K));
354        summary.push_str(&format!("   Attosecond energy: {:.2} keV\\n", constants::ATTOSECOND_ENERGY_KEV));
355        summary.push_str(&format!("   Consciousness scale: {:.0e} s\\n", constants::CONSCIOUSNESS_SCALE_NS));
356
357        // Computational bounds
358        summary.push_str("\\n🧮 Computational Bounds:\\n");
359        let test_energy = 1e-15;
360        let min_time = constants::PLANCK_H / (4.0 * test_energy);
361        let min_uncertainty = constants::PLANCK_HBAR / 2.0;
362        let thermal_energy = constants::BOLTZMANN_K * constants::ROOM_TEMPERATURE_K;
363
364        summary.push_str(&format!("   Min time (1 fJ): {:.2e} s\\n", min_time));
365        summary.push_str(&format!("   Min uncertainty: {:.2e} J⋅s\\n", min_uncertainty));
366        summary.push_str(&format!("   Thermal energy: {:.2e} J ({:.1} meV)\\n",
367                                 thermal_energy, thermal_energy / constants::EV_TO_JOULES * 1000.0));
368
369        summary
370    }
371
372    /// Quick validation check for runtime use
373    pub fn quick_check() -> bool {
374        // Essential checks that must pass
375        constants::PLANCK_H > 0.0 &&
376        constants::PLANCK_HBAR > 0.0 &&
377        constants::BOLTZMANN_K > 0.0 &&
378        constants::SPEED_OF_LIGHT > 0.0 &&
379        constants::EV_TO_JOULES > 0.0 &&
380        (constants::PLANCK_HBAR - constants::PLANCK_H / (2.0 * PI)).abs() < 1e-40 &&
381        constants::CONSCIOUSNESS_SCALE_NS == 1e-9
382    }
383}
384
385#[cfg(test)]
386mod tests {
387    use super::*;
388
389    #[test]
390    fn test_physics_validation() {
391        let report = PhysicsValidator::validate_constants();
392
393        // Print full report for debugging
394        if !report.constants_valid || !report.computational_bounds_valid || !report.numerical_stability_valid {
395            println!("{}", PhysicsValidator::generate_summary(&report));
396        }
397
398        assert!(report.constants_valid, "Physics constants must be valid");
399        assert!(report.computational_bounds_valid, "Computational bounds must be valid");
400        assert!(report.numerical_stability_valid, "Numerical calculations must be stable");
401    }
402
403    #[test]
404    fn test_quick_check() {
405        assert!(PhysicsValidator::quick_check(), "Quick physics check must pass");
406    }
407
408    #[test]
409    fn test_constant_relationships() {
410        // Test fundamental relationships
411        let calculated_hbar = constants::PLANCK_H / (2.0 * PI);
412        assert!((constants::PLANCK_HBAR - calculated_hbar).abs() < 1e-40);
413
414        // Test unit conversions
415        let one_ev_in_joules = constants::EV_TO_JOULES;
416        assert!(one_ev_in_joules > 1e-20 && one_ev_in_joules < 1e-18);
417
418        // Test energy scales
419        let thermal_energy = constants::BOLTZMANN_K * constants::ROOM_TEMPERATURE_K;
420        let thermal_ev = thermal_energy / constants::EV_TO_JOULES;
421        assert!(thermal_ev > 0.02 && thermal_ev < 0.03); // ~25 meV
422
423        // Test attosecond energy
424        let attosecond_energy_j = constants::ATTOSECOND_ENERGY_KEV * 1000.0 * constants::EV_TO_JOULES;
425        assert!(attosecond_energy_j > thermal_energy * 1000.0);
426    }
427
428    #[test]
429    fn test_numerical_precision() {
430        // Test that we can distinguish small differences
431        let base = constants::PLANCK_H;
432        let epsilon = base * 1e-15;
433        assert!(base + epsilon > base);
434
435        // Test reciprocal precision
436        let energy = 1e-15;
437        let time = constants::PLANCK_H / (4.0 * energy);
438        let energy_back = constants::PLANCK_H / (4.0 * time);
439        let relative_error = (energy - energy_back).abs() / energy;
440        assert!(relative_error < 1e-12);
441    }
442
443    #[test]
444    fn test_physical_reasonableness() {
445        // Test that calculated times are physically reasonable
446        let femtojoule = 1e-15;
447        let min_time = constants::PLANCK_H / (4.0 * femtojoule);
448        assert!(min_time > 1e-25); // Much larger than Planck time
449        assert!(min_time < 1e-15); // Much smaller than femtosecond
450
451        // Test that uncertainty product is reasonable
452        let uncertainty_product = femtojoule * min_time;
453        let min_uncertainty = constants::PLANCK_HBAR / 2.0;
454        assert!(uncertainty_product >= min_uncertainty);
455
456        // Test consciousness time scale
457        assert_eq!(constants::CONSCIOUSNESS_SCALE_NS, 1e-9);
458        let ns_energy = constants::PLANCK_H / (4.0 * constants::CONSCIOUSNESS_SCALE_NS);
459        let ns_energy_ev = ns_energy / constants::EV_TO_JOULES;
460        assert!(ns_energy_ev < 1.0); // Should be sub-eV
461    }
462}