Skip to content

Transforms

transforms

Spatial augmentation transforms for BVH motion data.

Bvh-level API — All transforms operate on :class:~pybvh.bvh.Bvh objects and follow the inplace=False convention: by default they return a new object, leaving the original unchanged.

NumPy-level API — Lower-level functions (mirror_angles, rotate_angles_vertical) accept raw arrays + minimal metadata for users who work with pre-extracted arrays.

All angle parameters are in radians (pybvh's internal convention); functions that rotate accept a degrees=True flag matching the convention in :mod:~pybvh.rotations.

translate_root(bvh: Bvh, offset: npt.ArrayLike, inplace: bool = False) -> Bvh | None

Shift the root position by a constant 3-D offset.

Parameters:

Name Type Description Default
bvh Bvh

Input motion.

required
offset array_like of shape (3,)

Translation vector (dx, dy, dz).

required
inplace bool

If True, modify bvh and return None.

False

Returns:

Type Description
Bvh or None

Raises:

Type Description
ValueError

If offset is not of shape (3,), or if the root is static (CHANNELS 0): it stays at its offset.

random_translate_root(bvh: Bvh, offset_range: tuple[float, float] = (-100.0, 100.0), rng: np.random.Generator | None = None) -> Bvh

Translate root by a random offset sampled uniformly per axis.

Parameters:

Name Type Description Default
bvh Bvh

Input motion.

required
offset_range tuple of (low, high)

Uniform sampling range applied to each axis independently.

(-100.0, 100.0)
rng Generator or None

Random generator for reproducibility.

None

Returns:

Type Description
Bvh

add_rotation_noise(bvh: Bvh, sigma: float, rng: np.random.Generator | None = None, inplace: bool = False, wrap: bool = False, degrees: bool = False) -> Bvh | None

Add zero-mean Gaussian noise to joint rotation angles.

Parameters:

Name Type Description Default
bvh Bvh

Input motion.

required
sigma float

Standard deviation of the rotation noise in radians (or degrees if degrees=True), added to joint_angles. 0 is a no-op and draws nothing from rng.

required
rng Generator or None

Random generator for reproducibility.

None
inplace bool

If True, modify bvh and return None.

False
wrap bool

If True, wrap noised angles to [-π, π]. Default False: BVH channels can legitimately hold values outside that range (accumulated rotations spanning multiple turns), and wrapping those would corrupt them.

False
degrees bool

If True, interpret sigma in degrees. Default False (radians).

False

Returns:

Type Description
Bvh or None

A static root's row (CHANNELS 0) gets no noise: the root does not rotate.

See Also

add_position_noise : The root-translation counterpart.

add_position_noise(bvh: Bvh, sigma: float, rng: np.random.Generator | None = None, inplace: bool = False) -> Bvh | None

Add zero-mean Gaussian noise to the root translation.

Parameters:

Name Type Description Default
bvh Bvh

Input motion.

required
sigma float

Standard deviation of the noise added to root_pos, in the skeleton's length unit — the same unit as the bone offsets, so it scales with the file rather than being absolute. There is no degrees= here because this is a length, not an angle. 0 is a no-op and draws nothing from rng.

required
rng Generator or None

Random generator for reproducibility.

None
inplace bool

If True, modify bvh and return None.

False

Returns:

Type Description
Bvh or None

Raises:

Type Description
ValueError

If sigma is negative, or if the root is static (CHANNELS 0): it stays at its offset.

See Also

add_rotation_noise : The joint-angle counterpart.

perturb_speed(bvh: Bvh, factor: float) -> Bvh

Change motion speed by resampling.

A factor of 2.0 makes the motion twice as fast (fewer frames); 0.5 makes it half as fast (more frames). Uses the existing :meth:Bvh.resample which performs quaternion SLERP for rotations.

Parameters:

Name Type Description Default
bvh Bvh

Input motion.

required
factor float

Speed multiplier (must be > 0).

required

Returns:

Type Description
Bvh

New Bvh with an adjusted frame count and the original frame_time — the clip's duration changes, its playback rate does not.

Notes

This resamples: the motion is re-interpolated onto a new time grid (see :meth:Bvh.resample), so joint rotations pass through SLERP and the frame count changes. The alternative convention — scale frame_time by 1 / factor and leave the samples untouched — is lossless and changes duration too, but yields a non-standard frame rate rather than a resampled clip. Use that directly when you want playback-rate change without interpolation.

random_perturb_speed(bvh: Bvh, factor_range: tuple[float, float] = (0.8, 1.2), rng: np.random.Generator | None = None) -> Bvh

Apply a random speed change sampled uniformly from factor_range.

Parameters:

Name Type Description Default
bvh Bvh

Input motion.

required
factor_range tuple of (low, high)

Range for the speed factor.

(0.8, 1.2)
rng Generator or None

Random generator for reproducibility.

None

Returns:

Type Description
Bvh

drop_frames(bvh: Bvh, drop_rate: float, rng: np.random.Generator | None = None, inplace: bool = False) -> Bvh | None

Replace randomly selected frames with SLERP-interpolated values.

Dropped frames are filled by spherical linear interpolation (SLERP) of the nearest kept neighbours' quaternion rotations and linear interpolation of root positions. The output has the same frame count as the input, and kept frames are preserved exactly (bit-for-bit) — only the dropped frames are re-synthesized.

Parameters:

Name Type Description Default
bvh Bvh

Input motion.

required
drop_rate float

Fraction of frames to drop, in [0, 1). First and last frames are always kept.

required
rng Generator or None

Random generator for reproducibility.

None
inplace bool

If True, modify bvh and return None.

False

Returns:

Type Description
Bvh or None

rotate_angles_vertical(joint_angles: npt.NDArray[np.float64], root_pos: npt.NDArray[np.float64], angle: float, up_idx: int, root_order: str, degrees: bool = False, pivot: str | npt.ArrayLike = 'origin') -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]

Rotate motion around the vertical axis (NumPy-level).

Only modifies root_pos and the root joint's Euler angles (index 0 in joint_angles). Non-root joints are in parent-local coordinates and are unaffected.

Parameters:

Name Type Description Default
joint_angles ndarray of shape (F, J, 3)

Euler angles in radians (pybvh's internal convention).

required
root_pos ndarray of shape (F, 3)

Root translation per frame.

required
angle float

Rotation angle in radians (or degrees if degrees=True).

required
up_idx int

Index of the up axis (0=X, 1=Y, 2=Z).

required
root_order str

Euler order of the root joint, e.g. 'ZYX'.

required
degrees bool

If True, interpret angle in degrees. Default False (radians).

False
pivot ('origin', 'root')

World-space point the motion turns about. "origin" (default) turns about the world origin, so a motion standing away from it sweeps through space along an arc; "root" turns about the first frame's root position, i.e. turn-in-place; an explicit (3,) point turns about a fixed landmark. Only the two horizontal components are read — every point on a vertical line spans the same rotation axis — so "root" is equivalently the first-frame root projected to the ground plane.

"origin"

Returns:

Type Description
(new_joint_angles, new_root_pos)

Copies with the rotation applied. Angles in radians.

Notes

The pivot only translates the root trajectory: rotating about p is the same as root_pos - p → rotate about the origin → + p, and the root's world rotation is identical either way. So a pipeline that already centers its clips on the first-frame root gets turn-in-place from the default "origin" and needs no pivot=.

See Also

rotate_vertical : Bvh-level wrapper that auto-detects up_idx and root_order from the skeleton.

Examples:

>>> from pybvh import read_bvh_file
>>> bvh = read_bvh_file('bvh_data/bvh_test1.bvh')
>>> angles = bvh.joint_angles          # (F, J, 3) radians
>>> pos = bvh.root_pos                 # (F, 3)
>>> up = {'x': 0, 'y': 1, 'z': 2}[bvh.world_up[1]]
>>> order = ''.join(bvh.root.rot_channels)
>>> new_angles, new_pos = rotate_angles_vertical(
...     angles, pos, np.pi / 2, up, order)

rotate_vertical(bvh: Bvh, angle: float, world_up: str | None = None, degrees: bool = False, pivot: str | npt.ArrayLike = 'origin', inplace: bool = False) -> Bvh | None

Rotate the entire motion around the vertical (up) axis.

Only the root joint's world-space rotation and root position are modified. Child joints are in parent-local coordinates and are unaffected.

Parameters:

Name Type Description Default
bvh Bvh

Input motion.

required
angle float

Rotation angle in radians (positive = counter-clockwise when viewed from above). Pass degrees=True for degrees.

required
world_up str or None

Signed axis string (e.g. '+y'). Auto-detected if None.

None
degrees bool

If True, interpret angle in degrees. Default False (radians).

False
pivot ('origin', 'root')

World-space point the motion turns about. Default "origin", the world origin: a character standing away from it sweeps through space along an arc rather than turning where it stands. "root" is that turn-in-place — it pivots about the first frame's root position, projected to the ground plane. An explicit (3,) point pivots about a fixed landmark (a dataset capture centre, a stage mark). Only the two horizontal components of a point are read: every point on a vertical line spans the same rotation axis, so the up-axis component is dropped and heights come through untouched.

"origin"
inplace bool

If True, modify bvh and return None.

False

Returns:

Type Description
Bvh or None

Raises:

Type Description
ValueError

If the root is static (CHANNELS 0): it does not move or rotate.

Notes

The pivot moves only the root trajectory — the root's world rotation, and every child joint's parent-local angles, are identical for any pivot. Equivalently, pivot="root" is center on the first-frame root → rotate about the origin → un-center: a pipeline that already centers its clips gets turn-in-place from the default and needs no pivot= at all.

Randomized pivots are deliberately not offered here (unlike angle, which has :func:random_rotate_vertical). A random pivot is a rotation composed with a translation, so it is already expressible as rotate_vertical + :func:translate_root, and which distribution to draw from is a pipeline's decision, not a motion's.

random_rotate_vertical(bvh: Bvh, angle_range: tuple[float, float] = (-np.pi, np.pi), world_up: str | None = None, degrees: bool = False, pivot: str | npt.ArrayLike = 'origin', rng: np.random.Generator | None = None) -> Bvh

Rotate motion by a random angle around the vertical axis.

Parameters:

Name Type Description Default
bvh Bvh

Input motion.

required
angle_range tuple of (low, high)

Angle sampling range in radians (default full circle, (-π, π)), or in degrees if degrees=True.

(-pi, pi)
world_up str or None

Signed axis string. Auto-detected if None.

None
degrees bool

If True, interpret angle_range in degrees. Default False (radians).

False
pivot ('origin', 'root')

World-space point to turn about, as in :func:rotate_vertical. Only the angle is random; the pivot is fixed for the call.

"origin"
rng Generator or None

Random generator for reproducibility.

None

Returns:

Type Description
Bvh

mirror_angles(joint_angles: npt.NDArray[np.float64], root_pos: npt.NDArray[np.float64], lr_joint_pairs: list[tuple[int, int]], lateral_idx: int, rot_channels: Sequence[Sequence[str]]) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]

Mirror joint angles and root position (NumPy-level).

Performs the array-level operations of mirroring: negating the lateral component of root_pos, swapping L/R joint angle columns, and negating Euler angle components whose rotation axis is not the lateral axis.

This function does not modify skeleton offsets (bone geometry). For a complete mirror that also adjusts the skeleton, use the Bvh-level :func:mirror function.

Parameters:

Name Type Description Default
joint_angles ndarray of shape (F, J, 3)

Euler angles in radians (pybvh's internal convention).

required
root_pos ndarray of shape (F, 3)

Root translation per frame.

required
lr_joint_pairs list of (left_idx, right_idx)

Index pairs into the joint axis of joint_angles.

required
lateral_idx int

Index of the lateral axis (0=X, 1=Y, 2=Z).

required
rot_channels sequence of sequences of str

Per-joint Euler channel order, e.g. [('Z','Y','X'), ...] (each joint's rot_channels) or ['ZYX', ...]. Length must equal J.

required

Returns:

Type Description
(new_joint_angles, new_root_pos)

Copies with the mirroring applied.

Notes

Each joint keeps its own Euler order. The pair members of lr_joint_pairs may declare different channel orders (BVH permits it, and solver output sometimes does it); when they do, the swapped triple is re-expressed in the destination joint's order by way of a rotation matrix rather than copied across verbatim. The alternative would be to swap the orders along with the numbers, but that changes the skeleton definition and would make the mirror of a mirror lossless only by accident. The two agree whenever a pair already shares an order, which is the common case.

Re-expressing a triple returns the canonical Euler solution for that order, so the output numbers of a mismatched pair need not match the input numbers even though the rotation is the same — compare rotations (or FK positions), not raw angles.

See Also

mirror : Bvh-level wrapper that also mirrors skeleton offsets and auto-detects lr_joint_pairs, lateral_idx, and rot_channels from the skeleton.

Examples:

>>> from pybvh import read_bvh_file
>>> bvh = read_bvh_file('bvh_data/bvh_test1.bvh')
>>> angles = bvh.joint_angles
>>> pos = bvh.root_pos
>>> pairs = bvh.lr_pairs
>>> lat_idx = {'x': 0, 'y': 1, 'z': 2}[bvh.left_at(frame=0)[1]]
>>> channels = [n.rot_channels for n in bvh.nodes if not n.is_end_site()]
>>> new_angles, new_pos = mirror_angles(
...     angles, pos, pairs, lat_idx, channels)

mirror(bvh: Bvh, lr_mapping: dict[str, str] | None = None, lateral: str | None = None, inplace: bool = False) -> Bvh | None

Mirror (reflect) the motion across the lateral plane.

Swaps left/right joint data and negates the appropriate rotation and position components so that the skeleton appears as a mirror image. :attr:~pybvh.bvh.Bvh.joint_translations are mirrored as the offsets are: the lateral component negated, the columns of an L/R pair swapped.

Parameters:

Name Type Description Default
bvh Bvh

Input motion.

required
lr_mapping dict or None

{"LeftArm": "RightArm", ...}. Defaults to :attr:Bvh.lr_mapping (auto-detected or user-set).

None
lateral str or None

Axis perpendicular to the mirror plane, e.g. 'x' or '+x' (the sign is irrelevant for mirroring). Auto-detected if None, and the detection is usually the right thing to use: it reads the skeleton's own left, the left-minus-right rest-pose positions averaged over the L/R joint pairs with the :attr:~pybvh.bvh.Bvh.rest_up component removed, so it measures how this skeleton is actually built rather than assuming a convention, and never reads world_up. Rest up is read as it would be with lr_mapping set on the clip: on a rig without a named up joint, from the legs among its pairs. Pass an explicit axis only to override that, or when the detection raises because the L/R offsets are degenerate (parallel to rest_up, or zero).

None
inplace bool

If True, modify bvh and return None. With True, the skeleton is replaced, not edited: a node taken from bvh.nodes before the call keeps its old values.

False

Returns:

Type Description
Bvh or None

Raises:

Type Description
ValueError

If no left/right pairs are available, if an explicitly passed lr_mapping names joints that don't exist, or if one joint of an L/R pair translates and the other does not.

reorient_world_up(bvh: Bvh, new_up: str, inplace: bool = False) -> Bvh | None

Change the world coordinate system's vertical axis.

Applies a global rotation to the entire animation (root translation, skeleton offsets, joint translations, root joint rotations) so the world vertical axis changes from the current bvh.world_up to new_up. The character looks visually identical; only the coordinate system changes. A static root (CHANNELS 0) keeps its zero rotation: its offset and root_pos turn with the world.

Restricted to axis-aligned rotations (multiples of 90 degrees) for lossless transformation. Many rotations carry the old up onto the new one; pybvh applies the smallest. Between two different axes that is the 90-degree turn about the axis perpendicular to both. Between the two signs of one axis ('+y' to '-y') no smallest one exists, and pybvh turns 180 degrees about the next axis in the cycle X, Y, Z (y flips about z, z about x, x about y); the flip about the other horizontal axis differs from it by a half turn about the up axis, so the character would face the opposite way.

Parameters:

Name Type Description Default
bvh Bvh

Input motion. Its current :attr:~pybvh.bvh.Bvh.world_up, set or inferred, is the axis rotated away from.

required
new_up str

Target up axis, e.g. '+y'.

required
inplace bool

If True, modify bvh and return None. Default False: return a reoriented copy. With True, the skeleton is replaced, not edited: a node taken from bvh.nodes before the call keeps its old values.

False

Returns:

Type Description
Bvh or None

The reoriented copy, or None when inplace=True. Its world_up is new_up, set as an override. The guessed axis turns with the frames, so assigning 'auto' afterwards gives the axis the rotated frames show.

reorient_rest_up(bvh: Bvh, new_up: str, inplace: bool = False) -> Bvh | None

Rotate the skeleton's rest-pose offsets so its own up (rest up) aligns with new_up, compensating all joint rotations so that FK positions are unchanged. :attr:~pybvh.bvh.Bvh.joint_translations turn with the offsets.

This fixes files where the rest pose and animation disagree on the up axis (e.g. rest pose authored in Y-up but animation plays in Z-up). After this call, the disagreement warning disappears.

The world coordinate system is unchanged: root_pos and world_up are NOT modified.

The rotation is chosen as :func:reorient_world_up chooses it.

Parameters:

Name Type Description Default
bvh Bvh

Input motion. Its rest-pose up axis is inferred from the joint offsets, as :attr:~pybvh.bvh.Bvh.rest_up reports it.

required
new_up str

Target rest-pose up axis, e.g. '+y'.

required
inplace bool

If True, modify bvh and return None. Default False: return a reoriented copy. With True, the skeleton is replaced, not edited: a node taken from bvh.nodes before the call keeps its old values.

False

Returns:

Type Description
Bvh or None

The reoriented copy, or None when inplace=True.

Raises:

Type Description
ValueError

If the rest pose is degenerate (no up axis can be inferred), or if the root is static (CHANNELS 0): the root would have to take the inverse turn, and a static root does not rotate.

reorient_rest_forward(bvh: Bvh, new_forward: str, inplace: bool = False) -> Bvh | None

Rotate the skeleton's rest-pose offsets so the character faces new_forward, compensating all joint rotations so FK positions are unchanged. :attr:~pybvh.bvh.Bvh.joint_translations turn with the offsets.

The rotation is about the rest pose's own up, :attr:~pybvh.bvh.Bvh.rest_up: the rest pose turns in its own frame, whatever :attr:~pybvh.bvh.Bvh.world_up is, so rest_up is the same afterwards and :attr:~pybvh.bvh.Bvh.rest_forward is new_forward. new_forward must not be parallel to rest_up.

Parameters:

Name Type Description Default
bvh Bvh

Input motion. Its rest-pose forward and up are read from the rest pose, as :attr:~pybvh.bvh.Bvh.rest_forward and :attr:~pybvh.bvh.Bvh.rest_up report them.

required
new_forward str

Target rest-pose forward axis, e.g. '+y' or '-z'.

required
inplace bool

If True, modify bvh and return None. Default False: return a reoriented copy. With True, the skeleton is replaced, not edited: a node taken from bvh.nodes before the call keeps its old values.

False

Returns:

Type Description
Bvh or None

The reoriented copy, or None when inplace=True.

Raises:

Type Description
ValueError

If the rest pose is degenerate (no up axis can be inferred), new_forward is parallel to rest_up, or the root is static (CHANNELS 0): the root would have to take the inverse turn, and a static root does not rotate.