quantrs2-core 0.1.3

Core types and traits for the QuantRS2 quantum computing 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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
//! Neutral Atom Quantum Computing Platform
//!
//! This module implements neutral atom quantum computing using ultracold atoms
//! trapped in optical tweezers. It includes:
//! - Rydberg atom interactions for two-qubit gates
//! - Optical tweezer array management
//! - Laser pulse sequences for gate operations
//! - Atom loading and arrangement protocols
//! - Error models for neutral atom platforms

use crate::{
    error::{QuantRS2Error, QuantRS2Result},
    qubit::QubitId,
};
use rustc_hash::FxHashMap;
use scirs2_core::ndarray::{Array1, Array2};
use scirs2_core::Complex64;
use std::collections::HashMap;
use std::f64::consts::PI;

/// Types of neutral atoms used for quantum computing
#[derive(Debug, Clone, PartialEq)]
pub enum AtomSpecies {
    /// Rubidium-87 (commonly used)
    Rb87,
    /// Cesium-133
    Cs133,
    /// Strontium-88
    Sr88,
    /// Ytterbium-171
    Yb171,
    /// Custom atom with specified properties
    Custom {
        mass: f64,             // atomic mass in u
        ground_state: String,  // ground state configuration
        rydberg_state: String, // Rydberg state used
    },
}

impl AtomSpecies {
    /// Get atomic mass in atomic mass units
    pub const fn mass(&self) -> f64 {
        match self {
            Self::Rb87 => 86.909_183,
            Self::Cs133 => 132.905_447,
            Self::Sr88 => 87.905_614,
            Self::Yb171 => 170.936_426,
            Self::Custom { mass, .. } => *mass,
        }
    }

    /// Get typical trap depth in μK
    pub const fn typical_trap_depth(&self) -> f64 {
        match self {
            Self::Rb87 | Self::Custom { .. } => 1000.0,
            Self::Cs133 => 800.0,
            Self::Sr88 => 1200.0,
            Self::Yb171 => 900.0,
        }
    }

    /// Get Rydberg state energy in GHz
    pub const fn rydberg_energy(&self) -> f64 {
        match self {
            Self::Rb87 | Self::Custom { .. } => 100.0, // Example value
            Self::Cs133 => 95.0,
            Self::Sr88 => 110.0,
            Self::Yb171 => 105.0,
        }
    }
}

/// Position in 3D space (in micrometers)
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Position3D {
    pub x: f64,
    pub y: f64,
    pub z: f64,
}

impl Position3D {
    pub const fn new(x: f64, y: f64, z: f64) -> Self {
        Self { x, y, z }
    }

    /// Calculate distance to another position
    pub fn distance_to(&self, other: &Self) -> f64 {
        (self.z - other.z)
            .mul_add(
                self.z - other.z,
                (self.y - other.y).mul_add(self.y - other.y, (self.x - other.x).powi(2)),
            )
            .sqrt()
    }

    /// Calculate Rydberg interaction strength at this distance
    pub fn rydberg_interaction(&self, other: &Self, c6: f64) -> f64 {
        let distance = self.distance_to(other);
        if distance == 0.0 {
            f64::INFINITY
        } else {
            c6 / distance.powi(6) // van der Waals interaction
        }
    }
}

/// State of a neutral atom
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AtomState {
    /// Ground state |g⟩
    Ground,
    /// Rydberg state |r⟩
    Rydberg,
    /// Intermediate state during laser transitions
    Intermediate,
    /// Atom is missing (loading failure)
    Missing,
}

/// Individual neutral atom in an optical tweezer
#[derive(Debug, Clone)]
pub struct NeutralAtom {
    /// Atom species
    pub species: AtomSpecies,
    /// Position in the tweezer array
    pub position: Position3D,
    /// Current quantum state
    pub state: AtomState,
    /// Loading probability (success rate)
    pub loading_probability: f64,
    /// Lifetime in trap (seconds)
    pub lifetime: f64,
    /// Coherence time (seconds)
    pub coherence_time: f64,
}

impl NeutralAtom {
    /// Create a new neutral atom
    pub const fn new(species: AtomSpecies, position: Position3D) -> Self {
        Self {
            species,
            position,
            state: AtomState::Ground,
            loading_probability: 0.9, // 90% loading success
            lifetime: 100.0,          // 100 seconds
            coherence_time: 1.0,      // 1 second
        }
    }

    /// Check if atom is successfully loaded
    pub fn is_loaded(&self) -> bool {
        self.state != AtomState::Missing
    }

    /// Calculate interaction strength with another atom
    pub fn interaction_with(&self, other: &Self) -> f64 {
        // C6 coefficient for Rydberg interactions (MHz·μm^6)
        let c6 = match (&self.species, &other.species) {
            (AtomSpecies::Cs133, AtomSpecies::Cs133) => 6000.0,
            (AtomSpecies::Sr88, AtomSpecies::Sr88) => 4500.0,
            (AtomSpecies::Yb171, AtomSpecies::Yb171) => 4800.0,
            (AtomSpecies::Rb87, AtomSpecies::Rb87) | _ => 5000.0, // Rb87 and mixed species
        };

        self.position.rydberg_interaction(&other.position, c6)
    }
}

/// Optical tweezer for trapping individual atoms
#[derive(Debug, Clone)]
pub struct OpticalTweezer {
    /// Position of the tweezer focus
    pub position: Position3D,
    /// Laser power (mW)
    pub power: f64,
    /// Wavelength (nm)
    pub wavelength: f64,
    /// Numerical aperture of focusing objective
    pub numerical_aperture: f64,
    /// Whether tweezer is active
    pub active: bool,
    /// Trapped atom (if any)
    pub atom: Option<NeutralAtom>,
}

impl OpticalTweezer {
    /// Create a new optical tweezer
    pub const fn new(
        position: Position3D,
        power: f64,
        wavelength: f64,
        numerical_aperture: f64,
    ) -> Self {
        Self {
            position,
            power,
            wavelength,
            numerical_aperture,
            active: true,
            atom: None,
        }
    }

    /// Calculate trap depth in μK
    pub fn trap_depth(&self) -> f64 {
        if !self.active {
            return 0.0;
        }

        // Simplified calculation: depth ∝ power / (wavelength * beam_waist²)
        let beam_waist = self.wavelength / (PI * self.numerical_aperture); // Rough approximation
        (self.power * 1000.0) / (self.wavelength * beam_waist.powi(2))
    }

    /// Load an atom into the tweezer
    pub fn load_atom(&mut self, mut atom: NeutralAtom) -> bool {
        if !self.active || self.atom.is_some() {
            return false;
        }

        // Simulate probabilistic loading
        use scirs2_core::random::prelude::*;
        let mut rng = thread_rng();
        let success = rng.random::<f64>() < atom.loading_probability;

        if success {
            atom.position = self.position;
            self.atom = Some(atom);
            true
        } else {
            false
        }
    }

    /// Remove atom from tweezer
    pub const fn remove_atom(&mut self) -> Option<NeutralAtom> {
        self.atom.take()
    }

    /// Check if tweezer has an atom
    pub const fn has_atom(&self) -> bool {
        self.atom.is_some()
    }
}

/// Laser system for controlling neutral atoms
#[derive(Debug, Clone)]
pub struct LaserSystem {
    /// Wavelength in nm
    pub wavelength: f64,
    /// Power in mW
    pub power: f64,
    /// Beam waist in μm
    pub beam_waist: f64,
    /// Detuning from atomic transition in MHz
    pub detuning: f64,
    /// Laser linewidth in kHz
    pub linewidth: f64,
    /// Whether laser is currently on
    pub active: bool,
}

impl LaserSystem {
    /// Create a new laser system
    pub const fn new(wavelength: f64, power: f64, beam_waist: f64, detuning: f64) -> Self {
        Self {
            wavelength,
            power,
            beam_waist,
            detuning,
            linewidth: 1.0, // 1 kHz linewidth
            active: false,
        }
    }

    /// Calculate Rabi frequency in MHz
    pub fn rabi_frequency(&self) -> f64 {
        if !self.active {
            return 0.0;
        }

        // Simplified: Ω ∝ √(power) / beam_waist
        (self.power.sqrt() * 10.0) / self.beam_waist
    }

    /// Set laser detuning
    pub const fn set_detuning(&mut self, detuning: f64) {
        self.detuning = detuning;
    }

    /// Turn laser on/off
    pub const fn set_active(&mut self, active: bool) {
        self.active = active;
    }
}

/// Neutral atom quantum computer platform
#[derive(Debug)]
pub struct NeutralAtomQC {
    /// Array of optical tweezers
    pub tweezers: Vec<OpticalTweezer>,
    /// Map from qubit ID to tweezer index
    pub qubit_map: FxHashMap<QubitId, usize>,
    /// Laser systems for different transitions
    pub lasers: HashMap<String, LaserSystem>,
    /// Current quantum state (simplified representation)
    pub state: Array1<Complex64>,
    /// Number of qubits
    pub num_qubits: usize,
    /// Global phase accumulation
    pub global_phase: f64,
    /// Error model parameters
    pub error_model: NeutralAtomErrorModel,
}

impl NeutralAtomQC {
    /// Create a new neutral atom quantum computer
    pub fn new(num_qubits: usize) -> Self {
        let mut tweezers = Vec::new();
        let mut qubit_map = FxHashMap::default();

        // Create a linear array of tweezers
        for i in 0..num_qubits {
            let position = Position3D::new(i as f64 * 5.0, 0.0, 0.0); // 5 μm spacing
            let tweezer = OpticalTweezer::new(
                position, 1.0,    // 1 mW power
                1064.0, // 1064 nm wavelength
                0.75,   // NA = 0.75
            );
            tweezers.push(tweezer);
            qubit_map.insert(QubitId(i as u32), i);
        }

        // Setup laser systems
        let mut lasers = HashMap::new();

        // Cooling laser (for Rb87)
        lasers.insert(
            "cooling".to_string(),
            LaserSystem::new(780.0, 10.0, 100.0, -10.0),
        );

        // Rydberg excitation laser
        lasers.insert(
            "rydberg".to_string(),
            LaserSystem::new(480.0, 1.0, 2.0, 0.0),
        );

        // Two-photon Raman laser
        lasers.insert("raman".to_string(), LaserSystem::new(795.0, 5.0, 10.0, 0.0));

        // Initialize quantum state to |00...0⟩
        let dim = 1 << num_qubits;
        let mut state = Array1::zeros(dim);
        state[0] = Complex64::new(1.0, 0.0);

        Self {
            tweezers,
            qubit_map,
            lasers,
            state,
            num_qubits,
            global_phase: 0.0,
            error_model: NeutralAtomErrorModel::default(),
        }
    }

    /// Load atoms into the tweezer array
    pub fn load_atoms(&mut self, species: AtomSpecies) -> QuantRS2Result<usize> {
        let mut loaded_count = 0;

        for tweezer in &mut self.tweezers {
            let atom = NeutralAtom::new(species.clone(), tweezer.position);
            if tweezer.load_atom(atom) {
                loaded_count += 1;
            }
        }

        Ok(loaded_count)
    }

    /// Perform atom rearrangement to fill gaps
    pub fn rearrange_atoms(&mut self) -> QuantRS2Result<()> {
        // Collect all loaded atoms
        let mut atoms = Vec::new();
        for tweezer in &mut self.tweezers {
            if let Some(atom) = tweezer.remove_atom() {
                atoms.push(atom);
            }
        }

        // Redistribute atoms to fill tweezers from the beginning
        for (i, atom) in atoms.into_iter().enumerate() {
            if i < self.tweezers.len() {
                self.tweezers[i].load_atom(atom);
            }
        }

        Ok(())
    }

    /// Apply single-qubit rotation gate
    pub fn apply_single_qubit_gate(
        &mut self,
        qubit: QubitId,
        gate_matrix: &Array2<Complex64>,
    ) -> QuantRS2Result<()> {
        let tweezer_idx = *self
            .qubit_map
            .get(&qubit)
            .ok_or_else(|| QuantRS2Error::InvalidInput(format!("Qubit {qubit:?} not found")))?;

        // Check if atom is present
        if !self.tweezers[tweezer_idx].has_atom() {
            return Err(QuantRS2Error::InvalidOperation(
                "No atom in tweezer".to_string(),
            ));
        }

        // Apply gate using tensor product
        let qubit_index = qubit.0 as usize;
        let new_state = self.apply_single_qubit_tensor(qubit_index, gate_matrix)?;
        self.state = new_state;

        // Apply errors
        self.apply_single_qubit_errors(qubit_index)?;

        Ok(())
    }

    /// Apply two-qubit Rydberg gate
    pub fn apply_rydberg_gate(&mut self, control: QubitId, target: QubitId) -> QuantRS2Result<()> {
        let control_idx = *self.qubit_map.get(&control).ok_or_else(|| {
            QuantRS2Error::InvalidInput(format!("Control qubit {control:?} not found"))
        })?;
        let target_idx = *self.qubit_map.get(&target).ok_or_else(|| {
            QuantRS2Error::InvalidInput(format!("Target qubit {target:?} not found"))
        })?;

        // Check if both atoms are present
        if !self.tweezers[control_idx].has_atom() || !self.tweezers[target_idx].has_atom() {
            return Err(QuantRS2Error::InvalidOperation(
                "Missing atoms for two-qubit gate".to_string(),
            ));
        }

        // Check interaction strength
        let control_atom = self.tweezers[control_idx].atom.as_ref().ok_or_else(|| {
            QuantRS2Error::InvalidOperation("Control atom unexpectedly missing".to_string())
        })?;
        let target_atom = self.tweezers[target_idx].atom.as_ref().ok_or_else(|| {
            QuantRS2Error::InvalidOperation("Target atom unexpectedly missing".to_string())
        })?;
        let interaction = control_atom.interaction_with(target_atom);

        if interaction < 1.0 {
            // Minimum interaction strength in MHz
            return Err(QuantRS2Error::InvalidOperation(
                "Insufficient Rydberg interaction".to_string(),
            ));
        }

        // Apply Rydberg CZ gate (simplified)
        let cz_matrix = self.create_rydberg_cz_matrix()?;
        let new_state =
            self.apply_two_qubit_tensor(control.0 as usize, target.0 as usize, &cz_matrix)?;
        self.state = new_state;

        // Apply errors
        self.apply_two_qubit_errors(control.0 as usize, target.0 as usize)?;

        Ok(())
    }

    /// Create Rydberg CZ gate matrix
    fn create_rydberg_cz_matrix(&self) -> QuantRS2Result<Array2<Complex64>> {
        let mut cz = Array2::eye(4);
        cz[[3, 3]] = Complex64::new(-1.0, 0.0); // |11⟩ → -|11⟩
        Ok(cz)
    }

    /// Apply single-qubit gate using tensor product
    fn apply_single_qubit_tensor(
        &self,
        qubit_idx: usize,
        gate: &Array2<Complex64>,
    ) -> QuantRS2Result<Array1<Complex64>> {
        let dim = 1 << self.num_qubits;
        let mut new_state = Array1::zeros(dim);

        for state in 0..dim {
            let qubit_bit = (state >> qubit_idx) & 1;
            let other_bits = state & !(1 << qubit_idx);

            for new_qubit_bit in 0..2 {
                let new_state_idx = other_bits | (new_qubit_bit << qubit_idx);
                let gate_element = gate[[new_qubit_bit, qubit_bit]];
                new_state[new_state_idx] += gate_element * self.state[state];
            }
        }

        Ok(new_state)
    }

    /// Apply two-qubit gate using tensor product
    fn apply_two_qubit_tensor(
        &self,
        qubit1: usize,
        qubit2: usize,
        gate: &Array2<Complex64>,
    ) -> QuantRS2Result<Array1<Complex64>> {
        let dim = 1 << self.num_qubits;
        let mut new_state = Array1::zeros(dim);

        for state in 0..dim {
            let bit1 = (state >> qubit1) & 1;
            let bit2 = (state >> qubit2) & 1;
            let other_bits = state & !((1 << qubit1) | (1 << qubit2));
            let two_qubit_state = (bit1 << 1) | bit2;

            for new_two_qubit_state in 0..4 {
                let new_bit1 = (new_two_qubit_state >> 1) & 1;
                let new_bit2 = new_two_qubit_state & 1;
                let new_state_idx = other_bits | (new_bit1 << qubit1) | (new_bit2 << qubit2);

                let gate_element = gate[[new_two_qubit_state, two_qubit_state]];
                new_state[new_state_idx] += gate_element * self.state[state];
            }
        }

        Ok(new_state)
    }

    /// Apply single-qubit error models
    fn apply_single_qubit_errors(&mut self, _qubit: usize) -> QuantRS2Result<()> {
        // Simplified error model - in practice would include:
        // - Laser intensity fluctuations
        // - Decoherence from atom motion
        // - Spontaneous emission
        // - AC Stark shifts

        use scirs2_core::random::prelude::*;
        let mut rng = thread_rng();

        // Add small random phase error
        let phase_error = rng.random_range(-0.01..0.01);
        self.global_phase += phase_error;

        Ok(())
    }

    /// Apply two-qubit error models
    fn apply_two_qubit_errors(&mut self, _qubit1: usize, _qubit2: usize) -> QuantRS2Result<()> {
        // Simplified error model for Rydberg gates
        use scirs2_core::random::prelude::*;
        let mut rng = thread_rng();

        // Rydberg gate errors are typically higher
        let phase_error = rng.random_range(-0.05..0.05);
        self.global_phase += phase_error;

        Ok(())
    }

    /// Measure a qubit
    pub fn measure_qubit(&mut self, qubit: QubitId) -> QuantRS2Result<u8> {
        let qubit_idx = qubit.0 as usize;
        if qubit_idx >= self.num_qubits {
            return Err(QuantRS2Error::InvalidInput(
                "Qubit index out of range".to_string(),
            ));
        }

        // Calculate probabilities
        let mut prob_0 = 0.0;
        let mut prob_1 = 0.0;

        for state in 0..(1 << self.num_qubits) {
            let amplitude_sq = self.state[state].norm_sqr();
            if (state >> qubit_idx) & 1 == 0 {
                prob_0 += amplitude_sq;
            } else {
                prob_1 += amplitude_sq;
            }
        }

        // Sample measurement result
        use scirs2_core::random::prelude::*;
        let mut rng = thread_rng();
        let result: usize = usize::from(rng.random::<f64>() >= prob_0 / (prob_0 + prob_1));

        // Collapse state
        let mut new_state = Array1::zeros(1 << self.num_qubits);
        let normalization = if result == 0 {
            prob_0.sqrt()
        } else {
            prob_1.sqrt()
        };

        for state in 0..(1 << self.num_qubits) {
            if ((state >> qubit_idx) & 1) == result {
                new_state[state] = self.state[state] / normalization;
            }
        }

        self.state = new_state;
        Ok(result as u8)
    }

    /// Get number of loaded atoms
    pub fn loaded_atom_count(&self) -> usize {
        self.tweezers.iter().filter(|t| t.has_atom()).count()
    }

    /// Get quantum state probabilities
    pub fn get_probabilities(&self) -> Vec<f64> {
        self.state.iter().map(|c| c.norm_sqr()).collect()
    }

    /// Reset to ground state
    pub fn reset(&mut self) {
        let dim = 1 << self.num_qubits;
        self.state = Array1::zeros(dim);
        self.state[0] = Complex64::new(1.0, 0.0);
        self.global_phase = 0.0;
    }

    /// Get atom positions for visualization
    pub fn get_atom_positions(&self) -> Vec<(QubitId, Position3D, bool)> {
        self.tweezers
            .iter()
            .enumerate()
            .filter_map(|(i, tweezer)| {
                self.qubit_map
                    .iter()
                    .find(|(_, &idx)| idx == i)
                    .map(|(&qubit_id, _)| (qubit_id, tweezer.position, tweezer.has_atom()))
            })
            .collect()
    }
}

/// Error model for neutral atom quantum computing
#[derive(Debug, Clone)]
pub struct NeutralAtomErrorModel {
    /// Loading fidelity (probability of successful atom loading)
    pub loading_fidelity: f64,
    /// Single-qubit gate fidelity
    pub single_qubit_fidelity: f64,
    /// Two-qubit gate fidelity
    pub two_qubit_fidelity: f64,
    /// Measurement fidelity
    pub measurement_fidelity: f64,
    /// Coherence time in seconds
    pub coherence_time: f64,
    /// Rydberg blockade radius in μm
    pub blockade_radius: f64,
}

impl Default for NeutralAtomErrorModel {
    fn default() -> Self {
        Self {
            loading_fidelity: 0.95,
            single_qubit_fidelity: 0.999,
            two_qubit_fidelity: 0.98,
            measurement_fidelity: 0.99,
            coherence_time: 1.0,
            blockade_radius: 10.0,
        }
    }
}

/// Neutral atom gate library
pub struct NeutralAtomGates;

impl NeutralAtomGates {
    /// X gate (π rotation around X-axis)
    pub fn x_gate() -> Array2<Complex64> {
        let mut x = Array2::zeros((2, 2));
        x[[0, 1]] = Complex64::new(1.0, 0.0);
        x[[1, 0]] = Complex64::new(1.0, 0.0);
        x
    }

    /// Y gate (π rotation around Y-axis)
    pub fn y_gate() -> Array2<Complex64> {
        let mut y = Array2::zeros((2, 2));
        y[[0, 1]] = Complex64::new(0.0, -1.0);
        y[[1, 0]] = Complex64::new(0.0, 1.0);
        y
    }

    /// Z gate (π rotation around Z-axis)
    pub fn z_gate() -> Array2<Complex64> {
        let mut z = Array2::zeros((2, 2));
        z[[0, 0]] = Complex64::new(1.0, 0.0);
        z[[1, 1]] = Complex64::new(-1.0, 0.0);
        z
    }

    /// Hadamard gate
    pub fn h_gate() -> Array2<Complex64> {
        let h_val = 1.0 / 2.0_f64.sqrt();
        let mut h = Array2::zeros((2, 2));
        h[[0, 0]] = Complex64::new(h_val, 0.0);
        h[[0, 1]] = Complex64::new(h_val, 0.0);
        h[[1, 0]] = Complex64::new(h_val, 0.0);
        h[[1, 1]] = Complex64::new(-h_val, 0.0);
        h
    }

    /// Rotation around X-axis
    pub fn rx_gate(theta: f64) -> Array2<Complex64> {
        let cos_half = (theta / 2.0).cos();
        let sin_half = (theta / 2.0).sin();

        let mut rx = Array2::zeros((2, 2));
        rx[[0, 0]] = Complex64::new(cos_half, 0.0);
        rx[[0, 1]] = Complex64::new(0.0, -sin_half);
        rx[[1, 0]] = Complex64::new(0.0, -sin_half);
        rx[[1, 1]] = Complex64::new(cos_half, 0.0);
        rx
    }

    /// Rotation around Y-axis
    pub fn ry_gate(theta: f64) -> Array2<Complex64> {
        let cos_half = (theta / 2.0).cos();
        let sin_half = (theta / 2.0).sin();

        let mut ry = Array2::zeros((2, 2));
        ry[[0, 0]] = Complex64::new(cos_half, 0.0);
        ry[[0, 1]] = Complex64::new(-sin_half, 0.0);
        ry[[1, 0]] = Complex64::new(sin_half, 0.0);
        ry[[1, 1]] = Complex64::new(cos_half, 0.0);
        ry
    }

    /// Rotation around Z-axis
    pub fn rz_gate(theta: f64) -> Array2<Complex64> {
        let exp_neg = Complex64::new(0.0, -theta / 2.0).exp();
        let exp_pos = Complex64::new(0.0, theta / 2.0).exp();

        let mut rz = Array2::zeros((2, 2));
        rz[[0, 0]] = exp_neg;
        rz[[1, 1]] = exp_pos;
        rz
    }
}

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

    #[test]
    fn test_atom_species_properties() {
        let rb87 = AtomSpecies::Rb87;
        assert!((rb87.mass() - 86.909183).abs() < 1e-6);
        assert!(rb87.typical_trap_depth() > 0.0);
        assert!(rb87.rydberg_energy() > 0.0);

        let custom = AtomSpecies::Custom {
            mass: 100.0,
            ground_state: "5s".to_string(),
            rydberg_state: "50s".to_string(),
        };
        assert_eq!(custom.mass(), 100.0);
    }

    #[test]
    fn test_position_calculations() {
        let pos1 = Position3D::new(0.0, 0.0, 0.0);
        let pos2 = Position3D::new(3.0, 4.0, 0.0);

        assert_eq!(pos1.distance_to(&pos2), 5.0);

        let interaction = pos1.rydberg_interaction(&pos2, 1000.0);
        assert!(interaction > 0.0);
        assert!(interaction.is_finite());
    }

    #[test]
    fn test_optical_tweezer() {
        let position = Position3D::new(0.0, 0.0, 0.0);
        let mut tweezer = OpticalTweezer::new(position, 1.0, 1064.0, 0.75);

        assert!(tweezer.active);
        assert!(!tweezer.has_atom());
        assert!(tweezer.trap_depth() > 0.0);

        let atom = NeutralAtom::new(AtomSpecies::Rb87, position);
        let loaded = tweezer.load_atom(atom);
        // Loading is probabilistic, so we can't guarantee success
        // Test that loading returns a valid boolean value (no panic)
        let _result = loaded; // Simply verify the operation completes
    }

    #[test]
    fn test_laser_system() {
        let mut laser = LaserSystem::new(780.0, 10.0, 100.0, -10.0);

        assert!(!laser.active);
        assert_eq!(laser.rabi_frequency(), 0.0);

        laser.set_active(true);
        assert!(laser.rabi_frequency() > 0.0);

        laser.set_detuning(5.0);
        assert_eq!(laser.detuning, 5.0);
    }

    #[test]
    fn test_neutral_atom_creation() {
        let position = Position3D::new(1.0, 2.0, 3.0);
        let atom = NeutralAtom::new(AtomSpecies::Rb87, position);

        assert_eq!(atom.species, AtomSpecies::Rb87);
        assert_eq!(atom.position, position);
        assert_eq!(atom.state, AtomState::Ground);
        assert!(atom.is_loaded());
    }

    #[test]
    fn test_neutral_atom_qc_initialization() {
        let qc = NeutralAtomQC::new(3);

        assert_eq!(qc.num_qubits, 3);
        assert_eq!(qc.tweezers.len(), 3);
        assert_eq!(qc.qubit_map.len(), 3);
        assert_eq!(qc.state.len(), 8); // 2^3 = 8

        // Initial state should be |000⟩
        assert!((qc.state[0].norm_sqr() - 1.0).abs() < 1e-10);
        for i in 1..8 {
            assert!(qc.state[i].norm_sqr() < 1e-10);
        }
    }

    #[test]
    fn test_atom_loading() {
        let mut qc = NeutralAtomQC::new(2);
        let loaded = qc
            .load_atoms(AtomSpecies::Rb87)
            .expect("Failed to load atoms");

        // Should attempt to load into both tweezers
        assert!(loaded <= 2);
        assert!(qc.loaded_atom_count() <= 2);
    }

    #[test]
    fn test_single_qubit_gates() {
        let mut qc = NeutralAtomQC::new(1);
        qc.load_atoms(AtomSpecies::Rb87)
            .expect("Failed to load atoms");

        if qc.loaded_atom_count() > 0 {
            let x_gate = NeutralAtomGates::x_gate();
            let result = qc.apply_single_qubit_gate(QubitId(0), &x_gate);

            // If atom is loaded, gate should succeed
            assert!(result.is_ok());
        }
    }

    #[test]
    fn test_two_qubit_rydberg_gate() {
        let mut qc = NeutralAtomQC::new(2);
        qc.load_atoms(AtomSpecies::Rb87)
            .expect("Failed to load atoms");

        if qc.loaded_atom_count() == 2 {
            let result = qc.apply_rydberg_gate(QubitId(0), QubitId(1));
            // Should succeed if both atoms are loaded and close enough
            assert!(result.is_ok() || result.is_err()); // Test interface
        }
    }

    #[test]
    fn test_measurement() {
        let mut qc = NeutralAtomQC::new(1);
        qc.load_atoms(AtomSpecies::Rb87)
            .expect("Failed to load atoms");

        if qc.loaded_atom_count() > 0 {
            let result = qc.measure_qubit(QubitId(0));
            if let Ok(measurement) = result {
                assert!(measurement == 0 || measurement == 1);
            }
        }
    }

    #[test]
    fn test_gate_matrices() {
        let x = NeutralAtomGates::x_gate();
        let y = NeutralAtomGates::y_gate();
        let z = NeutralAtomGates::z_gate();
        let h = NeutralAtomGates::h_gate();

        // Test basic properties
        assert_eq!(x.dim(), (2, 2));
        assert_eq!(y.dim(), (2, 2));
        assert_eq!(z.dim(), (2, 2));
        assert_eq!(h.dim(), (2, 2));

        // Test Pauli X matrix elements
        assert_eq!(x[[0, 1]], Complex64::new(1.0, 0.0));
        assert_eq!(x[[1, 0]], Complex64::new(1.0, 0.0));
        assert_eq!(x[[0, 0]], Complex64::new(0.0, 0.0));
        assert_eq!(x[[1, 1]], Complex64::new(0.0, 0.0));
    }

    #[test]
    fn test_rotation_gates() {
        let rx_pi = NeutralAtomGates::rx_gate(PI);
        let _ry_pi = NeutralAtomGates::ry_gate(PI);
        let _rz_pi = NeutralAtomGates::rz_gate(PI);

        // RX(π) should be approximately -iX
        let x = NeutralAtomGates::x_gate();
        let expected_rx = x.mapv(|x| Complex64::new(0.0, -1.0) * x);

        for i in 0..2 {
            for j in 0..2 {
                assert!((rx_pi[[i, j]] - expected_rx[[i, j]]).norm() < 1e-10);
            }
        }
    }

    #[test]
    fn test_atom_rearrangement() {
        let mut qc = NeutralAtomQC::new(3);

        // Manually add some atoms to non-consecutive tweezers with 100% loading probability
        let mut atom1 = NeutralAtom::new(AtomSpecies::Rb87, qc.tweezers[0].position);
        let mut atom2 = NeutralAtom::new(AtomSpecies::Rb87, qc.tweezers[2].position);
        atom1.loading_probability = 1.0; // Ensure 100% loading success for test
        atom2.loading_probability = 1.0; // Ensure 100% loading success for test
        qc.tweezers[0].atom = Some(atom1);
        qc.tweezers[2].atom = Some(atom2);

        assert_eq!(qc.loaded_atom_count(), 2);

        // Rearrange should succeed
        assert!(qc.rearrange_atoms().is_ok());

        // After rearrangement, atoms should be in consecutive tweezers
        assert!(qc.tweezers[0].has_atom());
        assert!(qc.tweezers[1].has_atom());
        assert!(!qc.tweezers[2].has_atom());
    }

    #[test]
    fn test_error_model_defaults() {
        let error_model = NeutralAtomErrorModel::default();

        assert!(error_model.loading_fidelity > 0.0 && error_model.loading_fidelity <= 1.0);
        assert!(
            error_model.single_qubit_fidelity > 0.0 && error_model.single_qubit_fidelity <= 1.0
        );
        assert!(error_model.two_qubit_fidelity > 0.0 && error_model.two_qubit_fidelity <= 1.0);
        assert!(error_model.measurement_fidelity > 0.0 && error_model.measurement_fidelity <= 1.0);
        assert!(error_model.coherence_time > 0.0);
        assert!(error_model.blockade_radius > 0.0);
    }

    #[test]
    fn test_quantum_state_probabilities() {
        let qc = NeutralAtomQC::new(2);
        let probs = qc.get_probabilities();

        assert_eq!(probs.len(), 4); // 2^2 = 4 states

        // Probabilities should sum to 1
        let total: f64 = probs.iter().sum();
        assert!((total - 1.0).abs() < 1e-10);

        // Initial state |00⟩ should have probability 1
        assert!((probs[0] - 1.0).abs() < 1e-10);
    }

    #[test]
    fn test_atom_position_retrieval() {
        let qc = NeutralAtomQC::new(2);
        let positions = qc.get_atom_positions();

        assert_eq!(positions.len(), 2);

        // Check that positions are returned correctly
        for (qubit_id, position, has_atom) in positions {
            assert!(qubit_id.0 < 2);
            assert!(position.x >= 0.0); // Should be at positive x coordinates
                                        // has_atom depends on loading success, so we just test the interface
                                        // Test that has_atom returns a boolean value
                                        // has_atom is a boolean, so this assertion is always true
                                        // We're just exercising the has_atom method
            let _ = has_atom;
        }
    }
}