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 |
kept_sources |
list of str or None
|
|
dropped_indices |
list of int
|
Indices of clips that were dropped by the topology gate. |
dropped_sources |
list of str or None
|
|
drop_reasons |
list of str
|
One human-readable reason per dropped clip, aligned with
|
applied_stages |
list of dict
|
One dict per kept clip, aligned with |
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, |
joint_idx |
(ndarray, shape(N))
|
Index of each node's rotation along |
euler_orders |
list of str
|
Per-joint Euler order, e.g. Indexed by joint column, not by node. |
translation_idx |
(ndarray, shape(N))
|
Index of each node's position along |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the arrays disagree on
|
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: |
required |
Returns:
| Type | Description |
|---|---|
FkTopology
|
|
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'
|
warn_on_world_up_disagreement
|
bool
|
If True (default) and |
True
|
lr_mapping
|
dict or None
|
Explicit left/right joint pair mapping
( |
None
|
body_anchor
|
str or None
|
The name of the joint the body's measures start from, set on the
clip as :attr: |
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 |
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 Timeat 6 decimals:0.033333for 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_timeis1 / rate. When several fit, or none with up to 3 decimals, it is the value as read.0.033333and0.033read as1 / 30.0.004166reads as1 / 240, and0.033367as1 / 29.97.0.017(every whole rate from 56 to 60 fps fits) and0.008341(119.88 and 119.89 fps) are kept as read. A 29.97 fps file becomes1 / 29.97, which is 1.000001e-6 relative from NTSC's exact1001 / 30000. When you need that value, setbvh.frame_time = 1001 / 30000after 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.033366700033366700reads as itself, one float from1 / 29.97. The text alone cannot tell a short frame time from a truncated one. So :func:write_bvh_filewrites all 17 significant digits (its Notes say why). A clip whoseframe_timeis0.033is written0.033000000000000002, and it reads back as0.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.033333against1 / 30). Where the rule keeps the text, the two agree. The rounded rate differs from pybvh's wherever pybvh's is not whole (0.033367gives 30 fps,0.01759 fps). In a file at 6 decimals, it also differs on some whole rates above 720 fps (0.001386gives 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_posrow, on the root and on every translating joint (a joint whoseCHANNELSline declares 3 position + 3 rotation channels; its values are :attr:Bvh.joint_translations). A file that declares rotations before positions, orZposition Yposition Xposition, parses correctly, and the node'spos_channelsis('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_filewrites 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 |
required |
verbose
|
bool
|
If True, print a one-line confirmation to stdout on success.
Default |
False
|
overwrite
|
bool
|
If True (default), replace an existing file at |
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the file extension is not |
FileNotFoundError
|
If the parent directory does not exist. |
FileExistsError
|
If |
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'
|
sort
|
bool or {'lexicographic', 'natural'}
|
File ordering. |
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 |
False
|
max_workers
|
int or None
|
Maximum number of threads when |
None
|
world_up
|
str
|
World vertical axis applied to every loaded file.
|
'auto'
|
warn_on_world_up_disagreement
|
bool
|
Passed to :func: |
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 |
False
|
body_anchor
|
str or None
|
The name of the joint the body's measures start from, set on
every loaded file (see :func: |
None
|
Returns:
| Type | Description |
|---|---|
list of Bvh
|
One Bvh object per successfully loaded file. Shorter than the
set of matched files when |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If |
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'
|
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 |
False
|
pad_value
|
float
|
Value to use for padding (default |
0.0
|
include_joint_translations
|
bool
|
If True, add the block of joint translations after the root
position, as :func: |
False
|
Returns:
| Type | Description |
|---|---|
ndarray or list of ndarray
|
If |
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:
- Topology check vs
reference(if provided). On mismatch, the clip is dropped or raises peron_incompatible. - Bone-proportion retargeting to
reference(if provided). - 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 time1 / target_fpsexactly. - World-up reorientation to
target_world_up(if provided andbvh.world_up != target_world_up). Rotates the entire scene — affects offsets, root_pos, and theworld_upflag. - Rest-up reorientation to
target_rest_up(if provided andbvh.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. - Rest-forward reorientation to
target_rest_forward(if provided andbvh.rest_forward != target_rest_forward). Rotates rest-pose offsets around the vertical axis so the skeleton's rest-pose facing matches. - 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 |
None
|
target_fps
|
float or None
|
Target frame rate in Hz. Clips without this rate by
:meth: |
None
|
target_world_up
|
str or None
|
Signed-axis string ( |
None
|
target_rest_up
|
str or None
|
Signed-axis string. Clips whose |
None
|
target_rest_forward
|
str or None
|
Signed-axis string. Clips whose |
None
|
target_euler_order
|
str or None
|
Three-character order like |
None
|
on_incompatible
|
('drop', 'raise')
|
Behavior on topology mismatch with |
"drop"
|
verbose
|
bool
|
If True (default), emit a single |
True
|
return_report
|
bool
|
If True, return |
False
|
Returns:
| Type | Description |
|---|---|
list of Bvh, or (list of Bvh, HarmonizeReport)
|
Harmonized clips (and optional report). The list may be shorter
than |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 table and a list are told apart by the type of the first
element. A table is data: :func: |
required |
df
|
DataFrame
|
Motion data in the form :meth: |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bvh |
Bvh
|
Fully constructed |
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: |
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: |
required |
Returns:
| Type | Description |
|---|---|
list of dict
|
One entry per node, in |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a node's parent is not in |
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, |
Raises:
| Type | Description |
|---|---|
ValueError
|
Naming the entry's index and name, when:
|
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: Renamed from |
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: |
None
|
centered
|
str
|
|
'world'
|
world_up
|
str or None
|
Signed world-up axis string (e.g. |
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: |
None
|
Returns:
| Type | Description |
|---|---|
(ndarray, shape(F, N, 3) or (N, 3))
|
Spatial coordinates for all nodes (including end sites).
Returns 2-D |
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 |
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 |
required |
centered
|
(bool, keyword - only)
|
If True, subtract each array's centroid — the mean over every axis except the last (i.e. over all points, and all frames for a sequence) — before fitting. Default False (fit about the origin). |
False
|
Returns:
| Type | Description |
|---|---|
float
|
The optimal scale |
Notes
Source: Troje 2002 (pose normalization); Umeyama 1991 for the centered convention.