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 unitary for gate `name` on `n` qubits.
90pub fn gate(name: &str, n: usize) -> Result<CMat<f64>> {
91    let (o, l, i) = (c(0.0, 0.0), c(1.0, 0.0), c(0.0, 1.0));
92    let s = FRAC_1_SQRT_2;
93    let (sr, si) = (c(s, 0.0), c(0.0, s));
94    let g = match (n, name) {
95        (1, "X") => mat(2, &[o, l, l, o]),
96        (1, "Y") => mat(2, &[o, -i, i, o]),
97        (1, "Z") => mat(2, &[l, o, o, -l]),
98        (1, "H") => mat(2, &[sr, sr, sr, -sr]),
99        (1, "S") => mat(2, &[l, o, o, i]),
100        (1, "T") => mat(2, &[l, o, o, C::from_polar(1.0, std::f64::consts::FRAC_PI_4)]),
101        (2, "CNOT" | "CX") => mat(4, &[l, o, o, o, o, l, o, o, o, o, o, l, o, o, l, o]),
102        (2, "CZ") => mat(4, &[l, o, o, o, o, l, o, o, o, o, l, o, o, o, o, -l]),
103        (2, "SWAP") => mat(4, &[l, o, o, o, o, o, l, o, o, l, o, o, o, o, o, l]),
104        (2, "iSWAP") => mat(4, &[l, o, o, o, o, o, i, o, o, i, o, o, o, o, o, l]),
105        (2, "√iSWAP") => mat(4, &[l, o, o, o, o, sr, si, o, o, si, sr, o, o, o, o, l]),
106        (2, "ECR") => mat(4, &[o, o, sr, si, o, o, si, sr, sr, -si, o, o, -si, sr, o, o]),
107        (3, "Toff") => {
108            let mut m = CMat::<f64>::identity(8);
109            m.set(6, 6, o);
110            m.set(7, 7, o);
111            m.set(6, 7, l);
112            m.set(7, 6, l);
113            m
114        }
115        _ => {
116            return Err(Error::Config(format!(
117                "gate \"{name}\" is not available for {n} qubits"
118            )));
119        }
120    };
121    Ok(g)
122}
123
124/// `Π_q exp(∓i·β_q·Op_q)` over the qubits in order, with `Op` the spin operator for each axis and the sign `−`
125/// for `x`, `y`, `z` and `+` for `-x`, `-y`, `-z`.  `beta` is in radians.
126pub fn rotation(axes: &[String], beta: &[f64], n: usize) -> Result<CMat<f64>> {
127    let ops = spin_ops(n);
128    let mut u = CMat::<f64>::identity(1 << n);
129    for (q, (axis, &b)) in axes.iter().zip(beta).enumerate() {
130        let (k, sign) = match axis.as_str() {
131            "x" => (0, -1.0),
132            "-x" => (0, 1.0),
133            "y" => (1, -1.0),
134            "-y" => (1, 1.0),
135            "z" => (2, -1.0),
136            "-z" => (2, 1.0),
137            _ => return Err(Error::Config(format!("unknown rotation axis \"{axis}\""))),
138        };
139        let uq = expm(&ops[q][k].scale(c(0.0, sign * b)))?;
140        u = u.matmul(&uq)?;
141    }
142    Ok(u)
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148
149    fn strs(v: &[&str]) -> Vec<String> {
150        v.iter().map(|s| s.to_string()).collect()
151    }
152
153    #[test]
154    fn axis_states_are_eigenstates_of_the_paulis() {
155        let p = paulis();
156        for (axis, k, eig) in [
157            ("Z", 2, 1.0),
158            ("-Z", 2, -1.0),
159            ("X", 0, 1.0),
160            ("-X", 0, -1.0),
161            ("Y", 1, 1.0),
162            ("-Y", 1, -1.0),
163        ] {
164            let psi = product_state(&strs(&[axis])).unwrap();
165            let got = p[k].matmul(&psi).unwrap();
166            assert!(got.max_abs_diff(&psi.scale_re(eig)) < 1e-15, "{axis}");
167        }
168    }
169
170    #[test]
171    fn densities_are_pure_with_unit_trace() {
172        let rho = product_density(&strs(&["X", "-Y"])).unwrap();
173        assert!((rho.trace() - c(1.0, 0.0)).norm() < 1e-15);
174        let rho2 = rho.matmul(&rho).unwrap();
175        assert!((rho2.trace() - c(1.0, 0.0)).norm() < 1e-15);
176        assert!(rho.is_hermitian(1e-15));
177    }
178
179    #[test]
180    fn gates_are_unitary() {
181        for n in 1..=3 {
182            for name in gate_names(n) {
183                let g = gate(name, n).unwrap();
184                let gg = g.matmul(&g.adjoint()).unwrap();
185                assert!(gg.max_abs_diff(&CMat::identity(g.rows)) < 1e-15, "{name}");
186            }
187        }
188        assert!(gate("CNOT", 1).is_err());
189        assert!(gate("Toff", 4).is_err());
190    }
191
192    #[test]
193    fn cnot_flips_the_second_qubit_when_the_first_is_one() {
194        let g = gate("CNOT", 2).unwrap();
195        let psi = product_state(&strs(&["-Z", "Z"])).unwrap(); // |10>
196        let out = g.matmul(&psi).unwrap();
197        let want = product_state(&strs(&["-Z", "-Z"])).unwrap(); // |11>
198        assert!(out.max_abs_diff(&want) < 1e-15);
199    }
200
201    #[test]
202    fn a_180_degree_x_rotation_inverts_z() {
203        let u = rotation(&strs(&["x"]), &[std::f64::consts::PI], 1).unwrap();
204        let psi = product_state(&strs(&["Z"])).unwrap();
205        let out = u.matmul(&psi).unwrap();
206        // |0> -> -i|1>
207        assert!((out.get(1, 0).norm() - 1.0).abs() < 1e-14);
208        assert!(out.get(0, 0).norm() < 1e-14);
209    }
210
211    #[test]
212    fn spin_ops_have_the_half_factor_and_qubit_zero_is_most_significant() {
213        let ops = spin_ops(2);
214        // Z on qubit 0 = diag(1, 1, -1, -1)/2.
215        let z0 = &ops[0][2];
216        assert_eq!(z0.get(0, 0), c(0.5, 0.0));
217        assert_eq!(z0.get(1, 1), c(0.5, 0.0));
218        assert_eq!(z0.get(2, 2), c(-0.5, 0.0));
219    }
220}