# Batches and threads ## Batches In the batch examples of this guide, `x, y, z` are `n_objects` = 200,000 uniform points in the unit cube, `qx, qy, qz` are 50,000 uniform query points, and `bad_x` is `qx` with entry 99 moved outside the box (`X, Y, Z`, `QX, QY, QZ` and `n` in C++); they are made as shown under *Arguments in Python*. Every query also exists as a *batch*: one call that answers many query points, or many objects already in the grid. A batch has the name of the single query, and is selected by its argument: three vectors (C++) or three arrays (Python) in place of three numbers, or a vector or array of indices in place of one index. ```{literalinclude} ../examples/example_batch.cpp :language: cpp :start-at: "const std::vector nearest = grid.nearestObject(QX, QY, QZ);" :end-at: "printf(\"query 12 has %llu neighbours within %.2f\\n\", (unsigned long long)(last-first), radius);" ``` ```{literalinclude} ../examples/example_batch.py :language: python :start-at: "nearest = grid.nearest_object(qx, qy, qz)" :end-at: "five = grid.nearest_objects(5, qx, qy, qz)" ``` **Results are in input order.** The result of query `i` is in position `i`, and equals that of the single query, in the same order. **In Python a batch is faster than a loop of single queries**, by about the cost of a call per query; the [performance page](benchmark.md#per-call) gives the figures. In C++ a batch can share its queries among [workers](#workers-and-threads). **The shape of the result.** The batches of `nearestObject` and `nearestObjects` are rectangular: a vector of `n*N` in C++, with query `i`'s at `[i*N, (i+1)*N)`, and an array of shape `(n_query, N)` in Python. `countObjects` returns one count per query, as a `std::vector` or an `int64` array. A batch of `closeObjects` returns two arrays, since each query finds a different number of objects: `indices`, every index found, concatenated in query order, and `offsets`, with one more entry than there are queries, starting at 0 and ending at the length of `indices`. The result of query `i` is `indices[offsets[i]]` up to, excluding, `indices[offsets[i+1]]`; a query that found nothing has two equal offsets. In C++ the two are the members of a `MeshGrid::Batch`; in Python, `close_objects` returns a named tuple `meshsearch.Batch` with the fields `indices` and `offsets`, which also unpacks as a pair. The offsets are 64-bit (`std::uint64_t`; `int64` in Python), since a batch can find more than 2³² objects in total. ```{literalinclude} ../examples/example_batch.py :language: python :start-at: "radius = 0.02" :end-at: "assert np.array_equal(counts, within)" ``` With the two flat arrays, per-query quantities are single vectorised expressions: pair each result with its query, then reduce with `np.bincount` or select with a mask. ```{literalinclude} ../examples/example_batch.py :language: python :start-at: "query_of = np.repeat(np.arange(len(qx)), counts)" :end-at: "mean_distance = np.divide(summed, counts, out=np.zeros(len(qx)), where=counts > 0)" ``` **Batches over objects** take their indices, and exclude each object from its own result. ```{literalinclude} ../examples/example_batch.py :language: python :start-at: "objects = nearest[:1000]" :end-at: "assert np.array_equal(np.diff(ring_offsets), around)" ``` ```{literalinclude} ../examples/example_batch.cpp :language: cpp :start-at: "const std::vector objects = {0, 1, 2};" :end-at: "const std::vector around = grid.countObjects(objects, radius);" ``` **Arguments in Python.** Query points may be any one-dimensional array-like of real numbers: a float64 or integer array is used as it is, and anything else, such as a list or a float32 array, is converted by numpy first. Indices may be any one-dimensional array-like of integers; an integer array of any dtype is used as it is, never cast, so a negative index, or one not in the grid, raises `meshsearch.IndexError`. A list or tuple is converted by numpy first. An argument that has a length makes the call a batch, so a one-element list returns a one-element result. The query points of these examples were made as follows: ```{literalinclude} ../examples/example_batch.py :language: python :start-at: "queries = rng.random((50_000, 3))" :end-at: "qz = queries[:, 2]" ``` The package is typed. It installs the stub of its module, so a type checker such as mypy knows from the arguments whether a call is a single query or a batch, and what it returns: an `int` or an array of `uint32`, for instance. The [Python reference](python.rst) shows the types. ## Reusing memory between calls **In C++**, each query that returns a container also has a form that writes into one passed by the caller, before `workers` where there is one: a `std::vector` for indices, a `std::vector` for counts, a `std::vector` for flags, a `MeshGrid::Batch` for a batch of balls or shells. The container is cleared, then filled, and keeps its capacity, so with single queries and small batches a container declared outside a loop stops allocating once it has reached the largest result. A large batch may still allocate working space of its own on every call. In every index batch that returns indices the container may be the index vector itself (for `closeObjects`, `Batch::indices`); it then does not keep its capacity. If the call throws, the content of the container is unspecified. ```{literalinclude} ../examples/example_batch.cpp :language: cpp :start-at: "std::vector found;" :end-at: "if (rings.indices.size() != totals.back()) return 1;" ``` **In Python**, the batches of `nearest_object` (`uint32`, shape `(n_query,)`), `nearest_objects` (`uint32`, `(n_query, n)`), `count_objects` (`int64`, `(n_query,)`), `contains` and `is_alive` (`bool`, `(n_query,)`) accept an array to fill through the keyword-only argument `out=`, and return it. The array must have exactly that dtype and shape, and be C-contiguous and writeable; a C-contiguous view into a larger array, such as one row of a table, is accepted. Nothing is converted: a wrong dtype, a read-only array or an object that is not an array raises `TypeError`, and a wrong shape or layout raises `meshsearch.Error`. The array is checked before any query runs, and is not written to if the call raises. `close_objects` has no `out=`; `count_objects` gives the totals in advance. ```{literalinclude} ../examples/example_batch.py :language: python :start-at: "neighbours = np.empty((len(qx), 5), dtype=np.uint32)" :end-at: "assert np.array_equal(neighbours, five)" ``` ## Workers and threads Every batch can share its queries among threads, which it starts for the call. Its last argument gives their number, at least 1, or −1: `meshsearch::Workers` in C++, after `Rmin` where there is one, and the keyword-only `workers=` in Python. One, the default, runs the batch in the calling thread. **Results do not depend on the number of workers**: any number gives the same indices and counts, in the same order, and the same error on invalid input. Here the grid holds 5,000 points and the batch 10,000 query points. ```{literalinclude} ../examples/example.py :language: python :start-at: "qx, qy, qz = rng.random(10_000), rng.random(10_000), rng.random(10_000)" :end-at: "assert all(np.array_equal(a, b) for a, b in zip(balls, grid.close_objects(qx, qy, qz, 0.05)))" ``` ```{literalinclude} ../examples/example.cpp :language: cpp :start-at: "std::vector QX, QY, QZ;" :end-at: "&& balls.indices == single.indices && balls.offsets == single.offsets;" ``` `workers=-1`, or `Workers(-1)`, uses every core available to the process: on Linux the cores of its CPU affinity set, which is what a job scheduler assigns, elsewhere every core of the machine. On processors whose cores differ in speed, such as Apple's, a number equal to the fast cores can be quicker ([performance page](benchmark.md#workers)). A number above the cores is accepted. A batch too small to share uses fewer threads, or one, and if a thread cannot be started the batch continues on fewer. The queries, and every other `const` member in C++, may also be called concurrently on one grid from any number of threads, and each call returns what it would return alone. `addObject` and `removeObject` may not run while any other thread uses the grid; the grid takes no lock, so the caller must ensure this. A container passed to a C++ query, or an `out=` array in Python, must not be accessed by another thread until the call returns. In Python, a batch releases the GIL while its queries run, so other Python threads continue and may query the same grid. The module declares that it does not require the GIL, so on a free-threaded build of CPython (3.14t) importing it leaves the GIL disabled, and threads query in parallel under the same rules. More than one worker suits a large batch in a process that is otherwise idle. A program that already runs batches from threads of its own should leave each at one worker, so that the two do not compete for the same cores.