linkcell 0.4.1

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
#ifndef LINKCELL_HPP
#define LINKCELL_HPP

#if defined(_MSC_VER)
#if !defined(_MSVC_LANG) || _MSVC_LANG < 201703L
#error "linkcell.hpp requires C++17 or later"
#endif
#elif defined(__cplusplus) && __cplusplus < 201703L
#error "linkcell.hpp requires C++17 or later"
#endif

extern "C" {
#include "linkcell.h"
}

#include <array>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>

namespace linkcell {

/// Failure from a neighbour search. `status()` is the C ABI return
/// (0 success, nonzero failure).
class Error : public std::runtime_error {
public:
  Error(int status, std::string message)
      : std::runtime_error(message.empty() ? "linkcell: knearest failed"
                                           : std::move(message)),
        status_(status) {}

  explicit Error(std::string message) : Error(1, std::move(message)) {}

  [[nodiscard]] int status() const noexcept { return status_; }

private:
  int status_;
};

/// Periodic parallelepiped. Fields match `lc_cell` (lattice vectors
/// a, b, c and dump-cell origin).
struct Cell {
  std::array<double, 3> a{};
  std::array<double, 3> b{};
  std::array<double, 3> c{};
  std::array<double, 3> origin{};

  Cell() = default;

  explicit Cell(const lc_cell &raw) noexcept
      : a{raw.ax, raw.ay, raw.az}, b{raw.bx, raw.by, raw.bz},
        c{raw.cx, raw.cy, raw.cz}, origin{raw.ox, raw.oy, raw.oz} {}

  static Cell ortho(double lx, double ly, double lz) noexcept {
    Cell cell;
    cell.a = {lx, 0.0, 0.0};
    cell.b = {0.0, ly, 0.0};
    cell.c = {0.0, 0.0, lz};
    return cell;
  }

  static Cell from_vectors(std::array<double, 3> a, std::array<double, 3> b,
                           std::array<double, 3> c,
                           std::array<double, 3> origin = {}) noexcept {
    Cell cell;
    cell.a = a;
    cell.b = b;
    cell.c = c;
    cell.origin = origin;
    return cell;
  }

  [[nodiscard]] lc_cell raw() const noexcept {
    return lc_cell{a[0],        a[1],        a[2],        b[0],
                   b[1],        b[2],        c[0],        c[1],
                   c[2],        origin[0],   origin[1],   origin[2]};
  }

  [[nodiscard]] explicit operator lc_cell() const noexcept { return raw(); }
};

/// Owned packed n-by-k neighbour indices.
///
/// `data()[i * k() + j]` is the j-th neighbour of source i, nearest
/// first. The slot is -1 when that neighbour is missing (masked or
/// isolated).
class Neighbours {
public:
  Neighbours() = default;

  Neighbours(std::vector<int> idx, std::size_t n, std::size_t k)
      : Neighbours(std::move(idx),
                   std::vector<double>(n * k, std::numeric_limits<double>::quiet_NaN()),
                   n, k) {}

  Neighbours(std::vector<int> idx, std::vector<double> d2, std::size_t n,
             std::size_t k)
      : idx_(std::move(idx)), d2_(std::move(d2)), n_(n), k_(k) {
    if (k != 0 && n > std::numeric_limits<std::size_t>::max() / k) {
      throw Error("n * k overflows");
    }
    if (idx_.size() != n * k || d2_.size() != n * k) {
      throw Error("out buffer length must be n * k");
    }
  }

  /// j-th neighbour of source i, or -1 if missing.
  [[nodiscard]] int neighbour(std::size_t i, std::size_t j) const {
    if (i >= n_ || j >= k_) {
      throw std::out_of_range("linkcell: neighbour index out of range");
    }
    return idx_[i * k_ + j];
  }

  /// Squared distance of neighbour (i, j). Unused slots are NaN.
  [[nodiscard]] double dist2(std::size_t i, std::size_t j) const {
    if (i >= n_ || j >= k_) {
      throw std::out_of_range("linkcell: neighbour index out of range");
    }
    return d2_[i * k_ + j];
  }

  [[nodiscard]] std::size_t n() const noexcept { return n_; }
  [[nodiscard]] std::size_t k() const noexcept { return k_; }
  [[nodiscard]] std::size_t size() const noexcept { return n_ * k_; }
  [[nodiscard]] const int *data() const noexcept { return idx_.data(); }
  [[nodiscard]] const double *distances() const noexcept { return d2_.data(); }
  [[nodiscard]] const int *begin() const noexcept { return idx_.data(); }
  [[nodiscard]] const int *end() const noexcept { return idx_.data() + size(); }

private:
  std::vector<int> idx_;
  std::vector<double> d2_;
  std::size_t n_ = 0;
  std::size_t k_ = 0;
};

namespace detail {

template <typename R, typename Xyz, typename Count, typename... Rest>
Count count_arg(R (*)(Xyz, Count, Rest...));

// C ABI counts are size_t. Convert through the declared parameter
// type and refuse truncation if a future header regresses.
using lc_count = decltype(count_arg(&lc_knearest));

static_assert(std::is_integral<lc_count>::value,
              "lc_knearest count parameter must be an integral type");

inline lc_count to_c_count(std::size_t v, const char *what) {
  const auto maxv =
      static_cast<std::size_t>(std::numeric_limits<lc_count>::max());
  if (v > maxv) {
    throw Error(std::string("linkcell: ") + what +
                " exceeds the C ABI count range");
  }
  return static_cast<lc_count>(v);
}

inline void call_c(const double *xyz, std::size_t n, const Cell &cell,
                   std::size_t k, int *out, const int *mask, double cell_hint,
                   double *out_d2 = nullptr, std::size_t n_frames = 1) {
  if (n == 0 || n_frames == 0) {
    throw Error("no points");
  }
  if (k == 0) {
    throw Error("k must be at least 1");
  }
  if (xyz == nullptr || out == nullptr) {
    throw Error("null pointer");
  }
  const lc_cell raw = cell.raw();
  const int status = lc_knearest_many(
      xyz, to_c_count(n, "n"), to_c_count(n_frames, "n_frames"), &raw,
      to_c_count(k, "k"), mask, cell_hint, out, out_d2);
  if (status != 0) {
    const char *msg = lc_last_error();
    throw Error(status, msg ? std::string(msg)
                            : std::string("linkcell: knearest failed"));
  }
}

} // namespace detail

/// Write packed indices into caller-owned `out` of length `out_len`.
/// `out_len` must be `n * k`. `mask` is nullptr or n ints.
inline void knearest_into(const double *xyz, std::size_t n, const Cell &cell,
                          std::size_t k, int *out, std::size_t out_len,
                          const int *mask = nullptr, double cell_hint = 0.0,
                          double *out_d2 = nullptr) {
  if (k != 0 && n > std::numeric_limits<std::size_t>::max() / k) {
    throw Error("n * k overflows");
  }
  if (out_len != n * k) {
    throw Error("out buffer length must be n * k");
  }
  detail::call_c(xyz, n, cell, k, out, mask, cell_hint, out_d2);
}

/// Frame-major batch. `xyz` is `n_frames * n * 3`. `out` / `out_d2`
/// are `n_frames * n * k`.
inline void knearest_into_many(const double *xyz, std::size_t n,
                               std::size_t n_frames, const Cell &cell,
                               std::size_t k, int *out, std::size_t out_len,
                               const int *mask = nullptr,
                               double cell_hint = 0.0,
                               double *out_d2 = nullptr) {
  if (k != 0 && n_frames != 0 &&
      n > std::numeric_limits<std::size_t>::max() / k / n_frames) {
    throw Error("n * k * n_frames overflows");
  }
  if (out_len != n * k * n_frames) {
    throw Error("out buffer length must be n_frames * n * k");
  }
  detail::call_c(xyz, n, cell, k, out, mask, cell_hint, out_d2, n_frames);
}

/// One allocation of n * k indices. `neighbour(i, j)` is the j-th
/// neighbour of i, or -1.
[[nodiscard]] inline Neighbours
knearest(const double *xyz, std::size_t n, const Cell &cell, std::size_t k,
         const int *mask = nullptr, double cell_hint = 0.0) {
  if (k != 0 && n > std::numeric_limits<std::size_t>::max() / k) {
    throw Error("n * k overflows");
  }
  std::vector<int> out(n * k, -1);
  std::vector<double> d2(n * k, std::numeric_limits<double>::quiet_NaN());
  detail::call_c(xyz, n, cell, k, out.data(), mask, cell_hint, d2.data());
  return Neighbours(std::move(out), std::move(d2), n, k);
}

/// `std::vector<std::array<double, 3>>` is already packed n * 3 doubles.
[[nodiscard]] inline Neighbours
knearest(const std::vector<std::array<double, 3>> &xyz, const Cell &cell,
         std::size_t k, const int *mask = nullptr, double cell_hint = 0.0) {
  const double *ptr = xyz.empty() ? nullptr : xyz.front().data();
  return knearest(ptr, xyz.size(), cell, k, mask, cell_hint);
}

/// One atom-image inside a cutoff. `shift` is vesin / tonari `S`.
/// Displacement is `r_j - r_i + S H` in the caller's basis.
struct ShiftedPair {
  int i = 0;
  int j = 0;
  std::array<int, 3> shift{{0, 0, 0}};
  double dist2 = 0.0;
};

/// Pairs with squared distance strictly below `cutoff * cutoff`.
///
/// `half` keeps one side of `(i, j, S)` and `(j, i, -S)`. This is the
/// cutoff list. k-nearest is [`knearest`].
[[nodiscard]] inline std::vector<ShiftedPair>
pairs_within(const double *xyz, std::size_t n, const Cell &cell, double cutoff,
             const int *mask = nullptr, double cell_hint = 0.0,
             bool half = false) {
  if (n == 0 || xyz == nullptr) {
    throw Error("no points");
  }
  static_assert(sizeof(ShiftedPair) == sizeof(lc_pair) &&
                    alignof(ShiftedPair) == alignof(lc_pair) &&
                    offsetof(ShiftedPair, j) == offsetof(lc_pair, j) &&
                    offsetof(ShiftedPair, shift) == offsetof(lc_pair, shift) &&
                    offsetof(ShiftedPair, dist2) == offsetof(lc_pair, dist2),
                "ShiftedPair must match lc_pair");
  const lc_cell raw = cell.raw();
  std::size_t count = 0;
  // The query keeps its search on this thread; the fill below writes
  // the rows from it.
  const int status = lc_pairs_within_rows(
      xyz, detail::to_c_count(n, "n"), &raw, cutoff, mask, cell_hint,
      half ? 1 : 0, nullptr, 0, &count);
  if (status != 0) {
    const char *msg = lc_last_error();
    throw Error(status, msg ? std::string(msg)
                            : std::string("linkcell: pairs_within failed"));
  }
  if (count == 0) {
    return {};
  }
  std::vector<ShiftedPair> out(count);
  std::size_t wrote = 0;
  const int fill = lc_pairs_within_rows(
      xyz, detail::to_c_count(n, "n"), &raw, cutoff, mask, cell_hint,
      half ? 1 : 0, reinterpret_cast<lc_pair *>(out.data()), count, &wrote);
  if (fill != 0) {
    const char *msg = lc_last_error();
    throw Error(fill, msg ? std::string(msg)
                          : std::string("linkcell: pairs_within failed"));
  }
  out.resize(wrote);
  return out;
}

/// How many partner stencils have been built in this process.
[[nodiscard]] inline std::uint64_t stencil_builds() noexcept {
  return lc_stencil_builds();
}

/// Cartesian half pair list of an open cluster.
///
/// Each row has `i < j`, shift zero, and squared distance strictly
/// below `cutoff * cutoff`. Bins are the occupied Cartesian cells. Their
/// partner stencil depends on the cutoff and `cell_hint` alone, so it is
/// reused by frames that occupy other bins.
[[nodiscard]] inline std::vector<ShiftedPair>
pairs_open(const double *xyz, std::size_t n, double cutoff,
           double cell_hint = 0.0) {
  if (n == 0 || xyz == nullptr) {
    return {};
  }
  static_assert(sizeof(ShiftedPair) == sizeof(lc_pair) &&
                    alignof(ShiftedPair) == alignof(lc_pair),
                "ShiftedPair must match lc_pair");
  std::size_t count = 0;
  const int status = lc_pairs_open(xyz, detail::to_c_count(n, "n"), cutoff,
                                   cell_hint, nullptr, 0, &count);
  if (status != 0) {
    const char *msg = lc_last_error();
    throw Error(status, msg ? std::string(msg)
                            : std::string("linkcell: pairs_open failed"));
  }
  if (count == 0) {
    return {};
  }
  std::vector<ShiftedPair> out(count);
  std::size_t wrote = 0;
  const int fill =
      lc_pairs_open(xyz, detail::to_c_count(n, "n"), cutoff, cell_hint,
                    reinterpret_cast<lc_pair *>(out.data()), count, &wrote);
  if (fill != 0) {
    const char *msg = lc_last_error();
    throw Error(fill, msg ? std::string(msg)
                          : std::string("linkcell: pairs_open failed"));
  }
  out.resize(wrote);
  return out;
}

/// [`pairs_within`] with a periodicity mask.
///
/// `periodic[k]` false is an open axis. `closed` keeps the cutoff
/// boundary on an open or mixed cell. `exclude_self_images` drops
/// `i == j`.
[[nodiscard]] inline std::vector<ShiftedPair>
pairs_within_pbc(const double *xyz, std::size_t n, const Cell &cell,
                 const std::array<bool, 3> &periodic, double cutoff,
                 const int *mask = nullptr, double cell_hint = 0.0,
                 bool half = false, bool closed = false,
                 bool exclude_self_images = false) {
  if (n == 0 || xyz == nullptr) {
    return {};
  }
  const int pbc[3] = {periodic[0] ? 1 : 0, periodic[1] ? 1 : 0,
                      periodic[2] ? 1 : 0};
  const lc_cell raw = cell.raw();
  std::size_t count = 0;
  const int status = lc_pairs_within_pbc(
      xyz, detail::to_c_count(n, "n"), &raw, pbc, cutoff, mask, cell_hint,
      half ? 1 : 0, closed ? 1 : 0, exclude_self_images ? 1 : 0, nullptr, 0,
      &count);
  if (status != 0) {
    const char *msg = lc_last_error();
    throw Error(status, msg ? std::string(msg)
                            : std::string("linkcell: pairs_within_pbc failed"));
  }
  if (count == 0) {
    return {};
  }
  std::vector<ShiftedPair> out(count);
  std::size_t wrote = 0;
  const int fill = lc_pairs_within_pbc(
      xyz, detail::to_c_count(n, "n"), &raw, pbc, cutoff, mask, cell_hint,
      half ? 1 : 0, closed ? 1 : 0, exclude_self_images ? 1 : 0,
      reinterpret_cast<lc_pair *>(out.data()), count, &wrote);
  if (fill != 0) {
    const char *msg = lc_last_error();
    throw Error(fill, msg ? std::string(msg)
                          : std::string("linkcell: pairs_within_pbc failed"));
  }
  out.resize(wrote);
  return out;
}

[[nodiscard]] inline const char *version() noexcept { return lc_version(); }

/// Fractional bins and a point count per bin.
struct CellGrid {
  int nx = 0;
  int ny = 0;
  int nz = 0;
  std::array<double, 3> bin_width{};
  std::vector<std::uint64_t> weight;

  [[nodiscard]] std::size_t ncell() const noexcept { return weight.size(); }
};

/// Periodic adjacency. Each undirected pair is two arcs of one weight.
struct CellGraph {
  CellGrid grid;
  std::vector<std::uint32_t> offsets;
  std::vector<std::uint32_t> neighbor;
  std::vector<std::uint64_t> edge_weight;
};

/// Domain id of each cell. `method` matches `lc_partition`.
/// `balance <= 0` selects `1 + parts * w_max / total`.
/// `w_max` is the heaviest cell weight. `device` asks for the CUDA curve split.
[[nodiscard]] inline std::vector<int>
partition(const double *xyz, std::size_t n, const Cell &cell, double cutoff,
          std::size_t parts, int method = 4, const int *mask = nullptr,
          double cell_hint = 0.0, double balance = 0.0, bool device = false) {
  if (n == 0 || xyz == nullptr) {
    throw Error("no points");
  }
  const lc_cell raw = cell.raw();
  std::size_t ncell = 0;
  const int query = lc_partition(
      xyz, detail::to_c_count(n, "n"), &raw, cutoff, mask, cell_hint, parts,
      static_cast<std::uint8_t>(method), balance, device ? 1 : 0, nullptr, 0,
      &ncell);
  if (query != 0) {
    const char *msg = lc_last_error();
    throw Error(query, msg ? std::string(msg) : std::string("linkcell: partition failed"));
  }
  std::vector<int> out(ncell);
  std::size_t wrote = 0;
  const int fill = lc_partition(
      xyz, detail::to_c_count(n, "n"), &raw, cutoff, mask, cell_hint, parts,
      static_cast<std::uint8_t>(method), balance, device ? 1 : 0, out.data(),
      ncell, &wrote);
  if (fill != 0) {
    const char *msg = lc_last_error();
    throw Error(fill, msg ? std::string(msg) : std::string("linkcell: partition failed"));
  }
  out.resize(wrote);
  return out;
}

/// Bin radii for `cutoff * depth`.
[[nodiscard]] inline std::array<std::uint32_t, 3>
halo_width(double cutoff, std::uint32_t depth,
           const std::array<double, 3> &bin_width) {
  std::array<std::uint32_t, 3> out{};
  const int status = lc_halo_width(cutoff, depth, bin_width.data(), out.data());
  if (status != 0) {
    const char *msg = lc_last_error();
    throw Error(status, msg ? std::string(msg) : std::string("linkcell: halo width failed"));
  }
  return out;
}

/// Ghost cell ids of `domain`.
[[nodiscard]] inline std::vector<int>
halo(const std::array<int, 3> &nxyz, const std::vector<int> &assign, int domain,
     const std::array<std::uint32_t, 3> &width) {
  std::size_t count = 0;
  const int query =
      lc_halo(nxyz.data(), assign.data(), assign.size(), domain, width.data(),
              nullptr, 0, &count);
  if (query != 0) {
    const char *msg = lc_last_error();
    throw Error(query, msg ? std::string(msg) : std::string("linkcell: halo failed"));
  }
  std::vector<int> out(count);
  if (count == 0) {
    return out;
  }
  std::size_t wrote = 0;
  const int fill =
      lc_halo(nxyz.data(), assign.data(), assign.size(), domain, width.data(),
              out.data(), count, &wrote);
  if (fill != 0) {
    const char *msg = lc_last_error();
    throw Error(fill, msg ? std::string(msg) : std::string("linkcell: halo failed"));
  }
  out.resize(wrote);
  return out;
}

} // namespace linkcell

#endif