Getting started¶
Points, indices and the box¶
A grid is built from the coordinates of the points, a cell side, and optionally the limits of the box. The coordinates come either as three arrays of equal length, one per axis, or as one array of points, x, y and z for each in turn: in C++, three vectors, three pointers with a count, or one pointer to n interleaved triples; in Python, three array-likes, or one of shape (N, 3). Every form builds the same grid from the same values, with the same results in the same order. The coordinates are copied into the grid, which keeps no reference to the caller’s arrays. The library prescribes no unit: coordinates, the cell side and every radius must be in the same one.
An object is a point held by the grid, and its index is its position in the arrays passed to the constructor, or its row in an array of points. Indices are stable for the life of the grid: removing an object leaves its index permanently invalid, adding one issues a new index, and no index is reused or renumbered.
The box is the region in which the grid accepts points. Every member that
takes a point, a query point or a new object, raises Error for a point
outside it; only contains, which tests a point, does not.
The box is set in one of two ways.
Explicit limits,
{{xlo, xhi}, {ylo, yhi}, {zlo, zhi}}, describe the region to which the points and every later query point belong: the survey volume, the simulation box, the unit cube. Every coordinate passed to the constructor must lie within them.Fitted limits, when none are given, are the range of the points, widened by a small margin.
Pass limits whenever a query point can fall outside the range of the
objects. With fitted limits, a query point beyond the outermost object, or
drawn from a different sample than the objects, can raise Error. Whether it
does depends on how the box was rounded to whole cells, which is not part of
the interface. Fitted limits are safe only when every query point is an
object or is known to lie within their range. An empty set of points requires
explicit limits.
In the examples of this page, x, y, z (X, Y, Z in C++) are n = 5,000
uniform points in the unit cube.
limits = [[0.0, 1.0], [0.0, 1.0], [0.0, 1.0]]
# The cell side, the one tuning parameter. The mean separation of n points in
# a volume V is (V / n) ** (1/3). Here it is two mean separations; the guide
# explains the choice and what other choices cost. Coordinates, cell side and
# radii share one unit, whatever it is.
volume = 1.0
separation = (volume / n) ** (1 / 3)
cellsize = 2 * separation
grid = meshsearch.MeshGrid(x, y, z, cellsize, limits=limits)
meshsearch::MeshGrid::Options options;
options.limits = std::array<std::array<double,2>,3>{{{0.,1.}, {0.,1.}, {0.,1.}}};
// The cell side, the one tuning parameter. The mean separation of n points
// in a volume V is cbrt(V/n). Here it is two mean separations; the guide
// explains the choice and what other choices cost. Coordinates, cell side
// and radii share one unit, whatever it is.
const double volume = 1.;
const double separation = std::cbrt(volume/double(n));
const double cellsize = 2.*separation;
meshsearch::MeshGrid grid(X, Y, Z, cellsize, options);
The same points as one array of rows, an (N, 3) array in Python and interleaved triples in C++, build the same grid:
pos = np.column_stack((x, y, z))
from_rows = meshsearch.MeshGrid(pos, cellsize, limits=limits)
std::vector<double> XYZ;
for (std::size_t i=0; i<n; ++i) {
XYZ.push_back(X[i]);
XYZ.push_back(Y[i]);
XYZ.push_back(Z[i]);
}
const meshsearch::MeshGrid interleaved(XYZ.data(), n, cellsize, options);
The box is then extended to a whole number of cells. On each axis that is not
periodic it is widened symmetrically, so get_lims() (lims in Python) can
be slightly larger than the limits given, and always contains them; a point
in the added margin is accepted. An axis along which the box has no extent,
because every point has the same coordinate or the limits have lo == hi,
gets a single cell, so flat and one-dimensional point sets are accepted. On a
periodic axis the box is exactly the limits; see
periodic boxes.
Choosing the cell side¶
The cell side is the one tuning parameter. A query visits the cells that can hold a result and tests every object in them: large cells hold many objects that are too far away, small cells make a query visit many empty cells and cost memory. The cell side affects only speed and memory, never results.
The scale against which to set it is the mean separation s: for N objects in a volume V, the cube root of V/N, the typical distance between neighbours in a uniform distribution. For a million objects in the unit cube, s = 0.01.
On uniform data, start between 1.5 and 2.5 mean separations, a compromise between the optima of the different queries. If one kind of query dominates, move towards its optimum:
nearest and N nearest: lower, 1 to 1.5 mean separations. Below one mean separation the memory grows as the cube of the reduction and the other queries slow down, for a gain only on the nearest object on uniform data;
balls and shells: higher, since the work grows with the radius measured in cells. At a radius of two mean separations the radius query was fastest at the largest side tried, four, and close to that at three; for other radii, measure.
On clustered data, measure. The optimum depends on how strongly the data
cluster and where the queries fall, and on the clustered set of the
performance page it differs from the uniform one. Build grids at a few cell
sides between 1 and 4 mean separations and time a batch of queries
like your own.
benchmarks/benchmark_cellsize.py
does this for the sets of the performance page and reports the occupancy of
the cells; its source shows the steps to repeat on your own points.
The measurements are on the performance page.
Queries¶
There are four queries, each of which can be asked about a point or about an object already in the grid.
nearestObjectreturns the index of the nearest object.nearestObjects(N, …)returns the N nearest, nearest first. N may be 0, which returns nothing, and may not exceed the number of objects that can be results.closeObjects(…, Rmax, Rmin)returns every object at a distance d withRmin <= d <= Rmax: a ball whenRminis 0, its default, and a shell otherwise. Both ends are included, soRmin == Rmaxselects the objects at exactly that distance.Rmaxmay be+inf. A ball extending past the box is truncated at its faces, except along a periodic axis, where it wraps (periodic boxes).countObjectsreturns the number of objectscloseObjectswould return for the same arguments, without collecting them.
nearest = grid.nearest_object(0.5, 0.5, 0.5)
print(f"nearest to the box centre: object {nearest} at "
f"({x[nearest]:.4f}, {y[nearest]:.4f}, {z[nearest]:.4f})")
# Index results are uint32 arrays, so they index straight back into the
# coordinate arrays.
ten = grid.nearest_objects(10, 0.5, 0.5, 0.5)
print(f"ten nearest to the centre: {ten}")
print("their distances:",
np.round(np.sqrt((x[ten] - 0.5) ** 2 + (y[ten] - 0.5) ** 2
+ (z[ten] - 0.5) ** 2), 4))
# A shell is rmin <= d <= rmax, both ends included; with rmin left out it is a
# ball. The order of the indices is not meaningful.
shell = grid.close_objects(0.5, 0.5, 0.5, 0.15, 0.10)
counted = grid.count_objects(0.5, 0.5, 0.5, 0.15, 0.10)
print(f"objects between 0.10 and 0.15 of the centre: {shell.size} (counted: {counted})")
# Asked about an object in the grid, a query leaves that object out of its own
# answer.
around = grid.nearest_objects(5, nearest)
const unsigned int nearest = grid.nearestObject(0.5, 0.5, 0.5);
std::printf("nearest to the box centre: object %u at (%.4f, %.4f, %.4f)\n",
nearest, X[nearest], Y[nearest], Z[nearest]);
const std::vector<unsigned int> ten = grid.nearestObjects(10, 0.5, 0.5, 0.5);
std::printf("ten nearest to the centre:");
for (const auto index : ten) std::printf(" %u", index);
std::printf("\n");
// A shell is Rmin <= d <= Rmax, both ends included; with Rmin left out it
// is a ball. The order of the indices is not meaningful.
const std::vector<unsigned int> shell = grid.closeObjects(0.5, 0.5, 0.5, 0.15, 0.10);
const std::size_t counted = grid.countObjects(0.5, 0.5, 0.5, 0.15, 0.10);
std::printf("objects between 0.10 and 0.15 of the centre: %zu (counted: %zu)\n", shell.size(), counted);
// Asked about an object in the grid, a query leaves that object out of its
// own answer.
const std::vector<unsigned int> around = grid.nearestObjects(5, nearest);
A query about an object excludes that object by identity. Another object at the same position is a different object, at distance 0, and is returned. A query about a point excludes nothing: an object lying on the point is at distance 0 and is returned.
Distances are Euclidean, with the minimum image along
periodic axes. They are compared through their squares, computed in double
precision, so an object exactly on a radius is decided by that comparison
alone. Objects at equal distance are ranked by ascending index, and a tie at
the N-th place keeps the lower indices. The assignment of objects to cells
never changes a result. The order of the indices closeObjects returns
carries no meaning; see reproducibility.
Testing points and indices¶
contains(x, y, z) reports whether a point lies in the box, which is the
test every member taking a point applies. It is false for a NaN coordinate,
and never raises for a value of the right type. isAlive(index) (is_alive
in Python) reports whether an index names an object still in the grid; it is
the one member taking an index that does not raise for a value of the right
type, and returns false for an index out of range or removed, and in Python
for a negative one. Both also take a batch and return one flag
per entry: a std::vector<std::uint8_t> of 0 and 1 in C++, a bool array in
Python. They serve to screen a batch before it is queried. In the example below,
qx, qy, qz are 50,000 uniform query points in the unit cube, bad_x is
qx with entry 99 moved outside the box, and n_objects is the
number of objects in the grid.
accepted = grid.contains(bad_x, qy, qz)
print(f"\n{accepted.sum()} of {len(accepted)} query points lie in the box; "
f"query 99 does not: {not accepted[99]}")
assert accepted.sum() == len(qx) - 1 and not accepted[99]
alive = grid.is_alive(np.array([0, 1, n_objects - 1, n_objects, -1]))
assert alive.tolist() == [True, True, True, False, False]
std::vector<double> screened = QX;
screened[99] = 5.;
const std::vector<std::uint8_t> accepted = grid.contains(screened, QY, QZ);
const std::vector<unsigned int> asked = {0, 1, (unsigned int)n};
const std::vector<std::uint8_t> alive = grid.isAlive(asked);
Three members expose the cells: get_cell gives the linear index of the cell
holding a point, get_cellCoords (get_cell_coords) its coordinates
(ix, iy, iz), and get_objectsInCell (get_objects_in_cell) the objects in
it. The linear index is (ix * ny + iy) * nz + iz, with (nx, ny, nz) the
cells per axis from get_nCells() (n_cells). They serve to inspect a grid;
no query requires them.
Errors¶
Errors are exceptions, never return codes or empty results.
raised |
C++ |
Python |
|---|---|---|
on any invalid input or impossible query |
|
|
on an index out of range or removed |
|
|
when memory runs out |
|
|
on an argument of the wrong type |
(a compile error) |
|
Catching Error therefore catches every error the grid itself raises, index
errors included, but not exhaustion of memory or, in Python, a TypeError.
Error is raised for:
the constructor: coordinate arrays of different lengths, a coordinate that is not finite or lies outside the limits, a cell side that is not finite and positive, limits that are not finite or have
lo > hi, no points and no limits, a periodic axis without limits, whose period is not an integer multiple of the shortest or is below 2⁻¹⁰⁰⁰, or whose limits are too large to shift by the period, and a grid too large to address (a cell side tiny against the box or whose reciprocal overflows, more than 2,147,483,647 cells along an axis, more than 4,294,967,295 objects, or a box so large that distances across it overflow a double). In C++ a null pointer with a count above zero is refused. Python also requires the limits to be three pairs (a flat list of two numbers is aTypeError), and the coordinates to be one-dimensional arrays, orposof shape (N, 3). A failed constructor builds nothing.a query point outside the box, and any point query on a default-constructed C++ grid, which has no box;
a negative or NaN radius, or
Rmin > Rmax;an N larger than the number of objects that can be results, a negative N in Python, an empty grid for the nearest object, and
nearestObjectabout an object when no other object remains (its batch: fewer than two objects, even for no index);a batch of
nearestObjectswhose result, queries times N, is too large to count;a batch whose coordinate arrays differ in length, or, in Python, an argument that is not one-dimensional, a number among arrays included;
a number of workers that is 0 or below −1;
addObjectfor a point outside the box, or once 4,294,967,295 indices have been issued.
IndexError is raised by every member taking an index, except isAlive, for
an index out of range or removed, and in Python for a negative index, which is
never counted from the end. In Python a float where an index is expected
raises TypeError.
A batch raises wherever one of its queries would, and returns no partial
result. In Python the message names the first query that failed, as in
query 99: X coordinate outside the box. The checks that do not depend on
the query points (the radii, N, the array lengths, an empty grid) are made
even for an empty batch. An addObject that fails leaves the grid unchanged.