linkcell 0.6.0

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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
/* Generated by cbindgen from src/capi.rs. Do not edit. */

/*
 * linkcell C API.
 *
 * Memory ownership
 *   - lc_knearest writes into caller-owned out_nn (length n * k).
 *   - lc_knearest_d2 also writes out_d2 (length n * k, unused NaN).
 *   - lc_knearest_many is the frame-major batch (n_frames * n * k).
 *   - lc_pairs_within writes caller-owned i, j, shift, dist2 rows.
 *     Null outputs query the row count.
 *   - lc_last_error returns a thread-local pointer. Do not free. The
 *     pointer is invalid after the next lc_knearest on the same thread.
 *     lc_version does not read or write the slot.
 *   - lc_version returns a process-static pointer. Do not free.
 *
 * Thread safety
 *   - Distinct searches may run concurrently.
 *   - lc_last_error is a thread-local slot. Read it on the same thread
 *     that received a nonzero return from lc_knearest.
 */


#ifndef LINKCELL_H
#define LINKCELL_H

#pragma once

/* Generated with cbindgen:0.29.4 */

/* Warning, this file is autogenerated by cbindgen. Don't modify this manually. */

#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>

/**
 * How [`partition_graph`] cuts the cell graph.
 */
enum Method
#if defined(__cplusplus) || __STDC_VERSION__ >= 202311L
  : uint8_t
#endif // defined(__cplusplus) || __STDC_VERSION__ >= 202311L
 {
    /**
     * Morton order, then a weighted prefix split.
     */
    Morton = 0,
    /**
     * Hilbert order, then a weighted prefix split.
     */
    Hilbert = 1,
    /**
     * Weighted recursive coordinate bisection.
     */
    Rcb = 2,
    /**
     * Hilbert prefix split, then Fiduccia-Mattheyses.
     */
    HilbertFm = 3,
    /**
     * Recursive coordinate bisection, then Fiduccia-Mattheyses.
     */
    RcbFm = 4,
    /**
     * Serial Scotch `SCOTCH_graphPart`, feature `scotch` only.
     */
    Scotch = 5,
    /**
     * Heavy-edge coarsening, coarse bisection, refinement on the way back.
     */
    Multi = 6,
    /**
     * PT-Scotch `SCOTCH_dgraphPart`, feature `ptscotch` only.
     */
    PtScotch = 7,
};
#ifndef __cplusplus
#if __STDC_VERSION__ >= 202311L
typedef enum Method Method;
#else
typedef uint8_t Method;
#endif // __STDC_VERSION__ >= 202311L
#endif // __cplusplus

/**
 * Periodic parallelepiped. Lattice vectors are a, b, c (same as vesin rows).
 */
typedef struct lc_cell {
    /**
     * Lattice vector a, x.
     */
    double ax;
    /**
     * Lattice vector a, y.
     */
    double ay;
    /**
     * Lattice vector a, z.
     */
    double az;
    /**
     * Lattice vector b, x.
     */
    double bx;
    /**
     * Lattice vector b, y.
     */
    double by;
    /**
     * Lattice vector b, z.
     */
    double bz;
    /**
     * Lattice vector c, x.
     */
    double cx;
    /**
     * Lattice vector c, y.
     */
    double cy;
    /**
     * Lattice vector c, z.
     */
    double cz;
    /**
     * Origin x.
     */
    double ox;
    /**
     * Origin y.
     */
    double oy;
    /**
     * Origin z.
     */
    double oz;
} lc_cell;

/**
 * One cutoff row: source `i`, target `j`, shift `S`, squared distance.
 * The C++ `linkcell::ShiftedPair` has this layout.
 */
typedef struct lc_pair {
    /**
     * Source index.
     */
    int i;
    /**
     * Target index.
     */
    int j;
    /**
     * Integer cell shift `(na, nb, nc)` applied to the target.
     */
    int shift[3];
    /**
     * Squared distance after the shift.
     */
    double dist2;
} lc_pair;

/**
 * Default method.
 *
 * The panel sums edge cuts over the five systems. The default is the
 * native method with the smallest sum among those that stay within
 * the balance bound on every system. A tie breaks toward the smaller
 * sum of median wall times.
 */
#define DEFAULT_METHOD RcbFm

#ifdef __cplusplus
extern "C" {
#endif // __cplusplus

/**
 * Periodic cell adjacency. Edge weights are pair counts from
 * `lc_pairs_within` with `half` set.
 *
 * A null `out_weight` queries `*out_ncell` and `*out_arcs` and
 * returns 0. Otherwise every output buffer is required. `cap_weight`
 * is the cell capacity and `cap_arcs` is the arc capacity.
 * `out_offsets` has length `ncell + 1`.
 *
 * # Safety
 *
 * Same point contract as [`lc_cell_grid`]. On a fill, `out_offsets`
 * is writable for `ncell + 1` counts, `out_neighbor` and `out_edge`
 * for `out_arcs` entries.
 */
int lc_cell_graph(const double *xyz,
                  size_t n,
                  const struct lc_cell *simbox,
                  double cutoff,
                  const int *mask,
                  double cell_hint,
                  int *out_nxyz,
                  double *out_width,
                  uint64_t *out_weight,
                  uint32_t *out_offsets,
                  uint32_t *out_neighbor,
                  uint64_t *out_edge,
                  size_t cap_weight,
                  size_t cap_arcs,
                  size_t *out_ncell,
                  size_t *out_arcs);

/**
 * Point counts on the linked-cell mesh.
 *
 * `out_nxyz` receives `nx, ny, nz`. `out_width` receives the three bin
 * widths. `out_weight` receives one count per cell, in the order
 * `((iz * ny) + iy) * nx + ix`. A null `out_weight` is a query:
 * `*out_ncell` is the cell count and the return is 0.
 *
 * # Safety
 *
 * `xyz` is readable for `n * 3` doubles. `simbox` points at one
 * `lc_cell`. `mask`, if non-null, is readable for `n` ints.
 * `out_ncell` is writable. On a fill, `out_nxyz` is writable for 3
 * ints, `out_width` for 3 doubles, and `out_weight` for `*out_ncell`
 * counts.
 */
int lc_cell_grid(const double *xyz,
                 size_t n,
                 const struct lc_cell *simbox,
                 double cutoff,
                 const int *mask,
                 double cell_hint,
                 int *out_nxyz,
                 double *out_width,
                 uint64_t *out_weight,
                 size_t cap,
                 size_t *out_ncell);

/**
 * Run `cb(ctx, begin, end)` over disjoint spans of `0..n` on the pool
 * selected by [`lc_set_threads`]. One thread runs the whole span on the
 * caller. The spans cover `0..n` exactly once.
 */
void lc_for_slabs(int n, void *ctx, void (*cb)(void*, int, int));

/**
 * Ghost cells of `domain`. A null `out_ghost` queries `*out_count`.
 *
 * # Safety
 *
 * `nxyz` is readable for 3 ints. `assign` is readable for `ncell`
 * ints. `width` is readable for 3 counts. On a fill, `out_ghost` is
 * writable for `*out_count` ints.
 */
int lc_halo(const int *nxyz,
            const int *assign,
            size_t ncell,
            int domain,
            const uint32_t *width,
            int *out_ghost,
            size_t cap,
            size_t *out_count);

/**
 * Bin radii for `cutoff * depth`. `out_width` receives three counts.
 *
 * # Safety
 *
 * `bin_width` is readable for 3 doubles. `out_width` is writable for
 * 3 counts.
 */
int lc_halo_width(double cutoff,
                  uint32_t depth,
                  const double *bin_width,
                  uint32_t *out_width);

/**
 * k-nearest neighbours for `n` points.
 *
 * `xyz` is packed row-major `n` triples `(x, y, z)` (`n * 3` doubles).
 * `n` is the point count (`size_t`); `0` is an error.
 * `simbox` is the periodic cell (lattice vectors a, b, c and origin).
 * `k` is neighbours per source (`size_t`); `0` is an error.
 * `mask` of `NULL` includes every point; otherwise `n` ints, nonzero to
 * include that point as both source and candidate.
 * `cell_hint` is the target cell edge. Values `<= 0` select the default
 * (3.0 in the box units).
 * `out_nn` is caller-owned output. Neighbours of source `i` occupy
 * `out_nn[i*k + t]`, nearest first. Missing slots are `-1`. Length is
 * `n * k` ints.
 *
 * `xyz`, `simbox`, and `out_nn` must be non-null when `n > 0` and
 * `k > 0`. `mask` may be `NULL`.
 *
 * Returns `0` on success. Nonzero on failure. Read `lc_last_error()` on
 * the same thread. The last-error string is thread-local: it is not
 * shared across threads, is valid until the next `lc_*` call on this
 * thread, and must not be freed.
 *
 * # Safety
 *
 * `xyz` is aligned for `double` and readable for `n * 3` doubles.
 * `simbox` is aligned and points at one valid `lc_cell`.
 * `out_nn` is aligned for `int` and writable for `n * k` ints.
 * `mask`, if non-null, is aligned for `int` and readable for `n` ints.
 * `n * 3` and `n * k` fit in `size_t`.
 */
int lc_knearest(const double *xyz,
                size_t n,
                const struct lc_cell *simbox,
                size_t k,
                const int *mask,
                double cell_hint,
                int *out_nn);

/**
 * The k-nearest graph of `n` points as CSR.
 *
 * Inputs are those of [`lc_knearest`]. Row `i` of the nominations is
 * its `k` nearest, nearest first. With `mutual` nonzero, row `i` holds
 * every `j` that row `i` lists and that lists `i`: the lower indices
 * ascending, then the higher ones nearest first. Otherwise each edge
 * comes from one nomination slot `s = i * k + t`: the lower index's
 * when both rows list each other, the only one that names it when one
 * does. A row holds its edges in slot order: edges from lower rows
 * ascending, then its own nearest first, then edges from higher rows
 * ascending.
 *
 * `out_offsets` is caller-owned, `n + 1` ints. `alloc(ctx, total)` is
 * called once, from any thread of the search, and returns `total`
 * writable ints for the columns; null fails the call. The search, the
 * degrees, and the fill run in one parallel region.
 *
 * # Safety
 *
 * Same pointer contract as [`lc_knearest`]. `out_offsets` is writable
 * for `n + 1` ints. `alloc` returns null or `total` writable ints and
 * does not unwind.
 */
int lc_knearest_csr(const double *xyz,
                    size_t n,
                    const struct lc_cell *simbox,
                    size_t k,
                    const int *mask,
                    double cell_hint,
                    int mutual,
                    int *out_offsets,
                    int *(*alloc)(void*, size_t),
                    void *ctx);

/**
 * Like [`lc_knearest`], and write squared distances into `out_d2`.
 *
 * `out_d2` is caller-owned, length `n * k`. Unused slots are `NaN`.
 * `out_d2` may be `NULL` to skip distances (same as [`lc_knearest`]).
 *
 * # Safety
 *
 * Same pointer contract as [`lc_knearest`]. `out_d2`, if non-null,
 * is aligned for `double` and writable for `n * k` doubles.
 */
int lc_knearest_d2(const double *xyz,
                   size_t n,
                   const struct lc_cell *simbox,
                   size_t k,
                   const int *mask,
                   double cell_hint,
                   int *out_nn,
                   double *out_d2);

/**
 * Frame-major batch. `xyz` is `n_frames * n` packed triples.
 * `out_nn` / `out_d2` are `n_frames * n * k`. One shared cell.
 * `mask` is length `n` or `NULL`. `out_d2` may be `NULL`.
 *
 * # Safety
 *
 * `xyz` is readable for `n_frames * n * 3` doubles. `out_nn` is
 * writable for `n_frames * n * k` ints. `out_d2`, if non-null, is
 * writable for `n_frames * n * k` doubles. `simbox` and `mask`
 * follow [`lc_knearest`].
 */
int lc_knearest_many(const double *xyz,
                     size_t n,
                     size_t n_frames,
                     const struct lc_cell *simbox,
                     size_t k,
                     const int *mask,
                     double cell_hint,
                     int *out_nn,
                     double *out_d2);

/**
 * Thread-local last-error string shared by the status-returning `lc_*`
 * calls in `linkcell.h`.
 *
 * Returns a pointer to a NUL-terminated UTF-8 C string, or `NULL` if
 * the last such call on this thread succeeded, or if none has failed
 * yet. [`lc_version`] does not read or write the slot.
 * Distinct threads have independent slots. The pointer is valid until
 * the next such `lc_*` call on this thread. Do not free it.
 */
const char *lc_last_error(void);

/**
 * Domain of each cell and the bin of each point, from one mesh cut.
 *
 * `method` and `balance` follow [`lc_partition`]. A null `out_domain`
 * queries `*out_ncell` and does not write. On a fill, `out_nxyz` is
 * three ints, `out_width` is three bin widths, `out_domain` is one
 * domain per cell, and `out_point_cell` is one bin per point.
 *
 * # Safety
 *
 * Same point contract as [`lc_cell_grid`]. On a fill, `out_domain` is
 * writable for `*out_ncell` ints and `out_point_cell` for `n` ints.
 */
int lc_mesh_cut(const double *xyz,
                size_t n,
                const struct lc_cell *simbox,
                double cutoff,
                const int *mask,
                double cell_hint,
                size_t parts,
                uint8_t method,
                double balance,
                int device,
                int *out_nxyz,
                double *out_width,
                int *out_domain,
                int *out_point_cell,
                size_t cap_cell,
                size_t cap_point,
                size_t *out_ncell);

/**
 * Width selected by [`lc_set_threads`], or the global pool when unset.
 */
int lc_num_threads(void);

/**
 * Owned points are 2. Points in a cell painted from the owned walk are 1.
 *
 * The stencil is the one [`crate::rank_mask`] paints while it visits the
 * cells of `domain`. `width` is three bin radii.
 *
 * # Safety
 *
 * `nxyz` is readable for 3 ints. `assign` is readable for `ncell` ints.
 * `point_cell` is readable for `n` ints. `width` is readable for 3
 * counts. `out_hit` is writable for `n` ints.
 */
int lc_owned_mask(const int *nxyz,
                  const int *assign,
                  size_t ncell,
                  const int *point_cell,
                  size_t n,
                  int domain,
                  const uint32_t *width,
                  int *out_hit);

/**
 * Cartesian half pair list of an open cluster.
 *
 * Every axis is open. Each row has `i < j`, shift `(0, 0, 0)`, and
 * `dist2` strictly below `cutoff` squared. Null `out` queries
 * `*out_count`. A short buffer sets `*out_count` and returns nonzero
 * without writing. The 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.
 *
 * # Safety
 *
 * `xyz` is readable for `n * 3` doubles. `out_count` is writable.
 * On a fill, `out` is writable for `cap` rows.
 */
int lc_pairs_open(const double *xyz,
                  size_t n,
                  double cutoff,
                  double cell_hint,
                  struct lc_pair *out,
                  size_t cap,
                  size_t *out_count);

/**
 * Cutoff pairs with the vesin / tonari shift `S`.
 *
 * Each row is one atom-image: `out_i[t]`, `out_j[t]`,
 * `out_shift[3*t + 0..3]` = `(na, nb, nc)`, and `out_d2[t]`.
 * Displacement is `r_j - r_i + S H` in the caller's basis.
 * `dist2` is strictly below `cutoff` squared. `half` nonzero keeps
 * the canonical side of `(i, j, S)` versus `(j, i, -S)`.
 *
 * Pass null `out_i`, `out_j`, `out_shift`, and `out_d2` to query.
 * `*out_count` receives the row count and the return is 0.
 * Otherwise all four buffers are required and `cap` is their row
 * capacity. A short buffer sets `*out_count` to the needed row count
 * and returns nonzero without writing.
 *
 * A query, or a short buffer, keeps its search on the calling thread.
 * The next call on that thread takes it when every input is the same
 * bit for bit (`xyz`, the box, `cutoff`, `mask`, `cell_hint`, `half`)
 * and writes the rows without searching again. Any other call drops
 * it. A fill that writes does not keep anything.
 *
 * # Safety
 *
 * `xyz` is readable for `n * 3` doubles. `simbox` points at one
 * `lc_cell`. `mask`, if non-null, is readable for `n` ints.
 * `out_count` is writable. On a fill, `out_i` and `out_j` are
 * writable for `cap` ints, `out_shift` for `cap * 3` ints, and
 * `out_d2` for `cap` doubles.
 */
int lc_pairs_within(const double *xyz,
                    size_t n,
                    const struct lc_cell *simbox,
                    double cutoff,
                    const int *mask,
                    double cell_hint,
                    int half,
                    int *out_i,
                    int *out_j,
                    int *out_shift,
                    double *out_d2,
                    size_t cap,
                    size_t *out_count);

/**
 * Cutoff neighbours of every point as CSR rows.
 *
 * Row `i` is `out_cols[out_offsets[i] .. out_offsets[i + 1]]`: every
 * `j != i` with an image whose squared distance is strictly below
 * `cutoff` squared, once, ascending. On a periodic axis that is the
 * minimum-image distance, also past half the box, where one atom meets
 * another through several images. A periodic image of `i` is not
 * listed. `half` nonzero keeps `j > i` only. `out_d2`, if non-null,
 * receives the squared distance of the nearest image of each column.
 *
 * `pbc` is three ints, nonzero for a periodic axis, or null for a fully
 * periodic cell; `simbox` may be null when every axis is open. `mask`
 * and `cell_hint` are those of [`lc_pairs_within_pbc`]. A masked-out
 * point has an empty row and appears in no row. The rows and distances
 * are the same bits at every [`lc_set_threads`] width and SIMD path.
 *
 * Sizing: every call sets `*need_offsets` (`n + 1`) and `*need_cols`.
 * Null `out_offsets`, `out_cols`, and `out_d2` is a query and returns
 * 0. Otherwise `out_offsets` holds `cap_offsets` ints and `out_cols`
 * (and `out_d2` if non-null) `cap_cols` values. A short buffer returns
 * nonzero without writing. A query or a short buffer keeps its rows on
 * the calling thread, and the next call there with the same inputs bit
 * for bit copies them out without searching again. A buffer large
 * enough on the first call takes the rows straight from the search.
 *
 * `n == 0` succeeds with one offset, `0`. A cutoff that is not finite
 * and positive, a coordinate that is not finite, or more columns than
 * `INT_MAX` returns nonzero with [`lc_last_error`] set.
 *
 * # Safety
 *
 * `xyz` is readable for `n * 3` doubles. `simbox`, if any axis is
 * periodic, points at one `lc_cell`. `pbc`, if non-null, is three ints.
 * `mask`, if non-null, is `n` ints. `need_offsets` and `need_cols` are
 * writable. On a fill, `out_offsets` is writable for `cap_offsets`
 * ints, `out_cols` for `cap_cols` ints, and `out_d2`, if non-null, for
 * `cap_cols` doubles.
 */
int lc_pairs_within_csr(const double *xyz,
                        size_t n,
                        const struct lc_cell *simbox,
                        const int *pbc,
                        double cutoff,
                        const int *mask,
                        double cell_hint,
                        int half,
                        int *out_offsets,
                        size_t cap_offsets,
                        int *out_cols,
                        double *out_d2,
                        size_t cap_cols,
                        size_t *need_offsets,
                        size_t *need_cols);

/**
 * [`lc_pairs_within_rows`] with a periodicity mask.
 *
 * `pbc` is three ints. Nonzero means that axis is periodic. A null
 * `pbc` is fully periodic. An open axis is binned on the occupied
 * Cartesian cells and is not padded into a periodic box. `closed`
 * nonzero keeps `dist2 <= cutoff²` on an open or mixed cell.
 * `exclude_self_images` nonzero drops `i == j`.
 *
 * Null `out` is a count query. Otherwise `out` holds `cap` rows.
 * A query or a short buffer keeps its rows on the calling thread for
 * the next call with the same inputs bit for bit.
 *
 * # Safety
 *
 * `xyz` is readable for `n * 3` doubles. `simbox`, if any axis is
 * periodic, points at one `lc_cell`. `pbc`, if non-null, is three
 * ints. `mask`, if non-null, is `n` ints. `out_count` is writable.
 * On a fill, `out` is writable for `cap` rows.
 */
int lc_pairs_within_pbc(const double *xyz,
                        size_t n,
                        const struct lc_cell *simbox,
                        const int *pbc,
                        double cutoff,
                        const int *mask,
                        double cell_hint,
                        int half,
                        int closed,
                        int exclude_self_images,
                        struct lc_pair *out,
                        size_t cap,
                        size_t *out_count);

/**
 * [`lc_pairs_within`] with one array of [`lc_pair`] rows.
 *
 * Null `out` is a query: `*out_count` receives the row count and the
 * return is 0. Otherwise `out` holds `cap` rows. A short buffer sets
 * `*out_count` to the needed count and returns nonzero without
 * writing. A query or a short buffer keeps its search on the calling
 * thread for the next call with the same inputs, as in
 * [`lc_pairs_within`].
 *
 * # Safety
 *
 * `xyz` is readable for `n * 3` doubles. `simbox` points at one
 * `lc_cell`. `mask`, if non-null, is readable for `n` ints.
 * `out_count` is writable. On a fill, `out` is writable for `cap`
 * rows.
 */
int lc_pairs_within_rows(const double *xyz,
                         size_t n,
                         const struct lc_cell *simbox,
                         double cutoff,
                         const int *mask,
                         double cell_hint,
                         int half,
                         struct lc_pair *out,
                         size_t cap,
                         size_t *out_count);

/**
 * Domain id of each cell.
 *
 * `method` is 0 Morton, 1 Hilbert, 2 recursive coordinate bisection,
 * 3 Hilbert plus Fiduccia-Mattheyses, 4 bisection plus that pass,
 * 5 Scotch, 6 multilevel, 7 PT-Scotch. `balance <= 0` selects
 * `1 + parts * w_max / total`, where `w_max` is the heaviest cell
 * weight and `total` is the sum of the cell weights. `device` nonzero runs the
 * curve split on the CUDA device and returns nonzero when that device
 * is absent. A null `out_domain` queries `*out_ncell`.
 *
 * # Safety
 *
 * Same point contract as [`lc_cell_grid`]. On a fill, `out_domain` is
 * writable for `ncell` ints.
 */
int lc_partition(const double *xyz,
                 size_t n,
                 const struct lc_cell *simbox,
                 double cutoff,
                 const int *mask,
                 double cell_hint,
                 size_t parts,
                 uint8_t method,
                 double balance,
                 int device,
                 int *out_domain,
                 size_t cap,
                 size_t *out_ncell);

/**
 * Domain of each cell from caller-supplied weights.
 *
 * `nxyz` is `nx, ny, nz`. `weight` has one count per cell, in the
 * order `((iz * ny) + iy) * nx + ix`. `method` and `balance` follow
 * [`lc_partition`]. A plain bisection reads the weights and not the
 * pair arcs. `out_domain` receives one domain per cell.
 *
 * # Safety
 *
 * `nxyz` is readable for 3 ints. `weight` is readable for `ncell`
 * counts. `out_domain` is writable for `ncell` ints.
 */
int lc_partition_weights(const int *nxyz,
                         const uint64_t *weight,
                         size_t ncell,
                         size_t parts,
                         uint8_t method,
                         double balance,
                         int *out_domain);

extern int32_t lc_ptscotch_part(int32_t n,
                                const int32_t *offsets,
                                const int32_t *edges,
                                const int32_t *vwgt,
                                const int32_t *ewgt,
                                int32_t parts,
                                double imbalance,
                                int32_t *part,
                                double *seconds_max);

extern int32_t lc_scotch_part(int32_t n,
                              const int32_t *offsets,
                              const int32_t *edges,
                              const int32_t *vwgt,
                              const int32_t *ewgt,
                              int32_t parts,
                              double imbalance,
                              int32_t *part);

/**
 * Run `cb` at the end of this thread's next `lc_knearest`, still inside
 * its pool. A null `cb` clears it. The hook belongs to the calling
 * thread; a search started on another thread does not run it. The search
 * clears nothing by itself: the caller drops the hook when the call
 * returns.
 */
void lc_set_continuation(void *ctx, void (*cb)(void*));

/**
 * Install the device curve split used by the `device` partition. The
 * GPU library calls this from a static initializer when it is loaded. A
 * null `f` removes it, and the device partition then reports no device.
 */
void lc_set_gpu_curve_split(int32_t (*f)(const uint32_t *atom_bin,
                                         size_t natom,
                                         const uint32_t *coords,
                                         size_t ncell,
                                         uint32_t parts,
                                         uint32_t *assign,
                                         uint64_t *out_weight,
                                         uint8_t method));

/**
 * CPUs Rayon workers may use. Every worker may run on any of them.
 * Replaces any list recorded earlier. A pool that has already started
 * keeps the cpus it was built with. `n <= 0` is ignored.
 */
void lc_set_places(const int *cpus, int n);

/**
 * Choose the Rayon width for later searches. `n == 0` leaves it unset:
 * the search starts on the calling thread with Rayon's and OpenMP's own
 * widths. `n == 1` runs the whole search on the calling thread and
 * starts no thread. `n < 0` selects one thread.
 */
void lc_set_threads(int n);

/**
 * How many partner stencils have been built in this process.
 *
 * A reused stencil does not increment the count. The periodic list and
 * the open-cell list share the counter.
 */
uint64_t lc_stencil_builds(void);

/**
 * Run `nstages` stages in one parallel region on the pool selected by
 * [`lc_set_threads`], the caller one of the workers (see `team`). Stage
 * `s` is `chunks[s]` calls of `fn_(ctx, s, chunk, worker)`, in any order
 * and on any worker; every chunk of a stage returns before any chunk of
 * the next starts. `worker` is fixed for one worker thread during the
 * call and below [`lc_team_width`], so it can index per-worker scratch.
 * No worker that has not started holds up a stage or the return.
 *
 * # Safety
 *
 * `chunks` is readable for `nstages` sizes. `fn_` does not unwind and
 * may be called from any thread of the pool until the call returns.
 */
int lc_team_run(size_t nstages,
                const size_t *chunks,
                void (*fn_)(void*, size_t, size_t, size_t),
                void *ctx);

/**
 * Workers an [`lc_team_run`] started now may use: the `worker` index it
 * passes is below this.
 */
size_t lc_team_width(void);

/**
 * Library version string. Process-static, NUL-terminated. Do not free.
 */
const char *lc_version(void);

/**
 * Owned points are 2. Ghosts within `reach` of an owned atom are 1.
 *
 * # Safety
 *
 * `xyz` is readable for `n * 3` doubles. `lengths` and `nxyz` are
 * readable for 3 entries. `assign` is readable for `ncell` ints.
 * `point_cell` is readable for `n` ints. `hwidth` is readable for 3
 * counts. `out_hit` is writable for `n` ints.
 */
int lc_within_reach(const double *xyz,
                    size_t n,
                    const double *lengths,
                    const int *nxyz,
                    const int *assign,
                    size_t ncell,
                    const int *point_cell,
                    const uint32_t *hwidth,
                    int domain,
                    double reach,
                    int *out_hit);

#ifdef __cplusplus
}  // extern "C"
#endif  // __cplusplus

#endif  /* LINKCELL_H */

#ifndef LINKCELL_LC_CELL_ORTHO_H
#define LINKCELL_LC_CELL_ORTHO_H

#ifdef __cplusplus
extern "C" {
#endif

/**
 * Orthorhombic cell with origin at zero.
 */
static inline lc_cell lc_cell_ortho(double lx, double ly, double lz) {
    lc_cell c;
    c.ax = lx;
    c.ay = 0.0;
    c.az = 0.0;
    c.bx = 0.0;
    c.by = ly;
    c.bz = 0.0;
    c.cx = 0.0;
    c.cy = 0.0;
    c.cz = lz;
    c.ox = 0.0;
    c.oy = 0.0;
    c.oz = 0.0;
    return c;
}

#ifdef __cplusplus
}  /* extern "C" */
#endif

#endif  /* LINKCELL_LC_CELL_ORTHO_H */