[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M73K2P7T20RN7S76GDNTNKYE":3,"skill-same:01M73K2P7T20RN7S76GDNTNKYE":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M73K2P7T20RN7S76GDNTNKYE","trackpy-particle-tracking",null,"Python library for single-particle tracking (SPT) in video microscopy via the Crocker-Grier algorithm. Locate particles (fluorescent spots, colloids, vesicles, cells) per frame, link into trajectories, filter short tracks, and compute MSD for diffusion analysis. 2D\u002F3D with subpixel accuracy; reads TIF stacks, AVI, image series via pims. Use for quantitative SPT and diffusion coefficient extraction from fluorescence or brightfield video.","bg-szy\u002FTOP-SKILLS","bg-szy","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F106576190?v=4","01M73A4E8KPV67SFXRY8XZGNBX","ShuZhiyong","01M73A4E96MQ294MHM74TZBVQD",6,"BSD-3-Clause","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Ftrackpy-particle-tracking\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: \"trackpy-particle-tracking\"\ndescription: \"Python library for single-particle tracking (SPT) in video microscopy via the Crocker-Grier algorithm. Locate particles (fluorescent spots, colloids, vesicles, cells) per frame, link into trajectories, filter short tracks, and compute MSD for diffusion analysis. 2D\u002F3D with subpixel accuracy; reads TIF stacks, AVI, image series via pims. Use for quantitative SPT and diffusion coefficient extraction from fluorescence or brightfield video.\"\nlicense: \"BSD-3-Clause\"\n---\n\n# trackpy\n\n## Overview\n\ntrackpy is a Python library for single-particle tracking (SPT) in video microscopy. It implements the Crocker-Grier algorithm to locate bright spots in each frame with subpixel precision, then links those positions across frames into continuous trajectories. From trajectories, trackpy computes mean squared displacement (MSD), diffusion coefficients, and motion classifications (confined, normal, directed). It handles 2D fluorescence videos, 3D confocal z-stacks, and large image sequences via memory-efficient streaming through the pims image reader library.\n\n## When to Use\n\n- You have a fluorescence microscopy video of labeled particles (quantum dots, fluorescent beads, vesicles, receptors) and need to extract individual trajectories and diffusion coefficients.\n- You want to measure particle mobility: compute MSD curves and distinguish Brownian diffusion, directed motion, or confined motion from single-particle tracks.\n- You are analyzing colloid dynamics, lipid membrane diffusion, intracellular cargo transport, or virus-cell interactions where you need per-particle trajectory data.\n- You need 3D tracking from confocal z-stack time series to capture out-of-plane motion of particles or organelles.\n- You want to apply drift correction to remove stage drift before computing intrinsic particle motion statistics.\n- You need ensemble MSD averaged across hundreds of tracks to extract population-level diffusion behavior with statistical power.\n- Use `TrackMate` (Fiji\u002FImageJ plugin) instead when you need a graphical interface, manual curation of tracks, or integration with biological object segmenters (Cellpose, StarDist).\n- Use `napari` with `napari-trackpy` instead when you want interactive visualization and manual editing of trajectories alongside image data.\n\n## Prerequisites\n\n- **Python packages**: `trackpy`, `pims`, `pandas`, `numpy`, `matplotlib`, `scipy`\n- **Data requirements**: Grayscale or single-channel image sequence (TIF stack, AVI, or directory of PNG\u002FTIF frames); particles should appear as bright Gaussian spots on a darker background (or use `invert=True` for dark spots on bright background)\n- **Environment**: Works in Jupyter notebooks and scripts; `pims` handles most microscopy formats; for ND2 or CZI files install `pims-nd2` or `aicsimageio`\n\n```bash\npip install trackpy pims pandas numpy matplotlib scipy\n# For reading multi-channel or proprietary formats:\npip install pims[bioformats]   # Bioformats via JPype\npip install aicsimageio        # ND2, CZI, LIF via AICSImageIO\n```\n\n## Quick Start\n\n```python\nimport trackpy as tp\nimport pims\n\n# Load a TIF image stack (T frames × Y × X)\nframes = pims.open(\"particles.tif\")   # shape: (T, Y, X)\n\n# Locate particles in all frames\nf = tp.batch(frames, diameter=11, minmass=500)\nprint(f\"Found {len(f)} particle detections across {f['frame'].nunique()} frames\")\n\n# Link into trajectories\nt = tp.link(f, search_range=5, memory=3)\n\n# Remove short-lived tracks (fewer than 10 frames)\nt = tp.filter_stubs(t, threshold=10)\nprint(f\"Retained {t['particle'].nunique()} trajectories\")\n\n# Compute ensemble MSD\nimsd = tp.imsd(t, mpp=0.16, fps=10)   # mpp: microns per pixel, fps: frames per second\nprint(imsd.head())\n```\n\n## Core API\n\n### Module 1: tp.locate() — Single-Frame Particle Detection\n\n`tp.locate()` finds bright circular features in one image frame using a bandpass filter followed by local maximum detection. It returns a DataFrame with subpixel x\u002Fy positions, integrated mass, signal, and eccentricity for each detected particle.\n\n```python\nimport trackpy as tp\nimport pims\nimport matplotlib.pyplot as plt\n\nframes = pims.open(\"particles.tif\")\nframe0 = frames[0]   # single 2D array\n\n# Locate particles: diameter must be odd integer, roughly matching spot size in pixels\nf0 = tp.locate(frame0, diameter=11, minmass=300, maxsize=None, separation=None)\nprint(f\"Detected {len(f0)} particles in frame 0\")\nprint(f0[['x', 'y', 'mass', 'size', 'ecc']].head())\n# x, y: subpixel centroid; mass: integrated brightness; size: Gaussian width; ecc: eccentricity (0=circular)\n```\n\n```python\n# Diagnostic plot: annotate detected particles on the raw frame\nfig, ax = plt.subplots(figsize=(8, 8))\ntp.annotate(f0, frame0, ax=ax, imshow_style={\"cmap\": \"gray\"})\nax.set_title(f\"Frame 0: {len(f0)} particles detected\")\nplt.tight_layout()\nplt.savefig(\"locate_diagnostic.png\", dpi=150)\nprint(\"Saved locate_diagnostic.png\")\n```\n\n### Module 2: tp.batch() — Multi-Frame Detection\n\n`tp.batch()` applies `tp.locate()` to every frame in an image sequence and concatenates results into a single DataFrame with a `frame` column. It accepts any pims-compatible image reader or a list of 2D arrays.\n\n```python\nimport trackpy as tp\nimport pims\n\nframes = pims.open(\"particles.tif\")\n\n# Locate particles across all frames (same parameters as tp.locate)\nf = tp.batch(frames, diameter=11, minmass=300, processes=1)\n# processes=1 uses serial processing; set processes=\"auto\" for multicore (requires joblib)\nprint(f\"Total detections: {len(f)}\")\nprint(f\"Frames with data: {f['frame'].nunique()} \u002F {len(frames)}\")\nprint(f\"Mean particles per frame: {len(f)\u002Ff['frame'].nunique():.1f}\")\nprint(f.groupby('frame').size().describe())\n```\n\n```python\n# Mass histogram: use to choose minmass cutoff\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(figsize=(6, 4))\nf['mass'].hist(bins=40, ax=ax)\nax.axvline(300, color='red', linestyle='--', label='minmass=300')\nax.set_xlabel(\"Integrated mass\")\nax.set_ylabel(\"Count\")\nax.set_title(\"Mass distribution of detections\")\nax.legend()\nplt.tight_layout()\nplt.savefig(\"mass_histogram.png\", dpi=150)\nprint(\"Saved mass_histogram.png — use to refine minmass cutoff\")\n```\n\n### Module 3: tp.link() — Trajectory Linking\n\n`tp.link()` connects particle detections across frames into trajectories by solving a bipartite assignment problem (Hungarian algorithm). It adds a `particle` column (integer trajectory ID) to the positions DataFrame. `search_range` (pixels) is the maximum displacement between frames; `memory` allows a particle to disappear for up to N frames before being dropped.\n\n```python\nimport trackpy as tp\nimport pims\n\nframes = pims.open(\"particles.tif\")\nf = tp.batch(frames, diameter=11, minmass=300)\n\n# Link: search_range in pixels; memory handles brief disappearances (blinking, out-of-focus)\nt = tp.link(f, search_range=5, memory=3)\nprint(f\"Number of unique trajectories: {t['particle'].nunique()}\")\nprint(f\"Trajectory length distribution:\")\nprint(t.groupby('particle').size().describe())\n```\n\n```python\n# Visualize all trajectories overlaid on the first frame\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(figsize=(8, 8))\ntp.plot_traj(t, superimpose=frames[0], ax=ax)\nax.set_title(f\"{t['particle'].nunique()} trajectories\")\nplt.tight_layout()\nplt.savefig(\"trajectories.png\", dpi=150)\nprint(\"Saved trajectories.png\")\n```\n\n### Module 4: tp.filter_stubs() — Short-Track Removal\n\n`tp.filter_stubs()` removes trajectories shorter than a given number of frames. Short tracks arise from noise detections, particles entering\u002Fleaving the field of view, or linking errors. Removing them improves MSD reliability because short tracks contribute high-variance MSD estimates at long lag times.\n\n```python\nimport trackpy as tp\nimport pims\n\nframes = pims.open(\"particles.tif\")\nf = tp.batch(frames, diameter=11, minmass=300)\nt = tp.link(f, search_range=5, memory=3)\n\nbefore = t['particle'].nunique()\nt_filt = tp.filter_stubs(t, threshold=10)   # keep only tracks with ≥10 frames\nafter = t_filt['particle'].nunique()\nprint(f\"Tracks before filtering: {before}\")\nprint(f\"Tracks after filtering (≥10 frames): {after}\")\nprint(f\"Removed {before - after} short tracks ({100*(before-after)\u002Fbefore:.1f}%)\")\n```\n\n### Module 5: MSD Analysis — tp.imsd() and tp.emsd()\n\n`tp.imsd()` computes per-particle mean squared displacement as a function of lag time, returning a DataFrame (lag time as index, particle ID as columns). `tp.emsd()` computes the ensemble-averaged MSD across all particles. Both require the physical scale (`mpp`, microns per pixel) and frame rate (`fps`).\n\n```python\nimport trackpy as tp\nimport pims\nimport matplotlib.pyplot as plt\n\nframes = pims.open(\"particles.tif\")\nf = tp.batch(frames, diameter=11, minmass=300)\nt = tp.link(f, search_range=5, memory=3)\nt = tp.filter_stubs(t, threshold=10)\n\nmpp = 0.16    # microns per pixel (from microscope calibration)\nfps = 10.0    # frames per second\n\n# Individual MSD curves (one column per particle)\nimsd = tp.imsd(t, mpp=mpp, fps=fps, max_lagtime=100)\nprint(f\"IMSD shape: {imsd.shape}\")  # (lag times) × (particles)\n\n# Ensemble MSD\nemsd = tp.emsd(t, mpp=mpp, fps=fps, max_lagtime=100)\nprint(f\"EMSD at lag 1 s: {emsd.iloc[0]:.4f} µm²\")\n```\n\n```python\n# Plot ensemble MSD and fit diffusion coefficient\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import linregress\n\nmpp = 0.16\nfps = 10.0\n\n# Fit MSD = 4*D*t (2D Brownian) over first 10 lag times\nlag_s = emsd.index.values[:10]   # lag times in seconds\nmsd_vals = emsd.values[:10]\nslope, intercept, r, p, se = linregress(lag_s, msd_vals)\nD = slope \u002F 4   # diffusion coefficient in µm²\u002Fs\nprint(f\"Diffusion coefficient D = {D:.4f} µm²\u002Fs  (R²={r**2:.3f})\")\n\nfig, ax = plt.subplots(figsize=(6, 5))\nax.plot(emsd.index, emsd.values, 'o-', label='Ensemble MSD')\nax.plot(lag_s, slope * lag_s + intercept, 'r--', label=f'Fit: D={D:.4f} µm²\u002Fs')\nax.set_xlabel(\"Lag time (s)\")\nax.set_ylabel(\"MSD (µm²)\")\nax.set_title(\"Ensemble Mean Squared Displacement\")\nax.legend()\nplt.tight_layout()\nplt.savefig(\"emsd.png\", dpi=150)\nprint(\"Saved emsd.png\")\n```\n\n### Module 6: Motion Analysis — Characterize and Drift Correction\n\n`tp.motion.characterize()` computes per-trajectory statistics (mean velocity, net displacement, straightness). `tp.subtract_drift()` removes bulk stage drift from trajectories before MSD analysis.\n\n```python\nimport trackpy as tp\nimport pims\n\nframes = pims.open(\"particles.tif\")\nf = tp.batch(frames, diameter=11, minmass=300)\nt = tp.link(f, search_range=5, memory=3)\nt = tp.filter_stubs(t, threshold=10)\n\n# Estimate and subtract drift (bulk movement of the sample\u002Fstage)\ndrift = tp.compute_drift(t)\nprint(\"Drift (first 5 frames):\")\nprint(drift.head())\n\nt_corrected = tp.subtract_drift(t.copy(), drift)\nprint(f\"Drift subtracted from {t_corrected['particle'].nunique()} trajectories\")\n```\n\n```python\nimport trackpy as tp\n\n# Characterize individual trajectories (requires tp.motion module)\nfrom trackpy import motion\n\n# Per-particle summary statistics\nchar = motion.characterize(t, mpp=0.16, fps=10.0)\nprint(char.columns.tolist())\n# Columns: 'alpha' (anomalous exponent), 'D_app' (apparent diffusion), 'r^2' (fit quality)\nprint(char[['alpha', 'D_app']].describe())\n# alpha ~ 1.0: Brownian; alpha \u003C 1: confined\u002Fsubdiffusion; alpha > 1: directed\u002Fsuperdiffusion\n```\n\n## Common Workflows\n\n### Workflow 1: Full 2D Tracking Pipeline with MSD and Diffusion Coefficient\n\n**Goal**: Load a fluorescence video, locate and link particles across all frames, filter short tracks, compute MSD, and extract diffusion coefficients.\n\n```python\nimport trackpy as tp\nimport pims\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import linregress\n\n# ── 1. Load image sequence ──────────────────────────────────────────────────\nframes = pims.open(\"fluorescence_video.tif\")   # (T, Y, X) grayscale TIF stack\nprint(f\"Loaded {len(frames)} frames, frame shape: {frames.frame_shape}\")\n\n# ── 2. Tune detection on a single frame ─────────────────────────────────────\nf0 = tp.locate(frames[0], diameter=11, minmass=400)\nprint(f\"Frame 0: {len(f0)} particles detected\")\n# Adjust diameter (odd integer ≥ spot size) and minmass until count looks right\n\n# ── 3. Batch detect across all frames ───────────────────────────────────────\nf = tp.batch(frames, diameter=11, minmass=400, processes=1)\nprint(f\"Total detections: {len(f)} across {f['frame'].nunique()} frames\")\n\n# ── 4. Link into trajectories ────────────────────────────────────────────────\nt = tp.link(f, search_range=6, memory=3)\nprint(f\"Unique trajectories before filtering: {t['particle'].nunique()}\")\n\n# ── 5. Remove short trajectories ─────────────────────────────────────────────\nt = tp.filter_stubs(t, threshold=15)\nprint(f\"Trajectories after filtering (≥15 frames): {t['particle'].nunique()}\")\n\n# ── 6. Subtract stage drift ───────────────────────────────────────────────────\ndrift = tp.compute_drift(t)\nt = tp.subtract_drift(t.copy(), drift)\n\n# ── 7. Compute MSD ────────────────────────────────────────────────────────────\nmpp = 0.16   # µm\u002Fpixel — from microscope calibration\nfps = 10.0   # frames per second\n\nemsd = tp.emsd(t, mpp=mpp, fps=fps, max_lagtime=50)\nimsd = tp.imsd(t, mpp=mpp, fps=fps, max_lagtime=50)\n\n# ── 8. Fit diffusion coefficient from linear regime (first 10 points) ─────────\nn_fit = 10\nlag_s = emsd.index.values[:n_fit]\nmsd_v = emsd.values[:n_fit]\nslope, intercept, r, _, _ = linregress(lag_s, msd_v)\nD = slope \u002F 4   # MSD = 4Dt for 2D Brownian\nprint(f\"Diffusion coefficient D = {D:.4f} µm²\u002Fs  (R²={r**2:.3f})\")\n\n# ── 9. Plot ────────────────────────────────────────────────────────────────────\nfig, axes = plt.subplots(1, 2, figsize=(12, 5))\n\n# Individual + ensemble MSD\naxes[0].plot(imsd.index, imsd.values, alpha=0.2, color='steelblue', linewidth=0.8)\naxes[0].plot(emsd.index, emsd.values, 'k-', linewidth=2, label='Ensemble MSD')\naxes[0].plot(lag_s, slope * lag_s + intercept, 'r--', label=f'D={D:.4f} µm²\u002Fs')\naxes[0].set_xlabel(\"Lag time (s)\")\naxes[0].set_ylabel(\"MSD (µm²)\")\naxes[0].set_title(\"MSD: individual (blue) + ensemble (black)\")\naxes[0].legend()\n\n# Trajectory overlay\ntp.plot_traj(t, superimpose=frames[0], ax=axes[1])\naxes[1].set_title(f\"{t['particle'].nunique()} trajectories\")\n\nplt.tight_layout()\nplt.savefig(\"tracking_results.png\", dpi=150, bbox_inches=\"tight\")\nprint(\"Saved tracking_results.png\")\n\n# ── 10. Export trajectories ───────────────────────────────────────────────────\nt.to_csv(\"trajectories.csv\", index=False)\nemsd.to_csv(\"ensemble_msd.csv\")\nprint(\"Exported trajectories.csv and ensemble_msd.csv\")\n```\n\n### Workflow 2: 3D Particle Tracking from Confocal Z-Stacks\n\n**Goal**: Track particles in 3D from a time-series of confocal z-stacks (T × Z × Y × X), link in 3D, and compute 3D MSD.\n\n```python\nimport trackpy as tp\nimport pims\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# ── 1. Load 4D image stack (T × Z × Y × X) ─────────────────────────────────\n# pims opens multi-page TIF; reshape into (T, Z, Y, X) as needed\nraw = pims.open(\"confocal_3d_timeseries.tif\")\n# Assume each \"frame\" in pims is one Z-slice; reshape to (T, Z, Y, X)\nT, n_z = 50, 20   # adjust to match acquisition\nframes_4d = np.array(raw).reshape(T, n_z, raw.frame_shape[0], raw.frame_shape[1])\nprint(f\"4D stack shape: {frames_4d.shape}\")  # (T, Z, Y, X)\n\n# ── 2. Detect in 3D (tp.locate works on 3D arrays) ─────────────────────────\n# For 3D, pass a single 3D volume; diameter can be (z_diam, y_diam, x_diam)\nf0_3d = tp.locate(frames_4d[0], diameter=(7, 11, 11), minmass=2000)\nprint(f\"3D detections in t=0: {len(f0_3d)}\")\nprint(f0_3d[['x', 'y', 'z', 'mass']].head())\n\n# ── 3. Batch detect across all time points ──────────────────────────────────\ndetections = []\nfor t_idx in range(T):\n    frame_3d = frames_4d[t_idx]    # Z × Y × X\n    detected = tp.locate(frame_3d, diameter=(7, 11, 11), minmass=2000)\n    detected['frame'] = t_idx\n    detections.append(detected)\n\nimport pandas as pd\nf3d = pd.concat(detections, ignore_index=True)\nprint(f\"Total 3D detections: {len(f3d)}\")\n\n# ── 4. Link in 3D ────────────────────────────────────────────────────────────\n# search_range in pixels; use a 3-tuple (z, y, x) for anisotropic voxels\nt3d = tp.link(f3d, search_range=(3, 6, 6), memory=2)\nt3d = tp.filter_stubs(t3d, threshold=10)\nprint(f\"3D trajectories: {t3d['particle'].nunique()}\")\n\n# ── 5. Compute 3D MSD ────────────────────────────────────────────────────────\nmpp_xy = 0.16   # µm\u002Fpixel in x, y\nmpp_z = 0.30    # µm\u002Fpixel in z (z-step size)\nfps = 1.0       # z-stack volume rate\n\n# Scale z coordinates to µm\nt3d_um = t3d.copy()\nt3d_um['x'] *= mpp_xy\nt3d_um['y'] *= mpp_xy\nt3d_um['z'] *= mpp_z\n\nemsd_3d = tp.emsd(t3d_um, mpp=1.0, fps=fps, max_lagtime=20)  # mpp=1 since already in µm\nprint(f\"3D ensemble MSD (lag=1 s): {emsd_3d.iloc[0]:.4f} µm²\")\n\n# ── 6. Fit 3D diffusion coefficient (MSD = 6Dt for 3D) ─────────────────────\nfrom scipy.stats import linregress\nlag_s = emsd_3d.index.values[:8]\nslope, _, r, _, _ = linregress(lag_s, emsd_3d.values[:8])\nD_3d = slope \u002F 6\nprint(f\"3D Diffusion coefficient D = {D_3d:.4f} µm²\u002Fs  (R²={r**2:.3f})\")\n\nt3d.to_csv(\"trajectories_3d.csv\", index=False)\nprint(\"Saved trajectories_3d.csv\")\n```\n\n## Key Parameters\n\n| Parameter | Module | Default | Range \u002F Options | Effect |\n|-----------|--------|---------|-----------------|--------|\n| `diameter` | `locate`, `batch` | required | odd integer ≥ 3 (or tuple for 3D) | Approximate particle diameter in pixels; must be odd. Too small: split detections. Too large: merged detections |\n| `minmass` | `locate`, `batch` | `100` | `0` to `∞` | Minimum integrated brightness; primary filter against noise. Start at 0, plot mass histogram, set to separate noise peak |\n| `search_range` | `link` | required | `1`–`50` pixels | Max displacement between frames. Set to ~1.5× max expected per-frame movement |\n| `memory` | `link` | `0` | `0`–`10` frames | Frames a particle may be absent before track is broken; useful for blinking fluorophores |\n| `threshold` | `filter_stubs` | `1` | integer ≥ 1 | Minimum track length in frames; short tracks have unreliable MSD |\n| `max_lagtime` | `imsd`, `emsd` | `100` | integer | Maximum lag time in frames for MSD calculation; use ~10–20% of total frames for reliability |\n| `mpp` | `imsd`, `emsd` | `1` | float > 0 | Microns per pixel; converts pixel units to physical units (µm) |\n| `fps` | `imsd`, `emsd` | `1` | float > 0 | Frames per second; converts frame lag to seconds |\n| `separation` | `locate`, `batch` | `diameter+1` | integer | Minimum center-to-center distance between features; prevents double-counting dense particles |\n| `invert` | `locate`, `batch` | `False` | `True`, `False` | Set `True` for dark particles on bright background (transmitted light imaging) |\n\n## Best Practices\n\n1. **Always tune `diameter` and `minmass` on a single frame first**: Run `tp.locate()` on one representative frame and use `tp.annotate()` to visually check detections before committing to `tp.batch()`. Over-detection wastes time; under-detection misses particles.\n\n   ```python\n   f0 = tp.locate(frames[0], diameter=11, minmass=200)\n   tp.annotate(f0, frames[0])   # visual check in Jupyter\n   ```\n\n2. **Set `search_range` conservatively**: Too large a search range causes spurious links between unrelated particles in dense samples. Estimate typical per-frame displacement from `tp.locate()` output scatter before linking.\n\n3. **Subtract drift before computing MSD**: Stage drift inflates MSD, causing overestimation of D. Always call `tp.compute_drift()` + `tp.subtract_drift()` before `tp.emsd()`.\n\n4. **Use only the linear regime for diffusion coefficient fitting**: MSD curves become noisy at long lag times (few track pairs contribute). Fit only the first 10–20% of available lag times. Use log-log slope to detect non-Brownian behavior before fitting.\n\n5. **Do not mix `mpp` units between locate and MSD steps**: `tp.locate()` returns positions in pixels. `mpp` is applied only in `tp.imsd()`\u002F`tp.emsd()`. Avoid rescaling positions manually before linking, as this breaks the pixel-unit search_range.\n\n6. **For 3D tracking with anisotropic voxels**: Pass `diameter` and `search_range` as tuples matching `(z, y, x)` axis order. The z-step is usually 2-5× coarser than xy pixel size; set the z component of `diameter` and `search_range` accordingly.\n\n## Common Recipes\n\n### Recipe: Drift Correction and Corrected MSD Comparison\n\nWhen to use: Compare raw vs drift-corrected MSD to assess stage drift contribution.\n\n```python\nimport trackpy as tp\nimport pims\nimport matplotlib.pyplot as plt\n\nframes = pims.open(\"particles.tif\")\nf = tp.batch(frames, diameter=11, minmass=400, processes=1)\nt = tp.link(f, search_range=6, memory=3)\nt = tp.filter_stubs(t, threshold=15)\n\nmpp, fps = 0.16, 10.0\n\n# MSD without drift correction\nemsd_raw = tp.emsd(t, mpp=mpp, fps=fps, max_lagtime=50)\n\n# Subtract drift\ndrift = tp.compute_drift(t)\nt_corr = tp.subtract_drift(t.copy(), drift)\nemsd_corr = tp.emsd(t_corr, mpp=mpp, fps=fps, max_lagtime=50)\n\nfig, ax = plt.subplots(figsize=(6, 5))\nax.loglog(emsd_raw.index, emsd_raw.values, 'r--', label='Raw MSD')\nax.loglog(emsd_corr.index, emsd_corr.values, 'b-', label='Drift-corrected MSD')\nax.set_xlabel(\"Lag time (s)\")\nax.set_ylabel(\"MSD (µm²)\")\nax.set_title(\"Effect of drift correction on MSD\")\nax.legend()\nplt.tight_layout()\nplt.savefig(\"drift_correction_comparison.png\", dpi=150)\nprint(\"Saved drift_correction_comparison.png\")\n```\n\n### Recipe: Classify Particles by Diffusion Regime\n\nWhen to use: Separate particle population into confined, normal (Brownian), and directed motion based on log-log MSD slope (anomalous exponent alpha).\n\n```python\nimport trackpy as tp\nimport pims\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import linregress\n\nframes = pims.open(\"particles.tif\")\nf = tp.batch(frames, diameter=11, minmass=400, processes=1)\nt = tp.link(f, search_range=6, memory=3)\nt = tp.filter_stubs(t, threshold=20)\n\ndrift = tp.compute_drift(t)\nt = tp.subtract_drift(t.copy(), drift)\n\nmpp, fps = 0.16, 10.0\nimsd = tp.imsd(t, mpp=mpp, fps=fps, max_lagtime=30)\n\n# Fit log-log slope (anomalous exponent alpha) for each particle\nresults = []\nfor pid in imsd.columns:\n    curve = imsd[pid].dropna()\n    if len(curve) \u003C 5:\n        continue\n    log_lag = np.log(curve.index.values)\n    log_msd = np.log(curve.values)\n    slope, intercept, r, _, _ = linregress(log_lag[:10], log_msd[:10])\n    D_app = np.exp(intercept) \u002F 4   # apparent D from intercept\n    results.append({'particle': pid, 'alpha': slope, 'D_app': D_app, 'r2': r**2})\n\ndf_char = pd.DataFrame(results)\n\n# Classify by alpha\ndf_char['regime'] = pd.cut(\n    df_char['alpha'],\n    bins=[-np.inf, 0.7, 1.3, np.inf],\n    labels=['confined', 'brownian', 'directed']\n)\nprint(df_char['regime'].value_counts())\nprint(f\"\\nMean D by regime:\\n{df_char.groupby('regime')['D_app'].mean()}\")\n\ndf_char.to_csv(\"particle_classification.csv\", index=False)\nprint(\"Saved particle_classification.csv\")\n```\n\n### Recipe: Filter by Eccentricity to Remove Aggregates\n\nWhen to use: Exclude non-circular detections (doublets, aggregates, debris) that pass the mass threshold but are elongated.\n\n```python\nimport trackpy as tp\nimport pims\n\nframes = pims.open(\"particles.tif\")\nf = tp.batch(frames, diameter=11, minmass=400, processes=1)\n\n# Eccentricity: 0 = perfect circle, 1 = line\n# Remove elongated features (likely aggregates or debris)\nf_round = f[f['ecc'] \u003C 0.3]\nprint(f\"Before ecc filter: {len(f)} detections\")\nprint(f\"After ecc filter (ecc\u003C0.3): {len(f_round)} detections\")\nprint(f\"Removed: {len(f)-len(f_round)} elongated features\")\n\nt = tp.link(f_round, search_range=6, memory=3)\nt = tp.filter_stubs(t, threshold=10)\nprint(f\"Trajectories after eccentricity filtering: {t['particle'].nunique()}\")\n```\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| Too many spurious detections | `minmass` too low or `diameter` mismatched to spot size | Plot mass histogram; raise `minmass` to the valley between noise and signal peaks. Verify `diameter` matches actual spot width in pixels |\n| Few or zero detections | `minmass` too high, or particles are dim \u002F out of focus | Lower `minmass`; check image contrast; apply background subtraction before locate |\n| Very short trajectories (all stubs filtered out) | `search_range` too small for particle velocity, or `memory=0` with blinking | Increase `search_range` to 1.5–2× max per-frame displacement; set `memory=2` or `3` for blinking dyes |\n| MSD curves are noisy or non-monotonic at long lag times | Too few tracks or fitting too many lag points | Use only first 10–20% of lag times for fitting; ensure at least 50+ trajectories for ensemble MSD |\n| Drift correction makes MSD worse | Too few immobile reference particles; drift estimated from mobile particles | Include fiducial beads or immobile particles; use `tp.compute_drift()` only on particles known to be immobile |\n| `MemoryError` during `tp.batch()` | All frames loaded into RAM at once | Use pims lazy reader (default); set `processes=1`; process frames in chunks using a loop over `tp.locate()` |\n| 3D `locate` returns 2D positions only | Passed a 2D frame instead of a 3D volume | Confirm input array has 3 dimensions `(Z, Y, X)`; check `frames_4d[t_idx].ndim == 3` |\n| Linked trajectories fragment into many short segments | Particles moving faster than `search_range` between frames | Increase `search_range`; increase `memory`; consider sub-sampling frames if frame rate is very high |\n\n## References\n\n- [trackpy documentation](http:\u002F\u002Fsoft-matter.github.io\u002Ftrackpy\u002F) — official API reference, tutorials, and notebooks\n- [trackpy GitHub repository](https:\u002F\u002Fgithub.com\u002Fsoft-matter\u002Ftrackpy) — source code, issue tracker, example notebooks\n- [Crocker, J.C. & Grier, D.G. (1996). Methods of Digital Video Microscopy for Colloidal Studies. *J. Colloid Interface Sci.* 179, 298–310](https:\u002F\u002Fdoi.org\u002F10.1006\u002Fjcis.1996.0217) — original algorithm paper\n- [pims documentation](http:\u002F\u002Fsoft-matter.github.io\u002Fpims\u002F) — image sequence reader library that integrates with trackpy\n- [trackpy walkthrough notebook](https:\u002F\u002Fgithub.com\u002Fsoft-matter\u002Ftrackpy\u002Fblob\u002Fmaster\u002Fdoc\u002Ftutorial\u002Fwalkthrough.ipynb) — step-by-step tutorial for 2D tracking\n","# trackpy\n\n## Overview\n\ntrackpy is a Python library for single-particle tracking (SPT) in video microscopy. It implements the Crocker-Grier algorithm to locate bright spots in each frame with subpixel precision, then links those positions across frames into continuous trajectories. From trajectories, trackpy computes mean squared displacement (MSD), diffusion coefficients, and motion classifications (confined, normal, directed). It handles 2D fluorescence videos, 3D confocal z-stacks, and large image sequences via memory-efficient streaming through the pims image reader library.\n\n## When to Use\n\n- You have a fluorescence microscopy video of labeled particles (quantum dots, fluorescent beads, vesicles, receptors) and need to extract individual trajectories and diffusion coefficients.\n- You want to measure particle mobility: compute MSD curves and distinguish Brownian diffusion, directed motion, or confined motion from single-particle tracks.\n- You are analyzing colloid dynamics, lipid membrane diffusion, intracellular cargo transport, or virus-cell interactions where you need per-particle trajectory data.\n- You need 3D tracking from confocal z-stack time series to capture out-of-plane motion of particles or organelles.\n- You want to apply drift correction to remove stage drift before computing intrinsic particle motion statistics.\n- You need ensemble MSD averaged across hundreds of tracks to extract population-level diffusion behavior with statistical power.\n- Use `TrackMate` (Fiji\u002FImageJ plugin) instead when you need a graphical interface, manual curation of tracks, or integration with biological object segmenters (Cellpose, StarDist).\n- Use `napari` with `napari-trackpy` instead when you want interactive visualization and manual editing of trajectories alongside image data.\n\n## Prerequisites\n\n- **Python packages**: `trackpy`, `pims`, `pandas`, `numpy`, `matplotlib`, `scipy`\n- **Data requirements**: Grayscale or single-channel image sequence (TIF stack, AVI, or directory of PNG\u002FTIF frames); particles should appear as bright Gaussian spots on a darker background (or use `invert=True` for dark spots on bright background)\n- **Environment**: Works in Jupyter notebooks and scripts; `pims` handles most microscopy formats; for ND2 or CZI files install `pims-nd2` or `aicsimageio`\n\n```bash\npip install trackpy pims pandas numpy matplotlib scipy\n# For reading multi-channel or proprietary formats:\npip install pims[bioformats]   # Bioformats via JPype\npip install aicsimageio        # ND2, CZI, LIF via AICSImageIO\n```\n\n## Quick Start\n\n```python\nimport trackpy as tp\nimport pims\n\n# Load a TIF image stack (T frames × Y × X)\nframes = pims.open(\"particles.tif\")   # shape: (T, Y, X)\n\n# Locate particles in all frames\nf = tp.batch(frames, diameter=11, minmass=500)\nprint(f\"Found {len(f)} particle detections across {f['frame'].nunique()} frames\")\n\n# Link into trajectories\nt = tp.link(f, search_range=5, memory=3)\n\n# Remove short-lived tracks (fewer than 10 frames)\nt = tp.filter_stubs(t, threshold=10)\nprint(f\"Retained {t['particle'].nunique()} trajectories\")\n\n# Compute ensemble MSD\nimsd = tp.imsd(t, mpp=0.16, fps=10)   # mpp: microns per pixel, fps: frames per second\nprint(imsd.head())\n```\n\n## Core API\n\n### Module 1: tp.locate() — Single-Frame Particle Detection\n\n`tp.locate()` finds bright circular features in one image frame using a bandpass filter followed by local maximum detection. It returns a DataFrame with subpixel x\u002Fy positions, integrated mass, signal, and eccentricity for each detected particle.\n\n```python\nimport trackpy as tp\nimport pims\nimport matplotlib.pyplot as plt\n\nframes = pims.open(\"particles.tif\")\nframe0 = frames[0]   # single 2D array\n\n# Locate particles: diameter must be odd integer, roughly matching spot size in pixels\nf0 = tp.locate(frame0, diameter=11, minmass=300, maxsize=None, separation=None)\nprint(f\"Detected {len(f0)} particles in frame 0\")\nprint(f0[['x', 'y', 'mass', 'size', 'ecc']].head())\n# x, y: subpixel centroid; mass: integrated brightness; size: Gaussian width; ecc: eccentricity (0=circular)\n```\n\n```python\n# Diagnostic plot: annotate detected particles on the raw frame\nfig, ax = plt.subplots(figsize=(8, 8))\ntp.annotate(f0, frame0, ax=ax, imshow_style={\"cmap\": \"gray\"})\nax.set_title(f\"Frame 0: {len(f0)} particles detected\")\nplt.tight_layout()\nplt.savefig(\"locate_diagnostic.png\", dpi=150)\nprint(\"Saved locate_diagnostic.png\")\n```\n\n### Module 2: tp.batch() — Multi-Frame Detection\n\n`tp.batch()` applies `tp.locate()` to every frame in an image sequence and concatenates results into a single DataFrame with a `frame` column. It accepts any pims-compatible image reader or a list of 2D arrays.\n\n```python\nimport trackpy as tp\nimport pims\n\nframes = pims.open(\"particles.tif\")\n\n# Locate particles across all frames (same parameters as tp.locate)\nf = tp.batch(frames, diameter=11, minmass=300, processes=1)\n# processes=1 uses serial processing; set processes=\"auto\" for multicore (requires joblib)\nprint(f\"Total detections: {len(f)}\")\nprint(f\"Frames with data: {f['frame'].nunique()} \u002F {len(frames)}\")\nprint(f\"Mean particles per frame: {len(f)\u002Ff['frame'].nunique():.1f}\")\nprint(f.groupby('frame').size().describe())\n```\n\n```python\n# Mass histogram: use to choose minmass cutoff\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(figsize=(6, 4))\nf['mass'].hist(bins=40, ax=ax)\nax.axvline(300, color='red', linestyle='--', label='minmass=300')\nax.set_xlabel(\"Integrated mass\")\nax.set_ylabel(\"Count\")\nax.set_title(\"Mass distribution of detections\")\nax.legend()\nplt.tight_layout()\nplt.savefig(\"mass_histogram.png\", dpi=150)\nprint(\"Saved mass_histogram.png — use to refine minmass cutoff\")\n```\n\n### Module 3: tp.link() — Trajectory Linking\n\n`tp.link()` connects particle detections across frames into trajectories by solving a bipartite assignment problem (Hungarian algorithm). It adds a `particle` column (integer trajectory ID) to the positions DataFrame. `search_range` (pixels) is the maximum displacement between frames; `memory` allows a particle to disappear for up to N frames before being dropped.\n\n```python\nimport trackpy as tp\nimport pims\n\nframes = pims.open(\"particles.tif\")\nf = tp.batch(frames, diameter=11, minmass=300)\n\n# Link: search_range in pixels; memory handles brief disappearances (blinking, out-of-focus)\nt = tp.link(f, search_range=5, memory=3)\nprint(f\"Number of unique trajectories: {t['particle'].nunique()}\")\nprint(f\"Trajectory length distribution:\")\nprint(t.groupby('particle').size().describe())\n```\n\n```python\n# Visualize all trajectories overlaid on the first frame\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(figsize=(8, 8))\ntp.plot_traj(t, superimpose=frames[0], ax=ax)\nax.set_title(f\"{t['particle'].nunique()} trajectories\")\nplt.tight_layout()\nplt.savefig(\"trajectories.png\", dpi=150)\nprint(\"Saved trajectories.png\")\n```\n\n### Module 4: tp.filter_stubs() — Short-Track Removal\n\n`tp.filter_stubs()` removes trajectories shorter than a given number of frames. Short tracks arise from noise detections, particles entering\u002Fleaving the field of view, or linking errors. Removing them improves MSD reliability because short tracks contribute high-variance MSD estimates at long lag times.\n\n```python\nimport trackpy as tp\nimport pims\n\nframes = pims.open(\"particles.tif\")\nf = tp.batch(frames, diameter=11, minmass=300)\nt = tp.link(f, search_range=5, memory=3)\n\nbefore = t['particle'].nunique()\nt_filt = tp.filter_stubs(t, threshold=10)   # keep only tracks with ≥10 frames\nafter = t_filt['particle'].nunique()\nprint(f\"Tracks before filtering: {before}\")\nprint(f\"Tracks after filtering (≥10 frames): {after}\")\nprint(f\"Removed {before - after} short tracks ({100*(before-after)\u002Fbefore:.1f}%)\")\n```\n\n### Module 5: MSD Analysis — tp.imsd() and tp.emsd()\n\n`tp.imsd()` computes per-particle mean squared displacement as a function of lag time, returning a DataFrame (lag time as index, particle ID as columns). `tp.emsd()` computes the ensemble-averaged MSD across all particles. Both require the physical scale (`mpp`, microns per pixel) and frame rate (`fps`).\n\n```python\nimport trackpy as tp\nimport pims\nimport matplotlib.pyplot as plt\n\nframes = pims.open(\"particles.tif\")\nf = tp.batch(frames, diameter=11, minmass=300)\nt = tp.link(f, search_range=5, memory=3)\nt = tp.filter_stubs(t, threshold=10)\n\nmpp = 0.16    # microns per pixel (from microscope calibration)\nfps = 10.0    # frames per second\n\n# Individual MSD curves (one column per particle)\nimsd = tp.imsd(t, mpp=mpp, fps=fps, max_lagtime=100)\nprint(f\"IMSD shape: {imsd.shape}\")  # (lag times) × (particles)\n\n# Ensemble MSD\nemsd = tp.emsd(t, mpp=mpp, fps=fps, max_lagtime=100)\nprint(f\"EMSD at lag 1 s: {emsd.iloc[0]:.4f} µm²\")\n```\n\n```python\n# Plot ensemble MSD and fit diffusion coefficient\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import linregress\n\nmpp = 0.16\nfps = 10.0\n\n# Fit MSD = 4*D*t (2D Brownian) over first 10 lag times\nlag_s = emsd.index.values[:10]   # lag times in seconds\nmsd_vals = emsd.values[:10]\nslope, intercept, r, p, se = linregress(lag_s, msd_vals)\nD = slope \u002F 4   # diffusion coefficient in µm²\u002Fs\nprint(f\"Diffusion coefficient D = {D:.4f} µm²\u002Fs  (R²={r**2:.3f})\")\n\nfig, ax = plt.subplots(figsize=(6, 5))\nax.plot(emsd.index, emsd.values, 'o-', label='Ensemble MSD')\nax.plot(lag_s, slope * lag_s + intercept, 'r--', label=f'Fit: D={D:.4f} µm²\u002Fs')\nax.set_xlabel(\"Lag time (s)\")\nax.set_ylabel(\"MSD (µm²)\")\nax.set_title(\"Ensemble Mean Squared Displacement\")\nax.legend()\nplt.tight_layout()\nplt.savefig(\"emsd.png\", dpi=150)\nprint(\"Saved emsd.png\")\n```\n\n### Module 6: Motion Analysis — Characterize and Drift Correction\n\n`tp.motion.characterize()` computes per-trajectory statistics (mean velocity, net displacement, straightness). `tp.subtract_drift()` removes bulk stage drift from trajectories before MSD analysis.\n\n```python\nimport trackpy as tp\nimport pims\n\nframes = pims.open(\"particles.tif\")\nf = tp.batch(frames, diameter=11, minmass=300)\nt = tp.link(f, search_range=5, memory=3)\nt = tp.filter_stubs(t, threshold=10)\n\n# Estimate and subtract drift (bulk movement of the sample\u002Fstage)\ndrift = tp.compute_drift(t)\nprint(\"Drift (first 5 frames):\")\nprint(drift.head())\n\nt_corrected = tp.subtract_drift(t.copy(), drift)\nprint(f\"Drift subtracted from {t_corrected['particle'].nunique()} trajectories\")\n```\n\n```python\nimport trackpy as tp\n\n# Characterize individual trajectories (requires tp.motion module)\nfrom trackpy import motion\n\n# Per-particle summary statistics\nchar = motion.characterize(t, mpp=0.16, fps=10.0)\nprint(char.columns.tolist())\n# Columns: 'alpha' (anomalous exponent), 'D_app' (apparent diffusion), 'r^2' (fit quality)\nprint(char[['alpha', 'D_app']].describe())\n# alpha ~ 1.0: Brownian; alpha \u003C 1: confined\u002Fsubdiffusion; alpha > 1: directed\u002Fsuperdiffusion\n```\n\n## Common Workflows\n\n### Workflow 1: Full 2D Tracking Pipeline with MSD and Diffusion Coefficient\n\n**Goal**: Load a fluorescence video, locate and link particles across all frames, filter short tracks, compute MSD, and extract diffusion coefficients.\n\n```python\nimport trackpy as tp\nimport pims\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import linregress\n\n# ── 1. Load image sequence ──────────────────────────────────────────────────\nframes = pims.open(\"fluorescence_video.tif\")   # (T, Y, X) grayscale TIF stack\nprint(f\"Loaded {len(frames)} frames, frame shape: {frames.frame_shape}\")\n\n# ── 2. Tune detection on a single frame ─────────────────────────────────────\nf0 = tp.locate(frames[0], diameter=11, minmass=400)\nprint(f\"Frame 0: {len(f0)} particles detected\")\n# Adjust diameter (odd integer ≥ spot size) and minmass until count looks right\n\n# ── 3. Batch detect across all frames ───────────────────────────────────────\nf = tp.batch(frames, diameter=11, minmass=400, processes=1)\nprint(f\"Total detections: {len(f)} across {f['frame'].nunique()} frames\")\n\n# ── 4. Link into trajectories ────────────────────────────────────────────────\nt = tp.link(f, search_range=6, memory=3)\nprint(f\"Unique trajectories before filtering: {t['particle'].nunique()}\")\n\n# ── 5. Remove short trajectories ─────────────────────────────────────────────\nt = tp.filter_stubs(t, threshold=15)\nprint(f\"Trajectories after filtering (≥15 frames): {t['particle'].nunique()}\")\n\n# ── 6. Subtract stage drift ───────────────────────────────────────────────────\ndrift = tp.compute_drift(t)\nt = tp.subtract_drift(t.copy(), drift)\n\n# ── 7. Compute MSD ────────────────────────────────────────────────────────────\nmpp = 0.16   # µm\u002Fpixel — from microscope calibration\nfps = 10.0   # frames per second\n\nemsd = tp.emsd(t, mpp=mpp, fps=fps, max_lagtime=50)\nimsd = tp.imsd(t, mpp=mpp, fps=fps, max_lagtime=50)\n\n# ── 8. Fit diffusion coefficient from linear regime (first 10 points) ─────────\nn_fit = 10\nlag_s = emsd.index.values[:n_fit]\nmsd_v = emsd.values[:n_fit]\nslope, intercept, r, _, _ = linregress(lag_s, msd_v)\nD = slope \u002F 4   # MSD = 4Dt for 2D Brownian\nprint(f\"Diffusion coefficient D = {D:.4f} µm²\u002Fs  (R²={r**2:.3f})\")\n\n# ── 9. Plot ────────────────────────────────────────────────────────────────────\nfig, axes = plt.subplots(1, 2, figsize=(12, 5))\n\n# Individual + ensemble MSD\naxes[0].plot(imsd.index, imsd.values, alpha=0.2, color='steelblue', linewidth=0.8)\naxes[0].plot(emsd.index, emsd.values, 'k-', linewidth=2, label='Ensemble MSD')\naxes[0].plot(lag_s, slope * lag_s + intercept, 'r--', label=f'D={D:.4f} µm²\u002Fs')\naxes[0].set_xlabel(\"Lag time (s)\")\naxes[0].set_ylabel(\"MSD (µm²)\")\naxes[0].set_title(\"MSD: individual (blue) + ensemble (black)\")\naxes[0].legend()\n\n# Trajectory overlay\ntp.plot_traj(t, superimpose=frames[0], ax=axes[1])\naxes[1].set_title(f\"{t['particle'].nunique()} trajectories\")\n\nplt.tight_layout()\nplt.savefig(\"tracking_results.png\", dpi=150, bbox_inches=\"tight\")\nprint(\"Saved tracking_results.png\")\n\n# ── 10. Export trajectories ───────────────────────────────────────────────────\nt.to_csv(\"trajectories.csv\", index=False)\nemsd.to_csv(\"ensemble_msd.csv\")\nprint(\"Exported trajectories.csv and ensemble_msd.csv\")\n```\n\n### Workflow 2: 3D Particle Tracking from Confocal Z-Stacks\n\n**Goal**: Track particles in 3D from a time-series of confocal z-stacks (T × Z × Y × X), link in 3D, and compute 3D MSD.\n\n```python\nimport trackpy as tp\nimport pims\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# ── 1. Load 4D image stack (T × Z × Y × X) ─────────────────────────────────\n# pims opens multi-page TIF; reshape into (T, Z, Y, X) as needed\nraw = pims.open(\"confocal_3d_timeseries.tif\")\n# Assume each \"frame\" in pims is one Z-slice; reshape to (T, Z, Y, X)\nT, n_z = 50, 20   # adjust to match acquisition\nframes_4d = np.array(raw).reshape(T, n_z, raw.frame_shape[0], raw.frame_shape[1])\nprint(f\"4D stack shape: {frames_4d.shape}\")  # (T, Z, Y, X)\n\n# ── 2. Detect in 3D (tp.locate works on 3D arrays) ─────────────────────────\n# For 3D, pass a single 3D volume; diameter can be (z_diam, y_diam, x_diam)\nf0_3d = tp.locate(frames_4d[0], diameter=(7, 11, 11), minmass=2000)\nprint(f\"3D detections in t=0: {len(f0_3d)}\")\nprint(f0_3d[['x', 'y', 'z', 'mass']].head())\n\n# ── 3. Batch detect across all time points ──────────────────────────────────\ndetections = []\nfor t_idx in range(T):\n    frame_3d = frames_4d[t_idx]    # Z × Y × X\n    detected = tp.locate(frame_3d, diameter=(7, 11, 11), minmass=2000)\n    detected['frame'] = t_idx\n    detections.append(detected)\n\nimport pandas as pd\nf3d = pd.concat(detections, ignore_index=True)\nprint(f\"Total 3D detections: {len(f3d)}\")\n\n# ── 4. Link in 3D ────────────────────────────────────────────────────────────\n# search_range in pixels; use a 3-tuple (z, y, x) for anisotropic voxels\nt3d = tp.link(f3d, search_range=(3, 6, 6), memory=2)\nt3d = tp.filter_stubs(t3d, threshold=10)\nprint(f\"3D trajectories: {t3d['particle'].nunique()}\")\n\n# ── 5. Compute 3D MSD ────────────────────────────────────────────────────────\nmpp_xy = 0.16   # µm\u002Fpixel in x, y\nmpp_z = 0.30    # µm\u002Fpixel in z (z-step size)\nfps = 1.0       # z-stack volume rate\n\n# Scale z coordinates to µm\nt3d_um = t3d.copy()\nt3d_um['x'] *= mpp_xy\nt3d_um['y'] *= mpp_xy\nt3d_um['z'] *= mpp_z\n\nemsd_3d = tp.emsd(t3d_um, mpp=1.0, fps=fps, max_lagtime=20)  # mpp=1 since already in µm\nprint(f\"3D ensemble MSD (lag=1 s): {emsd_3d.iloc[0]:.4f} µm²\")\n\n# ── 6. Fit 3D diffusion coefficient (MSD = 6Dt for 3D) ─────────────────────\nfrom scipy.stats import linregress\nlag_s = emsd_3d.index.values[:8]\nslope, _, r, _, _ = linregress(lag_s, emsd_3d.values[:8])\nD_3d = slope \u002F 6\nprint(f\"3D Diffusion coefficient D = {D_3d:.4f} µm²\u002Fs  (R²={r**2:.3f})\")\n\nt3d.to_csv(\"trajectories_3d.csv\", index=False)\nprint(\"Saved trajectories_3d.csv\")\n```\n\n## Key Parameters\n\n| Parameter | Module | Default | Range \u002F Options | Effect |\n|-----------|--------|---------|-----------------|--------|\n| `diameter` | `locate`, `batch` | required | odd integer ≥ 3 (or tuple for 3D) | Approximate particle diameter in pixels; must be odd. Too small: split detections. Too large: merged detections |\n| `minmass` | `locate`, `batch` | `100` | `0` to `∞` | Minimum integrated brightness; primary filter against noise. Start at 0, plot mass histogram, set to separate noise peak |\n| `search_range` | `link` | required | `1`–`50` pixels | Max displacement between frames. Set to ~1.5× max expected per-frame movement |\n| `memory` | `link` | `0` | `0`–`10` frames | Frames a particle may be absent before track is broken; useful for blinking fluorophores |\n| `threshold` | `filter_stubs` | `1` | integer ≥ 1 | Minimum track length in frames; short tracks have unreliable MSD |\n| `max_lagtime` | `imsd`, `emsd` | `100` | integer | Maximum lag time in frames for MSD calculation; use ~10–20% of total frames for reliability |\n| `mpp` | `imsd`, `emsd` | `1` | float > 0 | Microns per pixel; converts pixel units to physical units (µm) |\n| `fps` | `imsd`, `emsd` | `1` | float > 0 | Frames per second; converts frame lag to seconds |\n| `separation` | `locate`, `batch` | `diameter+1` | integer | Minimum center-to-center distance between features; prevents double-counting dense particles |\n| `invert` | `locate`, `batch` | `False` | `True`, `False` | Set `True` for dark particles on bright background (transmitted light imaging) |\n\n## Best Practices\n\n1. **Always tune `diameter` and `minmass` on a single frame first**: Run `tp.locate()` on one representative frame and use `tp.annotate()` to visually check detections before committing to `tp.batch()`. Over-detection wastes time; under-detection misses particles.\n\n   ```python\n   f0 = tp.locate(frames[0], diameter=11, minmass=200)\n   tp.annotate(f0, frames[0])   # visual check in Jupyter\n   ```\n\n2. **Set `search_range` conservatively**: Too large a search range causes spurious links between unrelated particles in dense samples. Estimate typical per-frame displacement from `tp.locate()` output scatter before linking.\n\n3. **Subtract drift before computing MSD**: Stage drift inflates MSD, causing overestimation of D. Always call `tp.compute_drift()` + `tp.subtract_drift()` before `tp.emsd()`.\n\n4. **Use only the linear regime for diffusion coefficient fitting**: MSD curves become noisy at long lag times (few track pairs contribute). Fit only the first 10–20% of available lag times. Use log-log slope to detect non-Brownian behavior before fitting.\n\n5. **Do not mix `mpp` units between locate and MSD steps**: `tp.locate()` returns positions in pixels. `mpp` is applied only in `tp.imsd()`\u002F`tp.emsd()`. Avoid rescaling positions manually before linking, as this breaks the pixel-unit search_range.\n\n6. **For 3D tracking with anisotropic voxels**: Pass `diameter` and `search_range` as tuples matching `(z, y, x)` axis order. The z-step is usually 2-5× coarser than xy pixel size; set the z component of `diameter` and `search_range` accordingly.\n\n## Common Recipes\n\n### Recipe: Drift Correction and Corrected MSD Comparison\n\nWhen to use: Compare raw vs drift-corrected MSD to assess stage drift contribution.\n\n```python\nimport trackpy as tp\nimport pims\nimport matplotlib.pyplot as plt\n\nframes = pims.open(\"particles.tif\")\nf = tp.batch(frames, diameter=11, minmass=400, processes=1)\nt = tp.link(f, search_range=6, memory=3)\nt = tp.filter_stubs(t, threshold=15)\n\nmpp, fps = 0.16, 10.0\n\n# MSD without drift correction\nemsd_raw = tp.emsd(t, mpp=mpp, fps=fps, max_lagtime=50)\n\n# Subtract drift\ndrift = tp.compute_drift(t)\nt_corr = tp.subtract_drift(t.copy(), drift)\nemsd_corr = tp.emsd(t_corr, mpp=mpp, fps=fps, max_lagtime=50)\n\nfig, ax = plt.subplots(figsize=(6, 5))\nax.loglog(emsd_raw.index, emsd_raw.values, 'r--', label='Raw MSD')\nax.loglog(emsd_corr.index, emsd_corr.values, 'b-', label='Drift-corrected MSD')\nax.set_xlabel(\"Lag time (s)\")\nax.set_ylabel(\"MSD (µm²)\")\nax.set_title(\"Effect of drift correction on MSD\")\nax.legend()\nplt.tight_layout()\nplt.savefig(\"drift_correction_comparison.png\", dpi=150)\nprint(\"Saved drift_correction_comparison.png\")\n```\n\n### Recipe: Classify Particles by Diffusion Regime\n\nWhen to use: Separate particle population into confined, normal (Brownian), and directed motion based on log-log MSD slope (anomalous exponent alpha).\n\n```python\nimport trackpy as tp\nimport pims\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import linregress\n\nframes = pims.open(\"particles.tif\")\nf = tp.batch(frames, diameter=11, minmass=400, processes=1)\nt = tp.link(f, search_range=6, memory=3)\nt = tp.filter_stubs(t, threshold=20)\n\ndrift = tp.compute_drift(t)\nt = tp.subtract_drift(t.copy(), drift)\n\nmpp, fps = 0.16, 10.0\nimsd = tp.imsd(t, mpp=mpp, fps=fps, max_lagtime=30)\n\n# Fit log-log slope (anomalous exponent alpha) for each particle\nresults = []\nfor pid in imsd.columns:\n    curve = imsd[pid].dropna()\n    if len(curve) \u003C 5:\n        continue\n    log_lag = np.log(curve.index.values)\n    log_msd = np.log(curve.values)\n    slope, intercept, r, _, _ = linregress(log_lag[:10], log_msd[:10])\n    D_app = np.exp(intercept) \u002F 4   # apparent D from intercept\n    results.append({'particle': pid, 'alpha': slope, 'D_app': D_app, 'r2': r**2})\n\ndf_char = pd.DataFrame(results)\n\n# Classify by alpha\ndf_char['regime'] = pd.cut(\n    df_char['alpha'],\n    bins=[-np.inf, 0.7, 1.3, np.inf],\n    labels=['confined', 'brownian', 'directed']\n)\nprint(df_char['regime'].value_counts())\nprint(f\"\\nMean D by regime:\\n{df_char.groupby('regime')['D_app'].mean()}\")\n\ndf_char.to_csv(\"particle_classification.csv\", index=False)\nprint(\"Saved particle_classification.csv\")\n```\n\n### Recipe: Filter by Eccentricity to Remove Aggregates\n\nWhen to use: Exclude non-circular detections (doublets, aggregates, debris) that pass the mass threshold but are elongated.\n\n```python\nimport trackpy as tp\nimport pims\n\nframes = pims.open(\"particles.tif\")\nf = tp.batch(frames, diameter=11, minmass=400, processes=1)\n\n# Eccentricity: 0 = perfect circle, 1 = line\n# Remove elongated features (likely aggregates or debris)\nf_round = f[f['ecc'] \u003C 0.3]\nprint(f\"Before ecc filter: {len(f)} detections\")\nprint(f\"After ecc filter (ecc\u003C0.3): {len(f_round)} detections\")\nprint(f\"Removed: {len(f)-len(f_round)} elongated features\")\n\nt = tp.link(f_round, search_range=6, memory=3)\nt = tp.filter_stubs(t, threshold=10)\nprint(f\"Trajectories after eccentricity filtering: {t['particle'].nunique()}\")\n```\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| Too many spurious detections | `minmass` too low or `diameter` mismatched to spot size | Plot mass histogram; raise `minmass` to the valley between noise and signal peaks. Verify `diameter` matches actual spot width in pixels |\n| Few or zero detections | `minmass` too high, or particles are dim \u002F out of focus | Lower `minmass`; check image contrast; apply background subtraction before locate |\n| Very short trajectories (all stubs filtered out) | `search_range` too small for particle velocity, or `memory=0` with blinking | Increase `search_range` to 1.5–2× max per-frame displacement; set `memory=2` or `3` for blinking dyes |\n| MSD curves are noisy or non-monotonic at long lag times | Too few tracks or fitting too many lag points | Use only first 10–20% of lag times for fitting; ensure at least 50+ trajectories for ensemble MSD |\n| Drift correction makes MSD worse | Too few immobile reference particles; drift estimated from mobile particles | Include fiducial beads or immobile particles; use `tp.compute_drift()` only on particles known to be immobile |\n| `MemoryError` during `tp.batch()` | All frames loaded into RAM at once | Use pims lazy reader (default); set `processes=1`; process frames in chunks using a loop over `tp.locate()` |\n| 3D `locate` returns 2D positions only | Passed a 2D frame instead of a 3D volume | Confirm input array has 3 dimensions `(Z, Y, X)`; check `frames_4d[t_idx].ndim == 3` |\n| Linked trajectories fragment into many short segments | Particles moving faster than `search_range` between frames | Increase `search_range`; increase `memory`; consider sub-sampling frames if frame rate is very high |\n\n## References\n\n- [trackpy documentation](http:\u002F\u002Fsoft-matter.github.io\u002Ftrackpy\u002F) — official API reference, tutorials, and notebooks\n- [trackpy GitHub repository](https:\u002F\u002Fgithub.com\u002Fsoft-matter\u002Ftrackpy) — source code, issue tracker, example notebooks\n- [Crocker, J.C. & Grier, D.G. (1996). Methods of Digital Video Microscopy for Colloidal Studies. *J. Colloid Interface Sci.* 179, 298–310](https:\u002F\u002Fdoi.org\u002F10.1006\u002Fjcis.1996.0217) — original algorithm paper\n- [pims documentation](http:\u002F\u002Fsoft-matter.github.io\u002Fpims\u002F) — image sequence reader library that integrates with trackpy\n- [trackpy walkthrough notebook](https:\u002F\u002Fgithub.com\u002Fsoft-matter\u002Ftrackpy\u002Fblob\u002Fmaster\u002Fdoc\u002Ftutorial\u002Fwalkthrough.ipynb) — step-by-step tutorial for 2D tracking\n",{"name":5,"license":15,"description":7},"master","63f17866001c5ca854bf2fa0b678ce277133de5b","skills\u002Fawesome-skills\u002Ftrackpy-particle-tracking",0,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS","https:\u002F\u002Fbg-szy.github.io\u002FTOP-SKILLS\u002F","https:\u002F\u002Fgithub.com\u002Fbg-szy","https:\u002F\u002Fwww.ecust.edu.cn\u002F","a student of East China University of Science and Technology","2026-11-15 03:38:02",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add bg-szy\u002FTOP-SKILLS --skill trackpy-particle-tracking",{"tool":40,"command":41},"bunx","bunx skills add bg-szy\u002FTOP-SKILLS --skill trackpy-particle-tracking",{"tool":43,"command":44},"pnpm","pnpm dlx skills add bg-szy\u002FTOP-SKILLS --skill trackpy-particle-tracking","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Ftrackpy-particle-tracking\u002FSKILL.md",true,[],[49,58,65,72,79,86],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":54,"categories":55,"keywords":56,"publishedAt":57},"01M7DXW9N826PKXK174PVW3038","serpmaven","Scrape Google search results (SERP) to JSON with SERP Maven (serpmaven) - a real Chrome browser on a residential proxy with sticky sessions. Run it as a CLI, a Python library, a local HTTP search API (`serve`), an MCP server or a Docker image; set the proxy login, workers, pages and cost tracking. Use when the user wants Google results, rank tracking, a self-hosted SERP API, or live Google search for an AI agent.","MIT","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fserpmaven\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":59,"name":60,"nameZh":6,"description":61,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":57},"01M7DXVHSTWDV65475QEQ915M7","revnu-landing-page-audit","Find out why a landing page isn't turning visitors into signups, demos or sales. Audits one page against what the ad, post or search that sends people there promised, then checks the first screen, proof, call to action, friction and mobile. Returns at most 7 prioritized fixes, plus what is fine and what could not be checked; rewrites specific lines and fixes the page in the repo when asked. Never promises a conversion lift. Works without a Revnu account. Use when the user says or asks: \"audit my landing page\", \"why isn't this page converting\", \"review my homepage\", \"my ads get clicks but no signups\", \"people bounce from the pricing page\", \"CRO review\", \"improve conversion rate\", \"is my hero section clear\", \"roast my landing page\", \"rewrite my headline\", \"what's wrong with this page\", \"landing page feedback\", \"make the signup page convert better\". Not for SEO or AI-search audits, page speed engineering on its own, or building a new page from scratch.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-landing-page-audit\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":57},"01M7DXV8X2D7B3VTD4HHYYHTGR","revnu-growth-context","Write down once who buys, what they're stuck on, what it costs, what proof you have and what you've already tried, so every growth task starts from facts instead of a questionnaire. Creates or updates .agents\u002Frevnu-growth.md from the repo, the live site and the user, and imports an existing product-marketing.md. Use when the user says \"set up our marketing context\", \"who is our ideal customer\", \"write our ICP\", \"describe the product for marketing\", \"positioning doc\", \"what's our brand voice\", \"remember this about our customers\", \"log what we tried\", \"what have we learned from marketing\", \"we changed pricing, update the context\", \"update our growth notes\", \"summarize the business for the agent\", \"import my product-marketing.md\", \"start a growth doc\", or before a first marketing, SEO, outreach or launch task when no context file exists. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-growth-context\u002FSKILL.md",[],[],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":57},"01M7DXV0DGJ1G0A60PAHC6J3C5","revnu-get-listed","Get onto the third-party pages AI answers and search cite when buyers ask for the best tool in your category: \"best X\" roundups, directories, review sites, GitHub awesome lists, community threads and comparison pages. Finds which ones are cited, ranks them by fit and effort, and drafts each submission, PR or pitch by the target's own rules. Use when the user says \"get us listed\", \"which directories should we submit to\", \"how do we get into best-of lists\", \"why does ChatGPT recommend competitors and not us\", \"get mentioned in AI answers\", \"submit to awesome lists\", \"get on G2\", \"where are our competitors listed\", \"pitch listicle authors\", \"find backlink opportunities\", \"launch directories\", \"get into roundups\", \"Product Hunt alternatives\", \"where should we be listed\", \"get cited by Perplexity\". Never submits, pays or posts without a yes. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-get-listed\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":57},"01M7DXTSPMGT9D6DSS0HP9BSTA","revnu-ai-readiness-audit","Audit whether your website gives ChatGPT, Perplexity, Claude, Gemini and Google's AI Overviews something worth quoting, and fix the pages that don't. Use when the user says or asks \"is my site ready for AI search\", \"audit my site for AI answers\", \"AEO audit\", \"GEO audit\", \"why doesn't ChatGPT quote our pricing\", \"make our pages citable by AI\", \"do I need llms.txt\", \"does schema help with ChatGPT\", \"check our structured data\", \"is our content visible without JavaScript\", \"AI SEO audit\", \"optimize our homepage for AI answers\", \"LLM SEO check\", \"why does AI get our product wrong\", \"fix our site for AI Overviews\". Checks fetchability and indexability, answers in the raw HTML, entity facts, schema (including JS-injected markup), headings, dates and llms.txt, then gives at most 10 prioritised fixes and edits the repo when asked. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-ai-readiness-audit\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":57},"01M7DXSZHCVTRS620GC3S97JZV","proxy-troubleshooting","Diagnose residential proxy failures, with NodeMaven's gateway as the reference - 407 with correct credentials, 406, 410, 500, a connection that hangs, ERR_TUNNEL_CONNECTION_FAILED in a browser, Playwright or Puppeteer ignoring proxy credentials, a sticky session that changes IP, geo-targeting that is silently ignored, passwords with special characters, and unexpected traffic from headless Chrome. Use when a proxy connection fails, returns the wrong location, or costs more traffic than expected.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fproxy-troubleshooting\u002FSKILL.md",[],[]]