1pub mod accelerated;
13pub mod driven;
14pub mod torus;
15
16pub use driven::{Driven, VectorPotential, constant_force};
17pub use torus::{Evolution, Record, Torus};
18
19use caroli_model::{CMat, c64};
20use caroli_torus::Fft2;
21use faer::Side;
22
23pub fn exp_i(h: &CMat, tau: f64) -> CMat {
25 let evd = h.self_adjoint_eigen(Side::Lower).expect("Hermitian eigenproblem");
26 let (s, u) = (evd.S(), evd.U());
27 let n = h.nrows();
28 let phases: Vec<c64> = (0..n).map(|k| c64::from_polar(1.0, -s[k].re * tau)).collect();
29 CMat::from_fn(n, n, |i, j| (0..n).map(|k| u[(i, k)] * phases[k] * u[(j, k)].conj()).sum())
30}
31
32pub fn bessel_j(x: f64, count: usize) -> Vec<f64> {
35 if x == 0.0 {
36 return (0..count).map(|n| if n == 0 { 1.0 } else { 0.0 }).collect();
37 }
38 let ax = x.abs();
39 if ax < 1e-30 {
40 let mut term = 1.0;
42 return (0..count)
43 .map(|n| {
44 if n > 0 {
45 term *= x / 2.0 / n as f64;
46 }
47 term
48 })
49 .collect();
50 }
51 let top = count.max(ax as usize) + 30 + (10.0 * ax.cbrt()) as usize;
52 let mut j = vec![0.0; top + 2];
53 j[top] = 1e-300;
54 for n in (1..=top).rev() {
55 j[n - 1] = 2.0 * n as f64 / ax * j[n] - j[n + 1];
56 if j[n - 1].abs() > 1e250 {
57 j.iter_mut().for_each(|v| *v *= 1e-250);
58 }
59 }
60 let norm = j[0] + 2.0 * j.iter().skip(2).step_by(2).sum::<f64>();
61 j.truncate(count);
62 j.iter_mut().enumerate().for_each(|(n, v)| {
63 *v /= norm;
64 if x < 0.0 && n % 2 == 1 {
66 *v = -*v;
67 }
68 });
69 j
70}
71
72#[derive(Clone, Debug)]
75pub struct Chebyshev {
76 pub coefficients: Vec<c64>,
78}
79
80impl Chebyshev {
81 pub fn new(dt: f64, centre: f64, half_width: f64, tol: f64) -> Self {
83 let tau = half_width * dt;
84 let guess = (1.3 * tau.abs()) as usize + 40 + (8.0 * tau.abs().cbrt()) as usize;
85 let j = bessel_j(tau, guess);
86 let last = j.iter().rposition(|v| v.abs() > tol).unwrap_or(0);
87 let phase = c64::from_polar(1.0, -centre * dt);
88 let coefficients = (0..=last.max(1))
89 .map(|n| {
90 let minus_i_n =
91 [c64::new(1.0, 0.0), c64::new(0.0, -1.0), c64::new(-1.0, 0.0), c64::new(0.0, 1.0)][n % 4];
92 phase * minus_i_n * if n == 0 { j[0] } else { 2.0 * j[n] }
93 })
94 .collect();
95 Self { coefficients }
96 }
97
98 pub fn step(&self, apply: impl Fn(&[c64], &mut [c64]), psi: &mut [c64]) {
101 use rayon::prelude::*;
102 const CHUNK: usize = 1 << 14;
103 let c = &self.coefficients;
104 let n = psi.len();
105 let mut t0 = psi.to_vec();
106 let mut t1 = vec![c64::new(0.0, 0.0); n];
107 apply(&t0, &mut t1);
108 psi.par_chunks_mut(CHUNK).zip(t0.par_chunks(CHUNK)).zip(t1.par_chunks(CHUNK)).for_each(
109 |((p, a), b)| {
110 for ((p, a), b) in p.iter_mut().zip(a).zip(b) {
111 *p = c[0] * a + c[1] * b;
112 }
113 },
114 );
115 let mut t2 = vec![c64::new(0.0, 0.0); n];
116 for &ck in &c[2..] {
117 apply(&t1, &mut t2);
118 psi.par_chunks_mut(CHUNK).zip(t2.par_chunks_mut(CHUNK)).zip(t0.par_chunks(CHUNK)).for_each(
119 |((p, next), prev)| {
120 for ((p, x), q) in p.iter_mut().zip(next.iter_mut()).zip(prev) {
121 *x = 2.0 * *x - q;
122 *p += ck * *x;
123 }
124 },
125 );
126 std::mem::swap(&mut t0, &mut t1);
128 std::mem::swap(&mut t1, &mut t2);
129 }
130 }
131}
132
133pub trait TimeDependent {
135 fn apply(&self, stages: &[(f64, f64)], x: &[c64], y: &mut [c64]);
137 fn bounds(&self) -> (f64, f64);
139}
140
141pub fn magnus4_step(h: &impl TimeDependent, psi: &mut [c64], t: f64, dt: f64, tol: f64) {
147 let s3 = 3f64.sqrt();
148 let (t1, t2) = (t + (0.5 - s3 / 6.0) * dt, t + (0.5 + s3 / 6.0) * dt);
149 let (a1, a2) = ((3.0 - 2.0 * s3) / 12.0, (3.0 + 2.0 * s3) / 12.0);
150 let (lo, hi) = h.bounds();
151 for stages in [[(t1, a2), (t2, a1)], [(t1, a1), (t2, a2)]] {
152 let (blo, bhi) = stages
154 .iter()
155 .fold((0.0, 0.0), |(l, u), &(_, w)| (l + (w * lo).min(w * hi), u + (w * lo).max(w * hi)));
156 let (centre, half) = ((bhi + blo) / 2.0, ((bhi - blo) / 2.0 * 1.01).max(1e-300));
157 let cheb = Chebyshev::new(dt, centre, half, tol);
158 cheb.step(
159 |x, y| {
160 h.apply(&stages, x, y);
161 y.iter_mut().zip(x).for_each(|(y, x)| *y = (*y - centre * x) / half);
162 },
163 psi,
164 );
165 }
166}
167
168pub fn apply_local(psi: &mut [c64], nn: usize, comps: usize, blocks: &[(usize, CMat)]) {
170 let mut tmp = vec![c64::new(0.0, 0.0); comps];
171 for (site, b) in blocks {
172 for (j, t) in tmp.iter_mut().enumerate() {
173 *t = (0..comps).map(|i| b[(j, i)] * psi[site + nn * i]).sum();
174 }
175 for (j, t) in tmp.iter().enumerate() {
176 psi[site + nn * j] = *t;
177 }
178 }
179}
180
181pub fn apply_k(psi_k: &mut [c64], comps: usize, blocks: &[CMat]) {
183 let nn = blocks.len();
184 let mut tmp = vec![c64::new(0.0, 0.0); comps];
185 for (k, b) in blocks.iter().enumerate() {
186 for (j, t) in tmp.iter_mut().enumerate() {
187 *t = (0..comps).map(|i| b[(j, i)] * psi_k[k + nn * i]).sum();
188 }
189 for (j, t) in tmp.iter().enumerate() {
190 psi_k[k + nn * j] = *t;
191 }
192 }
193}
194
195#[derive(Clone, Debug)]
197pub struct SplitOperator {
198 pub n: usize,
200 pub comps: usize,
202 pub half_potential: Vec<(usize, CMat)>,
204 fft: Fft2,
205}
206
207impl SplitOperator {
208 pub fn new(n: usize, comps: usize, v: &[(usize, CMat)], dt: f64) -> Self {
211 let mut summed: std::collections::BTreeMap<usize, CMat> = std::collections::BTreeMap::new();
212 for (s, b) in v {
213 summed.entry(*s).and_modify(|m| *m += b).or_insert_with(|| b.clone());
214 }
215 let half_potential = summed.into_iter().map(|(s, b)| (s, exp_i(&b, dt / 2.0))).collect();
216 Self { n, comps, half_potential, fft: Fft2::new(n) }
217 }
218
219 pub fn with_half_steps(n: usize, comps: usize, half_potential: Vec<(usize, CMat)>) -> Self {
221 Self { n, comps, half_potential, fft: Fft2::new(n) }
222 }
223
224 pub fn to_k(&self, psi: &mut [c64]) {
226 psi.chunks_exact_mut(self.n * self.n).for_each(|c| self.fft.forward(c));
227 }
228
229 pub fn to_x(&self, psi: &mut [c64]) {
231 let norm = (self.n * self.n) as f64;
232 psi.chunks_exact_mut(self.n * self.n).for_each(|c| {
233 self.fft.backward(c);
234 c.iter_mut().for_each(|z| *z /= norm);
235 });
236 }
237
238 pub fn step(&self, psi_x: &mut [c64], kinetic_step: &[CMat]) {
240 let nn = self.n * self.n;
241 apply_local(psi_x, nn, self.comps, &self.half_potential);
242 self.to_k(psi_x);
243 apply_k(psi_x, self.comps, kinetic_step);
244 self.to_x(psi_x);
245 apply_local(psi_x, nn, self.comps, &self.half_potential);
246 }
247}
248
249#[cfg(test)]
250mod tests {
251 use super::*;
252
253 #[test]
256 fn magnus4_is_fourth_order() {
257 struct Driven(CMat, CMat);
258 #[allow(clippy::needless_range_loop)] impl TimeDependent for Driven {
260 fn apply(&self, stages: &[(f64, f64)], x: &[c64], y: &mut [c64]) {
261 let n = x.len();
262 y.iter_mut().for_each(|v| *v = c64::new(0.0, 0.0));
263 for &(t, w) in stages {
264 let f = (1.3 * t).cos();
265 for i in 0..n {
266 for j in 0..n {
267 y[i] += w * (self.0[(i, j)] + f * self.1[(i, j)]) * x[j];
268 }
269 }
270 }
271 }
272 fn bounds(&self) -> (f64, f64) {
273 let r = |m: &CMat| {
274 (0..m.nrows())
275 .map(|i| (0..m.ncols()).map(|j| m[(i, j)].norm()).sum::<f64>())
276 .fold(0.0, f64::max)
277 };
278 let b = r(&self.0) + r(&self.1);
279 (-b, b)
280 }
281 }
282 let n = 6;
283 let herm = |seed: f64| {
284 let a = CMat::from_fn(n, n, |i, j| {
285 c64::new((seed * (i * 7 + j) as f64).sin(), (seed * (i + 3 * j) as f64).cos())
286 });
287 CMat::from_fn(n, n, |i, j| (a[(i, j)] + a[(j, i)].conj()) * 0.5)
288 };
289 let h = Driven(herm(0.37), herm(1.11));
290 let psi0: Vec<c64> =
291 (0..n).map(|i| c64::new(1.0 / (n as f64).sqrt(), 0.0) * c64::from_polar(1.0, i as f64)).collect();
292 let evolve = |dt: f64| {
293 let mut psi = psi0.clone();
294 let steps = (2.0 / dt).round() as usize;
295 for k in 0..steps {
296 magnus4_step(&h, &mut psi, k as f64 * dt, dt, 1e-15);
297 }
298 psi
299 };
300 let reference = evolve(0.0125);
301 let err =
302 |dt: f64| evolve(dt).iter().zip(&reference).map(|(a, b)| (a - b).norm_sqr()).sum::<f64>().sqrt();
303 let (e1, e2) = (err(0.2), err(0.1));
304 assert!(e1 / e2 > 12.0 && e1 / e2 < 20.0, "errors {e1:e}, {e2:e}");
305 let norm: f64 = reference.iter().map(|z| z.norm_sqr()).sum();
306 assert!((norm - 1.0).abs() < 1e-13);
307 }
308
309 #[test]
311 fn split_operator_sums_duplicate_sites() {
312 let m = |a: f64, b: f64| {
313 CMat::from_fn(2, 2, |i, j| {
314 c64::new(if i == j { a * if i == 0 { 1.0 } else { -1.0 } } else { b }, 0.0)
315 })
316 };
317 let twice = SplitOperator::new(4, 2, &[(5, m(0.0, 0.8)), (5, m(0.6, 0.0))], 0.1);
318 let once = SplitOperator::new(4, 2, &[(5, m(0.6, 0.8))], 0.1);
319 assert_eq!(twice.half_potential.len(), 1);
320 assert!((&twice.half_potential[0].1 - &once.half_potential[0].1).norm_max() < 1e-15);
321 }
322
323 #[test]
324 fn bessel_values() {
325 let j = bessel_j(1.0, 6);
327 assert!((j[0] - 0.765_197_686_557_966_6).abs() < 1e-15);
328 assert!((j[1] - 0.440_050_585_744_933_5).abs() < 1e-15);
329 assert!((j[5] - 2.497_577_302_112_344e-4).abs() < 1e-17);
330 let tiny = bessel_j(1e-60, 3);
331 assert!(
332 (tiny[0] - 1.0).abs() < 1e-15
333 && (tiny[1] - 5e-61).abs() < 1e-75
334 && (tiny[2] - 1.25e-121).abs() < 1e-135
335 );
336 let j = bessel_j(10.0, 13);
337 assert!((j[0] + 0.245_935_764_451_348_3).abs() < 1e-14);
338 assert!((j[12] - 6.337_025_497_015_6e-2).abs() < 1e-13);
339 }
340
341 #[test]
344 fn chebyshev_matches_exact_exponential() {
345 use caroli_lattice::Region;
346 use caroli_model::presets::{BhzParams, bhz};
347 let model = bhz(BhzParams { lambda: 0.2, ..BhzParams::default() });
348 let region = Region::cuboid(model.lattice(), [5, 4, 0]);
349 let h = model.sparse_hamiltonian(®ion);
350 let (lo, hi) = h.spectral_bounds();
351 let (centre, half) = ((hi + lo) / 2.0, (hi - lo) / 2.0 * 1.01);
352 let scaled = h.rescaled(centre, half);
353 let dense = h.to_dense();
354 let psi0: Vec<c64> =
355 (0..h.n).map(|i| c64::new((0.7 * i as f64).cos(), (0.2 * i as f64).sin())).collect();
356 for dt in [0.05, 7.5] {
357 let mut psi = psi0.clone();
358 Chebyshev::new(dt, centre, half, 1e-15).step(|x, y| scaled.apply(x, y), &mut psi);
359 let u = exp_i(&dense, dt);
360 let exact: Vec<c64> = (0..h.n).map(|r| (0..h.n).map(|c| u[(r, c)] * psi0[c]).sum()).collect();
361 let err = psi.iter().zip(&exact).map(|(a, b)| (a - b).norm()).fold(0.0, f64::max);
362 assert!(err < 1e-12, "dt {dt}: {err:e}");
363 }
364 }
365
366 #[test]
368 fn exponential_of_pauli() {
369 let sx = CMat::from_fn(2, 2, |i, j| if i != j { c64::new(1.0, 0.0) } else { c64::new(0.0, 0.0) });
370 let u = exp_i(&sx, 0.7);
371 assert!((u[(0, 0)] - c64::new(0.7f64.cos(), 0.0)).norm() < 1e-14);
372 assert!((u[(0, 1)] - c64::new(0.0, -0.7f64.sin())).norm() < 1e-14);
373 }
374
375 #[test]
378 fn unitary_steps() {
379 let n = 8;
380 let prop = SplitOperator::new(n, 1, &[(3, CMat::from_fn(1, 1, |_, _| c64::new(0.4, 0.0)))], 0.05);
381 let kin: Vec<CMat> = (0..n * n)
382 .map(|k| exp_i(&CMat::from_fn(1, 1, |_, _| c64::new((k as f64 * 0.1).cos(), 0.0)), 0.05))
383 .collect();
384 let mut psi: Vec<c64> =
385 (0..n * n).map(|i| c64::new((i as f64).sin(), (0.5 * i as f64).cos())).collect();
386 let norm0: f64 = psi.iter().map(|z| z.norm_sqr()).sum();
387 for _ in 0..50 {
388 prop.step(&mut psi, &kin);
389 }
390 let norm: f64 = psi.iter().map(|z| z.norm_sqr()).sum();
391 assert!((norm - norm0).abs() < 1e-11 * norm0);
392 }
393}