Skip to main content

caroli_cli/
run.rs

1//! The calculations: each writes one CSV table, a row per scan point, configuration and value.
2
3use crate::Error;
4use crate::build::{self, Leads, Params};
5use crate::input::*;
6use caroli::born::{Disorder, Scba};
7use caroli::dynamics::{Evolution, Torus};
8use caroli::kpm::Spectrum;
9use caroli::prelude::*;
10use rayon::prelude::*;
11use std::collections::BTreeMap;
12use std::fmt::Write as _;
13
14/// A finished calculation: its table and a one-line summary.
15pub struct Table {
16    /// The CSV text: a header line, then the rows.
17    pub csv: String,
18    /// One line naming the calculation and its size.
19    pub summary: String,
20}
21
22/// A scan point: the values of the scanned parameters and every parameter.
23type Point = (Vec<f64>, Params);
24
25/// Header columns of the scanned parameters.
26fn scan_header(scan: &BTreeMap<String, Values>) -> String {
27    scan.keys().map(|k| format!("{k},")).collect()
28}
29
30fn scan_prefix(values: &[f64]) -> String {
31    values.iter().map(|v| format!("{v},")).collect()
32}
33
34fn fmt(x: f64) -> String {
35    format!("{x:e}")
36}
37
38/// Runs `job` on every pair (scan point, configuration) in parallel; the rows keep their order.
39fn over_points<F>(points: &[Point], configs: usize, job: F) -> Result<String, Error>
40where
41    F: Fn(&Point, usize) -> Result<String, Error> + Sync,
42{
43    let jobs: Vec<(usize, usize)> =
44        (0..points.len()).flat_map(|p| (0..configs).map(move |c| (p, c))).collect();
45    let rows: Vec<String> =
46        jobs.par_iter().map(|&(p, c)| job(&points[p], c)).collect::<Result<_, Error>>()?;
47    Ok(rows.concat())
48}
49
50/// The calculation `run` of `input` with the parameters `base`.
51pub fn run(input: &Input, run: &RunInput, base: &BTreeMap<String, f64>) -> Result<Table, Error> {
52    match run {
53        RunInput::Transmission(r) => transmission(input, r, base),
54        RunInput::Local(r) => local(input, r, base),
55        RunInput::Bands(r) => bands(input, r, base),
56        RunInput::Spectrum(r) => spectrum(input, r, base),
57        RunInput::Dos(r) => dos(input, r, base),
58        RunInput::Conductivity(r) => conductivity(input, r, base),
59        RunInput::Scba(r) => scba(input, r, base),
60        RunInput::Evolution(r) => evolution(input, r, base),
61    }
62}
63
64/// The clean model, the sample, and the disordered model of configuration `c`.
65fn system(input: &Input, p: &Params, c: usize) -> Result<(Model, Region, Model), Error> {
66    let clean = build::model(&input.model, p)?;
67    let region = build::region(&clean, &input.system)?;
68    let device = build::disordered(input, p, &region, c)?;
69    Ok((clean, region, device))
70}
71
72fn transmission(input: &Input, r: &TransmissionRun, base: &BTreeMap<String, f64>) -> Result<Table, Error> {
73    let points = build::scan_points(&input.parameters, base, &r.scan)?;
74    let configs = r.configurations.unwrap_or(1);
75    let (_, region, _) = system(input, &points[0].1, 0)?;
76    let leads = build::leads(&input.system, &region)?;
77    let two = matches!(leads, Leads::Axis(_)) && r.sectors.is_none();
78    let count = match &leads {
79        Leads::Axis(_) => 2,
80        Leads::Faces(f) => f.len(),
81    };
82    let mut header = format!("{}config,energy", scan_header(&r.scan));
83    if two {
84        header += ",T";
85    } else if let Some(s) = &r.sectors {
86        let sectors: Vec<usize> =
87            s.iter().copied().collect::<std::collections::BTreeSet<_>>().into_iter().collect();
88        for p in 0..count {
89            for &a in &sectors {
90                for q in 0..count {
91                    for &b in &sectors {
92                        if (p, a) != (q, b) {
93                            write!(header, ",T_{p}.{a}_{q}.{b}").unwrap();
94                        }
95                    }
96                }
97            }
98        }
99    } else {
100        for p in 0..count {
101            for q in 0..count {
102                if p != q {
103                    write!(header, ",T_{p}_{q}").unwrap();
104                }
105            }
106        }
107    }
108    header.push('\n');
109    let mut csv = header;
110    for point in &points {
111        let energies = point.1.values(&r.energies)?;
112        let (clean, region, first) = system(input, &point.1, 0)?;
113        let leads = build::leads(&input.system, &region)?;
114        let rows = match leads {
115            Leads::Axis(axis) if r.sectors.is_none() => {
116                // The leads are clean: one set of self-energies per energy serves every configuration.
117                let reference = NestedTwoTerminal::from_model(&first, &clean, &region, axis);
118                let sigma: Vec<_> = energies.par_iter().map(|&e| reference.self_energies(e)).collect();
119                drop(reference);
120                over_points(std::slice::from_ref(point), configs, |(values, p), c| {
121                    let (clean, region, device) = system(input, p, c)?;
122                    let sys = NestedTwoTerminal::from_model(&device, &clean, &region, axis);
123                    let mut out = String::new();
124                    for (e, s) in energies.iter().zip(&sigma) {
125                        let t =
126                            s.as_ref().ok().and_then(|s| sys.transmission_with(s).ok()).unwrap_or(f64::NAN);
127                        writeln!(out, "{}{c},{e},{}", scan_prefix(values), fmt(t)).unwrap();
128                    }
129                    Ok(out)
130                })?
131            }
132            leads => {
133                let interfaces = match leads {
134                    Leads::Faces(f) => f,
135                    Leads::Axis(axis) => face_pair(&region, axis),
136                };
137                over_points(std::slice::from_ref(point), configs, |(values, p), c| {
138                    let (clean, region, device) = system(input, p, c)?;
139                    let sys = NestedMultiTerminal::from_model(&device, &clean, &region, &interfaces);
140                    let mut out = String::new();
141                    for &e in &energies {
142                        let cells: Vec<f64> = match &r.sectors {
143                            None => match sys.transmissions(e) {
144                                Ok(t) => (0..count)
145                                    .flat_map(|p| (0..count).filter(move |q| *q != p).map(move |q| (p, q)))
146                                    .map(|(p, q)| t[p][q])
147                                    .collect(),
148                                Err(_) => vec![f64::NAN; count * (count - 1)],
149                            },
150                            Some(s) => {
151                                let labels = vec![Some(s.clone()); count];
152                                let labs: Vec<usize> = s
153                                    .iter()
154                                    .copied()
155                                    .collect::<std::collections::BTreeSet<_>>()
156                                    .into_iter()
157                                    .collect();
158                                let n = labs.len();
159                                match sys.sector_transmissions(e, &labels) {
160                                    Ok(st) => {
161                                        let at = |l: (usize, usize)| st.labels.iter().position(|x| *x == l);
162                                        let mut v = Vec::new();
163                                        for p in 0..count {
164                                            for &a in &labs {
165                                                for q in 0..count {
166                                                    for &b in &labs {
167                                                        if (p, a) != (q, b) {
168                                                            v.push(match (at((p, a)), at((q, b))) {
169                                                                (Some(k), Some(l)) => st.t[k][l],
170                                                                _ => 0.0,
171                                                            });
172                                                        }
173                                                    }
174                                                }
175                                            }
176                                        }
177                                        v
178                                    }
179                                    Err(_) => vec![f64::NAN; (count * n) * (count * n - 1)],
180                                }
181                            }
182                        };
183                        let cells: Vec<String> = cells.into_iter().map(fmt).collect();
184                        writeln!(out, "{}{c},{e},{}", scan_prefix(values), cells.join(",")).unwrap();
185                    }
186                    Ok(out)
187                })?
188            }
189        };
190        csv.push_str(&rows);
191    }
192    let summary =
193        format!("transmission: {} scan points × {configs} configurations, {count} leads", points.len());
194    Ok(Table { csv, summary })
195}
196
197/// The two end faces of `axis`.
198fn face_pair(region: &Region, axis: usize) -> Vec<Interface> {
199    [-1i64, 1]
200        .iter()
201        .map(|&sign| {
202            let coords = region.sites().iter().map(|s| s.cell[axis]);
203            let edge = if sign < 0 { coords.min() } else { coords.max() }.expect("sites");
204            let sites: Vec<Site> = region.sites().iter().copied().filter(|s| s.cell[axis] == edge).collect();
205            Interface {
206                slice: Region::from_sites(region.lattice(), sites),
207                outward: std::array::from_fn(|c| if c == axis { sign } else { 0 }),
208            }
209        })
210        .collect()
211}
212
213/// Scattering states of a two-terminal or multi-terminal device.
214enum Device {
215    Two(NestedTwoTerminal),
216    Multi(NestedMultiTerminal),
217}
218
219impl Device {
220    fn states(&self, e: f64) -> Result<ScatteringStates, Error> {
221        Ok(match self {
222            Device::Two(d) => d.scattering_states(e)?,
223            Device::Multi(d) => d.scattering_states(e)?,
224        })
225    }
226    fn bonds(&self, s: &ScatteringStates, f: &[f64], op: Option<&CMat>) -> Vec<BondCurrent> {
227        match (self, op) {
228            (Device::Two(d), None) => d.bond_currents(s, f),
229            (Device::Two(d), Some(o)) => d.operator_currents(s, f, o),
230            (Device::Multi(d), None) => d.bond_currents(s, f),
231            (Device::Multi(d), Some(o)) => d.operator_currents(s, f, o),
232        }
233    }
234    fn densities(&self, s: &ScatteringStates, f: &[f64], op: Option<&CMat>) -> Vec<f64> {
235        match self {
236            Device::Two(d) => d.site_densities(s, f, op),
237            Device::Multi(d) => d.site_densities(s, f, op),
238        }
239    }
240}
241
242fn local(input: &Input, r: &LocalRun, base: &BTreeMap<String, f64>) -> Result<Table, Error> {
243    let points = build::scan_points(&input.parameters, base, &r.scan)?;
244    let configs = r.configurations.unwrap_or(1);
245    let ops: Vec<(String, CMat)> = r
246        .operators
247        .iter()
248        .map(|(k, v)| Ok((k.clone(), points[0].1.matrix(v)?)))
249        .collect::<Result<_, Error>>()?;
250    let mut header = format!("{}config,x,y,z,jx,jy,jz,density,ldos", scan_header(&r.scan));
251    for (name, _) in &ops {
252        write!(header, ",{name},j{name}_x,j{name}_y,j{name}_z").unwrap();
253    }
254    header.push('\n');
255    let rows = over_points(&points, configs, |(values, p), c| {
256        let (clean, region, device) = system(input, p, c)?;
257        let lattice = region.lattice().clone();
258        let (dev, leads) = match build::leads(&input.system, &region)? {
259            Leads::Axis(axis) => {
260                (Device::Two(NestedTwoTerminal::from_model(&device, &clean, &region, axis)), 2)
261            }
262            Leads::Faces(f) => {
263                let n = f.len();
264                (Device::Multi(NestedMultiTerminal::from_model(&device, &clean, &region, &f)), n)
265            }
266        };
267        let f: Vec<f64> = match &r.occupations {
268            Some(o) if o.len() == leads => o.clone(),
269            Some(o) => return Err(format!("{} occupations for {leads} leads", o.len()).into()),
270            None => (0..leads).map(|k| (k == 0) as u8 as f64).collect(),
271        };
272        let ones = vec![1.0; leads];
273        let energies = p.values(&r.energies)?;
274        let n = region.len();
275        let width = 5 + 4 * ops.len();
276        // Per site: current (3), density, ldos, then per operator density and current (3).
277        let mut acc = vec![vec![0.0; width]; n];
278        let index: std::collections::HashMap<Site, usize> =
279            region.sites().iter().enumerate().map(|(i, s)| (*s, i)).collect();
280        let add = |acc: &mut Vec<Vec<f64>>, bonds: Vec<BondCurrent>, slot: usize| {
281            for b in bonds {
282                let (ra, rb) = (lattice.position(b.from), lattice.position(b.to));
283                let d = [rb[0] - ra[0], rb[1] - ra[1], rb[2] - ra[2]];
284                let norm = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
285                for s in [b.from, b.to] {
286                    if let Some(&i) = index.get(&s) {
287                        for k in 0..3 {
288                            acc[i][slot + k] += 0.5 * b.current * d[k] / norm;
289                        }
290                    }
291                }
292            }
293        };
294        for &e in &energies {
295            let states = dev.states(e)?;
296            add(&mut acc, dev.bonds(&states, &f, None), 0);
297            for (i, (d, l)) in
298                dev.densities(&states, &f, None).iter().zip(dev.densities(&states, &ones, None)).enumerate()
299            {
300                acc[i][3] += d;
301                acc[i][4] += l;
302            }
303            for (k, (_, op)) in ops.iter().enumerate() {
304                let slot = 5 + 4 * k;
305                for (i, d) in dev.densities(&states, &f, Some(op)).iter().enumerate() {
306                    acc[i][slot] += d;
307                }
308                add(&mut acc, dev.bonds(&states, &f, Some(op)), slot + 1);
309            }
310        }
311        let m = energies.len() as f64;
312        let mut out = String::new();
313        for (site, a) in region.sites().iter().zip(&acc) {
314            let r = lattice.position(*site);
315            let v: Vec<String> = a.iter().map(|x| fmt(x / m)).collect();
316            writeln!(out, "{}{c},{},{},{},{}", scan_prefix(values), r[0], r[1], r[2], v.join(",")).unwrap();
317        }
318        Ok(out)
319    })?;
320    let summary = format!("local: {} scan points × {configs} configurations", points.len());
321    Ok(Table { csv: header + &rows, summary })
322}
323
324fn bands(input: &Input, r: &BandsRun, base: &BTreeMap<String, f64>) -> Result<Table, Error> {
325    if !input.disorder.is_empty() {
326        eprintln!("bands: the disorder is ignored (bands of the clean model)");
327    }
328    let points = build::scan_points(&input.parameters, base, &r.scan)?;
329    let eig = |h: CMat| -> Vec<f64> { h.self_adjoint_eigenvalues(faer::Side::Lower).expect("eigenvalues") };
330    let (header, rows) = if let Some(path) = &r.path {
331        let header = format!("{}s,band,energy\n", scan_header(&r.scan));
332        let rows = over_points(&points, 1, |(values, p), _| {
333            let model = build::model(&input.model, p)?;
334            let dim = model.lattice().dim();
335            let corners: Vec<Vec<f64>> = path
336                .iter()
337                .map(|c| {
338                    if c.len() != dim {
339                        return Err(Error::from(format!("path corners need {dim} Bloch phases")));
340                    }
341                    c.iter().map(|x| p.num(x)).collect()
342                })
343                .collect::<Result<_, Error>>()?;
344            let cell = Region::cuboid(model.lattice(), [1, 1, 1]);
345            let periods: Vec<[i64; 3]> = (0..dim).map(|a| std::array::from_fn(|c| (c == a) as i64)).collect();
346            let per = r.points.unwrap_or(50);
347            let mut out = String::new();
348            let mut s = 0.0;
349            for w in corners.windows(2) {
350                let length = w[0].iter().zip(&w[1]).map(|(a, b)| (b - a).powi(2)).sum::<f64>().sqrt();
351                for k in 0..per {
352                    let f = k as f64 / per as f64;
353                    let phase: Vec<f64> = w[0].iter().zip(&w[1]).map(|(a, b)| a + f * (b - a)).collect();
354                    for (b, e) in eig(model.bloch_hamiltonian(&cell, &periods, &phase)).iter().enumerate() {
355                        writeln!(out, "{}{},{b},{e}", scan_prefix(values), s + f * length).unwrap();
356                    }
357                }
358                s += length;
359            }
360            let last = corners.last().expect("corner");
361            for (b, e) in eig(model.bloch_hamiltonian(&cell, &periods, last)).iter().enumerate() {
362                writeln!(out, "{}{s},{b},{e}", scan_prefix(values)).unwrap();
363            }
364            Ok(out)
365        })?;
366        (header, rows)
367    } else {
368        let header = format!("{}k,band,energy\n", scan_header(&r.scan));
369        let rows = over_points(&points, 1, |(values, p), _| {
370            let model = build::model(&input.model, p)?;
371            let region = build::region(&model, &input.system)?;
372            let axis = match build::leads(&input.system, &region)? {
373                Leads::Axis(a) => a,
374                Leads::Faces(f) => (0..3).find(|&c| f[0].outward[c] != 0).expect("axis"),
375            };
376            let slice = &region.slices(axis)[0];
377            let period: [i64; 3] = std::array::from_fn(|c| (c == axis) as i64);
378            let ks = match &r.k {
379                Some(v) => p.values(v)?,
380                None => (0..201)
381                    .map(|k| -std::f64::consts::PI + 2.0 * std::f64::consts::PI * k as f64 / 200.0)
382                    .collect(),
383            };
384            let mut out = String::new();
385            for k in ks {
386                for (b, e) in eig(model.bloch_hamiltonian(slice, &[period], &[k])).iter().enumerate() {
387                    writeln!(out, "{}{k},{b},{e}", scan_prefix(values)).unwrap();
388                }
389            }
390            Ok(out)
391        })?;
392        (header, rows)
393    };
394    Ok(Table { csv: header + &rows, summary: format!("bands: {} scan points", points.len()) })
395}
396
397/// Largest dense problem of `spectrum`.
398const DENSE_LIMIT: usize = 8000;
399
400fn spectrum(input: &Input, r: &SpectrumRun, base: &BTreeMap<String, f64>) -> Result<Table, Error> {
401    let points = build::scan_points(&input.parameters, base, &r.scan)?;
402    let configs = r.configurations.unwrap_or(1);
403    let rows = over_points(&points, configs, |(values, p), c| {
404        let (_, region, device) = system(input, p, c)?;
405        if region.orbitals() > DENSE_LIMIT {
406            return Err(
407                format!("{} orbitals: too many for a dense spectrum (use `dos`)", region.orbitals()).into()
408            );
409        }
410        let h = if input.system.periodic {
411            let periods = build::periods(&input.system);
412            device.bloch_hamiltonian(&region, &periods, &vec![0.0; periods.len()])
413        } else {
414            device.hamiltonian(&region)
415        };
416        let e = h.self_adjoint_eigenvalues(faer::Side::Lower).map_err(|e| format!("{e:?}"))?;
417        Ok(e.iter().enumerate().map(|(k, x)| format!("{}{c},{k},{x}\n", scan_prefix(values))).collect())
418    })?;
419    let header = format!("{}config,index,energy\n", scan_header(&r.scan));
420    Ok(Table {
421        csv: header + &rows,
422        summary: format!("spectrum: {} scan points × {configs} configurations", points.len()),
423    })
424}
425
426/// The KPM spectrum of a configuration.
427fn kpm<'a>(
428    device: &'a Model,
429    region: &'a Region,
430    periods: &[[i64; 3]],
431    moments: Option<usize>,
432    vectors: Option<usize>,
433    seed: Option<u64>,
434    bounds: Option<[f64; 2]>,
435) -> Spectrum<'a> {
436    let mut s = Spectrum::periodic(device, region, periods)
437        .moments(moments.unwrap_or(512))
438        .vectors(vectors.unwrap_or(10));
439    if let Some(seed) = seed {
440        s = s.seed(seed);
441    }
442    if let Some([lo, hi]) = bounds {
443        s = s.bounds(lo, hi);
444    }
445    s
446}
447
448fn dos(input: &Input, r: &DosRun, base: &BTreeMap<String, f64>) -> Result<Table, Error> {
449    let points = build::scan_points(&input.parameters, base, &r.scan)?;
450    let configs = r.configurations.unwrap_or(1);
451    let periods = if input.system.periodic { build::periods(&input.system) } else { Vec::new() };
452    let mut header = format!("{}config,energy,dos", scan_header(&r.scan));
453    r.projections.keys().for_each(|k| write!(header, ",{k}").unwrap());
454    header.push('\n');
455    let rows = over_points(&points, configs, |(values, p), c| {
456        let (_, region, device) = system(input, p, c)?;
457        let s = kpm(&device, &region, &periods, r.moments, r.vectors, r.seed.map(|x| x + c as u64), r.bounds);
458        let energies = p.values(&r.energies)?;
459        let mut columns = vec![s.dos(&energies)];
460        for e in r.projections.values() {
461            columns.push(s.projected_dos(&p.matrix(e)?, &energies));
462        }
463        let mut out = String::new();
464        for (k, e) in energies.iter().enumerate() {
465            let v: Vec<String> = columns.iter().map(|col| fmt(col[k])).collect();
466            writeln!(out, "{}{c},{e},{}", scan_prefix(values), v.join(",")).unwrap();
467        }
468        Ok(out)
469    })?;
470    Ok(Table {
471        csv: header + &rows,
472        summary: format!("dos: {} scan points × {configs} configurations", points.len()),
473    })
474}
475
476fn direction(axis: char) -> Result<[f64; 3], Error> {
477    Ok(match axis {
478        'x' => [1.0, 0.0, 0.0],
479        'y' => [0.0, 1.0, 0.0],
480        'z' => [0.0, 0.0, 1.0],
481        other => return Err(format!("component axis `{other}`").into()),
482    })
483}
484
485fn conductivity(input: &Input, r: &ConductivityRun, base: &BTreeMap<String, f64>) -> Result<Table, Error> {
486    if !input.system.periodic {
487        return Err("the conductivity needs a periodic sample ([system] periodic = true)".into());
488    }
489    let points = build::scan_points(&input.parameters, base, &r.scan)?;
490    let configs = r.configurations.unwrap_or(1);
491    let components = r.components.clone().unwrap_or_else(|| vec!["xx".into(), "xy".into()]);
492    let pairs: Vec<([f64; 3], [f64; 3])> = components
493        .iter()
494        .map(|c| {
495            let ch: Vec<char> = c.chars().collect();
496            if ch.len() != 2 {
497                return Err(Error::from(format!("component `{c}`: two axes such as xy")));
498            }
499            Ok((direction(ch[0])?, direction(ch[1])?))
500        })
501        .collect::<Result<_, Error>>()?;
502    let periods = build::periods(&input.system);
503    let mut header = format!("{}config,energy", scan_header(&r.scan));
504    components.iter().for_each(|k| write!(header, ",sigma_{k}").unwrap());
505    header.push('\n');
506    let rows = over_points(&points, configs, |(values, p), c| {
507        let (_, region, device) = system(input, p, c)?;
508        let s = kpm(
509            &device,
510            &region,
511            &periods,
512            r.moments.or(Some(256)),
513            r.vectors,
514            r.seed.map(|x| x + c as u64),
515            r.bounds,
516        );
517        let energies = p.values(&r.energies)?;
518        let temperature = p.opt(&r.temperature, 0.0)?;
519        let columns: Vec<Vec<f64>> =
520            pairs.iter().map(|(a, b)| s.conductivity(*a, *b, &energies, temperature)).collect();
521        let mut out = String::new();
522        for (k, e) in energies.iter().enumerate() {
523            let v: Vec<String> = columns.iter().map(|col| fmt(col[k])).collect();
524            writeln!(out, "{}{c},{e},{}", scan_prefix(values), v.join(",")).unwrap();
525        }
526        Ok(out)
527    })?;
528    Ok(Table {
529        csv: header + &rows,
530        summary: format!("conductivity (e²/h): {} scan points × {configs} configurations", points.len()),
531    })
532}
533
534/// The disorder of the input as SCBA vertices: independent on every site, so one set of vertices
535/// per sublattice of the cell. The `cells` windows do not apply (bulk).
536fn born_disorder(input: &Input, p: &Params, model: &Model) -> Result<Disorder, Error> {
537    let cell = Region::cuboid(model.lattice(), [1, 1, 1]);
538    let n = cell.orbitals();
539    let embed = |m: &CMat, o: usize| {
540        let mut out = CMat::zeros(n, n);
541        for i in 0..m.nrows() {
542            for j in 0..m.ncols() {
543                out[(o + i, o + j)] = m[(i, j)];
544            }
545        }
546        out
547    };
548    let mut total = Disorder { mean_field: CMat::zeros(n, n), vertices: Vec::new() };
549    for d in &input.disorder {
550        for (i, site) in cell.sites().iter().enumerate() {
551            if d.sublattices.as_ref().is_some_and(|l| !l.contains(&site.sub)) {
552                continue;
553            }
554            let (o, orb) = (cell.offset(i), cell.site_orbitals(i));
555            let part = match d.kind.as_str() {
556                "anderson" => {
557                    let w = p.num(d.strength.as_ref().ok_or("anderson disorder needs `strength`")?)?;
558                    let id =
559                        CMat::from_fn(
560                            orb,
561                            orb,
562                            |a, b| if a == b { c64::new(1.0, 0.0) } else { c64::new(0.0, 0.0) },
563                        );
564                    Disorder { mean_field: CMat::zeros(n, n), vertices: vec![(w * w / 12.0, embed(&id, o))] }
565                }
566                "magnetic" => {
567                    let conc =
568                        p.num(d.concentration.as_ref().ok_or("magnetic disorder needs `concentration`")?)?;
569                    let j = p.num(d.exchange.as_ref().ok_or("magnetic disorder needs `exchange`")?)?;
570                    let s = build::spin_matrices(d, p, orb)?;
571                    Disorder::magnetic(
572                        conc,
573                        j,
574                        build::moments(d, p)?,
575                        &[embed(&s[0], o), embed(&s[1], o), embed(&s[2], o)],
576                    )
577                }
578                other => return Err(format!("unknown disorder `{other}`").into()),
579            };
580            total = total.and(part);
581        }
582    }
583    Ok(total)
584}
585
586fn scba(input: &Input, r: &ScbaRun, base: &BTreeMap<String, f64>) -> Result<Table, Error> {
587    let points = build::scan_points(&input.parameters, base, &r.scan)?;
588    let model0 = build::model(&input.model, &points[0].1)?;
589    let n = Region::cuboid(model0.lattice(), [1, 1, 1]).orbitals();
590    let dim = model0.lattice().dim();
591    drop(model0);
592    let grid = r.k_grid.clone().unwrap_or_else(|| vec![64; dim]);
593    if grid.len() != dim {
594        return Err(format!("`k_grid` needs {dim} sizes").into());
595    }
596    let mut header = format!("{}energy,dos", scan_header(&r.scan));
597    (0..n).for_each(|k| write!(header, ",sigma_re_{k},sigma_im_{k}").unwrap());
598    header += ",residual\n";
599    let rows = over_points(&points, 1, |(values, p), _| {
600        let model = build::model(&input.model, p)?;
601        let scba = Scba::from_model(&model, &grid, born_disorder(input, p, &model)?);
602        let energies = p.values(&r.energies)?;
603        let eta = p.opt(&r.eta, 1e-3)?;
604        let mut out = String::new();
605        for (e, sol) in energies.iter().zip(scba.sweep(&energies, eta)) {
606            let total = scba.total_self_energy(&sol.sigma);
607            let sigma: Vec<String> =
608                (0..n).map(|k| format!("{},{}", fmt(total[(k, k)].re), fmt(total[(k, k)].im))).collect();
609            let dos = scba.dos(*e, eta, &sol.sigma);
610            writeln!(
611                out,
612                "{}{e},{},{},{}",
613                scan_prefix(values),
614                fmt(dos),
615                sigma.join(","),
616                fmt(sol.residual)
617            )
618            .unwrap();
619        }
620        Ok(out)
621    })?;
622    Ok(Table { csv: header + &rows, summary: format!("scba: {} scan points, k grid {grid:?}", points.len()) })
623}
624
625fn evolution(input: &Input, r: &EvolutionRun, base: &BTreeMap<String, f64>) -> Result<Table, Error> {
626    let points = build::scan_points(&input.parameters, base, &r.scan)?;
627    let configs = r.configurations.unwrap_or(1);
628    let size = input.system.size.clone().unwrap_or_default();
629    if size.len() != 2 || size[0] != size[1] {
630        return Err("the evolution runs on an n × n torus: [system] size = [n, n]".into());
631    }
632    let n = size[0];
633    let rows = over_points(&points, configs, |(values, p), c| {
634        let (_, _, device) = system(input, p, c)?;
635        let force = match &r.force {
636            Some(f) => {
637                let v: Vec<f64> = f.iter().map(|x| p.num(x)).collect::<Result<_, Error>>()?;
638                std::array::from_fn(|i| v.get(i).copied().unwrap_or(0.0))
639            }
640            None => [0.0; 3],
641        };
642        if !device.has_uniform_hoppings() {
643            return Err("the evolution needs hoppings without field or site-dependent terms".into());
644        }
645        let mut torus = Torus::new(&device, n).with_force(force);
646        if let InitialInput::Band { orbitals: Some(o), .. } = &r.initial {
647            let comps = torus.components();
648            if o.iter().any(|&a| a >= comps) {
649                return Err(format!("`orbitals` of the band: a cell has {comps} orbitals").into());
650            }
651            if let Some(g) = torus
652                .groups()
653                .iter()
654                .find(|g| g.iter().any(|a| o.contains(a)) && !g.iter().all(|a| o.contains(a)))
655            {
656                return Err(format!(
657                    "`orbitals` of the band must include all of {g:?}, coupled by the hoppings"
658                )
659                .into());
660            }
661            torus = torus.with_sector(o);
662        }
663        let starts = match &r.initial {
664            InitialInput::FermiSea { fermi, vectors, seed, moments } => {
665                let (mu, count, seed) =
666                    (p.opt(fermi, 0.0)?, vectors.unwrap_or(1), seed.unwrap_or(1) + c as u64);
667                if input.disorder.is_empty() {
668                    torus.filled(mu, count, seed)
669                } else {
670                    torus.fermi_sea(mu, count, seed, moments.unwrap_or(1024))
671                }
672            }
673            InitialInput::Band { fermi, vectors, seed, .. } => {
674                torus.filled(p.opt(fermi, 0.0)?, vectors.unwrap_or(1), seed.unwrap_or(1) + c as u64)
675            }
676            InitialInput::Localized { cell, orbital, window } => {
677                if cell.len() != 2 || cell[0] >= n || cell[1] >= n {
678                    return Err("`cell` of the localized state: two indices inside the torus".into());
679                }
680                let o = orbital.unwrap_or(0);
681                if o >= torus.components() {
682                    return Err(format!("orbital {o} of a cell with {} orbitals", torus.components()).into());
683                }
684                vec![torus.localized([cell[0], cell[1]], o, window.map(|[a, b]| (a, b)))]
685            }
686        };
687        let ev = Evolution {
688            dt: p.num(&r.dt)?,
689            steps: r.steps,
690            every: r.every.unwrap_or(1),
691            fermi: p.opt(&r.fermi, 0.0)?,
692            densities: false,
693        };
694        let rec = torus.evolve(&starts, &ev);
695        let mut out = String::new();
696        for k in 0..rec.times.len() {
697            writeln!(
698                out,
699                "{}{c},{},{},{},{},{},{}",
700                scan_prefix(values),
701                rec.times[k],
702                fmt(rec.norm[k]),
703                fmt(rec.current[k][0]),
704                fmt(rec.current[k][1]),
705                fmt(rec.excited[k]),
706                fmt(rec.width[k])
707            )
708            .unwrap();
709        }
710        Ok(out)
711    })?;
712    let header = format!("{}config,t,norm,jx,jy,excited,width\n", scan_header(&r.scan));
713    Ok(Table {
714        csv: header + &rows,
715        summary: format!("evolution: {} scan points × {configs} configurations", points.len()),
716    })
717}