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
//! Pulse-level control interfaces for quantum hardware providers.
//!
//! This module provides low-level pulse control for quantum operations,
//! enabling fine-grained control over quantum gates and measurements.

use crate::{DeviceError, DeviceResult};
use scirs2_core::Complex64;
use std::collections::HashMap;
use std::f64::consts::PI;

/// Pulse shape types
#[derive(Debug, Clone, PartialEq)]
pub enum PulseShape {
    /// Gaussian pulse
    Gaussian {
        duration: f64,
        sigma: f64,
        amplitude: Complex64,
    },
    /// Gaussian with derivative removal (DRAG)
    GaussianDrag {
        duration: f64,
        sigma: f64,
        amplitude: Complex64,
        beta: f64,
    },
    /// Square/constant pulse
    Square { duration: f64, amplitude: Complex64 },
    /// Cosine-tapered pulse
    CosineTapered {
        duration: f64,
        amplitude: Complex64,
        rise_time: f64,
    },
    /// Arbitrary waveform
    Arbitrary {
        samples: Vec<Complex64>,
        sample_rate: f64,
    },
}

/// Channel types for pulse control
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ChannelType {
    /// Drive channel for qubit control
    Drive(u32),
    /// Measurement channel
    Measure(u32),
    /// Control channel for two-qubit gates
    Control(u32, u32),
    /// Readout channel
    Readout(u32),
    /// Acquire channel for measurement
    Acquire(u32),
}

/// Pulse instruction
#[derive(Debug, Clone)]
pub struct PulseInstruction {
    /// Time when pulse starts (in dt units)
    pub t0: u64,
    /// Channel to play pulse on
    pub channel: ChannelType,
    /// Pulse shape and parameters
    pub pulse: PulseShape,
    /// Optional phase shift
    pub phase: Option<f64>,
    /// Optional frequency shift
    pub frequency: Option<f64>,
}

/// Pulse schedule (collection of instructions)
#[derive(Debug, Clone)]
pub struct PulseSchedule {
    /// Name of the schedule
    pub name: String,
    /// Duration in dt units
    pub duration: u64,
    /// List of pulse instructions
    pub instructions: Vec<PulseInstruction>,
    /// Metadata
    pub metadata: HashMap<String, String>,
}

/// Calibration data for pulse operations
#[derive(Debug, Clone)]
pub struct PulseCalibration {
    /// Default pulse parameters for single-qubit gates
    pub single_qubit_defaults: HashMap<String, PulseShape>,
    /// Default pulse parameters for two-qubit gates
    pub two_qubit_defaults: HashMap<String, PulseShape>,
    /// Qubit frequencies (GHz)
    pub qubit_frequencies: Vec<f64>,
    /// Measurement frequencies (GHz)
    pub meas_frequencies: Vec<f64>,
    /// Drive power calibration
    pub drive_powers: Vec<f64>,
    /// Sample time (dt) in seconds
    pub dt: f64,
}

/// Pulse builder for creating schedules
pub struct PulseBuilder {
    schedule: PulseSchedule,
    current_time: u64,
    calibration: Option<PulseCalibration>,
}

impl PulseBuilder {
    /// Create a new pulse builder
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            schedule: PulseSchedule {
                name: name.into(),
                duration: 0,
                instructions: Vec::new(),
                metadata: HashMap::new(),
            },
            current_time: 0,
            calibration: None,
        }
    }

    /// Create with calibration data
    pub fn with_calibration(name: impl Into<String>, calibration: PulseCalibration) -> Self {
        let mut builder = Self::new(name);
        builder.calibration = Some(calibration);
        builder
    }

    /// Add a pulse instruction
    #[must_use]
    pub fn play(mut self, channel: ChannelType, pulse: PulseShape) -> Self {
        let duration = match &pulse {
            PulseShape::Gaussian { duration, .. }
            | PulseShape::GaussianDrag { duration, .. }
            | PulseShape::Square { duration, .. }
            | PulseShape::CosineTapered { duration, .. } => *duration,
            PulseShape::Arbitrary {
                samples,
                sample_rate,
            } => samples.len() as f64 / sample_rate,
        };

        let duration_dt = self
            .calibration
            .as_ref()
            .map_or(duration as u64, |cal| (duration / cal.dt) as u64);

        self.schedule.instructions.push(PulseInstruction {
            t0: self.current_time,
            channel,
            pulse,
            phase: None,
            frequency: None,
        });

        self.current_time += duration_dt;
        self.schedule.duration = self.schedule.duration.max(self.current_time);
        self
    }

    /// Add a delay
    #[must_use]
    pub fn delay(mut self, duration: u64, channel: ChannelType) -> Self {
        // Delays are implicit - just advance time
        self.current_time += duration;
        self.schedule.duration = self.schedule.duration.max(self.current_time);
        self
    }

    /// Set phase on a channel
    #[must_use]
    pub fn set_phase(mut self, channel: ChannelType, phase: f64) -> Self {
        self.schedule.instructions.push(PulseInstruction {
            t0: self.current_time,
            channel,
            pulse: PulseShape::Square {
                duration: 0.0,
                amplitude: Complex64::new(0.0, 0.0),
            },
            phase: Some(phase),
            frequency: None,
        });
        self
    }

    /// Set frequency on a channel
    #[must_use]
    pub fn set_frequency(mut self, channel: ChannelType, frequency: f64) -> Self {
        self.schedule.instructions.push(PulseInstruction {
            t0: self.current_time,
            channel,
            pulse: PulseShape::Square {
                duration: 0.0,
                amplitude: Complex64::new(0.0, 0.0),
            },
            phase: None,
            frequency: Some(frequency),
        });
        self
    }

    /// Barrier - synchronize channels
    #[must_use]
    pub fn barrier(mut self, channels: Vec<ChannelType>) -> Self {
        // Find latest time across channels
        let max_time = self
            .schedule
            .instructions
            .iter()
            .filter(|inst| channels.contains(&inst.channel))
            .map(|inst| {
                let duration = match &inst.pulse {
                    PulseShape::Gaussian { duration, .. }
                    | PulseShape::GaussianDrag { duration, .. }
                    | PulseShape::Square { duration, .. }
                    | PulseShape::CosineTapered { duration, .. } => *duration,
                    PulseShape::Arbitrary {
                        samples,
                        sample_rate,
                    } => samples.len() as f64 / sample_rate,
                };
                let duration_dt = self
                    .calibration
                    .as_ref()
                    .map_or(duration as u64, |cal| (duration / cal.dt) as u64);
                inst.t0 + duration_dt
            })
            .max()
            .unwrap_or(self.current_time);

        self.current_time = max_time;
        self
    }

    /// Add metadata
    #[must_use]
    pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.schedule.metadata.insert(key.into(), value.into());
        self
    }

    /// Build the pulse schedule
    pub fn build(self) -> PulseSchedule {
        self.schedule
    }
}

/// Provider-specific pulse backend
pub trait PulseBackend {
    /// Execute a pulse schedule
    fn execute_pulse_schedule(
        &self,
        schedule: &PulseSchedule,
        shots: usize,
        meas_level: MeasLevel,
    ) -> DeviceResult<PulseResult>;

    /// Get pulse calibration data
    fn get_calibration(&self) -> DeviceResult<PulseCalibration>;

    /// Validate a pulse schedule
    fn validate_schedule(&self, schedule: &PulseSchedule) -> DeviceResult<()>;
}

/// Measurement level for pulse experiments
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MeasLevel {
    /// Raw ADC values
    Raw,
    /// IQ values after demodulation
    Kerneled,
    /// Discriminated qubit states
    Classified,
}

/// Result from pulse execution
#[derive(Debug, Clone)]
pub struct PulseResult {
    /// Measurement data
    pub measurements: Vec<MeasurementData>,
    /// Execution metadata
    pub metadata: HashMap<String, String>,
}

/// Measurement data from pulse execution
#[derive(Debug, Clone)]
pub enum MeasurementData {
    /// Raw ADC samples
    Raw(Vec<Vec<Complex64>>),
    /// IQ values
    IQ(Vec<Vec<Complex64>>),
    /// Classified states
    States(Vec<Vec<u8>>),
}

/// IBM Pulse backend implementation
#[cfg(feature = "ibm")]
pub struct IBMPulseBackend {
    backend_name: String,
    calibration: PulseCalibration,
}

#[cfg(feature = "ibm")]
impl IBMPulseBackend {
    pub fn new(backend_name: String) -> Self {
        // Default calibration - would be fetched from backend
        let calibration = PulseCalibration {
            single_qubit_defaults: HashMap::new(),
            two_qubit_defaults: HashMap::new(),
            qubit_frequencies: vec![5.0; 5], // GHz
            meas_frequencies: vec![6.5; 5],  // GHz
            drive_powers: vec![0.1; 5],
            dt: 2.2222e-10, // ~0.22 ns
        };

        Self {
            backend_name,
            calibration,
        }
    }
}

#[cfg(feature = "ibm")]
impl PulseBackend for IBMPulseBackend {
    fn execute_pulse_schedule(
        &self,
        schedule: &PulseSchedule,
        shots: usize,
        meas_level: MeasLevel,
    ) -> DeviceResult<PulseResult> {
        // Validate first
        self.validate_schedule(schedule)?;

        // Convert to Qiskit pulse format and execute
        // This is a placeholder - actual implementation would use Qiskit
        Ok(PulseResult {
            measurements: vec![],
            metadata: HashMap::new(),
        })
    }

    fn get_calibration(&self) -> DeviceResult<PulseCalibration> {
        Ok(self.calibration.clone())
    }

    fn validate_schedule(&self, schedule: &PulseSchedule) -> DeviceResult<()> {
        // Check duration limits
        if schedule.duration > 1_000_000 {
            return Err(DeviceError::APIError("Schedule too long".to_string()));
        }

        // Check channel availability
        for inst in &schedule.instructions {
            match &inst.channel {
                ChannelType::Drive(q) | ChannelType::Measure(q) => {
                    if *q >= self.calibration.qubit_frequencies.len() as u32 {
                        return Err(DeviceError::APIError(format!("Invalid qubit: {q}")));
                    }
                }
                ChannelType::Control(q1, q2) => {
                    if *q1 >= self.calibration.qubit_frequencies.len() as u32
                        || *q2 >= self.calibration.qubit_frequencies.len() as u32
                    {
                        return Err(DeviceError::APIError("Invalid control channel".to_string()));
                    }
                }
                _ => {}
            }
        }

        Ok(())
    }
}

/// Standard pulse library
pub struct PulseLibrary;

impl PulseLibrary {
    /// Create a Gaussian pulse
    pub const fn gaussian(duration: f64, sigma: f64, amplitude: f64) -> PulseShape {
        PulseShape::Gaussian {
            duration,
            sigma,
            amplitude: Complex64::new(amplitude, 0.0),
        }
    }

    /// Create a DRAG pulse
    pub const fn drag(duration: f64, sigma: f64, amplitude: f64, beta: f64) -> PulseShape {
        PulseShape::GaussianDrag {
            duration,
            sigma,
            amplitude: Complex64::new(amplitude, 0.0),
            beta,
        }
    }

    /// Create a square pulse
    pub const fn square(duration: f64, amplitude: f64) -> PulseShape {
        PulseShape::Square {
            duration,
            amplitude: Complex64::new(amplitude, 0.0),
        }
    }

    /// Create a cosine-tapered pulse
    pub const fn cosine_tapered(duration: f64, amplitude: f64, rise_time: f64) -> PulseShape {
        PulseShape::CosineTapered {
            duration,
            amplitude: Complex64::new(amplitude, 0.0),
            rise_time,
        }
    }

    /// Create X gate pulse
    pub const fn x_pulse(calibration: &PulseCalibration, qubit: u32) -> PulseShape {
        // Default X pulse - π rotation
        Self::gaussian(160e-9, 40e-9, 0.5)
    }

    /// Create Y gate pulse
    pub const fn y_pulse(calibration: &PulseCalibration, qubit: u32) -> PulseShape {
        // Y pulse with phase
        PulseShape::Gaussian {
            duration: 160e-9,
            sigma: 40e-9,
            amplitude: Complex64::new(0.0, 0.5), // 90 degree phase
        }
    }

    /// Create SX (√X) gate pulse
    pub const fn sx_pulse(calibration: &PulseCalibration, qubit: u32) -> PulseShape {
        // π/2 rotation
        Self::gaussian(160e-9, 40e-9, 0.25)
    }

    /// Create RZ gate using phase shift
    pub const fn rz_pulse(angle: f64) -> PulseInstruction {
        PulseInstruction {
            t0: 0,
            channel: ChannelType::Drive(0), // Will be updated
            pulse: PulseShape::Square {
                duration: 0.0,
                amplitude: Complex64::new(0.0, 0.0),
            },
            phase: Some(angle),
            frequency: None,
        }
    }

    /// Create measurement pulse
    pub const fn measure_pulse(calibration: &PulseCalibration, qubit: u32) -> PulseShape {
        // Square measurement pulse
        Self::square(2e-6, 0.1)
    }
}

/// Pulse schedule templates for common operations
pub struct PulseTemplates;

impl PulseTemplates {
    /// Create a calibrated X gate schedule
    pub fn x_gate(qubit: u32, calibration: &PulseCalibration) -> PulseSchedule {
        PulseBuilder::with_calibration("x_gate", calibration.clone())
            .play(
                ChannelType::Drive(qubit),
                PulseLibrary::x_pulse(calibration, qubit),
            )
            .build()
    }

    /// Create a calibrated CNOT gate schedule
    pub fn cnot_gate(control: u32, target: u32, calibration: &PulseCalibration) -> PulseSchedule {
        // Simplified CNOT using cross-resonance
        let cr_amp = 0.3;
        let cr_duration = 560e-9;

        PulseBuilder::with_calibration("cnot_gate", calibration.clone())
            // Pre-rotation on control
            .play(
                ChannelType::Drive(control),
                PulseLibrary::sx_pulse(calibration, control),
            )
            // Cross-resonance pulse
            .play(
                ChannelType::Control(control, target),
                PulseLibrary::gaussian(cr_duration, cr_duration / 4.0, cr_amp),
            )
            // Simultaneous rotations
            .play(
                ChannelType::Drive(control),
                PulseLibrary::x_pulse(calibration, control),
            )
            .play(
                ChannelType::Drive(target),
                PulseLibrary::x_pulse(calibration, target),
            )
            .barrier(vec![ChannelType::Drive(control), ChannelType::Drive(target)])
            .build()
    }

    /// Create a measurement schedule
    pub fn measure(qubits: Vec<u32>, calibration: &PulseCalibration) -> PulseSchedule {
        let mut builder = PulseBuilder::with_calibration("measure", calibration.clone());

        // Play measurement pulses simultaneously
        for &qubit in &qubits {
            builder = builder.play(
                ChannelType::Measure(qubit),
                PulseLibrary::measure_pulse(calibration, qubit),
            );
        }

        // Acquire data
        for &qubit in &qubits {
            builder = builder.play(
                ChannelType::Acquire(qubit),
                PulseShape::Square {
                    duration: 2e-6,
                    amplitude: Complex64::new(1.0, 0.0),
                },
            );
        }

        builder.build()
    }

    /// Create a Rabi oscillation experiment
    pub fn rabi_experiment(
        qubit: u32,
        amplitudes: Vec<f64>,
        calibration: &PulseCalibration,
    ) -> Vec<PulseSchedule> {
        amplitudes
            .into_iter()
            .map(|amp| {
                PulseBuilder::with_calibration(format!("rabi_{amp}"), calibration.clone())
                    .play(
                        ChannelType::Drive(qubit),
                        PulseLibrary::gaussian(160e-9, 40e-9, amp),
                    )
                    .play(
                        ChannelType::Measure(qubit),
                        PulseLibrary::measure_pulse(calibration, qubit),
                    )
                    .build()
            })
            .collect()
    }

    /// Create a T1 relaxation experiment
    pub fn t1_experiment(
        qubit: u32,
        delays: Vec<u64>,
        calibration: &PulseCalibration,
    ) -> Vec<PulseSchedule> {
        delays
            .into_iter()
            .map(|delay| {
                PulseBuilder::with_calibration(format!("t1_{delay}"), calibration.clone())
                    .play(
                        ChannelType::Drive(qubit),
                        PulseLibrary::x_pulse(calibration, qubit),
                    )
                    .delay(delay, ChannelType::Drive(qubit))
                    .play(
                        ChannelType::Measure(qubit),
                        PulseLibrary::measure_pulse(calibration, qubit),
                    )
                    .build()
            })
            .collect()
    }

    /// Create a Ramsey experiment (T2)
    pub fn ramsey_experiment(
        qubit: u32,
        delays: Vec<u64>,
        detuning: f64,
        calibration: &PulseCalibration,
    ) -> Vec<PulseSchedule> {
        delays
            .into_iter()
            .map(|delay| {
                PulseBuilder::with_calibration(format!("ramsey_{delay}"), calibration.clone())
                    // First π/2 pulse
                    .play(
                        ChannelType::Drive(qubit),
                        PulseLibrary::sx_pulse(calibration, qubit),
                    )
                    // Evolution with detuning
                    .set_frequency(ChannelType::Drive(qubit), detuning)
                    .delay(delay, ChannelType::Drive(qubit))
                    .set_frequency(ChannelType::Drive(qubit), 0.0)
                    // Second π/2 pulse
                    .play(
                        ChannelType::Drive(qubit),
                        PulseLibrary::sx_pulse(calibration, qubit),
                    )
                    // Measure
                    .play(
                        ChannelType::Measure(qubit),
                        PulseLibrary::measure_pulse(calibration, qubit),
                    )
                    .build()
            })
            .collect()
    }
}

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

    #[test]
    fn test_pulse_builder() {
        let schedule = PulseBuilder::new("test")
            .play(
                ChannelType::Drive(0),
                PulseLibrary::gaussian(100e-9, 25e-9, 0.5),
            )
            .delay(50, ChannelType::Drive(0))
            .play(
                ChannelType::Drive(0),
                PulseLibrary::gaussian(100e-9, 25e-9, 0.5),
            )
            .build();

        assert_eq!(schedule.name, "test");
        assert_eq!(schedule.instructions.len(), 2);
    }

    #[test]
    fn test_pulse_shapes() {
        let gaussian = PulseLibrary::gaussian(100e-9, 25e-9, 0.5);
        match gaussian {
            PulseShape::Gaussian {
                duration,
                sigma,
                amplitude,
            } => {
                assert_eq!(duration, 100e-9);
                assert_eq!(sigma, 25e-9);
                assert_eq!(amplitude.re, 0.5);
            }
            _ => panic!("Wrong pulse type"),
        }

        let drag = PulseLibrary::drag(100e-9, 25e-9, 0.5, 0.1);
        match drag {
            PulseShape::GaussianDrag { beta, .. } => {
                assert_eq!(beta, 0.1);
            }
            _ => panic!("Wrong pulse type"),
        }
    }

    #[test]
    fn test_pulse_calibration() {
        let cal = PulseCalibration {
            single_qubit_defaults: HashMap::new(),
            two_qubit_defaults: HashMap::new(),
            qubit_frequencies: vec![5.0, 5.1, 5.2],
            meas_frequencies: vec![6.5, 6.6, 6.7],
            drive_powers: vec![0.1, 0.1, 0.1],
            dt: 2.2222e-10,
        };

        let schedule = PulseTemplates::x_gate(0, &cal);
        assert!(!schedule.instructions.is_empty());
    }

    #[test]
    fn test_experiments() {
        let cal = PulseCalibration {
            single_qubit_defaults: HashMap::new(),
            two_qubit_defaults: HashMap::new(),
            qubit_frequencies: vec![5.0],
            meas_frequencies: vec![6.5],
            drive_powers: vec![0.1],
            dt: 2.2222e-10,
        };

        // Rabi experiment
        let rabi_schedules =
            PulseTemplates::rabi_experiment(0, vec![0.1, 0.2, 0.3, 0.4, 0.5], &cal);
        assert_eq!(rabi_schedules.len(), 5);

        // T1 experiment
        let t1_schedules = PulseTemplates::t1_experiment(0, vec![0, 100, 200, 500, 1000], &cal);
        assert_eq!(t1_schedules.len(), 5);

        // Ramsey experiment
        let ramsey_schedules = PulseTemplates::ramsey_experiment(
            0,
            vec![0, 50, 100, 200],
            1e6, // 1 MHz detuning
            &cal,
        );
        assert_eq!(ramsey_schedules.len(), 4);
    }
}