Repository navigation
Conversation
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
quantmsio/operate/tools.py (2)
169-211: Fix None-handling for select_mods in get_modification_details
elif modification in select_mods:will raise TypeError whenselect_modsis None. Permit all mods whenselect_modsis None.Apply this diff:
- elif modification in select_mods: + elif (select_mods is None) or (modification in select_mods): modifications.append(modification) modification_details.append( { "modification_name": mods_dict[modification][0], "fields": [{"position": position, "localization_probability": 1.0}], } )
85-93: Handle single-key groupby: ensure key is a tuple before save_slice_fileWhen
partitionshas one column,groupbykeys may be scalars; iterating over them insave_slice_filewill iterate characters. Wrap scalars in a tuple.Apply this diff:
- if partitions and len(partitions) > 0: - for key, df in table.groupby(partitions): - parquet_table = pa.Table.from_pandas(df, schema=schema) - pqwriters = save_slice_file( - parquet_table, pqwriters, output_folder, key, filename - ) + if partitions and len(partitions) > 0: + for key, df in table.groupby(partitions): + if not isinstance(key, tuple): + key = (key,) + parquet_table = pa.Table.from_pandas(df, schema=schema) + pqwriters = save_slice_file( + parquet_table, pqwriters, output_folder, key, filename + )
🧹 Nitpick comments (2)
quantmsio/operate/tools.py (2)
302-305: Avoid KeyError if 'sample_accession' is absent in SDRFUse
errors="ignore"to safely drop the column only if present.Apply this diff:
- sdrf_df.drop(columns=["sample_accession"], inplace=True) + sdrf_df.drop(columns=["sample_accession"], inplace=True, errors="ignore")
274-274: Trim and limit split when extracting accession fallbackAvoid trailing spaces and excessive splits.
Apply this diff:
- return [re.split(r"[;,]", proteins)[0]] + return [re.split(r"[;,]", proteins, maxsplit=1)[0].strip()]
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
quantmsio/operate/tools.py(7 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
quantmsio/operate/tools.py (4)
quantmsio/core/sdrf.py (2)
transform_sdrf(425-458)get_experiment_type_from_sdrf(272-317)quantmsio/operate/query.py (4)
map_spectrum_mz(30-41)get_unique_peptides(245-253)iter_file(125-136)close(344-348)quantmsio/utils/file_utils.py (4)
close_file(302-319)save_file(260-299)save_slice_file(211-257)close(419-432)quantmsio/utils/pride_utils.py (1)
get_unanimous_name(21-34)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: unit-tests
- GitHub Check: unit-tests (3.11)
- GitHub Check: unit-tests (3.10)
- GitHub Check: unit-tests
- GitHub Check: build
🔇 Additional comments (5)
quantmsio/operate/tools.py (5)
159-167: Remove merge artifact: “Before Code:” commentThis looks like a leftover marker and should be removed.
Apply this diff:
-# Before Code: def get_ahocorasick(mods_dict: dict) -> ahocorasick.Automaton:
283-290: Good: defensive handling of NaN in transform_ibaqLogging and dropping NaN rows before expansion avoids runtime errors and unexpected object types.
299-301: Rename misspelled function: genereate_ibaq_feature → generate_ibaq_featureAvoid leaking a typo into the public API; update the call site.
Apply this diff:
-def genereate_ibaq_feature( +def generate_ibaq_feature( sdrf_path: Union[Path, str], parquet_path: Union[Path, str] ) -> Generator[pa.Table, None, None]:And:
- for feature in genereate_ibaq_feature(sdrf_path, parquet_path): + for feature in generate_ibaq_feature(sdrf_path, parquet_path):Also applies to: 345-346
337-350: Ensure output directory exists and pass string path to ParquetWriterPrevents failures when parent directory is missing and improves PyArrow compatibility.
Apply this diff:
pqwriter = None - for feature in genereate_ibaq_feature(sdrf_path, parquet_path): - if not pqwriter: - pqwriter = pq.ParquetWriter(output_path, feature.schema) + # Ensure parent directory exists + Path(output_path).parent.mkdir(parents=True, exist_ok=True) + for feature in generate_ibaq_feature(sdrf_path, parquet_path): + if not pqwriter: + pqwriter = pq.ParquetWriter(str(output_path), feature.schema) pqwriter.write_table(feature)
5-11: pyahocorasick declared — found in pyproject.toml (pyahocorasick = "*") and requirements.txt; imports present in quantmsio/operate/query.py and quantmsio/operate/tools.py.
| def get_peptide_map(unique_peptides: list, fasta: str) -> defaultdict: | ||
| peptide_map: defaultdict = defaultdict(list) | ||
| automaton = ahocorasick.Automaton() | ||
| for key in mods_dict.keys(): | ||
| key = "(" + key + ")" | ||
| automaton.add_word(key, key) | ||
| for sequence in unique_peptides: | ||
| automaton.add_word(sequence, sequence) | ||
| automaton.make_automaton() | ||
| return automaton | ||
|
|
||
| fasta_proteins: list = list() | ||
| FASTAFile().load(fasta, fasta_proteins) | ||
|
|
||
| for entry in fasta_proteins: | ||
| accession = entry.identifier.split("|")[1] | ||
| for match in automaton.iter(entry.sequence): | ||
| peptide = match[1] | ||
| if accession not in peptide_map[peptide]: | ||
| peptide_map[peptide].append(accession) | ||
| return peptide_map | ||
|
|
There was a problem hiding this comment.
Make FASTA accession parsing robust in get_peptide_map
entry.identifier.split("|")[1] will fail for headers without the pipe format. Reuse the local helper to parse accessions safely.
Apply this diff:
- for entry in fasta_proteins:
- accession = entry.identifier.split("|")[1]
+ for entry in fasta_proteins:
+ accessions = get_protein_accession(entry.identifier)
+ accession = accessions[0] if accessions else entry.identifier
for match in automaton.iter(entry.sequence):
peptide = match[1]
if accession not in peptide_map[peptide]:
peptide_map[peptide].append(accession)📝 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.
| def get_peptide_map(unique_peptides: list, fasta: str) -> defaultdict: | |
| peptide_map: defaultdict = defaultdict(list) | |
| automaton = ahocorasick.Automaton() | |
| for key in mods_dict.keys(): | |
| key = "(" + key + ")" | |
| automaton.add_word(key, key) | |
| for sequence in unique_peptides: | |
| automaton.add_word(sequence, sequence) | |
| automaton.make_automaton() | |
| return automaton | |
| fasta_proteins: list = list() | |
| FASTAFile().load(fasta, fasta_proteins) | |
| for entry in fasta_proteins: | |
| accession = entry.identifier.split("|")[1] | |
| for match in automaton.iter(entry.sequence): | |
| peptide = match[1] | |
| if accession not in peptide_map[peptide]: | |
| peptide_map[peptide].append(accession) | |
| return peptide_map | |
| def get_peptide_map(unique_peptides: list, fasta: str) -> defaultdict: | |
| peptide_map: defaultdict = defaultdict(list) | |
| automaton = ahocorasick.Automaton() | |
| for sequence in unique_peptides: | |
| automaton.add_word(sequence, sequence) | |
| automaton.make_automaton() | |
| fasta_proteins: list = list() | |
| FASTAFile().load(fasta, fasta_proteins) | |
| for entry in fasta_proteins: | |
| accessions = get_protein_accession(entry.identifier) | |
| accession = accessions[0] if accessions else entry.identifier | |
| for match in automaton.iter(entry.sequence): | |
| peptide = match[1] | |
| if accession not in peptide_map[peptide]: | |
| peptide_map[peptide].append(accession) | |
| return peptide_map |
🤖 Prompt for AI Agents
In quantmsio/operate/tools.py around lines 214 to 231, the code assumes every
FASTA header contains '|' and uses entry.identifier.split("|")[1], which will
raise on non-pipe headers; instead call the project's existing FASTA header
parsing helper to extract the accession safely (replace the split with the local
helper function that returns the accession from entry.identifier), use that
returned accession variable in the loop, and keep the rest of the peptide
mapping logic unchanged.
| def map_peptide_to_protein( | ||
| parquet_file: str, | ||
| fasta: str, | ||
| output_folder: str, | ||
| filename: str, | ||
| label: str = "feature", | ||
| ) -> None: | ||
| p = Query(parquet_file) | ||
| unique_peptides = p.get_unique_peptides() | ||
| peptide_map = get_peptide_map(unique_peptides, fasta) | ||
| pqwriter = None | ||
| for table in p.iter_chunk(batch_size=2000000): | ||
| table["pg_accessions"] = table["sequence"].map(peptide_map) | ||
| table = table[table["pg_accessions"].apply(lambda x: len(x) > 0)] | ||
| table.loc[:, "unique"] = ( | ||
| table["pg_accessions"] | ||
| .apply(lambda x: 0 if len(x) > 1 else 1) | ||
| .astype(np.int32) | ||
| ) | ||
| if label == "feature": | ||
| parquet_table = pa.Table.from_pandas(table, schema=FEATURE_SCHEMA) | ||
| pqwriter = save_file(parquet_table, pqwriter, output_folder, filename) | ||
| else: | ||
| parquet_table = pa.Table.from_pandas(table, schema=IBAQ_SCHEMA) | ||
| pqwriter = save_file(parquet_table, pqwriter, output_folder, filename) | ||
| close_file(None, pqwriter) |
There was a problem hiding this comment.
🧩 Analysis chain
Avoid NaN from Series.map with defaultdict; ensure [] for unmapped peptides
Series.map with a dict returns NaN for missing keys (defaultdict behavior is not guaranteed here). Using get via apply ensures list default and prevents len(NaN) errors.
Apply this diff:
- pqwriter = None
- for table in p.iter_chunk(batch_size=2000000):
- table["pg_accessions"] = table["sequence"].map(peptide_map)
+ pqwriter = None
+ for table in p.iter_chunk(batch_size=2000000):
+ table["pg_accessions"] = table["sequence"].apply(lambda s: peptide_map.get(s, []))
table = table[table["pg_accessions"].apply(lambda x: len(x) > 0)]
table.loc[:, "unique"] = (
table["pg_accessions"]
.apply(lambda x: 0 if len(x) > 1 else 1)
.astype(np.int32)
)Also, please confirm that Query.iter_chunk exists and yields DataFrames as expected.
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== Show quantmsio/operate/tools.py (first 400 lines) ==="
sed -n '1,400p' quantmsio/operate/tools.py || true
echo
echo "=== Search for Query class/iter_chunk and get_peptide_map definitions/usages ==="
rg -n --hidden -S "class Query\b|def iter_chunk\b|def get_unique_peptides\b|def get_peptide_map\b" || true
echo
echo "=== Search for Query instantiations and uses of .map( and .apply( around quantmsio ==="
rg -n --hidden -S "Query\(|\.map\(|\.apply\(" quantmsio || trueLength of output: 18511
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Pandas version:"
python - <<'PY'
import pandas as pd
from collections import defaultdict
print(pd.__version__)
mapping=defaultdict(list)
mapping['A']=['P1']
mapping['B']=['P2']
s=pd.Series(['A','C','B'])
print("Series:")
print(s.tolist())
print("map with defaultdict:")
res_map = s.map(mapping)
print(res_map.tolist())
print("mapping after map (keys):", list(mapping.keys()))
print("apply with mapping.get:")
res_apply = s.apply(lambda x: mapping.get(x, []))
print(res_apply.tolist())
print("mapping after apply (keys):", list(mapping.keys()))
PY
echo
echo "=== Show Query.iter_chunk and get_unique_peptides in quantmsio/operate/query.py ==="
sed -n '1,320p' quantmsio/operate/query.py || trueLength of output: 134
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== Show quantmsio/operate/query.py (full file) ==="
sed -n '1,400p' quantmsio/operate/query.py || trueLength of output: 12570
Replace Series.map with mapping.get to avoid NaN for unmapped peptides
Series.map with a dict-like can yield NaN for missing keys and will cause len(NaN) failures; use apply(lambda s: peptide_map.get(s, [])) to guarantee an empty list for unmapped peptides. Confirmed: Query.iter_chunk exists and yields pandas DataFrames.
- pqwriter = None
- for table in p.iter_chunk(batch_size=2000000):
- table["pg_accessions"] = table["sequence"].map(peptide_map)
+ pqwriter = None
+ for table in p.iter_chunk(batch_size=2000000):
+ table["pg_accessions"] = table["sequence"].apply(lambda s: peptide_map.get(s, []))
table = table[table["pg_accessions"].apply(lambda x: len(x) > 0)]
table.loc[:, "unique"] = (
table["pg_accessions"]
.apply(lambda x: 0 if len(x) > 1 else 1)
.astype(np.int32)
)File: quantmsio/operate/tools.py — map_peptide_to_protein (around lines 233–258)
📝 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.
| def map_peptide_to_protein( | |
| parquet_file: str, | |
| fasta: str, | |
| output_folder: str, | |
| filename: str, | |
| label: str = "feature", | |
| ) -> None: | |
| p = Query(parquet_file) | |
| unique_peptides = p.get_unique_peptides() | |
| peptide_map = get_peptide_map(unique_peptides, fasta) | |
| pqwriter = None | |
| for table in p.iter_chunk(batch_size=2000000): | |
| table["pg_accessions"] = table["sequence"].map(peptide_map) | |
| table = table[table["pg_accessions"].apply(lambda x: len(x) > 0)] | |
| table.loc[:, "unique"] = ( | |
| table["pg_accessions"] | |
| .apply(lambda x: 0 if len(x) > 1 else 1) | |
| .astype(np.int32) | |
| ) | |
| if label == "feature": | |
| parquet_table = pa.Table.from_pandas(table, schema=FEATURE_SCHEMA) | |
| pqwriter = save_file(parquet_table, pqwriter, output_folder, filename) | |
| else: | |
| parquet_table = pa.Table.from_pandas(table, schema=IBAQ_SCHEMA) | |
| pqwriter = save_file(parquet_table, pqwriter, output_folder, filename) | |
| close_file(None, pqwriter) | |
| def map_peptide_to_protein( | |
| parquet_file: str, | |
| fasta: str, | |
| output_folder: str, | |
| filename: str, | |
| label: str = "feature", | |
| ) -> None: | |
| p = Query(parquet_file) | |
| unique_peptides = p.get_unique_peptides() | |
| peptide_map = get_peptide_map(unique_peptides, fasta) | |
| pqwriter = None | |
| for table in p.iter_chunk(batch_size=2000000): | |
| table["pg_accessions"] = table["sequence"].apply(lambda s: peptide_map.get(s, [])) | |
| table = table[table["pg_accessions"].apply(lambda x: len(x) > 0)] | |
| table.loc[:, "unique"] = ( | |
| table["pg_accessions"] | |
| .apply(lambda x: 0 if len(x) > 1 else 1) | |
| .astype(np.int32) | |
| ) | |
| if label == "feature": | |
| parquet_table = pa.Table.from_pandas(table, schema=FEATURE_SCHEMA) | |
| pqwriter = save_file(parquet_table, pqwriter, output_folder, filename) | |
| else: | |
| parquet_table = pa.Table.from_pandas(table, schema=IBAQ_SCHEMA) | |
| pqwriter = save_file(parquet_table, pqwriter, output_folder, filename) | |
| close_file(None, pqwriter) |
🤖 Prompt for AI Agents
quantmsio/operate/tools.py around lines 233 to 258: Series.map with a dict can
return NaN for unmapped peptides which breaks len(x) calls; replace
table["sequence"].map(peptide_map) with table["sequence"].apply(lambda s:
peptide_map.get(s, [])) so unmapped sequences yield an empty list, preserving
subsequent len(...) logic and downstream schema writes; keep the rest of the
loop and writer/close behavior unchanged.
Optimize some files based on CodeFactor.
There was a problem hiding this comment.
Actionable comments posted: 6
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
quantmsio/commands/convert/quantms.py (1)
547-550: Preserve traceback and close indexer on failureAlso make sure to close indexer if creation succeeded but later steps fail.
- except Exception as e: - logger.exception(f"Error during processing: {str(e)}") - raise click.ClickException(f"Error: {str(e)}\nCheck the logs for more details.") + except Exception as e: + if 'indexer' in locals() and indexer is not None: + with contextlib.suppress(Exception): + indexer.close() + logger.exception("Error during processing") + raise click.ClickException("Error: %s\nCheck the logs for more details." % e) from e
🧹 Nitpick comments (32)
quantmsio/core/quantms/feature.py (2)
564-570: Bind loop variable in lambda to avoid late-binding bug.Avoid B023 by capturing
iat definition time.- ).apply( - lambda rows: merge_psm(rows, i), - axis=1, - ) + ).apply( + lambda rows, idx=i: merge_psm(rows, idx), + axis=1, + )
124-129: Narrow overly broad exception handling.Replace bare
except Exceptionwith specific exceptions and move returns into else blocks where applicable (TRY300/BLE001).Also applies to: 327-331, 351-353, 363-367, 421-424
quantmsio/utils/mztab_utils.py (2)
280-288: Use pathlib for cross‑platform path cleanup (handles backslashes).- # Extract filename without extension - filename = clean_path.split("/")[-1].split(".")[0] - return filename + from pathlib import PurePath + return PurePath(clean_path).name.split(".")[0]
42-53: Replace generic Exceptions with specific ones.Prefer ValueError with concise messages; define a custom exception if reused.
Also applies to: 51-53, 78-81
tests/core/idxml/test_idxml_psm.py (2)
124-131: Use logger.exception in except blocks to capture tracebacks.- except Exception as e: - logger.error(f"=== DEBUG: Error in test_convert_to_parquet: {e} ===") - logger.error(f"=== DEBUG: Exception type: {type(e)} ===") + except Exception: + logger.exception("=== DEBUG: Error in test_convert_to_parquet ===") import traceback - - logger.error(f"=== DEBUG: Traceback: {traceback.format_exc()} ===") + logger.error(f"=== DEBUG: Traceback: {traceback.format_exc()} ===") raise
200-201: Avoid asserting broad Exception.Assert a specific exception type raised by IdXmlPsm for missing files (e.g., RuntimeError from pyopenms), or use pytest.raises with a message regex.
quantmsio/core/openms.py (2)
333-338: Decode meta keys to str when extracting additional scores.PyOpenMS keys can be bytes; use decoded key for consistency.
- for key in keys: + for key in keys: try: - value = hit.getMetaValue(key) + key_str = key.decode() if isinstance(key, bytes) else key + value = hit.getMetaValue(key_str) if isinstance(value, (int, float)): - scores.append({"score_name": key, "score_value": float(value)}) + scores.append({"score_name": key_str, "score_value": float(value)}) except (KeyError, TypeError, ValueError, RuntimeError):
187-189: Narrow broad exception in _get_run or log with traceback.tests/core/quantms/psms/test_psm.py (2)
298-305: Use truthiness instead of == True/False.- assert ( - _is_ms_run_location_line( - ["MTD", "ms_run[1]-location", "file:///path/file.mzML"] - ) - == True - ) - assert _is_ms_run_location_line(["MTD", "ms_run[1]-format", "mzML"]) == False - assert _is_ms_run_location_line(["PRT", "accession", "P12345"]) == False + assert _is_ms_run_location_line(["MTD", "ms_run[1]-location", "file:///path/file.mzML"]) + assert not _is_ms_run_location_line(["MTD", "ms_run[1]-format", "mzML"]) + assert not _is_ms_run_location_line(["PRT", "accession", "P12345"])
566-576: Remove f-prefix without placeholders and unused enumerate var.- logger.info(f"\nTop 10 protein groups with lowest q-values:") + logger.info("\nTop 10 protein groups with lowest q-values:") - for i, (accession, qvalue) in enumerate(sorted_groups[:10], 1): + for accession, qvalue in sorted_groups[:10]: protein_count = len(accession.split(";"))quantmsio/core/idxml.py (5)
56-57: Log exceptions with traceback for parse failures.- except Exception as e: - logging.error(f"Error parsing IdXML file with pyopenms: {e}") + except Exception: + logging.exception("Error parsing IdXML file with pyopenms") raise
170-172: Use logging.exception for peptide hit parse errors.- except Exception as e: - logging.warning(f"Error parsing peptide hit with pyopenms: {e}") + except Exception: + logging.exception("Error parsing peptide hit with pyopenms") return None
638-673: Ensure output dir exists and enable parquet compression.- table = pa.Table.from_pandas(df, schema=PSM_SCHEMA) - pq.write_table(table, output_path) + from pathlib import Path + output_path = Path(output_path) + output_path.parent.mkdir(parents=True, exist_ok=True) + table = pa.Table.from_pandas(df, schema=PSM_SCHEMA) + pq.write_table(table, str(output_path), compression="zstd")
601-612: Narrow broad exception and include traceback when attaching spectra.- except (ValueError, Exception) as e: - logging.warning(f"Error fetching spectrum (scan={scan_value}): {e}") + except ValueError: + logging.warning(f"Error fetching spectrum (scan={scan_value}): invalid scan") + except Exception: + logging.exception(f"Error fetching spectrum (scan={scan_value})")Apply similarly in OnDisc path.
Also applies to: 634-637
84-93: Optional: fallback decoy detection via accession prefix.If target_decoy meta missing, consider DECOY_ prefix heuristic as in OpenMSHandler._is_decoy.
quantmsio/core/quantms/psm.py (3)
672-684: Improve slice(): typed exceptions, fix typo, avoid shadowing df.- if not isinstance(partitions, list): - raise Exception(f"{partitions} is not a list") + if not isinstance(partitions, list): + raise TypeError(f"{partitions} is not a list") if len(partitions) == 0: - raise Exception(f"{partitions} is empty") - for partion in partitions: - if partion not in cols: - raise Exception(f"{partion} does not exist") - for key, df in df.groupby(partitions): - yield key, df + raise ValueError("partitions is empty") + for partition in partitions: + if partition not in cols: + raise KeyError(f"{partition} does not exist") + for key, group_df in df.groupby(partitions): + yield key, group_df
447-454: Remove duplicate assignments for mz_array/intensity_array.transformed_record["mz_array"] = None transformed_record["intensity_array"] = None transformed_record["number_peaks"] = None transformed_record["ion_mobility"] = None - transformed_record["mz_array"] = None - transformed_record["intensity_array"] = None
70-72: Narrow broad exceptions and prefer logger.exception where appropriate.Replace
except Exceptionwith specific exceptions; uselogger.exceptionon unexpected failures.Also applies to: 114-116, 173-175, 275-277, 457-459, 598-601, 666-668
quantmsio/commands/convert/quantms.py (8)
5-10: Tighten imports: add uuid/contextlib, drop unused osYou’ll need uuid for safer temp-path generation and contextlib (if you use suppress). After refactors below, os becomes unused.
import logging -import os from pathlib import Path import tempfile from typing import Optional +from uuid import uuid4 +import contextlib
271-275: Avoid extra full pass over idXML just to countget_psm_count likely re-iterates the file; consider omitting or computing during conversion.
334-344: Use Optional[...] in signatures for parameters defaulting to NoneAligns with PEP 484 and resolves Ruff RUF013.
-def convert_quantms_pg_cmd( - mztab_path: Path = None, - database_path: Path = None, - msstats_file: Path = None, - sdrf_file: Path = None, - output_folder: Path = None, - output_prefix: str = "pg", - compute_topn: bool = True, - compute_ibaq: bool = True, - topn: int = 3, - verbose: bool = False, -): +def convert_quantms_pg_cmd( + mztab_path: Optional[Path] = None, + database_path: Optional[Path] = None, + msstats_file: Optional[Path] = None, + sdrf_file: Optional[Path] = None, + output_folder: Optional[Path] = None, + output_prefix: str = "pg", + compute_topn: bool = True, + compute_ibaq: bool = True, + topn: int = 3, + verbose: bool = False, +):
425-427: Parquet: enable compression and dictionary encodingReduce file size and speed up I/O.
- pq.write_table(table, str(output_file)) + pq.write_table(table, str(output_file), compression="zstd", use_dictionary=True)
488-490: Avoid setting the root logger level in CLI commandsSetting the root logger to DEBUG affects the entire app. Prefer configuring only this module’s logger or a dedicated logger hierarchy.
141-169: Expose chunksize as a CLI option (PSM)Large datasets benefit from tuning this; current value is hardcoded.
Example:
@convert.command("quantms-psm") @@ -@click.option("--verbose", help="Enable verbose logging", is_flag=True) +@click.option("--chunksize", help="Rows per batch", default=1_000_000, type=int) +@click.option("--verbose", help="Enable verbose logging", is_flag=True) def convert_quantms_psm_cmd( @@ - verbose: bool = False, + chunksize: int, + verbose: bool = False, ): @@ - psm = Psm(indexer) - psm.convert_to_parquet(output_path=str(output_file), chunksize=1000000) + psm = Psm(indexer) + psm.convert_to_parquet(output_path=str(output_file), chunksize=chunksize)
317-331: Validate topn > 0 when computing TopNPrevent silent misconfiguration.
@click.option( "--topn", help="Number of peptides to use for TopN intensity", default=3, type=int, ) @@ def convert_quantms_pg_cmd( @@ ): + if compute_topn and topn <= 0: + raise click.ClickException("--topn must be > 0 when --compute-topn is enabled.")
186-213: Deduplicate indexer open/create logic into a helperThree near-identical blocks; factor into a function to reduce drift and ease fixes.
Sketch:
def _open_or_create_indexer(mztab_path: Optional[Path], database_path: Optional[Path], sdrf_file: Optional[Path] = None, msstats_file: Optional[Path] = None) -> MzTabIndexer: if database_path and database_path.exists(): return MzTabIndexer.open(database_path=str(database_path), sdrf_path=sdrf_file) if database_path and mztab_path: return MzTabIndexer.create(mztab_path=str(mztab_path), msstats_path=str(msstats_file) if msstats_file else None, sdrf_path=str(sdrf_file) if sdrf_file else None, database_path=str(database_path)) if mztab_path: temp_db_path = str(Path(tempfile.gettempdir()) / f"quantms_{uuid4().hex}.duckdb") return MzTabIndexer.create(mztab_path=str(mztab_path), msstats_path=str(msstats_file) if msstats_file else None, sdrf_path=str(sdrf_file) if sdrf_file else None, database_path=temp_db_path) raise click.ClickException("You must provide either --database-path (existing) or --mztab-path (to create a new indexer).")Also applies to: 377-410, 88-121
tests/core/quantms/psms/test_duckdb_creation.py (6)
31-41: Remove hard-coded local paths from TEST_CASES.Avoid committing user-specific absolute paths. Either remove this param or gate it via an env flag in a separate, locally-run test.
Apply this diff to remove the unused local test case:
- pytest.param( - "pxd020192_duckdb", - Path( - "/Users/yperez/work/quantms.io/tissues/PXD020192/PXD020192.sdrf_openms_design_openms.mzTab.gz" - ), - Path( - "/Users/yperez/work/quantms.io/tissues/PXD020192/PXD020192.sdrf_openms_design_msstats_in.csv.gz" - ), - Path("/Users/yperez/work/quantms.io/tissues/PXD020192/PXD020192.sdrf.tsv"), - marks=pytest.mark.skip(reason="Local test, big data file"), - ),
45-50: Rename test to match current behavior (DuckDB-only) and tighten docstring.The test name/docs still mention Parquet but the implementation is DuckDB-only.
-@pytest.mark.parametrize("test_name, mztab_path, msstats_path, sdrf_path", TEST_CASES) -def test_create_duckdb_and_parquet(test_name, mztab_path, msstats_path, sdrf_path): +@pytest.mark.parametrize("test_name, mztab_path, msstats_path, sdrf_path", TEST_CASES) +def test_create_duckdb_database(test_name, mztab_path, msstats_path, sdrf_path): """ - Test creating a DuckDB database or Parquet store from various mzTab formats. - This single test function is parameterized to run for each case in TEST_CASES. + Test creating a DuckDB database from various mzTab formats. + Parameterized to run for each case in TEST_CASES. """ - # The output path will be a file for duckdb and a directory for parquet + # Output path is a DuckDB fileAlso applies to: 55-56
74-76: Fix incomplete comment.- # Verification logic depends on the used + # Verification logic depends on the backend used
80-90: Assert MSstats table presence when msstats_path is provided.Strengthens verification and prevents silent omissions.
tables = [t[0] for t in con.execute("SHOW TABLES").fetchall()] assert "metadata" in tables and "proteins" in tables and "psms" in tables + if msstats_path: + assert "msstats" in tables, "MSstats table expected when msstats_path is provided" metadata_count = con.execute("SELECT COUNT(*) FROM metadata").fetchone()[0] proteins_count = con.execute("SELECT COUNT(*) FROM proteins").fetchone()[0] psms_count = con.execute("SELECT COUNT(*) FROM psms").fetchone()[0]
171-174: Use the public close() API instead of touching _duckdb.Accessing internals is brittle and bypasses resource cleanup in close().
- mztab_step1._duckdb.close() - mztab_step1._duckdb = None + mztab_step1.close() @@ - mztab_step2._duckdb.close() + mztab_step2.close() @@ - mztab_step1._duckdb.close() - mztab_step1._duckdb = None + mztab_step1.close() @@ - mztab_step2._duckdb.close() + mztab_step2.close() @@ - mztab_new._duckdb.close() + mztab_new.close() @@ - mztab_existing._duckdb.close() + mztab_existing.close() @@ - mztab_new._duckdb.close() + mztab_new.close() @@ - mztab_existing._duckdb.close() + mztab_existing.close()Also applies to: 236-237, 299-301, 360-360, 426-427, 505-506, 571-572, 650-651
653-661: Make cleanup helper use close() with a safe fallback.Ensures full teardown paths execute (e.g., _sdrf_handler release).
def cleanup_mztab_indexer(mztab_indexer): """Clean up MzTabIndexer instance and its connections.""" - if mztab_indexer and hasattr(mztab_indexer, "_duckdb") and mztab_indexer._duckdb: - try: - mztab_indexer._duckdb.close() - except (AttributeError, RuntimeError, OSError): - # Ignore cleanup errors - connection may already be closed or invalid - pass + if not mztab_indexer: + return + try: + if hasattr(mztab_indexer, "close"): + mztab_indexer.close() + elif hasattr(mztab_indexer, "_duckdb") and mztab_indexer._duckdb: + mztab_indexer._duckdb.close() + except (AttributeError, RuntimeError, OSError): + # Ignore cleanup errors - connection may already be closed or invalid + pass
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (10)
quantmsio/commands/convert/quantms.py(1 hunks)quantmsio/core/idxml.py(1 hunks)quantmsio/core/openms.py(2 hunks)quantmsio/core/quantms/feature.py(1 hunks)quantmsio/core/quantms/psm.py(1 hunks)quantmsio/utils/mztab_utils.py(1 hunks)tests/core/idxml/test_idxml_psm.py(1 hunks)tests/core/quantms/psms/test_duckdb_creation.py(1 hunks)tests/core/quantms/psms/test_psm.py(1 hunks)tests/core/quantms/test_feature.py(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- tests/core/quantms/test_feature.py
🧰 Additional context used
🧬 Code graph analysis (9)
quantmsio/utils/mztab_utils.py (3)
quantmsio/utils/pride_utils.py (1)
fetch_modifications_from_mztab_line(518-561)quantmsio/core/fragpipe/fragpipe.py (2)
append(45-46)peptidoform(196-221)quantmsio/core/idxml.py (2)
_process_n_terminal_modification(334-346)_process_c_terminal_modification(348-361)
quantmsio/commands/convert/quantms.py (9)
quantmsio/core/idxml_utils/idxml.py (3)
IdXmlPsm(19-589)convert_to_parquet(503-578)get_psm_count(580-589)quantmsio/core/quantms/mztab.py (10)
MzTabIndexer(114-3019)open(184-220)create(140-181)close(345-350)get_psm_count(1503-1518)get_metadata(1277-1292)get_protein_count(1468-1483)get_protein_details_count(1485-1501)_has_msstats_table(1567-1580)get_msstats(1397-1413)quantmsio/core/project.py (1)
create_uuid_filename(59-62)quantmsio/core/quantms/feature.py (2)
Feature(24-939)write_feature_to_file(639-669)quantmsio/core/quantms/pg.py (3)
MzTabProteinGroups(17-656)quantify_from_msstats_optimized(198-316)_convert_to_parquet_format(188-196)quantmsio/core/quantms/psm.py (2)
Psm(28-740)convert_to_parquet(685-740)quantmsio/utils/file_utils.py (1)
close(419-432)quantmsio/operate/query.py (1)
close(344-348)quantmsio/operate/statistics.py (1)
close(108-112)
tests/core/quantms/psms/test_psm.py (4)
quantmsio/core/quantms/psm.py (5)
Psm(28-740)iter_psm_table(279-311)convert_to_parquet(685-740)_extract_ms_runs(52-72)_get_protein_qvalue(74-116)quantmsio/core/quantms/mztab.py (5)
MzTabIndexer(114-3019)close(345-350)create(140-181)_get_num_psms(1388-1395)get_metadata(1277-1292)quantmsio/utils/mztab_utils.py (6)
fetch_ms_runs_from_mztab_line(327-369)extract_ms_runs_from_metadata(372-418)extract_ms_runs_from_lines(421-452)_clean_file_path(259-288)_is_ms_run_location_line(291-305)_extract_ms_run_id_from_key(308-324)tests/core/quantms/psms/test_mztab_indexer.py (1)
cleanup_test_resources(18-45)
tests/core/quantms/psms/test_duckdb_creation.py (1)
quantmsio/core/quantms/mztab.py (5)
MzTabIndexer(114-3019)create(140-181)close(345-350)open(184-220)add_msstats_table(1640-1701)
quantmsio/core/quantms/psm.py (6)
quantmsio/core/openms.py (1)
get_openms_score_name(350-356)quantmsio/core/quantms/mztab.py (7)
get_metadata(1277-1292)get_protein_best_searchengine_score(1363-1370)_is_protein_score_qvalue(1294-1322)stream_section(1520-1565)_get_table_source(1252-1275)_get_num_psms(1388-1395)close(345-350)quantmsio/utils/file_utils.py (4)
extract_protein_list(58-75)ParquetBatchWriter(341-432)write_batch(370-381)close(419-432)quantmsio/utils/pride_utils.py (3)
generate_scan_number(76-81)get_petidoform_msstats_notation(262-309)standardize_protein_string_accession(176-191)quantmsio/utils/mztab_utils.py (2)
extract_ms_runs_from_metadata(372-418)parse_pepidoform_with_modifications(455-530)quantmsio/core/duckdb.py (1)
cleanup_duckdb(59-78)
quantmsio/core/idxml.py (1)
quantmsio/core/openms.py (3)
OpenMSHandler(14-347)_extract_additional_scores(314-347)get_spectrum_from_scan(21-43)
quantmsio/core/openms.py (2)
quantmsio/utils/mztab_utils.py (1)
parse_peptidoform_openms(738-756)quantmsio/core/idxml.py (1)
_extract_additional_scores(226-259)
quantmsio/core/quantms/feature.py (4)
quantmsio/core/quantms/mztab.py (7)
close(345-350)get_psms(1356-1361)get_metadata(1277-1292)get_proteins(1324-1338)get_msstats_experiment_type(1853-1891)iter_msstats_files(1989-2039)get_unique_from_psm_table(2988-3019)quantmsio/operate/tools.py (1)
get_protein_accession(269-274)quantmsio/utils/file_utils.py (4)
extract_protein_list(58-75)ParquetBatchWriter(341-432)close(419-432)write_batch(370-381)quantmsio/core/duckdb.py (1)
cleanup_duckdb(59-78)
tests/core/idxml/test_idxml_psm.py (2)
quantmsio/core/idxml_utils/idxml.py (4)
IdXmlPsm(19-589)get_psm_count(580-589)iter_psm_table(271-294)convert_to_parquet(503-578)quantmsio/core/openms.py (1)
OpenMSHandler(14-347)
🪛 Ruff (0.13.1)
quantmsio/utils/mztab_utils.py
42-42: Create your own exception
(TRY002)
42-42: Avoid specifying long messages outside the exception class
(TRY003)
51-51: Create your own exception
(TRY002)
51-51: Avoid specifying long messages outside the exception class
(TRY003)
78-80: Create your own exception
(TRY002)
78-80: Avoid specifying long messages outside the exception class
(TRY003)
quantmsio/commands/convert/quantms.py
123-125: Abstract raise to an inner function
(TRY301)
123-125: Avoid specifying long messages outside the exception class
(TRY003)
135-135: Use explicit conversion flag
Replace with conversion flag
(RUF010)
135-135: Redundant exception object included in logging.exception call
(TRY401)
136-136: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling
(B904)
136-136: Avoid specifying long messages outside the exception class
(TRY003)
136-136: Use explicit conversion flag
Replace with conversion flag
(RUF010)
214-216: Abstract raise to an inner function
(TRY301)
214-216: Avoid specifying long messages outside the exception class
(TRY003)
221-221: Use explicit conversion flag
Replace with conversion flag
(RUF010)
221-221: Redundant exception object included in logging.exception call
(TRY401)
222-222: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling
(B904)
222-222: Avoid specifying long messages outside the exception class
(TRY003)
222-222: Use explicit conversion flag
Replace with conversion flag
(RUF010)
277-277: Use explicit conversion flag
Replace with conversion flag
(RUF010)
277-277: Redundant exception object included in logging.exception call
(TRY401)
278-278: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling
(B904)
278-278: Avoid specifying long messages outside the exception class
(TRY003)
278-278: Use explicit conversion flag
Replace with conversion flag
(RUF010)
334-334: PEP 484 prohibits implicit Optional
Convert to Optional[T]
(RUF013)
335-335: PEP 484 prohibits implicit Optional
Convert to Optional[T]
(RUF013)
336-336: PEP 484 prohibits implicit Optional
Convert to Optional[T]
(RUF013)
337-337: PEP 484 prohibits implicit Optional
Convert to Optional[T]
(RUF013)
338-338: PEP 484 prohibits implicit Optional
Convert to Optional[T]
(RUF013)
411-413: Abstract raise to an inner function
(TRY301)
411-413: Avoid specifying long messages outside the exception class
(TRY003)
430-430: Use explicit conversion flag
Replace with conversion flag
(RUF010)
430-430: Redundant exception object included in logging.exception call
(TRY401)
431-431: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling
(B904)
431-431: Avoid specifying long messages outside the exception class
(TRY003)
431-431: Use explicit conversion flag
Replace with conversion flag
(RUF010)
480-480: PEP 484 prohibits implicit Optional
Convert to Optional[T]
(RUF013)
510-512: Abstract raise to an inner function
(TRY301)
510-512: Avoid specifying long messages outside the exception class
(TRY003)
533-533: f-string without any placeholders
Remove extraneous f prefix
(F541)
544-544: Do not catch blind exception: Exception
(BLE001)
548-548: Use explicit conversion flag
Replace with conversion flag
(RUF010)
548-548: Redundant exception object included in logging.exception call
(TRY401)
549-549: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling
(B904)
549-549: Avoid specifying long messages outside the exception class
(TRY003)
549-549: Use explicit conversion flag
Replace with conversion flag
(RUF010)
tests/core/quantms/psms/test_psm.py
45-45: Do not catch blind exception: Exception
(BLE001)
58-58: Do not catch blind exception: Exception
(BLE001)
299-302: Avoid equality comparisons to True; use ...: for truth checks
Replace comparison
(E712)
304-304: Avoid equality comparisons to False; use not ...: for false checks
Replace comparison
(E712)
305-305: Avoid equality comparisons to False; use not ...: for false checks
Replace comparison
(E712)
566-566: f-string without any placeholders
Remove extraneous f prefix
(F541)
570-570: Loop control variable i not used within loop body
(B007)
tests/core/quantms/psms/test_duckdb_creation.py
137-137: f-string without any placeholders
Remove extraneous f prefix
(F541)
166-166: f-string without any placeholders
Remove extraneous f prefix
(F541)
226-226: f-string without any placeholders
Remove extraneous f prefix
(F541)
263-263: f-string without any placeholders
Remove extraneous f prefix
(F541)
293-293: f-string without any placeholders
Remove extraneous f prefix
(F541)
350-350: f-string without any placeholders
Remove extraneous f prefix
(F541)
385-385: f-string without any placeholders
Remove extraneous f prefix
(F541)
419-419: f-string without any placeholders
Remove extraneous f prefix
(F541)
472-472: f-string without any placeholders
Remove extraneous f prefix
(F541)
499-499: f-string without any placeholders
Remove extraneous f prefix
(F541)
530-530: f-string without any placeholders
Remove extraneous f prefix
(F541)
564-564: f-string without any placeholders
Remove extraneous f prefix
(F541)
617-617: f-string without any placeholders
Remove extraneous f prefix
(F541)
644-644: f-string without any placeholders
Remove extraneous f prefix
(F541)
quantmsio/core/quantms/psm.py
68-68: Consider moving this statement to an else block
(TRY300)
70-70: Do not catch blind exception: Exception
(BLE001)
114-114: Do not catch blind exception: Exception
(BLE001)
173-173: Do not catch blind exception: Exception
(BLE001)
274-274: Consider moving this statement to an else block
(TRY300)
275-275: Do not catch blind exception: Exception
(BLE001)
455-455: Consider moving this statement to an else block
(TRY300)
457-457: Do not catch blind exception: Exception
(BLE001)
526-526: f-string without any placeholders
Remove extraneous f prefix
(F541)
598-598: Do not catch blind exception: Exception
(BLE001)
599-599: Use logging.exception instead of logging.error
Replace with exception
(TRY400)
619-628: Possible SQL injection vector through string-based query construction
(S608)
666-666: Do not catch blind exception: Exception
(BLE001)
667-667: Use logging.exception instead of logging.error
Replace with exception
(TRY400)
676-676: Prefer TypeError exception for invalid type
(TRY004)
676-676: Create your own exception
(TRY002)
676-676: Avoid specifying long messages outside the exception class
(TRY003)
678-678: Create your own exception
(TRY002)
678-678: Avoid specifying long messages outside the exception class
(TRY003)
681-681: Create your own exception
(TRY002)
681-681: Avoid specifying long messages outside the exception class
(TRY003)
682-682: Loop control variable df overrides iterable it iterates
(B020)
quantmsio/core/idxml.py
56-56: Use logging.exception instead of logging.error
Replace with exception
(TRY400)
147-168: Consider moving this statement to an else block
(TRY300)
170-170: Do not catch blind exception: Exception
(BLE001)
561-561: Do not catch blind exception: Exception
(BLE001)
609-609: Do not catch blind exception: Exception
(BLE001)
628-628: Value being cast to int is already an integer
Remove unnecessary int call
(RUF046)
634-634: Do not catch blind exception: Exception
(BLE001)
quantmsio/core/openms.py
187-187: Consider moving this statement to an else block
(TRY300)
188-188: Do not catch blind exception: Exception
(BLE001)
224-224: Consider moving this statement to an else block
(TRY300)
quantmsio/core/quantms/feature.py
124-124: Consider moving this statement to an else block
(TRY300)
126-126: Do not catch blind exception: Exception
(BLE001)
327-327: Consider moving this statement to an else block
(TRY300)
328-328: Do not catch blind exception: Exception
(BLE001)
350-350: Consider moving this statement to an else block
(TRY300)
351-351: Do not catch blind exception: Exception
(BLE001)
363-363: Consider moving this statement to an else block
(TRY300)
364-364: Do not catch blind exception: Exception
(BLE001)
421-421: Consider moving this statement to an else block
(TRY300)
422-422: Do not catch blind exception: Exception
(BLE001)
568-568: Function definition does not bind loop variable i
(B023)
631-631: Function definition does not bind loop variable i
(B023)
tests/core/idxml/test_idxml_psm.py
125-125: Use logging.exception instead of logging.error
Replace with exception
(TRY400)
126-126: Use logging.exception instead of logging.error
Replace with exception
(TRY400)
129-129: Use logging.exception instead of logging.error
Replace with exception
(TRY400)
200-200: Do not assert blind exception: Exception
(B017)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: unit-tests
- GitHub Check: unit-tests (3.11)
- GitHub Check: unit-tests
- GitHub Check: unit-tests (3.10)
🔇 Additional comments (18)
quantmsio/core/quantms/feature.py (3)
626-633: Bind loop variable in lambda to avoid late-binding bug (duplicate of previous fix).- ].apply( - lambda rows: merge_psm(rows, i), - axis=1, - ) + ].apply( + lambda rows, idx=i: merge_psm(rows, idx), + axis=1, + )
682-717: Anchor protein becomes list then coerced to string; confirm schema expectations.
anchor_proteinis converted to list, later cast to str; result looks like "['P12345']". Verify FEATURE_SCHEMA expects a string, or normalize to single accession/first item before casting.Would you like a patch to keep
anchor_proteinas a scalar consistently?
553-561: Fix key mismatch: cast precursor_charge to str when building the lookup key.
map_dictuses charge as string; this path uses int, causing misses.- key = ( - rows["reference_file_name"], - rows["peptidoform"], - rows["precursor_charge"], - ) + key = ( + rows["reference_file_name"], + rows["peptidoform"], + str(rows["precursor_charge"]), + )tests/core/idxml/test_idxml_psm.py (1)
60-64: LGTM: safe temp file creation.Good use of NamedTemporaryFile(delete=False) and cleanup.
tests/core/quantms/psms/test_psm.py (1)
78-84: LGTM: safe temp path creation and cleanup pattern.Also applies to: 107-113, 143-152, 189-195, 356-361, 449-454, 606-611
quantmsio/core/quantms/psm.py (3)
150-159: Avoid astype(int) before dropping NaNs when extracting score indices.- score_df.loc[:, "mztab_score_name"] = ( - score_df["key"].str.extract(r"\[(\d+)\]").astype(int) - ) + score_df.loc[:, "mztab_score_name"] = pd.to_numeric( + score_df["key"].str.extract(r"\[(\d+)\]")[0], errors="coerce" + ) score_df.loc[:, "name_term"] = ( score_df["value"].str.split(",").str[2].str.strip() ) - # Drop rows where extraction failed - score_df.dropna(subset=["mztab_score_name", "name_term"], inplace=True) + score_df.dropna(subset=["mztab_score_name", "name_term"], inplace=True) + score_df.loc[:, "mztab_score_name"] = score_df["mztab_score_name"].astype(int)
544-546: Fix typo: “consesus_support” → “consensus_support”.- struct = { - "cv_name": "consesus_support", + struct = { + "cv_name": "consensus_support", "cv_value": str(consensus_support), }
652-658: Fix ms_run mapping and guard score conversion in extract_from_pep.- ref_file = None - if pd.notna(row["spectra_ref"]): - try: - ms_run_id = row["spectra_ref"].split(":")[0] - ref_file = self._ms_runs.get(ms_run_id) - except (ValueError, AttributeError): - pass + ref_file = None + if pd.notna(row["spectra_ref"]): + ref_file = self._get_reference_file_name(row["spectra_ref"]) - if key not in pep_map or row["score"] < pep_map[key][0]: - pep_map[key] = [row["score"], ref_file, scan_number] + try: + score_val = float(row["score"]) + except (TypeError, ValueError): + continue + if key not in pep_map or score_val < pep_map[key][0]: + pep_map[key] = [score_val, ref_file, scan_number]Also applies to: 660-663
quantmsio/core/openms.py (1)
291-309: Don’t overwrite existing mod entries when adding terminal mods.Appending N-/C‑term positions must not replace residue‑level entries having the same mod name.
- if peptide_sequence.hasCTerminalModification(): + if peptide_sequence.hasCTerminalModification(): c_term_mod = peptide_sequence.getCTerminalModification() c_term_pos = f"C-term.{sequence_length + 1}" - modifications[c_term_mod.getName()] = { - "name": c_term_mod.getName(), - "accession": c_term_mod.getUniModAccession(), - "fields": [{"position": c_term_pos, "scores": []}], - } + entry = modifications.setdefault( + c_term_mod.getName(), + { + "name": c_term_mod.getName(), + "accession": c_term_mod.getUniModAccession(), + "fields": [], + }, + ) + entry["fields"].append({"position": c_term_pos, "scores": []}) - if peptide_sequence.hasNTerminalModification(): + if peptide_sequence.hasNTerminalModification(): n_term_mod = peptide_sequence.getNTerminalModification() n_term_pos = "N-term.0" - modifications[n_term_mod.getName()] = { - "name": n_term_mod.getName(), - "accession": n_term_mod.getUniModAccession(), - "fields": [{"position": n_term_pos, "scores": []}], - } + entry = modifications.setdefault( + n_term_mod.getName(), + { + "name": n_term_mod.getName(), + "accession": n_term_mod.getUniModAccession(), + "fields": [], + }, + ) + entry["fields"].append({"position": n_term_pos, "scores": []})quantmsio/commands/convert/quantms.py (9)
134-137: Preserve traceback and simplify logging in exception pathUse logger.exception without embedding the exception, and chain ClickException with “from e”.
- except Exception as e: - logger.exception(f"Error in feature conversion: {str(e)}") - raise click.ClickException(f"Error: {str(e)}\nCheck the logs for more details.") + except Exception as e: + logger.exception("Error in feature conversion") + raise click.ClickException("Error: %s\nCheck the logs for more details." % e) from e
220-223: Preserve traceback and simplify logging (PSM)- except Exception as e: - logger.exception(f"Error in PSM conversion: {str(e)}") - raise click.ClickException(f"Error: {str(e)}\nCheck the logs for more details.") + except Exception as e: + logger.exception("Error in PSM conversion") + raise click.ClickException("Error: %s\nCheck the logs for more details." % e) from e
276-279: Preserve traceback and simplify logging (idXML)- except Exception as e: - logger.exception(f"Error in idXML PSM conversion: {str(e)}") - raise click.ClickException(f"Error: {str(e)}\nCheck the logs for more details.") + except Exception as e: + logger.exception("Error in idXML PSM conversion") + raise click.ClickException("Error: %s\nCheck the logs for more details." % e) from e
429-432: Preserve traceback and simplify logging (PG)- except Exception as e: - logger.exception(f"Error in mzTab protein group conversion: {str(e)}") - raise click.ClickException(f"Error: {str(e)}\nCheck the logs for more details.") + except Exception as e: + logger.exception("Error in mzTab protein group conversion") + raise click.ClickException("Error: %s\nCheck the logs for more details." % e) from e
500-523: LGTM on backend selection and output path checksConfirm MzTabIndexer.create supports backend="parquet" with database_path as a directory as used here.
88-105: Nice: consistent open-or-create flow and composition with Feature
185-199: Nice: consistent open-or-create flow and composition with Psm
415-427: Good use of context manager for PG to guarantee cleanup
377-410: Repeat: safer temp DB path generation (no pre-create/unlink)- elif mztab_path: - # No database_path provided, create a temporary one - temp_db_file = tempfile.NamedTemporaryFile(suffix=".duckdb", delete=False) - temp_db_path = temp_db_file.name - temp_db_file.close() - if os.path.exists(temp_db_path): - os.unlink(temp_db_path) + elif mztab_path: + # No database_path provided, generate a unique temporary path (file must not exist) + temp_db_path = str(Path(tempfile.gettempdir()) / f"quantms_{uuid4().hex}.duckdb") logger.info( f"Creating temporary MzTabIndexer at {temp_db_path} from {mztab_path}" )Likely an incorrect or invalid review comment.
| elif mztab_path: | ||
| # No database_path provided, create a temporary one | ||
| temp_db_file = tempfile.NamedTemporaryFile(suffix=".duckdb", delete=False) | ||
| temp_db_path = temp_db_file.name | ||
| temp_db_file.close() | ||
| if os.path.exists(temp_db_path): | ||
| os.unlink(temp_db_path) | ||
| logger.info( | ||
| f"Creating temporary MzTabIndexer at {temp_db_path} from {mztab_path}" | ||
| ) | ||
| indexer = MzTabIndexer.create( | ||
| mztab_path=str(mztab_path), | ||
| msstats_path=msstats_file, | ||
| sdrf_path=sdrf_file, | ||
| database_path=temp_db_path, | ||
| ) |
There was a problem hiding this comment.
Avoid TOCTOU: don’t pre-create then unlink temp DB file
Generating a unique path without creating the file removes the race window and keeps MzTabIndexer.create precondition (path must not exist).
- # No database_path provided, create a temporary one
- temp_db_file = tempfile.NamedTemporaryFile(suffix=".duckdb", delete=False)
- temp_db_path = temp_db_file.name
- temp_db_file.close()
- if os.path.exists(temp_db_path):
- os.unlink(temp_db_path)
+ # No database_path provided, generate a unique temporary path (file must not exist)
+ temp_db_path = str(Path(tempfile.gettempdir()) / f"quantms_{uuid4().hex}.duckdb")
logger.info(
f"Creating temporary MzTabIndexer at {temp_db_path} from {mztab_path}"
)Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In quantmsio/commands/convert/quantms.py around lines 106–121, avoid creating
then unlinking a temp file (TOCTOU) before calling MzTabIndexer.create; instead
generate a unique non-existent path and pass that: build a candidate path in the
system temp dir (e.g. tempfile.gettempdir()) combined with a UUID and the
".duckdb" suffix, loop/retry if os.path.exists until you have a non-existent
name, ensure uuid and tempfile are imported, then call MzTabIndexer.create with
that path (without creating the file beforehand).
| # No database_path provided, create a temporary one | ||
| temp_db_file = tempfile.NamedTemporaryFile(suffix=".duckdb", delete=False) | ||
| temp_db_path = temp_db_file.name | ||
| temp_db_file.close() | ||
| if os.path.exists(temp_db_path): | ||
| os.unlink(temp_db_path) | ||
| logger.info( | ||
| f"Creating temporary MzTabIndexer at {temp_db_path} from {mztab_path}" | ||
| ) | ||
| indexer = MzTabIndexer.create( | ||
| mztab_path=str(mztab_path), | ||
| database_path=temp_db_path, | ||
| ) | ||
| else: |
There was a problem hiding this comment.
Repeat: safer temp DB path generation (no pre-create/unlink)
- elif mztab_path:
- # No database_path provided, create a temporary one
- temp_db_file = tempfile.NamedTemporaryFile(suffix=".duckdb", delete=False)
- temp_db_path = temp_db_file.name
- temp_db_file.close()
- if os.path.exists(temp_db_path):
- os.unlink(temp_db_path)
+ elif mztab_path:
+ # No database_path provided, generate a unique temporary path (file must not exist)
+ temp_db_path = str(Path(tempfile.gettempdir()) / f"quantms_{uuid4().hex}.duckdb")
logger.info(
f"Creating temporary MzTabIndexer at {temp_db_path} from {mztab_path}"
)Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In quantmsio/commands/convert/quantms.py around lines 200-213, the temp DB path
is being created then immediately unlinked (pre-creating and deleting the file),
which is unnecessary and unsafe; instead generate a safe temporary pathname
without the create/delete dance by using the OS temp function (e.g.,
tempfile.mkstemp or NamedTemporaryFile with delete=False) to obtain a unique
path, close the returned file descriptor, do NOT unlink the file, and pass that
path to MzTabIndexer.create so the indexer can create the DB file itself; remove
the os.path.exists/unlink logic and ensure the temporary file descriptor is
closed before calling MzTabIndexer.
| # Log some basic statistics | ||
| try: | ||
| metadata_count = len(indexer.get_metadata()) | ||
| protein_count = indexer.get_protein_count() | ||
| protein_details_count = indexer.get_protein_details_count() | ||
| psm_count = indexer.get_psm_count() | ||
|
|
||
| logger.info(f"Successfully processed:") | ||
| logger.info(f" - Metadata entries: {metadata_count:,}") | ||
| logger.info(f" - Proteins: {protein_count:,}") | ||
| logger.info(f" - Protein details: {protein_details_count:,}") | ||
| logger.info(f" - PSMs: {psm_count:,}") | ||
|
|
||
| if indexer._has_msstats_table(): | ||
| msstats_data = indexer.get_msstats() | ||
| if msstats_data is not None: | ||
| logger.info(f" - MSstats entries: {len(msstats_data):,}") | ||
|
|
||
| except Exception as stats_error: | ||
| logger.warning(f"Could not retrieve statistics: {stats_error}") | ||
|
|
There was a problem hiding this comment.
Always close indexer to release DB handles
Ensure DuckDB/Parquet resources are freed even if stats gathering fails.
- # Log some basic statistics
- try:
+ # Log some basic statistics
+ try:
metadata_count = len(indexer.get_metadata())
protein_count = indexer.get_protein_count()
protein_details_count = indexer.get_protein_details_count()
psm_count = indexer.get_psm_count()
- logger.info(f"Successfully processed:")
+ logger.info("Successfully processed:")
logger.info(f" - Metadata entries: {metadata_count:,}")
logger.info(f" - Proteins: {protein_count:,}")
logger.info(f" - Protein details: {protein_details_count:,}")
logger.info(f" - PSMs: {psm_count:,}")
- if indexer._has_msstats_table():
- msstats_data = indexer.get_msstats()
- if msstats_data is not None:
- logger.info(f" - MSstats entries: {len(msstats_data):,}")
+ msstats_data = indexer.get_msstats()
+ if msstats_data is not None:
+ logger.info(f" - MSstats entries: {len(msstats_data):,}")
except Exception as stats_error:
logger.warning(f"Could not retrieve statistics: {stats_error}")
+ finally:
+ if indexer is not None:
+ with contextlib.suppress(Exception):
+ indexer.close()📝 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.
| # Log some basic statistics | |
| try: | |
| metadata_count = len(indexer.get_metadata()) | |
| protein_count = indexer.get_protein_count() | |
| protein_details_count = indexer.get_protein_details_count() | |
| psm_count = indexer.get_psm_count() | |
| logger.info(f"Successfully processed:") | |
| logger.info(f" - Metadata entries: {metadata_count:,}") | |
| logger.info(f" - Proteins: {protein_count:,}") | |
| logger.info(f" - Protein details: {protein_details_count:,}") | |
| logger.info(f" - PSMs: {psm_count:,}") | |
| if indexer._has_msstats_table(): | |
| msstats_data = indexer.get_msstats() | |
| if msstats_data is not None: | |
| logger.info(f" - MSstats entries: {len(msstats_data):,}") | |
| except Exception as stats_error: | |
| logger.warning(f"Could not retrieve statistics: {stats_error}") | |
| # Log some basic statistics | |
| try: | |
| metadata_count = len(indexer.get_metadata()) | |
| protein_count = indexer.get_protein_count() | |
| protein_details_count = indexer.get_protein_details_count() | |
| psm_count = indexer.get_psm_count() | |
| logger.info("Successfully processed:") | |
| logger.info(f" - Metadata entries: {metadata_count:,}") | |
| logger.info(f" - Proteins: {protein_count:,}") | |
| logger.info(f" - Protein details: {protein_details_count:,}") | |
| logger.info(f" - PSMs: {psm_count:,}") | |
| msstats_data = indexer.get_msstats() | |
| if msstats_data is not None: | |
| logger.info(f" - MSstats entries: {len(msstats_data):,}") | |
| except Exception as stats_error: | |
| logger.warning(f"Could not retrieve statistics: {stats_error}") | |
| finally: | |
| if indexer is not None: | |
| with contextlib.suppress(Exception): | |
| indexer.close() |
🧰 Tools
🪛 Ruff (0.13.1)
533-533: f-string without any placeholders
Remove extraneous f prefix
(F541)
544-544: Do not catch blind exception: Exception
(BLE001)
🤖 Prompt for AI Agents
In quantmsio/commands/convert/quantms.py around lines 526 to 546, the indexer DB
handles are not guaranteed to be released if gathering statistics raises an
exception; ensure the indexer is closed in all cases by calling its close() (or
using its context manager) in a finally block after the stats try/except, or
wrap the entire stats retrieval in a with indexer: block so DuckDB/Parquet
resources are always freed even when errors occur.
| if modification == "": | ||
| return {} | ||
| accession = modification.split("-")[1] | ||
| unimod_accession = accession |
There was a problem hiding this comment.
Don’t drop all mods on empty token; skip empties and harden parsing.
Current logic returns {} when encountering an empty item (e.g., trailing comma). This discards parsed modifications.
- if modification == "":
- return {}
- accession = modification.split("-")[1]
+ if modification == "":
+ continue
+ parts = modification.split("-", 1)
+ if len(parts) != 2:
+ continue
+ accession = parts[1]Also consider raising ValueError instead of Exception for unknown accessions.
Also applies to: 66-81
🤖 Prompt for AI Agents
In quantmsio/utils/mztab_utils.py around lines 66 to 81, the code currently
returns {} when encountering an empty modification token (e.g., trailing comma)
and uses a generic Exception for unknown accessions; instead, change the loop to
skip empty tokens (continue) rather than returning early, validate the split
result length and that the expected segment exists before indexing (if not,
continue or raise ValueError with a clear message), map unknown accessions by
raising ValueError rather than Exception, and ensure the function accumulates
parsed modifications and returns the full mapping rather than discarding parsed
items when an empty token is encountered.
| if not mztab_path.exists(): | ||
| pytest.skip(f"Test file not found: {mztab_path}") | ||
|
|
There was a problem hiding this comment.
Skip early if any required input file is missing.
Currently only mzTab is checked; missing MSstats/SDRF files will error.
- if not mztab_path.exists():
- pytest.skip(f"Test file not found: {mztab_path}")
+ missing = [p for p in (mztab_path, msstats_path, sdrf_path) if not Path(p).exists()]
+ if missing:
+ pytest.skip(f"Test files not found: {', '.join(map(str, missing))}")📝 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.
| if not mztab_path.exists(): | |
| pytest.skip(f"Test file not found: {mztab_path}") | |
| missing = [p for p in (mztab_path, msstats_path, sdrf_path) if not Path(p).exists()] | |
| if missing: | |
| pytest.skip(f"Test files not found: {', '.join(map(str, missing))}") |
🤖 Prompt for AI Agents
In tests/core/quantms/psms/test_duckdb_creation.py around lines 51 to 53, the
test only checks for mztab_path and skips if missing, but does not check other
required input files (e.g., MSstats and SDRF), which causes errors later; update
the precondition to verify existence of all required paths (mztab_path,
msstats_path, sdrf_path or whatever variables hold those input files), and if
any are missing call pytest.skip with a clear message listing the missing
file(s) so the test is skipped early when any required input is absent.
| with tempfile.TemporaryDirectory() as temp_dir: | ||
| output_path = Path(temp_dir) / "test_two_step.duckdb" | ||
|
|
||
| print(f"\n=== Testing Two-Step Creation Process ===") |
There was a problem hiding this comment.
Fix Ruff F541: remove f-strings without placeholders.
These will fail linting.
- print(f"\n=== Testing Two-Step Creation Process ===")
+ print("\n=== Testing Two-Step Creation Process ===")
@@
- print(f"Initial database created with:")
+ print("Initial database created with:")
@@
- print(f"\nFinal database contains:")
+ print("\nFinal database contains:")
@@
- print(f"\n=== Testing Two-Step Creation Process (TMT) ===")
+ print("\n=== Testing Two-Step Creation Process (TMT) ===")
@@
- print(f"Initial database created with:")
+ print("Initial database created with:")
@@
- print(f"\nFinal database contains:")
+ print("\nFinal database contains:")
@@
- print(f"\n=== Testing Create vs Open Database with Class Methods ===")
+ print("\n=== Testing Create vs Open Database with Class Methods ===")
@@
- print(f"New database created with:")
+ print("New database created with:")
@@
- print(f"Existing database opened with:")
+ print("Existing database opened with:")
@@
- print(f"\nSummary:")
+ print("\nSummary:")
@@
- print(f"\n=== Testing Create vs Open Database with Class Methods (TMT) ===")
+ print("\n=== Testing Create vs Open Database with Class Methods (TMT) ===")
@@
- print(f"New database created with:")
+ print("New database created with:")
@@
- print(f"Existing database opened with:")
+ print("Existing database opened with:")
@@
- print(f"\nSummary:")
+ print("\nSummary:")Also applies to: 166-166, 226-226, 263-263, 293-293, 350-350, 385-385, 419-419, 472-472, 499-499, 530-530, 564-564, 617-617, 644-644
🧰 Tools
🪛 Ruff (0.13.1)
137-137: f-string without any placeholders
Remove extraneous f prefix
(F541)
🤖 Prompt for AI Agents
In tests/core/quantms/psms/test_duckdb_creation.py around line 137 (and also
lines 166, 226, 263, 293, 350, 385, 419, 472, 499, 530, 564, 617, 644), there
are f-strings used without any placeholders which triggers Ruff F541; replace
those f-strings with plain string literals (remove the leading f) or use
print(...) without f-string formatting so the strings are regular non-f-strings
to satisfy the linter.
Add optional spectral data fields
There was a problem hiding this comment.
Actionable comments posted: 13
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (4)
docs/README.adoc (4)
783-789: Broken cross-reference: use <>The anchor defined later is [[diann-scan]], but here it references <>.
-| <<scan-diann>> +| <<diann-scan>>
1298-1307: Duplicate anchor [[scan]][[scan]] is already defined earlier (Line 168-171). Duplicate IDs break xrefs in Asciidoc.
- Remove the second [[scan]] anchor or rename it (e.g., [[diann-scan]] already exists below).
904-906: Duplicate anchor [[peptidoform]]This anchor is already defined above (Line 109-117). Remove or rename to avoid ID collision.
112-114: Typo: “show be written” → “should be written”Minor wording fix.
-The peptidoform show be written +The peptidoform should be written
🧹 Nitpick comments (22)
quantmsio/core/idxml_utils/idxml.py (4)
159-162: Remove unused parameter from iterator signature.spectral_data is unused in iter_idxml_psms; drop it to avoid confusion.
Apply:
- def iter_idxml_psms( - self, batch_size: int = 1000, spectral_data: bool = False - ) -> Iterator[List[Dict[str, Any]]]: + def iter_idxml_psms(self, batch_size: int = 1000) -> Iterator[List[Dict[str, Any]]]:
49-53: Avoid pre-loading all PSMs into memory.Building self.psm_records defeats streaming; remove eager materialization to reduce memory footprint for large files.
Apply:
- self.psm_records = [] - for batch in self.iter_idxml_psms(): - self.psm_records.extend(batch) - self.logger.info(f"Loaded {len(self.psm_records)} PSM records") + # Stream on demand via iter_idxml_psms()/iter_psm_table() to minimize memory.
439-449: Use logging.exception for traceback; reduce noisy multi-logs.Consolidate into a single exception log; keep minimal context.
Apply:
- except Exception as e: - self.logger.error(f"=== DEBUG: Error transforming PSM record: {e} ===") - self.logger.error(f"=== DEBUG: Record keys: {list(record.keys())} ===") - self.logger.error( - f"=== DEBUG: Record sample: {dict(list(record.items())[:5])} ===" - ) - import traceback - - self.logger.error( - f"=== DEBUG: Transformation traceback: {traceback.format_exc()} ===" - ) - return None + except Exception: + self.logger.exception("Error transforming PSM record") + return None
532-532: Remove unnecessary f-prefix in constant string.Minor cleanup; appeases linters.
Apply:
- logger.info(f"=== DEBUG: convert_to_parquet started ===") + logger.info("=== DEBUG: convert_to_parquet started ===")quantmsio/core/idxml.py (7)
19-20: Don’t configure root logging in a library module.Remove logging.basicConfig; let applications configure logging.
Apply:
-logging.basicConfig(format="%(asctime)s - %(message)s", level=logging.INFO) -logger = logging.getLogger(__name__) +logger = logging.getLogger(__name__)
96-105: Decoy detection should fall back to protein evidence.If target_decoy meta is absent, check peptide evidences with “DECOY_” prefix like OpenMSHandler._is_decoy.
Apply:
def _determine_is_decoy_generic(self, hit_object) -> int: - """Determine if a hit is decoy based on target_decoy metadata value only""" + """Determine if a hit is decoy using target_decoy meta; fallback to evidence.""" try: target_decoy_value = hit_object.getMetaValue("target_decoy") if target_decoy_value is not None: return 1 if str(target_decoy_value).lower() == "decoy" else 0 except (AttributeError, ValueError, TypeError): pass - return 0 + try: + evidences = hit_object.getPeptideEvidences() + return 1 if any(ev.getAccesssion().startswith("DECOY_") for ev in evidences) else 0 + except Exception: + return 0
68-69: Log full traceback on parse failures.Use logging.exception to keep stack trace.
Apply:
- except Exception as e: - logging.error(f"Error parsing IdXML file with pyopenms: {e}") + except Exception: + logging.exception("Error parsing IdXML file with pyopenms") raise
585-587: Use logging.exception when mzML attach fails.Apply:
- except Exception as e: - method_name = "OnDiscExperiment" if self._use_ondisc else "traditional" - logging.warning(f"Failed to attach mzML spectra using {method_name}: {e}") + except Exception: + method_name = "OnDiscExperiment" if self._use_ondisc else "traditional" + logging.exception(f"Failed to attach mzML spectra using {method_name}")
632-634: Use logging.exception for spectrum fetch errors (traditional).Apply:
- except (ValueError, Exception) as e: - logging.warning(f"Error fetching spectrum (scan={scan_value}): {e}") + except Exception: + logging.exception(f"Error fetching spectrum (scan={scan_value})") psm["number_peaks"] = psm["mz_array"] = psm["intensity_array"] = None
657-659: Use logging.exception for spectrum fetch errors (OnDisc).Apply:
- except (ValueError, IndexError, Exception) as e: - logging.warning(f"Error fetching spectrum (scan={scan_value}): {e}") + except Exception: + logging.exception(f"Error fetching spectrum (scan={scan_value})") psm["number_peaks"] = psm["mz_array"] = psm["intensity_array"] = None
651-651: Drop redundant int() around len().Apply:
- psm["number_peaks"] = int(len(spectrum_mz)) + psm["number_peaks"] = len(spectrum_mz)quantmsio/core/quantms/psm.py (2)
670-671: Log full traceback when extract_from_pep fails.Apply:
- except Exception as e: - self.logger.error(f"Error extracting peptide information: {e}") + except Exception: + self.logger.exception("Error extracting peptide information") return {}
529-529: Remove unnecessary f-prefix.Apply:
- self.logger.warning(f"Could not convert global_qvalue to float") + self.logger.warning("Could not convert global_qvalue to float")quantmsio/commands/convert/idxml.py (2)
38-44: Align function signature with Path types and new flag.Type the parameters as Path and accept the new use_ondisc flag.
-def convert_idxml_file( - idxml_file: Union[Path, str], - output_folder: str, - mzml_file: Optional[Union[Path, str]], - output_prefix_file: Optional[str], - spectral_data: bool = False, -) -> None: +def convert_idxml_file( + idxml_file: Path, + output_folder: Path, + mzml_file: Optional[Path], + output_prefix_file: str, + spectral_data: bool = False, + use_ondisc: bool = False, +) -> None:
46-58: Remove redundant required check; ensure output dir exists; use Path-joins; passuse_ondisc.Click enforces required options; rely on that. Create the output folder and use Path for joins. Pass
use_ondiscthrough to IdXML.- if idxml_file is None or output_folder is None: - raise click.UsageError("Please provide all the required parameters") - - if not output_prefix_file: - output_prefix_file = "psm" - - parser = IdXML( - idxml_path=idxml_file, mzml_path=mzml_file, spectral_data=spectral_data - ) - output_path = ( - f"{output_folder}/{create_uuid_filename(output_prefix_file, '.psm.parquet')}" - ) - parser.to_parquet(output_path) + output_folder.mkdir(parents=True, exist_ok=True) + + parser = IdXML( + idxml_path=idxml_file, + mzml_path=mzml_file, + use_ondisc=use_ondisc, + spectral_data=spectral_data, + ) + output_path = output_folder / create_uuid_filename( + output_prefix_file, ".psm.parquet" + ) + parser.to_parquet(output_path)As per coding guidelines.
quantmsio/commands/convert/maxquant.py (4)
79-83: Drop redundant required-args check.Click already enforces required options; this branch is unreachable and flagged by linters.
- if not all([msms_file, output_folder]): - raise click.UsageError("ERROR: Please provide all required parameters")
183-186: Drop redundant required-args check (feature).Same as PSM; Click ensures required args.
- if not all([evidence_file, sdrf_file, output_folder]): - raise click.UsageError("ERROR: Please provide all required parameters")
290-293: Drop redundant required-args check (PG).Click handles this; remove the branch.
- if not all([protein_groups_file, sdrf_file, output_folder]): - raise click.UsageError("ERROR: Please provide all required parameters")
16-20: Optional: avoid defining a local Click group here.These commands are re-registered under the top-level CLI; consider exporting plain
@click.commandcallables and dropping this file’sconvertgroup and__main__block to reduce duplication.Also applies to: 323-325
quantmsio/commands/convert/quantms.py (1)
346-356: Type hints: use Optional for parameters defaulting to NonePEP 484 discourages implicit Optional.
-def convert_quantms_pg_cmd( - mztab_path: Path = None, - database_path: Path = None, - msstats_file: Path = None, - sdrf_file: Path = None, - output_folder: Path = None, +def convert_quantms_pg_cmd( + mztab_path: Optional[Path] = None, + database_path: Optional[Path] = None, + msstats_file: Optional[Path] = None, + sdrf_file: Optional[Path] = None, + output_folder: Optional[Path] = None,quantmsio/core/maxquant/maxquant.py (2)
28-29: Don’t configure root logging in a library module
logging.basicConfigin library code affects host apps/tests.-logging.basicConfig(format="%(asctime)s - %(message)s", level=logging.INFO) logger = logging.getLogger(__name__)
586-589: Narrow broad excepts and use logger.exception where appropriateCatching bare
Exceptionhides real errors; prefer specific exceptions or re-raise after logging.If you want, I can sweep the module for
except Exceptionand propose targeted exception types.Also applies to: 981-983, 1276-1280, 1444-1447, 1547-1549
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (10)
docs/README.adoc(9 hunks)quantmsio/commands/convert/idxml.py(1 hunks)quantmsio/commands/convert/maxquant.py(1 hunks)quantmsio/commands/convert/quantms.py(1 hunks)quantmsio/core/format.py(10 hunks)quantmsio/core/idxml.py(1 hunks)quantmsio/core/idxml_utils/idxml.py(1 hunks)quantmsio/core/maxquant/maxquant.py(1 hunks)quantmsio/core/quantms/psm.py(1 hunks)quantmsio/quantmsioc.py(3 hunks)
🧰 Additional context used
🧬 Code graph analysis (8)
quantmsio/quantmsioc.py (17)
quantmsio/commands/convert/quantms.py (5)
convert(23-25)convert_quantms_feature_cmd(64-136)convert_quantms_psm_cmd(168-228)convert_quantms_pg_cmd(345-443)create_duckdb_cmd(488-561)quantmsio/commands/convert/maxquant.py (4)
convert(17-19)convert_maxquant_feature_cmd(153-228)convert_maxquant_pg_cmd(264-320)convert_maxquant_psm_cmd(54-103)quantmsio/commands/convert/diann.py (2)
convert_diann_cmd(206-222)convert_diann_pg_cmd(263-277)quantmsio/commands/convert/fragpipe.py (1)
convert_fragpipe_psm_cmd(32-51)quantmsio/commands/convert/quantms_project.py (1)
convert_quantms_project_cmd(321-347)quantmsio/commands/convert/idxml.py (1)
convert_idxml_file(38-58)quantmsio/commands/transform/ae.py (1)
convert_ibaq_absolute_cmd(51-82)quantmsio/commands/transform/anndata.py (1)
merge_ae_files_cmd(30-52)quantmsio/commands/transform/de.py (1)
convert_msstats_differential_cmd(114-129)quantmsio/commands/transform/gene.py (1)
map_gene_message_cmd(45-67)quantmsio/commands/transform/ibaq.py (1)
convert_ibaq_file_cmd(36-57)quantmsio/commands/transform/spectra.py (1)
map_spectrum_message_cmd(39-59)quantmsio/commands/transform/uniprot.py (1)
map_latest_uniprot_cmd(36-58)quantmsio/commands/utils/attach.py (1)
attach_file_to_json_cmd(34-47)quantmsio/commands/utils/plot.py (1)
plot_cmd(18-20)quantmsio/commands/utils/project.py (1)
generate_pride_project_json_cmd(45-86)quantmsio/commands/utils/stats.py (1)
statistics_cmd(13-15)
quantmsio/commands/convert/quantms.py (6)
quantmsio/core/idxml_utils/idxml.py (3)
IdXmlPsm(19-602)convert_to_parquet(516-591)get_psm_count(593-602)quantmsio/core/quantms/mztab.py (10)
MzTabIndexer(114-3019)open(184-220)create(140-181)close(345-350)get_psm_count(1503-1518)get_metadata(1277-1292)get_protein_count(1468-1483)get_protein_details_count(1485-1501)_has_msstats_table(1567-1580)get_msstats(1397-1413)quantmsio/core/project.py (1)
create_uuid_filename(59-62)quantmsio/core/quantms/feature.py (2)
Feature(24-939)write_feature_to_file(639-669)quantmsio/core/quantms/pg.py (3)
MzTabProteinGroups(17-656)quantify_from_msstats_optimized(198-316)_convert_to_parquet_format(188-196)quantmsio/core/quantms/psm.py (2)
Psm(28-750)convert_to_parquet(688-750)
quantmsio/core/idxml_utils/idxml.py (4)
quantmsio/core/openms.py (3)
_get_run(158-189)_is_decoy(191-200)_extract_modifications_from_sequence(228-312)quantmsio/utils/file_utils.py (3)
ParquetBatchWriter(341-432)write_batch(370-381)close(419-432)quantmsio/utils/pride_utils.py (2)
generate_scan_number(76-81)standardize_protein_string_accession(176-191)quantmsio/utils/mztab_utils.py (1)
parse_peptidoform_openms(738-756)
quantmsio/commands/convert/idxml.py (2)
quantmsio/core/project.py (1)
create_uuid_filename(59-62)quantmsio/core/idxml.py (2)
IdXML(23-712)to_parquet(661-696)
quantmsio/core/maxquant/maxquant.py (2)
quantmsio/core/sdrf.py (3)
SDRFHandler(90-458)get_experiment_type_from_sdrf(272-317)get_sample_map_run(410-423)quantmsio/utils/file_utils.py (4)
ParquetBatchWriter(341-432)extract_protein_list(58-75)write_batch(370-381)close(419-432)
quantmsio/core/idxml.py (1)
quantmsio/core/openms.py (3)
OpenMSHandler(14-347)_extract_additional_scores(314-347)get_spectrum_from_scan(21-43)
quantmsio/core/quantms/psm.py (6)
quantmsio/core/openms.py (1)
get_openms_score_name(350-356)quantmsio/core/quantms/mztab.py (7)
get_metadata(1277-1292)get_protein_best_searchengine_score(1363-1370)_is_protein_score_qvalue(1294-1322)stream_section(1520-1565)_get_table_source(1252-1275)_get_num_psms(1388-1395)close(345-350)quantmsio/utils/file_utils.py (4)
extract_protein_list(58-75)ParquetBatchWriter(341-432)write_batch(370-381)close(419-432)quantmsio/utils/pride_utils.py (3)
generate_scan_number(76-81)get_petidoform_msstats_notation(262-309)standardize_protein_string_accession(176-191)quantmsio/utils/mztab_utils.py (2)
extract_ms_runs_from_metadata(372-418)parse_pepidoform_with_modifications(455-530)quantmsio/core/duckdb.py (1)
cleanup_duckdb(59-78)
quantmsio/commands/convert/maxquant.py (4)
quantmsio/core/maxquant/maxquant.py (5)
MaxQuant(128-1884)process_psm_file(433-465)_init_protein_group_qvalue_mapping(959-983)process_feature_file(672-758)process_pg_file(1058-1115)quantmsio/quantmsioc.py (2)
project(100-102)convert(76-78)quantmsio/core/project.py (1)
create_uuid_filename(59-62)quantmsio/utils/logger.py (1)
get_logger(8-10)
🪛 Ruff (0.13.1)
quantmsio/commands/convert/quantms.py
123-125: Abstract raise to an inner function
(TRY301)
123-125: Avoid specifying long messages outside the exception class
(TRY003)
135-135: Use explicit conversion flag
Replace with conversion flag
(RUF010)
135-135: Redundant exception object included in logging.exception call
(TRY401)
136-136: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling
(B904)
136-136: Avoid specifying long messages outside the exception class
(TRY003)
136-136: Use explicit conversion flag
Replace with conversion flag
(RUF010)
220-222: Abstract raise to an inner function
(TRY301)
220-222: Avoid specifying long messages outside the exception class
(TRY003)
227-227: Use explicit conversion flag
Replace with conversion flag
(RUF010)
227-227: Redundant exception object included in logging.exception call
(TRY401)
228-228: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling
(B904)
228-228: Avoid specifying long messages outside the exception class
(TRY003)
228-228: Use explicit conversion flag
Replace with conversion flag
(RUF010)
289-289: Use explicit conversion flag
Replace with conversion flag
(RUF010)
289-289: Redundant exception object included in logging.exception call
(TRY401)
290-290: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling
(B904)
290-290: Avoid specifying long messages outside the exception class
(TRY003)
290-290: Use explicit conversion flag
Replace with conversion flag
(RUF010)
346-346: PEP 484 prohibits implicit Optional
Convert to Optional[T]
(RUF013)
347-347: PEP 484 prohibits implicit Optional
Convert to Optional[T]
(RUF013)
348-348: PEP 484 prohibits implicit Optional
Convert to Optional[T]
(RUF013)
349-349: PEP 484 prohibits implicit Optional
Convert to Optional[T]
(RUF013)
350-350: PEP 484 prohibits implicit Optional
Convert to Optional[T]
(RUF013)
423-425: Abstract raise to an inner function
(TRY301)
423-425: Avoid specifying long messages outside the exception class
(TRY003)
442-442: Use explicit conversion flag
Replace with conversion flag
(RUF010)
442-442: Redundant exception object included in logging.exception call
(TRY401)
443-443: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling
(B904)
443-443: Avoid specifying long messages outside the exception class
(TRY003)
443-443: Use explicit conversion flag
Replace with conversion flag
(RUF010)
492-492: PEP 484 prohibits implicit Optional
Convert to Optional[T]
(RUF013)
522-524: Abstract raise to an inner function
(TRY301)
522-524: Avoid specifying long messages outside the exception class
(TRY003)
545-545: f-string without any placeholders
Remove extraneous f prefix
(F541)
556-556: Do not catch blind exception: Exception
(BLE001)
560-560: Use explicit conversion flag
Replace with conversion flag
(RUF010)
560-560: Redundant exception object included in logging.exception call
(TRY401)
561-561: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling
(B904)
561-561: Avoid specifying long messages outside the exception class
(TRY003)
561-561: Use explicit conversion flag
Replace with conversion flag
(RUF010)
quantmsio/core/idxml_utils/idxml.py
89-89: Do not catch blind exception: Exception
(BLE001)
99-99: Do not catch blind exception: Exception
(BLE001)
112-112: Do not catch blind exception: Exception
(BLE001)
127-127: Do not catch blind exception: Exception
(BLE001)
136-136: Do not catch blind exception: Exception
(BLE001)
145-145: Do not catch blind exception: Exception
(BLE001)
154-154: Do not catch blind exception: Exception
(BLE001)
160-160: Unused method argument: spectral_data
(ARG002)
216-216: Do not catch blind exception: Exception
(BLE001)
437-437: Consider moving this statement to an else block
(TRY300)
439-439: Do not catch blind exception: Exception
(BLE001)
440-440: Use logging.exception instead of logging.error
Replace with exception
(TRY400)
441-441: Use logging.exception instead of logging.error
Replace with exception
(TRY400)
442-444: Use logging.exception instead of logging.error
Replace with exception
(TRY400)
447-449: Use logging.exception instead of logging.error
Replace with exception
(TRY400)
532-532: f-string without any placeholders
Remove extraneous f prefix
(F541)
580-580: Use logging.exception instead of logging.error
Replace with exception
(TRY400)
581-581: Use logging.exception instead of logging.error
Replace with exception
(TRY400)
584-584: Use logging.exception instead of logging.error
Replace with exception
(TRY400)
quantmsio/commands/convert/idxml.py
47-47: Avoid specifying long messages outside the exception class
(TRY003)
quantmsio/core/maxquant/maxquant.py
119-119: Do not catch blind exception: Exception
(BLE001)
234-234: PEP 484 prohibits implicit Optional
Convert to Optional[T]
(RUF013)
249-249: PEP 484 prohibits implicit Optional
Convert to Optional[T]
(RUF013)
359-359: Do not catch blind exception: Exception
(BLE001)
360-360: Use logging.exception instead of logging.error
Replace with exception
(TRY400)
404-404: Do not catch blind exception: Exception
(BLE001)
407-407: Do not catch blind exception: Exception
(BLE001)
562-562: Consider moving this statement to an else block
(TRY300)
584-584: Consider moving this statement to an else block
(TRY300)
586-586: Do not catch blind exception: Exception
(BLE001)
587-587: Use logging.exception instead of logging.error
Replace with exception
(TRY400)
676-676: PEP 484 prohibits implicit Optional
Convert to Optional[T]
(RUF013)
677-677: PEP 484 prohibits implicit Optional
Convert to Optional[T]
(RUF013)
981-981: Do not catch blind exception: Exception
(BLE001)
982-982: Use logging.exception instead of logging.error
Replace with exception
(TRY400)
1062-1062: PEP 484 prohibits implicit Optional
Convert to Optional[T]
(RUF013)
1276-1276: Do not catch blind exception: Exception
(BLE001)
1277-1279: Use logging.exception instead of logging.error
Replace with exception
(TRY400)
1444-1444: Do not catch blind exception: Exception
(BLE001)
1547-1547: Do not catch blind exception: Exception
(BLE001)
1611-1611: Unnecessary key check before dictionary access
Replace with dict.get
(RUF019)
1800-1800: PEP 484 prohibits implicit Optional
Convert to Optional[T]
(RUF013)
1837-1837: Avoid specifying long messages outside the exception class
(TRY003)
1864-1864: PEP 484 prohibits implicit Optional
Convert to Optional[T]
(RUF013)
1868-1868: Avoid specifying long messages outside the exception class
(TRY003)
1907-1907: PEP 484 prohibits implicit Optional
Convert to Optional[T]
(RUF013)
quantmsio/core/idxml.py
68-68: Use logging.exception instead of logging.error
Replace with exception
(TRY400)
164-188: Consider moving this statement to an else block
(TRY300)
190-190: Do not catch blind exception: Exception
(BLE001)
584-584: Do not catch blind exception: Exception
(BLE001)
632-632: Do not catch blind exception: Exception
(BLE001)
651-651: Value being cast to int is already an integer
Remove unnecessary int call
(RUF046)
657-657: Do not catch blind exception: Exception
(BLE001)
quantmsio/core/quantms/psm.py
70-70: Consider moving this statement to an else block
(TRY300)
72-72: Do not catch blind exception: Exception
(BLE001)
116-116: Do not catch blind exception: Exception
(BLE001)
175-175: Do not catch blind exception: Exception
(BLE001)
276-276: Consider moving this statement to an else block
(TRY300)
277-277: Do not catch blind exception: Exception
(BLE001)
458-458: Consider moving this statement to an else block
(TRY300)
460-460: Do not catch blind exception: Exception
(BLE001)
529-529: f-string without any placeholders
Remove extraneous f prefix
(F541)
601-601: Do not catch blind exception: Exception
(BLE001)
602-602: Use logging.exception instead of logging.error
Replace with exception
(TRY400)
622-631: Possible SQL injection vector through string-based query construction
(S608)
669-669: Do not catch blind exception: Exception
(BLE001)
670-670: Use logging.exception instead of logging.error
Replace with exception
(TRY400)
679-679: Prefer TypeError exception for invalid type
(TRY004)
679-679: Create your own exception
(TRY002)
679-679: Avoid specifying long messages outside the exception class
(TRY003)
681-681: Create your own exception
(TRY002)
681-681: Avoid specifying long messages outside the exception class
(TRY003)
684-684: Create your own exception
(TRY002)
684-684: Avoid specifying long messages outside the exception class
(TRY003)
685-685: Loop control variable df overrides iterable it iterates
(B020)
quantmsio/commands/convert/maxquant.py
81-81: Abstract raise to an inner function
(TRY301)
81-81: Avoid specifying long messages outside the exception class
(TRY003)
102-102: Use explicit conversion flag
Replace with conversion flag
(RUF010)
103-103: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling
(B904)
103-103: Avoid specifying long messages outside the exception class
(TRY003)
103-103: Use explicit conversion flag
Replace with conversion flag
(RUF010)
185-185: Abstract raise to an inner function
(TRY301)
185-185: Avoid specifying long messages outside the exception class
(TRY003)
222-224: Abstract raise to an inner function
(TRY301)
222-224: Avoid specifying long messages outside the exception class
(TRY003)
227-227: Use explicit conversion flag
Replace with conversion flag
(RUF010)
228-228: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling
(B904)
228-228: Avoid specifying long messages outside the exception class
(TRY003)
228-228: Use explicit conversion flag
Replace with conversion flag
(RUF010)
292-292: Abstract raise to an inner function
(TRY301)
292-292: Avoid specifying long messages outside the exception class
(TRY003)
318-318: Use explicit conversion flag
Replace with conversion flag
(RUF010)
320-320: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling
(B904)
320-320: Avoid specifying long messages outside the exception class
(TRY003)
320-320: Use explicit conversion flag
Replace with conversion flag
(RUF010)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: unit-tests
- GitHub Check: unit-tests (3.11)
- GitHub Check: unit-tests (3.10)
- GitHub Check: unit-tests
🔇 Additional comments (12)
quantmsio/core/idxml.py (1)
661-696: Ensure output directory exists and compress parquet.Prevents parent-dir failures and reduces file size.
Apply:
- table = pa.Table.from_pandas(df, schema=PSM_SCHEMA) - pq.write_table(table, output_path) + output_path = Path(output_path) + output_path.parent.mkdir(parents=True, exist_ok=True) + table = pa.Table.from_pandas(df, schema=PSM_SCHEMA) + pq.write_table(table, str(output_path), compression="zstd")quantmsio/core/quantms/psm.py (5)
685-687: Avoid variable shadowing in groupby loop.Apply:
- for key, df in df.groupby(partitions): - yield key, df + for key, group_df in df.groupby(partitions): + yield key, group_df
151-161: Avoid NaN cast error when extracting score indices.Apply:
- score_df.loc[:, "mztab_score_name"] = ( - score_df["key"].str.extract(r"\[(\d+)\]").astype(int) - ) + score_df.loc[:, "mztab_score_name"] = pd.to_numeric( + score_df["key"].str.extract(r"\[(\d+)\]")[0], errors="coerce" + ) score_df.loc[:, "name_term"] = ( score_df["value"].str.split(",").str[2].str.strip() ) - # Drop rows where extraction failed - score_df.dropna(subset=["mztab_score_name", "name_term"], inplace=True) + # Drop rows where extraction failed, then cast to int + score_df.dropna(subset=["mztab_score_name", "name_term"], inplace=True) + score_df.loc[:, "mztab_score_name"] = score_df["mztab_score_name"].astype(int)
655-661: Fix MS run → filename mapping (wrong key type)._lookup uses integer ms_run IDs; using raw “ms_run[X]” always returns None. Reuse the helper.
Apply:
- if pd.notna(row["spectra_ref"]): - try: - ms_run_id = row["spectra_ref"].split(":")[0] - ref_file = self._ms_runs.get(ms_run_id) - except (ValueError, AttributeError): - pass + if pd.notna(row["spectra_ref"]): + ref_file = self._get_reference_file_name(row["spectra_ref"])
663-666: Guard None and normalize score before comparison.Apply:
- if key not in pep_map or row["score"] < pep_map[key][0]: - pep_map[key] = [row["score"], ref_file, scan_number] + try: + score_val = float(row["score"]) + except (TypeError, ValueError): + continue + if key not in pep_map or score_val < pep_map[key][0]: + pep_map[key] = [score_val, ref_file, scan_number]
547-549: Fix typo in CV parameter name (“consensus_support”).Apply:
- struct = { - "cv_name": "consesus_support", + struct = { + "cv_name": "consensus_support", "cv_value": str(consensus_support), }quantmsio/core/idxml_utils/idxml.py (1)
229-233: Decode protein accessions safely (avoid crashes).Items from extractProteinAccessionsSet may already be str; unconditional .decode() can raise. Decode bytes only; coerce others to str.
Apply:
- protein_accessions = [ - acc.decode() for acc in hit.extractProteinAccessionsSet() - ] + protein_accessions = [ + acc.decode() if isinstance(acc, (bytes, bytearray)) else str(acc) + for acc in hit.extractProteinAccessionsSet() + ]quantmsio/commands/convert/idxml.py (2)
13-27: Harden CLI option types to Path and validate existence.Use click.Path with path_type=Path for robust validation and to receive Path objects. This avoids manual checks and downstream type ambiguity.
Apply:
@click.option( "--idxml-file", help="the IdXML file containing identifications", required=True, + type=click.Path(exists=True, dir_okay=False, path_type=Path), ) @click.option( "--output-folder", help="Folder where the parquet file will be generated", required=True, + type=click.Path(file_okay=False, dir_okay=True, path_type=Path), ) @click.option( "--mzml-file", help="Optional mzML to attach spectra by scan", required=False, + type=click.Path(exists=True, dir_okay=False, path_type=Path), )Based on learnings.
28-37: Set a default prefix in the option and expose an OnDisc toggle.Provide a sensible default for output_prefix_file at the decorator level and add a --use-ondisc flag so users can opt into lower‑memory spectra attachment.
@click.option( "--output-prefix-file", help="Prefix of the parquet file needed to generate the file name", - required=False, + required=False, + default="psm", ) @click.option( "--spectral-data", help="Spectral data fields (optional)", is_flag=True, ) +@click.option( + "--use-ondisc/--no-use-ondisc", + default=False, + help="Use OnDiscMSExperiment to attach spectra with lower memory usage", +)Based on learnings.
quantmsio/commands/convert/maxquant.py (2)
101-104: Preserve exception context with chaining.Use
from eto keep the original traceback; this also satisfies Ruff B904.- raise click.ClickException(f"Error: {str(e)}\nCheck the logs for more details.") + raise click.ClickException( + f"Error: {str(e)}\nCheck the logs for more details." + ) from e
226-229: Preserve exception context with chaining (feature).Chain the ClickException.
- raise click.ClickException(f"Error: {str(e)}\nCheck the logs for more details.") + raise click.ClickException( + f"Error: {str(e)}\nCheck the logs for more details." + ) from equantmsio/quantmsioc.py (1)
118-126: All transform commands have explicit Click command names
Verified that eachquantmsio/commands/transform/*file is decorated with@click.command("…"), providing stable, user-friendly names. No further changes needed.
| - The spectra information aims to provide for a given feature the scan used to identify it. In DDA protocols LFQ-DDA and DIAplex, we recommended os use the best psm for a given feature. | ||
| - Protein groups `gg_accessions` should contain all the proteins that discreve the protein group — for example, in MQ and FragPipe the anchor protein is the one selected to represent the group; while DIA-NN put all the proteins within a group. Similar to the psm section <<psm>> the entire list of proteins for a given group could be written in the `pg_accessions` field. | ||
| - conditions: Conditions for every feature, are the values of the `factor values`. |
There was a problem hiding this comment.
Typos and clarity
- “recommended os use” → “recommended to use”
- “discreve” → “describe”
-- In DDA protocols LFQ-DDA and DIAplex, we recommended os use the best psm for a given feature.
+- In DDA protocols (LFQ-DDA and DIAplex), we recommend to use the best PSM for a given feature.
- Protein groups `gg_accessions` should contain all the proteins that discreve the protein group
+ Protein groups `gg_accessions` should contain all the proteins that describe the protein group📝 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.
| - The spectra information aims to provide for a given feature the scan used to identify it. In DDA protocols LFQ-DDA and DIAplex, we recommended os use the best psm for a given feature. | |
| - Protein groups `gg_accessions` should contain all the proteins that discreve the protein group — for example, in MQ and FragPipe the anchor protein is the one selected to represent the group; while DIA-NN put all the proteins within a group. Similar to the psm section <<psm>> the entire list of proteins for a given group could be written in the `pg_accessions` field. | |
| - conditions: Conditions for every feature, are the values of the `factor values`. | |
| - The spectra information aims to provide for a given feature the scan used to identify it. In DDA protocols (LFQ-DDA and DIAplex), we recommend to use the best PSM for a given feature. | |
| - Protein groups `gg_accessions` should contain all the proteins that describe the protein group — for example, in MQ and FragPipe the anchor protein is the one selected to represent the group; while DIA-NN put all the proteins within a group. Similar to the psm section <<psm>> the entire list of proteins for a given group could be written in the `pg_accessions` field. | |
| - conditions: Conditions for every feature, are the values of the `factor values`. |
🤖 Prompt for AI Agents
In docs/README.adoc around lines 1234 to 1236, fix two typos and improve
clarity: change “recommended os use” to “recommended to use” and “discreve” to
“describe”; while there, slightly rephrase the sentences for clarity (e.g., “we
recommended to use the best PSM for a given feature” and “Protein groups
`gg_accessions` should contain all the proteins that describe the protein
group”) keeping original meaning and punctuation.
| processor.process_pg_file( | ||
| protein_groups_path=str(protein_groups_file), | ||
| output_path=str(output_path), | ||
| sdrf_path=str(sdrf_file), | ||
| ) |
There was a problem hiding this comment.
--batch-size is ignored in PG conversion; pass it to process_pg_file.
Users expect the option to apply; wire it through.
processor.process_pg_file(
protein_groups_path=str(protein_groups_file),
output_path=str(output_path),
- sdrf_path=str(sdrf_file),
+ sdrf_path=str(sdrf_file),
+ chunksize=batch_size,
)📝 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.
| processor.process_pg_file( | |
| protein_groups_path=str(protein_groups_file), | |
| output_path=str(output_path), | |
| sdrf_path=str(sdrf_file), | |
| ) | |
| processor.process_pg_file( | |
| protein_groups_path=str(protein_groups_file), | |
| output_path=str(output_path), | |
| sdrf_path=str(sdrf_file), | |
| chunksize=batch_size, | |
| ) |
🤖 Prompt for AI Agents
In quantmsio/commands/convert/maxquant.py around lines 309 to 313, the call to
processor.process_pg_file does not pass the CLI --batch-size option, so the
option is ignored; update the call to forward the batch size (e.g., add
batch_size=batch_size) when invoking process_pg_file, ensuring the variable name
matches the parsed argument and that the processor method accepts this
parameter; if needed, update the processor.process_pg_file signature to accept a
batch_size parameter and propagate it to the internal processing loop.
| # No database_path provided, create a temporary one | ||
| temp_db_file = tempfile.NamedTemporaryFile(suffix=".duckdb", delete=False) | ||
| temp_db_path = temp_db_file.name | ||
| temp_db_file.close() | ||
| if os.path.exists(temp_db_path): | ||
| os.unlink(temp_db_path) | ||
| logger.info( |
There was a problem hiding this comment.
Avoid TOCTOU: don’t pre-create temp DuckDB files; generate a unique non-existent path
Pre-creating and unlinking a temp file is racy. Generate a unique path and let MzTabIndexer.create create it.
@@
- elif mztab_path:
- # No database_path provided, create a temporary one
- temp_db_file = tempfile.NamedTemporaryFile(suffix=".duckdb", delete=False)
- temp_db_path = temp_db_file.name
- temp_db_file.close()
- if os.path.exists(temp_db_path):
- os.unlink(temp_db_path)
+ elif mztab_path:
+ # No database_path provided, generate a unique non-existent path
+ from uuid import uuid4
+ temp_db_path = str(Path(tempfile.gettempdir()) / f"quantms_{uuid4().hex}.duckdb")
@@
- elif mztab_path:
- # No database_path provided, create a temporary one
- temp_db_file = tempfile.NamedTemporaryFile(suffix=".duckdb", delete=False)
- temp_db_path = temp_db_file.name
- temp_db_file.close()
- if os.path.exists(temp_db_path):
- os.unlink(temp_db_path)
+ elif mztab_path:
+ # No database_path provided, generate a unique non-existent path
+ from uuid import uuid4
+ temp_db_path = str(Path(tempfile.gettempdir()) / f"quantms_{uuid4().hex}.duckdb")
@@
- elif mztab_path:
- # No database_path provided, create a temporary one
- temp_db_file = tempfile.NamedTemporaryFile(suffix=".duckdb", delete=False)
- temp_db_path = temp_db_file.name
- temp_db_file.close()
- if os.path.exists(temp_db_path):
- os.unlink(temp_db_path)
+ elif mztab_path:
+ # No database_path provided, generate a unique non-existent path
+ from uuid import uuid4
+ temp_db_path = str(Path(tempfile.gettempdir()) / f"quantms_{uuid4().hex}.duckdb")Also applies to: 206-213, 408-413
🤖 Prompt for AI Agents
In quantmsio/commands/convert/quantms.py around lines 107-113 (and similarly at
206-213 and 408-413), the code currently creates a temporary file then
immediately unlinks it (TOCTOU); instead, generate a unique, non-existent path
and pass that path to MzTabIndexer.create so the indexer creates the file
itself. Replace the NamedTemporaryFile + unlink pattern with construction of a
safe unique path (e.g., using tempfile.gettempprefix or tempfile.mkdtemp
combined with a random suffix or uuid and the .duckdb extension) or use
tempfile.TemporaryDirectory to create a directory and join a generated filename,
ensure delete-on-close is not relied upon, and remove the explicit os.unlink
call so the file is not pre-created before MzTabIndexer.create runs.
| logger.exception(f"Error in feature conversion: {str(e)}") | ||
| raise click.ClickException(f"Error: {str(e)}\nCheck the logs for more details.") |
There was a problem hiding this comment.
Preserve traceback with exception chaining
Use “from e” when re-raising inside except to keep context.
- except Exception as e:
- logger.exception(f"Error in feature conversion: {str(e)}")
- raise click.ClickException(f"Error: {str(e)}\nCheck the logs for more details.")
+ except Exception as e:
+ logger.exception("Error in feature conversion", exc_info=e)
+ raise click.ClickException("Error: Check the logs for more details.") from e
@@
- except Exception as e:
- logger.exception(f"Error in PSM conversion: {str(e)}")
- raise click.ClickException(f"Error: {str(e)}\nCheck the logs for more details.")
+ except Exception as e:
+ logger.exception("Error in PSM conversion", exc_info=e)
+ raise click.ClickException("Error: Check the logs for more details.") from e
@@
- except Exception as e:
- logger.exception(f"Error in idXML PSM conversion: {str(e)}")
- raise click.ClickException(f"Error: {str(e)}\nCheck the logs for more details.")
+ except Exception as e:
+ logger.exception("Error in idXML PSM conversion", exc_info=e)
+ raise click.ClickException("Error: Check the logs for more details.") from e
@@
- except Exception as e:
- logger.exception(f"Error in mzTab protein group conversion: {str(e)}")
- raise click.ClickException(f"Error: {str(e)}\nCheck the logs for more details.")
+ except Exception as e:
+ logger.exception("Error in mzTab protein group conversion", exc_info=e)
+ raise click.ClickException("Error: Check the logs for more details.") from e
@@
- except Exception as e:
- logger.exception(f"Error during processing: {str(e)}")
- raise click.ClickException(f"Error: {str(e)}\nCheck the logs for more details.")
+ except Exception as e:
+ logger.exception("Error during processing", exc_info=e)
+ raise click.ClickException("Error: Check the logs for more details.") from eAlso applies to: 227-228, 289-290, 441-443, 559-561
🧰 Tools
🪛 Ruff (0.13.1)
135-135: Use explicit conversion flag
Replace with conversion flag
(RUF010)
135-135: Redundant exception object included in logging.exception call
(TRY401)
136-136: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling
(B904)
136-136: Avoid specifying long messages outside the exception class
(TRY003)
136-136: Use explicit conversion flag
Replace with conversion flag
(RUF010)
🤖 Prompt for AI Agents
In quantmsio/commands/convert/quantms.py around lines 135-136 (and similarly at
227-228, 289-290, 441-443, 559-561), the code logs the exception then re-raises
a new ClickException without exception chaining; modify each raise to use "raise
click.ClickException(f\"Error: {str(e)}\\nCheck the logs for more details.\")
from e" so the original traceback is preserved while keeping the existing log
call, ensuring the new exception is chained to the caught exception for full
context.
| # Create database with mzTab data using factory method | ||
| indexer = MzTabIndexer.create( | ||
| mztab_path=str(input_file), | ||
| msstats_path=str(msstats_file) if msstats_file else None, | ||
| backend=backend, | ||
| database_path=str(database_path), | ||
| max_memory=max_memory, | ||
| worker_threads=threads, | ||
| ) | ||
|
|
||
| logger.info("Processing complete!") | ||
|
|
||
| # Log some basic statistics | ||
| try: | ||
| metadata_count = len(indexer.get_metadata()) | ||
| protein_count = indexer.get_protein_count() | ||
| protein_details_count = indexer.get_protein_details_count() | ||
| psm_count = indexer.get_psm_count() | ||
|
|
||
| logger.info(f"Successfully processed:") | ||
| logger.info(f" - Metadata entries: {metadata_count:,}") | ||
| logger.info(f" - Proteins: {protein_count:,}") | ||
| logger.info(f" - Protein details: {protein_details_count:,}") | ||
| logger.info(f" - PSMs: {psm_count:,}") | ||
|
|
||
| if indexer._has_msstats_table(): | ||
| msstats_data = indexer.get_msstats() | ||
| if msstats_data is not None: | ||
| logger.info(f" - MSstats entries: {len(msstats_data):,}") | ||
|
|
||
| except Exception as stats_error: | ||
| logger.warning(f"Could not retrieve statistics: {stats_error}") | ||
|
|
||
| except Exception as e: | ||
| logger.exception(f"Error during processing: {str(e)}") | ||
| raise click.ClickException(f"Error: {str(e)}\nCheck the logs for more details.") |
There was a problem hiding this comment.
Always close indexer in create-duckdb; fix stray f-string
Ensure DB handles are released and remove f-prefix without placeholders.
- # Create database with mzTab data using factory method
- indexer = MzTabIndexer.create(
+ # Create database with mzTab data using factory method
+ indexer = MzTabIndexer.create(
mztab_path=str(input_file),
msstats_path=str(msstats_file) if msstats_file else None,
backend=backend,
database_path=str(database_path),
max_memory=max_memory,
worker_threads=threads,
- )
-
- logger.info("Processing complete!")
-
- # Log some basic statistics
- try:
+ )
+
+ logger.info("Processing complete!")
+
+ # Log some basic statistics
+ try:
metadata_count = len(indexer.get_metadata())
protein_count = indexer.get_protein_count()
protein_details_count = indexer.get_protein_details_count()
psm_count = indexer.get_psm_count()
- logger.info(f"Successfully processed:")
+ logger.info("Successfully processed:")
logger.info(f" - Metadata entries: {metadata_count:,}")
logger.info(f" - Proteins: {protein_count:,}")
logger.info(f" - Protein details: {protein_details_count:,}")
logger.info(f" - PSMs: {psm_count:,}")
if indexer._has_msstats_table():
msstats_data = indexer.get_msstats()
if msstats_data is not None:
logger.info(f" - MSstats entries: {len(msstats_data):,}")
- except Exception as stats_error:
- logger.warning(f"Could not retrieve statistics: {stats_error}")
+ except Exception as stats_error:
+ logger.warning(f"Could not retrieve statistics: {stats_error}")
+ finally:
+ with contextlib.suppress(Exception):
+ indexer.close()Add at top of file:
+import contextlibAlso applies to: 538-558, 545-545
🧰 Tools
🪛 Ruff (0.13.1)
545-545: f-string without any placeholders
Remove extraneous f prefix
(F541)
556-556: Do not catch blind exception: Exception
(BLE001)
560-560: Use explicit conversion flag
Replace with conversion flag
(RUF010)
560-560: Redundant exception object included in logging.exception call
(TRY401)
561-561: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling
(B904)
561-561: Avoid specifying long messages outside the exception class
(TRY003)
561-561: Use explicit conversion flag
Replace with conversion flag
(RUF010)
| spectrum_ref = record.get("spectrum_ref", "") | ||
| if spectrum_ref: | ||
| transformed_record["scan"] = generate_scan_number(spectrum_ref) | ||
| transformed_record["reference_file_name"] = ( | ||
| self._extract_reference_file_name(spectrum_ref) | ||
| ) | ||
| else: | ||
| transformed_record["scan"] = "unknown" | ||
| transformed_record["reference_file_name"] = "unknown" | ||
|
|
There was a problem hiding this comment.
Prefer stored reference_file_name over parsing ms_run token.
Use the run captured earlier; fall back to parser only if missing.
Apply:
if spectrum_ref:
- transformed_record["scan"] = generate_scan_number(spectrum_ref)
- transformed_record["reference_file_name"] = (
- self._extract_reference_file_name(spectrum_ref)
- )
+ transformed_record["scan"] = generate_scan_number(spectrum_ref)
+ transformed_record["reference_file_name"] = (
+ record.get("reference_file_name")
+ or self._extract_reference_file_name(spectrum_ref)
+ )
else:
- transformed_record["scan"] = "unknown"
- transformed_record["reference_file_name"] = "unknown"
+ transformed_record["scan"] = "unknown"
+ transformed_record["reference_file_name"] = (
+ record.get("reference_file_name") or "unknown"
+ )📝 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.
| spectrum_ref = record.get("spectrum_ref", "") | |
| if spectrum_ref: | |
| transformed_record["scan"] = generate_scan_number(spectrum_ref) | |
| transformed_record["reference_file_name"] = ( | |
| self._extract_reference_file_name(spectrum_ref) | |
| ) | |
| else: | |
| transformed_record["scan"] = "unknown" | |
| transformed_record["reference_file_name"] = "unknown" | |
| spectrum_ref = record.get("spectrum_ref", "") | |
| if spectrum_ref: | |
| transformed_record["scan"] = generate_scan_number(spectrum_ref) | |
| transformed_record["reference_file_name"] = ( | |
| record.get("reference_file_name") | |
| or self._extract_reference_file_name(spectrum_ref) | |
| ) | |
| else: | |
| transformed_record["scan"] = "unknown" | |
| transformed_record["reference_file_name"] = ( | |
| record.get("reference_file_name") or "unknown" | |
| ) |
🤖 Prompt for AI Agents
In quantmsio/core/idxml_utils/idxml.py around lines 371 to 380, the code
currently parses reference_file_name from the spectrum_ref token
unconditionally; instead prefer the previously captured run value and only fall
back to parsing the ms_run token when run is missing. Update the branch so that
when spectrum_ref is present you set transformed_record["scan"] =
generate_scan_number(spectrum_ref) and set
transformed_record["reference_file_name"] = run if run is truthy, otherwise call
self._extract_reference_file_name(spectrum_ref); keep the else case setting both
fields to "unknown".
| if key_identifier not in modifications: | ||
| modifications[key_identifier] = { | ||
| "name": mod_name, | ||
| "accession": mod_accession, | ||
| "positions": [], | ||
| } | ||
| modifications[key_identifier]["positions"].append(position_entry) | ||
|
|
There was a problem hiding this comment.
Align modifications structure with PSM schema (“fields”, not “positions”).
Current output uses “positions”; downstream schema and other code use “fields” with per-position scores. This will mis-schema Parquet writes.
Apply:
- modifications[key_identifier] = {
- "name": mod_name,
- "accession": mod_accession,
- "positions": [],
- }
- modifications[key_identifier]["positions"].append(position_entry)
+ modifications[key_identifier] = {
+ "name": mod_name,
+ "accession": mod_accession,
+ "fields": [],
+ }
+ modifications[key_identifier]["fields"].append(position_entry)And normalize before DataFrame:
- if isinstance(modifications, list):
- for mod in modifications:
- if isinstance(mod, dict) and "positions" in mod:
- # Ensure positions is a list
- if hasattr(mod["positions"], "tolist"):
- mod["positions"] = mod["positions"].tolist()
- # Ensure scores in each position is a list
- for pos in mod["positions"]:
+ if isinstance(modifications, list):
+ for mod in modifications:
+ if isinstance(mod, dict) and "fields" in mod:
+ if hasattr(mod["fields"], "tolist"):
+ mod["fields"] = mod["fields"].tolist()
+ for pos in mod["fields"]:
if isinstance(pos, dict) and "scores" in pos:
if hasattr(pos["scores"], "tolist"):
pos["scores"] = pos["scores"].tolist()Also applies to: 471-483
| for i in range(min(8, len(tmt_channels))): | ||
| reporter_col = f"Reporter intensity {i}" | ||
| corrected_col = f"Reporter intensity corrected {i}" | ||
|
|
||
| if ( | ||
| reporter_col in row.index | ||
| and pd.notna(row[reporter_col]) | ||
| and row[reporter_col] > 0 | ||
| ): | ||
| channel_name = tmt_channels[i] | ||
|
|
||
| sample_accession = self._get_tmt_sample_accession( | ||
| reference_file_name, channel_name | ||
| ) | ||
|
|
||
| intensities.append( | ||
| { | ||
| "sample_accession": sample_accession, | ||
| "channel": channel_name, | ||
| "intensity": float(row[reporter_col]), | ||
| } | ||
| ) | ||
|
|
||
| if corrected_col in row.index and pd.notna(row[corrected_col]): | ||
| additional_intensities.append( | ||
| { | ||
| "sample_accession": sample_accession, | ||
| "channel": channel_name, | ||
| "intensities": [ | ||
| { | ||
| "intensity_name": corrected_col, | ||
| "intensity_value": float(row[corrected_col]), | ||
| } | ||
| ], | ||
| } | ||
| ) | ||
|
|
||
| return intensities, additional_intensities |
There was a problem hiding this comment.
TMT reporter loop limited to 8 channels — truncates TMT10/11/16 data
Hard-coding min(8, len(tmt_channels)) drops channels beyond index 7. Detect reporter indices dynamically from columns.
- for i in range(min(8, len(tmt_channels))):
- reporter_col = f"Reporter intensity {i}"
- corrected_col = f"Reporter intensity corrected {i}"
+ # Discover reporter indices present in this row
+ reporter_indices = sorted({
+ int(m.group(1))
+ for col in row.index
+ for m in [re.match(r"Reporter intensity(?: corrected)?\s+(\d+)$", str(col))]
+ if m
+ })
+ for i in reporter_indices:
+ reporter_col = f"Reporter intensity {i}"
+ corrected_col = f"Reporter intensity corrected {i}"
...
- channel_name = tmt_channels[i]
+ # Guard if SDRF channels list is shorter than MaxQuant columns
+ channel_name = tmt_channels[i] if i < len(tmt_channels) else f"TMT{i}"Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In quantmsio/core/maxquant/maxquant.py around lines 292 to 329, the loop
currently uses min(8, len(tmt_channels)) which truncates TMT10/11/16
experiments; change the loop to detect reporter indices dynamically instead of
hard-coding 8—either iterate over range(len(tmt_channels)) or, better, derive
valid indices by scanning row.index for columns matching "Reporter intensity
{n}" / "Reporter intensity corrected {n}" (parse n, ensure n <
len(tmt_channels)), then for each detected index get channel_name =
tmt_channels[n], check presence and pd.notna for reporter and corrected cols,
and append to intensities/additional_intensities as before; ensure you handle
non-sequential/missing indices safely and convert values to float.
| if protein_str: | ||
| df_chunk = df_chunk[ | ||
| df_chunk["Proteins"].str.contains( | ||
| protein_str, na=False, regex=False | ||
| ) | ||
| ] | ||
| if df_chunk.empty: | ||
| continue |
There was a problem hiding this comment.
Protein filter uses literal contains with a ‘|’-joined pattern
With regex=False, "P1|P2" is treated literally; expected “any of”. Use regex with escaped tokens.
- df_chunk = df_chunk[
- df_chunk["Proteins"].str.contains(
- protein_str, na=False, regex=False
- )
- ]
+ pattern = "|".join(map(re.escape, protein_list))
+ df_chunk = df_chunk[
+ df_chunk["Proteins"].astype(str).str.contains(pattern, na=False, regex=True)
+ ]📝 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.
| if protein_str: | |
| df_chunk = df_chunk[ | |
| df_chunk["Proteins"].str.contains( | |
| protein_str, na=False, regex=False | |
| ) | |
| ] | |
| if df_chunk.empty: | |
| continue | |
| if protein_str: | |
| # build a regex that matches any of the proteins, escaping special chars | |
| pattern = "|".join(map(re.escape, protein_list)) | |
| df_chunk = df_chunk[ | |
| df_chunk["Proteins"] | |
| .astype(str) | |
| .str.contains(pattern, na=False, regex=True) | |
| ] | |
| if df_chunk.empty: | |
| continue |
🤖 Prompt for AI Agents
In quantmsio/core/maxquant/maxquant.py around lines 726 to 733, the protein
filter currently calls str.contains with regex=False so a pattern like "P1|P2"
is treated literally; split the incoming protein_str on '|' into tokens, escape
each token (to avoid regex metacharacters), rejoin with '|' to form an
alternation regex, and call
df_chunk["Proteins"].str.contains(<escaped_alternation>, na=False, regex=True)
so the filter matches any of the listed proteins.
| # Convert commands | ||
| convert.add_command(convert_diann_cmd, name="diann") | ||
| convert.add_command(convert_diann_pg_cmd, name="diann-pg") | ||
| convert.add_command(maxquant_psm_convert, name="maxquant-psm") | ||
| convert.add_command(maxquant_feature_convert, name="maxquant-feature") | ||
| convert.add_command(maxquant_pg_convert, name="maxquant-pg") | ||
| convert.add_command(convert_fragpipe_psm_cmd, name="fragpipe") | ||
| convert.add_command(quantms_psm_convert, name="quantms-psm") | ||
| convert.add_command(quantms_feature_convert, name="quantms-feature") | ||
| convert.add_command(quantms_pg_convert, name="quantms-pg") | ||
| convert.add_command(convert_idxml_file, name="idxml") | ||
|
|
There was a problem hiding this comment.
Expose DuckDB creator on the CLI (currently imported but not registered).
create_duckdb_cmd is imported as duckdb_creator but not added to the convert group; users can’t invoke it.
convert.add_command(quantms_pg_convert, name="quantms-pg")
convert.add_command(convert_idxml_file, name="idxml")
+
+# DuckDB utilities
+convert.add_command(duckdb_creator, name="create-duckdb")📝 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.
| # Convert commands | |
| convert.add_command(convert_diann_cmd, name="diann") | |
| convert.add_command(convert_diann_pg_cmd, name="diann-pg") | |
| convert.add_command(maxquant_psm_convert, name="maxquant-psm") | |
| convert.add_command(maxquant_feature_convert, name="maxquant-feature") | |
| convert.add_command(maxquant_pg_convert, name="maxquant-pg") | |
| convert.add_command(convert_fragpipe_psm_cmd, name="fragpipe") | |
| convert.add_command(quantms_psm_convert, name="quantms-psm") | |
| convert.add_command(quantms_feature_convert, name="quantms-feature") | |
| convert.add_command(quantms_pg_convert, name="quantms-pg") | |
| convert.add_command(convert_idxml_file, name="idxml") | |
| # Convert commands | |
| convert.add_command(convert_diann_cmd, name="diann") | |
| convert.add_command(convert_diann_pg_cmd, name="diann-pg") | |
| convert.add_command(maxquant_psm_convert, name="maxquant-psm") | |
| convert.add_command(maxquant_feature_convert, name="maxquant-feature") | |
| convert.add_command(maxquant_pg_convert, name="maxquant-pg") | |
| convert.add_command(convert_fragpipe_psm_cmd, name="fragpipe") | |
| convert.add_command(quantms_psm_convert, name="quantms-psm") | |
| convert.add_command(quantms_feature_convert, name="quantms-feature") | |
| convert.add_command(quantms_pg_convert, name="quantms-pg") | |
| convert.add_command(convert_idxml_file, name="idxml") | |
| # DuckDB utilities | |
| convert.add_command(duckdb_creator, name="create-duckdb") |
🤖 Prompt for AI Agents
In quantmsio/quantmsioc.py around lines 105 to 116, the imported DuckDB creator
(create_duckdb_cmd aliased as duckdb_creator) is not registered with the convert
click group so users cannot call it; add a registration line to expose it (e.g.,
convert.add_command(duckdb_creator, name="duckdb") using the same pattern as the
other convert commands) and place it with the other convert.add_command calls so
the CLI exposes the duckdb creator.
Merge main into dev.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (5)
quantmsio/operate/tools.py (4)
163-163: Remove merge artifact comment.The comment
# Before Code:is a merge artifact and should be removed.Apply this diff:
-# Before Code: def get_ahocorasick(mods_dict: dict) -> ahocorasick.Automaton:
228-233: Make FASTA accession parsing robust.Line 229 uses
entry.identifier.split("|")[1], which will raiseIndexErrorfor headers without the pipe format. Reuse the localget_protein_accessionhelper for safe parsing.Apply this diff:
for entry in fasta_proteins: - accession = entry.identifier.split("|")[1] + accessions = get_protein_accession(entry.identifier) + accession = accessions[0] if accessions else entry.identifier for match in automaton.iter(entry.sequence): peptide = match[1] if accession not in peptide_map[peptide]: peptide_map[peptide].append(accession)
248-255: Replace Series.map with mapping.get to avoid NaN for unmapped peptides.Line 249 uses
Series.mapwith a dict-like, which can yield NaN for missing keys and will causelen(NaN)failures on line 250. Useapply(lambda s: peptide_map.get(s, []))to guarantee an empty list for unmapped peptides.Apply this diff:
pqwriter = None for table in p.iter_chunk(batch_size=2000000): - table["pg_accessions"] = table["sequence"].map(peptide_map) + table["pg_accessions"] = table["sequence"].apply(lambda s: peptide_map.get(s, [])) table = table[table["pg_accessions"].apply(lambda x: len(x) > 0)] table.loc[:, "unique"] = ( table["pg_accessions"] .apply(lambda x: 0 if len(x) > 1 else 1) .astype(np.int32) )
303-310: Rename misspelled function: genereate_ibaq_feature → generate_ibaq_featureThe function name is misspelled. Rename it to
generate_ibaq_featureand update all call sites.Apply this diff:
-def genereate_ibaq_feature( +def generate_ibaq_feature( sdrf_path: Union[Path, str], parquet_path: Union[Path, str] ) -> Generator[pa.Table, None, None]:And update the call site at line 349:
- for feature in genereate_ibaq_feature(sdrf_path, parquet_path): + for feature in generate_ibaq_feature(sdrf_path, parquet_path):quantmsio/core/fragpipe/fragpipe.py (1)
380-393: Batch size and safety check concerns remain unaddressed.The signature improvements (type hints, parameter naming, docstring) are good. However, the concerns raised in the previous review remain:
Aggressive batch size: The 1,000,000 default is 100× larger than the original 10,000 and could cause memory pressure on resource-constrained systems.
Missing safety checks: No validation that
msms_fileexists or thatself.output_directoryis writable.Consider applying the previously suggested improvements:
def write_psms_to_parquet( self, msms_file: Path, - batch_size: int = 1000000, + batch_size: int = 100000, # More conservative default output_prefix: Optional[str] = None, ) -> None: """ Write PSMs to parquet file. Args: msms_file: Path to the psm.tsv file batch_size: Number of rows to process at a time output_prefix: Prefix for the output file name """ + # Validate input file exists + if not msms_file.exists(): + raise FileNotFoundError(f"PSM file not found: {msms_file}") + + # Ensure output directory exists + self.output_directory.mkdir(parents=True, exist_ok=True) + if not output_prefix: output_prefix = "psm"
🧹 Nitpick comments (4)
quantmsio/operate/tools.py (3)
166-166: Simplify dict iteration.
mods_dict.keys()can be replaced withmods_dictfor cleaner iteration.Apply this diff:
- for key in mods_dict.keys(): + for key in mods_dict:
287-294: Use named logger for consistency.Lines 290-292 use
logging.warning, but line 341 shows a named logger (logging.getLogger("transform.ibaq")). For consistency and to respect logger configuration, instantiate a module-level or function-level logger and uselogger.warninginstead.Apply this diff to use a module-level logger:
At the top of the file, after imports:
+logger = logging.getLogger(__name__)Then update line 290:
- logging.warning( + logger.warning( "[transform_ibaq]: The 'intensities' column contains NaN values." )
348-354: Ensure parent directory exists and pass string path to ParquetWriter.Line 351 creates a ParquetWriter with
output_path, which isUnion[Path, str]. Some PyArrow versions require a string path. Additionally, ensure the parent directory exists before creating the writer.Apply this diff:
+ Path(output_path).parent.mkdir(parents=True, exist_ok=True) pqwriter = None for feature in genereate_ibaq_feature(sdrf_path, parquet_path): if not pqwriter: - pqwriter = pq.ParquetWriter(output_path, feature.schema) + pqwriter = pq.ParquetWriter(str(output_path), feature.schema) pqwriter.write_table(feature)quantmsio/core/fragpipe/fragpipe.py (1)
407-422: Support RecordBatch input inParquetBatchWriter.write_batch.The current signature accepts only
List[dict](quantmsio/utils/file_utils.py:370), sobatch.to_pylist()duplicates memory. Overload or extendwrite_batchto acceptpa.RecordBatch(orpa.Table) directly and write it via PyArrow, eliminating the intermediate Python‐list conversion and halving peak memory use.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
quantmsio/core/fragpipe/fragpipe.py(2 hunks)quantmsio/operate/tools.py(7 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
quantmsio/core/fragpipe/fragpipe.py (1)
quantmsio/utils/file_utils.py (3)
ParquetBatchWriter(341-432)write_batch(370-381)close(419-432)
quantmsio/operate/tools.py (5)
quantmsio/core/openms.py (1)
OpenMSHandler(14-347)quantmsio/core/sdrf.py (2)
transform_sdrf(425-458)get_experiment_type_from_sdrf(272-317)quantmsio/operate/query.py (6)
Query(63-369)map_spectrum_mz(30-41)get_unique_peptides(245-253)iter_chunk(119-123)iter_file(125-136)close(344-348)quantmsio/utils/file_utils.py (5)
close_file(302-319)load_de_or_ae(138-169)save_file(260-299)save_slice_file(211-257)close(419-432)quantmsio/utils/pride_utils.py (1)
get_unanimous_name(21-34)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: unit-tests
- GitHub Check: unit-tests (3.10)
- GitHub Check: unit-tests (3.11)
- GitHub Check: unit-tests
🔇 Additional comments (3)
quantmsio/operate/tools.py (1)
273-278: Confirm external API impact for get_protein_accession.No internal call sites were found in the repository, but this change alters the public API: when no pipe character is present, it now returns only the first accession (rather than splitting into all items). Verify that any external consumers or downstream clients are updated to handle this new behavior.
quantmsio/core/fragpipe/fragpipe.py (2)
394-398: LGTM: UUID-based file naming prevents collisions.The default prefix assignment and UUID-based filename generation ensure unique output files, preventing accidental overwrites.
407-428: Solid resource cleanup with try/finally.The resource management is well-structured:
- Lazy writer initialization avoids creating empty files
finallyblock ensures cleanup even on errors- Warning logged when no data is processed
Minor enhancement: Consider catching and re-raising specific exceptions with context:
try: for i, batch in enumerate( self.convert_psms(msms_file, batch_size=batch_size) ): # ... processing ... except (IOError, OSError) as e: logger.error("Failed to read PSM file %s: %s", msms_file, e) raise except pa.ArrowInvalid as e: logger.error("Invalid Arrow data in batch: %s", e) raise finally: # ... cleanup ...
Simplify CI workflow by removing integration and full test suites.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
.github/workflows/python-app.yml (1)
36-38: Update to actions/setup-python@v5.The static analysis tool correctly identifies that
actions/setup-python@v4is outdated and should be upgraded to v5 to ensure compatibility with current GitHub Actions runners.Apply this diff:
- - name: Set up Python 3.10 - uses: actions/setup-python@v4 - with: - python-version: "3.10" + - name: Set up Python 3.10 + uses: actions/setup-python@v5 + with: + python-version: "3.10"
🧹 Nitpick comments (1)
.github/workflows/python-app.yml (1)
47-52: Consider lowering max-complexity threshold.The
max-complexity=30setting is quite permissive. While this may be intentional for legacy code, consider gradually reducing it to 15-20 to encourage simpler, more maintainable functions. The ignored F401 (unused imports) may also hide cleanup opportunities.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
.github/workflows/python-app.yml(1 hunks)
🧰 Additional context used
🪛 actionlint (1.7.7)
.github/workflows/python-app.yml
36-36: the runner of "actions/setup-python@v4" action is too old to run on GitHub Actions. update the action's version to fix this issue
(action)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: unit-tests
- GitHub Check: unit-tests (3.10)
- GitHub Check: unit-tests (3.11)
- GitHub Check: unit-tests
🔇 Additional comments (5)
.github/workflows/python-app.yml (5)
11-15: LGTM! Valuable automation additions.The scheduled daily run and manual trigger capability enhance CI flexibility. The cron syntax is correct for a 2 AM UTC daily execution.
24-24: LGTM! Action version updated.Upgrading to
actions/checkout@v4aligns with current GitHub Actions best practices.
39-46: LGTM! Improved dependency management.The switch to
poetry installfor development mode and explicit inclusion ofpytest-timeoutimprove the test environment setup. This aligns well with modern Python development practices.
53-56: LGTM! Clear test scope separation.The explicit filtering of integration tests with
-m "not integration"ensures fast, focused unit test runs. This complements the separate integration-tests workflow mentioned in the AI summary.
31-31: LGTM! Descriptive job naming.The
unit-testsjob name accurately reflects its focused scope after excluding integration tests.
PR Type
Enhancement
Description
Major CLI restructuring with organized command groups
Enhanced logging system with structured output support
New quantms workflow conversion command
Improved error handling and verbose logging
Changes walkthrough 📝
28 files
Add quantms workflow conversion commandAdd DIA-NN conversion commandsAdd PSM conversion and comparison commandsAdd feature conversion commandAdd visualization plotting commandsRestructure CLI with organized command groupsAdd differential expression transformation commandAdd statistical analysis commandsUpdate MaxQuant conversion commandsAdd enhanced logging to PSM processingAdd enhanced logging to feature processingAdd project management commandsAdd absolute expression transformation commandUpdate schema with nullable fieldsUpdate FragPipe PSM conversion methodAdd gene mapping transformation commandUpdate project save methodsUpdate FragPipe conversion commandAdd UniProt mapping transformation commandAdd IBAQ transformation commandAdd spectra transformation commandUpdate AnnData merge commandUpdate file attachment commandAdd logging to MzTab classAdd logger utility moduleAdd convert commands packageAdd transform commands packageAdd utils commands package1 files
Fix regex patterns with raw strings7 files
Update feature schema with scan formatMajor documentation update with usage examplesUpdate PSM schema with record typesAdd comprehensive logging documentationAdd differential expression schemaUpdate IBAQ use case documentationAdd absolute expression schema2 files
Update DuckDB version requirementUpdate Python and PyOpenMS version requirements13 files
Summary by CodeRabbit
New Features
Documentation
Schemas / Formats
Tests & CI
Chores