quantrs2-device 0.1.3

Quantum device connectors for the QuantRS2 framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
//! Continuous variable quantum gates
//!
//! This module implements the standard gate set for continuous variable quantum computing,
//! including Gaussian operations and some non-Gaussian operations.

use super::{Complex, GaussianState};
use crate::{DeviceError, DeviceResult};
use serde::{Deserialize, Serialize};
use std::f64::consts::PI;

/// Types of CV gates
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum CVGateType {
    /// Displacement gate D(α)
    Displacement { amplitude: Complex },
    /// Squeezing gate S(r, φ)
    Squeezing { parameter: f64, phase: f64 },
    /// Two-mode squeezing gate S₂(r, φ)
    TwoModeSqueezing { parameter: f64, phase: f64 },
    /// Beamsplitter gate BS(θ, φ)
    Beamsplitter { transmittance: f64, phase: f64 },
    /// Phase rotation gate R(φ)
    PhaseRotation { phase: f64 },
    /// Controlled displacement gate CD(α)
    ControlledDisplacement { amplitude: Complex },
    /// Controlled phase gate CP(s)
    ControlledPhase { parameter: f64 },
    /// Cross-Kerr gate CK(κ)
    CrossKerr { parameter: f64 },
    /// Cubic phase gate V(γ)
    CubicPhase { parameter: f64 },
    /// Position measurement M_x(s)
    PositionMeasurement { result: f64 },
    /// Momentum measurement M_p(s)
    MomentumMeasurement { result: f64 },
}

/// CV gate parameters for parameterized operations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CVGateParams {
    /// Real parameters (amplitudes, phases, etc.)
    pub real_params: Vec<f64>,
    /// Complex parameters (displacements, etc.)
    pub complex_params: Vec<Complex>,
    /// Target modes
    pub target_modes: Vec<usize>,
    /// Control modes (if applicable)
    pub control_modes: Vec<usize>,
}

/// Sequence of CV gates forming a quantum program
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CVGateSequence {
    /// Gates in the sequence
    pub gates: Vec<(CVGateType, CVGateParams)>,
    /// Total number of modes required
    pub num_modes: usize,
}

impl CVGateSequence {
    /// Create a new empty gate sequence
    pub const fn new(num_modes: usize) -> Self {
        Self {
            gates: Vec::new(),
            num_modes,
        }
    }

    /// Add a displacement gate
    pub fn displacement(&mut self, mode: usize, amplitude: Complex) -> DeviceResult<()> {
        if mode >= self.num_modes {
            return Err(DeviceError::InvalidInput(format!(
                "Mode {mode} exceeds sequence capacity"
            )));
        }

        self.gates.push((
            CVGateType::Displacement { amplitude },
            CVGateParams {
                real_params: vec![amplitude.real, amplitude.imag],
                complex_params: vec![amplitude],
                target_modes: vec![mode],
                control_modes: vec![],
            },
        ));

        Ok(())
    }

    /// Add a squeezing gate
    pub fn squeezing(&mut self, mode: usize, parameter: f64, phase: f64) -> DeviceResult<()> {
        if mode >= self.num_modes {
            return Err(DeviceError::InvalidInput(format!(
                "Mode {mode} exceeds sequence capacity"
            )));
        }

        self.gates.push((
            CVGateType::Squeezing { parameter, phase },
            CVGateParams {
                real_params: vec![parameter, phase],
                complex_params: vec![],
                target_modes: vec![mode],
                control_modes: vec![],
            },
        ));

        Ok(())
    }

    /// Add a two-mode squeezing gate
    pub fn two_mode_squeezing(
        &mut self,
        mode1: usize,
        mode2: usize,
        parameter: f64,
        phase: f64,
    ) -> DeviceResult<()> {
        if mode1 >= self.num_modes || mode2 >= self.num_modes {
            return Err(DeviceError::InvalidInput(
                "One or both modes exceed sequence capacity".to_string(),
            ));
        }

        self.gates.push((
            CVGateType::TwoModeSqueezing { parameter, phase },
            CVGateParams {
                real_params: vec![parameter, phase],
                complex_params: vec![],
                target_modes: vec![mode1, mode2],
                control_modes: vec![],
            },
        ));

        Ok(())
    }

    /// Add a beamsplitter gate
    pub fn beamsplitter(
        &mut self,
        mode1: usize,
        mode2: usize,
        transmittance: f64,
        phase: f64,
    ) -> DeviceResult<()> {
        if mode1 >= self.num_modes || mode2 >= self.num_modes {
            return Err(DeviceError::InvalidInput(
                "One or both modes exceed sequence capacity".to_string(),
            ));
        }

        if !(0.0..=1.0).contains(&transmittance) {
            return Err(DeviceError::InvalidInput(
                "Transmittance must be between 0 and 1".to_string(),
            ));
        }

        self.gates.push((
            CVGateType::Beamsplitter {
                transmittance,
                phase,
            },
            CVGateParams {
                real_params: vec![transmittance, phase],
                complex_params: vec![],
                target_modes: vec![mode1, mode2],
                control_modes: vec![],
            },
        ));

        Ok(())
    }

    /// Add a phase rotation gate
    pub fn phase_rotation(&mut self, mode: usize, phase: f64) -> DeviceResult<()> {
        if mode >= self.num_modes {
            return Err(DeviceError::InvalidInput(format!(
                "Mode {mode} exceeds sequence capacity"
            )));
        }

        self.gates.push((
            CVGateType::PhaseRotation { phase },
            CVGateParams {
                real_params: vec![phase],
                complex_params: vec![],
                target_modes: vec![mode],
                control_modes: vec![],
            },
        ));

        Ok(())
    }

    /// Add a controlled displacement gate
    pub fn controlled_displacement(
        &mut self,
        control_mode: usize,
        target_mode: usize,
        amplitude: Complex,
    ) -> DeviceResult<()> {
        if control_mode >= self.num_modes || target_mode >= self.num_modes {
            return Err(DeviceError::InvalidInput(
                "Control or target mode exceeds sequence capacity".to_string(),
            ));
        }

        self.gates.push((
            CVGateType::ControlledDisplacement { amplitude },
            CVGateParams {
                real_params: vec![amplitude.real, amplitude.imag],
                complex_params: vec![amplitude],
                target_modes: vec![target_mode],
                control_modes: vec![control_mode],
            },
        ));

        Ok(())
    }

    /// Add a controlled phase gate
    pub fn controlled_phase(
        &mut self,
        control_mode: usize,
        target_mode: usize,
        parameter: f64,
    ) -> DeviceResult<()> {
        if control_mode >= self.num_modes || target_mode >= self.num_modes {
            return Err(DeviceError::InvalidInput(
                "Control or target mode exceeds sequence capacity".to_string(),
            ));
        }

        self.gates.push((
            CVGateType::ControlledPhase { parameter },
            CVGateParams {
                real_params: vec![parameter],
                complex_params: vec![],
                target_modes: vec![target_mode],
                control_modes: vec![control_mode],
            },
        ));

        Ok(())
    }

    /// Add a cross-Kerr gate
    pub fn cross_kerr(&mut self, mode1: usize, mode2: usize, parameter: f64) -> DeviceResult<()> {
        if mode1 >= self.num_modes || mode2 >= self.num_modes {
            return Err(DeviceError::InvalidInput(
                "One or both modes exceed sequence capacity".to_string(),
            ));
        }

        self.gates.push((
            CVGateType::CrossKerr { parameter },
            CVGateParams {
                real_params: vec![parameter],
                complex_params: vec![],
                target_modes: vec![mode1, mode2],
                control_modes: vec![],
            },
        ));

        Ok(())
    }

    /// Add a cubic phase gate (non-Gaussian)
    pub fn cubic_phase(&mut self, mode: usize, parameter: f64) -> DeviceResult<()> {
        if mode >= self.num_modes {
            return Err(DeviceError::InvalidInput(format!(
                "Mode {mode} exceeds sequence capacity"
            )));
        }

        self.gates.push((
            CVGateType::CubicPhase { parameter },
            CVGateParams {
                real_params: vec![parameter],
                complex_params: vec![],
                target_modes: vec![mode],
                control_modes: vec![],
            },
        ));

        Ok(())
    }

    /// Get the number of gates in the sequence
    pub fn gate_count(&self) -> usize {
        self.gates.len()
    }

    /// Get the depth of the sequence (maximum number of gates on any mode)
    pub fn depth(&self) -> usize {
        let mut mode_depths = vec![0; self.num_modes];

        for (_, params) in &self.gates {
            for &mode in &params.target_modes {
                mode_depths[mode] += 1;
            }
            for &mode in &params.control_modes {
                mode_depths[mode] += 1;
            }
        }

        *mode_depths.iter().max().unwrap_or(&0)
    }

    /// Check if the sequence contains only Gaussian operations
    pub fn is_gaussian(&self) -> bool {
        for (gate_type, _) in &self.gates {
            match gate_type {
                CVGateType::CubicPhase { .. }
                | CVGateType::PositionMeasurement { .. }
                | CVGateType::MomentumMeasurement { .. } => return false,
                _ => continue,
            }
        }
        true
    }

    /// Execute the gate sequence on a Gaussian state
    pub fn execute_on_state(&self, state: &mut GaussianState) -> DeviceResult<()> {
        if state.num_modes != self.num_modes {
            return Err(DeviceError::InvalidInput(
                "State mode count doesn't match sequence requirements".to_string(),
            ));
        }

        for (gate_type, params) in &self.gates {
            self.execute_single_gate(gate_type, params, state)?;
        }

        Ok(())
    }

    /// Execute a single gate on the state
    fn execute_single_gate(
        &self,
        gate_type: &CVGateType,
        params: &CVGateParams,
        state: &mut GaussianState,
    ) -> DeviceResult<()> {
        match gate_type {
            CVGateType::Displacement { amplitude } => {
                if params.target_modes.len() != 1 {
                    return Err(DeviceError::InvalidInput(
                        "Displacement gate requires exactly one target mode".to_string(),
                    ));
                }
                state.apply_displacement(params.target_modes[0], *amplitude)?;
            }

            CVGateType::Squeezing { parameter, phase } => {
                if params.target_modes.len() != 1 {
                    return Err(DeviceError::InvalidInput(
                        "Squeezing gate requires exactly one target mode".to_string(),
                    ));
                }
                state.apply_squeezing(params.target_modes[0], *parameter, *phase)?;
            }

            CVGateType::TwoModeSqueezing { parameter, phase } => {
                if params.target_modes.len() != 2 {
                    return Err(DeviceError::InvalidInput(
                        "Two-mode squeezing gate requires exactly two target modes".to_string(),
                    ));
                }
                state.apply_two_mode_squeezing(
                    params.target_modes[0],
                    params.target_modes[1],
                    *parameter,
                    *phase,
                )?;
            }

            CVGateType::Beamsplitter {
                transmittance,
                phase,
            } => {
                if params.target_modes.len() != 2 {
                    return Err(DeviceError::InvalidInput(
                        "Beamsplitter gate requires exactly two target modes".to_string(),
                    ));
                }
                state.apply_beamsplitter(
                    params.target_modes[0],
                    params.target_modes[1],
                    *transmittance,
                    *phase,
                )?;
            }

            CVGateType::PhaseRotation { phase } => {
                if params.target_modes.len() != 1 {
                    return Err(DeviceError::InvalidInput(
                        "Phase rotation gate requires exactly one target mode".to_string(),
                    ));
                }
                state.apply_phase_rotation(params.target_modes[0], *phase)?;
            }

            CVGateType::ControlledDisplacement { amplitude } => {
                if params.control_modes.len() != 1 || params.target_modes.len() != 1 {
                    return Err(DeviceError::InvalidInput(
                        "Controlled displacement requires one control and one target mode"
                            .to_string(),
                    ));
                }
                self.apply_controlled_displacement(
                    params.control_modes[0],
                    params.target_modes[0],
                    *amplitude,
                    state,
                )?;
            }

            CVGateType::ControlledPhase { parameter } => {
                if params.control_modes.len() != 1 || params.target_modes.len() != 1 {
                    return Err(DeviceError::InvalidInput(
                        "Controlled phase requires one control and one target mode".to_string(),
                    ));
                }
                self.apply_controlled_phase(
                    params.control_modes[0],
                    params.target_modes[0],
                    *parameter,
                    state,
                )?;
            }

            CVGateType::CrossKerr { parameter } => {
                if params.target_modes.len() != 2 {
                    return Err(DeviceError::InvalidInput(
                        "Cross-Kerr gate requires exactly two target modes".to_string(),
                    ));
                }
                self.apply_cross_kerr(
                    params.target_modes[0],
                    params.target_modes[1],
                    *parameter,
                    state,
                )?;
            }

            CVGateType::CubicPhase { parameter } => {
                return Err(DeviceError::UnsupportedOperation(
                    "Cubic phase gate is non-Gaussian and not supported for Gaussian states"
                        .to_string(),
                ));
            }

            CVGateType::PositionMeasurement { .. } | CVGateType::MomentumMeasurement { .. } => {
                return Err(DeviceError::UnsupportedOperation(
                    "Measurements should be performed separately from gate sequences".to_string(),
                ));
            }
        }

        Ok(())
    }

    /// Apply controlled displacement (simplified implementation)
    fn apply_controlled_displacement(
        &self,
        control_mode: usize,
        target_mode: usize,
        amplitude: Complex,
        state: &mut GaussianState,
    ) -> DeviceResult<()> {
        // Simplified implementation - would need full multimode transformation
        // For now, apply displacement scaled by control mode amplitude
        let control_amplitude = Complex::new(
            state.mean_vector[2 * control_mode] / (2.0_f64).sqrt(),
            state.mean_vector[2 * control_mode + 1] / (2.0_f64).sqrt(),
        );

        let scaled_amplitude = amplitude * control_amplitude.magnitude();
        state.apply_displacement(target_mode, scaled_amplitude)?;

        Ok(())
    }

    /// Apply controlled phase (simplified implementation)
    fn apply_controlled_phase(
        &self,
        control_mode: usize,
        target_mode: usize,
        parameter: f64,
        state: &mut GaussianState,
    ) -> DeviceResult<()> {
        // Simplified implementation
        let control_photon_number = self.estimate_photon_number(control_mode, state);
        let phase = parameter * control_photon_number;
        state.apply_phase_rotation(target_mode, phase)?;

        Ok(())
    }

    /// Apply cross-Kerr interaction
    fn apply_cross_kerr(
        &self,
        mode1: usize,
        mode2: usize,
        parameter: f64,
        state: &mut GaussianState,
    ) -> DeviceResult<()> {
        // Simplified cross-Kerr implementation
        // Cross-Kerr induces phase shifts proportional to photon numbers
        let n1 = self.estimate_photon_number(mode1, state);
        let n2 = self.estimate_photon_number(mode2, state);

        state.apply_phase_rotation(mode1, parameter * n2)?;
        state.apply_phase_rotation(mode2, parameter * n1)?;

        Ok(())
    }

    /// Estimate photon number for a mode (for simplified implementations)
    fn estimate_photon_number(&self, mode: usize, state: &GaussianState) -> f64 {
        let mean_x = state.mean_vector[2 * mode];
        let mean_p = state.mean_vector[2 * mode + 1];
        let var_x = state.covariancematrix[2 * mode][2 * mode];
        let var_p = state.covariancematrix[2 * mode + 1][2 * mode + 1];

        // Average photon number approximation
        0.5 * (mean_p.mul_add(mean_p, mean_x.powi(2)) / 2.0 + (var_x + var_p) - 1.0)
    }
}

/// Common CV gate implementations
pub struct CVGateLibrary;

impl CVGateLibrary {
    /// Create a displacement gate
    pub fn displacement(amplitude: Complex) -> (CVGateType, CVGateParams) {
        (
            CVGateType::Displacement { amplitude },
            CVGateParams {
                real_params: vec![amplitude.real, amplitude.imag],
                complex_params: vec![amplitude],
                target_modes: vec![],
                control_modes: vec![],
            },
        )
    }

    /// Create a squeezing gate
    pub fn squeezing(parameter: f64, phase: f64) -> (CVGateType, CVGateParams) {
        (
            CVGateType::Squeezing { parameter, phase },
            CVGateParams {
                real_params: vec![parameter, phase],
                complex_params: vec![],
                target_modes: vec![],
                control_modes: vec![],
            },
        )
    }

    /// Create a 50:50 beamsplitter
    pub fn balanced_beamsplitter() -> (CVGateType, CVGateParams) {
        (
            CVGateType::Beamsplitter {
                transmittance: 0.5,
                phase: 0.0,
            },
            CVGateParams {
                real_params: vec![0.5, 0.0],
                complex_params: vec![],
                target_modes: vec![],
                control_modes: vec![],
            },
        )
    }

    /// Create a Hadamard-like operation for CV (Fourier transform)
    pub fn fourier_transform() -> CVGateSequence {
        let mut sequence = CVGateSequence::new(1);
        sequence
            .phase_rotation(0, PI / 2.0)
            .expect("Phase rotation on mode 0 should always succeed for single-mode sequence");
        sequence
    }

    /// Create a CNOT-like operation for CV
    pub fn cv_cnot() -> CVGateSequence {
        let mut sequence = CVGateSequence::new(2);
        // Simplified CV CNOT using beamsplitter and phase rotations
        sequence
            .beamsplitter(0, 1, 0.5, 0.0)
            .expect("Beamsplitter on modes 0,1 should always succeed for two-mode sequence");
        sequence
            .phase_rotation(1, PI)
            .expect("Phase rotation on mode 1 should always succeed for two-mode sequence");
        sequence
            .beamsplitter(0, 1, 0.5, 0.0)
            .expect("Beamsplitter on modes 0,1 should always succeed for two-mode sequence");
        sequence
    }

    /// Create an EPR pair generation sequence
    pub fn epr_pair_generation(squeezing_param: f64) -> CVGateSequence {
        let mut sequence = CVGateSequence::new(2);
        sequence
            .two_mode_squeezing(0, 1, squeezing_param, 0.0)
            .expect("Two-mode squeezing on modes 0,1 should always succeed for two-mode sequence");
        sequence
    }

    /// Create a GKP (Gottesman-Kitaev-Preskill) state preparation sequence
    pub fn gkp_state_preparation() -> CVGateSequence {
        let mut sequence = CVGateSequence::new(1);
        // Simplified GKP preparation using multiple squeezing operations
        for i in 0..10 {
            let phase = 2.0 * PI * i as f64 / 10.0;
            sequence
                .squeezing(0, 0.5, phase)
                .expect("Squeezing on mode 0 should always succeed for single-mode sequence");
        }
        sequence
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_gate_sequence_creation() {
        let mut sequence = CVGateSequence::new(3);
        assert_eq!(sequence.num_modes, 3);
        assert_eq!(sequence.gate_count(), 0);
    }

    #[test]
    fn test_displacement_gate_addition() {
        let mut sequence = CVGateSequence::new(2);
        let amplitude = Complex::new(1.0, 0.5);

        sequence
            .displacement(0, amplitude)
            .expect("Failed to add displacement gate");
        assert_eq!(sequence.gate_count(), 1);

        match &sequence.gates[0].0 {
            CVGateType::Displacement { amplitude: a } => {
                assert_eq!(*a, amplitude);
            }
            _ => panic!("Expected displacement gate"),
        }
    }

    #[test]
    fn test_beamsplitter_gate_addition() {
        let mut sequence = CVGateSequence::new(2);

        sequence
            .beamsplitter(0, 1, 0.7, PI / 4.0)
            .expect("Failed to add beamsplitter gate");
        assert_eq!(sequence.gate_count(), 1);

        match &sequence.gates[0].0 {
            CVGateType::Beamsplitter {
                transmittance,
                phase,
            } => {
                assert_eq!(*transmittance, 0.7);
                assert_eq!(*phase, PI / 4.0);
            }
            _ => panic!("Expected beamsplitter gate"),
        }
    }

    #[test]
    fn test_gaussian_property() {
        let mut sequence = CVGateSequence::new(2);

        sequence
            .displacement(0, Complex::new(1.0, 0.0))
            .expect("Failed to add displacement gate");
        sequence
            .squeezing(1, 0.5, 0.0)
            .expect("Failed to add squeezing gate");
        sequence
            .beamsplitter(0, 1, 0.5, 0.0)
            .expect("Failed to add beamsplitter gate");

        assert!(sequence.is_gaussian());

        sequence
            .cubic_phase(0, 0.1)
            .expect("Failed to add cubic phase gate");
        assert!(!sequence.is_gaussian());
    }

    #[test]
    fn test_sequence_depth_calculation() {
        let mut sequence = CVGateSequence::new(3);

        sequence
            .displacement(0, Complex::new(1.0, 0.0))
            .expect("Failed to add first displacement gate");
        sequence
            .displacement(0, Complex::new(0.5, 0.0))
            .expect("Failed to add second displacement gate");
        sequence
            .squeezing(1, 0.5, 0.0)
            .expect("Failed to add squeezing gate");
        sequence
            .beamsplitter(0, 2, 0.5, 0.0)
            .expect("Failed to add beamsplitter gate");

        assert_eq!(sequence.depth(), 3); // Mode 0 has 3 operations
    }

    #[test]
    fn test_gate_execution_on_state() {
        let mut sequence = CVGateSequence::new(2);
        sequence
            .displacement(0, Complex::new(1.0, 0.0))
            .expect("Failed to add displacement gate");
        sequence
            .squeezing(1, 0.5, 0.0)
            .expect("Failed to add squeezing gate");

        let mut state = GaussianState::vacuum_state(2);
        sequence
            .execute_on_state(&mut state)
            .expect("Failed to execute gate sequence on state");

        // Check that the displacement was applied
        assert!(state.mean_vector[0] > 0.0);

        // Check that squeezing was applied
        // For mode 1 (index 2 for x-quadrature), squeezing should reduce variance
        // Expected: 0.5 * exp(-2*r) = 0.5 * exp(-1) ≈ 0.184
        assert!(state.covariancematrix[2][2] < 0.5);
    }

    #[test]
    fn test_epr_pair_generation() {
        let sequence = CVGateLibrary::epr_pair_generation(1.0);
        assert_eq!(sequence.gate_count(), 1);

        let mut state = GaussianState::vacuum_state(2);
        sequence
            .execute_on_state(&mut state)
            .expect("Failed to execute EPR pair generation sequence");

        // EPR state should have correlations between modes
        let entanglement = state.calculate_entanglement_measures();
        assert!(entanglement.epr_correlation > 0.0);
    }

    #[test]
    fn test_balanced_beamsplitter() {
        let (gate_type, params) = CVGateLibrary::balanced_beamsplitter();

        match gate_type {
            CVGateType::Beamsplitter {
                transmittance,
                phase,
            } => {
                assert_eq!(transmittance, 0.5);
                assert_eq!(phase, 0.0);
            }
            _ => panic!("Expected balanced beamsplitter"),
        }
    }

    #[test]
    fn test_invalid_mode_error() {
        let mut sequence = CVGateSequence::new(2);

        let result = sequence.displacement(3, Complex::new(1.0, 0.0));
        assert!(result.is_err());

        let result = sequence.beamsplitter(0, 3, 0.5, 0.0);
        assert!(result.is_err());
    }
}