Skip to main content

caroli_dynamics/
torus.rs

1//! Time evolution of a periodic 2D [`Model`] on an `n × n` torus under a uniform vector potential,
2//! by the split-operator method.
3//!
4//! The translation-invariant part `M(k, A)` (every hopping, with the Peierls factor
5//! `exp(−i A·d)` of its bond) is diagonal in k; the site-dependent on-site terms of the model
6//! (disorder, potentials) act in real space. A step is `U_V(dt/2) U_K U_V(dt/2)` with
7//! `U_K(k) = exp(−i M(k, A(t + dt/2)) dt)`: second order in `dt`. Without site-dependent terms the
8//! wave functions stay in k space and every k evolves on its own.
9//!
10//! The observables are those of a non-interacting electron gas: the current density, the density
11//! of carriers excited above the Fermi energy of the instantaneous clean bands (pair creation by
12//! a field), the width of a wave packet and the densities. A filled Fermi sea enters as a
13//! stochastic trace ([`Torus::filled`]): a random-phase superposition of the occupied band
14//! states, whose expectation values estimate the traces over the occupied states.
15//!
16//! Wave functions are stored component by component, `ψ[x + n·y + n²·c]`, `c` running over the
17//! orbitals of the unit cell (every sublattice), as in [`caroli_torus`].
18
19use crate::driven::{VectorPotential, constant_force};
20use crate::{apply_local, exp_i};
21use caroli_disorder::rng::Xoshiro256;
22use caroli_lattice::{Region, Site, Vec3};
23use caroli_model::{CMat, Model, c64};
24use caroli_torus::{Fft2, k_value};
25use faer::Side;
26use rayon::prelude::*;
27
28/// A hopping block of the unit cell: `⟨row| H |col⟩` towards the cell `images` away.
29#[derive(Clone, Debug)]
30struct Hop {
31    row: usize,
32    col: usize,
33    images: [i64; 2],
34    displacement: Vec3,
35    matrix: CMat,
36}
37
38/// A band state at one k: energy, orbitals of its group, amplitudes on them.
39type BandState = (f64, Vec<usize>, Vec<c64>);
40
41/// A periodic 2D model on an `n × n` torus of unit cells.
42pub struct Torus {
43    n: usize,
44    comps: usize,
45    vectors: [Vec3; 2],
46    /// Position, in the cell, of the site of each orbital.
47    offsets: Vec<Vec3>,
48    onsite: CMat,
49    hops: Vec<Hop>,
50    /// Groups of orbitals that `M(k)` never couples to one another.
51    groups: Vec<Vec<usize>>,
52    /// Site-dependent on-site terms of each cell (`x + n·y`), on all the orbitals of the cell.
53    local: Vec<(usize, CMat)>,
54    /// Orbitals of the band states that [`Torus::filled`] fills and that the excited-carrier
55    /// count reads (all of them if `None`).
56    sector: Option<Vec<usize>>,
57    potential: VectorPotential,
58    fft: Fft2,
59}
60
61/// The parameters of [`Torus::evolve`].
62#[derive(Clone, Copy, Debug, PartialEq)]
63pub struct Evolution {
64    /// Time step, in units of `ħ` over the energy unit of the model.
65    pub dt: f64,
66    /// Number of steps: the run ends at `t = steps · dt`.
67    pub steps: usize,
68    /// Observables every `every` steps (and at the start).
69    pub every: usize,
70    /// Fermi energy of the excited-carrier count.
71    pub fermi: f64,
72    /// Whether to record the densities.
73    pub densities: bool,
74}
75
76/// The observables recorded by [`Torus::evolve`], averaged over the start vectors.
77#[derive(Clone, Debug, Default, PartialEq)]
78pub struct Record {
79    /// Time of each record, `t = k · every · dt` (`k = 0, 1, …`).
80    pub times: Vec<f64>,
81    /// `⟨ψ|ψ⟩`.
82    pub norm: Vec<f64>,
83    /// Current density `⟨v⟩/Ω` (`v = i[H, r]`, `Ω` the area of the torus), x and y.
84    pub current: Vec<[f64; 2]>,
85    /// Density of carriers in the instantaneous clean bands above the Fermi energy (those of the
86    /// sector, if one is set), per unit area.
87    pub excited: Vec<f64>,
88    /// `sqrt(⟨Δr²⟩ − ⟨Δr⟩²)`, positions taken around the densest orbital at the start (nearest
89    /// image).
90    pub width: Vec<f64>,
91    /// `|ψ|²` of every orbital (`x + n·y + n²·c`), if asked.
92    pub densities: Vec<Vec<f64>>,
93}
94
95impl Torus {
96    /// The model on an `n × n` torus, without field. Its hoppings must be the same in every cell
97    /// (no hopping term, no Peierls phase: use [`crate::Driven`] otherwise); its site-dependent
98    /// on-site terms are read on every site of the torus.
99    pub fn new(model: &Model, n: usize) -> Self {
100        let lattice = model.lattice();
101        assert_eq!(lattice.dim(), 2, "a torus of a 2D lattice");
102        assert!(
103            model.has_uniform_hoppings(),
104            "the torus needs hoppings without site-dependent terms or Peierls phases"
105        );
106        let cell = Region::cuboid(lattice, [1, 1, 0]);
107        let comps = cell.orbitals();
108        let mut onsite = CMat::zeros(comps, comps);
109        let mut offsets = Vec::with_capacity(comps);
110        for (i, site) in cell.sites().iter().enumerate() {
111            let (o, m) = (cell.offset(i), model.sublattice_onsite(site.sub));
112            add_block(&mut onsite, o, o, m, c64::new(1.0, 0.0));
113            offsets.extend(std::iter::repeat_n(lattice.position(*site), m.nrows()));
114        }
115        let hops: Vec<Hop> = model
116            .bonds(&cell, &[[1, 0, 0], [0, 1, 0]])
117            .into_iter()
118            .map(|b| Hop {
119                row: cell.offset(b.from),
120                col: cell.offset(b.to),
121                images: [b.images[0], b.images[1]],
122                displacement: b.displacement,
123                matrix: b.matrix,
124            })
125            .collect();
126        // Orbitals coupled by M(k): union-find on the non-zero entries.
127        let mut parent: Vec<usize> = (0..comps).collect();
128        fn root(p: &mut [usize], mut i: usize) -> usize {
129            while p[i] != i {
130                p[i] = p[p[i]];
131                i = p[i];
132            }
133            i
134        }
135        let mut link = |a: usize, b: usize| {
136            let (ra, rb) = (root(&mut parent, a), root(&mut parent, b));
137            parent[ra] = rb;
138        };
139        for a in 0..comps {
140            for b in 0..comps {
141                if onsite[(a, b)] != c64::new(0.0, 0.0) {
142                    link(a, b);
143                }
144            }
145        }
146        for h in &hops {
147            for a in 0..h.matrix.nrows() {
148                for b in 0..h.matrix.ncols() {
149                    if h.matrix[(a, b)] != c64::new(0.0, 0.0) {
150                        link(h.row + a, h.col + b);
151                    }
152                }
153            }
154        }
155        let mut groups: std::collections::BTreeMap<usize, Vec<usize>> = Default::default();
156        for a in 0..comps {
157            groups.entry(root(&mut parent, a)).or_default().push(a);
158        }
159        let mut local = Vec::new();
160        for y in 0..n as i64 {
161            for x in 0..n as i64 {
162                let mut block: Option<CMat> = None;
163                for (i, s) in cell.sites().iter().enumerate() {
164                    if let Some(m) = model.onsite_terms(&Site { cell: [x, y, 0], sub: s.sub }) {
165                        let b = block.get_or_insert_with(|| CMat::zeros(comps, comps));
166                        add_block(b, cell.offset(i), cell.offset(i), &m, c64::new(1.0, 0.0));
167                    }
168                }
169                if let Some(b) = block {
170                    local.push((x as usize + n * y as usize, b));
171                }
172            }
173        }
174        let v = lattice.vectors();
175        Self {
176            n,
177            comps,
178            vectors: [v[0], v[1]],
179            offsets,
180            onsite,
181            hops,
182            groups: groups.into_values().collect(),
183            local,
184            sector: None,
185            potential: std::sync::Arc::new(|_| [0.0; 3]),
186            fft: Fft2::new(n),
187        }
188    }
189
190    /// A constant force `F` from `t = 0`: `A(t) = −F t`, the crystal momentum moves as `k + F t`.
191    pub fn with_force(self, force: Vec3) -> Self {
192        self.with_vector_potential(constant_force(force))
193    }
194
195    /// Any uniform vector potential `A(t)`.
196    pub fn with_vector_potential(mut self, potential: VectorPotential) -> Self {
197        self.potential = potential;
198        self
199    }
200
201    /// Restricts [`Self::filled`] and the excited-carrier count to the band states on `orbitals`
202    /// (of the unit cell), a union of groups of orbitals that `M(k)` does not couple to the
203    /// others: one spin of a model whose hoppings conserve the spin, say. The evolution itself is
204    /// unchanged (the disorder may carry the states out of the sector), and so is
205    /// [`Self::fermi_sea`].
206    pub fn with_sector(mut self, orbitals: &[usize]) -> Self {
207        for g in &self.groups {
208            let inside = g.iter().filter(|c| orbitals.contains(c)).count();
209            assert!(inside == 0 || inside == g.len(), "the sector splits the coupled orbitals {g:?}");
210        }
211        self.sector = Some(orbitals.to_vec());
212        self
213    }
214
215    /// The groups of orbitals of the cell that `M(k)` does not couple to one another (the
216    /// blocks of a sector, see [`Self::with_sector`]).
217    pub fn groups(&self) -> &[Vec<usize>] {
218        &self.groups
219    }
220
221    /// Whether the group of orbitals `g` lies in the sector.
222    fn in_sector(&self, g: &[usize]) -> bool {
223        self.sector.as_ref().is_none_or(|s| g.iter().all(|c| s.contains(c)))
224    }
225
226    /// Side `n` of the torus, in unit cells (`n × n` of them).
227    pub fn size(&self) -> usize {
228        self.n
229    }
230
231    /// Orbitals per unit cell.
232    pub fn components(&self) -> usize {
233        self.comps
234    }
235
236    /// Area of the torus.
237    pub fn area(&self) -> f64 {
238        let [a, b] = self.vectors;
239        (a[0] * b[1] - a[1] * b[0]).abs() * (self.n * self.n) as f64
240    }
241
242    /// `M(k, A)` at the k point of FFT index `k` (`kx + n·ky`).
243    pub fn kinetic(&self, k: usize, a: Vec3) -> CMat {
244        self.k_matrix(k, a, None)
245    }
246
247    /// The velocity `∂M/∂k` along `direction` at k index `k`: `Σ i (d·direction) t e^{i(k·n − A·d)}`.
248    pub fn velocity(&self, k: usize, a: Vec3, direction: Vec3) -> CMat {
249        self.k_matrix(k, a, Some(direction))
250    }
251
252    fn k_matrix(&self, k: usize, a: Vec3, direction: Option<Vec3>) -> CMat {
253        let n = self.n;
254        let (p1, p2) = (k_value(k % n, n), k_value(k / n, n));
255        let mut m =
256            if direction.is_some() { CMat::zeros(self.comps, self.comps) } else { self.onsite.clone() };
257        for h in &self.hops {
258            let d = h.displacement;
259            let phase =
260                p1 * h.images[0] as f64 + p2 * h.images[1] as f64 - (a[0] * d[0] + a[1] * d[1] + a[2] * d[2]);
261            let factor = match direction {
262                None => c64::from_polar(1.0, phase),
263                Some(u) => {
264                    c64::new(0.0, d[0] * u[0] + d[1] * u[1] + d[2] * u[2]) * c64::from_polar(1.0, phase)
265                }
266            };
267            add_block(&mut m, h.row, h.col, &h.matrix, factor);
268        }
269        m
270    }
271
272    /// Band energies and states of `M(k, A)`, group by group: `(energy, orbitals of the group,
273    /// state on them)`.
274    fn bands(&self, m: &CMat) -> Vec<(f64, &[usize], Vec<c64>)> {
275        let mut out = Vec::with_capacity(self.comps);
276        for g in &self.groups {
277            let sub = CMat::from_fn(g.len(), g.len(), |i, j| m[(g[i], g[j])]);
278            let evd = sub.self_adjoint_eigen(Side::Lower).expect("Hermitian eigenproblem");
279            for b in 0..g.len() {
280                out.push((evd.S()[b].re, g.as_slice(), (0..g.len()).map(|i| evd.U()[(i, b)]).collect()));
281            }
282        }
283        out
284    }
285
286    /// `exp(−i M dt)`, group by group (two-orbital groups in closed form).
287    fn propagator(&self, m: &CMat, dt: f64) -> CMat {
288        let mut u = CMat::zeros(self.comps, self.comps);
289        for g in &self.groups {
290            match g.len() {
291                1 => u[(g[0], g[0])] = c64::from_polar(1.0, -m[(g[0], g[0])].re * dt),
292                2 => {
293                    let (a, b, d) = (m[(g[0], g[0])].re, m[(g[0], g[1])], m[(g[1], g[1])].re);
294                    let (mean, z) = (0.5 * (a + d), 0.5 * (a - d));
295                    let r = (z * z + b.norm_sqr()).sqrt();
296                    let (c, s) = ((r * dt).cos(), if r > 0.0 { (r * dt).sin() / r } else { dt });
297                    let phase = c64::from_polar(1.0, -mean * dt);
298                    let mi = c64::new(0.0, -s);
299                    u[(g[0], g[0])] = phase * (c + mi * z);
300                    u[(g[1], g[1])] = phase * (c - mi * z);
301                    u[(g[0], g[1])] = phase * mi * b;
302                    u[(g[1], g[0])] = phase * mi * b.conj();
303                }
304                _ => {
305                    let sub = CMat::from_fn(g.len(), g.len(), |i, j| m[(g[i], g[j])]);
306                    let e = exp_i(&sub, dt);
307                    for (i, &gi) in g.iter().enumerate() {
308                        for (j, &gj) in g.iter().enumerate() {
309                            u[(gi, gj)] = e[(i, j)];
310                        }
311                    }
312                }
313            }
314        }
315        u
316    }
317
318    /// Forward FFT of every component.
319    pub fn to_k(&self, psi: &mut [c64]) {
320        psi.chunks_exact_mut(self.n * self.n).for_each(|c| self.fft.forward(c));
321    }
322
323    /// Backward FFT of every component divided by n² (inverse of [`Self::to_k`]).
324    pub fn to_x(&self, psi: &mut [c64]) {
325        let norm = (self.n * self.n) as f64;
326        psi.chunks_exact_mut(self.n * self.n).for_each(|c| {
327            self.fft.backward(c);
328            c.iter_mut().for_each(|z| *z /= norm);
329        });
330    }
331
332    /// `ψ_k ← f(k, ψ_k)` for every k, in parallel (`ψ` in k space, component by component).
333    fn per_k(&self, psi: &mut [c64], f: impl Fn(usize, &mut [c64]) + Sync) {
334        let (nn, m) = (self.n * self.n, self.comps);
335        let mut by_k = vec![c64::new(0.0, 0.0); nn * m];
336        for c in 0..m {
337            for k in 0..nn {
338                by_k[k * m + c] = psi[k + nn * c];
339            }
340        }
341        by_k.par_chunks_exact_mut(m).enumerate().with_min_len(64).for_each(|(k, v)| f(k, v));
342        for c in 0..m {
343            for k in 0..nn {
344                psi[k + nn * c] = by_k[k * m + c];
345            }
346        }
347    }
348
349    /// `Σ_k f(k, ψ_k)` in parallel.
350    fn sum_k<T: Send + std::iter::Sum<T>>(&self, psi: &[c64], f: impl Fn(usize, &[c64]) -> T + Sync) -> T {
351        let (nn, m) = (self.n * self.n, self.comps);
352        (0..nn)
353            .into_par_iter()
354            .with_min_len(64)
355            .map(|k| {
356                let v: Vec<c64> = (0..m).map(|c| psi[k + nn * c]).collect();
357                f(k, &v)
358            })
359            .sum()
360    }
361
362    /// The Fermi sea below `fermi` of the clean bands at `t = 0`, as `vectors` random-phase
363    /// superpositions of the occupied band states (k space): for each of them `⟨ψ|O|ψ⟩`
364    /// estimates `Tr[P O]`, `P` the projector on the occupied states, and `⟨ψ|ψ⟩` is their number.
365    /// Only the band states of the sector, if one is set ([`Self::with_sector`]).
366    pub fn filled(&self, fermi: f64, vectors: usize, seed: u64) -> Vec<Vec<c64>> {
367        let (nn, a0) = (self.n * self.n, (self.potential)(0.0));
368        let bands: Vec<Vec<BandState>> = (0..nn)
369            .into_par_iter()
370            .map(|k| {
371                let m = self.kinetic(k, a0);
372                self.bands(&m).into_iter().map(|(e, g, u)| (e, g.to_vec(), u)).collect()
373            })
374            .collect();
375        let mut rng = Xoshiro256::seed_from_u64(seed);
376        (0..vectors)
377            .map(|_| {
378                let mut psi = vec![c64::new(0.0, 0.0); nn * self.comps];
379                for (k, bk) in bands.iter().enumerate() {
380                    for (e, g, u) in bk {
381                        let phase =
382                            c64::from_polar(self.n as f64, 2.0 * std::f64::consts::PI * rng.uniform());
383                        if *e < fermi && self.in_sector(g) {
384                            for (i, &c) in g.iter().enumerate() {
385                                psi[k + nn * c] += phase * u[i];
386                            }
387                        }
388                    }
389                }
390                psi
391            })
392            .collect()
393    }
394
395    /// The Fermi sea below `fermi` of the whole Hamiltonian at `t = 0`, site-dependent terms
396    /// included: `vectors` random-phase vectors (in real space) projected by a Chebyshev
397    /// expansion of `θ(fermi − H)` with `moments` terms and the Jackson kernel (k space, as
398    /// [`Self::filled`]). The step is smeared over about `π·ΔE/moments`, `ΔE` the half-width of
399    /// the spectrum. Without disorder it is [`Self::filled`] up to that smearing; with disorder it
400    /// is the ground state, where [`Self::filled`] is the clean one, which the disorder sets in
401    /// motion.
402    pub fn fermi_sea(&self, fermi: f64, vectors: usize, seed: u64, moments: usize) -> Vec<Vec<c64>> {
403        let (nn, a0) = (self.n * self.n, (self.potential)(0.0));
404        let kinetic: Vec<CMat> = (0..nn).into_par_iter().map(|k| self.kinetic(k, a0)).collect();
405        // Spectral bounds: the bands, widened by the largest local term (row sums).
406        let (mut lo, mut hi) = kinetic
407            .par_iter()
408            .map(|m| {
409                let e = m.self_adjoint_eigenvalues(Side::Lower).expect("eigenvalues");
410                (e[0], e[e.len() - 1])
411            })
412            .reduce(|| (f64::INFINITY, f64::NEG_INFINITY), |a, b| (a.0.min(b.0), a.1.max(b.1)));
413        let local_norm = self
414            .local
415            .iter()
416            .map(|(_, v)| {
417                (0..v.nrows())
418                    .map(|i| (0..v.ncols()).map(|j| v[(i, j)].norm()).sum::<f64>())
419                    .fold(0.0, f64::max)
420            })
421            .fold(0.0, f64::max);
422        lo -= local_norm;
423        hi += local_norm;
424        let (centre, half) = (0.5 * (lo + hi), 0.5 * (hi - lo) * 1.01 + 1e-12);
425        let op = caroli_torus::TorusOperator::new(self.n, self.comps, kinetic, self.local.clone());
426        let apply = |x: &[c64], y: &mut [c64]| {
427            op.apply(x, y);
428            y.iter_mut().zip(x).for_each(|(y, x)| *y = (*y - centre * x) / half);
429        };
430        // θ(μ − x) = Σ c_n T_n(x): c_0 = 1 − φ/π, c_n = −2 sin(nφ)/(nπ), φ = arccos μ̃.
431        let phi = ((fermi - centre) / half).clamp(-1.0, 1.0).acos();
432        let kernel = caroli_kpm::jackson(moments);
433        let coefficient = |n: usize| {
434            let c = if n == 0 {
435                1.0 - phi / std::f64::consts::PI
436            } else {
437                -2.0 * (n as f64 * phi).sin() / (n as f64 * std::f64::consts::PI)
438            };
439            c * kernel[n]
440        };
441        let mut rng = Xoshiro256::seed_from_u64(seed);
442        let len = nn * self.comps;
443        (0..vectors)
444            .map(|_| {
445                let r: Vec<c64> = (0..len)
446                    .map(|_| c64::from_polar(1.0, 2.0 * std::f64::consts::PI * rng.uniform()))
447                    .collect();
448                let mut out: Vec<c64> = r.iter().map(|x| x * coefficient(0)).collect();
449                let (mut prev, mut cur) = (r, vec![c64::new(0.0, 0.0); len]);
450                apply(&prev, &mut cur);
451                out.iter_mut().zip(&cur).for_each(|(o, c)| *o += c * coefficient(1));
452                let mut next = vec![c64::new(0.0, 0.0); len];
453                for n in 2..moments {
454                    apply(&cur, &mut next);
455                    next.iter_mut().zip(&prev).for_each(|(x, p)| *x = 2.0 * *x - p);
456                    out.iter_mut().zip(&next).for_each(|(o, c)| *o += c * coefficient(n));
457                    std::mem::swap(&mut prev, &mut cur);
458                    std::mem::swap(&mut cur, &mut next);
459                }
460                self.to_k(&mut out);
461                out
462            })
463            .collect()
464    }
465
466    /// The orbital `orbital` of cell `cell` (k space, unit norm), projected on the clean band
467    /// states at `t = 0` whose energy lies in `window` if one is given.
468    pub fn localized(&self, cell: [usize; 2], orbital: usize, window: Option<(f64, f64)>) -> Vec<c64> {
469        let nn = self.n * self.n;
470        let mut psi = vec![c64::new(0.0, 0.0); nn * self.comps];
471        psi[cell[0] + self.n * cell[1] + nn * orbital] = c64::new(1.0, 0.0);
472        self.to_k(&mut psi);
473        if let Some((lo, hi)) = window {
474            let a0 = (self.potential)(0.0);
475            self.per_k(&mut psi, |k, v| {
476                let bands = self.bands(&self.kinetic(k, a0));
477                let mut out = vec![c64::new(0.0, 0.0); v.len()];
478                for (e, g, u) in bands {
479                    if e >= lo && e <= hi {
480                        let overlap: c64 = g.iter().zip(&u).map(|(&c, x)| x.conj() * v[c]).sum();
481                        g.iter().zip(&u).for_each(|(&c, x)| out[c] += overlap * x);
482                    }
483                }
484                v.copy_from_slice(&out);
485            });
486            let norm = (psi.iter().map(|z| z.norm_sqr()).sum::<f64>() / nn as f64).sqrt();
487            assert!(norm > 0.0, "no band state in the window");
488            psi.iter_mut().for_each(|z| *z /= norm);
489        }
490        psi
491    }
492
493    /// One step `ψ(t) → ψ(t + dt)` of a state in k space (no site-dependent term).
494    fn kinetic_step(&self, psi_k: &mut [c64], t: f64, dt: f64) {
495        let a = (self.potential)(t + 0.5 * dt);
496        self.per_k(psi_k, |k, v| {
497            let u = self.propagator(&self.kinetic(k, a), dt);
498            let w: Vec<c64> = (0..v.len()).map(|i| (0..v.len()).map(|j| u[(i, j)] * v[j]).sum()).collect();
499            v.copy_from_slice(&w);
500        });
501    }
502
503    /// Evolves each start state (k space, e.g. from [`Self::filled`] or [`Self::localized`]) from
504    /// `t = 0` and records the observables, averaged over the start states.
505    pub fn evolve(&self, starts: &[Vec<c64>], ev: &Evolution) -> Record {
506        assert!(!starts.is_empty() && ev.every > 0);
507        let nn = self.n * self.n;
508        let half: Vec<(usize, CMat)> = self.local.iter().map(|(s, v)| (*s, exp_i(v, 0.5 * ev.dt))).collect();
509        let reference = {
510            let mut x = starts[0].clone();
511            self.to_x(&mut x);
512            let (best, _) = x
513                .iter()
514                .enumerate()
515                .fold((0, -1.0), |(b, m), (i, z)| if z.norm_sqr() > m { (i, z.norm_sqr()) } else { (b, m) });
516            best
517        };
518        let mut record = Record::default();
519        for (s, start) in starts.iter().enumerate() {
520            let mut psi = start.clone();
521            let in_x = !self.local.is_empty();
522            if in_x {
523                self.to_x(&mut psi);
524            }
525            let mut row = 0;
526            for step in 0..=ev.steps {
527                let t = step as f64 * ev.dt;
528                if step % ev.every == 0 {
529                    let (mut k, mut x) = (psi.clone(), psi.clone());
530                    if in_x {
531                        self.to_k(&mut k)
532                    } else {
533                        self.to_x(&mut x)
534                    }
535                    let m = self.measure(&k, &x, t, ev, reference);
536                    if s == 0 {
537                        record.times.push(t);
538                        record.norm.push(0.0);
539                        record.current.push([0.0; 2]);
540                        record.excited.push(0.0);
541                        record.width.push(0.0);
542                        if ev.densities {
543                            record.densities.push(vec![0.0; nn * self.comps]);
544                        }
545                    }
546                    record.norm[row] += m.0;
547                    record.current[row][0] += m.1[0];
548                    record.current[row][1] += m.1[1];
549                    record.excited[row] += m.2;
550                    record.width[row] += m.3;
551                    if ev.densities {
552                        record.densities[row].iter_mut().zip(&x).for_each(|(d, z)| *d += z.norm_sqr());
553                    }
554                    row += 1;
555                }
556                if step == ev.steps {
557                    break;
558                }
559                if in_x {
560                    apply_local(&mut psi, nn, self.comps, &half);
561                    self.to_k(&mut psi);
562                    self.kinetic_step(&mut psi, t, ev.dt);
563                    self.to_x(&mut psi);
564                    apply_local(&mut psi, nn, self.comps, &half);
565                } else {
566                    self.kinetic_step(&mut psi, t, ev.dt);
567                }
568            }
569        }
570        let count = starts.len() as f64;
571        record
572            .norm
573            .iter_mut()
574            .chain(record.excited.iter_mut())
575            .chain(record.width.iter_mut())
576            .for_each(|x| *x /= count);
577        record.current.iter_mut().flatten().for_each(|x| *x /= count);
578        record.densities.iter_mut().flatten().for_each(|x| *x /= count);
579        record
580    }
581
582    /// `(norm, current density, excited density, width)` of a state given in k and x space.
583    fn measure(
584        &self,
585        psi_k: &[c64],
586        psi_x: &[c64],
587        t: f64,
588        ev: &Evolution,
589        reference: usize,
590    ) -> (f64, [f64; 2], f64, f64) {
591        let nn = (self.n * self.n) as f64;
592        let a = (self.potential)(t);
593        let (area, (ex, ey)) = (self.area(), ([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]));
594        let expectation = |m: &CMat, v: &[c64]| -> f64 {
595            (0..v.len())
596                .map(|i| (0..v.len()).map(|j| v[i].conj() * m[(i, j)] * v[j]).sum::<c64>())
597                .sum::<c64>()
598                .re
599        };
600        let (jx, jy, excited): (f64, f64, f64) = self
601            .sum_k(psi_k, |k, v| {
602                let (vx, vy) = (self.velocity(k, a, ex), self.velocity(k, a, ey));
603                let up: f64 = self
604                    .bands(&self.kinetic(k, a))
605                    .into_iter()
606                    .filter(|(e, g, _)| *e > ev.fermi && self.in_sector(g))
607                    .map(|(_, g, u)| g.iter().zip(&u).map(|(&c, x)| x.conj() * v[c]).sum::<c64>().norm_sqr())
608                    .sum();
609                Triple(expectation(&vx, v), expectation(&vy, v), up)
610            })
611            .into();
612        let norm = psi_x.iter().map(|z| z.norm_sqr()).sum::<f64>();
613        // Positions around the reference orbital, nearest image on the torus.
614        let n = self.n as i64;
615        let (rx, ry, rc) = (
616            (reference % (n * n) as usize) as i64 % n,
617            (reference % (n * n) as usize) as i64 / n,
618            reference / (n * n) as usize,
619        );
620        let wrap = |d: i64| (d + n / 2).rem_euclid(n) - n / 2;
621        let [a1, a2] = self.vectors;
622        let (mut m1, mut m2) = ([0.0; 2], 0.0);
623        for (i, z) in psi_x.iter().enumerate() {
624            let p = z.norm_sqr();
625            if p == 0.0 {
626                continue;
627            }
628            let (cell, c) = (i % (n * n) as usize, i / (n * n) as usize);
629            let (dx, dy) = (wrap(cell as i64 % n - rx) as f64, wrap(cell as i64 / n - ry) as f64);
630            let r = [
631                dx * a1[0] + dy * a2[0] + self.offsets[c][0] - self.offsets[rc][0],
632                dx * a1[1] + dy * a2[1] + self.offsets[c][1] - self.offsets[rc][1],
633            ];
634            m1[0] += p * r[0];
635            m1[1] += p * r[1];
636            m2 += p * (r[0] * r[0] + r[1] * r[1]);
637        }
638        let width = if norm > 0.0 {
639            (m2 / norm - (m1[0] * m1[0] + m1[1] * m1[1]) / (norm * norm)).max(0.0).sqrt()
640        } else {
641            0.0
642        };
643        (norm, [jx / (nn * area), jy / (nn * area)], excited / (nn * area), width)
644    }
645}
646
647/// Three sums at once.
648struct Triple(f64, f64, f64);
649
650impl std::iter::Sum for Triple {
651    fn sum<I: Iterator<Item = Triple>>(iter: I) -> Self {
652        iter.fold(Triple(0.0, 0.0, 0.0), |a, b| Triple(a.0 + b.0, a.1 + b.1, a.2 + b.2))
653    }
654}
655
656impl From<Triple> for (f64, f64, f64) {
657    fn from(t: Triple) -> Self {
658        (t.0, t.1, t.2)
659    }
660}
661
662/// `m[r0.., c0..] += factor · b`.
663fn add_block(m: &mut CMat, r0: usize, c0: usize, b: &CMat, factor: c64) {
664    for i in 0..b.nrows() {
665        for j in 0..b.ncols() {
666            m[(r0 + i, c0 + j)] += factor * b[(i, j)];
667        }
668    }
669}