Bvh Class¶
Bvh(nodes: list[BvhNode] | tuple[BvhNode, ...] | None = None, root_pos: npt.ArrayLike | None = None, joint_angles: npt.ArrayLike | None = None, frame_time: float = 0, world_up: str = 'auto', lr_mapping: dict[str, str] | None = None, source_path: str | None = None, warn_on_world_up_disagreement: bool = True, joint_translations: npt.ArrayLike | None = None, body_anchor: NodeSelector | None = None)
¶
Container for BVH motion-capture data.
The hierarchy is stored as a tuple of BvhNode objects (one per
joint / end-site). Motion data is stored as three arrays:
root_pos: shape(F, 3)— root translation per framejoint_angles: shape(F, J, 3)— Euler angles in radians per joint per framejoint_translations: shape(F, P, 3)— per frame, the position relative to its parent of each joint other than the root that declares position channels (P = 0 on most skeletons)
Bvh is a sequence of frames: len(bvh) == frame_count and
bvh[i] returns frame i as a one-frame Bvh. For joint or node
counts, use bvh.joint_count or len(bvh.node_index).
Attributes:
| Name | Type | Description |
|---|---|---|
nodes |
tuple of BvhNode
|
Skeleton hierarchy in depth-first order, as a file lists it.
The constructor takes a list or a tuple and keeps a tuple of its
own, so a later edit to the list it was given leaves the clip as
it was.
The constructor checks that the tree is wired both ways: the
depth-first walk of |
root |
BvhRoot
|
The root node ( |
root_pos |
(ndarray, shape(F, 3))
|
Root position per frame. |
joint_angles |
(ndarray, shape(F, J, 3))
|
Euler angles in radians per joint per frame. (BVH files
store angles in degrees; the deg↔rad conversion happens at the
I/O boundary in :func: |
joint_translations |
(ndarray, shape(F, P, 3))
|
Per frame, the position relative to its parent of each
translating joint (see :attr: |
frame_time |
float
|
Duration of one frame in seconds. |
frame_count |
int
|
Number of frames (read-only). |
node_index |
dict
|
Mapping from node name to its index in |
joint_index |
dict
|
Mapping from joint name to its index in |
joint_names |
list of str
|
Names of non-end-site joints in topological order (read-only). |
joint_count |
int
|
Number of non-end-site joints (read-only). |
source_path |
str or None
|
Path of the file this Bvh was read from, or |
Construction & I/O¶
Create a Bvh from a file, a DataFrame, or another instance. Write it back losslessly.
from_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
classmethod
¶
Read a Bvh from a .bvh file — the constructor counterpart of :meth:write.
Delegates to :func:pybvh.io.read_bvh_file; see it for parameter
details.
from_df(hier: Sequence[BvhNode] | Sequence[Mapping[str, Any]], df) -> Bvh
classmethod
¶
Build a Bvh from a skeleton and a motion DataFrame.
The constructor counterpart of :meth:to_node_table and
:meth:to_df_dict: hier is a node table, or a node list such
as :attr:nodes, and df holds euler-mode frames. A table is
data, so the clip builds nodes of its own from it; a node list is
taken over as the constructor takes one: the clip owns and
freezes those nodes, and nodes another clip owns are shared.
Delegates to :func:pybvh.df_to_bvh; see it for the two forms of
hier, the expected column naming and what raises.
write(filepath: str | Path, verbose: bool = False, overwrite: bool = True) -> None
¶
Write the Bvh object to a .bvh file.
Pass overwrite=False to raise FileExistsError rather than
replace an existing file. See :func:pybvh.io.write_bvh_file.
copy(nodes: Sequence[BvhNode] | Sequence[Mapping[str, Any]] | None = None) -> Bvh
¶
Return an independent copy, on this skeleton or on an edited one.
The node hierarchy, root_pos, joint_angles and
joint_translations, frame_time, source_path, a manual
world_up, the warn preference, a user-set L/R mapping and a
set :attr:body_anchor are copied. Editing either
clip afterwards, its arrays or its nodes, never affects the other.
A guessed world up is inherited (see :attr:world_up). Values the
clip computes from these (forward-kinematics positions, the floor
height) are not copied: the copy computes them again on first
read.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nodes
|
list of dict or sequence of BvhNode
|
A skeleton for the copy, the way to change a clip's frozen
skeleton: |
None
|
Returns:
| Type | Description |
|---|---|
Bvh
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If |
Examples:
Data, metadata & skeleton introspection¶
The raw motion arrays, the joint hierarchy, and the two index spaces (see the Core Concepts guide).
nodes: tuple[BvhNode, ...]
property
¶
Skeleton hierarchy, one node per joint and end site.
In depth-first order as the file lists it: nodes[0] is the
:class:~pybvh.bvhnode.BvhRoot, and end sites
(:class:~pybvh.bvhnode.BvhEndSite) are included. len(nodes)
is therefore the node count N that indexes
:meth:node_positions (shape (F, N, 3)), not the joint count
J that indexes :attr:joint_angles; :attr:node_index and
:attr:joint_index map names to each.
The clip owns these nodes and has frozen them: assigning a
node's name, offset, parent, children or channels
raises AttributeError, and nodes itself cannot be
assigned, nor edited in place, being a tuple (list(bvh.nodes)
gives a list). Change the skeleton through the methods that edit it
(:meth:scale, :meth:retarget, :meth:extract_joints,
:meth:change_euler_order), or edit it as a table and copy the
clip onto it: table = bvh.to_node_table(), edit the rows, then
bvh.copy(nodes=table) (see :meth:copy). The
methods swap in a new tuple of new nodes, even with
inplace=True, so a tuple or node taken before the call keeps
the old skeleton.
root: BvhRoot
property
¶
The root joint, nodes[0].
The node placed in the world frame: its translation per frame is
:attr:root_pos, and its rotation is joint 0 of
:attr:joint_angles. A translating joint also has position
channels, in its parent's frame (:attr:joint_translations); a
static root (CHANNELS 0) has none and stays at its offset.
Read-only: the root is whatever nodes starts with.
root_pos: npt.NDArray[np.float64]
property
writable
¶
Root translation per frame, shape (F, 3).
Returns a read-only view of the underlying array — call
bvh.root_pos.copy() if you need a writable array. To
replace the whole array, assign via the setter
(bvh.root_pos = new_arr); for in-place edits, copy → mutate
→ assign back.
On a static root (CHANNELS 0, see
:meth:~pybvh.bvhnode.BvhRoot.is_static) it holds the root's
offset in every frame, and the setter raises ValueError.
Its length is the clip's frame count. To change the frame count,
assign root_pos and :attr:joint_angles, and on a skeleton
with translating joints :attr:joint_translations too, each with
the same number of frames: the setters check no frame count, and
an operation on a clip whose arrays disagree raises
ValueError. On a skeleton with no translating joint,
:attr:joint_translations holds no value and takes the frame
count of root_pos.
joint_angles: npt.NDArray[np.float64]
property
writable
¶
Per-joint Euler angles, shape (F, J, 3) (radians).
Returns a read-only view of the underlying array — call
bvh.joint_angles.copy() if you need a writable array. To
replace the whole array, assign via the setter
(bvh.joint_angles = new_arr); for in-place edits, copy →
mutate → assign back.
Read-only view protects against the common footgun of
angles = b.joint_angles; angles -= angles.mean(axis=0)
silently corrupting the Bvh.
On a static root (CHANNELS 0, see
:meth:~pybvh.bvhnode.BvhRoot.is_static) the root's row is zero
in every frame, and the setter raises ValueError on an array
whose row 0 is not.
joint_translations: npt.NDArray[np.float64]
property
writable
¶
Per-frame positions of the translating joints, shape (F, P, 3).
A translating joint is a joint other than the root whose
CHANNELS line declares 3 position channels besides its 3
rotation channels (its pos_channels is ('X', 'Y', 'Z')).
Column p holds the p-th such joint in :attr:nodes order: its
position relative to its parent, in its parent's frame, as the
file's values (X Y Z), not the difference from its offset.
In each frame they replace the joint's offset, which is the
rest pose only (ADR 0010): a joint with OFFSET 0 10 0 and the
values 0 12 0 is 12 above its parent, not 22. P = 0 on a
skeleton whose joints other than the root only rotate.
Returns a read-only view of the underlying array, like
:attr:root_pos. To replace the whole array, assign via the
setter (bvh.joint_translations = new_arr); the shape must
fit the skeleton (ValueError otherwise), and the assignment
starts the world-up guess again, as for :attr:root_pos.
frame_count: int
property
¶
Number of frames (computed from root_pos).
frame_time: float
property
writable
¶
Seconds between successive frames.
0 means "unset": it is the constructor's default, and any
clip may carry it, with or without frames. Most operations that
need a rate raise ValueError on an unset clip, and so does
:func:~pybvh.io.write_bvh_file, since a file must state its
frame time; :meth:to_df_dict gives it NaN times. Assigning a
negative number, NaN or infinity raises ValueError.
A clip written by :func:~pybvh.io.write_bvh_file and read
back has the same frame time. A frame time read from another
writer's file may differ from its text, since
:func:~pybvh.io.read_bvh_file recovers a rate that the writer
truncated or rounded: 0.033333 reads as 1 / 30 and
0.033367 as 1 / 29.97. The Notes of
:func:~pybvh.io.read_bvh_file give the rule.
fps: float
property
writable
¶
Frames per second — convenience inverse of :attr:frame_time.
Returns 0.0 when frame_time == 0 (the "unset" sentinel)
rather than raising, mirroring the behaviour of :meth:__str__.
Assigning sets frame_time to 1 / fps, the value
:func:~pybvh.io.read_bvh_file gives a file whose rate it
recovers: after bvh.fps = 29.97, bvh.frame_time equals
the frame time read from Frame Time: 0.033367. The rate must
be a positive finite number, so 0, a negative rate, NaN and
infinity raise ValueError rather than mark the rate as unset.
Examples:
joint_names: list[str]
property
¶
Names of non-end-site joints in topological order.
Returns:
| Type | Description |
|---|---|
list of str
|
|
joint_count: int
property
¶
Number of non-end-site joints.
Returns:
| Type | Description |
|---|---|
int
|
|
euler_orders: list[str]
property
¶
Per-joint Euler rotation orders as strings.
Returns:
| Type | Description |
|---|---|
list of str
|
e.g. |
node_index: dict[str, int]
property
¶
Mapping from node name to its integer index in nodes.
Indexes the output of :meth:node_positions (shape
(F, N, 3)), which includes end sites. For indexing
:attr:joint_angles (shape (F, J, 3), excludes end sites),
use :attr:joint_index instead.
.. warning::
joint_index and node_index share keys for every
non-end-site joint but return different integers once
any end site has appeared earlier in the hierarchy. Indexing
joint_angles with node_index (or
:meth:node_positions with joint_index) produces
silently misaligned data — no shape mismatch, just the
wrong limb. Pick one consistently per array, or use
:meth:Bvh.index to make the intent explicit at the call
site.
Returns:
| Type | Description |
|---|---|
dict
|
|
joint_index: dict[str, int]
property
¶
Mapping from joint name to its integer index in joint_angles axis 1.
Excludes end sites. Use this instead of
bvh.joint_names.index(name) for joint-axis lookups.
.. warning::
joint_index and node_index share keys for every
non-end-site joint but return different integers once
any end site has appeared earlier in the hierarchy. Indexing
:meth:node_positions with joint_index (or
joint_angles with node_index) produces silently
misaligned data. Pick one consistently per array, or use
:meth:Bvh.index to make the intent explicit at the call
site.
Returns:
| Type | Description |
|---|---|
dict
|
|
index(node: NodeSelector, space: Literal['joint', 'node']) -> int
¶
The integer index of one node in the requested index space.
Unambiguous alternative to picking between :attr:joint_index
and :attr:node_index at the call site. Use space='joint'
when indexing :attr:joint_angles / :meth:joint_velocities /
:meth:joint_accelerations / :meth:joint_positions /
:meth:angular_velocities (any (F, J, ...) array). Use
space='node' when indexing :meth:node_positions /
:meth:node_velocities / :meth:node_accelerations (any
(F, N, ...) array).
This is the resolver of every parameter of Bvh, analysis
and features that selects a node (see
:data:~pybvh.NodeSelector). A BvhNode is found by identity
among :attr:nodes. A name must match exactly one node of the
requested space: :attr:node_index and :attr:joint_index keep
the last of the nodes that share a name, where this method raises
and asks for the node. A name that a joint and an end site share
therefore selects the joint with space='joint', and raises
with space='node'.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node
|
str or BvhNode
|
The node's name, or the node itself, one of :attr: |
required |
space
|
('joint', 'node')
|
Which index space to look up. |
'joint'
|
Returns:
| Type | Description |
|---|---|
int
|
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
NodeSelector: TypeAlias = str | BvhNode
module-attribute
¶
A node of a clip, selected by its name or given as the node itself.
Every parameter of :class:~pybvh.bvh.Bvh, :mod:pybvh.analysis and
:mod:pybvh.features that selects one node takes a NodeSelector, and one
that selects a set of nodes takes a sequence of them.
:meth:~pybvh.bvh.Bvh.index resolves it, the same way for every entry point:
- a :class:
BvhNodeis found by identity among the clip'snodes, so a node of another clip, or one taken before the clip's skeleton was replaced, is refused; - a name must match exactly one node of the index space the entry point works in. A name that two nodes share is refused, and the node itself selects either of them.
An integer is not a NodeSelector: it does not say whether it counts in
joint space or in node space. bvh.nodes[i] is node i. Integers stay in
the array-level functions (:func:pybvh.transforms.mirror_angles,
:mod:pybvh.geometry), where the array fixes the space. The name maps, an L/R
mapping, the name_mapping of :meth:~pybvh.bvh.Bvh.retarget and the
masses of :func:~pybvh.analysis.kinetic_energy given as a mapping, key
values by names: they are not selections.
joint_tips: dict[str, int | None]
property
¶
Mapping from joint name to its end-site node index, or None.
For every non-end-site joint (root included): the node-space index of the joint's end-site child — a row of :meth:node_positions output — or None for interior joints whose children are all joints. The tip is the bone's far end, so bvh.node_positions()[:, bvh.joint_tips["LeftFoot"]] is the toe-tip trajectory without knowing the end site's generated display name.
Resolution is identity-based on the node tree, never by name: end-site display names are cosmetic (the parser generates 'EndSite' + parent name) and may even collide with a real joint's name, which would make a name-keyed lookup through :attr:node_index silently pick the wrong node. A joint with several end-site children (nonstandard, but the parser accepts it) maps to the first one in file order.
Returns:
| Type | Description |
|---|---|
dict
|
|
See Also
node_index : Name → node index for every node (joints and end sites). nodes : The flat depth-first node list these indices point into.
edges: list[tuple[int, int]]
property
¶
Skeleton edge list as (child_idx, parent_idx) tuples.
Indices use joint_angles index space (non-end-site joints
only, matching joint_names order). The root joint has no
parent and produces no edge, so a skeleton with J joints
yields J - 1 edges.
Parents are resolved by node identity (via
:attr:fk_topology), never by name — see :attr:node_edges.
See Also
node_edges : Same list but in nodes index space (includes
end sites) — what graph models over the full visual skeleton
typically want.
node_edges: list[tuple[int, int]]
property
¶
Skeleton edge list as (child_idx, parent_idx) tuples in
nodes index space (includes end sites).
Parallels :attr:edges (joint-axis only); use node_edges
when the downstream graph treats end sites as real leaves
(visual skeleton, per-bone styling, GCN inputs over the full
topology). node_edges has one more edge per end site than
edges.
Parents are resolved by node identity (via
:attr:fk_topology), never by name. Node names are not unique in
general — the parser derives end-site display names from the
parent joint's name, so two end sites under one joint collide —
and a name-keyed lookup would silently emit an edge pointing at
the wrong parent, yielding a graph of the right length that
encodes the wrong skeleton.
fk_topology: FkTopology
property
¶
The skeleton as plain arrays — everything forward kinematics reads.
Bone offsets, parent indices, joint-column indices and Euler
orders, with no node objects: see :class:~pybvh.FkTopology.
Pass it to :func:~pybvh.frames_to_node_positions to run FK from
a preprocessed dataset, where the source .bvh is long closed.
It is also this class's single derivation of skeleton topology —
:attr:edges, :attr:node_edges and the bone list the
:mod:~pybvh.bvhplot backends draw are all views of its
parent_idx, so they cannot disagree with the geometry FK
produces.
Recomputed per access rather than cached: it is an O(N) walk over
a few dozen nodes, and a cache would need invalidating on every
operation that touches offsets or channel order (:meth:retarget,
:meth:scale, :meth:mirror, :meth:change_euler_order) for a
saving that does not show up in a profile.
Returns:
| Type | Description |
|---|---|
FkTopology
|
|
matches_hierarchy(other: Bvh, match_offsets: bool = True, atol: float = _OFFSET_ATOL) -> bool
¶
Whether self and other share the same skeleton hierarchy.
Hierarchy is defined as: same node names in topological order
(including end sites), each node of the same kind (a joint or an
end site), each node's parent the node at the same position (not
merely a node of the same name, since names may repeat), and —
when match_offsets=True (default) — same rest-pose offsets,
each component within the absolute atol. Motion data, Euler
rotation orders, and frame timing are NOT compared.
Use this when you need to know that two clips describe the same
skeleton in the same rest pose — e.g. before batching to a
rotation-invariant representation (6d / quat /
rotmat) whose channel layout doesn't depend on Euler order.
Pass match_offsets=False when the caller is about to overwrite
rest offsets anyway (e.g. retargeting): it loosens the check to
the skeleton graph alone — joint names and parent structure —
accepting two characters of different bone proportions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Bvh
|
The clip to compare against. Anything that is not a |
required |
match_offsets
|
bool
|
If True (default), require rest-pose offsets to agree within
|
True
|
atol
|
float
|
Absolute tolerance for each offset component, in the file's
length unit (default |
_OFFSET_ATOL
|
Returns:
| Type | Description |
|---|---|
bool
|
|
See Also
matches_channels : Compare per-joint position channels and Euler orders. matches_topology : Conjunction of hierarchy + channels.
matches_channels(other: Bvh) -> bool
¶
Whether self and other share the same channel layout.
Compares, joint by joint in node order, which joints declare
position channels (which joints translate) and each joint's
Euler rotation order. Only the declaration is compared, never the
values of :attr:joint_translations: a bone that stretches and
comes back still matches its own skeleton. This is a
serialization property:
clips with identical underlying rotations but different stored
Euler orders have different channel layouts.
Use this in addition to :meth:matches_hierarchy when batching
to a representation whose channel layout depends on the source
Euler order (euler / axisangle).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Bvh
|
The clip to compare against. Anything that is not a |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
See Also
matches_hierarchy : Compare joint hierarchy and rest offsets. matches_topology : Conjunction of hierarchy + channels.
matches_topology(other: Bvh) -> bool
¶
Whether self and other share both hierarchy and channel layout.
Convenience for matches_hierarchy(other) and matches_channels(other).
Two Bvhs that satisfy this predicate can be batched together for
any representation (euler, axisangle, 6d, quat,
rotmat) without conversion.
.. note::
Prior to 0.7.0, matches_topology checked only
joint_names and euler_orders — it did not catch
differences in parent structure or rest offsets. The current
definition is stricter: clips with identical names but
differing rest offsets no longer match.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Bvh
|
The clip to compare against. Anything that is not a |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
See Also
matches_hierarchy : The hierarchy half (joints, parents, offsets). matches_channels : The channel-layout half (per-joint position channels and Euler orders).
matches_rate(other: Bvh | float) -> bool
¶
Whether self has the same rate as other, a clip or a rate in fps.
The same rate means frame times within a relative 2e-6:
abs(a - b) <= 2e-6 * max(a, b), where a rate in fps stands
for the frame time 1 / fps that bvh.fps = fps sets. The
tolerance is relative because the error a computation or a saved
table leaves in a frame time scales with the frame time, so one
tolerance serves 24 fps and 1000 fps alike. 2e-6 lets a
29.97 fps file, read as 1 / 29.97, match an exact NTSC clip at
1001 / 30000, which differ by 1e-6 of the larger; it is still
far below the 1e-3 between 29.97 and 30 fps. So a clip at
frame_time = 0.013 matches b.resample(1 / 0.013), whose
frame time is 0.013000000000000001.
Two clips whose frame time is 0 (unset) have the same rate; an
unset clip has the rate of no set clip and of no fps. == on
two clips is exact, as it is for their arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Bvh or float
|
The clip, or the rate in frames per second, to compare against. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
See Also
matches_topology : Whether two clips share a skeleton.
Examples:
to_node_table() -> list[dict[str, Any]]
¶
Export the skeleton as a node table: one plain dict per node.
The skeleton as plain data, the counterpart of :meth:from_df's
hier argument as :meth:to_df_dict is of its df. One
entry per node in :attr:nodes order, each 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. Position is identity, so two end sites under one
joint and joints sharing a name are carried as they are, which
no name-keyed export can do. :func:~pybvh.nodes_to_table
defines the format and names its conventions;
:func:~pybvh.nodes_from_table builds a tree back from it.
The table is the named twin of :attr:fk_topology: parent
with None read as -1 is its parent_idx, the stacked
offset values are its offsets, and the entries with a
rot_channels key (a static root's [] included) are its
joint columns, in order.
Returns:
| Type | Description |
|---|---|
list of dict
|
One entry per node, in :attr: |
to_df_dict(mode: str = 'euler', centered: str = 'world') -> dict[str, npt.NDArray[np.float64]]
¶
Return a dict of arrays for pd.DataFrame(result).
Each key is a column name, each value a 1-D NumPy array of
length frame_count. The first column is time, each
frame's time in seconds (its index times :attr:frame_time).
On an unset clip (frame_time 0) every time is NaN, which
:meth:from_df reads back as an unset clip; zeros would read
back as a constant column, which it refuses, and raising would
refuse the motion of a clip that has no rate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
str
|
|
'euler'
|
centered
|
str
|
|
'world'
|
Returns:
| Type | Description |
|---|---|
dict
|
Column-name → 1-D array mapping, ready for |
Raises:
| Type | Description |
|---|---|
ValueError
|
If mode is not |
Notes
Node names are not unique in a BVH file: the two end sites of one
joint share their generated display name, and joints may repeat
a name. Columns are labelled the way pandas.read_csv labels
repeated headers: the first node of a name keeps it, each later
one gets .1, .2, ... before the axis and kind
(Arm_Z_rot, Arm.1_Z_rot; EndSiteHand_X,
EndSiteHand.1_X), counted up until the label is neither
another node's name nor a label already given. Blender's BVH
importer does the same with .001. The suffix
is a column label only: the node keeps its name, which
:meth:to_node_table and :attr:nodes carry and
:func:~pybvh.df_to_bvh reads the labels back from. The
alternative, raising on a repeated name, would refuse every hand
whose thumb tip and finger tip are both end sites in coordinates
mode; before v0.10.0 the later node's values silently replaced
the earlier one's under the earlier one's column. The suffix is
assigned over the nodes the mode exports, so a joint can be
X in euler mode and X.1 in coordinates mode when an
earlier end site shares its name.
Orientation & frames of reference¶
Up axis, facing direction, L/R pairs, and the reorientation family (see the World Up guide).
world_up: str
property
writable
¶
Gravity axis of the BVH coordinate system.
Returned as a signed axis string ('+y', '-z', etc.).
Constant per file. Guessed from the first animation frame's
direction from :attr:body_anchor to the head, with rest-pose
topology as fallback. On a clip with no body
(:attr:body_anchor None) the guess raises ValueError
until you set the axis or name the anchor.
Issues a UserWarning if the first frame and rest pose disagree,
unless the clip (or the clip it derives from) was loaded with
warn_on_world_up_disagreement=False, and one if nothing says
which way is up; each warning is given once per guess, on the
first read of the axis that guess gave (at load, for a clip read
from a file). :attr:orientation_report says which state below
the axis is in and what a guess was read from.
A clip's world up is in one of three states:
- Set: an axis you assigned, or passed as
world_up=at load, or the target of :meth:reorient_world_up. It is kept until you assign another, and every clip derived from this one keeps it set. :meth:reorient_world_upalso turns the guessed axis with the frames, so clearing its axis gives the one the rotated frames show. - Inferred: guessed from this clip's own first frame, for a
clip read from a file or built from arrays. It is guessed again
when you assign :attr:
root_pos, :attr:joint_angles, :attr:joint_translationsor frames (bvh[i] = other), the one change that replaces the recording, and never by an edit pybvh makes. Setting :attr:lr_mappingguesses it again too: on a rig with no head, neck, chest or spine joint the guess falls back to :attr:rest_up, which is read from the legs of the mapping, so the clip gets the axis that mapping passed at load gives. A guess from the first frame comes out the same, and does not warn again. Setting :attr:body_anchorguesses it again as well, since the guess measures from the anchor: the clip gets the axis thatbody_anchor=passed at load gives. - Inherited: a clip pybvh derives from this one reports the
axis guessed here, without guessing from its own frames:
copy(), slicing,a + banda += b(froma), :meth:resample, the transforms, :meth:retarget, :meth:extract_jointsand a pickle. Cutting, resampling or transforming a clip does not change which way is up, though a slice whose first frame is a crouch or a fall would be guessed differently on its own. Assigning motion to the derived clip guesses again, as for an inferred axis; setting :attr:lr_mappingor :attr:body_anchoron it does not.
:attr:world_up_inferred always guesses from this clip's own
motion: where it differs from world_up and you set no axis,
the axis was inherited.
The detection specifics, since they decide which answer you get:
"head" is the joint :attr:rest_up reads, the first in node
order whose name holds head as a word, else neck,
chest or spine, in any case and after a foo:
namespace or a .001 suffix (mixamorig:Head and Bip01
Head match, Forehead does not; end sites are not read),
skipping one that sits on :attr:body_anchor in the rest pose;
and the frame-0
reading is accepted only when its largest component is at least
twice the second-largest — a first frame bent or leaning far
from every axis is treated as ambiguous and defers to
:attr:rest_up, with a warning when the body anchor's rotation
at frame 0 carries :attr:rest_up onto another axis, since the
rest pose may then be authored in another convention than the
motion. A figure straight and horizontal at frame 0 with its
head near a horizontal axis (lying flat, a plank) does decide,
on that axis, with the disagreement warning when
:attr:rest_up names another axis; set the axis when the guess
is wrong. When the rest pose is
degenerate too, the property warns and returns
'+y'. Use
:attr:world_up_inferred to see what the heuristic picks
while an override is in effect.
Can be overridden manually via the setter when auto-detection produces the wrong answer (e.g. authored BVH files where the rest pose convention differs from the animation's world orientation):
>>> bvh = Bvh.from_file('bvh_data/bvh_test1.bvh')
>>> bvh.world_up = '+y'
Assign 'auto' or None to clear a previous override and
return to the guessed axis, inferred or inherited.
Note: BVH files do not store a world-up field, so manual overrides are lost on write→read round trips and must be re-applied.
world_up_inferred: str
property
¶
What the auto heuristic would pick, regardless of any override.
Useful for auditing whether a manual bvh.world_up = '+x'
override was necessary, or for diagnosing skeletons whose
animation and rest-pose conventions disagree. Always runs the
inference fresh on this clip's own motion, and neither reads nor
changes the axis :attr:world_up reports, so on a clip that
inherited its world up it shows what a guess of its own would
have been. Warns on a disagreement as :attr:world_up does, and
is silenced the same way (warn_on_world_up_disagreement=False
at load).
Compare against :attr:world_up to see whether an override, or
an inherited axis, is in effect:
>>> bvh = Bvh.from_file('bvh_data/bvh_test1.bvh')
>>> bvh.world_up = '+y' # a user override
>>> bvh.world_up_inferred # auto's guess
'+z'
>>> bvh.world_up
'+y'
world_up_axis: Axis
property
¶
:attr:world_up parsed into numeric form — Axis(index, sign, vector).
The three fields are the machine-usable views of the same signed axis string (always derived from the resolved :attr:world_up, so manual overrides are respected):
index(int): the up coordinate's column (0 = x, 1 = y, 2 = z) in any(..., 3)position array.sign(float):+1.0or-1.0— multiply the raw coordinate by it to get an up-positive height.vector(ndarray, shape(3,)): the unit vector along the up direction, sign included (e.g.[0, -1, 0]for'-y'). A fresh array on every access — mutating it never corrupts the Bvh.
Example — up-positive heights of every node in every frame:
>>> bvh = Bvh.from_file('bvh_data/bvh_test1.bvh')
>>> coords = bvh.node_positions()
>>> heights = coords[:, :, bvh.world_up_axis.index] * bvh.world_up_axis.sign
See Also
world_up : The signed axis string this is parsed from (settable). rest_forward_axis, rest_up_axis : The other two parsed axis properties. floor_height : The scene ground level along this axis, in raw (unsigned) coordinates.
Axis = namedtuple('Axis', ['index', 'sign', 'vector'])
module-attribute
¶
parse_axis(axis: str, *, allow_unsigned: bool = False) -> Axis
¶
Parse a signed axis string into an :class:Axis.
The public form of the parser behind :attr:Bvh.world_up_axis and friends,
for code that holds an axis string of its own — a dataset convention
from a config file, or one of the axis strings pybvh returns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
axis
|
str
|
Signed axis string: |
required |
allow_unsigned
|
bool
|
If True, also accept a bare letter ( |
False
|
Returns:
| Type | Description |
|---|---|
Axis
|
The parsed |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
orientation_report: OrientationReport
property
¶
Each orientation fact of the clip, and how it was obtained.
Whether :attr:rest_up, :attr:rest_forward and
:attr:world_up were set, measured or defaulted, and how, with
the rest pose's left and the source of the L/R mapping; see
:class:~pybvh.OrientationReport for each field. Those members
always answer, a default included, so their return value alone
cannot say which it was: this can.
Read without a warning: a warning about a default fires when the
defaulted fact itself is read (:attr:world_up, once per guess;
:attr:rest_forward; the facing), and each points here. Computed on first read and
kept until the skeleton changes, :attr:world_up or
:attr:lr_mapping or :attr:body_anchor is assigned, or the
motion is assigned
(:attr:root_pos, :attr:joint_angles, bvh[i] = other),
which guesses world up again.
Examples:
OrientationReport(rest_up: str | None, rest_up_source: _RestUpSource | None, rest_left: str | None, rest_forward: str | None, rest_forward_source: _RestForwardSource | None, world_up: str | None, world_up_source: _WorldUpSource | None, world_up_inherited: bool, lr_mapping_source: _LrMappingSource | None, body_anchor: BvhNode | None, body_anchor_source: _BodyAnchorSource, body_anchor_candidates: tuple[BvhNode, ...])
dataclass
¶
How each orientation fact of a clip was obtained.
Returned by :attr:Bvh.orientation_report <pybvh.bvh.Bvh.orientation_report>.
rest_up, rest_forward and world_up are the values the
members of the same names return; each *_source says whether the
value was set, measured or defaulted, and how, so a default never
passes for a measurement (rest_forward and world_up always
answer, whatever the clip carries, on a clip with a body). Frozen: a
clip's report is replaced, never edited, when what it was read from
changes.
On a clip with no body (body_anchor None) the facts read from
the body are None, with their sources: rest_up, rest_left,
rest_forward and a guessed world_up. The members of the same
names raise there; the report does not. A world_up set or
inherited is reported as on any clip.
The facts belong to two frames (ADR 0004). The skeleton's own
frame is read from the rest pose alone, the skeleton with every
rotation zero, and never from world up: rest_up, rest_left,
rest_forward. The world frame is read from the motion:
world_up. The world rotation of the body anchor at a frame is
what carries a skeleton fact into the world. Per-frame facts (the facing at a
frame) are not here: :meth:~pybvh.bvh.Bvh.forward_at,
:meth:~pybvh.bvh.Bvh.left_at and
:meth:~pybvh.bvh.Bvh.facing_frame carry them, with
FacingFrame.valid as the per-frame mark.
Attributes:
| Name | Type | Description |
|---|---|---|
rest_up |
str or None
|
The skeleton's own up, a signed axis string, |
rest_up_source |
{'named_joint', 'leg_pair', 'largest_spread'} or None
|
|
rest_left |
str or None
|
The skeleton's own left: the left-minus-right rest positions of
the L/R pairs, averaged, with the |
rest_forward |
str or None
|
The direction the rest pose faces in the skeleton's own frame;
|
rest_forward_source |
{'lr_geometry', 'default'} or None
|
|
world_up |
str or None
|
The world's vertical, a signed axis string; |
world_up_source |
{'set', 'first_frame', 'rest_up', 'default'} or None
|
|
world_up_inherited |
bool
|
True when the guess was made on the clip this one was derived
from (a slice, a copy, a transformed clip, a pickle) and taken
over as it was: |
lr_mapping_source |
{'set', 'names'} or None
|
Where the L/R mapping the rest left is read from comes from:
|
body_anchor |
BvhNode or None
|
The joint the body's measures start from, a node of the clip:
what :attr: |
body_anchor_source |
{'set', 'lr_pairs', 'default', 'ambiguous'}
|
|
body_anchor_candidates |
tuple of BvhNode
|
The joints that competed for the anchor, the most joints below
them first: the meeting joints the rule compared, the anchor alone
when the pairs meet at one joint closest to the root. Under a
static root, when the trees below it give no body, the candidate
of each tree with at least half the joints of the largest, the
largest tree first; when the largest tree is kept, the meeting
joints compared inside it. Empty for |
body_anchor: BvhNode | None
property
writable
¶
The joint the body's measures start from, a node of the clip,
or None when the clip has no body.
The joint you set (see Setting it below), else the one a rule
finds from the hierarchy and the L/R pairs of
:attr:lr_mapping: each pair meets at the lowest joint that both
its joints' chains to the root pass through, and the anchor is
the meeting joint closest to the root. The legs meet at the hips,
the arms lower, at the chest, so on most rigs the anchor is the
hips, also when the root is a reference node above them or has a
helper beside them. Of several meeting joints at the same depth,
the one with the most joints below it, end sites not counted,
when each other one has fewer than half as many. Otherwise the
clip has no body, for instance two figures under one root, and
the anchor is None; reading it does not raise. Under a static
root (CHANNELS 0), each child of the root heads a tree, and
the trees are compared first, by the same half rule: a second
tree with at least half the joints of the largest gives no body,
and otherwise only the pairs inside the largest tree are read. Without a pair, the root. The rest positions and the motion are not read.
:attr:orientation_report says how it was found, in
body_anchor_source, and which joints were compared, in
body_anchor_candidates.
The rule's anchor is found on first read and kept until the
skeleton changes or :attr:lr_mapping is assigned. A clip derived
from this one finds its own.
Setting it. Where you know better than the rule, assign a
joint: its name or the node itself, one of :attr:nodes, resolved
as :meth:index resolves one with space='joint'. Pass
body_anchor= to :func:~pybvh.read_bvh_file to set it at
load, by name. The joint you set is the anchor, and
:attr:orientation_report gives the source "set" and no
candidate. Assign None to return to the rule, as
world_up = None returns to the guess. Setting it, or returning
to the rule, clears the values computed from the anchor (the
report, the world up this clip guessed and the floor height),
which are computed again on first read; a world up set or
inherited stays (see :attr:world_up).
A set anchor is one of your settings, as a set :attr:lr_mapping
is (ADR 0003). Assigning the motion or :attr:lr_mapping, and
pybvh's own edits of the skeleton (:meth:scale,
:meth:reorient_rest_up, ...), keep it. Every clip derived from
this one carries it: a slice, :meth:copy, a concatenation,
:meth:resample, a transformed clip, and a pickle. copy(nodes=)
carries it to the joint at the same position, under its new name;
a copy that changes the joint count, which only a clip without
motion allows, drops it. :meth:extract_joints
carries it when the joint is kept. A derived clip that no longer
holds the joint drops the setting and uses the rule.
A clip with no body. When the anchor is None, every
body-level operation raises ValueError, naming the candidates
and the way out, bvh.body_anchor = ... (the node,
bvh.nodes[i], when the candidates share a name with another
joint): the world-up guess,
:attr:rest_up, :attr:rest_forward and
:attr:has_lr_geometry, the facing (:meth:forward_at,
:meth:left_at, :meth:facing_frame), :meth:root_trajectory,
the centered="anchor", "first_ground" and
"anchor_ground" modes,
:meth:auto_detect_feet, :meth:foot_contacts,
:meth:ground_contacts, :meth:skeleton_size, the gait
descriptors and :meth:mirror. The operations that treat all nodes alike work as on any clip:
reading, writing, forward kinematics, the derivatives, slicing,
concatenation, :meth:resample, the Euler orders,
:meth:scale, :meth:extract_joints and the bounding volumes.
The scene ground (:attr:floor_height) and drawing read world
up, whose guess is body-level: they work once :attr:world_up
is set or the anchor named. Reading the anchor,
:attr:orientation_report and :attr:lr_mapping never raises.
Raises:
| Type | Description |
|---|---|
TypeError
|
On assignment, if the value is neither a name, a |
ValueError
|
On assignment, if the node is not one of :attr: |
Examples:
>>> bvh = Bvh.from_file('bvh_data/synthetic/reference_humanoid_6ch.bvh')
>>> bvh.root.name, bvh.body_anchor.name
('Reference', 'Hips')
>>> bvh.body_anchor = 'Chest'
>>> bvh.orientation_report.body_anchor_source
'set'
>>> bvh.body_anchor = None
>>> bvh.body_anchor.name, bvh.orientation_report.body_anchor_source
('Hips', 'lr_pairs')
rest_up: str | None
property
¶
The skeleton's own up axis, read from the rest pose alone.
Read-only. The main axis from :attr:body_anchor to the first
joint of the body, in node order, whose name holds head as a
word, else neck, chest or spine, in any case and
after a foo: namespace or a .001 suffix: Head,
mixamorig:Head, Bip01 Head and CC_Base_Head are
heads, Forehead is not. A joint that sits on the anchor is
skipped, and end sites, whose names are generated, are not read.
The body is the anchor and every node below it; when no joint
below the anchor has one of these names, it starts at the
closest joint above the anchor that has one below it, so a prop
or a helper beside the body is never the head joint.
Without such a joint, the axis opposite the legs: the first pair
of :attr:lr_pairs that meets at the anchor, split across two of
its branches, read from the anchor to the far ends of those
branches. Without such a pair either, the axis along which the
rest pose spreads most, a weak reading: a T-pose wider than tall
spreads most along its arms. :attr:orientation_report says
which, in rest_up_source. The animation is never read.
:attr:world_up's guess reads the same joint.
Contrast with :attr:world_up, which is animation-derived
(inferred from the first frame's anchor-to-head direction). On
clean files the two agree; when they disagree, the BVH was
authored with the rest pose in one convention and animated in
another, and :meth:reorient_rest_up can fix it in place.
Returns:
| Type | Description |
|---|---|
str or None
|
Signed axis string (e.g. |
rest_up_axis: Axis | None
property
¶
:attr:rest_up parsed into numeric form — Axis(index, sign, vector), or None.
None exactly when :attr:rest_up is None — a degenerate rest pose (single-node skeleton, or all joints coincident) that carries no directional information. Each parsed axis property mirrors the nullability of the string it parses, so bvh.rest_up is None and bvh.rest_up_axis is None always agree.
Note this is the skeleton's own up axis, read from the rest pose alone. For the world vertical — animation-derived, and always defined — use :attr:world_up_axis.
See Also
rest_up : The signed axis string this is parsed from. world_up_axis, rest_forward_axis : The other two parsed axis properties.
rest_forward: str
property
¶
The direction the rest pose faces, in the skeleton's own frame.
Read-only. rest left × rest up, where rest left is the rest
pose's L/R geometry (the pairs of :attr:lr_mapping whose two
joints are in the body, as :attr:rest_up reads it) measured
against :attr:rest_up. Read from the rest pose alone, like
:attr:rest_up: never from :attr:world_up or the animation.
The rest pose is the skeleton with every rotation zero, so this
is a direction in the skeleton's frame, not in the world; the
world rotation of :attr:body_anchor at a frame carries it into
the world, which is
what the heading of :func:~pybvh.analysis.root_trajectory
reads. On a clean file, where rest up is world up, it is also
what :meth:forward_at measures on the rest pose's own
positions. On a file whose rest pose is authored in another
convention than its motion it may lie along world up:
bvh_test3.bvh (world up '+z', rest up '+y') faces
'+z'.
Without usable L/R geometry (no pairs, or pairs that lie along
rest up) it is a house default for rest up, arbitrary but
stable, and reading it warns; :attr:orientation_report
(rest_forward_source) and :attr:has_lr_geometry tell the
two apart.
Use this to check whether a skeleton's rest-pose facing matches
a dataset convention without having to call
:func:reorient_rest_forward and compare results.
Returns:
| Type | Description |
|---|---|
str
|
Signed axis string (e.g. |
rest_forward_axis: Axis
property
¶
:attr:rest_forward parsed into numeric form — Axis(index, sign, vector).
Never None: :attr:rest_forward always resolves, because it falls back to an arbitrary-but-stable axis perpendicular to :attr:rest_up when the skeleton carries no usable L/R geometry. That fallback is indistinguishable here from a measured result; :attr:orientation_report (rest_forward_source) and :attr:has_lr_geometry tell them apart.
See Also
rest_forward : The signed axis string this is parsed from. world_up_axis, rest_up_axis : The other two parsed axis properties.
floor_height: float
property
¶
Scene ground height, in raw world coordinates along world_up.
A single scalar: where this clip's ground is, in the BVH's own
coordinate system, signed along the raw up axis (so for
world_up='-y' a floor at raw y≈5 returns ≈5). This is the
height to draw a ground plane at.
Convention: the 2nd percentile of the per-frame minimum height over all nodes, end sites included. Two choices are being made there, and both have alternatives:
- All nodes, not the feet. The ground is where the clip's geometry bottoms out, whichever body part gets there — a hand in floor work, a hip in a fall, a toe tip in ordinary walking. Estimating from auto-detected feet instead (what this property did before v0.9.0) reads systematically high: a toe end site hangs below the toe joint on most rigs, and over 406 sampled clips the feet-only estimate sat a median 1% of the clip span (max 6.6%) above this one, never below.
- 2nd percentile, not the true minimum. Robust to occasional
glitched-low frames, at the cost of letting a genuinely low frame dip
slightly below the returned level. For the exact minimum use
coords[..., up].min(), orfoot_contacts(floor="min")for that function's own reference; this property stays 2nd-percentile.
A persistently misplaced node — one that sits below the ground in most frames, not just a few — will drag this down; the percentile absorbs transient glitches, not systematic ones. Contact detection does not move with it: the detectors measure against a reference of their own.
This is not the reference :func:~pybvh.analysis.foot_contacts
compares foot clearance against. That one is estimated per call, over
the nodes being tested, and is reported as the contact_reference
of its :class:~pybvh.ContactReport (return_info=True). The two
answer different questions — this one belongs to the clip, that one to
the query — and they differ by roughly a toe length on any rig with toe
end sites. Passing this value in as foot_contacts(floor=...) will
make every foot read as airborne.
Computed on first read and kept until the skeleton, the motion or
:attr:world_up changes; assigning :attr:world_up measures it
again along the new axis. The contact detectors never compute or
read it.
forward_at(frame: int = 0) -> str
¶
Character's world-space forward (facing) direction at a given frame.
Computed from actual joint positions at the given frame — the
leftward axis is derived by averaging (left − right) across
the L/R joint pairs of the body in world space, then crossed with
world_up to produce the forward direction (forward =
leftward × up). This tracks the character's actual facing as
they rotate through the animation.
This is the snapped classification — the continuous facing
vector is quantized to the nearest of the six signed world
axes. See :meth:facing_frame for the continuous per-frame
basis as unit vectors, and for the fallback when the frame's
left/right axis cannot be read (the body's heading at that
frame, then a house default, which warns).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
int
|
Frame index (default 0). Must be within the animation range. |
0
|
Returns:
| Type | Description |
|---|---|
str
|
Signed axis string (e.g. |
See Also
facing_frame : The continuous per-frame basis (vectors, all frames at once). left_at : Leftward direction.
left_at(frame: int = 0) -> str
¶
Character's world-space leftward direction at a given frame.
Returns the signed axis along which a positive step moves from
the character's right side toward their left side (e.g.
right-shoulder → left-shoulder direction). Follows the
right-hand-rule convention leftward = world_up × forward so
the triple (world_up, :meth:forward_at, left_at) forms
a consistent orthonormal frame in every axis convention pybvh
supports.
Computed from joint positions at the given frame, so it tracks hip twist and shoulder rotation as the character moves.
This is the snapped classification — see :meth:facing_frame
for the continuous per-frame basis as unit vectors, and its
fallback. The label is world_up × forward_at(frame), so it is
never world up itself, even on a frame whose left/right axis is
vertical.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
int
|
Frame index (default 0). Must be within the animation range. |
0
|
Returns:
| Type | Description |
|---|---|
str
|
Signed axis string (e.g. |
See Also
forward_at : Facing direction. facing_frame : The continuous per-frame basis (vectors, all frames at once). world_up : World vertical axis.
facing_frame()
¶
Per-frame facing basis as continuous unit vectors.
Returns a FacingFrame(forward, left, up, valid) named tuple:
three (F, 3) arrays — the yaw-only, gravity-aligned
orthonormal basis that :meth:forward_at / :meth:left_at
snap to axis labels — plus a (F,) bool array, False on
frames whose basis is the constant fallback rather than a
measurement. See :func:pybvh.analysis.facing_frame for the
full construction, conventions, and fallback policy.
lr_mapping: dict[str, str] | None
property
writable
¶
Left/right joint pair mapping for this skeleton (bidirectional).
A dict describing the skeleton's bilateral symmetry pairs.
None if no pairs could be auto-detected and no explicit
mapping was provided.
The dict is symmetric: both directions of each pair are
present, so mapping['LeftArm'] == 'RightArm' AND
mapping['RightArm'] == 'LeftArm'. Useful for mirroring-based
data augmentation, where a lookup can come from either side.
Detection, run on first use, pairs two joints whose names differ only by their side, in one of these conventions, tried in this order:
- a delimited suffix:
arm.L,arm_r,arm.Left,arm_right; - the word
Left/Rightanywhere, in any case:LeftArm,leftArm,LeftEye; L/Rbefore an uppercase letter:LArm;l,r,leftorrightin any case, as a word of its own between.,_or spaces:b_l_upleg,L_legUpper0001_bind_JNT,Bip01 L Thigh;左/右as the first character:左足;l/rbefore an uppercase letter:lThigh;l/rwith no delimiter:lfemur.
A name is paired by the first convention that pairs it, and only
when its partner is also a joint: a joint with no partner stays
unpaired. A Mixamo mixamorig: namespace and a numbered
.001 duplicate suffix are set aside before the match. Two
conventions are read narrowly, so that a name that only looks like
a side is not paired: 左 / 右 count as the first character
only, and the last convention counts only when it gives two pairs
or more on the skeleton, since one pair such as light /
right can differ by its first letter by chance. Skeletons with
conventions the heuristic can't parse have lr_mapping = None —
in that case, set it explicitly:
>>> bvh = Bvh.from_file('bvh_data/bvh_test1.bvh')
>>> bvh.lr_mapping = {'LeftArm': 'RightArm', 'LeftUpLeg': 'RightUpLeg'}
The assigned dict is one-directional; pybvh symmetrizes it internally. Either form works on assignment.
or pass lr_mapping= at load time:
>>> bvh = Bvh.from_file('bvh_data/bvh_test1.bvh', lr_mapping={'LeftArm': 'RightArm'})
Consumers: mirror(), orientation_report (and so
rest_forward and has_lr_geometry),
forward_at(), left_at(), facing_frame(). On a rig with
no head, neck, chest or spine joint, rest_up is read from the
legs of the mapping, and so is the world up guessed from it: setting
the mapping guesses the clip's own :attr:world_up again, and its
:attr:floor_height with it, as passing it at load would have. A
world up set, or inherited from the clip this one was derived from,
stays (see :attr:world_up).
Note: BVH files don't store L/R pair info, so user-set mappings
are lost on bvh.write() round-trips — same wart as
world_up. Re-apply after reading.
lr_pairs: list[tuple[int, int]] | None
property
¶
Left/right joint pairs as index tuples in joint_angles space.
Index-space counterpart of :attr:lr_mapping: one
(left, right) tuple per pair, in mapping order, resolved as
:func:~pybvh.transforms.mirror resolves its pairs. Returns
None when no mapping is available (matches the
lr_mapping sentinel — one "no pairs" convention across both
surfaces); bvh.lr_pairs or [] gives a list either way.
Useful for graph construction and array-level ops that index
joints by position rather than by name, such as
:func:~pybvh.transforms.mirror_angles.
node_lr_pairs: list[tuple[int, int]] | None
property
¶
Left/right node pairs as index tuples in nodes index space.
Node-space counterpart of :attr:lr_pairs, covering joints and
their end sites — so a mirror over :meth:node_positions output
can swap every paired vertex, including the fingertips, toe tips
and head top that only exist in node space. None when no L/R
mapping is available, the same sentinel as :attr:lr_pairs and
:attr:lr_mapping.
Order is deterministic: every joint pair in :attr:lr_mapping
order first, then the end-site pairs in that same order, so
metadata built from it reproduces across runs.
Left and right joints are matched by name (that is what
:attr:lr_mapping is), but looked up among joints only, so an
end site whose generated display name collides with a joint's
cannot shadow it. The end sites themselves are matched
positionally within each joint and resolved by identity.
A joint pair whose two sides carry different numbers of end
sites has no well-defined tip correspondence. The pair itself is
still returned and its end sites are dropped, matching
:attr:lr_pairs' habit of filtering what it cannot resolve rather
than raising from a property. :func:~pybvh.transforms.mirror
raises on the same condition instead, because a half-swapped
skeleton is a wrong answer rather than a partial one.
Returns:
| Type | Description |
|---|---|
list of (int, int) or None
|
|
See Also
lr_pairs : The same pairing in joint_angles index space.
joint_tips : Each joint's first end site, for tip trajectories.
has_lr_geometry: bool
property
¶
Whether the rest pose carries usable left/right direction.
True when the skeleton's L/R joint pairs give a lateral axis
in the rest pose that does not lie along :attr:rest_up, i.e.
when :attr:rest_forward is measured from this skeleton
rather than a house default: orientation_report.rest_forward_source
== "lr_geometry". It is False exactly when reading
:attr:rest_forward emits the fallback UserWarning.
Like :attr:rest_forward, it reads the rest pose alone, never
:attr:world_up.
This is the check :attr:rest_forward (and so
:attr:rest_forward_axis) cannot express in its own return
value: with no usable L/R geometry it returns an
arbitrary-but-stable axis chosen from :attr:rest_up alone,
which is indistinguishable from a measured result. When it
matters whether a facing was derived from the data — comparing
a skeleton against a dataset convention, say, where a fallback
would "match" every time — check this first.
Assigning :attr:lr_mapping explicitly is what fixes a False
on a skeleton whose joints simply are not named recognizably.
This property describes the rest pose. The per-frame
:meth:forward_at / :meth:facing_frame measure each frame's
coordinates first and fall back only on frames where that
fails, so on a skeleton with zero rest offsets but animated L/R
separation they can still measure while this reports False.
Examples:
>>> bvh = Bvh.from_file('bvh_data/bvh_test1.bvh')
>>> dataset_convention = '+y' # the rest facing the dataset assumes
>>> if bvh.has_lr_geometry:
... assert bvh.rest_forward == dataset_convention
... else:
... ... # facing is a default, not a measurement
See Also
rest_forward : The axis whose fallback this reports. lr_mapping : The pairs the measurement is derived from.
reorient_world_up(new_up: str, inplace: bool = False) -> Bvh | None
¶
Change the world coordinate system's up axis. See :func:pybvh.transforms.reorient_world_up.
reorient_rest_up(new_up: str, inplace: bool = False) -> Bvh | None
¶
Reorient rest-pose up axis without changing FK positions. See :func:pybvh.transforms.reorient_rest_up.
reorient_rest_forward(new_forward: str, inplace: bool = False) -> Bvh | None
¶
Reorient rest-pose forward direction without changing FK positions. See :func:pybvh.transforms.reorient_rest_forward.
Forward kinematics¶
From joint angles to 3D positions. The Gallery draws the centered modes.
node_positions(frame: int | None = None, centered: str = 'world') -> npt.NDArray[np.float64]
¶
Per-node 3D positions (joints + end sites) — shape (F, N, 3).
Returns an ndarray of shape (N, 3) for a single frame or
(F, N, 3) for all frames, where N is the total number of
nodes (joints + end sites). Use :attr:node_index to look up
rows by name.
For the joint-axis subset (excluding end sites) that aligns with
:attr:joint_angles and :meth:joint_velocities, use
:meth:joint_positions instead.
World-frame forward kinematics is cached across calls (invalidated
whenever motion data changes), so repeated calls — including with
different centered modes — only pay for FK once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
int or None
|
Frame index to return. |
None
|
centered
|
str
|
The three centred modes read the body anchor, which is the
root on a clip whose anchor is its root. On a root that
stays in place with the body below it (a static root,
With frame given, every mode gives that frame's row of the
whole clip: |
'world'
|
joint_positions(frame: int | None = None, centered: str = 'world') -> npt.NDArray[np.float64]
¶
Per-joint 3D positions (end sites excluded) — shape (F, J, 3).
Joint-axis subset of :meth:node_positions. Index-aligns with
:attr:joint_angles and :meth:joint_velocities — use
:attr:joint_index to look up rows by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
int or None
|
Frame index to return. |
None
|
centered
|
str
|
See :meth: |
'world'
|
rest_pose_positions() -> npt.NDArray[np.float64]
¶
Rest-pose node positions (all angles zero, root at origin) — (N, 3).
Derived from the skeleton offsets alone, so it works on Bvh objects
with no motion data. Use :attr:node_index to look up rows by name.
Computed once per skeleton; each call returns a new array, so writing into it leaves the clip unchanged.
rest_pose_angles() -> npt.NDArray[np.float64]
¶
Rest-pose joint angles — zeros of shape (J, 3) (radians).
Companion of :meth:rest_pose_positions in joint_angles space
(one single-frame row, matching :attr:joint_index).
Rotation representations¶
Conversions to and from every representation (see Choosing a Representation).
to_rotmat() -> npt.NDArray[np.float64]
¶
Convert the per-joint Euler angles to rotation matrices.
Returns:
| Name | Type | Description |
|---|---|---|
joint_rotmats |
(ndarray, shape(num_frames, num_joints, 3, 3))
|
Rotation matrix for each joint in each frame.
Joint order matches |
Notes
The conversions carry rotations only: :attr:root_pos and
:attr:joint_translations are read from the clip as they are.
When multiple rotation representations are needed (e.g. 6D for
the model and quaternions for runtime SLERP), call to_rotmat
once and apply the relevant rotations.rotmat_to_* primitives
directly — the Euler conversion runs once instead of per
representation.
to_6d() -> npt.NDArray[np.float64]
¶
Convert the per-joint Euler angles to the 6D rotation representation.
The 6D representation (Zhou et al., CVPR 2019) is continuous and well-suited for neural network training.
Returns:
| Name | Type | Description |
|---|---|---|
joint_rot6d |
(ndarray, shape(num_frames, num_joints, 6))
|
6D rotation for each joint in each frame. |
Notes
When multiple representations are needed, call :meth:to_rotmat
once and apply :func:pybvh.rotations.rotmat_to_rot6d /
rotmat_to_quat / rotmat_to_axisangle directly to avoid
running the Euler conversion more than once.
to_quat() -> npt.NDArray[np.float64]
¶
Convert the per-joint Euler angles to quaternions.
Returns:
| Name | Type | Description |
|---|---|---|
joint_quats |
(ndarray, shape(num_frames, num_joints, 4))
|
Quaternion (w, x, y, z) for each joint in each frame, in
canonical form ( |
Notes
The canonical form is applied per frame, so the returned
sequence is not guaranteed to be temporally continuous: a joint
rotating through 180° flips sign between adjacent frames even
though the motion is smooth. Every quaternion is still exactly
the right rotation; it is the representation that jumps. Wrap
with :func:pybvh.rotations.quat_unwrap when feeding the array
to anything that differences or measures distance on the raw
values.
See :meth:to_rotmat for the multi-representation reuse pattern.
to_axisangle() -> npt.NDArray[np.float64]
¶
Convert the per-joint Euler angles to axis-angle vectors.
The axis-angle representation is the unit rotation axis scaled by the rotation angle in radians. Used in SMPL/SMPL-X body models and many pose estimation pipelines.
Returns:
| Name | Type | Description |
|---|---|---|
joint_aa |
(ndarray, shape(num_frames, num_joints, 3))
|
Axis-angle vector for each joint in each frame. |
Notes
See :meth:to_rotmat for the multi-representation reuse pattern.
from_rotmat(joint_rotmats: npt.ArrayLike, inplace: bool = False) -> Bvh | None
¶
Set the joint rotations from rotation matrices.
Converts rotation matrices to Euler angles in each joint's
rot_channels order and writes :attr:joint_angles. Inverse of
:meth:to_rotmat. :attr:root_pos and :attr:joint_translations
stay as they are; to replace them too, assign them, or build a new
clip with the :class:Bvh constructor. Like an assignment of
:attr:joint_angles, the call starts the world-up guess again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
joint_rotmats
|
(array_like, shape(num_frames, num_joints, 3, 3))
|
Rotation matrix per joint per frame. The frame count must be
the clip's. Joint order must match |
required |
inplace
|
bool
|
If True, modify self and return None. If False, return a modified copy while leaving self unchanged. |
False
|
Returns:
| Type | Description |
|---|---|
None or Bvh
|
None if inplace, otherwise a new Bvh object. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If the frame or joint count does not match the clip, or if
the rotations turn a static root ( |
from_6d(joint_rot6d: npt.ArrayLike, inplace: bool = False) -> Bvh | None
¶
Set the joint rotations from 6D rotation data.
Converts 6D rotations to Euler angles in each joint's
rot_channels order and writes :attr:joint_angles. Inverse of
:meth:to_6d. :attr:root_pos and :attr:joint_translations
stay as they are; to replace them too, assign them, or build a new
clip with the :class:Bvh constructor. Like an assignment of
:attr:joint_angles, the call starts the world-up guess again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
joint_rot6d
|
(array_like, shape(num_frames, num_joints, 6))
|
6D rotation per joint per frame. The frame count must be the
clip's. Joint order must match |
required |
inplace
|
bool
|
If True, modify self and return None. If False, return a modified copy while leaving self unchanged. |
False
|
Returns:
| Type | Description |
|---|---|
None or Bvh
|
None if inplace, otherwise a new Bvh object. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If the frame or joint count does not match the clip, or if
the rotations turn a static root ( |
from_quat(joint_quats: npt.ArrayLike, inplace: bool = False) -> Bvh | None
¶
Set the joint rotations from quaternions.
Converts quaternions to Euler angles in each joint's
rot_channels order and writes :attr:joint_angles. Inverse of
:meth:to_quat. :attr:root_pos and :attr:joint_translations
stay as they are; to replace them too, assign them, or build a new
clip with the :class:Bvh constructor. Like an assignment of
:attr:joint_angles, the call starts the world-up guess again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
joint_quats
|
(array_like, shape(num_frames, num_joints, 4))
|
Quaternion (w, x, y, z) per joint per frame. The frame count
must be the clip's. Joint order must match
|
required |
inplace
|
bool
|
If True, modify self and return None. If False, return a modified copy while leaving self unchanged. |
False
|
Returns:
| Type | Description |
|---|---|
None or Bvh
|
None if inplace, otherwise a new Bvh object. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If the frame or joint count does not match the clip, or if
the rotations turn a static root ( |
from_axisangle(joint_aa: npt.ArrayLike, inplace: bool = False) -> Bvh | None
¶
Set the joint rotations from axis-angle vectors.
Converts axis-angle vectors to Euler angles in each joint's
rot_channels order and writes :attr:joint_angles. Inverse of
:meth:to_axisangle. :attr:root_pos and
:attr:joint_translations stay as they are; to replace them too,
assign them, or build a new clip with the :class:Bvh
constructor. Like an assignment of :attr:joint_angles, the call
starts the world-up guess again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
joint_aa
|
(array_like, shape(num_frames, num_joints, 3))
|
Axis-angle vector per joint per frame. The frame count must be
the clip's. Joint order must match |
required |
inplace
|
bool
|
If True, modify self and return None. If False, return a modified copy while leaving self unchanged. |
False
|
Returns:
| Type | Description |
|---|---|
None or Bvh
|
None if inplace, otherwise a new Bvh object. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If the frame or joint count does not match the clip, or if
the rotations turn a static root ( |
change_euler_order(order: str | Sequence[str], joint: NodeSelector | None = None, inplace: bool = False) -> Bvh | None
¶
Change the Euler angle order of one or all joints.
Converts rotation data via rotation matrices so the resulting Euler angles use the new order but represent the same physical rotations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
order
|
str or list of 3 chars
|
New rotation order, e.g. 'XYZ' or ['X', 'Y', 'Z']. |
required |
joint
|
str, BvhNode, or None
|
The one joint to change, by its name or as the node itself (see
:meth: |
None
|
inplace
|
bool
|
If True, modify self and return None.
If False, return a modified copy while leaving self unchanged.
With True, the skeleton is replaced, not edited: a node taken from
|
False
|
Returns:
| Type | Description |
|---|---|
None or Bvh
|
None if inplace, otherwise a new Bvh object. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If :meth: |
Frame & skeleton operations¶
Timeline and skeleton editing (see the Skeleton Operations guide). Slicing and concatenation use plain Python syntax:
bvh[10:50]returns the frame range as a newBvh.bvh_a + bvh_bconcatenates two clips with matching skeletons.
resample(target_fps: float) -> Bvh
¶
Resample frames to a new frame rate via interpolation.
Root position is linearly interpolated. Joint rotations are converted to quaternions and interpolated with SLERP for smooth, gimbal-lock-free results. This is the rotation-aware alternative to naive per-channel linear interpolation on Euler angles, which produces wobble and gimbal-lock artifacts.
The new timestamps are 0, 1/fps, 2/fps, … up to the original
clip's duration — anchored at t = 0, and the last sample is
the largest multiple of the new period that still fits. The
original final frame is reproduced only when the duration is an
exact multiple of that period; otherwise the clip is shortened
by up to one new frame period. The alternative convention —
stretch the grid to land exactly on the final frame, giving
round(duration · fps) + 1 samples and an irregular last
interval — keeps the endpoint at the cost of an inexact rate.
A clip that already has the rate, by :meth:matches_rate's rule,
is not interpolated: the result keeps its samples and takes
1 / target_fps, the
frame time bvh.fps = target_fps sets. So does a clip shorter
than two frames, which has nothing to interpolate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_fps
|
float
|
Target frames per second. |
required |
Returns:
| Type | Description |
|---|---|
Bvh
|
New Bvh with resampled frames. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
extract_joints(joints: Sequence[NodeSelector]) -> Bvh
¶
Extract a subset of joints into a new Bvh.
Removed joints' offsets are collapsed into their nearest kept descendant via vector addition (valid at rest pose). Their rotation contribution during animation is lost.
A kept joint keeps its position channels. A removed translating
joint's translation is summed into its nearest kept descendant,
per frame, in place of its offset, and that descendant becomes a
translating joint (see :attr:joint_translations); a removed
joint that does not translate adds its offset to every frame of a
translating descendant. So a kept joint's FK position is the
source's whenever the removed joints above it do not rotate. An
end site added below a childless kept joint reads the rest
offsets of the removed joints between them.
The result lists its nodes in depth-first order, as a file
would, so writing it and reading it back keeps
:meth:matches_hierarchy. A kept joint left with nothing below
it (no kept descendant, no end site of its own) gets an end site
named 'EndSite' + name, placed right after it, at the offset
of its nearest original end-site descendant (zero when it has
none).
source_path, a manual world_up override, and a user-set
lr_mapping (filtered to pairs whose joints are both kept) and a
set :attr:body_anchor whose joint is kept are preserved on the
result; a set anchor whose joint is removed is dropped, and the
result uses the rule. A guessed world up is inherited, not
guessed again from the kept joints (see :attr:world_up).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
joints
|
sequence of str or BvhNode
|
The joints to keep, each by its name or as the node itself
(see :meth: |
required |
Returns:
| Type | Description |
|---|---|
Bvh
|
New Bvh with the reduced skeleton and corresponding motion data. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If the root is not among |
retarget(new_skeleton: Bvh, name_mapping: dict[str, str] | None = None, strict: bool = False, inplace: bool = False) -> Bvh | None
¶
Copy joint offsets from a reference skeleton.
A translating joint keeps its displacement from its rest pose: its
joint_translations move by the change of its offset,
pos + (new_offset - old_offset) in every frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
new_skeleton
|
Bvh
|
Reference skeleton whose offsets will be copied. |
required |
name_mapping
|
dict
|
Maps self's joint names to |
None
|
strict
|
bool
|
If True, raise |
False
|
inplace
|
bool
|
If True, modify self and return None.
If False (default), return a modified copy.
With True, the skeleton is replaced, not edited: a node taken from
|
False
|
Returns:
| Type | Description |
|---|---|
None or Bvh
|
The result keeps this clip's world up, set or guessed: a new
skeleton does not change which way is up, so it is not guessed
again from the new offsets (see :attr: |
scale(scale: float, inplace: bool = False) -> Bvh | None
¶
Uniformly scale all node offsets, the root translation and the joint translations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scale
|
float
|
Uniform scale factor. Only scalars are accepted: per-axis world factors applied to parent-local offsets are not geometrically meaningful once joints rotate during animation. |
required |
inplace
|
bool
|
If True, modify self and return None.
If False (default), return a modified copy.
With True, the skeleton is replaced, not edited: a node taken from
|
False
|
Returns:
| Type | Description |
|---|---|
None or Bvh
|
|
Kinematics, trajectory & contacts¶
The velocity ladder, the root-trajectory features, and foot-contact detection (see the Feature Export guide).
joint_velocities(centered: str = 'world', in_frames: bool = False, stencil: str = 'central', pad: str = 'edge') -> npt.NDArray[np.float64]
¶
Per-joint position velocities — shape (F, J, 3). See :func:pybvh.analysis.joint_velocities.
node_velocities(centered: str = 'world', in_frames: bool = False, stencil: str = 'central', pad: str = 'edge') -> npt.NDArray[np.float64]
¶
Per-node position velocities (joints + end sites) — shape (F, N, 3). See :func:pybvh.analysis.node_velocities.
joint_accelerations(centered: str = 'world', in_frames: bool = False, stencil: str = 'central', pad: str = 'edge') -> npt.NDArray[np.float64]
¶
Per-joint position accelerations — shape (F, J, 3). See :func:pybvh.analysis.joint_accelerations.
node_accelerations(centered: str = 'world', in_frames: bool = False, stencil: str = 'central', pad: str = 'edge') -> npt.NDArray[np.float64]
¶
Per-node position accelerations (joints + end sites) — shape (F, N, 3). See :func:pybvh.analysis.node_accelerations.
joint_speed_derivative(centered: str = 'world', in_frames: bool = False, stencil: str = 'central', pad: str = 'edge') -> npt.NDArray[np.float64]
¶
Per-joint rate of change of speed d‖v‖/dt — shape (F, J). See :func:pybvh.analysis.joint_speed_derivative.
node_speed_derivative(centered: str = 'world', in_frames: bool = False, stencil: str = 'central', pad: str = 'edge') -> npt.NDArray[np.float64]
¶
Per-node rate of change of speed d‖v‖/dt (joints + end sites) — shape (F, N). See :func:pybvh.analysis.node_speed_derivative.
angular_velocities(in_frames: bool = False, stencil: str = 'central', pad: str = 'edge', degrees: bool = False) -> npt.NDArray[np.float64]
¶
Compute per-joint angular velocities. See :func:pybvh.analysis.angular_velocities.
root_trajectory(world_up: str | None = None, include_velocities: bool = False, stencil: str = 'central', pad: str = 'edge', degrees: bool = False) -> npt.NDArray[np.float64]
¶
Extract root trajectory features. See :func:pybvh.analysis.root_trajectory.
foot_contacts(feet: Sequence[NodeSelector] | None = None, method: str = 'combined', *, vel_threshold: float | Sequence[float] | npt.NDArray[np.float64] | None = None, vel_smooth_duration: float | None = None, height_threshold: float | Sequence[float] | npt.NDArray[np.float64] | None = None, floor: float | str | None = None, min_contact_duration: float = 0.1, min_gap_duration: float = 0.1, hysteresis: float = 0.25, adaptive: bool = False, height_reference: str | None = None, return_info: bool = False) -> npt.NDArray[np.float64] | tuple[npt.NDArray[np.float64], ContactReport]
¶
Detect foot contact labels. See :func:pybvh.analysis.foot_contacts.
ground_contacts(nodes: Sequence[NodeSelector], method: str = 'combined', *, vel_threshold: float | Sequence[float] | npt.NDArray[np.float64] | None = None, vel_smooth_duration: float | None = None, height_threshold: float | Sequence[float] | npt.NDArray[np.float64] | None = None, floor: float | str | None = None, min_contact_duration: float = 0.1, min_gap_duration: float = 0.1, hysteresis: float = 0.25, adaptive: bool = False, height_reference: str | None = None, return_info: bool = False) -> npt.NDArray[np.float64] | tuple[npt.NDArray[np.float64], ContactReport]
¶
Detect ground contacts for an arbitrary node set. See :func:pybvh.analysis.ground_contacts.
auto_detect_feet() -> list[BvhNode]
¶
Auto-detect the clip's feet, as nodes, from skeleton topology. See :func:pybvh.analysis.auto_detect_feet.
Feature export¶
The one-stop flat (F, D) array for ML pipelines.
to_feature_array(representation: str = '6d', include_root_pos: bool = True, include_velocities: bool = False, include_foot_contacts: bool = False, centered: str = 'world', feet: Sequence[NodeSelector] | None = None, stencil: str = 'central', pad: str = 'edge', include_joint_translations: bool = False) -> npt.NDArray[np.float64]
¶
Export motion as a flat feature array. See :func:pybvh.features.to_feature_array.
feature_array_layout(*, num_feet: int = 0, representation: str = '6d', include_root_pos: bool = True, include_joint_translations: bool = False, include_velocities: bool = False, include_foot_contacts: bool = False) -> dict[str, slice]
¶
Column layout of :meth:to_feature_array output. See :func:pybvh.features.feature_array_layout.
Trajectory & pose geometry¶
Position descriptors. The Gallery draws each one. Their array-pure kernels are in pybvh.geometry.
curvature(node: NodeSelector, stencil: str = 'central', pad: str = 'edge') -> npt.NDArray[np.float64]
¶
Per-frame trajectory curvature of node. See :func:pybvh.geometry.curvature.
torsion(node: NodeSelector, stencil: str = 'central', pad: str = 'edge') -> npt.NDArray[np.float64]
¶
Per-frame trajectory torsion of node. See :func:pybvh.geometry.torsion.
movement_phase(node: NodeSelector, stencil: str = 'central', pad: str = 'edge') -> npt.NDArray[np.float64]
¶
Per-frame movement phase (speed · curvature) of node.
Raises ValueError when the clip's frame_time is 0 (unset).
See :func:pybvh.geometry.movement_phase.
path_length(node: NodeSelector) -> float
¶
Arc length travelled by node. See :func:pybvh.geometry.path_length.
directness(node: NodeSelector) -> float
¶
Directness of node's path (net displacement ÷ path length).
See :func:pybvh.geometry.directness.
ground_path(node: NodeSelector) -> geometry.GroundPath
¶
Ground-plane path of node (uses world_up). See :func:pybvh.geometry.ground_path.
inter_joint_distance(pairs: Sequence[tuple[NodeSelector, NodeSelector]]) -> npt.NDArray[np.float64]
¶
Per-frame distances between node pairs, each node a name or a BvhNode.
pairs is a sequence of pairs, such as [('Hips', 'Spine')];
anything else raises TypeError. A pair may name one node twice,
and its distance is 0. See :func:pybvh.geometry.inter_joint_distance.
joint_angle(a: NodeSelector, vertex: NodeSelector, b: NodeSelector, degrees: bool = False) -> npt.NDArray[np.float64]
¶
Per-frame angle at vertex in a–vertex–b. See :func:pybvh.geometry.joint_angle.
triangle_area(a: NodeSelector, b: NodeSelector, c: NodeSelector) -> npt.NDArray[np.float64]
¶
Per-frame area of triangle (a, b, c). See :func:pybvh.geometry.triangle_area.
segment_axis_angle(node_a: NodeSelector, node_b: NodeSelector, degrees: bool = False) -> npt.NDArray[np.float64]
¶
Per-frame angle of the segment node_a→node_b to world_up.
See :func:pybvh.geometry.segment_axis_angle.
bounding_box() -> geometry.BoundingBox
¶
Per-frame axis-aligned bounding box of all nodes. See :func:pybvh.geometry.bounding_box.
bounding_sphere() -> geometry.BoundingSphere
¶
Per-frame approximate enclosing sphere of all nodes. See :func:pybvh.geometry.bounding_sphere.
bounding_ellipsoid() -> geometry.BoundingEllipsoid
¶
Per-frame PCA-aligned bounding ellipsoid of all nodes. See :func:pybvh.geometry.bounding_ellipsoid.
center_of_mass(weights: npt.NDArray[np.float64] | None = None) -> npt.NDArray[np.float64]
¶
Per-frame centre of mass of all nodes (uniform by default; pass per-node masses).
See :func:pybvh.geometry.center_of_mass.
com_displacement(weights: npt.NDArray[np.float64] | None = None, com_ref: npt.NDArray[np.float64] | None = None) -> npt.NDArray[np.float64]
¶
Per-frame centre-of-mass travel from a reference.
com_ref defaults to the first frame's centre of mass, in the
same world frame as :meth:center_of_mass, so the result is how far
the CoM has travelled since the start (0 at frame 0). Pass an
explicit com_ref (e.g. center_of_mass().mean(0)) for a
different baseline. See :func:pybvh.geometry.com_displacement.
verticality() -> npt.NDArray[np.float64]
¶
Per-frame height/width ratio along world_up. See :func:pybvh.geometry.verticality.
Dynamics, smoothness & gait¶
Dynamic descriptors (see the Motion Descriptors guide). Their array-pure kernels are in pybvh.analysis.
node_jerk(centered: str = 'world', in_frames: bool = False, stencil: str = 'central', pad: str = 'edge') -> npt.NDArray[np.float64]
¶
Per-node position jerk — (F, N, 3). See :func:pybvh.analysis.node_jerk.
joint_jerk(centered: str = 'world', in_frames: bool = False, stencil: str = 'central', pad: str = 'edge') -> npt.NDArray[np.float64]
¶
Per-joint position jerk — (F, J, 3). See :func:pybvh.analysis.joint_jerk.
smoothness(node: NodeSelector, metric: str = 'sparc', **kwargs: Any) -> float
¶
Smoothness of node's speed profile. See :func:pybvh.analysis.smoothness.
Computes the node's per-frame speed ‖velocity‖ and passes it
to the chosen metric at sampling rate 1 / frame_time.
metric is one of "sparc" (default),
"dimensionless_jerk", "log_dimensionless_jerk",
"integrated_squared_jerk", "mean_squared_jerk",
"rms_squared_jerk", "number_of_peaks", "speed_metric".
Metric-specific options are forwarded as keyword arguments —
"sparc" accepts padlevel (FFT zero-padding exponent,
default 4), fc (max cutoff frequency in Hz, default
10.0) and amp_th (amplitude threshold, default 0.05);
"dimensionless_jerk" and "log_dimensionless_jerk" accept
normalize ("peak_speed" default, "mean_speed" or
"amplitude") and amplitude; "number_of_peaks"
accepts min_height (minimum height for a maximum to count;
default counts all). The remaining metrics take none. Raises
ValueError when the clip's frame_time is 0 (unset).
velocity_reductions(node: NodeSelector)
¶
Scalar reductions of node's speed profile (peak, mean, …).
Computes the node's per-frame speed ‖velocity‖ and reduces it
at sampling rate 1 / frame_time, and raises ValueError
when that frame_time is 0 (unset). See
:func:pybvh.analysis.velocity_reductions.
kinetic_energy(masses: npt.NDArray[np.float64] | Mapping[str, float] | None = None, centered: str = 'world', stencil: str = 'central', pad: str = 'edge') -> npt.NDArray[np.float64]
¶
Per-frame kinetic energy over joints. masses may be a (J,) array
or a {joint_name: mass} mapping. See :func:pybvh.analysis.kinetic_energy.
skeleton_size(feet: Sequence[NodeSelector] | None = None) -> float
¶
Absolute skeleton scale — mean rest-pose distance from the feet to the joint they branch from.
That joint is the lowest one that has the feet in two or more of
its branches, else :attr:body_anchor. Raises ValueError for a
skeleton whose size cannot be measured (no feet found, or all feet
on that joint) rather than
returning a substitute. See :func:pybvh.analysis.skeleton_size.
cadence(feet: Sequence[NodeSelector] | None = None, *, contacts: npt.NDArray[np.float64] | None = None) -> float
¶
Step rate (onsets/second). See :func:pybvh.analysis.cadence.
stride_length(feet: Sequence[NodeSelector] | None = None, *, contacts: npt.NDArray[np.float64] | None = None) -> float
¶
Mean stride length. See :func:pybvh.analysis.stride_length.
walking_pace() -> float
¶
Mean horizontal speed. See :func:pybvh.analysis.walking_pace.
gait_parameters(feet: Sequence[NodeSelector] | None = None, *, contacts: npt.NDArray[np.float64] | None = None)
¶
Spatiotemporal gait parameters. See :func:pybvh.analysis.gait_parameters.
range_of_motion(joint: NodeSelector) -> npt.NDArray[np.float64]
¶
Peak-to-peak range of joint's Euler angles — (3,) per channel.
Selects in JOINT space (rotations exist only on joints), so an end
site raises ValueError, and a name that a joint and an end site
share selects the joint. See :func:pybvh.analysis.range_of_motion.
Augmentation transforms¶
Seeded data augmentation (see the Data Augmentation guide). The array-level functions are in pybvh.transforms.
mirror(lr_mapping: dict[str, str] | None = None, lateral: str | None = None, inplace: bool = False) -> Bvh | None
¶
Mirror motion across the lateral plane. See :func:pybvh.transforms.mirror.
rotate_vertical(angle: float, world_up: str | None = None, degrees: bool = False, pivot: str | npt.ArrayLike = 'origin', inplace: bool = False) -> Bvh | None
¶
Rotate entire motion around the vertical axis (angle in radians), about the world origin or pivot=. See :func:pybvh.transforms.rotate_vertical.
translate_root(offset: npt.ArrayLike, inplace: bool = False) -> Bvh | None
¶
Shift root position by a constant offset. See :func:pybvh.transforms.translate_root.
add_rotation_noise(sigma: float, rng: np.random.Generator | None = None, inplace: bool = False, wrap: bool = False, degrees: bool = False) -> Bvh | None
¶
Add Gaussian noise (sigma in radians, or degrees with degrees=True) to joint angles. See :func:pybvh.transforms.add_rotation_noise.
add_position_noise(sigma: float, rng: np.random.Generator | None = None, inplace: bool = False) -> Bvh | None
¶
Add Gaussian noise (sigma in the skeleton's length unit) to the root translation. See :func:pybvh.transforms.add_position_noise.
perturb_speed(factor: float) -> Bvh
¶
Change motion speed by resampling. See :func:pybvh.transforms.perturb_speed.
drop_frames(drop_rate: float, rng: np.random.Generator | None = None, inplace: bool = False) -> Bvh | None
¶
Replace dropped frames with SLERP interpolation. See :func:pybvh.transforms.drop_frames.
random_translate_root(offset_range: tuple[float, float] = (-100.0, 100.0), rng: np.random.Generator | None = None) -> Bvh
¶
Translate root by a random offset. See :func:pybvh.transforms.random_translate_root.
random_rotate_vertical(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 (radians). See :func:pybvh.transforms.random_rotate_vertical.
random_perturb_speed(factor_range: tuple[float, float] = (0.8, 1.2), rng: np.random.Generator | None = None) -> Bvh
¶
Apply a random speed change. See :func:pybvh.transforms.random_perturb_speed.
Visualization¶
Quick-look plotting on the object. Multi-skeleton comparison lives in pybvh.bvhplot.
plot_rest_pose(**kwargs)
¶
Plot the rest pose. See :func:pybvh.bvhplot.rest_pose.
plot_frame(frame=0, **kwargs)
¶
Plot a single frame. See :func:pybvh.bvhplot.frame.
plot_sequence(**kwargs)
¶
Sequence still (sampled poses, lighter = past).
See :func:pybvh.bvhplot.sequence.
plot_trajectory(**kwargs)
¶
Plot the root trajectory. See :func:pybvh.bvhplot.trajectory.
render(filepath: str | Path = Path('./anim.mp4'), **kwargs)
¶
Render animation to file. See :func:pybvh.bvhplot.render.
play(**kwargs)
¶
Interactive playback. See :func:pybvh.bvhplot.play.