1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
// FIXME: derived serde traits do not yet show up as feature-gated
// FIXME: cf. https://github.com/rust-lang/rust/issues/103300
//! `zelll`[^etymology] provides a Rust implementation of the __cell lists__ algorithm.
//!
//! Particle simulations usually require to compute interactions between those particles.
//! Considering all _pairwise_ interactions of _`n`_ particles would be of time complexity _`O(n²)`_.\
//! Cell lists facilitate _linear-time_ enumeration of particle pairs closer than a certain
//! cutoff distance by dividing the enclosing bounding box into (cuboid) grid cells.
//!
//! # Caveats
//!
//! `zelll` is motivated by _coarse-grained_ (bio-)molecular simulations but is not restricted to that.\
//! This is reflected by a few points:
//!
//! - internally, the simulation box is represented by a (sparse) hash map only storing non-empty grid cells,
//! which gives an upper bound for memory usage of _`n`_
//! - bounding boxes are assumed to change and are computed from particle data\
//! (future APIs may be added to set a fixed bounding box)
//! - instead of cell _lists_, slices into a contiguous storage buffer are used
//! - periodic boundary conditions are currently not supported
//! - parts of this implementation are more cache-aware than others, which becomes noticeable with
//! larger data sets\
//! (at `10⁶` -- `10⁷` particles, mostly depending on last-level cache size)
//! but is less pronounced with structured data[^structureddata]
//!
//! # Usage
//!
//! The general pattern in which this crate is intended to be used is roughly:
//!
//! 1. construct `CellGrid` from particle positions
//! 2. enumerate pairs in order to compute particle interactions
//! 3. simulate particle motion
//! 4. rebuild `CellGrid` from updated particle positions
//!
//! This crate only provides iteration over particle pairs.
//! It is left to the user to filter (e.g. by distance) and compute interaction potentials.
//! The `rayon` feature enables parallel iteration. Performance gains depend on data size and
//! computational cost per pair though. Benchmarks are encouraged.
//!
//! While the main struct [`CellGrid`] is generic over dimension `N`,
//! it is intended to be used with `N = 2` or `N = 3`.
//! Data represented as fixed-size arrays is supported by wrapping in [`Particle`].\
//! Additionally, implementing [`ParticleLike`] allows usage of custom types as particle data.
//! This can be used to encode different kinds of particles or enable interior mutability if required.
//!
//! # Examples
//! ```
//! use zelll::CellGrid;
//!
//! let data = vec![[0.0, 0.0, 0.0], [1.0,2.0,0.0], [0.0, 0.1, 0.2]];
//! let mut cg = CellGrid::new(data.iter().copied().enumerate(), 1.0);
//!
//! for ((i, p), (j, q)) in cg.particle_pairs() {
//! /* do some work */
//! }
//!
//! cg.rebuild_mut(data.iter().copied().enumerate(), Some(0.5));
//! ```
//!
//! [^etymology]: abbrv. from German _Zelllisten_ /ˈʦɛlɪstən/, for cell lists.
//! [^structureddata]: Usually, (bio-)molecular data files are not completely unordered
//! even though they could be.
//! In practice, it may be a reasonable assumption that sequentially proximate
//! particles often have spatially clustered coordinates as well.
// inlined re-exports
pub use crateCellGrid;
/// Particle data trait.
///
/// This trait is required for types used with [`CellGrid`]
/// which needs to know how to get coordinate data.\
///
/// <div class="warning">
///
/// `ParticleLike` is a subtrait of [`Clone`].
/// This allows to use the [_interior mutability_](https://doc.rust-lang.org/stable/std/cell/index.html#when-to-choose-interior-mutability) pattern.
///
/// Usually, [`Copy`] types are preferable (they tend to implement `Clone` by copying).
/// In general, the smaller the type, the better (for the CPU cache).
///
/// </div>
///
/// Note that [`CellGrid`] is more specific than this trait and requires implementing `ParticleLike<[{float}; N]>`.
///
/// We do not provide a blanket implementation for types implementing `Into<[T; N]> + Copy` but
/// a wrapper type instead.
/// Therefore, [`nalgebra::SVector`](https://docs.rs/nalgebra/latest/nalgebra/base/type.SVector.html), or types that can be `Deref`-coerced
/// into the former or [`mint`](https://docs.rs/mint/latest/mint/) types, can be used
/// by wrapping them in [`Particle`].
///
/// For convenience, this trait is implemented for `[{float}; N]` and key-value tuples.
///
/// Having custom types implement this trait allows for patterns like interior mutability,
/// referencing separate storage (e.g. with ECS, or concurrent storage types),
/// or particle data being of different kinds.
///
/// # Examples
/// ```
/// # use zelll::ParticleLike;
/// # #[derive(Clone, Copy)]
/// # enum Element {
/// # Hydrogen, // no associated coordinate data since it's the same for all variants
/// # Oxygen,
/// # // ...
/// # }
/// #
/// // Typically, we would associate data with `Element` variants for concise code
/// // but here, every variant would carry the same type of data.
/// #[derive(Clone, Copy)]
/// struct Atom {
/// kind: Element,
/// coords: [f64; 3],
/// }
/// impl ParticleLike for Atom {
/// #[inline]
/// fn coords(&self) -> [f64; 3] {
/// self.coords // no pattern matching required here
/// }
/// }
/// ```
/// Wrapper type that implements [`ParticleLike`] for types that are `Into<[T; N]> + Copy`.
///
/// Notable types that can be used with `Particle` include `({float}, ...)`,
/// [`nalgebra::SVector`](https://docs.rs/nalgebra/latest/nalgebra/base/type.SVector.html),
/// or [`mint`](https://docs.rs/mint/latest/mint/) types.
///
/// `Particle` can be `Deref`-coerced into the wrapped type.
///
/// # Examples
/// ```
/// use zelll::{Particle, ParticleLike};
///
/// let x: Particle<_> = (0.0f64, 0.0f64, 0.0f64).into();
/// x.coords();
/// ```
/// # Examples
/// Wrapping an array is redundant but illustrates the `Deref` behavior:
/// ```
/// # use zelll::{Particle, ParticleLike};
/// let x = Particle::from([0.0f64; 3]);
/// x.coords(); // calls impl ParticleLike<T> for Particle<P>
/// (*x).coords(); // calls impl ParticleLike<T> for P where P: ParticleLike<T>
/// ```
/// Sometimes, it is useful to store indices alongside particle data.
/// This is easily facilitated by enumerating the iterator used to construct a `CellGrid`.
///
/// Other types such as [`std::collections::HashMap`] can also be used
/// although it is less straight-forward.
///
/// <div class="warning">
///
/// See
/// [`impl ParticleLike<[T; N]> for &P`](#impl-ParticleLike%3C%5BT;+N%5D%3E-for-%26P)
/// for more information.
///
/// </div>
///
/// # Examples
/// Here, `ip` is a tuple `(usize, P)`.
/// ```
/// # use zelll::ParticleLike;
/// # let x = [0.0f64; 3];
/// # let points: Vec<_> = std::iter::repeat_n(x, 10).collect();
/// points.iter()
/// .copied()
/// .enumerate()
/// .map(|ip| ip.coords());
/// ```
/// ```
/// # use zelll::ParticleLike;
/// # use std::collections::HashMap;
/// # let data = [("a", [0.0f64; 3]); 10];
/// let points = HashMap::from(data);
/// // this iterator is consuming
/// points.into_iter().map(|kv| kv.coords());
/// // after constructing a CellGrid
/// // and iterating over pairs, the particles have to be inserted
/// // into a hash map again to do any meaningful work
/// ```
/// References to `ParticleLike` types can also be used with
/// [`CellGrid`].
///
/// <div class="warning">
///
/// This trait `impl` aims to support collections like `HashMap` in an ergonomic way.
/// Usually, `CellGrid` is intended to be used without references to particle data, i.e. use
/// `.iter().copied()` where possible (and `.enumerate()` if preferable).
///
/// </div>
///
/// # Examples
/// `HashMap::iter()` cannot be used with [`Iterator::copied()`]:
/// ```compile_fail
/// # use zelll::ParticleLike;
/// # use std::collections::HashMap;
/// let data = [("a", [0.0f64; 3]); 10];
/// let points = HashMap::from(data);
/// // this iterator is not consuming the hash map
/// points.iter()
/// .copied() // this does not work on HashMap
/// .map(|kv| kv.coords());
/// ```
/// Either just iterate by reference if you cannot consume the hash map using `.into_iter()`:
/// ```
/// # use zelll::ParticleLike;
/// # use std::collections::HashMap;
/// # let data = [("a", [0.0f64; 3]); 10];
/// # let points = HashMap::from(data);
/// // this iterator is not consuming the hash map
/// points.iter().map(|kv| kv.coords());
/// ```
/// Or replicate `.copied()` behavior manually (preferred method):
/// ```
/// # use zelll::ParticleLike;
/// # use std::collections::HashMap;
/// # let data = [("a", [0.0f64; 3]); 10];
/// # let points = HashMap::from(data);
/// // this iterator manually copies its values
/// points.iter()
/// .map(|(&k, &v)| (k, v))
/// .map(|kv| kv.coords());
/// ```