{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": "# Tutorial: from formula to centroids\n\nThis notebook walks through the enviPat pipeline for two compounds, glucose and\ncaffeine, plus the chlorinated pesticide chlorpyrifos to show a richer isotope pattern:\n\n1. {func}`~envipat.formula.check_chemform`: validate formulas and compute\n monoisotopic masses,\n2. {func}`~envipat.isopattern.isopattern`: isotope fine structure,\n3. {func}`~envipat.envelope.envelope`: theoretical profile at a given resolution,\n4. {func}`~envipat.vdetect.vdetect`: centroids of that profile,\n\nand then the same in one call with {func}`~envipat.isowrap.isowrap` and a\nresolution interpolated from an instrument curve with\n{func}`~envipat.resolution.get_resolution`.\n\nThe notebook is executed on every documentation build, so all outputs below are\nproduced by the current version of the package.", "id": "cell-00" }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": "import matplotlib.pyplot as plt\n\nimport envipat as ep\nimport envipat.data as data\n\nisotopes = data.isotopes\nisotopes.head()", "id": "cell-01" }, { "cell_type": "markdown", "metadata": {}, "source": "## 1. Check the formulas\n\n`check_chemform` normalizes each formula (every element gets an explicit\ncount, bracketed groups are expanded) and flags invalid ones in the `warning`\ncolumn. The normalized `new_formula` is what the later steps use as keys.", "id": "cell-02" }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": "formulas = [\"C6H12O6\", \"C8H10N4O2\", \"C9H11Cl3NO3PS\", \"C6H12Xx6\"]\nchecked = ep.check_chemform(isotopes, formulas)\nchecked", "id": "cell-03" }, { "cell_type": "markdown", "metadata": {}, "source": "The last formula contains an unknown element, so its `warning` is `True`.\nPipeline functions expect valid formulas, so keep only the valid rows:", "id": "cell-04" }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": "checked = checked[~checked[\"warning\"]].reset_index(drop=True)\nchlorpyrifos = checked[\"new_formula\"][2] # \"C9H11Cl3N1O3P1S1\"\nchecked", "id": "cell-05" }, { "cell_type": "markdown", "metadata": {}, "source": "## 2. Isotope fine structure\n\n`isopattern` returns a `dict` keyed by formula. Each value is a DataFrame with\nthe peak `m/z`, its `abundance` relative to the most intense peak (default\n`rel_to=0`) and the isotope counts of every peak. Peaks below `threshold`\n(in percent) are pruned. `charge=1` computes m/z of the singly charged\nion (electron mass subtracted).", "id": "cell-06" }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": "pattern = ep.isopattern(\n isotopes,\n checked[\"new_formula\"],\n threshold=0.1,\n charge=1,\n algo=2,\n verbose=False,\n)\npattern[chlorpyrifos].head(10)", "id": "cell-07" }, { "cell_type": "markdown", "metadata": {}, "source": "## 3. Theoretical profile\n\n`envelope` convolutes each stick pattern with a Gaussian (or\n`env=\"CauchyLorentz\"`) peak shape. The peak width follows from the resolving\npower, `resolution`: FWHM = m/z / resolution. With `dmz=\"get\"` the m/z step is\nderived from the resolution (`frac` of the FWHM).", "id": "cell-08" }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": "profiles = ep.envelope(pattern, dmz=\"get\", frac=0.1, resolution=60_000, verbose=False)\nprofiles[chlorpyrifos].head()", "id": "cell-09" }, { "cell_type": "markdown", "metadata": {}, "source": "## 4. Centroids\n\n`vdetect` with `detect=\"centroid\"` returns one m/z/abundance pair per resolved\nprofile peak. At this resolution, fine-structure peaks that lie closer together\nthan the peak width merge into a single centroid.", "id": "cell-10" }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": "centroids = ep.vdetect(profiles, detect=\"centroid\", verbose=False)\ncentroids[chlorpyrifos]", "id": "cell-11" }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": "def plot_compound(formula, ax):\n sticks = pattern[formula]\n profile = profiles[formula]\n cents = centroids[formula]\n ax.plot(profile[\"m/z\"], profile[\"abundance\"], lw=1, label=\"profile\")\n ax.vlines(sticks[\"m/z\"], 0, sticks[\"abundance\"], color=\"grey\", lw=1, label=\"fine structure\")\n ax.plot(cents[\"m/z\"], cents[\"abundance\"], \"o\", ms=4, label=\"centroids\")\n ax.set(title=formula, xlabel=\"m/z\", ylabel=\"relative abundance\")\n\n\nfig, ax = plt.subplots(figsize=(8, 4))\nplot_compound(chlorpyrifos, ax)\nax.legend()\nfig.tight_layout()", "id": "cell-12" }, { "cell_type": "markdown", "metadata": {}, "source": "Zooming in on the M+1 cluster of caffeine: at a resolving power of 60 000\n(FWHM about 0.003 at m/z 195) the 15N and 13C isotopologues are resolved, but\nthe 2H isotopologue, 0.003 above the 13C one, merges into the 13C peak.", "id": "cell-13" }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": "fig, ax = plt.subplots(figsize=(8, 4))\nplot_compound(\"C8H10N4O2\", ax)\nax.set_xlim(195.07, 195.095)\nax.set_ylim(0, 10)\nax.ticklabel_format(axis=\"x\", useOffset=False)\nax.legend()\nfig.tight_layout()", "id": "cell-14" }, { "cell_type": "markdown", "metadata": {}, "source": "## 5. Everything in one call\n\n`isowrap` runs steps 2-4. Instead of one fixed `resolution`, real instruments\nhave a resolving power that depends on m/z. The bundled\n{data}`~envipat.data.resolution_list` holds calibration curves for common\ninstruments; `get_resolution` interpolates one at each formula's mass.", "id": "cell-15" }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": "resmass = data.resolution_list[\"Elite_R240000@400\"]\nresolution = ep.get_resolution(checked, resmass)\nresolution", "id": "cell-16" }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": "result = ep.isowrap(\n isotopes,\n checked,\n resolution=resolution,\n threshold=0.1,\n charge=1,\n detect=\"centroid\",\n verbose=False,\n)\nresult[\"C8H10N4O2\"]", "id": "cell-17" }, { "cell_type": "markdown", "metadata": {}, "source": "This curve gives a resolving power of about 350 000 at caffeine's mass, so\nthe 2H isotopologue at m/z 195.086 now gets its own centroid, next to the\n15N and 13C ones.\n\n## Results that failed\n\nEvery pipeline function maps a formula whose calculation failed to the string\n`\"error\"` instead of a DataFrame, as the R package does. Check before use:", "id": "cell-18" }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": "for formula, peaks in result.items():\n if isinstance(peaks, str):\n print(f\"{formula}: calculation failed\")\n else:\n base_mz = peaks[\"m/z\"].iloc[peaks[\"abundance\"].argmax()]\n print(f\"{formula}: {len(peaks)} centroids, base peak at m/z {base_mz:.4f}\")", "id": "cell-19" } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 5 }