Skip to main content

caroli_disorder/
lib.rs

1//! Disorder: reproducible random streams, Anderson disorder and classical magnetic impurities.
2//!
3//! The draws follow the algorithms of the thesis codes (same order, same formulas). With
4//! [`rng::Xoshiro256::gfortran`] they rebuild the thesis configurations bit for bit; with any
5//! other seed they are ordinary, reproducible random configurations.
6
7pub mod rng;
8
9use caroli_lattice::Site;
10use caroli_model::{CMat, OnSite, c64};
11use rng::Xoshiro256;
12use std::collections::HashMap;
13
14/// `n` distinct sites drawn among `candidates` by a partial Fisher–Yates shuffle (thesis
15/// `impurities_set`): for `i = 1..n`, swap entry `i` with a uniform entry of `i..=len`. The
16/// order of `candidates` matters for reproducibility; the thesis lists the impurity region
17/// with x varying fastest.
18pub fn choose_sites(rng: &mut Xoshiro256, candidates: &[Site], n: usize) -> Vec<Site> {
19    assert!(n <= candidates.len(), "{n} impurities for {} sites", candidates.len());
20    let mut tab: Vec<usize> = (0..candidates.len()).collect();
21    for i in 0..n {
22        let r = rng.integer(i + 1, candidates.len()) - 1;
23        tab.swap(i, r);
24    }
25    tab[..n].iter().map(|&k| candidates[k]).collect()
26}
27
28/// Distribution of classical unit moments, axisymmetric about z: `n_z = a u + b` for a
29/// uniform `u`, azimuth `φ = 2π u'` uniform. The formulas are those of the thesis codes.
30#[derive(Clone, Copy, Debug, PartialEq)]
31pub enum Moments {
32    /// Isotropic: `n_z` uniform in [−1, 1] (thesis `spin = 0`).
33    Isotropic,
34    /// Inside a cone of half-angle `theta0` (radians) around z: `n_z` uniform in [cos θ0, 1]
35    /// (thesis `spin ≠ 0`, `theta_0`).
36    Cone {
37        /// Half-angle of the cone (radians): 0 puts every moment along +z, π is isotropic.
38        theta0: f64,
39    },
40    /// Mean polarisation `mz` along z: `n_z` uniform in [2 mz − 1, 1] (thesis 2015 codes, `Mz`).
41    Polarized {
42        /// Mean `⟨n_z⟩`, in [0, 1]: 1 puts every moment along +z, 0 is isotropic.
43        mz: f64,
44    },
45}
46
47impl Moments {
48    fn nz(&self, u: f64) -> f64 {
49        match *self {
50            Moments::Isotropic => 2.0 * u - 1.0,
51            Moments::Cone { theta0 } => -(1.0 - theta0.cos()) * u + 1.0,
52            Moments::Polarized { mz } => {
53                assert!((0.0..=1.0).contains(&mz), "polarisation mz = {mz} outside [0, 1]");
54                2.0 * (1.0 - mz) * u + 2.0 * mz - 1.0
55            }
56        }
57    }
58
59    /// `n` moments: all the `n_z` draws first, then all the azimuths (thesis order).
60    pub fn draw(&self, rng: &mut Xoshiro256, n: usize) -> Vec<[f64; 3]> {
61        let nz: Vec<f64> = rng.uniforms(n).into_iter().map(|u| self.nz(u)).collect();
62        let phi: Vec<f64> = rng.uniforms(n).into_iter().map(|u| 2.0 * std::f64::consts::PI * u).collect();
63        nz.iter()
64            .zip(&phi)
65            .map(|(&z, &p)| {
66                let perp = (1.0 - z * z).sqrt();
67                [perp * p.cos(), perp * p.sin(), z]
68            })
69            .collect()
70    }
71}
72
73/// Classical magnetic impurities: distinct sites and their unit moments.
74#[derive(Clone, Debug, PartialEq)]
75pub struct MagneticImpurities {
76    /// Sites of the impurities, distinct.
77    pub sites: Vec<Site>,
78    /// Unit moment `n = (n_x, n_y, n_z)` of each impurity, in the order of `sites`.
79    pub moments: Vec<[f64; 3]>,
80}
81
82impl MagneticImpurities {
83    /// `n` impurities among `candidates` (see [`choose_sites`]), moments drawn from `moments`.
84    pub fn generate(rng: &mut Xoshiro256, candidates: &[Site], n: usize, moments: Moments) -> Self {
85        let sites = choose_sites(rng, candidates, n);
86        let moments = moments.draw(rng, n);
87        Self { sites, moments }
88    }
89
90    /// Mean moment.
91    pub fn magnetisation(&self) -> [f64; 3] {
92        let n = self.moments.len().max(1) as f64;
93        std::array::from_fn(|a| self.moments.iter().map(|m| m[a]).sum::<f64>() / n)
94    }
95
96    /// On-site exchange term `J (n_x S_x + n_y S_y + n_z S_z)` on the impurity sites, for the
97    /// spin matrices `s` of the model (e.g. [`caroli_model::presets::bhz_spin`]).
98    pub fn exchange(&self, j: f64, s: &[CMat; 3]) -> OnSiteMap {
99        let mut map = OnSiteMap::default();
100        for (site, n) in self.sites.iter().zip(&self.moments) {
101            let (rows, cols) = (s[0].nrows(), s[0].ncols());
102            let v = CMat::from_fn(rows, cols, |a, b| {
103                c64::new(j, 0.0) * (s[0][(a, b)] * n[0] + s[1][(a, b)] * n[1] + s[2][(a, b)] * n[2])
104            });
105            map.add(*site, v);
106        }
107        map
108    }
109}
110
111/// Anderson disorder: uniform on-site energies in `[−w/2, w/2)` times the identity.
112#[derive(Clone, Debug, PartialEq)]
113pub struct Anderson {
114    /// Disordered sites.
115    pub sites: Vec<Site>,
116    /// On-site energy of each site, in the order of `sites` (times the identity in [`Self::onsite`]).
117    pub energies: Vec<f64>,
118}
119
120impl Anderson {
121    /// One energy per site, drawn in the order of `sites`.
122    pub fn generate(rng: &mut Xoshiro256, sites: &[Site], w: f64) -> Self {
123        let energies = rng.uniforms(sites.len()).into_iter().map(|u| w * (u - 0.5)).collect();
124        Self { sites: sites.to_vec(), energies }
125    }
126
127    /// On-site term for sites with `orbitals` orbitals.
128    pub fn onsite(&self, orbitals: usize) -> OnSiteMap {
129        let mut map = OnSiteMap::default();
130        for (site, &e) in self.sites.iter().zip(&self.energies) {
131            map.add(
132                *site,
133                CMat::from_fn(
134                    orbitals,
135                    orbitals,
136                    |a, b| if a == b { c64::new(e, 0.0) } else { c64::new(0.0, 0.0) },
137                ),
138            );
139        }
140        map
141    }
142}
143
144/// Site-dependent on-site matrices stored in a map (sums when a site is added twice).
145#[derive(Clone, Debug, Default)]
146pub struct OnSiteMap {
147    map: HashMap<Site, CMat>,
148}
149
150impl OnSiteMap {
151    /// Adds `m` to the matrix of `site`, or stores it if the site has none yet.
152    pub fn add(&mut self, site: Site, m: CMat) {
153        match self.map.get_mut(&site) {
154            Some(v) => *v += m,
155            None => {
156                self.map.insert(site, m);
157            }
158        }
159    }
160
161    /// The matrix of `site`, if it has one.
162    pub fn get(&self, site: &Site) -> Option<&CMat> {
163        self.map.get(site)
164    }
165
166    /// Number of sites with a matrix.
167    pub fn len(&self) -> usize {
168        self.map.len()
169    }
170
171    /// Whether no site has a matrix.
172    pub fn is_empty(&self) -> bool {
173        self.map.is_empty()
174    }
175}
176
177impl OnSite for OnSiteMap {
178    fn matrix(&self, site: &Site) -> Option<CMat> {
179        self.map.get(site).cloned()
180    }
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186
187    fn line(n: i64) -> Vec<Site> {
188        (0..n).map(|x| Site { cell: [x, 0, 0], sub: 0 }).collect()
189    }
190
191    #[test]
192    fn distinct_sites() {
193        let mut rng = Xoshiro256::seed_from_u64(7);
194        let s = choose_sites(&mut rng, &line(50), 30);
195        let mut u = s.clone();
196        u.sort();
197        u.dedup();
198        assert_eq!(u.len(), 30);
199    }
200
201    #[test]
202    fn moment_distributions() {
203        let mut rng = Xoshiro256::seed_from_u64(3);
204        for m in [Moments::Isotropic, Moments::Cone { theta0: 0.3 }, Moments::Polarized { mz: 0.8 }] {
205            for n in m.draw(&mut rng, 200) {
206                assert!((n[0] * n[0] + n[1] * n[1] + n[2] * n[2] - 1.0).abs() < 1e-12);
207            }
208        }
209        // Polarisation 1 and cone 0: all moments along +z.
210        let up = Moments::Polarized { mz: 1.0 }.draw(&mut rng, 10);
211        assert!(up.iter().all(|n| n[2] == 1.0));
212        let mean = MagneticImpurities {
213            sites: line(1000),
214            moments: Moments::Polarized { mz: 0.6 }.draw(&mut rng, 1000),
215        }
216        .magnetisation();
217        assert!((mean[2] - 0.6).abs() < 0.05, "<n_z> = {}", mean[2]);
218    }
219}