### Install Cascadia using Conda and Pip Source: https://github.com/noble-lab/cascadia/blob/main/docs/source/getting_started.md Installs Cascadia and its dependencies using conda for environment management and pip for package installation. Requires Python 3.10 and creates a dedicated conda environment named 'cascadia_env'. ```shell conda create --name cascadia_env python=3.10 conda activate cascadia_env pip install cascadia ``` -------------------------------- ### Train a New Cascadia Model from Scratch Source: https://github.com/noble-lab/cascadia/blob/main/docs/source/getting_started.md Trains a new Cascadia model using labeled training and validation datasets in .asf format. Requires specifying the paths to both datasets as positional arguments. ```shell cascadia train training_data.asf validation_data.asf ``` -------------------------------- ### .asf Format Example - Default Source: https://github.com/noble-lab/cascadia/blob/main/docs/source/file_formats.md An example of an augmented spectrum in the .asf format, demonstrating the required annotations and the structure of peak data. This format is crucial for training Cascadia. ```default BEGIN IONS TITLE=1 PEPMASS=402.5 CHARGE=1 SCAN=1 RT=0.31070598402 SEQ=PEPTIDEK 185.07986450195312 0.666241404428991 0 2 367.8453063964844 0.4087404090593467 0 2 400.98358154296875 0.8838386047632094 0 2 401.1849060058594 0.4504917813994659 0 2 401.2586669921875 0.42375381912879023 0 2 401.9834289550781 0.6479885582525154 0 2 418.99261474609375 0.6245163448036832 0 2 606.7568359378328 0.41198908195979644 0 2 606.756835937573 0.41198908195979644 0 2 843.2614135742188 0.41591027114618606 0 2 946.1708374023438 0.430206516710194 0 2 185.07986450195312 0.666241404428991 1 2 367.8453063964844 0.4087404090593467 1 2 400.98358154296875 0.8838386047632094 1 2 401.1849060058594 0.4504917813994659 1 2 401.2586669921875 0.42375381912879023 1 2 401.9834289550781 0.6479885582525154 1 2 418.99261474609375 0.6245163448036832 1 2 185.07986450195312 0.666241404428991 -1 2 367.8453063964844 0.4087404090593467 -1 2 400.98358154296875 0.8838386047632094 -1 2 401.1849060058594 0.4504917813994659 -1 2 401.2586669921875 0.42375381912879023 -1 2 401.9834289550781 0.6479885582525154 -1 2 418.99261474609375 0.6245163448036832 -1 2 606.7568359375737 0.41198908195979644 -1 2 843.2614135742188 0.41591027114618606 -1 2 946.1708374023438 0.430206516710194 -1 2 400.1812744140625 0.2918983249625358 0 1 400.3501892089844 0.3196363715025925 0 1 401.2091979980469 0.34867104752184375 0 1 403.2320556640625 0.30672175589489503 0 1 402.2713624687576 0.2951177103313615 -1 1 403.17193603515625 0.362321942870444 -1 1 END IONS ``` -------------------------------- ### Fine-tune a Pre-trained Cascadia Model Source: https://github.com/noble-lab/cascadia/blob/main/docs/source/getting_started.md Fine-tunes an existing pre-trained Cascadia model on new data. This is achieved by providing the path to the pre-trained model checkpoint as an additional argument to the 'train' command. ```shell cascadia train training_data.asf validation_data.asf \ --model pretrained_checkpoint.ckpt ``` -------------------------------- ### Run De Novo Sequencing with Cascadia Source: https://github.com/noble-lab/cascadia/blob/main/docs/source/getting_started.md Performs de novo sequencing on input MS data (mzML format) using a pre-trained Cascadia model. Outputs results to a specified file (e.g., demo_results.ssl) which can be loaded into Skyline. Recommended for Linux with a GPU. ```shell cascadia sequence \ demo.mzML \ cascadia.ckpt \ --out demo_results ``` -------------------------------- ### SSL (Spectrum Sequence List) File Format Example Source: https://context7.com/noble-lab/cascadia/llms.txt The SSL format is compatible with Skyline for spectral library generation and result visualization. It is a tab-delimited file containing information about the source file, scan, charge, sequence, score type, score, retention time, and time window. ```text file scan charge sequence score-type score retention-time start-time end-time experiment.mzML 1 2 PEPTIDEK UNKNOWN 0.95 15.5 14.5 16.5 experiment.mzML 2 3 M[+15.99]ASSSPEC UNKNOWN 0.87 22.3 21.3 23.3 ``` -------------------------------- ### ASF (Augmented Spectrum Format) Example Source: https://context7.com/noble-lab/cascadia/llms.txt The ASF format extends MGF to include augmented spectra with retention time and MS level information for training Cascadia models. It includes peak intensity, relative retention time, and MS level for each ion. ```text BEGIN IONS TITLE=1 PEPMASS=402.5 CHARGE=2 SCAN=1 RT=0.31070598402 SEQ=PEPTIDEK 185.079864 0.666241 0 2 367.845306 0.408740 0 2 400.983581 0.883838 0 2 401.184906 0.450491 1 2 401.258666 0.423753 -1 2 400.181274 0.291898 0 1 END IONS # Column format: m/z intensity relative_rt ms_level # relative_rt: position relative to center scan (-w to +w) # ms_level: 1 for MS1, 2 for MS2 ``` -------------------------------- ### Cascadia Model Training CLI Source: https://context7.com/noble-lab/cascadia/llms.txt Trains a new model from scratch or fine-tunes an existing checkpoint using labeled augmented spectrum files (.asf format). ```APIDOC ## POST /train ### Description Trains a new Cascadia model or fine-tunes an existing checkpoint using labeled augmented spectrum files. ### Method POST ### Endpoint /train ### Parameters #### Path Parameters - **training_data** (string) - Required - Path to the training data in .asf format. - **validation_data** (string) - Required - Path to the validation data in .asf format. #### Query Parameters - **model** (string) - Optional - Path to a pre-trained model checkpoint to fine-tune. - **batch_size** (integer) - Optional - Batch size for training (default: 32). - **width** (integer) - Optional - Retention time augmentation width (default: 2). - **max_charge** (integer) - Optional - Maximum precursor charge to consider (default: 4). - **max_epochs** (integer) - Optional - Maximum number of training epochs (default: 10). - **learning_rate** (float) - Optional - Learning rate for the optimizer (default: 1e-5). ### Request Example ```bash cascadia train training_data.asf validation_data.asf --model pretrained_checkpoint.ckpt --batch_size 32 --width 2 --max_charge 4 --max_epochs 10 --learning_rate 1e-5 ``` ### Response #### Success Response (200) - **checkpoint_path** (string) - Path to the newly saved model checkpoint. - **log_directory** (string) - Directory where TensorBoard logs are saved. #### Response Example ```json { "checkpoint_path": "checkpoint_MM-DD-HH:MM:SS/Cascadia-10-5000.ckpt", "log_directory": "logs/" } ``` ``` -------------------------------- ### Writing De Novo Sequencing Predictions to SSL Format Source: https://context7.com/noble-lab/cascadia/llms.txt The `write_results` function outputs de novo sequencing predictions in SSL format for visualization in Skyline. It requires the predictions, output file name, source mzML file name, and parameters for isolation window size, score threshold, and time width. ```python from cascadia.utils import write_results import numpy as np # After running trainer.predict(), write results to file # predictions format: list of (pred_seqs, true_seqs, pep_conf, aa_conf, rts, precursors) write_results( preds=predictions, # Output from trainer.predict() results_file="output", # Will create output.ssl raw_file="experiment.mzML", # Source mzML file name isolation_window_size=25, # Isolation window for mass filtering score_threshold=0.8, # Minimum confidence threshold time_width=60 # Retention time window in seconds ) ``` -------------------------------- ### Perform De Novo Peptide Sequencing via CLI Source: https://context7.com/noble-lab/cascadia/llms.txt The cascadia sequence command processes mzML files to perform de novo peptide sequencing. It supports various configuration parameters such as score thresholds, batch sizes, and custom modification vocabularies, outputting results in the SSL format. ```bash cascadia sequence sample.mzML model_checkpoint.ckpt cascadia sequence \ experiment.mzML \ cascadia.ckpt \ --outfile results \ --score_threshold 0.8 \ --batch_size 64 \ --width 2 \ --max_charge 4 \ --modifications mskb ``` -------------------------------- ### PeptideTokenizer (Python API) Source: https://context7.com/noble-lab/cascadia/llms.txt Handles parsing and tokenization of ProForma-compliant peptide sequences, including mass calculations. ```APIDOC ## Class: PeptideTokenizer ### Description Manages the tokenization and de-tokenization of peptide sequences, supporting various modification sets and custom ProForma inputs. It also facilitates mass calculations for precursor and fragment ions. ### Methods #### `from_massivekb` Creates a `PeptideTokenizer` instance using the MassIVE-KB modification vocabulary. - **replace_isoleucine_with_leucine** (bool) - Whether to replace 'I' with 'L'. - **reverse** (bool) - Whether to enable sequence reversal. #### `from_proforma` Creates a `PeptideTokenizer` instance from a list of custom ProForma sequences. - **sequences** (list[str]) - List of ProForma-compliant peptide sequences. - **replace_isoleucine_with_leucine** (bool) - Whether to replace 'I' with 'L'. - **reverse** (bool) - Whether to enable sequence reversal. #### `tokenize` Converts a list of peptide sequences into token indices. - **sequences** (list[str]) - List of peptide strings to tokenize. - **add_stop** (bool) - Whether to add a stop token at the end of each sequence. **Returns:** `torch.Tensor` of token indices. #### `detokenize` Converts a tensor of token indices back into peptide strings. - **tokens** (torch.Tensor) - Tensor of token indices. **Returns:** `list[str]` of detokenized peptide strings. ### Usage Example ```python from cascadia.depthcharge.tokenizers import PeptideTokenizer # Initialize with MassIVE-KB tokenizer_kb = PeptideTokenizer.from_massivekb( replace_isoleucine_with_leucine=True, reverse=False ) # Initialize with custom ProForma sequences custom_sequences = [ "PEPTIDEK", "M[Oxidation]ASSSPEC", "[Acetyl]-NTERM" ] tokenizer_custom = PeptideTokenizer.from_proforma( sequences=custom_sequences, replace_isoleucine_with_leucine=True, reverse=False ) # Tokenize sequences sequences = ["PEPTIDEK", "MASSSPEC"] tokens = tokenizer_kb.tokenize(sequences, add_stop=True) # Detokenize tokens peptides = tokenizer_kb.detokenize(tokens) print(peptides) # Output: ['PEPTIDEK', 'MASSSPEC'] ``` ``` -------------------------------- ### Calculate Ion m/z Values Source: https://context7.com/noble-lab/cascadia/llms.txt Calculates precursor and fragment ion m/z values for given peptide sequences and charge states. It returns a list of PeptideIons objects containing precursor m/z and fragment m/z arrays. ```python from cascadia.depthcharge.tokenizers import PeptideTokenizer # Initialize tokenizer tokenizer = PeptideTokenizer.from_massivekb( reverse=False, replace_isoleucine_with_leucine=True ) # Calculate precursor and fragment ion m/z values ions = tokenizer.ions( sequences=["PEPTIDEK"], precursor_charges=[2], max_fragment_charge=1 ) # Returns list of PeptideIons with precursor m/z and b/y fragment m/z arrays print(f"Precursor m/z: {ions[0].precursor}") print(f"Fragment ions shape: {ions[0].fragments.shape}") # (2, seq_len-1, charge) ``` -------------------------------- ### Initialize and Run AugmentedSpec2Pep Model Source: https://context7.com/noble-lab/cascadia/llms.txt The AugmentedSpec2Pep class is the core transformer model for peptide sequencing. This snippet demonstrates how to initialize the model from scratch or load it from a checkpoint, and how to execute inference using PyTorch Lightning. ```python import torch from cascadia.model import AugmentedSpec2Pep from cascadia.depthcharge.tokenizers import PeptideTokenizer import pytorch_lightning as pl tokenizer = PeptideTokenizer.from_massivekb(reverse=False, replace_isoleucine_with_leucine=True) model = AugmentedSpec2Pep( d_model=512, n_layers=9, n_head=8, dim_feedforward=1024, dropout=0, rt_width=2, tokenizer=tokenizer, max_charge=4, lr=1e-4 ) model = AugmentedSpec2Pep.load_from_checkpoint("cascadia.ckpt", d_model=512, n_layers=9, n_head=8, dim_feedforward=1024, dropout=0, rt_width=2, tokenizer=tokenizer, max_charge=10) trainer = pl.Trainer(accelerator='gpu', devices=1) predictions = trainer.predict(model, dataloaders=data_loader) ``` -------------------------------- ### Apply Preprocessing to Mass Spectra Source: https://context7.com/noble-lab/cascadia/llms.txt Provides functions to prepare mass spectra for model input, including intensity scaling and peak filtering. These functions can be chained to create custom preprocessing pipelines. ```python from cascadia.depthcharge.data import preprocessing from cascadia.depthcharge.data.spectrum_datasets import SpectrumDataset # Available preprocessing functions (from spectrum_utils) # - filter_intensity: Filter peaks by intensity # - remove_precursor_peak: Remove precursor peak region # - round: Round m/z values # - scale_intensity: Scale intensities (log, root, rank) # - set_mz_range: Filter by m/z range # Example: Custom preprocessing pipeline dataset = SpectrumDataset( ms_data_files="spectra.mzML", preprocessing_fn=[ preprocessing.set_mz_range(min_mz=140), # Remove low m/z noise preprocessing.filter_intensity(max_num_peaks=200), # Keep top 200 peaks preprocessing.scale_intensity(scaling="root"), # Square root transform preprocessing.scale_to_unit_norm, # Normalize to unit norm ] ) ``` -------------------------------- ### Train or Fine-tune Cascadia Models via CLI Source: https://context7.com/noble-lab/cascadia/llms.txt The cascadia train command is used to train models from scratch or fine-tune existing checkpoints using .asf format data. It allows for hyperparameter tuning including batch size, epochs, and learning rate, with outputs saved as model checkpoints and TensorBoard logs. ```bash cascadia train training_data.asf validation_data.asf cascadia train \ training_data.asf \ validation_data.asf \ --model pretrained_checkpoint.ckpt \ --batch_size 32 \ --width 2 \ --max_charge 4 \ --max_epochs 10 \ --learning_rate 1e-5 ``` -------------------------------- ### Manage Peptide Tokenization with PeptideTokenizer Source: https://context7.com/noble-lab/cascadia/llms.txt The PeptideTokenizer class parses and tokenizes ProForma-compliant peptide sequences. It supports loading vocabularies from MassIVE-KB or custom sequences, providing methods to convert sequences to token indices and back to strings. ```python from cascadia.depthcharge.tokenizers import PeptideTokenizer tokenizer = PeptideTokenizer.from_massivekb(replace_isoleucine_with_leucine=True, reverse=False) custom_sequences = ["PEPTIDEK", "M[Oxidation]ASSSPEC", "[Acetyl]-NTERM"] tokenizer = PeptideTokenizer.from_proforma(sequences=custom_sequences, replace_isoleucine_with_leucine=True, reverse=False) sequences = ["PEPTIDEK", "MASSSPEC"] tokens = tokenizer.tokenize(sequences, add_stop=True) peptides = tokenizer.detokenize(tokens) ``` -------------------------------- ### Cascadia De Novo Sequencing CLI Source: https://context7.com/noble-lab/cascadia/llms.txt Performs de novo peptide sequencing on mzML mass spectrometry files using a trained model checkpoint. ```APIDOC ## POST /sequence ### Description Performs de novo peptide sequencing on mzML mass spectrometry files using a trained model checkpoint. ### Method POST ### Endpoint /sequence ### Parameters #### Query Parameters - **mzml_file** (string) - Required - Path to the mzML mass spectrometry file. - **checkpoint_path** (string) - Required - Path to the trained Cascadia model checkpoint. - **outfile** (string) - Optional - Base name for the output file (default: results). - **score_threshold** (float) - Optional - Minimum score threshold for predictions (default: 0.8). - **batch_size** (integer) - Optional - Batch size for inference (default: 64). - **width** (integer) - Optional - Retention time augmentation width (default: 2). - **max_charge** (integer) - Optional - Maximum precursor charge to consider (default: 4). - **modifications** (string) - Optional - Predefined modification set (e.g., mskb) or custom modification string. ### Request Example ```bash cascadia sequence sample.mzML model_checkpoint.ckpt --outfile results --score_threshold 0.8 --batch_size 64 --width 2 --max_charge 4 --modifications mskb ``` ### Response #### Success Response (200) - **output_file** (string) - Path to the generated SSL file containing predictions. #### Response Example ```json { "output_file": "results.ssl" } ``` **Output File Format (results.ssl):** Tab-delimited file with columns: file, scan, charge, sequence, score-type, score, retention-time, start-time, end-time ``` -------------------------------- ### Augment Mass Spectra from mzML Files Source: https://context7.com/noble-lab/cascadia/llms.txt The augment_spectra function processes raw mzML files to create augmented spectra by combining MS1 and MS2 scans surrounding each precursor detection. It can be used as a full pipeline or step-by-step. ```python from cascadia.augment import augment_spectra, get_centers, extract_spectra, write_asf import os # Full augmentation pipeline (used internally by cascadia sequence) temp_path = "./augmented_spectra" os.makedirs(temp_path, exist_ok=True) asf_file, isolation_window_size, cycle_time = augment_spectra( mzml_file="experiment.mzML", temp_path=temp_path, top_n=150, # Top N peaks per scan scan_width=2, # Number of adjacent scans (width parameter) max_pep_length=30, # Maximum peptide length max_charge=4 # Maximum charge states to enumerate ) print(f"Augmented spectra file: {asf_file}") print(f"Isolation window size: {isolation_window_size}") print(f"Cycle time: {cycle_time} seconds") # Step-by-step augmentation for custom processing # Step 1: Extract precursor centers from mzML f_to_mzrt_to_pep, max_mz, window_size, cycle_time = get_centers("experiment.mzML") # Step 2: Extract spectra for each precursor time_width = 3 * cycle_time # Time window for augmentation for part in f_to_mzrt_to_pep.keys(): prec_to_spec = extract_spectra( "experiment.mzML", f_to_mzrt_to_pep, part, top_n=150, time_width=time_width, max_mz=max_mz ) # Step 3: Write augmented spectra to ASF format write_asf( outfile="augmented.asf", prec_to_spec=prec_to_spec, scan_width=2, max_pep_length=30, max_charge=4 ) ``` -------------------------------- ### AugmentedSpec2Pep Model (Python API) Source: https://context7.com/noble-lab/cascadia/llms.txt The main transformer model for peptide sequencing, combining spectrum encoding and peptide decoding. ```APIDOC ## Class: AugmentedSpec2Pep ### Description Represents the core transformer model for de novo peptide sequencing. It includes a spectrum encoder, peptide decoder, and auxiliary heads for precursor mass prediction and fragment classification. ### Methods #### `__init__` Initializes the `AugmentedSpec2Pep` model. - **d_model** (int) - Transformer hidden dimension. - **n_layers** (int) - Number of transformer layers. - **n_head** (int) - Number of attention heads. - **dim_feedforward** (int) - Feedforward network dimension. - **dropout** (float) - Dropout rate. - **rt_width** (int) - Retention time augmentation width. - **tokenizer** (PeptideTokenizer) - Instance of `PeptideTokenizer`. - **max_charge** (int) - Maximum precursor charge. - **lr** (float) - Learning rate. #### `load_from_checkpoint` Loads model weights and configuration from a checkpoint file. - **checkpoint_path** (str) - Path to the checkpoint file. - **d_model**, **n_layers**, **n_head**, **dim_feedforward**, **dropout**, **rt_width**, **tokenizer**, **max_charge** - Model configuration parameters (can override values from checkpoint). ### Usage Example (Inference) ```python import torch from cascadia.model import AugmentedSpec2Pep from cascadia.depthcharge.tokenizers import PeptideTokenizer # Initialize tokenizer tokenizer = PeptideTokenizer.from_massivekb( reverse=False, replace_isoleucine_with_leucine=True ) # Load model from checkpoint model = AugmentedSpec2Pep.load_from_checkpoint( "cascadia.ckpt", d_model=512, n_layers=9, n_head=8, dim_feedforward=1024, dropout=0, rt_width=2, tokenizer=tokenizer, max_charge=10 ) # Run inference using PyTorch Lightning trainer import pytorch_lightning as pl trainer = pl.Trainer(accelerator='gpu', devices=1) predictions = trainer.predict(model, dataloaders=data_loader) # Process predictions for pred_seqs, true_seqs, pep_confidence, aa_confidence, rts, precursors in predictions: for seq, conf in zip(pred_seqs, pep_confidence): print(f"Predicted: {seq}, Confidence: {torch.exp(conf):.4f}") ``` ### Output Predictions typically include predicted sequences, confidence scores, retention times, and precursor information. ``` -------------------------------- ### Manage Annotated Mass Spectra Datasets Source: https://context7.com/noble-lab/cascadia/llms.txt The AnnotatedSpectrumDataset class manages collections of labeled mass spectra, storing them in an efficient HDF5 index for rapid random access during training. It supports custom preprocessing functions. ```python from cascadia.depthcharge.data.spectrum_datasets import AnnotatedSpectrumDataset from cascadia.depthcharge.data.preprocessing import scale_intensity, scale_to_unit_norm from cascadia.depthcharge.tokenizers import PeptideTokenizer # Initialize tokenizer tokenizer = PeptideTokenizer.from_massivekb( reverse=False, replace_isoleucine_with_leucine=True ) # Create dataset from ASF file with preprocessing dataset = AnnotatedSpectrumDataset( tokenizer=tokenizer, ms_data_files="training_spectra.asf", index_path="train_index.hdf5", preprocessing_fn=[ scale_intensity(scaling="root"), # Square root transform scale_to_unit_norm # Normalize to unit norm ] ) # Create DataLoader for training train_loader = dataset.loader( batch_size=32, num_workers=4, pin_memory=True, shuffle=True ) # Access individual spectra with dataset: spectrum = dataset.get_spectrum(0) print(f"Precursor m/z: {spectrum.precursor_mz}") print(f"Precursor charge: {spectrum.precursor_charge}") print(f"Annotation: {spectrum.label}") print(f"Number of peaks: {len(spectrum.mz)}") # Dataset properties print(f"Total spectra: {dataset.n_spectra}") print(f"Total peaks: {dataset.n_peaks}") print(f"MS files: {dataset.ms_files}") ``` -------------------------------- ### Custom Preprocessing Function for Spectrum Data Source: https://context7.com/noble-lab/cascadia/llms.txt Defines a custom preprocessing function that applies a log transform to the intensity of spectral data. This function is intended for use with the SpectrumDataset class, potentially in conjunction with other preprocessing steps like scaling to unit norm. ```python import numpy as np from cascadia import preprocessing # Custom preprocessing function that applies log transform. def custom_preprocessing(spectrum): """Custom preprocessing that applies log transform.""" spectrum._inner._intensity = np.log1p(spectrum.intensity) return spectrum dataset_custom = SpectrumDataset( ms_data_files="spectra.mzML", preprocessing_fn=[ custom_preprocessing, preprocessing.scale_to_unit_norm, ] ) ``` -------------------------------- ### Tokenize Peptide Sequences Source: https://context7.com/noble-lab/cascadia/llms.txt Splits a peptide sequence into individual tokens (amino acids and modified residues). This is a fundamental step for processing peptide data. ```python from cascadia.depthcharge.tokenizers import PeptideTokenizer # Initialize tokenizer tokenizer = PeptideTokenizer.from_massivekb( reverse=False, replace_isoleucine_with_leucine=True ) # Split a sequence into tokens tokens_list = tokenizer.split("M[Oxidation]ASSSPEC") # Returns: ['M[Oxidation]', 'A', 'S', 'S', 'S', 'P', 'E', 'C'] ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.