Repository navigation
pyopenms: switch to nanobind bindings - #8699
Conversation
How old
|
Pattern in .pyx |
Classification | Goes to |
|---|---|---|
In PERFORMANCE_CRITICAL_METHODS set |
CPP_PERFORMANCE |
SPECIAL_METHODS (C++ lambda) |
Uses cdef, .inst.get(), deref(), memoryviews |
CPP_REQUIRED |
SPECIAL_METHODS (C++ lambda) |
| Everything else | PURE_PYTHON |
addons/*.py (Python) |
Concrete examples
| Method | Old (.pyx) | New location | Why |
|---|---|---|---|
get_peaks |
Cython buffer protocol loops | C++ SPECIAL_METHODS |
Performance — loops over all peaks |
set_peaks |
Cython with dtype checks | C++ SPECIAL_METHODS |
Performance + memory ownership |
to_df |
Cython calling get_peaks | Python addons/msspectrum.py |
Just calls public methods + pandas |
__repr__ |
Cython | Python addons/msspectrum.py |
Pure string formatting |
__iter__ on AASequence |
Cython with shared_ptr |
C++ SPECIAL_METHODS |
Needs C++ pointer management |
fromStringPermissive |
N/A (was auto-generated) | C++ SPECIAL_METHODS |
Needs OpenMS::String conversion |
Loading at runtime
- nanobind
.somodules load (C++ bindings +SPECIAL_METHODS) apply_addons(globals())runs, importing alladdons/*.pymodules@addon("ClassName")decorator registers methods in a registry- Each registered method is
setattr'd onto the nanobind class
The key benefit: you can edit Python addons without rebuilding C++. Only performance-critical or C++-dependent code lives in the compiled layer.
|
Cool! First of all, two things:
|
|
Ah I thought it was a different PR but you just renamed it 😄 still, the questions are valid. |
|
haha not yet. |
|
also: should we use a submodule for pyopenms? |
|
We could but not sure. Would make the transition a tiny bit easier but has some overhead until we actually split. Especially since it is currently under heavy development |
d6c9e3f to
e18e374
Compare
Port the last missing MSSpectrum addon from the old Cython bindings. Uses the same DLTensor + manual stride check pattern as rasterizeRTMZ. Adds 12 tests covering sum/max aggregation, edge cases, and validation. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ocstrings Use nb::type<T>() instead of nb::handle() as scope in all 13 nb::make_iterator calls so iterator types get a proper __module__, eliminating Python 3.12 DeprecationWarning. Skip int-inherited methods on IntEnum subclasses in docstring RST validation to avoid CPython's malformed int.from_bytes/to_bytes docstrings. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…gs (#8751) Add per-MS-level range queries by binding byMSLevel() and introducing a SpectrumRanges type for the returned range container. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Add section covering the pyopenms_wheel prebuilt mode, per-platform wheel repair tools, cibuildwheel CI usage, and known pitfalls (CMake COMPONENT gotcha, macOS library paths, nanobind reimport, Arrow discovery). Co-Authored-By: Claude Opus 4.6 <[email protected]>
…s to C++ bindings Migrate ~580 lines of Python addon code to C++ nanobind bindings: - Add __repr__/__str__ to 30+ classes across 8 binding files - Add Param dict-like API (keys, values, items, get, __getitem__, __setitem__, __contains__, update, from_dict, asDict, to_dict) - Delete fully-replaced addon files: repr_methods.py, param.py, drange.py - Remove migrated __repr__/__str__ from remaining addon files Co-Authored-By: Claude Opus 4.6 <[email protected]>
Merge unique content (type casters, addons, cross-module sharing, error messages) from the plain text file into the markdown version and delete the duplicate. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Remove outdated generator/ folder references and update pyOpenMS description to reflect hand-maintained nanobind bindings with 13 domain modules, addon system, and type casters. Expand project structure tree with all binding files. Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Fix _parquet_query.py: import ParquetFilterBuilder from pyopenms namespace instead of non-existent _parquet_filter module - Add BUILD_WITH_INSTALL_RPATH 1 to module properties so RPATH is applied at build time, enabling dev workflow from build directory Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Combine dual heap allocations into single char[] buffer with one nb::capsule in get_peaks() for MSSpectrum, MSChromatogram, and Mobilogram, reducing per-call overhead for small arrays (~1.7x faster for 500-peak spectra). - Add NOMINSIZE to all nanobind_add_module() calls so CMake Release -O3 is not overridden by nanobind's default -Os (size optimization), improving all binding code paths by ~20-60%. - Add warnings.warn() fallback when _arrow_zerocopy is unavailable, alerting users to rebuild with -DWITH_PARQUET=ON. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…eptideSearchEngineFIAlgorithm Add nanobind bindings for three new/expanded C++ classes from develop: - OpenSearchModificationAnalysis with 7 nested structs (ModificationPattern, ModificationSummary, DeltaMassEntry, PTMEntry, DeltaMassStatistics, PTMStatistics, OpenSearchAnalysisResult) and 6 public methods - PeptideSearchEngineFIAlgorithm.SearchResult struct and new overloads: in-memory search(PeakMap, FASTAEntry) and searchWithModificationAnalysis - QPXFile.exportToParquet (static, under WITH_PARQUET) - ParquetWriteConfig struct with Compression enum (under WITH_PARQUET) Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Add min_length/max_length parameters to ProteaseDigestion.digest() - Add 4-arg search() overloads accepting prot_ids output parameter - Reorder search/searchWithModificationAnalysis overloads so in-memory (PeakMap) versions precede file-based (String) to fix nanobind implicit conversion matching the wrong overload - Add 14 missing FileHandler bindings: getConsistentOutputfileType, getFeatOptions/setFeatOptions, loadSpectrum/storeSpectrum, storeFeatures, loadConsensusFeatures/storeConsensusFeatures, loadIdentifications/storeIdentifications, loadTransitions/ storeTransitions, loadTransformations/storeTransformations Co-Authored-By: Claude Opus 4.6 <[email protected]>
Clarify which ordering constraints in _priority_modules are hard requirements vs defensive documentation, based on analysis of nanobind's nb_type_new() base-class assertion and lazy type resolution. Co-Authored-By: Claude Opus 4.6 <[email protected]>
long_format=True: Route through Arrow C++ exporter (spectra_to_arrow) with types_mapper=pd.ArrowDtype for zero-copy Arrow→pandas. ~2.4x faster. long_format=False: Add get2DPeakDataSemiWide() C++ binding that exports peak data as contiguous flat buffers + offsets in a single pass. Python side slices into zero-copy numpy views per spectrum. 1.6–5x faster. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…d use flat buffer path for to_df(long_format=True) Move get2DPeakDataLong from Python addon to C++ nanobind binding with full float64 precision for mz/rt (2.3x faster standalone). Replace the Arrow-based to_df(long_format=True) with get2DPeakDataSemiWide + np.repeat, eliminating Arrow dependency and per-level loop+concat (3.4–15.8x faster, no WITH_PARQUET required). Co-Authored-By: Claude Opus 4.6 <[email protected]>
…method After rebasing on develop, sync nanobind bindings with upstream changes: - Remove CrossLinksDB.readFromOBOFile (deleted in ModificationsDB refactoring) - Add FeatureMapArrowIO, ConsensusMapArrowIO, ProteinIdentificationArrowIO Parquet bindings in bind_format.cpp (behind WITH_PARQUET) - Add zero-copy Arrow Table export/import for all three new IO classes in arrow_zerocopy.cpp via C Data Interface (table_to_pyarrow / pyarrow_to_table) - Fix ProteinIdentificationArrowIO import methods: use lambda wrappers that return modified vectors instead of broken direct-pointer bindings (STL type caster creates temporaries, losing output parameter modifications) Co-Authored-By: Claude Opus 4.6 <[email protected]>
31f0e56 to
689149f
Compare
Test Parquet round-trip and zero-copy Arrow export/import for FeatureMapArrowIO, ConsensusMapArrowIO, and ProteinIdentificationArrowIO. Also verify CrossLinksDB.readFromOBOFile was removed. Key coverage: - Parquet directory export/import preserves features, RT, m/z - Zero-copy Arrow Table export returns correct rows and columns - Arrow round-trip (export → import) preserves data - ProteinIdentification import returns lists (regression for STL type caster output parameter bug) - Empty container edge cases Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Fix nanobind cast error: use value instead of const-ref for std::vector<ProteinIdentification> in arrow_zerocopy export functions (nanobind cannot return reference to STL type caster temporary) - Add missing #include <OpenMS/KERNEL/ConsensusMap.h> in bind_metadata.cpp (needed for ExperimentalDesign::fromConsensusMap after develop rebase) - Fix test: import pyarrow.parquet as pq for read_table calls - Update test_api_singletons: readFromOBOFile was removed in develop Co-Authored-By: Claude Opus 4.6 <[email protected]>
In standalone builds (cibuildwheel/py-build-cmake), OPENMS_ARROW_TARGET is not exported by OpenMSConfig.cmake. The _arrow_zerocopy module now uses Arrow C++ API functions (ExportSchema, ImportRecordBatch, etc.) for zero-copy Table conversion, so it needs to link against Arrow. Add find_package(Arrow) fallback when OPENMS_ARROW_TARGET is not set. Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
Let’s merge the prototype |
…to features by feature_id The previous commits restored 3.5.0's merge keys on the peptide hits. That does not bring 3.5.0 code back: with the keys restored, 3.5.0's merge of get_df() and peptide_identifications_to_df() still fails in 3.6, with "You are trying to merge on uint64 and str columns for key 'feature_id'". The hits could only carry feature_id as text, because a meta value cannot hold an unsigned 64-bit integer. The copies also carried synthetic meta values into anything that stored them. The keys were lost by accident: d3f1ea6, part of the nanobind switch (#8699), rewrote get_assigned_peptide_identifications() as a plain collector and replaced the test's merge assertions with checks that the DataFrames exist. #8699 promised an identical Python API, and no CHANGELOG entry mentions the change. Rather than restore the annotation, give the merge a proper API: - get_assigned_peptide_identifications() stays a plain getter; its docstring says so and points to to_peptide_df(). - FeatureMap.to_peptide_df() writes one row per assigned PeptideIdentification, as PeptideIdentificationList.to_df() does, preceded by feature_id as uint64. The two frames merge on feature_id without conversion. peptide_df_columns() lists the columns. - to_df() always indexes by uint64. pandas inferred int64 when every ID happened to fit, which would not merge cleanly with the uint64 feature_id of to_peptide_df(). The user guide's merge example uses to_peptide_df(), and its table comes from the new output. test_000 again asserts the 15 merged rows on BSA1_F1_idmapped.featureXML that 3.5.0 asserted. The CHANGELOG announces the new methods, and as BREAKING the unchanged hits and the uint64 feature_id. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01YC1T2K9HQEUk2kQMZqC8h7
…to features by feature_id The previous commits restored 3.5.0's merge keys on the peptide hits. That does not bring 3.5.0 code back: with the keys restored, 3.5.0's merge of get_df() and peptide_identifications_to_df() still fails in 3.6, with "You are trying to merge on uint64 and str columns for key 'feature_id'". The hits could only carry feature_id as text, because a meta value cannot hold an unsigned 64-bit integer. The copies also carried synthetic meta values into anything that stored them. The keys were lost by accident: d3f1ea6, part of the nanobind switch (#8699), rewrote get_assigned_peptide_identifications() as a plain collector and replaced the test's merge assertions with checks that the DataFrames exist. #8699 promised an identical Python API, and no CHANGELOG entry mentions the change. Rather than restore the annotation, give the merge a proper API: - get_assigned_peptide_identifications() stays a plain getter; its docstring says so and points to to_peptide_df(). - FeatureMap.to_peptide_df() writes one row per assigned PeptideIdentification, as PeptideIdentificationList.to_df() does, preceded by feature_id as uint64. The two frames merge on feature_id without conversion. peptide_df_columns() lists the columns. - A feature_id meta value on the hits, as 3.5.0 added it, gives way to that column; inserting it next to the meta value column raised "cannot insert feature_id, already exists". The docstring also notes that the merge needs unique feature IDs: features created in Python have the ID 0 until setUniqueIds() assigns them one. - to_df() always indexes by uint64. pandas inferred int64 when every ID happened to fit, so the index type depended on the data, and the frames of two maps concatenated to a float64 index that rounds the IDs. The user guide's merge example uses to_peptide_df(), and its table comes from the new output. test_000 again asserts the 15 merged rows on BSA1_F1_idmapped.featureXML that 3.5.0 asserted. The CHANGELOG announces the new methods, and as BREAKING the unchanged hits and the uint64 feature_id. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01YC1T2K9HQEUk2kQMZqC8h7
…ications with to_df() on feature_id (#10288) * [FIX,PYOPENMS] get_assigned_peptide_identifications() sets the merge keys on the hits The 3.6 port of FeatureMap.get_assigned_peptide_identifications() only collected the PeptideIdentifications. It no longer added feature_id, ID_native_id and ID_filename to the peptide hits, as 3.5.0 did, so the merge the user guide documents failed with KeyError: 'feature_id' (#10260, item 4). The hits get feature_id again, as text, because a meta value cannot hold the unsigned 64-bit unique ID. ID_native_id and ID_filename are set only when they are known, instead of 'unknown', matching the nulls to_df() reports since #10117. The feature map itself stays unchanged. to_df() indexes features by the numeric feature_id, so the user guide and the docstring now convert the column before merging, and leave out PeptideIdentifications without hits, which have no hit to carry it. The CHANGELOG marks the type change against 3.5.0's text feature_id as BREAKING. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01YC1T2K9HQEUk2kQMZqC8h7 * [FIX,PYOPENMS] get_assigned_peptide_identifications(): drop keys that are unknown now A hit that already carried ID_native_id or ID_filename, for example from an earlier annotation stored in the file, kept that value when the feature's native ID or run path is unknown now, although to_df() reports it as null. The key is now removed in that case. The docstring also says that a map without identified hits gives no feature_id column to merge on. Both came up in CodeRabbit's review. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01YC1T2K9HQEUk2kQMZqC8h7 * [PYOPENMS] FeatureMap.to_peptide_df(): link assigned identifications to features by feature_id The previous commits restored 3.5.0's merge keys on the peptide hits. That does not bring 3.5.0 code back: with the keys restored, 3.5.0's merge of get_df() and peptide_identifications_to_df() still fails in 3.6, with "You are trying to merge on uint64 and str columns for key 'feature_id'". The hits could only carry feature_id as text, because a meta value cannot hold an unsigned 64-bit integer. The copies also carried synthetic meta values into anything that stored them. The keys were lost by accident: d3f1ea6, part of the nanobind switch (#8699), rewrote get_assigned_peptide_identifications() as a plain collector and replaced the test's merge assertions with checks that the DataFrames exist. #8699 promised an identical Python API, and no CHANGELOG entry mentions the change. Rather than restore the annotation, give the merge a proper API: - get_assigned_peptide_identifications() stays a plain getter; its docstring says so and points to to_peptide_df(). - FeatureMap.to_peptide_df() writes one row per assigned PeptideIdentification, as PeptideIdentificationList.to_df() does, preceded by feature_id as uint64. The two frames merge on feature_id without conversion. peptide_df_columns() lists the columns. - A feature_id meta value on the hits, as 3.5.0 added it, gives way to that column; inserting it next to the meta value column raised "cannot insert feature_id, already exists". The docstring also notes that the merge needs unique feature IDs: features created in Python have the ID 0 until setUniqueIds() assigns them one. - to_df() always indexes by uint64. pandas inferred int64 when every ID happened to fit, so the index type depended on the data, and the frames of two maps concatenated to a float64 index that rounds the IDs. The user guide's merge example uses to_peptide_df(), and its table comes from the new output. test_000 again asserts the 15 merged rows on BSA1_F1_idmapped.featureXML that 3.5.0 asserted. The CHANGELOG announces the new methods, and as BREAKING the unchanged hits and the uint64 feature_id. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01YC1T2K9HQEUk2kQMZqC8h7 * [PYOPENMS] df_columns(): name the score of an empty score type as to_df() does PeptideIdentificationList.to_df() builds a numpy structured array, and numpy names a field without a name after its position. For an empty score type the score column is therefore 'f3', while df_columns() listed ''. FeatureMap.peptide_df_columns() inherited the mismatch, and a column selection taken from df_columns() dropped the score with an "Unknown column(s) ignored" warning. df_columns() now reports the name that to_df() writes. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01YC1T2K9HQEUk2kQMZqC8h7 --------- Co-authored-by: Claude <[email protected]>
pyOpenMS — Nanobind-Based Python Bindings for OpenMS
This PR replaces the original pyOpenMS (based on autowrap/Cython) with hand-maintained nanobind-based bindings. The new bindings are faster to build, produce smaller binaries, and are easier to maintain.
Architecture
Hand-Maintained Bindings
Bindings are hand-maintained C++ source files in
src/pyOpenMS/bindings/. There is no code generator — each binding file directly uses nanobind's API to wrap OpenMS classes.Each file corresponds to a domain of the OpenMS C++ library:
bind_kernel.cppKERNEL/(MSSpectrum, MSExperiment, Feature, ...)bind_metadata.cppMETADATA/(SpectrumSettings, DataProcessing, ...)bind_chemistry.cppCHEMISTRY/(AASequence, EmpiricalFormula, ...)bind_analysis.cppANALYSIS/(MapAlignment, IDMapper, ...)bind_featurefinder.cppFEATUREFINDER/bind_format.cppFORMAT/(MzMLFile, IdXMLFile, ...)bind_processing.cppPROCESSING/(GaussFilter, PeakPicker, ...)bind_datastructures.cppDATASTRUCTURES/,MATH/,CONCEPT/bind_ml.cppML/bind_misc.cppmain_module.cppTotal: ~18,000 lines of hand-maintained C++ binding code wrapping 544 classes.
Multi-Module Architecture
The bindings compile into 12 shared libraries:
_pyopenms— main entry point (placeholder)_pyopenms_kernel,_pyopenms_metadata, ...,_pyopenms_misc— 10 domain modules_arrow_zerocopy— optional Apache Arrow zero-copy export (whenWITH_PARQUET=ON)All modules declare
NB_DOMAIN "pyopenms"so that types defined in one module are visible in all others. Domain-based splitting (vs hash-based) means related classes compile together, improving build locality and making the code easier to navigate.Custom Type Casters
Custom nanobind type casters in
bindings/type_casters/handle automatic C++ ↔ Python conversion:openms_string_caster.hOpenMS::Stringstr(with bytes fallback)openms_dposition_caster.hDPosition<1>,DPosition<2>float,tuple[float, float]openms_datavalue_caster.hDataValue,ParamValueNone/int/float/str/listopenms_stl_caster.hvector<String>,map<String,V>,set<String>list[str],dict[str,V],set[str]std_string_bytes_caster.hstd::stringstrorbytesnanobind_ms_data_consumer.hIMSDataConsumerall_casters.hAddon System
Pure Python methods are injected into wrapped C++ classes at import time via the addon system (
pyopenms/addons/, 23 files):Performance-critical methods like
get_peaks(),set_peaks(), andget_data_dict()are implemented as C++ lambdas directly in the binding files rather than as Python addons.Stub Generation (PEP 561)
Type stub files (
.pyi) are generated for IDE autocompletion and static type checking:nanobind.stubgengenerates initial stubs from compiled modulesstubs.patchapplies pattern fixesfix_stubs.pypost-processes stubs (keyword parameter names, NDArray annotations, etc.)py.typedmarker for PEP 561 complianceData Export
get_peaks()returns(mz_array, intensity_array)as numpy arraysto_df()/get_df()on spectra, chromatograms, features, and mapsspectra_to_arrow()/chromatograms_to_arrow()via Arrow C Data Interface for zero-copy exportBackward Compatibility
The Python-level API is identical to the original pyOpenMS:
get_peaks,set_peaks,to_df, etc.)__eq__,__getitem__,__iter__, etc.)PeakMap→MSExperiment,PeakSpectrum→MSSpectrumBuilding
As part of OpenMS (in-tree)
Standalone wheel
Wheel CI (cibuildwheel)
Wheels are built for Python 3.10–3.14 on Linux (x86_64, aarch64), macOS (arm64), and Windows (AMD64) using cibuildwheel with custom manylinux containers. Build configuration is in
pyproject.toml.Testing
Wrapping New Classes
bindings/bind_<domain>.cppbased on the C++ header path#include <OpenMS/...>for the headernb::class_<ClassName>(m, "ClassName", "docstring")with.def()chains// --- ClassName ---section comment for navigationSee
src/pyOpenMS/CLAUDE.mdfor detailed development instructions.Key Dependencies