Skip to main content

caroli_lattice/
lib.rs

1//! Lattices, finite regions and transport slices.
2//!
3//! A [`Lattice`] is a Bravais lattice (1, 2 or 3 primitive vectors) with a basis of
4//! [`Sublattice`]s, each carrying a number of orbitals. A [`Region`] is a finite, ordered set of
5//! [`Site`]s of a lattice; it fixes the orbital ordering of every matrix built on it.
6
7use std::collections::HashMap;
8
9/// Cartesian vector.
10pub type Vec3 = [f64; 3];
11
12/// Integer coordinates of a unit cell along the primitive vectors (unused axes are 0).
13pub type Cell = [i64; 3];
14
15/// One site of the basis of a lattice.
16#[derive(Clone, Debug, PartialEq)]
17pub struct Sublattice {
18    /// Label of the sublattice, such as `A` or `B`.
19    pub name: String,
20    /// Position inside the unit cell (Cartesian).
21    pub offset: Vec3,
22    /// Number of orbitals (including spin) carried by each site of this sublattice.
23    pub orbitals: usize,
24}
25
26/// A Bravais lattice with a basis.
27#[derive(Clone, Debug, PartialEq)]
28pub struct Lattice {
29    vectors: Vec<Vec3>,
30    sublattices: Vec<Sublattice>,
31}
32
33impl Lattice {
34    /// Lattice with the given primitive vectors (1 to 3 of them) and no sublattice yet.
35    pub fn new(vectors: &[Vec3]) -> Self {
36        assert!((1..=3).contains(&vectors.len()), "a lattice has 1, 2 or 3 primitive vectors");
37        Self { vectors: vectors.to_vec(), sublattices: Vec::new() }
38    }
39
40    /// Adds a sublattice and returns the lattice (builder style).
41    pub fn with_sublattice(mut self, name: &str, offset: Vec3, orbitals: usize) -> Self {
42        assert!(orbitals > 0, "a sublattice carries at least one orbital");
43        self.sublattices.push(Sublattice { name: name.to_owned(), offset, orbitals });
44        self
45    }
46
47    /// Square lattice of constant `a` with one sublattice of `orbitals` orbitals.
48    pub fn square(a: f64, orbitals: usize) -> Self {
49        Self::new(&[[a, 0.0, 0.0], [0.0, a, 0.0]]).with_sublattice("A", [0.0; 3], orbitals)
50    }
51
52    /// Simple cubic lattice of constant `a` with one sublattice of `orbitals` orbitals.
53    pub fn cubic(a: f64, orbitals: usize) -> Self {
54        Self::new(&[[a, 0.0, 0.0], [0.0, a, 0.0], [0.0, 0.0, a]]).with_sublattice("A", [0.0; 3], orbitals)
55    }
56
57    /// Honeycomb lattice with nearest-neighbour distance `a` (sublattices A and B).
58    pub fn honeycomb(a: f64, orbitals: usize) -> Self {
59        let s3 = 3f64.sqrt();
60        Self::new(&[[s3 * a, 0.0, 0.0], [0.5 * s3 * a, 1.5 * a, 0.0]])
61            .with_sublattice("A", [0.0; 3], orbitals)
62            .with_sublattice("B", [0.0, a, 0.0], orbitals)
63    }
64
65    /// Number of primitive vectors.
66    pub fn dim(&self) -> usize {
67        self.vectors.len()
68    }
69
70    /// Primitive vectors (Cartesian), 1 to 3 of them.
71    pub fn vectors(&self) -> &[Vec3] {
72        &self.vectors
73    }
74
75    /// Sublattices of the basis, indexed by [`Site::sub`].
76    pub fn sublattices(&self) -> &[Sublattice] {
77        &self.sublattices
78    }
79
80    /// Cartesian position of a site.
81    pub fn position(&self, site: Site) -> Vec3 {
82        let mut r = self.sublattices[site.sub].offset;
83        for (n, v) in site.cell.iter().zip(&self.vectors) {
84            for (ri, vi) in r.iter_mut().zip(v) {
85                *ri += *n as f64 * vi;
86            }
87        }
88        r
89    }
90}
91
92/// A site: a unit cell and a sublattice index.
93#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
94pub struct Site {
95    /// Unit cell, in integer coordinates along the primitive vectors.
96    pub cell: Cell,
97    /// Index of the sublattice in [`Lattice::sublattices`].
98    pub sub: usize,
99}
100
101/// A finite, ordered set of sites. The order fixes the orbital layout of matrices: site `i`
102/// occupies orbitals `offset(i) .. offset(i) + orbitals(i)`.
103#[derive(Clone, Debug)]
104pub struct Region {
105    lattice: Lattice,
106    sites: Vec<Site>,
107    index: HashMap<Site, usize>,
108    offsets: Vec<usize>,
109    orbitals: usize,
110}
111
112impl Region {
113    /// Region made of the given sites, in this order (duplicates are an error).
114    pub fn from_sites(lattice: &Lattice, sites: Vec<Site>) -> Self {
115        let mut index = HashMap::with_capacity(sites.len());
116        let mut offsets = Vec::with_capacity(sites.len());
117        let mut orbitals = 0;
118        for (i, s) in sites.iter().enumerate() {
119            assert!(s.sub < lattice.sublattices.len(), "unknown sublattice {}", s.sub);
120            assert!(index.insert(*s, i).is_none(), "duplicate site {s:?}");
121            offsets.push(orbitals);
122            orbitals += lattice.sublattices[s.sub].orbitals;
123        }
124        Self { lattice: lattice.clone(), sites, index, offsets, orbitals }
125    }
126
127    /// All sites of the cells `0..extent[a]` along each primitive vector `a` (extents beyond
128    /// the lattice dimension are ignored). Sites are ordered with the first axis varying
129    /// slowest, then the sublattice fastest: for a ribbon along x this groups the sites by
130    /// column, which is the slice order used for transport.
131    pub fn cuboid(lattice: &Lattice, extent: [usize; 3]) -> Self {
132        let dim = lattice.dim();
133        let n = |a: usize| if a < dim { extent[a] as i64 } else { 1 };
134        let mut sites = Vec::new();
135        for i in 0..n(0) {
136            for j in 0..n(1) {
137                for k in 0..n(2) {
138                    for sub in 0..lattice.sublattices.len() {
139                        sites.push(Site { cell: [i, j, k], sub });
140                    }
141                }
142            }
143        }
144        Self::from_sites(lattice, sites)
145    }
146
147    /// Sites of the cuboid `0..extent` whose position satisfies `inside`.
148    pub fn shaped(lattice: &Lattice, extent: [usize; 3], inside: impl Fn(Vec3) -> bool) -> Self {
149        let all = Self::cuboid(lattice, extent);
150        let sites = all.sites.into_iter().filter(|s| inside(lattice.position(*s))).collect();
151        Self::from_sites(lattice, sites)
152    }
153
154    /// The lattice of the sites.
155    pub fn lattice(&self) -> &Lattice {
156        &self.lattice
157    }
158
159    /// Sites of the region, in the order of their orbitals.
160    pub fn sites(&self) -> &[Site] {
161        &self.sites
162    }
163
164    /// Number of sites.
165    pub fn len(&self) -> usize {
166        self.sites.len()
167    }
168
169    /// Whether the region has no site.
170    pub fn is_empty(&self) -> bool {
171        self.sites.is_empty()
172    }
173
174    /// Index of a site in the region, if it belongs to it.
175    pub fn index_of(&self, site: &Site) -> Option<usize> {
176        self.index.get(site).copied()
177    }
178
179    /// First orbital of site `i`.
180    pub fn offset(&self, i: usize) -> usize {
181        self.offsets[i]
182    }
183
184    /// Number of orbitals of site `i`.
185    pub fn site_orbitals(&self, i: usize) -> usize {
186        self.lattice.sublattices[self.sites[i].sub].orbitals
187    }
188
189    /// Total number of orbitals (size of the matrices built on the region).
190    pub fn orbitals(&self) -> usize {
191        self.orbitals
192    }
193
194    /// Splits the region into slices along primitive vector `axis`: slice `n` holds the sites
195    /// whose cell coordinate along `axis` is the `n`-th smallest value present. Each slice keeps
196    /// the relative order of the region.
197    pub fn slices(&self, axis: usize) -> Vec<Region> {
198        let mut by_coord: std::collections::BTreeMap<i64, Vec<Site>> = Default::default();
199        for s in &self.sites {
200            by_coord.entry(s.cell[axis]).or_default().push(*s);
201        }
202        by_coord.into_values().map(|sites| Self::from_sites(&self.lattice, sites)).collect()
203    }
204
205    /// The same region translated by `cells` unit cells.
206    pub fn translated(&self, cells: Cell) -> Region {
207        let sites = self
208            .sites
209            .iter()
210            .map(|s| Site {
211                cell: [s.cell[0] + cells[0], s.cell[1] + cells[1], s.cell[2] + cells[2]],
212                sub: s.sub,
213            })
214            .collect();
215        Self::from_sites(&self.lattice, sites)
216    }
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222
223    #[test]
224    fn cuboid_orders_by_first_axis() {
225        let lat = Lattice::square(1.0, 4);
226        let r = Region::cuboid(&lat, [3, 2, 0]);
227        assert_eq!(r.len(), 6);
228        assert_eq!(r.orbitals(), 24);
229        assert_eq!(r.sites()[1], Site { cell: [0, 1, 0], sub: 0 });
230        assert_eq!(r.offset(2), 8);
231        let slices = r.slices(0);
232        assert_eq!(slices.len(), 3);
233        assert!(slices.iter().all(|s| s.len() == 2));
234    }
235
236    #[test]
237    fn honeycomb_positions() {
238        let lat = Lattice::honeycomb(1.0, 2);
239        let b = lat.position(Site { cell: [0, 0, 0], sub: 1 });
240        assert!((b[1] - 1.0).abs() < 1e-15);
241        let r = Region::shaped(&lat, [4, 4, 0], |p| p[0] < 3.0);
242        assert!(r.len() < 32);
243    }
244}