quantrs2_device/photonic/
config.rs

1//! Configuration management for photonic quantum devices
2
3use crate::DeviceResult;
4use serde::{Deserialize, Serialize};
5use std::collections::HashMap;
6use std::time::Duration;
7
8/// Photonic system types
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
10pub enum PhotonicSystem {
11    /// Continuous variable quantum computing
12    ContinuousVariable,
13    /// Gate-based photonic quantum computing
14    GateBased,
15    /// Measurement-based quantum computing
16    MeasurementBased,
17    /// Hybrid photonic systems
18    Hybrid,
19}
20
21/// Advanced configuration for photonic quantum devices
22#[derive(Debug, Clone, Serialize, Deserialize, Default)]
23pub struct PhotonicConfig {
24    /// Base system configuration
25    pub system: SystemConfig,
26    /// Hardware configuration
27    pub hardware: HardwareConfig,
28    /// Measurement configuration
29    pub measurement: MeasurementConfig,
30    /// Error correction settings
31    pub error_correction: ErrorCorrectionConfig,
32    /// Optimization settings
33    pub optimization: OptimizationConfig,
34}
35
36/// System configuration
37#[derive(Debug, Clone, Serialize, Deserialize)]
38pub struct SystemConfig {
39    /// Photonic system type
40    pub system_type: PhotonicSystem,
41    /// Number of optical modes
42    pub mode_count: usize,
43    /// Cutoff dimension for Fock space
44    pub cutoff_dimension: usize,
45    /// Maximum photon number
46    pub max_photon_number: usize,
47    /// Squeezing parameter range
48    pub squeezing_range: (f64, f64),
49    /// Displacement amplitude range
50    pub displacement_range: (f64, f64),
51}
52
53/// Hardware configuration
54#[derive(Debug, Clone, Serialize, Deserialize, Default)]
55pub struct HardwareConfig {
56    /// Laser configuration
57    pub laser: LaserConfig,
58    /// Detector configuration
59    pub detector: DetectorConfig,
60    /// Beam splitter configuration
61    pub beam_splitter: BeamSplitterConfig,
62    /// Phase shifter configuration
63    pub phase_shifter: PhaseShifterConfig,
64    /// Squeezer configuration
65    pub squeezer: SqueezerConfig,
66}
67
68/// Laser configuration
69#[derive(Debug, Clone, Serialize, Deserialize)]
70pub struct LaserConfig {
71    /// Wavelength (nm)
72    pub wavelength: f64,
73    /// Power (mW)
74    pub power: f64,
75    /// Linewidth (Hz)
76    pub linewidth: f64,
77    /// Coherence time (ns)
78    pub coherence_time: f64,
79    /// Intensity noise (dB/Hz)
80    pub intensity_noise: f64,
81    /// Phase noise (rad²/Hz)
82    pub phase_noise: f64,
83}
84
85/// Detector configuration
86#[derive(Debug, Clone, Serialize, Deserialize)]
87pub struct DetectorConfig {
88    /// Detection efficiency
89    pub efficiency: f64,
90    /// Dark count rate (Hz)
91    pub dark_count_rate: f64,
92    /// Dead time (ns)
93    pub dead_time: f64,
94    /// Timing jitter (ps)
95    pub timing_jitter: f64,
96    /// Number resolution
97    pub number_resolution: bool,
98    /// Quantum efficiency
99    pub quantum_efficiency: f64,
100}
101
102/// Beam splitter configuration
103#[derive(Debug, Clone, Serialize, Deserialize)]
104pub struct BeamSplitterConfig {
105    /// Transmission coefficient
106    pub transmission: f64,
107    /// Reflection coefficient
108    pub reflection: f64,
109    /// Loss coefficient
110    pub loss: f64,
111    /// Phase shift (radians)
112    pub phase_shift: f64,
113    /// Bandwidth (Hz)
114    pub bandwidth: f64,
115}
116
117/// Phase shifter configuration
118#[derive(Debug, Clone, Serialize, Deserialize)]
119pub struct PhaseShifterConfig {
120    /// Maximum phase shift (radians)
121    pub max_phase_shift: f64,
122    /// Phase resolution (radians)
123    pub phase_resolution: f64,
124    /// Response time (ns)
125    pub response_time: f64,
126    /// Drift rate (rad/s)
127    pub drift_rate: f64,
128}
129
130/// Squeezer configuration
131#[derive(Debug, Clone, Serialize, Deserialize)]
132pub struct SqueezerConfig {
133    /// Maximum squeezing parameter
134    pub max_squeezing: f64,
135    /// Squeezing bandwidth (Hz)
136    pub bandwidth: f64,
137    /// Anti-squeezing penalty
138    pub anti_squeezing_penalty: f64,
139    /// Pump power (mW)
140    pub pump_power: f64,
141}
142
143/// Measurement configuration
144#[derive(Debug, Clone, Serialize, Deserialize, Default)]
145pub struct MeasurementConfig {
146    /// Homodyne detection settings
147    pub homodyne: HomodyneConfig,
148    /// Heterodyne detection settings
149    pub heterodyne: HeterodyneConfig,
150    /// Photon counting settings
151    pub photon_counting: PhotonCountingConfig,
152    /// Tomography settings
153    pub tomography: TomographyConfig,
154}
155
156/// Homodyne detection configuration
157#[derive(Debug, Clone, Serialize, Deserialize)]
158pub struct HomodyneConfig {
159    /// Local oscillator power (mW)
160    pub lo_power: f64,
161    /// Detection efficiency
162    pub efficiency: f64,
163    /// Electronic noise (V²/Hz)
164    pub electronic_noise: f64,
165    /// Shot noise clearance (dB)
166    pub shot_noise_clearance: f64,
167}
168
169/// Heterodyne detection configuration
170#[derive(Debug, Clone, Serialize, Deserialize)]
171pub struct HeterodyneConfig {
172    /// Local oscillator power (mW)
173    pub lo_power: f64,
174    /// Intermediate frequency (Hz)
175    pub intermediate_frequency: f64,
176    /// Detection efficiency
177    pub efficiency: f64,
178    /// Phase resolution (radians)
179    pub phase_resolution: f64,
180}
181
182/// Photon counting configuration
183#[derive(Debug, Clone, Serialize, Deserialize)]
184pub struct PhotonCountingConfig {
185    /// Maximum count rate (Hz)
186    pub max_count_rate: f64,
187    /// Detection window (ns)
188    pub detection_window: f64,
189    /// Coincidence window (ns)
190    pub coincidence_window: f64,
191    /// Background count rate (Hz)
192    pub background_rate: f64,
193}
194
195/// Quantum state tomography configuration
196#[derive(Debug, Clone, Serialize, Deserialize)]
197pub struct TomographyConfig {
198    /// Number of measurement settings
199    pub measurement_settings: usize,
200    /// Shots per setting
201    pub shots_per_setting: usize,
202    /// Reconstruction method
203    pub reconstruction_method: TomographyMethod,
204    /// Regularization parameter
205    pub regularization: f64,
206}
207
208/// Tomography reconstruction methods
209#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
210pub enum TomographyMethod {
211    /// Maximum likelihood estimation
212    MaximumLikelihood,
213    /// Linear inversion
214    LinearInversion,
215    /// Bayesian inference
216    Bayesian,
217    /// Compressed sensing
218    CompressedSensing,
219}
220
221/// Error correction configuration
222#[derive(Debug, Clone, Serialize, Deserialize)]
223pub struct ErrorCorrectionConfig {
224    /// Enable error correction
225    pub enabled: bool,
226    /// Error correction scheme
227    pub scheme: ErrorCorrectionScheme,
228    /// Loss tolerance
229    pub loss_tolerance: f64,
230    /// Phase error tolerance
231    pub phase_error_tolerance: f64,
232    /// Syndrome extraction rounds
233    pub syndrome_rounds: usize,
234}
235
236/// Error correction schemes for photonic systems
237#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
238pub enum ErrorCorrectionScheme {
239    /// No error correction
240    None,
241    /// GKP (Gottesman-Kitaev-Preskill) codes
242    GKP,
243    /// Cat codes
244    Cat,
245    /// Binomial codes
246    Binomial,
247    /// Four-component cat codes
248    FourComponentCat,
249}
250
251/// Optimization configuration
252#[derive(Debug, Clone, Serialize, Deserialize)]
253pub struct OptimizationConfig {
254    /// Enable gate optimization
255    pub gate_optimization: bool,
256    /// Enable measurement optimization
257    pub measurement_optimization: bool,
258    /// Enable loss compensation
259    pub loss_compensation: bool,
260    /// Optimization algorithm
261    pub algorithm: OptimizationAlgorithm,
262    /// Maximum iterations
263    pub max_iterations: usize,
264    /// Convergence tolerance
265    pub tolerance: f64,
266}
267
268/// Optimization algorithms
269#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
270pub enum OptimizationAlgorithm {
271    /// Gradient descent
272    GradientDescent,
273    /// Simulated annealing
274    SimulatedAnnealing,
275    /// Genetic algorithm
276    Genetic,
277    /// Particle swarm optimization
278    ParticleSwarm,
279    /// Bayesian optimization
280    Bayesian,
281}
282
283impl Default for SystemConfig {
284    fn default() -> Self {
285        Self {
286            system_type: PhotonicSystem::ContinuousVariable,
287            mode_count: 8,
288            cutoff_dimension: 10,
289            max_photon_number: 50,
290            squeezing_range: (-2.0, 2.0),
291            displacement_range: (-5.0, 5.0),
292        }
293    }
294}
295
296impl Default for LaserConfig {
297    fn default() -> Self {
298        Self {
299            wavelength: 1550.0,
300            power: 10.0,
301            linewidth: 100.0,
302            coherence_time: 10.0,
303            intensity_noise: -140.0,
304            phase_noise: 1e-6,
305        }
306    }
307}
308
309impl Default for DetectorConfig {
310    fn default() -> Self {
311        Self {
312            efficiency: 0.9,
313            dark_count_rate: 100.0,
314            dead_time: 50.0,
315            timing_jitter: 100.0,
316            number_resolution: true,
317            quantum_efficiency: 0.85,
318        }
319    }
320}
321
322impl Default for BeamSplitterConfig {
323    fn default() -> Self {
324        Self {
325            transmission: 0.5,
326            reflection: 0.5,
327            loss: 0.01,
328            phase_shift: 0.0,
329            bandwidth: 1e12,
330        }
331    }
332}
333
334impl Default for PhaseShifterConfig {
335    fn default() -> Self {
336        Self {
337            max_phase_shift: 2.0 * std::f64::consts::PI,
338            phase_resolution: 0.01,
339            response_time: 1.0,
340            drift_rate: 1e-6,
341        }
342    }
343}
344
345impl Default for SqueezerConfig {
346    fn default() -> Self {
347        Self {
348            max_squeezing: 10.0,
349            bandwidth: 1e9,
350            anti_squeezing_penalty: 3.0,
351            pump_power: 100.0,
352        }
353    }
354}
355
356impl Default for HomodyneConfig {
357    fn default() -> Self {
358        Self {
359            lo_power: 1.0,
360            efficiency: 0.9,
361            electronic_noise: 1e-8,
362            shot_noise_clearance: 10.0,
363        }
364    }
365}
366
367impl Default for HeterodyneConfig {
368    fn default() -> Self {
369        Self {
370            lo_power: 1.0,
371            intermediate_frequency: 1e6,
372            efficiency: 0.85,
373            phase_resolution: 0.01,
374        }
375    }
376}
377
378impl Default for PhotonCountingConfig {
379    fn default() -> Self {
380        Self {
381            max_count_rate: 1e6,
382            detection_window: 10.0,
383            coincidence_window: 1.0,
384            background_rate: 100.0,
385        }
386    }
387}
388
389impl Default for TomographyConfig {
390    fn default() -> Self {
391        Self {
392            measurement_settings: 16,
393            shots_per_setting: 10000,
394            reconstruction_method: TomographyMethod::MaximumLikelihood,
395            regularization: 1e-6,
396        }
397    }
398}
399
400impl Default for ErrorCorrectionConfig {
401    fn default() -> Self {
402        Self {
403            enabled: false,
404            scheme: ErrorCorrectionScheme::None,
405            loss_tolerance: 0.1,
406            phase_error_tolerance: 0.05,
407            syndrome_rounds: 3,
408        }
409    }
410}
411
412impl Default for OptimizationConfig {
413    fn default() -> Self {
414        Self {
415            gate_optimization: true,
416            measurement_optimization: true,
417            loss_compensation: true,
418            algorithm: OptimizationAlgorithm::GradientDescent,
419            max_iterations: 1000,
420            tolerance: 1e-6,
421        }
422    }
423}
424
425/// Configuration builder for photonic devices
426pub struct PhotonicConfigBuilder {
427    config: PhotonicConfig,
428}
429
430impl PhotonicConfigBuilder {
431    pub fn new() -> Self {
432        Self {
433            config: PhotonicConfig::default(),
434        }
435    }
436
437    #[must_use]
438    pub const fn system_type(mut self, system_type: PhotonicSystem) -> Self {
439        self.config.system.system_type = system_type;
440        self
441    }
442
443    #[must_use]
444    pub const fn mode_count(mut self, count: usize) -> Self {
445        self.config.system.mode_count = count;
446        self
447    }
448
449    #[must_use]
450    pub const fn cutoff_dimension(mut self, cutoff: usize) -> Self {
451        self.config.system.cutoff_dimension = cutoff;
452        self
453    }
454
455    #[must_use]
456    pub const fn laser_wavelength(mut self, wavelength: f64) -> Self {
457        self.config.hardware.laser.wavelength = wavelength;
458        self
459    }
460
461    #[must_use]
462    pub const fn detection_efficiency(mut self, efficiency: f64) -> Self {
463        self.config.hardware.detector.efficiency = efficiency;
464        self
465    }
466
467    #[must_use]
468    pub const fn enable_error_correction(mut self, enabled: bool) -> Self {
469        self.config.error_correction.enabled = enabled;
470        self
471    }
472
473    #[must_use]
474    pub const fn error_correction_scheme(mut self, scheme: ErrorCorrectionScheme) -> Self {
475        self.config.error_correction.scheme = scheme;
476        self
477    }
478
479    #[must_use]
480    pub const fn optimization_algorithm(mut self, algorithm: OptimizationAlgorithm) -> Self {
481        self.config.optimization.algorithm = algorithm;
482        self
483    }
484
485    pub fn build(self) -> DeviceResult<PhotonicConfig> {
486        self.validate()?;
487        Ok(self.config)
488    }
489
490    fn validate(&self) -> DeviceResult<()> {
491        if self.config.system.mode_count == 0 {
492            return Err(crate::DeviceError::InvalidInput(
493                "Mode count must be greater than 0".to_string(),
494            ));
495        }
496
497        if self.config.system.cutoff_dimension == 0 {
498            return Err(crate::DeviceError::InvalidInput(
499                "Cutoff dimension must be greater than 0".to_string(),
500            ));
501        }
502
503        if self.config.hardware.laser.wavelength <= 0.0 {
504            return Err(crate::DeviceError::InvalidInput(
505                "Laser wavelength must be positive".to_string(),
506            ));
507        }
508
509        if self.config.hardware.detector.efficiency < 0.0
510            || self.config.hardware.detector.efficiency > 1.0
511        {
512            return Err(crate::DeviceError::InvalidInput(
513                "Detection efficiency must be between 0 and 1".to_string(),
514            ));
515        }
516
517        Ok(())
518    }
519}
520
521impl Default for PhotonicConfigBuilder {
522    fn default() -> Self {
523        Self::new()
524    }
525}
526
527/// Predefined configurations for common photonic setups
528pub struct PhotonicConfigurations;
529
530impl PhotonicConfigurations {
531    /// Configuration for continuous variable quantum computing
532    pub fn cv_config() -> PhotonicConfig {
533        PhotonicConfigBuilder::new()
534            .system_type(PhotonicSystem::ContinuousVariable)
535            .mode_count(8)
536            .cutoff_dimension(20)
537            .laser_wavelength(1550.0)
538            .detection_efficiency(0.9)
539            .build()
540            .expect("CV config uses valid parameters")
541    }
542
543    /// Configuration for gate-based photonic quantum computing
544    pub fn gate_based_config() -> PhotonicConfig {
545        PhotonicConfigBuilder::new()
546            .system_type(PhotonicSystem::GateBased)
547            .mode_count(16)
548            .cutoff_dimension(5)
549            .laser_wavelength(780.0)
550            .detection_efficiency(0.95)
551            .enable_error_correction(true)
552            .error_correction_scheme(ErrorCorrectionScheme::GKP)
553            .build()
554            .expect("Gate-based config uses valid parameters")
555    }
556
557    /// Configuration for measurement-based quantum computing
558    pub fn mbqc_config() -> PhotonicConfig {
559        PhotonicConfigBuilder::new()
560            .system_type(PhotonicSystem::MeasurementBased)
561            .mode_count(32)
562            .cutoff_dimension(3)
563            .laser_wavelength(532.0)
564            .detection_efficiency(0.85)
565            .optimization_algorithm(OptimizationAlgorithm::Bayesian)
566            .build()
567            .expect("MBQC config uses valid parameters")
568    }
569
570    /// Configuration for hybrid photonic systems
571    pub fn hybrid_config() -> PhotonicConfig {
572        PhotonicConfigBuilder::new()
573            .system_type(PhotonicSystem::Hybrid)
574            .mode_count(24)
575            .cutoff_dimension(15)
576            .laser_wavelength(1064.0)
577            .detection_efficiency(0.92)
578            .enable_error_correction(true)
579            .error_correction_scheme(ErrorCorrectionScheme::Cat)
580            .build()
581            .expect("Hybrid config uses valid parameters")
582    }
583}
584
585#[cfg(test)]
586mod tests {
587    use super::*;
588
589    #[test]
590    fn test_config_builder() {
591        let config = PhotonicConfigBuilder::new()
592            .mode_count(10)
593            .cutoff_dimension(15)
594            .laser_wavelength(1550.0)
595            .build();
596
597        assert!(config.is_ok());
598        let config = config.expect("Config should be valid");
599        assert_eq!(config.system.mode_count, 10);
600        assert_eq!(config.system.cutoff_dimension, 15);
601        assert_eq!(config.hardware.laser.wavelength, 1550.0);
602    }
603
604    #[test]
605    fn test_predefined_configs() {
606        let cv = PhotonicConfigurations::cv_config();
607        assert_eq!(cv.system.system_type, PhotonicSystem::ContinuousVariable);
608
609        let gate_based = PhotonicConfigurations::gate_based_config();
610        assert_eq!(gate_based.system.system_type, PhotonicSystem::GateBased);
611        assert!(gate_based.error_correction.enabled);
612
613        let mbqc = PhotonicConfigurations::mbqc_config();
614        assert_eq!(mbqc.system.system_type, PhotonicSystem::MeasurementBased);
615
616        let hybrid = PhotonicConfigurations::hybrid_config();
617        assert_eq!(hybrid.system.system_type, PhotonicSystem::Hybrid);
618    }
619
620    #[test]
621    fn test_invalid_config() {
622        let config = PhotonicConfigBuilder::new().mode_count(0).build();
623
624        assert!(config.is_err());
625    }
626}