.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/01-mass_calibration.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_01-mass_calibration.py: Mass calibration ================ This tutorial demonstrates how to estimate a contrast-to-mass calibration from a calibration movie: 1. Load a calibration movie. 2. Run detection + PSF fitting to obtain a table of event contrasts. 3. Fit peaks in the contrast histogram. 4. Fit a (linear) contrast-to-mass calibration and plot the result. .. GENERATED FROM PYTHON SOURCE LINES 13-14 .. code-block:: Python :dedent: 1 .. GENERATED FROM PYTHON SOURCE LINES 16-19 Imports ------- We first import necessary packages and modules. .. GENERATED FROM PYTHON SOURCE LINES 19-23 .. code-block:: Python import matplotlib.pyplot as plt import numpy as np .. GENERATED FROM PYTHON SOURCE LINES 24-30 Download example data --------------------- This tutorial expects a calibration movie. For now, the example downloads a small calibration file from Zenodo. You can replace this block with a direct file path once you have a local calibration movie. .. GENERATED FROM PYTHON SOURCE LINES 30-47 .. code-block:: Python from zenodozipdownloader import ZenodoZipDownloader import massphoto as mp files = ZenodoZipDownloader( doi="10.5281/zenodo.15800729", download_dir="example_data", ).download(inner_pattern="005_mfp1_500x.mp") if not files: raise RuntimeError( "Failed to download example data. Please download it manually from https://zenodo.org/record/15800729 " "or set path_calib to your own calibration movie." ) path_calib = files[0] print(f"Using calibration movie: {path_calib}") .. rst-class:: sphx-glr-script-out .. code-block:: none Using calibration movie: /home/runner/work/massphoto/massphoto/docs/source/_examples/example_data/005_mfp1_500x.mp .. GENERATED FROM PYTHON SOURCE LINES 48-54 Inputs ------ `expected_masses_kDa` should match the ladder present in the calibration movie. `contrast_slope_guess` is only used to choose sensible histogram bins and initial peak locations (kDa/contrast). .. GENERATED FROM PYTHON SOURCE LINES 54-62 .. code-block:: Python # Expected masses for the first N peaks (kDa). Adjust to match your ladder. expected_masses_kDa = np.arange(1, 8) * 86.0 # A rough contrast-to-mass slope estimate used to choose sensible binning and # initial peak locations (kDa/contrast). If unsure, keep the default. contrast_slope_guess = 3e4 .. GENERATED FROM PYTHON SOURCE LINES 63-68 Run detection + fitting ----------------------- This is the main pipeline step. The output is a DataFrame with fitted event positions and a `contrasts` column. .. GENERATED FROM PYTHON SOURCE LINES 68-77 .. code-block:: Python movie, _metadata = mp.read_movie(path_calib) fitres_calib = mp.fit(movie, movie_correct_drift=True) print(f"Detected+fit events used for calibration: n={len(fitres_calib)}") fitres_calib[["frame", "x", "y", "contrasts"]].head() .. rst-class:: sphx-glr-script-out .. code-block:: none process movie chunks: 0%| | 0/36 [00:00
frame x y contrasts
0 20 94.167944 32.324291 0.002724
1 38 123.995974 20.961641 0.010899
2 40 93.441404 21.917409 0.002605
3 42 141.535097 40.692372 0.005699
4 42 143.770046 52.605493 0.008198


.. GENERATED FROM PYTHON SOURCE LINES 78-83 Fit contrast histogram peaks ---------------------------- We model the histogram as a sum of bin-integrated Gaussians. The fitted peak centres (`mu`) are used as contrast values for the calibration fit. .. GENERATED FROM PYTHON SOURCE LINES 83-96 .. code-block:: Python bins = np.arange(-20, 660, 4) / contrast_slope_guess initial_peaks = expected_masses_kDa / contrast_slope_guess mpfit_calib = mp.distfit.fit( fitres_calib["contrasts"], bins=bins, initial_peaks=initial_peaks, include_background=False, ) print("\nFitted peak centres (contrast):") mpfit_calib.peaks[["mu", "sigma", "A"]] .. rst-class:: sphx-glr-script-out .. code-block:: none Fitted peak centres (contrast): .. raw:: html
mu sigma A
0 0.002924 0.000348 803.369926
1 0.005812 0.000433 518.591835
2 0.008627 0.000440 282.832731
3 0.011308 0.000563 169.690019
4 0.014191 0.000526 93.389237
5 0.016910 0.000717 70.160655
6 0.019726 0.000333 26.722994


.. GENERATED FROM PYTHON SOURCE LINES 97-102 Plot contrast histogram ----------------------- This is a useful sanity check: you should see distinct peaks and a reasonable fit overlay. .. GENERATED FROM PYTHON SOURCE LINES 102-111 .. code-block:: Python plt.figure(figsize=(6, 3)) plt.hist(fitres_calib["contrasts"], bins=bins, edgecolor="none") plt.plot(mpfit_calib.model_x, mpfit_calib.model_y, color="black", lw=1, label="fit") plt.xlabel("Contrast c") plt.ylabel("Counts") plt.title("Contrast histogram") plt.legend() plt.tight_layout() .. image-sg:: /auto_examples/images/sphx_glr_01-mass_calibration_001.png :alt: Contrast histogram :srcset: /auto_examples/images/sphx_glr_01-mass_calibration_001.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 112-117 Fit contrast-to-mass calibration -------------------------------- We fit a polynomial (default: linear) mapping contrast to mass (kDa). Often the lower-mass peaks are the cleanest, so we only use the first few for the fit. .. GENERATED FROM PYTHON SOURCE LINES 117-125 .. code-block:: Python n_values_for_fit = min(5, len(expected_masses_kDa), len(mpfit_calib.peaks)) calibration = mp.mass_calibration.fit( mpfit_calib.peaks["mu"][:n_values_for_fit], expected_masses_kDa[:n_values_for_fit], ) print("\nFitted calibration (contrast -> mass, kDa):", calibration) .. rst-class:: sphx-glr-script-out .. code-block:: none Fitted calibration (contrast -> mass, kDa): -4.98688693 + 30677.65217447·x .. GENERATED FROM PYTHON SOURCE LINES 126-133 Update from existing calibration (mass-domain peaks) ---------------------------------------------------- If you already have a previous calibration, measured peak positions may be in mass units already. In that case, pass those values to ``fit`` with ``input_unit='auto'`` (or ``'mass'``) and provide the previous calibration for inversion to contrast before fitting. .. GENERATED FROM PYTHON SOURCE LINES 133-147 .. code-block:: Python previous_calibration = (-5.2, 3.1e4) measured_peak_masses_kDa = mp.mass_calibration.apply( mpfit_calib.peaks["mu"][:n_values_for_fit].to_numpy(), previous_calibration, ) calibration_updated = mp.mass_calibration.fit( measured_peak_masses_kDa, expected_masses_kDa[:n_values_for_fit], input_unit="auto", reference_calibration=previous_calibration, ) print("Updated calibration from mass-domain peak positions:", calibration_updated) .. rst-class:: sphx-glr-script-out .. code-block:: none Updated calibration from mass-domain peak positions: -4.98688693 + 30677.65217447·x .. GENERATED FROM PYTHON SOURCE LINES 148-149 Optionally, update the package wide defaults (`massphoto.defaults.mass_calibration`) with the fitted calibration. .. GENERATED FROM PYTHON SOURCE LINES 149-154 .. code-block:: Python calibration = mp.mass_calibration.fit( mpfit_calib.peaks["mu"][:n_values_for_fit], expected_masses_kDa[:n_values_for_fit], update_defaults=True, ) .. GENERATED FROM PYTHON SOURCE LINES 155-160 Plot mass calibration --------------------- This plot shows the fitted peak positions (with width estimates) and the resulting calibration curve. .. GENERATED FROM PYTHON SOURCE LINES 160-181 .. code-block:: Python plt.figure(figsize=(6, 3)) plt.errorbar( x=mpfit_calib.peaks["mu"][:n_values_for_fit], y=expected_masses_kDa[:n_values_for_fit], xerr=mpfit_calib.peaks["sigma"][:n_values_for_fit], fmt="|", color="black", capsize=0, linewidth=2, label="peaks used for fit", ) x_fit = np.array([bins[0], bins[-1]], dtype=float) plt.plot(x_fit, calibration(x_fit), lw=1, label="linear fit") plt.xlabel("Contrast c") plt.ylabel("Expected mass m (kDa)") plt.title("Mass calibration") plt.legend() plt.tight_layout() .. image-sg:: /auto_examples/images/sphx_glr_01-mass_calibration_002.png :alt: Mass calibration :srcset: /auto_examples/images/sphx_glr_01-mass_calibration_002.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 182-186 Apply calibration ----------------- Apply the mass calibration to add a ``masses_kDa`` column to the fit results. .. GENERATED FROM PYTHON SOURCE LINES 186-191 .. code-block:: Python fitres_calib = mp.mass_calibration.apply(fitres_calib, calibration) fitres_calib[["frame", "x", "y", "contrasts", "masses_kDa"]].head() .. raw:: html
frame x y contrasts masses_kDa
0 20 94.167944 32.324291 0.002724 78.586279
1 38 123.995974 20.961641 0.010899 329.372803
2 40 93.441404 21.917409 0.002605 74.915870
3 42 141.535097 40.692372 0.005699 169.849288
4 42 143.770046 52.605493 0.008198 246.513887


.. GENERATED FROM PYTHON SOURCE LINES 192-197 Mass distribution after calibration ----------------------------------- Finally, inspect the calibrated mass distribution. The expected ladder masses are shown as dashed vertical lines. .. GENERATED FROM PYTHON SOURCE LINES 197-218 .. code-block:: Python plt.figure(figsize=(6, 3)) plt.hist( fitres_calib["masses_kDa"], bins=np.arange(-100, 700, 2.5), edgecolor="none", label="Single-protein events", ) for mass in expected_masses_kDa: plt.axvline( mass, color="red", ls="--", lw=1, label="Expected masses" if mass == expected_masses_kDa[0] else None, ) plt.xlabel("Mass (kDa)") plt.ylabel("Counts") plt.title("Mass distribution after calibration") plt.legend() plt.tight_layout() .. image-sg:: /auto_examples/images/sphx_glr_01-mass_calibration_003.png :alt: Mass distribution after calibration :srcset: /auto_examples/images/sphx_glr_01-mass_calibration_003.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 36.692 seconds) .. _sphx_glr_download_auto_examples_01-mass_calibration.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: 01-mass_calibration.ipynb <01-mass_calibration.ipynb>` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: 01-mass_calibration.py <01-mass_calibration.py>` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: 01-mass_calibration.zip <01-mass_calibration.zip>` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_