### Install CasanovoUtils from PyPI Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/getting_started.md Installs the CasanovoUtils package using pip. This is the recommended method for most users. Ensure you have Python 3.13 or later installed. ```bash pip install casanovoutils ``` -------------------------------- ### Verify CasanovoUtils Installation Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/getting_started.md Checks if the CasanovoUtils command-line tools are installed and accessible. Running the --help flag on each command confirms successful installation and provides usage information. ```bash graph-prec-cov --help downsample-ms --help mgf-utils --help casanovo-utils --help ``` -------------------------------- ### Install CasanovoUtils from Source Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/getting_started.md Installs CasanovoUtils by cloning the repository and using pip. This method is useful for developers or when needing the latest unreleased changes. It requires Git and Python 3.13+. ```bash git clone https://github.com/Noble-Lab/casanovoutils.git cd casanovoutils pip install . ``` ```bash git clone https://github.com/Noble-Lab/casanovoutils.git cd casanovoutils uv sync ``` -------------------------------- ### Compare Two Models Precision-Coverage Curves Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/getting_started.md Compares the precision-coverage curves of two different models on a single plot. Allows customization of figure dimensions and requires mzTab and MGF files for each model. ```bash graph-prec-cov \ --fig_width 6 \ --fig_height 4 \ add-peptides modelA.mztab truth.mgf "Model A" \ add-peptides modelB.mztab truth.mgf "Model B" \ save comparison.png ``` -------------------------------- ### Chain MGF Operations with mgf-utils Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/getting_started.md Performs multiple MGF file operations, such as downsampling, in a single command using `mgf-utils`. This allows chaining operations and writing to a single output file. ```bash mgf-utils file1.mgf file2.mgf \ downsample --k 5 \ write --outfile combined_downsampled.mgf ``` -------------------------------- ### Get Precision-Coverage DataFrame Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/autoapi/casanovoutils/prec_cov/index.md Builds a precision-coverage DataFrame from predicted and ground truth PSMs. ```APIDOC ## POST /casanovoutils/prec_cov/get_prec_cov_df ### Description Build a precision-coverage DataFrame from predicted and ground truth PSMs. Loads or constructs a ground truth DataFrame, tokenizes both predicted and ground truth sequences, parses per-amino-acid scores, and computes precision-coverage metrics. When `aa_level` is `True`, sequences are first aligned with gap insertion and then exploded so that each row represents a single amino acid position rather than a full peptide. ### Method POST ### Endpoint /casanovoutils/prec_cov/get_prec_cov_df ### Parameters #### Request Body - **ground_truth_df** (casanovoutils.utils.DfPath | None) - Optional - Path to or an already-loaded ground truth DataFrame. If `None`, both `mgf_df` and `mztab_df` must be provided and the ground truth DataFrame will be constructed via `get_ground_truth_df()`. - **mgf_df** (casanovoutils.utils.DfPath | None) - Optional - Path to or an already-loaded MGF PSM DataFrame. Required when `ground_truth_df` is `None`. - **mztab_df** (casanovoutils.utils.DfPath | None) - Optional - Path to or an already-loaded mzTab DataFrame. Required when `ground_truth_df` is `None`. - **residues_path** (casanovoutils.utils.DfPath | None) - Optional - Path to a residue mass YAML file passed through to `tokenize_sequences()`. If `None`, the bundled `residues.yaml` is used. - **replace_isoleucine_with_leucine** (bool) - Optional - If `True` (default), isoleucine (I) is replaced with leucine (L) during tokenization, treating them as equivalent. - **aa_level** (bool) - Optional - If `True`, perform per-amino-acid alignment via gap insertion and explode the DataFrame so each row corresponds to a single amino acid position. If `False` (default), metrics are computed at the peptide level using the peptide-level score column. - **align_tie_beak_suffix** (bool) - Optional - Passed through to the alignment step when `aa_level` is `True`. Controls tie-breaking behavior when the gap and no-gap paths score equally during traceback. Defaults to `True`. - **out_path** (os.PathLike | None) - Optional - If provided, the resulting DataFrame is written to this path before being returned. The format is inferred from the file extension. ### Response #### Success Response (200) - **result** (polars.DataFrame) - A DataFrame with precision and coverage metrics. At peptide level, each row is one PSM; at amino acid level (`aa_level=True`), each row is one aligned amino acid position. #### Response Example { "result": "[DataFrame object]" } #### Error Response (400) - **error** (str) - ValueError: If `ground_truth_df` is `None` and either `mgf_df` or `mztab_df` is also `None`. ``` -------------------------------- ### Plot Precision-Coverage Curve Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/getting_started.md Generates a precision-coverage curve plot from a Casanovo mzTab output file and its corresponding MGF input file. The area under the curve (AUPC) is automatically calculated and displayed. ```bash graph-prec-cov \ add-peptides results.mztab ground_truth.mgf "My Model" \ save prec_cov.png ``` -------------------------------- ### GET /residues Source: https://context7.com/noble-lab/casanovoutils/llms.txt Loads a mapping of amino acid residue names to their respective masses from a YAML file or the default bundled table. ```APIDOC ## GET /residues ### Description Loads a mapping of amino acid residue names to masses. If no path is provided, the function loads the bundled default residue mass table. ### Method GET ### Parameters #### Query Parameters - **path** (string) - Optional - Path to a custom YAML file containing residue masses. ### Request Example `get_residues(path="my_residues.yaml")` ### Response #### Success Response (200) - **dict** (object) - A dictionary mapping residue names to float mass values. #### Response Example { "G": 57.021464, "C[Carbamidomethyl]": 160.030649 } ``` -------------------------------- ### Export Residue Mass Table Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/getting_started.md Exports the current residue mass table to a YAML file. This file can be edited to include custom modifications or non-standard residues, and then passed back to other Casanovo tools using the `--residues_path` option. ```bash casanovo-utils dump-residues residues.yaml ``` -------------------------------- ### Downsample MGF File Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/getting_started.md Reduces the number of spectra in an MGF file by retaining a specified maximum number of spectra per peptide sequence. Outputs the downsampled spectra to a new MGF file. ```bash downsample-ms input.mgf --outfile sampled.mgf --k 2 ``` -------------------------------- ### GET /get_prec_cov_df Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/autoapi/casanovoutils/prec_cov/index.md Builds a precision-coverage DataFrame at either the peptide or amino acid level by comparing predicted and ground truth PSM DataFrames. ```APIDOC ## GET /get_prec_cov_df ### Description Builds a precision-coverage DataFrame from predicted and ground truth PSM data. This function handles tokenization, alignment, and score parsing to compute cumulative precision and coverage. ### Method GET ### Endpoint /get_prec_cov_df ### Parameters #### Query Parameters - **predicted_df** (DataFrame) - Required - The DataFrame containing predicted PSMs. - **ground_truth_df** (DataFrame) - Required - The DataFrame containing ground truth PSMs. - **level** (str) - Optional - The level of evaluation, either 'peptide' or 'amino_acid'. ### Response #### Success Response (200) - **precision** (float) - Cumulative precision value. - **coverage** (float) - Cumulative coverage value. ### Response Example { "precision": [0.95, 0.92, 0.88], "coverage": [0.1, 0.2, 0.3] } ``` -------------------------------- ### Execute CLI entry point for precision-coverage Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/autoapi/casanovoutils/prec_cov/index.md The main function serves as the command-line interface entry point for the precision-coverage module. ```python from casanovoutils.prec_cov import main if __name__ == "__main__": main() ``` -------------------------------- ### Execute CLI Commands for Data Processing Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/autoapi/casanovoutils/utils/index.md Demonstrates how to invoke the casanovoutils CLI to process MGF, mzTab, or ground truth files. These commands map to internal data loading functions and require an output path argument. ```bash python module.py get_mgf_psms path/to/file.mgf --out_path out.parquet python module.py get_mztab path/to/file.mztab --out_path out.parquet python module.py get_groundtruth path/to/file.mgf path/to/file.mztab --out_path out.parquet ``` -------------------------------- ### Configure Logging in Python Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/autoapi/casanovoutils/utils/index.md Configures the logging system to output to stdout at the INFO level. Optionally accepts a file path to enable append-mode logging to a specified file. ```python import os from casanovoutils.utils import configure_logging # Configure logging to stdout only configure_logging() # Configure logging to stdout and a file configure_logging(log_file="app.log") ``` -------------------------------- ### MGF Utilities: Write Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/cli_reference.md Writes the current spectra to a specified MGF file. ```APIDOC ## `write` ### Description Write the current spectra to an MGF file. ### Method Not applicable (command-line utility) ### Endpoint Not applicable (command-line utility) ### Parameters #### Query Parameters - **`--outfile`** (path) - Required - Output file path. Defaults to "out.mgf". ### Request Example ```bash mgf-utils input.mgf write --outfile merged.mgf ``` ### Response #### Success Response (200) An MGF file is created at the specified output path. #### Response Example (No direct response body, file is created at `--outfile` path) ``` -------------------------------- ### Chainable MGF Operations (CLI) Source: https://context7.com/noble-lab/casanovoutils/llms.txt Provides a chainable interface for working with one or more MGF files. Input files are streamed together as a single dataset, and operations like shuffle, downsample, and write can be chained in sequence. The class maintains state across method calls, enabling complex pipelines in a single command. ```bash # Merge two MGF files and write to a new file mgf-utils file1.mgf file2.mgf write --outfile merged.mgf # Downsample then write mgf-utils input.mgf downsample --k 3 write --outfile downsampled.mgf # Merge, downsample, and write in one command mgf-utils file1.mgf file2.mgf \ downsample --k 5 \ write --outfile merged_downsampled.mgf # Set a custom random seed for reproducibility mgf-utils input.mgf --random_seed 123 \ shuffle \ downsample --k 2 \ write --outfile processed.mgf ``` -------------------------------- ### POST /get_prec_cov_df Source: https://context7.com/noble-lab/casanovoutils/llms.txt Builds a precision-coverage DataFrame from predicted and ground truth PSMs for model evaluation. ```APIDOC ## POST /get_prec_cov_df ### Description Computes precision-coverage metrics by comparing ground truth MGF data against mzTab predictions. ### Method POST ### Parameters #### Request Body - **mgf_df** (string) - Required - Path to ground truth MGF. - **mztab_df** (string) - Required - Path to predictions mzTab. - **aa_level** (bool) - Optional - Whether to perform amino-acid-level evaluation. ### Response #### Success Response (200) - **dataframe** (object) - A DataFrame containing 'pc_precision' and 'pc_coverage' columns. ``` -------------------------------- ### CasanovoUtils: Dump Residues Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/cli_reference.md Copies the default residue mass table to a specified path, allowing for custom modifications. ```APIDOC ## `dump-residues` ### Description Copy the default residue mass table (a YAML file) to a specified path. This file can then be edited and passed back to other tools via `--residues_path`. ### Method Not applicable (command-line utility) ### Endpoint Not applicable (command-line utility) ### Parameters #### Path Parameters - **`destination_path`** (path) - Required - Destination path for the YAML file. ### Request Example ```bash casanovo-utils dump-residues my_residues.yaml ``` ### Response #### Success Response (200) A YAML file containing residue masses is created at the `destination_path`. #### Response Example (No direct response body, file is created at `destination_path`) ``` -------------------------------- ### Join MGF and mzTab Data with get_ground_truth_df Source: https://context7.com/noble-lab/casanovoutils/llms.txt Joins MGF PSM metadata with mzTab spectrum match annotations. Aligns data based on spectrum index and performs a left join. Dependencies: casanovoutils.utils. Inputs: MGF file path, mzTab file path. Outputs: Unified Pandas DataFrame with joined columns. ```python from casanovoutils.utils import get_ground_truth_df # Join MGF ground truth with mzTab predictions merged_df = get_ground_truth_df( mgf_path="experiment.mgf", mztab_path="casanovo_output.mztab", out_path="merged_data.parquet" ) # Access joined columns print(merged_df.columns) ``` -------------------------------- ### Downsample and Write Spectra (Bash) Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/cli_reference.md Performs downsampling of spectra based on peptide sequence, limiting the number of spectra per peptide using the `--k` argument, and then writes the result to an MGF file specified by `--outfile`. ```bash mgf-utils input.mgf downsample --k 3 write --outfile downsampled.mgf ``` -------------------------------- ### Build Precision-Coverage DataFrame with get_prec_cov_df Source: https://context7.com/noble-lab/casanovoutils/llms.txt Builds a precision-coverage DataFrame from predicted and ground truth PSMs. Supports peptide-level and amino-acid-level evaluation, with options for sequence alignment and score parsing. Dependencies: casanovoutils.prec_cov. Inputs: MGF file path, mzTab file path, evaluation level flags. Outputs: Pandas DataFrame with precision-coverage metrics. ```python from casanovoutils.prec_cov import get_prec_cov_df # Peptide-level precision-coverage evaluation pc_df = get_prec_cov_df( mgf_df="ground_truth.mgf", mztab_df="predictions.mztab", replace_isoleucine_with_leucine=True, aa_level=False, out_path="peptide_prec_cov.parquet" ) # Access precision and coverage columns precision = pc_df.get_column("pc_precision").to_numpy() coverage = pc_df.get_column("pc_coverage").to_numpy() # Amino-acid-level evaluation with sequence alignment aa_pc_df = get_prec_cov_df( mgf_df="ground_truth.mgf", mztab_df="predictions.mztab", aa_level=True, align_tie_beak_suffix=True, out_path="aa_prec_cov.parquet" ) ``` -------------------------------- ### Merge, Downsample, and Write Spectra (Bash) Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/cli_reference.md Combines multiple MGF files, downsamples the merged spectra (limiting to `--k` spectra per peptide), and writes the final output to a specified MGF file using the `--outfile` argument. ```bash mgf-utils file1.mgf file2.mgf \ downsample --k 5 \ write --outfile merged_downsampled.mgf ``` -------------------------------- ### Write Spectra to MGF File (Bash) Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/cli_reference.md Writes the current spectra to a specified MGF file. The `--outfile` argument defines the output file path. If not provided, it defaults to 'out.mgf'. ```bash mgf-utils file1.mgf file2.mgf write --outfile merged.mgf ``` -------------------------------- ### Dump Default Residue Mass Table (Bash) Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/cli_reference.md Copies the default residue mass table, typically a YAML file, to a specified destination path. This allows for customization of residue masses for use with other tools via the `--residues_path` argument. ```bash casanovo-utils dump-residues my_residues.yaml ``` -------------------------------- ### Load Amino Acid Mass Table with get_residues Source: https://context7.com/noble-lab/casanovoutils/llms.txt Loads a mapping of amino acid residue names to masses from a YAML file. If no path is provided, it loads a default bundled table including standard amino acids and common modifications. Dependencies: casanovoutils. Inputs: Optional YAML file path. Outputs: Dictionary mapping residue names to masses. ```python from casanovoutils import get_residues # Load the default residue mass table residues = get_residues() print(residues["G"]) # Glycine: 57.021464 print(residues["C[Carbamidomethyl]"]) # 160.030649 # Load a custom residue mass table custom_residues = get_residues("my_residues.yaml") ``` -------------------------------- ### Load residue masses from YAML Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/autoapi/casanovoutils/utils/index.md Loads a mapping of amino acid residue names to their masses from a YAML file. If no path is provided, it defaults to the bundled residues.yaml file. ```python from casanovoutils.utils import get_residues # Load default residues residues = get_residues() # Load custom residues custom_residues = get_residues(residues_path="path/to/custom_residues.yaml") ``` -------------------------------- ### Build Precision-Coverage Plot with GraphPrecCov Source: https://context7.com/noble-lab/casanovoutils/llms.txt A dataclass-based plot builder for creating and comparing precision-coverage curves. Accumulates datasets, computes AUPC, and displays values in the legend. Designed for programmatic use and CLI. Dependencies: casanovoutils.prec_cov. Inputs: Precision-coverage dataframes, plot settings. Outputs: Saved plot image. ```python from casanovoutils.prec_cov import GraphPrecCov, get_prec_cov_df # Create a precision-coverage plotter with custom settings plotter = GraphPrecCov( fig_width=6.0, fig_height=4.0, fig_dpi=150, legend_location="lower left", ax_x_label="Coverage", ax_y_label="Precision" ) # Compute precision-coverage data and add to plot pc_df = get_prec_cov_df( mgf_df="ground_truth.mgf", mztab_df="predictions.mztab" ) plotter.add_series(pc_df, "Model A") # Add another dataset pc_df2 = get_prec_cov_df( mgf_df="ground_truth.mgf", mztab_df="predictions_b.mztab" ) plotter.add_series(pc_df2, "Model B") # Save the comparison plot plotter.save("comparison.png") ``` -------------------------------- ### Downsample and Write MGF with downsample_mgf_pep Source: https://context7.com/noble-lab/casanovoutils/llms.txt A convenience wrapper that downsamples spectra by peptide and writes the result directly to an MGF file. This combines downsampling and file output. Dependencies: casanovoutils.downsample. Inputs: Input MGF file path, output MGF file path, k (max spectra per peptide), shuffle (boolean), random_seed. Outputs: None (writes to file). ```python from casanovoutils.downsample import downsample_mgf_pep # Downsample and write to a new MGF file downsample_mgf_pep( spectra="input.mgf", outfile="sampled.mgf", k=3, shuffle=True, random_seed=42 ) ``` -------------------------------- ### Function: downsample_mgf_pep Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/autoapi/casanovoutils/downsample/index.md A convenience wrapper that performs downsampling and writes the resulting spectra directly to an MGF file. ```APIDOC ## FUNCTION downsample_mgf_pep ### Description Downsamples spectra by peptide and writes the output directly to a specified MGF file path. ### Parameters - **spectra** (os.PathLike | Iterable) - Required - Input MGF path or spectrum iterable. - **outfile** (os.PathLike) - Optional - Output path for the MGF file (default: 'out.mgf'). - **k** (int) - Optional - Max PSMs per peptide (default: 1). - **shuffle** (bool) - Optional - Whether to shuffle before writing (default: False). - **random_seed** (int) - Optional - Random seed (default: 42). ### Response - **Returns** (None) - Writes the downsampled spectra to the specified outfile. ``` -------------------------------- ### POST /downsample_mgf_pep Source: https://context7.com/noble-lab/casanovoutils/llms.txt Convenience wrapper to downsample spectra by peptide and write the result directly to an MGF file. ```APIDOC ## POST /downsample_mgf_pep ### Description Performs peptide-based downsampling and saves the output to a specified MGF file. ### Method POST ### Parameters #### Request Body - **spectra** (string) - Required - Input MGF path. - **outfile** (string) - Required - Output MGF path. - **k** (int) - Required - Max spectra per peptide. ### Request Example { "spectra": "input.mgf", "outfile": "sampled.mgf", "k": 3 } ``` -------------------------------- ### Downsample MGF Files by Peptide (CLI) Source: https://context7.com/noble-lab/casanovoutils/llms.txt Downsamples one or more MGF files by limiting the number of spectra retained per peptide sequence. Useful for dataset balancing, reducing redundancy, and faster benchmarking. Supports reproducible sampling via random seeds and optional shuffling of output spectra. ```bash # Keep at most 1 spectrum per peptide (default) downsample-ms input.mgf --outfile sampled.mgf # Keep up to 5 spectra per peptide with shuffling downsample-ms input.mgf --outfile sampled.mgf --k 5 --shuffle # Reproducible sampling with a specific random seed downsample-ms input.mgf --outfile sampled.mgf --k 2 --random_seed 0 ``` -------------------------------- ### Fill Null Columns with Defaults Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/autoapi/casanovoutils/prec_cov/index.md Standardizes DataFrames by filling null values in sequence and score columns with empty strings or -1.0 respectively. ```python def fill_null_columns(df: polars.DataFrame, pred_col: str) -> polars.DataFrame: return df.with_columns([ pl.col(pred_col).fill_null(""), pl.col("score").fill_null(-1.0) ]) ``` -------------------------------- ### Load Ground Truth DataFrame Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/autoapi/casanovoutils/prec_cov/index.md Constructs or loads a ground truth PSM DataFrame from provided file paths or existing objects. Raises a ValueError if required inputs are missing. ```python def load_ground_truth_df(ground_truth_df=None, mgf_df=None, mztab_df=None) -> polars.DataFrame: if ground_truth_df is None and (mgf_df is None or mztab_df is None): raise ValueError("Missing required input files") # Logic to load or construct DataFrame return df ``` -------------------------------- ### Chainable MGF Operations with MgfUtils Source: https://context7.com/noble-lab/casanovoutils/llms.txt A stateful utility class for working with MGF files, allowing chained operations like shuffling and downsampling. Uses pyteomics.mgf.chain for memory-efficient streaming. Dependencies: casanovoutils.mgfutils, pyteomics. Inputs: One or more MGF file paths, random_seed. Outputs: Modified MGF data written to a file. ```python from casanovoutils.mgfutils import MgfUtils # Create instance with multiple input files mgf = MgfUtils("file1.mgf", "file2.mgf", random_seed=42) # Chain operations mgf.downsample(k=5) mgf.write(outfile="merged_downsampled.mgf") ``` -------------------------------- ### MGF Utilities: Downsample Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/cli_reference.md Downsamples spectra by peptide sequence, limiting the number of spectra per peptide. ```APIDOC ## `downsample` ### Description Downsample spectra by peptide sequence. ### Method Not applicable (command-line utility) ### Endpoint Not applicable (command-line utility) ### Parameters #### Query Parameters - **`--k`** (int) - Optional - Maximum spectra per peptide sequence. Defaults to 1. ### Request Example ```bash mgf-utils input.mgf downsample --k 3 ``` ### Response #### Success Response (200) Output is written to stdout or piped to another command. #### Response Example (No direct response body, output depends on subsequent commands) ``` -------------------------------- ### Class GraphPrecCov Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/autoapi/casanovoutils/prec_cov/index.md Stateful plot builder for accumulating and comparing multiple precision-coverage curves. ```APIDOC ## Class GraphPrecCov ### Description Stateful class for accumulating multiple datasets onto a single precision-coverage plot. Useful for programmatic or CLI-based visualization. ### Parameters - **fig_width** (float) - Optional - Width of the figure in inches. - **fig_height** (float) - Optional - Height of the figure in inches. - **legend_location** (str) - Optional - Location of the legend. ### Methods - **add_peptides(data)**: Adds a new curve to the current axes. - **clear()**: Resets the current figure. - **show()**: Displays the accumulated plot. ``` -------------------------------- ### Export Residue Mass Table (CLI) Source: https://context7.com/noble-lab/casanovoutils/llms.txt Exports the default residue mass table (a YAML file) to a specified path. This file can be edited to add custom modifications or non-standard residues, then passed back to other tools via the `--residues_path` option. ```bash # Export the default residue mass table casanovo-utils dump-residues my_residues.yaml # Edit my_residues.yaml to add custom modifications, then use it: graph-prec-cov --residues_path my_residues.yaml \ add-peptides results.mztab truth.mgf "Custom" \ save custom_eval.png ``` -------------------------------- ### Plot Precision-Coverage Curves (CLI) Source: https://context7.com/noble-lab/casanovoutils/llms.txt Plots and compares precision-coverage curves for peptide-level predictions from one or more datasets. Calculates the area under the precision-coverage curve (AUPC) and displays it in the legend. Supports configurable figure dimensions, legend positioning, and axis labels. ```bash # Plot a single precision-coverage curve graph-prec-cov \ add-peptides results.mztab ground_truth.mgf "Casanovo" \ save prec_cov.png # Compare multiple models on one figure with custom dimensions graph-prec-cov \ --fig_width 6 \ --fig_height 4 \ --legend_location "upper right" \ add-peptides modelA.mztab truth.mgf "Model A" \ add-peptides modelB.mztab truth.mgf "Model B" \ save comparison.png # Disable I/L equivalence for strict evaluation graph-prec-cov \ add-peptides results.mztab truth.mgf "Strict" --noreplace_i_l \ save strict.png ``` -------------------------------- ### Downsample Spectra by Peptide with downsample_spectra Source: https://context7.com/noble-lab/casanovoutils/llms.txt Downsamples spectra by limiting the number of PSMs per peptide sequence. Spectra are grouped by peptide, then up to k are randomly sampled. The resulting spectra can optionally be shuffled. Dependencies: casanovoutils.downsample. Inputs: Spectra file (e.g., MGF), k (max spectra per peptide), shuffle (boolean), random_seed. Outputs: Iterable of spectrum dictionaries. ```python from casanovoutils.downsample import downsample_spectra # Downsample to at most 2 spectra per peptide sampled = downsample_spectra( spectra="experiment.mgf", k=2, shuffle=True, random_seed=42 ) # Result is an iterable of spectrum dictionaries print(f"Retained {len(list(sampled))}" spectra after downsampling) ``` -------------------------------- ### Align Tokens with Gaps - Python Source: https://context7.com/noble-lab/casanovoutils/llms.txt Aligns two token sequences by inserting gap markers to maximize exact position-wise matches. Gaps are inserted into the shorter sequence using dynamic programming and greedy traceback. It takes predicted and ground truth sequences along with their scores as input. ```python from casanovoutils.align import align_tokens_with_gaps # Align predicted and ground truth token sequences predicted = ["P", "E", "P", "T", "I", "D", "E"] ground_truth = ["P", "E", "P", "T", "I", "D", "E", "K"] scores = [0.99, 0.98, 0.97, 0.96, 0.95, 0.94, 0.93] aligned_pred, aligned_gt, aligned_scores = align_tokens_with_gaps( predicted=predicted, ground_truth=ground_truth, scores=scores, gap="-", tie_break_suffix=True ) print(aligned_pred) # ['P', 'E', 'P', 'T', 'I', 'D', 'E', '-'] print(aligned_gt) # ['P', 'E', 'P', 'T', 'I', 'D', 'E', 'K'] print(aligned_scores) # [0.99, 0.98, 0.97, 0.96, 0.95, 0.94, 0.93, -1.0] ``` -------------------------------- ### Group Spectra by Peptide Sequence (Python API) Source: https://context7.com/noble-lab/casanovoutils/llms.txt Reads spectra from an MGF file and groups them by peptide sequence into a dictionary. This function iterates through all spectra and builds a mapping from each peptide sequence to its corresponding list of PSM entries. It accepts either a file path or an existing Pyteomics MGF reader. ```python from casanovoutils import get_pep_dict_mgf # Group spectra by peptide sequence from an MGF file pep_dict = get_pep_dict_mgf("experiment.mgf") # Access spectra for a specific peptide peptide_spectra = pep_dict["PEPTIDEK"] print(f"Found {len(peptide_spectra)} spectra for PEPTIDEK") # Iterate over all peptides and their spectra for peptide, spectra in pep_dict.items(): print(f"{peptide}: {len(spectra)} PSMs") ``` -------------------------------- ### Align and Explode Sequences Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/autoapi/casanovoutils/prec_cov/index.md Aligns predicted and ground truth token sequences and explodes the data to per-AA rows. ```APIDOC ## POST /casanovoutils/prec_cov/align_and_explode ### Description Align predicted and ground truth token sequences and explode to per-AA rows. Iterates over each row, aligns the predicted and ground truth token sequences with gap insertion via [`mutate_row_as_dict()`](#casanovoutils.prec_cov.mutate_row_as_dict), then explodes the resulting list columns so that each row corresponds to a single amino acid position. ### Method POST ### Endpoint /casanovoutils/prec_cov/align_and_explode ### Parameters #### Request Body - **df** (polars.DataFrame) - Required - Input DataFrame with tokenized predicted and ground truth sequence columns and parsed per-amino-acid scores. - **tie_break_suffix** (bool) - Required - Passed through to [`mutate_row_as_dict()`](#casanovoutils.prec_cov.mutate_row_as_dict). Controls tie-breaking behavior when the gap and no-gap paths score equally during traceback. ### Response #### Success Response (200) - **result** (polars.DataFrame) - A DataFrame exploded to one row per aligned amino acid position, with gap characters inserted where sequences do not align. #### Response Example { "result": "[DataFrame object]" } ``` -------------------------------- ### Define Global Constants for Column Names and Sentinel Values Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/autoapi/casanovoutils/constants/index.md This snippet defines global constants for various column names and sentinel values used within the casanovoutils library. These constants are typically strings representing column headers in DataFrames or float values for specific purposes like minimum scores. ```python class Constants: ground_truth_sequence_column: str = 'mgf_seq' aa_scores_column: str = 'mztab_opt_ms_run[1]_aa_scores' pep_score_column: str = 'mztab_search_engine_score[1]' aa_idx_column: str = 'pc_aa_idx' precision_column: str = 'pc_precision' coverage_column: str = 'pc_coverage' predicted_tokens: str = 'mztab_tokens' ground_truth_tokens: str = 'mgf_tokens' min_score: float = -1.0 ``` -------------------------------- ### POST /downsample_spectra Source: https://context7.com/noble-lab/casanovoutils/llms.txt Downsamples spectra by grouping them by peptide sequence and limiting the number of PSMs per sequence. ```APIDOC ## POST /downsample_spectra ### Description Groups spectra by peptide sequence and randomly samples up to k spectra for each unique peptide. ### Method POST ### Parameters #### Request Body - **spectra** (string) - Required - Path to the input MGF file. - **k** (int) - Required - Maximum number of spectra to retain per peptide. - **shuffle** (bool) - Optional - Whether to shuffle the resulting spectra. - **random_seed** (int) - Optional - Seed for reproducibility. ### Request Example { "spectra": "experiment.mgf", "k": 2, "shuffle": true, "random_seed": 42 } ### Response #### Success Response (200) - **iterable** (list) - An iterable of spectrum dictionaries. ``` -------------------------------- ### Calculate Precision and Coverage Metrics Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/autoapi/casanovoutils/prec_cov/index.md Computes cumulative precision and coverage metrics based on a score column. It sorts the input DataFrame and generates boolean correctness, precision, and coverage columns. ```python def calc_precision_coverage(pc_df: polars.DataFrame, score_col: str) -> polars.DataFrame: # Sorts by score_col and calculates cumulative metrics return pc_df.with_columns([ (pl.col("match") == True).alias("pc_is_correct"), # ... precision and coverage calculation logic ]) ``` -------------------------------- ### Tokenize peptide sequences Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/autoapi/casanovoutils/utils/index.md Splits peptide sequences into tokens using a provided tokenizer. Supports merging N-terminal modifications with the first residue token. ```python from casanovoutils.utils import tokenize_helper import depthcharge tokenizer = depthcharge.tokenizers.PeptideTokenizer() seq = "[UNIMOD:1]PEPTIDE" tokens = tokenize_helper(seq, tokenizer, combine_n_term=True) ``` -------------------------------- ### Plot precision-coverage curves using graph_prec_cov Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/autoapi/casanovoutils/prec_cov/index.md Generates and optionally saves precision-coverage plots from one or more DataFrame files. It uses the file stem as the series label and supports various output formats based on the file extension. ```python from casanovoutils.prec_cov import graph_prec_cov # Plotting from multiple files and saving to a specific path graph_prec_cov("path/to/data1.csv", "path/to/data2.csv", out_path="output_plot.png") ``` -------------------------------- ### POST /graph_prec_cov Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/autoapi/casanovoutils/prec_cov/index.md Plots pre-computed precision-coverage DataFrames using matplotlib. ```APIDOC ## POST /graph_prec_cov ### Description Generates a matplotlib figure from one or more pre-computed precision-coverage DataFrames. ### Method POST ### Endpoint /graph_prec_cov ### Request Body - **dataframes** (List[DataFrame]) - Required - List of pre-computed precision-coverage DataFrames. - **output_path** (str) - Optional - File path to save the generated figure. ### Response #### Success Response (200) - **status** (str) - Confirmation of plot generation. ### Response Example { "status": "success", "message": "Plot generated successfully" } ``` -------------------------------- ### Tokenize and Parse Scores Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/autoapi/casanovoutils/prec_cov/index.md Tokenizes predicted and ground truth sequences and parses per-AA score strings into lists of floats. ```APIDOC ## POST /casanovoutils/prec_cov/tokenize_and_parse_scores ### Description Tokenize predicted and ground truth sequences and parse per-AA score strings. Applies `tokenize_sequences()` to both the ground truth and predicted sequence columns, then parses the comma-separated per-amino-acid score strings in the aa scores column into lists of floats. ### Method POST ### Endpoint /casanovoutils/prec_cov/tokenize_and_parse_scores ### Parameters #### Request Body - **df** (polars.DataFrame) - Required - Input DataFrame containing sequence and score columns. - **pred_col** (str) - Required - Name of the predicted sequence column. - **residues_path** (os.PathLike | None) - Optional - Path to a residue mass YAML file. If `None`, the bundled `residues.yaml` is used. - **replace_isoleucine_with_leucine** (bool) - Required - If `True`, isoleucine (I) is replaced with leucine (L) during tokenization, treating them as equivalent. ### Response #### Success Response (200) - **result** (polars.DataFrame) - The DataFrame with added token columns and the aa scores column converted from comma-separated strings to lists of floats. #### Response Example { "result": "[DataFrame object]" } ``` -------------------------------- ### Process and tokenize sequence DataFrames Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/autoapi/casanovoutils/utils/index.md Applies tokenization to a specific column in a Polars DataFrame and appends the resulting token list and sequence length as new columns. ```python import polars as pl from casanovoutils.utils import tokenize_sequences df = pl.DataFrame({"peptide": ["PEPTIDE", "KPEPTIDE"]}) tokenized_df = tokenize_sequences(df, seq_column="peptide", out_prefix="pep") ``` -------------------------------- ### Tokenize Sequences - Python Source: https://context7.com/noble-lab/casanovoutils/llms.txt Tokenizes a peptide sequence column in a Polars DataFrame and appends token and length columns. It uses depthcharge's MskbPeptideTokenizer and supports custom residue mass tables and I/L equivalence. Input is a Polars DataFrame with a 'sequence' column. ```python from casanovoutils.utils import tokenize_sequences import polars as pl # Create a DataFrame with peptide sequences df = pl.DataFrame({ "sequence": ["PEPTIDEK", "M[Oxidation]YPEPTIDE", "[Acetyl]-ACDEFG"] }) # Tokenize sequences with I/L equivalence df = tokenize_sequences( df, seq_column="sequence", out_prefix="pep", residues_path=None, # Use default residue table replace_isoleucine_with_leucine=True ) print(df.columns) # ['sequence', 'pep_tokens', 'pep_sequence_len'] print(df["pep_tokens"][0]) # ['P', 'E', 'P', 'T', 'L', 'D', 'E', 'K'] ``` -------------------------------- ### Read and merge proteomics data Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/autoapi/casanovoutils/utils/index.md Provides utilities to read various file formats into Polars DataFrames and join MGF metadata with mzTab annotations. ```python from casanovoutils.utils import read_dataframe, get_mztab_df, get_ground_truth_df # Read generic dataframe df = read_dataframe("data.parquet") # Load mzTab data mztab_df = get_mztab_df("results.mztab") # Join MGF and mzTab data combined_df = get_ground_truth_df("spectra.mgf", "results.mztab") ``` -------------------------------- ### Function: downsample_spectra Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/autoapi/casanovoutils/downsample/index.md Downsamples a collection of spectra by limiting the number of PSMs per peptide sequence to a specified maximum. ```APIDOC ## FUNCTION downsample_spectra ### Description Groups spectra by peptide sequence and randomly samples up to 'k' spectra per unique peptide. Returns an iterable of the sampled spectra. ### Parameters - **spectra** (os.PathLike | Iterable) - Required - Path to MGF file or iterable of Pyteomics spectrum dictionaries. - **k** (int) - Required - Maximum number of spectra (PSMs) to retain per unique peptide. - **shuffle** (bool) - Required - Whether to shuffle the final list of sampled spectra. - **random_seed** (int | None) - Optional - Seed for reproducible sampling. ### Response - **Returns** (Iterable[PyteomicsSpectrum]) - A list-like iterable of downsampled spectrum dictionaries. ``` -------------------------------- ### Mutate Row for Token Alignment Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/autoapi/casanovoutils/prec_cov/index.md Aligns predicted and ground truth token sequences within a dictionary row. This function mutates the row in-place to include gap-aligned sequences and scores. ```python def mutate_row_as_dict(tie_break_suffix: bool, row: dict[str, Any]) -> dict[str, Any]: # Mutates row in-place with aligned sequences and scores return row ``` -------------------------------- ### Determine Predicted Sequence Column Name Dynamically Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/autoapi/casanovoutils/constants/index.md This function dynamically determines the name of the predicted sequence column within a Polars DataFrame. It prioritizes checking for a ProForma-formatted column and falls back to a standard mzTab sequence column if the ProForma column is not found. The input is a Polars DataFrame, and the output is the string name of the identified column. ```python import polars as pl class Constants: # ... other constants ... @staticmethod def get_pred_sequence_column(df: pl.DataFrame) -> str: """Determine the name of the predicted sequence column. Checks for the presence of a ProForma-formatted prediction column first, falling back to the plain mzTab sequence column if it is absent. Parameters ---------- df : polars.DataFrame A DataFrame expected to contain either "mztab_opt_ms_run[1]_proforma" or "mztab_sequence". Returns ------- str The name of the predicted sequence column. """ proforma_col = "mztab_opt_ms_run[1]_proforma" mztab_seq_col = "mztab_sequence" if proforma_col in df.columns: return proforma_col elif mztab_seq_col in df.columns: return mztab_seq_col else: raise ValueError("Neither ProForma nor mzTab sequence column found.") ``` -------------------------------- ### Add Precision-Coverage Series to Plot Source: https://github.com/noble-lab/casanovoutils/blob/main/docs/autoapi/casanovoutils/prec_cov/index.md Adds a precision-coverage curve to the current matplotlib figure. It computes the Area Under the Precision-Coverage (AUPC) curve using the trapezoidal rule and labels the series in the legend. ```python def add_series(pc_df: polars.DataFrame, series_name: str, color: str | None = None, linestyle: str | None = None) -> None: # Implementation logic for computing AUPC and plotting with matplotlib pass ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.