Skip to content

Add fragment annotation arrays to PSM schema - #115

Merged
ypriverol merged 3 commits into
mainfrom
copilot/fix-108
Sep 29, 2025
Merged

ypriverol merged 3 commits into
mainfrom
copilot/fix-108

Conversation

Copilot AI commented Sep 19, 2025 •

Copy link
Copy Markdown
Contributor

User description

Add Fragment Annotation Arrays to PSM Schema - COMPLETED ✅

Successfully implemented fragment-level annotation arrays to store fragment ion metadata from modern search engines like Sage.

Implementation Completed

  • Added three new nullable array fields to PSM schema in quantmsio/core/format.py:

    • charge_array: pa.list_(pa.int32()) - Fragment ion charge values
    • ion_type_array: pa.list_(pa.string()) - Fragment ion type annotations (b, y, a, etc.)
    • ion_mobility_array: pa.list_(pa.float32()) - Fragment ion mobility values
  • Updated all data processing modules to initialize new fields as None:

    • quantmsio/core/maxquant.py - MaxQuant PSM transformation
    • quantmsio/core/psm.py - General PSM processing
    • quantmsio/core/fragpipe.py - FragPipe data conversion
    • quantmsio/operate/tools.py - Spectrum mapping operations
  • Added comprehensive test suite in tests/test_fragment_annotations.py:

    • Schema structure validation
    • Field type verification (correct PyArrow types)
    • Nullable behavior testing
    • Table creation with fragment data
    • Backward compatibility validation
  • Applied Black code formatting to all modified files to ensure compliance with CI requirements

Technical Implementation

  • Follows existing patterns: Same design as mz_array and intensity_array
  • Nullable arrays: Full backward compatibility with existing datasets
  • Proper metadata: Descriptive field documentation
  • Consistent types: int32 for charges, string for ion types, float32 for mobility
  • Zero breaking changes: All existing code continues to work unchanged
  • PEP 8 compliant: All code properly formatted with Black

Usage Example

# Fragment annotation data can now be stored
psm_data = {
    'mz_array': [[100.1, 200.2, 300.3]], 
    'intensity_array': [[1000.0, 2000.0, 3000.0]],
    'charge_array': [[1, 1, 2]],                 # NEW
    'ion_type_array': [['b', 'y', 'b']],        # NEW  
    'ion_mobility_array': [[0.8, 0.9, 1.0]],    # NEW
}

Future Extensions

Search engine adapters can now be updated to populate these fields when fragment annotations are available, enabling:

  • Enhanced spectrum visualization with ion type labels
  • Machine learning models using fragment-level metadata
  • Standardized storage of rich annotation data across different search engines

This implementation provides a robust foundation for fragment annotation storage while maintaining full compatibility with existing quantms.io workflows.

Fixes #108.


💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.


PR Type

Enhancement


Description

  • Add three fragment annotation arrays to PSM schema

  • Initialize new fields as None in data processing modules

  • Add comprehensive test suite for fragment annotations

  • Maintain backward compatibility with existing datasets


Diagram Walkthrough

flowchart LR
  A["PSM Schema"] --> B["Add charge_array field"]
  A --> C["Add ion_type_array field"] 
  A --> D["Add ion_mobility_array field"]
  B --> E["Update Processing Modules"]
  C --> E
  D --> E
  E --> F["MaxQuant Module"]
  E --> G["FragPipe Module"]
  E --> H["PSM Module"]
  E --> I["Tools Module"]
  F --> J["Initialize as None"]
  G --> J
  H --> J
  I --> J
  J --> K["Add Test Suite"]
Loading

File Walkthrough

Relevant files
Enhancement
format.py
Add fragment annotation arrays to PSM schema                         

quantmsio/core/format.py

  • Add three new nullable array fields to PSM schema
  • charge_array for fragment ion charges (int32)
  • ion_type_array for ion type annotations (string)
  • ion_mobility_array for mobility values (float32)
+21/-0   
fragpipe.py
Initialize fragment arrays in FragPipe module                       

quantmsio/core/fragpipe.py

  • Initialize new fragment annotation arrays as None
  • Add charge_arrays, ion_type_arrays, ion_mobility_arrays
  • Maintain backward compatibility in to_arrow method
+12/-0   
maxquant.py
Initialize fragment arrays in MaxQuant module                       

quantmsio/core/maxquant.py

  • Add initialization of three new fragment annotation fields
  • Set charge_array, ion_type_array, ion_mobility_array to None
  • Update transform_psm method for compatibility
+3/-0     
psm.py
Initialize fragment arrays in PSM module                                 

quantmsio/core/psm.py

  • Add three new fragment annotation fields to add_addition_msg
  • Initialize charge_array, ion_type_array, ion_mobility_array as None
  • Ensure backward compatibility in PSM processing
+3/-0     
tools.py
Initialize fragment arrays in tools module                             

quantmsio/operate/tools.py

  • Initialize new fragment annotation arrays as None
  • Add backward compatibility for spectrum mapping operations
  • Update generate_psms_of_spectrum function
+4/-0     
Tests
test_fragment_annotations.py
Add comprehensive fragment annotation tests                           

tests/test_fragment_annotations.py

  • Add comprehensive test suite for fragment annotation fields
  • Test schema structure, field types, and nullable behavior
  • Validate table creation and backward compatibility
  • Include tests for null values and proper descriptions
+195/-0 

Copilot AI commented Sep 19, 2025

Copy link
Copy Markdown
Contributor Author

@timosachsenberg 👋 This repository doesn't have Copilot instructions. With Copilot instructions, I can understand the repository better, work faster and produce higher quality PRs.

I can generate a .github/copilot-instructions.md file for you automatically. Click here to open a pre-filled issue and assign it to me. I'll write the instructions, and then tag you for review.

Copilot AI changed the title [WIP] Add fragment annotations (if available) Add fragment annotation arrays to PSM schema Sep 19, 2025
@ypriverol

Copy link
Copy Markdown
Contributor

@copilot can you check PythonBlack

Copilot AI commented Sep 25, 2025

Copy link
Copy Markdown
Contributor Author

@copilot can you check PythonBlack

Applied Black formatting to all modified files. The test file needed formatting adjustments to comply with PEP 8 standards. All files now pass black --check . validation. Changes in commit 7f99eca.

Copilot AI requested a review from ypriverol September 25, 2025 06:36
@ypriverol
ypriverol marked this pull request as ready for review September 29, 2025 09:19
@coderabbitai

coderabbitai Bot commented Sep 29, 2025

Copy link
Copy Markdown
Contributor

Important

Review skipped

Bot user detected.

To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


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

@qodo-code-review

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis ✅

108 - PR Code Verified

Compliant requirements:

  • Add three new nullable fragment-level array fields to the PSM schema: charge_array (int32), ion_type_array (string), ion_mobility_array (float32)
  • Ensure the arrays mirror mz_array and intensity_array design (variable-length, nullable) for backward compatibility
  • Update processing modules to initialize these fields (when not provided) without breaking existing workflows
  • Provide tests validating schema structure, field types, nullable behavior, table creation, and backward compatibility

Requires further human verification:

  • Validate that downstream consumers (e.g., readers/visualization tools) handle new fields correctly in real datasets
  • Confirm adapters for search engines that provide annotations actually populate these fields in end-to-end runs
⏱️ Estimated effort to review: 2 🔵🔵⚪⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Schema Consistency

Confirm the new array fields are marked nullable in the schema (matching mz_array/intensity_array behavior) and that metadata keys/encoding align with existing conventions across the codebase.

pa.field(
    "charge_array",
    pa.list_(pa.int32()),
    metadata={
        "description": "Array of fragment ion charge values for the spectrum used for the peptide spectrum match"
    },
),
pa.field(
    "ion_type_array",
    pa.list_(pa.string()),
    metadata={
        "description": "Array of fragment ion type annotations (e.g., b, y, a) for the spectrum used for the peptide spectrum match"
    },
),
pa.field(
    "ion_mobility_array",
    pa.list_(pa.float32()),
    metadata={
        "description": "Array of fragment ion mobility values for the spectrum used for the peptide spectrum match"
    },
),
Type Alignment

Ensure the initialized None arrays use the exact same PyArrow list types as defined in the schema and that row counts match other columns to avoid Table assembly issues.

charge_arrays = pa.array(
    [None] * len(precursor_charge), type=pa.list_(pa.int32())
)
ion_type_arrays = pa.array(
    [None] * len(precursor_charge), type=pa.list_(pa.string())
)
ion_mobility_arrays = pa.array(
    [None] * len(precursor_charge), type=pa.list_(pa.float32())
)
return {
    "precursor_charge": pa.array(precursor_charge, type=pa.int32()),
    "observed_mz": pa.array(observed_mz, type=pa.float32()),
    "rt": pa.array(retention_time, type=pa.float32()),
    "scan": pa.array(scan_number, type=pa.string()),
    "source_file": pa.array(source_file, type=pa.string(), from_pandas=True),
    "ion_mobility": pa.array(ion_mobility, type=pa.float32(), from_pandas=True),
    "num_peaks": num_peaks_array,
    "mz_array": mz_arrays,
    "intensity_array": intensity_arrays,
    "charge_array": charge_arrays,
    "ion_type_array": ion_type_arrays,
    "ion_mobility_array": ion_mobility_arrays,
DataFrame/Arrow Sync

Setting new columns to None may lead to dtype/object inconsistencies when later converting to Arrow; verify that downstream save_parquet logic correctly casts to list types or uses the schema.

# Initialize new fragment annotation arrays as None for backward compatibility
table["charge_array"] = None
table["ion_type_array"] = None
table["ion_mobility_array"] = None

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
Refactor repetitive null array creation

Refactor the repetitive creation of null PyArrow arrays by using a dictionary
and a comprehension to improve conciseness and maintainability.

quantmsio/core/fragpipe.py [275-290]

-mz_arrays = pa.array(
-    [None] * len(precursor_charge), type=pa.list_(pa.float32())
-)
-intensity_arrays = pa.array(
-    [None] * len(precursor_charge), type=pa.list_(pa.float32())
-)
-num_peaks_array = pa.array([None] * len(precursor_charge), type=pa.int32())
-charge_arrays = pa.array(
-    [None] * len(precursor_charge), type=pa.list_(pa.int32())
-)
-ion_type_arrays = pa.array(
-    [None] * len(precursor_charge), type=pa.list_(pa.string())
-)
-ion_mobility_arrays = pa.array(
-    [None] * len(precursor_charge), type=pa.list_(pa.float32())
-)
+num_rows = len(precursor_charge)
+null_array_specs = {
+    "mz_array": pa.list_(pa.float32()),
+    "intensity_array": pa.list_(pa.float32()),
+    "num_peaks": pa.int32(),
+    "charge_array": pa.list_(pa.int32()),
+    "ion_type_array": pa.list_(pa.string()),
+    "ion_mobility_array": pa.list_(pa.float32()),
+}
 
+null_arrays = {
+    name: pa.array([None] * num_rows, type=dtype)
+    for name, dtype in null_array_specs.items()
+}
+mz_arrays = null_arrays["mz_array"]
+intensity_arrays = null_arrays["intensity_array"]
+num_peaks_array = null_arrays["num_peaks"]
+charge_arrays = null_arrays["charge_array"]
+ion_type_arrays = null_arrays["ion_type_array"]
+ion_mobility_arrays = null_arrays["ion_mobility_array"]
+

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 5

__

Why: The suggestion correctly identifies repetitive code and proposes a valid refactoring that improves maintainability by centralizing the array definitions, making future changes easier.

Low
Refactor column initialization for conciseness

Refactor the add_addition_msg method to initialize multiple DataFrame columns to
None by iterating over a list of column names for better conciseness.

quantmsio/core/psm.py [211-220]

 @staticmethod
 def add_addition_msg(df: pd.DataFrame) -> None:
-    df.loc[:, "predicted_rt"] = None
-    df.loc[:, "ion_mobility"] = None
-    df.loc[:, "number_peaks"] = None
-    df.loc[:, "mz_array"] = None
-    df.loc[:, "intensity_array"] = None
-    df.loc[:, "charge_array"] = None
-    df.loc[:, "ion_type_array"] = None
-    df.loc[:, "ion_mobility_array"] = None
+    additional_cols = [
+        "predicted_rt",
+        "ion_mobility",
+        "number_peaks",
+        "mz_array",
+        "intensity_array",
+        "charge_array",
+        "ion_type_array",
+        "ion_mobility_array",
+    ]
+    for col in additional_cols:
+        df.loc[:, col] = None

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 4

__

Why: The suggestion proposes a valid refactoring that improves code conciseness and maintainability by grouping column initializations, which is a good practice.

Low
  • More

@ypriverol
ypriverol deleted the copilot/fix-108 branch October 11, 2025 02:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add fragment annotations (if available)

3 participants