Skip to content

Arrow export from MSExperiment - #8577

Closed
iamritikiit wants to merge 27 commits into
OpenMS:developfrom
iamritikiit:feature/cpp-arrow-ms-experiment
Closed

iamritikiit wants to merge 27 commits into
OpenMS:developfrom
iamritikiit:feature/cpp-arrow-ms-experiment

Conversation

@iamritikiit

@iamritikiit iamritikiit commented Dec 30, 2025 •

Copy link
Copy Markdown
Contributor

Description

This PR introduces a minimal, opt-in C++ helper for exporting MSExperiment
to an Apache Arrow table when OpenMS is built with Parquet/Arrow support.

The implementation is intentionally a stub and placed in a separate file
(ArrowExport.h / ArrowExport.cpp) to establish structure for incremental
follow-up work. The code is fully guarded by WITH_PARQUET and does not change
any existing behavior.

Built locally with Arrow/Parquet enabled and ran ctest successfully
(adapter and pipeline tests depending on external tools were skipped as expected).

Refs #8574

Checklist

  • Make sure that you are listed in the AUTHORS file
  • Add relevant changes and new features to the CHANGELOG file
  • I have commented my code, particularly in hard-to-understand areas
  • New and existing unit tests pass locally with my changes
  • Updated or added python bindings for changed or new classes (Tick if no updates were necessary.)

Summary by CodeRabbit

  • New Features

    • Export MSExperiment to Apache Arrow and Parquet (spectra & chromatograms) in long or semi‑wide layouts; configurable columns, RT/m/z/MS‑level filters, optional precursor and ion‑mobility fields, Parquet compression/tuning, zero‑copy Python interop, get_arrow_columns and extended to_arrow (spectra, chromatograms, or both).
  • Chores

    • Build updated to include Arrow/Parquet zero‑copy Python extension; pyarrow added to build requirements.
  • Tests

    • New unit/integration tests for Arrow/Parquet exports, formats, filters, column discovery, Parquet options, and edge cases.
  • Bug Fixes

    • Corrected CV term for time‑delayed fragmentation spectra.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Dec 30, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds a WITH_PARQUET-guarded Arrow/Parquet export subsystem: new C++ OpenMS::ArrowExport API and implementation, CMake and pyOpenMS build wiring, a zero-copy Cython Python extension, MSExperiment to_arrow/get_arrow_columns bindings, and unit + class tests.

Changes

Cohort / File(s) Summary
Core C++ API & impl
src/openms/include/OpenMS/FORMAT/ArrowExport.h, src/openms/source/FORMAT/ArrowExport.cpp
New OpenMS::ArrowExport public API and implementation: export spectra/chromatograms to Arrow (Long / SemiWide) and Parquet, config structs (spectra/chrom), Parquet write options, Arrow C Data Interface exports, filtering (ms_level/RT/mz), IM/precursor handling, builders for long/semi-wide, parquet writer helpers, and error logging.
OpenMS sources CMake
src/openms/include/OpenMS/FORMAT/sources.cmake, src/openms/source/FORMAT/sources.cmake
Add conditional inclusion/appending of ArrowExport header/source under WITH_PARQUET; separate HDF5 and Parquet conditionals.
pyOpenMS build wiring
src/pyOpenMS/CMakeLists.txt
New Cython extension target arrow_zerocopy (_arrow_zerocopy) built when WITH_PARQUET, links Arrow/OpenMS, integrated into pyopenms build, and test wiring updated.
Cython interface & zerocopy module
src/pyOpenMS/pxds/ArrowExport.pxd, src/pyOpenMS/pyopenms/_arrow_zerocopy.pyx
pxd exposes ArrowExport config/types and selected methods; _arrow_zerocopy.pyx implements zero-copy export via Arrow C Data Interface, marshals ArrowSchema/ArrowArray, imports into pyarrow, and manages memory/ownership.
pyOpenMS MSExperiment binding
src/pyOpenMS/addons/MSExperiment.pyx
Adds _get_cpp_pointer, get_arrow_columns, and extended to_arrow supporting spectra/chromatograms/both, filters, formats, precursor/ion-mobility flags, zero-copy path (pyopenms._arrow_zerocopy) and Python fallback builders.
Python & C++ tests / test wiring
src/pyOpenMS/tests/unittests/test_dataframe_columns.py, src/tests/class_tests/openms/source/ArrowExport_test.cpp, src/tests/class_tests/openms/executables.cmake, src/tests/class_tests/openms/CMakeLists.txt
New unit and class tests exercising Arrow schemas, formats, filters, and Parquet writes; adds ArrowExport_test target and updates test lists.
Misc small change
src/openms/source/FORMAT/HANDLERS/MzMLHandler.cpp
CV term update: replaced MS:1000789 with MS:1000790 for time‑delayed fragmentation spectrum emission.
Python build deps
src/pyOpenMS/requirements_bld.txt
Added pyarrow to Python build requirements.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant Py as Python caller (MSExperiment)
    participant Cxy as Cython (_arrow_zerocopy)
    participant CPP as C++ OpenMS::ArrowExport
    participant ABI as Arrow C Data Interface
    participant PyA as pyarrow

    Note over Py,Cxy: Zero-copy export (spectra or chromatograms)
    Py->>Cxy: spectra_to_arrow(exp, config) / chromatograms_to_arrow(...)
    Cxy->>Cxy: build Arrow*ExportConfig from args
    Cxy->>CPP: allocate ArrowSchema*, ArrowArray*
    Cxy->>CPP: export*ToArrowCDataInterface(exp_ptr, config, schema_ptr, array_ptr) (nogil)
    CPP->>ABI: populate ArrowSchema and ArrowArray with buffers (zero-copy)
    alt export success
        Cxy->>PyA: pa.RecordBatch._import_from_c(schema_ptr, array_ptr)
        PyA-->>Py: pyarrow.Table (ownership transferred)
    else export failure
        CPP-->>Cxy: return false
        Cxy->>Cxy: free schema/array memory
        Cxy-->>Py: raise RuntimeError
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • jpfeuffer

Poem

🐇 I hopped through rows and lists with glee,
packed mz and rt and intensity,
zero‑copy tunnels bytes to sky,
Parquet quilts tuck columns nigh,
carrots, columns, bytes — hop, fly!

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Arrow export from MSExperiment' directly and clearly summarizes the main change: adding Arrow export functionality for MSExperiment data. It is specific, concise, and accurately reflects the primary purpose of this PR.
Docstring Coverage ✅ Passed Docstring coverage is 83.33% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

📜 Recent review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cdb6709 and 82a1334.

📒 Files selected for processing (3)
  • src/openms/source/FORMAT/HANDLERS/MzMLHandler.cpp
  • src/pyOpenMS/requirements_bld.txt
  • src/tests/class_tests/openms/executables.cmake
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/pyOpenMS/requirements_bld.txt
  • src/tests/class_tests/openms/executables.cmake
🧰 Additional context used
📓 Path-based instructions (3)
src/openms/**/*.{cpp,h,hpp,cc,cxx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

src/openms/**/*.{cpp,h,hpp,cc,cxx}: Follow the existing C++ coding conventions in the codebase
Use the established naming patterns for classes, methods, and variables
Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)
Follow the established error handling patterns
Utilize OpenMS logging mechanisms
Be mindful of memory usage when processing large datasets
Consider algorithmic complexity for data processing operations
Use appropriate OpenMS containers and algorithms

Files:

  • src/openms/source/FORMAT/HANDLERS/MzMLHandler.cpp
**/*.{h,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{h,cpp}: Use 2-space indentation for C++ and header files; no tabs; Unix line endings (LF)
All non-template exported classes, structs, functions, and variables must use OPENMS_DLLAPI macro; templates are exempt
One class per file; class name must match file name exactly
Always pair .h header files with .cpp implementation files
Class and type names must use PascalCase; methods must use lowerCamelCase; variables must use snake_case
Private and protected member variables must end with trailing underscore _
Enum names and macro definitions must use UPPER_SNAKE_CASE; prefer enum class over C-style enums
Use OpenMS primitive types from OpenMS/CONCEPT/Types.h instead of standard C++ types
Use Size/SignedSize types for STL .size() values instead of standard integer types
Prefer references over pointers in C++ code
Use Rule-of-0 (no explicit copy/move) or Rule-of-6 (all copy/move/destroy); never use Rule-of-5
Accessor methods must use get/set pairs for protected/private members; do not return references to primitive types
All exceptions must derive from Exception::Base; throw with file, line, and OPENMS_PRETTY_FUNCTION; catch by reference
Code comments must use // style; should comprise at least ~5% of code; describe the next few lines in plain English
Use .clang-format configuration from repository root for code formatting; check with clang-format --dry-run -Werror
Use OpenMS logging macros and OpenMS::LogStream; avoid std::cout and std::cerr
Avoid std::endl; prefer \n for better performance
Prefer OpenMS::String for numeric formatting and parsing
Braces must be on their own lines and aligned; always use braces even for single-line blocks (trivial one-liners may remain single-line)
Space required after keywords (if, for, while) and around binary operators

Files:

  • src/openms/source/FORMAT/HANDLERS/MzMLHandler.cpp
**

📄 CodeRabbit inference engine (AGENTS.md)

File extensions must be lowercase except for ML, XML, and mzData

Files:

  • src/openms/source/FORMAT/HANDLERS/MzMLHandler.cpp
🧠 Learnings (1)
📚 Learning: 2025-12-04T16:25:07.026Z
Learnt from: timosachsenberg
Repo: OpenMS/OpenMS PR: 8177
File: src/openms/source/FORMAT/HANDLERS/MzMLHandler.cpp:5069-5074
Timestamp: 2025-12-04T16:25:07.026Z
Learning: In OpenMS mzML writing, PSI-MS term MS:1003441 "ion mobility centroid frame" is a spectrum-level cvParam. It should be written at spectrum level (not scan level).

Applied to files:

  • src/openms/source/FORMAT/HANDLERS/MzMLHandler.cpp
🔇 Additional comments (2)
src/openms/source/FORMAT/HANDLERS/MzMLHandler.cpp (2)

4167-4173: PSI-MS term MS:1000790 is correct for time-delayed fragmentation spectrum.

The change achieves reader-writer consistency: the reader-side handler already maps MS:1000790 to InstrumentSettings::ScanMode::TDF, and this update ensures the writer emits the same accession when TDF mode is present. The term name and accession are aligned with the PSI-MS ontology and usage is consistent across the file.


5144-5150: TDF accession MS:1000790 and EMC accession MS:1000789 are correct and consistent. This prevents mismatched accessions that could cause round-trip deserialization to interpret the spectrum type differently during read-back.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
src/openms/source/FORMAT/ArrowExport.cpp (1)

1-28: Well-structured stub implementation.

The placeholder implementation is properly guarded with WITH_PARQUET and includes helpful TODO comments outlining the required implementation steps. The use of a commented parameter (/* exp */) and nullptr return is appropriate for a stub.

When you're ready to implement the full conversion logic, I can help generate:

  • Arrow schema definition for MSExperiment data structures
  • Array builders for spectrum/chromatogram data
  • Unit tests for the export functionality

Would you like me to create a tracking issue for the implementation work?

src/openms/include/OpenMS/FORMAT/ArrowExport.h (2)

1-6: Consider adding the $Maintainer:$ tag.

Per coding guidelines, header files should include a $Maintainer:$ marker in the preamble. While not critical for a stub, adding it now establishes consistency.

🔎 Suggested addition
 // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
 // SPDX-License-Identifier: BSD-3-Clause
+//
+// $Maintainer: <your_email_here> $
 
 #pragma once

Based on coding guidelines requiring $Maintainer:$ in every .h file header preamble.


22-25: Enhance Doxygen documentation when implementing full functionality.

The current @brief is sufficient for a stub, but consider adding @param [in] exp and @return tags when implementing the full export logic to align with OpenMS documentation standards.

🔎 Example enhanced documentation
 /**
   @brief Export MSExperiment to Apache Arrow Table
+  
+  @param [in] exp The MSExperiment to export
+  @return Shared pointer to Arrow Table containing the exported data, or nullptr on failure
+  
+  @throws Exception::InvalidParameter if the experiment is empty
+  @throws Exception::ParseError if Arrow table construction fails
 */

Based on coding guidelines requiring parameter direction tags and comprehensive API documentation.

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b0e5f38 and b7e1295.

📒 Files selected for processing (4)
  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
  • src/openms/include/OpenMS/FORMAT/sources.cmake
  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/openms/source/FORMAT/sources.cmake
🧰 Additional context used
📓 Path-based instructions (10)
src/openms/**

📄 CodeRabbit inference engine (AGENTS.md)

src/openms/**: Use lowercase file extensions (except ML/XML and mzData where case is significant)
When adding new file formats, update FileHandler::NamesOfTypes[], schema files, and tests

Files:

  • src/openms/include/OpenMS/FORMAT/sources.cmake
  • src/openms/source/FORMAT/sources.cmake
  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
src/openms/**/*.{cpp,h,hpp,cc,cxx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

src/openms/**/*.{cpp,h,hpp,cc,cxx}: Follow the existing C++ coding conventions in the codebase
Use the established naming patterns for classes, methods, and variables
Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)
Follow the established error handling patterns
Utilize OpenMS logging mechanisms
Be mindful of memory usage when processing large datasets
Consider algorithmic complexity for data processing operations
Use appropriate OpenMS containers and algorithms

Files:

  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
**/*.{h,hpp,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{h,hpp,cpp}: Never use std::cout or std::cerr directly; use OpenMS logging macros instead
Never use std::endl; use \n for performance
Use PascalCase for class names, type names, and namespace names
Use lowerCamelCase for method and function names
Use snake_case for variable names
Use trailing underscore for private and protected member variables
Use UPPER_SNAKE_CASE for enum values and preprocessor macros
Use Size and SignedSize types from OpenMS for STL .size() values instead of platform-dependent types
Prefer references over pointers in C++ code
Always use braces for control flow blocks, even single-line statements (trivial one-liners may be kept single-line)
Place opening and closing braces on their own lines, aligned vertically
Add a space after control flow keywords (if, for, while, switch)
Add spacing around binary operators
Use OpenMS::String for numeric formatting and parsing instead of standard library alternatives
Use OpenMS primitive types from OpenMS/CONCEPT/Types.h
Follow Rule-of-0 or Rule-of-6 for class design (ensure proper move/copy semantics or default them)
Derive exception classes from Exception::Base; throw with file, line, and OPENMS_PRETTY_FUNCTION information
Catch exceptions by const reference
Use ./.clang-format configuration file from repository root for code formatting
Provide comments covering at least ~5% of code; use // style and describe the next few lines in plain English
Use C++20 language standard; avoid features not supported across all target platforms (Linux, macOS, Windows)

Files:

  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
**/*.{h,hpp,cpp,py,pyx,pxd}

📄 CodeRabbit inference engine (AGENTS.md)

Use 2-space indentation, no tabs; enforce Unix line endings (LF)

Files:

  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
**/{include,source}/**/*.{h,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

Pair each C++ header file (.h) with a corresponding implementation file (.cpp) for non-template code

Files:

  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
src/openms/**/*.{h,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

src/openms/**/*.{h,cpp}: For new C++ classes: create paired .h and .cpp files, add Doxygen documentation, create a class test, apply OPENMS_DLLAPI, and register in CMake lists
File name must match class name; one class per file (except templates with _impl.h suffix)
When modifying C++ APIs, update corresponding .pxd files and pyOpenMS addons

Files:

  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
src/openms/include/OpenMS/**/*.h

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Add Doxygen comments for new public methods and classes

Files:

  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
**/*.h

📄 CodeRabbit inference engine (AGENTS.md)

**/*.h: Never add using namespace or using std::... declarations in header files
Apply OPENMS_DLLAPI export macro to all non-template exported classes, structs, functions, and variables
Implement get/set accessor pairs for protected and private member variables
Do not use reference getters for primitive types; return by value instead
Include $Maintainer:$ marker in every .h file header preamble
Use forward declarations in header files; include only base class headers, non-pointer members, and templates

Files:

  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
**/*.{h,hpp}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{h,hpp}: Use @brief tag in Doxygen comments; it is required and should not be auto-generated
Include parameter direction tags [in], [out], or [in,out] for all Doxygen @param entries
Document all possible exceptions thrown from a method using Doxygen @throws or @exception tags

Files:

  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
**/*.{h,_impl.h}

📄 CodeRabbit inference engine (AGENTS.md)

Use templates only with _impl.h suffix when necessary; .h files must never include _impl.h

Files:

  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
🧠 Learnings (15)
📚 Learning: 2025-12-25T14:45:31.705Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-25T14:45:31.705Z
Learning: Applies to src/tests/class_tests/openms/source/*_test.cpp : Use `USE_CASE_DESCRIPTION` pattern for test names; add test source file to `executables.cmake`

Applied to files:

  • src/openms/include/OpenMS/FORMAT/sources.cmake
  • src/openms/source/FORMAT/sources.cmake
📚 Learning: 2025-09-03T12:58:20.032Z
Learnt from: timosachsenberg
Repo: OpenMS/OpenMS PR: 8177
File: src/tests/topp/CMakeLists.txt:1857-1865
Timestamp: 2025-09-03T12:58:20.032Z
Learning: OpenMS tests: When adding new TOPP tests in src/tests/topp/CMakeLists.txt that compare outputs via FuzzyDiff, always add set_tests_properties("<tool>_<n>_out<m>" PROPERTIES DEPENDS "<tool>_<n>") to avoid flakiness under parallel CTest runs.

Applied to files:

  • src/openms/include/OpenMS/FORMAT/sources.cmake
📚 Learning: 2025-12-25T14:45:31.705Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-25T14:45:31.705Z
Learning: Applies to src/openms/**/*.{h,cpp} : For new C++ classes: create paired `.h` and `.cpp` files, add Doxygen documentation, create a class test, apply `OPENMS_DLLAPI`, and register in CMake lists

Applied to files:

  • src/openms/include/OpenMS/FORMAT/sources.cmake
  • src/openms/source/FORMAT/sources.cmake
  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2025-12-25T14:45:31.705Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-25T14:45:31.705Z
Learning: Applies to src/openms/**/*.{h,cpp} : When modifying C++ APIs, update corresponding `.pxd` files and pyOpenMS addons

Applied to files:

  • src/openms/include/OpenMS/FORMAT/sources.cmake
  • src/openms/source/FORMAT/sources.cmake
📚 Learning: 2025-12-25T14:45:31.705Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-25T14:45:31.705Z
Learning: Applies to **/*.{h,hpp,cpp} : Use OpenMS primitive types from `OpenMS/CONCEPT/Types.h`

Applied to files:

  • src/openms/include/OpenMS/FORMAT/sources.cmake
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/include/OpenMS/**/*.h : Add Doxygen comments for new public methods and classes

Applied to files:

  • src/openms/include/OpenMS/FORMAT/sources.cmake
  • src/openms/source/FORMAT/sources.cmake
  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
📚 Learning: 2025-12-25T14:45:31.705Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-25T14:45:31.705Z
Learning: Applies to src/openms/** : When adding new file formats, update `FileHandler::NamesOfTypes[]`, schema files, and tests

Applied to files:

  • src/openms/source/FORMAT/sources.cmake
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Be mindful of memory usage when processing large datasets

Applied to files:

  • src/openms/source/FORMAT/sources.cmake
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)

Applied to files:

  • src/openms/source/FORMAT/sources.cmake
  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/tests/class_tests/openms/**/*.cpp : Write unit tests for new functionality

Applied to files:

  • src/openms/source/FORMAT/sources.cmake
  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Use the established naming patterns for classes, methods, and variables

Applied to files:

  • src/openms/source/FORMAT/sources.cmake
📚 Learning: 2025-12-25T14:45:31.705Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-25T14:45:31.705Z
Learning: Applies to src/openms/extern/** : Never modify files in `src/openms/extern/` (third-party vendored code)

Applied to files:

  • src/openms/source/FORMAT/sources.cmake
📚 Learning: 2025-12-25T14:45:31.705Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-25T14:45:31.705Z
Learning: Applies to src/topp/*.cpp : TOPP tool source files must be registered in `src/topp/executables.cmake` and `ToolHandler.cpp`

Applied to files:

  • src/openms/source/FORMAT/sources.cmake
📚 Learning: 2025-12-25T14:45:31.705Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-25T14:45:31.705Z
Learning: Applies to src/tests/topp/CMakeLists.txt : Add TOPP tool tests to `src/tests/topp/CMakeLists.txt` with corresponding test data

Applied to files:

  • src/openms/source/FORMAT/sources.cmake
📚 Learning: 2025-12-25T14:45:31.705Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-25T14:45:31.705Z
Learning: Applies to **/*.h : Apply `OPENMS_DLLAPI` export macro to all non-template exported classes, structs, functions, and variables

Applied to files:

  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
🧬 Code graph analysis (1)
src/openms/include/OpenMS/FORMAT/ArrowExport.h (1)
src/openms/source/FORMAT/ArrowExport.cpp (2)
  • exportMSExperimentToArrow (14-23)
  • exportMSExperimentToArrow (14-14)
🔇 Additional comments (2)
src/openms/source/FORMAT/sources.cmake (1)

106-109: LGTM! Clean integration of ArrowExport.cpp into the build system.

The conditional addition of ArrowExport.cpp alongside QuantmsIO.cpp under the WITH_PARQUET block is correct and follows the established pattern.

src/openms/include/OpenMS/FORMAT/sources.cmake (1)

118-120: LGTM! Header inclusion properly guarded.

The conditional addition of ArrowExport.h mirrors the source file integration and correctly follows the same pattern used for other optional dependencies like HDF5.

@timosachsenberg

Copy link
Copy Markdown
Contributor

Feel free to add to this branch but try to keep number of pushes low. It’s a rather heavy ci

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (1)
src/openms/source/FORMAT/ArrowExport.cpp (1)

32-33: Clarify variable naming to avoid confusion with integer type.

The variable name int_builder (and later int_array) could be misread as "integer builder" rather than "intensity builder". Consider using intensity_builder or inten_builder for clarity.

🔎 Proposed naming improvement
     // Builders for columns: mz, intensity, rt (all float64)
     arrow::DoubleBuilder mz_builder(pool);
-    arrow::DoubleBuilder int_builder(pool);
+    arrow::DoubleBuilder intensity_builder(pool);
     arrow::DoubleBuilder rt_builder(pool);
 
     // ... later in code ...
 
-        st = int_builder.Append(peak.getIntensity());
+        st = intensity_builder.Append(peak.getIntensity());
         if (!st.ok()) return nullptr;
 
     // ... and at finalization ...
 
     std::shared_ptr<arrow::Array> mz_array;
-    std::shared_ptr<arrow::Array> int_array;
+    std::shared_ptr<arrow::Array> intensity_array;
     std::shared_ptr<arrow::Array> rt_array;
 
     if (!mz_builder.Finish(&mz_array).ok()) return nullptr;
-    if (!int_builder.Finish(&int_array).ok()) return nullptr;
+    if (!intensity_builder.Finish(&intensity_array).ok()) return nullptr;
     if (!rt_builder.Finish(&rt_array).ok()) return nullptr;
 
     // ... and in table creation ...
 
-    return arrow::Table::Make(schema, {mz_array, int_array, rt_array});
+    return arrow::Table::Make(schema, {mz_array, intensity_array, rt_array});
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b7e1295 and 484ab7e.

📒 Files selected for processing (2)
  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
  • src/openms/source/FORMAT/ArrowExport.cpp
🧰 Additional context used
📓 Path-based instructions (10)
src/openms/**/*.{cpp,h,hpp,cc,cxx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

src/openms/**/*.{cpp,h,hpp,cc,cxx}: Follow the existing C++ coding conventions in the codebase
Use the established naming patterns for classes, methods, and variables
Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)
Follow the established error handling patterns
Utilize OpenMS logging mechanisms
Be mindful of memory usage when processing large datasets
Consider algorithmic complexity for data processing operations
Use appropriate OpenMS containers and algorithms

Files:

  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
**/*.{h,hpp,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{h,hpp,cpp}: Never use std::cout or std::cerr directly; use OpenMS logging macros instead
Never use std::endl; use \n for performance
Use PascalCase for class names, type names, and namespace names
Use lowerCamelCase for method and function names
Use snake_case for variable names
Use trailing underscore for private and protected member variables
Use UPPER_SNAKE_CASE for enum values and preprocessor macros
Use Size and SignedSize types from OpenMS for STL .size() values instead of platform-dependent types
Prefer references over pointers in C++ code
Always use braces for control flow blocks, even single-line statements (trivial one-liners may be kept single-line)
Place opening and closing braces on their own lines, aligned vertically
Add a space after control flow keywords (if, for, while, switch)
Add spacing around binary operators
Use OpenMS::String for numeric formatting and parsing instead of standard library alternatives
Use OpenMS primitive types from OpenMS/CONCEPT/Types.h
Follow Rule-of-0 or Rule-of-6 for class design (ensure proper move/copy semantics or default them)
Derive exception classes from Exception::Base; throw with file, line, and OPENMS_PRETTY_FUNCTION information
Catch exceptions by const reference
Use ./.clang-format configuration file from repository root for code formatting
Provide comments covering at least ~5% of code; use // style and describe the next few lines in plain English
Use C++20 language standard; avoid features not supported across all target platforms (Linux, macOS, Windows)

Files:

  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
**/*.{h,hpp,cpp,py,pyx,pxd}

📄 CodeRabbit inference engine (AGENTS.md)

Use 2-space indentation, no tabs; enforce Unix line endings (LF)

Files:

  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
**/{include,source}/**/*.{h,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

Pair each C++ header file (.h) with a corresponding implementation file (.cpp) for non-template code

Files:

  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
src/openms/**/*.{h,cpp}

📄 CodeRabbit inference engine (AGENTS.md)

src/openms/**/*.{h,cpp}: For new C++ classes: create paired .h and .cpp files, add Doxygen documentation, create a class test, apply OPENMS_DLLAPI, and register in CMake lists
File name must match class name; one class per file (except templates with _impl.h suffix)
When modifying C++ APIs, update corresponding .pxd files and pyOpenMS addons

Files:

  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
src/openms/**

📄 CodeRabbit inference engine (AGENTS.md)

src/openms/**: Use lowercase file extensions (except ML/XML and mzData where case is significant)
When adding new file formats, update FileHandler::NamesOfTypes[], schema files, and tests

Files:

  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
src/openms/include/OpenMS/**/*.h

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Add Doxygen comments for new public methods and classes

Files:

  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
**/*.h

📄 CodeRabbit inference engine (AGENTS.md)

**/*.h: Never add using namespace or using std::... declarations in header files
Apply OPENMS_DLLAPI export macro to all non-template exported classes, structs, functions, and variables
Implement get/set accessor pairs for protected and private member variables
Do not use reference getters for primitive types; return by value instead
Include $Maintainer:$ marker in every .h file header preamble
Use forward declarations in header files; include only base class headers, non-pointer members, and templates

Files:

  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
**/*.{h,hpp}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{h,hpp}: Use @brief tag in Doxygen comments; it is required and should not be auto-generated
Include parameter direction tags [in], [out], or [in,out] for all Doxygen @param entries
Document all possible exceptions thrown from a method using Doxygen @throws or @exception tags

Files:

  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
**/*.{h,_impl.h}

📄 CodeRabbit inference engine (AGENTS.md)

Use templates only with _impl.h suffix when necessary; .h files must never include _impl.h

Files:

  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
🧠 Learnings (4)
📓 Common learnings
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/tests/class_tests/openms/**/*.cpp : Write unit tests for new functionality

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2025-12-25T14:45:31.705Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-25T14:45:31.705Z
Learning: Applies to **/*.h : Apply `OPENMS_DLLAPI` export macro to all non-template exported classes, structs, functions, and variables

Applied to files:

  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
🧬 Code graph analysis (1)
src/openms/include/OpenMS/FORMAT/ArrowExport.h (1)
src/openms/source/FORMAT/ArrowExport.cpp (2)
  • exportMSExperimentToArrow (15-75)
  • exportMSExperimentToArrow (15-15)

@timosachsenberg

Copy link
Copy Markdown
Contributor

@jpfeuffer what arguments should this function get? Do we want to decide between long and wide Format? Do we want to pass a column set that should be exported?

@jpfeuffer

Copy link
Copy Markdown
Contributor

I guess the same as the numpy version?

@timosachsenberg

Copy link
Copy Markdown
Contributor

@jpfeuffer it would be great to have the option to include spectrum metadata like precursor information, ion mobility etc.
not sure if we already have the best interface on the numpy level

@jpfeuffer

Copy link
Copy Markdown
Contributor

Hmm. I personally would do four levels. Potentially configurable as an OR flag.

  • Raw peaks
  • important class members ( like precursor)
  • array metadata (like IM)
  • value metadata (MetaInfoInterface)

The problem about value and array metadata is that without prespecifying the values you want, you would need to prescan all spectra first to generate the schema.

And specifying the values you want is also tricky without that prescan unless you can guarantee that all spectra have the same metadata values.

@jpfeuffer

Copy link
Copy Markdown
Contributor

Without tests, it is meaningless to start CI.

@timosachsenberg

Copy link
Copy Markdown
Contributor
  • array metadata (like IM) -> I would argue this should be in the raw peaks category as well (-> 3 levels)

What about prefiltering:
e.g. MS level? should this be an argument to prefilter the data?
what about mz and rt range or even IM range?

@jpfeuffer

Copy link
Copy Markdown
Contributor

Sure. Why not. Well maybe IM can be raw peak but it is also awkward if it is not there, although less of a problem with arrow. We could also do a schema change depending on if IM data is present.

@jpfeuffer

Copy link
Copy Markdown
Contributor

Note that pre filtering gives the impression that it can be nicely used to extract multiple areas by calling it multiple times, although there are better options to extract multiple regions.

@timosachsenberg

Copy link
Copy Markdown
Contributor

Deep Analysis: Arrow/Parquet Export Interface Design

Based on thorough analysis of the PR discussion and existing MS Parquet implementations, here's a comprehensive proposal for the Arrow export interface.

Existing Implementations Survey

Tool Format Row Structure Core Columns Precursor Handling IM Handling
ThermoRawFileParser mzParquet 1 row/peak scan, level, rt, mz, intensity Nullable columns FAIMS CV
Depthcharge Arrow/Parquet 1 row/spectrum scan_id, ms_level precursor_mz/charge Extensible
mzPeak Multi-Parquet 1 row/peak spectrum_index, mz, intensity Separate metadata file Optional
arcMS Parquet/HDF5 Tabular rt, mz, intensity Per-level tables HDMS^E support
Simple SQL (2025 paper) Parquet/SQLite 1 row/peak filename, scan_index, rt, mz, intensity Separate MS2 table N/A

Key Insights

  1. Long format (1 row per peak) is dominant - this is what Arrow/Parquet excel at
  2. Precursor info uses nullable columns (not separate tables) in modern implementations
  3. Ion mobility is treated as another peak-level dimension when present
  4. Spectrum index/ID is essential for grouping peaks back to spectra
  5. ThermoRawFileParser's schema is the most mature reference implementation

Proposed Schema

Based on community practice and the discussion between @timosachsenberg and @jpfeuffer:

Column Type Nullable Description
mz float64 No Peak m/z value
intensity float32 No Peak intensity
rt float64 No Retention time (seconds)
ion_mobility float64 Yes Ion mobility value (NaN if absent)
ms_level uint8 No MS level (1, 2, ...)
spectrum_index uint32 No Index into MSExperiment
native_id string No Native spectrum identifier
precursor_mz float64 Yes Precursor m/z (null for MS1)
precursor_charge int16 Yes Precursor charge (null/0 if unknown)
precursor_intensity float32 Yes Precursor intensity
isolation_lower float64 Yes Isolation window lower bound
isolation_upper float64 Yes Isolation window upper bound

Design Rationale

  • No separate export levels - Include all columns, use nullable types for optional data
  • Column filtering via columns parameter - User selects what they need
  • Nullable precursor columns - Null for MS1, populated for MS2+
  • Ion mobility always in schema - NaN when no IM data (consistent schema across files)
  • Matches ThermoRawFileParser - Interoperability with existing tooling

Proposed C++ Interface

struct OPENMS_DLLAPI ArrowExportConfig
{
  // === Filtering ===
  std::vector<UInt> ms_levels;       ///< Empty = all MS levels
  double min_rt = 0, max_rt = 0;     ///< RT range (0,0 = no filter)
  double min_mz = 0, max_mz = 0;     ///< m/z range (0,0 = no filter)

  // === Column Selection ===
  /// Columns to export. Empty = all available columns.
  std::vector<std::string> columns;
};

/// Export to Arrow Table (C++ API)
OPENMS_DLLAPI std::shared_ptr<arrow::Table> exportMSExperimentToArrow(
  const MSExperiment& exp,
  const ArrowExportConfig& config = ArrowExportConfig{});

/// Export via Arrow C Data Interface (for Python bindings - zero-copy)
OPENMS_DLLAPI bool exportMSExperimentToArrowCData(
  const MSExperiment& exp,
  const ArrowExportConfig& config,
  ArrowSchema* out_schema,
  ArrowArray* out_array);

/// Get available column names
OPENMS_DLLAPI std::vector<std::string> getArrowExportColumns(const MSExperiment& exp);

pyOpenMS Interface

def to_arrow(self,
             ms_levels=None,
             min_rt=0, max_rt=0,
             min_mz=0, max_mz=0,
             columns=None):
    """
    Export MSExperiment to Apache Arrow Table.
    
    One row per peak. Spectrum metadata is replicated for each peak.
    
    :param ms_levels: Filter by MS levels (None = all)
    :param min_rt/max_rt: RT range filter (0,0 = no filter)
    :param min_mz/max_mz: m/z range filter
    :param columns: Columns to include (None = all)
    :return: pyarrow.Table
    
    Example::
    
        # All data
        table = exp.to_arrow()
        
        # MS2 only, minimal columns
        table = exp.to_arrow(
            ms_levels=[2],
            columns=['mz', 'intensity', 'precursor_mz']
        )
        
        # Save to Parquet
        import pyarrow.parquet as pq
        pq.write_table(table, 'sample.parquet')
        
        # Query with DuckDB
        import duckdb
        duckdb.sql('SELECT * FROM table WHERE ms_level = 2')
    """

The Python binding uses the Arrow C Data Interface for zero-copy transfer from C++ to Python.


Summary

This design:

  • ✅ Aligns with existing MS Parquet implementations (ThermoRawFileParser, mzPeak)
  • ✅ Addresses @jpfeuffer's tiered export suggestion (via column selection)
  • ✅ Includes precursor info and ion mobility as requested by @timosachsenberg
  • ✅ Supports filtering by MS level, RT, and m/z ranges
  • ✅ Simple interface with sensible defaults
  • ✅ Zero-copy Python integration via Arrow C Data Interface
  • ✅ Can be conveniently wrapped in pyOpenMS

@timosachsenberg

Copy link
Copy Markdown
Contributor

Usage Examples

C++ Usage

#include <OpenMS/FORMAT/ArrowExport.h>
#include <OpenMS/FORMAT/MzMLFile.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <parquet/arrow/writer.h>

using namespace OpenMS;

// Load data
MSExperiment exp;
MzMLFile().load("sample.mzML", exp);

// Example 1: Full export (all columns, all spectra)
auto table = exportMSExperimentToArrow(exp);

// Example 2: MS2 spectra only
ArrowExportConfig config;
config.ms_levels = {2};
auto table = exportMSExperimentToArrow(exp, config);

// Example 3: RT-filtered export
ArrowExportConfig config;
config.min_rt = 100.0;
config.max_rt = 500.0;
auto table = exportMSExperimentToArrow(exp, config);

// Example 4: Minimal columns for performance
ArrowExportConfig config;
config.columns = {"mz", "intensity", "rt"};
auto table = exportMSExperimentToArrow(exp, config);

// Example 5: MS2 with precursor info only
ArrowExportConfig config;
config.ms_levels = {2};
config.columns = {"mz", "intensity", "spectrum_index", "precursor_mz", "precursor_charge"};
auto table = exportMSExperimentToArrow(exp, config);

// Example 6: Write to Parquet file
auto outfile = arrow::io::FileOutputStream::Open("output.parquet").ValueOrDie();
parquet::arrow::WriteTable(*table, arrow::default_memory_pool(), outfile, /*chunk_size=*/1000000);

Python Usage

import pyopenms as oms

# Load data
exp = oms.MSExperiment()
oms.MzMLFile().load("sample.mzML", exp)

# Example 1: Full export
table = exp.to_arrow()

# Example 2: MS2 only
table = exp.to_arrow(ms_levels=[2])

# Example 3: RT-filtered
table = exp.to_arrow(min_rt=100, max_rt=500)

# Example 4: Minimal columns
table = exp.to_arrow(columns=['mz', 'intensity', 'rt'])

# Example 5: MS2 precursor analysis
table = exp.to_arrow(
    ms_levels=[2],
    columns=['spectrum_index', 'mz', 'intensity', 'precursor_mz', 'precursor_charge']
)

# Example 6: Combined filters
table = exp.to_arrow(
    ms_levels=[1, 2],
    min_rt=60, max_rt=3600,
    min_mz=100, max_mz=2000,
    columns=['mz', 'intensity', 'rt', 'ms_level', 'ion_mobility']
)

Integration with Data Science Tools

# Convert to pandas
df = table.to_pandas()

# Convert to polars (zero-copy)
import polars as pl
df = pl.from_arrow(table)

# Save to Parquet
import pyarrow.parquet as pq
pq.write_table(table, 'sample.parquet')

# Query with DuckDB (zero-copy)
import duckdb
conn = duckdb.connect()
conn.register('ms_data', table)

# Find all MS2 spectra with precursor > 500 m/z
result = conn.sql('''
    SELECT DISTINCT spectrum_index, precursor_mz, precursor_charge
    FROM ms_data 
    WHERE ms_level = 2 AND precursor_mz > 500
    ORDER BY precursor_mz
''').fetchdf()

# Calculate TIC per spectrum
tic = conn.sql('''
    SELECT spectrum_index, rt, SUM(intensity) as tic
    FROM ms_data
    GROUP BY spectrum_index, rt
    ORDER BY rt
''').fetchdf()

# Extract ion chromatogram (XIC)
xic = conn.sql('''
    SELECT rt, SUM(intensity) as intensity
    FROM ms_data
    WHERE mz BETWEEN 500.0 AND 500.5 AND ms_level = 1
    GROUP BY rt
    ORDER BY rt
''').fetchdf()

Batch Processing

from pathlib import Path
import pyarrow.parquet as pq

# Convert multiple files to Parquet
for mzml_file in Path('data/').glob('*.mzML'):
    exp = oms.MSExperiment()
    oms.MzMLFile().load(str(mzml_file), exp)
    
    table = exp.to_arrow(columns=['mz', 'intensity', 'rt', 'ms_level', 'spectrum_index'])
    
    parquet_file = mzml_file.with_suffix('.parquet')
    pq.write_table(table, parquet_file, compression='zstd')
    
    print(f'{mzml_file.name}: {mzml_file.stat().st_size/1e6:.1f} MB -> {parquet_file.stat().st_size/1e6:.1f} MB')

@timosachsenberg

Copy link
Copy Markdown
Contributor

Chromatogram Support

Key Decision: Separate Tables

Spectra and chromatograms must be separate Arrow tables because:

  1. Different schemas (mz vs rt as position column)
  2. Different semantics (peaks at one time vs signal over time)
  3. Mixing would confuse downstream analysis tools
  4. Follows mzPeak precedent (separate spectra_data.parquet and chromatograms_data.parquet)

Note: ThermoRawFileParser Parquet export is spectrum-only.


Chromatogram Schema

Column Type Nullable Description
rt float64 No Retention time
intensity float32 No Signal intensity
chromatogram_index uint32 No Index into getChromatograms()
native_id string No Chromatogram identifier
chromatogram_type string No TIC, BPC, SRM, SIM, XIC, etc.
precursor_mz float64 Yes Q1 m/z (null for TIC/BPC)
precursor_charge int16 Yes Precursor charge
product_mz float64 Yes Q3 m/z (null for non-SRM)

Revised C++ Interface

struct OPENMS_DLLAPI ArrowExportConfig
{
  // Filtering
  std::vector<UInt> ms_levels;        ///< For spectra: filter by MS level
  double min_rt = 0, max_rt = 0;      ///< RT range filter
  double min_mz = 0, max_mz = 0;      ///< m/z range filter (spectra only)
  
  // Column selection
  std::vector<std::string> columns;   ///< Empty = all columns
};

// === Spectra Export ===
OPENMS_DLLAPI std::shared_ptr<arrow::Table> exportSpectraToArrow(
  const MSExperiment& exp,
  const ArrowExportConfig& config = ArrowExportConfig{});

OPENMS_DLLAPI bool exportSpectraToArrowCData(
  const MSExperiment& exp,
  const ArrowExportConfig& config,
  ArrowSchema* out_schema,
  ArrowArray* out_array);

OPENMS_DLLAPI std::vector<std::string> getSpectraArrowColumns(const MSExperiment& exp);

// === Chromatograms Export ===
OPENMS_DLLAPI std::shared_ptr<arrow::Table> exportChromatogramsToArrow(
  const MSExperiment& exp,
  const ArrowExportConfig& config = ArrowExportConfig{});

OPENMS_DLLAPI bool exportChromatogramsToArrowCData(
  const MSExperiment& exp,
  const ArrowExportConfig& config,
  ArrowSchema* out_schema,
  ArrowArray* out_array);

OPENMS_DLLAPI std::vector<std::string> getChromatogramsArrowColumns(const MSExperiment& exp);

Python API

# Spectra export (one row per peak)
spectra_table = exp.spectra_to_arrow(
    ms_levels=[1, 2],
    min_rt=60, max_rt=3600,
    columns=['mz', 'intensity', 'rt', 'ms_level', 'precursor_mz']
)

# Chromatograms export (one row per time point)  
chrom_table = exp.chromatograms_to_arrow(
    min_rt=60, max_rt=3600,
    columns=['rt', 'intensity', 'native_id', 'precursor_mz', 'product_mz']
)

# Save to Parquet
import pyarrow.parquet as pq
pq.write_table(spectra_table, 'sample_spectra.parquet')
pq.write_table(chrom_table, 'sample_chromatograms.parquet')

# Query SRM transitions with DuckDB
import duckdb
duckdb.sql('''
    SELECT native_id, precursor_mz, product_mz, MAX(intensity) as max_int
    FROM chrom_table
    WHERE chromatogram_type = "SELECTED_REACTION_MONITORING_CHROMATOGRAM"
    GROUP BY native_id, precursor_mz, product_mz
''')

Summary

Data Type Function Key Columns
Spectra exportSpectraToArrow() mz, intensity, rt, ms_level, precursor_*
Chromatograms exportChromatogramsToArrow() rt, intensity, chromatogram_type, precursor_mz, product_mz

Both share ArrowExportConfig for filtering and column selection.

@timosachsenberg

timosachsenberg commented Jan 3, 2026 •

Copy link
Copy Markdown
Contributor

Alternative: Single Function Design

Alternative approach using one function for both spectra and chromatograms.

Core Insight

Both data types share:

  • Same parent container (MSExperiment)
  • Similar structure (position + intensity + metadata)
  • Same filtering needs (RT range, column selection)

The difference is just what we're exporting, which can be a parameter.


C++ Interface

#pragma once

#include <OpenMS/config.h>

#ifdef WITH_PARQUET

#include <OpenMS/CONCEPT/Types.h>
#include <memory>
#include <vector>
#include <string>

namespace arrow { class Table; }
struct ArrowSchema;
struct ArrowArray;

namespace OpenMS
{
  class MSExperiment;

  /// What to export from MSExperiment
  enum class ArrowDataType { Spectra, Chromatograms };

  /// Configuration for Arrow export
  struct OPENMS_DLLAPI ArrowExportConfig
  {
    // === Filtering ===
    std::vector<UInt> ms_levels;       ///< Spectra only: filter by MS level
    double min_rt = 0, max_rt = 0;     ///< Both: RT range (0,0 = no filter)
    double min_mz = 0, max_mz = 0;     ///< Spectra only: m/z range
    
    // === Column Selection ===
    std::vector<std::string> columns;  ///< Empty = all type-appropriate columns
  };

  /**
    @brief Export MSExperiment data to Arrow Table
    
    @param exp The MSExperiment to export
    @param type What to export: Spectra (default) or Chromatograms
    @param config Export configuration (filtering, column selection)
    @return Arrow Table with one row per peak/point
  */
  OPENMS_DLLAPI std::shared_ptr<arrow::Table> exportToArrow(
    const MSExperiment& exp,
    ArrowDataType type = ArrowDataType::Spectra,
    const ArrowExportConfig& config = ArrowExportConfig{});

  /**
    @brief Export via Arrow C Data Interface (for Python bindings)
  */
  OPENMS_DLLAPI bool exportToArrowCData(
    const MSExperiment& exp,
    ArrowDataType type,
    const ArrowExportConfig& config,
    ArrowSchema* out_schema,
    ArrowArray* out_array);

  /**
    @brief Get available column names for given export type
  */
  OPENMS_DLLAPI std::vector<std::string> getArrowColumns(
    const MSExperiment& exp,
    ArrowDataType type = ArrowDataType::Spectra);

} // namespace OpenMS

#endif

Python API

def to_arrow(self, 
             data='spectra',
             ms_levels=None,
             min_rt=0, max_rt=0,
             min_mz=0, max_mz=0,
             columns=None):
    """
    Export MSExperiment data to Apache Arrow Table.
    
    :param data: 'spectra' (default) or 'chromatograms'
    :param ms_levels: Filter by MS levels (spectra only)
    :param min_rt/max_rt: RT range filter (both)
    :param min_mz/max_mz: m/z range filter (spectra only)
    :param columns: Columns to include (None = all)
    :return: pyarrow.Table
    """

def get_arrow_columns(self, data='spectra'):
    """
    Get available column names for export type.
    
    :param data: 'spectra' or 'chromatograms'
    :return: List of column names
    """

Usage Examples

import pyopenms as oms

exp = oms.MSExperiment()
oms.MzMLFile().load('sample.mzML', exp)

# === Spectra (default) ===
table = exp.to_arrow()
table = exp.to_arrow('spectra')

# MS2 only, RT filtered
table = exp.to_arrow('spectra', ms_levels=[2], min_rt=60, max_rt=3600)

# Minimal columns
table = exp.to_arrow('spectra', columns=['mz', 'intensity', 'rt'])

# === Chromatograms ===
table = exp.to_arrow('chromatograms')

# RT filtered
table = exp.to_arrow('chromatograms', min_rt=60, max_rt=3600)

# SRM analysis columns
table = exp.to_arrow('chromatograms', 
    columns=['rt', 'intensity', 'native_id', 'precursor_mz', 'product_mz'])

# === Column Discovery ===
exp.get_arrow_columns('spectra')
# ['mz', 'intensity', 'rt', 'ion_mobility', 'ms_level', 'spectrum_index', 
#  'native_id', 'precursor_mz', 'precursor_charge', ...]

exp.get_arrow_columns('chromatograms')
# ['rt', 'intensity', 'chromatogram_index', 'native_id', 'chromatogram_type',
#  'precursor_mz', 'precursor_charge', 'product_mz']

# === Export Both ===
spectra = exp.to_arrow('spectra')
chroms = exp.to_arrow('chromatograms')

import pyarrow.parquet as pq
pq.write_table(spectra, 'sample_spectra.parquet')
pq.write_table(chroms, 'sample_chromatograms.parquet')

C++ Usage

#include <OpenMS/FORMAT/ArrowExport.h>
#include <OpenMS/FORMAT/MzMLFile.h>

using namespace OpenMS;

MSExperiment exp;
MzMLFile().load("sample.mzML", exp);

// Spectra (default)
auto spectra = exportToArrow(exp);

// MS2 only
ArrowExportConfig config;
config.ms_levels = {2};
auto ms2 = exportToArrow(exp, ArrowDataType::Spectra, config);

// Chromatograms
auto chroms = exportToArrow(exp, ArrowDataType::Chromatograms);

// RT-filtered chromatograms
ArrowExportConfig chrom_config;
chrom_config.min_rt = 60;
chrom_config.max_rt = 3600;
auto filtered = exportToArrow(exp, ArrowDataType::Chromatograms, chrom_config);

Design Rationale

Aspect Solution
One function exportToArrow(exp, type, config)
Type-safe Enum ArrowDataType prevents invalid strings
Sensible default Spectra (the 90% use case)
Shared config Type-irrelevant options silently ignored
Single return One table, not dict/tuple
Clean Python exp.to_arrow('chromatograms')

Column Reference

Spectra Columns (data='spectra')

Column Type Nullable
mz float64 No
intensity float32 No
rt float64 No
ion_mobility float64 Yes
ms_level uint8 No
spectrum_index uint32 No
native_id string No
precursor_mz float64 Yes
precursor_charge int16 Yes
precursor_intensity float32 Yes
isolation_lower float64 Yes
isolation_upper float64 Yes

Chromatogram Columns (data='chromatograms')

Column Type Nullable
rt float64 No
intensity float32 No
chromatogram_index uint32 No
native_id string No
chromatogram_type string No
precursor_mz float64 Yes
precursor_charge int16 Yes
product_mz float64 Yes

@timosachsenberg

timosachsenberg commented Jan 3, 2026 •

Copy link
Copy Markdown
Contributor

Thoughts about the two possibilities? I kind of like the one function approach (especially in python)

@jpfeuffer

Copy link
Copy Markdown
Contributor

No big preference. I think due to the dynamic nature of the columns we can't do static typing anyway really.

@mobiusklein

Copy link
Copy Markdown

Since you're talking about Arrow tables in memory but looking at Parquet tables on disk for guidance, keep in mind that Parquet has several layers of compression while Arrow is stored in more-or-less native form in memory. This means that Parquet encourages repeated values and nullability for long-form tables, using row group ranges, page ranges, and partitioning. These layouts have few benefits for Arrow.

Consider the long form where each row is a peak with a repeated spectrum index vs each row is a spectrum with an index and a list of peaks. In the long form, the index is repeated physically unless you use a logical array type (dictionary, run-end encoded) to store that array. So if the index is 32 bit, you are wasting 4 bytes per peak, 25% of the memory allocated, or 40% if the index is 64 bit. If you instead use a list array for the m/z and intensities, you only store the index once, and add the cost of 2-4 32 bit integers per row for list offsets. List arrays' drawbacks are that there are few pre-existing compute kernels that can operate on them directly, a bigger issue in Python than in C++ though. Lists are harder to use in Parquet, cannot be indexed for row group/page pruning, and the aforementioned compression can make it a few repeated columns a non-issue.

The long form also has to make awkward decisions for representing the empty spectrum, a spectrum with zero peaks but the full complement of metadata. This might happen if you're representing post-processed spectra and you don't have a policy in place for dropping spectra with zero peaks. In this scenario, do you make the a single row with null in m/z and other peak-derived values? Or do you split the data?

For mzPeak, I chose to split the data because even with that compression, there is overhead to store all those repeated values, and it also handily sidesteps the empty spectrum problem.

@jpfeuffer

jpfeuffer commented Jan 4, 2026 •

Copy link
Copy Markdown
Contributor

Thanks a lot for your input!! I totally agree with everything and therefore was never a fan of long format in memory. It was contributed quite some time ago for numpy arrays to be used with pandas and I think it was better than no "native" exchange of data.
Personally, I would be glad if we'd change back to arrays but somehow people really like the long format because maybe it allows for easier SQL-like statements without nested list queries? And I think some plotting libraries prefer long formats (important for the numpy array export).
I guess our current stance is more on the side of "as easy as possible" despite performance drawbacks (for the python wrappers). Also considering that loading into a C++ datastructure first and then converting to Arrow is already negating a lot of efficiency (it gets interesting if we implement a streaming or on-disc-access loader for [indexed] mzml to arrow).
In the current design not only the index is repeated but every metadatum at the spectrum (rt, ms-level, spectrum_id_string, and many more). I was aware of Categorical encodings but I am not sure which drawbacks they have if you have 10000s of values.
One thing to consider is that users can decide not to export those columns and build a dict of metadata on their own if they wish to not repeat data.

I would still obviously vote for "semi"-wide/array or split form if that is an option @timosachsenberg.
In theory it shouldn't be hard to offer both types of formats even. We might have functions for long and wide for the numpy case already.

Good catch about empty spectra. Never thought about it. Clear contra against long format.

Last thing to consider might be serialization performance if you ever want to write it to a standard format as parquet for example. If we want to enable users to do that in the near future, it might be worthwhile to have a similar strategy as this format to avoid too many rearrangements. But I assume it will be negligible to actual processing time and memory requirements most of the time.

@timosachsenberg

Copy link
Copy Markdown
Contributor

thanks for the input. I have no strong opinion here but agree that we should be able to efficiently serialize to parquet and also have an efficient in memory representation.
As it seems it can't be achieved both with one layout so I would say we add an option to switch between long and (semi-)wide format?

For long, we basically already have a plan. how would it look for the wide format? everything as in the long format except for having columns with mz,int,IM lists? (which go into a single "cell")

@timosachsenberg

timosachsenberg commented Jan 5, 2026 •

Copy link
Copy Markdown
Contributor

Comprehensive Arrow Schema Type Recommendations

Based on research across OpenMS internals, mzPeak, AlphaTims, ProteoWizard, and Arrow best practices:

Per-Peak Data (Core Numeric Columns)

Column Recommended Type Rationale
m/z float64 Required for sub-ppm mass accuracy. OpenMS uses double. msconvert defaults to 64-bit. At m/z=1000, float32 gives only 0.1 ppm precision - insufficient for modern instruments.
intensity float32 OpenMS Peak1D::IntensityType = float. msconvert defaults to 32-bit. Dynamic range adequately covered.
ion mobility float32 OpenMS FloatDataArray = std::vector<float>. Instrument precision only 0.1-2%. mzPeak offers --ion-mobility-f32.

Per-Spectrum Metadata

Column Recommended Type Rationale
retention_time float32 RT precision ~6 sec RSD. At 3600s, float32 gives ~0.0003s precision. Could use float64 for OpenMS consistency, but float32 saves 50%.
ms_level uint8 or dictionary<int8, utf8> Only values 1, 2, 3 (rarely 4+). Dictionary encoding ideal for low cardinality. uint8 range 0-255 is ample.
polarity int8 or dictionary<int8, utf8> Only 3 values: UNKNOWN(0), POSITIVE(1), NEGATIVE(2). OpenMS IonSource::Polarity enum. Perfect for dictionary encoding with strings "+", "-", "?".
spectrum_index int32 600K+ spectra per PASEF run. int32 handles 2.1B spectra.
native_id (string) dictionary<int32, utf8> Spectrum identifiers often have patterns. Dictionary encoding reduces repetition.

Precursor Information (MS2+ spectra)

Column Recommended Type Rationale
precursor_mz float64 Same precision requirements as m/z array.
precursor_intensity float32 Same as intensity array.
precursor_charge int8 Typically 1-10. OpenMS stores as int. int8 range (-128 to 127) is sufficient.
isolation_window_lower float32 Relative offset, typically 0.5-2.0 Da. float32 sufficient.
isolation_window_upper float32 Same as above.
collision_energy float32 Typical values 20-60 eV. float32 has ample precision.
activation_method dictionary<int8, utf8> ~20 possible values (CID, HCD, ETD, etc.). OpenMS has 19 ActivationMethod enum values. Ideal for dictionary encoding.

Additional Metadata

Column Recommended Type Rationale
centroided bool Binary flag.
scan_window_lower_mz float32 Scan range bounds, float32 sufficient.
scan_window_upper_mz float32 Same.
base_peak_mz float64 Same precision as m/z.
base_peak_intensity float32 Same precision as intensity.
injection_time float32 Milliseconds, float32 sufficient.
filter_string dictionary<int32, utf8> Often repetitive across spectra, good for dictionary.

Dictionary Encoding Recommendations

For low-cardinality columns, Arrow dictionary encoding provides:

Best candidates for dictionary encoding:

  1. ms_level - 3-4 unique values
  2. polarity - 3 unique values
  3. activation_method - ~20 unique values
  4. filter_string - often repetitive
  5. native_id - may have patterns

Example Semi-Wide Schema

spectrum_metadata:
  spectrum_index:     int32
  native_id:          dictionary<int32, utf8>
  ms_level:           uint8  (or dictionary)
  polarity:           int8   (or dictionary)  
  rt:                 float32
  base_peak_mz:       float64
  base_peak_intensity: float32
  
precursor_info:  (nullable for MS1)
  precursor_mz:       float64
  precursor_charge:   int8
  precursor_intensity: float32
  isolation_window_lower: float32
  isolation_window_upper: float32
  collision_energy:   float32
  activation_method:  dictionary<int8, utf8>

peak_data:  (list arrays for semi-wide format)
  mz:                 list<float64>
  intensity:          list<float32>
  ion_mobility:       list<float32>  (nullable)

Sources

timosachsenberg and others added 2 commits January 5, 2026 21:02
Implements Apache Arrow export functionality for MSExperiment data,
enabling zero-copy data transfer to Python data science tools.

C++ implementation (requires WITH_PARQUET=ON):
- ArrowExport.h/cpp with exportSpectraToArrow() and exportChromatogramsToArrow()
- Long format (one row per peak) and semi-wide format (one row per spectrum)
- Filtering by MS level, RT range, m/z range
- Column selection and precursor/ion mobility options
- C Data Interface for zero-copy transfer to Python
- 17 unit tests in ArrowExport_test.cpp

pyOpenMS bindings:
- Unified MSExperiment.to_arrow() supporting spectra, chromatograms, or both
- get_arrow_columns() discovery method
- Zero-copy path via _arrow_zerocopy.pyx (when WITH_PARQUET enabled)
- Pure Python fallback with proper Arrow null handling
- Backward compatible long_format parameter (deprecated)
- 18 unit tests for Arrow export functionality

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Adds functions to export MSExperiment spectra and chromatograms directly
to Apache Parquet files with configurable compression options.

- Add ParquetWriteConfig struct with compression (NONE/SNAPPY/GZIP/LZ4/ZSTD)
- Add exportSpectraToParquet() and exportChromatogramsToParquet() functions
- Support configurable row group size, compression level, and statistics
- Add 7 unit tests for Parquet export functionality

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Fix all issues with AI Agents 🤖
In @src/openms/include/OpenMS/FORMAT/sources.cmake:
- Around line 118-124: There are two identical WITH_PARQUET blocks appending
ArrowExport.h to sources_list_h which creates a duplicate entry; remove the
redundant block so ArrowExport.h is appended only once (keep a single if
(WITH_PARQUET) list(APPEND sources_list_h ArrowExport.h) guard) or consolidate
into one guarded append ensuring symbols ArrowExport.h, sources_list_h and the
WITH_PARQUET check are used exactly once.

In @src/openms/source/FORMAT/ArrowExport.cpp:
- Around line 981-986: The chromatogram long-format Finish() calls
(rt_builder.Finish, intensity_builder.Finish, chrom_index_builder.Finish,
native_id_builder.Finish, precursor_mz_builder.Finish,
product_mz_builder.Finish) currently return nullptr on failure without logging;
update each failure branch to log the Arrow status error before returning (match
the spectra export pattern), e.g. call the same logging macro/function used
elsewhere in this file (e.g. LOG_ERROR or processLogger) and include the status
message/details (status.ToString() or equivalent) and context (which
builder/field failed) prior to returning nullptr so failures are visible.
🧹 Nitpick comments (8)
src/pyOpenMS/tests/unittests/test_dataframe_columns.py (1)

826-841: Consider using pytest.xfail or a cleaner skip pattern.

The current try/except pattern may hide unexpected failures if the error message changes. Consider using pytest.mark.xfail with a condition or checking the experiment state before calling to_arrow().

🔎 Alternative using xfail marker
+    @pytest.mark.xfail(reason="Empty experiment handling requires rebuild with fixed addon", strict=False)
     def test_to_arrow_empty_experiment(self):
         """Test to_arrow() with empty experiment."""
         pytest.importorskip('pyarrow')
         import pyarrow as pa

         exp = pyopenms.MSExperiment()
-        # Empty experiments require a fix to handle getMinRT() on empty ranges
-        # The fix is in MSExperiment.pyx addon; after rebuild this will work
-        try:
-            table = exp.to_arrow(data='spectra')
-            assert isinstance(table, pa.Table)
-            assert table.num_rows == 0
-        except RuntimeError as e:
-            if "Empty or uninitalized range" in str(e):
-                pytest.skip("Empty experiment handling requires rebuild with fixed addon")
+        table = exp.to_arrow(data='spectra')
+        assert isinstance(table, pa.Table)
+        assert table.num_rows == 0
src/tests/class_tests/openms/source/ArrowExport_test.cpp (1)

441-458: Consider using NEW_TMP_FILE macro for automatic cleanup.

The manual temp file management using File::getTempDirectory() and File::remove() works but doesn't follow the coding guideline to use NEW_TMP_FILE(filename) macro. If tests fail before cleanup, temp files will remain.

🔎 Proposed fix using NEW_TMP_FILE
 START_SECTION(exportSpectraToParquet - basic export)
 {
   MSExperiment exp = createTestExperiment();

-  // Export to temp file
-  String filename = File::getTempDirectory() + "/test_spectra.parquet";
+  // Export to temp file with automatic cleanup
+  String filename;
+  NEW_TMP_FILE(filename);

   bool success = exportSpectraToParquet(exp, filename);
   TEST_EQUAL(success, true)

   // Verify file was created
   TEST_EQUAL(File::exists(filename), true)
   TEST_EQUAL(File::empty(filename), false)
-
-  // Clean up
-  File::remove(filename);
 }
 END_SECTION

Note: Apply similar changes to other Parquet test sections (lines 460-480, 483-501, 504-518, 521-536, 539-557).

src/pyOpenMS/pxds/ArrowExport.pxd (1)

48-65: Consider adding copy constructor declarations.

Per coding guidelines, copy constructors should be declared in .pxd files even when the C++ class may have deleted copy constructors. This is a pyOpenMS/Cython convention for proper wrapper generation.

🔎 Proposed addition of copy constructors
     cdef cppclass ArrowSpectraExportConfig:
         ArrowSpectraExportConfig() except + nogil
+        ArrowSpectraExportConfig(ArrowSpectraExportConfig&) except + nogil
         ArrowExportFormat format
         libcpp_vector[unsigned int] ms_levels
         double min_rt
         double max_rt
         double min_mz
         double max_mz
         libcpp_vector[libcpp_string] columns
         bool include_precursor_info
         bool include_ion_mobility

     cdef cppclass ArrowChromatogramExportConfig:
         ArrowChromatogramExportConfig() except + nogil
+        ArrowChromatogramExportConfig(ArrowChromatogramExportConfig&) except + nogil
         ArrowExportFormat format
         double min_rt
         double max_rt
         libcpp_vector[libcpp_string] columns

Based on learnings, this is a standard pyOpenMS convention.

src/pyOpenMS/addons/MSExperiment.pyx (3)

236-258: Column order inconsistency between Python fallback and C++ implementation for semi-wide format.

The Python implementation uses the same column order for both long and semi-wide formats, but the C++ implementation uses a different order for semi-wide (starts with spectrum_index, rt, ms_level, native_id, mz, intensity). Since the zero-copy path delegates to C++, users may see different column orders depending on whether WITH_PARQUET is enabled.

Consider aligning the column order with the C++ implementation for consistency:

🔎 Suggested fix
-        spectra_long_cols = ['mz', 'intensity', 'rt']
-        spectra_semi_wide_cols = ['mz', 'intensity', 'rt']
+        spectra_long_cols = ['mz', 'intensity', 'rt']
+        spectra_semi_wide_cols = ['spectrum_index', 'rt', 'ms_level', 'native_id', 'mz', 'intensity']

         # ion_mobility comes after rt in C++ (before spectrum_index)
         if include_ion_mobility:
             spectra_long_cols.append('ion_mobility')
-            spectra_semi_wide_cols.append('ion_mobility')
+            # For semi_wide, ion_mobility comes after intensity
+            pass  # handled below

-        spectra_long_cols.extend(['spectrum_index', 'ms_level', 'native_id'])
-        spectra_semi_wide_cols.extend(['spectrum_index', 'ms_level', 'native_id'])
+        spectra_long_cols.extend(['spectrum_index', 'ms_level', 'native_id'])
+        
+        if include_ion_mobility:
+            spectra_semi_wide_cols.append('ion_mobility')

569-573: Simplify redundant ms_levels handling.

Both branches (if ms_levels is None and elif not ms_levels) perform the same action. This can be simplified.

🔎 Suggested fix
         # Handle ms_levels default
-        if ms_levels is None:
-            ms_levels = self.getMSLevels() if num_spectra > 0 else []
-        elif not ms_levels:
+        if not ms_levels:  # Handles both None and empty list
             ms_levels = self.getMSLevels() if num_spectra > 0 else []

677-691: Potential issue with ion mobility data indexing after m/z filtering.

When applying the m/z filter mask to ion mobility data, the code checks if len(im_data) == original_len. However, original_len is set from len(mzs) before filtering, which should be correct. The issue is that when iterating by index using mz_mask[i], the logic assumes the IM data indices correspond 1:1 with peak indices, which is correct.

However, the fallback to None values when lengths don't match (line 688) silently loses data. Consider logging a warning when this mismatch occurs, as it may indicate data corruption.

🔎 Suggested improvement
                         if mz_mask is not None and len(im_data) == original_len:
                             im_data = [im_data[i] for i in range(len(mz_mask)) if mz_mask[i]]
                         if len(im_data) == n_peaks:
                             all_ion_mobility.extend(im_data)
                         else:
+                            import warnings
+                            warnings.warn(
+                                f"Ion mobility data length ({len(im_data)}) doesn't match "
+                                f"peak count ({n_peaks}) for spectrum {spec_idx}",
+                                RuntimeWarning
+                            )
                             all_ion_mobility.extend([None] * n_peaks)
src/openms/source/FORMAT/ArrowExport.cpp (2)

448-741: Consider extracting common schema-building logic to reduce complexity.

Static analysis flags this as a "Very Complex Method" (similar to buildLongFormatTable and exportChromatogramsToArrow). While the implementation is correct and well-structured, consider extracting the schema-building phase (lines 637-737) into a helper function shared between long and semi-wide builders to reduce duplication.

This is a refactoring suggestion for maintainability rather than a correctness issue.


1130-1131: Consider using ValueUnsafe() instead of ValueOrDie() after explicit status check.

Since you've already verified batch_result.ok() on line 1124, using ValueUnsafe() would be more explicit that this is a safe dereference rather than relying on ValueOrDie() which implies potential exception.

This is a minor style suggestion; the current code is correct.

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 484ab7e and b310d58.

📒 Files selected for processing (10)
  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
  • src/openms/include/OpenMS/FORMAT/sources.cmake
  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/pyOpenMS/CMakeLists.txt
  • src/pyOpenMS/addons/MSExperiment.pyx
  • src/pyOpenMS/pxds/ArrowExport.pxd
  • src/pyOpenMS/pyopenms/_arrow_zerocopy.pyx
  • src/pyOpenMS/tests/unittests/test_dataframe_columns.py
  • src/tests/class_tests/openms/executables.cmake
  • src/tests/class_tests/openms/source/ArrowExport_test.cpp
🧰 Additional context used
📓 Path-based instructions (21)
**/*.{h,hpp,hxx,cpp,cc,cxx,py,pyx,pxd,cmake}

📄 CodeRabbit inference engine (AGENTS.md)

Use Unix line endings (LF) in all code files

Files:

  • src/tests/class_tests/openms/executables.cmake
  • src/tests/class_tests/openms/source/ArrowExport_test.cpp
  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/pyOpenMS/tests/unittests/test_dataframe_columns.py
  • src/pyOpenMS/addons/MSExperiment.pyx
  • src/openms/include/OpenMS/FORMAT/sources.cmake
  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
  • src/pyOpenMS/pxds/ArrowExport.pxd
  • src/pyOpenMS/pyopenms/_arrow_zerocopy.pyx
src/tests/class_tests/**/executables.cmake

📄 CodeRabbit inference engine (AGENTS.md)

Register new C++ unit test files in src/tests/class_tests/openms/executables.cmake or equivalent

Files:

  • src/tests/class_tests/openms/executables.cmake
src/tests/class_tests/**/*

📄 CodeRabbit inference engine (AGENTS.md)

Keep test data small and use whitelisting for unstable lines in C++ unit test comparisons

Files:

  • src/tests/class_tests/openms/executables.cmake
  • src/tests/class_tests/openms/source/ArrowExport_test.cpp
**/{executables.cmake,CMakeLists.txt}

📄 CodeRabbit inference engine (AGENTS.md)

Register C++ source files in CMake configuration (executables.cmake or CMakeLists.txt)

Files:

  • src/tests/class_tests/openms/executables.cmake
  • src/pyOpenMS/CMakeLists.txt
src/tests/class_tests/openms/**/*.cpp

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Write unit tests for new functionality

Files:

  • src/tests/class_tests/openms/source/ArrowExport_test.cpp
**/*.{cpp,cc,cxx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{cpp,cc,cxx}: Use OpenMS logging macros instead of std::cout/std::cerr directly in C++ code
Use \n instead of std::endl for performance in C++ code
Use using namespace and using std::... declarations only in C++ .cpp files, not in headers

Files:

  • src/tests/class_tests/openms/source/ArrowExport_test.cpp
  • src/openms/source/FORMAT/ArrowExport.cpp
**/*.{h,hpp,hxx,cpp,cc,cxx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{h,hpp,hxx,cpp,cc,cxx}: Use 2-space indentation in C++ headers and implementation files, not tabs
Place opening and closing braces on their own lines, aligned, in C++ code
Include a space after keywords (if, for, while) in C++ code
Always use braces in C++ code, even for single-line blocks (trivial one-liners may stay single-line)
Use PascalCase for C++ class, type, and namespace names
Use lowerCamelCase for C++ method names
Use snake_case for C++ variable names
Use UPPER_SNAKE_CASE for C++ enum and macro names
Class name must match file name, with one class per file in C++
Always pair C++ .h header files with corresponding .cpp implementation files
Method parameters in C++ should use lower_case with underscores and document ranges/units
Use lowercase file extensions for file names, except for ML, XML, and mzData in C++
Use OpenMS primitive types from OpenMS/CONCEPT/Types.h instead of standard C++ types
Derive C++ exceptions from Exception::Base and throw with file/line/OPENMS_PRETTY_FUNCTION
Catch C++ exceptions by reference, not by value
Use // style comments, not /* */ for inline comments in C++ code
Include a $Maintainer:$ marker in the file preamble of every C++ file
Use .clang-format configuration from repository root for C++ code formatting
Use OpenMS logging macros and OpenMS::LogStream instead of direct std::cout/std::cerr in C++ code
Avoid pointers in C++ code; prefer references instead
Use Size/SignedSize OpenMS types for STL .size() values instead of std::size_t or int
Prefer OpenMS::String for numeric formatting and parsing over standard C++ methods

Files:

  • src/tests/class_tests/openms/source/ArrowExport_test.cpp
  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
**/*.{h,hpp,hxx,cpp,cc,cxx,py,pyx}

📄 CodeRabbit inference engine (AGENTS.md)

Write code comments in plain English describing the next few lines of code, comprising at least ~5% of code

Files:

  • src/tests/class_tests/openms/source/ArrowExport_test.cpp
  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/pyOpenMS/tests/unittests/test_dataframe_columns.py
  • src/pyOpenMS/addons/MSExperiment.pyx
  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
  • src/pyOpenMS/pyopenms/_arrow_zerocopy.pyx
src/tests/class_tests/**/*_test.{cpp,cc,cxx}

📄 CodeRabbit inference engine (AGENTS.md)

src/tests/class_tests/**/*_test.{cpp,cc,cxx}: Unit tests in C++ must use START_TEST, START_SECTION, and END_SECTION macros from OpenMS/CONCEPT/ClassTest.h
C++ unit test files should be named with _test suffix and located in src/tests/class_tests/
Use NEW_TMP_FILE(filename) macro for each output file in C++ unit tests to avoid side effects
Use FuzzyDiff for numeric comparisons in C++ unit tests instead of exact equality checks
Wrap template methods with 2+ arguments in parentheses inside START_SECTION macros in C++ tests

Files:

  • src/tests/class_tests/openms/source/ArrowExport_test.cpp
src/openms/**/*.{cpp,h,hpp,cc,cxx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

src/openms/**/*.{cpp,h,hpp,cc,cxx}: Follow the existing C++ coding conventions in the codebase
Use the established naming patterns for classes, methods, and variables
Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)
Follow the established error handling patterns
Utilize OpenMS logging mechanisms
Be mindful of memory usage when processing large datasets
Consider algorithmic complexity for data processing operations
Use appropriate OpenMS containers and algorithms

Files:

  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
src/pyOpenMS/tests/**/*.py

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Write pyOpenMS tests for new Python bindings

Files:

  • src/pyOpenMS/tests/unittests/test_dataframe_columns.py
**/*.{py,pyx,pxd}

📄 CodeRabbit inference engine (AGENTS.md)

Use 4-space indentation in Python and Cython files per PEP 8, not tabs

Files:

  • src/pyOpenMS/tests/unittests/test_dataframe_columns.py
  • src/pyOpenMS/addons/MSExperiment.pyx
  • src/pyOpenMS/pxds/ArrowExport.pxd
  • src/pyOpenMS/pyopenms/_arrow_zerocopy.pyx
src/pyOpenMS/**/*.{py,pyx,pxd}

📄 CodeRabbit inference engine (AGENTS.md)

Use snake_case for Python-facing names and DataFrame column names in pyOpenMS

Files:

  • src/pyOpenMS/tests/unittests/test_dataframe_columns.py
  • src/pyOpenMS/addons/MSExperiment.pyx
  • src/pyOpenMS/pxds/ArrowExport.pxd
  • src/pyOpenMS/pyopenms/_arrow_zerocopy.pyx
src/pyOpenMS/**/*.{py,pyx}

📄 CodeRabbit inference engine (AGENTS.md)

Do not call .decode() on autowrap string returns in pyOpenMS; autowrap returns Python strings

Files:

  • src/pyOpenMS/tests/unittests/test_dataframe_columns.py
  • src/pyOpenMS/addons/MSExperiment.pyx
  • src/pyOpenMS/pyopenms/_arrow_zerocopy.pyx
src/pyOpenMS/**/*.{pyx,pxd}

📄 CodeRabbit inference engine (AGENTS.md)

Avoid custom __init__ in pyOpenMS unless required; it overrides autowrap dispatchers

Files:

  • src/pyOpenMS/addons/MSExperiment.pyx
  • src/pyOpenMS/pxds/ArrowExport.pxd
  • src/pyOpenMS/pyopenms/_arrow_zerocopy.pyx
src/pyOpenMS/addons/*.pyx

📄 CodeRabbit inference engine (AGENTS.md)

src/pyOpenMS/addons/*.pyx: Implement get_data_dict() in pyOpenMS addon to return numpy arrays
Keep pyOpenMS addon code minimal; avoid redundant aliases and over-engineering

Files:

  • src/pyOpenMS/addons/MSExperiment.pyx
src/pyOpenMS/**/*.pyx

📄 CodeRabbit inference engine (AGENTS.md)

src/pyOpenMS/**/*.pyx: Avoid cdef for autowrap string returns in pyOpenMS Cython code
Avoid cdef typed variables for autowrap return values inside def methods in pyOpenMS
Use strict indentation for # wrap-doc: comments in pyOpenMS Cython code

Files:

  • src/pyOpenMS/addons/MSExperiment.pyx
  • src/pyOpenMS/pyopenms/_arrow_zerocopy.pyx
src/openms/include/OpenMS/**/*.h

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Add Doxygen comments for new public methods and classes

Files:

  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
**/*.{h,hpp,hxx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{h,hpp,hxx}: Never add using namespace or using std::... declarations in C++ header files
Use trailing underscore for C++ private and protected member variable names
Prefer enum class over unscoped enums in C++ code
Use _impl.h suffix only when necessary for template implementations; .h files must not include _impl.h
Never use using namespace or using std::... declarations in C++ header files
Follow Rule-of-0 or Rule-of-6 for C++ class design (special member functions)
Implement get/set accessor pairs for C++ protected and private members instead of direct access
Never use reference getters for primitive types in C++ accessor methods
Document possible C++ exceptions in Doxygen comments with @throws or @exception tags
Include OPENMS_DLLAPI export macro on all non-template exported C++ classes, structs, functions, and variables
Do not include OPENMS_DLLAPI export macro on C++ template classes and functions
Include OPENMS_DLLAPI in friend operator declarations in C++ classes
Prefer forward declarations in C++ headers; include only base class headers, non-pointer members, and templates
Doxygen documentation in C++ headers must use /** */ block comments with @ tags (not \ backslash)
@brief is required in C++ Doxygen comments and must not be auto-generated from first line
Include a file header with Copyright, SPDX license, Maintainer, and Authors in every C++ header file
Use [in], [out], or [in,out] parameter direction tags in C++ Doxygen method documentation for all parameters
Use @return tag in C++ Doxygen comments to document return values
Use @throws or @exception tags in C++ Doxygen comments to document exceptions
Use @ingroup tag in C++ class Doxygen comments for category grouping (e.g., Analysis_ID)
Group C++ constructors and destructors together with @name Doxygen tag
Use @note tag in C++ Doxygen comments for important usage notes
Use @warning tag in C++ Doxygen comments for usage warnings
Use @todo ...

Files:

  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
src/pyOpenMS/pxds/*.pxd

📄 CodeRabbit inference engine (AGENTS.md)

src/pyOpenMS/pxds/*.pxd: Always declare default and copy constructors in pyOpenMS .pxd declaration files
Use cimport instead of Python import for Cython declarations in pyOpenMS .pxd files
Use cdef cppclass ClassName: without base for non-inheriting classes in pyOpenMS .pxd files
Keep .pxd file signatures in sync with C++ APIs; update or remove wrap-ignore when wrapping changes
Do not add Python-only methods to pyOpenMS .pxd files; use addons or _dataframes.py wrappers

Files:

  • src/pyOpenMS/pxds/ArrowExport.pxd
**/CMakeLists.txt

📄 CodeRabbit inference engine (AGENTS.md)

CMake configuration files must list all dependencies and build targets

Files:

  • src/pyOpenMS/CMakeLists.txt
🧠 Learnings (44)
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Applies to src/tests/class_tests/**/executables.cmake : Register new C++ unit test files in `src/tests/class_tests/openms/executables.cmake` or equivalent

Applied to files:

  • src/tests/class_tests/openms/executables.cmake
  • src/tests/class_tests/openms/source/ArrowExport_test.cpp
  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/pyOpenMS/CMakeLists.txt
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/tests/class_tests/openms/**/*.cpp : Write unit tests for new functionality

Applied to files:

  • src/tests/class_tests/openms/executables.cmake
  • src/tests/class_tests/openms/source/ArrowExport_test.cpp
  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/pyOpenMS/tests/unittests/test_dataframe_columns.py
📚 Learning: 2025-09-03T12:58:20.032Z
Learnt from: timosachsenberg
Repo: OpenMS/OpenMS PR: 8177
File: src/tests/topp/CMakeLists.txt:1857-1865
Timestamp: 2025-09-03T12:58:20.032Z
Learning: OpenMS tests: When adding new TOPP tests in src/tests/topp/CMakeLists.txt that compare outputs via FuzzyDiff, always add set_tests_properties("<tool>_<n>_out<m>" PROPERTIES DEPENDS "<tool>_<n>") to avoid flakiness under parallel CTest runs.

Applied to files:

  • src/tests/class_tests/openms/executables.cmake
  • src/tests/class_tests/openms/source/ArrowExport_test.cpp
  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/pyOpenMS/CMakeLists.txt
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Applies to src/tests/topp/CMakeLists.txt : Add TOPP tool integration tests in `src/tests/topp/CMakeLists.txt` for new tools

Applied to files:

  • src/tests/class_tests/openms/executables.cmake
  • src/tests/class_tests/openms/source/ArrowExport_test.cpp
  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/pyOpenMS/CMakeLists.txt
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/tests/class_tests/openms/*Test.cpp : Follow naming convention: `ClassNameTest.cpp` for `ClassName`

Applied to files:

  • src/tests/class_tests/openms/executables.cmake
  • src/tests/class_tests/openms/source/ArrowExport_test.cpp
  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Applies to src/topp/!(executables.cmake) : Add new C++ TOPP tool source files to `src/topp/executables.cmake` and register in `ToolHandler.cpp`

Applied to files:

  • src/tests/class_tests/openms/executables.cmake
  • src/openms/include/OpenMS/FORMAT/sources.cmake
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Applies to src/tests/class_tests/**/*_test.{cpp,cc,cxx} : Unit tests in C++ must use `START_TEST`, `START_SECTION`, and `END_SECTION` macros from `OpenMS/CONCEPT/ClassTest.h`

Applied to files:

  • src/tests/class_tests/openms/executables.cmake
  • src/tests/class_tests/openms/source/ArrowExport_test.cpp
  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Applies to src/tests/class_tests/**/*_test.{cpp,cc,cxx} : Use `NEW_TMP_FILE(filename)` macro for each output file in C++ unit tests to avoid side effects

Applied to files:

  • src/tests/class_tests/openms/executables.cmake
  • src/tests/class_tests/openms/source/ArrowExport_test.cpp
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Applies to src/tests/class_tests/**/* : Keep test data small and use whitelisting for unstable lines in C++ unit test comparisons

Applied to files:

  • src/tests/class_tests/openms/executables.cmake
  • src/tests/class_tests/openms/source/ArrowExport_test.cpp
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Applies to **/*.{h,hpp,hxx} : Include `OPENMS_DLLAPI` export macro on all non-template exported C++ classes, structs, functions, and variables

Applied to files:

  • src/tests/class_tests/openms/executables.cmake
  • src/openms/include/OpenMS/FORMAT/sources.cmake
  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)

Applied to files:

  • src/tests/class_tests/openms/source/ArrowExport_test.cpp
  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/openms/include/OpenMS/FORMAT/sources.cmake
  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
  • src/pyOpenMS/pxds/ArrowExport.pxd
  • src/pyOpenMS/pyopenms/_arrow_zerocopy.pyx
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/pyOpenMS/tests/**/*.py : Write pyOpenMS tests for new Python bindings

Applied to files:

  • src/tests/class_tests/openms/source/ArrowExport_test.cpp
  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/pyOpenMS/tests/unittests/test_dataframe_columns.py
  • src/pyOpenMS/CMakeLists.txt
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/include/OpenMS/**/*.h : Add Doxygen comments for new public methods and classes

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/openms/include/OpenMS/FORMAT/sources.cmake
  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Ensure existing tests pass before suggesting changes

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Applies to src/tests/class_tests/**/*_test.{cpp,cc,cxx} : C++ unit test files should be named with `_test` suffix and located in `src/tests/class_tests/`

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Follow the established error handling patterns

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Utilize OpenMS logging mechanisms

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Applies to **/*.{cpp,cc,cxx} : Use OpenMS logging macros instead of `std::cout`/`std::cerr` directly in C++ code

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Applies to **/*.{h,hpp,hxx,cpp,cc,cxx} : Use OpenMS logging macros and `OpenMS::LogStream` instead of direct `std::cout`/`std::cerr` in C++ code

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2026-01-04T21:35:37.785Z
Learnt from: timosachsenberg
Repo: OpenMS/OpenMS PR: 8588
File: src/pyOpenMS/tests/unittests/test_TargetedQuantitation.py:1-456
Timestamp: 2026-01-04T21:35:37.785Z
Learning: For Python files in the repository, follow PEP 8: use 4-space indentation, avoid tabs, and ensure Unix LF line endings. The 2-space indentation and Unix line endings guideline applies to C/Cython in their respective languages; Python files should adhere to Python style (PEP 8) regardless of other language rules.

Applied to files:

  • src/pyOpenMS/tests/unittests/test_dataframe_columns.py
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Applies to src/pyOpenMS/pxds/*.pxd : Do not add Python-only methods to pyOpenMS `.pxd` files; use addons or `_dataframes.py` wrappers

Applied to files:

  • src/pyOpenMS/addons/MSExperiment.pyx
  • src/pyOpenMS/pxds/ArrowExport.pxd
  • src/pyOpenMS/CMakeLists.txt
  • src/pyOpenMS/pyopenms/_arrow_zerocopy.pyx
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Applies to src/pyOpenMS/addons/*.pyx : Implement `get_data_dict()` in pyOpenMS addon to return numpy arrays

Applied to files:

  • src/pyOpenMS/addons/MSExperiment.pyx
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Applies to src/pyOpenMS/addons/*.pyx : Keep pyOpenMS addon code minimal; avoid redundant aliases and over-engineering

Applied to files:

  • src/pyOpenMS/addons/MSExperiment.pyx
  • src/pyOpenMS/pxds/ArrowExport.pxd
  • src/pyOpenMS/pyopenms/_arrow_zerocopy.pyx
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Applies to **/*.{h,hpp,hxx} : Include `OPENMS_DLLAPI` in friend operator declarations in C++ classes

Applied to files:

  • src/openms/include/OpenMS/FORMAT/sources.cmake
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Applies to **/*.{h,hpp,hxx} : Do not include `OPENMS_DLLAPI` export macro on C++ template classes and functions

Applied to files:

  • src/openms/include/OpenMS/FORMAT/sources.cmake
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Applies to **/*.{h,hpp,hxx,cpp,cc,cxx} : Include a `$Maintainer:$` marker in the file preamble of every C++ file

Applied to files:

  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Applies to **/*.{h,hpp,hxx} : Include a file header with Copyright, SPDX license, Maintainer, and Authors in every C++ header file

Applied to files:

  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Follow the existing C++ coding conventions in the codebase

Applied to files:

  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
📚 Learning: 2025-06-16T15:48:09.667Z
Learnt from: FreezB11
Repo: OpenMS/OpenMS PR: 7969
File: src/pyOpenMS/pxds/TMTThirtyTwoPlexQuantitationMethod.pxd:4-4
Timestamp: 2025-06-16T15:48:09.667Z
Learning: In OpenMS .pxd files, the established pattern for extern from statements is to include angle brackets inside the string literal, like `cdef extern from "<OpenMS/PATH/TO/FILE.h>" namespace "OpenMS":`. This is consistent across all existing quantitation method .pxd files and other .pxd files in the OpenMS codebase.

Applied to files:

  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
  • src/pyOpenMS/pxds/ArrowExport.pxd
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Applies to CHANGELOG* : Update `CHANGELOG` file with changes when making contributions to OpenMS

Applied to files:

  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Applies to **/*.{h,hpp,hxx} : Use `todo` tag in C++ Doxygen comments with assignee name: `todo JohnDoe fix this`

Applied to files:

  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/pyOpenMS/**/*.h : Add Doxygen comments for new public methods and classes in pyOpenMS bindings

Applied to files:

  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
  • src/pyOpenMS/pxds/ArrowExport.pxd
  • src/pyOpenMS/CMakeLists.txt
  • src/pyOpenMS/pyopenms/_arrow_zerocopy.pyx
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Applies to **/*.{h,hpp,hxx} : `brief` is required in C++ Doxygen comments and must not be auto-generated from first line

Applied to files:

  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
📚 Learning: 2025-10-21T13:02:16.431Z
Learnt from: timosachsenberg
Repo: OpenMS/OpenMS PR: 8318
File: src/openms/include/OpenMS/ML/CLUSTERING/HashGrid.h:466-480
Timestamp: 2025-10-21T13:02:16.431Z
Learning: In OpenMS, when making internal methods public (e.g., in HashGrid.h), remove XXX/TODO comments about implementation details rather than documenting them in the public API documentation.

Applied to files:

  • src/openms/include/OpenMS/FORMAT/ArrowExport.h
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Applies to src/pyOpenMS/pxds/*.pxd : Use `cimport` instead of Python `import` for Cython declarations in pyOpenMS `.pxd` files

Applied to files:

  • src/pyOpenMS/pxds/ArrowExport.pxd
  • src/pyOpenMS/CMakeLists.txt
  • src/pyOpenMS/pyopenms/_arrow_zerocopy.pyx
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Applies to src/pyOpenMS/pxds/*.pxd : Keep `.pxd` file signatures in sync with C++ APIs; update or remove `wrap-ignore` when wrapping changes

Applied to files:

  • src/pyOpenMS/pxds/ArrowExport.pxd
  • src/pyOpenMS/CMakeLists.txt
  • src/pyOpenMS/pyopenms/_arrow_zerocopy.pyx
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Applies to src/pyOpenMS/pxds/*.pxd : Always declare default and copy constructors in pyOpenMS `.pxd` declaration files

Applied to files:

  • src/pyOpenMS/pxds/ArrowExport.pxd
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Applies to src/pyOpenMS/pxds/*.pxd : Use `cdef cppclass ClassName:` without base for non-inheriting classes in pyOpenMS `.pxd` files

Applied to files:

  • src/pyOpenMS/pxds/ArrowExport.pxd
📚 Learning: 2025-11-18T20:08:08.900Z
Learnt from: timosachsenberg
Repo: OpenMS/OpenMS PR: 8374
File: src/pyOpenMS/pxds/SimpleSVM.pxd:0-0
Timestamp: 2025-11-18T20:08:08.900Z
Learning: In pyOpenMS .pxd files, copy constructors should be declared for wrapped C++ classes (e.g., `ClassName(ClassName&) except + nogil`) even when the C++ class has a deleted copy constructor. This is a standard pyOpenMS/Cython convention required for proper wrapper generation and Python object semantics.

Applied to files:

  • src/pyOpenMS/pxds/ArrowExport.pxd
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Applies to src/pyOpenMS/**/*.pyx : Avoid `cdef` typed variables for autowrap return values inside `def` methods in pyOpenMS

Applied to files:

  • src/pyOpenMS/pxds/ArrowExport.pxd
  • src/pyOpenMS/pyopenms/_arrow_zerocopy.pyx
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Update pyOpenMS bindings when making C++ API changes

Applied to files:

  • src/pyOpenMS/CMakeLists.txt
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Regenerate pyOpenMS after addon changes by removing `.cpp_extension_generated` and rebuilding

Applied to files:

  • src/pyOpenMS/CMakeLists.txt
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Set `OPENMS_CONTRIB_LIBS` and `CMAKE_PREFIX_PATH` when configuring OpenMS with contrib or system dependencies

Applied to files:

  • src/pyOpenMS/CMakeLists.txt
📚 Learning: 2026-01-05T17:45:38.954Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-05T17:45:38.954Z
Learning: Configure OpenMS with `cmake -DCMAKE_BUILD_TYPE=Debug ../OpenMS` from out-of-tree `OpenMS-build/` directory

Applied to files:

  • src/pyOpenMS/CMakeLists.txt
🧬 Code graph analysis (1)
src/openms/include/OpenMS/FORMAT/ArrowExport.h (1)
src/openms/source/FORMAT/ArrowExport.cpp (16)
  • exportSpectraToArrow (746-762)
  • exportSpectraToArrow (746-748)
  • getSpectraArrowColumns (765-824)
  • getSpectraArrowColumns (765-767)
  • exportChromatogramsToArrow (827-1072)
  • exportChromatogramsToArrow (827-829)
  • getChromatogramArrowColumns (1075-1105)
  • getChromatogramArrowColumns (1075-1077)
  • exportSpectraToArrowCDataInterface (1108-1156)
  • exportSpectraToArrowCDataInterface (1108-1112)
  • exportChromatogramsToArrowCDataInterface (1159-1207)
  • exportChromatogramsToArrowCDataInterface (1159-1163)
  • exportSpectraToParquet (1313-1329)
  • exportSpectraToParquet (1313-1317)
  • exportChromatogramsToParquet (1332-1348)
  • exportChromatogramsToParquet (1332-1336)
🪛 GitHub Check: CodeFactor
src/openms/source/FORMAT/ArrowExport.cpp

[warning] 827-1074: src/openms/source/FORMAT/ArrowExport.cpp#L827-L1074
Very Complex Method


[warning] 448-745: src/openms/source/FORMAT/ArrowExport.cpp#L448-L745
Very Complex Method


[warning] 135-447: src/openms/source/FORMAT/ArrowExport.cpp#L135-L447
Very Complex Method

🔇 Additional comments (23)
src/tests/class_tests/openms/executables.cmake (1)

284-284: LGTM!

The new ArrowExport_test is correctly registered in the WITH_PARQUET guarded block alongside related Arrow/Parquet tests. This aligns with the coding guidelines requiring test registration in executables.cmake.

src/pyOpenMS/tests/unittests/test_dataframe_columns.py (2)

622-668: LGTM!

The test class setup and fixture are well-structured, providing comprehensive test data including MS1/MS2 spectra with precursors and chromatograms. The fixture correctly sets up isolation windows and precursor properties needed for thorough testing.


669-885: Test coverage is comprehensive and well-structured.

The tests cover all major functionality including format variations, filtering, column selection, backward compatibility with deprecation warnings, and error handling for invalid parameters. The use of pytest.importorskip('pyarrow') ensures tests are skipped gracefully when PyArrow is unavailable.

src/tests/class_tests/openms/source/ArrowExport_test.cpp (3)

1-27: LGTM!

The file header follows OpenMS conventions with proper copyright, SPDX license, and $Maintainer:$ marker. The using namespace declarations are correctly placed in the .cpp file (not header), following coding guidelines.


32-79: Well-designed test helpers.

The helper functions create appropriately sized test data (7 total peaks across 3 spectra) following the guideline to keep test data small. The MS2 spectrum includes comprehensive precursor metadata for thorough testing.


83-559: Comprehensive test coverage for Arrow export functionality.

The tests thoroughly cover:

  • Empty experiment handling
  • Long and semi-wide formats
  • MS level, RT, and m/z filtering
  • Column selection
  • Precursor info inclusion/exclusion
  • Chromatogram exports
  • Config struct defaults
  • Parquet export with compression options

All tests follow OpenMS conventions using proper macros.

src/pyOpenMS/CMakeLists.txt (2)

524-593: Well-structured Arrow zerocopy module integration.

The CMake configuration correctly:

  • Guards the module with WITH_PARQUET
  • Obtains Arrow include directories with a fallback path
  • Properly chains build dependencies (compile_pxds → arrow_zerocopy → pyopenms_compile)
  • Sets consistent output properties matching other pyOpenMS modules
  • Defines necessary compile definitions (WITH_PARQUET=1)

676-676: Test file correctly registered.

The new test_dataframe_columns.py is properly added to the unittest file list, ensuring the Arrow export tests run as part of the pyOpenMS test suite.

src/pyOpenMS/pyopenms/_arrow_zerocopy.pyx (3)

1-52: LGTM!

The module setup is clean with proper Cython directives, comprehensive docstring, and correct Arrow C Data Interface struct declarations matching the C ABI. The imports use cimport appropriately for Cython declarations.


149-198: Correct Arrow C Data Interface memory handling.

The memory management follows Arrow C Data Interface semantics correctly:

  1. Allocate and zero-initialize schema/array structs
  2. C++ fills them with data and release callbacks
  3. PyArrow's _import_from_c takes ownership of the Arrow data
  4. Free the wrapper structs (not the Arrow data itself)
  5. PyArrow will call release callbacks on garbage collection

The error handling properly cleans up in all failure paths.


201-283: LGTM!

The chromatograms_to_arrow function follows the same correct pattern as spectra_to_arrow with proper memory management and error handling.

src/pyOpenMS/pxds/ArrowExport.pxd (2)

1-11: LGTM!

The file header and imports follow pyOpenMS conventions. Using cimport for Cython declarations is correct per coding guidelines.


67-91: Well-documented function declarations.

The C Data Interface export functions are properly declared with except + nogil for thread safety and include wrap-doc comments for documentation generation.

src/pyOpenMS/addons/MSExperiment.pyx (1)

812-892: LGTM!

The chromatogram Arrow table builder correctly handles both long and semi-wide formats with proper RT filtering and consistent column construction.

src/openms/source/FORMAT/ArrowExport.cpp (4)

31-133: LGTM!

The helper functions are well-designed with clear responsibilities. The O(1) lookup via unordered_set for MS levels and the pre-counting functions for capacity reservation are good performance optimizations.


196-203: Minor: spectrum_idx incremented even for filtered spectra.

The spectrum_idx is incremented even when spectra are filtered out, which means it represents the original index in the MSExperiment rather than a sequential index of exported spectra. This is actually the correct behavior for maintaining traceability, but it should be documented.


746-824: LGTM!

The export dispatcher and column discovery functions are well-implemented. The column ordering correctly reflects the different schemas between long and semi-wide formats.


1210-1348: LGTM!

The Parquet writing implementation is comprehensive with proper error handling, configurable compression options, and correct file lifecycle management.

src/openms/include/OpenMS/FORMAT/ArrowExport.h (5)

1-29: LGTM!

The file header follows OpenMS conventions with proper copyright, SPDX license, maintainer, and authors. The forward declaration of arrow::Table correctly avoids exposing Arrow implementation details while the necessary includes are minimal.


34-93: LGTM!

The enum class and configuration struct are well-documented with clear Doxygen comments. The default values are sensible, and the notes about sentinel values (0 = no filter) are helpful.


96-158: LGTM!

Excellent Doxygen documentation with comprehensive schema descriptions for both long and semi-wide formats. The parameter documentation includes proper direction tags and the notes about error handling and empty experiments are helpful.


225-265: LGTM!

The C Data Interface declarations include critical ownership documentation (lines 237-239) about release callback responsibilities. This is essential for correct memory management in Python bindings.


267-387: LGTM!

The ParquetWriteConfig struct is thoroughly documented with performance guidelines specific to MS data. The example code in the Doxygen for exportSpectraToParquet provides clear usage patterns.

@mobiusklein

Copy link
Copy Markdown

For long, we basically already have a plan. how would it look for the wide format? everything as in the long format except for having columns with mz,int,IM lists? (which go into a single "cell")

Yes, these would be List or LargeList arrays. LargeList is necessary if the total # of entries across all rows in the array exceeds a 32 bit integer's addressable space. Conceivable if you are loading profile data, though perhaps not practical. Same goes for String vs LargeString where the total element count is # of bytes.

All the commentary about encoding parts of strings is not realistic. If you parsed nativeIds, perhaps, but that breaks them into structs. Same goes for filter strings. There is also no point in dictionary encoding MS level or polarity, the key and the value are the same size. Maybe run encoding makes some amount of sense if you are going to use a logical array type. For clarity, Parquet has run length encoding on disk, Arrow has run end encoding in memory, they are similar in their compression but REE is better for repeated access.

Comment thread src/pyOpenMS/addons/MSExperiment.pyx Resolved
Comment thread src/pyOpenMS/addons/MSExperiment.pyx Resolved
…Make

Address jpfeuffer's review comments on Arrow export PR:

- ArrowExport.pxd: Add const to reference parameters to match C++ signatures,
  improve wrap-doc documentation with purpose and performance info
- _arrow_zerocopy.pyx: Add Cython type signatures to function parameters,
  fix docstring format to use Sphinx :param:/:type:/:return: style
- MSExperiment.pyx: get_arrow_columns() now calls C++ ArrowExport methods
  when available for consistency, add type signatures to get_arrow_columns()
  and to_arrow()
- CMakeLists.txt: Add missing target_link_libraries for ArrowExport_test
  to fix Windows build (arrow/api.h not found)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
}

/// Check if spectrum passes filter criteria
bool passesFilter(const MSSpectrum& spec,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

??? the ms_levels are in the config!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is wrong everywhere.

}

/// Check if a peak passes m/z filter
inline bool peakPassesMzFilter(double mz, double min_mz, double max_mz)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no, use binary search onspectrum to get start end and then unpack.

@timosachsenberg

Copy link
Copy Markdown
Contributor

Addressed review comments in commit 7b0067c:

Fixes:

  • Added const to all reference parameters in ArrowExport.pxd to match C++ signatures
  • Added detailed wrap-docs explaining purpose and O(n) runtime complexity
  • Added Cython type signatures to _arrow_zerocopy.pyx functions
  • Fixed docstrings to use Sphinx :param:/:type:/:return: format
  • get_arrow_columns() now calls C++ ArrowExport methods when available
  • Added type signatures to get_arrow_columns() and to_arrow()
  • Fixed Windows build: Added missing target_link_libraries(ArrowExport_test ...) in CMakeLists.txt

Not changed:

  • Enum wrapping in private module (acknowledged as low priority)
  • Empty experiment handling (needed for schema consistency in Python fallback)
  • Python list → Arrow array pattern (PyArrow doesn't expose C++ builders)


// Check RT range filter
double rt = spec.getRT();
if (config.min_rt != 0 || config.max_rt != 0)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here. you should be able to use binary search if you assume sortedness, which we usually guarantee.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In @src/pyOpenMS/pxds/ArrowExport.pxd:
- Around line 60-61: ArrowExport currently exposes only a default constructor;
add a copy constructor declaration to match pyOpenMS autowrap conventions (as
done for ArrowSpectraExportConfig and ArrowChromatogramExportConfig). Update the
ArrowExport class declaration to include a copy ctor signature like
"ArrowExport(ArrowExport const &)" with the same exception and nogil annotations
as the default ctor (i.e., keep "except + nogil"), so the autowrapper can
generate proper copy semantics for ArrowExport.
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b89c137 and 7b0067c.

📒 Files selected for processing (4)
  • src/pyOpenMS/addons/MSExperiment.pyx
  • src/pyOpenMS/pxds/ArrowExport.pxd
  • src/pyOpenMS/pyopenms/_arrow_zerocopy.pyx
  • src/tests/class_tests/openms/CMakeLists.txt
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{py,pyx,pxd}

📄 CodeRabbit inference engine (AGENTS.md)

Use 4-space indentation for Python/Cython files (PEP 8); no tabs; Unix line endings

Files:

  • src/pyOpenMS/pxds/ArrowExport.pxd
  • src/pyOpenMS/pyopenms/_arrow_zerocopy.pyx
  • src/pyOpenMS/addons/MSExperiment.pyx
src/pyOpenMS/pxds/**/*.pxd

📄 CodeRabbit inference engine (AGENTS.md)

src/pyOpenMS/pxds/**/*.pxd: Always declare default and copy constructors in .pxd files for pyOpenMS wrapping
Use cimport, not Python import for Cython imports in .pxd files
For non-inheriting classes use cdef cppclass ClassName: with no base in .pxd files
Use wrap-doc: formatting with exactly # (hash + 2 spaces) for all documentation continuation lines in .pxd files

Files:

  • src/pyOpenMS/pxds/ArrowExport.pxd
src/pyOpenMS/addons/**/*.pyx

📄 CodeRabbit inference engine (AGENTS.md)

src/pyOpenMS/addons/**/*.pyx: Use snake_case for Python-facing names and DataFrame columns in pyOpenMS
Autowrap returns Python strings; do NOT call .decode() on autowrap string return values
Avoid cdef typed variables for autowrap return values inside def methods in .pyx files; use Python type checks instead
Keep pyOpenMS addons minimal; avoid redundant aliases in addon files

Files:

  • src/pyOpenMS/addons/MSExperiment.pyx
🧠 Learnings (21)
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/tests/class_tests/openms/**/*.cpp : Write unit tests for new functionality

Applied to files:

  • src/tests/class_tests/openms/CMakeLists.txt
📚 Learning: 2026-01-07T06:33:27.217Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.217Z
Learning: Add unit tests in `src/tests/class_tests/openms/source/ClassName_test.cpp` and register in `executables.cmake` for all new classes

Applied to files:

  • src/tests/class_tests/openms/CMakeLists.txt
📚 Learning: 2025-09-03T12:58:20.032Z
Learnt from: timosachsenberg
Repo: OpenMS/OpenMS PR: 8177
File: src/tests/topp/CMakeLists.txt:1857-1865
Timestamp: 2025-09-03T12:58:20.032Z
Learning: OpenMS tests: When adding new TOPP tests in src/tests/topp/CMakeLists.txt that compare outputs via FuzzyDiff, always add set_tests_properties("<tool>_<n>_out<m>" PROPERTIES DEPENDS "<tool>_<n>") to avoid flakiness under parallel CTest runs.

Applied to files:

  • src/tests/class_tests/openms/CMakeLists.txt
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/tests/class_tests/openms/*Test.cpp : Follow naming convention: `ClassNameTest.cpp` for `ClassName`

Applied to files:

  • src/tests/class_tests/openms/CMakeLists.txt
📚 Learning: 2026-01-07T06:33:27.218Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.218Z
Learning: Applies to src/tests/class_tests/openms/source/**/*_test.cpp : Use `START_SECTION` and `END_SECTION` macros in C++ unit tests; wrap template methods with 2+ arguments in parentheses

Applied to files:

  • src/tests/class_tests/openms/CMakeLists.txt
📚 Learning: 2026-01-07T06:33:27.218Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.218Z
Learning: Applies to src/tests/class_tests/openms/source/**/*_test.cpp : Use `NEW_TMP_FILE` macro for each output file in tests to avoid side effects

Applied to files:

  • src/tests/class_tests/openms/CMakeLists.txt
📚 Learning: 2026-01-07T06:33:27.218Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.218Z
Learning: Applies to src/tests/class_tests/openms_gui/source/**/*_test.cpp : GUI tests must be located in `src/tests/class_tests/openms_gui/source/` and use Qt TestLib framework

Applied to files:

  • src/tests/class_tests/openms/CMakeLists.txt
📚 Learning: 2026-01-07T06:33:27.218Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.218Z
Learning: Applies to src/openms/include/**/*.{h,hpp,hxx} : Add `OPENMS_DLLAPI` macro on all non-template exported classes, structs, functions, and variables; include in friend operator declarations

Applied to files:

  • src/tests/class_tests/openms/CMakeLists.txt
  • src/pyOpenMS/pxds/ArrowExport.pxd
📚 Learning: 2026-01-07T06:33:27.217Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.217Z
Learning: Add TOPP tests in `src/tests/topp/CMakeLists.txt` with corresponding test data files

Applied to files:

  • src/tests/class_tests/openms/CMakeLists.txt
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/include/OpenMS/**/*.h : Add Doxygen comments for new public methods and classes

Applied to files:

  • src/tests/class_tests/openms/CMakeLists.txt
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/pyOpenMS/**/*.h : Add Doxygen comments for new public methods and classes in pyOpenMS bindings

Applied to files:

  • src/pyOpenMS/pxds/ArrowExport.pxd
  • src/pyOpenMS/pyopenms/_arrow_zerocopy.pyx
  • src/pyOpenMS/addons/MSExperiment.pyx
📚 Learning: 2026-01-07T06:33:27.218Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.218Z
Learning: Applies to src/pyOpenMS/pxds/**/*.pxd : Use `cimport`, not Python `import` for Cython imports in `.pxd` files

Applied to files:

  • src/pyOpenMS/pxds/ArrowExport.pxd
  • src/pyOpenMS/pyopenms/_arrow_zerocopy.pyx
📚 Learning: 2026-01-07T06:33:27.218Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.218Z
Learning: Applies to src/pyOpenMS/pxds/**/*.pxd : Always declare default and copy constructors in `.pxd` files for pyOpenMS wrapping

Applied to files:

  • src/pyOpenMS/pxds/ArrowExport.pxd
📚 Learning: 2025-11-18T20:08:08.900Z
Learnt from: timosachsenberg
Repo: OpenMS/OpenMS PR: 8374
File: src/pyOpenMS/pxds/SimpleSVM.pxd:0-0
Timestamp: 2025-11-18T20:08:08.900Z
Learning: In pyOpenMS .pxd files, copy constructors should be declared for wrapped C++ classes (e.g., `ClassName(ClassName&) except + nogil`) even when the C++ class has a deleted copy constructor. This is a standard pyOpenMS/Cython convention required for proper wrapper generation and Python object semantics.

Applied to files:

  • src/pyOpenMS/pxds/ArrowExport.pxd
📚 Learning: 2025-06-16T15:48:09.667Z
Learnt from: FreezB11
Repo: OpenMS/OpenMS PR: 7969
File: src/pyOpenMS/pxds/TMTThirtyTwoPlexQuantitationMethod.pxd:4-4
Timestamp: 2025-06-16T15:48:09.667Z
Learning: In OpenMS .pxd files, the established pattern for extern from statements is to include angle brackets inside the string literal, like `cdef extern from "<OpenMS/PATH/TO/FILE.h>" namespace "OpenMS":`. This is consistent across all existing quantitation method .pxd files and other .pxd files in the OpenMS codebase.

Applied to files:

  • src/pyOpenMS/pxds/ArrowExport.pxd
📚 Learning: 2026-01-07T06:33:27.218Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.218Z
Learning: Applies to src/pyOpenMS/addons/**/*.pyx : Avoid `cdef` typed variables for autowrap return values inside `def` methods in `.pyx` files; use Python type checks instead

Applied to files:

  • src/pyOpenMS/pxds/ArrowExport.pxd
  • src/pyOpenMS/pyopenms/_arrow_zerocopy.pyx
📚 Learning: 2026-01-07T06:33:27.218Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.218Z
Learning: Applies to src/pyOpenMS/pxds/**/*.pxd : For non-inheriting classes use `cdef cppclass ClassName:` with no base in `.pxd` files

Applied to files:

  • src/pyOpenMS/pxds/ArrowExport.pxd
📚 Learning: 2026-01-07T06:33:27.218Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.218Z
Learning: Applies to src/pyOpenMS/addons/**/*.pyx : Keep pyOpenMS addons minimal; avoid redundant aliases in addon files

Applied to files:

  • src/pyOpenMS/pxds/ArrowExport.pxd
  • src/pyOpenMS/pyopenms/_arrow_zerocopy.pyx
  • src/pyOpenMS/addons/MSExperiment.pyx
📚 Learning: 2026-01-07T06:33:27.218Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.218Z
Learning: Applies to src/openms/**/*.{cpp,cc,cxx,h,hpp,hxx} : Avoid pointers; prefer references in C++ code

Applied to files:

  • src/pyOpenMS/pxds/ArrowExport.pxd
📚 Learning: 2026-01-07T06:33:27.218Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.218Z
Learning: Applies to src/pyOpenMS/addons/**/*.pyx : Use snake_case for Python-facing names and DataFrame columns in pyOpenMS

Applied to files:

  • src/pyOpenMS/addons/MSExperiment.pyx
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Maintain consistency with the surrounding code

Applied to files:

  • src/pyOpenMS/addons/MSExperiment.pyx
🔇 Additional comments (9)
src/tests/class_tests/openms/CMakeLists.txt (1)

83-86: LGTM!

The test target linkage is correct and consistent with other Arrow/Parquet tests in the same block.

src/pyOpenMS/pyopenms/_arrow_zerocopy.pyx (2)

104-218: LGTM! Solid zero-copy implementation.

The function correctly:

  • Validates the format parameter (lines 137-141)
  • Uses Cython type signatures
  • Manages Arrow C Data Interface memory with proper cleanup on error paths
  • Transfers ownership to PyArrow after successful import

221-312: LGTM! Consistent with spectra export.

Follows the same robust pattern as spectra_to_arrow() with proper format validation, memory management, and error handling.

src/pyOpenMS/pxds/ArrowExport.pxd (1)

16-102: Configuration classes look good.

Both ArrowSpectraExportConfig and ArrowChromatogramExportConfig correctly declare default and copy constructors, and all method parameters are properly const-qualified.

src/pyOpenMS/addons/MSExperiment.pyx (5)

6-15: LGTM! Clean pointer retrieval for zero-copy export.

This internal method correctly returns the C++ object address for use by the _arrow_zerocopy module.


216-318: LGTM! Good C++ integration with Python fallback.

The method correctly:

  • Includes Cython type signatures (line 216-217)
  • Uses C++ ArrowExport.getSpectraArrowColumns() when available for consistency
  • Provides Python fallback matching C++ column ordering
  • Follows Sphinx documentation format

387-690: LGTM! Comprehensive and well-structured export method.

The method correctly:

  • Includes complete Cython type signatures
  • Handles backward compatibility with deprecation warning (lines 490-498)
  • Validates parameters (lines 500-504)
  • Prioritizes zero-copy C++ path when available (lines 514-550)
  • Provides robust Python fallback with proper empty-experiment handling
  • Follows Sphinx documentation format

692-892: LGTM! Correct column ordering for both formats.

The helper correctly implements:

  • Long format with scalar columns (line 777-795 order matches C++)
  • Semi-wide format with list columns (line 868-886 order matches C++)
  • Proper m/z filtering with mask application
  • Ion mobility handling with filter mask preservation
  • Null handling for missing precursor/IM data

894-975: LGTM! Chromatogram export correctly structured.

The helper correctly implements:

  • Long format with scalar columns (line 929-934 order matches C++)
  • Semi-wide format with list columns (line 964-969 order matches C++)
  • RT filtering with proper mask application
  • Always includes precursor_mz and product_mz (identity columns for chromatograms)

Comment thread src/pyOpenMS/pxds/ArrowExport.pxd Resolved
@jpfeuffer

Copy link
Copy Markdown
Contributor

https://cdash.seqan.de/test/300335260

haha this is not good. I think it skips all arrow tests because it doesn't have pyarrow imported/installed?

Optimize ArrowExport performance by using binary search instead of
linear iteration:

- Add getRTFilteredRange() using MSExperiment::RTBegin/RTEnd for O(log n)
  RT range filtering instead of checking each spectrum's RT linearly
- Add getMZFilteredRange() using MSSpectrum::MZBegin/MZEnd for O(log n)
  m/z range filtering instead of checking each peak's m/z linearly
- Replace passesFilter() with passesMSLevelFilter() - RT filtering is now
  done via binary search, only MS level filtering remains as linear check
- Update buildLongFormatTable and buildSemiWideFormatTable to use the
  new binary search range functions
- Update helper functions (countTotalPeaks, countFilteredSpectra,
  experimentHasIMData) to use binary search

This significantly improves performance for large experiments when
filtering by RT or m/z range, reducing complexity from O(n) to O(log n)
for finding the range boundaries.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Fix all issues with AI agents
In @src/openms/source/FORMAT/ArrowExport.cpp:
- Around line 350-353: Remove the dead increment statements ++peak_idx and
++spectrum_idx in ArrowExport.cpp: the loop already recalculates peak_idx from
std::distance(spec.begin(), peak_it) each iteration and spectrum_idx is
incremented in the for-loop header, so delete these redundant increments (they
appear after the inner loop/processing block) to avoid no-op code and potential
confusion; verify no other code relies on those post-increment side-effects.
- Around line 1012-1074: The code returns nullptr on many Arrow builder failures
without logging; update each failure site that currently does "if (!status.ok())
return nullptr;" (including Reserve calls on
chrom_index_builder/precursor_mz_builder/product_mz_builder, Append calls on
native_id_builder/rt_list_builder/intensity_list_builder/rt_value_builder/intensity_value_builder,
and Finish calls on
chrom_index_builder/native_id_builder/rt_list_builder/intensity_list_builder/precursor_mz_builder/product_mz_builder)
to log the error first using OPENMS_LOG_ERROR << status.ToString() << std::endl;
then return nullptr so the error-handling matches the spectra export pattern.
- Around line 988-993: The Finish() calls for rt_builder, intensity_builder,
chrom_index_builder, native_id_builder, precursor_mz_builder, and
product_mz_builder currently return nullptr on failure without logging the Arrow
status; update each failure path to log the Arrow status using OpenMS logging
(e.g., LOG_ERROR or appropriate logger) before returning nullptr, similar to the
pattern used elsewhere in this file (see earlier Finish() handling), by
capturing the returned status (status.ok() false) and calling the logger with a
descriptive message and status.To locate changes, modify the blocks around
rt_builder.Finish(&arr), intensity_builder.Finish(&arr),
chrom_index_builder.Finish(&arr), native_id_builder.Finish(&arr),
precursor_mz_builder.Finish(&arr), and product_mz_builder.Finish(&arr) to log
status.To be consistent, include the field name in the log message and the
status.To summarize: on each Finish() failure, log the Arrow Status via OpenMS
logging before returning nullptr.
🧹 Nitpick comments (2)
src/openms/source/FORMAT/ArrowExport.cpp (2)

152-460: Consider adding inline comments to explain complex logic.

The file has minimal inline comments (well below the ~5% guideline) despite implementing complex Arrow table-building operations. Key areas that would benefit from brief explanatory comments:

  • Peak data extraction and filtering logic (e.g., lines 246–351)
  • List builder append patterns (e.g., lines 596–641)
  • Empty chromatogram schema construction (lines 842–918)

Brief //-style comments describing multi-step operations would improve maintainability without impacting performance.

Based on coding guideline: "Include at least ~5% of code as comments in C++ using // style, plain English describing the next few lines."

Also applies to: 464-748, 834-1079


152-460: Consider extracting helper functions to reduce complexity.

Three functions are flagged for high cyclomatic complexity. While the coordinated Arrow builder state makes decomposition challenging, some repeated patterns could be extracted:

  • Precursor extraction: Lines 230–235 and 552–582 repeat precursor info logic
  • Field/array assembly: Lines 357–459, 645–744, 984–996, 1065–1075 follow the same pattern
  • Empty schema builders: Lines 842–918 could be a helper

These extractions would modularize the code without performance impact. However, given the performance-sensitive nature of these paths, this refactor is optional.

Per static analysis: CodeFactor warns of "Very Complex Method" for these three functions.

Also applies to: 464-748, 834-1079

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7b0067c and e198c6e.

📒 Files selected for processing (1)
  • src/openms/source/FORMAT/ArrowExport.cpp
🧰 Additional context used
📓 Path-based instructions (7)
src/openms/**/*.{cpp,h,hpp,cc,cxx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

src/openms/**/*.{cpp,h,hpp,cc,cxx}: Follow the existing C++ coding conventions in the codebase
Use the established naming patterns for classes, methods, and variables
Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)
Follow the established error handling patterns
Utilize OpenMS logging mechanisms
Be mindful of memory usage when processing large datasets
Consider algorithmic complexity for data processing operations
Use appropriate OpenMS containers and algorithms

Files:

  • src/openms/source/FORMAT/ArrowExport.cpp
**/*.{cpp,cc,cxx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{cpp,cc,cxx}: Never use std::cout or std::cerr directly; use OpenMS logging macros instead
Always use braces for control structures, even for single-line blocks (trivial one-liners may stay single-line)
Braces for control structures must align with opening/closing braces on their own lines

Files:

  • src/openms/source/FORMAT/ArrowExport.cpp
**/*.{cpp,cc,cxx,h,hpp,hxx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{cpp,cc,cxx,h,hpp,hxx}: Never use std::endl; use \n for performance
Use 2-space indentation for C++/headers; no tabs; Unix line endings
Use classes/types/namespaces in PascalCase
Use lowerCamelCase for method names
Use snake_case for variable names
Use trailing underscore for private/protected member variable names
Use UPPER_SNAKE_CASE for enums and macros
Include space after keywords (if, for, while) and around binary operators
Avoid the C++ preprocessor; prefer enum class over macro constants

Files:

  • src/openms/source/FORMAT/ArrowExport.cpp
src/openms/**/*.{cpp,cc,cxx,h,hpp,hxx}

📄 CodeRabbit inference engine (AGENTS.md)

src/openms/**/*.{cpp,cc,cxx,h,hpp,hxx}: Prefer OpenMS::String for numeric formatting and parsing instead of standard stream operators
Use Size/SignedSize types for STL .size() values instead of raw integers
Use OpenMS primitive types from OpenMS/CONCEPT/Types.h
Derive custom exceptions from Exception::Base; throw with file/line/OPENMS_PRETTY_FUNCTION; catch by reference
Avoid pointers; prefer references in C++ code
Use OpenMS/CONCEPT/Types.h primitive types instead of standard C++ types for consistency
Use lower_case_with_underscores for method/function parameters and document ranges/units

Files:

  • src/openms/source/FORMAT/ArrowExport.cpp
src/openms/source/**/*.{cpp,cc,cxx}

📄 CodeRabbit inference engine (AGENTS.md)

Include at least ~5% of code as comments in C++ using // style, plain English describing the next few lines

Files:

  • src/openms/source/FORMAT/ArrowExport.cpp
src/openms/**/*.{h,hpp,hxx,cpp,cc,cxx}

📄 CodeRabbit inference engine (AGENTS.md)

Include $Maintainer:$ marker in file preamble of every header and source file

Files:

  • src/openms/source/FORMAT/ArrowExport.cpp
src/openms/**/*.{cpp,cc,cxx}

📄 CodeRabbit inference engine (AGENTS.md)

Use OPENMS_LOG_WARN, OPENMS_LOG_INFO, and other OpenMS logging macros instead of std::cout or std::cerr

Files:

  • src/openms/source/FORMAT/ArrowExport.cpp
🧠 Learnings (17)
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/include/OpenMS/**/*.h : Add Doxygen comments for new public methods and classes

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2026-01-07T06:33:27.218Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.218Z
Learning: Applies to src/openms/include/**/*.{h,hpp,hxx} : Add `OPENMS_DLLAPI` macro on all non-template exported classes, structs, functions, and variables; include in friend operator declarations

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/tests/class_tests/openms/**/*.cpp : Write unit tests for new functionality

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2026-01-07T06:33:27.217Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.217Z
Learning: Add unit tests in `src/tests/class_tests/openms/source/ClassName_test.cpp` and register in `executables.cmake` for all new classes

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/pyOpenMS/tests/**/*.py : Write pyOpenMS tests for new Python bindings

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/tests/class_tests/openms/*Test.cpp : Follow naming convention: `ClassNameTest.cpp` for `ClassName`

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2026-01-07T06:33:27.218Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.218Z
Learning: Applies to src/tests/class_tests/openms_gui/source/**/*_test.cpp : GUI tests must be located in `src/tests/class_tests/openms_gui/source/` and use Qt TestLib framework

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2026-01-07T06:33:27.218Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.218Z
Learning: Applies to src/tests/class_tests/openms/source/**/*_test.cpp : Use `START_SECTION` and `END_SECTION` macros in C++ unit tests; wrap template methods with 2+ arguments in parentheses

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2025-09-03T12:58:20.032Z
Learnt from: timosachsenberg
Repo: OpenMS/OpenMS PR: 8177
File: src/tests/topp/CMakeLists.txt:1857-1865
Timestamp: 2025-09-03T12:58:20.032Z
Learning: OpenMS tests: When adding new TOPP tests in src/tests/topp/CMakeLists.txt that compare outputs via FuzzyDiff, always add set_tests_properties("<tool>_<n>_out<m>" PROPERTIES DEPENDS "<tool>_<n>") to avoid flakiness under parallel CTest runs.

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2026-01-07T06:33:27.218Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.218Z
Learning: Applies to src/tests/class_tests/openms/source/**/*_test.cpp : Use `NEW_TMP_FILE` macro for each output file in tests to avoid side effects

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Ensure existing tests pass before suggesting changes

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2026-01-07T06:33:27.217Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.217Z
Learning: Add TOPP tests in `src/tests/topp/CMakeLists.txt` with corresponding test data files

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Follow the established error handling patterns

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Utilize OpenMS logging mechanisms

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2026-01-07T06:33:27.218Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.218Z
Learning: Applies to src/openms/**/*.{cpp,cc,cxx} : Use `OPENMS_LOG_WARN`, `OPENMS_LOG_INFO`, and other OpenMS logging macros instead of `std::cout` or `std::cerr`

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2026-01-07T06:33:27.218Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.218Z
Learning: Applies to **/*.{cpp,cc,cxx} : Never use `std::cout` or `std::cerr` directly; use OpenMS logging macros instead

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
🧬 Code graph analysis (1)
src/openms/source/FORMAT/ArrowExport.cpp (1)
src/openms/include/OpenMS/FORMAT/ArrowExport.h (2)
  • exportSpectraToParquet (377-380)
  • exportChromatogramsToParquet (396-399)
🪛 GitHub Check: CodeFactor
src/openms/source/FORMAT/ArrowExport.cpp

[warning] 448-745: src/openms/source/FORMAT/ArrowExport.cpp#L448-L745
Very Complex Method


[warning] 135-447: src/openms/source/FORMAT/ArrowExport.cpp#L135-L447
Very Complex Method


[warning] 827-1074: src/openms/source/FORMAT/ArrowExport.cpp#L827-L1074
Very Complex Method

timosachsenberg and others added 2 commits January 7, 2026 19:02
Remove redundant ++peak_idx and ++spectrum_idx increments that became
dead code after the binary search refactor:
- peak_idx is now calculated from std::distance() each iteration
- spectrum_idx is already incremented in the for-loop header

Addresses CodeRabbit review comment.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Add OPENMS_LOG_ERROR statements to all Arrow builder operations
in chromatogram export functions for both long and semi-wide formats.
This provides better diagnostics when Arrow operations fail.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In @src/openms/source/FORMAT/ArrowExport.cpp:
- Around line 197-1310: The logging calls use std::endl which flushes stdout
unnecessarily; replace all occurrences of OPENMS_LOG_ERROR << ... << std::endl
with OPENMS_LOG_ERROR << ... << '\n' throughout this file (e.g. in
buildLongFormatTable, buildSemiWideFormatTable,
exportSpectraToArrowCDataInterface, exportChromatogramsToArrowCDataInterface,
writeTableToParquet and their error paths such as mz_builder Reserve/Finish,
native_id_builder Append, list/value builder Append/Finish, table
export/CombineChunksToBatch, parquet file open/write/close errors) so each error
logging statement uses '\n' instead of std::endl to avoid forced flushes.
🧹 Nitpick comments (2)
src/openms/source/FORMAT/ArrowExport.cpp (2)

151-1351: Add descriptive comments to meet the ~5% guideline.

The file contains ~1,356 lines but has minimal comments. Per coding guidelines: "Include at least ~5% of code as comments in C++ using // style, plain English describing the next few lines." This would require approximately 68 lines of comments.

Consider adding comments to explain:

  • The overall strategy in buildLongFormatTable and buildSemiWideFormatTable (e.g., "Pre-reserve capacity for all peaks to avoid reallocations")
  • Complex logic such as the ion mobility data handling (lines 238-244, 581-587)
  • The rationale for using UnsafeAppend vs. safe Append (lines 257-261)
  • The chromatogram empty-table builder logic (lines 836-914)
  • The RT filtering approach in chromatogram export (lines 960-962, 1033-1051)

As per coding guidelines.


151-456: Consider refactoring to reduce complexity.

Static analysis flags buildLongFormatTable as very complex (312 lines). While the implementation is functional, extracting helper methods could improve maintainability:

  • Extract column-building logic (e.g., buildMZColumn, buildIntensityColumn, buildPrecursorColumns)
  • Extract the peak iteration loop into a separate method
  • Extract schema/array finalization into a helper

This refactoring would make the method easier to test and maintain, though it can be deferred to a future PR.

Based on static analysis hints.

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e198c6e and de0fb14.

📒 Files selected for processing (1)
  • src/openms/source/FORMAT/ArrowExport.cpp
🧰 Additional context used
📓 Path-based instructions (7)
src/openms/**/*.{cpp,h,hpp,cc,cxx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

src/openms/**/*.{cpp,h,hpp,cc,cxx}: Follow the existing C++ coding conventions in the codebase
Use the established naming patterns for classes, methods, and variables
Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)
Follow the established error handling patterns
Utilize OpenMS logging mechanisms
Be mindful of memory usage when processing large datasets
Consider algorithmic complexity for data processing operations
Use appropriate OpenMS containers and algorithms

Files:

  • src/openms/source/FORMAT/ArrowExport.cpp
**/*.{cpp,cc,cxx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{cpp,cc,cxx}: Never use std::cout or std::cerr directly; use OpenMS logging macros instead
Always use braces for control structures, even for single-line blocks (trivial one-liners may stay single-line)
Braces for control structures must align with opening/closing braces on their own lines

Files:

  • src/openms/source/FORMAT/ArrowExport.cpp
**/*.{cpp,cc,cxx,h,hpp,hxx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{cpp,cc,cxx,h,hpp,hxx}: Never use std::endl; use \n for performance
Use 2-space indentation for C++/headers; no tabs; Unix line endings
Use classes/types/namespaces in PascalCase
Use lowerCamelCase for method names
Use snake_case for variable names
Use trailing underscore for private/protected member variable names
Use UPPER_SNAKE_CASE for enums and macros
Include space after keywords (if, for, while) and around binary operators
Avoid the C++ preprocessor; prefer enum class over macro constants

Files:

  • src/openms/source/FORMAT/ArrowExport.cpp
src/openms/**/*.{cpp,cc,cxx,h,hpp,hxx}

📄 CodeRabbit inference engine (AGENTS.md)

src/openms/**/*.{cpp,cc,cxx,h,hpp,hxx}: Prefer OpenMS::String for numeric formatting and parsing instead of standard stream operators
Use Size/SignedSize types for STL .size() values instead of raw integers
Use OpenMS primitive types from OpenMS/CONCEPT/Types.h
Derive custom exceptions from Exception::Base; throw with file/line/OPENMS_PRETTY_FUNCTION; catch by reference
Avoid pointers; prefer references in C++ code
Use OpenMS/CONCEPT/Types.h primitive types instead of standard C++ types for consistency
Use lower_case_with_underscores for method/function parameters and document ranges/units

Files:

  • src/openms/source/FORMAT/ArrowExport.cpp
src/openms/source/**/*.{cpp,cc,cxx}

📄 CodeRabbit inference engine (AGENTS.md)

Include at least ~5% of code as comments in C++ using // style, plain English describing the next few lines

Files:

  • src/openms/source/FORMAT/ArrowExport.cpp
src/openms/**/*.{h,hpp,hxx,cpp,cc,cxx}

📄 CodeRabbit inference engine (AGENTS.md)

Include $Maintainer:$ marker in file preamble of every header and source file

Files:

  • src/openms/source/FORMAT/ArrowExport.cpp
src/openms/**/*.{cpp,cc,cxx}

📄 CodeRabbit inference engine (AGENTS.md)

Use OPENMS_LOG_WARN, OPENMS_LOG_INFO, and other OpenMS logging macros instead of std::cout or std::cerr

Files:

  • src/openms/source/FORMAT/ArrowExport.cpp
🧠 Learnings (19)
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2026-01-07T06:33:27.218Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.218Z
Learning: Applies to src/openms/include/**/*.{h,hpp,hxx} : Add `OPENMS_DLLAPI` macro on all non-template exported classes, structs, functions, and variables; include in friend operator declarations

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/tests/class_tests/openms/**/*.cpp : Write unit tests for new functionality

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2026-01-07T06:33:27.217Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.217Z
Learning: Add unit tests in `src/tests/class_tests/openms/source/ClassName_test.cpp` and register in `executables.cmake` for all new classes

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/pyOpenMS/tests/**/*.py : Write pyOpenMS tests for new Python bindings

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/tests/class_tests/openms/*Test.cpp : Follow naming convention: `ClassNameTest.cpp` for `ClassName`

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2026-01-07T06:33:27.218Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.218Z
Learning: Applies to src/tests/class_tests/openms_gui/source/**/*_test.cpp : GUI tests must be located in `src/tests/class_tests/openms_gui/source/` and use Qt TestLib framework

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2026-01-07T06:33:27.218Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.218Z
Learning: Applies to src/tests/class_tests/openms/source/**/*_test.cpp : Use `START_SECTION` and `END_SECTION` macros in C++ unit tests; wrap template methods with 2+ arguments in parentheses

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2025-09-03T12:58:20.032Z
Learnt from: timosachsenberg
Repo: OpenMS/OpenMS PR: 8177
File: src/tests/topp/CMakeLists.txt:1857-1865
Timestamp: 2025-09-03T12:58:20.032Z
Learning: OpenMS tests: When adding new TOPP tests in src/tests/topp/CMakeLists.txt that compare outputs via FuzzyDiff, always add set_tests_properties("<tool>_<n>_out<m>" PROPERTIES DEPENDS "<tool>_<n>") to avoid flakiness under parallel CTest runs.

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Ensure existing tests pass before suggesting changes

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2026-01-07T06:33:27.218Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.218Z
Learning: Applies to src/tests/class_tests/openms/source/**/*_test.cpp : Use `NEW_TMP_FILE` macro for each output file in tests to avoid side effects

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2026-01-07T06:33:27.217Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.217Z
Learning: Add TOPP tests in `src/tests/topp/CMakeLists.txt` with corresponding test data files

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Follow the established error handling patterns

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Utilize OpenMS logging mechanisms

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2026-01-07T06:33:27.218Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.218Z
Learning: Applies to src/openms/**/*.{cpp,cc,cxx} : Use `OPENMS_LOG_WARN`, `OPENMS_LOG_INFO`, and other OpenMS logging macros instead of `std::cout` or `std::cerr`

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2026-01-07T06:33:27.218Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.218Z
Learning: Applies to **/*.{cpp,cc,cxx} : Never use `std::cout` or `std::cerr` directly; use OpenMS logging macros instead

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Consider algorithmic complexity for data processing operations

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Be mindful of memory usage when processing large datasets

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
📚 Learning: 2026-01-07T06:33:27.218Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.218Z
Learning: Applies to src/openms/**/*.{cpp,cc,cxx,h,hpp,hxx} : Prefer `OpenMS::String` for numeric formatting and parsing instead of standard stream operators

Applied to files:

  • src/openms/source/FORMAT/ArrowExport.cpp
🧬 Code graph analysis (1)
src/openms/source/FORMAT/ArrowExport.cpp (1)
src/openms/include/OpenMS/FORMAT/ArrowExport.h (2)
  • exportSpectraToParquet (377-380)
  • exportChromatogramsToParquet (396-399)
🪛 GitHub Check: CodeFactor
src/openms/source/FORMAT/ArrowExport.cpp

[warning] 448-745: src/openms/source/FORMAT/ArrowExport.cpp#L448-L745
Very Complex Method


[warning] 135-447: src/openms/source/FORMAT/ArrowExport.cpp#L135-L447
Very Complex Method


[warning] 827-1074: src/openms/source/FORMAT/ArrowExport.cpp#L827-L1074
Very Complex Method

…riter

The MzML writer was incorrectly using MS:1000789 (enhanced multiply charged
spectrum) for TDF (time-delayed fragmentation spectrum) instead of the
correct MS:1000790. This caused a mismatch with the reader which correctly
maps MS:1000790 to ScanMode::TDF.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@jpfeuffer

Copy link
Copy Markdown
Contributor

I think it's still not tested. Did you see my comment? Just in case you wonder why you can't see all your fixes.

Arrow-related tests in test_dataframe_columns.py were being skipped
in CI because pyarrow was not installed. The C++ Arrow libraries
(libarrow-dev, libparquet-dev) are installed, but the Python package
was missing from requirements_bld.txt.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/pyOpenMS/requirements_bld.txt (1)

9-9: Consider specifying a minimum pyarrow version.

The addition of pyarrow aligns well with the new Arrow export functionality and addresses the CI test reliability issue (preventing tests from being skipped). However, unlike other build dependencies (e.g., numpy >= 2.0, Cython >= 3.1.0), no version constraint is specified. Verify whether the implementation requires a minimum pyarrow version for API compatibility or if broad version compatibility is intentional.

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5d98008 and dbdd6b1.

📒 Files selected for processing (1)
  • src/pyOpenMS/requirements_bld.txt

@timosachsenberg

Copy link
Copy Markdown
Contributor

CI Failure Analysis

I investigated the CI failures and found the following:

Root Cause

The CI failures appear to be related to build caching and symbol resolution issues rather than code problems.

When I ran the ArrowExport_test locally after a clean rebuild with WITH_PARQUET=ON, all 24 tests passed successfully:

  • All Arrow table export tests (spectra and chromatograms)
  • All Parquet file export tests
  • Column filtering, MS level filtering, RT/m/z range filtering
  • Both Long and SemiWide formats

Evidence

Initially when running the test against a stale build, I saw:

undefined symbol: _ZN6OpenMS11ArrowExport22exportSpectraToParquetE...

This indicates the ArrowExport.cpp object file was compiled but not linked into libOpenMS.so. After rebuilding the OpenMS library target, all tests pass.

Potential CI Issues

  1. Incremental builds: If the CI is using cached builds, the ArrowExport.cpp might be compiled but not linked into the final library
  2. CMake configuration timing: The sources.cmake correctly adds ArrowExport.cpp when WITH_PARQUET=ON, but if CMake doesn't regenerate properly, the library linking might be incomplete

Recommendation

The CI should ensure a clean build when WITH_PARQUET is enabled, or the CMake cache should be invalidated when this option changes. The code itself appears correct - this is a build system issue.


Tested locally on Linux with GCC

@jpfeuffer

jpfeuffer commented Jan 9, 2026 •

Copy link
Copy Markdown
Contributor

We are not using cached builds 😄 and macos is working..
And the failure it reports was nowhere to be seen. Tell it to stop making BS excuses.

The C++ ArrowExport::getSpectraArrowColumns() and getChromatogramArrowColumns()
return std::vector<std::string>. When exposed via Cython, these are converted
to Python bytes by default. The tests expected Python str objects.

Added .decode('utf-8') to convert the bytes to strings, following the same
pattern used elsewhere in pyOpenMS (e.g., PeptideIdentificationList.pyx:170).

This fix resolves the 3 failing tests in test_dataframe_columns.py:
- test_get_arrow_columns_spectra
- test_get_arrow_columns_chromatograms
- test_get_arrow_columns_both

Co-Authored-By: Claude Opus 4.5 <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In @src/pyOpenMS/addons/MSExperiment.pyx:
- Around line 508-512: The zero-copy path sets _max_rt/_max_mz to 0.0 to mean
"no filter" while the Python fallback uses float('inf'), causing inconsistent
behavior; make the Python fallback use the same defaults as the zero-copy path
(use 0.0 for min defaults only when intended and 0.0 for max defaults to
represent "no filter" per the C++ API) by replacing float('inf') uses for
_max_rt/_max_mz with 0.0 and remove the duplicate defaulting logic in the Python
path (the block around lines 636-656) so both paths share the same default
handling for _min_rt, _max_rt, _min_mz, and _max_mz.
- Around line 251-283: The autowrapped ArrowExport methods already return Python
lists of str, so remove the .decode('utf-8') calls on the results of
ArrowExport.getSpectraArrowColumns(self, config) and
ArrowExport.getChromatogramArrowColumns(self, config) and assign their return
values directly to result['spectra'] and result['chromatograms']; keep the
existing branching logic and error handling unchanged, just replace the
decoded-list construction with the direct method returns.
🧹 Nitpick comments (2)
src/pyOpenMS/addons/MSExperiment.pyx (2)

760-774: Ion mobility filtering logic is correct but could be clarified.

Lines 766-767 check if im_data has the same length as original_len before applying the m/z filter mask. This is correct logic, but the condition could be simplified for clarity.

Optional: Simplify ion mobility filter check
                         im_arr = spec.getFloatDataArrays()[im_idx]
                         im_data = np.array([im_arr[i] for i in range(len(im_arr))])
                         # Apply same m/z filter mask if it was created (numpy boolean indexing)
-                        if mz_mask is not None and len(im_data) == original_len:
+                        if mz_mask is not None:
-                            im_data = im_data[mz_mask]
-                        if len(im_data) == n_peaks:
-                            all_ion_mobility.extend(im_data)
-                        else:
-                            all_ion_mobility.extend([None] * n_peaks)
+                            if len(im_data) == original_len:
+                                im_data = im_data[mz_mask]
+                            # If filtered length matches, use it; otherwise use None
+                            if len(im_data) == n_peaks:
+                                all_ion_mobility.extend(im_data)
+                            else:
+                                all_ion_mobility.extend([None] * n_peaks)
+                        else:
+                            all_ion_mobility.extend(im_data if len(im_data) == n_peaks else [None] * n_peaks)

This makes the filtering logic flow more explicit.


855-866: Consider using numpy indexing for ion mobility filtering in semi-wide format.

Line 862 filters ion mobility data using a Python list comprehension over a numpy boolean mask. While correct, this could be more efficient using numpy array indexing.

Optional: Use numpy for filtering
                 if include_ion_mobility:
                     if spec.containsIMData():
                         im_idx, _ = spec.getIMData()
                         im_arr = spec.getFloatDataArrays()[im_idx]
                         im_data = [im_arr[i] for i in range(len(im_arr))]
                         # Apply same m/z filter mask if it was created
                         if mz_mask is not None and len(im_data) == original_len:
-                            im_data = [im_data[i] for i in range(len(mz_mask)) if mz_mask[i]]
+                            im_data = np.array(im_data)[mz_mask].tolist()
                         all_ion_mobility.append(im_data)

This uses numpy's optimized boolean indexing before converting back to list.

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dbdd6b1 and b140054.

📒 Files selected for processing (1)
  • src/pyOpenMS/addons/MSExperiment.pyx
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{py,pyx,pxd}

📄 CodeRabbit inference engine (AGENTS.md)

Use 4-space indentation for Python/Cython files (PEP 8); no tabs; Unix line endings

Files:

  • src/pyOpenMS/addons/MSExperiment.pyx
src/pyOpenMS/addons/**/*.pyx

📄 CodeRabbit inference engine (AGENTS.md)

src/pyOpenMS/addons/**/*.pyx: Use snake_case for Python-facing names and DataFrame columns in pyOpenMS
Autowrap returns Python strings; do NOT call .decode() on autowrap string return values
Avoid cdef typed variables for autowrap return values inside def methods in .pyx files; use Python type checks instead
Keep pyOpenMS addons minimal; avoid redundant aliases in addon files

Files:

  • src/pyOpenMS/addons/MSExperiment.pyx
🧠 Learnings (5)
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/pyOpenMS/**/*.h : Add Doxygen comments for new public methods and classes in pyOpenMS bindings

Applied to files:

  • src/pyOpenMS/addons/MSExperiment.pyx
📚 Learning: 2026-01-07T06:33:27.218Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.218Z
Learning: Applies to src/pyOpenMS/addons/**/*.pyx : Use snake_case for Python-facing names and DataFrame columns in pyOpenMS

Applied to files:

  • src/pyOpenMS/addons/MSExperiment.pyx
📚 Learning: 2026-01-07T06:33:27.218Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-07T06:33:27.218Z
Learning: Applies to src/pyOpenMS/addons/**/*.pyx : Keep pyOpenMS addons minimal; avoid redundant aliases in addon files

Applied to files:

  • src/pyOpenMS/addons/MSExperiment.pyx
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Applies to src/openms/**/*.{cpp,h,hpp,cc,cxx} : Use OpenMS data structures (e.g., MSExperiment, FeatureMap, PeptideIdentification)

Applied to files:

  • src/pyOpenMS/addons/MSExperiment.pyx
📚 Learning: 2025-08-05T12:43:11.681Z
Learnt from: CR
Repo: OpenMS/OpenMS PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-08-05T12:43:11.681Z
Learning: Maintain consistency with the surrounding code

Applied to files:

  • src/pyOpenMS/addons/MSExperiment.pyx
🔇 Additional comments (4)
src/pyOpenMS/addons/MSExperiment.pyx (4)

1-3: LGTM: Import for pointer type is appropriate.

The uintptr_t import is correct for the pointer-to-integer cast in _get_cpp_pointer.


6-15: LGTM: Pointer access implementation is correct.

The cast through uintptr_t is the appropriate way to expose a C++ object address to Python for zero-copy operations.


557-634: LGTM: Empty experiment handling is comprehensive.

The empty table construction properly defines the full schema with correct Arrow types for both long and semi-wide formats, ensuring schema consistency even when no data is present.


894-975: LGTM: Chromatogram table construction is well-structured.

Both long and semi-wide formats correctly handle RT filtering, empty results, and maintain proper column order and types matching the C++ implementation.

Comment thread src/pyOpenMS/addons/MSExperiment.pyx Resolved
Comment thread src/pyOpenMS/addons/MSExperiment.pyx Resolved
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@timosachsenberg

Copy link
Copy Markdown
Contributor

@jpfeuffer good to go? marked as experimental anyways

@jpfeuffer

Copy link
Copy Markdown
Contributor

Can we wait for the pyopenms restructure PR? Almost done.

@timosachsenberg

Copy link
Copy Markdown
Contributor

the large number of changes made it necessary to squash and put in a new PR. thanks for getting started with it!

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.

4 participants