Skip to main content

caroli_cli/
lib.rs

1//! The `caroli` command: a system and its simulations described in a TOML file.
2//!
3//! ```toml
4//! title = "Clean BHZ ribbon"
5//!
6//! [parameters]
7//! M = -0.137
8//!
9//! [model]
10//! preset = "bhz"
11//! mass = "M"
12//!
13//! [system]
14//! size = [40, 20]
15//!
16//! [[run]]
17//! type = "transmission"
18//! energies = { from = -0.3, to = 0.3, count = 61 }
19//! ```
20//!
21//! `caroli run input.toml` writes one CSV table per `[[run]]` in an output directory. The input
22//! format is described in `crates/caroli-cli/README.md`, with commented examples in
23//! `crates/caroli-cli/inputs/`.
24
25pub mod build;
26pub mod input;
27pub mod run;
28
29use std::collections::BTreeMap;
30use std::path::Path;
31
32/// An error of the command, whose message says what is wrong.
33pub type Error = Box<dyn std::error::Error + Send + Sync>;
34
35/// Parses an input file.
36pub fn parse(text: &str) -> Result<input::Input, Error> {
37    let input: input::Input = toml::from_str(text)?;
38    if input.runs.is_empty() {
39        return Err("no [[run]] in the input".into());
40    }
41    Ok(input)
42}
43
44/// A short description of the system: lattice, sample, leads, runs.
45pub fn describe(input: &input::Input, overrides: &BTreeMap<String, f64>) -> Result<String, Error> {
46    let p = build::Params::resolve(&input.parameters, overrides)?;
47    let model = build::model(&input.model, &p)?;
48    let lattice = model.lattice();
49    let mut out = String::new();
50    if let Some(t) = &input.title {
51        out += &format!("{t}\n");
52    }
53    out += &format!(
54        "lattice: dimension {}, {} sublattice(s) with {:?} orbitals\n",
55        lattice.dim(),
56        lattice.sublattices().len(),
57        lattice.sublattices().iter().map(|s| s.orbitals).collect::<Vec<_>>()
58    );
59    out += &format!("parameters: {:?}\n", p.0);
60    if let Some(size) = &input.system.size {
61        let region = build::region(&model, &input.system)?;
62        // Builds the disorder too, to report its errors.
63        build::disordered(input, &p, &region, 0)?;
64        out += &format!(
65            "sample: {:?} cells, {} sites, {} orbitals{}\n",
66            size,
67            region.len(),
68            region.orbitals(),
69            if input.system.periodic { ", periodic" } else { "" }
70        );
71    }
72    out += &format!("disorder: {} term(s)\n", input.disorder.len());
73    for (k, r) in input.runs.iter().enumerate() {
74        out += &format!("run {k}: {}\n", output_name(k, r));
75    }
76    Ok(out)
77}
78
79/// Name of the table of run `k`.
80pub fn output_name(k: usize, r: &input::RunInput) -> String {
81    use input::RunInput::*;
82    let (kind, output) = match r {
83        Transmission(x) => ("transmission", &x.output),
84        Local(x) => ("local", &x.output),
85        Bands(x) => ("bands", &x.output),
86        Spectrum(x) => ("spectrum", &x.output),
87        Dos(x) => ("dos", &x.output),
88        Conductivity(x) => ("conductivity", &x.output),
89        Scba(x) => ("scba", &x.output),
90        Evolution(x) => ("evolution", &x.output),
91    };
92    output.clone().unwrap_or_else(|| format!("{k:02}-{kind}.csv"))
93}
94
95/// Runs the calculations of `input` (all, or those of `only`), writing their tables in
96/// `out_dir`. Returns a summary line per calculation.
97pub fn run_all(
98    input: &input::Input,
99    out_dir: &Path,
100    overrides: &BTreeMap<String, f64>,
101    only: Option<&[usize]>,
102) -> Result<Vec<String>, Error> {
103    std::fs::create_dir_all(out_dir)?;
104    let mut lines = Vec::new();
105    for (k, r) in input.runs.iter().enumerate() {
106        if only.is_some_and(|o| !o.contains(&k)) {
107            continue;
108        }
109        let t = std::time::Instant::now();
110        let table = run::run(input, r, overrides).map_err(|e| format!("run {k}: {e}"))?;
111        let path = out_dir.join(output_name(k, r));
112        std::fs::write(&path, &table.csv)?;
113        lines.push(format!("{} → {} ({:.1?})", table.summary, path.display(), t.elapsed()));
114    }
115    Ok(lines)
116}