Skip to main content

caroli_walk/
walk.rs

1//! The walk operator `U = V(J) M C` and its application on the CPU, in f64 or f32.
2
3use crate::graph::Graph;
4use caroli_model::{CMat, SparseMatrix, c64};
5use num_complex::Complex;
6use num_traits::Float;
7use rayon::prelude::*;
8
9/// Spin configurations per parallel task.
10#[cfg(not(test))]
11const CHUNK: usize = 1 << 14;
12/// Small pieces in the tests, so that their small walks go through every way of cutting the rows
13/// (several pieces per row, edge spins above the piece).
14#[cfg(test)]
15const CHUNK: usize = 1 << 2;
16
17/// The real type of a state on the CPU: `f64`, or `f32` for half the memory traffic and twice
18/// the SIMD width, at about 10⁻⁷ of relative error per step (see [`crate::gpu`] for checked
19/// runs in reduced precision).
20pub trait Real: Float + Send + Sync + std::fmt::Debug + 'static {
21    /// `x` in this type: rounded to `f32`, unchanged for `f64`.
22    fn of(x: f64) -> Self;
23    /// The value in `f64` (exact).
24    fn wide(self) -> f64;
25}
26
27impl Real for f64 {
28    fn of(x: f64) -> Self {
29        x
30    }
31    fn wide(self) -> f64 {
32        self
33    }
34}
35
36impl Real for f32 {
37    fn of(x: f64) -> Self {
38        x as f32
39    }
40    fn wide(self) -> f64 {
41        self as f64
42    }
43}
44
45fn narrow<T: Real>(z: c64) -> Complex<T> {
46    Complex::new(T::of(z.re), T::of(z.im))
47}
48
49/// A state converted to f32.
50pub fn to_single(psi: &[c64]) -> Vec<Complex<f32>> {
51    psi.par_iter().map(|&z| narrow(z)).collect()
52}
53
54/// A state converted to f64.
55pub fn to_double(psi: &[Complex<f32>]) -> Vec<c64> {
56    psi.par_iter().map(|z| c64::new(z.re as f64, z.im as f64)).collect()
57}
58
59/// The rows of every node of `graph`, in order: `(x, ψ[offsets[x] L .. offsets[x + 1] L])` for
60/// rows of `l` configurations. The half-edges of a node are consecutive
61/// ([`Graph::half_edges_of`]), so each node owns one block of the state.
62fn node_blocks<'a, T>(
63    graph: &'a Graph,
64    l: usize,
65    psi: &'a mut [Complex<T>],
66) -> impl Iterator<Item = (usize, &'a mut [Complex<T>])> {
67    let mut rest = psi;
68    (0..graph.nodes()).map(move |x| {
69        let (block, tail) = std::mem::take(&mut rest).split_at_mut(graph.degree(x) * l);
70        rest = tail;
71        (x, block)
72    })
73}
74
75/// Rows `i` and `j` (`i ≠ j`) of `l` entries of the state, borrowed together.
76fn two_rows<T>(psi: &mut [T], l: usize, i: usize, j: usize) -> (&mut [T], &mut [T]) {
77    debug_assert_ne!(i, j, "two distinct rows");
78    if i < j {
79        let (low, high) = psi.split_at_mut(j * l);
80        (&mut low[i * l..(i + 1) * l], &mut high[..l])
81    } else {
82        let (low, high) = psi.split_at_mut(i * l);
83        (&mut high[..l], &mut low[j * l..(j + 1) * l])
84    }
85}
86
87/// Runs `f` on the successive pieces of `size` entries of `row`, in parallel or on the calling
88/// thread.
89fn each_piece<T: Send>(row: &mut [T], size: usize, parallel: bool, f: impl Fn(&mut [T]) + Sync + Send) {
90    if parallel {
91        row.par_chunks_mut(size).for_each(f);
92    } else {
93        row.chunks_mut(size).for_each(f);
94    }
95}
96
97/// Runs `f` on the matching pieces of `size` entries of `a` and `b`, in parallel or on the
98/// calling thread.
99fn each_pair<T: Send>(
100    a: &mut [T],
101    b: &mut [T],
102    size: usize,
103    parallel: bool,
104    f: impl Fn(&mut [T], &mut [T]) + Sync + Send,
105) {
106    if parallel {
107        a.par_chunks_mut(size).zip(b.par_chunks_mut(size)).for_each(|(a, b)| f(a, b));
108    } else {
109        a.chunks_mut(size).zip(b.chunks_mut(size)).for_each(|(a, b)| f(a, b));
110    }
111}
112
113/// `(p, α, β)` of the edge update, in the precision of the state.
114type Exchange<T> = (Complex<T>, Complex<T>, Complex<T>);
115
116/// The edge update on runs of quadruples: `a0, a1` (half-edge `a`, edge spin up and down),
117/// `b0, b1` (half-edge `b`); `(p, α, β)` from [`SpinWalk::exchange`]. With `ACC`, returns the
118/// probabilities `Σ |a'|²`, `Σ |b'|²` of the updated entries.
119#[inline]
120fn exchange_run<T: Real, const ACC: bool>(
121    a0: &mut [Complex<T>],
122    a1: &mut [Complex<T>],
123    b0: &mut [Complex<T>],
124    b1: &mut [Complex<T>],
125    (p, alpha, beta): Exchange<T>,
126) -> (f64, f64) {
127    let (mut sa, mut sb) = (T::zero(), T::zero());
128    for (((x0, x1), y0), y1) in a0.iter_mut().zip(a1.iter_mut()).zip(b0.iter_mut()).zip(b1.iter_mut()) {
129        let (u0, u1, v0, v1) = (*x0, *x1, *y0, *y1);
130        *x0 = p * v0;
131        *x1 = alpha * v1 + beta * u0;
132        *y0 = beta * v1 + alpha * u0;
133        *y1 = p * u1;
134        if ACC {
135            sa = sa + x0.norm_sqr() + x1.norm_sqr();
136            sb = sb + y0.norm_sqr() + y1.norm_sqr();
137        }
138    }
139    (sa.wide(), sb.wide())
140}
141
142/// The edge update for a low spin bit `B`: the rows `a`, `b` in blocks of `2B` configurations,
143/// the first `B` with the spin up.
144#[inline]
145fn edge_blocks<T: Real, const B: usize, const ACC: bool>(
146    a: &mut [Complex<T>],
147    b: &mut [Complex<T>],
148    (p, alpha, beta): Exchange<T>,
149) -> (f64, f64) {
150    let (mut sa, mut sb) = (T::zero(), T::zero());
151    for (a, b) in a.chunks_exact_mut(2 * B).zip(b.chunks_exact_mut(2 * B)) {
152        for i in 0..B {
153            let (u0, u1, v0, v1) = (a[i], a[i + B], b[i], b[i + B]);
154            a[i] = p * v0;
155            a[i + B] = alpha * v1 + beta * u0;
156            b[i] = beta * v1 + alpha * u0;
157            b[i + B] = p * u1;
158            if ACC {
159                sa = sa + a[i].norm_sqr() + a[i + B].norm_sqr();
160                sb = sb + b[i].norm_sqr() + b[i + B].norm_sqr();
161            }
162        }
163    }
164    (sa.wide(), sb.wide())
165}
166
167/// The edge update when the edge spin is a low bit (`2 bit` fits in a piece): `a`, `b` hold
168/// whole blocks of `2 bit` configurations of the two rows, the first `bit` with the spin up.
169#[inline]
170fn edge_span<T: Real, const ACC: bool>(
171    bit: usize,
172    a: &mut [Complex<T>],
173    b: &mut [Complex<T>],
174    k: Exchange<T>,
175) -> (f64, f64) {
176    match bit {
177        1 => edge_blocks::<T, 1, ACC>(a, b, k),
178        2 => edge_blocks::<T, 2, ACC>(a, b, k),
179        4 => edge_blocks::<T, 4, ACC>(a, b, k),
180        _ => {
181            let (mut sa, mut sb) = (0.0, 0.0);
182            for (a, b) in a.chunks_exact_mut(2 * bit).zip(b.chunks_exact_mut(2 * bit)) {
183                let ((a0, a1), (b0, b1)) = (a.split_at_mut(bit), b.split_at_mut(bit));
184                let (x, y) = exchange_run::<T, ACC>(a0, a1, b0, b1, k);
185                sa += x;
186                sb += y;
187            }
188            (sa, sb)
189        }
190    }
191}
192
193/// Coin `R(θ) = [[cos θ, −sin θ], [sin θ, cos θ]]` on the two colors of a node.
194///
195/// The motion leaves the walker on the edge it came along, so on a ring the coin angle `θ` sets
196/// what it does next: it turns back with amplitude `cos θ` and goes on with amplitude `sin θ`.
197/// At `θ = 0` the walker bounces on one edge forever, at `θ = π/2` it runs around the ring.
198pub fn rotation(theta: f64) -> CMat {
199    let (s, c) = theta.sin_cos();
200    CMat::from_fn(2, 2, |i, j| c64::new([[c, -s], [s, c]][i][j], 0.0))
201}
202
203/// Grover coin `2/d 𝟙 − I` (`𝟙` the matrix of ones).
204pub fn grover(d: usize) -> CMat {
205    CMat::from_fn(d, d, |i, j| c64::new(2.0 / d as f64 - if i == j { 1.0 } else { 0.0 }, 0.0))
206}
207
208/// Fourier coin `e^{2iπ jk/d} / √d`.
209pub fn fourier(d: usize) -> CMat {
210    let norm = 1.0 / (d as f64).sqrt();
211    CMat::from_fn(d, d, |j, k| c64::from_polar(norm, 2.0 * std::f64::consts::PI * (j * k) as f64 / d as f64))
212}
213
214/// A walker on a graph coupled to one spin per edge (K. Sellapillay and A. D. Verga, Phys. Rev.
215/// E 103, 032123 (2021)). One step is `U = V(J) M C`:
216///
217/// - the coin `C` applies `coins[x]` to the colors of each node `x`;
218/// - the motion `M` swaps the two half-edges of every edge, `|x c_y s⟩ ↔ |y c_x s⟩`;
219/// - the interaction `V(J) = exp(i J τ·σ / 4)` couples, on every edge, the walker's side of the
220///   edge (`τ`) to the edge spin (`σ`): an exchange that can move the walker across the edge
221///   while flipping the spin.
222///
223/// The state is `ψ[h · 2^|E| + s]`: half-edge `h`, spin configuration `s` (bit `e` of `s` is the
224/// spin of edge `e`, 0 for up).
225#[derive(Clone, Debug)]
226pub struct SpinWalk {
227    graph: Graph,
228    coins: Vec<CMat>,
229    j: f64,
230}
231
232impl SpinWalk {
233    /// Walk with one coin per node (a `d_x × d_x` unitary) and coupling `j`.
234    pub fn new(graph: Graph, coins: Vec<CMat>, j: f64) -> Self {
235        assert_eq!(coins.len(), graph.nodes(), "one coin per node");
236        for (x, c) in coins.iter().enumerate() {
237            let d = graph.degree(x);
238            assert!(c.nrows() == d && c.ncols() == d, "node {x}: the coin must be {d} × {d}");
239        }
240        assert!(graph.edges() < usize::BITS as usize - 8, "too many spins");
241        Self { graph, coins, j }
242    }
243
244    /// The one-dimensional lattice of the paper: a ring of `n` nodes, coin `R(θ)` everywhere.
245    pub fn ring(n: usize, theta: f64, j: f64) -> Self {
246        Self::new(Graph::cycle(n), vec![rotation(theta); n], j)
247    }
248
249    /// The graph of the walk; edge `e` carries spin `e`.
250    pub fn graph(&self) -> &Graph {
251        &self.graph
252    }
253
254    /// The coin of each node `x` (`d_x × d_x`, on its colors).
255    pub fn coins(&self) -> &[CMat] {
256        &self.coins
257    }
258
259    /// Particle–spin coupling `J`.
260    pub fn coupling(&self) -> f64 {
261        self.j
262    }
263
264    /// Spin configurations per half-edge, `2^|E|`.
265    pub fn row_len(&self) -> usize {
266        1usize << self.graph.edges()
267    }
268
269    /// Dimension of the Hilbert space, `2|E| · 2^|E|`.
270    pub fn dimension(&self) -> usize {
271        self.graph.half_edges() * self.row_len()
272    }
273
274    /// The edge part `V(J) M` on the four amplitudes `(a0, a1, b0, b1)` of an edge: half-edges
275    /// `a`, `b`, edge spin 0 or 1. Returns `(p, α, β)` such that
276    /// `a0' = p b0`, `a1' = α b1 + β a0`, `b0' = β b1 + α a0`, `b1' = p a1`.
277    pub fn exchange(&self) -> (c64, c64, c64) {
278        let j = self.j;
279        let q = c64::from_polar(1.0, -j / 4.0);
280        (c64::from_polar(1.0, j / 4.0), q * (j / 2.0).cos(), q * c64::new(0.0, (j / 2.0).sin()))
281    }
282
283    /// One step `ψ ← U ψ`, on all the threads of the rayon pool (f64 or f32 state).
284    ///
285    /// # Panics
286    ///
287    /// If `psi.len()` is not [`Self::dimension`], as every method that takes a state.
288    pub fn step<T: Real>(&self, psi: &mut [Complex<T>]) {
289        self.coin(psi, true);
290        self.edges(psi, true);
291    }
292
293    /// `steps` steps.
294    pub fn steps<T: Real>(&self, psi: &mut [Complex<T>], steps: usize) {
295        for _ in 0..steps {
296            self.step(psi);
297        }
298    }
299
300    /// One step on the calling thread only: for many small walks run side by side (a scan of
301    /// parameters), each state staying in its core's cache.
302    pub fn step_serial<T: Real>(&self, psi: &mut [Complex<T>]) {
303        self.coin(psi, false);
304        self.edges(psi, false);
305    }
306
307    /// `steps` steps on the calling thread only.
308    pub fn steps_serial<T: Real>(&self, psi: &mut [Complex<T>], steps: usize) {
309        for _ in 0..steps {
310            self.step_serial(psi);
311        }
312    }
313
314    /// `ψ ← C ψ`, the coin part of a step.
315    pub fn coin_pass<T: Real>(&self, psi: &mut [Complex<T>]) {
316        self.coin(psi, true);
317    }
318
319    /// `ψ ← V(J) M ψ`, the motion and interaction part of a step.
320    pub fn edge_pass<T: Real>(&self, psi: &mut [Complex<T>]) {
321        self.edges(psi, true);
322    }
323
324    /// `ψ ← C ψ`: every node's coin on its own block of rows ([`node_blocks`]).
325    fn coin<T: Real>(&self, psi: &mut [Complex<T>], parallel: bool) {
326        assert_eq!(psi.len(), self.dimension(), "state of the wrong dimension");
327        let l = self.row_len();
328        if parallel {
329            let blocks: Vec<_> = node_blocks(&self.graph, l, psi).collect();
330            blocks.into_par_iter().for_each(|(x, block)| self.coin_node(x, block, true));
331        } else {
332            node_blocks(&self.graph, l, psi).for_each(|(x, block)| self.coin_node(x, block, false));
333        }
334    }
335
336    /// The coin of node `x` on its rows, `block` (`d_x` rows of `L` configurations), by pieces of
337    /// `CHUNK` configurations.
338    fn coin_node<T: Real>(&self, x: usize, block: &mut [Complex<T>], parallel: bool) {
339        let (l, coin) = (self.row_len(), &self.coins[x]);
340        let c = |i: usize, j: usize| narrow::<T>(coin[(i, j)]);
341        match self.graph.degree(x) {
342            0 => {}
343            1 => {
344                let c = c(0, 0);
345                each_piece(block, CHUNK, parallel, |row| row.iter_mut().for_each(|v| *v = *v * c));
346            }
347            2 => {
348                let (u, v) = block.split_at_mut(l);
349                if (0..4).all(|k| coin[(k / 2, k % 2)].im == 0.0) {
350                    // A real coin (the rotation R(θ)): half the multiplications.
351                    let (c00, c01, c10, c11) = (c(0, 0).re, c(0, 1).re, c(1, 0).re, c(1, 1).re);
352                    each_pair(u, v, CHUNK, parallel, |u, v| {
353                        for (u, v) in u.iter_mut().zip(v.iter_mut()) {
354                            let (a, b) = (*u, *v);
355                            *u = a * c00 + b * c01;
356                            *v = a * c10 + b * c11;
357                        }
358                    });
359                } else {
360                    let (c00, c01, c10, c11) = (c(0, 0), c(0, 1), c(1, 0), c(1, 1));
361                    each_pair(u, v, CHUNK, parallel, |u, v| {
362                        for (u, v) in u.iter_mut().zip(v.iter_mut()) {
363                            let (a, b) = (*u, *v);
364                            *u = c00 * a + c01 * b;
365                            *v = c10 * a + c11 * b;
366                        }
367                    });
368                }
369            }
370            d => {
371                let matrix: Vec<Complex<T>> = (0..d * d).map(|k| c(k / d, k % d)).collect();
372                // Piece k of every row: the d amplitudes of each configuration of the piece.
373                let mut pieces: Vec<Vec<&mut [Complex<T>]>> =
374                    (0..l.div_ceil(CHUNK)).map(|_| Vec::with_capacity(d)).collect();
375                for row in block.chunks_exact_mut(l) {
376                    for (piece, part) in pieces.iter_mut().zip(row.chunks_mut(CHUNK)) {
377                        piece.push(part);
378                    }
379                }
380                let apply = |mut views: Vec<&mut [Complex<T>]>| {
381                    let zero = Complex::new(T::zero(), T::zero());
382                    let mut buf = vec![zero; d];
383                    for i in 0..views.first().map_or(0, |v| v.len()) {
384                        for (b, v) in buf.iter_mut().zip(&views) {
385                            *b = v[i];
386                        }
387                        for (r, v) in views.iter_mut().enumerate() {
388                            v[i] = (0..d).fold(zero, |acc, k| acc + matrix[r * d + k] * buf[k]);
389                        }
390                    }
391                };
392                if parallel {
393                    pieces.into_par_iter().for_each(apply);
394                } else {
395                    pieces.into_iter().for_each(apply);
396                }
397            }
398        }
399    }
400
401    /// `(p, α, β)` in the precision of the state.
402    fn exchange_in<T: Real>(&self) -> Exchange<T> {
403        let (p, alpha, beta) = self.exchange();
404        (narrow(p), narrow(alpha), narrow(beta))
405    }
406
407    /// `ψ ← V(J) M ψ`: every edge on its two rows ([`Self::edge_serial`]).
408    fn edges<T: Real>(&self, psi: &mut [Complex<T>], parallel: bool) {
409        assert_eq!(psi.len(), self.dimension(), "state of the wrong dimension");
410        let (l, k) = (self.row_len(), self.exchange_in::<T>());
411        if parallel {
412            // Every half-edge is a side of one edge: the edges own disjoint pairs of rows.
413            let mut rows: Vec<Option<&mut [Complex<T>]>> = psi.chunks_exact_mut(l).map(Some).collect();
414            let edges: Vec<_> = (0..self.graph.edges())
415                .map(|e| {
416                    let (ha, hb) = self.graph.halves(e);
417                    let mut take = |h: usize| rows[h].take().expect("each half-edge is a side of one edge");
418                    (e, take(ha), take(hb))
419                })
420                .collect();
421            edges.into_par_iter().for_each(|(e, a, b)| self.edge_parallel(e, a, b, k));
422        } else {
423            for e in 0..self.graph.edges() {
424                let (ha, hb) = self.graph.halves(e);
425                let (a, b) = two_rows(psi, l, ha, hb);
426                self.edge_serial::<T, false>(e, a, b, k, |_, _| {});
427            }
428        }
429    }
430
431    /// One step on the calling thread, adding the probability of every half-edge after the step
432    /// to `acc` (`Σ_s |ψ(h, s)|²`, one entry per half-edge) at no extra sweep over memory: for
433    /// time averages in scans of parameters.
434    ///
435    /// # Panics
436    ///
437    /// If `psi.len()` is not [`Self::dimension`] or `acc.len()` is not the number of half-edges.
438    pub fn step_serial_accumulate<T: Real>(&self, psi: &mut [Complex<T>], acc: &mut [f64]) {
439        assert_eq!(acc.len(), self.graph.half_edges(), "one accumulator per half-edge");
440        self.coin(psi, false);
441        let (l, k) = (self.row_len(), self.exchange_in::<T>());
442        for e in 0..self.graph.edges() {
443            let (ha, hb) = self.graph.halves(e);
444            let (a, b) = two_rows(psi, l, ha, hb);
445            self.edge_serial::<T, true>(e, a, b, k, |pa, pb| {
446                acc[ha] += pa;
447                acc[hb] += pb;
448            });
449        }
450    }
451
452    /// Edge `e` on its rows `a` and `b` (its half-edges, [`Graph::halves`]), on the calling
453    /// thread, by pieces of `CHUNK` quadruples: a whole range of `2 CHUNK` configurations when
454    /// the edge spin is a low bit, or `CHUNK` configurations with the spin up and their partners,
455    /// `2^e` further, when it is a high bit. With `ACC`, `sink` receives the probabilities of the
456    /// updated entries of each piece, in order.
457    fn edge_serial<T: Real, const ACC: bool>(
458        &self,
459        e: usize,
460        a: &mut [Complex<T>],
461        b: &mut [Complex<T>],
462        k: Exchange<T>,
463        mut sink: impl FnMut(f64, f64),
464    ) {
465        let (bit, span) = (1usize << e, self.row_len().min(2 * CHUNK));
466        if 2 * bit <= span {
467            for (a, b) in a.chunks_mut(span).zip(b.chunks_mut(span)) {
468                let (pa, pb) = edge_span::<T, ACC>(bit, a, b, k);
469                sink(pa, pb);
470            }
471        } else {
472            // Blocks of 2 bit configurations, the spin up in the first half: one piece is a run
473            // of each half of both rows.
474            let run = span / 2;
475            for (a, b) in a.chunks_exact_mut(2 * bit).zip(b.chunks_exact_mut(2 * bit)) {
476                let ((a0, a1), (b0, b1)) = (a.split_at_mut(bit), b.split_at_mut(bit));
477                let runs = a0
478                    .chunks_mut(run)
479                    .zip(a1.chunks_mut(run))
480                    .zip(b0.chunks_mut(run))
481                    .zip(b1.chunks_mut(run));
482                for (((a0, a1), b0), b1) in runs {
483                    let (pa, pb) = exchange_run::<T, ACC>(a0, a1, b0, b1, k);
484                    sink(pa, pb);
485                }
486            }
487        }
488    }
489
490    /// [`Self::edge_serial`] on all the threads of the rayon pool, without the probabilities.
491    fn edge_parallel<T: Real>(&self, e: usize, a: &mut [Complex<T>], b: &mut [Complex<T>], k: Exchange<T>) {
492        let (bit, span) = (1usize << e, self.row_len().min(2 * CHUNK));
493        if 2 * bit <= span {
494            a.par_chunks_mut(span).zip(b.par_chunks_mut(span)).for_each(|(a, b)| {
495                edge_span::<T, false>(bit, a, b, k);
496            });
497        } else {
498            let run = span / 2;
499            a.par_chunks_exact_mut(2 * bit).zip(b.par_chunks_exact_mut(2 * bit)).for_each(|(a, b)| {
500                let ((a0, a1), (b0, b1)) = (a.split_at_mut(bit), b.split_at_mut(bit));
501                a0.par_chunks_mut(run)
502                    .zip(a1.par_chunks_mut(run))
503                    .zip(b0.par_chunks_mut(run))
504                    .zip(b1.par_chunks_mut(run))
505                    .for_each(|(((a0, a1), b0), b1)| {
506                        exchange_run::<T, false>(a0, a1, b0, b1, k);
507                    });
508            });
509        }
510    }
511
512    /// The one-step operator `U` as a sparse matrix (at most `2 d_max` entries per column).
513    pub fn matrix(&self) -> SparseMatrix {
514        let l = self.row_len();
515        let (p, alpha, beta) = self.exchange();
516        // V M on |h, s⟩.
517        let vm = |h: usize, s: usize| -> Vec<(usize, usize, c64)> {
518            let e = self.graph.edge_of(h);
519            let (ha, hb) = self.graph.halves(e);
520            let bit = 1usize << e;
521            let down = s & bit != 0;
522            match (h == ha, down) {
523                (true, false) => vec![(ha, s | bit, beta), (hb, s, alpha)],
524                (true, true) => vec![(hb, s, p)],
525                (false, false) => vec![(ha, s, p)],
526                (false, true) => vec![(ha, s, alpha), (hb, s & !bit, beta)],
527            }
528        };
529        let mut entries = Vec::with_capacity(self.dimension() * 2 * self.graph.max_degree());
530        for x in 0..self.graph.nodes() {
531            let rows = self.graph.half_edges_of(x);
532            for (c, h) in rows.clone().enumerate() {
533                for s in 0..l {
534                    for (r, hr) in rows.clone().enumerate() {
535                        let w = self.coins[x][(r, c)];
536                        if w == c64::new(0.0, 0.0) {
537                            continue;
538                        }
539                        for (ho, so, v) in vm(hr, s) {
540                            entries.push((ho * l + so, h * l + s, v * w));
541                        }
542                    }
543                }
544            }
545        }
546        SparseMatrix::from_triplets(self.dimension(), entries)
547    }
548
549    /// The product state `walker ⊗ spins[0] ⊗ … ⊗ spins[|E| − 1]`, with `walker` the amplitude
550    /// on each half-edge and `spins[e]` the (up, down) amplitudes of spin `e`.
551    pub fn product_state(&self, walker: &[c64], spins: &[[c64; 2]]) -> Vec<c64> {
552        assert_eq!(walker.len(), self.graph.half_edges(), "one walker amplitude per half-edge");
553        assert_eq!(spins.len(), self.graph.edges(), "one spin state per edge");
554        let mut config = vec![c64::new(1.0, 0.0)];
555        for spin in spins {
556            let down: Vec<c64> = config.iter().map(|v| v * spin[1]).collect();
557            config.iter_mut().for_each(|v| *v *= spin[0]);
558            config.extend(down);
559        }
560        let l = self.row_len();
561        let mut psi = vec![c64::new(0.0, 0.0); self.dimension()];
562        psi.par_chunks_mut(l).zip(walker.par_iter()).for_each(|(row, &w)| {
563            if w != c64::new(0.0, 0.0) {
564                row.iter_mut().zip(&config).for_each(|(v, &c)| *v = w * c);
565            }
566        });
567        psi
568    }
569
570    /// Walker on color `c` of node `x` (a half-edge), as the `walker` of [`Self::product_state`].
571    pub fn localized(&self, x: usize, c: usize) -> Vec<c64> {
572        let mut w = vec![c64::new(0.0, 0.0); self.graph.half_edges()];
573        w[self.graph.half_edge(x, c)] = c64::new(1.0, 0.0);
574        w
575    }
576}
577
578/// Spin up `|0⟩`.
579pub const UP: [c64; 2] = [c64::new(1.0, 0.0), c64::new(0.0, 0.0)];
580
581/// Spin along +x, `|+⟩ = (|0⟩ + |1⟩)/√2`.
582pub const PLUS: [c64; 2] =
583    [c64::new(std::f64::consts::FRAC_1_SQRT_2, 0.0), c64::new(std::f64::consts::FRAC_1_SQRT_2, 0.0)];
584
585#[cfg(test)]
586mod tests {
587    use super::*;
588
589    fn random_state(n: usize, seed: u64) -> Vec<c64> {
590        let mut x = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
591        let mut next = || {
592            x ^= x << 13;
593            x ^= x >> 7;
594            x ^= x << 17;
595            (x >> 11) as f64 / (1u64 << 53) as f64 - 0.5
596        };
597        let v: Vec<c64> = (0..n).map(|_| c64::new(next(), next())).collect();
598        let norm = v.iter().map(|z| z.norm_sqr()).sum::<f64>().sqrt();
599        v.iter().map(|z| z / norm).collect()
600    }
601
602    fn distance(a: &[c64], b: &[c64]) -> f64 {
603        a.iter().zip(b).map(|(x, y)| (x - y).norm_sqr()).sum::<f64>().sqrt()
604    }
605
606    /// The structured step and the explicit matrix agree, on rings and on a graph of degree 3.
607    #[test]
608    fn step_matches_matrix() {
609        let walks = [
610            SpinWalk::ring(3, 0.4, 0.9),
611            SpinWalk::ring(5, std::f64::consts::FRAC_PI_3, 1.0),
612            SpinWalk::new(
613                Graph::from_edges(4, &[(0, 1), (0, 2), (0, 3), (1, 2)]),
614                vec![
615                    fourier(3),
616                    grover(2),
617                    rotation(0.3),
618                    CMat::from_fn(1, 1, |_, _| c64::from_polar(1.0, 0.7)),
619                ],
620                0.6,
621            ),
622        ];
623        for (k, walk) in walks.iter().enumerate() {
624            let u = walk.matrix();
625            let psi = random_state(walk.dimension(), k as u64 + 1);
626            let mut stepped = psi.clone();
627            walk.step(&mut stepped);
628            let mut product = vec![c64::new(0.0, 0.0); psi.len()];
629            u.apply(&psi, &mut product);
630            assert!(distance(&stepped, &product) < 1e-13, "walk {k}");
631        }
632    }
633
634    /// `U` is unitary: its columns are orthonormal.
635    #[test]
636    fn unitary() {
637        let walk = SpinWalk::ring(3, 0.8, 2.1);
638        let n = walk.dimension();
639        let columns: Vec<Vec<c64>> = (0..n)
640            .map(|j| {
641                let mut v = vec![c64::new(0.0, 0.0); n];
642                v[j] = c64::new(1.0, 0.0);
643                walk.step(&mut v);
644                v
645            })
646            .collect();
647        for i in 0..n {
648            for j in 0..n {
649                let dot: c64 = columns[i].iter().zip(&columns[j]).map(|(a, b)| a.conj() * b).sum();
650                let expected = if i == j { 1.0 } else { 0.0 };
651                assert!((dot - expected).norm() < 1e-13, "columns {i}, {j}");
652            }
653        }
654    }
655
656    /// Without coupling the spins are spectators: the walker follows the free walk on 2|E|
657    /// amplitudes, whatever the spin state.
658    #[test]
659    fn free_walk() {
660        let (n, theta) = (6, 0.7);
661        let walk = SpinWalk::ring(n, theta, 0.0);
662        let spins = vec![PLUS; n];
663        let mut psi = walk.product_state(&walk.localized(2, 0), &spins);
664        // The free walk alone: no spins, the same graph.
665        let free = SpinWalk::ring(n, theta, 0.0);
666        let mut w = walk.localized(2, 0);
667        for _ in 0..25 {
668            walk.step(&mut psi);
669            // Free step on the walker amplitudes: coin then swap of the edge half-edges.
670            let mut next = w.clone();
671            for x in 0..n {
672                let (a, b) = (w[2 * x], w[2 * x + 1]);
673                let c = &free.coins()[x];
674                next[2 * x] = c[(0, 0)] * a + c[(0, 1)] * b;
675                next[2 * x + 1] = c[(1, 0)] * a + c[(1, 1)] * b;
676            }
677            for e in 0..n {
678                let (ha, hb) = free.graph().halves(e);
679                next.swap(ha, hb);
680            }
681            w = next;
682            let expected = walk.product_state(&w, &spins);
683            assert!(distance(&psi, &expected) < 1e-12);
684        }
685    }
686
687    #[test]
688    fn single_precision() {
689        let walk = SpinWalk::ring(8, 0.7, 1.1);
690        let psi = random_state(walk.dimension(), 13);
691        let mut double = psi.clone();
692        let mut single = to_single(&psi);
693        walk.steps(&mut double, 50);
694        walk.steps(&mut single, 50);
695        let error = distance(&to_double(&single), &double);
696        assert!(error > 1e-12 && error < 1e-4, "f32 after 50 steps: {error:e}");
697    }
698
699    #[test]
700    fn accumulated_probabilities() {
701        let walk = SpinWalk::ring(7, 0.9, 0.4);
702        let mut psi = random_state(walk.dimension(), 11);
703        let mut acc = vec![0.0; walk.graph().half_edges()];
704        walk.step_serial_accumulate(&mut psi, &mut acc);
705        let mut stepped = random_state(walk.dimension(), 11);
706        walk.step(&mut stepped);
707        assert!(distance(&psi, &stepped) < 1e-15);
708        for (a, b) in acc.iter().zip(&walk.half_edge_probabilities(&psi)) {
709            assert!((a - b).abs() < 1e-14);
710        }
711    }
712
713    #[test]
714    fn serial_matches_parallel() {
715        let walk = SpinWalk::ring(9, 0.6, 1.3);
716        let mut a = random_state(walk.dimension(), 5);
717        let mut b = a.clone();
718        walk.steps(&mut a, 7);
719        walk.steps_serial(&mut b, 7);
720        assert!(distance(&a, &b) < 1e-15);
721    }
722
723    /// The coin pass then the edge pass make one step.
724    #[test]
725    fn passes_make_a_step() {
726        let walk = SpinWalk::ring(6, 0.5, 0.8);
727        let mut a = random_state(walk.dimension(), 3);
728        let mut b = a.clone();
729        walk.coin_pass(&mut a);
730        walk.edge_pass(&mut a);
731        walk.step(&mut b);
732        assert!(distance(&a, &b) < 1e-15);
733    }
734
735    /// A state of the wrong length is refused, never written past its end.
736    #[test]
737    #[should_panic(expected = "state of the wrong dimension")]
738    fn coin_pass_checks_the_dimension() {
739        let walk = SpinWalk::ring(4, 0.3, 0.5);
740        let mut psi = vec![c64::new(1.0, 0.0); 4];
741        walk.coin_pass(&mut psi);
742    }
743
744    #[test]
745    #[should_panic(expected = "state of the wrong dimension")]
746    fn edge_pass_checks_the_dimension() {
747        let walk = SpinWalk::ring(4, 0.3, 0.5);
748        let mut psi = vec![c64::new(1.0, 0.0); walk.dimension() + 1];
749        walk.edge_pass(&mut psi);
750    }
751
752    #[test]
753    #[should_panic(expected = "state of the wrong dimension")]
754    fn serial_step_checks_the_dimension() {
755        let walk = SpinWalk::ring(4, 0.3, 0.5);
756        let mut psi = vec![c64::new(1.0, 0.0); walk.dimension() - 1];
757        let mut acc = vec![0.0; walk.graph().half_edges()];
758        walk.step_serial_accumulate(&mut psi, &mut acc);
759    }
760
761    #[test]
762    fn product_states() {
763        let walk = SpinWalk::ring(3, 0.1, 0.2);
764        let psi = walk.product_state(&walk.localized(1, 0), &[UP, PLUS, UP]);
765        let l = walk.row_len();
766        let h = walk.graph().half_edge(1, 0);
767        // Spin 1 is the middle bit: configurations 0 and 2 carry 1/√2.
768        assert!((psi[h * l] - PLUS[0]).norm() < 1e-15 && (psi[h * l + 2] - PLUS[1]).norm() < 1e-15);
769        assert!(psi.iter().map(|z| z.norm_sqr()).sum::<f64>() - 1.0 < 1e-15);
770    }
771}