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
//! Device implementation for topological quantum computers
//!
//! This module provides the device interface for topological quantum computers,
//! integrating anyon manipulation, braiding, and fusion operations.

use super::{
    anyons::AnyonFactory, braiding::BraidingOperationManager, fusion::FusionOperationExecutor,
    Anyon, BraidingDirection, FusionRuleSet, NonAbelianAnyonType, TopologicalCapabilities,
    TopologicalCharge, TopologicalDevice, TopologicalError, TopologicalQubit, TopologicalResult,
    TopologicalSystemType,
};
use crate::{Circuit, CircuitExecutor, CircuitResult, DeviceError, DeviceResult, QuantumDevice};
use scirs2_core::random::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::Duration;

/// Enhanced topological quantum device with full anyon manipulation
pub struct EnhancedTopologicalDevice {
    /// Core topological device
    pub core_device: TopologicalDevice,
    /// Anyon factory for creating anyons
    pub anyon_factory: AnyonFactory,
    /// Braiding operation manager
    pub braiding_manager: BraidingOperationManager,
    /// Fusion operation executor
    pub fusion_executor: FusionOperationExecutor,
    /// Device configuration
    pub config: TopologicalDeviceConfig,
    /// Connection status
    pub is_connected: bool,
}

/// Configuration for topological quantum devices
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TopologicalDeviceConfig {
    /// Maximum execution time for operations
    pub max_execution_time: Duration,
    /// Temperature of the system (mK)
    pub operating_temperature: f64,
    /// Topological gap energy scale (K)
    pub topological_gap: f64,
    /// Coherence length (μm)
    pub coherence_length: f64,
    /// Anyon manipulation precision
    pub manipulation_precision: f64,
    /// Braiding fidelity
    pub braiding_fidelity: f64,
    /// Fusion fidelity
    pub fusion_fidelity: f64,
    /// Measurement fidelity
    pub measurement_fidelity: f64,
    /// Enable advanced error correction
    pub enable_error_correction: bool,
    /// Hardware-specific parameters
    pub hardware_params: HashMap<String, String>,
}

impl Default for TopologicalDeviceConfig {
    fn default() -> Self {
        Self {
            max_execution_time: Duration::from_secs(300),
            operating_temperature: 0.01, // 10 mK
            topological_gap: 1.0,        // 1 K
            coherence_length: 100.0,     // 100 μm
            manipulation_precision: 0.99,
            braiding_fidelity: 0.9999,
            fusion_fidelity: 0.999,
            measurement_fidelity: 0.999,
            enable_error_correction: true,
            hardware_params: HashMap::new(),
        }
    }
}

impl EnhancedTopologicalDevice {
    /// Create a new enhanced topological device
    pub fn new(
        system_type: TopologicalSystemType,
        fusion_rules: FusionRuleSet,
        capabilities: TopologicalCapabilities,
        config: TopologicalDeviceConfig,
    ) -> TopologicalResult<Self> {
        let core_device =
            TopologicalDevice::new(system_type.clone(), fusion_rules.clone(), capabilities);

        let anyon_type = match system_type {
            TopologicalSystemType::NonAbelian { anyon_type, .. } => anyon_type,
            _ => NonAbelianAnyonType::Fibonacci, // Default
        };

        let anyon_factory = AnyonFactory::new(anyon_type.clone(), fusion_rules.clone());
        let braiding_manager = BraidingOperationManager::new(anyon_type.clone());
        let fusion_executor = FusionOperationExecutor::new(anyon_type, fusion_rules);

        Ok(Self {
            core_device,
            anyon_factory,
            braiding_manager,
            fusion_executor,
            config,
            is_connected: false,
        })
    }

    /// Connect to the topological quantum hardware
    pub async fn connect(&mut self) -> TopologicalResult<()> {
        // Simulate hardware connection
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Verify system integrity
        self.verify_system_integrity().await?;

        self.is_connected = true;
        Ok(())
    }

    /// Disconnect from the hardware
    pub async fn disconnect(&mut self) -> TopologicalResult<()> {
        self.is_connected = false;
        Ok(())
    }

    /// Verify system integrity
    async fn verify_system_integrity(&self) -> TopologicalResult<()> {
        // Check topological gap
        if self.config.topological_gap < 0.1 {
            return Err(TopologicalError::InvalidWorldline(
                "Topological gap too small for reliable operation".to_string(),
            ));
        }

        // Check coherence length
        if self.config.coherence_length < 10.0 {
            return Err(TopologicalError::InvalidWorldline(
                "Coherence length too small".to_string(),
            ));
        }

        Ok(())
    }

    /// Initialize topological qubits
    pub async fn initialize_topological_qubits(
        &mut self,
        num_qubits: usize,
    ) -> TopologicalResult<Vec<usize>> {
        let mut qubit_ids = Vec::new();

        for _ in 0..num_qubits {
            // Create anyon pairs for each qubit
            let charge = match self.core_device.system_type {
                TopologicalSystemType::NonAbelian {
                    anyon_type: NonAbelianAnyonType::Fibonacci,
                    ..
                } => TopologicalCharge::fibonacci_tau(),
                TopologicalSystemType::NonAbelian {
                    anyon_type: NonAbelianAnyonType::Ising,
                    ..
                } => TopologicalCharge::ising_sigma(),
                _ => TopologicalCharge::identity(),
            };

            // Create anyon pairs at different positions
            let positions = [
                (qubit_ids.len() as f64 * 10.0, 0.0),
                ((qubit_ids.len() as f64).mul_add(10.0, 5.0), 0.0),
                (qubit_ids.len() as f64 * 10.0, 5.0),
                ((qubit_ids.len() as f64).mul_add(10.0, 5.0), 5.0),
            ];

            let (anyon1_id, anyon2_id) = self
                .core_device
                .create_anyon_pair(charge.clone(), [positions[0], positions[1]])?;

            let (anyon3_id, anyon4_id) = self
                .core_device
                .create_anyon_pair(charge, [positions[2], positions[3]])?;

            // Create topological qubit from four anyons
            let qubit_id = self
                .core_device
                .create_topological_qubit(vec![anyon1_id, anyon2_id, anyon3_id, anyon4_id])?;

            qubit_ids.push(qubit_id);
        }

        Ok(qubit_ids)
    }

    /// Perform a topological X gate via braiding
    pub async fn topological_x_gate(&mut self, qubit_id: usize) -> TopologicalResult<()> {
        let qubit = self.core_device.qubits.get(&qubit_id).ok_or_else(|| {
            TopologicalError::InvalidBraiding(format!("Qubit {qubit_id} not found"))
        })?;

        if qubit.anyons.len() < 4 {
            return Err(TopologicalError::InsufficientAnyons {
                needed: 4,
                available: qubit.anyons.len(),
            });
        }

        // Perform braiding sequence for X gate
        let anyon1_id = qubit.anyons[0];
        let anyon2_id = qubit.anyons[1];

        // Single braid for X rotation
        self.core_device
            .braid_anyons(anyon1_id, anyon2_id, BraidingDirection::Clockwise, 1)?;

        Ok(())
    }

    /// Perform a topological Z gate via braiding
    pub async fn topological_z_gate(&mut self, qubit_id: usize) -> TopologicalResult<()> {
        let qubit = self.core_device.qubits.get(&qubit_id).ok_or_else(|| {
            TopologicalError::InvalidBraiding(format!("Qubit {qubit_id} not found"))
        })?;

        if qubit.anyons.len() < 4 {
            return Err(TopologicalError::InsufficientAnyons {
                needed: 4,
                available: qubit.anyons.len(),
            });
        }

        // Perform braiding sequence for Z gate
        let anyon1_id = qubit.anyons[0];
        let anyon3_id = qubit.anyons[2];

        // Different braiding pattern for Z rotation
        self.core_device.braid_anyons(
            anyon1_id,
            anyon3_id,
            BraidingDirection::Counterclockwise,
            1,
        )?;

        Ok(())
    }

    /// Perform a topological CNOT gate
    pub async fn topological_cnot_gate(
        &mut self,
        control_qubit: usize,
        target_qubit: usize,
    ) -> TopologicalResult<()> {
        // Get anyons from both qubits
        let control_anyons = {
            let qubit = self.core_device.qubits.get(&control_qubit).ok_or_else(|| {
                TopologicalError::InvalidBraiding(format!(
                    "Control qubit {control_qubit} not found"
                ))
            })?;
            qubit.anyons.clone()
        };

        let target_anyons = {
            let qubit = self.core_device.qubits.get(&target_qubit).ok_or_else(|| {
                TopologicalError::InvalidBraiding(format!("Target qubit {target_qubit} not found"))
            })?;
            qubit.anyons.clone()
        };

        // Perform complex braiding sequence for CNOT
        // This is simplified - actual implementation would be more complex
        if !control_anyons.is_empty() && !target_anyons.is_empty() {
            self.core_device.braid_anyons(
                control_anyons[0],
                target_anyons[0],
                BraidingDirection::Clockwise,
                2,
            )?;
        }

        Ok(())
    }

    /// Measure a topological qubit
    pub async fn measure_topological_qubit(&mut self, qubit_id: usize) -> TopologicalResult<bool> {
        let result = self.core_device.measure_qubit(qubit_id)?;

        // Apply measurement fidelity
        let actual_fidelity = thread_rng().random::<f64>();
        if actual_fidelity < self.config.measurement_fidelity {
            Ok(result)
        } else {
            Ok(!result) // Measurement error
        }
    }

    /// Reset a topological qubit to |0⟩ state
    pub async fn reset_topological_qubit(&mut self, qubit_id: usize) -> TopologicalResult<()> {
        if let Some(qubit) = self.core_device.qubits.get_mut(&qubit_id) {
            qubit.state = super::TopologicalQubitState::zero();
            qubit.braiding_history.clear();
            Ok(())
        } else {
            Err(TopologicalError::InvalidBraiding(format!(
                "Qubit {qubit_id} not found for reset"
            )))
        }
    }

    /// Get device status and diagnostics
    pub async fn get_diagnostics(&self) -> TopologicalDeviceDiagnostics {
        let system_status = self.core_device.get_system_status();

        TopologicalDeviceDiagnostics {
            is_connected: self.is_connected,
            system_status,
            operating_temperature: self.config.operating_temperature,
            topological_gap: self.config.topological_gap,
            average_braiding_fidelity: self.config.braiding_fidelity,
            total_operations: self.braiding_manager.get_operation_history().len(),
            error_rate: 1.0 - self.config.braiding_fidelity,
        }
    }
}

/// Diagnostics information for topological devices
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TopologicalDeviceDiagnostics {
    pub is_connected: bool,
    pub system_status: super::TopologicalSystemStatus,
    pub operating_temperature: f64,
    pub topological_gap: f64,
    pub average_braiding_fidelity: f64,
    pub total_operations: usize,
    pub error_rate: f64,
}

#[cfg(feature = "ibm")]
#[async_trait::async_trait]
impl QuantumDevice for EnhancedTopologicalDevice {
    async fn is_available(&self) -> DeviceResult<bool> {
        Ok(self.is_connected && self.config.topological_gap > 0.1)
    }

    async fn qubit_count(&self) -> DeviceResult<usize> {
        Ok(self.core_device.capabilities.max_qubits)
    }

    async fn properties(&self) -> DeviceResult<HashMap<String, String>> {
        let mut props = HashMap::new();
        props.insert("device_type".to_string(), "topological".to_string());
        props.insert(
            "anyon_type".to_string(),
            format!("{:?}", self.core_device.system_type),
        );
        props.insert(
            "max_anyons".to_string(),
            self.core_device.capabilities.max_anyons.to_string(),
        );
        props.insert(
            "max_qubits".to_string(),
            self.core_device.capabilities.max_qubits.to_string(),
        );
        props.insert(
            "braiding_fidelity".to_string(),
            self.config.braiding_fidelity.to_string(),
        );
        props.insert(
            "topological_gap".to_string(),
            self.config.topological_gap.to_string(),
        );
        props.insert(
            "coherence_length".to_string(),
            self.config.coherence_length.to_string(),
        );
        Ok(props)
    }

    async fn is_simulator(&self) -> DeviceResult<bool> {
        Ok(true) // This implementation is a simulator
    }
}

#[cfg(not(feature = "ibm"))]
impl QuantumDevice for EnhancedTopologicalDevice {
    fn is_available(&self) -> DeviceResult<bool> {
        Ok(self.is_connected && self.config.topological_gap > 0.1)
    }

    fn qubit_count(&self) -> DeviceResult<usize> {
        Ok(self.core_device.capabilities.max_qubits)
    }

    fn properties(&self) -> DeviceResult<HashMap<String, String>> {
        let mut props = HashMap::new();
        props.insert("device_type".to_string(), "topological".to_string());
        props.insert(
            "anyon_type".to_string(),
            format!("{:?}", self.core_device.system_type),
        );
        props.insert(
            "max_anyons".to_string(),
            self.core_device.capabilities.max_anyons.to_string(),
        );
        props.insert(
            "max_qubits".to_string(),
            self.core_device.capabilities.max_qubits.to_string(),
        );
        props.insert(
            "braiding_fidelity".to_string(),
            self.config.braiding_fidelity.to_string(),
        );
        props.insert(
            "topological_gap".to_string(),
            self.config.topological_gap.to_string(),
        );
        props.insert(
            "coherence_length".to_string(),
            self.config.coherence_length.to_string(),
        );
        Ok(props)
    }

    fn is_simulator(&self) -> DeviceResult<bool> {
        Ok(true) // This implementation is a simulator
    }
}

#[cfg(feature = "ibm")]
#[async_trait::async_trait]
impl CircuitExecutor for EnhancedTopologicalDevice {
    async fn execute_circuit<const N: usize>(
        &self,
        circuit: &Circuit<N>,
        shots: usize,
    ) -> DeviceResult<CircuitResult> {
        if !self.is_connected {
            return Err(DeviceError::DeviceNotInitialized(
                "Topological device not connected".to_string(),
            ));
        }

        // Simplified circuit execution
        // In practice, this would translate circuit gates to braiding operations
        let mut counts = HashMap::new();

        // Simulate perfect braiding for now
        let all_zeros = "0".repeat(N);
        counts.insert(all_zeros, shots);

        let mut metadata = HashMap::new();
        metadata.insert("device_type".to_string(), "topological".to_string());
        metadata.insert(
            "braiding_fidelity".to_string(),
            self.config.braiding_fidelity.to_string(),
        );
        metadata.insert("execution_time_ms".to_string(), "100".to_string());

        Ok(CircuitResult {
            counts,
            shots,
            metadata,
        })
    }

    async fn execute_circuits<const N: usize>(
        &self,
        circuits: Vec<&Circuit<N>>,
        shots: usize,
    ) -> DeviceResult<Vec<CircuitResult>> {
        let mut results = Vec::new();

        for circuit in circuits {
            let result = self.execute_circuit(circuit, shots).await?;
            results.push(result);
        }

        Ok(results)
    }

    async fn can_execute_circuit<const N: usize>(
        &self,
        _circuit: &Circuit<N>,
    ) -> DeviceResult<bool> {
        Ok(N <= self.core_device.capabilities.max_qubits)
    }

    async fn estimated_queue_time<const N: usize>(
        &self,
        _circuit: &Circuit<N>,
    ) -> DeviceResult<Duration> {
        // Topological quantum computers have very long coherence times
        Ok(Duration::from_secs(10))
    }
}

#[cfg(not(feature = "ibm"))]
impl CircuitExecutor for EnhancedTopologicalDevice {
    fn execute_circuit<const N: usize>(
        &self,
        _circuit: &Circuit<N>,
        shots: usize,
    ) -> DeviceResult<CircuitResult> {
        if !self.is_connected {
            return Err(DeviceError::DeviceNotInitialized(
                "Topological device not connected".to_string(),
            ));
        }

        // Simplified circuit execution
        // In practice, this would translate circuit gates to braiding operations
        let mut counts = HashMap::new();

        // Simulate perfect braiding for now
        let all_zeros = "0".repeat(N);
        counts.insert(all_zeros, shots);

        let mut metadata = HashMap::new();
        metadata.insert("device_type".to_string(), "topological".to_string());
        metadata.insert(
            "braiding_fidelity".to_string(),
            self.config.braiding_fidelity.to_string(),
        );
        metadata.insert("execution_time_ms".to_string(), "100".to_string());

        Ok(CircuitResult {
            counts,
            shots,
            metadata,
        })
    }

    fn execute_circuits<const N: usize>(
        &self,
        circuits: Vec<&Circuit<N>>,
        shots: usize,
    ) -> DeviceResult<Vec<CircuitResult>> {
        let mut results = Vec::new();

        for circuit in circuits {
            let result = self.execute_circuit(circuit, shots)?;
            results.push(result);
        }

        Ok(results)
    }

    fn can_execute_circuit<const N: usize>(&self, _circuit: &Circuit<N>) -> DeviceResult<bool> {
        Ok(N <= self.core_device.capabilities.max_qubits)
    }

    fn estimated_queue_time<const N: usize>(
        &self,
        _circuit: &Circuit<N>,
    ) -> DeviceResult<Duration> {
        // Topological quantum computers have very long coherence times
        Ok(Duration::from_secs(10))
    }
}

/// Create a Fibonacci anyon topological device
pub fn create_fibonacci_device(
    max_anyons: usize,
    max_qubits: usize,
) -> TopologicalResult<EnhancedTopologicalDevice> {
    let system_type = TopologicalSystemType::NonAbelian {
        anyon_type: NonAbelianAnyonType::Fibonacci,
        fusion_rules: FusionRuleSet::fibonacci(),
    };

    let capabilities = TopologicalCapabilities {
        max_anyons,
        max_qubits,
        supported_anyons: vec![
            TopologicalCharge::identity(),
            TopologicalCharge::fibonacci_tau(),
        ],
        available_operations: vec![
            super::TopologicalOperation::AnyonCreation {
                charge_type: "τ".to_string(),
            },
            super::TopologicalOperation::Braiding {
                direction: BraidingDirection::Clockwise,
            },
            super::TopologicalOperation::Fusion,
            super::TopologicalOperation::Measurement,
        ],
        braiding_fidelity: 0.9999,
        fusion_fidelity: 0.999,
        topological_gap: 1.0,
        coherence_length: 100.0,
    };

    let config = TopologicalDeviceConfig::default();
    let fusion_rules = FusionRuleSet::fibonacci();

    EnhancedTopologicalDevice::new(system_type, fusion_rules, capabilities, config)
}

/// Create an Ising anyon topological device
pub fn create_ising_device(
    max_anyons: usize,
    max_qubits: usize,
) -> TopologicalResult<EnhancedTopologicalDevice> {
    let system_type = TopologicalSystemType::NonAbelian {
        anyon_type: NonAbelianAnyonType::Ising,
        fusion_rules: FusionRuleSet::ising(),
    };

    let capabilities = TopologicalCapabilities {
        max_anyons,
        max_qubits,
        supported_anyons: vec![
            TopologicalCharge::identity(),
            TopologicalCharge::ising_sigma(),
            TopologicalCharge::ising_psi(),
        ],
        available_operations: vec![
            super::TopologicalOperation::AnyonCreation {
                charge_type: "σ".to_string(),
            },
            super::TopologicalOperation::Braiding {
                direction: BraidingDirection::Clockwise,
            },
            super::TopologicalOperation::Fusion,
            super::TopologicalOperation::Measurement,
        ],
        braiding_fidelity: 0.999,
        fusion_fidelity: 0.998,
        topological_gap: 0.5,
        coherence_length: 50.0,
    };

    let config = TopologicalDeviceConfig::default();
    let fusion_rules = FusionRuleSet::ising();

    EnhancedTopologicalDevice::new(system_type, fusion_rules, capabilities, config)
}

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

    #[tokio::test]
    async fn test_fibonacci_device_creation() {
        let device = create_fibonacci_device(100, 10).expect("Failed to create Fibonacci device");
        assert_eq!(device.core_device.capabilities.max_anyons, 100);
        assert_eq!(device.core_device.capabilities.max_qubits, 10);
    }

    #[tokio::test]
    async fn test_device_connection() {
        let mut device = create_fibonacci_device(50, 5).expect("Failed to create Fibonacci device");
        assert!(!device.is_connected);

        device.connect().await.expect("Failed to connect to device");
        assert!(device.is_connected);

        device
            .disconnect()
            .await
            .expect("Failed to disconnect from device");
        assert!(!device.is_connected);
    }

    #[tokio::test]
    async fn test_qubit_initialization() {
        let mut device =
            create_fibonacci_device(100, 10).expect("Failed to create Fibonacci device");
        device.connect().await.expect("Failed to connect to device");

        let qubit_ids = device
            .initialize_topological_qubits(3)
            .await
            .expect("Failed to initialize topological qubits");
        assert_eq!(qubit_ids.len(), 3);
    }

    #[tokio::test]
    async fn test_topological_gates() {
        let mut device =
            create_fibonacci_device(100, 10).expect("Failed to create Fibonacci device");
        device.connect().await.expect("Failed to connect to device");

        let qubit_ids = device
            .initialize_topological_qubits(2)
            .await
            .expect("Failed to initialize topological qubits");

        // Test X gate
        device
            .topological_x_gate(qubit_ids[0])
            .await
            .expect("Failed to apply X gate");

        // Test Z gate
        device
            .topological_z_gate(qubit_ids[0])
            .await
            .expect("Failed to apply Z gate");

        // Test CNOT gate
        device
            .topological_cnot_gate(qubit_ids[0], qubit_ids[1])
            .await
            .expect("Failed to apply CNOT gate");
    }

    #[tokio::test]
    async fn test_measurement() {
        let mut device = create_fibonacci_device(50, 5).expect("Failed to create Fibonacci device");
        device.connect().await.expect("Failed to connect to device");

        let qubit_ids = device
            .initialize_topological_qubits(1)
            .await
            .expect("Failed to initialize topological qubits");
        let result = device
            .measure_topological_qubit(qubit_ids[0])
            .await
            .expect("Failed to measure topological qubit");

        // Result should be boolean
        // result is bool, always true or false
    }

    #[tokio::test]
    async fn test_device_diagnostics() {
        let device = create_fibonacci_device(50, 5).expect("Failed to create Fibonacci device");
        let diagnostics = device.get_diagnostics().await;

        assert!(!diagnostics.is_connected);
        assert!(diagnostics.topological_gap > 0.0);
        assert!(diagnostics.average_braiding_fidelity > 0.0);
    }

    #[cfg(feature = "ibm")]
    #[tokio::test]
    async fn test_quantum_device_traits_async() {
        let device = create_ising_device(30, 3).expect("Failed to create Ising device");

        assert!(device
            .is_simulator()
            .await
            .expect("Failed to check if device is simulator"));
        assert_eq!(
            device
                .qubit_count()
                .await
                .expect("Failed to get qubit count"),
            3
        );

        let properties = device
            .properties()
            .await
            .expect("Failed to get device properties");
        assert_eq!(
            properties
                .get("device_type")
                .expect("device_type property not found"),
            "topological"
        );
    }

    #[cfg(not(feature = "ibm"))]
    #[test]
    fn test_quantum_device_traits() {
        let device = create_ising_device(30, 3).expect("Failed to create Ising device");

        assert!(device
            .is_simulator()
            .expect("Failed to check if device is simulator"));
        assert_eq!(device.qubit_count().expect("Failed to get qubit count"), 3);

        let properties = device
            .properties()
            .expect("Failed to get device properties");
        assert_eq!(
            properties
                .get("device_type")
                .expect("device_type property not found"),
            "topological"
        );
    }
}