roqoqo 1.22.2

Rust Quantum Computing Toolkit by HQS
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
// Copyright © 2021-2024 HQS Quantum Simulations GmbH. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing permissions and
// limitations under the License.

use crate::operations;
use crate::prelude::*;
use crate::Circuit;
use crate::RoqoqoError;
use ndarray::prelude::*;
use num_complex::Complex64;
use qoqo_calculator::CalculatorFloat;
#[cfg(feature = "overrotate")]
use rand_distr::{Distribution, Normal};
#[cfg(feature = "serialize")]
use serde::{Deserialize, Serialize};
use std::{f64::consts::PI, panic};

/// The Molmer-Sorensen gate between multiple qubits.
///
/// The gate applies the rotation under the product of Pauli X operators on multiple qubits.
/// In mathematical terms the gate applies exp(-i * θ/2 * X_i0 * X_i1 * ... * X_in).
#[allow(clippy::upper_case_acronyms)]
#[derive(
    Debug,
    Clone,
    PartialEq,
    roqoqo_derive::InvolveQubits,
    roqoqo_derive::SupportedVersion,
    roqoqo_derive::Operate,
    roqoqo_derive::Substitute,
    roqoqo_derive::OperateMultiQubit,
    roqoqo_derive::Rotate,
)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "json_schema", derive(schemars::JsonSchema))]
pub struct MultiQubitMS {
    /// The qubits involved in the multi qubit Molmer-Sorensen gate.
    qubits: Vec<usize>,
    /// The angle of the multi qubit Molmer-Sorensen gate.
    theta: CalculatorFloat,
}

#[allow(non_upper_case_globals)]
const TAGS_MultiQubitMS: &[&str; 4] = &[
    "Operation",
    "GateOperation",
    "MultiQubitGateOperation",
    "MultiQubitMS",
];

impl OperateGate for MultiQubitMS {
    fn unitary_matrix(&self) -> Result<Array2<Complex64>, RoqoqoError> {
        let dim = 2_usize.pow(self.qubits.len() as u32);
        let mut array: Array2<Complex64> = Array2::zeros((dim, dim));
        let cos: Complex64 = Complex64::new((self.theta.float()? / 2.0).cos(), 0.0);
        let sin: Complex64 = Complex64::new(0.0, -(self.theta.float()? / 2.0).sin());
        for i in 0..dim {
            array[(i, i)] = cos;
            array[(i, dim - i - 1)] = sin;
        }
        Ok(array)
    }
}

impl OperateMultiQubitGate for MultiQubitMS {
    fn circuit(&self) -> Circuit {
        let dim = self.qubits.len();
        let mut circuit = Circuit::new();
        for q in self.qubits.iter() {
            circuit += operations::Hadamard::new(*q);
        }
        for q in self.qubits[1..].iter() {
            circuit += operations::CNOT::new(*q - 1, *q);
        }
        circuit += operations::RotateZ::new(dim - 1, self.theta.clone());
        for q in self.qubits[1..].iter() {
            circuit += operations::CNOT::new(dim - *q - 1, dim - *q);
        }
        for q in self.qubits.iter() {
            circuit += operations::Hadamard::new(*q);
        }
        circuit
    }
}

/// The multi qubit CNOT-Product gate: applies the CNOT gate with multiple controls.
///
/// This corresponds to a generalised Toffoli gate.
#[allow(clippy::upper_case_acronyms)]
#[derive(
    Debug,
    Clone,
    PartialEq,
    roqoqo_derive::InvolveQubits,
    roqoqo_derive::Operate,
    roqoqo_derive::Substitute,
    roqoqo_derive::OperateMultiQubit,
)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "json_schema", derive(schemars::JsonSchema))]
pub struct MultiQubitCNOT {
    qubits: Vec<usize>,
}

#[allow(non_upper_case_globals)]
const TAGS_MultiQubitCNOT: &[&str; 4] = &[
    "Operation",
    "GateOperation",
    "MultiQubitGateOperation",
    "MultiQubitCNOT",
];

impl operations::ImplementedIn1point20 for MultiQubitCNOT {}

impl SupportedVersion for MultiQubitCNOT {
    fn minimum_supported_roqoqo_version(&self) -> (u32, u32, u32) {
        (1, 20, 0)
    }
}

impl OperateGate for MultiQubitCNOT {
    fn unitary_matrix(&self) -> Result<Array2<Complex64>, RoqoqoError> {
        let dim = 2_usize.pow(self.qubits.len() as u32);
        let mut array = Array2::eye(dim);
        array
            .slice_mut(s![dim - 2.., dim - 2..])
            .assign(&array![[0., 1.], [1., 0.]]);
        Ok(array.map(|x| x.into()))
    }
}

impl OperateMultiQubitGate for MultiQubitCNOT {
    // https://en.wikipedia.org/wiki/Toffoli_gate#/media/File:Qcircuit_ToffolifromCNOT.svg
    fn circuit(&self) -> Circuit {
        let mut circuit = Circuit::new();
        match self.qubits().len() {
            2 => {
                circuit += operations::CNOT::new(self.qubits[0], self.qubits[1]);
            }
            3 => {
                circuit += operations::Hadamard::new(self.qubits[2]);
                circuit += operations::CNOT::new(self.qubits[1], self.qubits[2]);
                circuit +=
                    operations::PhaseShiftState1::new(self.qubits[2], -CalculatorFloat::FRAC_PI_4);
                circuit += operations::CNOT::new(self.qubits[0], self.qubits[2]);
                circuit += operations::TGate::new(self.qubits[2]);
                circuit += operations::CNOT::new(self.qubits[1], self.qubits[2]);
                circuit +=
                    operations::PhaseShiftState1::new(self.qubits[2], -CalculatorFloat::FRAC_PI_4);
                circuit += operations::CNOT::new(self.qubits[0], self.qubits[2]);
                circuit += operations::TGate::new(self.qubits[1]);
                circuit += operations::TGate::new(self.qubits[2]);
                circuit += operations::Hadamard::new(self.qubits[2]);
                circuit += operations::CNOT::new(self.qubits[0], self.qubits[1]);
                circuit += operations::TGate::new(self.qubits[0]);
                circuit +=
                    operations::PhaseShiftState1::new(self.qubits[1], -CalculatorFloat::FRAC_PI_4);
                circuit += operations::CNOT::new(self.qubits[0], self.qubits[1]);
            }
            _ => panic!(
                "Only MultiQubitCNOT gates with 2 or 3 controls can be turned into a circuit."
            ),
        }
        circuit
    }
}

/// The multi qubit Pauli-Z-Product gate.
///
/// The gate applies the rotation under the product of Pauli Z operators on multiple qubits.
/// In mathematical terms the gate applies exp(-i * θ/2 * Z_i0 * Z_i1 * ... * Z_in).
#[allow(clippy::upper_case_acronyms)]
#[derive(
    Debug,
    Clone,
    PartialEq,
    roqoqo_derive::InvolveQubits,
    roqoqo_derive::SupportedVersion,
    roqoqo_derive::Operate,
    roqoqo_derive::Substitute,
    roqoqo_derive::OperateMultiQubit,
    roqoqo_derive::Rotate,
)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "json_schema", derive(schemars::JsonSchema))]
pub struct MultiQubitZZ {
    /// The qubits involved in the multi qubit Molmer-Sorensen gate.
    qubits: Vec<usize>,
    /// The angle of the multi qubit Molmer-Sorensen gate.
    theta: CalculatorFloat,
}

#[allow(non_upper_case_globals)]
const TAGS_MultiQubitZZ: &[&str; 4] = &[
    "Operation",
    "GateOperation",
    "MultiQubitGateOperation",
    "MultiQubitZZ",
];

impl OperateGate for MultiQubitZZ {
    fn unitary_matrix(&self) -> Result<Array2<Complex64>, RoqoqoError> {
        let dim = 2_usize.pow(self.qubits.len() as u32);
        let mut array: Array2<Complex64> = Array2::zeros((dim, dim));
        let cos: Complex64 = Complex64::new((self.theta.float()? / 2.0).cos(), 0.0);
        let sin: Complex64 = Complex64::new(0.0, -(self.theta.float()? / 2.0).sin());
        for i in 0..dim {
            // Fix the signs of the imaginary part due to the ZZZ..ZZ product
            let prefactor: f64 = (0..self.qubits.len())
                .map(|q| match i.div_euclid(2usize.pow(q as u32)) % 2 {
                    0 => 1.0,
                    1 => -1.0,
                    _ => panic!("Internal division error MuliQubitZZ"),
                })
                .product();
            array[(i, i)] = cos + prefactor * sin;
        }
        Ok(array)
    }
}

impl OperateMultiQubitGate for MultiQubitZZ {
    fn circuit(&self) -> Circuit {
        let dim = self.qubits.len();
        let mut circuit = Circuit::new();
        for q in self.qubits[1..].iter() {
            circuit += operations::CNOT::new(*q - 1, *q);
        }
        circuit += operations::RotateZ::new(dim - 1, self.theta.clone());
        for q in self.qubits[1..].iter() {
            circuit += operations::CNOT::new(dim - *q - 1, dim - *q);
        }
        circuit
    }
}

/// The gate to be replaced by a gate defined with GateDefinition gate.
///
/// The gate applies a gate previously defined by GateDefinition with the name gate_name.
#[cfg(feature = "unstable_operation_definition")]
#[allow(clippy::upper_case_acronyms)]
#[derive(
    Debug,
    Clone,
    PartialEq,
    roqoqo_derive::OperateMultiQubit,
    roqoqo_derive::Operate,
    roqoqo_derive::InvolveQubits,
)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "json_schema", derive(schemars::JsonSchema))]
pub struct CallDefinedGate {
    /// The name of the called defined operations.
    gate_name: String,
    /// The qubits that for this call replace the qubits in the internal definition of the called gate
    /// (get replaced in order of apppearance in gate defintion).
    qubits: Vec<usize>,
    /// List of float values that replace the free parameters in the internal defintion of the called gate
    /// (get replaced in order of apppearance in gate defintion).
    free_parameters: Vec<CalculatorFloat>,
}

#[cfg(feature = "unstable_operation_definition")]
impl Substitute for CallDefinedGate {
    fn substitute_parameters(
        &self,
        calculator: &qoqo_calculator::Calculator,
    ) -> Result<Self, RoqoqoError> {
        let mut new_params: Vec<CalculatorFloat> = vec![];
        for param in &self.free_parameters.clone() {
            new_params.push(CalculatorFloat::from(
                calculator
                    .parse_get(param.clone())
                    .map_err(RoqoqoError::CalculatorError)?,
            ));
        }

        Ok(CallDefinedGate::new(
            self.gate_name.clone(),
            self.qubits.clone(),
            new_params,
        ))
    }

    fn remap_qubits(
        &self,
        mapping: &std::collections::HashMap<usize, usize>,
    ) -> Result<Self, RoqoqoError> {
        crate::operations::check_valid_mapping(mapping)?;
        let mut new_qubits: Vec<usize> = Vec::new();
        for q in &self.qubits {
            new_qubits.push(*mapping.get(q).ok_or(Err("")).map_err(
                |_x: std::result::Result<&usize, &str>| RoqoqoError::QubitMappingError {
                    qubit: *q,
                },
            )?)
        }

        Ok(CallDefinedGate::new(
            self.gate_name.clone(),
            new_qubits,
            self.free_parameters.clone(),
        ))
    }
}

#[cfg(feature = "unstable_operation_definition")]
impl super::ImplementedIn1point13 for CallDefinedGate {}

#[cfg(feature = "unstable_operation_definition")]
impl SupportedVersion for CallDefinedGate {
    fn minimum_supported_roqoqo_version(&self) -> (u32, u32, u32) {
        (1, 13, 0)
    }
}

#[cfg(feature = "unstable_operation_definition")]
#[allow(non_upper_case_globals)]
const TAGS_CallDefinedGate: &[&str; 3] =
    &["Operation", "MultiQubitGateOperation", "CallDefinedGate"];

/// The quantum Fourier transform.
///
/// This is the quantum analogue of the discrete Fourier transform, which maps between the time
/// domain and the frequency domain.
/// The QFT maps a quantum state |x> to |y> according to the following transformation:
///
/// .. math::
///     y_k = \frac{1}{\sqrt{N}} \sum_{j=0}^{N-1} x_j e^{\frac{2 \pi \mathrm{i} j k}{N}}
///
#[allow(clippy::upper_case_acronyms)]
#[derive(
    Debug,
    Clone,
    PartialEq,
    roqoqo_derive::InvolveQubits,
    roqoqo_derive::Operate,
    roqoqo_derive::Substitute,
    roqoqo_derive::OperateMultiQubit,
)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "json_schema", derive(schemars::JsonSchema))]
pub struct QFT {
    /// The qubits involved in the QFT.
    qubits: Vec<usize>,
    /// Include qubit swaps at the end.
    swaps: bool,
    /// Do inverse QFT.
    inverse: bool,
}

const TAGS_QFT: &[&str; 4] = &[
    "Operation",
    "GateOperation",
    "MultiQubitGateOperation",
    "QFT",
];

impl operations::ImplementedIn1point20 for QFT {}

impl SupportedVersion for QFT {
    fn minimum_supported_roqoqo_version(&self) -> (u32, u32, u32) {
        (1, 20, 0)
    }
}

impl OperateGate for QFT {
    fn unitary_matrix(&self) -> Result<Array2<Complex64>, RoqoqoError> {
        let dim = self.qubits.len();
        if !self.swaps && dim > 1 {
            return Err(RoqoqoError::GenericError {
                msg: "Unitary matrix output is only supported for QFT with swapping.".into(),
            });
        }
        let n = 2_usize.pow(dim as u32);
        let mut array = Array2::zeros((n, n));
        for i in 0..n {
            for j in 0..n {
                let mut theta = 2. * PI * (i as f64 * j as f64) / (n as f64);
                if self.inverse {
                    theta *= -1.;
                }
                array[[i, j]] = Complex64::from_polar(1. / (n as f64).sqrt(), theta);
            }
        }
        Ok(array)
    }
}

impl OperateMultiQubitGate for QFT {
    fn circuit(&self) -> Circuit {
        let dim = self.qubits.len();
        let mut circuit = Circuit::new();

        if self.swaps && self.inverse {
            for i in 0..dim / 2 {
                circuit += operations::SWAP::new(self.qubits[i], self.qubits[dim - i - 1]);
            }
        }
        for i in 0..dim {
            circuit += operations::Hadamard::new(self.qubits[i]);
            for j in i + 1..dim {
                let mut theta = PI / 2.0_f64.powi((j - i) as i32);
                if self.inverse {
                    theta *= -1.;
                }
                circuit += operations::ControlledPhaseShift::new(
                    self.qubits[j],
                    self.qubits[i],
                    theta.into(),
                );
            }
        }
        if self.swaps && !self.inverse {
            for i in 0..dim / 2 {
                circuit += operations::SWAP::new(self.qubits[i], self.qubits[dim - i - 1]);
            }
        }
        circuit
    }
}