Motion Capture and Biomechanics Analysis for PhysioExperiment Objects
PhysioMoCap provides a comprehensive motion capture, pose estimation, and biomechanical analysis toolkit built on the PhysioExperiment data model. With 177 exported functions -- the largest package in the PhysioExperiment ecosystem -- it covers the full analysis pipeline from file I/O through kinematics, kinetics, gait analysis, movement variability, EMG integration, and clinical statistics. PhysioMoCap supports optical motion capture (C3D, Venus3D), markerless pose estimation (OpenPose, DeepLabCut, MediaPipe, OpenCap), skeletal animation formats (BVH, ASF/AMC), OpenSim musculoskeletal modeling, and standardized datasets (GaitRec).
You can install PhysioMoCap from r-universe:
# the containers build on Bioconductor, so its repositories are needed too
install.packages("BiocManager", repos = "https://cloud.r-project.org")
install.packages("PhysioMoCap",
repos = c("https://x-biosignal.r-universe.dev", BiocManager::repositories()))
Or install the development version from GitHub:
# install.packages("remotes", repos = "https://cloud.r-project.org")
remotes::install_github("x-biosignal/PhysioMoCap")
library(PhysioMoCap)
# A demonstration recording: bilateral lower-limb markers at 120 Hz.
# No external file is needed; for real data use readMoCapAuto() or a format
# reader such as readTRC() (readC3D() is shown in the note below).
pe <- demoMoCapData()$mocap
# Inspect the data
pe
samplingRate(pe) # 120 Hz
channelNames(pe) # marker names
# Detect gait events from the kinematics (schema_gait is a TaskSchema object)
events <- detectEvents(pe, schema = schema_gait)
events
# Segment the recording into gait-cycle phases
phases <- segmentPhases(pe, events, schema = schema_gait)
# Visualise the ensemble-averaged gait cycle
plotGaitCycle(pe, events)
# Spatiotemporal gait parameters (cadence, stance/swing, symmetry) from
# bilateral heel-strike (HS) and toe-off (TO) events
gait_events <- data.frame(
event = c("HS_R", "TO_L", "HS_L", "TO_R", "HS_R", "TO_L", "HS_L", "TO_R", "HS_R"),
index = c(12, 35, 72, 95, 132, 155, 192, 215, 252)
)
calculateGaitParameters(pe, gait_events, side = "both")
Reading a real C3D recording needs the optional c3dr package and a .c3d
file; the same gait workflow then applies to the loaded object:
# install.packages("c3dr")
# pe <- readC3D("walking_trial.c3d") # PhysioExperiment: markers + analog + force data
# events <- detectEvents(pe, schema = schema_gait)
# calculateGaitParameters(pe, gait_events, side = "both")
Read data from all major motion capture, pose estimation, and biomechanics formats through a unified interface:
Optical motion capture:
readC3D() -- C3D binary format (marker positions, analog data, force plates)readVenus3D() -- Venus3D optical tracking systemreadMoCapCSV() -- generic CSV with configurable column mappingMarkerless pose estimation:
readOpenPose() -- OpenPose JSON keypoint outputreadDeepLabCut() -- DeepLabCut HDF5/CSV pose estimationreadMediaPipe() -- MediaPipe holistic/pose landmarksreadOpenCap() -- OpenCap cloud-based markerless captureSkeletal animation:
readBVH() -- BioVision Hierarchy motion filesreadASF() / readAMC() -- Acclaim skeleton and motion dataOpenSim musculoskeletal modeling:
readTRC() -- marker coordinate filesreadMOT() -- motion/force data filesreadSTO() -- storage files (IK, ID, muscle analysis results)readOpenSimOutputs() -- batch read all OpenSim tool outputsStandardized datasets:
readGaitRec() -- GaitRec clinical gait databaseAuto-detection:
readMoCapAuto() -- automatically detect format and call the appropriate readerDefine skeletal models and compute joint-level kinematics:
define_skeleton() / SkeletonModel() -- create custom skeletal topology with segment definitionsget_bone_connections(), get_limb_pairs(), get_segment_lengths() -- query skeleton structurecalculateJointAngles() -- 3D joint angles from marker positionsvectorAngle() -- angle between arbitrary 3D vectorsestimateOrientation() -- orientation estimation from IMU or marker dataquaternionToEuler() / eulerToQuaternion() -- rotation representation conversioncalibrateIMU() -- IMU sensor calibrationDetect and fill missing marker data in optical tracking recordings:
detectGaps() -- identify gaps (missing frames) per markerfillGaps() -- gap filling with configurable methodfillGapsLinear() -- linear interpolation for short gapsfillGapsSpline() -- cubic spline interpolation for longer gapsreportGaps() -- summary statistics of gap distributionAutomated marker labeling and swap correction for optical systems:
trackMarkers() -- frame-to-frame marker assignment using the Hungarian algorithmdetectSwaps() -- identify marker label swaps between framescorrectSwaps() -- automatically correct detected label swapsGeneral-purpose signal processing adapted for motion data:
filterSignals() -- apply filters to PhysioExperiment assay databutterworthFilter() -- Butterworth IIR filter (low/high/bandpass)savgolFilter() -- Savitzky-Golay smoothing filterdifferentiate() -- numerical differentiation (central differences)computeVelocity() / computeAcceleration() / computeJerk() / computeSpeed() -- kinematic derivativesresampleSignal() / resampleVector() -- change sampling rate via interpolationmovingAverage() -- moving average smoothingCenter of mass, segment inertia, and gravity compensation:
calculateCOM() -- whole-body center of mass from segment modelcalculateSegmentCOM() -- segment-level center of massestimateSegmentInertia() -- inertial parameters from anthropometric tablessegmentParameters() -- segment mass, length, and COM locationremoveGravity() -- subtract gravitational component from accelerometer dataEvent detection and movement phase segmentation with pre-built task schemas:
detectEvents() -- automatic event detection from kinematic signalsmanualEvents() -- define events from known timestampsEvent() / Phase() -- event and phase constructorsgetEvent() / getEventNames() -- query detected eventssegmentPhases() -- segment continuous data into movement phasesextractPhase() -- extract data within a specific phasegetPhase() / getPhaseNames() / getPhaseData() / getPhaseColors() -- phase accessorshasValidPhases() -- validate phase segmentationphaseTiming() / phaseDurations() / phaseRatios() -- temporal characteristics of phasesPre-built task schemas:
TaskSchema() / validateSchema() / getSchema() / listSchemas() -- schema managementschema_gait() -- walking (heel strike, toe off, stance, swing)schema_running() -- running (flight phase, contact phase)schema_jump() -- vertical/horizontal jump (takeoff, flight, landing)schema_cycling() -- pedaling (top dead center, power phase, recovery)schema_balance() -- postural balance (quiet stance, perturbation, recovery)schema_cutting() -- cutting maneuvers (approach, plant, push-off)schema_throw() -- throwing (wind-up, acceleration, release, follow-through)Variability, similarity, and dimensionality reduction for movement waveforms:
normalizeMovement() -- time-normalize waveforms to percentage of cyclenormalizedTimeAxis() -- generate normalized time vectordtwDistance() -- dynamic time warping distance between waveformsdtwDistanceMatrix() -- pairwise DTW distance matrixdtwWarp() -- compute optimal warping pathdtwAverage() -- DTW barycenter averagingdtwClustering() -- hierarchical clustering of movement patternswaveformPCA() -- principal component analysis of waveform ensemblesextractWaveformFeatures() -- extract amplitude, timing, and shape featureswaveformUMAP() -- UMAP dimensionality reduction for movement patternswaveformTSNE() -- t-SNE dimensionality reductioncombineTrials() -- combine multiple trials into an ensemblebatchNormalize() -- batch normalization across trialsSpatiotemporal gait parameters and symmetry assessment:
calculateGaitParameters() -- cadence, stride length, walking speed, stance/swing ratiosummarizeGaitParameters() -- aggregate parameters across multiple cyclescalculateStepSymmetry() -- step length and timing symmetrysymmetryIndex() -- Robinson symmetry index and related metricsGround reaction force analysis and contact detection:
analyzeForcePlate() / analyzeForcePlatePE() -- comprehensive force plate analysisdetectForcePlateContacts() -- threshold-based contact detectionfilterGRF() -- low-pass filter for ground reaction force datacalculateCOP() -- center of pressure calculationcomputeLoadingRate() -- vertical GRF loading ratecomputeImpulse() -- impulse (time integral of GRF)Joint moment and power estimation from kinematics and kinetics:
inverseDynamics2D() -- planar (sagittal plane) inverse dynamicsinverseDynamics3D() -- full 3D inverse dynamicscomputeJointPower() -- joint power from moment and angular velocityElectromyography processing and synchronization with motion data:
normalizeEMG() -- amplitude normalization (MVC, peak, mean)rectifyEMG() -- full-wave rectificationcomputeRMSEnvelope() -- root mean square envelopeprocessEMG() -- combined rectification + envelope pipelinealignEMGtoMoCap() -- temporal alignment of EMG to motion capture dataintegrateEMGMoCap() -- unified EMG-MoCap analysissynchronizeSignals() -- general-purpose signal synchronizationReliability and agreement metrics commonly used in rehabilitation research:
icc() -- intraclass correlation coefficient (ICC) for inter-rater/test-retest reliabilitysem() -- standard error of measurementmdc() -- minimal detectable changeblandAltman() -- Bland-Altman limits of agreement analysiscohensD() -- Cohen's d effect sizeetaSquared() -- eta-squared effect size for ANOVA designsInterface for OpenSim musculoskeletal simulation workflows:
create_schema_from_opensim() -- derive task schemas from OpenSim motion filesbatch_analyze_opensim() -- batch processing of OpenSim resultsrun_opensim_toolchain() -- run OpenSim tools (IK, ID, SO, RRA, CMC) from RBiomechanics-specific plotting functions:
plotSkeleton() / plotSkeleton3D() -- 2D and 3D stick figure visualizationplotSkeletonOverlay() / plotSkeletonSequence() -- multi-frame skeleton displayplotTrajectory() -- marker trajectory over timeplotCycle() / plotGaitCycle() -- ensemble-averaged cycle plots with variability bandsplotMultiPanel() -- multi-channel panel plots (kinematics, kinetics, EMG)plotSpaghetti() -- overlaid individual trials (spaghetti plot)plotPhasePortrait() -- phase plane plots (position vs. velocity)plotPhaseDurations() -- phase timing bar chartsplotSymmetry() -- symmetry radar/bar plotsplotDTW() -- DTW alignment visualizationplotFPCA() -- functional PCA component plotsplotPCAScatter() / plotPCAVariance() -- PCA results visualizationplotUMAP() -- UMAP embedding scatter plotsplotWaveformComparison() -- side-by-side waveform comparisonplotGroupComparison() -- group-level statistical comparison plotsplotCorrelationMatrix() -- correlation heatmapsplotEffectSizeForest() -- forest plots for effect sizesTools for validating analysis pipelines against reference data:
createBenchmarkExample() -- generate synthetic benchmark datasetsrunBenchmarkSuite() -- run full benchmark pipelinebenchmarkAgreement() -- compute agreement metrics against gold standardbenchmarkManifestTemplate() / writeBenchmarkManifest() / validateBenchmarkManifest() -- manage benchmark data manifestsdefaultBenchmarkThresholds() -- standard thresholds for biomechanics validationHelpers for new users to explore the package without external data:
quickStartMoCap() -- generate a complete worked example with simulated dataassessMoCapReadiness() -- check data readiness for downstream analysisdemoMoCapData() -- create demonstration PhysioExperiment objects| Application | Key Functions |
|---|---|
| Clinical gait analysis |
readC3D(), detectEvents(), calculateGaitParameters(), plotGaitCycle()
|
| Markerless pose tracking |
readOpenPose(), readDeepLabCut(), readMediaPipe()
|
| Running biomechanics |
schema_running(), analyzeForcePlate(), computeLoadingRate()
|
| Movement variability |
dtwDistance(), dtwClustering(), waveformPCA(), fPCA()
|
| Musculoskeletal modeling |
readTRC(), run_opensim_toolchain(), inverseDynamics3D()
|
| Rehabilitation assessment |
icc(), sem(), mdc(), blandAltman(), symmetryIndex()
|
| EMG-MoCap integration |
normalizeEMG(), alignEMGtoMoCap(), plotMultiPanel()
|
| Balance/postural control |
schema_balance(), calculateCOP(), plotTrajectory()
|
Optional (in Suggests):
PhysioMoCap is part of the PhysioExperiment ecosystem, a suite of R packages for multi-modal physiological signal analysis:
| Package | Description |
|---|---|
| PhysioCore | Core data structures and accessors |
| PhysioIO | File I/O (EDF, HDF5, BIDS, CSV, MAT) |
| PhysioPreprocess | Preprocessing (filters, ICA, resampling) |
| PhysioAnalysis | Analysis and visualization |
| PhysioCrossModal | Cross-modal coupling and connectivity |
| PhysioMoCap | Motion capture and biomechanics |
Visit the r-universe page to browse all available packages.
MIT License. See LICENSE for details.
Yusuke Matsui
Part of the Physio ecosystem. Community and policy documents live in the umbrella repository: