Skip to content

pyopenms: switch to nanobind bindings - #8699

Merged
timosachsenberg merged 130 commits into
developfrom
nano
Mar 1, 2026
Merged

timosachsenberg merged 130 commits into
developfrom
nano

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Jan 27, 2026 •

Copy link
Copy Markdown
Contributor

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:

File Domain C++ Headers
bind_kernel.cpp Core data types KERNEL/ (MSSpectrum, MSExperiment, Feature, ...)
bind_metadata.cpp Metadata classes METADATA/ (SpectrumSettings, DataProcessing, ...)
bind_chemistry.cpp Chemistry CHEMISTRY/ (AASequence, EmpiricalFormula, ...)
bind_analysis.cpp Analysis algorithms ANALYSIS/ (MapAlignment, IDMapper, ...)
bind_featurefinder.cpp Feature finding FEATUREFINDER/
bind_format.cpp File I/O FORMAT/ (MzMLFile, IdXMLFile, ...)
bind_processing.cpp Signal processing PROCESSING/ (GaussFilter, PeakPicker, ...)
bind_datastructures.cpp Data structures & math DATASTRUCTURES/, MATH/, CONCEPT/
bind_ml.cpp Machine learning ML/
bind_misc.cpp Everything else Remaining classes
main_module.cpp Entry point (empty placeholder)

Total: ~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 (when WITH_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:

Header Types Python Equivalent
openms_string_caster.h OpenMS::String str (with bytes fallback)
openms_dposition_caster.h DPosition<1>, DPosition<2> float, tuple[float, float]
openms_datavalue_caster.h DataValue, ParamValue None/int/float/str/list
openms_stl_caster.h vector<String>, map<String,V>, set<String> list[str], dict[str,V], set[str]
std_string_bytes_caster.h std::string str or bytes
nanobind_ms_data_consumer.h IMSDataConsumer Python consumer interface
all_casters.h (master include) Includes all above + nanobind STL

Addon System

Pure Python methods are injected into wrapped C++ classes at import time via the addon system (pyopenms/addons/, 23 files):

# pyopenms/addons/msspectrum.py
from . import addon

@addon("MSSpectrum")
def get_tic(self):
    """Return the total ion current (sum of intensities)."""
    import numpy as np
    _, intensities = self.get_peaks()
    return float(np.sum(intensities))

Performance-critical methods like get_peaks(), set_peaks(), and get_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:

  1. nanobind.stubgen generates initial stubs from compiled modules
  2. stubs.patch applies pattern fixes
  3. fix_stubs.py post-processes stubs (keyword parameter names, NDArray annotations, etc.)
  4. py.typed marker for PEP 561 compliance

Data Export

  • NumPy arrays: get_peaks() returns (mz_array, intensity_array) as numpy arrays
  • Pandas DataFrames: to_df() / get_df() on spectra, chromatograms, features, and maps
  • Apache Arrow (optional): spectra_to_arrow() / chromatograms_to_arrow() via Arrow C Data Interface for zero-copy export

Backward Compatibility

The Python-level API is identical to the original pyOpenMS:

  • Same class names, method signatures, return types
  • Same addon methods (get_peaks, set_peaks, to_df, etc.)
  • Same operator overloads (__eq__, __getitem__, __iter__, etc.)
  • Aliases preserved: PeakMap → MSExperiment, PeakSpectrum → MSSpectrum
  • Nested enum aliases set as class attributes for backward compatibility

Building

As part of OpenMS (in-tree)

# Configure OpenMS with PYOPENMS=ON
cmake -B OpenMS-build -DPYOPENMS=ON ...

# Build pyopenms target
cmake --build OpenMS-build --target pyopenms -j$(nproc)

Standalone wheel

cd src/pyOpenMS
pip wheel . --no-build-isolation

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

# Run tests (from /tmp to avoid import shadowing)
cd /tmp
PYTHONPATH=.../OpenMS-build/pyOpenMS python3 -m pytest .../src/pyOpenMS/tests/ -v

# Or via ctest (runs from build directory)
ctest --test-dir OpenMS-build -R pyopenms_tests

Wrapping New Classes

  1. Pick bindings/bind_<domain>.cpp based on the C++ header path
  2. Add #include <OpenMS/...> for the header
  3. Add nb::class_<ClassName>(m, "ClassName", "docstring") with .def() chains
  4. Each class has a // --- ClassName --- section comment for navigation
  5. Build and test

See src/pyOpenMS/CLAUDE.md for detailed development instructions.

Key Dependencies

  • nanobind v2.10.0 (fetched automatically)
  • Python 3.9+ (3.10+ for wheels)
  • NumPy 2.0+
  • py-build-cmake (PEP 517 build backend for standalone wheels)

@timosachsenberg timosachsenberg changed the title experiment: use libclang and existing pxd to generaet nanobind bindings experiment: use libclang and existing pxd to generate nanobind bindings Jan 27, 2026
Comment thread src/pyOpenMS2/tests/test_peak1d.py Fixed
@timosachsenberg

Copy link
Copy Markdown
Contributor Author

How old .pyx addon files map to the new nanobind system

In the old autowrap/Cython system, each .pyx file in src/pyOpenMS/addons/ contains Cython methods that get injected into the auto-generated wrapper classes. These mix Python and C-level code — cdef typed variables, .inst.get() for raw C++ pointer access, deref(), numpy buffer protocol with mode="c", etc.

In pyOpenMS2, this is split into two layers:

1. Pure Python addons (src/pyOpenMS2/pyopenms/addons/*.py)

Methods that don't need direct C++ access. They call public bound methods and do high-level logic:

@addon("MSSpectrum")
def to_df(self, columns=None):
    mzs, intensities = self.get_peaks()  # calls C++ binding
    return pd.DataFrame({"mz": mzs, "intensity": intensities})

These are injected at import time via setattr() — no rebuild needed when you edit them.

2. C++ lambdas in SPECIAL_METHODS (nanobind_emitter_v2.py)

Performance-critical methods and anything that needs direct C++ memory access. These are nanobind lambda bindings compiled into the .so:

.def("get_peaks", [](const OpenMS::MSSpectrum& self) {
    // C++ loop over peaks, return numpy arrays via capsules
})

How the decision is made

The addon_processor.py classifies each old .pyx method:

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

  1. nanobind .so modules load (C++ bindings + SPECIAL_METHODS)
  2. apply_addons(globals()) runs, importing all addons/*.py modules
  3. @addon("ClassName") decorator registers methods in a registry
  4. 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.

@timosachsenberg timosachsenberg changed the title experiment: use libclang and existing pxd to generate nanobind bindings pyopenms: switch to nanobind bindings Feb 6, 2026
@jpfeuffer

Copy link
Copy Markdown
Contributor

Cool! First of all, two things:

  • Time to split pyopenms away from OpenMS?
  • Did you benchmark timing the heaviest addon functions? Now that they are not compiled anymore they should be slower.

@jpfeuffer

Copy link
Copy Markdown
Contributor

Ah I thought it was a different PR but you just renamed it 😄 still, the questions are valid.

@timosachsenberg

Copy link
Copy Markdown
Contributor Author

haha not yet.
For the split: we should do this once we can agree on a naming and versioning scheme.
I did not do a benchmark yet. There are still some rough edges (e.g. I think I will switch the back to copies for MSExperiment when getitem is used.
Also all the arrow and numpy stuff needs to be compared and benchmarked

@timosachsenberg

Copy link
Copy Markdown
Contributor Author

also: should we use a submodule for pyopenms?

@jpfeuffer

jpfeuffer commented Feb 6, 2026 •

Copy link
Copy Markdown
Contributor

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

@timosachsenberg
timosachsenberg marked this pull request as ready for review February 7, 2026 13:20
@timosachsenberg
timosachsenberg force-pushed the nano branch 2 times, most recently from d6c9e3f to e18e374 Compare February 7, 2026 20:55
timosachsenberg and others added 17 commits February 28, 2026 10:25
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]>
…8538) (#8805)

* .

* Create test_matrix_zerocopy.py

* Update test_matrix_zerocopy.py
…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]>
timosachsenberg and others added 4 commits February 28, 2026 11:04
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]>
@timosachsenberg

Copy link
Copy Markdown
Contributor Author

Let’s merge the prototype

@timosachsenberg
timosachsenberg merged commit 3e94ef6 into develop Mar 1, 2026
49 of 51 checks passed
@timosachsenberg
timosachsenberg deleted the nano branch March 1, 2026 16:46
timosachsenberg pushed a commit that referenced this pull request Sep 27, 2026
…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
timosachsenberg pushed a commit that referenced this pull request Sep 27, 2026
…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
timosachsenberg added a commit that referenced this pull request Sep 27, 2026
…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]>
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.

3 participants