Skip to main content

CandyCrunch

DOI License Tests codecov

What is CandyCrunch?

CandyCrunch is a package for predicting glycan structure from LC-MS/MS data. It contains the CandyCrunch model, along with the rest of the inference pipeline and downstream spectrum processing tools. These are further described in our manuscript Urban et al. (2024) – Predicting glycan structure from tandem mass spectrometry via deep learning published in Nature Methods.

Using CandyCrunch – Desktop app

No Python or command line needed: download CandyCrunch-<version>-Windows-Setup.exe (Windows) or CandyCrunch-<version>-macOS.dmg (macOS) from the latest release, install it (on macOS, drag CandyCrunch onto the Applications folder beside it in the disk image), and start CandyCrunch from the Start menu or Applications. The Windows installer needs no administrator rights; afterwards, Thermo .raw, mzML, mzXML, and mgf files can be opened with CandyCrunch from their right-click menu, and saved results open with a double-click. The macOS app is not notarized, so on first start macOS asks you to allow it once under System Settings > Privacy & Security > Open Anyway. Windows SmartScreen may hold back the installer of a new release at first ("Windows protected your PC"); More info > Run anyway installs it. The app looks for a new release at every start: Update in the status bar shows what's new and installs it in place with two clicks, keeping your settings, and Help > What's new lists the changes of every release.

Python users get the same app with

pip install "candycrunch[gui]"
candycrunch_gui

The desktop app runs CandyCrunch on one or several Thermo and Waters .raw, SCIEX .wiff, Bruker and Agilent .d, mzML, mzXML, mzData, mgf, .cc, or xlsx files without any code, with a progress bar that shows how far a run is and about how long it will still take. Results come as a table with SNFG drawings, and each glycan peak shows its annotated MS² spectrum (Save image… writes it at print size as PNG, SVG, or PDF, with the m/z of every labeled peak), fragment table, candidate structures, and position on a retention time vs. m/z map. Several runs are harmonized into a feature table with per-run abundances, and the Compare groups tab tests which glycans or motifs differ between groups of runs (two groups: glycowork's differential expression; three or more: ANOVA with Tukey's post-hoc tests), with a volcano plot, per-group abundances, and Excel export. Predictions can be curated (assign another candidate, enter a structure, exclude a peak), exported as CSV or Excel (optionally with SNFG drawings), and saved to reopen later without rerunning. Export > Save batch report… writes the report of --report for a batch. The CandyCrumbs tab annotates any peak list with any glycan, composition, or glycopeptide. To try the app without data of your own, File > Add example run adds a small bundled O-glycan run.

Install CandyCrunch

CandyCrunch runs on Python 3.11 or newer (on Intel Macs, Python 3.11 or 3.12, the last versions PyTorch builds for them).

PyPI:

pip install candycrunch

Using CandyCrunch – Command line interface:

If you would like to run our main inference function from the command line, you can do so using the candycrunch_predict command that comes with CandyCrunch. Its tables and the app's exports add a references column: the links glycowork's database holds for each structure, also for structures without a GlyTouCan ID.

Requires at a minimum:

--spectra_filepath, type=string(s): one or more filepaths to Thermo and Waters .raw, SCIEX .wiff, Bruker and Agilent .d, mzML, mzXML, mzData, or mgf files (also gzipped: .mzML.gz, .mzXML.gz, .mgf.gz) or .cc/.xlsx files from extract_spectra, and/or folders of .raw, .wiff, .d, mzML, mzXML, mzData, mgf, or .cc files (the .xlsx files in a folder are not used); several files are processed together via `wrap_inference_batch` 
--glycan_class, type=string(s): the glycan class measured ("N", "O", "lipid"/"free"), or several measured together in one run (e.g., `--glycan_class N O`)
--output, type=string: an output filepath ending with `.csv` or `.xlsx`

Optional arguments:

--mode, type=string: mass spectrometry mode; options are 'negative' or 'positive'; default: 'negative' 
--max_charge, type=int: maximum precursor charge to consider; default:3
--sample_prep, type=string: options are 'underivatized', 'permethylated', 'deuteropermethylated', and 'peracetylated'; default:'underivatized'
--sialic_derivatization, type=string: linkage-specific sialic acid derivatization of underivatized samples, or of samples permethylated after it; options are 'EE' (ethyl esterification), 'EEA' (ethyl esterification and amidation), 'ME' (methyl esterification), 'DMA' (dimethylamidation), 'SALSA', 'GQ' (glycoqueuing: aniline on every sialic acid, which tells no linkage; with GirardP), and 'GQ-d5' (d5-aniline on a2-6); precursor masses then tell a2-6 from a2-3/8/9 sialic acids; default:None
--reducing_end_variants, type=string(s): other reducing ends the glycans may carry: 'free' (glycans that escaped reduction or labeling, counted for their glycan), 'ethyl_glycoside' (rows of their own), 'glycosylamine' (PA glycans whose label was not reduced, counted for their glycan), and/or 'glycosylaminitol' (1-amino-1-deoxy-alditols of reduced N-glycans that were still glycosylamines when reduced, counted for their glycan); give none of them to turn this off; default: free, plus ethyl_glycoside for lipid, glycosylamine for PA, and glycosylaminitol for reduced N-glycans
--adducts, type=string(s): ions that carry the charge of the precursors in place of protons, e.g., Li+ for lithium salts in the mobile phase ([M+Li]+, [M+2Li]2+, ...); the usual adducts (Na+, K+, NH4+ in positive, acetate, formate, HCO3- in negative mode) are always considered; default:None (Na+ for permethylated glycans in positive mode)
--run_anion, type=string: anion of the mobile phase in negative mode (HCO3-, Formate, or Acetate): read before the other anion adducts, and its adduct ions count for abundances; default: all are considered, and with survey scans the anion neutral glycans show counts
--modification, type=string(s): reducing-end modification of glycans; options are 'reduced', 'reduced_D' (NaBD4), 'unreduced' (free reducing end), '2AA', '2AB', 'procainamide', 'PA', 'APTS', 'aminoxyTMT', 'GirardP', 'benzyl' (benzyl glycoside, e.g., CORA), 'glycolate' and 'lactate' (O-glycans released oxidatively, on the glycolic acid of their Ser or the lactic acid of their Thr), or 'custom'; several for glycans of several reducing ends side by side (e.g., glycolate lactate), the first being the run's own; default:'reduced'
--mass_tag, type=float: only if modification = "custom", mass of custom reducing end tag; default:None
--lc, type=string: type of liquid chromatography; options are 'PGC', 'C18', 'other', and 'infusion' (direct infusion without LC: each precursor's spectra are one row; spectra without retention times, such as an mgf of an infusion or a single spectrum, are processed so whatever lc says); default:'PGC'
--trap, type=string: type of mass analyzer that records the MS2 spectra (the survey scan analyzer is read from the file); options are 'linear', 'orbitrap', 'amazon', and 'other'; the instrument stored in the file overrides it; default:'linear'
--rt_min, type=float: whether only spectra from a minimum retention time (in minutes) onward should be considered; default:0 (runs longer than 20 min then skip their first 2 min)
--rt_max, type=float: whether only spectra up to a maximum retention time (in minutes) should be considered; default:0 (all; in runs longer than 40 min, rows in the last 10% need a peak of their own over a low background)
--rt_diff, type=float: maximum retention time difference (in minutes) to peak apex that can be grouped with that peak; default:1.0
--spectra, type=bool: whether to also output the actual spectra used for prediction, as a peak_d column; default:False
--get_missing, type=bool: whether to also organize spectra without a matching prediction but a valid composition; default:False
--filter_out, type=string(s): space-separated monosaccharide or modification types; compositions containing any of them are not considered (e.g., Pen if you know there is none); the list replaces the default, and giving none of them filters nothing; Ac is always left out of permethylated and peracetylated samples; default: HexA
--ppm_thresh, type=float: mass tolerance in ppm, used for grouping spectra, matching compositions, and filtering by ppm error (all on precursors), and for matching fragments of ion-trap MS2 (orbitrap MS2 are matched at 15 ppm, other MS2 at 0.05 Da); default:300
--pred_thresh, type=float: minimum model probability of a structure among the isomers of its composition; default:0.01
--crumbs_thresh, type=float: CandyCrumbs annotation score a prediction has to exceed to be kept (2 lower for files with orbitrap or timsTOF survey scans); default:3
--extra_thresh, type=float: model probability from which structures of another glycan class are allowed; default:0.2
--frag_num, type=int: number of top fragments to show per spectrum; default:100
--supplement, type=bool: whether to impute observed biosynthetic intermediaries from biosynthetic networks; default:True
--experimental, type=bool: whether to impute missing predictions via database searches etc.; default:True
--taxonomy_level, type=string: taxonomic level used to restrict the glycan database; default:'Class'
--taxonomy_filter, type=string: taxon at taxonomy_level used to restrict the glycan database; default:'Mammalia'
--glycan_database, type=string: your own glycan database, as .txt, .csv, .tsv, or .xlsx files of glycans (one per line or row) and/or the glycans themselves, space-separated: structures in IUPAC-condensed, WURCS, GlycoCT, or as GlyTouCan IDs, and compositions such as H5N4F1 or Hex5HexNAc4dHex1; structures the model does not know are found by their fragments; in the app, Advanced settings > Glycan database; default: none (glycowork's database)
--database_mode, type=string: 'only' (--glycan_database in place of glycowork's database: only its glycans are reported) or 'add' (beside it); default:'only'
--intra_cat_thresh, type=float: several files only, minutes the RT of a structure can differ from the mean of its group across files; default:1.0
--top_n_isomers, type=int: several files only, number of isomer groups at each composition to retain in each file; default:5
--n_jobs, type=int: number of processes: files processed in parallel, and fragment scoring and supporting peaks within a file; default:1
--plot_glycans, type=bool: whether to write the output as an .xlsx file that contains SNFG images of all top1 predictions (a `.csv` output additionally gets an `.xlsx` of the same name); default:False
--composition_format, type=string: how the output tables write compositions, 'dict' ({'Hex': 5, 'HexNAc': 4, 'dHex': 1}), 'names' (Hex5HexNAc4dHex1), or 'letters' (H5N4F1; A Neu5Ac, G Neu5Gc, S sulfate); in the app, View > Compositions as (or a right click on the Composition column's header) sets how tables, the detail pane, and exports write them; default:dict
--report, type=string: several files only: also writes a report of the batch for the people whose samples it measured, an .xlsx workbook with the glycan profile of every sample (with SNFG drawings and the diagnostic ions of each structure), glycowork's motifs per sample, sample checks, every peak with what it is, and the annotated MS2 spectrum of each glycan (`glycan_report` in `candycrunch.reporting`); default:None
--internal_standard, type=string(s): with --report, internal standards spiked into every sample, each a composition, optionally with its charge and RT in minutes (e.g., H5N3A2 or H5N3A2,-2,17.1); the first is the reference of every sample's glycan amount, and of an ion that comes with it at a constant ratio only what a sample holds clearly above that background stays in the profile; default:None
--version: prints the CandyCrunch version and exits

Basic usage

$ candycrunch_predict --spectra_filepath path_to_my_files/file.mzML --glycan_class O --output path_to_my_outputs/output_file.csv

Several files, or a folder of Thermo and Waters .raw, SCIEX .wiff, Bruker and Agilent .d, mzML, mzXML, mzData, or mgf files, are harmonized across runs with wrap_inference_batch. The output file then holds a feature table with one row per isomer group (top1 prediction, consensus m/z and RT, number of files with MS2 evidence) and its relative abundance and evidence (MS2 or MS1-only) in every file, and each file's predictions are written next to it as output_file_<file name>.csv:

$ candycrunch_predict --spectra_filepath path_to_my_files/ --glycan_class O --intra_cat_thresh 1.75 --top_n_isomers 2 --output path_to_my_outputs/output_file.csv

With --report path_to_my_outputs/report.xlsx a batch also gets a report for the people whose samples it measured: the glycan profile of every sample with SNFG drawings, glycowork's motifs per sample (its named motifs and every monosaccharide and disaccharide), sample checks, every peak with a note on what is not in the profile (glucose oligomers, peeling products, in-source fragments, glycans of another class), and the evidence of each glycan: the diagnostic ions that place its residues, linked to its MS2 spectrum annotated by CandyCrumbs. With --internal_standard H5N3A2 the standard is measured in every sample, each sample's glycan amount is given relative to it, the standard is left out of the profile, and an ion that comes with it at a constant ratio (an impurity, the reagents spiked with it, or carryover) has that background subtracted, keeping only what a sample holds clearly above it:

$ candycrunch_predict --spectra_filepath path_to_my_files/ --glycan_class O --output path_to_my_outputs/output_file.csv --report path_to_my_outputs/report.xlsx --internal_standard H5N3A2

## Using CandyCrunch &ndash; In your browser
To try CandyCrunch without installing anything, [bojarlab.github.io/CandyCrunch](https://bojarlab.github.io/CandyCrunch/) runs the CandyCrunch pipeline in a browser tab, with the same files and settings as the command line, and gives its results as CSV and Excel downloads. Your files are read where they are and never uploaded. A bundled example run lets you try it without data of your own. It needs Chrome or Edge 137 or newer. For large runs and batches, the desktop app is faster.

## Using CandyCrunch &ndash; LC-MS/MS glycan annotation
### `wrap_inference` (in `candycrunch.prediction`) <br>
Wrapper function to predict glycan structures from raw LC-MS/MS spectra using `CandyCrunch`  
  
#### Requires at a minimum:  
<pre>
- spectra_filepath, type = string: a filepath to a run (Thermo or Waters .raw, SCIEX .wiff, Bruker or Agilent .d, mzML, mzXML, mzData, or mgf, or a .zip of one), or a .cc or .xlsx file from extract_spectra, or a dataframe of spectra as load_spectra_filepath returns them <br />
- glycan_class, type = string or list: the glycan class measured ("N", "O", "lipid"/"free"), or a list of the classes measured together in one run (e.g., `["N", "O"]` for N- and O-glycans released from one sample)
</pre>
Thermo and Waters .raw, SCIEX .wiff, Bruker and Agilent .d, mzML, mzXML, mzData, and mgf files are internally processed into extracted spectra; .raw files are read directly, and timsTOF .d folders of DDA-PASEF runs (also those of early timsTOF software) as well, without any conversion or vendor software (survey frames are summed over their ion mobility scans, m/z come from the file's own TOF calibration, and the unfragmented precursor is removed from MS2 spectra; diaPASEF is not supported; timsTOF runs without ion mobility, with an analysis.tsf, are read from the centroided line spectra the instrument stores). Bruker ion trap .d folders (esquire, HCT, amaZon, with an Analysis.yep) and Bruker Q-TOF .d folders (maXis, impact, compact, micrOTOF-Q, with an analysis.baf) are read directly as well, from the centroided line spectra the instrument stores (Q-TOF m/z from the file's own TOF calibration). Waters MassLynx .raw folders of Q-TOF DDA runs (SYNAPT, Xevo G2, Q-Tof Premier; e.g., Fast DDA) are read directly too, with the file's own calibration, continuum scans centroided as MassLynx does; the lock mass function is left out and no lock mass correction is applied, and ion mobility (HDMS) and MSE runs are not supported. With accurate (orbitrap or timsTOF) survey scans, a peak the model has no structure for gets a database structure of its composition if the precursor m/z pins that composition and its fragments back the structure up. mzML files converted from timsTOF data work with or without combining ion mobility scans in msconvert. xlsx files need to be extracted already, in the format of the example file in [`examples/`](https://github.com/BojarLab/CandyCrunch/tree/main/examples). `extract_spectra(spectra_filepath)` (in `candycrunch.prediction`) writes such an xlsx from a .raw, .wiff, .d, mzML, mzXML, mzData, or mgf file, with precursor m/z already refined from MS1, so it gives the same predictions as the original file at a fraction of the size (only quantification falls back to precursor intensity, as MS1 scans are not kept). `extract_spectra(spectra_filepath, file_format = 'cc')` instead writes a compact binary .cc file that keeps everything CandyCrunch reads from the original file (MS2 and MS3 spectra exactly as loaded, the detected ion mode and analyzers, and the survey scans), so predictions and XIC quantification from it match the original (a 38 MB mzML becomes a 4.8 MB .cc, read in a tenth of a second); it is a zip of numpy arrays that `numpy.load` opens.
<details>
<summary>

#### Optional arguments:
</summary>
<pre>
model, type=PyTorch object or callable: the trained CandyCrunch model (default), or any structure predictor as a callable that takes a dataframe with one row per (pooled spectrum, candidate composition) and returns a list of (IUPAC structure, probability) tuples per row <br />
glycans, type=list: ordered list of glycans used to train CandyCrunch which can be predicted by the model <br />
bin_num, type=int: number of bins to separate the MS2 spectrum into; default:2048 <br />
frag_num, type=int: number of top fragments to show in df_out per spectrum; default:100 <br />
max_charge, type=int: maximum signed charge to consider; the sign sets the mass spectrometry mode (negative or positive); default:-3 <br />
modification, type=string or list: reducing-end modification of glycans; options are 'reduced', 'reduced_D', '2AA', '2AB', 'procainamide', 'PA', 'APTS', 'aminoxyTMT', 'GirardP', 'benzyl' (benzyl glycoside, e.g., CORA), 'glycolate' and 'lactate' (O-glycans released oxidatively, on the glycolic acid of their Ser or the lactic acid of their Thr), or 'custom' (without mass_tag for a free reducing end); a list for glycans of several reducing ends side by side (e.g., ['glycolate', 'lactate']), the first being the run's own, whose rows then name their reducing end in a column reducing_end; default:'reduced' <br />
mass_tag, type=float: only if modification = "custom", mass of custom reducing end tag; default:None <br />
lc, type=string: type of liquid chromatography; options are 'PGC', 'C18', 'other', and 'infusion' (direct infusion without LC: each precursor's spectra are one row; spectra without retention times, such as an mgf of an infusion or a single spectrum, are processed so whatever lc says); default:'PGC' <br />
trap, type=string: type of mass analyzer that records the MS2 spectra (the survey scan analyzer is read from the file); options are 'linear', 'orbitrap', 'amazon', and 'other'; the instrument stored in the file overrides it; default:'linear' <br />
rt_min, type=float: whether only spectra from a minimum retention time (in minutes) onward should be considered; default:0 (runs longer than 20 min then skip their first 2 min) <br />
rt_max, type=float: whether only spectra up to a maximum retention time (in minutes) should be considered; default:0 (all; in runs longer than 40 min, rows in the last 10% need a peak of their own over a low background) <br />
rt_diff, type=float: maximum retention time difference (in minutes) to peak apex that can be grouped with that peak; default:1.0 <br />
pred_thresh, type=float: minimum model probability of a structure among the isomers of its composition; default:0.01 <br />
temperature, type=float: the temperature factor used to calibrate logits; default:1.15 <br />
spectra, type=bool: whether to also output the actual spectra used for prediction; the result is then a tuple (dataframe, list of peak dictionaries); default:False <br />
get_missing, type=bool: whether to also organize spectra without a matching prediction but a valid composition; default:False <br />
filter_out, type=set: set of monosaccharide or modification types that is used to filter out compositions (e.g., if you know there is no Pen); Ac is always left out of permethylated and peracetylated samples; default:{'HexA'} <br />
ppm_thresh, type=float: mass tolerance in ppm, used for grouping spectra, matching compositions, and filtering by ppm error (all on precursors), and for matching fragments of ion-trap MS2 (orbitrap MS2 are matched at 15 ppm, other MS2 at 0.05 Da); default:300 <br />
crumbs_thresh, type=float: CandyCrumbs annotation score a prediction has to exceed to be kept (2 lower for files with orbitrap or timsTOF survey scans); default:3 <br />
sample_prep, type=string: options are 'underivatized', 'permethylated', 'deuteropermethylated', and 'peracetylated'; default:'underivatized' <br />
extra_thresh, type=float: model probability from which structures of another glycan class are allowed (e.g., N-glycans in O-glycan samples); default:0.2 <br />
supplement, type=bool: whether to impute observed biosynthetic intermediaries from biosynthetic networks; default:True <br />
experimental, type=bool: whether to impute missing predictions via database searches etc.; default:True <br />
mass_dic, type=dict: only if experimental = "True", dictionary of form mass : list of glycans; will be generated internally <br />
taxonomy_level, type=string: taxonomic level used to restrict the glycan database; default:'Class' <br />
taxonomy_filter, type=string: taxon at taxonomy_level used to restrict the glycan database; default:'Mammalia' <br />
df_use, type=DataFrame: only if experimental = "True", sugarbase-like database of glycans with species associations etc.; default: use glycowork-stored df_glycan <br />
glycan_database, type=string or list: your own glycan database, a .txt, .csv, .tsv, or .xlsx file or a list of glycan structures (IUPAC-condensed, WURCS, GlycoCT, GlyTouCan IDs) and compositions (H5N4F1, Hex5HexNAc4dHex1); its structures are candidates of their compositions, also those the model does not know, which are found by their fragments; default:None <br />
database_mode, type=string: 'only' (glycan_database in place of glycowork's database: only its compositions are candidates and only its glycans are reported) or 'add' (beside it); default:'only' <br />
plot_glycans, type=bool: whether to save an .xlsx file with SNFG images of all top1 predictions next to spectra_filepath, named like it plus _output; default:False <br />
sialic_derivatization, type=string or tuple: linkage-specific sialic acid derivatization of underivatized samples, or of samples permethylated after it, 'EE', 'EEA', 'ME', 'DMA', 'SALSA', 'GQ', 'GQ-d5', or a pair of glycowork SIALIC_PRODUCTS for a2-6 and a2-3/8/9 sialic acids; precursor masses then tell a2-6 from a2-3/8/9 sialic acids; default:None <br />
reducing_end_variants, type=dict: other reducing ends the glycans may carry, as name: group on the free glycan's reducing end (formula or mass; 0 for a free reducing end), e.g., {'free': 0} or {'ethyl glycoside': 'C2H4'}; default:None (free reducing ends of reduced or labeled glycans, plus ethyl glycosides for 'lipid', glycosylamines for 'PA', and glycosylaminitols, NH3-O, for reduced N-glycans) <br />
adducts, type=string or list: ions of glycowork's adduct table that carry the charge of the precursors in place of protons, e.g., 'Li+' for lithium salts in the mobile phase; their compositions come before the protonated ones; the usual adducts (Na+, K+, NH4+ or acetate, formate, HCO3-) are always considered; default:None (['Na+'] for permethylated glycans in positive mode, which [] turns off) <br />
run_anion, type=string: anion of the mobile phase in negative mode ('HCO3-', 'Formate', or 'Acetate'): read before the other anion adducts, and with survey scans its adduct ions count for abundances; default:None (all are considered, and with survey scans the anion neutral glycans show counts) <br />
n_jobs, type=int: number of processes for fragment scoring and supporting peaks (a script using n_jobs > 1 needs if __name__ == '__main__' on Windows and macOS); default:1 <br />
rt_max_default, type=float: minimum maximum retention time to normalize to; default:30.0 <br />
return_inputs, type=bool: whether to return the model's inputs instead of predictions, as a callable model receives them (e.g., to build training data from runs with known structures); default:False <br />
</pre>
</details>

#### Basic usage
```python
from candycrunch.prediction import wrap_inference
annotated_spectra_df = wrap_inference("C:/myfiles/my_spectra.mzML", 'O')
m/z top1_pred confidence predictions composition num_spectra charge RT rel_abundance top_fragments adduct ppm_error notes GlyTouCan_ID supported_by
384.184 Gal(b1-3)GalNAc 0.728 [('Gal(b1-3)GalNAc', 0.8329)] {'Hex': 1, 'HexNAc': 1} 8 -1 6.76 0.2 [204.0339, 155.9961, 178.9275, ...] 85.15 G15559XW
530.211 Fuc(a1-2)Gal(b1-3)GalNAc 0.866 [('Fuc(a1-2)Gal(b1-3)GalNAc', 0.9339)] {'Hex': 1, 'HexNAc': 1, 'dHex': 1} 13 -1 19.91 0.81 [205.0392, 204.032, 246.9845, ...] 3.81 G05545HU 1/1 residues supported: Fuc(a1-2) on Gal (324.9 C2a, 307.1 B2a)
... ... ... ... ... ... ... ... ... ... ... ... ... ... ...

confidence is the probability that top1_pred is the glycan of the peak, exactly as written: one calibrated score built from the model's probability of the structure among the isomers of its composition (also in predictions, with the other candidates), the CandyCrumbs fragment evidence, the MS2 peaks that place each residue (see supporting_ions), other peaks with the same structure, where the structure came from, the peak's abundance, and more (see candycrunch/confidence.py; the app shows each row's breakdown). On curated test sets it is calibrated to within about 0.03.

rel_abundance is the peak's share (in %) of the summed abundance of all rows. With survey scans it sums the isotope envelope of the glycan's ion over its chromatographic peak, its other charge states that follow that peak, and, in a run whose neutral glycans ionize as adducts of the mobile phase's anion (e.g., ammonium bicarbonate), the adduct ions that follow it ([M+HCO3-H]2-, [M+HCO3]-), whether or not they were fragmented. supported_by lists the MS2 peaks that place each residue of the structure (see supporting_ions).

wrap_inference_batch (in candycrunch.prediction)

Wrapper function to predict glycan structures from multiple LC-MS/MS files using CandyCrunch.
This function works similarly to wrap_inference except a list of filenames is provided and a tuple is returned: a feature table and a dictionary of output DataFrames, one for each input file, keyed by their filenames.
The feature table has one row per composition of an isomer group (by its structure, or by its composition where no file names one and MS2 shows it in some file; a glycan that files report at different charge states is one row) with its top1 prediction, consensus m/z, RT, charge, composition, GlyTouCan ID, the number of files with MS2 evidence, and a flag (in-source fragment, peeling product, glucose oligomer, or other class; compare_groups leaves flagged features out unless include_flagged), followed by its relative abundance in each file and an evidence_<file> column per file ('ms2', or 'ms1_only' if it was gap-filled from MS1; in batches of 10 or more files only isomer groups that at least two files report by MS2 are gap-filled). The first column holds the glycans; compare_groups (in candycrunch.differential) tests the table for differences between groups of files with glycowork's get_differential_expression (two groups) or get_glycanova (three or more), as the app's Compare groups tab does.
Precursors are clustered by m/z across files within the mass tolerance, and glycan predictions are assigned to groups based on the prediction most often ranked first in the group across files (ties go to the highest probability summed over the group), which rows of the group's composition without a prediction also take. Useful for retention time correction but cannot correct LC runs in cases where noise exceeds signal.

The algorithm operates under the assumption that the same structures should elute at a given RT ± intra_cat_thresh. At each composition, an isomer group is kept if it is among the top_n_isomers groups of any file, preferring groups with a prediction, then groups seen in more files, then groups more abundant in that file. For files with MS1 scans (.raw, .wiff, .d, mzML, mzXML, mzData, .cc), an isomer group without MS2 in a file is filled in from MS1 if the file shows a genuine chromatographic peak for it within intra_cat_thresh that is at least as intense as the weakest precursor that got MS2 in that file.

Requires at a minimum:

- spectra_filepath_list, type = list: list of filepaths to Thermo and Waters .raw, SCIEX .wiff, Bruker and Agilent .d, mzML, mzXML, mzData, or mgf files and/or .cc/.xlsx files 
- glycan_class, type = string or list: the glycan class measured ("N", "O", "lipid"/"free"), or a list of the classes measured together in one run
- intra_cat_thresh, type = float: minutes the RT of a structure can differ from the mean of a group.

Optional arguments:

  • top_n_isomers, type = int: number of isomer groups at each composition to retain in each file; default:5
  • n_jobs, type = int: number of files to process in parallel (in separate processes), and of processes for the supporting peaks of each file's rows; default:1
  • library_thresh, type = float: MS2 cosine at which a peak without a structure takes the structure of a peak at the same m/z and charge in another file; None turns this off; default:0.9
    All other optional arguments as in wrap_inference, except return_inputs

```python from candycrunch.prediction import wrap_inference_batch spectra_filepath_list = ["C:/myfiles/my_spectra_exp1.mzML","C:/myfiles/my_spectra_exp2.mzML", "C:/myfiles/my_spectra_exp3.mzML","C:/myfiles/my_spectra_exp4.mzML"] combined_batch, results_dict = wrap_inference_batch(spectra_filepath_list, 'O', 1.75, 2) ```

This is what results_dict would look like

{'my_spectra_exp1': pd.DataFrame(...),
 'my_spectra_exp2': pd.DataFrame(...),
 'my_spectra_exp3': pd.DataFrame(...),
 'my_spectra_exp4': pd.DataFrame(...)}

Using CandyCrumbs – MS2 fragment annotation

CandyCrumbs (in candycrunch.analysis)

Wrapper function to annotate MS2 fragments using CandyCrumbs

Requires at a minimum:

- input_string, type=string or dict: a glycan in IUPAC-condensed format, a composition, or a glycopeptide as 'PEPT*glycan*IDE' or a dict with 'peptide', 'glycans', and 'glycosites' (0-based) 
- fragment_masses, type=list: all observed masses which are to be annotated with possible fragment names
from candycrunch.analysis import CandyCrumbs
condensed_iupac_glycan = 'Gal(a1-3)Gal(b1-4)GlcNAc(b1-6)[GalNAc(b1-4)GlcNAc(b1-3)]Gal(b1-4)Glc'
ms2_fragment_masses = [425.07, 443.07, 546.19, 1216.32]
annotated_fragments_dict = CandyCrumbs(condensed_iupac_glycan, fragment_masses = ms2_fragment_masses, mass_threshold = 1)

Optional arguments:

mass_threshold, type=float: the maximum tolerated mass difference between observed masses and possible fragments; default:None (0.5 Da, or 10 ppm for glycopeptides) 
mass_threshold_ppm, type=float: a ppm bound on each match on top of mass_threshold, for accurate MS2; default:None
intensities, type=list: intensities of fragment_masses, which help choose between annotations; default:None
max_cleavages, type=int: maximum number of allowed concurrent cleavages per possible fragment; default:3
simplify, type=bool: whether to select a single fragment for each mass based on mass difference, number of cleavages, and other fragments; default:True
charge, type=int: the charge state of the precursor ion (singly-charged, doubly-charged, etc.); default:-1
mass_tag, type=float: mass of the glycan label or reducing end modification; default:None (alditol, 2 H)
iupac, type=bool: whether to also return the fragment sequence in IUPAC-condensed nomenclature; default:False
sample_prep, type=string: options are 'underivatized', 'permethylated', 'deuteropermethylated', and 'peracetylated'; default:'underivatized'
glycan_class, type=string: 'N' or 'O', used to assign candidate sites in glycopeptides; default:None
fragmentation_method, type=string: 'CID', 'HCD', 'ETD', 'ECD', 'EED', 'EDD', 'NETD', 'EThcD', 'ETciD', or 'UVPD', which sets the peptide ion types of glycopeptides and the hydrogen shifts of radical fragments; default:None
sialic_derivatization, type=string or tuple: as in wrap_inference; every sialic acid then needs its linkage; default:None
ms3_precursor, type=float: m/z of the MS2 fragment isolated for an MS3 spectrum, whose fragments are then annotated as fragments of it; default:None
disable_global_mods, type=bool: whether to disable global modifications (neutral losses, adducts); default:False
disable_X_cross_rings, type=bool: whether to strip out X-type cross-rings; default:None (chosen from the charge and derivatization)
chance_filter, type=bool: whether to leave out the fragment kinds that match m/z-shifted decoy spectra as often as real ones at a wide tolerance; default:None (chosen from the tolerance)
disable_A_cross_rings, type=bool or string: whether to strip out A-type cross-rings, or 'non_reducing' for all but the A_R ions; default:None (chosen from the charge)
prior_weight, type=float: weighting of prior-informed scoring with simplify=True; default:1.0
allow_internal_peptide_fragments, type=bool: whether to allow peptide fragments cleaved at both termini; default:False
max_global_mods, type=int: how many global modifications may co-occur on one fragment; default:None (chosen from the glycan)
metal_cations, type=bool or set: whether fragments can carry metal cations (positive mode; True: Na+ and K+), or the ones they can carry (e.g., {'+Li'} for a lithiated precursor); default:True
n_term_modification, type=string or float: a modification of a glycopeptide's N-terminal amine, by Unimod name (e.g., 'Carbamidomethyl' of an over-alkylated peptide) or mass, which every N-terminal ion and the intact peptide carry; default:None

This is what annotated_fragments_dict would look like

{425.07: None,
 443.07: {'Theoretical fragment masses': [443.14062],
  'Domon-Costello nomenclatures': [['02A_3_Alpha']],
  'Fragment charges': [-1]},
 546.19: {'Theoretical fragment masses': [546.20394],
  'Domon-Costello nomenclatures': [['Y_2_Alpha', 'Y_3_Beta']],
  'Fragment charges': [-1]},
 1216.32: {'Theoretical fragment masses': [1216.44724],
  'Domon-Costello nomenclatures': [['M_C2H4O2']],
  'Fragment charges': [-1]}}

It isn't always easy to quickly visualize the Domon-Costello nomenclature. Here is an example of how we can use GlycoDraw to visualize one of the outputs:

from candycrunch.analysis import domon_costello_to_fragIUPAC
from glycowork.motif.draw import GlycoDraw
#This will calculate where on the glycan the fragments occurred and return a valid GlycoDraw input
fragment_iupac = domon_costello_to_fragIUPAC('Gal(a1-3)Gal(b1-4)GlcNAc(b1-6)[GalNAc(b1-4)GlcNAc(b1-3)]Gal(b1-4)Glc', ['Y_3_Beta', 'Y_2_Alpha'])

#Then we can simply draw the result with GlycoDraw
GlycoDraw(fragment_iupac)

More tools (in candycrunch.analysis)

  • plot_annotated_spectrum(glycan, mzs, intensities, charge = -1): an MS2 spectrum with its CandyCrumbs annotations labeled and drawn as SNFG cartoons (also straight from the table and spectra of wrap_inference(..., spectra = True))
  • supporting_ions(glycan, peaks, candidates = other_predictions): the intense peaks that tie each residue of a predicted structure to its position, and those that tell it apart from competing candidates
  • rank_glycopeptide_structures(peptide, modification_str, peaks), rank_glycopeptide_compositions, rank_glycopeptide_sites: the glycan structures, compositions, and sites (with a glycan space, also the split of a total composition into one glycan per site, glycan_splits) of a glycoproteomics identification (e.g., 'N5(HexNAc(4)Hex(5)Fuc(1))' from a search engine) ranked by their fragment evidence
from candycrunch.prediction import load_spectra_filepath
from candycrunch.analysis import rank_glycopeptide_structures
spectra = load_spectra_filepath("C:/myfiles/my_glycopeptides.raw")
ranked = rank_glycopeptide_structures('EEQYNSTYR', 'N5(HexNAc(4)Hex(5)Fuc(1))', spectra['peak_d'][0], charge = 3, fragmentation_method = spectra['activation'][0])

Modules

prediction

  • Includes all functions used in wrap_inference.
  • Contains process_raw_stack, process_wiff_stack, process_waters_stack, process_tdf_stack, process_tsf_stack, process_baf_stack, process_yep_stack, process_masshunter_stack, process_mzML_stack, process_mzXML_stack, and process_mzdata_stack to extract spectra from Thermo and Waters .raw, SCIEX .wiff, Bruker and Agilent .d, mzML, mzXML, and mzData files

analysis

  • Includes all functions used in CandyCrumbs.
  • Contains functions to analyze and compare averaged spectra
  • Contains other functions to manipulate glycan string representations, e.g., domon_costello_to_fragIUPAC

differential

  • Contains compare_groups, differential abundance between groups of runs on a wrap_inference_batch feature table with glycowork's statistics

reporting

  • Contains glycan_report, the report of a wrap_inference_batch batch as one workbook: glycan profiles per sample with each glycan's diagnostic ions, glycowork's motifs per sample, sample checks against an internal standard, every peak, and each glycan's annotated MS2 spectrum

model

  • Includes code for model definition, dataset handling, and data augmentation; only used in the back-end

confidence

  • Contains calibrated_confidence, the probability that a reported structure is right, behind the confidence column

references

  • Contains glycan_references, what glycowork's database cites for a structure

utils

  • Contains the readers of vendor files that need no vendor library

cli and gui

  • The command line candycrunch_predict and the desktop app candycrunch_gui

inference

  • Runs the model without PyTorch, as the desktop app and the in-browser version do

examples (folder)

  • Includes the extracted spectra of an example mzML file from Kouka et al. 2022

Citation

If you use CandyCrunch or any of our datasets in your work, please cite Urban et al., Nat Methods 2024.
The data used to train CandyCrunch can be found at Zenodo, under doi:10.5281/zenodo.7940046

@article{urban2024candycrunch,
  title = {Predicting glycan structure from tandem mass spectrometry via deep learning},
  author = {Urban, James and Jin, Chunsheng and Thomsson, Kristina A. and Karlsson, Niclas G. and Ives, Callum M. and Fadda, Elisa and Bojar, Daniel},
  journal = {Nature Methods},
  volume = {21},
  pages = {1206--1215},
  year = {2024},
  doi = {10.1038/s41592-024-02314-6}
}

Privacy

The desktop app sends crash and bug reports only when you choose to send them, sends anonymous usage statistics unless you switch them off (Help > Send anonymous usage statistics), and asks GitHub whether a newer version exists. packaging/privacy.txt, which the installer shows before installing, lists exactly what each contains.

Metadata

Release files for candycrunch 1.0.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for candycrunch 1.0.2
File Size Uploaded Provenance Actions
candycrunch-1.0.2.tar.gz 61.7 MB With provenance Details for candycrunch-1.0.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for candycrunch 1.0.2
File Interpreter ABI Platform Actions
candycrunch-1.0.2-py3-none-any.whl Python 3 none any Details for candycrunch-1.0.2-py3-none-any.whl

Total release size: 123.3 MB

Release files / candycrunch-1.0.2.tar.gz

Download URL candycrunch-1.0.2.tar.gz
Size 61.7 MB
Tags Source
SHA-256 checksum
How to use checksums
ba7f067cc2e982742a3e1a1b9cbc62a3db66addf88b444cbdb15f92863d056cc
BLAKE2b-256 checksum
How to use checksums
b534754648b7201eb41541413bd195923247088f86d5332df4a56776b1fee32c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

Release files / candycrunch-1.0.2-py3-none-any.whl

Download URL candycrunch-1.0.2-py3-none-any.whl
Size 61.6 MB
Tags Python 3
SHA-256 checksum
How to use checksums
25c6ddea4f2272f58ce0a3b97496720c77484f9321205e254e21f4be7abc4f21
BLAKE2b-256 checksum
How to use checksums
df5a9a589244d49e1a22a2dd899dc0c9db8af3678c7fcb680a991bcfb9e3d824
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

Security for candycrunch 1.0.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for candycrunch-1.0.2.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page