Tutorial: from formula to centroids¶
This notebook walks through the enviPat pipeline for two compounds, glucose and caffeine, plus the chlorinated pesticide chlorpyrifos to show a richer isotope pattern:
check_chemform(): validate formulas and compute monoisotopic masses,isopattern(): isotope fine structure,envelope(): theoretical profile at a given resolution,vdetect(): centroids of that profile,
and then the same in one call with isowrap() and a
resolution interpolated from an instrument curve with
get_resolution().
The notebook is executed on every documentation build, so all outputs below are produced by the current version of the package.
import matplotlib.pyplot as plt
import envipat as ep
import envipat.data as data
isotopes = data.isotopes
isotopes.head()
| element | isotope | mass | abundance | ratioC | |
|---|---|---|---|---|---|
| 0 | H | 1H | 1.007825 | 0.999885 | 6 |
| 1 | H | 2H | 2.014102 | 0.000115 | 6 |
| 2 | He | 3He | 3.016029 | 0.000001 | 0 |
| 3 | He | 4He | 4.002603 | 0.999999 | 0 |
| 4 | Li | 6Li | 6.015122 | 0.075900 | 0 |
1. Check the formulas¶
check_chemform normalizes each formula (every element gets an explicit
count, bracketed groups are expanded) and flags invalid ones in the warning
column. The normalized new_formula is what the later steps use as keys.
formulas = ["C6H12O6", "C8H10N4O2", "C9H11Cl3NO3PS", "C6H12Xx6"]
checked = ep.check_chemform(isotopes, formulas)
checked
| warning | new_formula | monoisotopic_mass | |
|---|---|---|---|
| 0 | False | C6H12O6 | 180.063388 |
| 1 | False | C8H10N4O2 | 194.080376 |
| 2 | False | C9H11Cl3N1O3P1S1 | 348.926284 |
| 3 | True | C6H12Xx6 | -9999.000000 |
The last formula contains an unknown element, so its warning is True.
Pipeline functions expect valid formulas, so keep only the valid rows:
checked = checked[~checked["warning"]].reset_index(drop=True)
chlorpyrifos = checked["new_formula"][2] # "C9H11Cl3N1O3P1S1"
checked
| warning | new_formula | monoisotopic_mass | |
|---|---|---|---|
| 0 | False | C6H12O6 | 180.063388 |
| 1 | False | C8H10N4O2 | 194.080376 |
| 2 | False | C9H11Cl3N1O3P1S1 | 348.926284 |
2. Isotope fine structure¶
isopattern returns a dict keyed by formula. Each value is a DataFrame with
the peak m/z, its abundance relative to the most intense peak (default
rel_to=0) and the isotope counts of every peak. Peaks below threshold
(in percent) are pruned. charge=1 computes m/z of the singly charged
ion (electron mass subtracted).
pattern = ep.isopattern(
isotopes,
checked["new_formula"],
threshold=0.1,
charge=1,
algo=2,
verbose=False,
)
pattern[chlorpyrifos].head(10)
| m/z | abundance | 31P | 12C | 13C | 1H | 2H | 35Cl | 37Cl | 14N | 15N | 16O | 18O | 17O | 32S | 34S | 33S | 36S | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 348.925735 | 100.000000 | 1 | 9 | 0 | 11 | 0 | 3 | 0 | 1 | 0 | 3 | 0 | 0 | 1 | 0 | 0 | 0 |
| 1 | 349.922770 | 0.365330 | 1 | 9 | 0 | 11 | 0 | 3 | 0 | 0 | 1 | 3 | 0 | 0 | 1 | 0 | 0 | 0 |
| 2 | 349.925123 | 0.789557 | 1 | 9 | 0 | 11 | 0 | 3 | 0 | 1 | 0 | 3 | 0 | 0 | 0 | 0 | 1 | 0 |
| 3 | 349.929090 | 9.734155 | 1 | 8 | 1 | 11 | 0 | 3 | 0 | 1 | 0 | 3 | 0 | 0 | 1 | 0 | 0 | 0 |
| 4 | 349.929952 | 0.114278 | 1 | 9 | 0 | 11 | 0 | 3 | 0 | 1 | 0 | 2 | 0 | 1 | 1 | 0 | 0 | 0 |
| 5 | 349.932012 | 0.126515 | 1 | 9 | 0 | 10 | 1 | 3 | 0 | 1 | 0 | 3 | 0 | 0 | 1 | 0 | 0 | 0 |
| 6 | 350.921531 | 4.474155 | 1 | 9 | 0 | 11 | 0 | 3 | 0 | 1 | 0 | 3 | 0 | 0 | 0 | 1 | 0 | 0 |
| 7 | 350.922785 | 95.987328 | 1 | 9 | 0 | 11 | 0 | 2 | 1 | 1 | 0 | 3 | 0 | 0 | 1 | 0 | 0 | 0 |
| 8 | 350.929981 | 0.616498 | 1 | 9 | 0 | 11 | 0 | 3 | 0 | 1 | 0 | 2 | 1 | 0 | 1 | 0 | 0 | 0 |
| 9 | 350.932445 | 0.421128 | 1 | 7 | 2 | 11 | 0 | 3 | 0 | 1 | 0 | 3 | 0 | 0 | 1 | 0 | 0 | 0 |
3. Theoretical profile¶
envelope convolutes each stick pattern with a Gaussian (or
env="CauchyLorentz") peak shape. The peak width follows from the resolving
power, resolution: FWHM = m/z / resolution. With dmz="get" the m/z step is
derived from the resolution (frac of the FWHM).
profiles = ep.envelope(pattern, dmz="get", frac=0.1, resolution=60_000, verbose=False)
profiles[chlorpyrifos].head()
| m/z | abundance | |
|---|---|---|
| 0 | 347.925735 | 0.0 |
| 1 | 347.926323 | 0.0 |
| 2 | 347.926910 | 0.0 |
| 3 | 347.927498 | 0.0 |
| 4 | 347.928085 | 0.0 |
4. Centroids¶
vdetect with detect="centroid" returns one m/z/abundance pair per resolved
profile peak. At this resolution, fine-structure peaks that lie closer together
than the peak width merge into a single centroid.
centroids = ep.vdetect(profiles, detect="centroid", verbose=False)
centroids[chlorpyrifos]
| m/z | abundance | |
|---|---|---|
| 0 | 348.925735 | 97.962344 |
| 1 | 349.928643 | 10.934385 |
| 2 | 350.922813 | 100.000000 |
| 3 | 351.925661 | 10.985837 |
| 4 | 352.919912 | 35.672620 |
| 5 | 353.922606 | 3.738394 |
| 6 | 354.917064 | 4.950609 |
| 7 | 355.919869 | 0.452264 |
| 8 | 356.912681 | 0.146851 |
def plot_compound(formula, ax):
sticks = pattern[formula]
profile = profiles[formula]
cents = centroids[formula]
ax.plot(profile["m/z"], profile["abundance"], lw=1, label="profile")
ax.vlines(sticks["m/z"], 0, sticks["abundance"], color="grey", lw=1, label="fine structure")
ax.plot(cents["m/z"], cents["abundance"], "o", ms=4, label="centroids")
ax.set(title=formula, xlabel="m/z", ylabel="relative abundance")
fig, ax = plt.subplots(figsize=(8, 4))
plot_compound(chlorpyrifos, ax)
ax.legend()
fig.tight_layout()
Zooming in on the M+1 cluster of caffeine: at a resolving power of 60 000 (FWHM about 0.003 at m/z 195) the 15N and 13C isotopologues are resolved, but the 2H isotopologue, 0.003 above the 13C one, merges into the 13C peak.
fig, ax = plt.subplots(figsize=(8, 4))
plot_compound("C8H10N4O2", ax)
ax.set_xlim(195.07, 195.095)
ax.set_ylim(0, 10)
ax.ticklabel_format(axis="x", useOffset=False)
ax.legend()
fig.tight_layout()
5. Everything in one call¶
isowrap runs steps 2-4. Instead of one fixed resolution, real instruments
have a resolving power that depends on m/z. The bundled
resolution_list holds calibration curves for common
instruments; get_resolution interpolates one at each formula’s mass.
resmass = data.resolution_list["Elite_R240000@400"]
resolution = ep.get_resolution(checked, resmass)
resolution
0 357708.024086
1 344548.705984
2 256965.514283
Name: resolution, dtype: float64
result = ep.isowrap(
isotopes,
checked,
resolution=resolution,
threshold=0.1,
charge=1,
detect="centroid",
verbose=False,
)
result["C8H10N4O2"]
| m/z | abundance | |
|---|---|---|
| 0 | 194.079827 | 100.000000 |
| 1 | 195.076862 | 1.468826 |
| 2 | 195.083182 | 8.697315 |
| 3 | 195.086104 | 0.115610 |
| 4 | 196.080217 | 0.127745 |
| 5 | 196.084073 | 0.415243 |
| 6 | 196.086537 | 0.330930 |
This curve gives a resolving power of about 350 000 at caffeine’s mass, so the 2H isotopologue at m/z 195.086 now gets its own centroid, next to the 15N and 13C ones.
Results that failed¶
Every pipeline function maps a formula whose calculation failed to the string
"error" instead of a DataFrame, as the R package does. Check before use:
for formula, peaks in result.items():
if isinstance(peaks, str):
print(f"{formula}: calculation failed")
else:
base_mz = peaks["m/z"].iloc[peaks["abundance"].argmax()]
print(f"{formula}: {len(peaks)} centroids, base peak at m/z {base_mz:.4f}")
C6H12O6: 6 centroids, base peak at m/z 180.0628
C8H10N4O2: 7 centroids, base peak at m/z 194.0798
C9H11Cl3N1O3P1S1: 23 centroids, base peak at m/z 350.9227