Skip to content

API Reference

Find a function

The fastest route from "I want to…" to the exact call. The Gallery also draws everything visual, one picture per feature.

I want to… Call Reference
Load / write a BVH file pybvh.read_bvh_file(path) / bvh.write(path) I/O
Load a whole directory read_bvh_directory("data/", parallel=True) Batch
Reconcile mixed skeletons / fps / up-axes harmonize(clips) batch.harmonize
Get 3D joint positions (forward kinematics) bvh.node_positions() Bvh.node_positions
Convert rotation representations bvh.to_quat(), bvh.to_6d(), … Rotations
Interpolate rotations / rigid transforms rotations.quat_slerp(...) / rotations.screw_interpolate(...) Rotations & SE(3)
Detect foot contacts bvh.foot_contacts() analysis.foot_contacts
Measure gait (cadence, stride, symmetry) bvh.gait_parameters() analysis.gait_parameters
Score movement smoothness (SPARC, jerk) bvh.smoothness(node, metric="sparc") analysis.smoothness
Velocities / accelerations / jerk bvh.joint_velocities() … bvh.node_jerk() Analysis
Trajectory shape (curvature, path length, …) bvh.curvature(node), bvh.path_length(node) Geometry
Pose extent & centre of mass bvh.bounding_box(), bvh.center_of_mass() Geometry
Relative pose of two segments, SE(3) twists rotations.relative_transform(...), se3_log Rotations & SE(3)
Augment data (mirror, rotate, noise, …) bvh.mirror(), bvh.rotate_vertical(a), … Transforms
Export one ML-ready feature array bvh.to_feature_array(representation="6d") features.to_feature_array
Stack many clips into one array batch_to_numpy(clips, pad=True) batch.batch_to_numpy
Smooth / differentiate / FFT a signal signal.box_filter_smooth(...), signal.fft_magnitude(...) Signal
Visualize (snapshot, video, interactive) bvh.plot_frame(), bvh.render("out.mp4"), bvh.play() Visualization
Edit the skeleton (retarget, scale, subset) bvh.retarget(ref), bvh.extract_joints([...]) Bvh.retarget
Slice / concatenate / resample frames bvh[10:50], bvh + other, bvh.resample(30) Bvh Class
Fix the up axis or facing convention bvh.reorient_world_up('+z'), bvh.reorient_rest_up('+z') Bvh.reorient_world_up
Round-trip through pandas bvh.to_df_dict() / pybvh.df_to_bvh(...) Bvh Class

Modules at a glance

Module Owns Page
pybvh.Bvh the central container: skeleton + motion, with every high-level method Bvh Class
pybvh.io reading and writing .bvh files I/O
pybvh.rotations conversions between all rotation representations, SLERP, SE(3) rigid-transform math Rotations & SE(3)
pybvh.geometry array-pure position descriptors: trajectories, bounding volumes, centre of mass Geometry
pybvh.transforms augmentation: mirror, rotate, translate, noise, speed, dropout Transforms
pybvh.analysis motion dynamics: velocities → jerk, foot contacts, gait, smoothness, covariance Analysis
pybvh.features the flat (F, D) ML feature-array export and its column layout Features
pybvh.signal array-pure signal utilities: finite differences, stats, smoothing, FFT Signal
pybvh.batch directory-level loading, harmonization, batched NumPy export Batch
pybvh.bvhplot visualization: snapshots, video/GIF export, interactive playback Visualization

Top-level exports

pybvh

Read, write and analyze BVH motion capture data as NumPy arrays.

A Bvh holds one clip: its skeleton, the root translation, shape (F, 3) in the file's length unit, and the joint rotations, shape (F, J, 3), as Euler angles in radians (files store degrees; the conversion happens on reading and writing). read_bvh_file loads one file and read_bvh_directory a folder of them. The package namespace re-exports the main entry points; everything else lives in its submodule, for example rotations, transforms, analysis, features or bvhplot.

HarmonizeReport(kept_indices: list[int] = list(), kept_sources: list[str | None] = list(), dropped_indices: list[int] = list(), dropped_sources: list[str | None] = list(), drop_reasons: list[str] = list(), applied_stages: list[dict[str, str]] = list()) dataclass

Per-call summary of what :func:harmonize did to each clip.

All fields use JSON-native types so the report can be serialized directly with json.dumps(dataclasses.asdict(report)) and embedded as audit metadata alongside a preprocessed dataset.

Attributes:

Name Type Description
kept_indices list of int

Indices (into the input clips list) of clips that survived the topology gate.

kept_sources list of str or None

source_path of each kept clip, aligned with kept_indices.

dropped_indices list of int

Indices of clips that were dropped by the topology gate.

dropped_sources list of str or None

source_path of each dropped clip, aligned with dropped_indices.

drop_reasons list of str

One human-readable reason per dropped clip, aligned with dropped_indices.

applied_stages list of dict

One dict per kept clip, aligned with kept_indices. Each dict records which harmonization stages ran for that clip, with before→after where meaningful. Possible keys: "retarget", "resample", "world_up", "rest_up", "rest_forward", "euler_order". Empty dict means the clip passed the gate without needing any transformation. "resample" records an interpolation only: a clip that already has target_fps's rate and only takes its exact frame time has no "resample" key.

FkTopology

Bases: _FkTopologyFields

A skeleton's topology as plain arrays — everything forward kinematics reads.

The array-signature counterpart of a node tree: :func:frames_to_node_positions accepts one of these in place of a :class:~pybvh.Bvh or a node list such as :attr:~pybvh.Bvh.nodes, so a caller holding only arrays (a data loader reading a preprocessed dataset, an augmentation step that has no source file open) can run forward kinematics without reconstructing node objects.

This is an FK input bundle, not a skeleton descriptor: it carries what the FK loop reads and nothing else — no names, no orientation axes, no channel layout. Every field is independently serializable (four arrays and a list of strings), so a preprocessing step can store the five values in whatever container it already uses; the type itself is not a serialization format. For anything else about a skeleton, keep the :class:~pybvh.Bvh.

Instances validate on construction (see Raises), because the train-time caller builds one from arrays with no node tree to check against. A malformed topology raises here rather than producing silently wrong geometry: two of the failure modes are indistinguishable from valid input downstream — a root marked as an end site reads joint_idx == -1 as a negative index into the rotation array, and a node parented to an end site reads uninitialized memory for its parent's accumulated rotation.

Attributes:

Name Type Description
offsets (ndarray, shape(N, 3))

Each node's rest-pose offset from its parent, in the skeleton's length unit. Node order is the caller's; it need not be depth-first, but parents must precede children (see Raises).

parent_idx (ndarray, shape(N))

Index of each node's parent, -1 for the root. Exactly one -1, and it is necessarily at index 0.

joint_idx (ndarray, shape(N))

Index of each node's rotation along joint_angles axis 1, and -1 for end sites — which is also what marks a node as an end site; there is no separate flag.

euler_orders list of str

Per-joint Euler order, e.g. ['ZYX', ...], length J. A static root (CHANNELS 0) declares no rotation channel and has order '': forward kinematics reads its rotation as the identity, and refuses a non-zero angle for it (see :func:~pybvh.rotations.euler_to_rotmat). Only the root, at joint column 0, may have ''.

Indexed by joint column, not by node. euler_orders[j] is the order of the node whose joint_idx == j. The two coincide only when joint_idx counts up in node order, which is what :meth:from_nodes and :attr:Bvh.fk_topology produce. A caller that permutes the joint columns — packing vertices into a graph layout, say — must permute this list the same way. No check can catch a mismatch: every permutation is a valid topology, just not the one you meant.

translation_idx (ndarray, shape(N))

Index of each node's position along joint_translations axis 1, and -1 for a node placed at its offset in every frame: the root (placed by root_pos), an end site, and a joint that only rotates. A translating joint (one whose CHANNELS line declares position channels) is placed at its row of joint_translations in each frame instead of its offset. All -1 on a clip whose joints other than the root only rotate. Required: without it, a translating joint would be placed at its offset, wrong with no error.

Raises:

Type Description
ValueError

If the arrays disagree on N, offsets is not (N, 3), an Euler order is neither a permutation of 'XYZ' nor '' on the root at joint column 0, or any of the following invariants is broken:

  • Parents precede children (parent_idx[i] < i). The FK loop fills node i while reading its parent's already-written row, so a forward reference reads an unwritten one.
  • Exactly one root (one -1 in parent_idx).
  • The root is a joint (joint_idx[0] >= 0). A -1 there is a valid negative index into the rotation array, so it silently applies the last joint's rotation to the whole skeleton.
  • No node is parented to an end site. End sites accumulate no rotation, so their children would read an uninitialized frame.
  • Joint columns are a complete range — the non-negative joint_idx values are exactly 0..J-1, each once — and len(euler_orders) == J.
  • Translation columns are a complete range — the non-negative translation_idx values are exactly 0..P-1, each once — and neither the root (its position is root_pos) nor an end site reads one.
See Also

Bvh.fk_topology : Derive one from a loaded skeleton. from_nodes : Derive one from a bare node list. frames_to_node_positions : The FK entry point that consumes it.

Examples:

>>> from pybvh import read_bvh_file
>>> bvh = read_bvh_file('bvh_data/bvh_test1.bvh')
>>> topology = bvh.fk_topology            # at preprocessing time
>>> root_pos, joint_angles = bvh.root_pos, bvh.joint_angles
>>> joint_translations = bvh.joint_translations  # the motion, kept as arrays
>>> import os, tempfile
>>> folder = tempfile.TemporaryDirectory()  # any folder of yours
>>> path = os.path.join(folder.name, 'topology.npz')
>>> np.savez(path, offsets=topology.offsets, parent_idx=topology.parent_idx,
...          joint_idx=topology.joint_idx, euler_orders=topology.euler_orders,
...          translation_idx=topology.translation_idx)
>>> # at train time, no Bvh in sight
>>> with np.load(path) as d:
...     topology = FkTopology(d['offsets'], d['parent_idx'], d['joint_idx'],
...                           list(d['euler_orders']), d['translation_idx'])
>>> coords = frames_to_node_positions(topology, root_pos, joint_angles,
...                                   joint_translations=joint_translations)
>>> folder.cleanup()

__new__(offsets: npt.ArrayLike, parent_idx: npt.ArrayLike, joint_idx: npt.ArrayLike, euler_orders: list[str], translation_idx: npt.ArrayLike) -> FkTopology

Build a topology from its five fields, validated.

offsets is converted to float64, parent_idx, joint_idx and translation_idx to intp, and each Euler order to str, so a topology loaded from np.load (a string array of orders, say) comes back in the same form :meth:from_nodes produces. The fields and the ValueError raised for a malformed topology are described on the class.

from_nodes(nodes: Sequence[BvhNode]) -> FkTopology classmethod

Derive a topology from a node tree.

Parameters:

Name Type Description Default
nodes sequence of BvhNode

Nodes in an order where every parent precedes its children — the depth-first order of :attr:Bvh.nodes, for instance.

required

Returns:

Type Description
FkTopology

joint_idx counts up in node order, so euler_orders matches :attr:Bvh.euler_orders element for element: a static root (CHANNELS 0), which declares no rotation channel, reads ''. translation_idx counts up in node order over the translating joints, the order of :attr:Bvh.joint_translations' columns.

Notes

Parents are resolved by object identity, never by name: node names need not be unique (the parser generates end-site display names from the parent's name, so two end sites under one joint collide), and a name-keyed lookup would silently attach a limb to the wrong parent.

read_bvh_file(filepath: str | Path, world_up: str = 'auto', warn_on_world_up_disagreement: bool = True, lr_mapping: dict[str, str] | None = None, body_anchor: str | None = None) -> Bvh

Parse a BVH motion capture file and return a Bvh object.

Parameters:

Name Type Description Default
filepath str or Path

Path to the BVH file.

required
world_up str

World vertical axis. "auto" (default) auto-detects from animation data. Pass a signed axis string like "+y" to skip auto-detection and suppress the disagreement warning.

'auto'
warn_on_world_up_disagreement bool

If True (default) and world_up="auto", emit a UserWarning when the rest-pose and first-frame inferences disagree. The returned clip keeps the setting for its lifetime. Load does not spend it. world_up is inferred again when you assign the motion (root_pos, joint_angles or frames). Each of those inferences follows the setting, and so does :attr:Bvh.world_up_inferred. Clips that a :class:Bvh operation derives from this one (slices, copy(), transformed copies, extract_joints, resample) inherit the setting, along with the world up itself. A concatenation a + b follows a, as it does for frame_time. A clip rebuilt from its data (:func:~pybvh.df_to_bvh, :meth:Bvh.from_df) is a new clip, like one read from a file. It starts from the default. The alternative is a one-shot suppression of the load-time inference only. It would warn again on the first motion assignment of a clip that you asked to keep quiet.

True
lr_mapping dict or None

Explicit left/right joint pair mapping ({"arm.L": "arm.R", ...}). If you give one, the name-based auto-detection is skipped for this file. Use it for skeletons whose naming conventions the heuristic cannot parse.

None
body_anchor str or None

The name of the joint the body's measures start from, set on the clip as :attr:Bvh.body_anchor is set, before the world up is guessed. None (default) leaves the anchor to the rule that :attr:Bvh.body_anchor describes. Give it when you know better than the rule, such as on a rig whose chest and hips meet the L/R pairs at the same depth. The clip and every clip derived from it keep it (see :attr:Bvh.body_anchor).

None

Returns:

Name Type Description
bvh Bvh

A Bvh object containing the skeleton hierarchy, root positions, joint angles, and frame time.

Raises:

Type Description
ValueError

If the file is malformed, for example if its Frame Time is missing, zero, negative, NaN or infinite, or if a joint declares other channels than 3 rotation channels, or 3 position + 3 rotation channels (the error names the joint). The root declares 3 position + 3 rotation channels, or none (CHANNELS 0). Also if the file holds several hierarchies (ROOT blocks): a Bvh is one hierarchy, and the error gives their count. Also if body_anchor names no joint, an end site, or more than one joint (the error of :meth:Bvh.index).

Notes

BVH files store joint angles in degrees. pybvh holds them in radians, on :attr:Bvh.joint_angles. This function converts them on read. :func:write_bvh_file converts them back on write.

A root that declares CHANNELS 0 (Blender's exporter writes one, ROOT __0, above an armature with several root bones) is a static root (:meth:~pybvh.bvhnode.BvhRoot.is_static). It stays at its OFFSET with no rotation: :attr:Bvh.root_pos holds its offset in every frame, and its row of :attr:Bvh.joint_angles is zero. :func:write_bvh_file writes it back as CHANNELS 0.

The name of a ROOT or JOINT is the rest of its line, with the whitespace at both ends removed. Inner whitespace is kept as written: JOINT Bip01 L Thigh (a 3ds Max Biped name) reads as "Bip01 L Thigh", and :func:write_bvh_file writes it back the same. A { as the line's last word opens the block and is not part of the name: ROOT Hips { reads as "Hips". The BVH format has no quoting, and other readers differ on such a name: bvh-python keeps the first word only, and Blender's importer joins the words with underscores (Bip01_L_Thigh). So a file with these names can read differently elsewhere. pybvh does not warn about it.

The reader normalizes three things, rather than preserving them verbatim. So a round-trip is lossless in motion, but not byte-for-byte:

  • Frame time is recovered when the file's value is the frame time of a round rate, truncated or rounded by its exporter. Exporters often print Frame Time at 6 decimals: 0.033333 for 30 fps, which is 30.0003 fps. A resample and back then drifts. The reader looks for the rate with the fewest decimals, from 0 to 3, whose frame time gives exactly the file's text when it is rounded or truncated to the decimals that the file prints. When exactly one rate with that many decimals fits, bvh.frame_time is 1 / rate. When several fit, or none with up to 3 decimals, it is the value as read. 0.033333 and 0.033 read as 1 / 30. 0.004166 reads as 1 / 240, and 0.033367 as 1 / 29.97. 0.017 (every whole rate from 56 to 60 fps fits) and 0.008341 (119.88 and 119.89 fps) are kept as read. A 29.97 fps file becomes 1 / 29.97, which is 1.000001e-6 relative from NTSC's exact 1001 / 30000. When you need that value, set bvh.frame_time = 1001 / 30000 after reading. The rule recovers lost digits, not round numbers. So a text of 17 significant digits or more, which names one float exactly, is kept as read: 0.033366700033366700 reads as itself, one float from 1 / 29.97. The text alone cannot tell a short frame time from a truncated one. So :func:write_bvh_file writes all 17 significant digits (its Notes say why). A clip whose frame_time is 0.033 is written 0.033000000000000002, and it reads back as 0.033. None of the other BVH readers surveyed recovers a rate. Those that use the value take the text as printed. One (fairmotion) rounds the rate to a whole number. Where the rule recovers a rate, the printed value differs from pybvh's by less than one unit of its last decimal (0.033333 against 1 / 30). Where the rule keeps the text, the two agree. The rounded rate differs from pybvh's wherever pybvh's is not whole (0.033367 gives 30 fps, 0.017 59 fps). In a file at 6 decimals, it also differs on some whole rates above 720 fps (0.001386 gives 722 fps, where pybvh reads 721).
  • Channels are reordered to position-first, with the position channels in X, Y, Z order, the order of a :attr:Bvh.root_pos row, on the root and on every translating joint (a joint whose CHANNELS line declares 3 position + 3 rotation channels; its values are :attr:Bvh.joint_translations). A file that declares rotations before positions, or Zposition Yposition Xposition, parses correctly, and the node's pos_channels is ('X', 'Y', 'Z'): the declared order is not kept. Position channels interleaved with rotation channels are read as translate first, then rotate. :func:write_bvh_file writes the canonical order, so a write changes such a declaration once, and the output is the same from then on. The rotation channels keep their declared order, which is the node's Euler order.
  • Offsets and motion values are written at 6 decimal places, so re-reading a written file quantizes at ~1e-6 in the file's own units. The frame time is written at 17 significant digits, which reads back as the same float.

Values that pybvh infers or that you set (world_up, lr_mapping, body_anchor) have nowhere to live in the BVH format. They are lost on write. Re-apply them after reading.

write_bvh_file(bvh: Bvh, filepath: str | Path, verbose: bool = False, overwrite: bool = True) -> None

Write a Bvh object to a .bvh file.

Parameters:

Name Type Description Default
bvh Bvh

The motion data to write.

required
filepath str or Path

Destination file path. Must have a .bvh extension.

required
verbose bool

If True, print a one-line confirmation to stdout on success. Default False, so that preprocessing loops that write many files do not flood the terminal by default.

False
overwrite bool

If True (default), replace an existing file at filepath. Pass False to refuse instead: the call then raises FileExistsError. That is worth doing when the destination is hand-authored data rather than a regenerable output.

True

Raises:

Type Description
ValueError

If the file extension is not .bvh, or if bvh.frame_time is 0 (unset). A file must state its frame time, and :func:read_bvh_file refuses Frame Time: 0. Also if the clip's motion arrays disagree on frame count (the setters do not check it); the file is then left as it was.

FileNotFoundError

If the parent directory does not exist.

FileExistsError

If filepath exists and overwrite=False.

Notes

pybvh stores joint angles in radians, but the BVH format requires degrees. This function converts them on write.

Offsets and motion values are written with 6 decimal places. That is the de facto BVH convention (and what most DCC tools emit). So motion data re-read from a written file is quantized at ~1e-6, in the skeleton's length unit and in degrees.

Frame Time is the exception. It is written at 17 significant digits, with trailing zeros kept (f"{frame_time:#.17g}": 0.033333333333333333 for 30 fps, 0.12000000000000000 for 0.12 s). So the file holds the clip's frame time without loss. A truncated frame time compounds across every frame of a resample, but a truncated coordinate does not. The shortest text that reads back as the same float (Python's repr) is not enough, because :func:read_bvh_file takes a Frame Time with few decimals for an exporter's truncated rate. So 0.12 would read back as 1 / 8, and 0.033 as 1 / 30. The reader keeps a text of 17 significant digits as read. So every frame time that this function writes reads back as the same float.

The BVH format carries no place for world_up, lr_mapping, or source_path. Those are lost on write, and re-inferred on read. The root's channels, and a translating joint's, are always written position-first, as Xposition Yposition Zposition, then the rotation channels in the node's Euler order, whatever order the source file declared. So a write reorders a node whose file declared its position channels in another order, after its rotations or interleaved with them (:func:read_bvh_file reads all three).

read_bvh_directory(dirpath: str | Path, pattern: str = '*.bvh', sort: bool | str = True, parallel: bool = False, max_workers: int | None = None, world_up: str = 'auto', warn_on_world_up_disagreement: bool = True, lr_mapping: dict[str, str] | None = None, skip_errors: bool = False, body_anchor: str | None = None) -> list[Bvh]

Load all BVH files from a directory.

Parameters:

Name Type Description Default
dirpath str or Path

Directory to search for BVH files.

required
pattern str

Glob pattern to filter files (default "*.bvh").

'*.bvh'
sort bool or {'lexicographic', 'natural'}

File ordering. True (default) and "lexicographic" sort by full path string — the same order Python's sorted() over paths produces, so a list built elsewhere with sorted() (labels, split manifests) stays index-aligned; note it puts file10.bvh before file2.bvh. "natural" compares embedded digit runs numerically (file2 before file10, case-insensitive) — opt-in, because silently diverging from the ecosystem's lexicographic default would misalign such parallel lists. False keeps the filesystem's glob order (non-deterministic across platforms).

True
parallel bool

If True, read and parse the files in parallel using threads. Parsing is CPU-bound and GIL-limited, so this mainly helps on slow storage (network filesystems, cold disks); expect little speedup on a warm local disk. Each clip is then built on the calling thread, so its warnings (such as the world-up disagreement) name the line that called this function, as they do without parallel.

False
max_workers int or None

Maximum number of threads when parallel=True. None defers to the ThreadPoolExecutor default.

None
world_up str

World vertical axis applied to every loaded file. "auto" (default) auto-detects per file. Pass e.g. "+y" to override all files uniformly.

'auto'
warn_on_world_up_disagreement bool

Passed to :func:read_bvh_file for every file: False silences the rest-pose / first-frame disagreement warning on each clip, for its lifetime (see there).

True
lr_mapping dict or None

Explicit left/right joint pair mapping applied to every loaded file. Useful when a whole dataset shares an unusual naming convention the auto-detect heuristic can't parse.

None
skip_errors bool

If True, files that fail to load emit a UserWarning and are skipped. If False (default), the first failure propagates as the original exception. Use True when robustness against occasional corrupt files matters more than strict verification.

False
body_anchor str or None

The name of the joint the body's measures start from, set on every loaded file (see :func:read_bvh_file). A file that has no joint of that name, or more than one, fails to load, as skip_errors says.

None

Returns:

Type Description
list of Bvh

One Bvh object per successfully loaded file. Shorter than the set of matched files when skip_errors=True and some failed.

Raises:

Type Description
FileNotFoundError

If dirpath does not exist.

batch_to_numpy(bvh_list: list[Bvh], representation: str = 'euler', include_root_pos: bool = True, pad: bool = False, pad_value: float = 0.0, include_joint_translations: bool = False) -> npt.NDArray[np.float64] | list[npt.NDArray[np.float64]]

Convert a list of Bvh objects to NumPy arrays.

All Bvh objects must share the same skeleton hierarchy. For representations whose channel layout depends on the source Euler order ('euler', 'axisangle'), all clips must additionally share the same per-joint Euler orders. For rotation-invariant representations ('6d', 'quat', 'rotmat') the Euler-order check is skipped. With include_joint_translations=True all clips must also have the same translating joints, whatever the representation; with it off, which joints translate is not checked, because no column depends on it. The roots' position channels are never compared: a static root (CHANNELS 0) has the columns of a root with position channels.

Parameters:

Name Type Description Default
bvh_list list of Bvh

BVH objects to convert.

required
representation str

Rotation representation: 'euler' (default), '6d', 'quat', 'axisangle', or 'rotmat'.

'euler'
include_root_pos bool

If True (default), prepend root position (3 columns) to the rotation data.

True
pad bool

If True, zero-pad shorter sequences to the maximum length and return a single 3-D array (B, F_max, D). If False (default), return a list of 2-D arrays.

False
pad_value float

Value to use for padding (default 0.0).

0.0
include_joint_translations bool

If True, add the block of joint translations after the root position, as :func:~pybvh.features.to_feature_array does. Default False.

False

Returns:

Type Description
ndarray or list of ndarray

If pad=True: array of shape (B, F_max, D). If pad=False: list of arrays, each (F_i, D).

Raises:

Type Description
ValueError

If skeletons are incompatible or representation is unknown.

harmonize(clips: list[Bvh], *, reference: Bvh | None = None, target_fps: float | None = None, target_world_up: str | None = None, target_rest_up: str | None = None, target_rest_forward: str | None = None, target_euler_order: str | None = None, on_incompatible: Literal['drop', 'raise'] = 'drop', verbose: bool = True, return_report: bool = False) -> list[Bvh] | tuple[list[Bvh], HarmonizeReport]

Apply dataset-level harmonization to a list of clips.

For each clip, applies in order:

  1. Topology check vs reference (if provided). On mismatch, the clip is dropped or raises per on_incompatible.
  2. Bone-proportion retargeting to reference (if provided).
  3. Frame-rate resampling to target_fps (if provided and the clip does not already have that rate by :meth:Bvh.matches_rate's rule). A clip that has it is not interpolated; it takes the frame time 1 / target_fps exactly.
  4. World-up reorientation to target_world_up (if provided and bvh.world_up != target_world_up). Rotates the entire scene — affects offsets, root_pos, and the world_up flag.
  5. Rest-up reorientation to target_rest_up (if provided and bvh.rest_up != target_rest_up). Rotates only the rest-pose offsets and compensates joint rotations so FK positions are unchanged; the world frame is untouched.
  6. Rest-forward reorientation to target_rest_forward (if provided and bvh.rest_forward != target_rest_forward). Rotates rest-pose offsets around the vertical axis so the skeleton's rest-pose facing matches.
  7. Euler-order re-expression to target_euler_order (if provided and any per-joint Euler order differs). Re-expresses each joint's stored Euler angles in the target order while preserving the underlying rotations.

The ordering matters: world-up is "heaviest" (touches everything), rest-up modifies only rest-pose offsets (leaving world frame intact), and rest-forward is a further rotation of those same offsets about rest up, which is the target one by then. Euler-order re-expression runs last because it only rewrites channel layout, not geometry.

Any of the reference / target_* kwargs may be None to skip that stage. Passing all as None returns a shallow copy of clips (no-op).

Parameters:

Name Type Description Default
clips list of Bvh

Input clips.

required
reference Bvh or None

If provided, every clip must match reference.matches_hierarchy (same joints, same parent structure — rest offsets are allowed to differ since retargeting will overwrite them next). Kept clips are then retargeted to reference's bone offsets.

None
target_fps float or None

Target frame rate in Hz. Clips without this rate by :meth:Bvh.matches_rate's rule are resampled via quaternion SLERP. The others keep their samples. Every kept clip leaves with the frame time 1 / target_fps, the one bvh.fps = target_fps sets, so the results join.

None
target_world_up str or None

Signed-axis string ('+y', '-z', ...). Clips whose world_up differs are rotated via reorient_world_up.

None
target_rest_up str or None

Signed-axis string. Clips whose rest_up differs are corrected via reorient_rest_up. Typically used to fix files whose rest pose and animation disagree on the up axis.

None
target_rest_forward str or None

Signed-axis string. Clips whose rest_forward differs are rotated via reorient_rest_forward so the rest pose faces a consistent direction across the dataset.

None
target_euler_order str or None

Three-character order like 'XYZ' / 'ZYX'. When set, clips with any joint whose Euler order differs are re-expressed in the target order via :meth:Bvh.change_euler_order. A static root (CHANNELS 0) declares no rotation channel: it keeps none, and its order does not count as a difference. This is orientation-preserving: underlying rotations are unchanged; only the channel layout is rewritten. Numerical drift can occur on gimbal-lock-adjacent rotations — for bit-exact round-trips across the conversion, prefer rotation-invariant representations ('6d' / 'quat') downstream.

None
on_incompatible ('drop', 'raise')

Behavior on topology mismatch with reference. "drop" (default) skips the clip; "raise" raises ValueError at the first mismatch.

"drop"
verbose bool

If True (default), emit a single UserWarning at end of call when one or more clips were dropped, summarizing how many were dropped and identifying the first few. Set to False to silence the summary entirely.

True
return_report bool

If True, return (clips, report) where report is a :class:HarmonizeReport describing every stage applied to every kept clip plus per-clip drop reasons. Default False keeps the return type as a plain list[Bvh].

False

Returns:

Type Description
list of Bvh, or (list of Bvh, HarmonizeReport)

Harmonized clips (and optional report). The list may be shorter than clips if any were dropped.

Raises:

Type Description
ValueError

If on_incompatible is not one of the accepted values, if on_incompatible='raise' and a clip mismatches reference, if target_fps is not a positive finite number, or if target_fps is given and a clip's frame_time is 0 (unset).

df_to_bvh(hier: Sequence[BvhNode] | Sequence[Mapping[str, Any]], df: pd.DataFrame) -> Bvh

Create a Bvh object from a skeleton and a motion DataFrame.

Build a complete BVH representation by combining a skeleton with per-frame motion data stored in a pandas DataFrame. The skeleton decides the node order of the resulting Bvh; the DataFrame's motion columns are matched to it by name.

Parameters:

Name Type Description Default
hier list of dict or list of BvhNode

The skeleton, supplied as either:

  • A node table, as :meth:Bvh.to_node_table returns: one dict per node in depth-first order with name, parent (the index of the parent's entry, None on the root), offset, rot_channels on the root and joints and pos_channels on the root and translating joints; an entry without rot_channels is an end site. :func:~pybvh.nodes_from_table defines the format, its two leniencies and what it rejects.
  • A node list of BvhRoot, BvhJoint and BvhEndSite objects in depth-first order, such as :attr:Bvh.nodes. It is taken over as :class:Bvh takes the nodes it is given: the clip holds those node objects and freezes them, so a node edited afterwards raises; nodes another clip owns are frozen already and are shared. A call that raises leaves the list editable. Pass nodes_to_table(nodes) to keep it editable.

A table and a list are told apart by the type of the first element. A table is data: :func:~pybvh.nodes_from_table builds the clip's own nodes from it. Either raises ValueError when it is not one tree in depth-first order, a list's nodes wired both ways (each in its parent's children, with that parent as its parent). Channel orders come from the skeleton and are never inferred from df: a table entry states its rot_channels or it is an end site. The name-keyed hierarchy dict of earlier releases is refused with TypeError.

required
df DataFrame

Motion data in the form :meth:Bvh.to_df_dict gives with mode='euler': a time column, matched without regard to case (the first such column when several differ only by case), and the hierarchy's flat layout: per joint in node order, <joint>_<axis>_pos per position channel if the joint declares any (the root's are :attr:Bvh.root_pos, another joint's its column of :attr:Bvh.joint_translations), then <joint>_<axis>_rot per rotation channel, a repeated node name labelled .1, .2, ... as to_df_dict labels it. Which joints translate is read from hier, never guessed from the columns: a _pos column of a joint hier does not translate is ignored, and a static root (CHANNELS 0) has no columns; it is placed at its offset with no rotation. The labels expected are derived from hier, and the columns bind by name: their order in df is free, and columns outside the expected set are ignored. The _rot columns are in degrees (see Notes).

required

Returns:

Name Type Description
bvh Bvh

Fully constructed Bvh instance containing the hierarchy, root positions, joint translations, joint angles, and frame frequency derived from the time column.

Raises:

Type Description
TypeError

If hier is the name-keyed hierarchy dict of earlier releases, or neither a node table nor a node list.

ValueError

If hier is empty, or is not one tree in depth-first order (see :func:~pybvh.nodes_from_table for a table, :class:Bvh for a list); if df has no time column, lacks a column the hierarchy expects (the message lists every missing label and, when df has repeated labels, states how repeated node names are labelled) or lists an expected label more than once; if df has fewer than two rows, if the first and last values of its time column are equal (the message names the column), or if the frame time derived from it is not finite.

Notes

The DataFrame's _rot columns are in degrees — the human-readable convention used by :meth:Bvh.to_df_dict output. df_to_bvh converts them to the radians held on :attr:Bvh.joint_angles; feed this function degrees even though the rest of the pybvh API works in radians.

The frame time is the elapsed time of the time column divided by its number of intervals, so a first timestamp other than zero does not matter and uneven intervals are averaged rather than refused. A time column saved at a few decimals leaves that frame time a little off its clip's rate, so the rate is recovered by the rule :func:~pybvh.read_bvh_file applies to a truncated Frame Time (its Notes state it), with one difference: a table keeps no printed decimals, so the rate's frame time must lie within a relative 5e-7 of the measured one, in place of the values a file's printed decimals allow. A column saved at 6 decimals measures the frame time within 5e-7 when it spans two seconds or more, or one second when its first time is 0, as :meth:Bvh.to_df_dict writes it: only the last time then carries the rounding. A 30, 120 or 29.97 fps clip that long comes back at exactly 1 / 30, 1 / 120 or 1 / 29.97; a shorter one, or fewer decimals, may keep the measured value. NTSC's exact 1001 / 30000 is not the frame time of a rate with up to 3 decimals, so a clip at that frame time comes back from a table saved at 6 decimals at its measured frame time: when that long, within 5e-7 of 1001 / 30000, so never as 1 / 29.97, which is 1.000001e-6 from it. A clip that goes out through :meth:Bvh.to_df_dict and back therefore keeps its skeleton exactly, its motion within float precision, the degrees conversion being the one step applied to the angles, and its rate within 5e-7.

A time column of NaN on every row reads back as an unset clip (frame_time 0): it is what :meth:Bvh.to_df_dict gives a clip without a frame time. A column whose first and last values are equal is refused rather than read as unset, since it states times that do not move rather than no times.

Columns bind by label, not by position. The alternative, reading the motion columns in the order they come, would accept a frame whose columns are in the file's order under any labels, and would read a reordered or mislabelled one wrong without an error; by-label binding reads a reordered frame right and refuses a mislabelled one. The labels are those of :meth:Bvh.to_df_dict, which labels a repeated node name .1, .2, ... in node order, the first keeping its name, the way pandas.read_csv labels repeated headers; raising on a repeated name instead would refuse every hand whose two fingertips are end sites in coordinates mode. The suffix is counted over the nodes a mode exports, the joints here, so a joint that is X.1 in a coordinates export because an earlier end site shares its name is plain X in the euler frame this function reads. A coordinates export is one-way: positions do not determine the joint angles, and this function reads euler-mode frames only.

nodes_to_table(nodes: Sequence[BvhNode]) -> list[dict[str, Any]]

Export a node tree as a node table: one plain dict per node.

The node table is the skeleton as plain data, the named twin of :class:~pybvh.FkTopology: nodes in the order they are given (for :attr:Bvh.nodes, the depth-first order of the file), each node an entry whose parent is the index of its parent's entry. Position is identity. Names play no part in it, because BVH names are not unique: two end sites under one joint share their generated display name, and duplicate joint names occur in real files, so a name-keyed export (the {name: ...} hierarchy dict of earlier releases) loses nodes that this table keeps.

Each entry has these keys, in this order:

name The node's name, a str. For an end site, the display name ('EndSiteHips'), which is cosmetic. parent The index of the parent's entry in this table, None for the root (entry 0) and nowhere else. offset The rest offset from the parent, an ndarray of shape (3,) and a copy, as node.offset is everywhere in pybvh; a caller writing JSON calls .tolist(). pos_channels The position channels, ['X', 'Y', 'Z'], on the root and on a translating joint (a joint other than the root that declares position channels); [] on a static root (CHANNELS 0). Absent on a joint that only rotates and on an end site, so the table of a skeleton whose joints only rotate has it on the root alone. It precedes rot_channels as a file's CHANNELS line lists them. rot_channels The Euler order, e.g. ['Z', 'Y', 'X'], on the root and on joints only; [] on a static root. An entry without it is an end site; there is no kind flag. Channel orders are never inferred, so the rule is unambiguous.

The kinds of entry, read from their keys:

================== =================== ====================== Entry pos_channels rot_channels ================== =================== ====================== root ['X', 'Y', 'Z'] an order static root [] [] rotating joint absent an order translating joint ['X', 'Y', 'Z'] an order end site absent absent ================== =================== ======================

There is no children key: children are derived from parent, in table order, so the two cannot disagree. Entries are fresh objects, safe to mutate.

Relation to :class:~pybvh.FkTopology: offsets is the stacked offset values, parent_idx is parent with None read as -1, joint_idx counts up over the entries that have a rot_channels key (the root, a static root's [] included, and the joints) and euler_orders is those rot_channels joined, '' on a static root. The table adds the names and splits the root's channels; FkTopology stays an FK input bundle with no names.

Conventions, and the alternatives they were chosen over: the table is a list of dict, not a DataFrame and not a class, because a plain list has one index and position is the identity here, whereas a DataFrame has a label index and a positional one that sorting, filtering or concatenating pull apart, which makes an integer parent reference ambiguous between the two. The root's parent is None rather than FkTopology's -1, because -1 is a valid Python index (the last entry): None cannot index anything by accident, and the conversion to parent_idx is one expression.

This function exports what it is given and validates nothing: a node list that is not in depth-first order gives a table that is not either, which :func:nodes_from_table then rejects.

Parameters:

Name Type Description Default
nodes sequence of BvhNode

A node tree, every parent listed before its children, such as :attr:Bvh.nodes.

required

Returns:

Type Description
list of dict

One entry per node, in nodes order.

Raises:

Type Description
ValueError

If a node's parent is not in nodes.

See Also

nodes_from_table : The inverse, and the validation of the format. FkTopology.from_nodes : The same positions, as arrays for FK.

Examples:

The rig of one joint carrying two end sites, which no name-keyed export can hold, built here from a table by the inverse:

>>> nodes = nodes_from_table([
...     {'name': 'Hips', 'parent': None, 'offset': [0, 0, 0],
...      'rot_channels': 'ZYX'},
...     {'name': 'Hand', 'parent': 0, 'offset': [0, 1, 0],
...      'rot_channels': 'ZYX'},
...     {'parent': 1, 'offset': [1, 0, 0]},
...     {'parent': 1, 'offset': [0, 0, 2]},
... ])
>>> nodes_to_table(nodes)
[{'name': 'Hips', 'parent': None, 'offset': array([0., 0., 0.]),
  'pos_channels': ['X', 'Y', 'Z'], 'rot_channels': ['Z', 'Y', 'X']},
 {'name': 'Hand', 'parent': 0, 'offset': array([0., 1., 0.]),
  'rot_channels': ['Z', 'Y', 'X']},
 {'name': 'EndSiteHand', 'parent': 1, 'offset': array([1., 0., 0.])},
 {'name': 'EndSiteHand', 'parent': 1, 'offset': array([0., 0., 2.])}]

nodes_from_table(table: Sequence[Mapping[str, Any]]) -> list[BvhNode]

Build a node tree from a node table, wired and checked.

The inverse of :func:nodes_to_table, and the way to build a skeleton from plain data without wiring parents and children by hand. It returns fresh :class:BvhRoot, :class:BvhJoint and :class:BvhEndSite objects, one per entry in table order, with parent and children wired from the indices, so the two cannot disagree, and it validates the table as it builds (see Raises).

The format is the one :func:nodes_to_table writes, one dict per node with name, parent (the index of the parent's entry, None on the root), offset (three numbers), rot_channels (root and joints) and pos_channels (the root and translating joints; :func:nodes_to_table gives the kinds of entry). An entry without rot_channels is an end site; there is no kind flag and no children key. Position is identity, so names need not be unique: two end sites under one joint, or two joints named alike, come back as they were. The relation to :class:~pybvh.FkTopology is the one :func:nodes_to_table describes: parent with None as -1 is parent_idx, and the entries with a rot_channels key (a static root's [] included) are the joint columns, in order.

The table must be in depth-first order: entry 0 is the root and every joint is followed by its whole subtree, the order a .bvh file writes. The order is required, not repaired: joint_angles columns follow the node order, and :func:~pybvh.io.write_bvh_file writes the depth-first order of children, so a breadth-first table silently reordered to depth-first would move the columns away from the joints they describe, and left as it is would write a file whose channel order disagrees with the motion it carries. A table out of order raises instead, naming the entry.

Two leniencies, so a table can be written by hand: a root entry without pos_channels gets ['X', 'Y', 'Z'], and an end-site entry without name gets 'EndSite' + parent name, the parser's own rule. The root entry may also omit parent, whose only value is None. Nothing else is inferred.

Parameters:

Name Type Description Default
table sequence of dict

One entry per node, in depth-first order.

required

Returns:

Type Description
list of BvhNode

Fresh nodes in table order, parent and children wired.

Raises:

Type Description
ValueError

Naming the entry's index and name, when:

  • entry 0 has a parent, or any other entry has parent set to None (exactly one root, at index 0);
  • parent is not an int in [0, i) (parents precede their children; no self or forward reference);
  • the parent entry is an end site (end sites are leaves);
  • the depth-first walk of the tree from entry 0 does not visit the entries as 0, 1, ..., N-1;
  • offset is missing or not three numbers, or a channel list is not a permutation of 'XYZ' (None included: the node constructors would default it, this function infers nothing);
  • pos_channels is not ['X', 'Y', 'Z'] in that order, or [] on the root;
  • the root has one of pos_channels and rot_channels empty and not the other ([] and [] is a static root, and rot_channels: [] with pos_channels absent is refused: the static root is spelt explicitly);
  • pos_channels sits on an end site, or is [] on a joint (a joint that only rotates omits the key: one spelling per state);
  • an entry has a key the format does not define (a misspelt rot_channels would otherwise silently turn a joint into an end site).
See Also

nodes_to_table : The inverse, and the format in full. FkTopology : The same positions as arrays, without names.

Examples:

>>> nodes = nodes_from_table([
...     {'name': 'Hips', 'parent': None, 'offset': [0, 0, 0],
...      'rot_channels': 'ZYX'},
...     {'name': 'Hand', 'parent': 0, 'offset': [0, 1, 0],
...      'rot_channels': 'ZYX'},
...     {'parent': 1, 'offset': [1, 0, 0]},
...     {'parent': 1, 'offset': [0, 0, 2]},
... ])
>>> [node.name for node in nodes]
['Hips', 'Hand', 'EndSiteHand', 'EndSiteHand']

frames_to_node_positions(skeleton: Bvh | list[BvhNode] | tuple[BvhNode, ...] | FkTopology, root_pos: npt.ArrayLike | None = None, joint_angles: npt.ArrayLike | None = None, centered: str = 'world', world_up: str | None = None, joint_translations: npt.ArrayLike | None = None) -> npt.NDArray[np.float64]

Return spatial coordinates of all nodes for one or multiple frames.

Parameters:

Name Type Description Default
skeleton Bvh or list or tuple of BvhNode or FkTopology

The skeleton to pose. Pass an :class:FkTopology to run forward kinematics from arrays alone, with no node objects — see :attr:Bvh.fk_topology for producing one.

Renamed from nodes_container in 0.8.2, when the array form was added and the old name stopped being true.

required
root_pos (ndarray, shape(F, 3) or (3,))

Root position per frame. If None, extracted from skeleton (which must then be a Bvh object).

None
joint_angles (ndarray, shape(F, J, 3) or (J, 3))

Euler angles in radians per joint per frame (pybvh's internal convention; matches :attr:Bvh.joint_angles). If None, extracted from skeleton. A non-Euler stream converts first — see :mod:pybvh.rotations.

None
centered str

"world" – root at its actual position. "anchor" – the centre node at origin in every frame. "first_ground" – ground-plane centering: the first frame's centre node position is subtracted in the two axes other than world_up only, so the motion starts above the origin at its original height. Given one frame, it is the first frame: this function sees no other. For that frame's row of the whole clip, call :meth:Bvh.node_positions with frame=. "anchor_ground" – each frame's centre node position is subtracted in the two axes other than world_up only, so the travel is removed and the height kept. The centre node is the :attr:~pybvh.bvh.Bvh.body_anchor of a skeleton given as a Bvh, and the root of a node list or an :class:FkTopology, which carry no L/R mapping to find a body from (see :meth:Bvh.node_positions).

'world'
world_up str or None

Signed world-up axis string (e.g. '+y') — only read by centered="first_ground" and "anchor_ground", to decide which coordinate is left untouched. Defaults to the skeleton's own world_up when skeleton is a :class:~pybvh.Bvh. There is no default for the other two input forms: a node list and an FkTopology carry no gravity direction, and guessing one silently mis-centers every skeleton that does not happen to match the guess.

None
joint_translations (ndarray, shape(F, P, 3) or (P, 3))

Per frame, the position of each translating joint relative to its parent, in its parent's frame (matches :attr:Bvh.joint_translations). Required when the skeleton has a translating joint and the motion is passed; extracted from skeleton with the rest of the motion when root_pos and joint_angles are. May be omitted on a skeleton with no translating joint (P = 0).

None

Returns:

Type Description
(ndarray, shape(F, N, 3) or (N, 3))

Spatial coordinates for all nodes (including end sites). Returns 2-D (N, 3) when a single frame is provided, 3-D (F, N, 3) otherwise.

Raises:

Type Description
ValueError

If centered is not one of the four modes; if root_pos / joint_angles are omitted for a skeleton that carries no motion; if they disagree on frame count or on the joint count the skeleton declares; if joint_translations is omitted on a skeleton with a translating joint, or does not fit its translating joints or frame count; or if centered="first_ground" or "anchor_ground" is requested without a world_up and the skeleton cannot supply one.

Notes

Nodes are placed parents first. A node's position is its parent's accumulated rotation applied to its offset, plus its parent's position, P = R_acc[parent] @ offset + P[parent]; a joint then accumulates its own rotation onto its parent's, R_acc = R_acc[parent] @ R, where R is the matrix of its Euler angles, intrinsic and pre-multiplied in the joint's channel order (see :mod:pybvh.rotations). An end site has no rotation and takes the first step only. A translating joint takes its row of joint_translations in place of its offset in the first step: its position channels are its whole position relative to its parent, and its offset is the rest pose only (ADR 0010).

The recurrence starts from the root at the origin, with its own rotation as R_acc; its offset is not added, its position channels being its position. Centering then translates every node of a frame alike: by that frame's root_pos under "world", by root_pos less the first frame's ground-plane position under "first_ground", by root_pos less its own ground-plane position under "anchor_ground", and not at all under "anchor". On a Bvh whose body anchor is not its root, "anchor" then subtracts each frame's anchor position, "first_ground" subtracts the first frame's anchor ground-plane position from the world positions in place of the root's, and "anchor_ground" each frame's. A reader that adds the root's offset to root_pos instead places every node off by that offset, which differs only for a file whose root offset is not zero.

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 reference.

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 s (nan if target is all-zero — or, with centered=True, constant, since a centered constant array is all-zero).

Notes

Source: Troje 2002 (pose normalization); Umeyama 1991 for the centered convention.