Skip to content

pybvh Feature Gallery

One picture per feature, designed so that the figure is the explanation:

  • operations and geometric descriptors are drawn in 3D on the skeleton.
  • dynamic descriptors are annotated on the signals they summarize.
  • SE(3) transforms are drawn as coordinate frames.

Where a real pose would obscure the idea, a small synthetic example is used instead. Sections 1-5 cover the core library (viewing, concepts, transforms, skeleton ops, export). Sections 6-12 cover the motion-descriptor layer introduced in pybvh 0.8.0.

Each cell shows the feature call (bvh.mirror(), bvh.curvature(...), …). Where a figure needs extra annotation, the matplotlib lives in the companion module gallery_plots.py (imported as gp). So the notebook stays about the features, not the plumbing.

API reference for everything shown here: Bvh class · geometry · analysis · rotations & SE(3) · transforms · signal

Sections: 1 load & see · 2 core concepts, drawn · 3 transforms & augmentation · 4 skeleton & frame ops · 5 contacts & feature export · 6 geometry (relations) · 7 geometry (bounding & centre of mass) · 8 geometry (trajectory) · 9 analysis (dynamics & gait) · 10 SE(3) rigid transforms · 11 signal utilities · 12 scale.

If your viewer fails to render any figure or clip, the notebook on nbviewer renders everything.

Generated page

This page is generated from the executed notebook feature_gallery.ipynb — download it to run every figure live. Do not edit docs/gallery/ by hand; regenerate with python scripts/export_gallery.py.

Every figure at a glance — click any tile to jump to it.

%matplotlib inline
from pathlib import Path

import numpy as np

import pybvh
from pybvh import analysis, geometry, rotations, signal

import gallery_plots as gp

REPO = Path.cwd().parent if Path.cwd().name in ("tutorials", "gallery") else Path.cwd()
bvh = pybvh.read_bvh_file(REPO / "bvh_data" / "bvh_test1.bvh")
pos = bvh.node_positions()  # (F, N, 3)
F = bvh.frame_count
dt = bvh.frame_time
t = np.arange(F) * dt
FRAME = F // 2  # a representative pose
P = pos[FRAME]


def idx(name):
    return bvh.index(name, space="node")


print(bvh)
24 joints, 126 frames at 30.0 fps (frame_time=0.033333s, from bvh_test1.bvh)

Where the drawing lives & adjusting the view. A gp.fig_* function in gallery_plots.py builds every figure. To re-aim the 3D camera for all figures, set gp.VIEW_ELEV / gp.VIEW_AZIM. A handful of figures pin their own angle inside their function. For those, edit the angle there. The skeleton/triad/equal-box helpers also live in that module.

1 · Load & see

The test clip used through most of this gallery, rendered with bvh.render to a GIF committed beside this notebook. The clip is resampled to the GIF's 20 fps, so that it plays in real time. The markdown cell below displays the committed file, rather than the cell embedding the clip as an output. It does so because GitHub's notebook renderer shows image/png outputs but silently drops image/gif ones. So an embedded clip would be invisible exactly where most readers meet the library. For an interactive scrubber instead, use bvh.play() in a live kernel.

seq_gif = gp.motion_clip_gif(bvh)  # renders the clip itself — no single feature value to surface

the test clip, rendered by bvh.render with the front camera

plot_rest_pose & plot_frame — the two static snapshots: the rest pose and any animation frame, with camera="front"/"side"/"top" or a custom (azimuth, elevation) tuple. The rest pose has all joint angles zero, and offsets only. It is the first thing to check on a new file. Multi-skeleton comparisons use the same functions from pybvh.bvhplot with a list, as later sections show.

fig, ax = bvh.plot_rest_pose()
ax.set_title("plot_rest_pose() — offsets only, angles zero");

plot_rest_pose

fig, ax = bvh.plot_frame(frame=FRAME, camera="side")
ax.set_title(f"plot_frame({FRAME}, camera='side')");

plot_rest_pose

plot_sequence — the motion-paper still. It shows equidistantly sampled poses in one figure. Lightness encodes time (lighter = earlier). The root's path is dashed on the floor. layout="offset" (default) places poses at their world positions, so locomotion reads left to right. Here it is shown on real walking mocap: CMU subject 12, data from mocap.cs.cmu.edu. Sections 2, 5 and 9 reuse this clip. layout="overlay" superimposes the poses instead, each centred on the body anchor. It is the right mode for in-place motion.

walk = pybvh.read_bvh_file(REPO / "bvh_data" / "cmu_12_01_walk.bvh")
fig, ax = walk.plot_sequence(n_poses=8)
ax.set_title("plot_sequence(n_poses=8) — lighter = earlier");

plot_sequence

Style — every figure above uses the default preset "paper": ground plane, per-chain colors, joint markers, axes off. All bvhplot functions take style=. Its value is either:

  • a preset name: "paper", "debug" (the single-blue-with-full-axes look, for coordinate inspection), or "dark" (for slides and project pages).
  • a Style instance overriding any field, e.g. Style("paper", floor="checker", bone_width=4).
fig, ax = bvh.plot_frame(frame=FRAME, style="dark")
ax.set_title("plot_frame(style='dark')");

Style

The 0.9.0 default, and the look it replaced. Left: style="paper", which every bvhplot function applies unless told otherwise. Right: the same call with style="debug". It reproduces the pre-0.9.0 output pixel-for-pixel. It is the one-line migration for code written against the old default. It is also the style to choose when you need to read coordinates off the axes.

fig, (ax_paper, ax_debug) = gp.side_by_side_3d()
bvh.plot_frame(frame=FRAME, ax=ax_paper)  # style="paper" is the default
bvh.plot_frame(frame=FRAME, style="debug", ax=ax_debug)
ax_paper.set_title("style='paper' (0.9.0 default)")
ax_debug.set_title("style='debug' (pre-0.9.0)");

The 0.9.0 default, and the look it replaced.

plot_frame(backend="vedo") — the same pose as a shadowed 3D capsule render. It is the publication-figure alternative to the matplotlib stick figure. The render is computed fully offscreen (headless-safe). It is returned as an (H, W, 3) uint8 RGB array. render(backend="vedo") exports the same look as video.

capsule_img = bvh.plot_frame(frame=FRAME, backend="vedo")
gp.fig_image(capsule_img, "plot_frame(backend='vedo') — shadowed capsules")
(<Figure size 650x600 with 1 Axes>,
 <Axes: title={'center': "plot_frame(backend='vedo') — shadowed capsules"}>)

plot_frame(backend="vedo")

render(ghost=N, trajectory=True) — motion context inside a clip. ghost=N trails N faded copies of recent poses behind the live skeleton (spaced Style.ghost_spacing seconds apart, nearer ones darker). And trajectory=True draws the root's path on the floor as it goes, so a single frame of the video says where the motion has been. Two seconds of the walk clip, world-centered so that the character travels across the frame:

ghost_gif = gp.ghost_trace_gif(walk[:240])

two seconds of the walk clip rendered with ghost=3 and trajectory=True

render(camera="turntable") — a full 360° orbit over the clip's duration. It is the standard way to show a motion from every side in one clip. Here it runs with centered="anchor", which pins the body anchor so that the orbit is the only motion in frame. Export knobs that no still can show:

  • supersample: 2× anti-aliasing by default on the OpenCV backend.
  • codec="h264", for mp4s that play in a browser.
  • frame_counter=True, to stamp Frame f/F for review.
turntable_gif = gp.turntable_gif(walk)

the walk clip with the camera orbiting a full 360 degrees

2 · Core concepts, drawn

The ideas every pybvh user needs, one figure each. Full prose: the Core Concepts and World Up guides.

node_positions(centered=…) — the three coordinate modes for forward-kinematics output. Shown on the walking clip loaded in section 1. Travel makes the modes unmistakable. Same clip, same frame. The blue trail is the root's path over the whole clip. On this clip the body anchor is the root, the hips, so the trail shows the body anchor.

  • "world" keeps absolute file coordinates.
  • "first_ground" shifts the first frame's body anchor over the origin. The character still travels.
  • "anchor" pins the body anchor at the origin every frame. The trail collapses to a point: pose only, no travel.
gp.fig_centered_modes(walk, walk.frame_count // 2)

node_positions(centered=…)

Why 6D exists — a smooth rotation crossing the ±180° boundary, read out in three representations:

  • Euler snaps from +180° to −180°.
  • The canonical quaternion flips the sign of z where w crosses zero.
  • 6D stays perfectly smooth. That property makes it the default for neural-network outputs.

(The other two Euler pitfalls, gimbal lock and order-dependence, are illustrated in tutorial 3.)

input_angles = np.linspace(170, 190, 41)
euler = np.zeros((41, 3))
euler[:, 0] = input_angles  # Z component in ZYX order
recovered = rotations.rotmat_to_euler(
    rotations.euler_to_rotmat(euler, "ZYX", degrees=True), "ZYX", degrees=True
)
quats = rotations.euler_to_quat(euler, "ZYX", degrees=True)
rot6d = rotations.euler_to_rot6d(euler, "ZYX", degrees=True)
gp.fig_rotation_continuity(input_angles, recovered, quats, rot6d)

Why 6D exists

world_up · forward_at · left_at — the orientation triple:

  • world_up is the gravity axis, auto-detected from the animation.
  • forward_at(frame) is the character's facing direction at a frame, derived from the L/R joint pairs.
  • left_at = world_up × forward completes the right-handed frame.

All three return signed-axis strings like '+z'.

gp.fig_orientation_triad(bvh, FRAME)

figure 11

reorient_world_up — files disagree on which axis is "up" (Y-up vs Z-up exporters). reorient_world_up rotates the whole scene into a chosen convention. The character looks identical. Only the coordinates are rewritten. Here a Y-up file is unified to Z-up.

bvh_yup = pybvh.read_bvh_file(REPO / "bvh_data" / "bvh_test2.bvh")
pybvh.bvhplot.frame(
    [bvh_yup, bvh_yup.reorient_world_up("+z")],
    frame=0,
    labels=[f"original (world_up '{bvh_yup.world_up}')", "reorient_world_up('+z')"],
);

reorient_world_up

reorient_rest_up — some files author the rest pose in one convention but the animation in another. pybvh warns on load. It trusts the animation. reorient_rest_up rewrites the rest pose to match. It compensates every joint rotation, so that the animated joint positions are unchanged to machine precision (printed below). reorient_rest_forward is the same idea for the facing axis.

import warnings

with warnings.catch_warnings():
    warnings.simplefilter(
        "ignore"
    )  # test3's rest/animation mismatch warns on load — that mismatch is the point
    bvh_mixed = pybvh.read_bvh_file(REPO / "bvh_data" / "bvh_test3.bvh")
bvh_fixedrest = bvh_mixed.reorient_rest_up("+z")
print(
    "max joint-position change:",
    np.abs(bvh_mixed.node_positions() - bvh_fixedrest.node_positions()).max(),
)
pybvh.bvhplot.rest_pose(
    [bvh_mixed, bvh_fixedrest],
    labels=["rest pose as authored (up ≠ animation up)", "reorient_rest_up('+z')"],
);
max joint-position change: 2.1316282072803006e-14

reorient_rest_up

3 · Transforms & augmentation

The standard motion augmentations, each drawn as before/after. All exist as Bvh methods and as array-level pybvh.transforms functions. All accept a seeded rng. Each has a random_* variant that samples its parameter. Full prose: the Data Augmentation guide.

mirror — flips the motion left↔right. It is not just an axis negation. The lateral axis is flipped and every Left*/Right* joint pair swaps data (both auto-detected). So the result stays anatomically possible.

pybvh.bvhplot.frame([bvh, bvh.mirror()], frame=FRAME, labels=["original", "mirror()"]);

mirror

rotate_vertical & translate_root — yaw the whole motion about the up axis, and shift it by a constant offset. A yaw about the up axis is the one rotation that preserves ground contact. The top-down root paths show both at once:

  • the rotated path pivots 90° about the origin.
  • the translated one is the same shape displaced.
pybvh.bvhplot.trajectory(
    [bvh, bvh.rotate_vertical(np.pi / 2), bvh.translate_root([50, 0, 0])],
    labels=["original", "rotate_vertical(π/2)", "translate_root(+50 x)"],
);

rotate_vertical

add_rotation_noise — zero-mean Gaussian noise on the joint angles (σ in radians). Calibration on a human skeleton:

  • σ ≈ 0.5° is imperceptible sensor-level noise.
  • σ ≈ 2° is a typical augmentation.
  • σ ≈ 5° is clearly visible.
  • σ > 10° is destructive.
pybvh.bvhplot.frame(
    [
        bvh,
        bvh.add_rotation_noise(sigma=np.radians(0.5), rng=np.random.default_rng(42)),
        bvh.add_rotation_noise(sigma=np.radians(5.0), rng=np.random.default_rng(42)),
    ],
    frame=FRAME,
    labels=["original", "σ = 0.5°", "σ = 5°"],
);

add_rotation_noise

perturb_speed — changes how fast the motion plays, by resampling (SLERP under the hood). The subtlety worth a figure: it changes the frame count, not the frame rate. At factor 2, this 126-frame 30 fps clip becomes 63 frames, still at 30 fps.

gp.fig_perturb_speed(bvh, bvh.perturb_speed(0.5), bvh.perturb_speed(2.0))

perturb_speed

drop_frames — simulates mocap dropouts. A random fraction of frames is replaced (not removed) by values interpolated from the nearest kept neighbours. The interpolation is linear for the root, and SLERP for rotations. The frame count out is the same. The red dots mark the re-synthesized frames, visibly flattened where fine motion was lost.

gp.fig_drop_frames(bvh, bvh.drop_frames(drop_rate=0.5, rng=np.random.default_rng(0)))

drop_frames

Composing transforms — every transform returns a new Bvh, so augmentation pipelines chain:

augmented = (
    bvh.mirror()
    .rotate_vertical(np.pi / 4)
    .add_rotation_noise(sigma=0.02, rng=np.random.default_rng(42))
    .perturb_speed(1.1)
)
pybvh.bvhplot.frame(
    [bvh, augmented],
    frame=45,
    labels=["original", "mirror → yaw 45° → noise → 1.1× speed"],
    camera=(120, 20),
);

Composing transforms

4 · Skeleton & frame ops

Editing the skeleton and the timeline. Full prose: the Skeleton Operations guide.

scale, retarget & extract_joints:

  • scale resizes the skeleton. Rotations stay untouched.
  • retarget copies another skeleton's bone proportions, and it keeps the motion. This is the dataset-normalization move.
  • extract_joints keeps a subset of joints. The offsets of removed joints collapse into the nearest kept descendant.

Left to right on one shared scale: original, scaled 0.5×, a 1.5×-tall clip retargeted back to the original proportions (so it matches the original's size again), and an 11-joint subset.

tall = bvh.scale(1.5)
major = [
    "Hips",
    "Spine3",
    "Head",
    "RightArm",
    "RightHand",
    "LeftArm",
    "LeftHand",
    "RightUpLeg",
    "RightFoot",
    "LeftUpLeg",
    "LeftFoot",
]
gp.fig_skeleton_ops(
    [bvh, bvh.scale(0.5), tall.retarget(bvh), bvh.extract_joints(major)],
    ["original", "scale(0.5)", "tall.retarget(bvh)", "extract_joints\n(11 of 24)"],
    FRAME,
)

scale

resample — change the frame rate. The new samples are SLERP-interpolated onto the same motion. (Slicing bvh[10:50] and concatenation bvh_a + bvh_b complete the timeline operations. They need no figure.)

gp.fig_resample(bvh, bvh.resample(10))

resample

5 · Contacts & feature export

From motion to ML-ready labels and arrays. Contact detection needs locomotion to be interesting. So this section runs on the walking clip loaded in section 1. First comes the clip itself, rendered from a fixed side camera so that the skeleton walks through world space. The gait descriptors in section 9 reuse it too.

walk_gif = gp.walk_clip_gif(walk)

the walking clip, rendered by bvh.render with a fixed side camera

foot_contacts — binary planted/swing labels per foot per frame. The default detector thresholds two signals and ANDs them (the HuMoR heuristic):

  • foot speed (slow enough?).
  • clearance above the estimated floor (low enough?).

Each signal catches the other's failure mode. Here the call uses adaptive=True, the right setting for known locomotion. That setting splits each foot's speed threshold from its own speed. The height threshold is calibrated, as by default, to each foot's own level over the frames that the speed threshold calls slow. The green spans are the detected stance phases.

feet = [foot.name for foot in analysis.auto_detect_feet(walk)]
gp.fig_foot_contacts_signals(walk, feet)

foot_contacts

root_trajectory — the body anchor's ground-plane position plus its heading as a (sin, cos) pair. It is the standard root parameterization in motion-generation pipelines. bvhplot.trajectory(..., facing_arrows=True) draws the heading along the path.

traj_feats = walk.root_trajectory()  # (F, 4): ground a/b + heading sin/cos
pybvh.bvhplot.trajectory(walk, facing_arrows=True);

root_trajectory

to_feature_array — composes root position, joint rotations (any representation), velocities, and foot contacts into one flat (F, D) array. feature_array_layout reports each block's column slice, so that downstream code never counts columns. The diagram shows the layout of the exact call below.

feat = bvh.to_feature_array(
    representation="6d", include_velocities=True, include_foot_contacts=True
)
layout = bvh.feature_array_layout(
    num_feet=2, representation="6d", include_velocities=True, include_foot_contacts=True
)
gp.fig_feature_layout(layout, feat.shape)

to_feature_array


Everything below is the quantitative motion-descriptor layer added in pybvh 0.8.0: geometry, dynamics, gait, SE(3), and signal utilities. Each is drawn so that the picture explains the number. Prose overview: the Motion Descriptors guide.

6 · Geometry — relations between points

These measure relationships among joint positions. Each is drawn on a single pose with the measured quantity labelled.

inter_joint_distance — the straight-line distance between two joints. The dashed line is the measured segment. Its length is printed on it.

d = bvh.inter_joint_distance([("RightHand", "LeftHand")])[FRAME, 0]
gp.fig_inter_joint_distance(
    bvh, FRAME, "RightHand", "LeftHand", d, "inter_joint_distance: ‖RightHand − LeftHand‖"
)

inter_joint_distance

joint_angle — the angle at a vertex joint between its two neighbours. The two red bones meet at the elbow. The orange arc and label show the angle. (The figure is drawn at the most-bent-elbow frame, so that the angle is unmistakable.)

elbow = bvh.joint_angle("RightArm", "RightForeArm", "RightHand", degrees=True)
fa = int(np.argmin(elbow))  # most-bent elbow frame
gp.fig_joint_angle(
    bvh,
    fa,
    "RightArm",
    "RightForeArm",
    "RightHand",
    elbow[fa],
    "joint_angle: shoulder–elbow–wrist (the elbow angle)",
)

joint_angle

segment_axis_angle — the angle of a bone relative to a reference axis (here the world up). The blue arrow is "up". The red bone is the segment. The arc is the angle between them.

saa = bvh.segment_axis_angle("RightForeArm", "RightHand", degrees=True)[FRAME]
gp.fig_segment_axis_angle(
    bvh, FRAME, "RightForeArm", "RightHand", saa, "segment_axis_angle: forearm vs world-up"
)

segment_axis_angle

triangle_area — the area of the triangle spanned by three joints (a coarse "openness" measure). The shaded triangle is the measured region.

area = bvh.triangle_area("Head", "RightHand", "LeftHand")[FRAME]
gp.fig_triangle_area(
    bvh, FRAME, "Head", "RightHand", "LeftHand", area, "triangle_area: Head · RightHand · LeftHand"
)

triangle_area

point_to_plane_distance & point_to_segment_distance — signed distance from a point to an infinite plane, and shortest distance to a finite segment (clamped to the endpoints). Shown on a clean synthetic setup so the perpendicular drop is unmistakable.

gp.fig_point_to_plane_segment_synthetic()  # didactic illustration on synthetic points (no bvh feature)

point_to_plane_distance

On the skeleton. The same two distances become useful motion features:

  • point_to_plane_distance to the ground gives a foot's clearance: how high it is lifted off the floor.
  • point_to_segment_distance to a body axis gives how far a hand reaches from the torso.

Both are drawn on the same pose: the frame where the toe is most lifted. The red perpendicular is the measured distance.

floor = pos[:, :, 2].min()
kf = int(np.argmax(pos[:, idx("RightToeBase"), 2]))  # most-lifted-toe frame
clearance = geometry.point_to_plane_distance(
    pos[kf, idx("RightToeBase")], np.array([0, 0, floor]), gp.UP
)
reach = geometry.point_to_segment_distance(
    pos[kf, idx("RightHand")], pos[kf, idx("Hips")], pos[kf, idx("Neck")]
)
gp.fig_point_to_plane_segment_skeleton(bvh, kf, clearance, reach)

On the skeleton.

7 · Geometry — bounding volumes & centre of mass

Whole-pose descriptors, drawn as the actual bounding shape around the skeleton.

bounding_box (axis-aligned), bounding_sphere (Ritter, approximate), bounding_ellipsoid (PCA-aligned) — three ways to enclose the pose. Each wireframe encloses every joint. The ellipsoid tilts with the body's spread.

box, sph = bvh.bounding_box(), bvh.bounding_sphere()
ell = geometry.bounding_ellipsoid(P)
gp.fig_bounding_volumes(bvh, FRAME, box, sph, ell)

bounding_box

center_of_mass (uniform centroid) and com_displacement — the black dot is the per-frame CoM. The dashed line shows how far it has travelled from the start CoM (frame 0, the default reference). The CoM trail over the whole clip is faint blue.

com = bvh.center_of_mass()
disp = bvh.com_displacement()
gp.fig_com(bvh, com, disp, frame=50)

center_of_mass

verticality — vertical extent ÷ horizontal extent. The green bar is the height span (along up). The orange bar is the horizontal width. Their ratio is the verticality (> 1 = tall/upright).

gp.fig_verticality(bvh, FRAME, bvh.verticality()[FRAME])

verticality

8 · Geometry — trajectory descriptors

These read a single joint's path over the whole clip. We use the right hand.

JT = "RightHand"
traj = pos[:, idx(JT), :]

First, to make the static trajectory plots below intuitive, watch the hand trace its path. The skeleton animates while the blue trail grows behind the hand, frame by frame. The finished blue curve is the hand trajectory that every descriptor in this section reads as traj. The GIF is resampled to 20 fps, so that it plays in real time.

gif_path = gp.trajectory_trace_gif(bvh, JT)

the right hand tracing its trajectory, frame by frame

path_length vs directness — the blue curve is the actual path (its arc length = path_length). The dashed chord is the straight start→end distance. directness = chord ÷ path (1 = perfectly straight).

gp.fig_path_directness(
    traj, bvh.path_length(JT), bvh.directness(JT), f"path_length & directness ({JT})"
)

path_length

curvature — how sharply the path bends (κ = 1 ÷ the radius of the circle that best hugs the path at each point). The figure colours the trajectory: bright = tight turn, dark = nearly straight.

kappa = bvh.curvature(JT)
gp.fig_curvature(traj, kappa, f"curvature along {JT} path")

curvature

torsion — how a path twists out of its plane (0 for any flat curve). It is a third-derivative quantity, so on real mocap it is swamped by finite-difference noise and spikes wherever the path is momentarily straight (its denominator → 0). To see what it actually measures, we use a clean synthetic curve: a flat circle that lifts into a helix. Torsion is ~0 on the flat part, and it rises where the curve leaves the plane.

s = np.linspace(0, 6 * np.pi, 600)
climb_rate = 0.4 * (1 + np.tanh(s - 3 * np.pi)) / 2  # vertical speed: smoothly 0 → 0.4
z = np.cumsum(climb_rate) * (s[1] - s[0])  # integrate it: flat, then climbs
helix = np.stack([np.cos(s), np.sin(s), z], axis=1)  # smooth join → no torsion spike
tor = geometry.torsion(helix)
gp.fig_torsion(helix, tor, "torsion: flat circle → rising helix")

torsion

Note — the ratio torsion / curvature - or τ/κ (Lancret invariant). Curvature and torsion are the complete pair of Frenet invariants. Together they fix a 3D curve up to a rigid motion. Their ratio has a clean meaning: τ/κ is constant iff the curve is a generalized helix, and that constant is the helix's pitch. On the curve above, it is ~0 along the flat circle and ≈0.40 (the climb rate) on the helix. It is a one-liner from the two primitives: geometry.torsion(traj) / geometry.curvature(traj). It is left at that, because as a feature it inherits torsion's noise and adds a second blow-up where κ→0. So it stays a documented composition rather than a library call.

movement_phase — speed·curvature, so it peaks where the joint moves both fast and sharply. Shown along the real hand path. Bright marks the moments that combine high speed with a tight turn.

mp = geometry.movement_phase(traj, dt)
gp.fig_movement_phase(bvh, JT, mp)

movement_phase

ground_path — the joint's path projected onto the ground plane (its shadow). distance is the length of that shadow. area is the region it encloses (shoelace). The figure shows the 3D path, its shadow, and the filled area.

gp.fig_ground_path(bvh, JT, bvh.ground_path(JT))

ground_path

pose_distance — the Euclidean distance between two whole poses. Computed between every pair of frames, it gives a self-similarity matrix. With this colormap, bright = similar and dark = dissimilar. The diagonal is brightest: every pose matches itself. Recurring motifs appear as off-diagonal bright streaks.

D = geometry.pose_distance(pos[:, None], pos[None, :])  # (F, F) self-similarity
gp.fig_pose_distance(D)

pose_distance

mean_pose_subtract — removes the average pose. It returns a per-frame, per-joint deviation from it (shape (F, N, 3)): the motion about the mean. The figure shows the mean pose (grey skeleton, what gets subtracted) and a single frame's slice of that deviation field (red arrows).

resid = geometry.mean_pose_subtract(pos)  # motion about the mean pose
gp.fig_mean_pose_subtract(bvh, FRAME, resid)

mean_pose_subtract

9 · Analysis — dynamics

Velocity-derived descriptors. Most are best read on the signal itself, with the quantity they compute annotated directly. The right-hand speed profile and sampling rate are reused below.

The traced right-hand clip from section 8 once more. It is the signal that these descriptors summarize:

the right hand tracing its trajectory, frame by frame

speed = np.linalg.norm(bvh.node_velocities()[:, idx(JT)], axis=-1)
fs = 1.0 / dt

node_jerk / joint_jerk — the third derivative of position (rate of change of acceleration). Large jerk = abrupt, unsmooth motion. Shown as the hand's speed, acceleration, and jerk magnitude stacked by frame. Note that the acceleration here is the full acceleration-vector magnitude. So it also spikes on sharp turns (direction changes), not only on speed changes.

acc = np.linalg.norm(bvh.node_accelerations()[:, idx(JT)], axis=-1)
jerk = np.linalg.norm(bvh.node_jerk()[:, idx(JT)], axis=-1)
gp.fig_jerk_ladder(
    np.arange(F), speed, acc, jerk, f"{JT}: the velocity → acceleration → jerk ladder"
)

figure 44

smoothness(metric=…) scores a speed profile. Each metric has its own scale and direction. The next cell states them. SPARC (more negative = less smooth) is the one with a clean geometric picture. So we use it to build intuition here. The others have no natural 2D drawing. They are compared as numbers below. (Synthetic on purpose: smoothness is a contrast metric, so we show a known smooth vs jerky pair.) Left: the two speed profiles. The jerky one's wiggle count is what number_of_peaks reports. Right: their normalized spectra. SPARC is the arc length of this curve. The smooth motion's energy sits entirely at low frequency (a short arc). The jerky tremor adds a bump at 7 Hz that lengthens the arc. That extra length is its lower SPARC.

# -- synthetic data creation --
FS = 200.0  # sampling rate of the synthetic signal
tt = np.arange(200) / FS  # one second of samples at FS
smooth = tt**2 * (1 - tt) ** 2
smooth /= smooth.max()
jerky = smooth + 0.12 * np.sin(2 * np.pi * 7 * tt)  # a superimposed 7 Hz tremor adds jerk
# -- data analysis --
sparc = [analysis.smoothness(p, FS, metric="sparc") for p in (smooth, jerky)]
gp.fig_smoothness_profiles(smooth, jerky, sparc, FS)

smoothness(metric=…)

The full smoothness family — every metric scored on the same smooth vs jerky pair through the smoothness(metric=…) dispatcher. The call is now shown in the cell. The jerk-based metrics all rate the tremulous motion as less smooth: more negative for SPARC / DLJ / LDLJ, larger for the squared-jerk metrics and the peak count. speed_metric captures a different notion (mean-to-peak ratio), so it need not move the same way.

metrics = [
    "sparc",
    "dimensionless_jerk",
    "log_dimensionless_jerk",
    "number_of_peaks",
    "speed_metric",
    "integrated_squared_jerk",
    "mean_squared_jerk",
    "rms_squared_jerk",
]
scores = {m: [analysis.smoothness(p, FS, metric=m) for p in (smooth, jerky)] for m in metrics}
gp.fig_smoothness_bars(scores)

figure 46

velocity_reductions — scalar summaries of a speed profile: peak, mean, their ratio peak_to_mean, peak_acceleration (the steepest speed-up) and peak_deceleration (the steepest slowing). All shown on the hand's speed.

vr = analysis.velocity_reductions(speed, fs=fs)
gp.fig_velocity_reductions(t, speed, vr, fs, f"velocity_reductions ({JT})")

velocity_reductions

zero_crossings & active_segments / active_duration — left: where a (centred) signal changes sign, with the count. Right: a speed profile with a threshold, the active (moving) spans shaded and their total duration.

zc = analysis.zero_crossings(speed - speed.mean())
active = analysis.active_duration(speed, speed.mean(), fs)
gp.fig_zero_crossings_active(t, speed, zc, active)

zero_crossings

kinetic_energy — per-frame Σ‖vⱼ‖² over all joints (unit-mass). Left: the energy curve. Right: a pose with each joint coloured by its instantaneous speed (red or black = fast). That pose shows where the energy is. For mass-weighted energy, pass masses={joint: m}. pybvh ships no mass model.

ke = bvh.kinetic_energy()
gp.fig_kinetic_energy(bvh, ke, FRAME, t)

kinetic_energy

range_of_motion — the peak-to-peak span of a joint's Euler angles over the clip. The figure shows each rotation channel's trace, with its min–max band shaded. The band height is the ROM.

rom = bvh.range_of_motion("RightForeArm")
gp.fig_range_of_motion(bvh, "RightForeArm", rom, t)

range_of_motion

Note that ch1 has no range of motion here (ROM = 0°). This is because the forearm's rotation order is ZYX, so ch1 is the Y-rotation, and for the elbow that is the non-hinge axis. The elbow is a hinge. It flexes in a single plane, captured here by ch0 (the Z-rotation, ~102°). The bone also twists along its length (ch2, the X-rotation, ~73° of pronation/supination). But the elbow physically cannot bend sideways, so that channel stays at 0 for the whole clip.

cov3dj & lagged_covariance — fixed-size statistical descriptors of a whole sequence:

  • cov3dj: the covariance of all 3D joint coordinates (3N×3N).
  • lagged_covariance: the channel covariance at a temporal lag.

The figure draws them as heatmaps. Block structure reflects coordinated joints.

C = analysis.cov3dj(bvh.joint_positions())
L = analysis.lagged_covariance(bvh.joint_velocities().reshape(F, -1), lag=1)
gp.fig_covariance(C, L)

cov3dj

skeleton_size — the absolute scale proxy: the mean rest-pose distance from the joint the feet branch from, the hips, to the feet (red lines). It scales linearly with the whole skeleton.

bvh_feet = [foot.name for foot in analysis.auto_detect_feet(bvh)]
gp.fig_skeleton_size(bvh, bvh_feet, analysis.skeleton_size(bvh, feet=bvh_feet))

skeleton_size

Gait — on real walking mocap

The remaining descriptors in this section are gait metrics. Unlike everything above, they run on the real walking clip shown in section 5 (walk, with its auto-detected feet), because gait only becomes meaningful over several real strides.

gait_parameters — one-pass spatiotemporal gait analysis from foot contacts + foot landings. It also exposes the cadence / stride_length / walking_pace scalars individually. Since gait input is locomotion by definition, it detects contacts with foot_contacts(…, adaptive=True). That setting splits each foot's speed threshold from its own speed. The height threshold is calibrated to each foot's own stance level. That calibration is what handles retargeted mocap whose feet hover above the estimated floor. Top: the contact raster (blue = planted), with double-support frames shaded orange. It illustrates stance_fraction and double_support_fraction. Bottom: each foot's ground path (in travel-aligned coordinates), with its landing points marked and joined, so that stride_length (landing→landing) and left/right asymmetry are visible. The remaining scalars are printed in the titles. (Kinematic only. Dynamic gait, like joint torques or ground-reaction force, needs a physical model and is out of scope.)

t_walk = np.arange(walk.frame_count) * walk.frame_time
g = walk.gait_parameters(feet=feet)  # feet auto-detected in section 5
gp.fig_gait(walk, feet, g, t_walk)

gait_parameters

10 · Rotations — SE(3) rigid-transform math

Rigid transforms are drawn as coordinate frames (triads): red/green/blue = the x/y/z axes of the frame.

se3_exp / se3_log — a twist [ω, v] (six numbers, rotation first) exponentiates to a 4×4 rigid transform. se3_log inverts it exactly (see the inset round-trip). ω is an axis-angle vector: here 1.4 rad ≈ 80° about z. v is the twist's linear generator, not the final translation. The exp map couples it to the ongoing rotation (d = V(ω)·v). So the origin of the identity frame (faint) travels along the dashed helix to the black dot at d ≈ [0.70, 0.59, 0.60], where the transformed frame (bold) lands. The grey line is the true screw axis.

twist = np.array([0.0, 0.0, 1.4, 1.0, 0.0, 0.6])  # ω about z, with translation
gp.fig_se3_exp(twist)

not

screw_interpolate — the SE(3) analogue of SLERP. It blends two rigid transforms along the constant screw connecting them, rotating and translating together. t = 0 returns T₀. t = 1 returns T₁. An array of ts broadcasts, so the single call below yields all seven triads at once. Their opacity grows with t: T₀ faintest, T₁ boldest. The dashed curve traces the origin's screw arc between them.

T0 = np.eye(4)
T1 = rotations.se3_exp(np.array([0.3, 1.2, 0.6, 2.0, 1.0, 0.5]))
ts = np.linspace(0, 1, 7)
frames = rotations.screw_interpolate(T0, T1, ts)  # (7, 4, 4): t=0 → T₀ … t=1 → T₁
gp.fig_screw_interpolate(frames, ts)

screw_interpolate

relative_transform — the pose of one body segment in another's local frame (the geometry→SE(3) bridge). The two arm bones are drawn. The printed twist is the relative transform se3_log(T_upper⁻¹ T_fore). Segment frames are completed with a fixed world reference direction. That direction keeps the features smooth over time, but it ties them to global heading. So root-align the motion (e.g. harmonize) before you compare these features across clips.

upper = np.stack([P[idx("RightArm")], P[idx("RightForeArm")]])
fore = np.stack([P[idx("RightForeArm")], P[idx("RightHand")]])
twist = rotations.se3_log(rotations.relative_transform(upper[None], fore[None])[0])
gp.fig_relative_transform(bvh, FRAME, twist)

relative_transform

rotation_geodesic_distance — the shortest angular distance between two orientations. Left: two orientation triads and the angle between them. Right: the geodesic distance of the root's orientation at each frame from frame 0.

rotmats = bvh.to_rotmat()
root_R = rotmats[:, 0]
geo = np.degrees(
    rotations.rotation_geodesic_distance(np.broadcast_to(root_R[0], root_R.shape), root_R)
)
gp.fig_geodesic(root_R, geo, t)

rotation_geodesic_distance

11 · Signal — signal utilities

Array-pure numeric helpers, each shown on a small constructed signal where the effect is obvious.

finite_difference — the shared derivative operator. On a sine wave, the central and forward differences both track the analytic derivative (cosine). Central is symmetric. It is also more accurate.

x = np.linspace(0, 4 * np.pi, 200)
h = x[1] - x[0]
d_central = signal.finite_difference(np.sin(x), h, stencil="central")
d_forward = signal.finite_difference(np.sin(x), h, stencil="forward")
gp.fig_finite_difference(x, d_central, d_forward)

finite_difference

temporal_stats & box_filter_smooth — left: a noisy signal with its mean ± std band, and skewness/kurtosis printed. Right: the same signal smoothed by a box (moving-average) filter.

rng = np.random.default_rng(0)
noisy = np.sin(x) + 0.4 * rng.standard_normal(x.size)
st = signal.temporal_stats(noisy)
smoothed = signal.box_filter_smooth(noisy, window=15)
gp.fig_temporal_box(x, noisy, st, smoothed)

temporal_stats

fft_magnitude / dominant_frequency — left: a signal mixing 3 Hz and 11 Hz, shown in time (first second). Right: its one-sided magnitude spectrum (fft_magnitude) resolves both components as peaks. dominant_frequency picks the strongest. The red line lands on the taller 3 Hz peak, not merely any peak.

fsx, n = 100.0, 512
tx = np.arange(n) / fsx
mix = np.sin(2 * np.pi * 3 * tx) + 0.5 * np.sin(2 * np.pi * 11 * tx)
freqs, mag = signal.fft_magnitude(mix, fsx)
dom = signal.dominant_frequency(mix, fsx)
gp.fig_fft(tx, mix, freqs, mag, dom)

figure 60

ramer_douglas_peucker — simplifies a curve, keeping only the points needed to preserve its shape within a tolerance. The noisy curve (grey) is reduced to a few vertices (red) that still capture its form.

tc = np.linspace(0, 1, 300)
curve = np.stack([tc, np.sin(2 * np.pi * tc) + 0.05 * rng.standard_normal(tc.size)], 1)
simp = signal.ramer_douglas_peucker(curve, eps=0.15)
gp.fig_rdp(curve, simp, 0.15)

ramer_douglas_peucker

12 · Scale

relative_scale_factor — the least-squares uniform scale that best matches one skeleton to another. Here a skeleton (blue) and a 1.6× copy (orange) are shown. The recovered factor matches the original poses back together.

rest = bvh.rest_pose_positions()
factor = analysis.relative_scale_factor(rest, rest * 1.6)
gp.fig_relative_scale(bvh, factor, 1.6)

relative_scale_factor


That is pybvh's visual surface: every operation, transform, descriptor, and utility that has a picture. Each is drawn so that the picture explains the call. What has no natural picture (file I/O, batch loading, harmonization, pandas) lives in the capability map instead. The array-pure kernels (geometry.*, the smoothness functions, the SE(3) math, signal.*) take plain NumPy arrays. So any of these visuals can be reproduced without a Bvh at all.