Skip to content

[pyOpenMS] Add Python bindings for XICParquetFile - #8738

Merged
timosachsenberg merged 2 commits into
developfrom
feat/xic_parquet_python
Feb 5, 2026
Merged

timosachsenberg merged 2 commits into
developfrom
feat/xic_parquet_python

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Feb 4, 2026 •

Copy link
Copy Markdown
Contributor

Description

This PR adds Python bindings for reading XIC data from Parquet files, enabling seamless integration with pandas, pyarrow, and pyopenms_viz.

Note: This PR depends on #8737 (C++ core) and should be merged after it.

pyOpenMS Bindings

Added bindings to load XICs from Parquet files using pyopenms, which includes using predicate pushdowns for filtering data prior to loading into memory. This also integrates nicely with pyopenms_viz.

import pyopenms as poms
import pyopenms_viz
import pandas as pd
import glob
from matplotlib import pyplot as plt 
pd.options.plotting.backend = "ms_matplotlib"
 
files = glob.glob('*.xic')
xic_h = poms.XICParquetFile(files)
xic_h.get_chromatograms(filter="precursor_id=1318 & annotation=y3^1").plot(kind="chromatogram", x="rt", y="intensity", by="source_file")

Additions

  • XICParquetFile Python bindings with:
    • list-of-files constructor support
    • get_data_dict, get_chromatograms, to_df, to_arrow
    • get_analyte_dict, get_analyte_df, get_run_dict, get_run_df
    • df_columns for column discovery
    • Filter expressions with predicate pushdown support
  • ParquetFilter/ParquetFilterBuilder Python bindings for typed filter construction
  • ParquetQuery/ChromatogramQuery for chainable querying in Python
  • Unit tests for Python bindings

Based on work by @singjc in PR #8725.

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

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Read XIC chromatogram data directly from Parquet files with support for multiple files.
    • Query and filter chromatogram data by precursor ID, transition ID, MS level, charge, and other criteria.
    • Convert XIC data to multiple formats including dictionaries, DataFrames, and Apache Arrow tables.
    • Access run metadata and analyte information with flexible structure options.
  • Tests

    • Added comprehensive unit tests for XIC Parquet file functionality.

@coderabbitai

coderabbitai Bot commented Feb 4, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR introduces PyOpenMS Python bindings for reading XIC (Extracted Ion Chromatogram) data from Parquet files, adding the XICParquetFile class with multi-file support, flexible querying, and filtering capabilities via a new ParquetFilterBuilder. It includes Cython pxd/pyx interfaces, high-level Python wrappers, CMake build configuration, type converters, and comprehensive unit tests.

Changes

Cohort / File(s) Summary
Cython Parquet Filter Bindings
src/pyOpenMS/pxds/ParquetFilter.pxd, src/pyOpenMS/pyopenms/_parquet_filter.pxd, src/pyOpenMS/pyopenms/_parquet_filter.pyx
New Cython interfaces and wrappers exposing ParquetFilter and ParquetFilterBuilder from C++, enabling fluent query construction with chainable comparison predicates (eq, ne, lt, le, gt, ge) for int64_t and String types, plus membership predicates.
XICParquetFile C++ Bindings
src/pyOpenMS/pxds/XICParquetFile.pxd
New Cython interface mapping C++ XICParquetFile with related data structures (XICChromatogram, XICRunInfo, XICAnalyte) and methods supporting single/multi-file loading, filtering, and metadata retrieval.
High-Level Python Wrappers
src/pyOpenMS/addons/XICParquetFile.pyx, src/pyOpenMS/pyopenms/_parquet_query.py
XICParquetFile class exposing data access methods (to_df, to_arrow, get_data_dict, get_analyte_dict, get_run_dict) and a chainable ParquetQuery/ChromatogramQuery builder for filtering with domain-specific predicates and lazy pandas/pyarrow conversion.
Build & Code Generation
src/pyOpenMS/CMakeLists.txt, src/pyOpenMS/create_cpp_extension.py
CMake configuration for building parquet_filter Cython extension module, Arrow target fallback resolution, codegen output declarations, and pxd/addon filtering logic to exclude Parquet-related files when WITH_PARQUET is disabled.
Type Converters
src/pyOpenMS/converters/special_autowrap_conversionproviders.py
Enhanced StdVectorStringConverter and StdSetStringConverter to accept both bytes and str elements, with per-item bytes handling and encoding logic.
Unit Tests
src/pyOpenMS/tests/unittests/test_XICParquetFile.py
Comprehensive test suite validating schema columns, run/analyte metadata, data retrieval in nested/exploded forms, DataFrame conversion, query filtering, and error handling for Parquet support availability.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Python Client
    participant XICFile as XICParquetFile
    participant Query as ChromatogramQuery
    participant Builder as ParquetFilterBuilder
    participant CPP as C++ OpenMS
    participant Parquet as Parquet File
    
    Client->>XICFile: __init__(filename or filenames)
    XICFile->>CPP: Load XICParquetFile instance
    
    Client->>XICFile: query_chromatograms()
    XICFile->>Query: Create ChromatogramQuery
    
    Client->>Query: filter_precursor_id(value)
    Query->>Query: _add_condition(column, op, value)
    Query->>Builder: Create ParquetFilterBuilder
    Builder->>Builder: eq(column, value)
    
    Client->>Query: filter_ms_level(level)
    Query->>Builder: eq(column, level)
    
    Client->>Query: to_df(explode=False)
    Query->>XICFile: _get_data_dict_from_parquet_filter(builder)
    XICFile->>CPP: getChromatograms(filter)
    CPP->>Parquet: Read filtered XIC data
    Parquet-->>CPP: Chromatogram records
    CPP-->>XICFile: Vector<XICChromatogram>
    XICFile->>XICFile: Convert to dict
    Query->>Query: Build DataFrame
    Query-->>Client: pandas.DataFrame
Loading
sequenceDiagram
    participant Client as Python Client
    participant XICFile as XICParquetFile
    participant CPP as C++ OpenMS
    participant Parquet as Parquet File
    
    Client->>XICFile: get_data_dict(explode=True)
    XICFile->>CPP: load() or getChromatograms()
    CPP->>Parquet: Read all/filtered XIC records
    Parquet-->>CPP: Chromatogram + metadata
    CPP-->>XICFile: Vector<XICChromatogram>
    
    XICFile->>XICFile: _get_data_dict_from_parquet_filter(explode=True)
    XICFile->>XICFile: Flatten rt/intensity arrays per record
    XICFile-->>Client: Dict with exploded arrays
    
    Client->>XICFile: to_arrow()
    XICFile->>XICFile: Build pyarrow.Table from dict
    XICFile-->>Client: pyarrow.Table
Loading

Possibly related PRs

  • PR #8737: Introduces the C++ XICParquetFile, ParquetFilter, and related data structures that this PR wraps in Python bindings.
  • PR #8422: Modifies PyOpenMS CMake Parquet build wiring and Arrow target resolution, providing infrastructure this PR builds upon.
  • PR #8106: Updates pyOpenMS CMake custom-command codegen structure and output declarations that this PR extends for Parquet module generation.

Suggested reviewers

  • poshul
  • jpfeuffer

Poem

🐰 A Parquet file hops into view,
With filters and queries shiny and new,
ChromatogramQuery chains with delight,
Data to DataFrames, oh what a sight!
Arrow and pandas in harmony dance,
PyOpenMS Parquet's wonderful chance!

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 24.87% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically identifies the main change: adding Python bindings for XICParquetFile, which aligns with the core objective of making XIC Parquet file functionality accessible via pyopenms.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/xic_parquet_python

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: 12

🤖 Fix all issues with AI agents
In `@src/openms/include/OpenMS/FORMAT/DATAACCESS/sources.cmake`:
- Around line 5-7: Move the MSChromatogramParquetConsumer.h entry into a
WITH_PARQUET conditional block so it is only added when WITH_PARQUET is enabled:
wrap the MSChromatogramParquetConsumer.h line in if(WITH_PARQUET) ... endif() in
src/openms/include/OpenMS/FORMAT/DATAACCESS/sources.cmake (place it alongside
other Parquet headers like ParquetFilter.h and XICParquetFile.h) to keep the
Parquet-specific consumer consistent with the rest of the guarded Parquet files.

In `@src/openms/include/OpenMS/FORMAT/ParquetFilter.h`:
- Around line 41-46: Add a Doxygen `@brief` for the public method
FilterExpression::empty() in the header: place a brief one-line `@brief` comment
immediately above the bool empty() const; declaration, follow it with a blank
line and any additional details if needed (no `@param` tags are required since
there are no parameters), so the method matches the project's Doxygen style for
public API.

In `@src/openms/source/FORMAT/XICParquetFile.cpp`:
- Around line 282-291: getOptionalInt_ currently unsafely downcasts the
arrow::Array to arrow::Int64Array; change it to handle arbitrary integer array
types by delegating to the existing getIntValueFromArray_ helper (or add
type-checking) instead of static_pointer_casting. Update getOptionalInt_ to call
getIntValueFromArray_(array, row, value) when array is non-null and not
IsNull(row); if getIntValueFromArray_ is defined later, forward-declare it or
move its definition above getOptionalInt_ so the compiler can resolve the call.
- Line 1609: The line declaring schema has an extra leading whitespace breaking
the 2-space indentation convention; locate the declaration
"std::shared_ptr<arrow::Schema> schema =
readParquetSchemaAllFiles_(filenames_);" in XICParquetFile.cpp (around the code
that calls readParquetSchemaAllFiles_) and remove the extra leading space so the
line is indented with the same 2-space level as surrounding statements.

In `@src/pyOpenMS/pxds/ParquetFilter.pxd`:
- Around line 1-4: Add a short plain-English comment block at the top of
ParquetFilter.pxd describing the purpose of this pxd (bindings for Parquet
filter utilities) and briefly explain the three imports (libcpp_vector, int64_t,
String) and why they're needed; update the header comment to be ~1–3 lines so
the file meets the ~5% comment guideline and references the types used by the
surrounding Cython code (libcpp_vector, int64_t, String) to make the intent
clear.
- Around line 10-55: Update the ParquetFilter and ParquetFilterBuilder Cython
declarations to include both exception and nogil annotations (use "except +
nogil") on every public method listed (andNext, orNext, eq, ne, lt, le, gt, ge,
in_/"in", empty, the ParquetFilterBuilder constructors, and filter()) so
exceptions propagate correctly and the GIL can be released where appropriate;
also add brief comments above each cppclass and group of methods describing
their purpose and usage (short one-line doc comments for the classes and each
overload group) to meet the ~5% comment ratio requirement.

In `@src/pyOpenMS/pxds/XICParquetFile.pxd`:
- Around line 85-135: Add exception-translation and GIL-release to the
XICParquetFile accessors/I/O methods: change the declarations of getFilename(),
getFilenames(), load(vector[XICChromatogram]&), all getChromatograms(...)
overloads, getRuns(...), getAnalytes(...), and getColumns(...) to include
"except +" and "nogil" (e.g. "except + nogil") so C++ exceptions like
Exception::InvalidValue are translated and the GIL can be released during
file/Arrow/Parquet I/O.
- Around line 12-78: Declare explicit default and copy constructors for the
nested C++ structs XICChromatogram, XICRunInfo, and XICAnalyte in the .pxd
(e.g., add Foo() and Foo(const Foo&) declarations) so Cython can wrap them; also
update the const getter methods getFilename() and getFilenames() on
XICParquetFile to include "except +" so exceptions propagate correctly when
called from Python. Ensure you reference the exact cppclass names
XICChromatogram, XICRunInfo, XICAnalyte and the XICParquetFile methods
getFilename()/getFilenames() when making these additions.

In `@src/pyOpenMS/pyopenms/_parquet_filter.pxd`:
- Around line 13-37: The bindings declare C++ classes _String (OpenMS::String)
and _ParquetFilterBuilder (OpenMS::ParquetFilterBuilder) but are missing copy
constructors required by pyOpenMS .pxd patterns; add matching copy ctor
declarations: for _String add _String(const _String&) except +, and for
_ParquetFilterBuilder add _ParquetFilterBuilder(const _ParquetFilterBuilder&)
except + so the .pxd matches the C++ copyable types and the rest of the wrapper
code expectations.

In `@src/pyOpenMS/pyopenms/_parquet_query.py`:
- Around line 30-40: The __init__ currently catches all Exceptions when
importing and instantiating _parquet_filter, which hides real initialization
errors; change the try/except to only catch ImportError when importing
_parquet_filter (so assign self._typed = None on ImportError) and let any
exception raised by ParquetFilterBuilder() propagate (or re-raise) so
initialization failures are not silently ignored—update the block that
references _parquet_filter and ParquetFilterBuilder accordingly and ensure
self._typed remains None only when the module is truly unavailable.
- Around line 88-167: The bug is that bytes values are being stringified as
b'...' instead of decoded text; update _quote_string to decode bytes (e.g., if
isinstance(value, bytes): value = value.decode('utf-8')) before str(), update
the IN branch in _add_condition to decode bytes elements in the list
comprehension (convert each v to str(v.decode('utf-8')) when isinstance(v,
bytes)), and update the scalar string path in _add_condition (sval = str(value))
to decode bytes first (if isinstance(value, bytes): value =
value.decode('utf-8'); then sval = str(value)). Ensure decoding uses a
consistent encoding (UTF-8) and preserve existing ValueError behavior.

In `@src/topp/TextExporter.cpp`:
- Around line 1662-1776: The CHROMPARQUET branch opens the output with ofstream
outstr(out.c_str()) but doesn't verify creation, so a bad/unwritable path
produces no output; add a check after opening outstr (e.g. if (!outstr) or
!outstr.is_open()) and handle it the same as other exporters by throwing an
appropriate exception (e.g. Exception::UnableToCreateFile or using
writeLogError_/return INCOMPATIBLE_INPUT_DATA consistent with surrounding code)
before constructing SVOutStream and proceeding with
XICParquetFile/XICChromatogram processing; reference the outstr variable and the
CHROMPARQUET branch around XICParquetFile, writeOptionalInt, and SVOutStream.
🧹 Nitpick comments (10)
src/pyOpenMS/create_cpp_extension.py (1)

93-98: Align addon filtering with pxd filtering to handle potential Arrow addons.*

_is_parquet_addon only checks 'Parquet', while _is_parquet_related excludes both Arrow* and Parquet*. No Arrow*.pyx addons currently exist, but if added in the future, they would bypass the WITH_PARQUET filter and could break builds. Extend the addon predicate to include Arrow* as well to maintain consistency:

-    def _is_parquet_addon(name):
-      return 'Parquet' in name
+    def _is_parquet_addon(name):
+      return name.startswith('Arrow') or ('Parquet' in name)
src/pyOpenMS/converters/special_autowrap_conversionproviders.py (1)

503-507: Consider updating StdSetStringConverter for consistency.

StdVectorStringConverter.type_check_expression (line 405) was updated to accept both bytes and str, but StdSetStringConverter.type_check_expression still only accepts bytes. For a consistent user experience, consider updating this converter similarly.

♻️ Proposed fix
     def type_check_expression(self, cpp_type, arg_var):
         return Code().add("""
-          |isinstance($arg_var, set) and all(isinstance(i, bytes) for i in
+          |isinstance($arg_var, set) and all(isinstance(i, (bytes, str)) for i in
           + $arg_var)
           """, locals()).render()

You would also need to update input_conversion (lines 509-531) to handle str items similarly to the vector converter.

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

33-54: Consider checking FromRecordBatches result before ValueOrDie().

While this is test code where a crash effectively indicates test failure, the pattern at line 53 calls ValueOrDie() on the FromRecordBatches result without first checking ok(). For consistency with the ImportRecordBatch handling (lines 47-50), consider adding a check.

♻️ Optional improvement
   // Convert to Table
-  return arrow::Table::FromRecordBatches({batch_result.ValueOrDie()}).ValueOrDie();
+  auto table_result = arrow::Table::FromRecordBatches({batch_result.ValueOrDie()});
+  if (!table_result.ok())
+  {
+    return nullptr;
+  }
+  return table_result.ValueOrDie();
 }

56-77: Same pattern applies to exportChromatogramsViaInterface.

Line 76 has the same unchecked ValueOrDie() call on FromRecordBatches result.

cmake/cmake_findExternalLibs.cmake (1)

230-250: Consider consistent indentation for maintainability.

The Arrow Dataset handling logic is correct, but the indentation is inconsistent (lines 244-249 use different indent levels than surrounding code). This makes the nested if structure harder to follow.

🔧 Suggested formatting improvement
    if(OPENMS_ARROW_DATASET_TARGET)
      message(STATUS "Using Arrow Dataset target: ${OPENMS_ARROW_DATASET_TARGET}")
      # Arrow Dataset (static) may pull in libxml2 symbols; link explicitly.
      # This avoids missing xmlBufferFree at runtime when dataset pushdown is enabled.
      find_package(LibXml2 REQUIRED)
    endif()
- endif()
+  endif()
  endif()
src/tests/class_tests/openms/source/XICParquetFile_test.cpp (1)

138-148: Consider adding tests for ParquetFilterBuilder and getColumns.

The test suite provides good basic coverage. Based on the AI summary mentioning ParquetFilterBuilder and column discovery functionality, consider adding tests for:

  1. ParquetFilterBuilder chainable API (e.g., ParquetFilterBuilder().eq("PRECURSOR_ID", 2).build())
  2. Column discovery via getColumns() or similar method
💡 Example additional tests
START_SECTION(void getColumns())
{
`#ifdef` WITH_PARQUET
  XICParquetFile xic(OPENMS_GET_TEST_DATA_PATH("XICParquetFile_1_input.xic"));
  std::vector<String> columns = xic.getColumns();
  TEST_EQUAL(columns.empty(), false)
  // Verify expected schema columns are present
  TEST_EQUAL(std::find(columns.begin(), columns.end(), "PRECURSOR_ID") != columns.end(), true)
`#endif`
}
END_SECTION

START_SECTION(ParquetFilterBuilder usage)
{
`#ifdef` WITH_PARQUET
  XICParquetFile xic(OPENMS_GET_TEST_DATA_PATH("XICParquetFile_1_input.xic"));
  auto filter = ParquetFilterBuilder().eq("PRECURSOR_ID", 2).build();
  std::vector<XICChromatogram> chroms;
  xic.getChromatograms(chroms, filter);
  TEST_EQUAL(chroms.size() > 0, true)
`#endif`
}
END_SECTION
src/pyOpenMS/addons/XICParquetFile.pyx (1)

83-300: Consider factoring the duplicate chromatogram-to-dict logic.
get_data_dict() and _get_data_dict_from_parquet_filter() share the same conversion loops; a shared helper would prevent drift.

♻️ Sketch of a shared helper
+    cdef dict _chroms_to_dict(self, libcpp_vector[_XICChromatogram]& chroms, bint explode):
+        # build lists + return dict (current shared logic)
+        ...
+
     def get_data_dict(...):
         cdef libcpp_vector[_XICChromatogram] chroms
         self.inst.get().getChromatograms(...)
-        return {
-            ...
-        }
+        return self._chroms_to_dict(chroms, explode)

     def _get_data_dict_from_parquet_filter(...):
         cdef libcpp_vector[_XICChromatogram] chroms
         self.inst.get().getChromatograms(chroms, deref(cpp_filter))
-        return {
-            ...
-        }
+        return self._chroms_to_dict(chroms, explode)
src/openms/include/OpenMS/FORMAT/XICParquetFile.h (1)

145-159: Consider adding a virtual destructor or documenting the class is not intended for inheritance.

The class has defaulted copy constructor and copy assignment, but no move operations. Given this class holds std::vector<String>, move operations could improve performance. However, since the class follows Rule-of-0 (relying on compiler-generated special members), this is acceptable.

💡 Optional: Explicitly default move operations for clarity
     XICParquetFile(const XICParquetFile& rhs) = default;
     XICParquetFile& operator=(const XICParquetFile& rhs) = default;
+    XICParquetFile(XICParquetFile&& rhs) = default;
+    XICParquetFile& operator=(XICParquetFile&& rhs) = default;
src/openms/source/FORMAT/XICParquetFile.cpp (2)

1080-1089: Potential performance concern with row-by-row slicing in manual filter.

Creating a new RecordBatch slice for each matching row via batch->Slice(row, 1) and collecting them individually could be inefficient for large datasets. Consider using a selection vector approach.

This is flagged by static analysis as a complex method. The row-by-row slicing creates many small batches that are later concatenated. For large tables, this could be optimized by collecting matching row indices first and then slicing contiguous ranges, but the current approach is functionally correct.


1487-1493: Redundant post-filter checks after Arrow filtering.

These manual checks duplicate the filtering already performed by applyArrowFilter_ or the Arrow Dataset scanner. If the filter was successfully applied, these conditions should always pass.

These checks appear to be safety fallbacks for cases where filtering might not have been applied (e.g., dropped unsupported columns). Consider documenting this intent or removing them if the upstream filtering is guaranteed to handle all cases. The current implementation is safe but potentially wasteful.

Comment on lines 5 to 7
set(sources_list_h
MSChromatogramParquetConsumer.h
MSDataAggregatingConsumer.h

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.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

# Locate the header and check for internal guards
fd -a 'MSChromatogramParquetConsumer.h' src/openms/include

Repository: OpenMS/OpenMS

Length of output: 151


🏁 Script executed:

# Also check the actual sources.cmake file to see context
cat -n src/openms/include/OpenMS/FORMAT/DATAACCESS/sources.cmake | head -20

Repository: OpenMS/OpenMS

Length of output: 678


🏁 Script executed:

# Search for WITH_PARQUET patterns in the CMAKE file
rg -n "WITH_PARQUET" src/openms/include/OpenMS/FORMAT/DATAACCESS/sources.cmake

Repository: OpenMS/OpenMS

Length of output: 39


🏁 Script executed:

# Check the header for internal guards
cat -n src/openms/include/OpenMS/FORMAT/DATAACCESS/MSChromatogramParquetConsumer.h | head -30

Repository: OpenMS/OpenMS

Length of output: 1378


🏁 Script executed:

# Search for WITH_PARQUET in the parent directory CMakeLists
rg -n "WITH_PARQUET" src/openms/include/OpenMS/FORMAT/

Repository: OpenMS/OpenMS

Length of output: 269


🏁 Script executed:

# Check if the parent CMakeLists.txt guards the DATAACCESS subdirectory
fd -a 'CMakeLists.txt' src/openms/include/OpenMS/FORMAT/ -exec cat -n {} + | grep -A5 -B5 "DATAACCESS"

Repository: OpenMS/OpenMS

Length of output: 287


🏁 Script executed:

# Check context around line 121 in sources.cmake
cat -n src/openms/include/OpenMS/FORMAT/sources.cmake | sed -n '115,130p'

Repository: OpenMS/OpenMS

Length of output: 521


🏁 Script executed:

# Check if there's a CMakeLists.txt in FORMAT directory that conditionally includes DATAACCESS
cat -n src/openms/include/OpenMS/FORMAT/CMakeLists.txt | head -50

Repository: OpenMS/OpenMS

Length of output: 136


🏁 Script executed:

# Check for any preprocessing or conditional inclusion of MSChromatogramParquetConsumer.h
rg -n "MSChromatogramParquetConsumer" src/openms/include/OpenMS/FORMAT/

Repository: OpenMS/OpenMS

Length of output: 1069


🏁 Script executed:

# Check MSDataWritingConsumer.h for Parquet/Arrow includes
cat -n src/openms/include/OpenMS/FORMAT/DATAACCESS/MSDataWritingConsumer.h | head -50

Repository: OpenMS/OpenMS

Length of output: 2193


🏁 Script executed:

# Search for Arrow/Parquet includes in DATAACCESS headers
rg -n "#include.*[Pp]arquet|#include.*[Aa]rrow" src/openms/include/OpenMS/FORMAT/DATAACCESS/

Repository: OpenMS/OpenMS

Length of output: 39


🏁 Script executed:

# Check if MSChromatogramParquetConsumer implementation file has guards
fd -a 'MSChromatogramParquetConsumer.cpp' src/openms/source || true

Repository: OpenMS/OpenMS

Length of output: 145


🏁 Script executed:

# Check the implementation file for WITH_PARQUET guards
head -50 src/openms/source/FORMAT/DATAACCESS/MSChromatogramParquetConsumer.cpp

Repository: OpenMS/OpenMS

Length of output: 1594


🏁 Script executed:

# Search for WITH_PARQUET in the implementation
rg -n "WITH_PARQUET\|#ifdef\|#endif" src/openms/source/FORMAT/DATAACCESS/MSChromatogramParquetConsumer.cpp | head -20

Repository: OpenMS/OpenMS

Length of output: 39


Move MSChromatogramParquetConsumer.h under a WITH_PARQUET guard for consistency.

The header is currently added unconditionally (line 6), but sibling Parquet-related headers like ParquetFilter.h and XICParquetFile.h are guarded with WITH_PARQUET in the parent sources.cmake (lines 121–125). While the header itself doesn't directly include Parquet/Arrow libraries, the implementation file properly guards those dependencies. For consistency and to prevent users from attempting to use this Parquet-specific class without Parquet support enabled, move the header into a conditional block.

Suggested fix
 set(sources_list_h
-  MSChromatogramParquetConsumer.h
   MSDataAggregatingConsumer.h

Then in the parent src/openms/include/OpenMS/FORMAT/sources.cmake, add:

 if (WITH_PARQUET)
   list(APPEND sources_list_h ArrowExport.h)
   list(APPEND sources_list_h ParquetFilter.h)
   list(APPEND sources_list_h XICParquetFile.h)
+  list(APPEND sources_list_h DATAACCESS/MSChromatogramParquetConsumer.h)
 endif()
🤖 Prompt for AI Agents
In `@src/openms/include/OpenMS/FORMAT/DATAACCESS/sources.cmake` around lines 5 -
7, Move the MSChromatogramParquetConsumer.h entry into a WITH_PARQUET
conditional block so it is only added when WITH_PARQUET is enabled: wrap the
MSChromatogramParquetConsumer.h line in if(WITH_PARQUET) ... endif() in
src/openms/include/OpenMS/FORMAT/DATAACCESS/sources.cmake (place it alongside
other Parquet headers like ParquetFilter.h and XICParquetFile.h) to keep the
Parquet-specific consumer consistent with the rest of the guarded Parquet files.

Comment on lines +41 to +46
struct OPENMS_DLLAPI FilterExpression
{
std::vector<Condition> conditions;
std::vector<String> connectors; // "AND" / "OR"

bool empty() const;

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.

⚠️ Potential issue | 🟡 Minor

Add a Doxygen @brief for FilterExpression::empty().
This is a public API method and should be documented like the rest of the header.

📝 Suggested doc addition
   struct OPENMS_DLLAPI FilterExpression
   {
     std::vector<Condition> conditions;
     std::vector<String> connectors; // "AND" / "OR"

+    /**
+      `@brief` Check whether the expression has no conditions.
+      `@return` True if no conditions are present.
+    */
     bool empty() const;
   };
As per coding guidelines: Use Doxygen documentation with `@brief` tag (required), followed by blank line and details; use `@param[in]`, `@param[out]`, or `@param[in,out]` for all parameters.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
struct OPENMS_DLLAPI FilterExpression
{
std::vector<Condition> conditions;
std::vector<String> connectors; // "AND" / "OR"
bool empty() const;
struct OPENMS_DLLAPI FilterExpression
{
std::vector<Condition> conditions;
std::vector<String> connectors; // "AND" / "OR"
/**
`@brief` Check whether the expression has no conditions.
`@return` True if no conditions are present.
*/
bool empty() const;
🤖 Prompt for AI Agents
In `@src/openms/include/OpenMS/FORMAT/ParquetFilter.h` around lines 41 - 46, Add a
Doxygen `@brief` for the public method FilterExpression::empty() in the header:
place a brief one-line `@brief` comment immediately above the bool empty() const;
declaration, follow it with a blank line and any additional details if needed
(no `@param` tags are required since there are no parameters), so the method
matches the project's Doxygen style for public API.

Comment on lines +282 to +291
bool getOptionalInt_(const std::shared_ptr<arrow::Array>& array, int64_t row, Int64& value)
{
if (!array || array->IsNull(row))
{
return false;
}
auto typed = std::static_pointer_cast<arrow::Int64Array>(array);
value = typed->Value(row);
return true;
}

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.

⚠️ Potential issue | 🟡 Minor

Unsafe downcast in getOptionalInt_ assumes Int64 type.

The function unconditionally casts to Int64Array, but the column might have a different integer type (Int32, etc.). While getIntValueFromArray_ (lines 864-904) handles multiple integer types, getOptionalInt_ does not.

🐛 Consider using getIntValueFromArray_ or adding type checking
     bool getOptionalInt_(const std::shared_ptr<arrow::Array>& array, int64_t row, Int64& value)
     {
       if (!array || array->IsNull(row))
       {
         return false;
       }
-      auto typed = std::static_pointer_cast<arrow::Int64Array>(array);
-      value = typed->Value(row);
-      return true;
+      return getIntValueFromArray_(array, row, value);
     }

Note: This would require forward-declaring or reordering getIntValueFromArray_ before getOptionalInt_.

🤖 Prompt for AI Agents
In `@src/openms/source/FORMAT/XICParquetFile.cpp` around lines 282 - 291,
getOptionalInt_ currently unsafely downcasts the arrow::Array to
arrow::Int64Array; change it to handle arbitrary integer array types by
delegating to the existing getIntValueFromArray_ helper (or add type-checking)
instead of static_pointer_casting. Update getOptionalInt_ to call
getIntValueFromArray_(array, row, value) when array is non-null and not
IsNull(row); if getIntValueFromArray_ is defined later, forward-declare it or
move its definition above getOptionalInt_ so the compiler can resolve the call.

};
const std::vector<String>& requested_columns = columns.empty() ? default_columns : columns;

std::shared_ptr<arrow::Schema> schema = readParquetSchemaAllFiles_(filenames_);

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.

⚠️ Potential issue | 🟡 Minor

Inconsistent indentation on line 1609.

There's extra leading whitespace before std::shared_ptr<arrow::Schema> that breaks the consistent 2-space indentation pattern.

🔧 Fix indentation
-  std::shared_ptr<arrow::Schema> schema = readParquetSchemaAllFiles_(filenames_);
+    std::shared_ptr<arrow::Schema> schema = readParquetSchemaAllFiles_(filenames_);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
std::shared_ptr<arrow::Schema> schema = readParquetSchemaAllFiles_(filenames_);
std::shared_ptr<arrow::Schema> schema = readParquetSchemaAllFiles_(filenames_);
🤖 Prompt for AI Agents
In `@src/openms/source/FORMAT/XICParquetFile.cpp` at line 1609, The line declaring
schema has an extra leading whitespace breaking the 2-space indentation
convention; locate the declaration "std::shared_ptr<arrow::Schema> schema =
readParquetSchemaAllFiles_(filenames_);" in XICParquetFile.cpp (around the code
that calls readParquetSchemaAllFiles_) and remove the extra leading space so the
line is indented with the same 2-space level as surrounding statements.

Comment thread src/pyOpenMS/pxds/ParquetFilter.pxd Resolved
Comment on lines +85 to +135
const String& getFilename() const
const StringList& getFilenames() const

void load(vector[XICChromatogram]& output) const # wrap-ignore
# wrap-doc:
# Load all chromatograms from the file.

void getChromatograms(vector[XICChromatogram]& output,
Int64 precursor_id,
Int64 transition_id,
const String& modified_sequence,
Int64 precursor_charge,
Int64 product_charge,
Int64 ms_level,
Int64 run_id,
const String& filter) const # wrap-ignore
# wrap-doc:
# Load chromatograms with optional filtering.
#
# :param precursor_id: Optional precursor id (-1 to ignore)
# :param transition_id: Optional transition id (-1 to ignore)
# :param modified_sequence: Optional modified sequence (empty to ignore)
# :param precursor_charge: Optional precursor charge (-1 to ignore)
# :param product_charge: Optional product charge (-1 to ignore)
# :param ms_level: Optional MS level (-1 to ignore)
# :param run_id: Optional run id (-1 to ignore)
# :param filter: Optional filter expression string

void getChromatograms(vector[XICChromatogram]& output,
const ParquetFilter& filter) const # wrap-ignore
# wrap-doc:
# Load chromatograms using a typed parquet filter.

void getChromatograms(vector[XICChromatogram]& output,
const ParquetFilterBuilder& filter) const # wrap-ignore
# wrap-doc:
# Load chromatograms using a typed parquet filter builder.

void getRuns(vector[XICRunInfo]& output) except + # wrap-ignore
# wrap-doc:
# Return unique run metadata (run_id, source_file).

void getAnalytes(vector[XICAnalyte]& output,
const StringList& columns,
bool nest_transitions) except + # wrap-ignore
# wrap-doc:
# Return unique analyte metadata.

void getColumns(StringList& output) except + # wrap-ignore
# wrap-doc:
# Return parquet schema column names.

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.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# First, let's locate and examine the XICParquetFile.pxd file
find . -name "XICParquetFile.pxd" -type f

Repository: OpenMS/OpenMS

Length of output: 95


🏁 Script executed:

# Check if the file exists and view the relevant section
if [ -f "src/pyOpenMS/pxds/XICParquetFile.pxd" ]; then
  wc -l src/pyOpenMS/pxds/XICParquetFile.pxd
fi

Repository: OpenMS/OpenMS

Length of output: 97


🏁 Script executed:

# Read the file to see the actual code at lines 85-135
if [ -f "src/pyOpenMS/pxds/XICParquetFile.pxd" ]; then
  sed -n '1,150p' src/pyOpenMS/pxds/XICParquetFile.pxd | cat -n
fi

Repository: OpenMS/OpenMS

Length of output: 5967


🏁 Script executed:

# Search for the C++ implementation to understand if these are I/O or exception-throwing methods
find . -name "XICParquetFile.h" -o -name "XICParquetFile.hpp" -o -name "XICParquetFile.cpp" | head -5

Repository: OpenMS/OpenMS

Length of output: 154


🏁 Script executed:

# Read the C++ header file to understand the method signatures
head -200 src/openms/include/OpenMS/FORMAT/XICParquetFile.h | cat -n

Repository: OpenMS/OpenMS

Length of output: 8472


🏁 Script executed:

# Get the full header to understand exception safety
wc -l src/openms/include/OpenMS/FORMAT/XICParquetFile.h

Repository: OpenMS/OpenMS

Length of output: 110


🏁 Script executed:

# Read the critical method declarations
sed -n '1,100p' src/openms/include/OpenMS/FORMAT/XICParquetFile.h | cat -n

Repository: OpenMS/OpenMS

Length of output: 4322


🏁 Script executed:

# Check for any exception specifications in the C++ code
grep -n "noexcept\|throw\|except" src/openms/include/OpenMS/FORMAT/XICParquetFile.h || echo "No explicit exception specs found"

Repository: OpenMS/OpenMS

Length of output: 90


🏁 Script executed:

# Check the implementation for exception handling
head -50 src/openms/source/FORMAT/XICParquetFile.cpp | cat -n

Repository: OpenMS/OpenMS

Length of output: 1953


🏁 Script executed:

# Let me check the rest of the C++ header to see all method declarations
sed -n '150,220p' src/openms/include/OpenMS/FORMAT/XICParquetFile.h | cat -n

Repository: OpenMS/OpenMS

Length of output: 3163


🏁 Script executed:

# Check other similar .pxd files for patterns with I/O methods
find src/pyOpenMS/pxds -name "*.pxd" -type f | xargs grep -l "load\|get" | head -3

Repository: OpenMS/OpenMS

Length of output: 216


🏁 Script executed:

# Look at ParquetFilter.pxd to see similar patterns
cat src/pyOpenMS/pxds/ParquetFilter.pxd

Repository: OpenMS/OpenMS

Length of output: 2804


🏁 Script executed:

# Let me check if there are any other similar file reader classes to compare patterns
grep -l "except.*nogil" src/pyOpenMS/pxds/*.pxd | head -3 | xargs -I {} bash -c 'echo "=== {} ===" && grep "except.*nogil" {}'

Repository: OpenMS/OpenMS

Length of output: 8344


🏁 Script executed:

# Check the implementation to confirm exception throwing behavior
sed -n '40,100p' src/openms/source/FORMAT/XICParquetFile.cpp | cat -n

Repository: OpenMS/OpenMS

Length of output: 3091


Add except + nogil to XICParquetFile accessors and I/O methods.

Methods that perform file I/O or query data are missing proper exception translation and thread-safety annotations:

  • getFilename() and getFilenames() need except + nogil
  • All getChromatograms() overloads need except + nogil
  • load() needs except + nogil
  • getRuns(), getAnalytes(), and getColumns() need nogil added (they already have except +)

The C++ implementation throws Exception::InvalidValue on file access failures and other Arrow/Parquet errors. These methods must declare exception handling with except + and allow GIL release during I/O operations with nogil.

Proposed changes
-        const String& getFilename() const
-        const StringList& getFilenames() const
+        const String& getFilename() const except + nogil
+        const StringList& getFilenames() const except + nogil

-        void load(vector[XICChromatogram]& output) const  # wrap-ignore
+        void load(vector[XICChromatogram]& output) const except + nogil  # wrap-ignore

-        void getChromatograms(vector[XICChromatogram]& output,
+        void getChromatograms(vector[XICChromatogram]& output,
                               Int64 precursor_id,
                               Int64 transition_id,
                               const String& modified_sequence,
                               Int64 precursor_charge,
                               Int64 product_charge,
                               Int64 ms_level,
                               Int64 run_id,
-                              const String& filter) const  # wrap-ignore
+                              const String& filter) const except + nogil  # wrap-ignore

-        void getChromatograms(vector[XICChromatogram]& output,
-                              const ParquetFilter& filter) const  # wrap-ignore
+        void getChromatograms(vector[XICChromatogram]& output,
+                              const ParquetFilter& filter) const except + nogil  # wrap-ignore

-        void getChromatograms(vector[XICChromatogram]& output,
-                              const ParquetFilterBuilder& filter) const  # wrap-ignore
+        void getChromatograms(vector[XICChromatogram]& output,
+                              const ParquetFilterBuilder& filter) const except + nogil  # wrap-ignore

-        void getRuns(vector[XICRunInfo]& output) except +  # wrap-ignore
+        void getRuns(vector[XICRunInfo]& output) except + nogil  # wrap-ignore

-        void getAnalytes(vector[XICAnalyte]& output,
-                         const StringList& columns,
-                         bool nest_transitions) except +  # wrap-ignore
+        void getAnalytes(vector[XICAnalyte]& output,
+                         const StringList& columns,
+                         bool nest_transitions) except + nogil  # wrap-ignore

-        void getColumns(StringList& output) except +  # wrap-ignore
+        void getColumns(StringList& output) except + nogil  # wrap-ignore
🤖 Prompt for AI Agents
In `@src/pyOpenMS/pxds/XICParquetFile.pxd` around lines 85 - 135, Add
exception-translation and GIL-release to the XICParquetFile accessors/I/O
methods: change the declarations of getFilename(), getFilenames(),
load(vector[XICChromatogram]&), all getChromatograms(...) overloads,
getRuns(...), getAnalytes(...), and getColumns(...) to include "except +" and
"nogil" (e.g. "except + nogil") so C++ exceptions like Exception::InvalidValue
are translated and the GIL can be released during file/Arrow/Parquet I/O.

Comment on lines +13 to +37
cdef extern from "<OpenMS/DATASTRUCTURES/String.h>" namespace "OpenMS":
cdef cppclass _String "OpenMS::String":
_String() except +
_String(const char*) except +

cdef extern from "<OpenMS/FORMAT/ParquetFilter.h>" namespace "OpenMS":
cdef cppclass _ParquetFilterBuilder "OpenMS::ParquetFilterBuilder":
_ParquetFilterBuilder() except +
_ParquetFilterBuilder& andNext()
_ParquetFilterBuilder& orNext()
_ParquetFilterBuilder& eq(const _String& column, int64_t value)
_ParquetFilterBuilder& ne(const _String& column, int64_t value)
_ParquetFilterBuilder& lt(const _String& column, int64_t value)
_ParquetFilterBuilder& le(const _String& column, int64_t value)
_ParquetFilterBuilder& gt(const _String& column, int64_t value)
_ParquetFilterBuilder& ge(const _String& column, int64_t value)
_ParquetFilterBuilder& in_ "in"(const _String& column, const libcpp_vector[int64_t]& values)
_ParquetFilterBuilder& eq(const _String& column, const _String& value)
_ParquetFilterBuilder& ne(const _String& column, const _String& value)
_ParquetFilterBuilder& lt(const _String& column, const _String& value)
_ParquetFilterBuilder& le(const _String& column, const _String& value)
_ParquetFilterBuilder& gt(const _String& column, const _String& value)
_ParquetFilterBuilder& ge(const _String& column, const _String& value)
_ParquetFilterBuilder& in_ "in"(const _String& column, const libcpp_vector[_String]& values)
bint empty() const

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.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# First, let's find and examine the C++ header files referenced
find . -name "String.h" -path "*/DATASTRUCTURES/*" | head -5

Repository: OpenMS/OpenMS

Length of output: 108


🏁 Script executed:

# Look for the ParquetFilter.h header
find . -name "ParquetFilter.h" -path "*/FORMAT/*" | head -5

Repository: OpenMS/OpenMS

Length of output: 107


🏁 Script executed:

# Check other .pxd files for established patterns with copy constructors
fd -t f "\.pxd$" src/pyOpenMS/pxds/ | head -20

Repository: OpenMS/OpenMS

Length of output: 849


🏁 Script executed:

# Examine the C++ String.h header
head -100 ./src/openms/include/OpenMS/DATASTRUCTURES/String.h | cat -n

Repository: OpenMS/OpenMS

Length of output: 3697


🏁 Script executed:

# Get more of String.h to see constructors
sed -n '1,200p' ./src/openms/include/OpenMS/DATASTRUCTURES/String.h | grep -A 5 -B 5 "String(" | head -40

Repository: OpenMS/OpenMS

Length of output: 1464


🏁 Script executed:

# Examine the ParquetFilter.h header
head -150 ./src/openms/include/OpenMS/FORMAT/ParquetFilter.h | cat -n

Repository: OpenMS/OpenMS

Length of output: 5283


🏁 Script executed:

# Check a sample .pxd file to see copy constructor pattern
cat -n src/pyOpenMS/pxds/AASequence.pxd | head -50

Repository: OpenMS/OpenMS

Length of output: 3203


🏁 Script executed:

# Look for ParquetFilterBuilder class in the C++ header
grep -n "class ParquetFilterBuilder" ./src/openms/include/OpenMS/FORMAT/ParquetFilter.h

Repository: OpenMS/OpenMS

Length of output: 39


🏁 Script executed:

# Get more context around ParquetFilterBuilder if it exists
sed -n '1,300p' ./src/openms/include/OpenMS/FORMAT/ParquetFilter.h | tail -100

Repository: OpenMS/OpenMS

Length of output: 3205


🏁 Script executed:

# Check if ParquetFilterBuilder is defined elsewhere or if it's actually ParquetFilter
grep -r "ParquetFilterBuilder" ./src/openms/include/OpenMS/FORMAT/ | head -20

Repository: OpenMS/OpenMS

Length of output: 2287


🏁 Script executed:

# Check the actual .pxd file content to see if it uses nogil
cat -n src/pyOpenMS/pyopenms/_parquet_filter.pxd

Repository: OpenMS/OpenMS

Length of output: 2446


🏁 Script executed:

# Double-check other similar .pxd files to confirm the copy constructor pattern
head -30 src/pyOpenMS/pxds/AbsoluteQuantitation.pxd | grep -A 3 "cdef cppclass"

Repository: OpenMS/OpenMS

Length of output: 193


🏁 Script executed:

# Check one more example
head -40 src/pyOpenMS/pxds/Acquisition.pxd | grep -A 3 "cdef cppclass"

Repository: OpenMS/OpenMS

Length of output: 146


🏁 Script executed:

# Look for constructor declarations in AbsoluteQuantitation.pxd
grep -A 10 "cdef cppclass AbsoluteQuantitation" src/pyOpenMS/pxds/AbsoluteQuantitation.pxd | head -20

Repository: OpenMS/OpenMS

Length of output: 587


🏁 Script executed:

# Look for constructor declarations in Acquisition.pxd
grep -A 10 "cdef cppclass Acquisition" src/pyOpenMS/pxds/Acquisition.pxd | head -20

Repository: OpenMS/OpenMS

Length of output: 432


🏁 Script executed:

# Check one more simpler example - look at String.pxd if it exists
find src/pyOpenMS/pxds -name "String.pxd" -exec cat {} \;

Repository: OpenMS/OpenMS

Length of output: 2582


Add copy constructors for the C++ declarations.

pyOpenMS .pxd bindings require copy constructors for wrapped C++ classes. The C++ classes OpenMS::String and OpenMS::ParquetFilterBuilder both define copy constructors, and these must be declared in the .pxd file to match the established pattern throughout the codebase.

Proposed fix
 cdef extern from "<OpenMS/DATASTRUCTURES/String.h>" namespace "OpenMS":
     cdef cppclass _String "OpenMS::String":
         _String() except +
+        _String(const _String&) except +
         _String(const char*) except +

 cdef extern from "<OpenMS/FORMAT/ParquetFilter.h>" namespace "OpenMS":
     cdef cppclass _ParquetFilterBuilder "OpenMS::ParquetFilterBuilder":
         _ParquetFilterBuilder() except +
+        _ParquetFilterBuilder(const _ParquetFilterBuilder&) except +
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
cdef extern from "<OpenMS/DATASTRUCTURES/String.h>" namespace "OpenMS":
cdef cppclass _String "OpenMS::String":
_String() except +
_String(const char*) except +
cdef extern from "<OpenMS/FORMAT/ParquetFilter.h>" namespace "OpenMS":
cdef cppclass _ParquetFilterBuilder "OpenMS::ParquetFilterBuilder":
_ParquetFilterBuilder() except +
_ParquetFilterBuilder& andNext()
_ParquetFilterBuilder& orNext()
_ParquetFilterBuilder& eq(const _String& column, int64_t value)
_ParquetFilterBuilder& ne(const _String& column, int64_t value)
_ParquetFilterBuilder& lt(const _String& column, int64_t value)
_ParquetFilterBuilder& le(const _String& column, int64_t value)
_ParquetFilterBuilder& gt(const _String& column, int64_t value)
_ParquetFilterBuilder& ge(const _String& column, int64_t value)
_ParquetFilterBuilder& in_ "in"(const _String& column, const libcpp_vector[int64_t]& values)
_ParquetFilterBuilder& eq(const _String& column, const _String& value)
_ParquetFilterBuilder& ne(const _String& column, const _String& value)
_ParquetFilterBuilder& lt(const _String& column, const _String& value)
_ParquetFilterBuilder& le(const _String& column, const _String& value)
_ParquetFilterBuilder& gt(const _String& column, const _String& value)
_ParquetFilterBuilder& ge(const _String& column, const _String& value)
_ParquetFilterBuilder& in_ "in"(const _String& column, const libcpp_vector[_String]& values)
bint empty() const
cdef extern from "<OpenMS/DATASTRUCTURES/String.h>" namespace "OpenMS":
cdef cppclass _String "OpenMS::String":
_String() except +
_String(const _String&) except +
_String(const char*) except +
cdef extern from "<OpenMS/FORMAT/ParquetFilter.h>" namespace "OpenMS":
cdef cppclass _ParquetFilterBuilder "OpenMS::ParquetFilterBuilder":
_ParquetFilterBuilder() except +
_ParquetFilterBuilder(const _ParquetFilterBuilder&) except +
_ParquetFilterBuilder& andNext()
_ParquetFilterBuilder& orNext()
_ParquetFilterBuilder& eq(const _String& column, int64_t value)
_ParquetFilterBuilder& ne(const _String& column, int64_t value)
_ParquetFilterBuilder& lt(const _String& column, int64_t value)
_ParquetFilterBuilder& le(const _String& column, int64_t value)
_ParquetFilterBuilder& gt(const _String& column, int64_t value)
_ParquetFilterBuilder& ge(const _String& column, int64_t value)
_ParquetFilterBuilder& in_ "in"(const _String& column, const libcpp_vector[int64_t]& values)
_ParquetFilterBuilder& eq(const _String& column, const _String& value)
_ParquetFilterBuilder& ne(const _String& column, const _String& value)
_ParquetFilterBuilder& lt(const _String& column, const _String& value)
_ParquetFilterBuilder& le(const _String& column, const _String& value)
_ParquetFilterBuilder& gt(const _String& column, const _String& value)
_ParquetFilterBuilder& ge(const _String& column, const _String& value)
_ParquetFilterBuilder& in_ "in"(const _String& column, const libcpp_vector[_String]& values)
bint empty() const
🤖 Prompt for AI Agents
In `@src/pyOpenMS/pyopenms/_parquet_filter.pxd` around lines 13 - 37, The bindings
declare C++ classes _String (OpenMS::String) and _ParquetFilterBuilder
(OpenMS::ParquetFilterBuilder) but are missing copy constructors required by
pyOpenMS .pxd patterns; add matching copy ctor declarations: for _String add
_String(const _String&) except +, and for _ParquetFilterBuilder add
_ParquetFilterBuilder(const _ParquetFilterBuilder&) except + so the .pxd matches
the C++ copyable types and the rest of the wrapper code expectations.

Comment on lines +30 to +40
def __init__(self, typed_builder=None):
self._pending_connector = None
self._condition_count = 0
self._typed = typed_builder
self._typed_has_condition = False
if self._typed is None:
try:
from . import _parquet_filter
self._typed = _parquet_filter.ParquetFilterBuilder()
except Exception:
self._typed = None

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.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

cat -n src/pyOpenMS/pyopenms/_parquet_query.py | head -50

Repository: OpenMS/OpenMS

Length of output: 2043


🏁 Script executed:

# Search for ParquetFilterBuilder definition and usage
rg -A 10 "class ParquetFilterBuilder" src/pyOpenMS/

Repository: OpenMS/OpenMS

Length of output: 2004


🏁 Script executed:

# Look for any exception patterns around _parquet_filter imports
rg -B 3 -A 5 "_parquet_filter" src/pyOpenMS/

Repository: OpenMS/OpenMS

Length of output: 8758


Catch only ImportError when loading the optional _parquet_filter module. Broad Exception catching masks real initialization failures in ParquetFilterBuilder(). Distinguish between "module unavailable" (ImportError) and "initialization failed" (other exceptions) to surface bugs rather than silently degrading.

🛠️ Proposed fix
         if self._typed is None:
             try:
                 from . import _parquet_filter
                 self._typed = _parquet_filter.ParquetFilterBuilder()
-            except Exception:
+            except ImportError:
                 self._typed = None
🧰 Tools
🪛 Ruff (0.14.14)

[warning] 39-39: Do not catch blind exception: Exception

(BLE001)

🤖 Prompt for AI Agents
In `@src/pyOpenMS/pyopenms/_parquet_query.py` around lines 30 - 40, The __init__
currently catches all Exceptions when importing and instantiating
_parquet_filter, which hides real initialization errors; change the try/except
to only catch ImportError when importing _parquet_filter (so assign self._typed
= None on ImportError) and let any exception raised by ParquetFilterBuilder()
propagate (or re-raise) so initialization failures are not silently
ignored—update the block that references _parquet_filter and
ParquetFilterBuilder accordingly and ensure self._typed remains None only when
the module is truly unavailable.

Comment on lines +88 to +167
def _quote_string(self, value):
if value is None:
raise ValueError("String filter value cannot be None")
s = str(value)
has_single = "'" in s
has_double = '"' in s
if has_single and has_double:
raise ValueError("String filter value contains both quote types: %r" % s)
if has_double:
return "'%s'" % s
return '"%s"' % s

def _format_value(self, value, is_string):
if is_string:
return self._quote_string(value)
try:
return str(int(value))
except Exception as exc:
raise ValueError("Expected integer value, got %r" % (value,)) from exc

def _add_condition(self, column, op, value, is_string):
connector = self._consume_connector()
op_norm = op.upper()
is_list = isinstance(value, (list, tuple))
if op_norm != "IN" and is_list:
op_norm = "IN"
if op_norm == "IN":
if not is_list:
raise ValueError("IN operator expects a list/tuple of values")
if not value:
raise ValueError("IN operator expects a non-empty list of values")
if self._typed is not None:
if self._typed_has_condition:
if connector == "OR":
self._typed.orNext()
else:
self._typed.andNext()
if is_string:
self._typed.in_(column, [str(v) for v in value])
else:
self._typed.in_(column, [int(v) for v in value])
self._typed_has_condition = True
else:
if self._typed is not None:
if self._typed_has_condition:
if connector == "OR":
self._typed.orNext()
else:
self._typed.andNext()
if is_string:
sval = str(value)
if op_norm == "=":
self._typed.eq(column, sval)
elif op_norm == "!=":
self._typed.ne(column, sval)
elif op_norm == "<":
self._typed.lt(column, sval)
elif op_norm == "<=":
self._typed.le(column, sval)
elif op_norm == ">":
self._typed.gt(column, sval)
elif op_norm == ">=":
self._typed.ge(column, sval)
else:
raise ValueError("Unsupported operator: %s" % op)
else:
ival = int(value)
if op_norm == "=":
self._typed.eq(column, ival)
elif op_norm == "!=":
self._typed.ne(column, ival)
elif op_norm == "<":
self._typed.lt(column, ival)
elif op_norm == "<=":
self._typed.le(column, ival)
elif op_norm == ">":
self._typed.gt(column, ival)
elif op_norm == ">=":
self._typed.ge(column, ival)
else:

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.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

# First, let's check if the file exists and read the relevant lines
head -n 200 src/pyOpenMS/pyopenms/_parquet_query.py | tail -n +88

Repository: OpenMS/OpenMS

Length of output: 4554


🏁 Script executed:

# Let's also examine the beginning of the file to understand imports and class structure
head -n 100 src/pyOpenMS/pyopenms/_parquet_query.py

Repository: OpenMS/OpenMS

Length of output: 3424


🏁 Script executed:

# Check the complete file to understand the full context
wc -l src/pyOpenMS/pyopenms/_parquet_query.py

Repository: OpenMS/OpenMS

Length of output: 100


Normalize bytes to text before building string predicates.

The filter() method accepts bytes as input (line ~67: isinstance(value, (str, bytes))), but str(b"...") produces "b'...'" rather than the decoded string. This breaks string comparisons by comparing against the wrong literal.

The proposed fix should be applied to three locations:

  1. _quote_string() – decode bytes before str() conversion
  2. IN operator path (line ~115) – decode bytes in the list comprehension
  3. Scalar string comparison path (line ~130) – decode bytes before assignment
🛠️ Proposed fix
     def _quote_string(self, value):
         if value is None:
             raise ValueError("String filter value cannot be None")
+        if isinstance(value, (bytes, bytearray)):
+            value = value.decode()
         s = str(value)
@@
                 if is_string:
-                    self._typed.in_(column, [str(v) for v in value])
+                    self._typed.in_(column, [
+                        v.decode() if isinstance(v, (bytes, bytearray)) else str(v)
+                        for v in value
+                    ])
                 else:
                     self._typed.in_(column, [int(v) for v in value])
@@
                 if is_string:
-                    sval = str(value)
+                    sval = value.decode() if isinstance(value, (bytes, bytearray)) else str(value)
                     if op_norm == "=":
                         self._typed.eq(column, sval)
🧰 Tools
🪛 Ruff (0.14.14)

[warning] 90-90: Avoid specifying long messages outside the exception class

(TRY003)


[warning] 116-116: Avoid specifying long messages outside the exception class

(TRY003)


[warning] 118-118: Avoid specifying long messages outside the exception class

(TRY003)

🤖 Prompt for AI Agents
In `@src/pyOpenMS/pyopenms/_parquet_query.py` around lines 88 - 167, The bug is
that bytes values are being stringified as b'...' instead of decoded text;
update _quote_string to decode bytes (e.g., if isinstance(value, bytes): value =
value.decode('utf-8')) before str(), update the IN branch in _add_condition to
decode bytes elements in the list comprehension (convert each v to
str(v.decode('utf-8')) when isinstance(v, bytes)), and update the scalar string
path in _add_condition (sval = str(value)) to decode bytes first (if
isinstance(value, bytes): value = value.decode('utf-8'); then sval =
str(value)). Ensure decoding uses a consistent encoding (UTF-8) and preserve
existing ValueError behavior.

Comment thread src/topp/TextExporter.cpp Resolved
timosachsenberg and others added 2 commits February 4, 2026 22:10
This PR adds Python bindings for reading XIC data from Parquet files,
enabling integration with pandas, pyarrow, and pyopenms_viz.

Additions:
- XICParquetFile Python bindings with:
  - list-of-files constructor support
  - get_data_dict, get_chromatograms, to_df, to_arrow
  - get_analyte_dict, get_analyte_df, get_run_dict, get_run_df
  - df_columns for column discovery
  - Filter expressions with predicate pushdown support
- ParquetFilter/ParquetFilterBuilder Python bindings for typed filter construction
- ParquetQuery/ChromatogramQuery for chainable querying
- Unit tests for Python bindings

Example usage:
```python
import pyopenms as poms
import glob

files = glob.glob('*.xic')
xic_h = poms.XICParquetFile(files)
xic_h.get_chromatograms(filter="precursor_id=1318 & annotation=y3^1").plot(
    kind="chromatogram", x="rt", y="intensity", by="source_file"
)
```

Depends on PR #8737 (C++ core).
Based on work from PR #8725 by @singjc.

Co-Authored-By: singjc <[email protected]>
Co-Authored-By: Claude Opus 4.5 <[email protected]>
Remove `from String cimport String` from XICParquetFile.pyx addon.

This import brought in the C++ cppclass declaration, which conflicts
with the autowrap-generated cdef class wrapper on Windows. The addon
uses `isinstance(x, String)` which requires the Python type (cdef class),
not the cppclass. The cdef class is already available in scope when
the addon is injected into the generated module.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@timosachsenberg
timosachsenberg force-pushed the feat/xic_parquet_python branch from 67ea102 to 7990953 Compare February 4, 2026 21:11

@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/pyopenms/_parquet_filter.pyx`:
- Around line 65-121: The type-dispatch checks wrongly only test isinstance(...,
(str, bytes)) so objects that implement a toString() method get misrouted and
cast to int64_t; update the predicate methods eq, ne, lt, le, gt, ge and the
in_() values[0] branch to treat any object that has a callable toString
attribute as a string-like value (i.e. extend the condition to check
hasattr(value, "toString") and callable(value.toString) or for sequences check
the first item similarly) so the code uses _to_string(...) for those cases
instead of casting to int64_t.
🧹 Nitpick comments (2)
src/pyOpenMS/converters/special_autowrap_conversionproviders.py (1)

400-407: Type hint for StdVectorStringConverter should reflect accepted str inputs.

type_check_expression accepts both bytes and str (via .encode()), but matching_python_type_full returns "List[bytes]", which will mislead type checkers and .pyi stub consumers. Update to "List[Union[bytes, str]]" to match the actual API.

Suggested change
     def matching_python_type_full(self, cpp_type):
-        return "List[bytes]"
+        return "List[Union[bytes, str]]"
src/pyOpenMS/CMakeLists.txt (1)

440-506: Optional: drop redundant if(WITH_PARQUET) nesting around parquet_filter.

The outer block already guards WITH_PARQUET, so removing the inner condition reduces indentation and keeps the flow tighter.

♻️ Suggested simplification
-    if(WITH_PARQUET)
-      message(STATUS "Building Parquet filter builder module for pyOpenMS")
+    message(STATUS "Building Parquet filter builder module for pyOpenMS")
@@
-      install(TARGETS parquet_filter
+    install(TARGETS parquet_filter
         COMPONENT python_modules
         LIBRARY DESTINATION pyopenms
         RUNTIME DESTINATION pyopenms
       )
-    endif()

Comment on lines +65 to +121
def eq(self, column, value):
if isinstance(value, (str, bytes)):
self.inst.get().eq(_to_string(column), _to_string(value))
else:
self.inst.get().eq(_to_string(column), <int64_t>value)
return self

def ne(self, column, value):
if isinstance(value, (str, bytes)):
self.inst.get().ne(_to_string(column), _to_string(value))
else:
self.inst.get().ne(_to_string(column), <int64_t>value)
return self

def lt(self, column, value):
if isinstance(value, (str, bytes)):
self.inst.get().lt(_to_string(column), _to_string(value))
else:
self.inst.get().lt(_to_string(column), <int64_t>value)
return self

def le(self, column, value):
if isinstance(value, (str, bytes)):
self.inst.get().le(_to_string(column), _to_string(value))
else:
self.inst.get().le(_to_string(column), <int64_t>value)
return self

def gt(self, column, value):
if isinstance(value, (str, bytes)):
self.inst.get().gt(_to_string(column), _to_string(value))
else:
self.inst.get().gt(_to_string(column), <int64_t>value)
return self

def ge(self, column, value):
if isinstance(value, (str, bytes)):
self.inst.get().ge(_to_string(column), _to_string(value))
else:
self.inst.get().ge(_to_string(column), <int64_t>value)
return self

def in_(self, column, values):
cdef libcpp_vector[_String] v1
cdef libcpp_vector[int64_t] v2
if values is None:
raise TypeError("values must be a list or tuple")
if len(values) == 0:
raise ValueError("values must be non-empty")
if isinstance(values[0], (str, bytes)):
for item1 in values:
v1.push_back(_to_string(item1))
self.inst.get().in_(_to_string(column), v1)
else:
for item2 in values:
v2.push_back(<int64_t>item2)
self.inst.get().in_(_to_string(column), v2)

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.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

# First, let's find and examine the _parquet_filter.pyx file
fd -t f "_parquet_filter.pyx" | head -5

Repository: OpenMS/OpenMS

Length of output: 98


🏁 Script executed:

# Check the file size and read relevant sections
wc -l src/pyOpenMS/pyopenms/_parquet_filter.pyx

Repository: OpenMS/OpenMS

Length of output: 102


🏁 Script executed:

# Read the file to understand _to_string() and the full context
cat -n src/pyOpenMS/pyopenms/_parquet_filter.pyx | head -150

Repository: OpenMS/OpenMS

Length of output: 5146


🏁 Script executed:

# Search for _to_string implementation in the codebase
rg -A 5 "def _to_string|cdef.*_to_string" src/pyOpenMS/pyopenms

Repository: OpenMS/OpenMS

Length of output: 511


🏁 Script executed:

# Look for OpenMS String class definitions in .pxd files
rg "cdef.*String" src/pyOpenMS --type pyx --type pxd -A 2 | head -30

Repository: OpenMS/OpenMS

Length of output: 84


🏁 Script executed:

# Search for usage of ParquetFilterBuilder predicates with potential String objects
rg "\.eq\(|\.ne\(|\.lt\(|\.le\(|\.gt\(|\.ge\(|\.in_\(" src/pyOpenMS --type pyx | head -20

Repository: OpenMS/OpenMS

Length of output: 84


🏁 Script executed:

# Check if any OpenMS String-like objects have toString() method
rg "toString" src/pyOpenMS --type pyx --type pxd | head -20

Repository: OpenMS/OpenMS

Length of output: 84


Add toString() detection to predicate type dispatch logic.

The predicates use isinstance(value, (str, bytes)) to route values between string and numeric branches, but the _to_string() helper already supports objects with a toString() method. OpenMS String-like values would fail when cast to int64_t. Detect toString() objects at the dispatch level to match _to_string() behavior.

Proposed fix
+cdef inline bint _is_string_value(object value):
+    return isinstance(value, (str, bytes)) or hasattr(value, "toString")
+
 def eq(self, column, value):
-    if isinstance(value, (str, bytes)):
+    if _is_string_value(value):
         self.inst.get().eq(_to_string(column), _to_string(value))
     else:
         self.inst.get().eq(_to_string(column), <int64_t>value)
     return self

Apply the same change to ne, lt, le, gt, ge, and the values[0] check in in_().

🤖 Prompt for AI Agents
In `@src/pyOpenMS/pyopenms/_parquet_filter.pyx` around lines 65 - 121, The
type-dispatch checks wrongly only test isinstance(..., (str, bytes)) so objects
that implement a toString() method get misrouted and cast to int64_t; update the
predicate methods eq, ne, lt, le, gt, ge and the in_() values[0] branch to treat
any object that has a callable toString attribute as a string-like value (i.e.
extend the condition to check hasattr(value, "toString") and
callable(value.toString) or for sequences check the first item similarly) so the
code uses _to_string(...) for those cases instead of casting to int64_t.

@timosachsenberg
timosachsenberg merged commit abad806 into develop Feb 5, 2026
40 of 41 checks passed
@timosachsenberg
timosachsenberg deleted the feat/xic_parquet_python branch February 5, 2026 01:45
timosachsenberg added a commit that referenced this pull request Feb 13, 2026
…rrect references

Add 22 missing PR entries across all sections (TOPP tools, PyOpenMS,
OpenMS Library, Fixes, Build System) and fix two incorrect PR number
references (#8633→#8637 for SpectrumNativeIDParser, #8725→#8737/#8738
for XICParquetFile).

Co-Authored-By: Claude Opus 4.6 <[email protected]>
timosachsenberg added a commit that referenced this pull request Feb 13, 2026
…rrect references (#8759)

Add 22 missing PR entries across all sections (TOPP tools, PyOpenMS,
OpenMS Library, Fixes, Build System) and fix two incorrect PR number
references (#8633→#8637 for SpectrumNativeIDParser, #8725→#8737/#8738
for XICParquetFile).

Co-authored-by: Claude Opus 4.6 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant