seams-core v2.14.0
libyodaLib, the C++ engine of d-SEAMS
Loading...
Searching...
No Matches
index_range.hpp
Go to the documentation of this file.
1// Copyright (c) d-SEAMS developers
2#ifndef SEAMS_INDEX_RANGE_H_
3#define SEAMS_INDEX_RANGE_H_
4
5#include <cstdint>
6#include <limits>
7#include <vector>
8
9// Cell counts and neighbour-list offsets are signed 32-bit indexes.
10// A product or a running sum that does not fit is undefined as a signed
11// overflow, and the wrapped value then sizes the wrong array.
12
13namespace seams {
14
15inline bool gridFits(int nx, int ny, int nz, int &cells) {
16 if (nx <= 0 || ny <= 0 || nz <= 0) {
17 return false;
18 }
19 const std::int64_t prod = std::int64_t{nx} * ny * nz;
20 if (prod > std::numeric_limits<int>::max()) {
21 return false;
22 }
23 cells = static_cast<int>(prod);
24 return true;
25}
26
27// Drop the longest axis until the cell count fits in a signed int and
28// does not exceed maxCells. Axes are not taken below floorDim. A coarser
29// cell is at least as wide as the cutoff the caller used to size the
30// original grid, so a one-cell halo still covers that cutoff.
31// 1<<22 is above the orthorhombic bond grid of an 884736-molecule ice
32// cell (about 88^3) and below a product that wraps a signed int.
33inline void coarsenUntilFits(int &nx, int &ny, int &nz, int floorDim,
34 int maxCells = 1 << 22) {
35 if (floorDim < 1) {
36 floorDim = 1;
37 }
38 if (maxCells < 1) {
39 maxCells = 1;
40 }
41 int cells = 0;
42 while (!gridFits(nx, ny, nz, cells) || cells > maxCells) {
43 int *axis = &nx;
44 if (ny > *axis) {
45 axis = &ny;
46 }
47 if (nz > *axis) {
48 axis = &nz;
49 }
50 if (*axis <= floorDim) {
51 return;
52 }
53 --(*axis);
54 }
55}
56
57// Exclusive of nothing: offsets[0] = 0 and offsets[i+1] is the sum of
58// the first i+1 counts. False when a count is negative or the sum does
59// not fit in a signed int, which is the width of the offset array.
60inline bool prefixCounts(const int *counts, int n, std::vector<int> &offsets) {
61 if (n < 0 || (n > 0 && counts == nullptr)) {
62 return false;
63 }
64 offsets.assign(static_cast<std::size_t>(n) + 1, 0);
65 std::int64_t sum = 0;
66 for (int i = 0; i < n; ++i) {
67 if (counts[i] < 0) {
68 return false;
69 }
70 sum += counts[i];
71 if (sum > std::numeric_limits<int>::max()) {
72 return false;
73 }
74 offsets[static_cast<std::size_t>(i) + 1] = static_cast<int>(sum);
75 }
76 return true;
77}
78
79} // namespace seams
80
81#endif
void coarsenUntilFits(int &nx, int &ny, int &nz, int floorDim, int maxCells=1<< 22)
bool prefixCounts(const int *counts, int n, std::vector< int > &offsets)
bool gridFits(int nx, int ny, int nz, int &cells)