Skip to main content

linkcell/
skin.rs

1//! Verlet skin over a cutoff pair list.
2//!
3//! The candidate list is [`pairs_within_columns`] at `cutoff + skin`.
4//! A later frame reuses it while every atom is within `skin / 2` of its
5//! reference position, after the box-corner correction of Verlet
6//! (Phys. Rev. **159**, 98, 1967) as used by vesin and LAMMPS. The kept
7//! rows satisfy `|q + H S - p|^2` strictly below `cutoff²`. Shifts inside
8//! `[-3, 3]^3` are a one-byte code; the filter gathers coordinates eight
9//! at a time and compacts the hits. A wider shift keeps the three shift
10//! columns and uses the same test.
11
12use crate::cell::Cell;
13use crate::pairs::{pairs_within_columns, PairColumns};
14use crate::skin_simd::Soa;
15use crate::Error;
16
17/// Cutoff list with a Verlet skin.
18///
19/// `update` rebuilds the candidates when an atom has moved too far and
20/// otherwise only filters them. The returned columns borrow the list.
21pub struct SkinList {
22    cell: Cell,
23    cutoff: f64,
24    skin: f64,
25    half: bool,
26    reference: Vec<[f64; 3]>,
27    ref_h: [[f64; 3]; 3],
28    soa: Soa,
29    d2: Vec<f64>,
30    cols: PairColumns,
31    vectors: Vec<[f64; 3]>,
32    built: bool,
33}
34
35impl SkinList {
36    /// Empty list. The first [`Self::update`] builds the candidates.
37    pub fn new(cell: Cell, cutoff: f64, skin: f64, half: bool) -> Result<Self, Error> {
38        if !cutoff.is_finite() || cutoff <= 0.0 {
39            return Err(Error::BadCutoff);
40        }
41        if !skin.is_finite() || skin < 0.0 {
42            return Err(Error::BadCutoff);
43        }
44        Ok(Self {
45            cell,
46            cutoff,
47            skin,
48            half,
49            reference: Vec::new(),
50            ref_h: cell.h(),
51            soa: Soa::empty(),
52            d2: Vec::new(),
53            cols: PairColumns::default(),
54            vectors: Vec::new(),
55            built: false,
56        })
57    }
58
59    /// Cutoff the rows were filtered to.
60    pub fn cutoff(&self) -> f64 {
61        self.cutoff
62    }
63
64    /// Skin added on top of the cutoff when the candidates were built.
65    pub fn skin(&self) -> f64 {
66        self.skin
67    }
68
69    /// Rows from the last [`Self::update`].
70    pub fn columns(&self) -> &PairColumns {
71        &self.cols
72    }
73
74    /// Shifted vectors from the last update that asked for them.
75    /// Empty when that update did not.
76    pub fn vectors(&self) -> &[[f64; 3]] {
77        &self.vectors
78    }
79
80    /// `true` when `xyz` is not covered by the stored candidates.
81    pub fn needs_rebuild(&self, xyz: &[[f64; 3]]) -> bool {
82        if !self.built || xyz.len() != self.reference.len() {
83            return true;
84        }
85        let half = self.skin * 0.5;
86        let corner = corner_span(self.cell.h(), self.ref_h) * 0.5;
87        if corner > half {
88            return true;
89        }
90        let room = half - corner;
91        let room2 = room * room;
92        for (p, r) in xyz.iter().zip(self.reference.iter()) {
93            let dx = p[0] - r[0];
94            let dy = p[1] - r[1];
95            let dz = p[2] - r[2];
96            if dx * dx + dy * dy + dz * dz > room2 {
97                return true;
98            }
99        }
100        false
101    }
102
103    /// Filter `xyz`, rebuilding the candidates first when the skin is spent.
104    ///
105    /// `want_vector` fills [`Self::vectors`] with `q + H S - p`.
106    pub fn update(&mut self, xyz: &[[f64; 3]], want_vector: bool) -> Result<&PairColumns, Error> {
107        if xyz.is_empty() {
108            return Err(Error::Empty);
109        }
110        if self.needs_rebuild(xyz) {
111            self.rebuild(xyz)?;
112        }
113        self.filter(xyz, want_vector)?;
114        Ok(&self.cols)
115    }
116
117    fn rebuild(&mut self, xyz: &[[f64; 3]]) -> Result<(), Error> {
118        let reach = self.cutoff + self.skin;
119        self.soa = gather_candidates(xyz, &self.cell, reach, self.half)?;
120        self.reference = xyz.to_vec();
121        self.ref_h = self.cell.h();
122        self.built = true;
123        Ok(())
124    }
125
126    fn filter(&mut self, xyz: &[[f64; 3]], want_vector: bool) -> Result<(), Error> {
127        self.soa.filter(
128            xyz,
129            &self.cell,
130            self.cutoff * self.cutoff,
131            want_vector,
132            &mut self.d2,
133            &mut self.cols,
134            &mut self.vectors,
135        )
136    }
137}
138
139pub(crate) fn gather_candidates(
140    xyz: &[[f64; 3]],
141    cell: &Cell,
142    reach: f64,
143    half: bool,
144) -> Result<Soa, Error> {
145    let mut cols = PairColumns::default();
146    pairs_within_columns(xyz, cell, reach, None, None, half, &mut cols)?;
147    Soa::from_columns(&cols, xyz.len())
148}
149
150fn corner_span(h: [[f64; 3]; 3], href: [[f64; 3]; 3]) -> f64 {
151    let mut best1 = 0.0;
152    let mut best2 = 0.0;
153    for bits in 0..8 {
154        let b = [
155            f64::from(bits & 1),
156            f64::from((bits >> 1) & 1),
157            f64::from((bits >> 2) & 1),
158        ];
159        let mut d = [0.0; 3];
160        for a in 0..3 {
161            let corner = b[0] * h[0][a] + b[1] * h[1][a] + b[2] * h[2][a];
162            let old = b[0] * href[0][a] + b[1] * href[1][a] + b[2] * href[2][a];
163            d[a] = corner - old;
164        }
165        let n2 = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
166        if n2 > best1 {
167            best2 = best1;
168            best1 = n2;
169        } else if n2 > best2 {
170            best2 = n2;
171        }
172    }
173    best1.sqrt() + best2.sqrt()
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179    use crate::pairs::pairs_within_columns;
180
181    fn canon(i: i32, j: i32, mut s: [i32; 3]) -> (i32, i32, [i32; 3]) {
182        let swap = if i != j {
183            i > j
184        } else if s[0] != 0 {
185            s[0] > 0
186        } else if s[1] != 0 {
187            s[1] > 0
188        } else {
189            s[2] > 0
190        };
191        if swap {
192            s = [-s[0], -s[1], -s[2]];
193            (j, i, s)
194        } else {
195            (i, j, s)
196        }
197    }
198
199    fn set_of(cols: &PairColumns) -> Vec<(i32, i32, [i32; 3])> {
200        let mut v: Vec<_> = (0..cols.len())
201            .map(|k| canon(cols.i[k], cols.j[k], cols.shift[k]))
202            .collect();
203        v.sort_unstable();
204        v
205    }
206
207    #[test]
208    fn skin_filter_matches_a_fresh_list() {
209        let cell = Cell::ortho(12.0, 11.0, 10.0).unwrap();
210        let mut xyz = Vec::new();
211        let mut state = 0x1234_5678_u64;
212        for _ in 0..80 {
213            let mut p = [0.0; 3];
214            for (a, slot) in p.iter_mut().enumerate() {
215                state = state.wrapping_mul(6364136223846793005).wrapping_add(1);
216                *slot = (state >> 33) as f64 / (1u64 << 31) as f64 * cell.widths()[a];
217            }
218            xyz.push(p);
219        }
220        let mut fresh = PairColumns::default();
221        pairs_within_columns(&xyz, &cell, 3.5, None, None, true, &mut fresh).unwrap();
222        let mut skin = SkinList::new(cell, 3.5, 0.6, true).unwrap();
223        let (got, n) = {
224            let cols = skin.update(&xyz, true).unwrap();
225            (set_of(cols), cols.len())
226        };
227        assert_eq!(got, set_of(&fresh));
228        assert_eq!(skin.vectors().len(), n);
229        let mut moved = xyz.clone();
230        for p in &mut moved {
231            p[0] += 0.02;
232        }
233        assert!(!skin.needs_rebuild(&moved));
234        let got = {
235            let cols = skin.update(&moved, false).unwrap();
236            set_of(cols)
237        };
238        let mut again = PairColumns::default();
239        pairs_within_columns(&moved, &cell, 3.5, None, None, true, &mut again).unwrap();
240        assert_eq!(got, set_of(&again));
241        assert!(skin.vectors().is_empty());
242    }
243}