Skip to main content

ctrl_freeq/setup/
states.rs

1//! Spin operators, product states, gates and rotations.
2//!
3//! Qubit 0 is the most significant factor of every Kronecker product, as in the Python package.
4
5use std::f64::consts::FRAC_1_SQRT_2;
6
7use crate::autodiff::C;
8use crate::error::{Error, Result};
9use crate::linalg::{CMat, Mat, expm};
10
11fn c(re: f64, im: f64) -> C<f64> {
12    C::new(re, im)
13}
14
15fn mat(n: usize, entries: &[C<f64>]) -> CMat<f64> {
16    Mat::from_vec(n, n, entries.to_vec()).expect("literal matrices have the right size")
17}
18
19/// The Pauli matrices `[σx, σy, σz]`.
20pub fn paulis() -> [CMat<f64>; 3] {
21    let (o, l, i) = (c(0.0, 0.0), c(1.0, 0.0), c(0.0, 1.0));
22    [mat(2, &[o, l, l, o]), mat(2, &[o, -i, i, o]), mat(2, &[l, o, o, -l])]
23}
24
25/// `op` acting on qubit `qubit` of `n`, identity on the rest.
26pub fn embed(op: &CMat<f64>, qubit: usize, n: usize) -> CMat<f64> {
27    let id = CMat::<f64>::identity(op.rows);
28    let mut out = CMat::<f64>::identity(1);
29    for q in 0..n {
30        out = out.kron(if q == qubit { op } else { &id });
31    }
32    out
33}
34
35/// Per qubit, the spin operators `[X, Y, Z] = [σx, σy, σz]/2` in the `2ⁿ`-dimensional space.
36pub fn spin_ops(n: usize) -> Vec<[CMat<f64>; 3]> {
37    let p = paulis();
38    (0..n)
39        .map(|q| [0, 1, 2].map(|k| embed(&p[k].scale_re(0.5), q, n)))
40        .collect()
41}
42
43/// Per qubit, the Pauli observables `[σx, σy, σz]` in the `2ⁿ`-dimensional space.
44pub fn pauli_ops(n: usize) -> Vec<[CMat<f64>; 3]> {
45    let p = paulis();
46    (0..n).map(|q| [0, 1, 2].map(|k| embed(&p[k], q, n))).collect()
47}
48
49/// The single-qubit state along `axis` (`Z` = |0⟩, `-Z` = |1⟩, `X`, `-X`, `Y`, `-Y`).
50fn axis_state(axis: &str) -> Result<[C<f64>; 2]> {
51    let s = FRAC_1_SQRT_2;
52    Ok(match axis {
53        "Z" => [c(1.0, 0.0), c(0.0, 0.0)],
54        "-Z" => [c(0.0, 0.0), c(1.0, 0.0)],
55        "X" => [c(s, 0.0), c(s, 0.0)],
56        "-X" => [c(s, 0.0), c(-s, 0.0)],
57        "Y" => [c(s, 0.0), c(0.0, s)],
58        "-Y" => [c(s, 0.0), c(0.0, -s)],
59        _ => return Err(Error::Config(format!("unknown state axis \"{axis}\""))),
60    })
61}
62
63/// The product state vector for one axis per qubit.
64pub fn product_state(axes: &[String]) -> Result<CMat<f64>> {
65    let mut out = CMat::<f64>::identity(1);
66    for a in axes {
67        let s = axis_state(a)?;
68        out = out.kron(&Mat::column(s.to_vec()));
69    }
70    Ok(out)
71}
72
73/// The product density matrix `⊗ ½(I ± σ)` for one axis per qubit.
74pub fn product_density(axes: &[String]) -> Result<CMat<f64>> {
75    let psi = product_state(axes)?;
76    psi.matmul(&psi.adjoint())
77}
78
79/// Gate names available for `n` qubits, in the order the interface lists them.
80pub fn gate_names(n: usize) -> &'static [&'static str] {
81    match n {
82        1 => &["X", "Y", "Z", "H", "S", "T"],
83        2 => &["CNOT", "CX", "CZ", "SWAP", "iSWAP", "√iSWAP", "ECR"],
84        3 => &["Toff"],
85        _ => &[],
86    }
87}
88
89/// The canonical name of gate `name`, which some gates have more than one of: `CX` is `CNOT`.
90///
91/// Targets name one gate when their canonical names agree, whatever the configuration spelled; see
92/// [`Targets::single_gate`](crate::config::Targets::single_gate).
93pub fn canonical_gate(name: &str) -> &str {
94    match name {
95        "CX" => "CNOT",
96        other => other,
97    }
98}
99
100/// The unitary for gate `name` on `n` qubits.
101pub fn gate(name: &str, n: usize) -> Result<CMat<f64>> {
102    let (o, l, i) = (c(0.0, 0.0), c(1.0, 0.0), c(0.0, 1.0));
103    let s = FRAC_1_SQRT_2;
104    let (sr, si) = (c(s, 0.0), c(0.0, s));
105    let g = match (n, name) {
106        (1, "X") => mat(2, &[o, l, l, o]),
107        (1, "Y") => mat(2, &[o, -i, i, o]),
108        (1, "Z") => mat(2, &[l, o, o, -l]),
109        (1, "H") => mat(2, &[sr, sr, sr, -sr]),
110        (1, "S") => mat(2, &[l, o, o, i]),
111        (1, "T") => mat(2, &[l, o, o, C::from_polar(1.0, std::f64::consts::FRAC_PI_4)]),
112        (2, "CNOT" | "CX") => mat(4, &[l, o, o, o, o, l, o, o, o, o, o, l, o, o, l, o]),
113        (2, "CZ") => mat(4, &[l, o, o, o, o, l, o, o, o, o, l, o, o, o, o, -l]),
114        (2, "SWAP") => mat(4, &[l, o, o, o, o, o, l, o, o, l, o, o, o, o, o, l]),
115        (2, "iSWAP") => mat(4, &[l, o, o, o, o, o, i, o, o, i, o, o, o, o, o, l]),
116        (2, "√iSWAP") => mat(4, &[l, o, o, o, o, sr, si, o, o, si, sr, o, o, o, o, l]),
117        (2, "ECR") => mat(4, &[o, o, sr, si, o, o, si, sr, sr, -si, o, o, -si, sr, o, o]),
118        (3, "Toff") => {
119            let mut m = CMat::<f64>::identity(8);
120            m.set(6, 6, o);
121            m.set(7, 7, o);
122            m.set(6, 7, l);
123            m.set(7, 6, l);
124            m
125        }
126        _ => {
127            return Err(Error::Config(format!(
128                "gate \"{name}\" is not available for {n} qubits"
129            )));
130        }
131    };
132    Ok(g)
133}
134
135/// `Π_q exp(∓i·β_q·Op_q)` over the qubits in order, with `Op` the spin operator for each axis and the sign `−`
136/// for `x`, `y`, `z` and `+` for `-x`, `-y`, `-z`.  `beta` is in radians.
137pub fn rotation(axes: &[String], beta: &[f64], n: usize) -> Result<CMat<f64>> {
138    let ops = spin_ops(n);
139    let mut u = CMat::<f64>::identity(1 << n);
140    for (q, (axis, &b)) in axes.iter().zip(beta).enumerate() {
141        let (k, sign) = match axis.as_str() {
142            "x" => (0, -1.0),
143            "-x" => (0, 1.0),
144            "y" => (1, -1.0),
145            "-y" => (1, 1.0),
146            "z" => (2, -1.0),
147            "-z" => (2, 1.0),
148            _ => return Err(Error::Config(format!("unknown rotation axis \"{axis}\""))),
149        };
150        let uq = expm(&ops[q][k].scale(c(0.0, sign * b)))?;
151        u = u.matmul(&uq)?;
152    }
153    Ok(u)
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159
160    fn strs(v: &[&str]) -> Vec<String> {
161        v.iter().map(|s| s.to_string()).collect()
162    }
163
164    #[test]
165    fn axis_states_are_eigenstates_of_the_paulis() {
166        let p = paulis();
167        for (axis, k, eig) in [
168            ("Z", 2, 1.0),
169            ("-Z", 2, -1.0),
170            ("X", 0, 1.0),
171            ("-X", 0, -1.0),
172            ("Y", 1, 1.0),
173            ("-Y", 1, -1.0),
174        ] {
175            let psi = product_state(&strs(&[axis])).unwrap();
176            let got = p[k].matmul(&psi).unwrap();
177            assert!(got.max_abs_diff(&psi.scale_re(eig)) < 1e-15, "{axis}");
178        }
179    }
180
181    #[test]
182    fn densities_are_pure_with_unit_trace() {
183        let rho = product_density(&strs(&["X", "-Y"])).unwrap();
184        assert!((rho.trace() - c(1.0, 0.0)).norm() < 1e-15);
185        let rho2 = rho.matmul(&rho).unwrap();
186        assert!((rho2.trace() - c(1.0, 0.0)).norm() < 1e-15);
187        assert!(rho.is_hermitian(1e-15));
188    }
189
190    #[test]
191    fn gates_are_unitary() {
192        for n in 1..=3 {
193            for name in gate_names(n) {
194                let g = gate(name, n).unwrap();
195                let gg = g.matmul(&g.adjoint()).unwrap();
196                assert!(gg.max_abs_diff(&CMat::identity(g.rows)) < 1e-15, "{name}");
197            }
198        }
199        assert!(gate("CNOT", 1).is_err());
200        assert!(gate("Toff", 4).is_err());
201    }
202
203    #[test]
204    fn cnot_flips_the_second_qubit_when_the_first_is_one() {
205        let g = gate("CNOT", 2).unwrap();
206        let psi = product_state(&strs(&["-Z", "Z"])).unwrap(); // |10>
207        let out = g.matmul(&psi).unwrap();
208        let want = product_state(&strs(&["-Z", "-Z"])).unwrap(); // |11>
209        assert!(out.max_abs_diff(&want) < 1e-15);
210    }
211
212    #[test]
213    fn a_180_degree_x_rotation_inverts_z() {
214        let u = rotation(&strs(&["x"]), &[std::f64::consts::PI], 1).unwrap();
215        let psi = product_state(&strs(&["Z"])).unwrap();
216        let out = u.matmul(&psi).unwrap();
217        // |0> -> -i|1>
218        assert!((out.get(1, 0).norm() - 1.0).abs() < 1e-14);
219        assert!(out.get(0, 0).norm() < 1e-14);
220    }
221
222    #[test]
223    fn spin_ops_have_the_half_factor_and_qubit_zero_is_most_significant() {
224        let ops = spin_ops(2);
225        // Z on qubit 0 = diag(1, 1, -1, -1)/2.
226        let z0 = &ops[0][2];
227        assert_eq!(z0.get(0, 0), c(0.5, 0.0));
228        assert_eq!(z0.get(1, 1), c(0.5, 0.0));
229        assert_eq!(z0.get(2, 2), c(-0.5, 0.0));
230    }
231}