| Title: | Motion Capture and Biomechanics Analysis for PhysioExperiment Objects |
|---|---|
| Description: | Provides motion capture, pose estimation, and biomechanical simulation analysis for PhysioExperiment objects. Includes I/O for C3D, Venus3D, GaitRec, OpenPose, DeepLabCut, MediaPipe, BVH, ASF/AMC, OpenSim, and generic CSV formats. Provides marker tracking (Hungarian algorithm), signal filtering, numerical differentiation, resampling, center of mass calculation, gait parameters, clinical statistics (ICC, SEM, MDC, Bland-Altman), movement phase segmentation, dynamic time warping, movement normalization, functional PCA, force-plate kinetics (GRF filtering, COP, loading rate, impulse), planar inverse dynamics (joint moments/power), EMG integration (rectification, RMS envelope, MVC normalization), gait/running/jump task schemas, OpenSim workflow integration, and biomechanics-specific visualization. |
| Authors: | Yusuke Matsui [aut, cre] |
| Maintainer: | Yusuke Matsui <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.2.0 |
| Built: | 2026-05-16 05:34:30 UTC |
| Source: | https://github.com/x-biosignal/PhysioMoCap |
Align EMG to motion-capture sampling grid
alignEMGtoMoCap( emg, emg_sampling_rate, mocap_length, mocap_sampling_rate, method = "linear" )alignEMGtoMoCap( emg, emg_sampling_rate, mocap_length, mocap_sampling_rate, method = "linear" )
emg |
Numeric vector or matrix of EMG data (time x channels). |
emg_sampling_rate |
EMG sampling rate (Hz). |
mocap_length |
Target number of MoCap samples. |
mocap_sampling_rate |
Target MoCap sampling rate (Hz). |
method |
Interpolation method passed to |
Matrix of aligned EMG data with mocap_length rows.
Merletti R, Parker PA (2004). "Electromyography: Physiology, Engineering, and Non-Invasive Applications." IEEE Press/Wiley.
integrateEMGMoCap() for full EMG-MoCap integration,
resampleSignal() for general signal resampling.
emg <- matrix(rnorm(2000), ncol = 2) emg_aligned <- alignEMGtoMoCap(emg, 1000, mocap_length = 200, mocap_sampling_rate = 100)emg <- matrix(rnorm(2000), ncol = 2) emg_aligned <- alignEMGtoMoCap(emg, 1000, mocap_length = 200, mocap_sampling_rate = 100)
Convenience wrapper that filters GRF components and computes COP, loading rate, and impulse summaries.
analyzeForcePlate( forces, moments = NULL, sampling_rate, cutoff = 20, threshold = 20, order = 4, filter_method = c("butterworth", "moving_average"), origin = c(0, 0, 0) )analyzeForcePlate( forces, moments = NULL, sampling_rate, cutoff = 20, threshold = 20, order = 4, filter_method = c("butterworth", "moving_average"), origin = c(0, 0, 0) )
forces |
Matrix/data.frame with force components (X, Y, Z). |
moments |
Optional matrix/data.frame with moment components (X, Y, Z). |
sampling_rate |
Sampling rate in Hz. |
cutoff |
Low-pass cutoff for force filtering. |
threshold |
Contact threshold for stance detection. |
order |
Butterworth filter order. |
filter_method |
Filtering method passed to |
origin |
Force-plate origin used in COP computation. |
A list with elements: filtered_forces, cop, loading_rate,
impulse, and summary.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
filterGRF() for ground reaction force filtering,
calculateCOP() for center of pressure computation,
computeLoadingRate() for loading rate analysis,
analyzeForcePlatePE() for PhysioExperiment-based analysis.
f <- cbind(Fx = rep(0, 1000), Fy = rep(0, 1000), Fz = c(rep(0, 200), abs(sin(seq(0, pi, length.out = 600))) * 800, rep(0, 200))) out <- analyzeForcePlate(f, sampling_rate = 1000)f <- cbind(Fx = rep(0, 1000), Fy = rep(0, 1000), Fz = c(rep(0, 200), abs(sin(seq(0, pi, length.out = 600))) * 800, rep(0, 200))) out <- analyzeForcePlate(f, sampling_rate = 1000)
Convenience wrapper for analyzeForcePlate() when force and moment
components are stored in PhysioExperiment assays.
analyzeForcePlatePE( pe, force_assay = "grf", moment_assay = NULL, plate_index = 1L, sampling_rate = NULL, ... )analyzeForcePlatePE( pe, force_assay = "grf", moment_assay = NULL, plate_index = 1L, sampling_rate = NULL, ... )
pe |
A PhysioExperiment object. |
force_assay |
Assay name containing force data with 3 columns
(X, Y, Z). If not present, the function tries |
moment_assay |
Optional assay name containing moments with 3 columns.
If not present, the function tries |
plate_index |
Which plate to analyze when components are provided as separate assays with multiple force plates. Accepts:
|
sampling_rate |
Optional sampling rate in Hz. If |
... |
Additional arguments passed to |
A forceplate_analysis object (single plate) or
forceplate_analysis_multi (when plate_index = "all").
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
analyzeForcePlate() for matrix-based force plate analysis,
print.forceplate_analysis() for displaying results.
## Not run: pe <- readC3D("trial.c3d", include_analog = TRUE) out <- analyzeForcePlatePE(pe) ## End(Not run)## Not run: pe <- readC3D("trial.c3d", include_analog = TRUE) out <- analyzeForcePlatePE(pe) ## End(Not run)
Performs a compact quality and metadata checklist so beginners can quickly identify missing requirements before running kinematics or kinetics.
assessMoCapReadiness( pe, required_assays = c("position_x", "position_y", "position_z"), min_frames = 100, min_markers = 5, min_sampling_rate = 50, max_missing_rate = 0.05 )assessMoCapReadiness( pe, required_assays = c("position_x", "position_y", "position_z"), min_frames = 100, min_markers = 5, min_sampling_rate = 50, max_missing_rate = 0.05 )
pe |
A |
required_assays |
Character vector of required assay names. |
min_frames |
Minimum recommended number of frames. |
min_markers |
Minimum recommended number of markers/channels. |
min_sampling_rate |
Minimum recommended sampling rate (Hz). |
max_missing_rate |
Maximum allowed missing-value rate per required assay. |
An S3 object of class "mocap_readiness" with score, grade, checks,
and summary metrics.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
print.mocap_readiness() for formatted display of readiness results,
quickStartMoCap() for complete getting-started workflow,
demoMoCapData() for generating demo data.
demo <- demoMoCapData(seed = 1) report <- assessMoCapReadiness(demo$mocap) reportdemo <- demoMoCapData(seed = 1) report <- assessMoCapReadiness(demo$mocap) report
Loads an OpenSim session and performs batch movement analysis using a TaskSchema for event detection and normalization.
batch_analyze_opensim( session_dir, schema, signal_mapping = list(), trials = NULL, normalize_method = NULL, ... )batch_analyze_opensim( session_dir, schema, signal_mapping = list(), trials = NULL, normalize_method = NULL, ... )
session_dir |
Directory containing OpenSim output files, or an opensim_session/opensim_workflow object from signalIO |
schema |
A TaskSchema object defining events and phases |
signal_mapping |
Named list mapping schema signal names to actual channel names in the data |
trials |
Character vector of trial names to analyze. If NULL, analyzes all. |
normalize_method |
Override schema normalization method |
... |
Additional arguments passed to normalizeMovement |
A list containing:
trials: List of normalized trial data
events: List of detected events per trial
phases: List of phase timing per trial
summary: Summary statistics across trials
Delp SL, Anderson FC, Arnold AS, Loan P, Habib A, John CT, Guendelman E, Thelen DG (2007). "OpenSim: Open-Source Software to Create and Analyze Dynamic Simulations of Movement." IEEE Transactions on Biomedical Engineering, 54(11), 1940-1950.
create_schema_from_opensim() for creating task schemas from
OpenSim models.
## Not run: library(signalIO) # Load session and analyze results <- batch_analyze_opensim( "subject01/", schema = schema_gait, signal_mapping = list(vGRF = "ground_force_vy_r") ) # Access normalized trials trial1 <- results$trials[[1]] # View summary print(results$summary) ## End(Not run)## Not run: library(signalIO) # Load session and analyze results <- batch_analyze_opensim( "subject01/", schema = schema_gait, signal_mapping = list(vGRF = "ground_force_vy_r") ) # Access normalized trials trial1 <- results$trials[[1]] # View summary print(results$summary) ## End(Not run)
Normalizes multiple trials and returns them in a consistent format.
batchNormalize( trials, method = "cycle", norm_length = 101L, schema = NULL, ... )batchNormalize( trials, method = "cycle", norm_length = 101L, schema = NULL, ... )
trials |
List of matrices or PhysioExperiment objects |
method |
Normalization method |
norm_length |
Target length |
schema |
Optional TaskSchema |
... |
Additional arguments |
3D array (time x channels x trials) or list
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
normalizeMovement(), normalizedTimeAxis(), combineTrials()
Computes per-variable metrics (RMSE, MAE, bias, correlation, R2, ICC, Bland-Altman LoA width) between prediction and reference data.
benchmarkAgreement( prediction, reference, trial_id = "trial_1", thresholds = defaultBenchmarkThresholds("balanced"), alignment = c("truncate", "resample") )benchmarkAgreement( prediction, reference, trial_id = "trial_1", thresholds = defaultBenchmarkThresholds("balanced"), alignment = c("truncate", "resample") )
prediction |
Numeric vector/matrix/data.frame. |
reference |
Numeric vector/matrix/data.frame. |
trial_id |
Label used in output rows. |
thresholds |
Optional named list from |
alignment |
Alignment mode when sample lengths differ:
|
Object of class "benchmark_agreement" with metrics, summary,
and thresholds.
Shrout PE, Fleiss JL (1979). "Intraclass Correlations: Uses in Assessing Rater Reliability." Psychological Bulletin, 86(2), 420-428.
Bland JM, Altman DG (1986). "Statistical Methods for Assessing Agreement Between Two Methods of Clinical Measurement." Lancet, 327(8476), 307-310.
defaultBenchmarkThresholds() for threshold configuration,
runBenchmarkSuite() for multi-trial benchmarking,
blandAltman() for Bland-Altman agreement analysis.
ref <- data.frame(a = sin(seq(0, 1, length.out = 100))) pred <- ref + rnorm(100, sd = 0.01) out <- benchmarkAgreement(pred, ref, trial_id = "demo") out$summaryref <- data.frame(a = sin(seq(0, 1, length.out = 100))) pred <- ref + rnorm(100, sd = 0.01) out <- benchmarkAgreement(pred, ref, trial_id = "demo") out$summary
Produces a template data.frame describing benchmark trials and file paths.
benchmarkManifestTemplate(n = 1L)benchmarkManifestTemplate(n = 1L)
n |
Number of template rows to create. |
A data.frame manifest template.
Bland JM, Altman DG (1986). "Statistical Methods for Assessing Agreement Between Two Methods of Clinical Measurement." Lancet, 327(8476), 307-310.
writeBenchmarkManifest() for writing the template to CSV,
validateBenchmarkManifest() for validating manifest structure.
benchmarkManifestTemplate(2)benchmarkManifestTemplate(2)
Performs a Bland-Altman analysis comparing two measurement methods or two time points. Computes the bias (mean difference), limits of agreement, and confidence interval for the bias.
blandAltman(x, y, confidence = 0.95)blandAltman(x, y, confidence = 0.95)
x |
Numeric vector of measurements from method/time 1. |
y |
Numeric vector of measurements from method/time 2. |
confidence |
Numeric; confidence level for limits of agreement (default 0.95). |
The Bland-Altman method assesses agreement between two measurements by plotting their difference against their mean. The limits of agreement are:
where is the mean difference (bias) and is the
SD of differences.
A list with components:
Mean difference (x - y)
Lower limit of agreement
Upper limit of agreement
Standard deviation of differences
Two-element vector with lower and upper CI for the bias
Bland JM, Altman DG (1986). Statistical methods for assessing agreement between two methods of clinical measurement. Lancet, 327(8476), 307-310.
icc() for intraclass correlation reliability analysis,
benchmarkAgreement() for benchmark validation agreement metrics.
set.seed(42) method1 <- rnorm(30, mean = 50, sd = 10) method2 <- method1 + rnorm(30, mean = 0, sd = 3) result <- blandAltman(method1, method2) result$bias result$lower_loa result$upper_loaset.seed(42) method1 <- rnorm(30, mean = 50, sd = 10) method2 <- method1 + rnorm(30, mean = 0, sd = 3) result <- blandAltman(method1, method2) result$bias result$lower_loa result$upper_loa
Designs a Butterworth IIR filter and applies it using zero-phase filtering (forward-backward) to avoid phase distortion.
butterworthFilter( x, cutoff, sampling_rate, type = c("lowpass", "highpass", "bandpass", "bandstop"), order = 4 )butterworthFilter( x, cutoff, sampling_rate, type = c("lowpass", "highpass", "bandpass", "bandstop"), order = 4 )
x |
A numeric vector or matrix (time x channels). |
cutoff |
Cutoff frequency in Hz. A single value for "lowpass" or
"highpass"; a length-2 vector |
sampling_rate |
Sampling rate in Hz. |
type |
Filter type: "lowpass", "highpass", "bandpass", or "bandstop". |
order |
Filter order (default: 4). |
Requires the signal package. NAs in the input are temporarily interpolated before filtering and restored afterward.
Filtered data with the same dimensions as x.
Butterworth S (1930). "On the Theory of Filter Amplifiers." Wireless Engineer, 7, 536-541.
filterSignals() for filtering PhysioExperiment objects,
savgolFilter() for Savitzky-Golay polynomial smoothing.
## Not run: # Filter a single vector x <- sin(2 * pi * 5 * seq(0, 1, length.out = 1000)) + sin(2 * pi * 50 * seq(0, 1, length.out = 1000)) x_filt <- butterworthFilter(x, cutoff = 20, sampling_rate = 1000, type = "lowpass") ## End(Not run)## Not run: # Filter a single vector x <- sin(2 * pi * 5 * seq(0, 1, length.out = 1000)) + sin(2 * pi * 50 * seq(0, 1, length.out = 1000)) x_filt <- butterworthFilter(x, cutoff = 20, sampling_rate = 1000, type = "lowpass") ## End(Not run)
Computes the whole-body center of mass (COM) at each time frame from 3D (or 2D) marker position data and body segment inertial parameters.
calculateCOM(pe, body_mass, skeleton = NULL, bsip = NULL, marker_map = NULL)calculateCOM(pe, body_mass, skeleton = NULL, bsip = NULL, marker_map = NULL)
pe |
A |
body_mass |
Numeric scalar, body mass in kilograms. Must be positive. |
skeleton |
Optional |
bsip |
Optional data.frame of body segment parameters (as
returned by |
marker_map |
Optional named list mapping each segment to its
proximal and distal marker names. Each element should be a character
vector of length 2: |
The algorithm proceeds as follows:
For each body segment, compute the segment COM position as:
where is the COM proximal fraction from the BSIP table.
Compute the whole-body COM as the mass-weighted average of all segment COMs:
where is the segment mass and
is the total body mass.
A PhysioExperiment object with additional assays com_x,
com_y, and (if 3D) com_z. Each assay is a single-column matrix
with column name "COM" and the same number of rows as the input.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
Zatsiorsky VM (2002). "Kinetics of Human Motion." Human Kinetics.
segmentParameters() for body segment inertial parameters,
calculateSegmentCOM() for individual segment center of mass,
symmetryIndex() for bilateral symmetry assessment.
## Not run: pe <- readTRC("markers.trc") result <- calculateCOM(pe, body_mass = 75) com_x <- SummarizedExperiment::assay(result, "com_x") ## End(Not run)## Not run: pe <- readTRC("markers.trc") result <- calculateCOM(pe, body_mass = 75) com_x <- SummarizedExperiment::assay(result, "com_x") ## End(Not run)
Computes COP coordinates from force and moment components using standard force-plate equations (assuming a vertical Z axis).
calculateCOP(forces, moments, origin = c(0, 0, 0), min_vertical_force = 20)calculateCOP(forces, moments, origin = c(0, 0, 0), min_vertical_force = 20)
forces |
Matrix/data.frame with at least three columns for force components (X, Y, Z). |
moments |
Matrix/data.frame with at least three columns for moment components (X, Y, Z). |
origin |
Numeric length-3 vector with force-plate origin |
min_vertical_force |
Minimum absolute vertical force required to compute
COP (samples below this threshold are set to |
A data.frame with columns cop_x, cop_y, cop_z,
free_moment, and vertical_force.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
analyzeForcePlate() for comprehensive force plate analysis,
calculateCOM() for whole-body center of mass computation.
f <- cbind(Fx = rep(0, 10), Fy = rep(0, 10), Fz = rep(1000, 10)) m <- cbind(Mx = rep(100, 10), My = rep(-200, 10), Mz = rep(0, 10)) cop <- calculateCOP(f, m)f <- cbind(Fx = rep(0, 10), Fy = rep(0, 10), Fz = rep(1000, 10)) m <- cbind(Mx = rep(100, 10), My = rep(-200, 10), Mz = rep(0, 10)) cop <- calculateCOP(f, m)
Computes temporal and spatial gait parameters from detected gait events. Temporal parameters include stride time, step time, stance/swing durations, double support time, and cadence. Spatial parameters (step length, stride length, step width, walking speed) require position data in the PhysioExperiment assays.
calculateGaitParameters( pe, events, body_height = NULL, side = c("right", "left", "both") )calculateGaitParameters( pe, events, body_height = NULL, side = c("right", "left", "both") )
pe |
A PhysioExperiment object with position data (assays named
|
events |
A |
body_height |
Numeric; body height in metres for normalized parameters (optional). Currently reserved for future use. |
side |
Character; which side(s) to compute. One of |
Events must use one of the recognised naming conventions:
"HS_R", "HS_L" / "TO_R", "TO_L"
"right_heel_strike", "left_heel_strike" /
"right_toe_off", "left_toe_off"
The events data.frame may use either event_name or
event for the event name column, and either time (in sample
indices) or time_sec (in seconds) for timing.
An S3 object of class "gait_parameters" inheriting from
data.frame. Each row is one stride cycle. Columns include:
Side label ("right" or "left")
Stride number (sequential within side)
Time between consecutive ipsilateral heel strikes (s)
Time from contralateral to ipsilateral heel strike (s)
Heel strike to toe off on the same side (s)
Toe off to next heel strike on the same side (s)
Stance as percentage of stride time
Swing as percentage of stride time
Time with both feet on the ground (s)
Steps per minute (60 / step_time)
AP distance between feet at consecutive heel strikes (m)
AP distance between ipsilateral heel strikes (m)
ML distance between feet at heel strike (m)
Stride length / stride time (m/s)
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
Perry J, Burnfield JM (2010). "Gait Analysis: Normal and Pathological Function." 2nd ed. SLACK Incorporated.
calculateStepSymmetry() for symmetry analysis of gait parameters,
summarizeGaitParameters() for descriptive statistics of gait data,
plotGaitCycle() for gait cycle visualization.
# See test file for worked examples with synthetic data# See test file for worked examples with synthetic data
Computes joint angles from 3D (or 2D) position data stored in a PhysioExperiment object. Each joint is defined by three points: proximal, joint (vertex), and distal. The angle at the vertex is computed using the specified convention.
calculateJointAngles(pe, joints, convention = c("3point"), degrees = TRUE)calculateJointAngles(pe, joints, convention = c("3point"), degrees = TRUE)
pe |
A |
joints |
A named list of joint definitions. Each element is a
list with components |
convention |
Character string specifying the angle convention.
Currently only |
degrees |
Logical. If |
For the "3point" convention, the angle is computed at the vertex
(joint point) between the proximal-to-joint and distal-to-joint
direction vectors:
where and
.
The result is clamped to (or in
degrees). If any of the three points contain NA for a given frame,
the angle for that frame is NA.
A PhysioExperiment object with an additional "joint_angles"
assay containing the computed angles (n_frames x n_joints). The
column names of the assay correspond to the names of the joints
list. The colData is updated with joint angle metadata.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
Grood ES, Suntay WJ (1983). "A joint coordinate system for the clinical description of three-dimensional motions: application to the knee." Journal of Biomechanical Engineering, 105(2), 136-144.
vectorAngle(), quaternionToEuler(), eulerToQuaternion()
## Not run: pe <- readTRC("markers.trc") joints <- list( right_elbow = list( proximal = "RShoulder", joint = "RElbow", distal = "RWrist" ), right_knee = list( proximal = "RHip", joint = "RKnee", distal = "RAnkle" ) ) pe_angles <- calculateJointAngles(pe, joints) SummarizedExperiment::assay(pe_angles, "joint_angles") ## End(Not run)## Not run: pe <- readTRC("markers.trc") joints <- list( right_elbow = list( proximal = "RShoulder", joint = "RElbow", distal = "RWrist" ), right_knee = list( proximal = "RHip", joint = "RKnee", distal = "RAnkle" ) ) pe_angles <- calculateJointAngles(pe, joints) SummarizedExperiment::assay(pe_angles, "joint_angles") ## End(Not run)
Lower-level function that computes the center of mass for individual body segments from marker position data.
calculateSegmentCOM(pe, proximal_markers, distal_markers, com_fractions)calculateSegmentCOM(pe, proximal_markers, distal_markers, com_fractions)
pe |
A |
proximal_markers |
Character vector of proximal marker names, one per segment. |
distal_markers |
Character vector of distal marker names,
one per segment (same length as |
com_fractions |
Numeric vector of COM proximal fractions (0-1),
one per segment (same length as |
A named list of matrices, one per segment. Each matrix has
dimensions (n_frames x 2) for 2D data or (n_frames x 3) for 3D
data, with columns named "x", "y", and (optionally) "z".
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
calculateCOM() for whole-body center of mass,
segmentParameters() for body segment inertial parameters.
## Not run: pe <- readTRC("markers.trc") seg_coms <- calculateSegmentCOM( pe, proximal_markers = c("RHip", "LHip"), distal_markers = c("RKnee", "LKnee"), com_fractions = c(0.4095, 0.4095) ) ## End(Not run)## Not run: pe <- readTRC("markers.trc") seg_coms <- calculateSegmentCOM( pe, proximal_markers = c("RHip", "LHip"), distal_markers = c("RKnee", "LKnee"), com_fractions = c(0.4095, 0.4095) ) ## End(Not run)
Computes symmetry metrics comparing left and right sides. Includes the Robinson Symmetry Index and the left/right ratio for each parameter.
calculateStepSymmetry(gait_params)calculateStepSymmetry(gait_params)
gait_params |
A |
A Symmetry Index (SI) of 0 indicates perfect symmetry. Values above 10 are generally considered clinically asymmetric.
A data.frame with columns:
Name of the gait parameter
Mean value for the left side
Mean value for the right side
Robinson Symmetry Index: |L - R| / (0.5 * (L + R)) * 100
Left / Right ratio
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
calculateGaitParameters() for computing gait temporal-spatial parameters,
symmetryIndex() for general symmetry index computation,
plotSymmetry() for symmetry visualization.
# See test file for worked examples# See test file for worked examples
Estimates accelerometer and gyroscope biases from data recorded during a static (motionless) period. The accelerometer bias is computed relative to the expected gravity vector, and the gyroscope bias is the mean angular velocity during the static period.
calibrateIMU(accel_static, gyro_static)calibrateIMU(accel_static, gyro_static)
accel_static |
Numeric matrix (n x 3) of accelerometer readings during the static period, in m/s^2. |
gyro_static |
Numeric matrix (n x 3) of gyroscope readings during the static period, in rad/s. |
The function assumes the sensor is stationary. The accelerometer bias is estimated by subtracting the expected gravity contribution from the mean accelerometer reading. Gravity direction is inferred from the mean acceleration direction, and its expected magnitude is 9.81 m/s^2.
The gyroscope bias is simply the mean of the gyroscope readings during the static period (should be near zero for a stationary sensor).
A list with components:
Numeric vector of length 3. Mean accelerometer bias for each axis. For a perfectly calibrated sensor at rest, this would be (0, 0, 0) after accounting for gravity.
Numeric vector of length 3. Mean gyroscope bias for each axis (rad/s). A stationary sensor should read zero; any offset is the bias.
Madgwick SOH, Harrison AJL, Vaidyanathan R (2011). "Estimation of IMU and MARG orientation using a gradient descent algorithm." IEEE International Conference on Rehabilitation Robotics.
estimateOrientation(), removeGravity()
# Simulate static IMU data with known biases n <- 500 accel_bias_true <- c(0.05, -0.03, 0.02) gyro_bias_true <- c(0.001, -0.002, 0.0015) accel <- matrix(rep(c(0, 0, -9.81), each = n), ncol = 3) + matrix(rep(accel_bias_true, each = n), ncol = 3) gyro <- matrix(rep(gyro_bias_true, each = n), ncol = 3) cal <- calibrateIMU(accel, gyro)# Simulate static IMU data with known biases n <- 500 accel_bias_true <- c(0.05, -0.03, 0.02) gyro_bias_true <- c(0.001, -0.002, 0.0015) accel <- matrix(rep(c(0, 0, -9.81), each = n), ncol = 3) + matrix(rep(accel_bias_true, each = n), ncol = 3) gyro <- matrix(rep(gyro_bias_true, each = n), ncol = 3) cal <- calibrateIMU(accel, gyro)
Computes Cohen's d effect size for comparing two groups or conditions, with confidence intervals and qualitative interpretation.
cohensD(x, y, paired = FALSE, pooled = TRUE)cohensD(x, y, paired = FALSE, pooled = TRUE)
x |
Numeric vector for group 1 (or condition 1 if paired). |
y |
Numeric vector for group 2 (or condition 2 if paired). |
paired |
Logical; if TRUE, computes effect size for paired data using the SD of differences as the denominator. |
pooled |
Logical; if TRUE (default), uses pooled SD as denominator.
If FALSE, uses the SD of |
For independent groups with pooled = TRUE, the pooled SD is:
For paired data, the denominator is the SD of the within-pair differences.
Interpretation thresholds follow Cohen (1988):
|d| < 0.2: negligible
0.2 <= |d| < 0.5: small
0.5 <= |d| < 0.8: medium
|d| >= 0.8: large
A list with components:
Cohen's d value
Lower bound of 95 percent confidence interval
Upper bound of 95 percent confidence interval
Qualitative label: "negligible", "small", "medium", or "large"
Cohen J (1988). Statistical Power Analysis for the Behavioral Sciences. Lawrence Erlbaum Associates.
etaSquared() for ANOVA-based effect sizes,
plotEffectSizeForest() for forest plot visualization of effect sizes.
set.seed(42) x <- rnorm(30, mean = 10, sd = 2) y <- rnorm(30, mean = 8, sd = 2) result <- cohensD(x, y) result$d result$interpretationset.seed(42) x <- rnorm(30, mean = 10, sd = 2) y <- rnorm(30, mean = 8, sd = 2) result <- cohensD(x, y) result$d result$interpretation
Combine multiple trials with segmented phases
combineTrials(..., labels = NULL)combineTrials(..., labels = NULL)
... |
segmented_phases objects to combine |
labels |
Optional labels for each trial |
A multi_trial_phases object
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
segmentPhases(), batchNormalize(), normalizeMovement()
Computes acceleration (second derivative) from position or velocity assays. If velocity assays already exist, differentiates those (first derivative of velocity). Otherwise, computes the second derivative of position directly.
computeAcceleration( pe, assay_names = NULL, method = "central", sampling_rate = NULL )computeAcceleration( pe, assay_names = NULL, method = "central", sampling_rate = NULL )
pe |
A PhysioExperiment object. |
assay_names |
Character vector of assay names to differentiate. If NULL (default), auto-detects velocity_x/y/z (preferred) or position_x/y/z assays. |
method |
Finite difference method: "central" (default), "forward", or "backward". |
sampling_rate |
Sampling rate in Hz. If NULL (default), uses
|
PhysioExperiment with new accel_x, accel_y, accel_z assays added.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
computeVelocity() for first-order derivatives,
computeJerk() for third-order derivatives,
differentiate() for general-purpose numerical differentiation.
## Not run: pe <- make_mocap_markers(n_time = 100, n_markers = 4, sr = 120) pe <- computeAcceleration(pe) ## End(Not run)## Not run: pe <- make_mocap_markers(n_time = 100, n_markers = 4, sr = 120) pe <- computeAcceleration(pe) ## End(Not run)
Integrates vertical force over detected stance phases using trapezoidal integration.
computeImpulse( force, sampling_rate, threshold = 20, subtract_threshold = FALSE )computeImpulse( force, sampling_rate, threshold = 20, subtract_threshold = FALSE )
force |
Numeric vector or matrix of vertical force values. |
sampling_rate |
Sampling rate in Hz. |
threshold |
Contact threshold in force units. |
subtract_threshold |
Logical; if |
For vector input: data.frame with one row per stance and columns
including impulse (force*time units).
For matrix input: same structure plus channel.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
analyzeForcePlate() for comprehensive force plate analysis,
computeLoadingRate() for loading rate computation.
grf <- c(rep(0, 50), rep(600, 100), rep(0, 50)) computeImpulse(grf, sampling_rate = 1000)grf <- c(rep(0, 50), rep(600, 100), rep(0, 50)) computeImpulse(grf, sampling_rate = 1000)
Computes jerk (third derivative of position) from position assays.
computeJerk(pe, method = "central", sampling_rate = NULL)computeJerk(pe, method = "central", sampling_rate = NULL)
pe |
A PhysioExperiment object containing position assays. |
method |
Finite difference method: "central" (default), "forward", or "backward". |
sampling_rate |
Sampling rate in Hz. If NULL (default), uses
|
PhysioExperiment with new jerk_x, jerk_y, jerk_z assays added.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
computeAcceleration() for second-order derivatives,
computeVelocity() for first-order derivatives,
differentiate() for general-purpose numerical differentiation.
## Not run: pe <- make_mocap_markers(n_time = 100, n_markers = 4, sr = 120) pe <- computeJerk(pe) ## End(Not run)## Not run: pe <- make_mocap_markers(n_time = 100, n_markers = 4, sr = 120) pe <- computeJerk(pe) ## End(Not run)
Compute joint power from moment and angular velocity
computeJointPower(moment, angular_velocity)computeJointPower(moment, angular_velocity)
moment |
Numeric vector of joint moment values. |
angular_velocity |
Numeric vector of joint angular velocity in rad/s. |
Numeric vector of joint power (W).
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
inverseDynamics2D() for computing joint moments in 2D,
inverseDynamics3D() for computing joint moments in 3D.
computeJointPower(c(10, 12, 8), c(2, 1.5, 1))computeJointPower(c(10, 12, 8), c(2, 1.5, 1))
Detects stance phases from a vertical GRF signal and computes loading rate from initial contact to peak force for each stance.
computeLoadingRate( vgrf, sampling_rate, threshold = 20, method = c("instantaneous", "average") )computeLoadingRate( vgrf, sampling_rate, threshold = 20, method = c("instantaneous", "average") )
vgrf |
Numeric vector or matrix of vertical GRF values. |
sampling_rate |
Sampling rate in Hz. |
threshold |
Contact threshold in force units. |
method |
Loading-rate method: |
For vector input: a data.frame with one row per stance.
For matrix input: same data.frame with an added channel column.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
analyzeForcePlate() for comprehensive force plate analysis,
computeImpulse() for impulse computation.
grf <- c(rep(0, 100), seq(0, 800, length.out = 150), seq(800, 0, length.out = 150), rep(0, 100)) computeLoadingRate(grf, sampling_rate = 1000)grf <- c(rep(0, 100), seq(0, 800, length.out = 150), seq(800, 0, length.out = 150), rep(0, 100)) computeLoadingRate(grf, sampling_rate = 1000)
Compute moving RMS envelope of EMG
computeRMSEnvelope(x, window_samples = 50L, center = TRUE)computeRMSEnvelope(x, window_samples = 50L, center = TRUE)
x |
Numeric vector or matrix (time x channels). |
window_samples |
Window length in samples. |
center |
Logical; if |
RMS envelope with the same dimensions as x.
Merletti R, Parker PA (2004). "Electromyography: Physiology, Engineering, and Non-Invasive Applications." IEEE Press/Wiley.
rectifyEMG() for signal rectification,
normalizeEMG() for MVC or peak normalization,
processEMG() for complete EMG processing pipeline.
set.seed(1) sig <- rnorm(1000) env <- computeRMSEnvelope(sig, window_samples = 50)set.seed(1) sig <- rnorm(1000) env <- computeRMSEnvelope(sig, window_samples = 50)
Computes the magnitude of the velocity vector (Euclidean norm) at each time point for each marker/keypoint.
computeSpeed(pe, velocity_assays = NULL)computeSpeed(pe, velocity_assays = NULL)
pe |
A PhysioExperiment object containing velocity assays. |
velocity_assays |
Character vector of velocity assay names. If NULL (default), auto-detects velocity_x/y/z or velocity_kp_x/y. |
PhysioExperiment with a new "speed" assay containing the scalar
speed: sqrt(vx^2 + vy^2 + vz^2).
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
computeVelocity() for computing velocity components,
computeAcceleration() for computing acceleration.
## Not run: pe <- make_mocap_markers(n_time = 100, n_markers = 4, sr = 120) pe <- computeVelocity(pe) pe <- computeSpeed(pe) ## End(Not run)## Not run: pe <- make_mocap_markers(n_time = 100, n_markers = 4, sr = 120) pe <- computeVelocity(pe) pe <- computeSpeed(pe) ## End(Not run)
Computes velocity (first derivative) from position assays in a PhysioExperiment object using finite differences.
computeVelocity( pe, assay_names = NULL, method = "central", sampling_rate = NULL )computeVelocity( pe, assay_names = NULL, method = "central", sampling_rate = NULL )
pe |
A PhysioExperiment object containing position assays. |
assay_names |
Character vector of assay names to differentiate. If NULL (default), auto-detects position_x/y/z or keypoint_x/y assays. |
method |
Finite difference method: "central" (default), "forward", or "backward". |
sampling_rate |
Sampling rate in Hz. If NULL (default), uses
|
PhysioExperiment with new velocity assays added. For 3D marker data, assays named velocity_x, velocity_y, velocity_z. For 2D keypoint data, assays named velocity_kp_x, velocity_kp_y.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
computeAcceleration() for second-order derivatives,
computeSpeed() for scalar speed from velocity components,
differentiate() for general-purpose numerical differentiation.
## Not run: pe <- make_mocap_markers(n_time = 100, n_markers = 4, sr = 120) pe <- computeVelocity(pe) # velocity_x, velocity_y, velocity_z assays are now present ## End(Not run)## Not run: pe <- make_mocap_markers(n_time = 100, n_markers = 4, sr = 120) pe <- computeVelocity(pe) # velocity_x, velocity_y, velocity_z assays are now present ## End(Not run)
Repairs marker trajectories by swapping the data columns of detected swap pairs from the swap frame onward.
correctSwaps(pe, swaps, assay_prefix = "position", min_confidence = 0.5)correctSwaps(pe, swaps, assay_prefix = "position", min_confidence = 0.5)
pe |
A PhysioExperiment with position assays. |
swaps |
A |
assay_prefix |
Prefix for position assay names. Default |
min_confidence |
Minimum confidence threshold for applying a correction. Swaps below this threshold are skipped. Default 0.5. |
A PhysioExperiment with corrected position assays.
## Not run: swaps <- detectSwaps(pe) pe_fixed <- correctSwaps(pe, swaps, min_confidence = 0.3) ## End(Not run)## Not run: swaps <- detectSwaps(pe) pe_fixed <- correctSwaps(pe, swaps, min_confidence = 0.3) ## End(Not run)
Generates a TaskSchema based on an OpenSim model's markers and available
signal channels. This function creates appropriate event definitions that
can be used with detectEvents() for automatic event detection.
create_schema_from_opensim( model, task_type = c("gait", "running", "jump", "generic"), available_signals = NULL, side = "right" )create_schema_from_opensim( model, task_type = c("gait", "running", "jump", "generic"), available_signals = NULL, side = "right" )
model |
One of:
|
task_type |
Type of movement task: "gait", "running", "jump", "generic" |
available_signals |
Character vector of signal names available in the data (e.g., from IK, ID, or GRF data) |
side |
Character, which side to base events on: "right", "left", or "both" |
This function analyzes the model's markers and the available signals to generate an appropriate TaskSchema. For gait analysis, it prefers GRF-based detection if available, falling back to marker-based or kinematic detection.
A TaskSchema object configured for the specified task type
Delp SL, Anderson FC, Arnold AS, Loan P, Habib A, John CT, Guendelman E, Thelen DG (2007). "OpenSim: Open-Source Software to Create and Analyze Dynamic Simulations of Movement." IEEE Transactions on Biomedical Engineering, 54(11), 1940-1950.
batch_analyze_opensim() for batch processing of OpenSim sessions,
detectEvents() for event detection using task schemas.
## Not run: library(signalIO) # Load OpenSim model model <- read_osim("gait2354.osim") # Load IK results ik <- read_mot("ik_results.mot") ik_channels <- rownames(ik) # Create gait schema with available channels schema <- create_schema_from_opensim(model, "gait", ik_channels) print(schema) # Use schema for event detection events <- detectEvents(data, schema) ## End(Not run)## Not run: library(signalIO) # Load OpenSim model model <- read_osim("gait2354.osim") # Load IK results ik <- read_mot("ik_results.mot") ik_channels <- rownames(ik) # Create gait schema with available channels schema <- create_schema_from_opensim(model, "gait", ik_channels) print(schema) # Use schema for event detection events <- detectEvents(data, schema) ## End(Not run)
Generates prediction/reference CSV pairs and a manifest for dry-run validation benchmarking when external data are not yet available.
createBenchmarkExample( output_dir = tempdir(), n_trials = 3L, n_samples = 300L, variables = c("hip_angle", "knee_angle", "ankle_angle"), noise_sd = 0.02, seed = 1 )createBenchmarkExample( output_dir = tempdir(), n_trials = 3L, n_samples = 300L, variables = c("hip_angle", "knee_angle", "ankle_angle"), noise_sd = 0.02, seed = 1 )
output_dir |
Output directory where files are written. |
n_trials |
Number of synthetic trials. |
n_samples |
Samples per trial. |
variables |
Character vector of variable names. |
noise_sd |
Prediction noise SD relative to the generated reference. |
seed |
Random seed. |
A list with manifest, manifest_path, and data_dir.
Bland JM, Altman DG (1986). "Statistical Methods for Assessing Agreement Between Two Methods of Clinical Measurement." Lancet, 327(8476), 307-310.
runBenchmarkSuite() for running the benchmark suite,
benchmarkManifestTemplate() for creating empty manifest templates.
ex <- createBenchmarkExample(n_trials = 2, seed = 1) runBenchmarkSuite(ex$manifest, data_dir = ex$data_dir)ex <- createBenchmarkExample(n_trials = 2, seed = 1) runBenchmarkSuite(ex$manifest, data_dir = ex$data_dir)
Returns a named list of threshold values used by benchmark pass/fail logic.
defaultBenchmarkThresholds(profile = c("balanced", "strict", "lenient"))defaultBenchmarkThresholds(profile = c("balanced", "strict", "lenient"))
profile |
Threshold profile: |
Named list with threshold fields:
rmse_max, mae_max, bias_abs_max, cor_min, icc_min.
Shrout PE, Fleiss JL (1979). "Intraclass Correlations: Uses in Assessing Rater Reliability." Psychological Bulletin, 86(2), 420-428.
benchmarkAgreement() for computing agreement metrics,
runBenchmarkSuite() for running a full benchmark suite.
defaultBenchmarkThresholds()defaultBenchmarkThresholds()
Factory function that returns a SkeletonModel for a well-known
pose estimation or motion capture marker set.
define_skeleton(model_name)define_skeleton(model_name)
model_name |
Character string. One of:
|
A SkeletonModel object.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
SkeletonModel(), get_bone_connections(), get_limb_pairs()
sk <- define_skeleton("BODY_25") print(sk) sk_coco <- define_skeleton("COCO") get_bone_connections(sk_coco)sk <- define_skeleton("BODY_25") print(sk) sk_coco <- define_skeleton("COCO") get_bone_connections(sk_coco)
Generates synthetic motion capture, force, and EMG data so first-time users can run package workflows without external files.
demoMoCapData( n_frames = 300, sampling_rate = 120, n_markers = 8, emg_sampling_rate = 1000, seed = 123 )demoMoCapData( n_frames = 300, sampling_rate = 120, n_markers = 8, emg_sampling_rate = 1000, seed = 123 )
n_frames |
Number of MoCap frames to generate. |
sampling_rate |
MoCap sampling rate in Hz. |
n_markers |
Number of markers in the synthetic marker set. |
emg_sampling_rate |
EMG sampling rate in Hz. |
seed |
Optional random seed for reproducibility. Set to |
A named list with:
A PhysioExperiment with position_x, position_y,
position_z assays.
Numeric vector of synthetic vertical GRF.
Matrix with force_x, force_y, force_z columns.
Data frame with 2D joint-center coordinates for ankle, knee, and hip.
Data frame with ankle/knee/hip joint angles (radians).
Matrix of synthetic EMG channels.
MoCap sampling rate (Hz).
EMG sampling rate (Hz).
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
quickStartMoCap() for a complete getting-started workflow,
assessMoCapReadiness() for data quality assessment.
demo <- demoMoCapData(seed = 1) demo$mocap head(demo$joints)demo <- demoMoCapData(seed = 1) demo$mocap head(demo$joints)
Automatically detects events defined in a TaskSchema based on signal data.
detectEvents( x, schema, signals = NULL, method = c("auto", "manual", "hybrid"), sampling_rate = NULL, ... )detectEvents( x, schema, signals = NULL, method = c("auto", "manual", "hybrid"), sampling_rate = NULL, ... )
x |
PhysioExperiment object or matrix (time x channels) |
schema |
TaskSchema object defining events to detect |
signals |
Named list of signal vectors for detection. If NULL and x is
a PhysioExperiment, signals are extracted from column names. If x is a
matrix with named columns, signals are auto-created from those names;
otherwise provide |
method |
Detection approach:
|
sampling_rate |
Sampling rate in Hz. Required if x is a matrix. |
... |
Additional arguments passed to detection methods |
A data.frame with columns:
event - Event name
label - Human-readable label
index - Sample index of event
time - Time in seconds
percent - Percent of movement (if applicable)
method - Detection method used
confidence - Detection confidence (0-1)
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
manualEvents(), segmentPhases(), TaskSchema()
# Create synthetic gait data set.seed(123) n <- 1000 t <- seq(0, 1, length.out = n) vGRF <- c(rep(0, 100), sin(seq(0, pi, length.out = 500)) * 800, rep(0, 400)) vGRF <- vGRF + rnorm(n, 0, 10) signals <- list(vGRF = vGRF) events <- detectEvents(as.matrix(vGRF), schema_gait, signals = signals, sampling_rate = 1000)# Create synthetic gait data set.seed(123) n <- 1000 t <- seq(0, 1, length.out = n) vGRF <- c(rep(0, 100), sin(seq(0, pi, length.out = 500)) * 800, rep(0, 400)) vGRF <- vGRF + rnorm(n, 0, 10) signals <- list(vGRF = vGRF) events <- detectEvents(as.matrix(vGRF), schema_gait, signals = signals, sampling_rate = 1000)
Identifies threshold-based contact windows from vertical GRF signals.
detectForcePlateContacts(vgrf, threshold = 20, sampling_rate = NULL)detectForcePlateContacts(vgrf, threshold = 20, sampling_rate = NULL)
vgrf |
Numeric vector or matrix of vertical GRF (rows = time, columns = plates/channels). |
threshold |
Contact threshold in force units. |
sampling_rate |
Optional sampling rate in Hz. If provided, durations are returned in seconds. |
A data.frame with one row per detected contact and columns:
plate, stance, onset, offset, duration_samples, duration_s,
and peak_force.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
analyzeForcePlate() for comprehensive force plate analysis,
analyzeForcePlatePE() for PhysioExperiment-based analysis.
v <- cbind( fp1 = c(rep(0, 100), rep(500, 200), rep(0, 100)), fp2 = c(rep(0, 200), rep(700, 100), rep(0, 100)) ) detectForcePlateContacts(v, threshold = 20, sampling_rate = 1000)v <- cbind( fp1 = c(rep(0, 100), rep(500, 200), rep(0, 100)), fp2 = c(rep(0, 200), rep(700, 100), rep(0, 100)) ) detectForcePlateContacts(v, threshold = 20, sampling_rate = 1000)
Scans the specified assay of a PhysioExperiment object for contiguous runs of NA values and returns a data.frame describing each gap.
detectGaps(pe, assay_name = "position_x")detectGaps(pe, assay_name = "position_x")
pe |
A PhysioExperiment object |
assay_name |
Name of the assay to scan (default: "position_x") |
A data.frame with columns:
channel - Channel (column) name or index
start - Start index of the gap (1-based)
end - End index of the gap (1-based)
size - Number of consecutive NA values
Federolf PA (2013). "A novel approach to solve the 'missing marker problem' in marker-based motion analysis that does not require additional assumptions about the biodynamic model." Journal of Biomechanics, 46(13), 2173-2178.
reportGaps(), fillGaps(), fillGapsLinear()
pe <- PhysioCore::PhysioExperiment( assays = S4Vectors::SimpleList(position_x = matrix(c(1, NA, NA, 4), ncol = 1)), colData = S4Vectors::DataFrame(label = "M1", type = "marker"), samplingRate = 120 ) gaps <- detectGaps(pe, assay_name = "position_x")pe <- PhysioCore::PhysioExperiment( assays = S4Vectors::SimpleList(position_x = matrix(c(1, NA, NA, 4), ncol = 1)), colData = S4Vectors::DataFrame(label = "M1", type = "marker"), samplingRate = 120 ) gaps <- detectGaps(pe, assay_name = "position_x")
Identifies frames where two or more marker trajectories abruptly swap
positions, indicating a labelling error. Swaps are detected by velocity
spikes that exceed median + 5 * MAD and show a cross-over pattern
between marker pairs.
detectSwaps(pe, threshold = NULL, window = 5, assay_prefix = "position")detectSwaps(pe, threshold = NULL, window = 5, assay_prefix = "position")
pe |
A PhysioExperiment with position assays. |
threshold |
Velocity threshold for spike detection. If |
window |
Number of frames around a spike to check for cross-over patterns. Default 5. |
assay_prefix |
Prefix for position assay names. Default |
A data.frame with columns:
Frame index where the swap was detected.
Name or index of the first marker in the swap pair.
Name or index of the second marker.
Velocity of marker_a at the swap frame.
Velocity of marker_b at the swap frame.
Confidence score (0-1) based on how closely the cross-over distances match.
If no swaps are detected, an empty data.frame with the same columns is returned.
trackMarkers(), correctSwaps()
## Not run: pe <- readVenus3D("capture.csv") pe_tracked <- trackMarkers(pe) swaps <- detectSwaps(pe_tracked) if (nrow(swaps) > 0) { pe_fixed <- correctSwaps(pe_tracked, swaps) } ## End(Not run)## Not run: pe <- readVenus3D("capture.csv") pe_tracked <- trackMarkers(pe) swaps <- detectSwaps(pe_tracked) if (nrow(swaps) > 0) { pe_fixed <- correctSwaps(pe_tracked, swaps) } ## End(Not run)
Low-level function to compute numerical derivatives of arbitrary order using finite difference methods.
differentiate(x, dt, method = c("central", "forward", "backward"), order = 1L)differentiate(x, dt, method = c("central", "forward", "backward"), order = 1L)
x |
Numeric vector or matrix (time x channels). |
dt |
Time step between samples (1 / sampling_rate). |
method |
Difference method: "central", "forward", or "backward". |
order |
Derivative order: 1 (velocity), 2 (acceleration), or 3 (jerk). |
For method = "central" with order = 1:
For method = "central" with order = 2:
For higher orders, the derivative is computed by repeated application of the first-order formula.
Differentiated data with same dimensions as input. Boundary values where the stencil cannot be applied are set to NA.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
computeVelocity() for computing velocity from PhysioExperiment,
computeAcceleration() for second-order derivatives,
savgolFilter() for smoothed differentiation via Savitzky-Golay.
# Differentiate sin to get cos t <- seq(0, 2 * pi, length.out = 200) x <- sin(t) dx <- differentiate(x, dt = t[2] - t[1], method = "central", order = 1) # dx should approximate cos(t)# Differentiate sin to get cos t <- seq(0, 2 * pi, length.out = 200) x <- sin(t) dx <- differentiate(x, dt = t[2] - t[1], method = "central", order = 1) # dx should approximate cos(t)
Computes the average waveform using DTW Barycenter Averaging, which accounts for time warping in the averaging process.
dtwAverage(x, init = "medoid", max_iter = 30, tol = 1e-04, window_size = NULL)dtwAverage(x, init = "medoid", max_iter = 30, tol = 1e-04, window_size = NULL)
x |
A PhysioExperiment object or matrix (time x observations). |
init |
Initial reference: "medoid", "mean", or a numeric vector. |
max_iter |
Maximum iterations for DBA. |
tol |
Convergence tolerance. |
window_size |
Sakoe-Chiba band width. |
A list containing:
average |
The DTW-averaged waveform |
iterations |
Number of iterations used |
alignments |
List of alignment paths to the average |
Sakoe H, Chiba S (1978). "Dynamic programming algorithm optimization for spoken word recognition." IEEE Transactions on Acoustics, Speech, and Signal Processing, 26(1), 43-49.
Petitjean F, Ketterlin A, Gancarski P (2011). "A global averaging method for dynamic time warping, with applications to clustering." Pattern Recognition, 44(3), 678-693.
dtwDistance(), dtwDistanceMatrix(), dtwClustering()
# Average multiple gait cycles with timing variation set.seed(123) t <- seq(0, 100, length.out = 100) data <- sapply(1:20, function(i) { phase <- rnorm(1, 0, 10) sin(2 * pi * (t + phase) / 100) * 30 + rnorm(100, 0, 2) }) avg <- dtwAverage(data) plot(avg$average, type = "l")# Average multiple gait cycles with timing variation set.seed(123) t <- seq(0, 100, length.out = 100) data <- sapply(1:20, function(i) { phase <- rnorm(1, 0, 10) sin(2 * pi * (t + phase) / 100) * 30 + rnorm(100, 0, 2) }) avg <- dtwAverage(data) plot(avg$average, type = "l")
Clusters waveforms using DTW distance with hierarchical or k-medoids method.
dtwClustering( x, k = 2, method = c("hierarchical", "kmedoids"), linkage = "ward.D2", window_size = NULL )dtwClustering( x, k = 2, method = c("hierarchical", "kmedoids"), linkage = "ward.D2", window_size = NULL )
x |
A PhysioExperiment object or matrix (time x observations). |
k |
Number of clusters. |
method |
Clustering method: "hierarchical" or "kmedoids". |
linkage |
For hierarchical: "ward.D2", "complete", "average", etc. |
window_size |
Sakoe-Chiba band width. |
A list containing:
clusters |
Cluster assignments |
centers |
Cluster centers (medoids or DBA averages) |
distance_matrix |
DTW distance matrix used |
Sakoe H, Chiba S (1978). "Dynamic programming algorithm optimization for spoken word recognition." IEEE Transactions on Acoustics, Speech, and Signal Processing, 26(1), 43-49.
dtwDistance(), dtwDistanceMatrix(), dtwAverage()
# Cluster gait patterns set.seed(123) t <- seq(0, 100, length.out = 100) # Generate two groups with different patterns group1 <- sapply(1:15, function(i) { sin(2 * pi * t / 100) * 30 + rnorm(100, 0, 3) }) group2 <- sapply(1:15, function(i) { sin(2 * pi * t / 100 + pi/4) * 20 + rnorm(100, 0, 3) }) data <- cbind(group1, group2) result <- dtwClustering(data, k = 2) table(result$clusters)# Cluster gait patterns set.seed(123) t <- seq(0, 100, length.out = 100) # Generate two groups with different patterns group1 <- sapply(1:15, function(i) { sin(2 * pi * t / 100) * 30 + rnorm(100, 0, 3) }) group2 <- sapply(1:15, function(i) { sin(2 * pi * t / 100 + pi/4) * 20 + rnorm(100, 0, 3) }) data <- cbind(group1, group2) result <- dtwClustering(data, k = 2) table(result$clusters)
Functions for Dynamic Time Warping analysis including distance computation, alignment, averaging, and clustering of biomechanical waveforms. Compute DTW distance between two time series
dtwDistance( x, y, window_size = NULL, step_pattern = c("symmetric2", "symmetric1", "asymmetric"), normalize = TRUE )dtwDistance( x, y, window_size = NULL, step_pattern = c("symmetric2", "symmetric1", "asymmetric"), normalize = TRUE )
x |
First time series (numeric vector or matrix column). |
y |
Second time series (numeric vector or matrix column). |
window_size |
Sakoe-Chiba band width (NULL for no constraint). |
step_pattern |
Step pattern: "symmetric1", "symmetric2", or "asymmetric". |
normalize |
Logical; whether to normalize distance by path length. |
Calculates the Dynamic Time Warping distance and alignment path between two waveforms, allowing for non-linear time alignment.
DTW finds the optimal alignment between two time series by warping the time axis. It's useful for comparing movements that may occur at different speeds or with timing differences.
A list of class "dtw_result" containing:
distance |
DTW distance |
normalized_distance |
Distance normalized by path length |
path |
Alignment path (matrix with columns 'index1', 'index2') |
cost_matrix |
Accumulated cost matrix |
Sakoe H, Chiba S (1978). "Dynamic programming algorithm optimization for spoken word recognition." IEEE Transactions on Acoustics, Speech, and Signal Processing, 26(1), 43-49.
dtwDistanceMatrix(), dtwAverage(), dtwClustering(), dtwWarp()
# Two gait cycles with different timing t <- seq(0, 100, length.out = 100) x <- sin(2 * pi * t / 100) * 30 y <- sin(2 * pi * (t + 10) / 100) * 30 # Phase shifted result <- dtwDistance(x, y) print(result$distance)# Two gait cycles with different timing t <- seq(0, 100, length.out = 100) x <- sin(2 * pi * t / 100) * 30 y <- sin(2 * pi * (t + 10) / 100) * 30 # Phase shifted result <- dtwDistance(x, y) print(result$distance)
Computes pairwise DTW distances between all columns of a matrix or between observations in a PhysioExperiment.
dtwDistanceMatrix(x, window_size = NULL, normalize = TRUE, parallel = FALSE)dtwDistanceMatrix(x, window_size = NULL, normalize = TRUE, parallel = FALSE)
x |
A PhysioExperiment object or matrix (time x observations). |
window_size |
Sakoe-Chiba band width constraint. |
normalize |
Logical; normalize by path length. |
parallel |
Logical; use parallel processing. |
A symmetric distance matrix.
Sakoe H, Chiba S (1978). "Dynamic programming algorithm optimization for spoken word recognition." IEEE Transactions on Acoustics, Speech, and Signal Processing, 26(1), 43-49.
dtwDistance(), dtwAverage(), dtwClustering()
# Create matrix of 10 gait cycles set.seed(123) t <- seq(0, 100, length.out = 100) data <- sapply(1:10, function(i) { phase <- rnorm(1, 0, 10) sin(2 * pi * (t + phase) / 100) * 30 + rnorm(100, 0, 2) }) dist_matrix <- dtwDistanceMatrix(data)# Create matrix of 10 gait cycles set.seed(123) t <- seq(0, 100, length.out = 100) data <- sapply(1:10, function(i) { phase <- rnorm(1, 0, 10) sin(2 * pi * (t + phase) / 100) * 30 + rnorm(100, 0, 2) }) dist_matrix <- dtwDistanceMatrix(data)
Applies a DTW alignment path to warp one waveform to match another.
dtwWarp(x, dtw_result, to = c("query", "reference"))dtwWarp(x, dtw_result, to = c("query", "reference"))
x |
Waveform to warp. |
dtw_result |
DTW result from dtwDistance(). |
to |
Which series to warp to: "query" (index1) or "reference" (index2). |
Warped waveform.
Sakoe H, Chiba S (1978). "Dynamic programming algorithm optimization for spoken word recognition." IEEE Transactions on Acoustics, Speech, and Signal Processing, 26(1), 43-49.
dtwDistance(), dtwAverage(), normalizeMovement()
Fuses accelerometer, gyroscope, and optionally magnetometer data to estimate 3D orientation over time. Returns both quaternion and Euler angle representations.
estimateOrientation( accel, gyro, mag = NULL, method = c("madgwick", "complementary"), beta = 0.1, sampling_rate )estimateOrientation( accel, gyro, mag = NULL, method = c("madgwick", "complementary"), beta = 0.1, sampling_rate )
accel |
Numeric matrix (n x 3) of accelerometer readings in m/s^2. Columns correspond to x, y, z axes. |
gyro |
Numeric matrix (n x 3) of gyroscope readings in rad/s. Columns correspond to x, y, z axes. |
mag |
Numeric matrix (n x 3) of magnetometer readings, or |
method |
Character. Sensor fusion method: |
beta |
Numeric. Filter gain for the Madgwick filter (default 0.1). For the complementary filter this parameter sets the alpha coefficient (gyroscope trust weight). Lower values for Madgwick or higher values for complementary increase reliance on the gyroscope. |
sampling_rate |
Numeric. Sampling rate in Hz. |
The Madgwick filter uses a gradient-descent algorithm to correct
gyroscope drift using accelerometer (and optionally magnetometer)
measurements. The beta parameter controls the correction strength.
The complementary filter blends gyroscope integration (high-pass)
with accelerometer tilt estimation (low-pass). The beta parameter
serves as the alpha coefficient, controlling the balance between
gyroscope and accelerometer contributions.
A data.frame with columns:
Time in seconds from start.
Roll angle (degrees), rotation about X axis.
Pitch angle (degrees), rotation about Y axis.
Yaw angle (degrees), rotation about Z axis.
Quaternion scalar component.
Quaternion x component.
Quaternion y component.
Quaternion z component.
Madgwick SOH, Harrison AJL, Vaidyanathan R (2011). "Estimation of IMU and MARG orientation using a gradient descent algorithm." IEEE International Conference on Rehabilitation Robotics.
removeGravity(), calibrateIMU(), quaternionToEuler()
# Simulate static IMU data (sensor resting with gravity along -Z) n <- 100 accel <- matrix(c(rep(0, n), rep(0, n), rep(-9.81, n)), ncol = 3) gyro <- matrix(0, nrow = n, ncol = 3) result <- estimateOrientation(accel, gyro, sampling_rate = 100) head(result)# Simulate static IMU data (sensor resting with gravity along -Z) n <- 100 accel <- matrix(c(rep(0, n), rep(0, n), rep(-9.81, n)), ncol = 3) gyro <- matrix(0, nrow = n, ncol = 3) result <- estimateOrientation(accel, gyro, sampling_rate = 100) head(result)
Builds foot/shank/thigh inertial parameters from body mass and segment lengths using De Leva-style coefficients.
estimateSegmentInertia( body_mass, segment_lengths = NULL, body_height = NULL, model = c("deLeva_male", "deLeva_female") )estimateSegmentInertia( body_mass, segment_lengths = NULL, body_height = NULL, model = c("deLeva_male", "deLeva_female") )
body_mass |
Body mass in kilograms. |
segment_lengths |
Named numeric vector with |
body_height |
Body height in meters, required when
|
model |
Anthropometric coefficient set: |
A data.frame with segment mass, COM fraction, radius of gyration, and segment moment of inertia about COM.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
segmentParameters() for body segment inertial parameters,
inverseDynamics2D() for 2D inverse dynamics computation,
inverseDynamics3D() for 3D inverse dynamics computation.
inertia <- estimateSegmentInertia( body_mass = 70, segment_lengths = c(foot = 0.25, shank = 0.43, thigh = 0.45) )inertia <- estimateSegmentInertia( body_mass = 70, segment_lengths = c(foot = 0.25, shank = 0.43, thigh = 0.45) )
Computes eta-squared, partial eta-squared, and omega-squared from a one-way between-subjects comparison.
etaSquared(x, groups)etaSquared(x, groups)
x |
Numeric vector of values. |
groups |
Factor or character vector of group membership. |
Eta-squared is the proportion of total variance explained by group membership:
Omega-squared provides a less biased estimate:
For one-way designs, partial eta-squared equals eta-squared.
A list with components:
Eta-squared (SS_between / SS_total)
Partial eta-squared (SS_between / (SS_between + SS_within))
Omega-squared (bias-corrected effect size)
Cohen J (1988). "Statistical Power Analysis for the Behavioral Sciences." Lawrence Erlbaum Associates.
cohensD() for pairwise effect sizes,
plotEffectSizeForest() for forest plot visualization.
set.seed(42) x <- c(rnorm(20, 10, 2), rnorm(20, 12, 2), rnorm(20, 14, 2)) groups <- rep(c("A", "B", "C"), each = 20) result <- etaSquared(x, groups) result$eta_sqset.seed(42) x <- c(rnorm(20, 10, 2), rnorm(20, 12, 2), rnorm(20, 14, 2)) groups <- rep(c("A", "B", "C"), each = 20) result <- etaSquared(x, groups) result$eta_sq
Converts Euler angles (roll, pitch, yaw) to quaternion (w, x, y, z) representation using the specified rotation order.
eulerToQuaternion(roll, pitch, yaw, order = "ZYX")eulerToQuaternion(roll, pitch, yaw, order = "ZYX")
roll |
Numeric. Rotation about X axis (in radians by default, or degrees if values > 2*pi suggest degree input). |
pitch |
Numeric. Rotation about Y axis. |
yaw |
Numeric. Rotation about Z axis. |
order |
Character. Rotation order. Default |
Input angles are assumed to be in radians. For the "ZYX"
convention, the combined quaternion is computed as:
The resulting quaternion is always returned with
(canonical form).
A matrix with columns w, x, y, z. If inputs are
scalars, returns a 1-row matrix. If inputs are vectors, returns
a matrix with one row per element.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
Grood ES, Suntay WJ (1983). "A joint coordinate system for the clinical description of three-dimensional motions: application to the knee." Journal of Biomechanical Engineering, 105(2), 136-144.
quaternionToEuler(), calculateJointAngles(), vectorAngle()
# Zero rotation -> identity quaternion eulerToQuaternion(0, 0, 0) # 90-degree rotation about Z axis (input in radians) eulerToQuaternion(0, 0, pi/2)# Zero rotation -> identity quaternion eulerToQuaternion(0, 0, 0) # 90-degree rotation about Z axis (input in radians) eulerToQuaternion(0, 0, pi/2)
Defines an event within a movement task that can be detected automatically or specified manually.
Event( name, label, detection_method = "threshold", detection_params = list(), typical_timing = NULL )Event( name, label, detection_method = "threshold", detection_params = list(), typical_timing = NULL )
name |
Short identifier for the event (e.g., "hs1", "to") |
label |
Human-readable label (e.g., "Heel Strike", "Toe Off") |
detection_method |
Method for automatic detection:
|
detection_params |
List of parameters for detection method:
|
typical_timing |
Expected timing as percentage of movement (0-100), used for validation and as fallback |
An Event object (S3 class)
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
Phase(), TaskSchema(), detectEvents()
# Heel strike event detected when vertical GRF rises above 10N hs <- Event("hs", "Heel Strike", "threshold", list(signal = "vGRF", threshold = 10, direction = "rising"), typical_timing = 0) # Toe off event detected when vertical GRF falls below 10N to <- Event("to", "Toe Off", "threshold", list(signal = "vGRF", threshold = 10, direction = "falling"), typical_timing = 60) # Peak knee flexion pk <- Event("peak_flex", "Peak Knee Flexion", "peak", list(signal = "knee_angle", type = "max"))# Heel strike event detected when vertical GRF rises above 10N hs <- Event("hs", "Heel Strike", "threshold", list(signal = "vGRF", threshold = 10, direction = "rising"), typical_timing = 0) # Toe off event detected when vertical GRF falls below 10N to <- Event("to", "Toe Off", "threshold", list(signal = "vGRF", threshold = 10, direction = "falling"), typical_timing = 60) # Peak knee flexion pk <- Event("peak_flex", "Peak Knee Flexion", "peak", list(signal = "knee_angle", type = "max"))
Extract a single phase from segmented data
extractPhase(x, phase_name, search_subphases = TRUE)extractPhase(x, phase_name, search_subphases = TRUE)
x |
A segmented_phases object |
phase_name |
Name of the phase to extract |
search_subphases |
Whether to search within subphases |
A matrix of phase data
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
segmentPhases(), phaseTiming(), getPhaseData()
Functions for dimensionality reduction and visualization of high-dimensional biomechanical waveform data including PCA, UMAP, and t-SNE. Extract waveform features for dimensionality reduction
extractWaveformFeatures(x, features = c("statistical", "shape"), n_points = 50)extractWaveformFeatures(x, features = c("statistical", "shape"), n_points = 50)
x |
A PhysioExperiment object or matrix (time x observations). |
features |
Character vector of features to extract: "raw" (flattened waveform), "statistical" (summary stats), "frequency" (spectral features), "shape" (curve characteristics). |
n_points |
For "raw", number of points to resample to. |
Extracts summary features from waveforms for use with standard dimensionality reduction methods.
Feature types:
raw: The raw waveform resampled to n_points
statistical: Mean, SD, min, max, range, skewness, kurtosis
frequency: Dominant frequency, spectral centroid, bandwidth
shape: Peaks, zero crossings, area under curve
A matrix (observations x features) suitable for PCA/UMAP.
van der Maaten L, Hinton G (2008). "Visualizing Data using t-SNE." Journal of Machine Learning Research, 9, 2579-2605.
waveformPCA(), waveformUMAP(), waveformTSNE()
# Extract features from gait data set.seed(123) data <- matrix(rnorm(1000), nrow = 100, ncol = 10) features <- extractWaveformFeatures(data, features = c("statistical", "shape"))# Extract features from gait data set.seed(123) data <- matrix(rnorm(1000), nrow = 100, ncol = 10) features <- extractWaveformFeatures(data, features = c("statistical", "shape"))
Fills NA gaps in one or more position assays of a PhysioExperiment object
using interpolation. Gaps larger than max_gap are left as NA.
fillGaps(pe, method = c("spline", "linear"), max_gap = 50, assay_names = NULL)fillGaps(pe, method = c("spline", "linear"), max_gap = 50, assay_names = NULL)
pe |
A PhysioExperiment object |
method |
Interpolation method: |
max_gap |
Maximum gap size (in samples) to fill. Gaps larger than this
are left as NA. Set to |
assay_names |
Character vector of assay names to fill. If |
PhysioExperiment with filled assays (modified in place)
Federolf PA (2013). "A novel approach to solve the 'missing marker problem' in marker-based motion analysis that does not require additional assumptions about the biodynamic model." Journal of Biomechanics, 46(13), 2173-2178.
detectGaps(), reportGaps(), fillGapsLinear(), fillGapsSpline()
pe <- PhysioCore::PhysioExperiment( assays = S4Vectors::SimpleList( position_x = matrix(c(1, NA, NA, 4, 5), ncol = 1), position_y = matrix(c(10, NA, NA, 40, 50), ncol = 1) ), colData = S4Vectors::DataFrame(label = "M1", type = "marker"), samplingRate = 120 ) pe_filled <- fillGaps(pe, method = "linear", max_gap = 50)pe <- PhysioCore::PhysioExperiment( assays = S4Vectors::SimpleList( position_x = matrix(c(1, NA, NA, 4, 5), ncol = 1), position_y = matrix(c(10, NA, NA, 40, 50), ncol = 1) ), colData = S4Vectors::DataFrame(label = "M1", type = "marker"), samplingRate = 120 ) pe_filled <- fillGaps(pe, method = "linear", max_gap = 50)
Fills NA values in a numeric vector using linear interpolation via
approx.
fillGapsLinear(x)fillGapsLinear(x)
x |
Numeric vector potentially containing NAs |
Numeric vector with NAs filled by linear interpolation. Leading and trailing NAs (outside the range of valid data) remain as NA.
Federolf PA (2013). "A novel approach to solve the 'missing marker problem' in marker-based motion analysis that does not require additional assumptions about the biodynamic model." Journal of Biomechanics, 46(13), 2173-2178.
fillGapsSpline(), fillGaps(), detectGaps()
x <- c(1, NA, NA, 4, 5, NA, 7) fillGapsLinear(x)x <- c(1, NA, NA, 4, 5, NA, 7) fillGapsLinear(x)
Fills NA values in a numeric vector using smooth spline interpolation via
smooth.spline.
fillGapsSpline(x, spar = NULL)fillGapsSpline(x, spar = NULL)
x |
Numeric vector potentially containing NAs |
spar |
Smoothing parameter passed to |
Numeric vector with NAs filled by spline interpolation. Leading and trailing NAs (outside the range of valid data) remain as NA.
Federolf PA (2013). "A novel approach to solve the 'missing marker problem' in marker-based motion analysis that does not require additional assumptions about the biodynamic model." Journal of Biomechanics, 46(13), 2173-2178.
fillGapsLinear(), fillGaps(), detectGaps()
x <- c(1, NA, NA, 4, 5, NA, 7) fillGapsSpline(x)x <- c(1, NA, NA, 4, 5, NA, 7) fillGapsSpline(x)
Applies low-pass filtering to force-plate signals. By default this uses a
zero-phase Butterworth filter (requires the signal package). If signal
is not available, the function falls back to a moving-average filter.
filterGRF( x, sampling_rate, cutoff = 20, order = 4, method = c("butterworth", "moving_average") )filterGRF( x, sampling_rate, cutoff = 20, order = 4, method = c("butterworth", "moving_average") )
x |
Numeric vector or matrix (time x channels). |
sampling_rate |
Sampling rate in Hz. |
cutoff |
Low-pass cutoff frequency in Hz. |
order |
Butterworth filter order. |
method |
Filtering method: |
Filtered data with the same dimensions as x.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
butterworthFilter() for general Butterworth filtering,
analyzeForcePlate() for comprehensive force plate analysis.
sr <- 1000 t <- seq(0, 1, length.out = sr) x <- sin(2 * pi * 10 * t) + 0.2 * sin(2 * pi * 150 * t) y <- filterGRF(x, sampling_rate = sr, cutoff = 25)sr <- 1000 t <- seq(0, 1, length.out = sr) x <- sin(2 * pi * 10 * t) + 0.2 * sin(2 * pi * 150 * t) y <- filterGRF(x, sampling_rate = sr, cutoff = 25)
Applies a Butterworth IIR filter to signal data stored in a PhysioExperiment object. The filter is applied using zero-phase filtering (forward-backward) to avoid phase distortion.
filterSignals( pe, type = c("lowpass", "highpass", "bandpass", "bandstop"), cutoff, order = 4, assay_name = NULL, output_assay = NULL )filterSignals( pe, type = c("lowpass", "highpass", "bandpass", "bandstop"), cutoff, order = 4, assay_name = NULL, output_assay = NULL )
pe |
A PhysioExperiment object. |
type |
Filter type: "lowpass", "highpass", "bandpass", or "bandstop". |
cutoff |
Cutoff frequency in Hz. A single value for "lowpass" or
"highpass"; a length-2 vector |
order |
Filter order (default: 4). |
assay_name |
Which assay to filter. If NULL, uses the first assay. |
output_assay |
Name for the output assay. If NULL, defaults to
|
This function requires the signal package (listed in Suggests). If not installed, an informative error message with install instructions is provided.
The Butterworth filter is designed using signal::butter() and applied
with signal::filtfilt() for zero-phase filtering. The cutoff frequency
is normalized to the Nyquist frequency automatically.
A PhysioExperiment object with filtered data stored as a new assay.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
Butterworth S (1930). "On the Theory of Filter Amplifiers." Wireless Engineer, 7, 536-541.
butterworthFilter() for filtering raw vectors and matrices,
savgolFilter() for Savitzky-Golay polynomial smoothing,
movingAverage() for simple moving average smoothing.
## Not run: pe <- make_mocap_markers(n_time = 500, n_markers = 4, sr = 120) pe_filt <- filterSignals(pe, type = "lowpass", cutoff = 10) ## End(Not run)## Not run: pe <- make_mocap_markers(n_time = 500, n_markers = 4, sr = 120) pe_filt <- filterSignals(pe, type = "lowpass", cutoff = 10) ## End(Not run)
Functions for functional data analysis including functional PCA (fPCA), functional regression, and curve registration. These methods treat biomechanical waveforms as continuous functions. Functional Principal Component Analysis (fPCA)
fPCA(x, n_components = 5, smooth = FALSE, smooth_param = 10)fPCA(x, n_components = 5, smooth = FALSE, smooth_param = 10)
x |
A PhysioExperiment object or matrix (time x observations). |
n_components |
Number of principal components to retain. |
smooth |
Logical; if TRUE, smooths the data before analysis. |
smooth_param |
Smoothing parameter (higher = smoother). |
Performs functional PCA on waveform data to identify the main modes of variation in movement patterns.
fPCA decomposes waveform variability into orthogonal modes. In gait analysis, PC1 often represents overall amplitude, PC2 timing/phase shifts, and subsequent PCs capture more subtle shape variations.
A list of class "fpca_result" containing:
scores |
PC scores for each observation (observations x components) |
loadings |
PC loadings/eigenfunctions (time x components) |
variance_explained |
Proportion of variance explained by each PC |
cumulative_variance |
Cumulative variance explained |
mean_function |
Mean waveform across observations |
Ramsay JO, Silverman BW (2005). "Functional Data Analysis." 2nd ed. Springer.
reconstructFPCA() for waveform reconstruction from fPCA results,
plotFPCA() for visualization of fPCA results,
registerCurves() for separating phase and amplitude variation.
# Simulate gait angle data (100 time points x 30 subjects) set.seed(123) t <- seq(0, 100, length.out = 100) base_curve <- sin(2 * pi * t / 100) * 30 # Add subject variability data <- sapply(1:30, function(i) { amplitude <- rnorm(1, 1, 0.2) phase <- rnorm(1, 0, 5) base_curve * amplitude + rnorm(100, 0, 2) }) pe <- PhysioExperiment(assays = list(values = data), samplingRate = 100) fpca_result <- fPCA(pe, n_components = 4) # Plot first two PC loadings plotFPCA(fpca_result)# Simulate gait angle data (100 time points x 30 subjects) set.seed(123) t <- seq(0, 100, length.out = 100) base_curve <- sin(2 * pi * t / 100) * 30 # Add subject variability data <- sapply(1:30, function(i) { amplitude <- rnorm(1, 1, 0.2) phase <- rnorm(1, 0, 5) base_curve * amplitude + rnorm(100, 0, 2) }) pe <- PhysioExperiment(assays = list(values = data), samplingRate = 100) fpca_result <- fPCA(pe, n_components = 4) # Plot first two PC loadings plotFPCA(fpca_result)
Returns the bone connections as an edge list (data.frame) or as an adjacency matrix.
get_bone_connections(skeleton, as_matrix = FALSE)get_bone_connections(skeleton, as_matrix = FALSE)
skeleton |
A |
as_matrix |
Logical. If |
If as_matrix = FALSE, a data.frame with columns from_label,
to_label, and bone_name. If as_matrix = TRUE, a symmetric
logical adjacency matrix.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
SkeletonModel(), define_skeleton(), get_segment_lengths()
sk <- define_skeleton("COCO") edges <- get_bone_connections(sk) head(edges) adj <- get_bone_connections(sk, as_matrix = TRUE) dim(adj)sk <- define_skeleton("COCO") edges <- get_bone_connections(sk) head(edges) adj <- get_bone_connections(sk, as_matrix = TRUE) dim(adj)
Identifies corresponding left and right keypoint pairs in a skeleton model, useful for bilateral symmetry analysis.
get_limb_pairs(skeleton)get_limb_pairs(skeleton)
skeleton |
A |
A data.frame with columns left and right, where each
row is a matched pair of keypoint labels.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
SkeletonModel(), define_skeleton(), get_segment_lengths()
sk <- define_skeleton("BODY_25") pairs <- get_limb_pairs(sk) head(pairs)sk <- define_skeleton("BODY_25") pairs <- get_limb_pairs(sk) head(pairs)
Calculates the Euclidean distance between connected keypoints for each
frame. The PhysioExperiment must contain position_x, position_y,
and (optionally) position_z assays with columns matching skeleton
keypoint labels.
get_segment_lengths(pe, skeleton)get_segment_lengths(pe, skeleton)
pe |
A |
skeleton |
A |
A matrix of segment lengths with dimensions (n_frames x n_bones). Column names are bone names.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
SkeletonModel(), get_bone_connections(), get_limb_pairs()
## Not run: pe <- readOpenPose("path/to/frames/", model = "BODY_25") sk <- define_skeleton("BODY_25") lengths <- get_segment_lengths(pe, sk) ## End(Not run)## Not run: pe <- readOpenPose("path/to/frames/", model = "BODY_25") sk <- define_skeleton("BODY_25") lengths <- get_segment_lengths(pe, sk) ## End(Not run)
Get an event by name from a TaskSchema
getEvent(schema, event_name)getEvent(schema, event_name)
schema |
A TaskSchema object |
event_name |
Name of the event to retrieve |
An Event object or NULL if not found
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
getEventNames(), getPhase(), TaskSchema()
Get event names from a TaskSchema
getEventNames(schema)getEventNames(schema)
schema |
A TaskSchema object |
Character vector of event names
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
getPhaseNames(), getEvent(), TaskSchema()
Get a phase by name from a TaskSchema
getPhase(schema, phase_name, search_subphases = TRUE)getPhase(schema, phase_name, search_subphases = TRUE)
schema |
A TaskSchema object |
phase_name |
Name of the phase to retrieve |
search_subphases |
Whether to search within subphases |
A Phase object or NULL if not found
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
getPhaseNames(), getPhaseColors(), getEvent()
Get phase colors from a TaskSchema
getPhaseColors(schema, include_subphases = FALSE)getPhaseColors(schema, include_subphases = FALSE)
schema |
A TaskSchema object |
include_subphases |
Whether to include subphase colors |
Named character vector of colors (phase name -> color)
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
getPhaseNames(), getPhase(), TaskSchema()
Get data for all phases as a list of matrices
getPhaseData(x, include_subphases = FALSE)getPhaseData(x, include_subphases = FALSE)
x |
A segmented_phases object |
include_subphases |
Whether to include subphases |
Named list of matrices
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
segmentPhases(), extractPhase(), hasValidPhases()
Get phase names from a TaskSchema
getPhaseNames(schema, include_subphases = FALSE)getPhaseNames(schema, include_subphases = FALSE)
schema |
A TaskSchema object |
include_subphases |
Whether to include subphase names |
Character vector of phase names
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
getEventNames(), getPhase(), getPhaseColors()
Get a pre-built schema by name
getSchema(name)getSchema(name)
name |
Name of the schema ("gait", "running", "jump", "throw", "balance", "cutting", "cycling") |
A TaskSchema object
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
listSchemas(), TaskSchema(), validateSchema()
gait <- getSchema("gait") jump <- getSchema("jump")gait <- getSchema("gait") jump <- getSchema("jump")
Check if all phases are valid
hasValidPhases(x)hasValidPhases(x)
x |
A segmented_phases object |
Logical indicating if all phases have valid data
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
segmentPhases(), getPhaseData(), extractPhase()
Computes the ICC using ANOVA-based methods following Shrout & Fleiss (1979). Supports one-way and two-way random/mixed models, agreement and consistency types, and single or average unit measures.
icc( ratings, model = c("twoway", "oneway"), type = c("agreement", "consistency"), unit = c("single", "average") )icc( ratings, model = c("twoway", "oneway"), type = c("agreement", "consistency"), unit = c("single", "average") )
ratings |
Numeric matrix with subjects as rows and raters/sessions as columns. |
model |
Character; ICC model type:
|
type |
Character; agreement type:
|
unit |
Character; unit of measurement:
|
The function implements the six ICC forms from Shrout & Fleiss (1979):
ICC(1,1): One-way random, single measures
ICC(1,k): One-way random, average measures
ICC(2,1): Two-way random, absolute agreement, single measures
ICC(2,k): Two-way random, absolute agreement, average measures
ICC(3,1): Two-way mixed, consistency, single measures
ICC(3,k): Two-way mixed, consistency, average measures
A list with components:
ICC value
Lower bound of 95 percent confidence interval
Upper bound of 95 percent confidence interval
F statistic from ANOVA
p-value for testing ICC = 0
Model used
Agreement type used
Shrout PE, Fleiss JL (1979). Intraclass correlations: Uses in assessing rater reliability. Psychological Bulletin, 86(2), 420-428.
sem() for standard error of measurement based on ICC,
mdc() for minimal detectable change,
blandAltman() for agreement analysis between methods.
# Test-retest reliability ratings <- matrix(c( 9, 2, 5, 8, 6, 1, 3, 2, 8, 4, 6, 8, 7, 1, 2, 6, 10, 5, 6, 9, 6, 2, 4, 7 ), nrow = 6, ncol = 4, byrow = TRUE) result <- icc(ratings, model = "twoway", type = "agreement") result$icc# Test-retest reliability ratings <- matrix(c( 9, 2, 5, 8, 6, 1, 3, 2, 8, 4, 6, 8, 7, 1, 2, 6, 10, 5, 6, 9, 6, 2, 4, 7 ), nrow = 6, ncol = 4, byrow = TRUE) result <- icc(ratings, model = "twoway", type = "agreement") result$icc
Aligns EMG to MoCap sample times and returns a combined table for downstream feature analysis.
integrateEMGMoCap( mocap, emg, mocap_sampling_rate = NULL, emg_sampling_rate, mocap_assay = NULL, process = TRUE, ... )integrateEMGMoCap( mocap, emg, mocap_sampling_rate = NULL, emg_sampling_rate, mocap_assay = NULL, process = TRUE, ... )
mocap |
A numeric matrix/data.frame (time x features), or a PhysioExperiment object. |
emg |
Numeric vector or matrix (time x channels). |
mocap_sampling_rate |
MoCap sampling rate in Hz. If |
emg_sampling_rate |
EMG sampling rate in Hz. |
mocap_assay |
Assay name to use when |
process |
Logical; if |
... |
Additional arguments passed to |
A list with mocap, emg_aligned, and combined data.frame.
Merletti R, Parker PA (2004). "Electromyography: Physiology, Engineering, and Non-Invasive Applications." IEEE Press/Wiley.
processEMG() for EMG processing pipeline,
alignEMGtoMoCap() for time-alignment of EMG to MoCap,
synchronizeSignals() for general multi-signal synchronization.
mocap <- matrix(rnorm(500), ncol = 5) emg <- matrix(rnorm(5000), ncol = 2) out <- integrateEMGMoCap(mocap, emg, mocap_sampling_rate = 100, emg_sampling_rate = 1000)mocap <- matrix(rnorm(500), ncol = 5) emg <- matrix(rnorm(5000), ncol = 2) out <- integrateEMGMoCap(mocap, emg, mocap_sampling_rate = 100, emg_sampling_rate = 1000)
Computes sagittal-plane ankle, knee, and hip net moments from joint-center coordinates, GRF, COP, and segment inertial terms.
inverseDynamics2D( joints, grf, sampling_rate, angles = NULL, angular_velocity = NULL, angular_acceleration = NULL, inertial = NULL, angle_unit = c("radian", "degree") )inverseDynamics2D( joints, grf, sampling_rate, angles = NULL, angular_velocity = NULL, angular_acceleration = NULL, inertial = NULL, angle_unit = c("radian", "degree") )
joints |
Matrix/data.frame with columns |
grf |
Matrix/data.frame with at least |
sampling_rate |
Sampling rate in Hz. |
angles |
Optional matrix/data.frame with columns |
angular_velocity |
Optional matrix/data.frame with columns
|
angular_acceleration |
Optional matrix/data.frame with columns
|
inertial |
Optional data.frame from |
angle_unit |
Unit of |
A data.frame with time index and joint moments (ankle_moment,
knee_moment, hip_moment). If angular velocity is available,
corresponding power columns are included.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
inverseDynamics3D() for 3D inverse dynamics computation,
estimateSegmentInertia() for segment inertial properties,
computeJointPower() for joint power calculation.
n <- 200 joints <- data.frame( ankle_x = rep(0.00, n), ankle_y = rep(0.05, n), knee_x = rep(0.00, n), knee_y = rep(0.45, n), hip_x = rep(0.00, n), hip_y = rep(0.85, n) ) grf <- data.frame(fx = rep(0, n), fy = abs(sin(seq(0, pi, length.out = n))) * 800, cop_x = rep(0.02, n), cop_y = rep(0, n)) id <- inverseDynamics2D(joints, grf, sampling_rate = 100)n <- 200 joints <- data.frame( ankle_x = rep(0.00, n), ankle_y = rep(0.05, n), knee_x = rep(0.00, n), knee_y = rep(0.45, n), hip_x = rep(0.00, n), hip_y = rep(0.85, n) ) grf <- data.frame(fx = rep(0, n), fy = abs(sin(seq(0, pi, length.out = n))) * 800, cop_x = rep(0.02, n), cop_y = rep(0, n)) id <- inverseDynamics2D(joints, grf, sampling_rate = 100)
Computes ankle, knee, and hip net moments in 3D from joint-center coordinates, GRF, COP, and optional inertial terms.
inverseDynamics3D( joints, grf, sampling_rate, angles = NULL, angular_velocity = NULL, angular_acceleration = NULL, inertial = NULL, angle_unit = c("radian", "degree") )inverseDynamics3D( joints, grf, sampling_rate, angles = NULL, angular_velocity = NULL, angular_acceleration = NULL, inertial = NULL, angle_unit = c("radian", "degree") )
joints |
Matrix/data.frame with columns |
grf |
Matrix/data.frame with columns |
sampling_rate |
Sampling rate in Hz. |
angles |
Optional matrix/data.frame containing 3D joint angles with
columns |
angular_velocity |
Optional 3D joint angular velocity table. |
angular_acceleration |
Optional 3D joint angular acceleration table. |
inertial |
Optional data.frame from |
angle_unit |
Unit of angle-related inputs: |
A data.frame with time and moment components:
*_moment_x, *_moment_y, *_moment_z. If angular velocity is
available, *_power_total columns are included.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
inverseDynamics2D() for sagittal-plane inverse dynamics,
estimateSegmentInertia() for segment inertial properties,
computeJointPower() for joint power calculation.
n <- 200 joints <- data.frame( ankle_x = rep(0.00, n), ankle_y = rep(0.00, n), ankle_z = rep(0.05, n), knee_x = rep(0.00, n), knee_y = rep(0.00, n), knee_z = rep(0.45, n), hip_x = rep(0.00, n), hip_y = rep(0.00, n), hip_z = rep(0.85, n) ) grf <- data.frame( fx = rep(50, n), fy = rep(0, n), fz = rep(700, n), cop_x = rep(0.02, n), cop_y = rep(0, n), cop_z = rep(0, n) ) out <- inverseDynamics3D(joints, grf, sampling_rate = 100)n <- 200 joints <- data.frame( ankle_x = rep(0.00, n), ankle_y = rep(0.00, n), ankle_z = rep(0.05, n), knee_x = rep(0.00, n), knee_y = rep(0.00, n), knee_z = rep(0.45, n), hip_x = rep(0.00, n), hip_y = rep(0.00, n), hip_z = rep(0.85, n) ) grf <- data.frame( fx = rep(50, n), fy = rep(0, n), fz = rep(700, n), cop_x = rep(0.02, n), cop_y = rep(0, n), cop_z = rep(0, n) ) out <- inverseDynamics3D(joints, grf, sampling_rate = 100)
Get list of all pre-built schemas
listSchemas()listSchemas()
Named list of all available pre-built TaskSchema objects
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
getSchema(), TaskSchema(), validateSchema()
schemas <- listSchemas() names(schemas)schemas <- listSchemas() names(schemas)
Create a detected_events object from manually specified times or indices.
manualEvents( schema, times = NULL, indices = NULL, sampling_rate = NULL, n_samples )manualEvents( schema, times = NULL, indices = NULL, sampling_rate = NULL, n_samples )
schema |
TaskSchema object |
times |
Named numeric vector of event times in seconds |
indices |
Named integer vector of event indices |
sampling_rate |
Sampling rate (required if using times) |
n_samples |
Total number of samples (required) |
A detected_events data.frame
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
detectEvents(), segmentPhases(), TaskSchema()
events <- manualEvents( schema_gait, times = c(hs1 = 0, to = 0.6, hs2 = 1.0), sampling_rate = 1000, n_samples = 1000 )events <- manualEvents( schema_gait, times = c(hs1 = 0, to = 0.6, hs2 = 1.0), sampling_rate = 1000, n_samples = 1000 )
Computes the minimal detectable change from the standard error of measurement.
mdc(sem_value, confidence = 0.95)mdc(sem_value, confidence = 0.95)
sem_value |
Numeric; the standard error of measurement. |
confidence |
Numeric; confidence level (default 0.95). |
MDC is computed as:
where .
At 95\
Numeric MDC value.
Shrout PE, Fleiss JL (1979). "Intraclass Correlations: Uses in Assessing Rater Reliability." Psychological Bulletin, 86(2), 420-428.
sem() for computing standard error of measurement,
icc() for computing intraclass correlation coefficients.
sem_val <- 2.5 mdc(sem_val, confidence = 0.95)sem_val <- 2.5 mdc(sem_val, confidence = 0.95)
Applies a symmetric moving average for quick smoothing of signal data.
Uses stats::filter() internally with equal weights.
movingAverage(x, window = 5)movingAverage(x, window = 5)
x |
A numeric vector or matrix (time x channels). |
window |
Window size for the moving average (default: 5). Will be coerced to an odd integer. |
Smoothed data with the same dimensions as x. Edge values where
the full window cannot be applied are set to NA.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
butterworthFilter() for Butterworth low-pass filtering,
savgolFilter() for Savitzky-Golay polynomial smoothing.
# Smooth a noisy signal x <- sin(seq(0, 4 * pi, length.out = 200)) + rnorm(200, sd = 0.3) x_smooth <- movingAverage(x, window = 7)# Smooth a noisy signal x <- sin(seq(0, 4 * pi, length.out = 200)) + rnorm(200, sd = 0.3) x_smooth <- movingAverage(x, window = 7)
Generates an appropriate time axis for normalized data.
normalizedTimeAxis( norm_length, method = "cycle", unit = c("percent", "normalized", "degrees") )normalizedTimeAxis( norm_length, method = "cycle", unit = c("percent", "normalized", "degrees") )
norm_length |
Length of normalized data |
method |
Normalization method used |
unit |
Output unit ("percent", "normalized", "degrees") |
Numeric vector of time values
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
normalizeMovement(), batchNormalize(), segmentPhases()
# 0-100% axis t_pct <- normalizedTimeAxis(101, method = "cycle", unit = "percent") # 0-360 degrees for cycling t_deg <- normalizedTimeAxis(361, method = "cycle", unit = "degrees")# 0-100% axis t_pct <- normalizedTimeAxis(101, method = "cycle", unit = "percent") # 0-360 degrees for cycling t_deg <- normalizedTimeAxis(361, method = "cycle", unit = "degrees")
Normalize EMG by MVC or peak
normalizeEMG(x, method = c("mvc", "peak"), mvc = NULL, scale_percent = TRUE)normalizeEMG(x, method = c("mvc", "peak"), mvc = NULL, scale_percent = TRUE)
x |
Numeric vector or matrix (time x channels). |
method |
Normalization method: |
mvc |
Numeric scalar or vector of MVC reference values. Required when
|
scale_percent |
Logical; if |
Normalized signal with same dimensions as x.
Merletti R, Parker PA (2004). "Electromyography: Physiology, Engineering, and Non-Invasive Applications." IEEE Press/Wiley.
rectifyEMG() for signal rectification,
computeRMSEnvelope() for RMS envelope computation,
processEMG() for complete EMG processing pipeline.
x <- matrix(abs(rnorm(500)), ncol = 2) normalizeEMG(x, method = "peak")x <- matrix(abs(rnorm(500)), ncol = 2) normalizeEMG(x, method = "peak")
Normalizes movement data using various methods appropriate for different task types.
normalizeMovement( x, method = c("cycle", "phase", "landmark", "dtw", "absolute"), norm_length = 101L, schema = NULL, events = NULL, reference = NULL, ... )normalizeMovement( x, method = c("cycle", "phase", "landmark", "dtw", "absolute"), norm_length = 101L, schema = NULL, events = NULL, reference = NULL, ... )
x |
Data to normalize:
|
method |
Normalization method:
|
norm_length |
Target length after normalization (default 101 for 0-100%) |
schema |
Optional TaskSchema for context |
events |
Optional detected_events for landmark alignment |
reference |
Reference trial for DTW (default: mean of all trials) |
... |
Additional arguments passed to specific methods |
Normalized data in the same format as input (or matrix for segmented_phases)
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
batchNormalize(), normalizedTimeAxis(), segmentPhases()
# Normalize a matrix to 101 points data <- matrix(rnorm(500), nrow = 500, ncol = 3) normalized <- normalizeMovement(data, method = "cycle", norm_length = 101)# Normalize a matrix to 101 points data <- matrix(rnorm(500), nrow = 500, ncol = 3) normalized <- normalizeMovement(data, method = "cycle", norm_length = 101)
Defines a phase within a movement task, bounded by start and end events.
Phase(name, label, start_event, end_event, color = NULL, subphases = list())Phase(name, label, start_event, end_event, color = NULL, subphases = list())
name |
Short identifier for the phase (e.g., "stance", "swing") |
label |
Human-readable label (e.g., "Stance Phase") |
start_event |
Name of the event marking phase start |
end_event |
Name of the event marking phase end |
color |
Optional color for visualization (hex code) |
subphases |
Optional list of Phase objects for nested phases |
A Phase object (S3 class)
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
Event(), TaskSchema(), segmentPhases()
# Simple phase definition stance <- Phase("stance", "Stance Phase", "hs1", "to", color = "#E8F4F8") # Phase with subphases stance <- Phase("stance", "Stance Phase", "hs1", "to", color = "#E8F4F8", subphases = list( Phase("loading", "Loading Response", "hs1", "ff"), Phase("midstance", "Midstance", "ff", "ho"), Phase("propulsion", "Propulsion", "ho", "to") ))# Simple phase definition stance <- Phase("stance", "Stance Phase", "hs1", "to", color = "#E8F4F8") # Phase with subphases stance <- Phase("stance", "Stance Phase", "hs1", "to", color = "#E8F4F8", subphases = list( Phase("loading", "Loading Response", "hs1", "ff"), Phase("midstance", "Midstance", "ff", "ho"), Phase("propulsion", "Propulsion", "ho", "to") ))
Get phase durations
phaseDurations(x, unit = c("percent", "seconds", "samples"))phaseDurations(x, unit = c("percent", "seconds", "samples"))
x |
A segmented_phases object |
unit |
"samples", "seconds", or "percent" |
Named numeric vector of phase durations
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
phaseTiming(), phaseRatios(), segmentPhases()
Calculate phase ratios
phaseRatios(x, reference = "total")phaseRatios(x, reference = "total")
x |
A segmented_phases object |
reference |
Reference for ratio calculation ("total" or phase name) |
Named numeric vector of phase ratios
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
phaseDurations(), phaseTiming(), segmentPhases()
Get phase timing information
phaseTiming(x, as_percent = TRUE)phaseTiming(x, as_percent = TRUE)
x |
A segmented_phases object |
as_percent |
Return timing as percentage (TRUE) or seconds (FALSE) |
A data.frame with phase timing information
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
segmentPhases(), phaseDurations(), phaseRatios()
Creates a heatmap visualization of a correlation matrix with optional clustering and significance masking.
plotCorrelationMatrix( x, method = "pearson", cluster = TRUE, show_values = TRUE, show_significance = FALSE, alpha = 0.05, colors = c("#B2182B", "white", "#2166AC"), title = "Correlation Matrix" )plotCorrelationMatrix( x, method = "pearson", cluster = TRUE, show_values = TRUE, show_significance = FALSE, alpha = 0.05, colors = c("#B2182B", "white", "#2166AC"), title = "Correlation Matrix" )
x |
A correlation matrix, data.frame, or PhysioExperiment. |
method |
If x is data, correlation method: "pearson", "spearman", "kendall". |
cluster |
Logical; apply hierarchical clustering to reorder. |
show_values |
Logical; display correlation values in cells. |
show_significance |
Logical; mask non-significant correlations. |
alpha |
Significance threshold for masking. |
colors |
Color palette (low, mid, high). |
title |
Plot title. |
A ggplot object.
Wickham H (2016). "ggplot2: Elegant Graphics for Data Analysis." Springer.
plotEffectSizeForest() for forest plots of effect sizes,
plotWaveformComparison() for comparing waveform patterns across groups.
# Correlation matrix of joint angles set.seed(123) data <- data.frame( Hip = rnorm(100), Knee = rnorm(100), Ankle = rnorm(100) ) data$Knee <- data$Hip * 0.7 + rnorm(100, 0, 0.5) # Correlated plotCorrelationMatrix(data)# Correlation matrix of joint angles set.seed(123) data <- data.frame( Hip = rnorm(100), Knee = rnorm(100), Ankle = rnorm(100) ) data$Knee <- data$Hip * 0.7 + rnorm(100, 0, 0.5) # Correlated plotCorrelationMatrix(data)
Creates a waveform plot with automatic phase and event annotations based on the TaskSchema. This is a generalized version of plotGaitCycle.
plotCycle( x, schema = NULL, events = NULL, channel = 1L, show_mean = TRUE, show_sd = TRUE, show_ci = FALSE, ci = 0.95, show_individual = FALSE, show_events = NULL, show_phases = NULL, time_axis = NULL, xlab = NULL, ylab = "Value", title = NULL, colors = NULL, ... )plotCycle( x, schema = NULL, events = NULL, channel = 1L, show_mean = TRUE, show_sd = TRUE, show_ci = FALSE, ci = 0.95, show_individual = FALSE, show_events = NULL, show_phases = NULL, time_axis = NULL, xlab = NULL, ylab = "Value", title = NULL, colors = NULL, ... )
x |
Normalized data (matrix, PhysioExperiment, or 3D array) |
schema |
TaskSchema object for formatting and annotations |
events |
Optional detected_events for event markers |
channel |
Channel index or name to plot (for multi-channel data) |
show_mean |
Show mean line |
show_sd |
Show standard deviation band |
show_ci |
Show confidence interval band |
ci |
Confidence level (default 0.95) |
show_individual |
Show individual trials |
show_events |
Show event markers |
show_phases |
Show phase regions |
time_axis |
Custom time axis values |
xlab |
X-axis label (default from schema) |
ylab |
Y-axis label |
title |
Plot title |
colors |
Named vector of colors for phases |
... |
Additional arguments passed to ggplot |
A ggplot object
Wickham H (2016). "ggplot2: Elegant Graphics for Data Analysis." Springer.
plotGroupComparison() for multi-group comparisons,
plotMultiPanel() for multi-channel cycle visualization,
plotPhaseDurations() for phase duration bar charts.
# Basic usage with schema data <- matrix(rnorm(101 * 10), nrow = 101) p <- plotCycle(data, schema = schema_gait) # With events events <- manualEvents(schema_gait, c(hs1 = 0, to = 0.6, hs2 = 1.0), sampling_rate = 100, n_samples = 101) p <- plotCycle(data, schema = schema_gait, events = events)# Basic usage with schema data <- matrix(rnorm(101 * 10), nrow = 101) p <- plotCycle(data, schema = schema_gait) # With events events <- manualEvents(schema_gait, c(hs1 = 0, to = 0.6, hs2 = 1.0), sampling_rate = 100, n_samples = 101) p <- plotCycle(data, schema = schema_gait, events = events)
Visualizes the DTW alignment between two waveforms.
plotDTW( dtw_result, x = NULL, y = NULL, type = c("alignment", "cost", "waveforms", "all") )plotDTW( dtw_result, x = NULL, y = NULL, type = c("alignment", "cost", "waveforms", "all") )
dtw_result |
A dtw_result object from dtwDistance(). |
x |
First waveform (optional, for overlay). |
y |
Second waveform (optional, for overlay). |
type |
Plot type: "alignment", "cost", "waveforms", or "all". |
A ggplot object or list of plots.
Sakoe H, Chiba S (1978). "Dynamic programming algorithm optimization for spoken word recognition." IEEE Transactions on Acoustics, Speech, and Signal Processing, 26(1), 43-49.
dtwDistance(), dtwWarp(), dtwClustering()
Creates a forest plot displaying effect sizes with confidence intervals, commonly used for meta-analysis style visualization of multiple comparisons.
plotEffectSizeForest( effects, ci_lower, ci_upper, labels = NULL, null_value = 0, sort_by = c("none", "effect", "name"), title = "Effect Sizes" )plotEffectSizeForest( effects, ci_lower, ci_upper, labels = NULL, null_value = 0, sort_by = c("none", "effect", "name"), title = "Effect Sizes" )
effects |
Named vector or data.frame of effect sizes. |
ci_lower |
Lower confidence interval bounds. |
ci_upper |
Upper confidence interval bounds. |
labels |
Labels for each effect (uses names if not provided). |
null_value |
Reference line value (default: 0). |
sort_by |
How to sort: "none", "effect", "name". |
title |
Plot title. |
A ggplot object.
Wickham H (2016). "ggplot2: Elegant Graphics for Data Analysis." Springer.
cohensD() for computing Cohen's d effect sizes,
etaSquared() for computing eta-squared effect sizes,
plotCorrelationMatrix() for correlation heatmaps.
# Forest plot of effect sizes across joints effects <- c(Hip = 0.8, Knee = 1.2, Ankle = 0.3) ci_lower <- c(0.4, 0.8, -0.1) ci_upper <- c(1.2, 1.6, 0.7) plotEffectSizeForest(effects, ci_lower, ci_upper)# Forest plot of effect sizes across joints effects <- c(Hip = 0.8, Knee = 1.2, Ankle = 0.3) ci_lower <- c(0.4, 0.8, -0.1) ci_upper <- c(1.2, 1.6, 0.7) plotEffectSizeForest(effects, ci_lower, ci_upper)
Visualizes functional PCA results including loadings and variance explained.
plotFPCA( x, type = c("loadings", "variance", "scores", "all"), components = 1:4, time_axis = NULL )plotFPCA( x, type = c("loadings", "variance", "scores", "all"), components = 1:4, time_axis = NULL )
x |
An fpca_result object. |
type |
Plot type: "loadings", "variance", "scores", or "all". |
components |
Which components to plot. |
time_axis |
Optional time axis values. |
A ggplot object (or list of plots for type = "all").
Ramsay JO, Silverman BW (2005). "Functional Data Analysis." 2nd ed. Springer.
fPCA() for computing fPCA results,
reconstructFPCA() for waveform reconstruction.
Plots waveforms normalized to gait cycle (0-100%) with options for displaying multiple trials, mean, and variability bands.
plotGaitCycle( x, events = NULL, normalize_to = 101, show_events = TRUE, show_mean = TRUE, show_sd = TRUE, show_individual = TRUE, event_labels = c(HS = 0, TO = 60, HS = 100), title = "Gait Cycle", ylab = "Value" )plotGaitCycle( x, events = NULL, normalize_to = 101, show_events = TRUE, show_mean = TRUE, show_sd = TRUE, show_individual = TRUE, event_labels = c(HS = 0, TO = 60, HS = 100), title = "Gait Cycle", ylab = "Value" )
x |
A PhysioExperiment, matrix, or list of matrices. |
events |
Optional data.frame with gait events (heel strike, toe off). |
normalize_to |
Length to normalize (default: 101 for 0-100%). |
show_events |
Logical; show vertical lines at gait events. |
show_mean |
Logical; show mean waveform. |
show_sd |
Logical; show SD bands. |
show_individual |
Logical; show individual trials. |
event_labels |
Labels for gait events. |
title |
Plot title. |
ylab |
Y-axis label. |
A ggplot object.
Wickham H (2016). "ggplot2: Elegant Graphics for Data Analysis." Springer.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
plotWaveformComparison() for multi-group comparisons,
plotSpaghetti() for individual waveform overlays,
calculateGaitParameters() for computing gait metrics.
# Normalize and plot knee angle across gait cycle set.seed(123) data <- sapply(1:10, function(i) { n <- sample(90:110, 1) # Variable cycle length sin(seq(0, 2*pi, length.out = n)) * 60 + rnorm(n, 0, 3) }) plotGaitCycle(data, show_mean = TRUE, show_sd = TRUE, ylab = "Knee Flexion (deg)")# Normalize and plot knee angle across gait cycle set.seed(123) data <- sapply(1:10, function(i) { n <- sample(90:110, 1) # Variable cycle length sin(seq(0, 2*pi, length.out = n)) * 60 + rnorm(n, 0, 3) }) plotGaitCycle(data, show_mean = TRUE, show_sd = TRUE, ylab = "Knee Flexion (deg)")
Compares waveforms between groups with schema-aware formatting.
plotGroupComparison( x, groups, schema = NULL, events = NULL, show_individual = FALSE, ci = 0.95, xlab = NULL, ylab = "Value", title = NULL, group_colors = NULL, ... )plotGroupComparison( x, groups, schema = NULL, events = NULL, show_individual = FALSE, ci = 0.95, xlab = NULL, ylab = "Value", title = NULL, group_colors = NULL, ... )
x |
Normalized data (matrix: time x samples) |
groups |
Factor or character vector indicating group membership |
schema |
TaskSchema object |
events |
Optional detected_events |
show_individual |
Show individual waveforms |
ci |
Confidence interval level |
xlab |
X-axis label |
ylab |
Y-axis label |
title |
Plot title |
group_colors |
Named vector of colors for groups |
... |
Additional arguments |
A ggplot object
Wickham H (2016). "ggplot2: Elegant Graphics for Data Analysis." Springer.
plotCycle() for single-group cycle visualization,
plotWaveformComparison() for alternative group comparison plots.
Creates a faceted plot showing multiple channels or variables.
plotMultiPanel( x, schema = NULL, channels = NULL, facet_scales = "free_y", show_mean = TRUE, show_sd = TRUE, ... )plotMultiPanel( x, schema = NULL, channels = NULL, facet_scales = "free_y", show_mean = TRUE, show_sd = TRUE, ... )
x |
Normalized data (matrix or 3D array) |
schema |
TaskSchema object |
channels |
Channels to plot (indices or names) |
facet_scales |
Scales for faceting ("free_y", "fixed", etc.) |
show_mean |
Show mean across trials |
show_sd |
Show SD bands |
... |
Additional arguments passed to plotCycle |
A ggplot object
Wickham H (2016). "ggplot2: Elegant Graphics for Data Analysis." Springer.
plotCycle() for single-channel cycle visualization,
plotGroupComparison() for between-group comparisons.
Creates a scatter plot of PCA scores.
plotPCAScatter(x, components = c(1, 2), groups = NULL, labels = NULL)plotPCAScatter(x, components = c(1, 2), groups = NULL, labels = NULL)
x |
A waveform_pca object. |
components |
Which PCs to plot (length 2). |
groups |
Optional grouping factor for coloring. |
labels |
Optional labels for points. |
A ggplot object.
van der Maaten L, Hinton G (2008). "Visualizing Data using t-SNE." Journal of Machine Learning Research, 9, 2579-2605.
waveformPCA(), plotPCAVariance(), plotUMAP()
Creates a scree plot showing variance explained by each PC.
plotPCAVariance(x, n_components = NULL)plotPCAVariance(x, n_components = NULL)
x |
A waveform_pca object. |
n_components |
Number of components to show. |
A ggplot object.
van der Maaten L, Hinton G (2008). "Visualizing Data using t-SNE." Journal of Machine Learning Research, 9, 2579-2605.
waveformPCA(), plotPCAScatter(), plotUMAP()
Visualizes phase durations across conditions or groups.
plotPhaseDurations( phases_list, labels = NULL, unit = c("percent", "seconds"), show_values = TRUE, title = "Phase Durations", ... )plotPhaseDurations( phases_list, labels = NULL, unit = c("percent", "seconds"), show_values = TRUE, title = "Phase Durations", ... )
phases_list |
List of segmented_phases objects or timing data.frames |
labels |
Labels for each entry |
unit |
"percent" or "seconds" |
show_values |
Show duration values on bars |
title |
Plot title |
... |
Additional arguments |
A ggplot object
Wickham H (2016). "ggplot2: Elegant Graphics for Data Analysis." Springer.
plotCycle() for cycle-normalized waveform visualization,
calculateGaitParameters() for computing gait phase parameters.
Creates a phase portrait (angle vs angular velocity) for analyzing movement dynamics and coordination patterns.
plotPhasePortrait( angle, velocity = NULL, sampling_rate = 100, groups = NULL, normalize = FALSE, title = "Phase Portrait" )plotPhasePortrait( angle, velocity = NULL, sampling_rate = 100, groups = NULL, normalize = FALSE, title = "Phase Portrait" )
angle |
Angle time series (vector or matrix). |
velocity |
Angular velocity. If NULL, computed from angle. |
sampling_rate |
Sampling rate (needed if velocity computed). |
groups |
Optional grouping factor. |
normalize |
Logical; normalize to unit circle. |
title |
Plot title. |
A ggplot object.
Wickham H (2016). "ggplot2: Elegant Graphics for Data Analysis." Springer.
computeVelocity() for computing angular velocities from position data,
plotGaitCycle() for time-domain gait cycle visualization.
# Phase portrait of knee angle set.seed(123) t <- seq(0, 2*pi, length.out = 100) angle <- sin(t) * 60 velocity <- cos(t) * 60 * (2*pi/100) # Derivative plotPhasePortrait(angle, velocity)# Phase portrait of knee angle set.seed(123) t <- seq(0, 2*pi, length.out = 100) angle <- sin(t) * 60 velocity <- cos(t) * 60 * (2*pi/100) # Derivative plotPhasePortrait(angle, velocity)
Draws a single frame from a PhysioExperiment as a 2D stick figure by projecting 3D marker positions onto an anatomical plane.
plotSkeleton( pe, skeleton, frame = 1, plane = c("sagittal", "frontal", "transverse"), show_labels = FALSE, show_confidence = FALSE, point_size = 3, segment_color = "gray40", title = NULL )plotSkeleton( pe, skeleton, frame = 1, plane = c("sagittal", "frontal", "transverse"), show_labels = FALSE, show_confidence = FALSE, point_size = 3, segment_color = "gray40", title = NULL )
pe |
A PhysioExperiment object with |
skeleton |
A |
frame |
Integer frame (row) index to plot (default 1). |
plane |
Anatomical plane for projection: |
show_labels |
Logical; annotate markers with their labels. |
show_confidence |
Logical; color markers by confidence if a
|
point_size |
Marker point size (default 3). |
segment_color |
Color for bone segments (default |
title |
Plot title. If |
A ggplot object.
Wickham H (2016). "ggplot2: Elegant Graphics for Data Analysis." Springer.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
plotSkeletonSequence() for multi-frame faceted display,
plotSkeletonOverlay() for overlaid motion visualization,
plotSkeleton3D() for pseudo-3D rendering,
projectTo2D() for coordinate projection utilities.
## Not run: pe <- readOpenPose("frames/", model = "BODY_25") sk <- define_skeleton("BODY_25") plotSkeleton(pe, sk, frame = 1, plane = "frontal") ## End(Not run)## Not run: pe <- readOpenPose("frames/", model = "BODY_25") sk <- define_skeleton("BODY_25") plotSkeleton(pe, sk, frame = 1, plane = "frontal") ## End(Not run)
Renders one frame of a skeleton in a perspective-like 3D projection using a lightweight base graphics backend (no external 3D dependency required).
plotSkeleton3D( pe, skeleton, frame = 1, azimuth = 35, elevation = 20, distance = 6, show_labels = FALSE, point_col = "steelblue", segment_col = "gray40", point_cex = 1.1, segment_lwd = 1.5, main = NULL, draw = TRUE )plotSkeleton3D( pe, skeleton, frame = 1, azimuth = 35, elevation = 20, distance = 6, show_labels = FALSE, point_col = "steelblue", segment_col = "gray40", point_cex = 1.1, segment_lwd = 1.5, main = NULL, draw = TRUE )
pe |
A PhysioExperiment object with |
skeleton |
A |
frame |
Integer frame index. |
azimuth |
View azimuth angle in degrees. |
elevation |
View elevation angle in degrees. |
distance |
Perspective distance (larger = weaker perspective). |
show_labels |
Logical; if |
point_col |
Point color. |
segment_col |
Segment color. |
point_cex |
Point size. |
segment_lwd |
Segment line width. |
main |
Plot title. If |
draw |
Logical; if |
Invisibly returns a list with projected coordinates and view parameters.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
plotSkeleton() for 2D skeleton visualization,
projectTo2D() for manual coordinate projection.
## Not run: pe <- readOpenPose("frames/", model = "BODY_25") sk <- define_skeleton("BODY_25") plotSkeleton3D(pe, sk, frame = 10, azimuth = 35, elevation = 20) ## End(Not run)## Not run: pe <- readOpenPose("frames/", model = "BODY_25") sk <- define_skeleton("BODY_25") plotSkeleton3D(pe, sk, frame = 10, azimuth = 35, elevation = 20) ## End(Not run)
Draws multiple frames on the same plot. Earlier frames are rendered with
lower opacity when alpha_decay = TRUE.
plotSkeletonOverlay( pe, skeleton, frames, plane = c("sagittal", "frontal", "transverse"), alpha_decay = TRUE, base_alpha = 0.2, show_labels = FALSE, point_size = 3, segment_color = "gray40", title = NULL )plotSkeletonOverlay( pe, skeleton, frames, plane = c("sagittal", "frontal", "transverse"), alpha_decay = TRUE, base_alpha = 0.2, show_labels = FALSE, point_size = 3, segment_color = "gray40", title = NULL )
pe |
A PhysioExperiment object with |
skeleton |
A |
frames |
Integer vector of frame indices to overlay. |
plane |
Anatomical plane for projection: |
alpha_decay |
Logical; if |
base_alpha |
Minimum alpha for the earliest frame (default 0.2). |
show_labels |
Logical; annotate markers with their labels. |
point_size |
Marker point size (default 3). |
segment_color |
Color for bone segments (default |
title |
Plot title. If |
A ggplot object.
Wickham H (2016). "ggplot2: Elegant Graphics for Data Analysis." Springer.
plotSkeleton() for single-frame skeleton visualization,
plotSkeletonSequence() for multi-frame faceted display.
## Not run: pe <- readOpenPose("frames/", model = "BODY_25") sk <- define_skeleton("BODY_25") plotSkeletonOverlay(pe, sk, frames = c(1, 5, 10, 15, 20)) ## End(Not run)## Not run: pe <- readOpenPose("frames/", model = "BODY_25") sk <- define_skeleton("BODY_25") plotSkeletonOverlay(pe, sk, frames = c(1, 5, 10, 15, 20)) ## End(Not run)
Creates a multi-panel faceted plot showing the skeleton at several frames.
plotSkeletonSequence( pe, skeleton, frames, plane = c("sagittal", "frontal", "transverse"), ncol = 3, show_labels = FALSE, show_confidence = FALSE, point_size = 2, segment_color = "gray40", title = NULL )plotSkeletonSequence( pe, skeleton, frames, plane = c("sagittal", "frontal", "transverse"), ncol = 3, show_labels = FALSE, show_confidence = FALSE, point_size = 2, segment_color = "gray40", title = NULL )
pe |
A PhysioExperiment object with |
skeleton |
A |
frames |
Integer vector of frame indices to plot. |
plane |
Anatomical plane for projection: |
ncol |
Number of columns in the faceted layout (default 3). |
show_labels |
Logical; annotate markers with their labels. |
show_confidence |
Logical; color markers by confidence if a
|
point_size |
Marker point size (default 3). |
segment_color |
Color for bone segments (default |
title |
Plot title. If |
A ggplot object with facets.
Wickham H (2016). "ggplot2: Elegant Graphics for Data Analysis." Springer.
plotSkeleton() for single-frame skeleton visualization,
plotSkeletonOverlay() for overlaid frames on a single plot.
## Not run: pe <- readOpenPose("frames/", model = "BODY_25") sk <- define_skeleton("BODY_25") plotSkeletonSequence(pe, sk, frames = c(1, 10, 20), ncol = 3) ## End(Not run)## Not run: pe <- readOpenPose("frames/", model = "BODY_25") sk <- define_skeleton("BODY_25") plotSkeletonSequence(pe, sk, frames = c(1, 10, 20), ncol = 3) ## End(Not run)
Creates a spaghetti plot showing individual subject waveforms with a highlighted mean trajectory.
plotSpaghetti( x, time_axis = NULL, highlight_mean = TRUE, individual_color = "gray60", mean_color = "red", alpha = 0.4, title = NULL, xlab = "Time", ylab = "Value" )plotSpaghetti( x, time_axis = NULL, highlight_mean = TRUE, individual_color = "gray60", mean_color = "red", alpha = 0.4, title = NULL, xlab = "Time", ylab = "Value" )
x |
A PhysioExperiment or matrix (time x observations). |
time_axis |
Optional time axis values. |
highlight_mean |
Logical; highlight mean with thick line. |
individual_color |
Color for individual lines. |
mean_color |
Color for mean line. |
alpha |
Transparency for individual lines. |
title |
Plot title. |
xlab |
X-axis label. |
ylab |
Y-axis label. |
A ggplot object.
Wickham H (2016). "ggplot2: Elegant Graphics for Data Analysis." Springer.
plotGaitCycle() for gait cycle visualization with event markers,
plotWaveformComparison() for multi-group waveform comparisons.
Creates a symmetry plot comparing bilateral waveforms, useful for gait symmetry analysis.
plotSymmetry( left, right, time_axis = NULL, ci = 0.95, show_diagonal = TRUE, plot_type = c("overlay", "scatter"), title = "Symmetry Analysis" )plotSymmetry( left, right, time_axis = NULL, ci = 0.95, show_diagonal = TRUE, plot_type = c("overlay", "scatter"), title = "Symmetry Analysis" )
left |
Matrix of left side waveforms (time x observations). |
right |
Matrix of right side waveforms (time x observations). |
time_axis |
Optional time axis values. |
ci |
Confidence interval level. |
show_diagonal |
Logical; show y=x diagonal reference line. |
plot_type |
"overlay" for time series, "scatter" for L vs R scatter. |
title |
Plot title. |
A ggplot object.
Wickham H (2016). "ggplot2: Elegant Graphics for Data Analysis." Springer.
plotWaveformComparison() for multi-group waveform comparisons,
calculateStepSymmetry() for quantifying gait symmetry,
symmetryIndex() for computing symmetry indices.
# Compare left and right knee angles set.seed(123) t <- seq(0, 100, length.out = 101) left <- sapply(1:20, function(i) sin(2*pi*t/100) * 30 + rnorm(101, 0, 2)) right <- sapply(1:20, function(i) sin(2*pi*t/100) * 28 + rnorm(101, 0, 2)) # Slight asymmetry plotSymmetry(left, right, time_axis = t, plot_type = "overlay")# Compare left and right knee angles set.seed(123) t <- seq(0, 100, length.out = 101) left <- sapply(1:20, function(i) sin(2*pi*t/100) * 30 + rnorm(101, 0, 2)) right <- sapply(1:20, function(i) sin(2*pi*t/100) * 28 + rnorm(101, 0, 2)) # Slight asymmetry plotSymmetry(left, right, time_axis = t, plot_type = "overlay")
Plots 2D trajectory, useful for balance (CoP) or cutting (CoM) analysis.
plotTrajectory( x, y, schema = NULL, show_path = TRUE, show_points = FALSE, show_ellipse = TRUE, ellipse_ci = 0.95, show_start_end = TRUE, color_by = NULL, xlab = NULL, ylab = NULL, title = NULL, ... )plotTrajectory( x, y, schema = NULL, show_path = TRUE, show_points = FALSE, show_ellipse = TRUE, ellipse_ci = 0.95, show_start_end = TRUE, color_by = NULL, xlab = NULL, ylab = NULL, title = NULL, ... )
x |
X-coordinate data |
y |
Y-coordinate data |
schema |
TaskSchema object |
show_path |
Show trajectory path |
show_points |
Show individual points |
show_ellipse |
Show confidence ellipse |
ellipse_ci |
Confidence level for ellipse |
show_start_end |
Mark start and end points |
color_by |
Optional variable for coloring (e.g., time) |
xlab |
X-axis label |
ylab |
Y-axis label |
title |
Plot title |
... |
Additional arguments |
A ggplot object
Wickham H (2016). "ggplot2: Elegant Graphics for Data Analysis." Springer.
plotSkeleton() for full-body skeleton visualization,
plotPhasePortrait() for phase-space trajectory plots.
Creates a scatter plot of UMAP embedding.
plotUMAP(x, groups = NULL, labels = NULL)plotUMAP(x, groups = NULL, labels = NULL)
x |
A waveform_umap object. |
groups |
Optional grouping factor. |
labels |
Optional point labels. |
A ggplot object.
van der Maaten L, Hinton G (2008). "Visualizing Data using t-SNE." Journal of Machine Learning Research, 9, 2579-2605.
waveformUMAP(), plotPCAScatter(), waveformPCA()
Visualization functions designed for biomechanical waveform analysis including group comparisons, gait cycle plots, and symmetry analysis. Plot waveform comparison across groups
plotWaveformComparison( x, groups, channel = 1L, ci = 0.95, show_individual = FALSE, time_axis = NULL, colors = NULL, title = NULL, xlab = "Time", ylab = "Value" )plotWaveformComparison( x, groups, channel = 1L, ci = 0.95, show_individual = FALSE, time_axis = NULL, colors = NULL, title = NULL, xlab = "Time", ylab = "Value" )
x |
A PhysioExperiment object or matrix (time x observations). |
groups |
Factor or vector indicating group membership. |
channel |
For PhysioExperiment with multiple channels, which to plot. |
ci |
Confidence interval level (default: 0.95). |
show_individual |
Logical; show individual waveforms as thin lines. |
time_axis |
Optional time axis values (e.g., 0-100 for gait cycle). |
colors |
Optional color palette for groups. |
title |
Plot title. |
xlab |
X-axis label. |
ylab |
Y-axis label. |
Creates a comparison plot showing mean waveforms with confidence bands for multiple groups. Ideal for comparing gait patterns between conditions.
A ggplot object.
Wickham H (2016). "ggplot2: Elegant Graphics for Data Analysis." Springer.
plotGaitCycle() for single-group gait cycle visualization,
plotSymmetry() for left-right symmetry plots,
plotSpaghetti() for individual waveform overlay plots.
# Compare gait patterns between groups set.seed(123) # Control group control <- sapply(1:15, function(i) sin(seq(0, 2*pi, length.out = 101)) * 30 + rnorm(101, 0, 3)) # Patient group (reduced range of motion) patient <- sapply(1:15, function(i) sin(seq(0, 2*pi, length.out = 101)) * 20 + rnorm(101, 0, 3)) data <- cbind(control, patient) groups <- factor(rep(c("Control", "Patient"), each = 15)) plotWaveformComparison(data, groups, time_axis = 0:100, xlab = "Gait Cycle (%)", ylab = "Knee Angle (deg)")# Compare gait patterns between groups set.seed(123) # Control group control <- sapply(1:15, function(i) sin(seq(0, 2*pi, length.out = 101)) * 30 + rnorm(101, 0, 3)) # Patient group (reduced range of motion) patient <- sapply(1:15, function(i) sin(seq(0, 2*pi, length.out = 101)) * 20 + rnorm(101, 0, 3)) data <- cbind(control, patient) groups <- factor(rep(c("Control", "Patient"), each = 15)) plotWaveformComparison(data, groups, time_axis = 0:100, xlab = "Gait Cycle (%)", ylab = "Knee Angle (deg)")
Print method for ASFSkeleton objects
## S3 method for class 'ASFSkeleton' print(x, ...)## S3 method for class 'ASFSkeleton' print(x, ...)
x |
An |
... |
Additional arguments (ignored). |
Invisibly returns x.
CMU Graphics Lab (2003). "CMU Motion Capture Database." http://mocap.cs.cmu.edu/.
readASF() for reading ASF skeleton files,
readAMC() for reading AMC motion data.
Print benchmark agreement summary
## S3 method for class 'benchmark_agreement' print(x, ...)## S3 method for class 'benchmark_agreement' print(x, ...)
x |
A |
... |
Additional arguments (unused). |
Invisibly returns x.
Shrout PE, Fleiss JL (1979). "Intraclass Correlations: Uses in Assessing Rater Reliability." Psychological Bulletin, 86(2), 420-428.
benchmarkAgreement() for computing agreement metrics.
Print benchmark manifest validation result
## S3 method for class 'benchmark_manifest_validation' print(x, ...)## S3 method for class 'benchmark_manifest_validation' print(x, ...)
x |
A |
... |
Additional arguments (unused). |
Invisibly returns x.
Bland JM, Altman DG (1986). "Statistical Methods for Assessing Agreement Between Two Methods of Clinical Measurement." Lancet, 327(8476), 307-310.
validateBenchmarkManifest() for performing manifest validation.
Print benchmark suite summary
## S3 method for class 'benchmark_suite' print(x, ...)## S3 method for class 'benchmark_suite' print(x, ...)
x |
A |
... |
Additional arguments (unused). |
Invisibly returns x.
Shrout PE, Fleiss JL (1979). "Intraclass Correlations: Uses in Assessing Rater Reliability." Psychological Bulletin, 86(2), 420-428.
runBenchmarkSuite() for running the benchmark suite.
Print method for detected events
## S3 method for class 'detected_events' print(x, ...)## S3 method for class 'detected_events' print(x, ...)
x |
A detected_events object |
... |
Additional arguments (unused) |
Print DTW clustering result
## S3 method for class 'dtw_clustering' print(x, ...)## S3 method for class 'dtw_clustering' print(x, ...)
x |
A dtw_clustering object |
... |
Additional arguments (unused) |
Print DTW result
## S3 method for class 'dtw_result' print(x, ...)## S3 method for class 'dtw_result' print(x, ...)
x |
A dtw_result object |
... |
Additional arguments (unused) |
Print a forceplate analysis summary
## S3 method for class 'forceplate_analysis' print(x, ...)## S3 method for class 'forceplate_analysis' print(x, ...)
x |
A |
... |
Additional arguments (ignored). |
Invisibly returns x.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
analyzeForcePlate() for performing force plate analysis,
analyzeForcePlatePE() for PhysioExperiment-based analysis.
Print a multi-plate forceplate analysis summary
## S3 method for class 'forceplate_analysis_multi' print(x, ...)## S3 method for class 'forceplate_analysis_multi' print(x, ...)
x |
A |
... |
Additional arguments (ignored). |
Invisibly returns x.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
analyzeForcePlatePE() for multi-plate force plate analysis,
print.forceplate_analysis() for single-plate result display.
Print fPCA result
## S3 method for class 'fpca_result' print(x, ...)## S3 method for class 'fpca_result' print(x, ...)
x |
An fpca_result object |
... |
Additional arguments (unused) |
Ramsay JO, Silverman BW (2005). "Functional Data Analysis." 2nd ed. Springer.
fPCA() for performing functional principal component analysis,
plotFPCA() for visualization of fPCA results,
reconstructFPCA() for waveform reconstruction from fPCA scores.
S3 print method showing mean +/- SD for each parameter.
## S3 method for class 'gait_parameters' print(x, ...)## S3 method for class 'gait_parameters' print(x, ...)
x |
A |
... |
Additional arguments (unused). |
Perry J, Burnfield JM (2010). "Gait Analysis: Normal and Pathological Function." 2nd ed. SLACK Incorporated.
calculateGaitParameters() for computing gait parameters,
summarizeGaitParameters() for descriptive statistics.
Print a quick-start summary
## S3 method for class 'mocap_quickstart' print(x, ...)## S3 method for class 'mocap_quickstart' print(x, ...)
x |
A |
... |
Additional arguments (unused). |
Invisibly returns x.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
quickStartMoCap() for the complete getting-started workflow.
Print a MoCap readiness report
## S3 method for class 'mocap_readiness' print(x, ...)## S3 method for class 'mocap_readiness' print(x, ...)
x |
A |
... |
Additional arguments (unused). |
Invisibly returns x.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
assessMoCapReadiness() for computing the readiness report.
Print method for multi-trial phases
## S3 method for class 'multi_trial_phases' print(x, ...)## S3 method for class 'multi_trial_phases' print(x, ...)
x |
A multi_trial_phases object |
... |
Additional arguments (unused) |
Print method for segmented phases
## S3 method for class 'segmented_phases' print(x, ...)## S3 method for class 'segmented_phases' print(x, ...)
x |
A segmented_phases object |
... |
Additional arguments (unused) |
Print a SkeletonModel object
## S3 method for class 'SkeletonModel' print(x, ...)## S3 method for class 'SkeletonModel' print(x, ...)
x |
A |
... |
Additional arguments (ignored). |
Invisibly returns x.
Print waveform PCA result
## S3 method for class 'waveform_pca' print(x, ...)## S3 method for class 'waveform_pca' print(x, ...)
x |
A waveform_pca object |
... |
Additional arguments (unused) |
Print waveform UMAP result
## S3 method for class 'waveform_umap' print(x, ...)## S3 method for class 'waveform_umap' print(x, ...)
x |
A waveform_umap object |
... |
Additional arguments (unused) |
Applies optional band-pass filtering, rectification, RMS envelope extraction, optional low-pass smoothing, and optional MVC normalization.
processEMG( x, sampling_rate, bandpass = c(20, 450), envelope_cutoff = 6, rms_window_ms = 50, mvc = NULL, filter_method = c("butterworth", "moving_average") )processEMG( x, sampling_rate, bandpass = c(20, 450), envelope_cutoff = 6, rms_window_ms = 50, mvc = NULL, filter_method = c("butterworth", "moving_average") )
x |
Numeric vector or matrix (time x channels). |
sampling_rate |
Sampling rate in Hz. |
bandpass |
Optional length-2 numeric vector (Hz). If |
envelope_cutoff |
Low-pass cutoff (Hz) applied to RMS envelope. |
rms_window_ms |
RMS window length in milliseconds. |
mvc |
Optional MVC value(s) for normalization. |
filter_method |
Filter method used in low-pass steps. |
A list with filtered, rectified, envelope, and
(when mvc is provided) normalized.
Merletti R, Parker PA (2004). "Electromyography: Physiology, Engineering, and Non-Invasive Applications." IEEE Press/Wiley.
rectifyEMG() for signal rectification,
computeRMSEnvelope() for RMS envelope computation,
normalizeEMG() for MVC or peak normalization,
integrateEMGMoCap() for EMG-MoCap data integration.
set.seed(1) emg <- matrix(rnorm(2000), ncol = 2) out <- processEMG(emg, sampling_rate = 1000)set.seed(1) emg <- matrix(rnorm(2000), ncol = 2) out <- processEMG(emg, sampling_rate = 1000)
Selects two of three coordinate axes based on the anatomical plane,
returning a data frame with u (horizontal) and v (vertical) columns.
projectTo2D(x, y, z, plane = c("sagittal", "frontal", "transverse"))projectTo2D(x, y, z, plane = c("sagittal", "frontal", "transverse"))
x |
Numeric vector of X (medial-lateral) coordinates. |
y |
Numeric vector of Y (anterior-posterior) coordinates. |
z |
Numeric vector of Z (vertical) coordinates. |
plane |
Character string specifying the projection plane.
One of |
A data frame with columns u and v.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
plotSkeleton() for 2D skeleton visualization,
plotSkeleton3D() for pseudo-3D skeleton rendering.
proj <- projectTo2D(c(1, 2), c(3, 4), c(5, 6), plane = "sagittal") proj$u # Y values (anterior-posterior) proj$v # Z values (vertical)proj <- projectTo2D(c(1, 2), c(3, 4), c(5, 6), plane = "sagittal") proj$u # Y values (anterior-posterior) proj$v # Z values (vertical)
Converts a quaternion (w, x, y, z) representation to Euler angles (roll, pitch, yaw) using the specified rotation order.
quaternionToEuler(w, x, y, z, order = "ZYX", degrees = TRUE)quaternionToEuler(w, x, y, z, order = "ZYX", degrees = TRUE)
w |
Numeric. Scalar (real) part of the quaternion. |
x |
Numeric. First imaginary component. |
y |
Numeric. Second imaginary component. |
z |
Numeric. Third imaginary component. |
order |
Character. Rotation order. Default |
degrees |
Logical. If |
For the "ZYX" (Tait-Bryan) convention:
roll = rotation about X axis
pitch = rotation about Y axis
yaw = rotation about Z axis
The quaternion is assumed to be unit (normalized). If not unit, it is normalized internally before conversion.
A matrix with columns roll, pitch, yaw. If inputs
are scalars, returns a 1-row matrix. If inputs are vectors,
returns a matrix with one row per element.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
Grood ES, Suntay WJ (1983). "A joint coordinate system for the clinical description of three-dimensional motions: application to the knee." Journal of Biomechanical Engineering, 105(2), 136-144.
eulerToQuaternion(), calculateJointAngles(), vectorAngle()
# Identity quaternion -> zero Euler angles quaternionToEuler(1, 0, 0, 0) # 90-degree rotation about Z axis quaternionToEuler(cos(pi/4), 0, 0, sin(pi/4))# Identity quaternion -> zero Euler angles quaternionToEuler(1, 0, 0, 0) # 90-degree rotation about Z axis quaternionToEuler(cos(pi/4), 0, 0, sin(pi/4))
Runs a compact end-to-end pipeline for first-time users: kinematics derivatives, readiness scoring, and optional force-plate, inverse-dynamics, and EMG modules.
quickStartMoCap( n_frames = 300, sampling_rate = NULL, emg_sampling_rate = 1000, seed = 123, mocap = NULL, path = NULL, format = c("auto", "csv", "c3d", "trc", "bvh", "amc"), forces = NULL, joints = NULL, joint_angles = NULL, emg = NULL )quickStartMoCap( n_frames = 300, sampling_rate = NULL, emg_sampling_rate = 1000, seed = 123, mocap = NULL, path = NULL, format = c("auto", "csv", "c3d", "trc", "bvh", "amc"), forces = NULL, joints = NULL, joint_angles = NULL, emg = NULL )
n_frames |
Number of MoCap frames for demo mode. |
sampling_rate |
MoCap sampling rate in Hz. In non-demo mode, if |
emg_sampling_rate |
EMG sampling rate in Hz. |
seed |
Random seed for reproducibility in demo mode. |
mocap |
Optional |
path |
Optional file path to load via |
format |
Format hint passed to |
forces |
Optional force matrix/data.frame for force-plate analysis. |
joints |
Optional joint-center data for inverse dynamics. |
joint_angles |
Optional joint-angle data for inverse dynamics. |
emg |
Optional EMG matrix for EMG processing. |
If mocap or path is omitted, synthetic demo data are generated.
An object of class "mocap_quickstart" containing generated outputs,
readiness report, and notes for skipped/failed optional modules.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
demoMoCapData() for generating demo data without analysis,
assessMoCapReadiness() for data quality assessment,
print.mocap_quickstart() for formatted display of results.
qs <- quickStartMoCap(seed = 1) qsqs <- quickStartMoCap(seed = 1) qs
Parses an Acclaim Motion Capture (AMC) file containing frame-by-frame joint angle data. AMC files store joint angles per frame, with each frame listing joint names followed by their DOF values. An optional ASF skeleton can be provided for validation and DOF mapping.
readAMC(path, asf = NULL, fps = 120)readAMC(path, asf = NULL, fps = 120)
path |
Character string giving the path to the |
asf |
An |
fps |
Numeric frame rate in Hz. AMC files do not store frame rate, so this must be specified (default: 120). |
A PhysioExperiment object with:
rotation_x, rotation_y, rotation_z for all joints;
position_x, position_y, position_z for the root joint only.
DataFrame with label (joint names), type
("root" or "joint"), and dof_count (number of DOFs).
List with asf_skeleton (if provided), source_file,
and units (from ASF if provided).
Set to fps.
CMU Graphics Lab (2003). "CMU Motion Capture Database." http://mocap.cs.cmu.edu/.
readASF() for reading skeleton definitions in ASF format,
readMoCapCSV() for reading motion capture data from CSV files.
asf_file <- system.file("testdata", "sample.asf", package = "PhysioMoCap") amc_file <- system.file("testdata", "sample.amc", package = "PhysioMoCap") if (nzchar(asf_file) && nzchar(amc_file)) { skel <- readASF(asf_file) pe <- readAMC(amc_file, asf = skel) pe }asf_file <- system.file("testdata", "sample.asf", package = "PhysioMoCap") amc_file <- system.file("testdata", "sample.amc", package = "PhysioMoCap") if (nzchar(asf_file) && nzchar(amc_file)) { skel <- readASF(asf_file) pe <- readAMC(amc_file, asf = skel) pe }
Parses an Acclaim Skeleton File (ASF) that defines the skeleton hierarchy, bone properties, and degrees of freedom. ASF files contain sections for units, root configuration, bone data, and hierarchy relationships.
readASF(path)readASF(path)
path |
Character string giving the path to the |
An S3 object of class "ASFSkeleton" with components:
Named list of unit definitions (mass, length, angle).
List with root joint configuration: position, orientation, order, and axis.
Named list of bone definitions, each with id, name, direction, length, axis, dof, and limits.
Named list mapping parent joint names to character vectors of child joint names.
CMU Graphics Lab (2003). "CMU Motion Capture Database." http://mocap.cs.cmu.edu/.
readAMC() for reading motion data in AMC format,
print.ASFSkeleton() for displaying skeleton structure.
asf_file <- system.file("testdata", "sample.asf", package = "PhysioMoCap") if (nzchar(asf_file)) { skel <- readASF(asf_file) skel }asf_file <- system.file("testdata", "sample.asf", package = "PhysioMoCap") if (nzchar(asf_file)) { skel <- readASF(asf_file) skel }
Reads a BVH (Biovision Hierarchy) file containing skeleton animation data. BVH files have two sections: HIERARCHY (joint tree structure with offsets and channel definitions) and MOTION (frame data). The ROOT joint has 6 channels (3 position + 3 rotation), while child JOINTs have 3 channels (rotation only).
readBVH(path)readBVH(path)
path |
Character string giving the path to the |
A PhysioExperiment object with rotation assays (rotation_x,
rotation_y, rotation_z) for all joints, and position assays
(position_x, position_y, position_z) for the root joint.
colData includes joint names (label), channel type (type), and
parent_joint. metadata includes bvh_skeleton (hierarchy tree),
rotation_order, frame_time, offsets, and source_file.
samplingRate is computed as 1 / frame_time.
Meredith M, Maddock S (2001). "Motion Capture File Formats Explained." Department of Computer Science, University of Sheffield.
readC3D(), readTRC(), readOpenPose()
bvh_file <- system.file("testdata", "sample.bvh", package = "PhysioMoCap") if (nzchar(bvh_file)) { pe <- readBVH(bvh_file) pe }bvh_file <- system.file("testdata", "sample.bvh", package = "PhysioMoCap") if (nzchar(bvh_file)) { pe <- readBVH(bvh_file) pe }
Reads a C3D file containing 3D marker position data using the c3dr package. C3D is a widely used binary format for storing biomechanical motion capture data including point (marker) positions and optional analog channel data (e.g., force plate signals).
readC3D(path, include_analog = FALSE)readC3D(path, include_analog = FALSE)
path |
Character string giving the path to the |
include_analog |
Logical; if |
A PhysioExperiment object with three assays: "position_x",
"position_y", and "position_z", each a matrix with rows as time
frames and columns as markers. If the C3D file contains residual data,
a "quality" assay is also included. Column metadata (colData)
contains label (marker names from POINT:LABELS), type ("marker"),
and body_segment (NA). Metadata includes c3d_parameters,
source_file, and a time vector computed from frame rate.
C3D.org. "The C3D File Format." https://www.c3d.org/.
readTRC(), readBVH(), readOpenPose()
if (requireNamespace("c3dr", quietly = TRUE)) { c3d_file <- c3dr::c3d_example() pe <- readC3D(c3d_file) pe }if (requireNamespace("c3dr", quietly = TRUE)) { c3d_file <- c3dr::c3d_example() pe <- readC3D(c3d_file) pe }
Reads DeepLabCut (DLC) pose estimation output from CSV or HDF5 format and returns a PhysioExperiment object with keypoint coordinates and confidence scores.
readDeepLabCut(path, fps = 30, format = c("csv", "h5"))readDeepLabCut(path, fps = 30, format = c("csv", "h5"))
path |
Path to a DeepLabCut output file (CSV or H5). |
fps |
Frame rate in Hz (frames per second). Default 30. DeepLabCut does not store frame rate in its output, so this must be specified by the user. |
format |
File format: |
DeepLabCut outputs pose estimation results in CSV or HDF5 format.
CSV format has a 3-row multi-level header:
Row 1: scorer name (the DLC model name)
Row 2: bodypart names
Row 3: coordinate type (x, y, likelihood)
Followed by numeric data where each row is a frame and columns are
grouped as [x, y, likelihood] triplets per bodypart.
H5 format stores data in a hierarchical HDF5 structure under
df_with_missing/table. Requires the rhdf5 package.
A PhysioExperiment with assays:
X coordinates matrix (frames x bodyparts)
Y coordinates matrix (frames x bodyparts)
Detection likelihood matrix (frames x bodyparts)
The colData contains columns label (bodypart names), type
("keypoint"), and scorer (the DLC scorer/model name).
The metadata list contains dlc_scorer, format, and source_file.
Mathis A, Mamidanna P, Cury KM, Abe T, Murthy VN, Mathis MW, Bethge M (2018). "DeepLabCut: markerless pose estimation of user-defined body parts with deep learning." Nature Neuroscience, 21(9), 1281-1289.
readOpenPose(), readMediaPipe(), readOpenCap()
## Not run: # Read DeepLabCut CSV output pe <- readDeepLabCut("path/to/DLC_output.csv", fps = 30) # Read HDF5 format pe <- readDeepLabCut("path/to/DLC_output.h5", fps = 25, format = "h5") ## End(Not run)## Not run: # Read DeepLabCut CSV output pe <- readDeepLabCut("path/to/DLC_output.csv", fps = 30) # Read HDF5 format pe <- readDeepLabCut("path/to/DLC_output.h5", fps = 25, format = "h5") ## End(Not run)
Reads MediaPipe landmark data from a directory of per-frame JSON files or a single CSV file and returns a PhysioExperiment object.
readMediaPipe(path, model = c("pose", "hand"), fps = 30)readMediaPipe(path, model = c("pose", "hand"), fps = 30)
path |
Path to a directory of JSON files or a single CSV file. |
model |
Landmark model: |
fps |
Frame rate in Hz (frames per second). Default 30. |
MediaPipe can output landmarks in two formats:
JSON (directory of per-frame files): Each JSON file contains a
"landmarks" array where each element has x, y, z, and
visibility fields. Optionally, a "world_landmarks" array may be
present with world-space coordinates.
CSV (single file): Columns named landmark_0_x, landmark_0_y,
landmark_0_z, landmark_0_visibility, landmark_1_x, etc. Each row
corresponds to one frame.
Pose model (33 landmarks): Full body landmarks from nose to feet.
Hand model (21 landmarks): Hand landmarks from wrist to fingertips.
A PhysioExperiment with assays:
X coordinates matrix (frames x landmarks)
Y coordinates matrix (frames x landmarks)
Z coordinates matrix (frames x landmarks)
Visibility scores matrix (frames x landmarks)
If world landmarks are present (JSON with world_landmarks field),
additional assays are included:
World X coordinates matrix
World Y coordinates matrix
World Z coordinates matrix
The colData contains columns label (landmark name), type
("landmark"), model (the MediaPipe model used), and landmark_idx
(0-based landmark index).
Lugaresi C, Tang J, Nash H, McClanahan C, Uboweja E, Hays M, Zhang F, Chang CL, Yong MG, Lee J, et al. (2019). "MediaPipe: A Framework for Building Perception Pipelines." arXiv:1906.08172.
readOpenPose(), readDeepLabCut(), define_skeleton()
## Not run: # Read directory of MediaPipe JSON files pe <- readMediaPipe("path/to/mediapipe_output/", model = "pose", fps = 30) # Read CSV format pe <- readMediaPipe("path/to/landmarks.csv", model = "hand", fps = 60) ## End(Not run)## Not run: # Read directory of MediaPipe JSON files pe <- readMediaPipe("path/to/mediapipe_output/", model = "pose", fps = 30) # Read CSV format pe <- readMediaPipe("path/to/landmarks.csv", model = "hand", fps = 60) ## End(Not run)
Chooses a reader based on file extension and returns a PhysioExperiment.
This is designed for first-time users who want one entry point for common
MoCap formats.
readMoCapAuto( path, format = c("auto", "csv", "c3d", "trc", "bvh", "amc"), sampling_rate = NULL, sep = ",", header_rows = 1L, skip = 0L, include_analog = FALSE, asf = NULL, fps = 120 )readMoCapAuto( path, format = c("auto", "csv", "c3d", "trc", "bvh", "amc"), sampling_rate = NULL, sep = ",", header_rows = 1L, skip = 0L, include_analog = FALSE, asf = NULL, fps = 120 )
path |
Path to a motion-capture file. |
format |
Reader format. |
sampling_rate |
Sampling rate for CSV files when not inferable. |
sep |
Delimiter used for CSV/TSV files. |
header_rows |
Number of header rows for CSV/TSV. |
skip |
Number of lines to skip before data for CSV/TSV. |
include_analog |
Logical; passed to |
asf |
Optional ASF skeleton for AMC files. Either an |
fps |
Frame rate for AMC files. |
A PhysioExperiment object.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
readMoCapCSV() for CSV/TSV motion capture data,
readASF() and readAMC() for Acclaim skeleton and motion files,
assessMoCapReadiness() for data quality assessment.
trc_file <- system.file("testdata", "sample.trc", package = "PhysioMoCap") if (nzchar(trc_file)) { pe <- readMoCapAuto(trc_file) pe }trc_file <- system.file("testdata", "sample.trc", package = "PhysioMoCap") if (nzchar(trc_file)) { pe <- readMoCapAuto(trc_file) pe }
Generic CSV reader that handles common motion capture CSV exports from
various systems including Qualisys, Vicon, and generic marker position
formats. Returns a PhysioExperiment with position_x, position_y, and
position_z assays.
readMoCapCSV( path, format = c("auto", "xyz", "wide", "long", "qualisys", "vicon"), sampling_rate = NULL, header_rows = 1L, skip = 0L, sep = ",", marker_names = NULL, coord_columns = NULL )readMoCapCSV( path, format = c("auto", "xyz", "wide", "long", "qualisys", "vicon"), sampling_rate = NULL, header_rows = 1L, skip = 0L, sep = ",", marker_names = NULL, coord_columns = NULL )
path |
Path to the CSV file. |
format |
Format hint: |
sampling_rate |
Sampling rate in Hz. Required if not detectable from
the file (e.g., from a Time column). If |
header_rows |
Number of header rows. Default 1. |
skip |
Number of lines to skip before reading. Default 0. |
sep |
Column separator. Default |
marker_names |
Explicit marker names (overrides auto-detection from column names). Must match the number of markers detected from columns. |
coord_columns |
Mapping of coordinate types as a named list of regex
patterns, e.g., |
When format = "auto", the function inspects column names:
If columns match *_x, *_y, *_z pattern (case-insensitive)
with consistent marker prefixes, the "xyz" format is used.
If columns match *X, *Y, *Z suffix pattern, the "wide"
format is used.
If the header contains "Qualisys" or "QTM", the "qualisys"
format is used.
If columns include frame, marker, x, y, z
(case-insensitive), the "long" format is used.
If a Time or time column is present and contains numeric values,
the sampling rate is computed from the median time step. An explicit
sampling_rate argument always takes precedence.
A PhysioExperiment with assays:
X coordinates matrix (frames x markers)
Y coordinates matrix (frames x markers)
Z coordinates matrix (frames x markers)
The colData contains columns label (marker names) and type
("marker"). The metadata list contains format, source_file,
and optionally time (if a Time column was found).
Wickham H (2014). "Tidy Data." Journal of Statistical Software, 59(10), 1-23.
readASF() and readAMC() for Acclaim skeleton and motion files,
readMoCapAuto() for automatic format detection.
## Not run: # Read xyz-format CSV pe <- readMoCapCSV("markers.csv", sampling_rate = 120) # Read with auto-detection from Time column pe <- readMoCapCSV("markers.csv") # Read tab-separated file pe <- readMoCapCSV("qualisys_export.tsv", format = "qualisys", sep = "\t") # Override marker names pe <- readMoCapCSV("data.csv", marker_names = c("Hip", "Knee", "Ankle"), sampling_rate = 100) ## End(Not run)## Not run: # Read xyz-format CSV pe <- readMoCapCSV("markers.csv", sampling_rate = 120) # Read with auto-detection from Time column pe <- readMoCapCSV("markers.csv") # Read tab-separated file pe <- readMoCapCSV("qualisys_export.tsv", format = "qualisys", sep = "\t") # Override marker names pe <- readMoCapCSV("data.csv", marker_names = c("Hip", "Knee", "Ankle"), sampling_rate = 100) ## End(Not run)
Reads an OpenSim motion file containing joint angles, kinematics, or other time-series data. MOT files use a tab-separated format with a header block ending in "endheader".
readMOT(path)readMOT(path)
path |
Character string giving the path to the |
A PhysioExperiment object with the data stored in the "raw"
assay. The first column (time) is used to compute the sampling rate.
Header metadata such as inDegrees is stored in metadata().
Delp SL, Anderson FC, Arnold AS, Loan P, Habib A, John CT, Guendelman E, Thelen DG (2007). "OpenSim: Open-Source Software to Create and Analyze Dynamic Simulations of Movement." IEEE Transactions on Biomedical Engineering, 54(11), 1940-1950.
readSTO(), readTRC(), readOpenCap()
mot_file <- system.file("testdata", "sample.mot", package = "PhysioMoCap") if (nzchar(mot_file)) { pe <- readMOT(mot_file) pe }mot_file <- system.file("testdata", "sample.mot", package = "PhysioMoCap") if (nzchar(mot_file)) { pe <- readMOT(mot_file) pe }
Downloads motion capture session data from the OpenCap API
(https://app.opencap.ai). Marker trajectory data is returned as TRC
format and kinematics data as MOT format, both parsed using the existing
readTRC and readMOT functions.
readOpenCap( session_id, trial_id = NULL, api_key = NULL, data_type = c("markers", "kinematics"), base_url = "https://app.opencap.ai/api" )readOpenCap( session_id, trial_id = NULL, api_key = NULL, data_type = c("markers", "kinematics"), base_url = "https://app.opencap.ai/api" )
session_id |
Character string giving the OpenCap session identifier (the 36-character UUID at the end of the session URL). |
trial_id |
Character string giving the trial identifier within the
session. If |
api_key |
Character string with the OpenCap API key. If |
data_type |
Character string specifying the type of data to download.
One of |
base_url |
Character string giving the base URL for the OpenCap API.
Default is |
The function requires the httr package for HTTP requests. If httr is not installed, a clear error message is given.
Authentication uses an API key passed via the api_key parameter or
the OPENCAP_API_KEY environment variable. The key is sent as a
Bearer token in the Authorization header.
The download workflow is:
Retrieve session metadata from
GET /sessions/{session_id}/
List trials from
GET /sessions/{session_id}/trials/
Download the result file (TRC or MOT) for the selected trial
Parse using readTRC() or readMOT()
A PhysioExperiment object. For data_type = "markers",
this contains position_x, position_y, and position_z
assays (from readTRC). For data_type = "kinematics",
this contains a raw assay with joint angle data (from
readMOT). Session and trial metadata are stored in
metadata().
Uhlrich SD, Falisse A, Kidzinski L, Muccini J, Ko M, Chaudhari AS, Hicks JL, Delp SL (2023). "OpenCap: Human movement dynamics from smartphone videos." PLoS Computational Biology, 19(10), e1011462.
readTRC(), readMOT(), readC3D()
## Not run: # Download marker data (requires API key) pe <- readOpenCap("abcd1234-5678-90ab-cdef-1234567890ab") # Download kinematics with explicit API key pe <- readOpenCap( session_id = "abcd1234-5678-90ab-cdef-1234567890ab", api_key = "my-api-key", data_type = "kinematics" ) ## End(Not run)## Not run: # Download marker data (requires API key) pe <- readOpenCap("abcd1234-5678-90ab-cdef-1234567890ab") # Download kinematics with explicit API key pe <- readOpenCap( session_id = "abcd1234-5678-90ab-cdef-1234567890ab", api_key = "my-api-key", data_type = "kinematics" ) ## End(Not run)
Reads OpenPose JSON keypoint data from a directory of frame files or a single JSON file and returns a PhysioExperiment object.
readOpenPose(path, model = c("BODY_25", "COCO"), fps = 30, person_id = 1L)readOpenPose(path, model = c("BODY_25", "COCO"), fps = 30, person_id = 1L)
path |
Path to a directory of JSON files or a single JSON file. |
model |
Keypoint model: |
fps |
Frame rate in Hz (frames per second). Default 30. |
person_id |
Which person to extract (1-based index). Default 1 (first detected person). |
OpenPose outputs one JSON file per video frame. Each file contains a
"people" array where each person's pose is stored as a flat array
of [x, y, confidence] triplets.
BODY_25 model (25 keypoints): Nose, Neck, RShoulder, RElbow, RWrist, LShoulder, LElbow, LWrist, MidHip, RHip, RKnee, RAnkle, LHip, LKnee, LAnkle, REye, LEye, REar, LEar, LBigToe, LSmallToe, LHeel, RBigToe, RSmallToe, RHeel.
COCO model (18 keypoints): Nose, Neck, RShoulder, RElbow, RWrist, LShoulder, LElbow, LWrist, RHip, RKnee, RAnkle, LHip, LKnee, LAnkle, REye, LEye, REar, LEar.
Frames where the specified person is not detected will contain
NA values for all keypoints.
A PhysioExperiment with assays:
X coordinates matrix (frames x keypoints)
Y coordinates matrix (frames x keypoints)
Detection confidence matrix (frames x keypoints)
The colData contains columns label (keypoint name), type
("keypoint"), and model (the OpenPose model used).
Cao Z, Hidalgo G, Simon T, Wei SE, Sheikh Y (2019). "OpenPose: Realtime Multi-Person 2D Pose Estimation Using Part Affinity Fields." IEEE Transactions on Pattern Analysis and Machine Intelligence, 43(1), 172-186.
readDeepLabCut(), readMediaPipe(), define_skeleton()
## Not run: # Read directory of OpenPose JSON files pe <- readOpenPose("path/to/openpose_output/", fps = 30) # Read with COCO model pe <- readOpenPose("path/to/output/", model = "COCO", fps = 25) # Extract second person pe <- readOpenPose("path/to/output/", person_id = 2) ## End(Not run)## Not run: # Read directory of OpenPose JSON files pe <- readOpenPose("path/to/openpose_output/", fps = 30) # Read with COCO model pe <- readOpenPose("path/to/output/", model = "COCO", fps = 25) # Extract second person pe <- readOpenPose("path/to/output/", person_id = 2) ## End(Not run)
Reads one or more OpenSim output files and returns PhysioExperiment objects.
readOpenSimOutputs(files, format = c("auto", "mot", "sto", "trc"))readOpenSimOutputs(files, format = c("auto", "mot", "sto", "trc"))
files |
Character vector of file paths. |
format |
One of |
Named list of PhysioExperiment objects.
readMOT(), readSTO(), readTRC()
Reads an OpenSim storage file containing forces, moments, or other computed quantities. STO files share the same tab-separated format as MOT files with a header block ending in "endheader".
readSTO(path)readSTO(path)
path |
Character string giving the path to the |
A PhysioExperiment object with the data stored in the "raw"
assay. The first column (time) is used to compute the sampling rate.
Header metadata is stored in metadata().
Delp SL, Anderson FC, Arnold AS, Loan P, Habib A, John CT, Guendelman E, Thelen DG (2007). "OpenSim: Open-Source Software to Create and Analyze Dynamic Simulations of Movement." IEEE Transactions on Biomedical Engineering, 54(11), 1940-1950.
readMOT(), readTRC(), readOpenCap()
sto_file <- system.file("testdata", "sample.sto", package = "PhysioMoCap") if (nzchar(sto_file)) { pe <- readSTO(sto_file) pe }sto_file <- system.file("testdata", "sample.sto", package = "PhysioMoCap") if (nzchar(sto_file)) { pe <- readSTO(sto_file) pe }
Reads marker trajectory data from an OpenSim TRC file. TRC files store 3D marker positions (X, Y, Z) in a specific header format that differs from MOT/STO files.
readTRC(path)readTRC(path)
path |
Character string giving the path to the |
A PhysioExperiment object with three assays: "position_x",
"position_y", and "position_z", each with columns named by marker.
Header metadata (DataRate, Units, etc.) is stored in metadata().
Delp SL, Anderson FC, Arnold AS, Loan P, Habib A, John CT, Guendelman E, Thelen DG (2007). "OpenSim: Open-Source Software to Create and Analyze Dynamic Simulations of Movement." IEEE Transactions on Biomedical Engineering, 54(11), 1940-1950.
readMOT(), readSTO(), readC3D()
trc_file <- system.file("testdata", "sample.trc", package = "PhysioMoCap") if (nzchar(trc_file)) { pe <- readTRC(trc_file) pe }trc_file <- system.file("testdata", "sample.trc", package = "PhysioMoCap") if (nzchar(trc_file)) { pe <- readTRC(trc_file) pe }
Reads motion capture data exported from the OptiTrack -> Motive -> Venus3D
pipeline. The Venus3D CSV format uses #-prefixed header lines for metadata
and stores 3D marker coordinates in wide format with columns like 1(X),
1(Y), 1(Z), 2(X), etc.
readVenus3D(path, marker_names = NULL)readVenus3D(path, marker_names = NULL)
path |
Path to the Venus3D CSV file. |
marker_names |
Optional character vector of marker names to assign. Must
match the number of markers in the file. If |
Because Venus3D randomly reassigns marker labels across frames, downstream
use of trackMarkers() is typically required to establish consistent marker
identities.
A PhysioExperiment with assays:
X coordinates matrix (frames x markers)
Y coordinates matrix (frames x markers)
Z coordinates matrix (frames x markers)
The colData contains columns label (marker names) and type
("marker"). The metadata list contains format, source_file,
format_version, units, coordinate_system, and time (numeric vector
of frame times).
Venus3D Software Documentation, C-Motion Inc.
trackMarkers() for resolving Venus3D's random label assignment,
readMoCapCSV() for generic CSV formats, readMoCapAuto() for automatic
format detection.
## Not run: pe <- readVenus3D("capture.csv") # Assign meaningful marker names pe <- readVenus3D("capture.csv", marker_names = c("Hip", "Knee", "Ankle")) # Follow with marker tracking to resolve label shuffling pe_tracked <- trackMarkers(pe) ## End(Not run)## Not run: pe <- readVenus3D("capture.csv") # Assign meaningful marker names pe <- readVenus3D("capture.csv", marker_names = c("Hip", "Knee", "Ankle")) # Follow with marker tracking to resolve label shuffling pe_tracked <- trackMarkers(pe) ## End(Not run)
Reconstructs individual waveforms using a subset of principal components.
reconstructFPCA(fpca_result, n_components = NULL, observation = NULL)reconstructFPCA(fpca_result, n_components = NULL, observation = NULL)
fpca_result |
An fpca_result object from fPCA(). |
n_components |
Number of components to use for reconstruction. |
observation |
Indices of observations to reconstruct. If NULL, all. |
Matrix of reconstructed waveforms (time x observations).
Ramsay JO, Silverman BW (2005). "Functional Data Analysis." 2nd ed. Springer.
fPCA() for performing the decomposition,
plotFPCA() for visualizing fPCA results.
# Create sample data and run fPCA first set.seed(123) t <- seq(0, 100, length.out = 100) base_curve <- sin(2 * pi * t / 100) * 30 data <- sapply(1:20, function(i) base_curve * rnorm(1, 1, 0.2) + rnorm(100, 0, 2)) fpca_result <- fPCA(data, n_components = 4) # Reconstruct using only first 2 PCs reconstructed <- reconstructFPCA(fpca_result, n_components = 2)# Create sample data and run fPCA first set.seed(123) t <- seq(0, 100, length.out = 100) base_curve <- sin(2 * pi * t / 100) * 30 data <- sapply(1:20, function(i) base_curve * rnorm(1, 1, 0.2) + rnorm(100, 0, 2)) fpca_result <- fPCA(data, n_components = 4) # Reconstruct using only first 2 PCs reconstructed <- reconstructFPCA(fpca_result, n_components = 2)
Rectify EMG signals
rectifyEMG(x, method = c("fullwave", "halfwave"))rectifyEMG(x, method = c("fullwave", "halfwave"))
x |
Numeric vector or matrix (time x channels). |
method |
Rectification method: |
Rectified signal with the same dimensions as x.
Merletti R, Parker PA (2004). "Electromyography: Physiology, Engineering, and Non-Invasive Applications." IEEE Press/Wiley.
computeRMSEnvelope() for computing RMS envelope,
processEMG() for complete EMG processing pipeline.
x <- c(-1, -0.5, 0, 0.5, 1) rectifyEMG(x, method = "fullwave")x <- c(-1, -0.5, 0, 0.5, 1) rectifyEMG(x, method = "fullwave")
Aligns waveforms by estimating and removing phase variation. Uses landmark registration or continuous registration.
registerCurves( x, method = c("continuous", "landmark"), landmarks = NULL, template = NULL )registerCurves( x, method = c("continuous", "landmark"), landmarks = NULL, template = NULL )
x |
A PhysioExperiment object or matrix (time x observations). |
method |
Registration method: "landmark" or "continuous". |
landmarks |
For landmark method, matrix of landmark times (landmarks x obs). |
template |
Template curve to align to. If NULL, uses mean. |
Phase variation (timing differences) can obscure amplitude differences in biomechanical data. Registration separates phase and amplitude variation.
A list containing:
registered |
Registered waveforms |
warping |
Warping functions |
template |
Template used for registration |
Ramsay JO, Silverman BW (2005). "Functional Data Analysis." 2nd ed. Springer.
fPCA() for functional PCA after registration,
plotGaitCycle() for plotting registered gait waveforms.
# Simulate data with phase variation set.seed(123) t <- seq(0, 100, length.out = 100) data <- sapply(1:20, function(i) { phase_shift <- rnorm(1, 0, 10) t_shifted <- t + phase_shift sin(2 * pi * t_shifted / 100) * 30 + rnorm(100, 0, 2) }) pe <- PhysioExperiment(assays = list(values = data), samplingRate = 100) reg_result <- registerCurves(pe, method = "continuous")# Simulate data with phase variation set.seed(123) t <- seq(0, 100, length.out = 100) data <- sapply(1:20, function(i) { phase_shift <- rnorm(1, 0, 10) t_shifted <- t + phase_shift sin(2 * pi * t_shifted / 100) * 30 + rnorm(100, 0, 2) }) pe <- PhysioExperiment(assays = list(values = data), samplingRate = 100) reg_result <- registerCurves(pe, method = "continuous")
Subtracts the rotated gravity vector from raw accelerometer data,
leaving only dynamic (linear) acceleration. The gravity direction
is determined by rotating the reference gravity vector (0, 0, -g)
from the world frame into the sensor frame using the provided
orientation quaternions.
removeGravity(accel, orientation, g = 9.81)removeGravity(accel, orientation, g = 9.81)
accel |
Numeric matrix (n x 3) of raw accelerometer readings in m/s^2. |
orientation |
A data.frame or matrix containing orientation
quaternions. If a data.frame, must contain columns |
g |
Numeric. Gravitational acceleration magnitude (default 9.81 m/s^2). |
For each time step, the gravity vector in the world frame
(0, 0, -g) is rotated into the sensor frame using the conjugate
of the orientation quaternion. This rotated gravity is then
subtracted from the raw accelerometer reading.
Numeric matrix (n x 3) of dynamic (gravity-free) acceleration.
Madgwick SOH, Harrison AJL, Vaidyanathan R (2011). "Estimation of IMU and MARG orientation using a gradient descent algorithm." IEEE International Conference on Rehabilitation Robotics.
estimateOrientation(), calibrateIMU(), quaternionToEuler()
n <- 100 accel <- matrix(c(rep(0, n), rep(0, n), rep(-9.81, n)), ncol = 3) gyro <- matrix(0, nrow = n, ncol = 3) ori <- estimateOrientation(accel, gyro, sampling_rate = 100) dyn_accel <- removeGravity(accel, ori)n <- 100 accel <- matrix(c(rep(0, n), rep(0, n), rep(-9.81, n)), ncol = 3) gyro <- matrix(0, nrow = n, ncol = 3) ori <- estimateOrientation(accel, gyro, sampling_rate = 100) dyn_accel <- removeGravity(accel, ori)
Prints a human-readable summary of gap statistics including total number of gaps, average gap size, and percentage of missing data.
reportGaps(gaps, sampling_rate)reportGaps(gaps, sampling_rate)
gaps |
A data.frame as returned by |
sampling_rate |
Sampling rate in Hz (used to report gap durations) |
Invisibly returns a list with summary statistics:
total_gaps - Total number of gaps
avg_size - Average gap size in samples
total_missing - Total number of missing samples
pct_missing - Percentage of missing data (if computable)
Federolf PA (2013). "A novel approach to solve the 'missing marker problem' in marker-based motion analysis that does not require additional assumptions about the biodynamic model." Journal of Biomechanics, 46(13), 2173-2178.
detectGaps(), fillGaps(), fillGapsLinear()
gaps <- data.frame( channel = c("M1", "M1", "M2"), start = c(10, 50, 20), end = c(15, 55, 30), size = c(6, 6, 11) ) reportGaps(gaps, sampling_rate = 120)gaps <- data.frame( channel = c("M1", "M1", "M2"), start = c(10, 50, 20), end = c(15, 55, 30), size = c(6, 6, 11) ) reportGaps(gaps, sampling_rate = 120)
Resamples all (or selected) numeric assays of a PhysioExperiment object to a new target sampling rate. Both upsampling and downsampling are supported.
resampleSignal( pe, target_rate, method = c("linear", "spline"), assay_names = NULL )resampleSignal( pe, target_rate, method = c("linear", "spline"), assay_names = NULL )
pe |
A PhysioExperiment object. |
target_rate |
Target sampling rate in Hz. |
method |
Interpolation method: "linear" (default) or "spline". |
assay_names |
Character vector of assay names to resample. If NULL (default), all numeric assays are resampled. |
A new PhysioExperiment with resampled assays, updated
samplingRate, and updated metadata$time vector.
Oppenheim AV, Willsky AS, Nawab SH (1997). "Signals and Systems." 2nd ed. Prentice Hall.
resampleVector() for resampling individual numeric vectors,
synchronizeSignals() for synchronizing multiple experiments.
pe <- PhysioCore::PhysioExperiment( assays = S4Vectors::SimpleList( position_x = matrix(sin(seq(0, 2 * pi, length.out = 100)), ncol = 1) ), colData = S4Vectors::DataFrame(label = "M1", type = "marker"), samplingRate = 100 ) pe2 <- resampleSignal(pe, target_rate = 200) PhysioCore::samplingRate(pe2) # 200pe <- PhysioCore::PhysioExperiment( assays = S4Vectors::SimpleList( position_x = matrix(sin(seq(0, 2 * pi, length.out = 100)), ncol = 1) ), colData = S4Vectors::DataFrame(label = "M1", type = "marker"), samplingRate = 100 ) pe2 <- resampleSignal(pe, target_rate = 200) PhysioCore::samplingRate(pe2) # 200
Resamples a numeric vector from one sampling rate to another using interpolation.
resampleVector(x, from_rate, to_rate, method = c("linear", "spline"))resampleVector(x, from_rate, to_rate, method = c("linear", "spline"))
x |
Numeric vector to resample. |
from_rate |
Original sampling rate in Hz. |
to_rate |
Target sampling rate in Hz. |
method |
Interpolation method: "linear" uses |
A numeric vector resampled at the target rate.
Oppenheim AV, Willsky AS, Nawab SH (1997). "Signals and Systems." 2nd ed. Prentice Hall.
resampleSignal() for resampling PhysioExperiment objects,
synchronizeSignals() for synchronizing multiple signals.
# Resample a 100Hz signal to 200Hz x <- sin(seq(0, 2 * pi, length.out = 100)) x_up <- resampleVector(x, from_rate = 100, to_rate = 200) length(x_up) # 200# Resample a 100Hz signal to 200Hz x <- sin(seq(0, 2 * pi, length.out = 100)) x_up <- resampleVector(x, from_rate = 100, to_rate = 200) length(x_up) # 200
Executes OpenSim setup XML files sequentially through PhysioOpenSim.
run_opensim_toolchain( ik_setup = NULL, id_setup = NULL, so_setup = NULL, rra_setup = NULL, cmc_setup = NULL, analyze_setup = NULL, workdir = NULL, cli = NULL, timeout_sec = 0L, fail_on_error = TRUE, extra_args = character() )run_opensim_toolchain( ik_setup = NULL, id_setup = NULL, so_setup = NULL, rra_setup = NULL, cmc_setup = NULL, analyze_setup = NULL, workdir = NULL, cli = NULL, timeout_sec = 0L, fail_on_error = TRUE, extra_args = character() )
ik_setup |
Optional path to IK setup XML. |
id_setup |
Optional path to ID setup XML. |
so_setup |
Optional path to SO setup XML. |
rra_setup |
Optional path to RRA setup XML. |
cmc_setup |
Optional path to CMC setup XML. |
analyze_setup |
Optional path to Analyze setup XML. |
workdir |
Optional working directory for all tool runs. |
cli |
Optional OpenSim CLI command/path. |
timeout_sec |
Timeout in seconds for each tool execution. |
fail_on_error |
If |
extra_args |
Optional character vector appended to each tool run. |
Named list with entries for executed tools (ik, id, so,
rra, cmc, analyze).
batch_analyze_opensim(), create_schema_from_opensim()
Executes all benchmark rows in a manifest and returns aggregate summaries.
runBenchmarkSuite( manifest, data_dir = ".", thresholds = defaultBenchmarkThresholds("balanced"), alignment = c("truncate", "resample"), report_dir = NULL )runBenchmarkSuite( manifest, data_dir = ".", thresholds = defaultBenchmarkThresholds("balanced"), alignment = c("truncate", "resample"), report_dir = NULL )
manifest |
Manifest data.frame or manifest CSV path.
|
data_dir |
Base directory for relative manifest file paths. |
thresholds |
Named threshold list from |
alignment |
Alignment mode passed to |
report_dir |
Optional output directory. If supplied, summary and detailed CSV reports are written. |
Object of class "benchmark_suite" with summary, metrics,
manifest, and thresholds.
Shrout PE, Fleiss JL (1979). "Intraclass Correlations: Uses in Assessing Rater Reliability." Psychological Bulletin, 86(2), 420-428.
benchmarkAgreement() for single-trial agreement analysis,
createBenchmarkExample() for generating example benchmark data,
print.benchmark_suite() for displaying suite results.
ex <- createBenchmarkExample(n_trials = 2, seed = 1) suite <- runBenchmarkSuite(ex$manifest, data_dir = ex$data_dir) suite$summaryex <- createBenchmarkExample(n_trials = 2, seed = 1) suite <- runBenchmarkSuite(ex$manifest, data_dir = ex$data_dir) suite$summary
Pure R implementation of the Savitzky-Golay filter using local polynomial fitting. Useful for smoothing noisy signals while preserving features like peak height and width better than simple moving averages.
savgolFilter(x, window_length = 11, poly_order = 3, deriv = 0)savgolFilter(x, window_length = 11, poly_order = 3, deriv = 0)
x |
A numeric vector or matrix (time x channels). |
window_length |
Window length for the filter. Must be a positive odd integer. |
poly_order |
Polynomial order for local fitting (must be less than
|
deriv |
Derivative order. 0 for smoothing, 1 for first derivative, 2 for second derivative, etc. |
The Savitzky-Golay filter fits a local polynomial of degree poly_order
to a window of window_length points, using least-squares. The filter
coefficients are computed analytically and applied via convolution.
For differentiation (deriv > 0), the result is the derivative of the
fitted polynomial, which provides a smooth estimate of the derivative.
Edge handling: the first and last floor(window_length/2) points are
computed with truncated windows where possible, or set to NA.
Filtered/smoothed data with the same dimensions as x.
Savitzky A, Golay MJE (1964). "Smoothing and Differentiation of Data by Simplified Least Squares Procedures." Analytical Chemistry, 36(8), 1627-1639.
butterworthFilter() for frequency-domain Butterworth filtering,
movingAverage() for simple moving average smoothing,
differentiate() for numerical differentiation.
# Smooth a noisy sine wave t <- seq(0, 2 * pi, length.out = 200) x <- sin(t) + rnorm(200, sd = 0.2) x_smooth <- savgolFilter(x, window_length = 11, poly_order = 3) # Compute first derivative dx <- savgolFilter(x, window_length = 11, poly_order = 3, deriv = 1)# Smooth a noisy sine wave t <- seq(0, 2 * pi, length.out = 200) x <- sin(t) + rnorm(200, sd = 0.2) x_smooth <- savgolFilter(x, window_length = 11, poly_order = 3) # Compute first derivative dx <- savgolFilter(x, window_length = 11, poly_order = 3, deriv = 1)
Task schema for postural control/balance analysis.
schema_balanceschema_balance
A TaskSchema object for continuous balance assessment.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
TaskSchema(), schema_gait, schema_cutting
print(schema_balance)print(schema_balance)
Task schema for cutting and change of direction analysis.
schema_cuttingschema_cutting
A TaskSchema object with COD-specific events and phases.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
TaskSchema(), schema_gait, schema_running
print(schema_cutting)print(schema_cutting)
Task schema for cycling pedal stroke analysis.
schema_cyclingschema_cycling
A TaskSchema object with cycling-specific events and phases.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
TaskSchema(), schema_gait, schema_running
print(schema_cycling)print(schema_cycling)
Task schema for walking gait analysis with standard events and phases.
schema_gaitschema_gait
A TaskSchema object with:
Heel strike (x2), foot flat, midstance, heel off, toe off
Stance (with loading, midstance, propulsion subphases), Swing
cycle (0-100%)
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
TaskSchema(), getSchema(), schema_running
print(schema_gait) getEventNames(schema_gait) getPhaseNames(schema_gait)print(schema_gait) getEventNames(schema_gait) getPhaseNames(schema_gait)
Task schema for vertical jump analysis (countermovement, drop jump, etc.).
schema_jumpschema_jump
A TaskSchema object with jump-specific events and phases.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
TaskSchema(), schema_gait, schema_throw
print(schema_jump)print(schema_jump)
Task schema for running gait analysis.
schema_runningschema_running
A TaskSchema object with running-specific events and phases.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
TaskSchema(), schema_gait, schema_jump
print(schema_running)print(schema_running)
Task schema for throwing motion analysis (baseball, softball, etc.).
schema_throwschema_throw
A TaskSchema object with throwing-specific events and phases.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
TaskSchema(), schema_gait, schema_cutting
print(schema_throw)print(schema_throw)
Returns a data.frame of body segment inertial parameters including mass fractions and center of mass proximal fractions for standard anthropometric models.
segmentParameters(model = "deLeva_male")segmentParameters(model = "deLeva_male")
model |
Character string specifying the anthropometric model.
One of |
The De Leva (1996) tables provide adjusted body segment parameters based on Zatsiorsky's data, separately for males and females. The Winter (2009) model provides a simplified set of parameters commonly used in gait analysis.
Segments include: head, trunk, upper_arm_r, upper_arm_l, forearm_r, forearm_l, hand_r, hand_l, thigh_r, thigh_l, shank_r, shank_l, foot_r, foot_l (14 segments total).
A data.frame with columns:
Character, name of the body segment.
Numeric, fraction of total body mass (as percentage, 0-100).
Numeric, fraction of segment length from the proximal endpoint to the segment center of mass (0-1).
Character, default proximal marker name.
Character, default distal marker name.
De Leva, P. (1996). Adjustments to Zatsiorsky-Seluyanov's segment inertia parameters. Journal of Biomechanics, 29(9), 1223-1230.
Winter, D.A. (2009). Biomechanics and Motor Control of Human Movement (4th ed.). Wiley.
calculateCOM() for whole-body center of mass computation,
calculateSegmentCOM() for individual segment center of mass,
estimateSegmentInertia() for segment inertial properties.
bsip <- segmentParameters("deLeva_male") head(bsip) sum(bsip$mass_fraction) # approximately 100bsip <- segmentParameters("deLeva_male") head(bsip) sum(bsip$mass_fraction) # approximately 100
Divides movement data into phases based on detected events and schema definition.
segmentPhases(x, events, schema, include_subphases = TRUE)segmentPhases(x, events, schema, include_subphases = TRUE)
x |
PhysioExperiment object or matrix (time x channels) |
events |
A detected_events data.frame from detectEvents() |
schema |
TaskSchema object defining phase structure |
include_subphases |
Whether to include subphases in output |
A segmented_phases object (list) containing:
phases - List of phase data
metadata - Phase timing information
schema - Original schema
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
detectEvents(), extractPhase(), phaseTiming(), normalizeMovement()
# Assuming events have been detected # phases <- segmentPhases(data, events, schema_gait)# Assuming events have been detected # phases <- segmentPhases(data, events, schema_gait)
Computes the standard error of measurement from the SD of scores and a reliability coefficient (ICC or test-retest correlation).
sem(x, icc_value = NULL, reliability = NULL)sem(x, icc_value = NULL, reliability = NULL)
x |
Numeric vector of observed scores. Used to compute SD. |
icc_value |
Numeric; ICC value to use as the reliability coefficient. |
reliability |
Numeric; alternative reliability coefficient (e.g.,
test-retest correlation). Exactly one of |
SEM is computed as:
where is the reliability coefficient (ICC or correlation).
Numeric SEM value.
Shrout PE, Fleiss JL (1979). "Intraclass Correlations: Uses in Assessing Rater Reliability." Psychological Bulletin, 86(2), 420-428.
icc() for computing intraclass correlation coefficients,
mdc() for minimal detectable change based on SEM.
scores <- c(10, 12, 15, 11, 13, 14, 9, 16, 12, 11) sem(scores, icc_value = 0.90)scores <- c(10, 12, 15, 11, 13, 14, 9, 16, 12, 11) sem(scores, icc_value = 0.90)
Constructs an S3 SkeletonModel object that defines a skeleton topology
for pose estimation or motion capture data. A skeleton consists of named
keypoints (joints/markers), bones connecting them, and an optional
hierarchical tree structure.
SkeletonModel(name, keypoints, bones, hierarchy, root_keypoint)SkeletonModel(name, keypoints, bones, hierarchy, root_keypoint)
name |
Character string identifying the skeleton model
(e.g., |
keypoints |
A
|
bones |
A
|
hierarchy |
Named list of parent-to-children relationships. Each element name is a parent keypoint label; the value is a character vector of child keypoint labels. |
root_keypoint |
Character, label of the root keypoint in the
hierarchy (e.g., |
A SkeletonModel object (S3 class).
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
define_skeleton(), get_bone_connections(), get_segment_lengths()
# Minimal skeleton kp <- data.frame( id = 0:2, label = c("Head", "Torso", "Hip"), body_region = c("head", "torso", "pelvis") ) bones <- data.frame( from_id = c(0, 1), to_id = c(1, 2), bone_name = c("neck", "spine") ) hier <- list(Head = "Torso", Torso = "Hip") sk <- SkeletonModel("mini", kp, bones, hier, "Head") print(sk)# Minimal skeleton kp <- data.frame( id = 0:2, label = c("Head", "Torso", "Hip"), body_region = c("head", "torso", "pelvis") ) bones <- data.frame( from_id = c(0, 1), to_id = c(1, 2), bone_name = c("neck", "spine") ) hier <- list(Head = "Torso", Torso = "Hip") sk <- SkeletonModel("mini", kp, bones, hier, "Head") print(sk)
Computes mean, standard deviation, and coefficient of variation for each gait parameter across all strides.
summarizeGaitParameters(gait_params)summarizeGaitParameters(gait_params)
gait_params |
A |
A data.frame with columns parameter, side,
mean, sd, and cv (coefficient of variation as
percentage).
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. John Wiley & Sons.
calculateGaitParameters() for computing gait parameters,
print.gait_parameters() for formatted display of results.
# See test file for worked examples# See test file for worked examples
Calculates a symmetry index between left and right side measurements using standard methods from the biomechanics literature.
symmetryIndex(left, right, method = "robinson")symmetryIndex(left, right, method = "robinson")
left |
Numeric vector or matrix of left-side values. |
right |
Numeric vector or matrix of right-side values (same
dimensions as |
method |
Character string specifying the symmetry index method.
|
The Robinson (1987) symmetry index returns 0 for perfect symmetry and larger values for greater asymmetry. It is expressed as a percentage. The ratio method returns 1.0 for perfect symmetry.
For vectors, a numeric vector of symmetry indices. For
matrices, row-wise symmetry indices (a numeric vector of length
equal to nrow(left)).
Robinson, R.O., Herzog, W., & Nigg, B.M. (1987). Use of force platform variables to quantify the effects of chiropractic manipulation on gait symmetry. Journal of Manipulative and Physiological Therapeutics, 10(4), 172-176.
calculateStepSymmetry() for gait-specific symmetry metrics,
plotSymmetry() for symmetry visualization,
calculateGaitParameters() for comprehensive gait analysis.
# Perfect symmetry symmetryIndex(10, 10) # returns 0 # Known asymmetry symmetryIndex(10, 8) # returns ~22.2% # Ratio method symmetryIndex(10, 8, method = "ratio") # returns 1.25# Perfect symmetry symmetryIndex(10, 10) # returns 0 # Known asymmetry symmetryIndex(10, 8) # returns ~22.2% # Ratio method symmetryIndex(10, 8, method = "ratio") # returns 1.25
Resamples a list of PhysioExperiment objects so they all share the same sampling rate and have the same number of time points.
synchronizeSignals(pe_list, target_rate = NULL, method = c("linear", "spline"))synchronizeSignals(pe_list, target_rate = NULL, method = c("linear", "spline"))
pe_list |
A list of PhysioExperiment objects. |
target_rate |
Target sampling rate in Hz. If NULL (default), the highest sampling rate among the inputs is used. |
method |
Interpolation method: "linear" (default) or "spline". |
A list of PhysioExperiment objects, all with the same sampling rate and the same number of rows (time points).
Oppenheim AV, Willsky AS, Nawab SH (1997). "Signals and Systems." 2nd ed. Prentice Hall.
resampleSignal() for resampling individual PhysioExperiment objects,
resampleVector() for resampling raw numeric vectors.
pe1 <- PhysioCore::PhysioExperiment( assays = S4Vectors::SimpleList( raw = matrix(rnorm(100), ncol = 1) ), colData = S4Vectors::DataFrame(label = "ch1", type = "marker"), samplingRate = 100 ) pe2 <- PhysioCore::PhysioExperiment( assays = S4Vectors::SimpleList( raw = matrix(rnorm(200), ncol = 1) ), colData = S4Vectors::DataFrame(label = "ch1", type = "marker"), samplingRate = 200 ) synced <- synchronizeSignals(list(pe1, pe2))pe1 <- PhysioCore::PhysioExperiment( assays = S4Vectors::SimpleList( raw = matrix(rnorm(100), ncol = 1) ), colData = S4Vectors::DataFrame(label = "ch1", type = "marker"), samplingRate = 100 ) pe2 <- PhysioCore::PhysioExperiment( assays = S4Vectors::SimpleList( raw = matrix(rnorm(200), ncol = 1) ), colData = S4Vectors::DataFrame(label = "ch1", type = "marker"), samplingRate = 200 ) synced <- synchronizeSignals(list(pe1, pe2))
Defines a complete movement task schema including events, phases, normalization method, metrics, and visualization defaults.
TaskSchema( task_type, task_label = task_type, events = list(), phases = list(), normalization = c("cycle", "phase", "landmark", "dtw", "absolute"), norm_length = 101L, metrics = character(), vis_defaults = list() )TaskSchema( task_type, task_label = task_type, events = list(), phases = list(), normalization = c("cycle", "phase", "landmark", "dtw", "absolute"), norm_length = 101L, metrics = character(), vis_defaults = list() )
task_type |
Short identifier for the task type (e.g., "gait", "jump") |
task_label |
Human-readable label (e.g., "Gait Cycle", "Vertical Jump") |
events |
List of Event objects defining key timepoints |
phases |
List of Phase objects defining movement phases |
normalization |
Normalization method:
|
norm_length |
Target length after normalization (default 101 for 0-100%) |
metrics |
Character vector of recommended metrics for this task |
vis_defaults |
List of default visualization parameters:
|
A TaskSchema object (S3 class)
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
Event(), Phase(), getSchema(), validateSchema()
# Simple task schema my_task <- TaskSchema( task_type = "simple", task_label = "Simple Movement", events = list( Event("start", "Start", "threshold", list(signal = "velocity", threshold = 0.1, direction = "rising")), Event("end", "End", "threshold", list(signal = "velocity", threshold = 0.1, direction = "falling")) ), phases = list( Phase("main", "Main Phase", "start", "end") ), normalization = "cycle" )# Simple task schema my_task <- TaskSchema( task_type = "simple", task_label = "Simple Movement", events = list( Event("start", "Start", "threshold", list(signal = "velocity", threshold = 0.1, direction = "rising")), Event("end", "End", "threshold", list(signal = "velocity", threshold = 0.1, direction = "falling")) ), phases = list( Phase("main", "Main Phase", "start", "end") ), normalization = "cycle" )
Resolves inconsistent marker labelling across frames by establishing frame-to-frame correspondences using the Hungarian algorithm. This is essential for Venus3D data where marker IDs are randomly reassigned each frame.
trackMarkers( pe, method = "hungarian", max_distance = Inf, use_prediction = FALSE, assay_prefix = "position" )trackMarkers( pe, method = "hungarian", max_distance = Inf, use_prediction = FALSE, assay_prefix = "position" )
pe |
A PhysioExperiment with |
method |
Assignment method: |
max_distance |
Maximum allowed assignment distance. Assignments
exceeding this threshold are set to |
use_prediction |
Logical. If |
assay_prefix |
Prefix for position assay names. Default |
The algorithm:
Frame 1 defines the reference labelling.
For each subsequent frame, a Euclidean distance cost matrix is computed between reference positions and observed positions.
The cost matrix is solved via clue::solve_LSAP() (Hungarian
algorithm) or a greedy heuristic.
If marker counts differ between frames, the cost matrix is padded with dummy entries (cost = 1e12).
Assignments exceeding max_distance are marked as NA.
With use_prediction = TRUE, reference positions are extrapolated
using velocity from the two preceding frames.
A PhysioExperiment where columns consistently correspond to the
same physical marker across all frames. The metadata$tracking list
contains:
Integer matrix (frames x markers) of column indices from the original data used at each frame.
Numeric matrix (frames x markers) of assignment costs (Euclidean distances) at each frame.
Character string indicating the method used.
Kuhn HW (1955). "The Hungarian Method for the Assignment Problem." Naval Research Logistics Quarterly, 2(1-2), 83-97.
readVenus3D() for reading Venus3D data, detectSwaps() and
correctSwaps() for post-tracking swap repair.
## Not run: pe <- readVenus3D("capture.csv") pe_tracked <- trackMarkers(pe) # With velocity prediction for fast movements pe_tracked <- trackMarkers(pe, use_prediction = TRUE, max_distance = 50) ## End(Not run)## Not run: pe <- readVenus3D("capture.csv") pe_tracked <- trackMarkers(pe) # With velocity prediction for fast movements pe_tracked <- trackMarkers(pe, use_prediction = TRUE, max_distance = 50) ## End(Not run)
Checks structural validity and file existence for benchmark inputs.
validateBenchmarkManifest(manifest, data_dir = ".")validateBenchmarkManifest(manifest, data_dir = ".")
manifest |
A manifest data.frame or path to a manifest CSV. |
data_dir |
Base directory used to resolve relative file paths. |
An object of class "benchmark_manifest_validation" with fields:
valid, issues, and manifest.
Bland JM, Altman DG (1986). "Statistical Methods for Assessing Agreement Between Two Methods of Clinical Measurement." Lancet, 327(8476), 307-310.
benchmarkManifestTemplate() for creating manifest templates,
print.benchmark_manifest_validation() for displaying validation results.
m <- benchmarkManifestTemplate(1) v <- validateBenchmarkManifest(m) v$validm <- benchmarkManifestTemplate(1) v <- validateBenchmarkManifest(m) v$valid
Checks that a TaskSchema is internally consistent.
validateSchema(schema)validateSchema(schema)
schema |
A TaskSchema object |
TRUE if valid, otherwise throws an error
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
TaskSchema(), getSchema(), listSchemas()
Computes the angle between pairs of 3D vectors. Accepts either single vectors (length-3 numeric) or matrices where each row is a vector (n x 3). Vectorized for efficient computation across time frames.
vectorAngle(v1, v2, degrees = TRUE)vectorAngle(v1, v2, degrees = TRUE)
v1 |
Numeric vector of length 3 or matrix with 3 columns. |
v2 |
Numeric vector of length 3 or matrix with 3 columns. |
degrees |
Logical. If |
The angle is computed as:
The dot product is clamped to before applying
acos to avoid numerical issues. If either vector has zero
magnitude, the result is NA.
Numeric vector of angles. Length 1 for vector inputs,
or nrow(v1) for matrix inputs.
Winter DA (2009). "Biomechanics and Motor Control of Human Movement." 4th ed. Wiley.
Grood ES, Suntay WJ (1983). "A joint coordinate system for the clinical description of three-dimensional motions: application to the knee." Journal of Biomechanical Engineering, 105(2), 136-144.
calculateJointAngles(), quaternionToEuler(), eulerToQuaternion()
# 90-degree angle vectorAngle(c(1, 0, 0), c(0, 1, 0)) # Vectorized across rows v1 <- matrix(c(1,0,0, 0,1,0), nrow = 2, byrow = TRUE) v2 <- matrix(c(0,1,0, 0,0,1), nrow = 2, byrow = TRUE) vectorAngle(v1, v2)# 90-degree angle vectorAngle(c(1, 0, 0), c(0, 1, 0)) # Vectorized across rows v1 <- matrix(c(1,0,0, 0,1,0), nrow = 2, byrow = TRUE) v2 <- matrix(c(0,1,0, 0,0,1), nrow = 2, byrow = TRUE) vectorAngle(v1, v2)
Performs Principal Component Analysis on waveform data, either using extracted features or raw waveforms.
waveformPCA( x, method = c("features", "raw"), features = c("statistical", "shape"), n_components = 10, scale = TRUE )waveformPCA( x, method = c("features", "raw"), features = c("statistical", "shape"), n_components = 10, scale = TRUE )
x |
A PhysioExperiment object or matrix. |
method |
Feature extraction method: "features" or "raw". |
features |
If method = "features", which features to extract. |
n_components |
Number of PCs to retain. |
scale |
Logical; scale features to unit variance. |
A list of class "waveform_pca" containing:
scores |
PC scores (observations x components) |
loadings |
PC loadings (features x components) |
variance_explained |
Variance explained by each PC |
cumulative_variance |
Cumulative variance |
center |
Feature means |
scale |
Feature SDs (if scaled) |
van der Maaten L, Hinton G (2008). "Visualizing Data using t-SNE." Journal of Machine Learning Research, 9, 2579-2605.
extractWaveformFeatures(), waveformUMAP(), plotPCAScatter(), plotPCAVariance()
# PCA on gait features set.seed(123) data <- matrix(rnorm(1000), nrow = 100, ncol = 10) pca_result <- waveformPCA(data, method = "features") plotPCAScatter(pca_result)# PCA on gait features set.seed(123) data <- matrix(rnorm(1000), nrow = 100, ncol = 10) pca_result <- waveformPCA(data, method = "features") plotPCAScatter(pca_result)
Performs t-SNE dimensionality reduction on waveform data. Requires the Rtsne package.
waveformTSNE( x, perplexity = 30, n_components = 2, max_iter = 1000, features = c("statistical", "shape"), use_pca = TRUE, n_pca = 30, seed = NULL )waveformTSNE( x, perplexity = 30, n_components = 2, max_iter = 1000, features = c("statistical", "shape"), use_pca = TRUE, n_pca = 30, seed = NULL )
x |
A PhysioExperiment object, matrix, or waveform_pca result. |
perplexity |
t-SNE perplexity parameter. |
n_components |
Number of dimensions (usually 2). |
max_iter |
Maximum iterations. |
features |
If x is waveform data, features to extract. |
use_pca |
Logical; pre-reduce with PCA. |
n_pca |
Number of PCA components. |
seed |
Random seed. |
A list of class "waveform_tsne" containing:
embedding |
t-SNE coordinates |
n_obs |
Number of observations |
van der Maaten L, Hinton G (2008). "Visualizing Data using t-SNE." Journal of Machine Learning Research, 9, 2579-2605.
waveformPCA(), waveformUMAP(), extractWaveformFeatures()
Performs UMAP dimensionality reduction on waveform data for visualization. Requires the uwot package.
waveformUMAP( x, n_neighbors = 15, n_components = 2, min_dist = 0.1, metric = "euclidean", features = c("statistical", "shape"), use_pca = TRUE, n_pca = 30, seed = NULL )waveformUMAP( x, n_neighbors = 15, n_components = 2, min_dist = 0.1, metric = "euclidean", features = c("statistical", "shape"), use_pca = TRUE, n_pca = 30, seed = NULL )
x |
A PhysioExperiment object, matrix, or waveform_pca result. |
n_neighbors |
Number of neighbors for UMAP. |
n_components |
Number of UMAP dimensions (usually 2). |
min_dist |
Minimum distance parameter. |
metric |
Distance metric: "euclidean", "cosine", "manhattan". |
features |
If x is waveform data, features to extract. |
use_pca |
Logical; pre-reduce with PCA (recommended for high-dim). |
n_pca |
Number of PCA components to use as input. |
seed |
Random seed for reproducibility. |
A list of class "waveform_umap" containing:
embedding |
UMAP coordinates (observations x n_components) |
n_obs |
Number of observations |
params |
UMAP parameters used |
van der Maaten L, Hinton G (2008). "Visualizing Data using t-SNE." Journal of Machine Learning Research, 9, 2579-2605.
waveformPCA(), waveformTSNE(), plotUMAP(), extractWaveformFeatures()
## Not run: # UMAP on gait data data <- matrix(rnorm(1000), nrow = 100, ncol = 10) umap_result <- waveformUMAP(data, n_neighbors = 15) plotUMAP(umap_result) ## End(Not run)## Not run: # UMAP on gait data data <- matrix(rnorm(1000), nrow = 100, ncol = 10) umap_result <- waveformUMAP(data, n_neighbors = 15) plotUMAP(umap_result) ## End(Not run)
Write a benchmark manifest template to CSV
writeBenchmarkManifest(path, n = 1L, overwrite = FALSE)writeBenchmarkManifest(path, n = 1L, overwrite = FALSE)
path |
Output CSV path. |
n |
Number of template rows. |
overwrite |
Logical; overwrite existing file if |
Invisibly returns path.
Bland JM, Altman DG (1986). "Statistical Methods for Assessing Agreement Between Two Methods of Clinical Measurement." Lancet, 327(8476), 307-310.
benchmarkManifestTemplate() for creating the manifest data.frame,
validateBenchmarkManifest() for validating manifest structure.
## Not run: writeBenchmarkManifest("benchmark_manifest.csv", n = 3) ## End(Not run)## Not run: writeBenchmarkManifest("benchmark_manifest.csv", n = 3) ## End(Not run)