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.

  const std::vector<unsigned int> nearest = grid.nearestObject(QX, QY, QZ);
  std::printf("nearest object to query 0: %u\n", nearest[0]);

  // nearestObjects returns N per query, flat: query i's N at [i*N, (i+1)*N).
  const unsigned int N = 5;
  const std::vector<unsigned int> five = grid.nearestObjects(N, QX, QY, QZ);
  std::printf("five nearest to query 0:");
  for (unsigned int k=0; k<N; ++k) std::printf(" %u", five[k]);
  std::printf("\n");

  // closeObjects returns a varying number per query, so a batch comes back as
  // a MeshGrid::Batch: every index in one vector, and offsets with one more
  // entry than queries. Query i found indices[offsets[i]] up to, excluding,
  // indices[offsets[i+1]].
  const double radius = 0.02;
  const meshsearch::MeshGrid::Batch shells = grid.closeObjects(QX, QY, QZ, radius);
  const std::uint64_t first = shells.offsets[12];
  const std::uint64_t last = shells.offsets[13];
  std::printf("query 12 has %llu neighbours within %.2f\n", (unsigned long long)(last-first), radius);
nearest = grid.nearest_object(qx, qy, qz)
print(f"nearest_object -> {nearest.dtype} {nearest.shape}")
distance_to_nearest = np.sqrt((x[nearest] - qx) ** 2 + (y[nearest] - qy) ** 2
                              + (z[nearest] - qz) ** 2)
print(f"  mean distance to the nearest object: {distance_to_nearest.mean():.5f}")

# 2. The five nearest to each query point, nearest first. This one is
#    rectangular -- every query returns exactly five -- so it comes back as a
#    single (n_query, 5) array and needs no offsets.
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 gives the figures. In C++ a batch can share its queries among workers.

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<std::uint64_t> 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.

radius = 0.02
within = grid.count_objects(qx, qy, qz, radius)
print(f"count_objects -> {within.dtype} {within.shape}, mean {within.mean():.2f}")

# 4. A ball around each query point. The count varies per query, so the result
#    cannot be rectangular. It comes back in compressed-row form: one flat
#    array of every result, and an offsets array saying where each query's
#    results begin and end.
indices, offsets = grid.close_objects(qx, qy, qz, radius)
print(f"close_objects -> indices {indices.dtype} {indices.shape}, "
      f"offsets {offsets.dtype} {offsets.shape}")

# The results of query i are one slice, with no copying:
i = 12
print(f"  query {i} has {offsets[i + 1] - offsets[i]} neighbours: "
      f"{indices[offsets[i]:offsets[i + 1]]}")

# The per-query count is a difference of offsets -- no loop, no unpacking --
# and it is what count_objects returned.
counts = np.diff(offsets)
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.

query_of = np.repeat(np.arange(len(qx)), counts)

dx = x[indices] - qx[query_of]
dy = y[indices] - qy[query_of]
dz = z[indices] - qz[query_of]
distance = np.sqrt(dx * dx + dy * dy + dz * dz)

# The mean distance to the neighbours of each query. bincount sums over the
# results belonging to each query; the guarded divide leaves a query with no
# neighbours at zero rather than dividing by it.
summed = np.bincount(query_of, weights=distance, minlength=len(qx))
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.

objects = nearest[:1000]
partner = grid.nearest_object(objects)
ring, ring_offsets = grid.close_objects(objects, radius)
around = grid.count_objects(objects, radius)
print(f"\nobject {objects[0]}: nearest other object {partner[0]}, "
      f"{around[0]} objects within {radius}")
assert np.array_equal(np.diff(ring_offsets), around)
  const std::vector<unsigned int> objects = {0, 1, 2};
  const std::vector<std::uint64_t> 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:

queries = rng.random((50_000, 3))
qx = queries[:, 0]
qy = queries[:, 1]
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 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<unsigned int> for indices, a std::vector<std::uint64_t> for counts, a std::vector<std::uint8_t> 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.

  std::vector<unsigned int> found;
  std::size_t total = 0;
  for (unsigned int i=0; i<1000; ++i) {
    grid.closeObjects(i, radius, found);
    total += found.size();
  }
  std::printf("neighbours within %.2f of objects 0 to 999: %zu\n", radius, total);

  // The batch forms take a container in the same way: here a vector of
  // counts and a MeshGrid::Batch, each reused for three radii.
  std::vector<std::uint64_t> tally;
  meshsearch::MeshGrid::Batch rings;
  std::vector<std::uint64_t> totals;
  for (const double r : {0.01, 0.02, 0.04}) {
    grid.countObjects(QX, QY, QZ, r, tally);
    grid.closeObjects(QX, QY, QZ, r, rings);
    totals.push_back(std::accumulate(tally.begin(), tally.end(), std::uint64_t(0)));
    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.

neighbours = np.empty((len(qx), 5), dtype=np.uint32)
tally = np.empty(len(qx), dtype=np.int64)
for r in (0.01, 0.02, 0.04):
    grid.count_objects(qx, qy, qz, r, out=tally)
    print(f"  within {r}: {int(tally.sum())} neighbours over all queries")
grid.nearest_objects(5, qx, qy, qz, out=neighbours)
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.

qx, qy, qz = rng.random(10_000), rng.random(10_000), rng.random(10_000)
alone = grid.nearest_objects(10, qx, qy, qz)
shared = grid.nearest_objects(10, qx, qy, qz, workers=-1)
assert np.array_equal(shared, alone)
balls = grid.close_objects(qx, qy, qz, 0.05, workers=-1)
assert all(np.array_equal(a, b) for a, b in zip(balls, grid.close_objects(qx, qy, qz, 0.05)))
  std::vector<double> QX, QY, QZ;
  for (std::size_t i=0; i<10000; ++i) {
    QX.push_back(unit(gen));
    QY.push_back(unit(gen));
    QZ.push_back(unit(gen));
  }
  const meshsearch::Workers every(-1);
  const std::vector<unsigned int> alone = grid.nearestObjects(10, QX, QY, QZ);
  const std::vector<unsigned int> shared = grid.nearestObjects(10, QX, QY, QZ, every);
  const meshsearch::MeshGrid::Batch balls = grid.closeObjects(QX, QY, QZ, 0.05, 0., every);
  const meshsearch::MeshGrid::Batch single = grid.closeObjects(QX, QY, QZ, 0.05);
  const bool parallel = shared == alone
    && 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). 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.