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
//! Gate synthesis from unitary matrices
//!
//! This module provides algorithms to decompose arbitrary unitary matrices
//! into sequences of quantum gates, including:
//! - Single-qubit unitary decomposition (ZYZ, XYX, etc.)
//! - Two-qubit unitary decomposition (KAK/Cartan)
//! - General n-qubit synthesis using Cosine-Sine decomposition

use crate::cartan::{CartanDecomposer, CartanDecomposition};
// use crate::controlled::{make_controlled, ControlledGate};
use crate::error::{QuantRS2Error, QuantRS2Result};
use crate::gate::{single::*, GateOp};
use crate::matrix_ops::{matrices_approx_equal, DenseMatrix, QuantumMatrix};
use crate::qubit::QubitId;
use scirs2_core::ndarray::{Array2, ArrayView2};
use scirs2_core::Complex64;
use std::f64::consts::PI;

/// Result of single-qubit decomposition
#[derive(Debug, Clone)]
pub struct SingleQubitDecomposition {
    /// Global phase
    pub global_phase: f64,
    /// First rotation angle (Z or X depending on basis)
    pub theta1: f64,
    /// Middle rotation angle (Y)
    pub phi: f64,
    /// Last rotation angle (Z or X depending on basis)
    pub theta2: f64,
    /// The basis used (e.g., "ZYZ", "XYX")
    pub basis: String,
}

/// Decompose a single-qubit unitary into ZYZ rotations
pub fn decompose_single_qubit_zyz(
    unitary: &ArrayView2<Complex64>,
) -> QuantRS2Result<SingleQubitDecomposition> {
    if unitary.shape() != &[2, 2] {
        return Err(QuantRS2Error::InvalidInput(
            "Single-qubit unitary must be 2x2".to_string(),
        ));
    }

    // Check unitarity
    let matrix = DenseMatrix::new(unitary.to_owned())?;
    if !matrix.is_unitary(1e-10)? {
        return Err(QuantRS2Error::InvalidInput(
            "Matrix is not unitary".to_string(),
        ));
    }

    // Extract matrix elements
    let a = unitary[[0, 0]];
    let b = unitary[[0, 1]];
    let c = unitary[[1, 0]];
    let d = unitary[[1, 1]];

    // Calculate global phase from determinant
    let det = a * d - b * c;
    let global_phase = det.arg() / 2.0;

    // Normalize by the determinant to make the matrix special unitary
    let det_sqrt = det.sqrt();
    let a = a / det_sqrt;
    let b = b / det_sqrt;
    let c = c / det_sqrt;
    let d = d / det_sqrt;

    // Decompose into ZYZ angles
    // U = e^(i*global_phase) * Rz(theta2) * Ry(phi) * Rz(theta1)

    let phi = 2.0 * a.norm().acos();

    let (theta1, theta2) = if phi.abs() < 1e-10 {
        // Identity or phase gate
        let phase = if a.norm() > 0.5 {
            a.arg() * 2.0
        } else {
            d.arg() * 2.0
        };
        (0.0, phase)
    } else if (phi - PI).abs() < 1e-10 {
        // Pi rotation
        (-b.arg() + c.arg() + PI, 0.0)
    } else {
        // From Rz(θ₂)·Ry(φ)·Rz(θ₁) decomposition of SU(2) matrix [[a,b],[c,d]]:
        //   arg(a) = -(θ₁+θ₂)/2  and  arg(c) = (θ₂-θ₁)/2
        // Solving: θ₁ = -arg(a) - arg(c),  θ₂ = arg(c) - arg(a)
        let theta1 = -a.arg() - c.arg();
        let theta2 = c.arg() - a.arg();
        (theta1, theta2)
    };

    Ok(SingleQubitDecomposition {
        global_phase,
        theta1,
        phi,
        theta2,
        basis: "ZYZ".to_string(),
    })
}

/// Decompose a single-qubit unitary into XYX rotations
pub fn decompose_single_qubit_xyx(
    unitary: &ArrayView2<Complex64>,
) -> QuantRS2Result<SingleQubitDecomposition> {
    // Convert to Pauli basis and use ZYZ decomposition
    // Safety: 2x2 shape with 4 elements is guaranteed valid
    let h_gate = Array2::from_shape_vec(
        (2, 2),
        vec![
            Complex64::new(1.0, 0.0),
            Complex64::new(1.0, 0.0),
            Complex64::new(1.0, 0.0),
            Complex64::new(-1.0, 0.0),
        ],
    )
    .expect("2x2 Hadamard matrix shape is always valid")
        / Complex64::new(2.0_f64.sqrt(), 0.0);

    // Transform: U' = H * U * H
    let u_transformed = h_gate.dot(unitary).dot(&h_gate);
    let decomp = decompose_single_qubit_zyz(&u_transformed.view())?;

    Ok(SingleQubitDecomposition {
        global_phase: decomp.global_phase,
        theta1: decomp.theta1,
        phi: decomp.phi,
        theta2: decomp.theta2,
        basis: "XYX".to_string(),
    })
}

/// Convert single-qubit decomposition to gate sequence
pub fn single_qubit_gates(
    decomp: &SingleQubitDecomposition,
    qubit: QubitId,
) -> Vec<Box<dyn GateOp>> {
    let mut gates: Vec<Box<dyn GateOp>> = Vec::new();

    match decomp.basis.as_str() {
        "ZYZ" => {
            if decomp.theta1.abs() > 1e-10 {
                gates.push(Box::new(RotationZ {
                    target: qubit,
                    theta: decomp.theta1,
                }));
            }
            if decomp.phi.abs() > 1e-10 {
                gates.push(Box::new(RotationY {
                    target: qubit,
                    theta: decomp.phi,
                }));
            }
            if decomp.theta2.abs() > 1e-10 {
                gates.push(Box::new(RotationZ {
                    target: qubit,
                    theta: decomp.theta2,
                }));
            }
        }
        "XYX" => {
            if decomp.theta1.abs() > 1e-10 {
                gates.push(Box::new(RotationX {
                    target: qubit,
                    theta: decomp.theta1,
                }));
            }
            if decomp.phi.abs() > 1e-10 {
                gates.push(Box::new(RotationY {
                    target: qubit,
                    theta: decomp.phi,
                }));
            }
            if decomp.theta2.abs() > 1e-10 {
                gates.push(Box::new(RotationX {
                    target: qubit,
                    theta: decomp.theta2,
                }));
            }
        }
        _ => {} // Unknown basis
    }

    gates
}

/// Result of two-qubit KAK decomposition (alias for CartanDecomposition)
pub type KAKDecomposition = CartanDecomposition;

/// Decompose a two-qubit unitary using KAK decomposition
pub fn decompose_two_qubit_kak(
    unitary: &ArrayView2<Complex64>,
) -> QuantRS2Result<KAKDecomposition> {
    // Use Cartan decomposer for KAK decomposition
    let mut decomposer = CartanDecomposer::new();
    let owned_unitary = unitary.to_owned();
    decomposer.decompose(&owned_unitary)
}

/// Convert KAK decomposition to gate sequence
pub fn kak_to_gates(
    decomp: &KAKDecomposition,
    qubit1: QubitId,
    qubit2: QubitId,
) -> QuantRS2Result<Vec<Box<dyn GateOp>>> {
    // Use CartanDecomposer to convert to gates
    let decomposer = CartanDecomposer::new();
    let qubit_ids = vec![qubit1, qubit2];
    decomposer.to_gates(decomp, &qubit_ids)
}

/// Synthesize an arbitrary unitary matrix into quantum gates
pub fn synthesize_unitary(
    unitary: &ArrayView2<Complex64>,
    qubits: &[QubitId],
) -> QuantRS2Result<Vec<Box<dyn GateOp>>> {
    let n = unitary.nrows();

    if n != unitary.ncols() {
        return Err(QuantRS2Error::InvalidInput(
            "Matrix must be square".to_string(),
        ));
    }

    let num_qubits = (n as f64).log2() as usize;
    if (1 << num_qubits) != n {
        return Err(QuantRS2Error::InvalidInput(
            "Matrix dimension must be a power of 2".to_string(),
        ));
    }

    if qubits.len() != num_qubits {
        return Err(QuantRS2Error::InvalidInput(format!(
            "Need {} qubits, got {}",
            num_qubits,
            qubits.len()
        )));
    }

    // Check unitarity
    let matrix = DenseMatrix::new(unitary.to_owned())?;
    if !matrix.is_unitary(1e-10)? {
        return Err(QuantRS2Error::InvalidInput(
            "Matrix is not unitary".to_string(),
        ));
    }

    match num_qubits {
        1 => {
            let decomp = decompose_single_qubit_zyz(unitary)?;
            Ok(single_qubit_gates(&decomp, qubits[0]))
        }
        2 => {
            let decomp = decompose_two_qubit_kak(unitary)?;
            kak_to_gates(&decomp, qubits[0], qubits[1])
        }
        _ => {
            // For n-qubit gates, use recursive decomposition
            // This is a placeholder - would implement Cosine-Sine decomposition
            Err(QuantRS2Error::UnsupportedOperation(format!(
                "Synthesis for {num_qubits}-qubit gates not yet implemented"
            )))
        }
    }
}

/// Check if a unitary is close to a known gate
pub fn identify_gate(unitary: &ArrayView2<Complex64>, tolerance: f64) -> Option<String> {
    let n = unitary.nrows();

    match n {
        2 => {
            // Check common single-qubit gates
            let gates = vec![
                ("I", Array2::eye(2)),
                // Safety: All 2x2 shapes with 4 elements are guaranteed valid
                (
                    "X",
                    Array2::from_shape_vec(
                        (2, 2),
                        vec![
                            Complex64::new(0.0, 0.0),
                            Complex64::new(1.0, 0.0),
                            Complex64::new(1.0, 0.0),
                            Complex64::new(0.0, 0.0),
                        ],
                    )
                    .expect("2x2 X gate shape is always valid"),
                ),
                (
                    "Y",
                    Array2::from_shape_vec(
                        (2, 2),
                        vec![
                            Complex64::new(0.0, 0.0),
                            Complex64::new(0.0, -1.0),
                            Complex64::new(0.0, 1.0),
                            Complex64::new(0.0, 0.0),
                        ],
                    )
                    .expect("2x2 Y gate shape is always valid"),
                ),
                (
                    "Z",
                    Array2::from_shape_vec(
                        (2, 2),
                        vec![
                            Complex64::new(1.0, 0.0),
                            Complex64::new(0.0, 0.0),
                            Complex64::new(0.0, 0.0),
                            Complex64::new(-1.0, 0.0),
                        ],
                    )
                    .expect("2x2 Z gate shape is always valid"),
                ),
                (
                    "H",
                    Array2::from_shape_vec(
                        (2, 2),
                        vec![
                            Complex64::new(1.0, 0.0),
                            Complex64::new(1.0, 0.0),
                            Complex64::new(1.0, 0.0),
                            Complex64::new(-1.0, 0.0),
                        ],
                    )
                    .expect("2x2 H gate shape is always valid")
                        / Complex64::new(2.0_f64.sqrt(), 0.0),
                ),
            ];

            for (name, gate) in gates {
                if matrices_approx_equal(unitary, &gate.view(), tolerance) {
                    return Some(name.to_string());
                }
            }
        }
        4 => {
            // Check common two-qubit gates
            let mut cnot = Array2::eye(4);
            cnot[[2, 2]] = Complex64::new(0.0, 0.0);
            cnot[[2, 3]] = Complex64::new(1.0, 0.0);
            cnot[[3, 2]] = Complex64::new(1.0, 0.0);
            cnot[[3, 3]] = Complex64::new(0.0, 0.0);

            if matrices_approx_equal(unitary, &cnot.view(), tolerance) {
                return Some("CNOT".to_string());
            }
        }
        _ => {}
    }

    None
}

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

    #[test]
    fn test_single_qubit_decomposition() {
        // Test Hadamard gate
        let h = Array2::from_shape_vec(
            (2, 2),
            vec![
                Complex64::new(1.0, 0.0),
                Complex64::new(1.0, 0.0),
                Complex64::new(1.0, 0.0),
                Complex64::new(-1.0, 0.0),
            ],
        )
        .expect("Hadamard matrix shape is always valid 2x2")
            / Complex64::new(2.0_f64.sqrt(), 0.0);

        let decomp =
            decompose_single_qubit_zyz(&h.view()).expect("ZYZ decomposition should succeed");

        // Reconstruct and verify
        let rz1 = Array2::from_shape_vec(
            (2, 2),
            vec![
                Complex64::new(0.0, -decomp.theta1 / 2.0).exp(),
                Complex64::new(0.0, 0.0),
                Complex64::new(0.0, 0.0),
                Complex64::new(0.0, decomp.theta1 / 2.0).exp(),
            ],
        )
        .expect("Rz1 matrix shape is always valid 2x2");

        let ry = Array2::from_shape_vec(
            (2, 2),
            vec![
                Complex64::new((decomp.phi / 2.0).cos(), 0.0),
                Complex64::new(-(decomp.phi / 2.0).sin(), 0.0),
                Complex64::new((decomp.phi / 2.0).sin(), 0.0),
                Complex64::new((decomp.phi / 2.0).cos(), 0.0),
            ],
        )
        .expect("Ry matrix shape is always valid 2x2");

        let rz2 = Array2::from_shape_vec(
            (2, 2),
            vec![
                Complex64::new(0.0, -decomp.theta2 / 2.0).exp(),
                Complex64::new(0.0, 0.0),
                Complex64::new(0.0, 0.0),
                Complex64::new(0.0, decomp.theta2 / 2.0).exp(),
            ],
        )
        .expect("Rz2 matrix shape is always valid 2x2");

        // Reconstruct: e^(i*global_phase) * Rz(theta2) * Ry(phi) * Rz(theta1)
        let reconstructed = Complex64::new(0.0, decomp.global_phase).exp() * rz2.dot(&ry).dot(&rz1);

        // Check reconstruction
        assert!(matrices_approx_equal(
            &h.view(),
            &reconstructed.view(),
            1e-10
        ));
    }

    #[test]
    fn test_gate_identification() {
        let x = Array2::from_shape_vec(
            (2, 2),
            vec![
                Complex64::new(0.0, 0.0),
                Complex64::new(1.0, 0.0),
                Complex64::new(1.0, 0.0),
                Complex64::new(0.0, 0.0),
            ],
        )
        .expect("X gate matrix shape is always valid 2x2");

        assert_eq!(identify_gate(&x.view(), 1e-10), Some("X".to_string()));
    }
}