1use crate::pauli::{s0, sx, sy, sz};
17use crate::{CMat, Model, c64};
18use caroli_lattice::Lattice;
19use std::collections::BTreeMap;
20
21#[derive(Debug, thiserror::Error, PartialEq)]
23pub enum ContinuumError {
24 #[error("unexpected `{0}` at position {1}")]
26 Unexpected(String, usize),
27 #[error("unknown name `{0}`")]
29 Unknown(String),
30 #[error("matrices of sizes {0} and {1} do not match")]
32 Size(usize, usize),
33 #[error("{0}")]
36 Invalid(String),
37}
38
39#[derive(Clone, Debug)]
41enum Value {
42 Number(c64),
43 Matrix(CMat),
44}
45
46impl Value {
47 fn size(&self) -> Option<usize> {
48 match self {
49 Value::Number(_) => None,
50 Value::Matrix(m) => Some(m.nrows()),
51 }
52 }
53
54 fn matrix(&self, n: usize) -> CMat {
55 match self {
56 Value::Number(x) => CMat::from_fn(n, n, |i, j| if i == j { *x } else { c64::new(0.0, 0.0) }),
57 Value::Matrix(m) => m.clone(),
58 }
59 }
60
61 fn add(&self, other: &Value) -> Result<Value, ContinuumError> {
62 Ok(match (self, other) {
63 (Value::Number(a), Value::Number(b)) => Value::Number(a + b),
64 _ => {
65 let n = size_of(self, other)?;
66 Value::Matrix(&self.matrix(n) + &other.matrix(n))
67 }
68 })
69 }
70
71 fn mul(&self, other: &Value) -> Result<Value, ContinuumError> {
72 Ok(match (self, other) {
73 (Value::Number(a), Value::Number(b)) => Value::Number(a * b),
74 (Value::Number(a), Value::Matrix(m)) | (Value::Matrix(m), Value::Number(a)) => {
75 Value::Matrix(CMat::from_fn(m.nrows(), m.ncols(), |i, j| m[(i, j)] * a))
76 }
77 (Value::Matrix(a), Value::Matrix(b)) => {
78 size_of(self, other)?;
79 Value::Matrix(a * b)
80 }
81 })
82 }
83}
84
85fn size_of(a: &Value, b: &Value) -> Result<usize, ContinuumError> {
86 match (a.size(), b.size()) {
87 (Some(x), Some(y)) if x != y => Err(ContinuumError::Size(x, y)),
88 (Some(x), _) | (_, Some(x)) => Ok(x),
89 (None, None) => Ok(1),
90 }
91}
92
93type Poly = BTreeMap<[u32; 3], Value>;
95
96fn add(a: &Poly, b: &Poly) -> Result<Poly, ContinuumError> {
97 let mut out = a.clone();
98 for (k, v) in b {
99 let sum = match out.get(k) {
100 Some(x) => x.add(v)?,
101 None => v.clone(),
102 };
103 out.insert(*k, sum);
104 }
105 Ok(out)
106}
107
108fn mul(a: &Poly, b: &Poly) -> Result<Poly, ContinuumError> {
109 let mut out = Poly::new();
110 for (ka, va) in a {
111 for (kb, vb) in b {
112 let k = [ka[0] + kb[0], ka[1] + kb[1], ka[2] + kb[2]];
113 let term = va.mul(vb)?;
114 let sum = match out.get(&k) {
115 Some(x) => x.add(&term)?,
116 None => term,
117 };
118 out.insert(k, sum);
119 }
120 }
121 Ok(out)
122}
123
124fn constant(v: Value) -> Poly {
125 Poly::from([([0, 0, 0], v)])
126}
127
128#[derive(Clone, Debug, PartialEq)]
129enum Token {
130 Number(f64),
131 Name(String),
132 Symbol(char),
133 Power,
134}
135
136fn tokens(text: &str) -> Result<Vec<(Token, usize)>, ContinuumError> {
137 let chars: Vec<char> = text.chars().collect();
138 let mut out = Vec::new();
139 let mut k = 0;
140 while k < chars.len() {
141 let c = chars[k];
142 if c.is_whitespace() {
143 k += 1;
144 } else if c.is_ascii_digit() || c == '.' {
145 let start = k;
146 while k < chars.len() && (chars[k].is_ascii_digit() || chars[k] == '.') {
147 k += 1;
148 }
149 if k < chars.len() && (chars[k] == 'e' || chars[k] == 'E') {
150 k += 1;
151 if k < chars.len() && (chars[k] == '+' || chars[k] == '-') {
152 k += 1;
153 }
154 while k < chars.len() && chars[k].is_ascii_digit() {
155 k += 1;
156 }
157 }
158 let s: String = chars[start..k].iter().collect();
159 let x = s.parse().map_err(|_| ContinuumError::Unexpected(s.clone(), start))?;
160 out.push((Token::Number(x), start));
161 } else if c.is_alphabetic() || c == '_' {
162 let start = k;
163 while k < chars.len() && (chars[k].is_alphanumeric() || chars[k] == '_') {
164 k += 1;
165 }
166 out.push((Token::Name(chars[start..k].iter().collect()), start));
167 } else if c == '*' && chars.get(k + 1) == Some(&'*') {
168 out.push((Token::Power, k));
169 k += 2;
170 } else if c == '^' {
171 out.push((Token::Power, k));
172 k += 1;
173 } else if "+-*/(),".contains(c) {
174 out.push((Token::Symbol(c), k));
175 k += 1;
176 } else {
177 return Err(ContinuumError::Unexpected(c.to_string(), k));
178 }
179 }
180 Ok(out)
181}
182
183struct Parser<'a> {
184 tokens: Vec<(Token, usize)>,
185 at: usize,
186 params: &'a [(&'a str, f64)],
187}
188
189impl Parser<'_> {
190 fn peek(&self) -> Option<&Token> {
191 self.tokens.get(self.at).map(|t| &t.0)
192 }
193
194 fn unexpected(&self) -> ContinuumError {
195 match self.tokens.get(self.at) {
196 Some((t, pos)) => ContinuumError::Unexpected(format!("{t:?}"), *pos),
197 None => ContinuumError::Invalid("unexpected end of the expression".into()),
198 }
199 }
200
201 fn expect(&mut self, c: char) -> Result<(), ContinuumError> {
202 if self.peek() == Some(&Token::Symbol(c)) {
203 self.at += 1;
204 Ok(())
205 } else {
206 Err(self.unexpected())
207 }
208 }
209
210 fn expr(&mut self) -> Result<Poly, ContinuumError> {
212 let mut acc = self.term()?;
213 while let Some(Token::Symbol(c @ ('+' | '-'))) = self.peek().cloned() {
214 self.at += 1;
215 let mut rhs = self.term()?;
216 if c == '-' {
217 rhs = mul(&rhs, &constant(Value::Number(c64::new(-1.0, 0.0))))?;
218 }
219 acc = add(&acc, &rhs)?;
220 }
221 Ok(acc)
222 }
223
224 fn term(&mut self) -> Result<Poly, ContinuumError> {
226 let mut acc = self.factor()?;
227 while let Some(Token::Symbol(c @ ('*' | '/'))) = self.peek().cloned() {
228 self.at += 1;
229 let rhs = self.factor()?;
230 acc = if c == '*' {
231 mul(&acc, &rhs)?
232 } else {
233 let divisor = match (rhs.len(), rhs.get(&[0, 0, 0])) {
234 (1, Some(Value::Number(x))) => *x,
235 _ => {
236 return Err(ContinuumError::Invalid(
237 "division by something else than a number".into(),
238 ));
239 }
240 };
241 mul(&acc, &constant(Value::Number(c64::new(1.0, 0.0) / divisor)))?
242 };
243 }
244 Ok(acc)
245 }
246
247 fn factor(&mut self) -> Result<Poly, ContinuumError> {
249 match self.peek() {
250 Some(Token::Symbol('-')) => {
251 self.at += 1;
252 let f = self.factor()?;
253 return mul(&f, &constant(Value::Number(c64::new(-1.0, 0.0))));
254 }
255 Some(Token::Symbol('+')) => {
256 self.at += 1;
257 return self.factor();
258 }
259 _ => {}
260 }
261 let base = self.atom()?;
262 if self.peek() == Some(&Token::Power) {
263 self.at += 1;
264 let power = match self.peek() {
265 Some(Token::Number(x)) if x.fract() == 0.0 && *x >= 0.0 => *x as u32,
266 _ => return Err(ContinuumError::Invalid("powers must be non-negative integers".into())),
267 };
268 self.at += 1;
269 let mut acc = constant(Value::Number(c64::new(1.0, 0.0)));
270 for _ in 0..power {
271 acc = mul(&acc, &base)?;
272 }
273 return Ok(acc);
274 }
275 Ok(base)
276 }
277
278 fn atom(&mut self) -> Result<Poly, ContinuumError> {
280 match self.peek().cloned() {
281 Some(Token::Number(x)) => {
282 self.at += 1;
283 Ok(constant(Value::Number(c64::new(x, 0.0))))
284 }
285 Some(Token::Symbol('(')) => {
286 self.at += 1;
287 let e = self.expr()?;
288 self.expect(')')?;
289 Ok(e)
290 }
291 Some(Token::Name(name)) => {
292 self.at += 1;
293 if name == "kron" {
294 self.expect('(')?;
295 let a = self.expr()?;
296 self.expect(',')?;
297 let b = self.expr()?;
298 self.expect(')')?;
299 return kron(&a, &b);
300 }
301 if let Some(f) = function(&name) {
302 self.expect('(')?;
303 let x = self.expr()?;
304 self.expect(')')?;
305 return match (x.len(), x.get(&[0, 0, 0])) {
306 (1, Some(Value::Number(v))) if v.im == 0.0 => {
307 Ok(constant(Value::Number(c64::new(f(v.re), 0.0))))
308 }
309 (0, _) => Ok(constant(Value::Number(c64::new(f(0.0), 0.0)))),
310 _ => Err(ContinuumError::Invalid(format!("{name} takes a real number"))),
311 };
312 }
313 if name == "pi" && !self.params.iter().any(|(p, _)| *p == "pi") {
314 return Ok(constant(Value::Number(c64::new(std::f64::consts::PI, 0.0))));
315 }
316 let k = |d: usize| {
317 let mut p = [0u32; 3];
318 p[d] = 1;
319 Ok(Poly::from([(p, Value::Number(c64::new(1.0, 0.0)))]))
320 };
321 match name.as_str() {
322 "k_x" | "kx" => k(0),
323 "k_y" | "ky" => k(1),
324 "k_z" | "kz" => k(2),
325 "i" => Ok(constant(Value::Number(c64::new(0.0, 1.0)))),
326 "s0" | "sigma_0" => Ok(constant(Value::Matrix(s0()))),
327 "sx" | "sigma_x" => Ok(constant(Value::Matrix(sx()))),
328 "sy" | "sigma_y" => Ok(constant(Value::Matrix(sy()))),
329 "sz" | "sigma_z" => Ok(constant(Value::Matrix(sz()))),
330 _ => match self.params.iter().find(|(p, _)| *p == name) {
331 Some((_, x)) => Ok(constant(Value::Number(c64::new(*x, 0.0)))),
332 None => Err(ContinuumError::Unknown(name)),
333 },
334 }
335 }
336 _ => Err(self.unexpected()),
337 }
338 }
339}
340
341fn function(name: &str) -> Option<fn(f64) -> f64> {
343 Some(match name {
344 "sqrt" => f64::sqrt,
345 "exp" => f64::exp,
346 "ln" => f64::ln,
347 "sin" => f64::sin,
348 "cos" => f64::cos,
349 "tan" => f64::tan,
350 "abs" => f64::abs,
351 _ => return None,
352 })
353}
354
355pub fn evaluate(expression: &str, params: &[(&str, f64)]) -> Result<CMat, ContinuumError> {
358 let c = Continuum::parse(expression, params)?;
359 if c.terms.keys().any(|p| p != &[0, 0, 0]) {
360 return Err(ContinuumError::Invalid(format!("`{expression}` depends on k")));
361 }
362 Ok(c.terms.get(&[0, 0, 0]).cloned().unwrap_or_else(|| CMat::zeros(c.orbitals, c.orbitals)))
363}
364
365pub fn number(expression: &str, params: &[(&str, f64)]) -> Result<f64, ContinuumError> {
367 let m = evaluate(expression, params)?;
368 if m.nrows() != 1 || m[(0, 0)].im != 0.0 {
369 return Err(ContinuumError::Invalid(format!("`{expression}` is not a real number")));
370 }
371 Ok(m[(0, 0)].re)
372}
373
374fn kron(a: &Poly, b: &Poly) -> Result<Poly, ContinuumError> {
376 let only = |p: &Poly| -> Result<CMat, ContinuumError> {
377 match (p.len(), p.get(&[0, 0, 0])) {
378 (1, Some(Value::Matrix(m))) => Ok(m.clone()),
379 (1, Some(Value::Number(x))) => Ok(CMat::from_fn(1, 1, |_, _| *x)),
380 _ => Err(ContinuumError::Invalid("kron takes constant matrices".into())),
381 }
382 };
383 Ok(constant(Value::Matrix(crate::pauli::kron(&only(a)?, &only(b)?))))
384}
385
386#[derive(Clone, Debug)]
388pub struct Continuum {
389 orbitals: usize,
390 terms: BTreeMap<[u32; 3], CMat>,
391}
392
393impl Continuum {
394 pub fn parse(expression: &str, params: &[(&str, f64)]) -> Result<Self, ContinuumError> {
396 let mut parser = Parser { tokens: tokens(expression)?, at: 0, params };
397 let poly = parser.expr()?;
398 if parser.at != parser.tokens.len() {
399 return Err(parser.unexpected());
400 }
401 let mut orbitals: Option<usize> = None;
402 for v in poly.values() {
403 if let Some(n) = v.size() {
404 match orbitals {
405 Some(m) if m != n => return Err(ContinuumError::Size(m, n)),
406 _ => orbitals = Some(n),
407 }
408 }
409 }
410 let orbitals = orbitals.unwrap_or(1);
411 Ok(Self { orbitals, terms: poly.iter().map(|(k, v)| (*k, v.matrix(orbitals))).collect() })
412 }
413
414 pub fn orbitals(&self) -> usize {
416 self.orbitals
417 }
418
419 pub fn dim(&self) -> usize {
421 self.terms.keys().map(|p| (0..3).rev().find(|&d| p[d] > 0).map_or(1, |d| d + 1)).max().unwrap_or(1)
422 }
423
424 pub fn discretize(&self, a: f64) -> Model {
427 self.discretize_in(a, self.dim())
428 }
429
430 pub fn discretize_in(&self, a: f64, dim: usize) -> Model {
435 assert!(
436 (1..=3).contains(&dim) && dim >= self.dim(),
437 "a lattice of {dim} dimensions cannot hold k in {} directions",
438 self.dim()
439 );
440 let n = self.orbitals;
441 let stencil = |p: u32| -> BTreeMap<i64, f64> {
443 let d1 = BTreeMap::from([(-1, -0.5 / a), (1, 0.5 / a)]);
444 let d2 = BTreeMap::from([(-1, 1.0 / (a * a)), (0, -2.0 / (a * a)), (1, 1.0 / (a * a))]);
445 let convolve = |x: &BTreeMap<i64, f64>, y: &BTreeMap<i64, f64>| {
446 let mut out = BTreeMap::new();
447 for (i, u) in x {
448 for (j, v) in y {
449 *out.entry(i + j).or_insert(0.0) += u * v;
450 }
451 }
452 out
453 };
454 let mut s = if p % 2 == 1 { d1 } else { BTreeMap::from([(0, 1.0)]) };
455 for _ in 0..p / 2 {
456 s = convolve(&s, &d2);
457 }
458 s
459 };
460 let mut blocks: BTreeMap<[i64; 3], CMat> = BTreeMap::new();
461 for (power, coefficient) in &self.terms {
462 let total: u32 = power.iter().sum();
464 let phase = (0..total).fold(c64::new(1.0, 0.0), |acc, _| acc * c64::new(0.0, -1.0));
465 let mut offsets: Vec<([i64; 3], f64)> = vec![([0, 0, 0], 1.0)];
466 for (d, &p) in power.iter().enumerate() {
467 let s = stencil(p);
468 offsets = offsets
469 .iter()
470 .flat_map(|(o, w)| {
471 s.iter().map(move |(&step, &ws)| {
472 let mut o2 = *o;
473 o2[d] += step;
474 (o2, w * ws)
475 })
476 })
477 .collect();
478 }
479 for (o, w) in offsets {
480 let block = blocks.entry(o).or_insert_with(|| CMat::zeros(n, n));
481 *block += CMat::from_fn(n, n, |i, j| coefficient[(i, j)] * phase * w);
482 }
483 }
484 let vectors: Vec<[f64; 3]> =
485 (0..dim).map(|d| std::array::from_fn(|c| if c == d { a } else { 0.0 })).collect();
486 let lattice = Lattice::new(&vectors).with_sublattice("A", [0.0; 3], n);
487 let zero = CMat::zeros(n, n);
488 let onsite = blocks.get(&[0, 0, 0]).cloned().unwrap_or_else(|| zero.clone());
489 let scale = blocks.values().map(|m| m.norm_max()).fold(0.0, f64::max).max(f64::MIN_POSITIVE);
490 assert!(
491 (&onsite - onsite.adjoint()).norm_max() <= 1e-12 * scale,
492 "the on-site matrix is not Hermitian"
493 );
494 let mut model = Model::new(lattice).onsite(0, onsite);
495 for (o, m) in &blocks {
496 let positive = o.iter().find(|&&c| c != 0).is_some_and(|&c| c > 0);
497 if !positive || m.norm_max() == 0.0 {
498 continue;
499 }
500 let back = blocks.get(&[-o[0], -o[1], -o[2]]).unwrap_or(&zero);
501 assert!(
502 (back - m.adjoint()).norm_max() <= 1e-12 * scale,
503 "the hoppings {o:?} and their opposites are not conjugate: the Hamiltonian is not Hermitian"
504 );
505 model = model.hopping(0, 0, *o, m.clone());
506 }
507 model
508 }
509}
510
511#[cfg(test)]
512mod tests {
513 use super::*;
514 use crate::presets::{BhzParams, bhz};
515 use caroli_lattice::Region;
516
517 #[test]
521 fn bhz_from_its_continuum_form() {
522 let p = BhzParams::default();
523 let params = [("A", p.a), ("B", p.b), ("C", p.c), ("D", p.d), ("M", p.mass)];
524 let h = Continuum::parse(
525 "C - D*(k_x^2 + k_y^2) + (M - B*(k_x**2 + k_y**2))*kron(s0, sz) + A*(k_x*kron(sz, sx) - k_y*kron(s0, sy))",
526 ¶ms,
527 )
528 .unwrap();
529 assert_eq!((h.orbitals(), h.dim()), (4, 2));
530 let model = h.discretize(1.0);
531 let region = Region::cuboid(model.lattice(), [4, 3, 0]);
532 let reference = bhz(p);
533 let diff = (model.hamiltonian(®ion)
534 - reference.hamiltonian(&Region::cuboid(reference.lattice(), [4, 3, 0])))
535 .norm_max();
536 assert!(diff < 1e-14, "BHZ: {diff:e}");
537 }
538
539 #[test]
542 fn free_particle_and_errors() {
543 let a = 0.5;
544 let model = Continuum::parse("k_x^2 + k_y^2", &[]).unwrap().discretize(a);
545 assert!(
546 (model.onsite_matrix(&caroli_lattice::Site { cell: [0, 0, 0], sub: 0 })[(0, 0)].re
547 - 4.0 / (a * a))
548 .abs()
549 < 1e-14
550 );
551 assert_eq!(model.hoppings().len(), 2);
552 assert!(model.hoppings().iter().all(|h| (h.matrix[(0, 0)].re + 1.0 / (a * a)).abs() < 1e-14));
553 let h = Continuum::parse("k_x^3 + 2*k_x*k_y + k_z", &[]).unwrap();
555 assert_eq!(h.dim(), 3);
556 let m = h.discretize(1.0);
557 assert!(
558 m.hoppings().iter().any(|hop| hop.offset == [2, 0, 0])
559 && m.hoppings().iter().any(|hop| hop.offset == [1, 1, 0])
560 );
561 assert!(matches!(Continuum::parse("k_x + q", &[]), Err(ContinuumError::Unknown(_))));
562 assert!(matches!(Continuum::parse("sx + kron(sx, sz)", &[]), Err(ContinuumError::Size(2, 4))));
563 assert!(Continuum::parse("(k_x", &[]).is_err());
564 }
565
566 #[test]
568 fn constant_expressions() {
569 let x = number("2*sqrt(3)*cos(pi/3) + abs(-t)", &[("t", 0.5)]).unwrap();
570 assert!((x - (3f64.sqrt() + 0.5)).abs() < 1e-15);
571 let m = evaluate("J*kron(sz, s0) + i*sx/2", &[("J", 0.7)]);
572 assert!(m.is_err(), "sizes 4 and 2");
573 let m = evaluate("J*kron(sz, s0) + i*kron(s0, sx)/2", &[("J", 0.7)]).unwrap();
574 assert_eq!(m.nrows(), 4);
575 assert!(
576 (m[(0, 0)] - c64::new(0.7, 0.0)).norm() < 1e-15
577 && (m[(0, 1)] - c64::new(0.0, 0.5)).norm() < 1e-15
578 );
579 assert!(number("sx", &[]).is_err() && number("i", &[]).is_err() && evaluate("k_x*sz", &[]).is_err());
580 assert_eq!(number("pi", &[("pi", 3.0)]).unwrap(), 3.0);
582 }
583
584 #[test]
585 #[should_panic(expected = "not Hermitian")]
586 fn non_hermitian_terms() {
587 let _ = Continuum::parse("i*k_x^2", &[]).unwrap().discretize(1.0);
588 }
589}