quantrs2-device 0.2.1

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
#[cfg(feature = "ibm")]
use async_trait::async_trait;
#[cfg(feature = "ibm")]
use chrono;
use quantrs2_circuit::prelude::Circuit;
use std::collections::HashMap;
#[cfg(feature = "ibm")]
use std::sync::Arc;
#[cfg(feature = "ibm")]
use std::time::Duration;

#[cfg(feature = "ibm")]
use crate::{
    ibm::IBMQuantumClient, CircuitExecutor, CircuitResult, DeviceError, DeviceResult, QuantumDevice,
};

#[cfg(not(feature = "ibm"))]
use crate::{
    ibm::IBMQuantumClient, CircuitExecutor, CircuitResult, DeviceError, DeviceResult, QuantumDevice,
};

/// Implementation of QuantumDevice and CircuitExecutor for IBM Quantum hardware
#[cfg(feature = "ibm")]
pub struct IBMQuantumDevice {
    /// Internal IBM Quantum client
    client: Arc<IBMQuantumClient>,
    /// Selected backend
    backend: crate::ibm::IBMBackend,
    /// Configuration options
    config: IBMDeviceConfig,
}

#[cfg(not(feature = "ibm"))]
pub struct IBMQuantumDevice;

/// Configuration options for IBM Quantum devices
#[derive(Debug, Clone)]
pub struct IBMDeviceConfig {
    /// Default number of shots if not specified
    pub default_shots: usize,
    /// Optimization level (0-3)
    pub optimization_level: usize,
    /// Default timeout for job completion in seconds
    pub timeout_seconds: u64,
    /// Whether to use qubit routing optimization
    pub optimize_routing: bool,
    /// Maximum number of parallel jobs to submit at once
    pub max_parallel_jobs: usize,
}

#[cfg(feature = "ibm")]
impl Default for IBMDeviceConfig {
    fn default() -> Self {
        Self {
            default_shots: 1024,
            optimization_level: 1,
            timeout_seconds: 300,
            optimize_routing: true,
            max_parallel_jobs: 5,
        }
    }
}

#[cfg(not(feature = "ibm"))]
impl Default for IBMDeviceConfig {
    fn default() -> Self {
        Self {
            default_shots: 1024,
            optimization_level: 1,
            timeout_seconds: 300,
            optimize_routing: true,
            max_parallel_jobs: 5,
        }
    }
}

#[cfg(feature = "ibm")]
impl IBMQuantumDevice {
    /// Create a new IBM Quantum device with the specified backend
    pub async fn new(
        client: IBMQuantumClient,
        backend_name: &str,
        config: Option<IBMDeviceConfig>,
    ) -> DeviceResult<Self> {
        let backend = client.get_backend(backend_name).await?;
        let client = Arc::new(client);

        Ok(Self {
            client,
            backend,
            config: config.unwrap_or_default(),
        })
    }

    /// Create a circuit config for submission
    fn create_circuit_config<const N: usize>(
        &self,
        circuit: &Circuit<N>,
        shots: Option<usize>,
    ) -> DeviceResult<crate::ibm::IBMCircuitConfig> {
        let qasm = self.circuit_to_qasm(circuit)?;
        let shots = shots.unwrap_or(self.config.default_shots);

        Ok(crate::ibm::IBMCircuitConfig {
            name: format!("quantrs_circuit_{}", chrono::Utc::now().timestamp()),
            qasm,
            shots,
            optimization_level: Some(self.config.optimization_level),
            initial_layout: None, // Could be optimized in future
        })
    }

    /// Convert a Quantrs circuit to QASM for IBM Quantum.
    ///
    /// Delegates the actual gate-by-gate translation to
    /// [`IBMQuantumClient::circuit_to_qasm`], which in turn uses the circuit
    /// crate's validated OpenQASM 2.0 exporter (`quantrs2_circuit::qasm`).
    /// This guarantees the emitted QASM contains every gate in `circuit`
    /// rather than just the register declarations.
    fn circuit_to_qasm<const N: usize>(&self, circuit: &Circuit<N>) -> DeviceResult<String> {
        if N > self.backend.n_qubits {
            return Err(DeviceError::CircuitConversion(format!(
                "Circuit has {} qubits but backend {} only supports {} qubits",
                N, self.backend.name, self.backend.n_qubits
            )));
        }

        IBMQuantumClient::circuit_to_qasm(circuit, None)
    }
}

#[cfg(not(feature = "ibm"))]
impl IBMQuantumDevice {
    /// Create a new IBM Quantum device with the specified backend
    pub async fn new(
        _client: IBMQuantumClient,
        _backend_name: &str,
        _config: Option<IBMDeviceConfig>,
    ) -> DeviceResult<Self> {
        Err(DeviceError::UnsupportedDevice(
            "IBM Quantum support not enabled. Recompile with the 'ibm' feature.".to_string(),
        ))
    }
}

#[cfg(feature = "_async_device")]
#[async_trait]
impl QuantumDevice for IBMQuantumDevice {
    async fn is_available(&self) -> DeviceResult<bool> {
        // Check the backend status
        let backend = self.client.get_backend(&self.backend.name).await?;
        Ok(backend.status == "active")
    }

    async fn qubit_count(&self) -> DeviceResult<usize> {
        Ok(self.backend.n_qubits)
    }

    async fn properties(&self) -> DeviceResult<HashMap<String, String>> {
        // In a complete implementation, this would fetch detailed properties
        // from the IBM Quantum API
        let mut props = HashMap::new();
        props.insert("name".to_string(), self.backend.name.clone());
        props.insert("description".to_string(), self.backend.description.clone());
        props.insert("version".to_string(), self.backend.version.clone());
        props.insert("n_qubits".to_string(), self.backend.n_qubits.to_string());
        props.insert("simulator".to_string(), self.backend.simulator.to_string());

        Ok(props)
    }

    async fn is_simulator(&self) -> DeviceResult<bool> {
        Ok(self.backend.simulator)
    }
}

#[cfg(not(feature = "_async_device"))]
impl QuantumDevice for IBMQuantumDevice {
    fn is_available(&self) -> DeviceResult<bool> {
        Err(DeviceError::UnsupportedDevice(
            "IBM Quantum support not enabled".to_string(),
        ))
    }

    fn qubit_count(&self) -> DeviceResult<usize> {
        Err(DeviceError::UnsupportedDevice(
            "IBM Quantum support not enabled".to_string(),
        ))
    }

    fn properties(&self) -> DeviceResult<HashMap<String, String>> {
        Err(DeviceError::UnsupportedDevice(
            "IBM Quantum support not enabled".to_string(),
        ))
    }

    fn is_simulator(&self) -> DeviceResult<bool> {
        Err(DeviceError::UnsupportedDevice(
            "IBM Quantum support not enabled".to_string(),
        ))
    }
}

#[cfg(feature = "_async_device")]
#[async_trait]
impl CircuitExecutor for IBMQuantumDevice {
    async fn execute_circuit<const N: usize>(
        &self,
        circuit: &Circuit<N>,
        shots: usize,
    ) -> DeviceResult<CircuitResult> {
        // Create circuit config
        let config = self.create_circuit_config(circuit, Some(shots))?;

        // Submit the circuit
        let job_id = self
            .client
            .submit_circuit(&self.backend.name, config)
            .await?;

        // Wait for the job to complete
        let result = self
            .client
            .wait_for_job(&job_id, Some(self.config.timeout_seconds))
            .await?;

        // Convert to CircuitResult
        let mut metadata = HashMap::new();
        metadata.insert("job_id".to_string(), job_id);
        metadata.insert("backend".to_string(), self.backend.name.clone());
        metadata.insert("shots".to_string(), shots.to_string());

        Ok(CircuitResult {
            counts: result.counts,
            shots: result.shots,
            metadata,
        })
    }

    async fn execute_circuits<const N: usize>(
        &self,
        circuits: Vec<&Circuit<N>>,
        shots: usize,
    ) -> DeviceResult<Vec<CircuitResult>> {
        if circuits.is_empty() {
            return Ok(Vec::new());
        }

        // Limit the number of parallel jobs based on config
        let chunk_size = self.config.max_parallel_jobs.max(1);
        let mut results = Vec::new();

        // Process circuits in chunks to avoid overloading the API
        for chunk in circuits.chunks(chunk_size) {
            let mut configs = Vec::new();

            // Create configs for each circuit in this chunk
            for circuit in chunk {
                let config = self.create_circuit_config(circuit, Some(shots))?;
                configs.push(config);
            }

            // Submit the batch of circuits
            let job_ids = self
                .client
                .submit_circuits_parallel(&self.backend.name, configs)
                .await?;

            // Wait for all jobs to complete
            let mut chunk_results = Vec::new();
            for job_id in job_ids {
                let result = self
                    .client
                    .wait_for_job(&job_id, Some(self.config.timeout_seconds))
                    .await?;

                let mut metadata = HashMap::new();
                metadata.insert("job_id".to_string(), job_id);
                metadata.insert("backend".to_string(), self.backend.name.clone());
                metadata.insert("shots".to_string(), shots.to_string());

                chunk_results.push(CircuitResult {
                    counts: result.counts,
                    shots: result.shots,
                    metadata,
                });
            }

            results.extend(chunk_results);
        }

        Ok(results)
    }

    async fn can_execute_circuit<const N: usize>(
        &self,
        _circuit: &Circuit<N>,
    ) -> DeviceResult<bool> {
        // Basic check: does the circuit fit on the device?
        if N > self.backend.n_qubits {
            return Ok(false);
        }

        // In a more sophisticated implementation, this would check:
        // - If all gates in the circuit are supported by the backend
        // - If the circuit depth is within backend limits
        // - If the connectivity requirements are satisfied

        // For now, just do a basic qubit count check
        Ok(true)
    }

    async fn estimated_queue_time<const N: usize>(
        &self,
        _circuit: &Circuit<N>,
    ) -> DeviceResult<Duration> {
        // In a complete implementation, this would query the IBM Quantum API
        // for the current queue times or use a heuristic based on backend popularity

        // For now, return a placeholder estimate
        if self.backend.simulator {
            Ok(Duration::from_secs(10)) // Simulators typically have short queues
        } else {
            Ok(Duration::from_secs(3600)) // Hardware often has longer queues
        }
    }
}

#[cfg(not(feature = "_async_device"))]
impl CircuitExecutor for IBMQuantumDevice {
    fn execute_circuit<const N: usize>(
        &self,
        _circuit: &Circuit<N>,
        _shots: usize,
    ) -> DeviceResult<CircuitResult> {
        Err(DeviceError::UnsupportedDevice(
            "IBM Quantum support not enabled".to_string(),
        ))
    }

    fn execute_circuits<const N: usize>(
        &self,
        _circuits: Vec<&Circuit<N>>,
        _shots: usize,
    ) -> DeviceResult<Vec<CircuitResult>> {
        Err(DeviceError::UnsupportedDevice(
            "IBM Quantum support not enabled".to_string(),
        ))
    }

    fn can_execute_circuit<const N: usize>(&self, _circuit: &Circuit<N>) -> DeviceResult<bool> {
        Err(DeviceError::UnsupportedDevice(
            "IBM Quantum support not enabled".to_string(),
        ))
    }

    fn estimated_queue_time<const N: usize>(
        &self,
        _circuit: &Circuit<N>,
    ) -> DeviceResult<std::time::Duration> {
        Err(DeviceError::UnsupportedDevice(
            "IBM Quantum support not enabled".to_string(),
        ))
    }
}

#[cfg(all(test, feature = "ibm"))]
mod tests {
    use super::*;

    fn test_device() -> IBMQuantumDevice {
        let client = IBMQuantumClient::new("test_token").expect("build test client");
        let backend = crate::ibm::IBMBackend {
            id: "ibmq_test".to_string(),
            name: "ibmq_test".to_string(),
            simulator: true,
            n_qubits: 5,
            status: "active".to_string(),
            description: "Test backend".to_string(),
            version: "1.0".to_string(),
        };

        IBMQuantumDevice {
            client: Arc::new(client),
            backend,
            config: IBMDeviceConfig::default(),
        }
    }

    #[test]
    fn test_circuit_to_qasm_emits_real_gates_on_device() {
        // Build a Bell-state circuit: H on q0, CNOT(q0, q1).
        let mut circuit = Circuit::<2>::new();
        circuit.h(0).expect("add H");
        circuit.cnot(0, 1).expect("add CNOT");

        let device = test_device();
        let qasm = device
            .circuit_to_qasm(&circuit)
            .expect("QASM conversion should succeed");

        // Header and registers must be present.
        assert!(qasm.contains("OPENQASM 2.0"), "missing header: {qasm}");
        assert!(qasm.contains("qreg q[2]"), "missing register: {qasm}");

        // Critically: the REAL gate lines must be emitted (not just headers).
        assert!(qasm.contains("h q[0]"), "missing H gate: {qasm}");
        assert!(qasm.contains("cx q[0], q[1]"), "missing CNOT gate: {qasm}");
    }

    #[test]
    fn test_circuit_to_qasm_rejects_oversized_circuit() {
        let mut circuit = Circuit::<8>::new();
        circuit.h(0).expect("add H");

        let device = test_device(); // backend only supports 5 qubits
        let result = device.circuit_to_qasm(&circuit);
        assert!(result.is_err(), "expected oversized circuit to be rejected");
    }
}