Biomechanical Operations¶
Functions for computing biomechanical metrics such as phase angles, continuous relative phase, signal filtering, movement onset detection, and data normalisation.
Filtering¶
- biomechzoo.biomech_ops.filter_data.filter_data(data, ch, filt=None)[source]¶
Filter one or more channels from a zoo data dictionary using specified filter parameters.
- Parameters:
data (dict) – The zoo data dictionary containing signal channels.
ch (str or list of str) – The name(s) of the channel(s) to filter.
filt (dict, optional) – Dictionary specifying filter parameters. Keys may include: - ‘ftype’: ‘butter’ (default) - ‘order’: filter order (default: 4) - ‘cutoff’: cutoff frequency or tuple (Hz) - ‘btype’: ‘low’, ‘high’, ‘bandpass’, ‘bandstop’ (default: ‘lowpass’)
- Returns:
data (dict) – The updated data dictionary with filtered channels.
- Parameters:
- Return type:
- biomechzoo.biomech_ops.filter_line.filter_line(signal_raw, filt=None, fs=None)[source]¶
Filter a 1-D signal array using a Butterworth filter.
- Parameters:
signal_raw (ndarray) – Raw 1-D signal to be filtered.
filt (dict, optional) – Filter parameter dictionary with keys: - ‘ftype’ : str — filter type, e.g. ‘butter’ (default) - ‘order’ : int — filter order (default: 4) - ‘cutoff’ : float or tuple — cutoff frequency in Hz - ‘btype’ : str — ‘lowpass’, ‘highpass’, ‘bandpass’, or ‘bandstop’ - ‘filtfilt’ : bool — zero-phase filtering if True - ‘fs’ : float — sampling frequency in Hz (required)
fs (float, optional) – Sampling frequency in Hz. Only used when filt is not provided.
- Returns:
signal_filtered (ndarray) – Filtered signal array.
- Raises:
ValueError – If ‘fs’ is not provided when filt is None, or if ‘fs’ key is missing from the filt dictionary.
NotImplementedError – If a filter type other than ‘butter’ is specified.
- Parameters:
- Return type:
- biomechzoo.biomech_ops.filter_line.kt_butter(ts, fc, fs, order=2, btype='lowpass', filtfilt=True)[source]¶
Apply a Butterworth filter to a time series.
- Parameters:
ts (ndarray) – 1-D input time series to filter.
fc (float or tuple of float) – Cut-off frequency in Hz. Use a float for lowpass/highpass filters, or a tuple of two floats (e.g.,
(10., 13.)) for bandpass/bandstop.fs (float) – Sampling frequency in Hz.
order (int, optional) – Order of the Butterworth filter. Default is 2.
btype ({‘lowpass’, ‘highpass’, ‘bandpass’, ‘bandstop’}, optional) – Type of filter. Default is ‘lowpass’.
filtfilt (bool, optional) – If True, the filter is applied twice (forward and backward) to eliminate phase lag. If False, only a forward pass is applied. Default is True.
- Returns:
ts_f (ndarray) – Filtered copy of the input time series.
- Parameters:
- Return type:
Notes
This function was adapted from kineticstoolkit. Thanks @felxi.
Phase Angle¶
- biomechzoo.biomech_ops.phase_angle_data.phase_angle_data(data, channels)[source]¶
Compute phase angle for one or more channels using the Hilbert transform.
- Parameters:
data (dict) – Biomechanical data dictionary loaded from a zoo file.
channels (list of str) – Channel names on which to compute the phase angle.
- Returns:
data_new (dict) – Updated data dictionary with phase angle results appended as new channels named ‘<channel>_phase_angle’.
- Raises:
ValueError – If a specified channel is not found in the data dictionary.
- Parameters:
- Return type:
See also
phase_angle_lineCore line-level phase angle computation.
continuous_relative_phase_dataCompute CRP from phase angle channels.
- biomechzoo.biomech_ops.phase_angle_line.phase_angle_line(r)[source]¶
Compute phase angle for a single kinematic waveform using the Hilbert transform.
- Parameters:
r (array_like) – 1-D array of kinematic data (e.g., joint or segment angle).
- Returns:
PA (ndarray) – 1-D array of phase angle in degrees computed via the Hilbert transform.
- Parameters:
r (_SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes])
- Return type:
References
Lamb and Stöckl (2014). On the use of continuous relative phase. Clinical Biomechanics. https://doi.org/10.1016/j.clinbiomech.2014.03.008
Continuous Relative Phase¶
- biomechzoo.biomech_ops.continuous_relative_phase_data.continuous_relative_phase_data(data, ch_dist, ch_prox)[source]¶
Compute continuous relative phase (CRP) between two kinematic channels.
Determines the CRP on a 0-180 scale, correcting for discontinuities in signals greater than 180 degrees.
- Parameters:
data (dict) – Biomechanical data dictionary loaded from a zoo file.
ch_dist (str) – Name of the distal channel (e.g., knee angle).
ch_prox (str) – Name of the proximal channel (e.g., hip angle).
- Returns:
data_new (dict) – Updated data dictionary with a new CRP channel appended, named ‘<ch_dist>_<ch_prox>_crp’.
- Parameters:
- Return type:
See also
phase_angle_dataCompute phase angle using the Hilbert transform.
continuous_relative_phase_lineCore line-level CRP computation.
- biomechzoo.biomech_ops.continuous_relative_phase_line.continuous_relative_phase_line(dist, prox)[source]¶
Compute continuous relative phase (CRP) between two kinematic waveforms.
Determines CRP on a 0-180 scale, correcting for discontinuities in signals greater than 180 degrees.
- Parameters:
dist (ndarray) – Kinematic data of the distal segment or joint.
prox (ndarray) – Kinematic data of the proximal segment or joint.
- Returns:
crp (ndarray) – Continuous relative phase between dist and prox data.
- Parameters:
dist (_SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes])
prox (_SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes])
- Return type:
Normalisation¶
- biomechzoo.biomech_ops.normalize_data.normalize_data(data, nlength=101)[source]¶
Normalize all channels in a zoo data dictionary to a target length.
- Parameters:
data (dict) – Biomechanical data dictionary loaded from a zoo file.
nlength (int, optional) – Target number of samples after normalization. Default is 101, which corresponds to 0-100% of a movement cycle.
- Returns:
data_new (dict) – Deep copy of the input data with all channel ‘line’ arrays resampled to
nlengthsamples.- Parameters:
- Return type:
Notes
It is often necessary to partition data to a single cycle first (see
partition_data()) before normalizing.Event data and zoosystem metadata are not fully updated in the current implementation; warnings are issued accordingly.
- biomechzoo.biomech_ops.normalize_line.normalize_line(channel_data, nlength=101)[source]¶
Interpolate a channel array to a target length.
- Parameters:
channel_data (ndarray) – 1-D or 2-D numpy array of shape (n,) or (n, k) to be resampled.
nlength (int, optional) – Target number of samples. Default is 101.
- Returns:
channel_data_norm (ndarray) – Array resampled to shape (nlength,) or (nlength, k) using linear interpolation.
- Parameters:
- Return type:
Movement Onset¶
- biomechzoo.biomech_ops.movement_onset.movement_onset(yd, fsamp, constants)[source]¶
Detect the time of movement onset from an acceleration magnitude signal.
Uses sliding-window mean and standard deviation to identify when sustained movement begins. Thresholds are relaxed iteratively if no onset is found.
- Parameters:
yd (ndarray) – 1-D array of the acceleration magnitude signal.
fsamp (float) – Sampling frequency in Hz.
constants (list of float) – Threshold constants
[mean_thresh, std_thresh]. Recommended values: running —[1.2, 0.2]; walking —[0.6, 0.2].
- Returns:
onset_time (int or None) – Sample index of detected movement onset, or None if not detected.
- Parameters:
- Return type:
int | None
Notes
The signal is low-pass filtered at 20 Hz (4th-order Butterworth) before feature extraction. Thresholds are halved each iteration until onset is found or the minimum threshold (0.1) is reached.
- biomechzoo.biomech_ops.movement_onset.movement_offset(yd, fsamp, constants)[source]¶
Detect the time of movement offset from an acceleration magnitude signal.
Mirrors the logic of
movement_onset()by reversing the signal before detection, then mapping the result back to original time.- Parameters:
yd (ndarray) – 1-D array of the acceleration magnitude signal.
fsamp (float) – Sampling frequency in Hz.
constants (list of float) – Threshold constants
[mean_thresh, std_thresh].
- Returns:
onset_time (int or None) – Sample index of detected movement offset, or None if not detected.
- Parameters:
- Return type:
int | None
- biomechzoo.biomech_ops.movement_onset.sliding_window_features(ch_data, fsamp)[source]¶
Compute mean/std features over a 2-second sliding window.
- Parameters:
ch_data (ndarray) – 1-D input signal.
fsamp (float) – Sampling frequency in Hz. Must be an integer value in practice, since it is used directly as a window/step size in
range(), which requires integer arguments.
- Returns:
features (ndarray of shape (n_windows, 2)) – Per-window
(mean, std)feature pairs.timestamps (ndarray of shape (n_windows,)) – Start sample index of each window.
- Parameters:
- Return type:
- biomechzoo.biomech_ops.movement_onset.check_already_moving(features, mean_thresh=1.2, std_thresh=0.2)[source]¶
Check whether the signal is already moving at the start of the window.
- Parameters:
features (ndarray of shape (n_windows, 2)) – Per-window
(mean, std)features, as returned bysliding_window_features().mean_thresh (float, optional) – Mean threshold for the movement to be considered active. Default is 1.2.
std_thresh (float, optional) – Std threshold for the movement to be considered active. Default is 0.2.
- Returns:
already_moving (bool) – True if the first 5 windows all exceed both thresholds.
- Parameters:
- Return type:
- biomechzoo.biomech_ops.movement_onset.detect_movement_onset(features, fs, mean_thresh=1.2, std_thresh=0.2, min_duration=3)[source]¶
Detect the first window index where sustained movement begins.
- Parameters:
features (ndarray of shape (n_windows, 2)) – Per-window
(mean, std)features, as returned bysliding_window_features().fs (float) – Sampling frequency in Hz.
mean_thresh (float, optional) – Mean threshold for a window to count as movement. Default is 1.2.
std_thresh (float, optional) – Std threshold for a window to count as movement. Default is 0.2.
min_duration (float, optional) – Minimum number of consecutive movement windows (scaled by
fs / 50) required to confirm onset. Default is 3.
- Returns:
onset_index (int or None) – Index into
featuresof the first confirmed movement window, or None if not detected.- Parameters:
- Return type:
int | None
- biomechzoo.biomech_ops.movement_onset.bw_filter(data, fsamp, N, fc, btype, output='ba')[source]¶
Apply a zero-phase Butterworth filter to a 1-D signal.
- Parameters:
data (ndarray) – 1-D input signal array.
fsamp (float) – Sampling frequency in Hz.
N (int) – Filter order.
fc (float) – Cutoff frequency in Hz.
btype (str) – Filter type (e.g., ‘low’, ‘high’, ‘bandpass’).
output (str, optional) – Output format for scipy.signal.butter. Default is ‘ba’.
- Returns:
filtered_data (ndarray) – Zero-phase filtered signal of the same shape as input.
- Parameters:
- Return type:
Resampling¶
- biomechzoo.biomech_ops.resample.resample_data(signal_dict, up, down, axis=0)[source]¶
Upsample/downsample data using
scipy.signal.resample_poly.- Parameters:
signal_dict (dict) – Zoo data dictionary. Only numeric ndarray/list-valued entries are resampled; the ‘zoosystem’ entry and non-numeric or empty arrays are copied through unchanged.
up (int) – Upsampling factor.
down (int) – Downsampling factor.
axis (int, optional) – Axis along which to resample. Default is 0.
- Returns:
new_dict (dict) – New dictionary with resampled arrays.
- Raises:
ValueError – If both
upanddownare 1 (no resampling requested).- Parameters:
- Return type: