meshsearch 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,45 @@
1
+ name: CI
2
+
3
+ on: [push, pull_request]
4
+
5
+ jobs:
6
+ build:
7
+ name: ${{ matrix.os }}
8
+ runs-on: ${{ matrix.os }}
9
+ strategy:
10
+ fail-fast: false
11
+ matrix:
12
+ os: [ubuntu-latest, macos-latest]
13
+
14
+ steps:
15
+ - uses: actions/checkout@v7
16
+
17
+ - name: Configure
18
+ run: cmake -S . -B build
19
+
20
+ - name: Build
21
+ run: cmake --build build
22
+
23
+ - name: Test
24
+ run: ctest --test-dir build --output-on-failure
25
+
26
+ python:
27
+ name: python module on ubuntu-latest
28
+ runs-on: ubuntu-latest
29
+
30
+ # The job above builds the static library and links it into executables.
31
+ # This one links it into a shared object, which is a different link and the
32
+ # one that release wheels and every Linux source install perform.
33
+ steps:
34
+ - uses: actions/checkout@v7
35
+
36
+ - uses: actions/setup-python@v7
37
+ with:
38
+ python-version: "3.12"
39
+
40
+ - name: Build and install the module
41
+ # pyproject.toml sets MESHSEARCH_BUILD_PYTHON=ON for this build
42
+ run: pip install ".[test]"
43
+
44
+ - name: Test
45
+ run: pytest tests/test_meshgrid.py
@@ -0,0 +1,88 @@
1
+ name: Release
2
+
3
+ # Publishes to PyPI when a v* tag is pushed. Run it from the Actions tab
4
+ # (workflow_dispatch) to build and test the artefacts without publishing.
5
+
6
+ on:
7
+ push:
8
+ tags: ["v*"]
9
+ workflow_dispatch:
10
+
11
+ permissions:
12
+ contents: read
13
+
14
+ jobs:
15
+ sdist:
16
+ name: sdist
17
+ runs-on: ubuntu-latest
18
+ steps:
19
+ - uses: actions/checkout@v7
20
+
21
+ - uses: actions/setup-python@v7
22
+ with:
23
+ python-version: "3.12"
24
+
25
+ - name: The tag must match the version in pyproject.toml
26
+ if: github.event_name == 'push'
27
+ run: |
28
+ tag="${GITHUB_REF_NAME#v}"
29
+ version=$(python -c "import tomllib, pathlib; print(tomllib.loads(pathlib.Path('pyproject.toml').read_text())['project']['version'])")
30
+ if [ "$tag" != "$version" ]; then
31
+ echo "tag $GITHUB_REF_NAME does not match version $version in pyproject.toml"
32
+ exit 1
33
+ fi
34
+
35
+ - name: Build
36
+ run: pipx run build --sdist
37
+
38
+ - name: Check the metadata PyPI will render
39
+ run: pipx run twine check dist/*
40
+
41
+ - uses: actions/upload-artifact@v7
42
+ with:
43
+ name: dist-sdist
44
+ path: dist/*.tar.gz
45
+
46
+ wheels:
47
+ name: wheels on ${{ matrix.os }}
48
+ runs-on: ${{ matrix.os }}
49
+ strategy:
50
+ fail-fast: false
51
+ matrix:
52
+ os: [ubuntu-latest, ubuntu-24.04-arm, macos-latest]
53
+
54
+ steps:
55
+ - uses: actions/checkout@v7
56
+
57
+ - uses: pypa/cibuildwheel@v4.2.1
58
+ with:
59
+ output-dir: wheelhouse
60
+
61
+ - uses: actions/upload-artifact@v7
62
+ with:
63
+ name: dist-${{ matrix.os }}
64
+ path: wheelhouse/*.whl
65
+
66
+ publish:
67
+ name: publish to PyPI
68
+ needs: [sdist, wheels]
69
+ if: github.event_name == 'push'
70
+ runs-on: ubuntu-latest
71
+
72
+ # The trusted publisher on PyPI is configured against this environment name
73
+ # and this workflow's filename. Changing either means changing it there.
74
+ environment:
75
+ name: pypi
76
+ url: https://pypi.org/p/meshsearch
77
+
78
+ permissions:
79
+ id-token: write # mints the OIDC token PyPI checks; no API token
80
+
81
+ steps:
82
+ - uses: actions/download-artifact@v8
83
+ with:
84
+ pattern: dist-*
85
+ merge-multiple: true
86
+ path: dist
87
+
88
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,40 @@
1
+ # Build
2
+ build/
3
+ build*/
4
+ cmake-build*/
5
+ *.o
6
+ *.a
7
+ compile_commands.json
8
+ .cache/
9
+ CMakeCache.txt
10
+ CMakeFiles/
11
+ CTestTestfile.cmake
12
+ Testing/
13
+
14
+ # Python
15
+ __pycache__/
16
+ *.py[cod]
17
+ *.egg-info/
18
+ .pytest_cache/
19
+ dist/
20
+ .venv/
21
+ venv/
22
+
23
+ # Editors
24
+ .vscode/
25
+ .idea/
26
+ .clangd/
27
+ *.swp
28
+ *.swo
29
+ *~
30
+ \#*\#
31
+
32
+ # OS
33
+ .DS_Store
34
+ .DS_Store?
35
+ ._*
36
+ Thumbs.db
37
+ desktop.ini
38
+
39
+ CLAUDE.md
40
+
@@ -0,0 +1,72 @@
1
+ cmake_minimum_required(VERSION 3.16)
2
+
3
+ project(meshsearch VERSION 0.1.0 LANGUAGES CXX)
4
+
5
+ set(CMAKE_CXX_STANDARD 17)
6
+ set(CMAKE_CXX_STANDARD_REQUIRED ON)
7
+ set(CMAKE_CXX_EXTENSIONS OFF)
8
+ set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
9
+
10
+ if (NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
11
+ set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
12
+ endif()
13
+
14
+ option(MESHSEARCH_BUILD_TESTS "Build the C++ test suite" ON)
15
+ option(MESHSEARCH_BUILD_EXAMPLES "Build the example" ON)
16
+ option(MESHSEARCH_BUILD_PYTHON "Build the Python bindings" OFF)
17
+
18
+ add_library(meshsearch STATIC src/MeshGrid.cpp)
19
+
20
+ # The archive gets linked into the Python module, which is a shared object.
21
+ # Without this, GCC emits absolute relocations that a shared object cannot use
22
+ # and the link fails on Linux; Clang on macOS is position-independent anyway.
23
+ set_target_properties(meshsearch PROPERTIES POSITION_INDEPENDENT_CODE ON)
24
+
25
+ target_include_directories(meshsearch PUBLIC
26
+ $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
27
+ $<INSTALL_INTERFACE:include>)
28
+
29
+ target_compile_features(meshsearch PUBLIC cxx_std_17)
30
+
31
+ if (CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang|AppleClang")
32
+ target_compile_options(meshsearch PRIVATE -Wall -Wextra)
33
+ endif()
34
+
35
+ if (MESHSEARCH_BUILD_EXAMPLES)
36
+ add_executable(example examples/example.cpp)
37
+ target_link_libraries(example PRIVATE meshsearch)
38
+
39
+ if (CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang|AppleClang")
40
+ target_compile_options(example PRIVATE -Wall -Wextra)
41
+ endif()
42
+ endif()
43
+
44
+ if (MESHSEARCH_BUILD_TESTS)
45
+ include(CTest)
46
+ enable_testing()
47
+
48
+ add_executable(test_meshgrid tests/test_meshgrid.cpp)
49
+ target_link_libraries(test_meshgrid PRIVATE meshsearch)
50
+
51
+ if (CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang|AppleClang")
52
+ target_compile_options(test_meshgrid PRIVATE -Wall -Wextra)
53
+ endif()
54
+
55
+ add_test(NAME meshgrid COMMAND test_meshgrid)
56
+ endif()
57
+
58
+ if (MESHSEARCH_BUILD_PYTHON)
59
+ find_package(Python 3.9 REQUIRED COMPONENTS Interpreter Development.Module)
60
+
61
+ execute_process(
62
+ COMMAND "${Python_EXECUTABLE}" -m nanobind --cmake_dir
63
+ OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE nanobind_ROOT)
64
+ find_package(nanobind CONFIG REQUIRED)
65
+
66
+ # The module is named meshsearch; the target cannot be, the library is.
67
+ nanobind_add_module(meshsearch_python NB_STATIC python/meshsearch_python.cpp)
68
+ set_target_properties(meshsearch_python PROPERTIES OUTPUT_NAME meshsearch)
69
+ target_link_libraries(meshsearch_python PRIVATE meshsearch)
70
+
71
+ install(TARGETS meshsearch_python LIBRARY DESTINATION .)
72
+ endif()
@@ -0,0 +1,29 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2026, Simone Sartori
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ 1. Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ 3. Neither the name of the copyright holder nor the names of its
17
+ contributors may be used to endorse or promote products derived from
18
+ this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,250 @@
1
+ Metadata-Version: 2.1
2
+ Name: meshsearch
3
+ Version: 0.1.0
4
+ Summary: A uniform cubic mesh over a set of points, for neighbour queries
5
+ Author: Simone Sartori
6
+ License: BSD 3-Clause License
7
+
8
+ Copyright (c) 2026, Simone Sartori
9
+ All rights reserved.
10
+
11
+ Redistribution and use in source and binary forms, with or without
12
+ modification, are permitted provided that the following conditions are met:
13
+
14
+ 1. Redistributions of source code must retain the above copyright notice, this
15
+ list of conditions and the following disclaimer.
16
+
17
+ 2. Redistributions in binary form must reproduce the above copyright notice,
18
+ this list of conditions and the following disclaimer in the documentation
19
+ and/or other materials provided with the distribution.
20
+
21
+ 3. Neither the name of the copyright holder nor the names of its
22
+ contributors may be used to endorse or promote products derived from
23
+ this software without specific prior written permission.
24
+
25
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
26
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
28
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
29
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
33
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
34
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35
+
36
+ Requires-Python: >=3.9
37
+ Requires-Dist: numpy
38
+ Provides-Extra: test
39
+ Requires-Dist: pytest; extra == "test"
40
+ Provides-Extra: benchmark
41
+ Requires-Dist: pytest; extra == "benchmark"
42
+ Requires-Dist: scipy; extra == "benchmark"
43
+ Requires-Dist: scikit-learn; extra == "benchmark"
44
+ Requires-Dist: psutil; extra == "benchmark"
45
+ Description-Content-Type: text/markdown
46
+
47
+ # meshsearch
48
+ Author: Simone Sartori (simone.sartori@inaf.it, simosart23@gmail.com)
49
+
50
+ A uniform cubic mesh over a set of points in three dimensions, for neighbour
51
+ queries: the object nearest a point, the N nearest, and every object in a
52
+ spherical shell. Objects are indexed by their position in the coordinate
53
+ vectors passed to the constructor, and can be added and removed afterwards.
54
+
55
+ C++17, no dependencies outside the standard library. Extracted from
56
+ CosmoBolognaLib, but it depends on nothing from it.
57
+
58
+ `include/meshsearch/MeshGrid.h` is the specification: it declares the
59
+ interface and states the guarantees it makes.
60
+
61
+ ## Build
62
+
63
+ Needs CMake 3.16 or later and a C++17 compiler.
64
+
65
+ ```
66
+ cmake -S . -B build
67
+ cmake --build build
68
+ ```
69
+
70
+ That produces the static library `libmeshsearch.a`, the test binary and the
71
+ example. CI configures, builds and tests on Ubuntu and macOS on every push;
72
+ locally it is also built with GCC 13, 14, 15 and 16, and with AppleClang 15.
73
+
74
+ A version of this code is distributed as part of the
75
+ [CosmoBolognaLib](https://github.com/federicomarulli/CosmoBolognaLib)
76
+ (Marulli, Veropalumbo & Moresco 2016, A&C, 14, 35), where it was
77
+ originally developed.
78
+
79
+ ## Tests
80
+
81
+ ```
82
+ ctest --test-dir build
83
+ ```
84
+
85
+ The load-bearing tests compare every query against brute force over several
86
+ thousand random points, in both dense and sparse regimes, and with duplicate
87
+ and coincident points. The rest check the guarantees the header states.
88
+
89
+ ## Example
90
+
91
+ `examples/example.cpp` is a short tour of the interface; run it with
92
+ `./build/example`. In outline:
93
+
94
+ ```cpp
95
+ #include "meshsearch/MeshGrid.h"
96
+
97
+ // coordinates as three parallel vectors, and a cell side in the same unit
98
+ meshsearch::MeshGrid grid(X, Y, Z, cellsize);
99
+
100
+ unsigned int nearest = grid.nearestObject(0.5, 0.5, 0.5);
101
+ std::vector<unsigned int> ten = grid.nearestObjects(10, 0.5, 0.5, 0.5);
102
+ std::vector<unsigned int> shell = grid.closeObjects(0.5, 0.5, 0.5, 0.15, 0.10);
103
+
104
+ // the same questions about an object in the grid, which is excluded from
105
+ // its own answer
106
+ std::vector<unsigned int> around = grid.nearestObjects(5, nearest);
107
+ ```
108
+
109
+ Three things to know before using it. A shell is `Rmin <= d <= Rmax`, closed at
110
+ both ends, so a ball holds every object within `Rmax` and an object sitting
111
+ exactly on either radius is returned. Indices are stable:
112
+ `removeObject` leaves an index permanently invalid, `addObject` issues a new
113
+ one, and indices are never reused or renumbered, so a stored index never comes
114
+ to mean a different object. And errors are exceptions — `meshsearch::Error`, or
115
+ `meshsearch::IndexError` for an index that is out of range or removed — never
116
+ return codes.
117
+
118
+ The overloads taking an object exclude it **by identity, not by distance**:
119
+ `closeObjects(i, Rmax)` omits object `i` itself, but another object at the same
120
+ position is a different object, is at `d = 0`, and is returned. The same holds
121
+ for `nearestObject` and `nearestObjects`. The point-taking overloads have no
122
+ identity to exclude, so an object lying on the query point is simply within the
123
+ radius and is returned.
124
+
125
+ Const members may be called concurrently on one grid; non-const members may
126
+ not.
127
+
128
+ ## Performance
129
+
130
+ `docs/benchmark.md` measures meshsearch against scipy's `cKDTree` and sklearn's
131
+ `BallTree`, and measures what the cell side costs. At 1e7 uniform points:
132
+
133
+ - construction is 2x to 3.7x faster than cKDTree;
134
+ - nearest neighbour is 5x to 8x faster per call and 2.4x to 3.1x faster
135
+ batched, at a cell side of one mean separation;
136
+ - a radius query on a coarse grid is the fastest thing measured, 8.76
137
+ microseconds batched against cKDTree's 9.22;
138
+ - `k = 10` is 2x to 7x slower than batched cKDTree — take that query elsewhere
139
+ if it dominates;
140
+ - memory is the price: 1.5 GiB at one mean separation against cKDTree's
141
+ 400 MiB, falling to 672 MiB at four.
142
+
143
+ The cell side is the one tuning parameter. Two to three mean separations is a
144
+ reasonable default, one mean separation favours nearest-neighbour queries, and
145
+ three to four favours shells; `python docs/benchmark_cellsize.py --sweep`
146
+ repeats the sweep on your own data.
147
+
148
+ ## Python
149
+
150
+ The same grid is available from Python, with snake_case names and numpy
151
+ results. Install from the source tree:
152
+
153
+ ```
154
+ pip install .
155
+ ```
156
+
157
+ ```python
158
+ import numpy as np
159
+ import meshsearch
160
+
161
+ grid = meshsearch.MeshGrid(x, y, z, cellsize) # three arrays, one cell side
162
+
163
+ len(grid) # live object count
164
+ grid.lims, grid.n_cells, grid.cellsize # read-only properties
165
+
166
+ grid.nearest_object(0.5, 0.5, 0.5) # an index
167
+ grid.nearest_objects(10, 0.5, 0.5, 0.5) # uint32 array, nearest first
168
+ grid.close_objects(0.5, 0.5, 0.5, 0.15, 0.10) # uint32 array, a shell
169
+ grid.nearest_objects(5, index) # about an object, which is excluded
170
+ ```
171
+
172
+ `meshsearch.Error` derives from `ValueError`. `meshsearch.IndexError` derives
173
+ from both `meshsearch.Error` and Python's `IndexError`, mirroring the C++
174
+ hierarchy, so an index fault can be caught either as the Python type it stands
175
+ for or along with every other error the grid raises.
176
+
177
+ Run the Python tests with `pytest tests/test_meshgrid.py` against an installed
178
+ build.
179
+
180
+ ### Batched queries
181
+
182
+ The three point-taking queries also accept arrays of query points, answering
183
+ all of them in one call:
184
+
185
+ ```python
186
+ nearest = grid.nearest_object(qx, qy, qz) # (n_query,) uint32
187
+ five = grid.nearest_objects(5, qx, qy, qz) # (n_query, 5) uint32
188
+ idx, off = grid.close_objects(qx, qy, qz, 0.02) # compressed-row form
189
+ ```
190
+
191
+ The same names are overloaded: three scalars ask about one point, three arrays
192
+ ask about many. Query points must be numpy arrays rather than lists, because an
193
+ array argument is what selects the batched form. A one-element array takes the
194
+ batched path and returns a one-element result.
195
+
196
+ **This exists only in Python, and that is deliberate.** Crossing the Python
197
+ boundary costs a few microseconds per call, which is more than some of these
198
+ queries take to run: it is why calling scipy's `cKDTree` once per point is
199
+ about five times slower than handing it the whole array, on identical work. A
200
+ C++ caller has no such boundary and writes a loop, so the C++ library has no
201
+ batched API and is not missing one. The **index-taking overloads have no
202
+ batched form either**, in Python or C++: their input is a single index, so
203
+ there is no per-call cost to amortise over anything.
204
+
205
+ A batched call raises where the single-point call would, naming the query that
206
+ failed — `query 17: X coordinate outside the box` — and returns nothing
207
+ partial.
208
+
209
+ ### The compressed-row result
210
+
211
+ `nearest_objects` is rectangular: every query returns exactly `n`, so the
212
+ result is one `(n_query, n)` array. A shell is not — the count varies per query
213
+ — so `close_objects` returns two arrays instead:
214
+
215
+ - **`indices`** holds every result, concatenated in query order.
216
+ - **`offsets`** has `n_query + 1` entries. The results of query `i` are
217
+ `indices[offsets[i]:offsets[i+1]]`. `offsets[0]` is `0` and the last entry is
218
+ `len(indices)`. A query with no results gives an empty slice, never a missing
219
+ entry. Both arrays are `uint32`, and `offsets` counts results, not queries, so
220
+ it is wide enough for the whole batch.
221
+
222
+ ```python
223
+ idx, off = grid.close_objects(qx, qy, qz, 0.02)
224
+
225
+ idx[off[i]:off[i+1]] # the neighbours of query i, no copy
226
+ counts = np.diff(off) # how many each query found
227
+ counts.sum() == len(idx) # always
228
+ ```
229
+
230
+ The idiom that makes this form worth learning is pairing each result with the
231
+ query it came from:
232
+
233
+ ```python
234
+ query_of = np.repeat(np.arange(len(qx)), np.diff(off))
235
+ ```
236
+
237
+ `indices` and `query_of` are now two flat arrays of the same length, so any
238
+ per-query quantity is one vectorised expression over every result at once —
239
+ `np.bincount(query_of, weights=...)` to reduce per query, boolean masks to
240
+ select across queries. `examples/example_batch.py` works through it.
241
+
242
+ **Why not a list of arrays?** Because that would allocate one Python object per
243
+ query, which is the cost the batched call exists to remove: a batch of 50,000
244
+ queries would hand back 50,000 numpy arrays. There is deliberately no helper to
245
+ convert the compressed form into such a list, it would be slow and would undo
246
+ the point. Slice it, or use the flat form directly.
247
+
248
+ ## Licence
249
+
250
+ BSD 3-Clause; see `LICENSE`.