Analysis¶
analysis
¶
Motion analysis for BVH data.
Velocities, accelerations, angular velocities, root trajectory, and foot
contacts. Every function takes a :class:~pybvh.bvh.Bvh object as its
first argument; thin wrapper methods on the Bvh class delegate here.
Feature-array export for ML pipelines lives in :mod:pybvh.features.
Velocities & accelerations¶
The finite-difference kinematics ladder over FK positions and rotations.
node_velocities(bvh: Bvh, centered: str = 'world', in_frames: bool = False, stencil: str = 'central', pad: str = 'edge') -> npt.NDArray[np.float64]
¶
Compute per-node position velocities (joints + end sites).
Differentiates through :func:pybvh.signal.finite_difference, with
two orthogonal choices:
stencilpicks the finite-difference method — central (second-order accurate, symmetric) or forward (first-order, causal).padpicks the boundary-handling convention —"edge"fills the boundary so the output has the same shape as the input;"none"drops the boundary frames that the stencil can't define.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bvh
|
Bvh
|
Input motion. |
required |
centered
|
str
|
Coordinate centering mode (default |
'world'
|
in_frames
|
bool
|
If True, return velocity in units/frame. If False (default), return velocity in units/second. |
False
|
stencil
|
('central', 'forward')
|
|
"central"
|
pad
|
('edge', 'none')
|
|
"edge"
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Shape depends on ========= ====== ================
stencil pad shape
========= ====== ================
central edge |
See Also
joint_velocities : Same data restricted to non-end-site joints
((F, J, 3)). Use that when the output should index-align
with :attr:Bvh.joint_angles / :func:angular_velocities.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the clip is too short for the chosen combination,
|
joint_velocities(bvh: Bvh, centered: str = 'world', in_frames: bool = False, stencil: str = 'central', pad: str = 'edge') -> npt.NDArray[np.float64]
¶
Compute per-joint position velocities (end sites excluded).
Returns the joint-axis subset of :func:node_velocities — same
finite-difference math, but restricted to non-end-site joints so
the output indexes match :attr:Bvh.joint_angles and
:func:angular_velocities. Output shape is (F, J, 3) (or the
appropriate trimmed variant per stencil × pad).
See :func:node_velocities for the full parameter / shape docs.
node_accelerations(bvh: Bvh, centered: str = 'world', in_frames: bool = False, stencil: str = 'central', pad: str = 'edge') -> npt.NDArray[np.float64]
¶
Compute per-node position accelerations (joints + end sites).
Applies the chosen stencil twice to the input positions and pads
or crops once, at the end:
:func:pybvh.signal.finite_difference with order=2.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bvh
|
Bvh
|
Input motion. |
required |
centered
|
str
|
Coordinate centering mode (default |
'world'
|
in_frames
|
bool
|
If True, return acceleration in units/frame^2. If False (default), return in units/second^2. |
False
|
stencil
|
('central', 'forward')
|
Finite-difference method applied twice. Default |
"central"
|
pad
|
('edge', 'none')
|
Boundary handling. |
"edge"
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Shape depends on ========= ====== ================
stencil pad shape
========= ====== ================
central edge |
Composition identity: ``np.gradient(node_velocities(), dt)`` equals
|
|
``node_accelerations()`` exactly under the defaults
|
|
(``stencil="central"``, ``pad="edge"``). Not guaranteed for other
|
|
combinations.
|
|
See Also
joint_accelerations : Same data restricted to non-end-site joints
((F, J, 3)).
Raises:
| Type | Description |
|---|---|
ValueError
|
If the clip is too short for the chosen combination,
|
joint_accelerations(bvh: Bvh, centered: str = 'world', in_frames: bool = False, stencil: str = 'central', pad: str = 'edge') -> npt.NDArray[np.float64]
¶
Compute per-joint position accelerations (end sites excluded).
Returns the joint-axis subset of :func:node_accelerations — same
twice-applied finite-difference math, restricted to non-end-site
joints so output indexes match :attr:Bvh.joint_angles. Output
shape is (F, J, 3) (or the appropriate trimmed variant per
stencil × pad).
See :func:node_accelerations for the full parameter / shape docs.
node_speed_derivative(bvh: Bvh, centered: str = 'world', in_frames: bool = False, stencil: str = 'central', pad: str = 'edge') -> npt.NDArray[np.float64]
¶
Per-node rate of change of speed d‖v‖/dt (joints + end sites).
Computes the per-node speed ‖v‖ from :func:node_velocities, then
applies the same finite-difference stencil once more to that scalar
series. Positive values mean the node is speeding up, negative
values mean it is slowing down — the natural "is the movement
accelerating or braking" signal, independent of direction changes.
This is the tangential acceleration a_t = d‖v‖/dt of the
node's trajectory. The complementary normal (centripetal) component
is a_n = ‖v‖² · κ with κ the trajectory curvature
(:func:pybvh.geometry.curvature), and the two decompose the full
acceleration vector: a_t² + a_n² = ‖a‖².
It is not recoverable from :func:node_accelerations: this is
the difference of the norm (Δ‖v⃗‖), not the norm of the
difference (‖Δv⃗‖ = ‖a⃗‖). A direction change at constant speed
gives ‖a⃗‖ > 0 but d‖v‖/dt = 0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bvh
|
Bvh
|
Input motion. |
required |
centered
|
str
|
Coordinate centering mode (default |
'world'
|
in_frames
|
bool
|
If True, return the rate in units/frame^2. If False (default), return in units/second^2. |
False
|
stencil
|
('central', 'forward')
|
Finite-difference method, applied at both stages (positions →
velocities, speed → its derivative). Default |
"central"
|
pad
|
('edge', 'none')
|
Boundary handling, applied at both stages. |
"edge"
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Shape depends on ========= ====== ================
stencil pad shape
========= ====== ================
central edge |
See Also
joint_speed_derivative : Same data restricted to non-end-site
joints ((F, J)).
node_accelerations : The vector second derivative — its norm is the
full ‖a‖, of which this is the tangential component.
velocity_reductions : peak_acceleration / peak_deceleration
are the extrema of this series (stencil="forward",
pad="none").
Raises:
| Type | Description |
|---|---|
ValueError
|
If the clip is too short for the chosen combination,
|
Notes
Source: Hachimura et al. 2005 (Time Effort).
joint_speed_derivative(bvh: Bvh, centered: str = 'world', in_frames: bool = False, stencil: str = 'central', pad: str = 'edge') -> npt.NDArray[np.float64]
¶
Per-joint rate of change of speed d‖v‖/dt (end sites excluded).
Returns the joint-axis subset of :func:node_speed_derivative —
same two-stage finite-difference math, restricted to non-end-site
joints so output indexes match :attr:Bvh.joint_angles. Output
shape is (F, J) (or the appropriate trimmed variant per
stencil × pad).
See :func:node_speed_derivative for the full parameter / shape /
sign-semantics docs.
angular_velocities(bvh: Bvh, in_frames: bool = False, stencil: str = 'central', pad: str = 'edge', degrees: bool = False) -> npt.NDArray[np.float64]
¶
Compute per-joint angular velocities via rotation matrix log map.
These are the rates of each joint's parent-relative (local)
rotation — the BVH channels themselves — expressed in the joint's
own (body) frame: ω[i] = log(R_i^T @ R_{i+1}) / dt on the local
rotation matrices, no forward kinematics involved. Two published
alternatives differ: the world-frame angular velocity of a
segment (the biomechanics convention) composes rotations down the
chain first and diverges for every joint whose parent is itself
rotating; and the spatial-frame rate log(R_{i+1} @ R_i^T)
differs from the body-frame rate by conjugation with R — same
magnitude, rotated axis. The local convention is what BVH data
natively parameterizes; compose Bvh.to_rotmat output through
the hierarchy yourself if you need segment rates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bvh
|
Bvh
|
Input motion. |
required |
in_frames
|
bool
|
If True, return angular velocity in radians/frame (or
degrees/frame if |
False
|
degrees
|
bool
|
If True, convert the final output from radians to degrees.
Default False (radians). Consistent with the |
False
|
stencil
|
('central', 'forward')
|
|
"central"
|
pad
|
('edge', 'none')
|
|
"edge"
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Shape depends on ========= ====== ================
stencil pad shape
========= ====== ================
central edge Direction is the rotation axis; magnitude is the rotation
angle (radians or radians/second). Angles are clamped to
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If fewer than 2 frames ( |
Root trajectory & foot contacts¶
Ground-plane features of the body anchor and binary contact labels. The Gallery draws the contact signals.
root_trajectory(bvh: Bvh, world_up: str | None = None, include_velocities: bool = False, stencil: str = 'central', pad: str = 'edge', degrees: bool = False) -> npt.NDArray[np.float64]
¶
Extract root trajectory features commonly used in motion ML.
Returns the ground-plane position and heading angle (as
sin/cos pair) of :attr:~pybvh.bvh.Bvh.body_anchor, the joint
the body's measures start from. On a clip whose anchor is its root,
the most common case, that is the root's. Optionally appends
ground-plane and heading velocities.
The heading reference is :attr:~pybvh.bvh.Bvh.rest_forward, the
direction the rest pose faces in the skeleton's own frame (rest left
× rest up, read from the rest pose alone). The body anchor's world
rotation at each frame (its own rotation composed with those of the
joints above it) carries it into the world, and the heading is its
projection on the ground. At a frame whose anchor's world rotation
is identity the heading is therefore rest forward's own ground
direction, whatever
rotation the clip starts with. When rest forward is the house
default (no usable left/right geometry; reading it warns), the
heading is still built on it, and both the heading and its rate of
turn (heading_vel) depend on that guessed reference whenever
the anchor pitches or rolls: a tilted anchor's forward projects on
the ground at an angle, and turns there at a rate, that differ with
the forward it starts from. On a defaulted rest forward they are
reliable only for an anchor that turns about world up alone.
:func:facing_frame chooses otherwise for its fallback, which takes
no heading from a defaulted rest forward.
The heading is orientation-derived — the body anchor's world
rotation applied to the rest forward, projected to the ground plane — not
the direction of travel (a side-stepping character keeps its
heading). It therefore inherits pelvis twist, and its ground-plane
projection shrinks when the character bends far forward;
:func:facing_frame is the whole-body, yaw-only alternative that
avoids both. For the direction of motion, differentiate the ground
position (the ground_*_vel columns).
On a frame where that projection is too short to read (the anchor's
forward stands along world up, norm below 1e-6) the heading is
undefined, and its heading_sin and heading_cos are NaN,
the :mod:pybvh.geometry policy for values the motion makes
undefined, rather than an arbitrary angle. With
include_velocities=True the NaN spreads into the
heading_vel samples whose finite-difference stencil reads that
frame (with the default central stencil, the frames either side of
it); the heading is unwrapped over the readable frames only, so no
other sample is affected. The ground columns are always finite.
The function keeps its name, but the trajectory is the body
anchor's, not the root's. On a root that stays in place with the
body below it (a static root, CHANNELS 0, or a reference node
whose channels do not change), it therefore describes the body: the
body anchor travels and turns while the root stays still.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bvh
|
Bvh
|
Input motion. |
required |
world_up
|
str or None
|
Signed axis string (e.g. |
None
|
include_velocities
|
bool
|
If True, append |
False
|
stencil
|
optional
|
Only used with |
'central'
|
pad
|
optional
|
Only used with |
'central'
|
degrees
|
bool
|
If True, convert the |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Shape Columns: |
foot_contacts(bvh: Bvh, feet: Sequence[NodeSelector] | None = None, method: str = 'combined', *, vel_threshold: float | Sequence[float] | npt.NDArray[np.float64] | None = None, vel_smooth_duration: float | None = None, height_threshold: float | Sequence[float] | npt.NDArray[np.float64] | None = None, floor: float | str | None = None, min_contact_duration: float = 0.1, min_gap_duration: float = 0.1, hysteresis: float = 0.25, adaptive: bool = False, height_reference: str | None = None, return_info: bool = False) -> npt.NDArray[np.float64] | tuple[npt.NDArray[np.float64], _contacts.ContactReport]
¶
Detect binary foot contact labels per frame.
The default combines a velocity check (foot not moving) and a
height check (foot near the ground) following the HuMoR heuristic
— each signal catches a different failure mode of the other.
method="velocity" and method="height" remain available as
single-signal escape hatches.
The sizes are read from the joint the feet branch from: the lowest joint that has the feet in two or more of its branches (the hips of a biped, where the hind and the front chains part on a quadruped), else, for one foot or feet along one leg, :attr:~pybvh.Bvh.body_anchor. The skeleton scale of the default thresholds is the feet's mean rest distance to that joint, as in :func:skeleton_size, and the "feet below hips" check compares the feet's rest height with its. A root above or beside the body is passed over.
The positions tested are the clip's world-frame forward kinematics, which the clip caches (:meth:Bvh.node_positions). Positions the caller holds (smoothed, predicted or edited) take the array path: the node's row is bvh.index(name, space="node"), and :mod:pybvh.geometry and :mod:pybvh.signal measure it.
Each method reads its own settings, and a setting given that the chosen method does not read raises a ValueError instead of being ignored: method="velocity" reads vel_threshold and vel_smooth_duration; method="height" reads height_threshold and floor; method="combined" reads all four, and height_reference when height_threshold is not given. Every method reads min_contact_duration, min_gap_duration and hysteresis, and adaptive where it leaves a threshold to derive. The settings some method does not read default to None, which stands for the default named under each.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bvh
|
Bvh
|
Input motion. |
required |
feet
|
sequence of str or BvhNode, or None
|
The feet to test, each a node name or one of |
None
|
method
|
('combined', 'velocity', 'height')
|
|
"combined"
|
vel_threshold
|
float, array_like of shape (n_feet,), or None, keyword-only
|
Speed threshold in world units per second, finite and above
zero: one value for every foot, or one per foot in the order of
the contacts' columns, such as a :class: |
None
|
vel_smooth_duration
|
(float or None, keyword - only)
|
Physical time span (seconds) the foot-speed estimator is
conditioned over before thresholding. Displacement vectors are
box-averaged over |
None
|
height_threshold
|
float, array_like of shape (n_feet,), or None, keyword-only
|
Clearance above the estimated floor, in world units, finite and
above zero: one value for every foot, or one per foot, as
|
None
|
floor
|
float, ``"auto"``, ``"min"`` or None, keyword-only
|
Height of the reference the clearance is measured against, along
the raw This reference is not :attr: |
None
|
min_contact_duration
|
(float, keyword - only)
|
Morphological open: contact runs shorter than this many
seconds are set to 0. Default |
0.1
|
min_gap_duration
|
(float, keyword - only)
|
Morphological close: non-contact gaps shorter than this many
seconds are filled (set to 1). Default |
0.1
|
hysteresis
|
(float, keyword - only)
|
Schmitt-trigger band fraction, in |
0.25
|
adaptive
|
(bool, keyword - only)
|
If True, split a threshold left to derive from each foot's own
signal (Otsu's bimodal split between the stance and swing
clusters) instead of taking the fixed scale fraction. What it
splits depends on the method: under |
False
|
height_reference
|
('velocity', 'floor')
|
How the default |
"velocity"
|
return_info
|
(bool, keyword - only)
|
If True, return |
False
|
Returns:
| Type | Description |
|---|---|
ndarray of shape ``(F, n_feet)``, or
|
|
tuple ``(ndarray, ContactReport)`` when ``return_info=True``.
|
Binary contact labels (1.0 = contact, 0.0 = no contact).
For |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
TypeError
|
If |
See Also
ground_contacts : The same detection engine for arbitrary (non-foot) node sets — hands, knees, props.
auto_detect_feet : The detection used when feet is None.
ground_contacts(bvh: Bvh, nodes: Sequence[NodeSelector], method: str = 'combined', *, vel_threshold: float | Sequence[float] | npt.NDArray[np.float64] | None = None, vel_smooth_duration: float | None = None, height_threshold: float | Sequence[float] | npt.NDArray[np.float64] | None = None, floor: float | str | None = None, min_contact_duration: float = 0.1, min_gap_duration: float = 0.1, hysteresis: float = 0.25, adaptive: bool = False, height_reference: str | None = None, return_info: bool = False) -> npt.NDArray[np.float64] | tuple[npt.NDArray[np.float64], _contacts.ContactReport]
¶
Detect ground-contact labels for an arbitrary set of nodes.
The same detection engine as :func:foot_contacts — velocity and/or clearance-above-floor thresholding with hysteresis and duration filters — but for any node set: hands during floor work, knees in a crawl, a prop bone, a fingertip end site. Because the nodes are not assumed to be feet, two foot-specific behaviors are dropped: there is no rest-pose "feet below hips" sanity check, and height_reference defaults to "floor" instead of :func:foot_contacts' "velocity" — the per-node stance calibration behind "velocity" presumes regular ground contact, which feet in locomotion have and a hand that touches the floor twice does not.
The positions tested are the clip's cached world-frame forward kinematics, as in :func:foot_contacts.
.. warning::
With the default floor="auto" the floor is estimated from the given nodes' own trajectories (2nd percentile of their per-frame minimum height). A node set that never actually grounds makes its lowest hover point the "floor" and fabricates contacts there. Unless the nodes genuinely reach the ground for a meaningful fraction of the clip, pass an explicit float. :attr:Bvh.floor_height is the scene ground and reads low for this purpose — it is measured over all nodes, including end sites that reach below any joint centre — so a joint compared against it needs a height_threshold widened by that offset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bvh
|
Bvh
|
Input motion. |
required |
nodes
|
sequence of str or BvhNode
|
The nodes to test, each a node name or one of |
required |
method
|
('combined', 'velocity', 'height')
|
Same meaning as in :func: |
"combined"
|
vel_threshold
|
keyword - only
|
Same meaning and defaults as in :func: |
None
|
vel_smooth_duration
|
keyword - only
|
Same meaning and defaults as in :func: |
None
|
height_threshold
|
keyword - only
|
Same meaning and defaults as in :func: |
None
|
floor
|
keyword - only
|
Same meaning and defaults as in :func: |
None
|
min_contact_duration
|
keyword - only
|
Same meaning and defaults as in :func: |
None
|
min_gap_duration
|
keyword - only
|
Same meaning and defaults as in :func: |
None
|
hysteresis
|
keyword - only
|
Same meaning and defaults as in :func: |
None
|
adaptive
|
keyword - only
|
Same meaning and defaults as in :func: |
None
|
height_reference
|
('floor', 'velocity')
|
|
"floor"
|
return_info
|
(bool, keyword - only)
|
As in :func: |
False
|
Returns:
| Type | Description |
|---|---|
ndarray of shape ``(F, n_nodes)``, or tuple ``(ndarray, ContactReport)`` when ``return_info=True``.
|
Binary contact labels (1.0 = contact); columns follow |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
TypeError
|
If |
See Also
foot_contacts : The foot-specialized entry point (auto-detection, rest-pose sanity check, height_reference="velocity" default).
ContactReport(*, nodes: tuple[BvhNode, ...], method: str, vel_smooth_duration: float | None, vel_smooth_frames: int | None, height_reference: str | None, min_contact_duration: float, min_gap_duration: float, hysteresis: float, adaptive: bool, floor_setting: float | _FloorEstimate | None, skeleton_scale: float, skeleton_scale_measured: bool, vel_threshold: npt.NDArray[np.float64] | None, vel_threshold_source: tuple[_VelocitySource, ...] | None, speed: npt.NDArray[np.float64] | None, height_threshold: npt.NDArray[np.float64] | None, height_threshold_source: tuple[_HeightSource, ...] | None, contact_reference: float | None, clearance: npt.NDArray[np.float64] | None, confidence: npt.NDArray[np.float64], foot_skate_mean: npt.NDArray[np.float64], foot_skate_max: npt.NDArray[np.float64], airborne_fraction: float, height_at_contact: npt.NDArray[np.float64] | None)
dataclass
¶
What one contact detection applied, and the signals it compared.
Returned beside the contacts by :func:pybvh.analysis.foot_contacts and :func:pybvh.analysis.ground_contacts (and their Bvh wrappers) when return_info=True. Every field is always present: a field the call's method does not use is None. A per-node value is (n_nodes,) in the order of nodes, the order of the contacts' columns, whether one node is tested or several; nothing is averaged over the nodes. Frozen, and its arrays are read-only; == compares identity, since the fields hold arrays.
Attributes:
| Name | Type | Description |
|---|---|---|
nodes |
tuple of BvhNode
|
The tested nodes, the clip's own, in column order, however they were selected (by name or as |
method |
{'combined', 'velocity', 'height'}
|
The method applied. |
vel_smooth_duration |
float or None
|
The span (seconds) the speed is smoothed over; |
vel_smooth_frames |
int or None
|
That span in frames, the window applied. |
height_reference |
{'velocity', 'floor'} or None
|
How the height threshold was anchored; |
min_contact_duration, min_gap_duration |
float
|
The duration filters applied, in seconds. |
hysteresis |
float
|
The hysteresis band applied, as a fraction of each threshold. |
adaptive |
bool
|
Whether Otsu's split was asked for ( |
floor_setting |
{"auto", "min"} or float, or None
|
The |
skeleton_scale |
float
|
The scale the default thresholds are written in and the foot skate is divided by: the mean rest distance to the tested nodes from the joint they branch from under :func: |
skeleton_scale_measured |
bool
|
Whether |
vel_threshold |
ndarray, shape (n_nodes,), or None
|
The speed threshold applied to each node, in units per second; |
vel_threshold_source |
tuple of str, or None
|
Where each node's |
speed |
ndarray, shape (F, n_nodes), or None
|
Each node's speed, in units per second, the signal compared against |
height_threshold |
ndarray, shape (n_nodes,), or None
|
The clearance threshold applied to each node, in world units; |
height_threshold_source |
tuple of str, or None
|
Where each node's |
contact_reference |
float or None
|
The contact reference, along the raw |
clearance |
ndarray, shape (F, n_nodes), or None
|
Each node's height above |
confidence |
(ndarray, shape(n_nodes))
|
Each node's detection decisiveness in |
foot_skate_mean, foot_skate_max |
(ndarray, shape(n_nodes))
|
The mean and the largest, over each node's contact runs of two frames or more, of how far the node drifts horizontally within the run, divided by the skeleton scale; a planted node should be near |
airborne_fraction |
float
|
The fraction of frames in which no tested node is in contact. |
height_at_contact |
ndarray, shape (n_nodes,), or None
|
Each node's mean |
auto_detect_feet(bvh: Bvh) -> list[BvhNode]
¶
Auto-detect the clip's feet by topology.
Algorithm:
- Substring match: candidates are the joints of the body whose
names contain
"foot"or"toe"(case-insensitive). The body is :attr:~pybvh.Bvh.body_anchorand every node below it, started at the closest joint above the anchor that has one below it when no joint below the anchor has a head name (head,neck,chest,spine) or a foot name (leg,foot,toe,toes), each read as a word of the name. So a 3ds MaxFootstepsnode beside the hips, or a prop beside the body, is no candidate. - Tip-descendant filter: keep only candidates that have an end site or a toe-named child. This drops IK helpers, which typically have no children.
- Most-distal filter: drop candidates whose subtree (any depth)
contains another candidate. On a rig with
Foot → ToeBase → EndSite, this keeps onlyToeBase— the more distal, ground-contacting joint. - Deterministic order: sort by rest-pose height along
bvh.world_up(lowest first); alphabetical name within ties so the output is stable across runs.
If step 1 produces matches but step 2 drops all of them, the
tip filter is skipped with a UserWarning (better than
returning nothing for unusual rigs).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bvh
|
Bvh
|
Input skeleton. |
required |
Returns:
| Type | Description |
|---|---|
list of BvhNode
|
The feet, nodes of |
Notes
This is the same detection used internally by
:func:foot_contacts when feet=None. Call it
directly to preview the detection or to pass the feet back in:
the nodes select the feet by identity, so a foot whose name another
node shares is still selected, where its name would be refused. The
nodes belong to bvh: another clip, or bvh after an in-place
edit replaced its skeleton, refuses them, and takes their names
([node.name for node in feet]) or its own detection instead.
An empty result is a report, not an error: this function never raises on footless rigs. The contact detectors are where emptiness becomes fatal — :func:foot_contacts and :func:ground_contacts both raise ValueError when handed an empty selection, so a silent [] cannot flow into a zero-column contact array.
Facing frame¶
The continuous per-frame facing basis. It is the vector form of the snapped Bvh.forward_at / Bvh.left_at axis labels.
FacingFrame = namedtuple('FacingFrame', ['forward', 'left', 'up', 'valid'])
module-attribute
¶
facing_frame(bvh: Bvh) -> FacingFrame
¶
Per-frame facing basis of the character, as continuous unit vectors.
Returns the orthonormal right-handed triple (forward, left, up)
for every frame — the continuous form of the axis-label pair
:meth:Bvh.forward_at / :meth:Bvh.left_at, which snap exactly
this basis to the nearest signed world axis. Use the labels for
rest-pose canonicalization and dataset-convention checks; use this
function whenever the actual facing direction matters — the snapped
label stays constant while a character turns through less than 90°,
the vectors track the rotation frame by frame.
This is a yaw-only, gravity-aligned facing frame: up is the
exact :attr:Bvh.world_up unit vector on every frame, so the basis
only ever rotates about the vertical — deliberately not a pelvis
orientation (no roll or pitch; a character bending forward keeps
their facing frame level). It is also distinct from
:func:root_trajectory's heading, which is a second facing
estimate built differently — the body anchor's world rotation applied to
the rest forward — not a direction of motion: that heading inherits
pelvis twist and collapses toward numerical ambiguity when the
character bends far forward, while this basis measures the
whole-body L/R geometry and stays yaw-only. The two diverge
whenever the pelvis turns or tilts relative to the body. Neither
is velocity-based; for the direction of travel, differentiate
ground position (root_trajectory's ground_*_vel columns).
Construction (per frame, all in world space): the leftward
direction is the average of (left_pos - right_pos) over the
L/R joint pairs in :attr:Bvh.lr_mapping whose two joints are in
the body that :attr:Bvh.body_anchor heads, so a prop or a second
figure beside it is not read, projected onto the
horizontal plane and normalized; forward = leftward × up;
left = up × forward (re-orthogonalized). The triple satisfies
forward × left = up.
Fallback policy (shared by :meth:Bvh.forward_at and
:meth:Bvh.left_at): a frame whose horizontal (left - right)
average nearly vanishes or lies along world_up (norm below
1e-6, the body on its side) takes the body's heading at that
frame (the one :func:root_trajectory returns) as its forward, when
:attr:Bvh.rest_forward is measured and that heading is readable
(:func:root_trajectory builds a heading on a defaulted rest
forward too, for its rate of turn; as a facing it would offer a
guessed direction as a measured one); otherwise the arbitrary-but-stable per-up-axis default ('+z' for
a y-up world), with a UserWarning that names the frames. A
skeleton with no lr_mapping takes that default on every frame,
with a warning that names the skeleton. Every row keeps
forward = left × up, so the triple stays orthonormal and
right-handed, and left is never world_up. The valid
field reports exactly those frames: False on every fallback row,
heading or default (all-False when the skeleton has no L/R pairs
at all). The fallback rows still carry a usable basis rather than
nan, so rendering-style consumers can ignore valid; anything
measuring facing should mask by it. The bvhplot follow camera
does: it takes no heading from such frames, and interpolates across
them from the measured frames around them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bvh
|
Bvh
|
Input motion. |
required |
Returns:
| Type | Description |
|---|---|
FacingFrame
|
Named tuple |
See Also
Bvh.forward_at, Bvh.left_at : The categorical (snapped axis label) form of the same construction. root_trajectory : Body-anchor-orientation heading (a different facing estimate — see Notes above; not a travel direction).
Jerk¶
The third rung of the velocity → acceleration → jerk ladder.
node_jerk(bvh: Bvh, centered: str = 'world', in_frames: bool = False, stencil: str = 'central', pad: str = 'edge') -> npt.NDArray[np.float64]
¶
Compute per-node position jerk (third derivative) — (F, N, 3).
Applies the chosen stencil three times to the positions and pads
or crops once, at the end (:func:pybvh.signal.finite_difference
with order=3), the next rung of the velocity → acceleration →
jerk ladder. The jerk magnitude
np.linalg.norm(node_jerk(...), axis=-1) is the usual smoothness
signal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bvh
|
Bvh
|
Input motion. |
required |
centered
|
str
|
Coordinate centering mode (default |
'world'
|
in_frames
|
bool
|
If True, units/frame³; else units/second³ (default). |
False
|
stencil
|
('central', 'forward')
|
Finite-difference method applied three times. Default
|
"central"
|
pad
|
('edge', 'none')
|
|
"edge"
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Per-node jerk. Composition identity:
|
Raises:
| Type | Description |
|---|---|
ValueError
|
Too-short clip, |
joint_jerk(bvh: Bvh, centered: str = 'world', in_frames: bool = False, stencil: str = 'central', pad: str = 'edge') -> npt.NDArray[np.float64]
¶
Per-joint position jerk (end sites excluded) — (F, J, 3).
The joint-axis subset of :func:node_jerk, index-aligned with
:attr:Bvh.joint_angles. See :func:node_jerk for full docs.
Smoothness metrics¶
Array-pure kernels on a speed profile, plus the smoothness(metric=…) dispatcher. The speed profile is (T,) for a scalar, or (T, K) reduced per column.
sparc(speed: npt.NDArray[np.float64], fs: float, padlevel: int = 4, fc: float = 10.0, amp_th: float = 0.05) -> float | npt.NDArray[np.float64]
¶
Spectral arc length (SPARC) smoothness of a speed profile.
The negative arc length of the normalized Fourier magnitude spectrum
over [0, fc] Hz — a smoothness measure that is robust to noise and
invariant to amplitude/duration. Values are ≤ 0; closer to 0
is smoother.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
speed
|
(ndarray, shape(T) or (T, K))
|
Speed profile, or a signed scalar velocity — the spectrum is
taken of the values as given, not their magnitude, so the two
are genuinely different inputs here (matching the reference
implementation). A 2-D input is |
required |
fs
|
float
|
Sampling rate in Hz. |
required |
padlevel
|
int
|
Zero-padding exponent: |
4
|
fc
|
float
|
Upper cutoff frequency in Hz (default 10.0). |
10.0
|
amp_th
|
float
|
Normalized amplitude threshold selecting the spectral band (default 0.05). |
0.05
|
Returns:
| Type | Description |
|---|---|
float or ndarray
|
The spectral arc length (SAL) — a scalar for |
Notes
Source: Balasubramanian et al. 2015, "On the analysis of movement
smoothness." Reimplemented in NumPy; validated against the authors'
reference output (see tests/test_smoothness_golden.py).
dimensionless_jerk(speed: npt.NDArray[np.float64], fs: float, normalize: str = 'peak_speed', amplitude: float | npt.NDArray[np.float64] | None = None) -> float | npt.NDArray[np.float64]
¶
Dimensionless jerk (DLJ) smoothness of a speed profile.
Integrated squared jerk made scale-invariant by dividing out movement
duration and size — -(duration³ / peak²) · ∫ (d²v/dt²)² dt at the
default. More negative is less smooth.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
speed
|
(ndarray, shape(T) or (T, K))
|
Speed profile, or a signed scalar velocity (Hogan & Sternad
define the measure on |
required |
fs
|
float
|
Sampling rate in Hz. |
required |
normalize
|
('peak_speed', 'mean_speed', 'amplitude')
|
Which published normalizer to apply to the jerk integral
(default |
"peak_speed"
|
amplitude
|
float or ndarray
|
The movement extent |
None
|
Returns:
| Type | Description |
|---|---|
float or ndarray
|
The dimensionless jerk ( |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Notes
Hogan & Sternad 2009 give the measure in three forms::
∫(d²v/dt²)² dt · D⁵/A² ≡ · D³/v_mean² | variant: · D³/v_peak²
The first two are the same measure — A = v_mean · D — so
"mean_speed" is exactly "amplitude" evaluated at the arc
length the speed profile itself implies, A = ∫|v| dt. Passing
amplitude= is only a different measure when the extent comes
from somewhere else, most usefully the endpoint displacement
‖p_T − p_0‖, which is smaller than the arc length for any path
that is not straight. (For the arc length of a trajectory, prefer
"mean_speed" over amplitude=geometry.path_length(traj): the
chord sum uses a different quadrature than this function's integral
and will not agree exactly.)
"peak_speed" — the default, and what the widely used reference
implementation computes — is genuinely distinct from the other two.
It differs by a factor of (v_mean / v_peak)², which depends on the
shape of the speed profile rather than being constant, so a
bell-shaped reach and a plateaued sustained movement of equal extent
and duration rank differently under it. That factor is
:func:speed_metric, so dimensionless_jerk(v, fs, "mean_speed")
equals dimensionless_jerk(v, fs) / speed_metric(v)**2.
Reproducing a published DLJ figure therefore means matching its convention; the default is unchanged from earlier pybvh releases.
Source: Hogan & Sternad 2009; Balasubramanian et al. (the
"peak_speed" form). Validated against the reference output.
log_dimensionless_jerk(speed: npt.NDArray[np.float64], fs: float, normalize: str = 'peak_speed', amplitude: float | npt.NDArray[np.float64] | None = None) -> float | npt.NDArray[np.float64]
¶
Log dimensionless jerk (LDLJ) — -ln|DLJ|.
The log transform of :func:dimensionless_jerk, the form most used in
practice. More negative is less smooth.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
speed
|
(ndarray, shape(T) or (T, K))
|
Speed profile; a 2-D input is |
required |
fs
|
float
|
Sampling rate in Hz. |
required |
normalize
|
('peak_speed', 'mean_speed', 'amplitude')
|
Normalizer forwarded to :func: |
"peak_speed"
|
amplitude
|
float or ndarray
|
Movement extent forwarded to :func: |
None
|
Returns:
| Type | Description |
|---|---|
float or ndarray
|
|
Notes
Source: Balasubramanian et al. Validated against the reference output.
number_of_peaks(speed: npt.NDArray[np.float64], min_height: float | None = None) -> int | npt.NDArray[np.int_]
¶
Number of local maxima in a speed profile.
A simple smoothness proxy — a single smooth movement has one velocity peak; more peaks mean more sub-movements.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
speed
|
(ndarray, shape(T) or (T, K))
|
Speed profile; a 2-D input is |
required |
min_height
|
float or None
|
Minimum height a maximum must reach to be counted, in the same
units as |
None
|
Returns:
| Type | Description |
|---|---|
int or ndarray
|
Count of qualifying strict interior local maxima — a scalar for
|
Notes
Strictness. A sample counts when it is strictly greater than both neighbours. The alternative, allowing ties, would count every sample of a flat-topped peak separately, which is worse; the cost of strictness is that an exactly flat maximum — two or more equal adjacent samples — counts as zero peaks rather than one. Exact ties are rare in float data but reachable after quantization or box-filter smoothing.
Sign. The comparison is on the values as given, not their
magnitude, so for a signed velocity this counts maxima of the signed
signal — velocity peaks in one direction — and a trough at -5
beside neighbours at -6 is a maximum. That is the right reading
for a scalar velocity and a no-op for a speed profile; use
min_height if you want only the positive-going peaks.
Height threshold. With no threshold, every micro-fluctuation is a
"sub-movement", so on noisy data the count tracks the noise rather
than the movement — Hogan & Sternad 2009 warn about exactly this
(peak counting is "prone to spurious peaks", and separately blind to
arrests). The default is unthresholded because that is what the
metric means in its source literature, not because it is the better
choice for real data; set min_height when the profile is noisy.
It is absolute rather than a fraction of the peak so it composes with
whatever normalization you have already applied — for a relative
threshold, pass min_height=0.05 * speed.max().
Source: Balasubramanian et al. (number-of-peaks metric); Hogan &
Sternad 2009 (its noise sensitivity). Note the pinned SPARC reference
implementation ships no peak-counting function, so unlike
:func:sparc and :func:dimensionless_jerk this metric has no
golden-reference test — only the properties asserted in
tests/test_analysis_primitives.py.
speed_metric(speed: npt.NDArray[np.float64]) -> float | npt.NDArray[np.float64]
¶
Mean-to-peak speed ratio — mean|v| / max|v|, in [0, 1].
A bell-shaped (smooth) speed profile has a low ratio; a flat plateau approaches 1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
speed
|
(ndarray, shape(T) or (T, K))
|
Speed profile, or a signed scalar velocity; a 2-D input is |
required |
Returns:
| Type | Description |
|---|---|
float or ndarray
|
The mean/peak ratio — a scalar for |
Notes
Both reductions take the magnitude. For a non-negative speed profile
that is simply mean(v) / max(v); for a signed velocity it is what
keeps the documented [0, 1] range true, since a raw mean cancels
toward zero on an out-and-back movement and would yield a ratio at or
below zero against a positive peak.
The same magnitude convention is used by
:func:dimensionless_jerk's "mean_speed" normalizer, which makes
this the exact conversion factor between its two distinct
normalizers: dimensionless_jerk(v, fs, "mean_speed") ==
dimensionless_jerk(v, fs) / speed_metric(v)**2.
Source: Balasubramanian et al. (speed-metric); Flash & Hogan.
integrated_squared_jerk(speed: npt.NDArray[np.float64], fs: float) -> float | npt.NDArray[np.float64]
¶
Integrated squared jerk — ∫ (d²v/dt²)² dt (dimensional).
Accepts (T,) (scalar out) or (T, K) ((K,) out, reduced
per column).
mean_squared_jerk(speed: npt.NDArray[np.float64], fs: float) -> float | npt.NDArray[np.float64]
¶
Mean squared jerk — mean((d²v/dt²)²).
Accepts (T,) (scalar out) or (T, K) ((K,) out, reduced
per column).
rms_squared_jerk(speed: npt.NDArray[np.float64], fs: float) -> float | npt.NDArray[np.float64]
¶
Root-mean-square jerk — sqrt(mean((d²v/dt²)²)).
Accepts (T,) (scalar out) or (T, K) ((K,) out, reduced
per column).
smoothness(speed: npt.NDArray[np.float64], fs: float, metric: str = 'sparc', **kwargs: Any) -> float | npt.NDArray[np.float64] | npt.NDArray[np.int_]
¶
Dispatch to a named smoothness metric on a speed profile.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
speed
|
(ndarray, shape(T) or (T, K))
|
Speed profile; a 2-D input is |
required |
fs
|
float
|
Sampling rate in Hz. |
required |
metric
|
str
|
One of |
'sparc'
|
**kwargs
|
Any
|
Metric-specific options: |
{}
|
Returns:
| Type | Description |
|---|---|
(float, int or ndarray)
|
The selected smoothness value — a scalar for |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Signal reductions¶
Scalar summaries of a speed or activity signal.
VelocityReductions = namedtuple('VelocityReductions', ['peak', 'mean', 'peak_to_mean', 'peak_acceleration', 'peak_deceleration'])
module-attribute
¶
velocity_reductions(speed: npt.NDArray[np.float64], fs: float) -> VelocityReductions
¶
Scalar reductions of a speed profile.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
speed
|
(ndarray, shape(T) or (T, K))
|
Speed profile; a 2-D input is |
required |
fs
|
float
|
Sampling rate in Hz; scales |
required |
Returns:
| Type | Description |
|---|---|
VelocityReductions
|
Named tuple |
Notes
All fields reduce the values as given — none takes a magnitude
first. For a genuine (non-negative) speed profile that is the only
reading; for a signed scalar velocity it means peak is the
signed maximum (not the excursion max|v|) and peak_to_mean
is unbounded (a raw mean cancels toward zero on an out-and-back
movement, going nan at exactly zero). This differs from
:func:speed_metric, whose documented [0, 1] range forces the
magnitude convention mean|v| / max|v| — so for signed input
peak_to_mean is not 1 / speed_metric. Take np.abs
first if you want magnitude reductions of a signed velocity.
peak_acceleration and peak_deceleration are the positive and
negative extrema (clamped at 0) of the per-frame speed-derivative
series d‖v‖/dt: when speed is the norm of
:func:node_velocities with stencil="forward", pad="none",
they equal the extrema of :func:node_speed_derivative under the
same convention (asserted in the test suite so the two can't drift).
Source: Pollick et al., Halovic & Kroos, Samadani et al.
zero_crossings(signal: npt.NDArray[np.float64], axis: int = 0) -> npt.NDArray[np.int_]
¶
Count sign changes of a signal along an axis.
Strict crossings only — consecutive samples with a product < 0;
exact zeros are not counted as crossings. The consequence: a sign
change that passes through an exact zero sample (+1, 0, -1)
counts zero crossings, not one. The alternative convention —
sign-change counting, np.diff(np.sign(x)) != 0 — counts it
(twice, unless zeros are carried forward). Exact zeros are rare in
float data but reachable after quantization, rectification, or
box-filter smoothing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signal
|
ndarray
|
Input signal. |
required |
axis
|
int
|
Axis along which to count (default 0). |
0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Crossing counts with |
Notes
Source: Zhao & Badler (motion feature counts).
active_segments(speed: npt.NDArray[np.float64], threshold: float) -> npt.NDArray[np.bool_]
¶
Boolean mask of "active" (above-threshold) samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
speed
|
ndarray
|
Speed (or any non-negative activity) signal. |
required |
threshold
|
float
|
Activity threshold; samples strictly above it are active. No hidden default — the caller picks the threshold, keeping this a theory-neutral primitive. |
required |
Returns:
| Type | Description |
|---|---|
ndarray of bool
|
|
Notes
Source: Pollick et al., Bernhardt & Robinson.
active_duration(speed: npt.NDArray[np.float64], threshold: float, fs: float) -> float | npt.NDArray[np.float64]
¶
Total time spent active — active sample count / fs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
speed
|
(ndarray, shape(T) or (T, K))
|
Speed signal; a 2-D input is |
required |
threshold
|
float
|
Activity threshold (see :func: |
required |
fs
|
float
|
Sampling rate in Hz. Required — the time base must be stated explicitly, matching the other array-pure kernels. |
required |
Returns:
| Type | Description |
|---|---|
float or ndarray
|
Active duration in seconds — a scalar for |
Energy, gait & range of motion¶
Kinetic energy and the spatiotemporal gait parameters. gait_parameters computes all of the gait parameters in one pass.
kinetic_energy(bvh: Bvh, masses: npt.NDArray[np.float64] | Mapping[str, float] | None = None, centered: str = 'world', stencil: str = 'central', pad: str = 'edge') -> npt.NDArray[np.float64]
¶
Per-frame kinetic energy summed over joints.
With masses, Σ_j ½ m_j ‖v_j‖² (true kinetic energy). Without,
Σ_j ‖v_j‖² (unit-mass energy proxy) — pybvh ships no segment-mass
model, so pass anatomical masses for physical energy. This is a
point-mass-at-joints model; rigid-body energy (segment-CoM masses,
rotational inertia) is not supported.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bvh
|
Bvh
|
Input motion. |
required |
masses
|
ndarray of shape (J,), or mapping {joint_name: mass}
|
Per-joint masses (end sites excluded). A mapping keyed by joint name
is validated for exact coverage and is the safer form — an array
relies on matching |
None
|
centered
|
str
|
Centering mode for the velocities (default |
'world'
|
stencil
|
optional
|
Velocity finite-difference convention (see
:func: |
'central'
|
pad
|
optional
|
Velocity finite-difference convention (see
:func: |
'central'
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Per-frame energy; leading length follows the velocity
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a |
Notes
Source: Głowinski et al., Piana et al., Lu et al. 2025.
cadence(bvh: Bvh, feet: Sequence[NodeSelector] | None = None, *, contacts: npt.NDArray[np.float64] | None = None) -> float
¶
Step rate — foot-contact onsets per second.
A projection of :func:gait_parameters (the single definition of
every gait scalar).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bvh
|
Bvh
|
Input motion. |
required |
feet
|
sequence of str or BvhNode, or None
|
The feet, each a node name or one of |
None
|
contacts
|
(ndarray, shape(F, n_feet))
|
Pre-computed contact labels (see :func: |
None
|
Returns:
| Type | Description |
|---|---|
float
|
Steps per second ( |
Raises:
| Type | Description |
|---|---|
ValueError
|
Where :func: |
TypeError
|
Where :func: |
Notes
Unit. Steps per second, consistent with every other rate in pybvh (Hz, units/s). The clinical gait literature — including the sources below — reports cadence in steps per minute; multiply by 60 to compare against published figures. Onsets are pooled over all contact columns, so passing more than two contact-bearing joints per foot inflates the count proportionally.
Source: Crane & Gross, Gross et al. 2012, Karg et al. 2010.
stride_length(bvh: Bvh, feet: Sequence[NodeSelector] | None = None, *, contacts: npt.NDArray[np.float64] | None = None) -> float
¶
Mean stride length — distance between successive same-foot landings.
The standard, foot-measured stride: for each foot, the horizontal
distance between its position at consecutive contact onsets, pooled
over feet and averaged. A projection of :func:gait_parameters —
see that for the full spatiotemporal set (variability, step length,
stance, double-support, asymmetry) computed in one pass.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bvh
|
Bvh
|
Input motion. |
required |
feet
|
sequence of str or BvhNode, or None
|
The feet, each a node name or one of |
None
|
contacts
|
(ndarray, shape(F, n_feet))
|
Pre-computed contact labels (see :func: |
None
|
Returns:
| Type | Description |
|---|---|
float
|
Mean stride length in skeleton units ( |
Raises:
| Type | Description |
|---|---|
ValueError
|
Where :func: |
TypeError
|
Where :func: |
Notes
Source: Crane & Gross, Gross et al. 2012, Karg et al. 2010.
walking_pace(bvh: Bvh) -> float
¶
Mean horizontal speed — the body anchor's ground-path length per second.
Same definition as the walking_pace field of
:func:gait_parameters, but computed directly from the path of
:attr:~pybvh.bvh.Bvh.body_anchor (the root's, on a clip whose
anchor is its root) so
it needs no feet or contact detection. Note it only
approximates stride_length × cadence / 2 (exact for straight,
steady, symmetric gait; it diverges on curved or irregular walking
because the anchor's path and the foot landings measure different
things). On a root that stays in place with the body below it (a
static root, or a reference node whose channels do not change), the
pace is still the body's, read from the body anchor, not the root.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bvh
|
Bvh
|
Input motion. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Horizontal units per second ( |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the clip's |
Notes
Source: Crane & Gross, Gross et al. 2012.
GaitParameters = namedtuple('GaitParameters', ['cadence', 'walking_pace', 'stride_length', 'stride_cv', 'step_length', 'stance_fraction', 'double_support_fraction', 'asymmetry'])
module-attribute
¶
gait_parameters(bvh: Bvh, feet: Sequence[NodeSelector] | None = None, *, contacts: npt.NDArray[np.float64] | None = None) -> GaitParameters
¶
Spatiotemporal gait parameters in one pass.
Bundles the foot-measured gait analysis: cadence (onsets/s),
walking_pace (body anchor ground speed), stride_length and its
coefficient of variation stride_cv (landing→next-same-foot-landing),
step_length (forward advance between successive any-foot landings,
measured along the direction of travel so step width is excluded),
stance_fraction (mean fraction of a cycle a foot is planted),
double_support_fraction (fraction of frames with ≥2 feet planted), and
asymmetry (left/right stride difference). Underdetermined fields are
nan — uniformly, across all eight (e.g. asymmetry without one
identifiable left and right foot, stride_length if no foot completes
two contacts, step_length if there is no net travel, cadence and
walking_pace on a zero-duration clip).
These are kinematic — computed from foot positions and contact timing alone. Dynamic gait analysis (joint torques, ground-reaction force, mechanical work) needs a physical model and is out of scope.
Conventions worth naming, since published gait figures differ on all three:
stride_cvpools each foot's deviations from that same foot's mean before taking the standard deviation, then divides by the overall mean stride. The plainer alternative — the CV of the pooled stride sample — folds left/right asymmetry into "variability"; here the two are separate fields, and they diverge exactly in proportion toasymmetry.asymmetryis|mean_L − mean_R| / (½(mean_L + mean_R)): unsigned and unitless. Robinson's Symmetry Index, standard in the gait literature, is the same ratio kept signed and ×100 — multiply by 100 for SI magnitude; the direction of the asymmetry is not recoverable from this field.step_lengthprojects onto a single whole-clip progression chord (the body anchor's first→last horizontal displacement), not a per-step heading. On a curved walk this systematically shortens the value, and a closed loop has no net travel and returnsnan.stride_lengthby contrast is the full Euclidean distance between same-foot landings, so it includes lateral step width whilestep_lengthexcludes it — the two are not the 2:1 pair a clinical report would use on curved or wide-stance gait.walking_paceand the progression chord ofstep_lengthread the body anchor (:attr:~pybvh.bvh.Bvh.body_anchor), which is the root on a clip whose anchor is its root. On a root that stays in place with the body below it (a static root, or a reference node whose channels do not change), they describe the body, read from the body anchor, not the root. The foot-measured fields do not read the anchor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bvh
|
Bvh
|
Input motion. |
required |
feet
|
sequence of str or BvhNode, or None
|
The feet, each a node name or one of |
None
|
contacts
|
(ndarray, shape(F, n_feet))
|
Pre-computed contact labels (column order matching |
None
|
Returns:
| Type | Description |
|---|---|
GaitParameters
|
Named tuple of the eight parameters above. |
Raises:
| Type | Description |
|---|---|
ValueError
|
Where :func: |
TypeError
|
Where :func: |
Notes
Source: Crane & Gross, Gross et al. 2012, Karg et al. 2010.
range_of_motion(signal: npt.NDArray[np.float64], axis: int = 0) -> npt.NDArray[np.float64]
¶
Peak-to-peak range of a signal — max − min along an axis.
For a joint-angle channel this is its range of motion over the clip.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signal
|
ndarray
|
Input signal (e.g. a joint-angle time series). |
required |
axis
|
int
|
Axis to reduce over (default 0, the frame axis). |
0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The peak-to-peak range with |
Notes
Source: gait / biomechanics range-of-motion descriptors.
Scale & covariance descriptors¶
Skeleton-size normalization and fixed-size sequence statistics.
skeleton_size(bvh: Bvh, feet: Sequence[NodeSelector] | None = None) -> float
¶
Absolute skeleton scale — mean rest-pose distance from the feet to the joint they branch from.
That joint is the lowest one that has the feet in two or more of its
branches: the hips of a biped, where the hind and the front chains
part on a quadruped. For one foot, or feet along one leg, it is
:attr:~pybvh.Bvh.body_anchor. So a root above or beside the body
leaves the size alone, and on a rig whose anchor is its chest the
size is still measured from the hips.
A size proxy that scales linearly with the whole skeleton (≈ half the
standing height for a humanoid). Only the leg chain contributes, so
finger/spine subdivision does not affect it. This is the public name for
the scale foot_contacts uses internally to set its thresholds; use it
for size normalization. For the relative scale between two skeletons,
see :func:relative_scale_factor.
A skeleton whose size cannot be measured — auto-detection finds no
feet, or every foot sits exactly on that joint — raises rather than
returning a substitute: any fabricated number (1.0 reads as a
plausible metre-scale humanoid, nan poisons everything scaled by
it) would be indistinguishable from, or worse than, a measurement.
Catch the error and choose your own scale if a total function is
needed. (The contact detectors' skeleton scale uses 1.0 in its
place on such a rig, since a threshold must exist even where a
measurement does not, and their :class:~pybvh.ContactReport says
so: skeleton_scale_measured is False.)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bvh
|
Bvh
|
Input skeleton. |
required |
feet
|
sequence of str or BvhNode, or None
|
The feet, each a node name or one of |
None
|
Returns:
| Type | Description |
|---|---|
float
|
Mean rest-pose distance from the joint the feet branch from to
the feet
(always |
Raises:
| Type | Description |
|---|---|
ValueError
|
Where :func: |
TypeError
|
Where :func: |
Notes
Source: gait/biomech normalization (Troje, Karg et al.).
relative_scale_factor(reference: npt.NDArray[np.float64], target: npt.NDArray[np.float64], *, centered: bool = False) -> float
¶
Least-squares uniform scale matching target to reference.
The scalar s minimizing ‖reference − s·target‖² over all
coordinates — i.e. s = ⟨reference, target⟩ / ⟨target, target⟩ (Troje-
style size normalization between two skeletons or poses). Both arrays must
share shape (e.g. two (N, 3) rest poses, or (F, N, 3) sequences).
This is the relative scale between skeletons; for a single skeleton's
absolute size, see :func:skeleton_size.
By default the fit is taken about the coordinate origin — neither
array is mean-centered first. The Procrustes/Umeyama convention
centers both point sets on their centroids before fitting scale; the
two agree only when the poses are already centered, and diverge in
proportion to the centroid offset. That makes the origin form right
for rest poses (root at the origin) and wrong for world-frame
sequences with a translated root — pass centered=True for those.
Note centered=True is the scale-only Procrustes fit: no
rotation is estimated, so it is not the full Umeyama similarity
estimate, whose scale differs once a rotation is jointly fitted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reference
|
ndarray
|
The pose/sequence to match. |
required |
target
|
ndarray
|
The pose/sequence being scaled. Same shape as |
required |
centered
|
(bool, keyword - only)
|
If True, subtract each array's centroid — the mean over every axis except the last (i.e. over all points, and all frames for a sequence) — before fitting. Default False (fit about the origin). |
False
|
Returns:
| Type | Description |
|---|---|
float
|
The optimal scale |
Notes
Source: Troje 2002 (pose normalization); Umeyama 1991 for the centered convention.
cov3dj(pos: npt.NDArray[np.float64]) -> npt.NDArray[np.float64]
¶
Covariance of 3D joint positions over time (Cov3DJ).
Flattens each frame's joints to a 3N vector and returns the
(3N, 3N) population covariance across frames (divides by F,
not F − 1) — a fixed-size pose descriptor independent of
sequence length.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pos
|
(ndarray, shape(F, N, 3))
|
Per-frame joint positions. |
required |
Returns:
| Type | Description |
|---|---|
ndarray, shape (3N, 3N)
|
The population covariance matrix. |
Notes
Source: Hussein et al. (Cov3DJ).
lagged_covariance(signal: npt.NDArray[np.float64], lag: int) -> npt.NDArray[np.float64]
¶
Lagged covariance matrix — M(l) = (1/(T−l)) Σ_t (v_{t+l} − v̄)(v_t − v̄)ᵀ.
Captures temporal structure between channels at a fixed lag: the
covariance between the signal and itself lag samples earlier,
averaged over the T − l overlapping sample pairs (so every entry
is a mean, independent of the lag). The signal is centered on its
temporal mean v̄ first — a true covariance, so a constant offset
contributes nothing. lag=0 reduces to the ordinary population
covariance of the channels (cf. :func:cov3dj).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signal
|
(ndarray, shape(T, D))
|
Multichannel signal (time × channels). |
required |
lag
|
int
|
Non-negative lag in samples. |
required |
Returns:
| Type | Description |
|---|---|
(ndarray, shape(D, D))
|
The lagged covariance. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Notes
Source: Venture et al. (lagged covariance descriptors).