Summary
The amplitude and period of body bending during locomotion are key quantitative parameters that describe the locomotion of Caenorhabditis elegans. Here, we present a computational workflow for calculating these parameters from centroid trajectory data using a custom Python function. We describe steps for integrating trajectory smoothing, signal transformation, and peak detection to extract robust amplitude and period estimates. We include representative figures of raw and processed trajectories to illustrate each analytical step.
Subject areas: Bioinformatics, Behavior, Computer sciences
Graphical abstract

Highlights
-
•
A protocol for quantifying locomotion from centroid trajectories
-
•
Steps for extracting bending amplitude and period
-
•
Instructions for baseline smoothing and peak detection
-
•
Guidance on automated batch analysis of worm trajectories
Publisher’s note: Undertaking any experimental protocol requires adherence to local institutional guidelines for laboratory safety and ethics.
The amplitude and period of body bending during locomotion are key quantitative parameters that describe the locomotion of Caenorhabditis elegans. Here, we present a computational workflow for calculating these parameters from centroid trajectory data using a custom Python function. We describe steps for integrating trajectory smoothing, signal transformation, and peak detection to extract robust amplitude and period estimates. We include representative figures of raw and processed trajectories to illustrate each analytical step.
Before you begin
Body-bending amplitude and period are fundamental metrics for characterizing locomotion in C. elegans.1,2,3,4 Quantitative assessment of these parameters enables systematic comparison of locomotor phenotypes across genetic, developmental, or environmental conditions. Accurate extraction of bending dynamics is therefore essential for behavioral and neuromuscular studies.
Traditional approaches typically rely on high-resolution imaging and full-body posture reconstruction to track the propagation of body waves along the worm axis.5,6 Although these methods provide detailed kinematic information, they often require specialized imaging systems, substantial computational resources, and complex segmentation algorithms, which may limit accessibility in laboratories using standard recording setups.
Here, we present a centroid-based computational workflow to quantify body-bending amplitude and period directly from the worm’s center-of-mass trajectory (Figure 1). The protocol describes the specific parameters and preprocessing steps used for analyzing single-worm recordings under controlled laboratory conditions. This approach assumes sustained oscillatory locomotion, during which body bending produces rhythmic lateral deviations relative to the overall trajectory of motion. These deviations are reflected in the centroid path as periodic fluctuations around a smoothed locomotion baseline. Displacement of the centroid relative to this baseline therefore provides a reduced one-dimensional representation of the dominant oscillatory component of body bending. With appropriate parameter adjustment, the workflow can be applied to single-worm recordings acquired using standard digital imaging systems.
Figure 1.

Overview of the flowchart of analytic methods
Innovation
This protocol provides an efficient and broadly applicable workflow for quantifying locomotion in Caenorhabditis elegans. Instead of relying on high-resolution imaging and full-body posture reconstruction, the method estimates body-bending amplitude and period directly from centroid trajectories. This abstraction preserves key behavioral features while reducing computational demands and improving compatibility with standard or low-resolution imaging systems.
In addition, we provide a Python-based analysis pipeline that integrates trajectory preprocessing and extraction of quantitative locomotion parameters within a single workflow. Unlike approaches that rely solely on endpoint behavioral indices, this framework captures continuous temporal dynamics. Overall, the protocol supports rapid, scalable, and reproducible locomotion analysis across developmental stages and experimental conditions.
Prepare the experimental platform
Timing: 30 min
-
1.
Prepare locomotion assay plates.
-
2.
Set up illumination using an LED panel to provide uniform bottom lighting.
-
3.
Mount the MV-CA060-11GM camera (Hikvision) on a stable stand.
Note: Data recording requires an MV-CA060-11GM camera (Hikvision) and a culture dish containing a single worm.
Set up the software environment
Timing: 30 min
-
4.
Install Anaconda (version 2024.10 or later).
-
5.
Install PyCharm IDE (version 2025.1.3 or later).
-
6.
Create a dedicated Conda environment and install dependencies using the provided “environment.yml” file.
-
7.
Clone or download the analysis code from the GitHub repository (https://github.com/shiruixia/worm_locomotion_analysis.git).
Note: The analytical pipeline is compatible with Windows 10 or later, macOS 10.14 or later, or Linux (e.g., Ubuntu 18.04 or newer). Minimum requirements include a quad-core 2.5 GHz processor, 16 GB RAM, and 50 GB SSD storage. For larger datasets, at least 32 GB RAM and 8 CPU cores are recommended.
Note: The repository contains the files required to run the analysis workflow, including the Python script used for body-bending period and amplitude extraction.
Key resources table
| REAGENT or RESOURCE | SOURCE | IDENTIFIER |
|---|---|---|
| Chemicals, peptides, and recombinant proteins | ||
| 2 g Agar | Riale | A6190 |
| 0.6 g NaCl | Sangon Biotech | A501218 |
| 200μL 1 M MgSO4 | Sangon Biotech | A500864 |
| 200μL 1 M CaCl2 | Sigma | C5670 |
| 5mL 1 M KPO4 pH=6.6 | Sigma; Sangon Biotech | K2HPO4 1.05104,; KH2PO4 A600445 |
| Experimental models: Organisms/strains | ||
| Caenorhabditis elegans: N2 Bristol, young adult hermaphrodites | Caenorhabditis Genetics Center(CGC) | RRID: WB-STRAIN:N2 |
| Software and algorithms | ||
| Nematode Trajectory Analysis.exe | N/A | N/A |
| Worm locomotion analysis (v1.0) | GitHub |
https://github.com/shiruixia/worm_locomotion_analysis.git DOI: https://doi.org/10.5281/zenodo.18728707 |
| Anaconda 2024.10 | Anaconda, Inc. | https://www.anaconda.com/ |
| PyCharm 2025.1.3 | JetBrains | https://www.jetbrains.com/pycharm/ |
| Python v.3.13.5 | Python Software Foundation (PSF) | https://www.python.org/ |
| pandas v.2.2.3 | PyPI/pandas development team | https://pypi.org/project/pandas/ |
| numpy v.2.1.3 | PyPI/NumPy developers | https://pypi.org/project/numpy/2.1.3/ |
| Matplotlib v.3.10.0 | PyPI/Matplotlib Development Team | https://pypi.org/project/matplotlib/3.10.0/ |
| Scipy v.1.15.3 | PyPI/SciPy developers | https://pypi.org/project/scipy/1.15.3/ |
| Tqdm v.4.67.1 | PyPI/tqdm developers | https://pypi.org/project/tqdm/ |
| Other | ||
| Camera | Hikrobot | MV-CA060-11GM |
| Objective Lens | Hikrobot | MVL-HF1628M-6MPE |
| Illumination Source (LED) | NVC LIGHTING | JC-329-0303-16 W-PB |
| Intel Core Ultra 9 285H CPU @ 2.90 GHz with 32 GB RAM (Windows 11) | N/A | N/A |
Materials and equipment
NGM Plate
| Reagent | Final concentration | Amount |
|---|---|---|
| Agar | 1% | 2 g |
| NaCl | 0.3% | 0.6 g |
| MgSO4 | 1mM | 200 μL |
| CaCl2 | 1mM | 200μL |
| KPO4 pH=6.6 | 1mM | 5mL |
| H2O | N/A | 200mL |
| Total | N/A | N/A |
Store at 25°C for up to 3 months.
Step-by-step method details
Data acquisition
Timing: Variable (depending on the number of worms and the experimental termination criteria)
This section describes standardized procedures for recording locomotion videos and extracting centroid trajectory data from individual worms. Proper environmental control and imaging setup are essential to ensure accurate downstream analysis.
-
1.Maintain stable environmental conditions.
-
a.Maintain the temperature at 22–24°C.
-
b.Avoid changes in lighting during recording.
-
a.
-
2.Prepare locomotion assay plates. troubleshooting 1.
-
a.Prepare NGM plates according to the recipe in Materials and equipment.
-
b.Pour appropriate NGM agar plates according to the standard composition.
-
c.Allow plates to dry at 25°C before use.
-
a.
-
3.Transfer C. elegans onto the assay plate. troubleshooting 1.
-
a.Pick one experimental worm and gently place it at the center of the agar surface.
-
b.Avoid scratching or damaging the agar surface.
-
a.
-
4.Check the setting of imaging system (Figure 2). troubleshooting 2.
-
a.Place the assay plate on an illuminated LED panel to provide uniform bottom lighting. Adjust the panel brightness as needed to ensure even illumination.
-
b.Adjust the position of the assay plate based on the camera preview so that it is centered directly beneath the high-resolution camera (MV-CA060-11GM, Hikvision).
-
c.Manually adjust the focal distance to ensure clear visualization of the worm body outline.
-
a.
-
5.Record locomotion videos. troubleshooting 2.
-
a.Set the frame rate to 10 frames per second under constant illumination.
-
b.Start recording until either the maximum pre-set duration is reached, or a user-defined termination criterion is satisfied (e.g., worm reaches boundary).
-
c.Save videos in AVI format for downstream processing.
-
a.
-
6.
Import locomotion video into Nematode Trajectory Analysis.exe. troubleshooting 2.
-
7.Calibrate pixel-to-distance conversion. troubleshooting 2.
-
a.Enter the reference distance (mm).
-
b.Draw a line on the reference object.
-
c.Click Confirm.
-
a.
Note: The calibration procedure, which converts pixel distance into physical units, is performed only once unless major system parameters (such as camera magnification, height, or plate-to-lens distance) are altered. If any of these parameters change, recalibration must be performed before further analysis.
-
8.Perform centroid tracking (Figure 3). troubleshooting 2.
-
a.Click Start Analysis.
-
b.After tracking completes, click Export to Excel.
-
c.Save the exported.xlsx file containing: Frame number, Centroid X position (mm), Centroid Y position (mm).
-
a.
Note: These centroid coordinates serve as input for period and amplitude analysis.
Figure 2.
Workflow for Data Acquisition
The locomotion assay for C. elegans was conducted under standardized imaging conditions.
(A) A single worm was placed near the center of an NGM agar plate.
(B) The culture plate containing the worm was positioned under the MV-CA060-11GM camera (Hikvision). The aperture and focal distance were manually adjusted to clearly visualize the worm body outline.
(C) Video recording was initiated at a frame rate of 10 frames per second and continued until the predetermined experimental endpoint.
(D) The recorded video was processed using the executable Nematode Trajectory Analysis.exe, which automatically extracted the worm’s centroid coordinates and exported them as an Excel file containing the X–Y position for each frame.
Figure 3.
Workflow for Centroid Extraction Using Nematode Trajectory Anlysis.exe
Screenshots illustrating sequential steps for extracting centroid trajectories from locomotion recordings:
(A) Load the locomotion video.
(B–C) Enter reference distance and draw calibration line to define pixel-to-length conversion.
(D) Start analysis to track centroids, then export results to Excel for quantitative measurement of body-bending behavior.
Data preprocessing
Timing: 10 min
This section describes the preparation and organization of centroid trajectory data prior to feature extraction. It ensures that raw coordinate files are correctly formatted, structured, and ready for automated batch processing (Figure 4).
-
9.Set up computational environment and dependencies.
-
a.Install required Python libraries listed in the key resources table.
-
b.Import dependencies before running the analysis scripts.
-
a.
import time
import os
import math
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from scipy.signal import savgol_filter, find_peaks
from tqdm import tqdm
-
10.Prepare Input Data and specify input/output paths.
-
a.Specify input and output folder paths.BASE_DIR = os.path.dirname(os.path.abspath(__file__))ROOT_DIR = os.path.join(BASE_DIR, “data")OUTPUT_PATH = os.path.join(BASE_DIR, “results")# Use os.path.join to ensure the FIGURE_FILE_NAME is correctly builtFIGURE_FILE_NAME_FOR_PLOTTING = “AIA glc3_Train_1.xlsx"
-
b.Confirm that each input file contains sequential centroid coordinates (X and Y position in millimeters) across frames (Figure 5).
-
a.
Note: In the input Excel file, columns “x” and “y” contain centroid coordinates (mm) for each frame.
-
11.Specify algorithm hyperparameters, using the default, or customize them as needed. troubleshooting 3.QC_MIN_MEDIAN_STEP = 1e-6QC_JUMP_FACTOR = 8.0QC_IQR_FACTOR = 4.0QC_MIN_VALID_FRACTION = 0.6PAD_SEC = 1
CRITICAL: Ensure that QC-related parameters (e.g., QC_MIN_MEDIAN_STEP, QC_JUMP_FACTOR, QC_IQR_FACTOR) are appropriately tuned for the recording quality and sampling frequency. Overly strict thresholds may exclude valid trajectories, whereas overly permissive thresholds may retain tracking artifacts.Note: Five key hyperparameters that can be tuned are as follows:-
a.QC_MIN_MEDIAN_STEP (default = 1e−6): the minimum median frame-to-frame displacement required for a trajectory to be considered valid. If the median displacement falls below this threshold, the trajectory is classified as unreliable and excluded from analysis. Increasing this value makes the algorithm more sensitive to near-static segments and may exclude recordings with prolonged pausing. Decreasing it allows inclusion of low-motility trajectories but may retain collapsed or poorly tracked data.
-
b.QC_JUMP_FACTOR (default = 8.0): the multiplier that defines how large a frame-to-frame displacement must be, relative to the typical step size, to be considered abnormal. Lower values increase sensitivity to abrupt centroid discontinuities but may exclude legitimate rapid movements. Higher values make the filtering more permissive and may retain occasional tracking jumps.
-
c.QC_IQR_FACTOR (default = 4.0): the interquartile-range threshold used to detect displacement outliers. Smaller values impose stricter filtering and may remove moderate variability, whereas larger values reduce sensitivity to statistical outliers.
-
d.PAD_SEC (default = 1 s): the duration of temporal padding applied before and after each abnormal frame. This parameter expands exclusion windows to account for unstable motion segments surrounding tracking artifacts. Larger values remove longer contiguous segments, while smaller values restrict exclusion to narrower intervals.
-
e.QC_MIN_VALID_FRACTION (default = 0.6): the minimum proportion of frames that must remain after quality control for a trajectory to be retained. Increasing this value enforces stricter dataset inclusion criteria, whereas decreasing it allows partially fragmented trajectories to proceed to analysis.
-
a.
-
12.
-
13.
Identify abnormal frames based on displacement statistics. Mark frames as abnormal when the displacement between consecutive frames is substantially larger than the typical step size observed within the trajectory, or when it lies outside a robust interquartile-range threshold. If the overall median displacement is close to zero, classify the trajectory as unreliable and exclude it from further analysis.
Note: Abnormally large displacements commonly arise from transient segmentation failure or centroid mis-localization. Near-zero displacement may reflect pausing behavior or tracking collapse.
-
14.
Expand abnormal frames using temporal padding. For each abnormal frame, extend the exclusion window to include a fixed duration before and after the flagged frame (e.g., 1 seconds on each side) to account for unstable motion segments surrounding the event.
-
15.
Exclude abnormal frames prior to baseline extraction.
Figure 4.
Directory structure for Python-based trajectory processing
Representative screenshots showing the organization of raw tracking files and processed outputs generated during trajectory analysis.
Figure 5.

Input Data Structure for period and amplitude extraction
Example showing the expected format of centroid trajectory data, where each row represents one video frame.
Remove all flagged frames (after padding) to obtain the cleaned trajectory (x∗,y∗). If the proportion of retained frames falls below a predefined threshold (e.g., 60% of the original frames), exclude the entire trajectory from downstream analysis.
Note: Excluding trajectories with insufficient valid frames reduces bias introduced by fragmented or unstable segments.
Feature extraction
Timing: Variable (depending on the number and length of trajectory files)
This section describes the computational procedures used to extract bending amplitude and period from centroid trajectory data. The algorithm reconstructs a locomotion baseline, generates a displacement signal, and identifies oscillatory features corresponding to body-bending cycles (Figure 6).
Note: On a Windows 11 workstation (Intel Core Ultra 9 285H CPU, 32 GB RAM), batch analysis of 18 trajectory files required approximately 1.0 s total wall time (∼0.06 s per file). The normalized computational cost was approximately 0.07 s per 1,000 frames. Computational cost scales approximately linearly with trajectory length.
-
16.Specify algorithm hyperparameters, using the default, or customize them as needed. troubleshooting 4, 5, 6.FRAME_RATE = 10BASELINE_SMOOTH_SEC = 0.5SG_WINDOW_SEC = 1.2MIN_PEAK_WIDTH_SEC = 0.1MAX_PEAK_WIDTH_SEC = 3.5SG_POLYORDER = 3
CRITICAL: The smoothing window (SG_WINDOW_SEC) and peak width constraints must be selected in accordance with the expected bending period of the organism. Excessive smoothing may attenuate true oscillatory signals, whereas insufficient smoothing may introduce noise-driven peak artifacts.Note: Five key hyperparameters that can be tuned are as follows:-
a.FRAME_RATE (default = 10 frames per second): The acquisition sampling frequency of the centroid trajectory data. This parameter determines the temporal resolution of the analysis and is used to convert all time-based parameters (specified in seconds) into frame units. When analyzing recordings acquired at different sampling rates, FRAME_RATE must be updated accordingly to preserve temporal consistency across filtering and peak detection steps.
-
b.BASELINE_SMOOTH_SEC (default = 0.5 s): The temporal window used for baseline trajectory smoothing via a moving average filter. A smaller value preserves fine oscillatory details in the centroid path but increases sensitivity to high-frequency noise. A larger value enhances smoothing and reduces short-term fluctuations but may attenuate shallow or rapid body bends. In general, this parameter should reflect the expected timescale of forward locomotion relative to body bending. The window length is automatically converted to frame units according to FRAME_RATE.
-
c.SG_WINDOW_SEC (default = 1.2 s): The temporal window used for Savitzky–Golay filtering of the distance signal representing body bending amplitude. Increasing this parameter produces smoother oscillatory traces and reduces noise-induced peak artifacts but may blur rapid bending events. Decreasing the window length increases responsiveness to fast oscillations but may introduce spurious extrema due to noise. In specifying this value, consider the typical bending period of the organism. The window length is automatically converted to an odd number of frames based on FRAME_RATE to satisfy the Savitzky–Golay filter requirement.
-
d.MIN_PEAK_WIDTH_SEC and MAX_PEAK_WIDTH_SEC (default = 0.1 s and 3.5 s, respectively): These parameters constrain the allowable temporal duration of detected oscillatory peaks. The minimum width excludes narrow, noise-driven spikes, while the maximum width filters out unusually broad, non-oscillatory fluctuations. If the minimum width is set too low, false-positive detections may increase; if set too high, genuine short-duration oscillations may be missed. Likewise, an excessively large maximum width may admit slow drift artifacts, whereas an overly restrictive value may truncate valid long-period oscillations. Both parameters are defined in seconds and automatically converted to frame units to ensure temporal invariance across sampling frequencies.
-
e.SG_POLYORDER (default = 3): The polynomial order used in the Savitzky–Golay filter. Higher values preserve waveform sharpness and local curvature but may amplify noise fluctuations, whereas lower values generate smoother curves with reduced sensitivity to high-frequency components. Unlike window length parameters, SG_POLYORDER is independent of sampling frequency and typically remains stable across datasets with similar signal characteristics.
-
a.
-
17.
Extract the locomotion baseline by smoothing. Smooth raw centroid trajectories (x, y) using a moving average filter to obtain the locomotion baseline.
-
18.Construct the distance signal.
-
a.Calculate the displacement of the worm relative to its locomotion baseline to generate a one-dimensional distance function that captures periodic body-bending dynamics.
-
b.Apply a Savitzky–Golay filter to the distance function to reduce high-frequency noise while preserving waveform shape.
-
a.
-
19.Detect peaks and compute amplitude/period.
-
a.Identify local maxima and minima of the smoothed distance function using prominence and width thresholds in the find_peaks function in Python. Set peak width constraints using MIN_PEAK_WIDTH_SEC and MAX_PEAK_WIDTH_SEC, and set prominence using PEAK_PARAMS in the script.
-
b.Align consecutive extrema to calculate bending amplitude (peak-to-valley distance) and bending period (time interval between consecutive maxima).
-
a.
-
20.
Statistical feature calculation. Calculate summary metrics, including mean, median, standard deviation, and quartiles for bending amplitude and period.
-
21.Export results and logs.
-
a.Save extracted features for all processed files in an.xlsx file.
-
b.Log files that fail processing in a separate report to ensure transparency.
-
a.
Note: While each step is outlined for transparency, users typically only need to run the main function to complete the analysis automatically.
Figure 6.
Output Excel Result Screenshot
Visualization
Timing: 5 min
This section describes visualization procedures used to inspect baseline correction, displacement signals, and detected bending cycles. These diagnostic plots allow users to validate the accuracy of feature extraction (Figure 7).
-
22.
Plot raw trajectory and baseline. Overlay raw centroid trajectories with the computed locomotion baseline to confirm correct baseline extraction.
-
23.
Plot the distance function. Plot the smoothed displacement trace over time to visualize periodic oscillatory behavior.
-
24.
Overlay detected extrema and annotate amplitude/period. Highlight detected local maxima and minima. Draw vertical lines to indicate bending amplitude and horizontal lines to indicate bending period.
-
25.
Generate segmented views for long recordings. Divide long datasets into segments and display them separately for improved visualization clarity.
if __name__ == '__main__':
FIGURE_FILE_PATH = os.path.join(ROOT_DIR,
FIGURE_FILE_NAME_FOR_PLOTTING)
print(“--- Phase 1: Starting Batch Analysis ---")
t0 = time.perf_counter()
df_results = batch_analyze(ROOT_DIR, OUTPUT_PATH)
t1 = time.perf_counter()
batch_sec = t1 - t0
n_ok = len(df_results) if df_results is not None else 0
print(f“\n[RUNTIME] Batch analysis wall time: {batch_sec:.2f} s")
if n_ok > 0:
print(f“ [RUNTIME] Mean time per file (successful only): {batch_sec / n_ok:.2f} s/file")
print(f“ [RUNTIME] Estimated time for 100 files: {(batch_sec / n_ok) ∗ 100 / 60:.2f} min")
if df_results is not None and not df_results.empty:
print(f“Batch analysis completed. Results saved to: {OUTPUT_PATH}")
print(“\nAnalysis Results (File Name and Key Metrics Only): ")
print(df_results[['file_name', 'avg_velocity', 'period_mean', 'amp_mean']].head())
else:
print(“Batch analysis did not return any valid data. ")
# --- Phase 2: Single File Plotting ---
if os.path.exists(FIGURE_FILE_PATH):
print(f“\n--- Phase 2: Starting Plotting for: {os.path.basename(FIGURE_FILE_PATH)} ---")
main_plot_segmented_analysis(FIGURE_FILE_PATH, segment_size_pairs=10)
else:
print(f“\nWarning: Plotting skipped. Figure file not found at: {FIGURE_FILE_PATH}\n"
f“Please ensure '{os.path.basename(FIGURE_FILE_NAME_FOR_PLOTTING)}' exists in '{ROOT_DIR}'. ")
Note: Diagnostic plots are generated automatically when running the main workflow; users may optionally run the plotting function for a single file. These diagnostic plots allow visual inspection of detected extrema in relation to the smoothed displacement signal, supporting evaluation of peak detection performance.
Figure 7.
Visualization panels
(A)Actual Trajectory and Smoothed Baseline: The entire actual trajectory of a worm (black curve) and its corresponding locomotion baseline (red curve).
(B)Distance Function: The distance from the worm’s actual trajectory to the smoothed baseline, visualized as a function of frame index. After smoothing and denoising, the distance function exhibits a periodic oscillatory pattern.
(C) Amplitude and Period Quantification: This panel visualizes how amplitude and period are defined. Maximum and minimum are identified (red and blue circles). Amplitude is defined by the vertical distance between a maximum and an adjacent minimum (blue vertical line), while period is the horizontal distance between two consecutive maxima (red horizontal line).
Expected outcomes
This protocol enables robust and automated quantification of key locomotor dynamics in C. elegans based on centroid trajectory data. The workflow outputs biologically interpretable metrics, including the bending period (s) and oscillation amplitude (mm). These measures are widely used to assess neuromuscular function and behavioral states, making the analysis well suited for studies investigating genetic, developmental, or environmental modulation of locomotion.
The analysis produces three main categories of outputs that support both quantification and quality control. First, trajectory files provide time-series datasets of centroid displacement traces used for bending detection. Second, a summary Excel report compiles mean and standard deviation values for period and amplitude across individuals. Third, diagnostic figures visually display raw trajectories against the smoothed baseline, the constructed distance function, and detected extrema, enabling users to validate feature extraction.
Variability in detected locomotion features can arise from both biological diversity (e.g., behavioral state transitions, individual differences) and measurement-related factors (e.g., tracker noise). Overall, this protocol provides a reproducible and modular framework for biomechanical characterization of nematode locomotion. With minimal user input, it enables fully automated batch analysis. The workflow can readily extend to comparative studies involving mutants, aging effects, chemotaxis assays, or neuromodulatory manipulations, supporting broad applications in behavioral genetics and neuroscience.
Quantification and statistical analysis
Quantitative locomotion parameters were extracted from each processed trajectory, including bending period (s), amplitude (mm), mean velocity, and the number of detected cycles. For each individual worm, the distributions of period and amplitude across detected cycles were summarised using median, standard deviation, and interquartile range (IQR). These statistics were automatically exported into a structured Excel report (Figure 6).
This protocol emphasises descriptive behavioural quantification. The extracted metrics provide baseline measurements for subsequent comparative studies (e.g., genetic mutants, ageing assays, environmental perturbations). To facilitate reproducibility and pipeline validation, a sample dataset and full analysis code are publicly available at the GitHub repository:
Limitations
This protocol estimates oscillatory bending dynamics from centroid displacement relative to a smoothed locomotion baseline, rather than from full-body posture reconstruction. As a result, behaviors involving large-amplitude turns (e.g., omega turns), body overlap, or transient tracking ambiguity may introduce deviations between centroid-derived amplitude and posture-based measurements.
The workflow is primarily intended for sustained forward locomotion under stable tracking conditions. Trajectory segments exhibiting minimal displacement, abrupt centroid discontinuities, or unstable tracking should be excluded during preprocessing to maintain measurement reliability. Because this approach does not encode head–tail orientation or body curvature, it does not distinguish forward from reverse locomotion cycles and does not resolve fine-scale posture dynamics.
In addition, reliable centroid-based amplitude and period estimation requires adequate temporal sampling relative to the intrinsic bending frequency of the worm. If the recording frame rate is too low compared to the oscillation frequency, peak detection accuracy may decrease due to insufficient temporal resolution.
Troubleshooting
Problem 1
Condensation forms on the inner surface of the culture dish lid, significantly reducing video clarity. Related to Steps 2–3.
Potential solution
Allow the NGM agar plate to fully cool to room temperature before placing the lid on the dish. Moisture condensation commonly arises when a warm plate is sealed prematurely. Before initiating video recording, visually inspect the lid to ensure it is completely free of water droplets.
Problem 2
Video appears blurry or the worm body is partially obscured. Related to Steps 4–8.
Potential solution
This problem typically occurs when video contrast is too low or the worm outline is unclear. Before recording, carefully adjust the camera lens aperture and focus to optimize image sharpness. Ensure that the worm’s body boundary is well-defined and exhibits high contrast.
Problem 3
Many frames are excluded during quality control. Related to Step 11.
Potential solution
This may occur when centroid detection is unstable (e.g., low contrast, temporary body overlap, or segmentation errors) or when the recording contains prolonged pausing with minimal displacement.
Improve imaging conditions (e.g., optimize illumination and focus), ensure accurate centroid extraction, or reduce animal density to minimize overlap. If exclusion is driven by threshold sensitivity rather than tracking failure, adjust quality control parameters accordingly. Increasing QC_JUMP_FACTOR or QC_IQR_FACTOR makes the filtering more permissive, whereas decreasing them makes exclusion stricter.
Problem 4
No oscillatory peaks are detected in the centroid-derived distance signal. Related to Step 16.
Potential solution
This may occur if the smoothing parameters are overly restrictive, resulting in attenuation of short-period oscillatory components in the centroid-derived signal, or if the peak detection thresholds are set too stringently. To recover valid oscillatory peaks, either decrease SG_WINDOW_SEC to reduce smoothing strength, reduce MIN_PEAK_WIDTH_SEC to allow shorter-duration cycles, or lower the prominence threshold in PEAK_PARAMS.
Problem 5
Excessive peaks are detected, resulting in unrealistically short oscillation periods. Related to Step 16.
Potential solution
Over-detection of peaks typically reflects overly permissive parameter settings, where small-amplitude or short-duration fluctuations are treated as valid oscillatory events. This can be addressed by increasing SG_WINDOW_SEC, widening the minimum peak width constraint (MIN_PEAK_WIDTH_SEC), or elevating the prominence threshold in PEAK_PARAMS.
Problem 6
The smoothed trajectory appears overly flattened and oscillatory features are diminished. Related to Step 16.
Potential solution
To maintain realistic oscillatory patterns, we need to apply smoothing conservatively. Whether adjusting SG_WINDOW_SEC or SMOOTH_WINDOW, ensure that the window length does not exceed the expected oscillation period.
Resource availability
Lead contact
Further information and requests for resources should be directed to and will be fulfilled by the lead contact, He Liu (heliu@bnu.edu.cn).
Technical contact
Technical questions on executing this protocol should be directed to and will be answered by the technical contact, Ruixia Shi (ruixiashi@mail.bnu.edu.cn).
Materials availability
The executable file (.exe) and analysis code have been deposited as supplementary attachments to this protocol.
Data and code availability
All analysis code and example datasets are available on GitHub (https://github.com/shiruixia/worm_locomotion_analysis.git). A version of record of the repository has been archived at Zenodo (https://doi.org/10.5281/zenodo.18728707).
Acknowledgments
This work was supported by the National Natural Science Foundation of China (NSFC) under grant nos. 32371079 and 12575033.
Author contributions
H.L. and R.S. conceived and designed the protocol. R.S. developed the methodology and wrote the initial draft. Y.S. contributed to protocol optimization and validation. Z.D. provided critical revisions and conceptual input. H.L. supervised the project. All authors read and approved the final manuscript.
Declaration of interests
The authors declare no competing interests.
Contributor Information
Ruixia Shi, Email: ruixiashi@mail.bnu.edu.cn.
He Liu, Email: heliu@bnu.edu.cn.
References
- 1.Zhao B., Khare P., Feldman L., Dent J.A. Reversal Frequency in Caenorhabditis elegans Represents an Integrated Response to the State of the Animal and Its Environment. J. Neurosci. 2003;23:5319–5328. doi: 10.1523/JNEUROSCI.23-12-05319.2003. [DOI] [PMC free article] [PubMed] [Google Scholar]
- 2.Pradhan S., Quilez S., Homer K., Hendricks M. Environmental Programming of Adult Foraging Behavior in C. elegans. Curr. Biol. 2019;29:2867–2879.e4. doi: 10.1016/j.cub.2019.07.045. [DOI] [PubMed] [Google Scholar]
- 3.Liu H., Wu T., Canales X.G., Wu M., Choi M.-K., Duan F., Calarco J.A., Zhang Y. Forgetting generates a novel state that is reactivatable. Sci. Adv. 2022;8 doi: 10.1126/sciadv.abi9071. [DOI] [PMC free article] [PubMed] [Google Scholar]
- 4.Bhat U.S., H S., Surendran S., Tasnim N., Babu K. FLP-15 modulates the amplitude of body-bends during locomotion in Caenorhabditis elegans. Open Biol. 2025;15 doi: 10.1098/rsob.250165. [DOI] [PMC free article] [PubMed] [Google Scholar]
- 5.Malvar S., Gontijo R.G., Carmo B.S., Cunha F.R. On the kinematics-wave motion of living particles in suspension. Biomicrofluidics. 2017;11 doi: 10.1063/1.4997715. [DOI] [PMC free article] [PubMed] [Google Scholar]
- 6.Stephens G.J., Johnson-Kerner B., Bialek W., Ryu W.S. Dimensionality and Dynamics in the Behavior of C. elegans. PLoS Comput. Biol. 2008;4 doi: 10.1371/journal.pcbi.1000028. [DOI] [PMC free article] [PubMed] [Google Scholar]
Associated Data
This section collects any data citations, data availability statements, or supplementary materials included in this article.
Data Availability Statement
All analysis code and example datasets are available on GitHub (https://github.com/shiruixia/worm_locomotion_analysis.git). A version of record of the repository has been archived at Zenodo (https://doi.org/10.5281/zenodo.18728707).

Timing: 30 min



