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(
111        &self,
112        operation_time_s: f64,
113    ) -> QuantumResult<DecoherenceResult> {
114        let coherence_time_s = self.coherence_time();
115        let t1_time_s = self.relaxation_time_t1();
116        let t2_time_s = self.dephasing_time_t2();
117
118        let is_valid = operation_time_s < coherence_time_s;
119        let coherence_preserved = (-operation_time_s / coherence_time_s).exp();
120
121        if !is_valid {
122            return Err(QuantumError::DecoherenceExceeded {
123                decoherence_time_s: coherence_time_s,
124                operation_time_s,
125            });
126        }
127
128        Ok(DecoherenceResult {
129            is_valid,
130            operation_time_s,
131            coherence_time_s,
132            t1_relaxation_s: t1_time_s,
133            t2_dephasing_s: t2_time_s,
134            coherence_preserved,
135            temperature_k: self.temperature,
136            thermal_rate_hz: self.thermal_rate,
137            dephasing_rate_hz: self.dephasing_rate,
138            environment_type: self.classify_environment(),
139            noise_analysis: self.noise_spectrum.analyze_at_time(operation_time_s),
140        })
141    }
142
143    /// Classify environment based on temperature
144    pub fn classify_environment(&self) -> EnvironmentType {
145        if self.temperature < 1.0 {
146            EnvironmentType::UltraCryogenic
147        } else if self.temperature < 4.2 {
148            EnvironmentType::Cryogenic
149        } else if self.temperature < 77.0 {
150            EnvironmentType::LiquidNitrogen
151        } else if self.temperature < 273.0 {
152            EnvironmentType::Cold
153        } else {
154            EnvironmentType::RoomTemperature
155        }
156    }
157
158    /// Predict coherence evolution over time
159    pub fn predict_coherence_evolution(&self, max_time_s: f64, steps: usize) -> CoherenceEvolution {
160        let dt = max_time_s / steps as f64;
161        let mut times = Vec::new();
162        let mut coherences = Vec::new();
163        let coherence_time = self.coherence_time();
164
165        for i in 0..=steps {
166            let t = i as f64 * dt;
167            let coherence = (-t / coherence_time).exp();
168            times.push(t);
169            coherences.push(coherence);
170        }
171
172        CoherenceEvolution {
173            times,
174            coherences,
175            coherence_time_s: coherence_time,
176            environment: self.classify_environment(),
177        }
178    }
179
180    /// Analyze decoherence across different time scales
181    pub fn analyze_time_scales(&self) -> DecoherenceAnalysis {
182        let scales = vec![
183            ("attosecond", 1e-18),
184            ("femtosecond", 1e-15),
185            ("picosecond", 1e-12),
186            ("nanosecond", 1e-9),
187            ("microsecond", 1e-6),
188            ("millisecond", 1e-3),
189        ];
190
191        let coherence_time = self.coherence_time();
192        let mut assessments = Vec::new();
193
194        for (name, time_s) in scales {
195            let coherence_preserved = (-time_s / coherence_time).exp();
196            let is_feasible = coherence_preserved > 0.5; // 50% coherence threshold
197
198            assessments.push(TimeScaleAssessment {
199                scale_name: name.to_string(),
200                time_s,
201                coherence_preserved,
202                is_feasible,
203                coherence_quality: if coherence_preserved > 0.9 {
204                    CoherenceQuality::Excellent
205                } else if coherence_preserved > 0.7 {
206                    CoherenceQuality::Good
207                } else if coherence_preserved > 0.5 {
208                    CoherenceQuality::Marginal
209                } else {
210                    CoherenceQuality::Poor
211                },
212            });
213        }
214
215        DecoherenceAnalysis {
216            environment: self.classify_environment(),
217            temperature_k: self.temperature,
218            coherence_time_s: coherence_time,
219            t1_time_s: self.relaxation_time_t1(),
220            t2_time_s: self.dephasing_time_t2(),
221            assessments,
222            recommended_scale: self.recommend_time_scale(),
223        }
224    }
225
226    /// Recommend optimal time scale for consciousness operations
227    fn recommend_time_scale(&self) -> String {
228        let coherence_time = self.coherence_time();
229
230        if coherence_time > 1e-6 {
231            "microsecond".to_string()
232        } else if coherence_time > 1e-9 {
233            "nanosecond".to_string()
234        } else if coherence_time > 1e-12 {
235            "picosecond".to_string()
236        } else {
237            "femtosecond".to_string()
238        }
239    }
240
241    /// Set custom decoherence parameters
242    pub fn set_decoherence_rates(&mut self, thermal_rate_hz: f64, dephasing_rate_hz: f64) {
243        self.thermal_rate = thermal_rate_hz;
244        self.dephasing_rate = dephasing_rate_hz;
245    }
246}
247
248impl Default for DecoherenceTracker {
249    fn default() -> Self {
250        Self::new()
251    }
252}
253
254/// Environmental noise spectrum characterization
255#[derive(Debug, Clone)]
256pub struct NoiseSpectrum {
257    /// Temperature for thermal noise
258    temperature: f64,
259    /// Low-frequency cutoff (Hz)
260    low_freq_cutoff: f64,
261    /// High-frequency cutoff (Hz)
262    high_freq_cutoff: f64,
263    /// Noise power spectral density
264    spectral_density: HashMap<String, f64>,
265}
266
267impl NoiseSpectrum {
268    fn new(temperature_k: f64) -> Self {
269        let mut spectral_density = HashMap::new();
270
271        // Johnson noise (thermal)
272        let johnson_noise = 4.0 * constants::BOLTZMANN_K * temperature_k;
273        spectral_density.insert("thermal".to_string(), johnson_noise);
274
275        // 1/f noise
276        spectral_density.insert("flicker".to_string(), 1e-15);
277
278        // Shot noise
279        spectral_density.insert("shot".to_string(), 1e-18);
280
281        Self {
282            temperature: temperature_k,
283            low_freq_cutoff: 1e3,   // 1 kHz
284            high_freq_cutoff: 1e12, // 1 THz
285            spectral_density,
286        }
287    }
288
289    fn analyze_at_time(&self, time_s: f64) -> NoiseAnalysis {
290        let frequency = 1.0 / time_s;
291
292        let thermal_noise = self.spectral_density["thermal"];
293        let flicker_noise = self.spectral_density["flicker"] / frequency.max(1.0);
294        let shot_noise = self.spectral_density["shot"];
295
296        let total_noise = thermal_noise + flicker_noise + shot_noise;
297
298        NoiseAnalysis {
299            frequency_hz: frequency,
300            thermal_noise_density: thermal_noise,
301            flicker_noise_density: flicker_noise,
302            shot_noise_density: shot_noise,
303            total_noise_density: total_noise,
304            dominant_source: if thermal_noise > flicker_noise && thermal_noise > shot_noise {
305                "thermal".to_string()
306            } else if flicker_noise > shot_noise {
307                "flicker".to_string()
308            } else {
309                "shot".to_string()
310            },
311        }
312    }
313}
314
315/// Result of decoherence validation
316#[derive(Debug, Clone)]
317pub struct DecoherenceResult {
318    pub is_valid: bool,
319    pub operation_time_s: f64,
320    pub coherence_time_s: f64,
321    pub t1_relaxation_s: f64,
322    pub t2_dephasing_s: f64,
323    pub coherence_preserved: f64,
324    pub temperature_k: f64,
325    pub thermal_rate_hz: f64,
326    pub dephasing_rate_hz: f64,
327    pub environment_type: EnvironmentType,
328    pub noise_analysis: NoiseAnalysis,
329}
330
331impl DecoherenceResult {
332    pub fn summary(&self) -> String {
333        format!(
334            "Decoherence Check: {} (coherence: {:.1}%, T₂: {:.1e}s, env: {:?})",
335            if self.is_valid { "PASS" } else { "FAIL" },
336            self.coherence_preserved * 100.0,
337            self.coherence_time_s,
338            self.environment_type
339        )
340    }
341}
342
343/// Environment classification for decoherence analysis
344#[derive(Debug, Clone, PartialEq)]
345pub enum EnvironmentType {
346    UltraCryogenic,  // < 1K
347    Cryogenic,       // 1-4.2K
348    LiquidNitrogen,  // 4.2-77K
349    Cold,            // 77-273K
350    RoomTemperature, // > 273K
351}
352
353/// Coherence quality classification
354#[derive(Debug, Clone, PartialEq)]
355pub enum CoherenceQuality {
356    Excellent, // > 90%
357    Good,      // 70-90%
358    Marginal,  // 50-70%
359    Poor,      // < 50%
360}
361
362/// Noise analysis for specific operation
363#[derive(Debug, Clone)]
364pub struct NoiseAnalysis {
365    pub frequency_hz: f64,
366    pub thermal_noise_density: f64,
367    pub flicker_noise_density: f64,
368    pub shot_noise_density: f64,
369    pub total_noise_density: f64,
370    pub dominant_source: String,
371}
372
373/// Coherence evolution over time
374#[derive(Debug, Clone)]
375pub struct CoherenceEvolution {
376    pub times: Vec<f64>,
377    pub coherences: Vec<f64>,
378    pub coherence_time_s: f64,
379    pub environment: EnvironmentType,
380}
381
382/// Decoherence analysis across time scales
383#[derive(Debug, Clone)]
384pub struct DecoherenceAnalysis {
385    pub environment: EnvironmentType,
386    pub temperature_k: f64,
387    pub coherence_time_s: f64,
388    pub t1_time_s: f64,
389    pub t2_time_s: f64,
390    pub assessments: Vec<TimeScaleAssessment>,
391    pub recommended_scale: String,
392}
393
394/// Assessment of coherence at specific time scale
395#[derive(Debug, Clone)]
396pub struct TimeScaleAssessment {
397    pub scale_name: String,
398    pub time_s: f64,
399    pub coherence_preserved: f64,
400    pub is_feasible: bool,
401    pub coherence_quality: CoherenceQuality,
402}
403
404#[cfg(test)]
405mod tests {
406    use super::*;
407    use approx::assert_relative_eq;
408
409    #[test]
410    fn test_decoherence_tracker_creation() {
411        let tracker = DecoherenceTracker::new();
412        assert_eq!(tracker.temperature, constants::ROOM_TEMPERATURE_K);
413        assert!(tracker.coherence_time() > 0.0);
414    }
415
416    #[test]
417    fn test_cryogenic_environment() {
418        let cryo_tracker = DecoherenceTracker::cryogenic();
419        let room_tracker = DecoherenceTracker::new();
420
421        // Cryogenic should have much longer coherence time
422        assert!(cryo_tracker.coherence_time() > room_tracker.coherence_time());
423        assert_eq!(
424            cryo_tracker.classify_environment(),
425            EnvironmentType::UltraCryogenic
426        );
427    }
428
429    #[test]
430    fn test_operation_time_validation() {
431        let tracker = DecoherenceTracker::new();
432
433        // Very short operation should be valid
434        let result = tracker.validate_operation_time(1e-12).unwrap();
435        assert!(result.is_valid);
436        assert!(result.coherence_preserved > 0.9);
437    }
438
439    #[test]
440    fn test_coherence_evolution() {
441        let tracker = DecoherenceTracker::new();
442        let evolution = tracker.predict_coherence_evolution(1e-9, 100);
443
444        assert_eq!(evolution.times.len(), 101);
445        assert_eq!(evolution.coherences.len(), 101);
446
447        // Coherence should decay over time
448        assert!(evolution.coherences[0] > evolution.coherences[50]);
449        assert!(evolution.coherences[50] > evolution.coherences[100]);
450    }
451
452    #[test]
453    fn test_time_scale_analysis() {
454        let tracker = DecoherenceTracker::new();
455        let analysis = tracker.analyze_time_scales();
456
457        assert_eq!(analysis.assessments.len(), 6);
458
459        // Shorter time scales should generally have better coherence
460        let femtosecond = analysis
461            .assessments
462            .iter()
463            .find(|a| a.scale_name == "femtosecond")
464            .unwrap();
465        let microsecond = analysis
466            .assessments
467            .iter()
468            .find(|a| a.scale_name == "microsecond")
469            .unwrap();
470
471        assert!(femtosecond.coherence_preserved > microsecond.coherence_preserved);
472    }
473
474    #[test]
475    fn test_thermal_decoherence_rate() {
476        // Higher temperature should lead to faster decoherence
477        let rate_300k = DecoherenceTracker::calculate_thermal_decoherence_rate(300.0);
478        let rate_100k = DecoherenceTracker::calculate_thermal_decoherence_rate(100.0);
479        let rate_10k = DecoherenceTracker::calculate_thermal_decoherence_rate(10.0);
480
481        assert!(rate_300k > rate_100k);
482        assert!(rate_100k > rate_10k);
483    }
484
485    #[test]
486    fn test_noise_spectrum_analysis() {
487        let tracker = DecoherenceTracker::new();
488        let noise = tracker.noise_spectrum.analyze_at_time(1e-9);
489
490        assert!(noise.total_noise_density > 0.0);
491        assert!(!noise.dominant_source.is_empty());
492        // `1.0 / 1e-9` is not exactly `1e9` in f64 (1e-9 is not exactly
493        // representable). Use a relative epsilon instead of `assert_eq!`.
494        assert_relative_eq!(noise.frequency_hz, 1e9, epsilon = 1e-6);
495    }
496
497    #[test]
498    fn test_environment_classification() {
499        assert_eq!(
500            DecoherenceTracker::with_temperature(0.1).classify_environment(),
501            EnvironmentType::UltraCryogenic
502        );
503        assert_eq!(
504            DecoherenceTracker::with_temperature(4.0).classify_environment(),
505            EnvironmentType::Cryogenic
506        );
507        assert_eq!(
508            DecoherenceTracker::with_temperature(300.0).classify_environment(),
509            EnvironmentType::RoomTemperature
510        );
511    }
512}