|
Download tasks/data/forward/20tab__bvh-python.b7e0058/instruction.md from Lego-X/ProgramGen: direct link, hf CLI and curl.
- Browser
- Download file 34.7 kB
-
https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/20tab__bvh-python.b7e0058/instruction.md
- Command line
-
hf download hf://datasets/Lego-X/ProgramGen/tasks/data/forward/20tab__bvh-python.b7e0058/instruction.md
-
curl -L -o instruction.md https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/20tab__bvh-python.b7e0058/instruction.md
34.7 kB
| # 20tab/bvh-python | |
| ## Project Overview | |
| bvh-python is a small, focused Python library for parsing BVH (Biovision hierarchical data) motion-capture files, the text-based format commonly exported by mocap software and 3D animation tools such as Mixamo. Its purpose is to let Python programs load a .bvh file and easily query both halves of the format: the HIERARCHY section, which describes the skeletal rig as a tree of joints with offsets and channel definitions, and the MOTION section, which stores the per-frame animation samples. The library is intentionally a reader rather than a full animation toolkit; it exposes the parsed data instead of rendering or retargeting it, making it useful as a foundation for scripts that analyze, convert, or visualize mocap data. | |
| The distribution is deliberately compact: the entire implementation lives in a single module, bvh.py, published as the 'bvh' package (version 0.3) by 20Tab S.r.l., with a test suite in tests/test_bvh.py. The central component is the Bvh class, instantiated from the raw text of a file. Parsing builds a tree of Node objects representing each line of the hierarchy (ROOT, JOINT, OFFSET, CHANNELS, MOTION header entries), with the root node granting iterator and filter access. On top of this tree, Bvh offers convenience accessors: joint lookups by name, joint_parent, joint_parent_index, joint_direct_children, joint_offset, and joint_channels for skeleton structure; get_joints_names and search for enumerating or finding nodes; and motion queries such as nframes, frame_time, and frame_joint_channel, which return numeric values for a given frame, joint, and channel. This clean split between the generic node tree and the domain-specific query API is the library's core architecture. | |
| Re-implement this repository from scratch so that the original test suite passes. The sections below document the language/environment, the project structure, the public API the tests exercise, and per-capability implementation guidance. | |
| ## Submission Constraints (read carefully — the evaluation depends on these) | |
| This is a **closed-book** task. The graded test suite is **hidden** and will be | |
| injected into the workspace at evaluation time. To be scored correctly you MUST | |
| follow these rules: | |
| 1. **Do NOT create or modify any files under the test directories** (e.g. | |
| `tests/`, `test/`, `testing/`, or files named `test_*.py` / `conftest.py`). | |
| The grader injects its own test files at those paths; any file you place | |
| there will collide with the injected suite and cause the whole evaluation to | |
| score 0. Implement **only** the library/source code — never the tests. | |
| 2. **Your package MUST be importable by the name the tests use.** The hidden | |
| tests `import` your package by its documented top-level name (see the | |
| Project Directory Structure and API Usage Guide below). Provide a valid | |
| `pyproject.toml` / `setup.py` / `setup.cfg` and lay out your modules so that | |
| `pip install -e .` succeeds and the package imports cleanly. If your package | |
| is not installable/importable, every test errors out and the reward is 0. | |
| 3. **Match the documented module paths and public API exactly** (names, | |
| signatures, and any literal error/exception strings). Internal helpers not | |
| listed in the API guide may be implemented however you like. | |
| ## Install / Reconstruction Contract | |
| Follow this contract before implementing the documented APIs: | |
| - **Project root**: `/workspace/repo` at runtime; the submitted repository root is `.`. | |
| - **Package/distribution name**: `bvh` | |
| - **Package roots**: `.` | |
| - **Install strategy**: `editable-install` | |
| - **Import/entry**: use the package and public entry points listed in the API Usage Guide; do not invent a different top-level package. | |
| - **Provision commands**: | |
| ```bash | |
| python3 -I -c 'import base64; from pathlib import Path; Path('"'"'/tmp/programgen-pip-compat-v1.py'"'"').write_bytes(base64.b64decode('"'"'aW1wb3J0IG9zCmZyb20gcGF0aGxpYiBpbXBvcnQgUGF0aAppbXBvcnQgc3VicHJvY2VzcwppbXBvcnQgc3lzCmltcG9ydCB0ZW1wZmlsZQoKZGVmIGNvbnN0cmFpbmVkX2J1aWxkX2luc3RhbGwoY29tbWFuZCwgcnVuKToKICAgIGNvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCgnUFJPR1JBTUdFTl9CVUlMRF9DT05TVFJBSU5UJykKICAgIGlmIG5vdCBjb25zdHJhaW50IG9yICctLW5vLWJ1aWxkLWlzb2xhdGlvbicgaW4gY29tbWFuZDoKICAgICAgICByZXR1cm4gTm9uZQogICAg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RvdXQud3JpdGUob3V0cHV0KQogICAgc3lzLnN0ZG91dC5mbHVzaCgpCiAgICBpZiByZXN1bHQucmV0dXJuY29kZSA9PSAwOgogICAgICAgIHJldHVybiAwCiAgICBsZWdhY3kgPSAnaW52YWxpZCBtZXRhZGF0YScgaW4gb3V0cHV0Lmxvd2VyKCkgYW5kICdwbGVhc2UgdXNlIHBpcDwyNC4xJyBpbiBvdXRwdXQubG93ZXIoKQogICAgaWYgbm90IGxlZ2FjeSBvciBub3QgKDMsIDgpIDw9IHN5cy52ZXJzaW9uX2luZm9bOjJdIDw9ICgzLCAxMik6CiAgICAgICAgcmV0dXJuIHJlc3VsdC5yZXR1cm5jb2RlCiAgICBwcmludCgnW3Byb2dyYW1nZW5dIGxlZ2FjeSBkaXN0cmlidXRpb24gbWV0YWRhdGE6IHJldHJ5aW5nIHRoZSB1bmNoYW5nZWQgcmVxdWlyZW1lbnRzIHdpdGggcGlwPDI0LjEnLCBmbHVzaD1UcnVlKQogICAgY2hhbmdlZCA9IHJ1bihbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICdwaXA8MjQuMSddKQogICAgaWYgY2hhbmdlZC5yZXR1cm5jb2RlOgogICAgICAgIHJldHVybiBjaGFuZ2VkLnJldHVybmNvZGUKICAgIHJldHVybiBydW4oY29tbWFuZCkucmV0dXJuY29kZQoKaWYgX19uYW1lX18gPT0gJ19fbWFpbl9fJzoKICAgIHJhaXNlIFN5c3RlbUV4aXQoaW5zdGFsbChzeXMuYXJndlsxOl0pKQo='"'"'))' | |
| programgen_pip_install() { python3 -I /tmp/programgen-pip-compat-v1.py "$@"; } | |
| export -f programgen_pip_install | |
| programgen_pip_install python3 -m pip install -U pip 'setuptools<82' wheel | |
| programgen_pip_install python3 -m pip install 'setuptools>=61,<82' wheel | |
| ( | |
| programgen_install_report="$(mktemp)" | |
| trap 'rm -f "$programgen_install_report"' EXIT | |
| SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 programgen_pip_install python3 -m pip install -e . --no-build-isolation --no-deps --report "$programgen_install_report" | |
| python3 -c 'exec("import json,subprocess,sys\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.utils import canonicalize_name\nreport=json.load(open(sys.argv[1], encoding='"'"'utf-8'"'"'))\n\nrequested={canonicalize_name(name) for name in ()}\nrequirements=[]\nfor item in report.get('"'"'install'"'"', []):\n metadata=item.get('"'"'metadata'"'"', {})\n name=canonicalize_name(metadata.get('"'"'name'"'"', '"'"''"'"'))\n provided={canonicalize_name(value) for value in metadata.get('"'"'provides_extra'"'"', [])}\n selected={'"'"''"'"'} | (provided & requested)\n parsed=[Requirement(value) for value in metadata.get('"'"'requires_dist'"'"', [])]\n while True:\n added=set()\n for requirement in parsed:\n if requirement.marker is not None and not any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n continue\n if canonicalize_name(requirement.name)==name:\n if requirement.url or (requirement.specifier and not requirement.specifier.contains(metadata.get('"'"'version'"'"', '"'"''"'"'), prereleases=True)):\n raise ValueError('"'"'local extra requires a different target distribution'"'"')\n extras={canonicalize_name(value) for value in requirement.extras}\n if not extras <= provided:\n raise ValueError('"'"'local extra refers to an undeclared extra'"'"')\n added.update(extras - selected)\n if not added:\n break\n selected.update(added)\n for requirement in parsed:\n if canonicalize_name(requirement.name)==name:\n continue\n if requirement.marker is None or any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n requirement.marker=None\n requirements.append(str(requirement))\nrequirements=list(dict.fromkeys(requirements))\nsubprocess.run([sys.executable, '"'"'-I'"'"', '"'"'/tmp/programgen-pip-compat-v1.py'"'"', sys.executable, '"'"'-m'"'"', '"'"'pip'"'"', '"'"'install'"'"', *requirements], check=True) if requirements else None\n")' "$programgen_install_report" | |
| ) | |
| ``` | |
| - **Runtime setup**: | |
| ```bash | |
| { | |
| SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 SETUPTOOLS_SCM_WRITE_TO_SOURCE=1 python3 -m pip install -e "$PWD" --no-build-isolation --no-deps; | |
| } | |
| ``` | |
| - **Project root for installation**: `.` | |
| - **Build-version environment**: `SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0`, `PDM_BUILD_SCM_VERSION=0.0.0`, `POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0`, `UV_DYNAMIC_VERSIONING_BYPASS=0.0.0` | |
| - **Test directory**: `tests` | |
| - **Test command**: `bash -lc 'set -uo pipefail | |
| run=(python3 -m pytest -vv -o addopts= tests/test_bvh.py) | |
| if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv -o addopts= tests/test_bvh.py); fi | |
| collect=(python3 -m pytest -q -o addopts= tests/test_bvh.py) | |
| collected_output=$("${collect[@]}" --collect-only) | |
| collect_rc=$? | |
| if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then | |
| printf "%s\n" "$collected_output" >&2 | |
| printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 | |
| exit "$collect_rc" | |
| fi | |
| mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '"'"'/::/p'"'"' | sed '"'"'s/[[:space:]]*$//'"'"') | |
| if [ "${#collected[@]}" -gt 500 ]; then | |
| while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'"'"'::'"'"' -v limit=500 '"'"'{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}'"'"') | |
| fi | |
| "${run[@]}"; exit $?'` | |
| - **Test startup**: run the exact test command above from the project root after installation; hidden tests are injected separately. | |
| ## Environment & Project Structure | |
| - **Language**: python | |
| - **Build system**: python | |
| - **Test command**: `bash -lc set -uo pipefail | |
| run=(python3 -m pytest -vv -o addopts= tests/test_bvh.py) | |
| if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv -o addopts= tests/test_bvh.py); fi | |
| collect=(python3 -m pytest -q -o addopts= tests/test_bvh.py) | |
| collected_output=$("${collect[@]}" --collect-only) | |
| collect_rc=$? | |
| if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then | |
| printf "%s\n" "$collected_output" >&2 | |
| printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 | |
| exit "$collect_rc" | |
| fi | |
| mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '/::/p' | sed 's/[[:space:]]*$//') | |
| if [ "${#collected[@]}" -gt 500 ]; then | |
| while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'::' -v limit=500 '{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}') | |
| fi | |
| "${run[@]}"; exit $?` | |
| ### Project Directory Structure | |
| ``` | |
| .gitignore | |
| LICENSE | |
| README.md | |
| bvh.py | |
| setup.py | |
| ``` | |
| ## API Usage Guide | |
| Each capability below lists the components the tests exercise with their exact signatures and behavior. Re-create these so the tests pass; internal helpers not listed here may be implemented freely. | |
| ### Capability: BVH file loading and tokenization | |
| # BVH file loading and tokenization | |
| ## Purpose and scope | |
| This capability is the entry point of the library: turning the raw text of a `.bvh` file into the two in-memory structures every other accessor depends on — a node tree for the `HIERARCHY` section and a list of frame rows for the `MOTION` section. Construction is a single call: `Bvh(data)` with `data` being the file's full text as one string. The constructor performs all parsing eagerly; there is no separate load/parse step, no streaming, and no validation pass beyond the structural rules described below. A second public class, `BvhNode`, is the building block of the resulting tree and is what callers receive when they iterate or filter the parsed hierarchy. | |
| Both classes are imported from the top-level `bvh` package (`from bvh import Bvh, BvhNode`). `Bvh` is the parser; `BvhNode` is the generic tree element, useful both because the parser instantiates it and because tests construct or type-check it directly (e.g. asserting that an empty document still yields a root that `isinstance`-checks as `BvhNode`). | |
| ## Construction and state changes | |
| `Bvh(data)` performs three state changes before returning: | |
| 1. `self.data = data` — the original string is retained verbatim. Tests rely on exact retention (the character count of the raw file text equals `len(mocap.data)`), so do not normalize, decode differently, or strip anything at this stage. | |
| 2. `self.root = BvhNode()` — a sentinel root node with an empty `value` list. It is not a real hierarchy line; it exists so that top-level lines (`HIERARCHY`, `ROOT ...`, `MOTION`, `Frames: ...`, `Frame Time: ...`) become its children. The sentinel's empty `value` also has a visible consequence: calling the `.name` property on the root itself raises `IndexError` because there is no `value[1]`. | |
| 3. `self.frames = []` followed by `self.tokenize()` — tokenization runs inside the constructor and fills both `self.root` (children) and `self.frames` (frame rows). | |
| `tokenize()` can be called again on an existing instance, but note it is **not idempotent in place**: it does not clear `self.root.children` or `self.frames`, so a re-call appends duplicates. Fresh parsing means a fresh `Bvh` instance. | |
| ## Line splitting details | |
| Tokenizer input is a character scan over `self.data`, not `str.splitlines()`. Characters accumulate until a line terminator is seen. Both `\n` and `\r` terminate a line, which means: | |
| - `\r\n` (Windows CRLF) produces exactly one line — the `\r` flushes the accumulator, and the following `\n` sees an empty accumulator and is ignored. The bundled test fixtures end each line with `\r\n`, and the parser accepts them without producing blank entries. | |
| - bare `\n`, bare `\r`, and even mixed endings in one file all work. | |
| - a terminator emits a line only if the accumulator is non-empty *at that moment*, so truly blank lines, `\r\n` pairs on empty lines, and any amount of consecutive newlines are silently dropped. A line containing only spaces and/or tabs is **not** dropped: its accumulator is non-empty, so it is emitted — and because `re.split(r'\s+', '')` yields the single-token list `['']`, it surfaces as a one-token list whose only token is the empty string. Before the `Frame Time:` marker such a line becomes a junk `BvhNode([''])` in the tree (its `str()` is `''`; its `name` raises `IndexError`); after the marker it is appended to `frames` as a `['']` row, shifting the frame count and every column alignment after it. | |
| - text after the final line without a trailing terminator is **discarded**: there is no end-of-input flush. Every meaningful line in a BVH file must end with a newline (or carriage return) for it to register. The fixtures satisfy this. | |
| Each accumulated line is stripped and split on runs of whitespace via `re.split(r'\s+', line.strip())`. Consequences worth encoding in a re-implementation: | |
| - indentation is irrelevant: a nested `{` appears simply as the one-token list `['{']`. | |
| - tabs and multiple spaces are equivalent separators; for lines containing at least one non-whitespace character, runs collapse and no empty tokens are produced (the whitespace-only `['']` case above is the one exception). | |
| - The BVH `Frame Time:` header is conventionally written with a tab after the colon (`Frame Time:\t0.033333`); splitting handles this and yields `['Frame', 'Time:', '0.033333']`. | |
| - leading/trailing whitespace disappears, so `OFFSET` values parse cleanly even when file formatting is sloppy. | |
| ## Tree building: stack discipline | |
| The splitter first converts the entire document to a list of token lists, then walks it once with a stack of nodes (initialized to `[self.root]`) and a `node` variable holding the most recently created node: | |
| - A token list whose first token is `{` pushes `node` — the most recently created node — onto the stack. This is how a `JOINT` (or `ROOT`) line becomes the parent of its `OFFSET`, `CHANNELS`, and child `JOINT` lines. In a well-formed file `{` always follows a joint line, so `node` is defined. But `node` starts out as `None`, so a `{` encountered before any node has been created pushes `None`; the next node-creating line then calls `add_child` on that stack top and fails with `AttributeError` (`'NoneType' object has no attribute 'add_child'`). If a `}` comes first, it pops the `None` back off and parsing resumes under the sentinel root with no complaint. The mirror case is unvalidated too: a `{` appearing *after* a `}` re-pushes the stale last-created node, and every subsequent line mis-nests beneath it. There is no explicit brace-matching error. | |
| - A token list whose first token is `}` pops the stack (including any `None` a stray leading `{` pushed). No node is created for braces, which is why iterating the tree never surfaces `{`/`}` entries. | |
| - Any other token list becomes a `BvhNode(item)` appended as a child of the current stack top, and becomes the new `node`. | |
| Depth therefore comes purely from brace order, not indentation. At the end of the hierarchy the stack returns to the sentinel root, and the top-level children appear in document order. For a normal file the root's direct children are exactly, in order: the `HIERARCHY` line, the single `ROOT ...` line, the `MOTION` line, the `Frames: N` line, and the `Frame Time: ...` line — a five-element sequence that the tests assert verbatim via `str(node)` (which joins the node's tokens with single spaces). | |
| A quirk to preserve: the parser does not check that the stack is exhausted or balanced. An extra `}` pops the sentinel root and leaves an empty stack; a subsequent node creation then fails with `IndexError` from accessing the stack top, and a `{` before any node produces the `AttributeError` described above. Malformed input is handled by silent mis-nesting until it happens to crash — via `AttributeError` or `IndexError` — never by a dedicated parse error. | |
| ## The Frame Time marker and frame separation | |
| The walk tracks a `frame_time_found` flag. When a token list's first token is `Frame` and its second is `Time:` (exact token match — `Frames:` does not match, since its first token is the string `Frames:`), the flag is set *after* that line is processed normally. The comparison is written as `item[0] == 'Frame' and item[1] == 'Time:'`, and the `item[1]` access is unguarded: any pre-marker line whose token list is exactly `['Frame']` — first token `Frame`, no second token — raises `IndexError` during `tokenize()`, and a faithful re-implementation must reproduce this rather than length-guard the check. (Whitespace-only `['']` lines do not trigger it: their first token is `''`, so the `and` short-circuits before `item[1]` is touched.) Consequently: | |
| - The `Frame Time:` line itself becomes a root child node with tokens `['Frame', 'Time:', '<value>']`; the frame period is readable from that node's third token (`value[2]`), which is exactly how the `frame_time` property retrieves it. | |
| - Every subsequent line is appended to `self.frames` as a plain list of string tokens and is **not** represented in the node tree. Frame rows are the only document content outside the tree. | |
| This marker check is the sole separator between hierarchy and motion. If a file lacks a `Frame Time:` line, no flag is ever set and frame data (if present) is parsed as hierarchy nodes instead — silent garbage, not an error. Ordering matters too: the `Frames: N` line precedes the marker, so it stays a node; the marker line precedes all frame rows. | |
| ## The `frames` list and laziness of numeric conversion | |
| `mocap.frames` is a list of lists of strings, one list per motion frame, in file order. No numbers are converted at parse time. The count of this list equals the declared `Frames:` count in the fixtures (`nframes == len(mocap.frames)` is asserted), but nothing enforces that equality during parsing — declaration and row count can drift apart in malformed files without a parse-time complaint (and a whitespace-only line after the marker quietly adds a `['']` row, per the splitting rules above). Numeric coercion (`float(...)`) happens only inside the motion accessors, and index errors for out-of-range frame indices surface there as list `IndexError`s, not during construction. | |
| ## BvhNode behavior visible through loading | |
| A `BvhNode` wraps one document line as `self.value` (the token list), plus `self.children` and `self.parent`. The behaviors that matter after loading: | |
| - **Parent linking at creation**: `BvhNode(value, parent=...)` auto-registers itself with the given parent via `add_child`. The tokenizer always constructs children this way (through the stack top's `add_child`), so `parent` pointers are correct for the whole tree, and `joint_parent`/`joint_parent_index` can distinguish the sentinel root (parent is `self.root`, reported as `None` / `-1`). | |
| - **Iteration**: iterating a node yields its direct children in insertion order; `filter(key)` yields only direct children whose *first* token equals `key`. `mocap.root` is iterable, so `mocap.root.filter('ROOT')` finds the single root joint node. `filter` is a generator and compares only direct children — it does not recurse (recursive matching is `Bvh.search`'s job). | |
| - **Key lookup**: `node[key]` scans each direct child's token list for an occurrence of `key` and returns *the remainder of that token list after the key* as a new list — e.g. a `ROOT` node's `['OFFSET']` lookup returns the three offset strings `['0.0000', '0.0000', '0.0000']`. If the key is the last token of a matched child, the result is `None` (not an error). If no direct child contains the token anywhere, `IndexError` is raised. This token-scan semantics explains why attribute names must not collide with values on the same line, and why `root['Broken']` raises `IndexError` in the tests. | |
| - **String form**: `str(node)` joins the node's tokens with single spaces, so `'ROOT mixamorig:Hips'` reproduces the source line modulo whitespace normalization. Note the tokenizer also normalizes the `Frame Time:` tab into a space in this rendering (`'Frame Time: 0.0333333'`). | |
| - **`name`**: returns `value[1]`, i.e. the second token. For `ROOT Hips` that is `Hips`; for joint nodes it is the joint name (including `:`-containing Mixamo names like `mixamorig:Hips` — no splitting on `:` occurs). For one-token nodes such as `HIERARCHY` or `{`-less single-token lines, `name` raises `IndexError`. | |
| - **Mutable default**: `BvhNode.__init__` defaults `value=[]`; the parsed object is stored as-is (by reference), so callers should treat `node.value` as owned by the node. The default itself is a single list object created once at function definition and shared by every `BvhNode` constructed without a value: the sentinel roots of two separate `Bvh` instances alias the same list (`Bvh(a).root.value is Bvh(b).root.value`), so mutating one no-argument node's `value` mutates all of them. Explicitly passed lists are likewise stored by reference, not copied. A re-implementation must preserve this shared-default/by-reference semantics or explicitly document the observable difference. | |
| ## Error behavior of the loading path itself | |
| Tokenization raises nothing for empty or minimally valid input. `Bvh('')` succeeds: the accumulator never fills, so there are no lines; `root` is an empty `BvhNode`, `frames` is `[]`. The exceptions it *can* raise directly are the malformed-input crashes cataloged above — `IndexError` from a lone pre-marker `Frame` line, `AttributeError` from a `{` before any node, and `IndexError` from node creation on an over-popped stack — never a dedicated parse error. The documented `LookupError` messages (`'joint not found'`, `'number of frames not found'`, `'frame time not found'`) all originate from downstream accessors, not from loading — an empty instance parses fine and only fails when, say, `nframes` or `frame_time` is queried (each via `filter` finding no matching root child, converted from `StopIteration`). Keep that split in mind: loading is permissive; queries are strict. | |
| ## Realistic workflow | |
| A consumer loads once and queries many times: `Bvh(open('file.bvh').read())`, then use the root tree for structure (`filter('ROOT')`, `search('JOINT', name)`, brace-derived parent/child links) and `frames` for per-frame channel values, whose column indexing is derived from the `CHANNELS` nodes parsed into the same tree. The loading step's guarantees the rest of the API relies on are: (a) every `ROOT`/`JOINT`/`OFFSET`/`CHANNELS`/`Frames:`/`Frame Time:` line is a node with exact original tokens; (b) node nesting mirrors brace nesting; (c) `frames` rows align one-to-one with motion lines after the marker; (d) all values remain strings until an accessor coerces them. | |
| #### Exact API Reference | |
| #### `bvh.BvhNode` | |
| - **Import Path**: `from bvh import BvhNode` | |
| - **Required Test Import Paths**: | |
| - bvh.BvhNode | |
| - **Exact Test Import Statements**: | |
| - from bvh import Bvh, BvhNode | |
| - **Kind**: class | |
| - **Signature**: | |
| ```python | |
| class BvhNode: | |
| def __init__(self, value=[], parent=None) | |
| def add_child(self, item) | |
| def filter(self, key) | |
| def __iter__(self) | |
| def __getitem__(self, key) | |
| def __repr__(self) | |
| @property | |
| def name(self) | |
| value: Any | |
| children: list | |
| parent: Any | |
| ``` | |
| #### `bvh.Bvh` | |
| - **Import Path**: `from bvh import Bvh` | |
| - **Required Test Import Paths**: | |
| - bvh.Bvh | |
| - **Exact Test Import Statements**: | |
| - from bvh import Bvh, BvhNode | |
| - **Kind**: class | |
| - **Signature**: | |
| ```python | |
| class Bvh: | |
| def __init__(self, data) | |
| def tokenize(self) | |
| def search(self, *items) | |
| def get_joints(self) | |
| def get_joints_names(self) | |
| def joint_direct_children(self, name) | |
| def get_joint_index(self, name) | |
| def get_joint(self, name) | |
| def joint_offset(self, name) | |
| def joint_channels(self, name) | |
| def get_joint_channels_index(self, joint_name) | |
| def get_joint_channel_index(self, joint, channel) | |
| def frame_joint_channel(self, frame_index, joint, channel, value=None) | |
| def frame_joint_channels(self, frame_index, joint, channels, value=None) | |
| def frames_joint_channels(self, joint, channels, value=None) | |
| def joint_parent(self, name) | |
| def joint_parent_index(self, name) | |
| @property | |
| def nframes(self) | |
| @property | |
| def frame_time(self) | |
| data: Any | |
| root: Any | |
| frames: list | |
| ``` | |
| - **Raises** (implementation must reproduce these exact messages): | |
| - `joint not found` | |
| - `number of frames not found` | |
| - `frame time not found` | |
| ## Detailed Implementation Nodes | |
| ### Node: BVH file loading and tokenization | |
| ## Functional constraints | |
| **`Bvh(data)`** — eager parser; no second phase. | |
| - Store `data` verbatim on the instance; tests check exact character counts. | |
| - Create sentinel root (`BvhNode()` with empty `value`) and empty `frames` list, then run tokenization. | |
| - Raises nothing for valid text; malformed input fails via silent mis-nesting, a direct `AttributeError` or `IndexError` (see tree-build and marker rules below), or a downstream `IndexError`. | |
| **Line splitting** — character scan, not `splitlines`: | |
| - `\n` and `\r` each terminate a line; `\r\n` yields one line (empty accumulator on the `\n` is skipped). | |
| - Emit a token list only when the accumulator is non-empty at the terminator → truly blank lines and repeated newlines are dropped. Whitespace-only lines (spaces/tabs only) have a non-empty accumulator and are **not** dropped: they emit the token list `['']`, since `re.split(r'\s+', '')` returns a one-element list containing the empty string. | |
| - No end-of-input flush: a final line without a trailing terminator is lost. | |
| - Split each line with `re.split(r'\s+', line.strip())`: tabs/multiple spaces collapse, indentation vanishes; for lines containing non-whitespace characters, no empty tokens are produced. `Frame Time:\t0.033333` → `['Frame', 'Time:', '0.033333']`. | |
| **Tree build** — single pass with `node_stack = [self.root]` and `node = None`: | |
| - First token `{`: push `node` — the most recently created node (`None` before any node exists). No `{` node exists in the tree. A `{` before any node has been created pushes `None`; the next node-creating line then raises `AttributeError` (`None` has no `add_child`), unless a `}` pops the `None` first, in which case parsing resumes under the sentinel root. A `{` after a `}` re-pushes the stale last-created node and mis-nests all subsequent lines. | |
| - First token `}`: pop the stack. Unbalanced `}` can empty the stack; later node creation then raises `IndexError`. | |
| - Otherwise: create `BvhNode(item)`, append via the stack top's `add_child` (sets child's `parent`), and make it the new `node`. | |
| - Top-level children of the sentinel root, in document order: `HIERARCHY`, `ROOT <name>`, `MOTION`, `Frames: <n>`, `Frame Time: <dt>`. `str(node)` = tokens joined by single spaces. | |
| **Frame Time marker** — the only hierarchy/motion separator: | |
| - Match is exact on tokens: first token `Frame` **and** second token `Time:`. `Frames:` does not match. | |
| - The test `item[0] == 'Frame' and item[1] == 'Time:'` indexes `item[1]` unguarded: a pre-marker line whose token list is exactly `['Frame']` crashes `tokenize()` with `IndexError`. A faithful re-implementation must reproduce this rather than length-guard the check. (Whitespace-only `['']` lines are safe: `item[0]` is `''`, so the `and` short-circuits.) | |
| - Set the flag *after* processing the line, so the `Frame Time:` line remains a root child; its third token (`value[2]`) is the frame period the `frame_time` property reads. | |
| - All later lines append to `frames` as plain token lists; they never become nodes. | |
| - Missing marker ⇒ no frames are ever separated (frame rows would be parsed as hierarchy nodes); no error is raised. | |
| **Post-load invariants**: | |
| - `frames`: list of lists of strings, one per motion line, file order; strings only — numeric conversion is deferred to accessors. | |
| - `len(frames)` matches the declared `Frames:` count in valid fixtures, but parsing does not enforce the correspondence. | |
| - Whitespace-only lines are not dropped: before the marker one becomes a junk node with `value == ['']` (`str()` is `''`, `name` raises `IndexError`); after the marker it becomes a `['']` row in `frames`, shifting frame counts and column alignment. | |
| - Empty input: `Bvh('')` succeeds; root has no children, `frames == []`. The sentinel root's `value` is `[]`, so `.name` on it raises `IndexError`. | |
| - Do not call `tokenize()` twice on one instance; it appends without clearing (duplicated children/frames). Re-instantiate instead. | |
| **`BvhNode(value=[], parent=None)`**: | |
| - Stores `value` as given (by reference); auto-registers with `parent` via `add_child` (sets the child's `parent`, appends to the parent's `children`). | |
| - The `value=[]` default is a single shared list object created once at definition time: every no-argument `BvhNode` aliases it, so `Bvh(a).root.value is Bvh(b).root.value` holds and mutating one no-arg node's `value` mutates all of them. Explicitly passed lists are stored by reference, not copied. Preserve this shared-default/by-reference semantics or explicitly document the observable difference. | |
| - `add_child(item)` reassigns `item.parent` to the receiver and appends it last. | |
| - `filter(key)` yields direct children whose `value[0] == key` (generator, non-recursive). | |
| - Iteration yields direct children in insertion order. | |
| - `node[key]`: scan each direct child's tokens for `key`; return the tokens *after* it as a list, or `None` if the key was the child's last token; `IndexError` if no direct child contains it anywhere. | |
| - `name` = `value[1]`; `str(node)` = `' '.join(value)`. | |
| ### Usage example | |
| ```python | |
| from bvh import Bvh, BvhNode | |
| with open('tests/test_freebvh.bvh') as f: | |
| mocap = Bvh(f.read()) | |
| assert isinstance(mocap.root, BvhNode) | |
| assert [str(n) for n in mocap.root] == [ | |
| 'HIERARCHY', 'ROOT mixamorig:Hips', 'MOTION', | |
| 'Frames: 69', 'Frame Time: 0.0333333'] | |
| assert len(mocap.frames) == 69 # rows after the Frame Time marker | |
| assert mocap.frames[0][0] == '4.3314' # still strings at load time | |
| root_joint = next(mocap.root.filter('ROOT')) | |
| assert root_joint.name == 'mixamorig:Hips' | |
| ``` | |