linkcell 0.4.2

Periodic linked-cell cutoff pairs and k-nearest neighbour search
Documentation
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
//! Open-cell pairs: occupied Cartesian bins, no periodic padding.

use std::collections::BTreeMap;
use std::sync::Mutex;

use linkcell::{
    cell_for_pbc, lc_cell, lc_pair, pairs_open, pairs_within, pairs_within_pbc, stencil_builds,
    Cell, Error, PbcQuery,
};

static LOCK: Mutex<()> = Mutex::new(());

type Key = (usize, usize, [i32; 3]);

fn xorshift(state: &mut u64) -> u64 {
    *state ^= state.wrapping_shl(13);
    *state ^= state.wrapping_shr(7);
    *state ^= state.wrapping_shl(17);
    *state
}

fn cluster() -> Vec<[f64; 3]> {
    let mut xyz = Vec::with_capacity(27);
    for iz in 0..3 {
        for iy in 0..3 {
            for ix in 0..3 {
                xyz.push([(ix + 2) as f64, (iy + 2) as f64, (iz + 2) as f64]);
            }
        }
    }
    xyz
}

/// One step of the corner atom. Seed 42 and step 0.25 change the
/// bounding span on 267 of 400 moves.
fn nudge(xyz: &mut [[f64; 3]], state: &mut u64) {
    let step = 0.25;
    for coord in &mut xyz[26] {
        let draw = xorshift(state);
        let unit = (draw % 10001) as f64 / 10000.0;
        *coord += unit * 2.0 * step - step;
    }
}

fn padded_box(xyz: &[[f64; 3]], cutoff: f64) -> Cell {
    let mut length = [0.0; 3];
    for axis in 0..3 {
        let mut lo = f64::INFINITY;
        let mut hi = f64::NEG_INFINITY;
        for point in xyz {
            lo = lo.min(point[axis]);
            hi = hi.max(point[axis]);
        }
        let span = if lo.is_finite() {
            (hi - lo).max(0.0)
        } else {
            0.0
        };
        length[axis] = 2.0 * span + 4.0 * cutoff + 10.0;
    }
    Cell::ortho(length[0], length[1], length[2]).unwrap()
}

fn map_of(rows: &[linkcell::Pair]) -> BTreeMap<Key, f64> {
    rows.iter()
        .map(|pair| ((pair.i, pair.j, pair.shift), pair.dist2))
        .collect()
}

fn brute_open(xyz: &[[f64; 3]], cutoff: f64, half: bool) -> BTreeMap<Key, f64> {
    let mut found = BTreeMap::new();
    let limit = cutoff * cutoff;
    for i in 0..xyz.len() {
        for j in 0..xyz.len() {
            if i == j || (half && i > j) {
                continue;
            }
            let dx = xyz[j][0] - xyz[i][0];
            let dy = xyz[j][1] - xyz[i][1];
            let dz = xyz[j][2] - xyz[i][2];
            let dist2 = dx * dx + dy * dy + dz * dz;
            if dist2 < limit {
                found.insert((i, j, [0, 0, 0]), dist2);
            }
        }
    }
    found
}

fn assert_same(rows: &[linkcell::Pair], want: &BTreeMap<Key, f64>) {
    let got = map_of(rows);
    assert_eq!(got.len(), rows.len(), "duplicate rows");
    assert_eq!(got, *want);
}

#[test]
fn four_hundred_moves_keep_the_open_stencil() {
    let _guard = LOCK.lock().unwrap_or_else(|err| err.into_inner());
    let cutoff = 2.5;
    let hint = Some(8.0);
    let mut xyz = cluster();
    let box0 = padded_box(&xyz, cutoff);
    pairs_within(&xyz, &box0, cutoff, None, hint, true).unwrap();
    let before = stencil_builds();
    let mut state = 42u64;
    for _ in 0..400 {
        nudge(&mut xyz, &mut state);
        let widened = padded_box(&xyz, cutoff);
        pairs_within(&xyz, &widened, cutoff, None, hint, true).unwrap();
    }
    let padded = stencil_builds() - before;
    assert_eq!(
        padded, 267,
        "padding each open axis rebuilds the stencil when the span changes"
    );

    let mut xyz = cluster();
    let first = pairs_open(&xyz, cutoff, hint).unwrap();
    assert_same(&first, &brute_open(&xyz, cutoff, true));
    let before = stencil_builds();
    let mut state = 42u64;
    for _ in 0..400 {
        nudge(&mut xyz, &mut state);
        let rows = pairs_open(&xyz, cutoff, hint).unwrap();
        assert_same(&rows, &brute_open(&xyz, cutoff, true));
    }
    assert_eq!(
        stencil_builds() - before,
        0,
        "the walk stays inside the Cartesian bin of edge 8, so the bounding bins do not change"
    );
}

#[test]
fn open_reach_past_the_image_cast_is_too_many_images() {
    let err = pairs_open(
        &[[0.0, 0.0, 0.0], [0.5, 0.0, 0.0]],
        2_147_483_646.0,
        Some(1.0),
    )
    .unwrap_err();
    assert_eq!(err, Error::TooManyImages);
}

#[test]
fn crossing_a_bin_face_keeps_the_open_stencil() {
    let _guard = LOCK.lock().unwrap_or_else(|err| err.into_inner());
    let mut xyz = cluster();
    pairs_open(&xyz, 2.5, Some(8.0)).unwrap();
    let before = stencil_builds();
    xyz[26][0] += 20.0;
    let rows = pairs_open(&xyz, 2.5, Some(8.0)).unwrap();
    assert_same(&rows, &brute_open(&xyz, 2.5, true));
    assert_eq!(stencil_builds() - before, 0);
    pairs_open(&xyz, 2.5, Some(8.0)).unwrap();
    assert_eq!(stencil_builds() - before, 0);
}

/// A periodic axis keeps the per-bin link list, so the bounding bins are
/// still part of its key.
#[test]
fn crossing_an_open_face_of_a_slab_rebuilds_once() {
    let _guard = LOCK.lock().unwrap_or_else(|err| err.into_inner());
    let (cell, mut xyz) = slab();
    let query = PbcQuery::new([true, true, false], 2.2).half(true);
    pairs_within_pbc(&xyz, &cell, &query).unwrap();
    let before = stencil_builds();
    xyz[3][2] += 9.0;
    let rows = pairs_within_pbc(&xyz, &cell, &query).unwrap();
    assert_same(&rows, &brute_slab(&xyz, &cell, 2.2));
    assert_eq!(stencil_builds() - before, 1);
    pairs_within_pbc(&xyz, &cell, &query).unwrap();
    assert_eq!(stencil_builds() - before, 1);
}

fn water_at(origin: [f64; 3]) -> Vec<[f64; 3]> {
    [[0.0, 0.0, 0.0], [0.757, 0.586, 0.0], [-0.757, 0.586, 0.0]]
        .iter()
        .map(|p| [p[0] + origin[0], p[1] + origin[1], p[2] + origin[2]])
        .collect()
}

/// A small molecule that moves, also across bin faces, keeps the stencil
/// it first built, on the half and the full list.
#[test]
fn small_molecules_build_the_open_stencil_at_most_once() {
    let _guard = LOCK.lock().unwrap_or_else(|err| err.into_inner());
    let cutoff = 2.0;
    pairs_open(&cluster(), 1.7, None).unwrap();
    let before = stencil_builds();
    let mut state = 99u64;
    for step in 0..300 {
        let drift = |state: &mut u64| (xorshift(state) % 10_001) as f64 / 10_000.0 - 0.5;
        let origin = [
            5.0 + 0.01 * step as f64 + drift(&mut state),
            5.0 - 0.02 * step as f64 + drift(&mut state),
            5.0 + drift(&mut state),
        ];
        let mut xyz = water_at(origin);
        if step % 3 == 0 {
            xyz.extend(water_at([origin[0] + 2.8, origin[1], origin[2] + 0.4]));
        }
        let rows = pairs_open(&xyz, cutoff, None).unwrap();
        assert_same(&rows, &brute_open(&xyz, cutoff, true));
        let full = pairs_within_pbc(
            &xyz,
            &Cell::ortho(1.0, 1.0, 1.0).unwrap(),
            &PbcQuery::open(cutoff),
        )
        .unwrap();
        assert_same(&full, &brute_open(&xyz, cutoff, false));
    }
    let builds = stencil_builds() - before;
    assert!(
        builds <= 1,
        "a small molecule built the open stencil {builds} times"
    );
}

/// A cutoff of many bin edges reaches past the stored rows. Frames that
/// span more bins widen the table a bounded number of times, only on the
/// axis they outgrow, and still match brute force. A reach of a million
/// bins does not walk the whole reach.
#[test]
fn a_long_reach_widens_the_open_rows_and_matches_brute_force() {
    let _guard = LOCK.lock().unwrap_or_else(|err| err.into_inner());
    let cutoff = 6.0;
    let hint = Some(0.25);
    let mut state = 0x5eed_u64;
    let mut frames = Vec::new();
    for size in [2.0, 6.0, 12.0, 3.0, 12.0] {
        let xyz: Vec<[f64; 3]> = (0..40)
            .map(|_| {
                [
                    10.0 + size * (xorshift(&mut state) % 1000) as f64 / 1000.0,
                    10.0 + size * (xorshift(&mut state) % 1000) as f64 / 1000.0,
                    10.0 + size * (xorshift(&mut state) % 1000) as f64 / 1000.0,
                ]
            })
            .collect();
        frames.push(xyz);
    }
    pairs_open(&frames[0], cutoff, hint).unwrap();
    let before = stencil_builds();
    for xyz in &frames {
        for half in [true, false] {
            let query = PbcQuery::open(cutoff).half(half).cell_hint(hint);
            let rows = pairs_within_pbc(xyz, &Cell::ortho(1.0, 1.0, 1.0).unwrap(), &query).unwrap();
            assert_same(&rows, &brute_open(xyz, cutoff, half));
        }
    }
    assert_eq!(
        stencil_builds() - before,
        1,
        "the 6 Ã… frame widens the rows to the whole reach of 26 bins once"
    );

    let line = |axis: usize| -> Vec<[f64; 3]> {
        (0..12)
            .map(|k| {
                let mut p = [10.0, 10.0, 10.0];
                p[axis] += 0.9 * k as f64;
                p
            })
            .collect()
    };
    pairs_open(&frames[0], cutoff, Some(0.2)).unwrap();
    let before = stencil_builds();
    for axis in [1, 2, 1, 2] {
        let xyz = line(axis);
        let rows = pairs_open(&xyz, cutoff, Some(0.2)).unwrap();
        assert_same(&rows, &brute_open(&xyz, cutoff, true));
    }
    assert_eq!(
        stencil_builds() - before,
        2,
        "a frame long on y and then one long on z each widen their own axis"
    );

    let pair = [[0.0, 0.0, 0.0], [0.5, 0.0, 0.0], [3.0e5, 0.0, 0.0]];
    let rows = pairs_open(&pair, 1.0e6, Some(1.0)).unwrap();
    assert_same(&rows, &brute_open(&pair, 1.0e6, true));
}

/// Band images of one molecule sit in different bins and span different
/// bin counts. Visiting them in turn is the contact check of a band step.
#[test]
fn alternating_open_frames_share_one_stencil() {
    let _guard = LOCK.lock().unwrap_or_else(|err| err.into_inner());
    let cutoff = 1.5;
    let near = cluster();
    let mut far: Vec<[f64; 3]> = near
        .iter()
        .map(|p| [1.3 * p[0] + 7.1, 0.9 * p[1] - 3.4, 1.1 * p[2] + 11.6])
        .collect();
    far[5][1] -= 2.2;
    let frames = [near, far];
    pairs_open(&frames[0], cutoff, None).unwrap();
    let before = stencil_builds();
    for round in 0..20 {
        let xyz = &frames[round % 2];
        let rows = pairs_open(xyz, cutoff, None).unwrap();
        assert_same(&rows, &brute_open(xyz, cutoff, true));
    }
    assert_eq!(
        stencil_builds() - before,
        0,
        "an open stencil depends on the bin edge and the cutoff, not on the occupied bins"
    );
}

#[test]
fn randomized_clusters_match_brute_force_and_a_large_box() {
    let _guard = LOCK.lock().unwrap_or_else(|err| err.into_inner());
    let mut state = 0x1234_5678_9abc_def0u64;
    for trial in 0..12 {
        let n = 5 + (xorshift(&mut state) % 20) as usize;
        let mut xyz = Vec::with_capacity(n);
        for _ in 0..n {
            xyz.push([
                20.0 + (xorshift(&mut state) % 10_000) as f64 / 1000.0,
                20.0 + (xorshift(&mut state) % 10_000) as f64 / 1000.0,
                20.0 + (xorshift(&mut state) % 10_000) as f64 / 1000.0,
            ]);
        }
        let cutoff = 1.2 + (trial % 4) as f64 * 0.4;
        let hint = if trial % 2 == 0 { None } else { Some(1.5) };
        for half in [true, false] {
            let query = PbcQuery::open(cutoff).half(half).cell_hint(hint);
            let dummy = Cell::ortho(1.0, 1.0, 1.0).unwrap();
            let rows = pairs_within_pbc(&xyz, &dummy, &query).unwrap();
            assert_same(&rows, &brute_open(&xyz, cutoff, half));
            if half {
                let big = Cell::ortho(80.0, 80.0, 80.0).unwrap();
                let periodic = pairs_within(&xyz, &big, cutoff, None, hint, true).unwrap();
                let open_pairs: BTreeMap<_, _> = map_of(&rows);
                let periodic_pairs = map_of(&periodic);
                assert!(periodic_pairs.keys().all(|key| key.2 == [0, 0, 0]));
                assert_eq!(
                    open_pairs.keys().collect::<Vec<_>>(),
                    periodic_pairs.keys().collect::<Vec<_>>()
                );
            }
        }
    }
}

/// Ten points in a 5 x 6 x 8 cell, inside the cell on the periodic x
/// and y.
fn slab() -> (Cell, Vec<[f64; 3]>) {
    let cell = Cell::ortho(5.0, 6.0, 8.0).unwrap();
    let mut state = 7u64;
    let mut xyz = Vec::new();
    for _ in 0..10 {
        xyz.push([
            (xorshift(&mut state) % 5000) as f64 / 1000.0,
            (xorshift(&mut state) % 6000) as f64 / 1000.0,
            1.0 + (xorshift(&mut state) % 4000) as f64 / 1000.0,
        ]);
    }
    (cell, xyz)
}

/// Half list of a slab periodic on x and y, by scanning one image on each.
fn brute_slab(xyz: &[[f64; 3]], cell: &Cell, cutoff: f64) -> BTreeMap<Key, f64> {
    let mut want = BTreeMap::new();
    let limit = cutoff * cutoff;
    let span = [1i32, 1, 0];
    for i in 0..xyz.len() {
        for j in 0..xyz.len() {
            if i > j {
                continue;
            }
            for sa in -span[0]..=span[0] {
                for sb in -span[1]..=span[1] {
                    let shift = [sa, sb, 0];
                    if i == j && shift == [0, 0, 0] {
                        continue;
                    }
                    if i == j && shift[0] > 0 {
                        continue;
                    }
                    if i == j && shift[0] == 0 && shift[1] > 0 {
                        continue;
                    }
                    let delta = cell.lattice_shift(sa, sb, 0);
                    let dx = xyz[j][0] + delta[0] - xyz[i][0];
                    let dy = xyz[j][1] + delta[1] - xyz[i][1];
                    let dz = xyz[j][2] + delta[2] - xyz[i][2];
                    let dist2 = dx * dx + dy * dy + dz * dz;
                    if dist2 < limit {
                        want.insert((i, j, shift), dist2);
                    }
                }
            }
        }
    }
    want
}

#[test]
fn mixed_slab_matches_an_image_scan() {
    let _guard = LOCK.lock().unwrap_or_else(|err| err.into_inner());
    let (cell, xyz) = slab();
    let periodic = [true, true, false];
    let cutoff = 2.2;
    let query = PbcQuery::new(periodic, cutoff).half(true);
    let rows = pairs_within_pbc(&xyz, &cell, &query).unwrap();
    let want = brute_slab(&xyz, &cell, cutoff);
    assert_same(&rows, &want);
    assert!(!want.is_empty());
}

#[test]
fn closed_cutoff_keeps_the_boundary() {
    let _guard = LOCK.lock().unwrap_or_else(|err| err.into_inner());
    let xyz = [[0.0, 0.0, 0.0], [2.5, 0.0, 0.0]];
    let cell = Cell::ortho(1.0, 1.0, 1.0).unwrap();
    let strict = pairs_within_pbc(&xyz, &cell, &PbcQuery::open(2.5).half(true)).unwrap();
    assert!(strict.is_empty());
    let closed =
        pairs_within_pbc(&xyz, &cell, &PbcQuery::open(2.5).half(true).closed(true)).unwrap();
    assert_eq!(closed.len(), 1);
    assert_eq!(closed[0].dist2, 6.25);
}

#[test]
fn mask_drops_a_point() {
    let _guard = LOCK.lock().unwrap_or_else(|err| err.into_inner());
    let xyz = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.2, 0.0, 0.0]];
    let cell = Cell::ortho(1.0, 1.0, 1.0).unwrap();
    let query = PbcQuery::open(2.0)
        .half(true)
        .mask(Some(&[true, false, true]));
    let rows = pairs_within_pbc(&xyz, &cell, &query).unwrap();
    assert_eq!(rows.len(), 1);
    assert_eq!((rows[0].i, rows[0].j), (0, 2));
}

#[test]
fn zero_open_vector_still_bins() {
    let _guard = LOCK.lock().unwrap_or_else(|err| err.into_inner());
    let rows = [[4.0, 0.0, 0.0], [0.0, 5.0, 0.0], [0.0, 0.0, 0.0]];
    let cell = cell_for_pbc(rows, [0.0, 0.0, 0.0], [true, true, false]).unwrap();
    let xyz = [[0.2, 0.2, 1.0], [3.9, 0.3, 1.2], [0.4, 0.2, 3.0]];
    let query = PbcQuery::new([true, true, false], 2.0).half(true);
    let found = pairs_within_pbc(&xyz, &cell, &query).unwrap();
    assert!(!found.is_empty());
    assert!(found.iter().all(|pair| pair.shift[2] == 0));
}

extern "C" {
    fn lc_pairs_open(
        xyz: *const f64,
        n: usize,
        cutoff: f64,
        cell_hint: f64,
        out: *mut lc_pair,
        cap: usize,
        out_count: *mut usize,
    ) -> i32;
    fn lc_stencil_builds() -> u64;
    fn lc_pairs_within_pbc(
        xyz: *const f64,
        n: usize,
        simbox: *const lc_cell,
        pbc: *const i32,
        cutoff: f64,
        mask: *const i32,
        cell_hint: f64,
        half: i32,
        closed: i32,
        exclude_self_images: i32,
        out: *mut lc_pair,
        cap: usize,
        out_count: *mut usize,
    ) -> i32;
}

#[test]
fn c_api_open_list_matches_the_rust_rows() {
    let _guard = LOCK.lock().unwrap_or_else(|err| err.into_inner());
    let xyz = cluster();
    let flat: Vec<f64> = xyz.iter().flat_map(|p| *p).collect();
    let want = pairs_open(&xyz, 2.5, Some(8.0)).unwrap();
    let mut count = 0usize;
    let query = unsafe {
        lc_pairs_open(
            flat.as_ptr(),
            xyz.len(),
            2.5,
            8.0,
            std::ptr::null_mut(),
            0,
            &mut count,
        )
    };
    assert_eq!(query, 0);
    assert_eq!(count, want.len());
    let mut out = vec![lc_pair::default(); count];
    let mut wrote = 0usize;
    let fill = unsafe {
        lc_pairs_open(
            flat.as_ptr(),
            xyz.len(),
            2.5,
            8.0,
            out.as_mut_ptr(),
            count,
            &mut wrote,
        )
    };
    assert_eq!(fill, 0);
    assert_eq!(wrote, want.len());
    for (got, row) in out.iter().zip(&want) {
        assert_eq!(got.i as usize, row.i);
        assert_eq!(got.j as usize, row.j);
        assert_eq!(got.shift, row.shift);
        assert_eq!(got.dist2, row.dist2);
    }
    let builds = unsafe { lc_stencil_builds() };
    assert!(builds >= stencil_builds());
    let _ = builds;

    let cell = Cell::ortho(9.0, 9.0, 9.0).unwrap();
    let raw = lc_cell {
        ax: 9.0,
        ay: 0.0,
        az: 0.0,
        bx: 0.0,
        by: 9.0,
        bz: 0.0,
        cx: 0.0,
        cy: 0.0,
        cz: 9.0,
        ox: 0.0,
        oy: 0.0,
        oz: 0.0,
    };
    let pbc = [1, 1, 0];
    let mut count = 0usize;
    let status = unsafe {
        lc_pairs_within_pbc(
            flat.as_ptr(),
            xyz.len(),
            &raw,
            pbc.as_ptr(),
            2.5,
            std::ptr::null(),
            0.0,
            1,
            0,
            0,
            std::ptr::null_mut(),
            0,
            &mut count,
        )
    };
    assert_eq!(status, 0);
    let rust = pairs_within_pbc(
        &xyz,
        &cell,
        &PbcQuery::new([true, true, false], 2.5).half(true),
    )
    .unwrap();
    assert_eq!(count, rust.len());
}