Skip to main content

ctrl_freeq/autodiff/
ops_complex.rs

1//! Operations on complex matrices - the propagation's building blocks - and their adjoints.
2//!
3//! Adjoints use the conjugate convention of the tape: for `W = A·B`, `∂L/∂A = G·Bᴴ` and `∂L/∂B = Aᴴ·G`.
4
5use super::tape::{Op, Tape, Value, Var, liftc, mulc};
6use super::{C, Scalar};
7use crate::error::{Error, Result};
8use crate::linalg::{CMat, RMat, expm, expm_frechet_adjoint, expm_mi_dt};
9
10/// Which part of a time step a dissipation channel covers.
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum Step {
13    /// `exp(dt·D)`, between two unitary steps.
14    Full,
15    /// `exp(dt·D/2)`, at either end of the pulse.
16    Half,
17}
18
19/// The dissipative half of a Lindblad time step: the channel `exp(dt·D)`, with
20/// `D[ρ] = Σ_k (L_k ρ L_k† − ½{L_k†L_k, ρ})` for the collapse operators `L_k`, and its half-step counterpart.
21///
22/// Both channels are exact, so every step is completely positive and trace preserving: states stay physical and
23/// fidelities at most 1 however long the step is compared with T1 and T2.  Half a channel at each end of the pulse
24/// with whole ones between the unitary steps is Strang splitting, second order in `dt`.
25#[derive(Clone, Debug, PartialEq)]
26pub struct LindbladOps {
27    dim: usize,
28    /// The non-zero entries `(to, from, value)` of `exp(dt·D)` acting on the row-major `vec(ρ)`.
29    channel: Vec<(usize, usize, C<f64>)>,
30    /// The same for `exp(dt·D/2)`.
31    half_channel: Vec<(usize, usize, C<f64>)>,
32}
33
34impl LindbladOps {
35    /// The channel for `collapse`, square operators of one dimension, over a step `dt`.
36    ///
37    /// Time runs forwards: a negative step is not a channel and would take populations below zero.
38    pub fn new(collapse: &[CMat<f64>], dt: f64) -> Result<Self> {
39        if !(dt >= 0.0 && dt.is_finite()) {
40            return Err(Error::Config(format!(
41                "a Lindblad step of {dt} seconds; it must be zero or more"
42            )));
43        }
44        let dim = collapse
45            .first()
46            .ok_or_else(|| Error::Config("Lindblad evolution needs at least one collapse operator".into()))?
47            .rows;
48        if collapse.iter().any(|l| l.shape() != (dim, dim)) {
49            return Err(Error::Dimension(
50                "collapse operators must be square and of one size".into(),
51            ));
52        }
53        // The generator column by column: column i·dim + j is vec(D[|i⟩⟨j|]).
54        let n = dim * dim;
55        let mut generator = CMat::<f64>::zeros(n, n);
56        for from in 0..n {
57            let mut e = CMat::<f64>::zeros(dim, dim);
58            e.data[from] = C::new(dt, 0.0);
59            for (to, v) in dissipator(collapse, &e)?.data.into_iter().enumerate() {
60                generator.set(to, from, v);
61            }
62        }
63        let entries = |map: CMat<f64>| -> Vec<(usize, usize, C<f64>)> {
64            (0..n)
65                .flat_map(|to| (0..n).map(move |from| (to, from)))
66                .map(|(to, from)| (to, from, map.get(to, from)))
67                .filter(|&(_, _, v)| v != C::new(0.0, 0.0))
68                .collect()
69        };
70        Ok(LindbladOps {
71            dim,
72            channel: entries(expm(&generator)?),
73            half_channel: entries(expm(&generator.scale_re(0.5))?),
74        })
75    }
76
77    /// The channel for `step` applied to `rho`, or its adjoint (the Heisenberg-picture map) when `adjoint` is set.
78    pub fn apply<T: Scalar>(&self, rho: &CMat<T>, step: Step, adjoint: bool) -> Result<CMat<T>> {
79        if rho.shape() != (self.dim, self.dim) {
80            return Err(Error::Dimension(format!(
81                "a {}x{} density matrix for {}-level collapse operators",
82                rho.rows, rho.cols, self.dim
83            )));
84        }
85        let mut out = CMat::<T>::zeros(self.dim, self.dim);
86        let channel = match step {
87            Step::Full => &self.channel,
88            Step::Half => &self.half_channel,
89        };
90        for &(to, from, v) in channel {
91            if adjoint {
92                out.data[from] += mulc(v.conj(), rho.data[to]);
93            } else {
94                out.data[to] += mulc(v, rho.data[from]);
95            }
96        }
97        Ok(out)
98    }
99}
100
101/// `D[ρ] = Σ_k (L ρ L† − ½{L†L, ρ})`.
102fn dissipator(collapse: &[CMat<f64>], rho: &CMat<f64>) -> Result<CMat<f64>> {
103    let mut out = CMat::<f64>::zeros(rho.rows, rho.cols);
104    for l in collapse {
105        let l_dag = l.adjoint();
106        let l_dag_l = l_dag.matmul(l)?;
107        out = out.add(&l.matmul(rho)?.matmul(&l_dag)?)?;
108        out.axpy_re(-0.5, &l_dag_l.matmul(rho)?.add(&rho.matmul(&l_dag_l)?)?);
109    }
110    Ok(out)
111}
112
113impl<'a, T: Scalar> Tape<'a, T> {
114    /// `re + i·im`.
115    pub fn complex(&mut self, re: Var, im: Var) -> Result<Var> {
116        let (a, b) = (self.value(re).r("complex")?, self.value(im).r("complex")?);
117        if a.shape() != b.shape() {
118            return Err(Error::Dimension(
119                "complex: real and imaginary parts differ in shape".into(),
120            ));
121        }
122        let out = CMat {
123            rows: a.rows,
124            cols: a.cols,
125            data: a.data.iter().zip(&b.data).map(|(&x, &y)| C::new(x, y)).collect(),
126        };
127        Ok(self.push(Value::C(out), Op::Complex(re, im), &[re, im]))
128    }
129
130    /// The real part.
131    pub fn real(&mut self, z: Var) -> Result<Var> {
132        let out = self.value(z).c("real")?.map(|v| v.re);
133        Ok(self.push(Value::R(out), Op::Real(z), &[z]))
134    }
135
136    /// The imaginary part.
137    pub fn imag(&mut self, z: Var) -> Result<Var> {
138        let out = self.value(z).c("imag")?.map(|v| v.im);
139        Ok(self.push(Value::R(out), Op::Imag(z), &[z]))
140    }
141
142    /// Elementwise `z · c` for a constant `c` of the same shape.
143    pub fn mul_const_c(&mut self, z: Var, c: &'a CMat<f64>) -> Result<Var> {
144        let x = self.value(z).c("mul_const_c")?;
145        if x.shape() != c.shape() {
146            return Err(Error::Dimension("mul_const_c: shapes differ".into()));
147        }
148        let out = CMat {
149            rows: x.rows,
150            cols: x.cols,
151            data: x.data.iter().zip(&c.data).map(|(&v, &k)| mulc(k, v)).collect(),
152        };
153        Ok(self.push(Value::C(out), Op::MulConstC(z, c), &[z]))
154    }
155
156    /// `H = H₀ + Σ_k u[row, k]·ops[k]` for a real `u` and constant `H₀`, `ops`.
157    pub fn lincomb_row(&mut self, h0: &CMat<f64>, u: Var, row: usize, ops: &'a [CMat<f64>]) -> Result<Var> {
158        let um = self.value(u).r("lincomb_row")?;
159        if um.cols != ops.len() || row >= um.rows {
160            return Err(Error::Dimension(format!(
161                "lincomb_row: row {row} of a {}x{} control matrix with {} operators",
162                um.rows,
163                um.cols,
164                ops.len()
165            )));
166        }
167        let mut h = CMat::<T>::lift(h0);
168        for (k, op) in ops.iter().enumerate() {
169            if op.shape() != h.shape() {
170                return Err(Error::Dimension("lincomb_row: operator shape differs from H0".into()));
171            }
172            let coeff = um.get(row, k);
173            for (d, &o) in h.data.iter_mut().zip(&op.data) {
174                d.re += coeff * T::from_f64(o.re);
175                d.im += coeff * T::from_f64(o.im);
176            }
177        }
178        Ok(self.push(Value::C(h), Op::LincombRow(u, row, ops), &[u]))
179    }
180
181    /// `U = exp(−i·dt·H)`.
182    pub fn expm_mi_dt(&mut self, h: Var, dt: f64) -> Result<Var> {
183        let out = expm_mi_dt(self.value(h).c("expm_mi_dt")?, T::from_f64(dt))?;
184        Ok(self.push(Value::C(out), Op::ExpmMiDt(h, dt), &[h]))
185    }
186
187    /// Complex matrix product `a·b` (a matrix-vector product when `b` is a column).
188    pub fn matmul(&mut self, a: Var, b: Var) -> Result<Var> {
189        let out = self.value(a).c("matmul")?.matmul(self.value(b).c("matmul")?)?;
190        Ok(self.push(Value::C(out), Op::Matmul(a, b), &[a, b]))
191    }
192
193    /// `U·ρ·U†`.
194    pub fn sandwich(&mut self, u: Var, rho: Var) -> Result<Var> {
195        let um = self.value(u).c("sandwich")?;
196        let out = um.matmul(self.value(rho).c("sandwich")?)?.matmul(&um.adjoint())?;
197        Ok(self.push(Value::C(out), Op::Sandwich(u, rho), &[u, rho]))
198    }
199
200    /// A whole or half dissipation step, `exp(dt·D)[ρ]` or `exp(dt·D/2)[ρ]`.
201    pub fn lindblad_step(&mut self, rho: Var, ops: &'a LindbladOps, step: Step) -> Result<Var> {
202        let out = ops.apply(self.value(rho).c("lindblad_step")?, step, false)?;
203        Ok(self.push(Value::C(out), Op::Lindblad(rho, ops, step), &[rho]))
204    }
205
206    /// The fidelity of the evolved columns `Ψ` to the target columns `T`, as a `1 × 1` real.
207    ///
208    /// With `k` columns - the images of `k` orthonormal states - it is the average fidelity over their span,
209    /// `(‖M‖² + |Tr M|²)/(k·(k + 1))` with `M = T†·Ψ`, which counts population leaving the span as lost.  One column
210    /// gives `|⟨t|ψ⟩|²`.
211    pub fn fidelity(&mut self, target: &'a CMat<f64>, psi: Var) -> Result<Var> {
212        let p = self.value(psi).c("fidelity")?;
213        if p.shape() != target.shape() {
214            return Err(Error::Dimension("fidelity: state and target differ in shape".into()));
215        }
216        let m = adjoint_times(target, p);
217        let k = T::from_f64(target.cols as f64);
218        let norm: T = m.data.iter().fold(T::zero(), |acc, z| acc + z.re * z.re + z.im * z.im);
219        let s = m.trace();
220        let out = RMat::from_vec(1, 1, vec![(norm + s.re * s.re + s.im * s.im) / (k * (k + T::one()))])?;
221        Ok(self.push(Value::R(out), Op::Fidelity(target, psi), &[psi]))
222    }
223
224    /// `Re Tr(ρ·σ)`, as a `1 × 1` real.
225    pub fn re_trace_product(&mut self, sigma: &'a CMat<f64>, rho: Var) -> Result<Var> {
226        let r = self.value(rho).c("re_trace_product")?;
227        if r.shape() != sigma.shape() || !r.is_square() {
228            return Err(Error::Dimension("re_trace_product: shapes differ".into()));
229        }
230        let n = r.rows;
231        let mut acc = T::zero();
232        for i in 0..n {
233            for j in 0..n {
234                acc += mulc(sigma.get(j, i), r.get(i, j)).re;
235            }
236        }
237        let out = RMat::from_vec(1, 1, vec![acc])?;
238        Ok(self.push(Value::R(out), Op::ReTraceProduct(sigma, rho), &[rho]))
239    }
240}
241
242/// `t†·p` for a constant `t`.
243fn adjoint_times<T: Scalar>(t: &CMat<f64>, p: &CMat<T>) -> CMat<T> {
244    let mut out = CMat::<T>::zeros(t.cols, p.cols);
245    for r in 0..t.rows {
246        for i in 0..t.cols {
247            let a = t.get(r, i).conj();
248            for j in 0..p.cols {
249                out.data[i * p.cols + j] += mulc(a, p.get(r, j));
250            }
251        }
252    }
253    out
254}
255
256// ------------------------------------------------------------------ adjoints ----
257
258pub(crate) fn complex_adjoint<T: Scalar>(re: Var, im: Var, g: &Value<T>) -> Result<Vec<(Var, Value<T>)>> {
259    let g = g.c("complex")?;
260    Ok(vec![(re, Value::R(g.map(|z| z.re))), (im, Value::R(g.map(|z| z.im)))])
261}
262
263/// Adjoint of taking the real (`imag == false`) or imaginary part.
264pub(crate) fn real_adjoint<T: Scalar>(g: &Value<T>, imag: bool) -> Result<Value<T>> {
265    let g = g.r("real/imag")?;
266    Ok(Value::C(g.map(|v| {
267        if imag {
268            C::new(T::zero(), v)
269        } else {
270            C::new(v, T::zero())
271        }
272    })))
273}
274
275pub(crate) fn mul_const_c_adjoint<T: Scalar>(c: &CMat<f64>, g: &Value<T>) -> Result<Value<T>> {
276    let g = g.c("mul_const_c")?;
277    Ok(Value::C(CMat {
278        rows: g.rows,
279        cols: g.cols,
280        data: g.data.iter().zip(&c.data).map(|(&v, &k)| mulc(k.conj(), v)).collect(),
281    }))
282}
283
284pub(crate) fn lincomb_row_adjoint<T: Scalar>(
285    u: &Value<T>,
286    row: usize,
287    ops: &[CMat<f64>],
288    g: &Value<T>,
289) -> Result<Value<T>> {
290    let (rows, cols) = u.shape();
291    let g = g.c("lincomb_row")?;
292    let mut out = RMat::<T>::zeros(rows, cols);
293    for (k, op) in ops.iter().enumerate() {
294        // Re⟨op, G⟩ = Σ Re(conj(op)·G)
295        let mut acc = T::zero();
296        for (&o, &gv) in op.data.iter().zip(&g.data) {
297            acc += T::from_f64(o.re) * gv.re + T::from_f64(o.im) * gv.im;
298        }
299        out.set(row, k, acc);
300    }
301    Ok(Value::R(out))
302}
303
304pub(crate) fn expm_mi_dt_adjoint<T: Scalar>(h: &Value<T>, dt: f64, g: &Value<T>) -> Result<Value<T>> {
305    let h = h.c("expm_mi_dt")?;
306    let a = h.scale(C::new(T::zero(), T::from_f64(-dt)));
307    let ga = expm_frechet_adjoint(&a, g.c("expm_mi_dt")?)?;
308    // A = −i·dt·H, so ∂L/∂H = conj(−i·dt)·∂L/∂A = i·dt·∂L/∂A.
309    Ok(Value::C(ga.scale(C::new(T::zero(), T::from_f64(dt)))))
310}
311
312pub(crate) fn matmul_adjoint<T: Scalar>(
313    a: Var,
314    b: Var,
315    va: &Value<T>,
316    vb: &Value<T>,
317    g: &Value<T>,
318) -> Result<Vec<(Var, Value<T>)>> {
319    let (x, y, g) = (va.c("matmul")?, vb.c("matmul")?, g.c("matmul")?);
320    Ok(vec![
321        (a, Value::C(g.matmul(&y.adjoint())?)),
322        (b, Value::C(x.adjoint().matmul(g)?)),
323    ])
324}
325
326pub(crate) fn sandwich_adjoint<T: Scalar>(
327    u: Var,
328    rho: Var,
329    vu: &Value<T>,
330    vr: &Value<T>,
331    g: &Value<T>,
332) -> Result<Vec<(Var, Value<T>)>> {
333    let (um, r, g) = (vu.c("sandwich")?, vr.c("sandwich")?, g.c("sandwich")?);
334    // W = U ρ U†:  ∂L/∂ρ = U† G U,   ∂L/∂U = G U ρᴴ + Gᴴ U ρ.
335    let grad_rho = um.adjoint().matmul(g)?.matmul(um)?;
336    let grad_u = g
337        .matmul(um)?
338        .matmul(&r.adjoint())?
339        .add(&g.adjoint().matmul(um)?.matmul(r)?)?;
340    Ok(vec![(u, Value::C(grad_u)), (rho, Value::C(grad_rho))])
341}
342
343pub(crate) fn lindblad_adjoint<T: Scalar>(ops: &LindbladOps, step: Step, g: &Value<T>) -> Result<Value<T>> {
344    Ok(Value::C(ops.apply(g.c("lindblad_step")?, step, true)?))
345}
346
347pub(crate) fn fidelity_adjoint<T: Scalar>(t: &CMat<f64>, psi: &Value<T>, g: &Value<T>) -> Result<Value<T>> {
348    let m = adjoint_times(t, psi.c("fidelity")?);
349    let s = m.trace();
350    let k = t.cols as f64;
351    let scale = g.r("fidelity")?.data[0] * T::from_f64(2.0 / (k * (k + 1.0)));
352    // In the conjugate convention ∂‖T†Ψ‖²/∂Ψ = 2·T·M and ∂|Tr T†Ψ|²/∂Ψ = 2·s·T.
353    let mut out = CMat::<T>::zeros(t.rows, t.cols);
354    for r in 0..t.rows {
355        for c in 0..t.cols {
356            let mut acc = s * liftc(t.get(r, c));
357            for i in 0..t.cols {
358                acc += mulc(t.get(r, i), m.get(i, c));
359            }
360            out.data[r * t.cols + c] = C::new(acc.re * scale, acc.im * scale);
361        }
362    }
363    Ok(Value::C(out))
364}
365
366pub(crate) fn re_trace_product_adjoint<T: Scalar>(sigma: &CMat<f64>, g: &Value<T>) -> Result<Value<T>> {
367    let s = g.r("re_trace_product")?.data[0];
368    // ∂ Re Tr(ρσ) / ∂ρ = σᴴ.
369    Ok(Value::C(CMat::<T>::lift(&sigma.adjoint()).scale_re(s)))
370}