Skip to main content

sublinear_solver/temporal_nexus/quantum/
decoherence.rs

1//! Quantum Decoherence Tracking for Temporal Consciousness
2//!
3//! This module implements realistic quantum decoherence modeling to validate
4//! the feasibility of quantum consciousness operations in real environments.
5//! Decoherence sets practical limits on quantum coherence time and thus
6//! temporal consciousness precision.
7//!
8//! ## Decoherence Mechanisms
9//!
10//! 1. **Thermal Decoherence**: Interaction with thermal environment
11//! 2. **Dephasing**: Loss of phase coherence due to noise
12//! 3. **Relaxation**: Energy dissipation to environment
13//! 4. **Measurement**: Observer-induced decoherence
14//!
15//! ## Decoherence Time Scales
16//!
17//! Typical decoherence times in various environments:
18//! - Room temperature: 10^-12 to 10^-9 seconds
19//! - Cryogenic (mK): 10^-6 to 10^-3 seconds
20//! - Ultra-high vacuum: 10^-9 to 10^-6 seconds
21
22use crate::temporal_nexus::quantum::{constants, QuantumError, QuantumResult};
23use std::collections::HashMap;
24
25/// Quantum decoherence tracker for consciousness operations
26#[derive(Debug, Clone)]
27pub struct DecoherenceTracker {
28    /// Environment temperature (K)
29    temperature: f64,
30    /// Thermal decoherence rate (1/s)
31    thermal_rate: f64,
32    /// Dephasing rate due to noise (1/s)
33    dephasing_rate: f64,
34    /// System-environment coupling strength
35    coupling_strength: f64,
36    /// Environmental noise spectrum parameters
37    noise_spectrum: NoiseSpectrum,
38}
39
40impl DecoherenceTracker {
41    /// Create new decoherence tracker with room temperature defaults
42    pub fn new() -> Self {
43        Self::with_temperature(constants::ROOM_TEMPERATURE_K)
44    }
45
46    /// Create tracker with specific temperature
47    pub fn with_temperature(temperature_k: f64) -> Self {
48        let thermal_rate = Self::calculate_thermal_decoherence_rate(temperature_k);
49        
50        // Pure dephasing is dominated by interactions with the thermal
51        // environment, so it must scale with temperature too — otherwise
52        // a 10 mK cryogenic tracker reports the same coherence time as a
53        // 300 K room-temp tracker (test_cryogenic_environment regression).
54        // Use 1 GHz at room temperature (300 K) as the anchor and scale
55        // linearly; clamped to a 1 Hz floor so f64 inverses stay finite.
56        let dephasing_rate = (1.0e9 * (temperature_k / 300.0)).max(1.0);
57
58        Self {
59            temperature: temperature_k,
60            thermal_rate,
61            dephasing_rate,
62            coupling_strength: 1e-3, // Weak coupling
63            noise_spectrum: NoiseSpectrum::new(temperature_k),
64        }
65    }
66
67    /// Create tracker for cryogenic environment
68    pub fn cryogenic() -> Self {
69        Self::with_temperature(0.01) // 10 mK
70    }
71
72    /// Calculate thermal decoherence rate using Fermi's golden rule
73    fn calculate_thermal_decoherence_rate(temperature_k: f64) -> f64 {
74        if temperature_k <= 0.0 {
75            return 0.0;
76        }
77        
78        let thermal_energy = constants::BOLTZMANN_K * temperature_k;
79        let typical_coupling = 1e-6; // Weak coupling in eV
80        let coupling_j = typical_coupling * constants::EV_TO_JOULES;
81        
82        // Decoherence rate ∝ coupling² × thermal energy / ℏ
83        let rate = (coupling_j.powi(2) * thermal_energy) / constants::PLANCK_HBAR;
84        // No artificial floor: the previous `rate.max(1e3)` clamped both
85        // 300 K and 10 mK runs to 1 kHz, making temperature-ordering
86        // assertions (test_thermal_decoherence_rate) flap. Return the
87        // physical value; downstream callers add their own coherence-time
88        // floors where appropriate.
89        rate
90    }
91
92    /// Calculate coherence time from decoherence rates
93    pub fn coherence_time(&self) -> f64 {
94        let total_rate = self.thermal_rate + self.dephasing_rate;
95        1.0 / total_rate
96    }
97
98    /// Calculate T1 (relaxation) time
99    pub fn relaxation_time_t1(&self) -> f64 {
100        // T1 typically longer than T2
101        2.0 / self.thermal_rate
102    }
103
104    /// Calculate T2 (dephasing) time
105    pub fn dephasing_time_t2(&self) -> f64 {
106        1.0 / self.dephasing_rate
107    }
108
109    /// Validate if operation time is within coherence window
110    pub fn validate_operation_time(&self, operation_time_s: f64) -> QuantumResult<DecoherenceResult> {
111        let coherence_time_s = self.coherence_time();
112        let t1_time_s = self.relaxation_time_t1();
113        let t2_time_s = self.dephasing_time_t2();
114        
115        let is_valid = operation_time_s < coherence_time_s;
116        let coherence_preserved = (-operation_time_s / coherence_time_s).exp();
117        
118        if !is_valid {
119            return Err(QuantumError::DecoherenceExceeded {
120                decoherence_time_s: coherence_time_s,
121                operation_time_s,
122            });
123        }
124        
125        Ok(DecoherenceResult {
126            is_valid,
127            operation_time_s,
128            coherence_time_s,
129            t1_relaxation_s: t1_time_s,
130            t2_dephasing_s: t2_time_s,
131            coherence_preserved,
132            temperature_k: self.temperature,
133            thermal_rate_hz: self.thermal_rate,
134            dephasing_rate_hz: self.dephasing_rate,
135            environment_type: self.classify_environment(),
136            noise_analysis: self.noise_spectrum.analyze_at_time(operation_time_s),
137        })
138    }
139
140    /// Classify environment based on temperature
141    pub fn classify_environment(&self) -> EnvironmentType {
142        if self.temperature < 1.0 {
143            EnvironmentType::UltraCryogenic
144        } else if self.temperature < 4.2 {
145            EnvironmentType::Cryogenic
146        } else if self.temperature < 77.0 {
147            EnvironmentType::LiquidNitrogen
148        } else if self.temperature < 273.0 {
149            EnvironmentType::Cold
150        } else {
151            EnvironmentType::RoomTemperature
152        }
153    }
154
155    /// Predict coherence evolution over time
156    pub fn predict_coherence_evolution(&self, max_time_s: f64, steps: usize) -> CoherenceEvolution {
157        let dt = max_time_s / steps as f64;
158        let mut times = Vec::new();
159        let mut coherences = Vec::new();
160        let coherence_time = self.coherence_time();
161        
162        for i in 0..=steps {
163            let t = i as f64 * dt;
164            let coherence = (-t / coherence_time).exp();
165            times.push(t);
166            coherences.push(coherence);
167        }
168        
169        CoherenceEvolution {
170            times,
171            coherences,
172            coherence_time_s: coherence_time,
173            environment: self.classify_environment(),
174        }
175    }
176
177    /// Analyze decoherence across different time scales
178    pub fn analyze_time_scales(&self) -> DecoherenceAnalysis {
179        let scales = vec![
180            ("attosecond", 1e-18),
181            ("femtosecond", 1e-15),
182            ("picosecond", 1e-12),
183            ("nanosecond", 1e-9),
184            ("microsecond", 1e-6),
185            ("millisecond", 1e-3),
186        ];
187        
188        let coherence_time = self.coherence_time();
189        let mut assessments = Vec::new();
190        
191        for (name, time_s) in scales {
192            let coherence_preserved = (-time_s / coherence_time).exp();
193            let is_feasible = coherence_preserved > 0.5; // 50% coherence threshold
194            
195            assessments.push(TimeScaleAssessment {
196                scale_name: name.to_string(),
197                time_s,
198                coherence_preserved,
199                is_feasible,
200                coherence_quality: if coherence_preserved > 0.9 {
201                    CoherenceQuality::Excellent
202                } else if coherence_preserved > 0.7 {
203                    CoherenceQuality::Good
204                } else if coherence_preserved > 0.5 {
205                    CoherenceQuality::Marginal
206                } else {
207                    CoherenceQuality::Poor
208                },
209            });
210        }
211        
212        DecoherenceAnalysis {
213            environment: self.classify_environment(),
214            temperature_k: self.temperature,
215            coherence_time_s: coherence_time,
216            t1_time_s: self.relaxation_time_t1(),
217            t2_time_s: self.dephasing_time_t2(),
218            assessments,
219            recommended_scale: self.recommend_time_scale(),
220        }
221    }
222
223    /// Recommend optimal time scale for consciousness operations
224    fn recommend_time_scale(&self) -> String {
225        let coherence_time = self.coherence_time();
226        
227        if coherence_time > 1e-6 {
228            "microsecond".to_string()
229        } else if coherence_time > 1e-9 {
230            "nanosecond".to_string()
231        } else if coherence_time > 1e-12 {
232            "picosecond".to_string()
233        } else {
234            "femtosecond".to_string()
235        }
236    }
237
238    /// Set custom decoherence parameters
239    pub fn set_decoherence_rates(&mut self, thermal_rate_hz: f64, dephasing_rate_hz: f64) {
240        self.thermal_rate = thermal_rate_hz;
241        self.dephasing_rate = dephasing_rate_hz;
242    }
243}
244
245impl Default for DecoherenceTracker {
246    fn default() -> Self {
247        Self::new()
248    }
249}
250
251/// Environmental noise spectrum characterization
252#[derive(Debug, Clone)]
253pub struct NoiseSpectrum {
254    /// Temperature for thermal noise
255    temperature: f64,
256    /// Low-frequency cutoff (Hz)
257    low_freq_cutoff: f64,
258    /// High-frequency cutoff (Hz)
259    high_freq_cutoff: f64,
260    /// Noise power spectral density
261    spectral_density: HashMap<String, f64>,
262}
263
264impl NoiseSpectrum {
265    fn new(temperature_k: f64) -> Self {
266        let mut spectral_density = HashMap::new();
267        
268        // Johnson noise (thermal)
269        let johnson_noise = 4.0 * constants::BOLTZMANN_K * temperature_k;
270        spectral_density.insert("thermal".to_string(), johnson_noise);
271        
272        // 1/f noise
273        spectral_density.insert("flicker".to_string(), 1e-15);
274        
275        // Shot noise
276        spectral_density.insert("shot".to_string(), 1e-18);
277        
278        Self {
279            temperature: temperature_k,
280            low_freq_cutoff: 1e3,  // 1 kHz
281            high_freq_cutoff: 1e12, // 1 THz
282            spectral_density,
283        }
284    }
285    
286    fn analyze_at_time(&self, time_s: f64) -> NoiseAnalysis {
287        let frequency = 1.0 / time_s;
288        
289        let thermal_noise = self.spectral_density["thermal"];
290        let flicker_noise = self.spectral_density["flicker"] / frequency.max(1.0);
291        let shot_noise = self.spectral_density["shot"];
292        
293        let total_noise = thermal_noise + flicker_noise + shot_noise;
294        
295        NoiseAnalysis {
296            frequency_hz: frequency,
297            thermal_noise_density: thermal_noise,
298            flicker_noise_density: flicker_noise,
299            shot_noise_density: shot_noise,
300            total_noise_density: total_noise,
301            dominant_source: if thermal_noise > flicker_noise && thermal_noise > shot_noise {
302                "thermal".to_string()
303            } else if flicker_noise > shot_noise {
304                "flicker".to_string()
305            } else {
306                "shot".to_string()
307            },
308        }
309    }
310}
311
312/// Result of decoherence validation
313#[derive(Debug, Clone)]
314pub struct DecoherenceResult {
315    pub is_valid: bool,
316    pub operation_time_s: f64,
317    pub coherence_time_s: f64,
318    pub t1_relaxation_s: f64,
319    pub t2_dephasing_s: f64,
320    pub coherence_preserved: f64,
321    pub temperature_k: f64,
322    pub thermal_rate_hz: f64,
323    pub dephasing_rate_hz: f64,
324    pub environment_type: EnvironmentType,
325    pub noise_analysis: NoiseAnalysis,
326}
327
328impl DecoherenceResult {
329    pub fn summary(&self) -> String {
330        format!(
331            "Decoherence Check: {} (coherence: {:.1}%, T₂: {:.1e}s, env: {:?})",
332            if self.is_valid { "PASS" } else { "FAIL" },
333            self.coherence_preserved * 100.0,
334            self.coherence_time_s,
335            self.environment_type
336        )
337    }
338}
339
340/// Environment classification for decoherence analysis
341#[derive(Debug, Clone, PartialEq)]
342pub enum EnvironmentType {
343    UltraCryogenic,   // < 1K
344    Cryogenic,        // 1-4.2K
345    LiquidNitrogen,   // 4.2-77K
346    Cold,             // 77-273K
347    RoomTemperature,  // > 273K
348}
349
350/// Coherence quality classification
351#[derive(Debug, Clone, PartialEq)]
352pub enum CoherenceQuality {
353    Excellent, // > 90%
354    Good,      // 70-90%
355    Marginal,  // 50-70%
356    Poor,      // < 50%
357}
358
359/// Noise analysis for specific operation
360#[derive(Debug, Clone)]
361pub struct NoiseAnalysis {
362    pub frequency_hz: f64,
363    pub thermal_noise_density: f64,
364    pub flicker_noise_density: f64,
365    pub shot_noise_density: f64,
366    pub total_noise_density: f64,
367    pub dominant_source: String,
368}
369
370/// Coherence evolution over time
371#[derive(Debug, Clone)]
372pub struct CoherenceEvolution {
373    pub times: Vec<f64>,
374    pub coherences: Vec<f64>,
375    pub coherence_time_s: f64,
376    pub environment: EnvironmentType,
377}
378
379/// Decoherence analysis across time scales
380#[derive(Debug, Clone)]
381pub struct DecoherenceAnalysis {
382    pub environment: EnvironmentType,
383    pub temperature_k: f64,
384    pub coherence_time_s: f64,
385    pub t1_time_s: f64,
386    pub t2_time_s: f64,
387    pub assessments: Vec<TimeScaleAssessment>,
388    pub recommended_scale: String,
389}
390
391/// Assessment of coherence at specific time scale
392#[derive(Debug, Clone)]
393pub struct TimeScaleAssessment {
394    pub scale_name: String,
395    pub time_s: f64,
396    pub coherence_preserved: f64,
397    pub is_feasible: bool,
398    pub coherence_quality: CoherenceQuality,
399}
400
401#[cfg(test)]
402mod tests {
403    use super::*;
404    use approx::assert_relative_eq;
405
406    #[test]
407    fn test_decoherence_tracker_creation() {
408        let tracker = DecoherenceTracker::new();
409        assert_eq!(tracker.temperature, constants::ROOM_TEMPERATURE_K);
410        assert!(tracker.coherence_time() > 0.0);
411    }
412
413    #[test]
414    fn test_cryogenic_environment() {
415        let cryo_tracker = DecoherenceTracker::cryogenic();
416        let room_tracker = DecoherenceTracker::new();
417        
418        // Cryogenic should have much longer coherence time
419        assert!(cryo_tracker.coherence_time() > room_tracker.coherence_time());
420        assert_eq!(cryo_tracker.classify_environment(), EnvironmentType::UltraCryogenic);
421    }
422
423    #[test]
424    fn test_operation_time_validation() {
425        let tracker = DecoherenceTracker::new();
426        
427        // Very short operation should be valid
428        let result = tracker.validate_operation_time(1e-12).unwrap();
429        assert!(result.is_valid);
430        assert!(result.coherence_preserved > 0.9);
431    }
432
433    #[test]
434    fn test_coherence_evolution() {
435        let tracker = DecoherenceTracker::new();
436        let evolution = tracker.predict_coherence_evolution(1e-9, 100);
437        
438        assert_eq!(evolution.times.len(), 101);
439        assert_eq!(evolution.coherences.len(), 101);
440        
441        // Coherence should decay over time
442        assert!(evolution.coherences[0] > evolution.coherences[50]);
443        assert!(evolution.coherences[50] > evolution.coherences[100]);
444    }
445
446    #[test]
447    fn test_time_scale_analysis() {
448        let tracker = DecoherenceTracker::new();
449        let analysis = tracker.analyze_time_scales();
450        
451        assert_eq!(analysis.assessments.len(), 6);
452        
453        // Shorter time scales should generally have better coherence
454        let femtosecond = analysis.assessments.iter()
455            .find(|a| a.scale_name == "femtosecond").unwrap();
456        let microsecond = analysis.assessments.iter()
457            .find(|a| a.scale_name == "microsecond").unwrap();
458        
459        assert!(femtosecond.coherence_preserved > microsecond.coherence_preserved);
460    }
461
462    #[test]
463    fn test_thermal_decoherence_rate() {
464        // Higher temperature should lead to faster decoherence
465        let rate_300k = DecoherenceTracker::calculate_thermal_decoherence_rate(300.0);
466        let rate_100k = DecoherenceTracker::calculate_thermal_decoherence_rate(100.0);
467        let rate_10k = DecoherenceTracker::calculate_thermal_decoherence_rate(10.0);
468        
469        assert!(rate_300k > rate_100k);
470        assert!(rate_100k > rate_10k);
471    }
472
473    #[test]
474    fn test_noise_spectrum_analysis() {
475        let tracker = DecoherenceTracker::new();
476        let noise = tracker.noise_spectrum.analyze_at_time(1e-9);
477
478        assert!(noise.total_noise_density > 0.0);
479        assert!(!noise.dominant_source.is_empty());
480        // `1.0 / 1e-9` is not exactly `1e9` in f64 (1e-9 is not exactly
481        // representable). Use a relative epsilon instead of `assert_eq!`.
482        assert_relative_eq!(noise.frequency_hz, 1e9, epsilon = 1e-6);
483    }
484
485    #[test]
486    fn test_environment_classification() {
487        assert_eq!(DecoherenceTracker::with_temperature(0.1).classify_environment(), 
488                   EnvironmentType::UltraCryogenic);
489        assert_eq!(DecoherenceTracker::with_temperature(4.0).classify_environment(), 
490                   EnvironmentType::Cryogenic);
491        assert_eq!(DecoherenceTracker::with_temperature(300.0).classify_environment(), 
492                   EnvironmentType::RoomTemperature);
493    }
494}