1use caroli_lattice::{Cell, Lattice, Region, Site, Vec3};
10use faer::Mat;
11pub use faer::c64;
12
13pub mod continuum;
14pub mod gamma;
15pub mod presets;
16pub mod sparse;
17
18pub use sparse::SparseMatrix;
19
20pub type CMat = Mat<c64>;
22
23pub trait IntoMatrix {
25 fn into_matrix(self) -> CMat;
27}
28
29impl IntoMatrix for CMat {
30 fn into_matrix(self) -> CMat {
31 self
32 }
33}
34
35impl IntoMatrix for &CMat {
36 fn into_matrix(self) -> CMat {
37 self.clone()
38 }
39}
40
41impl IntoMatrix for f64 {
42 fn into_matrix(self) -> CMat {
43 CMat::from_fn(1, 1, |_, _| c64::new(self, 0.0))
44 }
45}
46
47impl IntoMatrix for c64 {
48 fn into_matrix(self) -> CMat {
49 CMat::from_fn(1, 1, |_, _| self)
50 }
51}
52
53pub mod pauli {
55 use crate::{CMat, c64};
56
57 fn matrix(m: [[c64; 2]; 2]) -> CMat {
58 CMat::from_fn(2, 2, |i, j| m[i][j])
59 }
60
61 const O: c64 = c64::new(0.0, 0.0);
62 const L: c64 = c64::new(1.0, 0.0);
63 const I: c64 = c64::new(0.0, 1.0);
64
65 pub fn s0() -> CMat {
67 matrix([[L, O], [O, L]])
68 }
69
70 pub fn sx() -> CMat {
72 matrix([[O, L], [L, O]])
73 }
74
75 pub fn sy() -> CMat {
77 matrix([[O, -I], [I, O]])
78 }
79
80 pub fn sz() -> CMat {
82 matrix([[L, O], [O, -L]])
83 }
84
85 pub fn kron(a: &CMat, b: &CMat) -> CMat {
87 let (p, q) = (b.nrows(), b.ncols());
88 CMat::from_fn(a.nrows() * p, a.ncols() * q, |i, j| a[(i / p, j / q)] * b[(i % p, j % q)])
89 }
90}
91
92#[derive(Clone, Debug)]
95pub struct Hopping {
96 pub from: usize,
98 pub to: usize,
100 pub offset: Cell,
102 pub matrix: CMat,
104}
105
106#[derive(Clone, Debug)]
110pub struct Bond {
111 pub from: usize,
113 pub to: usize,
115 pub images: Vec<i64>,
118 pub displacement: Vec3,
120 pub matrix: CMat,
122}
123
124pub trait OnSite: Send + Sync {
126 fn matrix(&self, site: &Site) -> Option<CMat>;
128}
129
130impl<F: Fn(&Site) -> Option<CMat> + Send + Sync> OnSite for F {
131 fn matrix(&self, site: &Site) -> Option<CMat> {
132 self(site)
133 }
134}
135
136pub trait HoppingTerm: Send + Sync {
141 fn matrix(&self, from: &Site, to: &Site, t: &CMat) -> Option<CMat>;
144}
145
146impl<F: Fn(&Site, &Site, &CMat) -> Option<CMat> + Send + Sync> HoppingTerm for F {
147 fn matrix(&self, from: &Site, to: &Site, t: &CMat) -> Option<CMat> {
148 self(from, to, t)
149 }
150}
151
152pub trait Peierls: Send + Sync {
155 fn phase(&self, to: Vec3, from: Vec3) -> f64;
158}
159
160impl<F: Fn(Vec3, Vec3) -> f64 + Send + Sync> Peierls for F {
161 fn phase(&self, to: Vec3, from: Vec3) -> f64 {
162 self(to, from)
163 }
164}
165
166pub mod gauge {
176 use caroli_lattice::Vec3;
177
178 pub fn landau_x(b: f64) -> impl Fn(Vec3, Vec3) -> f64 + Send + Sync + Clone {
180 move |ri, rj| -b * 0.5 * (ri[1] + rj[1]) * (ri[0] - rj[0])
181 }
182
183 pub fn landau_y(b: f64) -> impl Fn(Vec3, Vec3) -> f64 + Send + Sync + Clone {
185 move |ri, rj| b * 0.5 * (ri[0] + rj[0]) * (ri[1] - rj[1])
186 }
187
188 pub fn symmetric(b: f64) -> impl Fn(Vec3, Vec3) -> f64 + Send + Sync + Clone {
190 move |ri, rj| {
191 let (xm, ym) = (0.5 * (ri[0] + rj[0]), 0.5 * (ri[1] + rj[1]));
192 0.5 * b * (-ym * (ri[0] - rj[0]) + xm * (ri[1] - rj[1]))
193 }
194 }
195
196 pub fn landau_x_to_along(b: f64, d: Vec3) -> impl Fn(Vec3) -> f64 + Send + Sync + Clone {
201 let norm = d[0].hypot(d[1]);
202 let (dx, dy) = if norm > 0.0 { (d[0] / norm, d[1] / norm) } else { (1.0, 0.0) };
204 move |r| 0.5 * b * (dx * dy * r[0] * r[0] + 2.0 * dy * dy * r[0] * r[1] - dx * dy * r[1] * r[1])
206 }
207}
208
209pub struct Model {
211 lattice: Lattice,
212 onsite: Vec<CMat>,
213 hoppings: Vec<Hopping>,
214 extra: Vec<Box<dyn OnSite>>,
215 hopping_terms: Vec<Box<dyn HoppingTerm>>,
216 peierls: Option<Box<dyn Peierls>>,
217 field: Option<f64>,
219}
220
221impl Model {
222 pub fn new(lattice: Lattice) -> Self {
224 let onsite = lattice.sublattices().iter().map(|s| CMat::zeros(s.orbitals, s.orbitals)).collect();
225 Self {
226 lattice,
227 onsite,
228 hoppings: Vec::new(),
229 extra: Vec::new(),
230 hopping_terms: Vec::new(),
231 peierls: None,
232 field: None,
233 }
234 }
235
236 pub fn lattice(&self) -> &Lattice {
238 &self.lattice
239 }
240
241 pub fn hoppings(&self) -> &[Hopping] {
244 &self.hoppings
245 }
246
247 pub fn onsite(mut self, sub: usize, matrix: impl IntoMatrix) -> Self {
249 let matrix = matrix.into_matrix();
250 let n = self.lattice.sublattices()[sub].orbitals;
251 assert_eq!((matrix.nrows(), matrix.ncols()), (n, n), "on-site matrix of sublattice {sub}");
252 self.onsite[sub] = matrix;
253 self
254 }
255
256 pub fn hopping(mut self, from: usize, to: usize, offset: Cell, matrix: impl IntoMatrix) -> Self {
259 let matrix = matrix.into_matrix();
260 let subs = self.lattice.sublattices();
261 assert_eq!((matrix.nrows(), matrix.ncols()), (subs[from].orbitals, subs[to].orbitals));
262 assert!(offset != [0; 3] || from != to, "an on-site term is not a hopping");
263 self.hoppings.push(Hopping { from, to, offset, matrix });
264 self
265 }
266
267 pub fn with_onsite_term(mut self, term: impl OnSite + 'static) -> Self {
269 self.extra.push(Box::new(term));
270 self
271 }
272
273 pub fn with_hopping_term(mut self, term: impl HoppingTerm + 'static) -> Self {
276 self.hopping_terms.push(Box::new(term));
277 self
278 }
279
280 fn hopping_matrix<'a>(&self, hop: &'a Hopping, from: &Site, to: &Site) -> std::borrow::Cow<'a, CMat> {
283 let mut m = std::borrow::Cow::Borrowed(&hop.matrix);
284 for term in &self.hopping_terms {
285 if let Some(v) = term.matrix(from, to, &m) {
286 assert_eq!(
287 (v.nrows(), v.ncols()),
288 (hop.matrix.nrows(), hop.matrix.ncols()),
289 "hopping term of the wrong size"
290 );
291 m = std::borrow::Cow::Owned(v);
292 }
293 }
294 m
295 }
296
297 pub fn with_peierls(mut self, phase: impl Peierls + 'static) -> Self {
300 self.peierls = Some(Box::new(phase));
301 self.field = None;
302 self
303 }
304
305 pub fn with_field(mut self, b: f64) -> Self {
309 self.peierls = Some(Box::new(gauge::landau_x(b)));
310 self.field = Some(b);
311 self
312 }
313
314 pub fn field(&self) -> Option<f64> {
316 self.field
317 }
318
319 pub fn sublattice_onsite(&self, sub: usize) -> &CMat {
321 &self.onsite[sub]
322 }
323
324 pub fn onsite_terms(&self, site: &Site) -> Option<CMat> {
327 let mut sum: Option<CMat> = None;
328 for term in &self.extra {
329 if let Some(v) = term.matrix(site) {
330 match &mut sum {
331 Some(s) => *s += v,
332 None => sum = Some(v),
333 }
334 }
335 }
336 sum
337 }
338
339 pub fn has_uniform_hoppings(&self) -> bool {
342 self.hopping_terms.is_empty() && self.peierls.is_none()
343 }
344
345 pub fn bonds(&self, region: &Region, periods: &[Cell]) -> Vec<Bond> {
350 let images = (!periods.is_empty()).then(|| Images::new(region, periods));
351 let mut out = Vec::new();
352 for (i, site) in region.sites().iter().enumerate() {
353 let ri = self.lattice.position(*site);
354 for hop in &self.hoppings {
355 let ends =
356 [(hop.from == site.sub, 1, hop.to, false), (hop.to == site.sub, -1, hop.from, true)];
357 for (applies, sign, sub, adjoint) in ends {
358 if !applies {
359 continue;
360 }
361 let partner = shifted(site, hop.offset, sign, sub);
362 let (j, n) = match &images {
363 None => match region.index_of(&partner) {
364 Some(j) => (j, Vec::new()),
365 None => continue,
366 },
367 Some(images) => match images.locate(&partner) {
368 Some(found) => found,
369 None => continue,
370 },
371 };
372 let rj = self.lattice.position(partner);
373 let m = if adjoint {
374 self.hopping_matrix(hop, &partner, site).adjoint().to_owned()
375 } else {
376 self.hopping_matrix(hop, site, &partner).into_owned()
377 };
378 let factor = self.phased(c64::new(1.0, 0.0), site, &partner);
379 out.push(Bond {
380 from: i,
381 to: j,
382 images: n,
383 displacement: [rj[0] - ri[0], rj[1] - ri[1], rj[2] - ri[2]],
384 matrix: CMat::from_fn(m.nrows(), m.ncols(), |a, b| factor * m[(a, b)]),
385 });
386 }
387 }
388 }
389 out
390 }
391
392 fn phased(&self, factor: c64, i: &Site, j: &Site) -> c64 {
394 match &self.peierls {
395 None => factor,
396 Some(p) => {
397 let (s, c) = p.phase(self.lattice.position(*i), self.lattice.position(*j)).sin_cos();
398 factor * c64::new(c, s)
399 }
400 }
401 }
402
403 pub fn onsite_matrix(&self, site: &Site) -> CMat {
405 let mut m = self.onsite[site.sub].clone();
406 for term in &self.extra {
407 if let Some(v) = term.matrix(site) {
408 m += v;
409 }
410 }
411 m
412 }
413
414 pub fn hamiltonian(&self, region: &Region) -> CMat {
416 let mut h = CMat::zeros(region.orbitals(), region.orbitals());
417 self.build(&mut h, region, &[], &[]);
418 h
419 }
420
421 pub fn bloch_hamiltonian(&self, region: &Region, periods: &[Cell], phases: &[f64]) -> CMat {
425 let mut h = CMat::zeros(region.orbitals(), region.orbitals());
426 self.build(&mut h, region, periods, phases);
427 h
428 }
429
430 pub fn sparse_hamiltonian(&self, region: &Region) -> SparseMatrix {
433 self.sparse_bloch_hamiltonian(region, &[], &[])
434 }
435
436 pub fn sparse_bloch_hamiltonian(
438 &self,
439 region: &Region,
440 periods: &[Cell],
441 phases: &[f64],
442 ) -> SparseMatrix {
443 let mut t = Triplets(Vec::new());
444 self.build(&mut t, region, periods, phases);
445 SparseMatrix::from_triplets(region.orbitals(), t.0)
446 }
447
448 fn build(&self, h: &mut impl Sink, region: &Region, periods: &[Cell], phases: &[f64]) {
453 assert_eq!(periods.len(), phases.len());
454 for i in 0..region.len() {
455 h.block(
456 region.offset(i),
457 region.offset(i),
458 &self.onsite_matrix(®ion.sites()[i]),
459 c64::new(1.0, 0.0),
460 false,
461 );
462 }
463 if periods.is_empty() {
464 self.add_couplings_one_way(h, region, region, c64::new(1.0, 0.0));
465 return;
466 }
467 let images = Images::new(region, periods);
468 for (i, site) in region.sites().iter().enumerate() {
469 for hop in &self.hoppings {
470 let ends =
473 [(hop.from == site.sub, 1, hop.to, false), (hop.to == site.sub, -1, hop.from, true)];
474 for (applies, sign, sub, adjoint) in ends {
475 if !applies {
476 continue;
477 }
478 let partner = shifted(site, hop.offset, sign, sub);
479 if let Some((j, n)) = images.locate(&partner) {
480 let phase: f64 = n.iter().zip(phases).map(|(n, k)| *n as f64 * k).sum();
481 let (s, cs) = phase.sin_cos();
482 let factor = self.phased(c64::new(cs, s), site, &partner);
483 let m = if adjoint {
484 self.hopping_matrix(hop, &partner, site)
485 } else {
486 self.hopping_matrix(hop, site, &partner)
487 };
488 h.block(region.offset(i), region.offset(j), &m, factor, adjoint);
489 }
490 }
491 }
492 }
493 }
494
495 pub fn sparse_velocity(
501 &self,
502 region: &Region,
503 periods: &[Cell],
504 phases: &[f64],
505 direction: Vec3,
506 ) -> SparseMatrix {
507 assert_eq!(periods.len(), phases.len());
508 let mut t = Triplets(Vec::new());
509 let images = (!periods.is_empty()).then(|| Images::new(region, periods));
510 for (i, site) in region.sites().iter().enumerate() {
511 let ri = self.lattice.position(*site);
512 for hop in &self.hoppings {
513 let ends =
514 [(hop.from == site.sub, 1, hop.to, false), (hop.to == site.sub, -1, hop.from, true)];
515 for (applies, sign, sub, adjoint) in ends {
516 if !applies {
517 continue;
518 }
519 let partner = shifted(site, hop.offset, sign, sub);
520 let (j, phase) = match &images {
521 None => match region.index_of(&partner) {
522 Some(j) => (j, 0.0),
523 None => continue,
524 },
525 Some(images) => match images.locate(&partner) {
526 Some((j, n)) => (j, n.iter().zip(phases).map(|(n, k)| *n as f64 * k).sum()),
527 None => continue,
528 },
529 };
530 let rj = self.lattice.position(partner);
531 let along: f64 = (0..3).map(|c| (rj[c] - ri[c]) * direction[c]).sum();
532 let (s, cs) = phase.sin_cos();
533 let factor = self.phased(c64::new(cs, s), site, &partner) * c64::new(0.0, along);
534 let m = if adjoint {
535 self.hopping_matrix(hop, &partner, site)
536 } else {
537 self.hopping_matrix(hop, site, &partner)
538 };
539 t.block(region.offset(i), region.offset(j), &m, factor, adjoint);
540 }
541 }
542 }
543 SparseMatrix::from_triplets(region.orbitals(), t.0)
544 }
545
546 pub fn coupling(&self, a: &Region, b: &Region) -> CMat {
548 let mut h = CMat::zeros(a.orbitals(), b.orbitals());
549 self.add_couplings_one_way(&mut h, a, b, c64::new(1.0, 0.0));
550 h
551 }
552
553 fn add_couplings_one_way(&self, h: &mut impl Sink, a: &Region, b: &Region, factor: c64) {
556 for (i, site) in a.sites().iter().enumerate() {
557 for hop in &self.hoppings {
558 if hop.from == site.sub {
560 let partner = shifted(site, hop.offset, 1, hop.to);
561 if let Some(j) = b.index_of(&partner) {
562 let m = self.hopping_matrix(hop, site, &partner);
563 h.block(a.offset(i), b.offset(j), &m, self.phased(factor, site, &partner), false);
564 }
565 }
566 if hop.to == site.sub {
568 let partner = shifted(site, hop.offset, -1, hop.from);
569 if let Some(j) = b.index_of(&partner) {
570 let m = self.hopping_matrix(hop, &partner, site);
571 h.block(a.offset(i), b.offset(j), &m, self.phased(factor, site, &partner), true);
572 }
573 }
574 }
575 }
576 }
577
578 pub fn slice_blocks(&self, region: &Region, axis: usize) -> (Vec<Region>, Vec<CMat>, Vec<CMat>) {
582 let slices = region.slices(axis);
583 let diag = slices.iter().map(|s| self.hamiltonian(s)).collect();
584 let off = slices.windows(2).map(|w| self.coupling(&w[0], &w[1])).collect();
585 for hop in &self.hoppings {
586 assert!(hop.offset[axis].abs() <= 1, "hopping range exceeds one slice along axis {axis}");
587 }
588 (slices, diag, off)
589 }
590}
591
592fn shifted(site: &Site, offset: Cell, sign: i64, sub: usize) -> Site {
593 Site {
594 cell: [
595 site.cell[0] + sign * offset[0],
596 site.cell[1] + sign * offset[1],
597 site.cell[2] + sign * offset[2],
598 ],
599 sub,
600 }
601}
602
603struct Images {
610 rows: Vec<[i64; 3]>,
612 pivots: Vec<usize>,
613 w: Vec<Vec<i64>>,
615 classes: std::collections::HashMap<([i64; 3], usize), (usize, Vec<i64>)>,
617}
618
619impl Images {
620 fn new(region: &Region, periods: &[Cell]) -> Self {
621 let m = periods.len();
622 let mut rows: Vec<[i64; 3]> = periods.to_vec();
623 let mut w: Vec<Vec<i64>> = (0..m).map(|i| (0..m).map(|j| (i == j) as i64).collect()).collect();
624 let mut pivots = Vec::new();
625 let mut top = 0;
626 for col in 0..3 {
627 if top == m {
628 break;
629 }
630 while let Some(p) = (top..m).filter(|&i| rows[i][col] != 0).min_by_key(|&i| rows[i][col].abs()) {
632 rows.swap(top, p);
633 w.swap(top, p);
634 let (pivot_row, pivot_w) = (rows[top], w[top].clone());
635 let mut done = true;
636 for i in top + 1..m {
637 let f = rows[i][col] / pivot_row[col];
638 if f != 0 {
639 rows[i].iter_mut().zip(&pivot_row).for_each(|(x, y)| *x -= f * y);
640 w[i].iter_mut().zip(&pivot_w).for_each(|(x, y)| *x -= f * y);
641 }
642 done &= rows[i][col] == 0;
643 }
644 if done {
645 break;
646 }
647 }
648 if rows[top][col] != 0 {
649 if rows[top][col] < 0 {
650 rows[top].iter_mut().for_each(|x| *x = -*x);
651 w[top].iter_mut().for_each(|x| *x = -*x);
652 }
653 pivots.push(col);
654 top += 1;
655 }
656 }
657 assert_eq!(top, m, "periods must be linearly independent");
658 let mut images = Self { rows, pivots, w, classes: Default::default() };
659 for (i, site) in region.sites().iter().enumerate() {
660 let (rep, k) = images.reduce(site.cell);
661 let previous = images.classes.insert((rep, site.sub), (i, k));
662 assert!(previous.is_none(), "the region holds two sites a whole number of periods apart");
663 }
664 images
665 }
666
667 fn reduce(&self, cell: [i64; 3]) -> ([i64; 3], Vec<i64>) {
669 let mut x = cell;
670 let mut k = vec![0; self.rows.len()];
671 for (i, (&c, row)) in self.pivots.iter().zip(&self.rows).enumerate() {
672 let q = x[c].div_euclid(row[c]);
673 for a in 0..3 {
674 x[a] -= q * row[a];
675 }
676 k[i] = q;
677 }
678 (x, k)
679 }
680
681 fn locate(&self, site: &Site) -> Option<(usize, Vec<i64>)> {
684 let (rep, k) = self.reduce(site.cell);
685 let (j, kq) = self.classes.get(&(rep, site.sub))?;
686 let m = self.rows.len();
687 let n = (0..m).map(|l| (0..m).map(|i| (k[i] - kq[i]) * self.w[i][l]).sum()).collect();
688 Some((*j, n))
689 }
690}
691
692trait Sink {
694 fn block(&mut self, r0: usize, c0: usize, m: &CMat, factor: c64, adjoint: bool);
696}
697
698impl Sink for CMat {
699 fn block(&mut self, r0: usize, c0: usize, m: &CMat, factor: c64, adjoint: bool) {
700 let (rows, cols) = if adjoint { (m.ncols(), m.nrows()) } else { (m.nrows(), m.ncols()) };
701 for j in 0..cols {
702 for i in 0..rows {
703 let v = if adjoint { m[(j, i)].conj() } else { m[(i, j)] };
704 self[(r0 + i, c0 + j)] += factor * v;
705 }
706 }
707 }
708}
709
710struct Triplets(Vec<(usize, usize, c64)>);
711
712impl Sink for Triplets {
713 fn block(&mut self, r0: usize, c0: usize, m: &CMat, factor: c64, adjoint: bool) {
714 let (rows, cols) = if adjoint { (m.ncols(), m.nrows()) } else { (m.nrows(), m.ncols()) };
715 for j in 0..cols {
716 for i in 0..rows {
717 let v = if adjoint { m[(j, i)].conj() } else { m[(i, j)] };
718 if v != c64::new(0.0, 0.0) {
719 self.0.push((r0 + i, c0 + j, factor * v));
720 }
721 }
722 }
723 }
724}
725
726pub fn combine<C: Into<c64> + Copy>(terms: &[(C, &CMat)]) -> CMat {
729 let (n, m) = (terms[0].1.nrows(), terms[0].1.ncols());
730 CMat::from_fn(n, m, |i, j| terms.iter().map(|(c, mat)| (*c).into() * mat[(i, j)]).sum())
731}