Skip to content

feat(pycvc): SWIG python bindings skeleton (volume/filters/sdf, numpy typemaps) - #104

Closed
transfix wants to merge 1 commit into
masterfrom
feat/pycvc-swig-skeleton
Closed

transfix wants to merge 1 commit into
masterfrom
feat/pycvc-swig-skeleton

Conversation

@transfix

@transfix transfix commented Jul 16, 2026 •

Copy link
Copy Markdown
Owner

First working cut of pycvc — the SWIG Python bindings the Modernization Plan Phase 13 designed but never built (zero .i files existed until now). Scope is a deliberately minimal first wrap surface: enough to manufacture a smoothed risk field r̃ and a mesh→SDF→numpy φ from Python, nothing more.

Base: branched from 30e079d (post-#101 master, before the volrover3 extraction landed). src/pycvc/ is new and the two CMakeLists edits are one-liners, so it should rebase cleanly onto the lean-SDK master; happy to rebase in review if preferred.

What's wrapped

One module pycvc, four hand-curated .i fragments under src/pycvc/ (no raw libcvc headers are %included — they are boost/CGAL-heavy and SWIG chokes on the template depth):

  • app.i — cvc::app as a hidden, lazily-constructed module singleton. Python never sees a context; every wrapped op threads it through internally. (Deliberately leaked at shutdown to avoid static-destruction-order issues with the app's boost threads.)
  • volume.i — dimension, bounding_box, voxels, volume with numpy conversion; dims/spacing/bbox accessors, volume::interpolate, np.asarray(vol) / vol.shape sugar. pycvc.volume(np_array[, bbox]) constructs from any 3D array.
  • ops.i — vol_normalize, vol_scale, vol_clip, vol_clamp_min, vol_mask, vol_inverse_mask, vol_downsample, compute_stats.
  • sdf.i — minimal cvc::geometry (numpy mesh in/out: points (N,3) float64, tris (M,3) uint64), generate_sphere/generate_cube, and sdf(geom, x, y, z[, bbox][, flip_normals]) gated on CVC_ENABLE_SDF at both SWIG-time and compile-time (the gate is ON in our standard builds and pulls no extra deps, so no fragment had to be dropped — when a build disables SDF the function simply doesn't exist in the module).

Smoothing: voxels.bilateralFilter, anisotropicDiffusion, gdtvFilter — wrapped via %extend rather than declared directly, because the C++ filters read min()/max() before filtering and never call unsetMinMax(), so a following vol_normalize would remap against stale pre-filter bounds (found while verifying; the binding invalidates the cache after each filter call, and the pipeline test locks the behavior in). Upstream fix to the filters themselves is a separate follow-up.

Not wrapped (by design): GUI/Qt, cvc::state/state_exec/distributed state, energy/docking, directors/callbacks, volume file I/O.

NumPy strategy: copy-in / copy-out

A C-ordered (Z, Y, X) array maps 1:1 onto the libcvc voxel layout (x fastest), so each direction is a single flat memcpy: pycvc.volume(arr) copies in through the raw-pointer volume ctor; vol.to_numpy() / np.asarray(vol) copies out via PyArray_SimpleNew. Hand-written helpers against the numpy C API — not numpy.i (not shipped in numpy wheels) and not zero-copy. Zero-copy out (PyArray_SimpleNewFromData + PyArray_BASE holding the owning voxels alive) is the flagged next step; copies side-step the shared_array/copy-on-write lifetime hazards and are noise next to the filters this surface exists for. dtypes: uint8/16/32, float32/64 map to UChar/UShort/UInt/Float/Double; everything else force-casts to float32. 2D rasters are the degenerate ZDim()==1 case (arr[None]).

Build integration

  • New top-level option CVC_BUILD_PYTHON (default OFF) → src/pycvc/ via swig_add_library, linking cvc::cvc + Python3::Module + Python3::NumPy; extension + proxy land in <build>/python/.
  • Verified with: system SWIG 4.2.0 (/usr/bin/swig4.0 — the cvcpkg swig 4.4.1 recipe exists in libcvc-deps but isn't built into the local deps prefix yet; find_package(SWIG 4.0) will pick the prefix one up once it is), Python 3.12.3 + NumPy 2.5.1, the usual deps/ prefix (Boost 1.86, CGAL 6.0.1), Release, CUDA off.
  • Feature gates propagate to SWIG's preprocessor (CVC_ENABLE_SDF/CVC_ENABLE_MESHER as -D on the .i), and the wrap compile inherits them from the cvc target's PUBLIC definitions — the binding can't drift from the library build.

Verification

src/pycvc/tests/test_roundtrip.py — 7/7 passed (Release build, 3.5s):

  • float32 (32,32,8) → volume → np.asarray round-trips bit-exact, shape/dtype preserved
  • bilateralFilter(200, 1.5, 2): values changed, all finite, std 0.288 → 0.037
  • anisotropicDiffusion(5): changed, finite, smoother
  • vol_normalize(v, 0, 1) → exactly [0.0, 1.0], argmax preserved
  • bbox/spacing accessors + interpolate at a grid point == array value
  • r̃ pipeline (noise → bilateral → normalize) stretches the filtered field to exactly [0,1] (regression for the stale min/max fix)
  • sphere mesh (114 verts / 224 tris) → sdf 16³ → numpy: finite, min −0.963 < 0 < max 1.616 (inside/outside sign change)

Run: PYTHONPATH=<build>/python python -m pytest src/pycvc/tests/test_roundtrip.py -v

Honest gaps / next steps

  • Copy, not zero-copy (see above) — fine for whole-field ops, wrong default for chatty per-agent sampling (which belongs in numpy anyway).
  • GIL held during filters/SDF — no Py_BEGIN_ALLOW_THREADS yet; single-threaded Python callers won't notice.
  • Degenerate-Z (ZDim()==1) filter behavior unvalidated — the 2D-raster path needs its own test before downstream code relies on it.
  • No CI wiring — the pytest runs manually; needs a CVC_BUILD_PYTHON=ON job once the SWIG dep story lands in CI.
  • SDFLibrary prints diagnostics to stdout — noisy from Python; upstream cleanup candidate.
  • Packaging: cvcpkg python_sdist recipe (recipes/pycvc, Phase-7 mechanism) so downstream Python packages import from the hermetic prefix; then volrover embedded-Python (G6) consumes the same module. Version lock-step pycvc == libcvc.
  • Upstream filter unsetMinMax() fix + regression test (separate PR).

… typemaps)

First cut of the pycvc SWIG module (Modernization Phase 13 design, G5 in
the 2026-07-15 near-term goals). New CVC_BUILD_PYTHON CMake option
(default OFF) builds a _pycvc extension from four hand-curated .i
fragments under src/pycvc/:

- app.i:    hidden cvc::app module-context singleton (lazily constructed,
            never exposed to Python)
- volume.i: dimension/bounding_box/voxels/volume with numpy conversion
            (copy-in/copy-out, (Z,Y,X) C-order maps onto the libcvc voxel
            layout so conversion is a flat memcpy); bilateralFilter/
            anisotropicDiffusion/gdtvFilter wrapped via %extend so the
            stale cached min/max is invalidated after in-place filtering
- ops.i:    vol_normalize/scale/clip/clamp_min/mask/inverse_mask/
            downsample/compute_stats
- sdf.i:    minimal cvc::geometry (numpy mesh in/out) + sdf() gated on
            CVC_ENABLE_SDF + generate_sphere/generate_cube

Deliberately not wrapped: GUI/Qt, state/state_exec/distributed state,
energy/docking, directors/callbacks, volume file I/O.

Verified: src/pycvc/tests/test_roundtrip.py (7 tests) passes against a
Release build — numpy float32 (32,32,8) round-trips exactly, bilateral
filter smooths (std 0.288 -> 0.037) with finite values, vol_normalize
stretches the filtered field to exactly [0,1], and a sphere mesh ->
16^3 SDF -> numpy round trip shows the inside/outside sign change.
@transfix

Copy link
Copy Markdown
Owner Author

Superseded: pycvc Geometry (#107), Volume (#108), and zero-copy numpy + CUDA (#114) are merged; this early skeleton is no longer needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant