# 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. ```{literalinclude} ../examples/example.py :language: python :start-at: "limits = [[0.0, 1.0], [0.0, 1.0], [0.0, 1.0]]" :end-at: "grid = meshsearch.MeshGrid(x, y, z, cellsize, limits=limits)" ``` ```{literalinclude} ../examples/example.cpp :language: cpp :start-at: "meshsearch::MeshGrid::Options options;" :end-at: "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: ```{literalinclude} ../examples/example.py :language: python :start-at: "pos = np.column_stack((x, y, z))" :end-at: "from_rows = meshsearch.MeshGrid(pos, cellsize, limits=limits)" ``` ```{literalinclude} ../examples/example.cpp :language: cpp :start-at: "std::vector XYZ;" :end-at: "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](periodic.md). ## 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](grid-over-time.md#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`](https://github.com/SimoSartori/meshsearch/blob/main/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](benchmark.md#cell-side). ## Queries There are four queries, each of which can be asked about a point or about an object already in the grid. - `nearestObject` returns 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* with `Rmin <= d <= Rmax`: a *ball* when `Rmin` is 0, its default, and a *shell* otherwise. Both ends are included, so `Rmin == Rmax` selects the objects at exactly that distance. `Rmax` may be `+inf`. A ball extending past the box is truncated at its faces, except along a periodic axis, where it wraps ([periodic boxes](periodic.md)). - `countObjects` returns the number of objects `closeObjects` would return for the same arguments, without collecting them. ```{literalinclude} ../examples/example.py :language: python :start-at: "nearest = grid.nearest_object(0.5, 0.5, 0.5)" :end-at: "around = grid.nearest_objects(5, nearest)" ``` ```{literalinclude} ../examples/example.cpp :language: cpp :start-at: "const unsigned int nearest = grid.nearestObject(0.5, 0.5, 0.5);" :end-at: "const std::vector 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](periodic.md) 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](grid-over-time.md#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](batches.md) and return one flag per entry: a `std::vector` 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. ```{literalinclude} ../examples/example_batch.py :language: python :start-at: "accepted = grid.contains(bad_x, qy, qz)" :end-at: "assert alive.tolist() == [True, True, True, False, False]" ``` ```{literalinclude} ../examples/example_batch.cpp :language: cpp :start-at: "std::vector screened = QX;" :end-at: "const std::vector 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 | `meshsearch::Error`, derived from `std::runtime_error` | `meshsearch.Error`, derived from `ValueError` | | on an index out of range or removed | `meshsearch::IndexError`, derived from `Error` | `meshsearch.IndexError`, derived from both `meshsearch.Error` and the built-in `IndexError` | | when memory runs out | `std::bad_alloc` | `MemoryError` | | on an argument of the wrong type | (a compile error) | `TypeError` | 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 a `TypeError`), and the coordinates to be one-dimensional arrays, or `pos` of 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 `nearestObject` about an object when no other object remains (its batch: fewer than two objects, even for no index); - a batch of `nearestObjects` whose 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](batches.md#workers-and-threads) that is 0 or below −1; - `addObject` for 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.