Skip to main content

linkcell/
replica.rs

1//! One neighbour structure for every bead of a ring polymer.
2//!
3//! The candidates are built on the bead centroid at
4//! `cutoff + 2 R + skin`, where `R` is the largest minimum-image
5//! distance from the centroid to a bead. Any pair inside `cutoff` on a
6//! bead that still lies within `R` of the centroid is in that list.
7//! [`ReplicaList::update_bead`] filters one bead.
8//! [`ReplicaList::filter_all`] loads each candidate once and filters every
9//! bead in that pass. A bead that has moved more than `skin / 2` from the
10//! positions used at the last build rebuilds the shared candidates from
11//! the stored bead coordinates.
12
13use minimage::ring_centroid;
14
15use crate::cell::Cell;
16use crate::pairs::PairColumns;
17use crate::skin::gather_candidates;
18use crate::skin_simd::Soa;
19use crate::Error;
20
21/// Shared candidate list and one filtered frame per bead.
22pub struct ReplicaList {
23    cell: Cell,
24    cutoff: f64,
25    skin: f64,
26    half: bool,
27    beads: usize,
28    atoms: usize,
29    soa: Soa,
30    d2: Vec<f64>,
31    /// Bead-major positions from the last build or update.
32    last: Vec<[f64; 3]>,
33    frames: Vec<PairColumns>,
34    /// Largest minimum-image distance from the centroid at the last build.
35    spread: f64,
36}
37
38impl ReplicaList {
39    /// Build the shared list and filter every bead.
40    ///
41    /// `xyz` is bead-major, `beads * atoms` points, `atoms = xyz.len() / beads`.
42    pub fn build(
43        xyz: &[[f64; 3]],
44        beads: usize,
45        cell: Cell,
46        cutoff: f64,
47        skin: f64,
48        half: bool,
49    ) -> Result<Self, Error> {
50        if !cutoff.is_finite() || cutoff <= 0.0 || !skin.is_finite() || skin < 0.0 {
51            return Err(Error::BadCutoff);
52        }
53        if beads == 0 || xyz.is_empty() || xyz.len() % beads != 0 {
54            return Err(Error::Empty);
55        }
56        let atoms = xyz.len() / beads;
57        let mut list = Self {
58            cell,
59            cutoff,
60            skin,
61            half,
62            beads,
63            atoms,
64            soa: Soa::empty(),
65            d2: Vec::new(),
66            last: xyz.to_vec(),
67            frames: (0..beads).map(|_| PairColumns::default()).collect(),
68            spread: 0.0,
69        };
70        list.rebuild_from_last()?;
71        Ok(list)
72    }
73
74    /// Number of beads.
75    pub fn beads(&self) -> usize {
76        self.beads
77    }
78
79    /// Atoms in one bead.
80    pub fn atoms(&self) -> usize {
81        self.atoms
82    }
83
84    /// Spread `R` from the last shared build.
85    pub fn spread(&self) -> f64 {
86        self.spread
87    }
88
89    /// Filtered rows of bead `b` from the last build or update.
90    pub fn bead(&self, b: usize) -> Result<&PairColumns, Error> {
91        self.frames.get(b).ok_or(Error::BufferSize)
92    }
93
94    /// Unique unordered atom pairs in the shared candidate list.
95    ///
96    /// Self-images (`i == j`) are omitted. This is the spatial sparsity
97    /// pattern of a ring-polymer potential: every bead's cutoff pairs are
98    /// a subset, and the spring terms along the ring do not add atom pairs.
99    pub fn sparsity(&self) -> Vec<(u32, u32)> {
100        let mut pairs = Vec::new();
101        self.soa.each_end(|i, j| {
102            if i != j {
103                pairs.push(if i < j { (i, j) } else { (j, i) });
104            }
105        });
106        pairs.sort_unstable();
107        pairs.dedup();
108        pairs
109    }
110
111    /// Filter every stored bead from the shared candidate list.
112    ///
113    /// One pass loads each candidate once and gathers every bead's
114    /// coordinates into the same lanes. A shift that does not fit the
115    /// packed code falls back to a pass per bead.
116    pub fn filter_all(&mut self) -> Result<(), Error> {
117        let cut2 = self.cutoff * self.cutoff;
118        if self.soa.is_coded() {
119            return self.soa.filter_beads(
120                &self.last,
121                self.beads,
122                &self.cell,
123                cut2,
124                &mut self.frames,
125            );
126        }
127        for b in 0..self.beads {
128            let start = b * self.atoms;
129            let frame = self.last[start..start + self.atoms].to_vec();
130            self.filter_bead(b, &frame)?;
131        }
132        Ok(())
133    }
134
135    /// Replace bead `b` and return its filtered rows.
136    ///
137    /// A move inside the skin only filters that bead. A larger move
138    /// rebuilds the shared candidates and every bead's rows.
139    pub fn update_bead(&mut self, b: usize, xyz: &[[f64; 3]]) -> Result<&PairColumns, Error> {
140        if b >= self.beads || xyz.len() != self.atoms {
141            return Err(Error::BufferSize);
142        }
143        let moved = self.bead_moved(b, xyz);
144        let base = b * self.atoms;
145        self.last[base..base + self.atoms].copy_from_slice(xyz);
146        if moved {
147            self.rebuild_from_last()?;
148        } else {
149            self.filter_bead(b, xyz)?;
150        }
151        Ok(&self.frames[b])
152    }
153
154    fn bead_moved(&self, b: usize, xyz: &[[f64; 3]]) -> bool {
155        let half = self.skin * 0.5;
156        let room2 = half * half;
157        let base = b * self.atoms;
158        for (p, r) in xyz.iter().zip(self.last[base..base + self.atoms].iter()) {
159            let dx = p[0] - r[0];
160            let dy = p[1] - r[1];
161            let dz = p[2] - r[2];
162            if dx * dx + dy * dy + dz * dz > room2 {
163                return true;
164            }
165        }
166        false
167    }
168
169    fn rebuild_from_last(&mut self) -> Result<(), Error> {
170        let centroid = ring_centroid(&self.cell, self.beads, &self.last)?;
171        let mut spread2 = 0.0;
172        for (a, centre) in centroid.iter().enumerate() {
173            for b in 0..self.beads {
174                let d2 = self.cell.dist2(*centre, self.last[b * self.atoms + a]);
175                if d2 > spread2 {
176                    spread2 = d2;
177                }
178            }
179        }
180        self.spread = spread2.sqrt();
181        let reach = self.cutoff + 2.0 * self.spread + self.skin;
182        self.soa = gather_candidates(&centroid, &self.cell, reach, self.half)?;
183        self.filter_all()
184    }
185
186    fn filter_bead(&mut self, b: usize, xyz: &[[f64; 3]]) -> Result<(), Error> {
187        let mut vectors = Vec::new();
188        self.soa.filter(
189            xyz,
190            &self.cell,
191            self.cutoff * self.cutoff,
192            false,
193            &mut self.d2,
194            &mut self.frames[b],
195            &mut vectors,
196        )
197    }
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203    use crate::pairs::pairs_within_columns;
204
205    fn canon(cols: &PairColumns) -> Vec<(i32, i32, [i32; 3])> {
206        let mut v: Vec<_> = (0..cols.len())
207            .map(|k| {
208                let (i, j, s) = (cols.i[k], cols.j[k], cols.shift[k]);
209                if i < j
210                    || (i == j
211                        && (s[0] < 0 || (s[0] == 0 && (s[1] < 0 || (s[1] == 0 && s[2] < 0)))))
212                {
213                    (i, j, s)
214                } else {
215                    (j, i, [-s[0], -s[1], -s[2]])
216                }
217            })
218            .collect();
219        v.sort_unstable();
220        v
221    }
222
223    #[test]
224    fn each_bead_matches_its_own_list() {
225        let cell = Cell::ortho(14.0, 14.0, 14.0).unwrap();
226        let atoms = 40;
227        let beads = 4;
228        let mut xyz = vec![[0.0; 3]; beads * atoms];
229        let mut state = 7_u64;
230        for a in 0..atoms {
231            state = state.wrapping_mul(6364136223846793005).wrapping_add(1);
232            let base = [
233                (state >> 11) as f64 / (1u64 << 53) as f64 * 14.0,
234                {
235                    state = state.wrapping_mul(6364136223846793005).wrapping_add(1);
236                    (state >> 11) as f64 / (1u64 << 53) as f64 * 14.0
237                },
238                {
239                    state = state.wrapping_mul(6364136223846793005).wrapping_add(1);
240                    (state >> 11) as f64 / (1u64 << 53) as f64 * 14.0
241                },
242            ];
243            for b in 0..beads {
244                xyz[b * atoms + a] = [
245                    (base[0] + 0.03 * b as f64).rem_euclid(14.0),
246                    base[1],
247                    base[2],
248                ];
249            }
250        }
251        let rep = ReplicaList::build(&xyz, beads, cell, 3.2, 0.5, true).unwrap();
252        assert!(rep.spread() < 0.2);
253        for b in 0..beads {
254            let mut fresh = PairColumns::default();
255            pairs_within_columns(
256                &xyz[b * atoms..(b + 1) * atoms],
257                &cell,
258                3.2,
259                None,
260                None,
261                true,
262                &mut fresh,
263            )
264            .unwrap();
265            assert_eq!(canon(rep.bead(b).unwrap()), canon(&fresh));
266        }
267        let mut moved = xyz[0..atoms].to_vec();
268        for p in &mut moved {
269            p[1] += 0.01;
270        }
271        let mut owned = ReplicaList::build(&xyz, beads, cell, 3.2, 0.5, true).unwrap();
272        let cols = owned.update_bead(0, &moved).unwrap();
273        let mut fresh = PairColumns::default();
274        pairs_within_columns(&moved, &cell, 3.2, None, None, true, &mut fresh).unwrap();
275        assert_eq!(canon(cols), canon(&fresh));
276        assert!(!rep.sparsity().is_empty());
277    }
278}