1use crate::Error;
4use crate::input::*;
5use caroli::disorder::OnSiteMap;
6use caroli::model::continuum::{self, Continuum};
7use caroli::model::presets::{BhzParams, GFactors, Spin, bhz, bhz_block, bhz_spin};
8use caroli::prelude::*;
9use std::collections::BTreeMap;
10
11#[derive(Clone, Debug, Default, PartialEq)]
13pub struct Params(pub BTreeMap<String, f64>);
14
15impl Params {
16 pub fn resolve(raw: &BTreeMap<String, Num>, overrides: &BTreeMap<String, f64>) -> Result<Self, Error> {
19 for name in overrides.keys() {
20 if !raw.contains_key(name) {
21 return Err(format!("unknown parameter `{name}` (not in [parameters])").into());
22 }
23 }
24 let mut done: BTreeMap<String, f64> = overrides.clone();
25 let mut pending: Vec<(&String, &Num)> = raw.iter().filter(|(k, _)| !done.contains_key(*k)).collect();
26 while !pending.is_empty() {
27 let before = pending.len();
28 let mut last_error = None;
29 pending.retain(|(name, value)| match Params(done.clone()).num(value) {
30 Ok(x) => {
31 done.insert((*name).clone(), x);
32 false
33 }
34 Err(e) => {
35 last_error = Some(format!("parameter `{name}`: {e}"));
36 true
37 }
38 });
39 if pending.len() == before {
40 return Err(last_error.unwrap_or_default().into());
41 }
42 }
43 Ok(Self(done))
44 }
45
46 fn list(&self) -> Vec<(&str, f64)> {
47 self.0.iter().map(|(k, v)| (k.as_str(), *v)).collect()
48 }
49
50 pub fn num(&self, n: &Num) -> Result<f64, Error> {
52 match n {
53 Num::Value(x) => Ok(*x),
54 Num::Expr(e) => continuum::number(e, &self.list()).map_err(|err| format!("`{e}`: {err}").into()),
55 }
56 }
57
58 pub fn opt(&self, n: &Option<Num>, default: f64) -> Result<f64, Error> {
60 n.as_ref().map_or(Ok(default), |n| self.num(n))
61 }
62
63 pub fn matrix(&self, e: &str) -> Result<CMat, Error> {
65 continuum::evaluate(e, &self.list()).map_err(|err| format!("`{e}`: {err}").into())
66 }
67
68 pub fn values(&self, v: &Values) -> Result<Vec<f64>, Error> {
70 match v {
71 Values::One(n) => Ok(vec![self.num(n)?]),
72 Values::List(l) => l.iter().map(|n| self.num(n)).collect(),
73 Values::Range(r) => {
74 let (from, to) = (self.num(&r.from)?, self.num(&r.to)?);
75 match (r.count, &r.step) {
76 (Some(n), None) => Ok((0..n)
77 .map(|k| if n == 1 { from } else { from + (to - from) * k as f64 / (n - 1) as f64 })
78 .collect()),
79 (None, Some(step)) => {
80 let step = self.num(step)?;
81 if step.is_nan() || step <= 0.0 {
82 return Err("a range step must be positive".into());
83 }
84 let n = ((to - from) / step + 1e-9).floor() as usize + 1;
85 Ok((0..n).map(|k| from + step * k as f64).collect())
86 }
87 _ => Err("a range needs either `count` or `step`".into()),
88 }
89 }
90 }
91 }
92}
93
94pub fn scan_points(
97 raw: &BTreeMap<String, Num>,
98 base: &BTreeMap<String, f64>,
99 scan: &BTreeMap<String, Values>,
100) -> Result<Vec<(Vec<f64>, Params)>, Error> {
101 let p0 = Params::resolve(raw, base)?;
102 let axes: Vec<(String, Vec<f64>)> =
103 scan.iter().map(|(k, v)| Ok((k.clone(), p0.values(v)?))).collect::<Result<_, Error>>()?;
104 let mut points = vec![Vec::new()];
105 for (_, values) in &axes {
106 points = points
107 .into_iter()
108 .flat_map(|p| values.iter().map(move |v| [p.clone(), vec![*v]].concat()))
109 .collect();
110 }
111 points
112 .into_iter()
113 .map(|values| {
114 let mut overrides = base.clone();
115 for ((name, _), v) in axes.iter().zip(&values) {
116 overrides.insert(name.clone(), *v);
117 }
118 Ok((values, Params::resolve(raw, &overrides)?))
119 })
120 .collect()
121}
122
123fn vec3(v: &[f64]) -> [f64; 3] {
124 std::array::from_fn(|i| v.get(i).copied().unwrap_or(0.0))
125}
126
127fn cell3(v: &[i64]) -> [i64; 3] {
128 std::array::from_fn(|i| v.get(i).copied().unwrap_or(0))
129}
130
131pub fn model(m: &ModelInput, p: &Params) -> Result<Model, Error> {
133 let sources =
134 [m.preset.is_some(), m.continuum.is_some(), m.lattice.is_some()].iter().filter(|x| **x).count();
135 if sources != 1 {
136 return Err("[model] needs exactly one of `preset`, `continuum` and `lattice`".into());
137 }
138 let spacing = p.opt(&m.spacing, 1.0)?;
139 let t = p.opt(&m.t, 1.0)?;
140 let spin = |x: CMat| if m.spin { kron(&x, &s0()) } else { x };
141 let scalar = |x: f64| spin(CMat::from_fn(1, 1, |_, _| c64::new(x, 0.0)));
142 let preset_only = |name: &str, given: bool| -> Result<(), Error> {
143 if given { Err(format!("`{name}` does not apply to this model").into()) } else { Ok(()) }
144 };
145 let bhz_options = [&m.a, &m.b, &m.c, &m.d, &m.mass, &m.lambda].iter().any(|x| x.is_some());
146 let mut model = if let Some(preset) = &m.preset {
147 let bhz_params = || -> Result<BhzParams, Error> {
148 let d = BhzParams::default();
149 Ok(BhzParams {
150 a: p.opt(&m.a, d.a)?,
151 b: p.opt(&m.b, d.b)?,
152 c: p.opt(&m.c, d.c)?,
153 d: p.opt(&m.d, d.d)?,
154 mass: p.opt(&m.mass, d.mass)?,
155 lambda: p.opt(&m.lambda, d.lambda)?,
156 })
157 };
158 if !preset.starts_with("bhz") {
159 preset_only("a, b, c, d, mass, lambda", bhz_options)?;
160 } else {
161 preset_only("t", m.t.is_some())?;
162 preset_only("spin", m.spin)?;
163 }
164 if preset != "qwz" {
165 preset_only("m", m.m.is_some())?;
166 }
167 match preset.as_str() {
168 "bhz" => bhz(bhz_params()?),
169 "bhz-up" => bhz_block(bhz_params()?, Spin::Up),
170 "bhz-down" => bhz_block(bhz_params()?, Spin::Down),
171 "graphene" => {
172 let h = scalar(-t);
173 Model::new(Lattice::honeycomb(spacing, if m.spin { 2 } else { 1 }))
174 .hopping(0, 1, [0, 0, 0], &h)
175 .hopping(0, 1, [0, -1, 0], &h)
176 .hopping(0, 1, [1, -1, 0], &h)
177 }
178 "chain" | "square" | "cubic" => {
179 let orbitals = if m.spin { 2 } else { 1 };
180 let lattice = match preset.as_str() {
181 "chain" => Lattice::new(&[[spacing, 0.0, 0.0]]).with_sublattice("a", [0.0; 3], orbitals),
182 "square" => Lattice::square(spacing, orbitals),
183 _ => Lattice::cubic(spacing, orbitals),
184 };
185 let dim = lattice.dim();
186 (0..dim).fold(Model::new(lattice), |model, a| {
187 model.hopping(0, 0, std::array::from_fn(|c| (c == a) as i64), scalar(-t))
188 })
189 }
190 "qwz" => {
191 preset_only("spin", m.spin)?;
192 let mass = p.opt(&m.m, 1.0)?;
193 let i = c64::new(0.0, 1.0);
194 let half = c64::new(0.5, 0.0);
195 Model::new(Lattice::square(spacing, 2))
196 .onsite(0, combine(&[(mass, &sz())]))
197 .hopping(0, 0, [1, 0, 0], combine(&[(half, &sz()), (-i * 0.5, &sx())]))
198 .hopping(0, 0, [0, 1, 0], combine(&[(half, &sz()), (-i * 0.5, &sy())]))
199 }
200 other => return Err(format!("unknown preset `{other}`").into()),
201 }
202 } else if let Some(expr) = &m.continuum {
203 preset_only("a, b, c, d, mass, lambda", bhz_options)?;
204 Continuum::parse(expr, &p.list()).map_err(|e| format!("continuum `{expr}`: {e}"))?.discretize(spacing)
205 } else {
206 let l = m.lattice.as_ref().expect("lattice");
207 if l.vectors.is_empty() || l.vectors.len() > 3 {
208 return Err("a lattice needs 1 to 3 vectors".into());
209 }
210 let vectors: Vec<[f64; 3]> = l.vectors.iter().map(|v| vec3(v)).collect();
211 let lattice = l.sublattices.iter().enumerate().fold(Lattice::new(&vectors), |lat, (k, s)| {
212 lat.with_sublattice(s.name.as_deref().unwrap_or(&format!("s{k}")), vec3(&s.position), s.orbitals)
213 });
214 Model::new(lattice)
215 };
216 let subs = model.lattice().sublattices().len();
217 for o in &m.onsite {
218 if o.sublattice >= subs {
219 return Err(format!("on-site term on sublattice {} of {subs}", o.sublattice).into());
220 }
221 let x = p.matrix(&o.matrix)?;
222 let n = model.lattice().sublattices()[o.sublattice].orbitals;
223 if x.nrows() != n {
224 return Err(format!("on-site `{}` of size {} for {n} orbitals", o.matrix, x.nrows()).into());
225 }
226 if m.lattice.is_some() {
227 model = model.onsite(o.sublattice, x);
228 } else {
229 let sub = o.sublattice;
230 model = model.with_onsite_term(move |s: &Site| (s.sub == sub).then(|| x.clone()));
231 }
232 }
233 let dim = model.lattice().dim();
234 for h in &m.hoppings {
235 if h.from >= subs || h.to >= subs || h.offset.len() != dim {
236 return Err(
237 format!("hopping {h:?}: sublattices below {subs}, an offset of {dim} integers").into()
238 );
239 }
240 let x = p.matrix(&h.matrix)?;
241 let orb = |s: usize| model.lattice().sublattices()[s].orbitals;
242 if (x.nrows(), x.ncols()) != (orb(h.from), orb(h.to)) {
243 return Err(format!("hopping `{}` of size {}×{}", h.matrix, x.nrows(), x.ncols()).into());
244 }
245 model = model.hopping(h.from, h.to, cell3(&h.offset), x);
246 }
247 if let Some(b) = &m.field {
248 model = model.with_field(p.num(b)?);
249 }
250 Ok(model)
251}
252
253pub fn disordered(input: &Input, p: &Params, region: &Region, config: usize) -> Result<Model, Error> {
255 let mut model = model(&input.model, p)?;
256 for (k, d) in input.disorder.iter().enumerate() {
257 let map = disorder_map(d, p, region, config, k).map_err(|e| format!("[[disorder]] {k}: {e}"))?;
258 model = model.with_onsite_term(map);
259 }
260 Ok(model)
261}
262
263fn disorder_map(
264 d: &DisorderInput,
265 p: &Params,
266 region: &Region,
267 config: usize,
268 index: usize,
269) -> Result<OnSiteMap, Error> {
270 let lattice = region.lattice();
271 let inside = |c: i64, r: &Option<[i64; 2]>| r.is_none_or(|[a, b]| (a..b).contains(&c));
272 let cells = d.cells.clone().unwrap_or_default();
273 let sites: Vec<Site> = region
274 .sites()
275 .iter()
276 .copied()
277 .filter(|s| {
278 inside(s.cell[0], &cells.x)
279 && inside(s.cell[1], &cells.y)
280 && inside(s.cell[2], &cells.z)
281 && d.sublattices.as_ref().is_none_or(|l| l.contains(&s.sub))
282 })
283 .collect();
284 let seed = d.seed.unwrap_or(1 + 1000 * index as u64) + config as u64;
285 let mut rng = Xoshiro256::seed_from_u64(seed);
286 let mut map = OnSiteMap::default();
287 match d.kind.as_str() {
288 "anderson" => {
289 let w = p.num(d.strength.as_ref().ok_or("anderson disorder needs `strength`")?)?;
290 let a = Anderson::generate(&mut rng, &sites, w);
291 for (s, e) in a.sites.iter().zip(&a.energies) {
292 let n = lattice.sublattices()[s.sub].orbitals;
293 map.add(
294 *s,
295 CMat::from_fn(n, n, |i, j| if i == j { c64::new(*e, 0.0) } else { c64::new(0.0, 0.0) }),
296 );
297 }
298 }
299 "magnetic" => {
300 let conc = p.num(d.concentration.as_ref().ok_or("magnetic disorder needs `concentration`")?)?;
301 let j = p.num(d.exchange.as_ref().ok_or("magnetic disorder needs `exchange`")?)?;
302 let moments = moments(d, p)?;
303 let imp =
304 MagneticImpurities::generate(&mut rng, &sites, (conc * sites.len() as f64) as usize, moments);
305 for (s, n) in imp.sites.iter().zip(&imp.moments) {
306 let spin = spin_matrices(d, p, lattice.sublattices()[s.sub].orbitals)?;
307 map.add(*s, combine(&[(j * n[0], &spin[0]), (j * n[1], &spin[1]), (j * n[2], &spin[2])]));
308 }
309 }
310 other => return Err(format!("unknown disorder `{other}` (anderson, magnetic)").into()),
311 }
312 Ok(map)
313}
314
315pub fn moments(d: &DisorderInput, p: &Params) -> Result<Moments, Error> {
318 Ok(match d.moments.as_deref().unwrap_or("isotropic") {
319 "isotropic" => Moments::Isotropic,
320 "polarized" | "polarised" => Moments::Polarized { mz: p.opt(&d.mz, 1.0)? },
321 "cone" => Moments::Cone {
322 theta0: p.num(d.theta0.as_ref().ok_or("cone moments need `theta0`")?)?.to_radians(),
323 },
324 other => return Err(format!("unknown moments `{other}` (isotropic, polarized, cone)").into()),
325 })
326}
327
328pub fn spin_matrices(d: &DisorderInput, p: &Params, orbitals: usize) -> Result<[CMat; 3], Error> {
330 let s = match &d.spin {
331 None if orbitals == 2 => [sx(), sy(), sz()],
332 None => return Err(format!("give the `spin` matrices of sites with {orbitals} orbitals").into()),
333 Some(SpinInput::Name(n)) => match n.as_str() {
334 "pauli" => [sx(), sy(), sz()],
335 "same-g" => bhz_spin(GFactors::Same),
336 "opposite-g" => bhz_spin(GFactors::Opposite),
337 other => {
338 return Err(
339 format!("unknown spin `{other}` (pauli, same-g, opposite-g, or three matrices)").into()
340 );
341 }
342 },
343 Some(SpinInput::Matrices(m)) if m.len() == 3 => {
344 [p.matrix(&m[0])?, p.matrix(&m[1])?, p.matrix(&m[2])?]
345 }
346 Some(SpinInput::Matrices(_)) => return Err("`spin` takes three matrices".into()),
347 };
348 if s.iter().any(|m| m.nrows() != orbitals) {
349 return Err(format!("spin matrices of size {} for sites of {orbitals} orbitals", s[0].nrows()).into());
350 }
351 Ok(s)
352}
353
354pub fn region(model: &Model, system: &SystemInput) -> Result<Region, Error> {
356 let dim = model.lattice().dim();
357 let size = system.size.as_ref().ok_or("[system] needs `size`")?;
358 if size.len() != dim || size.contains(&0) {
359 return Err(format!("`size` needs {dim} positive numbers of cells").into());
360 }
361 Ok(Region::cuboid(model.lattice(), std::array::from_fn(|i| size.get(i).copied().unwrap_or(1))))
362}
363
364pub fn periods(system: &SystemInput) -> Vec<[i64; 3]> {
366 let size = system.size.clone().unwrap_or_default();
367 (0..size.len()).map(|a| std::array::from_fn(|c| if c == a { size[a] as i64 } else { 0 })).collect()
368}
369
370pub enum Leads {
372 Axis(usize),
374 Faces(Vec<Interface>),
376}
377
378pub fn leads(system: &SystemInput, region: &Region) -> Result<Leads, Error> {
380 let names = system.leads.clone().unwrap_or_else(|| vec!["-x".into(), "+x".into()]);
381 let dim = region.lattice().dim();
382 let parsed: Vec<(i64, usize)> = names
383 .iter()
384 .map(|n| {
385 let sign = match n.chars().next() {
386 Some('-') => -1,
387 Some('+') => 1,
388 _ => return Err(format!("lead `{n}`: a face such as -x or +y")),
389 };
390 let axis = match &n[1..] {
391 "x" => 0,
392 "y" => 1,
393 "z" => 2,
394 _ => return Err(format!("lead `{n}`: a face such as -x or +y")),
395 };
396 if axis >= dim {
397 return Err(format!("lead `{n}` on a lattice of dimension {dim}"));
398 }
399 Ok((sign, axis))
400 })
401 .collect::<Result<_, String>>()?;
402 if parsed.len() < 2 {
403 return Err("transport needs at least two leads".into());
404 }
405 if parsed.len() == 2 && parsed[0] == (-1, parsed[0].1) && parsed[1] == (1, parsed[0].1) {
406 return Ok(Leads::Axis(parsed[0].1));
407 }
408 let interfaces = parsed
409 .iter()
410 .map(|&(sign, axis)| {
411 let coords = region.sites().iter().map(|s| s.cell[axis]);
412 let edge = if sign < 0 { coords.min() } else { coords.max() }.expect("sites");
413 let sites: Vec<Site> = region.sites().iter().copied().filter(|s| s.cell[axis] == edge).collect();
414 Interface {
415 slice: Region::from_sites(region.lattice(), sites),
416 outward: std::array::from_fn(|c| if c == axis { sign } else { 0 }),
417 }
418 })
419 .collect();
420 Ok(Leads::Faces(interfaces))
421}