diff --git a/docs/developer-workflows/ai-delegation-and-review.md b/docs/developer-workflows/ai-delegation-and-review.md index f32e38a..7154098 100644 --- a/docs/developer-workflows/ai-delegation-and-review.md +++ b/docs/developer-workflows/ai-delegation-and-review.md @@ -50,8 +50,11 @@ Existing consequential strategic and visual oversight remains unchanged. The Main Worker proactively reports concise high-level progress and recommends closure when useful review returns have diminished to minor improvements. It -does not wait for Ben to ask or chase perfect or zero-finding reviews. The -handoff summarizes the recent review trend and significance, current fixes, +does not wait for Ben to ask or chase perfect or zero-finding reviews. +Immediately before reporting readiness to the Overseer, the Main Worker +refreshes the PR title and body for the final scope and validation, then reads +back its title, body, head, base, and state under the [repository-safety rule](../../AGENTS.md#repository-safety). +The handoff summarizes the recent review trend and significance, current fixes, and consequential remaining gaps, using existing evidence. The Overseer assesses that recommendation promptly and decides whether to merge, request a specific necessary fix, or raise a retained-human decision. This creates no diff --git a/docs/project/current-handover.md b/docs/project/current-handover.md index 704caf6..6371654 100644 --- a/docs/project/current-handover.md +++ b/docs/project/current-handover.md @@ -7,35 +7,35 @@ with live verification and navigation. ## Resumed runway — 2026-09-08 Ben explicitly resumed the exact paused runway through the Overseer on -2026-09-08. The fail-closed PowerShell/stdin invocation repair has now passed -parser, mocks, and both non-launching stdin sentinels (empty-profile and -nonnumeric-port), with both rejected-input child processes exiting nonzero and no trailing sentinel; quoted-argument -preview and fake handoff match, and no execution-policy mutation occurred. -Main's follow-up changed only cleanup-receipt guidance to require current-PID, -executable, and profile verification; no algorithm changed. Revalidate the -pause snapshot and these status pointers before continuing the lowest -integration lane: PR #127 plus up to two dependent follow-ups, with each layer -below 100 changed files. PR #127 currently has 57 prospective paths; the two -planned follow-ups are approximately 92 and 79 paths. Packaging and review remain primary, and upper-work must not -delay the lower lane. A genuine final-review-ready clean immutable head may then -receive the hosted and committed-diff CLI review cycle together. Current -real-browser coverage is deferred; no browser repair or setup lane remains -active. No local native Chromium or Playwright was available; the setup attempt -installed only npm Playwright 1.63.0 packages at -`/home/ben/.cache/pr127-native-browser-IFXwYI`, with no browser download or -launch and no new infrastructure or launcher project. Windows-side execution is -not permanently prohibited, but any future coverage must be provably hidden and -profile-isolated and create no visible Windows desktop windows, tabs, consoles, -focus changes, or popups. Real Windows launch and nonintrusion remain -unverified. No additional broad waiver is granted. Previous source/CLI gallery -hash-based validation remains retained evidence. Current merge responsibility is -assigned exclusively to the Overseer: Main prepares and pushes PRs, implements, -reviews, fixes, validates, and reports concise readiness, but never merges or -enables auto-merge, including after readiness acknowledgment. The Overseer -alone assesses agreed gates and decides and executes merge; Ben retains product, -direction, and consequential boundaries. Ben explicitly authorizes closure after -the current fixes and checks, subject to Overseer assessment. The pause record -below is historical. +2026-09-08. PR #127 merged into `main` on 2026-09-09 NZST +(`2026-09-08T12:14:09Z`) by the Overseer after required CI passed. The current +lower integration follows the package and validation state in the Active +runway. + +The current package and validation state are recorded in the Active runway. No +experiment execution, new geometry, candidate construction, or acceptance +occurs here. Upper body and foundation work remain separate. The named human +checkpoint remains a coherent, recognizable simplified whole character at rest +and in restrained combined poses, with movement driven by real source, frame, +and binding data. + +The Overseer retains exclusive merge assessment and execution; Main has no +merge authority and Ben retains the consequential boundaries. The prior PR #127 +closure authorization is historical and scoped, not standing automatic approval +for this next PR. The pause record below is historical. + +## Current Layer 2 lower integration + +This handover now points at the lower integration checkout +`/home/ben/src/creature-kernel-worktrees/lower-connected-leg-integration` on +`codex/lower-connected-leg-integration`. It carries the lower package described +in the Active runway and performs no experiment execution or geometry +validation; later body/foundation paths remain deferred to the upper layer. +The four copied experiment directories are exploratory or historical +prerequisites whose own READMEs retain lifecycle and evidence authority. The +current whole-character human checkpoint is unchanged: a coherent, +recognizable simplified whole character at rest and in restrained combined +poses, with movement driven by real source, frame, and binding data. ## Historical pause snapshot — 2026-09-07 @@ -90,7 +90,7 @@ the draft integration package, refresh exact PR head/file count, and consider the pending immutable-head review cycle. Real-browser evidence and whole-PR human merge authority remain unsatisfied; no browser retry is implicit. -## Last-known context +## Historical Layer 1 last-known context The following values are expected last-known context for this Layer 1 integration checkout and are explicitly untrusted until verified live: @@ -112,22 +112,21 @@ The original active development checkout remains `codex/owned-root-assembly-successor`; pelvis source work continues there and was not edited by this integration layer. -## Layer 1 integration destination +## Layer 2 lower integration destination -This checkout packages and tests the historical owned-root and gallery fixes -under the three-PR stack. The four stage-specific documentation overlays record -historical closeout and navigation only; captured regression checks change no -construction and publish no candidate. No parked experiment is reactivated. -The current continuation is the integrated -coarse-to-anatomical whole-character Active runway. Later lower/body paths are -follow-up stack material and remain prose-only until their files arrive here. +This checkout carries the lower Layer 2 source/evidence package under the +three-layer stack. The documentation changes provide lower-layer navigation +while preserving the copied experiment records and their lifecycle and evidence +states. Packaging reactivates no parked experiment and establishes no geometry +result. The current continuation is the integrated coarse-to-anatomical +whole-character Active runway. Later body/foundation paths remain deferred to +the upper layer. -PR #127 and the supplied head remain pending CI, independent review, hosted and -CLI checks, and human control-plane gates. This handover grants no merge -authorization. The current integration checks and consolidated review remain -pending. +The lower package continues under the Active runway. The Overseer retains +exclusive merge assessment and execution, and the prior PR #127 closure +authorization is historical and scoped to that merged PR. -Focused integration results and their capture paths are recorded in +Historical Layer 1 integration results and their capture paths are recorded in [Layer 1 integration evidence](status.md#layer-1-integration-evidence-2026-09-07). Ben stopped browser launches after the trial method caused visible Chrome errors and failed tabs. Browser coverage remains incomplete; continuation diff --git a/docs/project/status.md b/docs/project/status.md index 9089645..ec5ebcc 100644 --- a/docs/project/status.md +++ b/docs/project/status.md @@ -15,32 +15,33 @@ governs what resumes next. ## Active runway **RESUMED on 2026-09-08 at Ben's explicit request relayed by the Overseer.** -Resume the exact paused runway. The fail-closed PowerShell/stdin invocation -repair has now passed parser, mocks, and both non-launching stdin sentinels -(empty-profile and nonnumeric-port), with both rejected-input child processes exiting nonzero and no trailing sentinel; -quoted-argument preview and fake handoff match, and no execution-policy -mutation occurred. Main's follow-up changed only cleanup-receipt guidance to -require current-PID, executable, and profile verification; no algorithm changed. -Revalidate this pause snapshot and the current handover before continuing the -lowest integration lane: -PR #127 currently has 57 prospective paths; its two planned follow-ups are -approximately 92 and 79 paths, each below 100 changed files. Packaging and review remain primary, and -upper-work must not delay that lower lane. A genuine final-review-ready clean -immutable head is required before the hosted and committed-diff CLI review cycle -runs together. Current real-browser coverage is deferred; no browser repair or -setup lane remains active. No local native Chromium or Playwright was available; -the setup attempt installed only npm Playwright 1.63.0 packages at -`/home/ben/.cache/pr127-native-browser-IFXwYI`, with no browser download or -launch and no new infrastructure or launcher project. Windows-side execution is -not permanently prohibited, but any future coverage must be provably hidden and +The paused PR #127 integration is now historical: PR #127 merged into `main` on +2026-09-09 NZST (`2026-09-08T12:14:09Z`) by the Overseer after required CI +passed. The current lower integration is rebased onto `origin/main` at +`f30faafe598ef7f94341691fe492228f165943de`. + +The next package is the lower connected-leg prerequisites and three pelvis +records: 88 added source/evidence paths, plus three navigation overlays and one +small authorized workflow timing edit, for 92 prospective PR paths. First-use +public help/prepare/captured-verify passed; the +adversarial absent/existing/tampered verification cases passed with identical +before/after existing snapshot hashes; and the fresh captured 26 synthetic +runner tests passed with pre/post verification. The 61 added Python and 16 JSON +files parsed successfully. This package performs no experiment execution, new +geometry, candidate construction, or acceptance. +Upper body and foundation work remain separate. The named human checkpoint +remains a coherent, recognizable simplified whole character at rest and in +restrained combined poses, driven by real source, frame, and binding data. + +Real-browser coverage remains deferred; no browser repair or setup lane is +active. Any future Windows invocation must be provably hidden and profile-isolated and create no visible Windows desktop windows, tabs, consoles, -focus changes, or popups. Real Windows launch and nonintrusion remain -unverified. No additional broad waiver is granted. Previous source/CLI gallery -hash-based validation remains retained evidence. Ben explicitly authorizes -closure after the current fixes and checks, subject to Overseer assessment. -Under Ben's authorization, the Overseer owns merge assessment and execution; -Main has no merge authority, and retained-human boundaries remain with Ben. The -paused snapshot is preserved as +focus changes, or popups. Native launch and nonintrusion remain unverified. + +The Overseer retains exclusive merge assessment and execution; Main has no +merge authority and Ben retains the consequential boundaries. The prior PR #127 +closure authorization is historical and scoped, not standing automatic approval +for this next PR. The paused snapshot is preserved as historical record in the [current handover](current-handover.md#historical-pause-snapshot--2026-09-07). @@ -61,25 +62,17 @@ individual limbs, trials, and poses do not substitute for that checkpoint, and this remains experimental evidence rather than a product, specification, or architecture adoption. -This Layer 1 integration checkout packages and tests the historical owned-root -and gallery fixes from PR #127. Main supplied the current draft head -`4ae0a5c8176c60791248ad6eb5e52dc657a2dd34` against base -`db5f11efff124d500d875f7839c53fee9a75f395`; CI, independent review, hosted and -CLI checks, and human control-plane gates remain pending. This status records no -merge authorization. The stage ledger is -[stacked-integration-ledger.md](stacked-integration-ledger.md). - -The owned-root assembly and exact-five attempt below are stopped, superseded -historical evidence. Lower/body experiments and the active pelvis source work -are follow-up stack material; those directories are not present in this Layer 1 -checkout. Pelvis development continues in -`/home/ben/src/creature-kernel-worktrees/owned-root-assembly-successor` on -`codex/owned-root-assembly-successor`. This integration layer runs captured -regression checks without changing construction or publishing a new candidate; -no parked experiment is reactivated. +The current checkout is the Layer 2 lower integration described above. It does +not execute experiments or validate geometry. Later body/foundation paths +remain deferred to the upper layer, while the copied lower experiment records +remain exploratory or historical prerequisites only. No experiment is +reactivated here. ## Layer 1 integration evidence (2026-09-07) +This section is a historical snapshot of the former Layer 1 integration and +does not define the current lower-package continuation. + The local gallery correction passed 58 focused tests, including delayed group transition and Tab/Escape propagation checks. A fresh independent first-use CLI trial confirmed the documented success, canonical-metre off-grid diff --git a/experiments/README.md b/experiments/README.md index 61860e4..939da56 100644 --- a/experiments/README.md +++ b/experiments/README.md @@ -6,7 +6,11 @@ and passed, while broader experiment obligations remain open. The owned-root assembly successor is closed historical evidence. Current continuation is the integrated coarse-to-anatomical whole-character runway in the [Active runway](../docs/project/status.md#active-runway); lower/body experiments -are follow-up stack material and are not present in this Layer 1 checkout. +are Layer 2 follow-up material in this checkout. The Layer 2 package is based on +merged PR #127/main and its current package and validation state are described +in the Active runway. It does not execute experiments or validate geometry, and +later body/foundation paths remain deferred to the upper layer. No experiment is +reactivated or accepted by this package. Experiments provide reproducible evidence for research questions and decisions. They do not become product or architecture contracts automatically. Research @@ -56,6 +60,18 @@ experiments/EXP-NNNN-short-title/ Copy [the experiment template](experiment-template.md). Keep the registry below current as experiments are created. +## Layer 2 copied prerequisites + +These four directories are copied exploratory or historical prerequisites for +the lower integration package. Their own READMEs remain authoritative for +experiment lifecycle, evidence closure, and technology outcome. This checkout +does not execute them or claim acceptance: + +- [Connected-leg assembly staging](connected-leg-assembly/README.md) +- [Local pelvis/hip articulation](pelvis-hip-articulation/README.md) +- [Pelvis source calibration](pelvis-source-calibration/README.md) +- [Bounded pelvis-to-thigh transition](pelvis-thigh-transition/README.md) + ## Registered experiments - [EXP-0002 numeric/frame profile](EXP-0002-numeric-frame-profile/README.md) — diff --git a/experiments/connected-leg-assembly/005-calf-measurement.md b/experiments/connected-leg-assembly/005-calf-measurement.md new file mode 100644 index 0000000..bab8cce --- /dev/null +++ b/experiments/connected-leg-assembly/005-calf-measurement.md @@ -0,0 +1,100 @@ +# Baseline005 anthropomorphic calf measurement diagnostic + +Status: diagnostic-only analysis of immutable saved meshes. Baseline005 remains +rejected by its frozen `signed_calf_posterior_expansion` gate. This note changes +no geometry, protocol, helper, or outcome. + +## Provenance + +The diagnostic read +`connected-leg-assembly-005-integrated-{snapshot,run}` in +`/home/ben/.cache/creature-kernel/`. Its retained derivation script is +`connected-leg-assembly-005-calf-measurement/derive.py` (SHA-256 +`c68aee6108b3322eb12647bd874a462d195d09b027f149a90ebbc01e4bd0d79a`) +and its machine-readable output is `evidence.json` (SHA-256 +`316b5f67764a8382e979b46dfef126ab419a404127e91f64e616afd18e4337c6`). +The managed frozen launcher executed that script against the saved JSON only; +no body construction, pose, collision, or render was rerun. + +Captured source SHA-256 identities were: `perturbations.py` +`ffb1a35594a63534108efd7851262a1b28324dbee677d3cc226974c71372340d`, +`construction.py` +`199672cfb8b57d49842d63b7c1043a0a85b1129eb742dd4b0d8016f52b6b765b`, +`runner.py` `ef41bb5823787308410d25b3e499e0abfde4ea30cf259aaf4c0b6ddbc3a33bd2`, +`inputs.json` `1fbd9448bcef2861fc61623b497e67bd2e84a1106818dcac9d84dcf04bd60bda`, +and `protocol.json` +`8d62a981f37de28500e1b15b545c0e608941610d5fb253902dd450526d010446`. +The anthropomorphic snapshot inputs were `005-mesh-L0` +`6237cc7940e1559fbf05d18ab20d87b444c3dd3dd7238a41ffe17f3c6b881e2e`, +`006-mesh-L2` +`59e4ee377c28451b36ebb821199ecc386bf01ee2421db86d9ada18da9c9bf761`, +`007-binding` +`91e85077e88ea3c503a593755449bb7cce36fac5bd8ac71743fee6449a2c9aa2`, +`008-case` `0f3a9bd29d33f8a9ca5f6b116084209c539eb37120d93d9973c00613358d8c91`, +and `009-landmarks` +`4cd4ca7f973a5f9953818446c7cd7252dae4065bcb4aba8e7b9f423e31c991fb`. +Exact saved-output paths and hashes are in `evidence.json`. + +## Finding + +The source perturbation raised the left posterior calf radius from `0.065` m +to `0.0715` m. At the calf, local +`F=(0,-0.32599068331940423,0.9453729816262723)` and posterior is `-F`. +The frozen strict `forward < 0` selection chose template slots 0, 1, 6, and 7: + +- slot 0: `(-0.7071067811865474,-0.7071067811865474)`, `4.596194` mm; +- slot 1: `(-1,-7.988858113051086e-18)`, `0` mm; +- slot 6: `(0.7071067811865474,-0.7071067811865475)`, `4.596194` mm; +- slot 7: `(-1.4030851643930054e-17,-1)`, `6.5` mm. + +Slot 1 is the nominal lateral planar sample. A binary64 projection residue made +its template forward coordinate slightly negative, so the frozen gate selected +it even though its emitted coordinate displacement rounded to exactly zero. +The recorded L0 analytic error was `9.35e-17` m and full-stencil L2 error was +`2.74e-16` m, both within the frozen `1e-8` tolerance. + +Local L0 response was confined as designed: maximum displacement was `2.228571` +mm at knee-post support, `6.5` mm at calf, and `2.8` mm at ankle approach; the +mid-thigh, knee-pre, knee, ankle, root, and opposite leg remained unchanged. + +Across the 416 L2 vertices with nonzero stencil support from any of the eight +L0 calf-ring controls, signed displacement along calf `-F` was positive at 273, +zero at 143, negative at 0, and at most `4.773528` mm. The posterior support +envelope moved from `0.0546801503` m to `0.0594536780` m, an expansion of +`0.0047735277` m. This is a support-domain envelope across the subdivided calf +neighbourhood, not an exact planar calf section; it demonstrates coherent +supported posterior expansion but does not characterize one cross-sectional +profile or establish anatomy quality. + +## Bounded interpretation and closure + +The zero therefore identifies a measurement-selection defect, not absence of +meaningful posterior L2 response. It does not retroactively pass Baseline005. +If independent review agrees, evidence closure can reuse these same saved +baseline and perturbed meshes: remeasure a tolerance-classified strictly +posterior domain and/or the declared L2 support envelope, recording that as a +later diagnostic. Repeating the unchanged 10-pose collision run would add no +evidence about this measurement defect. + +Independence limit: this analysis began from Main's reported failed metric and +was completed before considering Noether's independent report. + +## Accepted measurement-only closure + +Main accepted the subsequent Baseline007 measurement-only closure after direct +review of the fixed 416-vertex support domain, literal before/after extrema, +all-row pass reduction, and exact comparisons with the preserved 005 geometry. +The exact report is +`/home/ben/.cache/creature-kernel/connected-leg-assembly-007-measurement-closure/measurement-closure.json` +(SHA-256 +`ae1d322e6b43b51708e81b0b3e8224af19cdce17b9ab1c70337cdc73e9f960b1`). +The focused perturbation suite passed 9 tests with 0 failures. + +Within that report, `built_L0` is the perturbed constructor result and +`perturbed_L0` is the evaluator's identical L0 return. They are aliases from +one perturbation regeneration, not independent executions. Likewise, +`execution.body_generation: false` means that no upstream calibrated root was +generated: the calf perturbation geometry was regenerated from the saved 005 +root. No new pose, collision, or render was run. This acceptance closes only +the corrected calf measurement; it does not pass the rejected 005 full run, +accept body anatomy, or establish a whole-character result. diff --git a/experiments/connected-leg-assembly/README.md b/experiments/connected-leg-assembly/README.md new file mode 100644 index 0000000..3bc6185 --- /dev/null +++ b/experiments/connected-leg-assembly/README.md @@ -0,0 +1,250 @@ +# EXP-0003: Connected-leg assembly staging + +Experiment ID: EXP-0003 + +Experiment lifecycle: running + +Evidence closure: open + +Technology outcome: none + +Owner: Main Worker; Overseer provides scoped independent review + +Date started: — + +Date completed: — + +Research questions: Pending the Main decision and detailed protocol + +Related DRs: — + +Related proposal (deferred Layer 3 path: `experiments/connected-leg-assembly/pelvis-foundation-proposal.md`) — Proposed; source003 rejected the shared correction for human admission, no body execution GO. + +Related recipe (deferred Layer 3 path: `experiments/connected-leg-assembly/pelvis-foundation-recipe.md`) — initial law and one shared correction evaluated; source003 failed human source admission, no body admitted. + +Source evidence (deferred Layer 3 path: `experiments/connected-leg-assembly/pelvis-foundation-source-results.md`) — 001/002 closure plus source003; corrected law failed human source admission and existing-topology construction is rejected. + +Successor representation (deferred Layer 3 path: `experiments/connected-leg-assembly/pelvis-boundary-support-proposal.md`) — Proposed Rev2 ten-phase upper-pelvis collar with separate abdomen handoff; fresh review and Main correctness closure complete, unexecuted. + +Successor recipe (deferred Layer 3 path: `experiments/connected-leg-assembly/pelvis-boundary-support-recipe.md`) — Proposed Rev2 shared source law, exact 162/146 topology and binding contract; recipe/review prerequisite complete, capture required before evaluation. + +Successor review (deferred Layer 3 path: `experiments/connected-leg-assembly/pelvis-boundary-support-review.md`) — Rev1 and fresh Rev2 challenges complete; narrow technical findings closed without changing source coefficients or topology. + +## Protocol + +The prepared [protocol](protocol.json) and [inputs](inputs.json) record the +current Main baseline. The baseline stages one common +source/frame/subdivision/binding path from each calibrated L0 root through an +explicit knee and shank to open ankle ports. The protocol remains frozen; this +evidence does not update its JSON values or establish a technology outcome. + +## Question + +Can the current calibrated connected root L0 be staged through the knee and +shank as one evaluated connected surface while reusing source-driven hip frames, +existing subdivision, and automatic hierarchical binding? + +## Hypothesis + +A common leg staging path may extend the connected root coherently through the +knee and shank while preserving source/frame/binding-driven movement of the +displayed evaluated surface. This is untested evidence, not an architecture or +product claim. + +## Decision Impact + +The result may inform the next internal whole-character refinement step. The +leg is an internal milestone; the first integrated whole-character refinement +remains the named Ben checkpoint. + +## Inputs and Fixtures + +Use the immutable roots, matching prior L2 rests, original case/reference +metadata, and prior hip bindings named in [inputs](inputs.json). J remains an +independent pose input; T and K remain the original source points. The +[example brief](example-brief.md) records the appearance scope, not a species +or gait contract. + +## Method + +Stage the common source-driven leg through the knee and shank, including the +angled anthropomorphic K-to-A rest frame, and test automatic hierarchical +binding on the same evaluated connected surface. The stage ends at open ankle +ports: foot-bearing, heel, sole, and paw geometry are not implemented. Do not +add per-case mesh repairs or disconnected display meshes. + +## Environment + +The first capture-tool invocation is recorded below as tool-invalid, not +candidate evidence. Baseline002 rest capture and verification are recorded +below, followed by the Baseline003 and Baseline004 outcomes and the later +Baseline005 immutable run. The original protocol and inputs remain frozen from +before these runs, and the exact source, inputs, protocol, frozen mesh +identities, and managed runtime remain those described by the +[protocol](protocol.json). This Layer 2 checkout performs no experiment +execution or geometry validation. + +## Metrics and Thresholds + +The [protocol](protocol.json) declares topology, source/section, binding, +stencil, intersection, strain, hip-regression, perturbation, and visual checks. +The asymmetric-radius rule does not gate centroid equality with A; anatomy +plausibility remains a separate visual judgment. + +## Reproduction + +The existing runner's prepare/run/verify command syntax is shown below with +new-path placeholders only; this is reproduction syntax, not an execution +outcome: + +```bash +# Placeholders must be fresh absent paths for each reproduction. +trial_python="/home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot/runtime/bin/python" +trial_launcher="/home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot/source/experiments/current-form-surface-preview/surface_preview_launcher.sh" +trial_snapshot="/home/ben/.cache/creature-kernel/connected-leg-assembly-NEW-rest-snapshot" +trial_output="/home/ben/.cache/creature-kernel/connected-leg-assembly-NEW-rest-run" + +PYTHONDONTWRITEBYTECODE=1 CK_CURRENT_FORM_SURFACE_PYTHON="$trial_python" bash "$trial_launcher" experiments/connected-leg-assembly/runner.py prepare --snapshot "$trial_snapshot" --rest-only +PYTHONDONTWRITEBYTECODE=1 CK_CURRENT_FORM_SURFACE_PYTHON="$trial_python" bash "$trial_launcher" "${trial_snapshot}/source/experiments/connected-leg-assembly/runner.py" run --snapshot "$trial_snapshot" --output "$trial_output" --rest-only +PYTHONDONTWRITEBYTECODE=1 CK_CURRENT_FORM_SURFACE_PYTHON="$trial_python" bash "$trial_launcher" "${trial_snapshot}/source/experiments/connected-leg-assembly/runner.py" verify --snapshot "$trial_snapshot" +``` + +The verified focused checker command uses the managed runtime launcher: + +```bash +PYTHONDONTWRITEBYTECODE=1 CK_CURRENT_FORM_SURFACE_PYTHON=/home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot/runtime/bin/python bash /home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot/source/experiments/current-form-surface-preview/surface_preview_launcher.sh -m unittest discover -s experiments/connected-leg-assembly/tests -p test_checks.py -v +``` + +This is checker evidence only; it does not turn the captured or failed +Baselines into candidate acceptance. + +Subsequent focused geometry-building tests use the capture-first entrypoint so +the live test is never executed before its source snapshot. The test file and +optional unittest names are logical experiment paths; the entrypoint resolves +their actual captured paths from the runner manifest rather than assuming a +snapshot layout: + +```bash +PYTHONDONTWRITEBYTECODE=1 CK_CURRENT_FORM_SURFACE_PYTHON=/home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot/runtime/bin/python bash /home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot/source/experiments/current-form-surface-preview/surface_preview_launcher.sh experiments/connected-leg-assembly/captured_tests.py --snapshot /home/ben/.cache/creature-kernel/connected-leg-captured-tests-NEW-snapshot --test-file tests/test_head_construction.py --test-name HeadConstructionTests.test_declared_controls_reach_actual_l0_and_evaluated_l2_surface +``` + +The entrypoint calls the existing runner preparation and verification seams, +runs only the selected captured test script with the manifest-recorded managed +interpreter, verifies the snapshot again, and emits a JSON status/path report. +Its tooling-only bootstrap at +`/home/ben/.cache/creature-kernel/connected-leg-captured-tests-001-snapshot` +passed 4 mocked tests with both verifications passing; no geometry test ran. +The captured runtime and external frozen dependencies remain reused rather +than copied, and the existing manifest explicitly does not claim hermetic OS, +loader, or kernel isolation. + +## Results + +The first capture-tool invocation was tool-invalid, not candidate execution: +the retained paths `/home/ben/.cache/creature-kernel/connected-leg-assembly-001-rest-snapshot` +and `/home/ben/.cache/creature-kernel/connected-leg-assembly-001-rest-run` +record both cases failing construction with `ConstructionError: leg_inputs must +contain both sides and the two shared factors`. No mesh, image, or pose was +generated; the source consumer received the wrong shape, source inputs were +unchanged, and no anatomical verdict or geometry refinement was consumed. The +original runner's top-level status `internal-diagnostic` with exit 0 is not +success; `full_pass: false` and the per-case exceptions are decisive. Old +outputs are preserved. This is a historical 001 record: its `constructor +alignment and runner error propagation underway` and `verification incomplete` +labels apply to that invocation only, not current work. No later exit-0 +verification is claimed here without the exact evidence. +At that time, this note recorded only a tool-invalid invocation and the +generic experiment remained planned/open/none. The following running/open/none +wording belongs to that Baseline002 stage record; it does not replace the +later Baseline005 history below. + +Baseline002 rest capture and run completed with verification passed at +`/home/ben/.cache/creature-kernel/connected-leg-assembly-002-rest-snapshot` and +`/home/ben/.cache/creature-kernel/connected-leg-assembly-002-rest-run`. +Snapshot SHA-256 is +`f3f885444298e7073aaf2831c3070c22487534d6ea67c5bb5fe3e37c49d4fdc0`; the +artifact manifest SHA-256 is +`975f415790b1ae21a49632a41027363f9de8a1fbbbf9e91fad5011a216531dbe`. Both +cases reported base `264v248q` and L2 `4041v3968q`, with no exceptions, +render errors, or drift. Actual body execution occurred, but this is not a +candidate pass. The remaining experiment interpretation is recorded by the +later stage entries below. + +Main directly inspected both rest triptychs and undersides at those exact +paths: the hip, thigh, knee, and shank read as continuous, with no obvious new +seam or gross rest collapse. Retained are the pinched waist, schematic groin, +weak buttock, and faceting; limbs end at open ankles, with no head, arms, or +feet. This is scoped initial static inspection only, not anatomy polish, a +technical pass, or pose acceptance. Main does not request Ben review at this +internal leg milestone. Old 001 outputs remain unchanged. + +Baseline003's actual execution at +`/home/ben/.cache/creature-kernel/connected-leg-assembly-003-pose-snapshot` and +`/home/ben/.cache/creature-kernel/connected-leg-assembly-003-pose-run` exposed +a numeric-guard issue; it was fixed without changing weights, but the run +remains a failed diagnostic outcome, not a candidate pass. Separately, the +captured 52-test suite pass for Baseline004 (test count from the execution +record, not presumed from the run report) is at +`/home/ben/.cache/creature-kernel/connected-leg-assembly-004-checked-snapshot`. +The Baseline004 source run report at +`/home/ben/.cache/creature-kernel/connected-leg-assembly-004-checked-run` +records an actual run with runtime integration failures: fourth-pose mirrored +`15_15` label/meaning metadata was forwarded as angles; bent render bounds +were left at rest-only bounds because they finalize after the pose loop; +pose collision checks were unavailable; and perturbations were not reached +after the earlier pose error. `perturbations.py` was captured, so it was not a +missing module. The runner is now fixed; no rerun success is claimed. At that +stage these outcomes left the experiment running/open/none; Baseline005 is the +later immutable run recorded below. + +Baseline005 is now an immutable finished run at +`/home/ben/.cache/creature-kernel/connected-leg-assembly-005-integrated-snapshot` +and `/home/ben/.cache/creature-kernel/connected-leg-assembly-005-integrated-run`; +no restart run was made. It captured 59 tests with 0 skips; the full runner +exited 1 on an anthropomorphic calf metric-only reject. All 10 pose checks +completed with full `315m` total-pair coverage and 0 hits. Human perturbations +were 3/3 pass; anthropomorphic perturbations were 2/3, with the signed-calf +metric failing 0 among positives while analytic L2 matched. There were no +exceptions or render errors, and postverify passed. Luna and Sol are +investigating read-only; this does not claim the measurement bug resolved. +Main personally viewed all 10 final surface triptychs at the 005 run, with no +obvious tear, seam, or gross collapse; knees remain schematic/angular and the +inherited waist/chest form defects persist. This is recovered render +diagnostic evidence, not polished body or all-pose acceptance. + +## Analysis + +Interpretation remains bounded. Baseline005 records the latest captured checks +and perturbations, including an anthropomorphic metric-only reject under +read-only investigation; these execution outcomes do not establish anatomy, +technical, pose, or product acceptance. + +## Limitations + +This is a bounded leg-staging experiment, not whole-body architecture, a +supported morphology promise, a detailed anatomy study, or the named Ben +checkpoint. Human and loose wolf-like humanoid appearance references share the +common pipeline. The human plantigrade arrangement is a provisional staging +hypothesis; the anthropomorphic case uses an angled shank for its coarse +digitigrade target. Both stop at open ankles, and foot-bearing geometry is not +yet implemented. + +Saved-root loading isolates this connection and binding test; it is not the +final source-to-whole-character path. Before the whole-character checkpoint, +assembly must regenerate the root from its recorded source construction and +inputs and demonstrate that the rebuild matches the intended baseline. These +saved meshes must not become hidden authored inputs. This obligation is +preserved here without regenerating the root now or introducing a new +framework. + +## Conclusion + +Running with open evidence closure and no technology outcome. The tool-invalid +invocation remains historical; Baseline002 is execution evidence, not a +candidate pass, and the protocol remains frozen. + +## Recommended Follow-up + +Complete the remaining checks and source perturbations only within the Active +runway, then stop for the named whole-character checkpoint or a retained-human +boundary. diff --git a/experiments/connected-leg-assembly/arm-inputs.json b/experiments/connected-leg-assembly/arm-inputs.json new file mode 100644 index 0000000..aa4208e --- /dev/null +++ b/experiments/connected-leg-assembly/arm-inputs.json @@ -0,0 +1,76 @@ +{ + "schema": "creature-kernel.connected-leg-assembly-arm-inputs.v1", + "status": "initial-candidate-inputs-frozen", + "coordinate_convention": "metres; global X lateral, +Y up, +Z front", + "source_ownership": "J is shoulders.{side}.arm_origin in the original calibrated source case; it is not an arm-input field", + "budget": { + "initial_candidate_count": 1, + "shared_correction_max": 1, + "correction_condition": "only an evidence-justified shared correction after first actual-surface evidence", + "per_case_repairs": false, + "input_retuning_before_first_surface": false, + "alternative_constructions": false + }, + "cases": [ + { + "case_id": "calibrated_ordinary_human", + "sides": { + "left": { + "E": [-0.485, 0.365, 0.0], + "W": [-0.705, 0.285, 0.010], + "radii": { + "upper": [0.052, 0.054], + "elbow": [0.040, 0.043], + "forearm": [0.045, 0.048], + "wrist": [0.030, 0.034], + "palm": [0.043, 0.033] + }, + "hand_length": 0.120 + }, + "right": { + "E": [0.485, 0.365, 0.0], + "W": [0.705, 0.285, 0.010], + "radii": { + "upper": [0.052, 0.054], + "elbow": [0.040, 0.043], + "forearm": [0.045, 0.048], + "wrist": [0.030, 0.034], + "palm": [0.043, 0.033] + }, + "hand_length": 0.120 + } + }, + "status_note": "bounded masculine-direction coarse staging hypothesis; not anthropometry" + }, + { + "case_id": "calibrated_upright_anthropomorphic", + "sides": { + "left": { + "E": [-0.500, 0.355, -0.005], + "W": [-0.735, 0.265, 0.015], + "radii": { + "upper": [0.055, 0.058], + "elbow": [0.042, 0.045], + "forearm": [0.048, 0.052], + "wrist": [0.032, 0.036], + "palm": [0.046, 0.036] + }, + "hand_length": 0.130 + }, + "right": { + "E": [0.500, 0.355, -0.005], + "W": [0.735, 0.265, 0.015], + "radii": { + "upper": [0.055, 0.058], + "elbow": [0.042, 0.045], + "forearm": [0.048, 0.052], + "wrist": [0.032, 0.036], + "palm": [0.046, 0.036] + }, + "hand_length": 0.130 + } + }, + "status_note": "same generic construction with provisional loose wolf-like proportions; no species branch" + } + ] +} diff --git a/experiments/connected-leg-assembly/arm_construction.py b/experiments/connected-leg-assembly/arm_construction.py new file mode 100644 index 0000000..330bae4 --- /dev/null +++ b/experiments/connected-leg-assembly/arm_construction.py @@ -0,0 +1,539 @@ +"""Bounded connected coarse-arm construction on named root arm ports.""" +from __future__ import annotations + +from collections.abc import Mapping +import copy +import math +from typing import Any + + +_SIDES = ("left", "right") +_PORTS = {side: f"port.{side}_arm" for side in _SIDES} +_OWNERS = {side: f"domain.{side}_arm" for side in _SIDES} +_RADII = ("upper", "elbow", "forearm", "wrist", "palm") +_INPUT_KEYS = frozenset(("E", "W", "radii", "hand_length")) +_OPTIONAL_INPUT_KEYS = frozenset(("hand_terminal_scale",)) +_DEFAULT_HAND_TERMINAL_SCALE = 0.55 +_TOL = 1.0e-8 +_FRAME_TOL = 1.0e-7 +_AREA_TOL = 1.0e-12 + + +class ArmConstructionError(ValueError): + """Raised when the bounded arm candidate cannot be admitted.""" + + +def _fail(message: str) -> None: + raise ArmConstructionError(message) + + +def _mapping(value: Any, where: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping): + _fail(f"{where} must be a mapping") + return value + + +def _finite(value: Any, where: str) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float)): + _fail(f"{where} must be a finite real number") + result = float(value) + if not math.isfinite(result): + _fail(f"{where} must be a finite real number") + return result + + +def _positive(value: Any, where: str) -> float: + result = _finite(value, where) + if result <= 0.0: + _fail(f"{where} must be positive") + return result + + +def _vector(value: Any, where: str) -> tuple[float, float, float]: + if type(value) not in (list, tuple) or len(value) != 3: + _fail(f"{where} must be a three-component vector") + return tuple(_finite(item, f"{where}[{axis}]") + for axis, item in enumerate(value)) # type: ignore[return-value] + + +def _add(a: tuple[float, float, float], b: tuple[float, float, float]) -> tuple[float, float, float]: + return tuple(a[i] + b[i] for i in range(3)) # type: ignore[return-value] + + +def _sub(a: tuple[float, float, float], b: tuple[float, float, float]) -> tuple[float, float, float]: + return tuple(a[i] - b[i] for i in range(3)) # type: ignore[return-value] + + +def _scale(v: tuple[float, float, float], factor: float) -> tuple[float, float, float]: + return tuple(factor * item for item in v) # type: ignore[return-value] + + +def _dot(a: tuple[float, float, float], b: tuple[float, float, float]) -> float: + return sum(a[i] * b[i] for i in range(3)) + + +def _cross(a: tuple[float, float, float], b: tuple[float, float, float]) -> tuple[float, float, float]: + return (a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0]) + + +def _norm(v: tuple[float, float, float]) -> float: + return math.sqrt(_dot(v, v)) + + +def _normalise(v: tuple[float, float, float], where: str) -> tuple[float, float, float]: + length = _norm(v) + if not math.isfinite(length) or length <= _TOL: + _fail(f"{where} must have positive finite length") + return _scale(v, 1.0 / length) + + +def _lerp(a: tuple[float, float, float], b: tuple[float, float, float], fraction: float) -> tuple[float, float, float]: + return _add(_scale(a, 1.0 - fraction), _scale(b, fraction)) + + +def _frame(tangent: Any) -> dict[str, tuple[float, float, float]]: + """Return the settled +Y-projected right-handed frame.""" + t = _normalise(_vector(tangent, "tangent"), "tangent") + up = (0.0, 1.0, 0.0) + u = _sub(up, _scale(t, _dot(up, t))) + u = _normalise(u, "+Y projection") + f = _normalise(_cross(t, u), "frame forward") + if _dot(f, (0.0, 0.0, 1.0)) < 0.0: + u, f = _scale(u, -1.0), _scale(f, -1.0) + if abs(_dot(t, u)) > _FRAME_TOL or abs(_dot(t, f)) > _FRAME_TOL or abs(_dot(u, f)) > _FRAME_TOL: + _fail("derived arm frame is not orthogonal") + if _dot(_cross(t, u), f) < 1.0 - _FRAME_TOL: + _fail("derived arm frame is not right-handed") + return {"tangent": t, "U": u, "F": f} + + +def _edge_key(a: int, b: int) -> tuple[int, int]: + return (a, b) if a < b else (b, a) + + +def _edge_uses(quads: list[tuple[int, int, int, int]]) -> dict[tuple[int, int], list[tuple[int, int, int]]]: + uses: dict[tuple[int, int], list[tuple[int, int, int]]] = {} + for face_index, face in enumerate(quads): + for corner, left in enumerate(face): + right = face[(corner + 1) % 4] + uses.setdefault(_edge_key(left, right), []).append((face_index, left, right)) + return uses + + +def _quads(raw: Any, count: int, where: str) -> list[tuple[int, int, int, int]]: + if type(raw) not in (list, tuple) or not raw: + _fail(f"{where} must be a non-empty sequence") + result = [] + for index, face in enumerate(raw): + if type(face) not in (list, tuple) or len(face) != 4 or any(type(v) is not int for v in face): + _fail(f"{where}[{index}] must contain four integer indices") + checked = tuple(face) + if len(set(checked)) != 4 or any(v < 0 or v >= count for v in checked): + _fail(f"{where}[{index}] has invalid indices") + result.append(checked) + return result # type: ignore[return-value] + + +def _loops(raw: Any, count: int, where: str) -> dict[str, list[int]]: + value = _mapping(raw, where) + result: dict[str, list[int]] = {} + for name, loop in value.items(): + if type(name) is not str or type(loop) not in (list, tuple) or len(loop) < 3: + _fail(f"{where} contains an invalid named loop") + checked = list(loop) + if len(set(checked)) != len(checked) or any(type(v) is not int or v < 0 or v >= count for v in checked): + _fail(f"{where}.{name} contains invalid indices") + result[name] = checked + return result + + +def _topology(vertices: list[tuple[float, float, float]], quads: list[tuple[int, int, int, int]], + loops: Mapping[str, list[int]], where: str) -> None: + uses = _edge_uses(quads) + if any(len(rows) not in (1, 2) for rows in uses.values()): + _fail(f"{where} has a non-manifold edge") + if any(len(rows) == 2 and rows[0][1:] == rows[1][1:] for rows in uses.values()): + _fail(f"{where} has an orientation conflict") + declared = set() + for name, loop in loops.items(): + for i, left in enumerate(loop): + edge = _edge_key(left, loop[(i + 1) % len(loop)]) + if len(uses.get(edge, ())) != 1 or edge in declared: + _fail(f"{where} loop {name!r} is not a unique boundary") + declared.add(edge) + boundary = {edge for edge, rows in uses.items() if len(rows) == 1} + if boundary != declared: + _fail(f"{where} named loops do not cover its boundary") + adjacency = {i: set() for i in range(len(vertices))} + for left, right in uses: + adjacency[left].add(right) + adjacency[right].add(left) + seen, pending = {0}, [0] + while pending: + current = pending.pop() + for neighbour in adjacency[current]: + if neighbour not in seen: + seen.add(neighbour) + pending.append(neighbour) + if len(seen) != len(vertices): + _fail(f"{where} is disconnected") + + +def _stencils(raw: Any, vertex_count: int) -> list[list[list[float | int]]]: + if type(raw) not in (list, tuple) or len(raw) != vertex_count: + _fail("base_mesh.base_stencils must cover every base vertex") + result = [] + for row_index, row in enumerate(raw): + if type(row) not in (list, tuple) or not row: + _fail(f"base_mesh.base_stencils[{row_index}] is empty") + checked, previous, total = [], -1, 0.0 + for term in row: + if type(term) not in (list, tuple) or len(term) != 2 or type(term[0]) is not int: + _fail(f"base_mesh.base_stencils[{row_index}] is malformed") + source, coefficient = term[0], _finite(term[1], "stencil coefficient") + if source <= previous or source < 0 or coefficient <= 0.0: + _fail(f"base_mesh.base_stencils[{row_index}] is invalid") + checked.append([source, coefficient]) + previous, total = source, total + coefficient + if abs(total - 1.0) > 1.0e-9: + _fail(f"base_mesh.base_stencils[{row_index}] does not partition unity") + result.append(checked) + return result + + +def _source_rows(source_case: Any) -> dict[str, dict[str, Any]]: + case = _mapping(source_case, "source_case") + components = _mapping(case.get("components"), "source_case.components") + result: dict[str, dict[str, Any]] = {} + for side in _SIDES: + prefix = f"shoulders.{side}." + def point(name: str) -> tuple[float, float, float]: + return tuple(_finite(components.get(f"{prefix}{name}.{axis}"), + f"source_case.components.{prefix}{name}.{axis}") + for axis in "xyz") # type: ignore[return-value] + result[side] = { + "J": point("arm_origin"), + "start_lateral": _positive(components.get(f"{prefix}start_lateral"), f"{prefix}start_lateral"), + "start_up": _positive(components.get(f"{prefix}start_up"), f"{prefix}start_up"), + "start_forward": _positive(components.get(f"{prefix}start_forward"), f"{prefix}start_forward"), + } + return result + + +def _input_rows(arm_inputs: Any) -> dict[str, dict[str, Any]]: + value = _mapping(arm_inputs, "arm_inputs") + if set(value) != set(_SIDES): + _fail("arm_inputs must contain exactly left and right") + result = {} + for side in _SIDES: + row = _mapping(value[side], f"arm_inputs.{side}") + if not _INPUT_KEYS.issubset(row) or set(row) - (_INPUT_KEYS | _OPTIONAL_INPUT_KEYS): + _fail(f"arm_inputs.{side} has unsupported or missing fields") + radii = _mapping(row["radii"], f"arm_inputs.{side}.radii") + if set(radii) != set(_RADII): + _fail(f"arm_inputs.{side}.radii has unsupported or missing fields") + parsed_radii = {} + for name in _RADII: + pair = radii[name] + if type(pair) not in (list, tuple) or len(pair) != 2: + _fail(f"arm_inputs.{side}.radii.{name} must be [up, forward]") + parsed_radii[name] = (_positive(pair[0], f"{side}.{name}.up"), + _positive(pair[1], f"{side}.{name}.forward")) + result[side] = {"E": _vector(row["E"], f"arm_inputs.{side}.E"), + "W": _vector(row["W"], f"arm_inputs.{side}.W"), + "radii": parsed_radii, + "hand_length": _positive(row["hand_length"], f"arm_inputs.{side}.hand_length"), + "hand_terminal_scale": _positive( + row.get("hand_terminal_scale", _DEFAULT_HAND_TERMINAL_SCALE), + f"arm_inputs.{side}.hand_terminal_scale")} + return result + + +def _port(base: Mapping[str, Any], side: str, source: Mapping[str, Any], + vertices: list[tuple[float, float, float]], loops: Mapping[str, list[int]]) -> tuple[ + list[int], tuple[float, float, float], list[tuple[float, float]]]: + name = _PORTS[side] + loop = loops.get(name) + if loop is None or len(loop) != 8: + _fail(f"base_mesh.loops.{name} must be an eight-vertex arm loop") + points = [vertices[index] for index in loop] + P = tuple(sum(point[axis] for point in points) / 8.0 for axis in range(3)) + J = source["J"] + sign = -1.0 if side == "left" else 1.0 + expected_P = (J[0] + sign * source["start_lateral"], J[1], J[2]) + if any(abs(P[axis] - expected_P[axis]) > _TOL for axis in range(3)): + _fail(f"source_case shoulders.{side} does not own the actual root arm port") + half_up, forward = 0.5 * source["start_up"], source["start_forward"] + expected_phase = {(-1.0, -1.0), (0.0, -1.0), (1.0, -1.0), + (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), + (-1.0, 1.0), (-1.0, 0.0)} + phase = [] + for point in points: + if abs(point[0] - P[0]) > _TOL: + _fail(f"{name} is not in its source-owned lateral plane") + pair = ((point[1] - P[1]) / half_up, (point[2] - P[2]) / forward) + snapped = tuple(0.0 if abs(value) <= _TOL else (1.0 if value > 0.0 else -1.0) + for value in pair) + if any(abs(pair[i] - snapped[i]) > _TOL for i in range(2)): + _fail(f"{name} does not match source start_up/start_forward") + phase.append(snapped) # type: ignore[arg-type] + if set(phase) != expected_phase: + _fail(f"{name} does not contain the expected source-owned eight-point phase") + return list(loop), P, phase + + +def _loop_winding(quads: list[tuple[int, int, int, int]], loop: list[int], side: str) -> int: + uses = _edge_uses(quads) + signs = [] + for i, left in enumerate(loop): + right = loop[(i + 1) % 8] + rows = uses.get(_edge_key(left, right), ()) + if len(rows) != 1: + _fail(f"{side} arm loop edge is not a unique boundary") + signs.append(1 if rows[0][1:] == (left, right) else -1) + if len(set(signs)) != 1: + _fail(f"{side} arm loop winding is inconsistent") + return signs[0] + + +def _ring(center: tuple[float, float, float], frame: Mapping[str, tuple[float, float, float]], + radii: tuple[float, float], phase: list[tuple[float, float]]) -> list[tuple[float, float, float]]: + return [_add(center, _add(_scale(frame["U"], uv[0] * radii[0]), + _scale(frame["F"], uv[1] * radii[1]))) + for uv in phase] + + +def _frame_phase(global_phase: list[tuple[float, float]], source: Mapping[str, Any], + frame: Mapping[str, tuple[float, float, float]]) -> list[tuple[float, float]]: + """Project the actual global-Y/Z port phase into the initial arm frame.""" + half_up = 0.5 * source["start_up"] + forward = source["start_forward"] + offsets = [(0.0, pair[0] * half_up, pair[1] * forward) for pair in global_phase] + projected = [(_dot(offset, frame["U"]), _dot(offset, frame["F"])) + for offset in offsets] + scales = (max(abs(pair[0]) for pair in projected), + max(abs(pair[1]) for pair in projected)) + if min(scales) <= _TOL: + _fail("actual arm port cannot define both section phase axes") + return [(pair[0] / scales[0], pair[1] / scales[1]) for pair in projected] + + +def _band(source: list[int], target: list[int], orientation: int) -> list[tuple[int, int, int, int]]: + result = [] + for i in range(8): + j = (i + 1) % 8 + result.append((source[j], source[i], target[i], target[j]) if orientation == 1 + else (source[i], source[j], target[j], target[i])) + return result + + +def _cap(ring: list[int], centre: int, orientation: int) -> list[tuple[int, int, int, int]]: + faces = [(ring[0], ring[1], ring[2], centre), + (ring[2], ring[3], ring[4], centre), + (ring[4], ring[5], ring[6], centre), + (ring[6], ring[7], ring[0], centre)] + return [tuple(reversed(face)) for face in faces] if orientation == 1 else faces + + +def _face_ok(vertices: list[list[float]], face: tuple[int, int, int, int]) -> bool: + p = [tuple(vertices[index]) for index in face] + first = _cross(_sub(p[1], p[0]), _sub(p[2], p[0])) + second = _cross(_sub(p[2], p[0]), _sub(p[3], p[0])) + return _norm(first) > _AREA_TOL and _norm(second) > _AREA_TOL and _dot(first, second) > 0.0 + + +def build(base_mesh: Mapping[str, Any], source_case: Mapping[str, Any], + arm_inputs: Mapping[str, Any]) -> dict[str, Any]: + """Attach bilateral source-owned coarse arms; introduce no binding.""" + base = _mapping(base_mesh, "base_mesh") + required = {"vertices", "quads", "face_owners", "control_owners", "loops", + "base_stencils", "frames", "metadata"} + if not required.issubset(base) or base.get("level") != 0: + _fail("base_mesh must be a connected L0 mesh") + vertices = [_vector(point, f"base_mesh.vertices[{i}]") for i, point in enumerate(base["vertices"])] + quads = _quads(base["quads"], len(vertices), "base_mesh.quads") + loops = _loops(base["loops"], len(vertices), "base_mesh.loops") + if not set(_PORTS.values()).issubset(loops): + _fail("base_mesh lacks the two named arm ports") + if len(base["face_owners"]) != len(quads) or len(base["control_owners"]) != len(vertices): + _fail("base_mesh owner arrays do not match its geometry") + _topology(vertices, quads, loops, "base_mesh") + stencils = _stencils(base["base_stencils"], len(vertices)) + sources, inputs = _source_rows(source_case), _input_rows(arm_inputs) + base_vertex_count, base_face_count = len(vertices), len(quads) + output_vertices = [list(point) for point in vertices] + output_quads = [list(face) for face in quads] + output_face_owners = list(base["face_owners"]) + output_control_owners = list(base["control_owners"]) + output_loops = {name: list(loop) for name, loop in loops.items() + if name not in _PORTS.values()} + metadata = copy.deepcopy(dict(_mapping(base["metadata"], "base_mesh.metadata"))) + metadata["arms"] = {} + base_owners = list(metadata.get("base_control_owners", base["control_owners"])) + if len(base_owners) != base_vertex_count: + _fail("base_mesh.metadata.base_control_owners does not match its vertices") + + for side in _SIDES: + source_loop, P, global_phase = _port(base, side, sources[side], vertices, loops) + J, E, W = sources[side]["J"], inputs[side]["E"], inputs[side]["W"] + upper_t = _normalise(_sub(E, P), f"{side} P-to-E") + fore_t = _normalise(_sub(W, E), f"{side} E-to-W") + if (side == "left" and (E[0] >= P[0] or W[0] >= E[0])) or \ + (side == "right" and (E[0] <= P[0] or W[0] <= E[0])): + _fail(f"{side} arm must progress outward from P through E to W") + collar_center = _add(P, _scale(upper_t, 0.6 * _norm(_sub(P, J)))) + hand_t = fore_t + hand_length = inputs[side]["hand_length"] + centres = [ + ("upper_belly", _lerp(P, E, 0.35)), + ("pre_elbow", _lerp(P, E, 0.85)), + ("elbow", E), + ("post_elbow", _lerp(E, W, 0.15)), + ("forearm_belly", _lerp(E, W, 0.45)), + ("pre_wrist", _lerp(E, W, 0.85)), + ("wrist", W), + ("palm", _add(W, _scale(hand_t, 0.30 * hand_length))), + ("knuckle", _add(W, _scale(hand_t, 0.68 * hand_length))), + ("terminal", _add(W, _scale(hand_t, 0.92 * hand_length))), + ] + radii = inputs[side]["radii"] + section_radii = [ + radii["upper"], + tuple((1.0 - 0.70) * radii["upper"][i] + 0.70 * radii["elbow"][i] for i in range(2)), + radii["elbow"], + tuple(0.5 * (radii["elbow"][i] + radii["forearm"][i]) for i in range(2)), + radii["forearm"], + tuple(0.25 * radii["forearm"][i] + 0.75 * radii["wrist"][i] for i in range(2)), + radii["wrist"], radii["palm"], + tuple(1.03 * value for value in radii["palm"]), + tuple(inputs[side]["hand_terminal_scale"] * value for value in radii["palm"]), + ] + upper_frame = _frame(upper_t) + phase = _frame_phase(global_phase, sources[side], upper_frame) + elbow_frame = _frame(_add(upper_t, fore_t)) + frames = [upper_frame, upper_frame, elbow_frame, + _frame(fore_t), _frame(fore_t), _frame(fore_t), + _frame(fore_t), _frame(hand_t), _frame(hand_t), _frame(hand_t)] + orientation = _loop_winding(quads, source_loop, side) + new_vertices, new_faces = [], [] + ring_indices: dict[str, list[int]] = {} + + collar = [] + shift = _sub(collar_center, P) + for source_index in source_loop: + index = len(output_vertices) + output_vertices.append(list(_add(vertices[source_index], shift))) + output_control_owners.append(_OWNERS[side]) + base_owners.append(_OWNERS[side]) + collar.append(index) + new_vertices.append(index) + ring_indices["collar"] = collar + + for (name, centre), radius, frame in zip(centres, section_radii, frames): + indices = [] + for point in _ring(centre, frame, radius, phase): + index = len(output_vertices) + output_vertices.append(list(point)) + output_control_owners.append(_OWNERS[side]) + base_owners.append(_OWNERS[side]) + indices.append(index) + new_vertices.append(index) + ring_indices[name] = indices + + cap_center = _add(W, _scale(hand_t, hand_length)) + cap_index = len(output_vertices) + output_vertices.append(list(cap_center)) + output_control_owners.append(_OWNERS[side]) + base_owners.append(_OWNERS[side]) + new_vertices.append(cap_index) + + sequence = [("port", source_loop), ("collar", collar)] + [ + (name, ring_indices[name]) for name, _ in centres] + face_ranges = {} + for (source_name, source_ring), (target_name, target_ring) in zip(sequence, sequence[1:]): + start = len(output_quads) + faces = _band(source_ring, target_ring, orientation) + output_quads.extend([list(face) for face in faces]) + output_face_owners.extend([_OWNERS[side]] * len(faces)) + indices = list(range(start, start + len(faces))) + face_ranges[f"{source_name}_to_{target_name}"] = indices + new_faces.extend(indices) + start = len(output_quads) + faces = _cap(ring_indices["terminal"], cap_index, orientation) + output_quads.extend([list(face) for face in faces]) + output_face_owners.extend([_OWNERS[side]] * len(faces)) + cap_faces = list(range(start, start + len(faces))) + face_ranges["terminal_cap"] = cap_faces + new_faces.extend(cap_faces) + if any(not _face_ok(output_vertices, tuple(output_quads[index])) for index in new_faces): + _fail(f"{side} arm contains a degenerate or folded quad") + + metadata["arms"][side] = { + "owner": _OWNERS[side], "J_source": f"shoulders.{side}.arm_origin", + "J": list(J), "P": list(P), "E": list(E), "W": list(W), + "bone_lengths": {"upper_J_E": _norm(_sub(E, J)), "visible_P_E": _norm(_sub(E, P)), + "forearm_E_W": _norm(_sub(W, E))}, + "source_port": {"name": _PORTS[side], "indices": source_loop, + "start_lateral": sources[side]["start_lateral"], + "full_up_span": sources[side]["start_up"], + "full_forward_span": 2.0 * sources[side]["start_forward"], + "global_yz_phase": [list(pair) for pair in global_phase], + "section_frame_phase": [list(pair) for pair in phase]}, + "collar": {"fraction_of_P_J": 0.6, "centre": list(collar_center), + "indices": collar, "exact_port_translation": True}, + "sections": [{"name": name, "centre": list(centre), "indices": ring_indices[name], + "radii_up_forward": list(radius), + "frame": {key: list(value) for key, value in frame.items()}} + for (name, centre), radius, frame in zip(centres, section_radii, frames)], + "cap": {"centre": list(cap_center), "vertex": cap_index, "faces": cap_faces}, + "hand_terminal_scale": { + "value": inputs[side]["hand_terminal_scale"], + "unit": "unitless", + "role": "terminal station palm-radius scale", + "source_lineage": f"arm_inputs.{side}.hand_terminal_scale", + "historical_default": _DEFAULT_HAND_TERMINAL_SCALE, + }, + "new_vertex_indices": new_vertices, "new_face_indices": new_faces, + "face_owner_ranges": face_ranges, "winding": orientation, + "binding": "not implemented; deferred nine-column D0/D1/D2 plan is recorded in arm-stage.md", + } + + metadata["base_control_owners"] = base_owners + metadata["base_vertex_count"] = len(output_vertices) + metadata["level"] = 0 + output = { + "schema": "creature-kernel.connected-leg-assembly-arm-mesh.v1", + "level": 0, "vertices": output_vertices, "quads": output_quads, + "face_owners": output_face_owners, "control_owners": output_control_owners, + "loops": output_loops, + "base_stencils": stencils + [[[index, 1.0]] for index in range(base_vertex_count, len(output_vertices))], + "frames": copy.deepcopy(base["frames"]), "metadata": metadata, + } + checked_vertices = [_vector(point, "output vertex") for point in output_vertices] + checked_quads = _quads(output_quads, len(output_vertices), "output.quads") + _topology(checked_vertices, checked_quads, output_loops, "output") + if output_vertices[:base_vertex_count] != [list(point) for point in vertices] or \ + output_quads[:base_face_count] != [list(face) for face in quads]: + _fail("output changed the inherited geometry prefix") + return output + + +def evaluate(mesh: Mapping[str, Any], levels: int = 2) -> list[dict[str, Any]]: + """Delegate to the current generic connected-leg Catmull--Clark evaluator.""" + if type(levels) is not int or levels < 0 or levels > 2: + _fail("levels must be an integer from zero through two") + metadata = _mapping(mesh.get("metadata"), "mesh.metadata") if isinstance(mesh, Mapping) else {} + if not isinstance(metadata.get("arms"), Mapping): + _fail("mesh must be an arm-construction L0 output") + try: + import construction + return construction.evaluate(mesh, levels=levels) + except Exception as exc: + if isinstance(exc, ArmConstructionError): + raise + raise ArmConstructionError(f"generic evaluator rejected arm output: {exc}") from exc + + +__all__ = ["ArmConstructionError", "build", "evaluate"] diff --git a/experiments/connected-leg-assembly/binding.py b/experiments/connected-leg-assembly/binding.py new file mode 100644 index 0000000..742a04e --- /dev/null +++ b/experiments/connected-leg-assembly/binding.py @@ -0,0 +1,2027 @@ +"""Bounded source-station binding for the connected-leg staging experiment. + +This module consumes the L0/L2 meshes produced by ``construction.py``. It +does not construct geometry or infer ownership from labels. The L0 mesh is +expected to contain the exact 152-vertex root prefix followed by seven +eight-vertex station rings for each side. The construction metadata must +expose those rings explicitly under one of +``metadata["chains"][side]["sections"]``:: + + metadata["chains"][side]["sections"] = [ + {"name": ..., "indices": [eight L0 indices], "centre": [...]}, ... + ] + +The section names and order are the construction contract. This binder does +not regenerate station geometry or infer ownership from labels. The rest L2 +mesh supplies the actual ``base_stencils`` used to propagate the five leg +weights, or the nine weights when source-owned arm metadata is present. +""" +from __future__ import annotations + +import copy +import math +from collections.abc import Mapping +from numbers import Real +from typing import Any + +import numpy as np + + +_SIDES = ("left", "right") +_LEG_JOINT_ORDER = ("pelvis", "left_hip", "left_knee", "right_hip", "right_knee") +_LEG_WEIGHT_COLUMNS = ("pelvis", "left_thigh", "left_shank", "right_thigh", "right_shank") +_ARM_JOINT_ORDER = (*_LEG_JOINT_ORDER, + "left_shoulder", "left_elbow", "right_shoulder", "right_elbow") +_ARM_WEIGHT_COLUMNS = (*_LEG_WEIGHT_COLUMNS, + "left_upper_arm", "left_forearm", + "right_upper_arm", "right_forearm") +_HEAD_JOINT_ORDER = (*_LEG_JOINT_ORDER, "neck") +_HEAD_WEIGHT_COLUMNS = (*_LEG_WEIGHT_COLUMNS, "neck") +_ARM_HEAD_JOINT_ORDER = (*_ARM_JOINT_ORDER, "neck") +_ARM_HEAD_WEIGHT_COLUMNS = (*_ARM_WEIGHT_COLUMNS, "neck") +_JOINT_ORDER = _LEG_JOINT_ORDER +_WEIGHT_COLUMNS = _LEG_WEIGHT_COLUMNS +_STATION_NAMES = ( + "mid_thigh", + "knee_pre_support", + "knee", + "knee_post_support", + "calf", + "ankle_approach", + "ankle", +) +_SOURCE_STATION_IDS = (".70TK", ".90TK", "K", "K+.12KA", "K+.35KA", "K+.72KA", "A") +_STATION_SHANK_WEIGHTS = (0.0, 0.0, 0.5, 1.0, 1.0, 1.0, 1.0) +_ROOT_VERTEX_COUNT = 152 +_STATION_COUNT = len(_STATION_NAMES) +_RING_VERTEX_COUNT = 8 +_TOLERANCE = 1.0e-12 +_FRAME_TOLERANCE = 1.0e-10 +_CONSTRUCTION_COORDINATE_TOLERANCE = 1.0e-8 +_SUPPORT_MULTIPLIER = 1.2 +_MID_THIGH_FRACTION = 0.70 +_CALF_FRACTION = 0.35 +_ANKLE_APPROACH_FRACTION = 0.72 +_TAIL_SUPPORT_OWN = 0.55 +_TAIL_SUPPORT_OTHER = 0.15 +_ARM_SECTION_NAMES = ( + "upper_belly", "pre_elbow", "elbow", "post_elbow", "forearm_belly", + "pre_wrist", "wrist", "palm", "knuckle", "terminal", +) + + +def _binding_layout(has_arms: bool, has_head: bool) -> tuple[tuple[str, ...], tuple[str, ...]]: + if has_arms and has_head: + return _ARM_HEAD_JOINT_ORDER, _ARM_HEAD_WEIGHT_COLUMNS + if has_arms: + return _ARM_JOINT_ORDER, _ARM_WEIGHT_COLUMNS + if has_head: + return _HEAD_JOINT_ORDER, _HEAD_WEIGHT_COLUMNS + return _LEG_JOINT_ORDER, _LEG_WEIGHT_COLUMNS + + +def _fail(message: str) -> None: + raise ValueError(message) + + +def _mapping(value: Any, where: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping): + _fail(f"{where} must be a mapping") + return value + + +def _number(value: Any, where: str) -> float: + if isinstance(value, bool) or not isinstance(value, Real): + _fail(f"{where} must be a finite number") + result = float(value) + if not math.isfinite(result): + _fail(f"{where} must be a finite number") + return result + + +def _vector(value: Any, where: str) -> list[float]: + if not isinstance(value, (list, tuple)) or len(value) != 3: + _fail(f"{where} must be a three-component vector") + return [_number(item, f"{where}[{index}]") + for index, item in enumerate(value)] + + +def _integer(value: Any, where: str) -> int: + if isinstance(value, bool) or not isinstance(value, int): + _fail(f"{where} must be an integer index") + return value + + +def _vertices(mesh: Mapping[str, Any], where: str) -> list[list[float]]: + raw = mesh.get("vertices") + if not isinstance(raw, (list, tuple)) or not raw: + _fail(f"{where}.vertices must be a non-empty list") + return [_vector(point, f"{where}.vertices[{index}]") + for index, point in enumerate(raw)] + + +def _quads(mesh: Mapping[str, Any], count: int, where: str) -> list[list[int]]: + raw = mesh.get("quads") + if not isinstance(raw, (list, tuple)): + _fail(f"{where}.quads must be a list") + result: list[list[int]] = [] + for quad_index, quad in enumerate(raw): + if not isinstance(quad, (list, tuple)) or len(quad) != 4: + _fail(f"{where}.quads[{quad_index}] must contain four indices") + checked = [_integer(value, f"{where}.quads[{quad_index}][{slot}]") + for slot, value in enumerate(quad)] + if any(value < 0 or value >= count for value in checked): + _fail(f"{where}.quads[{quad_index}] contains an out-of-range vertex") + result.append(checked) + if not result: + _fail(f"{where}.quads must not be empty") + return result + + +def _check_weight_bounds(weights: np.ndarray, where: str) -> None: + if not np.all(np.isfinite(weights)): + _fail(f"{where} must be finite") + # Numeric guard recovery matching the prior baseline binding: this is a + # validation tolerance only, not a binding-method retune. Do not clamp + # or renormalize the source/stencil result. + if np.any(weights < -_TOLERANCE) or np.any(weights > 1.0 + _TOLERANCE): + _fail(f"{where} contains a weight outside [-{_TOLERANCE}, 1 + {_TOLERANCE}]") + if not np.all(np.abs(np.sum(weights, axis=1) - 1.0) <= _TOLERANCE): + _fail(f"{where} do not partition unity") + + +def _weight_matrix(value: Any, rows: int, columns: int, where: str) -> np.ndarray: + if not isinstance(value, (list, tuple)) or len(value) != rows: + _fail(f"{where} must have shape {rows}x{columns}") + parsed = [] + for row_index, row in enumerate(value): + if not isinstance(row, (list, tuple)) or len(row) != columns: + _fail(f"{where}[{row_index}] must have {columns} columns") + parsed.append([_number(item, f"{where}[{row_index}][{column}]") + for column, item in enumerate(row)]) + result = np.asarray(parsed, dtype=np.float64) + _check_weight_bounds(result, where) + return result + + +def _validate_levels(base: Mapping[str, Any], rest: Mapping[str, Any]) -> None: + if "level" in base and base["level"] != 0: + _fail("base_mesh must be level 0") + if "level" in rest and rest["level"] != 2: + _fail("rest_mesh must be level 2") + + +def _tail_contract(base_mesh: Mapping[str, Any], base_count: int, + base_quads: list[list[int]], prior_quads: list[list[int]]) -> dict[str, Any] | None: + """Validate the explicit local host-58 replacement and tail weight handoff.""" + metadata = _mapping(base_mesh.get("metadata"), "base_mesh.metadata") + raw_tail = metadata.get("tail") + if raw_tail is None: + return None + tail = _mapping(raw_tail, "base_mesh.metadata.tail") + if tail.get("enabled") is not True: + _fail("base_mesh.metadata.tail.enabled must be true for a tail allocation") + + identity = _mapping(tail.get("source_host_identity"), + "base_mesh.metadata.tail.source_host_identity") + host_face = _integer(identity.get("face_index"), + "base_mesh.metadata.tail.source_host_identity.face_index") + host_vertices = identity.get("vertex_indices") + if not isinstance(host_vertices, (list, tuple)) or len(host_vertices) != 4: + _fail("tail source_host_identity.vertex_indices must contain four vertices") + host_vertices = [_integer(index, f"tail source host vertex {slot}") + for slot, index in enumerate(host_vertices)] + if len(set(host_vertices)) != 4 or host_face < 0 or host_face >= len(prior_quads): + _fail("tail source host identity is outside the supplied original root") + if identity.get("owner") != "domain.pelvis": + _fail("tail source host identity must name the domain.pelvis owner") + if host_vertices != prior_quads[host_face]: + _fail("tail source host identity does not match the supplied original root face") + + replacement = _mapping(tail.get("face_replacement"), + "base_mesh.metadata.tail.face_replacement") + if replacement.get("original_face_index") != host_face: + _fail("tail face replacement does not name the declared original host face") + if list(replacement.get("original_quad", ())) != host_vertices: + _fail("tail face replacement does not repeat the declared original host quad") + if replacement.get("original_host_retained") is not False: + _fail("tail host replacement must explicitly remove the original host face") + replacement_indices = replacement.get("replacement_face_indices") + if not isinstance(replacement_indices, (list, tuple)) or not replacement_indices: + _fail("tail face replacement must declare replacement face indices") + replacement_indices = [_integer(index, "tail replacement face index") + for index in replacement_indices] + if len(set(replacement_indices)) != len(replacement_indices): + _fail("tail replacement face indices must be unique") + if host_face not in replacement_indices: + _fail("tail replacement must retain the host face slot for the first annulus face") + one_to_many = replacement.get("one_to_many") + if one_to_many != [[host_face, *replacement_indices]]: + _fail("tail one-to-many face correspondence disagrees with replacement_face_indices") + if any(index < 0 or index >= len(base_quads) for index in replacement_indices): + _fail("tail replacement face index is outside base_mesh.quads") + if base_quads[host_face] == prior_quads[host_face]: + _fail("declared tail host replacement did not replace the original host quad") + + index_mapping = _mapping(metadata.get("index_mapping"), + "base_mesh.metadata.index_mapping") + kept_raw = index_mapping.get("root_face_mappings_excluding_tail_host") + expected_kept = [[index, index] for index in range(len(prior_quads)) + if index != host_face] + if kept_raw != expected_kept: + _fail("tail kept-face correspondence must explicitly preserve every non-host root face") + for old_index, new_index in expected_kept: + if base_quads[new_index] != prior_quads[old_index]: + _fail(f"tail kept-face correspondence changed root face {old_index}") + + raw_indices = tail.get("new_vertex_indices") + if not isinstance(raw_indices, (list, tuple)) or not raw_indices: + _fail("base_mesh.metadata.tail.new_vertex_indices must be non-empty") + new_indices = [_integer(index, f"tail.new_vertex_indices[{slot}]") + for slot, index in enumerate(raw_indices)] + if len(set(new_indices)) != len(new_indices): + _fail("tail.new_vertex_indices must be unique") + if any(index < _ROOT_VERTEX_COUNT or index >= base_count for index in new_indices): + _fail("tail.new_vertex_indices must reference appended L0 vertices") + + raw_rings = tail.get("ring_indices") + if not isinstance(raw_rings, (list, tuple)) or not raw_rings: + _fail("tail.ring_indices must contain ordered tail rings") + rings: list[list[int]] = [] + for ring_index, raw_ring in enumerate(raw_rings): + if not isinstance(raw_ring, (list, tuple)) or not raw_ring: + _fail(f"tail.ring_indices[{ring_index}] must be a non-empty ring") + ring = [_integer(index, f"tail.ring_indices[{ring_index}][{slot}]") + for slot, index in enumerate(raw_ring)] + if len(set(ring)) != len(ring) or any(index not in new_indices for index in ring): + _fail("tail ring allocations must be unique members of new_vertex_indices") + rings.append(ring) + if [index for ring in rings for index in ring] != new_indices: + _fail("tail ring_indices must cover new_vertex_indices in declared order") + if any(len(ring) != 4 for ring in rings): + _fail("tail rings must retain the four-corner source phase correspondence") + raw_phase = tail.get("source_phase") + if not isinstance(raw_phase, (list, tuple)) or len(raw_phase) != 4: + _fail("tail source_phase must contain four host-corner phases") + source_phase: list[list[int]] = [] + for corner, phase in enumerate(raw_phase): + if (not isinstance(phase, (list, tuple)) or len(phase) != 2 or + any(type(value) is not int or value not in (-1, 1) for value in phase)): + _fail(f"tail.source_phase[{corner}] must be a signed two-component phase") + source_phase.append(list(phase)) + if len({tuple(phase) for phase in source_phase}) != 4: + _fail("tail source_phase must contain four distinct host-corner phases") + host_record = _mapping(tail.get("host"), "base_mesh.metadata.tail.host") + if host_record.get("source_phase") != source_phase: + _fail("tail host and tail source_phase declarations must agree") + fractions = tail.get("station_fractions") + if not isinstance(fractions, (list, tuple)) or len(fractions) != len(rings): + _fail("tail station_fractions must match tail ring_indices") + fractions = [_number(value, f"tail.station_fractions[{index}]") + for index, value in enumerate(fractions)] + if any(value < 0.0 or value > 1.0 for value in fractions) or fractions != sorted(fractions): + _fail("tail station_fractions must be ordered inside [0, 1]") + if fractions[0] != 0.0 or fractions[-1] != 1.0: + _fail("tail station_fractions must begin at collar 0 and end at distal 1") + + transition = _mapping(tail.get("transition_weights"), + "base_mesh.metadata.tail.transition_weights") + blend_value = transition.get("collar_blend_strength") + if blend_value is None: + _fail("tail transition_weights must explicitly declare collar_blend_strength; no hidden default is permitted") + collar_blend = _number(blend_value, + "tail.transition_weights.collar_blend_strength") + if collar_blend < 0.0 or collar_blend > 1.0: + _fail("tail collar_blend_strength must lie in [0, 1]") + supports = _mapping(transition.get("supports"), + "tail.transition_weights.supports") + if set(supports) != {str(index) for index in new_indices}: + _fail("tail transition supports must cover every new tail vertex exactly once") + checked_supports: dict[int, tuple[list[int], list[float]]] = {} + for index in new_indices: + row = _mapping(supports[str(index)], f"tail.transition_weights.supports.{index}") + if row.get("target_joint") != "pelvis": + _fail(f"tail transition support {index} must target the existing pelvis joint") + support_indices = row.get("host_vertex_indices") + values = row.get("convex_weights") + if list(support_indices or ()) != host_vertices: + _fail(f"tail transition support {index} must use the declared original host corners") + corner = _integer(row.get("host_corner"), + f"tail transition support {index}.host_corner") + expected_corner = new_indices.index(index) % 4 + if corner != expected_corner: + _fail(f"tail transition support {index} has the wrong retained source corner") + if row.get("source_phase") != source_phase[corner]: + _fail(f"tail transition support {index} has the wrong source phase") + if not isinstance(values, (list, tuple)) or len(values) != len(host_vertices): + _fail(f"tail transition support {index} must provide one weight per host corner") + weights = [_number(value, f"tail support {index} weight {slot}") + for slot, value in enumerate(values)] + if any(value < -_TOLERANCE for value in weights) or abs(sum(weights) - 1.0) > _TOLERANCE: + _fail(f"tail transition support {index} must be a convex host-corner combination") + expected_weights = [ + _TAIL_SUPPORT_OWN if slot == corner else _TAIL_SUPPORT_OTHER + for slot in range(4) + ] + if any(abs(actual - expected) > _TOLERANCE + for actual, expected in zip(weights, expected_weights)): + _fail(f"tail transition support {index} must match the declared inset-corner rule") + checked_supports[index] = (host_vertices[:], weights) + return { + "host_face": host_face, + "host_vertices": host_vertices, + "replacement_faces": replacement_indices, + "kept_faces": expected_kept, + "new_vertex_indices": new_indices, + "rings": rings, + "station_fractions": fractions, + "source_phase": source_phase, + "collar_blend_strength": collar_blend, + "supports": checked_supports, + } + + +def _validate_root(base_vertices: list[list[float]], base_quads: list[list[int]], + prior_vertices: list[list[float]], prior_quads: list[list[int]], + base_mesh: Mapping[str, Any]) -> dict[str, Any] | None: + if len(prior_vertices) != _ROOT_VERTEX_COUNT: + _fail("prior_root_mesh must contain exactly 152 L0 vertices") + if len(base_vertices) < _ROOT_VERTEX_COUNT: + _fail("base_mesh must retain the 152-vertex root prefix") + if base_vertices[:_ROOT_VERTEX_COUNT] != prior_vertices: + _fail("base_mesh root coordinates do not exactly match prior_root_mesh") + if len(base_quads) < len(prior_quads): + _fail("base_mesh must retain all prior_root_mesh quads") + tail = _tail_contract(base_mesh, len(base_vertices), base_quads, prior_quads) + if tail is None and base_quads[:len(prior_quads)] != prior_quads: + _fail("base_mesh root quads do not exactly match prior_root_mesh") + return tail + + +def _validate_constructor_root_metadata(base_mesh: Mapping[str, Any], + prior_quad_count: int, + tail: Mapping[str, Any] | None) -> None: + metadata = _mapping(base_mesh.get("metadata"), "base_mesh.metadata") + root = _mapping(metadata.get("root"), "base_mesh.metadata.root") + if root.get("vertex_count") != _ROOT_VERTEX_COUNT: + _fail("base_mesh.metadata.root.vertex_count must be 152") + if root.get("face_count") != prior_quad_count: + _fail("base_mesh.metadata.root.face_count must match prior_root_mesh") + index_mapping = _mapping(metadata.get("index_mapping"), + "base_mesh.metadata.index_mapping") + expected_vertices = [[index, index] for index in range(_ROOT_VERTEX_COUNT)] + if index_mapping.get("root_vertex_old_to_new") != expected_vertices: + _fail("base_mesh root vertex index mapping does not preserve the supplied root") + expected_faces = [[index, index] for index in range(prior_quad_count)] + if tail is None and index_mapping.get("root_face_old_to_new") != expected_faces: + _fail("base_mesh root face index mapping does not preserve the supplied root") + + +def _prior_root_weights(prior_hip_binding: Mapping[str, Any]) -> np.ndarray: + raw = prior_hip_binding.get("base_weights") + result = _weight_matrix(raw, _ROOT_VERTEX_COUNT, 3, + "prior_hip_binding.base_weights") + return result + + +def _expanded_root_weights(prior: np.ndarray, base_count: int, + columns: tuple[str, ...]) -> np.ndarray: + minimum_count = _ROOT_VERTEX_COUNT + 2 * _STATION_COUNT * _RING_VERTEX_COUNT + if base_count < minimum_count: + _fail("base_mesh must retain all seven eight-vertex stations per side after the 152 root vertices") + result = np.zeros((base_count, len(columns)), dtype=np.float64) + result[:_ROOT_VERTEX_COUNT, 0] = prior[:, 0] + result[:_ROOT_VERTEX_COUNT, 1] = prior[:, 1] + result[:_ROOT_VERTEX_COUNT, 3] = prior[:, 2] + return result + + +def _expected_station_centres(points: Mapping[str, list[float]], support: float) -> list[np.ndarray]: + T = np.asarray(points["T"], dtype=np.float64) + K = np.asarray(points["K"], dtype=np.float64) + A = np.asarray(points["A"], dtype=np.float64) + fractions = (_MID_THIGH_FRACTION, 1.0 - support, 1.0, + _SUPPORT_MULTIPLIER * support, _CALF_FRACTION, + _ANKLE_APPROACH_FRACTION, 1.0) + return [T + fraction * (K - T) for fraction in fractions[:3]] + [ + K + fraction * (A - K) for fraction in fractions[3:] + ] + + +def _chain_rings(base_mesh: Mapping[str, Any], base_count: int, + legs: dict[str, dict[str, list[float]]], + declared_support: dict[str, float]) -> tuple[dict[str, list[list[int]]], + dict[str, list[list[float]]]]: + metadata = _mapping(base_mesh.get("metadata"), "base_mesh.metadata") + chains = _mapping(metadata.get("chains"), "base_mesh.metadata.chains") + if set(chains) != set(_SIDES): + _fail("base_mesh.metadata.chains must contain exactly left and right") + + rings: dict[str, list[list[int]]] = {} + centres: dict[str, list[list[float]]] = {} + for side in _SIDES: + chain = _mapping(chains[side], f"base_mesh.metadata.chains.{side}") + sections = chain.get("sections") + if not isinstance(sections, (list, tuple)) or len(sections) != _STATION_COUNT: + _fail(f"base_mesh.metadata.chains.{side}.sections must contain seven records") + if chain.get("ring_order") != list(_STATION_NAMES): + _fail(f"base_mesh.metadata.chains.{side}.ring_order does not match the constructor section order") + named = _mapping(chain.get("ring_indices_by_name"), + f"base_mesh.metadata.chains.{side}.ring_indices_by_name") + if set(named) != set(_STATION_NAMES): + _fail(f"base_mesh.metadata.chains.{side}.ring_indices_by_name has the wrong section names") + support = declared_support[side] + expected_centres = _expected_station_centres(legs[side], support) + side_rings: list[list[int]] = [] + side_centres: list[list[float]] = [] + for station_index, raw_section in enumerate(sections): + section = _mapping(raw_section, + f"base_mesh.metadata.chains.{side}.sections[{station_index}]") + if section.get("name") != _STATION_NAMES[station_index]: + _fail(f"construction section order/name mismatch for {side} station {station_index}") + if section.get("order") != station_index: + _fail(f"construction section order mismatch for {side} station {station_index}") + ring_value = section.get("indices") + if not isinstance(ring_value, (list, tuple)) or len(ring_value) != _RING_VERTEX_COUNT: + _fail(f"construction section {side}.{_STATION_NAMES[station_index]} must contain eight indices") + ring = [_integer(index, f"construction section {side}.{_STATION_NAMES[station_index]}.indices[{slot}]") + for slot, index in enumerate(ring_value)] + if len(set(ring)) != _RING_VERTEX_COUNT: + _fail(f"construction section {side}.{_STATION_NAMES[station_index]} contains duplicate indices") + named_ring = named[_STATION_NAMES[station_index]] + if list(named_ring) != ring: + _fail(f"construction named ring disagrees with section for {side}.{_STATION_NAMES[station_index]}") + fraction = _number(section.get("fraction"), + f"construction section {side}.{_STATION_NAMES[station_index]}.fraction") + expected_fraction = (_MID_THIGH_FRACTION, 1.0 - support, 1.0, + _SUPPORT_MULTIPLIER * support, _CALF_FRACTION, + _ANKLE_APPROACH_FRACTION, 1.0)[station_index] + if not math.isclose(fraction, expected_fraction, rel_tol=0.0, + abs_tol=_CONSTRUCTION_COORDINATE_TOLERANCE): + _fail(f"construction section fraction disagrees with support_fraction for {side}.{_STATION_NAMES[station_index]}") + centre = _vector(section.get("centre"), + f"construction section {side}.{_STATION_NAMES[station_index]}.centre") + if not np.allclose(centre, expected_centres[station_index], + atol=_CONSTRUCTION_COORDINATE_TOLERANCE, rtol=0.0): + _fail(f"construction section centre disagrees with T/K/A for {side}.{_STATION_NAMES[station_index]}") + side_rings.append(ring) + side_centres.append(centre) + new_indices = chain.get("new_vertex_indices") + expected_indices = [index for ring in side_rings for index in ring] + if not isinstance(new_indices, (list, tuple)) or list(new_indices) != expected_indices: + _fail(f"construction new_vertex_indices disagrees with sections for {side}") + rings[side] = side_rings + centres[side] = side_centres + + all_indices = [index for side in _SIDES for ring in rings[side] for index in ring] + if any(index < _ROOT_VERTEX_COUNT or index >= base_count for index in all_indices): + _fail("construction sections must reference only appended L0 station vertices") + if len(set(all_indices)) != len(all_indices): + _fail("construction sections must not overlap") + return rings, centres + + +def _arm_vertex_indices(base_mesh: Mapping[str, Any], base_count: int, + rings: dict[str, list[list[int]]], + excluded_indices: set[int] | None = None) -> dict[str, dict[str, Any]]: + """Validate the semantic appended-arm allocation, without fixed counts.""" + metadata = _mapping(base_mesh.get("metadata"), "base_mesh.metadata") + raw_arms = metadata.get("arms") + if raw_arms is None: + return {} + arms = _mapping(raw_arms, "base_mesh.metadata.arms") + if set(arms) != set(_SIDES): + _fail("base_mesh.metadata.arms must contain exactly left and right") + leg_indices = {index for side in _SIDES for ring in rings[side] for index in ring} + result: dict[str, dict[str, Any]] = {} + used: set[int] = set() + for side in _SIDES: + row = _mapping(arms[side], f"base_mesh.metadata.arms.{side}") + source_port = _mapping(row.get("source_port"), + f"base_mesh.metadata.arms.{side}.source_port") + port = [_integer(index, f"base_mesh.metadata.arms.{side}.source_port.indices[{i}]") + for i, index in enumerate(source_port.get("indices", []))] + if len(port) != _RING_VERTEX_COUNT or len(set(port)) != _RING_VERTEX_COUNT: + _fail(f"base_mesh.metadata.arms.{side}.source_port.indices must contain eight unique vertices") + if any(index < 0 or index >= _ROOT_VERTEX_COUNT for index in port): + _fail(f"base_mesh.metadata.arms.{side}.source_port.indices must reference root vertices") + collar = _mapping(row.get("collar"), f"base_mesh.metadata.arms.{side}.collar") + collar_value = collar.get("indices") + if not isinstance(collar_value, (list, tuple)) or len(collar_value) != _RING_VERTEX_COUNT: + _fail(f"base_mesh.metadata.arms.{side}.collar.indices must contain eight vertices") + collar_indices = [_integer(index, f"base_mesh.metadata.arms.{side}.collar.indices[{i}]") + for i, index in enumerate(collar_value)] + if len(set(collar_indices)) != _RING_VERTEX_COUNT: + _fail(f"base_mesh.metadata.arms.{side}.collar.indices must be unique") + sections_value = row.get("sections") + if not isinstance(sections_value, (list, tuple)) or len(sections_value) != len(_ARM_SECTION_NAMES): + _fail(f"base_mesh.metadata.arms.{side}.sections must contain the named arm sections") + section_indices: dict[str, list[int]] = {} + for expected_name, raw_section in zip(_ARM_SECTION_NAMES, sections_value): + section = _mapping(raw_section, + f"base_mesh.metadata.arms.{side}.sections.{expected_name}") + if section.get("name") != expected_name: + _fail(f"base_mesh.metadata.arms.{side}.sections order/name mismatch") + value = section.get("indices") + if not isinstance(value, (list, tuple)) or len(value) != _RING_VERTEX_COUNT: + _fail(f"base_mesh.metadata.arms.{side}.sections.{expected_name}.indices must contain eight vertices") + indices = [_integer(index, f"base_mesh.metadata.arms.{side}.sections.{expected_name}.indices[{i}]") + for i, index in enumerate(value)] + if len(set(indices)) != _RING_VERTEX_COUNT: + _fail(f"base_mesh.metadata.arms.{side}.sections.{expected_name}.indices must be unique") + section_indices[expected_name] = indices + cap = _mapping(row.get("cap"), f"base_mesh.metadata.arms.{side}.cap") + cap_index = _integer(cap.get("vertex"), f"base_mesh.metadata.arms.{side}.cap.vertex") + new_value = row.get("new_vertex_indices") + if not isinstance(new_value, (list, tuple)): + _fail(f"base_mesh.metadata.arms.{side}.new_vertex_indices must be a list") + new_indices = [_integer(index, f"base_mesh.metadata.arms.{side}.new_vertex_indices[{i}]") + for i, index in enumerate(new_value)] + expected = collar_indices + [index for name in _ARM_SECTION_NAMES + for index in section_indices[name]] + [cap_index] + if new_indices != expected: + _fail(f"base_mesh.metadata.arms.{side}.new_vertex_indices disagrees with semantic sections") + if len(set(new_indices)) != len(new_indices): + _fail(f"base_mesh.metadata.arms.{side} contains overlapping vertex allocations") + if any(index < _ROOT_VERTEX_COUNT or index >= base_count for index in new_indices): + _fail(f"base_mesh.metadata.arms.{side} contains an invalid appended vertex") + if (set(new_indices) & leg_indices or used & set(new_indices) + or (excluded_indices and set(new_indices) & excluded_indices)): + _fail(f"base_mesh.metadata.arms.{side} overwrites another allocation") + used.update(new_indices) + result[side] = { + "J": _vector(row.get("J"), f"base_mesh.metadata.arms.{side}.J"), + "E": _vector(row.get("E"), f"base_mesh.metadata.arms.{side}.E"), + "W": _vector(row.get("W"), f"base_mesh.metadata.arms.{side}.W"), + "source_port": port, + "collar": collar_indices, + "sections": section_indices, + "cap": cap_index, + "new_vertex_indices": new_indices, + } + return result + + +def _foot_vertex_indices(base_mesh: Mapping[str, Any], base_count: int, + rings: dict[str, list[list[int]]], + arms: Mapping[str, Any] | None = None, + heads: Mapping[str, Any] | None = None, + excluded_indices: set[int] | None = None) -> dict[str, list[int]]: + """Validate explicit foot allocation as the complement of known appendages.""" + metadata = _mapping(base_mesh.get("metadata"), "base_mesh.metadata") + leg_indices = {index for side in _SIDES for ring in rings[side] for index in ring} + appended = set(range(_ROOT_VERTEX_COUNT, base_count)) + arm_indices = {index for row in (arms or {}).values() + for index in row["new_vertex_indices"]} + head_indices = set((heads or {}).get("new_vertex_indices", ())) + excluded = set(excluded_indices or ()) + raw_feet = metadata.get("feet") + if raw_feet is None: + if leg_indices | arm_indices | head_indices | excluded != appended: + _fail("base_mesh appended vertices require metadata.feet for non-leg allocations") + return {side: [] for side in _SIDES} + + feet = _mapping(raw_feet, "base_mesh.metadata.feet") + if set(feet) != set(_SIDES): + _fail("base_mesh.metadata.feet must contain exactly left and right") + result: dict[str, list[int]] = {} + foot_indices: set[int] = set() + for side in _SIDES: + row = _mapping(feet[side], f"base_mesh.metadata.feet.{side}") + raw_indices = row.get("new_vertex_indices") + if not isinstance(raw_indices, (list, tuple)) or not raw_indices: + _fail(f"base_mesh.metadata.feet.{side}.new_vertex_indices must be non-empty") + checked = [_integer(index, f"base_mesh.metadata.feet.{side}.new_vertex_indices[{slot}]") + for slot, index in enumerate(raw_indices)] + if len(set(checked)) != len(checked): + _fail(f"base_mesh.metadata.feet.{side}.new_vertex_indices must be disjoint") + if any(index < _ROOT_VERTEX_COUNT or index >= base_count for index in checked): + _fail(f"base_mesh.metadata.feet.{side}.new_vertex_indices contains an invalid L0 vertex") + if set(checked) & (leg_indices | excluded): + _fail(f"base_mesh.metadata.feet.{side}.new_vertex_indices overwrites a leg allocation") + if foot_indices & set(checked): + _fail("base_mesh.metadata.feet left and right allocations must be disjoint") + result[side] = checked + foot_indices.update(checked) + + if leg_indices | arm_indices | head_indices | foot_indices | excluded != appended: + _fail("base_mesh leg and foot allocations must cover every appended L0 vertex exactly once") + if ((leg_indices & arm_indices) or (foot_indices & arm_indices) or + (leg_indices & head_indices) or (foot_indices & head_indices) or + (arm_indices & head_indices) or (excluded & (leg_indices | arm_indices | + head_indices | foot_indices))): + _fail("base_mesh leg, foot, arm, and head allocations must be disjoint") + return result + + +def _head_vertex_indices(base_mesh: Mapping[str, Any], base_count: int, + rings: dict[str, list[list[int]]], + arms: Mapping[str, Any], + excluded_indices: set[int] | None = None) -> dict[str, Any]: + """Validate the source-linked head handoff without inferring its pivot.""" + metadata = _mapping(base_mesh.get("metadata"), "base_mesh.metadata") + raw_head = metadata.get("head") + if raw_head is None: + return {} + head = _mapping(raw_head, "base_mesh.metadata.head") + handoff = _mapping(head.get("binding_handoff"), + "base_mesh.metadata.head.binding_handoff") + if handoff.get("pivot_source") != "stations.neck_collar.C": + _fail("base_mesh.metadata.head binding pivot must be stations.neck_collar.C") + pivot = _vector(handoff.get("pivot"), + "base_mesh.metadata.head.binding_handoff.pivot") + + def checked_indices(value: Any, where: str, lower: int, upper: int) -> list[int]: + if not isinstance(value, (list, tuple)) or not value: + _fail(f"{where} must be a non-empty index list") + values = [_integer(index, f"{where}[{slot}]") + for slot, index in enumerate(value)] + if len(set(values)) != len(values): + _fail(f"{where} must contain unique indices") + if any(index < lower or index >= upper for index in values): + _fail(f"{where} contains an out-of-range vertex") + return values + + port = checked_indices(head.get("neck_port_indices"), + "base_mesh.metadata.head.neck_port_indices", + 0, _ROOT_VERTEX_COUNT) + consumed_port = checked_indices( + handoff.get("consumed_neck_port_indices"), + "base_mesh.metadata.head.binding_handoff.consumed_neck_port_indices", + 0, _ROOT_VERTEX_COUNT, + ) + if consumed_port != port: + _fail("head binding handoff disagrees with neck_port_indices") + + stations = head.get("stations") + if not isinstance(stations, (list, tuple)): + _fail("base_mesh.metadata.head.stations must be a list") + support_records = [ + _mapping(row, "base_mesh.metadata.head.stations entry") + for row in stations if isinstance(row, Mapping) and row.get("name") == "neck_support" + ] + if len(support_records) != 1: + _fail("head metadata must contain exactly one neck_support station") + support = checked_indices( + support_records[0].get("indices"), + "base_mesh.metadata.head.stations.neck_support.indices", + _ROOT_VERTEX_COUNT, base_count, + ) + handoff_support = checked_indices( + handoff.get("neck_support_ring_indices"), + "base_mesh.metadata.head.binding_handoff.neck_support_ring_indices", + _ROOT_VERTEX_COUNT, base_count, + ) + if handoff_support != support: + _fail("head binding handoff disagrees with neck_support station") + + new_indices = checked_indices( + head.get("new_vertex_indices"), + "base_mesh.metadata.head.new_vertex_indices", + _ROOT_VERTEX_COUNT, base_count, + ) + handoff_new = checked_indices( + handoff.get("head_new_vertex_indices"), + "base_mesh.metadata.head.binding_handoff.head_new_vertex_indices", + _ROOT_VERTEX_COUNT, base_count, + ) + if handoff_new != new_indices: + _fail("head binding handoff disagrees with head.new_vertex_indices") + if not set(support).issubset(new_indices): + _fail("head neck_support ring must be part of head.new_vertex_indices") + + leg_indices = {index for side in _SIDES for ring in rings[side] for index in ring} + arm_indices = {index for row in arms.values() for index in row["new_vertex_indices"]} + head_set = set(new_indices) + if (head_set & leg_indices or head_set & arm_indices + or (excluded_indices and head_set & excluded_indices)): + _fail("head allocation overwrites an existing appendage allocation") + return { + "J": pivot, + "pivot_source": "stations.neck_collar.C", + "source_port": port, + "support": support, + "new_vertex_indices": new_indices, + } + + +def _root_edge_graph(base_mesh: Mapping[str, Any], + base_quads: list[list[int]], + attachments: Mapping[str, Mapping[str, Any]], + source_root_quads: list[list[int]] | None = None) -> tuple[list[set[int]], dict[str, Any]]: + """Build the root graph and verify every semantic port-to-support weld.""" + metadata = _mapping(base_mesh.get("metadata"), "base_mesh.metadata") + root = _mapping(metadata.get("root"), "base_mesh.metadata.root") + root_count = _integer(root.get("vertex_count"), + "base_mesh.metadata.root.vertex_count") + root_face_count = _integer(root.get("face_count"), + "base_mesh.metadata.root.face_count") + if root_count != _ROOT_VERTEX_COUNT: + _fail("base_mesh.metadata.root.vertex_count must be 152") + if root_face_count <= 0 or root_face_count > len(base_quads): + _fail("base_mesh.metadata.root.face_count is outside the base quad range") + + source_faces = base_quads[:root_face_count] if source_root_quads is None else source_root_quads + if len(source_faces) != root_face_count: + _fail("source root face correspondence does not cover the declared root face count") + graph = [set() for _ in range(root_count)] + for face_index, face in enumerate(source_faces): + if any(index < 0 or index >= root_count for index in face): + _fail(f"root face {face_index} references a non-root vertex") + for corner, left in enumerate(face): + right = face[(corner + 1) % 4] + graph[left].add(right) + graph[right].add(left) + + all_edges = set() + for face in base_quads: + for corner, left in enumerate(face): + all_edges.add((left, face[(corner + 1) % 4]) if left < face[(corner + 1) % 4] + else (face[(corner + 1) % 4], left)) + connections: dict[str, list[list[int]]] = {} + for name, row in attachments.items(): + port = row["port"] + support = row["support"] + pairs = [] + for port_index, support_index in zip(port, support): + edge = ((port_index, support_index) if port_index < support_index + else (support_index, port_index)) + if edge not in all_edges: + _fail(f"base_mesh {name} lacks a port-to-support connection") + pairs.append([port_index, support_index]) + connections[name] = pairs + return graph, {"connections": connections, "root_face_count": root_face_count} + + +def _graph_distance_neighbourhood(graph: list[set[int]], seeds: set[int], distance: int) -> set[int]: + current = set(seeds) + reached = set(seeds) + for _ in range(distance): + current = {neighbour for index in current for neighbour in graph[index]} - reached + reached.update(current) + return reached + + +def _root_free_field(graph: list[set[int]], connections: list[list[int]], + port: list[int], support: list[int], where: str) -> dict[str, Any]: + """Solve one D0/D1 free field with an explicit support=1, D2=0 boundary.""" + d0 = set(port) + d1 = {neighbour for index in d0 for neighbour in graph[index]} - d0 + d2 = {neighbour for index in d1 for neighbour in graph[index]} - d0 - d1 + if not d0 or not d1 or not d2: + _fail(f"{where} requires non-empty D0, D1, and D2 root regions") + if any(index < 0 or index >= _ROOT_VERTEX_COUNT for index in d0 | d1 | d2): + _fail(f"{where} graph region escaped the root") + free = sorted(d0 | d1) + seeds = d2 + support_set = set(support) + if not support_set: + _fail(f"{where} support ring is empty") + node_neighbours: dict[int, set[int]] = {index: set(graph[index]) for index in free} + for port_index, support_index in connections: + if port_index in node_neighbours: + node_neighbours[port_index].add(support_index) + positions = {index: row for row, index in enumerate(free)} + matrix = np.eye(len(free), dtype=np.float64) + rhs = np.zeros(len(free), dtype=np.float64) + for index in free: + neighbours = node_neighbours[index] + if not neighbours: + _fail(f"{where} has an unassigned free graph component") + row = positions[index] + for neighbour in neighbours: + if neighbour in positions: + matrix[row, positions[neighbour]] -= 1.0 / len(neighbours) + elif neighbour in support_set: + rhs[row] += 1.0 / len(neighbours) + elif neighbour in seeds: + # D2 is the zero boundary. Shared D2 nodes are allowed. + pass + else: + _fail(f"{where} free graph has an unassigned neighbour") + try: + values = np.linalg.solve(matrix, rhs) + except np.linalg.LinAlgError as exc: + raise ValueError(f"{where} free graph is not anchored") from exc + if not np.all(np.isfinite(values)): + _fail(f"{where} free graph produced non-finite influence") + field = {index: float(value) for index, value in zip(free, values)} + return { + "field": field, + "D0": sorted(d0), + "D1": sorted(d1), + "D2": sorted(d2), + "D0_count": len(d0), + "D1_count": len(d1), + "free_count": len(free), + "seed_count": len(d2), + "support_count": len(support_set), + "support_anchor_value": 1.0, + "collar_anchor_value": 1.0, + "D2_anchor_value": 0.0, + "values": {str(index): field[index] for index in free}, + } + + +def _arm_root_influence(base_mesh: Mapping[str, Any], + base_quads: list[list[int]], + arms: Mapping[str, Any], + rings: dict[str, list[list[int]]], + source_root_quads: list[list[int]] | None = None) -> dict[str, Any]: + """Compute the arm scalar field on root D0/D1 using source topology.""" + attachments = { + side: {"port": arms[side]["source_port"], + "support": arms[side]["collar"]} + for side in _SIDES + } + graph, graph_metadata = _root_edge_graph( + base_mesh, base_quads, attachments, source_root_quads, + ) + metadata = _mapping(base_mesh.get("metadata"), "base_mesh.metadata") + chains = _mapping(metadata.get("chains"), "base_mesh.metadata.chains") + per_side: dict[str, Any] = {} + all_free: dict[str, set[int]] = {} + all_seed: dict[str, set[int]] = {} + + for side in _SIDES: + record = _root_free_field( + graph, graph_metadata["connections"][side], + arms[side]["source_port"], arms[side]["collar"], + f"base_mesh arm {side}", + ) + per_side[side] = record + all_free[side] = set(record["D0"]) | set(record["D1"]) + all_seed[side] = set(record["D2"]) + + left_free, right_free = all_free["left"], all_free["right"] + if left_free & right_free: + _fail("bilateral arm D0/D1 regions overlap") + if left_free & all_seed["right"] or right_free & all_seed["left"]: + _fail("arm free region overlaps the opposite arm seed region") + + thigh_neighbourhood: set[int] = set() + for side in _SIDES: + chain = _mapping(chains.get(side), f"base_mesh.metadata.chains.{side}") + root_exit = chain.get("root_exit") + if not isinstance(root_exit, (list, tuple)) or not root_exit: + _fail(f"base_mesh.metadata.chains.{side}.root_exit is required for arm separation") + thigh = {_integer(index, f"base_mesh.metadata.chains.{side}.root_exit[{i}]") + for i, index in enumerate(root_exit)} + if any(index < 0 or index >= _ROOT_VERTEX_COUNT for index in thigh): + _fail(f"base_mesh.metadata.chains.{side}.root_exit must reference root vertices") + thigh_neighbourhood.update(_graph_distance_neighbourhood(graph, thigh, 2)) + if (left_free | right_free) & thigh_neighbourhood: + _fail("arm D0/D1 region overlaps a thigh-port neighbourhood") + + fields: dict[str, dict[int, float]] = { + side: per_side[side].pop("field") for side in _SIDES + } + for side in _SIDES: + per_side[side]["collar_count"] = len(arms[side]["collar"]) + return { + "fields": fields, + "per_side": per_side, + "bilateral_shared_D2": sorted(all_seed["left"] & all_seed["right"]), + "thigh_neighbourhood_count": len(thigh_neighbourhood), + "connections": graph_metadata["connections"], + } + + +def _head_root_influence(base_mesh: Mapping[str, Any], + base_quads: list[list[int]], + head: Mapping[str, Any], + arm_influence: Mapping[str, Any] | None, + source_root_quads: list[list[int]] | None = None) -> dict[str, Any]: + """Compute the head D0/D1 field and make shoulder overlap explicit.""" + graph, graph_metadata = _root_edge_graph( + base_mesh, base_quads, + {"head": {"port": head["source_port"], "support": head["support"]}}, + source_root_quads, + ) + record = _root_free_field( + graph, graph_metadata["connections"]["head"], + head["source_port"], head["support"], "base_mesh head", + ) + shoulder_nodes = set() + if arm_influence is not None: + shoulder_nodes = { + index for field in arm_influence["fields"].values() for index in field + } + overlap = sorted((set(record["D0"]) | set(record["D1"])) & shoulder_nodes) + record["shoulder_overlap"] = overlap + if overlap: + _fail(f"base_mesh head D0/D1 overlaps shoulder modified nodes: {overlap}") + field = record.pop("field") + return { + "field": field, + "per_root": record, + "connections": graph_metadata["connections"], + } + + +def _leg_inputs(value: Any) -> tuple[dict[str, dict[str, list[float]]], + dict[str, float], dict[str, float]]: + raw = _mapping(value, "leg_inputs") + if set(raw) != set(_SIDES): + _fail("leg_inputs must contain exactly left and right sides") + result: dict[str, dict[str, list[float]]] = {} + supports: dict[str, float] = {} + factors: dict[str, float] = {} + for side in _SIDES: + row = _mapping(raw[side], f"leg_inputs.{side}") + missing = [name for name in ("J", "T", "K", "A", "mid_thigh_factor", + "support_fraction") if name not in row] + if missing: + _fail(f"leg_inputs.{side} is missing {', '.join(missing)}") + points = {name: _vector(row[name], f"leg_inputs.{side}.{name}") + for name in ("J", "T", "K", "A")} + j, t, k, a = (np.asarray(points[name], dtype=np.float64) + for name in ("J", "T", "K", "A")) + if np.linalg.norm(j - k) <= _TOLERANCE: + _fail(f"leg_inputs.{side}.J and K must be distinct") + if np.linalg.norm(t - k) <= _TOLERANCE: + _fail(f"leg_inputs.{side}.T and K must be distinct") + if np.linalg.norm(k - a) <= _TOLERANCE: + _fail(f"leg_inputs.{side}.K and A must be distinct") + factor = _number(row["mid_thigh_factor"], + f"leg_inputs.{side}.mid_thigh_factor") + support = _number(row["support_fraction"], + f"leg_inputs.{side}.support_fraction") + if factor < 0.0: + _fail(f"leg_inputs.{side}.mid_thigh_factor must be non-negative") + if not 0.0 < support < 1.0: + _fail(f"leg_inputs.{side}.support_fraction must be strictly between zero and one") + result[side] = points + factors[side] = factor + supports[side] = support + return result, supports, factors + + +def _frame(origin: list[float], distal: list[float], where: str) -> dict[str, Any]: + origin_array = np.asarray(origin, dtype=np.float64) + distal_array = np.asarray(distal, dtype=np.float64) + y = origin_array - distal_array + y_norm = float(np.linalg.norm(y)) + if not math.isfinite(y_norm) or y_norm <= _TOLERANCE: + _fail(f"{where} frame has a degenerate Y axis") + y /= y_norm + x = np.asarray([1.0, 0.0, 0.0], dtype=np.float64) + x -= np.dot(x, y) * y + x_norm = float(np.linalg.norm(x)) + if not math.isfinite(x_norm) or x_norm <= _TOLERANCE: + _fail(f"{where} frame has no usable +X projection") + x /= x_norm + z = np.cross(x, y) + z_norm = float(np.linalg.norm(z)) + if not math.isfinite(z_norm) or z_norm <= _TOLERANCE: + _fail(f"{where} frame has a degenerate Z axis") + z /= z_norm + rotation = np.column_stack((x, y, z)) + matrix = np.eye(4, dtype=np.float64) + matrix[:3, :3] = rotation + matrix[:3, 3] = origin_array + return {"rotation": rotation.tolist(), "rest_global": matrix.tolist()} + + +def _arm_frame(origin: list[float], distal: list[float], where: str) -> dict[str, Any]: + """Build the arm pivot frame from a near-horizontal source bone.""" + origin_array = np.asarray(origin, dtype=np.float64) + distal_array = np.asarray(distal, dtype=np.float64) + y = origin_array - distal_array + y_norm = float(np.linalg.norm(y)) + if not math.isfinite(y_norm) or y_norm <= _TOLERANCE: + _fail(f"{where} frame has a degenerate Y axis") + y /= y_norm + global_up = np.asarray([0.0, 1.0, 0.0], dtype=np.float64) + x = global_up - np.dot(global_up, y) * y + x_norm = float(np.linalg.norm(x)) + if not math.isfinite(x_norm) or x_norm <= _TOLERANCE: + _fail(f"{where} frame has no usable global +Y projection") + x /= x_norm + z = np.cross(x, y) + z_norm = float(np.linalg.norm(z)) + if not math.isfinite(z_norm) or z_norm <= _TOLERANCE: + _fail(f"{where} frame has a degenerate Z axis") + z /= z_norm + if float(np.dot(z, [0.0, 0.0, 1.0])) < 0.0: + x, z = -x, -z + rotation = np.column_stack((x, y, z)) + matrix = np.eye(4, dtype=np.float64) + matrix[:3, :3] = rotation + matrix[:3, 3] = origin_array + return { + "rotation": rotation.tolist(), + "rest_global": matrix.tolist(), + "frame_rule": "Y=normalize(origin-distal); X=projected global +Y; Z=X cross Y; flip X/Z toward +Z", + } + + +def _matrix(value: Any, where: str) -> np.ndarray: + raw = np.asarray(value, dtype=np.float64) + if raw.shape != (4, 4) or not np.all(np.isfinite(raw)): + _fail(f"{where} must be a finite 4x4 matrix") + if not np.allclose(raw[3], [0.0, 0.0, 0.0, 1.0], atol=_FRAME_TOLERANCE, rtol=0.0): + _fail(f"{where} must be an affine rigid matrix") + rotation = raw[:3, :3] + if not np.allclose(rotation.T @ rotation, np.eye(3), + atol=_FRAME_TOLERANCE, rtol=0.0): + _fail(f"{where} rotation must be orthonormal") + determinant = float(np.linalg.det(rotation)) + if not math.isfinite(determinant) or abs(determinant - 1.0) > _FRAME_TOLERANCE: + _fail(f"{where} rotation must have positive unit determinant") + return raw + + +def _inverse_rigid(value: np.ndarray, where: str) -> np.ndarray: + # _matrix has already established the rigid affine contract, but use the + # requested inverse operation so the stored rest-local relation is clear. + try: + inverse = np.linalg.inv(value) + except np.linalg.LinAlgError as exc: + raise ValueError(f"{where} is singular") from exc + if not np.all(np.isfinite(inverse)): + _fail(f"{where} inverse is non-finite") + return inverse + + +def _matrix_rotation_x(angle_degrees: float) -> np.ndarray: + radians = math.radians(angle_degrees) + cosine, sine = math.cos(radians), math.sin(radians) + return np.array([[1.0, 0.0, 0.0, 0.0], + [0.0, cosine, -sine, 0.0], + [0.0, sine, cosine, 0.0], + [0.0, 0.0, 0.0, 1.0]], dtype=np.float64) + + +def _matrix_rotation_y(angle_degrees: float) -> np.ndarray: + radians = math.radians(angle_degrees) + cosine, sine = math.cos(radians), math.sin(radians) + return np.array([[cosine, 0.0, sine, 0.0], + [0.0, 1.0, 0.0, 0.0], + [-sine, 0.0, cosine, 0.0], + [0.0, 0.0, 0.0, 1.0]], dtype=np.float64) + + +def _matrix_rotation_z(angle_degrees: float) -> np.ndarray: + radians = math.radians(angle_degrees) + cosine, sine = math.cos(radians), math.sin(radians) + return np.array([[cosine, -sine, 0.0, 0.0], + [sine, cosine, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0]], dtype=np.float64) + + +def _angles(value: Any) -> dict[str, dict[str, float]]: + raw = _mapping(value, "angles_degrees") + if not set(_SIDES).issubset(raw) or set(raw).difference(set(_SIDES) | {"head"}): + _fail("angles_degrees must contain left and right, with optional head angles") + result: dict[str, dict[str, float]] = {} + for side in _SIDES: + row = _mapping(raw[side], f"angles_degrees.{side}") + allowed = {"hip", "knee", "ankle", "shoulder_raise", + "shoulder_forward", "elbow"} + if not {"hip", "knee"}.issubset(row) or set(row).difference(allowed): + _fail(f"angles_degrees.{side} must contain hip and knee, with optional arm angles") + parsed = {name: _number(row[name], f"angles_degrees.{side}.{name}") + for name in ("hip", "knee")} + if "ankle" in row: + ankle = _number(row["ankle"], f"angles_degrees.{side}.ankle") + if ankle != 0.0: + _fail("ankle angle is staging-only and must be zero") + parsed["ankle"] = 0.0 + for name in ("shoulder_raise", "shoulder_forward", "elbow"): + parsed[name] = _number(row.get(name, 0.0), + f"angles_degrees.{side}.{name}") + result[side] = parsed + head = raw.get("head", {}) + head_row = _mapping(head, "angles_degrees.head") + if set(head_row).difference({"yaw", "nod"}): + _fail("angles_degrees.head may contain only yaw and nod") + result["head"] = { + name: _number(head_row.get(name, 0.0), f"angles_degrees.head.{name}") + for name in ("yaw", "nod") + } + return result + + +def _point(matrix: np.ndarray, point: list[float], where: str) -> list[float]: + result = matrix @ np.r_[np.asarray(point, dtype=np.float64), 1.0] + if not np.all(np.isfinite(result)): + _fail(f"{where} is non-finite") + return result[:3].tolist() + + +def _frame_matrices(frame: Mapping[str, Any], side: str) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + thigh = _mapping(frame.get("thigh"), f"binding.rest_frames.{side}.thigh") + knee = _mapping(frame.get("knee"), f"binding.rest_frames.{side}.knee") + thigh_value = thigh.get("rest_global", thigh.get("rest_matrix")) + knee_value = knee.get("rest_global", knee.get("rest_matrix")) + thigh_rest = _matrix(thigh_value, f"binding.rest_frames.{side}.thigh.rest_global") + knee_rest = _matrix(knee_value, f"binding.rest_frames.{side}.knee.rest_global") + knee_local = _matrix(knee.get("rest_local"), + f"binding.rest_frames.{side}.knee.rest_local") + expected_local = _inverse_rigid(thigh_rest, f"binding.rest_frames.{side}.thigh.rest_global") @ knee_rest + if not np.allclose(knee_local, expected_local, atol=_FRAME_TOLERANCE, rtol=0.0): + _fail(f"binding.rest_frames.{side}.knee.rest_local does not match inverse(thigh)*knee") + return thigh_rest, knee_rest, knee_local + + +def _joint_transforms(binding: Mapping[str, Any], angles_degrees: Mapping[str, Any]) -> dict[str, dict[str, Any]]: + angles = _angles(angles_degrees) + joint_order = tuple(binding.get("joint_order", ())) + valid_layouts = { + _LEG_JOINT_ORDER: (False, False), + _ARM_JOINT_ORDER: (True, False), + _HEAD_JOINT_ORDER: (False, True), + _ARM_HEAD_JOINT_ORDER: (True, True), + } + if joint_order not in valid_layouts: + _fail("binding.joint_order must be a five-, six-, nine-, or ten-joint layout") + has_arms, has_head = valid_layouts[joint_order] + if not has_arms and any(angles[side][joint] != 0.0 + for side in _SIDES + for joint in ("shoulder_raise", "shoulder_forward", "elbow")): + _fail("arm pose angles require a nine- or ten-joint arm binding") + if not has_head and any(angles["head"][joint] != 0.0 + for joint in ("yaw", "nod")): + _fail("head pose angles require a six- or ten-joint head binding") + frames = _mapping(binding.get("rest_frames"), "binding.rest_frames") + expected_frames = set(_SIDES) | ({"head"} if has_head else set()) + if set(frames) != expected_frames: + _fail("binding.rest_frames does not match the selected joint layout") + result: dict[str, dict[str, Any]] = {} + identity = np.eye(4, dtype=np.float64) + result["pelvis"] = { + "rest_global": identity.tolist(), + "posed_global": identity.tolist(), + "skin_matrix": identity.tolist(), + "angle_degrees": {"hip": 0.0, "knee": 0.0, "ankle": 0.0}, + } + for side in _SIDES: + frame = _mapping(frames[side], f"binding.rest_frames.{side}") + thigh_rest, knee_rest, knee_local = _frame_matrices(frame, side) + thigh_inverse = _inverse_rigid(thigh_rest, + f"binding.rest_frames.{side}.thigh.rest_global") + hip_rotation = _matrix_rotation_x(-angles[side]["hip"]) + knee_rotation = _matrix_rotation_x(angles[side]["knee"]) + thigh_pose = thigh_rest @ hip_rotation + knee_pose = thigh_pose @ thigh_inverse @ knee_rest @ knee_rotation + thigh_skin = thigh_pose @ thigh_inverse + knee_skin = knee_pose @ _inverse_rigid( + knee_rest, f"binding.rest_frames.{side}.knee.rest_global" + ) + for name, matrix in (("thigh posed", thigh_pose), ("knee posed", knee_pose), + ("thigh skin", thigh_skin), ("knee skin", knee_skin)): + if not np.all(np.isfinite(matrix)): + _fail(f"{side} {name} matrix is non-finite") + + points = {} + for name in ("J", "T", "K", "A"): + points[name] = _vector(frame.get(name), + f"binding.rest_frames.{side}.{name}") + rest_knee_from_parent = _point(np.eye(4), points["K"], + f"{side} rest K") + posed_j = _point(thigh_skin, points["J"], f"{side} posed J") + posed_t = _point(thigh_skin, points["T"], f"{side} posed T") + posed_k_parent = _point(thigh_skin, points["K"], f"{side} posed K parent") + posed_k_knee = _point(knee_skin, points["K"], f"{side} posed K knee") + if not np.allclose(posed_k_parent, posed_k_knee, + atol=_FRAME_TOLERANCE, rtol=0.0): + _fail(f"{side} posed K differs between parent hip and knee") + posed_a = _point(knee_skin, points["A"], f"{side} posed A") + rest_points = {name: points[name] for name in ("J", "T", "K", "A")} + posed_points = {"J": posed_j, "T": posed_t, "K": posed_k_parent, "A": posed_a} + result[side] = { + "J": posed_j, + "T": posed_t, + "K": posed_k_parent, + "A": posed_a, + "rest_points": rest_points, + "posed_points": posed_points, + "rest_J": rest_points["J"], + "rest_T": rest_points["T"], + "rest_K": rest_points["K"], + "rest_A": rest_points["A"], + "posed_J": posed_points["J"], + "posed_T": posed_points["T"], + "posed_K": posed_points["K"], + "posed_A": posed_points["A"], + "posed_K_from_parent": posed_k_parent, + "posed_K_from_knee": posed_k_knee, + "thigh": { + "rest_global": thigh_rest.tolist(), + "posed_global": thigh_pose.tolist(), + "skin_matrix": thigh_skin.tolist(), + }, + "knee": { + "rest_global": knee_rest.tolist(), + "rest_local": knee_local.tolist(), + "posed_global": knee_pose.tolist(), + "skin_matrix": knee_skin.tolist(), + }, + # Short aliases keep the diagnostic convenient while the nested + # records above make the hierarchy and matrix roles explicit. + "rest_matrix": thigh_rest.tolist(), + "posed_matrix": thigh_pose.tolist(), + "skin_matrix": thigh_skin.tolist(), + "knee_rest_matrix": knee_rest.tolist(), + "knee_rest_local_matrix": knee_local.tolist(), + "knee_posed_matrix": knee_pose.tolist(), + "knee_skin_matrix": knee_skin.tolist(), + "angle_degrees": copy.deepcopy(angles[side]), + "rest_K_from_parent": rest_knee_from_parent, + } + if has_arms: + frame = _mapping(frames[side], f"binding.rest_frames.{side}") + shoulder = _mapping(frame.get("shoulder"), + f"binding.rest_frames.{side}.shoulder") + elbow = _mapping(frame.get("elbow"), + f"binding.rest_frames.{side}.elbow") + shoulder_rest = _matrix( + shoulder.get("rest_global", shoulder.get("rest_matrix")), + f"binding.rest_frames.{side}.shoulder.rest_global") + elbow_rest = _matrix( + elbow.get("rest_global", elbow.get("rest_matrix")), + f"binding.rest_frames.{side}.elbow.rest_global") + expected_elbow_local = _inverse_rigid( + shoulder_rest, f"binding.rest_frames.{side}.shoulder.rest_global") @ elbow_rest + elbow_local = _matrix( + elbow.get("rest_local"), + f"binding.rest_frames.{side}.elbow.rest_local") + if not np.allclose(elbow_local, expected_elbow_local, + atol=_FRAME_TOLERANCE, rtol=0.0): + _fail(f"binding.rest_frames.{side}.elbow.rest_local does not match shoulder hierarchy") + arm_points = _mapping(frame.get("arm_source_points"), + f"binding.rest_frames.{side}.arm_source_points") + arm_J = _vector(arm_points.get("J"), + f"binding.rest_frames.{side}.arm_source_points.J") + arm_E = _vector(arm_points.get("E"), + f"binding.rest_frames.{side}.arm_source_points.E") + arm_W = _vector(arm_points.get("W"), + f"binding.rest_frames.{side}.arm_source_points.W") + side_sign = -1.0 if side == "left" else 1.0 + shoulder_rotation = ( + _matrix_rotation_z(side_sign * angles[side]["shoulder_raise"]) @ + _matrix_rotation_x(-angles[side]["shoulder_forward"]) + ) + elbow_rotation = _matrix_rotation_x(-angles[side]["elbow"]) + shoulder_pose = shoulder_rest @ shoulder_rotation + elbow_pose = ( + shoulder_pose @ + _inverse_rigid(shoulder_rest, + f"binding.rest_frames.{side}.shoulder.rest_global") @ + elbow_rest @ elbow_rotation + ) + shoulder_skin = shoulder_pose @ _inverse_rigid( + shoulder_rest, f"binding.rest_frames.{side}.shoulder.rest_global") + elbow_skin = elbow_pose @ _inverse_rigid( + elbow_rest, f"binding.rest_frames.{side}.elbow.rest_global") + posed_arm_J = _point(shoulder_skin, arm_J, f"{side} posed arm J") + posed_arm_E_parent = _point(shoulder_skin, arm_E, + f"{side} posed arm E parent") + posed_arm_E_elbow = _point(elbow_skin, arm_E, + f"{side} posed arm E elbow") + if not np.allclose(posed_arm_E_parent, posed_arm_E_elbow, + atol=_FRAME_TOLERANCE, rtol=0.0): + _fail(f"{side} posed arm E differs between shoulder and elbow") + posed_arm_W = _point(elbow_skin, arm_W, f"{side} posed arm W") + result[side].update({ + "arm_rest_points": {"J": arm_J, "E": arm_E, "W": arm_W}, + "arm_posed_points": { + "J": posed_arm_J, "E": posed_arm_E_parent, "W": posed_arm_W, + }, + "rest_arm_J": arm_J, + "rest_arm_E": arm_E, + "rest_arm_W": arm_W, + "posed_arm_J": posed_arm_J, + "posed_arm_E": posed_arm_E_parent, + "posed_arm_W": posed_arm_W, + "posed_arm_E_from_shoulder": posed_arm_E_parent, + "posed_arm_E_from_elbow": posed_arm_E_elbow, + "shoulder": { + "rest_global": shoulder_rest.tolist(), + "posed_global": shoulder_pose.tolist(), + "skin_matrix": shoulder_skin.tolist(), + }, + "elbow": { + "rest_global": elbow_rest.tolist(), + "rest_local": elbow_local.tolist(), + "posed_global": elbow_pose.tolist(), + "skin_matrix": elbow_skin.tolist(), + }, + "arm_angle_degrees": { + "shoulder_raise": angles[side]["shoulder_raise"], + "shoulder_forward": angles[side]["shoulder_forward"], + "elbow": angles[side]["elbow"], + }, + }) + if has_head: + head_frame = _mapping(frames.get("head"), "binding.rest_frames.head") + head_rest = _matrix( + head_frame.get("rest_global", head_frame.get("rest_matrix")), + "binding.rest_frames.head.rest_global", + ) + head_J = _vector(head_frame.get("J"), "binding.rest_frames.head.J") + if not np.allclose(head_rest[:3, 3], head_J, + atol=_FRAME_TOLERANCE, rtol=0.0): + _fail("binding.rest_frames.head pivot does not match its rest frame") + head_rotation = ( + _matrix_rotation_y(angles["head"]["yaw"]) @ + _matrix_rotation_x(angles["head"]["nod"]) + ) + head_pose = head_rest @ head_rotation + head_skin = head_pose @ _inverse_rigid( + head_rest, "binding.rest_frames.head.rest_global") + forward_rest = np.asarray(head_J, dtype=np.float64) + [0.0, 0.0, 1.0] + posed_head_J = _point(head_skin, head_J, "posed head J") + posed_forward = _point(head_skin, forward_rest.tolist(), + "posed head forward endpoint") + result["head"] = { + "rest_J": head_J, + "posed_J": posed_head_J, + "rest_forward_endpoint": forward_rest.tolist(), + "posed_forward_endpoint": posed_forward, + "rest_forward_direction": [0.0, 0.0, 1.0], + "posed_forward_direction": (np.asarray(posed_forward) - + np.asarray(posed_head_J)).tolist(), + "rest_global": head_rest.tolist(), + "posed_global": head_pose.tolist(), + "skin_matrix": head_skin.tolist(), + "angle_degrees": copy.deepcopy(angles["head"]), + "pose_rotation_order": "Ry(yaw) @ Rx(nod)", + "pivot_source": head_frame.get("pivot_source"), + } + return result + + +def _rest_stencils(rest_mesh: Mapping[str, Any], base_count: int, + rest_count: int) -> list[list[tuple[int, float]]]: + raw = rest_mesh.get("base_stencils") + if not isinstance(raw, (list, tuple)) or len(raw) != rest_count: + _fail("rest_mesh.base_stencils must have one stencil per L2 vertex") + result: list[list[tuple[int, float]]] = [] + for vertex_index, stencil in enumerate(raw): + if not isinstance(stencil, (list, tuple)) or not stencil: + _fail(f"rest_mesh.base_stencils[{vertex_index}] must be non-empty") + row: list[tuple[int, float]] = [] + total = 0.0 + for term_index, term in enumerate(stencil): + if not isinstance(term, (list, tuple)) or len(term) != 2: + _fail(f"rest_mesh.base_stencils[{vertex_index}][{term_index}] must be [index, coefficient]") + base_index = _integer(term[0], + f"rest_mesh.base_stencils[{vertex_index}][{term_index}][0]") + if base_index < 0 or base_index >= base_count: + _fail(f"rest_mesh.base_stencils[{vertex_index}] contains an out-of-range index") + coefficient = _number(term[1], + f"rest_mesh.base_stencils[{vertex_index}][{term_index}][1]") + if coefficient < -_TOLERANCE: + _fail(f"rest_mesh.base_stencils[{vertex_index}] contains a negative coefficient") + row.append((base_index, coefficient)) + total += coefficient + if abs(total - 1.0) > _TOLERANCE: + _fail(f"rest_mesh.base_stencils[{vertex_index}] does not partition unity") + result.append(row) + return result + + +def _propagate_weights(stencils: list[list[tuple[int, float]]], + base_weights: np.ndarray) -> np.ndarray: + evaluated = np.zeros((len(stencils), base_weights.shape[1]), dtype=np.float64) + for vertex_index, stencil in enumerate(stencils): + for base_index, coefficient in stencil: + evaluated[vertex_index] += coefficient * base_weights[base_index] + _check_weight_bounds(evaluated, "evaluated_weights") + return evaluated + + +def _apply_station_weights(base_weights: np.ndarray, + rings: dict[str, list[list[int]]]) -> None: + for side, thigh_column, shank_column in ( + ("left", 1, 2), ("right", 3, 4) + ): + for station_index, ring in enumerate(rings[side]): + shank = _STATION_SHANK_WEIGHTS[station_index] + thigh = 1.0 - shank + for vertex_index in ring: + base_weights[vertex_index, thigh_column] = thigh + base_weights[vertex_index, shank_column] = shank + + +def _apply_foot_weights(base_weights: np.ndarray, + feet: dict[str, list[int]]) -> None: + for side, shank_column in (("left", 2), ("right", 4)): + for vertex_index in feet[side]: + if np.any(base_weights[vertex_index] != 0.0): + _fail(f"base_mesh.metadata.feet.{side} overwrites an existing base allocation") + base_weights[vertex_index, shank_column] = 1.0 + + +def _arm_appendage_blends(base_quads: list[list[int]], + arms: Mapping[str, Any]) -> dict[str, dict[int, float]]: + """Solve the separate arm elbow blend with semantic section anchors.""" + result: dict[str, dict[int, float]] = {} + for side in _SIDES: + row = arms[side] + sections = row["sections"] + zero = set(row["collar"]) | set(sections["upper_belly"]) | set(sections["pre_elbow"]) + free = set(sections["elbow"]) + one = (set(sections["post_elbow"]) | set(sections["forearm_belly"]) | + set(sections["pre_wrist"]) | set(sections["wrist"]) | + set(sections["palm"]) | set(sections["knuckle"]) | + set(sections["terminal"]) | {row["cap"]}) + if not zero or not free or not one or zero & free or zero & one or free & one: + _fail(f"base_mesh arm {side} has overlapping elbow blend regions") + graph: dict[int, set[int]] = {index: set() for index in zero | free | one} + for face in base_quads: + for corner, left in enumerate(face): + right = face[(corner + 1) % 4] + if left in graph and right in graph: + graph[left].add(right) + graph[right].add(left) + free_sorted = sorted(free) + positions = {index: row_index for row_index, index in enumerate(free_sorted)} + matrix = np.eye(len(free_sorted), dtype=np.float64) + rhs = np.zeros(len(free_sorted), dtype=np.float64) + for index in free_sorted: + neighbours = graph[index] + if not neighbours or not (neighbours & (zero | one)): + _fail(f"base_mesh arm {side} elbow blend is not anchored") + row_index = positions[index] + for neighbour in neighbours: + if neighbour in positions: + matrix[row_index, positions[neighbour]] -= 1.0 / len(neighbours) + elif neighbour in one: + rhs[row_index] += 1.0 / len(neighbours) + try: + values = np.linalg.solve(matrix, rhs) + except np.linalg.LinAlgError as exc: + raise ValueError(f"base_mesh arm {side} elbow blend is singular") from exc + if not np.all(np.isfinite(values)): + _fail(f"base_mesh arm {side} elbow blend is non-finite") + result[side] = {index: 0.0 for index in zero} + result[side].update({index: float(value) for index, value in zip(free_sorted, values)}) + result[side].update({index: 1.0 for index in one}) + return result + + +def _apply_arm_weights(base_weights: np.ndarray, + arms: Mapping[str, Any], + arm_blends: Mapping[str, Mapping[int, float]], + influence: Mapping[str, Any]) -> None: + for side, upper_column, fore_column in ( + ("left", 5, 6), ("right", 7, 8) + ): + for vertex_index, blend in arm_blends[side].items(): + if np.any(base_weights[vertex_index] != 0.0): + _fail(f"base_mesh arm {side} overwrites an existing base allocation") + if blend < -_TOLERANCE or blend > 1.0 + _TOLERANCE: + _fail(f"base_mesh arm {side} elbow blend is outside [0, 1]") + base_weights[vertex_index, upper_column] = 1.0 - blend + base_weights[vertex_index, fore_column] = blend + for side, upper_column in (("left", 5), ("right", 7)): + for vertex_index, value in influence["fields"][side].items(): + if value < -_TOLERANCE or value > 1.0 + _TOLERANCE: + _fail(f"base_mesh arm {side} shoulder influence is outside [0, 1]") + old = np.array(base_weights[vertex_index, :5], copy=True) + if np.any(base_weights[vertex_index, 5:] != 0.0): + _fail(f"base_mesh arm {side} root influence overwrites an arm allocation") + base_weights[vertex_index, :5] = old * (1.0 - value) + base_weights[vertex_index, upper_column] = value + + +def _apply_head_weights(base_weights: np.ndarray, + head: Mapping[str, Any], + influence: Mapping[str, Any], + neck_column: int) -> None: + """Apply the head one-hot appendage and its root D0/D1 transition field.""" + for vertex_index in head["new_vertex_indices"]: + if np.any(base_weights[vertex_index] != 0.0): + _fail("base_mesh head overwrites an existing base allocation") + base_weights[vertex_index, neck_column] = 1.0 + for vertex_index, value in influence["field"].items(): + if value < -_TOLERANCE or value > 1.0 + _TOLERANCE: + _fail("base_mesh head neck influence is outside [0, 1]") + if base_weights[vertex_index, neck_column] != 0.0: + _fail("base_mesh head root influence overwrites the neck allocation") + base_weights[vertex_index] *= 1.0 - value + base_weights[vertex_index, neck_column] = value + + +def _apply_tail_weights(base_weights: np.ndarray, + tail: Mapping[str, Any]) -> dict[str, Any]: + """Blend validated original-host support into the existing pelvis joint.""" + pelvis = np.zeros(base_weights.shape[1], dtype=np.float64) + pelvis[0] = 1.0 + applied: dict[str, Any] = {} + collar_strength = float(tail["collar_blend_strength"]) + for ring, fraction in zip(tail["rings"], tail["station_fractions"]): + pelvis_fraction = collar_strength + (1.0 - collar_strength) * float(fraction) + support_fraction = 1.0 - pelvis_fraction + for vertex_index in ring: + if np.any(base_weights[vertex_index] != 0.0): + _fail(f"tail vertex {vertex_index} overwrites an existing allocation") + host_indices, convex = tail["supports"][vertex_index] + host_support = np.zeros(base_weights.shape[1], dtype=np.float64) + for host_index, coefficient in zip(host_indices, convex): + host_support += coefficient * base_weights[host_index] + row = support_fraction * host_support + pelvis_fraction * pelvis + _check_weight_bounds(row.reshape(1, -1), f"tail base weight {vertex_index}") + base_weights[vertex_index] = row + applied[str(vertex_index)] = { + "ring_fraction": float(fraction), + "pelvis_fraction": pelvis_fraction, + "host_support_fraction": support_fraction, + "host_vertex_indices": list(host_indices), + "convex_weights": list(convex), + } + return { + "collar_blend_strength": collar_strength, + "distal_joint": "pelvis", + "vertices": applied, + "no_tail_joint": True, + } + + +def _frame_records(legs: dict[str, dict[str, list[float]]]) -> dict[str, dict[str, Any]]: + result: dict[str, dict[str, Any]] = {} + for side in _SIDES: + points = legs[side] + thigh = _frame(points["J"], points["K"], f"{side} thigh") + knee = _frame(points["K"], points["A"], f"{side} knee") + thigh_rest = _matrix(thigh["rest_global"], f"{side} thigh rest frame") + knee_rest = _matrix(knee["rest_global"], f"{side} knee rest frame") + knee_local = _inverse_rigid(thigh_rest, f"{side} thigh rest frame") @ knee_rest + result[side] = { + **copy.deepcopy(points), + "thigh": { + "rotation": thigh["rotation"], + "rest_global": thigh_rest.tolist(), + "rest_matrix": thigh_rest.tolist(), + }, + "knee": { + "rotation": knee["rotation"], + "rest_global": knee_rest.tolist(), + "rest_matrix": knee_rest.tolist(), + "rest_local": knee_local.tolist(), + }, + "rest_matrix": thigh_rest.tolist(), + "knee_rest_matrix": knee_rest.tolist(), + "knee_rest_local_matrix": knee_local.tolist(), + "T_local": (_inverse_rigid(thigh_rest, f"{side} thigh rest frame") @ + np.r_[np.asarray(points["T"]), 1.0]).tolist()[:3], + "K_local": (_inverse_rigid(thigh_rest, f"{side} thigh rest frame") @ + np.r_[np.asarray(points["K"]), 1.0]).tolist()[:3], + "A_local_knee": (_inverse_rigid(knee_rest, f"{side} knee rest frame") @ + np.r_[np.asarray(points["A"]), 1.0]).tolist()[:3], + } + return result + + +def _head_frame_record(frames: Mapping[str, Any], head: Mapping[str, Any]) -> dict[str, Any]: + """Record a world-aligned neck frame at the source-owned head pivot.""" + result = copy.deepcopy(dict(frames)) + J = _vector(head["J"], "base_mesh.metadata.head.binding_handoff.pivot") + matrix = np.eye(4, dtype=np.float64) + matrix[:3, 3] = np.asarray(J, dtype=np.float64) + result["head"] = { + "J": J, + "pivot_source": head["pivot_source"], + "rotation": np.eye(3, dtype=np.float64).tolist(), + "rest_global": matrix.tolist(), + "rest_matrix": matrix.tolist(), + "frame_rule": "world-aligned at source stations.neck_collar.C", + "pose_rotation_order": "Ry(yaw) @ Rx(nod)", + } + return result + + +def _arm_frame_records(frames: dict[str, dict[str, Any]], + arms: Mapping[str, Any]) -> dict[str, dict[str, Any]]: + """Add pivot frames derived from the source J->E and E->W bones.""" + result = copy.deepcopy(frames) + for side in _SIDES: + row = arms[side] + J = _vector(row["J"], f"base_mesh.metadata.arms.{side}.J") + E = _vector(row["E"], f"base_mesh.metadata.arms.{side}.E") + W = _vector(row["W"], f"base_mesh.metadata.arms.{side}.W") + shoulder = _arm_frame(J, E, f"{side} shoulder") + elbow = _arm_frame(E, W, f"{side} elbow") + shoulder_rest = _matrix(shoulder["rest_global"], + f"{side} shoulder rest frame") + elbow_rest = _matrix(elbow["rest_global"], + f"{side} elbow rest frame") + shoulder_local_elbow = _inverse_rigid( + shoulder_rest, f"{side} shoulder rest frame") @ elbow_rest + result[side]["shoulder"] = { + "rotation": shoulder["rotation"], + "rest_global": shoulder_rest.tolist(), + "rest_matrix": shoulder_rest.tolist(), + "frame_rule": shoulder["frame_rule"], + } + result[side]["elbow"] = { + "rotation": elbow["rotation"], + "rest_global": elbow_rest.tolist(), + "rest_matrix": elbow_rest.tolist(), + "rest_local": shoulder_local_elbow.tolist(), + "frame_rule": elbow["frame_rule"], + } + result[side]["arm_source_points"] = { + "J": J, "E": E, "W": W, + "frame_source": "source J->E and E->W bones; not construction P->E/E->W sections", + "pose_rotation_order": ( + "shoulder Rz(side_sign*shoulder_raise) @ Rx(-shoulder_forward); " + "elbow Rx(-elbow)" + ), + } + return result + + +def _joint_records(frames: Mapping[str, Any]) -> tuple[dict[str, dict[str, Any]], dict[str, str | None]]: + identity = np.eye(4, dtype=np.float64) + joints: dict[str, dict[str, Any]] = { + "pelvis": { + "rest_matrix": identity.tolist(), + "inverse_bind_matrix": identity.tolist(), + } + } + parents: dict[str, str | None] = {"pelvis": None} + for side in _SIDES: + frame = _mapping(frames[side], f"binding.rest_frames.{side}") + thigh_rest, knee_rest, _ = _frame_matrices(frame, side) + joints[f"{side}_hip"] = { + "rest_matrix": thigh_rest.tolist(), + "inverse_bind_matrix": _inverse_rigid( + thigh_rest, f"binding.rest_frames.{side}.thigh.rest_global" + ).tolist(), + } + joints[f"{side}_knee"] = { + "rest_matrix": knee_rest.tolist(), + "inverse_bind_matrix": _inverse_rigid( + knee_rest, f"binding.rest_frames.{side}.knee.rest_global" + ).tolist(), + } + parents[f"{side}_hip"] = "pelvis" + parents[f"{side}_knee"] = f"{side}_hip" + if "shoulder" in frame or "elbow" in frame: + if "shoulder" not in frame or "elbow" not in frame: + _fail(f"binding.rest_frames.{side} must contain both arm pivot frames") + shoulder = _matrix( + _mapping(frame["shoulder"], f"binding.rest_frames.{side}.shoulder").get("rest_global"), + f"binding.rest_frames.{side}.shoulder.rest_global") + elbow = _matrix( + _mapping(frame["elbow"], f"binding.rest_frames.{side}.elbow").get("rest_global"), + f"binding.rest_frames.{side}.elbow.rest_global") + joints[f"{side}_shoulder"] = { + "rest_matrix": shoulder.tolist(), + "inverse_bind_matrix": _inverse_rigid( + shoulder, f"binding.rest_frames.{side}.shoulder.rest_global" + ).tolist(), + } + joints[f"{side}_elbow"] = { + "rest_matrix": elbow.tolist(), + "inverse_bind_matrix": _inverse_rigid( + elbow, f"binding.rest_frames.{side}.elbow.rest_global" + ).tolist(), + } + parents[f"{side}_shoulder"] = "pelvis" + parents[f"{side}_elbow"] = f"{side}_shoulder" + if "head" in frames: + head = _mapping(frames["head"], "binding.rest_frames.head") + head_rest = _matrix( + head.get("rest_global", head.get("rest_matrix")), + "binding.rest_frames.head.rest_global", + ) + joints["neck"] = { + "rest_matrix": head_rest.tolist(), + "inverse_bind_matrix": _inverse_rigid( + head_rest, "binding.rest_frames.head.rest_global" + ).tolist(), + } + parents["neck"] = "pelvis" + return joints, parents + + +def bind(base_mesh: Mapping[str, Any], rest_mesh: Mapping[str, Any], + prior_root_mesh: Mapping[str, Any], prior_hip_binding: Mapping[str, Any], + leg_inputs: Mapping[str, Any]) -> dict[str, Any]: + """Bind legs plus optional source-owned arms and one neck/head joint.""" + base = _mapping(base_mesh, "base_mesh") + rest = _mapping(rest_mesh, "rest_mesh") + prior_root = _mapping(prior_root_mesh, "prior_root_mesh") + prior_binding = _mapping(prior_hip_binding, "prior_hip_binding") + legs, declared_support, mid_thigh_factor = _leg_inputs(leg_inputs) + base_vertices = _vertices(base, "base_mesh") + rest_vertices = _vertices(rest, "rest_mesh") + prior_vertices = _vertices(prior_root, "prior_root_mesh") + base_quads = _quads(base, len(base_vertices), "base_mesh") + prior_quads = _quads(prior_root, len(prior_vertices), "prior_root_mesh") + _quads(rest, len(rest_vertices), "rest_mesh") + _validate_levels(base, rest) + tail = _validate_root(base_vertices, base_quads, prior_vertices, prior_quads, base) + _validate_constructor_root_metadata(base, len(prior_quads), tail) + prior_weights = _prior_root_weights(prior_binding) + rings, station_points = _chain_rings( + base, len(base_vertices), legs, declared_support + ) + tail_indices = set(tail["new_vertex_indices"]) if tail is not None else set() + leg_indices = {index for side in _SIDES for ring in rings[side] for index in ring} + if tail_indices & leg_indices: + _fail("tail allocation overwrites an existing leg station allocation") + arms = _arm_vertex_indices(base, len(base_vertices), rings, tail_indices) + head = _head_vertex_indices(base, len(base_vertices), rings, arms, tail_indices) + feet = _foot_vertex_indices(base, len(base_vertices), rings, arms, head, tail_indices) + joint_order, columns = _binding_layout(bool(arms), bool(head)) + base_weights = _expanded_root_weights(prior_weights, len(base_vertices), columns) + _apply_station_weights(base_weights, rings) + _apply_foot_weights(base_weights, feet) + arm_influence = None + arm_blends = None + if arms: + arm_influence = _arm_root_influence( + base, base_quads, arms, rings, prior_quads, + ) + arm_blends = _arm_appendage_blends(base_quads, arms) + _apply_arm_weights(base_weights, arms, arm_blends, arm_influence) + head_influence = None + if head: + head_influence = _head_root_influence( + base, base_quads, head, arm_influence, prior_quads, + ) + _apply_head_weights(base_weights, head, head_influence, columns.index("neck")) + tail_weighting = None + if tail is not None: + tail_weighting = _apply_tail_weights(base_weights, tail) + _check_weight_bounds(base_weights, "base_weights") + stencils = _rest_stencils(rest, len(base_vertices), len(rest_vertices)) + evaluated_weights = _propagate_weights(stencils, base_weights) + frames = _frame_records(legs) + if arms: + frames = _arm_frame_records(frames, arms) + if head: + frames = _head_frame_record(frames, head) + joints, parents = _joint_records(frames) + ring_mapping = copy.deepcopy(rings) + bound_leg_inputs: dict[str, Any] = { + side: copy.deepcopy(dict(_mapping(leg_inputs[side], f"leg_inputs.{side}"))) + for side in _SIDES + } + for side in _SIDES: + for name in ("J", "T", "K", "A"): + bound_leg_inputs[side][name] = copy.deepcopy(legs[side][name]) + bound_leg_inputs[side]["support_fraction"] = declared_support[side] + bound_leg_inputs[side]["mid_thigh_factor"] = mid_thigh_factor[side] + result = { + "schema": "creature-kernel.connected-leg-assembly-binding.v1", + "joint_order": list(joint_order), + "weight_columns": list(columns), + "joints": joints, + "parents": parents, + "base_weights": base_weights.tolist(), + "evaluated_weights": evaluated_weights.tolist(), + "rest_frames": frames, + "leg_inputs": bound_leg_inputs, + "station_names": list(_STATION_NAMES), + "source_station_ids": list(_SOURCE_STATION_IDS), + "station_points": station_points, + "station_shank_weights": list(_STATION_SHANK_WEIGHTS), + "source_station_knee": list(_STATION_SHANK_WEIGHTS), + "prior_column_map": [0, 1, 3], + "chain_ring_mapping": ring_mapping, + "metadata": { + "algorithm": ( + "preserved_prior_root_hip_weights_plus_explicit_source_station_knee_blend_" + + ("source_root_arm_harmonic_and_source_root_neck_field_" + if arms and head else + "source_root_neck_field_" if head else + "source_root_arm_harmonic_" if arms else "") + + ("tail_host_support_to_pelvis_transition_" if tail is not None else "") + + f"then_l2_rest_stencil_{len(joint_order)}joint_lbs" + ), + "weight_method": "shared_source_station_knee_blend_with_explicit_center_and_support_rows", + "harmonic_knee_solver": False, + "numeric_guard": ( + "prior-baseline bound tolerance [-1e-12,1+1e-12]; validation " + "guard only, with no clamping, renormalization, or method retune" + ), + "tolerance": _TOLERANCE, + "coordinate_system": "metres; Y up; Z front", + "weight_columns": list(columns), + "joint_order": list(joint_order), + "parents": parents, + "root_vertex_count": _ROOT_VERTEX_COUNT, + "root_quad_count": len(prior_quads), + "station_count_per_side": _STATION_COUNT, + "ring_vertex_count": _RING_VERTEX_COUNT, + "station_names": list(_STATION_NAMES), + "source_station_ids": list(_SOURCE_STATION_IDS), + "station_points": station_points, + "station_shank_weights": list(_STATION_SHANK_WEIGHTS), + "source_station_knee": list(_STATION_SHANK_WEIGHTS), + "prior_column_map": [0, 1, 3], + "support_fraction": copy.deepcopy(declared_support), + "mid_thigh_factor": copy.deepcopy(mid_thigh_factor), + "chain_ring_mapping": ring_mapping, + "stencil_provenance": "REST", + "posed_cage_evaluation": False, + "rest_geometry_regenerated": False, + "root_weight_source": "prior_hip_binding.base_weights positional 152x3 captured calibration table", + "root_weight_mapping": { + "pelvis": "prior column 0", + "left_thigh": "prior column 1", + "left_shank": "zero", + "right_thigh": "prior column 2", + "right_shank": "zero", + }, + "hierarchy": { + "pelvis": "identity", + "left_shank": "left_thigh_parent", + "right_shank": "right_thigh_parent", + "ankle_joint": "not_present; later distal extension", + "tail_joint": "not_present; tail vertices transition to pelvis only", + }, + }, + } + if arms: + arm_indices = { + side: copy.deepcopy(row["new_vertex_indices"]) + for side, row in arms.items() + } + result["arm_vertex_indices"] = arm_indices + result["arm_root_influence"] = copy.deepcopy(arm_influence) + result["arm_elbow_blend"] = { + side: {str(index): value for index, value in values.items()} + for side, values in arm_blends.items() + } + result["metadata"]["arm_vertex_indices"] = copy.deepcopy(arm_indices) + result["metadata"]["arm_root_influence"] = copy.deepcopy(arm_influence) + result["metadata"]["arm_elbow_blend"] = copy.deepcopy(result["arm_elbow_blend"]) + result["metadata"]["arm_weighting"] = { + "root": "D0/D1 free root graph field; collar value 1; D2 zero boundary", + "collar_pre_elbow": 0.0, + "elbow": "free arm-appendage harmonic blend", + "post_elbow_onward": 1.0, + } + result["metadata"]["root_weight_mapping"].update({ + "left_upper_arm": "source arm harmonic influence", + "left_forearm": "zero on root; arm elbow blend on appended arm", + "right_upper_arm": "source arm harmonic influence", + "right_forearm": "zero on root; arm elbow blend on appended arm", + }) + result["metadata"]["hierarchy"].update({ + "left_forearm": "left_upper_arm_parent", + "right_forearm": "right_upper_arm_parent", + "left_shoulder": "pelvis", + "left_elbow": "left_shoulder_parent", + "right_shoulder": "pelvis", + "right_elbow": "right_shoulder_parent", + "pivot_frame_source": "source J->E and E->W bones; visible P->E frame excluded", + }) + if head: + head_indices = copy.deepcopy(head["new_vertex_indices"]) + result["head_vertex_indices"] = head_indices + result["head_root_influence"] = copy.deepcopy(head_influence) + result["metadata"]["head_vertex_indices"] = copy.deepcopy(head_indices) + result["metadata"]["head_root_influence"] = copy.deepcopy(head_influence) + result["metadata"]["head_weighting"] = { + "root": "D0/D1 free root graph field; neck support ring value 1; D2 zero boundary", + "appendage": "head, muzzle, and ears neck one-hot", + "shoulder_overlap": copy.deepcopy(head_influence["per_root"]["shoulder_overlap"]), + "pivot_source": "stations.neck_collar.C", + "neck_upper_port_is_pivot": False, + } + result["metadata"]["root_weight_mapping"]["neck"] = ( + "source head neck harmonic influence" + ) + result["metadata"]["hierarchy"].update({ + "neck": "pelvis", + "head_pivot": "stations.neck_collar.C", + "head_frame": "world-aligned at source pivot; neck_upper is connection port only", + }) + if any(feet.values()): + result["foot_vertex_indices"] = copy.deepcopy(feet) + result["metadata"]["foot_vertex_indices"] = copy.deepcopy(feet) + result["metadata"]["foot_weighting"] = { + "left": "left_shank_onehot", + "right": "right_shank_onehot", + "ankle_joint": "not_present", + } + if tail is not None: + result["tail_vertex_indices"] = copy.deepcopy(tail["new_vertex_indices"]) + result["tail_weighting"] = copy.deepcopy(tail_weighting) + result["metadata"]["tail_vertex_indices"] = copy.deepcopy(tail["new_vertex_indices"]) + result["metadata"]["tail_weighting"] = copy.deepcopy(tail_weighting) + result["metadata"]["tail_weighting_contract"] = { + "host_face": tail["host_face"], + "host_vertex_indices": copy.deepcopy(tail["host_vertices"]), + "kept_root_face_correspondence": copy.deepcopy(tail["kept_faces"]), + "replacement_face_indices": copy.deepcopy(tail["replacement_faces"]), + "collar_blend_strength": tail["collar_blend_strength"], + "distal_target_joint": "pelvis", + "tail_joint": "not_present", + } + return result + + +def joint_points(binding: Mapping[str, Any], angles: Mapping[str, Any]) -> dict[str, dict[str, Any]]: + """Return rest/posed hierarchy diagnostics for pelvis, hips, knees, and landmarks.""" + return _joint_transforms(_mapping(binding, "binding"), angles) + + +def pose(rest_mesh: Mapping[str, Any], binding: Mapping[str, Any], + angles: Mapping[str, Any]) -> dict[str, Any]: + """Apply the bound five-, six-, nine-, or ten-column LBS to rest L2.""" + rest = _mapping(rest_mesh, "rest_mesh") + bound = _mapping(binding, "binding") + vertices = _vertices(rest, "rest_mesh") + joint_order = tuple(bound.get("joint_order", ())) + valid_layouts = { + _LEG_JOINT_ORDER: (False, False), + _ARM_JOINT_ORDER: (True, False), + _HEAD_JOINT_ORDER: (False, True), + _ARM_HEAD_JOINT_ORDER: (True, True), + } + if joint_order not in valid_layouts: + _fail("binding.joint_order must be a five-, six-, nine-, or ten-joint layout") + has_arms, has_head = valid_layouts[joint_order] + _expected_joint_order, columns = _binding_layout(has_arms, has_head) + weights = _weight_matrix(bound.get("evaluated_weights"), len(vertices), + len(columns), "binding.evaluated_weights") + transforms = _joint_transforms(bound, angles) + skins = { + "pelvis": np.eye(4, dtype=np.float64), + "left_hip": _matrix(transforms["left"]["thigh"]["skin_matrix"], + "left hip skin_matrix"), + "left_knee": _matrix(transforms["left"]["knee"]["skin_matrix"], + "left knee skin_matrix"), + "right_hip": _matrix(transforms["right"]["thigh"]["skin_matrix"], + "right hip skin_matrix"), + "right_knee": _matrix(transforms["right"]["knee"]["skin_matrix"], + "right knee skin_matrix"), + } + if has_arms: + skins.update({ + "left_shoulder": _matrix(transforms["left"]["shoulder"]["skin_matrix"], + "left shoulder skin_matrix"), + "left_elbow": _matrix(transforms["left"]["elbow"]["skin_matrix"], + "left elbow skin_matrix"), + "right_shoulder": _matrix(transforms["right"]["shoulder"]["skin_matrix"], + "right shoulder skin_matrix"), + "right_elbow": _matrix(transforms["right"]["elbow"]["skin_matrix"], + "right elbow skin_matrix"), + }) + if has_head: + skins["neck"] = _matrix(transforms["head"]["skin_matrix"], + "neck skin_matrix") + parsed_angles = _angles(angles) + if not has_arms and any(parsed_angles[side][joint] != 0.0 + for side in _SIDES + for joint in ("shoulder_raise", "shoulder_forward", "elbow")): + _fail("arm pose angles require a nine-column arm binding") + if not has_head and any(parsed_angles["head"][joint] != 0.0 + for joint in ("yaw", "nod")): + _fail("head pose angles require a six- or ten-column head binding") + pose_angle_names = ("hip", "knee", "shoulder_raise", "shoulder_forward", "elbow") + no_body_motion = all(parsed_angles[side][joint] == 0.0 + for side in _SIDES for joint in pose_angle_names) + no_head_motion = all(parsed_angles["head"][joint] == 0.0 + for joint in ("yaw", "nod")) + if no_body_motion and no_head_motion: + posed_vertices = copy.deepcopy(vertices) + else: + posed_vertices = [] + for vertex_index, point in enumerate(vertices): + homogeneous = np.r_[np.asarray(point, dtype=np.float64), 1.0] + transformed = np.column_stack([ + (skins[name] @ homogeneous)[:3] for name in joint_order + ]) + value = transformed @ weights[vertex_index] + if not np.all(np.isfinite(value)): + _fail(f"posed vertex {vertex_index} is non-finite") + posed_vertices.append(value.tolist()) + + output = copy.deepcopy(dict(rest)) + output["vertices"] = posed_vertices + provenance = output.get("provenance", {}) + provenance = copy.deepcopy(dict(provenance)) if isinstance(provenance, Mapping) else {} + provenance.update({ + "vertices": f"POSED_BY_EVALUATED_REST_L2_{len(joint_order)}JOINT_LBS", + "rest_vertices": "INPUT_REST_L2", + "base_stencils": "REST", + "stencil_evaluation": "evaluated rest mesh; posed cage not evaluated", + }) + output["provenance"] = provenance + metadata = output.get("metadata", {}) + metadata = copy.deepcopy(dict(metadata)) if isinstance(metadata, Mapping) else {} + metadata.update({ + "representation": "pose", + "rest_geometry_regenerated": False, + "stencil_provenance": "REST", + "posed_cage_evaluation": False, + "pose_angles_degrees": copy.deepcopy(parsed_angles), + "joint_order": list(joint_order), + }) + output["metadata"] = metadata + return output + + +__all__ = ["bind", "joint_points", "pose"] diff --git a/experiments/connected-leg-assembly/body-chest-envelope-config.json b/experiments/connected-leg-assembly/body-chest-envelope-config.json new file mode 100644 index 0000000..a6ada85 --- /dev/null +++ b/experiments/connected-leg-assembly/body-chest-envelope-config.json @@ -0,0 +1,36 @@ +{ + "schema": "creature-kernel.connected-leg-assembly-body-chest-envelope-config.v1", + "status": "prepared; static-only; capture required before geometry execution", + "evidence_label": "CHEST-ENVELOPE001 causal experiment; informal WIP only; no human checkpoint or aesthetic acceptance claim.", + "acceptance": "numeric or mechanical passes do not imply anatomy acceptance", + "rationale": "Start from body-junction-integration-config.json and replace only the torso source input with the explicit source-linked chest envelope; the JUNCTION-001 component selection remains unchanged.", + "budget": "one shared CHEST-ENVELOPE001 candidate for both calibrated bodies; zero aesthetic corrections", + "execution_gate": "Raman capture and Main direct review are required before geometry execution", + "activation": { + "selection": "explicit body-config selection only", + "default_configs_unchanged": true, + "file_presence_is_not_activation": true, + "fallback": false + }, + "torso_refinement": { + "inputs": "torso-chest-envelope-inputs.json" + }, + "arms": { + "inputs": "arm-refinement-inputs.json" + }, + "head": { + "inputs": "head-refinement-inputs.json" + }, + "feet": { + "builder": "foot_junction_construction.py", + "inputs": "foot-form-inputs.json", + "policy": "foot-junction-policy.json", + "replaces": "FOOT003", + "candidate": "JUNCTION-001", + "status": "statically validated; downstream geometry capture pending" + }, + "tail": { + "builder": "tail_construction.py", + "inputs": "tail-inputs.json" + } +} diff --git a/experiments/connected-leg-assembly/body-junction-integration-config.json b/experiments/connected-leg-assembly/body-junction-integration-config.json new file mode 100644 index 0000000..f4d67ba --- /dev/null +++ b/experiments/connected-leg-assembly/body-junction-integration-config.json @@ -0,0 +1,34 @@ +{ + "schema": "creature-kernel.connected-leg-assembly-body-junction-integration-config.v1", + "status": "prepared; static-only; capture required before geometry execution", + "evidence_label": "Explicit JUNCTION-001 wholebody integration candidate; no visual or human acceptance claim.", + "acceptance": "numeric or mechanical passes do not imply anatomy acceptance", + "execution_gate": "Raman capture and Main direct review are required before geometry execution", + "activation": { + "selection": "explicit body-config selection only", + "default_configs_unchanged": true, + "file_presence_is_not_activation": true, + "fallback": false + }, + "torso_refinement": { + "inputs": "torso-silhouette-inputs.json" + }, + "arms": { + "inputs": "arm-refinement-inputs.json" + }, + "head": { + "inputs": "head-refinement-inputs.json" + }, + "feet": { + "builder": "foot_junction_construction.py", + "inputs": "foot-form-inputs.json", + "policy": "foot-junction-policy.json", + "replaces": "FOOT003", + "candidate": "JUNCTION-001", + "status": "statically validated; downstream geometry capture pending" + }, + "tail": { + "builder": "tail_construction.py", + "inputs": "tail-inputs.json" + } +} diff --git a/experiments/connected-leg-assembly/captured_tests.py b/experiments/connected-leg-assembly/captured_tests.py new file mode 100644 index 0000000..0b1c6ee --- /dev/null +++ b/experiments/connected-leg-assembly/captured_tests.py @@ -0,0 +1,170 @@ +"""Capture, verify, and run one selected unittest file from captured source. + +This is a thin entrypoint over :mod:`runner` capture provenance. It does not +copy dependencies independently, discover live tests, or claim a hermetic host. +""" +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import re +import subprocess +import sys +from typing import Any, Callable, Mapping + +import runner + + +_TEST_NAME = re.compile(r"^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*$") + + +class CapturedTestError(ValueError): + """Raised when a captured test cannot be resolved or executed safely.""" + + +def _logical_path(value: str) -> str: + path = Path(value) + if path.is_absolute() or ".." in path.parts or path.suffix != ".py": + raise CapturedTestError("test file must be a relative Python source path") + return path.as_posix() + + +def _captured_path(manifest: Mapping[str, Any], snapshot: Path, + logical_path: str) -> Path: + source = manifest.get("source") + rows = source.get("files") if isinstance(source, Mapping) else None + if not isinstance(rows, list): + raise CapturedTestError("capture manifest has no source file inventory") + matches = [row for row in rows + if isinstance(row, Mapping) and row.get("path") == logical_path] + if len(matches) != 1 or not isinstance(matches[0].get("snapshot_path"), str): + raise CapturedTestError( + f"capture manifest does not resolve exactly one {logical_path!r}") + recorded = Path(str(matches[0]["snapshot_path"])) + candidate = recorded if recorded.is_absolute() else snapshot / recorded + try: + resolved = candidate.resolve(strict=True) + resolved.relative_to(snapshot.resolve(strict=True)) + except (OSError, ValueError) as exc: + raise CapturedTestError( + f"captured test path escapes or is unavailable: {candidate}") from exc + if resolved.is_symlink() or not resolved.is_file(): + raise CapturedTestError(f"captured test is not a regular file: {resolved}") + return resolved + + +def _managed_python(manifest: Mapping[str, Any]) -> Path: + runtime = manifest.get("runtime") + value = runtime.get("executable") if isinstance(runtime, Mapping) else None + if not isinstance(value, str): + raise CapturedTestError("capture manifest has no managed runtime executable") + path = Path(value) + if (not path.is_absolute() or not path.is_file() + or not os.access(path, os.X_OK)): + raise CapturedTestError(f"managed runtime executable is unavailable: {path}") + # Preserve the exact recorded invocation path. Resolving a venv's + # bin/python symlink can bypass its pyvenv.cfg and site packages. + return path + + +def _capture_names(runner_module: Any, logical_test: str) -> list[str]: + names = list(runner_module.CAPTURE_FILES) + for required in ("runner.py", "captured_tests.py", logical_test): + if required not in names: + names.append(required) + return names + + +def run_captured_tests( + snapshot_value: str | os.PathLike[str], test_file: str, + test_names: list[str] | tuple[str, ...] = (), *, + runner_module: Any = runner, + process_run: Callable[..., subprocess.CompletedProcess[str]] | None = None, +) -> dict[str, Any]: + """Capture first, then run only ``test_file`` from its manifest path.""" + snapshot = Path(snapshot_value).resolve() + logical_test = _logical_path(test_file) + selected = list(test_names) + if any(not _TEST_NAME.fullmatch(name) for name in selected): + raise CapturedTestError("test names must be dotted unittest identifiers") + + manifest = runner_module.prepare( + snapshot, file_names=_capture_names(runner_module, logical_test)) + captured_test = _captured_path(manifest, snapshot, logical_test) + manifest_path = snapshot / "manifest.json" + runner_module.verify(snapshot) + interpreter = _managed_python(manifest) + command = [str(interpreter), str(captured_test), *selected, "-v"] + environment = dict(os.environ) + environment.pop("PYTHONPATH", None) + environment["PYTHONDONTWRITEBYTECODE"] = "1" + invoke = subprocess.run if process_run is None else process_run + + process_error: dict[str, str] | None = None + completed: subprocess.CompletedProcess[str] | None = None + try: + completed = invoke( + command, cwd=str(captured_test.parent), env=environment, + text=True, capture_output=True, check=False) + except Exception as exc: # The post-test verification still must run. + process_error = {"type": type(exc).__name__, "message": str(exc)} + + postverify_error: dict[str, str] | None = None + try: + runner_module.verify(snapshot) + except Exception as exc: + postverify_error = {"type": type(exc).__name__, "message": str(exc)} + + returncode = completed.returncode if completed is not None else None + status = ("passed" if returncode == 0 and process_error is None + and postverify_error is None else "failed") + return { + "schema": "creature-kernel.connected-leg-assembly-captured-tests.v1", + "status": status, + "snapshot_path": str(snapshot), + "manifest_path": str(manifest_path), + "captured_test_path": str(captured_test), + "managed_python": str(interpreter), + "selected_tests": selected or [""], + "command": command, + "preverify": "passed", + "test": { + "returncode": returncode, + "stdout": completed.stdout if completed is not None else "", + "stderr": completed.stderr if completed is not None else "", + "exception": process_error, + }, + "postverify": "failed" if postverify_error else "passed", + "postverify_error": postverify_error, + "limitations": [ + *list(manifest.get("limitations", [])), + "Only the selected captured test script is launched; its own unittest selector semantics determine methods run.", + "External frozen dependencies and the managed runtime retain the capture manifest's reuse and host-hermeticity limits.", + ], + } + + +def _main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description="Capture and run selected connected-leg unittests") + parser.add_argument("--snapshot", required=True) + parser.add_argument("--test-file", required=True) + parser.add_argument("--test-name", action="append", default=[]) + args = parser.parse_args(argv) + try: + report = run_captured_tests( + args.snapshot, args.test_file, args.test_name) + except Exception as exc: + report = { + "schema": "creature-kernel.connected-leg-assembly-captured-tests.v1", + "status": "error", + "exception": {"type": type(exc).__name__, "message": str(exc)}, + } + print(json.dumps(report, sort_keys=True, indent=2, allow_nan=False), flush=True) + return 0 if report.get("status") == "passed" else 1 + + +if __name__ == "__main__": + raise SystemExit(_main()) diff --git a/experiments/connected-leg-assembly/checks.py b/experiments/connected-leg-assembly/checks.py new file mode 100644 index 0000000..016d032 --- /dev/null +++ b/experiments/connected-leg-assembly/checks.py @@ -0,0 +1,3676 @@ +"""Independent checks for the planned connected-leg staging experiment. + +This module is deliberately a checker only. It does not build geometry, call +the binding implementation, repair meshes, or select a morphology. Missing +protocol information is reported as unavailable and never becomes a pass. +""" + +from __future__ import annotations + +from collections import defaultdict +import copy +import hashlib +import importlib.util +import math +from pathlib import Path +import sys +from typing import Any, Iterable, Mapping, Sequence + + +_JOINTS = ("pelvis", "left_hip", "left_knee", "right_hip", "right_knee") +_WEIGHT_COLUMNS = ("pelvis", "left_thigh", "left_shank", "right_thigh", "right_shank") +_ARM_JOINTS = (*_JOINTS, "left_shoulder", "left_elbow", "right_shoulder", "right_elbow") +_ARM_WEIGHT_COLUMNS = (*_WEIGHT_COLUMNS, "left_upper_arm", "left_forearm", + "right_upper_arm", "right_forearm") +_HEAD_JOINTS = (*_JOINTS, "neck") +_HEAD_WEIGHT_COLUMNS = (*_WEIGHT_COLUMNS, "neck") +_ARM_HEAD_JOINTS = (*_ARM_JOINTS, "neck") +_ARM_HEAD_WEIGHT_COLUMNS = (*_ARM_WEIGHT_COLUMNS, "neck") +_SIDES = ("left", "right") +_OLD_ROOT_VERTEX_COUNT = 152 +_OLD_WEIGHT_COLUMNS = ("pelvis", "left_leg", "right_leg") +_FIXED_PRIOR_COLUMN_MAP = (0, 1, 3) +_STATION_NAMES = ( + "mid_thigh", "knee_pre_support", "knee", "knee_post_support", + "calf", "ankle_approach", "ankle", +) +_STATION_SHANK_WEIGHTS = (0.0, 0.0, 0.5, 1.0, 1.0, 1.0, 1.0) +_ARM_SECTION_NAMES = ( + "upper_belly", "pre_elbow", "elbow", "post_elbow", "forearm_belly", + "pre_wrist", "wrist", "palm", "knuckle", "terminal", +) +_ARM_FRAME_SOURCE = "source J->E and E->W bones; not construction P->E/E->W sections" +_HEAD_FRAME_SOURCE = "world-aligned at source stations.neck_collar.C" +_TAIL_SUPPORT_OWN = 0.55 +_TAIL_SUPPORT_OTHER = 0.15 +_MAX_COLLISION_BLOCK = 1800 +_EXAMPLE_CAP = 8 + +_FROZEN_CORE = Path( + "/home/ben/.cache/creature-kernel/pelvis-thigh-transition/" + "attempt-2-snapshot/source/experiments/owned-root-assembly-successor/" + "mesh_correctness.py" +) +_BROADPHASE: Any | None = None + + +def _report(schema: str) -> dict[str, Any]: + return { + "schema": schema, + "pass": False, + "available": True, + "outcome": "fail", + "checks": {}, + "metrics": {}, + "diagnostics": {}, + "uncertainties": [], + "errors": [], + } + + +def _error(report: dict[str, Any], code: str, detail: str, **data: Any) -> None: + row: dict[str, Any] = {"code": code, "detail": detail} + row.update(data) + report["errors"].append(row) + + +def _unavailable(report: dict[str, Any], code: str, detail: str, **data: Any) -> None: + report["available"] = False + _error(report, code, detail, **data) + + +def _finish(report: dict[str, Any]) -> dict[str, Any]: + values = list(report["checks"].values()) + report["pass"] = bool(report["available"] and not report["errors"] and values and all(values)) + report["outcome"] = "pass" if report["pass"] else "unavailable" if not report["available"] else "fail" + return report + + +def _mapping(value: Any, label: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping): + raise ValueError(f"{label} must be a mapping") + return value + + +def _sequence(value: Any, label: str) -> list[Any]: + if isinstance(value, (str, bytes, bytearray)) or value is None: + raise ValueError(f"{label} must be a sequence") + try: + result = list(value) + except (TypeError, ValueError) as exc: + raise ValueError(f"{label} must be a sequence") from exc + return result + + +def _number(value: Any, label: str) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ValueError(f"{label} must be numeric") + result = float(value) + if not math.isfinite(result): + raise ValueError(f"{label} must be finite") + return result + + +def _vector(value: Any, label: str) -> tuple[float, float, float]: + values = _sequence(value, label) + if len(values) != 3: + raise ValueError(f"{label} must have three components") + return tuple(_number(item, f"{label}[{index}]") for index, item in enumerate(values)) # type: ignore[return-value] + + +def _matrix(value: Any, label: str) -> list[list[float]]: + raw = _sequence(value, label) + if len(raw) == 16: + raw = [raw[index:index + 4] for index in range(0, 16, 4)] + if len(raw) != 4 or any(not isinstance(row, Sequence) or len(row) != 4 for row in raw): + raise ValueError(f"{label} must be a 4x4 matrix") + result = [[_number(item, f"{label}[{r}][{c}]") for c, item in enumerate(row)] for r, row in enumerate(raw)] + return result + + +def _mesh(mesh: Any, label: str) -> dict[str, Any]: + value = _mapping(mesh, label) + raw_vertices = _sequence(value.get("vertices"), f"{label}.vertices") + vertices = [_vector(point, f"{label}.vertices[{index}]") for index, point in enumerate(raw_vertices)] + if not vertices: + raise ValueError(f"{label}.vertices must not be empty") + raw_quads = _sequence(value.get("quads"), f"{label}.quads") + quads: list[tuple[int, int, int, int]] = [] + for face_index, raw_face in enumerate(raw_quads): + face = _sequence(raw_face, f"{label}.quads[{face_index}]") + if len(face) != 4 or any(isinstance(index, bool) or not isinstance(index, int) for index in face): + raise ValueError(f"{label}.quads[{face_index}] must contain four integer indices") + checked = tuple(int(index) for index in face) + if len(set(checked)) != 4 or any(index < 0 or index >= len(vertices) for index in checked): + raise ValueError(f"{label}.quads[{face_index}] contains an invalid index") + quads.append(checked) # type: ignore[arg-type] + if not quads: + raise ValueError(f"{label}.quads must not be empty") + return { + "value": value, + "vertices": vertices, + "quads": quads, + "face_owners": value.get("face_owners"), + "loops": value.get("loops", value.get("boundary_loops")), + "stencils": value.get("base_stencils"), + "metadata": value.get("metadata", {}), + } + + +def _edge_incidence(quads: Sequence[Sequence[int]]) -> dict[tuple[int, int], list[tuple[int, int, int]]]: + result: dict[tuple[int, int], list[tuple[int, int, int]]] = defaultdict(list) + for face_index, face in enumerate(quads): + for slot, start in enumerate(face): + end = face[(slot + 1) % 4] + result[(min(start, end), max(start, end))].append((face_index, start, end)) + return dict(result) + + +def _boundary_cycles(incidence: Mapping[tuple[int, int], Sequence[tuple[int, int, int]]]) -> list[list[int]]: + outgoing: dict[int, list[int]] = defaultdict(list) + for uses in incidence.values(): + if len(uses) == 1: + _, start, end = uses[0] + outgoing[start].append(end) + if any(len(targets) != 1 for targets in outgoing.values()): + raise ValueError("boundary edges do not form directed cycles") + next_vertex = {start: targets[0] for start, targets in outgoing.items()} + remaining = set(next_vertex) + result: list[list[int]] = [] + while remaining: + start = min(remaining) + current = start + cycle: list[int] = [] + while current in remaining: + remaining.remove(current) + cycle.append(current) + current = next_vertex[current] + if current != start or len(cycle) < 3: + raise ValueError("boundary edge cycle is not closed") + result.append(cycle) + return result + + +def _cyclic_equal(actual: Sequence[int], expected: Sequence[int]) -> bool: + left = tuple(actual) + right = tuple(expected) + return any(left == target[index:] + target[:index] + for target in (right, tuple(reversed(right))) + for index in range(len(right))) + + +def _connected_components(quads: Sequence[Sequence[int]], vertex_count: int) -> int: + adjacency = [set() for _ in range(vertex_count)] + for face in quads: + for left, right in zip(face, face[1:] + face[:1]): + adjacency[left].add(right) + adjacency[right].add(left) + unseen = set(range(vertex_count)) + count = 0 + while unseen: + count += 1 + todo = [unseen.pop()] + while todo: + for neighbour in adjacency[todo.pop()].intersection(unseen): + unseen.remove(neighbour) + todo.append(neighbour) + return count + + +def _cross(a: Sequence[float], b: Sequence[float]) -> tuple[float, float, float]: + return (a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0]) + + +def _sub(a: Sequence[float], b: Sequence[float]) -> tuple[float, float, float]: + return tuple(float(a[index]) - float(b[index]) for index in range(3)) # type: ignore[return-value] + + +def _add(a: Sequence[float], b: Sequence[float]) -> tuple[float, float, float]: + return tuple(float(a[index]) + float(b[index]) for index in range(3)) # type: ignore[return-value] + + +def _scale(a: Sequence[float], factor: float) -> tuple[float, float, float]: + return tuple(float(value) * factor for value in a) # type: ignore[return-value] + + +def _dot(a: Sequence[float], b: Sequence[float]) -> float: + return sum(float(a[index]) * float(b[index]) for index in range(3)) + + +def _norm(a: Sequence[float]) -> float: + return math.sqrt(_dot(a, a)) + + +def _distance(a: Sequence[float], b: Sequence[float]) -> float: + return _norm(_sub(a, b)) + + +def _triangles(quads: Sequence[Sequence[int]]) -> list[tuple[int, int, int]]: + return [triangle for face in quads for triangle in ((face[0], face[1], face[2]), (face[0], face[2], face[3]))] + + +def _triangle_normal(vertices: Sequence[Sequence[float]], triangle: Sequence[int]) -> tuple[float, float, float]: + return _cross(_sub(vertices[triangle[1]], vertices[triangle[0]]), + _sub(vertices[triangle[2]], vertices[triangle[0]])) + + +def _triangle_area(vertices: Sequence[Sequence[float]], triangle: Sequence[int]) -> float: + return 0.5 * _norm(_triangle_normal(vertices, triangle)) + + +def _limit(protocol: Mapping[str, Any], names: Sequence[str]) -> float | tuple[float, float] | None: + pending: list[Mapping[str, Any]] = [protocol] + sources: list[Mapping[str, Any]] = [] + while pending: + source = pending.pop(0) + sources.append(source) + pending.extend(value for value in source.values() if isinstance(value, Mapping)) + for source in sources: + for name in names: + if name in source: + value = source[name] + if isinstance(value, Sequence) and not isinstance(value, (str, bytes)) and len(value) == 2: + return (_number(value[0], name), _number(value[1], name)) + return _number(value, name) + return None + + +def _require_limit(report: dict[str, Any], protocol: Mapping[str, Any], names: Sequence[str]) -> float | tuple[float, float]: + value = _limit(protocol, names) + if value is None: + _unavailable(report, "missing_protocol_threshold", f"protocol threshold is required: {names[0]}") + raise ValueError(f"missing protocol threshold {names[0]}") + return value + + +def _owner_is_inherited_lower(owner: Any) -> bool: + if not isinstance(owner, str): + return False + normal = owner.lower().replace("-", "_").replace(" ", "_") + return any(word in normal for word in ("pelvis", "hip", "abdomen")) + + +def _prior_face_count(mesh: Mapping[str, Any], protocol: Mapping[str, Any]) -> int | None: + metadata = mesh.get("metadata") + for source in (protocol, protocol.get("checks"), metadata): + if isinstance(source, Mapping): + for key in ("prior_face_count", "new_face_start", "original_face_count"): + if key in source: + value = source[key] + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + return None + return value + if isinstance(metadata, Mapping): + root = metadata.get("root") + if isinstance(root, Mapping): + value = root.get("face_count") + level = mesh.get("level", metadata.get("level", 0)) + if (isinstance(value, int) and not isinstance(value, bool) and value >= 0 + and isinstance(level, int) and not isinstance(level, bool) + and level >= 0): + return value * (4 ** level) + return None + + +def _lower_faces(parsed: Mapping[str, Any], protocol: Mapping[str, Any]) -> tuple[set[int], set[int], int | None]: + owners = parsed.get("face_owners") + if not isinstance(owners, Sequence) or len(owners) != len(parsed["quads"]): + raise ValueError("face_owners must cover every face for lower collision checks") + start = _prior_face_count(parsed["value"], protocol) + if start is None or start > len(owners): + raise ValueError("prior_face_count/new_face_start is required and must fit the face array") + lower = {index for index in range(start) if _owner_is_inherited_lower(owners[index])} + lower.update(range(start, len(owners))) + upper = set(range(start)).difference(lower) + return lower, upper, start + + +def _load_intersection_core() -> Any: + path = _FROZEN_CORE + if not path.is_file() or path.is_symlink(): + return None + spec = importlib.util.spec_from_file_location("connected_leg_generic_intersection", path) + if spec is None or spec.loader is None: + return None + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + function = getattr(module, "intersection_diagnostics", None) + if callable(function): + return function + return None + + +def _load_broadphase() -> Any: + """Load the captured broadphase wrapper beside this checker.""" + path = Path(__file__).resolve().with_name("collision_broadphase.py") + if not path.is_file() or path.is_symlink(): + return None + spec = importlib.util.spec_from_file_location( + "connected_leg_collision_broadphase", path + ) + if spec is None or spec.loader is None: + return None + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + try: + spec.loader.exec_module(module) + except Exception: + if sys.modules.get(spec.name) is module: + sys.modules.pop(spec.name, None) + return None + if Path(str(module.__file__)).resolve() != path: + return None + return module + + +def _set_broadphase(module: Any) -> None: + """Install the already-captured wrapper loaded by the runner.""" + global _BROADPHASE + _BROADPHASE = module + + +def _frozen_core_sha256() -> str | None: + try: + if not _FROZEN_CORE.is_file() or _FROZEN_CORE.is_symlink(): + return None + digest = hashlib.sha256() + with _FROZEN_CORE.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + except OSError: + return None + + +def _foot_collision_report(vertices: Sequence[Sequence[float]], + quads: Sequence[Sequence[int]], + owners: Sequence[str], lower_faces: set[int], + upper_faces: set[int]) -> dict[str, Any]: + """Adapt the accepted broadphase report to the checker face inventory. + + The wrapper owns broadphase, frozen narrowphase, and complete pair + accounting. This adapter only maps triangle ids to quad faces and keeps + the existing lower/upper ownership classification. + """ + result: dict[str, Any] = { + "available": False, + "coverage_complete": False, + "vertex_array_reused": True, + "method": None, + "narrowphase": None, + "blocks": [], + "calls": [], + "hit_triangle_pairs": [], + "hit_face_pairs": [], + "lower_hit_pairs": [], + "upper_only_hit_pairs": [], + "errors": [], + "intersection_core_path": str(_FROZEN_CORE), + "intersection_core_sha256": _frozen_core_sha256(), + "scope": {"triangle_count": 0, "pair_count": 0, + "complete_pair_accounting": False}, + } + triangles = _triangles(quads) + result["scope"]["triangle_count"] = len(triangles) + if not triangles: + result["errors"].append({ + "code": "empty_triangle_inventory", + "detail": "collision inventory is empty", + }) + return result + broadphase = _BROADPHASE or _load_broadphase() + collision_report = getattr(broadphase, "collision_report", None) + declared_core = getattr(broadphase, "FROZEN_CORE_PATH", None) + if (not callable(collision_report) or declared_core is None + or Path(str(declared_core)).resolve() != _FROZEN_CORE.resolve()): + result["errors"].append({ + "code": "broadphase_unavailable", + "detail": "accepted collision broadphase wrapper or pinned core is unavailable", + "wrapper_core_path": str(declared_core) if declared_core is not None else None, + }) + return result + result["method"] = getattr(broadphase, "METHOD", None) + try: + wrapped = collision_report(vertices, triangles, include_classifications=False) + if not isinstance(wrapped, Mapping): + raise ValueError("collision broadphase report must be an object") + result["narrowphase"] = wrapped.get("narrowphase") + result["blocks"] = wrapped.get("blocks", []) + result["pair_partition_complete"] = bool(wrapped.get("pair_partition_complete")) + result["final_classification_partition_complete"] = bool( + wrapped.get("final_classification_partition_complete") + ) + result["class_counts"] = wrapped.get("class_counts", {}) + result["survivor_pair_count"] = wrapped.get("survivor_pair_count") + result["hit_pairs_truncated"] = bool(wrapped.get("hit_pairs_truncated")) + result["scope"]["pair_count"] = wrapped.get("pair_count", 0) + result["scope"]["complete_pair_accounting"] = bool( + wrapped.get("pair_partition_complete") + and wrapped.get("final_classification_partition_complete") + and not wrapped.get("hit_pairs_truncated") + ) + result["coverage_complete"] = result["scope"]["complete_pair_accounting"] + result["errors"].extend(list(wrapped.get("errors", ()))) + result["candidate_pairs_truncated"] = bool(wrapped.get("candidate_pairs_truncated")) + result["nontrivial_evidence_truncated"] = bool(wrapped.get("nontrivial_evidence_truncated")) + result["expected_pair_count"] = wrapped.get("pair_count") + result["covered_pair_count"] = ( + wrapped.get("pair_count") if result["coverage_complete"] else + wrapped.get("survivor_pair_count") + ) + result["hit_triangle_pairs"] = [ + list(pair) for pair in wrapped.get("hit_pairs", ()) + ] + seen_faces: set[tuple[int, int]] = set() + for raw_pair in result["hit_triangle_pairs"]: + if len(raw_pair) != 2: + result["errors"].append({ + "code": "malformed_hit_pair", + "detail": "broadphase returned a non-pair hit record", + }) + continue + triangle_pair = tuple(sorted((int(raw_pair[0]), int(raw_pair[1])))) + face_pair = tuple(sorted((triangle_pair[0] // 2, triangle_pair[1] // 2))) + if face_pair[0] == face_pair[1] or face_pair in seen_faces: + continue + if any(index < 0 or index >= len(owners) for index in face_pair): + result["errors"].append({ + "code": "hit_face_out_of_range", + "detail": "broadphase hit pair mapped outside face ownership", + "triangles": list(triangle_pair), + }) + continue + seen_faces.add(face_pair) + row = {"triangles": list(triangle_pair), "faces": list(face_pair), + "owners": [owners[face_pair[0]], owners[face_pair[1]]]} + result["hit_face_pairs"].append(row) + if face_pair[0] in lower_faces or face_pair[1] in lower_faces: + result["lower_hit_pairs"].append(row) + elif face_pair[0] in upper_faces and face_pair[1] in upper_faces: + result["upper_only_hit_pairs"].append(row) + result["global_face_pair_count"] = len(seen_faces) + result["available"] = bool(wrapped.get("available") and + result["coverage_complete"] and + not result["errors"]) + except Exception as exc: + result["errors"].append({"code": "broadphase_failure", "detail": str(exc)}) + result["hit_triangle_pairs"] = sorted(result["hit_triangle_pairs"]) + result["hit_face_pairs"] = sorted(result["hit_face_pairs"], key=lambda row: tuple(row["faces"])) + result["lower_hit_pairs"] = sorted(result["lower_hit_pairs"], key=lambda row: tuple(row["faces"])) + result["upper_only_hit_pairs"] = sorted(result["upper_only_hit_pairs"], key=lambda row: tuple(row["faces"])) + result["pass"] = bool(result["available"] and not result["lower_hit_pairs"]) + return result + + +def _collision_report(vertices: Sequence[Sequence[float]], quads: Sequence[Sequence[int]], + owners: Sequence[str], lower_faces: set[int], upper_faces: set[int]) -> dict[str, Any]: + result: dict[str, Any] = { + "available": False, + "coverage_complete": False, + "vertex_array_reused": True, + "block_size": _MAX_COLLISION_BLOCK, + "blocks": [], + "calls": [], + "hit_triangle_pairs": [], + "hit_face_pairs": [], + "lower_hit_pairs": [], + "upper_only_hit_pairs": [], + "errors": [], + "intersection_core_path": str(_FROZEN_CORE), + } + triangles = _triangles(quads) + if not triangles: + result["errors"].append({"code": "empty_triangle_inventory", "detail": "collision inventory is empty"}) + return result + intersection_diagnostics = _load_intersection_core() + if intersection_diagnostics is None: + result["errors"].append({"code": "intersection_unavailable", "detail": "generic intersection diagnostic could not be loaded"}) + return result + + blocks = [list(range(start, min(start + _MAX_COLLISION_BLOCK, len(triangles)))) + for start in range(0, len(triangles), _MAX_COLLISION_BLOCK)] + result["blocks"] = [{"block": index, "triangle_ids": ids, "triangle_count": len(ids)} + for index, ids in enumerate(blocks)] + seen_triangle_pairs: set[tuple[int, int]] = set() + seen_face_pairs: set[tuple[int, int]] = set() + expected_pairs = len(triangles) * (len(triangles) - 1) // 2 + covered_pairs = 0 + + for first_block in range(len(blocks)): + for second_block in range(first_block, len(blocks)): + local_ids = blocks[first_block] if first_block == second_block else blocks[first_block] + blocks[second_block] + local_triangles = [triangles[index] for index in local_ids] + call: dict[str, Any] = { + "blocks": [first_block, second_block], + "triangle_count": len(local_triangles), + "pair_policy_complete": False, + "hit_pairs": [], + } + try: + diagnostic = intersection_diagnostics(vertices, local_triangles) + call["pair_count"] = diagnostic.get("pair_count") + call["processed_pair_count"] = diagnostic.get("pair_policy_evidence", {}).get("processed_pair_count") + call["pair_policy_complete"] = bool(diagnostic.get("pair_policy_complete")) + call["candidate_pairs_truncated"] = bool(diagnostic.get("candidate_pairs_truncated")) + call["hit_pairs_truncated"] = bool(diagnostic.get("hit_pairs_truncated")) + expected_local_pairs = len(local_triangles) * (len(local_triangles) - 1) // 2 + call["expected_pair_count"] = expected_local_pairs + call["processed_pair_count_matches"] = ( + call["pair_count"] == expected_local_pairs + and call["processed_pair_count"] == expected_local_pairs + ) + if first_block == second_block: + covered_pairs += len(blocks[first_block]) * (len(blocks[first_block]) - 1) // 2 + else: + covered_pairs += len(blocks[first_block]) * len(blocks[second_block]) + if not call["pair_policy_complete"] or not call["processed_pair_count_matches"]: + result["errors"].append({"code": "incomplete_pair_policy", "detail": "generic core did not process every local pair", "blocks": call["blocks"]}) + if call["hit_pairs_truncated"]: + result["errors"].append({"code": "truncated_collision_inventory", "detail": "generic core truncated intersection-hit evidence", "blocks": call["blocks"]}) + for local_first, local_second in diagnostic.get("hit_pairs", ()): + first = local_ids[int(local_first)] + second = local_ids[int(local_second)] + triangle_pair = tuple(sorted((first, second))) + if triangle_pair in seen_triangle_pairs: + continue + seen_triangle_pairs.add(triangle_pair) + face_pair = tuple(sorted((triangle_pair[0] // 2, triangle_pair[1] // 2))) + if face_pair[0] == face_pair[1]: + continue + if face_pair in seen_face_pairs: + continue + seen_face_pairs.add(face_pair) + row = { + "triangles": list(triangle_pair), + "faces": list(face_pair), + "owners": [owners[face_pair[0]], owners[face_pair[1]]], + } + call["hit_pairs"].append(list(triangle_pair)) + result["hit_triangle_pairs"].append(list(triangle_pair)) + result["hit_face_pairs"].append(row) + if face_pair[0] in lower_faces or face_pair[1] in lower_faces: + result["lower_hit_pairs"].append(row) + elif face_pair[0] in upper_faces and face_pair[1] in upper_faces: + result["upper_only_hit_pairs"].append(row) + except Exception as exc: + result["errors"].append({"code": "intersection_failure", "detail": str(exc), "blocks": call["blocks"]}) + result["calls"].append(call) + + result["expected_pair_count"] = expected_pairs + result["covered_pair_count"] = covered_pairs + result["coverage_complete"] = (covered_pairs == expected_pairs + and all(call["pair_policy_complete"] for call in result["calls"]) + and all(call.get("processed_pair_count_matches") for call in result["calls"]) + and not any(call.get("hit_pairs_truncated") for call in result["calls"])) + result["candidate_detail_truncated_calls"] = [ + call["blocks"] for call in result["calls"] if call.get("candidate_pairs_truncated") + ] + if result["candidate_detail_truncated_calls"]: + result["limitations"] = [ + "Broad-phase candidate detail is bounded, but the frozen core reports complete pair-policy processing and complete intersection-hit evidence." + ] + result["available"] = result["coverage_complete"] and not result["errors"] + result["hit_triangle_pairs"] = sorted(result["hit_triangle_pairs"]) + result["hit_face_pairs"] = sorted(result["hit_face_pairs"], key=lambda row: tuple(row["faces"])) + result["lower_hit_pairs"] = sorted(result["lower_hit_pairs"], key=lambda row: tuple(row["faces"])) + result["upper_only_hit_pairs"] = sorted(result["upper_only_hit_pairs"], key=lambda row: tuple(row["faces"])) + result["global_face_pair_count"] = len(seen_face_pairs) + result["pass"] = bool(result["available"] and not result["lower_hit_pairs"]) + return result + + +def _declared_loop_names(protocol: Mapping[str, Any]) -> set[str]: + for source in (protocol, protocol.get("checks")): + if isinstance(source, Mapping) and "boundary_loop_names" in source: + return {str(item) for item in _sequence(source["boundary_loop_names"], "boundary_loop_names")} + return {"neck", "arm.left", "arm.right", "ankle.left", "ankle.right"} + + +def _loop_role(name: str) -> str | None: + normal = name.lower().replace("_", ".").replace("-", ".").replace("port", "") + normal = ".".join(part for part in normal.split(".") if part) + aliases = { + "neck": "neck", "neck.upper": "neck", "upper.neck": "neck", + "arm.left": "arm.left", "left.arm": "arm.left", "left.arm.upper": "arm.left", + "arm.right": "arm.right", "right.arm": "arm.right", "right.arm.upper": "arm.right", + "ankle.left": "ankle.left", "left.ankle": "ankle.left", "left.thigh": "ankle.left", + "ankle.right": "ankle.right", "right.ankle": "ankle.right", "right.thigh": "ankle.right", + } + return aliases.get(normal) + + +def _arm_metadata_contract(mesh: Mapping[str, Any], vertex_count: int, + occupied: set[int] | None = None) -> dict[str, Any]: + """Validate the explicit connected-arm L0 allocation and J/E/W sources.""" + metadata = _mapping(mesh.get("metadata"), "mesh.metadata") + raw_arms = metadata.get("arms") + if raw_arms is None: + return {"present": False, "indices": {side: [] for side in _SIDES}, + "all_indices": set()} + arms = _mapping(raw_arms, "mesh.metadata.arms") + if set(arms) != set(_SIDES): + raise ValueError("mesh.metadata.arms must contain exactly left and right") + root = _mapping(metadata.get("root"), "mesh.metadata.root") + root_count = root.get("vertex_count") + if (isinstance(root_count, bool) or not isinstance(root_count, int) + or root_count != _OLD_ROOT_VERTEX_COUNT): + raise ValueError("mesh.metadata.root.vertex_count must preserve the original 152-vertex root") + base_count = metadata.get("base_vertex_count", vertex_count) + if (isinstance(base_count, bool) or not isinstance(base_count, int) + or not root_count < base_count <= vertex_count): + raise ValueError("mesh.metadata.base_vertex_count must lie inside the mesh vertex count") + + result: dict[str, Any] = {"present": True, "indices": {}, + "source_points": {}, "base_count": base_count, + "root_count": root_count} + all_indices: set[int] = set() + for side in _SIDES: + row = _mapping(arms[side], f"mesh.metadata.arms.{side}") + if row.get("J_source") != f"shoulders.{side}.arm_origin": + raise ValueError(f"mesh.metadata.arms.{side}.J_source must identify the calibrated arm_origin") + source_port = _mapping(row.get("source_port"), + f"mesh.metadata.arms.{side}.source_port") + if source_port.get("name") != f"port.{side}_arm": + raise ValueError(f"mesh.metadata.arms.{side}.source_port.name must identify the named arm port") + port = _sequence(source_port.get("indices"), + f"mesh.metadata.arms.{side}.source_port.indices") + if len(port) != 8 or len(set(port)) != 8: + raise ValueError(f"mesh.metadata.arms.{side}.source_port.indices must contain eight unique vertices") + if any(isinstance(index, bool) or not isinstance(index, int) + for index in port): + raise ValueError(f"mesh.metadata.arms.{side}.source_port.indices must contain integer vertices") + if any(index < 0 or index >= root_count for index in port): + raise ValueError(f"mesh.metadata.arms.{side}.source_port.indices must reference root vertices") + port = [int(index) for index in port] + + collar = _mapping(row.get("collar"), f"mesh.metadata.arms.{side}.collar") + collar_values = _sequence(collar.get("indices"), + f"mesh.metadata.arms.{side}.collar.indices") + if len(collar_values) != 8 or len(set(collar_values)) != 8: + raise ValueError(f"mesh.metadata.arms.{side}.collar.indices must contain eight unique vertices") + if any(isinstance(index, bool) or not isinstance(index, int) + for index in collar_values): + raise ValueError(f"mesh.metadata.arms.{side}.collar.indices must contain integer vertices") + collar_indices = [int(index) for index in collar_values] + + section_values = _sequence(row.get("sections"), + f"mesh.metadata.arms.{side}.sections") + if len(section_values) != len(_ARM_SECTION_NAMES): + raise ValueError(f"mesh.metadata.arms.{side}.sections must contain the complete named arm sections") + sections: dict[str, list[int]] = {} + for name, raw_section in zip(_ARM_SECTION_NAMES, section_values): + section = _mapping(raw_section, + f"mesh.metadata.arms.{side}.sections.{name}") + if section.get("name") != name: + raise ValueError(f"mesh.metadata.arms.{side}.sections order/name mismatch") + values = _sequence(section.get("indices"), + f"mesh.metadata.arms.{side}.sections.{name}.indices") + if len(values) != 8 or len(set(values)) != 8: + raise ValueError(f"mesh.metadata.arms.{side}.sections.{name}.indices must contain eight unique vertices") + if any(isinstance(index, bool) or not isinstance(index, int) + for index in values): + raise ValueError(f"mesh.metadata.arms.{side}.sections.{name}.indices must contain integer vertices") + sections[name] = [int(index) for index in values] + cap = _mapping(row.get("cap"), f"mesh.metadata.arms.{side}.cap") + cap_value = cap.get("vertex") + if isinstance(cap_value, bool) or not isinstance(cap_value, int): + raise ValueError(f"mesh.metadata.arms.{side}.cap.vertex must be an integer vertex") + cap_index = int(cap_value) + new_indices = _sequence(row.get("new_vertex_indices"), + f"mesh.metadata.arms.{side}.new_vertex_indices") + expected = collar_indices + [index for name in _ARM_SECTION_NAMES + for index in sections[name]] + [cap_index] + if any(isinstance(index, bool) or not isinstance(index, int) + for index in new_indices): + raise ValueError(f"mesh.metadata.arms.{side}.new_vertex_indices must contain integer vertices") + checked_new = [int(index) for index in new_indices] + if checked_new != expected: + raise ValueError(f"mesh.metadata.arms.{side}.new_vertex_indices disagrees with semantic sections") + if len(set(checked_new)) != len(checked_new): + raise ValueError(f"mesh.metadata.arms.{side} contains overlapping vertex allocations") + if any(index < root_count or index >= base_count for index in checked_new): + raise ValueError(f"mesh.metadata.arms.{side} contains an invalid appended vertex") + if all_indices.intersection(checked_new) or (occupied and occupied.intersection(checked_new)): + raise ValueError(f"mesh.metadata.arms.{side} overwrites another L0 allocation") + + source_points = { + name: _vector(row.get(name), f"mesh.metadata.arms.{side}.{name}") + for name in ("J", "E", "W") + } + if (source_points["J"] == source_points["E"] + or source_points["E"] == source_points["W"]): + raise ValueError(f"mesh.metadata.arms.{side} J/E/W bones must be non-degenerate") + result["indices"][side] = checked_new + result["source_points"][side] = source_points + all_indices.update(checked_new) + result["all_indices"] = all_indices + return result + + +def _head_metadata_contract(mesh: Mapping[str, Any], vertex_count: int, + occupied: set[int] | None = None) -> dict[str, Any]: + """Validate the one-joint neck/head handoff without treating the upper port as pivot.""" + metadata = _mapping(mesh.get("metadata"), "mesh.metadata") + raw_head = metadata.get("head") + if raw_head is None: + return {"present": False, "source_port": [], "support": [], + "new_vertex_indices": [], "all_indices": set()} + head = _mapping(raw_head, "mesh.metadata.head") + handoff = _mapping(head.get("binding_handoff"), "mesh.metadata.head.binding_handoff") + if handoff.get("joint") != "neck_head": + raise ValueError("head.binding_handoff.joint must be neck_head") + if handoff.get("pivot_source") != "stations.neck_collar.C": + raise ValueError("head binding pivot must be stations.neck_collar.C") + pivot = _vector(handoff.get("pivot"), "head.binding_handoff.pivot") + if head.get("neck_source") != "stations.neck_upper": + raise ValueError("head.neck_source must identify the upper port, not the pivot") + port = [int(index) for index in _sequence(head.get("neck_port_indices"), + "head.neck_port_indices")] + consumed = [int(index) for index in _sequence( + handoff.get("consumed_neck_port_indices"), + "head.binding_handoff.consumed_neck_port_indices")] + if len(port) != 6 or len(set(port)) != 6: + raise ValueError("head.neck_port_indices must contain six unique vertices") + if len(consumed) != 6 or len(set(consumed)) != 6 or consumed != port: + raise ValueError("head consumed neck boundary must exactly equal the six-point upper port") + if any(index < 0 or index >= _OLD_ROOT_VERTEX_COUNT for index in port): + raise ValueError("head.neck_port_indices must reference the original root") + + stations = _sequence(head.get("stations"), "head.stations") + support_rows = [ + _mapping(row, "head station") for row in stations + if isinstance(row, Mapping) and row.get("name") == "neck_support" + ] + if len(support_rows) != 1: + raise ValueError("head.stations must contain exactly one neck_support station") + support = [int(index) for index in _sequence( + support_rows[0].get("indices"), "head.stations.neck_support.indices")] + handoff_support = [int(index) for index in _sequence( + handoff.get("neck_support_ring_indices"), + "head.binding_handoff.neck_support_ring_indices")] + if len(support) != 6 or len(set(support)) != 6 or support != handoff_support: + raise ValueError("head neck_support ring and binding handoff must contain the same six vertices") + + new_indices = [int(index) for index in _sequence( + head.get("new_vertex_indices"), "head.new_vertex_indices")] + handoff_new = [int(index) for index in _sequence( + handoff.get("head_new_vertex_indices"), + "head.binding_handoff.head_new_vertex_indices")] + if new_indices != handoff_new or len(set(new_indices)) != len(new_indices): + raise ValueError("head vertex allocation and binding handoff must agree exactly") + if not new_indices or any(index < _OLD_ROOT_VERTEX_COUNT or index >= vertex_count + for index in new_indices): + raise ValueError("head.new_vertex_indices must be unique appended L0 vertices") + if any(index not in set(new_indices) for index in support): + raise ValueError("head neck_support vertices must be part of the head allocation") + feature = head.get("feature_new_vertex_indices", ()) + if feature is not None: + feature_indices = [int(index) for index in _sequence(feature, "head.feature_new_vertex_indices")] + if any(index not in set(new_indices) for index in feature_indices): + raise ValueError("head feature allocation must be contained in head.new_vertex_indices") + all_indices = set(new_indices) + if occupied and all_indices.intersection(occupied): + raise ValueError("head allocation overwrites another connected allocation") + return {"present": True, "J": pivot, "pivot_source": handoff["pivot_source"], + "source_port": port, "consumed_neck_port_indices": consumed, + "support": support, "new_vertex_indices": new_indices, + "all_indices": all_indices, "root_count": _OLD_ROOT_VERTEX_COUNT, + "base_count": metadata.get("base_vertex_count", vertex_count)} + + +def _tail_metadata_contract(mesh: Mapping[str, Any], vertex_count: int) -> dict[str, Any]: + """Validate the explicit pinned host-58 tail handoff without inferring anatomy.""" + raw_metadata = mesh.get("metadata", {}) + if raw_metadata is None: + raw_metadata = {} + if not isinstance(raw_metadata, Mapping): + raise ValueError("mesh.metadata must be a mapping") + metadata = raw_metadata + raw_tail = metadata.get("tail") + if raw_tail is None: + return {"present": False, "new_vertex_indices": [], "all_indices": set()} + tail = _mapping(raw_tail, "mesh.metadata.tail") + if tail.get("enabled") is not True or tail.get("owner") != "domain.tail": + raise ValueError("mesh.metadata.tail must be an enabled domain.tail allocation") + root = _mapping(metadata.get("root"), "mesh.metadata.root") + root_count = root.get("vertex_count") + root_face_count = root.get("face_count") + if root_count != _OLD_ROOT_VERTEX_COUNT or not isinstance(root_face_count, int) or root_face_count <= 0: + raise ValueError("tail metadata must preserve the 152-vertex source root and a positive face count") + base_count = metadata.get("base_vertex_count") + if isinstance(base_count, bool) or not isinstance(base_count, int) or base_count > vertex_count: + raise ValueError("tail metadata base_vertex_count must cover the declared L0") + identity = _mapping(tail.get("source_host_identity"), + "mesh.metadata.tail.source_host_identity") + host_face = identity.get("face_index") + host_vertices = _sequence(identity.get("vertex_indices"), + "mesh.metadata.tail.source_host_identity.vertex_indices") + if (identity.get("owner") != "domain.pelvis" or + isinstance(host_face, bool) or not isinstance(host_face, int) or + host_face < 0 or host_face >= root_face_count or len(host_vertices) != 4): + raise ValueError("tail source host identity must pin one pelvis quadrilateral") + host_vertices = [int(index) for index in host_vertices] + if len(set(host_vertices)) != 4 or any(index < 0 or index >= root_count for index in host_vertices): + raise ValueError("tail source host identity vertices must be four unique root vertices") + + replacement = _mapping(tail.get("face_replacement"), + "mesh.metadata.tail.face_replacement") + if (replacement.get("original_face_index") != host_face or + list(replacement.get("original_quad", ())) != host_vertices or + replacement.get("original_host_retained") is not False): + raise ValueError("tail face replacement must explicitly replace the pinned host face") + replacement_faces = _sequence(replacement.get("replacement_face_indices"), + "tail.face_replacement.replacement_face_indices") + replacement_faces = [int(index) for index in replacement_faces] + if (not replacement_faces or len(set(replacement_faces)) != len(replacement_faces) or + host_face not in replacement_faces or + replacement.get("one_to_many") != [[host_face, *replacement_faces]]): + raise ValueError("tail face replacement one-to-many mapping is incomplete") + quads = _sequence(mesh.get("quads"), "mesh.quads") + if any(index < 0 or index >= len(quads) for index in replacement_faces): + raise ValueError("tail replacement face index is outside mesh.quads") + index_mapping = _mapping(metadata.get("index_mapping"), "mesh.metadata.index_mapping") + kept = index_mapping.get("root_face_mappings_excluding_tail_host") + expected_kept = [[index, index] for index in range(root_face_count) if index != host_face] + if kept != expected_kept: + raise ValueError("tail kept-face correspondence must exclude only the pinned host face") + + new_indices = _sequence(tail.get("new_vertex_indices"), + "mesh.metadata.tail.new_vertex_indices") + if (not new_indices or any(isinstance(index, bool) or not isinstance(index, int) + for index in new_indices)): + raise ValueError("tail.new_vertex_indices must be non-empty integer IDs") + new_indices = [int(index) for index in new_indices] + if (len(set(new_indices)) != len(new_indices) or + any(index < root_count or index >= base_count for index in new_indices)): + raise ValueError("tail.new_vertex_indices must be a unique appended L0 allocation") + rings_raw = _sequence(tail.get("ring_indices"), "mesh.metadata.tail.ring_indices") + rings: list[list[int]] = [] + for ring_index, raw_ring in enumerate(rings_raw): + ring = _sequence(raw_ring, f"tail.ring_indices[{ring_index}]") + if len(ring) != 4 or any(index not in new_indices for index in ring): + raise ValueError("tail rings must preserve four-corner source phase order") + rings.append([int(index) for index in ring]) + if [index for ring in rings for index in ring] != new_indices: + raise ValueError("tail ring allocations must cover new_vertex_indices exactly once") + corner_by_vertex = { + vertex_index: corner + for ring in rings + for corner, vertex_index in enumerate(ring) + } + source_phase = _sequence(tail.get("source_phase"), "mesh.metadata.tail.source_phase") + if len(source_phase) != 4 or len({tuple(phase) for phase in source_phase}) != 4: + raise ValueError("tail source_phase must contain four distinct corners") + if any(len(phase) != 2 or any(type(value) is not int or value not in (-1, 1) + for value in phase) for phase in source_phase): + raise ValueError("tail source_phase entries must be signed pairs") + source_phase = [list(phase) for phase in source_phase] + host_record = _mapping(tail.get("host"), "mesh.metadata.tail.host") + if host_record.get("source_phase") != source_phase: + raise ValueError("tail host/source phase declarations must agree") + fractions = _sequence(tail.get("station_fractions"), + "mesh.metadata.tail.station_fractions") + fractions = [_number(value, f"tail.station_fractions[{index}]") + for index, value in enumerate(fractions)] + if (len(fractions) != len(rings) or not fractions or fractions != sorted(fractions) or + fractions[0] != 0.0 or fractions[-1] != 1.0 or + any(value < 0.0 or value > 1.0 for value in fractions)): + raise ValueError("tail station fractions must be ordered from collar 0 to tip 1") + + transition = _mapping(tail.get("transition_weights"), + "mesh.metadata.tail.transition_weights") + collar_blend = _number(transition.get("collar_blend_strength"), + "tail.transition_weights.collar_blend_strength") + if not 0.0 <= collar_blend <= 1.0: + raise ValueError("tail collar_blend_strength must lie in [0, 1]") + supports = _mapping(transition.get("supports"), + "tail.transition_weights.supports") + if set(supports) != {str(index) for index in new_indices}: + raise ValueError("tail supports must cover every new vertex exactly once") + checked_supports: dict[int, dict[str, Any]] = {} + for index in new_indices: + row = _mapping(supports[str(index)], f"tail.transition_weights.supports.{index}") + corner = corner_by_vertex[index] + if (row.get("target_joint") != "pelvis" or + list(row.get("host_vertex_indices", ())) != host_vertices or + row.get("host_corner") != corner or + row.get("source_phase") != source_phase[corner]): + raise ValueError(f"tail support {index} has an invalid host corner/phase contract") + weights = [_number(value, f"tail support {index}.convex_weights[{slot}]") + for slot, value in enumerate(_sequence(row.get("convex_weights"), + f"tail support {index}.convex_weights"))] + expected = [_TAIL_SUPPORT_OWN if slot == corner else _TAIL_SUPPORT_OTHER + for slot in range(4)] + if len(weights) != 4 or any(abs(actual - wanted) > 1e-12 + for actual, wanted in zip(weights, expected)): + raise ValueError(f"tail support {index} must match the declared .55/.15 corner rule") + checked_supports[index] = {"host_vertex_indices": host_vertices[:], + "host_corner": corner, + "source_phase": source_phase[corner], + "convex_weights": weights} + return { + "present": True, "owner": tail["owner"], "host_face": int(host_face), + "host_vertices": host_vertices, "replacement_faces": replacement_faces, + "kept_faces": expected_kept, "new_vertex_indices": new_indices, + "rings": rings, "station_fractions": fractions, + "source_phase": source_phase, "collar_blend_strength": collar_blend, + "supports": checked_supports, "root_count": root_count, + "root_face_count": root_face_count, "base_count": base_count, + "all_indices": set(new_indices), + } + + +def _foot_metadata_contract(mesh: Mapping[str, Any], vertex_count: int, + excluded_indices: set[int] | None = None) -> dict[str, Any]: + """Validate the explicit L0 allocation used by a closed terminal foot. + + The indices are source metadata, not a mesh-size convention. A returned + allocation is subsequently used by the binding check to verify the + shank-only five-column weights and their complete L2 transfer. + """ + metadata = _mapping(mesh.get("metadata"), "mesh.metadata") + tail_contract = _tail_metadata_contract(mesh, vertex_count) + tail_indices = set(tail_contract.get("all_indices", ())) + if "feet" not in metadata: + if not tail_contract["present"]: + # Preserve the historical no-feet path: the leg constructor owns + # its station allocation contract in _constructor_station_rings. + return {"present": False, "indices": {side: [] for side in _SIDES}, + "excluded_indices": set(excluded_indices or ())} + chains = _mapping(metadata.get("chains"), "mesh.metadata.chains") + leg_indices: set[int] = set() + for side in _SIDES: + chain = _mapping(chains.get(side), f"mesh.metadata.chains.{side}") + raw_chain = chain.get("new_vertex_indices", ()) + leg_indices.update(int(index) for index in _sequence(raw_chain, f"chains.{side}.new_vertex_indices")) + for raw_section in _sequence(chain.get("sections", ()), f"chains.{side}.sections"): + leg_indices.update(int(index) for index in _sequence( + _mapping(raw_section, "chain section").get("indices"), "chain section.indices")) + root_count = int(_mapping(metadata.get("root"), "mesh.metadata.root")["vertex_count"]) + base_count = int(metadata.get("base_vertex_count", vertex_count)) + appended = set(range(root_count, base_count)) + excluded = set(excluded_indices or ()) | tail_indices + if leg_indices | excluded != appended or leg_indices & excluded: + raise ValueError("mesh leg and tail metadata must cover every appended L0 vertex exactly once") + return {"present": False, "indices": {side: [] for side in _SIDES}, + "excluded_indices": excluded, "tail": tail_contract, + "base_count": base_count, "root_count": root_count} + + owner_count = metadata.get("base_vertex_count") + if isinstance(owner_count, bool) or not isinstance(owner_count, int) or owner_count <= 0: + raise ValueError("mesh.metadata.base_vertex_count must be a positive integer") + owners = metadata.get("base_control_owners") + if not isinstance(owners, (list, tuple)) or len(owners) != owner_count: + raise ValueError("mesh.metadata.base_control_owners must cover the declared L0") + level = mesh.get("level", metadata.get("level", 0)) + if level == 0: + l0_count = vertex_count + else: + l0_count = owner_count + raw_stencils = mesh.get("base_stencils") + if isinstance(raw_stencils, (list, tuple)): + for raw_row in raw_stencils: + if not isinstance(raw_row, (list, tuple)): + continue + for raw_term in raw_row: + if (isinstance(raw_term, (list, tuple)) and len(raw_term) == 2 + and isinstance(raw_term[0], int) and not isinstance(raw_term[0], bool)): + l0_count = max(l0_count, int(raw_term[0]) + 1) + if l0_count > vertex_count: + raise ValueError("declared L0 exceeds the mesh vertex count") + root = _mapping(metadata.get("root"), "mesh.metadata.root") + root_count = root.get("vertex_count") + if isinstance(root_count, bool) or not isinstance(root_count, int) or not 0 < root_count < l0_count: + raise ValueError("mesh.metadata.root.vertex_count must lie inside the declared L0") + + chains = _mapping(metadata.get("chains"), "mesh.metadata.chains") + if set(chains) != set(_SIDES): + raise ValueError("mesh.metadata.chains must contain exactly left and right") + leg_indices: set[int] = set() + for side in _SIDES: + chain = _mapping(chains[side], f"mesh.metadata.chains.{side}") + raw = chain.get("new_vertex_indices") + values = _sequence(raw, f"mesh.metadata.chains.{side}.new_vertex_indices") + if not values or any(isinstance(index, bool) or not isinstance(index, int) for index in values): + raise ValueError(f"mesh.metadata.chains.{side}.new_vertex_indices must contain integers") + checked = {int(index) for index in values} + if len(checked) != len(values) or any(index < root_count or index >= l0_count for index in checked): + raise ValueError(f"mesh.metadata.chains.{side}.new_vertex_indices is not a unique appended allocation") + if leg_indices & checked: + raise ValueError("mesh.metadata.chains allocations overlap") + leg_indices.update(checked) + + feet = _mapping(metadata.get("feet"), "mesh.metadata.feet") + if set(feet) != set(_SIDES): + raise ValueError("mesh.metadata.feet must contain exactly left and right") + foot_indices: dict[str, list[int]] = {} + assigned: set[int] = set() + for side in _SIDES: + row = _mapping(feet[side], f"mesh.metadata.feet.{side}") + values = _sequence(row.get("new_vertex_indices"), + f"mesh.metadata.feet.{side}.new_vertex_indices") + if not values or any(isinstance(index, bool) or not isinstance(index, int) for index in values): + raise ValueError(f"mesh.metadata.feet.{side}.new_vertex_indices must contain integers") + checked = [int(index) for index in values] + checked_set = set(checked) + if len(checked_set) != len(checked): + raise ValueError(f"mesh.metadata.feet.{side}.new_vertex_indices must be unique") + if any(index < root_count or index >= l0_count for index in checked_set): + raise ValueError(f"mesh.metadata.feet.{side}.new_vertex_indices is outside the declared L0") + if checked_set & leg_indices: + raise ValueError(f"mesh.metadata.feet.{side}.new_vertex_indices overlaps a leg allocation") + if checked_set & assigned: + raise ValueError("mesh.metadata.feet left and right allocations overlap") + foot_indices[side] = checked + assigned.update(checked_set) + + appended = set(range(root_count, l0_count)) + excluded = set(excluded_indices or ()) | tail_indices + if leg_indices | assigned | excluded != appended: + raise ValueError("mesh leg and foot metadata must cover every appended L0 vertex exactly once") + if ((leg_indices & excluded) or (assigned & excluded) or + (tail_indices & leg_indices) or (tail_indices & assigned)): + raise ValueError("mesh leg, foot, arm, and tail allocations must be disjoint") + return {"present": True, "indices": foot_indices, + "base_count": l0_count, "root_count": root_count, + "excluded_indices": excluded | assigned, "tail": tail_contract} + + +def _arm_graph_fields(base_mesh: Mapping[str, Any], + base_quads: Sequence[Sequence[int]], + arms: Mapping[str, Any], *, + root_quads: Sequence[Sequence[int]] | None = None) -> tuple[dict[str, dict[int, float]], + dict[str, dict[int, float]], + dict[str, Any]]: + """Independently solve the declared D0/D1-to-collar arm field and elbow blend.""" + metadata = _mapping(base_mesh.get("metadata"), "base.metadata") + root = _mapping(metadata.get("root"), "base.metadata.root") + root_count = root.get("vertex_count") + root_face_count = root.get("face_count") + if (isinstance(root_count, bool) or not isinstance(root_count, int) + or isinstance(root_face_count, bool) or not isinstance(root_face_count, int)): + raise ValueError("arm harmonic field requires integer root vertex/face counts") + if root_count != _OLD_ROOT_VERTEX_COUNT: + raise ValueError("arm harmonic field must preserve the original 152-vertex root") + root_quads = base_quads if root_quads is None else root_quads + if root_face_count <= 0 or root_face_count > len(root_quads): + raise ValueError("arm harmonic field root range is invalid") + root_graph = [set() for _ in range(root_count)] + graph = [set() for _ in range(max(root_count, 1 + max(max(face) for face in base_quads)))] + for face_index, face in enumerate(base_quads): + for slot, left in enumerate(face): + right = face[(slot + 1) % 4] + graph[left].add(right) + graph[right].add(left) + for face in root_quads[:root_face_count]: + for slot, left in enumerate(face): + right = face[(slot + 1) % 4] + if left >= root_count or right >= root_count: + raise ValueError("root face references a non-root vertex") + root_graph[left].add(right) + root_graph[right].add(left) + + def solve(matrix: list[list[float]], rhs: list[float], label: str) -> list[float]: + size = len(rhs) + augmented = [row[:] + [rhs[index]] for index, row in enumerate(matrix)] + for column in range(size): + pivot = max(range(column, size), key=lambda row: abs(augmented[row][column])) + if abs(augmented[pivot][column]) <= 1.0e-14: + raise ValueError(f"{label} harmonic system is singular") + augmented[column], augmented[pivot] = augmented[pivot], augmented[column] + divisor = augmented[column][column] + augmented[column] = [value / divisor for value in augmented[column]] + for row in range(size): + if row == column: + continue + factor = augmented[row][column] + if factor: + augmented[row] = [left - factor * right + for left, right in zip(augmented[row], augmented[column])] + values = [augmented[index][-1] for index in range(size)] + if any(not math.isfinite(value) for value in values): + raise ValueError(f"{label} harmonic system produced non-finite values") + return values + + fields: dict[str, dict[int, float]] = {} + blends: dict[str, dict[int, float]] = {} + regions: dict[str, tuple[set[int], set[int], set[int]]] = {} + diagnostics: dict[str, Any] = {"per_side": {}} + for side in _SIDES: + row = _mapping(arms[side], f"base.metadata.arms.{side}") + source = _mapping(row.get("source_port"), f"base.metadata.arms.{side}.source_port") + d0 = set(_sequence(source.get("indices"), + f"base.metadata.arms.{side}.source_port.indices")) + collar = set(_sequence(_mapping(row.get("collar"), + f"base.metadata.arms.{side}.collar").get("indices"), + f"base.metadata.arms.{side}.collar.indices")) + d1 = {neighbour for index in d0 for neighbour in root_graph[index]} - d0 + d2 = {neighbour for index in d1 for neighbour in root_graph[index]} - d0 - d1 + if not d0 or not d1 or not d2 or not collar: + raise ValueError(f"base.metadata.arms.{side} requires non-empty D0, D1, D2, and collar") + if (len(d0), len(d1), len(d2)) != (8, 8, 10): + raise ValueError( + f"base.metadata.arms.{side} requires D0/D1/D2 counts 8/8/10, " + f"got {len(d0)}/{len(d1)}/{len(d2)}" + ) + if set.intersection(*(set(values) for values in (d0, d1, d2))): + raise ValueError(f"base.metadata.arms.{side} D0/D1/D2 regions overlap") + regions[side] = (d0, d1, d2) + free = sorted(d0 | d1) + positions = {index: position for position, index in enumerate(free)} + matrix = [[1.0 if row_index == column_index else 0.0 + for column_index, _column in enumerate(free)] + for row_index in range(len(free))] + rhs = [0.0 for _ in free] + for index in free: + neighbours = graph[index] + if not neighbours: + raise ValueError(f"base.metadata.arms.{side} has an isolated D0/D1 vertex") + row_index = positions[index] + for neighbour in neighbours: + if neighbour in positions: + matrix[row_index][positions[neighbour]] -= 1.0 / len(neighbours) + elif neighbour in collar: + rhs[row_index] += 1.0 / len(neighbours) + elif neighbour in d2: + pass + else: + raise ValueError(f"base.metadata.arms.{side} D0/D1 has an undeclared neighbour") + values = solve(matrix, rhs, f"{side} shoulder") + fields[side] = {index: value for index, value in zip(free, values)} + + sections = _mapping(row, f"base.metadata.arms.{side}").get("sections") + section_rows = {str(_mapping(item, "arm section").get("name")): _mapping(item, "arm section") + for item in _sequence(sections, f"base.metadata.arms.{side}.sections")} + zero = set(collar) | set(_sequence(section_rows["upper_belly"].get("indices"), "arm upper_belly")) | set(_sequence(section_rows["pre_elbow"].get("indices"), "arm pre_elbow")) + free_elbow = set(_sequence(section_rows["elbow"].get("indices"), "arm elbow")) + one = set() + for name in ("post_elbow", "forearm_belly", "pre_wrist", "wrist", "palm", "knuckle", "terminal"): + one.update(_sequence(section_rows[name].get("indices"), f"arm {name}")) + one.add(int(_mapping(row.get("cap"), f"base.metadata.arms.{side}.cap").get("vertex"))) + if not zero or not free_elbow or not one or zero & free_elbow or zero & one or free_elbow & one: + raise ValueError(f"base.metadata.arms.{side} elbow blend regions overlap or are empty") + elbow_nodes = sorted(free_elbow) + elbow_positions = {index: position for position, index in enumerate(elbow_nodes)} + elbow_matrix = [[1.0 if row_index == column_index else 0.0 + for column_index, _column in enumerate(elbow_nodes)] + for row_index in range(len(elbow_nodes))] + elbow_rhs = [0.0 for _ in elbow_nodes] + for index in elbow_nodes: + neighbours = graph[index] + if not neighbours or not (neighbours & (zero | one)): + raise ValueError(f"base.metadata.arms.{side} elbow blend is not anchored") + row_index = elbow_positions[index] + for neighbour in neighbours: + if neighbour in elbow_positions: + elbow_matrix[row_index][elbow_positions[neighbour]] -= 1.0 / len(neighbours) + elif neighbour in one: + elbow_rhs[row_index] += 1.0 / len(neighbours) + elif neighbour not in zero: + raise ValueError(f"base.metadata.arms.{side} elbow has an undeclared neighbour") + elbow_values = solve(elbow_matrix, elbow_rhs, f"{side} elbow") + blends[side] = {index: 0.0 for index in zero} + blends[side].update({index: value for index, value in zip(elbow_nodes, elbow_values)}) + blends[side].update({index: 1.0 for index in one}) + diagnostics["per_side"][side] = { + "D0": sorted(d0), "D1": sorted(d1), "D2": sorted(d2), + "collar": sorted(collar), "elbow": sorted(free_elbow), + "shoulder_values": {str(index): fields[side][index] for index in free}, + } + if set(fields["left"]) & set(fields["right"]): + raise ValueError("bilateral arm D0/D1 regions overlap") + left_free = set(fields["left"]) + right_free = set(fields["right"]) + if (left_free & regions["right"][2]) or (right_free & regions["left"][2]): + raise ValueError("arm free region overlaps the opposite arm D2 boundary") + return fields, blends, diagnostics + + +def _head_graph_field(base_mesh: Mapping[str, Any], + base_quads: Sequence[Sequence[int]], + head: Mapping[str, Any], *, + root_quads: Sequence[Sequence[int]] | None = None) -> tuple[dict[int, float], dict[str, Any]]: + """Solve the declared neck D0/D1 field with support=1 and D2=0.""" + metadata = _mapping(base_mesh.get("metadata"), "base.metadata") + root = _mapping(metadata.get("root"), "base.metadata.root") + root_count, root_faces = root.get("vertex_count"), root.get("face_count") + if root_count != _OLD_ROOT_VERTEX_COUNT or not isinstance(root_faces, int): + raise ValueError("head harmonic field requires the original root face/vertex declaration") + root_quads = base_quads if root_quads is None else root_quads + if root_faces <= 0 or root_faces > len(root_quads): + raise ValueError("head harmonic field root range is invalid") + graph = [set() for _ in range(root_count)] + for face in root_quads[:root_faces]: + if any(index >= root_count for index in face): + raise ValueError("head harmonic field root faces must reference only root vertices") + for left, right in zip(face, face[1:] + face[:1]): + graph[left].add(right) + graph[right].add(left) + d0 = set(head["source_port"]) + support = set(head["support"]) + connections = [] + all_edges = { + tuple(sorted((left, right))) + for face in base_quads + for left, right in zip(face, face[1:] + face[:1]) + } + for port_index, support_index in zip(head["source_port"], head["support"]): + edge = tuple(sorted((port_index, support_index))) + if edge not in all_edges: + raise ValueError("head port-to-support weld is missing from the base mesh") + connections.append((port_index, support_index)) + d1 = {neighbour for index in d0 for neighbour in graph[index]} - d0 + d2 = {neighbour for index in d1 for neighbour in graph[index]} - d0 - d1 + if not d0 or not d1 or not d2 or not support: + raise ValueError("head harmonic field requires non-empty D0, D1, D2, and support") + free = sorted(d0 | d1) + positions = {index: position for position, index in enumerate(free)} + matrix = [[1.0 if row_index == column_index else 0.0 + for column_index, _column in enumerate(free)] + for row_index in range(len(free))] + rhs = [0.0 for _ in free] + for index in free: + neighbours = set(graph[index]) + for port_index, support_index in connections: + if index == port_index: + neighbours.add(support_index) + if not neighbours: + raise ValueError("head harmonic field has an isolated boundary vertex") + row = positions[index] + for neighbour in neighbours: + if neighbour in positions: + matrix[row][positions[neighbour]] -= 1.0 / len(neighbours) + elif neighbour in support: + rhs[row] += 1.0 / len(neighbours) + elif neighbour in d2: + pass + else: + raise ValueError("head D0/D1 has an undeclared root neighbour") + augmented = [row[:] + [rhs[index]] for index, row in enumerate(matrix)] + size = len(free) + for column in range(size): + pivot = max(range(column, size), key=lambda row: abs(augmented[row][column])) + if abs(augmented[pivot][column]) <= 1.0e-14: + raise ValueError("head harmonic system is singular") + augmented[column], augmented[pivot] = augmented[pivot], augmented[column] + divisor = augmented[column][column] + augmented[column] = [value / divisor for value in augmented[column]] + for row in range(size): + if row != column: + factor = augmented[row][column] + if factor: + augmented[row] = [left - factor * right + for left, right in zip(augmented[row], augmented[column])] + values = {index: augmented[position][-1] for position, index in enumerate(free)} + return values, {"D0": sorted(d0), "D1": sorted(d1), "D2": sorted(d2), + "support": sorted(support), "values": values} + + +def _tail_expected_base_rows(base_weights: Sequence[Sequence[float]], + tail_contract: Mapping[str, Any], + columns: Sequence[str]) -> dict[int, list[float]]: + """Derive tail L0 rows while retaining non-tail host rows for L2 transfer.""" + pelvis_column = list(columns).index("pelvis") if "pelvis" in columns else -1 + expected_rows: dict[int, list[float]] = {} + for ring, fraction in zip(tail_contract["rings"], tail_contract["station_fractions"]): + pelvis_fraction = (float(tail_contract["collar_blend_strength"]) + + (1.0 - float(tail_contract["collar_blend_strength"])) + * float(fraction)) + for vertex_index in ring: + support = tail_contract["supports"][vertex_index] + host_support = [0.0] * len(columns) + for host_index, coefficient in zip(support["host_vertex_indices"], + support["convex_weights"]): + for column in range(len(columns)): + host_support[column] += float(coefficient) * base_weights[host_index][column] + expected = [(1.0 - pelvis_fraction) * value for value in host_support] + if pelvis_column >= 0: + expected[pelvis_column] += pelvis_fraction + expected_rows[int(vertex_index)] = expected + return expected_rows + + +def _matrix_error(actual: Sequence[Sequence[float]], expected: Sequence[Sequence[float]]) -> float: + return max((abs(float(actual[row][column]) - float(expected[row][column])) + for row in range(4) for column in range(4)), default=math.inf) + + +def _stencil_rows(value: Any, vertex_count: int, base_count: int | None, label: str, + tolerance: float) -> list[list[tuple[int, float]]]: + rows = _sequence(value, label) + if len(rows) != vertex_count: + raise ValueError(f"{label} must cover every evaluated vertex") + result: list[list[tuple[int, float]]] = [] + for row_index, raw_row in enumerate(rows): + terms = _sequence(raw_row, f"{label}[{row_index}]") + if not terms: + raise ValueError(f"{label}[{row_index}] must not be empty") + checked: list[tuple[int, float]] = [] + previous = -1 + for term in terms: + pair = _sequence(term, f"{label}[{row_index}] term") + if len(pair) != 2 or isinstance(pair[0], bool) or not isinstance(pair[0], int): + raise ValueError(f"{label}[{row_index}] has an invalid index/coefficient pair") + index = int(pair[0]) + if index <= previous or index < 0 or (base_count is not None and index >= base_count): + raise ValueError(f"{label}[{row_index}] indices must be sorted and in range") + coefficient = _number(pair[1], f"{label}[{row_index}] coefficient") + if coefficient <= 0.0: + raise ValueError(f"{label}[{row_index}] coefficients must be positive") + checked.append((index, coefficient)) + previous = index + if abs(sum(coefficient for _, coefficient in checked) - 1.0) > tolerance: + raise ValueError(f"{label}[{row_index}] must partition unity within {tolerance}") + result.append(checked) + return result + + +def check_mesh(mesh: Mapping[str, Any], protocol: Mapping[str, Any]) -> dict[str, Any]: + """Check one staged mesh without imposing historical exact vertex counts.""" + report = _report("creature-kernel.connected-leg-assembly-mesh-checks.v1") + try: + parsed = _mesh(mesh, "mesh") + vertices, quads = parsed["vertices"], parsed["quads"] + incidence = _edge_incidence(quads) + edge_use = all(len(uses) in (1, 2) for uses in incidence.values()) + orientation = all(len(uses) != 2 or (uses[0][1], uses[0][2]) == (uses[1][2], uses[1][1]) + for uses in incidence.values()) + cycles: list[list[int]] = [] + boundary_valid = True + try: + cycles = _boundary_cycles(incidence) + except Exception as exc: + boundary_valid = False + _error(report, "boundary_cycle", str(exc)) + + loops = parsed["loops"] + declared_match = False + declared_roles: set[str | None] = set() + declared: dict[str, list[Any]] = {} + if isinstance(loops, Mapping): + declared = {str(name): _sequence(value, f"loops.{name}") for name, value in loops.items()} + declared_roles = {_loop_role(name) for name in declared} + declared_match = (len(cycles) == 5 and len(declared) == 5 + and all(any(_cyclic_equal(actual, expected) for expected in declared.values()) + for actual in cycles)) + declared_match = declared_match and declared_roles == _declared_loop_names(protocol) + else: + _error(report, "boundary_declaration", "mesh must declare named neck, arm, and ankle loops") + + metadata = parsed["metadata"] if isinstance(parsed["metadata"], Mapping) else {} + arm_present = "arms" in metadata + arm_contract: dict[str, Any] = { + "present": False, "indices": {side: [] for side in _SIDES}, + "all_indices": set(), + } + arm_metadata_valid = not arm_present + arm_indices: set[int] = set() + chain_indices: set[int] = set() + chains = metadata.get("chains") + if isinstance(chains, Mapping): + for side in _SIDES: + chain = chains.get(side) + if isinstance(chain, Mapping): + values = chain.get("new_vertex_indices", ()) + if isinstance(values, (list, tuple)): + chain_indices.update(index for index in values + if isinstance(index, int) and not isinstance(index, bool)) + if arm_present: + try: + occupied: set[int] = set() + if isinstance(chains, Mapping): + for side in _SIDES: + chain = chains.get(side) + if isinstance(chain, Mapping): + values = chain.get("new_vertex_indices", ()) + if isinstance(values, (list, tuple)): + occupied.update(index for index in values + if isinstance(index, int) and not isinstance(index, bool)) + arm_contract = _arm_metadata_contract(parsed["value"], len(vertices), occupied) + arm_indices = set(arm_contract["all_indices"]) + arm_metadata_valid = True + except Exception as exc: + _error(report, "arm_metadata", str(exc)) + + head_present = "head" in metadata + head_contract: dict[str, Any] = { + "present": False, "source_port": [], "support": [], + "new_vertex_indices": [], "all_indices": set(), + } + head_metadata_valid = not head_present + if head_present: + try: + head_contract = _head_metadata_contract( + parsed["value"], len(vertices), arm_indices | chain_indices + ) + head_metadata_valid = True + except Exception as exc: + _error(report, "head_metadata", str(exc)) + + tail_present = "tail" in metadata + tail_contract: dict[str, Any] = { + "present": False, "new_vertex_indices": [], "all_indices": set(), + } + tail_metadata_valid = not tail_present + if tail_present: + try: + tail_contract = _tail_metadata_contract(parsed["value"], len(vertices)) + tail_metadata_valid = True + except Exception as exc: + _error(report, "tail_metadata", str(exc)) + + allocation_exclusions = (arm_indices | + set(head_contract.get("all_indices", ())) | + set(tail_contract.get("all_indices", ()))) + foot_present = "feet" in metadata + foot_contract: dict[str, Any] = {"present": False, "indices": {side: [] for side in _SIDES}} + foot_metadata_valid = not foot_present + if foot_present: + try: + foot_contract = _foot_metadata_contract(parsed["value"], len(vertices), allocation_exclusions) + foot_metadata_valid = True + except Exception as exc: + _error(report, "foot_metadata", str(exc)) + + remaining_boundary_roles = {"neck", "arm.left", "arm.right", + "ankle.left", "ankle.right"} + if arm_present: + remaining_boundary_roles -= {"arm.left", "arm.right"} + if head_present: + remaining_boundary_roles.discard("neck") + if foot_present: + remaining_boundary_roles -= {"ankle.left", "ankle.right"} + declared_boundary_match = bool( + isinstance(loops, Mapping) + and len(cycles) == len(remaining_boundary_roles) + and len(declared) == len(remaining_boundary_roles) + and declared_roles == remaining_boundary_roles + and all(any(_cyclic_equal(actual, expected) for expected in declared.values()) + for actual in cycles) + ) + foot_declared_match = declared_boundary_match if foot_present else False + foot_boundary_contract = bool(foot_metadata_valid and boundary_valid and foot_declared_match) + + if not foot_present: + foot_declared_match = False + foot_boundary_contract = False + + if head_present: + head_boundary_contract = bool(head_metadata_valid and boundary_valid and declared_boundary_match) + else: + head_boundary_contract = False + + if arm_present and isinstance(loops, Mapping): + arm_declared_match = declared_boundary_match + else: + arm_declared_match = False + arm_boundary_contract = bool(arm_metadata_valid and boundary_valid and arm_declared_match) + + triangle_rows = _triangles(quads) + areas = [_triangle_area(vertices, triangle) for triangle in triangle_rows] + edge_lengths = [_distance(vertices[left], vertices[right]) for left, right in incidence] + quad_dots = [] + for face in quads: + first = _triangle_normal(vertices, (face[0], face[1], face[2])) + second = _triangle_normal(vertices, (face[0], face[2], face[3])) + first_norm, second_norm = _norm(first), _norm(second) + quad_dots.append(_dot(first, second) / (first_norm * second_norm) + if first_norm > 0.0 and second_norm > 0.0 else -1.0) + minimum_edge = _require_limit(report, protocol, ("minimum_edge_over_scale",)) + minimum_area = _require_limit(report, protocol, ("minimum_triangle_area_over_scale_squared",)) + if isinstance(minimum_edge, tuple) or isinstance(minimum_area, tuple): + raise ValueError("minimum edge and triangle area thresholds must be scalar") + stencil_tolerance = _require_limit(report, protocol, ( + "weight_sum_max_abs_error", "weight_partition_tolerance", + )) + if isinstance(stencil_tolerance, tuple): + raise ValueError("stencil partition tolerance must be scalar") + + stencils = parsed["stencils"] + base_count = None + for source in (metadata, protocol, protocol.get("checks")): + if isinstance(source, Mapping) and isinstance(source.get("base_vertex_count"), int): + base_count = source["base_vertex_count"] + break + if arm_present and arm_metadata_valid: + base_count = arm_contract["base_count"] + if head_present and head_metadata_valid: + base_count = head_contract["base_count"] + if foot_present: + base_count = (foot_contract["base_count"] if foot_metadata_valid + else len(vertices) if parsed["value"].get("level", metadata.get("level", 0)) == 0 + else base_count) + stencil_valid = False + if stencils is not None: + _stencil_rows(stencils, len(vertices), base_count, "mesh.base_stencils", + stencil_tolerance) + stencil_valid = True + else: + _error(report, "missing_base_stencils", "mesh.base_stencils is required") + + component_count = _connected_components(quads, len(vertices)) + report["metrics"].update({ + "vertex_count": len(vertices), "quad_count": len(quads), + "triangle_count": len(triangle_rows), "connected_components": component_count, + "boundary_count": len(cycles), "triangle_area_min": min(areas, default=None), + "edge_length_min": min(edge_lengths, default=None), + "quad_triangle_normal_dot_min": min(quad_dots, default=None), + }) + report["diagnostics"]["quad_triangle_dihedral"] = { + "gated": False, + "minimum_normal_dot": min(quad_dots, default=None), + } + report["uncertainties"].append( + "No quad-dihedral threshold is declared; the normal-dot value is diagnostic only." + ) + report["checks"].update({ + "finite_vertices_and_quads": True, + "one_connected_component": component_count == 1, + "no_nonmanifold_edges": edge_use, + "no_orientation_conflicts": orientation, + "edge_minimum": bool(edge_lengths) and min(edge_lengths) >= minimum_edge, + "triangle_minimum_area": bool(areas) and min(areas) >= minimum_area, + "base_stencils_positive_partition_unity": stencil_valid, + }) + if arm_present: + report["checks"].update({ + "arm_metadata_contract": arm_metadata_valid, + "arm_closed_boundary_contract": arm_boundary_contract, + "no_hand_boundary": arm_boundary_contract, + }) + if not arm_boundary_contract: + _error(report, "arm_boundary_contract", + "closed arm ports require only the declared neck and optional ankle boundaries") + if head_present: + report["checks"].update({ + "head_metadata_contract": head_metadata_valid, + "head_consumed_neck_boundary": head_boundary_contract, + "no_head_upper_boundary": head_boundary_contract, + }) + if not head_boundary_contract: + _error(report, "head_boundary_contract", + "neck_head must consume the named neck boundary and leave only unconsumed ports") + if foot_present: + report["checks"].update({ + "foot_metadata_contract": foot_metadata_valid, + "foot_closed_boundary_contract": foot_boundary_contract, + }) + if not foot_boundary_contract: + _error(report, "foot_boundary_contract", + "closed foot metadata requires exactly neck and two arm boundaries") + if tail_present: + report["checks"]["tail_metadata_contract"] = tail_metadata_valid + if not tail_metadata_valid: + _error(report, "tail_metadata_contract", + "tail metadata must declare the pinned host replacement and binding supports") + elif not foot_present and not tail_present and not arm_present and not head_present: + report["checks"].update({ + "exact_five_boundary_loops": boundary_valid and len(cycles) == 5, + "declared_neck_two_arms_two_ankles": declared_match, + }) + if component_count != 1: + _error(report, "disconnected_surface", "mesh must have one connected component") + if not edge_use: + _error(report, "nonmanifold_edges", "every edge must have one or two incident faces") + if not orientation: + _error(report, "orientation_conflict", "shared edges must have opposite directions") + if not edge_lengths or min(edge_lengths) < minimum_edge: + _error(report, "short_edge", "an edge is below the declared protocol minimum") + if not areas or min(areas) < minimum_area: + _error(report, "small_triangle_area", "a triangle is below the declared protocol minimum") + if not stencil_valid: + _error(report, "invalid_base_stencils", "base stencils must be positive and partition unity") + except Exception as exc: + if not report["errors"] or report["errors"][-1].get("detail") != str(exc): + _error(report, "input_or_check_failure", str(exc)) + return _finish(report) + + +def _identity_matrix() -> list[list[float]]: + return [[1.0 if row == column else 0.0 for column in range(4)] for row in range(4)] + + +def _mm(a: Sequence[Sequence[float]], b: Sequence[Sequence[float]]) -> list[list[float]]: + return [[sum(a[row][k] * b[k][column] for k in range(4)) for column in range(4)] for row in range(4)] + + +def _mp(matrix: Sequence[Sequence[float]], point: Sequence[float]) -> tuple[float, float, float]: + values = [float(point[0]), float(point[1]), float(point[2]), 1.0] + return tuple(sum(matrix[row][column] * values[column] for column in range(4)) for row in range(3)) # type: ignore[return-value] + + +def _inverse(matrix: Sequence[Sequence[float]]) -> list[list[float]]: + augmented = [list(map(float, matrix[row])) + [1.0 if row == column else 0.0 for column in range(4)] for row in range(4)] + for column in range(4): + pivot = max(range(column, 4), key=lambda row: abs(augmented[row][column])) + if abs(augmented[pivot][column]) == 0.0: + raise ValueError("matrix is singular") + augmented[column], augmented[pivot] = augmented[pivot], augmented[column] + divisor = augmented[column][column] + augmented[column] = [value / divisor for value in augmented[column]] + for row in range(4): + if row == column: + continue + factor = augmented[row][column] + augmented[row] = [left - factor * right for left, right in zip(augmented[row], augmented[column])] + return [row[4:] for row in augmented] + + +def _rotation_x(degrees: float, sign: float) -> list[list[float]]: + angle = math.radians(sign * degrees) + cosine, sine = math.cos(angle), math.sin(angle) + return [[1.0, 0.0, 0.0, 0.0], + [0.0, cosine, -sine, 0.0], + [0.0, sine, cosine, 0.0], + [0.0, 0.0, 0.0, 1.0]] + + +def _rotation_y(degrees: float) -> list[list[float]]: + angle = math.radians(degrees) + cosine, sine = math.cos(angle), math.sin(angle) + return [[cosine, 0.0, sine, 0.0], + [0.0, 1.0, 0.0, 0.0], + [-sine, 0.0, cosine, 0.0], + [0.0, 0.0, 0.0, 1.0]] + + +def _rotation_z(degrees: float) -> list[list[float]]: + angle = math.radians(degrees) + cosine, sine = math.cos(angle), math.sin(angle) + return [[cosine, -sine, 0.0, 0.0], + [sine, cosine, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0]] + + +def _normalise_vector(value: Sequence[float], label: str) -> tuple[float, float, float]: + length = _norm(value) + if not math.isfinite(length) or length <= 0.0: + raise ValueError(f"{label} must have positive finite length") + return _scale(value, 1.0 / length) + + +def _source_frame(origin: Sequence[float], distal: Sequence[float], label: str) -> list[list[float]]: + y_axis = _normalise_vector(_sub(origin, distal), f"{label} Y axis") + world_x = (1.0, 0.0, 0.0) + x_axis = _normalise_vector( + _sub(world_x, _scale(y_axis, _dot(world_x, y_axis))), + f"{label} projected +X", + ) + z_axis = _normalise_vector(_cross(x_axis, y_axis), f"{label} Z axis") + result = _identity_matrix() + for row in range(3): + result[row][0] = x_axis[row] + result[row][1] = y_axis[row] + result[row][2] = z_axis[row] + result[row][3] = float(origin[row]) + return result + + +def _arm_source_frame(origin: Sequence[float], distal: Sequence[float], + label: str) -> list[list[float]]: + """Build the settled arm frame from the source J->E or E->W bone.""" + y_axis = _normalise_vector(_sub(origin, distal), f"{label} Y axis") + world_y = (0.0, 1.0, 0.0) + x_axis = _normalise_vector( + _sub(world_y, _scale(y_axis, _dot(world_y, y_axis))), + f"{label} projected +Y", + ) + z_axis = _normalise_vector(_cross(x_axis, y_axis), f"{label} Z axis") + if _dot(z_axis, (0.0, 0.0, 1.0)) < 0.0: + x_axis = _scale(x_axis, -1.0) + z_axis = _scale(z_axis, -1.0) + result = _identity_matrix() + for row in range(3): + result[row][0] = x_axis[row] + result[row][1] = y_axis[row] + result[row][2] = z_axis[row] + result[row][3] = float(origin[row]) + return result + + +def _source_leg_points(leg_inputs: Mapping[str, Any]) -> dict[str, dict[str, tuple[float, float, float]]]: + raw = _mapping(leg_inputs, "leg_inputs") + if set(raw) != set(_SIDES): + raise ValueError("leg_inputs must contain exactly left and right") + return { + side: { + name: _vector(_mapping(raw[side], f"leg_inputs.{side}").get(name), + f"leg_inputs.{side}.{name}") + for name in ("J", "T", "K", "A") + } + for side in _SIDES + } + + +def _source_joint_rows(leg_inputs: Mapping[str, Any]) -> tuple[ + dict[str, dict[str, list[list[float]]]], + dict[str, dict[str, tuple[float, float, float]]], +]: + points = _source_leg_points(leg_inputs) + identity = _identity_matrix() + rows = {"pelvis": {"rest": identity, "inverse_bind": identity}} + for side in _SIDES: + thigh = _source_frame(points[side]["J"], points[side]["K"], f"{side} thigh") + knee = _source_frame(points[side]["K"], points[side]["A"], f"{side} knee") + rows[f"{side}_hip"] = {"rest": thigh, "inverse_bind": _inverse(thigh)} + rows[f"{side}_knee"] = {"rest": knee, "inverse_bind": _inverse(knee)} + return rows, points + + +def _matrix_max_error(left: Sequence[Sequence[float]], right: Sequence[Sequence[float]]) -> float: + return max(abs(float(left[row][column]) - float(right[row][column])) + for row in range(4) for column in range(4)) + + +def _binding_source_error(binding: Mapping[str, Any], leg_inputs: Mapping[str, Any]) -> tuple[float, bool]: + source_rows, source_points = _source_joint_rows(leg_inputs) + order, binding_rows, parents = _joint_rows(binding) + expected_parents = {"pelvis": None, "left_hip": "pelvis", "left_knee": "left_hip", + "right_hip": "pelvis", "right_knee": "right_hip"} + if tuple(order) in (_ARM_JOINTS, _ARM_HEAD_JOINTS): + expected_parents.update({"left_shoulder": "pelvis", "left_elbow": "left_shoulder", + "right_shoulder": "pelvis", "right_elbow": "right_shoulder"}) + if tuple(order) in (_HEAD_JOINTS, _ARM_HEAD_JOINTS): + expected_parents["neck"] = "pelvis" + structure_ok = tuple(order) in (_JOINTS, _HEAD_JOINTS, _ARM_JOINTS, _ARM_HEAD_JOINTS) and parents == expected_parents + errors = [] + for name in _JOINTS: + errors.append(_matrix_max_error(binding_rows[name]["rest"], source_rows[name]["rest"])) + errors.append(_matrix_max_error(binding_rows[name]["inverse_bind"], source_rows[name]["inverse_bind"])) + frames = _mapping(binding.get("rest_frames"), "binding.rest_frames") + expected_frame_keys = set(_SIDES) + if tuple(order) in (_HEAD_JOINTS, _ARM_HEAD_JOINTS): + expected_frame_keys.add("head") + if set(frames) != expected_frame_keys: + raise ValueError("binding.rest_frames must contain exactly the declared side and head frames") + for side in _SIDES: + frame = _mapping(frames[side], f"binding.rest_frames.{side}") + for point_name in ("J", "T", "K", "A"): + errors.append(_distance(_vector(frame.get(point_name), + f"binding.rest_frames.{side}.{point_name}"), + source_points[side][point_name])) + thigh = _mapping(frame.get("thigh"), f"binding.rest_frames.{side}.thigh") + knee = _mapping(frame.get("knee"), f"binding.rest_frames.{side}.knee") + errors.append(_matrix_max_error( + _matrix(thigh.get("rest_global", thigh.get("rest_matrix")), + f"binding.rest_frames.{side}.thigh.rest_global"), + source_rows[f"{side}_hip"]["rest"], + )) + errors.append(_matrix_max_error( + _matrix(knee.get("rest_global", knee.get("rest_matrix")), + f"binding.rest_frames.{side}.knee.rest_global"), + source_rows[f"{side}_knee"]["rest"], + )) + if tuple(order) in (_HEAD_JOINTS, _ARM_HEAD_JOINTS): + frames = _mapping(binding.get("rest_frames"), "binding.rest_frames") + head_frame = _mapping(frames.get("head"), "binding.rest_frames.head") + head_joint = binding_rows["neck"] + head_j = _vector(head_frame.get("J"), "binding.rest_frames.head.J") + expected = _identity_matrix() + for row in range(3): + expected[row][3] = head_j[row] + errors.extend((_matrix_max_error(head_joint["rest"], expected), + _matrix_max_error(head_joint["inverse_bind"], _inverse(expected)))) + return max(errors, default=math.inf), structure_ok + + +def _joint_angles(angles: Mapping[str, Any], side: str) -> tuple[float, float]: + row = angles.get(side) + if isinstance(row, Mapping): + hip = row.get("hip", row.get(f"{side}_hip", 0.0)) + knee = row.get("knee", row.get(f"{side}_knee", 0.0)) + elif row is not None: + hip, knee = row, 0.0 + else: + hip = angles.get(f"{side}_hip", 0.0) + knee = angles.get(f"{side}_knee", 0.0) + return _number(hip, f"angles.{side}.hip"), _number(knee, f"angles.{side}.knee") + + +def _joint_rows(binding: Mapping[str, Any]) -> tuple[list[str], dict[str, dict[str, Any]], dict[str, str | None]]: + raw_order = binding.get("joint_order", _JOINTS) + order = [str(item) for item in _sequence(raw_order, "binding.joint_order")] + if tuple(order) not in (_JOINTS, _HEAD_JOINTS, _ARM_JOINTS, _ARM_HEAD_JOINTS) or len(set(order)) != len(order): + raise ValueError("binding must expose the exact five-, six-, nine-, or ten-joint contract") + raw_joints = binding.get("joints") + if not isinstance(raw_joints, Mapping): + raise ValueError("binding.joints is required for independent hierarchical reconstruction") + rows: dict[str, dict[str, Any]] = {} + for name in order: + row = _mapping(raw_joints.get(name), f"binding.joints.{name}") + rows[name] = { + "rest": _matrix(row.get("rest_matrix"), f"binding.joints.{name}.rest_matrix"), + "inverse_bind": _matrix(row.get("inverse_bind_matrix", row.get("inverse_bind")), + f"binding.joints.{name}.inverse_bind_matrix"), + } + raw_parents = binding.get("parents", binding.get("hierarchy")) + parents: dict[str, str | None] = {"pelvis": None, "left_hip": "pelvis", "left_knee": "left_hip", + "right_hip": "pelvis", "right_knee": "right_hip"} + if tuple(order) in (_ARM_JOINTS, _ARM_HEAD_JOINTS): + parents.update({"left_shoulder": "pelvis", "left_elbow": "left_shoulder", + "right_shoulder": "pelvis", "right_elbow": "right_shoulder"}) + if tuple(order) in (_HEAD_JOINTS, _ARM_HEAD_JOINTS): + parents["neck"] = "pelvis" + if isinstance(raw_parents, Mapping): + for name in order: + if name in raw_parents: + parent = raw_parents[name] + parents[name] = None if parent is None else str(parent) + for name, parent in parents.items(): + if name in rows and parent is not None and parent not in rows: + raise ValueError(f"binding hierarchy parent {parent} is missing") + return order, rows, parents + + +def _expected_joint_poses(leg_inputs: Mapping[str, Any], angles: Mapping[str, Any], + binding: Mapping[str, Any] | None = None) -> tuple[list[str], dict[str, list[list[float]]], dict[str, list[list[float]]]]: + if binding is None: + rows, _points = _source_joint_rows(leg_inputs) + order = list(_JOINTS) + parents = {"pelvis": None, "left_hip": "pelvis", "left_knee": "left_hip", + "right_hip": "pelvis", "right_knee": "right_hip"} + else: + order, parsed_rows, parents = _joint_rows(binding) + rows = {name: {"rest": row["rest"], "inverse_bind": row["inverse_bind"]} + for name, row in parsed_rows.items()} + arm_angles = _arm_angles(angles) if tuple(order) in (_ARM_JOINTS, _ARM_HEAD_JOINTS) else None + head_angles = _head_angles(angles) if tuple(order) in (_HEAD_JOINTS, _ARM_HEAD_JOINTS) else None + local_rest: dict[str, list[list[float]]] = {} + for name in order: + parent = parents.get(name) + local_rest[name] = rows[name]["rest"] if parent is None else _mm(_inverse(rows[parent]["rest"]), rows[name]["rest"]) + posed: dict[str, list[list[float]]] = {} + for name in order: + parent = parents.get(name) + if name == "pelvis": + joint_angle = 0.0 + local_rotation = _identity_matrix() + elif name in {"left_hip", "left_knee", "right_hip", "right_knee"}: + side = "left" if name.startswith("left_") else "right" + hip_angle, knee_angle = _joint_angles(angles, side) + joint_angle = hip_angle if name.endswith("hip") else knee_angle + sign = -1.0 if name.endswith("hip") else 1.0 + local_rotation = _rotation_x(joint_angle, sign) + elif name == "neck": + if head_angles is None: + raise ValueError("neck joint rows require head angles") + local_rotation = _mm(_rotation_y(head_angles["yaw"]), + _rotation_x(head_angles["nod"], 1.0)) + else: + if arm_angles is None: + raise ValueError("arm joint rows require arm angles") + side = "left" if name.startswith("left_") else "right" + if name.endswith("shoulder"): + local_rotation = _mm( + _rotation_z((-1.0 if side == "left" else 1.0) * + arm_angles[side]["shoulder_raise"]), + _rotation_x(arm_angles[side]["shoulder_forward"], -1.0), + ) + elif name.endswith("elbow"): + local_rotation = _rotation_x(arm_angles[side]["elbow"], -1.0) + else: + raise ValueError(f"unsupported arm joint {name}") + local_pose = _mm(local_rest[name], local_rotation) + posed[name] = local_pose if parent is None else _mm(posed[parent], local_pose) + skins = {name: _mm(posed[name], rows[name]["inverse_bind"]) for name in order} + return order, posed, skins + + +def _weights(binding: Mapping[str, Any], count: int, order: Sequence[str]) -> list[list[float]]: + raw = binding.get("evaluated_weights", binding.get("weights")) + rows = _sequence(raw, "binding.evaluated_weights") + if len(rows) != count: + raise ValueError("binding.evaluated_weights must cover every rest vertex") + result: list[list[float]] = [] + for index, raw_row in enumerate(rows): + if isinstance(raw_row, Mapping): + if set(raw_row).difference(order): + raise ValueError(f"binding weight row {index} names an unknown joint") + row = [_number(raw_row.get(name, 0.0), f"weight[{index}].{name}") for name in order] + else: + values = _sequence(raw_row, f"binding.evaluated_weights[{index}]") + if len(values) != len(order): + raise ValueError(f"binding weight row {index} must contain five columns") + row = [_number(value, f"weight[{index}][{column}]") for column, value in enumerate(values)] + result.append(row) + return result + + +def _lbs(vertices: Sequence[Sequence[float]], weights: Sequence[Sequence[float]], skins: Mapping[str, Sequence[Sequence[float]]], order: Sequence[str]) -> list[tuple[float, float, float]]: + result = [] + for point, row in zip(vertices, weights): + contributions = [_scale(_mp(skins[name], point), row[index]) for index, name in enumerate(order)] + value = (0.0, 0.0, 0.0) + for contribution in contributions: + value = _add(value, contribution) + result.append(value) + return result + + +def _mesh_topology_equal(rest: Mapping[str, Any], posed: Mapping[str, Any]) -> bool: + return (rest.get("quads") == posed.get("quads") + and rest.get("loops", rest.get("boundary_loops")) == posed.get("loops", posed.get("boundary_loops"))) + + +def _arm_angles(angles: Mapping[str, Any]) -> dict[str, dict[str, float]]: + result: dict[str, dict[str, float]] = {} + for side in _SIDES: + row = _mapping(angles.get(side), f"angles.{side}") + allowed = {"hip", "knee", "ankle", "shoulder_raise", + "shoulder_forward", "elbow"} + if set(row).difference(allowed): + raise ValueError(f"angles.{side} contains an unsupported arm angle") + result[side] = { + name: _number(row.get(name, 0.0), f"angles.{side}.{name}") + for name in ("shoulder_raise", "shoulder_forward", "elbow") + } + return result + + +def _head_angles(angles: Mapping[str, Any]) -> dict[str, float]: + row = angles.get("head", {}) + row = _mapping(row, "angles.head") + if set(row).difference({"yaw", "nod"}): + raise ValueError("angles.head contains an unsupported neck/head angle") + return {name: _number(row.get(name, 0.0), f"angles.head.{name}") + for name in ("yaw", "nod")} + + +def _arm_endpoint_oracle(binding: Mapping[str, Any], + angles: Mapping[str, Any]) -> dict[str, Any]: + """Independently derive arm endpoints from source bones and settled angles.""" + parsed_angles = _arm_angles(angles) + frames = _mapping(binding.get("rest_frames"), "binding.rest_frames") + result: dict[str, Any] = {} + for side in _SIDES: + frame = _mapping(frames.get(side), f"binding.rest_frames.{side}") + source = _mapping(frame.get("arm_source_points"), + f"binding.rest_frames.{side}.arm_source_points") + points = {name: _vector(source.get(name), + f"binding.rest_frames.{side}.arm_source_points.{name}") + for name in ("J", "E", "W")} + shoulder_rest = _arm_source_frame(points["J"], points["E"], + f"{side} shoulder") + elbow_rest = _arm_source_frame(points["E"], points["W"], + f"{side} elbow") + shoulder_local = _mm( + _rotation_z((-1.0 if side == "left" else 1.0) * + parsed_angles[side]["shoulder_raise"]), + _rotation_x(parsed_angles[side]["shoulder_forward"], -1.0), + ) + elbow_local = _rotation_x(parsed_angles[side]["elbow"], -1.0) + shoulder_pose = _mm(shoulder_rest, shoulder_local) + elbow_pose = _mm( + _mm(_mm(shoulder_pose, _inverse(shoulder_rest)), elbow_rest), + elbow_local, + ) + shoulder_skin = _mm(shoulder_pose, _inverse(shoulder_rest)) + elbow_skin = _mm(elbow_pose, _inverse(elbow_rest)) + result[side] = { + "rest": points, + "posed": { + "J": _mp(shoulder_skin, points["J"]), + "E": _mp(shoulder_skin, points["E"]), + "W": _mp(elbow_skin, points["W"]), + }, + "shoulder_matrix": shoulder_pose, + "elbow_matrix": elbow_pose, + } + return result + + +def _head_source_frame_error(report: dict[str, Any], binding: Mapping[str, Any], + head_contract: Mapping[str, Any], tolerance: float) -> float: + """Compare the complete neck source frame and inverse bind to the handoff pivot.""" + frames = _mapping(binding.get("rest_frames"), "binding.rest_frames") + frame = _mapping(frames.get("head"), "binding.rest_frames.head") + joints = _mapping(binding.get("joints"), "binding.joints") + joint = _mapping(joints.get("neck"), "binding.joints.neck") + pivot = _vector(frame.get("J"), "binding.rest_frames.head.J") + expected = _identity_matrix() + for row in range(3): + expected[row][3] = pivot[row] + error = max( + _distance(pivot, head_contract["J"]), + _matrix_error(_matrix(frame.get("rest_global", frame.get("rest_matrix")), + "binding.rest_frames.head.rest_global"), expected), + _matrix_error(_matrix(joint.get("rest_matrix"), + "binding.joints.neck.rest_matrix"), expected), + _matrix_error(_matrix(joint.get("inverse_bind_matrix", joint.get("inverse_bind")), + "binding.joints.neck.inverse_bind_matrix"), _inverse(expected)), + ) + report["metrics"]["head_source_frame_max_error"] = error + declaration_ok = (frame.get("pivot_source") == "stations.neck_collar.C" + and frame.get("frame_source", _HEAD_FRAME_SOURCE) == _HEAD_FRAME_SOURCE) + report["checks"]["head_source_pivot_declaration"] = declaration_ok + report["checks"]["head_source_rest_inversebind_matrices"] = error <= tolerance + if not declaration_ok: + _error(report, "head_source_declaration", + "neck_head must declare stations.neck_collar.C as its pivot source") + if error > tolerance: + _error(report, "head_source_matrices", + "neck rest and inverse-bind matrices must be the complete source pivot frame") + return error + + +def _head_endpoint_oracle(binding: Mapping[str, Any], angles: Mapping[str, Any]) -> dict[str, Any]: + """Derive neck/head endpoint motion from the source pivot, independently of binder pose code.""" + frames = _mapping(binding.get("rest_frames"), "binding.rest_frames") + frame = _mapping(frames.get("head"), "binding.rest_frames.head") + pivot = _vector(frame.get("J"), "binding.rest_frames.head.J") + parsed = _head_angles(angles) + rest = _identity_matrix() + for row in range(3): + rest[row][3] = pivot[row] + posed = _mm(rest, _mm(_rotation_y(parsed["yaw"]), _rotation_x(parsed["nod"], 1.0))) + skin = _mm(posed, _inverse(rest)) + rest_forward = _add(pivot, (0.0, 0.0, 1.0)) + posed_pivot = _mp(skin, pivot) + posed_forward = _mp(skin, rest_forward) + return {"rest_global": rest, "posed_global": posed, "skin_matrix": skin, + "rest_J": pivot, "posed_J": posed_pivot, + "rest_forward_endpoint": rest_forward, + "posed_forward_endpoint": posed_forward, + "angle_degrees": parsed, + "pose_rotation_order": "Ry(yaw) @ Rx(nod)"} + + +def _check_head_endpoint_oracle(report: dict[str, Any], binding: Mapping[str, Any], + angles: Mapping[str, Any], posed_joints: Mapping[str, Any], + tolerance: float) -> None: + oracle = _head_endpoint_oracle(binding, angles) + actual = posed_joints.get("neck") + actual_error = (_matrix_error(actual, oracle["posed_global"]) + if actual is not None else math.inf) + direction = _sub(oracle["posed_forward_endpoint"], oracle["posed_J"]) + yaw_probe = dict(angles) + yaw_probe["head"] = {"yaw": 10.0, "nod": 0.0} + nod_probe = dict(angles) + nod_probe["head"] = {"yaw": 0.0, "nod": 10.0} + yaw = _head_endpoint_oracle(binding, yaw_probe) + nod = _head_endpoint_oracle(binding, nod_probe) + yaw_ok = yaw["posed_forward_endpoint"][0] > yaw["rest_forward_endpoint"][0] + nod_ok = nod["posed_forward_endpoint"][1] < nod["rest_forward_endpoint"][1] + report["checks"].update({ + "head_endpoint_source_oracle": actual_error <= tolerance, + "head_positive_yaw_face_plus_x": yaw_ok, + "head_positive_nod_face_down": nod_ok, + }) + report["metrics"].update({ + "head_endpoint_oracle_max_error": actual_error, + "head_rest_forward_direction": [0.0, 0.0, 1.0], + "head_pose_forward_direction": list(direction), + "head_yaw10_forward_endpoint": list(yaw["posed_forward_endpoint"]), + "head_nod10_forward_endpoint": list(nod["posed_forward_endpoint"]), + }) + if actual_error > tolerance: + _error(report, "head_endpoint_oracle", + "posed neck transform does not match the independent pivot endpoint oracle") + if not yaw_ok: + _error(report, "head_yaw_direction", "positive yaw 10 must move the face direction toward +X") + if not nod_ok: + _error(report, "head_nod_direction", "positive nod 10 must move the face direction downward") + + +def _check_arm_endpoint_oracle(report: dict[str, Any], binding: Mapping[str, Any], + angles: Mapping[str, Any], + posed_joints: Mapping[str, Sequence[Sequence[float]]], + tolerance: float) -> None: + """Check parent endpoints and semantic positive-angle directions.""" + oracle = _arm_endpoint_oracle(binding, angles) + endpoint_error = 0.0 + for side in _SIDES: + for joint_name, point_name in ((f"{side}_shoulder", "J"), + (f"{side}_elbow", "E")): + matrix = _matrix(posed_joints[joint_name], + f"posed joint {joint_name}") + expected = oracle[side]["posed"][point_name] + endpoint_error = max(endpoint_error, + max(abs(matrix[row][3] - expected[row]) + for row in range(3))) + + zero = {side: {"shoulder_raise": 0.0, "shoulder_forward": 0.0, + "elbow": 0.0} for side in _SIDES} + direction_checks: dict[str, bool] = {} + for side in _SIDES: + for angle_name, point_name, component, label in ( + ("shoulder_raise", "E", 1, "raise_E_y_increases"), + ("shoulder_forward", "E", 2, "forward_E_z_increases"), + ("elbow", "W", 2, "elbow_W_z_increases"), + ): + probe_angles = copy.deepcopy(zero) + probe_angles[side][angle_name] = 10.0 + probe = _arm_endpoint_oracle(binding, probe_angles)[side] + direction_checks[f"{side}_{label}"] = ( + probe["posed"][point_name][component] > + probe["rest"][point_name][component] + ) + report["metrics"]["arm_endpoint_oracle"] = { + side: {"rest": data["rest"], "posed": data["posed"]} + for side, data in oracle.items() + } + report["metrics"]["arm_endpoint_max_error"] = endpoint_error + report["checks"]["arm_endpoint_parent_oracle"] = endpoint_error <= tolerance + report["checks"].update(direction_checks) + if endpoint_error > tolerance: + _error(report, "arm_endpoint_oracle", + "arm shoulder/elbow parent endpoints do not match the independent source-bone oracle") + for name, passed in direction_checks.items(): + if not passed: + _error(report, name, + "positive arm angle has the wrong anatomical endpoint direction") + + +def check_pose(rest: Mapping[str, Any], posed: Mapping[str, Any], binding: Mapping[str, Any], + angles: Mapping[str, Any], protocol: Mapping[str, Any], + leg_inputs: Mapping[str, Any] | None = None) -> dict[str, Any]: + """Independently verify a posed surface for the supported 5/6/9/10 layouts.""" + report = _report("creature-kernel.connected-leg-assembly-pose-checks.v1") + try: + rest_parsed = _mesh(rest, "rest") + posed_parsed = _mesh(posed, "posed") + if len(rest_parsed["vertices"]) != len(posed_parsed["vertices"]): + raise ValueError("rest and posed vertex counts differ") + topology = _mesh_topology_equal(rest, posed) + report["checks"]["unchanged_topology"] = topology + if not topology: + _error(report, "topology_changed", "posed mesh must preserve vertex-indexed quads and declared loops") + + bound = _mapping(binding, "binding") + binding_order = tuple(bound.get("joint_order", ())) + arm_binding = binding_order in (_ARM_JOINTS, _ARM_HEAD_JOINTS) + head_binding = binding_order in (_HEAD_JOINTS, _ARM_HEAD_JOINTS) + if arm_binding: + _arm_angles(_mapping(angles, "angles")) + report["checks"]["arm_pose_angle_interface"] = True + if head_binding: + _head_angles(_mapping(angles, "angles")) + report["checks"]["head_pose_angle_interface"] = True + if leg_inputs is None: + raise ValueError("independent check_pose requires immutable leg_inputs") + source_inputs = _mapping(leg_inputs, "leg_inputs") + binding_inputs = _mapping(bound.get("leg_inputs"), "binding.leg_inputs") + input_copy_matches = binding_inputs == source_inputs + source_error, hierarchy_matches = _binding_source_error(bound, source_inputs) + source_limit = _require_limit(report, protocol, ( + "rest_transform_max_abs_error", "hierarchical_K_A_response_max_abs_error", + "independent_lbs_tolerance", + )) + if isinstance(source_limit, tuple): + raise ValueError("source-frame tolerance must be scalar") + report["checks"].update({ + "binding_leg_inputs_match_immutable_inputs": input_copy_matches, + "binding_rest_sources_match_J_K_A": hierarchy_matches and source_error <= source_limit, + }) + report["metrics"]["binding_rest_source_max_error"] = source_error + if not input_copy_matches: + _error(report, "binding_leg_inputs", "binding leg_inputs do not match the immutable case inputs") + if not hierarchy_matches or source_error > source_limit: + _error(report, "binding_rest_sources", "binding rest frames or inverse binds do not match source-derived J/K/A frames") + if arm_binding: + try: + rest_metadata = _mapping(rest.get("metadata", {}), "rest.metadata") + if "arms" in rest_metadata: + arm_contract = _arm_metadata_contract( + rest, len(rest_parsed["vertices"]) + ) + else: + frames = _mapping(bound.get("rest_frames"), "binding.rest_frames") + arm_contract = {"source_points": {}} + for side in _SIDES: + source = _mapping( + _mapping(frames[side], f"binding.rest_frames.{side}") + .get("arm_source_points"), + f"binding.rest_frames.{side}.arm_source_points", + ) + arm_contract["source_points"][side] = { + name: _vector(source.get(name), + f"binding.rest_frames.{side}.arm_source_points.{name}") + for name in ("J", "E", "W") + } + _check_arm_source_frames(report, bound, arm_contract, source_limit) + except Exception as exc: + _error(report, "arm_source_frames", str(exc)) + if head_binding: + try: + head_contract = _head_metadata_contract( + rest, len(rest_parsed["vertices"]) + ) + if not head_contract["present"]: + raise ValueError("head pose requires rest.metadata.head binding_handoff") + _head_source_frame_error(report, bound, head_contract, source_limit) + except Exception as exc: + _error(report, "head_source_frames", str(exc)) + order, posed_joints, skins = _expected_joint_poses( + source_inputs, _mapping(angles, "angles"), bound if (arm_binding or head_binding) else None + ) + if arm_binding: + _check_arm_endpoint_oracle( + report, bound, _mapping(angles, "angles"), posed_joints, source_limit + ) + if head_binding: + _check_head_endpoint_oracle( + report, bound, _mapping(angles, "angles"), posed_joints, source_limit + ) + weights = _weights(binding, len(rest_parsed["vertices"]), order) + partition_limit = _require_limit(report, protocol, ( + "weight_sum_max_abs_error", "weight_partition_tolerance", + )) + if isinstance(partition_limit, tuple): + raise ValueError("weight partition tolerance must be scalar") + finite_weights = all(math.isfinite(value) for row in weights for value in row) + nonnegative_weights = all(value >= -partition_limit for row in weights for value in row) + partition_error = max((abs(sum(row) - 1.0) for row in weights), default=math.inf) + report["checks"].update({ + "five_joint_transforms": tuple(order) in (_JOINTS, _HEAD_JOINTS, + _ARM_JOINTS, _ARM_HEAD_JOINTS), + "five_weight_columns": tuple(bound.get("weight_columns", ())) in ( + _WEIGHT_COLUMNS, _HEAD_WEIGHT_COLUMNS, _ARM_WEIGHT_COLUMNS, + _ARM_HEAD_WEIGHT_COLUMNS), + "six_joint_transforms": ((not head_binding) or + tuple(order) in (_HEAD_JOINTS, _ARM_HEAD_JOINTS)), + "six_weight_columns": ((not head_binding) or + tuple(bound.get("weight_columns", ())) in ( + _HEAD_WEIGHT_COLUMNS, _ARM_HEAD_WEIGHT_COLUMNS)), + "nine_joint_transforms": ((not arm_binding) or + tuple(order) in (_ARM_JOINTS, _ARM_HEAD_JOINTS)), + "nine_weight_columns": ((not arm_binding) or + tuple(bound.get("weight_columns", ())) in ( + _ARM_WEIGHT_COLUMNS, _ARM_HEAD_WEIGHT_COLUMNS)), + "ten_joint_transforms": ((not (arm_binding and head_binding)) or + tuple(order) == _ARM_HEAD_JOINTS), + "ten_weight_columns": ((not (arm_binding and head_binding)) or + tuple(bound.get("weight_columns", ())) == _ARM_HEAD_WEIGHT_COLUMNS), + "finite_weights": finite_weights, + "nonnegative_weights": nonnegative_weights, + "weight_partition_unity": finite_weights and partition_error <= partition_limit, + }) + if not finite_weights: + _error(report, "nonfinite_weights", "all five binding weights must be finite") + if not nonnegative_weights: + _error(report, "negative_weights", "binding weights must be nonnegative") + if partition_error > partition_limit: + _error(report, "weight_partition", "five binding weights must partition unity") + + expected_vertices = _lbs(rest_parsed["vertices"], weights, skins, order) + actual_vertices = posed_parsed["vertices"] + lbs_limit = _require_limit(report, protocol, ( + "source_effect_response_max_abs_error", "hierarchical_K_A_response_max_abs_error", + "independent_lbs_tolerance", "exported_lbs_tolerance", "pose_position_tolerance", + )) + if isinstance(lbs_limit, tuple): + raise ValueError("independent LBS tolerance must be scalar") + lbs_errors = [_distance(actual, expected) for actual, expected in zip(actual_vertices, expected_vertices)] + report["checks"]["independent_hierarchical_lbs"] = bool(lbs_errors) and max(lbs_errors) <= lbs_limit + report["metrics"].update({"weight_partition_error": partition_error, + "independent_lbs_max_error": max(lbs_errors, default=math.inf), + "independent_lbs_worst_vertices": sorted(range(len(lbs_errors)), key=lbs_errors.__getitem__, reverse=True)[:_EXAMPLE_CAP], + "joint_order": list(order), + "posed_joint_matrices": posed_joints}) + if not report["checks"]["independent_hierarchical_lbs"]: + _error(report, "independent_lbs", "posed vertices do not match independently reconstructed five-joint LBS") + + zero_pose = all(_joint_angles(angles, side) == (0.0, 0.0) + for side in ("left", "right")) + if arm_binding: + zero_pose = zero_pose and all( + value == 0.0 + for row in _arm_angles(_mapping(angles, "angles")).values() + for value in row.values() + ) + if head_binding: + zero_pose = zero_pose and all( + value == 0.0 for value in + _head_angles(_mapping(angles, "angles")).values() + ) + identity_limit = _require_limit(report, protocol, ( + "rest_identity_max_abs_error", "identity_position_tolerance", "identity_rest_tolerance", + )) + if isinstance(identity_limit, tuple): + raise ValueError("identity position tolerance must be scalar") + identity_errors = [_distance(actual, expected) for actual, expected in zip(actual_vertices, rest_parsed["vertices"])] + report["checks"]["identity_at_zero_angles"] = (not zero_pose) or (bool(identity_errors) and max(identity_errors) <= identity_limit) + report["metrics"]["identity_checked"] = zero_pose + report["metrics"]["identity_max_error"] = max(identity_errors, default=math.inf) + + lower_faces, upper_faces, face_start = _lower_faces(rest_parsed, protocol) + report["metrics"].update({"prior_face_count": face_start, "lower_face_count": len(lower_faces), "inherited_upper_face_count": len(upper_faces)}) + report["checks"]["lower_face_inventory"] = bool(lower_faces) + if not lower_faces: + _error(report, "empty_lower_inventory", "lower checks require inherited pelvis/hip/abdomen or appended faces") + + area_range = _require_limit(report, protocol, ( + "triangle_area_ratio_report_range", "lower_triangle_area_ratio", "triangle_area_ratio", + )) + edge_range = _require_limit(report, protocol, ( + "edge_ratio_report_range", "lower_edge_strain_ratio", "edge_strain_ratio", + )) + if not isinstance(area_range, tuple) or not isinstance(edge_range, tuple): + raise ValueError("pose diagnostic ranges have the wrong shape") + rest_triangles, posed_triangles = _triangles(rest_parsed["quads"]), _triangles(posed_parsed["quads"]) + lower_triangle_ids = [index for index in range(len(rest_triangles)) if index // 2 in lower_faces] + rest_areas = [_triangle_area(rest_parsed["vertices"], rest_triangles[index]) for index in lower_triangle_ids] + posed_areas = [_triangle_area(actual_vertices, posed_triangles[index]) for index in lower_triangle_ids] + area_ratios = [posed_area / rest_area if rest_area > 0.0 else math.inf for rest_area, posed_area in zip(rest_areas, posed_areas)] + edges = sorted({tuple(sorted((face[slot], face[(slot + 1) % 4]))) + for face_index, face in enumerate(rest_parsed["quads"]) if face_index in lower_faces + for slot in range(4)}) + edge_ratios = [_distance(actual_vertices[left], actual_vertices[right]) / _distance(rest_parsed["vertices"][left], rest_parsed["vertices"][right]) + if _distance(rest_parsed["vertices"][left], rest_parsed["vertices"][right]) > 0.0 else math.inf + for left, right in edges] + normal_dots = [] + for index in lower_triangle_ids: + rest_normal = _triangle_normal(rest_parsed["vertices"], rest_triangles[index]) + posed_normal = _triangle_normal(actual_vertices, posed_triangles[index]) + denominator = _norm(rest_normal) * _norm(posed_normal) + normal_dots.append(_dot(rest_normal, posed_normal) / denominator if denominator > 0.0 else -1.0) + report["diagnostics"].update({ + "lower_edge_strain": { + "range": list(edge_range), + "outside_range": (not edge_ratios or min(edge_ratios) < edge_range[0] + or max(edge_ratios) > edge_range[1]), + }, + "lower_triangle_area_ratio": { + "range": list(area_range), + "outside_range": (not area_ratios or min(area_ratios) < area_range[0] + or max(area_ratios) > area_range[1]), + }, + "lower_normal_dot": { + "gross_collapse": not normal_dots or min(normal_dots) <= 0.0, + "gated": False, + }, + }) + report["metrics"].update({ + "edge_strain_min": min(edge_ratios, default=math.inf), "edge_strain_max": max(edge_ratios, default=-math.inf), + "triangle_area_ratio_min": min(area_ratios, default=math.inf), "triangle_area_ratio_max": max(area_ratios, default=-math.inf), + "normal_dot_min": min(normal_dots, default=-1.0), "normal_dot_max": max(normal_dots, default=-1.0), + }) + report["uncertainties"].append( + "Strain, area-ratio, and corresponding-normal values are diagnostics; the protocol declares no anatomy acceptance gate." + ) + + owners = rest_parsed["face_owners"] + if not isinstance(owners, Sequence) or len(owners) != len(rest_parsed["quads"]): + raise ValueError("face_owners must cover every pose face") + # Terminal-foot surfaces use the accepted broadphase wrapper. The + # historical five-port leg surface keeps the original checker route. + arm_pose = ("arms" in _mapping(rest.get("metadata", {}), "rest.metadata") + or "arms" in _mapping(posed.get("metadata", {}), "posed.metadata")) + foot_pose = ("feet" in _mapping(rest.get("metadata", {}), "rest.metadata") + or "feet" in _mapping(posed.get("metadata", {}), "posed.metadata")) + head_pose = ("head" in _mapping(rest.get("metadata", {}), "rest.metadata") + or "head" in _mapping(posed.get("metadata", {}), "posed.metadata")) + collision = (_foot_collision_report(actual_vertices, posed_parsed["quads"], owners, + lower_faces, upper_faces) + if foot_pose or arm_pose or head_pose else + _collision_report(actual_vertices, posed_parsed["quads"], owners, + lower_faces, upper_faces)) + report["checks"]["lower_collision_inventory"] = bool(collision["available"] and collision["coverage_complete"] and not collision["lower_hit_pairs"]) + report["checks"]["collision_coverage_complete"] = bool(collision["available"] and collision["coverage_complete"]) + report["metrics"]["collision"] = collision + if not collision["available"]: + _unavailable(report, "collision_unavailable", "collision coverage or generic intersection evidence is unavailable") + elif collision["lower_hit_pairs"]: + _error(report, "lower_collision", "relevant lower faces contain non-adjacent intersections", pairs=collision["lower_hit_pairs"][:_EXAMPLE_CAP]) + except Exception as exc: + if not report["errors"] or report["errors"][-1].get("detail") != str(exc): + _error(report, "input_or_check_failure", str(exc)) + return _finish(report) + + +def _source_station_values(binding: Mapping[str, Any], leg_inputs: Mapping[str, Any]) -> Any: + sources = [binding, binding.get("metadata"), leg_inputs, leg_inputs.get("metadata") if isinstance(leg_inputs, Mapping) else None] + for source in sources: + if isinstance(source, Mapping): + for key in ("source_station_knee", "source_station_knee_values", "base_source_station_knee"): + if key in source: + return source[key] + stations = source.get("source_stations") + if isinstance(stations, Mapping) and "knee" in stations: + return stations["knee"] + return None + + +def _mapped_prior_weights(prior_binding: Mapping[str, Any], count: int) -> list[list[float]]: + raw = prior_binding.get("base_weights", prior_binding.get("weights")) + rows = _sequence(raw, "prior_hip_binding.base_weights") + if len(rows) != count: + raise ValueError("prior hip binding must cover the original 152 root vertices") + result = [] + for index, row in enumerate(rows): + values = _sequence(row, f"prior_hip_binding.base_weights[{index}]") + if len(values) != 3: + raise ValueError("prior hip binding must expose three weight columns") + result.append([_number(value, f"prior weight[{index}][{column}]") for column, value in enumerate(values)]) + return result + + +def _constructor_station_rings(base: Mapping[str, Any], base_count: int, + expected_indices: set[int] | None = None) -> dict[str, list[list[int]]]: + metadata = _mapping(base.get("metadata"), "base.metadata") + chains = _mapping(metadata.get("chains"), "base.metadata.chains") + if set(chains) != set(_SIDES): + raise ValueError("base.metadata.chains must contain exactly left and right") + result: dict[str, list[list[int]]] = {} + all_indices: list[int] = [] + for side in _SIDES: + chain = _mapping(chains[side], f"base.metadata.chains.{side}") + sections = _sequence(chain.get("sections"), f"base.metadata.chains.{side}.sections") + if len(sections) != len(_STATION_NAMES): + raise ValueError(f"base.metadata.chains.{side}.sections must contain seven stations") + side_rings = [] + for station_index, station_name in enumerate(_STATION_NAMES): + section = _mapping(sections[station_index], + f"base.metadata.chains.{side}.sections[{station_index}]") + if section.get("name") != station_name or section.get("order") != station_index: + raise ValueError(f"constructor station order mismatch for {side}.{station_name}") + ring = _sequence(section.get("indices"), f"constructor ring {side}.{station_name}") + if (len(ring) != 8 or any(isinstance(index, bool) or not isinstance(index, int) + for index in ring) or len(set(ring)) != 8): + raise ValueError(f"constructor ring {side}.{station_name} must contain eight unique indices") + checked = [int(index) for index in ring] + if any(index < _OLD_ROOT_VERTEX_COUNT or index >= base_count for index in checked): + raise ValueError(f"constructor ring {side}.{station_name} must reference appended vertices") + side_rings.append(checked) + all_indices.extend(checked) + result[side] = side_rings + expected = (set(range(_OLD_ROOT_VERTEX_COUNT, base_count)) + if expected_indices is None else expected_indices) + if len(set(all_indices)) != len(all_indices) or set(all_indices) != expected: + raise ValueError("constructor station rings must cover every appended vertex exactly once") + return result + + +def _check_arm_source_frames(report: dict[str, Any], binding: Mapping[str, Any], + arm_contract: Mapping[str, Any], + tolerance: float) -> float: + frames = _mapping(binding.get("rest_frames"), "binding.rest_frames") + joints = _mapping(binding.get("joints"), "binding.joints") + expected_parents = { + "pelvis": None, "left_hip": "pelvis", "left_knee": "left_hip", + "right_hip": "pelvis", "right_knee": "right_hip", + "left_shoulder": "pelvis", "left_elbow": "left_shoulder", + "right_shoulder": "pelvis", "right_elbow": "right_shoulder", + } + parents = binding.get("parents", binding.get("hierarchy")) + if not isinstance(parents, Mapping) or { + name: (None if parents.get(name) is None else str(parents.get(name))) + for name in _ARM_JOINTS + } != expected_parents: + _error(report, "arm_parent_hierarchy", + "9-column binding must declare the exact pelvis/shoulder/elbow parent hierarchy") + source_error = 0.0 + for side in _SIDES: + frame = _mapping(frames.get(side), f"binding.rest_frames.{side}") + source = _mapping(frame.get("arm_source_points"), + f"binding.rest_frames.{side}.arm_source_points") + expected = arm_contract["source_points"][side] + for name in ("J", "E", "W"): + actual = _vector(source.get(name), + f"binding.rest_frames.{side}.arm_source_points.{name}") + source_error = max(source_error, _distance(actual, expected[name])) + frame_source_ok = source.get("frame_source") == _ARM_FRAME_SOURCE + report["checks"][f"{side}_arm_source_frame_declaration"] = frame_source_ok + if not frame_source_ok: + _error(report, "arm_source_frame_declaration", + "arm pivot frames must declare source J->E and E->W bones, excluding construction P frames", + side=side) + shoulder = _mapping(frame.get("shoulder"), + f"binding.rest_frames.{side}.shoulder") + elbow = _mapping(frame.get("elbow"), + f"binding.rest_frames.{side}.elbow") + shoulder_matrix = _matrix(shoulder.get("rest_global", shoulder.get("rest_matrix")), + f"binding.rest_frames.{side}.shoulder.rest_global") + elbow_matrix = _matrix(elbow.get("rest_global", elbow.get("rest_matrix")), + f"binding.rest_frames.{side}.elbow.rest_global") + expected_shoulder = _arm_source_frame(expected["J"], expected["E"], + f"{side} shoulder") + expected_elbow = _arm_source_frame(expected["E"], expected["W"], + f"{side} elbow") + expected_elbow_local = _mm(_inverse(expected_shoulder), expected_elbow) + actual_elbow_local = _matrix( + elbow.get("rest_local"), + f"binding.rest_frames.{side}.elbow.rest_local", + ) + source_error = max(source_error, + _matrix_error(shoulder_matrix, expected_shoulder), + _matrix_error(elbow_matrix, expected_elbow), + _matrix_error(actual_elbow_local, expected_elbow_local)) + for joint_name, expected_point, matrix in ( + (f"{side}_shoulder", expected["J"], shoulder_matrix), + (f"{side}_elbow", expected["E"], elbow_matrix), + ): + joint = _mapping(joints.get(joint_name), f"binding.joints.{joint_name}") + joint_matrix = _matrix(joint.get("rest_matrix"), + f"binding.joints.{joint_name}.rest_matrix") + source_error = max(source_error, + _matrix_error( + joint_matrix, + expected_shoulder if joint_name.endswith("shoulder") + else expected_elbow, + ), + _matrix_error( + _matrix(joint.get("inverse_bind_matrix", joint.get("inverse_bind")), + f"binding.joints.{joint_name}.inverse_bind_matrix"), + _inverse(expected_shoulder if joint_name.endswith("shoulder") + else expected_elbow), + ), + max(abs(joint_matrix[row][3] - expected_point[row]) + for row in range(3))) + report["metrics"]["arm_source_frame_max_error"] = source_error + report["checks"]["arm_source_J_E_W_frames"] = source_error <= tolerance + if source_error > tolerance: + _error(report, "arm_source_frames", + "arm rest frames and joint origins must be derived from source J/E/W") + return source_error + + +def _check_arm_binding(report: dict[str, Any], base_parsed: Mapping[str, Any], + rest_parsed: Mapping[str, Any], binding: Mapping[str, Any], + prior_root_parsed: Mapping[str, Any], + prior_hip_binding: Mapping[str, Any], + leg_inputs: Mapping[str, Any], + protocol: Mapping[str, Any]) -> dict[str, Any]: + base_value = base_parsed["value"] + metadata = _mapping(base_value.get("metadata"), "base.metadata") + occupied = set() + chains = _mapping(metadata.get("chains"), "base.metadata.chains") + for side in _SIDES: + occupied.update(_sequence(_mapping(chains[side], f"base.metadata.chains.{side}") + .get("new_vertex_indices"), + f"base.metadata.chains.{side}.new_vertex_indices")) + arm_contract = _arm_metadata_contract(base_value, len(base_parsed["vertices"]), occupied) + arm_indices = set(arm_contract["all_indices"]) + head_present = "head" in metadata + head_contract = (_head_metadata_contract(base_value, len(base_parsed["vertices"]), arm_indices) + if head_present else {"present": False, "all_indices": set()}) + head_indices = set(head_contract.get("all_indices", ())) + weight_columns = _ARM_HEAD_WEIGHT_COLUMNS if head_present else _ARM_WEIGHT_COLUMNS + foot_contract = _foot_metadata_contract(base_value, len(base_parsed["vertices"]), + arm_indices | head_indices) + foot_indices = foot_contract["indices"] + expected_station_indices = (set(range(_OLD_ROOT_VERTEX_COUNT, len(base_parsed["vertices"]))) + - arm_indices + - head_indices + - set(foot_contract.get("excluded_indices", ()))) + rings = _constructor_station_rings(base_value, len(base_parsed["vertices"]), + expected_station_indices) + prior_weights = _mapped_prior_weights(_mapping(prior_hip_binding, "prior_hip_binding"), + _OLD_ROOT_VERTEX_COUNT) + raw_base = binding.get("base_weights", binding.get("weights")) + base_rows = _sequence(raw_base, "binding.base_weights") + if len(base_rows) != len(base_parsed["vertices"]): + raise ValueError("binding.base_weights must cover every L0 vertex") + base_weights = [] + for index, row in enumerate(base_rows): + values = _sequence(row, f"binding.base_weights[{index}]") + if len(values) != len(weight_columns): + raise ValueError("binding.base_weights has the wrong arm/head column count") + base_weights.append([_number(value, f"base weight[{index}][{column}]") + for column, value in enumerate(values)]) + tolerance = _require_limit(report, protocol, ( + "weight_sum_max_abs_error", "weight_partition_tolerance", "binding_transfer_tolerance", + )) + if isinstance(tolerance, tuple): + raise ValueError("binding tolerance must be scalar") + for index, row in enumerate(base_weights): + if any(value < -tolerance or value > 1.0 + tolerance for value in row): + _error(report, "arm_weight_bounds", "arm/head base weights must remain in the declared numeric bounds", vertex=index) + if abs(sum(row) - 1.0) > tolerance: + _error(report, "arm_weight_partition", "9-column base weights must partition unity", vertex=index) + + bound = _mapping(binding, "binding") + immutable_inputs = _mapping(leg_inputs, "leg_inputs") + binding_inputs = _mapping(bound.get("leg_inputs"), "binding.leg_inputs") + input_copy_matches = binding_inputs == immutable_inputs + source_error, hierarchy_matches = _binding_source_error(bound, immutable_inputs) + source_limit = _require_limit(report, protocol, ( + "rest_transform_max_abs_error", "binding_transfer_tolerance", "weight_partition_tolerance", + )) + if isinstance(source_limit, tuple): + raise ValueError("binding source tolerance must be scalar") + mapped = [int(value) for value in _sequence(bound.get("prior_column_map"), "prior_column_map")] + root_vertex_prefix = (base_parsed["vertices"][:_OLD_ROOT_VERTEX_COUNT] + == prior_root_parsed["vertices"]) + fixed_column_map = tuple(mapped) == _FIXED_PRIOR_COLUMN_MAP + arm_order_ok = tuple(bound.get("joint_order", ())) == (_ARM_HEAD_JOINTS if head_present else _ARM_JOINTS) + arm_columns_ok = tuple(bound.get("weight_columns", ())) == weight_columns + fields, blends, field_diagnostics = _arm_graph_fields( + base_value, base_parsed["quads"], metadata["arms"], + root_quads=prior_root_parsed["quads"] + ) + expected_base = [[0.0] * len(weight_columns) for _ in base_weights] + for index, old_row in enumerate(prior_weights): + expected_base[index][0] = old_row[0] + expected_base[index][1] = old_row[1] + expected_base[index][3] = old_row[2] + for side, upper_column in (("left", 5), ("right", 7)): + for index, influence in fields[side].items(): + expected_base[index][:5] = [value * (1.0 - influence) + for value in expected_base[index][:5]] + expected_base[index][upper_column] = influence + for side, upper_column, fore_column in (("left", 5, 6), ("right", 7, 8)): + for index, blend in blends[side].items(): + expected_base[index][upper_column] = 1.0 - blend + expected_base[index][fore_column] = blend + for side, thigh_column, shank_column in (("left", 1, 2), ("right", 3, 4)): + for station_index, ring in enumerate(rings[side]): + shank = _STATION_SHANK_WEIGHTS[station_index] + for index in ring: + expected_base[index][thigh_column] = 1.0 - shank + expected_base[index][shank_column] = shank + for side, shank_column in (("left", 2), ("right", 4)): + for index in foot_indices[side]: + expected_base[index][shank_column] = 1.0 + head_field: dict[int, float] = {} + head_diagnostics: dict[str, Any] = {} + if head_present: + head_field, head_diagnostics = _head_graph_field( + base_value, base_parsed["quads"], head_contract, + root_quads=prior_root_parsed["quads"] + ) + for index, influence in head_field.items(): + expected_base[index][:9] = [value * (1.0 - influence) + for value in expected_base[index][:9]] + expected_base[index][9] = influence + for index in head_indices: + expected_base[index] = [0.0] * 9 + [1.0] + tail_contract = _tail_metadata_contract(base_value, len(base_weights)) + if tail_contract["present"]: + expected_base_rows = _tail_expected_base_rows( + expected_base, tail_contract, weight_columns + ) + for index, row in expected_base_rows.items(): + expected_base[index] = row + base_error = max((abs(base_weights[index][column] - expected_base[index][column]) + for index in range(len(base_weights)) + for column in range(len(weight_columns))), default=math.inf) + arm_field_error = max( + (abs(base_weights[index][upper_column] - influence) + for side, upper_column in (("left", 5), ("right", 7)) + for index, influence in fields[side].items()), + default=math.inf, + ) + modified = set(fields["left"]) | set(fields["right"]) + if head_present and (set(head_field) & modified): + raise ValueError("head D0/D1 field overlaps an arm-modified root region") + if head_present: + modified.update(head_field) + prior_ratio_error = max( + (abs(base_weights[index][new_column] - + prior_weights[index][old_column] * (1.0 - fields[side][index])) + for side, upper_column in (("left", 5), ("right", 7)) + for index in fields[side] + for old_column, new_column in zip(range(3), _FIXED_PRIOR_COLUMN_MAP)), + default=math.inf, + ) + far_error = max((abs(base_weights[index][column] - expected_base[index][column]) + for index in range(_OLD_ROOT_VERTEX_COUNT) if index not in modified + for column in range(5)), default=0.0) + arm_source_error = _check_arm_source_frames(report, bound, arm_contract, source_limit) + head_source_error = (_head_source_frame_error(report, bound, head_contract, source_limit) + if head_present else 0.0) + stencils = _stencil_rows(rest_parsed["stencils"], len(rest_parsed["vertices"]), + len(base_weights), "rest.base_stencils", tolerance) + evaluated = _sequence(bound.get("evaluated_weights", bound.get("weights")), + "binding.evaluated_weights") + if len(evaluated) != len(rest_parsed["vertices"]): + raise ValueError("binding.evaluated_weights must cover every L2 vertex") + transfer_error = 0.0 + for vertex_index, row in enumerate(evaluated): + actual = [_number(value, f"evaluated weight[{vertex_index}][{column}]") + for column, value in enumerate(_sequence(row, f"evaluated weight[{vertex_index}]"))] + if len(actual) != len(weight_columns): + raise ValueError("binding.evaluated_weights has the wrong arm/head column count") + expected = [sum(coefficient * expected_base[base_index][column] + for base_index, coefficient in stencils[vertex_index]) + for column in range(len(weight_columns))] + transfer_error = max(transfer_error, + max(abs(actual[column] - expected[column]) + for column in range(len(weight_columns))) + ) + endpoint_error = max((abs(base_weights[index][column] - expected_base[index][column]) + for side in _SIDES for index, _blend in blends[side].items() + for column in range(len(weight_columns))), default=math.inf) + arm_checks = { + "declared_nine_weight_columns": arm_columns_ok, + "declared_nine_joint_hierarchy": arm_order_ok and hierarchy_matches, + "declared_ten_weight_columns": (not head_present) or arm_columns_ok, + "declared_ten_joint_hierarchy": (not head_present) or (arm_order_ok and hierarchy_matches), + "arm_source_J_E_W_frames": arm_source_error <= source_limit, + "arm_D0_D1_harmonic_shoulder": arm_field_error <= tolerance, + "arm_station_and_elbow_endpoint_weights": endpoint_error <= tolerance, + "arm_prior_ratios_and_far_rows": max(prior_ratio_error, far_error) <= tolerance, + "actual_l2_full_stencil_transfer": transfer_error <= tolerance, + "terminal_foot_full_l2_stencil_transfer": (not foot_contract["present"] or transfer_error <= tolerance), + "binding_leg_inputs_match_immutable_inputs": input_copy_matches, + "binding_rest_sources_match_J_K_A": hierarchy_matches and source_error <= source_limit, + } + if head_present: + arm_checks.update({ + "head_source_pivot_frame": head_source_error <= source_limit, + "head_D0_D1_harmonic_transition": max( + (abs(base_weights[index][9] - value) for index, value in head_field.items()), + default=math.inf, + ) <= tolerance, + "head_new_vertices_neck_onehot": all( + abs(base_weights[index][9] - 1.0) <= tolerance + and max(abs(value) for value in base_weights[index][:9]) <= tolerance + for index in head_indices + ), + "head_prior_ratios_and_far_rows": max( + (abs(base_weights[index][column] + - prior_weights[index][old_column] * (1.0 - head_field[index])) + for index in head_field + for old_column, column in zip(range(3), _FIXED_PRIOR_COLUMN_MAP)), + default=math.inf, + ) <= tolerance and far_error <= tolerance, + }) + report["checks"].update(arm_checks) + report["metrics"].update({ + "arm_graph": field_diagnostics, + "head_graph": head_diagnostics, + "arm_base_weight_max_error": base_error, + "arm_harmonic_field_max_error": arm_field_error, + "arm_far_root_weight_max_error": far_error, + "arm_modified_prior_ratio_max_error": prior_ratio_error, + "arm_endpoint_weight_max_error": endpoint_error, + "l2_full_stencil_max_error": transfer_error, + "prior_column_map": mapped, + }) + failures = { + "declared_nine_weight_columns": "binding weight columns do not match the exact nine-column arm contract", + "declared_nine_joint_hierarchy": "binding joint order or parent hierarchy does not match the exact nine-joint contract", + "arm_D0_D1_harmonic_shoulder": "arm root D0/D1 weights do not match the independent collar=1/D2=0 harmonic field", + "arm_station_and_elbow_endpoint_weights": "arm station or elbow endpoint weights do not match the declared section anchors", + "arm_prior_ratios_and_far_rows": "prior root weight ratios or far unchanged rows drifted", + "actual_l2_full_stencil_transfer": "evaluated 9-column weights do not equal complete rest stencil transfer", + } + if head_present: + failures.update({ + "declared_ten_weight_columns": "binding weight columns do not match the exact ten-column arm/head contract", + "declared_ten_joint_hierarchy": "binding joint order or parent hierarchy does not match the exact ten-joint contract", + "head_source_pivot_frame": "neck rest and inverse-bind matrices do not match the source pivot handoff", + "head_D0_D1_harmonic_transition": "neck root D0/D1 weights do not match the independent harmonic transition", + "head_new_vertices_neck_onehot": "head allocation must be one-hot to the neck joint", + "head_prior_ratios_and_far_rows": "neck transition changed prior root ratios or far rows unexpectedly", + }) + for name, detail in failures.items(): + if not arm_checks[name]: + _error(report, name, detail) + if not input_copy_matches: + _error(report, "binding_leg_inputs", "binding leg_inputs do not match immutable case inputs") + if not hierarchy_matches or source_error > source_limit: + _error(report, "binding_rest_sources", "binding leg rest frames do not match immutable J/K/A inputs") + return report + + +def _check_head_binding(report: dict[str, Any], base_parsed: Mapping[str, Any], + rest_parsed: Mapping[str, Any], binding: Mapping[str, Any], + prior_root_parsed: Mapping[str, Any], + prior_hip_binding: Mapping[str, Any], + leg_inputs: Mapping[str, Any], + protocol: Mapping[str, Any]) -> dict[str, Any]: + """Check the six-column neck/head transition independently of binder pose code.""" + base_value = base_parsed["value"] + metadata = _mapping(base_value.get("metadata"), "base.metadata") + chains = _mapping(metadata.get("chains"), "base.metadata.chains") + occupied: set[int] = set() + for side in _SIDES: + occupied.update(_sequence(_mapping(chains[side], f"base.metadata.chains.{side}") + .get("new_vertex_indices"), + f"base.metadata.chains.{side}.new_vertex_indices")) + head_contract = _head_metadata_contract(base_value, len(base_parsed["vertices"]), occupied) + if not head_contract["present"]: + raise ValueError("six-column binding requires base.metadata.head.binding_handoff") + head_indices = set(head_contract["all_indices"]) + foot_contract = _foot_metadata_contract(base_value, len(base_parsed["vertices"]), head_indices) + foot_indices = foot_contract["indices"] + expected_station_indices = (set(range(_OLD_ROOT_VERTEX_COUNT, len(base_parsed["vertices"]))) + - head_indices + - set(foot_contract.get("excluded_indices", ()))) + rings = _constructor_station_rings(base_value, len(base_parsed["vertices"]), + expected_station_indices) + prior_weights = _mapped_prior_weights(_mapping(prior_hip_binding, "prior_hip_binding"), + _OLD_ROOT_VERTEX_COUNT) + raw_base = binding.get("base_weights", binding.get("weights")) + base_rows = _sequence(raw_base, "binding.base_weights") + if len(base_rows) != len(base_parsed["vertices"]): + raise ValueError("binding.base_weights must cover every L0 vertex") + base_weights: list[list[float]] = [] + for index, row in enumerate(base_rows): + values = _sequence(row, f"binding.base_weights[{index}]") + if len(values) != len(_HEAD_WEIGHT_COLUMNS): + raise ValueError("6-column binding.base_weights must have pelvis/thigh/shank/neck columns") + base_weights.append([_number(value, f"base weight[{index}][{column}]") + for column, value in enumerate(values)]) + tolerance = _require_limit(report, protocol, ( + "weight_sum_max_abs_error", "weight_partition_tolerance", "binding_transfer_tolerance", + )) + if isinstance(tolerance, tuple): + raise ValueError("binding tolerance must be scalar") + bound = _mapping(binding, "binding") + immutable_inputs = _mapping(leg_inputs, "leg_inputs") + input_copy_matches = _mapping(bound.get("leg_inputs"), "binding.leg_inputs") == immutable_inputs + source_error, hierarchy_matches = _binding_source_error(bound, immutable_inputs) + source_limit = _require_limit(report, protocol, ( + "rest_transform_max_abs_error", "binding_transfer_tolerance", + "weight_partition_tolerance", + )) + if isinstance(source_limit, tuple): + raise ValueError("binding source tolerance must be scalar") + mapped = [int(value) for value in _sequence(bound.get("prior_column_map"), "prior_column_map")] + root_vertex_prefix = (base_parsed["vertices"][:_OLD_ROOT_VERTEX_COUNT] + == prior_root_parsed["vertices"]) + fixed_column_map = tuple(mapped) == _FIXED_PRIOR_COLUMN_MAP + station_values = _source_station_values(bound, immutable_inputs) + station_declaration_ok = (station_values is not None and + [float(value) for value in _sequence( + station_values, "source station knee values")] + == list(_STATION_SHANK_WEIGHTS)) + order_ok = tuple(bound.get("joint_order", ())) == _HEAD_JOINTS + columns_ok = tuple(bound.get("weight_columns", ())) == _HEAD_WEIGHT_COLUMNS + head_field, head_diagnostics = _head_graph_field( + base_value, base_parsed["quads"], head_contract, + root_quads=prior_root_parsed["quads"] + ) + expected_base = [[0.0] * len(_HEAD_WEIGHT_COLUMNS) for _ in base_weights] + for index, old_row in enumerate(prior_weights): + expected_base[index][0] = old_row[0] + expected_base[index][1] = old_row[1] + expected_base[index][3] = old_row[2] + for side, thigh_column, shank_column in (("left", 1, 2), ("right", 3, 4)): + for station_index, ring in enumerate(rings[side]): + shank = _STATION_SHANK_WEIGHTS[station_index] + for index in ring: + expected_base[index][thigh_column] = 1.0 - shank + expected_base[index][shank_column] = shank + for side, shank_column in (("left", 2), ("right", 4)): + for index in foot_indices[side]: + expected_base[index][shank_column] = 1.0 + for index, influence in head_field.items(): + expected_base[index][:5] = [value * (1.0 - influence) + for value in expected_base[index][:5]] + expected_base[index][5] = influence + for index in head_indices: + expected_base[index] = [0.0] * 5 + [1.0] + tail_contract = _tail_metadata_contract(base_value, len(base_weights)) + if tail_contract["present"]: + expected_base_rows = _tail_expected_base_rows( + expected_base, tail_contract, _HEAD_WEIGHT_COLUMNS + ) + for index, row in expected_base_rows.items(): + expected_base[index] = row + base_error = max((abs(base_weights[index][column] - expected_base[index][column]) + for index in range(len(base_weights)) + for column in range(len(_HEAD_WEIGHT_COLUMNS))), default=math.inf) + field_error = max((abs(base_weights[index][5] - influence) + for index, influence in head_field.items()), default=math.inf) + modified = set(head_field) + prior_ratio_error = max((abs(base_weights[index][column] + - prior_weights[index][old_column] * (1.0 - head_field[index])) + for index in head_field + for old_column, column in zip(range(3), _FIXED_PRIOR_COLUMN_MAP)), + default=math.inf) + far_error = max((abs(base_weights[index][column] - expected_base[index][column]) + for index in range(_OLD_ROOT_VERTEX_COUNT) if index not in modified + for column in range(5)), default=0.0) + source_frame_error = _head_source_frame_error(report, bound, head_contract, source_limit) + stencils = _stencil_rows(rest_parsed["stencils"], len(rest_parsed["vertices"]), + len(base_weights), "rest.base_stencils", tolerance) + evaluated = _sequence(bound.get("evaluated_weights", bound.get("weights")), + "binding.evaluated_weights") + if len(evaluated) != len(rest_parsed["vertices"]): + raise ValueError("binding.evaluated_weights must cover every L2 vertex") + transfer_error = 0.0 + for vertex_index, row in enumerate(evaluated): + actual = [_number(value, f"evaluated weight[{vertex_index}][{column}]") + for column, value in enumerate(_sequence(row, f"binding.evaluated_weights[{vertex_index}]"))] + if len(actual) != len(_HEAD_WEIGHT_COLUMNS): + raise ValueError("binding.evaluated_weights must have six columns") + expected = [sum(coefficient * expected_base[base_index][column] + for base_index, coefficient in stencils[vertex_index]) + for column in range(len(_HEAD_WEIGHT_COLUMNS))] + transfer_error = max(transfer_error, + max(abs(actual[column] - expected[column]) + for column in range(len(_HEAD_WEIGHT_COLUMNS)))) + report["checks"].update({ + "declared_six_weight_columns": columns_ok, + "declared_six_joint_hierarchy": order_ok and hierarchy_matches, + "declared_source_station_knee": station_declaration_ok, + "head_source_pivot_frame": source_frame_error <= source_limit, + "head_D0_D1_harmonic_transition": field_error <= tolerance, + "head_new_vertices_neck_onehot": all( + abs(base_weights[index][5] - 1.0) <= tolerance and + max(abs(value) for value in base_weights[index][:5]) <= tolerance + for index in head_indices + ), + "head_prior_ratios_and_far_rows": max(prior_ratio_error, far_error) <= tolerance, + "original_root_152x3_mapped_to_six_columns": root_vertex_prefix and fixed_column_map, + "actual_l2_full_stencil_transfer": transfer_error <= tolerance, + "binding_leg_inputs_match_immutable_inputs": input_copy_matches, + "binding_rest_sources_match_J_K_A": hierarchy_matches and source_error <= source_limit, + }) + report["metrics"].update({ + "head_graph": head_diagnostics, + "head_base_weight_max_error": base_error, + "head_harmonic_field_max_error": field_error, + "head_modified_prior_ratio_max_error": prior_ratio_error, + "head_far_root_weight_max_error": far_error, + "head_l2_full_stencil_max_error": transfer_error, + "prior_column_map": mapped, + "original_root_vertex_prefix": root_vertex_prefix, + "source_station_knee": station_values, + }) + failures = { + "declared_six_weight_columns": "binding weight columns do not match the exact six-column neck/head contract", + "declared_six_joint_hierarchy": "binding joint order or parent hierarchy does not match the exact six-joint contract", + "declared_source_station_knee": "declared base source-station knee values must equal [0,0,.5,1,1,1,1]", + "head_D0_D1_harmonic_transition": "neck root D0/D1 weights do not match the independent support=1/D2=0 harmonic field", + "head_new_vertices_neck_onehot": "head allocation must be one-hot to the neck joint", + "head_prior_ratios_and_far_rows": "head transition changed prior root ratios or far rows unexpectedly", + "original_root_152x3_mapped_to_six_columns": "the expanded L0 does not preserve the prior 152x3 root mapping", + "actual_l2_full_stencil_transfer": "evaluated six-column weights do not equal complete rest stencil transfer", + } + for name, detail in failures.items(): + if not report["checks"][name]: + _error(report, name, detail) + if not input_copy_matches: + _error(report, "binding_leg_inputs", "binding leg_inputs do not match immutable case inputs") + if not hierarchy_matches or source_error > source_limit: + _error(report, "binding_rest_sources", "binding leg rest frames or inverse binds do not match immutable J/K/A inputs") + return report + + +def _check_tail_binding(report: dict[str, Any], base_parsed: Mapping[str, Any], + rest_parsed: Mapping[str, Any], binding: Mapping[str, Any], + prior_root_parsed: Mapping[str, Any], + tail_contract: Mapping[str, Any], protocol: Mapping[str, Any]) -> None: + """Check the local host replacement and pelvis-only tail weight handoff.""" + try: + base_value = base_parsed["value"] + bound = _mapping(binding, "binding") + prior_quads = prior_root_parsed["quads"] + base_quads = base_parsed["quads"] + host_face = int(tail_contract["host_face"]) + host_vertices = list(tail_contract["host_vertices"]) + kept_exact = all( + 0 <= old_index < len(prior_quads) and 0 <= new_index < len(base_quads) + and base_quads[new_index] == prior_quads[old_index] + for old_index, new_index in tail_contract["kept_faces"] + ) + replacement_faces = list(tail_contract["replacement_faces"]) + replacement_slots_valid = all(0 <= index < len(base_quads) + for index in replacement_faces) + host_identity = (0 <= host_face < len(prior_quads) + and list(prior_quads[host_face]) == host_vertices) + host_replaced = (host_identity and 0 <= host_face < len(base_quads) + and list(base_quads[host_face]) != host_vertices) + + raw_columns = _sequence(bound.get("weight_columns"), "binding.weight_columns") + columns = [str(column) for column in raw_columns] + pelvis_column = columns.index("pelvis") if "pelvis" in columns else -1 + raw_base = binding.get("base_weights", binding.get("weights")) + base_rows = _sequence(raw_base, "binding.base_weights") + if len(base_rows) != len(base_parsed["vertices"]): + raise ValueError("binding.base_weights must cover every tail L0 vertex") + base_weights = [] + for index, row in enumerate(base_rows): + values = _sequence(row, f"binding.base_weights[{index}]") + if len(values) != len(columns): + raise ValueError("tail binding base weights disagree with weight_columns") + base_weights.append([_number(value, f"tail base weight[{index}][{column}]") + for column, value in enumerate(values)]) + tolerance = _require_limit(report, protocol, ( + "weight_sum_max_abs_error", "weight_partition_tolerance", "binding_transfer_tolerance", + )) + if isinstance(tolerance, tuple): + raise ValueError("tail binding tolerance must be scalar") + + fractions = { + vertex_index: float(fraction) + for ring, fraction in zip(tail_contract["rings"], tail_contract["station_fractions"]) + for vertex_index in ring + } + l0_error = 0.0 + l0_partition = True + expected_rows = _tail_expected_base_rows(base_weights, tail_contract, columns) + for vertex_index in tail_contract["new_vertex_indices"]: + expected = expected_rows[vertex_index] + l0_error = max(l0_error, + max((abs(base_weights[vertex_index][column] - expected[column]) + for column in range(len(columns))), default=math.inf)) + l0_partition = l0_partition and abs(sum(base_weights[vertex_index]) - 1.0) <= tolerance + + weighting = bound.get("tail_weighting") + weighting_contract = _mapping(_mapping(bound.get("metadata", {}), "binding.metadata") + .get("tail_weighting_contract", {}), + "binding.metadata.tail_weighting_contract") + declared_control = ( + weighting_contract.get("host_face") == host_face + and weighting_contract.get("host_vertex_indices") == host_vertices + and weighting_contract.get("kept_root_face_correspondence") == tail_contract["kept_faces"] + and weighting_contract.get("replacement_face_indices") == replacement_faces + and weighting_contract.get("collar_blend_strength") == tail_contract["collar_blend_strength"] + and weighting_contract.get("distal_target_joint") == "pelvis" + and weighting_contract.get("tail_joint") == "not_present" + ) + weighting_vertices = _mapping(weighting, "binding.tail_weighting").get("vertices", {}) + supports_match = True + for vertex_index in tail_contract["new_vertex_indices"]: + row = weighting_vertices.get(str(vertex_index)) + support = tail_contract["supports"][vertex_index] + supports_match = supports_match and isinstance(row, Mapping) and ( + row.get("host_vertex_indices") == support["host_vertex_indices"] + and row.get("convex_weights") == support["convex_weights"] + and row.get("ring_fraction") == fractions[vertex_index] + ) + + stencils = _stencil_rows(rest_parsed["stencils"], len(rest_parsed["vertices"]), + len(base_weights), "rest.base_stencils", tolerance) + evaluated = _sequence(bound.get("evaluated_weights", bound.get("weights")), + "binding.evaluated_weights") + if len(evaluated) != len(rest_parsed["vertices"]): + raise ValueError("binding.evaluated_weights must cover every tail L2 vertex") + tail_l2_rows = [index for index, row in enumerate(stencils) + if any(base_index in fractions for base_index, _coefficient in row)] + l2_error = 0.0 + for vertex_index in tail_l2_rows: + actual = [_number(value, f"tail evaluated weight[{vertex_index}][{column}]") + for column, value in enumerate(_sequence( + evaluated[vertex_index], f"binding.evaluated_weights[{vertex_index}]"))] + if len(actual) != len(columns): + raise ValueError("tail evaluated weights disagree with weight_columns") + expected = [sum(coefficient * expected_rows[base_index][column] + if base_index in expected_rows else + coefficient * base_weights[base_index][column] + for base_index, coefficient in stencils[vertex_index]) + for column in range(len(columns))] + l2_error = max(l2_error, + max((abs(actual[column] - expected[column]) + for column in range(len(columns))), default=math.inf)) + + checks = { + "tail_host_face_identity": host_identity, + "tail_kept_root_faces_exact": kept_exact, + "tail_host_face_replaced": host_replaced and replacement_slots_valid, + "tail_binding_control_explicit": declared_control, + "tail_corner_supports": supports_match, + "tail_l0_weight_formula": pelvis_column >= 0 and l0_error <= tolerance, + "tail_weight_partition": l0_partition, + "tail_l2_full_stencil_transfer": bool(tail_l2_rows) and l2_error <= tolerance, + } + report["checks"].update(checks) + report["metrics"].update({ + "tail_host_face": host_face, + "tail_host_vertices": host_vertices, + "tail_replacement_faces": replacement_faces, + "tail_new_vertex_count": len(tail_contract["new_vertex_indices"]), + "tail_l0_weight_max_error": l0_error, + "tail_l2_row_count": len(tail_l2_rows), + "tail_l2_weight_max_error": l2_error, + "tail_collar_blend_strength": tail_contract["collar_blend_strength"], + "tail_support_rule": ".55 own retained corner/.15 other retained corners", + }) + failures = { + "tail_host_face_identity": "tail host identity does not match the supplied original root", + "tail_kept_root_faces_exact": "a non-host root face changed despite the explicit kept-face mapping", + "tail_host_face_replaced": "tail host slot is not the declared one-to-many replacement", + "tail_binding_control_explicit": "binding metadata does not repeat the explicit pelvis-only tail control", + "tail_corner_supports": "tail binding did not retain the declared .55/.15 corner supports", + "tail_l0_weight_formula": "tail L0 weights do not match collar blend plus pelvis transition", + "tail_weight_partition": "tail L0 weights do not partition unity", + "tail_l2_full_stencil_transfer": "tail L2 rows do not equal complete rest-stencil weight transfer", + } + for name, detail in failures.items(): + if not checks[name]: + _error(report, name, detail) + except Exception as exc: + _error(report, "tail_binding_check_failure", str(exc)) + + +def check_binding(base: Mapping[str, Any], rest: Mapping[str, Any], binding: Mapping[str, Any], + prior_root: Mapping[str, Any], prior_hip_binding: Mapping[str, Any], + leg_inputs: Mapping[str, Any], protocol: Mapping[str, Any]) -> dict[str, Any]: + """Check the supported 5/6/9/10-column mapping and full L2 transfer independently.""" + report = _report("creature-kernel.connected-leg-assembly-binding-checks.v1") + try: + base_parsed = _mesh(base, "base") + rest_parsed = _mesh(rest, "rest") + prior_root_parsed = _mesh(prior_root, "prior_root") + if len(prior_root_parsed["vertices"]) != _OLD_ROOT_VERTEX_COUNT: + raise ValueError("prior root must preserve exactly 152 vertices") + tail_contract = _tail_metadata_contract(base_parsed["value"], + len(base_parsed["vertices"])) + base_metadata = base_parsed["value"].get("metadata", {}) + if isinstance(base_metadata, Mapping) and "arms" in base_metadata: + _check_arm_binding( + report, base_parsed, rest_parsed, binding, + prior_root_parsed, prior_hip_binding, leg_inputs, protocol + ) + if tail_contract["present"]: + _check_tail_binding(report, base_parsed, rest_parsed, binding, + prior_root_parsed, tail_contract, protocol) + return _finish(report) + if isinstance(base_metadata, Mapping) and "head" in base_metadata: + _check_head_binding( + report, base_parsed, rest_parsed, binding, + prior_root_parsed, prior_hip_binding, leg_inputs, protocol + ) + if tail_contract["present"]: + _check_tail_binding(report, base_parsed, rest_parsed, binding, + prior_root_parsed, tail_contract, protocol) + return _finish(report) + root_vertex_prefix = base_parsed["vertices"][:_OLD_ROOT_VERTEX_COUNT] == prior_root_parsed["vertices"] + if len(base_parsed["vertices"]) < _OLD_ROOT_VERTEX_COUNT: + root_vertex_prefix = False + prior_weights = _mapped_prior_weights(_mapping(prior_hip_binding, "prior_hip_binding"), _OLD_ROOT_VERTEX_COUNT) + raw_base = binding.get("base_weights", binding.get("weights")) + base_rows = _sequence(raw_base, "binding.base_weights") + if len(base_rows) != len(base_parsed["vertices"]): + raise ValueError("binding.base_weights must cover every L0 vertex") + base_weights = [] + for index, row in enumerate(base_rows): + values = _sequence(row, f"binding.base_weights[{index}]") + if len(values) != 5: + raise ValueError("binding.base_weights must have five columns") + base_weights.append([_number(value, f"base weight[{index}][{column}]") for column, value in enumerate(values)]) + tolerance = _require_limit(report, protocol, ( + "weight_sum_max_abs_error", "weight_partition_tolerance", "binding_transfer_tolerance", + )) + if isinstance(tolerance, tuple): + raise ValueError("binding tolerance must be scalar") + + bound = _mapping(binding, "binding") + immutable_inputs = _mapping(leg_inputs, "leg_inputs") + binding_inputs = _mapping(bound.get("leg_inputs"), "binding.leg_inputs") + input_copy_matches = binding_inputs == immutable_inputs + source_error, hierarchy_matches = _binding_source_error(bound, immutable_inputs) + source_limit = _require_limit(report, protocol, ( + "rest_transform_max_abs_error", "binding_transfer_tolerance", + "weight_partition_tolerance", + )) + if isinstance(source_limit, tuple): + raise ValueError("binding source tolerance must be scalar") + + station_values = _source_station_values(bound, immutable_inputs) + station_declaration_ok = (station_values is not None and + [float(value) for value in _sequence( + station_values, "source station knee values")] + == list(_STATION_SHANK_WEIGHTS)) + mapped = [int(value) for value in _sequence( + bound.get("prior_column_map"), "prior_column_map")] + fixed_column_map = tuple(mapped) == _FIXED_PRIOR_COLUMN_MAP + fixed_weight_columns = tuple(bound.get("weight_columns", ())) == _WEIGHT_COLUMNS + foot_contract = _foot_metadata_contract(base_parsed["value"], len(base_weights)) + foot_present = bool(foot_contract["present"]) + foot_indices = foot_contract["indices"] + expected_station_indices = set(range(_OLD_ROOT_VERTEX_COUNT, len(base_weights))) + expected_station_indices -= set(foot_contract.get("excluded_indices", ())) + rings = _constructor_station_rings(base_parsed["value"], len(base_weights), + expected_station_indices) + foot_declaration_ok = True + if foot_present: + expected_foot_declaration = { + side: list(foot_indices[side]) for side in _SIDES + } + binding_metadata = _mapping(bound.get("metadata", {}), "binding.metadata") + foot_declaration_ok = ( + bound.get("foot_vertex_indices") == expected_foot_declaration + and binding_metadata.get("foot_vertex_indices") == expected_foot_declaration + ) + expected_base = [[0.0] * 5 for _ in base_weights] + for index, old_row in enumerate(prior_weights): + for old_index, new_index in enumerate(_FIXED_PRIOR_COLUMN_MAP): + expected_base[index][new_index] = old_row[old_index] + for side, thigh_column, shank_column in ( + ("left", 1, 2), ("right", 3, 4), + ): + for station_index, ring in enumerate(rings[side]): + shank = _STATION_SHANK_WEIGHTS[station_index] + for vertex_index in ring: + expected_base[vertex_index][thigh_column] = 1.0 - shank + expected_base[vertex_index][shank_column] = shank + for side, shank_column in (("left", 2), ("right", 4)): + for vertex_index in foot_indices[side]: + expected_base[vertex_index][shank_column] = 1.0 + if tail_contract["present"]: + for ring, fraction in zip(tail_contract["rings"], tail_contract["station_fractions"]): + pelvis_fraction = (tail_contract["collar_blend_strength"] + + (1.0 - tail_contract["collar_blend_strength"]) * fraction) + for vertex_index in ring: + support = tail_contract["supports"][vertex_index] + host_support = [0.0] * 5 + for host_index, coefficient in zip(support["host_vertex_indices"], + support["convex_weights"]): + for column in range(5): + host_support[column] += coefficient * expected_base[host_index][column] + expected_base[vertex_index] = [ + (1.0 - pelvis_fraction) * value for value in host_support + ] + expected_base[vertex_index][0] += pelvis_fraction + base_error = max( + (abs(base_weights[index][column] - expected_base[index][column]) + for index in range(len(base_weights)) for column in range(5)), + default=math.inf, + ) + prior_mapping_ok = root_vertex_prefix and fixed_column_map and base_error <= tolerance + station_weight_error = max( + (abs(base_weights[index][column] - expected_base[index][column]) + for side in _SIDES for ring in rings[side] for index in ring + for column in range(5)), + default=math.inf, + ) + station_weights_ok = station_declaration_ok and station_weight_error <= tolerance + foot_weight_error = max( + (abs(base_weights[index][column] - expected_base[index][column]) + for side in _SIDES for index in foot_indices[side] + for column in range(5)), + default=0.0, + ) + foot_weights_ok = (not foot_present or + foot_declaration_ok and foot_weight_error <= tolerance) + + stencils = _stencil_rows(rest_parsed["stencils"], len(rest_parsed["vertices"]), + len(base_weights), "rest.base_stencils", tolerance) + evaluated = _sequence(binding.get("evaluated_weights", binding.get("weights")), "binding.evaluated_weights") + if len(evaluated) != len(rest_parsed["vertices"]): + raise ValueError("binding.evaluated_weights must cover every L2 vertex") + transfer_error = 0.0 + transfer_ok = True + for vertex_index, row in enumerate(evaluated): + actual = [_number(value, f"evaluated weight[{vertex_index}][{column}]") for column, value in enumerate(_sequence(row, f"binding.evaluated_weights[{vertex_index}]"))] + if len(actual) != 5: + raise ValueError("binding.evaluated_weights must have five columns") + expected = [sum(coefficient * expected_base[base_index][column] for base_index, coefficient in stencils[vertex_index]) + for column in range(5)] + transfer_error = max(transfer_error, max(abs(actual[column] - expected[column]) for column in range(5))) + transfer_ok = transfer_error <= tolerance + report["checks"].update({ + "declared_source_station_knee": station_declaration_ok, + "declared_five_weight_columns": fixed_weight_columns, + "original_root_vertices_preserved": root_vertex_prefix, + "original_root_152x3_mapped_to_five_columns": prior_mapping_ok, + "constructor_station_base_weights": station_weights_ok, + "actual_l2_full_stencil_transfer": transfer_ok, + "terminal_foot_metadata_and_shank_weights": foot_weights_ok, + "terminal_foot_full_l2_stencil_transfer": (not foot_present or transfer_ok), + "binding_leg_inputs_match_immutable_inputs": input_copy_matches, + "binding_rest_sources_match_J_K_A": hierarchy_matches and source_error <= source_limit, + }) + report["metrics"].update({"source_station_knee": station_values, + "base_weight_max_error": base_error, + "station_base_weight_max_error": station_weight_error, + "terminal_foot_base_weight_max_error": foot_weight_error, + "original_root_vertex_prefix": root_vertex_prefix, + "l2_full_stencil_max_error": transfer_error, + "prior_column_map": mapped, + "binding_rest_source_max_error": source_error}) + if not station_declaration_ok: + _error(report, "source_station_knee_values", "declared base source-station knee values must equal [0,0,.5,1,1,1,1]") + if not fixed_weight_columns: + _error(report, "weight_columns", "binding weight columns do not match pelvis/thigh/shank positional semantics") + if not root_vertex_prefix: + _error(report, "root_vertex_prefix", "the expanded L0 must preserve the original 152 root vertices") + if not prior_mapping_ok: + _error(report, "prior_root_mapping", "the preserved 152x3 prior binding does not map exactly into the five-column base field") + if not station_weights_ok: + _error(report, "station_base_weights", "constructor station rings do not carry the independently expected five-column base weights") + if not transfer_ok: + _error(report, "l2_stencil_transfer", "evaluated weights do not equal the full rest stencil transfer") + if not foot_weights_ok: + _error(report, "terminal_foot_weights", + "terminal foot L0 allocations must be declared in binding metadata and be shank one-hot") + if foot_present and not transfer_ok: + _error(report, "terminal_foot_l2_stencil_transfer", + "terminal foot evaluated weights do not equal the complete rest stencil transfer") + if not input_copy_matches: + _error(report, "binding_leg_inputs", "binding leg_inputs do not match the immutable case inputs") + if not hierarchy_matches or source_error > source_limit: + _error(report, "binding_rest_sources", "binding rest frames or inverse binds do not match source-derived J/K/A frames") + if tail_contract["present"]: + _check_tail_binding(report, base_parsed, rest_parsed, binding, + prior_root_parsed, tail_contract, protocol) + except Exception as exc: + if not report["errors"] or report["errors"][-1].get("detail") != str(exc): + _error(report, "input_or_check_failure", str(exc)) + return _finish(report) + + +def _stencil_signature(row: Any) -> tuple[tuple[int, float], ...]: + return tuple((int(pair[0]), float(pair[1])) for pair in _sequence(row, "stencil") ) + + +def _positions(mesh: Mapping[str, Any], count: int) -> list[Any] | None: + for source in (mesh, mesh.get("metadata")): + if isinstance(source, Mapping): + for key in ("parametric_positions", "patch_positions", "positions"): + if key in source: + values = _sequence(source[key], key) + if len(values) == count: + return values + return None + + +def _exit_vertices(mesh: Mapping[str, Any]) -> set[int]: + value = mesh.get("metadata") + if isinstance(value, Mapping): + for key in ("old_exit_vertices", "exit_vertices"): + if key in value: + return {int(index) for index in _sequence(value[key], key)} + loops = mesh.get("loops", mesh.get("boundary_loops")) + if isinstance(loops, Mapping): + result: set[int] = set() + for name, values in loops.items(): + normal = str(name).lower() + if any(word in normal for word in ("exit", "ankle", "thigh")): + result.update(int(index) for index in _sequence(values, f"loops.{name}")) + return result + return set() + + +def _declared_leg_root_ports(prior_root: Mapping[str, Any], + metadata: Mapping[str, Any]) -> dict[str, set[int]]: + """Validate the two leg seam declarations against the prior root topology.""" + raw_chains = metadata.get("chains") + if raw_chains is None: + return {} + chains = _mapping(raw_chains, "expanded_L0.metadata.chains") + loops = prior_root.get("loops") + if not isinstance(loops, Mapping): + raise ValueError("leg root ports require prior_L0 source loops") + boundary_cycles = _boundary_cycles(_edge_incidence(prior_root["quads"])) + closed = _mapping(_mapping(metadata.get("root"), + "expanded_L0.metadata.root").get("old_thigh_ports_closed"), + "expanded_L0.metadata.root.old_thigh_ports_closed") \ + if metadata.get("root", {}).get("old_thigh_ports_closed") is not None else None + result: dict[str, set[int]] = {} + occupied: set[int] = set() + for side in _SIDES: + chain = _mapping(chains.get(side), f"expanded_L0.metadata.chains.{side}") + declared = [int(index) for index in _sequence( + chain.get("root_exit"), f"expanded_L0.metadata.chains.{side}.root_exit")] + if len(declared) < 3 or len(set(declared)) != len(declared): + raise ValueError(f"expanded_L0.metadata.chains.{side}.root_exit must be a unique loop") + source_loop = loops.get(f"port.{side}_thigh") + if source_loop is None: + raise ValueError(f"prior_L0 is missing port.{side}_thigh") + source_loop = [int(index) for index in _sequence( + source_loop, f"prior_L0.loops.port.{side}_thigh")] + if (not _cyclic_equal(declared, source_loop) or + not any(_cyclic_equal(declared, boundary) for boundary in boundary_cycles)): + raise ValueError( + f"expanded_L0.metadata.chains.{side}.root_exit is not the declared prior-root boundary port") + if closed is not None: + closed_loop = [int(index) for index in _sequence( + closed.get(side), f"expanded_L0.metadata.root.old_thigh_ports_closed.{side}")] + if not _cyclic_equal(declared, closed_loop): + raise ValueError( + f"expanded_L0.metadata.root.old_thigh_ports_closed.{side} disagrees with chains.{side}.root_exit") + if occupied & set(declared): + raise ValueError("left and right leg root ports overlap") + occupied.update(declared) + result[f"leg_{side}"] = set(declared) + return result + + +def _declared_attachment_vertices(mesh: Mapping[str, Any], + tail: Mapping[str, Any], + prior_root: Mapping[str, Any]) -> dict[str, set[int]]: + """Return old-L0 source vertices whose appended seams may affect L2 stencils. + + A combined appendage mesh can change Catmull--Clark rows at several declared + ports. Those local rows are expected to lose exact full-stencil identity; + all other rows must still retain it. This is accounting for explicit + source metadata, not a distance-based exemption. + """ + metadata = _mapping(mesh.get("metadata"), "expanded_L0.metadata") + attachments: dict[str, set[int]] = {"tail": set(tail["host_vertices"])} + attachments.update(_declared_leg_root_ports(prior_root, metadata)) + + arms = metadata.get("arms") + if isinstance(arms, Mapping): + values: set[int] = set() + for side in _SIDES: + row = _mapping(arms.get(side), f"expanded_L0.metadata.arms.{side}") + source = _mapping(row.get("source_port"), + f"expanded_L0.metadata.arms.{side}.source_port") + values.update(int(index) for index in _sequence( + source.get("indices"), + f"expanded_L0.metadata.arms.{side}.source_port.indices")) + attachments["arms"] = values + + head = metadata.get("head") + if isinstance(head, Mapping): + handoff = head.get("binding_handoff") + source = handoff.get("consumed_neck_port_indices") if isinstance(handoff, Mapping) else None + if source is None: + source = head.get("neck_port_indices") + if source is not None: + attachments["head"] = {int(index) for index in _sequence( + source, "expanded_L0.metadata.head neck port indices")} + + feet = metadata.get("feet") + if isinstance(feet, Mapping): + values = set() + for side in _SIDES: + row = _mapping(feet.get(side), f"expanded_L0.metadata.feet.{side}") + source = row.get("ankle_source_loop") + if source is None: + attachment_loop = row.get("attachment_loop") + source = (attachment_loop.get("ankle") + if isinstance(attachment_loop, Mapping) else None) + if source is not None: + values.update(int(index) for index in _sequence( + source, f"expanded_L0.metadata.feet.{side}.ankle_source_loop")) + if values: + attachments["feet"] = values + + return attachments + + +def compare_root(prior_L0: Mapping[str, Any], expanded_L0: Mapping[str, Any], + prior_L2: Mapping[str, Any], expanded_L2: Mapping[str, Any]) -> dict[str, Any]: + """Compare unchanged root data, with an explicit tail host exception.""" + report = _report("creature-kernel.connected-leg-assembly-root-comparison.v1") + try: + old_l0, new_l0 = _mesh(prior_L0, "prior_L0"), _mesh(expanded_L0, "expanded_L0") + old_l2, new_l2 = _mesh(prior_L2, "prior_L2"), _mesh(expanded_L2, "expanded_L2") + l0_vertex_prefix = new_l0["vertices"][:len(old_l0["vertices"])] == old_l0["vertices"] + tail = _tail_metadata_contract(new_l0["value"], len(new_l0["vertices"])) + tail_mode = bool(tail["present"]) + if len(new_l0["vertices"]) < len(old_l0["vertices"]): + l0_vertex_prefix = False + if not old_l0["quads"] or not old_l2["quads"]: + raise ValueError("root comparison requires non-empty L0 and L2 face arrays") + if tail_mode: + host_face = int(tail["host_face"]) + host_identity = (host_face < len(old_l0["quads"]) + and list(old_l0["quads"][host_face]) == list(tail["host_vertices"])) + kept_exact = all( + 0 <= old_index < len(old_l0["quads"]) + and 0 <= new_index < len(new_l0["quads"]) + and new_l0["quads"][new_index] == old_l0["quads"][old_index] + for old_index, new_index in tail["kept_faces"] + ) + replacement_valid = ( + host_identity and host_face < len(new_l0["quads"]) + and list(new_l0["quads"][host_face]) != list(tail["host_vertices"]) + and all(0 <= index < len(new_l0["quads"]) for index in tail["replacement_faces"]) + ) + l0_face_prefix = kept_exact and replacement_valid + else: + l0_face_prefix = new_l0["quads"][:len(old_l0["quads"])] == old_l0["quads"] + host_identity = kept_exact = replacement_valid = True + if len(new_l0["quads"]) < len(old_l0["quads"]): + l0_face_prefix = False + relation_numerator, relation_denominator = len(new_l0["quads"]), len(old_l0["quads"]) + expected_l2 = len(old_l2["quads"]) * relation_numerator + l2_count_relation = len(new_l2["quads"]) * relation_denominator == expected_l2 + + old_stencils, new_stencils = old_l2["stencils"], new_l2["stencils"] + mapping_old_to_new: dict[int, int] = {} + mapping_consistent = True + stencil_invariance = True + changed_rows: list[dict[str, Any]] = [] + unexpected_far_rows: list[int] = [] + if old_stencils is None or new_stencils is None: + _unavailable(report, "missing_l2_stencils", "both L2 meshes must expose full base stencils") + stencil_invariance = False + else: + old_rows = _sequence(old_stencils, "prior_L2.base_stencils") + new_rows = _sequence(new_stencils, "expanded_L2.base_stencils") + if len(old_rows) != len(old_l2["vertices"]) or len(new_rows) != len(new_l2["vertices"]): + raise ValueError("L2 stencil arrays must cover their vertices") + old_exit = _exit_vertices(old_l2["value"]) + old_positions = _positions(old_l2["value"], len(old_l2["vertices"])) + new_positions = _positions(new_l2["value"], len(new_l2["vertices"])) + if tail_mode: + attachment_vertices = _declared_attachment_vertices(new_l0["value"], tail, old_l0["value"]) + all_attachment_vertices = set().union(*attachment_vertices.values()) + candidates: dict[tuple[tuple[tuple[int, float], ...], tuple[float, float, float]], list[int]] = defaultdict(list) + by_stencil: dict[tuple[tuple[int, float], ...], list[int]] = defaultdict(list) + for new_index, row in enumerate(new_rows): + signature = _stencil_signature(row) + by_stencil[signature].append(new_index) + candidates[(signature, new_l2["vertices"][new_index])].append(new_index) + used: set[int] = set() + for old_index, row in enumerate(old_rows): + signature = _stencil_signature(row) + exact = [index for index in candidates.get( + (signature, old_l2["vertices"][old_index]), []) if index not in used] + fallback = [index for index in by_stencil.get(signature, []) if index not in used] + new_index = (exact or fallback or [None])[0] + support_vertices = {int(pair[0]) for pair in _sequence( + row, "old attachment stencil")} + attachment_sources = sorted( + name for name, vertices in attachment_vertices.items() + if support_vertices & vertices + ) + near = bool(support_vertices & all_attachment_vertices) + if new_index is None: + mapping_consistent = False if not near else mapping_consistent + row_data: dict[str, Any] = { + "old_vertex": old_index, "new_vertex": None, + "expected_near_attachment": near, + "attachment_sources": attachment_sources, + "reason": "changed_full_stencil", + } + if near: + changed_rows.append(row_data) + else: + unexpected_far_rows.append(old_index) + changed_rows.append(row_data) + continue + used.add(new_index) + mapping_old_to_new[old_index] = new_index + displacement = _distance(old_l2["vertices"][old_index], new_l2["vertices"][new_index]) + if displacement > 0.0: + row_data = {"old_vertex": old_index, "new_vertex": new_index, + "surface_displacement": displacement, + "expected_near_attachment": near, + "attachment_sources": attachment_sources, + "reason": "same_full_stencil_displacement"} + if old_positions is not None and new_positions is not None: + row_data["parametric_position_displacement"] = _distance( + _vector(old_positions[old_index], "old parametric position"), + _vector(new_positions[new_index], "new parametric position")) + if old_exit: + row_data["distance_to_old_exit"] = min( + _distance(old_l2["vertices"][old_index], old_l2["vertices"][exit_index]) + for exit_index in old_exit if 0 <= exit_index < len(old_l2["vertices"]) + ) + changed_rows.append(row_data) + if not near: + unexpected_far_rows.append(old_index) + mapping_consistent = mapping_consistent and not unexpected_far_rows + stencil_invariance = not unexpected_far_rows + else: + mapping_new_to_old: dict[int, int] = {} + for old_face, new_face in zip(old_l2["quads"], new_l2["quads"][:len(old_l2["quads"])]): + for old_index, new_index in zip(old_face, new_face): + if (old_index in mapping_old_to_new and mapping_old_to_new[old_index] != new_index or + new_index in mapping_new_to_old and mapping_new_to_old[new_index] != old_index): + mapping_consistent = False + mapping_old_to_new[old_index] = new_index + mapping_new_to_old[new_index] = old_index + mapping_consistent = mapping_consistent and len(new_l2["quads"]) >= len(old_l2["quads"]) + for old_index, new_index in mapping_old_to_new.items(): + same = _stencil_signature(old_rows[old_index]) == _stencil_signature(new_rows[new_index]) + displacement = _distance(old_l2["vertices"][old_index], new_l2["vertices"][new_index]) + if same and displacement > 0.0: + stencil_invariance = False + if not same: + row_data = {"old_vertex": old_index, "new_vertex": new_index, + "surface_displacement": displacement} + if old_positions is not None and new_positions is not None: + row_data["parametric_position_displacement"] = _distance( + _vector(old_positions[old_index], "old parametric position"), + _vector(new_positions[new_index], "new parametric position")) + if old_exit: + row_data["distance_to_old_exit"] = min( + _distance(old_l2["vertices"][old_index], old_l2["vertices"][exit_index]) + for exit_index in old_exit if 0 <= exit_index < len(old_l2["vertices"]) + ) + changed_rows.append(row_data) + + report["checks"].update({ + "original_l0_vertex_prefix": l0_vertex_prefix, + "original_l0_face_prefix": l0_face_prefix, + "l2_face_count_relation": l2_count_relation, + "l2_face_prefix_mapping_consistent": mapping_consistent, + "same_full_stencil_unchanged_invariance": stencil_invariance, + }) + if tail_mode: + report["checks"].update({ + "tail_explicit_host_identity": host_identity, + "tail_kept_root_faces_exact": kept_exact, + "tail_host_replacement_declared": replacement_valid, + "tail_far_support_invariance": not unexpected_far_rows, + "tail_near_attachment_changes_labelled": all( + row.get("expected_near_attachment") for row in changed_rows + if row.get("new_vertex") is None or row.get("surface_displacement", 0.0) > 0.0 + ), + }) + parametric_displacements = [row["parametric_position_displacement"] for row in changed_rows + if "parametric_position_displacement" in row] + location_rows = [row for row in changed_rows if "distance_to_old_exit" in row] + report["metrics"].update({ + "l0_relation": {"numerator": relation_numerator, "denominator": relation_denominator}, + "old_to_new_l2_vertex_map": {str(key): value for key, value in sorted(mapping_old_to_new.items())}, + "changed_stencil_count": len(changed_rows), + "changed_stencil_displacements": changed_rows, + "unexpected_far_support_rows": unexpected_far_rows, + "tail_mode": tail_mode, + "parametric_patch_position_displacement_max": max(parametric_displacements, default=None), + "changed_stencil_location_worst": max(location_rows, key=lambda row: row["distance_to_old_exit"], default=None), + "changed_stencil_location_available": bool(location_rows), + "declared_attachment_vertices": { + name: sorted(vertices) for name, vertices in attachment_vertices.items() + } if tail_mode and old_stencils is not None and new_stencils is not None else {}, + }) + if not l0_vertex_prefix: + _error(report, "l0_vertex_prefix", "expanded L0 must preserve original vertices as a prefix") + if not l0_face_prefix: + _error(report, "tail_root_face_mapping" if tail_mode else "l0_face_prefix", + "expanded L0 must preserve every non-host face and explicitly replace only the declared host" + if tail_mode else "expanded L0 must append faces after the original face prefix") + if not l2_count_relation: + _error(report, "l2_face_count_relation", "expanded L2 face count does not equal original L2 count times the L0 relation") + if not mapping_consistent: + _error(report, "l2_face_mapping", "L2 correspondence is inconsistent outside the declared tail attachment") + if not stencil_invariance: + _error(report, "stencil_invariance", "far-support vertices with identical full stencils were displaced or lost") + if tail_mode and not report["checks"]["tail_near_attachment_changes_labelled"]: + _error(report, "tail_near_attachment_label", "tail attachment changes must be explicitly labelled as near-host changes") + except Exception as exc: + if not report["errors"] or report["errors"][-1].get("detail") != str(exc): + _error(report, "input_or_check_failure", str(exc)) + return _finish(report) + + +__all__ = ["check_mesh", "check_pose", "check_binding", "compare_root"] diff --git a/experiments/connected-leg-assembly/collision_broadphase.py b/experiments/connected-leg-assembly/collision_broadphase.py new file mode 100644 index 0000000..e0608dc --- /dev/null +++ b/experiments/connected-leg-assembly/collision_broadphase.py @@ -0,0 +1,275 @@ +"""Future-only NumPy AABB partition around the frozen collision narrowphase. + +This module is intentionally not wired into the connected-leg checker. It +keeps the frozen point, normalization, triangle, interval, shared-vertex, +shared-edge, duplicate, and SAT semantics, while replacing only exhaustive +Python pair enumeration with a bounded NumPy AABB partition. Every pair is +still accounted for in deterministic global ``i < j`` order. +""" +from __future__ import annotations + +import importlib.util +import math +from pathlib import Path +import sys +from typing import Any + +import numpy as np + + +FROZEN_CORE_PATH = Path( + "/home/ben/.cache/creature-kernel/pelvis-thigh-transition/" + "attempt-2-snapshot/source/experiments/owned-root-assembly-successor/" + "mesh_correctness.py" +) +METHOD = "numpy-conservative-aabb-partition-frozen-narrowphase.v1" +DEFAULT_BLOCK_SIZE = 1024 +MAX_BLOCK_SIZE = 2048 +_STAGES = ( + "aabb-disjoint", "sat-disjoint", "hit", "point-only", "excluded-adjacent" +) +_CORE: Any | None = None + + +def _load_core() -> Any: + global _CORE + if _CORE is not None: + return _CORE + if not FROZEN_CORE_PATH.is_file() or FROZEN_CORE_PATH.is_symlink(): + raise RuntimeError(f"frozen collision core is unavailable: {FROZEN_CORE_PATH}") + spec = importlib.util.spec_from_file_location( + "connected_leg_future_frozen_collision_core", FROZEN_CORE_PATH + ) + if spec is None or spec.loader is None: + raise RuntimeError(f"unable to load frozen collision core: {FROZEN_CORE_PATH}") + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + if Path(module.__file__).resolve() != FROZEN_CORE_PATH.resolve(): + raise RuntimeError("frozen collision core resolved away from its recorded path") + _CORE = module + return module + + +def _checked_block_size(value: Any) -> int: + if isinstance(value, bool) or not isinstance(value, int): + raise ValueError("block_size must be an integer") + if value <= 0 or value > MAX_BLOCK_SIZE: + raise ValueError(f"block_size must be in 1..{MAX_BLOCK_SIZE}") + return value + + +def _intersection_inputs_without_count_cap(core: Any, vertices: Any, + triangles: Any) -> tuple[Any, ...]: + """Use the frozen validation/normalization path without its 4096 wrapper.""" + points = core._points(vertices) + faces = core._indexed_rows( + triangles, 3, len(points), "triangles", cap=None + ) + normalized, scale = core._normalize_points(points) + for index, face in enumerate(faces): + length = core._norm_vec(core._triangle_normal(face, normalized)) + if not math.isfinite(length) or length <= core._FIXED_D: + core._fail(f"normalized triangle normal degeneracy at {index}") + bounds = tuple(core._aabb(normalized, face) for face in faces) + face_sets = tuple(frozenset(face) for face in faces) + return faces, normalized, scale, bounds, face_sets + + +def _aabb_disjoint_row(core: Any, lower: np.ndarray, upper: np.ndarray, + first: int, second_start: int, + second_end: int) -> np.ndarray: + """Return conservative frozen-interval AABB rejects for one first row.""" + second_lower = lower[second_start:second_end] + second_upper = upper[second_start:second_end] + first_lower = lower[first] + first_upper = upper[first] + # Moving the rejection cut toward -infinity can only turn a frozen reject + # into a survivor. It cannot reject a pair that the frozen interval rule + # would retain. + cut_for_second = np.nextafter( + second_lower - core.I0, -np.inf + ) + cut_for_first = np.nextafter( + first_lower - core.I0, -np.inf + ) + return np.any( + (first_upper < cut_for_second) | + (second_upper < cut_for_first), axis=1 + ) + + +def _bounded_append(target: list[Any], value: Any, cap: int) -> None: + if len(target) < cap: + target.append(value) + + +def _pair_ordinal(triangle_count: int, first: int, second: int) -> int: + return first * (2 * triangle_count - first - 1) // 2 + second - first - 1 + + +def collision_report(vertices: Any, triangles: Any, *, + include_classifications: bool = False, + block_size: int = DEFAULT_BLOCK_SIZE) -> dict[str, Any]: + """Return future-checker collision evidence with frozen classifications. + + The local parser intentionally accepts more than the frozen core's + production 4096-triangle wrapper, but retains every frozen per-point, + normalization, triangle-degeneracy, pair-status, shared-one rational, and + SAT operation. ``block_size`` is a bounded memory/performance parameter, + not a numerical or geometric gate. + """ + if not isinstance(include_classifications, bool): + raise ValueError("include_classifications must be a boolean") + block_size = _checked_block_size(block_size) + core = _load_core() + (faces, normalized, scale, bounds, face_sets) = \ + _intersection_inputs_without_count_cap(core, vertices, triangles) + triangle_count = len(faces) + expected_pairs = triangle_count * (triangle_count - 1) // 2 + if include_classifications and expected_pairs > core._MAX_CLASSIFICATION_DETAILS: + core._fail( + f"classification detail cap exceeded: {expected_pairs} > " + f"{core._MAX_CLASSIFICATION_DETAILS}" + ) + bounds_array = np.asarray(bounds, dtype=np.float64) + lower = bounds_array[:, :3] + upper = bounds_array[:, 3:] + class_counts = {stage: 0 for stage in _STAGES} + candidate_pairs: list[list[int]] = [] + hit_pairs: list[list[int]] = [] + nontrivial_classifications: list[list[Any]] = [] + classifications: list[list[Any]] | None = [] if include_classifications else None + candidate_count = 0 + hit_count = 0 + first_hit_pair: list[int] | None = None + proven_aabb_reject_count = 0 + survivor_count = 0 + + for first in range(max(0, triangle_count - 1)): + for second_start in range(first + 1, triangle_count, block_size): + second_end = min(second_start + block_size, triangle_count) + disjoint = _aabb_disjoint_row( + core, lower, upper, first, second_start, second_end + ) + reject_count = int(np.count_nonzero(disjoint)) + proven_aabb_reject_count += reject_count + if include_classifications: + second_offsets = range(second_end - second_start) + else: + second_offsets = np.flatnonzero(~disjoint).tolist() + survivor_count += len(second_offsets) + + for offset in second_offsets: + second = second_start + int(offset) + ordinal = _pair_ordinal(triangle_count, first, second) + if bool(disjoint[int(offset)]): + stage = "aabb-disjoint" + if include_classifications: + class_counts[stage] += 1 + assert classifications is not None + classifications.append([[first, second], stage]) + continue + + if include_classifications: + survivor_count += 1 + stage = core._pair_status( + first, second, faces, normalized, bounds, face_sets + ) + pair = (first, second) + if stage == "candidate": + candidate_count += 1 + if candidate_count > core._MAX_CANDIDATES: + core._fail( + f"AABB candidate cap exceeded: >{core._MAX_CANDIDATES}" + ) + _bounded_append(candidate_pairs, [first, second], + core._MAX_DIAGNOSTIC_EVIDENCE) + first_points = tuple(normalized[index] for index in faces[first]) + second_points = tuple(normalized[index] for index in faces[second]) + stage = "sat-disjoint" if core._sat_disjoint( + first_points, second_points + ) else "hit" + core._record_pair_policy( + triangle_count, first, second, ordinal, stage, class_counts + ) + if stage == "hit": + hit_count += 1 + if first_hit_pair is None: + first_hit_pair = [first, second] + _bounded_append(hit_pairs, [first, second], + core._MAX_DIAGNOSTIC_EVIDENCE) + if stage != "aabb-disjoint": + _bounded_append( + nontrivial_classifications, + [[first, second], stage], + core._MAX_DIAGNOSTIC_EVIDENCE, + ) + if classifications is not None: + classifications.append([[first, second], stage]) + + if not include_classifications: + class_counts["aabb-disjoint"] += proven_aabb_reject_count + classification_count = sum(class_counts.values()) + partition_complete = ( + proven_aabb_reject_count + survivor_count == expected_pairs + ) + classification_partition_complete = classification_count == expected_pairs + hit_pairs_truncated = hit_count > len(hit_pairs) + candidate_pairs_truncated = candidate_count > len(candidate_pairs) + nontrivial_pair_count = expected_pairs - class_counts["aabb-disjoint"] + nontrivial_evidence_truncated = ( + nontrivial_pair_count > len(nontrivial_classifications) + ) + errors: list[dict[str, Any]] = [] + if hit_pairs_truncated: + errors.append({ + "code": "truncated_collision_hit_inventory", + "detail": "frozen hit inventory evidence cap was exceeded", + }) + available = bool( + partition_complete and classification_partition_complete and not errors + ) + report: dict[str, Any] = { + "schema": "creature-kernel.connected-leg-future-collision.v1", + "method": METHOD, + "narrowphase": "frozen _pair_status followed by frozen _sat_disjoint", + "intersection_core_path": str(FROZEN_CORE_PATH), + "triangle_count": triangle_count, + "local_triangle_limit_exceeded": triangle_count > core._MAX_TRIANGLES, + "normalization_scale": scale, + "block_size": block_size, + "blocks": [ + {"block": index, "start": start, + "end": min(start + block_size, triangle_count), + "triangle_count": min(start + block_size, triangle_count) - start} + for index, start in enumerate(range(0, triangle_count, block_size)) + ], + "pair_count": expected_pairs, + "proven_aabb_reject_count": proven_aabb_reject_count, + "survivor_pair_count": survivor_count, + "pair_partition_complete": partition_complete, + "final_classification_count": classification_count, + "final_classification_partition_complete": classification_partition_complete, + "class_counts": {stage: class_counts[stage] for stage in _STAGES}, + "candidate_count": candidate_count, + "broad_phase_candidate_count": candidate_count, + "intersection_hit_count": hit_count, + "candidate_pairs": candidate_pairs, + "hit_pairs": hit_pairs, + "first_hit_pair": first_hit_pair, + "candidate_pairs_truncated": candidate_pairs_truncated, + "hit_pairs_truncated": hit_pairs_truncated, + "nontrivial_pair_count": nontrivial_pair_count, + "nontrivial_classifications": nontrivial_classifications, + "nontrivial_evidence_truncated": nontrivial_evidence_truncated, + "errors": errors, + "available": available, + "pass": bool(available and hit_count == 0), + } + if classifications is not None: + report["classifications"] = classifications + return report + + +__all__ = ["FROZEN_CORE_PATH", "METHOD", "collision_report"] diff --git a/experiments/connected-leg-assembly/construction.py b/experiments/connected-leg-assembly/construction.py new file mode 100644 index 0000000..83fb825 --- /dev/null +++ b/experiments/connected-leg-assembly/construction.py @@ -0,0 +1,842 @@ +"""Experiment-local connected leg staging from a saved calibrated root. + +This module deliberately stops at an open ankle port. It does not construct +feet, caps, a skeleton, a renderer, or a production topology. ``build`` +copies the supplied calibrated L0 vertices, quads, owners, and metadata +without renumbering them, then appends one welded bilateral chain per side. + +The root thigh loop is the existing eight-vertex loop named +``port.{side}_thigh`` and is not duplicated. Its centre is required to be +``T + .45 * (K - T)``. Seven new rings are appended in this exact order: + +* ``.70(T-K)`` is the mid-thigh row and ``(1-support_fraction)(T-K)`` is + the pre-knee support row (``.90(T-K)`` at the baseline support fraction); +* ``K`` is the knee row; +* ``K+(1.2*support_fraction)(A-K)`` is the post-knee support row + (``K+.12(A-K)`` at baseline), followed by ``K+.35(A-K)`` and + ``K+.72(A-K)``; and +* ``A`` is the open ankle row. + +The incoming radius is measured from the saved root exit ellipse. The +``mid_thigh_factor`` scales that ellipse at the .70 support row; radii then +linearly interpolate from that scaled row to the supplied knee radii. After +the knee, radii interpolate to the supplied calf radii at .35 and taper +linearly to the supplied ankle radii at 1.0. The lateral, anterior, and +posterior radii are independent, so posterior calf mass is an input rather +than a shape repair. + +The incoming tangent is ``normalize(K-T)`` and the outgoing tangent is +``normalize(A-K)``. The knee tangent is the normalized incoming/outgoing +bisector; ``support_fraction`` moves support rows only and does not alter the +knee frame. Each ring projects global +X onto its tangent plane, aligns its +sign to the preceding ring, and derives forward as ``X cross U`` with +``U = -tangent``. This preserves the saved root frame convention, avoids +arbitrary twist, and does not require a plantigrade direction. A zero +segment, singular +X projection, inconsistent root exit, or incompatible loop +winding is rejected rather than repaired. + +The evaluator delegates the old transition module's generic JSON +Catmull--Clark/stencil step. Its five-port and anatomy-specific gates are +not called. L0 uses identity base stencils; L1/L2 carry sparse, nonnegative +stencils back to the returned L0 vertices and propagate every declared loop. +For a fully closed mesh, a private adapter retains this module's exact +boundary checks and supplies the verified empty loop mapping to the same +frozen subdivision function; it does not manufacture a loop. +""" +from __future__ import annotations + +from collections.abc import Mapping +import copy +import hashlib +import importlib.util +import math +from pathlib import Path +import sys +from typing import Any + + +_SIDES = ("left", "right") +_THIGH_PORTS = {side: f"port.{side}_thigh" for side in _SIDES} +_ANKLE_PORTS = {side: f"port.{side}_ankle" for side in _SIDES} +_LEG_OWNERS = {side: f"domain.{side}_leg" for side in _SIDES} +_COORDINATE_TOLERANCE = 1.0e-8 +_STENCIL_TOLERANCE = 1.0e-10 +_MID_THIGH_FRACTION = 0.70 +_CALF_FRACTION = 0.35 +_ANKLE_APPROACH_FRACTION = 0.72 +_POST_KNEE_SUPPORT_MULTIPLIER = 1.2 +_ROLE_METADATA_KEYS = ("J_role", "TK_source_role", "distal_design_status") +_SIDE_GEOMETRIC_KEYS = ( + "J", "T", "K", "A", "radii", "mid_thigh_factor", "support_fraction" +) +_SIDE_INPUT_KEYS = frozenset((*_SIDE_GEOMETRIC_KEYS, *_ROLE_METADATA_KEYS)) +_GENERIC_TRANSITION_PATH = Path( + "/home/ben/.cache/creature-kernel/pelvis-thigh-transition/" + "attempt-2-snapshot/source/experiments/pelvis-thigh-transition/" + "construction.py" +) +_CLOSED_GENERIC_TRANSITION_CACHE: Any | None = None +_SECTION_NAMES = ( + "mid_thigh", + "knee_pre_support", + "knee", + "knee_post_support", + "calf", + "ankle_approach", + "ankle", +) + + +class ConstructionError(ValueError): + """Raised when the bounded leg construction cannot be admitted.""" + + +def _fail(message: str) -> None: + raise ConstructionError(message) + + +def _mapping(value: Any, where: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping): + _fail(f"{where} must be a mapping") + return value + + +def _finite(value: Any, where: str) -> float: + if type(value) is not float or not math.isfinite(value): + _fail(f"{where} must be a finite binary64 float") + return value + + +def _vector(value: Any, where: str) -> tuple[float, float, float]: + if type(value) not in (list, tuple) or len(value) != 3: + _fail(f"{where} must be a three-component vector") + return tuple(_finite(item, f"{where}[{index}]") + for index, item in enumerate(value)) # type: ignore[return-value] + + +def _scalar(value: Any, where: str, *, lower: float | None = None, + upper: float | None = None) -> float: + result = _finite(value, where) + if lower is not None and not result >= lower: + _fail(f"{where} must be >= {lower}") + if upper is not None and not result <= upper: + _fail(f"{where} must be <= {upper}") + return result + + +def _add(*values: tuple[float, float, float]) -> tuple[float, float, float]: + return tuple(sum(value[axis] for value in values) for axis in range(3)) # type: ignore[return-value] + + +def _sub(left: tuple[float, float, float], + right: tuple[float, float, float]) -> tuple[float, float, float]: + return tuple(left[axis] - right[axis] for axis in range(3)) # type: ignore[return-value] + + +def _scale(value: tuple[float, float, float], factor: float) -> tuple[float, float, float]: + return tuple(factor * item for item in value) # type: ignore[return-value] + + +def _dot(left: tuple[float, float, float], + right: tuple[float, float, float]) -> float: + return sum(left[axis] * right[axis] for axis in range(3)) + + +def _cross(left: tuple[float, float, float], + right: tuple[float, float, float]) -> tuple[float, float, float]: + return ( + left[1] * right[2] - left[2] * right[1], + left[2] * right[0] - left[0] * right[2], + left[0] * right[1] - left[1] * right[0], + ) + + +def _norm(value: tuple[float, float, float]) -> float: + return math.sqrt(_dot(value, value)) + + +def _normalise(value: tuple[float, float, float], where: str) -> tuple[float, float, float]: + length = _norm(value) + if not math.isfinite(length) or not length > 0.0: + _fail(f"{where} must have positive finite length") + return _scale(value, 1.0 / length) + + +def _lerp(left: tuple[float, float, float], + right: tuple[float, float, float], fraction: float) -> tuple[float, float, float]: + return _add(_scale(left, 1.0 - fraction), _scale(right, fraction)) + + +def _close(left: tuple[float, float, float], + right: tuple[float, float, float], where: str) -> None: + if any(abs(left[axis] - right[axis]) > _COORDINATE_TOLERANCE + for axis in range(3)): + _fail(f"{where} differs from the saved root") + + +def _edge_key(left: int, right: int) -> tuple[int, int]: + return (left, right) if left < right else (right, left) + + +def _edge_uses(quads: list[tuple[int, int, int, int]]) -> dict[tuple[int, int], list[tuple[int, int, int]]]: + uses: dict[tuple[int, int], list[tuple[int, int, int]]] = {} + for face_index, face in enumerate(quads): + for corner, left in enumerate(face): + right = face[(corner + 1) % 4] + uses.setdefault(_edge_key(left, right), []).append( + (face_index, left, right)) + return uses + + +def _validate_stencils(raw: Any, vertex_count: int, base_count: int) -> list[list[list[float | int]]]: + if type(raw) not in (list, tuple) or len(raw) != vertex_count: + _fail("base_stencils must contain one stencil per vertex") + result: list[list[list[float | int]]] = [] + for vertex_index, raw_stencil in enumerate(raw): + if type(raw_stencil) not in (list, tuple) or not raw_stencil: + _fail(f"base_stencils[{vertex_index}] must not be empty") + terms: list[list[float | int]] = [] + previous = -1 + total = 0.0 + for term_index, raw_term in enumerate(raw_stencil): + if type(raw_term) not in (list, tuple) or len(raw_term) != 2: + _fail(f"base_stencils[{vertex_index}][{term_index}] is malformed") + base_index, coefficient = raw_term + if type(base_index) is not int or base_index <= previous: + _fail(f"base_stencils[{vertex_index}] indices must be sorted and unique") + if base_index < 0 or base_index >= base_count: + _fail(f"base_stencils[{vertex_index}] references an unknown base vertex") + coefficient = _finite(coefficient, "base stencil coefficient") + if coefficient == 0.0 or coefficient < -_STENCIL_TOLERANCE: + _fail(f"base_stencils[{vertex_index}] has an invalid coefficient") + terms.append([base_index, coefficient]) + total += coefficient + previous = base_index + if abs(total - 1.0) > _STENCIL_TOLERANCE: + _fail(f"base_stencils[{vertex_index}] must partition unity") + result.append(terms) + return result + + +def _validate_mesh(mesh: Mapping[str, Any]) -> None: + required = ("vertices", "quads", "face_owners", "control_owners", + "loops", "base_stencils", "frames", "metadata") + if any(key not in mesh for key in required): + _fail("mesh is missing a required connected-leg field") + raw_vertices = mesh["vertices"] + if type(raw_vertices) not in (list, tuple) or not raw_vertices: + _fail("mesh.vertices must be a non-empty sequence") + vertices = [_vector(point, f"vertices[{index}]") + for index, point in enumerate(raw_vertices)] + raw_quads = mesh["quads"] + if type(raw_quads) not in (list, tuple) or not raw_quads: + _fail("mesh.quads must be a non-empty sequence") + quads: list[tuple[int, int, int, int]] = [] + seen_faces: set[tuple[int, int, int, int]] = set() + for face_index, raw_face in enumerate(raw_quads): + if type(raw_face) not in (list, tuple) or len(raw_face) != 4: + _fail(f"quads[{face_index}] must contain four indices") + face = tuple(raw_face) + if any(type(index) is not int for index in face): + _fail(f"quads[{face_index}] indices must be integers") + if len(set(face)) != 4 or any(index < 0 or index >= len(vertices) + for index in face): + _fail(f"quads[{face_index}] has invalid indices") + canonical = min(face[index:] + face[:index] + for index in range(4)) + reverse = tuple(reversed(face)) + canonical = min(canonical, *( + reverse[index:] + reverse[:index] for index in range(4))) + if canonical in seen_faces: + _fail("duplicate quad, including reversed/cyclic duplicate") + seen_faces.add(canonical) + quads.append(face) # type: ignore[arg-type] + + face_owners = mesh["face_owners"] + if type(face_owners) not in (list, tuple) or len(face_owners) != len(quads): + _fail("face_owners must match the quad count") + if any(type(owner) is not str or not owner for owner in face_owners): + _fail("face_owners must contain non-empty strings") + control_owners = mesh["control_owners"] + if type(control_owners) not in (list, tuple) or len(control_owners) != len(vertices): + _fail("control_owners must match the vertex count") + if any(type(owner) is not str or not owner for owner in control_owners): + _fail("control_owners must contain non-empty strings") + + metadata = _mapping(mesh["metadata"], "mesh.metadata") + base_owners = metadata.get("base_control_owners") + if type(base_owners) not in (list, tuple) or not base_owners: + _fail("metadata.base_control_owners must be a non-empty L0 owner list") + base_vertex_count = metadata.get("base_vertex_count", len(base_owners)) + if type(base_vertex_count) is not int or base_vertex_count != len(base_owners): + _fail("metadata.base_vertex_count must match the L0 owner count") + if any(type(owner) is not str or not owner for owner in base_owners): + _fail("metadata.base_control_owners must contain non-empty strings") + if metadata.get("admission_status") != "accepted": + _fail("connected-leg meshes must have accepted admission metadata") + if metadata.get("admission_failures") != []: + _fail("accepted connected-leg meshes must have no admission failures") + if type(metadata.get("dominant_owner_label")) is not str: + _fail("metadata.dominant_owner_label is required") + _validate_stencils(mesh["base_stencils"], len(vertices), len(base_owners)) + + raw_frames = mesh["frames"] + if type(raw_frames) is not dict or set(raw_frames) != set(_SIDES): + _fail("frames must contain exactly left and right") + for side in _SIDES: + frame = raw_frames[side] + if type(frame) is not dict: + _fail(f"frames.{side} must be a mapping") + for key in ("H", "d", "X", "U", "F", "exit"): + _vector(frame.get(key), f"frames.{side}.{key}") + _finite(frame.get("length"), f"frames.{side}.length") + + loops = _mapping(mesh["loops"], "mesh.loops") + declared: set[tuple[int, int]] = set() + for name, raw_loop in loops.items(): + if type(name) is not str or type(raw_loop) not in (list, tuple) or len(raw_loop) < 3: + _fail("each mesh loop must contain at least three vertex indices") + loop = tuple(raw_loop) + if any(type(index) is not int or index < 0 or index >= len(vertices) + for index in loop) or len(set(loop)) != len(loop): + _fail(f"loop {name!r} has invalid indices") + for index, left in enumerate(loop): + edge = _edge_key(left, loop[(index + 1) % len(loop)]) + if edge in declared: + _fail("a boundary edge is declared by more than one loop") + declared.add(edge) + + uses = _edge_uses(quads) + if any(len(rows) not in (1, 2) for rows in uses.values()): + _fail("mesh has a non-manifold edge") + if any(len(rows) == 2 and rows[0][1:] == rows[1][1:] + for rows in uses.values()): + _fail("mesh has an orientation conflict") + boundary = {edge for edge, rows in uses.items() if len(rows) == 1} + if declared != boundary: + _fail("declared loops do not cover the mesh boundary exactly") + + adjacency = {index: set() for index in range(len(vertices))} + for left, right in uses: + adjacency[left].add(right) + adjacency[right].add(left) + if any(not neighbours for neighbours in adjacency.values()): + _fail("mesh contains an unused vertex") + seen = {0} + pending = [0] + while pending: + vertex = pending.pop() + for neighbour in adjacency[vertex]: + if neighbour not in seen: + seen.add(neighbour) + pending.append(neighbour) + if len(seen) != len(vertices): + _fail("mesh is disconnected") + + +def _identity_stencils(count: int) -> list[list[list[float | int]]]: + return [[[index, 1.0]] for index in range(count)] + + +def _parse_leg_inputs(leg_inputs: Any) -> dict[str, dict[str, Any]]: + value = _mapping(leg_inputs, "leg_inputs") + if set(value) != set(_SIDES): + _fail("leg_inputs must contain only left and right side entries") + parsed: dict[str, dict[str, Any]] = {} + for side in _SIDES: + row = _mapping(value[side], f"leg_inputs.{side}") + if set(row) != _SIDE_INPUT_KEYS: + _fail( + f"leg_inputs.{side} must contain T/K/A/J, radii, the two " + "per-side factors, and the declared role metadata" + ) + factor = _scalar(row["mid_thigh_factor"], + f"leg_inputs.{side}.mid_thigh_factor", lower=0.0) + support = _scalar(row["support_fraction"], + f"leg_inputs.{side}.support_fraction", + lower=0.0, upper=1.0) + if not 0.0 < support < min( + 1.0 - _MID_THIGH_FRACTION, + _CALF_FRACTION / _POST_KNEE_SUPPORT_MULTIPLIER): + _fail( + f"leg_inputs.{side}.support_fraction must keep the named " + "support rings strictly between mid-thigh/knee and knee/calf" + ) + radii = _mapping(row["radii"], f"leg_inputs.{side}.radii") + if set(radii) != {"knee", "calf", "ankle"}: + _fail(f"leg_inputs.{side}.radii must contain knee, calf, and ankle") + checked_radii = {} + for name in ("knee", "calf", "ankle"): + vector = _vector(radii[name], f"leg_inputs.{side}.radii.{name}") + if any(not item > 0.0 for item in vector): + _fail(f"leg_inputs.{side}.radii.{name} must be positive") + checked_radii[name] = vector + parsed[side] = { + "J": _vector(row["J"], f"leg_inputs.{side}.J"), + "T": _vector(row["T"], f"leg_inputs.{side}.T"), + "K": _vector(row["K"], f"leg_inputs.{side}.K"), + "A": _vector(row["A"], f"leg_inputs.{side}.A"), + "radii": checked_radii, + "mid_thigh_factor": factor, + "support_fraction": support, + "role_metadata": { + key: row[key] for key in _ROLE_METADATA_KEYS + }, + } + for key, metadata in parsed[side]["role_metadata"].items(): + if type(metadata) is not str or not metadata: + _fail(f"leg_inputs.{side}.{key} must be a non-empty string") + return parsed + + +def _root_loop(root_mesh: Mapping[str, Any], side: str, vertex_count: int) -> list[int]: + loops = _mapping(root_mesh["loops"], "root_mesh.loops") + port = _THIGH_PORTS[side] + raw_loop = loops.get(port) + if type(raw_loop) not in (list, tuple) or len(raw_loop) != 8: + _fail(f"root_mesh.loops.{port} must be an eight-vertex loop") + loop = [int(index) if type(index) is int else -1 for index in raw_loop] + if any(index < 0 or index >= vertex_count for index in loop) or len(set(loop)) != 8: + _fail(f"root_mesh.loops.{port} is invalid") + metadata = _mapping(root_mesh["metadata"], "root_mesh.metadata") + transitions = _mapping(metadata.get("transition_indices"), + "root_mesh.metadata.transition_indices") + row = _mapping(transitions.get(side), f"transition_indices.{side}") + raw_exit = row.get("exit") + if type(raw_exit) not in (list, tuple) or tuple(raw_exit) != tuple(loop): + _fail(f"root metadata exit order disagrees with {port}") + return loop + + +def _root_edge_signs(root_quads: list[tuple[int, int, int, int]], + loop: list[int]) -> int: + uses = _edge_uses(root_quads) + signs = [] + for index, left in enumerate(loop): + right = loop[(index + 1) % len(loop)] + rows = uses.get(_edge_key(left, right), []) + if len(rows) != 1: + _fail("root thigh exit edge is not a unique boundary edge") + _, used_left, used_right = rows[0] + if (used_left, used_right) == (left, right): + signs.append(1) + elif (used_left, used_right) == (right, left): + signs.append(-1) + else: # pragma: no cover - guarded by the edge key lookup + _fail("root thigh exit edge direction cannot be inferred") + if len(set(signs)) != 1: + _fail("root thigh exit loop has inconsistent winding") + return signs[0] + + +def _project_plus_x(tangent: tuple[float, float, float], where: str) -> tuple[float, float, float]: + world_x = (1.0, 0.0, 0.0) + projected = _sub(world_x, _scale(tangent, _dot(world_x, tangent))) + return _normalise(projected, f"{where} projected +X") + + +def _root_template(root_vertices: list[tuple[float, float, float]], + loop: list[int], centre: tuple[float, float, float], + frame: Mapping[str, Any], side: str) -> tuple[list[tuple[float, float]], tuple[float, float, float]]: + x_axis = _vector(frame.get("X"), f"root_mesh.frames.{side}.X") + f_axis = _vector(frame.get("F"), f"root_mesh.frames.{side}.F") + direction = _vector(frame.get("d"), f"root_mesh.frames.{side}.d") + x_axis = _normalise(x_axis, f"root_mesh.frames.{side}.X") + f_axis = _normalise(f_axis, f"root_mesh.frames.{side}.F") + direction = _normalise(direction, f"root_mesh.frames.{side}.d") + up_axis = _scale(direction, -1.0) + if abs(_dot(x_axis, f_axis)) > _COORDINATE_TOLERANCE: + _fail(f"root_mesh.frames.{side} X/F are not orthogonal") + if _dot(_cross(x_axis, up_axis), f_axis) < 1.0 - 1.0e-6: + _fail(f"root_mesh.frames.{side} uses an incompatible forward convention") + projected_x = _project_plus_x(direction, f"root_mesh.frames.{side}") + if _dot(projected_x, x_axis) < 1.0 - 1.0e-6: + _fail(f"root_mesh.frames.{side}.X is not the projected +X frame") + + projected: list[tuple[float, float]] = [] + anterior = 0.0 + posterior = 0.0 + lateral = 0.0 + for vertex in loop: + delta = _sub(root_vertices[vertex], centre) + normal_residual = abs(_dot(delta, direction)) + if normal_residual > _COORDINATE_TOLERANCE: + _fail(f"root {side} thigh exit is not in its frame plane") + lateral_value = _dot(delta, x_axis) + forward_value = _dot(delta, f_axis) + lateral = max(lateral, abs(lateral_value)) + anterior = max(anterior, forward_value) + posterior = max(posterior, -forward_value) + projected.append((lateral_value, forward_value)) + if not lateral > 0.0 or not anterior > 0.0 or not posterior > 0.0: + _fail(f"root {side} thigh exit has a degenerate ellipse") + template = [ + (lateral_value / lateral, + forward_value / (anterior if forward_value >= 0.0 else posterior)) + for lateral_value, forward_value in projected + ] + return template, (lateral, anterior, posterior) + + +def _section_centres(T: tuple[float, float, float], + K: tuple[float, float, float], + A: tuple[float, float, float], + support_fraction: float) -> tuple[list[dict[str, Any]], tuple[float, float, float], tuple[float, float, float]]: + incoming = _normalise(_sub(K, T), "leg T-K segment") + outgoing = _normalise(_sub(A, K), "leg K-A segment") + pre_knee_fraction = 1.0 - support_fraction + post_knee_fraction = _POST_KNEE_SUPPORT_MULTIPLIER * support_fraction + return ([ + {"name": "mid_thigh", "path": "T_to_K", "fraction": _MID_THIGH_FRACTION, + "centre": _lerp(T, K, _MID_THIGH_FRACTION)}, + {"name": "knee_pre_support", "path": "T_to_K", "fraction": pre_knee_fraction, + "centre": _lerp(T, K, pre_knee_fraction)}, + {"name": "knee", "path": "T_to_K", "fraction": 1.0, + "centre": K}, + {"name": "knee_post_support", "path": "K_to_A", "fraction": post_knee_fraction, + "centre": _lerp(K, A, post_knee_fraction)}, + {"name": "calf", "path": "K_to_A", "fraction": _CALF_FRACTION, + "centre": _lerp(K, A, _CALF_FRACTION)}, + {"name": "ankle_approach", "path": "K_to_A", "fraction": _ANKLE_APPROACH_FRACTION, + "centre": _lerp(K, A, _ANKLE_APPROACH_FRACTION)}, + {"name": "ankle", "path": "K_to_A", "fraction": 1.0, + "centre": A}, + ], incoming, outgoing) + + +def _section_radii(exit_radii: tuple[float, float, float], + leg_radii: Mapping[str, tuple[float, float, float]], + factor: float, section: Mapping[str, Any]) -> tuple[float, float, float]: + name = section["name"] + if section["path"] == "T_to_K": + fraction = float(section["fraction"]) + mid = _scale(exit_radii, factor) + if fraction <= 0.70: + return _lerp(exit_radii, mid, (fraction - 0.45) / 0.25) + return _lerp(mid, leg_radii["knee"], (fraction - 0.70) / 0.30) + fraction = float(section["fraction"]) + if fraction <= 0.35: + return _lerp(leg_radii["knee"], leg_radii["calf"], fraction / 0.35) + result = _lerp(leg_radii["calf"], leg_radii["ankle"], + (fraction - 0.35) / 0.65) + if name == "ankle": + return leg_radii["ankle"] + return result + + +def _ring_frame(tangent: tuple[float, float, float], previous_x: tuple[float, float, float] | None, + where: str) -> dict[str, tuple[float, float, float]]: + x_axis = _project_plus_x(tangent, where) + if previous_x is not None and _dot(x_axis, previous_x) < 0.0: + x_axis = _scale(x_axis, -1.0) + up_axis = _scale(tangent, -1.0) + forward = _normalise(_cross(x_axis, up_axis), f"{where} forward frame") + return {"tangent": tangent, "X": x_axis, "U": up_axis, "F": forward} + + +def _jsonable(value: Any) -> Any: + if isinstance(value, Mapping): + return {str(key): _jsonable(item) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [_jsonable(item) for item in value] + return value + + +def _load_generic_transition() -> Any: + path = _GENERIC_TRANSITION_PATH + name = "_ck_connected_leg_generic_transition" + existing = sys.modules.get(name) + if existing is not None: + return existing + spec = importlib.util.spec_from_file_location(name, path) + if spec is None or spec.loader is None: + _fail(f"unable to load read-only generic transition evaluator: {path}") + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + return module + + +def _closed_generic_validation(mesh: Mapping[str, Any]) -> tuple[Any, ...]: + """Bridge local closed-mesh admission to the frozen generic evaluator.""" + _validate_mesh(mesh) + vertices = tuple(tuple(float(value) for value in point) + for point in mesh["vertices"]) + quads = tuple(tuple(int(index) for index in face) for face in mesh["quads"]) + uses = _edge_uses([tuple(face) for face in quads]) + loops = { + str(name): tuple(int(index) for index in loop) + for name, loop in _mapping(mesh["loops"], "mesh.loops").items() + } + stencils = tuple( + tuple((int(term[0]), float(term[1])) for term in stencil) + for stencil in mesh["base_stencils"] + ) + return ( + vertices, + quads, + tuple(mesh["face_owners"]), + tuple(mesh["control_owners"]), + loops, + stencils, + uses, + ) + + +def _load_closed_generic_transition() -> Any: + """Load the frozen subdivision code with only its loop admission bridged.""" + global _CLOSED_GENERIC_TRANSITION_CACHE + if _CLOSED_GENERIC_TRANSITION_CACHE is not None: + return _CLOSED_GENERIC_TRANSITION_CACHE + path = _GENERIC_TRANSITION_PATH.resolve() + path_digest = hashlib.sha256(str(path).encode("utf-8")).hexdigest()[:16] + owner = "".join(character if character.isalnum() else "_" + for character in __name__) + name = (f"_ck_connected_leg_closed_generic_{owner}_{path_digest}_" + f"{id(_closed_generic_validation):x}") + spec = importlib.util.spec_from_file_location( + name, path) + if spec is None or spec.loader is None: + _fail(f"unable to load closed-mesh generic evaluator: {path}") + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + module._validate_mesh = _closed_generic_validation + _CLOSED_GENERIC_TRANSITION_CACHE = module + return module + + +def build(root_mesh: Mapping[str, Any], leg_inputs: Mapping[str, Any]) -> dict[str, Any]: + """Append the bounded bilateral T/K/A chain to a saved calibrated L0 root.""" + root = _mapping(root_mesh, "root_mesh") + _validate_mesh(root) + vertices = [_vector(point, f"root_mesh.vertices[{index}]") + for index, point in enumerate(root["vertices"])] + root_quads = [tuple(face) for face in root["quads"]] + root_count = len(vertices) + root_face_count = len(root_quads) + root_loops = {str(name): list(loop) for name, loop in _mapping(root["loops"], "root_mesh.loops").items()} + frames = _mapping(root["frames"], "root_mesh.frames") + parsed = _parse_leg_inputs(leg_inputs) + + face_owners = list(root["face_owners"]) + control_owners = list(root["control_owners"]) + root_metadata = _mapping(root["metadata"], "root_mesh.metadata") + base_owners = list(root_metadata["base_control_owners"]) + output_vertices = copy.deepcopy(root["vertices"]) + output_quads = [list(face) for face in root_quads] + output_face_owners = list(face_owners) + output_control_owners = list(control_owners) + output_loops = {name: list(loop) for name, loop in root_loops.items() + if name not in _THIGH_PORTS.values()} + chain_metadata: dict[str, Any] = {} + mapping_metadata: dict[str, Any] = { + "root_vertex_old_to_new": [[index, index] for index in range(root_count)], + "root_face_old_to_new": [[index, index] for index in range(root_face_count)], + } + + for side in _SIDES: + row = parsed[side] + T, K, A = row["T"], row["K"], row["A"] + factor = row["mid_thigh_factor"] + support = row["support_fraction"] + root_frame = _mapping(frames.get(side), f"root_mesh.frames.{side}") + _close(T, _vector(root_frame.get("H"), f"root_mesh.frames.{side}.H"), + f"leg_inputs.{side}.T") + root_exit = _add(T, _scale(_sub(K, T), 0.45)) + _close(root_exit, _vector(root_frame.get("exit"), + f"root_mesh.frames.{side}.exit"), + f"computed {side} root exit") + loop = _root_loop(root, side, root_count) + centre = _scale(_add(*(vertices[index] for index in loop)), 1.0 / len(loop)) + _close(centre, root_exit, f"root {side} thigh exit centre") + signs = _root_edge_signs(root_quads, loop) + template, exit_radii = _root_template(vertices, loop, root_exit, + root_frame, side) + sections, incoming, outgoing = _section_centres(T, K, A, support) + knee_tangent = _normalise( + _add(incoming, outgoing), f"{side} knee bisector tangent") + tangents = (incoming, incoming, knee_tangent, outgoing, outgoing, + outgoing, outgoing) + section_radii = [] + section_frames = [] + previous_x = None + for section, tangent in zip(sections, tangents): + radii = _section_radii(exit_radii, row["radii"], factor, section) + frame = _ring_frame(tangent, previous_x, + f"{side}.{section['name']}") + previous_x = frame["X"] + section_radii.append(radii) + section_frames.append(frame) + + ring_indices: list[list[int]] = [] + new_vertex_indices: list[int] = [] + for section, radii, frame in zip(sections, section_radii, section_frames): + ring: list[int] = [] + for lateral, forward in template: + depth_radius = radii[1] if forward >= 0.0 else radii[2] + point = _add( + section["centre"], + _scale(frame["X"], lateral * radii[0]), + _scale(frame["F"], forward * depth_radius), + ) + index = len(output_vertices) + output_vertices.append(list(point)) + output_control_owners.append(_LEG_OWNERS[side]) + base_owners.append(_LEG_OWNERS[side]) + ring.append(index) + new_vertex_indices.append(index) + ring_indices.append(ring) + + source_rings = [loop, *ring_indices] + new_face_indices: list[int] = [] + for index, (source, target) in enumerate(zip(source_rings, source_rings[1:])): + for corner, source_left in enumerate(source): + source_right = source[(corner + 1) % len(source)] + target_left = target[corner] + target_right = target[(corner + 1) % len(target)] + if index == 0: + if signs == 1: + face = [source_right, source_left, target_left, target_right] + else: + face = [source_left, source_right, target_right, target_left] + elif signs == 1: + face = [source_right, source_left, target_left, target_right] + else: + face = [source_left, source_right, target_right, target_left] + new_face_indices.append(len(output_quads)) + output_quads.append(face) + output_face_owners.append(_LEG_OWNERS[side]) + + ankle_loop = ring_indices[-1] + output_loops[_ANKLE_PORTS[side]] = list(ankle_loop) + section_records = [] + for section_index, (section, radii, frame, ring) in enumerate( + zip(sections, section_radii, section_frames, ring_indices)): + section_records.append({ + "name": section["name"], + "path": section["path"], + "fraction": float(section["fraction"]), + "indices": list(ring), + "centre": list(section["centre"]), + "radii": list(radii), + "frame": {key: list(value) for key, value in frame.items()}, + "order": section_index, + }) + chain_metadata[side] = { + "owner": _LEG_OWNERS[side], + "pose_only_J": list(row["J"]), + "pose_only_J_usage": "recorded context; unused by rest construction", + "role_metadata": copy.deepcopy(row["role_metadata"]), + "mid_thigh_factor": factor, + "support_fraction": support, + "root_exit": list(loop), + "root_exit_centre": list(root_exit), + "root_exit_radii": list(exit_radii), + "root_edge_winding": signs, + "sections": section_records, + "ring_order": [section["name"] for section in section_records], + "ring_indices_by_name": { + section["name"]: list(section["indices"]) + for section in section_records + }, + "ankle_port": list(ankle_loop), + "new_vertex_indices": list(new_vertex_indices), + "new_face_indices": list(new_face_indices), + "incoming_tangent": list(incoming), + "outgoing_tangent": list(outgoing), + "knee_tangent": list(knee_tangent), + } + chain_metadata[side]["frames"] = { + "H": list(T), + "knee": list(K), + "ankle": list(A), + "length": _norm(_sub(K, T)), + "d": list(incoming), + "X": list(section_frames[0]["X"]), + "U": list(section_frames[0]["U"]), + "F": list(section_frames[0]["F"]), + "exit": list(root_exit), + } + mapping_metadata[f"{side}_new_vertices"] = list(new_vertex_indices) + mapping_metadata[f"{side}_new_faces"] = list(new_face_indices) + + metadata = { + "level": 0, + "admission_status": "accepted", + "admission_failures": [], + "base_control_owners": base_owners, + "base_vertex_count": len(base_owners), + "dominant_owner_label": ( + "display representative only; authoritative ownership is " + "base_control_owners plus full base_stencils" + ), + "root": { + "schema": root.get("schema"), + "level": root.get("level", 0), + "vertex_count": root_count, + "face_count": root_face_count, + "old_thigh_ports_closed": { + side: list(_root_loop(root, side, root_count)) for side in _SIDES + }, + }, + "index_mapping": mapping_metadata, + "chains": chain_metadata, + "scheme": { + "root_exit_fraction": 0.45, + "new_sections": [ + ".70(T-K)", "(1-support_fraction)(T-K)", "K", + "K+(1.2*support_fraction)(A-K)", + "K+.35(A-K)", "K+.72(A-K)", "A", + ], + "per_side_controls": ["mid_thigh_factor", "support_fraction"], + "pose_only_input": "J is recorded per side and does not reshape rest geometry", + "radius_order": ["lateral", "anterior", "posterior"], + "weld_rule": "reuse-root-exit-loop-no-duplicate-ring", + "terminal_rule": "open-ankle-port-no-foot-or-cap", + "frame_rule": "projected-plus-X-and-forward-X-cross-U", + "knee_tangent_rule": ( + "normalized-incoming-plus-outgoing-bisector-independent-of-" + "support_fraction" + ), + "evaluator": "read-only-generic-transition-catmull-clark-two-levels", + }, + } + output = { + "schema": "creature-kernel.connected-leg-assembly-mesh.v1", + "level": 0, + "vertices": output_vertices, + "quads": output_quads, + "face_owners": output_face_owners, + "control_owners": output_control_owners, + "loops": output_loops, + "base_stencils": _identity_stencils(len(output_vertices)), + "frames": { + side: copy.deepcopy(chain_metadata[side]["frames"]) + for side in _SIDES + }, + "metadata": metadata, + } + _validate_mesh(output) + return output + + +def evaluate(mesh: Mapping[str, Any], levels: int = 2) -> list[dict[str, Any]]: + """Evaluate the connected-leg mesh through zero, one, or two CC levels.""" + if type(levels) is not int or levels < 0 or levels > 2: + _fail("levels must be an integer between 0 and 2") + _validate_mesh(mesh) + current: Any = _jsonable(mesh) + result = [current] + loops = _mapping(mesh["loops"], "mesh.loops") + generic = (_load_closed_generic_transition() if not loops + else _load_generic_transition()) + for level in range(1, levels + 1): + current = generic._subdivide_once(current, level) + current = _jsonable(current) + _validate_mesh(current) + result.append(current) + return result + + +__all__ = ["ConstructionError", "build", "evaluate"] diff --git a/experiments/connected-leg-assembly/example-brief.md b/experiments/connected-leg-assembly/example-brief.md new file mode 100644 index 0000000..2cc8f5e --- /dev/null +++ b/experiments/connected-leg-assembly/example-brief.md @@ -0,0 +1,37 @@ +# Connected-leg assembly example brief + +Status: Short exploratory example brief; not a morphology contract, protocol, +execution input, or production promise. + +Provenance: Ben's approval relayed through the Overseer on 2026-09-06. + +Ben's direct feedback on the initial Baseline002 rest images on 2026-09-06 +was that they read too female for his preferred default. Human and +anthropomorphic examples should use a male/masculine-looking default. He +singled out the narrow waist with full hips and thighs, and the lateral chest +bulge; the chest bulge is an anatomical form defect, not merely gender +styling. This does not exclude female examples, assert a biologically +universal proportion rule, imply an adult context, or make a species claim. + +Ben approved two loose appearance references for the common exploratory +pipeline: + +- an ordinary human biped; +- a loose wolf-like humanoid biped with a simplified muzzle, upright ears, + tail, and a coarse digitigrade/paw-like lower limb. + +The species reference is for loose appearance only. It is not detailed anatomy, +taxonomy, fur, a production promise, or motivation for a separate branch. + +Both references use the common pipeline. A temporary shared plantigrade stage +may be used for connection and staging, but it must be labelled temporary and +must not redefine the anthropomorphic target. No per-case mesh fixes or +species-name geometry branches are permitted. + +This updates the example appraisal reference only, not current frozen inputs or +a formal product contract. The existing leg-motion/source-response baseline +and its no-retune, no-regeneration, no-protocol-change instruction remain +historical routing for that baseline. The subsequently authorized integrated +refinement is now active through explicit captured inputs, including the +masculine overall proportion balance and chest/shoulder-attachment defect; +this does not expand authority or change the Ben checkpoint. diff --git a/experiments/connected-leg-assembly/foot-attachment-inputs.json b/experiments/connected-leg-assembly/foot-attachment-inputs.json new file mode 100644 index 0000000..db7bd87 --- /dev/null +++ b/experiments/connected-leg-assembly/foot-attachment-inputs.json @@ -0,0 +1,25 @@ +{ + "schema": "creature-kernel.connected-leg-assembly-foot-attachment-inputs.v1", + "status": "FOOT-005-initial-candidate-frozen", + "bulk_source": { + "module": "foot_form_construction.py", + "input": "foot-form-inputs.json", + "callback_seam": "foot_form_construction.build.connector_builder" + }, + "connector": { + "ring_names": ["support_s0", "support_s1"], + "chord_fraction": 0.3333333333333333, + "edge_fraction": 0.5, + "incoming_fraction": 0.5, + "outside_fraction": 0.5, + "ray_fraction": 0.5, + "ray_origin_tolerance": 1e-09, + "orientation_tolerance": 1e-12 + }, + "budget": { + "initial_candidate_count": 1, + "shared_correction_max": 1, + "input_retuning": false, + "hole_rim_edits": false + } +} diff --git a/experiments/connected-leg-assembly/foot-form-inputs.json b/experiments/connected-leg-assembly/foot-form-inputs.json new file mode 100644 index 0000000..eaf3911 --- /dev/null +++ b/experiments/connected-leg-assembly/foot-form-inputs.json @@ -0,0 +1,79 @@ +{ + "schema": "creature-kernel.connected-leg-assembly-foot-form-inputs.v1", + "status": "FOOT-004-source-form-candidate-frozen-for-preflight", + "coordinate_convention": "local foot frame; origin actual leg A; X actual leg X; U projected global +Y; F=X cross U; radii are local-normal", + "source_semantics": { + "H": "rear heel surface-centre control", + "R": "ankle-body surface-centre control; not a joint", + "M": "forefoot-start surface-centre control", + "B": "forefoot-body surface-centre control", + "T": "terminal surface-centre control", + "reference_y": "contact-plane measurement only; no floor projection", + "x_local": "zero for every source centre; lateral placement comes from the actual frame" + }, + "budget": { + "initial_candidate_count": 1, + "shared_correction_max": 1, + "correction_condition": "only one evidence-justified shared construction correction after the initial candidate", + "input_retuning": false, + "alternative_constructions": false + }, + "cases": [ + { + "case_id": "calibrated_ordinary_human", + "construction": { + "midpoint_fraction": 0.5, + "rise_row_fractions": [0.25, 0.625], + "rise_width_exponent": 2.0, + "cross_section_rounding": 0.94, + "collar_fraction": 0.20 + }, + "sides": { + "left": { + "reference_y": -0.900, + "H": {"local_y": -0.045, "local_z": -0.055, "rL": 0.030, "rD": 0.030, "rP": 0.030}, + "R": {"local_y": -0.047, "local_z": 0.000, "rL": 0.032, "rD": 0.045, "rP": 0.028}, + "M": {"local_y": -0.045, "local_z": 0.075, "rL": 0.042, "rD": 0.034, "rP": 0.030}, + "B": {"local_y": -0.052, "local_z": 0.135, "rL": 0.052, "rD": 0.030, "rP": 0.025}, + "T": {"local_y": -0.057, "local_z": 0.210, "rL": 0.039, "rD": 0.020, "rP": 0.018} + }, + "right": { + "reference_y": -0.900, + "H": {"local_y": -0.045, "local_z": -0.055, "rL": 0.030, "rD": 0.030, "rP": 0.030}, + "R": {"local_y": -0.047, "local_z": 0.000, "rL": 0.032, "rD": 0.045, "rP": 0.028}, + "M": {"local_y": -0.045, "local_z": 0.075, "rL": 0.042, "rD": 0.034, "rP": 0.030}, + "B": {"local_y": -0.052, "local_z": 0.135, "rL": 0.052, "rD": 0.030, "rP": 0.025}, + "T": {"local_y": -0.057, "local_z": 0.210, "rL": 0.039, "rD": 0.020, "rP": 0.018} + } + } + }, + { + "case_id": "calibrated_upright_anthropomorphic", + "construction": { + "midpoint_fraction": 0.5, + "rise_row_fractions": [0.25, 0.625], + "rise_width_exponent": 2.0, + "cross_section_rounding": 0.94, + "collar_fraction": 0.20 + }, + "sides": { + "left": { + "reference_y": -0.880, + "H": {"local_y": -0.035, "local_z": -0.030, "rL": 0.027, "rD": 0.023, "rP": 0.025}, + "R": {"local_y": -0.040, "local_z": 0.0125, "rL": 0.026, "rD": 0.035, "rP": 0.026}, + "M": {"local_y": -0.207, "local_z": 0.130, "rL": 0.045, "rD": 0.030, "rP": 0.028}, + "B": {"local_y": -0.207, "local_z": 0.185, "rL": 0.057, "rD": 0.034, "rP": 0.028}, + "T": {"local_y": -0.213, "local_z": 0.260, "rL": 0.043, "rD": 0.022, "rP": 0.020} + }, + "right": { + "reference_y": -0.880, + "H": {"local_y": -0.035, "local_z": -0.030, "rL": 0.027, "rD": 0.023, "rP": 0.025}, + "R": {"local_y": -0.040, "local_z": 0.0125, "rL": 0.026, "rD": 0.035, "rP": 0.026}, + "M": {"local_y": -0.207, "local_z": 0.130, "rL": 0.045, "rD": 0.030, "rP": 0.028}, + "B": {"local_y": -0.207, "local_z": 0.185, "rL": 0.057, "rD": 0.034, "rP": 0.028}, + "T": {"local_y": -0.213, "local_z": 0.260, "rL": 0.043, "rD": 0.022, "rP": 0.020} + } + } + } + ] +} diff --git a/experiments/connected-leg-assembly/foot-inputs.json b/experiments/connected-leg-assembly/foot-inputs.json new file mode 100644 index 0000000..efe0be2 --- /dev/null +++ b/experiments/connected-leg-assembly/foot-inputs.json @@ -0,0 +1,57 @@ +{ + "schema": "creature-kernel.connected-leg-assembly-foot-inputs.v1", + "status": "candidate-inputs-frozen", + "coordinate_convention": "metres; global X lateral, +Y up, +Z front", + "source_semantics": { + "H": "heel source anchor behind the ankle entry", + "B": "ball/metatarsal source anchor ahead of the ankle entry", + "T": "forefoot/toe source anchor ahead of the ball", + "lateral_center": "leg_inputs[side].A[0]; not an authored foot x coordinate" + }, + "budget": { + "initial_candidate_count": 1, + "shared_correction_max": 1, + "correction_condition": "only an evidence-justified shared correction after the initial candidate", + "per_case_corrections": false, + "input_retuning": false, + "alternative_constructions": false + }, + "cases": [ + { + "case_id": "calibrated_ordinary_human", + "sides": { + "left": { + "H": {"z": -0.060, "plantar_y": -0.900, "halfwidth": 0.032, "dorsalthickness": 0.040}, + "B": {"z": 0.120, "plantar_y": -0.900, "halfwidth": 0.050, "dorsalthickness": 0.040}, + "T": {"z": 0.190, "plantar_y": -0.900, "halfwidth": 0.043, "dorsalthickness": 0.028}, + "collar_fraction": 0.20 + }, + "right": { + "H": {"z": -0.060, "plantar_y": -0.900, "halfwidth": 0.032, "dorsalthickness": 0.040}, + "B": {"z": 0.120, "plantar_y": -0.900, "halfwidth": 0.050, "dorsalthickness": 0.040}, + "T": {"z": 0.190, "plantar_y": -0.900, "halfwidth": 0.043, "dorsalthickness": 0.028}, + "collar_fraction": 0.20 + } + }, + "status_note": "bounded coarse staging hypothesis; not anthropometry" + }, + { + "case_id": "calibrated_upright_anthropomorphic", + "sides": { + "left": { + "H": {"z": -0.120, "plantar_y": -0.705, "halfwidth": 0.030, "dorsalthickness": 0.030}, + "B": {"z": 0.060, "plantar_y": -0.880, "halfwidth": 0.060, "dorsalthickness": 0.045}, + "T": {"z": 0.130, "plantar_y": -0.880, "halfwidth": 0.055, "dorsalthickness": 0.028}, + "collar_fraction": 0.20 + }, + "right": { + "H": {"z": -0.120, "plantar_y": -0.705, "halfwidth": 0.030, "dorsalthickness": 0.030}, + "B": {"z": 0.060, "plantar_y": -0.880, "halfwidth": 0.060, "dorsalthickness": 0.045}, + "T": {"z": 0.130, "plantar_y": -0.880, "halfwidth": 0.055, "dorsalthickness": 0.028}, + "collar_fraction": 0.20 + } + }, + "status_note": "bounded coarse staging hypothesis; heel raised relative to common ball/toe plane; not anthropometry" + } + ] +} diff --git a/experiments/connected-leg-assembly/foot-junction-policy.json b/experiments/connected-leg-assembly/foot-junction-policy.json new file mode 100644 index 0000000..fa621fd --- /dev/null +++ b/experiments/connected-leg-assembly/foot-junction-policy.json @@ -0,0 +1,55 @@ +{ + "schema": "creature-kernel.connected-leg-assembly-foot-junction-policy.v1", + "candidate": "JUNCTION-001", + "status": "prospective-static-only", + "source": { + "bulk_origin": "FOOT-004", + "pure_helpers": [ + "foot_form_construction._source_frame", + "foot_form_construction._grid_points" + ], + "forbidden_builders": [ + "foot_form_construction.build", + "foot_attachment_construction.build" + ] + }, + "graph": { + "local_vertex_count": 79, + "body_quad_count": 74, + "row_names": [ + "rear_heel", + "heel_ankle_midpoint", + "ankle_body", + "ankle_body_quarter", + "ankle_body_five_eighths", + "forefoot_start", + "forefoot_body", + "terminal" + ], + "columns": 5, + "frontier_row": 5, + "frontier_source": "M", + "hole_positions": [[1, 1], [2, 1], [3, 1], [3, 2], [3, 3], [2, 3], [1, 3], [1, 2]], + "omitted_position": [2, 2] + }, + "constraints": { + "basis_order": ["X", "U", "F"], + "edge_weight": "uniform_quad_edge", + "fixed_rows": [0, 5, 6, 7], + "plantar_u_rows": [1, 2, 3, 4], + "solver": "coordinatewise_dirichlet_harmonic_no_regularizer", + "residual_tolerance": 1.0e-10 + }, + "output": { + "omit_old_hole_vertices": true, + "use_existing_actual_A_indices": true, + "connector_rings": false, + "post_l2_correction": false + }, + "budget": { + "initial_candidate_count": 1, + "shared_correction_max": 1, + "parameter_search": false, + "input_retuning": false + } +} diff --git a/experiments/connected-leg-assembly/foot-junction-stage.md b/experiments/connected-leg-assembly/foot-junction-stage.md new file mode 100644 index 0000000..fa471bc --- /dev/null +++ b/experiments/connected-leg-assembly/foot-junction-stage.md @@ -0,0 +1,30 @@ +# JUNCTION-001 prospective implementation note + +Status: implementation prepared, static/AST review only; no candidate geometry, +L2 evaluation, collision result, render, or anatomy acceptance is claimed. + +JUNCTION-001 couples the existing ankle-port section and frame to the FOOT-004 +bulk grid through one local displacement solve. The source graph is the +existing 79-vertex, 74-quad grid: the eight old dorsal-hole vertices receive +`actual A - old H` Dirichlet displacement, row 0 and rows 5–7 are fixed, and +plantar rows 1–4 hold local foot-rest `U` displacement at zero while their +`X/F` components remain harmonic unknowns. Row 5 is the settled `M` frontier. +The solve uses uniform quad-edge weights independently for `X`, `U`, and `F`, +with no regularizer, parameter search, or fallback. + +The implementation reuses only FOOT-004's pure `_source_frame` and +`_grid_points` helpers. It omits the eight old hole vertices and writes the +existing ankle-port `A` indices directly into the surrounding faces. No +collar/support ring, ankle joint, source retune, or post-L2 correction is +introduced. Incoming leg controls and the actual `A` ownership, coordinates, +and stencils remain inherited. + +The explicit policy is in +[`foot-junction-policy.json`](foot-junction-policy.json), and the implementation +is in [`foot_junction_construction.py`](foot_junction_construction.py). Focused +tests are execution-owned by Raman and are intentionally not run in this +pre-capture handoff. They cover graph solvability, direct-mouth welding, +prefix/distal invariants, mirrored/source response, and local fold diagnostics; +full L2 stencil, thickness, intersection, and visual checks remain downstream +capture gates. If the coupled human/anthropomorphic batch fails, the result +returns to the Overseer before any successor. diff --git a/experiments/connected-leg-assembly/foot-stage.md b/experiments/connected-leg-assembly/foot-stage.md new file mode 100644 index 0000000..ea705f4 --- /dev/null +++ b/experiments/connected-leg-assembly/foot-stage.md @@ -0,0 +1,514 @@ +# Connected-leg foot stage + +Status: FOOT-001 static mechanical success; anthro flipper rejected at L2; +shared refinement authorized; internal prerequisite only + +This bounded stage adds one common coarse foot construction to the existing +expanded leg L0. It is not final anatomy, a species contract, a general rig, +or the named Ben checkpoint. The current 005 capture and its immutable root +sources are outside this stage and must not be edited. + +## Frozen original candidate and budget + +The finite budget for the original candidate was recorded before any foot +geometry execution: + +- Initial candidates: exactly 1. +- Shared construction correction: at most 1, only if the initial evidence + identifies a shared defect and the correction is justified by that evidence. +- Per-case repair, input retuning, alternate construction, repeated review + cycles, and budget carry-over are forbidden. + +The initial candidate is a connected 3x3-perimeter cage using this semantic +order for its dorsal and plantar perimeter: + +```text +D0 heel-left, D1 ball-left, D2 toe-left, D3 toe-centre, +D4 toe-right, D5 ball-right, D6 heel-right, D7 heel-centre +``` + +The existing ordered eight-vertex ankle loop `A` is reused. The candidate +creates `C = lerp(A, D, collar_fraction)` with `collar_fraction = 0.20`, then +connects `A -> C -> D -> P` with eight quad bands per transition. `P0..P7` +reuse the footprint outline and `P8` is the ball-centre. The plantar cap uses +these semantic quad groups, reversing all face winding when required by the +attached ankle-loop orientation: + +```text +P0 P1 P8 P7 +P1 P2 P3 P8 +P8 P3 P4 P5 +P7 P8 P5 P6 +``` + +The attached ankle loop's actual cyclic phase and winding are resolved from +its source ankle frame and projected positions. `A0..A7` are never assumed to +mean `D0..D7`. The chosen phase, direction, projected score, frame, source +anchors, ring indices, cap indices, and face-owner ranges are retained in +metadata. + +## Inputs and common construction + +`foot-inputs.json` contains only the two existing connected-leg cases and +mirrored left/right controls. The foot centreline is not given an authored x: +each side uses `leg_inputs[side].A[0]`. `A` remains the ankle endpoint, not the +heel. The generic source anchors are `H`, `B`, and `T`; the simple footprint +requires `H.z < A.z < B.z < T.z`, and ball width must exceed the measured +ankle-loop lateral half-width. Human-like and raised-heel contrasts are values +of these generic controls, not code branches or species names. + +The output preserves the expanded-leg vertices and faces as exact prefixes, +removes only the two ankle boundary declarations, and leaves the neck and two +arm ports as the only boundaries. The new foot is closed by the plantar cap. +No weights are introduced here; later foot vertices inherit corresponding +shank influence and this stage makes no ankle-articulation claim. + +The evaluator delegates to the current generic Catmull--Clark evaluator for +zero, one, or two levels. It is not changed or copied. The old ankle loop is +expected to become interior and move under subdivision. + +## Rejection gates and limitations + +The construction rejects non-finite or malformed inputs, invalid source +relationships, phase ambiguity, folded collar quads, footprint or 3D +self-intersection, degenerate faces, non-manifold or disconnected output, +prefix/topology regression, and any failure to close the ankle boundary. The +former bespoke 3D triangle/AABB check was limited: it could miss a second +triangle and skip the shared one. It has been replaced by the stronger frozen +intersection checker; the replacement is checker-only and does not authorize +or apply any geometry correction. Projected nesting alone is not accepted as +proof of separation. + +Direct visual rejection remains required for a future bounded appraisal: +cuff fold, self-intersection, disconnected foot, erased heel or paw mass, +rigid-shoe-like bulb, or limb regression. No full collision, pose, render, +contact, ground-pin, gait, or final-anatomy claim is made here. + +## Initial evidence command + +The bounded managed-runtime command is: + +```bash +PYTHONDONTWRITEBYTECODE=1 CK_CURRENT_FORM_SURFACE_PYTHON=/home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot/runtime/bin/python bash /home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot/source/experiments/current-form-surface-preview/surface_preview_launcher.sh -m unittest discover -s experiments/connected-leg-assembly/tests -p test_foot_construction.py -v +``` + +The tests include the fresh two-case L0 construction/evaluation for counts, +manifold closure, winding, correspondence, and meaningful source anchors. +They do not run a body capture or pose/collision protocol. + +## Initial candidate evidence + +The initial candidate was executed once for each canonical existing case in +memory. Both produced a 314-vertex/304-quad connected L0 with 25 new vertices +and 28 new faces per side, then passed delegated zero-, one-, and two-level +generic Catmull--Clark evaluation. The managed test command completed with 9 +tests passed and no failures or errors. + +The tests also exercised a cyclic phase shift and a reversed attached ankle +loop, confirming that correspondence and output winding are derived from the +actual source loop rather than an `A0..A7` assumption. This is implementation +evidence for the bounded candidate only; no pose, render, full collision, or +anatomy acceptance was run. The remaining risks are the angled-ankle 3D fold +and intersection envelope under future visual inspection, and whether the +coarse closed cage reads as a heel/forefoot rather than a rigid shoe-like +bulb. + +## FOOT-001 appraisal and next bounded refinement + +FOOT-001 achieved static mechanical success. Main's direct L2 visual appraisal +rejected the anthropomorphic flipper; the human coarse wedge was adequate for +this narrow stage. Neither is polished anatomy acceptance. The original shared +winding correction remains consumed and the remaining geometry budget is `0`. + +The Overseer separately authorized one shared forefoot-support refinement with +fixed H/B/T positions, widths, thicknesses, collar, and legs; it may alter only +local foot-support topology or interpolation. The budget is one candidate and +at most one evidence-justified shared adjustment. Its narrow goal is a raised +transition into a low, broad, finite-thickness forefoot while retaining the +elevated heel. No detailed toes, species branch, or input retune is authorized. +Linnaeus is diagnosing the actual sections before a concrete hypothesis. + +## Correction ledger and provenance + +The initial candidate's first managed test invocation failed during +`setUpClass`, before any test body ran. The original tool output is preserved +verbatim: + +```text +ERROR + +====================================================================== +ERROR: setUpClass (test_foot_construction.FootConstructionTests) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/home/ben/src/creature-kernel-worktrees/owned-root-assembly-successor/experiments/connected-leg-assembly/foot_construction.py", line 795, in build + _validate_output(output, base_mesh, base_vertex_count, base_face_count, + File "/home/ben/src/creature-kernel-worktrees/owned-root-assembly-successor/experiments/connected-leg-assembly/foot_construction.py", line 626, in _validate_output + _validate_topology(vertices, quads, loops, "output") + File "/home/ben/src/creature-kernel-worktrees/owned-root-assembly-successor/experiments/connected-leg-assembly/foot_construction.py", line 169, in _validate_topology + _fail(f"{where} has an orientation conflict") + File "/home/ben/src/creature-kernel-worktrees/owned-root-assembly-successor/experiments/connected-leg-assembly/foot_construction.py", line 40, in _fail + raise FootConstructionError(message) +foot_construction.FootConstructionError: output has an orientation conflict + +---------------------------------------------------------------------- +Ran 0 tests in 0.011s + +FAILED (errors=1) +``` + +The measured cause was the shared perimeter orientation between the D-to-P +band and the plantar cap. The one shared correction reversed all four +plantar-cap face windings for output orientation `+1`, while retaining the +semantic cap groups; the inverse rule remains used for reverse output +orientation. The known source delta was: + +```diff +-return faces if orientation == 1 else [tuple(reversed(face)) for face in faces] ++# The D->P band uses the P perimeter in ``orientation`` direction. The ++# closed plantar faces must use the opposite direction on every shared ++# perimeter edge; the semantic face grouping remains unchanged. ++return [tuple(reversed(face)) for face in faces] if orientation == 1 else faces +``` + +The original candidate's shared geometry-correction budget is consumed: +remaining budget `0`. No further correction to that original candidate, input +retuning, or candidate substitution is authorized; this does not limit the +separately authorized shared forefoot-support refinement above. A later +evaluator-only integration fix added +`metadata["base_vertex_count"] = len(base_control_owners)` after appending +the foot owners; it changed metadata integration only, not geometry, source +points, face grouping, coordinates, or the candidate budget. + +The initial pre-correction source was not immutably captured or separately +hashed. No initial-candidate provenance is inferred from the final source +identity. + +## Checker status and evidence boundary + +Cicero's checker-only replacement is complete. The managed validator result +was 11 tests passed, including the exact regressions +`test_frozen_core_catches_second_triangle_only_hit` and +`test_frozen_core_catches_one_shared_vertex_hit`. Exact pre/post geometry +comparison passed for both canonical cases, and complete frozen-core checking +passed for the 608-triangle L0. + +The prepatch source and baseline meshes are preserved at +`/home/ben/.cache/connected-leg-foot-prepatch.1knSpc/foot_construction.py`. +The two regressions above are the recorded reason the former bespoke checker +was replaced; they do not represent geometry changes. + +Sol's actual static foot-plus-leg check covered 2,688 triangles and +3,611,328 triangle pairs, with zero reported intersections. This supports a +static capture only; it is not a full-body pass and is not immutable-capture +evidence. The stronger checker is ready for Raman's static capture; no foot +render is authorized until that capture provides a new snapshot. + +The geometry candidate is unchanged and the correction budget remains zero: +this update changed only this stage record, with no construction, input, test, +capture, render, or geometry run. The unchanged candidate-file identities are: + +```text +5bb0c361e006818027ac5ff5dfe0eec713b6969ecb4ba9de809670490a3418c0 foot_construction.py +6e2d3ee26f28f80388c9ad0d4a8edef1cfbd28b5f90cc07228c295ad2c6a5dd0 foot-inputs.json +493101df145fdd1fc05d803a104b52f8e722b1fd76e4e3734b9064aabbefe6ab tests/test_foot_construction.py +``` + +## FOOT-002 initial shared support candidate + +This is a new, pre-execution candidate. FOOT-001 remains rejected and its +geometry-correction budget remains exhausted; this candidate has exactly one +initial execution allowance and at most one later shared, +evidence-justified adjustment. No adjustment has been spent. + +The fixed H/B/T positions, widths, thicknesses, collar fraction, leg inputs, +A/C/D/P points, and existing D-to-P band are unchanged. For each side, the +new full proximal support ring is: + +```text +R_i = lerp(C_i, D_i, 0.75), i=0..7, for x and z +R_i.y = source_dorsal_y(R_i.z) +``` + +`source_dorsal_y` is the piecewise-linear profile through +`H.plantar_y + H.dorsalthickness`, `B.plantar_y + B.dorsalthickness`, and +`T.plantar_y + T.dorsalthickness`. Any `R.z` outside the strict H..T range is +rejected; it is never clamped. The C-to-D band is replaced by matched C-to-R +and R-to-D eight-quad bands. + +The plantar support uses the existing P8 point as its centre, without a +duplicate vertex. Its closed eight-vertex loop is: + +```text +S_i = lerp(P_i, P8, beta_i) +beta = [.75, .20, .20, .20, .20, .20, .75, .75] +``` + +The unchanged P0..P7 perimeter connects to S0..S7 with eight annulus quads; +the inner loop closes with `S0S1P8S7`, `S1S2S3P8`, `P8S3S4S5`, and +`S7P8S5S6`, using the existing orientation rule. Every P edge and every S +edge has complete matching ownership; no perimeter edge is split. + +The construction hypothesis is a readable low, broad, finite-thickness +forefoot with the elevated heel retained and the H-to-B rise narrowed by the +near-B rear S supports and the source-profiled R ring. The initial evidence +must measure the same exact triangle-plane sections at `z=B.z` and +`z=(H.z+B.z)/2`, reporting plantar height, dorsal height, thickness, and +halfwidth against source interpolation. This is a response measurement, not +an exact-control interpolation claim. + +Acceptance/rejection criteria are: readable low broad finite-thickness +forefoot after a narrow raised transition; readable human foot; elevated heel +retained; and no cuff ridge, folds, tears, flipper, disconnected topology, or +limb regression. The initial result and images should be returned even if +rejected when the existing capture adapter can produce them. The second shape +adjustment is reserved for Main after initial surface and section inspection. + +The following are separately labelled source-response counterfactuals, not +input retuning: compare the actual L2 B section after a temporary +10% B +halfwidth perturbation, and after a temporary +0.01 m heel plantar-height +perturbation. Canonical inputs and the candidate remain unchanged by those +diagnostics. + +Pre-execution identities were recorded before the initial geometry run: + +```text +foot_construction.py db045ca40af84b7d9dd1402ef7c6ae2de7429ebb1987e2ab4a4b1a55230ed511 +foot-inputs.json 6e2d3ee26f28f80388c9ad0d4a8edef1cfbd28b5f90cc07228c295ad2c6a5dd0 +inputs.json 1fbd9448bcef2861fc61623b497e67bd2e84a1106818dcac9d84dcf04bd60bda +construction.py 199672cfb8b57d49842d63b7c1043a0a85b1129eb742dd4b0d8016f52b6b765b +foot_trial.py 94a7b1e8aaac6f659fea9bb04013ec9b741f83ecca4752334abd3aa55f4eeedc +frozen checker 4104b70e70e958a469125d1fff544e20fee44b784bf7915d8e724e63d4f39db1 +runtime requirements 69a3ce10b1f993d7913f02ca187eabb8d367abf214662ffa2132feacbdeedbec +runtime Python 3.10.12 +``` + +The existing `foot_trial.py` adapter remains Raman-owned and will be used only +after a source snapshot containing this candidate is ready. No capture or +render is started by this subsection. + +### Initial execution result + +The initial candidate was run with the managed test command above. It was +rejected at L0 validation on the first canonical case, before any test body, +L2 evaluation, source snapshot, capture, or render. The exact tool output was: + +```text +ERROR + +====================================================================== +ERROR: setUpClass (test_foot_construction.FootConstructionTests) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/home/ben/src/creature-kernel-worktrees/owned-root-assembly-successor/experiments/connected-leg-assembly/tests/test_foot_construction.py", line 72, in setUpClass + output = foot_construction.build(base, leg_inputs, foot_inputs) + File "/home/ben/src/creature-kernel-worktrees/owned-root-assembly-successor/experiments/connected-leg-assembly/foot_construction.py", line 916, in build + _validate_output(output, base_mesh, base_vertex_count, base_face_count, + File "/home/ben/src/creature-kernel-worktrees/owned-root-assembly-successor/experiments/connected-leg-assembly/foot_construction.py", line 705, in _validate_output + _validate_new_faces(vertices, quads, indices, side) + File "/home/ben/src/creature-kernel-worktrees/owned-root-assembly-successor/experiments/connected-leg-assembly/foot_construction.py", line 596, in _validate_new_faces + _fail(f"{side} foot quad {face_index} has a cuff fold") + File "/home/ben/src/creature-kernel-worktrees/owned-root-assembly-successor/experiments/connected-leg-assembly/foot_construction.py", line 52, in _fail + raise FootConstructionError(message) +foot_construction.FootConstructionError: left foot quad 268 has a cuff fold + +---------------------------------------------------------------------- +Ran 0 tests in 4.576s + +ERROR (errors=1) +``` + +Face 268 is the fifth semantic face of the left R-to-D band. This is an +initial-candidate rejection, not evidence for an input retune. The reserved +shared adjustment remains unused; no geometry bypass, counterfactual, +capture, render, or second shape adjustment was run. + +### FOOT-002 adjusted candidate ledger + +The single authorized R1..R5 forward-support adjustment was pre-captured at +`/home/ben/.cache/connected-leg-assembly-FOOT-002-adjusted-snapshot` and +executed once by this task through the static adapter, producing +`/home/ben/.cache/connected-leg-assembly-FOOT-002-adjusted-run` with exit 0. +Both canonical constructions completed. Focused tests, counterfactuals, +integrated poses, and other checks remain unrun; exit 0 is not acceptance. + +The adjustment budget is now 0 and closed. Main and Overseer rejected this +candidate after reviewing the existing adjusted run and section evidence: +the human remains readable, while the anthropomorphic case is a flipper. The +focused tests, counterfactuals, integrated poses, and other checks remain +unrun; exit 0 is not acceptance. The initial fold failure and its prior +unused-budget record above remain historical candidate state. No trial restart +or further correction is authorized for FOOT-002. + +### FOOT-003 longitudinal-grid implementation record + +Hypothesis/layout: use one shared closed longitudinal dorsal/plantar grid per +side with rows H, midpoint(H,A.z), A.z, A.z+0.25(B.z-A.z), +A.z+0.625(B.z-A.z), B, midpoint(B,T), T and lateral fractions +[-1,-.65,0,.65,1]. The H-to-B half-width uses the declared u^2 +interpolation; B-to-T is linear. The dorsal surface omits only the four +central quads around the unused centre at A, leaving an eight-vertex ankle +hole. The grid closes its two side strips and heel/toe end strips (22 outer +perimeter quads), then attaches the actual ankle loop through the unchanged +collar_fraction=.20 with two eight-quad bands. + +Source roles remain explicit: H and B/T are fixed source controls, A supplies +ankle-z attachment context, and derived row fractions are construction +hypotheses rather than anatomy. The implementation preserves the L0 prefix, +retained neck/arm ports, and explicit per-side new vertex/face indices, +source anchors, attachment loop, phase, and winding metadata. Inputs are +unchanged; FOOT-001 and FOOT-002 snapshots and reports are preserved. + +Single-review outcome: the requested FOOT-003 preflight approved this layout +for implementation. Risks retained for execution review are tilted-ankle +phase/winding and collar-band folds, dorsal-hole degeneracy, source-profile +height/width response, heel/body collision, and whether the fixed coarse +controls read as a low broad forefoot in both cases. Generic evaluation, +validation, and the frozen collision component are reused; this record makes +no acceptance claim. + +### FOOT-003 first-candidate status + +The first FOOT-003 candidate mechanically built and its focused tests passed. +Main personally inspected the saved result: the anthropomorphic foot remains a +thin, sloping flipper and is not accepted. One shared correction remains +unused; read-only diagnosis is underway. No trial restart or anatomy +acceptance is claimed, and frozen evidence remains unchanged. + +Budget: one initial candidate plus at most one shared correction; this is the +initial candidate and zero corrections have been spent. Raman remains the +sole capture/test/execution owner; the first candidate's saved evidence is +preserved. No trial restart, further correction, or anatomy acceptance is +claimed. + +### FOOT-003 disposition + +Main closes FOOT-003 rejected without using its optional shared correction; the +correction is waived, not exhausted, and no FOOT-004 is authorized. Fourteen +focused/static construction checks passed mechanically. Direct vision found an +anthropomorphic flipper and a human flat shoe. Full collisions, source +counterfactuals, and poses remain unrun. The saved FOOT-003 evidence is +preserved at its existing recorded paths. + +The source-faithful B-to-T interpolation does not establish anatomy. The +linear transverse slab, fixed steep H-to-B profile, and local ankle lift +explain the observed limitations, but do not prove that every fixed topology +is impossible. Luna's invented 5 mm hypothetical is not an acceptance gate. +The next foot source/form clarification is proposed to Overseer and remains +pending. + +### FOOT-004 source/form candidate implementation record + +Status: a fresh single Sol preflight approved this bounded implementation; +FOOT-003 remains historical and untouched. This candidate adds +`foot_form_construction.py`, `foot-form-inputs.json`, and focused tests without +editing `foot_construction.py` or `foot-inputs.json`. + +Hypothesis: retain the FOOT-003 eight-row, five-lateral grid, four-cell dorsal +hole, two eight-quad attachment bands, and 22-quad outer closure, but replace +the slab source with five local centre controls H/R/M/B/T and local-normal +radii rL/rD/rP. R is an ankle-body surface centre, not a joint; actual A and +the actual ankle attachment frame remain the attachment source. Centres are +piecewise linear, R-to-M width uses the fixed u^2 rise rule, rD/rP are linear, +and each section uses the settled `.94` rounded transverse profile. Reference +Y values are contact-plane measurements only; no floor projection is applied. + +Input differences and roles are prospective coarse artistic/engineering +calibration, not factual wolf anatomy: the human controls use a near-level +H/R/M/B/T centre path with a modest forefoot; the anthropomorphic controls use +the separately authored raised-heel-to-low-forefoot centre path and radii. +Both sides use the same values in their actual source frames; there are no +species branches. All controls, row derivations, frame axes, and radius +semantics are emitted in per-side metadata. + +Risks and rejection criteria: slab/flipper, heel spur, collar flare or fold, +disconnected/intersecting limb, and an unreadable low paw or human foot. The +planned source-response measurements are fixed semantic L2 B rL +10%, R/M +selected normal-radius +10%, and T forward extent; these are labelled +counterfactual diagnostics, not input retuning. If promising, Raman may later +run full collision and modest body poses; neither is part of this candidate +implementation. + +Budget: one initial construction candidate plus at most one shared construction +correction; zero corrections are spent and no input retuning is allowed after +freeze. The public API is +`build(base_mesh, leg_inputs, foot_form_case)` where the case is one exact row +from `foot-form-inputs.json` containing `case_id`, `construction`, and +`sides`; `evaluate(mesh, levels=0..2)` delegates to the existing generic +evaluator. The new module reuses FOOT-003 validation, topology, collision, +phase/winding, collar, and evaluation helpers; no shared-core extraction was +needed. Raman is the sole executor and must capture source/dependency/input +identities before the first build. All tests and checks remain UNRUN. + +#### FOOT-004 initial execution failure and settled correction + +The initial captured execution is preserved at +`/home/ben/.cache/connected-foot-static-004-snapshot`. Its `setUpClass` +failed before any foot candidate was constructed, at `_source_frame`, because +the implementation treated `base_mesh.frames..X` as the terminal ankle +section axis. In the actual construction output that field is the leg-summary +frame from the thigh/shank chain; it is not required to equal the validated +ankle attachment frame. + +The single shared correction is settled: `_source_frame` now takes `X` only +from `_ankle_chain`'s validated `attachment_frame["X"]`, while retaining the +actual A origin, projected global +Y `U`, `F = X cross U` consistency checks, +all fixed FOOT-004 inputs, topology, collar, and formulas. The base mesh leg +summary frame remains unchanged metadata and is not relabelled. A focused +mocked-frame regression covers differing summary and attachment axes. + +This is FOOT-004's one permitted shared construction correction. Remaining +correction budget: 0. No geometry build, geometry test, capture trial, or +diagnostic was run after the correction; Raman must capture the corrected +source/dependency/input identities before execution. All broader checks remain +UNRUN. + +### FOOT-005 attachment-only initial candidate record + +Status: Main selected this single bounded attachment candidate after the +FOOT-004 closure. This record is prospective until Raman captures the exact +source, dependency, and input identities and gives execution approval. The +frozen FOOT-004 source, inputs, source controls, ankle ring, dorsal hole, leg +binding, and all historical reports remain unchanged. The live +`foot_form_construction.py` module now includes only the explicit connector +seam; its default path retains the FOOT-004 collar arithmetic. + +The candidate adds `foot_attachment_construction.py` and +`foot-attachment-inputs.json`. It uses the explicit `connector_builder` seam +in `foot_form_construction.build`; omitting the callback retains the original +FOOT-004 collar arithmetic and default behavior. The new callback is invoked +before the shared output validator, so the known old anthro cuff is not +constructed or globally bypassed. Bulk grid arithmetic remains solely owned by +`foot_form_construction.py`. + +The authored implicit-versus-explicit default-callback test verifies live seam +routing only; it is not historical FOOT-004 equivalence evidence. Raman must +compare the frozen FOOT-004 default output for the human case and, if needed, +reproduce the frozen default anthropomorphic failure/raw geometry before any +claim about historical output or metadata equivalence. + +For each fixed corresponding A/H sector, the connector computes +`S0=A+l0*d_in` and `S1=H-l1*c_out`. `d_in` is the normalized matching +ankle-approach-to-A meridian. The hole boundary tangent is normalized +`Hnext-Hprev`; `n_area` is the consistently wound area-weighted sum of retained +incident foot quads. `c_out=normalize(n_area cross tangent)` is sign-selected +by the projected outside-neighbour centroid; zero or ambiguous orientation +fails. Each length is the settled minimum of chord/3, the half adjacent A/H +edge cap, its respective neighbour cap, and an optional half first-positive +retained-body ray hit. Ray `t` at or below the recorded origin tolerance is +ignored; there is no iterative direction or length search. + +The connector has only A→S0, S0→S1, and S1→H eight-quad bands, no caps, and +does not alter source stencils or binding. Chord/conormal/adjacent-direction +dots are recorded diagnostics, not mandatory positive gates. Existing quad +fold threshold and shared topology/winding/degeneracy validation remain gates. +The new module's local ring check currently rejects only zero-length support +edges; ring nonselfintersection and connector-versus-retained-body +intersection remain independently checked execution gates, not claims of full +coverage by the implementation. Later L2 surface checks also remain gates. +Undefined room or orientation fails without a workaround. + +Budget: one initial candidate plus at most one evidence-justified shared +correction; zero corrections are spent and no input retuning or initial hole +rim edits are permitted. Tests are authored but remain UNRUN. Raman is the +sole execution owner and must snapshot before any geometry test or build. diff --git a/experiments/connected-leg-assembly/foot_attachment_construction.py b/experiments/connected-leg-assembly/foot_attachment_construction.py new file mode 100644 index 0000000..1b52a22 --- /dev/null +++ b/experiments/connected-leg-assembly/foot_attachment_construction.py @@ -0,0 +1,402 @@ +"""FOOT-005 attachment-only connector over the frozen FOOT-004 bulk producer. + +The bulk source, grid arithmetic, source controls, phase, and winding come +from ``foot_form_construction``. This module owns only the two support rings +between the existing ankle ring and existing dorsal hole. +""" +from __future__ import annotations + +from collections.abc import Mapping +import copy +import math +from typing import Any + +import foot_construction as _shared +import foot_form_construction as _bulk + + +_SIDES = ("left", "right") +_RING_NAMES = ("support_s0", "support_s1") +_SECTOR_COUNT = 8 +_COORDINATE_TOLERANCE = 1.0e-10 +_AREA_TOLERANCE = 1.0e-12 + + +AttachmentConstructionError = _shared.FootConstructionError + + +def _fail(message: str) -> None: + raise AttachmentConstructionError(message) + + +def _mapping(value: Any, where: str) -> Mapping[str, Any]: + return _shared._mapping(value, where) + + +def _finite(value: Any, where: str) -> float: + return _shared._finite(value, where) + + +def _add(left: tuple[float, float, float], right: tuple[float, float, float]) -> tuple[float, float, float]: + return tuple(left[index] + right[index] for index in range(3)) # type: ignore[return-value] + + +def _sub(left: tuple[float, float, float], right: tuple[float, float, float]) -> tuple[float, float, float]: + return tuple(left[index] - right[index] for index in range(3)) # type: ignore[return-value] + + +def _scale(value: tuple[float, float, float], factor: float) -> tuple[float, float, float]: + return tuple(factor * item for item in value) # type: ignore[return-value] + + +def _dot(left: tuple[float, float, float], right: tuple[float, float, float]) -> float: + return sum(left[index] * right[index] for index in range(3)) + + +def _cross(left: tuple[float, float, float], right: tuple[float, float, float]) -> tuple[float, float, float]: + return ( + left[1] * right[2] - left[2] * right[1], + left[2] * right[0] - left[0] * right[2], + left[0] * right[1] - left[1] * right[0], + ) + + +def _norm(value: tuple[float, float, float]) -> float: + return math.sqrt(_dot(value, value)) + + +def _normalise(value: tuple[float, float, float], where: str) -> tuple[float, float, float]: + length = _norm(value) + if not math.isfinite(length) or length <= _COORDINATE_TOLERANCE: + _fail(f"{where} must have positive finite length") + return _scale(value, 1.0 / length) + + +def _parse_inputs(raw: Any) -> dict[str, Any]: + value = _mapping(raw, "foot_attachment_inputs") + if set(value) != {"schema", "status", "bulk_source", "connector", "budget"}: + _fail("foot_attachment_inputs has unsupported or missing fields") + if value["schema"] != "creature-kernel.connected-leg-assembly-foot-attachment-inputs.v1": + _fail("foot_attachment_inputs schema is not FOOT-005") + if value["status"] != "FOOT-005-initial-candidate-frozen": + _fail("foot_attachment_inputs status is not the frozen initial candidate") + bulk = _mapping(value["bulk_source"], "foot_attachment_inputs.bulk_source") + if set(bulk) != {"module", "input", "callback_seam"}: + _fail("foot_attachment_inputs.bulk_source has unsupported or missing fields") + if (bulk["module"] != "foot_form_construction.py" or + bulk["input"] != "foot-form-inputs.json" or + bulk["callback_seam"] != "foot_form_construction.build.connector_builder"): + _fail("FOOT-005 must reuse the settled FOOT-004 bulk producer and inputs") + connector = _mapping(value["connector"], "foot_attachment_inputs.connector") + expected_connector = { + "ring_names", "chord_fraction", "edge_fraction", "incoming_fraction", + "outside_fraction", "ray_fraction", "ray_origin_tolerance", + "orientation_tolerance", + } + if set(connector) != expected_connector: + _fail("foot_attachment_inputs.connector has unsupported or missing fields") + if (type(connector["ring_names"]) not in (list, tuple) or + list(connector["ring_names"]) != list(_RING_NAMES)): + _fail("FOOT-005 connector must expose support_s0 and support_s1") + parsed = { + "chord_fraction": _finite(connector["chord_fraction"], "connector.chord_fraction"), + "edge_fraction": _finite(connector["edge_fraction"], "connector.edge_fraction"), + "incoming_fraction": _finite(connector["incoming_fraction"], "connector.incoming_fraction"), + "outside_fraction": _finite(connector["outside_fraction"], "connector.outside_fraction"), + "ray_fraction": _finite(connector["ray_fraction"], "connector.ray_fraction"), + "ray_origin_tolerance": _finite(connector["ray_origin_tolerance"], "connector.ray_origin_tolerance"), + "orientation_tolerance": _finite(connector["orientation_tolerance"], "connector.orientation_tolerance"), + } + if (parsed["chord_fraction"] != 1.0 / 3.0 or + parsed["edge_fraction"] != 0.5 or + parsed["incoming_fraction"] != 0.5 or + parsed["outside_fraction"] != 0.5 or + parsed["ray_fraction"] != 0.5): + _fail("FOOT-005 connector length fractions differ from the settled formulas") + if not parsed["ray_origin_tolerance"] > 0.0 or not parsed["orientation_tolerance"] > 0.0: + _fail("FOOT-005 connector tolerances must be positive") + budget = _mapping(value["budget"], "foot_attachment_inputs.budget") + if set(budget) != {"initial_candidate_count", "shared_correction_max", "input_retuning", "hole_rim_edits"}: + _fail("foot_attachment_inputs.budget has unsupported or missing fields") + if budget != { + "initial_candidate_count": 1, + "shared_correction_max": 1, + "input_retuning": False, + "hole_rim_edits": False, + }: + _fail("FOOT-005 budget or freeze policy differs from the settled record") + return parsed + + +def _ray_triangle(start: tuple[float, float, float], direction: tuple[float, float, float], + a: tuple[float, float, float], b: tuple[float, float, float], + c: tuple[float, float, float], origin_tolerance: float) -> float | None: + edge1, edge2 = _sub(b, a), _sub(c, a) + h = _cross(direction, edge2) + determinant = _dot(edge1, h) + if abs(determinant) <= _AREA_TOLERANCE: + return None + inverse = 1.0 / determinant + source = _sub(start, a) + u = inverse * _dot(source, h) + if u < -_AREA_TOLERANCE or u > 1.0 + _AREA_TOLERANCE: + return None + q = _cross(source, edge1) + v = inverse * _dot(direction, q) + if v < -_AREA_TOLERANCE or u + v > 1.0 + _AREA_TOLERANCE: + return None + travel = inverse * _dot(edge2, q) + if travel <= origin_tolerance: + return None + return travel + + +def _first_body_ray_hit(vertices: list[tuple[float, float, float]], + faces: list[tuple[int, int, int, int]], + start: tuple[float, float, float], + direction: tuple[float, float, float], + origin_tolerance: float) -> float | None: + hits: list[float] = [] + for face in faces: + for triangle in ((face[0], face[1], face[2]), (face[0], face[2], face[3])): + hit = _ray_triangle(start, direction, vertices[triangle[0]], + vertices[triangle[1]], vertices[triangle[2]], + origin_tolerance) + if hit is not None: + hits.append(hit) + return min(hits) if hits else None + + +def _quad_area_vector(vertices: list[tuple[float, float, float]], + face: tuple[int, int, int, int]) -> tuple[float, float, float]: + return _add( + _cross(_sub(vertices[face[1]], vertices[face[0]]), + _sub(vertices[face[2]], vertices[face[0]])), + _cross(_sub(vertices[face[2]], vertices[face[0]]), + _sub(vertices[face[3]], vertices[face[0]])), + ) + + +def _mean(points: list[tuple[float, float, float]], where: str) -> tuple[float, float, float]: + if not points: + _fail(f"{where} has no points") + return tuple(sum(point[index] for point in points) / len(points) + for index in range(3)) # type: ignore[return-value] + + +def _support_connector(context: Mapping[str, Any], config: Mapping[str, Any]) -> dict[str, Any]: + side = context["side"] + vertices = [tuple(point) for point in context["output_vertices"]] + base_vertices = [tuple(point) for point in context["base_vertices"]] + base_quads = [tuple(face) for face in context["base_quads"]] + ankle_indices = list(context["semantic_ankle"]) + hole_indices = list(context["hole_indices"]) + retained_faces_by_name = context["retained_faces"] + retained_faces = [tuple(face) for name in ("dorsal_grid", "plantar_grid", "outer_perimeter") + for face in retained_faces_by_name[name]] + hole_set = set(hole_indices) + chain = _mapping(context["base_mesh_metadata"]["chains"][side], + f"base_mesh.metadata.chains.{side}") + ankle_loop = list(context["ankle_loop"]) + approach_loop = list(_mapping(chain["ring_indices_by_name"], "ankle ring metadata")["ankle_approach"]) + approach_by_ankle = dict(zip(ankle_loop, approach_loop)) + append_vertex = context["append_vertex"] + orientation_tolerance = config["orientation_tolerance"] + + s0_points: list[tuple[float, float, float]] = [] + s1_points: list[tuple[float, float, float]] = [] + diagnostics: list[dict[str, Any]] = [] + for index in range(_SECTOR_COUNT): + ankle = base_vertices[ankle_indices[index]] + hole = vertices[hole_indices[index]] + previous_ankle = base_vertices[approach_by_ankle[ankle_indices[index]]] + d_in = _normalise(_sub(ankle, previous_ankle), f"{side} sector {index} incoming meridian") + previous_hole = vertices[hole_indices[(index - 1) % _SECTOR_COUNT]] + next_hole = vertices[hole_indices[(index + 1) % _SECTOR_COUNT]] + t_boundary = _normalise(_sub(next_hole, previous_hole), + f"{side} sector {index} hole boundary tangent") + + incident_faces = [face for face in retained_faces if hole_indices[index] in face] + if not incident_faces: + _fail(f"{side} sector {index} hole has no retained incident foot faces") + area_vector = _mean([_quad_area_vector(vertices, face) for face in incident_faces], + f"{side} sector {index} area vectors") + n_area = _normalise(area_vector, f"{side} sector {index} retained area normal") + outside_indices = sorted({ + neighbour for face in incident_faces for neighbour in face + if neighbour not in hole_set + }) + outside_centroid = _mean([vertices[neighbour] for neighbour in outside_indices], + f"{side} sector {index} outside neighbours") + outside_vector = _sub(outside_centroid, hole) + outside_projection = _sub(outside_vector, _scale(n_area, _dot(outside_vector, n_area))) + outside_projection = _normalise( + outside_projection, f"{side} sector {index} projected outside direction" + ) + c_out = _normalise(_cross(n_area, t_boundary), + f"{side} sector {index} outgoing conormal") + outside_alignment = _dot(c_out, outside_projection) + if abs(outside_alignment) <= orientation_tolerance: + _fail(f"{side} sector {index} outgoing conormal orientation is ambiguous") + if outside_alignment < 0.0: + c_out = _scale(c_out, -1.0) + outside_alignment = -outside_alignment + + chord = _sub(hole, ankle) + chord_length = _norm(chord) + if chord_length <= _COORDINATE_TOLERANCE: + _fail(f"{side} sector {index} ankle-to-hole chord has no room") + adjacent_edges = [ + _norm(_sub(base_vertices[ankle_indices[(index - 1) % 8]], ankle)), + _norm(_sub(base_vertices[ankle_indices[(index + 1) % 8]], ankle)), + _norm(_sub(vertices[hole_indices[(index - 1) % 8]], hole)), + _norm(_sub(vertices[hole_indices[(index + 1) % 8]], hole)), + ] + if any(edge <= _COORDINATE_TOLERANCE for edge in adjacent_edges): + _fail(f"{side} sector {index} has a degenerate adjacent A/H edge") + edge_cap = config["edge_fraction"] * min(adjacent_edges) + incoming_length = _norm(_sub(ankle, previous_ankle)) + outside_distances = [_norm(_sub(vertices[neighbour], hole)) + for neighbour in outside_indices] + outside_mean = sum(outside_distances) / len(outside_distances) + l0_hit = _first_body_ray_hit( + vertices, retained_faces, ankle, d_in, config["ray_origin_tolerance"] + ) + l1_hit = _first_body_ray_hit( + vertices, retained_faces, hole, _scale(c_out, -1.0), + config["ray_origin_tolerance"] + ) + l0_candidates = { + "chord_third": config["chord_fraction"] * chord_length, + "half_adjacent_A_H_edge": edge_cap, + "half_incoming_meridian": config["incoming_fraction"] * incoming_length, + } + if l0_hit is not None: + l0_candidates["half_first_positive_body_ray_hit"] = config["ray_fraction"] * l0_hit + l1_candidates = { + "chord_third": config["chord_fraction"] * chord_length, + "half_adjacent_A_H_edge": edge_cap, + "half_mean_outside_neighbour_distance": config["outside_fraction"] * outside_mean, + } + if l1_hit is not None: + l1_candidates["half_first_positive_body_ray_hit"] = config["ray_fraction"] * l1_hit + l0 = min(l0_candidates.values()) + l1 = min(l1_candidates.values()) + if l0 <= _COORDINATE_TOLERANCE or l1 <= _COORDINATE_TOLERANCE: + _fail(f"{side} sector {index} has no positive bounded connector length") + s0 = _add(ankle, _scale(d_in, l0)) + s1 = _sub(hole, _scale(c_out, l1)) + s0_points.append(s0) + s1_points.append(s1) + chord_unit = _normalise(chord, f"{side} sector {index} chord") + diagnostics.append({ + "sector": index, + "name": _bulk._HOLE_BOUNDARY_NAMES[index], + "ankle_index": ankle_indices[index], + "hole_index": hole_indices[index], + "approach_index": approach_by_ankle[ankle_indices[index]], + "d_in": list(d_in), + "boundary_previous_direction": list(_normalise(_sub(hole, previous_hole), + f"{side} sector {index} previous boundary")), + "boundary_next_direction": list(_normalise(_sub(next_hole, hole), + f"{side} sector {index} next boundary")), + "boundary_tangent": list(t_boundary), + "n_area": list(n_area), + "c_out": list(c_out), + "outside_neighbour_indices": outside_indices, + "outside_alignment_dot": outside_alignment, + "chord_length": chord_length, + "chord_dot_d_in": _dot(chord_unit, d_in), + "chord_dot_c_out": _dot(chord_unit, c_out), + "adjacent_A_H_edge_lengths": adjacent_edges, + "incoming_meridian_length": incoming_length, + "outside_mean_neighbour_distance": outside_mean, + "first_body_ray_hit_in": l0_hit, + "first_body_ray_hit_out": l1_hit, + "l0_candidates": l0_candidates, + "l1_candidates": l1_candidates, + "l0": l0, + "l1": l1, + }) + + for name, ring in (("support_s0", s0_points), ("support_s1", s1_points)): + if len(ring) != _SECTOR_COUNT or any( + _norm(_sub(ring[(index + 1) % _SECTOR_COUNT], ring[index])) + <= _COORDINATE_TOLERANCE for index in range(_SECTOR_COUNT)): + _fail(f"{side} {name} has a degenerate ring edge") + s0_indices = [append_vertex(point) for point in s0_points] + s1_indices = [append_vertex(point) for point in s1_points] + orientation = context["orientation"] + return { + "ring_order": list(_RING_NAMES), + "rings": {"support_s0": s0_indices, "support_s1": s1_indices}, + "band_order": ["ankle_to_s0", "s0_to_s1", "s1_to_hole"], + "bands": { + "ankle_to_s0": _shared._band(ankle_indices, s0_indices, orientation), + "s0_to_s1": _shared._band(s0_indices, s1_indices, orientation), + "s1_to_hole": _shared._band(s1_indices, hole_indices, orientation), + }, + "metadata": { + "candidate": "FOOT-005 two measured-support-ring attachment", + "formula": "S0=A+l0*d_in; S1=H-l1*c_out", + "length_rule": "min(chord/3, half adjacent A/H edge cap, respective half-neighbour cap, optional half first positive retained-body ray hit)", + "ray_origin_rule": "strictly positive ray travel; t <= ray_origin_tolerance is ignored as an incident-origin hit", + "orientation_rule": "c_out=normalize(n_area cross boundary_tangent), sign selected by projected outside-neighbour dot; zero/ambiguous fails", + "diagnostic_policy": "chord/conormal/adjacent-direction dots are evidence only, not positive gates", + "diagnostics": diagnostics, + "source_lineage": "FOOT-004 rounded bulk grid and fixed ankle/hole endpoints; no source-control or binding changes", + "gates": "shared quad-fold threshold, topology/orientation/degeneracy, ring, retained-body intersection, and later L2 surface checks", + }, + } + + +def build(base_mesh: Mapping[str, Any], leg_inputs: Mapping[str, Any], + foot_form_inputs: Mapping[str, Any], + foot_attachment_inputs: Mapping[str, Any]) -> dict[str, Any]: + """Build FOOT-005 using the live FOOT-004 bulk builder callback seam.""" + config = _parse_inputs(foot_attachment_inputs) + metadata = _mapping(base_mesh["metadata"], "base_mesh.metadata") + + def connector_builder(context: Mapping[str, Any]) -> Mapping[str, Any]: + enriched = dict(context) + enriched["base_mesh_metadata"] = metadata + return _support_connector(enriched, config) + + output = _bulk.build( + base_mesh, leg_inputs, foot_form_inputs, + connector_builder=connector_builder, + ) + output = copy.deepcopy(output) + output["schema"] = "creature-kernel.connected-leg-assembly-foot-attachment-mesh.v1" + output_metadata = output["metadata"] + output_metadata["scheme"] = copy.deepcopy(output_metadata.get("scheme", {})) + output_metadata["scheme"]["foot_form"] = copy.deepcopy( + output_metadata["scheme"].get("foot_form", {}) + ) + output_metadata["scheme"]["foot_form"]["attachment"] = ( + "bulk grid only; FOOT-005 supplies the attachment connector" + ) + output_metadata["scheme"]["foot_attachment"] = { + "candidate": "FOOT-005 two measured-support-ring attachment", + "bulk_producer": "foot_form_construction.build with explicit connector_builder", + "fixed_endpoints": "existing actual ankle ring and existing dorsal hole ring", + "rings": ["support_s0", "support_s1"], + "bands": ["ankle_to_s0", "s0_to_s1", "s1_to_hole"], + "no_caps": True, + "binding": "existing shank binding/source stencils unchanged; no new ankle articulation", + } + for side in _SIDES: + foot = output_metadata["feet"][side] + foot["attachment_candidate"] = copy.deepcopy(foot.pop("connector")) + foot["attachment_candidate"]["input_schema"] = ( + "creature-kernel.connected-leg-assembly-foot-attachment-inputs.v1" + ) + return output + + +def evaluate(mesh: Mapping[str, Any], levels: int = 2) -> list[dict[str, Any]]: + """Reuse the current generic connected-leg evaluator.""" + return _bulk.evaluate(mesh, levels=levels) + + +__all__ = ["AttachmentConstructionError", "build", "evaluate"] diff --git a/experiments/connected-leg-assembly/foot_construction.py b/experiments/connected-leg-assembly/foot_construction.py new file mode 100644 index 0000000..2e49378 --- /dev/null +++ b/experiments/connected-leg-assembly/foot_construction.py @@ -0,0 +1,977 @@ +"""Bounded connected foot construction attached to the expanded leg L0. + +The module consumes the current connected-leg L0 output and the two existing +input maps. It reuses each ordered eight-vertex ankle loop, resolves its +cyclic phase and direction from the actual ankle frame, and closes a small +longitudinal dorsal/plantar grid. It does not create weights, a rig, pose +transforms, or a body. +""" +from __future__ import annotations + +from collections.abc import Mapping +import copy +import hashlib +import importlib.util +import math +from pathlib import Path +import sys +from typing import Any + + +_SIDES = ("left", "right") +_ANKLE_PORTS = {side: f"port.{side}_ankle" for side in _SIDES} +_FOOT_OWNERS = {side: f"domain.{side}_foot" for side in _SIDES} +_LONGITUDINAL_ROW_NAMES = ( + "heel", "heel_ankle_midpoint", "ankle", "ankle_quarter", + "ankle_five_eighths", "ball", "ball_toe_midpoint", "toe", +) +_LONGITUDINAL_ROW_FORMULAS = ( + "H.z", "midpoint(H.z,A.z)", "A.z", "A.z+0.25*(B.z-A.z)", + "A.z+0.625*(B.z-A.z)", "B.z", "midpoint(B.z,T.z)", "T.z", +) +_LONGITUDINAL_ROW_ROLES = ( + "H source heel control", + "derived H-to-A transition row", + "A ankle-z attachment context", + "derived A-to-B transition row", + "derived A-to-B transition row", + "B source ball control", + "derived B-to-T forefoot row", + "T source toe control", +) +_LATERAL_FRACTIONS = (-1.0, -0.65, 0.0, 0.65, 1.0) +_HOLE_BOUNDARY_POSITIONS = ( + (1, 1), (2, 1), (3, 1), (3, 2), + (3, 3), (2, 3), (1, 3), (1, 2), +) +_HOLE_BOUNDARY_NAMES = ( + "mid_ha_left", "ankle_left", "ankle_quarter_left", + "ankle_quarter_centre", "ankle_quarter_right", "ankle_right", + "mid_ha_right", "mid_ha_centre", +) +_ANCHORS = ("H", "B", "T") +_LEG_KEYS = frozenset(( + "J", "T", "K", "A", "radii", "mid_thigh_factor", "support_fraction", + "J_role", "TK_source_role", "distal_design_status", +)) +_COORDINATE_TOLERANCE = 1.0e-8 +_FRAME_TOLERANCE = 1.0e-6 +_AREA_TOLERANCE = 1.0e-12 +_CORRESPONDENCE_TIE_TOLERANCE = 1.0e-9 +_FROZEN_INTERSECTION_CORE = Path( + "/home/ben/.cache/creature-kernel/pelvis-thigh-transition/" + "attempt-2-snapshot/source/experiments/owned-root-assembly-successor/" + "mesh_correctness.py" +) +_FROZEN_INTERSECTION_MODULE = "connected_leg_frozen_intersection_core" + + +class FootConstructionError(ValueError): + """Raised when the bounded foot construction cannot be admitted.""" + + +def _fail(message: str) -> None: + raise FootConstructionError(message) + + +def _mapping(value: Any, where: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping): + _fail(f"{where} must be a mapping") + return value + + +def _finite(value: Any, where: str) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float)): + _fail(f"{where} must be a finite real number") + result = float(value) + if not math.isfinite(result): + _fail(f"{where} must be a finite real number") + return result + + +def _vector(value: Any, where: str) -> tuple[float, float, float]: + if type(value) not in (list, tuple) or len(value) != 3: + _fail(f"{where} must be a three-component vector") + return tuple(_finite(item, f"{where}[{index}]") + for index, item in enumerate(value)) # type: ignore[return-value] + + +def _positive(value: Any, where: str) -> float: + result = _finite(value, where) + if not result > 0.0: + _fail(f"{where} must be positive") + return result + + +def _close(left: tuple[float, float, float], right: tuple[float, float, float], + where: str) -> None: + if any(abs(left[index] - right[index]) > _COORDINATE_TOLERANCE + for index in range(3)): + _fail(f"{where} differs from the source metadata") + + +def _add(left: tuple[float, float, float], right: tuple[float, float, float]) -> tuple[float, float, float]: + return tuple(left[index] + right[index] for index in range(3)) # type: ignore[return-value] + + +def _sub(left: tuple[float, float, float], right: tuple[float, float, float]) -> tuple[float, float, float]: + return tuple(left[index] - right[index] for index in range(3)) # type: ignore[return-value] + + +def _scale(value: tuple[float, float, float], factor: float) -> tuple[float, float, float]: + return tuple(factor * item for item in value) # type: ignore[return-value] + + +def _dot(left: tuple[float, float, float], right: tuple[float, float, float]) -> float: + return sum(left[index] * right[index] for index in range(3)) + + +def _cross(left: tuple[float, float, float], right: tuple[float, float, float]) -> tuple[float, float, float]: + return ( + left[1] * right[2] - left[2] * right[1], + left[2] * right[0] - left[0] * right[2], + left[0] * right[1] - left[1] * right[0], + ) + + +def _norm(value: tuple[float, float, float]) -> float: + return math.sqrt(_dot(value, value)) + + +def _normalise(value: tuple[float, float, float], where: str) -> tuple[float, float, float]: + length = _norm(value) + if not math.isfinite(length) or not length > 0.0: + _fail(f"{where} must have positive finite length") + return _scale(value, 1.0 / length) + + +def _edge_key(left: int, right: int) -> tuple[int, int]: + return (left, right) if left < right else (right, left) + + +def _edge_uses(quads: list[tuple[int, int, int, int]]) -> dict[tuple[int, int], list[tuple[int, int, int]]]: + uses: dict[tuple[int, int], list[tuple[int, int, int]]] = {} + for face_index, face in enumerate(quads): + for corner, left in enumerate(face): + right = face[(corner + 1) % 4] + uses.setdefault(_edge_key(left, right), []).append( + (face_index, left, right)) + return uses + + +def _checked_quads(raw: Any, vertex_count: int, where: str) -> list[tuple[int, int, int, int]]: + if type(raw) not in (list, tuple) or not raw: + _fail(f"{where} must be a non-empty sequence") + result: list[tuple[int, int, int, int]] = [] + for face_index, raw_face in enumerate(raw): + if type(raw_face) not in (list, tuple) or len(raw_face) != 4: + _fail(f"{where}[{face_index}] must contain four indices") + face = tuple(raw_face) + if any(type(index) is not int for index in face): + _fail(f"{where}[{face_index}] indices must be integers") + if len(set(face)) != 4 or any(index < 0 or index >= vertex_count for index in face): + _fail(f"{where}[{face_index}] has invalid indices") + result.append(face) # type: ignore[arg-type] + return result + + +def _checked_loops(raw: Any, vertex_count: int, where: str) -> dict[str, list[int]]: + value = _mapping(raw, where) + if not value: + _fail(f"{where} must not be empty") + result: dict[str, list[int]] = {} + for name, raw_loop in value.items(): + if type(name) is not str or type(raw_loop) not in (list, tuple) or len(raw_loop) < 3: + _fail(f"{where} entries must be named loops of at least three vertices") + loop = list(raw_loop) + if any(type(index) is not int or index < 0 or index >= vertex_count for index in loop): + _fail(f"{where}.{name} has an invalid vertex") + if len(set(loop)) != len(loop): + _fail(f"{where}.{name} repeats a vertex") + result[name] = loop + return result + + +def _validate_topology(vertices: list[tuple[float, float, float]], + quads: list[tuple[int, int, int, int]], + loops: Mapping[str, list[int]], + where: str) -> dict[tuple[int, int], list[tuple[int, int, int]]]: + uses = _edge_uses(quads) + if any(len(rows) not in (1, 2) for rows in uses.values()): + _fail(f"{where} has a non-manifold edge") + if any(len(rows) == 2 and rows[0][1:] == rows[1][1:] for rows in uses.values()): + _fail(f"{where} has an orientation conflict") + declared: set[tuple[int, int]] = set() + for name, loop in loops.items(): + for index, left in enumerate(loop): + edge = _edge_key(left, loop[(index + 1) % len(loop)]) + if edge not in uses or len(uses[edge]) != 1: + _fail(f"{where} loop {name!r} is not a boundary loop") + if edge in declared: + _fail(f"{where} declares a boundary edge more than once") + declared.add(edge) + boundary = {edge for edge, rows in uses.items() if len(rows) == 1} + if declared != boundary: + _fail(f"{where} loops do not cover the boundary exactly") + adjacency = {index: set() for index in range(len(vertices))} + for left, right in uses: + adjacency[left].add(right) + adjacency[right].add(left) + if any(not neighbours for neighbours in adjacency.values()): + _fail(f"{where} contains an unused vertex") + seen = {0} + pending = [0] + while pending: + vertex = pending.pop() + for neighbour in adjacency[vertex]: + if neighbour not in seen: + seen.add(neighbour) + pending.append(neighbour) + if len(seen) != len(vertices): + _fail(f"{where} is disconnected") + return uses + + +def _validate_frame(raw: Any, where: str) -> dict[str, tuple[float, float, float]]: + frame = _mapping(raw, where) + result = {key: _vector(frame.get(key), f"{where}.{key}") + for key in ("tangent", "X", "U", "F")} + for key, value in result.items(): + if abs(_norm(value) - 1.0) > _FRAME_TOLERANCE: + _fail(f"{where}.{key} is not unit length") + if abs(_dot(result["X"], result["U"])) > _FRAME_TOLERANCE: + _fail(f"{where}.X and U are not orthogonal") + if abs(_dot(result["X"], result["F"])) > _FRAME_TOLERANCE: + _fail(f"{where}.X and F are not orthogonal") + if abs(_dot(result["U"], result["F"])) > _FRAME_TOLERANCE: + _fail(f"{where}.U and F are not orthogonal") + if _dot(_cross(result["X"], result["U"]), result["F"]) < 1.0 - _FRAME_TOLERANCE: + _fail(f"{where} does not use the source X/U/F orientation") + return result + + +def _validate_identity_stencils(raw: Any, count: int, where: str) -> None: + if type(raw) not in (list, tuple) or len(raw) != count: + _fail(f"{where} must contain one stencil per L0 vertex") + for index, stencil in enumerate(raw): + if type(stencil) not in (list, tuple) or len(stencil) != 1: + _fail(f"{where}[{index}] must be an identity stencil") + term = stencil[0] + if type(term) not in (list, tuple) or len(term) != 2: + _fail(f"{where}[{index}] is malformed") + if term[0] != index or float(term[1]) != 1.0: + _fail(f"{where}[{index}] must be [[{index}, 1.0]]") + + +def _validate_leg_inputs(leg_inputs: Any) -> dict[str, dict[str, Any]]: + value = _mapping(leg_inputs, "leg_inputs") + if set(value) != set(_SIDES): + _fail("leg_inputs must contain exactly left and right") + result: dict[str, dict[str, Any]] = {} + for side in _SIDES: + row = _mapping(value[side], f"leg_inputs.{side}") + if set(row) != _LEG_KEYS: + _fail(f"leg_inputs.{side} does not match the current connected-leg input schema") + checked = dict(row) + checked["A"] = _vector(row["A"], f"leg_inputs.{side}.A") + for key in ("J", "T", "K"): + _vector(row[key], f"leg_inputs.{side}.{key}") + for key in ("J_role", "TK_source_role", "distal_design_status"): + if type(row[key]) is not str or not row[key]: + _fail(f"leg_inputs.{side}.{key} must be non-empty text") + result[side] = checked + return result + + +def _parse_anchor(raw: Any, where: str) -> dict[str, float]: + row = _mapping(raw, where) + if set(row) != {"z", "plantar_y", "halfwidth", "dorsalthickness"}: + _fail(f"{where} has unsupported or missing fields") + return { + "z": _finite(row["z"], f"{where}.z"), + "plantar_y": _finite(row["plantar_y"], f"{where}.plantar_y"), + "halfwidth": _positive(row["halfwidth"], f"{where}.halfwidth"), + "dorsalthickness": _positive(row["dorsalthickness"], f"{where}.dorsalthickness"), + } + + +def _parse_foot_inputs(foot_inputs: Any) -> dict[str, dict[str, Any]]: + value = _mapping(foot_inputs, "foot_inputs") + if set(value) != set(_SIDES): + _fail("foot_inputs must contain exactly left and right") + result: dict[str, dict[str, Any]] = {} + for side in _SIDES: + row = _mapping(value[side], f"foot_inputs.{side}") + if set(row) != {"H", "B", "T", "collar_fraction"}: + _fail(f"foot_inputs.{side} has unsupported or missing fields") + anchors = {name: _parse_anchor(row[name], f"foot_inputs.{side}.{name}") + for name in _ANCHORS} + alpha = _finite(row["collar_fraction"], f"foot_inputs.{side}.collar_fraction") + if not 0.0 < alpha < 1.0: + _fail(f"foot_inputs.{side}.collar_fraction must be strictly between zero and one") + result[side] = {**anchors, "collar_fraction": alpha} + return result + + +def _ankle_chain(base_mesh: Mapping[str, Any], side: str, + leg_row: Mapping[str, Any], vertices: list[tuple[float, float, float]], + loops: Mapping[str, list[int]]) -> tuple[list[int], tuple[float, float, float], dict[str, tuple[float, float, float]]]: + metadata = _mapping(base_mesh["metadata"], "base_mesh.metadata") + chains = _mapping(metadata.get("chains"), "base_mesh.metadata.chains") + chain = _mapping(chains.get(side), f"base_mesh.metadata.chains.{side}") + port = _ANKLE_PORTS[side] + loop = loops.get(port) + if loop is None or len(loop) != 8: + _fail(f"base_mesh.loops.{port} must be an eight-vertex ankle loop") + if list(chain.get("ankle_port", ())) != loop: + _fail(f"base_mesh metadata ankle port disagrees with {port}") + sections = chain.get("sections") + if type(sections) not in (list, tuple): + _fail(f"base_mesh.metadata.chains.{side}.sections must be a sequence") + ankle_rows = [row for row in sections + if isinstance(row, Mapping) and row.get("name") == "ankle"] + if len(ankle_rows) != 1 or list(ankle_rows[0].get("indices", ())) != loop: + _fail(f"base_mesh metadata ankle section disagrees with {port}") + ankle = ankle_rows[0] + centre = _vector(ankle.get("centre"), f"base_mesh.metadata.chains.{side}.ankle.centre") + A = _vector(leg_row["A"], f"leg_inputs.{side}.A") + _close(centre, A, f"leg_inputs.{side}.A") + frame = _validate_frame(ankle.get("frame"), f"base_mesh.metadata.chains.{side}.ankle.frame") + for index in loop: + if abs(_dot(_sub(vertices[index], centre), frame["tangent"])) > _COORDINATE_TOLERANCE: + _fail(f"{port} is not in its declared source frame plane") + return loop, centre, frame + + +def _validate_base_mesh(base_mesh: Any, leg_inputs: Mapping[str, Any]) -> tuple[ + list[tuple[float, float, float]], list[tuple[int, int, int, int]], dict[str, list[int]], int, int]: + value = _mapping(base_mesh, "base_mesh") + required = {"vertices", "quads", "face_owners", "control_owners", "loops", + "base_stencils", "frames", "metadata"} + if not required.issubset(value): + _fail("base_mesh is missing a required connected-leg field") + if value.get("level") != 0: + _fail("base_mesh must be the expanded connected-leg L0") + raw_vertices = value["vertices"] + if type(raw_vertices) not in (list, tuple) or not raw_vertices: + _fail("base_mesh.vertices must be a non-empty sequence") + vertices = [_vector(point, f"base_mesh.vertices[{index}]") + for index, point in enumerate(raw_vertices)] + quads = _checked_quads(value["quads"], len(vertices), "base_mesh.quads") + face_owners = value["face_owners"] + control_owners = value["control_owners"] + if type(face_owners) not in (list, tuple) or len(face_owners) != len(quads): + _fail("base_mesh.face_owners must match base_mesh.quads") + if type(control_owners) not in (list, tuple) or len(control_owners) != len(vertices): + _fail("base_mesh.control_owners must match base_mesh.vertices") + if any(type(owner) is not str or not owner for owner in (*face_owners, *control_owners)): + _fail("base_mesh owners must be non-empty strings") + loops = _checked_loops(value["loops"], len(vertices), "base_mesh.loops") + expected_loops = { + "port.neck", "port.left_arm", "port.right_arm", + "port.left_ankle", "port.right_ankle", + } + if set(loops) != expected_loops: + _fail("base_mesh must expose exactly the three retained ports and two ankle ports") + _validate_topology(vertices, quads, loops, "base_mesh") + _validate_identity_stencils(value["base_stencils"], len(vertices), "base_mesh.base_stencils") + metadata = _mapping(value["metadata"], "base_mesh.metadata") + if metadata.get("admission_status") != "accepted" or metadata.get("admission_failures") != []: + _fail("base_mesh admission metadata is not accepted") + base_owners = metadata.get("base_control_owners") + if type(base_owners) not in (list, tuple) or len(base_owners) != len(vertices): + _fail("base_mesh metadata base_control_owners must match L0 vertices") + if any(type(owner) is not str or not owner for owner in base_owners): + _fail("base_mesh metadata base_control_owners must be non-empty strings") + if metadata.get("base_vertex_count", len(base_owners)) != len(base_owners): + _fail("base_mesh metadata base_vertex_count must match base_control_owners") + frames = _mapping(value["frames"], "base_mesh.frames") + if set(frames) != set(_SIDES): + _fail("base_mesh.frames must contain exactly left and right") + leg_rows = _validate_leg_inputs(leg_inputs) + for side in _SIDES: + _ankle_chain(value, side, leg_rows[side], vertices, loops) + return vertices, quads, loops, len(vertices), len(quads) + + +def _source_profile(z: float, controls: Mapping[str, Any], field: str, + side: str) -> float: + """Evaluate one piecewise-linear H/B/T source control without clamping.""" + H, B, T = (controls[name] for name in _ANCHORS) + if not H["z"] <= z <= T["z"]: + _fail(f"{side} longitudinal row z lies outside the H..T source profile") + if z <= B["z"]: + left, right = H, B + else: + left, right = B, T + fraction = (z - left["z"]) / (right["z"] - left["z"]) + if field == "halfwidth": + if z <= B["z"]: + fraction *= fraction + return left["halfwidth"] + fraction * (right["halfwidth"] - left["halfwidth"]) + if field == "plantar_y": + left_value, right_value = left["plantar_y"], right["plantar_y"] + elif field == "dorsal_y": + left_value = left["plantar_y"] + left["dorsalthickness"] + right_value = right["plantar_y"] + right["dorsalthickness"] + else: + _fail(f"unsupported source profile field: {field}") + return left_value + fraction * (right_value - left_value) + + +def _longitudinal_row_zs(A: tuple[float, float, float], + controls: Mapping[str, Any], side: str) -> list[float]: + H, B, T = (controls[name] for name in _ANCHORS) + if not H["z"] < A[2] < B["z"] < T["z"]: + _fail(f"{side} footprint must place heel behind A and ball/toe ahead of A") + rows = [ + H["z"], + 0.5 * (H["z"] + A[2]), + A[2], + A[2] + 0.25 * (B["z"] - A[2]), + A[2] + 0.625 * (B["z"] - A[2]), + B["z"], + 0.5 * (B["z"] + T["z"]), + T["z"], + ] + if any(not left < right for left, right in zip(rows, rows[1:])): + _fail(f"{side} longitudinal row z values are not strictly ordered") + return rows + + +def _longitudinal_grid_points(x: float, A: tuple[float, float, float], + controls: Mapping[str, Any], side: str) -> dict[str, Any]: + row_zs = _longitudinal_row_zs(A, controls, side) + rows = [] + top: list[list[tuple[float, float, float]]] = [] + bottom: list[list[tuple[float, float, float]]] = [] + for index, z in enumerate(row_zs): + width = _source_profile(z, controls, "halfwidth", side) + rows.append({ + "name": _LONGITUDINAL_ROW_NAMES[index], + "z": z, + "z_formula": _LONGITUDINAL_ROW_FORMULAS[index], + "source_role": _LONGITUDINAL_ROW_ROLES[index], + "halfwidth": width, + }) + top.append([(x + lateral * width, + _source_profile(z, controls, "dorsal_y", side), z) + for lateral in _LATERAL_FRACTIONS]) + bottom.append([(x + lateral * width, + _source_profile(z, controls, "plantar_y", side), z) + for lateral in _LATERAL_FRACTIONS]) + return {"rows": rows, "top": top, "bottom": bottom} + + +def _validate_footprint(A: tuple[float, float, float], + ankle_halfwidth: float, + controls: Mapping[str, Any], side: str) -> None: + H, B, T = (controls[name] for name in _ANCHORS) + _longitudinal_row_zs(A, controls, side) + if not B["halfwidth"] > ankle_halfwidth + _COORDINATE_TOLERANCE: + _fail(f"{side} ball width must exceed the attached ankle width") + if H["halfwidth"] > B["halfwidth"] or T["halfwidth"] > B["halfwidth"]: + _fail(f"{side} footprint width must not bulb beyond its ball section") + + +def _correspondence(base_loop: list[int], vertices: list[tuple[float, float, float]], + centre: tuple[float, float, float], + frame: Mapping[str, tuple[float, float, float]], + target_points: list[tuple[float, float, float]], + target_order: tuple[str, ...], side: str) -> dict[str, Any]: + def projected(point: tuple[float, float, float], origin: tuple[float, float, float]) -> tuple[float, float]: + delta = _sub(point, origin) + return (_dot(delta, frame["X"]), _dot(delta, frame["F"])) + + actual = [] + for index in base_loop: + pair = projected(vertices[index], centre) + length = math.hypot(pair[0], pair[1]) + if not length > _COORDINATE_TOLERANCE: + _fail(f"{side} ankle loop has a degenerate projected vertex") + actual.append((pair[0] / length, pair[1] / length)) + semantic = [] + for point in target_points: + pair = projected(point, centre) + length = math.hypot(pair[0], pair[1]) + if not length > _COORDINATE_TOLERANCE: + _fail(f"{side} foot semantic direction is degenerate in the ankle frame") + semantic.append((pair[0] / length, pair[1] / length)) + + candidates = [] + for direction in (1, -1): + for phase in range(8): + indices = [(phase + direction * offset) % 8 for offset in range(8)] + score = sum(actual[indices[offset]][0] * semantic[offset][0] + + actual[indices[offset]][1] * semantic[offset][1] + for offset in range(8)) + candidates.append({"phase": phase, "direction": direction, + "score": float(score), "indices": indices}) + candidates.sort(key=lambda row: (-row["score"], row["direction"], row["phase"])) + best = candidates[0] + if best["score"] <= 0.0: + _fail(f"{side} ankle-to-foot correspondence has no positive source-frame match") + if len(candidates) > 1 and best["score"] - candidates[1]["score"] <= _CORRESPONDENCE_TIE_TOLERANCE: + _fail(f"{side} ankle-to-foot correspondence is phase or orientation ambiguous") + return { + "ankle_loop_order": list(base_loop), + "target_order": list(target_order), + "target_to_ankle_indices": [base_loop[index] for index in best["indices"]], + "phase": best["phase"], + "direction": best["direction"], + "score": best["score"], + "runner_up_score": candidates[1]["score"], + "candidate_scores": [ + {key: row[key] for key in ("phase", "direction", "score")} + for row in candidates + ], + "method": "maximum cyclic phase/direction score from actual ankle-frame projected positions", + } + + +def _band(source: list[int], target: list[int], orientation: int) -> list[tuple[int, int, int, int]]: + if len(source) != 8 or len(target) != 8 or orientation not in (-1, 1): + _fail("foot bands require eight-vertex rings and a signed orientation") + result = [] + for index in range(8): + next_index = (index + 1) % 8 + if orientation == 1: + result.append((source[next_index], source[index], target[index], target[next_index])) + else: + result.append((source[index], source[next_index], target[next_index], target[index])) + return result + + +def _top_grid_faces(grid: list[list[int | None]]) -> list[tuple[int, int, int, int]]: + if len(grid) != len(_LONGITUDINAL_ROW_NAMES) or any(len(row) != 5 for row in grid): + _fail("top longitudinal grid must contain eight rows of five vertices") + result = [] + for row in range(len(grid) - 1): + for column in range(4): + corners = (grid[row][column], grid[row + 1][column], + grid[row + 1][column + 1], grid[row][column + 1]) + if any(index is None for index in corners): + continue + result.append(corners) # type: ignore[arg-type] + return result + + +def _bottom_grid_faces(grid: list[list[int]]) -> list[tuple[int, int, int, int]]: + if len(grid) != len(_LONGITUDINAL_ROW_NAMES) or any(len(row) != 5 for row in grid): + _fail("bottom longitudinal grid must contain eight rows of five vertices") + return [ + (grid[row][column], grid[row][column + 1], + grid[row + 1][column + 1], grid[row + 1][column]) + for row in range(len(grid) - 1) + for column in range(4) + ] + + +def _outer_grid_faces(top: list[list[int | None]], + bottom: list[list[int]]) -> list[tuple[int, int, int, int]]: + if any(top[row][column] is None for row in (0, len(top) - 1) + for column in range(5)): + _fail("longitudinal grid end rows cannot contain omitted vertices") + result: list[tuple[int, int, int, int]] = [] + for row in range(len(top) - 1): + left_top, left_next = top[row][0], top[row + 1][0] + right_top, right_next = top[row][4], top[row + 1][4] + if left_top is None or left_next is None or right_top is None or right_next is None: + _fail("longitudinal grid outer side contains an omitted vertex") + result.extend(( + (left_top, bottom[row][0], bottom[row + 1][0], left_next), + (right_top, right_next, bottom[row + 1][4], bottom[row][4]), + )) + for column in range(4): + result.extend(( + (top[0][column], top[0][column + 1], + bottom[0][column + 1], bottom[0][column]), + (top[-1][column], bottom[-1][column], + bottom[-1][column + 1], top[-1][column + 1]), + )) + return result + + +def _triangle(points: list[tuple[float, float, float]], face: tuple[int, int, int, int], + diagonal: int) -> tuple[tuple[float, float, float], ...]: + if diagonal == 0: + return points[face[0]], points[face[1]], points[face[2]] + return points[face[0]], points[face[2]], points[face[3]] + + +def _triangle_area_normal(triangle: tuple[tuple[float, float, float], ...], where: str) -> tuple[float, float, float]: + normal = _cross(_sub(triangle[1], triangle[0]), _sub(triangle[2], triangle[0])) + length = _norm(normal) + if not math.isfinite(length) or length <= _AREA_TOLERANCE: + _fail(f"{where} is degenerate") + return normal + + +def _validate_new_faces(vertices: list[tuple[float, float, float]], + quads: list[tuple[int, int, int, int]], + new_face_indices: list[int], side: str) -> None: + for face_index in new_face_indices: + face = quads[face_index] + first = _triangle(vertices, face, 0) + second = _triangle(vertices, face, 1) + n_first = _triangle_area_normal(first, f"{side} foot quad {face_index} first triangle") + n_second = _triangle_area_normal(second, f"{side} foot quad {face_index} second triangle") + if _dot(n_first, n_second) <= 0.0: + _fail(f"{side} foot quad {face_index} has a cuff fold") + + +def _core_identity(path: Path) -> dict[str, Any]: + try: + info = path.lstat() + except OSError as exc: + raise FootConstructionError(f"frozen intersection core is unavailable: {path}") from exc + if path.is_symlink() or not path.is_file() or not info: + _fail(f"frozen intersection core must be a regular non-symlink file: {path}") + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return {"bytes": path.stat().st_size, "sha256": digest.hexdigest()} + + +def _load_intersection_core() -> Any: + before = _core_identity(_FROZEN_INTERSECTION_CORE) + spec = importlib.util.spec_from_file_location( + _FROZEN_INTERSECTION_MODULE, _FROZEN_INTERSECTION_CORE + ) + if spec is None or spec.loader is None: + _fail(f"unable to load frozen intersection core: {_FROZEN_INTERSECTION_CORE}") + module = importlib.util.module_from_spec(spec) + sys.modules[_FROZEN_INTERSECTION_MODULE] = module + try: + spec.loader.exec_module(module) + except Exception: + if sys.modules.get(_FROZEN_INTERSECTION_MODULE) is module: + sys.modules.pop(_FROZEN_INTERSECTION_MODULE, None) + raise + if Path(str(module.__file__)).resolve() != _FROZEN_INTERSECTION_CORE.resolve(): + _fail("frozen intersection core resolved away from its pinned path") + after = _core_identity(_FROZEN_INTERSECTION_CORE) + if before != after: + _fail("frozen intersection core changed while being loaded") + function = getattr(module, "intersection_diagnostics", None) + if not callable(function): + _fail("frozen intersection core lacks intersection_diagnostics") + return function + + +def _validate_intersections(vertices: list[tuple[float, float, float]], + quads: list[tuple[int, int, int, int]], + base_face_count: int, + new_face_indices: list[int], side: str) -> None: + triangles = tuple( + triangle + for face in quads + for triangle in ((face[0], face[1], face[2]), (face[0], face[2], face[3])) + ) + expected_pairs = len(triangles) * (len(triangles) - 1) // 2 + try: + diagnostic = _load_intersection_core()(vertices, triangles) + except FootConstructionError: + raise + except Exception as exc: + _fail(f"frozen intersection core rejected the complete foot mesh: {exc}") + if not isinstance(diagnostic, Mapping): + _fail("frozen intersection core returned a non-mapping diagnostic") + evidence = diagnostic.get("pair_policy_evidence") + processed = evidence.get("processed_pair_count") if isinstance(evidence, Mapping) else None + if (diagnostic.get("pair_count") != expected_pairs or + processed != expected_pairs or + not diagnostic.get("pair_policy_complete")): + _fail("frozen intersection core did not account for every triangle pair") + if diagnostic.get("hit_pairs_truncated"): + _fail("frozen intersection core truncated the triangle hit list") + + new_faces = set(new_face_indices) + inherited_hits: list[tuple[int, int]] = [] + new_hits: list[tuple[int, int, tuple[int, int]]] = [] + for raw_pair in diagnostic.get("hit_pairs", ()): + if (not isinstance(raw_pair, (list, tuple)) or len(raw_pair) != 2 or + any(type(index) is not int or index < 0 or index >= len(triangles) + for index in raw_pair)): + _fail("frozen intersection core returned a malformed triangle hit") + triangle_pair = tuple(sorted(raw_pair)) + face_pair = tuple(sorted((triangle_pair[0] // 2, triangle_pair[1] // 2))) + if any(face in new_faces for face in face_pair): + new_hits.append((triangle_pair[0], triangle_pair[1], face_pair)) + else: + inherited_hits.append((triangle_pair[0], triangle_pair[1])) + if new_hits: + _fail(f"{side} foot self-intersects or intersects the attached leg; " + f"triangle hit {new_hits[0][:2]} maps to quad faces {new_hits[0][2]}") + + +def _validate_output(mesh: Mapping[str, Any], base: Mapping[str, Any], + base_vertex_count: int, base_face_count: int, + new_face_indices_by_side: Mapping[str, list[int]]) -> None: + vertices = [_vector(point, f"output.vertices[{index}]") + for index, point in enumerate(mesh["vertices"])] + quads = _checked_quads(mesh["quads"], len(vertices), "output.quads") + expected_prefix = [_vector(point, f"base_mesh.vertices[{index}]") + for index, point in enumerate(base["vertices"])] + if vertices[:base_vertex_count] != expected_prefix: + _fail("output does not preserve the expanded-leg vertex prefix") + if quads[:base_face_count] != [tuple(face) for face in base["quads"]]: + _fail("output does not preserve the expanded-leg face prefix") + loops = _checked_loops(mesh["loops"], len(vertices), "output.loops") + _validate_topology(vertices, quads, loops, "output") + if any(name in loops for name in _ANKLE_PORTS.values()): + _fail("closed foot output must not retain ankle boundary loops") + for name in ("port.neck", "port.left_arm", "port.right_arm"): + if loops.get(name) != list(base["loops"][name]): + _fail(f"output changed retained boundary loop {name}") + for side, indices in new_face_indices_by_side.items(): + _validate_new_faces(vertices, quads, indices, side) + _validate_intersections(vertices, quads, base_face_count, indices, side) + + +def build(base_mesh: Mapping[str, Any], leg_inputs: Mapping[str, Any], + foot_inputs: Mapping[str, Any]) -> dict[str, Any]: + """Attach one common closed longitudinal foot grid per side to L0.""" + leg_rows = _validate_leg_inputs(leg_inputs) + foot_rows = _parse_foot_inputs(foot_inputs) + base_vertices, base_quads, base_loops, base_vertex_count, base_face_count = ( + _validate_base_mesh(base_mesh, leg_rows) + ) + output_vertices = [list(point) for point in base_vertices] + output_quads = [list(face) for face in base_quads] + output_face_owners = list(base_mesh["face_owners"]) + output_control_owners = list(base_mesh["control_owners"]) + base_metadata = _mapping(base_mesh["metadata"], "base_mesh.metadata") + base_control_owners = list(base_metadata["base_control_owners"]) + output_loops = {name: list(loop) for name, loop in base_loops.items() + if name not in _ANKLE_PORTS.values()} + metadata = copy.deepcopy(dict(base_metadata)) + metadata["level"] = 0 + metadata["base_control_owners"] = base_control_owners + metadata["base_vertex_count"] = len(base_control_owners) + metadata["feet"] = {} + index_mapping = copy.deepcopy(metadata.get("index_mapping", {})) + new_face_indices_by_side: dict[str, list[int]] = {} + + for side in _SIDES: + ankle_loop, ankle_centre, ankle_frame = _ankle_chain( + base_mesh, side, leg_rows[side], base_vertices, base_loops + ) + A = leg_rows[side]["A"] + controls = foot_rows[side] + ankle_halfwidth = max(abs(_dot(_sub(base_vertices[index], ankle_centre), ankle_frame["X"])) + for index in ankle_loop) + _validate_footprint(A, ankle_halfwidth, controls, side) + grid = _longitudinal_grid_points(A[0], A, controls, side) + top_points = grid["top"] + bottom_points = grid["bottom"] + + top_indices: list[list[int | None]] = [[None] * 5 for _ in top_points] + bottom_indices: list[list[int]] = [[] for _ in bottom_points] + new_vertices: list[int] = [] + + def append_vertex(point: tuple[float, float, float]) -> int: + index = len(output_vertices) + output_vertices.append(list(point)) + output_control_owners.append(_FOOT_OWNERS[side]) + base_control_owners.append(_FOOT_OWNERS[side]) + new_vertices.append(index) + return index + + for row, points in enumerate(top_points): + for column, point in enumerate(points): + if row == 2 and column == 2: + continue + top_indices[row][column] = append_vertex(point) + for row, points in enumerate(bottom_points): + for point in points: + bottom_indices[row].append(append_vertex(point)) + + hole_points = [top_points[row][column] + for row, column in _HOLE_BOUNDARY_POSITIONS] + hole_indices = [top_indices[row][column] + for row, column in _HOLE_BOUNDARY_POSITIONS] + if any(index is None for index in hole_indices): + _fail(f"{side} ankle hole contains an omitted or missing vertex") + hole_indices = [int(index) for index in hole_indices] + correspondence = _correspondence( + ankle_loop, base_vertices, ankle_centre, ankle_frame, + hole_points, _HOLE_BOUNDARY_NAMES, side + ) + semantic_ankle = correspondence["target_to_ankle_indices"] + direction = int(correspondence["direction"]) + ankle_winding = _loop_winding(base_quads, ankle_loop, side) + orientation = ankle_winding * direction + if orientation != 1: + _fail(f"{side} ankle-to-hole winding is incompatible with the global dorsal grid") + + collar_points = [ + _lerp_point(base_vertices[semantic_ankle[index]], hole_points[index], + controls["collar_fraction"]) + for index in range(8) + ] + collar_indices = [append_vertex(point) for point in collar_points] + + foot_faces: list[int] = [] + face_ranges: dict[str, list[int]] = {} + + def add_faces(name: str, faces: list[tuple[int, int, int, int]]) -> None: + start = len(output_quads) + output_quads.extend([list(face) for face in faces]) + output_face_owners.extend([_FOOT_OWNERS[side]] * len(faces)) + indices = list(range(start, start + len(faces))) + face_ranges[name] = indices + foot_faces.extend(indices) + + add_faces("dorsal_grid", _top_grid_faces(top_indices)) + add_faces("plantar_grid", _bottom_grid_faces(bottom_indices)) + add_faces("outer_perimeter", _outer_grid_faces(top_indices, bottom_indices)) + add_faces("ankle_to_collar", _band(semantic_ankle, collar_indices, orientation)) + add_faces("collar_to_hole", _band(collar_indices, hole_indices, orientation)) + new_face_indices_by_side[side] = foot_faces + + source_anchors = { + name: [A[0], controls[name]["plantar_y"], controls[name]["z"]] + for name in _ANCHORS + } + metadata["feet"][side] = { + "owner": _FOOT_OWNERS[side], + "source_anchors": source_anchors, + "anchor_fields": copy.deepcopy({name: controls[name] for name in _ANCHORS}), + "ankle_source_loop": list(ankle_loop), + "attachment_loop": { + "ankle": list(ankle_loop), + "hole": list(hole_indices), + "collar": list(collar_indices), + }, + "ring_order": ["dorsal_grid", "plantar_grid", "ankle_hole", "collar"], + "ring_indices_by_name": { + "dorsal_grid": [index for row in top_indices for index in row + if index is not None], + "plantar_grid": [index for row in bottom_indices for index in row], + "ankle_hole": list(hole_indices), + "collar": list(collar_indices), + }, + "grid_indices": { + "dorsal": [list(row) for row in top_indices], + "plantar": [list(row) for row in bottom_indices], + }, + "longitudinal_rows": copy.deepcopy(grid["rows"]), + "lateral_fractions": list(_LATERAL_FRACTIONS), + "hole_boundary_positions": [list(position) + for position in _HOLE_BOUNDARY_POSITIONS], + "new_vertex_indices": list(new_vertices), + "new_face_indices": list(foot_faces), + "face_owner": _FOOT_OWNERS[side], + "face_owner_ranges": face_ranges, + "collar_fraction": controls["collar_fraction"], + "correspondence": correspondence, + "winding": { + "attached_ankle_loop": ankle_winding, + "target_direction": direction, + "output_orientation": orientation, + }, + "frames": { + "ankle_source": {key: list(value) for key, value in ankle_frame.items()}, + "foot_staging": { + "X": [1.0, 0.0, 0.0], "Y": [0.0, 1.0, 0.0], + "Z": [0.0, 0.0, 1.0], + }, + }, + "source_profiles": { + "height": "separate piecewise-linear H/B/T plantar_y and plantar_y+dorsalthickness", + "halfwidth": "H-to-B uses source halfwidth with u^2; B-to-T is linear", + }, + "binding": "no weights introduced; future foot vertices inherit corresponding shank influence", + } + index_mapping[f"{side}_foot_new_vertices"] = list(new_vertices) + index_mapping[f"{side}_foot_new_faces"] = list(foot_faces) + + metadata["base_vertex_count"] = len(base_control_owners) + metadata["index_mapping"] = index_mapping + metadata["scheme"] = copy.deepcopy(metadata.get("scheme", {})) + metadata["scheme"]["foot"] = { + "candidate": "closed longitudinal dorsal/plantar grid with a small dorsal ankle-entry hole", + "row_names": list(_LONGITUDINAL_ROW_NAMES), + "lateral_fractions": list(_LATERAL_FRACTIONS), + "row_zs": list(_LONGITUDINAL_ROW_FORMULAS), + "height_profiles": "plantar and dorsal heights independently follow source piecewise-linear H/B/T controls", + "halfwidth_profile": "H-to-B source halfwidth interpolated with u^2; B-to-T source halfwidth linear", + "dorsal_hole": "omit only row 1..2, column 1..2 quads and the unused row-2 column-2 vertex", + "outer_perimeter": "two longitudinal sides plus heel and toe end strips; 22 quads", + "attachment": "actual ankle-frame phase and edge winding, existing collar_fraction=.20, two eight-quad bands", + "source_roles": "H heel support, A ankle-z attachment context, B/T independent longitudinal forefoot controls", + "source_frame": "actual ankle frame projected correspondence; staging footprint is global X/Y/Z", + "ankle_boundary": "reused as an interior ring and removed from declared boundaries", + "evaluator": "read-only current connected-leg generic Catmull-Clark evaluator", + } + output = { + "schema": "creature-kernel.connected-leg-assembly-foot-mesh.v1", + "level": 0, + "vertices": output_vertices, + "quads": output_quads, + "face_owners": output_face_owners, + "control_owners": output_control_owners, + "loops": output_loops, + "base_stencils": list(base_mesh["base_stencils"]) + [ + [[index, 1.0]] for index in range(base_vertex_count, len(output_vertices)) + ], + "frames": copy.deepcopy(base_mesh["frames"]), + "metadata": metadata, + } + _validate_output(output, base_mesh, base_vertex_count, base_face_count, + new_face_indices_by_side) + return output + + +def _lerp_point(left: tuple[float, float, float], right: tuple[float, float, float], fraction: float) -> tuple[float, float, float]: + return tuple(left[index] + fraction * (right[index] - left[index]) + for index in range(3)) # type: ignore[return-value] + + +def _loop_winding(quads: list[tuple[int, int, int, int]], loop: list[int], side: str) -> int: + uses = _edge_uses(quads) + signs = [] + for index, left in enumerate(loop): + right = loop[(index + 1) % len(loop)] + rows = uses.get(_edge_key(left, right), []) + if len(rows) != 1: + _fail(f"{side} ankle loop edge is not a unique boundary edge") + used_left, used_right = rows[0][1:] + if (used_left, used_right) == (left, right): + signs.append(1) + elif (used_left, used_right) == (right, left): + signs.append(-1) + else: # pragma: no cover - guarded by edge key + _fail(f"{side} ankle loop winding cannot be resolved") + if len(set(signs)) != 1: + _fail(f"{side} ankle loop has inconsistent winding") + return signs[0] + + +def evaluate(mesh: Mapping[str, Any], levels: int = 2) -> list[dict[str, Any]]: + """Delegate evaluation to the current generic connected-leg evaluator.""" + if type(levels) is not int or levels < 0 or levels > 2: + _fail("levels must be an integer between zero and two") + metadata = _mapping(mesh.get("metadata"), "mesh.metadata") if isinstance(mesh, Mapping) else {} + if not isinstance(metadata.get("feet"), Mapping): + _fail("mesh must be a foot-construction L0 output") + try: + import construction + except ImportError as exc: # pragma: no cover - exercised only outside experiment source + _fail(f"current connected-leg evaluator is unavailable: {exc}") + evaluator = getattr(construction, "evaluate", None) + if not callable(evaluator): + _fail("current connected-leg evaluator has no evaluate function") + try: + return evaluator(mesh, levels=levels) + except Exception as exc: + if isinstance(exc, FootConstructionError): + raise + raise FootConstructionError( + f"current connected-leg generic evaluator rejected the foot output: {exc}" + ) from exc + + +__all__ = ["FootConstructionError", "build", "evaluate"] diff --git a/experiments/connected-leg-assembly/foot_form_construction.py b/experiments/connected-leg-assembly/foot_form_construction.py new file mode 100644 index 0000000..6bcccb3 --- /dev/null +++ b/experiments/connected-leg-assembly/foot_form_construction.py @@ -0,0 +1,691 @@ +"""FOOT-004 source/form candidate attached to expanded connected-leg L0. + +This candidate keeps the FOOT-003 grid connectivity and delegates its mesh, +topology, collision, and evaluation helpers to ``foot_construction``. It +changes only the source representation: five local centre controls and three +local-normal radii per control produce rounded ten-point transverse sections. +It does not create a joint, weights, a rig, poses, or a body. +""" +from __future__ import annotations + +from collections.abc import Callable, Mapping +import copy +import math +from typing import Any + +import foot_construction as _shared + + +_SIDES = ("left", "right") +_ANCHORS = ("H", "R", "M", "B", "T") +_LATERAL_FRACTIONS = (-1.0, -0.65, 0.0, 0.65, 1.0) +_ROW_NAMES = ( + "rear_heel", "heel_ankle_midpoint", "ankle_body", + "ankle_body_quarter", "ankle_body_five_eighths", "forefoot_start", + "forefoot_body", "terminal", +) +_ROW_FORMULAS = ( + "H", "midpoint(H,R)", "R", "R+0.25*(M-R)", + "R+0.625*(M-R)", "M", "B", "T", +) +_ROW_ROLES = ( + "H rear heel source control", + "derived H-to-R centre row", + "R ankle-body surface-centre source control; not a joint", + "derived R-to-M centre row", + "derived R-to-M centre row", + "M forefoot-start source control", + "B forefoot-body source control", + "T terminal source control", +) +_HOLE_BOUNDARY_POSITIONS = _shared._HOLE_BOUNDARY_POSITIONS +_HOLE_BOUNDARY_NAMES = _shared._HOLE_BOUNDARY_NAMES +_GLOBAL_Y = (0.0, 1.0, 0.0) +_GLOBAL_Z = (0.0, 0.0, 1.0) +_COORDINATE_TOLERANCE = 1.0e-8 +_FRAME_TOLERANCE = 1.0e-6 +_FORWARD_TOLERANCE = 1.0e-8 +_EXPECTED_CONSTRUCTION = { + "midpoint_fraction": 0.5, + "rise_row_fractions": (0.25, 0.625), + "rise_width_exponent": 2.0, + "cross_section_rounding": 0.94, + "collar_fraction": 0.20, +} + + +FootFormConstructionError = _shared.FootConstructionError + + +def _fail(message: str) -> None: + raise FootFormConstructionError(message) + + +def _mapping(value: Any, where: str) -> Mapping[str, Any]: + return _shared._mapping(value, where) + + +def _finite(value: Any, where: str) -> float: + return _shared._finite(value, where) + + +def _vector(value: Any, where: str) -> tuple[float, float, float]: + return _shared._vector(value, where) + + +def _add(*values: tuple[float, float, float]) -> tuple[float, float, float]: + return tuple(sum(value[axis] for value in values) + for axis in range(3)) # type: ignore[return-value] + + +def _sub(left: tuple[float, float, float], + right: tuple[float, float, float]) -> tuple[float, float, float]: + return tuple(left[axis] - right[axis] + for axis in range(3)) # type: ignore[return-value] + + +def _scale(value: tuple[float, float, float], factor: float) -> tuple[float, float, float]: + return tuple(factor * item for item in value) # type: ignore[return-value] + + +def _dot(left: tuple[float, float, float], + right: tuple[float, float, float]) -> float: + return sum(left[axis] * right[axis] for axis in range(3)) + + +def _cross(left: tuple[float, float, float], + right: tuple[float, float, float]) -> tuple[float, float, float]: + return ( + left[1] * right[2] - left[2] * right[1], + left[2] * right[0] - left[0] * right[2], + left[0] * right[1] - left[1] * right[0], + ) + + +def _norm(value: tuple[float, float, float]) -> float: + return math.sqrt(_dot(value, value)) + + +def _normalise(value: tuple[float, float, float], where: str) -> tuple[float, float, float]: + length = _norm(value) + if not math.isfinite(length) or length <= _COORDINATE_TOLERANCE: + _fail(f"{where} must have positive finite length") + return _scale(value, 1.0 / length) + + +def _lerp(left: tuple[float, float, float], + right: tuple[float, float, float], fraction: float) -> tuple[float, float, float]: + return _add(_scale(left, 1.0 - fraction), _scale(right, fraction)) + + +def _parse_anchor(raw: Any, where: str) -> dict[str, float]: + row = _mapping(raw, where) + if set(row) != {"local_y", "local_z", "rL", "rD", "rP"}: + _fail(f"{where} must contain exactly local_y, local_z, rL, rD, and rP") + result = { + "local_y": _finite(row["local_y"], f"{where}.local_y"), + "local_z": _finite(row["local_z"], f"{where}.local_z"), + "rL": _finite(row["rL"], f"{where}.rL"), + "rD": _finite(row["rD"], f"{where}.rD"), + "rP": _finite(row["rP"], f"{where}.rP"), + } + if any(result[key] <= 0.0 for key in ("rL", "rD", "rP")): + _fail(f"{where} radii must be positive") + return result + + +def _parse_construction(raw: Any) -> dict[str, Any]: + row = _mapping(raw, "foot_form_inputs.construction") + if set(row) != { + "midpoint_fraction", "rise_row_fractions", "rise_width_exponent", + "cross_section_rounding", "collar_fraction"}: + _fail("foot_form_inputs.construction has unsupported or missing fields") + midpoint = _finite(row["midpoint_fraction"], "construction.midpoint_fraction") + fractions = row["rise_row_fractions"] + if type(fractions) not in (list, tuple) or len(fractions) != 2: + _fail("construction.rise_row_fractions must contain two fractions") + rise_fractions = tuple(_finite(value, "construction.rise_row_fractions") + for value in fractions) + exponent = _finite(row["rise_width_exponent"], "construction.rise_width_exponent") + rounding = _finite(row["cross_section_rounding"], "construction.cross_section_rounding") + collar = _finite(row["collar_fraction"], "construction.collar_fraction") + if abs(midpoint - _EXPECTED_CONSTRUCTION["midpoint_fraction"]) > _FRAME_TOLERANCE: + _fail("construction.midpoint_fraction differs from the settled FOOT-004 value") + if any(abs(left - right) > _FRAME_TOLERANCE + for left, right in zip(rise_fractions, _EXPECTED_CONSTRUCTION["rise_row_fractions"])): + _fail("construction.rise_row_fractions differ from the settled FOOT-004 values") + if abs(exponent - _EXPECTED_CONSTRUCTION["rise_width_exponent"]) > _FRAME_TOLERANCE: + _fail("construction.rise_width_exponent differs from the settled FOOT-004 value") + if abs(rounding - _EXPECTED_CONSTRUCTION["cross_section_rounding"]) > _FRAME_TOLERANCE: + _fail("construction.cross_section_rounding differs from the settled FOOT-004 value") + if abs(collar - _EXPECTED_CONSTRUCTION["collar_fraction"]) > _FRAME_TOLERANCE: + _fail("construction.collar_fraction differs from the settled FOOT-004 value") + if not 0.0 < rise_fractions[0] < rise_fractions[1] < 1.0: + _fail("construction.rise_row_fractions must be increasing inside R..M") + if not 0.0 < rounding < 1.0: + _fail("construction.cross_section_rounding must be between zero and one") + if not 0.0 < collar < 1.0: + _fail("construction.collar_fraction must be between zero and one") + return { + "midpoint_fraction": midpoint, + "rise_row_fractions": list(rise_fractions), + "rise_width_exponent": exponent, + "cross_section_rounding": rounding, + "collar_fraction": collar, + } + + +def _parse_form_inputs(raw: Any) -> dict[str, Any]: + value = _mapping(raw, "foot_form_inputs") + if set(value) != {"case_id", "construction", "sides"}: + _fail("foot_form_inputs must be one exact case row with case_id, construction, and sides") + if type(value["case_id"]) is not str or not value["case_id"]: + _fail("foot_form_inputs.case_id must be non-empty text") + construction = _parse_construction(value["construction"]) + sides = _mapping(value["sides"], "foot_form_inputs.sides") + if set(sides) != set(_SIDES): + _fail("foot_form_inputs.sides must contain exactly left and right") + parsed_sides: dict[str, dict[str, Any]] = {} + for side in _SIDES: + source = _mapping(sides[side], f"foot_form_inputs.sides.{side}") + if set(source) != {"reference_y", *_ANCHORS}: + _fail(f"foot_form_inputs.sides.{side} has unsupported or missing fields") + parsed = {name: _parse_anchor(source[name], + f"foot_form_inputs.sides.{side}.{name}") + for name in _ANCHORS} + parsed["reference_y"] = _finite( + source["reference_y"], f"foot_form_inputs.sides.{side}.reference_y" + ) + local_zs = [parsed[name]["local_z"] for name in _ANCHORS] + if any(not left < right for left, right in zip(local_zs, local_zs[1:])): + _fail(f"foot_form_inputs.sides.{side} source centres must move forward H dict[str, tuple[float, float, float]]: + # ``base_mesh.frames.`` is the construction's leg-summary frame. It + # is retained as metadata, but it is not the terminal ankle section frame. + # The validated attachment frame returned by _ankle_chain is the sole + # source of the foot-local lateral axis. + X = _vector(attachment_frame.get("X"), + f"{side} attachment_frame.X") + projection = _sub(_GLOBAL_Y, _scale(X, _dot(_GLOBAL_Y, X))) + U = _normalise(projection, f"{side} source-frame up") + if _dot(U, _GLOBAL_Y) <= _FORWARD_TOLERANCE: + _fail(f"{side} source-frame up does not point toward global +Y") + F = _normalise(_cross(X, U), f"{side} source-frame forward") + if _dot(F, _GLOBAL_Z) <= _FORWARD_TOLERANCE: + _fail(f"{side} source-frame forward is not positively consistent with global +Z") + if _dot(_cross(X, U), F) < 1.0 - _FRAME_TOLERANCE: + _fail(f"{side} source frame is not right-handed") + return {"X": X, "U": U, "F": F} + + +def _world_point(origin: tuple[float, float, float], + frame: Mapping[str, tuple[float, float, float]], + local_y: float, local_z: float) -> tuple[float, float, float]: + return _add(origin, _scale(frame["U"], local_y), + _scale(frame["F"], local_z)) + + +def _segment_for_z(z: float, controls: Mapping[str, Mapping[str, float]]) -> int: + for index in range(len(_ANCHORS) - 1): + if z <= controls[_ANCHORS[index + 1]]["local_z"]: + return index + return len(_ANCHORS) - 2 + + +def _piecewise_value(z: float, controls: Mapping[str, Mapping[str, float]], + field: str, *, rise_exponent: float | None = None) -> tuple[float, int, float]: + segment = _segment_for_z(z, controls) + left_name, right_name = _ANCHORS[segment], _ANCHORS[segment + 1] + left, right = controls[left_name], controls[right_name] + fraction = ((z - left["local_z"]) / + (right["local_z"] - left["local_z"])) + used_fraction = fraction + if rise_exponent is not None and left_name == "R" and right_name == "M": + used_fraction = fraction ** rise_exponent + value = left[field] + used_fraction * (right[field] - left[field]) + return value, segment, fraction + + +def _unit_secants(origin: tuple[float, float, float], + frame: Mapping[str, tuple[float, float, float]], + controls: Mapping[str, Mapping[str, float]], + side: str) -> list[tuple[float, float, float]]: + centres = [ + _world_point(origin, frame, controls[name]["local_y"], controls[name]["local_z"]) + for name in _ANCHORS + ] + result = [] + for index, (left, right) in enumerate(zip(centres, centres[1:])): + tangent = _normalise(_sub(right, left), f"{side} source secant {index}") + if _dot(tangent, frame["F"]) <= _FORWARD_TOLERANCE: + _fail(f"{side} source secant reverses source-frame forward") + result.append(tangent) + return result + + +def _row_tangent(row_index: int, z: float, origin: tuple[float, float, float], + frame: Mapping[str, tuple[float, float, float]], + controls: Mapping[str, Mapping[str, float]], + secants: list[tuple[float, float, float]], side: str) -> tuple[float, float, float]: + if row_index == 0: + tangent = secants[0] + elif row_index == len(_ROW_NAMES) - 1: + tangent = secants[-1] + else: + control_index = next( + (index for index, name in enumerate(_ANCHORS) + if abs(z - controls[name]["local_z"]) <= _COORDINATE_TOLERANCE), + None, + ) + if control_index is not None: + tangent = _normalise( + _add(secants[control_index - 1], secants[control_index]), + f"{side} row {row_index} interior tangent", + ) + else: + tangent = secants[_segment_for_z(z, controls)] + if _dot(tangent, frame["F"]) <= _FORWARD_TOLERANCE: + _fail(f"{side} row {row_index} tangent reverses source-frame forward") + return tangent + + +def _grid_points(origin: tuple[float, float, float], + frame: Mapping[str, tuple[float, float, float]], + controls: Mapping[str, Mapping[str, float]], + construction: Mapping[str, Any], side: str) -> dict[str, Any]: + zs = [ + controls["H"]["local_z"], + construction["midpoint_fraction"] * ( + controls["H"]["local_z"] + controls["R"]["local_z"]), + controls["R"]["local_z"], + controls["R"]["local_z"] + construction["rise_row_fractions"][0] * ( + controls["M"]["local_z"] - controls["R"]["local_z"]), + controls["R"]["local_z"] + construction["rise_row_fractions"][1] * ( + controls["M"]["local_z"] - controls["R"]["local_z"]), + controls["M"]["local_z"], + controls["B"]["local_z"], + controls["T"]["local_z"], + ] + if any(not left < right for left, right in zip(zs, zs[1:])): + _fail(f"{side} FOOT-004 row z values are not strictly ordered") + secants = _unit_secants(origin, frame, controls, side) + rows: list[dict[str, Any]] = [] + top: list[list[tuple[float, float, float]]] = [] + bottom: list[list[tuple[float, float, float]]] = [] + for row_index, z in enumerate(zs): + centre_y, segment, fraction = _piecewise_value(z, controls, "local_y") + rL, _, _ = _piecewise_value( + z, controls, "rL", rise_exponent=construction["rise_width_exponent"] + ) + rD, _, _ = _piecewise_value(z, controls, "rD") + rP, _, _ = _piecewise_value(z, controls, "rP") + centre = _world_point(origin, frame, centre_y, z) + tangent = _row_tangent(row_index, z, origin, frame, controls, secants, side) + normal = _normalise(_cross(tangent, frame["X"]), + f"{side} row {row_index} local normal") + if _dot(normal, frame["U"]) <= _FORWARD_TOLERANCE: + _fail(f"{side} row {row_index} local normal points below the source frame") + rows.append({ + "name": _ROW_NAMES[row_index], + "formula": _ROW_FORMULAS[row_index], + "source_role": _ROW_ROLES[row_index], + "local_z": z, + "local_centre_y": centre_y, + "source_segment": f"{_ANCHORS[segment]}-{_ANCHORS[segment + 1]}", + "segment_fraction": fraction, + "centre": list(centre), + "tangent": list(tangent), + "normal": list(normal), + "rL": rL, + "rD": rD, + "rP": rP, + }) + row_top: list[tuple[float, float, float]] = [] + row_bottom: list[tuple[float, float, float]] = [] + for q in _LATERAL_FRACTIONS: + radicand = 1.0 - (construction["cross_section_rounding"] * q) ** 2 + if radicand <= 0.0: + _fail(f"{side} row {row_index} rounded section radicand is not positive") + arc = math.sqrt(radicand) + lateral = _scale(frame["X"], q * rL) + row_top.append(_add(centre, lateral, _scale(normal, arc * rD))) + row_bottom.append(_add(centre, lateral, _scale(normal, -arc * rP))) + top.append(row_top) + bottom.append(row_bottom) + return {"rows": rows, "top": top, "bottom": bottom, + "secants": [list(value) for value in secants]} + + +def _append_vertex(output_vertices: list[list[float]], output_owners: list[str], + owners: list[str], new_vertices: list[int], + point: tuple[float, float, float], owner: str) -> int: + index = len(output_vertices) + output_vertices.append(list(point)) + output_owners.append(owner) + owners.append(owner) + new_vertices.append(index) + return index + + +def _default_connector_builder(context: Mapping[str, Any]) -> dict[str, Any]: + """Preserve the original FOOT-004 collar connector in the default path.""" + append_vertex = context["append_vertex"] + semantic_ankle = context["semantic_ankle"] + hole_points = context["hole_points"] + orientation = context["orientation"] + form = context["form"] + collar_points = [ + _shared._lerp_point(context["base_vertices"][semantic_ankle[index]], + hole_points[index], + form["construction"]["collar_fraction"]) + for index in range(8) + ] + collar_indices = [append_vertex(point) for point in collar_points] + return { + "ring_order": ["collar"], + "rings": {"collar": collar_indices}, + "band_order": ["ankle_to_collar", "collar_to_hole"], + "bands": { + "ankle_to_collar": _shared._band( + semantic_ankle, collar_indices, orientation), + "collar_to_hole": _shared._band( + collar_indices, context["hole_indices"], orientation), + }, + "metadata": {}, + } + + +def _connector_result(raw: Any, output_vertex_count: int, side: str) -> dict[str, Any]: + result = _mapping(raw, f"{side} connector result") + if set(result) != {"ring_order", "rings", "band_order", "bands", "metadata"}: + _fail(f"{side} connector result has unsupported or missing fields") + ring_order = result["ring_order"] + band_order = result["band_order"] + if (type(ring_order) not in (list, tuple) or + type(band_order) not in (list, tuple) or + not ring_order or not band_order or + any(type(name) is not str or not name + for name in (*ring_order, *band_order))): + _fail(f"{side} connector ring and band orders must be non-empty names") + rings = _mapping(result["rings"], f"{side} connector rings") + bands = _mapping(result["bands"], f"{side} connector bands") + if set(rings) != set(ring_order) or set(bands) != set(band_order): + _fail(f"{side} connector order does not match its named rings and bands") + parsed_rings: dict[str, list[int]] = {} + for name in ring_order: + raw_ring = rings[name] + if type(raw_ring) not in (list, tuple) or len(raw_ring) != 8: + _fail(f"{side} connector ring {name} must contain eight vertices") + ring = list(raw_ring) + if (any(type(index) is not int or index < 0 or index >= output_vertex_count + for index in ring) or len(set(ring)) != 8): + _fail(f"{side} connector ring {name} has invalid or duplicate vertices") + parsed_rings[name] = ring + parsed_bands: dict[str, list[tuple[int, int, int, int]]] = {} + for name in band_order: + raw_band = bands[name] + if type(raw_band) not in (list, tuple) or len(raw_band) != 8: + _fail(f"{side} connector band {name} must contain eight quads") + parsed_bands[name] = _shared._checked_quads( + raw_band, output_vertex_count, f"{side} connector band {name}" + ) + return { + "ring_order": list(ring_order), + "rings": parsed_rings, + "band_order": list(band_order), + "bands": parsed_bands, + "metadata": copy.deepcopy(dict(_mapping( + result["metadata"], f"{side} connector metadata"))), + } + + +def build(base_mesh: Mapping[str, Any], leg_inputs: Mapping[str, Any], + foot_form_inputs: Mapping[str, Any], *, + connector_builder: Callable[[Mapping[str, Any]], Mapping[str, Any]] | None = None + ) -> dict[str, Any]: + """Attach the FOOT-004 rounded-source grid to expanded connected-leg L0.""" + leg_rows = _shared._validate_leg_inputs(leg_inputs) + form = _parse_form_inputs(foot_form_inputs) + base_vertices, base_quads, base_loops, base_vertex_count, base_face_count = ( + _shared._validate_base_mesh(base_mesh, leg_rows) + ) + output_vertices = [list(point) for point in base_vertices] + output_quads = [list(face) for face in base_quads] + output_face_owners = list(base_mesh["face_owners"]) + output_control_owners = list(base_mesh["control_owners"]) + base_metadata = _mapping(base_mesh["metadata"], "base_mesh.metadata") + base_control_owners = list(base_metadata["base_control_owners"]) + output_loops = { + name: list(loop) for name, loop in base_loops.items() + if name not in _shared._ANKLE_PORTS.values() + } + metadata = copy.deepcopy(dict(base_metadata)) + metadata["level"] = 0 + metadata["base_control_owners"] = base_control_owners + metadata["base_vertex_count"] = len(base_control_owners) + metadata["feet"] = {} + index_mapping = copy.deepcopy(metadata.get("index_mapping", {})) + new_face_indices_by_side: dict[str, list[int]] = {} + + for side in _SIDES: + ankle_loop, ankle_centre, attachment_frame = _shared._ankle_chain( + base_mesh, side, leg_rows[side], base_vertices, base_loops + ) + source_frame = _source_frame(base_mesh, side, attachment_frame) + controls = form["sides"][side] + grid = _grid_points( + ankle_centre, source_frame, + {name: controls[name] for name in _ANCHORS}, + form["construction"], side, + ) + top_points = grid["top"] + bottom_points = grid["bottom"] + top_indices: list[list[int | None]] = [[None] * 5 for _ in top_points] + bottom_indices: list[list[int]] = [[] for _ in bottom_points] + new_vertices: list[int] = [] + owner = _shared._FOOT_OWNERS[side] + + def append_vertex(point: tuple[float, float, float]) -> int: + return _append_vertex( + output_vertices, output_control_owners, base_control_owners, + new_vertices, point, owner + ) + + for row, points in enumerate(top_points): + for column, point in enumerate(points): + if row == 2 and column == 2: + continue + top_indices[row][column] = append_vertex(point) + for row, points in enumerate(bottom_points): + for point in points: + bottom_indices[row].append(append_vertex(point)) + + hole_points = [top_points[row][column] + for row, column in _HOLE_BOUNDARY_POSITIONS] + hole_indices = [top_indices[row][column] + for row, column in _HOLE_BOUNDARY_POSITIONS] + if any(index is None for index in hole_indices): + _fail(f"{side} FOOT-004 ankle hole contains a missing vertex") + hole_indices = [int(index) for index in hole_indices] + correspondence = _shared._correspondence( + ankle_loop, base_vertices, ankle_centre, attachment_frame, + hole_points, _HOLE_BOUNDARY_NAMES, side, + ) + semantic_ankle = correspondence["target_to_ankle_indices"] + direction = int(correspondence["direction"]) + ankle_winding = _shared._loop_winding(base_quads, ankle_loop, side) + orientation = ankle_winding * direction + if orientation != 1: + _fail(f"{side} FOOT-004 ankle-to-hole winding is incompatible") + dorsal_faces = _shared._top_grid_faces(top_indices) + plantar_faces = _shared._bottom_grid_faces(bottom_indices) + perimeter_faces = _shared._outer_grid_faces(top_indices, bottom_indices) + builder = _default_connector_builder if connector_builder is None else connector_builder + if not callable(builder): + _fail("connector_builder must be callable") + connector = _connector_result(builder({ + "side": side, + "base_vertices": base_vertices, + "base_quads": base_quads, + "output_vertices": output_vertices, + "output_control_owners": output_control_owners, + "base_control_owners": base_control_owners, + "new_vertices": new_vertices, + "append_vertex": append_vertex, + "ankle_loop": ankle_loop, + "ankle_centre": ankle_centre, + "attachment_frame": attachment_frame, + "semantic_ankle": semantic_ankle, + "hole_points": hole_points, + "hole_indices": hole_indices, + "orientation": orientation, + "owner": owner, + "top_indices": top_indices, + "bottom_indices": bottom_indices, + "retained_faces": { + "dorsal_grid": dorsal_faces, + "plantar_grid": plantar_faces, + "outer_perimeter": perimeter_faces, + }, + "grid": grid, + "controls": controls, + "form": form, + }), len(output_vertices), side) + + foot_faces: list[int] = [] + face_ranges: dict[str, list[int]] = {} + + def add_faces(name: str, faces: list[tuple[int, int, int, int]]) -> None: + start = len(output_quads) + output_quads.extend([list(face) for face in faces]) + output_face_owners.extend([owner] * len(faces)) + indices = list(range(start, start + len(faces))) + face_ranges[name] = indices + foot_faces.extend(indices) + + add_faces("dorsal_grid", dorsal_faces) + add_faces("plantar_grid", plantar_faces) + add_faces("outer_perimeter", perimeter_faces) + for name in connector["band_order"]: + add_faces(name, connector["bands"][name]) + new_face_indices_by_side[side] = foot_faces + + source_anchors = { + name: list(_world_point(ankle_centre, source_frame, + controls[name]["local_y"], + controls[name]["local_z"])) + for name in _ANCHORS + } + metadata["feet"][side] = { + "owner": owner, + "source_anchors": source_anchors, + "anchor_fields": copy.deepcopy({name: controls[name] for name in _ANCHORS}), + "ankle_source_loop": list(ankle_loop), + "attachment_loop": { + "ankle": list(ankle_loop), + "hole": list(hole_indices), + **{name: list(connector["rings"][name]) + for name in connector["ring_order"]}, + }, + "ring_order": ["dorsal_grid", "plantar_grid", "ankle_hole", + *connector["ring_order"]], + "ring_indices_by_name": { + "dorsal_grid": [index for row in top_indices for index in row + if index is not None], + "plantar_grid": [index for row in bottom_indices for index in row], + "ankle_hole": list(hole_indices), + **{name: list(connector["rings"][name]) + for name in connector["ring_order"]}, + }, + "grid_indices": { + "dorsal": [list(row) for row in top_indices], + "plantar": [list(row) for row in bottom_indices], + }, + "longitudinal_rows": copy.deepcopy(grid["rows"]), + "lateral_fractions": list(_LATERAL_FRACTIONS), + "hole_boundary_positions": [list(position) + for position in _HOLE_BOUNDARY_POSITIONS], + "new_vertex_indices": list(new_vertices), + "new_face_indices": list(foot_faces), + "face_owner": owner, + "face_owner_ranges": face_ranges, + "collar_fraction": form["construction"]["collar_fraction"], + "correspondence": correspondence, + "winding": { + "attached_ankle_loop": ankle_winding, + "target_direction": direction, + "output_orientation": orientation, + }, + "frames": { + "attachment": {key: list(value) + for key, value in attachment_frame.items()}, + "source": {key: list(value) for key, value in source_frame.items()}, + "origin": list(ankle_centre), + }, + "source_form": { + "input_schema": "creature-kernel.connected-leg-assembly-foot-form-inputs.v1", + "case_id": form["case_id"], + "construction": copy.deepcopy(form["construction"]), + "local_controls": copy.deepcopy(controls), + "reference_y": controls["reference_y"], + "reference_y_usage": "contact-plane measurement only; no floor projection", + "centre_rule": "piecewise-linear H/R/M/B/T local centres", + "radius_rule": "rL linear except R-to-M uses rise_width_exponent; rD/rP linear", + "normal_rule": "N=normalize(tangent cross attachment_frame.X)", + "cross_section_rule": "top/bottom use rounded q-section and distinct rD/rP local-normal radii", + "joint_rule": "R is ankle-body surface centre and is not a joint; actual A remains attachment origin", + "row_derivation": "rows use the explicit FOOT-004 formulas and adjacent-secant tangent rule", + }, + "binding": "no weights introduced; future foot vertices inherit corresponding shank influence", + } + if connector["metadata"]: + metadata["feet"][side]["connector"] = connector["metadata"] + index_mapping[f"{side}_foot_new_vertices"] = list(new_vertices) + index_mapping[f"{side}_foot_new_faces"] = list(foot_faces) + + metadata["base_vertex_count"] = len(base_control_owners) + metadata["index_mapping"] = index_mapping + metadata["scheme"] = copy.deepcopy(metadata.get("scheme", {})) + metadata["scheme"]["foot_form"] = { + "candidate": "FOOT-004 rounded longitudinal source/form grid", + "source_controls": list(_ANCHORS), + "rows": list(_ROW_FORMULAS), + "lateral_fractions": list(_LATERAL_FRACTIONS), + "hole": "reuse FOOT-003 row-2 centre omission and eight-vertex boundary", + "outer_perimeter": "reuse FOOT-003 22-quad closure", + "attachment": "reuse actual ankle phase/winding and collar_fraction=.20", + "frame": "origin actual A, X validated ankle attachment_frame.X, U projected global +Y, F=X cross U", + "radii": "local-normal rL/rD/rP; top and bottom remain distinct", + "evaluator": "read-only current connected-leg generic Catmull-Clark evaluator", + } + output = { + "schema": "creature-kernel.connected-leg-assembly-foot-form-mesh.v1", + "level": 0, + "vertices": output_vertices, + "quads": output_quads, + "face_owners": output_face_owners, + "control_owners": output_control_owners, + "loops": output_loops, + "base_stencils": list(base_mesh["base_stencils"]) + [ + [[index, 1.0]] for index in range(base_vertex_count, len(output_vertices)) + ], + "frames": copy.deepcopy(base_mesh["frames"]), + "metadata": metadata, + } + _shared._validate_output(output, base_mesh, base_vertex_count, base_face_count, + new_face_indices_by_side) + return output + + +def evaluate(mesh: Mapping[str, Any], levels: int = 2) -> list[dict[str, Any]]: + """Reuse FOOT-003's current generic connected-leg evaluator.""" + return _shared.evaluate(mesh, levels=levels) + + +__all__ = ["FootFormConstructionError", "build", "evaluate"] diff --git a/experiments/connected-leg-assembly/foot_form_failure_diagnostic.py b/experiments/connected-leg-assembly/foot_form_failure_diagnostic.py new file mode 100644 index 0000000..478e92a --- /dev/null +++ b/experiments/connected-leg-assembly/foot_form_failure_diagnostic.py @@ -0,0 +1,316 @@ +"""FOOT-004 rejected-candidate preservation adapter. + +This adapter executes against an existing immutable captured snapshot only. It +intercepts the shared validator to retain its raw L0 argument, calls the +original validator unchanged, preserves and reports the original exception, +then derives diagnostic L2/renderings from the retained payload when possible. +It never converts a validator failure into acceptance and never runs binding, +collision, poses, or source-response checks. +""" + +from __future__ import annotations + +import copy +import hashlib +import importlib.util +import json +from pathlib import Path +import sys +from typing import Any, Mapping + +runner: Any = None + + +SOURCE = Path("source/experiments/connected-leg-assembly") +CASES = ("calibrated_ordinary_human", "calibrated_upright_anthropomorphic") +FACE_INDEX = 326 + + +def _fail(message: str) -> None: + raise runner.RunnerError(message) + + +def _read(path: Path) -> tuple[Any, bytes]: + return runner._read_json(path) + + +def _case_row(document: Mapping[str, Any], case_id: str) -> Mapping[str, Any]: + rows = [row for row in document.get("cases", []) + if isinstance(row, Mapping) and row.get("id") == case_id] + if len(rows) != 1: + _fail(f"inputs lack unique case {case_id}") + return rows[0] + + +def _form_row(document: Mapping[str, Any], case_id: str) -> Mapping[str, Any]: + rows = [row for row in document.get("cases", []) + if isinstance(row, Mapping) and row.get("case_id") == case_id] + if len(rows) != 1: + _fail(f"foot-form inputs lack unique case {case_id}") + return rows[0] + + +def _source_base(snapshot: Path, manifest: Mapping[str, Any], + case: Mapping[str, Any], construction: Any, + root_source: Any) -> Mapping[str, Any]: + # Match the focused FOOT004 test's frozen candidate method exactly: + # immutable checked-in root reference, then the captured leg builder. + root_ref = case.get("root_mesh") + if not isinstance(root_ref, Mapping): + _fail(f"{case['id']} lacks root_mesh reference") + root_path = Path(str(root_ref.get("path"))) + expected = str(root_ref.get("sha256")) + if not root_path.is_file() or runner._sha256(root_path) != expected: + _fail(f"immutable root identity drifted: {root_path}") + root, _ = _read(root_path) + return construction.build(root, case["leg_inputs"]) + + +def _vector_sub(a: list[float], b: list[float]) -> list[float]: + return [a[i] - b[i] for i in range(3)] + + +def _cross(a: list[float], b: list[float]) -> list[float]: + return [a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0]] + + +def _triangle_normal(vertices: list[list[float]], triangle: list[int]) -> list[float]: + normal = _cross(_vector_sub(vertices[triangle[1]], vertices[triangle[0]]), + _vector_sub(vertices[triangle[2]], vertices[triangle[0]])) + length = sum(value * value for value in normal) ** 0.5 + return [value / length for value in normal] if length else [0.0, 0.0, 0.0] + + +def _face_record(mesh: Mapping[str, Any], face_index: int) -> dict[str, Any]: + vertices = mesh["vertices"] + quads = mesh.get("quads", mesh.get("faces")) + if face_index < 0 or face_index >= len(quads): + return {"status": "unavailable", "reason": "face index outside retained L0"} + quad = list(quads[face_index]) + triangles = [[quad[0], quad[1], quad[2]], [quad[0], quad[2], quad[3]]] + band = None + side = None + feet = mesh.get("metadata", {}).get("feet", {}) + for candidate_side, data in feet.items(): + for candidate_band, indices in data.get("face_owner_ranges", {}).items(): + if face_index in indices: + side, band = candidate_side, candidate_band + return { + "status": "retained", + "face_index": face_index, + "quad_vertex_indices": quad, + "vertices": [vertices[index] for index in quad], + "triangles": triangles, + "triangle_normals": [_triangle_normal(vertices, triangle) + for triangle in triangles], + "owner": mesh.get("face_owners", [None] * len(quads))[face_index], + "semantic_side": side, + "semantic_band": band, + } + + +def _detail_mesh(mesh: Mapping[str, Any], cutoff_y: float = -0.50) -> dict[str, Any]: + vertices = mesh["vertices"] + quads = mesh.get("quads", mesh.get("faces")) + selected = [list(face) for face in quads + if all(vertices[index][1] <= cutoff_y for index in face)] + if not selected: + _fail("detail crop selected no complete faces") + original = sorted({index for face in selected for index in face}) + remap = {old: new for new, old in enumerate(original)} + return { + "schema": "creature-kernel.connected-foot-form-detail-mesh.v1", + "level": 2, + "vertices": [vertices[index] for index in original], + "quads": [[remap[index] for index in face] for face in selected], + "metadata": {"crop": "faces wholly within world Y <= -0.50", + "capped": False, "original_vertex_indices": original}, + } + + +def main(snapshot: str, output: str) -> int: + snapshot_path = Path(snapshot) + output_path = Path(output) + adapter_path = Path(__file__).resolve() + if output_path.exists() or output_path.is_symlink(): + _fail(f"diagnostic output must be absent: {output_path}") + captured_runner_path = snapshot_path / SOURCE / "runner.py" + spec = importlib.util.spec_from_file_location( + "foot_form_diagnostic_captured_runner", captured_runner_path) + if spec is None or spec.loader is None: + raise RuntimeError("unable to load captured runner") + global runner + runner = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = runner + spec.loader.exec_module(runner) + adapter_before = runner._identity(adapter_path) + manifest = runner.verify(snapshot_path) + source_root = snapshot_path / SOURCE + inputs, inputs_raw = _read(source_root / "inputs.json") + forms, forms_raw = _read(source_root / "foot-form-inputs.json") + if not isinstance(inputs, Mapping) or not isinstance(forms, Mapping): + _fail("captured inputs must be objects") + + output_path.mkdir(parents=True) + (output_path / "diagnostic-adapter.py").write_bytes(adapter_path.read_bytes()) + adapter_copy = runner._identity(output_path / "diagnostic-adapter.py") + dependency_before = runner._dependency_identity() + shared = runner._load_module("foot_construction", source_root / "foot_construction.py") + sys.modules["foot_construction"] = shared + construction = runner._load_module("construction", source_root / "construction.py") + root_source = runner._load_module("root_source", source_root / "root_source.py") + foot_form = runner._load_module("foot_form_construction", + source_root / "foot_form_construction.py") + original_validator = shared._validate_output + retained: dict[str, Any] = {} + + def intercept(*args: Any, **kwargs: Any) -> Any: + retained["payload"] = copy.deepcopy(args[0]) if args else None + try: + return original_validator(*args, **kwargs) + except Exception as exc: + retained["error"] = {"type": type(exc).__name__, "message": str(exc)} + raise + + shared._validate_output = intercept + renderer_path = Path(str(manifest["dependency"]["before"]["renderer"]["path"])) + renderer = runner._load_module("foot_form_diagnostic_renderer", renderer_path) + results: list[dict[str, Any]] = [] + render_inputs: list[tuple[Path, Mapping[str, Any], Mapping[str, Any]]] = [] + + for index, case_id in enumerate(CASES): + case_dir = output_path / "cases" / f"case-{index:02d}-{case_id}" + case_dir.mkdir(parents=True) + retained.clear() + case = _case_row(inputs, case_id) + form = _form_row(forms, case_id) + result: dict[str, Any] = { + "id": case_id, + "accepted": False, + "execution_origin": ( + "original focused test candidate" if index == 0 + else "supplemental frozen-method case generation; not previously run by focused test" + ), + "gates_not_run": ["acceptance", "collision", "source-response", "poses"], + } + try: + base = _source_base(snapshot_path, manifest, case, construction, root_source) + foot_form.build(base, case["leg_inputs"], form) + except Exception as exc: + result["candidate_validation"] = { + "status": "failed", + "validator": "foot_construction._validate_output", + "error": retained.get("error", {"type": type(exc).__name__, + "message": str(exc)}), + } + if retained.get("payload") is None: + result["status"] = "rejected-diagnostic-unavailable" + result["reason"] = "validator did not expose an L0 payload" + runner._write_json(case_dir / "case-report.json", runner._jsonable(result)) + results.append(result) + continue + raw_l0 = retained["payload"] + runner._write_json(case_dir / "rejected-foot-L0.json", runner._jsonable(raw_l0)) + result["status"] = "REJECTED DIAGNOSTIC - RAW L0 RETAINED" + result["raw_l0"] = {"path": str(case_dir / "rejected-foot-L0.json"), + "vertices": len(raw_l0["vertices"]), + "quads": len(raw_l0["quads"])} + result["failing_face_326"] = _face_record(raw_l0, FACE_INDEX) + try: + levels = foot_form.evaluate(raw_l0, levels=2) + for level, mesh in enumerate(levels): + runner._write_json(case_dir / f"rejected-foot-L{level}.json", + runner._jsonable(mesh)) + l2 = levels[-1] + detail = _detail_mesh(l2) + runner._write_json(case_dir / "rejected-foot-detail-L2.json", + runner._jsonable(detail)) + result["diagnostic_evaluation"] = { + "status": "completed", + "levels": [{"level": level, "vertices": len(mesh["vertices"]), + "quads": len(mesh["quads"])} + for level, mesh in enumerate(levels)], + } + render_inputs.append((case_dir, l2, detail)) + except Exception as exc: + result["diagnostic_evaluation"] = { + "status": "failed", + "error": {"type": type(exc).__name__, "message": str(exc)}, + } + runner._write_json(case_dir / "case-report.json", runner._jsonable(result)) + results.append(result) + + render_errors: list[dict[str, Any]] = [] + if render_inputs: + full_bounds = runner._bounds([mesh for _path, mesh, _detail in render_inputs]) + detail_bounds = runner._bounds([detail for _path, _mesh, detail in render_inputs]) + for case_dir, mesh, detail in render_inputs: + full = runner._render_one( + renderer, mesh, case_dir / "rejected-full-leg-context.png", + case_dir.name, "FOOT-004 REJECTED DIAGNOSTIC - FULL LEG CONTEXT", + full_bounds, [], + ) + small = runner._render_one( + renderer, detail, case_dir / "rejected-foot-detail.png", + case_dir.name, "FOOT-004 REJECTED DIAGNOSTIC - FOOT DETAIL", + detail_bounds, [], + ) + for label, record in (("full_leg_context", full), ("foot_detail", small)): + if record.get("status") == "exception": + render_errors.append({"case": case_dir.name, "view": label, + "error": record.get("exception")}) + for result in results: + if result["id"] in case_dir.name: + result["renders"] = {"full_leg_context": runner._jsonable(full), + "foot_detail": runner._jsonable(small)} + runner._write_json(case_dir / "case-report.json", + runner._jsonable(result)) + + adapter_after = runner._identity(adapter_path) + dependency_after = runner._dependency_identity() + snapshot_after = runner.verify(snapshot_path) + report = { + "schema": "creature-kernel.connected-foot-form-rejected-diagnostic.v1", + "status": "rejected-diagnostic", + "accepted": False, + "source_snapshot": str(snapshot_path), + "snapshot_manifest": runner._identity(snapshot_path / "manifest.json"), + "snapshot_post_verify": snapshot_after.get("schema"), + "diagnostic_adapter": {"before": adapter_before, "captured": adapter_copy, + "after": adapter_after, + "unchanged": adapter_before == adapter_after}, + "dependency_before": dependency_before, + "dependency_after": dependency_after, + "dependency_drift": dependency_before != dependency_after, + "collision": "not-run", + "source_response": "not-run", + "poses": "not-run", + "render_errors": render_errors, + "cases": results, + "foot_form_inputs_sha256": hashlib.sha256(forms_raw).hexdigest(), + "inputs_sha256": hashlib.sha256(inputs_raw).hexdigest(), + } + runner._write_json(output_path / "diagnostic-report.json", runner._jsonable(report)) + files = [] + for path in sorted(output_path.rglob("*"), + key=lambda item: item.relative_to(output_path).as_posix()): + if path.is_file() and path.name != "artifact-manifest.json": + files.append({"path": path.relative_to(output_path).as_posix(), + **runner._identity(path)}) + runner._write_json(output_path / "artifact-manifest.json", { + "schema": "creature-kernel.connected-foot-form-rejected-diagnostic-artifacts.v1", + "files": files, + }) + return 1 + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="FOOT-004 rejected diagnostic") + parser.add_argument("--snapshot", required=True) + parser.add_argument("--output", required=True) + args = parser.parse_args() + raise SystemExit(main(args.snapshot, args.output)) diff --git a/experiments/connected-leg-assembly/foot_form_trial.py b/experiments/connected-leg-assembly/foot_form_trial.py new file mode 100644 index 0000000..7dda44b --- /dev/null +++ b/experiments/connected-leg-assembly/foot_form_trial.py @@ -0,0 +1,229 @@ +"""Thin captured FOOT-004 static-surface adapter. + +The adapter is intentionally separate from the legacy FOOT-003 trial. It +rebuilds the calibrated root and connected legs from captured source inputs, +passes one complete ``foot-form-inputs.json`` case row to +``foot_form_construction.build``, evaluates through the captured generic +Catmull--Clark helper, and renders only the resulting L2 surfaces. It does +not consume cached displayed meshes, run poses, binding, collision, or +acceptance checks. +""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path +import sys +from typing import Any, Mapping + +import runner + + +SOURCE = Path("source/experiments/connected-leg-assembly") +CASES = ("calibrated_ordinary_human", "calibrated_upright_anthropomorphic") + + +def _fail(message: str) -> None: + raise runner.RunnerError(message) + + +def _read(path: Path) -> tuple[Any, bytes]: + return runner._read_json(path) + + +def _case_row(document: Mapping[str, Any], case_id: str) -> Mapping[str, Any]: + rows = [row for row in document.get("cases", []) + if isinstance(row, Mapping) and row.get("id") == case_id] + if len(rows) != 1: + _fail(f"captured inputs lack unique case {case_id}") + return rows[0] + + +def _form_row(document: Mapping[str, Any], case_id: str) -> Mapping[str, Any]: + rows = [row for row in document.get("cases", []) + if isinstance(row, Mapping) and row.get("case_id") == case_id] + if len(rows) != 1: + _fail(f"foot-form inputs lack unique case {case_id}") + return rows[0] + + +def _source_base(snapshot: Path, manifest: Mapping[str, Any], + case: Mapping[str, Any], construction: Any, + root_source: Any) -> tuple[Mapping[str, Any], dict[str, Any]]: + case_id = str(case["id"]) + path_map = runner._path_map(manifest) + source_relative = path_map.get((case_id, "original_case")) + if source_relative is None: + _fail(f"captured path map lacks {case_id}.original_case") + source_case, _ = _read(runner._snapshot_path(snapshot, str(source_relative))) + rebuilt = root_source.reconstruct_source_case(source_case) + levels = rebuilt.get("levels") if isinstance(rebuilt, Mapping) else None + if not isinstance(levels, Mapping) or not isinstance(levels.get("L0"), Mapping): + _fail("root_source reconstruction must return an L0 mapping") + base = construction.build(levels["L0"], case["leg_inputs"]) + return base, { + "materialization": "source-rebuilt", + "root_provenance": rebuilt.get("provenance", {}), + "cache_role": "no cached displayed mesh consumed", + } + + +def _detail_mesh(mesh: Mapping[str, Any], cutoff_y: float = -0.50) -> dict[str, Any]: + """Select whole quads below the fixed world-Y detail cut without capping.""" + vertices = mesh["vertices"] + quads = mesh.get("quads", mesh.get("faces")) + selected = [list(face) for face in quads + if all(vertices[index][1] <= cutoff_y for index in face)] + if not selected: + _fail("FOOT-004 detail crop selected no complete faces") + original_indices = sorted({index for face in selected for index in face}) + remap = {old: new for new, old in enumerate(original_indices)} + return { + "schema": "creature-kernel.connected-foot-form-detail-mesh.v1", + "level": 2, + "vertices": [vertices[index] for index in original_indices], + "quads": [[remap[index] for index in face] for face in selected], + "metadata": { + "crop": "faces wholly within world Y <= -0.50", + "capped": False, + "original_vertex_indices": original_indices, + }, + } + + +def main(snapshot: str, output: str) -> int: + snapshot_path = Path(snapshot) + output_path = Path(output) + manifest = runner.verify(snapshot_path) + captured_trial = snapshot_path / SOURCE / "foot_form_trial.py" + if Path(__file__).resolve() != captured_trial.resolve(): + _fail("foot-form trial must execute from captured source") + if output_path.exists() or output_path.is_symlink(): + _fail(f"output must be absent: {output_path}") + + source_root = snapshot_path / SOURCE + inputs, inputs_raw = _read(source_root / "inputs.json") + form_document, form_raw = _read(source_root / "foot-form-inputs.json") + if not isinstance(inputs, Mapping) or not isinstance(form_document, Mapping): + _fail("captured input documents must be objects") + + dependency_before = runner._dependency_identity() + shared = runner._load_module("foot_construction", source_root / "foot_construction.py") + sys.modules["foot_construction"] = shared + construction = runner._load_module("construction", source_root / "construction.py") + root_source = runner._load_module("root_source", source_root / "root_source.py") + foot_form = runner._load_module("foot_form_construction", + source_root / "foot_form_construction.py") + renderer_path = Path(str(manifest["dependency"]["before"]["renderer"]["path"])) + renderer = runner._load_module("foot_form_frozen_renderer", renderer_path) + + output_path.mkdir(parents=True) + (output_path / "inputs.json").write_bytes(inputs_raw) + (output_path / "foot-form-inputs.json").write_bytes(form_raw) + (output_path / "runner-source.py").write_bytes((source_root / "runner.py").read_bytes()) + + results: list[dict[str, Any]] = [] + render_inputs: list[tuple[Path, Mapping[str, Any], Mapping[str, Any]]] = [] + for index, case_id in enumerate(CASES): + case_dir = output_path / "cases" / f"case-{index:02d}-{case_id}" + case_dir.mkdir(parents=True) + case = _case_row(inputs, case_id) + form_row = _form_row(form_document, case_id) + base, provenance = _source_base(snapshot_path, manifest, case, + construction, root_source) + output_l0 = foot_form.build(base, case["leg_inputs"], form_row) + levels = foot_form.evaluate(output_l0, levels=2) + for level, mesh in enumerate(levels): + runner._write_json(case_dir / f"foot-form-L{level}.json", + runner._jsonable(mesh)) + detail = _detail_mesh(levels[-1]) + runner._write_json(case_dir / "foot-detail-L2.json", + runner._jsonable(detail)) + result = { + "id": case_id, + "status": "STATIC CANDIDATE - PENDING COLLISION/VISUAL", + "accepted": False, + "materialization": provenance, + "base": {"vertices": len(output_l0["vertices"]), + "quads": len(output_l0["quads"])}, + "levels": [{"level": level, "vertices": len(mesh["vertices"]), + "quads": len(mesh["quads"])} + for level, mesh in enumerate(levels)], + "collision": "not-run", + "poses": "not-run", + } + runner._write_json(case_dir / "case-report.json", runner._jsonable(result)) + results.append(result) + render_inputs.append((case_dir, levels[-1], detail)) + + bounds = runner._bounds([mesh for _case_dir, mesh, _detail in render_inputs]) + detail_bounds = runner._bounds([detail for _case_dir, _mesh, detail in render_inputs]) + render_errors: list[dict[str, Any]] = [] + for case_dir, mesh, detail in render_inputs: + full_record = runner._render_one( + renderer, mesh, case_dir / "full-leg-context.png", case_dir.name, + "FOOT-004 STATIC CANDIDATE - PENDING COLLISION/VISUAL", + bounds, [], + ) + detail_record = runner._render_one( + renderer, detail, case_dir / "foot-detail.png", case_dir.name, + "FOOT-004 DETAIL - STATIC CANDIDATE - PENDING COLLISION/VISUAL", + detail_bounds, [], + ) + if full_record.get("status") == "exception": + render_errors.append({"case": case_dir.name, + "view": "full-leg-context", + "error": full_record.get("exception")}) + if detail_record.get("status") == "exception": + render_errors.append({"case": case_dir.name, + "view": "foot-detail", + "error": detail_record.get("exception")}) + for result in results: + if result["id"] in case_dir.name: + result["render"] = { + "full_leg_context": runner._jsonable(full_record), + "foot_detail": runner._jsonable(detail_record), + } + runner._write_json(case_dir / "case-report.json", + runner._jsonable(result)) + + dependency_after = runner._dependency_identity() + report = { + "schema": "creature-kernel.connected-foot-form-static-run.v1", + "status": "error" if render_errors else "static-candidate", + "accepted": False, + "geometry_execution": True, + "collision": "not-run", + "poses": "not-run", + "cases": results, + "bounds": bounds, + "render_errors": render_errors, + "dependency_before": dependency_before, + "dependency_after": dependency_after, + "dependency_drift": dependency_before != dependency_after, + "snapshot_manifest": runner._identity(snapshot_path / "manifest.json"), + "foot_form_inputs_sha256": hashlib.sha256(form_raw).hexdigest(), + } + runner._write_json(output_path / "run-report.json", runner._jsonable(report)) + files = [] + for path in sorted(output_path.rglob("*"), + key=lambda item: item.relative_to(output_path).as_posix()): + if path.is_file() and path.name != "artifact-manifest.json": + files.append({"path": path.relative_to(output_path).as_posix(), + **runner._identity(path)}) + runner._write_json(output_path / "artifact-manifest.json", { + "schema": "creature-kernel.connected-foot-form-static-artifacts.v1", + "files": files, + }) + return 1 if report["status"] == "error" else 0 + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Captured FOOT-004 static trial") + parser.add_argument("--snapshot", required=True) + parser.add_argument("--output", required=True) + args = parser.parse_args() + raise SystemExit(main(args.snapshot, args.output)) diff --git a/experiments/connected-leg-assembly/foot_junction_construction.py b/experiments/connected-leg-assembly/foot_junction_construction.py new file mode 100644 index 0000000..a9237b6 --- /dev/null +++ b/experiments/connected-leg-assembly/foot_junction_construction.py @@ -0,0 +1,668 @@ +"""JUNCTION-001 direct ankle-port / proximal-cage foot construction. + +This module owns one explicit local junction candidate. It reuses only the +pure FOOT-004 source-frame and bulk-grid helpers; it does not call either +FOOT-004/005 builder and then repair its output. The old eight-vertex dorsal +hole is a Dirichlet boundary for a coordinatewise harmonic displacement field. +The existing connected-leg ankle vertices remain the mouth vertices in the +result, so no collar or support ring is created here. + +Execution, L2 evaluation, collision, and visual acceptance remain downstream +capture work. This file deliberately has no post-L2 correction path. +""" +from __future__ import annotations + +from collections.abc import Mapping +import copy +import math +from typing import Any + +import foot_construction as _shared +import foot_form_construction as _bulk + + +_SIDES = ("left", "right") +_COMPONENTS = ("X", "U", "F") +_ROW_COUNT = 8 +_COLUMN_COUNT = 5 +_HOLE_POSITIONS = tuple(_shared._HOLE_BOUNDARY_POSITIONS) +_CENTRE_POSITION = (2, 2) +_COORDINATE_TOLERANCE = 1.0e-8 +_SOLVE_PIVOT_TOLERANCE = 1.0e-12 +_FACE_AREA_TOLERANCE = 1.0e-12 + + +class FootJunctionConstructionError(ValueError): + """Raised when the explicit JUNCTION-001 contract is incoherent.""" + + +def _fail(message: str) -> None: + raise FootJunctionConstructionError(message) + + +def _mapping(value: Any, where: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping): + _fail(f"{where} must be a mapping") + return value + + +def _finite(value: Any, where: str) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float)): + _fail(f"{where} must be a finite real number") + result = float(value) + if not math.isfinite(result): + _fail(f"{where} must be a finite real number") + return result + + +def _vector(value: Any, where: str) -> tuple[float, float, float]: + if type(value) not in (list, tuple) or len(value) != 3: + _fail(f"{where} must be a three-component vector") + return tuple(_finite(item, f"{where}[{index}]") + for index, item in enumerate(value)) # type: ignore[return-value] + + +def _add(left: tuple[float, float, float], + right: tuple[float, float, float]) -> tuple[float, float, float]: + return tuple(left[index] + right[index] for index in range(3)) # type: ignore[return-value] + + +def _sub(left: tuple[float, float, float], + right: tuple[float, float, float]) -> tuple[float, float, float]: + return tuple(left[index] - right[index] for index in range(3)) # type: ignore[return-value] + + +def _scale(value: tuple[float, float, float], factor: float) -> tuple[float, float, float]: + return tuple(factor * item for item in value) # type: ignore[return-value] + + +def _dot(left: tuple[float, float, float], + right: tuple[float, float, float]) -> float: + return sum(left[index] * right[index] for index in range(3)) + + +def _cross(left: tuple[float, float, float], + right: tuple[float, float, float]) -> tuple[float, float, float]: + return ( + left[1] * right[2] - left[2] * right[1], + left[2] * right[0] - left[0] * right[2], + left[0] * right[1] - left[1] * right[0], + ) + + +def _norm(value: tuple[float, float, float]) -> float: + return math.sqrt(_dot(value, value)) + + +def _edge_key(left: int, right: int) -> tuple[int, int]: + return (left, right) if left < right else (right, left) + + +def _policy(raw: Any) -> dict[str, Any]: + value = _mapping(raw, "junction_policy") + required = {"schema", "candidate", "status", "source", "graph", + "constraints", "output", "budget"} + if set(value) != required: + _fail("junction_policy has unsupported or missing fields") + if value["schema"] != "creature-kernel.connected-leg-assembly-foot-junction-policy.v1": + _fail("junction_policy schema is not JUNCTION-001 v1") + if value["candidate"] != "JUNCTION-001": + _fail("junction_policy candidate must be JUNCTION-001") + if value["status"] != "prospective-static-only": + _fail("junction_policy status must remain prospective-static-only") + + source = _mapping(value["source"], "junction_policy.source") + if set(source) != {"bulk_origin", "pure_helpers", "forbidden_builders"}: + _fail("junction_policy.source has unsupported or missing fields") + if source["bulk_origin"] != "FOOT-004": + _fail("junction_policy must use the FOOT-004 bulk source") + if list(source["pure_helpers"]) != ["foot_form_construction._source_frame", + "foot_form_construction._grid_points"]: + _fail("junction_policy pure helper lineage is not the settled FOOT-004 seam") + if list(source["forbidden_builders"]) != ["foot_form_construction.build", + "foot_attachment_construction.build"]: + _fail("junction_policy must forbid old builder-then-repair paths") + + graph = _mapping(value["graph"], "junction_policy.graph") + if set(graph) != {"local_vertex_count", "body_quad_count", "row_names", + "columns", "frontier_row", "frontier_source", "hole_positions", + "omitted_position"}: + _fail("junction_policy.graph has unsupported or missing fields") + if graph["local_vertex_count"] != 79 or graph["body_quad_count"] != 74: + _fail("junction_policy graph must be the 79-vertex/74-quad FOOT-004 bulk graph") + if list(graph["row_names"]) != list(_bulk._ROW_NAMES): + _fail("junction_policy row names do not match FOOT-004") + if graph["columns"] != _COLUMN_COUNT or graph["frontier_row"] != 5 or graph["frontier_source"] != "M": + _fail("junction_policy must keep row 5=M as the distal frontier") + if [list(position) for position in graph["hole_positions"]] != [list(position) for position in _HOLE_POSITIONS]: + _fail("junction_policy hole positions do not match FOOT-004") + if list(graph["omitted_position"]) != list(_CENTRE_POSITION): + _fail("junction_policy omitted centre does not match FOOT-004") + + constraints = _mapping(value["constraints"], "junction_policy.constraints") + if set(constraints) != {"basis_order", "edge_weight", "fixed_rows", "plantar_u_rows", + "solver", "residual_tolerance"}: + _fail("junction_policy.constraints has unsupported or missing fields") + if list(constraints["basis_order"]) != list(_COMPONENTS): + _fail("junction_policy basis order must be X/U/F") + if constraints["edge_weight"] != "uniform_quad_edge": + _fail("junction_policy must use uniform quad-edge weights") + if list(constraints["fixed_rows"]) != [0, 5, 6, 7] or list(constraints["plantar_u_rows"]) != [1, 2, 3, 4]: + _fail("junction_policy fixed rows do not preserve row 5=M and plantar rows 1..4") + if constraints["solver"] != "coordinatewise_dirichlet_harmonic_no_regularizer": + _fail("junction_policy solver is not the settled displacement solve") + residual_tolerance = _finite(constraints["residual_tolerance"], "constraints.residual_tolerance") + if not residual_tolerance > 0.0: + _fail("constraints.residual_tolerance must be positive") + + output = _mapping(value["output"], "junction_policy.output") + if set(output) != {"omit_old_hole_vertices", "use_existing_actual_A_indices", + "connector_rings", "post_l2_correction"}: + _fail("junction_policy.output has unsupported or missing fields") + if output["omit_old_hole_vertices"] is not True or output["use_existing_actual_A_indices"] is not True: + _fail("junction_policy must use direct existing ankle-port vertices") + if output["connector_rings"] is not False or output["post_l2_correction"] is not False: + _fail("junction_policy cannot add connector rings or a post-L2 correction") + + budget = _mapping(value["budget"], "junction_policy.budget") + if set(budget) != {"initial_candidate_count", "shared_correction_max", + "parameter_search", "input_retuning"}: + _fail("junction_policy.budget has unsupported or missing fields") + if budget["initial_candidate_count"] != 1 or budget["shared_correction_max"] != 1: + _fail("junction_policy budget must be one initial candidate plus one correction") + if budget["parameter_search"] is not False or budget["input_retuning"] is not False: + _fail("junction_policy cannot authorize parameter search or input retuning") + return copy.deepcopy(dict(value)) + + +def _local_grid(grid: Mapping[str, Any]) -> dict[str, Any]: + top_points = grid["top"] + bottom_points = grid["bottom"] + top: list[list[int | None]] = [[None] * _COLUMN_COUNT for _ in range(_ROW_COUNT)] + bottom: list[list[int]] = [[] for _ in range(_ROW_COUNT)] + points: list[tuple[float, float, float]] = [] + rows: list[int] = [] + regions: list[str] = [] + + for row, row_points in enumerate(top_points): + for column, point in enumerate(row_points): + if (row, column) == _CENTRE_POSITION: + continue + index = len(points) + top[row][column] = index + points.append(tuple(point)) + rows.append(row) + regions.append("dorsal") + for row, row_points in enumerate(bottom_points): + for point in row_points: + index = len(points) + bottom[row].append(index) + points.append(tuple(point)) + rows.append(row) + regions.append("plantar") + if len(points) != 79: + _fail(f"FOOT-004 local grid produced {len(points)} vertices, expected 79") + if any(len(row) != _COLUMN_COUNT for row in bottom): + _fail("FOOT-004 local plantar grid is not eight rows of five vertices") + return {"top": top, "bottom": bottom, "points": points, + "rows": rows, "regions": regions} + + +def _body_faces(local: Mapping[str, Any]) -> dict[str, list[tuple[int, int, int, int]]]: + faces = { + "dorsal_grid": _shared._top_grid_faces(local["top"]), + "plantar_grid": _shared._bottom_grid_faces(local["bottom"]), + "outer_perimeter": _shared._outer_grid_faces(local["top"], local["bottom"]), + } + if sum(len(value) for value in faces.values()) != 74: + _fail("JUNCTION-001 local body graph does not contain 74 quads") + return faces + + +def _adjacency(vertex_count: int, faces: list[tuple[int, int, int, int]]) -> list[set[int]]: + adjacency = [set() for _ in range(vertex_count)] + for face_index, face in enumerate(faces): + if len(set(face)) != 4: + _fail(f"local face {face_index} repeats a vertex") + for corner, left in enumerate(face): + right = face[(corner + 1) % 4] + if left == right: + _fail(f"local face {face_index} has a zero-length edge") + adjacency[left].add(right) + adjacency[right].add(left) + if any(not neighbours for neighbours in adjacency): + _fail("JUNCTION-001 local graph contains an unused vertex") + return adjacency + + +def _components(adjacency: list[set[int]], nodes: set[int]) -> list[list[int]]: + remaining = set(nodes) + result: list[list[int]] = [] + while remaining: + start = min(remaining) + pending = [start] + remaining.remove(start) + component = [] + while pending: + node = pending.pop() + component.append(node) + for neighbour in sorted(adjacency[node]): + if neighbour in remaining: + remaining.remove(neighbour) + pending.append(neighbour) + result.append(sorted(component)) + return result + + +def _solve_dense(matrix: list[list[float]], rhs: list[float], where: str, + residual_tolerance: float) -> tuple[list[float], float]: + size = len(rhs) + if size == 0: + return [], 0.0 + augmented = [list(row) + [rhs[index]] for index, row in enumerate(matrix)] + for column in range(size): + pivot_row = max(range(column, size), key=lambda row: abs(augmented[row][column])) + pivot = augmented[pivot_row][column] + if not math.isfinite(pivot) or abs(pivot) <= _SOLVE_PIVOT_TOLERANCE: + _fail(f"{where} has an undefined or singular harmonic system") + if pivot_row != column: + augmented[column], augmented[pivot_row] = augmented[pivot_row], augmented[column] + for row in range(column + 1, size): + factor = augmented[row][column] / augmented[column][column] + if factor == 0.0: + continue + for entry in range(column, size + 1): + augmented[row][entry] -= factor * augmented[column][entry] + solution = [0.0] * size + for row in range(size - 1, -1, -1): + tail = augmented[row][size] + for column in range(row + 1, size): + tail -= augmented[row][column] * solution[column] + solution[row] = tail / augmented[row][row] + if not math.isfinite(solution[row]): + _fail(f"{where} produced a non-finite displacement") + residual = 0.0 + for row in range(size): + residual = max(residual, abs(sum(matrix[row][column] * solution[column] + for column in range(size)) - rhs[row])) + if residual > residual_tolerance: + _fail(f"{where} residual {residual} exceeds {residual_tolerance}") + return solution, residual + + +def _harmonic_values(adjacency: list[set[int]], fixed: Mapping[int, float], + residual_tolerance: float, where: str) -> tuple[dict[int, float], dict[str, Any]]: + vertex_count = len(adjacency) + if any(index < 0 or index >= vertex_count for index in fixed): + _fail(f"{where} has a fixed vertex outside the graph") + free = set(range(vertex_count)) - set(fixed) + values = {index: float(value) for index, value in fixed.items()} + residuals: list[float] = [] + component_count = 0 + for component in _components(adjacency, free): + component_count += 1 + component_set = set(component) + boundary = sorted({neighbour for node in component + for neighbour in adjacency[node] if neighbour in fixed}) + if not boundary: + _fail(f"{where} free component {component[0]} has no Dirichlet boundary") + positions = {node: index for index, node in enumerate(component)} + matrix = [] + rhs = [] + for node in component: + row = [0.0] * len(component) + row[positions[node]] = float(len(adjacency[node])) + boundary_sum = 0.0 + for neighbour in sorted(adjacency[node]): + if neighbour in component_set: + row[positions[neighbour]] -= 1.0 + elif neighbour in fixed: + boundary_sum += values[neighbour] + else: # pragma: no cover - adjacency is the source of both sets + _fail(f"{where} encountered an unclassified graph neighbour") + matrix.append(row) + rhs.append(boundary_sum) + solution, residual = _solve_dense( + matrix, rhs, f"{where} component {component[0]}", residual_tolerance + ) + residuals.append(residual) + values.update({node: solution[index] for node, index in positions.items()}) + return values, { + "free_vertex_count": len(free), + "fixed_vertex_count": len(fixed), + "free_component_count": component_count, + "max_residual": max(residuals, default=0.0), + } + + +def _world_from_components(frame: Mapping[str, tuple[float, float, float]], + values: tuple[float, float, float]) -> tuple[float, float, float]: + return _add(_add(_scale(frame["X"], values[0]), _scale(frame["U"], values[1])), + _scale(frame["F"], values[2])) + + +def _displacements(local: Mapping[str, Any], faces: list[tuple[int, int, int, int]], + frame: Mapping[str, tuple[float, float, float]], + hole_local: list[int], hole_deltas: list[tuple[float, float, float]], + policy: Mapping[str, Any], side: str) -> tuple[list[tuple[float, float, float]], dict[str, Any]]: + if len(hole_local) != len(hole_deltas) or len(hole_local) != 8: + _fail(f"{side} junction needs eight hole/ankle displacement correspondences") + adjacency = _adjacency(len(local["points"]), faces) + rows = local["rows"] + fixed_rows = tuple(policy["constraints"]["fixed_rows"]) + plantar_rows = tuple(policy["constraints"]["plantar_u_rows"]) + residual_tolerance = float(policy["constraints"]["residual_tolerance"]) + hole_values = { + local_index: tuple(_dot(delta, frame[component]) for component in _COMPONENTS) + for local_index, delta in zip(hole_local, hole_deltas) + } + component_values: dict[str, dict[int, float]] = {} + solve_records: dict[str, dict[str, Any]] = {} + for component_index, component in enumerate(_COMPONENTS): + fixed: dict[int, float] = {} + for index, row in enumerate(rows): + if row in fixed_rows: + fixed[index] = 0.0 + for index, delta in hole_values.items(): + if index in fixed: + _fail(f"{side} hole displacement overlaps an all-coordinate fixed row") + fixed[index] = delta[component_index] + if component == "U": + for index, row in enumerate(rows): + if local["regions"][index] == "plantar" and row in plantar_rows: + if index in fixed and abs(fixed[index]) > _COORDINATE_TOLERANCE: + _fail(f"{side} plantar U constraint conflicts with a Dirichlet value") + fixed[index] = 0.0 + values, record = _harmonic_values( + adjacency, fixed, residual_tolerance, f"{side} {component} displacement" + ) + component_values[component] = values + solve_records[component] = record + + displacements = [tuple(component_values[component][index] + for component in _COMPONENTS) + for index in range(len(local["points"]))] + return displacements, { + "basis_order": list(_COMPONENTS), + "fixed_rows": list(fixed_rows), + "plantar_u_rows": list(plantar_rows), + "hole_local_displacements": [list(delta) for delta in hole_deltas], + "hole_local_components": [list(hole_values[index]) for index in hole_local], + "component_solves": solve_records, + "max_residual": max(record["max_residual"] for record in solve_records.values()), + } + + +def _triangle_normal(vertices: list[tuple[float, float, float]], + face: tuple[int, int, int, int], where: str) -> tuple[float, float, float]: + first = _cross(_sub(vertices[face[1]], vertices[face[0]]), + _sub(vertices[face[2]], vertices[face[0]])) + second = _cross(_sub(vertices[face[2]], vertices[face[0]]), + _sub(vertices[face[3]], vertices[face[0]])) + if _norm(first) <= _FACE_AREA_TOLERANCE or _norm(second) <= _FACE_AREA_TOLERANCE: + _fail(f"{where} has a degenerate triangle") + if _dot(first, second) <= 0.0: + _fail(f"{where} has a local quad fold") + return first + + +def _validate_side_output(vertices: list[tuple[float, float, float]], + quads: list[tuple[int, int, int, int]], + new_faces: list[int], actual_loop: list[int], side: str) -> None: + if len(new_faces) != 74: + _fail(f"{side} JUNCTION-001 output does not contain 74 new body quads") + for face_index in new_faces: + face = quads[face_index] + if len(set(face)) != 4: + _fail(f"{side} junction face {face_index} repeats a mouth or body vertex") + _triangle_normal(vertices, face, f"{side} junction face {face_index}") + if len(set(actual_loop)) != 8: + _fail(f"{side} ankle mouth repeats an existing port vertex") + uses = _shared._edge_uses(quads) + for index, left in enumerate(actual_loop): + edge = _edge_key(left, actual_loop[(index + 1) % len(actual_loop)]) + if len(uses.get(edge, ())) != 2: + _fail(f"{side} ankle mouth edge {edge} is not welded to exactly two quads") + + +def _map_local_face(face: tuple[int, int, int, int], local_to_output: Mapping[int, int], + hole_to_actual: Mapping[int, int], where: str) -> tuple[int, int, int, int]: + mapped = tuple(hole_to_actual.get(index, local_to_output.get(index, -1)) for index in face) + if any(index < 0 for index in mapped): + _fail(f"{where} references a local vertex that was not retained or mapped to A") + if len(set(mapped)) != 4: + _fail(f"{where} maps to a duplicate output vertex") + return mapped # type: ignore[return-value] + + +def build(base_mesh: Mapping[str, Any], leg_inputs: Mapping[str, Any], + foot_form_inputs: Mapping[str, Any], policy: Mapping[str, Any]) -> dict[str, Any]: + """Build JUNCTION-001 from an expanded connected-leg L0 and one FOOT-004 case.""" + settled_policy = _policy(policy) + leg_rows = _shared._validate_leg_inputs(leg_inputs) + form = _bulk._parse_form_inputs(foot_form_inputs) + base_vertices, base_quads, base_loops, base_vertex_count, base_face_count = ( + _shared._validate_base_mesh(base_mesh, leg_rows) + ) + base_metadata = _mapping(base_mesh["metadata"], "base_mesh.metadata") + if base_metadata.get("feet") not in (None, {}): + _fail("JUNCTION-001 expects an L0 without an already-attached foot") + output_vertices = [list(point) for point in base_vertices] + output_quads = [list(face) for face in base_quads] + output_face_owners = list(base_mesh["face_owners"]) + output_control_owners = list(base_mesh["control_owners"]) + base_control_owners = list(base_metadata["base_control_owners"]) + if len(base_control_owners) != base_vertex_count: + _fail("base_mesh metadata base_control_owners does not match the L0 prefix") + output_loops = { + name: list(loop) for name, loop in base_loops.items() + if name not in _shared._ANKLE_PORTS.values() + } + metadata = copy.deepcopy(dict(base_metadata)) + metadata["level"] = 0 + metadata["base_control_owners"] = base_control_owners + metadata["base_vertex_count"] = len(base_control_owners) + metadata["feet"] = {} + index_mapping = copy.deepcopy(metadata.get("index_mapping", {})) + new_face_indices_by_side: dict[str, list[int]] = {} + + for side in _SIDES: + ankle_loop, ankle_centre, attachment_frame = _shared._ankle_chain( + base_mesh, side, leg_rows[side], base_vertices, base_loops + ) + source_frame = _bulk._source_frame(base_mesh, side, attachment_frame) + controls = form["sides"][side] + grid = _bulk._grid_points( + ankle_centre, source_frame, + {name: controls[name] for name in _bulk._ANCHORS}, + form["construction"], side, + ) + local = _local_grid(grid) + faces_by_name = _body_faces(local) + body_faces = [face for name in ("dorsal_grid", "plantar_grid", "outer_perimeter") + for face in faces_by_name[name]] + hole_local = [local["top"][row][column] + for row, column in _HOLE_POSITIONS] + if any(index is None for index in hole_local): + _fail(f"{side} JUNCTION-001 hole correspondence contains a missing local vertex") + hole_local = [int(index) for index in hole_local] + hole_points = [grid["top"][row][column] for row, column in _HOLE_POSITIONS] + correspondence = _shared._correspondence( + ankle_loop, base_vertices, ankle_centre, attachment_frame, + hole_points, _shared._HOLE_BOUNDARY_NAMES, side, + ) + semantic_ankle = list(correspondence["target_to_ankle_indices"]) + direction = int(correspondence["direction"]) + ankle_winding = _shared._loop_winding(base_quads, ankle_loop, side) + if len(semantic_ankle) != len(ankle_loop) or set(semantic_ankle) != set(ankle_loop): + _fail(f"{side} JUNCTION-001 correspondence is not a permutation of the ankle loop") + if ankle_winding * direction != 1: + _fail(f"{side} JUNCTION-001 direct mouth phase/winding is incompatible") + # _correspondence already returns global vertex IDs, not offsets into + # ankle_loop. Keep its semantic phase/order while validating that it + # is exactly a permutation of the declared port. + actual_loop = list(semantic_ankle) + hole_deltas = [_sub(base_vertices[actual_loop[index]], hole_points[index]) + for index in range(8)] + displacements, solve_metadata = _displacements( + local, body_faces, source_frame, hole_local, hole_deltas, + settled_policy, side, + ) + moved_points = [ + _add(local["points"][index], + _world_from_components(source_frame, displacements[index])) + for index in range(len(local["points"])) + ] + + hole_to_actual = dict(zip(hole_local, actual_loop)) + local_to_output: dict[int, int] = {} + new_vertices: list[int] = [] + for local_index, point in enumerate(moved_points): + if local_index in hole_to_actual: + continue + output_index = len(output_vertices) + local_to_output[local_index] = output_index + output_vertices.append(list(point)) + output_control_owners.append(_shared._FOOT_OWNERS[side]) + base_control_owners.append(_shared._FOOT_OWNERS[side]) + new_vertices.append(output_index) + + new_faces: list[int] = [] + face_ranges: dict[str, list[int]] = {} + for name in ("dorsal_grid", "plantar_grid", "outer_perimeter"): + face_ranges[name] = [] + for face in faces_by_name[name]: + mapped = _map_local_face( + face, local_to_output, hole_to_actual, + f"{side} {name} face", + ) + output_face_owners.append(_shared._FOOT_OWNERS[side]) + output_quads.append(list(mapped)) + face_index = len(output_quads) - 1 + face_ranges[name].append(face_index) + new_faces.append(face_index) + output_vertices_typed = [_vector(point, f"output.vertices[{index}]") + for index, point in enumerate(output_vertices)] + output_quads_typed = [tuple(face) for face in output_quads] + _validate_side_output(output_vertices_typed, output_quads_typed, new_faces, + actual_loop, side) + new_face_indices_by_side[side] = new_faces + + old_grid_indices = { + "dorsal": [list(row) for row in local["top"]], + "plantar": [list(row) for row in local["bottom"]], + } + output_grid_indices = { + "dorsal": [ + [None if index is None else ( + hole_to_actual[index] if index in hole_to_actual + else local_to_output[index] + ) + for index in row] + for row in local["top"] + ], + "plantar": [[local_to_output[index] for index in row] + for row in local["bottom"]], + } + source_baseline = { + "case_id": form["case_id"], + "construction": copy.deepcopy(form["construction"]), + "local_controls": copy.deepcopy(controls), + "longitudinal_rows": copy.deepcopy(grid["rows"]), + "pure_helpers": ["foot_form_construction._source_frame", + "foot_form_construction._grid_points"], + "control_semantics": { + "H": "FOOT-004 rear heel surface-centre control", + "R": "FOOT-004 ankle-body surface-centre control; not a joint", + "rL_rD_rP": "FOOT-004 local-normal bulk-section radii; not mouth/aperture dimensions", + }, + "coordinates": "authoritative FOOT-004 foot-rest X/U/F; U constraint is mixed-coordinate, not a full world-rest differential", + } + metadata["feet"][side] = { + "owner": _shared._FOOT_OWNERS[side], + "ankle_source_loop": list(ankle_loop), + "junction_mouth_loop": list(actual_loop), + "old_grid_indices": old_grid_indices, + "output_grid_indices": output_grid_indices, + "omitted_old_hole_local_indices": list(hole_local), + "hole_boundary_positions": [list(position) for position in _HOLE_POSITIONS], + "new_vertex_indices": list(new_vertices), + "new_face_indices": list(new_faces), + "face_owner_ranges": face_ranges, + "correspondence": { + "target_order": list(_shared._HOLE_BOUNDARY_NAMES), + "old_hole_to_actual_A": [ + {"old_local_index": hole_local[index], + "actual_A_index": actual_loop[index], + "old_point": list(hole_points[index]), + "actual_point": list(base_vertices[actual_loop[index]]), + "world_displacement": list(hole_deltas[index])} + for index in range(8) + ], + "direction": direction, + "attached_ankle_loop_winding": ankle_winding, + }, + "frames": { + "attachment": {key: list(value) for key, value in attachment_frame.items()}, + "source": {key: list(value) for key, value in source_frame.items()}, + "origin": list(ankle_centre), + }, + "source_baseline": source_baseline, + "displacement_solve": solve_metadata, + "method": { + "candidate": "JUNCTION-001 direct owned-port plus coupled proximal-cage displacement", + "graph": "79 FOOT-004 local vertices and 74 uniform quad-edge body faces", + "frontier_row": "row 5=M; rows 5+ are all-coordinate Dirichlet zero", + "plantar_constraint": "rows 1..4 hold local U displacement at zero; X/F remain harmonic unknowns", + "hole_boundary": "actual A minus old H is prescribed in X/U/F", + "output": "old H vertices omitted; existing A indices used directly; no collar/support connector rings", + "binding": "incoming leg controls and A ownership/stencils/coordinates are unchanged; no ankle joint", + }, + "gates": { + "l0_topology_and_local_quad_fold": "implemented in this constructor", + "l2_stencils_source_response_and_intersections": "pending captured downstream execution", + "visual_and_anatomical_acceptance": "not evaluated", + }, + } + index_mapping[f"{side}_foot_junction_new_vertices"] = list(new_vertices) + index_mapping[f"{side}_foot_junction_new_faces"] = list(new_faces) + + metadata["base_vertex_count"] = len(base_control_owners) + metadata["index_mapping"] = index_mapping + metadata["scheme"] = copy.deepcopy(metadata.get("scheme", {})) + metadata["scheme"]["foot_junction"] = { + "candidate": "JUNCTION-001", + "source": "FOOT-004 pure source-frame/grid helpers", + "graph": "79 local vertices, 74 body quads, row 5=M frontier", + "displacement": "uniform quad-edge coordinatewise Dirichlet harmonic solve in foot-rest X/U/F", + "mouth": "existing actual ankle A indices replace the eight old dorsal H slots", + "connector_rings": False, + "post_l2_correction": False, + } + output = { + "schema": "creature-kernel.connected-leg-assembly-foot-junction-mesh.v1", + "level": 0, + "vertices": output_vertices, + "quads": output_quads, + "face_owners": output_face_owners, + "control_owners": output_control_owners, + "loops": output_loops, + "base_stencils": copy.deepcopy(base_mesh["base_stencils"]) + [ + [[index, 1.0]] for index in range(base_vertex_count, len(output_vertices)) + ], + "frames": copy.deepcopy(base_mesh["frames"]), + "metadata": metadata, + } + if output["vertices"][:base_vertex_count] != [list(point) for point in base_mesh["vertices"]]: + _fail("JUNCTION-001 changed the inherited L0 vertex prefix") + if output["quads"][:base_face_count] != [list(face) for face in base_mesh["quads"]]: + _fail("JUNCTION-001 changed the inherited L0 face prefix") + output_vertices_typed = [_vector(point, f"output.vertices[{index}]") + for index, point in enumerate(output["vertices"])] + output_quads_typed = [tuple(face) for face in output["quads"]] + _shared._validate_topology(output_vertices_typed, output_quads_typed, + output["loops"], "JUNCTION-001 output") + return output + + +__all__ = ["FootJunctionConstructionError", "build"] diff --git a/experiments/connected-leg-assembly/foot_trial.py b/experiments/connected-leg-assembly/foot_trial.py new file mode 100644 index 0000000..9e2fb65 --- /dev/null +++ b/experiments/connected-leg-assembly/foot_trial.py @@ -0,0 +1,324 @@ +"""Thin captured static-foot trial around the existing evidence helpers. + +This adapter owns only case selection, immutable-parent provenance, output +serialization, and frozen-renderer calls. Foot validation and Catmull--Clark +evaluation remain in ``foot_construction`` and the captured ``construction``. +No poses, weights, or collision acceptance are introduced here. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any, Mapping + +import runner + + +SOURCE = Path("source/experiments/connected-leg-assembly") +CASES = ("calibrated_ordinary_human", "calibrated_upright_anthropomorphic") +PARENT_ENV = "CONNECTED_LEG_PARENT_RUN" + + +def _fail(message: str) -> None: + raise runner.RunnerError(message) + + +def _identity(path: Path) -> dict[str, Any]: + return {"path": str(path), **runner._identity(path)} + + +def _read(path: Path) -> tuple[Any, bytes]: + return runner._read_json(path) + + +def _parent_base(parent: Path, index: int, case_id: str) -> Path: + return parent / "cases" / f"case-{index:02d}-{case_id}" / "base.json" + + +def _parent_inputs(parent: Path, case_id: str, raw: bytes, + document: dict[str, Any]) -> dict[str, Any]: + path = parent / "inputs.json" + parent_value, parent_raw = _read(path) + if parent_raw != raw or parent_value != document: + _fail("005 parent inputs differ from captured inputs") + rows = [row for row in document.get("cases", []) + if isinstance(row, dict) and row.get("id") == case_id] + if len(rows) != 1: + _fail(f"005 parent inputs lack unique case {case_id}") + return rows[0] + + +def _manifest_hash(parent: Path, relative: str) -> str: + value, _ = _read(parent / "artifact-manifest.json") + rows = value.get("files", []) if isinstance(value, dict) else [] + matches = [row for row in rows if isinstance(row, dict) and row.get("path") == relative] + if len(matches) != 1 or not isinstance(matches[0].get("sha256"), str): + _fail(f"005 artifact manifest lacks {relative}") + return str(matches[0]["sha256"]) + + +def _install_rejection_capture(foot: Any) -> tuple[dict[str, Any], Any]: + """Capture the validator payload while preserving the validator outcome. + + This is a diagnostic-only adapter for a post-failure preservation run. It + does not relax, replace, or reorder production validation: the original + ``_validate_output`` is called with the original arguments and its + exception is re-raised. The retained object is the exact candidate L0 + handed to that validator, before any test, binding, collision, pose, or + acceptance gate. + """ + original = getattr(foot, "_validate_output", None) + if not callable(original): + _fail("foot construction has no _validate_output interception point") + captured: dict[str, Any] = {"calls": 0, "payload": None, "error": None} + + def capture(*args: Any, **kwargs: Any) -> Any: + captured["calls"] += 1 + if args: + captured["payload"] = args[0] + try: + return original(*args, **kwargs) + except Exception as exc: + captured["error"] = { + "type": type(exc).__name__, "message": str(exc), + } + raise + + foot._validate_output = capture + return captured, original + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Captured static foot candidate") + parser.add_argument("--snapshot", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--parent-run", default=None) + args = parser.parse_args(argv) + + snapshot = Path(args.snapshot) + output = Path(args.output) + parent = Path(args.parent_run or __import__("os").environ.get(PARENT_ENV, "")) + captured_trial = snapshot / SOURCE / "foot_trial.py" + if Path(__file__).resolve() != captured_trial.resolve(): + _fail("foot trial must execute from captured source") + manifest = runner.verify(snapshot) + if output.exists() or output.is_symlink(): + _fail(f"output must be absent: {output}") + if not parent.is_dir() or parent.is_symlink(): + _fail(f"parent run must be a regular directory: {parent}") + + source_root = snapshot / SOURCE + inputs, inputs_raw = _read(source_root / "inputs.json") + foot_inputs, foot_inputs_raw = _read(source_root / "foot-inputs.json") + if not isinstance(inputs, dict) or not isinstance(foot_inputs, dict): + _fail("captured inputs are not objects") + foot_rows = {row.get("case_id"): row.get("sides") + for row in foot_inputs.get("cases", []) + if isinstance(row, dict)} + if set(foot_rows) != set(CASES): + _fail("foot inputs are not exactly the two calibrated cases") + parent_rows = [_parent_inputs(parent, case_id, inputs_raw, inputs) + for case_id in CASES] + parent_bases = [_parent_base(parent, index, case_id) + for index, case_id in enumerate(CASES)] + parent_before = [_identity(path) for path in [parent / "inputs.json", *parent_bases]] + for index, path in enumerate(parent_bases): + relative = f"cases/case-{index:02d}-{CASES[index]}/base.json" + if _manifest_hash(parent, relative) != parent_before[index + 1]["sha256"]: + _fail(f"005 parent base identity differs from its artifact manifest: {path}") + + dependency_before = runner._dependency_identity() + construction = runner._load_module("construction", source_root / "construction.py") + foot = runner._load_module("foot_construction", source_root / "foot_construction.py") + validation_capture, _original_validator = _install_rejection_capture(foot) + root_source_path = source_root / "root_source.py" + hip_source_path = source_root / "hip_source.py" + if root_source_path.exists() != hip_source_path.exists(): + _fail("root_source.py and hip_source.py must be captured together") + root_source = None + source_paths = runner._path_map(manifest) + if root_source_path.is_file(): + root_source = runner._load_module("root_source", root_source_path) + renderer_path = Path(str(manifest["dependency"]["before"]["renderer"]["path"])) + renderer = runner._load_module("foot_trial_frozen_renderer", renderer_path) + output.mkdir() + (output / "inputs.json").write_bytes(inputs_raw) + (output / "foot-inputs.json").write_bytes(foot_inputs_raw) + (output / "runner-source.py").write_bytes((source_root / "runner.py").read_bytes()) + results: list[dict[str, Any]] = [] + render_inputs: list[tuple[Path, Mapping[str, Any], int]] = [] + + for index, (case_id, parent_row, parent_base) in enumerate(zip(CASES, parent_rows, parent_bases)): + case_dir = output / "cases" / f"case-{index:02d}-{case_id}" + case_dir.mkdir(parents=True) + report: dict[str, Any] = {"id": case_id, "status": "error", "exceptions": []} + validation_capture.update({"calls": 0, "payload": None, "error": None}) + try: + base, _ = _read(parent_base) + leg_inputs = parent_row.get("leg_inputs") + foot_row = foot_rows[case_id] + if root_source is None: + leg_base = base + materialization = "legacy-cached-parent" + source_comparison = None + else: + source_relative = source_paths.get((case_id, "original_case")) + if source_relative is None: + _fail(f"captured path map lacks {case_id}.original_case for source rebuild") + source_case, _ = _read(runner._snapshot_path(snapshot, str(source_relative))) + rebuilt = root_source.reconstruct_source_case(source_case) + levels = rebuilt.get("levels") if isinstance(rebuilt, dict) else None + if not isinstance(levels, dict) or "L0" not in levels: + _fail("root_source reconstruction must return L0") + leg_base = construction.build(levels["L0"], leg_inputs) + materialization = "source-rebuilt" + source_comparison = { + "cache_role": "comparison-only; cached parent base is never a construction input", + "parent_base_exact": leg_base == base, + "root_provenance": rebuilt.get("provenance", {}), + } + output_l0 = foot.build(leg_base, leg_inputs, foot_row) + levels = foot.evaluate(output_l0, levels=2) + for level, mesh in enumerate(levels): + runner._write_json(case_dir / f"foot-L{level}.json", runner._jsonable(mesh)) + report.update({ + "status": "STATIC CANDIDATE - PENDING COLLISION/VISUAL", + "materialization": materialization, + "source_rebuild": source_comparison, + "parent_base": parent_before[index + 1], + "base": {"vertices": len(output_l0["vertices"]), "quads": len(output_l0["quads"])}, + "levels": [{"level": level, "vertices": len(mesh["vertices"]), + "quads": len(mesh["quads"])} for level, mesh in enumerate(levels)], + "render": None, + }) + render_inputs.append((case_dir, levels[-1], len(levels) - 1)) + except Exception as exc: + report["exceptions"].append({"type": type(exc).__name__, "message": str(exc)}) + retained = validation_capture.get("payload") + validator_error = validation_capture.get("error") + if retained is not None and validator_error is not None: + report.update({ + "status": "POST-FAILURE PRESERVATION - REJECTED L0 RETAINED", + "accepted": False, + "candidate_validation": { + "status": "failed", + "validator": "foot_construction._validate_output", + "calls": validation_capture.get("calls"), + "error": validator_error, + }, + "gates_not_run": [ + "connected-leg test suite", + "binding", + "collision", + "pose", + "whole-foot acceptance", + ], + "diagnostic_adapter": { + "purpose": "post-failure preservation", + "validator_behavior": "original validator called and exception re-raised", + "geometry_changed": False, + }, + }) + runner._write_json(case_dir / "rejected-foot-L0.json", + runner._jsonable(retained)) + try: + rejected_levels = foot.evaluate(retained, levels=2) + for level, mesh in enumerate(rejected_levels): + runner._write_json(case_dir / f"rejected-foot-L{level}.json", + runner._jsonable(mesh)) + report["diagnostic_evaluation"] = { + "status": "completed", + "levels": [{"level": level, + "vertices": len(mesh["vertices"]), + "quads": len(mesh["quads"])} + for level, mesh in enumerate(rejected_levels)], + } + render_inputs.append((case_dir, rejected_levels[-1], + len(rejected_levels) - 1)) + except Exception as evaluate_exc: + report["diagnostic_evaluation"] = { + "status": "failed", + "exception": {"type": type(evaluate_exc).__name__, + "message": str(evaluate_exc)}, + } + render_inputs.append((case_dir, retained, 0)) + report["rejected_l0"] = { + "path": str(case_dir / "rejected-foot-L0.json"), + "vertices": len(retained.get("vertices", [])), + "quads": len(retained.get("quads", [])), + } + runner._write_json(case_dir / "case-report.json", report) + results.append(report) + + bounds = runner._bounds([mesh for _path, mesh, _level in render_inputs]) if render_inputs else None + render_errors = [] + for case_dir, mesh, render_level in render_inputs: + record = runner._render_one(renderer, mesh, case_dir / "static.png", + str(case_dir.name), + f"POST-FAILURE PRESERVATION - REJECTED L{render_level}", + bounds, []) + record["source_level"] = render_level + if record.get("status") == "exception": + render_errors.append({"case": case_dir.name, "error": record["exception"]}) + for report in results: + if report["id"] in case_dir.name: + report["render"] = runner._jsonable(record) + runner._write_json(case_dir / "case-report.json", report) + + dependency_after = runner._dependency_identity() + parent_after = [_identity(path) for path in [parent / "inputs.json", *parent_bases]] + source_manifest_after = runner.verify(snapshot) + drift = dependency_before != dependency_after or parent_before != parent_after + candidate_failures = any( + row.get("candidate_validation", {}).get("status") == "failed" + for row in results + ) + status = ( + "error" if drift or render_errors else + "post-failure-preservation" if candidate_failures else + "static-candidate" + ) + report = { + "schema": "creature-kernel.connected-foot-static-run.v1", + "status": status, + "full_pass": False, + "accepted": False, + "capture_phase": "post-failure-preservation", + "pre_execution_capture": False, + "diagnostic_adapter": { + "source_path": str(source_root / "foot_trial.py"), + "source_identity": _identity(source_root / "foot_trial.py"), + "validator": "foot_construction._validate_output", + "behavior": "capture validator payload, call original, re-raise original failure", + }, + "collision": "pending_checker", + "visual": "pending_parent_appraisal", + "cases": results, + "bounds": bounds, + "render_errors": render_errors, + "parent_run": str(parent), + "parent_inputs": parent_before[0], + "parent_bases": parent_before[1:], + "parent_after": parent_after, + "dependency_before": dependency_before, + "dependency_after": dependency_after, + "dependency_drift": drift, + "snapshot_manifest": _identity(snapshot / "manifest.json"), + "source_manifest_verified": source_manifest_after.get("schema"), + "foot_inputs_sha256": hashlib.sha256(foot_inputs_raw).hexdigest(), + } + runner._write_json(output / "run-report.json", report) + files = [] + for path in sorted(output.rglob("*"), key=lambda item: item.relative_to(output).as_posix().encode()): + if path.is_file() and path.name != "artifact-manifest.json": + files.append({"path": path.relative_to(output).as_posix(), **runner._identity(path)}) + runner._write_json(output / "artifact-manifest.json", { + "schema": "creature-kernel.connected-foot-static-artifacts.v1", "files": files, + }) + return 1 if status in {"error", "post-failure-preservation"} else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/experiments/connected-leg-assembly/head-inputs.json b/experiments/connected-leg-assembly/head-inputs.json new file mode 100644 index 0000000..85cedc8 --- /dev/null +++ b/experiments/connected-leg-assembly/head-inputs.json @@ -0,0 +1,59 @@ +{ + "schema": "creature-kernel.connected-leg-assembly-head-inputs.v1", + "status": "initial-candidate-inputs-frozen", + "coordinate_convention": "metres; global X lateral, +Y up, +Z front", + "source_ownership": "neck origin and incoming radii come from stations.neck_upper in the original calibrated source case", + "budget": { + "initial_candidate_count": 1, + "shared_correction_max": 1, + "correction_condition": "only an evidence-justified shared correction after first execution", + "per_case_repairs": false, + "input_retuning_before_first_surface": false, + "alternative_constructions": false + }, + "cases": [ + { + "case_id": "calibrated_ordinary_human", + "head": { + "stations": { + "neck_support": {"up": 0.027, "radii": [0.052, 0.050, 0.050]}, + "jaw": {"up": 0.057, "radii": [0.072, 0.072, 0.063]}, + "cheek": {"up": 0.112, "radii": [0.095, 0.082, 0.078]}, + "brow": {"up": 0.167, "radii": [0.091, 0.075, 0.080]}, + "crown": {"up": 0.207, "radii": [0.070, 0.060, 0.062]} + }, + "crown_centre_up": 0.232, + "muzzle": null, + "ears": null + }, + "status_note": "bounded coarse human-like head hypothesis; not anthropometry" + }, + { + "case_id": "calibrated_upright_anthropomorphic", + "head": { + "stations": { + "neck_support": {"up": 0.027, "radii": [0.052, 0.050, 0.050]}, + "jaw": {"up": 0.057, "radii": [0.075, 0.080, 0.068]}, + "cheek": {"up": 0.112, "radii": [0.100, 0.090, 0.082]}, + "brow": {"up": 0.167, "radii": [0.095, 0.080, 0.085]}, + "crown": {"up": 0.207, "radii": [0.075, 0.062, 0.065]} + }, + "crown_centre_up": 0.227, + "muzzle": { + "length": 0.105, + "tip_halfwidth": 0.052, + "tip_halfheight": 0.026, + "tip_up_offset": 0.000 + }, + "ears": { + "tip_up": 0.140, + "lateral_outset": 0.018, + "base_halfwidth_x": 0.030, + "base_halfdepth_z": 0.010, + "tip_scale": 0.220 + } + }, + "status_note": "same generic construction with optional muzzle and upright pinnae; no species branch" + } + ] +} diff --git a/experiments/connected-leg-assembly/head-refinement-inputs.json b/experiments/connected-leg-assembly/head-refinement-inputs.json new file mode 100644 index 0000000..9bed4c5 --- /dev/null +++ b/experiments/connected-leg-assembly/head-refinement-inputs.json @@ -0,0 +1,56 @@ +{ + "schema": "creature-kernel.connected-leg-assembly-head-refinement-inputs.v1", + "status": "prospective-first-wholebody-refinement-batch", + "derivation": { + "vertical": "neck_support.up + 1.12 * (old_value - neck_support.up)", + "cranial_radii": "lateral * 1.15; anterior and posterior * 1.10", + "jaw_lateral": "the cranial lateral result * 1.10", + "preserved": ["neck_support", "source neck port", "source pivot", "base geometry", "topology", "ear phase"], + "note": "Prospective shared visual-calibration recipe, not an anatomy fact. Both cases use the same generic construction." + }, + "cases": [ + { + "case_id": "calibrated_ordinary_human", + "head": { + "stations": { + "neck_support": {"up": 0.027, "radii": [0.052, 0.05, 0.05]}, + "jaw": {"up": 0.0606, "radii": [0.09108, 0.0792, 0.0693]}, + "cheek": {"up": 0.1222, "radii": [0.10925, 0.0902, 0.0858]}, + "brow": {"up": 0.1838, "radii": [0.10465, 0.0825, 0.088]}, + "crown": {"up": 0.2286, "radii": [0.0805, 0.066, 0.0682]} + }, + "crown_centre_up": 0.2566, + "muzzle": null, + "ears": null + } + }, + { + "case_id": "calibrated_upright_anthropomorphic", + "head": { + "stations": { + "neck_support": {"up": 0.027, "radii": [0.052, 0.05, 0.05]}, + "jaw": {"up": 0.0606, "radii": [0.094875, 0.088, 0.0748]}, + "cheek": {"up": 0.1222, "radii": [0.115, 0.099, 0.0902]}, + "brow": {"up": 0.1838, "radii": [0.10925, 0.088, 0.0935]}, + "crown": {"up": 0.2286, "radii": [0.08625, 0.0682, 0.0715]} + }, + "crown_centre_up": 0.251, + "muzzle": { + "length": 0.09, + "tip_halfwidth": 0.058, + "tip_halfheight": 0.035, + "tip_up_offset": 0.0, + "support_halfwidth": 0.065, + "support_halfheight": 0.042 + }, + "ears": { + "tip_up": 0.11, + "lateral_outset": 0.025, + "base_halfwidth_x": 0.05, + "base_halfdepth_z": 0.012, + "tip_scale": 0.15 + } + } + } + ] +} diff --git a/experiments/connected-leg-assembly/head_construction.py b/experiments/connected-leg-assembly/head_construction.py new file mode 100644 index 0000000..d4c695c --- /dev/null +++ b/experiments/connected-leg-assembly/head_construction.py @@ -0,0 +1,655 @@ +"""Bounded six-phase connected head, muzzle, and coarse pinna construction.""" +from __future__ import annotations + +from collections.abc import Mapping +import copy +import json +import math +from pathlib import Path +from typing import Any + + +_PORT = "port.neck" +_OWNER = "domain.head" +_STATIONS = ("neck_support", "jaw", "cheek", "brow", "crown") +_PHASE_SET = {(-1.0, -1.0), (1.0, -1.0), (1.0, 0.0), + (1.0, 1.0), (-1.0, 1.0), (-1.0, 0.0)} +_TOL = 1.0e-8 +_AREA_TOL = 1.0e-12 +_REFINEMENT_SCHEMA = "creature-kernel.connected-leg-assembly-head-refinement-inputs.v1" +_EAR_ATTACHMENT_FRACTION = 0.12 +_EAR_TRANSITION_RULE = { + "id": "host-decomposed-axial-relaxation-v1", + "attachment_fraction": _EAR_ATTACHMENT_FRACTION, + "section_fractions": [0.35, 0.68, 1.0], + "transverse_blends": [0.45, 0.85, 1.0], + "formula": ( + "C + f*axis_vector + ((1-f)/(1-a))*h_parallel " + "+ (1-blend)*h_perp + blend*ideal_transverse_offset; " + "h=P-C, h_parallel=dot(h,axis)*axis, h_perp=h-h_parallel" + ), + "evidence_reference": { + "run": "INTEGRATED-REFINEMENT-001-rejected-diagnostic-001", + "artifact": "run/anthro/rejected-head-L0.json", + "raw_head_l0_sha256": "b8dfed686d7216c3ec5512e37bd39ce0e1a1108bd45f9d1a9fcb7b39a980214a", + "failed_quad": 673, + "raw_normal_dot": -1.6094300354600122e-7, + "normalized_normal_dot": -0.5826717579361298, + }, +} + + +class HeadConstructionError(ValueError): + """Raised when the bounded head candidate cannot be admitted.""" + + +def _fail(message: str) -> None: + raise HeadConstructionError(message) + + +def _mapping(value: Any, where: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping): + _fail(f"{where} must be a mapping") + return value + + +def _finite(value: Any, where: str) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float)): + _fail(f"{where} must be a finite real number") + result = float(value) + if not math.isfinite(result): + _fail(f"{where} must be a finite real number") + return result + + +def _positive(value: Any, where: str) -> float: + result = _finite(value, where) + if result <= 0.0: + _fail(f"{where} must be positive") + return result + + +def _vector(value: Any, where: str) -> tuple[float, float, float]: + if type(value) not in (list, tuple) or len(value) != 3: + _fail(f"{where} must be a three-component vector") + return tuple(_finite(item, f"{where}[{axis}]") + for axis, item in enumerate(value)) # type: ignore[return-value] + + +def _add(a: tuple[float, float, float], b: tuple[float, float, float]) -> tuple[float, float, float]: + return tuple(a[i] + b[i] for i in range(3)) # type: ignore[return-value] + + +def _sub(a: tuple[float, float, float], b: tuple[float, float, float]) -> tuple[float, float, float]: + return tuple(a[i] - b[i] for i in range(3)) # type: ignore[return-value] + + +def _scale(v: tuple[float, float, float], factor: float) -> tuple[float, float, float]: + return tuple(item * factor for item in v) # type: ignore[return-value] + + +def _dot(a: tuple[float, float, float], b: tuple[float, float, float]) -> float: + return sum(a[i] * b[i] for i in range(3)) + + +def _cross(a: tuple[float, float, float], b: tuple[float, float, float]) -> tuple[float, float, float]: + return (a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0]) + + +def _norm(v: tuple[float, float, float]) -> float: + return math.sqrt(_dot(v, v)) + + +def _normalise(v: tuple[float, float, float], where: str) -> tuple[float, float, float]: + length = _norm(v) + if not math.isfinite(length) or length <= _TOL: + _fail(f"{where} must have positive finite length") + return _scale(v, 1.0 / length) + + +def _edge(a: int, b: int) -> tuple[int, int]: + return (a, b) if a < b else (b, a) + + +def _edge_uses(quads: list[tuple[int, int, int, int]]) -> dict[tuple[int, int], list[tuple[int, int, int]]]: + uses: dict[tuple[int, int], list[tuple[int, int, int]]] = {} + for face_index, face in enumerate(quads): + for corner, left in enumerate(face): + right = face[(corner + 1) % 4] + uses.setdefault(_edge(left, right), []).append((face_index, left, right)) + return uses + + +def _quads(raw: Any, count: int, where: str) -> list[tuple[int, int, int, int]]: + if type(raw) not in (list, tuple) or not raw: + _fail(f"{where} must be a non-empty sequence") + result = [] + for index, face in enumerate(raw): + if type(face) not in (list, tuple) or len(face) != 4 or any(type(v) is not int for v in face): + _fail(f"{where}[{index}] must contain four integer indices") + checked = tuple(face) + if len(set(checked)) != 4 or any(v < 0 or v >= count for v in checked): + _fail(f"{where}[{index}] has invalid indices") + result.append(checked) + return result # type: ignore[return-value] + + +def _loops(raw: Any, count: int) -> dict[str, list[int]]: + value = _mapping(raw, "base_mesh.loops") + result = {} + for name, loop in value.items(): + if type(name) is not str or type(loop) not in (list, tuple) or len(loop) < 3: + _fail("base_mesh.loops contains an invalid entry") + checked = list(loop) + if len(set(checked)) != len(checked) or any(type(v) is not int or v < 0 or v >= count for v in checked): + _fail(f"base_mesh.loops.{name} has invalid indices") + result[name] = checked + return result + + +def _topology(vertices: list[tuple[float, float, float]], quads: list[tuple[int, int, int, int]], + loops: Mapping[str, list[int]], where: str) -> None: + uses = _edge_uses(quads) + if any(len(rows) not in (1, 2) for rows in uses.values()): + _fail(f"{where} has a non-manifold edge") + if any(len(rows) == 2 and rows[0][1:] == rows[1][1:] for rows in uses.values()): + _fail(f"{where} has an orientation conflict") + declared = set() + for name, loop in loops.items(): + for i, left in enumerate(loop): + edge = _edge(left, loop[(i + 1) % len(loop)]) + if len(uses.get(edge, ())) != 1 or edge in declared: + _fail(f"{where} loop {name!r} is not a unique boundary") + declared.add(edge) + if declared != {edge for edge, rows in uses.items() if len(rows) == 1}: + _fail(f"{where} named loops do not cover its boundary") + adjacency = {i: set() for i in range(len(vertices))} + for left, right in uses: + adjacency[left].add(right) + adjacency[right].add(left) + seen, pending = {0}, [0] + while pending: + current = pending.pop() + for neighbour in adjacency[current]: + if neighbour not in seen: + seen.add(neighbour) + pending.append(neighbour) + if len(seen) != len(vertices): + _fail(f"{where} is disconnected") + + +def _stencils(raw: Any, count: int) -> list[list[list[float | int]]]: + if type(raw) not in (list, tuple) or len(raw) != count: + _fail("base_mesh.base_stencils must cover every vertex") + result = [] + for row_index, row in enumerate(raw): + if type(row) not in (list, tuple) or not row: + _fail(f"base_mesh.base_stencils[{row_index}] is empty") + checked, previous, total = [], -1, 0.0 + for term in row: + if type(term) not in (list, tuple) or len(term) != 2 or type(term[0]) is not int: + _fail(f"base_mesh.base_stencils[{row_index}] is malformed") + source, coefficient = term[0], _finite(term[1], "stencil coefficient") + if source <= previous or source < 0 or coefficient <= 0.0: + _fail(f"base_mesh.base_stencils[{row_index}] is invalid") + checked.append([source, coefficient]) + previous, total = source, total + coefficient + if abs(total - 1.0) > 1.0e-9: + _fail(f"base_mesh.base_stencils[{row_index}] does not partition unity") + result.append(checked) + return result + + +def _source(source_case: Any) -> dict[str, Any]: + components = _mapping(_mapping(source_case, "source_case").get("components"), + "source_case.components") + prefix = "stations.neck_upper." + centre = tuple(_finite(components.get(f"{prefix}C.{axis}"), f"{prefix}C.{axis}") + for axis in "xyz") + pivot_prefix = "stations.neck_collar." + pivot = tuple(_finite(components.get(f"{pivot_prefix}C.{axis}"), + f"{pivot_prefix}C.{axis}") for axis in "xyz") + return {"centre": centre, + "pivot": pivot, + "rL": _positive(components.get(f"{prefix}rL"), f"{prefix}rL"), + "rA": _positive(components.get(f"{prefix}rA"), f"{prefix}rA"), + "rP": _positive(components.get(f"{prefix}rP"), f"{prefix}rP")} + + +def _feature(raw: Any, keys: set[str], where: str) -> dict[str, float] | None: + if raw is None: + return None + row = _mapping(raw, where) + if set(row) != keys: + _fail(f"{where} has unsupported or missing fields") + return {key: _positive(row[key], f"{where}.{key}") if key != "tip_up_offset" + else _finite(row[key], f"{where}.{key}") for key in keys} + + +def _muzzle_feature(raw: Any) -> dict[str, float] | None: + if raw is None: + return None + base_keys = {"length", "tip_halfwidth", "tip_halfheight", "tip_up_offset"} + support_keys = {"support_halfwidth", "support_halfheight"} + row = _mapping(raw, "head_inputs.muzzle") + if set(row) not in (base_keys, base_keys | support_keys): + _fail("head_inputs.muzzle has unsupported or missing fields") + result = {key: _positive(row[key], f"head_inputs.muzzle.{key}") + for key in (set(row) - {"tip_up_offset"})} + result["tip_up_offset"] = _finite(row["tip_up_offset"], "head_inputs.muzzle.tip_up_offset") + return result + + +def load_head_refinement_inputs(path: str | Path) -> dict[str, Any]: + """Load the explicit prospective head-refinement cases for later capture.""" + try: + value = json.loads(Path(path).read_text(encoding="utf-8"), + parse_constant=lambda token: (_ for _ in ()).throw(ValueError(token))) + except (OSError, UnicodeDecodeError, json.JSONDecodeError, ValueError) as exc: + _fail(f"invalid head refinement input document: {path}") + document = _mapping(value, "head refinement document") + if document.get("schema") != _REFINEMENT_SCHEMA: + _fail("head refinement document has an unsupported schema") + cases = document.get("cases") + if type(cases) is not list or not cases: + _fail("head refinement document must contain cases") + seen = set() + for index, case in enumerate(cases): + row = _mapping(case, f"head refinement cases[{index}]") + case_id = row.get("case_id") + if not isinstance(case_id, str) or not case_id or case_id in seen: + _fail("head refinement cases must have unique non-empty case_id values") + seen.add(case_id) + _inputs(row.get("head")) + return copy.deepcopy(dict(document)) + + +def head_inputs_for_refinement(path: str | Path, case_id: str) -> dict[str, Any]: + """Return one validated resulting head case from the captured document.""" + document = load_head_refinement_inputs(path) + for case in document["cases"]: + if case["case_id"] == case_id: + return copy.deepcopy(case["head"]) + _fail(f"head refinement document has no case: {case_id}") + + +def _inputs(raw: Any) -> dict[str, Any]: + value = _mapping(raw, "head_inputs") + if set(value) != {"stations", "crown_centre_up", "muzzle", "ears"}: + _fail("head_inputs has unsupported or missing fields") + stations = _mapping(value["stations"], "head_inputs.stations") + if set(stations) != set(_STATIONS): + _fail("head_inputs.stations must contain the five fixed stations") + parsed, previous = {}, 0.0 + for name in _STATIONS: + row = _mapping(stations[name], f"head_inputs.stations.{name}") + if set(row) != {"up", "radii"}: + _fail(f"head_inputs.stations.{name} has unsupported fields") + up = _positive(row["up"], f"{name}.up") + if up <= previous: + _fail("head station upward offsets must be strictly increasing") + radii = row["radii"] + if type(radii) not in (list, tuple) or len(radii) != 3: + _fail(f"{name}.radii must be [lateral, anterior, posterior]") + parsed[name] = {"up": up, "radii": tuple(_positive(v, f"{name}.radii") for v in radii)} + previous = up + crown_up = _positive(value["crown_centre_up"], "crown_centre_up") + if crown_up <= previous: + _fail("crown_centre_up must exceed the crown station") + muzzle = _muzzle_feature(value["muzzle"]) + ears = _feature(value["ears"], {"tip_up", "lateral_outset", "base_halfwidth_x", "base_halfdepth_z", "tip_scale"}, "head_inputs.ears") + if ears is not None and ears["tip_scale"] >= 1.0: + _fail("head_inputs.ears.tip_scale must be less than one") + return {"stations": parsed, "crown_centre_up": crown_up, "muzzle": muzzle, "ears": ears} + + +def _neck_port(source: Mapping[str, Any], vertices: list[tuple[float, float, float]], + loops: Mapping[str, list[int]]) -> tuple[list[int], list[tuple[float, float]]]: + loop = loops.get(_PORT) + if loop is None or len(loop) != 6: + _fail("base_mesh port.neck must contain six vertices") + centre = source["centre"] + phase = [] + for index in loop: + point = vertices[index] + if abs(point[1] - centre[1]) > _TOL: + _fail("actual neck port is not in its source plane") + x = (point[0] - centre[0]) / source["rL"] + radius = source["rA"] if point[2] >= centre[2] else source["rP"] + z = (point[2] - centre[2]) / radius + pair = tuple(0.0 if abs(v) <= _TOL else (1.0 if v > 0.0 else -1.0) for v in (x, z)) + if abs(x - pair[0]) > _TOL or abs(z - pair[1]) > _TOL: + _fail("actual neck port does not match source neck radii") + phase.append(pair) # type: ignore[arg-type] + if set(phase) != _PHASE_SET: + _fail("actual neck port does not have the required six-point rectangular phase") + return list(loop), phase + + +def _loop_winding(quads: list[tuple[int, int, int, int]], loop: list[int], where: str) -> int: + uses = _edge_uses(quads) + signs = [] + for i, left in enumerate(loop): + right = loop[(i + 1) % len(loop)] + rows = uses.get(_edge(left, right), ()) + if len(rows) != 1: + _fail(f"{where} is not a boundary") + signs.append(1 if rows[0][1:] == (left, right) else -1) + if len(set(signs)) != 1: + _fail(f"{where} winding is inconsistent") + return signs[0] + + +def _band(source: list[int], target: list[int], orientation: int) -> list[tuple[int, int, int, int]]: + if len(source) != len(target): + _fail("band rings must have equal sizes") + result = [] + for i in range(len(source)): + j = (i + 1) % len(source) + result.append((source[j], source[i], target[i], target[j]) if orientation == 1 + else (source[i], source[j], target[j], target[i])) + return result + + +def _six_ring(centre: tuple[float, float, float], radii: tuple[float, float, float], + phase: list[tuple[float, float]]) -> list[tuple[float, float, float]]: + lateral, anterior, posterior = radii + return [(centre[0] + pair[0] * lateral, centre[1], + centre[2] + pair[1] * (anterior if pair[1] >= 0.0 else posterior)) + for pair in phase] + + +def _append_ring(points: list[tuple[float, float, float]], vertices: list[list[float]], + control_owners: list[str], base_owners: list[str]) -> list[int]: + result = [] + for point in points: + result.append(len(vertices)) + vertices.append(list(point)) + control_owners.append(_OWNER) + base_owners.append(_OWNER) + return result + + +def _face_ok(vertices: list[list[float]], face: tuple[int, int, int, int]) -> bool: + points = [tuple(vertices[index]) for index in face] + first = _cross(_sub(points[1], points[0]), _sub(points[2], points[0])) + second = _cross(_sub(points[2], points[0]), _sub(points[3], points[0])) + return _norm(first) > _AREA_TOL and _norm(second) > _AREA_TOL and _dot(first, second) > 0.0 + + +def _host_loop(quads: list[tuple[int, int, int, int]], skipped: tuple[int, int, int, int], + where: str) -> tuple[list[int], int]: + loop = list(skipped) + return loop, _loop_winding(quads, loop, where) + + +def _muzzle_support_dimensions( + points: list[tuple[float, float, float]], + centre: tuple[float, float, float], + controls: Mapping[str, float], +) -> tuple[float, float, str]: + support_fields = {"support_halfwidth", "support_halfheight"} & set(controls) + if support_fields and support_fields != {"support_halfwidth", "support_halfheight"}: + _fail("muzzle support_halfwidth and support_halfheight must be supplied together") + if support_fields: + return controls["support_halfwidth"], controls["support_halfheight"], "explicit" + return ( + 0.5 * (max(abs(point[0] - centre[0]) for point in points) + controls["tip_halfwidth"]), + 0.5 * (max(abs(point[1] - centre[1]) for point in points) + controls["tip_halfheight"]), + "legacy-host-tip-average", + ) + + +def _append_muzzle(host: list[int], orientation: int, controls: Mapping[str, float], + vertices: list[list[float]], control_owners: list[str], base_owners: list[str]) -> tuple[list[int], list[tuple[int, int, int, int]], dict[str, Any]]: + points = [tuple(vertices[index]) for index in host] + centre = tuple(sum(point[axis] for point in points) / 4.0 for axis in range(3)) + phase = [(1.0 if point[0] > centre[0] else -1.0, + 1.0 if point[1] > centre[1] else -1.0) for point in points] + support_width, support_height, support_source = _muzzle_support_dimensions( + points, centre, controls + ) + rings = [] + for fraction, width, height in ((0.45, support_width, support_height), + (1.0, controls["tip_halfwidth"], controls["tip_halfheight"])): + ring_points = [(centre[0] + pair[0] * width, + centre[1] + controls["tip_up_offset"] * fraction + pair[1] * height, + centre[2] + controls["length"] * fraction) for pair in phase] + rings.append(_append_ring(ring_points, vertices, control_owners, base_owners)) + faces = _band(host, rings[0], orientation) + _band(rings[0], rings[1], orientation) + cap = tuple(reversed(rings[1])) if orientation == 1 else tuple(rings[1]) + faces.append(cap) # type: ignore[arg-type] + return [index for ring in rings for index in ring], faces, { + "host_indices": host, "support_indices": rings[0], "tip_indices": rings[1], + "host_phase_xy": [list(pair) for pair in phase], "support_source": support_source, + "controls": dict(controls)} + + +def _append_ear(side: str, host: list[int], orientation: int, controls: Mapping[str, float], + vertices: list[list[float]], control_owners: list[str], base_owners: list[str]) -> tuple[list[int], list[tuple[int, int, int, int]], dict[str, Any]]: + sign = -1.0 if side == "left" else 1.0 + points = [tuple(vertices[index]) for index in host] + centre = tuple(sum(point[axis] for point in points) / 4.0 for axis in range(3)) + axis_vector = (sign * controls["lateral_outset"], controls["tip_up"], 0.0) + axis = _normalise(axis_vector, f"{side} ear axis") + broad = _normalise(_sub((1.0, 0.0, 0.0), _scale(axis, axis[0])), f"{side} ear broad axis") + depth = _normalise(_cross(axis, broad), f"{side} ear depth axis") + vertical = [point[1] - centre[1] for point in points] + projected_depth = [_dot(_sub(point, centre), depth) for point in points] + if min(max(abs(v) for v in vertical), max(abs(v) for v in projected_depth)) <= _TOL: + _fail(f"{side} ear host cannot define corner phase") + phase = [(-sign * (1.0 if vertical[i] > 0.0 else -1.0), + 1.0 if projected_depth[i] > 0.0 else -1.0) for i in range(4)] + if len(set(phase)) != 4: + _fail(f"{side} ear host phase is ambiguous") + attachment_points = [_add(point, _scale(axis_vector, _EAR_ATTACHMENT_FRACTION)) + for point in points] + attachment = _append_ring(attachment_points, vertices, control_owners, base_owners) + rings = [] + for fraction, scale, blend in ((0.35, 1.0, 0.45), + (0.68, 0.65, 0.85), + (1.0, controls["tip_scale"], 1.0)): + ring_points = [] + for point, pair in zip(points, phase): + h = _sub(point, centre) + h_parallel = _scale(axis, _dot(h, axis)) + h_perp = _sub(h, h_parallel) + ideal_transverse_offset = _add( + _scale(broad, pair[0] * controls["base_halfwidth_x"] * scale), + _scale(depth, pair[1] * controls["base_halfdepth_z"] * scale), + ) + axial = _add( + centre, + _add( + _scale(axis_vector, fraction), + _scale( + h_parallel, + (1.0 - fraction) / (1.0 - _EAR_ATTACHMENT_FRACTION), + ), + ), + ) + transverse = _add( + _scale(h_perp, 1.0 - blend), + _scale(ideal_transverse_offset, blend), + ) + ring_points.append(_add(axial, transverse)) + rings.append(_append_ring(ring_points, vertices, control_owners, base_owners)) + faces = (_band(host, attachment, orientation) + _band(attachment, rings[0], orientation) + + _band(rings[0], rings[1], orientation) + + _band(rings[1], rings[2], orientation)) + cap = tuple(reversed(rings[2])) if orientation == 1 else tuple(rings[2]) + faces.append(cap) # type: ignore[arg-type] + return attachment + [index for ring in rings for index in ring], faces, { + "host_indices": host, "attachment_indices": attachment, + "section_indices": rings, "host_phase": [list(pair) for pair in phase], + "frame": {"axis": list(axis), "broad": list(broad), "depth": list(depth)}, + "transition_rule": copy.deepcopy(_EAR_TRANSITION_RULE), + "controls": dict(controls)} + + +def build(base_mesh: Mapping[str, Any], source_case: Mapping[str, Any], + head_inputs: Mapping[str, Any]) -> dict[str, Any]: + """Attach one source-owned six-phase coarse head; introduce no binding.""" + base = _mapping(base_mesh, "base_mesh") + required = {"vertices", "quads", "face_owners", "control_owners", "loops", + "base_stencils", "frames", "metadata"} + if not required.issubset(base) or base.get("level") != 0: + _fail("base_mesh must be a connected L0 mesh") + base_vertices = [_vector(point, f"base_mesh.vertices[{i}]") for i, point in enumerate(base["vertices"])] + base_quads = _quads(base["quads"], len(base_vertices), "base_mesh.quads") + loops = _loops(base["loops"], len(base_vertices)) + if len(base["face_owners"]) != len(base_quads) or len(base["control_owners"]) != len(base_vertices): + _fail("base_mesh owner arrays do not match its geometry") + _topology(base_vertices, base_quads, loops, "base_mesh") + stencils = _stencils(base["base_stencils"], len(base_vertices)) + source, controls = _source(source_case), _inputs(head_inputs) + neck_loop, phase = _neck_port(source, base_vertices, loops) + orientation = _loop_winding(base_quads, neck_loop, "neck port") + base_vertex_count, base_face_count = len(base_vertices), len(base_quads) + vertices = [list(point) for point in base_vertices] + quads = [list(face) for face in base_quads] + face_owners = list(base["face_owners"]) + control_owners = list(base["control_owners"]) + output_loops = {name: list(loop) for name, loop in loops.items() if name != _PORT} + metadata = copy.deepcopy(dict(_mapping(base["metadata"], "base_mesh.metadata"))) + base_owners = list(metadata.get("base_control_owners", base["control_owners"])) + if len(base_owners) != base_vertex_count: + _fail("base_mesh.metadata.base_control_owners does not match vertices") + + rings = {} + centres = {} + for name in _STATIONS: + row = controls["stations"][name] + centre = _add(source["centre"], (0.0, row["up"], 0.0)) + centres[name] = centre + rings[name] = _append_ring(_six_ring(centre, row["radii"], phase), + vertices, control_owners, base_owners) + + muzzle_enabled = controls["muzzle"] is not None + ears_enabled = controls["ears"] is not None + skipped: dict[str, tuple[int, int, int, int]] = {} + sequence = [("neck", neck_loop)] + [(name, rings[name]) for name in _STATIONS] + core_face_indices = [] + for (source_name, source_ring), (target_name, target_ring) in zip(sequence, sequence[1:]): + faces = _band(source_ring, target_ring, orientation) + for edge_index, face in enumerate(faces): + feature_name = None + if source_name == "jaw" and target_name == "cheek" and edge_index == phase.index((1.0, 1.0)): + feature_name = "muzzle" + if source_name == "brow" and target_name == "crown": + if edge_index == phase.index((-1.0, 0.0)): + feature_name = "left_ear" + elif edge_index == phase.index((1.0, -1.0)): + feature_name = "right_ear" + enabled = muzzle_enabled if feature_name == "muzzle" else ears_enabled if feature_name in ("left_ear", "right_ear") else False + if feature_name is not None and enabled: + skipped[feature_name] = face + continue + core_face_indices.append(len(quads)) + quads.append(list(face)) + face_owners.append(_OWNER) + + crown_centre = _add(source["centre"], (0.0, controls["crown_centre_up"], 0.0)) + crown_centre_index = len(vertices) + vertices.append(list(crown_centre)) + control_owners.append(_OWNER) + base_owners.append(_OWNER) + crown = rings["crown"] + crown_faces = [(crown[0], crown[1], crown[2], crown_centre_index), + (crown[2], crown[3], crown[4], crown_centre_index), + (crown[4], crown[5], crown[0], crown_centre_index)] + if orientation == 1: + crown_faces = [tuple(reversed(face)) for face in crown_faces] + for face in crown_faces: + core_face_indices.append(len(quads)) + quads.append(list(face)) + face_owners.append(_OWNER) + + features: dict[str, Any] = {"muzzle": {"enabled": False}, + "ears": {"enabled": False}} + feature_vertices, feature_faces = [], [] + if muzzle_enabled: + host, host_orientation = _host_loop(_quads(quads, len(vertices), "head core"), skipped["muzzle"], "muzzle host") + added_vertices, added_faces, detail = _append_muzzle(host, host_orientation, controls["muzzle"], vertices, control_owners, base_owners) + features["muzzle"] = {"enabled": True, **detail} + feature_vertices.extend(added_vertices) + for face in added_faces: + feature_faces.append(len(quads)); quads.append(list(face)); face_owners.append(_OWNER) + if ears_enabled: + ear_details = {} + for side in ("left", "right"): + key = f"{side}_ear" + host, host_orientation = _host_loop(_quads(quads, len(vertices), "head with feature openings"), skipped[key], key) + added_vertices, added_faces, detail = _append_ear(side, host, host_orientation, controls["ears"], vertices, control_owners, base_owners) + ear_details[side] = detail + feature_vertices.extend(added_vertices) + for face in added_faces: + feature_faces.append(len(quads)); quads.append(list(face)); face_owners.append(_OWNER) + features["ears"] = {"enabled": True, "sides": ear_details} + + new_face_indices = list(range(base_face_count, len(quads))) + if any(not _face_ok(vertices, tuple(quads[index])) for index in new_face_indices): + _fail("head contains a degenerate or folded quad") + new_vertex_indices = list(range(base_vertex_count, len(vertices))) + metadata["head"] = { + "owner": _OWNER, "neck_source": "stations.neck_upper", "neck_port_indices": neck_loop, + "neck_phase": [list(pair) for pair in phase], "winding": orientation, + "stations": [{"name": name, "centre": list(centres[name]), "indices": rings[name], + "radii_lateral_anterior_posterior": list(controls["stations"][name]["radii"])} + for name in _STATIONS], + "crown_centre": {"point": list(crown_centre), "index": crown_centre_index}, + "ear_transition_rule": (copy.deepcopy(_EAR_TRANSITION_RULE) + if ears_enabled else None), + "features": features, "new_vertex_indices": new_vertex_indices, + "new_face_indices": new_face_indices, "feature_vertex_indices": feature_vertices, + "feature_face_indices": feature_faces, + "binding_handoff": { + "joint": "neck_head", + "pivot_source": "stations.neck_collar.C", + "pivot": list(source["pivot"]), + "consumed_neck_port_indices": list(neck_loop), + "neck_support_ring_indices": list(rings["neck_support"]), + "head_new_vertex_indices": list(new_vertex_indices), + "feature_new_vertex_indices": list(feature_vertices), + }, + "binding": "not implemented", + } + metadata["base_control_owners"] = base_owners + metadata["base_vertex_count"] = len(vertices) + metadata["level"] = 0 + output = {"schema": "creature-kernel.connected-leg-assembly-head-mesh.v1", "level": 0, + "vertices": vertices, "quads": quads, "face_owners": face_owners, + "control_owners": control_owners, "loops": output_loops, + "base_stencils": stencils + [[[index, 1.0]] for index in new_vertex_indices], + "frames": copy.deepcopy(base["frames"]), "metadata": metadata} + _topology([tuple(point) for point in vertices], _quads(quads, len(vertices), "output.quads"), output_loops, "output") + if vertices[:base_vertex_count] != [list(point) for point in base_vertices] or quads[:base_face_count] != [list(face) for face in base_quads]: + _fail("output changed inherited geometry prefix") + return output + + +def evaluate(mesh: Mapping[str, Any], levels: int = 2) -> list[dict[str, Any]]: + """Delegate to the current generic connected-leg Catmull--Clark evaluator.""" + if type(levels) is not int or levels < 0 or levels > 2: + _fail("levels must be an integer from zero through two") + metadata = _mapping(mesh.get("metadata"), "mesh.metadata") if isinstance(mesh, Mapping) else {} + if not isinstance(metadata.get("head"), Mapping): + _fail("mesh must be a head-construction L0 output") + try: + import construction + return construction.evaluate(mesh, levels=levels) + except Exception as exc: + if isinstance(exc, HeadConstructionError): + raise + raise HeadConstructionError(f"generic evaluator rejected head output: {exc}") from exc + + +__all__ = [ + "HeadConstructionError", + "build", + "evaluate", + "head_inputs_for_refinement", + "load_head_refinement_inputs", +] diff --git a/experiments/connected-leg-assembly/hip_source.py b/experiments/connected-leg-assembly/hip_source.py new file mode 100644 index 0000000..4f6d503 --- /dev/null +++ b/experiments/connected-leg-assembly/hip_source.py @@ -0,0 +1,206 @@ +"""Source-driven bridge to the immutable frozen harmonic hip binder. + +This adapter owns input mapping and provenance only. It deliberately accepts +no prior binding and never reads cached weights from the connected-leg inputs. +""" + +from __future__ import annotations + +import copy +import hashlib +import importlib.util +import json +from collections.abc import Mapping +from pathlib import Path +import sys +from typing import Any + + +FROZEN_HIP_SNAPSHOT = Path( + "/home/ben/.cache/creature-kernel/pelvis-hip-articulation-harmonic-lbs-001-snapshot" +) +FROZEN_HIP_MANIFEST = FROZEN_HIP_SNAPSHOT / "manifest.json" +FROZEN_HIP_BINDING_RELATIVE = Path( + "source/experiments/pelvis-hip-articulation/binding.py" +) +FROZEN_HIP_BINDING = FROZEN_HIP_SNAPSHOT / FROZEN_HIP_BINDING_RELATIVE +FROZEN_HIP_MODULE = "ck_connected_leg_frozen_hip_binding" + + +class HipSourceError(ValueError): + """Raised when source inputs or frozen hip provenance are incoherent.""" + + +def _fail(message: str) -> None: + raise HipSourceError(message) + + +def _regular(path: Path, label: str) -> None: + try: + info = path.lstat() + except OSError as exc: + raise HipSourceError(f"{label} is unavailable: {path}") from exc + if path.is_symlink() or not path.is_file() or not info: + _fail(f"{label} must be a regular non-symlink file: {path}") + + +def _identity(path: Path) -> dict[str, Any]: + _regular(path, "frozen hip file") + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return {"bytes": path.stat().st_size, "sha256": digest.hexdigest()} + + +def _manifest() -> dict[str, Any]: + _regular(FROZEN_HIP_MANIFEST, "frozen hip manifest") + try: + value = json.loads(FROZEN_HIP_MANIFEST.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc: + raise HipSourceError(f"invalid frozen hip manifest: {FROZEN_HIP_MANIFEST}") from exc + if not isinstance(value, Mapping) or value.get("schema") != "creature-kernel.pelvis-hip-articulation-capture.v1": + _fail("frozen hip manifest schema is not admitted") + return dict(value) + + +def _binding_manifest_row(manifest: Mapping[str, Any]) -> Mapping[str, Any]: + captured = manifest.get("captured_source") + if not isinstance(captured, Mapping) or captured.get("before") != captured.get("after"): + _fail("frozen hip source manifest has drifted before/after inventories") + copies = captured.get("copies") + if not isinstance(copies, list): + _fail("frozen hip source manifest has no captured source copies") + row = next((item for item in copies + if isinstance(item, Mapping) + and item.get("snapshot_path") == FROZEN_HIP_BINDING_RELATIVE.as_posix()), None) + if not isinstance(row, Mapping): + _fail("frozen hip manifest lacks the captured binding module") + return row + + +def _load_frozen_binding() -> tuple[Any, dict[str, Any]]: + manifest = _manifest() + row = _binding_manifest_row(manifest) + before = _identity(FROZEN_HIP_BINDING) + expected = {"bytes": row.get("bytes"), "sha256": row.get("sha256")} + if before != expected: + _fail("frozen hip binding identity differs from its manifest") + spec = importlib.util.spec_from_file_location(FROZEN_HIP_MODULE, FROZEN_HIP_BINDING) + if spec is None or spec.loader is None: + _fail(f"unable to load frozen hip binding: {FROZEN_HIP_BINDING}") + module = importlib.util.module_from_spec(spec) + sys.modules[FROZEN_HIP_MODULE] = module + try: + spec.loader.exec_module(module) + except Exception: + if sys.modules.get(FROZEN_HIP_MODULE) is module: + sys.modules.pop(FROZEN_HIP_MODULE, None) + raise + if Path(str(module.__file__)).resolve() != FROZEN_HIP_BINDING.resolve(): + _fail("frozen hip binding resolved away from its snapshot path") + after = _identity(FROZEN_HIP_BINDING) + if before != after or after != expected: + _fail("frozen hip binding changed while being loaded") + return module, { + "frozen_helper_identity": { + "manifest_path": str(FROZEN_HIP_MANIFEST), + "path": str(FROZEN_HIP_BINDING), + "before": before, + "after": after, + }, + "binding_api": "bind(base_mesh, rest_mesh, case, reference_landmarks)", + } + + +def _vector(value: Any, label: str) -> list[float]: + if not isinstance(value, (list, tuple)) or len(value) != 3: + _fail(f"{label} must be a three-component vector") + result = [] + for index, item in enumerate(value): + if isinstance(item, bool) or not isinstance(item, (int, float)): + _fail(f"{label}[{index}] must be numeric") + result.append(float(item)) + return result + + +def _sides(value: Any, label: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping) or set(value) != {"left", "right"}: + _fail(f"{label} must contain exactly left and right") + return value + + +def _joints(explicit_j: Any, leg_inputs: Any) -> dict[str, list[float]]: + explicit: dict[str, list[float]] | None = None + if explicit_j is not None: + rows = _sides(explicit_j, "explicit_j") + explicit = {side: _vector(rows[side], f"explicit_j.{side}") + for side in ("left", "right")} + from_legs: dict[str, list[float]] | None = None + if leg_inputs is not None: + rows = _sides(leg_inputs, "leg_inputs") + from_legs = {} + for side in ("left", "right"): + row = rows[side] + if not isinstance(row, Mapping) or "J" not in row: + _fail(f"leg_inputs.{side}.J is required") + from_legs[side] = _vector(row["J"], f"leg_inputs.{side}.J") + if explicit is not None and from_legs is not None and explicit != from_legs: + _fail("explicit_j conflicts with leg_inputs.J") + if explicit is not None: + return explicit + if from_legs is not None: + return from_legs + _fail("explicit_j or leg_inputs is required") + + +def _source_case_inputs(source_case: Any, leg_inputs: Any) -> tuple[dict[str, Any], dict[str, list[float]]]: + if not isinstance(source_case, Mapping): + _fail("source_case must be a mapping") + components = source_case.get("components") + attachments = _sides(source_case.get("attachments"), "source_case.attachments") + if not isinstance(components, Mapping): + _fail("source_case.components must be a mapping") + case = copy.deepcopy(dict(source_case)) + expected_tk: dict[str, list[float]] = {} + for side in ("left", "right"): + attachment = attachments[side] + if not isinstance(attachment, Mapping) or "centre" not in attachment or "knee" not in attachment: + _fail(f"source_case.attachments.{side} must contain centre and knee") + expected_tk[side] = _vector(attachment["centre"], f"source_case.attachments.{side}.centre") + expected_tk[side + ".K"] = _vector(attachment["knee"], f"source_case.attachments.{side}.knee") + if leg_inputs is not None: + rows = _sides(leg_inputs, "leg_inputs") + for side in ("left", "right"): + row = rows[side] + if not isinstance(row, Mapping): + _fail(f"leg_inputs.{side} must be a mapping") + for field, source_key in (("T", "centre"), ("K", "knee")): + if field in row: + actual = _vector(row[field], f"leg_inputs.{side}.{field}") + expected = expected_tk[side if field == "T" else side + ".K"] + if actual != expected: + _fail(f"leg_inputs.{side}.{field} conflicts with source_case.attachments.{side}.{source_key}") + return case, expected_tk + + +def bind_source_case(root_l0: Mapping[str, Any], root_l2: Mapping[str, Any], + source_case: Mapping[str, Any], explicit_j: Any = None, + leg_inputs: Any = None) -> dict[str, Any]: + """Regenerate hip weights from rebuilt source surfaces and source ownership.""" + if not isinstance(root_l0, Mapping) or not isinstance(root_l2, Mapping): + _fail("root_l0 and root_l2 must be mesh mappings") + case, _ = _source_case_inputs(source_case, leg_inputs) + joints = _joints(explicit_j, leg_inputs) + references = {"joint_left": joints["left"], "joint_right": joints["right"]} + binder, provenance = _load_frozen_binding() + function = getattr(binder, "bind", None) + if not callable(function): + _fail("frozen hip binding lacks bind") + binding = function(root_l0, root_l2, case, references) + if not isinstance(binding, Mapping): + _fail("frozen hip binding returned a non-mapping result") + return {"binding": dict(binding), "provenance": provenance} + + +__all__ = ["HipSourceError", "bind_source_case"] diff --git a/experiments/connected-leg-assembly/inputs.json b/experiments/connected-leg-assembly/inputs.json new file mode 100644 index 0000000..f3eaa57 --- /dev/null +++ b/experiments/connected-leg-assembly/inputs.json @@ -0,0 +1,184 @@ +{ + "schema": "creature-kernel.connected-leg-assembly-inputs.v1", + "experiment_id": "EXP-0003", + "status": "prepared_not_executed", + "authorization": { + "scope": "internal connected-leg staging under the integrated coarse-to-anatomical runway", + "relayed_by": "Overseer", + "date": "2026-09-06", + "targets": ["ordinary human", "loose wolf-like humanoid anthropomorphic"], + "species_contract": false, + "note": "The anthropomorphic coarse digitigrade appearance target is approved for this experiment-local stage. Species and gait-specific paw/hock design remains provisional; the raised heel and foot are not implemented here." + }, + "provenance": { + "frozen_calibration_inputs": { + "path": "/home/ben/.cache/creature-kernel/pelvis-source-calibration-set-1/source/experiments/pelvis-source-calibration/inputs.json", + "sha256": "3c0cbe9a3ae81def226f91f3d5eddcff6e07f118360abc88670069fe9b010a8c" + }, + "frozen_calibration_manifest": { + "path": "/home/ben/.cache/creature-kernel/pelvis-source-calibration-set-1/run/artifact-sha-manifest-after.json", + "sha256": "f0152de5b6b82a60c35599b0b82af746704d1917446d8fceb88b2ca016275871" + }, + "frozen_hip_snapshot_manifest": { + "path": "/home/ben/.cache/creature-kernel/pelvis-hip-articulation-harmonic-lbs-001-snapshot/manifest.json", + "sha256": "e97406f487569b072c1885667a0fd49084a017b30f03cecb04562b81241bef54" + }, + "frozen_hip_artifact_manifest": { + "path": "/home/ben/.cache/creature-kernel/pelvis-hip-articulation-harmonic-lbs-001-run/artifact-sha-manifest.json", + "sha256": "c6733a75cbd0f7496e71256bc2ed56adb2b924b4e3136339efbe25c6b89fd9c3" + }, + "immutable_source_note": "Original calibration inputs, root meshes, prior rest meshes, and prior hip bindings are read-only evidence. New distal values below are explicit approximate artist design hypotheses, not measurements." + }, + "common_pipeline": { + "operation": "extend_saved_calibrated_l0_root_from_existing_thigh_exit_through_knee_and_shank_to_open_ankle_ports", + "common_for_cases": true, + "stage_ends_at": "open ankle ports", + "foot_or_sole": "not represented", + "preserve": ["J", "T", "K", "original root inputs", "original root meshes", "prior hip evidence"], + "former_thigh_exit": { + "new_role": "interior welded transition", + "prior_boundary_invariance_claim": false, + "note": "The former thigh exit becomes interior when the extension is attached; only regions unreachable by new subdivision may be asserted exactly unchanged." + }, + "section_coordinate_convention": "radii arrays are [lateral, anterior, posterior] and may be asymmetric; loop centroid is therefore not required to equal its source joint or endpoint." + }, + "cases": [ + { + "id": "calibrated_ordinary_human", + "design_intent": "upright human-like interim leg; plantigrade baseline is a reasonable staging hypothesis only, not an anthropometric claim", + "root_mesh": { + "path": "/home/ben/.cache/creature-kernel/pelvis-source-calibration-set-1/run/cases/case-05-calibrated_ordinary_human/mesh-L0.json", + "sha256": "1fb72cd3057bce3e0cf162ce8fd907feb289b182eb8014275719a514e5716eb4", + "level": "L0", + "immutable": true + }, + "prior_rest_mesh": { + "path": "/home/ben/.cache/creature-kernel/pelvis-source-calibration-set-1/run/cases/case-05-calibrated_ordinary_human/mesh-L2.json", + "sha256": "b4622902c4c7f8713a7a8679b511ca471ebea06cf5006900cbe0a88f8268f4b6", + "level": "L2", + "immutable": true + }, + "original_case": { + "path": "/home/ben/.cache/creature-kernel/pelvis-hip-articulation-harmonic-lbs-001-run/cases/calibrated_ordinary_human/case.json", + "sha256": "7d5ac5da5fe1631351a45a679f36d7aaedaf56136dc66edf325adb45fe84152f", + "calibration_source_path": "/home/ben/.cache/creature-kernel/pelvis-source-calibration-set-1/source/experiments/pelvis-source-calibration/inputs.json#/cases/5", + "calibration_source_sha256": "3c0cbe9a3ae81def226f91f3d5eddcff6e07f118360abc88670069fe9b010a8c" + }, + "original_ref": { + "path": "/home/ben/.cache/creature-kernel/pelvis-hip-articulation-harmonic-lbs-001-run/cases/calibrated_ordinary_human/landmarks.json", + "sha256": "56437705205dd27cd7a8aeb27661356258cf58cb9773e7edecef31d2c7b3a9f2", + "meaning": "preserved hip reference metadata; J is an independent pose input" + }, + "prior_hip_binding": { + "path": "/home/ben/.cache/creature-kernel/pelvis-hip-articulation-harmonic-lbs-001-run/cases/calibrated_ordinary_human/binding.json", + "sha256": "b0d60642460ead3ca5f53d26ac87a7f080cea69727d59f1bf2184bf6f7fe14a0" + }, + "leg_inputs": { + "left": { + "J": [-0.085, 0.0, 0.0], + "T": [-0.12, -0.05, 0.0], + "K": [-0.08, -0.43, 0.0], + "A": [-0.08, -0.82, 0.0], + "radii": { + "knee": [0.045, 0.045, 0.04], + "calf": [0.05, 0.043, 0.063], + "ankle": [0.028, 0.028, 0.03] + }, + "mid_thigh_factor": 0.85, + "support_fraction": 0.1, + "J_role": "preserve_independent_pose_input", + "TK_source_role": "preserve_original_thigh_source_points", + "distal_design_status": "approximate_artist hypothesis; uncertainty about 20 percent" + }, + "right": { + "J": [0.085, 0.0, 0.0], + "T": [0.12, -0.05, 0.0], + "K": [0.08, -0.43, 0.0], + "A": [0.08, -0.82, 0.0], + "radii": { + "knee": [0.045, 0.045, 0.04], + "calf": [0.05, 0.043, 0.063], + "ankle": [0.028, 0.028, 0.03] + }, + "mid_thigh_factor": 0.85, + "support_fraction": 0.1, + "J_role": "preserve_independent_pose_input", + "TK_source_role": "preserve_original_thigh_source_points", + "distal_design_status": "mirrored approximate artist hypothesis; uncertainty about 20 percent" + } + } + }, + { + "id": "calibrated_upright_anthropomorphic", + "design_intent": "loose wolf-like humanoid coarse digitigrade target; artistic hypothesis, not a canid specimen or gait contract", + "root_mesh": { + "path": "/home/ben/.cache/creature-kernel/pelvis-source-calibration-set-1/run/cases/case-06-calibrated_upright_anthropomorphic/mesh-L0.json", + "sha256": "6237cc7940e1559fbf05d18ab20d87b444c3dd3dd7238a41ffe17f3c6b881e2e", + "level": "L0", + "immutable": true + }, + "prior_rest_mesh": { + "path": "/home/ben/.cache/creature-kernel/pelvis-source-calibration-set-1/run/cases/case-06-calibrated_upright_anthropomorphic/mesh-L2.json", + "sha256": "59e4ee377c28451b36ebb821199ecc386bf01ee2421db86d9ada18da9c9bf761", + "level": "L2", + "immutable": true + }, + "original_case": { + "path": "/home/ben/.cache/creature-kernel/pelvis-hip-articulation-harmonic-lbs-001-run/cases/calibrated_upright_anthropomorphic/case.json", + "sha256": "0f3a9bd29d33f8a9ca5f6b116084209c539eb37120d93d9973c00613358d8c91", + "calibration_source_path": "/home/ben/.cache/creature-kernel/pelvis-source-calibration-set-1/source/experiments/pelvis-source-calibration/inputs.json#/cases/6", + "calibration_source_sha256": "3c0cbe9a3ae81def226f91f3d5eddcff6e07f118360abc88670069fe9b010a8c" + }, + "original_ref": { + "path": "/home/ben/.cache/creature-kernel/pelvis-hip-articulation-harmonic-lbs-001-run/cases/calibrated_upright_anthropomorphic/landmarks.json", + "sha256": "4cd4ca7f973a5f9953818446c7cd7252dae4065bcb4aba8e7b9f423e31c991fb", + "meaning": "preserved hip reference metadata; J is an independent pose input" + }, + "prior_hip_binding": { + "path": "/home/ben/.cache/creature-kernel/pelvis-hip-articulation-harmonic-lbs-001-run/cases/calibrated_upright_anthropomorphic/binding.json", + "sha256": "91e85077e88ea3c503a593755449bb7cce36fac5bd8ac71743fee6449a2c9aa2" + }, + "leg_inputs": { + "left": { + "J": [-0.095, 0.0, -0.005], + "T": [-0.135, -0.045, 0.0], + "K": [-0.1, -0.355, 0.025], + "A": [-0.1, -0.645, -0.075], + "radii": { + "knee": [0.05, 0.05, 0.045], + "calf": [0.055, 0.045, 0.065], + "ankle": [0.032, 0.03, 0.034] + }, + "mid_thigh_factor": 0.85, + "support_fraction": 0.1, + "J_role": "preserve_independent_pose_input", + "TK_source_role": "preserve_original_thigh_source_points", + "distal_design_status": "approximate artist hypothesis; uncertainty about 20 percent; A is posterior to K" + }, + "right": { + "J": [0.095, 0.0, -0.005], + "T": [0.135, -0.045, 0.0], + "K": [0.1, -0.355, 0.025], + "A": [0.1, -0.645, -0.075], + "radii": { + "knee": [0.05, 0.05, 0.045], + "calf": [0.055, 0.045, 0.065], + "ankle": [0.032, 0.03, 0.034] + }, + "mid_thigh_factor": 0.85, + "support_fraction": 0.1, + "J_role": "preserve_independent_pose_input", + "TK_source_role": "preserve_original_thigh_source_points", + "distal_design_status": "mirrored approximate artist hypothesis; uncertainty about 20 percent; A is posterior to K" + } + } + } + ], + "known_uncertainties": [ + "All new distal coordinates and radii are pre-run design hypotheses with approximately 20 percent uncertainty.", + "Ankle A is an open ankle-port endpoint, not a heel or sole endpoint; foot and raised-heel design remain future inputs.", + "No actual whole-character stature or final leg-to-body proportion has been established.", + "Human values are rough procedural proportions, not anthropometric truth; anthropomorphic values are an artistic hypothesis, not canid anatomy.", + "The source filename and appearance label do not infer gait or digitigrade geometry; only the current Overseer authorization permits this coarse anthropomorphic target." + ] +} diff --git a/experiments/connected-leg-assembly/perturbations.py b/experiments/connected-leg-assembly/perturbations.py new file mode 100644 index 0000000..c9826c8 --- /dev/null +++ b/experiments/connected-leg-assembly/perturbations.py @@ -0,0 +1,1365 @@ +"""Bounded, experiment-local perturbation evidence for connected-leg staging. + +The helper in this module is deliberately separate from construction, binding, +and the runner. It calls each collaborator exactly once per declared +perturbation, computes independent source/frame expectations, and returns +JSON-compatible records for a captured runner to serialize or render. It +does not tune, repair, or call the real calibrated bodies during preparation. + +The calf posterior metric treats a source-template seam as a numerical domain, +not as an anatomical threshold: a response is stable only when its projected +analytic displacement exceeds the baseline coordinate ULP bound. Smaller +responses remain recorded as bounded ``indeterminate`` samples. +""" +from __future__ import annotations + +import copy +import math +from collections.abc import Mapping, Sequence +from numbers import Real +from typing import Any + + +_PERTURBATION_IDS = ( + "left_A_y_minus_0.02", + "left_calf_posterior_radius_times_1.10", + "left_J_y_plus_0.01_at_hip15", +) +_SIDES = ("left", "right") +_SECTIONS = ( + "mid_thigh", + "knee_pre_support", + "knee", + "knee_post_support", + "calf", + "ankle_approach", + "ankle", +) +_SOURCE_FRACTIONS = (0.70, None, 1.0, None, 0.35, 0.72, 1.0) +_CALF_FRACTION = 0.35 +_ANKLE_APPROACH_FRACTION = 0.72 +_ROOT_EXIT_FRACTION = 0.45 +_POST_KNEE_SUPPORT_MULTIPLIER = 1.2 +_RING_SIZE = 8 +_CALF_POSTERIOR_METRIC_DEFINITION = { + "id": "calf-posterior-expansion-ulp-domain.v3", + "stable_rule": ( + "projected analytic response in -localF exceeds the conservative " + "baseline-coordinate ULP projection" + ), + "indeterminate_rule": ( + "responses at or below that ULP projection are recorded and actual " + "response must remain within the same representability bound" + ), + "support_envelope": ( + "all L2 vertices with nonzero baseline stencil support from any of " + "the eight L0 calf-ring controls; extent is measured from the fixed " + "calf centre along -localF; this is not an exact planar calf section" + ), + "source_frame": "the baseline left K-to-A calf frame is used for every projection", +} + + +class PerturbationUnavailable(ValueError): + """Raised when a collaborator or evidence input is incoherent.""" + + +def _mapping(value: Any, where: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping): + raise PerturbationUnavailable(f"{where} must be a mapping") + return value + + +def _number(value: Any, where: str) -> float: + if isinstance(value, bool) or not isinstance(value, Real): + raise PerturbationUnavailable(f"{where} must be a finite number") + result = float(value) + if not math.isfinite(result): + raise PerturbationUnavailable(f"{where} must be finite") + return result + + +def _vector(value: Any, where: str) -> tuple[float, float, float]: + if not isinstance(value, (list, tuple)) or len(value) != 3: + raise PerturbationUnavailable(f"{where} must be a three-component vector") + return tuple(_number(item, f"{where}[{index}]") + for index, item in enumerate(value)) # type: ignore[return-value] + + +def _jsonable(value: Any) -> Any: + """Convert collaborator output without allowing non-finite JSON values.""" + if isinstance(value, Mapping): + return {str(key): _jsonable(item) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [_jsonable(item) for item in value] + if type(value) is float: + if not math.isfinite(value): + raise PerturbationUnavailable("non-finite collaborator output") + return value + if type(value) is int or type(value) is bool or value is None or type(value) is str: + return value + tolist = getattr(value, "tolist", None) + if callable(tolist): + return _jsonable(tolist()) + if isinstance(value, Real): + result = float(value) + if not math.isfinite(result): + raise PerturbationUnavailable("non-finite collaborator output") + return result + raise PerturbationUnavailable(f"value of type {type(value).__name__} is not JSON-compatible") + + +def _add(*values: tuple[float, float, float]) -> tuple[float, float, float]: + return tuple(sum(value[axis] for value in values) for axis in range(3)) # type: ignore[return-value] + + +def _sub(left: tuple[float, float, float], + right: tuple[float, float, float]) -> tuple[float, float, float]: + return tuple(left[axis] - right[axis] for axis in range(3)) # type: ignore[return-value] + + +def _scale(value: tuple[float, float, float], factor: float) -> tuple[float, float, float]: + return tuple(factor * item for item in value) # type: ignore[return-value] + + +def _dot(left: tuple[float, float, float], + right: tuple[float, float, float]) -> float: + return sum(left[axis] * right[axis] for axis in range(3)) + + +def _cross(left: tuple[float, float, float], + right: tuple[float, float, float]) -> tuple[float, float, float]: + return ( + left[1] * right[2] - left[2] * right[1], + left[2] * right[0] - left[0] * right[2], + left[0] * right[1] - left[1] * right[0], + ) + + +def _norm(value: tuple[float, float, float]) -> float: + return math.sqrt(_dot(value, value)) + + +def _unit(value: tuple[float, float, float], where: str) -> tuple[float, float, float]: + length = _norm(value) + if not math.isfinite(length) or length <= 0.0: + raise PerturbationUnavailable(f"{where} has no finite positive length") + return _scale(value, 1.0 / length) + + +def _lerp(left: tuple[float, float, float], + right: tuple[float, float, float], fraction: float) -> tuple[float, float, float]: + return _add(_scale(left, 1.0 - fraction), _scale(right, fraction)) + + +def _max_abs(left: tuple[float, float, float], + right: tuple[float, float, float]) -> float: + return max(abs(left[axis] - right[axis]) for axis in range(3)) + + +def _zero(value: tuple[float, float, float], tolerance: float) -> bool: + return _norm(value) <= tolerance + + +def _mesh_vertices(mesh: Any, where: str) -> list[tuple[float, float, float]]: + raw = _mapping(mesh, where).get("vertices") + if not isinstance(raw, (list, tuple)) or not raw: + raise PerturbationUnavailable(f"{where}.vertices must be non-empty") + return [_vector(point, f"{where}.vertices[{index}]") + for index, point in enumerate(raw)] + + +def _quads(mesh: Any, where: str) -> list[list[int]]: + raw = _mapping(mesh, where).get("quads") + if not isinstance(raw, (list, tuple)): + raise PerturbationUnavailable(f"{where}.quads must be a sequence") + return [list(face) for face in raw] + + +def _stencil_rows(mesh: Any, where: str) -> list[list[tuple[int, float]]]: + value = _mapping(mesh, where) + raw = value.get("base_stencils", value.get("stencils")) + if not isinstance(raw, (list, tuple)): + raise PerturbationUnavailable(f"{where} has no full base stencils") + result: list[list[tuple[int, float]]] = [] + for row_index, row in enumerate(raw): + if not isinstance(row, (list, tuple)) or not row: + raise PerturbationUnavailable(f"{where}.stencils[{row_index}] is empty") + parsed: list[tuple[int, float]] = [] + for term_index, term in enumerate(row): + if not isinstance(term, (list, tuple)) or len(term) != 2: + raise PerturbationUnavailable( + f"{where}.stencils[{row_index}][{term_index}] is malformed" + ) + index = term[0] + if isinstance(index, bool) or not isinstance(index, int): + raise PerturbationUnavailable("stencil index must be an integer") + coefficient = _number(term[1], "stencil coefficient") + if coefficient < 0.0: + raise PerturbationUnavailable("stencil coefficient must be non-negative") + parsed.append((index, coefficient)) + result.append(parsed) + return result + + +def _loop(mesh: Any, name: str, where: str) -> list[int]: + raw = _mapping(mesh, where).get("loops") + if not isinstance(raw, Mapping) or name not in raw: + raise PerturbationUnavailable(f"{where}.loops.{name} is unavailable") + values = raw[name] + if not isinstance(values, (list, tuple)) or not values: + raise PerturbationUnavailable(f"{where}.loops.{name} is empty") + return [int(index) for index in values] + + +def _root_loop(root: Any, side: str) -> list[int]: + raw = _mapping(root, "root").get("loops") + name = f"port.{side}_thigh" + if isinstance(raw, Mapping) and name in raw: + values = raw[name] + else: + metadata = _mapping(root, "root").get("metadata") + transitions = _mapping(metadata, "root.metadata").get("transition_indices") + row = _mapping(transitions, "root.metadata.transition_indices").get(side) + values = _mapping(row, f"root.metadata.transition_indices.{side}").get("exit") + if not isinstance(values, (list, tuple)) or len(values) != _RING_SIZE: + raise PerturbationUnavailable(f"root {name} must contain eight vertices") + return [int(index) for index in values] + + +def _frames_for_tangents(tangents: Sequence[tuple[float, float, float]]) -> list[dict[str, tuple[float, float, float]]]: + previous_x: tuple[float, float, float] | None = None + result = [] + for index, tangent in enumerate(tangents): + x_axis = _unit(_sub((1.0, 0.0, 0.0), + _scale(tangent, _dot((1.0, 0.0, 0.0), tangent))), + f"source frame {index} projected +X") + if previous_x is not None and _dot(x_axis, previous_x) < 0.0: + x_axis = _scale(x_axis, -1.0) + up_axis = _scale(tangent, -1.0) + forward = _unit(_cross(x_axis, up_axis), f"source frame {index} forward") + frame = {"tangent": tangent, "X": x_axis, "U": up_axis, "F": forward} + result.append(frame) + previous_x = x_axis + return result + + +def _normalised_root_template(root: Any, side: str, + points: Mapping[str, tuple[float, float, float]], + tolerance: float) -> tuple[list[tuple[float, float]], tuple[float, float, float]]: + vertices = _mesh_vertices(root, "root") + loop = _root_loop(root, side) + incoming = _unit(_sub(points["K"], points["T"]), f"{side} source T-K") + frame = _frames_for_tangents([incoming])[0] + exit_centre = _add(points["T"], _scale(_sub(points["K"], points["T"]), _ROOT_EXIT_FRACTION)) + projected: list[tuple[float, float]] = [] + lateral_radius = 0.0 + anterior_radius = 0.0 + posterior_radius = 0.0 + for vertex_index in loop: + if vertex_index < 0 or vertex_index >= len(vertices): + raise PerturbationUnavailable(f"root {side} loop index is out of range") + delta = _sub(vertices[vertex_index], exit_centre) + if abs(_dot(delta, incoming)) > tolerance: + raise PerturbationUnavailable(f"root {side} loop is not in the source exit plane") + lateral = _dot(delta, frame["X"]) + forward = _dot(delta, frame["F"]) + lateral_radius = max(lateral_radius, abs(lateral)) + anterior_radius = max(anterior_radius, forward) + posterior_radius = max(posterior_radius, -forward) + projected.append((lateral, forward)) + if min(lateral_radius, anterior_radius, posterior_radius) <= 0.0: + raise PerturbationUnavailable(f"root {side} template has a degenerate radius") + template = [ + (lateral / lateral_radius, + forward / (anterior_radius if forward >= 0.0 else posterior_radius)) + for lateral, forward in projected + ] + return template, (lateral_radius, anterior_radius, posterior_radius) + + +_ROLE_METADATA_KEYS = ("J_role", "TK_source_role", "distal_design_status") + + +def _leg_values(value: Any) -> tuple[dict[str, dict[str, Any]], dict[str, float], dict[str, float]]: + raw = _mapping(value, "leg_inputs") + if set(raw) != set(_SIDES): + raise PerturbationUnavailable("leg_inputs must contain exactly left and right sides") + result = copy.deepcopy(dict(raw)) + factors: dict[str, float] = {} + supports: dict[str, float] = {} + for side in _SIDES: + row = _mapping(result.get(side), f"leg_inputs.{side}") + required = {"J", "T", "K", "A", "radii", "mid_thigh_factor", + "support_fraction", *_ROLE_METADATA_KEYS} + if set(row) != required: + raise PerturbationUnavailable( + f"leg_inputs.{side} must use the canonical per-side fields and role metadata" + ) + for name in ("J", "T", "K", "A"): + _vector(row.get(name), f"leg_inputs.{side}.{name}") + radii = _mapping(row.get("radii"), f"leg_inputs.{side}.radii") + for name in ("knee", "calf", "ankle"): + values = _vector(radii.get(name), f"leg_inputs.{side}.radii.{name}") + if any(item <= 0.0 for item in values): + raise PerturbationUnavailable(f"leg_inputs.{side}.radii.{name} must be positive") + for name in _ROLE_METADATA_KEYS: + if type(row[name]) is not str or not row[name]: + raise PerturbationUnavailable(f"leg_inputs.{side}.{name} must be a non-empty string") + factor = _number(row["mid_thigh_factor"], f"leg_inputs.{side}.mid_thigh_factor") + support = _number(row["support_fraction"], f"leg_inputs.{side}.support_fraction") + if factor < 0.0 or not 0.0 < support < 1.0: + raise PerturbationUnavailable(f"leg_inputs.{side} factors are outside their declared domains") + factors[side] = factor + supports[side] = support + return {side: result[side] for side in _SIDES}, factors, supports + + +def _apply_declared_change(value: Mapping[str, Any], spec: Mapping[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]: + result = copy.deepcopy(dict(value)) + change = _mapping(spec.get("change"), f"perturbation {spec.get('id')}.change") + path = str(change.get("path", "")) + prefix = "cases[*].leg_inputs." + if not path.startswith(prefix): + raise PerturbationUnavailable(f"unsupported declared perturbation path: {path}") + tail = path[len(prefix):] + try: + side, field_path = tail.split(".", 1) + field, index_text = field_path.rsplit("[", 1) + index = int(index_text.rstrip("]")) + except (ValueError, TypeError): + raise PerturbationUnavailable(f"malformed declared perturbation path: {path}") + if side not in _SIDES: + raise PerturbationUnavailable(f"unsupported perturbation side: {side}") + target: Any = result[side] + for part in field.split("."): + target = target[part] + old = _number(target[index], path) + operation = change.get("operation") + amount = _number(change.get("value"), f"{path} change") + if operation == "add": + new = old + amount + elif operation == "multiply": + new = old * amount + else: + raise PerturbationUnavailable(f"unsupported perturbation operation: {operation}") + target[index] = new + return result, {"path": path, "operation": operation, "old": old, "new": new} + + +def _source_plan(root: Any, legs: Mapping[str, Any], side: str, + factor: float, support: float, tolerance: float) -> dict[str, Any]: + row = _mapping(legs[side], f"legs.{side}") + points = {name: _vector(row[name], f"legs.{side}.{name}") + for name in ("J", "T", "K", "A")} + incoming = _unit(_sub(points["K"], points["T"]), f"{side} source T-K") + outgoing = _unit(_sub(points["A"], points["K"]), f"{side} source K-A") + knee_tangent = _unit(_add(incoming, outgoing), f"{side} source knee bisector") + frames = _frames_for_tangents([ + incoming, incoming, knee_tangent, outgoing, outgoing, outgoing, outgoing + ]) + template, exit_radii = _normalised_root_template(root, side, points, tolerance) + fractions = ( + 0.70, + 1.0 - support, + 1.0, + _POST_KNEE_SUPPORT_MULTIPLIER * support, + _CALF_FRACTION, + _ANKLE_APPROACH_FRACTION, + 1.0, + ) + centres = [ + _lerp(points["T"], points["K"], fractions[0]), + _lerp(points["T"], points["K"], fractions[1]), + points["K"], + _lerp(points["K"], points["A"], fractions[3]), + _lerp(points["K"], points["A"], fractions[4]), + _lerp(points["K"], points["A"], fractions[5]), + points["A"], + ] + radii = {name: _vector(_mapping(row["radii"], f"legs.{side}.radii")[name], + f"legs.{side}.radii.{name}") + for name in ("knee", "calf", "ankle")} + mid_radii = _scale(exit_radii, factor) + section_radii: list[tuple[float, float, float]] = [] + for name, fraction in zip(_SECTIONS, fractions): + if name in ("mid_thigh", "knee_pre_support", "knee"): + if fraction <= 0.70: + section_radii.append(_lerp(exit_radii, mid_radii, + (fraction - 0.45) / 0.25)) + else: + section_radii.append(_lerp(mid_radii, radii["knee"], + (fraction - 0.70) / 0.30)) + elif fraction <= _CALF_FRACTION: + section_radii.append(_lerp(radii["knee"], radii["calf"], + fraction / _CALF_FRACTION)) + elif name == "ankle": + section_radii.append(radii["ankle"]) + else: + section_radii.append(_lerp(radii["calf"], radii["ankle"], + (fraction - _CALF_FRACTION) / 0.65)) + section_points: list[list[tuple[float, float, float]]] = [] + for centre, section_radius, frame in zip(centres, section_radii, frames): + ring = [] + for lateral, forward in template: + depth_radius = section_radius[1] if forward >= 0.0 else section_radius[2] + ring.append(_add(centre, + _scale(frame["X"], lateral * section_radius[0]), + _scale(frame["F"], forward * depth_radius))) + section_points.append(ring) + return { + "points": points, + "incoming": incoming, + "outgoing": outgoing, + "knee_tangent": knee_tangent, + "template": template, + "exit_radii": exit_radii, + "fractions": fractions, + "centres": centres, + "radii": section_radii, + "frames": frames, + "section_points": section_points, + } + + +def _ring_mapping(mesh: Any, side: str) -> dict[str, list[int]]: + metadata = _mapping(_mapping(mesh, "mesh").get("metadata"), "mesh.metadata") + chains = _mapping(metadata.get("chains"), "mesh.metadata.chains") + chain = _mapping(chains.get(side), f"mesh.metadata.chains.{side}") + sections = chain.get("sections") + if not isinstance(sections, (list, tuple)) or len(sections) != len(_SECTIONS): + raise PerturbationUnavailable(f"mesh.metadata.chains.{side}.sections is incomplete") + result: dict[str, list[int]] = {} + for name, raw in zip(_SECTIONS, sections): + row = _mapping(raw, f"mesh.metadata.chains.{side}.{name}") + values = row.get("indices") + if not isinstance(values, (list, tuple)) or len(values) != _RING_SIZE: + raise PerturbationUnavailable(f"mesh metadata ring {side}.{name} is incomplete") + result[name] = [int(index) for index in values] + return result + + +def _analytic_l0_vertices(baseline_l0: Any, root: Any, + legs: Mapping[str, Any], + factors: Mapping[str, float], + supports: Mapping[str, float], + tolerance: float) -> tuple[list[tuple[float, float, float]], dict[str, dict[str, list[int]]], dict[str, dict[str, Any]]]: + vertices = _mesh_vertices(baseline_l0, "baseline_L0") + ring_maps = {side: _ring_mapping(baseline_l0, side) for side in _SIDES} + plans = {side: _source_plan(root, legs, side, factors[side], supports[side], tolerance) + for side in _SIDES} + expected = list(vertices) + for side in _SIDES: + for name, ring in ring_maps[side].items(): + expected_points = plans[side]["section_points"][_SECTIONS.index(name)] + for index, point in zip(ring, expected_points): + if index < 0 or index >= len(expected): + raise PerturbationUnavailable(f"analytic ring index {side}.{name} is out of range") + expected[index] = point + return expected, ring_maps, plans + + +def _delta(actual: Sequence[tuple[float, float, float]], + baseline: Sequence[tuple[float, float, float]]) -> list[tuple[float, float, float]]: + if len(actual) != len(baseline): + raise PerturbationUnavailable("baseline and perturbed vertex counts differ") + return [_sub(left, right) for left, right in zip(actual, baseline)] + + +def _max_delta_error(actual: Sequence[tuple[float, float, float]], + expected: Sequence[tuple[float, float, float]]) -> float: + if len(actual) != len(expected): + raise PerturbationUnavailable("actual and expected delta lengths differ") + return max((_norm(_sub(left, right)) for left, right in zip(actual, expected)), default=0.0) + + +def _expected_l2_delta(l0_delta: Sequence[tuple[float, float, float]], + rest_l2: Any) -> list[tuple[float, float, float]]: + rows = _stencil_rows(rest_l2, "baseline_L2") + result = [] + for row in rows: + result.append(_add(*(_scale(l0_delta[index], coefficient) + for index, coefficient in row))) + return result + + +def _coordinate_ulps(point: tuple[float, float, float]) -> tuple[float, float, float]: + return tuple(math.ulp(float(value)) for value in point) # type: ignore[return-value] + + +def _signed_ulp_bound(point: tuple[float, float, float], + direction: tuple[float, float, float]) -> float: + """Bound a projected one-ULP coordinate change without a profile threshold.""" + ulps = _coordinate_ulps(point) + return sum(abs(direction[index]) * ulps[index] for index in range(3)) + + +def _calf_posterior_measurement( + baseline_l0_vertices: Sequence[tuple[float, float, float]], + actual_l0_delta: Sequence[tuple[float, float, float]], + expected_l0_delta: Sequence[tuple[float, float, float]], + calf_indices: Sequence[int], + template: Sequence[tuple[float, float]], + baseline_l2_vertices: Sequence[tuple[float, float, float]], + baseline_l2_stencils: Sequence[Sequence[tuple[int, float]]], + actual_l2_delta: Sequence[tuple[float, float, float]], + expected_l2_delta: Sequence[tuple[float, float, float]], + frame: Mapping[str, Any], centre: Any, tolerance: Any) -> dict[str, Any]: + """Measure posterior response in a source-frame numerical domain. + + L0 records the exact eight-sample calf ring. The L2 support envelope is + every vertex with nonzero baseline stencil support from any of the eight + calf controls, independent of observed or expected displacement. Its + before/after maximum extent is not a planar section. + No sample is discarded: source samples and L2 support samples are each + labelled stable, indeterminate, or direction-invalid. + """ + if len(calf_indices) != _RING_SIZE or len(template) != _RING_SIZE: + raise PerturbationUnavailable("calf ring and source template must contain eight samples") + if (len(actual_l0_delta) != len(expected_l0_delta) or + len(actual_l0_delta) != len(baseline_l0_vertices)): + raise PerturbationUnavailable("L0 posterior measurement arrays do not cover the mesh") + if (len(actual_l2_delta) != len(expected_l2_delta) or + len(actual_l2_delta) != len(baseline_l2_vertices)): + raise PerturbationUnavailable("L2 posterior measurement arrays do not cover the mesh") + if len(baseline_l2_stencils) != len(baseline_l2_vertices): + raise PerturbationUnavailable("L2 posterior measurement stencils do not cover the mesh") + source_forward = _vector(_mapping(frame, "calf source frame").get("F"), + "calf source frame.F") + direction = _scale(source_forward, -1.0) + centre_point = _vector(centre, "calf source centre") + comparison_tolerance = _number(tolerance, "calf comparison tolerance") + if comparison_tolerance <= 0.0: + raise PerturbationUnavailable("calf comparison tolerance must be positive") + source_samples: list[dict[str, Any]] = [] + for slot, (vertex_index, local) in enumerate(zip(calf_indices, template)): + if vertex_index < 0 or vertex_index >= len(baseline_l0_vertices): + raise PerturbationUnavailable(f"calf sample {slot} is out of range") + expected_signed = _dot(expected_l0_delta[vertex_index], direction) + actual_signed = _dot(actual_l0_delta[vertex_index], direction) + ulps = _coordinate_ulps(baseline_l0_vertices[vertex_index]) + ulp_bound = _signed_ulp_bound(baseline_l0_vertices[vertex_index], direction) + if expected_signed > 0.0: + if expected_signed > ulp_bound: + domain = "posterior-stable" + response_pass = actual_signed > 0.0 + response_status = "positive" if response_pass else "failed-nonpositive" + else: + domain = "posterior-indeterminate" + response_pass = abs(actual_signed) <= ulp_bound + response_status = ( + "indeterminate-bounded" if response_pass + else "indeterminate-out-of-bound" + ) + elif expected_signed == 0.0: + domain = "zero-source-response" + response_pass = True + response_status = "outside-posterior-support" + else: + domain = "opposite-frame-response" + response_pass = False + response_status = "failed-opposite-frame" + source_samples.append({ + "slot": slot, + "l0_vertex_id": int(vertex_index), + "template_local": [float(local[0]), float(local[1])], + "expected_signed_minus_localF": expected_signed, + "actual_signed_minus_localF": actual_signed, + "coordinate_ulps": list(ulps), + "projected_ulp_bound": ulp_bound, + "domain": domain, + "response_status": response_status, + "pass": response_pass, + }) + + stable_source = [row for row in source_samples + if row["domain"] == "posterior-stable"] + indeterminate_source = [row for row in source_samples + if row["domain"] == "posterior-indeterminate"] + stable_source_extremum = max( + stable_source, key=lambda row: row["expected_signed_minus_localF"], + default=None, + ) + + calf_controls = set(calf_indices) + support_samples: list[dict[str, Any]] = [] + for index, (baseline_point, stencil, actual_delta, expected_delta) in enumerate( + zip(baseline_l2_vertices, baseline_l2_stencils, + actual_l2_delta, expected_l2_delta)): + if not any(base_index in calf_controls and coefficient != 0.0 + for base_index, coefficient in stencil): + continue + expected_norm = _norm(expected_delta) + expected_signed = _dot(expected_delta, direction) + actual_signed = _dot(actual_delta, direction) + ulps = _coordinate_ulps(baseline_point) + ulp_bound = _signed_ulp_bound(baseline_point, direction) + if expected_norm == 0.0: + domain = "zero-source-response" + response_pass = True + response_status = "outside-posterior-response" + elif expected_signed <= 0.0: + domain = "opposite-frame-response" + response_pass = False + response_status = "failed-opposite-frame" + elif expected_signed > ulp_bound: + domain = "posterior-stable" + response_pass = actual_signed > 0.0 + response_status = "positive" if response_pass else "failed-nonpositive" + else: + domain = "posterior-indeterminate" + response_pass = abs(actual_signed) <= ulp_bound + response_status = ( + "indeterminate-bounded" if response_pass + else "indeterminate-out-of-bound" + ) + support_samples.append({ + "l2_vertex_id": index, + "expected_signed_minus_localF": expected_signed, + "actual_signed_minus_localF": actual_signed, + "expected_vector_norm": expected_norm, + "baseline_extent_from_calf_centre_in_minus_localF": _dot( + _sub(baseline_point, centre_point), direction + ), + "actual_extent_from_calf_centre_in_minus_localF": _dot( + _sub(_add(baseline_point, actual_delta), centre_point), direction + ), + "coordinate_ulps": list(ulps), + "projected_ulp_bound": ulp_bound, + "domain": domain, + "response_status": response_status, + "pass": response_pass, + }) + + stable_support = [row for row in support_samples + if row["domain"] == "posterior-stable"] + indeterminate_support = [row for row in support_samples + if row["domain"] == "posterior-indeterminate"] + stable_support_extremum = max( + stable_support, key=lambda row: row["expected_signed_minus_localF"], + default=None, + ) + baseline_extent_row = max( + support_samples, + key=lambda row: row["baseline_extent_from_calf_centre_in_minus_localF"], + default=None, + ) + actual_extent_row = max( + support_samples, + key=lambda row: row["actual_extent_from_calf_centre_in_minus_localF"], + default=None, + ) + baseline_extent = ( + baseline_extent_row["baseline_extent_from_calf_centre_in_minus_localF"] + if baseline_extent_row is not None else 0.0 + ) + actual_extent = ( + actual_extent_row["actual_extent_from_calf_centre_in_minus_localF"] + if actual_extent_row is not None else 0.0 + ) + envelope_expansion = actual_extent - baseline_extent + meaningful_expansion = envelope_expansion > comparison_tolerance + source_pass = bool(stable_source) and all( + row["pass"] for row in source_samples + ) and stable_source_extremum is not None + support_pass = bool(support_samples) and bool(stable_support) and all( + row["pass"] for row in support_samples + ) and stable_support_extremum is not None and meaningful_expansion + return { + "metric_definition": copy.deepcopy(_CALF_POSTERIOR_METRIC_DEFINITION), + "source_frame_F": list(source_forward), + "projection_direction": list(direction), + "exact_planar_section": { + "l0_calf_ring_vertex_ids": [int(index) for index in calf_indices], + "definition": "the eight exact L0 calf-ring samples only", + }, + "source_samples": source_samples, + "stable_source_sample_count": len(stable_source), + "indeterminate_source_sample_count": len(indeterminate_source), + "stable_source_extremum": stable_source_extremum, + "stable_source_responses_positive_or_bounded": source_pass, + "support_envelope": { + "definition": _CALF_POSTERIOR_METRIC_DEFINITION["support_envelope"], + "l2_vertex_count": len(support_samples), + "stable_vertex_count": len(stable_support), + "indeterminate_vertex_count": len(indeterminate_support), + "samples": support_samples, + "stable_extremum": stable_support_extremum, + "stable_responses_positive_or_bounded": support_pass, + "baseline_extremum": None if baseline_extent_row is None else { + "l2_vertex_id": baseline_extent_row["l2_vertex_id"], + "extent_m": baseline_extent, + }, + "actual_extremum": None if actual_extent_row is None else { + "l2_vertex_id": actual_extent_row["l2_vertex_id"], + "extent_m": actual_extent, + }, + "extent_difference_m": envelope_expansion, + "comparison_tolerance_m": comparison_tolerance, + "actual_expansion_in_minus_localF": meaningful_expansion, + }, + "pass": bool(source_pass and support_pass), + } + + +def _topology_equal(left: Any, right: Any) -> bool: + lmap, rmap = _mapping(left, "left mesh"), _mapping(right, "right mesh") + if lmap.get("quads") != rmap.get("quads"): + return False + lloops, rloops = lmap.get("loops"), rmap.get("loops") + return lloops == rloops + + +def _same_stencils(left: Any, right: Any) -> bool: + try: + return _stencil_rows(left, "left mesh") == _stencil_rows(right, "right mesh") + except PerturbationUnavailable: + return False + + +def _pose_only_j_metadata(mesh: Any, side: str, where: str) -> tuple[float, float, float]: + """Read the one rest-mesh metadata field allowed to follow a J perturbation.""" + value = _mapping(mesh, where) + metadata = _mapping(value.get("metadata"), f"{where}.metadata") + chains = _mapping(metadata.get("chains"), f"{where}.metadata.chains") + chain = _mapping(chains.get(side), f"{where}.metadata.chains.{side}") + if "pose_only_J" not in chain: + raise PerturbationUnavailable( + f"{where}.metadata.chains.{side}.pose_only_J is unavailable" + ) + return _vector(chain["pose_only_J"], + f"{where}.metadata.chains.{side}.pose_only_J") + + +def _without_pose_only_j_metadata(mesh: Any, side: str, where: str) -> dict[str, Any]: + """Copy a mesh while removing only the identified pose-only J field.""" + result = copy.deepcopy(dict(_mapping(mesh, where))) + metadata = _mapping(result.get("metadata"), f"{where}.metadata") + chains = _mapping(metadata.get("chains"), f"{where}.metadata.chains") + chain = _mapping(chains.get(side), f"{where}.metadata.chains.{side}") + if "pose_only_J" not in chain: + raise PerturbationUnavailable( + f"{where}.metadata.chains.{side}.pose_only_J is unavailable" + ) + del chain["pose_only_J"] + return result + + +def _compare_rest_construction(baseline: Any, actual: Any, side: str, + expected_J: Any, where: str) -> dict[str, Any]: + """Compare rest construction exactly except the declared pose-only J field. + + The redaction is deliberately a single, structural path. Comparing the + resulting dictionaries keeps vertices, quads, ports, stencils, frames, + owners, and every other shape-bearing field exact; a changed or missing + field cannot be hidden by this exception. + """ + baseline_map = _mapping(baseline, f"{where}.baseline") + actual_map = _mapping(actual, f"{where}.actual") + expected = _vector(expected_J, f"{where}.expected pose-only J") + baseline_j = _pose_only_j_metadata(baseline_map, side, f"{where}.baseline") + actual_j = _pose_only_j_metadata(actual_map, side, f"{where}.actual") + baseline_without_j = _without_pose_only_j_metadata( + baseline_map, side, f"{where}.baseline") + actual_without_j = _without_pose_only_j_metadata( + actual_map, side, f"{where}.actual") + + vertices_equal = baseline_map.get("vertices") == actual_map.get("vertices") + topology_equal = ( + baseline_map.get("quads") == actual_map.get("quads") and + baseline_map.get("loops") == actual_map.get("loops") + ) + stencil_keys = {"base_stencils", "stencils"} & ( + set(baseline_map) | set(actual_map) + ) + stencils_equal = bool(stencil_keys) and all( + baseline_map.get(key) == actual_map.get(key) for key in stencil_keys + ) and {key for key in baseline_map if key in ("base_stencils", "stencils")} == { + key for key in actual_map if key in ("base_stencils", "stencils") + } + all_other_fields_equal = baseline_without_j == actual_without_j + pose_only_j_matches = actual_j == expected + only_declared_metadata_changed = ( + all_other_fields_equal and pose_only_j_matches and actual_j != baseline_j + ) + return { + "vertices_equal": vertices_equal, + "quads_and_ports_equal": topology_equal, + "stencils_equal": stencils_equal, + "all_other_fields_equal": all_other_fields_equal, + "pose_only_J_matches_intended_source": pose_only_j_matches, + "only_declared_pose_only_J_metadata_changed": only_declared_metadata_changed, + "baseline_pose_only_J": list(baseline_j), + "actual_pose_only_J": list(actual_j), + "expected_pose_only_J": list(expected), + } + + +def _metadata_centres(mesh: Any, side: str) -> list[tuple[float, float, float]]: + metadata = _mapping(_mapping(mesh, "mesh").get("metadata"), "mesh.metadata") + chain = _mapping(_mapping(metadata.get("chains"), "mesh.metadata.chains").get(side), + f"mesh.metadata.chains.{side}") + sections = chain.get("sections") + if not isinstance(sections, (list, tuple)) or len(sections) != len(_SECTIONS): + raise PerturbationUnavailable(f"mesh metadata centres for {side} are unavailable") + return [_vector(_mapping(row, f"{side} section").get("centre"), + f"{side} section centre") for row in sections] + + +def _mean(vertices: Sequence[tuple[float, float, float]]) -> tuple[float, float, float]: + if not vertices: + raise PerturbationUnavailable("cannot average an empty loop") + return _scale(tuple(sum(point[axis] for point in vertices) for axis in range(3)), + 1.0 / len(vertices)) # type: ignore[return-value] + + +def _check(checks: dict[str, Any], name: str, passed: bool, **details: Any) -> None: + checks[name] = {"pass": bool(passed), **_jsonable(details)} + + +def _protocol_tolerance(protocol: Mapping[str, Any]) -> float: + checks = _mapping(protocol.get("checks"), "protocol.checks") + binding = _mapping(checks.get("binding_and_pose"), "protocol.checks.binding_and_pose") + value = _number(binding.get("source_effect_response_max_abs_error"), + "protocol source effect tolerance") + if value <= 0.0: + raise PerturbationUnavailable("protocol source effect tolerance must be positive") + return value + + +def _normalised_inputs(value: Any) -> tuple[dict[str, Any], dict[str, dict[str, Any]], dict[str, float], dict[str, float]]: + raw = _mapping(value, "leg_inputs") + normalised = copy.deepcopy(dict(raw)) + legs, factors, supports = _leg_values(normalised) + return normalised, legs, factors, supports + + +def _construct(root: Any, inputs: Mapping[str, Any], construction_module: Any) -> tuple[Any, Any, Any]: + build = getattr(construction_module, "build", None) + evaluate = getattr(construction_module, "evaluate", None) + if not callable(build) or not callable(evaluate): + raise PerturbationUnavailable("construction module lacks build/evaluate") + built = build(copy.deepcopy(root), copy.deepcopy(dict(inputs))) + levels = evaluate(built) + if not isinstance(levels, (list, tuple)) or len(levels) < 2: + raise PerturbationUnavailable("construction evaluator did not return L0 and L2") + return built, levels[0], levels[-1] + + +def _bind(base: Any, rest: Any, root: Any, prior_binding: Any, + inputs: Mapping[str, Any], binding_module: Any) -> Any: + bind = getattr(binding_module, "bind", None) + if not callable(bind): + raise PerturbationUnavailable("binding module lacks bind") + return bind(copy.deepcopy(base), copy.deepcopy(rest), copy.deepcopy(root), + copy.deepcopy(prior_binding), copy.deepcopy(dict(inputs))) + + +def _record_exception(record: dict[str, Any], status: str, exc: Exception) -> dict[str, Any]: + record["status"] = status + record.setdefault("exceptions", []).append({ + "type": type(exc).__name__, + "message": str(exc), + }) + return record + + +def _base_record(spec: Mapping[str, Any], inputs: Mapping[str, Any]) -> dict[str, Any]: + return { + "id": str(spec.get("id")), + "status": "unavailable", + "intermediate_input": {"before": _jsonable(inputs)}, + "expected": {}, + "checks": {}, + "diagnostic_meshes": {}, + "exceptions": [], + } + + +def _run_A(record: dict[str, Any], spec: Mapping[str, Any], context: Mapping[str, Any]) -> None: + mutated, change = _apply_declared_change(context["inputs"], spec) + record["intermediate_input"]["change"] = change + record["intermediate_input"]["after"] = _jsonable(mutated) + _normalised, mutated_legs, factors, supports = _normalised_inputs(mutated) + built, l0, l2 = _construct(context["root"], _normalised, context["construction"]) + record["diagnostic_meshes"].update({"built_L0": _jsonable(built), + "perturbed_L0": _jsonable(l0), + "perturbed_L2": _jsonable(l2)}) + binding = _bind(l0, l2, context["root"], context["prior_binding"], + _normalised, context["binding"]) + record["binding"] = _jsonable(binding) + + expected_l0, ring_maps, plans = _analytic_l0_vertices( + context["baseline_L0"], context["root"], mutated_legs, factors, supports, + context["tolerance"] + ) + baseline_vertices = _mesh_vertices(context["baseline_L0"], "baseline_L0") + actual_vertices = _mesh_vertices(l0, "perturbed_L0") + actual_delta = _delta(actual_vertices, baseline_vertices) + expected_delta = _delta(expected_l0, context["baseline_expected_L0"]) + ankle_index = _SECTIONS.index("ankle") + left_plan = plans["left"] + left_ankle_mean = _mean(left_plan["section_points"][ankle_index]) + ankle_loop = _loop(l2, "port.left_ankle", "perturbed_L2") + ankle_points = [_mesh_vertices(l2, "perturbed_L2")[index] for index in ankle_loop] + outgoing = left_plan["outgoing"] + ankle_frame = left_plan["frames"][ankle_index] + A = left_plan["points"]["A"] + ankle_radii = left_plan["radii"][ankle_index] + expected_l0_mesh = copy.deepcopy(context["baseline_L0"]) + expected_l0_mesh["vertices"] = [list(point) for point in expected_l0] + record["expected"].update({ + "source_section_centres": { + side: [list(point) for point in plans[side]["centres"]] + for side in _SIDES + }, + "changed_source_sections": [ + name for name, before, after in zip( + _SECTIONS, context["plans"]["left"]["centres"], plans["left"]["centres"] + ) if not _zero(_sub(after, before), context["tolerance"]) + ], + "ankle_expected_world_loop_mean": list(left_ankle_mean), + "open_boundary_mean_rule": ( + "Each Catmull-Clark open-boundary level emits old boundary vertices " + "and edge midpoints; the arithmetic loop mean is preserved." + ), + "ankle_source_frame": {key: list(value) for key, value in ankle_frame.items()}, + "ankle_radii": list(ankle_radii), + "l0_delta": [list(point) for point in expected_delta], + }) + record["diagnostic_meshes"]["expected_L0"] = _jsonable(expected_l0_mesh) + checks = record["checks"] + _check(checks, "topology_unchanged", + _topology_equal(context["baseline_L0"], l0) and + _topology_equal(context["baseline_L2"], l2), + correspondence="same face/loop topology; support locality uses full stencils") + _check(checks, "source_driven_l0_response", + _max_delta_error(actual_delta, expected_delta) <= context["tolerance"], + max_abs_error=_max_delta_error(actual_delta, expected_delta), + tolerance=context["tolerance"]) + _check(checks, "source_section_centres_follow_TKA", + all(_max_abs(actual, expected) <= context["tolerance"] + for side in _SIDES + for actual, expected in zip( + _metadata_centres(l0, side), plans[side]["centres"])), + metadata_is_diagnostic_only=True) + l2_mean = _mean(ankle_points) + _check(checks, "l2_ankle_mean_matches_analytic_l0_mean", + _max_abs(l2_mean, left_ankle_mean) <= context["tolerance"], + actual=list(l2_mean), expected=list(left_ankle_mean), + tolerance=context["tolerance"]) + coplanar = max((abs(_dot(_sub(point, A), outgoing)) for point in ankle_points), + default=math.inf) + _check(checks, "ankle_boundary_coplanar_with_source_KA_frame", + coplanar <= context["tolerance"], max_abs_plane_residual=coplanar, + tolerance=context["tolerance"]) + within = True + envelope_residual = 0.0 + for point in ankle_points + [A]: + local = _sub(point, A) + lateral = abs(_dot(local, ankle_frame["X"])) + forward = _dot(local, ankle_frame["F"]) + depth = ankle_radii[1] if forward >= 0.0 else ankle_radii[2] + envelope_residual = max(envelope_residual, + lateral - ankle_radii[0], abs(forward) - depth) + within = within and lateral <= ankle_radii[0] + context["tolerance"] + within = within and abs(forward) <= depth + context["tolerance"] + _check(checks, "A_within_ankle_radial_envelope", within, + max_envelope_residual=envelope_residual, + tolerance=context["tolerance"]) + root_count = len(_mesh_vertices(context["root"], "root")) + root_unchanged = all(_zero(actual_delta[index], context["tolerance"]) + for index in range(min(root_count, len(actual_delta)))) + _check(checks, "upper_root_unaffected_by_source_A", root_unchanged, + proof="original root vertex prefix compared by preserved face topology") + support_indices = {index for index, point in enumerate(expected_delta) + if not _zero(point, context["tolerance"])} + far_root = all(_zero(actual_delta[index], context["tolerance"]) + for index in range(len(actual_delta)) if index not in support_indices) + _check(checks, "contralateral_and_far_L0_unchanged", far_root, + support_index_count=len(support_indices)) + baseline_l2_vertices = _mesh_vertices(context["baseline_L2"], "baseline_L2") + l2_vertices = _mesh_vertices(l2, "perturbed_L2") + l2_rows = _stencil_rows(context["baseline_L2"], "baseline_L2") + far_l2_indices = [index for index, row in enumerate(l2_rows) + if not any(base_index in support_indices for base_index, _ in row)] + far_l2 = all(_zero(_sub(l2_vertices[index], baseline_l2_vertices[index]), + context["tolerance"]) for index in far_l2_indices) + _check(checks, "far_L2_unchanged_by_full_stencil_support", far_l2, + far_vertex_count=len(far_l2_indices), + correspondence="full L2 stencil support; not old/new vertex-ID inference") + _check(checks, "full_L2_stencils_preserved", _same_stencils(context["baseline_L2"], l2)) + record["status"] = "pass" if all(item["pass"] for item in checks.values()) else "failed" + + +def _run_calf(record: dict[str, Any], spec: Mapping[str, Any], context: Mapping[str, Any]) -> None: + mutated, change = _apply_declared_change(context["inputs"], spec) + record["intermediate_input"]["change"] = change + record["intermediate_input"]["after"] = _jsonable(mutated) + _normalised, mutated_legs, factors, supports = _normalised_inputs(mutated) + built, l0, l2 = _construct(context["root"], _normalised, context["construction"]) + record["diagnostic_meshes"].update({"built_L0": _jsonable(built), + "perturbed_L0": _jsonable(l0), + "perturbed_L2": _jsonable(l2)}) + binding = _bind(l0, l2, context["root"], context["prior_binding"], + _normalised, context["binding"]) + record["binding"] = _jsonable(binding) + expected_l0, ring_maps, plans = _analytic_l0_vertices( + context["baseline_L0"], context["root"], mutated_legs, factors, supports, + context["tolerance"] + ) + baseline_expected, _, baseline_plans = _analytic_l0_vertices( + context["baseline_L0"], context["root"], context["legs"], + context["factors"], context["supports"], context["tolerance"] + ) + expected_delta = _delta(expected_l0, baseline_expected) + baseline_vertices = _mesh_vertices(context["baseline_L0"], "baseline_L0") + actual_vertices = _mesh_vertices(l0, "perturbed_L0") + actual_delta = _delta(actual_vertices, baseline_vertices) + calf_coefficients: dict[str, float] = {} + for name, fraction in zip(_SECTIONS, plans["left"]["fractions"]): + if name in ("mid_thigh", "knee_pre_support", "knee", "ankle"): + coefficient = 0.0 + elif fraction <= _CALF_FRACTION: + coefficient = fraction / _CALF_FRACTION + else: + coefficient = (1.0 - fraction) / (1.0 - _CALF_FRACTION) + calf_coefficients[name] = coefficient + posterior_input_delta = ( + _vector(mutated_legs["left"]["radii"]["calf"], "mutated calf")[2] - + _vector(context["legs"]["left"]["radii"]["calf"], "baseline calf")[2] + ) + explicit_delta = [(0.0, 0.0, 0.0) for _ in baseline_vertices] + template = baseline_plans["left"]["template"] + for name in ("knee_post_support", "calf", "ankle_approach"): + coefficient = calf_coefficients[name] + frame = baseline_plans["left"]["frames"][_SECTIONS.index(name)] + for vertex_index, (_, forward) in zip(ring_maps["left"][name], template): + if forward < 0.0: + explicit_delta[vertex_index] = _scale( + frame["F"], forward * posterior_input_delta * coefficient + ) + record["expected"].update({ + "piecewise_calf_posterior_coefficients": calf_coefficients, + "analytic_L0_delta": [list(point) for point in explicit_delta], + "posterior_template_direction": "negative forward-template vertices move in -localF", + }) + l2_expected_delta = _expected_l2_delta(explicit_delta, context["baseline_L2"]) + baseline_l2_vertices = _mesh_vertices(context["baseline_L2"], "baseline_L2") + actual_l2_vertices = _mesh_vertices(l2, "perturbed_L2") + actual_l2_delta = _delta(actual_l2_vertices, baseline_l2_vertices) + checks = record["checks"] + _check(checks, "topology_unchanged", + _topology_equal(context["baseline_L0"], l0) and + _topology_equal(context["baseline_L2"], l2)) + l0_error = _max_delta_error(actual_delta, explicit_delta) + _check(checks, "analytic_L0_parameter_response", + l0_error <= context["tolerance"], max_abs_error=l0_error, + tolerance=context["tolerance"]) + l2_error = _max_delta_error(actual_l2_delta, l2_expected_delta) + _check(checks, "analytic_full_stencil_L2_response", + l2_error <= context["tolerance"], max_abs_error=l2_error, + tolerance=context["tolerance"], + comparison="baseline full L2 stencils propagated from analytic L0 delta") + _check(checks, "source_KA_frame_unchanged", + baseline_plans["left"]["outgoing"] == plans["left"]["outgoing"] and + baseline_plans["left"]["frames"] == plans["left"]["frames"]) + points_unchanged = all( + _vector(mutated_legs[side][name], f"mutated {side}.{name}") == + _vector(context["legs"][side][name], f"baseline {side}.{name}") + for side in _SIDES for name in ("J", "T", "K", "A") + ) + _check(checks, "J_T_K_A_unchanged", points_unchanged) + ankle_loop_before = _loop(context["baseline_L2"], "port.left_ankle", "baseline_L2") + ankle_loop_after = _loop(l2, "port.left_ankle", "perturbed_L2") + ankle_same = ankle_loop_before == ankle_loop_after and all( + _zero(actual_l2_delta[index], context["tolerance"]) + for index in ankle_loop_after + ) + _check(checks, "ankle_boundary_and_loop_mean_unchanged", ankle_same, + reason="calf is an internal station, not an open boundary") + root_count = len(_mesh_vertices(context["root"], "root")) + root_same = all(_zero(actual_delta[index], context["tolerance"]) + for index in range(min(root_count, len(actual_delta)))) + right_same = all(_zero(actual_delta[index], context["tolerance"]) + for index in ring_maps["right"]["mid_thigh"] + + ring_maps["right"]["knee_pre_support"] + + ring_maps["right"]["knee"] + + ring_maps["right"]["knee_post_support"] + + ring_maps["right"]["calf"] + + ring_maps["right"]["ankle_approach"] + + ring_maps["right"]["ankle"]) + _check(checks, "root_and_other_leg_unchanged", root_same and right_same) + calf_indices = ring_maps["left"]["calf"] + calf_frame = baseline_plans["left"]["frames"][_SECTIONS.index("calf")] + posterior_measurement = _calf_posterior_measurement( + baseline_vertices, actual_delta, explicit_delta, calf_indices, template, + baseline_l2_vertices, + _stencil_rows(context["baseline_L2"], "baseline_L2"), + actual_l2_delta, l2_expected_delta, calf_frame, + baseline_plans["left"]["centres"][_SECTIONS.index("calf")], + context["tolerance"], + ) + record["metadata"] = { + "measurement_definition": copy.deepcopy( + _CALF_POSTERIOR_METRIC_DEFINITION + ), + "frozen_protocol_unchanged": True, + } + _check(checks, "signed_calf_posterior_expansion", + posterior_measurement["pass"], **posterior_measurement) + _check(checks, "full_L2_stencils_available", + len(_stencil_rows(context["baseline_L2"], "baseline_L2")) == len(baseline_l2_vertices)) + record["diagnostic_meshes"]["expected_L2_delta"] = [list(point) for point in l2_expected_delta] + record["status"] = "pass" if all(item["pass"] for item in checks.values()) else "failed" + + +def _rotation_about_axis(point: tuple[float, float, float], + pivot: tuple[float, float, float], + axis: tuple[float, float, float], + degrees: float) -> tuple[float, float, float]: + radians = math.radians(degrees) + cosine, sine = math.cos(radians), math.sin(radians) + value = _sub(point, pivot) + cross = _cross(axis, value) + parallel = _scale(axis, _dot(axis, value)) + rotated = _add(_scale(value, cosine), _scale(cross, sine), + _scale(parallel, 1.0 - cosine)) + return _add(pivot, rotated) + + +def _hip_axis(J: tuple[float, float, float], + K: tuple[float, float, float]) -> tuple[float, float, float]: + y_axis = _unit(_sub(J, K), "independent hip J-K axis") + return _unit(_sub((1.0, 0.0, 0.0), + _scale(y_axis, _dot((1.0, 0.0, 0.0), y_axis))), + "independent hip projected +X axis") + + +def _weights(binding: Any, count: int) -> list[list[float]]: + raw = _mapping(binding, "binding").get("evaluated_weights") + if not isinstance(raw, (list, tuple)) or len(raw) != count: + raise PerturbationUnavailable("binding evaluated_weights do not cover L2") + result = [] + for index, row in enumerate(raw): + if not isinstance(row, (list, tuple)) or len(row) != 5: + raise PerturbationUnavailable(f"binding evaluated_weights[{index}] must have five columns") + result.append([_number(value, f"binding weight {index}") for value in row]) + return result + + +def _independent_hip_pose(vertices: Sequence[tuple[float, float, float]], + weights: Sequence[Sequence[float]], + J: tuple[float, float, float], + K: tuple[float, float, float], + hip_degrees: float) -> tuple[list[tuple[float, float, float]], tuple[float, float, float]]: + axis = _hip_axis(J, K) + result = [] + for point, row in zip(vertices, weights): + transformed = _rotation_about_axis(point, J, axis, -hip_degrees) + left_weight = row[1] + row[2] + result.append(_add(_scale(point, 1.0 - left_weight), + _scale(transformed, left_weight))) + return result, axis + + +def _pose_spec(protocol: Mapping[str, Any]) -> Mapping[str, Any]: + poses = protocol.get("baseline_poses") + if not isinstance(poses, (list, tuple)): + raise PerturbationUnavailable("protocol baseline_poses is unavailable") + for pose in poses: + if isinstance(pose, Mapping) and pose.get("id") == "Lhip15_knee0": + return pose + raise PerturbationUnavailable("protocol does not declare Lhip15_knee0") + + +def _angles(pose: Mapping[str, Any]) -> dict[str, dict[str, float]]: + result = {} + for side in _SIDES: + row = _mapping(pose.get(side), f"pose.{side}") + result[side] = { + "hip": _number(row.get("hip"), f"pose.{side}.hip"), + "knee": _number(row.get("knee"), f"pose.{side}.knee"), + "ankle": _number(row.get("ankle", 0.0), f"pose.{side}.ankle"), + } + return result + + +def _run_J(record: dict[str, Any], spec: Mapping[str, Any], context: Mapping[str, Any]) -> None: + mutated, change = _apply_declared_change(context["inputs"], spec) + record["intermediate_input"]["change"] = change + record["intermediate_input"]["after"] = _jsonable(mutated) + _normalised, mutated_legs, factors, supports = _normalised_inputs(mutated) + built, l0, l2 = _construct(context["root"], _normalised, context["construction"]) + record["diagnostic_meshes"].update({"built_L0": _jsonable(built), + "perturbed_L0": _jsonable(l0), + "perturbed_L2": _jsonable(l2)}) + binding = _bind(l0, l2, context["root"], context["prior_binding"], + _normalised, context["binding"]) + record["binding"] = _jsonable(binding) + checks = record["checks"] + l0_rest = _compare_rest_construction( + context["baseline_L0"], l0, "left", mutated_legs["left"]["J"], + "rest_L0") + l2_rest = _compare_rest_construction( + context["baseline_L2"], l2, "left", mutated_legs["left"]["J"], + "rest_L2") + for level, comparison in (("L0", l0_rest), ("L2", l2_rest)): + _check( + checks, f"rest_{level}_shape_exactly_unchanged_except_pose_only_J", + comparison["all_other_fields_equal"], **comparison, + ) + _check( + checks, f"rest_{level}_pose_only_J_matches_intended_source", + comparison["pose_only_J_matches_intended_source"], **comparison, + ) + _check( + checks, f"rest_{level}_only_declared_pose_only_J_metadata_changed", + comparison["only_declared_pose_only_J_metadata_changed"], **comparison, + ) + baseline_l2_vertices = _mesh_vertices(context["baseline_L2"], "baseline_L2") + base_weights = _weights(context["baseline_binding"], len(baseline_l2_vertices)) + perturbed_weights = _weights(binding, len(baseline_l2_vertices)) + _check(checks, "weights_exactly_unchanged", perturbed_weights == base_weights) + pose = _pose_spec(context["protocol"]) + angles = _angles(pose) + _check(checks, "declared_Lhip15_knee0_has_zero_knee", angles["left"]["knee"] == 0.0) + pose_call = getattr(context["binding"], "pose", None) + if not callable(pose_call): + raise PerturbationUnavailable("binding module lacks pose") + baseline_pose = pose_call(copy.deepcopy(context["baseline_L2"]), + copy.deepcopy(context["baseline_binding"]), angles) + perturbed_pose = pose_call(copy.deepcopy(l2), copy.deepcopy(binding), angles) + baseline_pose_vertices = _mesh_vertices(baseline_pose, "baseline pose") + perturbed_pose_vertices = _mesh_vertices(perturbed_pose, "perturbed pose") + expected_baseline, baseline_axis = _independent_hip_pose( + baseline_l2_vertices, base_weights, + _vector(context["legs"]["left"]["J"], "baseline left J"), + _vector(context["legs"]["left"]["K"], "baseline left K"), + angles["left"]["hip"], + ) + expected_perturbed, perturbed_axis = _independent_hip_pose( + baseline_l2_vertices, perturbed_weights, + _vector(mutated_legs["left"]["J"], "perturbed left J"), + _vector(mutated_legs["left"]["K"], "perturbed left K"), + angles["left"]["hip"], + ) + actual_response = _delta(perturbed_pose_vertices, baseline_pose_vertices) + expected_response = _delta(expected_perturbed, expected_baseline) + response_error = _max_delta_error(actual_response, expected_response) + expected_pose_mesh = copy.deepcopy(perturbed_pose) + expected_pose_mesh["vertices"] = [list(point) for point in expected_perturbed] + record["diagnostic_meshes"].update({ + "baseline_pose": _jsonable(baseline_pose), + "perturbed_pose": _jsonable(perturbed_pose), + "expected_perturbed_pose": _jsonable(expected_pose_mesh), + }) + record["expected"].update({ + "pose_id": pose.get("id"), + "angles": _jsonable(angles), + "independent_oracle": "Rodrigues rotation about projected +X perpendicular to J-K, with positive hip Rx(-angle); knee is not used as an oracle", + "baseline_hip_axis": list(baseline_axis), + "perturbed_hip_axis": list(perturbed_axis), + "response": [list(point) for point in expected_response], + }) + _check(checks, "independent_weighted_Rodrigues_pose_response", + response_error <= context["tolerance"], + max_abs_error=response_error, tolerance=context["tolerance"], + oracle="independent weighted export, not binding.pose output") + _check(checks, "rest_points_TKA_unchanged", + all(_vector(mutated_legs[side][name], f"mutated {side}.{name}") == + _vector(context["legs"][side][name], f"baseline {side}.{name}") + for side in _SIDES for name in ("T", "K", "A"))) + record["status"] = "pass" if all(item["pass"] for item in checks.values()) else "failed" + + +def run_case(root: Any, prior_rest: Any, prior_binding: Any, + leg_inputs: Any, baseline_L0: Any, baseline_L2: Any, + baseline_binding: Any, protocol: Any, + construction_module: Any, binding_module: Any) -> dict[str, Any]: + """Run exactly the three declared perturbations for one captured case. + + The function performs no real-body call by itself. A captured runner may + supply real collaborator modules; unit tests should supply synthetic ones. + Any incoherent input or collaborator returns an explicit ``unavailable`` + record rather than silently treating a missing check as a pass. + """ + result: dict[str, Any] = { + "schema": "creature-kernel.connected-leg-assembly-perturbation-evidence.v1", + "status": "unavailable", + "declared_perturbation_ids": [], + "perturbations": [], + "exceptions": [], + } + try: + protocol_map = _mapping(protocol, "protocol") + raw_specs = protocol_map.get("input_perturbations") + if not isinstance(raw_specs, (list, tuple)): + raise PerturbationUnavailable("protocol.input_perturbations must be a list") + specs = [_mapping(spec, "protocol perturbation") for spec in raw_specs] + ids = [str(spec.get("id")) for spec in specs] + result["declared_perturbation_ids"] = ids + if ids != list(_PERTURBATION_IDS): + raise PerturbationUnavailable( + "protocol must declare exactly the three bounded perturbations in order" + ) + tolerance = _protocol_tolerance(protocol_map) + inputs, legs, factors, supports = _normalised_inputs(leg_inputs) + # This source plan is an independent baseline reference, not expected + # geometry copied from construction metadata. + baseline_expected, _, baseline_plans = _analytic_l0_vertices( + baseline_L0, root, legs, factors, supports, tolerance + ) + _mesh_vertices(prior_rest, "prior_rest") + _mesh_vertices(baseline_L2, "baseline_L2") + _mesh_vertices(baseline_L0, "baseline_L0") + context = { + "root": root, + "prior_rest": prior_rest, + "prior_binding": prior_binding, + "inputs": inputs, + "legs": legs, + "factors": factors, + "supports": supports, + "baseline_L0": baseline_L0, + "baseline_L2": baseline_L2, + "baseline_binding": baseline_binding, + "protocol": protocol_map, + "construction": construction_module, + "binding": binding_module, + "tolerance": tolerance, + "plans": baseline_plans, + "baseline_expected_L0": baseline_expected, + } + handlers = { + _PERTURBATION_IDS[0]: _run_A, + _PERTURBATION_IDS[1]: _run_calf, + _PERTURBATION_IDS[2]: _run_J, + } + for spec in specs: + record = _base_record(spec, inputs) + try: + handlers[str(spec["id"])](record, spec, context) + except PerturbationUnavailable as exc: + _record_exception(record, "unavailable", exc) + except Exception as exc: # explicit capture for runner serialization + _record_exception(record, "unavailable", exc) + result["perturbations"].append(record) + statuses = [record["status"] for record in result["perturbations"]] + if all(status == "pass" for status in statuses): + result["status"] = "pass" + elif any(status == "failed" for status in statuses): + result["status"] = "failed" + else: + result["status"] = "unavailable" + result["thresholds"] = {"analytic_response_tolerance": tolerance} + except PerturbationUnavailable as exc: + result["status"] = "unavailable" + result["exceptions"].append({"type": type(exc).__name__, "message": str(exc)}) + except Exception as exc: + result["status"] = "unavailable" + result["exceptions"].append({"type": type(exc).__name__, "message": str(exc)}) + return _jsonable(result) + + +__all__ = ["PerturbationUnavailable", "run_case"] diff --git a/experiments/connected-leg-assembly/protocol.json b/experiments/connected-leg-assembly/protocol.json new file mode 100644 index 0000000..1ae83a7 --- /dev/null +++ b/experiments/connected-leg-assembly/protocol.json @@ -0,0 +1,284 @@ +{ + "schema": "creature-kernel.connected-leg-assembly-protocol.v1", + "experiment_id": "EXP-0003", + "experiment_lifecycle": "planned", + "evidence_closure": "open", + "technology_outcome": "none", + "execution_state": "not_started", + "question": "Does one source-driven welded knee/shank extension from the saved calibrated L0 roots retain prior hip quality, preserve the connected surface, and follow explicit T/K/A source points and radii on actual L2 evaluated surfaces for both cases?", + "scope": { + "included": [ + "experiment-local connected root extension from the former thigh exits through knee and shank", + "open ankle boundary ports", + "common source, frame, subdivision, and hierarchical automatic-binding pipeline", + "ordinary-human and approved loose wolf-like humanoid anthropomorphic coarse cases", + "rest and restrained combined poses" + ], + "excluded": [ + "complete foot, heel, sole, paw, or whole-body completion", + "species or gait-specific production geometry contract", + "detailed fingers, facial animation, fur/render polish, advanced physics, engine integration", + "publication, push, merge, or production architecture" + ], + "case_symmetry": "Use the same construction and binding formulas for both cases; side mirroring is input data, not a case-specific repair.", + "anatomy_boundary": "A is the anthropomorphic case's provisional posterior ankle endpoint. It does not establish the future raised-heel/foot design." + }, + "method": { + "source_and_shape": { + "root": "Load each immutable calibrated L0 root and its matching immutable prior L2 rest mesh from inputs.json.", + "preserve": ["J", "T", "K", "original root inputs", "original root mesh", "prior hip binding evidence"], + "source_driven_skin": true, + "shared_formulas": true, + "painted_case_repairs": false, + "disconnected_display_meshes": false, + "former_thigh_exit": "Weld into the extension and treat as interior; do not assert prior boundary invariance at the former exit." + }, + "source_stations": [ + {"id": "0.70TK", "point": "T + 0.70 * (K - T)"}, + {"id": "0.90TK", "point": "T + 0.90 * (K - T)"}, + {"id": "K", "point": "K"}, + {"id": "K+0.12KA", "point": "K + 0.12 * (A - K)"}, + {"id": "K+0.35KA", "point": "K + 0.35 * (A - K)"}, + {"id": "K+0.72KA", "point": "K + 0.72 * (A - K)"}, + {"id": "A", "point": "A"} + ], + "section_and_knee_construction": { + "radii_order": ["lateral", "anterior", "posterior"], + "radii_source": "Use each side's explicit knee, calf, and ankle radii from inputs.json; do not force anterior/posterior equality.", + "knee_blend": { + "operator": "one explicit shared source-station knee blend", + "source_stations": ["T", "K", "A"], + "harmonic_knee": false, + "formula_policy": "Derive station centers, frames, and cross-sections from T/K/A and declared radii with the same formula on both cases; no harmonic solve and no painted replacement at K." + }, + "mid_thigh_factor": 0.85, + "support_fraction": 0.1, + "support_fraction_semantics": { + "value": 0.1, + "incoming_station": "1-s at nominal station 0.90TK", + "outgoing_station": "1.2s at nominal station K+0.12KA", + "meaning": "Support fraction governs the incoming and outgoing station influence; it is not an ignored field." + }, + "nominal_station_names": "Labels for the declared stations only; formulas use the source-point expressions and the support-fraction semantics above.", + "anthro_segment_frame": "Build the K-to-A rest frame from the actual angled K-A vector; do not assume a vertical shank." + }, + "binding": { + "prior_root_base_weights": { + "shape": [152, 3], + "columns": ["pelvis", "leftthigh", "rightthigh"], + "preserve_exact": true, + "mapping_to_new_columns": { + "new_columns": ["pelvis", "leftthigh", "leftshank", "rightthigh", "rightshank"], + "row_formula": "[pelvis, leftthigh, rightthigh] -> [pelvis, leftthigh, 0, rightthigh, 0]" + } + }, + "new_ring_weights": { + "station_order": ["0.70TK", "0.90TK", "K", "K+0.12KA", "K+0.35KA", "K+0.72KA", "A"], + "left_shank": [0, 0, 0.5, 1, 1, 1, 1], + "left_complementary_thigh": [1, 1, 0.5, 0, 0, 0, 0], + "right_shank": [0, 0, 0.5, 1, 1, 1, 1], + "right_complementary_thigh": [1, 1, 0.5, 0, 0, 0, 0], + "all_nonlocal_columns": 0, + "interpretation": "Apply the corresponding side's thigh/shank columns; each pair sums to one at every new ring." + }, + "stencils": "Propagate actual expanded L0-to-L2 subdivision stencils, never dominant-owner labels or a synthetic rest mesh.", + "hierarchy": { + "parent_order": ["pelvis", "hip", "thigh", "knee", "shank", "ankle_port"], + "rest_frames": "Use independent J as hip pose input, J-to-K for the hip/thigh rest frame, and K-to-A for the knee/shank rest frame.", + "pose_transform": "Apply inverse-bind then posed-global transforms in the parent/rest hierarchy.", + "positive_rotation_convention": { + "hip": "Rx(-angle)", + "knee": "Rx(+angle)", + "ankle": "Rx(0) staging" + }, + "cross_influences": "Hip movement must carry the hierarchical descendants; knee movement must affect the shank/ankle descendants while the explicit source-station transition remains observable." + } + } + }, + "baseline_poses": [ + { + "id": "rest", + "left": {"hip": 0, "knee": 0, "ankle": 0}, + "right": {"hip": 0, "knee": 0, "ankle": 0} + }, + { + "id": "Lhip15_knee0", + "left": {"hip": 15, "knee": 0, "ankle": 0}, + "right": {"hip": 0, "knee": 0, "ankle": 0} + }, + { + "id": "Lhip30_knee30", + "left": {"hip": 30, "knee": 30, "ankle": 0}, + "right": {"hip": 0, "knee": 0, "ankle": 0} + }, + { + "id": "mirrored15_15", + "label": "mirrored 15/15", + "left": {"hip": 0, "knee": 0, "ankle": 0}, + "right": {"hip": 15, "knee": 15, "ankle": 0}, + "meaning": "mirrored unilateral right-leg local sagittal pose; both20 supplies the symmetric bilateral case" + }, + { + "id": "bothhip20_knee20", + "left": {"hip": 20, "knee": 20, "ankle": 0}, + "right": {"hip": 20, "knee": 20, "ankle": 0} + } + ], + "input_perturbations": [ + { + "id": "left_A_y_minus_0.02", + "case_scope": "both", + "change": {"path": "cases[*].leg_inputs.left.A[1]", "operation": "add", "value": -0.02}, + "rest_geometry": "reconstruct the affected left distal source-driven extension; keep J/T/K and the right side unchanged", + "expected": "left distal station centers, K-A frame, final loop mean, and ankle-port placement respond in the negative-y direction; no centroid-equals-A assertion and no unrelated hip movement", + "evaluation": "compare against the analytic construction response and predicted loop mean, not merely changed vertex coordinates" + }, + { + "id": "left_calf_posterior_radius_times_1.10", + "case_scope": "both", + "change": {"path": "cases[*].leg_inputs.left.radii.calf[2]", "operation": "multiply", "value": 1.1}, + "rest_geometry": "reconstruct only the internal calf station through the shared source/radius formula; keep centerline J/T/K/A unchanged and leave the open ankle boundary/loop mean unchanged", + "expected": "actual L2 calf posterior envelope expands in -localF; centerline, ankle boundary, ankle loop mean, hip, and contralateral body remain unchanged", + "evaluation": "verify signed sectional-envelope response and analytical L2 displacement using fixed source frames and propagated stencils, not merely changed vertex coordinates" + }, + { + "id": "left_J_y_plus_0.01_at_hip15", + "case_scope": "both", + "change": {"path": "cases[*].leg_inputs.left.J[1]", "operation": "add", "value": 0.01}, + "pose": "Lhip15_knee0", + "rest_geometry": "identical to the unperturbed rest geometry; alter only the independent hip pose input and its rest-frame/pivot calculation", + "expected": "left hip-pivot pose displacement follows the analytic J change, with hierarchical descendants responding through the hip; rest vertices, source radii, and weights remain unchanged", + "evaluation": "compare analytic pose response and locality, not merely vertexchanged" + } + ], + "diagnostic_distinctions": { + "asymmetric_section_radii": { + "centroid_equals_joint_gate": false, + "reason": "Different anterior and posterior radii translate the section loop centroid away from its source centerline point.", + "required_gates": [ + "final ankle boundary is coplanar with its source section/frame", + "translated loop mean matches the analytic L0 placement plus the existing Catmull-Clark open-boundary rule", + "declared A is meaningful as the source endpoint and lies within the endpoint radial envelope" + ], + "anatomy_plausibility": "Keep visual anatomy judgment separate from the geometric section/centroid gates." + }, + "hip_regression": { + "comparison": "Compare prior/current hip-region surfaces by stencil-support mapping.", + "original_prefix": "Original L0 vertices/faces are preserved as a prefix.", + "correspondence": "Deterministic child-face/corner correspondence maps the old patch to the new patch for actual displacement; old/new vertex IDs are not direct correspondence.", + "exact_invariance": "Identical full stencils identify the far unchanged subset only.", + "near_exit": "Report drift around the now-interior former thigh exit; do not invent a universal tolerance.", + "inherited_upper": "Keep inherited upper-region failures separate from new lower-leg failures." + } + }, + "checks": { + "topology_and_geometry": { + "finite_vertices": true, + "valid_quad_indices": true, + "one_connected_component": true, + "boundary_ports": { + "exact_count": 5, + "retain": ["port.neck", "port.left_arm", "port.right_arm"], + "replace_former_thigh_ports": ["port.left_thigh", "port.right_thigh"], + "add_open_ports": ["port.left_ankle", "port.right_ankle"] + }, + "nonmanifold_edges": 0, + "winding_consistency": "required", + "positive_edges_and_areas": { + "scale": 1.0, + "minimum_edge_over_scale": 1e-08, + "minimum_triangle_area_over_scale_squared": 1e-10 + }, + "full_L0_stencil_coverage": "mandatory for every expanded L0 vertex used by L2" + }, + "binding_and_pose": { + "rest_identity_max_abs_error": 1e-09, + "weight_sum_max_abs_error": 1e-09, + "rest_transform_max_abs_error": 1e-09, + "hierarchical_K_A_response_max_abs_error": 1e-08, + "source_effect_response_max_abs_error": 1e-08, + "actual_expanded_stencils": "mandatory", + "independent_J": "must remain observable as a pose input without changing rest geometry in the J perturbation" + }, + "intersections": { + "lower_nonadjacent": { + "availability_required": true, + "complete_coverage_required": true, + "pass_required": true + }, + "inherited_upper": { + "report_separately": true, + "not_substituted_for_lower_pass": true + } + }, + "strain_and_collapse_diagnostics": { + "edge_ratio_report_range": [0.5, 2.0], + "edge_ratio_outside_range": "flag, not silently discard", + "triangle_area_ratio_report_range": [0.4, 2.5], + "triangle_area_ratio_outside_range": "flag, not silently discard", + "corresponding_triangle_dot_less_or_equal_zero": "diagnostic gross collapse flag", + "threshold_status": "new coarse safeguards for this staging protocol; not inherited acceptance thresholds from the old experiments" + } + }, + "visual_review": { + "views": ["front", "side", "rear_three_quarter"], + "fixtures": "matched camera, scale, lighting, and framing across prior/current rest and pose outputs", + "overlays": true, + "initial_geometry_before_binding": "may be rendered as a diagnostic, but is not a posed result", + "final_candidate": "Main Worker personally reviews actual images for every declared case/pose before any result is reported", + "direct_rejects": ["seam", "tear", "collapse", "knee bulbs", "sideways shank", "hip regression"], + "volume_claims": false, + "open_surface_note": "Open surfaces and inner walls must not be interpreted as capped solids or global volume evidence." + }, + "budget_and_failure_policy": { + "initial_candidate_count": 1, + "shared_construction_or_binding_correction_max": 1, + "correction_condition": "only one evidence-justified shared correction after the initial candidate", + "per_case_fixes": false, + "automatic_alternative": false, + "failure_hiding": false, + "retain_initial_failures": true, + "escalate_if_unconvincing_after_budget": "report to Overseer before any further work", + "internal_milestone_only": true + }, + "execution_boundary": { + "preparation_pass": { + "execution": false, + "body_generation": false, + "geometry_execution": false, + "candidate_capture": false, + "reason": "This pass only prepares and reviews the bounded inputs/protocol." + }, + "future_authorized_captured_run": { + "may_execute": true, + "authorization": "Only after Main review and within the declared experiment budget; no automatic trigger or automatic run.", + "pre_body_capture_required": { + "source_code_allowlist_and_sha256": true, + "inputs_and_protocol_sha256": true, + "frozen_root_and_prior_mesh_identities": true, + "managed_runtime_path_and_version": true + }, + "manual_main_capture_required": true, + "body_generation": "permitted only in that captured run and only for this bounded stage", + "geometry_execution": "permitted only in that captured run and only for this bounded stage" + }, + "managed_runtime_reference": "/home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot/runtime/bin/python", + "managed_launcher_reference": "/home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot/source/experiments/current-form-surface-preview/surface_preview_launcher.sh", + "current_code_capture": "No connected-leg implementation artifact is captured or executed by this preparation; a future run must first capture the exact directly referenced source and runtime." + }, + "research_references": [ + { + "url": "https://www.proko.com/course-lesson/how-to-draw-legs-bone-anatomy-for-artists", + "use": "femur inward tendency, more vertical tibia, and non-uniform calf; qualitative source context only" + }, + { + "url": "https://www.proko.com/course-lesson/how-to-draw-feet-with-structure-foot-bone-anatomy", + "use": "ankle above heel; supports leaving foot/heel design future and outside this stage" + }, + { + "url": "https://openstax.org/books/anatomy-and-physiology-2e/pages/8-4-bones-of-the-lower-limb", + "use": "general lower-limb terminology/context; not a measurement source for these inputs" + } + ], + "reproduction_status": "No launcher, body generation, geometry run, or test suite is authorized in this preparation pass." +} diff --git a/experiments/connected-leg-assembly/root_source.py b/experiments/connected-leg-assembly/root_source.py new file mode 100644 index 0000000..639ce0f --- /dev/null +++ b/experiments/connected-leg-assembly/root_source.py @@ -0,0 +1,225 @@ +"""Regenerate connected-leg roots from recorded calibration source cases. + +This is a small downstream bridge for the whole-character prerequisite. It +accepts the recorded calibration case data, loads the same frozen +pelvis-source-calibration dependency used by its runner, and returns the +serializer-normalized L0 and L2 meshes. It does not read a cached root mesh, +reinterpret source fields, or introduce a new construction method. +""" +from __future__ import annotations + +import copy +import hashlib +import importlib.util +from collections.abc import Mapping +import json +from pathlib import Path +import stat +import sys +from typing import Any + + +CALIBRATION_SET_ROOT = Path( + "/home/ben/.cache/creature-kernel/pelvis-source-calibration-set-1" +) +CALIBRATION_SOURCE_MANIFEST_PATH = CALIBRATION_SET_ROOT / "source/manifest.json" +CALIBRATION_RUNNER_RELATIVE = Path( + "experiments/pelvis-source-calibration/runner.py" +) +CALIBRATION_RUNNER_PATH = ( + CALIBRATION_SET_ROOT / "source" / CALIBRATION_RUNNER_RELATIVE +) +FROZEN_CONSTRUCTION_RELATIVE = Path( + "source/experiments/pelvis-thigh-transition/construction.py" +) + + +class SourceReconstructionError(ValueError): + """Raised when recorded source data or the frozen dependency is unavailable.""" + + +def _regular(path: Path, label: str) -> None: + try: + info = path.lstat() + except OSError as exc: + raise SourceReconstructionError(f"{label} is unavailable: {path}") from exc + if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode): + raise SourceReconstructionError( + f"{label} must be a regular non-symlink file: {path}" + ) + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def _verified_calibration_runner() -> tuple[Path, dict[str, Any]]: + _regular(CALIBRATION_SOURCE_MANIFEST_PATH, "calibration source manifest") + try: + manifest = json.loads(CALIBRATION_SOURCE_MANIFEST_PATH.read_text( + encoding="utf-8")) + except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc: + raise SourceReconstructionError( + f"invalid calibration source manifest: {CALIBRATION_SOURCE_MANIFEST_PATH}" + ) from exc + if not isinstance(manifest, Mapping): + raise SourceReconstructionError("calibration source manifest is not a mapping") + rows = manifest.get("files") + if not isinstance(rows, list): + raise SourceReconstructionError("calibration source manifest has no files") + row = next((item for item in rows + if isinstance(item, Mapping) and + item.get("path") == CALIBRATION_RUNNER_RELATIVE.as_posix()), None) + if not isinstance(row, Mapping) or not isinstance(row.get("sha256"), str): + raise SourceReconstructionError( + "immutable calibration source manifest lacks the captured runner" + ) + relative = Path(str(row["path"])) + if relative.is_absolute() or ".." in relative.parts: + raise SourceReconstructionError("captured runner manifest path is not relative") + path = CALIBRATION_SET_ROOT / "source" / relative + if path.resolve() != CALIBRATION_RUNNER_PATH.resolve(): + raise SourceReconstructionError("captured runner resolved to an unexpected path") + _regular(path, "captured calibration runner") + if {"bytes": path.stat().st_size, "sha256": _sha256(path)} != { + "bytes": row.get("bytes"), "sha256": row["sha256"] + }: + raise SourceReconstructionError("captured calibration runner identity drifted") + return path, {"path": str(path), "sha256": str(row["sha256"]), + "manifest_path": str(CALIBRATION_SOURCE_MANIFEST_PATH)} + + +def _load_calibration_runner() -> tuple[Any, dict[str, Any]]: + path, identity = _verified_calibration_runner() + spec = importlib.util.spec_from_file_location( + "ck_connected_leg_calibration_runner", path + ) + if spec is None or spec.loader is None: + raise SourceReconstructionError( + f"unable to load calibration runner: {path}" + ) + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + try: + spec.loader.exec_module(module) + except Exception as exc: + if sys.modules.get(spec.name) is module: + sys.modules.pop(spec.name, None) + raise SourceReconstructionError( + f"unable to load calibration runner: {path}" + ) from exc + if Path(module.__file__).resolve() != path.resolve(): + raise SourceReconstructionError("calibration runner resolved away from its source path") + return module, identity + + +def _load_frozen_construction() -> tuple[Any, dict[str, str]]: + calibration_runner, runner_identity = _load_calibration_runner() + dependency = calibration_runner._dependency_identity( + calibration_runner.FROZEN_ROOT + ) + construction_entry = dependency["manifest"]["construction"] + path = calibration_runner.FROZEN_ROOT / FROZEN_CONSTRUCTION_RELATIVE + construction = calibration_runner._load_module( + path, "ck_connected_leg_frozen_pelvis_construction" + ) + return construction, { + "calibration_runner": runner_identity, + "frozen_construction": { + "path": str(path), + "sha256": str(construction_entry["sha256"]), + "manifest_path": str(dependency["manifest"]["path"]), + "dependency_root": str(dependency["root"]), + }, + "calibration_runner_module": calibration_runner, + } + + +def _source_inputs(source_case: Any) -> tuple[dict[str, Any], dict[str, Any]]: + if not isinstance(source_case, Mapping): + raise SourceReconstructionError("source_case must be a mapping") + components = source_case.get("components") + attachments = source_case.get("attachments") + if not isinstance(components, Mapping): + raise SourceReconstructionError("source_case.components must be a mapping") + if not isinstance(attachments, Mapping): + raise SourceReconstructionError("source_case.attachments must be a mapping") + return copy.deepcopy(dict(components)), copy.deepcopy(dict(attachments)) + + +def reconstruct_source_case( + source_case: Any, *, constructor_transform: Any = None) -> dict[str, Any]: + """Reconstruct serializer-compatible L0 and L2 from one source case. + + ``source_case`` is the recorded calibration case mapping. Only its + ``components`` and ``attachments`` are passed to the frozen constructor; + the source case's provenance and reference-only fields are not converted + into geometry inputs. An optional private transform may install a local + source provider on the freshly verified constructor before the build and + return supplemental refinement provenance. + """ + components, attachments = _source_inputs(source_case) + construction, provenance = _load_frozen_construction() + supplemental_provenance: dict[str, Any] | None = None + if constructor_transform is not None: + if not callable(constructor_transform): + raise SourceReconstructionError( + "constructor_transform must be callable when provided" + ) + try: + supplemental = constructor_transform(construction, provenance) + except Exception as exc: + raise SourceReconstructionError( + "source-provider constructor transform failed" + ) from exc + if not isinstance(supplemental, Mapping): + raise SourceReconstructionError( + "source-provider constructor transform must return provenance mapping" + ) + supplemental_provenance = copy.deepcopy(dict(supplemental)) + build = getattr(construction, "build", None) + evaluate = getattr(construction, "evaluate", None) + if not callable(build) or not callable(evaluate): + raise SourceReconstructionError("frozen construction lacks build/evaluate") + try: + built = build(components, attachments, diagnostic=True) + evaluated = evaluate(built, levels=2) + except Exception as exc: + raise SourceReconstructionError( + "frozen source-case construction/evaluation failed" + ) from exc + if not isinstance(evaluated, (list, tuple)) or len(evaluated) != 3: + raise SourceReconstructionError( + "frozen construction.evaluate did not return L0/L1/L2" + ) + + result_provenance = dict(provenance) + calibration_runner = result_provenance.pop("calibration_runner_module") + levels: dict[str, Any] = {} + for level in (0, 2): + value = calibration_runner._bounded(evaluated[level]) + if not isinstance(value, Mapping): + raise SourceReconstructionError(f"evaluated L{level} is not a mapping") + mesh = dict(value) + mesh.update({ + "schema": "creature-kernel.pelvis-source-calibration-mesh.v1", + "level": level, + }) + levels[f"L{level}"] = mesh + return { + "schema": "creature-kernel.connected-leg-assembly-source-reconstruction.v1", + "source_case_id": source_case.get("id"), + "provenance": { + **result_provenance, + **({"source_refinement": supplemental_provenance} + if supplemental_provenance is not None else {}), + }, + "levels": levels, + } + + +__all__ = ["SourceReconstructionError", "reconstruct_source_case"] diff --git a/experiments/connected-leg-assembly/runner.py b/experiments/connected-leg-assembly/runner.py new file mode 100644 index 0000000..aeef626 --- /dev/null +++ b/experiments/connected-leg-assembly/runner.py @@ -0,0 +1,2081 @@ +"""Small prepare/run/verify harness for the connected-leg staging experiment. + +The harness owns evidence plumbing only. Construction, binding, checking and +rendering remain experiment-local collaborators and may be absent while their +interfaces are being prepared. In particular, importing this module never +executes a candidate body. +""" + +from __future__ import annotations + +import argparse +import ast +import copy +from datetime import datetime, timezone +import hashlib +import importlib.util +import json +import math +import os +from pathlib import Path +import platform +import sys +from types import ModuleType +from typing import Any, Iterable, Mapping + +sys.dont_write_bytecode = True +os.environ["PYTHONDONTWRITEBYTECODE"] = "1" + +HERE = Path(__file__).resolve().parent +SNAPSHOT_SOURCE = Path("source/experiments/connected-leg-assembly") +CAPTURE_DEPENDENCIES = { + "pelvis-source-calibration/section_diagnostic.py": ( + HERE.parent / "pelvis-source-calibration/section_diagnostic.py" + ), +} +FROZEN_DEPENDENCY_ROOT = Path( + "/home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot" +) +FROZEN_HIP_CAPTURE = Path( + "/home/ben/.cache/creature-kernel/pelvis-hip-articulation-harmonic-lbs-001-snapshot" + "/source/experiments/pelvis-hip-articulation/capture.py" +) +FROZEN_RENDERER_RELATIVE = Path("source/experiments/pelvis-thigh-transition/render.py") +FROZEN_COLLISION_CORE = Path( + "/home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot" + "/source/experiments/owned-root-assembly-successor/mesh_correctness.py" +) + +# This is a closed local allowlist, not a recursive copy of the repository. +# Missing entries are allowed during the staged interface phase; prepare will +# capture the ones that exist and run reports absent execution collaborators. +CAPTURE_FILES = ( + "runner.py", "construction.py", "binding.py", "checks.py", "render.py", + "perturbations.py", + "root_source.py", "hip_source.py", "foot_construction.py", "foot_trial.py", + "arm_construction.py", "head_construction.py", "body_assembly.py", + "pelvis_foundation.py", "pelvis_foundation_preflight.py", + "abdomen_foundation.py", "abdomen_foundation_provider.py", + "abdomen_foundation_preflight.py", "abdomen_foundation_body_evidence.py", + "tail_construction.py", + "foot_form_construction.py", "foot_attachment_construction.py", + "foot_junction_construction.py", + "torso_refinement.py", + "thorax_foundation.py", + "thorax_foundation_diagnostic.py", + "thorax_foundation_body_evidence.py", + "thorax_foundation_checks.py", + "chest_envelope_evidence.py", + "chest_envelope_diagnostics.py", + "collision_broadphase.py", + "foot-inputs.json", "foot-form-inputs.json", "tail-inputs.json", + "torso-refinement-inputs.json", "torso-silhouette-inputs.json", + "torso-silhouette-correction-inputs.json", + "torso-chest-depth-ablation-inputs.json", + "torso-chest-envelope-inputs.json", + "thorax-foundation-baseline-inputs.json", + "thorax-foundation-width-inputs.json", + "thorax-foundation-fullness-inputs.json", + "abdomen-foundation-baseline-inputs.json", + "abdomen-foundation-bow-inputs.json", + "abdomen-foundation-fullness-inputs.json", + "head-refinement-inputs.json", "arm-refinement-inputs.json", + "foot-attachment-inputs.json", "foot-junction-policy.json", + "body-config.json", "body-refinement-internal-config.json", + "body-torso-correction-config.json", + "body-junction-integration-config.json", + "body-chest-depth-ablation-config.json", + "body-chest-envelope-config.json", + "body-silhouette-refinement-config.json", "tail-stage.md", + "body-thorax-foundation-baseline-config.json", + "body-thorax-foundation-width-config.json", + "body-thorax-foundation-fullness-config.json", + "body-pelvis-foundation-baseline-config.json", + "body-pelvis-foundation-iliac-config.json", + "body-pelvis-foundation-gluteal-config.json", + "body-abdomen-foundation-baseline-config.json", + "body-abdomen-foundation-bow-config.json", + "body-abdomen-foundation-fullness-config.json", + "abdomen-foundation-proposal.md", + "pelvis-foundation-recipe.md", "pelvis-foundation-proposal.md", + "pelvis-foundation-baseline-inputs.json", + "pelvis-foundation-iliac-inputs.json", + "pelvis-foundation-gluteal-inputs.json", + "captured_tests.py", + "arm-inputs.json", "head-inputs.json", + "protocol.json", "inputs.json", "README.md", "example-brief.md", + "tests/test_runner.py", "tests/test_construction.py", "tests/test_binding.py", + "tests/test_checks.py", "tests/test_perturbations.py", "tests/test_integration.py", + "tests/test_root_source.py", "tests/test_hip_source.py", + "tests/test_foot_construction.py", + "tests/test_arm_construction.py", "tests/test_arm_refinement.py", + "tests/test_head_construction.py", "tests/test_head_refinement.py", + "tests/test_body_assembly.py", + "tests/test_foot_form_construction.py", "tests/test_foot_attachment_construction.py", + "tests/test_foot_junction_construction.py", + "tests/test_torso_refinement.py", + "tests/test_thorax_foundation_diagnostic.py", + "tests/test_thorax_foundation_body_evidence.py", + "tests/test_thorax_foundation_checks.py", + "tests/test_thorax_foundation.py", + "tests/test_chest_envelope_evidence.py", + "tests/test_tail_construction.py", + "tests/test_collision_broadphase.py", + "tests/test_pelvis_foundation.py", + "tests/test_pelvis_foundation_provider.py", + "tests/test_pelvis_foundation_selection.py", + "foot-junction-stage.md", +) +MAPPED_INPUT_FIELDS = ("root_mesh", "prior_rest_mesh", "prior_hip_binding") +OPTIONAL_MAPPED_INPUT_FIELDS = ("original_case", "original_ref") +CANONICAL_LEG_INPUT_FIELDS = ( + "left.J", "left.T", "left.K", "left.A", "left.radii", + "left.mid_thigh_factor", "left.support_fraction", "left.role_metadata", + "right.J", "right.T", "right.K", "right.A", "right.radii", + "right.mid_thigh_factor", "right.support_fraction", "right.role_metadata", +) +REQUIRED_CHECK_SIGNATURES = { + "checks.check_mesh": "check_mesh(mesh, protocol)", + "checks.check_binding": "check_binding(base, rest, binding, root, prior_binding, leg_inputs, protocol)", + "checks.check_pose": "check_pose(rest, posed, binding, angles, protocol, leg_inputs)", + "checks.compare_root": "compare_root(prior_L0, expanded_L0, prior_L2, expanded_L2)", +} +PERTURBATION_SIGNATURE = ( + "run_case(root, prior_rest, prior_binding, leg_inputs, baseline_L0, baseline_L2, " + "baseline_binding, protocol, construction_module, binding_module)" +) + +# Internal body evidence only. This is separate from the frozen leg protocol +# and reuses its checker thresholds; it is not the named whole-character +# checkpoint. The explicit fields must survive transport into binding.pose. +BODY_PROVISIONAL_POSES = ( + { + "id": "body_neutral", + "left": {"hip": 0, "knee": 0, "ankle": 0, + "shoulder_raise": 0, "shoulder_forward": 0, "elbow": 0}, + "right": {"hip": 0, "knee": 0, "ankle": 0, + "shoulder_raise": 0, "shoulder_forward": 0, "elbow": 0}, + "head": {"yaw": 0, "nod": 0}, + }, + { + "id": "body_combined_modest", + "left": {"hip": 10, "knee": 10, "ankle": 0, + "shoulder_raise": 8, "shoulder_forward": 6, "elbow": 10}, + "right": {"hip": -8, "knee": 8, "ankle": 0, + "shoulder_raise": -7, "shoulder_forward": 5, "elbow": 9}, + "head": {"yaw": 6, "nod": 4}, + }, +) + + +class RunnerError(ValueError): + """Raised when evidence cannot be admitted by the local runner contract.""" + + +def _fail(message: str) -> None: + raise RunnerError(message) + + +def _mapping(value: Any, where: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping): + _fail(f"{where} must be an object") + return value + + +def _canonical(value: str | os.PathLike[str], label: str) -> Path: + path = Path(value) + if not path.is_absolute() or os.path.normpath(str(path)) != str(path): + _fail(f"{label} must be an absolute canonical path") + return path + + +def _regular(path: Path, label: str) -> None: + try: + info = path.lstat() + except OSError as exc: + raise RunnerError(f"{label} is unavailable: {path}") from exc + if path.is_symlink() or not path.is_file() or not info: + _fail(f"{label} must be a regular non-symlink file: {path}") + + +def _directory(path: Path, label: str) -> None: + if path.is_symlink() or not path.is_dir(): + _fail(f"{label} must be a regular directory: {path}") + + +def _sha256_bytes(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _sha256(path: Path) -> str: + _regular(path, "hashed file") + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def _identity(path: Path) -> dict[str, Any]: + return {"bytes": path.stat().st_size, "sha256": _sha256(path)} + + +def _json_bytes(value: Any) -> bytes: + try: + return (json.dumps(value, sort_keys=True, indent=2, ensure_ascii=True, + allow_nan=False) + "\n").encode("utf-8") + except (TypeError, ValueError) as exc: + raise RunnerError(f"value is not finite JSON: {exc}") from exc + + +def _write_json(path: Path, value: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(_json_bytes(value)) + + +def _read_json(path: Path) -> tuple[Any, bytes]: + _regular(path, "JSON file") + raw = path.read_bytes() + try: + value = json.loads(raw.decode("utf-8"), + parse_constant=lambda token: (_ for _ in ()).throw(ValueError(token))) + except (UnicodeDecodeError, json.JSONDecodeError, ValueError) as exc: + raise RunnerError(f"invalid finite UTF-8 JSON: {path}") from exc + return value, raw + + +def _load_module(name: str, path: Path) -> ModuleType: + """Load a module from an admitted path, registering it before execution.""" + _regular(path, "dynamic module") + spec = importlib.util.spec_from_file_location(name, path) + if spec is None or spec.loader is None: + _fail(f"unable to load dynamic module: {path}") + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + try: + spec.loader.exec_module(module) + except Exception: + if sys.modules.get(name) is module: + sys.modules.pop(name, None) + raise + if Path(str(module.__file__)).resolve() != path.resolve(): + _fail(f"module resolved away from its frozen path: {name}") + return module + + +def _frozen_dependency_identity() -> dict[str, Any]: + """Obtain the existing transition identity through the pinned hip helper.""" + helper_before = _identity(FROZEN_HIP_CAPTURE) + helper = _load_module("ck_connected_leg_pinned_hip_capture", FROZEN_HIP_CAPTURE) + getter = getattr(helper, "_load_frozen_dependency_identity", None) + if not callable(getter): + _fail("pinned hip capture has no frozen dependency identity helper") + identity = getter() + if not isinstance(identity, Mapping): + _fail("frozen dependency identity is not an object") + identity = dict(identity) + helper_after = _identity(FROZEN_HIP_CAPTURE) + if helper_before != helper_after: + _fail("pinned hip capture helper changed while reading dependency identity") + root = Path(str(identity.get("root", FROZEN_DEPENDENCY_ROOT))) + renderer = root / FROZEN_RENDERER_RELATIVE + _regular(renderer, "frozen renderer") + collision_core = _collision_core_identity() + return { + "identity": identity, + "hip_capture_helper": {"path": str(FROZEN_HIP_CAPTURE), + "before": helper_before, "after": helper_after}, + "renderer": {"path": str(renderer), **_identity(renderer)}, + "collision_core": collision_core, + } + + +def _collision_core_identity() -> dict[str, Any]: + """Record Sol's checks-declared external core from its frozen location.""" + before = _identity(FROZEN_COLLISION_CORE) + after = _identity(FROZEN_COLLISION_CORE) + if before != after: + _fail("frozen collision core changed while reading its identity") + return {"path": str(FROZEN_COLLISION_CORE), "before": before, "after": after} + + +def _dependency_identity() -> dict[str, Any]: + """Public seam for tests and for before/after dependency verification.""" + return _frozen_dependency_identity() + + +def _adapter_dependency_identity(source_root: Path) -> dict[str, Any]: + """Record source-adapter dependencies without constructing a candidate.""" + root_path = source_root / "root_source.py" + hip_path = source_root / "hip_source.py" + present = [path for path in (root_path, hip_path) if path.is_file()] + if not present: + return {} + if len(present) != 2: + _fail("root_source.py and hip_source.py must be captured together") + try: + root_adapter = _load_module("ck_connected_leg_capture_root_source", root_path) + root_loader = getattr(root_adapter, "_load_frozen_construction", None) + if not callable(root_loader): + _fail("root_source.py has no frozen dependency loader") + _unused_root_construction, root_provenance = root_loader() + root_provenance = dict(root_provenance) + root_provenance.pop("calibration_runner_module", None) + + hip_adapter = _load_module("ck_connected_leg_capture_hip_source", hip_path) + hip_loader = getattr(hip_adapter, "_load_frozen_binding", None) + if not callable(hip_loader): + _fail("hip_source.py has no frozen dependency loader") + _unused_hip_binding, hip_provenance = hip_loader() + return _jsonable({"root_source": root_provenance, + "hip_source": hip_provenance}) + except RunnerError: + raise + except Exception as exc: + _fail(f"source-adapter dependency identity is unavailable: {exc}") + + +def _source_path(name: str) -> Path: + relative = Path(name) + if relative.is_absolute() or ".." in relative.parts: + _fail(f"source filename escapes the experiment: {name}") + path = HERE / relative + _regular(path, "experiment source") + return path + + +def _selected_source_names(file_names: Iterable[str] | None) -> list[str]: + names = list(CAPTURE_FILES if file_names is None else file_names) + if not names or len(set(names)) != len(names): + _fail("source file selection must be non-empty and unique") + selected = [Path(name).as_posix() for name in names + if (HERE / Path(name)).exists()] + for name in selected: + _source_path(name) + if "runner.py" not in selected: + _fail("capture must include runner.py") + return selected + + +def _local_imports(path: Path) -> set[str]: + try: + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + except (OSError, SyntaxError) as exc: + raise RunnerError(f"cannot inspect imports in {path}") from exc + result: set[str] = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + result.update(alias.name.split(".", 1)[0] for alias in node.names) + elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module: + result.add(node.module.split(".", 1)[0]) + return result + + +def _expand_imported_sources(names: list[str]) -> list[str]: + allowed = set(CAPTURE_FILES) + selected = set(names) + changed = True + while changed: + changed = False + for name in tuple(sorted(selected)): + if not name.endswith(".py"): + continue + for module_name in _local_imports(HERE / name): + candidate = f"{module_name}.py" + if candidate in allowed and (HERE / candidate).is_file() and candidate not in selected: + selected.add(candidate) + changed = True + return sorted(selected, key=lambda item: item.encode("utf-8")) + + +def _copy_file(source: Path, target: Path, label: str) -> dict[str, Any]: + _regular(source, label) + before = _identity(source) + if target.exists() or target.is_symlink(): + _fail(f"capture target must be absent: {target}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(source.read_bytes()) + after = _identity(source) + copied = _identity(target) + if before != after or before != copied: + _fail(f"{label} changed while being captured: {source}") + return {"origin_path": str(source), "snapshot_path": str(target), **before} + + +def _input_reference(value: Any) -> tuple[str, str] | None: + if (isinstance(value, Mapping) and isinstance(value.get("path"), str) + and isinstance(value.get("sha256"), str)): + return str(value["path"]), str(value["sha256"]) + return None + + +def _input_refs(document: Mapping[str, Any], inputs_path: Path) -> list[dict[str, Any]]: + cases = document.get("cases") + if not isinstance(cases, list): + _fail("inputs.json must contain a cases list") + refs: list[dict[str, Any]] = [] + for index, case in enumerate(cases): + if not isinstance(case, Mapping): + _fail(f"case {index} is not an object") + case_id = str(case.get("id", f"case-{index:02d}")) + for field in (*MAPPED_INPUT_FIELDS, *OPTIONAL_MAPPED_INPUT_FIELDS): + reference = _input_reference(case.get(field)) + if reference is None: + if field in OPTIONAL_MAPPED_INPUT_FIELDS: + continue + _fail(f"case {case_id} lacks mapped input field {field}") + reference_path, declared_sha256 = reference + origin = Path(reference_path) + if not origin.is_absolute(): + origin = inputs_path.parent / origin + _regular(origin, f"mapped input {case_id}.{field}") + if _sha256(origin) != declared_sha256: + _fail(f"mapped input {case_id}.{field} does not match its declared SHA-256") + refs.append({"case_id": case_id, "field": field, "origin": origin, + "declared_sha256": declared_sha256}) + explicit = document.get("input_files", []) + if explicit: + if not isinstance(explicit, list): + _fail("inputs.json input_files must be a list") + for row in explicit: + if (not isinstance(row, Mapping) or not isinstance(row.get("name"), str) + or not isinstance(row.get("path"), str) + or not isinstance(row.get("sha256"), str)): + _fail("input_files rows require name, path, and sha256") + origin = Path(str(row["path"])) + if not origin.is_absolute(): + origin = inputs_path.parent / origin + _regular(origin, f"explicit mapped input {row['name']}") + if _sha256(origin) != row["sha256"]: + _fail(f"explicit mapped input {row['name']} does not match its declared SHA-256") + refs.append({"name": str(row["name"]), "field": "explicit", "origin": origin, + "declared_sha256": str(row["sha256"])}) + return refs + + +def _host_record(dependency: Mapping[str, Any]) -> dict[str, Any]: + return { + "python": sys.version, + "python_executable": sys.executable, + "platform": platform.platform(), + "machine": platform.machine(), + "dependency_runtime": dependency.get("identity", {}).get("runtime", {}), + "limitations": [ + "This records the host and library identity but does not claim hermetic OS, loader, or kernel isolation.", + "The transition source/runtime are referenced and digest-verified; the 292 MB runtime is not cloned.", + ], + } + + +def prepare(snapshot: str | os.PathLike[str], file_names: Iterable[str] | None = None, + rest_only: bool = False) -> dict[str, Any]: + """Capture new source and concrete inputs into an absent snapshot.""" + target = _canonical(snapshot, "snapshot") + if target.exists() or target.is_symlink(): + _fail(f"snapshot must be absent: {target}") + if not target.parent.is_dir() or target.parent.is_symlink(): + _fail("snapshot parent must be an existing regular directory") + selected = _selected_source_names(file_names) + if rest_only and file_names is None: + selected = [name for name in selected if name != "checks.py"] + names = _expand_imported_sources(selected) + dependency_names = ( + dict(CAPTURE_DEPENDENCIES) + if "thorax_foundation_body_evidence.py" in names else {} + ) + inputs_source = HERE / "inputs.json" + if inputs_source.is_file(): + document, input_raw = _read_json(inputs_source) + if not isinstance(document, Mapping): + _fail("inputs.json must be an object") + refs = _input_refs(document, inputs_source) + else: + document, input_raw, refs = None, None, [] + dependency_before = _dependency_identity() + adapter_dependency_before = _adapter_dependency_identity(HERE) + target.mkdir() + source_rows: list[dict[str, Any]] = [] + try: + for name in names: + destination = target / SNAPSHOT_SOURCE / name + row = _copy_file(HERE / name, destination, "source file") + row["path"] = name + source_rows.append(row) + captured_dependency_rows: list[dict[str, Any]] = [] + for logical_name, origin in dependency_names.items(): + destination = target / "dependencies" / logical_name + row = _copy_file(origin, destination, "captured source dependency") + row.update({"path": logical_name, + "snapshot_path": destination.relative_to(target).as_posix(), + "origin_path": str(origin)}) + captured_dependency_rows.append(row) + input_rows: list[dict[str, Any]] = [] + by_origin: dict[Path, Path] = {} + for index, ref in enumerate(refs): + origin = ref["origin"] + destination = by_origin.get(origin) + if destination is None: + stem = origin.name or f"input-{index}" + destination = Path("inputs") / f"{index:03d}-{stem}" + by_origin[origin] = destination + row = _copy_file(origin, target / destination, "concrete input") + row.update({"path": destination.as_posix()}) + input_rows.append(row) + ref_row = {key: value for key, value in ref.items() if key != "origin"} + ref_row.update({"origin_path": str(origin), "snapshot_path": destination.as_posix()}) + input_rows.append(ref_row) + if input_raw is not None: + # The input document is a source artifact and is kept byte-for-byte; + # path rewrites belong to this manifest's path map. + _ = input_raw + dependency_after = _dependency_identity() + adapter_dependency_after = _adapter_dependency_identity(HERE) + if dependency_before != dependency_after: + _fail("frozen transition dependency changed while preparing capture") + if adapter_dependency_before != adapter_dependency_after: + _fail("source-adapter dependency changed while preparing capture") + source_manifest = { + "schema": "creature-kernel.connected-leg-assembly-source.v1", + "files": [{key: row[key] for key in ("path", "bytes", "sha256")} for row in source_rows], + } + _write_json(target / "source" / "manifest.json", source_manifest) + source_inventory = [{"path": row["path"], "bytes": row["bytes"], + "sha256": row["sha256"]} for row in source_rows] + dependency_inventory = [{"path": row["path"], "bytes": row["bytes"], + "sha256": row["sha256"]} + for row in captured_dependency_rows] + input_copies = [row for row in input_rows if "path" in row and "bytes" in row] + input_inventory = [{"path": row["path"], "bytes": row["bytes"], + "sha256": row["sha256"]} for row in input_copies] + manifest = { + "schema": "creature-kernel.connected-leg-assembly-capture.v1", + "status": "prepared", + "body_execution": False, + "captured_at_utc": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"), + "source": {"root": str(target / SNAPSHOT_SOURCE), "files": source_rows, + "before": source_inventory, "after": source_inventory}, + "captured_dependencies": { + "files": captured_dependency_rows, + "before": dependency_inventory, + "after": dependency_inventory, + }, + "code_manifest": {"sha256": _sha256_bytes(_json_bytes(source_manifest)), "files": source_rows}, + "input_manifest": { + "source_path": str(inputs_source) if inputs_source.is_file() else None, + "source_sha256": _sha256(inputs_source) if inputs_source.is_file() else None, + "copies": input_copies, + "before": input_inventory, "after": input_inventory, + "path_map": [row for row in input_rows if "case_id" in row or "name" in row], + }, + "dependency": {"root": str(dependency_before["identity"].get("root", FROZEN_DEPENDENCY_ROOT)), + "before": dependency_before, "after": dependency_after, + "reused_without_copy": True}, + "adapter_dependency": { + "before": adapter_dependency_before, + "after": adapter_dependency_after, + "reused_without_copy": True, + }, + "runtime": {"python": dependency_before["identity"].get("runtime", {}), + "executable": dependency_before["identity"].get("runtime", {}).get("executable")}, + "host": _host_record(dependency_before), + "limitations": [ + "Preparation is stdlib-only and does not execute construction, binding, checks, or candidate bodies.", + "Run must load the captured new source and the recorded frozen dependency locations, never the live worktree.", + "The host OS and dynamic-loader environment are not hermetic.", + ], + } + _write_json(target / "manifest.json", manifest) + return manifest + except Exception: + # Retain a partial capture for diagnosis; callers can choose a new + # absent path for a later repair/replay. + raise + + +def _manifest(snapshot: Path) -> dict[str, Any]: + value, _ = _read_json(snapshot / "manifest.json") + if not isinstance(value, Mapping) or value.get("schema") != "creature-kernel.connected-leg-assembly-capture.v1": + _fail("capture manifest schema is not admitted") + return dict(value) + + +def verify(snapshot: str | os.PathLike[str]) -> dict[str, Any]: + """Verify captured source/input bytes and the unchanged frozen dependency.""" + root = _canonical(snapshot, "snapshot") + _directory(root, "snapshot") + manifest = _manifest(root) + if manifest.get("body_execution") is not False: + _fail("capture manifest claims body execution") + source_group = manifest.get("source", {}) + if source_group.get("before") != source_group.get("after"): + _fail("captured source inventory drifted") + input_group = manifest.get("input_manifest", {}) + if input_group.get("before") != input_group.get("after"): + _fail("captured input inventory drifted") + dependency_group = manifest.get("captured_dependencies", {}) + if dependency_group.get("before", []) != dependency_group.get("after", []): + _fail("captured source dependency inventory drifted") + expected: set[str] = {"manifest.json", "source/manifest.json"} + source_rows = source_group.get("files", []) + for row in source_rows: + if not isinstance(row, Mapping): + _fail("source manifest row is malformed") + path = root / str(row["snapshot_path"]) + _regular(path, "captured source") + expected.add(path.relative_to(root).as_posix()) + if _identity(path) != {"bytes": row["bytes"], "sha256": row["sha256"]}: + _fail(f"captured source drifted: {path}") + for row in dependency_group.get("files", []): + if not isinstance(row, Mapping): + _fail("captured source dependency row is malformed") + path = root / str(row["snapshot_path"]) + _regular(path, "captured source dependency") + expected.add(path.relative_to(root).as_posix()) + if _identity(path) != {"bytes": row["bytes"], "sha256": row["sha256"]}: + _fail(f"captured source dependency drifted: {path}") + expected_source_manifest = {"schema": "creature-kernel.connected-leg-assembly-source.v1", + "files": [{key: row[key] for key in ("path", "bytes", "sha256")} + for row in source_rows]} + source_manifest, _ = _read_json(root / "source/manifest.json") + if source_manifest != expected_source_manifest: + _fail("captured source manifest drifted") + for row in input_group.get("copies", []): + path = root / str(row["snapshot_path"]) + _regular(path, "captured concrete input") + expected.add(path.relative_to(root).as_posix()) + if _identity(path) != {"bytes": row["bytes"], "sha256": row["sha256"]}: + _fail(f"captured input drifted: {path}") + actual = {path.relative_to(root).as_posix() for path in root.rglob("*") if path.is_file()} + if actual != expected: + _fail("snapshot contains missing or unexpected files") + dependency = _dependency_identity() + recorded = manifest.get("dependency", {}) + if dependency != recorded.get("before") or dependency != recorded.get("after"): + _fail("frozen dependency identity drifted") + recorded_adapters = manifest.get("adapter_dependency") + if recorded_adapters is not None: + adapter_dependency = _adapter_dependency_identity(root / SNAPSHOT_SOURCE) + if (adapter_dependency != recorded_adapters.get("before") or + adapter_dependency != recorded_adapters.get("after")): + _fail("source-adapter dependency identity drifted") + return manifest + + +def _snapshot_path(snapshot: Path, relative: str) -> Path: + path = snapshot / relative + try: + path.relative_to(snapshot) + except ValueError: + _fail(f"snapshot path escapes capture: {relative}") + _regular(path, "captured path") + return path + + +def _path_map(manifest: Mapping[str, Any]) -> dict[tuple[str, str], Path]: + rows = manifest.get("input_manifest", {}).get("path_map", []) + result: dict[tuple[str, str], Path] = {} + for row in rows: + if isinstance(row, Mapping) and isinstance(row.get("case_id"), str) and isinstance(row.get("field"), str): + result[(row["case_id"], row["field"])] = Path(str(row["snapshot_path"])) + return result + + +def _jsonable(value: Any) -> Any: + if isinstance(value, Mapping): + return {str(key): _jsonable(item) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [_jsonable(item) for item in value] + if type(value) in (str, int, float, bool) or value is None: + if isinstance(value, float) and not math.isfinite(value): + _fail("mesh contains a non-finite number") + return value + _fail(f"value is not JSON-serializable: {type(value).__name__}") + + +def _load_case_inputs(snapshot: Path, manifest: Mapping[str, Any], document: Mapping[str, Any]) -> list[dict[str, Any]]: + cases = document.get("cases") + if not isinstance(cases, list) or not cases: + _fail("captured inputs must contain a non-empty cases list") + mappings = _path_map(manifest) + loaded: list[dict[str, Any]] = [] + for index, raw_case in enumerate(cases): + if not isinstance(raw_case, Mapping): + _fail(f"case {index} is not an object") + case = dict(raw_case) + case_id = str(case.get("id", f"case-{index:02d}")) + values: dict[str, Any] = {} + for field in MAPPED_INPUT_FIELDS: + relative = mappings.get((case_id, field)) + if relative is None: + _fail(f"captured path map lacks {case_id}.{field}") + value, _ = _read_json(_snapshot_path(snapshot, str(relative))) + values[field] = value + for field in OPTIONAL_MAPPED_INPUT_FIELDS: + relative = mappings.get((case_id, field)) + if relative is not None: + values[field], _ = _read_json(_snapshot_path(snapshot, str(relative))) + values["leg_inputs"] = case.get("leg_inputs", {}) + loaded.append({"id": case_id, "case": case, "values": values}) + return loaded + + +def _load_body_config(snapshot: Path, manifest: Mapping[str, Any], + logical_path: str) -> Mapping[str, Any]: + relative = Path(logical_path) + if relative.is_absolute() or ".." in relative.parts or relative.suffix != ".json": + _fail("--body-config must name a relative captured JSON file") + rows = manifest.get("source", {}).get("files", []) + match = next((row for row in rows + if isinstance(row, Mapping) and row.get("path") == relative.as_posix()), None) + if not isinstance(match, Mapping) or not isinstance(match.get("snapshot_path"), str): + _fail(f"--body-config file is not captured: {logical_path}") + value, _ = _read_json(_snapshot_path(snapshot, str(match["snapshot_path"]))) + return _mapping(value, "body-config") + + +def _module_package(source_root: Path) -> str: + package_name = "ck_connected_leg_snapshot" + package = ModuleType(package_name) + package.__path__ = [str(source_root)] # type: ignore[attr-defined] + package.__package__ = package_name + sys.modules[package_name] = package + return package_name + + +def _load_collaborators(snapshot: Path, manifest: Mapping[str, Any], + rest_only: bool = False) -> dict[str, Any]: + source_root = snapshot / SNAPSHOT_SOURCE + package = _module_package(source_root) + paths = {row.get("path"): source_root / str(row.get("path")) + for row in manifest.get("source", {}).get("files", []) if isinstance(row, Mapping)} + result: dict[str, Any] = {} + dependency_root = Path(str(manifest["dependency"]["root"])) + generic_transition = dependency_root / "source/experiments/pelvis-thigh-transition/construction.py" + if generic_transition.is_file(): + result["generic_transition"] = _load_module( + "_ck_connected_leg_generic_transition", generic_transition) + broadphase_path = paths.get("collision_broadphase.py") + if broadphase_path is not None: + broadphase = _load_module(f"{package}.collision_broadphase", broadphase_path) + recorded_core = manifest.get("dependency", {}).get("before", {}).get("collision_core", {}) + recorded_core_path = recorded_core.get("path") if isinstance(recorded_core, Mapping) else None + declared_core_path = getattr(broadphase, "FROZEN_CORE_PATH", None) + if (recorded_core_path is None or declared_core_path is None + or Path(str(declared_core_path)).resolve() != Path(str(recorded_core_path)).resolve()): + _fail("captured collision broadphase does not declare the pinned collision core") + core_before = recorded_core.get("before") + core_after = recorded_core.get("after") + current_core = _identity(Path(str(declared_core_path))) + if current_core != core_before or current_core != core_after: + _fail("pinned collision core identity drifted") + result["collision_broadphase"] = broadphase + names = ("construction", "root_source", "hip_source") + if not rest_only: + names += ("binding", "checks", "perturbations", + "foot_construction", "foot_form_construction", + "foot_junction_construction", + "arm_construction", "head_construction", + "tail_construction", + "torso_refinement", "thorax_foundation", + "thorax_foundation_checks") + for name in names: + path = paths.get(f"{name}.py") + if path is not None: + result[name] = _load_module(f"{package}.{name}", path) + if name == "construction": + # Captured body_assembly imports these historical top-level + # names. Bind them before loading it, never to live modules. + sys.modules["construction"] = result[name] + elif name in {"root_source", "hip_source", "binding", + "foot_construction", "foot_junction_construction", + "arm_construction", "head_construction", + "foot_form_construction", "tail_construction", + "torso_refinement", "thorax_foundation"}: + sys.modules[name] = result[name] + if not rest_only: + pelvis_calculator_path = paths.get("pelvis_foundation.py") + if pelvis_calculator_path is not None: + result["pelvis_foundation"] = _load_module( + f"{package}.pelvis_foundation", pelvis_calculator_path + ) + # The captured abdomen provider has a package-relative import and + # a top-level fallback; bind both identities before it loads. + sys.modules["pelvis_foundation"] = result["pelvis_foundation"] + abdomen_calculator_path = paths.get("abdomen_foundation.py") + if abdomen_calculator_path is not None: + result["abdomen_foundation_calculator"] = _load_module( + f"{package}.abdomen_foundation", abdomen_calculator_path + ) + sys.modules["abdomen_foundation"] = result["abdomen_foundation_calculator"] + abdomen_provider_path = paths.get("abdomen_foundation_provider.py") + if abdomen_provider_path is not None: + result["abdomen_foundation_provider"] = _load_module( + f"{package}.abdomen_foundation_provider", abdomen_provider_path + ) + sys.modules["abdomen_foundation_provider"] = result["abdomen_foundation_provider"] + # The body seam calls this selected provider ``abdomen_foundation``; + # retain the filename-qualified key for provenance and diagnostics. + result["abdomen_foundation"] = result["abdomen_foundation_provider"] + checks = result.get("checks") + if checks is not None and result.get("collision_broadphase") is not None: + setter = getattr(checks, "_set_broadphase", None) + if callable(setter): + setter(result["collision_broadphase"]) + foot_path = paths.get("foot_construction.py") + foot_input_path = paths.get("foot-inputs.json") + if foot_path is not None or foot_input_path is not None: + if foot_path is None or foot_input_path is None: + _fail("foot_construction.py and foot-inputs.json must be captured together") + if result.get("foot_construction") is None: + result["foot_construction"] = _load_module( + f"{package}.foot_construction", foot_path) + sys.modules["foot_construction"] = result["foot_construction"] + result["foot_inputs"], _ = _read_json(foot_input_path) + if not rest_only: + input_files = { + "arm_inputs": "arm-inputs.json", + "arm_refinement_inputs": "arm-refinement-inputs.json", + "head_inputs": "head-inputs.json", + "head_refinement_inputs": "head-refinement-inputs.json", + "foot_form_inputs": "foot-form-inputs.json", + "foot_junction_policy": "foot-junction-policy.json", + "torso_refinement_inputs": "torso-refinement-inputs.json", + "torso_silhouette_inputs": "torso-silhouette-inputs.json", + "torso_silhouette_correction_inputs": "torso-silhouette-correction-inputs.json", + "torso_chest_depth_ablation_inputs": "torso-chest-depth-ablation-inputs.json", + "torso_chest_envelope_inputs": "torso-chest-envelope-inputs.json", + "thorax_foundation_baseline_inputs": "thorax-foundation-baseline-inputs.json", + "thorax_foundation_width_inputs": "thorax-foundation-width-inputs.json", + "thorax_foundation_fullness_inputs": "thorax-foundation-fullness-inputs.json", + "abdomen_foundation_baseline_inputs": "abdomen-foundation-baseline-inputs.json", + "abdomen_foundation_bow_inputs": "abdomen-foundation-bow-inputs.json", + "abdomen_foundation_fullness_inputs": "abdomen-foundation-fullness-inputs.json", + "tail_inputs": "tail-inputs.json", + } + for name, filename in input_files.items(): + input_path = paths.get(filename) + if input_path is not None: + result[name], _ = _read_json(input_path) + body_path = paths.get("body_assembly.py") + if body_path is not None: + result["body_assembly"] = _load_module(f"{package}.body_assembly", body_path) + renderer_path = Path(str(manifest["dependency"]["before"]["renderer"]["path"])) + result["render"] = _load_module("ck_connected_leg_frozen_renderer", renderer_path) + return result + + +def _protocol_poses(protocol: Mapping[str, Any]) -> list[dict[str, Any]]: + poses = protocol.get("poses", protocol.get("baseline_poses")) + if not isinstance(poses, list) or not poses: + _fail("protocol must declare a non-empty poses list") + result = [] + for index, row in enumerate(poses): + if not isinstance(row, Mapping) or not isinstance(row.get("id"), str): + _fail(f"protocol pose {index} is malformed") + angles = row.get("angles") + if not isinstance(angles, Mapping): + # The protocol stores pose metadata (for example ``label`` and + # ``meaning``) beside the two executable side-angle records. + # Pass only the declared binding input shape to binding.pose; + # metadata is retained in the captured protocol itself. + if all(side in row and isinstance(row[side], Mapping) for side in ("left", "right")): + angles = {side: row[side] for side in ("left", "right")} + if isinstance(row.get("head"), Mapping): + angles["head"] = row["head"] + else: + angles = {key: value for key, value in row.items() if key != "id"} + result.append({"id": row["id"], "angles": dict(angles)}) + return result + + +def _vertices(mesh: Any) -> list[list[float]]: + if not isinstance(mesh, Mapping) or not isinstance(mesh.get("vertices"), (list, tuple)): + _fail("mesh must expose a vertices list") + points = [] + for point in mesh["vertices"]: + if not isinstance(point, (list, tuple)) or len(point) != 3: + _fail("mesh vertex must be a three-component point") + values = [float(item) for item in point] + if not all(math.isfinite(item) for item in values): + _fail("mesh vertex is not finite") + points.append(values) + if not points: + _fail("mesh has no vertices") + return points + + +def _bounds(meshes: Iterable[Any]) -> list[list[float]]: + points = [point for mesh in meshes for point in _vertices(mesh)] + low = [min(point[axis] for point in points) for axis in range(3)] + high = [max(point[axis] for point in points) for axis in range(3)] + span = max(high[axis] - low[axis] for axis in range(3)) + margin = max(span * 0.05, 1e-6) + return [[value - margin for value in low], [value + margin for value in high]] + + +def _render_bounds_inputs(results: Iterable[Mapping[str, Any]]) -> list[Any]: + """Build one shared bounds inventory for ordinary and perturbation surfaces.""" + meshes: list[Any] = [] + for result in results: + meshes.extend(mesh for mesh in result.get("bounds_inputs", []) if isinstance(mesh, Mapping)) + meshes.extend(item["mesh"] for item in result.get("perturbation_meshes", []) + if isinstance(item, Mapping) and isinstance(item.get("mesh"), Mapping)) + return meshes + + +def _overlays(points: Any) -> list[dict[str, Any]]: + if not isinstance(points, Mapping): + return [] + result = [] + for side, value in points.items(): + if not isinstance(value, Mapping): + continue + for start_name, end_name in (("J", "T"), ("J", "K"), ("J", "A")): + if start_name in value and end_name in value: + result.append({"start": _jsonable(value[start_name]), "end": _jsonable(value[end_name]), + "color": [211, 77, 77] if str(side).lower().startswith("l") else [55, 112, 213], + "label": f"diagnostic {side} {start_name}-{end_name}"}) + return result + + +def _report_pass(report: Any) -> bool: + if not isinstance(report, Mapping): + _fail("checker report must be an object") + if type(report.get("pass")) is bool: + return bool(report["pass"]) + if report.get("outcome") in ("pass", "support", "reject", "failed"): + return report["outcome"] in ("pass", "support") + nested = report.get("technical") + if isinstance(nested, Mapping) and type(nested.get("pass")) is bool: + return bool(nested["pass"]) + _fail("checker report lacks an explicit pass/reject result") + + +def _safe_token(value: Any) -> str: + text = str(value) + if not text or any(character not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-" + for character in text): + _fail(f"evidence name is not a safe filename token: {text!r}") + return text + + +def _mesh_mapping(value: Any) -> bool: + return (isinstance(value, Mapping) and isinstance(value.get("vertices"), (list, tuple)) + and isinstance(value.get("quads", value.get("faces")), (list, tuple))) + + +def _save_perturbation_evidence(case_dir: Path, evidence: Mapping[str, Any]) -> list[dict[str, Any]]: + """Persist every returned diagnostic value and identify mesh values for render.""" + render_inputs: list[dict[str, Any]] = [] + records = evidence.get("perturbations") + if not isinstance(records, list): + return render_inputs + for record in records: + if not isinstance(record, Mapping): + continue + perturbation_id = _safe_token(record.get("id", "unknown")) + diagnostic_meshes = record.get("diagnostic_meshes", {}) + if not isinstance(diagnostic_meshes, Mapping): + continue + diagnostic_dir = case_dir / "perturbations" / perturbation_id + for name, value in diagnostic_meshes.items(): + filename = _safe_token(name) + ".json" + target = diagnostic_dir / filename + _write_json(target, _jsonable(value)) + if _mesh_mapping(value): + render_inputs.append({ + "perturbation_id": perturbation_id, + "name": _safe_token(name), + "path": target.relative_to(case_dir).as_posix(), + "mesh": _jsonable(value), + }) + return render_inputs + + +def _perturbation_result_ready(result: Any, expected_ids: list[str]) -> bool: + if not isinstance(result, Mapping) or result.get("status") != "pass": + return False + records = result.get("perturbations") + if not isinstance(records, list) or [row.get("id") for row in records if isinstance(row, Mapping)] != expected_ids: + return False + return len(records) == len(expected_ids) and all( + isinstance(row, Mapping) and row.get("status") == "pass" for row in records + ) + + +def _aggregate_perturbations(protocol: Mapping[str, Any], results: Iterable[Mapping[str, Any]], + perturbation_api_available: bool = False) -> dict[str, Any]: + """Summarize per-case perturbation evidence without turning omissions into pass.""" + declared = _perturbation_status(protocol) + if declared["status"] == "not-declared": + return declared + case_rows = list(results) + case_results = [row.get("perturbations") for row in case_rows] + if perturbation_api_available: + blockers = [] + for row in case_rows: + perturbation = row.get("perturbations") + if isinstance(perturbation, Mapping) and perturbation.get("status") == "blocked-by-earlier-error": + blockers.append(perturbation.get("blocker", {"case": row.get("id")})) + elif row.get("status") == "exception" and perturbation is None: + blockers.append({"case": row.get("id"), "stage": "unknown", + "detail": "case exception occurred before perturbation dispatch"}) + if blockers: + return {**declared, "status": "blocked-by-earlier-error", "execution": "not-run", + "blocker": blockers} + if case_results and all(isinstance(row, Mapping) and row.get("status") == "pass" + and _perturbation_result_ready(row, declared.get("declared_ids", [])) + for row in case_results): + return {**declared, "status": "pass", "execution": "captured"} + if case_results and all(isinstance(row, Mapping) and row.get("status") == "leg-only" + for row in case_results): + return {**declared, "status": "leg-only", "execution": "captured", + "coverage": "leg-baseline-only", "foot_coverage": "not-run"} + if any(isinstance(row, Mapping) and row.get("status") == "failed" for row in case_results): + return {**declared, "status": "failed", "execution": "captured"} + if any(isinstance(row, Mapping) and row.get("status") == "unavailable" for row in case_results): + return {**declared, "status": "unavailable", "execution": "captured"} + return declared + + +def _perturbation_status(protocol: Mapping[str, Any]) -> dict[str, Any]: + declared = protocol.get("input_perturbations", []) + if not isinstance(declared, list): + return {"status": "invalid", "declared_count": 0, + "reason": "protocol input_perturbations is not a list"} + return { + "status": "not-implemented" if declared else "not-declared", + "execution": "not-run", + "declared_count": len(declared), + "declared_ids": [row.get("id") for row in declared if isinstance(row, Mapping)], + "reason": "declared perturbations require the captured run_case hook", + } + + +def _readiness(modules: Mapping[str, Any], protocol: Mapping[str, Any]) -> dict[str, Any]: + checks = modules.get("checks") + available = { + name: bool(checks is not None and callable(getattr(checks, name, None))) + for name in ("check_mesh", "check_binding", "check_pose", "compare_root") + } + perturbation_api_available = bool( + modules.get("perturbations") is not None + and callable(getattr(modules["perturbations"], "run_case", None)) + ) + perturbation_protocol = _perturbation_status(protocol) + if perturbation_protocol["status"] == "not-implemented" and perturbation_api_available: + perturbation_protocol = { + **perturbation_protocol, + "implementation": "captured", + "reason": "captured run_case hook is available; execution is recorded per case", + } + else: + perturbation_protocol = {**perturbation_protocol, "implementation": "pending"} + return { + "status": "ready" if all(available.values()) else "pending", + "required_checks": { + key: {"signature": signature, "available": available[key.split(".")[-1]]} + for key, signature in REQUIRED_CHECK_SIGNATURES.items() + }, + "new_source_leg_inputs": list(CANONICAL_LEG_INPUT_FIELDS), + "protocol_pose_field": "baseline_poses", + "protocol_perturbations": perturbation_protocol, + "perturbation_api": { + "signature": PERTURBATION_SIGNATURE, + "available": perturbation_api_available, + }, + } + + +def _render_one(render: Any, mesh: Mapping[str, Any], path: Path, title: str, + status: str, bounds: list[list[float]], overlays: list[dict[str, Any]]) -> dict[str, Any]: + try: + surface = render.render_views(mesh["vertices"], mesh.get("quads", mesh.get("faces")), path, + title, status, bounds=bounds, overlays=None, + underside=True, allow_crop=False) + diagnostic = None + if overlays: + diagnostic = render.render_views(mesh["vertices"], mesh.get("quads", mesh.get("faces")), + path.with_name(path.stem + "-diagnostic.png"), title, + status, bounds=bounds, overlays=overlays, + underside=False, allow_crop=False) + return {"surface": _jsonable(surface), "diagnostic": _jsonable(diagnostic), "status": status} + except Exception as exc: + return {"status": "exception", "exception": {"type": type(exc).__name__, "message": str(exc)}} + + +def _visual_status(result: Mapping[str, Any], rest_only: bool, perturbation: bool = False) -> str: + if result.get("status") == "rejected": + return "REJECTED" + if result.get("status") == "exception": + return "EXECUTION ERROR - UNCLASSIFIED" + if rest_only: + return "INTERNAL DIAGNOSTIC - NO FULL PASS" + if result.get("status") == "pending" or perturbation: + return "CHECKS PENDING - VISUAL PENDING" + return "TECHNICAL PASS - VISUAL PENDING" + + +def _evaluate(module: Any, mesh: Mapping[str, Any]) -> list[Any]: + """Use the existing two-level evaluator, retaining tiny test doubles.""" + function = getattr(module, "evaluate", None) + if not callable(function): + _fail("construction collaborator has no evaluate function") + try: + value = function(mesh, levels=2) + except TypeError as exc: + # Existing synthetic runner tests predate the explicit levels keyword. + # Only retry that narrow compatibility shape; do not mask other errors. + if "unexpected keyword argument 'levels'" not in str(exc): + raise + value = function(mesh) + if not isinstance(value, (list, tuple)) or not value: + _fail("construction.evaluate must return a non-empty sequence") + return list(value) + + +def _source_mode(values: Mapping[str, Any], modules: Mapping[str, Any]) -> bool: + root_source = modules.get("root_source") + hip_source = modules.get("hip_source") + source_present = root_source is not None or hip_source is not None + if not source_present: + return False + if root_source is None or hip_source is None: + _fail("root_source.py and hip_source.py are required together") + if not callable(getattr(root_source, "reconstruct_source_case", None)): + _fail("root_source.reconstruct_source_case is not captured") + if not callable(getattr(hip_source, "bind_source_case", None)): + _fail("hip_source.bind_source_case is not captured") + if values.get("original_case") is None: + _fail("source rebuild requires the captured original_case input") + return True + + +def _foot_case_inputs(foot_inputs: Any, case_id: str) -> Mapping[str, Any]: + if not isinstance(foot_inputs, Mapping): + _fail("captured foot-inputs.json must be an object") + rows = [row for row in foot_inputs.get("cases", []) + if isinstance(row, Mapping) and row.get("case_id") == case_id] + if len(rows) != 1: + _fail(f"captured foot-inputs.json lacks unique case {case_id}") + sides = rows[0].get("sides") + if not isinstance(sides, Mapping): + _fail(f"captured foot-inputs.json case {case_id} lacks sides") + return sides + + +def _case_row(document: Any, case_id: str, label: str) -> Mapping[str, Any]: + if not isinstance(document, Mapping): + _fail(f"captured {label} must be an object") + rows = [row for row in document.get("cases", []) + if isinstance(row, Mapping) and row.get("case_id") == case_id] + if len(rows) != 1: + _fail(f"captured {label} lacks unique case {case_id}") + return rows[0] + + +def _component_case_inputs(document: Any, case_id: str, key: str, + label: str) -> Mapping[str, Any]: + if not isinstance(document, Mapping): + _fail(f"captured {label} must be an object") + rows = [row for row in document.get("cases", []) + if isinstance(row, Mapping) and row.get("case_id") == case_id] + if len(rows) != 1: + _fail(f"captured {label} lacks unique case {case_id}") + value = rows[0].get(key) + if not isinstance(value, Mapping): + _fail(f"captured {label} case {case_id} lacks {key}") + return value + + +def _body_dependencies(modules: Mapping[str, Any], + optional: Mapping[str, Any] | None = None) -> Any: + body = modules.get("body_assembly") + dependencies = getattr(body, "AssemblyDependencies", None) + if not callable(dependencies): + _fail("body_assembly.AssemblyDependencies is not captured") + selected = optional or {} + dependency_kwargs = dict( + root_source=modules.get("root_source"), + hip_source=modules.get("hip_source"), + leg_builder=modules.get("construction"), + binding=modules.get("binding"), + foot_builder=selected.get("foot_builder", modules.get("foot_construction")), + foot_builder_name=selected.get("foot_builder_name", "foot_construction.build"), + arm_builder=modules.get("arm_construction"), + head_builder=modules.get("head_construction"), + tail_builder=selected.get("tail_builder"), + tail_builder_name=selected.get("tail_builder_name"), + torso_refinement=modules.get("torso_refinement"), + ) + # Preserve the legacy dependency call unless a body config explicitly + # selects an optional foundation provider. + thorax_foundation = selected.get("thorax_foundation") + if thorax_foundation is not None: + dependency_kwargs["thorax_foundation"] = thorax_foundation + abdomen_foundation = selected.get("abdomen_foundation") + if abdomen_foundation is not None: + dependency_kwargs["abdomen_foundation"] = abdomen_foundation + return dependencies(**dependency_kwargs) + + +def _assemble_selected_body(modules: Mapping[str, Any], + source_case: Mapping[str, Any], + leg_inputs: Mapping[str, Any], + optional: Mapping[str, Any]) -> Mapping[str, Any]: + """Assemble one explicitly selected source-driven body. + + This is the single body-assembly seam used by the normal runner and by + bounded body evidence probes. The kwargs are intentionally the existing + runner kwargs; the helper does not introduce a second construction lane. + """ + body = modules.get("body_assembly") + if body is None or not callable(getattr(body, "assemble", None)): + _fail("body_assembly.assemble is not captured") + body_kwargs = { + "foot_inputs": optional["foot_inputs"], + "arm_inputs": optional["arm_inputs"], + "head_inputs": optional["head_inputs"], + "dependencies": _body_dependencies(modules, optional), + } + if optional["foot_form_inputs"] is not None: + body_kwargs["foot_form_inputs"] = optional["foot_form_inputs"] + if optional["foot_policy"] is not None: + body_kwargs["foot_policy"] = optional["foot_policy"] + if optional["tail_inputs"] is not None: + body_kwargs["tail_inputs"] = optional["tail_inputs"] + if optional["source_refinement_inputs"] is not None: + body_kwargs["source_refinement_inputs"] = optional["source_refinement_inputs"] + if optional["thorax_foundation_inputs"] is not None: + body_kwargs["thorax_foundation_inputs"] = optional["thorax_foundation_inputs"] + if optional["abdomen_foundation_inputs"] is not None: + body_kwargs["abdomen_foundation_inputs"] = optional["abdomen_foundation_inputs"] + if optional.get("pelvis_foundation_inputs") is not None: + body_kwargs["pelvis_foundation_inputs"] = optional["pelvis_foundation_inputs"] + result = body.assemble(source_case, leg_inputs, **body_kwargs) + if not isinstance(result, Mapping): + _fail("body_assembly.assemble must return a mapping") + return result + + +def _body_provisional_protocol(protocol: Mapping[str, Any], *, + has_arms: bool, has_head: bool) -> dict[str, Any]: + """Overlay two internal body poses while retaining captured thresholds.""" + result = dict(protocol) + result.pop("poses", None) + poses = copy.deepcopy(BODY_PROVISIONAL_POSES) + if not has_arms: + for row in poses: + for side in ("left", "right"): + for name in ("shoulder_raise", "shoulder_forward", "elbow"): + row[side][name] = 0 + if not has_head: + for row in poses: + row["head"] = {"yaw": 0, "nod": 0} + result["baseline_poses"] = list(poses) + result["body_provisional_evidence"] = { + "status": "internal-only", + "pose_count_per_case": 2, + "threshold_source": "captured connected-leg protocol", + "whole_character_checkpoint": False, + "arms_enabled": has_arms, + "head_enabled": has_head, + } + return result + + +def _body_config_section(body_config: Any, key: str) -> Mapping[str, Any] | None: + if body_config is None: + return None + document = _mapping(body_config, "body-config") + value = document.get(key) + if value is None: + return None + return _mapping(value, f"body-config.{key}") + + +def _body_optional_inputs(modules: Mapping[str, Any], case_id: str, + body_config: Mapping[str, Any] | None = None) -> dict[str, Any]: + values: dict[str, Any] = { + "source_refinement_inputs": None, + "thorax_foundation_inputs": None, + "thorax_foundation": None, + "thorax_foundation_input_name": None, + "abdomen_foundation_inputs": None, + "abdomen_foundation": None, + "abdomen_foundation_input_name": None, + "pelvis_foundation_inputs": None, + "pelvis_foundation": modules.get("pelvis_foundation"), + "pelvis_foundation_input_name": None, + "foot_inputs": None, + "foot_builder": modules.get("foot_construction"), + "foot_builder_name": "foot_construction.build", + "foot_form_inputs": None, + "foot_policy": None, + "arm_inputs": None, + "head_inputs": None, + "tail_inputs": None, + "tail_builder": None, + "tail_builder_name": None, + } + + torso_section = _body_config_section(body_config, "torso_refinement") + foundation_section = _body_config_section(body_config, "thorax_foundation") + abdomen_section = _body_config_section(body_config, "abdomen_foundation") + pelvis_section = _body_config_section(body_config, "pelvis_foundation") + if torso_section is not None and (foundation_section is not None + or abdomen_section is not None + or pelvis_section is not None): + _fail("body-config.torso_refinement and foundation sections are mutually exclusive") + if abdomen_section is not None and foundation_section is None: + _fail("body-config.abdomen_foundation requires thorax_foundation") + if pelvis_section is not None: + unknown_pelvis = set(pelvis_section) - {"inputs", "authority"} + if unknown_pelvis: + _fail(f"body-config.pelvis_foundation has unsupported fields: {sorted(unknown_pelvis)!r}") + if foundation_section is None or abdomen_section is None: + _fail("body-config.pelvis_foundation requires thorax_foundation and abdomen_foundation") + if foundation_section.get("inputs") != "thorax-foundation-baseline-inputs.json": + _fail("body-config.pelvis_foundation requires thorax-foundation-baseline-inputs.json") + if abdomen_section.get("inputs") != "abdomen-foundation-baseline-inputs.json": + _fail("body-config.pelvis_foundation requires abdomen-foundation-baseline-inputs.json") + + if torso_section is not None: + selected_file = torso_section.get("inputs") + torso_input_keys = { + "torso-refinement-inputs.json": "torso_refinement_inputs", + "torso-silhouette-inputs.json": "torso_silhouette_inputs", + "torso-silhouette-correction-inputs.json": "torso_silhouette_correction_inputs", + "torso-chest-depth-ablation-inputs.json": "torso_chest_depth_ablation_inputs", + "torso-chest-envelope-inputs.json": "torso_chest_envelope_inputs", + } + selected_input_key = torso_input_keys.get(selected_file) + if selected_input_key is None: + _fail("body-config.torso_refinement.inputs selects an unsupported captured input") + if modules.get("torso_refinement") is None: + _fail("body-config torso refinement requires torso_refinement.py") + values["source_refinement_inputs"] = modules.get(selected_input_key) + if values["source_refinement_inputs"] is None: + _fail(f"body-config torso refinement requires {selected_file}") + + if foundation_section is not None: + selected_file = foundation_section.get("inputs") + foundation_input_keys = { + "thorax-foundation-baseline-inputs.json": "thorax_foundation_baseline_inputs", + "thorax-foundation-width-inputs.json": "thorax_foundation_width_inputs", + "thorax-foundation-fullness-inputs.json": "thorax_foundation_fullness_inputs", + } + selected_input_key = foundation_input_keys.get(selected_file) + if selected_input_key is None: + _fail("body-config.thorax_foundation.inputs selects an unsupported captured input") + if modules.get("thorax_foundation") is None: + _fail("body-config thorax foundation requires thorax_foundation.py") + selected_inputs = modules.get(selected_input_key) + if selected_inputs is None: + _fail(f"body-config thorax foundation requires {selected_file}") + values["thorax_foundation_inputs"] = selected_inputs + values["thorax_foundation"] = modules["thorax_foundation"] + values["thorax_foundation_input_name"] = selected_file + + if abdomen_section is not None: + selected_file = abdomen_section.get("inputs") + abdomen_input_keys = { + "abdomen-foundation-baseline-inputs.json": "abdomen_foundation_baseline_inputs", + "abdomen-foundation-bow-inputs.json": "abdomen_foundation_bow_inputs", + "abdomen-foundation-fullness-inputs.json": "abdomen_foundation_fullness_inputs", + } + selected_input_key = abdomen_input_keys.get(selected_file) + if selected_input_key is None: + _fail("body-config.abdomen_foundation.inputs selects an unsupported captured input") + if modules.get("abdomen_foundation") is None: + _fail("body-config abdomen foundation requires abdomen_foundation_provider.py") + selected_inputs = modules.get(selected_input_key) + if selected_inputs is None: + _fail(f"body-config abdomen foundation requires {selected_file}") + values["abdomen_foundation_inputs"] = selected_inputs + values["abdomen_foundation"] = modules["abdomen_foundation"] + values["abdomen_foundation_input_name"] = selected_file + + if pelvis_section is not None: + selected_file = pelvis_section.get("inputs") + pelvis_input_keys = { + "pelvis-foundation-baseline-inputs.json": "pelvis_foundation_baseline_inputs", + "pelvis-foundation-iliac-inputs.json": "pelvis_foundation_iliac_inputs", + "pelvis-foundation-gluteal-inputs.json": "pelvis_foundation_gluteal_inputs", + } + selected_input_key = pelvis_input_keys.get(selected_file) + if selected_input_key is None: + _fail("body-config.pelvis_foundation.inputs selects an unsupported captured input") + if modules.get("pelvis_foundation") is None: + _fail("body-config pelvis foundation requires pelvis_foundation.py") + selected_inputs = modules.get(selected_input_key) + if selected_inputs is None: + _fail(f"body-config pelvis foundation requires {selected_file}") + abdomen_inputs = values.get("abdomen_foundation_inputs") + if (not isinstance(abdomen_inputs, Mapping) + or abdomen_inputs.get("bow") != 0.0 + or abdomen_inputs.get("fullness") != 1.0): + _fail("body-config.pelvis_foundation requires direct abdomen baseline values") + values["pelvis_foundation_inputs"] = selected_inputs + values["pelvis_foundation_input_name"] = selected_file + + feet_section = _body_config_section(body_config, "feet") + if feet_section is not None: + builder = feet_section.get("builder") + if builder == "foot_form_construction.py": + if modules.get("foot_form_construction") is None: + _fail("body-config FOOT004 requires foot_form_construction.py") + values["foot_inputs"] = _case_row( + modules.get("foot_form_inputs"), case_id, "foot-form-inputs.json" + ) + values["foot_builder"] = modules["foot_form_construction"] + values["foot_builder_name"] = "foot_form_construction.build" + elif builder == "foot_junction_construction.py": + if feet_section.get("inputs") != "foot-form-inputs.json": + _fail("JUNCTION-001 feet.inputs must select foot-form-inputs.json") + if feet_section.get("policy") != "foot-junction-policy.json": + _fail("JUNCTION-001 feet.policy must select foot-junction-policy.json") + if modules.get("foot_junction_construction") is None: + _fail("body-config JUNCTION-001 requires foot_junction_construction.py") + if modules.get("foot_form_inputs") is None: + _fail("body-config JUNCTION-001 requires foot-form-inputs.json") + policy = modules.get("foot_junction_policy") + if not isinstance(policy, Mapping): + _fail("body-config JUNCTION-001 requires foot-junction-policy.json") + if policy.get("schema") != "creature-kernel.connected-leg-assembly-foot-junction-policy.v1": + _fail("foot-junction-policy.json has an unsupported schema") + if policy.get("candidate") != "JUNCTION-001": + _fail("foot-junction-policy.json must select JUNCTION-001") + values["foot_form_inputs"] = _case_row( + modules.get("foot_form_inputs"), case_id, "foot-form-inputs.json" + ) + values["foot_policy"] = policy + values["foot_builder"] = modules["foot_junction_construction"] + values["foot_builder_name"] = "foot_junction_construction.build" + elif builder == "foot_construction.py": + if modules.get("foot_construction") is None: + _fail("body-config diagnostic feet requires foot_construction.py") + values["foot_inputs"] = _foot_case_inputs( + modules.get("foot_inputs"), case_id + ) + else: + _fail("body-config.feet.builder must select a captured foot builder") + else: + legacy_document = modules.get("foot_inputs") if body_config is None else None + if legacy_document is not None: + if modules.get("foot_construction") is None: + _fail("captured foot-inputs.json requires foot_construction.py") + values["foot_inputs"] = _foot_case_inputs(legacy_document, case_id) + + pairs = ( + ("arms", "arm_construction", "arm_inputs", "arm-inputs.json", "sides"), + ("head", "head_construction", "head_inputs", "head-inputs.json", "head"), + ) + for section_key, module_key, input_key, default_file, row_key in pairs: + selected_file = default_file + section = _body_config_section(body_config, section_key) + if section is not None: + selected_file = section.get("inputs") + if section_key == "arms": + allowed_files = {"arm-inputs.json", "arm-refinement-inputs.json"} + selected_input_key = ( + "arm_refinement_inputs" + if selected_file == "arm-refinement-inputs.json" + else "arm_inputs" + ) + else: + allowed_files = {"head-inputs.json", "head-refinement-inputs.json"} + selected_input_key = ( + "head_refinement_inputs" + if selected_file == "head-refinement-inputs.json" + else "head_inputs" + ) + if selected_file not in allowed_files: + _fail(f"body-config.{section_key}.inputs selects an unsupported captured input") + input_key = selected_input_key + document = modules.get(input_key) + module = modules.get(module_key) + if document is None: + if section is not None: + _fail(f"body-config.{section_key} requires {selected_file}") + continue + if module is None: + _fail(f"captured {input_key}.json requires its construction module") + values["head_inputs" if section_key == "head" else "arm_inputs"] = ( + _component_case_inputs(document, case_id, row_key, selected_file) + ) + + tail_section = _body_config_section(body_config, "tail") + if tail_section is not None: + if tail_section.get("builder") != "tail_construction.py": + _fail("body-config.tail.builder must select tail_construction.py") + if modules.get("tail_construction") is None: + _fail("body-config tail requires tail_construction.py") + values["tail_inputs"] = _case_row( + modules.get("tail_inputs"), case_id, "tail-inputs.json" + ) + values["tail_builder"] = modules["tail_construction"] + values["tail_builder_name"] = "tail_construction.build" + return values + + +def _source_cache_comparison(source_root: Mapping[str, Any], + source_rest: Mapping[str, Any], + source_binding: Mapping[str, Any], + cached_root: Any, cached_rest: Any, + cached_binding: Any) -> dict[str, Any]: + binding_keys = ("base_weights", "evaluated_weights", "rest_frames") + cached_binding_map = cached_binding if isinstance(cached_binding, Mapping) else {} + return { + "cache_role": "comparison-only; never a construction or binding input", + "root_L0_exact": source_root == cached_root, + "root_L2_exact": source_rest == cached_rest, + "root_binding_exact": { + key: source_binding.get(key) == cached_binding_map.get(key) + for key in binding_keys + }, + } + + +def _case_run(case_data: Mapping[str, Any], protocol: Mapping[str, Any], modules: Mapping[str, Any], + case_dir: Path, rest_only: bool, + body_config: Mapping[str, Any] | None = None) -> dict[str, Any]: + case = case_data["case"] + values = case_data["values"] + case_id = str(case_data["id"]) + construction = modules.get("construction") + if construction is None or not callable(getattr(construction, "build", None)) or not callable(getattr(construction, "evaluate", None)): + return {"id": case_id, "status": "pending", "reason": "construction API is not captured", "exceptions": []} + case_dir.mkdir(parents=True, exist_ok=True) + result: dict[str, Any] = {"id": case_id, "status": "pending", "exceptions": [], "poses": []} + if body_config is not None: + result["body_evidence"] = { + "label": body_config.get("evidence_label"), + "acceptance": body_config.get("acceptance"), + "status": body_config.get("status"), + } + stage = "construction" + try: + cached_root = values["root_mesh"] + cached_rest = values["prior_rest_mesh"] + cached_binding = values["prior_hip_binding"] + leg_inputs = values["leg_inputs"] + source_comparison: dict[str, Any] | None = None + body_mode = False + body_binding: Mapping[str, Any] | None = None + foot_enabled = False + tail_enabled = False + if _source_mode(values, modules): + stage = "source-reconstruction" + source_case = values["original_case"] + body = modules.get("body_assembly") + if body is not None: + body_mode = True + optional = _body_optional_inputs(modules, case_id, body_config) + stage = "body-assembly" + body_result = _assemble_selected_body( + modules, source_case, leg_inputs, optional + ) + root = body_result.get("rebuilt_root_l0") + prior_rest = body_result.get("rebuilt_root_l2") + prior_binding = body_result.get("rebuilt_root_binding") + built = body_result.get("final_l0") + baseline_l0 = built + baseline_l2 = body_result.get("final_l2") + body_binding = body_result.get("binding") + if not all(isinstance(value, Mapping) for value in + (root, prior_rest, prior_binding, built, + baseline_l2, body_binding)): + _fail("body_assembly result lacks rebuilt roots, final L0/L2, or binding") + source_comparison = _source_cache_comparison( + root, prior_rest, prior_binding, cached_root, + cached_rest, cached_binding) + if optional["thorax_foundation_inputs"] is not None: + source_comparison = { + **source_comparison, + "comparison_role": "diagnostic-only", + "required_for_full_pass": False, + "reason": ( + "thorax foundation intentionally rebuilds J/skin from " + "source; cached root remains comparison-only" + ), + } + source_provenance = { + "root_source": body_result.get("source_provenance", {}).get("root", {}), + "hip_source": body_result.get("source_provenance", {}).get("hip", {}), + "refinement": body_result.get("refinement_provenance"), + "effective_source_case": body_result.get("effective_source_case"), + "cache_comparison": source_comparison, + "component_manifest": body_result.get("component_manifest", {}), + "foundation_input_selection": { + "thorax": optional.get("thorax_foundation_input_name"), + "abdomen": optional.get("abdomen_foundation_input_name"), + "pelvis": optional.get("pelvis_foundation_input_name"), + }, + } + foundation_records = body_result.get("foundation_records") + if foundation_records is not None: + foundation_records = _mapping( + foundation_records, "body_result.foundation_records" + ) + if "abdomen_foundation" in foundation_records: + combined_name = "combined-foundation-source-evidence.json" + _write_json( + case_dir / combined_name, + _jsonable(foundation_records), + ) + source_provenance["combined_foundation_source_evidence"] = combined_name + result["combined_foundation_source_evidence"] = combined_name + evidence_name = "abdomen-foundation-source-evidence.json" + _write_json( + case_dir / evidence_name, + _jsonable(foundation_records["abdomen_foundation"]), + ) + source_provenance["abdomen_foundation_source_evidence"] = evidence_name + result["abdomen_foundation_source_evidence"] = evidence_name + if "pelvis_foundation" in foundation_records: + evidence_name = "pelvis-foundation-source-evidence.json" + _write_json( + case_dir / evidence_name, + _jsonable(foundation_records["pelvis_foundation"]), + ) + source_provenance["pelvis_foundation_source_evidence"] = evidence_name + result["pelvis_foundation_source_evidence"] = evidence_name + if "thorax_foundation" in foundation_records: + evidence_name = "thorax-foundation-source-evidence.json" + _write_json( + case_dir / evidence_name, + _jsonable(foundation_records["thorax_foundation"]), + ) + source_provenance["thorax_foundation_source_evidence"] = evidence_name + result["thorax_foundation_source_evidence"] = evidence_name + elif (optional["thorax_foundation_inputs"] is not None + and optional["abdomen_foundation_inputs"] is None): + evidence_name = "thorax-foundation-source-evidence.json" + _write_json(case_dir / evidence_name, _jsonable(foundation_records)) + source_provenance["thorax_foundation_source_evidence"] = evidence_name + result["thorax_foundation_source_evidence"] = evidence_name + _write_json(case_dir / "source-provenance.json", _jsonable(source_provenance)) + # Keep existing perturbation evidence on the leg-only baseline. + leg_built = construction.build(root, leg_inputs) + leg_levels = _evaluate(construction, leg_built) + foot_enabled = ( + optional["foot_inputs"] is not None or + optional["foot_form_inputs"] is not None + ) + tail_enabled = optional["tail_inputs"] is not None + else: + source_module = modules["root_source"] + source_result = source_module.reconstruct_source_case(source_case) + source_levels = source_result.get("levels") if isinstance(source_result, Mapping) else None + if not isinstance(source_levels, Mapping) or "L0" not in source_levels or "L2" not in source_levels: + _fail("root_source reconstruction must return L0 and L2 levels") + root = source_levels["L0"] + prior_rest = source_levels["L2"] + hip_result = modules["hip_source"].bind_source_case( + root, prior_rest, source_case, leg_inputs=leg_inputs) + if not isinstance(hip_result, Mapping) or not isinstance(hip_result.get("binding"), Mapping): + _fail("hip_source binding must return a binding mapping") + prior_binding = hip_result["binding"] + source_comparison = _source_cache_comparison( + root, prior_rest, prior_binding, cached_root, cached_rest, cached_binding) + _write_json(case_dir / "source-provenance.json", _jsonable({ + "root_source": source_result.get("provenance", {}), + "hip_source": hip_result.get("provenance", {}), + "cache_comparison": source_comparison, + })) + else: + # Older leg-only captures predate the source adapters. Preserve + # that mode, but keep the cached values in this explicitly named + # compatibility path rather than silently mixing modes. + root = cached_root + prior_rest = cached_rest + prior_binding = cached_binding + + if not body_mode: + leg_built = construction.build(root, leg_inputs) + leg_levels = _evaluate(construction, leg_built) + built = leg_built + levels = leg_levels + foot = modules.get("foot_construction") + foot_inputs = modules.get("foot_inputs") + if foot is not None or foot_inputs is not None: + if foot is None or foot_inputs is None: + _fail("foot_construction.py and foot-inputs.json are required together") + stage = "foot-construction" + foot_row = _foot_case_inputs(foot_inputs, case_id) + built = foot.build(leg_built, leg_inputs, foot_row) + levels = _evaluate(foot, built) + foot_enabled = True + baseline_l0 = levels[0] + baseline_l2 = levels[-1] + _write_json(case_dir / "prior-root.json", _jsonable(cached_root)) + _write_json(case_dir / "prior-rest.json", _jsonable(cached_rest)) + _write_json(case_dir / "prior-hip-binding.json", _jsonable(cached_binding)) + if source_comparison is not None: + _write_json(case_dir / "rebuilt-root-L0.json", _jsonable(root)) + _write_json(case_dir / "rebuilt-root-L2.json", _jsonable(prior_rest)) + _write_json(case_dir / "rebuilt-root-binding.json", _jsonable(prior_binding)) + result["rebuilt_root_artifacts"] = { + "L0": "rebuilt-root-L0.json", + "L2": "rebuilt-root-L2.json", + "binding": "rebuilt-root-binding.json", + } + _write_json(case_dir / "leg-baseline-L0.json", _jsonable(leg_levels[0])) + _write_json(case_dir / "leg-baseline-L2.json", _jsonable(leg_levels[-1])) + _write_json(case_dir / "base.json", _jsonable(built)) + _write_json(case_dir / "baseline-L0.json", _jsonable(baseline_l0)) + _write_json(case_dir / "baseline-L2.json", _jsonable(baseline_l2)) + _write_json(case_dir / "rest.json", _jsonable(baseline_l2)) + base_reloaded, _ = _read_json(case_dir / "base.json") + baseline_l0_reloaded, _ = _read_json(case_dir / "baseline-L0.json") + baseline_l2_reloaded, _ = _read_json(case_dir / "baseline-L2.json") + rest_reloaded, _ = _read_json(case_dir / "rest.json") + result.update({"rest": rest_reloaded, "base": base_reloaded, + "baseline_L0": baseline_l0_reloaded, + "baseline_L2": baseline_l2_reloaded, + "bounds_inputs": [rest_reloaded], + "materialization": "source-rebuilt" if source_comparison is not None else "legacy-cached-root", + "body_materialized": body_mode, + "foot_materialized": foot_enabled, + "tail_materialized": tail_enabled, + "source_rebuild": source_comparison}) + checks = modules.get("checks") + checks_ready = checks is not None and callable(getattr(checks, "check_mesh", None)) + if checks is None: + result["checks"] = {"status": "pending", "reason": "checks module is not captured"} + elif checks_ready: + report = checks.check_mesh(rest_reloaded, protocol) + _write_json(case_dir / "mesh-checks.json", _jsonable(report)) + result["checks"] = {"mesh": _jsonable(report), "mesh_pass": _report_pass(report)} + else: + result["checks"] = {"status": "pending", "reason": "checks.check_mesh is not ready"} + if rest_only: + result.update({"status": "internal-diagnostic", "full_pass": False, + "reason": "--rest-only stops before binding and is not a full pass"}) + return result + binding_module = modules.get("binding") + if binding_module is None: + result.update({"status": "pending", "reason": "binding API is not captured", "full_pass": False}) + return result + stage = "binding" + binding = body_binding if body_mode else binding_module.bind( + base_reloaded, rest_reloaded, root, prior_binding, leg_inputs) + _write_json(case_dir / "binding.json", _jsonable(binding)) + binding_reloaded, _ = _read_json(case_dir / "binding.json") + binding_check_ready = checks is not None and callable(getattr(checks, "check_binding", None)) + if binding_check_ready: + report = checks.check_binding(base_reloaded, rest_reloaded, binding_reloaded, + root, prior_binding, leg_inputs, protocol) + _write_json(case_dir / "binding-checks.json", _jsonable(report)) + result["checks"]["binding"] = _jsonable(report) + result["checks"]["binding_pass"] = _report_pass(report) + else: + result["checks"]["binding"] = {"status": "pending", "reason": "checks.check_binding is not ready"} + poses = _protocol_poses(protocol) + pose_points = [] + source_comparison_pass = True + if source_comparison is not None: + if source_comparison.get("required_for_full_pass") is False: + source_comparison_pass = True + else: + source_comparison_pass = bool( + source_comparison.get("root_L0_exact") and + source_comparison.get("root_L2_exact") and + all(source_comparison.get("root_binding_exact", {}).values()) + ) + all_pass = (result.get("checks", {}).get("mesh_pass", False) is True and + result.get("checks", {}).get("binding_pass", False) is True and + source_comparison_pass) + checks_complete = checks_ready and binding_check_ready + for pose in poses: + stage = f"pose:{pose['id']}" + pose_dir = case_dir / "poses" / str(pose["id"]) + pose_dir.mkdir(parents=True, exist_ok=True) + posed = binding_module.pose(rest_reloaded, binding_reloaded, pose["angles"]) + points = binding_module.joint_points(binding_reloaded, pose["angles"]) + _write_json(pose_dir / "mesh.json", _jsonable(posed)) + _write_json(pose_dir / "joints.json", _jsonable(points)) + posed_reloaded, _ = _read_json(pose_dir / "mesh.json") + pose_reloaded, _ = _read_json(pose_dir / "joints.json") + pose_record: dict[str, Any] = {"id": pose["id"], "angles": pose["angles"], "mesh": posed_reloaded, + "joints": pose_reloaded} + if checks is not None and callable(getattr(checks, "check_pose", None)): + report = checks.check_pose(rest_reloaded, posed_reloaded, binding_reloaded, + pose["angles"], protocol, leg_inputs) + _write_json(pose_dir / "checks.json", _jsonable(report)) + pose_record["checks"] = _jsonable(report) + pose_pass = _report_pass(report) + all_pass = all_pass and pose_pass + else: + pose_record["checks"] = {"status": "pending", "reason": "checks.check_pose is not ready"} + all_pass = False + checks_complete = False + result["poses"].append(pose_record) + # Add each successfully materialized pose immediately so a later + # case/pose exception cannot shrink the shared render bounds. + result["bounds_inputs"].append(posed_reloaded) + pose_points.append(pose_reloaded) + if checks is not None and callable(getattr(checks, "compare_root", None)): + stage = "root-comparison" + report = checks.compare_root(root, baseline_l0_reloaded, prior_rest, baseline_l2_reloaded) + _write_json(case_dir / "root-comparison.json", _jsonable(report)) + result["root_comparison"] = _jsonable(report) + all_pass = all_pass and _report_pass(report) + else: + result["root_comparison"] = {"status": "pending", "reason": "checks.compare_root is not ready"} + all_pass = False + checks_complete = False + stage = "perturbations" + perturbation_status = _perturbation_status(protocol) + perturbation_module = modules.get("perturbations") + perturbation_result: dict[str, Any] | None = None + if perturbation_status["status"] == "not-declared": + result["perturbations"] = perturbation_status + perturbation_pass = True + elif perturbation_module is None or not callable(getattr(perturbation_module, "run_case", None)): + result["perturbations"] = { + **perturbation_status, + "reason": "perturbations.run_case is not captured", + } + perturbation_pass = False + checks_complete = False + else: + perturbation_baseline_binding = binding_reloaded + leg_only_perturbations = body_mode or foot_enabled + if leg_only_perturbations: + # The existing perturbation hook is explicitly leg-only. Run + # it against the saved intermediate leg baseline only, and + # keep it out of body/foot acceptance accounting. + perturbation_baseline_binding = binding_module.bind( + leg_levels[0], leg_levels[-1], root, prior_binding, leg_inputs) + perturbation_result = perturbation_module.run_case( + root, prior_rest, prior_binding, leg_inputs, + leg_levels[0] if leg_only_perturbations else baseline_l0_reloaded, + leg_levels[-1] if leg_only_perturbations else baseline_l2_reloaded, + perturbation_baseline_binding, + protocol, construction, binding_module) + perturbation_result = _jsonable(perturbation_result) + if leg_only_perturbations: + perturbation_result = { + **perturbation_result, + "status": "leg-only", + "coverage": "leg-baseline-only", + "foot_coverage": "not-run", + "leg_baseline_result": perturbation_result, + } + _write_json(case_dir / "perturbations.json", perturbation_result) + result["perturbations"] = perturbation_result + result["perturbation_meshes"] = _save_perturbation_evidence(case_dir, perturbation_result) + expected_ids = perturbation_status.get("declared_ids", []) + perturbation_pass = (not foot_enabled and + _perturbation_result_ready(perturbation_result, expected_ids)) + complete = all_pass and checks_complete and perturbation_pass + perturbation_rejected = (isinstance(perturbation_result, Mapping) + and perturbation_result.get("status") == "failed") + result["status"] = ("technical-pass" if complete else + "pending" if not checks_complete or + (not perturbation_pass and not perturbation_rejected) else + "rejected") + result["full_pass"] = complete + result["overlay_points"] = pose_points + return result + except Exception as exc: + result["status"] = "exception" + result["full_pass"] = False + blocker = {"case": case_id, "stage": stage, "type": type(exc).__name__, "message": str(exc)} + result["exceptions"].append({"type": type(exc).__name__, "message": str(exc), "stage": stage}) + if (stage != "perturbations" and _perturbation_status(protocol)["status"] not in ("not-declared", "invalid") + and "perturbations" not in result + and modules.get("perturbations") is not None + and callable(getattr(modules["perturbations"], "run_case", None))): + result["perturbations"] = { + "status": "blocked-by-earlier-error", "execution": "not-run", "blocker": blocker, + } + return result + + +def run(snapshot: str | os.PathLike[str], output: str | os.PathLike[str], + rest_only: bool = False, body_config: str | None = None) -> dict[str, Any]: + """Execute captured collaborators once into an absent output directory.""" + snapshot_path = _canonical(snapshot, "snapshot") + manifest = verify(snapshot_path) + captured_runner = snapshot_path / SNAPSHOT_SOURCE / "runner.py" + if Path(__file__).resolve() != captured_runner.resolve(): + _fail("run must execute from the captured new-source runner") + output_path = _canonical(output, "output") + if output_path.exists() or output_path.is_symlink(): + _fail(f"output must be absent: {output_path}") + if not output_path.parent.is_dir() or output_path.parent.is_symlink(): + _fail("output parent must be an existing regular directory") + protocol, protocol_raw = _read_json(_snapshot_path(snapshot_path, str(SNAPSHOT_SOURCE / "protocol.json"))) + inputs, inputs_raw = _read_json(_snapshot_path(snapshot_path, str(SNAPSHOT_SOURCE / "inputs.json"))) + if not isinstance(protocol, Mapping) or not isinstance(inputs, Mapping): + _fail("captured protocol and inputs must be objects") + cases = _load_case_inputs(snapshot_path, manifest, inputs) + modules = _load_collaborators(snapshot_path, manifest, rest_only) + body_source_mode = bool( + not rest_only and modules.get("body_assembly") is not None + and any(isinstance(item.get("values", {}).get("original_case"), Mapping) + for item in cases) + ) + if body_config is not None and not body_source_mode: + _fail("--body-config requires source-driven body mode and is incompatible with --rest-only") + selected_body_config = (_load_body_config(snapshot_path, manifest, body_config) + if body_config is not None else None) + case_protocol = (_body_provisional_protocol( + protocol, + has_arms=modules.get("arm_inputs") is not None, + has_head=(modules.get("head_inputs") is not None or + modules.get("head_refinement_inputs") is not None), + ) if body_source_mode else protocol) + output_path.mkdir() + _write_json(output_path / "protocol.json", protocol) + if body_source_mode: + _write_json(output_path / "effective-body-protocol.json", _jsonable(case_protocol)) + (output_path / "inputs.json").write_bytes(inputs_raw) + (output_path / "runner-source.py").write_bytes((snapshot_path / SNAPSHOT_SOURCE / "runner.py").read_bytes()) + results = [] + for index, case in enumerate(cases): + results.append(_case_run(case, case_protocol, modules, + output_path / "cases" / f"case-{index:02d}-{case['id']}", + rest_only, selected_body_config)) + all_meshes = _render_bounds_inputs(results) + bounds = _bounds(all_meshes) if all_meshes else None + render = modules.get("render") + render_errors = [] + if render is not None and bounds is not None: + for case_index, result in enumerate(results): + case_dir = output_path / "cases" / f"case-{case_index:02d}-{result['id']}" + meshes = [result.get("rest")] + [row.get("mesh") for row in result.get("poses", [])] + meshes = [mesh for mesh in meshes if isinstance(mesh, Mapping)] + result["renders"] = [] + for mesh_index, mesh in enumerate(meshes): + status = _visual_status(result, rest_only) + overlays = [] + if mesh_index > 0 and mesh_index - 1 < len(result.get("overlay_points", [])): + overlays = _overlays(result["overlay_points"][mesh_index - 1]) + filename = "rest.png" if mesh_index == 0 else f"pose-{mesh_index:02d}.png" + record = _render_one(render, mesh, case_dir / filename, + str(result["id"]), status, bounds, overlays) + result["renders"].append(record) + if record.get("status") == "exception": + render_errors.append({"case": result["id"], "error": record["exception"]}) + for perturbation_mesh in result.get("perturbation_meshes", []): + if not isinstance(perturbation_mesh, Mapping) or not isinstance(perturbation_mesh.get("mesh"), Mapping): + continue + perturbation_id = _safe_token(perturbation_mesh.get("perturbation_id", "unknown")) + name = _safe_token(perturbation_mesh.get("name", "mesh")) + perturbation_path = case_dir / "perturbations" / perturbation_id / f"{name}.png" + record = _render_one(render, perturbation_mesh["mesh"], perturbation_path, + f"{result['id']} perturbation {perturbation_id} {name}", + _visual_status(result, rest_only, perturbation=True), bounds, []) + result.setdefault("perturbation_renders", []).append({ + "perturbation_id": perturbation_id, "name": name, "record": record, + }) + if record.get("status") == "exception": + render_errors.append({"case": result["id"], + "perturbation": perturbation_id, + "error": record["exception"]}) + post_run_verification: dict[str, Any] = { + "status": "verified", + "scope": "captured source/input, frozen transition/renderer/collision-core, and source adapters", + } + try: + verify(snapshot_path) + except Exception as exc: + post_run_verification = { + "status": "failed", + "scope": "captured source/input, frozen transition/renderer/collision-core, and source adapters", + "type": type(exc).__name__, + "message": str(exc), + } + perturbation_api_available = bool( + modules.get("perturbations") is not None + and callable(getattr(modules["perturbations"], "run_case", None)) + ) + perturbations = _aggregate_perturbations(protocol, results, perturbation_api_available) + overall_status = ("error" if any(item.get("status") == "exception" for item in results) or render_errors + or post_run_verification["status"] == "failed" else + "internal-diagnostic" if rest_only else + "rejected" if any(item.get("status") == "rejected" for item in results) else + "pending" if any(item.get("status") == "pending" for item in results) else + "pending" if perturbations["status"] in ("not-implemented", "unavailable", + "blocked-by-earlier-error") else + "rejected" if perturbations["status"] == "failed" else + "complete") + readiness = _readiness(modules, protocol) + report = { + "schema": "creature-kernel.connected-leg-assembly-run.v1", + "status": overall_status, + "full_pass": (post_run_verification["status"] == "verified" and + not rest_only and perturbations["status"] in ("not-declared", "pass") and + all(item.get("status") == "technical-pass" for item in results)), + "rest_only": rest_only, + "body_config": body_config, + "body_evidence": ( + { + "label": selected_body_config.get("evidence_label"), + "acceptance": selected_body_config.get("acceptance"), + "status": selected_body_config.get("status"), + } + if selected_body_config is not None else None + ), + "case_count": len(results), "cases": results, "shared_bounds": bounds, + "render_errors": render_errors, + "post_run_verification": post_run_verification, + "perturbations": perturbations, + "readiness": readiness, + "body_provisional_protocol": ( + _jsonable(case_protocol.get("body_provisional_evidence")) + if body_source_mode else None + ), + "effective_body_protocol_artifact": ( + "effective-body-protocol.json" if body_source_mode else None + ), + "numerical_checks": "pending" if rest_only or modules.get("checks") is None else "captured", + "pose_checks": "pending" if rest_only or modules.get("checks") is None else "captured", + "inputs_sha256": _sha256_bytes(inputs_raw), "protocol_sha256": _sha256_bytes(protocol_raw), + "limitations": ["Visual acceptance remains pending and is parent-owned.", "No publication, browser, or window launch is performed."], + } + _write_json(output_path / "run-report.json", _jsonable(report)) + files = [] + for path in sorted(output_path.rglob("*"), key=lambda item: item.relative_to(output_path).as_posix().encode("utf-8")): + if path.is_file() and path.name != "artifact-manifest.json": + files.append({"path": path.relative_to(output_path).as_posix(), **_identity(path)}) + _write_json(output_path / "artifact-manifest.json", {"schema": "creature-kernel.connected-leg-assembly-artifacts.v1", "files": files}) + return report + + +def _main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Connected-leg evidence runner") + subparsers = parser.add_subparsers(dest="command", required=True) + prepare_parser = subparsers.add_parser("prepare") + prepare_parser.add_argument("--snapshot", required=True) + prepare_parser.add_argument("--files", nargs="*") + prepare_parser.add_argument("--rest-only", action="store_true") + run_parser = subparsers.add_parser("run") + run_parser.add_argument("--snapshot", required=True) + run_parser.add_argument("--output", required=True) + run_parser.add_argument("--rest-only", action="store_true") + run_parser.add_argument("--body-config") + verify_parser = subparsers.add_parser("verify") + verify_parser.add_argument("--snapshot", required=True) + args = parser.parse_args(argv) + try: + if args.command == "prepare": + prepare(args.snapshot, args.files, args.rest_only) + elif args.command == "verify": + verify(args.snapshot) + else: + report = run(args.snapshot, args.output, args.rest_only, args.body_config) + if report.get("status") in ("error", "rejected"): + return 1 + except Exception as exc: + print(f"runner.py: error: {exc}", file=sys.stderr, flush=True) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(_main()) diff --git a/experiments/connected-leg-assembly/tail-inputs.json b/experiments/connected-leg-assembly/tail-inputs.json new file mode 100644 index 0000000..e6344aa --- /dev/null +++ b/experiments/connected-leg-assembly/tail-inputs.json @@ -0,0 +1,62 @@ +{ + "schema": "creature-kernel.connected-tail-assembly-inputs.v1", + "status": "candidate-inputs-frozen-before-geometry-execution", + "provenance": { + "source_mesh": "current source-built connected-leg L0 from construction.build", + "host_adapter_scope": "explicit local pelvis host adapter; not recovered universal anatomy", + "geometry_changes": "tail constructor only; no source retuning, binder, or tail articulation" + }, + "candidate_policy": { + "initial_candidate_count": 1, + "shared_geometry_correction_budget": 1, + "correction_count_before_execution": 0, + "per_case_repairs": false, + "preserve_rejected_payloads": true + }, + "host_identity": { + "face_index": 58, + "vertex_indices": [41, 44, 66, 63], + "owner": "domain.pelvis", + "identity_source": "current source-built mesh; coordinates and normal derived at build time" + }, + "common_shape": { + "inset_fraction": 0.4, + "collar_distance_m": 0.012, + "station_fractions": [0.0, 0.25, 0.5, 0.75, 1.0], + "ring_count": 5, + "centreline": "cubic Bezier with control distances 0, 1/3, 2/3, 1 of declared length", + "frame_rule": "project global +X onto each path tangent plane; V=X cross tangent; retain source host phase and winding" + }, + "cases": [ + { + "case_id": "calibrated_ordinary_human", + "enabled": false, + "host_identity": { + "face_index": 58, + "vertex_indices": [41, 44, 66, 63], + "owner": "domain.pelvis" + }, + "length": 0.45, + "terminal_direction": [0.0, -0.25, -1.0], + "radii": {"base": 0.035, "middle": 0.045, "tip": 0.008}, + "station_fractions": [0.0, 0.25, 0.5, 0.75, 1.0], + "collar_distance": 0.012, + "binding_controls": {"collar_blend_strength": 0.5} + }, + { + "case_id": "calibrated_upright_anthropomorphic", + "enabled": true, + "host_identity": { + "face_index": 58, + "vertex_indices": [41, 44, 66, 63], + "owner": "domain.pelvis" + }, + "length": 0.45, + "terminal_direction": [0.0, -0.25, -1.0], + "radii": {"base": 0.035, "middle": 0.045, "tip": 0.008}, + "station_fractions": [0.0, 0.25, 0.5, 0.75, 1.0], + "collar_distance": 0.012, + "binding_controls": {"collar_blend_strength": 0.5} + } + ] +} diff --git a/experiments/connected-leg-assembly/tail-stage.md b/experiments/connected-leg-assembly/tail-stage.md new file mode 100644 index 0000000..68c91bb --- /dev/null +++ b/experiments/connected-leg-assembly/tail-stage.md @@ -0,0 +1,203 @@ +# Connected-tail constructor staging + +Status: `implemented`; captured static L2 and visual artifacts are available, +with parent visual review pending and no technology or anatomy outcome + +This is a local constructor experiment for the connected-leg assembly. It is +not a universal anatomy adapter, a tail rig, a source-construction replacement, +or a product/whole-character result. The constructor consumes the current +source-built connected-leg L0 mesh and does not change the binder. + +## Frozen candidate + +The exact candidate is recorded in [tail-inputs.json](tail-inputs.json): one +initial candidate, no correction before execution, and at most one shared +geometry correction if later evidence justifies it. The pinned source host is +face `58`, vertices `[41, 44, 66, 63]`, owner `domain.pelvis`. Its coordinates +and oriented normal are derived from the supplied source-built mesh at build +time; the constructor rejects host identity drift instead of recovering a +different pelvis face. + +The host quad is replaced in its existing face-58 slot by the first inset +annulus quad. The remaining three annulus quads, four-corner tail sides, and +one terminal cap are appended. The original host quad is not retained as an +internal closing face. All inherited vertices and all non-host face slots stay +exact. The five total tail rings use fractions `0, .25, .5, .75, 1`; the +collar is the first translated ring. Inset corners use `C + .4(p-C)` and the +collar translates them outward by `0.012 m`. The frozen candidate uses length +`0.45 m`, declared terminal direction `(0, -.25, -1)` normalized by the +constructor, and base/middle/tip radii `.035/.045/.008 m`. + +Frames use the actual host phase and projected global `+X` on each cubic path +tangent plane, with `V = X cross tangent` and source-compatible winding. Future +tail transition supports are emitted as convex host-quad metadata targeting +the pelvis; weights remain explicitly unimplemented. No tail joint or +articulation is present. The human case is data-disabled and must return its +source mesh exactly; the anthropomorphic case is data-enabled without a +species branch. + +## Reproduction + +The candidate inputs and intended geometry design were frozen before the first +geometry-building test. That preliminary invocation found a mechanical +stencil-index bookkeeping error and produced no candidate result; the minimal +correction used the pre-append vertex count, without changing geometry, +inputs, or dependencies. The corrected code, tests, and inputs were then held +fixed for the final candidate run. The focused managed command is: + +```bash +PYTHONDONTWRITEBYTECODE=1 CK_CURRENT_FORM_SURFACE_PYTHON=/home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot/runtime/bin/python bash /home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot/source/experiments/current-form-surface-preview/surface_preview_launcher.sh -m unittest discover -s experiments/connected-leg-assembly/tests -p test_tail_construction.py -v +``` + +## Result + +The final run completed `6/6` tests with no skips or errors. The disabled human +case returned its source-built mesh exactly. The enabled anthropomorphic case +validated the pinned host identity, in-place face-58 replacement, one-to-many +mapping, unchanged non-host vertices/faces/loops/stencils, five rings, cubic +rear/down frames, cap closure, and convex future-support metadata. Hostile +identity/control cases rejected in memory; no rejected payload was persisted. + +A subsequent metadata-only preservation patch retained the inherited +construction scheme while adding the tail adapter entry; the same six-test +managed suite was rerun and remained green. Host geometry, controls, and +topology were unchanged. + +The original live constructor result contained no integrated capture, rendering, +or L2 evaluation. The later captured static evidence is recorded below and +does not add binding, source retuning, tail articulation, or a +whole-character/anatomy claim. + +## Provenance limitation and follow-up capture + +The original pre-test exact source/dependency/input snapshot was **not +preserved**. The earlier managed runtime path and immutable source references +were not a substitute for that snapshot, and no rendered trial was captured. +Any later capture is post hoc current-state provenance and must not be relabelled +as the original pre-test snapshot. + +The new `captured_tests.py` entrypoint was the required next provenance step. +The initial 008 manifest and captured-test result are retained below; the +allowlist obstacle was resolved for the subsequent 009 capture. + +## Post hoc capture attempt (008) + +The first capture after the historical gap was performed before any further +tail build, test, or render, using the verified copied managed runtime: + +- snapshot: `/home/ben/.cache/creature-kernel/connected-tail-assembly-008-capture` +- manifest: `/home/ben/.cache/creature-kernel/connected-tail-assembly-008-capture/manifest.json` +- result report: `/home/ben/.cache/creature-kernel/connected-tail-assembly-008-capture-report.json` +- runtime: `/home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot/runtime/bin/python` +- captured test: `/home/ben/.cache/creature-kernel/connected-tail-assembly-008-capture/source/experiments/connected-leg-assembly/tests/test_tail_construction.py` + +Capture pre-verification and post-verification passed. The manifest preserved +the admitted frozen construction, dependencies, and mapped calibration inputs. +It did not capture `tail_construction.py` or `tail-inputs.json`: those files +are absent from the current `runner.CAPTURE_FILES` allowlist, and local import +expansion admits only allowlisted files. The captured tail test therefore +returned `failed` before discovery with: +`ModuleNotFoundError: No module named 'tail_construction'`. + +This is a capture-packaging obstacle, not a constructor or geometry result. +No live fallback was run, no captured tail test passed, and no new static L2 +derivation or front/side/rear-three-quarter render was produced. The earlier +live constructor evidence remains unchanged and is not relabelled as captured +evidence. No workaround or recapture was applied to 008. + +## Captured static L2 and visual evidence (009) + +Leibniz's allowlist correction was captured before execution. The captured +focused tail suite then completed `6/6` tests with pre- and post-verification +passed: + +- capture: `/home/ben/.cache/creature-kernel/connected-tail-assembly-009-capture` +- manifest: `/home/ben/.cache/creature-kernel/connected-tail-assembly-009-capture/manifest.json` +- test report: `/home/ben/.cache/creature-kernel/connected-tail-assembly-009-capture-report.json` +- managed runtime: `/home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot/runtime/bin/python` + +The unchanged captured constructor was then evaluated through the captured +connected-leg evaluator at L2 and rendered with the manifest-recorded frozen +renderer. The complete static output is retained at +`/home/ben/.cache/creature-kernel/connected-tail-assembly-009-static-frames-adapter`; +its machine report is `render-report.json` and its artifact inventory is +`artifact-manifest.json`. + +The ordinary-human regression is tail-disabled and produced `264v/248q` at +L0 and `4041v/3968q` at L2. Its matched render contains front, side, and +rear-three-quarter views at 1600x550, plus an underside companion; tail detail +is explicitly unavailable because the feature is disabled. The +anthropomorphic case produced `284v/268q` at L0 and `4361v/4288q` at L2. It +has the same matched views and underside, a context render with three +centreline control-span overlays, and a tail-detail crop using 345 L2 vertices. +All are labelled `CAPTURED STATIC L2 - VISUAL REVIEW PENDING`; no visual +acceptance is claimed. + +The first static derivation attempt is preserved at +`/home/ben/.cache/creature-kernel/connected-tail-assembly-009-static` as a +tool failure: the frozen generic evaluator rejected the constructor's +diagnostic `frames.tail` field because its validator requires exactly +`left/right`, before rendering. The retained 009 static output uses a +memory-only adapter that removes only that non-consumed metadata field before +subdivision; vertices, quads, stencils, inputs, and constructor source are +unchanged. This compatibility limitation is recorded in `render-report.json`. + +Capture 008 remains the earlier failed/incomplete discovery attempt and was +not overwritten. No tail binding, pose, collision, whole-character run, or +geometry revision occurred. + +## Metadata contract closure (010) + +The constructor had already recorded path-frame diagnostics in +`metadata.tail.ring_frames`, but then appended a duplicate `frames.tail` entry +to the root frame mapping. The root `frames` contract is reserved for the +source left/right frames and the frozen evaluator requires exactly those keys. +The correction keeps `frames` equal to the input root frames and stores the +remaining diagnostic fields at `metadata.tail`: `host_normal`, `source_phase`, +`ring_frames`, and `frame_rule`. This is an interface correction only; no +vertices, quads, stencils, inputs, or binding fields changed. + +The corrected source was captured before focused tests or L2 derivation: + +- capture: `/home/ben/.cache/creature-kernel/connected-tail-assembly-010-frame-metadata-capture` +- manifest: `/home/ben/.cache/creature-kernel/connected-tail-assembly-010-frame-metadata-capture/manifest.json` +- test report: `/home/ben/.cache/creature-kernel/connected-tail-assembly-010-frame-metadata-capture-report.json` +- `tail_construction.py` SHA-256: `d2d2a49395ccafd8c752efdfd1482f56a3f3e494a7dd73fa96a78fa07a53cbbe` +- `tests/test_tail_construction.py` SHA-256: `b3bea3a19fa207bd78b8e4efdffb62f22f9b6f09f9fb125c5de71ba7b2098ce0` + +The captured focused suite passed `6/6`, with pre- and post-verification +passed. Direct captured evaluation then proved both cases' L0 geometry and +left/right root frames equal to the saved 009 frames-adapter outputs, and +proved all L2 nonmetadata fields plus root frames equal. The machine record is +`/home/ben/.cache/creature-kernel/connected-tail-assembly-010-frame-metadata-static-identity-replay/geometry-identity.json`. +The L2 geometry hashes are `9ab62ae04825b01908fc44a732ef8a8fac640887973b0765c727a027c08d4702` +(human) and `c4d26df73553736f049e164812dc86791916d00b2cb110c62b1c9031a868f733` +(anthropomorphic); root-frame hashes are respectively +`7075b4fa82de341d5774e9692cb653f75104962896d8b7d935ca316206a2f6e2` and +`703ff29b38949d76f47526cbe995adab8a5584339fabbdfab6456145cc058996`. + +Because the nonmetadata/root-frame identity is exact, the 009 matched, +context, diagnostic, underside, and anthropomorphic tail-detail images were +reused by identity; no unnecessary rerender was performed. The original 009 +raw evaluator failure and the 009 frames-adapter diagnostic derivation remain +preserved at their recorded paths above. + +## Saved-009 rear/overhead measurement view + +One rear/overhead detail view was generated directly from the saved 009 +anthropomorphic L2 mesh, with no construction or geometry rerun: + +- image: `/home/ben/.cache/creature-kernel/connected-tail-assembly-010-rear-overhead-detail/saved-009-L2-tail-rear-overhead.png` +- report: `/home/ben/.cache/creature-kernel/connected-tail-assembly-010-rear-overhead-detail/measurement-report.json` +- image SHA-256: `646737b3dbd1ad949ad32052164183a2243d4b2747af4a2572289f4d874b624b` + +The section uses the baseline middle station `f=0.5`, its four-corner source +support and source tangent frame, then exact intersections of all +`domain.tail` L2 triangles with the perpendicular plane. The source section +is `0.090000000000 m` wide in both X and the other normal V, from declared +middle radius `0.045 m`. The actual L2 section is +`0.077490234375 m` in both axes, half-width `0.0387451171875 m`, or +`0.8610026041666666` of that declared radius, across 78 intersection points; +maximum plane residual is `2.168404344971009e-17 m`. This records equal +X/V contraction at that station, not radius faithfulness or anatomy +acceptance, and does not authorize a shape correction. diff --git a/experiments/connected-leg-assembly/tail_construction.py b/experiments/connected-leg-assembly/tail_construction.py new file mode 100644 index 0000000..99d2bd6 --- /dev/null +++ b/experiments/connected-leg-assembly/tail_construction.py @@ -0,0 +1,461 @@ +"""Bounded connected-tail host adapter for the connected-leg experiment. + +This is intentionally local to the current source-built mesh. It pins one +pelvis host quad, replaces that quad in place with an inset annulus, and +appends a small capped tail. It does not infer a universal pelvis region, +modify the source construction, assign weights, or add a tail joint. +""" +from __future__ import annotations + +from collections.abc import Mapping +import copy +import math +from typing import Any + +import construction + + +_HOST_FACE_INDEX = 58 +_HOST_VERTEX_INDICES = (41, 44, 66, 63) +_HOST_OWNER = "domain.pelvis" +_TAIL_OWNER = "domain.tail" +_INSET_FRACTION = 0.4 +_TAIL_RING_COUNT = 5 +_COORDINATE_TOLERANCE = 1.0e-10 +_NORMAL_TOLERANCE = 1.0e-12 + + +class TailConstructionError(ValueError): + """Raised when the explicit local tail host or candidate is incoherent.""" + + +def _fail(message: str) -> None: + raise TailConstructionError(message) + + +def _mapping(value: Any, where: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping): + _fail(f"{where} must be a mapping") + return value + + +def _number(value: Any, where: str) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float)): + _fail(f"{where} must be a finite number") + result = float(value) + if not math.isfinite(result): + _fail(f"{where} must be a finite number") + return result + + +def _vector(value: Any, where: str) -> tuple[float, float, float]: + if not isinstance(value, (list, tuple)) or len(value) != 3: + _fail(f"{where} must be a three-component vector") + return tuple(_number(item, f"{where}[{index}]") + for index, item in enumerate(value)) # type: ignore[return-value] + + +def _normalise(value: tuple[float, float, float], where: str) -> tuple[float, float, float]: + length = math.sqrt(sum(item * item for item in value)) + if not math.isfinite(length) or length <= _NORMAL_TOLERANCE: + _fail(f"{where} must have positive finite length") + return tuple(item / length for item in value) # type: ignore[return-value] + + +def _add(left: tuple[float, float, float], right: tuple[float, float, float]) -> tuple[float, float, float]: + return tuple(left[index] + right[index] for index in range(3)) # type: ignore[return-value] + + +def _sub(left: tuple[float, float, float], right: tuple[float, float, float]) -> tuple[float, float, float]: + return tuple(left[index] - right[index] for index in range(3)) # type: ignore[return-value] + + +def _scale(value: tuple[float, float, float], factor: float) -> tuple[float, float, float]: + return tuple(factor * item for item in value) # type: ignore[return-value] + + +def _dot(left: tuple[float, float, float], right: tuple[float, float, float]) -> float: + return sum(left[index] * right[index] for index in range(3)) + + +def _cross(left: tuple[float, float, float], right: tuple[float, float, float]) -> tuple[float, float, float]: + return ( + left[1] * right[2] - left[2] * right[1], + left[2] * right[0] - left[0] * right[2], + left[0] * right[1] - left[1] * right[0], + ) + + +def _bezier(control: tuple[tuple[float, float, float], ...], fraction: float) -> tuple[float, float, float]: + one = 1.0 - fraction + terms = (one ** 3, 3.0 * one * one * fraction, + 3.0 * one * fraction * fraction, fraction ** 3) + return tuple(sum(terms[index] * control[index][axis] for index in range(4)) + for axis in range(3)) # type: ignore[return-value] + + +def _bezier_tangent(control: tuple[tuple[float, float, float], ...], fraction: float, + where: str) -> tuple[float, float, float]: + one = 1.0 - fraction + value = tuple( + 3.0 * (one * one * (control[1][axis] - control[0][axis]) + + 2.0 * one * fraction * (control[2][axis] - control[1][axis]) + + fraction * fraction * (control[3][axis] - control[2][axis])) + for axis in range(3) + ) + return _normalise(value, f"{where} tangent") + + +def _project_plus_x(tangent: tuple[float, float, float], where: str) -> tuple[float, float, float]: + world_x = (1.0, 0.0, 0.0) + return _normalise(_sub(world_x, _scale(tangent, _dot(world_x, tangent))), + f"{where} projected +X") + + +def _parse_controls(value: Any) -> dict[str, Any]: + raw = _mapping(value, "tail_inputs") + required = {"case_id", "enabled", "host_identity", "length", + "terminal_direction", "radii", "station_fractions", + "collar_distance", "binding_controls"} + if set(raw) != required: + _fail("tail_inputs has unsupported or missing fields") + if not isinstance(raw["case_id"], str) or not raw["case_id"]: + _fail("tail_inputs.case_id must be a non-empty string") + if type(raw["enabled"]) is not bool: + _fail("tail_inputs.enabled must be a boolean") + host = _mapping(raw["host_identity"], "tail_inputs.host_identity") + if set(host) != {"face_index", "vertex_indices", "owner"}: + _fail("tail_inputs.host_identity has unsupported or missing fields") + if type(host["face_index"]) is not int: + _fail("tail_inputs.host_identity.face_index must be an integer") + vertex_indices = host["vertex_indices"] + if (not isinstance(vertex_indices, (list, tuple)) or + tuple(vertex_indices) != _HOST_VERTEX_INDICES): + _fail("tail_inputs.host_identity.vertex_indices does not match the pinned host") + if host["owner"] != _HOST_OWNER: + _fail("tail_inputs.host_identity.owner does not match the pinned host") + if host["face_index"] != _HOST_FACE_INDEX: + _fail("tail_inputs.host_identity.face_index does not match the pinned host") + length = _number(raw["length"], "tail_inputs.length") + if length <= 0.0: + _fail("tail_inputs.length must be positive") + direction = _normalise(_vector(raw["terminal_direction"], + "tail_inputs.terminal_direction"), + "tail_inputs.terminal_direction") + radii = _mapping(raw["radii"], "tail_inputs.radii") + if set(radii) != {"base", "middle", "tip"}: + _fail("tail_inputs.radii must contain base, middle, and tip") + parsed_radii = {name: _number(radii[name], f"tail_inputs.radii.{name}") + for name in ("base", "middle", "tip")} + if any(radius <= 0.0 for radius in parsed_radii.values()): + _fail("tail_inputs.radii values must be positive") + fractions = raw["station_fractions"] + if (not isinstance(fractions, (list, tuple)) or + len(fractions) != _TAIL_RING_COUNT): + _fail("tail_inputs.station_fractions must contain five fractions") + parsed_fractions = [_number(item, f"tail_inputs.station_fractions[{index}]") + for index, item in enumerate(fractions)] + if (parsed_fractions[0] != 0.0 or parsed_fractions[-1] != 1.0 or + any(left >= right for left, right in zip(parsed_fractions, parsed_fractions[1:]))): + _fail("tail_inputs.station_fractions must increase from 0 to 1") + collar_distance = _number(raw["collar_distance"], "tail_inputs.collar_distance") + if collar_distance <= 0.0: + _fail("tail_inputs.collar_distance must be positive") + binding_controls = _mapping(raw["binding_controls"], + "tail_inputs.binding_controls") + if set(binding_controls) != {"collar_blend_strength"}: + _fail("tail_inputs.binding_controls must contain only collar_blend_strength") + collar_blend_strength = _number( + binding_controls["collar_blend_strength"], + "tail_inputs.binding_controls.collar_blend_strength", + ) + if not 0.0 <= collar_blend_strength <= 1.0: + _fail("tail_inputs.binding_controls.collar_blend_strength must lie in [0, 1]") + return { + "case_id": raw["case_id"], "enabled": raw["enabled"], + "host_identity": { + "face_index": host["face_index"], + "vertex_indices": list(vertex_indices), "owner": host["owner"], + }, + "length": length, "terminal_direction": direction, + "radii": parsed_radii, "station_fractions": parsed_fractions, + "collar_distance": collar_distance, + "binding_controls": { + "collar_blend_strength": collar_blend_strength, + }, + } + + +def _host_data(mesh: Mapping[str, Any], controls: Mapping[str, Any]) -> dict[str, Any]: + vertices = mesh["vertices"] + quads = mesh["quads"] + owners = mesh["face_owners"] + host = controls["host_identity"] + face_index = host["face_index"] + if face_index >= len(quads): + _fail("source-built mesh does not contain the pinned tail host face") + if face_index >= _mapping(mesh["metadata"], "source_mesh.metadata")["root"]["face_count"]: + _fail("pinned tail host face is not in the source root") + original_quad = list(quads[face_index]) + if original_quad != host["vertex_indices"]: + _fail("source-built mesh tail host face vertices do not match the pinned identity") + if owners[face_index] != host["owner"]: + _fail("source-built mesh tail host face owner does not match the pinned identity") + points = [tuple(float(value) for value in vertices[index]) + for index in original_quad] + centre = _scale(tuple(sum(point[axis] for point in points) for axis in range(3)), + 0.25) + raw_normal = _add(_cross(_sub(points[1], points[0]), _sub(points[2], points[0])), + _cross(_sub(points[2], points[0]), _sub(points[3], points[0]))) + normal = _normalise(raw_normal, "pinned tail host normal") + return { + "face_index": face_index, "original_quad": original_quad, + "owner": owners[face_index], "coordinates": [list(point) for point in points], + "centre": list(centre), "normal": list(normal), + } + + +def _radius_at(fraction: float, radii: Mapping[str, float]) -> float: + if fraction <= 0.5: + amount = fraction / 0.5 + return (1.0 - amount) * radii["base"] + amount * radii["middle"] + amount = (fraction - 0.5) / 0.5 + return (1.0 - amount) * radii["middle"] + amount * radii["tip"] + + +def _convex_supports(new_indices: list[int], host_indices: list[int], + source_phase: list[list[int]]) -> dict[str, Any]: + if len(host_indices) != 4 or len(source_phase) != 4: + _fail("tail support derivation requires four host corners and four source phases") + result: dict[str, Any] = {} + for offset, index in enumerate(new_indices): + corner = offset % 4 + weights = [0.15] * 4 + weights[corner] = 0.55 + result[str(index)] = { + "host_vertex_indices": list(host_indices), + "host_corner": corner, + "source_phase": list(source_phase[corner]), + "convex_weights": weights, + "target_joint": "pelvis", + "support_rule": "q=.4*P_i+.6*C; own corner=.55, other corners=.15", + } + return result + + +def build(source_mesh: Mapping[str, Any], tail_inputs: Mapping[str, Any]) -> dict[str, Any]: + """Build one explicit host-58 tail candidate or return a disabled case unchanged.""" + mesh = _mapping(source_mesh, "source_mesh") + construction._validate_mesh(mesh) + controls = _parse_controls(tail_inputs) + if not controls["enabled"]: + return copy.deepcopy(dict(mesh)) + + vertices = copy.deepcopy(mesh["vertices"]) + quads = [list(face) for face in mesh["quads"]] + face_owners = list(mesh["face_owners"]) + control_owners = list(mesh["control_owners"]) + base_stencils = copy.deepcopy(mesh["base_stencils"]) + metadata = copy.deepcopy(dict(_mapping(mesh["metadata"], "source_mesh.metadata"))) + host = _host_data(mesh, controls) + host_indices = host["original_quad"] + points = [tuple(point) for point in host["coordinates"]] + centre = tuple(host["centre"]) + normal = tuple(host["normal"]) + direction = controls["terminal_direction"] + tangent0 = direction + x0 = _project_plus_x(tangent0, "tail host path") + v0 = _normalise(_cross(x0, tangent0), "tail host path ring axis") + if _dot(normal, tangent0) <= _NORMAL_TOLERANCE: + _fail("pinned tail host normal is incompatible with the rear/down path") + + source_phase: list[list[int]] = [] + for corner, point in enumerate(points): + delta = _sub(point, centre) + lateral = _dot(delta, x0) + vertical = _dot(delta, v0) + if abs(lateral) <= _COORDINATE_TOLERANCE or abs(vertical) <= _COORDINATE_TOLERANCE: + _fail(f"pinned tail host corner {corner} has an ambiguous source phase") + source_phase.append([1 if lateral > 0.0 else -1, + 1 if vertical > 0.0 else -1]) + if len({tuple(phase) for phase in source_phase}) != 4: + _fail("pinned tail host does not expose four distinct source phases") + + inset = [_add(centre, _scale(_sub(point, centre), _INSET_FRACTION)) + for point in points] + translation = _scale(normal, controls["collar_distance"]) + collar = [_add(point, translation) for point in inset] + collar_centre = _scale(tuple(sum(point[axis] for point in collar) + for axis in range(3)), 0.25) + length = controls["length"] + terminal = _add(collar_centre, _scale(direction, length)) + control = (collar_centre, + _add(collar_centre, _scale(direction, length / 3.0)), + _add(collar_centre, _scale(direction, 2.0 * length / 3.0)), + terminal) + + original_vertex_count = len(vertices) + collar_indices = [] + for point in collar: + collar_indices.append(len(vertices)) + vertices.append(list(point)) + control_owners.append(_TAIL_OWNER) + ring_indices = [collar_indices] + ring_frames = [{ + "fraction": 0.0, + "centre": list(collar_centre), + "tangent": list(tangent0), "X": list(x0), "V": list(v0), + "radius": None, "source_phase": copy.deepcopy(source_phase), + }] + tail_new_indices = list(collar_indices) + for fraction in controls["station_fractions"][1:]: + centre_at = _bezier(control, fraction) + tangent = _bezier_tangent(control, fraction, f"tail station {fraction}") + x_axis = _project_plus_x(tangent, f"tail station {fraction}") + v_axis = _normalise(_cross(x_axis, tangent), + f"tail station {fraction} ring axis") + radius = _radius_at(fraction, controls["radii"]) + ring = [] + for lateral_phase, vertical_phase in source_phase: + point = _add(centre_at, + _add(_scale(x_axis, lateral_phase * radius), + _scale(v_axis, vertical_phase * radius))) + index = len(vertices) + vertices.append(list(point)) + control_owners.append(_TAIL_OWNER) + ring.append(index) + tail_new_indices.append(index) + ring_indices.append(ring) + ring_frames.append({ + "fraction": fraction, "centre": list(centre_at), + "tangent": list(tangent), "X": list(x_axis), "V": list(v_axis), + "radius": radius, "source_phase": copy.deepcopy(source_phase), + }) + + annulus_faces = [] + for corner in range(4): + next_corner = (corner + 1) % 4 + annulus_faces.append([ + host_indices[corner], host_indices[next_corner], + collar_indices[next_corner], collar_indices[corner], + ]) + tail_faces = [] + for source_ring, target_ring in zip(ring_indices, ring_indices[1:]): + for corner in range(4): + next_corner = (corner + 1) % 4 + tail_faces.append([ + source_ring[corner], source_ring[next_corner], + target_ring[next_corner], target_ring[corner], + ]) + cap_face = list(ring_indices[-1]) + original_face_count = len(quads) + quads[_HOST_FACE_INDEX] = annulus_faces[0] + face_owners[_HOST_FACE_INDEX] = _TAIL_OWNER + for face in annulus_faces[1:] + tail_faces + [cap_face]: + quads.append(face) + face_owners.append(_TAIL_OWNER) + for index in range(original_vertex_count, len(vertices)): + base_stencils.append([[index, 1.0]]) + + new_face_indices = [_HOST_FACE_INDEX] + list( + range(original_face_count, len(quads))) + annulus_face_indices = [_HOST_FACE_INDEX] + list( + range(original_face_count, original_face_count + len(annulus_faces) - 1)) + tail_face_start = original_face_count + len(annulus_faces) - 1 + tail_face_indices = list(range(tail_face_start, + tail_face_start + len(tail_faces))) + cap_face_index = tail_face_start + len(tail_faces) + + index_mapping = copy.deepcopy(dict( + _mapping(metadata.get("index_mapping", {}), "source_mesh.metadata.index_mapping") + )) + root_face_count = _mapping(metadata["root"], "source_mesh.metadata.root")["face_count"] + index_mapping["root_face_mappings_excluding_tail_host"] = [ + [index, index] for index in range(root_face_count) if index != _HOST_FACE_INDEX + ] + index_mapping["tail_new_vertices"] = list(tail_new_indices) + index_mapping["tail_new_faces"] = list(new_face_indices) + index_mapping["tail_face_replacement"] = { + "original_face_index": _HOST_FACE_INDEX, + "original_quad": list(host_indices), + "replacement_face_indices": list(annulus_face_indices), + "one_to_many": [[_HOST_FACE_INDEX, *annulus_face_indices]], + "original_host_retained": False, + } + metadata["index_mapping"] = index_mapping + old_base_owners = list(metadata.get("base_control_owners", [])) + if len(old_base_owners) != len(mesh["vertices"]): + _fail("source_mesh metadata base_control_owners does not cover the source vertices") + metadata["base_control_owners"] = old_base_owners + [_TAIL_OWNER] * len(tail_new_indices) + metadata["base_vertex_count"] = len(vertices) + metadata["tail"] = { + "owner": _TAIL_OWNER, + "enabled": True, + "host": { + **host, + "inset_fraction": _INSET_FRACTION, + "inset_corners": [list(point) for point in inset], + "collar_vertices": [list(point) for point in collar], + "collar_translation": list(translation), + "collar_distance": controls["collar_distance"], + "source_phase": copy.deepcopy(source_phase), + }, + "source_host_identity": copy.deepcopy(controls["host_identity"]), + "ring_indices": copy.deepcopy(ring_indices), + "ring_frames": ring_frames, + "host_normal": list(normal), + "source_phase": copy.deepcopy(source_phase), + "frame_rule": "project global +X onto each cubic tangent plane; V=X cross tangent", + "station_fractions": list(controls["station_fractions"]), + "centreline": { + "kind": "cubic_bezier", + "control_points": [list(point) for point in control], + "terminal_direction": list(direction), + "length": length, + }, + "radii": copy.deepcopy(controls["radii"]), + "new_vertex_indices": list(tail_new_indices), + "new_face_indices": list(new_face_indices), + "annulus_face_indices": list(annulus_face_indices), + "tail_face_indices": list(tail_face_indices), + "cap_face_index": cap_face_index, + "face_replacement": copy.deepcopy(index_mapping["tail_face_replacement"]), + "transition_weights": { + "status": "binding_declared_no_tail_joint", + "future_target_joint": "pelvis", + "collar_blend_strength": controls["binding_controls"]["collar_blend_strength"], + "support_rule": "q=.4*P_i+.6*C; own corner=.55, other corners=.15", + "supports": _convex_supports( + tail_new_indices, host_indices, source_phase + ), + }, + } + scheme = copy.deepcopy(dict(_mapping(metadata.get("scheme", {}), + "source_mesh.metadata.scheme"))) + scheme["tail_adapter"] = { + "adapter": "explicit pinned host-58 pelvis tail; not universal anatomy", + "host_face_replacement": "replace slot 58 with first annulus face; append remaining annulus, tail sides, and cap", + "root_geometry_preservation": "all inherited vertices and every non-host face remain exact", + "tail_ring_count": _TAIL_RING_COUNT, + "tail_joint": "not implemented", + "binding": "pelvis-only transition; no tail joint", + } + metadata["scheme"] = scheme + + output = { + "schema": "creature-kernel.connected-tail-assembly-mesh.v1", + "level": mesh.get("level", 0), + "vertices": vertices, + "quads": quads, + "face_owners": face_owners, + "control_owners": control_owners, + "loops": copy.deepcopy(mesh["loops"]), + "base_stencils": base_stencils, + "frames": copy.deepcopy(dict(mesh["frames"])), + "metadata": metadata, + } + construction._validate_mesh(output) + return output + + +__all__ = ["TailConstructionError", "build"] diff --git a/experiments/connected-leg-assembly/tests/test_arm_construction.py b/experiments/connected-leg-assembly/tests/test_arm_construction.py new file mode 100644 index 0000000..34fcd58 --- /dev/null +++ b/experiments/connected-leg-assembly/tests/test_arm_construction.py @@ -0,0 +1,177 @@ +"""Focused tests for the initial connected coarse-arm candidate.""" +from __future__ import annotations + +import copy +import hashlib +import json +import math +from pathlib import Path +import sys +import unittest + + +HERE = Path(__file__).resolve().parents[1] +if str(HERE) not in sys.path: + sys.path.insert(0, str(HERE)) + +import arm_construction # noqa: E402 +import checks # noqa: E402 +import collision_broadphase # noqa: E402 +import construction # noqa: E402 + + +INPUTS = json.loads((HERE / "inputs.json").read_text(encoding="utf-8")) +ARM_INPUTS = json.loads((HERE / "arm-inputs.json").read_text(encoding="utf-8")) +EXPECTED = ("calibrated_ordinary_human", "calibrated_upright_anthropomorphic") + + +def _sha(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def _load_reference(row, name): + ref = row[name] + path = Path(ref["path"]) + if _sha(path) != ref["sha256"]: + raise AssertionError(f"immutable {name} identity drifted: {path}") + return json.loads(path.read_text(encoding="utf-8")) + + +def _cases(): + arm_rows = {row["case_id"]: row["sides"] for row in ARM_INPUTS["cases"]} + result = [] + for row in INPUTS["cases"]: + if row["id"] not in EXPECTED: + continue + root = _load_reference(row, "root_mesh") + source = _load_reference(row, "original_case") + base = construction.build(root, row["leg_inputs"]) + arms = arm_construction.build(base, source, arm_rows[row["id"]]) + levels = arm_construction.evaluate(arms, levels=2) + result.append((row["id"], base, source, arm_rows[row["id"]], arms, levels)) + if tuple(row[0] for row in result) != EXPECTED: + raise AssertionError("canonical arm cases were not loaded") + return result + + +def _triangles(quads): + return [triangle for face in quads + for triangle in ((face[0], face[1], face[2]), (face[0], face[2], face[3]))] + + +class ArmConstructionTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cases = _cases() + + def test_actual_cases_evaluate_with_complete_stencils(self): + self.assertEqual(len(self.cases), 2) + for case_id, base, _source, _inputs, arms, levels in self.cases: + with self.subTest(case=case_id): + self.assertEqual(len(arms["vertices"]), len(base["vertices"]) + 178) + self.assertEqual(len(arms["quads"]), len(base["quads"]) + 184) + self.assertEqual([level["metadata"]["level"] for level in levels], [0, 1, 2]) + for level in levels: + self.assertEqual(len(level["base_stencils"]), len(level["vertices"])) + for stencil in level["base_stencils"]: + self.assertAlmostEqual(sum(float(term[1]) for term in stencil), 1.0, places=9) + self.assertTrue(all(term[1] > 0.0 for term in stencil)) + + def test_prefix_closure_and_source_owned_port(self): + for _case_id, base, source, _inputs, arms, _levels in self.cases: + self.assertEqual(arms["vertices"][:len(base["vertices"])], base["vertices"]) + self.assertEqual(arms["quads"][:len(base["quads"])], base["quads"]) + self.assertNotIn("port.left_arm", arms["loops"]) + self.assertNotIn("port.right_arm", arms["loops"]) + for side in ("left", "right"): + row = arms["metadata"]["arms"][side] + components = source["components"] + J = [components[f"shoulders.{side}.arm_origin.{axis}"] for axis in "xyz"] + self.assertEqual(row["J"], J) + self.assertEqual(row["J_source"], f"shoulders.{side}.arm_origin") + self.assertTrue(row["collar"]["exact_port_translation"]) + self.assertEqual(len(row["source_port"]["section_frame_phase"]), 8) + self.assertEqual(len(row["new_vertex_indices"]), 89) + self.assertEqual(len(row["new_face_indices"]), 92) + + def test_stale_source_origin_rejects_instead_of_becoming_duplicate_J(self): + _case_id, base, source, inputs, _arms, _levels = self.cases[0] + changed = copy.deepcopy(source) + changed["components"]["shoulders.left.arm_origin.x"] -= 0.001 + with self.assertRaisesRegex(arm_construction.ArmConstructionError, "does not own"): + arm_construction.build(base, changed, inputs) + self.assertNotIn("J", inputs["left"]) + + def test_frames_are_right_handed_front_facing_and_mirrored(self): + for tangent in ((-1.0, -1.0e-10, 1.0e-10), + (1.0, -1.0e-10, 1.0e-10)): + frame = arm_construction._frame(tangent) + t, u, f = frame["tangent"], frame["U"], frame["F"] + cross = arm_construction._cross(t, u) + self.assertGreater(sum(cross[i] * f[i] for i in range(3)), 1.0 - 1.0e-7) + self.assertGreaterEqual(f[2], 0.0) + self.assertAlmostEqual(sum(t[i] * u[i] for i in range(3)), 0.0, places=8) + for _case_id, _base, _source, _inputs, arms, _levels in self.cases: + left = arms["metadata"]["arms"]["left"]["sections"][0]["frame"] + right = arms["metadata"]["arms"]["right"]["sections"][0]["frame"] + self.assertLess(left["tangent"][0], 0.0) + self.assertGreater(right["tangent"][0], 0.0) + self.assertGreaterEqual(left["F"][2], 0.0) + self.assertGreaterEqual(right["F"][2], 0.0) + + def test_collar_distance_and_upper_length_use_source_J(self): + for _case_id, _base, _source, _inputs, arms, _levels in self.cases: + for side in ("left", "right"): + row = arms["metadata"]["arms"][side] + J, P, E = row["J"], row["P"], row["E"] + C = row["collar"]["centre"] + distance = lambda a, b: math.sqrt(sum((a[i] - b[i]) ** 2 for i in range(3))) + self.assertAlmostEqual(distance(C, P), 0.6 * distance(P, J), places=10) + self.assertAlmostEqual(row["bone_lengths"]["upper_J_E"], distance(J, E), places=12) + self.assertAlmostEqual(row["bone_lengths"]["visible_P_E"], distance(P, E), places=12) + self.assertGreater(row["bone_lengths"]["upper_J_E"], row["bone_lengths"]["visible_P_E"]) + + def test_E_W_radii_and_hand_length_have_independent_geometric_response(self): + _case_id, base, source, inputs, baseline, _levels = self.cases[0] + mutations = (("E", 1, -0.007, "elbow"), ("W", 2, 0.006, "wrist")) + for field, axis, delta, section in mutations: + changed = copy.deepcopy(inputs) + changed["left"][field][axis] += delta + output = arm_construction.build(base, source, changed) + before = next(row for row in baseline["metadata"]["arms"]["left"]["sections"] if row["name"] == section) + after = next(row for row in output["metadata"]["arms"]["left"]["sections"] if row["name"] == section) + self.assertAlmostEqual(after["centre"][axis] - before["centre"][axis], delta, places=12) + changed = copy.deepcopy(inputs) + changed["left"]["radii"]["forearm"][0] += 0.004 + output = arm_construction.build(base, source, changed) + before = next(row for row in baseline["metadata"]["arms"]["left"]["sections"] if row["name"] == "forearm_belly") + after = next(row for row in output["metadata"]["arms"]["left"]["sections"] if row["name"] == "forearm_belly") + self.assertAlmostEqual(after["radii_up_forward"][0] - before["radii_up_forward"][0], 0.004, places=12) + changed = copy.deepcopy(inputs) + changed["left"]["hand_length"] += 0.010 + output = arm_construction.build(base, source, changed) + before = baseline["metadata"]["arms"]["left"]["cap"]["centre"] + after = output["metadata"]["arms"]["left"]["cap"]["centre"] + self.assertAlmostEqual(math.sqrt(sum((after[i] - before[i]) ** 2 for i in range(3))), 0.010, places=10) + + def test_actual_L2_has_no_quad_folds_or_intersections_by_existing_checkers(self): + for case_id, _base, _source, _inputs, _arms, levels in self.cases: + mesh = levels[2] + dots = [] + for face in mesh["quads"]: + first = checks._triangle_normal(mesh["vertices"], (face[0], face[1], face[2])) + second = checks._triangle_normal(mesh["vertices"], (face[0], face[2], face[3])) + denominator = checks._norm(first) * checks._norm(second) + dots.append(checks._dot(first, second) / denominator if denominator > 0.0 else -1.0) + with self.subTest(case=case_id, check="fold"): + self.assertGreater(min(dots), 0.0) + collision = collision_broadphase.collision_report(mesh["vertices"], _triangles(mesh["quads"])) + with self.subTest(case=case_id, check="collision"): + self.assertTrue(collision["available"]) + self.assertTrue(collision["pair_partition_complete"]) + self.assertTrue(collision["final_classification_partition_complete"]) + self.assertEqual(collision["intersection_hit_count"], 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/connected-leg-assembly/tests/test_binding.py b/experiments/connected-leg-assembly/tests/test_binding.py new file mode 100644 index 0000000..f10e4fe --- /dev/null +++ b/experiments/connected-leg-assembly/tests/test_binding.py @@ -0,0 +1,890 @@ +from __future__ import annotations + +import copy +import json +import sys +import unittest +from pathlib import Path + +import numpy as np + + +EXPERIMENT_DIR = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(EXPERIMENT_DIR)) +import binding # noqa: E402 +import arm_construction # noqa: E402 +import construction # noqa: E402 +import head_construction # noqa: E402 + + +ROOT_COUNT = 152 +STATION_NAMES = ("mid_thigh", "knee_pre_support", "knee", "knee_post_support", "calf", "ankle_approach", "ankle") +INPUTS = json.loads((EXPERIMENT_DIR / "inputs.json").read_text(encoding="utf-8")) +ARM_INPUTS = json.loads((EXPERIMENT_DIR / "arm-inputs.json").read_text(encoding="utf-8")) +HEAD_INPUTS = json.loads((EXPERIMENT_DIR / "head-inputs.json").read_text(encoding="utf-8")) +ARM_CASE_IDS = ("calibrated_ordinary_human", "calibrated_upright_anthropomorphic") + + +def _angles(left_hip=0.0, left_knee=0.0, right_hip=0.0, right_knee=0.0): + return { + "left": {"hip": left_hip, "knee": left_knee, "ankle": 0.0}, + "right": {"hip": right_hip, "knee": right_knee, "ankle": 0.0}, + } + + +def _arm_angles(left_hip=0.0, left_knee=0.0, right_hip=0.0, right_knee=0.0, + left_raise=0.0, left_forward=0.0, left_elbow=0.0, + right_raise=0.0, right_forward=0.0, right_elbow=0.0): + return { + "left": {"hip": left_hip, "knee": left_knee, + "shoulder_raise": left_raise, + "shoulder_forward": left_forward, "elbow": left_elbow}, + "right": {"hip": right_hip, "knee": right_knee, + "shoulder_raise": right_raise, + "shoulder_forward": right_forward, "elbow": right_elbow}, + } + + +def _head_angles(yaw=0.0, nod=0.0): + return { + "left": {"hip": 0.0, "knee": 0.0, "ankle": 0.0}, + "right": {"hip": 0.0, "knee": 0.0, "ankle": 0.0}, + "head": {"yaw": yaw, "nod": nod}, + } + + +def _fixture(nonzero_rest_shank: bool = False): + root_vertices = [ + [float(index % 19) * 0.01, 1.0 + float(index // 19) * 0.01, + float(index % 3) * 0.02] + for index in range(ROOT_COUNT) + ] + root_quads = [[4 * index + slot for slot in range(4)] + for index in range(ROOT_COUNT // 4)] + left_j = [-0.5, 1.0, 0.0] + left_t = [-0.5, 0.9, 0.0] + left_k = [-0.5, 0.0, 0.0] + right_j = [0.5, 1.0, 0.0] + right_t = [0.5, 0.9, 0.0] + right_k = [0.5, 0.0, 0.0] + left_a = [-0.5, -0.8, 0.4] if nonzero_rest_shank else [-0.5, -1.0, 0.0] + right_a = [0.5, -0.8, -0.4] if nonzero_rest_shank else [0.5, -1.0, 0.0] + legs = { + "left": {"J": left_j, "T": left_t, "K": left_k, "A": left_a, + "mid_thigh_factor": 0.85, "support_fraction": 0.1}, + "right": {"J": right_j, "T": right_t, "K": right_k, "A": right_a, + "mid_thigh_factor": 0.85, "support_fraction": 0.1}, + } + + vertices = copy.deepcopy(root_vertices) + rings = {"left": [], "right": []} + for side, sign in (("left", -1.0), ("right", 1.0)): + j, t, k, a = (np.asarray(legs[side][name], dtype=float) + for name in ("J", "T", "K", "A")) + centres = (t + 0.70 * (k - t), t + 0.90 * (k - t), k, + k + 0.12 * (a - k), k + 0.35 * (a - k), + k + 0.72 * (a - k), a) + for station_index, centre in enumerate(centres): + ring = list(range(len(vertices), len(vertices) + 8)) + rings[side].append(ring) + for corner in range(8): + # The small ring is synthetic; its mean is the declared + # station point and it uses metres/Y-up/Z-front coordinates. + lateral = 0.02 if corner & 1 else -0.02 + depth = 0.015 if corner & 2 else -0.015 + vertical = 0.015 if corner & 4 else -0.015 + vertices.append((centre + [lateral * sign, vertical, depth]).tolist()) + + all_quads = copy.deepcopy(root_quads) + for side in ("left", "right"): + for ring in rings[side]: + all_quads.append(ring[:4]) + chains = {} + for side in ("left", "right"): + centres = (np.asarray(legs[side]["T"], dtype=float) + + 0.70 * (np.asarray(legs[side]["K"], dtype=float) - + np.asarray(legs[side]["T"], dtype=float)), + np.asarray(legs[side]["T"], dtype=float) + + 0.90 * (np.asarray(legs[side]["K"], dtype=float) - + np.asarray(legs[side]["T"], dtype=float)), + np.asarray(legs[side]["K"], dtype=float), + np.asarray(legs[side]["K"], dtype=float) + + 0.12 * (np.asarray(legs[side]["A"], dtype=float) - + np.asarray(legs[side]["K"], dtype=float)), + np.asarray(legs[side]["K"], dtype=float) + + 0.35 * (np.asarray(legs[side]["A"], dtype=float) - + np.asarray(legs[side]["K"], dtype=float)), + np.asarray(legs[side]["K"], dtype=float) + + 0.72 * (np.asarray(legs[side]["A"], dtype=float) - + np.asarray(legs[side]["K"], dtype=float)), + np.asarray(legs[side]["A"], dtype=float)) + sections = [{"name": name, "path": "T_to_K" if index < 3 else "K_to_A", + "fraction": (0.70, 0.90, 1.0, 0.12, 0.35, 0.72, 1.0)[index], + "indices": copy.deepcopy(ring), "centre": centre.tolist(), + "order": index} + for index, (name, ring, centre) in enumerate( + zip(STATION_NAMES, rings[side], centres))] + chains[side] = { + "sections": sections, + "ring_order": list(STATION_NAMES), + "ring_indices_by_name": {section["name"]: copy.deepcopy(section["indices"]) + for section in sections}, + "new_vertex_indices": [index for ring in rings[side] for index in ring], + } + base = { + "schema": "synthetic-connected-leg-l0", + "level": 0, + "vertices": vertices, + "quads": all_quads, + "metadata": { + "root": {"vertex_count": ROOT_COUNT, "face_count": len(root_quads)}, + "index_mapping": { + "root_vertex_old_to_new": [[index, index] for index in range(ROOT_COUNT)], + "root_face_old_to_new": [[index, index] for index in range(len(root_quads))], + }, + "chains": chains, + }, + } + rest = { + "schema": "synthetic-connected-leg-l2", + "level": 2, + "vertices": copy.deepcopy(vertices), + "quads": copy.deepcopy(all_quads), + "base_stencils": [[[index, 1.0]] for index in range(len(vertices))], + "metadata": {"source": "synthetic-rest"}, + } + prior_root = { + "schema": "synthetic-prior-root-l0", + "level": 0, + "vertices": copy.deepcopy(root_vertices), + "quads": copy.deepcopy(root_quads), + } + prior_weights = [] + for index in range(ROOT_COUNT): + if index % 3 == 0: + prior_weights.append([0.6, 0.4, 0.0]) + elif index % 3 == 1: + prior_weights.append([0.2, 0.0, 0.8]) + else: + prior_weights.append([1.0, 0.0, 0.0]) + prior_binding = { + "schema": "creature-kernel.pelvis-hip-articulation-binding.v1", + "base_weights": prior_weights, + } + return base, rest, prior_root, prior_binding, legs + + +def _bound(nonzero_rest_shank: bool = False): + values = _fixture(nonzero_rest_shank) + return binding.bind(*values), values + + +def _foot_fixture(): + base, rest, prior_root, prior_binding, legs = _fixture() + foot_points = { + "left": [ + [-0.54, -1.10, -0.08], [-0.46, -1.10, -0.08], + [-0.54, -1.10, 0.08], [-0.46, -1.10, 0.08], + [-0.50, -1.12, 0.16], + ], + "right": [ + [0.46, -1.10, -0.08], [0.54, -1.10, -0.08], + [0.46, -1.10, 0.08], [0.54, -1.10, 0.08], + [0.50, -1.12, 0.16], [0.50, -1.14, 0.24], + ], + } + foot_indices = {} + for side in ("left", "right"): + indices = [] + for point in foot_points[side]: + indices.append(len(base["vertices"])) + base["vertices"].append(list(point)) + foot_indices[side] = indices + base["metadata"]["feet"] = { + side: {"new_vertex_indices": copy.deepcopy(indices)} + for side, indices in foot_indices.items() + } + for side, indices in foot_indices.items(): + base["quads"].extend([ + indices[:4], indices[1:5], + ]) + rest["vertices"] = copy.deepcopy(base["vertices"]) + rest["quads"] = copy.deepcopy(base["quads"]) + rest["base_stencils"] = [ + [[index, 1.0]] for index in range(len(rest["vertices"])) + ] + mixed_index = foot_indices["left"][1] + root_index = 0 + rest["base_stencils"][mixed_index] = [ + [root_index, 0.25], [mixed_index, 0.75], + ] + return base, rest, prior_root, prior_binding, legs + + +def _foot_bound(): + values = _foot_fixture() + return binding.bind(*values), values + + +def _tail_fixture(): + base, rest, prior_root, prior_binding, legs = _fixture() + host_face = 2 + host_vertices = copy.deepcopy(prior_root["quads"][host_face]) + source_phase = [[-1, -1], [-1, 1], [1, 1], [1, -1]] + tail_indices = list(range(len(base["vertices"]), len(base["vertices"]) + 8)) + for point in ( + [0.0, 0.5, -0.05], [0.05, 0.5, -0.05], + [0.05, 0.55, -0.05], [0.0, 0.55, -0.05], + [0.0, 0.25, -0.15], [0.04, 0.25, -0.15], + [0.04, 0.29, -0.15], [0.0, 0.29, -0.15], + ): + base["vertices"].append(point) + ring0, ring1 = tail_indices[:4], tail_indices[4:] + base["quads"][host_face] = [host_vertices[0], host_vertices[1], ring0[1], ring0[0]] + base["quads"].extend([ + [host_vertices[1], host_vertices[2], ring0[2], ring0[1]], + [host_vertices[2], host_vertices[3], ring0[3], ring0[2]], + [host_vertices[3], host_vertices[0], ring0[0], ring0[3]], + [ring0[0], ring0[1], ring1[1], ring1[0]], + [ring0[1], ring0[2], ring1[2], ring1[1]], + [ring0[2], ring0[3], ring1[3], ring1[2]], + [ring0[3], ring0[0], ring1[0], ring1[3]], + ring1, + ]) + supports = { + str(index): { + "host_vertex_indices": copy.deepcopy(host_vertices), + "host_corner": index % 4, + "source_phase": copy.deepcopy(source_phase[index % 4]), + "convex_weights": [ + 0.55 if slot == index % 4 else 0.15 + for slot in range(4) + ], + "target_joint": "pelvis", + } + for index in tail_indices + } + kept_faces = [[index, index] for index in range(len(prior_root["quads"])) + if index != host_face] + replacement_faces = [host_face, len(prior_root["quads"]), + len(prior_root["quads"]) + 1, + len(prior_root["quads"]) + 2] + base["metadata"]["index_mapping"]["root_face_mappings_excluding_tail_host"] = kept_faces + base["metadata"]["tail"] = { + "enabled": True, + "source_host_identity": { + "face_index": host_face, + "vertex_indices": copy.deepcopy(host_vertices), + "owner": "domain.pelvis", + }, + "face_replacement": { + "original_face_index": host_face, + "original_quad": copy.deepcopy(host_vertices), + "replacement_face_indices": replacement_faces, + "one_to_many": [[host_face, *replacement_faces]], + "original_host_retained": False, + }, + "ring_indices": [ring0, ring1], + "station_fractions": [0.0, 1.0], + "source_phase": source_phase, + "host": {"source_phase": copy.deepcopy(source_phase)}, + "new_vertex_indices": tail_indices, + "transition_weights": { + "status": "implemented", + "collar_blend_strength": 0.5, + "future_target_joint": "pelvis", + "supports": supports, + }, + } + rest["vertices"] = copy.deepcopy(base["vertices"]) + rest["quads"] = copy.deepcopy(base["quads"]) + rest["base_stencils"] = [ + [[index, 1.0]] for index in range(len(rest["vertices"])) + ] + return base, rest, prior_root, prior_binding, legs + + +def _tail_bound(): + values = _tail_fixture() + return binding.bind(*values), values + + +def _actual_arm_cases(): + arm_rows = {row["case_id"]: row["sides"] for row in ARM_INPUTS["cases"]} + cases = [] + for row in INPUTS["cases"]: + if row["id"] not in ARM_CASE_IDS: + continue + root = json.loads(Path(row["root_mesh"]["path"]).read_text(encoding="utf-8")) + source = json.loads(Path(row["original_case"]["path"]).read_text(encoding="utf-8")) + prior_binding = json.loads(Path(row["prior_hip_binding"]["path"]).read_text(encoding="utf-8")) + base = construction.build(root, row["leg_inputs"]) + arm_mesh = arm_construction.build(base, source, arm_rows[row["id"]]) + levels = arm_construction.evaluate(arm_mesh, levels=2) + bound = binding.bind(arm_mesh, levels[2], root, prior_binding, row["leg_inputs"]) + cases.append((row["id"], root, arm_mesh, levels[2], prior_binding, bound)) + if tuple(case[0] for case in cases) != ARM_CASE_IDS: + raise AssertionError("canonical arm cases were not loaded") + return cases + + +def _actual_head_cases(with_arms=False): + head_rows = {row["case_id"]: row["head"] for row in HEAD_INPUTS["cases"]} + cases = [] + for row in INPUTS["cases"]: + if row["id"] not in ARM_CASE_IDS: + continue + root = json.loads(Path(row["root_mesh"]["path"]).read_text(encoding="utf-8")) + source = json.loads(Path(row["original_case"]["path"]).read_text(encoding="utf-8")) + prior_binding = json.loads(Path(row["prior_hip_binding"]["path"]).read_text(encoding="utf-8")) + base = construction.build(root, row["leg_inputs"]) + if with_arms: + arm_rows = {item["case_id"]: item["sides"] for item in ARM_INPUTS["cases"]} + base = arm_construction.build(base, source, arm_rows[row["id"]]) + head_mesh = head_construction.build(base, source, head_rows[row["id"]]) + levels = head_construction.evaluate(head_mesh, levels=2) + bound = binding.bind(head_mesh, levels[2], root, prior_binding, row["leg_inputs"]) + cases.append((row["id"], root, source, head_mesh, levels[2], prior_binding, bound)) + if tuple(case[0] for case in cases) != ARM_CASE_IDS: + raise AssertionError("canonical head cases were not loaded") + return cases + + +class BindingTests(unittest.TestCase): + def test_root_weight_preservation_and_five_column_mapping(self) -> None: + bound, (_base, _rest, _prior_root, prior_binding, _legs) = _bound() + prior = np.asarray(prior_binding["base_weights"]) + actual = np.asarray(bound["base_weights"][:ROOT_COUNT]) + expected = np.column_stack((prior[:, 0], prior[:, 1], + np.zeros(ROOT_COUNT), prior[:, 2], + np.zeros(ROOT_COUNT))) + np.testing.assert_array_equal(actual, expected) + self.assertEqual(bound["joint_order"], + ["pelvis", "left_hip", "left_knee", + "right_hip", "right_knee"]) + self.assertEqual(bound["weight_columns"], + ["pelvis", "left_thigh", "left_shank", + "right_thigh", "right_shank"]) + self.assertNotIn("foot_vertex_indices", bound) + for side in ("left", "right"): + actual_centres = bound["station_points"][side] + sections = _base["metadata"]["chains"][side]["sections"] + metadata_centres = [section["centre"] for section in sections] + self.assertEqual(actual_centres, metadata_centres) + + def test_stencil_propagation_produces_all_five_columns(self) -> None: + base, rest, prior_root, prior_binding, legs = _fixture() + rest["base_stencils"][-1] = [[0, 0.25], [152, 0.75]] + bound = binding.bind(base, rest, prior_root, prior_binding, legs) + expected = (0.25 * np.asarray(bound["base_weights"][0]) + + 0.75 * np.asarray(bound["base_weights"][152])) + np.testing.assert_allclose(bound["evaluated_weights"][-1], expected) + self.assertEqual(len(bound["evaluated_weights"][-1]), 5) + json.dumps(bound) + + def test_hierarchy_records_nonzero_rest_shank_angle(self) -> None: + bound, _values = _bound(nonzero_rest_shank=True) + points = binding.joint_points(bound, _angles()) + left_local = np.asarray(points["left"]["knee"]["rest_local"]) + self.assertFalse(np.allclose(left_local[:3, :3], np.eye(3))) + np.testing.assert_allclose(points["left"]["posed_K"], + points["left"]["rest_K"]) + + def test_rest_pose_is_identity_and_preserves_topology(self) -> None: + bound, (_base, rest, _prior_root, _prior_binding, _legs) = _bound() + posed = binding.pose(rest, bound, _angles()) + self.assertEqual(posed["vertices"], rest["vertices"]) + self.assertEqual(posed["quads"], rest["quads"]) + self.assertEqual(posed["base_stencils"], rest["base_stencils"]) + self.assertEqual(posed["metadata"]["representation"], "pose") + self.assertFalse(posed["metadata"]["posed_cage_evaluation"]) + points = binding.joint_points(bound, _angles()) + for side in ("left", "right"): + np.testing.assert_array_equal(points[side]["thigh"]["skin_matrix"], np.eye(4)) + np.testing.assert_array_equal(points[side]["knee"]["skin_matrix"], np.eye(4)) + + def test_parent_hip_carries_knee_when_knee_angle_is_zero(self) -> None: + bound, _values = _bound(nonzero_rest_shank=True) + points = binding.joint_points(bound, _angles(left_hip=30.0)) + left = points["left"] + np.testing.assert_allclose(left["posed_K_from_parent"], + left["posed_K_from_knee"], atol=1.0e-10) + np.testing.assert_allclose(left["posed_A"], + (np.asarray(left["thigh"]["skin_matrix"]) @ + np.r_[left["rest_A"], 1.0])[:3], + atol=1.0e-10) + + def test_positive_knee_angle_moves_ankle_back_in_negative_z(self) -> None: + bound, _values = _bound() + points = binding.joint_points(bound, _angles(left_knee=30.0)) + self.assertLess(points["left"]["posed_A"][2], 0.0) + np.testing.assert_allclose(points["left"]["posed_K"], + points["left"]["rest_K"], atol=1.0e-10) + + def test_mirrored_inputs_have_mirrored_pose_response(self) -> None: + bound, _values = _bound() + points = binding.joint_points( + bound, _angles(left_hip=20.0, left_knee=25.0, + right_hip=20.0, right_knee=25.0) + ) + left = np.asarray(points["left"]["posed_A"]) + right = np.asarray(points["right"]["posed_A"]) + np.testing.assert_allclose(left, [-right[0], right[1], right[2]], atol=1.0e-10) + + def test_invalid_inputs_are_rejected(self) -> None: + base, rest, prior_root, prior_binding, legs = _fixture() + wrong_root = copy.deepcopy(base) + wrong_root["vertices"][0][0] += 1.0e-6 + with self.assertRaises(ValueError): + binding.bind(wrong_root, rest, prior_root, prior_binding, legs) + + negative_prior = copy.deepcopy(prior_binding) + negative_prior["base_weights"][0] = [-0.1, 1.1, 0.0] + with self.assertRaises(ValueError): + binding.bind(base, rest, prior_root, negative_prior, legs) + + missing_chain = copy.deepcopy(base) + missing_chain["metadata"] = {} + with self.assertRaises(ValueError): + binding.bind(missing_chain, rest, prior_root, prior_binding, legs) + + degenerate_leg = copy.deepcopy(legs) + degenerate_leg["left"]["J"] = copy.deepcopy(degenerate_leg["left"]["K"]) + with self.assertRaises(ValueError): + binding.bind(base, rest, prior_root, prior_binding, degenerate_leg) + + bad_stencil = copy.deepcopy(rest) + bad_stencil["base_stencils"][0] = [[0, 0.5]] + with self.assertRaises(ValueError): + binding.bind(base, bad_stencil, prior_root, prior_binding, legs) + + bound, _ = _bound() + tampered = copy.deepcopy(bound) + tampered["evaluated_weights"][0][0] = -0.1 + with self.assertRaises(ValueError): + binding.pose(rest, tampered, _angles()) + + nonzero_ankle = _angles() + nonzero_ankle["left"]["ankle"] = 1.0 + with self.assertRaises(ValueError): + binding.pose(rest, bound, nonzero_ankle) + + def test_weight_guard_recovers_baseline_roundoff_without_relaxing_real_bounds(self) -> None: + one_ulp_over = np.nextafter(1.0, 2.0) + binding._check_weight_bounds( + np.asarray([[one_ulp_over, 0.0, 0.0]], dtype=float), + "one_ulp", + ) + with self.assertRaises(ValueError): + binding._check_weight_bounds( + np.asarray([[1.0 + 2.0 * binding._TOLERANCE, 0.0, 0.0]], dtype=float), + "real_upper", + ) + with self.assertRaises(ValueError): + binding._check_weight_bounds( + np.asarray([[-2.0 * binding._TOLERANCE, 1.0 + 2.0 * binding._TOLERANCE, 0.0]], dtype=float), + "real_lower", + ) + with self.assertRaises(ValueError): + binding._check_weight_bounds( + np.asarray([[0.5, 0.4, 0.0]], dtype=float), + "partition", + ) + + def test_explicit_feet_use_semantic_indices_and_preserve_zero_pose(self) -> None: + bound, (base, rest, _prior_root, _prior_binding, _legs) = _foot_bound() + feet = base["metadata"]["feet"] + for side in ("left", "right"): + indices = feet[side]["new_vertex_indices"] + self.assertEqual(bound["foot_vertex_indices"][side], indices) + column = 2 if side == "left" else 4 + for index in indices: + np.testing.assert_array_equal( + bound["base_weights"][index], + [0.0, 0.0, 1.0, 0.0, 0.0] if column == 2 + else [0.0, 0.0, 0.0, 0.0, 1.0], + ) + posed = binding.pose(rest, bound, _angles()) + self.assertEqual(posed["vertices"], rest["vertices"]) + self.assertEqual(posed["quads"], rest["quads"]) + self.assertEqual(posed["base_stencils"], rest["base_stencils"]) + + def test_feet_follow_existing_hierarchical_hip_and_knee_without_ankle_joint(self) -> None: + bound, (base, rest, _prior_root, _prior_binding, _legs) = _foot_bound() + angles = _angles(left_hip=25.0, left_knee=30.0) + posed = binding.pose(rest, bound, angles) + points = binding.joint_points(bound, angles) + left_index = base["metadata"]["feet"]["left"]["new_vertex_indices"][0] + right_index = base["metadata"]["feet"]["right"]["new_vertex_indices"][0] + knee_skin = np.asarray(points["left"]["knee"]["skin_matrix"]) + expected = (knee_skin @ np.r_[rest["vertices"][left_index], 1.0])[:3] + np.testing.assert_allclose(posed["vertices"][left_index], expected) + self.assertFalse(np.array_equal(posed["vertices"][left_index], + rest["vertices"][left_index])) + np.testing.assert_array_equal(posed["vertices"][right_index], + rest["vertices"][right_index]) + self.assertNotIn("ankle", bound["joint_order"]) + + def test_feet_partition_and_full_l2_stencil_transfer_preserve_existing_l0_weights(self) -> None: + baseline, _baseline_values = _bound() + bound, (base, rest, _prior_root, _prior_binding, _legs) = _foot_bound() + baseline_count = len(baseline["base_weights"]) + np.testing.assert_array_equal( + np.asarray(bound["base_weights"][:baseline_count]), + np.asarray(baseline["base_weights"]), + ) + base_weights = np.asarray(bound["base_weights"]) + evaluated = np.asarray(bound["evaluated_weights"]) + np.testing.assert_array_equal(base_weights.sum(axis=1), np.ones(len(base_weights))) + np.testing.assert_allclose(evaluated.sum(axis=1), np.ones(len(evaluated))) + mixed_index = base["metadata"]["feet"]["left"]["new_vertex_indices"][1] + expected = (0.25 * np.asarray(bound["base_weights"][0]) + + 0.75 * np.asarray(bound["base_weights"][mixed_index])) + np.testing.assert_allclose(bound["evaluated_weights"][mixed_index], expected) + self.assertEqual(len(rest["base_stencils"]), len(rest["vertices"])) + + def test_hostile_foot_metadata_is_rejected(self) -> None: + base, rest, prior_root, prior_binding, legs = _foot_fixture() + feet = base["metadata"]["feet"] + hostile = { + "duplicate_within_side": lambda value: value["left"]["new_vertex_indices"].__setitem__( + 1, value["left"]["new_vertex_indices"][0]), + "overlap_between_sides": lambda value: value["right"]["new_vertex_indices"].__setitem__( + 0, value["left"]["new_vertex_indices"][0]), + "root_vertex_overwrite": lambda value: value["left"]["new_vertex_indices"].__setitem__(0, 0), + "leg_vertex_overwrite": lambda value: value["left"]["new_vertex_indices"].__setitem__( + 0, base["metadata"]["chains"]["left"]["sections"][0]["indices"][0]), + "non_integer_id": lambda value: value["left"]["new_vertex_indices"].__setitem__(0, True), + "incomplete_coverage": lambda value: value["right"]["new_vertex_indices"].pop(), + "out_of_range_id": lambda value: value["right"]["new_vertex_indices"].__setitem__( + 0, len(base["vertices"])), + } + for name, mutate in hostile.items(): + with self.subTest(name=name): + candidate = copy.deepcopy(base) + mutate(candidate["metadata"]["feet"]) + with self.assertRaises(ValueError): + binding.bind(candidate, rest, prior_root, prior_binding, legs) + + def test_tail_transition_uses_declared_host_support_and_distal_pelvis(self) -> None: + bound, (base, rest, _prior_root, _prior_binding, _legs) = _tail_bound() + tail = base["metadata"]["tail"] + self.assertEqual(bound["tail_vertex_indices"], tail["new_vertex_indices"]) + self.assertNotIn("tail", bound["joint_order"]) + weights = np.asarray(bound["base_weights"], dtype=float) + self.assertTrue(np.allclose(weights.sum(axis=1), 1.0, atol=1.0e-12)) + for index in tail["ring_indices"][-1]: + np.testing.assert_array_equal(weights[index], [1.0, 0.0, 0.0, 0.0, 0.0]) + host = tail["source_host_identity"]["vertex_indices"] + expected_support = sum( + coefficient * weights[index] + for index, coefficient in zip(host, [0.55, 0.15, 0.15, 0.15]) + ) + collar = tail["ring_indices"][0][0] + expected_collar = 0.5 * expected_support + 0.5 * np.asarray( + [1.0, 0.0, 0.0, 0.0, 0.0] + ) + np.testing.assert_allclose(weights[collar], expected_collar, atol=1.0e-12) + evaluated = np.asarray(bound["evaluated_weights"], dtype=float) + np.testing.assert_allclose(evaluated, weights, atol=1.0e-12) + self.assertEqual(len(rest["base_stencils"]), len(rest["vertices"])) + + def test_tail_requires_explicit_collar_blend_strength(self) -> None: + values = _tail_fixture() + del values[0]["metadata"]["tail"]["transition_weights"]["collar_blend_strength"] + with self.assertRaisesRegex(ValueError, "collar_blend_strength"): + binding.bind(*values) + + def test_tail_uniform_centroid_support_is_rejected(self) -> None: + values = _tail_fixture() + support = values[0]["metadata"]["tail"]["transition_weights"]["supports"]["264"] + support["convex_weights"] = [0.25, 0.25, 0.25, 0.25] + with self.assertRaisesRegex(ValueError, "inset-corner rule"): + binding.bind(*values) + + def test_tail_host_correspondence_is_explicit_and_hostile_mapping_is_rejected(self) -> None: + mutations = { + "wrong_kept_target": lambda candidate: candidate["metadata"]["index_mapping"] + ["root_face_mappings_excluding_tail_host"].__setitem__(0, [0, 1]), + "wrong_replacement_host": lambda candidate: candidate["metadata"]["tail"] + ["face_replacement"].__setitem__("original_face_index", 3), + "original_host_retained": lambda candidate: candidate["metadata"]["tail"] + ["face_replacement"].__setitem__("original_host_retained", True), + } + for name, mutate in mutations.items(): + with self.subTest(name=name): + values = list(_tail_fixture()) + mutate(values[0]) + with self.assertRaises(ValueError): + binding.bind(*values) + + def test_harmonic_root_graph_uses_supplied_original_faces(self) -> None: + base, _rest, prior_root, _prior_binding, _legs = _fixture() + base["metadata"]["root"]["face_count"] = 1 + modified_prefix = copy.deepcopy(base["quads"]) + modified_prefix[0] = [0, 1, 2, 4] + graph, _metadata = binding._root_edge_graph( + base, modified_prefix, {}, prior_root["quads"][:1], + ) + self.assertIn(3, graph[0]) + self.assertNotIn(4, graph[0]) + + +class ArmBindingTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cases = _actual_arm_cases() + + def test_actual_root_graph_has_semantic_free_and_seed_regions(self): + for case_id, _root, arm_mesh, _rest, _prior, bound in self.cases: + with self.subTest(case=case_id): + influence = bound["metadata"]["arm_root_influence"] + self.assertGreater(influence["thigh_neighbourhood_count"], 0) + for side in ("left", "right"): + row = influence["per_side"][side] + self.assertEqual(row["D0_count"], 8) + self.assertEqual(row["D1_count"], 8) + self.assertEqual(row["free_count"], 16) + self.assertEqual(row["seed_count"], 10) + self.assertEqual(row["collar_anchor_value"], 1.0) + self.assertEqual(row["D2_anchor_value"], 0.0) + self.assertEqual(len(influence["connections"][side]), 8) + self.assertEqual(set(row["D0"]), set(arm_mesh["metadata"]["arms"][side]["source_port"]["indices"])) + self.assertEqual(influence["bilateral_shared_D2"], []) + + def test_root_arm_field_preserves_old_ratios_and_is_nine_column(self): + for case_id, _root, _arm_mesh, _rest, prior_binding, bound in self.cases: + with self.subTest(case=case_id): + self.assertEqual(bound["joint_order"], [ + "pelvis", "left_hip", "left_knee", "right_hip", "right_knee", + "left_shoulder", "left_elbow", "right_shoulder", "right_elbow", + ]) + self.assertEqual(bound["weight_columns"], [ + "pelvis", "left_thigh", "left_shank", "right_thigh", "right_shank", + "left_upper_arm", "left_forearm", "right_upper_arm", "right_forearm", + ]) + prior = np.asarray(prior_binding["base_weights"], dtype=float) + actual = np.asarray(bound["base_weights"], dtype=float) + influence = bound["metadata"]["arm_root_influence"] + for side, upper_column in (("left", 5), ("right", 7)): + free = influence["fields"][side] + for index, value in free.items(): + old = np.asarray([ + prior[index, 0], prior[index, 1], 0.0, + prior[index, 2], 0.0, + ]) + np.testing.assert_allclose(actual[index, :5], old * (1.0 - value), atol=1.0e-12) + self.assertAlmostEqual(actual[index, upper_column], value, places=12) + self.assertEqual(actual[index, 6 if side == "left" else 8], 0.0) + non_arm = set(range(ROOT_COUNT)) - set(influence["fields"]["left"]) - set(influence["fields"]["right"]) + for index in non_arm: + np.testing.assert_array_equal(actual[index, 5:], np.zeros(4)) + np.testing.assert_allclose(actual.sum(axis=1), np.ones(len(actual))) + + def test_arm_appendage_blend_anchors_and_free_elbow_are_semantic(self): + for case_id, _root, arm_mesh, _rest, _prior, bound in self.cases: + with self.subTest(case=case_id): + for side in ("left", "right"): + row = arm_mesh["metadata"]["arms"][side] + blends = {int(index): value for index, value in bound["arm_elbow_blend"][side].items()} + sections = {section["name"]: section["indices"] for section in row["sections"]} + for index in row["collar"]["indices"] + sections["upper_belly"] + sections["pre_elbow"]: + self.assertEqual(blends[index], 0.0) + for index in sections["post_elbow"] + sections["forearm_belly"] + sections["pre_wrist"] + sections["wrist"] + sections["palm"] + sections["knuckle"] + sections["terminal"] + [row["cap"]["vertex"]]: + self.assertEqual(blends[index], 1.0) + for index in sections["elbow"]: + self.assertGreater(blends[index], 0.0) + self.assertLess(blends[index], 1.0) + self.assertEqual(bound["metadata"]["arm_weighting"]["elbow"], + "free arm-appendage harmonic blend") + + def test_source_bone_pivot_frames_and_zero_pose_identity(self): + for case_id, _root, arm_mesh, rest, _prior, bound in self.cases: + with self.subTest(case=case_id): + posed = binding.pose(rest, bound, _arm_angles()) + self.assertEqual(posed["vertices"], rest["vertices"]) + self.assertEqual(posed["quads"], rest["quads"]) + self.assertEqual(posed["base_stencils"], rest["base_stencils"]) + for side in ("left", "right"): + source = arm_mesh["metadata"]["arms"][side] + frames = bound["rest_frames"][side] + shoulder = binding._arm_frame(source["J"], source["E"], f"{side} test shoulder") + elbow = binding._arm_frame(source["E"], source["W"], f"{side} test elbow") + np.testing.assert_array_equal( + frames["shoulder"]["rest_global"], shoulder["rest_global"]) + np.testing.assert_array_equal( + frames["elbow"]["rest_global"], elbow["rest_global"]) + self.assertEqual( + frames["arm_source_points"]["frame_source"], + "source J->E and E->W bones; not construction P->E/E->W sections", + ) + self.assertEqual( + frames["arm_source_points"]["pose_rotation_order"], + "shoulder Rz(side_sign*shoulder_raise) @ Rx(-shoulder_forward); elbow Rx(-elbow)", + ) + + def test_arm_frame_accepts_near_horizontal_bones_and_rejects_vertical_projection(self): + for distal in ([1.0, -1.0e-12, 0.0], [-1.0, -1.0e-12, 0.0]): + frame = binding._arm_frame([0.0, 0.0, 0.0], distal, "near-horizontal") + rotation = np.asarray(frame["rotation"]) + np.testing.assert_allclose(rotation.T @ rotation, np.eye(3), atol=1.0e-10) + self.assertGreater(np.linalg.det(rotation), 0.0) + self.assertGreaterEqual(rotation[2, 2], 0.0) + with self.assertRaisesRegex(ValueError, "global \+Y projection"): + binding._arm_frame([0.0, 0.0, 0.0], [0.0, -1.0, 0.0], "vertical") + + def test_unilateral_and_bilateral_modest_arm_poses_have_independent_endpoint_checks(self): + for case_id, _root, _arm_mesh, rest, _prior, bound in self.cases: + with self.subTest(case=case_id): + unilateral = _arm_angles(left_raise=15.0, left_forward=10.0, + left_elbow=25.0) + points = binding.joint_points(bound, unilateral) + for side in ("left", "right"): + side_points = points[side] + shoulder_skin = np.asarray(side_points["shoulder"]["skin_matrix"]) + elbow_skin = np.asarray(side_points["elbow"]["skin_matrix"]) + J = np.r_[side_points["rest_arm_J"], 1.0] + E = np.r_[side_points["rest_arm_E"], 1.0] + W = np.r_[side_points["rest_arm_W"], 1.0] + np.testing.assert_allclose(side_points["posed_arm_J"], (shoulder_skin @ J)[:3], atol=1.0e-10) + np.testing.assert_allclose(side_points["posed_arm_E"], (shoulder_skin @ E)[:3], atol=1.0e-10) + np.testing.assert_allclose(side_points["posed_arm_E"], (elbow_skin @ E)[:3], atol=1.0e-10) + np.testing.assert_allclose(side_points["posed_arm_W"], (elbow_skin @ W)[:3], atol=1.0e-10) + self.assertFalse(np.allclose(points["left"]["posed_arm_W"], points["left"]["rest_arm_W"])) + np.testing.assert_allclose(points["right"]["posed_arm_J"], points["right"]["rest_arm_J"], atol=1.0e-10) + + rest_points = binding.joint_points(bound, _arm_angles()) + raise_points = binding.joint_points( + bound, _arm_angles(left_raise=15.0, right_raise=15.0)) + forward_points = binding.joint_points( + bound, _arm_angles(left_forward=10.0, right_forward=10.0)) + elbow_points = binding.joint_points( + bound, _arm_angles(left_elbow=25.0, right_elbow=25.0)) + for side in ("left", "right"): + self.assertGreater(raise_points[side]["posed_arm_E"][1], + rest_points[side]["rest_arm_E"][1]) + self.assertGreater(forward_points[side]["posed_arm_E"][2], + rest_points[side]["rest_arm_E"][2]) + self.assertGreater(elbow_points[side]["posed_arm_W"][2], + rest_points[side]["rest_arm_W"][2]) + bilateral = _arm_angles(left_raise=15.0, left_forward=10.0, + left_elbow=25.0, right_raise=15.0, + right_forward=10.0, right_elbow=25.0) + mirrored = binding.joint_points(bound, bilateral) + for name in ("posed_arm_J", "posed_arm_E", "posed_arm_W"): + left = np.asarray(mirrored["left"][name]) + right = np.asarray(mirrored["right"][name]) + np.testing.assert_allclose(left, [-right[0], right[1], right[2]], atol=1.0e-10) + + +class HeadBindingTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cases = _actual_head_cases() + cls.arm_head_cases = _actual_head_cases(with_arms=True) + + def test_source_owned_neck_pivot_is_not_the_neck_upper_port(self): + for case_id, _root, source, head_mesh, _rest, _prior, bound in self.cases: + with self.subTest(case=case_id): + metadata = head_mesh["metadata"]["head"] + handoff = metadata["binding_handoff"] + expected = [source["components"][f"stations.neck_collar.C.{axis}"] + for axis in "xyz"] + upper = [source["components"][f"stations.neck_upper.C.{axis}"] + for axis in "xyz"] + self.assertEqual(handoff["pivot_source"], "stations.neck_collar.C") + self.assertEqual(bound["rest_frames"]["head"]["J"], expected) + self.assertEqual(bound["rest_frames"]["head"]["pivot_source"], + "stations.neck_collar.C") + self.assertNotEqual(expected, upper) + self.assertEqual(bound["metadata"]["head_weighting"]["neck_upper_port_is_pivot"], + False) + + def test_head_six_column_partition_stencils_and_preserved_root_ratios(self): + for case_id, _root, _source, head_mesh, rest, prior_binding, bound in self.cases: + with self.subTest(case=case_id): + self.assertEqual(bound["joint_order"], [ + "pelvis", "left_hip", "left_knee", "right_hip", "right_knee", "neck", + ]) + self.assertEqual(bound["weight_columns"], [ + "pelvis", "left_thigh", "left_shank", "right_thigh", "right_shank", "neck", + ]) + base_weights = np.asarray(bound["base_weights"], dtype=float) + evaluated = np.asarray(bound["evaluated_weights"], dtype=float) + np.testing.assert_allclose(base_weights.sum(axis=1), 1.0, atol=1.0e-12) + np.testing.assert_allclose(evaluated.sum(axis=1), 1.0, atol=1.0e-12) + self.assertEqual(len(evaluated), len(rest["vertices"])) + self.assertEqual(len(rest["base_stencils"]), len(rest["vertices"])) + head_indices = set(bound["head_vertex_indices"]) + neck_index = bound["weight_columns"].index("neck") + for index in head_indices: + expected = np.zeros(6) + expected[neck_index] = 1.0 + np.testing.assert_array_equal(base_weights[index], expected) + + prior = np.asarray(prior_binding["base_weights"], dtype=float) + old = np.column_stack((prior[:, 0], prior[:, 1], np.zeros(152), + prior[:, 2], np.zeros(152))) + influence = bound["head_root_influence"] + modified = set(influence["per_root"]["D0"]) | set(influence["per_root"]["D1"]) + for index in range(152): + if index in modified: + h = influence["field"][str(index)] if str(index) in influence["field"] else influence["field"][index] + np.testing.assert_allclose(base_weights[index, :5], old[index] * (1.0 - h), atol=1.0e-12) + self.assertAlmostEqual(base_weights[index, 5], h, places=12) + else: + np.testing.assert_array_equal(base_weights[index], np.r_[old[index], 0.0]) + + def test_head_identity_yaw_nod_endpoint_directions_and_hierarchy(self): + for case_id, _root, _source, _head_mesh, rest, _prior, bound in self.cases: + with self.subTest(case=case_id): + identity = binding.pose(rest, bound, _head_angles()) + self.assertEqual(identity["vertices"], rest["vertices"]) + self.assertEqual(identity["quads"], rest["quads"]) + self.assertEqual(identity["base_stencils"], rest["base_stencils"]) + self.assertEqual(bound["parents"]["neck"], "pelvis") + self.assertIn("neck", bound["joints"]) + + yaw = binding.joint_points(bound, _head_angles(yaw=10.0))["head"] + self.assertGreater(yaw["posed_forward_direction"][0], 0.0) + self.assertAlmostEqual(yaw["posed_forward_direction"][1], 0.0, places=12) + nod = binding.joint_points(bound, _head_angles(nod=10.0))["head"] + self.assertLess(nod["posed_forward_direction"][1], 0.0) + self.assertAlmostEqual(nod["posed_forward_direction"][0], 0.0, places=12) + self.assertEqual(yaw["pose_rotation_order"], "Ry(yaw) @ Rx(nod)") + + def test_head_transition_reports_no_shoulder_overlap_and_preserves_arm_layout(self): + for case_id, _root, _source, head_mesh, rest, _prior, bound in self.arm_head_cases: + with self.subTest(case=case_id): + self.assertEqual(len(bound["joint_order"]), 10) + self.assertEqual(bound["joint_order"][-1], "neck") + self.assertEqual(bound["weight_columns"][-1], "neck") + self.assertEqual(bound["head_root_influence"]["per_root"]["shoulder_overlap"], []) + evaluated = np.asarray(bound["evaluated_weights"], dtype=float) + self.assertEqual(len(evaluated), len(rest["vertices"])) + np.testing.assert_allclose(evaluated.sum(axis=1), 1.0, atol=1.0e-12) + neck_column = bound["weight_columns"].index("neck") + for index in bound["head_vertex_indices"]: + # L2 boundary stencils may blend the connected root seam; + # the semantic L0 appendage allocation is the one-hot + # contract, while L2 must preserve complete partitioning. + self.assertEqual(bound["base_weights"][index][neck_column], 1.0) + self.assertEqual(head_mesh["metadata"]["head"]["binding_handoff"]["joint"], + "neck_head") + + def test_neck_handoff_rejects_missing_or_wrong_source_pivot(self): + case_id, root, _source, head_mesh, rest, prior, _bound = self.cases[0] + leg_inputs = next(row["leg_inputs"] for row in INPUTS["cases"] + if row["id"] == case_id) + for replacement in (None, "stations.neck_upper.C"): + candidate = copy.deepcopy(head_mesh) + if replacement is None: + del candidate["metadata"]["head"]["binding_handoff"]["pivot_source"] + else: + candidate["metadata"]["head"]["binding_handoff"]["pivot_source"] = replacement + with self.assertRaises(ValueError): + binding.bind(candidate, rest, root, prior, leg_inputs) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/connected-leg-assembly/tests/test_captured_tests.py b/experiments/connected-leg-assembly/tests/test_captured_tests.py new file mode 100644 index 0000000..aecfa50 --- /dev/null +++ b/experiments/connected-leg-assembly/tests/test_captured_tests.py @@ -0,0 +1,152 @@ +"""Focused mocked tests for the capture-before-test entrypoint.""" +from __future__ import annotations + +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + + +HERE = Path(__file__).resolve().parents[1] +if str(HERE) not in sys.path: + sys.path.insert(0, str(HERE)) + +import captured_tests # noqa: E402 + + +class CapturedTestsEntrypointTests(unittest.TestCase): + def _fixture(self, root: Path, *, returncode: int = 0): + snapshot = root / "snapshot" + captured = snapshot / "arbitrary-layout" / "selected_case.py" + managed = root / "managed-python" + managed.write_text("runtime", encoding="utf-8") + managed.chmod(0o755) + logical = "tests/selected_case.py" + manifest = { + "source": {"files": [{ + "path": logical, + "snapshot_path": str(captured), + }]}, + "runtime": {"executable": str(managed)}, + "limitations": ["existing capture limitation"], + } + events = [] + + fake_runner = mock.Mock() + fake_runner.CAPTURE_FILES = ("runner.py", "root_source.py", "hip_source.py") + + def prepare(path, file_names): + events.append("prepare") + self.assertEqual(Path(path), snapshot) + self.assertIn("captured_tests.py", file_names) + self.assertIn(logical, file_names) + captured.parent.mkdir(parents=True) + captured.write_text("import unittest\nunittest.main()\n", encoding="utf-8") + (snapshot / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8") + return manifest + + def verify(_path): + events.append("verify") + return manifest + + def invoke(command, **kwargs): + events.append("test") + return subprocess.CompletedProcess(command, returncode, "selected stdout", "selected stderr") + + fake_runner.prepare.side_effect = prepare + fake_runner.verify.side_effect = verify + return snapshot, logical, fake_runner, invoke, events + + def test_uses_manifest_path_and_verifies_before_and_after_selected_test(self): + with tempfile.TemporaryDirectory() as directory: + snapshot, logical, fake_runner, invoke, events = self._fixture(Path(directory)) + report = captured_tests.run_captured_tests( + snapshot, logical, + ["ChosenTests.test_one"], + runner_module=fake_runner, process_run=invoke) + self.assertEqual(report["status"], "passed") + self.assertEqual(events, ["prepare", "verify", "test", "verify"]) + self.assertIn("arbitrary-layout/selected_case.py", report["captured_test_path"]) + self.assertEqual(report["selected_tests"], ["ChosenTests.test_one"]) + self.assertEqual(report["preverify"], "passed") + self.assertEqual(report["postverify"], "passed") + + def test_nonzero_selected_test_is_failed_but_snapshot_is_postverified(self): + with tempfile.TemporaryDirectory() as directory: + snapshot, logical, fake_runner, invoke, events = self._fixture( + Path(directory), returncode=1) + report = captured_tests.run_captured_tests( + snapshot, logical, + runner_module=fake_runner, process_run=invoke) + self.assertEqual(report["status"], "failed") + self.assertEqual(report["test"]["returncode"], 1) + self.assertEqual(events[-1], "verify") + self.assertEqual(report["postverify"], "passed") + + def test_postverify_failure_overrides_successful_test(self): + with tempfile.TemporaryDirectory() as directory: + snapshot, logical, fake_runner, invoke, events = self._fixture(Path(directory)) + original_verify = fake_runner.verify.side_effect + calls = 0 + + def verify(path): + nonlocal calls + calls += 1 + if calls == 2: + events.append("verify") + raise ValueError("captured drift") + return original_verify(path) + + fake_runner.verify.side_effect = verify + report = captured_tests.run_captured_tests( + snapshot, logical, + runner_module=fake_runner, process_run=invoke) + self.assertEqual(report["status"], "failed") + self.assertEqual(report["postverify"], "failed") + self.assertEqual(report["postverify_error"]["message"], "captured drift") + + def test_manifest_venv_symlink_is_retained_as_invocation_path(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + snapshot, logical, fake_runner, _invoke, events = self._fixture(root) + target = root / "system-python" + target.write_text("runtime target", encoding="utf-8") + target.chmod(0o755) + recorded = root / "venv" / "bin" / "python" + recorded.parent.mkdir(parents=True) + recorded.symlink_to(target) + manifest = fake_runner.prepare.side_effect(snapshot, [ + *fake_runner.CAPTURE_FILES, "captured_tests.py", logical]) + manifest["runtime"]["executable"] = str(recorded) + fake_runner.prepare.side_effect = lambda _path, file_names: manifest + fake_runner.verify.side_effect = lambda _path: manifest + invoked = [] + + def invoke(command, **_kwargs): + invoked.append(command) + return subprocess.CompletedProcess(command, 0, "", "") + + report = captured_tests.run_captured_tests( + snapshot, logical, + runner_module=fake_runner, process_run=invoke) + self.assertTrue(recorded.is_symlink()) + self.assertNotEqual(recorded, recorded.resolve()) + self.assertEqual(report["managed_python"], str(recorded)) + self.assertEqual(invoked[0][0], str(recorded)) + + def test_rejects_unsafe_paths_and_selector_flags_before_capture(self): + fake_runner = mock.Mock() + with self.assertRaises(captured_tests.CapturedTestError): + captured_tests.run_captured_tests("/tmp/unused", "../test.py", + runner_module=fake_runner) + with self.assertRaises(captured_tests.CapturedTestError): + captured_tests.run_captured_tests("/tmp/unused", "tests/test.py", + ["-k"], runner_module=fake_runner) + fake_runner.prepare.assert_not_called() + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/connected-leg-assembly/tests/test_checks.py b/experiments/connected-leg-assembly/tests/test_checks.py new file mode 100644 index 0000000..4d26fbf --- /dev/null +++ b/experiments/connected-leg-assembly/tests/test_checks.py @@ -0,0 +1,1346 @@ +import copy +import importlib.util +import json +import math +import os +import sys +import unittest +from unittest import mock +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +SPEC = importlib.util.spec_from_file_location("connected_leg_checks", ROOT / "checks.py") +CHECKS = importlib.util.module_from_spec(SPEC) +sys.modules[SPEC.name] = CHECKS +SPEC.loader.exec_module(CHECKS) +BINDING_SPEC = importlib.util.spec_from_file_location("connected_leg_binding_for_checks", ROOT / "binding.py") +BINDING = importlib.util.module_from_spec(BINDING_SPEC) +sys.modules[BINDING_SPEC.name] = BINDING +BINDING_SPEC.loader.exec_module(BINDING) + + +def identity(): + return [[1.0 if row == column else 0.0 for column in range(4)] for row in range(4)] + + +def protocol(prior_face_count=0): + return {"checks": { + "minimum_edge_over_scale": 1e-8, + "minimum_triangle_area_over_scale_squared": 1e-10, + "weight_partition_tolerance": 1e-9, + "independent_lbs_tolerance": 1e-9, + "identity_position_tolerance": 1e-9, + "lower_edge_strain_ratio": [0.5, 2.0], + "lower_triangle_area_ratio": [0.4, 2.5], + "lower_normal_dot_min": 0.0, + "prior_face_count": prior_face_count, + "boundary_loop_names": ["neck", "arm.left", "arm.right", "ankle.left", "ankle.right"], + }} + + +def leg_inputs(): + return { + "left": {"J": [-0.1, 0.0, 0.0], "T": [-0.12, -0.05, 0.0], + "K": [-0.08, -0.4, 0.03], "A": [-0.08, -0.7, -0.08]}, + "right": {"J": [0.1, 0.0, 0.0], "T": [0.12, -0.05, 0.0], + "K": [0.08, -0.4, 0.03], "A": [0.08, -0.7, -0.08]}, + } + + +def binding_for(vertices, weights=None, inputs=None): + inputs = copy.deepcopy(inputs if inputs is not None else leg_inputs()) + source_rows, points = CHECKS._source_joint_rows(inputs) + joints = {name: {"rest_matrix": source_rows[name]["rest"], + "inverse_bind_matrix": source_rows[name]["inverse_bind"]} + for name in CHECKS._JOINTS} + frames = {} + for side in ("left", "right"): + thigh_rest = source_rows[f"{side}_hip"]["rest"] + knee_rest = source_rows[f"{side}_knee"]["rest"] + frames[side] = { + **copy.deepcopy(points[side]), + "thigh": {"rest_global": thigh_rest}, + "knee": {"rest_global": knee_rest, + "rest_local": CHECKS._mm(CHECKS._inverse(thigh_rest), knee_rest)}, + } + return { + "joint_order": list(BINDING._JOINT_ORDER), + "weight_columns": list(BINDING._WEIGHT_COLUMNS), + "joints": joints, + "parents": {"pelvis": None, "left_hip": "pelvis", "left_knee": "left_hip", + "right_hip": "pelvis", "right_knee": "right_hip"}, + "rest_frames": frames, + "leg_inputs": inputs, + "evaluated_weights": copy.deepcopy( + weights if weights is not None else + [[1.0, 0.0, 0.0, 0.0, 0.0] for _ in vertices]), + } + + +def arm_source_binding(vertices): + """Small 9-column binding fixture with near-horizontal +/-X arm bones.""" + inputs = leg_inputs() + binding = binding_for(vertices, inputs=inputs) + binding["joint_order"] = list(CHECKS._ARM_JOINTS) + binding["weight_columns"] = list(CHECKS._ARM_WEIGHT_COLUMNS) + binding["parents"] = { + "pelvis": None, "left_hip": "pelvis", "left_knee": "left_hip", + "right_hip": "pelvis", "right_knee": "right_hip", + "left_shoulder": "pelvis", "left_elbow": "left_shoulder", + "right_shoulder": "pelvis", "right_elbow": "right_shoulder", + } + arm_points = { + "left": {"J": [-0.2, 1.0, 0.0], "E": [-1.0, 1.0, 0.0], + "W": [-1.6, 1.0, 0.0]}, + "right": {"J": [0.2, 1.0, 0.0], "E": [1.0, 1.0, 0.0], + "W": [1.6, 1.0, 0.0]}, + } + for side in ("left", "right"): + shoulder = CHECKS._arm_source_frame(arm_points[side]["J"], + arm_points[side]["E"], + f"{side} shoulder") + elbow = CHECKS._arm_source_frame(arm_points[side]["E"], + arm_points[side]["W"], + f"{side} elbow") + binding["rest_frames"][side].update({ + "arm_source_points": copy.deepcopy(arm_points[side]), + "shoulder": {"rest_global": shoulder}, + "elbow": {"rest_global": elbow, + "rest_local": CHECKS._mm(CHECKS._inverse(shoulder), elbow)}, + }) + binding["joints"][f"{side}_shoulder"] = { + "rest_matrix": shoulder, "inverse_bind_matrix": CHECKS._inverse(shoulder), + } + binding["joints"][f"{side}_elbow"] = { + "rest_matrix": elbow, "inverse_bind_matrix": CHECKS._inverse(elbow), + } + binding["evaluated_weights"] = [ + [1.0] + [0.0] * (len(CHECKS._ARM_WEIGHT_COLUMNS) - 1) + for _ in vertices + ] + return binding + + +def arm_graph_fixture(): + """Synthetic root graph with the accepted 8/8/10 D0/D1/D2 regions.""" + root_count = 152 + root_quads = [] + append_quads = [] + arms = {} + cursor = root_count + for side_index, side in enumerate(("left", "right")): + offset = side_index * 26 + d0 = list(range(offset, offset + 8)) + d1 = list(range(offset + 8, offset + 16)) + d2 = list(range(offset + 16, offset + 26)) + root_quads.extend([ + [d0[0], d0[1], d0[2], d0[3]], [d0[4], d0[5], d0[6], d0[7]], + [d1[0], d1[1], d1[2], d1[3]], [d1[4], d1[5], d1[6], d1[7]], + [d1[0], d1[1], d1[4], d1[5]], + ]) + for start in (0, 2, 4, 6): + root_quads.append([d0[start], d0[start + 1], d1[start + 1], d1[start]]) + root_quads.append([d1[start], d1[start + 1], d2[start + 1], d2[start]]) + root_quads.append([d1[0], d1[1], d2[8], d2[9]]) + + collar = list(range(cursor, cursor + 8)) + cursor += 8 + section_indices = [] + for _ in CHECKS._ARM_SECTION_NAMES: + section = list(range(cursor, cursor + 8)) + cursor += 8 + section_indices.append(section) + cap = cursor + cursor += 1 + for left, right in zip([collar] + section_indices[:-1], section_indices): + for slot in range(8): + next_slot = (slot + 1) % 8 + append_quads.append([left[slot], left[next_slot], + right[next_slot], right[slot]]) + for slot in range(8): + next_slot = (slot + 1) % 8 + append_quads.append([d0[slot], d0[next_slot], + collar[next_slot], collar[slot]]) + arms[side] = { + "J_source": f"shoulders.{side}.arm_origin", + "J": [float(side_index), 1.0, 0.0], + "E": [float(side_index) + 1.0, 1.0, 0.0], + "W": [float(side_index) + 2.0, 1.0, 0.0], + "source_port": {"name": f"port.{side}_arm", "indices": d0}, + "collar": {"indices": collar}, + "sections": [{"name": name, "indices": values} + for name, values in zip(CHECKS._ARM_SECTION_NAMES, section_indices)], + "cap": {"vertex": cap}, + "new_vertex_indices": collar + [index for section in section_indices for index in section] + [cap], + } + vertices = [[float(index), 0.0, 0.0] for index in range(cursor)] + quads = root_quads + append_quads + base = {"vertices": vertices, "quads": quads, + "metadata": {"root": {"vertex_count": root_count, + "face_count": len(root_quads)}, + "arms": arms}} + return base, arms + + +def combined_arm_head_tail_graph_fixture(): + """Final adjacency has a tail replacement inside the original root range.""" + base, arms = arm_graph_fixture() + old_root_faces = base["metadata"]["root"]["face_count"] + d0 = list(range(52, 58)) + d1 = list(range(60, 66)) + d2 = list(range(70, 76)) + support = list(range(len(base["vertices"]), len(base["vertices"]) + 6)) + tail = list(range(support[-1] + 1, support[-1] + 5)) + base["vertices"].extend([[float(index), 0.0, 1.0] for index in support + tail]) + head_root = [] + head_support = [] + for slot in range(6): + next_slot = (slot + 1) % 6 + head_root.extend(( + [d0[slot], d0[next_slot], d1[next_slot], d1[slot]], + [d1[slot], d1[next_slot], d2[next_slot], d2[slot]], + )) + head_support.append([d0[slot], d0[next_slot], support[next_slot], support[slot]]) + prior_quads = ( + base["quads"][:old_root_faces] + head_root + + base["quads"][old_root_faces:] + head_support + ) + base["metadata"]["root"]["face_count"] = old_root_faces + len(head_root) + base["metadata"]["head"] = { + "neck_port_indices": d0, + "binding_handoff": {"consumed_neck_port_indices": d0}, + } + final_quads = copy.deepcopy(prior_quads) + final_quads[old_root_faces] = [d0[0], d0[1], tail[0], tail[1]] + final_quads.extend([ + [tail[0], tail[1], tail[2], tail[3]], + [tail[1], tail[2], tail[3], support[0]], + ]) + head = {"source_port": d0, "support": support} + return base, arms, head, prior_quads, final_quads + + +def pose_mesh(vertices, owners): + return {"vertices": copy.deepcopy(vertices), "quads": [[0, 1, 2, 3]], + "face_owners": owners, "loops": {}} + + +def clean_adjacent_fixture(): + vertices = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]] + rest = pose_mesh(vertices, ["leg.left"]) + posed = pose_mesh(vertices, ["leg.left"]) + inputs = leg_inputs() + return rest, posed, binding_for(vertices, inputs=inputs), { + "left": {"hip": 0.0, "knee": 0.0}, + "right": {"hip": 0.0, "knee": 0.0}, + }, protocol(), inputs + + +def crossing_fixture(): + vertices = [ + [-1.0, -1.0, 0.0], [1.0, -1.0, 0.0], [1.0, 1.0, 0.0], [-1.0, 1.0, 0.0], + [0.0, -1.0, -1.0], [0.0, 1.0, -1.0], [0.0, 1.0, 1.0], [0.0, -1.0, 1.0], + ] + rest = {"vertices": vertices, "quads": [[0, 1, 2, 3], [4, 5, 6, 7]], + "face_owners": ["leg.left", "leg.right"], "loops": {}} + posed = copy.deepcopy(rest) + inputs = leg_inputs() + binding = binding_for(vertices, inputs=inputs) + return rest, posed, binding, { + "left": {"hip": 0.0, "knee": 0.0}, + "right": {"hip": 0.0, "knee": 0.0}, + }, protocol(), inputs + + +class CheckMeshTests(unittest.TestCase): + def test_reports_missing_five_port_boundary_contract(self): + vertices = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]] + mesh = {"vertices": vertices, "quads": [[0, 1, 2, 3]], + "loops": {"neck": [0, 1, 2, 3]}, + "base_stencils": [[[index, 1.0]] for index in range(4)]} + report = CHECKS.check_mesh(mesh, protocol()) + self.assertFalse(report["pass"]) + self.assertTrue(report["checks"]["one_connected_component"]) + self.assertFalse(report["checks"]["exact_five_boundary_loops"]) + self.assertFalse(report["checks"]["declared_neck_two_arms_two_ankles"]) + + def test_nonpositive_triangle_area_is_a_defect(self): + mesh = {"vertices": [[0.0, 0.0, 0.0]] * 4, "quads": [[0, 1, 2, 3]], + "loops": {}, "base_stencils": [[[index, 1.0]] for index in range(4)]} + report = CHECKS.check_mesh(mesh, protocol()) + self.assertFalse(report["pass"]) + self.assertFalse(report["checks"]["triangle_minimum_area"]) + self.assertEqual(report["outcome"], "fail") + + def test_stencil_partition_uses_declared_numeric_tolerance(self): + rows = [[[0, 1.0000000005]]] + self.assertEqual(CHECKS._stencil_rows(rows, 1, 1, "stencils", 1e-9), + [[(0, 1.0000000005)]]) + + def test_terminal_foot_metadata_accepts_three_retained_boundaries(self): + report = CHECKS.check_mesh(terminal_foot_mesh(), protocol()) + self.assertTrue(report["pass"], report) + self.assertTrue(report["checks"]["foot_metadata_contract"]) + self.assertTrue(report["checks"]["foot_closed_boundary_contract"]) + self.assertNotIn("exact_five_boundary_loops", report["checks"]) + + def test_terminal_foot_missing_metadata_does_not_admit_three_boundaries(self): + mesh = terminal_foot_mesh() + del mesh["metadata"]["feet"] + mesh["metadata"]["base_vertex_count"] = len(mesh["vertices"]) + mesh["metadata"]["base_control_owners"] = ["domain.root"] * len(mesh["vertices"]) + report = CHECKS.check_mesh(mesh, protocol()) + self.assertFalse(report["pass"]) + self.assertFalse(report["checks"]["exact_five_boundary_loops"]) + self.assertFalse(report["checks"]["declared_neck_two_arms_two_ankles"]) + + def test_terminal_foot_missing_side_is_rejected(self): + mesh = terminal_foot_mesh() + del mesh["metadata"]["feet"]["left"] + report = CHECKS.check_mesh(mesh, protocol()) + self.assertFalse(report["pass"]) + self.assertFalse(report["checks"]["foot_metadata_contract"]) + + def test_terminal_foot_overlapping_assignment_is_rejected(self): + mesh = terminal_foot_mesh() + mesh["metadata"]["feet"]["right"]["new_vertex_indices"] = [30, 31] + report = CHECKS.check_mesh(mesh, protocol()) + self.assertFalse(report["pass"]) + self.assertFalse(report["checks"]["foot_metadata_contract"]) + + def test_terminal_foot_out_of_range_assignment_is_rejected(self): + mesh = terminal_foot_mesh() + mesh["metadata"]["feet"]["right"]["new_vertex_indices"] = [36] + report = CHECKS.check_mesh(mesh, protocol()) + self.assertFalse(report["pass"]) + self.assertFalse(report["checks"]["foot_metadata_contract"]) + + def test_terminal_foot_loop_mismatch_is_rejected(self): + mesh = terminal_foot_mesh() + mesh["loops"]["port.right_ankle"] = mesh["loops"].pop("port.right_arm") + report = CHECKS.check_mesh(mesh, protocol()) + self.assertFalse(report["pass"]) + self.assertTrue(report["checks"]["foot_metadata_contract"]) + self.assertFalse(report["checks"]["foot_closed_boundary_contract"]) + + +class CheckPoseTests(unittest.TestCase): + def test_terminal_foot_pose_uses_broadphase_wrapper_and_complete_pair_scope(self): + rest, posed, binding, angles, limits, inputs = clean_adjacent_fixture() + rest["metadata"] = {"feet": {}} + posed["metadata"] = {"feet": {}} + calls = [] + + class Broadphase: + METHOD = "synthetic-broadphase" + FROZEN_CORE_PATH = CHECKS._FROZEN_CORE + + @staticmethod + def collision_report(vertices, triangles, *, include_classifications, block_size=1024): + calls.append((vertices, triangles, include_classifications, block_size)) + pair_count = len(triangles) * (len(triangles) - 1) // 2 + return { + "available": True, + "pair_count": pair_count, + "pair_partition_complete": True, + "final_classification_partition_complete": True, + "hit_pairs_truncated": False, + "candidate_pairs_truncated": False, + "nontrivial_evidence_truncated": False, + "hit_pairs": [], "errors": [], "blocks": [{"block": 0}], + "narrowphase": "frozen-oracle", + } + + with mock.patch.object(CHECKS, "_BROADPHASE", Broadphase()), \ + mock.patch.object(CHECKS, "_load_intersection_core", + side_effect=AssertionError("legacy route used")): + report = CHECKS.check_pose(rest, posed, binding, angles, limits, inputs) + + self.assertTrue(report["pass"], report) + self.assertEqual(len(calls), 1) + self.assertFalse(calls[0][2]) + collision = report["metrics"]["collision"] + self.assertEqual(collision["method"], "synthetic-broadphase") + self.assertEqual(collision["narrowphase"], "frozen-oracle") + self.assertEqual(collision["intersection_core_path"], str(CHECKS._FROZEN_CORE)) + self.assertEqual(len(collision["intersection_core_sha256"]), 64) + self.assertTrue(collision["scope"]["complete_pair_accounting"]) + self.assertEqual(collision["covered_pair_count"], collision["expected_pair_count"]) + + def test_terminal_foot_pose_maps_wrapper_hits_to_owned_faces(self): + rest, posed, binding, angles, limits, inputs = clean_adjacent_fixture() + rest["metadata"] = {"feet": {}} + posed["metadata"] = {"feet": {}} + extra = [[3.0, 0.0, 0.0], [4.0, 0.0, 0.0], + [4.0, 1.0, 0.0], [3.0, 1.0, 0.0]] + for mesh in (rest, posed): + mesh["vertices"] = mesh["vertices"] + extra + mesh["quads"] = [[0, 1, 2, 3], [4, 5, 6, 7]] + mesh["face_owners"] = ["leg.left", "leg.right"] + binding = binding_for(rest["vertices"], inputs=inputs) + + class Broadphase: + FROZEN_CORE_PATH = CHECKS._FROZEN_CORE + METHOD = "synthetic-broadphase" + + @staticmethod + def collision_report(_vertices, _triangles, *, include_classifications, block_size=1024): + return { + "available": True, "pair_count": 6, + "pair_partition_complete": True, + "final_classification_partition_complete": True, + "hit_pairs_truncated": False, + "candidate_pairs_truncated": False, + "nontrivial_evidence_truncated": False, + "hit_pairs": [[0, 2]], "errors": [], "blocks": [], + "narrowphase": "frozen-oracle", + } + + with mock.patch.object(CHECKS, "_BROADPHASE", Broadphase()): + report = CHECKS.check_pose(rest, posed, binding, angles, limits, inputs) + + collision = report["metrics"]["collision"] + self.assertEqual(collision["hit_face_pairs"][0]["faces"], [0, 1]) + self.assertFalse(report["checks"]["lower_collision_inventory"]) + + def test_terminal_foot_pose_without_wrapper_is_unavailable_not_legacy(self): + rest, posed, binding, angles, limits, inputs = clean_adjacent_fixture() + rest["metadata"] = {"feet": {}} + posed["metadata"] = {"feet": {}} + with mock.patch.object(CHECKS, "_BROADPHASE", None), \ + mock.patch.object(CHECKS, "_load_broadphase", return_value=None), \ + mock.patch.object(CHECKS, "_load_intersection_core", + side_effect=AssertionError("legacy route used")): + report = CHECKS.check_pose(rest, posed, binding, angles, limits, inputs) + + self.assertFalse(report["pass"]) + self.assertFalse(report["checks"]["collision_coverage_complete"]) + self.assertIn("collision_unavailable", + {row["code"] for row in report["errors"]}) + + def test_clean_adjacent_fixture_passes_and_has_complete_collision_coverage(self): + values = clean_adjacent_fixture() + report = CHECKS.check_pose(*values) + self.assertTrue(report["pass"], report) + self.assertTrue(report["checks"]["identity_at_zero_angles"]) + self.assertTrue(report["checks"]["collision_coverage_complete"]) + self.assertEqual(report["metrics"]["collision"]["global_face_pair_count"], 0) + + def test_synthetic_positive_crossing_fixture_is_caught(self): + values = crossing_fixture() + report = CHECKS.check_pose(*values) + self.assertFalse(report["pass"]) + self.assertFalse(report["checks"]["lower_collision_inventory"]) + self.assertGreaterEqual(len(report["metrics"]["collision"]["lower_hit_pairs"]), 1) + + def test_static_pose_with_nonzero_angle_fails_independent_lbs(self): + rest, posed, binding, angles, limits, inputs = clean_adjacent_fixture() + binding = copy.deepcopy(binding) + binding["evaluated_weights"] = [[0.0, 1.0, 0.0, 0.0, 0.0] for _ in rest["vertices"]] + angles = {"left": 15.0, "right": 0.0} + report = CHECKS.check_pose(rest, posed, binding, angles, limits, inputs) + self.assertFalse(report["pass"]) + self.assertFalse(report["checks"]["independent_hierarchical_lbs"]) + + def test_wrong_binding_frames_and_self_consistent_pose_fail_source_check(self): + rest, _posed, _binding, angles, limits, immutable_inputs = clean_adjacent_fixture() + wrong_inputs = copy.deepcopy(immutable_inputs) + wrong_inputs["left"]["J"][1] += 0.1 + weights = [[0.0, 1.0, 0.0, 0.0, 0.0] for _ in rest["vertices"]] + wrong_binding = binding_for(rest["vertices"], weights, wrong_inputs) + angles = {"left": {"hip": 15.0, "knee": 0.0}, + "right": {"hip": 0.0, "knee": 0.0}} + wrong_pose = BINDING.pose(rest, wrong_binding, angles) + report = CHECKS.check_pose(rest, wrong_pose, wrong_binding, angles, limits, + immutable_inputs) + self.assertFalse(report["pass"]) + self.assertFalse(report["checks"]["binding_leg_inputs_match_immutable_inputs"]) + self.assertFalse(report["checks"]["binding_rest_sources_match_J_K_A"]) + + def test_nonvertical_knee_uses_positive_rotation_after_parent_hip(self): + rest, _posed, _binding, _angles, limits, inputs = clean_adjacent_fixture() + weights = [[0.0, 0.0, 1.0, 0.0, 0.0] for _ in rest["vertices"]] + binding = binding_for(rest["vertices"], weights, inputs) + angles = {"left": {"hip": 20.0, "knee": 30.0}, + "right": {"hip": 0.0, "knee": 0.0}} + posed = BINDING.pose(rest, binding, angles) + report = CHECKS.check_pose(rest, posed, binding, angles, limits, inputs) + self.assertTrue(report["checks"]["independent_hierarchical_lbs"], report) + + def test_multiblock_pair_coverage_counts_cross_products_once(self): + vertices = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], + [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]] + quads = [(0, 1, 2, 3)] * 2050 # 4100 triangles: more than two default blocks. + def stub(_vertices, triangles): + pair_count = len(triangles) * (len(triangles) - 1) // 2 + return {"pair_count": pair_count, + "pair_policy_evidence": {"processed_pair_count": pair_count}, + "pair_policy_complete": True, "candidate_pairs_truncated": False, + "hit_pairs_truncated": False, "hit_pairs": []} + with mock.patch.object(CHECKS, "_load_intersection_core", return_value=stub): + report = CHECKS._collision_report( + vertices, quads, ["domain.left_leg"] * len(quads), + set(range(len(quads))), set(), + ) + self.assertTrue(report["coverage_complete"], report) + self.assertEqual(report["covered_pair_count"], report["expected_pair_count"]) + + def test_candidate_detail_truncation_does_not_hide_complete_hit_inventory(self): + vertices = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], + [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]] + def stub(_vertices, triangles): + pair_count = len(triangles) * (len(triangles) - 1) // 2 + return {"pair_count": pair_count, + "pair_policy_evidence": {"processed_pair_count": pair_count}, + "pair_policy_complete": True, "candidate_pairs_truncated": True, + "hit_pairs_truncated": False, "hit_pairs": []} + with mock.patch.object(CHECKS, "_load_intersection_core", return_value=stub): + report = CHECKS._collision_report( + vertices, [(0, 1, 2, 3)], ["domain.left_leg"], {0}, set(), + ) + self.assertTrue(report["coverage_complete"], report) + self.assertTrue(report["available"], report) + self.assertEqual(report["candidate_detail_truncated_calls"], [[0, 0]]) + + def test_processed_pair_mismatch_is_unavailable_even_if_helper_claims_complete(self): + vertices = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], + [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]] + def stub(_vertices, triangles): + pair_count = len(triangles) * (len(triangles) - 1) // 2 + return {"pair_count": pair_count, + "pair_policy_evidence": {"processed_pair_count": pair_count - 1}, + "pair_policy_complete": True, "candidate_pairs_truncated": False, + "hit_pairs_truncated": False, "hit_pairs": []} + with mock.patch.object(CHECKS, "_load_intersection_core", return_value=stub): + report = CHECKS._collision_report( + vertices, [(0, 1, 2, 3)], ["domain.left_leg"], {0}, set(), + ) + self.assertFalse(report["coverage_complete"], report) + self.assertFalse(report["available"], report) + self.assertEqual(report["errors"][0]["code"], "incomplete_pair_policy") + + def test_captured_actual_pose_has_complete_lower_surface_collision_coverage(self): + capture_value = os.environ.get("CONNECTED_LEG_CAPTURE_RUN") + if not capture_value: + self.skipTest("set CONNECTED_LEG_CAPTURE_RUN to exercise a captured full pose") + capture = Path(capture_value) + run_report = json.loads((capture / "run-report.json").read_text(encoding="utf-8")) + inputs = json.loads((capture / "inputs.json").read_text(encoding="utf-8")) + protocol_value = json.loads((capture / "protocol.json").read_text(encoding="utf-8")) + case = run_report["cases"][0] + case_inputs = next(row["leg_inputs"] for row in inputs["cases"] if row["id"] == case["id"]) + binding = json.loads((capture / "cases" / f"case-00-{case['id']}" / "binding.json").read_text(encoding="utf-8")) + pose = case["poses"][0] + report = CHECKS.check_pose(case["rest"], pose["mesh"], binding, pose["angles"], + protocol_value, case_inputs) + collision = report["metrics"]["collision"] + triangle_count = len(case["rest"]["quads"]) * 2 + self.assertEqual(triangle_count, 7936) + self.assertEqual(collision["covered_pair_count"], triangle_count * (triangle_count - 1) // 2) + self.assertTrue(collision["coverage_complete"], collision) + self.assertTrue(collision["available"], collision) + self.assertTrue(report["checks"]["lower_collision_inventory"], report) + self.assertNotIn("collision_unavailable", {row["code"] for row in report["errors"]}) + + def test_nested_constructor_root_face_count_scales_to_l2(self): + count = 2200 + parsed = {"value": {"metadata": {"level": 2, "root": {"face_count": 136}}}, + "quads": [(0, 1, 2, 3)] * count, + "face_owners": ["domain.torso"] * 2176 + ["domain.left_leg"] * 24} + lower, upper, start = CHECKS._lower_faces(parsed, {}) + self.assertEqual(start, 2176) + self.assertEqual(lower, set(range(2176, count))) + self.assertEqual(upper, set(range(2176))) + + def test_actual_protocol_and_binding_metadata_names_drive_pose_check(self): + actual_protocol = json.loads((ROOT / "protocol.json").read_text(encoding="utf-8")) + rest, posed, binding, angles, _limits, inputs = clean_adjacent_fixture() + rest["metadata"] = {"level": 2, "root": {"face_count": 0}} + posed["metadata"] = copy.deepcopy(rest["metadata"]) + self.assertEqual(tuple(binding["joint_order"]), tuple(BINDING._JOINT_ORDER)) + self.assertEqual(tuple(binding["weight_columns"]), tuple(BINDING._WEIGHT_COLUMNS)) + def stub(_vertices, triangles): + pair_count = len(triangles) * (len(triangles) - 1) // 2 + return {"pair_count": pair_count, + "pair_policy_evidence": {"processed_pair_count": pair_count}, + "pair_policy_complete": True, "candidate_pairs_truncated": False, + "hit_pairs_truncated": False, "hit_pairs": []} + with mock.patch.object(CHECKS, "_load_intersection_core", return_value=stub): + report = CHECKS.check_pose(rest, posed, binding, angles, actual_protocol, inputs) + self.assertTrue(report["pass"], report) + self.assertFalse(report["diagnostics"]["lower_normal_dot"]["gated"]) + self.assertEqual(CHECKS._limit(actual_protocol, ("weight_sum_max_abs_error",)), 1e-9) + + +class ArmCheckTests(unittest.TestCase): + def test_arm_source_frame_handles_bones_near_both_x_axes(self): + cases = { + "left": ([-0.2, 1.0, 0.0], [-1.0, 1.0, 0.0]), + "right": ([0.2, 1.0, 0.0], [1.0, 1.0, 0.0]), + } + for side, (origin, distal) in cases.items(): + frame = CHECKS._arm_source_frame(origin, distal, f"{side} arm") + self.assertAlmostEqual(frame[2][2], 1.0) + for column in range(3): + self.assertAlmostEqual( + math.sqrt(sum(frame[row][column] ** 2 for row in range(3))), 1.0 + ) + + def test_arm_endpoint_oracle_checks_settled_directions_for_both_sides(self): + binding = arm_source_binding([[0.0, 0.0, 0.0]]) + zero = {side: {"shoulder_raise": 0.0, "shoulder_forward": 0.0, + "elbow": 0.0} for side in ("left", "right")} + for side in ("left", "right"): + for angle_name, point_name, component in ( + ("shoulder_raise", "E", 1), + ("shoulder_forward", "E", 2), + ("elbow", "W", 2), + ): + angles = copy.deepcopy(zero) + angles[side][angle_name] = 10.0 + result = CHECKS._arm_endpoint_oracle(binding, angles)[side] + self.assertGreater(result["posed"][point_name][component], + result["rest"][point_name][component]) + + report = CHECKS._report("synthetic-arm-endpoint-check") + _order, posed_joints, _skins = CHECKS._expected_joint_poses( + leg_inputs(), zero, binding + ) + CHECKS._check_arm_endpoint_oracle( + report, binding, zero, posed_joints, 1.0e-9 + ) + self.assertFalse(report["errors"], report) + self.assertTrue(report["checks"]["arm_endpoint_parent_oracle"]) + + def test_arm_expected_pose_uses_negative_elbow_rotation(self): + binding = arm_source_binding([[0.0, 0.0, 0.0]]) + angles = {side: {"hip": 0.0, "knee": 0.0, + "shoulder_raise": 0.0, "shoulder_forward": 0.0, + "elbow": 20.0} for side in ("left", "right")} + _order, posed, _skins = CHECKS._expected_joint_poses( + leg_inputs(), angles, binding + ) + oracle = CHECKS._arm_endpoint_oracle(binding, angles) + for side in ("left", "right"): + self.assertAlmostEqual(posed[f"{side}_elbow"][1][3], + oracle[side]["posed"]["E"][1]) + self.assertGreater(oracle[side]["posed"]["W"][2], + oracle[side]["rest"]["W"][2]) + + def test_arm_source_check_rejects_same_origin_wrong_joint_rotation(self): + binding = arm_source_binding([[0.0, 0.0, 0.0]]) + wrong = copy.deepcopy(binding) + wrong["joints"]["left_shoulder"]["rest_matrix"] = CHECKS._mm( + wrong["joints"]["left_shoulder"]["rest_matrix"], + [[-1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, -1.0, 0.0], [0.0, 0.0, 0.0, 1.0]], + ) + contract = {"source_points": { + side: copy.deepcopy(binding["rest_frames"][side]["arm_source_points"]) + for side in ("left", "right") + }} + report = CHECKS._report("synthetic-arm-source-check") + CHECKS._check_arm_source_frames(report, wrong, contract, 1e-9) + self.assertFalse(report["checks"]["arm_source_J_E_W_frames"]) + self.assertIn("arm_source_frames", + {row["code"] for row in report["errors"]}) + + def test_arm_graph_uses_exact_8_8_10_regions_and_harmonic_field(self): + base, arms = arm_graph_fixture() + fields, _blends, diagnostics = CHECKS._arm_graph_fields( + base, base["quads"], arms + ) + for side in ("left", "right"): + details = diagnostics["per_side"][side] + self.assertEqual((len(details["D0"]), len(details["D1"]), + len(details["D2"])), (8, 8, 10)) + self.assertTrue(all(math.isfinite(value) + for value in fields[side].values()), + (fields, diagnostics)) + + def test_combined_head_arms_tail_use_prior_root_graph_and_final_adjacency(self): + base, arms, head, prior_quads, final_quads = combined_arm_head_tail_graph_fixture() + with self.assertRaisesRegex(ValueError, "root face references a non-root vertex"): + CHECKS._arm_graph_fields(base, final_quads, arms) + with self.assertRaisesRegex(ValueError, "root faces must reference only root vertices"): + CHECKS._head_graph_field(base, final_quads, head) + + fields, _blends, diagnostics = CHECKS._arm_graph_fields( + base, final_quads, arms, root_quads=prior_quads + ) + head_values, _head_diagnostics = CHECKS._head_graph_field( + base, final_quads, head, root_quads=prior_quads + ) + self.assertEqual(set(fields), {"left", "right"}) + self.assertTrue(all(math.isfinite(value) + for values in fields.values() + for value in values.values())) + self.assertEqual(set(head_values), set(head["source_port"] + list(range(60, 66)))) + self.assertEqual(set(diagnostics["per_side"]["left"]["D0"]), + set(arms["left"]["source_port"]["indices"])) + + def test_arm_binding_dispatch_finalizes_successful_specialized_report(self): + vertices = [[float(index), 0.0, 0.0] for index in range(152)] + mesh = {"vertices": vertices, "quads": [[0, 1, 2, 3]], + "metadata": {"arms": {}}} + + def specialized(report, *_args): + report["checks"]["specialized_complete"] = True + return report + + with mock.patch.object(CHECKS, "_check_arm_binding", + side_effect=specialized): + report = CHECKS.check_binding( + mesh, mesh, {}, {"vertices": vertices, + "quads": [[0, 1, 2, 3]]}, {}, {}, {} + ) + self.assertTrue(report["pass"], report) + + def test_arm_metadata_contract_accepts_named_source_allocations(self): + base, _arms = arm_graph_fixture() + contract = CHECKS._arm_metadata_contract(base, len(base["vertices"])) + self.assertTrue(contract["present"]) + self.assertEqual({side: len(indices) + for side, indices in contract["indices"].items()}, + {"left": 89, "right": 89}) + + def test_arm_pose_selects_complete_broadphase_route(self): + rest, posed, binding, angles, limits, inputs = clean_adjacent_fixture() + rest["metadata"] = {"arms": {"left": {}, "right": {}}} + posed["metadata"] = copy.deepcopy(rest["metadata"]) + calls = [] + + def broadphase(*_args, **_kwargs): + calls.append(True) + return {"available": True, "coverage_complete": True, + "lower_hit_pairs": []} + + with mock.patch.object(CHECKS, "_foot_collision_report", + side_effect=broadphase), \ + mock.patch.object(CHECKS, "_collision_report", + side_effect=AssertionError("legacy route used")): + report = CHECKS.check_pose(rest, posed, binding, angles, limits, inputs) + + self.assertEqual(len(calls), 1) + self.assertTrue(report["pass"], report) + self.assertTrue(report["checks"]["collision_coverage_complete"]) + + +def binding_fixture(): + root_vertices = [[float(index), 0.0, 0.0] for index in range(152)] + appended = [[float(index), -1.0, 0.0] for index in range(152, 264)] + vertices = root_vertices + appended + prior_root = {"vertices": copy.deepcopy(root_vertices), "quads": [[0, 1, 2, 3]]} + inputs = leg_inputs() + chains = {} + cursor = 152 + for side in ("left", "right"): + sections = [] + for order, name in enumerate(CHECKS._STATION_NAMES): + ring = list(range(cursor, cursor + 8)) + cursor += 8 + sections.append({"name": name, "order": order, "indices": ring}) + chains[side] = {"sections": sections} + base = {"vertices": copy.deepcopy(vertices), "quads": [[0, 1, 2, 3]], + "metadata": {"chains": chains}} + prior_rows = [[0.2, 0.3, 0.5] for _ in root_vertices] + base_rows = [[0.2, 0.3, 0.0, 0.5, 0.0] for _ in root_vertices] + for side, thigh, shank in (("left", 1, 2), ("right", 3, 4)): + for station_index, section in enumerate(chains[side]["sections"]): + shank_value = CHECKS._STATION_SHANK_WEIGHTS[station_index] + for _index in section["indices"]: + row = [0.0] * 5 + row[thigh], row[shank] = 1.0 - shank_value, shank_value + base_rows.append(row) + rest = {"vertices": copy.deepcopy(vertices), "quads": [[0, 1, 2, 3]], + "base_stencils": [[[index, 1.0]] for index in range(264)]} + binding = binding_for(vertices, base_rows, inputs) + binding.update({"base_weights": base_rows, + "source_station_knee": list(CHECKS._STATION_SHANK_WEIGHTS), + "prior_column_map": [0, 1, 3]}) + prior_binding = {"base_weights": prior_rows} + return base, rest, binding, prior_root, prior_binding, inputs, protocol() + + +def tail_metadata(new_indices, replacement_faces=(0, 1, 2)): + host = [0, 1, 2, 3] + phase = [[1, 1], [-1, 1], [-1, -1], [1, -1]] + rings = [list(new_indices[:4]), list(new_indices[4:8])] + corner_by_index = { + index: corner + for ring in rings + for corner, index in enumerate(ring) + } + supports = {} + for index in new_indices: + corner = corner_by_index[index] + supports[str(index)] = { + "target_joint": "pelvis", "host_vertex_indices": host[:], + "host_corner": corner, "source_phase": phase[corner], + "convex_weights": [0.55 if slot == corner else 0.15 for slot in range(4)], + } + return { + "owner": "domain.tail", "enabled": True, + "source_host_identity": {"owner": "domain.pelvis", "face_index": 0, + "vertex_indices": host[:]}, + "host": {"source_phase": copy.deepcopy(phase)}, + "source_phase": copy.deepcopy(phase), "ring_indices": rings, + "station_fractions": [0.0, 1.0], + "new_vertex_indices": list(new_indices), + "face_replacement": { + "original_face_index": 0, "original_quad": host[:], + "replacement_face_indices": list(replacement_faces), + "one_to_many": [[0, *replacement_faces]], + "original_host_retained": False, + }, + "transition_weights": { + "collar_blend_strength": 0.5, "supports": supports, + }, + } + + +def tail_binding_fixture(): + values = list(binding_fixture()) + base, rest, binding, prior_root, prior_binding, inputs, limits = values + tail_indices = list(range(264, 272)) + base["vertices"].extend([[float(index), -2.0, 0.0] for index in tail_indices]) + base["quads"] = [ + [0, 1, 264, 265], [1, 2, 266, 265], [264, 265, 269, 268], + [265, 266, 270, 269], [266, 267, 271, 270], + ] + base["metadata"].update({ + "base_vertex_count": 272, + "base_control_owners": ["domain.root"] * 264 + ["domain.tail"] * 8, + "root": {"vertex_count": 152, "face_count": 1}, + "index_mapping": {"root_face_mappings_excluding_tail_host": []}, + "tail": tail_metadata(tail_indices), + }) + rest["vertices"].extend([[float(index), -2.0, 0.0] for index in tail_indices]) + rest["base_stencils"].extend([[[index, 1.0]] for index in tail_indices]) + base_rows = copy.deepcopy(binding["base_weights"]) + base_rows.extend([[0.6, 0.15, 0.0, 0.25, 0.0] for _ in range(4)]) + base_rows.extend([[1.0, 0.0, 0.0, 0.0, 0.0] for _ in range(4)]) + binding["base_weights"] = base_rows + binding["evaluated_weights"] = copy.deepcopy(base_rows) + binding["tail_vertex_indices"] = tail_indices[:] + binding["tail_weighting"] = { + "collar_blend_strength": 0.5, "distal_joint": "pelvis", + "no_tail_joint": True, + "vertices": { + str(index): { + "ring_fraction": 0.0 if index < 268 else 1.0, + "pelvis_fraction": 0.5 if index < 268 else 1.0, + "host_support_fraction": 0.5 if index < 268 else 0.0, + "host_vertex_indices": [0, 1, 2, 3], + "convex_weights": [0.55 if slot == index % 4 else 0.15 for slot in range(4)], + } + for index in tail_indices + }, + } + binding["metadata"] = { + "tail_weighting_contract": { + "host_face": 0, "host_vertex_indices": [0, 1, 2, 3], + "kept_root_face_correspondence": [], + "replacement_face_indices": [0, 1, 2], + "collar_blend_strength": 0.5, + "distal_target_joint": "pelvis", "tail_joint": "not_present", + } + } + return base, rest, binding, prior_root, prior_binding, inputs, limits + + +def terminal_foot_mesh(): + """A small two-hole surface whose metadata exercises the foot contract.""" + width = height = 5 + vertices = [[float(x), float(y), 0.0] + for y in range(height + 1) for x in range(width + 1)] + omitted = {(1, 1), (3, 3)} + quads = [] + for y in range(height): + for x in range(width): + if (x, y) not in omitted: + lower = y * (width + 1) + x + quads.append([lower, lower + 1, lower + width + 2, lower + width + 1]) + cycles = CHECKS._boundary_cycles(CHECKS._edge_incidence(quads)) + loops = { + "port.neck": cycles[0], + "port.left_arm": cycles[1], + "port.right_arm": cycles[2], + } + owner_count = 28 + metadata = { + "level": 0, + "base_vertex_count": owner_count, + "base_control_owners": ["domain.root"] * owner_count, + "root": {"vertex_count": 4}, + "chains": { + "left": {"new_vertex_indices": list(range(4, 16))}, + "right": {"new_vertex_indices": list(range(16, 28))}, + }, + "feet": { + "left": {"new_vertex_indices": [28, 29, 30]}, + "right": {"new_vertex_indices": [31, 32, 33, 34, 35]}, + }, + } + return { + "vertices": vertices, + "quads": quads, + "loops": loops, + "base_stencils": [[[index, 1.0]] for index in range(len(vertices))], + "metadata": metadata, + } + + +def terminal_foot_binding_fixture(): + values = list(binding_fixture()) + base, rest, binding, prior_root, prior_binding, inputs, limits = values + base["vertices"].extend([[264.0, -1.0, 0.0], [265.0, -1.0, 0.0]]) + base_metadata = base["metadata"] + base_metadata["base_vertex_count"] = 266 + base_metadata["base_control_owners"] = ["domain.root"] * 266 + base_metadata["root"] = {"vertex_count": 152} + for side in ("left", "right"): + base_metadata["chains"][side]["new_vertex_indices"] = [ + index for section in base_metadata["chains"][side]["sections"] + for index in section["indices"] + ] + base_metadata["feet"] = { + "left": {"new_vertex_indices": [264]}, + "right": {"new_vertex_indices": [265]}, + } + rest["vertices"].extend([[264.0, -1.0, 0.0], [265.0, -1.0, 0.0]]) + rest["base_stencils"].extend([[[264, 1.0]], [[265, 1.0]]]) + binding["base_weights"].extend([ + [0.0, 0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 1.0], + ]) + binding["evaluated_weights"] = copy.deepcopy(binding["base_weights"]) + binding["foot_vertex_indices"] = {"left": [264], "right": [265]} + binding["metadata"] = { + "foot_vertex_indices": {"left": [264], "right": [265]}, + } + return base, rest, binding, prior_root, prior_binding, inputs, limits + + +class CheckBindingTests(unittest.TestCase): + def test_source_stations_prior_mapping_and_full_transfer_pass(self): + report = CHECKS.check_binding(*binding_fixture()) + self.assertTrue(report["pass"], report) + self.assertTrue(report["checks"]["declared_source_station_knee"]) + self.assertTrue(report["checks"]["original_root_152x3_mapped_to_five_columns"]) + self.assertTrue(report["checks"]["actual_l2_full_stencil_transfer"]) + + def test_in_range_prior_weight_change_is_caught_by_mapping(self): + values = list(binding_fixture()) + values[2] = copy.deepcopy(values[2]) + values[2]["base_weights"][0] = [0.21, 0.29, 0.0, 0.5, 0.0] + values[2]["evaluated_weights"][0] = copy.deepcopy(values[2]["base_weights"][0]) + report = CHECKS.check_binding(*values) + self.assertFalse(report["pass"]) + self.assertFalse(report["checks"]["original_root_152x3_mapped_to_five_columns"]) + + def test_full_stencil_transfer_is_not_replaced_by_partition_check(self): + values = list(binding_fixture()) + values[2] = copy.deepcopy(values[2]) + values[2]["evaluated_weights"][10] = [0.25, 0.25, 0.0, 0.5, 0.0] + report = CHECKS.check_binding(*values) + self.assertFalse(report["pass"]) + self.assertFalse(report["checks"]["actual_l2_full_stencil_transfer"]) + + def test_consistently_mutated_station_base_and_l2_weights_still_fail(self): + values = list(binding_fixture()) + values[2] = copy.deepcopy(values[2]) + values[2]["base_weights"][152] = [0.0, 0.75, 0.25, 0.0, 0.0] + values[2]["evaluated_weights"][152] = [0.0, 0.75, 0.25, 0.0, 0.0] + report = CHECKS.check_binding(*values) + self.assertFalse(report["pass"]) + self.assertFalse(report["checks"]["constructor_station_base_weights"]) + self.assertFalse(report["checks"]["actual_l2_full_stencil_transfer"]) + + def test_terminal_foot_metadata_and_shank_weights_pass(self): + report = CHECKS.check_binding(*terminal_foot_binding_fixture()) + self.assertTrue(report["pass"], report) + self.assertTrue(report["checks"]["terminal_foot_metadata_and_shank_weights"]) + self.assertTrue(report["checks"]["terminal_foot_full_l2_stencil_transfer"]) + + def test_terminal_foot_full_l2_stencil_transfer_rejects_mutated_surface_weight(self): + values = list(terminal_foot_binding_fixture()) + values[2] = copy.deepcopy(values[2]) + values[2]["evaluated_weights"][264] = [0.0, 0.0, 0.0, 0.0, 0.0] + report = CHECKS.check_binding(*values) + self.assertFalse(report["pass"]) + self.assertFalse(report["checks"]["terminal_foot_full_l2_stencil_transfer"]) + + def test_tail_binding_checks_explicit_control_corner_supports_and_stencils(self): + report = CHECKS.check_binding(*tail_binding_fixture()) + self.assertTrue(report["pass"], report) + for name in ( + "tail_host_face_identity", "tail_kept_root_faces_exact", + "tail_host_face_replaced", "tail_binding_control_explicit", + "tail_corner_supports", "tail_l0_weight_formula", + "tail_l2_full_stencil_transfer", + ): + self.assertTrue(report["checks"][name], (name, report)) + + def test_tail_checker_uses_declared_ring_ordinal_for_non_multiple_prefix(self): + tail_indices = list(range(265, 273)) + mesh = { + "vertices": [[0.0, 0.0, 0.0] for _ in range(273)], + "quads": [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]], + "metadata": { + "root": {"vertex_count": 152, "face_count": 1}, + "base_vertex_count": 273, + "index_mapping": {"root_face_mappings_excluding_tail_host": []}, + "tail": tail_metadata(tail_indices), + }, + } + contract = CHECKS._tail_metadata_contract(mesh, len(mesh["vertices"])) + self.assertEqual( + [contract["supports"][index]["host_corner"] for index in tail_indices], + [0, 1, 2, 3, 0, 1, 2, 3], + ) + + def test_tail_checker_rejects_pelvis_only_constant_against_nonpelvis_host_support(self): + values = list(tail_binding_fixture()) + original = values[2]["base_weights"][264] + self.assertGreater(original[1], 0.0) + self.assertGreater(original[3], 0.0) + self.assertTrue(CHECKS.check_binding(*values)["checks"]["tail_l0_weight_formula"]) + + values[2] = copy.deepcopy(values[2]) + values[2]["base_weights"][264] = [1.0, 0.0, 0.0, 0.0, 0.0] + values[2]["evaluated_weights"][264] = [1.0, 0.0, 0.0, 0.0, 0.0] + report = CHECKS.check_binding(*values) + self.assertFalse(report["pass"]) + self.assertFalse(report["checks"]["tail_l0_weight_formula"]) + + def test_tail_binding_rejects_uniform_centroid_support(self): + values = list(tail_binding_fixture()) + values[0] = copy.deepcopy(values[0]) + values[0]["metadata"]["tail"]["transition_weights"]["supports"]["264"]["convex_weights"] = [0.25] * 4 + report = CHECKS.check_binding(*values) + self.assertFalse(report["pass"]) + self.assertTrue(report["errors"]) + + def test_tail_binding_rejects_changed_kept_root_face(self): + values = list(tail_binding_fixture()) + values[0] = copy.deepcopy(values[0]) + values[0]["metadata"]["index_mapping"]["root_face_mappings_excluding_tail_host"] = [[0, 0]] + report = CHECKS.check_binding(*values) + self.assertFalse(report["pass"]) + self.assertTrue(report["errors"]) + + +class HeadCheckTests(unittest.TestCase): + def head_metadata(self): + port = list(range(6)) + support = list(range(152, 158)) + return { + "metadata": { + "head": { + "neck_source": "stations.neck_upper", + "neck_port_indices": port, + "stations": [{"name": "neck_support", "indices": support}], + "new_vertex_indices": support, + "binding_handoff": { + "joint": "neck_head", + "pivot_source": "stations.neck_collar.C", + "pivot": [0.0, 1.5, 0.0], + "consumed_neck_port_indices": port, + "neck_support_ring_indices": support, + "head_new_vertex_indices": support, + }, + } + } + } + + def head_binding(self): + pivot = [0.0, 1.5, 0.0] + rest = identity() + rest[0][3], rest[1][3], rest[2][3] = pivot + return { + "rest_frames": {"head": { + "J": pivot, + "pivot_source": "stations.neck_collar.C", + "rest_global": rest, + "frame_source": CHECKS._HEAD_FRAME_SOURCE, + }}, + "joints": {"neck": { + "rest_matrix": rest, + "inverse_bind_matrix": CHECKS._inverse(rest), + }}, + } + + def test_head_handoff_consumes_exact_upper_port_but_uses_collar_pivot(self): + contract = CHECKS._head_metadata_contract(self.head_metadata(), 158) + self.assertEqual(contract["source_port"], list(range(6))) + self.assertEqual(contract["consumed_neck_port_indices"], list(range(6))) + self.assertEqual(contract["J"], (0.0, 1.5, 0.0)) + self.assertEqual(contract["pivot_source"], "stations.neck_collar.C") + bad = self.head_metadata() + bad["metadata"]["head"]["binding_handoff"]["consumed_neck_port_indices"] = list(range(1, 7)) + with self.assertRaises(ValueError): + CHECKS._head_metadata_contract(bad, 158) + + def test_head_source_check_rejects_same_origin_wrong_rotation(self): + report = CHECKS._report("head-test") + contract = CHECKS._head_metadata_contract(self.head_metadata(), 158) + binding = self.head_binding() + self.assertEqual(CHECKS._head_source_frame_error(report, binding, contract, 1e-9), 0.0) + wrong = copy.deepcopy(binding) + wrong["joints"]["neck"]["rest_matrix"][0][0] = -1.0 + error = CHECKS._head_source_frame_error(report, wrong, contract, 1e-9) + self.assertGreater(error, 1e-9) + + def test_head_endpoint_oracle_has_declared_positive_directions(self): + binding = self.head_binding() + yaw = CHECKS._head_endpoint_oracle(binding, {"head": {"yaw": 10.0, "nod": 0.0}}) + nod = CHECKS._head_endpoint_oracle(binding, {"head": {"yaw": 0.0, "nod": 10.0}}) + self.assertGreater(yaw["posed_forward_endpoint"][0], yaw["rest_forward_endpoint"][0]) + self.assertLess(nod["posed_forward_endpoint"][1], nod["rest_forward_endpoint"][1]) + + def test_head_harmonic_identity_uses_positions_not_high_vertex_ids(self): + d0 = list(range(50, 56)) + d1 = list(range(60, 66)) + d2 = list(range(70, 76)) + support = list(range(152, 158)) + root_quads = [] + support_quads = [] + for slot in range(6): + next_slot = (slot + 1) % 6 + root_quads.extend(( + [d0[slot], d0[next_slot], d1[next_slot], d1[slot]], + [d1[slot], d1[next_slot], d2[next_slot], d2[slot]], + )) + support_quads.append( + [d0[slot], d0[next_slot], support[next_slot], support[slot]] + ) + base = { + "metadata": {"root": {"vertex_count": 152, + "face_count": len(root_quads)}}, + } + values, diagnostics = CHECKS._head_graph_field( + base, root_quads + support_quads, + {"source_port": d0, "support": support}, + ) + self.assertEqual(set(values), set(d0 + d1)) + self.assertTrue(all(math.isfinite(value) for value in values.values())) + self.assertEqual(diagnostics["support"], support) + + def test_joint_rows_keeps_all_five_six_nine_ten_layouts_explicit(self): + for order in (CHECKS._JOINTS, CHECKS._HEAD_JOINTS, + CHECKS._ARM_JOINTS, CHECKS._ARM_HEAD_JOINTS): + binding = {"joint_order": list(order), + "joints": {name: {"rest_matrix": identity(), + "inverse_bind_matrix": identity()} + for name in order}} + parents = {"pelvis": None, "left_hip": "pelvis", "left_knee": "left_hip", + "right_hip": "pelvis", "right_knee": "right_hip"} + if "neck" in order: + parents["neck"] = "pelvis" + for side in ("left", "right"): + if f"{side}_shoulder" in order: + parents.update({f"{side}_shoulder": "pelvis", + f"{side}_elbow": f"{side}_shoulder"}) + binding["parents"] = parents + parsed, _rows, parsed_parents = CHECKS._joint_rows(binding) + self.assertEqual(tuple(parsed), tuple(order)) + self.assertEqual(parsed_parents, parents) + + +def comparison_fixture(): + old_l0 = {"vertices": [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]], + "quads": [[0, 1, 2, 3]]} + new_l0 = {"vertices": old_l0["vertices"] + [[2.0, 0.0, 0.0], [3.0, 0.0, 0.0], [3.0, 1.0, 0.0], [2.0, 1.0, 0.0]], + "quads": [[0, 1, 2, 3], [4, 5, 6, 7]]} + old_l2 = {"vertices": old_l0["vertices"], "quads": [[0, 1, 2, 3]], + "base_stencils": [[[0, 1.0]], [[1, 1.0]], [[2, 1.0]], [[3, 1.0]]], + "loops": {"ankle.left": [2, 3, 0]}} + new_l2 = {"vertices": [[2.0, 0.0, 0.0], [3.0, 0.0, 0.0], [2.0, 1.0, 0.0], [3.0, 1.0, 0.0], + [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.01, 1.0, 0.0], [0.01, 1.0, 0.0]], + "quads": [[4, 5, 6, 7], [0, 1, 2, 3]], + "base_stencils": [[[4, 1.0]], [[5, 1.0]], [[6, 1.0]], [[7, 1.0]], + [[0, 1.0]], [[1, 1.0]], [[4, 1.0]], [[5, 1.0]]], + "loops": {"ankle.left": [6, 7, 4]}} + return old_l0, new_l0, old_l2, new_l2 + + +def tail_compare_fixture(): + root_vertices = [[float(index), 0.0, 0.0] for index in range(152)] + root_vertices[:8] = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], + [0.0, 1.0, 0.0], [2.0, 0.0, 0.0], [3.0, 0.0, 0.0], + [3.0, 1.0, 0.0], [2.0, 1.0, 0.0]] + old_l0 = { + "vertices": root_vertices, + "quads": [[0, 1, 2, 3], [4, 5, 6, 7]], + } + new_l0 = { + "vertices": old_l0["vertices"] + [[0.0, -0.1, 0.0], [1.0, -0.1, 0.0], + [1.0, -0.2, 0.0], [0.0, -0.2, 0.0], + [0.0, -0.3, 0.0], [1.0, -0.3, 0.0], + [1.0, -0.4, 0.0], [0.0, -0.4, 0.0]], + "quads": [[0, 1, 152, 153], [4, 5, 6, 7], [1, 2, 154, 153], + [152, 153, 155, 154]], + "metadata": { + "root": {"vertex_count": 152, "face_count": 2}, + "base_vertex_count": 160, + "index_mapping": { + "root_face_mappings_excluding_tail_host": [[1, 1]], + }, + "tail": tail_metadata(list(range(152, 160)), [0, 1, 2, 3]), + }, + } + old_l2 = { + "vertices": copy.deepcopy(old_l0["vertices"][:8]), + "quads": [[0, 1, 2, 3], [4, 5, 6, 7]], + "base_stencils": [[[index, 1.0]] for index in range(8)], + } + new_l2 = { + "vertices": [[0.1, 0.0, 0.0], [1.1, 0.0, 0.0], [1.0, 1.0, 0.0], + [0.0, 1.0, 0.0], [2.0, 0.0, 0.0], [3.0, 0.0, 0.0], + [3.0, 1.0, 0.0], [2.0, 1.0, 0.0]], + "quads": [[0, 1, 2, 3], [4, 5, 6, 7], [0, 1, 2, 3], [4, 5, 6, 7]], + "base_stencils": [[[8, 1.0]], [[9, 1.0]], [[2, 1.0]], [[3, 1.0]], + [[4, 1.0]], [[5, 1.0]], [[6, 1.0]], [[7, 1.0]]], + } + return old_l0, new_l0, old_l2, new_l2 + + +def combined_tail_compare_fixture(): + """Local CC changes are declared at tail, arm, head, and foot seams.""" + root_vertices = [[float(index), 0.0, 0.0] for index in range(152)] + tail_vertices = [[float(index), -1.0, 0.0] for index in range(152, 160)] + old_l0 = { + "vertices": root_vertices, + "quads": [[0, 1, 2, 3], [4, 5, 6, 7]], + } + new_l0 = { + "vertices": root_vertices + tail_vertices, + "quads": [[0, 1, 152, 153], [4, 5, 6, 7], + [152, 153, 154, 155], [156, 157, 158, 159]], + "metadata": { + "base_vertex_count": 160, + "root": {"vertex_count": 152, "face_count": 2}, + "index_mapping": {"root_face_mappings_excluding_tail_host": [[1, 1]]}, + "tail": tail_metadata(list(range(152, 160)), [0, 1, 2]), + "arms": { + "left": {"source_port": {"indices": [4]}}, + "right": {"source_port": {"indices": [7]}}, + }, + "head": {"binding_handoff": {"consumed_neck_port_indices": [5]}}, + "feet": { + "left": {"ankle_source_loop": [6]}, + "right": {"ankle_source_loop": [6]}, + }, + }, + } + old_l2 = { + "vertices": copy.deepcopy(root_vertices[:8]), + "quads": [[0, 1, 2, 3], [4, 5, 6, 7]], + "base_stencils": [[[index, 1.0]] for index in range(8)], + } + new_l2 = { + "vertices": copy.deepcopy(root_vertices[:8]), + "quads": [[0, 1, 2, 3], [4, 5, 6, 7], + [0, 1, 2, 3], [4, 5, 6, 7]], + "base_stencils": [ + [[0, 0.5], [152, 0.5]], [[1, 0.5], [153, 0.5]], + [[2, 0.5], [154, 0.5]], [[3, 0.5], [155, 0.5]], + [[4, 0.5], [152, 0.5]], [[5, 0.5], [153, 0.5]], + [[6, 0.5], [154, 0.5]], [[7, 1.0]], + ], + } + return old_l0, new_l0, old_l2, new_l2 + + +class CompareRootTests(unittest.TestCase): + def test_shifted_l2_vertex_indices_use_face_prefix_mapping(self): + report = CHECKS.compare_root(*comparison_fixture()) + self.assertTrue(report["pass"], report) + self.assertTrue(report["checks"]["l2_face_prefix_mapping_consistent"]) + self.assertEqual(report["metrics"]["changed_stencil_count"], 2) + self.assertIsNotNone(report["metrics"]["changed_stencil_location_worst"]) + + def test_original_l0_prefix_defect_is_reported(self): + values = list(comparison_fixture()) + values[1] = copy.deepcopy(values[1]) + values[1]["vertices"][0][0] = 0.1 + report = CHECKS.compare_root(*values) + self.assertFalse(report["pass"]) + self.assertFalse(report["checks"]["original_l0_vertex_prefix"]) + + def test_tail_compare_replaces_only_declared_host_and_keeps_far_support(self): + report = CHECKS.compare_root(*tail_compare_fixture()) + self.assertTrue(report["pass"], report) + self.assertTrue(report["checks"]["tail_explicit_host_identity"]) + self.assertTrue(report["checks"]["tail_kept_root_faces_exact"]) + self.assertTrue(report["checks"]["tail_far_support_invariance"]) + self.assertTrue(report["checks"]["tail_near_attachment_changes_labelled"]) + + def test_combined_appendage_local_stencils_are_labelled_without_hiding_far_rows(self): + report = CHECKS.compare_root(*combined_tail_compare_fixture()) + self.assertTrue(report["pass"], report) + self.assertTrue(report["checks"]["l2_face_prefix_mapping_consistent"]) + self.assertTrue(report["checks"]["same_full_stencil_unchanged_invariance"]) + self.assertTrue(report["checks"]["tail_near_attachment_changes_labelled"]) + sources = { + source + for row in report["metrics"]["changed_stencil_displacements"] + for source in row.get("attachment_sources", []) + } + self.assertEqual(sources, {"arms", "feet", "head", "tail"}) + + def test_tail_compare_rejects_far_support_displacement(self): + values = list(tail_compare_fixture()) + values[3] = copy.deepcopy(values[3]) + values[3]["vertices"][4][0] += 0.25 + report = CHECKS.compare_root(*values) + self.assertFalse(report["pass"]) + self.assertFalse(report["checks"]["tail_far_support_invariance"]) + + def test_leg_root_ports_are_declared_from_prior_boundary_and_label_changes(self): + prior_root = { + "vertices": [[float(index), 0.0, 0.0] for index in range(12)], + "quads": [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], + "loops": { + "port.left_thigh": [4, 5, 6, 7], + "port.right_thigh": [8, 9, 10, 11], + }, + } + expanded = { + "metadata": { + "chains": { + "left": {"root_exit": [4, 5, 6, 7]}, + "right": {"root_exit": [8, 9, 10, 11]}, + }, + "root": {"old_thigh_ports_closed": { + "left": [4, 5, 6, 7], "right": [8, 9, 10, 11], + }}, + } + } + attachments = CHECKS._declared_attachment_vertices( + expanded, {"host_vertices": [0, 1, 2, 3]}, prior_root) + self.assertEqual(attachments["leg_left"], {4, 5, 6, 7}) + self.assertEqual(attachments["leg_right"], {8, 9, 10, 11}) + + def test_leg_root_port_outside_prior_boundary_is_rejected(self): + prior_root = { + "vertices": [[float(index), 0.0, 0.0] for index in range(12)], + "quads": [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], + "loops": { + "port.left_thigh": [4, 5, 6, 7], + "port.right_thigh": [8, 9, 10, 11], + }, + } + expanded = {"metadata": {"chains": { + "left": {"root_exit": [4, 5, 6, 0]}, + "right": {"root_exit": [8, 9, 10, 11]}, + }}} + with self.assertRaises(ValueError): + CHECKS._declared_attachment_vertices( + expanded, {"host_vertices": [0, 1, 2, 3]}, prior_root) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/connected-leg-assembly/tests/test_collision_broadphase.py b/experiments/connected-leg-assembly/tests/test_collision_broadphase.py new file mode 100644 index 0000000..c19b0f8 --- /dev/null +++ b/experiments/connected-leg-assembly/tests/test_collision_broadphase.py @@ -0,0 +1,169 @@ +import importlib.util +import json +import math +from pathlib import Path +import sys +import time +import unittest + + +EXPERIMENT = Path(__file__).resolve().parents[1] +SPEC = importlib.util.spec_from_file_location( + "connected_leg_collision_broadphase", EXPERIMENT / "collision_broadphase.py" +) +COLLISION = importlib.util.module_from_spec(SPEC) +sys.modules[SPEC.name] = COLLISION +SPEC.loader.exec_module(COLLISION) +CORE = COLLISION._load_core() + + +def _frozen_pair_input(pair): + return pair[0] + pair[1][1:], ((0, 1, 2), (0, 3, 4)) + + +def _frozen_zero_input(pair): + return pair[0] + pair[1], ((0, 1, 2), (3, 4, 5)) + + +def _class_counts(report): + return tuple((stage, report["class_counts"][stage]) + for stage in ("aabb-disjoint", "sat-disjoint", "hit", + "point-only", "excluded-adjacent")) + + +class BroadphaseEquivalenceTests(unittest.TestCase): + def assert_equivalent_to_frozen(self, vertices, triangles, *, block_size=3): + frozen = CORE.intersection_diagnostics( + vertices, triangles, include_classifications=True + ) + actual = COLLISION.collision_report( + vertices, triangles, include_classifications=True, + block_size=block_size, + ) + self.assertEqual(actual["method"], COLLISION.METHOD) + self.assertEqual(actual["pair_count"], frozen["pair_count"]) + self.assertEqual(actual["normalization_scale"], frozen["normalization_scale"]) + self.assertEqual(actual["candidate_pairs"], [list(pair) for pair in frozen["candidate_pairs"]]) + self.assertEqual(actual["hit_pairs"], [list(pair) for pair in frozen["hit_pairs"]]) + self.assertEqual( + actual["classifications"], + [[list(pair), stage] for pair, stage in frozen["classifications"]], + ) + frozen_counts = dict(frozen["pair_policy_evidence"]["class_counts"]) + self.assertEqual(_class_counts(actual), tuple(frozen_counts.items())) + self.assertTrue(actual["pair_partition_complete"], actual) + self.assertTrue(actual["final_classification_partition_complete"], actual) + self.assertEqual(actual["proven_aabb_reject_count"] + + actual["survivor_pair_count"], actual["pair_count"]) + return actual + + def test_frozen_shared_one_and_shared_zero_fixtures_match_exactly(self): + for _fixture_id, pair, _expected in CORE._SHARED_ONE_FIXTURES: + with self.subTest(fixture=_fixture_id): + self.assert_equivalent_to_frozen(*_frozen_pair_input(pair)) + for fixture_id, pair, _expected in CORE._SHARED_ZERO_FIXTURES: + with self.subTest(fixture=fixture_id): + self.assert_equivalent_to_frozen(*_frozen_zero_input(pair)) + + def test_frozen_boundary_duplicate_and_edge_failures_remain_frozen(self): + p0 = CORE._P0 + one = CORE._ONE + fixed_d = CORE._FIXED_D + normal_points = ((p0, p0, p0), (one, p0, p0), (p0, fixed_d, p0)) + with self.assertRaisesRegex(CORE.MeshCorrectnessError, + "normalized triangle normal"): + COLLISION.collision_report(normal_points, ((0, 1, 2),)) + + successor = ((p0, p0, p0), (one, p0, p0), + (p0, float.fromhex("0x1.0000000000000p-45"), p0)) + self.assert_equivalent_to_frozen(successor, ((0, 1, 2),)) + + shared_two = ((p0, p0, p0), (one, p0, p0), (p0, one, p0), + (p0, -one, p0)) + self.assert_equivalent_to_frozen(shared_two, ((0, 1, 2), (1, 0, 3))) + with self.assertRaisesRegex(CORE.MeshCorrectnessError, "shared-two"): + COLLISION.collision_report(shared_two, ((0, 1, 2), (0, 1, 3))) + with self.assertRaisesRegex(CORE.MeshCorrectnessError, "duplicate triangle"): + COLLISION.collision_report( + normal_points[:2] + ((p0, one, p0),), + ((0, 1, 2), (0, 1, 2)), + ) + + def test_translated_scaled_fixture_and_cross_block_order_are_exact(self): + fixture = CORE._SHARED_ONE_FIXTURES[7] + vertices, triangles = _frozen_pair_input(fixture[1]) + self.assert_equivalent_to_frozen(vertices, triangles, block_size=1) + many_vertices = [] + many_triangles = [] + for row in range(11): + offset = len(many_vertices) + x = float(4 * row) + many_vertices.extend(((x, 0.0, 0.0), (x + 1.0, 0.0, 0.0), + (x, 1.0, 0.0))) + many_triangles.append((offset, offset + 1, offset + 2)) + self.assert_equivalent_to_frozen(many_vertices, many_triangles, + block_size=2) + + +class BroadphaseScaleTests(unittest.TestCase): + def test_known_collision_supports_more_than_frozen_triangle_limit(self): + clear_pair = CORE._CLEAR_PAIR + vertices = list(clear_pair[0] + clear_pair[1]) + triangles = [(0, 1, 2), (3, 4, 5)] + for row in range(4095): + offset = len(vertices) + x = 10.0 + 4.0 * row + vertices.extend(((x, 0.0, 0.0), (x + 1.0, 0.0, 0.0), + (x, 1.0, 0.0))) + triangles.append((offset, offset + 1, offset + 2)) + started = time.perf_counter() + report = COLLISION.collision_report(vertices, triangles, block_size=1024) + elapsed = time.perf_counter() - started + print(json.dumps({"known_collision_over_4096_seconds": elapsed, + "triangle_count": report["triangle_count"], + "hit_pairs": report["hit_pairs"]}, sort_keys=True)) + self.assertEqual(report["triangle_count"], 4097) + self.assertTrue(report["local_triangle_limit_exceeded"]) + self.assertEqual(report["hit_pairs"], [[0, 1]]) + self.assertEqual(report["intersection_hit_count"], 1) + self.assertTrue(report["pair_partition_complete"], report) + self.assertTrue(report["final_classification_partition_complete"], report) + self.assertEqual(report["proven_aabb_reject_count"] + + report["survivor_pair_count"], report["pair_count"]) + + def test_actual_004_rest_matches_preserved_fullcoverage_collision_report(self): + run_root = Path( + "/home/ben/.cache/creature-kernel/connected-leg-assembly-004-checked-run" + ) + if not run_root.is_dir(): + self.skipTest("preserved 004 run is unavailable") + run_report = json.loads((run_root / "run-report.json").read_text()) + case_dir = run_root / "cases/case-00-calibrated_ordinary_human" + rest = json.loads((case_dir / "rest.json").read_text()) + preserved = run_report["cases"][0]["poses"][0]["checks"]["metrics"]["collision"] + triangles = [triangle for face in rest["quads"] + for triangle in ((face[0], face[1], face[2]), + (face[0], face[2], face[3]))] + started = time.perf_counter() + actual = COLLISION.collision_report(rest["vertices"], triangles) + elapsed = time.perf_counter() - started + print(json.dumps({"actual_004_rest_seconds": elapsed, + "actual_004_rest_triangles": actual["triangle_count"], + "actual_004_rest_survivors": actual["survivor_pair_count"]}, + sort_keys=True)) + self.assertEqual(actual["pair_count"], preserved["expected_pair_count"]) + self.assertEqual(actual["hit_pairs"], preserved["hit_triangle_pairs"]) + self.assertEqual(actual["intersection_hit_count"], + len(preserved["hit_triangle_pairs"])) + self.assertEqual(preserved["covered_pair_count"], + preserved["expected_pair_count"]) + self.assertTrue(all(call["pair_policy_complete"] + for call in preserved["calls"])) + self.assertTrue(actual["pair_partition_complete"], actual) + self.assertTrue(actual["final_classification_partition_complete"], actual) + self.assertFalse(actual["hit_pairs_truncated"], actual) + self.assertEqual(actual["triangle_count"], 7936) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/connected-leg-assembly/tests/test_construction.py b/experiments/connected-leg-assembly/tests/test_construction.py new file mode 100644 index 0000000..57b01cf --- /dev/null +++ b/experiments/connected-leg-assembly/tests/test_construction.py @@ -0,0 +1,401 @@ +"""Synthetic unit tests for the bounded connected-leg construction.""" +from __future__ import annotations + +import json +import hashlib +import importlib.util +import math +from pathlib import Path +import sys +import unittest + + +HERE = Path(__file__).resolve().parents[1] +if str(HERE) not in sys.path: + sys.path.insert(0, str(HERE)) + +import construction # noqa: E402 + + +def _ring(center: tuple[float, float, float], radius_x: float = 0.2, + radius_z: float = 0.15) -> list[list[float]]: + return [ + [center[0] + radius_x * math.cos(2.0 * math.pi * index / 8.0), + center[1], + center[2] + radius_z * math.sin(2.0 * math.pi * index / 8.0)] + for index in range(8) + ] + + +def _root_mesh() -> tuple[dict, dict]: + left_T = (-0.75, 0.0, 0.0) + right_T = (0.75, 1.0, 0.0) + left_K = (-0.75, -1.0, 0.0) + right_K = (0.75, 0.0, 0.0) + left_A = (-0.55, -1.6, 0.18) + right_A = (0.55, -0.6, 0.18) + left_exit = tuple(left_T[axis] + 0.45 * (left_K[axis] - left_T[axis]) + for axis in range(3)) + right_exit = tuple(right_T[axis] + 0.45 * (right_K[axis] - right_T[axis]) + for axis in range(3)) + left_ring = _ring(left_exit) + right_ring = _ring(right_exit) + vertices = left_ring + right_ring + quads = [ + [index, (index + 1) % 8, 8 + (index + 1) % 8, 8 + index] + for index in range(8) + ] + owners = ["domain.root"] * len(quads) + root_frames = {} + transitions = {} + for side, T, K in (("left", left_T, left_K), ("right", right_T, right_K)): + direction = (0.0, -1.0, 0.0) + exit_point = [T[axis] + 0.45 * (K[axis] - T[axis]) for axis in range(3)] + root_frames[side] = { + "H": list(T), "knee": list(K), "length": 1.0, + "d": list(direction), "X": [1.0, 0.0, 0.0], + "U": [0.0, 1.0, 0.0], "F": [0.0, 0.0, 1.0], + "exit": exit_point, + } + loop = list(range(8)) if side == "left" else [8, 15, 14, 13, 12, 11, 10, 9] + transitions[side] = {"exit": loop} + root = { + "schema": "synthetic.connected-root.v1", + "level": 0, + "vertices": vertices, + "quads": quads, + "face_owners": owners, + "control_owners": ["domain.root"] * len(vertices), + "loops": { + "port.left_thigh": list(range(8)), + "port.right_thigh": [8, 15, 14, 13, 12, 11, 10, 9], + }, + "base_stencils": [[[index, 1.0]] for index in range(len(vertices))], + "frames": root_frames, + "metadata": { + "level": 0, + "admission_status": "accepted", + "admission_failures": [], + "base_control_owners": ["domain.root"] * len(vertices), + "dominant_owner_label": "synthetic root label", + "transition_indices": transitions, + }, + } + inputs = { + "left": { + "J": [-0.8, 0.1, 0.0], "T": list(left_T), "K": list(left_K), + "A": list(left_A), + "radii": {"knee": [0.15, 0.12, 0.13], + "calf": [0.13, 0.11, 0.18], + "ankle": [0.10, 0.09, 0.12]}, + "mid_thigh_factor": 0.85, "support_fraction": 0.10, + "J_role": "synthetic pose-only joint", + "TK_source_role": "synthetic source points", + "distal_design_status": "synthetic context", + }, + "right": { + "J": [0.8, 1.1, 0.0], "T": list(right_T), "K": list(right_K), + "A": list(right_A), + "radii": {"knee": [0.15, 0.12, 0.13], + "calf": [0.13, 0.11, 0.18], + "ankle": [0.10, 0.09, 0.12]}, + "mid_thigh_factor": 0.85, "support_fraction": 0.10, + "J_role": "synthetic pose-only joint", + "TK_source_role": "synthetic source points", + "distal_design_status": "synthetic context", + }, + } + return root, inputs + + +def _closed_cube() -> dict: + vertices = [ + [-1.0, -1.0, -1.0], [1.0, -1.0, -1.0], + [1.0, 1.0, -1.0], [-1.0, 1.0, -1.0], + [-1.0, -1.0, 1.0], [1.0, -1.0, 1.0], + [1.0, 1.0, 1.0], [-1.0, 1.0, 1.0], + ] + return { + "schema": "synthetic.closed-cube.v1", + "level": 0, + "vertices": vertices, + "quads": [ + [0, 3, 2, 1], [4, 5, 6, 7], [0, 1, 5, 4], + [3, 7, 6, 2], [0, 4, 7, 3], [1, 2, 6, 5], + ], + "face_owners": ["domain.cube"] * 6, + "control_owners": ["domain.cube"] * 8, + "loops": {}, + "base_stencils": [[[index, 1.0]] for index in range(8)], + "frames": { + side: { + "H": [0.0, 0.0, 0.0], "d": [0.0, -1.0, 0.0], + "X": [1.0, 0.0, 0.0], "U": [0.0, 1.0, 0.0], + "F": [0.0, 0.0, 1.0], "exit": [0.0, -1.0, 0.0], + "length": 1.0, + } + for side in ("left", "right") + }, + "metadata": { + "level": 0, + "admission_status": "accepted", + "admission_failures": [], + "base_control_owners": ["domain.cube"] * 8, + "base_vertex_count": 8, + "dominant_owner_label": "synthetic cube", + }, + } + + +class ConstructionTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.root, cls.inputs = _root_mesh() + cls.mesh = construction.build(cls.root, cls.inputs) + + def test_checked_in_inputs_parse_authoritative_shape_without_build(self): + with (HERE / "inputs.json").open(encoding="utf-8") as handle: + document = json.load(handle) + for case in document["cases"]: + raw = case["leg_inputs"] + self.assertEqual(set(raw), {"left", "right"}) + parsed = construction._parse_leg_inputs(raw) + for side in ("left", "right"): + self.assertEqual(parsed[side]["J"], tuple(raw[side]["J"])) + self.assertEqual(parsed[side]["T"], tuple(raw[side]["T"])) + self.assertEqual(parsed[side]["K"], tuple(raw[side]["K"])) + self.assertEqual(parsed[side]["A"], tuple(raw[side]["A"])) + self.assertEqual( + parsed[side]["mid_thigh_factor"], + raw[side]["mid_thigh_factor"], + ) + self.assertEqual( + parsed[side]["support_fraction"], + raw[side]["support_fraction"], + ) + self.assertEqual( + parsed[side]["role_metadata"], + {key: raw[side][key] + for key in ("J_role", "TK_source_role", "distal_design_status")}, + ) + + def test_build_preserves_root_and_welds_both_exit_loops(self): + root_count = len(self.root["vertices"]) + root_face_count = len(self.root["quads"]) + self.assertEqual(self.mesh["vertices"][:root_count], self.root["vertices"]) + self.assertEqual(self.mesh["quads"][:root_face_count], self.root["quads"]) + self.assertEqual(self.mesh["face_owners"][:root_face_count], + self.root["face_owners"]) + self.assertNotIn("port.left_thigh", self.mesh["loops"]) + self.assertNotIn("port.right_thigh", self.mesh["loops"]) + self.assertEqual(len(self.mesh["loops"]["port.left_ankle"]), 8) + self.assertEqual(len(self.mesh["loops"]["port.right_ankle"]), 8) + self.assertEqual(len(self.mesh["vertices"]), root_count + 2 * 7 * 8) + self.assertEqual(len(self.mesh["quads"]), root_face_count + 2 * 7 * 8) + self.assertEqual(self.mesh["metadata"]["index_mapping"]["root_vertex_old_to_new"][-1], + [root_count - 1, root_count - 1]) + + def test_metadata_records_exact_sections_frames_and_posterior_calf(self): + for side in ("left", "right"): + chain = self.mesh["metadata"]["chains"][side] + self.assertEqual([row["name"] for row in chain["sections"]], [ + "mid_thigh", "knee_pre_support", "knee", "knee_post_support", + "calf", "ankle_approach", "ankle", + ]) + self.assertAlmostEqual(chain["sections"][1]["fraction"], 0.90) + self.assertAlmostEqual(chain["sections"][3]["fraction"], 0.12) + self.assertEqual(chain["sections"][-1]["indices"], chain["ankle_port"]) + self.assertAlmostEqual(chain["sections"][4]["radii"][2], 0.18) + for row in chain["sections"]: + self.assertEqual(set(row["frame"]), {"tangent", "X", "U", "F"}) + self.assertTrue(all(math.isfinite(value) + for values in row["frame"].values() + for value in values)) + + def test_support_fraction_moves_named_support_rings(self): + inputs = json.loads(json.dumps(self.inputs)) + inputs["left"]["support_fraction"] = 0.20 + mesh = construction.build(self.root, inputs) + for side in ("left", "right"): + sections = mesh["metadata"]["chains"][side]["sections"] + pre_fraction = 0.80 if side == "left" else 0.90 + post_fraction = 0.24 if side == "left" else 0.12 + self.assertAlmostEqual(sections[1]["fraction"], pre_fraction) + self.assertAlmostEqual(sections[3]["fraction"], post_fraction) + T = inputs[side]["T"] + K = inputs[side]["K"] + A = inputs[side]["A"] + expected_pre = [ + T[index] + pre_fraction * (K[index] - T[index]) + for index in range(3) + ] + expected_post = [ + K[index] + post_fraction * (A[index] - K[index]) + for index in range(3) + ] + for actual, expected in zip(sections[1]["centre"], expected_pre): + self.assertAlmostEqual(actual, expected) + for actual, expected in zip(sections[3]["centre"], expected_post): + self.assertAlmostEqual(actual, expected) + self.assertEqual( + sections[2]["frame"], + self.mesh["metadata"]["chains"][side]["sections"][2]["frame"], + ) + + def test_one_side_factor_change_is_consumed_only_by_that_side(self): + inputs = json.loads(json.dumps(self.inputs)) + inputs["right"]["mid_thigh_factor"] = 0.70 + mesh = construction.build(self.root, inputs) + left_chain = mesh["metadata"]["chains"]["left"] + right_chain = mesh["metadata"]["chains"]["right"] + self.assertEqual(left_chain["mid_thigh_factor"], 0.85) + self.assertEqual(right_chain["mid_thigh_factor"], 0.70) + self.assertEqual( + left_chain["sections"][0]["radii"], + self.mesh["metadata"]["chains"]["left"]["sections"][0]["radii"], + ) + self.assertNotEqual( + right_chain["sections"][0]["radii"], + self.mesh["metadata"]["chains"]["right"]["sections"][0]["radii"], + ) + + def test_unknown_numeric_control_is_rejected(self): + inputs = json.loads(json.dumps(self.inputs)) + inputs["left"]["unadmitted_numeric_control"] = 1.0 + with self.assertRaises(construction.ConstructionError): + construction._parse_leg_inputs(inputs) + + def test_reverse_root_winding_keeps_every_band_non_crossed(self): + root = json.loads(json.dumps(self.root)) + root["quads"] = [list(reversed(face)) for face in root["quads"]] + mesh = construction.build(root, self.inputs) + for side in ("left", "right"): + chain = mesh["metadata"]["chains"][side] + self.assertEqual(chain["root_edge_winding"], -1) + rings = [chain["root_exit"]] + [ + section["indices"] for section in chain["sections"] + ] + face_index = chain["new_face_indices"][0] + for source, target in zip(rings, rings[1:]): + for corner in range(8): + expected = [ + source[corner], + source[(corner + 1) % 8], + target[(corner + 1) % 8], + target[corner], + ] + self.assertEqual(mesh["quads"][face_index], expected) + face_index += 1 + + def test_output_is_json_compatible_and_l0_stencils_are_identity(self): + encoded = json.dumps(self.mesh, allow_nan=False, sort_keys=True) + self.assertTrue(encoded) + for index, stencil in enumerate(self.mesh["base_stencils"]): + self.assertEqual(stencil, [[index, 1.0]]) + + def test_evaluate_propagates_generic_lineage_and_new_boundary_loops(self): + levels = construction.evaluate(self.mesh, levels=2) + self.assertEqual(len(levels), 3) + self.assertEqual([level["metadata"]["level"] for level in levels], [0, 1, 2]) + self.assertEqual(len(levels[1]["loops"]["port.left_ankle"]), 16) + self.assertEqual(len(levels[2]["loops"]["port.right_ankle"]), 32) + l0_count = len(self.mesh["vertices"]) + for level in levels[1:]: + self.assertEqual(len(level["base_stencils"]), len(level["vertices"])) + for stencil in level["base_stencils"]: + self.assertAlmostEqual(sum(term[1] for term in stencil), 1.0) + self.assertTrue(all(0 <= term[0] < l0_count and term[1] >= 0.0 + for term in stencil)) + self.assertNotIn("port.left_thigh", levels[2]["loops"]) + self.assertNotIn("port.right_thigh", levels[2]["loops"]) + self.assertEqual(json.dumps(levels, allow_nan=False)[:1], "[") + + def test_closed_cube_uses_same_cc_counts_and_valid_stencils(self): + levels = construction.evaluate(_closed_cube(), levels=2) + self.assertEqual([len(level["vertices"]) for level in levels], [8, 26, 98]) + self.assertEqual([len(level["quads"]) for level in levels], [6, 24, 96]) + for level_index, level in enumerate(levels): + self.assertEqual(level["loops"], {}) + self.assertEqual(level["metadata"]["level"], level_index) + for stencil in level["base_stencils"]: + self.assertAlmostEqual(sum(term[1] for term in stencil), 1.0) + self.assertTrue(all(0 <= term[0] < 8 and term[1] >= 0.0 + for term in stencil)) + + def test_open_output_matches_frozen_generic_numeric_hash(self): + actual = construction.evaluate(self.mesh, levels=2) + generic = construction._load_generic_transition() + expected = generic.evaluate(self.mesh, levels=2) + actual_bytes = json.dumps(actual, sort_keys=True, allow_nan=False).encode() + expected_bytes = json.dumps(expected, sort_keys=True, allow_nan=False).encode() + self.assertEqual(hashlib.sha256(actual_bytes).hexdigest(), + hashlib.sha256(expected_bytes).hexdigest()) + + def test_closed_mesh_missing_declared_loop_is_rejected(self): + hostile = _closed_cube() + hostile["quads"] = hostile["quads"][:-1] + hostile["face_owners"] = hostile["face_owners"][:-1] + with self.assertRaisesRegex(construction.ConstructionError, + "declared loops do not cover"): + construction.evaluate(hostile, levels=2) + + def test_frame_admission_rejects_missing_malformed_and_nonfinite_metadata(self): + missing = _closed_cube() + del missing["frames"]["right"] + with self.assertRaisesRegex(construction.ConstructionError, + "frames must contain exactly"): + construction.evaluate(missing, levels=0) + + malformed = _closed_cube() + malformed["frames"]["left"] = [] + with self.assertRaisesRegex(construction.ConstructionError, + "frames.left must be a mapping"): + construction.evaluate(malformed, levels=0) + + nonfinite = _closed_cube() + nonfinite["frames"]["right"]["H"][0] = float("nan") + with self.assertRaisesRegex(construction.ConstructionError, + "frames.right.H\[0\]"): + construction.evaluate(nonfinite, levels=0) + + def test_closed_evaluator_cache_isolated_between_loaded_constructions(self): + names = ("_ck_construction_cache_isolation_one", + "_ck_construction_cache_isolation_two") + loaded = [] + evaluators = [] + try: + for name in names: + sys.modules.pop(name, None) + spec = importlib.util.spec_from_file_location( + name, HERE / "construction.py") + self.assertIsNotNone(spec) + self.assertIsNotNone(spec.loader) + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + loaded.append(module) + evaluators.append(module._load_closed_generic_transition()) + + self.assertIsNot(evaluators[0], evaluators[1]) + self.assertNotEqual(evaluators[0].__name__, evaluators[1].__name__) + self.assertIs(evaluators[0]._validate_mesh, + loaded[0]._closed_generic_validation) + self.assertIs(evaluators[1]._validate_mesh, + loaded[1]._closed_generic_validation) + finally: + for module in evaluators + loaded: + sys.modules.pop(module.__name__, None) + + def test_incompatible_root_or_zero_leg_segment_fails_closed(self): + bad_inputs = json.loads(json.dumps(self.inputs)) + bad_inputs["left"]["T"][1] = 0.1 + with self.assertRaises(construction.ConstructionError): + construction.build(self.root, bad_inputs) + bad_inputs = json.loads(json.dumps(self.inputs)) + bad_inputs["right"]["A"] = bad_inputs["right"]["K"] + with self.assertRaises(construction.ConstructionError): + construction.build(self.root, bad_inputs) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/connected-leg-assembly/tests/test_foot_attachment_construction.py b/experiments/connected-leg-assembly/tests/test_foot_attachment_construction.py new file mode 100644 index 0000000..3484138 --- /dev/null +++ b/experiments/connected-leg-assembly/tests/test_foot_attachment_construction.py @@ -0,0 +1,174 @@ +"""Focused FOOT-005 attachment-only tests. + +Raman owns execution. These tests are intentionally written before the +capture and must not be run as part of this implementation handoff. +""" +from __future__ import annotations + +import hashlib +import inspect +import json +from pathlib import Path +import sys +import unittest + + +EXPERIMENT_DIR = Path(__file__).resolve().parents[1] +if str(EXPERIMENT_DIR) not in sys.path: + sys.path.insert(0, str(EXPERIMENT_DIR)) + +import construction # noqa: E402 +import foot_attachment_construction # noqa: E402 +import foot_form_construction # noqa: E402 + + +INPUTS_PATH = EXPERIMENT_DIR / "inputs.json" +FORM_INPUTS_PATH = EXPERIMENT_DIR / "foot-form-inputs.json" +ATTACHMENT_INPUTS_PATH = EXPERIMENT_DIR / "foot-attachment-inputs.json" +EXPECTED_CASES = ( + "calibrated_ordinary_human", + "calibrated_upright_anthropomorphic", +) +RETAINED_PORTS = {"port.neck", "port.left_arm", "port.right_arm"} + + +def _sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def _cases(): + document = json.loads(INPUTS_PATH.read_text(encoding="utf-8")) + form_document = json.loads(FORM_INPUTS_PATH.read_text(encoding="utf-8")) + attachment_inputs = json.loads(ATTACHMENT_INPUTS_PATH.read_text(encoding="utf-8")) + forms = {row["case_id"]: row for row in form_document["cases"]} + rows = [] + for case in document["cases"]: + if case["id"] not in EXPECTED_CASES: + continue + root_path = Path(case["root_mesh"]["path"]) + if _sha256(root_path) != case["root_mesh"]["sha256"]: + raise AssertionError(f"immutable root identity drifted: {root_path}") + rows.append(( + case["id"], + construction.build(json.loads(root_path.read_text(encoding="utf-8")), + case["leg_inputs"]), + case["leg_inputs"], + forms[case["id"]], + )) + if tuple(row[0] for row in rows) != EXPECTED_CASES: + raise AssertionError("the two canonical connected-leg cases were not loaded") + return rows, attachment_inputs + + +class ConnectorSeamTests(unittest.TestCase): + def test_default_builder_seam_preserves_old_collar_formula(self): + base_vertices = [(float(index), 0.0, 0.0) for index in range(8)] + hole_points = [(float(index), 10.0, 0.0) for index in range(8)] + appended = [] + + def append_vertex(point): + appended.append(tuple(point)) + return 8 + len(appended) - 1 + + result = foot_form_construction._default_connector_builder({ + "append_vertex": append_vertex, + "semantic_ankle": list(range(8)), + "hole_points": hole_points, + "hole_indices": list(range(16, 24)), + "orientation": 1, + "base_vertices": base_vertices, + "form": {"construction": {"collar_fraction": 0.20}}, + }) + self.assertIsNone(inspect.signature(foot_form_construction.build) + .parameters["connector_builder"].default) + self.assertEqual(result["ring_order"], ["collar"]) + self.assertEqual(result["band_order"], ["ankle_to_collar", "collar_to_hole"]) + self.assertEqual(appended[0], (0.0, 2.0, 0.0)) + self.assertEqual(appended[-1], (7.0, 2.0, 0.0)) + + def test_explicit_default_callback_matches_implicit_foot004_for_human(self): + cases, _attachment_inputs = _cases() + case_id, base, leg_inputs, form_inputs = cases[0] + self.assertEqual(case_id, "calibrated_ordinary_human") + implicit = foot_form_construction.build(base, leg_inputs, form_inputs) + explicit = foot_form_construction.build( + base, leg_inputs, form_inputs, + connector_builder=foot_form_construction._default_connector_builder, + ) + self.assertEqual(explicit, implicit) + + +class FootAttachmentConstructionTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cases, cls.attachment_inputs = _cases() + cls.outputs = [] + for case_id, base, leg_inputs, form_inputs in cls.cases: + output = foot_attachment_construction.build( + base, leg_inputs, form_inputs, cls.attachment_inputs + ) + levels = foot_attachment_construction.evaluate(output, levels=2) + cls.outputs.append((case_id, base, leg_inputs, form_inputs, output, levels)) + + def test_counts_prefix_ports_and_evaluation(self): + self.assertEqual(len(self.outputs), 2) + for case_id, base, _leg_inputs, _form_inputs, output, levels in self.outputs: + with self.subTest(case=case_id): + self.assertEqual((len(base["vertices"]), len(base["quads"])), (264, 248)) + self.assertEqual((len(output["vertices"]), len(output["quads"])), (454, 428)) + self.assertEqual([level["metadata"]["level"] for level in levels], [0, 1, 2]) + self.assertEqual(set(output["loops"]), RETAINED_PORTS) + self.assertEqual(output["vertices"][:264], base["vertices"]) + self.assertEqual(output["quads"][:248], base["quads"]) + + def test_two_support_rings_replace_old_collar(self): + for case_id, _base, _leg_inputs, _form_inputs, output, _levels in self.outputs: + for side in ("left", "right"): + with self.subTest(case=case_id, side=side): + foot = output["metadata"]["feet"][side] + self.assertNotIn("collar", foot["attachment_loop"]) + self.assertEqual(foot["ring_order"][-2:], ["support_s0", "support_s1"]) + self.assertEqual(set(foot["attachment_loop"]) - + {"ankle", "hole", "support_s0", "support_s1"}, set()) + for name in ("ankle_to_s0", "s0_to_s1", "s1_to_hole"): + self.assertEqual(len(foot["face_owner_ranges"][name]), 8) + self.assertNotIn("ankle_to_collar", foot["face_owner_ranges"]) + self.assertNotIn("collar_to_hole", foot["face_owner_ranges"]) + self.assertEqual(len(foot["new_vertex_indices"]), 95) + self.assertEqual(len(foot["new_face_indices"]), 90) + + def test_endpoints_bulk_source_and_explicit_diagnostics_are_preserved(self): + for case_id, base, _leg_inputs, form_inputs, output, _levels in self.outputs: + for side in ("left", "right"): + with self.subTest(case=case_id, side=side): + foot = output["metadata"]["feet"][side] + self.assertEqual(foot["attachment_loop"]["ankle"], + foot["ankle_source_loop"]) + self.assertEqual(len(foot["attachment_loop"]["hole"]), 8) + self.assertEqual(foot["source_form"]["local_controls"], + form_inputs["sides"][side]) + candidate = foot["attachment_candidate"] + self.assertEqual(len(candidate["diagnostics"]), 8) + self.assertIn("chord_dot_d_in", candidate["diagnostics"][0]) + self.assertIn("chord_dot_c_out", candidate["diagnostics"][0]) + self.assertIn("boundary_previous_direction", candidate["diagnostics"][0]) + self.assertIn("boundary_next_direction", candidate["diagnostics"][0]) + self.assertEqual(candidate["diagnostic_policy"].split(", ")[0], + "chord/conormal/adjacent-direction dots are evidence only") + self.assertEqual(output["vertices"][:len(base["vertices"])], + base["vertices"]) + + def test_mirrored_cases_keep_shared_lengths_and_support_correspondence(self): + for case_id, _base, _leg_inputs, _form_inputs, output, _levels in self.outputs: + left = output["metadata"]["feet"]["left"]["attachment_candidate"]["diagnostics"] + right = output["metadata"]["feet"]["right"]["attachment_candidate"]["diagnostics"] + for left_row, right_row in zip(left, right): + with self.subTest(case=case_id, sector=left_row["sector"]): + self.assertAlmostEqual(left_row["chord_length"], right_row["chord_length"]) + self.assertAlmostEqual(left_row["l0"], right_row["l0"]) + self.assertAlmostEqual(left_row["l1"], right_row["l1"]) + self.assertEqual(left_row["name"], right_row["name"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/connected-leg-assembly/tests/test_foot_construction.py b/experiments/connected-leg-assembly/tests/test_foot_construction.py new file mode 100644 index 0000000..ed04232 --- /dev/null +++ b/experiments/connected-leg-assembly/tests/test_foot_construction.py @@ -0,0 +1,369 @@ +"""Bounded tests for the connected coarse foot prerequisite.""" +from __future__ import annotations + +import copy +import hashlib +import json +import math +from pathlib import Path +import sys +import unittest + + +EXPERIMENT_DIR = Path(__file__).resolve().parents[1] +if str(EXPERIMENT_DIR) not in sys.path: + sys.path.insert(0, str(EXPERIMENT_DIR)) + +import construction # noqa: E402 +import foot_construction # noqa: E402 + + +INPUTS_PATH = EXPERIMENT_DIR / "inputs.json" +FOOT_INPUTS_PATH = EXPERIMENT_DIR / "foot-inputs.json" +EXPECTED_CASES = ( + "calibrated_ordinary_human", + "calibrated_upright_anthropomorphic", +) +RETAINED_PORTS = {"port.neck", "port.left_arm", "port.right_arm"} + + +def _sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def _actual_cases() -> list[tuple[str, dict, dict, dict, dict]]: + document = json.loads(INPUTS_PATH.read_text(encoding="utf-8")) + foot_document = json.loads(FOOT_INPUTS_PATH.read_text(encoding="utf-8")) + foot_rows = {row["case_id"]: row["sides"] for row in foot_document["cases"]} + result = [] + for case in document["cases"]: + case_id = case["id"] + if case_id not in EXPECTED_CASES: + continue + root_ref = case["root_mesh"] + root_path = Path(root_ref["path"]) + if _sha256(root_path) != root_ref["sha256"]: + raise AssertionError(f"immutable root identity drifted: {root_path}") + root = json.loads(root_path.read_text(encoding="utf-8")) + leg_inputs = case["leg_inputs"] + base = construction.build(root, leg_inputs) + result.append((case_id, base, leg_inputs, foot_rows[case_id], root)) + if tuple(row[0] for row in result) != EXPECTED_CASES: + raise AssertionError("the two canonical connected-leg cases were not loaded") + return result + + +def _edge_uses(quads): + uses = {} + for face_index, face in enumerate(quads): + for index, left in enumerate(face): + right = face[(index + 1) % 4] + edge = tuple(sorted((left, right))) + uses.setdefault(edge, []).append((face_index, left, right)) + return uses + + +class FootConstructionTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cases = _actual_cases() + cls.outputs = [] + for case_id, base, leg_inputs, foot_inputs, _root in cls.cases: + output = foot_construction.build(base, leg_inputs, foot_inputs) + levels = foot_construction.evaluate(output, levels=2) + cls.outputs.append((case_id, base, leg_inputs, foot_inputs, output, levels)) + + def test_longitudinal_candidate_runs_both_actual_cases_and_evaluates(self): + self.assertEqual(len(self.outputs), 2) + for case_id, base, _leg_inputs, _foot_inputs, output, levels in self.outputs: + with self.subTest(case=case_id): + self.assertEqual(len(base["vertices"]), 264) + self.assertEqual(len(base["quads"]), 248) + self.assertEqual(len(output["vertices"]), 438) + self.assertEqual(len(output["quads"]), 428) + self.assertEqual([level["metadata"]["level"] for level in levels], [0, 1, 2]) + for parent, child in zip(levels, levels[1:]): + edge_count = len(_edge_uses(parent["quads"])) + self.assertEqual(len(child["vertices"]), + len(parent["vertices"]) + edge_count + len(parent["quads"])) + self.assertEqual(set(output["loops"]), RETAINED_PORTS) + self.assertEqual(set(levels[2]["loops"]), RETAINED_PORTS) + + def test_closed_feet_are_manifold_wound_and_connected(self): + for case_id, _base, _leg_inputs, _foot_inputs, output, _levels in self.outputs: + with self.subTest(case=case_id): + uses = _edge_uses(output["quads"]) + self.assertTrue(all(len(rows) in (1, 2) for rows in uses.values())) + boundary = {edge for edge, rows in uses.items() if len(rows) == 1} + declared = set() + for loop in output["loops"].values(): + for index, left in enumerate(loop): + declared.add(tuple(sorted((left, loop[(index + 1) % len(loop)])))) + self.assertEqual(boundary, declared) + self.assertTrue(all(len(rows) == 2 for edge, rows in uses.items() + if any(index >= 264 for index in edge))) + self.assertNotIn("port.left_ankle", output["loops"]) + self.assertNotIn("port.right_ankle", output["loops"]) + for side in ("left", "right"): + foot = output["metadata"]["feet"][side] + self.assertEqual(len(foot["new_vertex_indices"]), 87) + self.assertEqual(len(foot["new_face_indices"]), 90) + self.assertEqual(foot["winding"]["output_orientation"], 1) + + def test_source_anchors_and_longitudinal_grid_have_meaningful_positions(self): + for case_id, _base, leg_inputs, foot_inputs, output, _levels in self.outputs: + for side in ("left", "right"): + with self.subTest(case=case_id, side=side): + foot = output["metadata"]["feet"][side] + controls = foot_inputs[side] + x = leg_inputs[side]["A"][0] + anchors = foot["source_anchors"] + for name in ("H", "B", "T"): + self.assertEqual(anchors[name], [x, controls[name]["plantar_y"], controls[name]["z"]]) + rows = foot["longitudinal_rows"] + self.assertEqual([row["name"] for row in rows], list( + foot_construction._LONGITUDINAL_ROW_NAMES + )) + self.assertEqual([row["z_formula"] for row in rows], list( + foot_construction._LONGITUDINAL_ROW_FORMULAS + )) + self.assertEqual([row["source_role"] for row in rows], list( + foot_construction._LONGITUDINAL_ROW_ROLES + )) + self.assertEqual(foot["lateral_fractions"], list( + foot_construction._LATERAL_FRACTIONS + )) + dorsal = foot["grid_indices"]["dorsal"] + plantar = foot["grid_indices"]["plantar"] + self.assertEqual(len(dorsal), 8) + self.assertEqual(len(plantar), 8) + self.assertIsNone(dorsal[2][2]) + self.assertEqual(len(foot["ring_indices_by_name"]["dorsal_grid"]), 39) + self.assertEqual(len(foot["ring_indices_by_name"]["plantar_grid"]), 40) + self.assertEqual(len(foot["attachment_loop"]["hole"]), 8) + self.assertEqual(foot["attachment_loop"]["hole"], + foot["ring_indices_by_name"]["ankle_hole"]) + self.assertEqual(foot["attachment_loop"]["ankle"], + foot["ankle_source_loop"]) + self.assertEqual( + foot["correspondence"]["target_order"], + list(foot_construction._HOLE_BOUNDARY_NAMES), + ) + self.assertGreater(foot["correspondence"]["score"], + foot["correspondence"]["runner_up_score"]) + + def test_longitudinal_rows_follow_declared_source_profiles(self): + def source_dorsal(z, controls): + H, B, T = (controls[name] for name in ("H", "B", "T")) + if z <= B["z"]: + left, right = H, B + else: + left, right = B, T + fraction = (z - left["z"]) / (right["z"] - left["z"]) + left_y = left["plantar_y"] + left["dorsalthickness"] + right_y = right["plantar_y"] + right["dorsalthickness"] + return left_y + fraction * (right_y - left_y) + + def source_plantar(z, controls): + H, B, T = (controls[name] for name in ("H", "B", "T")) + if z <= B["z"]: + left, right = H, B + else: + left, right = B, T + fraction = (z - left["z"]) / (right["z"] - left["z"]) + return left["plantar_y"] + fraction * (right["plantar_y"] - left["plantar_y"]) + + for case_id, _base, _leg_inputs, foot_inputs, output, _levels in self.outputs: + for side in ("left", "right"): + with self.subTest(case=case_id, side=side): + foot = output["metadata"]["feet"][side] + controls = foot_inputs[side] + A = _leg_inputs[side]["A"] + rows = foot["longitudinal_rows"] + expected_z = [ + controls["H"]["z"], + 0.5 * (controls["H"]["z"] + A[2]), + A[2], + A[2] + 0.25 * (controls["B"]["z"] - A[2]), + A[2] + 0.625 * (controls["B"]["z"] - A[2]), + controls["B"]["z"], + 0.5 * (controls["B"]["z"] + controls["T"]["z"]), + controls["T"]["z"], + ] + for row, z in zip(rows, expected_z): + self.assertAlmostEqual(row["z"], z) + if z <= controls["B"]["z"]: + u = (z - controls["H"]["z"]) / (controls["B"]["z"] - controls["H"]["z"]) + expected_width = controls["H"]["halfwidth"] + u * u * ( + controls["B"]["halfwidth"] - controls["H"]["halfwidth"] + ) + else: + u = (z - controls["B"]["z"]) / (controls["T"]["z"] - controls["B"]["z"]) + expected_width = controls["B"]["halfwidth"] + u * ( + controls["T"]["halfwidth"] - controls["B"]["halfwidth"] + ) + self.assertAlmostEqual(row["halfwidth"], expected_width) + + for row_index, row_indices in enumerate(foot["grid_indices"]["dorsal"]): + for column, index in enumerate(row_indices): + if index is None: + continue + top = output["vertices"][index] + bottom = output["vertices"][foot["grid_indices"]["plantar"][row_index][column]] + self.assertAlmostEqual(top[1], source_dorsal(rows[row_index]["z"], controls)) + self.assertAlmostEqual(bottom[1], source_plantar(rows[row_index]["z"], controls)) + self.assertAlmostEqual(top[0], bottom[0]) + self.assertAlmostEqual(top[2], bottom[2]) + + def test_dorsal_hole_and_grid_face_ranges_are_conforming(self): + for case_id, _base, _leg_inputs, _foot_inputs, output, _levels in self.outputs: + for side in ("left", "right"): + with self.subTest(case=case_id, side=side): + foot = output["metadata"]["feet"][side] + self.assertEqual(len(foot["attachment_loop"]["hole"]), 8) + self.assertEqual( + foot["ring_order"], + ["dorsal_grid", "plantar_grid", "ankle_hole", "collar"], + ) + ranges = foot["face_owner_ranges"] + self.assertEqual(len(ranges["dorsal_grid"]), 24) + self.assertEqual(len(ranges["plantar_grid"]), 28) + self.assertEqual(len(ranges["outer_perimeter"]), 22) + self.assertEqual(len(ranges["ankle_to_collar"]), 8) + self.assertEqual(len(ranges["collar_to_hole"]), 8) + + def test_source_profiles_reject_out_of_range_z(self): + _case_id, _base, _leg_inputs, foot_inputs, _output, _levels = self.outputs[0] + with self.assertRaises(foot_construction.FootConstructionError): + foot_construction._source_profile( + foot_inputs["left"]["H"]["z"] - 1.0, + foot_inputs["left"], + "dorsal_y", + "left", + ) + with self.assertRaises(foot_construction.FootConstructionError): + foot_construction._source_profile( + foot_inputs["left"]["T"]["z"] + 1.0, + foot_inputs["left"], + "plantar_y", + "left", + ) + + def test_old_prefix_and_three_ports_are_preserved_exactly(self): + for _case_id, base, _leg_inputs, _foot_inputs, output, _levels in self.outputs: + self.assertEqual(output["vertices"][:264], base["vertices"]) + self.assertEqual(output["quads"][:248], base["quads"]) + self.assertEqual(output["face_owners"][:248], base["face_owners"]) + self.assertEqual(output["control_owners"][:264], base["control_owners"]) + for name in RETAINED_PORTS: + self.assertEqual(output["loops"][name], base["loops"][name]) + self.assertNotIn("weights", output) + self.assertNotIn("base_weights", output) + + def test_phase_resolution_does_not_assume_a0_is_d0(self): + _case_id, base, leg_inputs, foot_inputs, _output, _levels = self.outputs[0] + shifted = copy.deepcopy(base) + side = "left" + original = list(shifted["loops"]["port.left_ankle"]) + shifted_loop = original[3:] + original[:3] + shifted["loops"]["port.left_ankle"] = shifted_loop + shifted["metadata"]["chains"][side]["ankle_port"] = list(shifted_loop) + for section in shifted["metadata"]["chains"][side]["sections"]: + if section["name"] == "ankle": + section["indices"] = list(shifted_loop) + output = foot_construction.build(shifted, leg_inputs, foot_inputs) + correspondence = output["metadata"]["feet"][side]["correspondence"] + self.assertEqual(correspondence["target_to_ankle_indices"][0], original[0]) + self.assertNotEqual(shifted_loop[0], correspondence["target_to_ankle_indices"][0]) + + def test_reversed_attached_loop_resolves_reverse_output_winding(self): + _case_id, base, leg_inputs, foot_inputs, _output, _levels = self.outputs[0] + reversed_base = copy.deepcopy(base) + side = "right" + original = list(reversed_base["loops"]["port.right_ankle"]) + reversed_loop = list(reversed(original)) + reversed_base["loops"]["port.right_ankle"] = reversed_loop + reversed_base["metadata"]["chains"][side]["ankle_port"] = list(reversed_loop) + for section in reversed_base["metadata"]["chains"][side]["sections"]: + if section["name"] == "ankle": + section["indices"] = list(reversed_loop) + output = foot_construction.build(reversed_base, leg_inputs, foot_inputs) + foot = output["metadata"]["feet"][side] + self.assertEqual(foot["correspondence"]["direction"], -1) + self.assertEqual(foot["winding"]["attached_ankle_loop"], -1) + self.assertEqual(foot["winding"]["output_orientation"], 1) + self.assertEqual(set(output["loops"]), RETAINED_PORTS) + + def test_invalid_foot_relationships_and_schema_fail_closed(self): + _case_id, base, leg_inputs, foot_inputs, _output, _levels = self.outputs[0] + bad = copy.deepcopy(foot_inputs) + bad["left"]["B"]["z"] = leg_inputs["left"]["A"][2] + with self.assertRaises(foot_construction.FootConstructionError): + foot_construction.build(base, leg_inputs, bad) + + bad = copy.deepcopy(foot_inputs) + bad["right"]["B"]["halfwidth"] = 0.001 + with self.assertRaises(foot_construction.FootConstructionError): + foot_construction.build(base, leg_inputs, bad) + + bad = copy.deepcopy(foot_inputs) + bad["left"]["unsupported"] = True + with self.assertRaises(foot_construction.FootConstructionError): + foot_construction.build(base, leg_inputs, bad) + + bad_leg_inputs = copy.deepcopy(leg_inputs) + bad_leg_inputs["left"]["unexpected"] = 1.0 + with self.assertRaises(foot_construction.FootConstructionError): + foot_construction.build(base, bad_leg_inputs, foot_inputs) + + def test_nonfinite_and_degenerate_foot_geometry_fail_closed(self): + _case_id, base, leg_inputs, foot_inputs, _output, _levels = self.outputs[0] + bad = copy.deepcopy(foot_inputs) + bad["left"]["T"]["dorsalthickness"] = float("nan") + with self.assertRaises(foot_construction.FootConstructionError): + foot_construction.build(base, leg_inputs, bad) + + bad = copy.deepcopy(foot_inputs) + bad["right"]["T"]["z"] = bad["right"]["B"]["z"] + with self.assertRaises(foot_construction.FootConstructionError): + foot_construction.build(base, leg_inputs, bad) + + def test_frozen_core_catches_second_triangle_only_hit(self): + vertices = [ + (0.0, 0.0, 0.0), (2.0, 0.0, 0.0), (2.0, 2.0, 0.0), + (0.0, 2.0, 0.0), (0.2, 1.2, -1.0), (0.2, 1.5, 1.0), + (0.8, 1.2, 0.0), (10.0, 10.0, 10.0), + ] + quads = [(0, 1, 2, 3), (4, 5, 6, 7)] + with self.assertRaisesRegex( + foot_construction.FootConstructionError, + r"triangle hit \(1, 2\) maps to quad faces \(0, 1\)"): + foot_construction._validate_intersections(vertices, quads, 1, [1], "left") + + def test_frozen_core_catches_one_shared_vertex_hit(self): + vertices = [ + (0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0), + (10.0, 10.0, 10.0), (1.0, 1.0, 0.0), (0.0, 0.0, 1.0), + (10.0, -10.0, 10.0), + ] + quads = [(0, 1, 2, 3), (0, 4, 5, 6)] + with self.assertRaisesRegex( + foot_construction.FootConstructionError, + r"triangle hit \(0, 2\) maps to quad faces \(0, 1\)"): + foot_construction._validate_intersections(vertices, quads, 1, [1], "left") + + def test_l2_stencils_remain_finite_and_partitioned(self): + for case_id, _base, _leg_inputs, _foot_inputs, _output, levels in self.outputs: + for level in levels: + with self.subTest(case=case_id, level=level["metadata"]["level"]): + self.assertEqual(len(level["base_stencils"]), len(level["vertices"])) + for stencil in level["base_stencils"]: + total = sum(float(term[1]) for term in stencil) + self.assertTrue(math.isfinite(total)) + self.assertAlmostEqual(total, 1.0, places=9) + self.assertTrue(all(term[0] >= 0 and term[1] >= -1.0e-10 + for term in stencil)) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/connected-leg-assembly/tests/test_foot_form_construction.py b/experiments/connected-leg-assembly/tests/test_foot_form_construction.py new file mode 100644 index 0000000..945e732 --- /dev/null +++ b/experiments/connected-leg-assembly/tests/test_foot_form_construction.py @@ -0,0 +1,221 @@ +"""Focused FOOT-004 source/form candidate tests. + +These tests are execution-owned by Raman. They deliberately use only the +two canonical synthetic/calibrated experiment cases and the frozen generic +connected-leg evaluator; no body construction or pose is included. +""" +from __future__ import annotations + +import copy +import hashlib +import json +from pathlib import Path +import sys +import unittest + + +EXPERIMENT_DIR = Path(__file__).resolve().parents[1] +if str(EXPERIMENT_DIR) not in sys.path: + sys.path.insert(0, str(EXPERIMENT_DIR)) + +import construction # noqa: E402 +import foot_form_construction # noqa: E402 + + +INPUTS_PATH = EXPERIMENT_DIR / "inputs.json" +FORM_INPUTS_PATH = EXPERIMENT_DIR / "foot-form-inputs.json" +EXPECTED_CASES = ( + "calibrated_ordinary_human", + "calibrated_upright_anthropomorphic", +) +RETAINED_PORTS = {"port.neck", "port.left_arm", "port.right_arm"} + + +def _sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def _actual_cases() -> list[tuple[str, dict, dict, dict]]: + document = json.loads(INPUTS_PATH.read_text(encoding="utf-8")) + form_document = json.loads(FORM_INPUTS_PATH.read_text(encoding="utf-8")) + form_rows = {row["case_id"]: row for row in form_document["cases"]} + result = [] + for case in document["cases"]: + case_id = case["id"] + if case_id not in EXPECTED_CASES: + continue + root_ref = case["root_mesh"] + root_path = Path(root_ref["path"]) + if _sha256(root_path) != root_ref["sha256"]: + raise AssertionError(f"immutable root identity drifted: {root_path}") + root = json.loads(root_path.read_text(encoding="utf-8")) + leg_inputs = case["leg_inputs"] + if case_id not in form_rows: + raise AssertionError(f"FOOT-004 inputs lack case {case_id}") + base = construction.build(root, leg_inputs) + result.append((case_id, base, leg_inputs, form_rows[case_id])) + if tuple(row[0] for row in result) != EXPECTED_CASES: + raise AssertionError("the two canonical connected-leg cases were not loaded") + return result + + +def _edge_uses(quads): + uses = {} + for face_index, face in enumerate(quads): + for index, left in enumerate(face): + right = face[(index + 1) % len(face)] + edge = tuple(sorted((left, right))) + uses.setdefault(edge, []).append((face_index, left, right)) + return uses + + +class SourceFrameTests(unittest.TestCase): + def test_source_frame_uses_attachment_x_not_leg_summary_x(self): + """A mocked terminal frame may differ from the construction summary.""" + attachment_x = (0.6, 0.0, 0.8) + source = foot_form_construction._source_frame( + {"frames": {"left": {"X": [1.0, 0.0, 0.0]}}}, + "left", + {"X": attachment_x}, + ) + self.assertEqual(source["X"], attachment_x) + self.assertAlmostEqual(source["U"][1], 1.0) + self.assertAlmostEqual(source["F"][2], 0.6) + + +class FootFormConstructionTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cases = _actual_cases() + cls.outputs = [] + for case_id, base, leg_inputs, form_inputs in cls.cases: + output = foot_form_construction.build(base, leg_inputs, form_inputs) + levels = foot_form_construction.evaluate(output, levels=2) + cls.outputs.append((case_id, base, leg_inputs, form_inputs, output, levels)) + + def test_candidate_preserves_prefix_counts_ports_and_evaluation(self): + self.assertEqual(len(self.outputs), 2) + for case_id, base, _leg_inputs, _form_inputs, output, levels in self.outputs: + with self.subTest(case=case_id): + self.assertEqual((len(base["vertices"]), len(base["quads"])), (264, 248)) + self.assertEqual((len(output["vertices"]), len(output["quads"])), (438, 428)) + self.assertEqual([level["metadata"]["level"] for level in levels], [0, 1, 2]) + self.assertEqual(set(output["loops"]), RETAINED_PORTS) + self.assertEqual(set(levels[2]["loops"]), RETAINED_PORTS) + self.assertEqual(output["vertices"][:264], base["vertices"]) + self.assertEqual(output["quads"][:248], base["quads"]) + + def test_reused_grid_is_closed_and_metadata_is_explicit(self): + for case_id, _base, _leg_inputs, _form_inputs, output, _levels in self.outputs: + with self.subTest(case=case_id): + uses = _edge_uses(output["quads"]) + boundary = {edge for edge, rows in uses.items() if len(rows) == 1} + declared = set() + for loop in output["loops"].values(): + for index, left in enumerate(loop): + declared.add(tuple(sorted((left, loop[(index + 1) % len(loop)])))) + self.assertEqual(boundary, declared) + self.assertTrue(all(len(rows) == 2 for edge, rows in uses.items() + if any(index >= 264 for index in edge))) + self.assertNotIn("port.left_ankle", output["loops"]) + self.assertNotIn("port.right_ankle", output["loops"]) + for side in ("left", "right"): + foot = output["metadata"]["feet"][side] + self.assertEqual(len(foot["new_vertex_indices"]), 87) + self.assertEqual(len(foot["new_face_indices"]), 90) + self.assertEqual(foot["winding"]["output_orientation"], 1) + ranges = foot["face_owner_ranges"] + self.assertEqual(len(ranges["dorsal_grid"]), 24) + self.assertEqual(len(ranges["plantar_grid"]), 28) + self.assertEqual(len(ranges["outer_perimeter"]), 22) + self.assertEqual(len(ranges["ankle_to_collar"]), 8) + self.assertEqual(len(ranges["collar_to_hole"]), 8) + + def test_source_form_rows_frames_and_radii_are_lineaged(self): + for case_id, _base, _leg_inputs, form_inputs, output, _levels in self.outputs: + for side in ("left", "right"): + with self.subTest(case=case_id, side=side): + foot = output["metadata"]["feet"][side] + source_form = foot["source_form"] + self.assertEqual(source_form["case_id"], case_id) + self.assertEqual(source_form["local_controls"], form_inputs["sides"][side]) + self.assertEqual(source_form["construction"], form_inputs["construction"]) + self.assertEqual(source_form["reference_y_usage"], + "contact-plane measurement only; no floor projection") + self.assertEqual( + [row["name"] for row in foot["longitudinal_rows"]], + list(foot_form_construction._ROW_NAMES), + ) + self.assertEqual( + [row["formula"] for row in foot["longitudinal_rows"]], + list(foot_form_construction._ROW_FORMULAS), + ) + self.assertEqual(foot["lateral_fractions"], + list(foot_form_construction._LATERAL_FRACTIONS)) + self.assertIsNone(foot["grid_indices"]["dorsal"][2][2]) + self.assertEqual(len(foot["attachment_loop"]["ankle"]), 8) + self.assertEqual(foot["attachment_loop"]["ankle"], + foot["ankle_source_loop"]) + self.assertEqual(len(foot["attachment_loop"]["hole"]), 8) + self.assertEqual( + foot["correspondence"]["target_order"], + list(foot_form_construction._HOLE_BOUNDARY_NAMES), + ) + self.assertEqual(set(foot["frames"]["source"]), {"X", "U", "F"}) + self.assertIn("R is ankle-body surface centre and is not a joint", + source_form["joint_rule"]) + + def test_rounding_uses_distinct_local_normal_top_and_bottom(self): + for case_id, _base, _leg_inputs, form_inputs, output, _levels in self.outputs: + for side in ("left", "right"): + with self.subTest(case=case_id, side=side): + foot = output["metadata"]["feet"][side] + controls = form_inputs["sides"][side] + rows = foot["longitudinal_rows"] + for row_index, row in enumerate(rows): + top_index = foot["grid_indices"]["dorsal"][row_index][2] + bottom_index = foot["grid_indices"]["plantar"][row_index][2] + self.assertIsNotNone(top_index) + top = output["vertices"][top_index] + bottom = output["vertices"][bottom_index] + centre = row["centre"] + normal = row["normal"] + expected_top = [centre[axis] + row["rD"] * normal[axis] + for axis in range(3)] + expected_bottom = [centre[axis] - row["rP"] * normal[axis] + for axis in range(3)] + for actual, expected in zip(top, expected_top): + self.assertAlmostEqual(actual, expected) + for actual, expected in zip(bottom, expected_bottom): + self.assertAlmostEqual(actual, expected) + if row_index in (0, 2, 5, 6, 7): + name = ("H", "R", "M", "B", "T")[(0, 1, 5, 6, 7).index(row_index)] + self.assertEqual(row["rL"], controls[name]["rL"]) + self.assertEqual(row["rD"], controls[name]["rD"]) + self.assertEqual(row["rP"], controls[name]["rP"]) + + def test_rejects_schema_frame_and_source_degeneracy(self): + _case_id, base, leg_inputs, form_inputs, _output, _levels = self.outputs[0] + bad = copy.deepcopy(form_inputs) + bad["sides"]["left"]["M"]["local_z"] = bad["sides"]["left"]["R"]["local_z"] + with self.assertRaises(foot_form_construction.FootFormConstructionError): + foot_form_construction.build(base, leg_inputs, bad) + + bad = copy.deepcopy(form_inputs) + bad["sides"]["right"]["B"]["rD"] = 0.0 + with self.assertRaises(foot_form_construction.FootFormConstructionError): + foot_form_construction.build(base, leg_inputs, bad) + + bad = copy.deepcopy(form_inputs) + bad["construction"]["cross_section_rounding"] = 1.0 + with self.assertRaises(foot_form_construction.FootFormConstructionError): + foot_form_construction.build(base, leg_inputs, bad) + + bad = copy.deepcopy(form_inputs) + bad["sides"]["left"]["unexpected"] = True + with self.assertRaises(foot_form_construction.FootFormConstructionError): + foot_form_construction.build(base, leg_inputs, bad) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/connected-leg-assembly/tests/test_foot_junction_construction.py b/experiments/connected-leg-assembly/tests/test_foot_junction_construction.py new file mode 100644 index 0000000..300f0d3 --- /dev/null +++ b/experiments/connected-leg-assembly/tests/test_foot_junction_construction.py @@ -0,0 +1,330 @@ +"""Static and captured real-build JUNCTION-001 contract tests. + +Raman owns execution of geometry-building tests. The synthetic tests exercise +the declared local graph and accounting rules. The real-build smoke is +intended for the captured run only: it uses both immutable connected-leg cases +and genuine FOOT-004 inputs, without L2 evaluation or the collision core. +""" +from __future__ import annotations + +import copy +import hashlib +import json +from pathlib import Path +import sys +import unittest + + +EXPERIMENT_DIR = Path(__file__).resolve().parents[1] +if str(EXPERIMENT_DIR) not in sys.path: + sys.path.insert(0, str(EXPERIMENT_DIR)) + +import foot_construction # noqa: E402 +import foot_form_construction # noqa: E402 +import foot_junction_construction as junction # noqa: E402 +import construction # noqa: E402 + + +INPUTS_PATH = EXPERIMENT_DIR / "inputs.json" +FORM_INPUTS_PATH = EXPERIMENT_DIR / "foot-form-inputs.json" +POLICY_PATH = EXPERIMENT_DIR / "foot-junction-policy.json" +EXPECTED_CASES = ( + "calibrated_ordinary_human", + "calibrated_upright_anthropomorphic", +) + + +def _policy() -> dict: + return json.loads(POLICY_PATH.read_text(encoding="utf-8")) + + +def _sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def _captured_real_cases() -> list[dict]: + document = json.loads(INPUTS_PATH.read_text(encoding="utf-8")) + form_document = json.loads(FORM_INPUTS_PATH.read_text(encoding="utf-8")) + forms = {row["case_id"]: row for row in form_document["cases"]} + result = [] + for case in document["cases"]: + if case["id"] not in EXPECTED_CASES: + continue + root_ref = case["root_mesh"] + root_path = Path(root_ref["path"]) + if _sha256(root_path) != root_ref["sha256"]: + raise AssertionError(f"immutable root identity drifted: {root_path}") + result.append({ + "id": case["id"], + "root": json.loads(root_path.read_text(encoding="utf-8")), + "leg_inputs": copy.deepcopy(case["leg_inputs"]), + "form_inputs": forms[case["id"]], + }) + if tuple(row["id"] for row in result) != EXPECTED_CASES: + raise AssertionError("the two canonical connected-leg cases were not loaded") + return result + + +def _source_grid(base: dict, row: dict, side: str) -> tuple[dict, dict]: + base_vertices = [tuple(point) for point in base["vertices"]] + ankle_loop, ankle_centre, attachment_frame = foot_construction._ankle_chain( + base, side, row["leg_inputs"][side], base_vertices, base["loops"] + ) + source_frame = foot_form_construction._source_frame( + base, side, attachment_frame + ) + controls = row["form_inputs"]["sides"][side] + grid = foot_form_construction._grid_points( + ankle_centre, source_frame, + {name: controls[name] for name in foot_form_construction._ANCHORS}, + row["form_inputs"]["construction"], side, + ) + return source_frame, grid + + +def _grid() -> dict: + top = [[(float(column), float(row), 1.0) for column in range(5)] + for row in range(8)] + bottom = [[(float(column), float(row), -1.0) for column in range(5)] + for row in range(8)] + return {"top": top, "bottom": bottom} + + +def _synthetic_junction_faces(): + local = junction._local_grid(_grid()) + by_name = junction._body_faces(local) + body_faces = [face for name in ("dorsal_grid", "plantar_grid", "outer_perimeter") + for face in by_name[name]] + holes = [local["top"][row][column] + for row, column in junction._HOLE_POSITIONS] + holes = [int(index) for index in holes] + local_to_output = {} + output_points = [] + for index, point in enumerate(local["points"]): + if index in holes: + continue + local_to_output[index] = len(output_points) + output_points.append(point) + actual_start = len(output_points) + actual_loop = list(range(actual_start, actual_start + 8)) + hole_to_actual = dict(zip(holes, actual_loop)) + actual_points = [ + tuple(local["points"][index][axis] + (0.0 if axis != 2 else 0.25) + for axis in range(3)) + for index in holes + ] + output_points.extend(actual_points) + support_start = len(output_points) + for index in range(8): + output_points.extend(((0.0, 0.0, 0.0), (0.0, 1.0, 0.0))) + base_faces = [] + for index in range(8): + left = actual_loop[index] + right = actual_loop[(index + 1) % 8] + support = support_start + 2 * index + base_faces.append((left, right, support, support + 1)) + output_faces = list(base_faces) + new_faces = [] + for face in body_faces: + mapped = junction._map_local_face( + face, local_to_output, hole_to_actual, "synthetic junction face" + ) + output_faces.append(mapped) + new_faces.append(len(output_faces) - 1) + return local, by_name, output_points, output_faces, new_faces, actual_loop + + +class JunctionPolicyTests(unittest.TestCase): + def test_policy_seals_frontier_and_forbids_old_builders(self): + policy = _policy() + parsed = junction._policy(policy) + self.assertEqual(parsed["graph"]["frontier_row"], 5) + self.assertEqual(parsed["graph"]["frontier_source"], "M") + self.assertEqual(parsed["output"]["connector_rings"], False) + self.assertEqual( + parsed["source"]["forbidden_builders"], + ["foot_form_construction.build", "foot_attachment_construction.build"], + ) + + def test_graph_is_79_vertices_and_74_quads(self): + local = junction._local_grid(_grid()) + faces = junction._body_faces(local) + self.assertEqual(len(local["points"]), 79) + self.assertEqual(sum(len(value) for value in faces.values()), 74) + self.assertEqual(len(local["top"]), 8) + self.assertEqual(local["top"][2][2], None) + + +class HarmonicDisplacementTests(unittest.TestCase): + def setUp(self): + self.policy = _policy() + self.local = junction._local_grid(_grid()) + by_name = junction._body_faces(self.local) + self.faces = [face for name in ("dorsal_grid", "plantar_grid", "outer_perimeter") + for face in by_name[name]] + self.frame = {"X": (1.0, 0.0, 0.0), "U": (0.0, 1.0, 0.0), + "F": (0.0, 0.0, 1.0)} + self.holes = [self.local["top"][row][column] + for row, column in junction._HOLE_POSITIONS] + self.holes = [int(index) for index in self.holes] + + def _solve(self, forward=0.02): + deltas = [(0.01 * index, 0.0, forward) for index in range(8)] + return junction._displacements( + self.local, self.faces, self.frame, self.holes, deltas, + self.policy, "synthetic", + ) + + def test_fixed_frontier_and_plantar_u_are_exact_constraints(self): + displacements, record = self._solve() + for index, row in enumerate(self.local["rows"]): + if row in (0, 5, 6, 7): + self.assertEqual(displacements[index], (0.0, 0.0, 0.0)) + if self.local["regions"][index] == "plantar" and row in (1, 2, 3, 4): + self.assertEqual(displacements[index][1], 0.0) + self.assertEqual(record["basis_order"], ["X", "U", "F"]) + self.assertLessEqual(record["max_residual"], 1.0e-10) + + def test_source_change_reaches_a_free_cage_vertex(self): + first, _ = self._solve(forward=0.01) + second, _ = self._solve(forward=0.03) + free_index = self.local["top"][2][0] + self.assertNotEqual(first[free_index], second[free_index]) + self.assertEqual(first[self.local["top"][5][2]], (0.0, 0.0, 0.0)) + + def test_disconnected_free_component_fails_without_fallback(self): + adjacency = [{1}, {0}, set()] + with self.assertRaises(junction.FootJunctionConstructionError): + junction._harmonic_values(adjacency, {0: 0.0}, 1.0e-10, "hostile") + + def test_mirrored_frames_preserve_local_solution_and_mirror_world_x(self): + left = junction._world_from_components( + {"X": (1.0, 0.0, 0.0), "U": (0.0, 1.0, 0.0), "F": (0.0, 0.0, 1.0)}, + (0.03, 0.01, 0.02), + ) + right = junction._world_from_components( + {"X": (-1.0, 0.0, 0.0), "U": (0.0, 1.0, 0.0), "F": (0.0, 0.0, -1.0)}, + (0.03, 0.01, 0.02), + ) + self.assertEqual(junction._cross((1.0, 0.0, 0.0), (0.0, 1.0, 0.0)), + (0.0, 0.0, 1.0)) + self.assertEqual(junction._cross((-1.0, 0.0, 0.0), (0.0, 1.0, 0.0)), + (0.0, 0.0, -1.0)) + self.assertEqual(left[0], -right[0]) + self.assertEqual(left[1], right[1]) + self.assertEqual(left[2], -right[2]) + + +class CapturedRealBuildSmokeTests(unittest.TestCase): + """Run only from Raman's capture; this is not a live pre-capture test.""" + + @classmethod + def setUpClass(cls): + cls.rows = _captured_real_cases() + cls.outputs = [] + for row in cls.rows: + base = construction.build(row["root"], row["leg_inputs"]) + output = junction.build( + base, row["leg_inputs"], row["form_inputs"], _policy() + ) + cls.outputs.append((row, base, output)) + + def _assert_inherited_prefix(self, base, output): + base_count = len(base["vertices"]) + face_count = len(base["quads"]) + # Keep these exact comparisons independent of any vertex-ID mapping + # used by the local junction grid. + self.assertEqual(output["vertices"][:base_count], base["vertices"]) + self.assertEqual(output["quads"][:face_count], base["quads"]) + + def _assert_fixed_rows(self, row, base, output): + for side in ("left", "right"): + source_frame, grid = _source_grid(base, row, side) + foot = output["metadata"]["feet"][side] + for grid_name, source_name in (("dorsal", "top"), ("plantar", "bottom")): + output_rows = foot["output_grid_indices"][grid_name] + source_rows = grid[source_name] + for row_index in (5, 6, 7): + for column, output_index in enumerate(output_rows[row_index]): + expected = tuple(source_rows[row_index][column]) + actual = tuple(output["vertices"][output_index]) + self.assertEqual(actual, expected) + + for row_index in (1, 2, 3, 4): + for column, output_index in enumerate(foot["output_grid_indices"]["plantar"][row_index]): + expected = tuple(grid["bottom"][row_index][column]) + actual = tuple(output["vertices"][output_index]) + displacement = junction._sub(actual, expected) + # The policy fixes the local U component exactly; X/F + # remain harmonic unknowns and are intentionally not + # compared to the source point here. + self.assertLess(abs(junction._dot(displacement, source_frame["U"])), + 1.0e-12) + + def test_captured_real_foot004_build_preserves_prefix_fixed_frontier_and_plantar_u(self): + self.assertEqual([row["id"] for row in self.rows], list(EXPECTED_CASES)) + for row, base, output in self.outputs: + with self.subTest(case=row["id"]): + self._assert_inherited_prefix(base, output) + self._assert_fixed_rows(row, base, output) + + def test_captured_a_perturbation_reaches_free_proximal_output(self): + row = copy.deepcopy(self.rows[0]) + _baseline_row, baseline_base, baseline_output = self.outputs[0] + row["leg_inputs"]["left"]["A"][2] += 0.01 + changed_base = construction.build(row["root"], row["leg_inputs"]) + changed_output = junction.build( + changed_base, row["leg_inputs"], row["form_inputs"], _policy() + ) + + self._assert_inherited_prefix(changed_base, changed_output) + self._assert_fixed_rows(row, changed_base, changed_output) + baseline_foot = baseline_output["metadata"]["feet"]["left"] + changed_foot = changed_output["metadata"]["feet"]["left"] + baseline_index = baseline_foot["output_grid_indices"]["dorsal"][2][0] + changed_index = changed_foot["output_grid_indices"]["dorsal"][2][0] + self.assertNotEqual( + tuple(baseline_output["vertices"][baseline_index]), + tuple(changed_output["vertices"][changed_index]), + ) + self.assertEqual( + baseline_output["vertices"][:len(baseline_base["vertices"])], + baseline_base["vertices"], + ) + + +class MouthAndAccountingTests(unittest.TestCase): + def test_direct_mouth_weld_and_no_duplicate_mouth_vertices(self): + _local, _by_name, vertices, quads, new_faces, actual_loop = _synthetic_junction_faces() + junction._validate_side_output( + vertices, quads, new_faces, actual_loop, "synthetic" + ) + self.assertEqual(len(set(actual_loop)), 8) + self.assertEqual(len(new_faces), 74) + uses = foot_construction._edge_uses([tuple(face) for face in quads]) + for index, left in enumerate(actual_loop): + edge = tuple(sorted((left, actual_loop[(index + 1) % 8]))) + self.assertEqual(len(uses[edge]), 2) + + def test_fixed_rows_keep_exact_source_points_in_moved_grid(self): + local = junction._local_grid(_grid()) + frame = {"X": (1.0, 0.0, 0.0), "U": (0.0, 1.0, 0.0), + "F": (0.0, 0.0, 1.0)} + faces_by_name = junction._body_faces(local) + faces = [face for name in ("dorsal_grid", "plantar_grid", "outer_perimeter") + for face in faces_by_name[name]] + holes = [int(local["top"][row][column]) + for row, column in junction._HOLE_POSITIONS] + displacements, _ = junction._displacements( + local, faces, frame, holes, [(0.0, 0.0, 0.0)] * 8, + _policy(), "synthetic", + ) + moved = [junction._add(point, junction._world_from_components(frame, displacement)) + for point, displacement in zip(local["points"], displacements)] + for index, row in enumerate(local["rows"]): + if row in (0, 5, 6, 7): + self.assertEqual(moved[index], local["points"][index]) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/connected-leg-assembly/tests/test_head_construction.py b/experiments/connected-leg-assembly/tests/test_head_construction.py new file mode 100644 index 0000000..f865efb --- /dev/null +++ b/experiments/connected-leg-assembly/tests/test_head_construction.py @@ -0,0 +1,297 @@ +"""Focused tests for the six-phase connected head candidate.""" +from __future__ import annotations + +import copy +import hashlib +import json +import math +from pathlib import Path +import sys +import unittest + + +HERE = Path(__file__).resolve().parents[1] +if str(HERE) not in sys.path: + sys.path.insert(0, str(HERE)) + +import checks # noqa: E402 +import collision_broadphase # noqa: E402 +import construction # noqa: E402 +import head_construction # noqa: E402 + + +INPUTS = json.loads((HERE / "inputs.json").read_text(encoding="utf-8")) +HEAD_INPUTS = json.loads((HERE / "head-inputs.json").read_text(encoding="utf-8")) +HEAD_REFINEMENT = HERE / "head-refinement-inputs.json" +EXPECTED = ("calibrated_ordinary_human", "calibrated_upright_anthropomorphic") + + +def _sha(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def _load(row, field): + ref = row[field] + path = Path(ref["path"]) + if _sha(path) != ref["sha256"]: + raise AssertionError(f"immutable {field} identity drifted: {path}") + return json.loads(path.read_text(encoding="utf-8")) + + +def _cases(): + controls = {row["case_id"]: row["head"] for row in HEAD_INPUTS["cases"]} + result = [] + for row in INPUTS["cases"]: + if row["id"] not in EXPECTED: + continue + root, source = _load(row, "root_mesh"), _load(row, "original_case") + base = construction.build(root, row["leg_inputs"]) + head = head_construction.build(base, source, controls[row["id"]]) + levels = head_construction.evaluate(head, levels=2) + result.append((row["id"], base, source, controls[row["id"]], head, levels)) + if tuple(row[0] for row in result) != EXPECTED: + raise AssertionError("canonical head cases were not loaded") + return result + + +def _triangles(quads): + return [triangle for face in quads for triangle in + ((face[0], face[1], face[2]), (face[0], face[2], face[3]))] + + +def _fixed_l2_domain(mesh, support): + support = set(support) + return [index for index, stencil in enumerate(mesh["base_stencils"]) + if any(int(term[0]) in support for term in stencil)] + + +def _axis_extent(mesh, indices, axis, maximum_only=False): + values = [mesh["vertices"][index][axis] for index in indices] + return max(values) if maximum_only else max(values) - min(values) + + +class HeadConstructionTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cases = _cases() + + def test_actual_cases_evaluate_with_complete_stencils(self): + for case_id, _base, _source, _controls, head, levels in self.cases: + with self.subTest(case=case_id): + self.assertEqual([level["metadata"]["level"] for level in levels], [0, 1, 2]) + for level in levels: + self.assertEqual(len(level["vertices"]), len(level["base_stencils"])) + for stencil in level["base_stencils"]: + self.assertAlmostEqual(sum(float(term[1]) for term in stencil), 1.0, places=9) + self.assertTrue(all(term[1] > 0.0 for term in stencil)) + self.assertNotIn("port.neck", head["loops"]) + + def test_inherited_prefix_closure_and_source_owned_phase(self): + expected_phase = {(-1.0, -1.0), (1.0, -1.0), (1.0, 0.0), + (1.0, 1.0), (-1.0, 1.0), (-1.0, 0.0)} + for _case_id, base, source, _controls, head, _levels in self.cases: + self.assertEqual(head["vertices"][:len(base["vertices"])], base["vertices"]) + self.assertEqual(head["quads"][:len(base["quads"])], base["quads"]) + meta = head["metadata"]["head"] + self.assertEqual({tuple(pair) for pair in meta["neck_phase"]}, expected_phase) + centre = [source["components"][f"stations.neck_upper.C.{axis}"] for axis in "xyz"] + first = meta["stations"][0]["centre"] + self.assertEqual(first[0], centre[0]); self.assertEqual(first[2], centre[2]) + + def test_binding_handoff_is_source_owned_and_matches_exact_allocations(self): + for _case_id, _base, source, _controls, head, _levels in self.cases: + meta = head["metadata"]["head"] + handoff = meta["binding_handoff"] + expected_pivot = [ + source["components"][f"stations.neck_collar.C.{axis}"] + for axis in "xyz" + ] + support = next(row for row in meta["stations"] + if row["name"] == "neck_support") + self.assertEqual(handoff["joint"], "neck_head") + self.assertEqual(handoff["pivot_source"], "stations.neck_collar.C") + self.assertEqual(handoff["pivot"], expected_pivot) + self.assertEqual(handoff["consumed_neck_port_indices"], + meta["neck_port_indices"]) + self.assertEqual(handoff["neck_support_ring_indices"], support["indices"]) + self.assertEqual(handoff["head_new_vertex_indices"], + meta["new_vertex_indices"]) + self.assertEqual(handoff["feature_new_vertex_indices"], + meta["feature_vertex_indices"]) + + def test_stale_source_neck_rejects(self): + _case_id, base, source, controls, _head, _levels = self.cases[0] + changed = copy.deepcopy(source) + changed["components"]["stations.neck_upper.rL"] += 0.001 + with self.assertRaisesRegex(head_construction.HeadConstructionError, "source neck radii"): + head_construction.build(base, changed, controls) + + def test_optional_features_are_generic_and_connected(self): + human, anthro = self.cases + self.assertFalse(human[4]["metadata"]["head"]["features"]["muzzle"]["enabled"]) + self.assertFalse(human[4]["metadata"]["head"]["features"]["ears"]["enabled"]) + features = anthro[4]["metadata"]["head"]["features"] + self.assertTrue(features["muzzle"]["enabled"]) + self.assertTrue(features["ears"]["enabled"]) + self.assertEqual(set(features["ears"]["sides"]), {"left", "right"}) + self.assertNotIn("case_id", anthro[3]) + + def test_ear_sections_are_broad_X_thin_Z_right_handed_and_mirrored(self): + features = self.cases[1][4]["metadata"]["head"]["features"]["ears"]["sides"] + for side in ("left", "right"): + row = features[side] + axis, broad, depth = (row["frame"][name] for name in ("axis", "broad", "depth")) + cross = head_construction._cross(tuple(axis), tuple(broad)) + self.assertGreater(sum(cross[i] * depth[i] for i in range(3)), 1.0 - 1.0e-7) + self.assertGreater(abs(broad[0]), 0.95) + self.assertGreater(abs(depth[2]), 0.95) + self.assertEqual(len(set(tuple(pair) for pair in row["host_phase"])), 4) + self.assertGreater(row["controls"]["base_halfwidth_x"], row["controls"]["base_halfdepth_z"]) + self.assertLess(features["left"]["frame"]["axis"][0], 0.0) + self.assertGreater(features["right"]["frame"]["axis"][0], 0.0) + + def _assert_l0_to_l2_response(self, baseline_l0, baseline_l2, changed_l0, + l0_support, measurement_support, axis, + maximum_only=False): + self.assertEqual(changed_l0["quads"], baseline_l0["quads"]) + changed_l2 = head_construction.evaluate(changed_l0, levels=2)[-1] + self.assertEqual(changed_l2["quads"], baseline_l2["quads"]) + self.assertEqual(changed_l2["base_stencils"], baseline_l2["base_stencils"]) + + support = set(l0_support) + l0_delta = [[changed_l0["vertices"][index][component] - + baseline_l0["vertices"][index][component] + for component in range(3)] + for index in range(len(baseline_l0["vertices"]))] + self.assertGreater(max(abs(value) for index in support for value in l0_delta[index]), + 100.0 * math.ulp(1.0)) + self.assertEqual( + max((abs(value) for index, row in enumerate(l0_delta) + if index not in support for value in row), default=0.0), + 0.0, + ) + + domain = _fixed_l2_domain(baseline_l2, support) + self.assertTrue(domain) + max_transfer_error = 0.0 + for vertex_index in domain: + expected = [sum(float(coefficient) * l0_delta[int(base_index)][component] + for base_index, coefficient in + baseline_l2["base_stencils"][vertex_index]) + for component in range(3)] + actual = [changed_l2["vertices"][vertex_index][component] - + baseline_l2["vertices"][vertex_index][component] + for component in range(3)] + max_transfer_error = max( + max_transfer_error, + max(abs(actual[component] - expected[component]) + for component in range(3)), + ) + self.assertLessEqual(max_transfer_error, 1.0e-12) + + measurement_domain = _fixed_l2_domain(baseline_l2, measurement_support) + before = _axis_extent(baseline_l2, measurement_domain, axis, maximum_only) + after = _axis_extent(changed_l2, measurement_domain, axis, maximum_only) + self.assertGreater(after - before, 100.0 * math.ulp(max(abs(before), 1.0))) + + def test_declared_controls_reach_actual_l0_and_evaluated_l2_surface(self): + for case_id, base, source, controls, baseline_l0, levels in self.cases: + with self.subTest(case=case_id, control="stations.cheek.radii[0]"): + baseline_l2 = levels[-1] + cheek = next(row for row in baseline_l0["metadata"]["head"]["stations"] + if row["name"] == "cheek")["indices"] + support = set(cheek) + muzzle = baseline_l0["metadata"]["head"]["features"]["muzzle"] + if muzzle["enabled"]: + support.update(muzzle["support_indices"]) + support.update(muzzle["tip_indices"]) + changed = copy.deepcopy(controls) + changed["stations"]["cheek"]["radii"][0] += 0.004 + changed_l0 = head_construction.build(base, source, changed) + self._assert_l0_to_l2_response( + baseline_l0, baseline_l2, changed_l0, support, cheek, axis=0) + + _case_id, base, source, controls, baseline_l0, levels = self.cases[1] + baseline_l2 = levels[-1] + features = baseline_l0["metadata"]["head"]["features"] + muzzle = features["muzzle"] + muzzle_support = set(muzzle["support_indices"] + muzzle["tip_indices"]) + changed = copy.deepcopy(controls) + changed["muzzle"]["length"] += 0.010 + self._assert_l0_to_l2_response( + baseline_l0, baseline_l2, + head_construction.build(base, source, changed), + muzzle_support, muzzle_support, axis=2, maximum_only=True) + + ears = features["ears"]["sides"] + ear_sections = { + side: {index for ring in ears[side]["section_indices"] for index in ring} + for side in ("left", "right") + } + all_sections = ear_sections["left"] | ear_sections["right"] + all_ear_vertices = all_sections | { + index for side in ("left", "right") + for index in ears[side]["attachment_indices"] + } + for control, amount, support, axis in ( + ("base_halfwidth_x", 0.003, all_sections, 0), + ("base_halfdepth_z", 0.002, all_sections, 2), + ("tip_up", 0.010, all_ear_vertices, 1), + ): + with self.subTest(case=_case_id, control=f"ears.{control}"): + changed = copy.deepcopy(controls) + changed["ears"][control] += amount + changed_l0 = head_construction.build(base, source, changed) + self._assert_l0_to_l2_response( + baseline_l0, baseline_l2, changed_l0, + support, support, axis=axis) + + def test_refined_muzzle_support_dimensions_reach_actual_l2_semantic_support(self): + # Capture-only geometry regression: this method is intentionally not + # run before the new source/input snapshot is created. + _case_id, base, source, _legacy_controls, _legacy_l0, _legacy_levels = self.cases[1] + refined_controls = head_construction.head_inputs_for_refinement( + HEAD_REFINEMENT, "calibrated_upright_anthropomorphic" + ) + baseline_l0 = head_construction.build(base, source, refined_controls) + baseline_l2 = head_construction.evaluate(baseline_l0, levels=2)[-1] + muzzle = baseline_l0["metadata"]["head"]["features"]["muzzle"] + support = set(muzzle["support_indices"]) + self.assertEqual(muzzle["support_source"], "explicit") + for field, amount, axis in ( + ("support_halfwidth", 0.007, 0), + ("support_halfheight", 0.006, 1), + ): + with self.subTest(control=f"muzzle.{field}"): + changed = copy.deepcopy(refined_controls) + changed["muzzle"][field] += amount + self._assert_l0_to_l2_response( + baseline_l0, + baseline_l2, + head_construction.build(base, source, changed), + support, + support, + axis=axis, + ) + + def test_actual_L2_has_no_quad_folds_or_intersections_by_existing_checkers(self): + for case_id, _base, _source, _controls, _head, levels in self.cases: + mesh = levels[2] + dots = [] + for face in mesh["quads"]: + first = checks._triangle_normal(mesh["vertices"], (face[0], face[1], face[2])) + second = checks._triangle_normal(mesh["vertices"], (face[0], face[2], face[3])) + denominator = checks._norm(first) * checks._norm(second) + dots.append(checks._dot(first, second) / denominator if denominator > 0.0 else -1.0) + with self.subTest(case=case_id, check="fold"): + self.assertGreater(min(dots), 0.0) + collision = collision_broadphase.collision_report(mesh["vertices"], _triangles(mesh["quads"])) + with self.subTest(case=case_id, check="collision"): + self.assertTrue(collision["available"]) + self.assertTrue(collision["pair_partition_complete"]) + self.assertTrue(collision["final_classification_partition_complete"]) + self.assertEqual(collision["intersection_hit_count"], 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/connected-leg-assembly/tests/test_hip_source.py b/experiments/connected-leg-assembly/tests/test_hip_source.py new file mode 100644 index 0000000..59e50ba --- /dev/null +++ b/experiments/connected-leg-assembly/tests/test_hip_source.py @@ -0,0 +1,115 @@ +from __future__ import annotations + +import copy +import json +from collections.abc import Mapping +from pathlib import Path +import sys +from typing import Any +import unittest + + +EXPERIMENT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(EXPERIMENT)) +import hip_source # noqa: E402 +import root_source # noqa: E402 + + +def _json(path: str | Path) -> Any: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def _difference_paths(expected: Any, actual: Any, path: str = "$", limit: int = 12) -> list[str]: + if limit <= 0: + return [path] + if type(expected) is not type(actual): + return [f"{path} (types {type(expected).__name__}/{type(actual).__name__})"] + if isinstance(expected, Mapping): + differences: list[str] = [] + for key in sorted(set(expected) | set(actual), key=str): + child = f"{path}.{key}" + if key not in expected or key not in actual: + differences.append(child) + else: + differences.extend(_difference_paths(expected[key], actual[key], child, + limit - len(differences))) + if len(differences) >= limit: + return differences[:limit] + return differences + if isinstance(expected, list): + differences = [] + if len(expected) != len(actual): + differences.append(f"{path} (length {len(expected)}/{len(actual)})") + for index, (left, right) in enumerate(zip(expected, actual)): + differences.extend(_difference_paths(left, right, f"{path}[{index}]", + limit - len(differences))) + if len(differences) >= limit: + return differences[:limit] + return differences + return [] if expected == actual else [path] + + +class HipSourceTests(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls.document = _json(EXPERIMENT / "inputs.json") + + def _case(self, index: int) -> tuple[dict, dict, dict, dict]: + row = self.document["cases"][index] + source_case = _json(row["original_case"]["path"]) + rebuilt = root_source.reconstruct_source_case(source_case) + prior = _json(row["prior_hip_binding"]["path"]) + return row, source_case, rebuilt, prior + + def test_both_recorded_cases_regenerate_saved_weights_and_frames(self) -> None: + for index in range(2): + row, source_case, rebuilt, prior = self._case(index) + result = hip_source.bind_source_case( + rebuilt["levels"]["L0"], rebuilt["levels"]["L2"], source_case, + leg_inputs=row["leg_inputs"]) + actual = result["binding"] + for key in ("base_weights", "evaluated_weights", "rest_frames"): + differences = _difference_paths(prior[key], actual[key], f"$.{key}") + self.assertFalse( + differences, + f"{row['id']} {key} metadata differs at: {', '.join(differences)}", + ) + + identity = result["provenance"]["frozen_helper_identity"] + self.assertEqual(identity["before"], identity["after"]) + self.assertEqual(identity["manifest_path"], str(hip_source.FROZEN_HIP_MANIFEST)) + self.assertEqual(identity["path"], str(hip_source.FROZEN_HIP_BINDING)) + self.assertNotEqual(identity["path"], str(EXPERIMENT / "binding.py")) + + def test_j_only_change_preserves_weights_and_rest_geometry_but_changes_frame(self) -> None: + row, source_case, rebuilt, _prior = self._case(0) + rest_before = copy.deepcopy(rebuilt["levels"]["L2"]) + baseline_inputs = copy.deepcopy(row["leg_inputs"]) + changed_inputs = copy.deepcopy(baseline_inputs) + changed_inputs["left"]["J"][1] += 0.01 + baseline = hip_source.bind_source_case( + rebuilt["levels"]["L0"], rebuilt["levels"]["L2"], source_case, + leg_inputs=baseline_inputs)["binding"] + changed = hip_source.bind_source_case( + rebuilt["levels"]["L0"], rebuilt["levels"]["L2"], source_case, + leg_inputs=changed_inputs)["binding"] + self.assertEqual(baseline["base_weights"], changed["base_weights"]) + self.assertEqual(baseline["evaluated_weights"], changed["evaluated_weights"]) + self.assertEqual(baseline["rest_frames"]["right"], changed["rest_frames"]["right"]) + self.assertNotEqual(baseline["rest_frames"]["left"], changed["rest_frames"]["left"]) + self.assertEqual(rest_before, rebuilt["levels"]["L2"]) + + def test_leg_t_or_k_conflict_is_rejected(self) -> None: + row, source_case, rebuilt, _prior = self._case(0) + for field in ("T", "K"): + changed = copy.deepcopy(row["leg_inputs"]) + changed["left"][field][0] += 0.001 + with self.subTest(field=field): + with self.assertRaisesRegex(hip_source.HipSourceError, rf"left\.{field} conflicts"): + hip_source.bind_source_case( + rebuilt["levels"]["L0"], rebuilt["levels"]["L2"], source_case, + leg_inputs=changed) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/connected-leg-assembly/tests/test_perturbations.py b/experiments/connected-leg-assembly/tests/test_perturbations.py new file mode 100644 index 0000000..74e234f --- /dev/null +++ b/experiments/connected-leg-assembly/tests/test_perturbations.py @@ -0,0 +1,534 @@ +import copy +import json +import math +import sys +import unittest +from pathlib import Path + + +EXPERIMENT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(EXPERIMENT)) +import perturbations # noqa: E402 + + +SIDES = ("left", "right") +SECTIONS = ( + "mid_thigh", "knee_pre_support", "knee", "knee_post_support", + "calf", "ankle_approach", "ankle", +) +FRACTIONS = (0.70, 0.90, 1.0, 0.12, 0.35, 0.72, 1.0) + + +def add(*values): + return tuple(sum(value[index] for value in values) for index in range(3)) + + +def sub(left, right): + return tuple(left[index] - right[index] for index in range(3)) + + +def scale(value, factor): + return tuple(factor * item for item in value) + + +def dot(left, right): + return sum(left[index] * right[index] for index in range(3)) + + +def cross(left, right): + return ( + left[1] * right[2] - left[2] * right[1], + left[2] * right[0] - left[0] * right[2], + left[0] * right[1] - left[1] * right[0], + ) + + +def unit(value): + length = math.sqrt(dot(value, value)) + return scale(value, 1.0 / length) + + +def lerp(left, right, fraction): + return add(scale(left, 1.0 - fraction), scale(right, fraction)) + + +def frame(tangent): + tangent = unit(tangent) + x = unit(sub((1.0, 0.0, 0.0), scale(tangent, tangent[0]))) + up = scale(tangent, -1.0) + return {"X": x, "U": up, "F": unit(cross(x, up))} + + +def rotate(point, pivot, axis, degrees): + angle = math.radians(degrees) + value = sub(point, pivot) + parallel = scale(axis, dot(axis, value)) + return add(scale(value, math.cos(angle)), + scale(cross(axis, value), math.sin(angle)), + scale(parallel, 1.0 - math.cos(angle)), pivot) + + +def synthetic_inputs(): + def row(side): + sign = -1.0 if side == "left" else 1.0 + return { + "J": [sign * 0.56, 2.1, 0.0], + "T": [sign * 0.5, 2.0, 0.0], + "K": [sign * 0.5, 1.0, 0.0], + "A": [sign * 0.5, 0.0, 0.0], + "radii": { + "knee": [0.20, 0.16, 0.18], + "calf": [0.18, 0.14, 0.22], + "ankle": [0.10, 0.09, 0.13], + }, + "mid_thigh_factor": 0.85, + "support_fraction": 0.10, + "J_role": "synthetic independent pose input", + "TK_source_role": "synthetic source points", + "distal_design_status": "synthetic test geometry", + } + return {side: row(side) for side in SIDES} + + +def synthetic_root(): + vertices = [] + for side in SIDES: + x_offset = -0.5 if side == "left" else 0.5 + exit_centre = (x_offset, 1.55, 0.0) + for corner in range(8): + angle = 2.0 * math.pi * corner / 8.0 + lateral = 0.20 * math.cos(angle) + forward_radius = 0.11 if math.sin(angle) >= 0.0 else 0.17 + forward = forward_radius * math.sin(angle) + vertices.append((exit_centre[0] + lateral, + exit_centre[1], + exit_centre[2] + forward)) + return { + "vertices": vertices, + "quads": [], + "loops": { + "port.left_thigh": list(range(0, 8)), + "port.right_thigh": list(range(8, 16)), + }, + "base_stencils": [[[index, 1.0]] for index in range(16)], + } + + +class SyntheticConstruction: + def __init__(self): + self.build_inputs = [] + self.build_count = 0 + self.evaluate_count = 0 + + def _mesh(self, root, inputs): + vertices = [tuple(point) for point in root["vertices"]] + metadata = {"chains": {}} + loops = copy.deepcopy(root["loops"]) + for side in SIDES: + row = inputs[side] + T, K, A = (tuple(row[name]) for name in ("T", "K", "A")) + incoming = unit(sub(K, T)) + outgoing = unit(sub(A, K)) + knee_tangent = unit(add(incoming, outgoing)) + frames = [frame(value) for value in + (incoming, incoming, knee_tangent, outgoing, + outgoing, outgoing, outgoing)] + exit_centre = add(T, scale(sub(K, T), 0.45)) + root_loop = root["loops"][f"port.{side}_thigh"] + template = [] + lat_radius = 0.0 + ant_radius = 0.0 + post_radius = 0.0 + projected = [] + incoming_frame = frames[0] + for index in root_loop: + delta = sub(tuple(root["vertices"][index]), exit_centre) + lateral = dot(delta, incoming_frame["X"]) + forward = dot(delta, incoming_frame["F"]) + projected.append((lateral, forward)) + lat_radius = max(lat_radius, abs(lateral)) + ant_radius = max(ant_radius, forward) + post_radius = max(post_radius, -forward) + for lateral, forward in projected: + template.append((lateral / lat_radius, + forward / (ant_radius if forward >= 0 else post_radius))) + exit_radii = (lat_radius, ant_radius, post_radius) + mid_radii = scale(exit_radii, row["mid_thigh_factor"]) + supplied = {name: tuple(row["radii"][name]) + for name in ("knee", "calf", "ankle")} + centres = [ + lerp(T, K, FRACTIONS[0]), lerp(T, K, FRACTIONS[1]), K, + lerp(K, A, FRACTIONS[3]), lerp(K, A, FRACTIONS[4]), + lerp(K, A, FRACTIONS[5]), A, + ] + radii = [] + for name, fraction in zip(SECTIONS, FRACTIONS): + if name in ("mid_thigh", "knee_pre_support", "knee") and fraction <= 0.70: + value = lerp(exit_radii, mid_radii, (fraction - 0.45) / 0.25) + elif name in ("mid_thigh", "knee_pre_support", "knee"): + value = lerp(mid_radii, supplied["knee"], (fraction - 0.70) / 0.30) + elif fraction <= 0.35: + value = lerp(supplied["knee"], supplied["calf"], fraction / 0.35) + elif name == "ankle": + value = supplied["ankle"] + else: + value = lerp(supplied["calf"], supplied["ankle"], (fraction - 0.35) / 0.65) + radii.append(value) + sections = [] + for name, centre, section_radii, section_frame in zip( + SECTIONS, centres, radii, frames): + ring = [] + for lateral, forward in template: + depth = section_radii[1] if forward >= 0.0 else section_radii[2] + point = add(centre, + scale(section_frame["X"], lateral * section_radii[0]), + scale(section_frame["F"], forward * depth)) + ring.append(len(vertices)) + vertices.append(point) + sections.append({"name": name, "indices": ring, "centre": list(centre)}) + metadata["chains"][side] = { + "pose_only_J": list(row["J"]), + "pose_only_J_usage": ( + "recorded context; unused by rest construction" + ), + "role_metadata": { + "J_role": row["J_role"], + "TK_source_role": row["TK_source_role"], + "distal_design_status": row["distal_design_status"], + }, + "sections": sections, + } + loops[f"port.{side}_ankle"] = list(sections[-1]["indices"]) + return { + "vertices": [list(point) for point in vertices], + "quads": [], + "loops": loops, + "base_stencils": [[[index, 1.0]] for index in range(len(vertices))], + "metadata": metadata, + } + + def build(self, root, inputs): + self.build_count += 1 + self.build_inputs.append(copy.deepcopy(inputs)) + return self._mesh(root, inputs) + + def evaluate(self, mesh): + self.evaluate_count += 1 + return [copy.deepcopy(mesh), copy.deepcopy(mesh)] + + +class SyntheticBinding: + def __init__(self): + self.bind_inputs = [] + self.bind_count = 0 + self.pose_count = 0 + + def bind(self, base, rest, root, prior_binding, inputs): + self.bind_count += 1 + self.bind_inputs.append(copy.deepcopy(inputs)) + weights = [] + for index in range(len(base["vertices"])): + row = [1.0, 0.0, 0.0, 0.0, 0.0] + for side, thigh, shank in (("left", 1, 2), ("right", 3, 4)): + for station, section in enumerate(base["metadata"]["chains"][side]["sections"]): + if index in section["indices"]: + shank_weight = (0.0, 0.0, 0.5, 1.0, 1.0, 1.0, 1.0)[station] + row[thigh] = 1.0 - shank_weight + row[shank] = shank_weight + row[0] = 0.0 + weights.append(row) + # The synthetic L2 is an identity-stencil copy of L0. + return {"evaluated_weights": copy.deepcopy(weights), + "base_weights": copy.deepcopy(weights), + "leg_inputs": copy.deepcopy(inputs)} + + def pose(self, rest_mesh, binding, angles): + self.pose_count += 1 + output = copy.deepcopy(rest_mesh) + inputs = binding["leg_inputs"] + J = tuple(inputs["left"]["J"]) + K = tuple(inputs["left"]["K"]) + y_axis = unit(sub(J, K)) + axis = unit(sub((1.0, 0.0, 0.0), scale(y_axis, y_axis[0]))) + hip = angles["left"]["hip"] + vertices = [] + for point, row in zip(rest_mesh["vertices"], binding["evaluated_weights"]): + source = tuple(point) + transformed = rotate(source, J, axis, -hip) + left_weight = row[1] + row[2] + vertices.append(list(add(scale(source, 1.0 - left_weight), + scale(transformed, left_weight)))) + output["vertices"] = vertices + return output + + +def synthetic_protocol(): + return { + "checks": {"binding_and_pose": {"source_effect_response_max_abs_error": 1.0e-8}}, + "baseline_poses": [ + {"id": "Lhip15_knee0", + "left": {"hip": 15, "knee": 0, "ankle": 0}, + "right": {"hip": 0, "knee": 0, "ankle": 0}}, + ], + "input_perturbations": [ + {"id": "left_A_y_minus_0.02", + "change": {"path": "cases[*].leg_inputs.left.A[1]", + "operation": "add", "value": -0.02}}, + {"id": "left_calf_posterior_radius_times_1.10", + "change": {"path": "cases[*].leg_inputs.left.radii.calf[2]", + "operation": "multiply", "value": 1.10}}, + {"id": "left_J_y_plus_0.01_at_hip15", + "change": {"path": "cases[*].leg_inputs.left.J[1]", + "operation": "add", "value": 0.01}}, + ], + } + + +def posterior_metric_fixture(stable_l0=True, expanding_l2=True, *, + non_extremal_only=False, + direction_invalid=False): + source_frame = { + "F": (0.0, -0.32599068331940423, 0.9453729816262723), + } + template = ( + (-1.0, -9.130123557772671e-18), + (-0.7071067811865475, -0.7071067811865475), + (0.0, 0.0), + (0.0, 1.0), + (0.7071067811865475, 0.7071067811865475), + (1.0, 0.0), + (0.7071067811865475, -0.7071067811865475), + (0.0, -1.0), + ) + direction = scale(source_frame["F"], -1.0) + seam_expected = scale(direction, 5.192757773483211e-20) + stable_expected = scale(direction, 0.004596194077712563) + zero = (0.0, 0.0, 0.0) + invalid = scale(direction, -0.001) if direction_invalid else zero + expected_l0 = [seam_expected, stable_expected, invalid] + [zero] * 6 + actual_l0 = [ + zero, stable_expected if stable_l0 else zero, invalid, *([zero] * 6) + ] + baseline_l0 = [ + (-0.155, -0.45649999999999996, -0.009999999999999998) + for _ in range(9) + ] + centre = (0.0, 0.0, 0.0) + baseline_l2 = [scale(direction, extent) for extent in (2.0, 1.0, 0.0, 10.0)] + stencils = [[(0, 1.0)], [(1, 1.0)], [(2, 1.0)], [(8, 1.0)]] + if non_extremal_only: + expected_l2 = [zero, scale(direction, 0.5), zero, zero] + else: + expected_l2 = [scale(direction, 0.5), scale(direction, 0.25), + invalid, zero] + actual_l2 = copy.deepcopy(expected_l2) if expanding_l2 else [zero] * 4 + return perturbations._calf_posterior_measurement( + baseline_l0, actual_l0, expected_l0, list(range(8)), template, + baseline_l2, stencils, actual_l2, expected_l2, source_frame, + centre, 1.0e-8, + ) + + +class PerturbationEvidenceTests(unittest.TestCase): + def setUp(self): + self.root = synthetic_root() + self.inputs = synthetic_inputs() + self.construction = SyntheticConstruction() + self.binding = SyntheticBinding() + self.baseline_L0 = self.construction.build(self.root, self.inputs) + self.baseline_L2 = copy.deepcopy(self.baseline_L0) + self.baseline_binding = self.binding.bind( + self.baseline_L0, self.baseline_L2, self.root, {}, self.inputs) + self.construction.build_inputs.clear() + self.construction.build_count = 0 + self.construction.evaluate_count = 0 + self.binding.bind_inputs.clear() + self.binding.bind_count = 0 + + def run_evidence(self, inputs=None): + return perturbations.run_case( + self.root, self.baseline_L2, {}, inputs or self.inputs, + self.baseline_L0, self.baseline_L2, self.baseline_binding, + synthetic_protocol(), self.construction, self.binding) + + @staticmethod + def failure_summary(result): + return [(item["id"], item["status"], { + name: details for name, details in item["checks"].items() + if not details.get("pass", False) + }, item["exceptions"]) for item in result["perturbations"]] + + def test_all_three_are_single_pass_and_json_compatible(self): + result = self.run_evidence() + self.assertEqual(result["status"], "pass", self.failure_summary(result)) + self.assertEqual(result["declared_perturbation_ids"], [ + "left_A_y_minus_0.02", + "left_calf_posterior_radius_times_1.10", + "left_J_y_plus_0.01_at_hip15", + ]) + self.assertTrue(all(item["status"] == "pass" for item in result["perturbations"])) + json.dumps(result, allow_nan=False) + self.assertEqual(self.construction.build_count, 3) + self.assertEqual(self.construction.evaluate_count, 3) + self.assertEqual(self.binding.bind_count, 3) + self.assertEqual(self.binding.pose_count, 2) + for sent in self.construction.build_inputs + self.binding.bind_inputs: + self.assertEqual(set(sent), set(SIDES)) + self.assertIn("mid_thigh_factor", sent["left"]) + self.assertIn("support_fraction", sent["right"]) + + def test_asymmetric_ankle_mean_is_not_gated_to_A(self): + result = self.run_evidence() + self.assertEqual(result["status"], "pass", self.failure_summary(result)) + record = result["perturbations"][0] + expected = record["expected"]["ankle_expected_world_loop_mean"] + A = self.inputs["left"]["A"] + self.assertGreater(abs(expected[2] - A[2]), 1.0e-6) + self.assertIn("l2_ankle_mean_matches_analytic_l0_mean", record["checks"]) + self.assertTrue(record["checks"]["l2_ankle_mean_matches_analytic_l0_mean"]["pass"]) + + def test_calf_uses_signed_piecewise_stencil_expectation(self): + result = self.run_evidence() + self.assertEqual(result["status"], "pass", self.failure_summary(result)) + record = result["perturbations"][1] + coefficients = record["expected"]["piecewise_calf_posterior_coefficients"] + self.assertAlmostEqual(coefficients["knee_post_support"], 0.12 / 0.35) + self.assertEqual(coefficients["calf"], 1.0) + self.assertAlmostEqual(coefficients["ankle_approach"], 0.28 / 0.65) + self.assertEqual(coefficients["ankle"], 0.0) + self.assertTrue(record["checks"]["analytic_full_stencil_L2_response"]["pass"]) + self.assertTrue(record["checks"]["ankle_boundary_and_loop_mean_unchanged"]["pass"]) + metric = record["checks"]["signed_calf_posterior_expansion"] + self.assertTrue(metric["support_envelope"]["actual_expansion_in_minus_localF"]) + self.assertGreater(metric["support_envelope"]["extent_difference_m"], 1.0e-8) + self.assertEqual( + metric["exact_planar_section"]["definition"], + "the eight exact L0 calf-ring samples only", + ) + self.assertTrue(record["checks"]["root_and_other_leg_unchanged"]["pass"]) + + def test_anthro_seam_is_indeterminate_but_stable_zero_response_fails(self): + seam = posterior_metric_fixture(stable_l0=True, expanding_l2=True) + samples = seam["source_samples"] + self.assertEqual(samples[0]["domain"], "posterior-indeterminate") + self.assertEqual(samples[0]["response_status"], "indeterminate-bounded") + self.assertLess(samples[0]["expected_signed_minus_localF"], + samples[0]["projected_ulp_bound"]) + self.assertEqual(samples[1]["domain"], "posterior-stable") + self.assertTrue(samples[1]["pass"]) + self.assertTrue(seam["pass"], seam) + + stable_zero = posterior_metric_fixture(stable_l0=False, expanding_l2=True) + stable_sample = stable_zero["source_samples"][1] + self.assertEqual(stable_sample["domain"], "posterior-stable") + self.assertEqual(stable_sample["response_status"], "failed-nonpositive") + self.assertFalse(stable_zero["pass"], stable_zero) + + def test_l2_support_envelope_without_expansion_fails(self): + metric = posterior_metric_fixture(stable_l0=True, expanding_l2=False) + self.assertGreater(metric["support_envelope"]["l2_vertex_count"], 0) + self.assertFalse(metric["support_envelope"]["actual_expansion_in_minus_localF"]) + self.assertFalse(metric["pass"], metric) + + def test_non_extremal_posterior_motion_does_not_count_as_envelope_growth(self): + metric = posterior_metric_fixture( + stable_l0=True, expanding_l2=True, non_extremal_only=True, + ) + envelope = metric["support_envelope"] + self.assertGreater(envelope["samples"][1]["actual_signed_minus_localF"], 0.0) + self.assertEqual(envelope["baseline_extremum"]["l2_vertex_id"], 0) + self.assertEqual(envelope["actual_extremum"]["l2_vertex_id"], 0) + self.assertEqual(envelope["extent_difference_m"], 0.0) + self.assertFalse(envelope["actual_expansion_in_minus_localF"]) + self.assertFalse(metric["pass"], metric) + + def test_direction_invalid_rows_are_retained_in_pass_reduction(self): + metric = posterior_metric_fixture( + stable_l0=True, expanding_l2=True, direction_invalid=True, + ) + source_row = metric["source_samples"][2] + support_row = next( + row for row in metric["support_envelope"]["samples"] + if row["l2_vertex_id"] == 2 + ) + self.assertEqual(source_row["domain"], "opposite-frame-response") + self.assertEqual(support_row["domain"], "opposite-frame-response") + self.assertFalse(source_row["pass"]) + self.assertFalse(support_row["pass"]) + self.assertFalse(metric["pass"], metric) + + def test_legacy_outer_factor_shape_is_unavailable_without_adaptation(self): + legacy = copy.deepcopy(self.inputs) + legacy["mid_thigh_factor"] = 0.85 + legacy["support_fraction"] = 0.10 + for side in SIDES: + del legacy[side]["mid_thigh_factor"] + del legacy[side]["support_fraction"] + result = self.run_evidence(legacy) + self.assertEqual(result["status"], "unavailable") + self.assertEqual(self.construction.build_count, 0) + self.assertIn("left and right sides", result["exceptions"][0]["message"]) + + def test_J_allows_only_intended_pose_metadata_and_rejects_shape_changes(self): + result = self.run_evidence() + self.assertEqual(result["status"], "pass", self.failure_summary(result)) + record = result["perturbations"][2] + for level in ("L0", "L2"): + self.assertTrue( + record["checks"][ + f"rest_{level}_shape_exactly_unchanged_except_pose_only_J" + ]["pass"] + ) + self.assertTrue( + record["checks"][ + f"rest_{level}_pose_only_J_matches_intended_source" + ]["pass"] + ) + self.assertTrue( + record["checks"][ + f"rest_{level}_only_declared_pose_only_J_metadata_changed" + ]["pass"] + ) + expected_J = [self.inputs["left"]["J"][0], + self.inputs["left"]["J"][1] + 0.01, + self.inputs["left"]["J"][2]] + self.assertEqual( + record["checks"]["rest_L0_pose_only_J_matches_intended_source"][ + "actual_pose_only_J" + ], + expected_J, + ) + + def candidate_with_expected_J(): + candidate = copy.deepcopy(self.baseline_L0) + candidate["metadata"]["chains"]["left"]["pose_only_J"] = expected_J + return candidate + + moved_vertex = candidate_with_expected_J() + moved_vertex["vertices"][16][0] += 0.01 + self.assertFalse( + perturbations._compare_rest_construction( + self.baseline_L0, moved_vertex, "left", expected_J, "vertex" + )["all_other_fields_equal"] + ) + + changed_stencil = candidate_with_expected_J() + changed_stencil["base_stencils"][16][0][1] = 0.5 + self.assertFalse( + perturbations._compare_rest_construction( + self.baseline_L0, changed_stencil, "left", expected_J, "stencil" + )["all_other_fields_equal"] + ) + + changed_topology = candidate_with_expected_J() + changed_topology["loops"]["port.left_ankle"] = [16, 17, 18, 19, + 20, 21, 22, 23] + self.assertFalse( + perturbations._compare_rest_construction( + self.baseline_L0, changed_topology, "left", expected_J, "topology" + )["all_other_fields_equal"] + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/connected-leg-assembly/tests/test_root_source.py b/experiments/connected-leg-assembly/tests/test_root_source.py new file mode 100644 index 0000000..0d46036 --- /dev/null +++ b/experiments/connected-leg-assembly/tests/test_root_source.py @@ -0,0 +1,172 @@ +import copy +import json +import sys +import unittest +from collections.abc import Mapping +from pathlib import Path +from unittest import mock + + +EXPERIMENT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(EXPERIMENT)) +import root_source # noqa: E402 + + +def _json(path): + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def _difference_paths(expected, actual, path="$", limit=12): + if limit <= 0: + return [path] + if type(expected) is not type(actual): + return [f"{path} (types {type(expected).__name__}/{type(actual).__name__})"] + if isinstance(expected, Mapping): + differences = [] + for key in sorted(set(expected) | set(actual), key=str): + child = f"{path}.{key}" + if key not in expected or key not in actual: + differences.append(child) + else: + differences.extend( + _difference_paths(expected[key], actual[key], child, + limit - len(differences)) + ) + if len(differences) >= limit: + return differences[:limit] + return differences + if isinstance(expected, list): + differences = [] + if len(expected) != len(actual): + differences.append(f"{path} (length {len(expected)}/{len(actual)})") + for index, (left, right) in enumerate(zip(expected, actual)): + differences.extend( + _difference_paths(left, right, f"{path}[{index}]", + limit - len(differences)) + ) + if len(differences) >= limit: + return differences[:limit] + return differences + return [] if expected == actual else [path] + + +class RootSourceTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.document = _json(EXPERIMENT / "inputs.json") + + def test_both_recorded_source_cases_rebuild_saved_L0_and_L2_exactly(self): + for case in self.document["cases"]: + source_case = _json(case["original_case"]["path"]) + rebuilt = root_source.reconstruct_source_case(source_case) + cls = case["id"] + self.assertEqual(rebuilt["source_case_id"], cls) + self.assertTrue( + rebuilt["provenance"]["frozen_construction"]["sha256"] + ) + for level, reference_key in (("L0", "root_mesh"), + ("L2", "prior_rest_mesh")): + expected = _json(case[reference_key]["path"]) + actual = rebuilt["levels"][level] + differences = _difference_paths(expected, actual) + self.assertFalse( + differences, + f"{cls} {level} differs at: {', '.join(differences)}", + ) + + def test_provenance_selects_immutable_captured_runner_not_live_sibling(self): + case = self.document["cases"][0] + source_case = _json(case["original_case"]["path"]) + rebuilt = root_source.reconstruct_source_case(source_case) + runner_path = Path(rebuilt["provenance"]["calibration_runner"]["path"]) + live_sibling = EXPERIMENT.parent / "pelvis-source-calibration" / "runner.py" + self.assertEqual(runner_path, root_source.CALIBRATION_RUNNER_PATH) + self.assertNotEqual(runner_path.resolve(), live_sibling.resolve()) + self.assertTrue(str(runner_path).startswith( + "/home/ben/.cache/creature-kernel/pelvis-source-calibration-set-1/" + )) + self.assertEqual( + rebuilt["provenance"]["calibration_runner"]["manifest_path"], + str(root_source.CALIBRATION_SOURCE_MANIFEST_PATH), + ) + self.assertEqual( + rebuilt["provenance"]["frozen_construction"]["dependency_root"], + "/home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot", + ) + + def test_recorded_source_component_reaches_frozen_consumer(self): + case = self.document["cases"][0] + source_case = _json(case["original_case"]["path"]) + changed = copy.deepcopy(source_case) + key = "stations.lower_pelvis.C.y" + changed["components"][key] = float(changed["components"][key]) + 0.001 + + baseline = root_source.reconstruct_source_case(source_case) + perturbed = root_source.reconstruct_source_case(changed) + baseline_l0 = baseline["levels"]["L0"] + perturbed_l0 = perturbed["levels"]["L0"] + self.assertNotEqual(baseline_l0["vertices"], perturbed_l0["vertices"]) + self.assertEqual(baseline_l0["quads"], perturbed_l0["quads"]) + self.assertEqual(baseline_l0["loops"], perturbed_l0["loops"]) + + def test_optional_constructor_transform_installs_locally_before_build(self): + construction = mock.Mock() + calibration_runner = mock.Mock() + verified_provenance = { + "calibration_runner": {"path": "runner.py"}, + "frozen_construction": {"sha256": "frozen"}, + "calibration_runner_module": calibration_runner, + } + events = [] + + def build(components, attachments, diagnostic): + self.assertEqual(events, ["transform"]) + self.assertEqual(components, {"component": 1}) + self.assertEqual(attachments, {"attachment": 2}) + self.assertTrue(diagnostic) + self.assertEqual(construction.source_provider, {"name": "torso"}) + events.append("build") + return {"mesh": "built"} + + def evaluate(built, levels): + self.assertEqual(events, ["transform", "build"]) + self.assertEqual(built, {"mesh": "built"}) + self.assertEqual(levels, 2) + events.append("evaluate") + return [{"level": 0}, {"level": 1}, {"level": 2}] + + construction.build.side_effect = build + construction.evaluate.side_effect = evaluate + calibration_runner._bounded.side_effect = lambda value: value + + def transform(private_constructor, complete_provenance): + self.assertIs(private_constructor, construction) + self.assertIs(complete_provenance, verified_provenance) + construction.source_provider = {"name": "torso"} + events.append("transform") + return {"provider": "torso", "config_sha256": "config"} + + source_case = { + "id": "mock-case", + "components": {"component": 1}, + "attachments": {"attachment": 2}, + } + with mock.patch.object( + root_source, "_load_frozen_construction", + return_value=(construction, verified_provenance)): + rebuilt = root_source.reconstruct_source_case( + source_case, constructor_transform=transform) + + self.assertEqual(events, ["transform", "build", "evaluate"]) + self.assertEqual( + rebuilt["provenance"]["source_refinement"], + {"provider": "torso", "config_sha256": "config"}, + ) + self.assertNotIn("calibration_runner_module", rebuilt["provenance"]) + self.assertIs( + verified_provenance["calibration_runner_module"], calibration_runner + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/connected-leg-assembly/tests/test_runner.py b/experiments/connected-leg-assembly/tests/test_runner.py new file mode 100644 index 0000000..231f9f2 --- /dev/null +++ b/experiments/connected-leg-assembly/tests/test_runner.py @@ -0,0 +1,1034 @@ +from __future__ import annotations + +import json +import hashlib +from pathlib import Path +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +import runner # noqa: E402 + + +def _dependency(root: Path) -> dict[str, object]: + return { + "identity": { + "root": str(root / "transition"), + "runtime": {"executable": str(root / "transition/runtime/bin/python")}, + }, + "renderer": {"path": str(root / "transition/source/render.py"), "bytes": 3, "sha256": "abc"}, + } + + +class RunnerTests(unittest.TestCase): + def test_json_serialization_is_finite_and_stable(self) -> None: + value = {"tuple": (1, 2), "nested": {"z": True, "a": 1.5}} + first = runner._json_bytes(value) + second = runner._json_bytes({"nested": {"a": 1.5, "z": True}, "tuple": [1, 2]}) + self.assertEqual(first, second) + self.assertEqual(json.loads(first), {"nested": {"a": 1.5, "z": True}, "tuple": [1, 2]}) + with self.assertRaises(runner.RunnerError): + runner._json_bytes({"bad": float("nan")}) + + def test_dynamic_import_registers_before_execution(self) -> None: + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "module.py" + path.write_text("import sys\nREGISTERED = sys.modules[__name__] is not None\n", encoding="utf-8") + loaded = runner._load_module("connected_leg_test_module", path) + self.assertIs(sys.modules["connected_leg_test_module"], loaded) + self.assertTrue(loaded.REGISTERED) + + def test_protocol_baseline_poses_preserve_zero_ankle_angles(self) -> None: + poses = runner._protocol_poses({"baseline_poses": [{ + "id": "rest", "left": {"hip": 0, "knee": 0, "ankle": 0}, + "right": {"hip": 2, "knee": 3, "ankle": 0}, + }]}) + self.assertEqual(poses[0]["angles"]["left"]["ankle"], 0) + self.assertEqual(poses[0]["angles"]["right"]["knee"], 3) + + def test_actual_protocol_pose_metadata_is_not_forwarded_as_angles(self) -> None: + protocol, _ = runner._read_json(runner.HERE / "protocol.json") + poses = runner._protocol_poses(protocol) + self.assertEqual([pose["id"] for pose in poses], + [row["id"] for row in protocol["baseline_poses"]]) + mirrored = next(pose for pose in poses if pose["id"] == "mirrored15_15") + self.assertEqual(set(mirrored["angles"]), {"left", "right"}) + self.assertEqual(mirrored["angles"]["right"]["ankle"], 0) + + def test_protocol_perturbations_are_explicitly_pending(self) -> None: + status = runner._perturbation_status({"input_perturbations": [{"id": "left_A"}]}) + self.assertEqual(status["status"], "not-implemented") + self.assertEqual(status["execution"], "not-run") + self.assertEqual(status["declared_ids"], ["left_A"]) + + def test_new_full_foot_capture_includes_broadphase_wrapper_and_test(self) -> None: + self.assertIn("collision_broadphase.py", runner.CAPTURE_FILES) + self.assertIn("tests/test_collision_broadphase.py", runner.CAPTURE_FILES) + + def test_chest_envelope_evidence_helper_is_in_source_and_test_inventory(self) -> None: + self.assertIn("chest_envelope_evidence.py", runner.CAPTURE_FILES) + self.assertIn("tests/test_chest_envelope_evidence.py", runner.CAPTURE_FILES) + + def test_body_capture_bundle_includes_assembly_components_and_inputs(self) -> None: + for name in ( + "body_assembly.py", "arm_construction.py", "head_construction.py", + "arm-inputs.json", "head-inputs.json", + "tests/test_body_assembly.py", "tests/test_arm_construction.py", + "tests/test_arm_refinement.py", + "tests/test_head_construction.py", "torso_refinement.py", + "tests/test_head_refinement.py", + "torso-refinement-inputs.json", "foot_form_construction.py", + "foot-form-inputs.json", "tail_construction.py", "tail-inputs.json", + "head-refinement-inputs.json", "body-config.json", + "body-refinement-internal-config.json", "tests/test_torso_refinement.py", + "torso-chest-depth-ablation-inputs.json", + "body-chest-depth-ablation-config.json", + "torso-chest-envelope-inputs.json", + "body-chest-envelope-config.json", + "thorax_foundation.py", + "thorax-foundation-baseline-inputs.json", + "thorax-foundation-width-inputs.json", + "thorax-foundation-fullness-inputs.json", + "body-thorax-foundation-baseline-config.json", + "body-thorax-foundation-width-config.json", + "body-thorax-foundation-fullness-config.json", + "tests/test_foot_form_construction.py", "tests/test_tail_construction.py", + ): + self.assertIn(name, runner.CAPTURE_FILES) + + def test_chest_envelope_preserves_junction_non_torso_config_projection(self) -> None: + junction, _ = runner._read_json( + ROOT / "body-junction-integration-config.json" + ) + envelope, _ = runner._read_json( + ROOT / "body-chest-envelope-config.json" + ) + excluded = {"schema", "evidence_label", "rationale", "budget", "torso_refinement"} + junction_projection = { + key: value for key, value in junction.items() if key not in excluded + } + envelope_projection = { + key: value for key, value in envelope.items() if key not in excluded + } + self.assertEqual(envelope_projection, junction_projection) + self.assertEqual( + envelope["torso_refinement"], + {"inputs": "torso-chest-envelope-inputs.json"}, + ) + + def test_new_body_components_require_explicit_body_config_selection(self) -> None: + legacy_foot = object() + form_foot = object() + torso = object() + thorax_foundation = object() + tail = object() + arms = object() + head = object() + modules = { + "foot_construction": legacy_foot, + "foot_inputs": {"cases": [{"case_id": "case", "sides": {}}]}, + "foot_form_construction": form_foot, + "foot_form_inputs": {"cases": [{"case_id": "case", + "construction": {}, "sides": {}}]}, + "torso_refinement": torso, + "torso_refinement_inputs": {"schema": "torso"}, + "torso_chest_depth_ablation_inputs": {"schema": "chest-depth-ablation"}, + "torso_chest_envelope_inputs": {"schema": "chest-envelope"}, + "thorax_foundation": thorax_foundation, + "thorax_foundation_baseline_inputs": {"schema": "thorax-baseline"}, + "thorax_foundation_width_inputs": {"schema": "thorax-width"}, + "thorax_foundation_fullness_inputs": {"schema": "thorax-fullness"}, + "arm_construction": arms, + "arm_inputs": {"cases": [{"case_id": "case", "sides": {}}]}, + "head_construction": head, + "head_inputs": {"cases": [{"case_id": "case", "head": {}}]}, + "head_refinement_inputs": {"cases": [{"case_id": "case", "head": {}}]}, + "tail_construction": tail, + "tail_inputs": {"cases": [{"case_id": "case", "enabled": False}]}, + } + baseline = runner._body_optional_inputs(modules, "case") + self.assertIs(baseline["foot_builder"], legacy_foot) + self.assertIs(baseline["foot_inputs"], modules["foot_inputs"]["cases"][0]["sides"]) + self.assertIsNone(baseline["source_refinement_inputs"]) + self.assertIsNone(baseline["thorax_foundation_inputs"]) + self.assertIsNone(baseline["thorax_foundation"]) + self.assertIsNone(baseline["tail_inputs"]) + + for filename, input_key in ( + ("thorax-foundation-baseline-inputs.json", "thorax_foundation_baseline_inputs"), + ("thorax-foundation-width-inputs.json", "thorax_foundation_width_inputs"), + ("thorax-foundation-fullness-inputs.json", "thorax_foundation_fullness_inputs"), + ): + foundation = runner._body_optional_inputs( + modules, "case", {"thorax_foundation": {"inputs": filename}} + ) + self.assertIs(foundation["thorax_foundation"], thorax_foundation) + self.assertIs(foundation["thorax_foundation_inputs"], modules[input_key]) + self.assertEqual(foundation["thorax_foundation_input_name"], filename) + + with self.assertRaisesRegex(runner.RunnerError, "mutually exclusive"): + runner._body_optional_inputs( + modules, "case", { + "torso_refinement": {"inputs": "torso-refinement-inputs.json"}, + "thorax_foundation": { + "inputs": "thorax-foundation-baseline-inputs.json" + }, + } + ) + missing_input = dict(modules) + del missing_input["thorax_foundation_width_inputs"] + with self.assertRaisesRegex(runner.RunnerError, "requires thorax-foundation-width-inputs.json"): + runner._body_optional_inputs( + missing_input, "case", { + "thorax_foundation": {"inputs": "thorax-foundation-width-inputs.json"} + } + ) + missing_provider = dict(modules) + del missing_provider["thorax_foundation"] + with self.assertRaisesRegex(runner.RunnerError, "requires thorax_foundation.py"): + runner._body_optional_inputs( + missing_provider, "case", { + "thorax_foundation": { + "inputs": "thorax-foundation-baseline-inputs.json" + } + } + ) + + missing_arm_refinement = dict(modules) + with self.assertRaisesRegex(runner.RunnerError, "requires arm-refinement-inputs.json"): + runner._body_optional_inputs( + missing_arm_refinement, "case", { + "arms": {"inputs": "arm-refinement-inputs.json"} + } + ) + missing_head_refinement = dict(modules) + del missing_head_refinement["head_refinement_inputs"] + with self.assertRaisesRegex(runner.RunnerError, "requires head-refinement-inputs.json"): + runner._body_optional_inputs( + missing_head_refinement, "case", { + "head": {"inputs": "head-refinement-inputs.json"} + } + ) + omitted_optional_inputs = dict(modules) + del omitted_optional_inputs["arm_inputs"] + del omitted_optional_inputs["head_inputs"] + omitted = runner._body_optional_inputs(omitted_optional_inputs, "case") + self.assertIsNone(omitted["arm_inputs"]) + self.assertIsNone(omitted["head_inputs"]) + + selected = runner._body_optional_inputs( + modules, "case", { + "torso_refinement": {"inputs": "torso-refinement-inputs.json"}, + "arms": {"inputs": "arm-inputs.json"}, + "head": {"inputs": "head-refinement-inputs.json"}, + "feet": {"builder": "foot_form_construction.py", + "inputs": "foot-form-inputs.json"}, + "tail": {"builder": "tail_construction.py", + "inputs": "tail-inputs.json"}, + } + ) + self.assertIs(selected["foot_builder"], form_foot) + self.assertIs(selected["foot_inputs"], modules["foot_form_inputs"]["cases"][0]) + self.assertIs(selected["source_refinement_inputs"], modules["torso_refinement_inputs"]) + self.assertIs(selected["arm_inputs"], modules["arm_inputs"]["cases"][0]["sides"]) + self.assertIs(selected["head_inputs"], modules["head_refinement_inputs"]["cases"][0]["head"]) + self.assertIs(selected["tail_builder"], tail) + self.assertIs(selected["tail_inputs"], modules["tail_inputs"]["cases"][0]) + + ablation = runner._body_optional_inputs( + modules, "case", { + "torso_refinement": { + "inputs": "torso-chest-depth-ablation-inputs.json" + } + } + ) + self.assertIs( + ablation["source_refinement_inputs"], + modules["torso_chest_depth_ablation_inputs"], + ) + + envelope = runner._body_optional_inputs( + modules, "case", { + "torso_refinement": { + "inputs": "torso-chest-envelope-inputs.json" + } + } + ) + self.assertIs( + envelope["source_refinement_inputs"], + modules["torso_chest_envelope_inputs"], + ) + + diagnostic = runner._body_optional_inputs( + modules, "case", { + "feet": {"builder": "foot_construction.py", "inputs": "foot-inputs.json"}, + "arms": {"inputs": "arm-inputs.json"}, + "head": {"inputs": "head-refinement-inputs.json"}, + } + ) + self.assertIs(diagnostic["foot_builder"], legacy_foot) + self.assertIs(diagnostic["foot_inputs"], modules["foot_inputs"]["cases"][0]["sides"]) + self.assertIs(diagnostic["head_inputs"], modules["head_refinement_inputs"]["cases"][0]["head"]) + + def test_prepare_captures_tail_bundle_without_enabling_tail_execution(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + source = root / "experiment" + (source / "tests").mkdir(parents=True) + tail_files = { + "runner.py": "# captured runner\n", + "tail_construction.py": "# current tail constructor\n", + "tail-inputs.json": "{\"source_case\": \"ordinary\"}\n", + "tail-stage.md": "# tail stage\n", + "tests/test_tail_construction.py": "# focused tail test\n", + } + for name, text in tail_files.items(): + path = source / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + + dependency = _dependency(root) + snapshot = root / "snapshot" + with mock.patch.object(runner, "HERE", source), \ + mock.patch.object(runner, "CAPTURE_FILES", tuple(tail_files)), \ + mock.patch.object(runner, "_dependency_identity", return_value=dependency): + manifest = runner.prepare(snapshot) + + captured = {row["path"] for row in manifest["source"]["files"]} + self.assertEqual(captured, set(tail_files)) + self.assertTrue(all( + (snapshot / "source/experiments/connected-leg-assembly" / name).is_file() + for name in tail_files + )) + self.assertNotIn("tail", manifest["source"].get("loaded_modules", [])) + + def test_body_pose_transport_preserves_head_angles(self) -> None: + poses = runner._protocol_poses({"baseline_poses": [{ + "id": "combined", "left": {"hip": 1, "knee": 2}, + "right": {"hip": 3, "knee": 4}, "head": {"yaw": 6, "nod": 4}, + }]}) + self.assertEqual(poses[0]["angles"]["head"], {"yaw": 6, "nod": 4}) + + def test_rest_only_construction_exception_is_overall_error(self) -> None: + class FailingConstruction: + @staticmethod + def build(_root, _leg_inputs): + raise ValueError("synthetic constructor input-shape failure") + + @staticmethod + def evaluate(_built): + raise AssertionError("evaluate must not run after build failure") + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + snapshot = root / "snapshot" + source = snapshot / "source/experiments/connected-leg-assembly" + source.mkdir(parents=True) + (source / "runner.py").write_text("captured runner\n", encoding="utf-8") + (source / "protocol.json").write_text( + json.dumps({"baseline_poses": [{"id": "rest", "left": {"ankle": 0}, "right": {"ankle": 0}}]}), + encoding="utf-8") + (source / "inputs.json").write_text(json.dumps({"cases": [{"id": "human", "leg_inputs": {}}]}), encoding="utf-8") + input_root = snapshot / "inputs" + input_root.mkdir() + for name, value in (("root.json", {}), ("rest.json", {}), ("binding.json", {})): + (input_root / name).write_text(json.dumps(value), encoding="utf-8") + path_map = [] + for field, name in (("root_mesh", "root.json"), ("prior_rest_mesh", "rest.json"), ("prior_hip_binding", "binding.json")): + path_map.append({"case_id": "human", "field": field, "snapshot_path": f"inputs/{name}"}) + manifest = {"schema": "synthetic", "input_manifest": {"path_map": path_map}} + output = root / "output" + with mock.patch.object(runner, "verify", return_value=manifest) as verify_mock, \ + mock.patch.object(runner, "__file__", str(source / "runner.py")), \ + mock.patch.object(runner, "_load_collaborators", return_value={"construction": FailingConstruction()}): + report = runner.run(snapshot, output, rest_only=True) + self.assertEqual(report["cases"][0]["status"], "exception") + self.assertEqual(report["status"], "error") + self.assertFalse(report["full_pass"]) + self.assertEqual(verify_mock.call_count, 2) + self.assertEqual(report["post_run_verification"]["status"], "verified") + self.assertTrue((output / "run-report.json").is_file()) + + def test_full_run_without_checks_keeps_unchecked_pose_evidence(self) -> None: + mesh = {"vertices": [[0.0, 0.0, 0.0]], "quads": []} + + class Construction: + @staticmethod + def build(_root, _leg_inputs): + return mesh + + @staticmethod + def evaluate(_base): + return [mesh] + + class Binding: + @staticmethod + def bind(*_args): + return {"synthetic": True} + + @staticmethod + def pose(_rest, _binding, _angles): + return mesh + + @staticmethod + def joint_points(_binding, _angles): + return {"left": {"J": [0.0, 0.0, 0.0], "T": [0.0, -1.0, 0.0]}} + + protocol = {"baseline_poses": [ + {"id": "rest", "left": {"hip": 0, "knee": 0, "ankle": 0}, "right": {"hip": 0, "knee": 0, "ankle": 0}}, + {"id": "moving", "left": {"hip": 15, "knee": 10, "ankle": 0}, "right": {"hip": 0, "knee": 0, "ankle": 0}}, + ]} + case = {"id": "synthetic", "leg_inputs": {}} + values = {"root_mesh": mesh, "prior_rest_mesh": mesh, "prior_hip_binding": {}, "leg_inputs": {}} + with tempfile.TemporaryDirectory() as directory: + result = runner._case_run( + {"id": "synthetic", "case": case, "values": values}, + protocol, {"construction": Construction(), "binding": Binding()}, + Path(directory) / "case", rest_only=False) + self.assertEqual(result["status"], "pending", result) + self.assertFalse(result["full_pass"]) + self.assertEqual([pose["id"] for pose in result["poses"]], ["rest", "moving"]) + self.assertEqual(result["checks"]["status"], "pending") + self.assertEqual(len(result["bounds_inputs"]), len(result["poses"]) + 1) + + def test_source_rebuild_is_authoritative_and_foot_uses_final_mesh(self) -> None: + cached_root = {"name": "cached-root", "vertices": [[0.0, 0.0, 0.0]], "quads": []} + cached_rest = {"name": "cached-rest", "vertices": [[0.0, 0.0, 0.0]], "quads": []} + source_root = {"name": "source-root", "vertices": [[1.0, 0.0, 0.0]], "quads": []} + source_rest = {"name": "source-rest", "vertices": [[1.0, 1.0, 0.0]], "quads": []} + leg_l0 = {"name": "leg-L0", "vertices": [[2.0, 0.0, 0.0]], "quads": []} + leg_l2 = {"name": "leg-L2", "vertices": [[2.0, 1.0, 0.0]], "quads": []} + foot_l0 = {"name": "foot-L0", "vertices": [[3.0, 0.0, 0.0]], "quads": []} + foot_l2 = {"name": "foot-L2", "vertices": [[3.0, 1.0, 0.0]], "quads": []} + calls: list[tuple[str, object]] = [] + + class Construction: + @staticmethod + def build(root, _leg_inputs): + calls.append(("leg-root", root)) + return leg_l0 + + @staticmethod + def evaluate(_mesh, levels=2): + self.assertEqual(levels, 2) + return [leg_l0, leg_l2] + + class RootSource: + @staticmethod + def reconstruct_source_case(_case): + return {"levels": {"L0": source_root, "L2": source_rest}, + "provenance": {"adapter": "root"}} + + source_binding = {"base_weights": [[1.0]], "evaluated_weights": [[1.0]], + "rest_frames": {"left": {}}} + + class HipSource: + @staticmethod + def bind_source_case(root, rest, _case, leg_inputs=None): + calls.extend([("hip-root", root), ("hip-rest", rest), + ("hip-inputs", leg_inputs)]) + return {"binding": source_binding, "provenance": {"adapter": "hip"}} + + class FootConstruction: + @staticmethod + def build(base, _leg_inputs, _foot_inputs): + calls.append(("foot-base", base)) + return foot_l0 + + @staticmethod + def evaluate(_mesh, levels=2): + self.assertEqual(levels, 2) + return [foot_l0, foot_l2] + + class Binding: + @staticmethod + def bind(*args): + calls.append(("final-binding", args)) + return {"joint_order": [], "evaluated_weights": [[1.0]]} + + @staticmethod + def pose(mesh, _binding, _angles): + calls.append(("pose-mesh", mesh)) + return mesh + + @staticmethod + def joint_points(_binding, _angles): + return {} + + protocol = {"baseline_poses": [{"id": "rest", "left": {}, "right": {}}]} + leg_inputs = {"left": {}, "right": {}} + modules = { + "construction": Construction(), "root_source": RootSource(), + "hip_source": HipSource(), "foot_construction": FootConstruction(), + "foot_inputs": {"cases": [{"case_id": "synthetic", + "sides": {"left": {}, "right": {}}}]}, + "binding": Binding(), + } + values = {"root_mesh": cached_root, "prior_rest_mesh": cached_rest, + "prior_hip_binding": {"cached": True}, "original_case": {}, + "leg_inputs": leg_inputs} + with tempfile.TemporaryDirectory() as directory: + legacy_case = Path(directory) / "case" + result = runner._case_run( + {"id": "synthetic", "case": {"id": "synthetic"}, "values": values}, + protocol, modules, legacy_case, rest_only=False) + self.assertFalse( + (legacy_case / "thorax-foundation-source-evidence.json").exists() + ) + + self.assertEqual(result["materialization"], "source-rebuilt") + self.assertTrue(result["foot_materialized"]) + self.assertEqual(dict(calls)["leg-root"], source_root) + self.assertEqual(dict(calls)["foot-base"], leg_l0) + final_binding = dict(calls)["final-binding"] + self.assertEqual(final_binding[0], foot_l0) + self.assertEqual(final_binding[1], foot_l2) + self.assertIs(final_binding[2], source_root) + self.assertIs(final_binding[3], source_binding) + self.assertEqual(result["source_rebuild"]["cache_role"], + "comparison-only; never a construction or binding input") + + def test_source_body_mode_injects_captured_modules_and_uses_final_levels(self) -> None: + cached_root = {"name": "root", "vertices": [[0.0, 0.0, 0.0]], "quads": []} + cached_rest = {"name": "root-rest", "vertices": [[0.0, 1.0, 0.0]], "quads": []} + cached_binding = {"base_weights": [], "evaluated_weights": [], "rest_frames": {}} + leg_l0 = {"name": "leg-l0", "vertices": [[1.0, 0.0, 0.0]], "quads": []} + leg_l1 = {"name": "leg-l1", "vertices": [[1.0, 0.5, 0.0]], "quads": []} + leg_l2 = {"name": "leg-l2", "vertices": [[1.0, 1.0, 0.0]], "quads": []} + final_l0 = {"name": "body-l0", "vertices": [[2.0, 0.0, 0.0]], "quads": []} + final_l2 = {"name": "body-l2", "vertices": [[2.0, 2.0, 0.0]], "quads": []} + foundation_root = {"name": "foundation-root", "vertices": [[9.0, 0.0, 0.0]], "quads": []} + foundation_rest = {"name": "foundation-rest", "vertices": [[9.0, 2.0, 0.0]], "quads": []} + foundation_binding = {"base_weights": [9], "evaluated_weights": [9], + "rest_frames": {"foundation": True}} + events = [] + + class Construction: + @staticmethod + def build(root, _legs): + events.append(("leg-build", root)) + return leg_l0 + + @staticmethod + def evaluate(mesh, levels=2): + events.append(("leg-evaluate", mesh, levels)) + return [leg_l0, leg_l1, leg_l2] + + class RootSource: + reconstruct_source_case = staticmethod(lambda _case: {"levels": { + "L0": cached_root, "L2": cached_rest}}) + + class HipSource: + bind_source_case = staticmethod(lambda *_args, **_kwargs: { + "binding": cached_binding, "provenance": {"adapter": "hip"}}) + + class Body: + class AssemblyDependencies: + def __init__(self, **kwargs): + self.kwargs = kwargs + events.append(("dependencies", kwargs)) + + @staticmethod + def assemble(source_case, legs, *, foot_inputs, arm_inputs, + head_inputs, dependencies, thorax_foundation_inputs=None): + events.append(("body", source_case, legs, foot_inputs, + arm_inputs, head_inputs, dependencies, + thorax_foundation_inputs)) + rebuilt_root_l0 = ( + foundation_root if thorax_foundation_inputs is not None else cached_root + ) + rebuilt_root_l2 = ( + foundation_rest if thorax_foundation_inputs is not None else cached_rest + ) + rebuilt_binding = ( + foundation_binding if thorax_foundation_inputs is not None else cached_binding + ) + result = { + "rebuilt_root_l0": rebuilt_root_l0, + "rebuilt_root_l2": rebuilt_root_l2, + "rebuilt_root_binding": rebuilt_binding, + "final_l0": final_l0, + "final_l2": final_l2, + "binding": {"body": True}, + "source_provenance": {"root": {}, "hip": {}}, + "component_manifest": {"arms": {"status": "built"}}, + } + if thorax_foundation_inputs is not None: + result["foundation_records"] = { + "selected_inputs": thorax_foundation_inputs, + } + return result + + class Binding: + @staticmethod + def pose(rest, _binding, angles): + events.append(("pose", rest, angles)) + return rest + + @staticmethod + def joint_points(_binding, _angles): + return {} + + arm_module = object() + head_module = object() + foot_module = object() + modules = { + "construction": Construction(), "root_source": RootSource(), + "hip_source": HipSource(), "body_assembly": Body(), + "binding": Binding(), "foot_construction": foot_module, + "arm_construction": arm_module, "head_construction": head_module, + "foot_inputs": {"cases": [{"case_id": "synthetic", "sides": {}}]}, + "arm_inputs": {"cases": [{"case_id": "synthetic", "sides": {}}]}, + "head_inputs": {"cases": [{"case_id": "synthetic", "head": {}}]}, + "thorax_foundation": object(), + "thorax_foundation_baseline_inputs": {"schema": "thorax-baseline"}, + "thorax_foundation_width_inputs": {"schema": "thorax-width"}, + "thorax_foundation_fullness_inputs": {"schema": "thorax-fullness"}, + } + values = {"root_mesh": cached_root, "prior_rest_mesh": cached_rest, + "prior_hip_binding": cached_binding, + "original_case": {"id": "synthetic"}, "leg_inputs": {}} + protocol = runner._body_provisional_protocol( + {"input_perturbations": []}, has_arms=True, has_head=True) + with tempfile.TemporaryDirectory() as directory: + legacy_case = Path(directory) / "case" + result = runner._case_run( + {"id": "synthetic", "case": {"id": "synthetic"}, "values": values}, + protocol, modules, legacy_case, rest_only=False) + self.assertFalse( + (legacy_case / "thorax-foundation-source-evidence.json").exists() + ) + + self.assertTrue(result["body_materialized"]) + self.assertTrue(result["foot_materialized"]) + self.assertTrue(result["source_rebuild"]["root_L0_exact"]) + self.assertTrue(result["source_rebuild"]["root_L2_exact"]) + self.assertNotIn("required_for_full_pass", result["source_rebuild"]) + self.assertEqual([event[0] for event in events], + ["dependencies", "body", "leg-build", "leg-evaluate", + "pose", "pose"]) + dependencies = events[0][1] + self.assertIs(dependencies["root_source"], modules["root_source"]) + self.assertIs(dependencies["hip_source"], modules["hip_source"]) + self.assertIs(dependencies["leg_builder"], modules["construction"]) + self.assertIs(dependencies["binding"], modules["binding"]) + self.assertIs(dependencies["arm_builder"], arm_module) + self.assertIs(dependencies["head_builder"], head_module) + body_event = events[1] + self.assertEqual(body_event[3], {}) + self.assertEqual(body_event[4], {}) + self.assertEqual(body_event[5], {}) + self.assertTrue(all(event[1] == final_l2 for event in events if event[0] == "pose")) + self.assertEqual(len(result["poses"]), 2) + + with tempfile.TemporaryDirectory() as directory: + foundation_result = runner._case_run( + {"id": "synthetic", "case": {"id": "synthetic"}, "values": values}, + protocol, modules, Path(directory) / "case", rest_only=False, + body_config={"thorax_foundation": { + "inputs": "thorax-foundation-baseline-inputs.json" + }}) + evidence = Path(directory) / "case" / "thorax-foundation-source-evidence.json" + self.assertEqual(foundation_result["thorax_foundation_source_evidence"], + "thorax-foundation-source-evidence.json") + self.assertEqual(json.loads(evidence.read_text(encoding="utf-8")), { + "selected_inputs": {"schema": "thorax-baseline"}, + }) + foundation_dependency = next( + event[1] for event in events + if event[0] == "dependencies" and "thorax_foundation" in event[1] + ) + self.assertIs(foundation_dependency["thorax_foundation"], + modules["thorax_foundation"]) + foundation_body_event = next( + event for event in reversed(events) + if event[0] == "body" and event[-1] is not None + ) + self.assertEqual(foundation_body_event[-1], + {"schema": "thorax-baseline"}) + self.assertFalse(foundation_result["source_rebuild"]["root_L0_exact"]) + self.assertFalse(foundation_result["source_rebuild"]["root_L2_exact"]) + self.assertFalse( + any(foundation_result["source_rebuild"]["root_binding_exact"].values()) + ) + self.assertEqual(foundation_result["source_rebuild"]["comparison_role"], + "diagnostic-only") + self.assertFalse(foundation_result["source_rebuild"]["required_for_full_pass"]) + self.assertIn("intentionally rebuilds J/skin", + foundation_result["source_rebuild"]["reason"]) + self.assertNotEqual(foundation_result["status"], "exception") + + def test_explicit_body_config_rejects_legacy_and_rest_only_modes(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + snapshot = root / "snapshot" + source = snapshot / runner.SNAPSHOT_SOURCE + source.mkdir(parents=True) + (source / "protocol.json").write_text("{}", encoding="utf-8") + (source / "inputs.json").write_text("{}", encoding="utf-8") + captured_runner = source / "runner.py" + captured_runner.write_text("# captured runner\n", encoding="utf-8") + with mock.patch.object(runner, "verify", return_value={}), \ + mock.patch.object(runner, "_load_case_inputs", return_value=[]), \ + mock.patch.object(runner, "_load_collaborators", return_value={}), \ + mock.patch.object(runner, "__file__", str(captured_runner)): + for rest_only in (False, True): + with self.subTest(rest_only=rest_only): + output = root / f"output-{rest_only}" + with self.assertRaisesRegex( + runner.RunnerError, + "requires source-driven body mode"): + runner.run( + snapshot, output, + rest_only=rest_only, + body_config="body-config.json", + ) + self.assertFalse(output.exists()) + + def test_foot_run_labels_legacy_perturbations_as_leg_only(self) -> None: + mesh = {"vertices": [[0.0, 0.0, 0.0]], "quads": []} + + class Construction: + @staticmethod + def build(_root, _leg_inputs): + return mesh + + @staticmethod + def evaluate(_mesh, levels=2): + return [mesh] + + class Foot: + @staticmethod + def build(_base, _leg_inputs, _foot_inputs): + return mesh + + @staticmethod + def evaluate(_mesh, levels=2): + return [mesh] + + class Binding: + @staticmethod + def bind(*_args): + return {"joint_order": [], "evaluated_weights": [[1.0]]} + + @staticmethod + def pose(_mesh, _binding, _angles): + return mesh + + @staticmethod + def joint_points(_binding, _angles): + return {} + + class Perturbations: + @staticmethod + def run_case(*_args): + return {"status": "pass", "perturbations": [ + {"id": "left_A", "status": "pass"}, + ]} + + protocol = {"baseline_poses": [{"id": "rest", "left": {}, "right": {}}], + "input_perturbations": [{"id": "left_A"}]} + modules = {"construction": Construction(), "foot_construction": Foot(), + "foot_inputs": {"cases": [{"case_id": "synthetic", + "sides": {"left": {}, "right": {}}}]}, + "binding": Binding(), "perturbations": Perturbations()} + values = {"root_mesh": mesh, "prior_rest_mesh": mesh, + "prior_hip_binding": {}, "leg_inputs": {}} + with tempfile.TemporaryDirectory() as directory: + result = runner._case_run( + {"id": "synthetic", "case": {"id": "synthetic"}, "values": values}, + protocol, modules, Path(directory) / "case", rest_only=False) + self.assertEqual(result["perturbations"]["status"], "leg-only") + self.assertEqual(result["perturbations"]["coverage"], "leg-baseline-only") + self.assertEqual(result["perturbations"]["foot_coverage"], "not-run") + self.assertFalse(result["full_pass"]) + + def test_checker_calls_use_immutable_inputs_and_original_l2(self) -> None: + mesh = {"vertices": [[0.0, 0.0, 0.0]], "quads": []} + calls = [] + + class Construction: + @staticmethod + def build(_root, _leg_inputs): + return mesh + + @staticmethod + def evaluate(_base): + return [mesh, mesh] + + class Binding: + @staticmethod + def bind(*_args): + return {"synthetic": True} + + @staticmethod + def pose(_rest, _binding, _angles): + return mesh + + @staticmethod + def joint_points(_binding, _angles): + return {} + + class Checks: + @staticmethod + def check_mesh(*args): + calls.append(("mesh", args)) + return {"pass": True} + + @staticmethod + def check_binding(*args): + calls.append(("binding", args)) + return {"pass": True} + + @staticmethod + def check_pose(*args): + calls.append(("pose", args)) + return {"pass": True} + + @staticmethod + def compare_root(*args): + calls.append(("root", args)) + return {"pass": True} + + protocol = {"baseline_poses": [{"id": "rest", "left": {"ankle": 0}, "right": {"ankle": 0}}]} + leg_inputs = {"left": {"J": [0, 0, 0]}, "right": {"J": [0, 0, 0]}} + with tempfile.TemporaryDirectory() as directory: + result = runner._case_run( + {"id": "synthetic", "case": {"id": "synthetic", "leg_inputs": leg_inputs}, + "values": {"root_mesh": mesh, "prior_rest_mesh": mesh, + "prior_hip_binding": {}, "leg_inputs": leg_inputs}}, + protocol, {"construction": Construction(), "binding": Binding(), "checks": Checks()}, + Path(directory) / "case", rest_only=False) + self.assertEqual(result["status"], "technical-pass", result) + by_name = dict(calls) + self.assertEqual(len(by_name["binding"]), 7) + self.assertIs(by_name["binding"][5], leg_inputs) + self.assertEqual(len(by_name["pose"]), 6) + self.assertIs(by_name["pose"][5], leg_inputs) + self.assertIs(by_name["root"][0], mesh) + self.assertIs(by_name["root"][2], mesh) + + def test_perturbation_hook_saves_all_returned_meshes_and_never_passes_missing(self) -> None: + mesh = {"vertices": [[0.0, 0.0, 0.0]], "quads": []} + calls = [] + + class Construction: + @staticmethod + def build(_root, _leg_inputs): + return mesh + + @staticmethod + def evaluate(_base): + return [mesh, mesh] + + class Binding: + @staticmethod + def bind(*_args): + return {"synthetic": True} + + @staticmethod + def pose(_rest, _binding, _angles): + return mesh + + @staticmethod + def joint_points(_binding, _angles): + return {} + + class Checks: + check_mesh = staticmethod(lambda *_args: {"pass": True}) + check_binding = staticmethod(lambda *_args: {"pass": True}) + check_pose = staticmethod(lambda *_args: {"pass": True}) + compare_root = staticmethod(lambda *_args: {"pass": True}) + + class Perturbations: + @staticmethod + def run_case(*args): + calls.append(args) + return {"status": "pass", "perturbations": [ + {"id": "left_A_y_minus_0.02", "status": "pass", "diagnostic_meshes": {"actual": mesh}}, + {"id": "left_calf_posterior_radius_times_1.10", "status": "pass", "diagnostic_meshes": {"failed": mesh}}, + {"id": "left_J_y_plus_0.01_at_hip15", "status": "pass", "diagnostic_meshes": {"expected": mesh}}, + ]} + + protocol = {"baseline_poses": [{"id": "rest", "left": {"ankle": 0}, "right": {"ankle": 0}}], + "input_perturbations": [ + {"id": "left_A_y_minus_0.02"}, + {"id": "left_calf_posterior_radius_times_1.10"}, + {"id": "left_J_y_plus_0.01_at_hip15"}, + ]} + values = {"root_mesh": mesh, "prior_rest_mesh": mesh, "prior_hip_binding": {}, "leg_inputs": {}} + modules = {"construction": Construction(), "binding": Binding(), "checks": Checks(), + "perturbations": Perturbations()} + with tempfile.TemporaryDirectory() as directory: + case_dir = Path(directory) / "case" + result = runner._case_run({"id": "synthetic", "case": {"id": "synthetic"}, "values": values}, + protocol, modules, case_dir, rest_only=False) + self.assertTrue((case_dir / "perturbations.json").is_file()) + self.assertTrue((case_dir / "perturbations/left_A_y_minus_0.02/actual.json").is_file()) + self.assertTrue((case_dir / "perturbations/left_calf_posterior_radius_times_1.10/failed.json").is_file()) + self.assertTrue((case_dir / "perturbations/left_J_y_plus_0.01_at_hip15/expected.json").is_file()) + self.assertEqual(result["status"], "technical-pass", result) + self.assertEqual(len(calls), 1) + self.assertEqual(len(calls[0]), 10) + + missing = dict(result) + missing["perturbations"] = {"status": "pass", "perturbations": []} + self.assertFalse(runner._perturbation_result_ready( + missing["perturbations"], [ + "left_A_y_minus_0.02", + "left_calf_posterior_radius_times_1.10", + "left_J_y_plus_0.01_at_hip15", + ])) + + def test_pose_failure_blocks_present_perturbation_dispatch_with_cause(self) -> None: + mesh = {"vertices": [[0.0, 0.0, 0.0]], "quads": []} + + class Construction: + @staticmethod + def build(_root, _leg_inputs): + return mesh + + @staticmethod + def evaluate(_base): + return [mesh, mesh] + + class Binding: + @staticmethod + def bind(*_args): + return {"synthetic": True} + + @staticmethod + def pose(_rest, _binding, _angles): + raise ValueError("synthetic pose input failure") + + @staticmethod + def joint_points(_binding, _angles): + raise AssertionError("joint_points must not run after pose failure") + + class Perturbations: + @staticmethod + def run_case(*_args): + raise AssertionError("perturbations must not dispatch after pose failure") + + protocol = { + "baseline_poses": [{"id": "rest", "left": {"hip": 0, "knee": 0, "ankle": 0}, + "right": {"hip": 0, "knee": 0, "ankle": 0}}], + "input_perturbations": [ + {"id": "left_A_y_minus_0.02"}, + {"id": "left_calf_posterior_radius_times_1.10"}, + {"id": "left_J_y_plus_0.01_at_hip15"}, + ], + } + values = {"root_mesh": mesh, "prior_rest_mesh": mesh, + "prior_hip_binding": {}, "leg_inputs": {}} + with tempfile.TemporaryDirectory() as directory: + result = runner._case_run( + {"id": "synthetic", "case": {"id": "synthetic"}, "values": values}, + protocol, + {"construction": Construction(), "binding": Binding(), + "perturbations": Perturbations()}, + Path(directory) / "case", rest_only=False) + self.assertEqual(result["status"], "exception") + self.assertEqual(result["perturbations"]["status"], "blocked-by-earlier-error") + self.assertEqual(result["perturbations"]["execution"], "not-run") + self.assertEqual(result["perturbations"]["blocker"]["stage"], "pose:rest") + self.assertEqual(result["perturbations"]["blocker"]["message"], "synthetic pose input failure") + + def test_shared_bounds_include_outlying_perturbation_surface(self) -> None: + rest = {"vertices": [[0.0, 0.0, 0.0]], "quads": []} + outlier = {"vertices": [[100.0, -100.0, 50.0]], "quads": []} + results = [{"bounds_inputs": [rest], + "perturbation_meshes": [{"mesh": outlier}]}] + bounds = runner._bounds(runner._render_bounds_inputs(results)) + self.assertLessEqual(bounds[0][0], 100.0) + self.assertLessEqual(bounds[0][1], -100.0) + self.assertGreaterEqual(bounds[1][2], 50.0) + + def test_cli_returns_nonzero_for_failed_execution(self) -> None: + with mock.patch.object(runner, "run", return_value={"status": "error"}): + self.assertEqual(runner._main(["run", "--snapshot", "/tmp/snapshot", "--output", "/tmp/output"]), 1) + + def test_prepare_captures_exact_sources_and_mapped_inputs(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + source = root / "experiment" + source.mkdir() + for name, text in { + "runner.py": "# captured runner\n", + "protocol.json": '{"poses":[{"id":"rest"}]}\n', + "construction.py": "import binding\n", + "binding.py": "VALUE = 1\n", + }.items(): + (source / name).write_text(text, encoding="utf-8") + for name, value in { + "root.json": {"vertices": [[0, 0, 0]]}, + "prior-rest.json": {"vertices": [[0, 0, 0]]}, + "prior-binding.json": {"weights": []}, + }.items(): + (source / name).write_text(json.dumps(value), encoding="utf-8") + def descriptor(name: str) -> dict[str, str]: + path = source / name + return {"path": str(path), "sha256": hashlib.sha256(path.read_bytes()).hexdigest()} + (source / "inputs.json").write_text(json.dumps({"cases": [{ + "id": "ordinary", "root_mesh": descriptor("root.json"), + "prior_rest_mesh": descriptor("prior-rest.json"), + "prior_hip_binding": descriptor("prior-binding.json"), + "leg_inputs": {"J": [0, 1, 0], "T": [0, 0, 0], "K": [0, -1, 0], "A": [0, -2, 0]}, + }]}), encoding="utf-8") + dependency = _dependency(root) + snapshot = root / "snapshot" + with mock.patch.object(runner, "HERE", source), \ + mock.patch.object(runner, "CAPTURE_FILES", ( + "runner.py", "construction.py", "binding.py", "protocol.json", "inputs.json")), \ + mock.patch.object(runner, "_dependency_identity", return_value=dependency): + manifest = runner.prepare(snapshot) + checked = runner.verify(snapshot) + self.assertEqual(checked["schema"], manifest["schema"]) + self.assertTrue((snapshot / "source/experiments/connected-leg-assembly/runner.py").is_file()) + self.assertTrue((snapshot / "source/experiments/connected-leg-assembly/binding.py").is_file()) + path_map = manifest["input_manifest"]["path_map"] + self.assertEqual({row["field"] for row in path_map}, { + "root_mesh", "prior_rest_mesh", "prior_hip_binding"}) + self.assertTrue(all(str(row["snapshot_path"]).startswith("inputs/") for row in path_map)) + self.assertTrue(manifest["dependency"]["reused_without_copy"]) + self.assertIn("does not claim hermetic", " ".join(manifest["host"]["limitations"]).lower()) + + def test_prepare_refuses_existing_snapshot_without_overwrite(self) -> None: + with tempfile.TemporaryDirectory() as directory: + source = Path(directory) / "experiment" + source.mkdir() + (source / "runner.py").write_text("runner\n", encoding="utf-8") + snapshot = Path(directory) / "snapshot" + snapshot.mkdir() + with mock.patch.object(runner, "HERE", source), \ + mock.patch.object(runner, "CAPTURE_FILES", ("runner.py",)): + with self.assertRaisesRegex(runner.RunnerError, "snapshot must be absent"): + runner.prepare(snapshot) + self.assertEqual(list(snapshot.iterdir()), []) + + def test_verify_refuses_drifted_captured_input(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + source = root / "experiment" + source.mkdir() + (source / "runner.py").write_text("runner\n", encoding="utf-8") + snapshot = root / "snapshot" + dependency = _dependency(root) + with mock.patch.object(runner, "HERE", source), \ + mock.patch.object(runner, "CAPTURE_FILES", ("runner.py",)), \ + mock.patch.object(runner, "_dependency_identity", return_value=dependency): + manifest = runner.prepare(snapshot) + # A source-only staged capture has no input files; adding one is + # still rejected as unexpected output rather than silently ignored. + (snapshot / "unexpected.json").write_text("{}", encoding="utf-8") + with mock.patch.object(runner, "_dependency_identity", return_value=dependency): + with self.assertRaisesRegex(runner.RunnerError, "unexpected files"): + runner.verify(snapshot) + self.assertEqual(manifest["status"], "prepared") + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/connected-leg-assembly/tests/test_tail_construction.py b/experiments/connected-leg-assembly/tests/test_tail_construction.py new file mode 100644 index 0000000..6922748 --- /dev/null +++ b/experiments/connected-leg-assembly/tests/test_tail_construction.py @@ -0,0 +1,197 @@ +"""Focused tests for the explicit host-58 connected-tail adapter.""" +from __future__ import annotations + +import copy +import json +from pathlib import Path +import sys +import unittest + +import numpy as np + + +HERE = Path(__file__).resolve().parents[1] +if str(HERE) not in sys.path: + sys.path.insert(0, str(HERE)) + +import construction # noqa: E402 +import tail_construction # noqa: E402 + + +INPUTS = json.loads((HERE / "inputs.json").read_text(encoding="utf-8")) +TAIL_INPUTS = json.loads((HERE / "tail-inputs.json").read_text(encoding="utf-8")) +TAIL_CASES = {row["case_id"]: row for row in TAIL_INPUTS["cases"]} +CASE_IDS = ("calibrated_ordinary_human", "calibrated_upright_anthropomorphic") +HOST_FACE = 58 +HOST_VERTICES = [41, 44, 66, 63] + + +def _actual_cases(): + result = [] + for row in INPUTS["cases"]: + if row["id"] not in CASE_IDS: + continue + root = json.loads(Path(row["root_mesh"]["path"]).read_text(encoding="utf-8")) + base = construction.build(root, row["leg_inputs"]) + controls = TAIL_CASES[row["id"]] + output = tail_construction.build(base, controls) + result.append((row["id"], base, output, controls)) + if tuple(row[0] for row in result) != CASE_IDS: + raise AssertionError("canonical tail cases were not loaded") + return result + + +class TailConstructionTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cases = _actual_cases() + + def test_disabled_human_feature_returns_source_mesh_exactly(self): + case_id, base, output, controls = self.cases[0] + self.assertEqual(case_id, "calibrated_ordinary_human") + self.assertFalse(controls["enabled"]) + self.assertEqual(output, base) + self.assertNotIn("tail", output["metadata"]) + + def test_pinned_host_is_derived_from_source_mesh_and_slot_is_replaced(self): + case_id, base, output, _controls = self.cases[1] + self.assertEqual(case_id, "calibrated_upright_anthropomorphic") + tail = output["metadata"]["tail"] + host = tail["host"] + self.assertEqual(host["face_index"], HOST_FACE) + self.assertEqual(host["original_quad"], HOST_VERTICES) + self.assertEqual(host["owner"], "domain.pelvis") + self.assertEqual(base["quads"][HOST_FACE], HOST_VERTICES) + self.assertEqual(base["face_owners"][HOST_FACE], "domain.pelvis") + np.testing.assert_array_equal(host["coordinates"], + [base["vertices"][index] for index in HOST_VERTICES]) + self.assertEqual(output["quads"][HOST_FACE], + output["quads"][tail["annulus_face_indices"][0]]) + self.assertNotIn(HOST_VERTICES, output["quads"]) + points = np.asarray(host["coordinates"], dtype=float) + raw_normal = np.cross(points[1] - points[0], points[2] - points[0]) + raw_normal += np.cross(points[2] - points[0], points[3] - points[0]) + expected_normal = raw_normal / np.linalg.norm(raw_normal) + np.testing.assert_allclose(host["normal"], expected_normal, atol=1.0e-12) + + def test_non_host_faces_vertices_and_face_indices_remain_stable(self): + _case_id, base, output, _controls = self.cases[1] + base_face_count = len(base["quads"]) + tail = output["metadata"]["tail"] + self.assertEqual(len(output["vertices"]), len(base["vertices"]) + 20) + self.assertEqual(len(output["quads"]), base_face_count + 20) + self.assertEqual(tail["annulus_face_indices"], + [HOST_FACE, base_face_count, base_face_count + 1, + base_face_count + 2]) + self.assertEqual(tail["tail_face_indices"], + list(range(base_face_count + 3, base_face_count + 19))) + self.assertEqual(tail["cap_face_index"], base_face_count + 19) + self.assertEqual(tail["new_face_indices"], + [HOST_FACE] + list(range(base_face_count, base_face_count + 20))) + self.assertEqual(output["vertices"][:len(base["vertices"])], base["vertices"]) + self.assertEqual(output["control_owners"][:len(base["control_owners"])], + base["control_owners"]) + self.assertEqual(output["base_stencils"][:len(base["base_stencils"])], + base["base_stencils"]) + for index, face in enumerate(base["quads"]): + if index != HOST_FACE: + self.assertEqual(output["quads"][index], face) + self.assertEqual(output["face_owners"][index], base["face_owners"][index]) + self.assertEqual(output["loops"], base["loops"]) + self.assertEqual(tail["face_replacement"]["original_host_retained"], False) + self.assertEqual(tail["face_replacement"]["one_to_many"], + [[HOST_FACE, *tail["annulus_face_indices"]]]) + + def test_inset_collar_source_phase_frames_and_cubic_stations_are_explicit(self): + _case_id, base, output, controls = self.cases[1] + tail = output["metadata"]["tail"] + host = tail["host"] + points = np.asarray(host["coordinates"], dtype=float) + centre = np.mean(points, axis=0) + inset = np.asarray(host["inset_corners"], dtype=float) + np.testing.assert_allclose(inset, centre + 0.4 * (points - centre), atol=1.0e-12) + collar = np.asarray(host["collar_vertices"], dtype=float) + np.testing.assert_allclose( + collar, + inset + float(controls["collar_distance"]) * np.asarray(host["normal"]), + atol=1.0e-12, + ) + self.assertEqual(len(tail["host"]["source_phase"]), 4) + self.assertEqual(len({tuple(phase) for phase in tail["host"]["source_phase"]}), 4) + self.assertEqual(len(tail["ring_indices"]), 5) + self.assertEqual(tail["station_fractions"], controls["station_fractions"]) + centreline = tail["centreline"] + self.assertEqual(centreline["kind"], "cubic_bezier") + self.assertEqual(len(centreline["control_points"]), 4) + self.assertEqual(tail["ring_indices"][0], tail["new_vertex_indices"][:4]) + self.assertEqual(output["frames"], base["frames"]) + self.assertNotIn("tail", output["frames"]) + self.assertEqual(tail["host_normal"], host["normal"]) + self.assertEqual(tail["source_phase"], host["source_phase"]) + self.assertEqual( + tail["frame_rule"], + "project global +X onto each cubic tangent plane; V=X cross tangent", + ) + for frame in tail["ring_frames"]: + tangent = np.asarray(frame["tangent"], dtype=float) + x_axis = np.asarray(frame["X"], dtype=float) + v_axis = np.asarray(frame["V"], dtype=float) + np.testing.assert_allclose(np.linalg.norm(tangent), 1.0, atol=1.0e-12) + np.testing.assert_allclose(np.linalg.norm(x_axis), 1.0, atol=1.0e-12) + np.testing.assert_allclose(np.linalg.norm(v_axis), 1.0, atol=1.0e-12) + self.assertAlmostEqual(float(np.dot(x_axis, tangent)), 0.0, places=12) + self.assertGreater(float(np.dot(np.cross(x_axis, tangent), v_axis)), 1.0 - 1.0e-12) + expected_direction = np.asarray([0.0, -0.25, -1.0]) + expected_direction /= np.linalg.norm(expected_direction) + np.testing.assert_allclose(tail["centreline"]["terminal_direction"], + expected_direction, atol=1.0e-12) + + def test_connected_cap_and_binding_supports_match_inset_corner_derivation(self): + _case_id, base, output, _controls = self.cases[1] + tail = output["metadata"]["tail"] + self.assertEqual(len(tail["tail_face_indices"]), 16) + self.assertEqual(len(output["quads"][tail["cap_face_index"]]), 4) + self.assertEqual(tail["transition_weights"]["status"], + "binding_declared_no_tail_joint") + self.assertEqual(tail["transition_weights"]["collar_blend_strength"], 0.5) + supports = tail["transition_weights"]["supports"] + self.assertEqual(set(map(int, supports)), set(tail["new_vertex_indices"])) + host_points = np.asarray([base["vertices"][index] for index in HOST_VERTICES], + dtype=float) + inset = np.asarray(tail["host"]["inset_corners"], dtype=float) + for offset, index in enumerate(tail["new_vertex_indices"]): + corner = offset % 4 + row = supports[str(index)] + self.assertEqual(row["host_vertex_indices"], HOST_VERTICES) + self.assertEqual(row["host_corner"], corner) + self.assertEqual(row["source_phase"], tail["source_phase"][corner]) + self.assertEqual(row["convex_weights"], + [0.55 if slot == corner else 0.15 for slot in range(4)]) + np.testing.assert_allclose( + np.asarray(row["convex_weights"]) @ host_points, + inset[corner], + atol=1.0e-12, + ) + self.assertEqual(row["target_joint"], "pelvis") + self.assertIn("q=.4*P_i+.6*C", row["support_rule"]) + self.assertEqual(output["metadata"]["base_control_owners"][:len(base["vertices"])], + base["metadata"]["base_control_owners"]) + + def test_host_identity_and_candidate_controls_reject_drift(self): + _case_id, base, _output, controls = self.cases[1] + hostile = copy.deepcopy(controls) + hostile["host_identity"]["vertex_indices"] = [41, 44, 63, 66] + with self.assertRaises(tail_construction.TailConstructionError): + tail_construction.build(base, hostile) + hostile = copy.deepcopy(controls) + hostile["host_identity"]["owner"] = "domain.root" + with self.assertRaises(tail_construction.TailConstructionError): + tail_construction.build(base, hostile) + hostile = copy.deepcopy(controls) + hostile["station_fractions"] = [0.0, 0.25, 0.25, 0.75, 1.0] + with self.assertRaises(tail_construction.TailConstructionError): + tail_construction.build(base, hostile) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/pelvis-hip-articulation/README.md b/experiments/pelvis-hip-articulation/README.md new file mode 100644 index 0000000..32b1a86 --- /dev/null +++ b/experiments/pelvis-hip-articulation/README.md @@ -0,0 +1,106 @@ +# Local pelvis/hip articulation probe + +Experiment lifecycle: finished + +Evidence closure: complete + +Technology outcome: support — limited regional baseline binding probe only + +The bounded result is recorded in [RESULTS.md](RESULTS.md). + +## Question and authorized outcome + +Can a shared automatically generated binding move both calibrated proximal +thighs around intelligible independent hip pivots while keeping their joined +surface credible under modest flexion? Ben authorized this local regional +checkpoint through the Overseer on 2026-09-05. It is not finished anatomy, +whole-body rigging, a production architecture choice or a lower quality goal. +Ordinary human and anthropomorphic bodies remain equally important targets +on the intended path to polished independent-artist animation. + +The [protocol](protocol.json) fixes one baseline binding, five poses per body, +one separate pivot-response diagnostic per body, and zero binding retunes, +rest-shape changes or topology changes before execution. Routine tooling +defects may be corrected without changing the method or this budget. A failed +baseline is closed and reported to the Overseer with a bounded recommendation; +it does not silently trigger another method or shape campaign. The Overseer +can direct routine regional follow-up under Ben's authorization. Stop for Ben +at the meaningful visual checkpoint or a retained-human decision. + +The [source calibration](../pelvis-source-calibration/README.md) and +[transition trial](../pelvis-thigh-transition/README.md) retain their exact +historical outcomes and exhausted budgets. Neither is restarted here. + +## What changes, and what does not + +Use the two saved calibrated L0/L2 meshes and exact original inputs. Do not +rebuild or reshape them. The independent J coordinates previously used only +as calibration reference points become **experimental hip pivots** here, with +their anatomical uncertainty retained. T remains thigh start, K remains knee; +their distinct joint-local rest coordinates are transformed with the thigh. +Pelvic landmark estimates remain diagnostics, not constraints forcing skin +through every point. This makes J meaningful for binding and pose without +requiring J to alter resting skin. The 92-component rest construction and +public Joint semantics are unchanged. + +Generate one three-column pelvis/left/right weight field from the actual L0 +quad-edge graph: ringB/exit vertices anchor each thigh, non-transition +vertices anchor the pelvis, and socket/ringA weights solve the uniform graph +Laplacian. Propagate those weights using the full stored subdivision stencils, +never dominant-owner labels. No hand-painted or case-selected weights exist. +Apply linear blend skinning to the preserved **evaluated L2 rest surface**. +This is not a claim that deforming and subdividing the control cage commute. +Stored subdivision provenance remains rest provenance; posed positions depend +on the recorded rest vertices, weights and actual joint transforms. + +Joint rest frames originate at J and use the J-to-K direction; fixed local +T/K coordinates are recorded separately. Inverse-bind then posed-global +transforms supply conventional skinning, as described by the +[Khronos skinning tutorial](https://github.khronos.org/glTF-Tutorials/gltfTutorial/gltfTutorial_020_Skins.html). +This is an experiment-local CPU implementation, not adoption of glTF, an +engine, an export contract or a general skeleton framework. + +## Evidence and judgment + +Reload exported meshes for independent transform and surface checks. The +protocol declares identity, weighting, frame, rigid distal-port, upper-pelvis +movement, local strain, gross-flip and lower-intersection checks. The full +body has open boundaries: no caps or global solid-volume claims are added. +The represented distal thigh ends must stay at their expected transformed +extent; the missing lower legs are outside scope. Keep inherited upper-body +issues and uncertain anatomical markers separate from new binding failures. + +Render matched actual surfaces and separate frame/landmark overlays at rest, +15/30-degree single-hip flexion, mirrored 15-degree flexion, and both hips at +20 degrees. Include underside views for rest and 30 degrees. The Main Worker +personally inspects these results. No moving-mesh or numeric success +alone is visual acceptance; no new pinching, collapse, attachment artifacts +or unwanted pelvic drag should be hidden by framing or overlays. + +Exact new code, inputs and existing rest-mesh identities are captured before +execution and checked after. Reuse the already captured managed runtime; +run its `surface_preview_launcher.sh` through `bash` with +`CK_CURRENT_FORM_SURFACE_PYTHON` pointing to the frozen runtime and +`PYTHONDONTWRITEBYTECODE=1`. Local artifact paths and exact run commands will +be recorded with the result. Nothing is published, pushed or merged here. + +## Reproduction + +Use absent sibling snapshot/output paths. The runner captures its exact source +allowlist and copied inputs; execution must use the captured runner from its +own directory. The example paths are local evidence, not repository files. + +```bash +export PYTHONDONTWRITEBYTECODE=1 +export CK_CURRENT_FORM_SURFACE_PYTHON=/home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot/runtime/bin/python +export CK_HIP_LAUNCHER=/home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot/source/experiments/current-form-surface-preview/surface_preview_launcher.sh +bash "$CK_HIP_LAUNCHER" experiments/pelvis-hip-articulation/runner.py prepare --snapshot /home/ben/.cache/creature-kernel/pelvis-hip-articulation-harmonic-lbs-001-snapshot +cd /home/ben/.cache/creature-kernel/pelvis-hip-articulation-harmonic-lbs-001-snapshot/source/experiments/pelvis-hip-articulation +bash "$CK_HIP_LAUNCHER" -m unittest discover -s tests -v +bash "$CK_HIP_LAUNCHER" runner.py run --snapshot /home/ben/.cache/creature-kernel/pelvis-hip-articulation-harmonic-lbs-001-snapshot --output /home/ben/.cache/creature-kernel/pelvis-hip-articulation-harmonic-lbs-001-run +bash "$CK_HIP_LAUNCHER" runner.py verify --snapshot /home/ben/.cache/creature-kernel/pelvis-hip-articulation-harmonic-lbs-001-snapshot +``` + +The existing renderer shows both sides of open surfaces. Opposite inner walls +can resemble end caps in an underside image; no caps are generated. Report +this limitation alongside the matched surface/diagnostic views. diff --git a/experiments/pelvis-hip-articulation/RESULTS.md b/experiments/pelvis-hip-articulation/RESULTS.md new file mode 100644 index 0000000..0e052d7 --- /dev/null +++ b/experiments/pelvis-hip-articulation/RESULTS.md @@ -0,0 +1,124 @@ +# Local pelvis/hip articulation probe results + +Experiment lifecycle: finished + +Evidence closure: complete + +Technology outcome: support — limited regional baseline binding probe only + +This result supports the one declared harmonic-weight/LBS baseline for the two +calibrated regional cases. It is not production rigging, an anatomy result, an +animation validation, or a new architecture contract. + +## Scope and execution + +The run used one shared method, one finite pose set, and zero binding retunes, +rest-shape changes, geometry replacement, rest-input changes, or topology +changes. It used the preserved calibrated L0/L2 surfaces for +`calibrated_ordinary_human` and `calibrated_upright_anthropomorphic`: + +- L0 graph-harmonic three-column weights, propagated by the stored full L2 + subdivision stencils; +- conventional three-joint LBS on the preserved evaluated L2 rest surface; +- `rest`, `left_flex_15`, `left_flex_30`, `right_flex_15`, and `both_flex_20` + for each case; and +- one diagnostic J-pivot counterfactual per case, with J moved by +0.01 metres + along source/world +Y while weights and rest vertices stayed unchanged. + +## Provenance and integrity + +Protocol: `pelvis-hip-articulation-harmonic-lbs-001`. + +Exact capture snapshot root: +`/home/ben/.cache/creature-kernel/pelvis-hip-articulation-harmonic-lbs-001-snapshot` + +Exact output run root: +`/home/ben/.cache/creature-kernel/pelvis-hip-articulation-harmonic-lbs-001-run` + +Recorded identities: + +- capture snapshot manifest (`manifest.json`): + `e97406f487569b072c1885667a0fd49084a017b30f03cecb04562b81241bef54`; +- output artifact manifest (`artifact-sha-manifest.json`): + `c6733a75cbd0f7496e71256bc2ed56adb2b924b4e3136339efbe25c6b89fd9c3`; +- output run report (`run-report.json`): + `208d2df0d5576b68c7f6a777361d86b0eb600275bf66ba02fdaa8f836baa9ff2`. + +The collector verified all 85 output files, 29,378,559 bytes, with zero drift. +The run report and per-case reports contain no errors. The captured source and +frozen runtime produced 33/33 main integrated tests, with 10/10 pose technical +passes and 2/2 binding-method passes. + +## Technical result + +All declared technical checks passed for both cases, including identity/rest +preservation, exact topology, frames and inverse bind, partition unity and +weight bounds, independent LBS, rigid distal ports, strict pelvis stationarity, +triangle/edge strain screening, gross-normal-flip screening, and zero reported +lower non-adjacent intersection pairs. + +The following ranges are the actual `left_flex_30` check values: + +| Case | Lower-edge ratio | Triangle-area ratio | Minimum normal dot | Lower intersections | +| --- | ---: | ---: | ---: | ---: | +| Ordinary human | 0.740470–1.379660 | 0.728193–1.354985 | 0.628836 | 0 | +| Upright anthropomorphic | 0.661852–1.449174 | 0.653300–1.429969 | 0.602151 | 0 | + +The anthropomorphic lower-edge minimum is near the declared 0.65 screening +floor. These are small-angle screening measurements, not evidence for deeper +bends or material-volume preservation. + +The J-pivot counterfactual produced a response while leaving weights and rest +vertices unchanged: `response_over_L` was `0.006084415350198488` for the +ordinary human and `0.007341277288441133` for the anthropomorphic case. This is +a causality diagnostic only; J is not a rest-shape control. + +## Main Worker visual judgment + +The Main Worker personally inspected all ten front/side/rear-three-quarter +surface triptychs, both L30 diagnostic overlays, the human L30 and +anthropomorphic rest/L30 undersides, and the historical human-rest underside. +There was no obvious new tear, sharp attachment seam, gross collapse, or +interpenetration from the small-angle bending. The same shared rule works on +these two cases as a limited regional baseline. The result is **READY FOR BEN +APPRAISAL** at the limited regional bend checkpoint, not a polished anatomy or +animation validation. + +The Overseer independently inspected rest, L30, and both20 views for both +cases, including both L30 undersides, and agrees that the result is ready for +limited appraisal. + +Existing pinched waist, schematic groin arch, weak buttocks, and faceting remain; +no rest-shape improvement is claimed. Open thigh boundaries can look capped in +underside views because opposite inner walls are rendered together; no caps are +generated. Overlay legends overlap in some diagnostic views, a presentation +limitation rather than a geometry result. + +## Review disposition and limitations + +A fresh Luna review identified the weight-method gap. A Sol-medium checker +worker implemented the fix using an independent graph Dirichlet, residual, and +stencil check; the Main Worker inspected and tested the resulting code. This +record does not claim a new independent post-fix full review; none was run. + +Adjacent folds are not exhaustively proven by the non-adjacent intersection +checker. The evidence remains visual inspection plus finite strain/normal +screening. The open lower boundaries do not support caps or global solid-volume +claims. Do not extrapolate this result to deeper bends, material volume, +whole-body behaviour, animation quality, or production rigging. + +The bounded probe also included local operational corrections for the capture +source/output manifest distinction, exported readback, overlay field lookup, +and synthetic-fixture winding. These did not change the method, inputs, +geometry, rest surface, topology, or retune budget. The historical pelvis +source-calibration and pelvis-to-thigh-transition verdicts remain unchanged. + +## Recommendation + +Pause for Ben's visual appraisal. Ben should accept or reject this limited bend +evidence, then settle the next scoped quality target with the Overseer. Do not +automatically add poses, alter geometry or topology, expand to the body, build a +general rig framework, publish, push, or merge. + +Reproduction commands and the captured-source procedure remain in the +[experiment README](README.md#reproduction). diff --git a/experiments/pelvis-hip-articulation/binding.py b/experiments/pelvis-hip-articulation/binding.py new file mode 100644 index 0000000..90ad677 --- /dev/null +++ b/experiments/pelvis-hip-articulation/binding.py @@ -0,0 +1,487 @@ +"""Small, experiment-local harmonic hip binding and rigid hip pose. + +The binding is deliberately separated from construction. ``base_mesh`` is +the L0 carrier used for the graph solve and ``rest_mesh`` is the stored L2 +surface whose sparse ``base_stencils`` provide the evaluated weights. The +rest surface is never regenerated or repaired here. +""" +from __future__ import annotations + +import copy +import math +from collections.abc import Mapping +from numbers import Real +from typing import Any + +import numpy as np + + +_SIDES = ("left", "right") +_GROUPS = ("socket", "ringA", "ringB", "exit") +_PORTS = {"left": "port.left_thigh", "right": "port.right_thigh"} +_TOLERANCE = 1.0e-12 + + +def _fail(message: str) -> None: + raise ValueError(message) + + +def _check_weight_bounds(weights: np.ndarray, where: str) -> None: + if np.any(weights < -_TOLERANCE) or np.any(weights > 1.0 + _TOLERANCE): + _fail(f"{where} contains a weight outside [-1e-12, 1+1e-12]") + + +def _number(value: Any, where: str) -> float: + if isinstance(value, bool) or not isinstance(value, Real): + _fail(f"{where} must be a finite number") + result = float(value) + if not math.isfinite(result): + _fail(f"{where} must be a finite number") + return result + + +def _vector(value: Any, where: str) -> list[float]: + if not isinstance(value, (list, tuple)) or len(value) != 3: + _fail(f"{where} must be a three-component vector") + return [_number(item, f"{where}[{index}]") for index, item in enumerate(value)] + + +def _mapping(value: Any, where: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping): + _fail(f"{where} must be a mapping") + return value + + +def _mesh_vertices(mesh: Mapping[str, Any], where: str) -> list[list[float]]: + raw = mesh.get("vertices") + if not isinstance(raw, (list, tuple)) or not raw: + _fail(f"{where}.vertices must be a non-empty list") + return [_vector(point, f"{where}.vertices[{index}]") + for index, point in enumerate(raw)] + + +def _integer(value: Any, where: str) -> int: + if isinstance(value, bool) or not isinstance(value, int): + _fail(f"{where} must be an integer index") + return value + + +def _quads(mesh: Mapping[str, Any], count: int, where: str) -> list[list[int]]: + raw = mesh.get("quads") + if not isinstance(raw, (list, tuple)): + _fail(f"{where}.quads must be a list") + result: list[list[int]] = [] + for qi, quad in enumerate(raw): + if not isinstance(quad, (list, tuple)) or len(quad) != 4: + _fail(f"{where}.quads[{qi}] must contain four indices") + checked = [_integer(vertex, f"{where}.quads[{qi}][{i}]") + for i, vertex in enumerate(quad)] + if any(vertex < 0 or vertex >= count for vertex in checked): + _fail(f"{where}.quads[{qi}] contains an out-of-range vertex") + result.append(checked) + if not result: + _fail(f"{where}.quads must not be empty") + return result + + +def _boundary_graph(mesh: Mapping[str, Any], count: int) -> list[set[int]]: + graph = [set() for _ in range(count)] + for quad in _quads(mesh, count, "base_mesh"): + for index, left in enumerate(quad): + right = quad[(index + 1) % 4] + if left == right: + _fail("base_mesh quad has a zero-length boundary edge") + graph[left].add(right) + graph[right].add(left) + + seen = {0} + pending = [0] + while pending: + vertex = pending.pop() + for neighbour in graph[vertex]: + if neighbour not in seen: + seen.add(neighbour) + pending.append(neighbour) + if len(seen) != count: + _fail("L0 quad-boundary graph is disconnected") + return graph + + +def _transition_indices(base_mesh: Mapping[str, Any], count: int) -> dict[str, dict[str, list[int]]]: + metadata = _mapping(base_mesh.get("metadata"), "base_mesh.metadata") + raw = _mapping(metadata.get("transition_indices"), + "base_mesh.metadata.transition_indices") + if set(raw) != set(_SIDES): + _fail("transition_indices must contain exactly left and right") + + result: dict[str, dict[str, list[int]]] = {} + used: set[int] = set() + for side in _SIDES: + row = _mapping(raw[side], f"transition_indices.{side}") + if set(row) != set(_GROUPS): + _fail(f"transition_indices.{side} must contain socket, ringA, ringB and exit") + result[side] = {} + for group in _GROUPS: + values = row[group] + if not isinstance(values, (list, tuple)) or not values: + _fail(f"transition_indices.{side}.{group} must be a non-empty list") + checked = [_integer(value, f"transition_indices.{side}.{group}[{i}]") + for i, value in enumerate(values)] + if len(set(checked)) != len(checked): + _fail(f"transition_indices.{side}.{group} contains duplicates") + if any(value < 0 or value >= count for value in checked): + _fail(f"transition_indices.{side}.{group} contains an out-of-range index") + if used.intersection(checked): + _fail("transition_indices groups must be disjoint") + used.update(checked) + result[side][group] = checked + return result + + +def _rest_stencils(rest_mesh: Mapping[str, Any], l0_count: int, + l2_count: int) -> list[list[tuple[int, float]]]: + raw = rest_mesh.get("base_stencils") + if not isinstance(raw, (list, tuple)) or len(raw) != l2_count: + _fail("rest_mesh.base_stencils must have one stencil per L2 vertex") + result: list[list[tuple[int, float]]] = [] + for vi, stencil in enumerate(raw): + if not isinstance(stencil, (list, tuple)) or not stencil: + _fail(f"rest_mesh.base_stencils[{vi}] must be non-empty") + checked: list[tuple[int, float]] = [] + total = 0.0 + for si, pair in enumerate(stencil): + if not isinstance(pair, (list, tuple)) or len(pair) != 2: + _fail(f"rest_mesh.base_stencils[{vi}][{si}] must be [index, coefficient]") + index = _integer(pair[0], f"rest_mesh.base_stencils[{vi}][{si}][0]") + if index < 0 or index >= l0_count: + _fail(f"rest_mesh.base_stencils[{vi}] contains an out-of-range index") + coefficient = _number(pair[1], f"rest_mesh.base_stencils[{vi}][{si}][1]") + checked.append((index, coefficient)) + total += coefficient + if not math.isfinite(total) or abs(total - 1.0) > _TOLERANCE: + _fail(f"rest_mesh.base_stencils[{vi}] does not partition unity") + result.append(checked) + return result + + +def _solve_base_weights(base_mesh: Mapping[str, Any], transitions: dict[str, dict[str, list[int]]], + graph: list[set[int]]) -> np.ndarray: + count = len(graph) + unknown = sorted({index for side in _SIDES for group in ("socket", "ringA") + for index in transitions[side][group]}) + if not unknown: + _fail("transition_indices has no unknown vertices") + unknown_position = {vertex: index for index, vertex in enumerate(unknown)} + columns: list[np.ndarray] = [] + + for leg_side in _SIDES: + leg_anchors = set(transitions[leg_side]["ringB"]) + leg_anchors.update(transitions[leg_side]["exit"]) + if leg_anchors.intersection(unknown): + _fail("leg anchors may not overlap unknown socket/ringA vertices") + matrix = np.zeros((len(unknown), len(unknown)), dtype=np.float64) + rhs = np.zeros(len(unknown), dtype=np.float64) + for vertex, row in unknown_position.items(): + matrix[row, row] = float(len(graph[vertex])) + for neighbour in graph[vertex]: + if neighbour in unknown_position: + matrix[row, unknown_position[neighbour]] -= 1.0 + elif neighbour in leg_anchors: + rhs[row] += 1.0 + try: + solved = np.linalg.solve(matrix, rhs) + except np.linalg.LinAlgError as exc: + raise ValueError(f"harmonic solve failed for {leg_side} leg") from exc + if not np.all(np.isfinite(solved)): + _fail(f"harmonic solve produced non-finite {leg_side} weights") + + column = np.zeros(count, dtype=np.float64) + column[unknown] = solved + column[list(leg_anchors)] = 1.0 + columns.append(column) + + left, right = columns + pelvis = 1.0 - left - right + weights = np.column_stack((pelvis, left, right)) + if not np.all(np.isfinite(weights)): + _fail("base weights are non-finite") + _check_weight_bounds(weights, "base weights") + sums = np.sum(weights, axis=1) + if not np.all(np.abs(sums - 1.0) <= _TOLERANCE): + _fail("base weights do not partition unity") + return weights + + +def _propagate_weights(stencils: list[list[tuple[int, float]]], + base_weights: np.ndarray) -> np.ndarray: + evaluated = np.zeros((len(stencils), 3), dtype=np.float64) + for vertex, stencil in enumerate(stencils): + for base_index, coefficient in stencil: + evaluated[vertex] += coefficient * base_weights[base_index] + if not np.all(np.isfinite(evaluated)): + _fail("evaluated weights are non-finite") + _check_weight_bounds(evaluated, "evaluated weights") + sums = np.sum(evaluated, axis=1) + if not np.all(np.abs(sums - 1.0) <= _TOLERANCE): + _fail("evaluated weights do not partition unity") + return evaluated + + +def _validate_distal_ports(rest_mesh: Mapping[str, Any], weights: np.ndarray) -> dict[str, int]: + loops = _mapping(rest_mesh.get("loops"), "rest_mesh.loops") + counts: dict[str, int] = {} + expected = {"left": np.array([0.0, 1.0, 0.0]), + "right": np.array([0.0, 0.0, 1.0])} + for side in _SIDES: + name = _PORTS[side] + raw_loop = loops.get(name) + if not isinstance(raw_loop, (list, tuple)) or not raw_loop: + _fail(f"rest_mesh.loops.{name} must be a non-empty list") + checked = [_integer(value, f"rest_mesh.loops.{name}[{i}]") + for i, value in enumerate(raw_loop)] + if any(value < 0 or value >= len(weights) for value in checked): + _fail(f"rest_mesh.loops.{name} contains an out-of-range vertex") + for vertex in checked: + if not np.all(np.abs(weights[vertex] - expected[side]) <= _TOLERANCE): + _fail(f"{name} is not full strength for the {side} leg") + counts[name] = len(checked) + return counts + + +def _case_points(case: Mapping[str, Any], reference_landmarks: Mapping[str, Any]) -> tuple[dict[str, Any], dict[str, list[float]], dict[str, list[float]], dict[str, list[float]]]: + components = case.get("components") + if not isinstance(components, Mapping): + _fail("case.components must be a mapping") + attachments = _mapping(case.get("attachments"), "case.attachments") + if set(attachments) != set(_SIDES): + _fail("case.attachments must contain exactly left and right") + landmarks = _mapping(reference_landmarks, "reference_landmarks") + result: dict[str, Any] = {} + joints: dict[str, list[float]] = {} + targets: dict[str, list[float]] = {} + knees: dict[str, list[float]] = {} + for side in _SIDES: + row = _mapping(attachments[side], f"case.attachments.{side}") + if "centre" not in row or "knee" not in row: + _fail(f"case.attachments.{side} must contain centre and knee") + target = _vector(row["centre"], f"case.attachments.{side}.centre") + knee = _vector(row["knee"], f"case.attachments.{side}.knee") + joint = _vector(landmarks.get(f"joint_{side}"), + f"reference_landmarks.joint_{side}") + if np.linalg.norm(np.asarray(target) - joint) <= _TOLERANCE: + _fail(f"{side} T must differ from J") + if np.linalg.norm(np.asarray(knee) - joint) <= _TOLERANCE: + _fail(f"{side} K must differ from J") + joints[side], targets[side], knees[side] = joint, target, knee + result["id"] = case.get("id") + result["components"] = copy.deepcopy(dict(components)) + result["attachments"] = copy.deepcopy(dict(attachments)) + return result, joints, targets, knees + + +def _frame(joint: list[float], target: list[float], knee: list[float]) -> dict[str, Any]: + j = np.asarray(joint, dtype=np.float64) + t = np.asarray(target, dtype=np.float64) + k = np.asarray(knee, dtype=np.float64) + y = j - k + y /= np.linalg.norm(y) + x = np.asarray([1.0, 0.0, 0.0], dtype=np.float64) + x -= np.dot(x, y) * y + x_norm = np.linalg.norm(x) + if not math.isfinite(float(x_norm)) or x_norm <= _TOLERANCE: + _fail("global +X has no usable projection for the joint frame") + x /= x_norm + z = np.cross(x, y) + rotation = np.column_stack((x, y, z)) + rest_matrix = np.eye(4, dtype=np.float64) + rest_matrix[:3, :3] = rotation + rest_matrix[:3, 3] = j + return { + "J": joint, + "T": target, + "K": knee, + "rotation": rotation.tolist(), + "rest_matrix": rest_matrix.tolist(), + "T_local": (rotation.T @ (t - j)).tolist(), + "K_local": (rotation.T @ (k - j)).tolist(), + } + + +def _json_matrix(value: Any, where: str) -> np.ndarray: + raw = np.asarray(value, dtype=np.float64) + if raw.shape != (4, 4) or not np.all(np.isfinite(raw)): + _fail(f"{where} must be a finite 4x4 matrix") + return raw + + +def _angles(angles_degrees: Mapping[str, Any]) -> dict[str, float]: + values = _mapping(angles_degrees, "angles_degrees") + if set(values) != set(_SIDES): + _fail("angles_degrees must contain exactly left and right") + return {side: _number(values[side], f"angles_degrees.{side}") + for side in _SIDES} + + +def _local_rotation_x(theta_degrees: float) -> np.ndarray: + if theta_degrees == 0.0: + return np.eye(4, dtype=np.float64) + radians = math.radians(-theta_degrees) + cosine, sine = math.cos(radians), math.sin(radians) + return np.array([[1.0, 0.0, 0.0, 0.0], + [0.0, cosine, -sine, 0.0], + [0.0, sine, cosine, 0.0], + [0.0, 0.0, 0.0, 1.0]], dtype=np.float64) + + +def _joint_transforms(binding: Mapping[str, Any], angles_degrees: Mapping[str, Any]) -> dict[str, dict[str, Any]]: + angles = _angles(angles_degrees) + frames = _mapping(binding.get("rest_frames"), "binding.rest_frames") + if set(frames) != set(_SIDES): + _fail("binding.rest_frames must contain exactly left and right") + result: dict[str, dict[str, Any]] = {} + for side in _SIDES: + frame = _mapping(frames[side], f"binding.rest_frames.{side}") + rest = _json_matrix(frame.get("rest_matrix"), + f"binding.rest_frames.{side}.rest_matrix") + local = _local_rotation_x(angles[side]) + posed = rest @ local + try: + skin = posed @ np.linalg.inv(rest) + except np.linalg.LinAlgError as exc: + raise ValueError(f"rest frame for {side} is singular") from exc + if not np.all(np.isfinite(skin)): + _fail(f"skin matrix for {side} is non-finite") + + def carried(name: str) -> list[float]: + point = np.asarray(_vector(frame.get(name), + f"binding.rest_frames.{side}.{name}")) + return (skin @ np.r_[point, 1.0])[:3].tolist() + + rest_points = { + "J": _vector(frame.get("J"), f"binding.rest_frames.{side}.J"), + "T": _vector(frame.get("T"), f"binding.rest_frames.{side}.T"), + "K": _vector(frame.get("K"), f"binding.rest_frames.{side}.K"), + } + posed_points = {name: carried(name) for name in ("J", "T", "K")} + result[side] = { + # J/T/K are the posed diagnostic points; J remains fixed. The + # explicit rest/posed maps make the convention unambiguous. + **posed_points, + "rest_points": rest_points, + "posed_points": posed_points, + "rest_J": rest_points["J"], + "rest_T": rest_points["T"], + "rest_K": rest_points["K"], + "posed_J": posed_points["J"], + "posed_T": posed_points["T"], + "posed_K": posed_points["K"], + "rest_matrix": rest.tolist(), + "posed_matrix": posed.tolist(), + "skin_matrix": skin.tolist(), + "angle_degrees": angles[side], + } + return result + + +def bind(base_mesh: Mapping[str, Any], rest_mesh: Mapping[str, Any], case: Mapping[str, Any], + reference_landmarks: Mapping[str, Any]) -> dict[str, Any]: + """Return a JSON-safe L0-harmonic/L2-stencil hip binding.""" + base = _mapping(base_mesh, "base_mesh") + rest = _mapping(rest_mesh, "rest_mesh") + base_vertices = _mesh_vertices(base, "base_mesh") + rest_vertices = _mesh_vertices(rest, "rest_mesh") + if "level" in base and base["level"] != 0: + _fail("base_mesh must be level 0") + if "level" in rest and rest["level"] != 2: + _fail("rest_mesh must be level 2") + graph = _boundary_graph(base, len(base_vertices)) + transitions = _transition_indices(base, len(base_vertices)) + stencils = _rest_stencils(rest, len(base_vertices), len(rest_vertices)) + base_weights = _solve_base_weights(base, transitions, graph) + evaluated_weights = _propagate_weights(stencils, base_weights) + port_counts = _validate_distal_ports(rest, evaluated_weights) + case_copy, joints, targets, knees = _case_points(case, reference_landmarks) + frames = {side: _frame(joints[side], targets[side], knees[side]) + for side in _SIDES} + + return { + "schema": "creature-kernel.pelvis-hip-articulation-binding.v1", + "base_weights": base_weights.tolist(), + "evaluated_weights": evaluated_weights.tolist(), + "l0_anchor_indices": copy.deepcopy(transitions), + "rest_frames": frames, + "t_local": {side: frames[side]["T_local"] for side in _SIDES}, + "k_local": {side: frames[side]["K_local"] for side in _SIDES}, + "case": case_copy, + "metadata": { + "algorithm": "uniform_l0_quad_boundary_harmonic_then_l2_sparse_stencil_3joint_lbs", + "tolerance": _TOLERANCE, + "rest_geometry_regenerated": False, + "base_graph": "undirected quad boundary edges; quad diagonals excluded", + "weight_columns": ["pelvis", "left_leg", "right_leg"], + "stencil_provenance": "REST", + "posed_cage_evaluation": False, + "l2_distal_port_loop_counts": port_counts, + "transition_indices": copy.deepcopy(transitions), + }, + } + + +def joint_points(binding: Mapping[str, Any], angles: Mapping[str, Any]) -> dict[str, dict[str, Any]]: + """Return rest/posed joint points and matrices for both experimental pivots.""" + return _joint_transforms(_mapping(binding, "binding"), angles) + + +def pose(rest_mesh: Mapping[str, Any], binding: Mapping[str, Any], + angles_degrees: Mapping[str, Any]) -> dict[str, Any]: + """Pose stored L2 rest vertices with conventional three-joint LBS.""" + rest = _mapping(rest_mesh, "rest_mesh") + vertices = _mesh_vertices(rest, "rest_mesh") + weights_raw = _mapping(binding, "binding").get("evaluated_weights") + if not isinstance(weights_raw, (list, tuple)) or len(weights_raw) != len(vertices): + _fail("binding.evaluated_weights must match rest_mesh vertex count") + weights = np.asarray([_vector(row, f"binding.evaluated_weights[{i}]") + for i, row in enumerate(weights_raw)], dtype=np.float64) + if weights.shape != (len(vertices), 3) or not np.all(np.isfinite(weights)): + _fail("binding.evaluated_weights must be finite N x 3 data") + _check_weight_bounds(weights, "binding.evaluated_weights") + if not np.all(np.abs(np.sum(weights, axis=1) - 1.0) <= _TOLERANCE): + _fail("binding.evaluated_weights do not partition unity") + transforms = _joint_transforms(_mapping(binding, "binding"), angles_degrees) + skins = {side: _json_matrix(transforms[side]["skin_matrix"], + f"{side}.skin_matrix") for side in _SIDES} + angles = _angles(angles_degrees) + if all(value == 0.0 for value in angles.values()): + posed_vertices = copy.deepcopy(vertices) + else: + posed_vertices = [] + for index, point in enumerate(vertices): + homogeneous = np.r_[np.asarray(point, dtype=np.float64), 1.0] + left_point = (skins["left"] @ homogeneous)[:3] + right_point = (skins["right"] @ homogeneous)[:3] + value = (weights[index, 0] * homogeneous[:3] + + weights[index, 1] * left_point + + weights[index, 2] * right_point) + if not np.all(np.isfinite(value)): + _fail(f"posed vertex {index} is non-finite") + posed_vertices.append(value.tolist()) + + output = copy.deepcopy(dict(rest)) + output["vertices"] = posed_vertices + provenance = copy.deepcopy(output.get("provenance", {})) + if not isinstance(provenance, dict): + provenance = {} + provenance.update({"vertices": "POSED_BY_REST_L2_3JOINT_LBS", + "base_stencils": "REST", + "stencil_evaluation": "not posed cage evaluation"}) + output["provenance"] = provenance + metadata = copy.deepcopy(output.get("metadata", {})) + if not isinstance(metadata, dict): + metadata = {} + metadata.update({"stencil_provenance": "REST", + "base_stencils_provenance": "REST", + "posed_cage_evaluation": False, + "rest_geometry_regenerated": False, + "pose_angles_degrees": {side: angles[side] for side in _SIDES}}) + output["metadata"] = metadata + return output diff --git a/experiments/pelvis-hip-articulation/capture.py b/experiments/pelvis-hip-articulation/capture.py new file mode 100644 index 0000000..4ec0b52 --- /dev/null +++ b/experiments/pelvis-hip-articulation/capture.py @@ -0,0 +1,298 @@ +"""Capture and verify inputs for the local pelvis/hip articulation probe. + +This module is intentionally a small, stdlib-only evidence helper. It does +not import geometry, execute a body, or copy the frozen runtime. +""" + +from __future__ import annotations + +from datetime import datetime, timezone +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import shutil +import stat +import sys +from typing import Any, Iterable, Mapping, NoReturn + +sys.dont_write_bytecode = True + +HERE = Path(__file__).resolve().parent +FROZEN_DEPENDENCY_ROOT = Path("/home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot") +FROZEN_CALIBRATION_ROOT = Path("/home/ben/.cache/creature-kernel/pelvis-source-calibration-set-1") +FROZEN_CALIBRATION_RUNNER = FROZEN_CALIBRATION_ROOT / "source/experiments/pelvis-source-calibration/runner.py" +CALIBRATION_SOURCE_MANIFEST = FROZEN_CALIBRATION_ROOT / "source/manifest.json" +CALIBRATION_PREPARE_REPORT = FROZEN_CALIBRATION_ROOT / "prepare-report.json" +CALIBRATION_ARTIFACT_MANIFEST = FROZEN_CALIBRATION_ROOT / "run/artifact-sha-manifest-after.json" +CALIBRATION_ARTIFACT_MANIFEST_SHA256 = "f0152de5b6b82a60c35599b0b82af746704d1917446d8fceb88b2ca016275871" +CONSTRUCTION_SHA256 = "7fd457e2206165eb5e404ce81732f4157234a2e13a64008d96ae75d6abcf5cdb" + +STANDARD_FILE_NAMES = ("capture.py", "tests/test_capture.py", "README.md", "protocol.json") +INPUT_MAPPINGS = ( + ("case_05_rest_L0", "run/cases/case-05-calibrated_ordinary_human/mesh-L0.json", "case-05-calibrated_ordinary_human-rest-L0.json", "rest_mesh"), + ("case_05_rest_L2", "run/cases/case-05-calibrated_ordinary_human/mesh-L2.json", "case-05-calibrated_ordinary_human-rest-L2.json", "rest_mesh"), + ("case_06_rest_L0", "run/cases/case-06-calibrated_upright_anthropomorphic/mesh-L0.json", "case-06-calibrated_upright_anthropomorphic-rest-L0.json", "rest_mesh"), + ("case_06_rest_L2", "run/cases/case-06-calibrated_upright_anthropomorphic/mesh-L2.json", "case-06-calibrated_upright_anthropomorphic-rest-L2.json", "rest_mesh"), + ("calibration_protocol", "source/experiments/pelvis-source-calibration/protocol.json", "pelvis-source-calibration-protocol.json", "calibration_protocol"), + ("calibration_inputs", "source/experiments/pelvis-source-calibration/inputs.json", "pelvis-source-calibration-inputs.json", "calibration_inputs"), +) + + +class CaptureError(ValueError): + """Raised when a capture or verification contract is not satisfied.""" + + +def _fail(message: str) -> NoReturn: + raise CaptureError(message) + + +def _regular(path: Path, label: str) -> None: + try: + info = path.lstat() + except OSError as exc: + _fail(f"{label} is unavailable: {path}") + if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode): + _fail(f"{label} must be a regular non-symlink file: {path}") + + +def _canonical(path: str | os.PathLike[str], label: str) -> Path: + value = Path(path) + if not value.is_absolute() or os.path.normpath(str(value)) != str(value): + _fail(f"{label} must be an absolute canonical path") + return value + + +def _sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def _strict_json(path: Path) -> tuple[Any, bytes]: + _regular(path, "JSON file") + try: + raw = path.read_bytes() + value = json.loads(raw.decode("utf-8"), parse_constant=lambda token: (_ for _ in ()).throw(ValueError(token))) + except (OSError, UnicodeDecodeError, json.JSONDecodeError, ValueError) as exc: + _fail(f"invalid finite UTF-8 JSON: {path}") + return value, raw + + +def _write_json(path: Path, value: Any) -> None: + path.write_bytes((json.dumps(value, sort_keys=True, indent=2, ensure_ascii=True, allow_nan=False) + "\n").encode("utf-8")) + + +def _file_identity(path: Path) -> dict[str, Any]: + _regular(path, "capture file") + return {"bytes": path.stat().st_size, "sha256": _sha256_file(path)} + + +def _inventory(paths: Iterable[Path]) -> list[dict[str, Any]]: + return [{"origin_path": str(path), **_file_identity(path)} for path in sorted(paths, key=lambda item: str(item).encode("utf-8"))] + + +def _load_frozen_dependency_identity() -> dict[str, Any]: + """Reuse the frozen calibration runner's stdlib identity implementation.""" + sys.dont_write_bytecode = True + _regular(FROZEN_CALIBRATION_RUNNER, "frozen calibration runner") + source_manifest, _ = _strict_json(CALIBRATION_SOURCE_MANIFEST) + source_rows = { + str(row.get("path")): row + for row in source_manifest.get("files", []) + if isinstance(row, Mapping) + } + runner_row = source_rows.get("experiments/pelvis-source-calibration/runner.py") + if runner_row is None or _file_identity(FROZEN_CALIBRATION_RUNNER) != { + "bytes": runner_row.get("bytes") if runner_row else None, + "sha256": runner_row.get("sha256") if runner_row else None, + }: + _fail("frozen calibration runner differs from the captured source manifest") + name = "ck_frozen_pelvis_source_calibration_runner" + spec = importlib.util.spec_from_file_location(name, FROZEN_CALIBRATION_RUNNER) + if spec is None or spec.loader is None: + _fail(f"unable to load frozen calibration runner: {FROZEN_CALIBRATION_RUNNER}") + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + try: + spec.loader.exec_module(module) + except Exception: + if sys.modules.get(name) is module: + sys.modules.pop(name, None) + raise + identity = module._dependency_identity(FROZEN_DEPENDENCY_ROOT) + if not isinstance(identity, dict): + _fail("frozen calibration runner returned a non-object dependency identity") + if identity["manifest"]["construction"]["sha256"] != CONSTRUCTION_SHA256: + _fail("frozen construction identity differs from the required SHA-256") + return identity + + +def _capture_names(file_names: Iterable[str] | None) -> list[str]: + names = list(STANDARD_FILE_NAMES if file_names is None else file_names) + if not names: + _fail("at least one experiment file must be captured") + if len(set(names)) != len(names): + _fail("file_names contains duplicates") + selected: list[str] = [] + for name in names: + relative = Path(name) + if relative.is_absolute() or ".." in relative.parts: + _fail(f"experiment filename must be relative and confined to the experiment: {name}") + path = HERE / relative + if file_names is None and not os.path.lexists(path): + continue + _regular(path, "experiment source") + selected.append(relative.as_posix()) + if not selected: + _fail("no requested experiment files exist") + return selected + + +def _calibration_inputs() -> list[tuple[str, Path, Path, str]]: + manifest, _ = _strict_json(CALIBRATION_SOURCE_MANIFEST) + report, _ = _strict_json(CALIBRATION_PREPARE_REPORT) + artifact, _ = _strict_json(CALIBRATION_ARTIFACT_MANIFEST) + if _sha256_file(CALIBRATION_ARTIFACT_MANIFEST) != CALIBRATION_ARTIFACT_MANIFEST_SHA256: + _fail("calibration artifact manifest differs from its frozen protocol hash") + if not isinstance(artifact, Mapping) or artifact.get("schema") != "creature-kernel.pelvis-source-calibration-artifacts.v1": + _fail("calibration artifact manifest is not admitted") + if not isinstance(manifest, Mapping) or manifest.get("schema") != "creature-kernel.pelvis-source-calibration-captured-source.v1": + _fail("captured calibration source manifest is not admitted") + if not isinstance(report, Mapping) or report.get("status") != "prepared": + _fail("captured calibration prepare report is not admitted") + artifact_rows = {str(row.get("path")): row for row in artifact.get("files", []) if isinstance(row, Mapping)} + rows = {str(row.get("path")): row for row in manifest.get("files", []) if isinstance(row, Mapping)} + result = [] + for name, relative, target_name, kind in INPUT_MAPPINGS: + source = FROZEN_CALIBRATION_ROOT / relative + _regular(source, "preserved calibration input") + expected = rows.get(relative.removeprefix("source/")) + actual = _file_identity(source) + if kind == "rest_mesh": + artifact_path = relative.removeprefix("run/") + artifact_expected = artifact_rows.get(artifact_path) + if artifact_expected is None: + _fail(f"calibration artifact manifest lacks: {artifact_path}") + if actual != {"bytes": artifact_expected.get("bytes"), "sha256": artifact_expected.get("sha256")}: + _fail(f"preserved rest mesh differs from the calibration artifact manifest: {source}") + else: + if expected is None: + _fail(f"captured calibration source manifest lacks: {relative}") + if actual != {"bytes": expected.get("bytes"), "sha256": expected.get("sha256")}: + _fail(f"preserved calibration input differs from its source manifest: {source}") + result.append((name, source, Path("inputs") / target_name, kind)) + return result + + +def _copy_group(output: Path, entries: Iterable[tuple[str, Path, Path, str]]) -> dict[str, Any]: + entries = list(entries) + before = [{"name": name, "origin_path": str(source), **_file_identity(source)} for name, source, _target, _kind in entries] + copies = [] + for name, source, relative_target, kind in entries: + target = output / relative_target + if target.exists() or target.is_symlink(): + _fail(f"capture target must be absent: {target}") + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, target) + copied = _file_identity(target) + source_identity = _file_identity(source) + if copied != source_identity: + _fail(f"copied bytes differ from source-before identity: {source}") + copies.append({"name": name, "kind": kind, "origin_path": str(source), "snapshot_path": relative_target.as_posix(), **copied}) + after = [{"name": name, "origin_path": str(source), **_file_identity(source)} for name, source, _target, _kind in entries] + if before != after: + _fail("source changed while being captured") + return {"before": before, "copies": copies, "after": after} + + +def prepare(output: str | os.PathLike[str], file_names: Iterable[str] | None = None) -> dict[str, Any]: + """Capture listed experiment files and frozen rest inputs into an absent path.""" + sys.dont_write_bytecode = True + output_path = _canonical(output, "prepare output") + if output_path.exists() or output_path.is_symlink(): + _fail(f"prepare output must be absent: {output_path}") + if not output_path.parent.is_dir() or output_path.parent.is_symlink(): + _fail("prepare output parent must be an existing regular directory") + names = _capture_names(file_names) + dependency_before = _load_frozen_dependency_identity() + source_entries = [(name, HERE / name, Path("source/experiments/pelvis-hip-articulation") / name, "experiment_source") for name in names] + input_entries = _calibration_inputs() + output_path.mkdir() + source_record = _copy_group(output_path, source_entries) + input_record = _copy_group(output_path, input_entries) + dependency_after = _load_frozen_dependency_identity() + if dependency_before != dependency_after: + _fail("frozen dependency changed while preparing the capture") + runtime_path = dependency_before["runtime"]["executable"] + manifest = { + "schema": "creature-kernel.pelvis-hip-articulation-capture.v1", + "status": "prepared", + "geometry_executed": False, + "body_articulation_executed": False, + "captured_at_utc": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"), + "runtime_path": runtime_path, + "runtime_environment": {"variable": "CK_CURRENT_FORM_SURFACE_PYTHON", "value": runtime_path}, + "frozen_dependency": {"root": str(FROZEN_DEPENDENCY_ROOT), "construction_sha256": CONSTRUCTION_SHA256, "reused_without_copy": True, "before": dependency_before, "after": dependency_after}, + "calibration_provenance": {"prepare_report": {"origin_path": str(CALIBRATION_PREPARE_REPORT), **_file_identity(CALIBRATION_PREPARE_REPORT)}, "source_manifest": {"origin_path": str(CALIBRATION_SOURCE_MANIFEST), **_file_identity(CALIBRATION_SOURCE_MANIFEST)}, "artifact_manifest": {"origin_path": str(CALIBRATION_ARTIFACT_MANIFEST), "sha256": CALIBRATION_ARTIFACT_MANIFEST_SHA256, "bytes": CALIBRATION_ARTIFACT_MANIFEST.stat().st_size}}, + "captured_source": {"file_names": names, **source_record}, + "inputs": {"filename_mappings": [{"name": name, "kind": kind, "origin_path": str(source), "snapshot_path": target.as_posix()} for name, source, target, kind in input_entries], **input_record}, + "limitations": ["This capture is stdlib-only and does not execute geometry or body articulation.", "The shared calibration dependency/runtime is referenced and identity-verified, not copied; the shared stdlib/OS environment is not fully hermetic.", "The captured launcher is not executable; reproduce it with bash and set CK_CURRENT_FORM_SURFACE_PYTHON to the exact recorded frozen runtime path."], + } + _write_json(output_path / "manifest.json", manifest) + return manifest + + +def verify(snapshot: str | os.PathLike[str]) -> dict[str, Any]: + """Verify a prepared capture and the unchanged frozen dependency identity.""" + snapshot_path = _canonical(snapshot, "snapshot") + if not snapshot_path.is_dir() or snapshot_path.is_symlink(): + _fail(f"snapshot must be a regular directory: {snapshot_path}") + manifest, _ = _strict_json(snapshot_path / "manifest.json") + if not isinstance(manifest, Mapping) or manifest.get("schema") != "creature-kernel.pelvis-hip-articulation-capture.v1": + _fail("capture manifest schema is not admitted") + if manifest.get("geometry_executed") or manifest.get("body_articulation_executed"): + _fail("capture manifest claims an execution") + expected_paths = set() + for group_name in ("captured_source", "inputs"): + group = manifest.get(group_name) + if not isinstance(group, Mapping) or group.get("before") != group.get("after"): + _fail(f"{group_name} source inventory drifted") + for row in group.get("copies", []): + if not isinstance(row, Mapping): + _fail(f"{group_name} copy row is malformed") + target = snapshot_path / str(row["snapshot_path"]) + try: + relative_target = target.relative_to(snapshot_path) + except ValueError: + _fail(f"captured path escapes snapshot: {target}") + expected_paths.add(relative_target.as_posix()) + if _file_identity(target) != {"bytes": row["bytes"], "sha256": row["sha256"]}: + _fail(f"captured file drifted: {target}") + actual_paths = {path.relative_to(snapshot_path).as_posix() for path in snapshot_path.rglob("*") if path.is_file() and path.name != "manifest.json"} + if actual_paths != expected_paths: + _fail("snapshot contains missing or unexpected captured files") + dependency = _load_frozen_dependency_identity() + recorded = manifest.get("frozen_dependency", {}) + if dependency != recorded.get("before") or dependency != recorded.get("after"): + _fail("frozen dependency identity drifted") + if manifest.get("runtime_path") != dependency["runtime"]["executable"] or manifest.get("frozen_dependency", {}).get("construction_sha256") != CONSTRUCTION_SHA256: + _fail("runtime or construction identity is not the required frozen identity") + return dict(manifest) + + +def artifact_manifest(output: str | os.PathLike[str]) -> dict[str, Any]: + """Return a small relative-path and SHA-256 inventory for a capture.""" + root = _canonical(output, "artifact output") + if not root.is_dir() or root.is_symlink(): + _fail(f"artifact output must be a regular directory: {root}") + files = [] + for path in sorted(root.rglob("*"), key=lambda item: item.relative_to(root).as_posix().encode("utf-8")): + if path.is_symlink(): + _fail(f"artifact tree contains a symlink: {path}") + if path.is_file(): + files.append({"path": path.relative_to(root).as_posix(), **_file_identity(path)}) + return {"schema": "creature-kernel.pelvis-hip-articulation-artifacts.v1", "files": files} diff --git a/experiments/pelvis-hip-articulation/checks.py b/experiments/pelvis-hip-articulation/checks.py new file mode 100644 index 0000000..d94ae98 --- /dev/null +++ b/experiments/pelvis-hip-articulation/checks.py @@ -0,0 +1,400 @@ +"""Independent, fail-closed checks for exported hip-articulation poses.""" + +from __future__ import annotations + +import importlib.util +import math +import sys +from pathlib import Path +from typing import Any, Mapping, Sequence + + +_OLD_CHECKS = Path("/home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot/source/experiments/pelvis-thigh-transition/checks.py") +_JOINTS = ("pelvis", "left_hip", "right_hip") +_EXAMPLE_CAP = 8 + + +def _vsub(a, b): return tuple(float(a[i]) - float(b[i]) for i in range(3)) +def _vadd(a, b): return tuple(float(a[i]) + float(b[i]) for i in range(3)) +def _vmul(a, s): return tuple(float(x) * float(s) for x in a) +def _dot(a, b): return sum(float(a[i]) * float(b[i]) for i in range(3)) +def _cross(a, b): return (a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]) +def _norm(a): return math.sqrt(_dot(a, a)) +def _distance(a, b): return _norm(_vsub(a, b)) + + +def _mat(value: Any, label: str) -> list[list[float]]: + if not isinstance(value, Sequence) or isinstance(value, (str, bytes)): + raise ValueError(f"{label} must be a 4x4 matrix") + if len(value) == 16: + rows = [value[i:i + 4] for i in range(0, 16, 4)] + else: + rows = value + if len(rows) != 4 or any(not isinstance(r, Sequence) or len(r) != 4 for r in rows): + raise ValueError(f"{label} must be a 4x4 matrix") + out = [[float(x) for x in row] for row in rows] + if not all(math.isfinite(x) for row in out for x in row): + raise ValueError(f"{label} is not finite") + return out + + +def _mm(a, b): return [[sum(a[r][k]*b[k][c] for k in range(4)) for c in range(4)] for r in range(4)] +def _mp(m, p): + q = [float(p[0]), float(p[1]), float(p[2]), 1.0] + return tuple(sum(m[r][c]*q[c] for c in range(4)) for r in range(3)) +def _identity_error(m): return max(abs(m[r][c] - (1.0 if r == c else 0.0)) for r in range(4) for c in range(4)) + + +def _rigid_inverse(m): + out = [[m[c][r] if r < 3 and c < 3 else 0.0 for c in range(4)] for r in range(4)] + out[3][3] = 1.0 + for r in range(3): out[r][3] = -sum(out[r][c]*m[c][3] for c in range(3)) + return out + + +def _landmark(data: Mapping[str, Any], side: str, name: str) -> tuple[float, float, float]: + value = None + if isinstance(data.get(side), Mapping): value = data[side].get(name) + if value is None and isinstance(data.get(name), Mapping): value = data[name].get(side) + if value is None: value = data.get(f"{side}_{name}") + if not isinstance(value, Sequence) or len(value) != 3: + raise ValueError(f"missing reference landmark {side}.{name}") + point = tuple(float(x) for x in value) + if not all(math.isfinite(x) for x in point): raise ValueError(f"non-finite reference landmark {side}.{name}") + return point + + +def _references(case, refs): + if isinstance(refs.get("left"), Mapping): return dict(refs) + attachments = case.get("attachments", {}) if isinstance(case, Mapping) else {} + result = {} + for side in ("left", "right"): + row = attachments.get(side, {}) if isinstance(attachments, Mapping) else {} + result[side] = {"J": refs.get(f"joint_{side}"), "T": row.get("centre"), "K": row.get("knee")} + crests = [refs.get("crest_left"), refs.get("crest_right")] + if all(isinstance(p, Sequence) and len(p) == 3 for p in crests): result["crest_y"] = max(float(p[1]) for p in crests) + return result + + +def _frame(j, k): + y0 = _vsub(j, k); yn = _norm(y0) + if yn == 0.0: raise ValueError("J and K coincide") + y = _vmul(y0, 1.0/yn) + xp = _vsub((1.0, 0.0, 0.0), _vmul(y, y[0])); xn = _norm(xp) + if xn == 0.0: raise ValueError("J-K is parallel to global +X") + x = _vmul(xp, 1.0/xn); z = _cross(x, y) + return [[x[0], y[0], z[0], j[0]], [x[1], y[1], z[1], j[1]], [x[2], y[2], z[2], j[2]], [0.0, 0.0, 0.0, 1.0]] + + +def _expected_matrices(angles, refs): + result = {"pelvis": [[1.,0.,0.,0.], [0.,1.,0.,0.], [0.,0.,1.,0.], [0.,0.,0.,1.]]} + for side in ("left", "right"): + rest = _frame(_landmark(refs, side, "J"), _landmark(refs, side, "K")) + a = math.radians(-float(angles.get(side, 0.0))); c, s = math.cos(a), math.sin(a) + rx = [[1.,0.,0.,0.], [0.,c,-s,0.], [0.,s,c,0.], [0.,0.,0.,1.]] + result[f"{side}_hip"] = (rest, _mm(rest, rx)) + return result + + +def _joint_rows(binding: Mapping[str, Any]): + joints = binding.get("joints") + if not isinstance(joints, Mapping): + frames = binding.get("rest_frames") + if not isinstance(frames, Mapping): raise ValueError("binding.rest_frames must be a mapping") + identity = [[1.,0.,0.,0.], [0.,1.,0.,0.], [0.,0.,1.,0.], [0.,0.,0.,1.]] + rows = {"pelvis": (identity, identity)} + for side in ("left", "right"): + row = frames.get(side) + if not isinstance(row, Mapping): raise ValueError(f"missing binding rest frame {side}") + rest = _mat(row.get("rest_matrix"), f"{side}.rest_matrix") + rows[f"{side}_hip"] = (rest, _rigid_inverse(rest)) + return rows + rows = {} + for name in _JOINTS: + row = joints.get(name) + if not isinstance(row, Mapping): raise ValueError(f"missing binding joint {name}") + rest = _mat(row.get("rest_matrix"), f"{name}.rest_matrix") + inv = _mat(row.get("inverse_bind_matrix", row.get("inverse_bind")), f"{name}.inverse_bind_matrix") + rows[name] = (rest, inv) + return rows + + +def _weights(binding, count): + raw = binding.get("evaluated_weights", binding.get("weights")) + order = binding.get("joint_order", list(_JOINTS)) + if not isinstance(raw, Sequence) or len(raw) != count: raise ValueError("binding.weights must cover every vertex") + out = [] + for i, row in enumerate(raw): + if isinstance(row, Mapping): vals = [float(row.get(name, 0.0)) for name in _JOINTS] + elif isinstance(row, Sequence) and len(row) == len(order): + keyed = dict(zip(order, row)); vals = [float(keyed.get(name, 0.0)) for name in _JOINTS] + else: raise ValueError(f"malformed weight row {i}") + out.append(vals) + return out + + +def _pose_payload(posed): + joints = posed.get("joints") + if joints is None and isinstance(posed.get("metadata"), Mapping): joints = posed["metadata"].get("joints") + if not isinstance(joints, Mapping): return None + result = {} + for name in _JOINTS: + row = joints.get(name) + if not isinstance(row, Mapping): raise ValueError(f"posed export is missing joint {name}") + result[name] = _mat(row.get("pose_matrix", row.get("matrix")), f"posed {name}.pose_matrix") + return result + + +def _lbs(vertices, weights, skins): + result = [] + for p, row in zip(vertices, weights): + result.append(tuple(sum(row[j] * _mp(skins[name], p)[axis] for j, name in enumerate(_JOINTS)) for axis in range(3))) + return result + + +def _triangles(quads): return [t for q in quads for t in ((q[0], q[1], q[2]), (q[0], q[2], q[3]))] +def _tri_area(v, t): return 0.5*_norm(_cross(_vsub(v[t[1]], v[t[0]]), _vsub(v[t[2]], v[t[0]]))) +def _face_normal(v, q): return _vadd(_cross(_vsub(v[q[1]], v[q[0]]), _vsub(v[q[2]], v[q[0]])), _cross(_vsub(v[q[2]], v[q[0]]), _vsub(v[q[3]], v[q[0]]))) + + +def _frozen_helpers(): + spec = importlib.util.spec_from_file_location("frozen_pelvis_transition_checks", _OLD_CHECKS) + if spec is None or spec.loader is None: raise RuntimeError("frozen intersection helper unavailable") + module = importlib.util.module_from_spec(spec); sys.modules[spec.name] = module; spec.loader.exec_module(module) + return module + + +def _crest_y(case, refs, protocol): + for source in (protocol, case, refs): + if isinstance(source, Mapping): + for key in ("crest_y", "pelvic_crest_y"): + if key in source: return float(source[key]) + raise ValueError("crest_y is required") + + +def _scale(case, refs, vertices): + lengths = [_distance(_landmark(refs, s, "J"), _landmark(refs, s, "K")) for s in ("left", "right")] + return sum(lengths)/len(lengths) if max(lengths) > 0.0 else max(_distance(vertices[0], p) for p in vertices) + + +def check_binding(base_mesh: Mapping[str, Any], rest_mesh: Mapping[str, Any], binding: Mapping[str, Any], + protocol: Mapping[str, Any]) -> dict[str, Any]: + """Verify the exported weights satisfy the declared harmonic/stencil method.""" + report = {"schema": "pelvis-hip-articulation-binding-checks-v1", "pass": False, "checks": {}, "metrics": {}, "errors": []} + try: + tolerance = float(protocol["checks"]["weight_partition_tolerance"]) + base_vertices, quads = base_mesh["vertices"], base_mesh["quads"] + count = len(base_vertices); graph = [set() for _ in range(count)] + for qi, quad in enumerate(quads): + if not isinstance(quad, Sequence) or len(quad) != 4: raise ValueError(f"malformed base quad {qi}") + for i, vertex in enumerate(quad): + neighbour = quad[(i+1) % 4] + if not isinstance(vertex, int) or not isinstance(neighbour, int) or min(vertex, neighbour) < 0 or max(vertex, neighbour) >= count: + raise ValueError(f"out-of-range base quad {qi}") + graph[vertex].add(neighbour); graph[neighbour].add(vertex) + seen, pending = ({0}, [0]) if count else (set(), []) + while pending: + vertex = pending.pop() + for neighbour in graph[vertex] - seen: seen.add(neighbour); pending.append(neighbour) + connected = len(seen) == count and count > 0 + transitions = base_mesh["metadata"]["transition_indices"] + groups = {(side, group): set(transitions[side][group]) for side in ("left", "right") + for group in ("socket", "ringA", "ringB", "exit")} + if any(not values or any(i < 0 or i >= count for i in values) for values in groups.values()): raise ValueError("invalid base transition indices") + unknown = groups["left", "socket"] | groups["left", "ringA"] | groups["right", "socket"] | groups["right", "ringA"] + left = groups["left", "ringB"] | groups["left", "exit"] + right = groups["right", "ringB"] | groups["right", "exit"] + if (unknown & left) or (unknown & right) or (left & right): raise ValueError("overlapping Dirichlet groups") + base_weights = binding.get("base_weights"); evaluated = binding.get("evaluated_weights") + if not isinstance(base_weights, Sequence) or len(base_weights) != count: raise ValueError("base_weights dimensions do not match L0") + if not isinstance(evaluated, Sequence) or len(evaluated) != len(rest_mesh["vertices"]): raise ValueError("evaluated_weights dimensions do not match L2") + rows = [[float(x) for x in row] for row in base_weights] + eval_rows = [[float(x) for x in row] for row in evaluated] + finite_dims = all(len(row) == 3 and all(math.isfinite(x) for x in row) for row in rows + eval_rows) + if not finite_dims: raise ValueError("weights must be finite three-column rows") + anchor_error = 0.0 + for i in set(range(count)) - unknown: + expected = (0., 1., 0.) if i in left else (0., 0., 1.) if i in right else (1., 0., 0.) + anchor_error = max(anchor_error, max(abs(rows[i][c]-expected[c]) for c in range(3))) + residual = max((abs(len(graph[i])*rows[i][c] - sum(rows[j][c] for j in graph[i])) + for i in unknown for c in range(3)), default=math.inf) + stencils = rest_mesh.get("base_stencils") + if not isinstance(stencils, Sequence) or len(stencils) != len(eval_rows): raise ValueError("base_stencils dimensions do not match L2") + stencil_error = 0.0 + for i, stencil in enumerate(stencils): + if not isinstance(stencil, Sequence) or not stencil: raise ValueError(f"malformed base stencil {i}") + for c in range(3): + expected = sum(float(coefficient)*rows[int(index)][c] for index, coefficient in stencil) + stencil_error = max(stencil_error, abs(eval_rows[i][c]-expected)) + report["checks"] = {"connected_base_graph": connected, "finite_dimensions": finite_dims, + "dirichlet_anchors": anchor_error <= tolerance, + "harmonic_residual": residual <= tolerance, + "stencil_transfer": stencil_error <= tolerance} + report["metrics"] = {"anchor_max_error": anchor_error, "laplacian_residual_max": residual, + "stencil_max_error": stencil_error} + except Exception as exc: + report["errors"].append({"code": "binding_check_failure", "detail": str(exc)}) + report["pass"] = not report["errors"] and bool(report["checks"]) and all(report["checks"].values()) + return report + + +def check_pose(rest_mesh: Mapping[str, Any], posed_mesh: Mapping[str, Any], binding: Mapping[str, Any], + angles: Mapping[str, float], case: Mapping[str, Any], reference_landmarks: Mapping[str, Any], + protocol: Mapping[str, Any]) -> dict[str, Any]: + """Return a small JSON-safe report; exported inputs are never repaired.""" + report: dict[str, Any] = {"schema": "pelvis-hip-articulation-checks-v1", "pass": False, "checks": {}, "metrics": {}, "errors": []} + fail = lambda code, detail: report["errors"].append({"code": code, "detail": str(detail)}) + try: + reference_landmarks = _references(case, reference_landmarks) + limits = protocol.get("checks") + if not isinstance(limits, Mapping): raise ValueError("protocol.checks must be a mapping") + weight_tolerance = float(limits["weight_partition_tolerance"]) + frame_tolerance = float(limits["frame_and_transform_tolerance"]) + identity_tolerance = float(limits["identity_error_over_L_max"]) + lbs_tolerance = float(limits["exported_LBS_error_over_L_max"]) + port_tolerance = float(limits["rigid_port_error_over_L_max"]) + pelvis_tolerance = float(limits["pelvis_only_weighted_error_over_L_max"]) + crest_tolerance = float(limits["above_crest_skin_displacement_over_L_max"]) + area_min, area_max = (float(x) for x in limits["lower_triangle_area_ratio"]) + edge_min, edge_max = (float(x) for x in limits["lower_edge_length_ratio"]) + normal_min = float(limits["lower_rest_posed_triangle_normal_dot_min"]) + intersection_max = int(limits["lower_nonadjacent_intersections_max"]) + rv, pv = rest_mesh["vertices"], posed_mesh["vertices"] + rq, pq = rest_mesh["quads"], posed_mesh["quads"] + if not isinstance(rv, Sequence) or not isinstance(pv, Sequence) or len(rv) != len(pv): raise ValueError("vertex arrays differ in length") + finite = all(isinstance(p, Sequence) and len(p) == 3 and all(math.isfinite(float(x)) for x in p) for p in list(rv)+list(pv)) + topology = rq == pq and rest_mesh.get("loops") == posed_mesh.get("loops") + report["checks"].update(finite_vertices=finite, exact_topology=topology) + if not finite: raise ValueError("non-finite or malformed vertices") + if not topology: fail("topology", "quads or welded-index loops changed") + L = _scale(case, reference_landmarks, rv) + joints = _joint_rows(binding); weights = _weights(binding, len(rv)); exported_pose = _pose_payload(posed_mesh) + finite_weights = all(math.isfinite(w) for row in weights for w in row) + bounds = finite_weights and all(-weight_tolerance <= w <= 1.0+weight_tolerance for row in weights for w in row) + partition_error = max(abs(sum(row)-1.0) for row in weights) + report["checks"].update(finite_weights=finite_weights, weight_bounds=bounds, + partition_unity=finite_weights and partition_error <= weight_tolerance) + if not finite_weights: raise ValueError("binding weights are non-finite") + expected = _expected_matrices(angles, reference_landmarks) + frame_errors, det_errors, inverse_errors, pose_export_errors = [], [], [], [] + expected_pose = {"pelvis": expected["pelvis"]} + for name in _JOINTS: + rest, inv = joints[name] + basis = [[rest[r][c] for c in range(3)] for r in range(3)] + frame_errors.append(max(abs(sum(basis[k][r]*basis[k][c] for k in range(3))-(r == c)) for r in range(3) for c in range(3))) + det = _dot(tuple(basis[r][0] for r in range(3)), _cross(tuple(basis[r][1] for r in range(3)), tuple(basis[r][2] for r in range(3)))) + det_errors.append(abs(det-1.0)); inverse_errors.append(_identity_error(_mm(rest, inv))) + if name != "pelvis": + exp_rest, exp_pose = expected[name]; frame_errors.append(max(abs(rest[r][c]-exp_rest[r][c]) for r in range(4) for c in range(4))); expected_pose[name] = exp_pose + if exported_pose is not None: + pose_export_errors.append(max(abs(exported_pose[name][r][c]-expected_pose[name][r][c]) for r in range(4) for c in range(4))) + metadata = posed_mesh.get("metadata", {}) + exported_angles = metadata.get("pose_angles_degrees", {}) if isinstance(metadata, Mapping) else {} + if not isinstance(exported_angles, Mapping) or any(side not in exported_angles for side in ("left", "right")): + raise ValueError("posed metadata must export both pose angles") + angle_error = max(abs(float(exported_angles.get(side, math.inf))-float(angles.get(side, 0.0))) for side in ("left", "right")) + local_errors = [] + frames = binding.get("rest_frames", {}) + for side in ("left", "right"): + if isinstance(frames, Mapping) and isinstance(frames.get(side), Mapping): + inv = joints[f"{side}_hip"][1] + for mark, key in (("T", "T_local"), ("K", "K_local")): + declared = frames[side].get(key, binding.get(key.lower(), {}).get(side) if isinstance(binding.get(key.lower()), Mapping) else None) + if not isinstance(declared, Sequence) or len(declared) != 3: raise ValueError(f"missing {side} {key}") + local_errors.append(_distance(declared, _mp(inv, _landmark(reference_landmarks, side, mark)))) + for mark in ("J", "T", "K"): + declared = frames[side].get(mark) + if declared is not None: local_errors.append(_distance(declared, _landmark(reference_landmarks, side, mark))) + skins_rest = {n: _mm(joints[n][0], joints[n][1]) for n in _JOINTS} + skins_pose = {n: _mm(expected_pose[n], joints[n][1]) for n in _JOINTS} + identity_error = max(_distance(a, b) for a, b in zip(rv, _lbs(rv, weights, skins_rest))) + posed_errors = [_distance(a, b) for a, b in zip(pv, _lbs(rv, weights, skins_pose))] + report["checks"].update(frames=max(frame_errors) <= frame_tolerance and max(det_errors) <= frame_tolerance, + inverse_bind=max(inverse_errors) <= frame_tolerance, + exported_pose=angle_error <= frame_tolerance and (not pose_export_errors or max(pose_export_errors) <= frame_tolerance), + landmark_rest_locals=(not local_errors or max(local_errors) <= frame_tolerance*L), + identity_rest=identity_error <= identity_tolerance*L, + independent_lbs=max(posed_errors) <= lbs_tolerance*L) + report["metrics"].update(scale=L, partition_error=partition_error, frame_error=max(frame_errors), determinant_error=max(det_errors), + inverse_bind_error=max(inverse_errors), pose_export_error=max(pose_export_errors, default=angle_error), + landmark_rest_local_error=max(local_errors, default=0.0), identity_rest_max_error=identity_error, + posed_lbs_max_error=max(posed_errors), posed_lbs_worst_vertices=sorted(range(len(posed_errors)), key=posed_errors.__getitem__, reverse=True)[:_EXAMPLE_CAP]) + + tris = _triangles(rq); rest_areas = [_tri_area(rv, t) for t in tris]; posed_areas = [_tri_area(pv, t) for t in tris] + owners = rest_mesh.get("face_owners", []) + if len(owners) != len(rq): raise ValueError("face_owners must cover quads") + frozen = _frozen_helpers() + lower_faces = {i for i, owner in enumerate(owners) if frozen._owner_is_lower(owner)} + lower_triangle_ids = [i for i in range(len(tris)) if i//2 in lower_faces] + area_ratios = [posed_areas[i]/rest_areas[i] if rest_areas[i] > 0 else math.inf for i in lower_triangle_ids] + edges = {tuple(sorted((q[i], q[(i+1)%4]))) for f, q in enumerate(rq) if f in lower_faces for i in range(4)} + edge_ratios = [_distance(pv[a], pv[b])/_distance(rv[a], rv[b]) for a, b in edges if _distance(rv[a], rv[b]) > 0] + normals, normal_face_ids = [], [] + for i in lower_triangle_ids: + triangle = tris[i] + a = _cross(_vsub(rv[triangle[1]], rv[triangle[0]]), _vsub(rv[triangle[2]], rv[triangle[0]])) + b = _cross(_vsub(pv[triangle[1]], pv[triangle[0]]), _vsub(pv[triangle[2]], pv[triangle[0]])) + normals.append(_dot(a, b)/(_norm(a)*_norm(b)) if _norm(a)*_norm(b) > 0 else -1.0); normal_face_ids.append(i//2) + tri_ids = [i//2 for i in range(len(tris))] + intersections = frozen._intersection_report(pv, tris, tri_ids, owners) + lower_intersection_count = len(intersections.get("lower_hit_pairs", [])) + report["checks"].update(triangle_area_ratios=bool(area_ratios) and min(area_ratios) >= area_min and max(area_ratios) <= area_max, + lower_edge_ratios=bool(edge_ratios) and min(edge_ratios) >= edge_min and max(edge_ratios) <= edge_max, + lower_nonadjacent_self_intersection=bool(intersections.get("available")) + and bool(intersections.get("pair_policy_complete")) + and bool(intersections.get("collision_inventory_complete")) + and lower_intersection_count <= intersection_max, + gross_normal_flip=(max(abs(float(angles.get(s, 0.0))) for s in ("left", "right")) > 30.0 or min(normals) > normal_min)) + report["metrics"].update(area_ratio_min=min(area_ratios), area_ratio_max=max(area_ratios), lower_edge_ratio_min=min(edge_ratios), + lower_edge_ratio_max=max(edge_ratios), normal_dot_min=min(normals), normal_dot_max=max(normals), + worst_normal_faces=[normal_face_ids[i] for i in sorted(range(len(normals)), key=normals.__getitem__)[:_EXAMPLE_CAP]], + lower_intersection_count=lower_intersection_count, + lower_intersection_examples=intersections.get("lower_hit_pairs", [])[:_EXAMPLE_CAP]) + + crest = _crest_y(case, reference_landmarks, protocol) + crest_ids = [i for i, p in enumerate(rv) if float(p[1]) >= crest] + crest_error = max((_distance(rv[i], pv[i]) for i in crest_ids), default=math.inf) + pelvis_ids = [i for i, row in enumerate(weights) if row[0] == 1.0 and row[1] == 0.0 and row[2] == 0.0] + pelvis_error = max((_distance(rv[i], pv[i]) for i in pelvis_ids), default=math.inf) + report["checks"].update(crest_ceiling=bool(crest_ids) and crest_error <= crest_tolerance*L, + strict_pelvis_stationary=bool(pelvis_ids) and pelvis_error <= pelvis_tolerance*L) + report["metrics"].update(crest_vertex_count=len(crest_ids), crest_max_displacement=crest_error, + strict_pelvis_vertex_count=len(pelvis_ids), strict_pelvis_max_displacement=pelvis_error) + + port_rows = {} + loops = rest_mesh.get("loops", {}) + for side in ("left", "right"): + ids = loops.get(f"port.{side}_thigh", []) + target = [_mp(skins_pose[f"{side}_hip"], rv[i]) for i in ids] + errors = [_distance(pv[i], q) for i, q in zip(ids, target)] + rc = tuple(sum(rv[i][a] for i in ids)/len(ids) for a in range(3)); pc = tuple(sum(pv[i][a] for i in ids)/len(ids) for a in range(3)) + ec = _mp(skins_pose[f"{side}_hip"], rc) + extent_error = max((abs(_distance(pc, pv[i])-_distance(ec, q)) for i, q in zip(ids, target)), default=math.inf) + def area_vector(points): + return _vmul(tuple(sum(_cross(points[i], points[(i+1) % len(points)])[a] for i in range(len(points))) for a in range(3)), .5) + actual_area, target_area = area_vector([pv[i] for i in ids]), area_vector(target) + area_vector_error = _distance(actual_area, target_area) + port_rows[side] = {"count": len(ids), "max_vertex_error": max(errors, default=math.inf), "centroid_error": _distance(pc, ec) if ids else math.inf, + "extent_error": extent_error, "area_vector_error": area_vector_error} + report["checks"]["distal_ports_rigid"] = all(r["count"] and max(r["max_vertex_error"], r["centroid_error"], r["extent_error"]) <= port_tolerance*L + and r["area_vector_error"] <= port_tolerance*L*L for r in port_rows.values()) + report["metrics"]["ports"] = port_rows + + landmark_errors = [] + for side in ("left", "right"): + pose_matrix = exported_pose[f"{side}_hip"] if exported_pose is not None else expected_pose[f"{side}_hip"] + skin = _mm(pose_matrix, joints[f"{side}_hip"][1]) + for name in ("J", "T", "K"): + p = _landmark(reference_landmarks, side, name) + expected_p = _mp(skins_pose[f"{side}_hip"], p) + landmark_errors.append(_distance(_mp(skin, p), expected_p)) + landmark_errors.append(_distance(_mp(skin, _landmark(reference_landmarks, side, "J")), _landmark(reference_landmarks, side, "J"))) + report["checks"]["exported_landmark_motion"] = max(landmark_errors) <= frame_tolerance*L + report["metrics"]["exported_landmark_max_error"] = max(landmark_errors) + provenance = posed_mesh.get("provenance", {}) + report["checks"]["rest_provenance_preserved"] = (isinstance(provenance, Mapping) and provenance.get("base_stencils") == "REST" + and not bool(metadata.get("posed_cage_evaluation", True))) + except Exception as exc: + fail("input_or_check_failure", exc) + report["pass"] = not report["errors"] and bool(report["checks"]) and all(report["checks"].values()) + return report diff --git a/experiments/pelvis-hip-articulation/protocol.json b/experiments/pelvis-hip-articulation/protocol.json new file mode 100644 index 0000000..3d8d9bd --- /dev/null +++ b/experiments/pelvis-hip-articulation/protocol.json @@ -0,0 +1,46 @@ +{ + "id": "pelvis-hip-articulation-harmonic-lbs-001", + "declared_at_utc": "2026-09-05T11:52:36Z", + "budget": {"binding_methods": 1, "binding_refinements": 0, "rest_shape_changes": 0, "topology_changes": 0}, + "calibration_snapshot": "/home/ben/.cache/creature-kernel/pelvis-source-calibration-set-1", + "calibration_artifact_manifest_sha256": "f0152de5b6b82a60c35599b0b82af746704d1917446d8fceb88b2ca016275871", + "dependency_snapshot": "/home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot", + "construction_sha256": "7fd457e2206165eb5e404ce81732f4157234a2e13a64008d96ae75d6abcf5cdb", + "cases": ["calibrated_ordinary_human", "calibrated_upright_anthropomorphic"], + "rest_case_directories": ["case-05-calibrated_ordinary_human", "case-06-calibrated_upright_anthropomorphic"], + "method": "Uniform L0 graph harmonic weights transferred through stored L2 subdivision stencils; three-joint linear blend skinning of the preserved evaluated rest surface.", + "anchors": {"pelvis": "Every L0 vertex outside both socket/ringA/ringB/exit sets", "left_leg": "left ringB and exit", "right_leg": "right ringB and exit", "unknown": "Both socket and ringA sets; solve graph harmonic weights without painting"}, + "joint_frame": "Origin J; Y=normalize(J-K); X=normalize(global+X projected perpendicular to Y); Z=X cross Y. Columns X,Y,Z form rest rotation. Positive flexion uses local RotX(-angle). Pose=Mrest*RotX(-angle); skin=Pose*inverse(Mrest). Pelvis root is identity.", + "J_role": "The two calibration joint reference points become independent experimental hip pivots for this probe only. They control inverse-bind and pose transforms, not resting skin construction; anatomical uncertainty remains.", + "landmark_roles": "T and K have distinct fixed joint-local rest positions, carried by joint pose. Estimated crest/ASIS/PSIS/pubis markers remain pelvis-frame diagnostic points; trochanter is carried with its thigh for illustration, not an implemented bone or anatomical validation.", + "poses": [ + {"id": "rest", "left": 0.0, "right": 0.0}, + {"id": "left_flex_15", "left": 15.0, "right": 0.0}, + {"id": "left_flex_30", "left": 30.0, "right": 0.0}, + {"id": "right_flex_15", "left": 0.0, "right": 15.0}, + {"id": "both_flex_20", "left": 20.0, "right": 20.0} + ], + "pivot_counterfactual": {"id": "diagnostic_left_J_up_10mm", "J_left_delta": [0.0, 0.01, 0.0], "pose": {"left": 15.0, "right": 0.0}, "cases": "both", "role": "One causality diagnostic per body, not input tuning or a candidate improvement. Rest vertices remain unchanged. Export the response; do not adopt shifted J."}, + "views": {"bounds": [[-0.32, -0.27, -0.22], [0.32, 0.34, 0.22]], "angles": ["front", "side", "rear-three-quarter"], "surface_and_overlay_separate": true, "underside": "rest and left_flex_30", "motion": "Optional straightforward animation using the declared poses only; no additional pose-search campaign"}, + "normalization": "L is mean left/right J-to-K rest distance for this body; points are metres. No per-case metric thresholds.", + "checks": { + "identity_error_over_L_max": 1e-12, + "weight_partition_tolerance": 1e-12, + "frame_and_transform_tolerance": 1e-10, + "exported_LBS_error_over_L_max": 1e-10, + "rigid_port_error_over_L_max": 1e-9, + "pelvis_only_weighted_error_over_L_max": 1e-10, + "above_crest_skin_displacement_over_L_max": 0.01, + "lower_triangle_area_ratio": [0.5, 2.0], + "lower_edge_length_ratio": [0.65, 1.5], + "lower_rest_posed_triangle_normal_dot_min": 0.0, + "lower_nonadjacent_intersections_max": 0, + "pivot_counterfactual_response_over_L_min": 1e-4, + "topology": "Identical quad arrays and welded index connectivity; finite vertices. No remeshing, welded repairs, caps or disconnected surfaces.", + "extent": "Every represented distal thigh-port vertex follows its joint rigidly, preserving port shape and its rest relationship to T/K, including the stationary leg. K beyond the open surface is not a missing-skin failure.", + "closed_volume": "Not applicable: open neck/arm/thigh boundaries. Do not infer global volume preservation from local area or port checks." + }, + "visual_rejection": ["Obvious separation or sharp attachment seam", "Gross collapse, new pinching or interpenetration in the transition", "Unexpected upper-pelvis drag or stationary-leg deformation beyond the intended shared transition", "Shortening or distortion of the represented distal thigh ends", "A presentation that hides defects or shows overlays in place of the actual posed surface"], + "interpretation": "Small-angle baseline binding test, not complete anatomy, full-body rig or production architecture acceptance. An LBS/harmonic-weight failure does not by itself reject the fixed surface or topology. Passing mechanical checks is necessary, not sufficient for the visual checkpoint.", + "stop": "At the first meaningful directly inspected regional visual checkpoint, return to Ben via Overseer. If the one baseline fails, close it honestly and send discriminating evidence plus a bounded next-step recommendation to Overseer before any method/shape/topology follow-up. No open-ended tuning. No publication, push, merge, body expansion, general rig or physics work." +} diff --git a/experiments/pelvis-hip-articulation/runner.py b/experiments/pelvis-hip-articulation/runner.py new file mode 100644 index 0000000..63705d8 --- /dev/null +++ b/experiments/pelvis-hip-articulation/runner.py @@ -0,0 +1,618 @@ +"""Bounded runner for the local pelvis/hip articulation probe.""" + +from __future__ import annotations + +import sys +sys.dont_write_bytecode = True + +import argparse +import copy +from datetime import datetime, timezone +import hashlib +import importlib.util +import json +import math +import os +from pathlib import Path +from typing import Any, Mapping + +os.environ["PYTHONDONTWRITEBYTECODE"] = "1" + + +HERE = Path(__file__).resolve().parent +SNAPSHOT_SOURCE = Path("source/experiments/pelvis-hip-articulation") +FROZEN_RENDERER = Path( + "/home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot" + "/source/experiments/pelvis-thigh-transition/render.py" +) +CAPTURE_FILES = ( + "binding.py", + "capture.py", + "checks.py", + "runner.py", + "README.md", + "protocol.json", + "tests/test_binding.py", + "tests/test_capture.py", + "tests/test_checks.py", + "tests/test_integration.py", + "tests/test_runner.py", +) +CASE_FILES = { + "calibrated_ordinary_human": ("case_05_rest_L0", "case_05_rest_L2"), + "calibrated_upright_anthropomorphic": ("case_06_rest_L0", "case_06_rest_L2"), +} +CASE_TITLES = { + "calibrated_ordinary_human": "human", + "calibrated_upright_anthropomorphic": "anthro", +} +POSE_TITLES = { + "rest": "rest", + "left_flex_15": "L15", + "left_flex_30": "L30", + "right_flex_15": "R15", + "both_flex_20": "both20", +} +UNDERSIDE_POSES = {"rest", "left_flex_30"} + + +class RunnerError(ValueError): + """Raised when the bounded runner contract cannot be satisfied.""" + + +def _fail(message: str) -> None: + raise RunnerError(message) + + +def _canonical(path: str | os.PathLike[str], label: str) -> Path: + value = Path(path) + if not value.is_absolute() or os.path.normpath(str(value)) != str(value): + _fail(f"{label} must be an absolute canonical path") + return value + + +def _regular(path: Path, label: str) -> None: + if path.is_symlink() or not path.is_file(): + _fail(f"{label} must be a regular file: {path}") + + +def _directory(path: Path, label: str) -> None: + if path.is_symlink() or not path.is_dir(): + _fail(f"{label} must be a regular directory: {path}") + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def _json_bytes(value: Any) -> bytes: + try: + return (json.dumps(value, sort_keys=True, indent=2, ensure_ascii=True, + allow_nan=False) + "\n").encode("utf-8") + except (TypeError, ValueError) as exc: + raise RunnerError(f"value is not finite JSON: {exc}") from exc + + +def _read_json(path: Path) -> tuple[Any, bytes]: + _regular(path, "JSON input") + raw = path.read_bytes() + try: + value = json.loads( + raw.decode("utf-8"), + parse_constant=lambda token: (_ for _ in ()).throw(ValueError(token)), + ) + except (UnicodeDecodeError, json.JSONDecodeError, ValueError) as exc: + _fail(f"invalid finite UTF-8 JSON: {path}: {exc}") + return value, raw + + +def _write_json(path: Path, value: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(_json_bytes(value)) + + +def _load_module(name: str, path: Path) -> Any: + """Load a file by path and register it before executing its body.""" + _regular(path, "dynamic module") + spec = importlib.util.spec_from_file_location(name, path) + if spec is None or spec.loader is None: + _fail(f"unable to load dynamic module: {path}") + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + try: + spec.loader.exec_module(module) + except Exception: + if sys.modules.get(name) is module: + sys.modules.pop(name, None) + raise + return module + + +def _snapshot_capture(snapshot: Path) -> Any: + return _load_module( + "ck_pelvis_hip_snapshot_capture", + snapshot / SNAPSHOT_SOURCE / "capture.py", + ) + + +def _require_snapshot(snapshot: str | os.PathLike[str]) -> Path: + path = _canonical(snapshot, "snapshot") + _directory(path, "snapshot") + return path + + +def _require_absent_output(output: str | os.PathLike[str], snapshot: Path) -> Path: + path = _canonical(output, "output") + if path.exists() or path.is_symlink(): + _fail(f"output must be absent: {path}") + if path.parent != snapshot.parent: + _fail("output must be a sibling of snapshot") + if path.parent.is_symlink() or not path.parent.is_dir(): + _fail("output parent must be an existing regular directory") + return path + + +def _capture_prepare(snapshot: Path) -> dict[str, Any]: + capture = _load_module("ck_pelvis_hip_worktree_capture", HERE / "capture.py") + return dict(capture.prepare(snapshot, CAPTURE_FILES)) + + +def prepare(snapshot: str | os.PathLike[str]) -> dict[str, Any]: + """Capture the exact source/input set into an absent snapshot.""" + path = _canonical(snapshot, "snapshot") + if path.exists() or path.is_symlink(): + _fail(f"snapshot must be absent: {path}") + return _capture_prepare(path) + + +def verify(snapshot: str | os.PathLike[str]) -> dict[str, Any]: + """Verify a captured snapshot with its captured helper.""" + path = _require_snapshot(snapshot) + capture = _snapshot_capture(path) + return dict(capture.verify(path)) + + +def _manifest_mapping(manifest: Mapping[str, Any]) -> dict[str, Path]: + inputs = manifest.get("inputs") + mappings = inputs.get("filename_mappings") if isinstance(inputs, Mapping) else None + if not isinstance(mappings, list): + _fail("capture manifest has no input filename mappings") + result: dict[str, Path] = {} + for row in mappings: + if not isinstance(row, Mapping) or not isinstance(row.get("name"), str): + _fail("capture input filename mapping is malformed") + relative = Path(str(row.get("snapshot_path", ""))) + if relative.is_absolute() or ".." in relative.parts: + _fail("capture input mapping escapes the snapshot") + if row["name"] in result: + _fail(f"duplicate capture input mapping: {row['name']}") + result[row["name"]] = relative + return result + + +def _mapped_input(snapshot: Path, mappings: Mapping[str, Path], name: str) -> Path: + if name not in mappings: + _fail(f"capture input mapping is missing: {name}") + path = snapshot / mappings[name] + try: + path.relative_to(snapshot) + except ValueError: + _fail(f"capture input mapping escapes the snapshot: {name}") + return path + + +def _load_run_inputs(snapshot: Path, manifest: Mapping[str, Any]) -> tuple[ + dict[str, Any], dict[str, Any], dict[str, tuple[dict[str, Any], dict[str, Any], dict[str, Any]]]]: + mappings = _manifest_mapping(manifest) + calibration_inputs, _ = _read_json( + _mapped_input(snapshot, mappings, "calibration_inputs")) + calibration_protocol, _ = _read_json( + _mapped_input(snapshot, mappings, "calibration_protocol")) + protocol, _ = _read_json(snapshot / SNAPSHOT_SOURCE / "protocol.json") + if not isinstance(protocol, Mapping) or not isinstance(protocol.get("poses"), list): + _fail("articulation protocol poses are malformed") + if len(protocol["poses"]) != 5: + _fail("articulation protocol must declare exactly five poses") + if not isinstance(calibration_inputs, Mapping) or not isinstance(calibration_protocol, Mapping): + _fail("calibration inputs or protocol is malformed") + input_cases = {row.get("id"): row for row in calibration_inputs.get("cases", []) + if isinstance(row, Mapping)} + protocol_cases = {row.get("id"): row for row in calibration_protocol.get("cases", []) + if isinstance(row, Mapping)} + result: dict[str, tuple[dict[str, Any], dict[str, Any], dict[str, Any]]] = {} + for case_id, (l0_name, l2_name) in CASE_FILES.items(): + case = input_cases.get(case_id) + calibration_case = protocol_cases.get(case_id) + if not isinstance(case, Mapping) or not isinstance(calibration_case, Mapping): + _fail(f"calibration case is missing: {case_id}") + refs = calibration_case.get("reference_landmarks") + if not isinstance(refs, Mapping): + _fail(f"reference landmarks are missing: {case_id}") + base, _ = _read_json(_mapped_input(snapshot, mappings, l0_name)) + rest, _ = _read_json(_mapped_input(snapshot, mappings, l2_name)) + if not isinstance(base, Mapping) or not isinstance(rest, Mapping): + _fail(f"rest mesh input is malformed: {case_id}") + result[case_id] = (dict(base), dict(rest), { + "case": copy.deepcopy(dict(case)), + "reference_landmarks": copy.deepcopy(dict(refs)), + }) + return dict(protocol), dict(calibration_protocol), result + + +def _identity() -> list[list[float]]: + return [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] + + +def _pose_export(mesh: Mapping[str, Any], points: Mapping[str, Any], + angles: Mapping[str, float]) -> dict[str, Any]: + exported = copy.deepcopy(dict(mesh)) + metadata = exported.get("metadata") + if not isinstance(metadata, dict): + metadata = {} + metadata["joints"] = { + "pelvis": {"pose_matrix": _identity()}, + "left_hip": {"pose_matrix": copy.deepcopy(points["left"]["posed_matrix"])}, + "right_hip": {"pose_matrix": copy.deepcopy(points["right"]["posed_matrix"])}, + } + metadata["pose_angles_degrees"] = { + "left": float(angles["left"]), "right": float(angles["right"]) + } + exported["metadata"] = metadata + return exported + + +def _matrix_point(matrix: Any, point: Any) -> list[float]: + return [sum(float(matrix[row][column]) * (float(point[column]) if column < 3 else 1.0) + for column in range(4)) for row in range(3)] + + +def _overlays(points: Mapping[str, Any], refs: Mapping[str, Any]) -> list[dict[str, Any]]: + overlays: list[dict[str, Any]] = [] + colours = {"left": [211, 77, 77], "right": [55, 112, 213]} + for side in ("left", "right"): + row = points[side]["posed_points"] + colour = colours[side] + overlays.extend([ + {"start": row["J"], "end": row["T"], "color": colour, + "label": f"diagnostic {side} J-T frame"}, + {"start": row["J"], "end": row["K"], "color": colour, + "label": f"diagnostic {side} J-K frame"}, + ]) + for name in ("crest", "asis", "psis"): + key = f"{name}_{side}" + if key in refs: + overlays.append({"start": refs[key], "end": refs[key], "color": colour, + "label": f"diagnostic uncertain {key}"}) + if "trochanter_" + side in refs: + carried = _matrix_point(points[side]["skin_matrix"], refs["trochanter_" + side]) + overlays.append({"start": carried, "end": carried, "color": colour, + "label": f"diagnostic uncertain trochanter_{side}"}) + if "pubic_symphysis" in refs: + point = refs["pubic_symphysis"] + overlays.append({"start": point, "end": point, "color": [145, 85, 170], + "label": "diagnostic uncertain pubic_symphysis"}) + return overlays + + +def _joint_evidence(points: Mapping[str, Any], angles: Mapping[str, float]) -> dict[str, Any]: + return {"schema": "pelvis-hip-articulation-joints-v1", + "angles_degrees": {"left": float(angles["left"]), + "right": float(angles["right"])}, + "joints": {"pelvis": {"pose_matrix": _identity()}, + "left": copy.deepcopy(points["left"]), + "right": copy.deepcopy(points["right"])} } + + +def _exception(phase: str, exc: BaseException) -> dict[str, str]: + return {"phase": phase, "type": type(exc).__name__, "message": str(exc)} + + +def _relative(path: Path, root: Path) -> str: + return path.relative_to(root).as_posix() + + +def _run_case(case_id: str, base: Mapping[str, Any], rest: Mapping[str, Any], + case: Mapping[str, Any], refs: Mapping[str, Any], protocol: Mapping[str, Any], + output: Path, binding_module: Any, checks_module: Any, + render_module: Any) -> dict[str, Any]: + case_dir = output / "cases" / case_id + case_dir.mkdir(parents=True, exist_ok=True) + _write_json(case_dir / "case.json", case) + _write_json(case_dir / "landmarks.json", refs) + original_vertices = copy.deepcopy(rest.get("vertices")) + summary: dict[str, Any] = {"id": case_id, "directory": _relative(case_dir, output), + "poses": [], "errors": []} + binding: dict[str, Any] | None = None + reloaded_binding: Mapping[str, Any] | None = None + binding_method_pass = False + pose_records: dict[str, dict[str, Any]] = {} + try: + binding = binding_module.bind(base, rest, case, refs) + _write_json(case_dir / "binding.json", binding) + reloaded_binding, _ = _read_json(case_dir / "binding.json") + if not isinstance(reloaded_binding, Mapping): + raise RunnerError("reloaded binding is not a mapping") + summary["binding"] = _relative(case_dir / "binding.json", output) + except Exception as exc: + error = _exception("bind", exc) + summary["errors"].append(error) + _write_json(case_dir / "error-bind.json", error) + + if binding is not None: + try: + binding_report = checks_module.check_binding(base, rest, reloaded_binding, protocol) + if not isinstance(binding_report, Mapping): + raise RunnerError("binding checker returned a non-mapping report") + _write_json(case_dir / "binding-checks.json", binding_report) + binding_method_pass = bool(binding_report.get("pass")) + summary["binding_checks"] = _relative(case_dir / "binding-checks.json", output) + except Exception as exc: + binding_report = {"schema": "pelvis-hip-articulation-binding-checks-v1", + "pass": False, "metrics": {}, + "errors": [_exception("binding-check", exc)]} + _write_json(case_dir / "binding-checks.json", binding_report) + summary["binding_checks"] = _relative(case_dir / "binding-checks.json", output) + summary["errors"].append(_exception("binding-check", exc)) + summary["binding_method_pass"] = binding_method_pass + for pose_decl in protocol["poses"]: + pose_id = pose_decl.get("id") if isinstance(pose_decl, Mapping) else None + angles = {"left": pose_decl.get("left"), "right": pose_decl.get("right")} \ + if isinstance(pose_decl, Mapping) else {} + pose_summary: dict[str, Any] = {"id": pose_id, "angles_degrees": angles, + "errors": []} + pose_dir = case_dir / "poses" / str(pose_id) + pose_dir.mkdir(parents=True, exist_ok=True) + try: + posed = binding_module.pose(rest, binding, angles) + points = binding_module.joint_points(binding, angles) + posed = _pose_export(posed, points, angles) + _write_json(pose_dir / "mesh.json", posed) + _write_json(pose_dir / "joints.json", _joint_evidence(points, angles)) + reloaded_mesh, _ = _read_json(pose_dir / "mesh.json") + reloaded_joints, _ = _read_json(pose_dir / "joints.json") + if not isinstance(reloaded_mesh, Mapping) or not isinstance(reloaded_joints, Mapping): + raise RunnerError("reloaded pose evidence is malformed") + check_report = checks_module.check_pose( + rest, reloaded_mesh, reloaded_binding, angles, case, refs, protocol) + _write_json(pose_dir / "checks.json", check_report) + technical = ("TECHNICAL PASS" + if binding_method_pass and check_report.get("pass") + else "TECHNICAL REJECTED") + render_record = None + try: + render_record = render_module.render_views( + reloaded_mesh["vertices"], reloaded_mesh["quads"], pose_dir / "surface.png", + f"{CASE_TITLES[case_id]} / {POSE_TITLES.get(str(pose_id), str(pose_id))}", + technical, protocol["views"]["bounds"], + _overlays(reloaded_joints["joints"], refs), + underside=str(pose_id) in UNDERSIDE_POSES, allow_crop=True) + _write_json(pose_dir / "render.json", render_record) + except Exception as exc: + error = _exception("render", exc) + pose_summary["errors"].append(error) + summary["errors"].append({"pose": pose_id, **error}) + _write_json(pose_dir / "error-render.json", error) + pose_summary.update({ + "directory": _relative(pose_dir, output), + "mesh": _relative(pose_dir / "mesh.json", output), + "joints": _relative(pose_dir / "joints.json", output), + "checks": _relative(pose_dir / "checks.json", output), + "technical_status": technical, + "visual_status": "pending", + }) + if render_record is not None: + pose_summary["render"] = { + key: _relative(Path(value), output) if value else None + for key, value in render_record.items() + if key.endswith("path") + } + pose_records[str(pose_id)] = {"mesh": reloaded_mesh, + "checks": check_report, + "binding": reloaded_binding} + except Exception as exc: + error = _exception("pose", exc) + pose_summary["errors"].append(error) + summary["errors"].append({"pose": pose_id, **error}) + _write_json(pose_dir / "error-pose.json", error) + summary["poses"].append(pose_summary) + + try: + nominal = pose_records.get("left_flex_15") + if nominal is None: + raise RunnerError("nominal left_flex_15 pose was not captured") + counterfactual = protocol.get("pivot_counterfactual") + if not isinstance(counterfactual, Mapping): + raise RunnerError("protocol pivot_counterfactual is malformed") + delta = counterfactual.get("J_left_delta") + counter_angles = counterfactual.get("pose") + if not isinstance(delta, list) or len(delta) != 3 or not isinstance(counter_angles, Mapping): + raise RunnerError("protocol pivot counterfactual delta or pose is malformed") + if set(counter_angles) != {"left", "right"}: + raise RunnerError("protocol pivot counterfactual pose must contain left and right") + shifted_refs = copy.deepcopy(dict(refs)) + shifted_refs["joint_left"] = [float(x) for x in shifted_refs["joint_left"]] + shifted_refs["joint_left"] = [point + float(offset) + for point, offset in zip(shifted_refs["joint_left"], delta)] + counter = binding_module.bind(base, rest, case, shifted_refs) + counter_pose = binding_module.pose(rest, counter, counter_angles) + counter_points = binding_module.joint_points(counter, counter_angles) + counter_pose = _pose_export(counter_pose, counter_points, counter_angles) + counter_dir = case_dir / "counterfactual" + _write_json(counter_dir / "binding.json", counter) + _write_json(counter_dir / "mesh.json", counter_pose) + _write_json(counter_dir / "joints.json", _joint_evidence(counter_points, counter_angles)) + reloaded_counter_binding, _ = _read_json(counter_dir / "binding.json") + reloaded_counter_mesh, _ = _read_json(counter_dir / "mesh.json") + reloaded_counter_joints, _ = _read_json(counter_dir / "joints.json") + if not all(isinstance(item, Mapping) for item in + (reloaded_counter_binding, reloaded_counter_mesh, reloaded_counter_joints)): + raise RunnerError("reloaded counterfactual evidence is malformed") + counter_checks = checks_module.check_pose( + rest, reloaded_counter_mesh, reloaded_counter_binding, counter_angles, + case, shifted_refs, protocol) + _write_json(counter_dir / "checks.json", counter_checks) + nominal_vertices = nominal["mesh"]["vertices"] + counter_vertices = reloaded_counter_mesh["vertices"] + response = max(math.dist(a, b) for a, b in zip(nominal_vertices, counter_vertices)) + scale = float(nominal["checks"].get("metrics", {}).get("scale", 0.0)) + threshold = float(protocol["checks"]["pivot_counterfactual_response_over_L_min"]) + response_over_l = response / scale if scale > 0.0 else math.inf + comparison = { + "schema": "pelvis-hip-articulation-counterfactual-v1", + "diagnostic_only": True, + "nominal_pose_id": "left_flex_15", + "counterfactual_pose": copy.deepcopy(dict(counter_angles)), + "J_left_delta": copy.deepcopy(delta), + "max_vertex_delta": response, + "L": scale, + "response_over_L": response_over_l, + "threshold_over_L_min": threshold, + "threshold_observed": response_over_l >= threshold, + "weights_unchanged": reloaded_counter_binding["evaluated_weights"] == reloaded_binding["evaluated_weights"], + } + _write_json(counter_dir / "comparison.json", comparison) + summary["counterfactual"] = { + "directory": _relative(counter_dir, output), + "binding": _relative(counter_dir / "binding.json", output), + "mesh": _relative(counter_dir / "mesh.json", output), + "joints": _relative(counter_dir / "joints.json", output), + "checks": _relative(counter_dir / "checks.json", output), + "comparison": _relative(counter_dir / "comparison.json", output), + "diagnostic_only": True, + "threshold_observed": comparison["threshold_observed"], + } + except Exception as exc: + error = _exception("counterfactual", exc) + summary["errors"].append(error) + _write_json(case_dir / "error-counterfactual.json", error) + + unchanged = rest.get("vertices") == original_vertices + integrity = {"schema": "pelvis-hip-articulation-rest-integrity-v1", + "vertices_unchanged": unchanged, + "vertex_count": len(original_vertices) if isinstance(original_vertices, list) else None} + _write_json(case_dir / "rest-integrity.json", integrity) + summary["rest_vertices_unchanged"] = unchanged + if not unchanged: + summary["errors"].append({"phase": "rest-integrity", "message": "rest vertices changed"}) + return summary + + +def _write_artifact_manifest(output: Path, capture: Any) -> dict[str, Any]: + inventory = capture.artifact_manifest(output) + record = {"schema": "creature-kernel.pelvis-hip-articulation-run-artifacts.v1", + "self": {"path": "artifact-sha-manifest.json", "sha256": "excluded"}, + "files": inventory["files"]} + _write_json(output / "artifact-sha-manifest.json", record) + return record + + +def run(snapshot: str | os.PathLike[str], output: str | os.PathLike[str]) -> dict[str, Any]: + """Execute the fixed binding/pose/render budget from a captured snapshot.""" + snapshot_path = _require_snapshot(snapshot) + output_path = _require_absent_output(output, snapshot_path) + expected_source = (snapshot_path / SNAPSHOT_SOURCE).resolve() + if Path.cwd().resolve() != expected_source or HERE != expected_source: + _fail("run must execute from snapshot/source/experiments/pelvis-hip-articulation") + + capture = _snapshot_capture(snapshot_path) + before = dict(capture.verify(snapshot_path)) + protocol, calibration_protocol, cases = _load_run_inputs(snapshot_path, before) + del calibration_protocol + binding_module = _load_module("ck_pelvis_hip_snapshot_binding", expected_source / "binding.py") + checks_module = _load_module("ck_pelvis_hip_snapshot_checks", expected_source / "checks.py") + render_module = _load_module("ck_pelvis_hip_frozen_render", FROZEN_RENDERER) + output_path.mkdir() + summaries = [] + run_errors = [] + for case_id in CASE_FILES: + base, rest, evidence = cases[case_id] + try: + summaries.append(_run_case( + case_id, base, rest, evidence["case"], evidence["reference_landmarks"], + protocol, output_path, binding_module, checks_module, render_module)) + except Exception as exc: + error = _exception("case", exc) + run_errors.append({"case": case_id, **error}) + case_dir = output_path / "cases" / case_id + case_dir.mkdir(parents=True, exist_ok=True) + _write_json(case_dir / "error-case.json", error) + + after = dict(capture.verify(snapshot_path)) + if before.get("frozen_dependency") != after.get("frozen_dependency"): + run_errors.append({"phase": "capture-verify", "message": "frozen dependency drifted"}) + for summary in summaries: + run_errors.extend({"case": summary["id"], **error} for error in summary["errors"]) + report = { + "schema": "pelvis-hip-articulation-run-v1", + "status": "completed" if not run_errors else "completed_with_errors", + "geometry_executed": True, + "snapshot_path": str(snapshot_path), + "output_path": str(output_path), + "protocol_id": protocol.get("id"), + "poses": [pose.get("id") for pose in protocol["poses"]], + "cases": summaries, + "errors": run_errors, + "invocation": { + "argv": list(sys.argv), + "cwd": str(Path.cwd()), + "python": str(sys.executable), + "environment": { + "PYTHONDONTWRITEBYTECODE": os.environ.get("PYTHONDONTWRITEBYTECODE"), + "CK_CURRENT_FORM_SURFACE_PYTHON": os.environ.get("CK_CURRENT_FORM_SURFACE_PYTHON"), + }, + }, + "provenance": { + "capture_manifest_sha256": _sha256(snapshot_path / "manifest.json"), + "capture_status_before": before.get("status"), + "capture_status_after": after.get("status"), + "frozen_dependency": before.get("frozen_dependency"), + "renderer": {"path": str(FROZEN_RENDERER), "sha256": _sha256(FROZEN_RENDERER)}, + "captured_input_mappings": before.get("inputs", {}).get("filename_mappings", []), + }, + "no_drift": { + "capture_verify_before_after": True, + "rest_vertices_unchanged": all(item.get("rest_vertices_unchanged", False) for item in summaries), + }, + "artifact_manifest": "artifact-sha-manifest.json", + "created_at_utc": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"), + } + _write_json(output_path / "run-report.json", report) + _write_artifact_manifest(output_path, capture) + return report + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + prepare_parser = commands.add_parser("prepare") + prepare_parser.add_argument("--snapshot", required=True) + run_parser = commands.add_parser("run") + run_parser.add_argument("--snapshot", required=True) + run_parser.add_argument("--output", required=True) + verify_parser = commands.add_parser("verify") + verify_parser.add_argument("--snapshot", required=True) + args = parser.parse_args(argv) + try: + if args.command == "prepare": + result = prepare(args.snapshot) + print(json.dumps({"status": result.get("status"), "snapshot": args.snapshot}, sort_keys=True)) + elif args.command == "run": + result = run(args.snapshot, args.output) + print(json.dumps({"status": result["status"], "output": args.output, + "errors": len(result["errors"])}, sort_keys=True)) + else: + result = verify(args.snapshot) + print(json.dumps({"status": result.get("status"), "snapshot": args.snapshot}, sort_keys=True)) + except (RunnerError, Exception) as exc: + print(f"pelvis-hip-articulation runner error: {exc}", file=sys.stderr) + return 2 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/experiments/pelvis-hip-articulation/tests/test_binding.py b/experiments/pelvis-hip-articulation/tests/test_binding.py new file mode 100644 index 0000000..049f7c5 --- /dev/null +++ b/experiments/pelvis-hip-articulation/tests/test_binding.py @@ -0,0 +1,180 @@ +from __future__ import annotations + +import copy +import json +import sys +import unittest +from pathlib import Path + +import numpy as np + + +EXPERIMENT_DIR = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(EXPERIMENT_DIR)) +import binding # noqa: E402 + + +def _mesh_fixture() -> tuple[dict, dict, dict, dict]: + # Four quads make a connected boundary-edge graph. The two unknowns on + # each side have the hand-solvable system [[2,-1],[-1,3]]. + vertices = [ + [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], + [0.0, 1.0, 0.0], [4.0, 0.0, 0.0], [5.0, 0.0, 0.0], + [4.0, 1.0, 0.0], [4.0, 1.0, 0.0], [2.0, 0.0, 0.0], + ] + quads = [[0, 1, 2, 8], [0, 8, 3, 1], + [4, 5, 6, 8], [4, 8, 7, 5]] + transitions = { + "left": {"socket": [0], "ringA": [1], "ringB": [2], "exit": [3]}, + "right": {"socket": [4], "ringA": [5], "ringB": [6], "exit": [7]}, + } + base = { + "schema": "synthetic-l0", + "level": 0, + "vertices": vertices, + "quads": quads, + "base_stencils": [[[index, 1.0]] for index in range(len(vertices))], + "loops": {"port.left_thigh": [3], "port.right_thigh": [7]}, + "control_owners": [f"owner-{index}" for index in range(len(vertices))], + "face_owners": ["face-owner"] * len(quads), + "metadata": {"transition_indices": transitions}, + } + rest_vertices = copy.deepcopy(vertices) + [[0.75, 0.0, 0.0]] + rest = { + "schema": "synthetic-l2", + "level": 2, + "vertices": rest_vertices, + "quads": copy.deepcopy(quads), + "base_stencils": copy.deepcopy(base["base_stencils"]) + [[[0, 0.25], [1, 0.75]]], + "loops": {"port.left_thigh": [3], "port.right_thigh": [7]}, + "control_owners": [f"evaluated-owner-{index}" for index in range(len(rest_vertices))], + "face_owners": ["evaluated-face-owner"] * len(quads), + "metadata": {"transition_indices": copy.deepcopy(transitions)}, + } + components = {f"component_{index:02d}": float(index) for index in range(92)} + case = { + "id": "synthetic-independent-joints", + "components": components, + "attachments": { + "left": {"centre": [0.0, 1.0, 0.0], "knee": [0.0, -1.0, 0.0]}, + "right": {"centre": [11.0, 5.0, 0.0], "knee": [10.0, 4.0, 0.0]}, + }, + } + landmarks = {"joint_left": [0.0, 0.0, 0.0], + "joint_right": [10.0, 5.0, 0.0]} + return base, rest, case, landmarks + + +def _binding() -> tuple[dict, dict, dict, dict, dict]: + base, rest, case, landmarks = _mesh_fixture() + result = binding.bind(base, rest, case, landmarks) + return result, base, rest, case, landmarks + + +class BindingTests(unittest.TestCase): + def test_uniform_harmonic_weights_are_positive_and_partitioned(self) -> None: + result, _base, _rest, case, _landmarks = _binding() + weights = np.asarray(result["base_weights"]) + np.testing.assert_allclose(weights.sum(axis=1), 1.0, atol=1.0e-12) + self.assertTrue(np.all(weights >= 0.0)) + self.assertTrue(np.all(weights[:2, :2] > 0.0)) + np.testing.assert_allclose(weights[0], [0.6, 0.4, 0.0]) + np.testing.assert_allclose(weights[1], [0.2, 0.8, 0.0]) + np.testing.assert_allclose(weights[2], [0.0, 1.0, 0.0]) + np.testing.assert_allclose(weights[6], [0.0, 0.0, 1.0]) + self.assertEqual(len(result["evaluated_weights"]), 10) + self.assertEqual(len(case["components"]), 92) + + def test_stencil_propagation_and_full_strength_distal_ports(self) -> None: + result, _base, rest, _case, _landmarks = _binding() + evaluated = np.asarray(result["evaluated_weights"]) + base_weights = np.asarray(result["base_weights"]) + np.testing.assert_allclose(evaluated[9], + 0.25 * base_weights[0] + 0.75 * base_weights[1]) + self.assertEqual(result["metadata"]["l2_distal_port_loop_counts"], + {"port.left_thigh": 1, "port.right_thigh": 1}) + self.assertEqual(result["l0_anchor_indices"]["left"]["exit"], [3]) + self.assertEqual(rest["base_stencils"][9], [[0, 0.25], [1, 0.75]]) + + def test_json_safe_and_rest_metadata_are_explicit(self) -> None: + result, _base, rest, _case, _landmarks = _binding() + json.dumps(result) + posed = binding.pose(rest, result, {"left": 0.0, "right": 0.0}) + json.dumps(posed) + self.assertEqual(posed["provenance"]["base_stencils"], "REST") + self.assertFalse(posed["metadata"]["posed_cage_evaluation"]) + self.assertEqual(posed["quads"], rest["quads"]) + self.assertEqual(posed["loops"], rest["loops"]) + self.assertEqual(posed["control_owners"], rest["control_owners"]) + self.assertEqual(posed["face_owners"], rest["face_owners"]) + self.assertEqual(posed["base_stencils"], rest["base_stencils"]) + + def test_hand_calculable_positive_90_degree_pivot_transform(self) -> None: + result, _base, rest, _case, _landmarks = _binding() + points = binding.joint_points(result, {"left": 90.0, "right": 0.0}) + left = points["left"] + np.testing.assert_allclose(left["posed_J"], left["J"], atol=1.0e-12) + np.testing.assert_allclose(left["T"], [0.0, 0.0, -1.0], atol=1.0e-12) + np.testing.assert_allclose(left["K"], [0.0, 0.0, 1.0], atol=1.0e-12) + np.testing.assert_allclose(left["posed_T"], [0.0, 0.0, -1.0], atol=1.0e-12) + np.testing.assert_allclose(left["posed_K"], [0.0, 0.0, 1.0], atol=1.0e-12) + np.testing.assert_allclose(left["skin_matrix"], + [[1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0]], atol=1.0e-12) + posed = binding.pose(rest, result, {"left": 90.0, "right": 0.0}) + np.testing.assert_allclose(posed["vertices"][3], [0.0, 0.0, -1.0], atol=1.0e-12) + + def test_independent_joints_change_frames_not_topology_weights_or_rest(self) -> None: + result, base, rest, case, landmarks = _binding() + changed = copy.deepcopy(landmarks) + changed["joint_left"] = [2.0, 3.0, 4.0] + changed_result = binding.bind(base, rest, case, changed) + self.assertEqual(changed_result["base_weights"], result["base_weights"]) + self.assertEqual(changed_result["evaluated_weights"], result["evaluated_weights"]) + self.assertNotEqual(changed_result["rest_frames"]["left"]["rest_matrix"], + result["rest_frames"]["left"]["rest_matrix"]) + self.assertEqual(rest["vertices"], _mesh_fixture()[1]["vertices"]) + posed = binding.pose(rest, changed_result, {"left": 0.0, "right": 0.0}) + self.assertEqual(posed["vertices"], rest["vertices"]) + + def test_zero_angle_pose_is_identity(self) -> None: + result, _base, rest, _case, _landmarks = _binding() + posed = binding.pose(rest, result, {"left": 0, "right": 0}) + self.assertEqual(posed["vertices"], rest["vertices"]) + points = binding.joint_points(result, {"left": 0, "right": 0}) + for side in ("left", "right"): + np.testing.assert_array_equal(points[side]["rest_matrix"], + points[side]["posed_matrix"]) + np.testing.assert_array_equal(points[side]["skin_matrix"], np.eye(4)) + + def test_wrong_indices_and_disconnected_graph_fail(self) -> None: + base, rest, case, landmarks = _mesh_fixture() + wrong = copy.deepcopy(base) + wrong["metadata"]["transition_indices"]["left"]["socket"] = [99] + with self.assertRaises(ValueError): + binding.bind(wrong, rest, case, landmarks) + + disconnected = copy.deepcopy(base) + disconnected["vertices"].append([20.0, 0.0, 0.0]) + disconnected["base_stencils"].append([[9, 1.0]]) + with self.assertRaises(ValueError): + binding.bind(disconnected, rest, case, landmarks) + + def test_material_negative_weights_fail_without_clamping(self) -> None: + base, rest, case, landmarks = _mesh_fixture() + negative = copy.deepcopy(rest) + negative["base_stencils"][9] = [[2, 2.0], [0, -1.0]] + with self.assertRaises(ValueError): + binding.bind(base, negative, case, landmarks) + + result, _base, rest, _case, _landmarks = _binding() + tampered = copy.deepcopy(result) + tampered["evaluated_weights"][9][0] = -0.01 + with self.assertRaises(ValueError): + binding.pose(rest, tampered, {"left": 0.0, "right": 0.0}) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/pelvis-hip-articulation/tests/test_capture.py b/experiments/pelvis-hip-articulation/tests/test_capture.py new file mode 100644 index 0000000..aabf3be --- /dev/null +++ b/experiments/pelvis-hip-articulation/tests/test_capture.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +import hashlib +import json +from pathlib import Path +import sys +import tempfile +import unittest +from unittest import mock + +HERE = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(HERE)) +import capture # noqa: E402 + + +def identity(root: Path, construction: str = "x") -> dict[str, object]: + return {"runtime": {"executable": "/frozen/runtime/bin/python"}, "manifest": {"construction": {"sha256": construction}}, "root": str(root)} + + +class CaptureTests(unittest.TestCase): + def test_prepare_refuses_existing_output(self) -> None: + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / "output" + output.mkdir() + with self.assertRaises(capture.CaptureError): + capture.prepare(str(output), ["capture.py"]) + + def test_prepare_copy_and_verify_with_tiny_files(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + source = root / "source" + source.mkdir() + (source / "capture.py").write_text("capture", encoding="utf-8") + (source / "tests").mkdir() + (source / "tests/test_capture.py").write_text("tests", encoding="utf-8") + calibration = root / "calibration" + calibration.mkdir() + (calibration / "prepare-report.json").write_text('{"status":"prepared"}', encoding="utf-8") + (calibration / "source-manifest.json").write_text('{"schema":"creature-kernel.pelvis-source-calibration-captured-source.v1","files":[]}', encoding="utf-8") + input_path = calibration / "input.json" + input_path.write_text('{"tiny":true}\n', encoding="utf-8") + frozen_runner = root / "runner.py" + frozen_runner.write_text("# stdlib-only test placeholder\n", encoding="utf-8") + entries = [("tiny", input_path, Path("inputs/tiny.json"), "rest_mesh")] + dependency = identity(root, capture.CONSTRUCTION_SHA256) + with mock.patch.object(capture, "HERE", source), mock.patch.object(capture, "INPUT_MAPPINGS", ()), mock.patch.object(capture, "CALIBRATION_SOURCE_MANIFEST", calibration / "source-manifest.json"), mock.patch.object(capture, "CALIBRATION_PREPARE_REPORT", calibration / "prepare-report.json"), mock.patch.object(capture, "FROZEN_CALIBRATION_RUNNER", frozen_runner), mock.patch.object(capture, "_calibration_inputs", return_value=entries), mock.patch.object(capture, "_load_frozen_dependency_identity", return_value=dependency): + output = root / "output" + manifest = capture.prepare(str(output), ["capture.py", "tests/test_capture.py"]) + self.assertFalse(manifest["geometry_executed"]) + self.assertEqual(capture.verify(str(output))["status"], "prepared") + self.assertEqual(len(capture.artifact_manifest(str(output))["files"]), 4) + + def test_verify_detects_changed_rest_mesh(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + target = root / "inputs/case-05-calibrated_ordinary_human-rest-L0.json" + target.parent.mkdir() + target.write_text("original", encoding="utf-8") + manifest = {"schema": "creature-kernel.pelvis-hip-articulation-capture.v1", "status": "prepared", "geometry_executed": False, "body_articulation_executed": False, "captured_source": {"before": [], "after": [], "copies": []}, "inputs": {"before": [], "after": [], "copies": [{"name": "case_05_rest_L0", "kind": "rest_mesh", "snapshot_path": "inputs/case-05-calibrated_ordinary_human-rest-L0.json", "bytes": 8, "sha256": hashlib.sha256(b"original").hexdigest()}]}, "frozen_dependency": {"before": {}, "after": {}, "construction_sha256": capture.CONSTRUCTION_SHA256}, "runtime_path": "/frozen/runtime/bin/python"} + (root / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8") + target.write_text("changed", encoding="utf-8") + with mock.patch.object(capture, "_load_frozen_dependency_identity", return_value={}): + with self.assertRaises(capture.CaptureError): + capture.verify(str(root)) + + def test_actual_frozen_dependency_identity_smoke_is_read_only(self) -> None: + dependency = capture._load_frozen_dependency_identity() + self.assertEqual(dependency["manifest"]["construction"]["sha256"], capture.CONSTRUCTION_SHA256) + self.assertEqual(dependency["runtime"]["executable"], str(capture.FROZEN_DEPENDENCY_ROOT / "runtime/bin/python")) + + def test_actual_calibration_inputs_manifest_smoke_is_read_only(self) -> None: + inputs = capture._calibration_inputs() + self.assertEqual(len(inputs), 6) + self.assertEqual(sum(kind == "rest_mesh" for _name, _source, _target, kind in inputs), 4) + self.assertEqual({name for name, _source, _target, _kind in inputs}, {"case_05_rest_L0", "case_05_rest_L2", "case_06_rest_L0", "case_06_rest_L2", "calibration_protocol", "calibration_inputs"}) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/pelvis-hip-articulation/tests/test_checks.py b/experiments/pelvis-hip-articulation/tests/test_checks.py new file mode 100644 index 0000000..8c970a8 --- /dev/null +++ b/experiments/pelvis-hip-articulation/tests/test_checks.py @@ -0,0 +1,207 @@ +import copy +import importlib.util +import math +import sys +import unittest +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +SPEC = importlib.util.spec_from_file_location("pelvis_hip_checks", ROOT / "checks.py") +CHECKS = importlib.util.module_from_spec(SPEC) +sys.modules[SPEC.name] = CHECKS +SPEC.loader.exec_module(CHECKS) + + +def mm(a, b): + return [[sum(a[r][k] * b[k][c] for k in range(4)) for c in range(4)] for r in range(4)] + + +def mp(m, p): + q = [*p, 1.0] + return [sum(m[r][c] * q[c] for c in range(4)) for r in range(3)] + + +def rigid(origin): + x, y, z = origin + rest = [[1., 0., 0., x], [0., 1., 0., y], [0., 0., 1., z], [0., 0., 0., 1.]] + inv = [[1., 0., 0., -x], [0., 1., 0., -y], [0., 0., 1., -z], [0., 0., 0., 1.]] + return rest, inv + + +def fixture(left=15.0, right=0.0, left_joint_y=0.0): + vertices = [ + [-.5, .8, 0.], [.5, .8, 0.], [.5, 1.2, 0.], [-.5, 1.2, 0.], + [-1.2, -.4, 0.], [-.8, -.4, 0.], [-.8, -.9, 0.], [-1.2, -.9, 0.], + [.8, -.4, 0.], [1.2, -.4, 0.], [1.2, -.9, 0.], [.8, -.9, 0.], + ] + quads = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]] + loops = {"port.left_thigh": [4, 5, 6, 7], "port.right_thigh": [8, 9, 10, 11]} + rest = {"vertices": vertices, "quads": quads, "loops": loops, + "face_owners": ["domain.pelvis", "domain.left_hip", "domain.right_hip"]} + ident, ident_inv = rigid((0., 0., 0.)) + left_rest, left_inv = rigid((-1., left_joint_y, 0.)) + right_rest, right_inv = rigid((1., 0., 0.)) + joints = {"pelvis": {"rest_matrix": ident, "inverse_bind_matrix": ident_inv}, + "left_hip": {"rest_matrix": left_rest, "inverse_bind_matrix": left_inv}, + "right_hip": {"rest_matrix": right_rest, "inverse_bind_matrix": right_inv}} + weights = [[1., 0., 0.]] * 4 + [[0., 1., 0.]] * 4 + [[0., 0., 1.]] * 4 + binding = {"joint_order": ["pelvis", "left_hip", "right_hip"], "evaluated_weights": weights, + "rest_frames": { + "left": {"rest_matrix": left_rest, "J": [-1., left_joint_y, 0.], "T": [-1., -.5, 0.], "K": [-1., -1., 0.], + "T_local": [0., -.5-left_joint_y, 0.], "K_local": [0., -1.-left_joint_y, 0.]}, + "right": {"rest_matrix": right_rest, "J": [1., 0., 0.], "T": [1., -.5, 0.], "K": [1., -1., 0.], + "T_local": [0., -.5, 0.], "K_local": [0., -1., 0.]}, + }} + poses = {"pelvis": ident} + for side, angle, rest_matrix in (("left", left, left_rest), ("right", right, right_rest)): + a = math.radians(-angle); c, s = math.cos(a), math.sin(a) + poses[f"{side}_hip"] = mm(rest_matrix, [[1.,0.,0.,0.], [0.,c,-s,0.], [0.,s,c,0.], [0.,0.,0.,1.]]) + skins = {name: mm(poses[name], joints[name]["inverse_bind_matrix"]) for name in poses} + posed_vertices = [] + for p, row in zip(vertices, weights): + posed_vertices.append([sum(row[j] * mp(skins[name], p)[a] for j, name in enumerate(("pelvis", "left_hip", "right_hip"))) for a in range(3)]) + posed = {**copy.deepcopy(rest), "vertices": posed_vertices, + "provenance": {"vertices": "POSED_BY_REST_L2_3JOINT_LBS", "base_stencils": "REST"}, + "metadata": {"posed_cage_evaluation": False, "pose_angles_degrees": {"left": left, "right": right}}} + refs = {"joint_left": [-1., left_joint_y, 0.], "joint_right": [1., 0., 0.], + "crest_left": [-1., .5, 0.], "crest_right": [1., .5, 0.]} + case = {"diagnostic_scale": 1., "attachments": { + "left": {"centre": [-1., -.5, 0.], "knee": [-1., -1., 0.]}, + "right": {"centre": [1., -.5, 0.], "knee": [1., -1., 0.]}}} + protocol = {"checks": { + "identity_error_over_L_max": 1e-12, "weight_partition_tolerance": 1e-12, + "frame_and_transform_tolerance": 1e-10, "exported_LBS_error_over_L_max": 1e-10, + "rigid_port_error_over_L_max": 1e-9, "pelvis_only_weighted_error_over_L_max": 1e-10, + "above_crest_skin_displacement_over_L_max": .01, "lower_triangle_area_ratio": [.5, 2.], + "lower_edge_length_ratio": [.65, 1.5], "lower_rest_posed_triangle_normal_dot_min": 0., + "lower_nonadjacent_intersections_max": 0}} + return rest, posed, binding, {"left": left, "right": right}, case, refs, protocol + + +def binding_fixture(): + vertices = [[float(x), float(y), 0.] for y in range(3) for x in range(4)] + quads = [[y*4+x, y*4+x+1, (y+1)*4+x+1, (y+1)*4+x] for y in range(2) for x in range(3)] + transitions = {"left": {"socket": [4], "ringA": [5], "ringB": [0], "exit": [1]}, + "right": {"socket": [6], "ringA": [7], "ringB": [2], "exit": [3]}} + base = {"vertices": vertices, "quads": quads, "metadata": {"transition_indices": transitions}} + graph = [set() for _ in vertices] + for quad in quads: + for i, vertex in enumerate(quad): graph[vertex].add(quad[(i+1) % 4]); graph[quad[(i+1) % 4]].add(vertex) + unknown = [4, 5, 6, 7]; position = {vertex: i for i, vertex in enumerate(unknown)} + matrix = [[0.]*4 for _ in range(4)]; fixed = [[0., 0., 0.] for _ in vertices] + for i in (0, 1): fixed[i] = [0., 1., 0.] + for i in (2, 3): fixed[i] = [0., 0., 1.] + for i in range(8, 12): fixed[i] = [1., 0., 0.] + rhs = [[0.]*3 for _ in range(4)] + for vertex, row in position.items(): + matrix[row][row] = len(graph[vertex]) + for neighbour in graph[vertex]: + if neighbour in position: matrix[row][position[neighbour]] -= 1. + else: + for column in range(3): rhs[row][column] += fixed[neighbour][column] + augmented = [matrix[i] + rhs[i] for i in range(4)] + for column in range(4): + pivot = max(range(column, 4), key=lambda row: abs(augmented[row][column])) + augmented[column], augmented[pivot] = augmented[pivot], augmented[column] + divisor = augmented[column][column]; augmented[column] = [x/divisor for x in augmented[column]] + for row in range(4): + if row != column: + factor = augmented[row][column] + augmented[row] = [a-factor*b for a, b in zip(augmented[row], augmented[column])] + for row, vertex in enumerate(unknown): fixed[vertex] = augmented[row][4:] + rest = {"vertices": copy.deepcopy(vertices), "base_stencils": [[[i, 1.]] for i in range(len(vertices))]} + binding = {"base_weights": copy.deepcopy(fixed), "evaluated_weights": copy.deepcopy(fixed)} + protocol = fixture()[-1] + return base, rest, binding, protocol + + +class CheckPoseTests(unittest.TestCase): + def check(self, values): + return CHECKS.check_pose(*values) + + def test_import_smoke_and_independent_matrix_response(self): + values = fixture() + self.assertGreater(values[1]["vertices"][6][2], 0.1) + report = self.check(values) + self.assertTrue(report["pass"], report) + self.assertLessEqual(report["metrics"]["posed_lbs_max_error"], 1e-10) + self.assertIn("frozen_pelvis_transition_checks", sys.modules) + self.assertTrue(report["checks"]["lower_nonadjacent_self_intersection"]) + self.assertEqual(report["metrics"]["lower_intersection_count"], 0) + + def test_wrong_pivot_is_caught(self): + values = list(fixture()) + values[2] = copy.deepcopy(values[2]) + values[2]["rest_frames"]["left"]["rest_matrix"][1][3] = .1 + report = self.check(values) + self.assertFalse(report["pass"]) + self.assertFalse(report["checks"]["frames"]) + + def test_left_joint_up_counterfactual_changes_pose_without_retuning(self): + nominal = fixture(left_joint_y=0.0) + shifted = fixture(left_joint_y=.01) + report = self.check(shifted) + response = max(math.dist(a, b) for a, b in zip(nominal[1]["vertices"], shifted[1]["vertices"])) + self.assertTrue(report["pass"], report) + self.assertGreater(response, 1e-4) + self.assertEqual(nominal[2]["evaluated_weights"], shifted[2]["evaluated_weights"]) + + def test_static_export_is_caught(self): + values = list(fixture()) + values[1] = copy.deepcopy(values[1]); values[1]["vertices"] = copy.deepcopy(values[0]["vertices"]) + report = self.check(values) + self.assertFalse(report["pass"]) + self.assertFalse(report["checks"]["independent_lbs"]) + + def test_malformed_weights_are_caught(self): + values = list(fixture()) + values[2] = copy.deepcopy(values[2]); values[2]["evaluated_weights"][4] = [1.2, -.2, 0.] + report = self.check(values) + self.assertFalse(report["pass"]) + self.assertFalse(report["checks"]["weight_bounds"]) + + def test_declared_weight_roundoff_tolerance_is_accepted(self): + values = list(fixture()) + values[2] = copy.deepcopy(values[2]) + values[2]["evaluated_weights"][4] = [-5e-13, 1.0+5e-13, 0.] + report = self.check(values) + self.assertTrue(report["checks"]["weight_bounds"], report) + self.assertTrue(report["checks"]["partition_unity"], report) + + def test_crest_ceiling_uses_higher_declared_crest(self): + values = fixture() + refs = copy.deepcopy(values[5]); refs["crest_left"][1] = .4; refs["crest_right"][1] = .6 + normalized = CHECKS._references(values[4], refs) + self.assertEqual(normalized["crest_y"], .6) + + def test_modified_quad_is_caught(self): + values = list(fixture()) + values[1] = copy.deepcopy(values[1]); values[1]["quads"][1] = [4, 5, 7, 6] + report = self.check(values) + self.assertFalse(report["pass"]) + self.assertFalse(report["checks"]["exact_topology"]) + + def test_gross_collapse_is_caught(self): + values = list(fixture()) + values[1] = copy.deepcopy(values[1]) + for i in (4, 5, 6, 7): values[1]["vertices"][i] = copy.deepcopy(values[1]["vertices"][4]) + report = self.check(values) + self.assertFalse(report["pass"]) + self.assertFalse(report["checks"]["triangle_area_ratios"]) + + def test_binding_method_and_wrong_in_range_field(self): + values = binding_fixture() + self.assertTrue(CHECKS.check_binding(*values)["pass"]) + wrong = list(values); wrong[2] = copy.deepcopy(values[2]) + wrong[2]["base_weights"][4][0] += .01 + wrong[2]["base_weights"][4][1] -= .01 + wrong[2]["evaluated_weights"] = copy.deepcopy(wrong[2]["base_weights"]) + report = CHECKS.check_binding(*wrong) + self.assertFalse(report["pass"]) + self.assertFalse(report["checks"]["harmonic_residual"]) + self.assertTrue(report["checks"]["stencil_transfer"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/pelvis-hip-articulation/tests/test_integration.py b/experiments/pelvis-hip-articulation/tests/test_integration.py new file mode 100644 index 0000000..8d38f42 --- /dev/null +++ b/experiments/pelvis-hip-articulation/tests/test_integration.py @@ -0,0 +1,95 @@ +from __future__ import annotations + +import copy +import json +import sys +import unittest +from pathlib import Path + + +EXPERIMENT_DIR = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(EXPERIMENT_DIR)) +import binding # noqa: E402 +import checks # noqa: E402 + + +def _fixture() -> tuple[dict, dict, dict, dict, dict]: + # Two four-vertex distal port loops attach through one ringB, socket and + # ringA chain per side to a small shared pelvis. The faces are nonzero + # area and the boundary-edge graph is connected. + vertices = [ + [-1.5, 0.0, -0.4], [-0.9, 0.0, -0.4], [-0.9, 0.6, -0.4], [-1.5, 0.6, -0.4], + [0.9, 0.0, -0.4], [1.5, 0.0, -0.4], [1.5, 0.6, -0.4], [0.9, 0.6, -0.4], + [-1.2, 0.15, 0.0], [-1.55, 0.15, 0.0], [-1.35, 0.8, 0.0], + [1.2, 0.15, 0.0], [1.55, 0.15, 0.0], [1.35, 0.8, 0.0], + [0.0, 1.0, 0.0], [-0.6, 1.2, 0.0], [0.6, 1.2, 0.0], [0.0, 1.6, 0.0], + ] + quads = [ + [0, 1, 2, 3], [1, 0, 9, 8], [8, 9, 10, 14], + [4, 5, 6, 7], [5, 4, 12, 11], [11, 12, 13, 14], + [14, 15, 16, 17], + ] + transitions = { + "left": {"socket": [9], "ringA": [10], "ringB": [8], "exit": [0, 1, 2, 3]}, + "right": {"socket": [12], "ringA": [13], "ringB": [11], "exit": [4, 5, 6, 7]}, + } + stencils = [[[index, 1.0]] for index in range(len(vertices))] + owners = ["synthetic_pelvis"] * len(quads) + base = { + "schema": "synthetic-l0", + "level": 0, + "vertices": copy.deepcopy(vertices), + "quads": copy.deepcopy(quads), + "base_stencils": copy.deepcopy(stencils), + "metadata": {"transition_indices": copy.deepcopy(transitions)}, + } + rest = { + "schema": "synthetic-l2", + "level": 2, + "vertices": copy.deepcopy(vertices), + "quads": copy.deepcopy(quads), + "base_stencils": stencils, + "loops": {"port.left_thigh": [0, 1, 2, 3], + "port.right_thigh": [4, 5, 6, 7]}, + "control_owners": [f"control-{index}" for index in range(len(vertices))], + "face_owners": owners, + "metadata": {"transition_indices": copy.deepcopy(transitions)}, + } + case = { + "id": "synthetic-integration", + "components": {f"component_{index:02d}": float(index) for index in range(92)}, + "attachments": { + "left": {"centre": [-1.2, 0.3, -0.4], "knee": [-1.2, -0.8, 0.0]}, + "right": {"centre": [1.2, 0.3, -0.4], "knee": [1.2, -0.8, 0.0]}, + }, + } + references = { + "joint_left": [-1.2, 0.3, 0.0], "joint_right": [1.2, 0.3, 0.0], + "crest_left": [-0.3, 1.5, 0.0], "crest_right": [0.3, 1.5, 0.0], + } + protocol = json.loads((EXPERIMENT_DIR / "protocol.json").read_text(encoding="utf-8")) + return base, rest, case, references, protocol + + +def _json_roundtrip(value: object) -> object: + return json.loads(json.dumps(value)) + + +class BindingIntegrationTests(unittest.TestCase): + def test_binding_pose_json_roundtrip_consumes_checks_at_identity_and_modest_pose(self) -> None: + base, rest, case, references, protocol = _fixture() + bound = _json_roundtrip(binding.bind(base, rest, case, references)) + protocol = _json_roundtrip(protocol) + self.assertIsInstance(bound, dict) + for angles in ({"left": 0.0, "right": 0.0}, + {"left": 15.0, "right": 0.0}): + posed = _json_roundtrip(binding.pose(rest, bound, angles)) + report = checks.check_pose(rest, posed, bound, angles, case, references, protocol) + self.assertTrue(report["pass"], report) + self.assertFalse(report["errors"], report) + self.assertEqual(rest["vertices"], base["vertices"]) + self.assertEqual(rest["quads"], base["quads"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/pelvis-hip-articulation/tests/test_runner.py b/experiments/pelvis-hip-articulation/tests/test_runner.py new file mode 100644 index 0000000..a582589 --- /dev/null +++ b/experiments/pelvis-hip-articulation/tests/test_runner.py @@ -0,0 +1,253 @@ +from __future__ import annotations + +import copy +import json +from pathlib import Path +import sys +import tempfile +import unittest +from unittest import mock + + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +import runner # noqa: E402 + + +IDENTITY = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] + + +class FakeBinding: + def bind(self, _base, _rest, _case, _refs): + return {"evaluated_weights": [[1.0, 0.0, 0.0]], "method": "synthetic"} + + def pose(self, rest, _binding, _angles): + return copy.deepcopy(rest) + + def joint_points(self, _binding, angles): + def row(): + return {"J": [0.0, 0.0, 0.0], "T": [0.0, -1.0, 0.0], + "K": [0.0, -2.0, 0.0], "posed_J": [0.0, 0.0, 0.0], + "posed_T": [0.0, -1.0, 0.0], "posed_K": [0.0, -2.0, 0.0], + "posed_points": {"J": [0.0, 0.0, 0.0], + "T": [0.0, -1.0, 0.0], + "K": [0.0, -2.0, 0.0]}, + "posed_matrix": IDENTITY, "skin_matrix": IDENTITY} + return {"left": row(), "right": row(), "angles": angles} + + +class FakeChecks: + def __init__(self, binding_pass=True): + self.calls = [] + self.binding_calls = [] + self.binding_pass = binding_pass + + def check_binding(self, *args): + self.binding_calls.append(args) + return {"schema": "synthetic-binding-checks-v1", "pass": self.binding_pass, + "metrics": {"synthetic": 1.0}, "errors": []} + + def check_pose(self, *_args): + self.calls.append(_args) + refs = _args[5] + scale = 10.0 if refs.get("joint_left", [0.0, 0.0, 0.0])[1] > 0.0 else 1.0 + return {"schema": "synthetic-checks-v1", "pass": True, + "checks": {"synthetic": True}, "metrics": {"scale": scale}, + "errors": []} + + +class FakeRender: + def __init__(self): + self.calls = [] + + def render_views(self, _vertices, _quads, output_path, _title, _status, + _bounds, _overlays, *, underside, allow_crop): + output_path = Path(output_path) + self.calls.append((_vertices, _quads, output_path, _overlays, underside, allow_crop)) + output_path.write_bytes(b"png") + diagnostic = output_path.with_name(output_path.stem + "-diagnostic.png") + diagnostic.write_bytes(b"diagnostic") + underside_path = None + if underside: + underside_path = output_path.with_name(output_path.stem + "-underside.png") + underside_path.write_bytes(b"underside") + return {"output_path": str(output_path), + "diagnostic_path": str(diagnostic), + "underside_path": str(underside_path) if underside_path else None} + + +def protocol_fixture(): + return {"views": {"bounds": [[-1.0, -1.0, -1.0], [1.0, 1.0, 1.0]]}, + "checks": {"pivot_counterfactual_response_over_L_min": 1.0}, + "pivot_counterfactual": {"J_left_delta": [0.0, 0.01, 0.0], + "pose": {"left": 15.0, "right": 0.0}}, + "poses": [{"id": "rest", "left": 0.0, "right": 0.0}, + {"id": "left_flex_15", "left": 15.0, "right": 0.0}, + {"id": "left_flex_30", "left": 30.0, "right": 0.0}, + {"id": "right_flex_15", "left": 0.0, "right": 15.0}, + {"id": "both_flex_20", "left": 20.0, "right": 20.0}]} + + +class RunnerTests(unittest.TestCase): + def test_capture_allowlist_is_exact_and_includes_integration(self): + self.assertEqual(set(runner.CAPTURE_FILES), { + "binding.py", "capture.py", "checks.py", "runner.py", + "README.md", "protocol.json", "tests/test_binding.py", + "tests/test_capture.py", "tests/test_checks.py", + "tests/test_integration.py", "tests/test_runner.py", + }) + + def test_absent_output_is_a_sibling_only(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + snapshot = root / "snapshot" + snapshot.mkdir() + output = root / "output" + self.assertEqual(runner._require_absent_output(output, snapshot), output) + output.mkdir() + with self.assertRaises(runner.RunnerError): + runner._require_absent_output(output, snapshot) + with self.assertRaises(runner.RunnerError): + runner._require_absent_output(snapshot / "nested", snapshot) + + def test_dynamic_import_is_registered_before_execution(self): + with tempfile.TemporaryDirectory() as directory: + module_path = Path(directory) / "module.py" + module_path.write_text("VALUE = 7\n", encoding="utf-8") + loaded = runner._load_module("synthetic_runner_module", module_path) + self.assertIs(sys.modules["synthetic_runner_module"], loaded) + self.assertEqual(loaded.VALUE, 7) + + def test_overlays_use_serialized_joint_schema_and_diagnostic_labels(self): + points = FakeBinding().joint_points({}, {"left": 15.0, "right": 0.0}) + refs = {"crest_left": [0.0, 0.5, 0.0], "crest_right": [0.0, 0.5, 0.0], + "asis_left": [0.0, 0.4, 0.1], "asis_right": [0.0, 0.4, 0.1], + "psis_left": [0.0, 0.3, -0.1], "psis_right": [0.0, 0.3, -0.1], + "trochanter_left": [0.0, -0.4, 0.0], + "trochanter_right": [0.0, -0.4, 0.0], + "pubic_symphysis": [0.0, -0.2, 0.0]} + overlays = runner._overlays({"left": points["left"], "right": points["right"]}, refs) + self.assertGreaterEqual(len(overlays), 11) + self.assertTrue(all(set(item) == {"start", "end", "color", "label"} + for item in overlays)) + self.assertTrue(all(item["label"].startswith("diagnostic") for item in overlays)) + self.assertEqual(overlays[0]["start"], [0.0, 0.0, 0.0]) + + def test_frozen_helper_import_smoke_does_not_execute_body(self): + loaded = runner._load_module( + "synthetic_runner_capture_smoke", ROOT / "capture.py") + self.assertIs(sys.modules["synthetic_runner_capture_smoke"], loaded) + self.assertTrue(hasattr(loaded, "prepare")) + + def test_pose_export_serializes_actual_joint_matrices(self): + mesh = {"vertices": [[0.0, 0.0, 0.0]], "metadata": {}} + points = {"left": {"posed_matrix": [[2.0] * 4] * 4}, + "right": {"posed_matrix": IDENTITY}} + exported = runner._pose_export(mesh, points, {"left": 15.0, "right": 0.0}) + self.assertEqual(exported["metadata"]["joints"]["left_hip"]["pose_matrix"], + points["left"]["posed_matrix"]) + self.assertEqual(exported["metadata"]["joints"]["pelvis"]["pose_matrix"], IDENTITY) + self.assertEqual(mesh["metadata"], {}) + json.dumps(exported) + + def test_synthetic_orchestration_keeps_five_poses_and_counterfactual_separate(self): + base = {"vertices": [[0.0, 0.0, 0.0]]} + rest = {"vertices": [[0.0, 0.0, 0.0]], "quads": [], "metadata": {}} + case = {"id": "calibrated_ordinary_human", "attachments": {}} + refs = {"joint_left": [0.0, 0.0, 0.0], "joint_right": [0.0, 0.0, 0.0], + "trochanter_left": [0.0, -0.4, 0.0], + "trochanter_right": [0.0, -0.4, 0.0]} + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / "output" + output.mkdir() + summary = runner._run_case( + "calibrated_ordinary_human", base, rest, case, refs, + protocol_fixture(), output, FakeBinding(), FakeChecks(), FakeRender()) + self.assertEqual(len(summary["poses"]), 5) + self.assertEqual({row["id"] for row in summary["poses"]}, + {pose["id"] for pose in protocol_fixture()["poses"]}) + self.assertTrue(summary["counterfactual"]["diagnostic_only"]) + self.assertTrue(summary["binding_method_pass"]) + self.assertNotIn("counterfactual", {row["id"] for row in summary["poses"]}) + self.assertTrue(summary["rest_vertices_unchanged"]) + self.assertTrue((output / "cases/calibrated_ordinary_human/poses/rest/mesh.json").is_file()) + self.assertTrue((output / "cases/calibrated_ordinary_human/counterfactual/checks.json").is_file()) + + def test_synthetic_orchestration_reads_back_mesh_binding_and_joints(self): + base = {"vertices": [[0.0, 0.0, 0.0]]} + rest = {"vertices": [[0.0, 0.0, 0.0]], "quads": [], "metadata": {}} + case = {"id": "calibrated_ordinary_human", "attachments": {}} + refs = {"joint_left": [0.0, 0.0, 0.0], "joint_right": [0.0, 0.0, 0.0], + "trochanter_left": [0.0, -0.4, 0.0], + "trochanter_right": [0.0, -0.4, 0.0]} + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / "output" + output.mkdir() + checks = FakeChecks() + render = FakeRender() + protocol = protocol_fixture() + protocol["pivot_counterfactual"] = { + "J_left_delta": [0.0, 0.02, 0.0], + "pose": {"left": 17.0, "right": 3.0}, + } + read_values = {} + original_read_json = runner._read_json + + def read_json(path): + value = original_read_json(path) + read_values[Path(path)] = value[0] + return value + + with mock.patch.object(runner, "_read_json", side_effect=read_json): + runner._run_case( + "calibrated_ordinary_human", base, rest, case, refs, + protocol, output, FakeBinding(), checks, render) + binding_path = output / "cases/calibrated_ordinary_human/binding.json" + mesh_path = output / "cases/calibrated_ordinary_human/poses/rest/mesh.json" + joints_path = output / "cases/calibrated_ordinary_human/poses/rest/joints.json" + self.assertIs(checks.calls[0][1], read_values[mesh_path]) + self.assertIs(checks.calls[0][2], read_values[binding_path]) + self.assertIs(checks.binding_calls[0][2], read_values[binding_path]) + self.assertIn(joints_path, read_values) + self.assertIs(render.calls[0][0], read_values[mesh_path]["vertices"]) + self.assertEqual(len(checks.calls), 6) + counter_binding = output / "cases/calibrated_ordinary_human/counterfactual/binding.json" + counter_mesh = output / "cases/calibrated_ordinary_human/counterfactual/mesh.json" + counter_joints = output / "cases/calibrated_ordinary_human/counterfactual/joints.json" + self.assertIn(counter_binding, read_values) + self.assertIn(counter_mesh, read_values) + self.assertIn(counter_joints, read_values) + comparison = json.loads((counter_mesh.parent / "comparison.json").read_text(encoding="utf-8")) + self.assertEqual(comparison["J_left_delta"], [0.0, 0.02, 0.0]) + self.assertEqual(comparison["counterfactual_pose"], {"left": 17.0, "right": 3.0}) + self.assertEqual(comparison["L"], 1.0) + counter_joints_value = read_values[counter_joints] + self.assertEqual(counter_joints_value["angles_degrees"], {"left": 17.0, "right": 3.0}) + + def test_binding_numeric_failure_does_not_hide_pose_evidence(self): + base = {"vertices": [[0.0, 0.0, 0.0]]} + rest = {"vertices": [[0.0, 0.0, 0.0]], "quads": [], "metadata": {}} + case = {"id": "calibrated_ordinary_human", "attachments": {}} + refs = {"joint_left": [0.0, 0.0, 0.0], "joint_right": [0.0, 0.0, 0.0], + "trochanter_left": [0.0, -0.4, 0.0], + "trochanter_right": [0.0, -0.4, 0.0]} + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / "output" + output.mkdir() + checks = FakeChecks(binding_pass=False) + render = FakeRender() + summary = runner._run_case( + "calibrated_ordinary_human", base, rest, case, refs, + protocol_fixture(), output, FakeBinding(), checks, render) + self.assertFalse(summary["binding_method_pass"]) + self.assertEqual(len(summary["poses"]), 5) + self.assertEqual(len(render.calls), 5) + self.assertTrue(all(row["technical_status"] == "TECHNICAL REJECTED" + for row in summary["poses"])) + self.assertTrue((output / "cases/calibrated_ordinary_human/binding-checks.json").is_file()) + self.assertTrue((output / "cases/calibrated_ordinary_human/poses/left_flex_15/mesh.json").is_file()) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/pelvis-source-calibration/README.md b/experiments/pelvis-source-calibration/README.md new file mode 100644 index 0000000..aec315a --- /dev/null +++ b/experiments/pelvis-source-calibration/README.md @@ -0,0 +1,105 @@ +# Pelvis source/anatomy calibration + +Experiment lifecycle: finished + +Evidence closure: complete + +Technology outcome: inconclusive + +Declared 2026-09-05. This is a bounded source/anatomy calibration, not a pass +for a new architecture, production surface contract, human-body promise, or +whole-body fixture. The parent-authored [protocol](protocol.json) is the +authoritative pre-generation record; its values were frozen before generated +results. The compact [results record](RESULTS.md) closes this calibration with +a mixed anatomical result; it does not reopen the rejected old trial. + +## Fixed scope + +The frozen construction is identified by SHA-256 +`7fd457e2206165eb5e404ce81732f4157234a2e13a64008d96ae75d6abcf5cdb` and uses +the dependency root +`/home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot`. +The budget is one calibration set, zero input refinements, and zero geometry +changes. It compares five unchanged historical controls with two new cases +through the same fixed construction. Shoulder geometry remains context only. + +The fixed base transform is scale `0.16`, translation `[0.0, 0.16, 0.0]`. +This is the protocol's display/input frame convention for placing the +comparison origin at the intended joint-centre height; it is not an anatomical +inference about the old source. One fixed diagnostic samples 41 sections over +`y=[-0.24, 0.16]`; no input tuning or shape repair is permitted. + +## Semantic trace and generator boundary + +| Concept | Current meaning and consequence | +| --- | --- | +| Declared hip `J` | The source hip Joint supplies proximal and distal frame records, both local translations `[0,0,0]` with identity rotation. Under authored Part transforms, the proximal endpoint is the pelvis origin `[0,0,0]`, while the distal endpoint is the thigh Part origin: `[±1,-1,0]` in the ordinary profiles and `[±1,-2,0]` in tall/slender. They do not supply one coincident world-space anatomical hip centre. This is missing anatomical resolution, not necessarily a normative invalid-source result; the spec keeps Joint semantics distinct from a rig or solver. | +| Executable `T` / `H` | `form_leg_profile_thigh_start` is the thigh-local start landmark. The exact-five projection adds the profile Part-placement chain and this landmark, producing `H`, which is also `hips.*.P_s` and the constructor's attachment centre. | +| Pelvis Part origin | The root pelvis Part is at `[0,0,0]`; it is not H. | +| Pelvic axial stations | `form_torso_profile_lower_pelvis`, `upper_pelvis`, `lower_abdomen`, and `waist_abdomen` provide envelope centres and radii. They are form stations, not automatically ASIS, crest, pubis, or other skeletal landmarks. | +| Skin bifurcation | The connected-section transition to two thigh contours is derived from H/K, radii, stations, and fixed transition topology. It is not an input landmark or a universal crotch plane. | + +Source and implementation references: [hip Joint](../../examples/body-documents/stylized-digitigrade-biped-authored-form.json) line 49, [thigh-start landmark](../../examples/body-documents/stylized-digitigrade-biped-authored-form.json) line 80, [pelvis Part](../../examples/body-documents/stylized-digitigrade-biped-authored-form.json) line 20, [pelvic station](../../examples/body-documents/stylized-digitigrade-biped-authored-form.json) line 90, [Joint semantics](../../spec/body-graph/README.md) lines 131-144, [exact-five projection](../owned-root-assembly-successor-exact-five/exact_five_runner.py) line 308, and [station projection](../owned-root-assembly-successor/prepared_projection.py) line 293. + +The explicit generator obstruction is unchanged: the fixed constructor accepts +only `centre` and `knee` attachments and requires `centre == hips.*.P_s`; it +has no independent `J` or `T` fields ([attachment contract](../pelvis-thigh-transition/construction.py) +lines 111-144). [Case provenance](../pelvis-thigh-transition/cases.py) lines +118-158 retains the hip frame pair as `joint_hint` only. Therefore this +calibration can execute T and diagnose J overlays, but cannot claim independent +J-to-skin causality without a code/contract change outside this budget. No code +change is made. + +## Protocol values + +The compact values below are preregeneration calculations from the frozen +protocol, not mesh measurements or generated-surface results. The full numeric +inputs remain authoritative in `protocol.json`. `T-K` is the executable +thigh-start-to-knee distance; `D/T-K` is the lower-pelvis-station-to-T vertical +offset divided by that distance; pelvis and thigh width use the corresponding +input envelope widths. + +| Case | J-K / stature | T-K (m) | D / T-K | Pelvis width / T-K | Thigh width / T-K | +| --- | ---: | ---: | ---: | ---: | ---: | +| `calibrated_ordinary_human` | `.246` | `.382` | `.157` | `.890` | `.393` | +| `calibrated_upright_anthropomorphic` | `.198` | `.313` | `.208` | `1.214` | `.543` | +| historical standard | — | — | `.55` | `3.00` | — | +| historical tall | — | — | `1.55` | `2.55` | — | +| historical slender | — | — | `1.55` | `2.40` | — | + +Tall/slender change thigh Part placement from `y=-1` to `y=-2`, but keep +thigh-local T at `[0,0,0]` and knee at `[0,-1,0]`. Both world landmarks move +down one unit; their distance stays one unit. The lower-pelvis station stays +at `y=-0.45`, so D increases from `0.55` to `1.55`. Profile dimension scaling +also narrows their envelopes but does not lengthen this landmark interval. +The profile names therefore cannot be treated as evidence of anatomically +longer femurs. Compact and stocky retain the standard T/K heights; all five +controls remain unchanged in this experiment. + +The human case uses an approximate adult-like calibration hypothesis. Its +quarter-height femur cue is the [Proko artist proportion guide](https://www.proko.com/course-lesson/how-to-draw-legs-bone-anatomy-for-artists), not sourced numeric anthropometry. The anthropomorphic case is an explicit artist-design +hypothesis informed by [stylized upright animal-body reference](https://www.disneyanimation.com/publications/flesh-flab-and-fascia-simulation-on-zootopia/), not a biological +measurement or reconstruction of a named character. [OpenStax](https://openstax.org/books/anatomy-and-physiology-2e/pages/8-3-the-pelvic-girdle-and-pelvis) supplies landmark relationships only; no population measurements are extracted. The protocol +records the stated uncertainties: human J about `±0.02 m`, thigh/pelvic +landmarks about `±0.025 m`, skin dimensions about `±0.03 m`; anthropomorphic +landmarks about `±0.03 m` and proportional allowances about `±20%`. + +## Boundary and diagnostic methodology + +The completed diagnostic evaluated whether the unchanged construction could show +a coherent pelvic envelope and credible two-contour transition for both new +cases while preserving the source distinction between diagnostic J and +executable T. It describes placement and section topology; it must not +reinterpret a J overlay as an executable joint, infer J-to-skin causality, or +retroactively alter the closed old trial's verdict or gates. + +The run completed with no exceptions and no source/dependency drift. A +parent-side synthetic-scale bug was fixed before body generation; it did not +change the frozen protocol values or authorize tuning. Results, limitations, +visual judgment, and the bounded next recommendation are recorded in +[RESULTS.md](RESULTS.md). + +The diagnostic implementation is [section_diagnostic.py](section_diagnostic.py), +with separate tests in [tests/test_section_diagnostic.py](tests/test_section_diagnostic.py). +The reproduction command uses the captured launcher through `bash` because its +execute permission is absent; it is recorded in [RESULTS.md](RESULTS.md). diff --git a/experiments/pelvis-source-calibration/RESULTS.md b/experiments/pelvis-source-calibration/RESULTS.md new file mode 100644 index 0000000..bc0368b --- /dev/null +++ b/experiments/pelvis-source-calibration/RESULTS.md @@ -0,0 +1,121 @@ +# Pelvis source/anatomy calibration results + +Experiment lifecycle: finished + +Evidence closure: complete + +Technology outcome: inconclusive + +Run date: 2026-09-05. The single frozen calibration set completed all seven +cases without exceptions, with source/dependency drift reported as false. This +is calibration evidence, not acceptance of a new architecture or a new body +promise. The old pelvis-to-thigh transition remains closed and rejected. + +## Frozen evidence + +The captured calibrated-inputs SHA-256 is +`3c0cbe9a3ae81def226f91f3d5eddcff6e07f118360abc88670069fe9b010a8c`. +The protocol SHA-256 is +`12570240c84af9894a46cd6bfdc4c9d3eb8df82d09fb7684e72d3d1844114028`. +The final artifact-manifest SHA-256 is +`f0152de5b6b82a60c35599b0b82af746704d1917446d8fceb88b2ca016275871`. +The main thread's 18 tests passed in the frozen runtime with the captured test +set. For the five unchanged historical controls, all three subdivision levels +had exactly matching vertex and quad arrays against the corresponding +`mesh-level-N.json` files from old final attempt-2 checked seed 17: 15/15 +mesh-level comparisons exact. This is not a claim that schemas or complete +serialized files are equal. +The main thread independently verified all 72 output-manifest file hashes, +with zero mismatches. The captured runtime packages and source files are +identified; host standard-library/system-library dependencies are not a fully +hermetic operating-system image. + +At level 2, every case had one connected face component, 2,249 vertices, +2,176 quads, 152 boundary edges, and zero non-manifold edges. All fourteen T +samples were inside their joined horizontal sections. For every case, thigh +axis fractions 0, .15, and .30 were inside; .45 reached an open-end +indeterminate or out-of-range condition, and every K was out of the represented +range as expected for the proximal stub. + +| Case group | Observed one-to-two contour bracket (display frame) | J-to-T samples | +| --- | --- | --- | +| standard, compact, stocky | `[-.02,-.01]` | diagnostic overlay not applicable | +| tall, slender | `[-.17,-.16]` | diagnostic overlay not applicable | +| calibrated ordinary human | `[-.08,-.07]` | 10/10 inside | +| calibrated upright anthropomorphic | `[-.07,-.06]` | 10/10 inside | + +Both new cases had no lower intersections at levels 0, 1, or 2, passed their +exit-loop checks and lower quad-normal checks, and retained the old own-side H +containment failure. Both also had `folds.lower.pass` true. +The old rejected verdict is unchanged. Upper context was not reappraised, +despite local lower-fold diagnostics. + +The own-side ray test examines a named hip patch, not the entire joined body. +Its missing medial hit is therefore not, by itself, evidence that T escaped +the whole skin. The new closed-section membership measurement answers a +different question; it does not retroactively relax or pass the old gate. + +## Anatomy interpretation and limits + +For both new cases, J and trochanter reference points were inside. Crest was +outside by about 15 mm and ASIS by about 18.5 mm. PSIS was outside by about +0.077 mm for the human case and 0.459 mm for the anthropomorphic case; pubis +was outside by about 35.7 mm and 65.2 mm respectively. These are distances to +the horizontal-section boundary, not shortest 3-D distances or hard anatomical +error measurements, so they are not strict 3-D tolerance failures. A +bifurcation bracket does not prove pubic-bone fit. + +The parent visual judgment was that recalibration made proximal leg roots much +more proportional and less shelf-like than the old controls in both cases. +The waist-to-pelvis transition remains abrupt and pinched, inner-groin +arching is schematic, and buttock shaping is weak. Faceting is present, but +more subdivision is not claimed to fix that structural shape. The result is a +coarse partial improvement, not a polished anatomy pass. + +The preregeneration ratios support the hypothesis that input proportions matter: +old source `D/T-K` was `.55` for standard and `1.55` for tall/slender, while the +new cases were `.157` and `.208`; old pelvis-width ratios were `3.0`, `2.55`, +and `2.4`, versus `.890` and `1.214` for the new cases. The result cannot +attribute all improvement to one changed value, prove generalization, or claim +five calibrated bodies. J remains reference-only; T is the executable input, +so source relationships are not yet closed. + +The image legend is: orange T-K, purple J-T, green reference points, blue left +T, and red right T; points are markers, not bones. Lower legs and head were not +generated, and cropped upper context is unchanged. Overlapping legend content +is a known frozen-renderer limitation and was not edited. The main thread +personally viewed the five historical triptychs and both new triptychs, +overlays, and undersides. No new renders were made after the run. + +## Reproduction and disposition + +The captured launcher has no execute permission, so reproduction uses `bash` +with the frozen runtime. The command used for this one run was: + +```bash +ck_calibration_old=/home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot +ck_calibration_snapshot=/home/ben/.cache/creature-kernel/pelvis-source-calibration-set-1 +CK_CURRENT_FORM_SURFACE_PYTHON="$ck_calibration_old/runtime/bin/python" PYTHONDONTWRITEBYTECODE=1 \ + bash "$ck_calibration_old/source/experiments/current-form-surface-preview/surface_preview_launcher.sh" \ + "$ck_calibration_snapshot/source/experiments/pelvis-source-calibration/runner.py" run --snapshot "$ck_calibration_snapshot" +``` + +The run requires a fresh prepared output; the existing prepared output is +protected. No tuning or geometry change is authorized by this result. The +bounded next recommendation is a small source-semantics/relationship design +that separates executable joint J from T and makes pelvic-landmark-to-evaluated- +skin obligations explicit, before refinements or bending. This is a +recommendation for Ben's next decision, not authorization or implementation. + +Local artifact root (not checked into the repository): +`/home/ben/.cache/creature-kernel/pelvis-source-calibration-set-1/run`. +It contains `run-report.json`, `artifact-sha-manifest-before.json`, and +`artifact-sha-manifest-after.json`. + +Matched views use identical cameras and pelvis/proximal-thigh crops. Under +that artifact root, `cases/case-05-calibrated_ordinary_human/` and +`cases/case-06-calibrated_upright_anthropomorphic/` each contain `surface.png`, +`landmarks.png`, `surface-underside.png`, `section-evidence.json`, and +`legacy-checks.json`. The five preceding case directories preserve historical +controls. These cache paths are local evidence pointers, not portable +repository links or published artifacts. diff --git a/experiments/pelvis-source-calibration/inputs.py b/experiments/pelvis-source-calibration/inputs.py new file mode 100644 index 0000000..afe6db1 --- /dev/null +++ b/experiments/pelvis-source-calibration/inputs.py @@ -0,0 +1,357 @@ +"""Prepare the one frozen pelvis source-calibration input set. + +This module is intentionally stdlib-only. It reads the predecessor's frozen +``inputs.json`` and the parent-owned protocol, then emits concrete generator +cases. It never imports or calls geometry code. +""" + +from __future__ import annotations + +from copy import deepcopy +import hashlib +import json +import math +import os +from pathlib import Path +from typing import Any, Mapping + + +HERE = Path(__file__).resolve().parent +FROZEN_ROOT = Path("/home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot") +FROZEN_OLD_INPUTS = FROZEN_ROOT / "source/experiments/pelvis-thigh-transition/inputs.json" +PROTOCOL_PATH = HERE / "protocol.json" +OLD_CASE_COUNT = 5 +NORMALIZATION_REASON = "frame/unit normalization" +ANATOMICAL_REASON = "anatomical estimate" +SCHEMA = "creature-kernel.pelvis-source-calibration-inputs.v1" + + +class InputError(ValueError): + """Raised when the frozen source or protocol cannot be admitted.""" + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _strict_json(path: Path) -> tuple[Any, bytes]: + if path.is_symlink() or not path.is_file(): + raise InputError(f"required regular file is unavailable: {path}") + try: + raw = path.read_bytes() + value = json.loads( + raw.decode("utf-8"), + parse_constant=lambda token: (_ for _ in ()).throw(ValueError(token)), + ) + except (OSError, UnicodeDecodeError, json.JSONDecodeError, ValueError) as exc: + raise InputError(f"invalid finite UTF-8 JSON: {path}") from exc + return value, raw + + +def _finite(value: Any, label: str) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise InputError(f"{label} must be numeric") + number = float(value) + if not math.isfinite(number): + raise InputError(f"{label} must be finite") + return number + + +def _canonical(path: str | os.PathLike[str], label: str) -> Path: + result = Path(path) + if not result.is_absolute() or os.path.normpath(str(result)) != str(result): + raise InputError(f"{label} must be an absolute canonical path") + return result + + +def _load_source() -> tuple[dict[str, Any], bytes, str]: + value, raw = _strict_json(FROZEN_OLD_INPUTS) + if not isinstance(value, dict) or not isinstance(value.get("cases"), list): + raise InputError("frozen predecessor inputs must contain a cases list") + if len(value["cases"]) < OLD_CASE_COUNT: + raise InputError("frozen predecessor inputs do not contain five controls") + controls = value["cases"][:OLD_CASE_COUNT] + expected = ( + "standard_neutral_reference", + "compact_broad_short_limb_large_head", + "tall_narrow_long_legged", + "slender_long_limb", + "stocky_broad_chested", + ) + actual = tuple(case.get("id") for case in controls if isinstance(case, dict)) + if actual != expected: + raise InputError(f"frozen control order differs: {actual!r}") + for case in controls: + if not isinstance(case, dict) or not isinstance(case.get("components"), dict): + raise InputError("frozen controls must be complete predecessor case dictionaries") + if not isinstance(case.get("attachments"), dict): + raise InputError("frozen controls must contain attachments") + return value, raw, _sha256(raw) + + +def _load_protocol() -> tuple[dict[str, Any], bytes, str]: + value, raw = _strict_json(PROTOCOL_PATH) + if not isinstance(value, dict) or value.get("version") != "pelvis-source-calibration.single-set.v1": + raise InputError("protocol version is not the declared single-set calibration protocol") + if value.get("historical_controls") != OLD_CASE_COUNT: + raise InputError("protocol historical control count is not five") + budget = value.get("budget") + if budget != {"calibration_sets": 1, "input_refinements": 0, "geometry_changes": 0}: + raise InputError("protocol budget is not the one-set/no-change budget") + transform = value.get("base_transform") + if not isinstance(transform, dict) or set(transform) != {"scale", "translation", "reason"}: + raise InputError("protocol base_transform shape is not admitted") + scale = _finite(transform["scale"], "protocol base_transform.scale") + translation = transform["translation"] + if scale <= 0.0 or not isinstance(translation, list) or len(translation) != 3: + raise InputError("protocol base_transform values are invalid") + [_finite(item, "protocol base_transform.translation") for item in translation] + cases = value.get("cases") + if not isinstance(cases, list) or len(cases) != 2: + raise InputError("protocol must declare exactly two calibration cases") + for case in cases: + if not isinstance(case, dict) or not isinstance(case.get("id"), str): + raise InputError("protocol calibration case is malformed") + for key in ("stations", "hip_radii", "attachments", "reference_landmarks"): + if key not in case: + raise InputError(f"protocol case {case.get('id')} lacks {key}") + return value, raw, _sha256(raw) + + +def _coordinate_component(key: str) -> int | None: + axis = key.rsplit(".", 1)[-1] + return {"x": 0, "y": 1, "z": 2}.get(axis) + + +def _affine_value(value: Any, axis: int | None, scale: float, translation: list[float]) -> float: + number = _finite(value, "source component") + return number * scale + (translation[axis] if axis is not None else 0.0) + + +def _affine_components(source: Mapping[str, Any], scale: float, translation: list[float], reason_detail: str) -> tuple[dict[str, float], list[dict[str, Any]]]: + result: dict[str, float] = {} + ledger: list[dict[str, Any]] = [] + for key, value in source.items(): + if not isinstance(key, str): + raise InputError("component IDs must be strings") + axis = _coordinate_component(key) + old = _finite(value, f"components.{key}") + new = _affine_value(value, axis, scale, translation) + result[key] = float(new) + if new != old: + ledger.append({ + "path": f"/components/{key}", + "old": old, + "new": float(new), + "reason": NORMALIZATION_REASON, + "reason_detail": reason_detail, + "protocol_reason_pointer": "/base_transform/reason", + }) + return result, ledger + + +def _affine_attachments(source: Mapping[str, Any], scale: float, translation: list[float], reason_detail: str) -> tuple[dict[str, Any], list[dict[str, Any]]]: + result: dict[str, Any] = {} + ledger: list[dict[str, Any]] = [] + for side, side_value in source.items(): + if not isinstance(side_value, Mapping): + raise InputError(f"attachments.{side} must be a mapping") + result[side] = {} + for name, point in side_value.items(): + if not isinstance(point, list) or len(point) != 3: + raise InputError(f"attachments.{side}.{name} must be a three-vector") + new_point = [] + for axis, value in enumerate(point): + old = _finite(value, f"attachments.{side}.{name}[{axis}]") + new = old * scale + translation[axis] + new_point.append(float(new)) + if new != old: + ledger.append({ + "path": f"/attachments/{side}/{name}/{axis}", + "old": old, + "new": float(new), + "reason": NORMALIZATION_REASON, + "reason_detail": reason_detail, + "protocol_reason_pointer": "/base_transform/reason", + }) + result[side][name] = new_point + return result, ledger + + +def _record(ledger: list[dict[str, Any]], path: str, old: Any, new: Any, reason: str, *, reason_detail: str | None = None, protocol_reason_pointer: str | None = None) -> None: + old_value = deepcopy(old) + new_value = deepcopy(new) + if old_value != new_value: + entry = {"path": path, "old": old_value, "new": new_value, "reason": reason} + if reason_detail is not None: + entry["reason_detail"] = reason_detail + if protocol_reason_pointer is not None: + entry["protocol_reason_pointer"] = protocol_reason_pointer + ledger.append(entry) + + +def _set_component(components: dict[str, float], ledger: list[dict[str, Any]], key: str, value: Any, *, reason_detail: str, protocol_reason_pointer: str) -> None: + if key not in components: + raise InputError(f"protocol override refers to unknown component: {key}") + old = components[key] + components[key] = float(_finite(value, key)) + _record(ledger, f"/components/{key}", old, components[key], ANATOMICAL_REASON, reason_detail=reason_detail, protocol_reason_pointer=protocol_reason_pointer) + + +def _apply_protocol_case(neutral: Mapping[str, Any], protocol_case: Mapping[str, Any], protocol_index: int, source_sha256: str, protocol_sha256: str, transform: Mapping[str, Any]) -> dict[str, Any]: + scale = _finite(transform["scale"], "base transform scale") + translation = [float(_finite(item, "base transform translation")) for item in transform["translation"]] + components, ledger = _affine_components(neutral["components"], scale, translation, str(transform["reason"])) + attachments, attachment_ledger = _affine_attachments(neutral["attachments"], scale, translation, str(transform["reason"])) + ledger.extend(attachment_ledger) + + stations = protocol_case["stations"] + if not isinstance(stations, Mapping): + raise InputError(f"protocol stations malformed: {protocol_case.get('id')}") + station_reason = str(protocol_case["station_reason"]) + station_reason_pointer = f"/cases/{protocol_index}/station_reason" + for station_name, station in stations.items(): + if not isinstance(station, Mapping) or set(station) != {"centre", "radii"}: + raise InputError(f"protocol station malformed: {station_name}") + centre = station["centre"] + radii = station["radii"] + if not isinstance(centre, list) or len(centre) != 3 or not isinstance(radii, list) or len(radii) != 3: + raise InputError(f"protocol station vectors malformed: {station_name}") + for axis, name in enumerate(("x", "y", "z")): + _set_component(components, ledger, f"stations.{station_name}.C.{name}", centre[axis], reason_detail=station_reason, protocol_reason_pointer=station_reason_pointer) + for name, value in zip(("rL", "rA", "rP"), radii): + _set_component(components, ledger, f"stations.{station_name}.{name}", value, reason_detail=station_reason, protocol_reason_pointer=station_reason_pointer) + + protocol_attachments = protocol_case["attachments"] + if not isinstance(protocol_attachments, Mapping) or set(protocol_attachments) != {"left", "right"}: + raise InputError("protocol attachments must contain left and right") + hip_radii = protocol_case["hip_radii"] + if not isinstance(hip_radii, list) or len(hip_radii) != 3: + raise InputError("protocol hip_radii must be a three-vector") + hip_radii_reason = str(protocol_case["hip_radii_reason"]) + hip_radii_reason_pointer = f"/cases/{protocol_index}/hip_radii_reason" + attachment_reason = str(protocol_case["attachment_reason"]) + attachment_reason_pointer = f"/cases/{protocol_index}/attachment_reason" + for side in ("left", "right"): + side_data = protocol_attachments[side] + if not isinstance(side_data, Mapping) or set(side_data) != {"centre", "knee"}: + raise InputError(f"protocol attachments.{side} is malformed") + for name in ("centre", "knee"): + point = side_data[name] + if not isinstance(point, list) or len(point) != 3: + raise InputError(f"protocol attachments.{side}.{name} is not a three-vector") + for axis, value in enumerate(point): + old = attachments[side][name][axis] + new = float(_finite(value, f"protocol attachments.{side}.{name}[{axis}]")) + attachments[side][name][axis] = new + _record(ledger, f"/attachments/{side}/{name}/{axis}", old, new, ANATOMICAL_REASON, reason_detail=attachment_reason, protocol_reason_pointer=attachment_reason_pointer) + for axis, name in enumerate(("x", "y", "z")): + _set_component(components, ledger, f"hips.{side}.P_s.{name}", side_data["centre"][axis], reason_detail=attachment_reason, protocol_reason_pointer=attachment_reason_pointer) + for name, value in zip(("r_x", "r_y", "r_z"), hip_radii): + _set_component(components, ledger, f"hips.{side}.{name}", value, reason_detail=hip_radii_reason, protocol_reason_pointer=hip_radii_reason_pointer) + + case_id = protocol_case["id"] + return { + "id": case_id, + "role": protocol_case["role"], + "components": components, + "attachments": attachments, + "provenance": { + "source": {"path": "frozen old inputs.json", "sha256": source_sha256}, + "base_case": "standard_neutral_reference", + "base_transform": { + "scale": scale, + "translation": translation, + "reason": transform["reason"], + }, + "protocol_case_id": case_id, + "change_ledger": ledger, + "protocol_sha256": protocol_sha256, + "reference_landmarks_excluded": True, + "claim": "single declared calibration input; no geometry or topology variation", + }, + } + + +def build_document() -> dict[str, Any]: + """Return the concrete seven-case document without constructing geometry.""" + source, _source_raw, source_sha256 = _load_source() + protocol, _protocol_raw, protocol_sha256 = _load_protocol() + controls = deepcopy(source["cases"][:OLD_CASE_COUNT]) + neutral = controls[0] + transform = protocol["base_transform"] + new_cases = [ + _apply_protocol_case(neutral, case, index, source_sha256, protocol_sha256, transform) + for index, case in enumerate(protocol["cases"]) + ] + cases = [*controls, *new_cases] + component_ids = list(source.get("component_ids", [])) + if not component_ids or set(neutral["components"]) != set(component_ids): + raise InputError("frozen neutral component inventory is inconsistent") + for case in new_cases: + if set(case["components"]) != set(component_ids): + raise InputError(f"calibration case component inventory differs: {case['id']}") + if "reference_landmarks" in case or "joint_left" in json.dumps(case, sort_keys=True): + raise InputError(f"reference-only landmark leaked into generator case: {case['id']}") + return { + "schema": SCHEMA, + "source": { + "path": str(FROZEN_OLD_INPUTS), + "sha256": source_sha256, + "historical_case_count": OLD_CASE_COUNT, + }, + "protocol": { + "path": "experiments/pelvis-source-calibration/protocol.json", + "sha256": protocol_sha256, + }, + "component_ids": component_ids, + "case_ids": [case["id"] for case in cases], + "historical_controls": [case["id"] for case in controls], + "calibration_cases": [case["id"] for case in new_cases], + "display_normalization": { + "scale": float(transform["scale"]), + "translation": [float(item) for item in transform["translation"]], + "reason": transform["reason"], + "applies_to": "historical display copies only; saved/evaluated meshes remain native generator output", + }, + "cases": cases, + "immutability": "one concrete seven-case set; no input refinement or geometry tuning", + } + + +def json_bytes(document: Mapping[str, Any]) -> bytes: + try: + return (json.dumps(document, sort_keys=True, indent=2, separators=(",", ": "), ensure_ascii=True, allow_nan=False) + "\n").encode("utf-8") + except (TypeError, ValueError, OverflowError) as exc: + raise InputError("concrete inputs are not finite deterministic JSON") from exc + + +def prepare(output: str | os.PathLike[str] | None = None) -> dict[str, Any]: + """Generate the concrete document and optionally write it to an absent path.""" + document = build_document() + if output is None: + return document + path = _canonical(output, "inputs output") + if path.exists() or path.is_symlink(): + raise InputError(f"refusing to replace existing concrete inputs: {path}") + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(json_bytes(document)) + return document + + +prepare_inputs = build_document + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Prepare frozen pelvis calibration inputs") + parser.add_argument("--output", required=True) + args = parser.parse_args() + prepare(args.output) + station_reason = str(protocol_case["station_reason"]) + station_reason_pointer = f"/cases/{protocol_index}/station_reason" + hip_radii_reason = str(protocol_case["hip_radii_reason"]) + hip_radii_reason_pointer = f"/cases/{protocol_index}/hip_radii_reason" + attachment_reason = str(protocol_case["attachment_reason"]) + attachment_reason_pointer = f"/cases/{protocol_index}/attachment_reason" diff --git a/experiments/pelvis-source-calibration/protocol.json b/experiments/pelvis-source-calibration/protocol.json new file mode 100644 index 0000000..398ad91 --- /dev/null +++ b/experiments/pelvis-source-calibration/protocol.json @@ -0,0 +1,88 @@ +{ + "version": "pelvis-source-calibration.single-set.v1", + "declared_before_generation": "2026-09-05", + "budget": {"calibration_sets": 1, "input_refinements": 0, "geometry_changes": 0}, + "construction_sha256": "7fd457e2206165eb5e404ce81732f4157234a2e13a64008d96ae75d6abcf5cdb", + "frozen_dependency_root": "/home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot", + "historical_controls": 5, + "base_transform": {"scale": 0.16, "translation": [0.0, 0.16, 0.0], "reason": "Normalize legacy neutral dimensions into metres and place the comparison origin at the intended joint-centre height; a display/input frame convention, not an anatomical inference about the old source."}, + "view_bounds": [[-0.32, -0.27, -0.22], [0.32, 0.34, 0.22]], + "historical_display_transform": {"scale": 0.16, "translation": [0.0, 0.16, 0.0]}, + "section_samples": 41, + "section_y_limits": [-0.24, 0.16], + "joint_to_thigh_segment_samples": [0.0, 0.25, 0.5, 0.75, 1.0], + "thigh_axis_segment_samples": [0.0, 0.15, 0.30, 0.45], + "reference_sources": [ + {"url": "https://openstax.org/books/anatomy-and-physiology-2e/pages/8-3-the-pelvic-girdle-and-pelvis", "role": "Skeletal landmark relationships, not numerical population measurements."}, + {"url": "https://www.proko.com/course-lesson/how-to-draw-legs-bone-anatomy-for-artists", "role": "Artist proportion guide: roughly quarter-height femur; femoral head is distinct from lateral trochanter/shaft; inward thigh direction. Approximate guide, not anthropometry."}, + {"url": "https://www.disneyanimation.com/publications/flesh-flab-and-fascia-simulation-on-zootopia/", "role": "Professional stylized upright animal-body reference: animal character and stylized anatomy coexist. No numerical coordinates are extracted; the experimental proportions below are our explicit design hypothesis, not Disney measurements or an architecture adoption."} + ], + "cases": [ + { + "id": "calibrated_ordinary_human", + "role": "Ordinary-adult lower-body structural calibration, not a full human fixture or population coverage.", + "nominal_stature_m": 1.75, + "reason": "Adult-like pelvis and femur proportions; separate medial/proximal hip joint from lateral/subtrochanteric thigh-start proxy. Preserve inherited upper context after the declared frame normalization; it is not newly calibrated anatomy.", + "uncertainty": "Hand-estimated reference interpretation: joint position about +/-0.02 m; thigh/pelvic landmarks about +/-0.025 m; skin dimensions about +/-0.03 m. Not measured-subject or clinical data, and no post-render adjustment is allowed.", + "stations": { + "lower_pelvis": {"centre": [0.0, 0.01, 0.0], "radii": [0.17, 0.115, 0.125]}, + "upper_pelvis": {"centre": [0.0, 0.10, 0.0], "radii": [0.145, 0.105, 0.11]}, + "lower_abdomen": {"centre": [0.0, 0.17, 0.0], "radii": [0.135, 0.095, 0.095]}, + "waist_abdomen": {"centre": [0.0, 0.24, 0.0], "radii": [0.12, 0.09, 0.09]} + }, + "station_reason": "Pelvic envelope is centred near the acetabular region, widest below the iliac crest; abdomen ascends above it. These remain envelope stations, not newly renamed bone landmarks. Depth includes posterior soft-tissue allowance. Values are one approximate adult-like calibration hypothesis.", + "hip_radii": [0.075, 0.06, 0.085], + "hip_radii_reason": "Approximate proximal-thigh skin half-width/depth and vertical support scale; r_y remains a construction influence scale, not a bone length or hip-joint radius.", + "attachments": { + "left": {"centre": [-0.12, -0.05, 0.0], "knee": [-0.08, -0.43, 0.0]}, + "right": {"centre": [0.12, -0.05, 0.0], "knee": [0.08, -0.43, 0.0]} + }, + "attachment_reason": "Thigh start is a proximal shaft/profile-start proxy, lateral and inferior to joint centre; knees are modestly medial. Joint-to-knee distance about 0.43 m is close to a quarter of nominal stature. T-to-knee is deliberately shorter and is not substituted for femur length.", + "reference_landmarks": { + "joint_left": [-0.085, 0.0, 0.0], "joint_right": [0.085, 0.0, 0.0], + "crest_left": [-0.135, 0.14, 0.0], "crest_right": [0.135, 0.14, 0.0], + "asis_left": [-0.115, 0.105, 0.075], "asis_right": [0.115, 0.105, 0.075], + "psis_left": [-0.045, 0.115, -0.09], "psis_right": [0.045, 0.115, -0.09], + "pubic_symphysis": [0.0, -0.07, 0.075], + "trochanter_left": [-0.16, -0.04, 0.0], "trochanter_right": [0.16, -0.04, 0.0] + }, + "expected_skin_bifurcation_y_interval": [-0.12, -0.04] + }, + { + "id": "calibrated_upright_anthropomorphic", + "role": "Stylized upright mammal lower-body calibration with broader pelvis and shorter femur relative to stature; no species-universal anatomy claim.", + "nominal_stature_m": 1.8, + "reason": "Equally important intended body family, tested through the SAME construction. Retain coherent upright pelvic support while allowing a broader/shorter proximal-leg design. Distal stance, animal head, fur and tail are absent, not claimed tested.", + "uncertainty": "Artist-design hypothesis rather than biological anthropometry: landmark positions about +/-0.03 m; proportional design allowances about +/-20%. It is not a numeric reconstruction of any named film character.", + "stations": { + "lower_pelvis": {"centre": [0.0, 0.02, 0.0], "radii": [0.19, 0.125, 0.14]}, + "upper_pelvis": {"centre": [0.0, 0.11, 0.0], "radii": [0.165, 0.115, 0.12]}, + "lower_abdomen": {"centre": [0.0, 0.185, 0.0], "radii": [0.15, 0.105, 0.105]}, + "waist_abdomen": {"centre": [0.0, 0.25, 0.0], "radii": [0.135, 0.10, 0.10]} + }, + "station_reason": "Deliberately broader and deeper upright pelvic envelope than the human case, while preserving the crest/joint/thigh ordering; stations remain skin-envelope controls, not skeletal landmarks.", + "hip_radii": [0.085, 0.065, 0.095], + "hip_radii_reason": "Broader proximal soft-tissue envelope for this stylized case, paired with a shorter thigh; no local mesh repair or species branch.", + "attachments": { + "left": {"centre": [-0.135, -0.045, 0.0], "knee": [-0.10, -0.355, 0.025]}, + "right": {"centre": [0.135, -0.045, 0.0], "knee": [0.10, -0.355, 0.025]} + }, + "attachment_reason": "Distinct lateral/inferior thigh start, modest inward and forward knee direction, joint-to-knee about 0.356 m. A stylized shorter femur is intentional; future distal anatomy must not be inferred from this local experiment.", + "reference_landmarks": { + "joint_left": [-0.095, 0.0, -0.005], "joint_right": [0.095, 0.0, -0.005], + "crest_left": [-0.15, 0.15, 0.0], "crest_right": [0.15, 0.15, 0.0], + "asis_left": [-0.13, 0.115, 0.08], "asis_right": [0.13, 0.115, 0.08], + "psis_left": [-0.05, 0.125, -0.10], "psis_right": [0.05, 0.125, -0.10], + "pubic_symphysis": [0.0, -0.065, 0.085], + "trochanter_left": [-0.18, -0.035, 0.0], "trochanter_right": [0.18, -0.035, 0.0] + }, + "expected_skin_bifurcation_y_interval": [-0.115, -0.035] + } + ], + "interpretation": { + "reference_landmarks": "Diagnostic targets only. J is NOT executable in this frozen generator; do not smuggle J into centre or claim J-to-skin causality.", + "skin_bifurcation": "Observed connected-section transition to two disjoint thigh contours, not a hip centre, source landmark, or exact universal crotch plane.", + "old_containment": "Original individual-side ray gate and rejected verdict are preserved. New joined-surface cross-sections diagnose placement only; they do not retroactively pass the old candidate.", + "stop": "Stop after one set and comparison even if proportions improve. No tuning or shape repair. If independent executable joint/landmark relations require code changes, report that obstruction explicitly." + } +} diff --git a/experiments/pelvis-source-calibration/runner.py b/experiments/pelvis-source-calibration/runner.py new file mode 100644 index 0000000..b43a0bf --- /dev/null +++ b/experiments/pelvis-source-calibration/runner.py @@ -0,0 +1,863 @@ +"""Prepare and run the bounded pelvis source-calibration evidence set. + +``prepare`` is stdlib-only and makes an absent, immutable source snapshot. +``run`` is deliberately fail-closed: it must be invoked through the captured +runner and the frozen runtime, and it never imports geometry from the mutable +worktree. The runner records diagnostics; it does not accept a policy gate. +""" + +from __future__ import annotations + +import argparse +from collections import defaultdict, deque +import hashlib +import importlib.util +import json +import math +import os +from pathlib import Path +import platform +import shutil +import stat +import sys +from typing import Any, Iterable, Mapping + + +HERE = Path(__file__).resolve().parent +FROZEN_ROOT = Path("/home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-2-snapshot") +CALIBRATION_RELATIVE = Path("experiments/pelvis-source-calibration") +CAPTURE_NAMES = ( + "inputs.py", + "runner.py", + "section_diagnostic.py", + "README.md", + "protocol.json", + "tests/test_inputs.py", + "tests/test_section_diagnostic.py", +) +CONTROL_IDS = ( + "standard_neutral_reference", + "compact_broad_short_limb_large_head", + "tall_narrow_long_legged", + "slender_long_limb", + "stocky_broad_chested", +) +RUNNER_SCHEMA = "creature-kernel.pelvis-source-calibration-run.v1" + + +class RunnerError(ValueError): + """Raised for snapshot, runtime, or evidence-contract failures.""" + + +def _fail(message: str) -> "NoReturn": + raise RunnerError(message) + + +def _sha256_bytes(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def _canonical(path: str | os.PathLike[str], label: str) -> Path: + value = Path(path) + if not value.is_absolute() or os.path.normpath(str(value)) != str(value): + _fail(f"{label} must be an absolute canonical path") + return value + + +def _regular(path: Path, label: str) -> None: + try: + info = path.lstat() + except OSError as exc: + _fail(f"{label} is unavailable: {path}") + if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode): + _fail(f"{label} must be a regular non-symlink file: {path}") + + +def _strict_json(path: Path) -> tuple[Any, bytes]: + _regular(path, "JSON input") + try: + raw = path.read_bytes() + value = json.loads( + raw.decode("utf-8"), + parse_constant=lambda token: (_ for _ in ()).throw(ValueError(token)), + ) + except (OSError, UnicodeDecodeError, json.JSONDecodeError, ValueError) as exc: + _fail(f"invalid finite UTF-8 JSON: {path}") + return value, raw + + +def _json_bytes(value: Any) -> bytes: + try: + return (json.dumps(value, sort_keys=True, indent=2, separators=(",", ": "), ensure_ascii=True, allow_nan=False) + "\n").encode("utf-8") + except (TypeError, ValueError, OverflowError) as exc: + raise RunnerError("value is not deterministic finite JSON") from exc + + +def _write_json(path: Path, value: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(_json_bytes(value)) + + +def _inventory(root: Path, paths: Iterable[Path]) -> list[dict[str, Any]]: + rows = [] + for path in sorted(paths, key=lambda item: item.relative_to(root).as_posix().encode("utf-8")): + _regular(path, "inventory entry") + rows.append({ + "path": path.relative_to(root).as_posix(), + "bytes": path.stat().st_size, + "sha256": _sha256_file(path), + }) + return rows + + +def _inventory_digest(rows: Any) -> str: + return _sha256_bytes(json.dumps(rows, sort_keys=True, separators=(",", ":")).encode("utf-8")) + + +def _source_entries(manifest: Mapping[str, Any], root: Path) -> list[dict[str, Any]]: + entries = manifest.get("source") + if not isinstance(entries, list) or not entries: + _fail("frozen manifest source inventory is missing") + verified = [] + for row in entries: + if not isinstance(row, Mapping) or set(row) != {"bytes", "path", "sha256", "snapshot_path"}: + _fail("frozen manifest source row does not match its actual schema") + relative = Path(str(row["path"])) + if relative.is_absolute() or ".." in relative.parts: + _fail(f"frozen source row is not relative: {relative}") + path = root / "source" / relative + _regular(path, "frozen source entry") + actual = {"bytes": path.stat().st_size, "sha256": _sha256_file(path)} + if actual != {"bytes": row["bytes"], "sha256": row["sha256"]}: + _fail(f"frozen source entry drifted: {relative}") + verified.append(dict(row)) + return verified + + +def _runtime_entries(manifest: Mapping[str, Any], root: Path) -> tuple[list[dict[str, Any]], dict[str, Any]]: + runtime = manifest.get("runtime") + if not isinstance(runtime, Mapping): + _fail("frozen manifest runtime record is missing") + required = {"clone_root", "executable", "candidate_environment", "files"} + if not required.issubset(runtime): + _fail("frozen manifest runtime record does not match its actual schema") + files = runtime["files"] + if not isinstance(files, list) or not files: + _fail("frozen manifest runtime file inventory is missing") + verified = [] + runtime_root = root / "runtime" + for row in files: + if not isinstance(row, Mapping) or set(row) != {"bytes", "path", "runtime_sha256", "sha256", "source_path"}: + _fail("frozen manifest runtime row does not match its actual schema") + relative = Path(str(row["path"])) + if relative.is_absolute() or ".." in relative.parts: + _fail(f"frozen runtime row is not relative: {relative}") + path = runtime_root / relative + _regular(path, "frozen runtime entry") + actual = {"bytes": path.stat().st_size, "runtime_sha256": _sha256_file(path)} + if actual != {"bytes": row["bytes"], "runtime_sha256": row["runtime_sha256"]}: + _fail(f"frozen runtime entry drifted: {relative}") + verified.append(dict(row)) + return verified, dict(runtime) + + +def _dependency_identity(root: Path) -> dict[str, Any]: + root = _canonical(root, "frozen dependency root") + manifest_path = root / "manifest.json" + environment_path = root / "environment.json" + manifest, manifest_raw = _strict_json(manifest_path) + environment, _environment_raw = _strict_json(environment_path) + if not isinstance(manifest, Mapping) or manifest.get("schema") != "pelvis-thigh-transition-source-snapshot.v1": + _fail("frozen dependency manifest schema is not pelvis-thigh-transition-source-snapshot.v1") + if not isinstance(environment, Mapping): + _fail("frozen environment record is not an object") + sources = _source_entries(manifest, root) + runtime_files, runtime = _runtime_entries(manifest, root) + if Path(str(runtime["clone_root"])).resolve() != (root / "runtime").resolve(): + _fail("frozen runtime clone_root does not match the selected dependency root") + executable = root / "runtime/bin/python" + if Path(str(runtime["executable"])).resolve() != executable.resolve(): + _fail("frozen runtime executable does not match runtime/bin/python") + source_packages = runtime.get("source_packages_before") + source_packages_after = runtime.get("source_packages_after") + if not isinstance(source_packages, Mapping) or not isinstance(source_packages_after, Mapping): + _fail("frozen runtime package inventories are missing") + if source_packages.get("inventory_sha256") != source_packages_after.get("inventory_sha256"): + _fail("frozen runtime package inventory changed between recorded copies") + source_by_path = {row["path"]: row for row in sources} + construction = source_by_path.get("experiments/pelvis-thigh-transition/construction.py") + if construction is None: + _fail("frozen manifest lacks old pelvis construction.py") + return { + "root": str(root), + "manifest": { + "path": str(manifest_path), + "sha256": _sha256_bytes(manifest_raw), + "schema": manifest["schema"], + "source_root": manifest.get("source_root"), + "source_entries": sources, + "source_inventory_sha256": _inventory_digest(sources), + "construction": dict(construction), + }, + "runtime": { + "clone_root": runtime["clone_root"], + "executable": runtime["executable"], + "candidate_environment": runtime["candidate_environment"], + "file_count": len(runtime_files), + "files_inventory_sha256": _inventory_digest(runtime_files), + "files": runtime_files, + }, + "environment": { + "path": str(environment_path), + "python_version": environment.get("python_version"), + "python_implementation": environment.get("python_implementation"), + "sys_prefix": environment.get("sys_prefix"), + "package_versions": environment.get("package_versions"), + "compiled_import_errors": environment.get("compiled_import_errors"), + "limitations": [ + "The prepare phase is stdlib-only and does not load compiled geometry/render dependencies.", + "The run phase is bound to the recorded frozen runtime and source snapshot.", + ], + }, + } + + +def _load_local_inputs(path: Path) -> Any: + spec = importlib.util.spec_from_file_location("ck_calibration_inputs", path) + if spec is None or spec.loader is None: + _fail(f"unable to load input preparer: {path}") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _copy_checked(source: Path, target: Path) -> dict[str, Any]: + _regular(source, "capture source") + before = {"bytes": source.stat().st_size, "sha256": _sha256_file(source)} + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, target) + _regular(target, "captured source") + after = {"bytes": target.stat().st_size, "sha256": _sha256_file(target)} + if after != before: + _fail(f"capture differs from source-before identity: {source}") + return {"path": target.relative_to(target.parents[2]).as_posix(), **before} + + +def prepare(output: str | os.PathLike[str]) -> dict[str, Any]: + """Capture the calibration source and concrete cases into an absent path.""" + sys.dont_write_bytecode = True + output_path = _canonical(output, "prepare output") + if output_path.exists() or output_path.is_symlink(): + _fail(f"prepare output must be absent: {output_path}") + if not output_path.parent.is_dir() or output_path.parent.is_symlink(): + _fail("prepare output parent must be an existing regular directory") + + input_module = _load_local_inputs(HERE / "inputs.py") + protocol_path = HERE / "protocol.json" + protocol, protocol_raw = _strict_json(protocol_path) + frozen_root = Path(str(protocol["frozen_dependency_root"])) if isinstance(protocol, Mapping) else FROZEN_ROOT + dependency_before = _dependency_identity(frozen_root) + source_paths = [HERE / name for name in CAPTURE_NAMES] + source_before = _inventory(HERE, source_paths) + document = input_module.build_document() + concrete = input_module.json_bytes(document) + + output_path.mkdir() + captured_root = output_path / "source" / CALIBRATION_RELATIVE + captured_rows = [] + for source in source_paths: + target = captured_root / source.relative_to(HERE) + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, target) + _regular(target, "captured source") + captured_rows.append({ + "path": target.relative_to(output_path / "source").as_posix(), + "bytes": target.stat().st_size, + "sha256": _sha256_file(target), + }) + input_target = captured_root / "inputs.json" + input_target.write_bytes(concrete) + captured_rows.append({ + "path": input_target.relative_to(output_path / "source").as_posix(), + "bytes": len(concrete), + "sha256": _sha256_bytes(concrete), + }) + _write_json(output_path / "source/manifest.json", { + "schema": "creature-kernel.pelvis-source-calibration-captured-source.v1", + "files": sorted(captured_rows, key=lambda row: row["path"].encode("utf-8")), + }) + + source_after = _inventory(HERE, source_paths) + dependency_after = _dependency_identity(frozen_root) + if source_before != source_after: + _fail("calibration source changed while being captured") + if dependency_before != dependency_after: + _fail("frozen dependency changed while preparing the snapshot") + report = { + "schema": "creature-kernel.pelvis-source-calibration-prepare.v1", + "status": "prepared", + "geometry_executed": False, + "render_executed": False, + "protocol": {"path": "source/experiments/pelvis-source-calibration/protocol.json", "sha256": _sha256_bytes(protocol_raw)}, + "concrete_inputs": {"path": "source/experiments/pelvis-source-calibration/inputs.json", "sha256": _sha256_bytes(concrete), "case_count": len(document["cases"])}, + "captured_source": {"files": captured_rows, "before": source_before, "after": source_after}, + "frozen_dependency": {"before": dependency_before, "after": dependency_after, "reused_without_copy": True}, + "limitations": [ + "No geometry, topology, tuning, renderer, or diagnostic body was executed.", + "The old dependency source and runtime remain referenced by their frozen absolute snapshot and are verified by manifest hashes.", + ], + } + _write_json(output_path / "prepare-report.json", report) + return report + + +def _load_captured_source(snapshot: Path) -> tuple[dict[str, Any], bytes]: + source_root = snapshot / "source" + manifest_path = source_root / "manifest.json" + manifest, raw = _strict_json(manifest_path) + if not isinstance(manifest, Mapping) or manifest.get("schema") != "creature-kernel.pelvis-source-calibration-captured-source.v1": + _fail("captured source manifest schema is not admitted") + rows = manifest.get("files") + if not isinstance(rows, list) or not rows: + _fail("captured source manifest has no files") + for row in rows: + if not isinstance(row, Mapping) or set(row) != {"bytes", "path", "sha256"}: + _fail("captured source manifest row is malformed") + path = source_root / str(row["path"]) + _regular(path, "captured source entry") + if {"bytes": path.stat().st_size, "sha256": _sha256_file(path)} != {"bytes": row["bytes"], "sha256": row["sha256"]}: + _fail(f"captured source entry drifted: {row['path']}") + required = {f"{CALIBRATION_RELATIVE.as_posix()}/{name}" for name in (*CAPTURE_NAMES, "inputs.json")} + if not required.issubset({str(row["path"]) for row in rows}): + _fail("captured source does not contain the complete calibration set") + return dict(manifest), raw + + +def _load_module(path: Path, name: str) -> Any: + _regular(path, "captured geometry/render module") + spec = importlib.util.spec_from_file_location(name, path) + if spec is None or spec.loader is None: + _fail(f"unable to load captured module: {path}") + module = importlib.util.module_from_spec(spec) + # Some frozen modules (notably dataclasses users) inspect their own + # sys.modules entry while executing. Register before exec, then remove a + # partial module if import fails. + sys.modules[name] = module + try: + spec.loader.exec_module(module) + except Exception: + if sys.modules.get(name) is module: + sys.modules.pop(name, None) + raise + if Path(module.__file__).resolve() != path.resolve(): + _fail(f"module resolved away from its frozen path: {name}") + return module + + +def _bounded(value: Any, depth: int = 0) -> Any: + if depth > 32: + _fail("diagnostic value is too deeply nested") + if value is None or isinstance(value, (str, bool, int)): + return value + if isinstance(value, float): + if not math.isfinite(value): + _fail("diagnostic value is non-finite") + return value + if isinstance(value, Mapping): + return {str(key): _bounded(item, depth + 1) for key, item in sorted(value.items(), key=lambda pair: str(pair[0]))} + if isinstance(value, (list, tuple)): + return [_bounded(item, depth + 1) for item in value] + # Runtime/library scalar conversion is admitted only for the known numpy + # scalar/array types used by the frozen renderer. Unknown objects must + # fail rather than become an untraceable string in evidence. + if type(value).__module__.split(".", 1)[0] == "numpy": + if hasattr(value, "tolist"): + return _bounded(value.tolist(), depth + 1) + if hasattr(value, "item"): + return _bounded(value.item(), depth + 1) + _fail(f"unsupported diagnostic serialization type: {type(value).__name__}") + + +def _mesh_arrays(mesh: Any) -> tuple[list[list[float]], list[list[int]]]: + if not isinstance(mesh, Mapping): + _fail("evaluated level is not a mapping") + vertices = mesh.get("vertices") + quads = mesh.get("quads") + if not isinstance(vertices, (list, tuple)) or not isinstance(quads, (list, tuple)): + _fail("evaluated level lacks concrete vertices/quads") + points = [] + for index, point in enumerate(vertices): + if not isinstance(point, (list, tuple)) or len(point) != 3: + _fail(f"mesh vertex {index} is not a vector3") + converted = [float(value) for value in point] + if not all(math.isfinite(value) for value in converted): + _fail(f"mesh vertex {index} is non-finite") + points.append(converted) + faces = [] + for index, face in enumerate(quads): + if not isinstance(face, (list, tuple)) or len(face) != 4 or not all(type(value) is int for value in face): + _fail(f"mesh quad {index} is not an integer quad") + converted = list(face) + if len(set(converted)) != 4 or any(value < 0 or value >= len(points) for value in converted): + _fail(f"mesh quad {index} has invalid indices") + faces.append(converted) + if not points or not faces: + _fail("mesh level is empty") + return points, faces + + +def _structural_stats(points: list[list[float]], faces: list[list[int]]) -> dict[str, Any]: + edges: dict[tuple[int, int], int] = defaultdict(int) + face_graph = [[] for _ in faces] + edge_faces: dict[tuple[int, int], list[int]] = defaultdict(list) + for face_index, face in enumerate(faces): + for offset in range(4): + edge = tuple(sorted((face[offset], face[(offset + 1) % 4]))) + edges[edge] += 1 + edge_faces[edge].append(face_index) + for adjacent in edge_faces.values(): + for left in adjacent: + for right in adjacent: + if left != right: + face_graph[left].append(right) + components = 0 + unseen = set(range(len(faces))) + while unseen: + components += 1 + start = unseen.pop() + queue = deque([start]) + while queue: + for neighbour in face_graph[queue.popleft()]: + if neighbour in unseen: + unseen.remove(neighbour) + queue.append(neighbour) + lengths = [] + for (left, right), count in edges.items(): + if count: + lengths.append(math.dist(points[left], points[right])) + return { + "classification": "structural_diagnostic_only", + "policy_acceptance": "not_evaluated", + "vertex_count": len(points), + "quad_count": len(faces), + "finite_vertices": True, + "valid_quad_indices": True, + "boundary_edge_count": sum(count == 1 for count in edges.values()), + "nonmanifold_edge_count": sum(count > 2 for count in edges.values()), + "connected_face_components": components, + "edge_length_min": min(lengths), + "edge_length_max": max(lengths), + } + + +def _affine_points(points: list[list[float]], scale: float, translation: list[float]) -> list[list[float]]: + return [[float(value * scale + translation[axis]) for axis, value in enumerate(point)] for point in points] + + +def _display_case(case: Mapping[str, Any], points: list[list[float]], protocol: Mapping[str, Any]) -> tuple[list[list[float]], float, str]: + if case["id"] in CONTROL_IDS: + transform = protocol["historical_display_transform"] + return _affine_points(points, float(transform["scale"]), [float(value) for value in transform["translation"]]), float(transform["scale"]), "historical_display_affine" + return points, 1.0, "native_calibration_frame" + + +def _overlays(case: Mapping[str, Any], protocol_case: Mapping[str, Any] | None, display_mode: str, protocol: Mapping[str, Any]) -> list[dict[str, Any]]: + overlays: list[dict[str, Any]] = [] + colours = {"left": [48, 112, 210], "right": [210, 72, 56]} + for side in ("left", "right"): + start = list(case["attachments"][side]["centre"]) + end = list(case["attachments"][side]["knee"]) + overlays.append({"start": start, "end": end, "color": [232, 126, 34], "label": f"T-K {side}"}) + if protocol_case is not None: + landmarks = protocol_case["reference_landmarks"] + joint = list(landmarks[f"joint_{side}"]) + thigh = list(case["attachments"][side]["centre"]) + overlays.append({"start": joint, "end": thigh, "color": [132, 70, 190], "label": f"J-T {side}"}) + if protocol_case is not None: + labels = { + "joint_left": "J left", "joint_right": "J right", + "crest_left": "crest left", "crest_right": "crest right", + "asis_left": "ASIS left", "asis_right": "ASIS right", + "psis_left": "PSIS left", "psis_right": "PSIS right", + "pubic_symphysis": "pubis", + "trochanter_left": "trochanter left", "trochanter_right": "trochanter right", + } + for name, value in protocol_case["reference_landmarks"].items(): + point = list(value) + overlays.append({"start": point, "end": point, "color": [30, 150, 90], "label": labels.get(name, name)}) + for side in ("left", "right"): + point = list(case["attachments"][side]["centre"]) + overlays.append({"start": point, "end": point, "color": colours[side], "label": f"T {side}"}) + if display_mode == "historical_display_affine": + display_transform = protocol["historical_display_transform"] + display_scale = float(display_transform["scale"]) + display_translation = [float(value) for value in display_transform["translation"]] + transform = lambda point: [value * display_scale + display_translation[axis] for axis, value in enumerate(point)] + overlays = [{**item, "start": transform(item["start"]), "end": transform(item["end"])} for item in overlays] + return overlays + + +def _point_summary(value: Mapping[str, Any]) -> dict[str, Any]: + result = {key: value[key] for key in ("status", "classification", "reason", "parity", "inside_contour_count", "boundary_distance") if key in value} + if "signed_boundary_distance" in value: + result["signed_boundary_distance"] = value["signed_boundary_distance"] + result["nearest_boundary_distance"] = value.get("boundary_distance") + result["nearest_boundary_distance_signed"] = value.get("signed_boundary_distance") + return _bounded(result) + + +def _section_summary(value: Mapping[str, Any], query_y: float) -> dict[str, Any]: + diagnostics = value.get("diagnostics") + closed = bool(diagnostics.get("closed_graph")) if isinstance(diagnostics, Mapping) else bool(value.get("closed_graph", False)) + contours = value.get("closed_contours") if isinstance(value.get("closed_contours"), list) else value.get("contours", []) + contour_bounds = [] + for contour in contours if isinstance(contours, list) else []: + if not isinstance(contour, list) or not contour: + continue + try: + xs = [float(point[0]) for point in contour] + zs = [float(point[1]) for point in contour] + contour_bounds.append({"min_x": min(xs), "max_x": max(xs), "min_z": min(zs), "max_z": max(zs)}) + except (TypeError, ValueError, IndexError): + contour_bounds = [] + break + return { + "y": query_y, + "status": value.get("status"), + "classification": value.get("classification"), + "closed": closed, + "loop_count": int(value.get("closed_count", 0) or 0), + "usable": bool(value.get("usable", False)), + "contour_bounds": contour_bounds, + "diagnostics": _bounded(value.get("diagnostics", {})), + } + + +def _intervals(rows: list[Mapping[str, Any]]) -> dict[str, Any]: + def nested(bounds: Any) -> bool: + if not isinstance(bounds, list) or len(bounds) != 2: + return True + first, second = bounds + if not isinstance(first, Mapping) or not isinstance(second, Mapping): + return True + return ((first["min_x"] <= second["min_x"] and first["max_x"] >= second["max_x"] and first["min_z"] <= second["min_z"] and first["max_z"] >= second["max_z"]) or + (second["min_x"] <= first["min_x"] and second["max_x"] >= first["max_x"] and second["min_z"] <= first["min_z"] and second["max_z"] >= first["max_z"])) + + intervals: list[list[float]] = [] + current: list[float] | None = None + for row in rows: + qualifies = bool(row.get("usable")) and row.get("status") == "CLOSED_SECTION" and int(row.get("loop_count", 0)) == 2 and not nested(row.get("contour_bounds")) + y = float(row["y"]) + if qualifies and current is None: + current = [y, y] + elif qualifies and current is not None: + current[1] = y + elif current is not None: + intervals.append(current) + current = None + if current is not None: + intervals.append(current) + brackets = [] + for first, second in zip(rows, rows[1:]): + counts = {int(first.get("loop_count", 0)), int(second.get("loop_count", 0))} + if counts == {1, 2}: + brackets.append({"y": [float(first["y"]), float(second["y"])], "loop_counts": [int(first.get("loop_count", 0)), int(second.get("loop_count", 0))]}) + return {"two_loop_ranges": intervals, "one_to_two_boundary_brackets": brackets} + + +def _diagnostics(section_module: Any, points: list[list[float]], faces: list[list[int]], case: Mapping[str, Any], protocol_case: Mapping[str, Any] | None, protocol: Mapping[str, Any], scale: float) -> dict[str, Any]: + inspect = section_module.inspect_section + evaluate = section_module.evaluate_point + low, high = (float(value) for value in protocol["section_y_limits"]) + sample_count = int(protocol["section_samples"]) + ys = [low + (high - low) * index / (sample_count - 1) for index in range(sample_count)] + raw_sections = [] + sections = [] + for y in ys: + raw = inspect(points, faces, y, scale) + raw_sections.append({"query_y": y, "result": _bounded(raw)}) + sections.append(_section_summary(raw, y)) + + if case["id"] in CONTROL_IDS: + display_transform = protocol["historical_display_transform"] + display_scale = float(display_transform["scale"]) + display_translation = [float(value) for value in display_transform["translation"]] + else: + display_scale = 1.0 + display_translation = [0.0, 0.0, 0.0] + + def query_point(value: list[float]) -> list[float]: + return [float(item * display_scale + display_translation[axis]) for axis, item in enumerate(value)] + + raw_points = [] + + def point(point: list[float]) -> dict[str, Any]: + query = query_point(point) + raw = evaluate(points, faces, query, scale) + raw_points.append({"point": query, "result": _bounded(raw)}) + return _point_summary(raw) + + attachments = case["attachments"] + t_k = {} + for side in ("left", "right"): + start = [float(value) for value in attachments[side]["centre"]] + knee = [float(value) for value in attachments[side]["knee"]] + fractions = [float(value) for value in protocol["thigh_axis_segment_samples"]] + t_k[side] = { + "T": point(start), + "K": point(knee), + "fractions": [{"fraction": fraction, "point": [start[index] + fraction * (knee[index] - start[index]) for index in range(3)], "result": point([start[index] + fraction * (knee[index] - start[index]) for index in range(3)])} for fraction in fractions], + } + reference = {} + j_t = {} + if protocol_case is not None: + raw_landmarks = protocol_case["reference_landmarks"] + reference = {name: {"point": [float(value) for value in values], "result": point([float(value) for value in values])} for name, values in raw_landmarks.items()} + fractions = [float(value) for value in protocol["joint_to_thigh_segment_samples"]] + for side in ("left", "right"): + joint = [float(value) for value in raw_landmarks[f"joint_{side}"]] + thigh = [float(value) for value in attachments[side]["centre"]] + j_t[side] = [{"fraction": fraction, "point": [joint[index] + fraction * (thigh[index] - joint[index]) for index in range(3)], "result": point([joint[index] + fraction * (thigh[index] - joint[index]) for index in range(3)])} for fraction in fractions] + return { + "frame": "comparison coordinate frame; controls use a display-only affine copy and saved meshes are unchanged", + "section_samples": sections, + "observed_bifurcation_intervals": _intervals(sections), + "expected_bifurcation_interval": protocol_case.get("expected_skin_bifurcation_y_interval") if protocol_case else None, + "reference_landmarks": reference, + "joint_to_thigh": j_t, + "thigh_to_knee": t_k, + "_raw_section_evidence": raw_sections, + "_raw_point_evidence": raw_points, + } + + +def _exception(exc: BaseException, phase: str) -> dict[str, str]: + return {"phase": phase, "type": type(exc).__name__, "message": str(exc)[:2000]} + + +def _load_old_case_document(frozen_root: Path) -> tuple[dict[str, Any], bytes]: + return _strict_json(frozen_root / "source/experiments/pelvis-thigh-transition/inputs.json") + + +def _artifact_files(root: Path) -> list[dict[str, Any]]: + excluded = {"artifact-sha-manifest-before.json", "artifact-sha-manifest-after.json", "run-report.json"} + paths = [path for path in root.rglob("*") if path.is_file() and path.name not in excluded] + return _inventory(root, paths) + + +def run_snapshot(snapshot: str | os.PathLike[str]) -> dict[str, Any]: + """Execute all seven captured cases once with the frozen old geometry.""" + snapshot_path = _canonical(snapshot, "snapshot") + if not snapshot_path.is_dir() or snapshot_path.is_symlink(): + _fail(f"snapshot must be a regular directory: {snapshot_path}") + captured_runner = snapshot_path / "source" / CALIBRATION_RELATIVE / "runner.py" + if Path(__file__).resolve() != captured_runner.resolve(): + _fail("run must execute from the captured newsource runner via surface_preview_launcher.sh") + sys.dont_write_bytecode = True + _load_captured_source(snapshot_path) + protocol_path = snapshot_path / "source" / CALIBRATION_RELATIVE / "protocol.json" + protocol, protocol_raw = _strict_json(protocol_path) + if not isinstance(protocol, Mapping): + _fail("captured protocol is not an object") + frozen_root = _canonical(str(protocol["frozen_dependency_root"]), "frozen dependency root") + # The dependency snapshot intentionally reuses its already-frozen runtime; + # prepare never copies the 292 MB runtime into the calibration snapshot. + runtime_path = frozen_root / "runtime/bin/python" + if not runtime_path.is_file() or runtime_path.is_symlink(): + _fail("frozen dependency runtime executable is unavailable") + if Path(sys.executable).resolve() != runtime_path.resolve(): + _fail("run interpreter is not the frozen dependency runtime") + if os.environ.get("CK_CURRENT_FORM_SURFACE_PYTHON") != str(runtime_path): + _fail("CK_CURRENT_FORM_SURFACE_PYTHON must name the frozen dependency runtime") + dependency_before = _dependency_identity(frozen_root) + expected_construction_sha = str(protocol["construction_sha256"]) + if dependency_before["manifest"]["construction"]["sha256"] != expected_construction_sha: + _fail("frozen construction hash differs from captured protocol") + input_path = snapshot_path / "source" / CALIBRATION_RELATIVE / "inputs.json" + input_value, input_raw = _strict_json(input_path) + if not isinstance(input_value, Mapping) or not isinstance(input_value.get("cases"), list): + _fail("captured inputs lack cases") + cases = list(input_value["cases"]) + ids = tuple(case.get("id") for case in cases if isinstance(case, Mapping)) + if len(cases) != 7 or ids != (*CONTROL_IDS, "calibrated_ordinary_human", "calibrated_upright_anthropomorphic") or len(set(ids)) != 7: + _fail(f"captured cases are not exactly the frozen seven-case set: {ids!r}") + old_value, _old_raw = _load_old_case_document(frozen_root) + if old_value["cases"][:5] != cases[:5]: + _fail("historical controls differ from the frozen predecessor dictionaries") + output = snapshot_path / "run" + if output.exists() or output.is_symlink(): + _fail(f"run output must be absent: {output}") + output.mkdir() + source_identity_before = _inventory(snapshot_path / "source", [path for path in (snapshot_path / "source").rglob("*") if path.is_file()]) + _write_json(output / "artifact-sha-manifest-before.json", {"schema": "creature-kernel.pelvis-source-calibration-artifacts.v1", "files": [], "source_identity": source_identity_before, "dependency_identity": dependency_before}) + + old_source = frozen_root / "source/experiments/pelvis-thigh-transition" + construction = _load_module(old_source / "construction.py", "ck_frozen_pelvis_construction") + renderer = _load_module(old_source / "render.py", "ck_frozen_pelvis_render") + legacy_checks = _load_module(old_source / "checks.py", "ck_frozen_pelvis_legacy_checks") + section_path = snapshot_path / "source" / CALIBRATION_RELATIVE / "section_diagnostic.py" + section_module = _load_module(section_path, "ck_captured_section_diagnostic") + for name in ("build", "evaluate"): + if not callable(getattr(construction, name, None)): + _fail(f"frozen construction lacks callable {name}") + for name in ("render_views",): + if not callable(getattr(renderer, name, None)): + _fail(f"frozen renderer lacks callable {name}") + if not callable(getattr(legacy_checks, "check_case", None)): + _fail("frozen legacy checks lack callable check_case") + for name in ("inspect_section", "evaluate_point"): + if not callable(getattr(section_module, name, None)): + _fail(f"captured diagnostic lacks callable {name}") + + protocol_cases = {case["id"]: case for case in protocol["cases"]} + case_reports = [] + for index, case in enumerate(cases): + case_id = str(case["id"]) + case_dir = output / "cases" / f"case-{index:02d}-{case_id}" + case_dir.mkdir(parents=True) + report: dict[str, Any] = { + "index": index, + "case_id": case_id, + "role": case.get("role"), + "historical_h_gate": {"status": "HISTORICAL_FAIL", "verdict": "fail", "rerun": False, "reason": "The old individual-side H gate/rejected verdict is retained and is not replaced by this diagnostic."}, + "status": "ERROR", + "exceptions": [], + "artifacts": [], + } + try: + built = construction.build(case["components"], case["attachments"], diagnostic=True) + evaluated = construction.evaluate(built, levels=2) + if not isinstance(evaluated, list) or len(evaluated) != 3: + _fail("frozen construction.evaluate did not return L0/L1/L2") + levels = [] + for level, mesh in enumerate(evaluated): + points, faces = _mesh_arrays(mesh) + mesh_path = case_dir / f"mesh-L{level}.json" + mesh_payload = _bounded(mesh) + if not isinstance(mesh_payload, Mapping): + _fail("evaluated mesh is not JSON-safe mapping data") + mesh_payload = dict(mesh_payload) + mesh_payload.update({"schema": "creature-kernel.pelvis-source-calibration-mesh.v1", "level": level}) + _write_json(mesh_path, mesh_payload) + report["artifacts"].append(mesh_path.relative_to(output).as_posix()) + levels.append((points, faces)) + if case_id not in CONTROL_IDS: + try: + legacy_result = legacy_checks.check_case(case, evaluated) + legacy_payload = { + "schema": "creature-kernel.pelvis-source-calibration-legacy-checks.v1", + "classification": "diagnostic_only_old_trial_gates", + "calibration_verdict": "not_evaluated", + "check_case": _bounded(legacy_result), + } + report["legacy_checks"] = { + "path": "legacy-checks.json", + "classification": "diagnostic_only_old_trial_gates", + "calibration_verdict": "not_evaluated", + "technical_pass": legacy_result.get("technical", {}).get("pass") if isinstance(legacy_result, Mapping) else None, + "lower_intersections": [level.get("nonadjacent_lower_intersections") for level in legacy_result.get("technical", {}).get("levels", [])] if isinstance(legacy_result, Mapping) else [], + "lower_folds": legacy_result.get("technical", {}).get("final_L2", {}).get("folds") if isinstance(legacy_result, Mapping) else None, + "containment": legacy_result.get("technical", {}).get("final_L2", {}).get("containment") if isinstance(legacy_result, Mapping) else None, + "upper_inherited": legacy_result.get("regional", {}).get("upper_inherited") if isinstance(legacy_result, Mapping) else None, + } + except Exception as exc: + legacy_payload = { + "schema": "creature-kernel.pelvis-source-calibration-legacy-checks.v1", + "classification": "diagnostic_only_old_trial_gates", + "calibration_verdict": "not_evaluated", + "exception": _exception(exc, "legacy-checks"), + } + report["exceptions"].append(_exception(exc, "legacy-checks")) + report["legacy_checks"] = { + "path": "legacy-checks.json", + "classification": "diagnostic_only_old_trial_gates", + "calibration_verdict": "not_evaluated", + "status": "ERROR", + } + _write_json(case_dir / "legacy-checks.json", legacy_payload) + report["artifacts"].append((case_dir / "legacy-checks.json").relative_to(output).as_posix()) + points, faces = levels[-1] + display_points, diagnostic_scale, display_mode = _display_case(case, points, protocol) + bounds = protocol["view_bounds"] + surface_meta = renderer.render_views(display_points, faces, case_dir / "surface.png", case_id, "UNVERIFIED - VISUAL PENDING", bounds=bounds, overlays=None, underside=True, allow_crop=True) + report["artifacts"].extend(path for path in ("cases/" + case_dir.name + "/surface.png", "cases/" + case_dir.name + "/surface-underside.png")) + overlays = _overlays(case, protocol_cases.get(case_id), display_mode, protocol) + landmark_base = case_dir / "landmarks-base.png" + landmark_meta = renderer.render_views(display_points, faces, landmark_base, case_id, "UNVERIFIED - DIAGNOSTIC OVERLAYS", bounds=bounds, overlays=overlays, underside=False, allow_crop=True) + diagnostic_path = case_dir / "landmarks-base-diagnostic.png" + if not diagnostic_path.is_file(): + _fail("renderer did not produce the diagnostic overlay image") + shutil.copyfile(diagnostic_path, case_dir / "landmarks.png") + report["artifacts"].extend(path for path in ("cases/" + case_dir.name + "/landmarks.png", "cases/" + case_dir.name + "/landmarks-base.png", "cases/" + case_dir.name + "/landmarks-base-diagnostic.png")) + diagnostics = _diagnostics(section_module, display_points, faces, case, protocol_cases.get(case_id), protocol, diagnostic_scale) + section_evidence = { + "schema": "creature-kernel.pelvis-source-calibration-section-evidence.v1", + "case_id": case_id, + "frame": diagnostics["frame"], + "inspect_section": diagnostics.pop("_raw_section_evidence"), + "evaluate_point": diagnostics.pop("_raw_point_evidence"), + } + section_evidence_path = case_dir / "section-evidence.json" + _write_json(section_evidence_path, section_evidence) + report["artifacts"].append(section_evidence_path.relative_to(output).as_posix()) + report.update({"status": "DIAGNOSTIC_ONLY", "display_mode": display_mode, "diagnostic_scale": diagnostic_scale, "render": {"surface": _bounded(surface_meta), "landmarks": _bounded(landmark_meta)}, "levels": [{"level": level, "structural": _structural_stats(level_points, level_faces)} for level, (level_points, level_faces) in enumerate(levels)], "diagnostics": diagnostics}) + except Exception as exc: + report["exceptions"].append(_exception(exc, "case")) + _write_json(case_dir / "case-report.json", report) + case_reports.append(report) + + dependency_after = _dependency_identity(frozen_root) + source_identity_after = _inventory(snapshot_path / "source", [path for path in (snapshot_path / "source").rglob("*") if path.is_file()]) + drift = dependency_before != dependency_after or source_identity_before != source_identity_after + after_files = _artifact_files(output) + _write_json(output / "artifact-sha-manifest-after.json", {"schema": "creature-kernel.pelvis-source-calibration-artifacts.v1", "files": after_files, "source_identity": source_identity_after, "dependency_identity": dependency_after}) + report = { + "schema": RUNNER_SCHEMA, + "status": "ERROR" if drift else "DIAGNOSTIC_ONLY", + "geometry_tuning": False, + "case_count": len(case_reports), + "cases": case_reports, + "protocol": {"path": "source/experiments/pelvis-source-calibration/protocol.json", "sha256": _sha256_bytes(protocol_raw)}, + "inputs": {"path": "source/experiments/pelvis-source-calibration/inputs.json", "bytes": len(input_raw), "sha256": _sha256_bytes(input_raw)}, + "old_h_gate": "HISTORICAL_FAIL", + "freeze": {"source_before": source_identity_before, "source_after": source_identity_after, "dependency_before": dependency_before, "dependency_after": dependency_after, "drift": drift}, + "artifacts": {"before": "artifact-sha-manifest-before.json", "after": "artifact-sha-manifest-after.json"}, + "limitations": [ + "Structural statistics and sections are evidence only; no policy acceptance is calculated.", + "J is evaluated only as a protocol reference point. It is not inserted into generator inputs or claimed as executable J-to-skin causality.", + "K samples outside the represented mesh range are reported by the diagnostic as out_of_represented_range, not as inside failures.", + ], + } + _write_json(output / "run-report.json", report) + return report + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Bounded pelvis source-calibration evidence harness") + commands = parser.add_subparsers(dest="command", required=True) + prepare_parser = commands.add_parser("prepare", help="capture the source and concrete inputs") + prepare_parser.add_argument("--output", required=True) + run_parser = commands.add_parser("run", help="run the captured seven-case set") + run_parser.add_argument("--snapshot", required=True) + args = parser.parse_args(argv) + try: + if args.command == "prepare": + prepare(args.output) + else: + run_snapshot(args.snapshot) + except Exception as exc: + print(f"runner.py: error: {exc}", file=sys.stderr, flush=True) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/experiments/pelvis-source-calibration/section_diagnostic.py b/experiments/pelvis-source-calibration/section_diagnostic.py new file mode 100644 index 0000000..08ca860 --- /dev/null +++ b/experiments/pelvis-source-calibration/section_diagnostic.py @@ -0,0 +1,275 @@ +"""Horizontal actual-surface section diagnostics; not a mesh gate or solid test.""" +from __future__ import annotations +import math +from collections import Counter +from typing import Any, Sequence + +_BOUNDARY_TOLERANCE = 1.0e-6 +_SLICE_OFFSET = 1.0e-7 +_PLANE_TOLERANCE = 1.0e-12 +_POINT_MERGE_TOLERANCE = 1.0e-9 +_LIMIT = "Horizontal actual-surface cross-section only; open ports are not capped. This is not a global solid-volume or containment claim." + +def _finite(value: Any) -> bool: + if isinstance(value, bool): + return False + try: + return math.isfinite(float(value)) + except (TypeError, ValueError, OverflowError): + return False + +def _vector(value: Any) -> tuple[float, float, float]: + if isinstance(value, (str, bytes, bytearray)): + raise ValueError("vertex/point must be a finite 3-vector") + try: + values = list(value) + except (TypeError, ValueError) as exc: + raise ValueError("vertex/point must be a finite 3-vector") from exc + if len(values) != 3 or any(not _finite(item) for item in values): + raise ValueError("vertex/point must be a finite 3-vector") + return tuple(float(item) for item in values) # type: ignore[return-value] + +def _validated(vertices: Any, quads: Any, scale: Any) -> tuple[Any, ...]: + if not _finite(scale) or float(scale) <= 0: + raise ValueError("scale must be finite and positive") + try: + raw_vertices, raw_quads = list(vertices), list(quads) + except (TypeError, ValueError) as exc: + raise ValueError("vertices and quads must be sequences") from exc + checked_vertices = tuple(_vector(value) for value in raw_vertices) + if not checked_vertices: + raise ValueError("vertices must not be empty") + checked_quads = [] + for face_index, value in enumerate(raw_quads): + try: + face = list(value) + except (TypeError, ValueError) as exc: + raise ValueError(f"quads[{face_index}] must have four indices") from exc + if len(face) != 4 or any(isinstance(index, bool) or not isinstance(index, int) for index in face): + raise ValueError(f"quads[{face_index}] must have four integer indices") + if len(set(face)) != 4 or any(index < 0 or index >= len(checked_vertices) for index in face): + raise ValueError(f"quads[{face_index}] contains an invalid index") + checked_quads.append(tuple(face)) + if not checked_quads: + raise ValueError("quads must not be empty") + return checked_vertices, tuple(checked_quads), float(scale) + +def _invalid(message: str) -> dict[str, Any]: + return {"status": "INVALID_INPUT", "classification": "invalid_input", "error": message, "interpretation_limit": _LIMIT} + +def _point_id(point: tuple[float, float], points: list[tuple[float, float]], buckets: dict[tuple[int, int], list[int]], tolerance: float) -> int: + cell = (math.floor(point[0] / tolerance), math.floor(point[1] / tolerance)) + best = None + for dx in (-1, 0, 1): + for dz in (-1, 0, 1): + for index in buckets.get((cell[0] + dx, cell[1] + dz), ()): + distance = math.hypot(point[0] - points[index][0], point[1] - points[index][1]) + if distance <= tolerance and (best is None or (distance, index) < best): + best = (distance, index) + if best is not None: + return best[1] + index = len(points) + points.append(point) + buckets.setdefault(cell, []).append(index) + return index + +def _section_at(vertices: Sequence[tuple[float, float, float]], quads: Sequence[tuple[int, int, int, int]], y: float, scale: float) -> dict[str, Any]: + plane_tolerance = max(_PLANE_TOLERANCE * scale, 1.0e-15) + merge_tolerance = max(_POINT_MERGE_TOLERANCE * scale, 1.0e-15) + points: list[tuple[float, float]] = [] + buckets: dict[tuple[int, int], list[int]] = {} + segments: set[tuple[int, int]] = set() + generated = 0 + plane_vertices: set[int] = set() + coplanar_triangles = 0 + coplanar_edges: set[tuple[int, int]] = set() + vertex_touches: set[int] = set() + def point_on(index: int) -> tuple[float, float]: + return vertices[index][0], vertices[index][2] + def crossing(first: int, second: int, first_distance: float, second_distance: float) -> tuple[float, float]: + fraction = first_distance / (first_distance - second_distance) + a, b = vertices[first], vertices[second] + return a[0] + fraction * (b[0] - a[0]), a[2] + fraction * (b[2] - a[2]) + def add_segment(first_point: tuple[float, float], second_point: tuple[float, float]) -> None: + nonlocal generated + first = _point_id(first_point, points, buckets, merge_tolerance) + second = _point_id(second_point, points, buckets, merge_tolerance) + if first != second: + generated += 1 + segments.add(tuple(sorted((first, second)))) + for quad in quads: + for triangle in ((quad[0], quad[1], quad[2]), (quad[0], quad[2], quad[3])): + distances = tuple(vertices[index][1] - y for index in triangle) + on = tuple(abs(distance) <= plane_tolerance for distance in distances) + plane_vertices.update(triangle[index] for index, is_on in enumerate(on) if is_on) + coplanar_edges.update(tuple(sorted((triangle[first], triangle[second]))) for first, second in ((0, 1), (1, 2), (2, 0)) if on[first] and on[second]) + if all(on): + coplanar_triangles += 1 + elif sum(on) == 2: + on_points = [point_on(triangle[index]) for index, is_on in enumerate(on) if is_on] + add_segment(on_points[0], on_points[1]) + elif sum(on) == 1: + on_index = on.index(True) + off = [index for index, is_on in enumerate(on) if not is_on] + if distances[off[0]] * distances[off[1]] < 0: + add_segment(point_on(triangle[on_index]), crossing(triangle[off[0]], triangle[off[1]], distances[off[0]], distances[off[1]])) + else: + vertex_touches.add(triangle[on_index]) + else: + crossings = [crossing(triangle[first], triangle[second], distances[first], distances[second]) for first, second in ((0, 1), (1, 2), (2, 0)) if distances[first] * distances[second] < 0] + if len(crossings) == 2: + add_segment(crossings[0], crossings[1]) + adjacency = [set() for _ in points] + for first, second in segments: + adjacency[first].add(second) + adjacency[second].add(first) + open_nodes = [index for index, neighbours in enumerate(adjacency) if len(neighbours) != 2] + closed_graph = bool(segments) and not open_nodes + contours: list[list[list[float]]] = [] + if closed_graph: + unseen = set(range(len(points))) + while unseen: + start = min(unseen) + current, previous, contour = start, None, [] + while True: + contour.append([points[current][0], points[current][1]]) + unseen.discard(current) + neighbours = sorted(adjacency[current]) + next_node = neighbours[0] if previous is None or neighbours[0] != previous else neighbours[1] + previous, current = current, next_node + if current == start: + break + contours.append(contour) + return {"points": points, "segments": [(points[a], points[b]) for a, b in sorted(segments)], "generated_segment_count": generated, "deduplicated_segment_count": len(segments), "adjacency": adjacency, "open_nodes": open_nodes, "closed_graph": closed_graph, "contours": contours, "plane_vertices": plane_vertices, "coplanar_triangles": coplanar_triangles, "coplanar_edges": coplanar_edges, "vertex_touches": vertex_touches, "merge_tolerance": merge_tolerance} + +def _orientation(a: Sequence[float], b: Sequence[float], c: Sequence[float]) -> float: + return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) +def _point_segment_distance(point: Sequence[float], first: Sequence[float], second: Sequence[float]) -> float: + dx, dz = second[0] - first[0], second[1] - first[1] + denominator = dx * dx + dz * dz + if denominator == 0: + return math.hypot(point[0] - first[0], point[1] - first[1]) + fraction = max(0.0, min(1.0, ((point[0] - first[0]) * dx + (point[1] - first[1]) * dz) / denominator)) + return math.hypot(point[0] - first[0] - fraction * dx, point[1] - first[1] - fraction * dz) +def _signed_distance(a: Sequence[float], b: Sequence[float], p: Sequence[float]) -> float: + length = math.hypot(b[0] - a[0], b[1] - a[1]) + return _orientation(a, b, p) / length if length else math.inf +def _on_segment(a: Sequence[float], b: Sequence[float], p: Sequence[float], tolerance: float) -> bool: + return _point_segment_distance(p, a, b) <= tolerance +def _intersects(a: Sequence[float], b: Sequence[float], c: Sequence[float], d: Sequence[float], tolerance: float) -> bool: + values = (_signed_distance(a, b, c), _signed_distance(a, b, d), _signed_distance(c, d, a), _signed_distance(c, d, b)) + opposite = ((values[0] > tolerance and values[1] < -tolerance) or (values[1] > tolerance and values[0] < -tolerance)) and ((values[2] > tolerance and values[3] < -tolerance) or (values[3] > tolerance and values[2] < -tolerance)) + return opposite or any(_on_segment(first, second, point, tolerance) for first, second, point in ((a, b, c), (a, b, d), (c, d, a), (c, d, b))) +def _self_intersections(contours: Sequence[Sequence[Sequence[float]]], tolerance: float) -> int: + edges = [(ci, ei, first, contour[(ei + 1) % len(contour)]) for ci, contour in enumerate(contours) for ei, first in enumerate(contour)] + count = 0 + for index, (ca, ea, a, b) in enumerate(edges): + for cb, eb, c, d in edges[index + 1:]: + adjacent = ca == cb and ((ea + 1) % len(contours[ca]) == eb or (eb + 1) % len(contours[cb]) == ea) + if not adjacent and _intersects(a, b, c, d, tolerance): + count += 1 + return count +def _bounds(contours: Sequence[Sequence[Sequence[float]]], points: Sequence[tuple[float, float]]) -> dict[str, float] | None: + values = [point for contour in contours for point in contour] or [[point[0], point[1]] for point in points] + if not values: + return None + xs, zs = [point[0] for point in values], [point[1] for point in values] + return {"min_x": min(xs), "max_x": max(xs), "min_z": min(zs), "max_z": max(zs)} + +def _summary(raw: dict[str, Any], y: float, scale: float, y_range: tuple[float, float]) -> dict[str, Any]: + if raw["open_nodes"]: + kind = "INDETERMINATE_OPEN_SECTION" + elif raw["self_intersection_count"]: + kind = "INDETERMINATE_SELF_INTERSECTION" + elif raw["closed_graph"]: + kind = "CLOSED_SECTION" + else: + kind = "EMPTY_SECTION" + exact = bool(raw["plane_vertices"] or raw["coplanar_triangles"]) + diagnostics = {"surface_y_range": [y_range[0], y_range[1]], "plane_tolerance": max(_PLANE_TOLERANCE * scale, 1.0e-15), "point_merge_tolerance": raw["merge_tolerance"], "generated_segment_count": raw["generated_segment_count"], "deduplicated_segment_count": raw["deduplicated_segment_count"], "node_count": len(raw["points"]), "degree_histogram": {str(key): value for key, value in sorted(Counter(len(row) for row in raw["adjacency"]).items())}, "open_node_count": len(raw["open_nodes"]), "exact_coplanarity": exact, "plane_vertex_count": len(raw["plane_vertices"]), "coplanar_triangle_count": raw["coplanar_triangles"], "coplanar_edge_count": len(raw["coplanar_edges"]), "vertex_touch_count": len(raw["vertex_touches"]), "section_self_intersection_count": raw["self_intersection_count"], "closed_graph": raw["closed_graph"]} + closed_count = len(raw["contours"]) if raw["closed_graph"] else 0 + diagnostics["segment_count"] = raw["deduplicated_segment_count"] + diagnostics["closed_contour_count"] = closed_count + return {"query_y": y, "scale": scale, "status": kind, "classification": kind, "section_classification": kind, "contours": raw["contours"], "closed_contours": raw["contours"] if raw["closed_graph"] else [], "closed_count": closed_count, "closed_contour_count": closed_count, "bounds": _bounds(raw["contours"] if raw["closed_graph"] else (), raw["points"]), "diagnostics": diagnostics, "ambiguous": False, "usable": kind == "CLOSED_SECTION" and not raw["self_intersection_count"], "interpretation_limit": _LIMIT} + +def _inspect_valid(vertices: Any, quads: Any, y: Any, scale: Any) -> tuple[dict[str, Any], dict[str, Any] | None]: + try: + checked_vertices, checked_quads, checked_scale = _validated(vertices, quads, scale) + if not _finite(y): + raise ValueError("query y must be finite") + query_y = float(y) + except ValueError as exc: + return _invalid(str(exc)), None + y_values = [point[1] for point in checked_vertices] + y_range = (min(y_values), max(y_values)) + raw = _section_at(checked_vertices, checked_quads, query_y, checked_scale) + raw["self_intersection_count"] = _self_intersections(raw["contours"], raw["merge_tolerance"]) if raw["closed_graph"] else 0 + result = _summary(raw, query_y, checked_scale, y_range) + if query_y < y_range[0] or query_y > y_range[1]: + result.update({"status": "OUT_OF_REPRESENTED_RANGE", "classification": "out_of_range", "section_classification": "OUT_OF_REPRESENTED_RANGE", "usable": False}) + result["diagnostics"]["out_of_represented_range"] = True + return result, raw + result["diagnostics"]["out_of_represented_range"] = False + if result["diagnostics"]["exact_coplanarity"]: + delta = _SLICE_OFFSET * checked_scale + slices = [] + for offset in (-delta, delta): + adjacent = _section_at(checked_vertices, checked_quads, query_y + offset, checked_scale) + adjacent["self_intersection_count"] = _self_intersections(adjacent["contours"], adjacent["merge_tolerance"]) if adjacent["closed_graph"] else 0 + item = _summary(adjacent, query_y + offset, checked_scale, y_range) + slices.append({"offset": offset, "query_y": query_y + offset, "section_classification": item["section_classification"], "closed_count": item["closed_count"], "bounds": item["bounds"]}) + disagreement = len({(item["section_classification"], item["closed_count"]) for item in slices}) > 1 + result.update({"status": "INDETERMINATE_AMBIGUOUS_SECTION", "classification": "INDETERMINATE_AMBIGUOUS_SECTION", "section_classification": "INDETERMINATE_AMBIGUOUS_SECTION", "ambiguous": True, "usable": False}) + result["diagnostics"].update({"adjacent_slices": slices, "adjacent_slice_disagreement": disagreement, "ambiguity_reason": "exact_plane_contact_with_fixed_adjacent_slices"}) + return result, raw + +def inspect_section(vertices: Any, quads: Any, y: Any, scale: Any) -> dict[str, Any]: + """Return contours, closure/count, bounds, and fail-closed section diagnostics.""" + result, _ = _inspect_valid(vertices, quads, y, scale) + return result + +def _parity(point: Sequence[float], contours: Sequence[Sequence[Sequence[float]]]) -> tuple[int, int]: + parity = containing = 0 + for contour in contours: + inside = False + for index, first in enumerate(contour): + second = contour[(index + 1) % len(contour)] + if (first[1] > point[1]) != (second[1] > point[1]) and point[0] < first[0] + (second[0] - first[0]) * (point[1] - first[1]) / (second[1] - first[1]): + inside = not inside + if inside: + parity ^= 1 + containing += 1 + return parity, containing + +def evaluate_point(vertices: Any, quads: Any, point: Any, scale: Any) -> dict[str, Any]: + """Classify a point using one horizontal actual-surface section.""" + try: + query_point = _vector(point) + except ValueError as exc: + return _invalid(str(exc)) + section, raw = _inspect_valid(vertices, quads, query_point[1], scale) + if raw is None: + return section + tolerance = _BOUNDARY_TOLERANCE * float(scale) + xz = (query_point[0], query_point[2]) + boundary_distance = min((_point_segment_distance(xz, first, second) for first, second in raw["segments"]), default=None) + bounds = section["bounds"] + within_bounds = bool(bounds and bounds["min_x"] - tolerance <= xz[0] <= bounds["max_x"] + tolerance and bounds["min_z"] - tolerance <= xz[1] <= bounds["max_z"] + tolerance) + result = {"point": [query_point[0], query_point[1], query_point[2]], "query_y": query_point[1], "scale": float(scale), "section": section, "parity": None, "inside_contour_count": None, "boundary_distance": boundary_distance, "boundary_tolerance": tolerance, "within_section_bounds": within_bounds, "interpretation_limit": _LIMIT} + y_min, y_max = section["diagnostics"]["surface_y_range"] + if query_point[1] < y_min or query_point[1] > y_max: + result.update({"status": "OUT_OF_REPRESENTED_RANGE", "classification": "out_of_range", "reason": "out_of_represented_range"}) + elif section["ambiguous"]: + result.update({"status": "INDETERMINATE_AMBIGUOUS_SECTION", "classification": "INDETERMINATE_AMBIGUOUS_SECTION", "reason": "exact_coplanarity_or_adjacent_slice_disagreement"}) + elif raw["open_nodes"]: + result.update({"status": "INDETERMINATE_OPEN_SECTION", "classification": "INDETERMINATE_OPEN_SECTION", "reason": "section_graph_has_non_degree_two_nodes"}) + elif raw["self_intersection_count"]: + result.update({"status": "INDETERMINATE_SELF_INTERSECTION", "classification": "INDETERMINATE_SELF_INTERSECTION", "reason": "section_contours_self_intersect"}) + elif not raw["segments"]: + result.update({"status": "OUTSIDE", "classification": "outside", "reason": "empty_section_within_represented_range", "parity": 0, "inside_contour_count": 0}) + elif boundary_distance is not None and boundary_distance <= tolerance: + result.update({"status": "ON_SURFACE", "classification": "on_surface", "reason": "within_section_boundary_tolerance"}) + else: + parity, containing = _parity(xz, raw["contours"]) + result.update({"parity": parity, "inside_contour_count": containing, "status": "INSIDE" if parity else "OUTSIDE", "classification": "inside" if parity else "outside", "reason": "odd_even_closed_contour_parity"}) + return result diff --git a/experiments/pelvis-source-calibration/tests/test_inputs.py b/experiments/pelvis-source-calibration/tests/test_inputs.py new file mode 100644 index 0000000..7531283 --- /dev/null +++ b/experiments/pelvis-source-calibration/tests/test_inputs.py @@ -0,0 +1,175 @@ +from __future__ import annotations + +import json +from pathlib import Path +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +import sys + +sys.path.insert(0, str(ROOT)) +import inputs # noqa: E402 +import runner # noqa: E402 + + +class CalibrationInputTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.document = inputs.build_document() + cls.source = json.loads(inputs.FROZEN_OLD_INPUTS.read_text(encoding="utf-8")) + cls.protocol = json.loads(inputs.PROTOCOL_PATH.read_text(encoding="utf-8")) + + def test_exactly_five_inherited_controls_then_two_protocol_cases(self): + cases = self.document["cases"] + self.assertEqual(len(cases), 7) + self.assertEqual(cases[:5], self.source["cases"][:5]) + self.assertEqual( + [case["id"] for case in cases], + [ + "standard_neutral_reference", + "compact_broad_short_limb_large_head", + "tall_narrow_long_legged", + "slender_long_limb", + "stocky_broad_chested", + "calibrated_ordinary_human", + "calibrated_upright_anthropomorphic", + ], + ) + + def test_protocol_overrides_are_concrete_and_affine_base_is_display_separate(self): + neutral = self.source["cases"][0] + for case, declared in zip(self.document["cases"][5:], self.protocol["cases"]): + self.assertEqual(case["role"], declared["role"]) + self.assertEqual(case["components"]["shoulders.left.arm_origin.x"], -0.16) + self.assertEqual(case["components"]["shoulders.left.arm_origin.y"], 0.48) + self.assertAlmostEqual(case["components"]["shoulders.left.shoulder_depth"], 0.056) + self.assertEqual(case["components"]["stations.lower_pelvis.C.y"], declared["stations"]["lower_pelvis"]["centre"][1]) + self.assertEqual(case["components"]["stations.lower_pelvis.rL"], declared["stations"]["lower_pelvis"]["radii"][0]) + self.assertEqual(case["components"]["hips.left.r_x"], declared["hip_radii"][0]) + self.assertEqual(case["attachments"]["right"]["knee"], declared["attachments"]["right"]["knee"]) + self.assertNotEqual(case["components"], neutral["components"]) + self.assertEqual(self.document["display_normalization"]["scale"], 0.16) + self.assertEqual(self.document["display_normalization"]["translation"], [0.0, 0.16, 0.0]) + self.assertIn("saved/evaluated meshes remain native", self.document["display_normalization"]["applies_to"]) + + def test_reference_landmarks_and_j_are_not_generator_fields(self): + for case in self.document["cases"][5:]: + self.assertNotIn("reference_landmarks", case) + serialized = json.dumps(case, sort_keys=True) + self.assertNotIn("joint_left", serialized) + self.assertNotIn("joint_right", serialized) + self.assertNotIn("\"J\"", serialized) + + def test_change_ledger_has_complete_reason_trace_for_each_change(self): + allowed_reasons = {inputs.NORMALIZATION_REASON, inputs.ANATOMICAL_REASON} + protocol_details = { + reason + for case in self.protocol["cases"] + for reason in (case["station_reason"], case["hip_radii_reason"], case["attachment_reason"]) + } + for case in self.document["cases"][5:]: + ledger = case["provenance"]["change_ledger"] + self.assertTrue(ledger) + for entry in ledger: + self.assertTrue({"path", "old", "new", "reason", "reason_detail", "protocol_reason_pointer"} <= set(entry)) + self.assertIn(entry["reason"], allowed_reasons) + self.assertNotEqual(entry["old"], entry["new"]) + if entry["reason"] == inputs.NORMALIZATION_REASON: + self.assertEqual(entry["reason_detail"], self.protocol["base_transform"]["reason"]) + self.assertEqual(entry["protocol_reason_pointer"], "/base_transform/reason") + else: + self.assertIn(entry["reason_detail"], protocol_details) + self.assertTrue(entry["protocol_reason_pointer"].startswith("/cases/")) + + paths = {entry["path"] for entry in ledger} + for key, old in self.source["cases"][0]["components"].items(): + axis = {"x": 0, "y": 1, "z": 2}.get(key.rsplit(".", 1)[-1]) + expected = float(old) * 0.16 + ([0.0, 0.16, 0.0][axis] if axis is not None else 0.0) + if expected != float(old): + self.assertIn(f"/components/{key}", paths) + + def test_prepare_is_deterministic_and_refuses_replacement(self): + first = inputs.json_bytes(inputs.build_document()) + second = inputs.json_bytes(inputs.build_document()) + self.assertEqual(first, second) + with tempfile.TemporaryDirectory() as temporary: + output = Path(temporary) / "inputs.json" + inputs.prepare(output) + self.assertEqual(output.read_bytes(), first) + with self.assertRaises(inputs.InputError): + inputs.prepare(output) + + def test_frozen_construction_and_checks_import_without_build(self): + runner.sys.dont_write_bytecode = True + old_source = inputs.FROZEN_ROOT / "source/experiments/pelvis-thigh-transition" + construction = runner._load_module(old_source / "construction.py", "test_frozen_construction_smoke") + checks = runner._load_module(old_source / "checks.py", "test_frozen_checks_smoke") + self.assertTrue(callable(construction.build)) + self.assertTrue(callable(construction.evaluate)) + self.assertTrue(callable(checks.check_case)) + + @staticmethod + def _two_tubes(): + vertices = [] + quads = [] + for centre_x in (-0.4, 0.4): + base = len(vertices) + for y in (-2.0, 0.0): + vertices.extend([ + [centre_x - 0.1, y, -0.1], + [centre_x + 0.1, y, -0.1], + [centre_x + 0.1, y, 0.1], + [centre_x - 0.1, y, 0.1], + ]) + for offset in range(4): + next_offset = (offset + 1) % 4 + quads.append([base + offset, base + next_offset, base + 4 + next_offset, base + 4 + offset]) + return vertices, quads + + def test_actual_section_diagnostics_transform_history_and_require_two_loops(self): + runner.sys.dont_write_bytecode = True + section = runner._load_module(ROOT / "section_diagnostic.py", "test_captured_section_integration") + points, faces = self._two_tubes() + display_points = runner._affine_points(points, 0.16, [0.0, 0.16, 0.0]) + case = { + "id": "standard_neutral_reference", + "attachments": { + "left": {"centre": [-0.4, -1.0, 0.0], "knee": [-0.38, -0.5, 0.0]}, + "right": {"centre": [0.4, -1.0, 0.0], "knee": [0.38, -0.5, 0.0]}, + }, + } + protocol = { + "section_samples": 41, + "section_y_limits": [-0.24, 0.16], + "joint_to_thigh_segment_samples": [0.0, 0.25, 0.5, 0.75, 1.0], + "thigh_axis_segment_samples": [0.0, 0.15, 0.3, 0.45], + "historical_display_transform": {"scale": 0.16, "translation": [0.0, 0.16, 0.0]}, + } + evidence = runner._diagnostics(section, display_points, faces, case, None, protocol, 0.16) + first_point = evidence["_raw_point_evidence"][0] + self.assertEqual(first_point["point"], [-0.064, 0.0, 0.0]) + self.assertNotEqual(first_point["result"]["status"], "OUT_OF_REPRESENTED_RANGE") + middle = next(row for row in evidence["section_samples"] if abs(row["y"]) < 1.0e-12) + self.assertTrue(middle["closed"]) + self.assertTrue(middle["usable"]) + self.assertEqual(middle["loop_count"], 2) + self.assertTrue(evidence["observed_bifurcation_intervals"]["two_loop_ranges"]) + self.assertEqual(evidence["observed_bifurcation_intervals"]["one_to_two_boundary_brackets"], []) + + def test_overlay_set_contains_joint_landmarks_and_both_paths(self): + case = self.document["cases"][5] + protocol_case = self.protocol["cases"][0] + overlays = runner._overlays(case, protocol_case, "native_calibration_frame", self.protocol) + labels = {item["label"] for item in overlays} + self.assertIn("J-T left", labels) + self.assertIn("J-T right", labels) + self.assertIn("T-K left", labels) + self.assertIn("T-K right", labels) + for label in ("J left", "crest left", "ASIS left", "PSIS left", "pubis", "trochanter left"): + self.assertIn(label, labels) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/pelvis-source-calibration/tests/test_section_diagnostic.py b/experiments/pelvis-source-calibration/tests/test_section_diagnostic.py new file mode 100644 index 0000000..e0ded17 --- /dev/null +++ b/experiments/pelvis-source-calibration/tests/test_section_diagnostic.py @@ -0,0 +1,148 @@ +from __future__ import annotations + +import json +import math +import sys +import unittest +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +import section_diagnostic # noqa: E402 + + +def _side_surface(center_x: float, radius_x: float, radius_z: float, sides: int = 8, y0: float = 0.0, y1: float = 2.0) -> tuple[list[tuple[float, float, float]], list[tuple[int, int, int, int]]]: + vertices = [] + for y in (y0, y1): + for index in range(sides): + angle = 2.0 * math.pi * index / sides + vertices.append((center_x + radius_x * math.cos(angle), y, radius_z * math.sin(angle))) + quads = [(index, (index + 1) % sides, sides + (index + 1) % sides, sides + index) for index in range(sides)] + return vertices, quads + + +def _box(remove_side: int | None = None): + vertices, quads = _side_surface(0.0, 1.0, 1.0, 4) + if remove_side is not None: + quads.pop(remove_side) + return vertices, quads + + +def _combine(*meshes): + vertices = [] + quads = [] + for mesh_vertices, mesh_quads in meshes: + offset = len(vertices) + vertices.extend(mesh_vertices) + quads.extend(tuple(index + offset for index in quad) for quad in mesh_quads) + return vertices, quads + + +def _annulus(): + return _combine(_side_surface(0.0, 3.0, 3.0), _side_surface(0.0, 1.0, 1.0)) + + +def _bowtie_surface(): + ring = [(-1.0, -1.0), (1.0, 1.0), (-1.0, 1.0), (1.0, -1.0)] + vertices = [(x, y, z) for y in (0.0, 2.0) for x, z in ring] + quads = [(index, (index + 1) % 4, 4 + (index + 1) % 4, 4 + index) for index in range(4)] + return vertices, quads + + +class SectionDiagnosticTests(unittest.TestCase): + def assert_json_safe(self, value): + json.dumps(value, allow_nan=False) + + def test_open_box_midpoint_inside_external_and_boundary(self): + vertices, quads = _box() + for point, expected in [((0.0, 1.0, 0.0), "inside"), ((2.0, 1.0, 0.0), "outside"), ((1.0, 1.0, 0.0), "on_surface")]: + with self.subTest(point=point): + result = section_diagnostic.evaluate_point(vertices, quads, point, 2.0) + self.assertEqual(result["classification"], expected, result) + self.assertEqual(result["section"]["closed_count"], 1) + self.assert_json_safe(result) + + def test_point_beyond_open_end_is_out_of_range(self): + vertices, quads = _side_surface(0.0, 1.0, 1.0) + result = section_diagnostic.evaluate_point(vertices, quads, (0.0, 3.0, 0.0), 2.0) + self.assertEqual(result["classification"], "out_of_range", result) + self.assertEqual(result["reason"], "out_of_represented_range") + self.assertEqual(result["section"]["classification"], "out_of_range") + self.assert_json_safe(result) + + def test_empty_section_within_mesh_height_is_outside(self): + vertices, quads = _combine(_side_surface(-2.0, 1.0, 1.0, y1=0.75), _side_surface(2.0, 1.0, 1.0, y0=1.25)) + result = section_diagnostic.evaluate_point(vertices, quads, (0.0, 1.0, 0.0), 2.0) + self.assertEqual(result["classification"], "outside", result) + self.assertEqual(result["reason"], "empty_section_within_represented_range") + self.assert_json_safe(result) + + def test_removed_side_is_indeterminate_open_section(self): + vertices, quads = _box(remove_side=0) + result = section_diagnostic.evaluate_point(vertices, quads, (0.0, 1.0, 0.0), 2.0) + self.assertEqual(result["classification"], "INDETERMINATE_OPEN_SECTION", result) + self.assertGreater(result["section"]["diagnostics"]["open_node_count"], 0) + self.assert_json_safe(result) + + def test_two_disjoint_tubes_have_inside_gap_outside(self): + vertices, quads = _combine(_side_surface(-2.0, 1.0, 1.0), _side_surface(2.0, 1.0, 1.0)) + for point, expected in [((-2.0, 1.0, 0.0), "inside"), ((2.0, 1.0, 0.0), "inside"), ((0.0, 1.0, 0.0), "outside")]: + with self.subTest(point=point): + result = section_diagnostic.evaluate_point(vertices, quads, point, 2.0) + self.assertEqual(result["classification"], expected, result) + self.assertEqual(result["section"]["closed_count"], 2) + self.assert_json_safe(result) + + def test_annular_hole_uses_even_parity(self): + vertices, quads = _annulus() + hole = section_diagnostic.evaluate_point(vertices, quads, (0.0, 1.0, 0.0), 2.0) + shell = section_diagnostic.evaluate_point(vertices, quads, (2.0, 1.0, 0.0), 2.0) + self.assertEqual(hole["classification"], "outside", hole) + self.assertEqual(hole["parity"], 0) + self.assertEqual(hole["inside_contour_count"], 2) + self.assertEqual(shell["classification"], "inside", shell) + self.assertEqual(shell["parity"], 1) + self.assert_json_safe(hole) + self.assert_json_safe(shell) + + def test_reversed_winding_keeps_membership(self): + vertices, quads = _box() + reversed_quads = [(a, d, c, b) for a, b, c, d in quads] + forward = section_diagnostic.evaluate_point(vertices, quads, (0.0, 1.0, 0.0), 2.0) + reversed_result = section_diagnostic.evaluate_point(vertices, reversed_quads, (0.0, 1.0, 0.0), 2.0) + self.assertEqual(forward["classification"], "inside") + self.assertEqual(reversed_result["classification"], "inside") + self.assertEqual(forward["parity"], reversed_result["parity"]) + self.assert_json_safe(reversed_result) + + def test_self_intersecting_section_does_not_claim_inside(self): + vertices, quads = _bowtie_surface() + result = section_diagnostic.evaluate_point(vertices, quads, (0.0, 1.0, 0.0), 2.0) + self.assertIn(result["classification"], {"INDETERMINATE_OPEN_SECTION", "INDETERMINATE_SELF_INTERSECTION"}, result) + self.assert_json_safe(result) + + def test_segment_intersection_uses_linear_scaled_tolerance(self): + first, second = (0.0, 0.0), (0.001, 0.001) + third, fourth = (0.0005, 0.0005001), (0.0006, 0.0007) + crossing_first, crossing_second = (0.0, 0.001), (0.001, 0.0) + for factor in (0.16, 1.0, 1000.0): + with self.subTest(scale_factor=factor): + scale_point = lambda point: tuple(factor * value for value in point) + tolerance = factor * 1.0e-9 + self.assertFalse(section_diagnostic._intersects(scale_point(first), scale_point(second), scale_point(third), scale_point(fourth), tolerance)) + self.assertTrue(section_diagnostic._intersects(scale_point(first), scale_point(second), scale_point(crossing_first), scale_point(crossing_second), tolerance)) + + def test_coincident_vertex_level_is_reported_ambiguous(self): + vertices, quads = _box() + section = section_diagnostic.inspect_section(vertices, quads, 0.0, 2.0) + result = section_diagnostic.evaluate_point(vertices, quads, (0.0, 0.0, 0.0), 2.0) + self.assertTrue(section["diagnostics"]["exact_coplanarity"], section) + self.assertTrue(section["ambiguous"], section) + self.assertTrue(result["classification"].startswith("INDETERMINATE_"), result) + self.assert_json_safe(section) + self.assert_json_safe(result) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/pelvis-thigh-transition/README.md b/experiments/pelvis-thigh-transition/README.md new file mode 100644 index 0000000..d95dd9b --- /dev/null +++ b/experiments/pelvis-thigh-transition/README.md @@ -0,0 +1,340 @@ +# Bounded pelvis-to-thigh transition + +Experiment lifecycle: finished + +Evidence closure: complete + +Technology outcome: reject + +Outcome scope: the bounded candidate and appraisal target, not every fixed-topology +method or an accepted whole-body architecture. Completed 2026-09-05 (NZST). + +Owner: main technical lead; Ben retains direction and acceptance. + +## Authorization and question + +Ben authorized this local experiment on 2026-09-05, following read-only +diagnosis of the stopped hip pre-filter. Astra orchestration is explicitly +authorized for this task. This is not acceptance of a whole-body architecture, +production interface, morphology promise, or replacement of the old trial's +gates. Research context: RQ-002, RQ-012, RQ-020 and RQ-021. + +Can a single shared pelvic transition separately control pelvic wrap and +thigh descent, while keeping both sides and the adjacent abdomen one welded, +source-linked evaluated surface across the existing five profiles and an +executable ordinary-human reference? + +The source-linked hip centre, thigh direction and local frame must have +explicit geometric consumers and meaning on the final surface. Vertex +movement alone is not proof of the expected structural response. Attachment +curves are generated from dimensions and consistent rules, not authored mesh +repairs. Human and anthropomorphic targets are equally important; their +defaults need not be identical. The long-term quality target is polished +independent-artist-quality models and animation. Real-time use remains primary, +with optional offline enhancement; this experiment chooses no new budget or +simulation system. + +## Finite budget, fixed before any candidate run + +One initial construction plus **at most two shared geometric refinements**: +attempts 0, 1 and 2. Stop at the first technically passing and directly visually +credible candidate, or after attempt 2. Any change that changes generated +coordinates or topology after a candidate run counts, even a geometric bug +fix. No alternate construction, profile-specific repair, input retuning, +threshold relaxation or further refinement is authorized. The chosen local +topology is fixed before attempt 0 and cannot be replaced during refinement. + +Pure evidence-tool defects may receive at most two repair/replay batches; +retain the defective outputs and record each batch. Such a batch must not +change geometry, cases or quality thresholds. Abort and report if these bounds +are insufficient. Deterministic repetitions and predeclared perturbations are +evidence runs, not tuning rounds. Do not render or rerun the old pre-filter. + +## Construction boundary and cases + +Only lower abdomen, pelvis and proximal thigh transitions may change. Preserve +the surrounding upper root as context. Keep promising shoulder evidence +separate: inherited arm/upper-body failures neither disappear nor become +failures caused by the new lower-body construction. No distal anatomy, +rigging, bend implementation, general anatomy framework or simulation. + +The construction has one welded bilateral pelvic/groin region with explicit +thigh interfaces and dedicated transition rows. All cases use the same code +and topology; case names never select geometric formulas. Exact inputs, source +pointers, local frame derivation, final layout and numeric acceptance measures +are recorded in `inputs.json` and this README before attempt 0. + +Development cases: existing standard neutral, compact/broad and slender. +Required coverage: all existing five profiles without changing their source +projection, plus one concrete simplified ordinary-human pelvic case generated +through the same construction. The human case is an executable challenge to +cross-family coarse proportions, not measured anatomical truth, a human +whole-body fixture or proof of population coverage. Its numeric inputs are +fixed before execution and may not be repaired individually. + +Required perturbations: isolated pelvis width, thigh spacing/hip-centre +translation, thigh direction, front/back offset, one asymmetric combination, +and one deliberately incompatible case. Their inputs and expected geometric +responses are declared before running; rejection cannot be rationalized by +inventing source-coherence restrictions after results. + +## Evidence and stopping + +### Initial layout and structural meaning (fixed before attempt 0) + +Keep the predecessor's upper-root surface as context. Replace each eight-quad +hip band with three eight-quad bands: shared socket boundary, ring A, ring B, +and distal exit. This is 152 controls and 136 quads at L0, with five open ports; +two ordinary Catmull-Clark steps yield 544 and 2176 quads. The fixed layout is +shared across every case. There is no evaluated-surface correction stage. + +H is the world-space thigh-start landmark, coincident with the thigh part +origin in the existing source. It is this experiment's consistently derived +attachment centre, not a claim that the source's joint-frame hints have been +resolved into a rig. K is the source knee landmark. Direction d is normalize(K-H). +The local frame uses U=-d, X=normalized projection of world +X orthogonal to d, +and F=X cross U. Identity source frames and a downward direction with +dot(d,world-down)>0.9 are admitted here. The distal skin exit is E=H+0.45(K-H), +not H. This ends within the proximal thigh; it adds no knee or distal anatomy. + +The eight perimeter directions normalize the predecessor's nonzero (u,q) +pairs to (a,b). The socket uses lateral radius +(lower-pelvis lateral extent minus |H.x-L.x| plus thigh r_x)/2 on its outer +side, and 1.10*r_x on its inner side; front/back depths average the respective +pelvic depth relative to H with thigh r_z. Its upward displacement is +0.35*(L.y-H.y)+0.25*r_y+0.15*(L.y-H.y)*side_sign*a. Thus source r_y controls +proximal vertical flesh extent, not bone length. Negative radii, nonpositive +L.y-H.y, inconsistent H/P_s, or nonpositive nominal medial clearance +(H_right.x-H_left.x-r_x_left-r_x_right) are input rejections, never clamps. + +Ring B is elliptical in the source-derived frame at H+0.30(K-H), with r_x/r_z; +the exit has the same ellipse at E. Ring A initially averages socket and ring +B coordinates. Sparse actual subdivision weights carry source construction +contributors to each evaluated vertex. These formulas are hypotheses, not +anatomical facts, and may consume the recorded refinement budget if wrong. + +### Quantitative checks fixed before attempt 0 + +Per-case scale S=max(2*lower_pelvis.rL, hip-centre spacing, hip-to-knee length). + +- All levels: valid indexing, finite coordinates, connected orientable welded + topology, five declared boundary loops, full ownership and lineage coverage; + edge length >1e-7*S and triangle area >1e-10*S^2. These are numerical + degeneracy checks, not anatomical quality scores. +- No non-adjacent lower-body self-intersections at L0/L1/L2. Report inherited + upper-only failures separately; they prohibit whole-root success claims. +- At L2, affected lower-body adjacent-face normal angle <=60 degrees and + consistent orientation of the two triangles in each quad. L0/L1 normal + angles are diagnostic, not inherited candidate acceptance thresholds. +- Each evaluated thigh exit: centroid within 1e-6*S of E; plane residual + <=1e-6*S; outward normal within 5 degrees of d; surface-induced outward + co-normal within 25 degrees of d. Frame orthonormality tolerance 1e-10. + Projected half-spans must be 0.75..1.05 times source r_x/r_z, allowing the + declared eight-control subdivision contraction without erasing dimensions. +- At H, rays along +/-X and +/-F must have odd distinct intersections with + the actual side's skin and nearest distance 0.6..2.5 times its respective + source radius. Report the analogous section 0.1 hip-to-knee length above H + diagnostically. This tests the centre's structural relation to skin rather + than a moving metadata marker. It is not a bone-clearance or tissue model. +- Source-centre perturbations must move the evaluated exit centroid by the + same vector within 1e-6*S; direction changes must rotate the exit axis with + the source direction. Increasing pelvic width must leave exits fixed and + increase an outer above-H section radius by at least 1e-4*S. Changed source + cases must change serialized evaluated coordinates, not just metadata. +- Repeat the final evidence under PYTHONHASHSEED=17 and 29, requiring identical + meshes, numeric reports and PNGs after excluding declared runtime paths. + +These thresholds guard this specific candidate's integrity and structural +response. They do not promise final anatomy, deformation or realism. Numerical +success remains insufficient without direct visual inspection. + +Retain ownership, welding, winding, finite/nondegenerate geometry, manifold +connectivity with declared open ports, non-self-intersection, deterministic +output and inspectable input-to-evaluated-surface causality. Do not retain the +predecessor's exact control counts or exact affected-vertex cardinalities as +universal requirements. Quantitative checks and scales are fixed before the +initial run. Report L0, L1 and L2 separately rather than equating a coarse cage +fold with visibly folded final skin. + +Reject apparent bulb-mounted thighs, sideways attachment instead of descent, +implausible pelvic/groin shape, abrupt abdominal transitions, pinching, folds +or intersecting skin even if numerical checks pass. Actual opaque shaded +surface views are primary evidence. Capture matched front, side and rear +three-quarter views; use underside and lineage/frame overlays only to explain +that same surface. Render numerically rejected meshes where finite valid +indexing makes it safe; label them REJECTED and keep them separate from any +passing candidate. Never hide a failed result behind publication gates. + +Every attempt executes from its own captured source tree and concrete inputs, +not the mutable worktree. Record file hashes, runtime/dependency identities, +commands, exact output inventory and any before/after drift. Capture dependency +files, not only a Git OID. Output manifests distinguish technical outcome, +direct visual judgment and human acceptance. Large meshes and images stay in +the local cache, not Git. No gallery publication, network effects, push or +merge is authorized. Return local matched image artifacts to Ben. + +Preserve the failed pre-filter's scripts and diagnostics, recovered current +dependency snapshots and explicit concurrency/missing-image limitations. +Recovered dependencies are not falsely labelled original executing code. +Preserve unrelated pending local review fixes, including the protected dirty +observation inbox. + +If successful, recommend a separately authorized small hip-bend/binding test +before further body expansion. Static success does not establish animation or +tissue-deformation quality. + +## Reproduction + +All Python geometry, tests and rendering use the existing pinned environment: + +```bash +experiments/current-form-surface-preview/surface_preview_launcher.sh SCRIPT ARGUMENTS +``` + +The first geometry/render capture uses `preserve_evidence.py --snapshot` to +capture this source tree and the pinned runtime into +`/home/ben/.cache/creature-kernel/pelvis-thigh-transition/attempt-0-snapshot`. +Run its captured `preview_only.py --inputs inputs.json --output ABSENT_PATH` +through the captured launcher, with `CK_CURRENT_FORM_SURFACE_PYTHON` pointing +to the captured `runtime/bin/python` and `PYTHONHASHSEED=17`. Input SHA-256: +`23132147711c792d3617963323d29e86323ed8539c64dbe9f18b32ce6be43db1`. +This first phase deliberately claims no numeric pass. Checks and their final +runner are captured separately after preflight corrections; their replay must +use identical construction, rendering and concrete input bytes. +Preservation scripts using +only the standard library may use `python3`; never use it for Pillow/NumPy work. + +## Results + +Attempt 0 captured and rendered all twelve cases. Parent visual inspection +rejects the pronounced pelvic shelf and elongated tall-profile pelvic region. +The initial numeric runner rejected its own nested checker report at depth 8; +`attempt-0-checked` preserves these tool errors, not geometric conclusions. +Evidence repair batch 1 raises only that serialization bound to 64 and replays +the identical construction, inputs and checks. Geometry remains unchanged. +Budget consumed: 1 initial run, 2/2 geometric refinements, +2/2 evidence-tool repair batches reserved. The first replay exposed two further +checker defects: the imported collision module lacked Python module registration, +and a generic port-name fallback selected neck/arm instead of thigh exits. +Evidence repair batch 2 fixes only those adapters and preserves the first replay +as tool-invalid. No geometric result is inferred from those false failures. + +### Refinement 1 (declared before execution) + +Actual L2 thigh-exit checks pass on all six mandatory attempt-0 surfaces. +The inherited j1 axial row switches abruptly between a lateral upper-pelvis +selector and a central lower-abdomen selector, with a boxy superellipse. +Hypothesis: this contributes to the visible pelvic shelf independently of the +now-controlled thigh descent. Replace only this row's formula: u=(i-2.5)/2.5, +q=k-1, t=u²; blend lower-abdomen radii and its centre (y averaged with upper +pelvis) toward upper-pelvis radii/centre with t. Normalize (u,q) onto an ellipse +instead of the previous exponent-2.6 section. No topology, source input, socket, +transition rows, exits, upper context j>=2, evaluator or threshold changes. +This spends refinement 1; it is not yet evidence of anatomical improvement. + +### Refinement 2 (declared before execution; final geometry budget) + +Direct inspection of all six attempt-1 bodies shows a reduced shelf, but the +high arch between short descending thigh stubs remains visually unconvincing. +Test a lower medial socket while retaining the outer wrap height: with +w=(1+side_sign*a)/2, socket y=H.y+w*(0.50*D+0.25*r_y)-(1-w)*0.10*length. +All other attempt-1 rules and every input remain unchanged. This is a shared +construction change, not an evaluated-surface repair. It tests whether the +existing neighbouring faces can form a credible lower central transition. +It may expose a conflict with the declared individual-side H ray test; that +test is not relaxed. Stop after this candidate's evidence, passing or failing. + +Parent has inspected all six mandatory attempts' matched primary views. +Attempt 2 is rejected: the inner opening is lower but the broad bridge/short +thigh-root proportions remain unconvincing, especially in the five inherited +profiles. The synthetic human is more plausible locally, not a whole-body pass. +Attempt-2 source-centre medial rays hit no own-side hip triangles in every main +case. Diagnostic rays against the whole lower surface instead hit the opposite +outer skin once (neutral distance 2.329349334160044; human 0.2838537160302547). +This supports a continuous pelvic envelope, rather than demonstrating H lies +outside the body. It does not replace or pass the frozen individual-side gate. +Final full checks and deterministic repetition are complete; no geometry remains +authorized. All further implementation requires a new user decision. + +### Evidence locations and interpretation + +All paths below are under +`/home/ben/.cache/creature-kernel/pelvis-thigh-transition/`: + +| Attempt | Captured code/runtime | Complete numeric evidence | Parent surface judgment | +| --- | --- | --- | --- | +| 0 | `attempt-0-final-check-snapshot` | `attempt-0-final-check/run-report.json`: all 11 valid cases pass; invalid case rejects | Reject: pelvic shelf and high arch | +| 1 | `attempt-1-snapshot` | `attempt-1-checked/run-report.json`: all 11 valid cases pass; invalid case rejects | Shelf improved; shared anatomical quality still insufficient | +| 2 | `attempt-2-snapshot` | `attempt-2-checked-seed17` and `attempt-2-checked-seed29`: all 11 valid cases fail only the declared H-containment condition; invalid case rejects | Reject at final budget; broad bridge/short-root appearance remains | + +`attempt-N-preview/CASE/surface.png` retains matched front, side and rear +three-quarter surfaces for every input, including rejected input diagnostics. +The numeric run case directories also retain full-root context, lower-crop, +underside and separate source-intention overlays. Context is not a shoulder +reappraisal. No whole-root, rigging, bend or animation quality claim is made. + +The final closure uses the captured `closure-snapshot` helper +`finish_evidence.py --first .../attempt-2-checked-seed17 --repeat +.../attempt-2-checked-seed29 --output .../final-rejected` with the captured +runtime and launcher. It compares mesh/PNG bytes and numeric reports, then +renders the stored final meshes with an explicit parent rejection label. +It does not construct or repair geometry. + +Executing geometry identities, SHA-256 of `construction.py`: + +- Attempt 0: `6e8b5157f58dc8f1d02be3d11c19f64eace374b74667a0d21f36f62a87782ecb`. +- Attempt 1: `b65fb1f00df90351e3e31bcc0a3ac382349b1e8cea016b35c5e974a9c74d1bb8`. +- Attempt 2 and closure: `7fd457e2206165eb5e404ce81732f4157234a2e13a64008d96ae75d6abcf5cdb`. + +Each snapshot manifest records all copied source and installed runtime files. +The copied venv includes Python executable and site-packages; the host OS, +standard-library base and system libraries remain an explicit reproducibility +boundary, not a fully hermetic operating-system image. Earlier failed pre-filter +files remain in `failed-prefilter-20260905`, with original-vs-recovered provenance +and missing-render limitations retained in `results/prefilter-closure.json`. + +The tall/slender source profiles lower H and K together without extending their +hip-to-knee distance. Their elongated pelvic region therefore cannot be +attributed solely to the new surface formula. The generator did not retune these +inputs. No result proves arbitrary morphology generalization or that every +one of the 92 available dimensions has been individually verified. + +Luna performed bounded input, construction, checks, rendering and evidence +implementation; Sol-medium supplied one independent pre-run code audit. The +Astra parent settled both shared refinements, inspected critical formulas and +all six mandatory actual-surface sets for each attempt, and owns rejection. +The preserved tool failures also show the synthetic tests initially missed +real report nesting, port selection and dependency-import integration defects. +They are evidence limitations/fixes, not anatomical failures. + +### Final result and next decision + +All eleven valid final cases pass topology/lineage, finite and nondegenerate +geometry, zero lower intersections at L0/L1/L2, L2 fold/quad orientation, and +source-linked exit/frame/span checks. All six prescribed perturbation responses +pass, including correct rejection of the incompatible input. All eleven valid +cases fail the unchanged individual-side H-containment requirement. The negative +fixture has real intersections/folds; its detailed collision inventory is +truncated at the helper's reporting cap and is explicitly incomplete, not a +precise total or a pass. + +Final repetition under hash seeds 17 and 29 is exact: **180/180 mesh/PNG artifacts +match byte-for-byte**, and all 14 numeric/input comparisons match. See +`final-rejected/determinism-report.json` and `final-rejected/output-manifest.json` +(manifest SHA-256 `2df9357a4ad08e416e96440addabf3a1bddae4dd61c2a38d965c0e379db1b0bc`). +All six primary final view sets are at `final-rejected/CASE/surface.png`, labelled +REJECTED - FINAL BUDGET; underside views are separate. No passing gallery exists. + +Validation: 33 synthetic tests passed; final actual-surface runs and repeat +checks completed. Documentation/whitespace validation also passed. Budget used: +initial candidate plus 2/2 geometric refinements and 2/2 evidence-tool repair +batches. No push, merge, gallery publication, rig or body expansion occurred. + +Recommendation (not authorization): preserve the source-linked transition, but +do not proceed to bending yet. A next bounded scope should first reconcile +pelvic/hip source proportions and define containment of the coherent pelvic +envelope rather than requiring an isolated tube around each H. Re-test coarse +pelvic/groin form with human and contrasting anthropomorphic inputs before a +small bend/binding checkpoint. Neither changing this failed trial's verdict nor +replacing topology is justified by these results. Fine anatomy and animation +quality remain unproved; subdivision or rendering alone cannot supply them. diff --git a/experiments/pelvis-thigh-transition/cases.py b/experiments/pelvis-thigh-transition/cases.py new file mode 100644 index 0000000..ef9915d --- /dev/null +++ b/experiments/pelvis-thigh-transition/cases.py @@ -0,0 +1,360 @@ +"""Numeric pelvis/thigh transition cases; geometry is deliberately out of scope.""" +from __future__ import annotations + +import copy +import hashlib +import json +import math +import sys +from pathlib import Path +from typing import Any + +ROOT = Path(__file__).resolve().parents[2] +EXACT_PACKAGE = ROOT / "experiments/owned-root-assembly-successor-exact-five" +if str(EXACT_PACKAGE) not in sys.path: + sys.path.insert(0, str(EXACT_PACKAGE)) + +import exact_five_runner as exact_five + + +SOURCE_ROLE = "examples/body-documents/stylized-digitigrade-biped-authored-form.json" +PROFILE_ROLE = "experiments/current-form-surface-preview/structural_profile_candidates.json" +SOURCE_PATH = ROOT / SOURCE_ROLE +PROFILE_PATH = ROOT / PROFILE_ROLE +SOURCE_SHA256 = "82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14" +PROFILE_SHA256 = "a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640" +PROFILE_IDS = ( + "standard_neutral_reference", + "compact_broad_short_limb_large_head", + "tall_narrow_long_legged", + "slender_long_limb", + "stocky_broad_chested", +) +HUMAN_ID = "ordinary_human_reference" +PERTURBATION_IDS = ( + "neutral_pelvis_width_plus_10pct", + "neutral_left_spacing_minus_005", + "neutral_left_direction_tilt_5deg", + "neutral_left_front_offset_plus_005", + "neutral_left_asymmetric_xz_and_radius", + "neutral_invalid_close_thick", +) + + +def _load_json(path: Path) -> dict[str, Any]: + expected = {SOURCE_PATH: SOURCE_SHA256, PROFILE_PATH: PROFILE_SHA256}.get(path) + raw = path.read_bytes() + if expected is None or hashlib.sha256(raw).hexdigest() != expected: + raise ValueError(f"fixed input SHA-256 mismatch before loading: {path}") + return exact_five.profiles.load_json(path, path.name) + + +def _address_key(address: dict[str, Any]) -> str: + return f"{address['namespace']}|{address['kind']}|{'|'.join(address['anchors'])}|{address['role']}" + + +def _source_indexes(source: dict[str, Any]) -> dict[str, dict[str, int]]: + body = source["body"] + parts = {_address_key(row["address"]): index for index, row in enumerate(body["parts"])} + landmarks = { + (row["owner"]["anchors"][0] if row["owner"]["anchors"] else "", row["owner"]["role"], row["role"]): index + for index, row in enumerate(body["landmarks"]) + } + frames = { + (_address_key(row["owner"]), row["role"]): index + for index, row in enumerate(body["frames"]) + } + joints = { + (_address_key(row["address"]), row["address"]["anchors"][0] if row["address"]["anchors"] else ""): index + for index, row in enumerate(body["joints"]) + } + return {"parts": parts, "landmarks": landmarks, "frames": frames, "joints": joints} + + +def _validate_identity_thigh_inputs(source: dict[str, Any]) -> None: + indexes = _source_indexes(source) + for side in ("left", "right"): + part_key = _part_key(side) + part = source["body"]["parts"][indexes["parts"][part_key]] + if part["placement"]["rotation_xyzw"] != [0, 0, 0, 1]: + raise ValueError(f"{part_key} placement rotation is not identity") + frame = source["body"]["frames"][indexes["frames"][(part_key, "form_leg_profile_control")]] + transform = frame["transform"] + if transform["translation"] != [0, 0, 0] or transform["rotation_xyzw"] != [0, 0, 0, 1]: + raise ValueError(f"{part_key} control frame is not identity") + + +def _part_key(side: str) -> str: + return f"main|part|{side}|thigh" + + +def _part_world_translation(source: dict[str, Any], row: dict[str, Any], key: str) -> list[float]: + parts = {_address_key(item["address"]): item for item in source["body"]["parts"]} + + def resolve(current: str, trail: set[str]) -> list[float]: + if current in trail: + raise ValueError("part containment cycle") + placement = row["part_placements"][current] + parent = parts[current]["containment"].get("parent") + if parent is None: + return [float(value) for value in placement] + parent_key = _address_key(parent) + parent_world = resolve(parent_key, trail | {current}) + return [parent_world[index] + float(placement[index]) for index in range(3)] + + return resolve(key, set()) + + +def _part_chain_keys(source: dict[str, Any], key: str) -> list[str]: + parts = {_address_key(item["address"]): item for item in source["body"]["parts"]} + parent = parts[key]["containment"].get("parent") + return [_address_key(parent), *[key]] if parent is not None else [key] + + +def _pointer_values(prefix: str) -> list[str]: + return [f"{prefix}/{axis}" for axis in range(3)] + + +def _attachment_provenance(source: dict[str, Any], row: dict[str, Any], profile_index: int, side: str) -> dict[str, Any]: + indexes = _source_indexes(source) + part_key = _part_key(side) + part_index = indexes["parts"][part_key] + thigh_start_key = (side, "thigh", "form_leg_profile_thigh_start") + knee_key = (side, "thigh", "form_leg_profile_knee") + thigh_start_index = indexes["landmarks"][thigh_start_key] + knee_index = indexes["landmarks"][knee_key] + frame_index = indexes["frames"][(part_key, "form_leg_profile_control")] + hip_joint_index = indexes["joints"][(f"main|joint|{side}|hip", side)] + hip_joint = source["body"]["joints"][hip_joint_index] + frame_transform = source["body"]["frames"][frame_index]["transform"] + start_prefix = f"/body/landmarks/{thigh_start_index}/position" + knee_prefix = f"/body/landmarks/{knee_index}/position" + chain_keys = _part_chain_keys(source, part_key) + source_part_pointers = [_pointer_values(f"/body/parts/{indexes['parts'][chain_key]}/placement/translation") for chain_key in chain_keys] + profile_part_pointers = [_pointer_values(f"/profiles/{profile_index}/part_placements/{chain_key}") for chain_key in chain_keys] + return { + "frame": { + "source_pointers": [f"/body/frames/{frame_index}/transform"], + "translation": frame_transform["translation"], + "rotation_xyzw": frame_transform["rotation_xyzw"], + "interpretation": "identity frame admitted; no rig or joint resolution", + }, + "centre": { + "derivation": "profile.world-part-plus-thigh-start.v1", + "source_pointers": [pointer for group in source_part_pointers for pointer in group] + _pointer_values(start_prefix), + "profile_pointers": [pointer for group in profile_part_pointers for pointer in group], + }, + "knee": { + "derivation": "profile.world-part-plus-source-knee.v1", + "source_pointers": [pointer for group in source_part_pointers for pointer in group] + _pointer_values(knee_prefix), + "profile_pointers": [pointer for group in profile_part_pointers for pointer in group], + }, + "joint_hint": { + "source_pointer": f"/body/joints/{hip_joint_index}", + "proximal_frame": hip_joint["proximal_frame"], + "distal_frame": hip_joint["distal_frame"], + "interpretation": "source hint retained for provenance; not interpreted as a solved skeleton", + }, + } + + +def _profile_case(profile_id: str, source: dict[str, Any], table: dict[str, Any]) -> dict[str, Any]: + projection = exact_five.project_profile(profile_id, source, table) + ids = tuple(exact_five.surface.GEOMETRY_COMPONENT_IDS) + components = {component: float(value) for component, value in zip(ids, projection["carrier"].values)} + profile_index = projection["profile_index"] + row = table["profiles"][profile_index] + attachments = {} + bindings = {} + for side in ("left", "right"): + world_part = _part_world_translation(source, row, _part_key(side)) + indexes = _source_indexes(source) + start_index = indexes["landmarks"][(side, "thigh", "form_leg_profile_thigh_start")] + knee_index = indexes["landmarks"][(side, "thigh", "form_leg_profile_knee")] + start = source["body"]["landmarks"][start_index]["position"] + knee = source["body"]["landmarks"][knee_index]["position"] + attachments[side] = { + "centre": [world_part[index] + float(start[index]) for index in range(3)], + "knee": [world_part[index] + float(knee[index]) for index in range(3)], + } + bindings[side] = _attachment_provenance(source, row, profile_index, side) + return { + "id": profile_id, + "role": "exactfive_unchanged_profileprojection", + "components": components, + "attachments": attachments, + "provenance": { + "source": {"path": SOURCE_ROLE, "sha256": SOURCE_SHA256}, + "profile": {"path": PROFILE_ROLE, "sha256": PROFILE_SHA256, "profile_id": profile_id, "profile_index": profile_index}, + "bindings": bindings, + "claim": "unchanged exact-five profile projection; no geometry executed", + }, + } + + +def _set_station(components: dict[str, float], station: str, centre: list[float], radii: tuple[float, float, float]) -> None: + station = f"stations.{station}" + for axis, value in zip(("x", "y", "z"), centre): + components[f"{station}.C.{axis}"] = float(value) + for name, value in zip(("rL", "rA", "rP"), radii): + components[f"{station}.{name}"] = float(value) + + +def _set_hip(components: dict[str, float], side: str, centre: list[float], radii: tuple[float, float, float]) -> None: + prefix = f"hips.{side}.P_s" + components[f"{prefix}.x"], components[f"{prefix}.y"], components[f"{prefix}.z"] = map(float, centre) + components[f"hips.{side}.r_x"], components[f"hips.{side}.r_y"], components[f"hips.{side}.r_z"] = map(float, radii) + + +def _human_case(neutral: dict[str, Any]) -> dict[str, Any]: + components = {key: float(value) * 0.16 for key, value in neutral["components"].items()} + hips = {"left": [-0.105, -0.16, 0.0], "right": [0.105, -0.16, 0.0]} + knees = {"left": [-0.105, -0.59, 0.0], "right": [0.105, -0.59, 0.0]} + for side in ("left", "right"): + _set_hip(components, side, hips[side], (0.085, 0.085, 0.090)) + _set_station(components, "lower_pelvis", [0.0, -0.072, 0.0], (0.180, 0.105, 0.120)) + _set_station(components, "upper_pelvis", [0.0, -0.032, 0.0], (0.160, 0.100, 0.105)) + _set_station(components, "lower_abdomen", [0.0, 0.040, 0.0], (0.135, 0.090, 0.090)) + _set_station(components, "waist_abdomen", [0.0, 0.080, 0.0], (0.120, 0.080, 0.075)) + return { + "id": HUMAN_ID, + "role": "executable_cross_family_challenge", + "components": components, + "attachments": {side: {"centre": hips[side], "knee": knees[side]} for side in ("left", "right")}, + "provenance": { + "source": {"path": SOURCE_ROLE, "sha256": SOURCE_SHA256}, + "profile": {"path": PROFILE_ROLE, "sha256": PROFILE_SHA256, "base_case": "standard_neutral_reference", "uniform_scale": 0.16}, + "bindings": {side: {"centre": {"derivation": "inputs.json.case-override.v1", "source_pointers": [f"/cases/5/attachments/{side}/centre"], "profile_pointers": []}, "knee": {"derivation": "inputs.json.case-override.v1", "source_pointers": [f"/cases/5/attachments/{side}/knee"], "profile_pointers": []}} for side in ("left", "right")}, + "authoritative_input_path": "experiments/pelvis-thigh-transition/inputs.json", + "override_authority": "literal /cases/5/attachments/* pointers and numeric component overrides in this file; source/profile are only uniformly scaled base context", + "frame": {"translation": [0.0, 0.0, 0.0], "rotation_xyzw": [0.0, 0.0, 0.0, 1.0], "interpretation": "identity local pelvis frame; no rig or joint resolution"}, + "claim": "synthetic adult coarse pelvic proportions; not anatomical measured truth or a whole-body fixture", + }, + } + + +def _copy_neutral(neutral: dict[str, Any], case_id: str, expected_change: dict[str, Any]) -> dict[str, Any]: + return {"id": case_id, "role": "predeclared_neutral_perturbation", "components": copy.deepcopy(neutral["components"]), "attachments": copy.deepcopy(neutral["attachments"]), "provenance": {"source": {"path": SOURCE_ROLE, "sha256": SOURCE_SHA256}, "profile": {"path": PROFILE_ROLE, "sha256": PROFILE_SHA256, "base_case": "standard_neutral_reference"}, "bindings": copy.deepcopy(neutral["provenance"]["bindings"]), "expected_change": expected_change, "claim": "numeric perturbation declaration only; no geometry executed"}} + + +def _perturbations(neutral: dict[str, Any]) -> list[dict[str, Any]]: + cases = [] + width = _copy_neutral(neutral, PERTURBATION_IDS[0], {"direction": "pelvic lower/upper lateral radii increase"}) + width["components"]["stations.lower_pelvis.rL"] *= 1.10 + width["components"]["stations.upper_pelvis.rL"] *= 1.10 + cases.append(width) + + spacing = _copy_neutral(neutral, PERTURBATION_IDS[1], {"direction": "left hip, knee and thigh start translate -x by 0.05"}) + spacing["components"]["hips.left.P_s.x"] -= 0.05 + for point in spacing["attachments"]["left"].values(): + point[0] -= 0.05 + cases.append(spacing) + + direction = _copy_neutral(neutral, PERTURBATION_IDS[2], {"direction": "left thigh direction tilts 5 degrees inward"}) + h = direction["attachments"]["left"]["centre"] + original_knee = neutral["attachments"]["left"]["knee"] + original_leg_length = math.sqrt(sum((original_knee[index] - h[index]) ** 2 for index in range(3))) + direction["attachments"]["left"]["knee"] = [ + h[0] + 0.0871557427 * original_leg_length, + h[1] - 0.9961946981 * original_leg_length, + h[2], + ] + direction["provenance"]["expected_change"]["original_leg_length"] = original_leg_length + cases.append(direction) + + front = _copy_neutral(neutral, PERTURBATION_IDS[3], {"direction": "left hip, knee and thigh start translate +z by 0.05"}) + front["components"]["hips.left.P_s.z"] += 0.05 + for point in front["attachments"]["left"].values(): + point[2] += 0.05 + cases.append(front) + + asymmetric = _copy_neutral(neutral, PERTURBATION_IDS[4], {"direction": "left x spacing -0.05, z offset +0.05, left lateral start radius +5%"}) + asymmetric["components"]["hips.left.P_s.x"] -= 0.05 + asymmetric["components"]["hips.left.P_s.z"] += 0.05 + asymmetric["components"]["hips.left.r_x"] *= 1.05 + for point in asymmetric["attachments"]["left"].values(): + point[0] -= 0.05 + point[2] += 0.05 + cases.append(asymmetric) + + invalid = _copy_neutral(neutral, PERTURBATION_IDS[5], {"direction": "deliberately incompatible medial overlap; expected rejection"}) + invalid["components"]["hips.left.P_s.x"] = -0.2 + invalid["components"]["hips.right.P_s.x"] = 0.2 + invalid["components"]["hips.left.r_x"] = 0.35 + invalid["components"]["hips.right.r_x"] = 0.35 + for side, x in (("left", -0.2), ("right", 0.2)): + invalid["attachments"][side]["centre"][0] = x + invalid["attachments"][side]["knee"][0] = x + cases.append(invalid) + return cases + + +def _validate_case(case: dict[str, Any], ids: tuple[str, ...]) -> None: + if set(case) != {"id", "role", "components", "attachments", "provenance"}: + raise ValueError(f"case shape mismatch: {case.get('id')}") + if tuple(case["components"]) != ids or any(type(value) is not float or not math.isfinite(value) for value in case["components"].values()): + raise ValueError(f"component carrier mismatch: {case['id']}") + for side in ("left", "right"): + for name in ("centre", "knee"): + point = case["attachments"][side][name] + if type(point) is not list or len(point) != 3 or any(type(value) is not float or not math.isfinite(value) for value in point): + raise ValueError(f"attachment mismatch: {case['id']} {side} {name}") + + +def load_cases() -> list[dict[str, Any]]: + """Return concrete carriers and attachment inputs without constructing geometry.""" + source = _load_json(SOURCE_PATH) + table = _load_json(PROFILE_PATH) + _validate_identity_thigh_inputs(source) + profile_cases = [_profile_case(profile_id, source, table) for profile_id in PROFILE_IDS] + human = _human_case(profile_cases[0]) + cases = [*profile_cases, human, *_perturbations(profile_cases[0])] + ids = tuple(exact_five.surface.GEOMETRY_COMPONENT_IDS) + for case in cases: + _validate_case(case, ids) + return cases + + +def _document(cases: list[dict[str, Any]]) -> dict[str, Any]: + return { + "schema": "creature-kernel.pelvis-thigh-transition-inputs.v1", + "source": {"path": SOURCE_ROLE, "sha256": SOURCE_SHA256}, + "profile_table": {"path": PROFILE_ROLE, "sha256": PROFILE_SHA256}, + "component_ids": list(exact_five.surface.GEOMETRY_COMPONENT_IDS), + "mandatory_case_ids": [*PROFILE_IDS, HUMAN_ID], + "perturbation_case_ids": list(PERTURBATION_IDS), + "cases": cases, + "immutability": "mandatory fixtures and perturbations are fixed once this file is written", + } + + +def _bytes(value: dict[str, Any]) -> bytes: + return (json.dumps(value, sort_keys=True, indent=2, separators=(",", ": ")) + "\n").encode("utf-8") + + +def _path(raw: str) -> Path: + path = Path(raw) + if not path.is_absolute() or path != Path(*path.parts) or path != path.resolve(strict=False): + raise ValueError("path must be absolute and canonical") + return path + + +def main(argv: list[str] | None = None) -> int: + argv = list(sys.argv[1:] if argv is None else argv) + if len(argv) != 2 or argv[0] not in {"--write-inputs", "--check-inputs"}: + raise SystemExit("usage: cases.py --write-inputs ABSENT_PATH | --check-inputs PATH") + path = _path(argv[1]) + expected = _bytes(_document(load_cases())) + if argv[0] == "--write-inputs": + if path.exists() or path.is_symlink(): + raise ValueError(f"refusing to replace existing input file: {path}") + path.write_bytes(expected) + return 0 + actual = path.read_bytes() + if actual != expected: + raise ValueError("inputs.json does not match current concrete case generation") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/experiments/pelvis-thigh-transition/checks.py b/experiments/pelvis-thigh-transition/checks.py new file mode 100644 index 0000000..4fde4a0 --- /dev/null +++ b/experiments/pelvis-thigh-transition/checks.py @@ -0,0 +1,1694 @@ +"""Fail-closed technical checks for the pelvis-to-thigh transition experiment. + +This module intentionally consumes only the experiment's generic evaluated +surface API. It does not call the stopped experiment's frozen geometry +validator and it does not construct or repair geometry. + +The public entry points are deliberately total: + +``check_case(case, levels)`` + Returns a JSON-safe diagnostic report, including malformed-input failures. + +``compare_perturbation(base_case, base_levels, case, levels)`` + Checks the declared response of a pre-declared perturbation without + selecting a profile or changing either input. +""" + +from __future__ import annotations + +import importlib.util +import itertools +import math +import sys +from collections import defaultdict +from pathlib import Path +from typing import Any, Iterable, Mapping, Sequence + + +_EXPECTED_BASE_VERTICES = 152 +_EXPECTED_BASE_QUADS = 136 +_LEVELS = (0, 1, 2) +_SCALE_EDGE_FLOOR = 1.0e-7 +_SCALE_TRIANGLE_FLOOR = 1.0e-10 +_FRAME_TOLERANCE = 1.0e-10 +_POSITION_TOLERANCE = 1.0e-6 +_RAY_TOLERANCE = 1.0e-6 +_EXIT_DIRECTION_TOLERANCE = 1.0e-6 +_EXIT_NORMAL_COS = math.cos(math.radians(5.0)) +_EXIT_CONORMAL_COS = math.cos(math.radians(25.0)) +_LOWER_FOLD_LIMIT_DEGREES = 60.0 +_RAY_RADIUS_MIN = 0.6 +_RAY_RADIUS_MAX = 2.5 +_PELVIS_WIDTH_RESPONSE_FLOOR = 1.0e-4 +_INTERSECTION_GROUP_COUNT = 3 + +_LOWER_OWNER_WORDS = ( + "pelvis", + "left_hip", + "right_hip", + "hip_left", + "hip_right", + "abdomen", + "groin", + "left_thigh", + "right_thigh", + "thigh_left", + "thigh_right", + "proximal_thigh", +) +_PELVIS_RAY_OWNER_WORDS = ( + "pelvis", + "left_hip", + "right_hip", + "hip_left", + "hip_right", + "groin", + "left_thigh", + "right_thigh", + "thigh_left", + "thigh_right", + "proximal_thigh", +) +_EXIT_NAME_WORDS = ("exit", "thigh", "left_hip", "right_hip") + + +class _CheckInputError(ValueError): + """An input-shape error which must become a report diagnostic.""" + + +def _is_mapping(value: Any) -> bool: + return isinstance(value, Mapping) + + +def _is_number(value: Any) -> bool: + return isinstance(value, (int, float)) and not isinstance(value, bool) + + +def _finite(value: Any) -> bool: + return _is_number(value) and math.isfinite(float(value)) + + +def _as_sequence(value: Any, label: str) -> list[Any]: + if isinstance(value, (str, bytes, bytearray)) or value is None: + raise _CheckInputError(f"{label} must be a sequence") + try: + result = list(value) + except (TypeError, ValueError) as exc: + raise _CheckInputError(f"{label} must be a sequence") from exc + return result + + +def _vector(value: Any, label: str) -> tuple[float, float, float]: + values = _as_sequence(value, label) + if len(values) != 3 or any(not _finite(item) for item in values): + raise _CheckInputError(f"{label} must be a finite 3-vector") + return (float(values[0]), float(values[1]), float(values[2])) + + +def _vec_add(a: Sequence[float], b: Sequence[float]) -> tuple[float, float, float]: + return tuple(float(a[i]) + float(b[i]) for i in range(3)) # type: ignore[return-value] + + +def _vec_sub(a: Sequence[float], b: Sequence[float]) -> tuple[float, float, float]: + return tuple(float(a[i]) - float(b[i]) for i in range(3)) # type: ignore[return-value] + + +def _vec_scale(a: Sequence[float], factor: float) -> tuple[float, float, float]: + return tuple(float(a[i]) * factor for i in range(3)) # type: ignore[return-value] + + +def _dot(a: Sequence[float], b: Sequence[float]) -> float: + return sum(float(a[i]) * float(b[i]) for i in range(3)) + + +def _cross(a: Sequence[float], b: Sequence[float]) -> tuple[float, float, float]: + return ( + float(a[1]) * float(b[2]) - float(a[2]) * float(b[1]), + float(a[2]) * float(b[0]) - float(a[0]) * float(b[2]), + float(a[0]) * float(b[1]) - float(a[1]) * float(b[0]), + ) + + +def _norm(a: Sequence[float]) -> float: + return math.sqrt(_dot(a, a)) + + +def _unit(a: Sequence[float], label: str) -> tuple[float, float, float]: + length = _norm(a) + if not math.isfinite(length) or length <= 0.0: + raise _CheckInputError(f"{label} must be finite and nonzero") + return _vec_scale(a, 1.0 / length) + + +def _angle_degrees(a: Sequence[float], b: Sequence[float]) -> float: + ua = _unit(a, "angle vector A") + ub = _unit(b, "angle vector B") + return math.degrees(math.acos(max(-1.0, min(1.0, _dot(ua, ub))))) + + +def _angle_radians(a: Sequence[float], b: Sequence[float]) -> float: + ua = _unit(a, "angle vector A") + ub = _unit(b, "angle vector B") + return math.acos(max(-1.0, min(1.0, _dot(ua, ub)))) + + +def _json_safe(value: Any) -> Any: + """Convert report values to JSON-compatible primitives, fail-closed.""" + + if isinstance(value, Mapping): + return {str(key): _json_safe(item) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [_json_safe(item) for item in value] + if isinstance(value, Path): + return str(value) + if isinstance(value, bool) or value is None or isinstance(value, str): + return value + if isinstance(value, int): + return value + if isinstance(value, float): + return value if math.isfinite(value) else None + if _is_number(value): + numeric = float(value) + return numeric if math.isfinite(numeric) else None + return str(value) + + +def _error(code: str, message: str, **details: Any) -> dict[str, Any]: + return {"code": code, "message": message, **details} + + +def _case_name(case: Any) -> str: + if not _is_mapping(case): + return "" + for key in ("name", "case", "id", "case_name"): + value = case.get(key) + if isinstance(value, str) and value: + return value + return "" + + +def _normalise_levels(levels: Any) -> dict[int, Any]: + if isinstance(levels, Mapping): + if isinstance(levels.get("levels"), (list, tuple, Mapping)): + return _normalise_levels(levels["levels"]) + result: dict[int, Any] = {} + for level in _LEVELS: + if level in levels: + result[level] = levels[level] + elif str(level) in levels: + result[level] = levels[str(level)] + return result + values = _as_sequence(levels, "levels") + return {index: values[index] for index in range(min(len(values), 3))} + + +def _mesh_parts(mesh: Any, level: int) -> tuple[list[tuple[float, float, float]], list[tuple[int, int, int, int]], list[str], list[str], dict[str, list[int]], Any, Any, Any]: + if not _is_mapping(mesh): + raise _CheckInputError(f"L{level} mesh must be a mapping") + raw_vertices = _as_sequence(mesh.get("vertices"), f"L{level}.vertices") + vertices = [_vector(point, f"L{level}.vertices[{index}]") for index, point in enumerate(raw_vertices)] + if not vertices: + raise _CheckInputError(f"L{level}.vertices must not be empty") + + raw_quads = _as_sequence(mesh.get("quads"), f"L{level}.quads") + quads: list[tuple[int, int, int, int]] = [] + for face_index, raw_face in enumerate(raw_quads): + face = _as_sequence(raw_face, f"L{level}.quads[{face_index}]") + if len(face) != 4: + raise _CheckInputError(f"L{level}.quads[{face_index}] must have four indices") + if any(isinstance(index, bool) or not isinstance(index, int) for index in face): + raise _CheckInputError(f"L{level}.quads[{face_index}] indices must be integers") + checked = tuple(int(index) for index in face) + if len(set(checked)) != 4 or any(index < 0 or index >= len(vertices) for index in checked): + raise _CheckInputError(f"L{level}.quads[{face_index}] contains an invalid index") + quads.append(checked) # type: ignore[arg-type] + if not quads: + raise _CheckInputError(f"L{level}.quads must not be empty") + + face_owners = _owner_rows(mesh.get("face_owners"), len(quads), f"L{level}.face_owners") + control_owners = _owner_rows(mesh.get("control_owners"), len(vertices), f"L{level}.control_owners") + loops = _loops(mesh.get("loops"), len(vertices), f"L{level}.loops") + return vertices, quads, face_owners, control_owners, loops, mesh.get("base_stencils"), mesh.get("frames"), mesh.get("metadata") + + +def _owner_rows(value: Any, expected: int, label: str) -> list[str]: + if isinstance(value, Mapping): + rows: list[Any] = [] + for index in range(expected): + if index in value: + rows.append(value[index]) + elif str(index) in value: + rows.append(value[str(index)]) + else: + rows.append(None) + else: + rows = _as_sequence(value, label) + if len(rows) != expected: + raise _CheckInputError(f"{label} must cover all {expected} entries") + if any(not isinstance(owner, str) or not owner for owner in rows): + raise _CheckInputError(f"{label} entries must be non-empty strings") + return list(rows) + + +def _lineage_rows(value: Any, vertex_count: int, base_vertex_count: int | None, label: str) -> list[list[tuple[int, float]]]: + rows = _as_sequence(value, label) + if len(rows) != vertex_count: + raise _CheckInputError(f"{label} must cover every vertex") + result: list[list[tuple[int, float]]] = [] + for row_index, raw_row in enumerate(rows): + terms = _as_sequence(raw_row, f"{label}[{row_index}]") + if not terms: + raise _CheckInputError(f"{label}[{row_index}] must not be empty") + checked: list[tuple[int, float]] = [] + previous = -1 + for term in terms: + pair = _as_sequence(term, f"{label}[{row_index}] term") + if len(pair) != 2 or isinstance(pair[0], bool) or not isinstance(pair[0], int): + raise _CheckInputError(f"{label}[{row_index}] has an invalid base index") + index = int(pair[0]) + if index <= previous or index < 0 or (base_vertex_count is not None and index >= base_vertex_count): + raise _CheckInputError(f"{label}[{row_index}] base indices must be sorted and in range") + if not _finite(pair[1]) or float(pair[1]) == 0.0: + raise _CheckInputError(f"{label}[{row_index}] has an invalid coefficient") + checked.append((index, float(pair[1]))) + previous = index + result.append(checked) + return result + + +def _loops(value: Any, vertex_count: int, label: str) -> dict[str, list[int]]: + if not _is_mapping(value): + raise _CheckInputError(f"{label} must be a mapping of declared loops") + result: dict[str, list[int]] = {} + used: set[int] = set() + for name, raw_loop in value.items(): + if not isinstance(name, str) or not name: + raise _CheckInputError(f"{label} names must be non-empty strings") + loop = _as_sequence(raw_loop, f"{label}.{name}") + if len(loop) < 3 or any(isinstance(index, bool) or not isinstance(index, int) for index in loop): + raise _CheckInputError(f"{label}.{name} must be a simple index cycle") + checked = [int(index) for index in loop] + if len(set(checked)) != len(checked) or any(index < 0 or index >= vertex_count for index in checked): + raise _CheckInputError(f"{label}.{name} contains invalid or repeated indices") + if used.intersection(checked): + raise _CheckInputError(f"{label} loops must not share boundary vertices") + used.update(checked) + result[name] = checked + if len(result) != 5: + raise _CheckInputError(f"{label} must contain exactly five declared loops") + return result + + +def _edge_incidence(quads: Sequence[Sequence[int]]) -> dict[tuple[int, int], list[tuple[int, int, int]]]: + incidence: dict[tuple[int, int], list[tuple[int, int, int]]] = defaultdict(list) + for face_index, face in enumerate(quads): + for slot, start in enumerate(face): + end = face[(slot + 1) % len(face)] + incidence[(min(start, end), max(start, end))].append((face_index, start, end)) + return dict(incidence) + + +def _canonical_cycle(cycle: Sequence[int]) -> tuple[int, ...]: + values = tuple(cycle) + candidates = [] + for sequence in (values, tuple(reversed(values))): + candidates.extend(sequence[index:] + sequence[:index] for index in range(len(sequence))) + return min(candidates) + + +def _cyclic_equal(actual: Sequence[int], expected: Sequence[int]) -> bool: + actual_values = tuple(actual) + expected_values = tuple(expected) + return any(actual_values == target[index:] + target[:index] + for target in (expected_values, tuple(reversed(expected_values))) + for index in range(len(target))) + + +def _boundary_cycles(incidence: Mapping[tuple[int, int], Sequence[tuple[int, int, int]]]) -> list[list[int]]: + boundary_edges = [uses[0] for uses in incidence.values() if len(uses) == 1] + outgoing: dict[int, list[int]] = defaultdict(list) + for _, start, end in boundary_edges: + outgoing[start].append(end) + if any(len(targets) != 1 for targets in outgoing.values()): + raise _CheckInputError("boundary edges do not form directed cycles") + next_vertex = {start: targets[0] for start, targets in outgoing.items()} + remaining = set(next_vertex) + cycles: list[list[int]] = [] + while remaining: + start = min(remaining) + current = start + cycle: list[int] = [] + while current in remaining: + remaining.remove(current) + cycle.append(current) + current = next_vertex[current] + if current != start or len(cycle) < 3: + raise _CheckInputError("boundary edge cycle is not closed") + cycles.append(cycle) + return cycles + + +def _connected_components(quads: Sequence[Sequence[int]], vertex_count: int) -> int: + adjacency: dict[int, set[int]] = {index: set() for index in range(vertex_count)} + for face in quads: + for first, second in zip(face, face[1:] + face[:1]): + adjacency[first].add(second) + adjacency[second].add(first) + unseen = set(range(vertex_count)) + count = 0 + while unseen: + count += 1 + todo = [unseen.pop()] + while todo: + neighbours = adjacency[todo.pop()].intersection(unseen) + unseen.difference_update(neighbours) + todo.extend(neighbours) + return count + + +def _mesh_structural_checks(level: int, mesh: Any, base_quad_count: int | None, + base_vertex_count: int | None = None) -> tuple[dict[str, Any], dict[str, Any] | None]: + """Return a level report and parsed values, or a report on malformed input.""" + + level_report: dict[str, Any] = {"level": level, "pass": False, "checks": {}, "errors": []} + try: + vertices, quads, face_owners, control_owners, loops, base_stencils, frames, metadata = _mesh_parts(mesh, level) + lineage = _lineage_rows(base_stencils, len(vertices), len(vertices) if level == 0 else base_vertex_count, + f"L{level}.base_stencils") + except Exception as exc: # total public report, including malformed mesh input + level_report["errors"].append(_error("invalid_mesh", str(exc))) + level_report["render_safe"] = False + return level_report, None + + level_report["vertex_count"] = len(vertices) + level_report["quad_count"] = len(quads) + level_report["checks"]["finite_vertices"] = all(_finite(value) for point in vertices for value in point) + level_report["checks"]["valid_indices"] = True + level_report["checks"]["owner_coverage"] = ( + len(face_owners) == len(quads) + and len(control_owners) == len(vertices) + and all(isinstance(value, str) and value for value in face_owners + control_owners) + ) + level_report["checks"]["lineage_coverage"] = len(lineage) == len(vertices) + level_report["checks"]["all_vertices_used"] = len({index for face in quads for index in face}) == len(vertices) + + incidence = _edge_incidence(quads) + edge_uses_valid = all(len(uses) in (1, 2) for uses in incidence.values()) + orientation_valid = all( + len(uses) != 2 or (uses[0][1], uses[0][2]) == (uses[1][2], uses[1][1]) + for uses in incidence.values() + ) + boundary_cycles: list[list[int]] = [] + boundary_valid = True + try: + boundary_cycles = _boundary_cycles(incidence) + except Exception as exc: + boundary_valid = False + level_report["errors"].append(_error("boundary_cycle", str(exc))) + declared_boundary_match = boundary_valid and len(boundary_cycles) == 5 and all( + any(_cyclic_equal(actual, declared) for declared in loops.values()) + for actual in boundary_cycles + ) + level_report["checks"].update({ + "connected_components": _connected_components(quads, len(vertices)), + "connected_one": _connected_components(quads, len(vertices)) == 1, + "edge_use_one_or_two": edge_uses_valid, + "interior_edges_opposite": orientation_valid, + "boundary_count_exact_five": len(boundary_cycles) == 5, + "declared_boundary_loops": declared_boundary_match, + "duplicate_quads": len({_canonical_cycle(face) for face in quads}) == len(quads), + }) + if not level_report["checks"]["connected_one"]: + level_report["errors"].append(_error("disconnected_surface", "surface must have one connected component")) + if not level_report["checks"]["owner_coverage"]: + level_report["errors"].append(_error("owner_coverage", "face and control owners must cover the mesh exactly")) + if not level_report["checks"]["lineage_coverage"]: + level_report["errors"].append(_error("lineage_coverage", "base stencils must cover every evaluated vertex")) + if base_quad_count is None: + base_quad_count = len(quads) if level == 0 else None + if level == 0: + exact_counts = len(vertices) == _EXPECTED_BASE_VERTICES and len(quads) == _EXPECTED_BASE_QUADS + level_report["checks"]["exact_initial_counts"] = exact_counts + elif base_quad_count is not None: + level_report["checks"]["fourfold_face_count"] = len(quads) == base_quad_count * (4 ** level) + else: + level_report["checks"]["fourfold_face_count"] = False + level_report["errors"].append(_error("missing_base_count", "cannot compare subdivision face count without L0")) + + if not level_report["checks"]["finite_vertices"]: + level_report["errors"].append(_error("nonfinite_vertices", "vertices contain non-finite coordinates")) + if not level_report["checks"]["all_vertices_used"]: + level_report["errors"].append(_error("unused_vertices", "every vertex ID must be used by a quad")) + if not edge_uses_valid: + level_report["errors"].append(_error("nonmanifold_edges", "every edge must have one or two incident faces")) + if not orientation_valid: + level_report["errors"].append(_error("orientation_conflict", "interior edge directions must be opposite")) + if not declared_boundary_match: + level_report["errors"].append(_error("boundary_declaration", "derived boundaries do not match five declared loops")) + if not level_report["checks"]["duplicate_quads"]: + level_report["errors"].append(_error("duplicate_quads", "duplicate or reversed/cyclic duplicate quads")) + if level == 0 and not level_report["checks"]["exact_initial_counts"]: + level_report["errors"].append(_error( + "initial_counts", f"L0 must contain exactly {_EXPECTED_BASE_VERTICES} vertices and {_EXPECTED_BASE_QUADS} quads")) + if level > 0 and not level_report["checks"]["fourfold_face_count"]: + level_report["errors"].append(_error("subdivision_face_count", "L1/L2 must have fourfold face counts")) + + # A finite, indexed, non-degenerate mesh remains safe to hand to the + # renderer even when a technical gate fails. + triangles = [triangle for face in quads for triangle in ((face[0], face[1], face[2]), (face[0], face[2], face[3]))] + triangle_areas = [0.5 * _norm(_cross(_vec_sub(vertices[b], vertices[a]), _vec_sub(vertices[c], vertices[a]))) + for a, b, c in triangles] + render_safe = bool(level_report["checks"]["finite_vertices"] and level_report["checks"]["valid_indices"] + and all(math.isfinite(area) and area > 0.0 for area in triangle_areas)) + level_report["render_safe"] = render_safe + parsed = { + "vertices": vertices, + "quads": quads, + "face_owners": face_owners, + "control_owners": control_owners, + "loops": loops, + "incidence": incidence, + "triangles": triangles, + "triangle_areas": triangle_areas, + "base_stencils": base_stencils, + "lineage": lineage, + "frames": frames, + "metadata": metadata, + "boundary_cycles": boundary_cycles, + } + level_report["checks"]["topology"] = not level_report["errors"] + level_report["pass"] = not level_report["errors"] + return level_report, parsed + + +def _lookup(mapping: Any, *keys: str) -> Any: + if not _is_mapping(mapping): + return None + for key in keys: + if key in mapping: + return mapping[key] + return None + + +def _source_mapping(case: Any) -> Mapping[str, Any]: + if not _is_mapping(case): + return {} + source = case.get("source") + # The preregistered case carrier uses ``source`` for provenance. Only a + # physical source metadata mapping is a source mapping for this checker. + if _is_mapping(source) and any(key in source for key in + ("H", "K", "hip_centres", "knee_centres", "lower_pelvis_width", "radii")): + return source + return case + + +def _find_number(mappings: Iterable[Any], keys: Sequence[str]) -> float | None: + for mapping in mappings: + value = _lookup(mapping, *keys) + if _finite(value): + return float(value) + return None + + +def _point_mapping(value: Any) -> dict[str, tuple[float, float, float]]: + result: dict[str, tuple[float, float, float]] = {} + if not _is_mapping(value): + return result + for key, raw_point in value.items(): + try: + result[str(key)] = _vector(raw_point, f"point {key}") + except Exception: + continue + return result + + +def _pair_distance(points: Mapping[str, Sequence[float]], first_words: Sequence[str], second_words: Sequence[str]) -> float | None: + first = next((points[key] for key in points if any(word in key.lower() for word in first_words)), None) + second = next((points[key] for key in points if any(word in key.lower() for word in second_words)), None) + if first is None or second is None: + return None + return _norm(_vec_sub(first, second)) + + +def _source_dimensions(case: Any) -> dict[str, Any]: + source = _source_mapping(case) + mappings = (source, case) + components = case.get("components", {}) if _is_mapping(case) and _is_mapping(case.get("components")) else {} + component_numbers = lambda *keys: next((float(components[key]) for key in keys + if _finite(components.get(key))), None) + pelvis_radius = component_numbers("stations.lower_pelvis.rL") + pelvis_width = _find_number(mappings, ("lower_pelvis_width", "pelvis_width", "width_pelvis")) + if pelvis_width is None and pelvis_radius is not None: + pelvis_width = 2.0 * pelvis_radius + if pelvis_width is None: + radius = _find_number(mappings, ("rL", "lower_radius", "pelvis_radius")) + if radius is not None: + pelvis_width = 2.0 * radius + + attachments = case.get("attachments", {}) if _is_mapping(case) else {} + hip_points = {str(side): _vector(item["centre"], f"{side} H") + for side, item in attachments.items() + if _is_mapping(item) and "centre" in item + and _is_mapping(case.get("attachments"))} + knee_points = {str(side): _vector(item["knee"], f"{side} K") + for side, item in attachments.items() + if _is_mapping(item) and "knee" in item + and _is_mapping(case.get("attachments"))} + hip_points.update({key: value for key, value in + _point_mapping(_lookup(source, "hip_centres", "hip_centers", "hips")).items() + if key not in hip_points}) + knee_points.update({key: value for key, value in + _point_mapping(_lookup(source, "knee_centres", "knee_centers", "knees")).items() + if key not in knee_points}) + if not hip_points: + for side in ("left", "right"): + values = [component_numbers(f"hips.{side}.P_s.{axis}") for axis in ("x", "y", "z")] + if all(value is not None for value in values): + hip_points[side] = tuple(values) # type: ignore[assignment] + hip_spacing = _find_number(mappings, ("hip_spacing", "hipSpacing")) + if hip_spacing is None: + hip_spacing = _pair_distance(hip_points, ("left",), ("right",)) + + hip_knee_distances: dict[str, float] = {} + explicit_hip_knee = _lookup(source, "hip_knee_distances", "hipKneeDistances") + if _is_mapping(explicit_hip_knee): + for key, value in explicit_hip_knee.items(): + if _finite(value): + hip_knee_distances[str(key)] = float(value) + for key, hip in hip_points.items(): + side = "left" if "left" in key.lower() else "right" if "right" in key.lower() else key + knee = next((point for knee_key, point in knee_points.items() if side in knee_key.lower()), None) + if knee is not None: + hip_knee_distances[side] = _norm(_vec_sub(knee, hip)) + explicit_distance = _find_number(mappings, ("distance_hip_knee", "hip_knee_distance", "hipKneeDistance")) + if explicit_distance is not None and not hip_knee_distances: + hip_knee_distances["all"] = explicit_distance + + declared_axis = _lookup(source, "axis", "source_axis", "sourceAxis") + try: + declared_axis = _unit(_vector(declared_axis, "source axis"), "source axis") + except Exception: + declared_axis = None + + source_h = _lookup(source, "H", "h", "structural_centre", "structural_center") + try: + source_h = _vector(source_h, "source H") + except Exception: + source_h = None + source_k = _lookup(source, "K", "k", "knee", "knee_centre", "knee_center") + try: + source_k = _vector(source_k, "source K") + except Exception: + source_k = None + # H is the source thigh-start attachment and K is the source knee + # landmark. A joint-frame hint is intentionally never consulted. + actual_axes: dict[str, tuple[float, float, float]] = {} + h_by_side: dict[str, tuple[float, float, float]] = {} + k_by_side: dict[str, tuple[float, float, float]] = {} + for side, hip in hip_points.items(): + if side in knee_points: + h_by_side[side] = hip + k_by_side[side] = knee_points[side] + try: + actual_axes[side] = _unit(_vec_sub(knee_points[side], hip), f"{side} H-to-K axis") + except Exception: + pass + if source_h is not None: + h_by_side.setdefault("default", source_h) + if source_k is not None: + k_by_side.setdefault("default", source_k) + if not actual_axes and source_h is not None and source_k is not None: + try: + actual_axes["default"] = _unit(_vec_sub(source_k, source_h), "source H-to-K axis") + except Exception: + pass + source_axis = next(iter(actual_axes.values()), declared_axis) + + radii = _lookup(source, "exit_radii", "radii", "thigh_radii", "source_radii") + if not _is_mapping(radii): + radii = {} + length = _find_number(mappings, ("length", "thigh_length", "hip_knee_length", "hipKneeLength")) + if length is None and hip_knee_distances: + length = max(hip_knee_distances.values()) + radii_from_components: dict[str, dict[str, float]] = {} + for side in ("left", "right"): + values = {axis: component_numbers(f"hips.{side}.r_{axis}") for axis in ("x", "y", "z")} + if any(value is not None for value in values.values()): + radii_from_components[side] = {key: value for key, value in values.items() if value is not None} + if radii_from_components: + if not _is_mapping(radii): + radii = {} + radii = {**radii, **radii_from_components} + r_y = {side: values.get("y") for side, values in radii_from_components.items() if values.get("y") is not None} + scale_inputs = [value for value in (pelvis_width, hip_spacing, max(hip_knee_distances.values(), default=None)) + if value is not None and value > 0.0] + scale = max(scale_inputs) if len(scale_inputs) == 3 else None + return { + "pelvis_width": pelvis_width, + "hip_spacing": hip_spacing, + "hip_knee_distances": hip_knee_distances, + "scale": scale, + "scale_inputs_complete": len(scale_inputs) == 3, + "hip_points": hip_points, + "knee_points": knee_points, + "H": source_h or next(iter(h_by_side.values()), None), + "H_by_side": h_by_side, + "K_by_side": k_by_side, + "axis": source_axis, + "declared_axis": declared_axis, + "actual_axes": actual_axes, + "length": length, + "radii": radii, + "r_y": r_y, + } + + +def _owner_is_lower(owner: str, pelvis_only: bool = False) -> bool: + normal = owner.lower().replace("-", "_").replace(" ", "_") + words = _PELVIS_RAY_OWNER_WORDS if pelvis_only else _LOWER_OWNER_WORDS + return any(word in normal for word in words) + + +def _triangle_normal(vertices: Sequence[Sequence[float]], triangle: Sequence[int]) -> tuple[float, float, float]: + return _cross(_vec_sub(vertices[triangle[1]], vertices[triangle[0]]), + _vec_sub(vertices[triangle[2]], vertices[triangle[0]])) + + +def _face_normal(vertices: Sequence[Sequence[float]], face: Sequence[int]) -> tuple[float, float, float]: + first = _triangle_normal(vertices, (face[0], face[1], face[2])) + second = _triangle_normal(vertices, (face[0], face[2], face[3])) + return _unit(_vec_add(first, second), "face normal") + + +def _triangle_inventory(parsed: Mapping[str, Any]) -> tuple[list[tuple[int, int, int]], list[int]]: + triangles = list(parsed["triangles"]) + owners = [index // 2 for index in range(len(triangles))] + return triangles, owners + + +def _intersection_report(vertices: Sequence[Sequence[float]], triangles: Sequence[Sequence[int]], face_ids: Sequence[int], face_owners: Sequence[str]) -> dict[str, Any]: + """Run the generic intersection diagnostic under its 4096-triangle cap. + + The new surface may contain 4352 triangles. Three disjoint groups are + used for the required pairwise unions; the three within-group calls are + also made because cross-group unions alone cannot mathematically cover + pairs whose two triangles share a group. Every call reuses the original + vertex array, so unreferenced vertices are intentionally not rewritten. + """ + + result: dict[str, Any] = { + "available": False, + "pair_policy_complete": True, + "collision_inventory_complete": True, + "vertex_array_reused": True, + "groups": [], + "calls": [], + "hit_pairs": [], + "lower_hit_pairs": [], + "upper_only_hit_pairs": [], + "errors": [], + } + try: + module_path = Path(__file__).resolve().parents[1] / "owned-root-assembly-successor" / "mesh_correctness.py" + spec = importlib.util.spec_from_file_location("owned_root_generic_mesh_correctness", module_path) + if spec is None or spec.loader is None: + raise _CheckInputError("generic intersection diagnostic could not be loaded") + module = importlib.util.module_from_spec(spec) + # Dataclasses resolve their declaring module through sys.modules. + sys.modules[spec.name] = module + spec.loader.exec_module(module) + intersection_diagnostics = module.intersection_diagnostics + except Exception as exc: + result["errors"].append(_error("intersection_unavailable", str(exc))) + return result + + triangle_count = len(triangles) + groups = [list(range(start, min(start + math.ceil(triangle_count / 3), triangle_count))) + for start in range(0, triangle_count, math.ceil(triangle_count / 3))] + while len(groups) < _INTERSECTION_GROUP_COUNT: + groups.append([]) + groups = groups[:_INTERSECTION_GROUP_COUNT] + result["groups"] = [{"group": index, "triangle_count": len(group), "triangle_ids": group} + for index, group in enumerate(groups)] + + # The three disjoint group unions cover every unordered triangle pair: + # each cross-group pair occurs in its group pair, and every within-group + # pair occurs in either union containing that group. + pair_group_specs = list(itertools.combinations(range(3), 2)) + seen_pairs: set[tuple[int, int]] = set() + for first_group, second_group in pair_group_specs: + local_ids = groups[first_group] if first_group == second_group else groups[first_group] + groups[second_group] + local_triangles = [triangles[index] for index in local_ids] + call: dict[str, Any] = { + "groups": [first_group, second_group], + "triangle_count": len(local_triangles), + "pair_policy_complete": False, + "hit_pairs": [], + } + if not local_triangles: + call["pair_policy_complete"] = True + result["calls"].append(call) + continue + try: + diagnostic = intersection_diagnostics(vertices, local_triangles) + call["pair_policy_complete"] = bool(diagnostic.get("pair_policy_complete")) + call["pair_count"] = diagnostic.get("pair_count", 0) + call["intersection_hit_count"] = diagnostic.get("intersection_hit_count", 0) + call["hit_pairs_truncated"] = bool(diagnostic.get("hit_pairs_truncated", False)) + if call["hit_pairs_truncated"]: + call["collision_inventory_complete"] = False + result["collision_inventory_complete"] = False + result["errors"].append(_error( + "incomplete_collision_inventory", + "generic intersection helper truncated hit_pairs at its evidence cap", + groups=[first_group, second_group], + hit_count=diagnostic.get("intersection_hit_count"), + )) + for local_first, local_second in diagnostic.get("hit_pairs", ()): + global_first = local_ids[int(local_first)] + global_second = local_ids[int(local_second)] + pair = tuple(sorted((global_first, global_second))) + if pair not in seen_pairs: + seen_pairs.add(pair) + result["hit_pairs"].append(pair) + face_pair = (face_ids[pair[0]], face_ids[pair[1]]) + owners = (face_owners[face_pair[0]], face_owners[face_pair[1]]) + if any(_owner_is_lower(owner) for owner in owners): + result["lower_hit_pairs"].append({"triangles": pair, "faces": face_pair, "owners": owners}) + else: + result["upper_only_hit_pairs"].append({"triangles": pair, "faces": face_pair, "owners": owners}) + call["hit_pairs"].append(pair) + except Exception as exc: + call["error"] = _error("intersection_failure", str(exc)) + result["errors"].append(call["error"]) + result["pair_policy_complete"] = False + result["calls"].append(call) + result["available"] = not result["errors"] + result["pair_policy_complete"] = result["available"] and all(call["pair_policy_complete"] for call in result["calls"]) + result["hit_pairs"].sort() + result["lower_hit_pairs"].sort(key=lambda item: tuple(item["triangles"])) + result["upper_only_hit_pairs"].sort(key=lambda item: tuple(item["triangles"])) + result["unreferenced_vertex_count"] = len(vertices) - len({index for triangle in triangles for index in triangle}) + result["pass"] = (result["pair_policy_complete"] and result["collision_inventory_complete"] + and not result["lower_hit_pairs"]) + return result + + +def _dimension_gates(parsed: Mapping[str, Any], scale_info: Mapping[str, Any], level: int) -> dict[str, Any]: + scale = scale_info.get("scale") + result: dict[str, Any] = {"scale": scale, "scale_source": "case_source_dimensions" if scale is not None else None} + edges = parsed["incidence"] + edge_lengths = [_norm(_vec_sub(parsed["vertices"][edge[1]], parsed["vertices"][edge[0]])) for edge in edges] + triangle_areas = list(parsed["triangle_areas"]) + if scale is None or not _finite(scale) or float(scale) <= 0.0: + result.update({"available": False, "pass": False, "edge_min": min(edge_lengths, default=None), + "triangle_area_min": min(triangle_areas, default=None)}) + result["error"] = _error("missing_scale", "S requires pelvis width, hip spacing, and hip-knee distance") + return result + scale = float(scale) + edge_threshold = _SCALE_EDGE_FLOOR * scale + area_threshold = _SCALE_TRIANGLE_FLOOR * scale * scale + result.update({ + "available": True, + "edge_min": min(edge_lengths, default=None), + "edge_threshold": edge_threshold, + "triangle_area_min": min(triangle_areas, default=None), + "triangle_area_threshold": area_threshold, + "edge_floor_pass": bool(edge_lengths) and min(edge_lengths) > edge_threshold, + "triangle_area_floor_pass": bool(triangle_areas) and min(triangle_areas) > area_threshold, + }) + result["pass"] = result["edge_floor_pass"] and result["triangle_area_floor_pass"] + if not result["pass"]: + result["error"] = _error("scaled_degeneracy", f"L{level} edge/triangle floors failed at case scale S") + return result + + +def _frame_sources(case: Any, final_parsed: Mapping[str, Any] | None) -> list[tuple[str, Mapping[str, Any]]]: + sources: list[tuple[str, Mapping[str, Any]]] = [] + # Final evaluated metadata is authoritative. Case-level metadata is a + # fallback for the synthetic unit fixtures only. + if final_parsed is not None and _is_mapping(final_parsed.get("frames")): + return [("L2.frames", final_parsed["frames"])] + if _is_mapping(case): + for key in ("frames", "frame"): + value = case.get(key) + if _is_mapping(value): + sources.append((f"case.{key}", value)) + if final_parsed is not None and _is_mapping(final_parsed.get("frames")): + sources.append(("L2.frames", final_parsed["frames"])) + return sources + + +def _frame_records(case: Any, final_parsed: Mapping[str, Any] | None) -> list[tuple[str, Mapping[str, Any]]]: + records: list[tuple[str, Mapping[str, Any]]] = [] + for source_name, source in _frame_sources(case, final_parsed): + direct_keys = {"H", "h", "X", "x", "U", "u", "Y", "y", "F", "f", "Z", "z", "axis", "d", "direction"} + if direct_keys.intersection(source): + records.append((source_name, source)) + continue + for key, value in source.items(): + if _is_mapping(value): + records.append((str(key), value)) + # A frame may be stored as a list of side records. + if final_parsed is not None and isinstance(final_parsed.get("frames"), (list, tuple)): + for index, value in enumerate(final_parsed["frames"]): + if _is_mapping(value): + records.append((f"L2.frames[{index}]", value)) + # Keep one record per label/source to avoid duplicate case and mesh copies. + unique: list[tuple[str, Mapping[str, Any]]] = [] + seen: set[tuple[str, int]] = set() + for label, record in records: + identity = (label, id(record)) + if identity not in seen: + seen.add(identity) + unique.append((label, record)) + return unique + + +def _frame_vectors(record: Mapping[str, Any]) -> tuple[tuple[float, float, float], ...]: + nested = _lookup(record, "frame", "XYZ", "xyz") + frame = nested if _is_mapping(nested) else record + x = _lookup(frame, "X", "x", "right") + u = _lookup(frame, "U", "u", "Y", "y", "up") + f = _lookup(frame, "F", "f", "Z", "z", "front") + return _vector(x, "frame X"), _vector(u, "frame U/Y"), _vector(f, "frame F/Z") + + +def _metadata_vector(record: Mapping[str, Any], *keys: str) -> tuple[float, float, float] | None: + value = _lookup(record, *keys) + try: + return _vector(value, ".".join(keys)) + except Exception: + return None + + +def _metadata_h(record: Mapping[str, Any], scale_info: Mapping[str, Any], side: str | None = None) -> tuple[float, float, float] | None: + by_side = scale_info.get("H_by_side", {}) + if side and side in by_side: + return by_side[side] + if scale_info.get("H") is not None: + return scale_info["H"] + return _metadata_vector(record, "H", "h", "structural_center", "structural_centre") + + +def _metadata_axis(record: Mapping[str, Any], scale_info: Mapping[str, Any], side: str | None = None) -> tuple[float, float, float] | None: + direct = _metadata_vector(record, "axis", "d", "direction", "source_axis", "sourceAxis") + if direct is not None: + try: + return _unit(direct, "metadata axis") + except Exception: + return None + actual = scale_info.get("actual_axes", {}) + if side and side in actual: + return actual[side] + axis = scale_info.get("axis") + if axis is not None: + try: + return _unit(axis, "source axis") + except Exception: + return None + return None + + +def _record_side(label: str) -> str | None: + normal = label.lower() + if "left" in normal: + return "left" + if "right" in normal: + return "right" + return None + + +def _expected_mapping(case: Any, final_parsed: Mapping[str, Any] | None) -> Any: + values = [] + if _is_mapping(case): + values.extend(case.get(key) for key in ("exitexpected", "exit_expected", "exit_expectations") if key in case) + source = case.get("source") + if _is_mapping(source): + values.extend(source.get(key) for key in ("exitexpected", "exit_expected", "exit_expectations") if key in source) + if final_parsed is not None: + frames = final_parsed.get("frames") + if _is_mapping(frames): + values.extend(frames.get(key) for key in ("exitexpected", "exit_expected") if key in frames) + metadata = final_parsed.get("metadata") + if _is_mapping(metadata): + values.extend(metadata.get(key) for key in ("exitexpected", "exit_expected") if key in metadata) + return next((value for value in values if value is not None), None) + + +def _index_loop_mapping(case: Any, final_parsed: Mapping[str, Any]) -> Any: + values = [] + if _is_mapping(case): + values.extend(case.get(key) for key in ("indexloops", "index_loops") if key in case) + source = case.get("source") + if _is_mapping(source): + values.extend(source.get(key) for key in ("indexloops", "index_loops") if key in source) + frames = final_parsed.get("frames") + if _is_mapping(frames): + values.extend(frames.get(key) for key in ("indexloops", "index_loops") if key in frames) + metadata = final_parsed.get("metadata") + if _is_mapping(metadata): + values.extend(metadata.get(key) for key in ("indexloops", "index_loops", "transition_indices") if key in metadata) + return next((value for value in values if value is not None), None) + + +def _exit_loop_names(case: Any, parsed: Mapping[str, Any]) -> list[str]: + loops = parsed["loops"] + if "port.left_thigh" in loops and "port.right_thigh" in loops: + return ["port.left_thigh", "port.right_thigh"] + index_mapping = _index_loop_mapping(case, parsed) + names: list[str] = [] + if _is_mapping(index_mapping): + for key, value in index_mapping.items(): + if isinstance(value, str) and value in loops: + names.append(value) + elif isinstance(key, str) and key in loops: + names.append(key) + elif isinstance(key, str) and isinstance(value, (list, tuple)): + try: + wanted = tuple(int(item) for item in value) + except Exception: + wanted = () + for loop_name, loop in loops.items(): + if tuple(loop) == wanted: + names.append(loop_name) + if not names: + names = [name for name in loops if any(word in name.lower() for word in _EXIT_NAME_WORDS)] + if len(names) < 2: + return [] # Missing exits fail the exit gate; other ports are not substitutes. + return list(dict.fromkeys(names))[:2] + + +def _side_value(mapping: Any, loop_name: str, side: str | None) -> Any: + if not _is_mapping(mapping): + return mapping + for key in (loop_name, side, "left" if side == "left" else "right" if side == "right" else None): + if key is not None and key in mapping: + return mapping[key] + return mapping.get("default") + + +def _expected_exit(case: Any, parsed: Mapping[str, Any], loop_name: str, side: str | None, record: Mapping[str, Any] | None, + scale_info: Mapping[str, Any]) -> tuple[tuple[float, float, float] | None, str]: + # Compute E from the captured source attachments first. Exported L2 + # metadata is evidence to compare, never the source of truth for E. + h = scale_info.get("H_by_side", {}).get(side) if side else None + k = scale_info.get("K_by_side", {}).get(side) if side else None + if h is None: + h = scale_info.get("H") + if k is None: + k = scale_info.get("K_by_side", {}).get("default") + if h is not None and k is not None: + delta = _vec_sub(k, h) + length = _norm(delta) + if length > 0.0: + return _vec_add(h, _vec_scale(delta, 0.45)), "source.H+0.45*(source.K-source.H)" + + explicit = _side_value(_expected_mapping(case, parsed), loop_name, side) + if _is_mapping(explicit): + for key in ("centroid", "center", "centre", "E", "expected"): + if key in explicit: + try: + return _vector(explicit[key], f"expected exit {loop_name}"), f"declared.{key}.fallback" + except Exception: + pass + elif explicit is not None: + try: + return _vector(explicit, f"expected exit {loop_name}"), "declared.fallback" + except Exception: + pass + return None, "unavailable" + + +def _source_radius(scale_info: Mapping[str, Any], loop_name: str, side: str | None, axis: str) -> float | None: + radii = scale_info.get("radii", {}) + values: list[Any] = [] + if _is_mapping(radii): + for key in (loop_name, side, "left" if side == "left" else "right" if side == "right" else None): + if key is not None and key in radii: + values.append(radii[key]) + values.append(radii) + for value in values: + if _is_mapping(value): + aliases = ("rx", "r_x", "x", "X") if axis == "X" else ("rz", "r_z", "z", "F", "f") + candidate = _lookup(value, *aliases) + if _finite(candidate) and float(candidate) > 0.0: + return float(candidate) + elif _finite(value) and float(value) > 0.0: + return float(value) + return None + + +def _loop_geometry(vertices: Sequence[Sequence[float]], loop: Sequence[int]) -> tuple[tuple[float, float, float], tuple[float, float, float], float]: + centroid = _vec_scale(tuple(sum(vertices[index][axis] for index in loop) for axis in range(3)), 1.0 / len(loop)) + area = (0.0, 0.0, 0.0) + for index, vertex in enumerate(loop): + area = _vec_add(area, _cross(_vec_sub(vertices[vertex], centroid), + _vec_sub(vertices[loop[(index + 1) % len(loop)]], centroid))) + area = _vec_scale(area, 0.5) + return centroid, _unit(area, "exit loop plane normal"), _norm(area) + + +def _exit_checks(case: Any, parsed: Mapping[str, Any], scale_info: Mapping[str, Any]) -> dict[str, Any]: + loops = parsed["loops"] + names = _exit_loop_names(case, parsed) + records = _frame_records(case, parsed) + result: dict[str, Any] = { + "exit_loops": names, + "pass": True, + "loops": {}, + "frame_records": [], + "render_metrics": {"pass": True, "loops": {}}, + } + record_by_side = {_record_side(label): record for label, record in records if _record_side(label) is not None} + if len(names) != 2: + result["pass"] = False + result["errors"] = [_error("exit_loop_count", "two exit loops are required")] + + for label, record in records: + frame_report: dict[str, Any] = {"label": label, "pass": False} + try: + x_axis, u_axis, f_axis = _frame_vectors(record) + lengths = tuple(_norm(axis) for axis in (x_axis, u_axis, f_axis)) + dots = (_dot(x_axis, u_axis), _dot(x_axis, f_axis), _dot(u_axis, f_axis)) + handed = _dot(_cross(x_axis, u_axis), f_axis) + frame_report.update({"X": x_axis, "U": u_axis, "F": f_axis, "lengths": lengths, "pairwise_dots": dots, + "right_handed_dot": handed, + "orthonormal": all(abs(length - 1.0) <= _FRAME_TOLERANCE for length in lengths) + and all(abs(dot) <= _FRAME_TOLERANCE for dot in dots), + "right_handed": handed >= 1.0 - _FRAME_TOLERANCE}) + side = _record_side(label) + reported_axis = _metadata_vector(record, "axis", "d", "direction", "source_axis", "sourceAxis") + axis = _unit(reported_axis, "evaluated frame axis") if reported_axis is not None else None + actual_axis = scale_info.get("actual_axes", {}).get(side) if side else scale_info.get("axis") + source_h = _metadata_h({}, scale_info, side) + frame_h = _metadata_vector(record, "H", "h") + frame_report["source_H_matches"] = (source_h is not None and frame_h is not None + and _norm(_vec_sub(frame_h, source_h)) <= _POSITION_TOLERANCE * float(scale_info.get("scale") or 0.0)) + if axis is not None and actual_axis is not None: + frame_report["source_axis_angle_radians"] = _angle_radians(axis, actual_axis) + frame_report["source_axis_matches_actual_H_to_K"] = frame_report["source_axis_angle_radians"] <= _EXIT_DIRECTION_TOLERANCE + else: + frame_report["source_axis_matches_actual_H_to_K"] = False + frame_report["source_axis_error"] = _error("missing_source_axis", "source axis and actual H-to-K axis are required") + frame_report["pass"] = bool(frame_report["orthonormal"] and frame_report["right_handed"] + and frame_report["source_H_matches"] + and frame_report["source_axis_matches_actual_H_to_K"]) + if not frame_report["pass"]: + frame_report["error"] = _error("frame_gate", "frame must be finite orthonormal, right-handed, and source-axis aligned") + except Exception as exc: + frame_report["error"] = _error("invalid_frame", str(exc)) + result["frame_records"].append(frame_report) + result["pass"] = result["pass"] and frame_report["pass"] + + for loop_name in names: + loop = loops[loop_name] + side = "left" if "left" in loop_name.lower() else "right" if "right" in loop_name.lower() else None + record = record_by_side.get(side) if side else (records[0][1] if records else None) + loop_report: dict[str, Any] = {"loop": loop_name, "pass": False} + render_report: dict[str, Any] = {"pass": False} + try: + centroid, plane_normal, area = _loop_geometry(parsed["vertices"], loop) + axis = _metadata_axis(record or {}, scale_info, side) + expected, expected_source = _expected_exit(case, parsed, loop_name, side, record, scale_info) + centroid_error = _norm(_vec_sub(centroid, expected)) if expected is not None else None + plane_error = max(abs(_dot(_vec_sub(parsed["vertices"][index], centroid), plane_normal)) for index in loop) + # Declared open-loop winding is inward for this interface. The + # geometric outward normal is therefore the negated Newell normal. + outward_normal = _vec_scale(plane_normal, -1.0) + outward_dot = _dot(outward_normal, axis) if axis is not None else None + incidence = parsed["incidence"] + conormals: list[float] = [] + missing_edges: list[tuple[int, int]] = [] + face_normals = {face_index: _face_normal(parsed["vertices"], face) + for face_index, face in enumerate(parsed["quads"])} + for index, start in enumerate(loop): + end = loop[(index + 1) % len(loop)] + uses = incidence.get((min(start, end), max(start, end)), []) + if len(uses) != 1: + missing_edges.append((start, end)) + continue + tangent = _unit(_vec_sub(parsed["vertices"][end], parsed["vertices"][start]), "exit loop tangent") + adjacent_normal = face_normals[uses[0][0]] + co_normal = _unit(_cross(tangent, adjacent_normal), "exit co-normal") + conormals.append(_dot(co_normal, axis) if axis is not None else float("nan")) + min_conormal = min(conormals) if conormals else None + loop_report.update({"centroid": centroid, "expected_centroid": expected, "expected_source": expected_source, + "centroid_error": centroid_error, "plane_normal": plane_normal, + "outward_normal": outward_normal, "plane_error": plane_error, + "plane_area": area, "outward_dot_direction": outward_dot, "co_normals": conormals, + "co_normal_min": min_conormal, "missing_boundary_edges": missing_edges}) + loop_report["pass"] = bool(expected is not None and axis is not None and centroid_error <= _POSITION_TOLERANCE * float(scale_info.get("scale") or 0.0) + and outward_dot is not None and outward_dot >= _EXIT_NORMAL_COS + and plane_error <= _POSITION_TOLERANCE * float(scale_info.get("scale") or 0.0) + and not missing_edges and min_conormal is not None and min_conormal >= _EXIT_CONORMAL_COS) + + x_axis, _, f_axis = _frame_vectors(record or {}) + projections_x = [_dot(_vec_sub(parsed["vertices"][index], centroid), x_axis) for index in loop] + projections_f = [_dot(_vec_sub(parsed["vertices"][index], centroid), f_axis) for index in loop] + half_x = 0.5 * (max(projections_x) - min(projections_x)) + half_f = 0.5 * (max(projections_f) - min(projections_f)) + source_rx = _source_radius(scale_info, loop_name, side, "X") + source_rz = _source_radius(scale_info, loop_name, side, "F") + ratios = {"X": half_x / source_rx if source_rx else None, "F": half_f / source_rz if source_rz else None} + render_report.update({"half_spans": {"X": half_x, "F": half_f}, "source_half_spans": {"X": source_rx, "F": source_rz}, + "ratios": ratios, + "span_pass": all(ratio is not None and 0.75 <= ratio <= 1.05 for ratio in ratios.values())}) + render_report["pass"] = bool(render_report["span_pass"]) + if not render_report["pass"]: + render_report["error"] = _error("exit_span_render_metric", "exit projected X/F half-spans must be 0.75..1.05 of source radii") + loop_report["render_metric_pass"] = render_report["pass"] + result["render_metrics"]["loops"][loop_name] = render_report + result["render_metrics"]["pass"] = result["render_metrics"]["pass"] and render_report["pass"] + except Exception as exc: + loop_report["error"] = _error("exit_loop_geometry", str(exc)) + result["render_metrics"]["loops"][loop_name] = render_report + result["render_metrics"]["pass"] = False + result["loops"][loop_name] = loop_report + result["pass"] = result["pass"] and loop_report["pass"] + result["pass"] = result["pass"] and result["render_metrics"]["pass"] + return result + + +def _lower_fold_checks(parsed: Mapping[str, Any]) -> dict[str, Any]: + incidence = parsed["incidence"] + face_normals = {index: _face_normal(parsed["vertices"], face) for index, face in enumerate(parsed["quads"])} + lower: list[dict[str, Any]] = [] + upper: list[dict[str, Any]] = [] + for edge, uses in incidence.items(): + if len(uses) != 2: + continue + first_face, second_face = uses[0][0], uses[1][0] + angle = _angle_degrees(face_normals[first_face], face_normals[second_face]) + row = {"edge": edge, "faces": [first_face, second_face], "owners": [parsed["face_owners"][first_face], parsed["face_owners"][second_face]], + "normal_angle_degrees": angle} + if any(_owner_is_lower(owner) for owner in row["owners"]): + lower.append(row) + else: + upper.append(row) + lower_failures = [row for row in lower if row["normal_angle_degrees"] > _LOWER_FOLD_LIMIT_DEGREES] + return { + "lower": {"pairs": lower, "failure_count": len(lower_failures), "pass": not lower_failures, + "failures": lower_failures, "limit_degrees": _LOWER_FOLD_LIMIT_DEGREES}, + "upper_inherited": {"pairs": upper, "diagnostic_only": True, "failure_count": 0, + "pass": True, "note": "upper folds are reported separately"}, + "control_angle_diagnostics": {"available": False, "gate": False, + "note": "control-angle observations are diagnostic only"}, + } + + +def _lower_quad_normal_checks(parsed: Mapping[str, Any]) -> dict[str, Any]: + failures = [] + samples = [] + for face_index, face in enumerate(parsed["quads"]): + if not _owner_is_lower(parsed["face_owners"][face_index]): + continue + first = _triangle_normal(parsed["vertices"], (face[0], face[1], face[2])) + second = _triangle_normal(parsed["vertices"], (face[0], face[2], face[3])) + value = _dot(first, second) + row = {"face": face_index, "normal_dot": value, "owner": parsed["face_owners"][face_index]} + samples.append(row) + if value < 0.0: + failures.append(row) + return {"samples": samples, "failure_count": len(failures), "failures": failures, "pass": not failures} + + +def _ray_triangle(origin: Sequence[float], direction: Sequence[float], vertices: Sequence[Sequence[float]], triangle: Sequence[int]) -> float | None: + a, b, c = (vertices[index] for index in triangle) + edge_one = _vec_sub(b, a) + edge_two = _vec_sub(c, a) + pvec = _cross(direction, edge_two) + determinant = _dot(edge_one, pvec) + if abs(determinant) <= 1.0e-14: + return None + inverse = 1.0 / determinant + tvec = _vec_sub(origin, a) + u = _dot(tvec, pvec) * inverse + if u < -1.0e-12 or u > 1.0 + 1.0e-12: + return None + qvec = _cross(tvec, edge_one) + v = _dot(direction, qvec) * inverse + if v < -1.0e-12 or u + v > 1.0 + 1.0e-12: + return None + distance = _dot(edge_two, qvec) * inverse + return distance if distance > 0.0 else None + + +def _deduplicate_hits(values: Sequence[float], tolerance: float) -> list[float]: + result: list[float] = [] + for value in sorted(values): + if not result or abs(value - result[-1]) > tolerance: + result.append(value) + return result + + +def _containment_checks(case: Any, parsed: Mapping[str, Any], scale_info: Mapping[str, Any]) -> dict[str, Any]: + scale = float(scale_info.get("scale") or 0.0) + result: dict[str, Any] = {"pass": False, "H_by_side": scale_info.get("H_by_side", {}), + "axis_by_side": scale_info.get("actual_axes", {}), "rays": {}, + "directional_radial_distances": {}, + "centres": {}, "section_above_H": {"diagnostic_only": True, "rays": {}}} + if scale <= 0.0: + result["error"] = _error("containment_inputs", "structural H and case scale S are required") + return result + records = _frame_records(case, parsed) + if not records: + result["error"] = _error("containment_frame", "actual L2 frame metadata is required") + return result + + any_record = False + all_sides_pass = True + for label, record in records: + side = _record_side(label) + h = _metadata_h(record, scale_info, side) + axis = _metadata_axis(record, scale_info, side) + try: + x_axis, _, f_axis = _frame_vectors(record) + except Exception as exc: + result["rays"][label] = {"pass": False, "error": _error("containment_frame", str(exc))} + all_sides_pass = False + continue + target_triangles = [triangle for triangle, face_index in zip(parsed["triangles"], range(len(parsed["triangles"]))) + if _owner_is_lower(parsed["face_owners"][face_index // 2], pelvis_only=True) + and (side is None or side in parsed["face_owners"][face_index // 2].lower())] + if not target_triangles: + target_triangles = [triangle for triangle, face_index in zip(parsed["triangles"], range(len(parsed["triangles"]))) + if _owner_is_lower(parsed["face_owners"][face_index // 2], pelvis_only=True)] + if h is None or not target_triangles: + result["rays"][label] = {"pass": False, "error": _error("containment_inputs", "H and side-hip/pelvis triangles are required")} + all_sides_pass = False + continue + any_record = True + side_rays: dict[str, Any] = {} + side_pass = True + for direction_name, direction, radius_axis in ( + ("+X", x_axis, "X"), ("-X", _vec_scale(x_axis, -1.0), "X"), + ("+F", f_axis, "F"), ("-F", _vec_scale(f_axis, -1.0), "F")): + distances = [_ray_triangle(h, direction, parsed["vertices"], triangle) for triangle in target_triangles] + hits = _deduplicate_hits([distance for distance in distances if distance is not None], _RAY_TOLERANCE * scale) + nearest = hits[0] if hits else None + radius = _source_radius(scale_info, "", side, radius_axis) + normalized = nearest / radius if nearest is not None and radius else None + row = {"direction": direction, "hit_distances": hits, "nearest_positive_hit": nearest, + "source_radius": radius, "normalized_radius": normalized, "distinct_crossing_count": len(hits), + "nearest_radius_pass": normalized is not None and _RAY_RADIUS_MIN <= normalized <= _RAY_RADIUS_MAX, + "odd_crossing_pass": bool(hits) and len(hits) % 2 == 1} + row["pass"] = row["nearest_radius_pass"] and row["odd_crossing_pass"] + side_rays[direction_name] = row + key = f"{side}:{direction_name}" if side else direction_name + result["rays"][key] = row + result["directional_radial_distances"][key] = nearest + result["centres"][key] = _vec_add(h, _vec_scale(direction, nearest)) if nearest is not None else None + side_pass = side_pass and row["pass"] + + section_origin = _vec_sub(h, _vec_scale(axis, 0.1 * float(scale_info.get("length") or scale))) if axis is not None else h + section_distances = [_ray_triangle(section_origin, direction, parsed["vertices"], triangle) for triangle in target_triangles] + section_hits = _deduplicate_hits([distance for distance in section_distances if distance is not None], _RAY_TOLERANCE * scale) + result["section_above_H"]["rays"][key] = { + "origin": section_origin, "direction": direction, "hit_distances": section_hits, + "nearest_positive_hit": section_hits[0] if section_hits else None, + "centre": _vec_add(section_origin, _vec_scale(direction, section_hits[0])) if section_hits else None, + } + summary_key = f"{side}:summary" if side else "summary" + result["rays"][summary_key] = {"pass": side_pass, "H": h, "axis": axis, "directions": side_rays} + all_sides_pass = all_sides_pass and side_pass + result["pass"] = any_record and all_sides_pass + result["inside_proximal_skin"] = result["pass"] + return result + + +def _profile_input_check(case: Any) -> dict[str, Any]: + keys = ("profile_selector", "profile_select", "selected_profile", "profile_formula", "formula_by_profile") + found = [key for key in keys if _is_mapping(case) and key in case] + return {"pass": not found, "selected_mechanism_keys": found, + "note": "case names may identify profiles; formulas must not be selected by profile"} + + +def _admission_check(case: Any, levels: Any, scale_info: Mapping[str, Any]) -> dict[str, Any]: + """Report constructor admission separately from finite renderability.""" + + failures: list[Any] = [] + if _is_mapping(case) and "admission_failures" in case: + value = case["admission_failures"] + failures.extend(value if isinstance(value, (list, tuple)) else [value]) + if _is_mapping(levels) and "admission_failures" in levels: + value = levels["admission_failures"] + failures.extend(value if isinstance(value, (list, tuple)) else [value]) + if isinstance(levels, (list, tuple)): + for mesh in levels: + if not _is_mapping(mesh): + continue + value = mesh.get("admission_failures") + if value is None and _is_mapping(mesh.get("metadata")): + value = mesh["metadata"].get("admission_failures") + if value is not None: + failures.extend(value if isinstance(value, (list, tuple)) else [value]) + + hip_points = scale_info.get("hip_points", {}) + radii = scale_info.get("radii", {}) + try: + left = hip_points["left"] + right = hip_points["right"] + centres_distance = abs(float(right[0]) - float(left[0])) + left_rx = _source_radius(scale_info, "", "left", "X") + right_rx = _source_radius(scale_info, "", "right", "X") + nominal_clearance = (centres_distance - left_rx - right_rx + if left_rx is not None and right_rx is not None else None) + except Exception: + centres_distance = left_rx = right_rx = nominal_clearance = None + clearance_admitted = nominal_clearance is not None and nominal_clearance > 0.0 + if nominal_clearance is not None and not clearance_admitted: + failures.append({"code": "nominal_medial_clearance", "message": "H centres must be separated beyond rx_left + rx_right"}) + return {"pass": not failures, "failures": failures, "nominal_medial_clearance": nominal_clearance, + "centres_distance": centres_distance, "rx_left": left_rx, "rx_right": right_rx, + "admission_rule": "centres_distance > rx_left + rx_right", + "diagnostic_render_allowed": True} + + +def _level_intersection_and_geometry(level: int, parsed: Mapping[str, Any], scale_info: Mapping[str, Any]) -> dict[str, Any]: + triangles, face_ids = _triangle_inventory(parsed) + intersections = _intersection_report(parsed["vertices"], triangles, face_ids, parsed["face_owners"]) + dimension = _dimension_gates(parsed, scale_info, level) + result = {"intersections": intersections, "scaled_degeneracy": dimension, + "nonadjacent_lower_intersections": {"count": len(intersections["lower_hit_pairs"]), + "pass": intersections["available"] and not intersections["lower_hit_pairs"], + "pairs": intersections["lower_hit_pairs"]}, + "upper_only_intersections": {"count": len(intersections["upper_only_hit_pairs"]), + "status": "inherited-failure" if intersections["upper_only_hit_pairs"] else "pass", + "pairs": intersections["upper_only_hit_pairs"], + "prohibits_full_root_claim": bool(intersections["upper_only_hit_pairs"])}} + return result + + +def check_case(case: Any, levels: Any) -> dict[str, Any]: + """Check L0/L1/L2 and return a JSON-safe diagnostic report, never raise.""" + + report: dict[str, Any] = { + "schema": "pelvis-thigh-transition/checks-v1", + "case": _case_name(case), + "technical": {"pass": False, "full_root_claim": False, "levels": []}, + "regional": {"lower_region": {"pass": False}, "upper_inherited": {"status": "unavailable", "pass": False}}, + "render": {"safe_levels": [], "safe": False}, + "diagnostics": [], + } + try: + level_map = _normalise_levels(levels) + except Exception as exc: + report["diagnostics"].append(_error("invalid_levels", str(exc))) + return _json_safe(report) + if set(level_map) != set(_LEVELS): + report["diagnostics"].append(_error("level_count", "evaluate must return exactly L0, L1, and L2")) + + scale_info = _source_dimensions(case) + admission = _admission_check(case, levels, scale_info) + report["admission"] = admission + report["source"] = {"H_by_side": scale_info.get("H_by_side", {}), "K_by_side": scale_info.get("K_by_side", {}), + "axis_by_side": scale_info.get("actual_axes", {}), "r_y": scale_info.get("r_y", {}), + "joint_frame_hints_used": False} + parsed_levels: dict[int, Mapping[str, Any]] = {} + base_quad_count: int | None = None + base_vertex_count: int | None = None + level_pass = True + for level in _LEVELS: + level_report, parsed = _mesh_structural_checks(level, level_map.get(level), base_quad_count, base_vertex_count) + if level == 0 and parsed is not None: + base_quad_count = len(parsed["quads"]) + base_vertex_count = len(parsed["vertices"]) + if parsed is not None: + parsed_levels[level] = parsed + if level == 0 or base_quad_count is not None: + geometry = _level_intersection_and_geometry(level, parsed, scale_info) + level_report.update(geometry) + level_report["pass"] = level_report["pass"] and geometry["scaled_degeneracy"]["pass"] \ + and geometry["nonadjacent_lower_intersections"]["pass"] + else: + level_report["pass"] = False + level_pass = level_pass and bool(level_report["pass"]) + report["technical"]["levels"].append(level_report) + report["render"]["safe_levels"].append(bool(level_report.get("render_safe"))) + + report["scale"] = { + "S": scale_info.get("scale"), + "inputs": {"lower_pelvis_width": scale_info.get("pelvis_width"), "hip_spacing": scale_info.get("hip_spacing"), + "hip_knee_distances": scale_info.get("hip_knee_distances")}, + "complete": scale_info.get("scale_inputs_complete", False), + "named_per_case": True, + } + report["input_contract"] = {"profile_selection": _profile_input_check(case)} + + if parsed_levels.get(2) is not None: + final = parsed_levels[2] + final_exit = _exit_checks(case, final, scale_info) + folds = _lower_fold_checks(final) + quad_normals = _lower_quad_normal_checks(final) + containment = _containment_checks(case, final, scale_info) + report["technical"]["final_L2"] = {"exit_loops": final_exit, "folds": folds, + "lower_quad_triangle_normals": quad_normals, + "containment": containment} + local_pass = final_exit["pass"] and folds["lower"]["pass"] and quad_normals["pass"] and containment["pass"] + else: + report["technical"]["final_L2"] = {"pass": False, "error": _error("missing_L2", "L2 is required for final checks")} + local_pass = False + + lower_intersection_pass = all( + level.get("nonadjacent_lower_intersections", {}).get("pass", False) + for level in report["technical"]["levels"] + ) and bool(report["technical"]["levels"]) + lower_pass = bool(level_pass and local_pass and lower_intersection_pass + and report["input_contract"]["profile_selection"]["pass"] + and admission["pass"]) + upper_hit_pairs = [ + pair + for level in report["technical"]["levels"] + for pair in level.get("upper_only_intersections", {}).get("pairs", []) + ] + report["regional"]["lower_region"] = { + "pass": lower_pass, + "nonadjacent_intersections": {"pass": lower_intersection_pass}, + "full_local_gates": local_pass, + } + report["regional"]["upper_inherited"] = { + "status": "inherited-failure" if upper_hit_pairs else "not-reappraised", + "intersection_pairs": upper_hit_pairs, + "computed_failures": upper_hit_pairs, + "prohibits_full_root_claim": True, + "does_not_change_lower_success": True, + } + report["technical"]["pass"] = lower_pass + report["technical"]["lower_region_pass"] = lower_pass + # This experiment does not re-appraise the complete upper root. Even a + # clean inherited diagnostic therefore cannot become a whole-root claim. + report["technical"]["full_root_claim"] = False + report["render"]["safe"] = bool(report["render"]["safe_levels"]) and all(report["render"]["safe_levels"]) + if not admission["pass"]: + report["diagnostics"].append(_error("admission_failure", "constructor/input admission failed; finite diagnostic rendering remains allowed", + failures=admission["failures"])) + if not report["render"]["safe"]: + report["diagnostics"].append(_error("render_unsafe", "one or more levels are not finite, indexed, and non-degenerate")) + if upper_hit_pairs: + report["diagnostics"].append(_error("upper_inherited_intersection", "upper-only intersection blocks a full-root claim", pairs=upper_hit_pairs)) + return _json_safe(report) + + +def _centroids_for_exits(case: Any, levels: Any) -> dict[str, tuple[float, float, float]]: + level_map = _normalise_levels(levels) + _, parsed = _mesh_structural_checks(2, level_map.get(2), None) + if parsed is None: + return {} + names = _exit_loop_names(case, parsed) + return {name: _loop_geometry(parsed["vertices"], parsed["loops"][name])[0] for name in names} + + +def _declared_response(case: Any) -> tuple[str | None, Mapping[str, Any]]: + if not _is_mapping(case): + return None, {} + value = next((case[key] for key in ("declared_response", "expected_response", "perturbation") if key in case), None) + if value is None and _is_mapping(case.get("provenance")): + value = case["provenance"].get("expected_change") + if isinstance(value, str): + return value, {} + if _is_mapping(value): + kind = _lookup(value, "kind", "type", "name", "response", "direction") + return str(kind) if kind is not None else None, value + return None, {} + + +def _response_delta(response: Mapping[str, Any], loop_name: str, side: str | None) -> tuple[float, float, float] | None: + value = _side_value(_lookup(response, "delta", "offset", "translation", "expected_delta"), loop_name, side) + try: + return _vector(value, "declared response delta") + except Exception: + return None + + +def _response_kind(kind: str) -> str: + return { + "neutral_pelvis_width_plus_10pct": "pelvis_width", + "neutral_left_spacing_minus_005": "centre_offset", + "neutral_left_direction_tilt_5deg": "direction_tilt", + "neutral_left_front_offset_plus_005": "centre_offset", + "neutral_left_asymmetric_xz_and_radius": "centre_offset", + "neutral_invalid_close_thick": "negative", + }.get(kind, "unknown") + + +def _response_source_axis(case: Any, side: str | None) -> tuple[float, float, float] | None: + info = _source_dimensions(case) + actual = info.get("actual_axes", {}) + if side in actual: + return actual[side] + return info.get("axis") + + +def compare_perturbation(base_case: Any, base_levels: Any, case: Any, levels: Any) -> dict[str, Any]: + """Check only the response declared by a pre-declared perturbation.""" + + result: dict[str, Any] = {"schema": "pelvis-thigh-transition/perturbation-checks-v1", "pass": False, + "declared": {}, "checks": {}, "diagnostics": []} + try: + declared_kind, response = _declared_response(case) + case_kind = _response_kind(_case_name(case)) + result["declared"] = {"case_id": _case_name(case), "kind": declared_kind, "test_kind": case_kind} + if case_kind == "unknown": + result["diagnostics"].append(_error("unknown_perturbation_id", "only the six registered perturbation IDs are accepted")) + return _json_safe(result) + if declared_kind is None: + result["diagnostics"].append(_error("missing_declared_response", "perturbation response must be explicitly declared")) + return _json_safe(result) + base_info = _source_dimensions(base_case) + new_info = _source_dimensions(case) + scale = new_info.get("scale") or base_info.get("scale") + result["scale"] = scale + if not _finite(scale) or float(scale) <= 0.0: + result["diagnostics"].append(_error("missing_scale", "perturbation comparison requires case scale S")) + return _json_safe(result) + scale = float(scale) + base_map = _normalise_levels(base_levels) + new_map = _normalise_levels(levels) + _, base_parsed = _mesh_structural_checks(2, base_map.get(2), None) + _, new_parsed = _mesh_structural_checks(2, new_map.get(2), None) + if base_parsed is None or new_parsed is None: + result["diagnostics"].append(_error("missing_L2", "perturbation comparison requires both actual L2 meshes")) + return _json_safe(result) + base_centres = {name: _loop_geometry(base_parsed["vertices"], base_parsed["loops"][name])[0] + for name in _exit_loop_names(base_case, base_parsed)} + new_centres = {name: _loop_geometry(new_parsed["vertices"], new_parsed["loops"][name])[0] + for name in _exit_loop_names(case, new_parsed)} + names = sorted(set(base_centres).intersection(new_centres)) + response_kind = case_kind + centroid_checks: list[dict[str, Any]] = [] + if response_kind in {"centre_offset", "pelvis_width"}: + for name in names: + side = "left" if "left" in name.lower() else "right" if "right" in name.lower() else None + expected_delta = _response_delta(response, name, side) + if expected_delta is None and response_kind == "centre_offset": + base_h = base_info.get("H_by_side", {}).get(side) + new_h = new_info.get("H_by_side", {}).get(side) + if base_h is not None and new_h is not None: + expected_delta = _vec_sub(new_h, base_h) + if expected_delta is None and response_kind == "pelvis_width": + expected_delta = (0.0, 0.0, 0.0) + observed_delta = _vec_sub(new_centres[name], base_centres[name]) + error = _norm(_vec_sub(observed_delta, expected_delta)) if expected_delta is not None else None + centroid_checks.append({"loop": name, "observed_delta": observed_delta, "expected_delta": expected_delta, + "error": error, "pass": error is not None and error <= _POSITION_TOLERANCE * scale}) + result["checks"]["exit_centroid_response"] = {"checks": centroid_checks, "applicable": response_kind in {"centre_offset", "pelvis_width"}, + "pass": True if response_kind not in {"centre_offset", "pelvis_width"} + else bool(centroid_checks) and all(row["pass"] for row in centroid_checks)} + + if _case_name(case) == "neutral_left_asymmetric_xz_and_radius": + span_rows = [] + source_ratio = (case["components"]["hips.left.r_x"] + / base_case["components"]["hips.left.r_x"]) + for name in names: + if "left" not in name.lower(): + continue + half_spans = [] + for parsed, centres in ((base_parsed, base_centres), (new_parsed, new_centres)): + x_axis = _unit(_vector(parsed["frames"]["left"]["X"], "L2 frame X"), "L2 frame X") + projections = [_dot(_vec_sub(parsed["vertices"][index], centres[name]), x_axis) + for index in parsed["loops"][name]] + half_spans.append(0.5 * (max(projections) - min(projections))) + old_span, new_span = half_spans + expected_span = old_span * source_ratio + error = abs(new_span - expected_span) + span_rows.append({"loop": name, "base_half_span": old_span, + "actual_half_span": new_span, "expected_half_span": expected_span, + "source_radius_ratio": source_ratio, + "actual_span_ratio": new_span / old_span if old_span > 0.0 else None, + "error": error, "tolerance": _POSITION_TOLERANCE * scale, + "pass": old_span > 0.0 and source_ratio > 1.0 and new_span > old_span + and error <= _POSITION_TOLERANCE * scale}) + result["checks"]["asymmetric_lateral_span_response"] = { + "checks": span_rows, "pass": bool(span_rows) and all(row["pass"] for row in span_rows)} + + actual_axis_checks: list[dict[str, Any]] = [] + if response_kind == "direction_tilt": + for name in names: + side = "left" if "left" in name.lower() else "right" if "right" in name.lower() else None + expected_axis = _response_source_axis(case, side) + observed_axis = _vec_scale(_loop_geometry(new_parsed["vertices"], new_parsed["loops"][name])[1], -1.0) + angle = _angle_radians(observed_axis, expected_axis) if observed_axis is not None and expected_axis is not None else None + actual_axis_checks.append({"loop": name, "observed_axis": observed_axis, "actual_new_H_to_K": expected_axis, + "angle_error_radians": angle, + "pass": angle is not None and angle <= _EXIT_DIRECTION_TOLERANCE}) + result["checks"]["direction_tilt_response"] = {"checks": actual_axis_checks, + "pass": bool(actual_axis_checks) and all(row["pass"] for row in actual_axis_checks)} + + if response_kind == "pelvis_width": + base_exit_pass = result["checks"]["exit_centroid_response"]["pass"] + base_containment = _containment_checks(base_case, base_parsed, base_info) + new_containment = _containment_checks(case, new_parsed, new_info) + base_section = base_containment.get("section_above_H", {}).get("rays", {}) + new_section = new_containment.get("section_above_H", {}).get("rays", {}) + extent_rows = [] + for side_name in sorted(set(base_section).intersection(new_section)): + old = base_section.get(side_name, {}).get("nearest_positive_hit") + new = new_section.get(side_name, {}).get("nearest_positive_hit") + extent_rows.append({"direction": side_name, "base": old, "perturbed": new, + "increase": new - old if _finite(new) and _finite(old) else None}) + outer_rows = [row for row in extent_rows if row["direction"].endswith(":+X") or row["direction"].endswith(":-X")] + extent_pass = any(row["increase"] is not None and row["increase"] >= _PELVIS_WIDTH_RESPONSE_FLOOR * scale + for row in outer_rows) + result["checks"]["pelvis_width_response"] = {"exits_unchanged": base_exit_pass, "ray_extent": extent_rows, + "at_least_one_side_increases": extent_pass, + "pass": base_exit_pass and extent_pass} + + coordinates_differ = False + try: + base_l2 = _normalise_levels(base_levels)[2] + new_l2 = _normalise_levels(levels)[2] + base_vertices = _as_sequence(base_l2.get("vertices"), "base L2 vertices") if _is_mapping(base_l2) else [] + new_vertices = _as_sequence(new_l2.get("vertices"), "new L2 vertices") if _is_mapping(new_l2) else [] + coordinates_differ = base_vertices != new_vertices + except Exception: + coordinates_differ = False + result["checks"]["exported_coordinate_arrays_differ"] = {"pass": coordinates_differ} + + negative = response_kind == "negative" + if negative: + points = new_info.get("hip_points", {}) + clearance = _pair_distance(points, ("left",), ("right",)) + left_radius = _source_radius(new_info, "left_exit", "left", "X") + right_radius = _source_radius(new_info, "right_exit", "right", "X") + admission = clearance is not None and left_radius is not None and right_radius is not None and clearance > left_radius + right_radius + rejected = clearance is not None and left_radius is not None and right_radius is not None and clearance <= left_radius + right_radius + result["checks"]["negative_medial_clearance_admission"] = {"centres_distance": clearance, + "rx_left": left_radius, "rx_right": right_radius, + "admission_rule": "centres_distance > rx_left + rx_right", + "constructor_admitted": admission, + "expected_negative_success": rejected, + "anatomy_pass": False, + "pass": rejected} + + applicable = [value.get("pass") for value in result["checks"].values()] + result["pass"] = bool(applicable) and all(applicable) + if negative and result["checks"].get("negative_medial_clearance_admission", {}).get("pass"): + result["status"] = "expected-negative-success; not an anatomy pass" + return _json_safe(result) + except Exception as exc: + result["diagnostics"].append(_error("perturbation_checker_failure", str(exc))) + return _json_safe(result) + + +__all__ = ["check_case", "compare_perturbation"] diff --git a/experiments/pelvis-thigh-transition/construction.py b/experiments/pelvis-thigh-transition/construction.py new file mode 100644 index 0000000..fea7a36 --- /dev/null +++ b/experiments/pelvis-thigh-transition/construction.py @@ -0,0 +1,981 @@ +"""Local owned-root pelvis/thigh transition construction. + +This module is deliberately a small experiment-local seam. It consumes the +predecessor's identity-free numeric component names and upper-context formula +authority, but owns the transition topology and subdivision implementation. +The returned meshes are plain mappings so the experiment does not inherit the +predecessor's frozen mesh class, profile admission, or validation gates. + +base_stencils uses a sparse, sorted tuple representation: +((base_vertex_index, coefficient), ...). Level zero is identity and each +later level contains the actual linear Catmull--Clark coefficients back to +those level-zero vertices. + +``control_owners`` is only a dominant-owner display label for each evaluated +vertex. The authoritative ownership and provenance are the base ownership +labels in metadata and the complete propagated ``base_stencils`` weights. +""" +from __future__ import annotations + +from collections import defaultdict +from collections.abc import Mapping +import importlib.util +import math +from pathlib import Path +import sys +from typing import Any + + +ROOT = Path(__file__).resolve().parents[2] +_SOURCE_DIR = ROOT / "experiments" / "owned-root-assembly-successor" +_SOURCE_PATH = _SOURCE_DIR / "owned_root_surface.py" +_MESH_CORRECTNESS_PATH = _SOURCE_DIR / "mesh_correctness.py" + + +def _load_module(name: str, path: Path) -> Any: + spec = importlib.util.spec_from_file_location(name, path) + if spec is None or spec.loader is None: + raise ImportError(f"unable to load experiment source module: {path}") + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + return module + + +def _load_source() -> Any: + # The predecessor uses a top-level mesh_correctness import when loaded + # from its own directory. Bind exactly that read-only dependency only + # while loading the source module, then restore any caller-owned binding. + marker = object() + previous = sys.modules.get("mesh_correctness", marker) + try: + dependency = _load_module("_ck_transition_mesh_correctness", + _MESH_CORRECTNESS_PATH) + sys.modules["mesh_correctness"] = dependency + return _load_module("_ck_transition_owned_root_surface", _SOURCE_PATH) + finally: + if previous is marker: + sys.modules.pop("mesh_correctness", None) + else: + sys.modules["mesh_correctness"] = previous + + +_SOURCE = _load_source() + +# This is the only component universe admitted by this local package. In +# particular, attachments are semantic additions, not new carrier fields. +GEOMETRY_COMPONENT_IDS = tuple(_SOURCE.GEOMETRY_COMPONENT_IDS) + +_SIDES = ("left", "right") +_SIDE_SIGN = {"left": -1.0, "right": 1.0} +_SIDE_DOMAIN = { + "left": "domain.left_hip", + "right": "domain.right_hip", +} +_SIDE_PORT = { + "left": "port.left_thigh", + "right": "port.right_thigh", +} +_SIDE_JUNCTION = { + "left": "junction.pelvis__left_hip", + "right": "junction.pelvis__right_hip", +} +_DOWN = (0.0, -1.0, 0.0) +_GLOBAL_X = (1.0, 0.0, 0.0) +_STENCIL_TOLERANCE = 1.0e-12 + + +def _fail(message: str) -> None: + raise ValueError(message) + + +def _finite_float(value: Any, where: str) -> float: + if type(value) is not float or not math.isfinite(value): + _fail(f"{where} must be a finite binary64 float") + return value + + +def _vector(value: Any, where: str) -> tuple[float, float, float]: + if type(value) not in (list, tuple) or len(value) != 3: + _fail(f"{where} must be a three-component vector") + return tuple(_finite_float(item, f"{where}[{index}]") + for index, item in enumerate(value)) # type: ignore[return-value] + + +def _positive(value: float, where: str) -> float: + if not math.isfinite(value) or not value > 0.0: + _fail(f"{where} must be positive and finite") + return value + + +def _validate_inputs( + components: dict[str, float], + attachments: dict[str, dict[str, list[float]]], +) -> tuple[Any, dict[str, dict[str, tuple[float, float, float]]]]: + if type(components) is not dict: + _fail("components must be a dict") + if set(components) != set(GEOMETRY_COMPONENT_IDS): + _fail("components must use exactly GEOMETRY_COMPONENT_IDS") + for component in GEOMETRY_COMPONENT_IDS: + _finite_float(components[component], f"components[{component!r}]") + + if type(attachments) is not dict or set(attachments) != set(_SIDES): + _fail("attachments must contain exactly left and right") + checked: dict[str, dict[str, tuple[float, float, float]]] = {} + for side in _SIDES: + row = attachments[side] + if type(row) is not dict or set(row) != {"centre", "knee"}: + _fail(f"attachments[{side!r}] must contain exactly centre and knee") + checked[side] = { + field: _vector(row[field], f"attachments[{side!r}][{field!r}]") + for field in ("centre", "knee") + } + + carrier = _SOURCE.GeometryComponents( + tuple(components[component] for component in GEOMETRY_COMPONENT_IDS) + ) + for side in _SIDES: + expected = tuple( + _component(carrier, f"hips.{side}.P_s.{axis}") + for axis in "xyz" + ) + if checked[side]["centre"] != expected: + _fail(f"attachments.{side}.centre must equal hips.{side}.P_s") + return carrier, checked + + +def _dot(left: tuple[float, float, float], + right: tuple[float, float, float]) -> float: + return left[0] * right[0] + left[1] * right[1] + left[2] * right[2] + + +def _sub(left: tuple[float, float, float], + right: tuple[float, float, float]) -> tuple[float, float, float]: + return tuple(left[index] - right[index] for index in range(3)) # type: ignore[return-value] + + +def _scale(value: tuple[float, float, float], + factor: float) -> tuple[float, float, float]: + return tuple(factor * item for item in value) # type: ignore[return-value] + + +def _add(*values: tuple[float, float, float]) -> tuple[float, float, float]: + return tuple(sum(value[index] for value in values) for index in range(3)) # type: ignore[return-value] + + +def _cross(left: tuple[float, float, float], + right: tuple[float, float, float]) -> tuple[float, float, float]: + return ( + left[1] * right[2] - left[2] * right[1], + left[2] * right[0] - left[0] * right[2], + left[0] * right[1] - left[1] * right[0], + ) + + +def _normalise(value: tuple[float, float, float], + where: str) -> tuple[float, float, float]: + length = math.sqrt(_dot(value, value)) + if not math.isfinite(length) or not length > 0.0: + _fail(f"{where} must have positive finite length") + return _scale(value, 1.0 / length) + + +def _component(components: Any, name: str) -> float: + return components.values[GEOMETRY_COMPONENT_IDS.index(name)] + + +def _station(components: Any, name: str) -> dict[str, Any]: + prefix = f"stations.{name}" + return { + "C": tuple(_component(components, f"{prefix}.C.{axis}") + for axis in "xyz"), + "rL": _component(components, f"{prefix}.rL"), + "rA": _component(components, f"{prefix}.rA"), + "rP": _component(components, f"{prefix}.rP"), + } + + +def _hip_radius(components: Any, side: str, field: str) -> float: + return _component(components, f"hips.{side}.{field}") + + +def _frame_and_dimensions( + components: Any, + attachments: dict[str, dict[str, tuple[float, float, float]]], +) -> dict[str, dict[str, Any]]: + lower = _station(components, "lower_pelvis") + for field in ("rL", "rA", "rP"): + _positive(lower[field], f"stations.lower_pelvis.{field}") + + result: dict[str, dict[str, Any]] = {} + for side in _SIDES: + H = attachments[side]["centre"] + knee = attachments[side]["knee"] + delta = _sub(knee, H) + length = math.sqrt(_dot(delta, delta)) + if not math.isfinite(length): + _fail(f"attachments.{side} knee distance must be finite") + _positive(length, f"attachments.{side} knee distance") + d = _scale(delta, 1.0 / length) + if not _dot(d, _DOWN) > 0.9: + _fail(f"attachments.{side} thigh direction must be within the down-axis gate") + + projected_x = _sub(_GLOBAL_X, _scale(d, _dot(_GLOBAL_X, d))) + X = _normalise(projected_x, f"attachments.{side} frame X") + U = _scale(d, -1.0) + F = _cross(X, U) + + rx = _positive(_hip_radius(components, side, "r_x"), + f"hips.{side}.r_x") + _positive(_hip_radius(components, side, "r_y"), + f"hips.{side}.r_y") + rz = _positive(_hip_radius(components, side, "r_z"), + f"hips.{side}.r_z") + D = lower["C"][1] - H[1] + _positive(D, f"{side} pelvis rise D") + + outward_radius = ( + lower["rL"] - abs(H[0] - lower["C"][0]) + rx + ) / 2.0 + inward_radius = 1.10 * rx + relative_z = lower["C"][2] - H[2] + front_radius = (lower["rA"] + relative_z + rz) / 2.0 + back_radius = (lower["rP"] - relative_z + rz) / 2.0 + for name, value in ( + ("outward lateral radius", outward_radius), + ("inward lateral radius", inward_radius), + ("front depth radius", front_radius), + ("back depth radius", back_radius), + ): + _positive(value, f"{side} {name}") + + E = _add(H, _scale(d, 0.45 * length)) + ring_b_centre = _add(H, _scale(d, 0.30 * length)) + result[side] = { + "H": H, + "knee": knee, + "length": length, + "d": d, + "X": X, + "U": U, + "F": F, + "exit": E, + "ring_b_centre": ring_b_centre, + "rx": rx, + "ry": _hip_radius(components, side, "r_y"), + "rz": rz, + "D": D, + "outward_sign": _SIDE_SIGN[side], + "outward_radius": outward_radius, + "inward_radius": inward_radius, + "front_radius": front_radius, + "back_radius": back_radius, + } + return result + + +def _perimeter(control_id: str, side: str) -> tuple[float, float]: + i, _j, k = _SOURCE.COORDINATE_BY_CONTROL[control_id] + u = float(i) - (1.0 if side == "left" else 4.0) + q = float(k - 1) + length = math.sqrt(u * u + q * q) + if not length > 0.0: + _fail(f"{control_id} is not a perimeter control") + return u / length, q / length + + +def _socket_point(info: dict[str, Any], + a: float, + b: float) -> tuple[float, float, float]: + lateral = ( + info["outward_radius"] + if info["outward_sign"] * a > 0.0 + else info["inward_radius"] + ) + depth = info["front_radius"] if b >= 0.0 else info["back_radius"] + # r_y is proximal vertical flesh extent and is an explicit consumer. + w = 0.5 * (1.0 + info["outward_sign"] * a) + y = ( + info["H"][1] + w * (0.50 * info["D"] + 0.25 * info["ry"]) + - (1.0 - w) * 0.10 * info["length"] + ) + return _add( + (info["H"][0], y, info["H"][2]), + _scale(info["X"], a * lateral), + _scale(info["F"], b * depth), + ) + + +def _port_point(info: dict[str, Any], + a: float, + b: float, + centre: tuple[float, float, float]) -> tuple[float, float, float]: + return _add( + centre, + _scale(info["X"], a * info["rx"]), + _scale(info["F"], b * info["rz"]), + ) + + +def _transition_rings( + frames: dict[str, dict[str, Any]], +) -> dict[str, dict[str, list[tuple[float, float, float]]]]: + result: dict[str, dict[str, list[tuple[float, float, float]]]] = {} + for side in _SIDES: + port_controls = tuple(_SOURCE.PORT_INFO[_SIDE_PORT[side]][2]) + junction_controls = tuple(_SOURCE.JUNCTION_TRACES[_SIDE_JUNCTION[side]]) + if len(port_controls) != len(junction_controls): + _fail(f"{side} transition loops have different lengths") + socket: list[tuple[float, float, float]] = [] + port: list[tuple[float, float, float]] = [] + ring_a: list[tuple[float, float, float]] = [] + ring_b: list[tuple[float, float, float]] = [] + for port_control, junction_control in zip(port_controls, junction_controls): + a, b = _perimeter(port_control, side) + if _perimeter(junction_control, side) != (a, b): + _fail(f"{side} transition loops are not perimeter aligned") + socket_point = _socket_point(frames[side], a, b) + port_point = _port_point(frames[side], a, b, frames[side]["exit"]) + ring_b_point = _port_point( + frames[side], a, b, frames[side]["ring_b_centre"] + ) + socket.append(socket_point) + port.append(port_point) + ring_b.append(ring_b_point) + ring_a.append(_scale(_add(socket_point, ring_b_point), 0.5)) + result[side] = { + "socket": socket, + "port": port, + "ringA": ring_a, + "ringB": ring_b, + } + return result + + +def _pelvic_abdominal_point( + components: Any, i: float, k: float, +) -> tuple[float, float, float]: + """Refinement 1: blend the j=1 station row onto a normalized ellipse.""" + u = (i - 2.5) / 2.5 + q = k - 1.0 + t = u * u + denom = math.sqrt(u * u + q * q) + if not denom > 0.0: + _fail("j=1 control must have a nonzero perimeter direction") + upper = _station(components, "upper_pelvis") + abdomen = _station(components, "lower_abdomen") + interior = ( + abdomen["C"][0], + 0.5 * (upper["C"][1] + abdomen["C"][1]), + abdomen["C"][2], + ) + centre = tuple( + (1.0 - t) * interior[axis] + t * upper["C"][axis] + for axis in range(3) + ) + radii = { + field: (1.0 - t) * abdomen[field] + t * upper[field] + for field in ("rL", "rA", "rP") + } + return ( + centre[0] + u / denom * radii["rL"], + centre[1], + centre[2] + q / denom * radii["rA" if q >= 0.0 else "rP"], + ) + + +def _original_vertices( + carrier: Any, + transitions: dict[str, dict[str, list[tuple[float, float, float]]]], +) -> list[tuple[float, float, float]]: + control_index = { + control_id: index for index, control_id in enumerate(_SOURCE.CONTROL_IDS) + } + port_positions = { + side: { + control_id: index + for index, control_id in enumerate( + _SOURCE.PORT_INFO[_SIDE_PORT[side]][2] + ) + } + for side in _SIDES + } + junction_positions = { + side: { + control_id: index + for index, control_id in enumerate( + _SOURCE.JUNCTION_TRACES[_SIDE_JUNCTION[side]] + ) + } + for side in _SIDES + } + vertices: list[tuple[float, float, float]] = [] + for control_id in _SOURCE.CONTROL_IDS: + i, j, k = _SOURCE.COORDINATE_BY_CONTROL[control_id] + if j == -1: + side = "left" if i <= 2 else "right" + position = port_positions[side].get(control_id) + if position is None: + _fail(f"{control_id} is not in its declared thigh port") + point = transitions[side]["port"][position] + elif j == 0: + side = "left" if i <= 2 else "right" + position = junction_positions[side].get(control_id) + if position is None: + _fail(f"{control_id} is not in its declared hip junction") + point = transitions[side]["socket"][position] + elif j == 1: + point = _pelvic_abdominal_point(carrier, i, k) + else: + # This is the settled upper-context source formula. No + # predecessor builder or validator is called here. + _formula, _dependencies, point, _parameters = ( + _SOURCE._formula_for_control(carrier, control_id) + ) + point = tuple(float(value) for value in point) + if len(point) != 3 or any(not math.isfinite(value) for value in point): + _fail(f"{control_id} produced a non-finite point") + vertices.append(tuple(point)) + if len(vertices) != len(control_index): + _fail("source control catalog changed while constructing vertices") + return vertices + + +def _edge_key(left: int, right: int) -> tuple[int, int]: + return (left, right) if left < right else (right, left) + + +def _transition_faces( + base_vertices: list[tuple[float, float, float]], + transitions: dict[str, dict[str, list[tuple[float, float, float]]]], +) -> tuple[Any, ...]: + control_index = { + control_id: index for index, control_id in enumerate(_SOURCE.CONTROL_IDS) + } + ring_indices: dict[str, dict[str, tuple[int, ...]]] = {} + vertices = list(base_vertices) + for side in _SIDES: + ring_a = tuple(range( + len(vertices), len(vertices) + len(transitions[side]["ringA"]) + )) + vertices.extend(transitions[side]["ringA"]) + ring_b = tuple(range( + len(vertices), len(vertices) + len(transitions[side]["ringB"]) + )) + vertices.extend(transitions[side]["ringB"]) + ring_indices[side] = {"ringA": ring_a, "ringB": ring_b} + + port_indices = { + side: { + control_id: control_index[control_id] + for control_id in _SOURCE.PORT_INFO[_SIDE_PORT[side]][2] + } + for side in _SIDES + } + junction_indices = { + side: { + control_id: control_index[control_id] + for control_id in _SOURCE.JUNCTION_TRACES[_SIDE_JUNCTION[side]] + } + for side in _SIDES + } + port_positions = { + side: { + vertex_index: position + for position, control_id in enumerate( + _SOURCE.PORT_INFO[_SIDE_PORT[side]][2] + ) + for vertex_index in (control_index[control_id],) + } + for side in _SIDES + } + quads: list[tuple[int, int, int, int]] = [] + owners: list[str] = [] + for _face_id, owner, controls in _SOURCE.FACE_RECORDS: + face = tuple(control_index[control_id] for control_id in controls) + side = next((candidate for candidate in _SIDES + if owner == _SIDE_DOMAIN[candidate]), None) + if side is None: + quads.append(face) # type: ignore[arg-type] + owners.append(owner) + continue + + port_set = set(port_indices[side].values()) + junction_set = set(junction_indices[side].values()) + starts = [ + slot for slot in range(4) + if face[slot] in port_set and face[(slot + 1) % 4] in port_set + ] + if len(starts) != 1: + _fail("hip face does not expose one directed port edge") + start = starts[0] + # Rotation keeps the original directed cycle; no global inversion is + # applied. Its shape is p0,p1,j1,j0. + p0, p1, j1, j0 = tuple( + face[(start + offset) % 4] for offset in range(4) + ) + if ( + p0 not in port_set or p1 not in port_set + or j0 not in junction_set or j1 not in junction_set + ): + _fail("hip face is not a port-to-junction quad") + a0 = ring_indices[side]["ringA"][port_positions[side][p0]] + a1 = ring_indices[side]["ringA"][port_positions[side][p1]] + b0 = ring_indices[side]["ringB"][port_positions[side][p0]] + b1 = ring_indices[side]["ringB"][port_positions[side][p1]] + quads.extend(((j1, j0, a0, a1), + (a1, a0, b0, b1), + (b1, b0, p0, p1))) + owners.extend((owner, owner, owner)) + + loops = { + port: tuple(control_index[control_id] for control_id in info[2]) + for port, info in _SOURCE.PORT_INFO.items() + } + transition_index_metadata = { + side: { + "socket": tuple(control_index[control_id] for control_id in + _SOURCE.JUNCTION_TRACES[_SIDE_JUNCTION[side]]), + "ringA": ring_indices[side]["ringA"], + "ringB": ring_indices[side]["ringB"], + "exit": tuple(control_index[control_id] for control_id in + _SOURCE.PORT_INFO[_SIDE_PORT[side]][2]), + } + for side in _SIDES + } + return vertices, quads, owners, transition_index_metadata, loops + + +def _metadata( + frames: dict[str, dict[str, Any]], + transition_indices: dict[str, dict[str, tuple[int, ...]]], + admission_failures: tuple[dict[str, Any], ...], + base_control_owners: tuple[str, ...], +) -> dict[str, Any]: + exported_frames = {} + for side in _SIDES: + info = frames[side] + exported_frames[side] = { + key: info[key] + for key in ("H", "knee", "length", "d", "X", "U", "F", "exit") + } + return { + "level": 0, + "admission_status": "rejected" if admission_failures else "accepted", + "admission_failures": admission_failures, + "base_control_owners": base_control_owners, + "dominant_owner_label": ( + "display representative only; authoritative ownership is " + "base_control_owners plus full base_stencils" + ), + "frames": exported_frames, + "transition_indices": transition_indices, + "exit_expected": {side: frames[side]["exit"] for side in _SIDES}, + } + + +def _identity_stencils(count: int) -> tuple[tuple[tuple[int, float], ...], ...]: + return tuple(((index, 1.0),) for index in range(count)) + + +def _incidence( + quads: Any, + _vertex_count: int, +) -> tuple[dict[tuple[int, int], list[tuple[int, int, int]]], + set[tuple[int, int]]]: + uses: dict[tuple[int, int], list[tuple[int, int, int]]] = defaultdict(list) + for face_index, face in enumerate(quads): + for slot, left in enumerate(face): + right = face[(slot + 1) % 4] + uses[_edge_key(left, right)].append((face_index, left, right)) + boundary = {edge for edge, rows in uses.items() if len(rows) == 1} + return dict(uses), boundary + + +def _validate_mesh(mesh: Mapping[str, Any]) -> tuple[Any, ...]: + required = {"vertices", "quads", "face_owners", "control_owners", + "loops", "base_stencils", "frames", "metadata"} + if not isinstance(mesh, Mapping) or not required.issubset(mesh): + _fail("mesh must provide the generic transition fields") + raw_vertices = mesh["vertices"] + raw_quads = mesh["quads"] + raw_face_owners = mesh["face_owners"] + raw_control_owners = mesh["control_owners"] + raw_loops = mesh["loops"] + raw_stencils = mesh["base_stencils"] + raw_frames = mesh["frames"] + metadata = mesh["metadata"] + if type(metadata) is not dict: + _fail("metadata must be a dict") + status = metadata.get("admission_status") + failures = metadata.get("admission_failures") + base_control_owners = metadata.get("base_control_owners") + dominant_owner_label = metadata.get("dominant_owner_label") + if status not in {"accepted", "rejected"}: + _fail("metadata must declare admission_status") + if type(failures) not in (list, tuple): + _fail("metadata must retain admission_failures") + if status == "accepted" and failures: + _fail("accepted metadata cannot retain admission failures") + if status == "rejected" and not failures: + _fail("rejected metadata must retain admission failures") + if type(base_control_owners) not in (list, tuple) or not base_control_owners: + _fail("metadata must retain base control owners") + if any(type(owner) is not str for owner in base_control_owners): + _fail("metadata base control owners must contain strings") + if type(dominant_owner_label) is not str or not dominant_owner_label: + _fail("metadata must explain the dominant owner label") + if type(raw_frames) is not dict or set(raw_frames) != set(_SIDES): + _fail("frames must contain exactly left and right") + for side in _SIDES: + frame = raw_frames[side] + if type(frame) is not dict: + _fail(f"frames.{side} must be a mapping") + for key in ("H", "d", "X", "U", "F", "exit"): + _vector(frame.get(key), f"frames.{side}.{key}") + _finite_float(frame.get("length"), f"frames.{side}.length") + if type(raw_vertices) not in (list, tuple) or not raw_vertices: + _fail("mesh vertices must be a non-empty sequence") + vertices = tuple(_vector(point, f"vertices[{index}]") + for index, point in enumerate(raw_vertices)) + if type(raw_quads) not in (list, tuple) or not raw_quads: + _fail("mesh quads must be a non-empty sequence") + quads: list[tuple[int, int, int, int]] = [] + for face_index, face in enumerate(raw_quads): + if type(face) not in (list, tuple) or len(face) != 4: + _fail(f"quads[{face_index}] must have four indices") + if any(type(index) is not int for index in face): + _fail(f"quads[{face_index}] indices must be integers") + checked = tuple(face) + if len(set(checked)) != 4 or any(index < 0 or index >= len(vertices) + for index in checked): + _fail(f"quads[{face_index}] has invalid indices") + quads.append(checked) # type: ignore[arg-type] + if type(raw_face_owners) not in (list, tuple): + _fail("face_owners must be a sequence") + face_owners = tuple(raw_face_owners) + if len(face_owners) != len(quads) or any(type(owner) is not str + for owner in face_owners): + _fail("face_owners must have one string owner per quad") + if type(raw_control_owners) not in (list, tuple) or not raw_control_owners: + _fail("control_owners must be a non-empty sequence") + control_owners = tuple(raw_control_owners) + if len(control_owners) != len(vertices) or any( + type(owner) is not str for owner in control_owners + ): + _fail("control_owners must contain one string owner per vertex") + if type(raw_stencils) not in (list, tuple) or len(raw_stencils) != len(vertices): + _fail("base_stencils must match the vertex count") + stencils: list[tuple[tuple[int, float], ...]] = [] + for vertex_index, stencil in enumerate(raw_stencils): + if type(stencil) not in (list, tuple) or not stencil: + _fail(f"base_stencils[{vertex_index}] must be non-empty") + checked_stencil: list[tuple[int, float]] = [] + previous = -1 + for item in stencil: + if type(item) not in (list, tuple) or len(item) != 2: + _fail(f"base_stencils[{vertex_index}] has an invalid term") + base_index, coefficient = item + if type(base_index) is not int or base_index <= previous: + _fail(f"base_stencils[{vertex_index}] must be sorted and unique") + if base_index < 0 or base_index >= len(base_control_owners): + _fail(f"base_stencils[{vertex_index}] references an unknown base vertex") + coefficient = _finite_float(coefficient, "base stencil coefficient") + if coefficient == 0.0: + _fail(f"base_stencils[{vertex_index}] contains a zero coefficient") + checked_stencil.append((base_index, coefficient)) + previous = base_index + stencil_sum = sum(coefficient for _base_index, coefficient in checked_stencil) + if abs(stencil_sum - 1.0) > _STENCIL_TOLERANCE: + _fail(f"base_stencils[{vertex_index}] must sum to one") + if any(coefficient < -_STENCIL_TOLERANCE + for _base_index, coefficient in checked_stencil): + _fail(f"base_stencils[{vertex_index}] must be nonnegative") + stencils.append(tuple(checked_stencil)) + + if type(raw_loops) is not dict or not raw_loops: + _fail("loops must be a non-empty dict") + loops: dict[str, tuple[int, ...]] = {} + for name, loop in raw_loops.items(): + if type(name) is not str or type(loop) not in (list, tuple) or len(loop) < 3: + _fail("each loop must be a named sequence of at least three vertices") + if any(type(index) is not int or index < 0 or index >= len(vertices) + for index in loop) or len(set(loop)) != len(loop): + _fail(f"loop {name!r} has invalid vertices") + loops[name] = tuple(loop) + + uses, boundary = _incidence(quads, len(vertices)) + if any(len(rows) not in (1, 2) for rows in uses.values()): + _fail("mesh has a non-manifold edge") + for rows in uses.values(): + if len(rows) == 2 and rows[0][1:] == rows[1][1:]: + _fail("mesh has an orientation conflict") + declared: set[tuple[int, int]] = set() + for name, loop in loops.items(): + for index, left in enumerate(loop): + edge = _edge_key(left, loop[(index + 1) % len(loop)]) + if edge not in boundary: + _fail(f"loop {name!r} contains a non-boundary edge") + if edge in declared: + _fail("boundary edge is declared by more than one loop") + declared.add(edge) + if declared != boundary: + _fail("loops do not cover the mesh boundary exactly") + + return (vertices, tuple(quads), face_owners, control_owners, loops, + tuple(stencils), uses) + + +def _medial_admission( + frames: dict[str, dict[str, Any]], +) -> tuple[dict[str, Any], ...]: + distance = frames["right"]["H"][0] - frames["left"]["H"][0] + required = frames["left"]["rx"] + frames["right"]["rx"] + clearance = distance - required + if clearance > 0.0: + return () + return ({ + "gate": "medial-clearance", + "outcome": "reject", + "observed_clearance": clearance, + "lateral_centre_distance": distance, + "required_distance": required, + },) + + +def build( + components: dict[str, float], + attachments: dict[str, dict[str, list[float]]], + diagnostic: bool = False, +) -> dict[str, Any]: + """Construct the fixed local L0 transition mesh.""" + if type(diagnostic) is not bool: + _fail("diagnostic must be a bool") + carrier, checked_attachments = _validate_inputs(components, attachments) + frames = _frame_and_dimensions(carrier, checked_attachments) + admission_failures = _medial_admission(frames) + if admission_failures and not diagnostic: + _fail("medial clearance admission failed; use diagnostic=True to retain it") + transitions = _transition_rings(frames) + base_vertices = _original_vertices(carrier, transitions) + vertices, quads, face_owners, transition_indices, loops = _transition_faces( + base_vertices, transitions + ) + control_owners = tuple( + _SOURCE.CONTROL_OWNERS[control_id] + for control_id in _SOURCE.CONTROL_IDS + ) + control_owners += tuple( + _SIDE_DOMAIN[side] + for side in _SIDES + for _index in range(2 * len(transitions[side]["ringA"])) + ) + metadata = _metadata(frames, transition_indices, admission_failures, + control_owners) + mesh = { + "vertices": tuple(vertices), + "quads": tuple(quads), + "face_owners": tuple(face_owners), + "control_owners": control_owners, + "loops": loops, + "base_stencils": _identity_stencils(len(vertices)), + "frames": metadata["frames"], + "metadata": metadata, + } + _validate_mesh(mesh) + return mesh + + +def _combine_stencils( + parent_stencils: tuple[tuple[tuple[int, float], ...], ...], + terms: list[tuple[int, float]], +) -> tuple[tuple[int, float], ...]: + values: dict[int, float] = defaultdict(float) + for parent_index, factor in terms: + for base_index, coefficient in parent_stencils[parent_index]: + values[base_index] += factor * coefficient + return tuple((base_index, coefficient) + for base_index, coefficient in sorted(values.items()) + if coefficient != 0.0) + + +def _owners_from_stencils( + base_owners: tuple[str, ...], + stencils: tuple[tuple[tuple[int, float], ...], ...], +) -> tuple[str, ...]: + owners = [] + for stencil in stencils: + base_index, _coefficient = min( + stencil, + key=lambda item: (-abs(item[1]), item[0]), + ) + owners.append(base_owners[base_index]) + return tuple(owners) + + +def _blend_points( + points: tuple[tuple[float, float, float], ...], + terms: list[tuple[int, float]], +) -> tuple[float, float, float]: + result = [0.0, 0.0, 0.0] + for point_index, factor in terms: + point = points[point_index] + for axis in range(3): + result[axis] += factor * point[axis] + return tuple(result) # type: ignore[return-value] + + +def _subdivide_once(mesh: Mapping[str, Any], level: int) -> dict[str, Any]: + points, quads, face_owners, control_owners, loops, parent_stencils, uses = ( + _validate_mesh(mesh) + ) + if type(level) is not int or level < 1: + _fail("subdivision level must be a positive integer") + + edges = tuple(sorted(uses)) + boundary = {edge for edge, rows in uses.items() if len(rows) == 1} + faces_at_vertex: dict[int, list[int]] = defaultdict(list) + edges_at_vertex: dict[int, list[tuple[int, int]]] = defaultdict(list) + for face_index, face in enumerate(quads): + for vertex in face: + faces_at_vertex[vertex].append(face_index) + for edge in edges: + left, right = edge + edges_at_vertex[left].append(edge) + edges_at_vertex[right].append(edge) + + vertex_terms: list[list[tuple[int, float]]] = [] + for vertex in range(len(points)): + boundary_edges = [edge for edge in boundary if vertex in edge] + if boundary_edges: + neighbours = sorted({ + other + for edge in boundary_edges + for other in edge + if other != vertex + }) + if len(neighbours) != 2: + _fail("boundary vertex does not have exactly two boundary neighbours") + vertex_terms.append([(vertex, 6.0 / 8.0), + (neighbours[0], 1.0 / 8.0), + (neighbours[1], 1.0 / 8.0)]) + continue + incident_faces = sorted(faces_at_vertex[vertex]) + incident_edges = sorted(edges_at_vertex[vertex]) + valence = len(incident_faces) + if valence == 0 or len(incident_edges) != valence: + _fail("interior vertex has inconsistent Catmull--Clark valence") + terms: list[tuple[int, float]] = [] + for face_index in incident_faces: + terms.extend((corner, 1.0 / (4.0 * valence * valence)) + for corner in quads[face_index]) + for left, right in incident_edges: + terms.extend(((left, 1.0 / (valence * len(incident_edges))), + (right, 1.0 / (valence * len(incident_edges))))) + terms.append((vertex, (valence - 3.0) / valence)) + vertex_terms.append(terms) + + edge_terms: list[list[tuple[int, float]]] = [] + for edge in edges: + left, right = edge + rows = uses[edge] + if len(rows) == 1: + edge_terms.append([(left, 0.5), (right, 0.5)]) + continue + terms = [(left, 0.25), (right, 0.25)] + for face_index, _face_left, _face_right in sorted(rows): + terms.extend((corner, 0.25 * 0.25) + for corner in quads[face_index]) + edge_terms.append(terms) + + face_terms = [ + [(corner, 0.25) for corner in face] + for face in quads + ] + vertices: list[tuple[float, float, float]] = [] + stencils: list[tuple[tuple[int, float], ...]] = [] + for terms in vertex_terms + edge_terms + face_terms: + vertices.append(_blend_points(points, terms)) + stencils.append(_combine_stencils(parent_stencils, terms)) + + vertex_count = len(points) + edge_indices = { + edge: vertex_count + index for index, edge in enumerate(edges) + } + face_start = vertex_count + len(edges) + child_quads: list[tuple[int, int, int, int]] = [] + child_owners: list[str] = [] + for face_index, face in enumerate(quads): + face_point = face_start + face_index + for corner, vertex in enumerate(face): + next_vertex = face[(corner + 1) % 4] + previous_vertex = face[(corner - 1) % 4] + child_quads.append(( + vertex, + edge_indices[_edge_key(vertex, next_vertex)], + face_point, + edge_indices[_edge_key(previous_vertex, vertex)], + )) + child_owners.append(face_owners[face_index]) + + child_loops = { + name: tuple( + item + for index, vertex in enumerate(loop) + for item in ( + vertex, + edge_indices[_edge_key(vertex, loop[(index + 1) % len(loop)])], + ) + ) + for name, loop in loops.items() + } + metadata = dict(mesh["metadata"]) + metadata["level"] = level + child = { + "vertices": tuple(vertices), + "quads": tuple(child_quads), + "face_owners": tuple(child_owners), + "control_owners": _owners_from_stencils( + tuple(metadata["base_control_owners"]), tuple(stencils) + ), + "loops": child_loops, + "base_stencils": tuple(stencils), + "frames": mesh["frames"], + "metadata": metadata, + } + _validate_mesh(child) + return child + + +def evaluate(mesh: Mapping[str, Any], levels: int = 2) -> list[dict[str, Any]]: + """Return the ordered sequence beginning with the supplied L0 mesh.""" + if type(levels) is not int or levels < 0 or levels > 2: + _fail("the local transition evaluates between zero and two CC levels") + _validate_mesh(mesh) + result = [dict(mesh)] + current: Mapping[str, Any] = mesh + for level in range(1, levels + 1): + current = _subdivide_once(current, level) + result.append(current) + return result + + +def build_case(case: Mapping[str, Any]) -> dict[str, Any]: + """Runner adapter; evidence runs opt into diagnostic retention.""" + if not isinstance(case, Mapping): + _fail("case must be a mapping") + return build(case["components"], case["attachments"], diagnostic=True) + + +def evaluate_case(mesh: Mapping[str, Any], _case: Mapping[str, Any]) -> list[dict[str, Any]]: + """Runner adapter for the fixed two-step evaluation.""" + return evaluate(mesh, levels=2) + + +__all__ = [ + "GEOMETRY_COMPONENT_IDS", + "build", + "build_case", + "evaluate", + "evaluate_case", +] diff --git a/experiments/pelvis-thigh-transition/finish_evidence.py b/experiments/pelvis-thigh-transition/finish_evidence.py new file mode 100644 index 0000000..c295dfc --- /dev/null +++ b/experiments/pelvis-thigh-transition/finish_evidence.py @@ -0,0 +1,152 @@ +"""Compare completed captured runs and render stored L2 evidence; never run checks.""" +import argparse +import hashlib +import importlib.util +import json +from pathlib import Path +import re + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def digest(data): + return hashlib.sha256(data).hexdigest() + + +def encoded(value): + return (json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False) + "\n").encode() + + +def read(path): + def invalid(token): + raise ValueError(f"nonfinite JSON token: {token}") + return json.loads(path.read_bytes(), parse_constant=invalid) + + +def normal(value, root): + # Only exact root strings or paths under that root; never replace prose/substrings. + if isinstance(value, str): + return "" + value[len(root):] if value == root or value.startswith(root + "/") else value + if isinstance(value, list): + return [normal(item, root) for item in value] + if isinstance(value, dict): + return {key: normal(item, root) for key, item in value.items()} + return value + + +def local(root, relative): + path = root / relative + require(not Path(relative).is_absolute() and path.resolve().is_relative_to(root), "artifact escapes run root") + require(path.is_file() and not path.is_symlink(), f"missing/nonregular artifact: {path}") + return path + + +def complete(root): + report, inputs = read(local(root, "run-report.json")), read(local(root, "inputs.json")) + require(report["schema"] == "creature-kernel.pelvis-thigh-transition-run-report.v1", "wrong report schema") + rows = report["cases"] + require(len(rows) == report["case_count"] == len(inputs["cases"]), "incomplete case count") + require([r["case_id"] for r in rows] == [c["id"] for c in inputs["cases"]], "case inventory mismatch") + require(len({r["case_id"] for r in rows}) == len(rows), "duplicate case IDs") + require(len(inputs["mandatory_case_ids"]) == len(set(inputs["mandatory_case_ids"])) == 6, "six mandatory IDs required") + comparisons = report["perturbation_comparisons"] + require([c["case_id"] for c in comparisons] == inputs["perturbation_case_ids"], "incomplete comparisons") + by_id = {} + for index, row in enumerate(rows): + case_id = row["case_id"] + require(re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]{0,95}", case_id), "unsafe case ID") + require(row["index"] == index and row["phase"] == "checkscomplete", "case not complete") + require(isinstance(row["check_result"], dict) and isinstance(row["outcome"], str), "missing case result") + directory = Path("cases") / f"case-{index:02d}-{case_id}" + require([a["level"] for a in row["artifacts"]] == [0, 1, 2], "missing mesh levels") + paths = [local(root, directory / a["path"]) for a in row["artifacts"]] + require(any((root / directory).glob("*.png")), "missing direct views") + by_id[case_id] = (row, paths[2]) + require(set(inputs["mandatory_case_ids"]).issubset(by_id), "missing mandatory cases") + return report, inputs, by_id + + +def inventory(root): + paths = sorted(p for p in root.rglob("*") if p.suffix.lower() == ".png" or p.match("mesh-level-*.json")) + return {p.relative_to(root).as_posix(): local(root, p.relative_to(root)) for p in paths} + + +def finish(first, repeat, output): + for path in (first, repeat, output): + require(path.is_absolute() and path == path.resolve(), "paths must be absolute and canonical") + require(first != repeat and first.is_dir() and repeat.is_dir(), "two distinct run roots required") + require(not output.exists() and not output.is_symlink() and output.parent.is_dir(), "output must be absent with existing parent") + require(not any(output.is_relative_to(root) for root in (first, repeat)), "output must be outside runs") + a, ai, ac = complete(first) + b, bi, bc = complete(repeat) + left, right = inventory(first), inventory(repeat) + mismatches, hashes = [], [{}, {}] + for name in sorted(left.keys() | right.keys()): + x, y = left[name].read_bytes() if name in left else None, right[name].read_bytes() if name in right else None + for table, data in zip(hashes, (x, y)): + if data is not None: + table[name] = {"bytes": len(data), "sha256": digest(data)} + if x != y: + mismatches.append({"path": name, "first": hashes[0].get(name), "repeat": hashes[1].get(name)}) + numeric, outcomes = [], [] + for case_id in sorted(ac.keys() | bc.keys()): + x = ac[case_id][0] if case_id in ac else None + y = bc[case_id][0] if case_id in bc else None + outcomes.append({"case_id": case_id, "first": x["outcome"] if x else None, "repeat": y["outcome"] if y else None}) + numeric.append((case_id, {k: x[k] for k in ("outcome", "check_result")} if x else None, + {k: y[k] for k in ("outcome", "check_result")} if y else None)) + numeric.extend((("perturbation_comparisons", a["perturbation_comparisons"], b["perturbation_comparisons"]), ("inputs", ai, bi))) + numeric_rows = [] + for name, x, y in numeric: + x, y = encoded(normal(x, str(first))), encoded(normal(y, str(repeat))) + numeric_rows.append({"name": name, "equal": x == y, "first_sha256": digest(x), "repeat_sha256": digest(y)}) + summary = {"schema": "pelvis-thigh-transition/determinism-v1", "first": str(first), "repeat": str(repeat), + "equal": not mismatches and all(r["equal"] for r in numeric_rows), "artifact_counts": [len(left), len(right)], + "inventory_sha256": [digest(encoded(h)) for h in hashes], "artifact_mismatches": mismatches, + "numeric_comparisons": numeric_rows, "per_case_outcomes": outcomes, + "normalization": "Only exact run-root strings and root/ path prefixes; all other data retained."} + meshes = {case_id: read(ac[case_id][1]) for case_id in ai["mandatory_case_ids"]} + renderer_path = Path(__file__).resolve().with_name("render.py") + spec = importlib.util.spec_from_file_location("finish_captured_render", renderer_path) + renderer = importlib.util.module_from_spec(spec) + spec.loader.exec_module(renderer) + output.mkdir() + (output / "determinism-report.json").write_bytes(encoded(summary)) + rendered = [] + for case_id, mesh in meshes.items(): + # Exact declared lower-crop frames from runner._case_bounds; no geometry import. + bounds = [[-0.30, -0.42, -0.20], [0.30, 0.16, 0.20]] if case_id == "ordinary_human_reference" else [[-2.4, -2.7, -1.3], [2.4, 1.0, 1.3]] + require(mesh["level"] == 2 and ac[case_id][0]["bounds"]["lowercrop"] == bounds, "L2/frame declaration mismatch") + directory = output / case_id + directory.mkdir() + metadata = renderer.render_views(mesh["vertices"], mesh["quads"], directory / "surface.png", title=case_id, + status="REJECTED - FINAL BUDGET", bounds=bounds, allow_crop=True, underside=True) + rendered.append({"case_id": case_id, "source_mesh": str(ac[case_id][1]), + "source_mesh_sha256": digest(ac[case_id][1].read_bytes()), "render": metadata}) + manifest = {"schema": "pelvis-thigh-transition/finish-manifest-v1", + "parent_judgment": {"status": "REJECTED - FINAL BUDGET", "source": "supplied parent instruction", + "automatically_inferred": False, "independent_of_technical_outcomes": True}, + "helper_sha256": digest(Path(__file__).read_bytes()), "renderer_sha256": digest(renderer_path.read_bytes()), + "renders": rendered, "files": [], "self_hash": "manifest SHA-256 returned on stdout; self excluded from files"} + for path in sorted(output.rglob("*")): + if path.is_file(): + data = path.read_bytes() + manifest["files"].append({"path": path.relative_to(output).as_posix(), "bytes": len(data), "sha256": digest(data)}) + raw = encoded(manifest) + (output / "output-manifest.json").write_bytes(raw) + return {"deterministic": summary["equal"], "output_manifest_sha256": digest(raw)} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ("first", "repeat", "output"): + parser.add_argument("--" + name, type=Path, required=True) + args = parser.parse_args() + print(json.dumps(finish(args.first, args.repeat, args.output), sort_keys=True), flush=True) + + +if __name__ == "__main__": + main() diff --git a/experiments/pelvis-thigh-transition/inputs.json b/experiments/pelvis-thigh-transition/inputs.json new file mode 100644 index 0000000..23fe452 --- /dev/null +++ b/experiments/pelvis-thigh-transition/inputs.json @@ -0,0 +1,3899 @@ +{ + "cases": [ + { + "attachments": { + "left": { + "centre": [ + -1.0, + -1.0, + 0.0 + ], + "knee": [ + -1.0, + -2.0, + 0.0 + ] + }, + "right": { + "centre": [ + 1.0, + -1.0, + 0.0 + ], + "knee": [ + 1.0, + -2.0, + 0.0 + ] + } + }, + "components": { + "hips.left.P_s.x": -1.0, + "hips.left.P_s.y": -1.0, + "hips.left.P_s.z": 0.0, + "hips.left.r_x": 0.32, + "hips.left.r_y": 0.28, + "hips.left.r_z": 0.3, + "hips.right.P_s.x": 1.0, + "hips.right.P_s.y": -1.0, + "hips.right.P_s.z": 0.0, + "hips.right.r_x": 0.32, + "hips.right.r_y": 0.28, + "hips.right.r_z": 0.3, + "shoulders.left.arm_origin.x": -1.0, + "shoulders.left.arm_origin.y": 2.0, + "shoulders.left.arm_origin.z": 0.0, + "shoulders.left.axilla.x": -1.1, + "shoulders.left.axilla.y": 1.7, + "shoulders.left.axilla.z": 0.0, + "shoulders.left.peak.x": -1.1, + "shoulders.left.peak.y": 2.15, + "shoulders.left.peak.z": 0.0, + "shoulders.left.shoulder_depth": 0.35, + "shoulders.left.start_forward": 0.32, + "shoulders.left.start_lateral": 0.35, + "shoulders.left.start_up": 0.3, + "shoulders.right.arm_origin.x": 1.0, + "shoulders.right.arm_origin.y": 2.0, + "shoulders.right.arm_origin.z": 0.0, + "shoulders.right.axilla.x": 1.1, + "shoulders.right.axilla.y": 1.7, + "shoulders.right.axilla.z": 0.0, + "shoulders.right.peak.x": 1.1, + "shoulders.right.peak.y": 2.15, + "shoulders.right.peak.z": 0.0, + "shoulders.right.shoulder_depth": 0.35, + "shoulders.right.start_forward": 0.32, + "shoulders.right.start_lateral": 0.35, + "shoulders.right.start_up": 0.3, + "stations.lower_abdomen.C.x": 0.0, + "stations.lower_abdomen.C.y": 0.25, + "stations.lower_abdomen.C.z": 0.0, + "stations.lower_abdomen.rA": 0.68, + "stations.lower_abdomen.rL": 1.125, + "stations.lower_abdomen.rP": 0.54, + "stations.lower_pelvis.C.x": 0.0, + "stations.lower_pelvis.C.y": -0.45, + "stations.lower_pelvis.C.z": 0.0, + "stations.lower_pelvis.rA": 0.85, + "stations.lower_pelvis.rL": 1.5, + "stations.lower_pelvis.rP": 0.6, + "stations.lower_ribcage.C.x": 0.0, + "stations.lower_ribcage.C.y": 1.05, + "stations.lower_ribcage.C.z": 0.0, + "stations.lower_ribcage.rA": 0.875, + "stations.lower_ribcage.rL": 1.45, + "stations.lower_ribcage.rP": 0.675, + "stations.neck_collar.C.x": 0.0, + "stations.neck_collar.C.y": 2.15, + "stations.neck_collar.C.z": 0.0, + "stations.neck_collar.rA": 0.4, + "stations.neck_collar.rL": 0.42, + "stations.neck_collar.rP": 0.4, + "stations.neck_upper.C.x": 0.0, + "stations.neck_upper.C.y": 2.55, + "stations.neck_upper.C.z": 0.0, + "stations.neck_upper.rA": 0.33, + "stations.neck_upper.rL": 0.34, + "stations.neck_upper.rP": 0.33, + "stations.upper_abdomen.C.x": 0.0, + "stations.upper_abdomen.C.y": 0.8, + "stations.upper_abdomen.C.z": 0.0, + "stations.upper_abdomen.rA": 0.725, + "stations.upper_abdomen.rL": 1.225, + "stations.upper_abdomen.rP": 0.56, + "stations.upper_pelvis.C.x": 0.0, + "stations.upper_pelvis.C.y": -0.2, + "stations.upper_pelvis.C.z": 0.0, + "stations.upper_pelvis.rA": 0.78, + "stations.upper_pelvis.rL": 1.35, + "stations.upper_pelvis.rP": 0.56, + "stations.upper_ribcage_shoulder.C.x": 0.0, + "stations.upper_ribcage_shoulder.C.y": 1.95, + "stations.upper_ribcage_shoulder.C.z": 0.0, + "stations.upper_ribcage_shoulder.rA": 0.9, + "stations.upper_ribcage_shoulder.rL": 1.5, + "stations.upper_ribcage_shoulder.rP": 0.7, + "stations.waist_abdomen.C.x": 0.0, + "stations.waist_abdomen.C.y": 0.5, + "stations.waist_abdomen.C.z": 0.0, + "stations.waist_abdomen.rA": 0.5, + "stations.waist_abdomen.rL": 0.875, + "stations.waist_abdomen.rP": 0.4 + }, + "id": "standard_neutral_reference", + "provenance": { + "bindings": { + "left": { + "centre": { + "derivation": "profile.world-part-plus-thigh-start.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|left|thigh/0", + "/profiles/0/part_placements/main|part|left|thigh/1", + "/profiles/0/part_placements/main|part|left|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/10/placement/translation/0", + "/body/parts/10/placement/translation/1", + "/body/parts/10/placement/translation/2", + "/body/landmarks/14/position/0", + "/body/landmarks/14/position/1", + "/body/landmarks/14/position/2" + ] + }, + "frame": { + "interpretation": "identity frame admitted; no rig or joint resolution", + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "source_pointers": [ + "/body/frames/8/transform" + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "joint_hint": { + "distal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "interpretation": "source hint retained for provenance; not interpreted as a solved skeleton", + "proximal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "source_pointer": "/body/joints/9" + }, + "knee": { + "derivation": "profile.world-part-plus-source-knee.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|left|thigh/0", + "/profiles/0/part_placements/main|part|left|thigh/1", + "/profiles/0/part_placements/main|part|left|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/10/placement/translation/0", + "/body/parts/10/placement/translation/1", + "/body/parts/10/placement/translation/2", + "/body/landmarks/16/position/0", + "/body/landmarks/16/position/1", + "/body/landmarks/16/position/2" + ] + } + }, + "right": { + "centre": { + "derivation": "profile.world-part-plus-thigh-start.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|right|thigh/0", + "/profiles/0/part_placements/main|part|right|thigh/1", + "/profiles/0/part_placements/main|part|right|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/13/placement/translation/0", + "/body/parts/13/placement/translation/1", + "/body/parts/13/placement/translation/2", + "/body/landmarks/19/position/0", + "/body/landmarks/19/position/1", + "/body/landmarks/19/position/2" + ] + }, + "frame": { + "interpretation": "identity frame admitted; no rig or joint resolution", + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "source_pointers": [ + "/body/frames/10/transform" + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "joint_hint": { + "distal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "interpretation": "source hint retained for provenance; not interpreted as a solved skeleton", + "proximal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "source_pointer": "/body/joints/12" + }, + "knee": { + "derivation": "profile.world-part-plus-source-knee.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|right|thigh/0", + "/profiles/0/part_placements/main|part|right|thigh/1", + "/profiles/0/part_placements/main|part|right|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/13/placement/translation/0", + "/body/parts/13/placement/translation/1", + "/body/parts/13/placement/translation/2", + "/body/landmarks/21/position/0", + "/body/landmarks/21/position/1", + "/body/landmarks/21/position/2" + ] + } + } + }, + "claim": "unchanged exact-five profile projection; no geometry executed", + "profile": { + "path": "experiments/current-form-surface-preview/structural_profile_candidates.json", + "profile_id": "standard_neutral_reference", + "profile_index": 0, + "sha256": "a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640" + }, + "source": { + "path": "examples/body-documents/stylized-digitigrade-biped-authored-form.json", + "sha256": "82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14" + } + }, + "role": "exactfive_unchanged_profileprojection" + }, + { + "attachments": { + "left": { + "centre": [ + -1.0, + -1.0, + 0.0 + ], + "knee": [ + -1.0, + -2.0, + 0.0 + ] + }, + "right": { + "centre": [ + 1.0, + -1.0, + 0.0 + ], + "knee": [ + 1.0, + -2.0, + 0.0 + ] + } + }, + "components": { + "hips.left.P_s.x": -1.0, + "hips.left.P_s.y": -1.0, + "hips.left.P_s.z": 0.0, + "hips.left.r_x": 0.336, + "hips.left.r_y": 0.294, + "hips.left.r_z": 0.315, + "hips.right.P_s.x": 1.0, + "hips.right.P_s.y": -1.0, + "hips.right.P_s.z": 0.0, + "hips.right.r_x": 0.336, + "hips.right.r_y": 0.294, + "hips.right.r_z": 0.315, + "shoulders.left.arm_origin.x": -3.0, + "shoulders.left.arm_origin.y": 2.0, + "shoulders.left.arm_origin.z": 0.0, + "shoulders.left.axilla.x": -3.1, + "shoulders.left.axilla.y": 1.7, + "shoulders.left.axilla.z": 0.0, + "shoulders.left.peak.x": -3.1, + "shoulders.left.peak.y": 2.15, + "shoulders.left.peak.z": 0.0, + "shoulders.left.shoulder_depth": 0.392, + "shoulders.left.start_forward": 0.336, + "shoulders.left.start_lateral": 0.368, + "shoulders.left.start_up": 0.315, + "shoulders.right.arm_origin.x": 3.0, + "shoulders.right.arm_origin.y": 2.0, + "shoulders.right.arm_origin.z": 0.0, + "shoulders.right.axilla.x": 3.1, + "shoulders.right.axilla.y": 1.7, + "shoulders.right.axilla.z": 0.0, + "shoulders.right.peak.x": 3.1, + "shoulders.right.peak.y": 2.15, + "shoulders.right.peak.z": 0.0, + "shoulders.right.shoulder_depth": 0.392, + "shoulders.right.start_forward": 0.336, + "shoulders.right.start_lateral": 0.368, + "shoulders.right.start_up": 0.315, + "stations.lower_abdomen.C.x": 0.0, + "stations.lower_abdomen.C.y": 0.25, + "stations.lower_abdomen.C.z": 0.0, + "stations.lower_abdomen.rA": 0.707, + "stations.lower_abdomen.rL": 1.328, + "stations.lower_abdomen.rP": 0.562, + "stations.lower_pelvis.C.x": 0.0, + "stations.lower_pelvis.C.y": -0.45, + "stations.lower_pelvis.C.z": 0.0, + "stations.lower_pelvis.rA": 0.884, + "stations.lower_pelvis.rL": 1.77, + "stations.lower_pelvis.rP": 0.624, + "stations.lower_ribcage.C.x": 0.0, + "stations.lower_ribcage.C.y": 1.05, + "stations.lower_ribcage.C.z": 0.0, + "stations.lower_ribcage.rA": 0.91, + "stations.lower_ribcage.rL": 1.711, + "stations.lower_ribcage.rP": 0.702, + "stations.neck_collar.C.x": 0.0, + "stations.neck_collar.C.y": 2.15, + "stations.neck_collar.C.z": 0.0, + "stations.neck_collar.rA": 0.42, + "stations.neck_collar.rL": 0.441, + "stations.neck_collar.rP": 0.42, + "stations.neck_upper.C.x": 0.0, + "stations.neck_upper.C.y": 2.55, + "stations.neck_upper.C.z": 0.0, + "stations.neck_upper.rA": 0.346, + "stations.neck_upper.rL": 0.357, + "stations.neck_upper.rP": 0.346, + "stations.upper_abdomen.C.x": 0.0, + "stations.upper_abdomen.C.y": 0.8, + "stations.upper_abdomen.C.z": 0.0, + "stations.upper_abdomen.rA": 0.754, + "stations.upper_abdomen.rL": 1.446, + "stations.upper_abdomen.rP": 0.582, + "stations.upper_pelvis.C.x": 0.0, + "stations.upper_pelvis.C.y": -0.2, + "stations.upper_pelvis.C.z": 0.0, + "stations.upper_pelvis.rA": 0.811, + "stations.upper_pelvis.rL": 1.593, + "stations.upper_pelvis.rP": 0.582, + "stations.upper_ribcage_shoulder.C.x": 0.0, + "stations.upper_ribcage_shoulder.C.y": 1.95, + "stations.upper_ribcage_shoulder.C.z": 0.0, + "stations.upper_ribcage_shoulder.rA": 0.936, + "stations.upper_ribcage_shoulder.rL": 1.77, + "stations.upper_ribcage_shoulder.rP": 0.728, + "stations.waist_abdomen.C.x": 0.0, + "stations.waist_abdomen.C.y": 0.5, + "stations.waist_abdomen.C.z": 0.0, + "stations.waist_abdomen.rA": 0.52, + "stations.waist_abdomen.rL": 1.032, + "stations.waist_abdomen.rP": 0.416 + }, + "id": "compact_broad_short_limb_large_head", + "provenance": { + "bindings": { + "left": { + "centre": { + "derivation": "profile.world-part-plus-thigh-start.v1", + "profile_pointers": [ + "/profiles/1/part_placements/main|part||pelvis/0", + "/profiles/1/part_placements/main|part||pelvis/1", + "/profiles/1/part_placements/main|part||pelvis/2", + "/profiles/1/part_placements/main|part|left|thigh/0", + "/profiles/1/part_placements/main|part|left|thigh/1", + "/profiles/1/part_placements/main|part|left|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/10/placement/translation/0", + "/body/parts/10/placement/translation/1", + "/body/parts/10/placement/translation/2", + "/body/landmarks/14/position/0", + "/body/landmarks/14/position/1", + "/body/landmarks/14/position/2" + ] + }, + "frame": { + "interpretation": "identity frame admitted; no rig or joint resolution", + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "source_pointers": [ + "/body/frames/8/transform" + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "joint_hint": { + "distal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "interpretation": "source hint retained for provenance; not interpreted as a solved skeleton", + "proximal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "source_pointer": "/body/joints/9" + }, + "knee": { + "derivation": "profile.world-part-plus-source-knee.v1", + "profile_pointers": [ + "/profiles/1/part_placements/main|part||pelvis/0", + "/profiles/1/part_placements/main|part||pelvis/1", + "/profiles/1/part_placements/main|part||pelvis/2", + "/profiles/1/part_placements/main|part|left|thigh/0", + "/profiles/1/part_placements/main|part|left|thigh/1", + "/profiles/1/part_placements/main|part|left|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/10/placement/translation/0", + "/body/parts/10/placement/translation/1", + "/body/parts/10/placement/translation/2", + "/body/landmarks/16/position/0", + "/body/landmarks/16/position/1", + "/body/landmarks/16/position/2" + ] + } + }, + "right": { + "centre": { + "derivation": "profile.world-part-plus-thigh-start.v1", + "profile_pointers": [ + "/profiles/1/part_placements/main|part||pelvis/0", + "/profiles/1/part_placements/main|part||pelvis/1", + "/profiles/1/part_placements/main|part||pelvis/2", + "/profiles/1/part_placements/main|part|right|thigh/0", + "/profiles/1/part_placements/main|part|right|thigh/1", + "/profiles/1/part_placements/main|part|right|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/13/placement/translation/0", + "/body/parts/13/placement/translation/1", + "/body/parts/13/placement/translation/2", + "/body/landmarks/19/position/0", + "/body/landmarks/19/position/1", + "/body/landmarks/19/position/2" + ] + }, + "frame": { + "interpretation": "identity frame admitted; no rig or joint resolution", + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "source_pointers": [ + "/body/frames/10/transform" + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "joint_hint": { + "distal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "interpretation": "source hint retained for provenance; not interpreted as a solved skeleton", + "proximal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "source_pointer": "/body/joints/12" + }, + "knee": { + "derivation": "profile.world-part-plus-source-knee.v1", + "profile_pointers": [ + "/profiles/1/part_placements/main|part||pelvis/0", + "/profiles/1/part_placements/main|part||pelvis/1", + "/profiles/1/part_placements/main|part||pelvis/2", + "/profiles/1/part_placements/main|part|right|thigh/0", + "/profiles/1/part_placements/main|part|right|thigh/1", + "/profiles/1/part_placements/main|part|right|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/13/placement/translation/0", + "/body/parts/13/placement/translation/1", + "/body/parts/13/placement/translation/2", + "/body/landmarks/21/position/0", + "/body/landmarks/21/position/1", + "/body/landmarks/21/position/2" + ] + } + } + }, + "claim": "unchanged exact-five profile projection; no geometry executed", + "profile": { + "path": "experiments/current-form-surface-preview/structural_profile_candidates.json", + "profile_id": "compact_broad_short_limb_large_head", + "profile_index": 1, + "sha256": "a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640" + }, + "source": { + "path": "examples/body-documents/stylized-digitigrade-biped-authored-form.json", + "sha256": "82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14" + } + }, + "role": "exactfive_unchanged_profileprojection" + }, + { + "attachments": { + "left": { + "centre": [ + -1.0, + -2.0, + 0.0 + ], + "knee": [ + -1.0, + -3.0, + 0.0 + ] + }, + "right": { + "centre": [ + 1.0, + -2.0, + 0.0 + ], + "knee": [ + 1.0, + -3.0, + 0.0 + ] + } + }, + "components": { + "hips.left.P_s.x": -1.0, + "hips.left.P_s.y": -2.0, + "hips.left.P_s.z": 0.0, + "hips.left.r_x": 0.272, + "hips.left.r_y": 0.238, + "hips.left.r_z": 0.255, + "hips.right.P_s.x": 1.0, + "hips.right.P_s.y": -2.0, + "hips.right.P_s.z": 0.0, + "hips.right.r_x": 0.272, + "hips.right.r_y": 0.238, + "hips.right.r_z": 0.255, + "shoulders.left.arm_origin.x": -2.0, + "shoulders.left.arm_origin.y": 2.0, + "shoulders.left.arm_origin.z": 0.0, + "shoulders.left.axilla.x": -2.1, + "shoulders.left.axilla.y": 1.7, + "shoulders.left.axilla.z": 0.0, + "shoulders.left.peak.x": -2.1, + "shoulders.left.peak.y": 2.15, + "shoulders.left.peak.z": 0.0, + "shoulders.left.shoulder_depth": 0.315, + "shoulders.left.start_forward": 0.272, + "shoulders.left.start_lateral": 0.298, + "shoulders.left.start_up": 0.255, + "shoulders.right.arm_origin.x": 2.0, + "shoulders.right.arm_origin.y": 2.0, + "shoulders.right.arm_origin.z": 0.0, + "shoulders.right.axilla.x": 2.1, + "shoulders.right.axilla.y": 1.7, + "shoulders.right.axilla.z": 0.0, + "shoulders.right.peak.x": 2.1, + "shoulders.right.peak.y": 2.15, + "shoulders.right.peak.z": 0.0, + "shoulders.right.shoulder_depth": 0.315, + "shoulders.right.start_forward": 0.272, + "shoulders.right.start_lateral": 0.298, + "shoulders.right.start_up": 0.255, + "stations.lower_abdomen.C.x": 0.0, + "stations.lower_abdomen.C.y": 0.25, + "stations.lower_abdomen.C.z": 0.0, + "stations.lower_abdomen.rA": 0.68, + "stations.lower_abdomen.rL": 0.956, + "stations.lower_abdomen.rP": 0.54, + "stations.lower_pelvis.C.x": 0.0, + "stations.lower_pelvis.C.y": -0.45, + "stations.lower_pelvis.C.z": 0.0, + "stations.lower_pelvis.rA": 0.85, + "stations.lower_pelvis.rL": 1.275, + "stations.lower_pelvis.rP": 0.6, + "stations.lower_ribcage.C.x": 0.0, + "stations.lower_ribcage.C.y": 1.05, + "stations.lower_ribcage.C.z": 0.0, + "stations.lower_ribcage.rA": 0.875, + "stations.lower_ribcage.rL": 1.232, + "stations.lower_ribcage.rP": 0.675, + "stations.neck_collar.C.x": 0.0, + "stations.neck_collar.C.y": 2.15, + "stations.neck_collar.C.z": 0.0, + "stations.neck_collar.rA": 0.38, + "stations.neck_collar.rL": 0.399, + "stations.neck_collar.rP": 0.38, + "stations.neck_upper.C.x": 0.0, + "stations.neck_upper.C.y": 2.55, + "stations.neck_upper.C.z": 0.0, + "stations.neck_upper.rA": 0.314, + "stations.neck_upper.rL": 0.323, + "stations.neck_upper.rP": 0.314, + "stations.upper_abdomen.C.x": 0.0, + "stations.upper_abdomen.C.y": 0.8, + "stations.upper_abdomen.C.z": 0.0, + "stations.upper_abdomen.rA": 0.725, + "stations.upper_abdomen.rL": 1.041, + "stations.upper_abdomen.rP": 0.56, + "stations.upper_pelvis.C.x": 0.0, + "stations.upper_pelvis.C.y": -0.2, + "stations.upper_pelvis.C.z": 0.0, + "stations.upper_pelvis.rA": 0.78, + "stations.upper_pelvis.rL": 1.148, + "stations.upper_pelvis.rP": 0.56, + "stations.upper_ribcage_shoulder.C.x": 0.0, + "stations.upper_ribcage_shoulder.C.y": 1.95, + "stations.upper_ribcage_shoulder.C.z": 0.0, + "stations.upper_ribcage_shoulder.rA": 0.9, + "stations.upper_ribcage_shoulder.rL": 1.275, + "stations.upper_ribcage_shoulder.rP": 0.7, + "stations.waist_abdomen.C.x": 0.0, + "stations.waist_abdomen.C.y": 0.5, + "stations.waist_abdomen.C.z": 0.0, + "stations.waist_abdomen.rA": 0.5, + "stations.waist_abdomen.rL": 0.744, + "stations.waist_abdomen.rP": 0.4 + }, + "id": "tall_narrow_long_legged", + "provenance": { + "bindings": { + "left": { + "centre": { + "derivation": "profile.world-part-plus-thigh-start.v1", + "profile_pointers": [ + "/profiles/2/part_placements/main|part||pelvis/0", + "/profiles/2/part_placements/main|part||pelvis/1", + "/profiles/2/part_placements/main|part||pelvis/2", + "/profiles/2/part_placements/main|part|left|thigh/0", + "/profiles/2/part_placements/main|part|left|thigh/1", + "/profiles/2/part_placements/main|part|left|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/10/placement/translation/0", + "/body/parts/10/placement/translation/1", + "/body/parts/10/placement/translation/2", + "/body/landmarks/14/position/0", + "/body/landmarks/14/position/1", + "/body/landmarks/14/position/2" + ] + }, + "frame": { + "interpretation": "identity frame admitted; no rig or joint resolution", + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "source_pointers": [ + "/body/frames/8/transform" + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "joint_hint": { + "distal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "interpretation": "source hint retained for provenance; not interpreted as a solved skeleton", + "proximal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "source_pointer": "/body/joints/9" + }, + "knee": { + "derivation": "profile.world-part-plus-source-knee.v1", + "profile_pointers": [ + "/profiles/2/part_placements/main|part||pelvis/0", + "/profiles/2/part_placements/main|part||pelvis/1", + "/profiles/2/part_placements/main|part||pelvis/2", + "/profiles/2/part_placements/main|part|left|thigh/0", + "/profiles/2/part_placements/main|part|left|thigh/1", + "/profiles/2/part_placements/main|part|left|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/10/placement/translation/0", + "/body/parts/10/placement/translation/1", + "/body/parts/10/placement/translation/2", + "/body/landmarks/16/position/0", + "/body/landmarks/16/position/1", + "/body/landmarks/16/position/2" + ] + } + }, + "right": { + "centre": { + "derivation": "profile.world-part-plus-thigh-start.v1", + "profile_pointers": [ + "/profiles/2/part_placements/main|part||pelvis/0", + "/profiles/2/part_placements/main|part||pelvis/1", + "/profiles/2/part_placements/main|part||pelvis/2", + "/profiles/2/part_placements/main|part|right|thigh/0", + "/profiles/2/part_placements/main|part|right|thigh/1", + "/profiles/2/part_placements/main|part|right|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/13/placement/translation/0", + "/body/parts/13/placement/translation/1", + "/body/parts/13/placement/translation/2", + "/body/landmarks/19/position/0", + "/body/landmarks/19/position/1", + "/body/landmarks/19/position/2" + ] + }, + "frame": { + "interpretation": "identity frame admitted; no rig or joint resolution", + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "source_pointers": [ + "/body/frames/10/transform" + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "joint_hint": { + "distal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "interpretation": "source hint retained for provenance; not interpreted as a solved skeleton", + "proximal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "source_pointer": "/body/joints/12" + }, + "knee": { + "derivation": "profile.world-part-plus-source-knee.v1", + "profile_pointers": [ + "/profiles/2/part_placements/main|part||pelvis/0", + "/profiles/2/part_placements/main|part||pelvis/1", + "/profiles/2/part_placements/main|part||pelvis/2", + "/profiles/2/part_placements/main|part|right|thigh/0", + "/profiles/2/part_placements/main|part|right|thigh/1", + "/profiles/2/part_placements/main|part|right|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/13/placement/translation/0", + "/body/parts/13/placement/translation/1", + "/body/parts/13/placement/translation/2", + "/body/landmarks/21/position/0", + "/body/landmarks/21/position/1", + "/body/landmarks/21/position/2" + ] + } + } + }, + "claim": "unchanged exact-five profile projection; no geometry executed", + "profile": { + "path": "experiments/current-form-surface-preview/structural_profile_candidates.json", + "profile_id": "tall_narrow_long_legged", + "profile_index": 2, + "sha256": "a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640" + }, + "source": { + "path": "examples/body-documents/stylized-digitigrade-biped-authored-form.json", + "sha256": "82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14" + } + }, + "role": "exactfive_unchanged_profileprojection" + }, + { + "attachments": { + "left": { + "centre": [ + -1.0, + -2.0, + 0.0 + ], + "knee": [ + -1.0, + -3.0, + 0.0 + ] + }, + "right": { + "centre": [ + 1.0, + -2.0, + 0.0 + ], + "knee": [ + 1.0, + -3.0, + 0.0 + ] + } + }, + "components": { + "hips.left.P_s.x": -1.0, + "hips.left.P_s.y": -2.0, + "hips.left.P_s.z": 0.0, + "hips.left.r_x": 0.25, + "hips.left.r_y": 0.218, + "hips.left.r_z": 0.234, + "hips.right.P_s.x": 1.0, + "hips.right.P_s.y": -2.0, + "hips.right.P_s.z": 0.0, + "hips.right.r_x": 0.25, + "hips.right.r_y": 0.218, + "hips.right.r_z": 0.234, + "shoulders.left.arm_origin.x": -2.0, + "shoulders.left.arm_origin.y": 2.0, + "shoulders.left.arm_origin.z": 0.0, + "shoulders.left.axilla.x": -2.1, + "shoulders.left.axilla.y": 1.7, + "shoulders.left.axilla.z": 0.0, + "shoulders.left.peak.x": -2.1, + "shoulders.left.peak.y": 2.15, + "shoulders.left.peak.z": 0.0, + "shoulders.left.shoulder_depth": 0.28, + "shoulders.left.start_forward": 0.25, + "shoulders.left.start_lateral": 0.273, + "shoulders.left.start_up": 0.234, + "shoulders.right.arm_origin.x": 2.0, + "shoulders.right.arm_origin.y": 2.0, + "shoulders.right.arm_origin.z": 0.0, + "shoulders.right.axilla.x": 2.1, + "shoulders.right.axilla.y": 1.7, + "shoulders.right.axilla.z": 0.0, + "shoulders.right.peak.x": 2.1, + "shoulders.right.peak.y": 2.15, + "shoulders.right.peak.z": 0.0, + "shoulders.right.shoulder_depth": 0.28, + "shoulders.right.start_forward": 0.25, + "shoulders.right.start_lateral": 0.273, + "shoulders.right.start_up": 0.234, + "stations.lower_abdomen.C.x": 0.0, + "stations.lower_abdomen.C.y": 0.25, + "stations.lower_abdomen.C.z": 0.0, + "stations.lower_abdomen.rA": 0.612, + "stations.lower_abdomen.rL": 0.9, + "stations.lower_abdomen.rP": 0.486, + "stations.lower_pelvis.C.x": 0.0, + "stations.lower_pelvis.C.y": -0.45, + "stations.lower_pelvis.C.z": 0.0, + "stations.lower_pelvis.rA": 0.765, + "stations.lower_pelvis.rL": 1.2, + "stations.lower_pelvis.rP": 0.54, + "stations.lower_ribcage.C.x": 0.0, + "stations.lower_ribcage.C.y": 1.05, + "stations.lower_ribcage.C.z": 0.0, + "stations.lower_ribcage.rA": 0.788, + "stations.lower_ribcage.rL": 1.16, + "stations.lower_ribcage.rP": 0.608, + "stations.neck_collar.C.x": 0.0, + "stations.neck_collar.C.y": 2.15, + "stations.neck_collar.C.z": 0.0, + "stations.neck_collar.rA": 0.34, + "stations.neck_collar.rL": 0.357, + "stations.neck_collar.rP": 0.34, + "stations.neck_upper.C.x": 0.0, + "stations.neck_upper.C.y": 2.55, + "stations.neck_upper.C.z": 0.0, + "stations.neck_upper.rA": 0.28, + "stations.neck_upper.rL": 0.289, + "stations.neck_upper.rP": 0.28, + "stations.upper_abdomen.C.x": 0.0, + "stations.upper_abdomen.C.y": 0.8, + "stations.upper_abdomen.C.z": 0.0, + "stations.upper_abdomen.rA": 0.652, + "stations.upper_abdomen.rL": 0.98, + "stations.upper_abdomen.rP": 0.504, + "stations.upper_pelvis.C.x": 0.0, + "stations.upper_pelvis.C.y": -0.2, + "stations.upper_pelvis.C.z": 0.0, + "stations.upper_pelvis.rA": 0.702, + "stations.upper_pelvis.rL": 1.08, + "stations.upper_pelvis.rP": 0.504, + "stations.upper_ribcage_shoulder.C.x": 0.0, + "stations.upper_ribcage_shoulder.C.y": 1.95, + "stations.upper_ribcage_shoulder.C.z": 0.0, + "stations.upper_ribcage_shoulder.rA": 0.81, + "stations.upper_ribcage_shoulder.rL": 1.2, + "stations.upper_ribcage_shoulder.rP": 0.63, + "stations.waist_abdomen.C.x": 0.0, + "stations.waist_abdomen.C.y": 0.5, + "stations.waist_abdomen.C.z": 0.0, + "stations.waist_abdomen.rA": 0.45, + "stations.waist_abdomen.rL": 0.7, + "stations.waist_abdomen.rP": 0.36 + }, + "id": "slender_long_limb", + "provenance": { + "bindings": { + "left": { + "centre": { + "derivation": "profile.world-part-plus-thigh-start.v1", + "profile_pointers": [ + "/profiles/3/part_placements/main|part||pelvis/0", + "/profiles/3/part_placements/main|part||pelvis/1", + "/profiles/3/part_placements/main|part||pelvis/2", + "/profiles/3/part_placements/main|part|left|thigh/0", + "/profiles/3/part_placements/main|part|left|thigh/1", + "/profiles/3/part_placements/main|part|left|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/10/placement/translation/0", + "/body/parts/10/placement/translation/1", + "/body/parts/10/placement/translation/2", + "/body/landmarks/14/position/0", + "/body/landmarks/14/position/1", + "/body/landmarks/14/position/2" + ] + }, + "frame": { + "interpretation": "identity frame admitted; no rig or joint resolution", + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "source_pointers": [ + "/body/frames/8/transform" + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "joint_hint": { + "distal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "interpretation": "source hint retained for provenance; not interpreted as a solved skeleton", + "proximal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "source_pointer": "/body/joints/9" + }, + "knee": { + "derivation": "profile.world-part-plus-source-knee.v1", + "profile_pointers": [ + "/profiles/3/part_placements/main|part||pelvis/0", + "/profiles/3/part_placements/main|part||pelvis/1", + "/profiles/3/part_placements/main|part||pelvis/2", + "/profiles/3/part_placements/main|part|left|thigh/0", + "/profiles/3/part_placements/main|part|left|thigh/1", + "/profiles/3/part_placements/main|part|left|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/10/placement/translation/0", + "/body/parts/10/placement/translation/1", + "/body/parts/10/placement/translation/2", + "/body/landmarks/16/position/0", + "/body/landmarks/16/position/1", + "/body/landmarks/16/position/2" + ] + } + }, + "right": { + "centre": { + "derivation": "profile.world-part-plus-thigh-start.v1", + "profile_pointers": [ + "/profiles/3/part_placements/main|part||pelvis/0", + "/profiles/3/part_placements/main|part||pelvis/1", + "/profiles/3/part_placements/main|part||pelvis/2", + "/profiles/3/part_placements/main|part|right|thigh/0", + "/profiles/3/part_placements/main|part|right|thigh/1", + "/profiles/3/part_placements/main|part|right|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/13/placement/translation/0", + "/body/parts/13/placement/translation/1", + "/body/parts/13/placement/translation/2", + "/body/landmarks/19/position/0", + "/body/landmarks/19/position/1", + "/body/landmarks/19/position/2" + ] + }, + "frame": { + "interpretation": "identity frame admitted; no rig or joint resolution", + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "source_pointers": [ + "/body/frames/10/transform" + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "joint_hint": { + "distal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "interpretation": "source hint retained for provenance; not interpreted as a solved skeleton", + "proximal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "source_pointer": "/body/joints/12" + }, + "knee": { + "derivation": "profile.world-part-plus-source-knee.v1", + "profile_pointers": [ + "/profiles/3/part_placements/main|part||pelvis/0", + "/profiles/3/part_placements/main|part||pelvis/1", + "/profiles/3/part_placements/main|part||pelvis/2", + "/profiles/3/part_placements/main|part|right|thigh/0", + "/profiles/3/part_placements/main|part|right|thigh/1", + "/profiles/3/part_placements/main|part|right|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/13/placement/translation/0", + "/body/parts/13/placement/translation/1", + "/body/parts/13/placement/translation/2", + "/body/landmarks/21/position/0", + "/body/landmarks/21/position/1", + "/body/landmarks/21/position/2" + ] + } + } + }, + "claim": "unchanged exact-five profile projection; no geometry executed", + "profile": { + "path": "experiments/current-form-surface-preview/structural_profile_candidates.json", + "profile_id": "slender_long_limb", + "profile_index": 3, + "sha256": "a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640" + }, + "source": { + "path": "examples/body-documents/stylized-digitigrade-biped-authored-form.json", + "sha256": "82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14" + } + }, + "role": "exactfive_unchanged_profileprojection" + }, + { + "attachments": { + "left": { + "centre": [ + -1.0, + -1.0, + 0.0 + ], + "knee": [ + -1.0, + -2.0, + 0.0 + ] + }, + "right": { + "centre": [ + 1.0, + -1.0, + 0.0 + ], + "knee": [ + 1.0, + -2.0, + 0.0 + ] + } + }, + "components": { + "hips.left.P_s.x": -1.0, + "hips.left.P_s.y": -1.0, + "hips.left.P_s.z": 0.0, + "hips.left.r_x": 0.358, + "hips.left.r_y": 0.314, + "hips.left.r_z": 0.336, + "hips.right.P_s.x": 1.0, + "hips.right.P_s.y": -1.0, + "hips.right.P_s.z": 0.0, + "hips.right.r_x": 0.358, + "hips.right.r_y": 0.314, + "hips.right.r_z": 0.336, + "shoulders.left.arm_origin.x": -3.0, + "shoulders.left.arm_origin.y": 2.0, + "shoulders.left.arm_origin.z": 0.0, + "shoulders.left.axilla.x": -3.1, + "shoulders.left.axilla.y": 1.7, + "shoulders.left.axilla.z": 0.0, + "shoulders.left.peak.x": -3.1, + "shoulders.left.peak.y": 2.15, + "shoulders.left.peak.z": 0.0, + "shoulders.left.shoulder_depth": 0.42, + "shoulders.left.start_forward": 0.368, + "shoulders.left.start_lateral": 0.402, + "shoulders.left.start_up": 0.345, + "shoulders.right.arm_origin.x": 3.0, + "shoulders.right.arm_origin.y": 2.0, + "shoulders.right.arm_origin.z": 0.0, + "shoulders.right.axilla.x": 3.1, + "shoulders.right.axilla.y": 1.7, + "shoulders.right.axilla.z": 0.0, + "shoulders.right.peak.x": 3.1, + "shoulders.right.peak.y": 2.15, + "shoulders.right.peak.z": 0.0, + "shoulders.right.shoulder_depth": 0.42, + "shoulders.right.start_forward": 0.368, + "shoulders.right.start_lateral": 0.402, + "shoulders.right.start_up": 0.345, + "stations.lower_abdomen.C.x": 0.0, + "stations.lower_abdomen.C.y": 0.25, + "stations.lower_abdomen.C.z": 0.0, + "stations.lower_abdomen.rA": 0.762, + "stations.lower_abdomen.rL": 1.462, + "stations.lower_abdomen.rP": 0.605, + "stations.lower_pelvis.C.x": 0.0, + "stations.lower_pelvis.C.y": -0.45, + "stations.lower_pelvis.C.z": 0.0, + "stations.lower_pelvis.rA": 0.952, + "stations.lower_pelvis.rL": 1.95, + "stations.lower_pelvis.rP": 0.672, + "stations.lower_ribcage.C.x": 0.0, + "stations.lower_ribcage.C.y": 1.05, + "stations.lower_ribcage.C.z": 0.0, + "stations.lower_ribcage.rA": 0.98, + "stations.lower_ribcage.rL": 1.885, + "stations.lower_ribcage.rP": 0.756, + "stations.neck_collar.C.x": 0.0, + "stations.neck_collar.C.y": 2.15, + "stations.neck_collar.C.z": 0.0, + "stations.neck_collar.rA": 0.46, + "stations.neck_collar.rL": 0.483, + "stations.neck_collar.rP": 0.46, + "stations.neck_upper.C.x": 0.0, + "stations.neck_upper.C.y": 2.55, + "stations.neck_upper.C.z": 0.0, + "stations.neck_upper.rA": 0.38, + "stations.neck_upper.rL": 0.391, + "stations.neck_upper.rP": 0.38, + "stations.upper_abdomen.C.x": 0.0, + "stations.upper_abdomen.C.y": 0.8, + "stations.upper_abdomen.C.z": 0.0, + "stations.upper_abdomen.rA": 0.812, + "stations.upper_abdomen.rL": 1.592, + "stations.upper_abdomen.rP": 0.627, + "stations.upper_pelvis.C.x": 0.0, + "stations.upper_pelvis.C.y": -0.2, + "stations.upper_pelvis.C.z": 0.0, + "stations.upper_pelvis.rA": 0.874, + "stations.upper_pelvis.rL": 1.755, + "stations.upper_pelvis.rP": 0.627, + "stations.upper_ribcage_shoulder.C.x": 0.0, + "stations.upper_ribcage_shoulder.C.y": 1.95, + "stations.upper_ribcage_shoulder.C.z": 0.0, + "stations.upper_ribcage_shoulder.rA": 1.008, + "stations.upper_ribcage_shoulder.rL": 1.95, + "stations.upper_ribcage_shoulder.rP": 0.784, + "stations.waist_abdomen.C.x": 0.0, + "stations.waist_abdomen.C.y": 0.5, + "stations.waist_abdomen.C.z": 0.0, + "stations.waist_abdomen.rA": 0.56, + "stations.waist_abdomen.rL": 1.138, + "stations.waist_abdomen.rP": 0.448 + }, + "id": "stocky_broad_chested", + "provenance": { + "bindings": { + "left": { + "centre": { + "derivation": "profile.world-part-plus-thigh-start.v1", + "profile_pointers": [ + "/profiles/4/part_placements/main|part||pelvis/0", + "/profiles/4/part_placements/main|part||pelvis/1", + "/profiles/4/part_placements/main|part||pelvis/2", + "/profiles/4/part_placements/main|part|left|thigh/0", + "/profiles/4/part_placements/main|part|left|thigh/1", + "/profiles/4/part_placements/main|part|left|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/10/placement/translation/0", + "/body/parts/10/placement/translation/1", + "/body/parts/10/placement/translation/2", + "/body/landmarks/14/position/0", + "/body/landmarks/14/position/1", + "/body/landmarks/14/position/2" + ] + }, + "frame": { + "interpretation": "identity frame admitted; no rig or joint resolution", + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "source_pointers": [ + "/body/frames/8/transform" + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "joint_hint": { + "distal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "interpretation": "source hint retained for provenance; not interpreted as a solved skeleton", + "proximal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "source_pointer": "/body/joints/9" + }, + "knee": { + "derivation": "profile.world-part-plus-source-knee.v1", + "profile_pointers": [ + "/profiles/4/part_placements/main|part||pelvis/0", + "/profiles/4/part_placements/main|part||pelvis/1", + "/profiles/4/part_placements/main|part||pelvis/2", + "/profiles/4/part_placements/main|part|left|thigh/0", + "/profiles/4/part_placements/main|part|left|thigh/1", + "/profiles/4/part_placements/main|part|left|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/10/placement/translation/0", + "/body/parts/10/placement/translation/1", + "/body/parts/10/placement/translation/2", + "/body/landmarks/16/position/0", + "/body/landmarks/16/position/1", + "/body/landmarks/16/position/2" + ] + } + }, + "right": { + "centre": { + "derivation": "profile.world-part-plus-thigh-start.v1", + "profile_pointers": [ + "/profiles/4/part_placements/main|part||pelvis/0", + "/profiles/4/part_placements/main|part||pelvis/1", + "/profiles/4/part_placements/main|part||pelvis/2", + "/profiles/4/part_placements/main|part|right|thigh/0", + "/profiles/4/part_placements/main|part|right|thigh/1", + "/profiles/4/part_placements/main|part|right|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/13/placement/translation/0", + "/body/parts/13/placement/translation/1", + "/body/parts/13/placement/translation/2", + "/body/landmarks/19/position/0", + "/body/landmarks/19/position/1", + "/body/landmarks/19/position/2" + ] + }, + "frame": { + "interpretation": "identity frame admitted; no rig or joint resolution", + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "source_pointers": [ + "/body/frames/10/transform" + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "joint_hint": { + "distal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "interpretation": "source hint retained for provenance; not interpreted as a solved skeleton", + "proximal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "source_pointer": "/body/joints/12" + }, + "knee": { + "derivation": "profile.world-part-plus-source-knee.v1", + "profile_pointers": [ + "/profiles/4/part_placements/main|part||pelvis/0", + "/profiles/4/part_placements/main|part||pelvis/1", + "/profiles/4/part_placements/main|part||pelvis/2", + "/profiles/4/part_placements/main|part|right|thigh/0", + "/profiles/4/part_placements/main|part|right|thigh/1", + "/profiles/4/part_placements/main|part|right|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/13/placement/translation/0", + "/body/parts/13/placement/translation/1", + "/body/parts/13/placement/translation/2", + "/body/landmarks/21/position/0", + "/body/landmarks/21/position/1", + "/body/landmarks/21/position/2" + ] + } + } + }, + "claim": "unchanged exact-five profile projection; no geometry executed", + "profile": { + "path": "experiments/current-form-surface-preview/structural_profile_candidates.json", + "profile_id": "stocky_broad_chested", + "profile_index": 4, + "sha256": "a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640" + }, + "source": { + "path": "examples/body-documents/stylized-digitigrade-biped-authored-form.json", + "sha256": "82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14" + } + }, + "role": "exactfive_unchanged_profileprojection" + }, + { + "attachments": { + "left": { + "centre": [ + -0.105, + -0.16, + 0.0 + ], + "knee": [ + -0.105, + -0.59, + 0.0 + ] + }, + "right": { + "centre": [ + 0.105, + -0.16, + 0.0 + ], + "knee": [ + 0.105, + -0.59, + 0.0 + ] + } + }, + "components": { + "hips.left.P_s.x": -0.105, + "hips.left.P_s.y": -0.16, + "hips.left.P_s.z": 0.0, + "hips.left.r_x": 0.085, + "hips.left.r_y": 0.085, + "hips.left.r_z": 0.09, + "hips.right.P_s.x": 0.105, + "hips.right.P_s.y": -0.16, + "hips.right.P_s.z": 0.0, + "hips.right.r_x": 0.085, + "hips.right.r_y": 0.085, + "hips.right.r_z": 0.09, + "shoulders.left.arm_origin.x": -0.16, + "shoulders.left.arm_origin.y": 0.32, + "shoulders.left.arm_origin.z": 0.0, + "shoulders.left.axilla.x": -0.17600000000000002, + "shoulders.left.axilla.y": 0.272, + "shoulders.left.axilla.z": 0.0, + "shoulders.left.peak.x": -0.17600000000000002, + "shoulders.left.peak.y": 0.344, + "shoulders.left.peak.z": 0.0, + "shoulders.left.shoulder_depth": 0.055999999999999994, + "shoulders.left.start_forward": 0.0512, + "shoulders.left.start_lateral": 0.055999999999999994, + "shoulders.left.start_up": 0.048, + "shoulders.right.arm_origin.x": 0.16, + "shoulders.right.arm_origin.y": 0.32, + "shoulders.right.arm_origin.z": 0.0, + "shoulders.right.axilla.x": 0.17600000000000002, + "shoulders.right.axilla.y": 0.272, + "shoulders.right.axilla.z": 0.0, + "shoulders.right.peak.x": 0.17600000000000002, + "shoulders.right.peak.y": 0.344, + "shoulders.right.peak.z": 0.0, + "shoulders.right.shoulder_depth": 0.055999999999999994, + "shoulders.right.start_forward": 0.0512, + "shoulders.right.start_lateral": 0.055999999999999994, + "shoulders.right.start_up": 0.048, + "stations.lower_abdomen.C.x": 0.0, + "stations.lower_abdomen.C.y": 0.04, + "stations.lower_abdomen.C.z": 0.0, + "stations.lower_abdomen.rA": 0.09, + "stations.lower_abdomen.rL": 0.135, + "stations.lower_abdomen.rP": 0.09, + "stations.lower_pelvis.C.x": 0.0, + "stations.lower_pelvis.C.y": -0.072, + "stations.lower_pelvis.C.z": 0.0, + "stations.lower_pelvis.rA": 0.105, + "stations.lower_pelvis.rL": 0.18, + "stations.lower_pelvis.rP": 0.12, + "stations.lower_ribcage.C.x": 0.0, + "stations.lower_ribcage.C.y": 0.168, + "stations.lower_ribcage.C.z": 0.0, + "stations.lower_ribcage.rA": 0.14, + "stations.lower_ribcage.rL": 0.23199999999999998, + "stations.lower_ribcage.rP": 0.10800000000000001, + "stations.neck_collar.C.x": 0.0, + "stations.neck_collar.C.y": 0.344, + "stations.neck_collar.C.z": 0.0, + "stations.neck_collar.rA": 0.064, + "stations.neck_collar.rL": 0.0672, + "stations.neck_collar.rP": 0.064, + "stations.neck_upper.C.x": 0.0, + "stations.neck_upper.C.y": 0.408, + "stations.neck_upper.C.z": 0.0, + "stations.neck_upper.rA": 0.05280000000000001, + "stations.neck_upper.rL": 0.054400000000000004, + "stations.neck_upper.rP": 0.05280000000000001, + "stations.upper_abdomen.C.x": 0.0, + "stations.upper_abdomen.C.y": 0.128, + "stations.upper_abdomen.C.z": 0.0, + "stations.upper_abdomen.rA": 0.11599999999999999, + "stations.upper_abdomen.rL": 0.196, + "stations.upper_abdomen.rP": 0.08960000000000001, + "stations.upper_pelvis.C.x": 0.0, + "stations.upper_pelvis.C.y": -0.032, + "stations.upper_pelvis.C.z": 0.0, + "stations.upper_pelvis.rA": 0.1, + "stations.upper_pelvis.rL": 0.16, + "stations.upper_pelvis.rP": 0.105, + "stations.upper_ribcage_shoulder.C.x": 0.0, + "stations.upper_ribcage_shoulder.C.y": 0.312, + "stations.upper_ribcage_shoulder.C.z": 0.0, + "stations.upper_ribcage_shoulder.rA": 0.14400000000000002, + "stations.upper_ribcage_shoulder.rL": 0.24, + "stations.upper_ribcage_shoulder.rP": 0.11199999999999999, + "stations.waist_abdomen.C.x": 0.0, + "stations.waist_abdomen.C.y": 0.08, + "stations.waist_abdomen.C.z": 0.0, + "stations.waist_abdomen.rA": 0.08, + "stations.waist_abdomen.rL": 0.12, + "stations.waist_abdomen.rP": 0.075 + }, + "id": "ordinary_human_reference", + "provenance": { + "authoritative_input_path": "experiments/pelvis-thigh-transition/inputs.json", + "bindings": { + "left": { + "centre": { + "derivation": "inputs.json.case-override.v1", + "profile_pointers": [], + "source_pointers": [ + "/cases/5/attachments/left/centre" + ] + }, + "knee": { + "derivation": "inputs.json.case-override.v1", + "profile_pointers": [], + "source_pointers": [ + "/cases/5/attachments/left/knee" + ] + } + }, + "right": { + "centre": { + "derivation": "inputs.json.case-override.v1", + "profile_pointers": [], + "source_pointers": [ + "/cases/5/attachments/right/centre" + ] + }, + "knee": { + "derivation": "inputs.json.case-override.v1", + "profile_pointers": [], + "source_pointers": [ + "/cases/5/attachments/right/knee" + ] + } + } + }, + "claim": "synthetic adult coarse pelvic proportions; not anatomical measured truth or a whole-body fixture", + "frame": { + "interpretation": "identity local pelvis frame; no rig or joint resolution", + "rotation_xyzw": [ + 0.0, + 0.0, + 0.0, + 1.0 + ], + "translation": [ + 0.0, + 0.0, + 0.0 + ] + }, + "override_authority": "literal /cases/5/attachments/* pointers and numeric component overrides in this file; source/profile are only uniformly scaled base context", + "profile": { + "base_case": "standard_neutral_reference", + "path": "experiments/current-form-surface-preview/structural_profile_candidates.json", + "sha256": "a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640", + "uniform_scale": 0.16 + }, + "source": { + "path": "examples/body-documents/stylized-digitigrade-biped-authored-form.json", + "sha256": "82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14" + } + }, + "role": "executable_cross_family_challenge" + }, + { + "attachments": { + "left": { + "centre": [ + -1.0, + -1.0, + 0.0 + ], + "knee": [ + -1.0, + -2.0, + 0.0 + ] + }, + "right": { + "centre": [ + 1.0, + -1.0, + 0.0 + ], + "knee": [ + 1.0, + -2.0, + 0.0 + ] + } + }, + "components": { + "hips.left.P_s.x": -1.0, + "hips.left.P_s.y": -1.0, + "hips.left.P_s.z": 0.0, + "hips.left.r_x": 0.32, + "hips.left.r_y": 0.28, + "hips.left.r_z": 0.3, + "hips.right.P_s.x": 1.0, + "hips.right.P_s.y": -1.0, + "hips.right.P_s.z": 0.0, + "hips.right.r_x": 0.32, + "hips.right.r_y": 0.28, + "hips.right.r_z": 0.3, + "shoulders.left.arm_origin.x": -1.0, + "shoulders.left.arm_origin.y": 2.0, + "shoulders.left.arm_origin.z": 0.0, + "shoulders.left.axilla.x": -1.1, + "shoulders.left.axilla.y": 1.7, + "shoulders.left.axilla.z": 0.0, + "shoulders.left.peak.x": -1.1, + "shoulders.left.peak.y": 2.15, + "shoulders.left.peak.z": 0.0, + "shoulders.left.shoulder_depth": 0.35, + "shoulders.left.start_forward": 0.32, + "shoulders.left.start_lateral": 0.35, + "shoulders.left.start_up": 0.3, + "shoulders.right.arm_origin.x": 1.0, + "shoulders.right.arm_origin.y": 2.0, + "shoulders.right.arm_origin.z": 0.0, + "shoulders.right.axilla.x": 1.1, + "shoulders.right.axilla.y": 1.7, + "shoulders.right.axilla.z": 0.0, + "shoulders.right.peak.x": 1.1, + "shoulders.right.peak.y": 2.15, + "shoulders.right.peak.z": 0.0, + "shoulders.right.shoulder_depth": 0.35, + "shoulders.right.start_forward": 0.32, + "shoulders.right.start_lateral": 0.35, + "shoulders.right.start_up": 0.3, + "stations.lower_abdomen.C.x": 0.0, + "stations.lower_abdomen.C.y": 0.25, + "stations.lower_abdomen.C.z": 0.0, + "stations.lower_abdomen.rA": 0.68, + "stations.lower_abdomen.rL": 1.125, + "stations.lower_abdomen.rP": 0.54, + "stations.lower_pelvis.C.x": 0.0, + "stations.lower_pelvis.C.y": -0.45, + "stations.lower_pelvis.C.z": 0.0, + "stations.lower_pelvis.rA": 0.85, + "stations.lower_pelvis.rL": 1.6500000000000001, + "stations.lower_pelvis.rP": 0.6, + "stations.lower_ribcage.C.x": 0.0, + "stations.lower_ribcage.C.y": 1.05, + "stations.lower_ribcage.C.z": 0.0, + "stations.lower_ribcage.rA": 0.875, + "stations.lower_ribcage.rL": 1.45, + "stations.lower_ribcage.rP": 0.675, + "stations.neck_collar.C.x": 0.0, + "stations.neck_collar.C.y": 2.15, + "stations.neck_collar.C.z": 0.0, + "stations.neck_collar.rA": 0.4, + "stations.neck_collar.rL": 0.42, + "stations.neck_collar.rP": 0.4, + "stations.neck_upper.C.x": 0.0, + "stations.neck_upper.C.y": 2.55, + "stations.neck_upper.C.z": 0.0, + "stations.neck_upper.rA": 0.33, + "stations.neck_upper.rL": 0.34, + "stations.neck_upper.rP": 0.33, + "stations.upper_abdomen.C.x": 0.0, + "stations.upper_abdomen.C.y": 0.8, + "stations.upper_abdomen.C.z": 0.0, + "stations.upper_abdomen.rA": 0.725, + "stations.upper_abdomen.rL": 1.225, + "stations.upper_abdomen.rP": 0.56, + "stations.upper_pelvis.C.x": 0.0, + "stations.upper_pelvis.C.y": -0.2, + "stations.upper_pelvis.C.z": 0.0, + "stations.upper_pelvis.rA": 0.78, + "stations.upper_pelvis.rL": 1.4850000000000003, + "stations.upper_pelvis.rP": 0.56, + "stations.upper_ribcage_shoulder.C.x": 0.0, + "stations.upper_ribcage_shoulder.C.y": 1.95, + "stations.upper_ribcage_shoulder.C.z": 0.0, + "stations.upper_ribcage_shoulder.rA": 0.9, + "stations.upper_ribcage_shoulder.rL": 1.5, + "stations.upper_ribcage_shoulder.rP": 0.7, + "stations.waist_abdomen.C.x": 0.0, + "stations.waist_abdomen.C.y": 0.5, + "stations.waist_abdomen.C.z": 0.0, + "stations.waist_abdomen.rA": 0.5, + "stations.waist_abdomen.rL": 0.875, + "stations.waist_abdomen.rP": 0.4 + }, + "id": "neutral_pelvis_width_plus_10pct", + "provenance": { + "bindings": { + "left": { + "centre": { + "derivation": "profile.world-part-plus-thigh-start.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|left|thigh/0", + "/profiles/0/part_placements/main|part|left|thigh/1", + "/profiles/0/part_placements/main|part|left|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/10/placement/translation/0", + "/body/parts/10/placement/translation/1", + "/body/parts/10/placement/translation/2", + "/body/landmarks/14/position/0", + "/body/landmarks/14/position/1", + "/body/landmarks/14/position/2" + ] + }, + "frame": { + "interpretation": "identity frame admitted; no rig or joint resolution", + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "source_pointers": [ + "/body/frames/8/transform" + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "joint_hint": { + "distal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "interpretation": "source hint retained for provenance; not interpreted as a solved skeleton", + "proximal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "source_pointer": "/body/joints/9" + }, + "knee": { + "derivation": "profile.world-part-plus-source-knee.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|left|thigh/0", + "/profiles/0/part_placements/main|part|left|thigh/1", + "/profiles/0/part_placements/main|part|left|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/10/placement/translation/0", + "/body/parts/10/placement/translation/1", + "/body/parts/10/placement/translation/2", + "/body/landmarks/16/position/0", + "/body/landmarks/16/position/1", + "/body/landmarks/16/position/2" + ] + } + }, + "right": { + "centre": { + "derivation": "profile.world-part-plus-thigh-start.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|right|thigh/0", + "/profiles/0/part_placements/main|part|right|thigh/1", + "/profiles/0/part_placements/main|part|right|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/13/placement/translation/0", + "/body/parts/13/placement/translation/1", + "/body/parts/13/placement/translation/2", + "/body/landmarks/19/position/0", + "/body/landmarks/19/position/1", + "/body/landmarks/19/position/2" + ] + }, + "frame": { + "interpretation": "identity frame admitted; no rig or joint resolution", + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "source_pointers": [ + "/body/frames/10/transform" + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "joint_hint": { + "distal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "interpretation": "source hint retained for provenance; not interpreted as a solved skeleton", + "proximal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "source_pointer": "/body/joints/12" + }, + "knee": { + "derivation": "profile.world-part-plus-source-knee.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|right|thigh/0", + "/profiles/0/part_placements/main|part|right|thigh/1", + "/profiles/0/part_placements/main|part|right|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/13/placement/translation/0", + "/body/parts/13/placement/translation/1", + "/body/parts/13/placement/translation/2", + "/body/landmarks/21/position/0", + "/body/landmarks/21/position/1", + "/body/landmarks/21/position/2" + ] + } + } + }, + "claim": "numeric perturbation declaration only; no geometry executed", + "expected_change": { + "direction": "pelvic lower/upper lateral radii increase" + }, + "profile": { + "base_case": "standard_neutral_reference", + "path": "experiments/current-form-surface-preview/structural_profile_candidates.json", + "sha256": "a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640" + }, + "source": { + "path": "examples/body-documents/stylized-digitigrade-biped-authored-form.json", + "sha256": "82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14" + } + }, + "role": "predeclared_neutral_perturbation" + }, + { + "attachments": { + "left": { + "centre": [ + -1.05, + -1.0, + 0.0 + ], + "knee": [ + -1.05, + -2.0, + 0.0 + ] + }, + "right": { + "centre": [ + 1.0, + -1.0, + 0.0 + ], + "knee": [ + 1.0, + -2.0, + 0.0 + ] + } + }, + "components": { + "hips.left.P_s.x": -1.05, + "hips.left.P_s.y": -1.0, + "hips.left.P_s.z": 0.0, + "hips.left.r_x": 0.32, + "hips.left.r_y": 0.28, + "hips.left.r_z": 0.3, + "hips.right.P_s.x": 1.0, + "hips.right.P_s.y": -1.0, + "hips.right.P_s.z": 0.0, + "hips.right.r_x": 0.32, + "hips.right.r_y": 0.28, + "hips.right.r_z": 0.3, + "shoulders.left.arm_origin.x": -1.0, + "shoulders.left.arm_origin.y": 2.0, + "shoulders.left.arm_origin.z": 0.0, + "shoulders.left.axilla.x": -1.1, + "shoulders.left.axilla.y": 1.7, + "shoulders.left.axilla.z": 0.0, + "shoulders.left.peak.x": -1.1, + "shoulders.left.peak.y": 2.15, + "shoulders.left.peak.z": 0.0, + "shoulders.left.shoulder_depth": 0.35, + "shoulders.left.start_forward": 0.32, + "shoulders.left.start_lateral": 0.35, + "shoulders.left.start_up": 0.3, + "shoulders.right.arm_origin.x": 1.0, + "shoulders.right.arm_origin.y": 2.0, + "shoulders.right.arm_origin.z": 0.0, + "shoulders.right.axilla.x": 1.1, + "shoulders.right.axilla.y": 1.7, + "shoulders.right.axilla.z": 0.0, + "shoulders.right.peak.x": 1.1, + "shoulders.right.peak.y": 2.15, + "shoulders.right.peak.z": 0.0, + "shoulders.right.shoulder_depth": 0.35, + "shoulders.right.start_forward": 0.32, + "shoulders.right.start_lateral": 0.35, + "shoulders.right.start_up": 0.3, + "stations.lower_abdomen.C.x": 0.0, + "stations.lower_abdomen.C.y": 0.25, + "stations.lower_abdomen.C.z": 0.0, + "stations.lower_abdomen.rA": 0.68, + "stations.lower_abdomen.rL": 1.125, + "stations.lower_abdomen.rP": 0.54, + "stations.lower_pelvis.C.x": 0.0, + "stations.lower_pelvis.C.y": -0.45, + "stations.lower_pelvis.C.z": 0.0, + "stations.lower_pelvis.rA": 0.85, + "stations.lower_pelvis.rL": 1.5, + "stations.lower_pelvis.rP": 0.6, + "stations.lower_ribcage.C.x": 0.0, + "stations.lower_ribcage.C.y": 1.05, + "stations.lower_ribcage.C.z": 0.0, + "stations.lower_ribcage.rA": 0.875, + "stations.lower_ribcage.rL": 1.45, + "stations.lower_ribcage.rP": 0.675, + "stations.neck_collar.C.x": 0.0, + "stations.neck_collar.C.y": 2.15, + "stations.neck_collar.C.z": 0.0, + "stations.neck_collar.rA": 0.4, + "stations.neck_collar.rL": 0.42, + "stations.neck_collar.rP": 0.4, + "stations.neck_upper.C.x": 0.0, + "stations.neck_upper.C.y": 2.55, + "stations.neck_upper.C.z": 0.0, + "stations.neck_upper.rA": 0.33, + "stations.neck_upper.rL": 0.34, + "stations.neck_upper.rP": 0.33, + "stations.upper_abdomen.C.x": 0.0, + "stations.upper_abdomen.C.y": 0.8, + "stations.upper_abdomen.C.z": 0.0, + "stations.upper_abdomen.rA": 0.725, + "stations.upper_abdomen.rL": 1.225, + "stations.upper_abdomen.rP": 0.56, + "stations.upper_pelvis.C.x": 0.0, + "stations.upper_pelvis.C.y": -0.2, + "stations.upper_pelvis.C.z": 0.0, + "stations.upper_pelvis.rA": 0.78, + "stations.upper_pelvis.rL": 1.35, + "stations.upper_pelvis.rP": 0.56, + "stations.upper_ribcage_shoulder.C.x": 0.0, + "stations.upper_ribcage_shoulder.C.y": 1.95, + "stations.upper_ribcage_shoulder.C.z": 0.0, + "stations.upper_ribcage_shoulder.rA": 0.9, + "stations.upper_ribcage_shoulder.rL": 1.5, + "stations.upper_ribcage_shoulder.rP": 0.7, + "stations.waist_abdomen.C.x": 0.0, + "stations.waist_abdomen.C.y": 0.5, + "stations.waist_abdomen.C.z": 0.0, + "stations.waist_abdomen.rA": 0.5, + "stations.waist_abdomen.rL": 0.875, + "stations.waist_abdomen.rP": 0.4 + }, + "id": "neutral_left_spacing_minus_005", + "provenance": { + "bindings": { + "left": { + "centre": { + "derivation": "profile.world-part-plus-thigh-start.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|left|thigh/0", + "/profiles/0/part_placements/main|part|left|thigh/1", + "/profiles/0/part_placements/main|part|left|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/10/placement/translation/0", + "/body/parts/10/placement/translation/1", + "/body/parts/10/placement/translation/2", + "/body/landmarks/14/position/0", + "/body/landmarks/14/position/1", + "/body/landmarks/14/position/2" + ] + }, + "frame": { + "interpretation": "identity frame admitted; no rig or joint resolution", + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "source_pointers": [ + "/body/frames/8/transform" + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "joint_hint": { + "distal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "interpretation": "source hint retained for provenance; not interpreted as a solved skeleton", + "proximal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "source_pointer": "/body/joints/9" + }, + "knee": { + "derivation": "profile.world-part-plus-source-knee.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|left|thigh/0", + "/profiles/0/part_placements/main|part|left|thigh/1", + "/profiles/0/part_placements/main|part|left|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/10/placement/translation/0", + "/body/parts/10/placement/translation/1", + "/body/parts/10/placement/translation/2", + "/body/landmarks/16/position/0", + "/body/landmarks/16/position/1", + "/body/landmarks/16/position/2" + ] + } + }, + "right": { + "centre": { + "derivation": "profile.world-part-plus-thigh-start.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|right|thigh/0", + "/profiles/0/part_placements/main|part|right|thigh/1", + "/profiles/0/part_placements/main|part|right|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/13/placement/translation/0", + "/body/parts/13/placement/translation/1", + "/body/parts/13/placement/translation/2", + "/body/landmarks/19/position/0", + "/body/landmarks/19/position/1", + "/body/landmarks/19/position/2" + ] + }, + "frame": { + "interpretation": "identity frame admitted; no rig or joint resolution", + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "source_pointers": [ + "/body/frames/10/transform" + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "joint_hint": { + "distal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "interpretation": "source hint retained for provenance; not interpreted as a solved skeleton", + "proximal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "source_pointer": "/body/joints/12" + }, + "knee": { + "derivation": "profile.world-part-plus-source-knee.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|right|thigh/0", + "/profiles/0/part_placements/main|part|right|thigh/1", + "/profiles/0/part_placements/main|part|right|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/13/placement/translation/0", + "/body/parts/13/placement/translation/1", + "/body/parts/13/placement/translation/2", + "/body/landmarks/21/position/0", + "/body/landmarks/21/position/1", + "/body/landmarks/21/position/2" + ] + } + } + }, + "claim": "numeric perturbation declaration only; no geometry executed", + "expected_change": { + "direction": "left hip, knee and thigh start translate -x by 0.05" + }, + "profile": { + "base_case": "standard_neutral_reference", + "path": "experiments/current-form-surface-preview/structural_profile_candidates.json", + "sha256": "a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640" + }, + "source": { + "path": "examples/body-documents/stylized-digitigrade-biped-authored-form.json", + "sha256": "82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14" + } + }, + "role": "predeclared_neutral_perturbation" + }, + { + "attachments": { + "left": { + "centre": [ + -1.0, + -1.0, + 0.0 + ], + "knee": [ + -0.9128442573, + -1.9961946981, + 0.0 + ] + }, + "right": { + "centre": [ + 1.0, + -1.0, + 0.0 + ], + "knee": [ + 1.0, + -2.0, + 0.0 + ] + } + }, + "components": { + "hips.left.P_s.x": -1.0, + "hips.left.P_s.y": -1.0, + "hips.left.P_s.z": 0.0, + "hips.left.r_x": 0.32, + "hips.left.r_y": 0.28, + "hips.left.r_z": 0.3, + "hips.right.P_s.x": 1.0, + "hips.right.P_s.y": -1.0, + "hips.right.P_s.z": 0.0, + "hips.right.r_x": 0.32, + "hips.right.r_y": 0.28, + "hips.right.r_z": 0.3, + "shoulders.left.arm_origin.x": -1.0, + "shoulders.left.arm_origin.y": 2.0, + "shoulders.left.arm_origin.z": 0.0, + "shoulders.left.axilla.x": -1.1, + "shoulders.left.axilla.y": 1.7, + "shoulders.left.axilla.z": 0.0, + "shoulders.left.peak.x": -1.1, + "shoulders.left.peak.y": 2.15, + "shoulders.left.peak.z": 0.0, + "shoulders.left.shoulder_depth": 0.35, + "shoulders.left.start_forward": 0.32, + "shoulders.left.start_lateral": 0.35, + "shoulders.left.start_up": 0.3, + "shoulders.right.arm_origin.x": 1.0, + "shoulders.right.arm_origin.y": 2.0, + "shoulders.right.arm_origin.z": 0.0, + "shoulders.right.axilla.x": 1.1, + "shoulders.right.axilla.y": 1.7, + "shoulders.right.axilla.z": 0.0, + "shoulders.right.peak.x": 1.1, + "shoulders.right.peak.y": 2.15, + "shoulders.right.peak.z": 0.0, + "shoulders.right.shoulder_depth": 0.35, + "shoulders.right.start_forward": 0.32, + "shoulders.right.start_lateral": 0.35, + "shoulders.right.start_up": 0.3, + "stations.lower_abdomen.C.x": 0.0, + "stations.lower_abdomen.C.y": 0.25, + "stations.lower_abdomen.C.z": 0.0, + "stations.lower_abdomen.rA": 0.68, + "stations.lower_abdomen.rL": 1.125, + "stations.lower_abdomen.rP": 0.54, + "stations.lower_pelvis.C.x": 0.0, + "stations.lower_pelvis.C.y": -0.45, + "stations.lower_pelvis.C.z": 0.0, + "stations.lower_pelvis.rA": 0.85, + "stations.lower_pelvis.rL": 1.5, + "stations.lower_pelvis.rP": 0.6, + "stations.lower_ribcage.C.x": 0.0, + "stations.lower_ribcage.C.y": 1.05, + "stations.lower_ribcage.C.z": 0.0, + "stations.lower_ribcage.rA": 0.875, + "stations.lower_ribcage.rL": 1.45, + "stations.lower_ribcage.rP": 0.675, + "stations.neck_collar.C.x": 0.0, + "stations.neck_collar.C.y": 2.15, + "stations.neck_collar.C.z": 0.0, + "stations.neck_collar.rA": 0.4, + "stations.neck_collar.rL": 0.42, + "stations.neck_collar.rP": 0.4, + "stations.neck_upper.C.x": 0.0, + "stations.neck_upper.C.y": 2.55, + "stations.neck_upper.C.z": 0.0, + "stations.neck_upper.rA": 0.33, + "stations.neck_upper.rL": 0.34, + "stations.neck_upper.rP": 0.33, + "stations.upper_abdomen.C.x": 0.0, + "stations.upper_abdomen.C.y": 0.8, + "stations.upper_abdomen.C.z": 0.0, + "stations.upper_abdomen.rA": 0.725, + "stations.upper_abdomen.rL": 1.225, + "stations.upper_abdomen.rP": 0.56, + "stations.upper_pelvis.C.x": 0.0, + "stations.upper_pelvis.C.y": -0.2, + "stations.upper_pelvis.C.z": 0.0, + "stations.upper_pelvis.rA": 0.78, + "stations.upper_pelvis.rL": 1.35, + "stations.upper_pelvis.rP": 0.56, + "stations.upper_ribcage_shoulder.C.x": 0.0, + "stations.upper_ribcage_shoulder.C.y": 1.95, + "stations.upper_ribcage_shoulder.C.z": 0.0, + "stations.upper_ribcage_shoulder.rA": 0.9, + "stations.upper_ribcage_shoulder.rL": 1.5, + "stations.upper_ribcage_shoulder.rP": 0.7, + "stations.waist_abdomen.C.x": 0.0, + "stations.waist_abdomen.C.y": 0.5, + "stations.waist_abdomen.C.z": 0.0, + "stations.waist_abdomen.rA": 0.5, + "stations.waist_abdomen.rL": 0.875, + "stations.waist_abdomen.rP": 0.4 + }, + "id": "neutral_left_direction_tilt_5deg", + "provenance": { + "bindings": { + "left": { + "centre": { + "derivation": "profile.world-part-plus-thigh-start.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|left|thigh/0", + "/profiles/0/part_placements/main|part|left|thigh/1", + "/profiles/0/part_placements/main|part|left|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/10/placement/translation/0", + "/body/parts/10/placement/translation/1", + "/body/parts/10/placement/translation/2", + "/body/landmarks/14/position/0", + "/body/landmarks/14/position/1", + "/body/landmarks/14/position/2" + ] + }, + "frame": { + "interpretation": "identity frame admitted; no rig or joint resolution", + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "source_pointers": [ + "/body/frames/8/transform" + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "joint_hint": { + "distal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "interpretation": "source hint retained for provenance; not interpreted as a solved skeleton", + "proximal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "source_pointer": "/body/joints/9" + }, + "knee": { + "derivation": "profile.world-part-plus-source-knee.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|left|thigh/0", + "/profiles/0/part_placements/main|part|left|thigh/1", + "/profiles/0/part_placements/main|part|left|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/10/placement/translation/0", + "/body/parts/10/placement/translation/1", + "/body/parts/10/placement/translation/2", + "/body/landmarks/16/position/0", + "/body/landmarks/16/position/1", + "/body/landmarks/16/position/2" + ] + } + }, + "right": { + "centre": { + "derivation": "profile.world-part-plus-thigh-start.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|right|thigh/0", + "/profiles/0/part_placements/main|part|right|thigh/1", + "/profiles/0/part_placements/main|part|right|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/13/placement/translation/0", + "/body/parts/13/placement/translation/1", + "/body/parts/13/placement/translation/2", + "/body/landmarks/19/position/0", + "/body/landmarks/19/position/1", + "/body/landmarks/19/position/2" + ] + }, + "frame": { + "interpretation": "identity frame admitted; no rig or joint resolution", + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "source_pointers": [ + "/body/frames/10/transform" + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "joint_hint": { + "distal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "interpretation": "source hint retained for provenance; not interpreted as a solved skeleton", + "proximal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "source_pointer": "/body/joints/12" + }, + "knee": { + "derivation": "profile.world-part-plus-source-knee.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|right|thigh/0", + "/profiles/0/part_placements/main|part|right|thigh/1", + "/profiles/0/part_placements/main|part|right|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/13/placement/translation/0", + "/body/parts/13/placement/translation/1", + "/body/parts/13/placement/translation/2", + "/body/landmarks/21/position/0", + "/body/landmarks/21/position/1", + "/body/landmarks/21/position/2" + ] + } + } + }, + "claim": "numeric perturbation declaration only; no geometry executed", + "expected_change": { + "direction": "left thigh direction tilts 5 degrees inward", + "original_leg_length": 1.0 + }, + "profile": { + "base_case": "standard_neutral_reference", + "path": "experiments/current-form-surface-preview/structural_profile_candidates.json", + "sha256": "a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640" + }, + "source": { + "path": "examples/body-documents/stylized-digitigrade-biped-authored-form.json", + "sha256": "82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14" + } + }, + "role": "predeclared_neutral_perturbation" + }, + { + "attachments": { + "left": { + "centre": [ + -1.0, + -1.0, + 0.05 + ], + "knee": [ + -1.0, + -2.0, + 0.05 + ] + }, + "right": { + "centre": [ + 1.0, + -1.0, + 0.0 + ], + "knee": [ + 1.0, + -2.0, + 0.0 + ] + } + }, + "components": { + "hips.left.P_s.x": -1.0, + "hips.left.P_s.y": -1.0, + "hips.left.P_s.z": 0.05, + "hips.left.r_x": 0.32, + "hips.left.r_y": 0.28, + "hips.left.r_z": 0.3, + "hips.right.P_s.x": 1.0, + "hips.right.P_s.y": -1.0, + "hips.right.P_s.z": 0.0, + "hips.right.r_x": 0.32, + "hips.right.r_y": 0.28, + "hips.right.r_z": 0.3, + "shoulders.left.arm_origin.x": -1.0, + "shoulders.left.arm_origin.y": 2.0, + "shoulders.left.arm_origin.z": 0.0, + "shoulders.left.axilla.x": -1.1, + "shoulders.left.axilla.y": 1.7, + "shoulders.left.axilla.z": 0.0, + "shoulders.left.peak.x": -1.1, + "shoulders.left.peak.y": 2.15, + "shoulders.left.peak.z": 0.0, + "shoulders.left.shoulder_depth": 0.35, + "shoulders.left.start_forward": 0.32, + "shoulders.left.start_lateral": 0.35, + "shoulders.left.start_up": 0.3, + "shoulders.right.arm_origin.x": 1.0, + "shoulders.right.arm_origin.y": 2.0, + "shoulders.right.arm_origin.z": 0.0, + "shoulders.right.axilla.x": 1.1, + "shoulders.right.axilla.y": 1.7, + "shoulders.right.axilla.z": 0.0, + "shoulders.right.peak.x": 1.1, + "shoulders.right.peak.y": 2.15, + "shoulders.right.peak.z": 0.0, + "shoulders.right.shoulder_depth": 0.35, + "shoulders.right.start_forward": 0.32, + "shoulders.right.start_lateral": 0.35, + "shoulders.right.start_up": 0.3, + "stations.lower_abdomen.C.x": 0.0, + "stations.lower_abdomen.C.y": 0.25, + "stations.lower_abdomen.C.z": 0.0, + "stations.lower_abdomen.rA": 0.68, + "stations.lower_abdomen.rL": 1.125, + "stations.lower_abdomen.rP": 0.54, + "stations.lower_pelvis.C.x": 0.0, + "stations.lower_pelvis.C.y": -0.45, + "stations.lower_pelvis.C.z": 0.0, + "stations.lower_pelvis.rA": 0.85, + "stations.lower_pelvis.rL": 1.5, + "stations.lower_pelvis.rP": 0.6, + "stations.lower_ribcage.C.x": 0.0, + "stations.lower_ribcage.C.y": 1.05, + "stations.lower_ribcage.C.z": 0.0, + "stations.lower_ribcage.rA": 0.875, + "stations.lower_ribcage.rL": 1.45, + "stations.lower_ribcage.rP": 0.675, + "stations.neck_collar.C.x": 0.0, + "stations.neck_collar.C.y": 2.15, + "stations.neck_collar.C.z": 0.0, + "stations.neck_collar.rA": 0.4, + "stations.neck_collar.rL": 0.42, + "stations.neck_collar.rP": 0.4, + "stations.neck_upper.C.x": 0.0, + "stations.neck_upper.C.y": 2.55, + "stations.neck_upper.C.z": 0.0, + "stations.neck_upper.rA": 0.33, + "stations.neck_upper.rL": 0.34, + "stations.neck_upper.rP": 0.33, + "stations.upper_abdomen.C.x": 0.0, + "stations.upper_abdomen.C.y": 0.8, + "stations.upper_abdomen.C.z": 0.0, + "stations.upper_abdomen.rA": 0.725, + "stations.upper_abdomen.rL": 1.225, + "stations.upper_abdomen.rP": 0.56, + "stations.upper_pelvis.C.x": 0.0, + "stations.upper_pelvis.C.y": -0.2, + "stations.upper_pelvis.C.z": 0.0, + "stations.upper_pelvis.rA": 0.78, + "stations.upper_pelvis.rL": 1.35, + "stations.upper_pelvis.rP": 0.56, + "stations.upper_ribcage_shoulder.C.x": 0.0, + "stations.upper_ribcage_shoulder.C.y": 1.95, + "stations.upper_ribcage_shoulder.C.z": 0.0, + "stations.upper_ribcage_shoulder.rA": 0.9, + "stations.upper_ribcage_shoulder.rL": 1.5, + "stations.upper_ribcage_shoulder.rP": 0.7, + "stations.waist_abdomen.C.x": 0.0, + "stations.waist_abdomen.C.y": 0.5, + "stations.waist_abdomen.C.z": 0.0, + "stations.waist_abdomen.rA": 0.5, + "stations.waist_abdomen.rL": 0.875, + "stations.waist_abdomen.rP": 0.4 + }, + "id": "neutral_left_front_offset_plus_005", + "provenance": { + "bindings": { + "left": { + "centre": { + "derivation": "profile.world-part-plus-thigh-start.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|left|thigh/0", + "/profiles/0/part_placements/main|part|left|thigh/1", + "/profiles/0/part_placements/main|part|left|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/10/placement/translation/0", + "/body/parts/10/placement/translation/1", + "/body/parts/10/placement/translation/2", + "/body/landmarks/14/position/0", + "/body/landmarks/14/position/1", + "/body/landmarks/14/position/2" + ] + }, + "frame": { + "interpretation": "identity frame admitted; no rig or joint resolution", + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "source_pointers": [ + "/body/frames/8/transform" + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "joint_hint": { + "distal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "interpretation": "source hint retained for provenance; not interpreted as a solved skeleton", + "proximal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "source_pointer": "/body/joints/9" + }, + "knee": { + "derivation": "profile.world-part-plus-source-knee.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|left|thigh/0", + "/profiles/0/part_placements/main|part|left|thigh/1", + "/profiles/0/part_placements/main|part|left|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/10/placement/translation/0", + "/body/parts/10/placement/translation/1", + "/body/parts/10/placement/translation/2", + "/body/landmarks/16/position/0", + "/body/landmarks/16/position/1", + "/body/landmarks/16/position/2" + ] + } + }, + "right": { + "centre": { + "derivation": "profile.world-part-plus-thigh-start.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|right|thigh/0", + "/profiles/0/part_placements/main|part|right|thigh/1", + "/profiles/0/part_placements/main|part|right|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/13/placement/translation/0", + "/body/parts/13/placement/translation/1", + "/body/parts/13/placement/translation/2", + "/body/landmarks/19/position/0", + "/body/landmarks/19/position/1", + "/body/landmarks/19/position/2" + ] + }, + "frame": { + "interpretation": "identity frame admitted; no rig or joint resolution", + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "source_pointers": [ + "/body/frames/10/transform" + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "joint_hint": { + "distal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "interpretation": "source hint retained for provenance; not interpreted as a solved skeleton", + "proximal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "source_pointer": "/body/joints/12" + }, + "knee": { + "derivation": "profile.world-part-plus-source-knee.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|right|thigh/0", + "/profiles/0/part_placements/main|part|right|thigh/1", + "/profiles/0/part_placements/main|part|right|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/13/placement/translation/0", + "/body/parts/13/placement/translation/1", + "/body/parts/13/placement/translation/2", + "/body/landmarks/21/position/0", + "/body/landmarks/21/position/1", + "/body/landmarks/21/position/2" + ] + } + } + }, + "claim": "numeric perturbation declaration only; no geometry executed", + "expected_change": { + "direction": "left hip, knee and thigh start translate +z by 0.05" + }, + "profile": { + "base_case": "standard_neutral_reference", + "path": "experiments/current-form-surface-preview/structural_profile_candidates.json", + "sha256": "a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640" + }, + "source": { + "path": "examples/body-documents/stylized-digitigrade-biped-authored-form.json", + "sha256": "82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14" + } + }, + "role": "predeclared_neutral_perturbation" + }, + { + "attachments": { + "left": { + "centre": [ + -1.05, + -1.0, + 0.05 + ], + "knee": [ + -1.05, + -2.0, + 0.05 + ] + }, + "right": { + "centre": [ + 1.0, + -1.0, + 0.0 + ], + "knee": [ + 1.0, + -2.0, + 0.0 + ] + } + }, + "components": { + "hips.left.P_s.x": -1.05, + "hips.left.P_s.y": -1.0, + "hips.left.P_s.z": 0.05, + "hips.left.r_x": 0.336, + "hips.left.r_y": 0.28, + "hips.left.r_z": 0.3, + "hips.right.P_s.x": 1.0, + "hips.right.P_s.y": -1.0, + "hips.right.P_s.z": 0.0, + "hips.right.r_x": 0.32, + "hips.right.r_y": 0.28, + "hips.right.r_z": 0.3, + "shoulders.left.arm_origin.x": -1.0, + "shoulders.left.arm_origin.y": 2.0, + "shoulders.left.arm_origin.z": 0.0, + "shoulders.left.axilla.x": -1.1, + "shoulders.left.axilla.y": 1.7, + "shoulders.left.axilla.z": 0.0, + "shoulders.left.peak.x": -1.1, + "shoulders.left.peak.y": 2.15, + "shoulders.left.peak.z": 0.0, + "shoulders.left.shoulder_depth": 0.35, + "shoulders.left.start_forward": 0.32, + "shoulders.left.start_lateral": 0.35, + "shoulders.left.start_up": 0.3, + "shoulders.right.arm_origin.x": 1.0, + "shoulders.right.arm_origin.y": 2.0, + "shoulders.right.arm_origin.z": 0.0, + "shoulders.right.axilla.x": 1.1, + "shoulders.right.axilla.y": 1.7, + "shoulders.right.axilla.z": 0.0, + "shoulders.right.peak.x": 1.1, + "shoulders.right.peak.y": 2.15, + "shoulders.right.peak.z": 0.0, + "shoulders.right.shoulder_depth": 0.35, + "shoulders.right.start_forward": 0.32, + "shoulders.right.start_lateral": 0.35, + "shoulders.right.start_up": 0.3, + "stations.lower_abdomen.C.x": 0.0, + "stations.lower_abdomen.C.y": 0.25, + "stations.lower_abdomen.C.z": 0.0, + "stations.lower_abdomen.rA": 0.68, + "stations.lower_abdomen.rL": 1.125, + "stations.lower_abdomen.rP": 0.54, + "stations.lower_pelvis.C.x": 0.0, + "stations.lower_pelvis.C.y": -0.45, + "stations.lower_pelvis.C.z": 0.0, + "stations.lower_pelvis.rA": 0.85, + "stations.lower_pelvis.rL": 1.5, + "stations.lower_pelvis.rP": 0.6, + "stations.lower_ribcage.C.x": 0.0, + "stations.lower_ribcage.C.y": 1.05, + "stations.lower_ribcage.C.z": 0.0, + "stations.lower_ribcage.rA": 0.875, + "stations.lower_ribcage.rL": 1.45, + "stations.lower_ribcage.rP": 0.675, + "stations.neck_collar.C.x": 0.0, + "stations.neck_collar.C.y": 2.15, + "stations.neck_collar.C.z": 0.0, + "stations.neck_collar.rA": 0.4, + "stations.neck_collar.rL": 0.42, + "stations.neck_collar.rP": 0.4, + "stations.neck_upper.C.x": 0.0, + "stations.neck_upper.C.y": 2.55, + "stations.neck_upper.C.z": 0.0, + "stations.neck_upper.rA": 0.33, + "stations.neck_upper.rL": 0.34, + "stations.neck_upper.rP": 0.33, + "stations.upper_abdomen.C.x": 0.0, + "stations.upper_abdomen.C.y": 0.8, + "stations.upper_abdomen.C.z": 0.0, + "stations.upper_abdomen.rA": 0.725, + "stations.upper_abdomen.rL": 1.225, + "stations.upper_abdomen.rP": 0.56, + "stations.upper_pelvis.C.x": 0.0, + "stations.upper_pelvis.C.y": -0.2, + "stations.upper_pelvis.C.z": 0.0, + "stations.upper_pelvis.rA": 0.78, + "stations.upper_pelvis.rL": 1.35, + "stations.upper_pelvis.rP": 0.56, + "stations.upper_ribcage_shoulder.C.x": 0.0, + "stations.upper_ribcage_shoulder.C.y": 1.95, + "stations.upper_ribcage_shoulder.C.z": 0.0, + "stations.upper_ribcage_shoulder.rA": 0.9, + "stations.upper_ribcage_shoulder.rL": 1.5, + "stations.upper_ribcage_shoulder.rP": 0.7, + "stations.waist_abdomen.C.x": 0.0, + "stations.waist_abdomen.C.y": 0.5, + "stations.waist_abdomen.C.z": 0.0, + "stations.waist_abdomen.rA": 0.5, + "stations.waist_abdomen.rL": 0.875, + "stations.waist_abdomen.rP": 0.4 + }, + "id": "neutral_left_asymmetric_xz_and_radius", + "provenance": { + "bindings": { + "left": { + "centre": { + "derivation": "profile.world-part-plus-thigh-start.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|left|thigh/0", + "/profiles/0/part_placements/main|part|left|thigh/1", + "/profiles/0/part_placements/main|part|left|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/10/placement/translation/0", + "/body/parts/10/placement/translation/1", + "/body/parts/10/placement/translation/2", + "/body/landmarks/14/position/0", + "/body/landmarks/14/position/1", + "/body/landmarks/14/position/2" + ] + }, + "frame": { + "interpretation": "identity frame admitted; no rig or joint resolution", + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "source_pointers": [ + "/body/frames/8/transform" + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "joint_hint": { + "distal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "interpretation": "source hint retained for provenance; not interpreted as a solved skeleton", + "proximal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "source_pointer": "/body/joints/9" + }, + "knee": { + "derivation": "profile.world-part-plus-source-knee.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|left|thigh/0", + "/profiles/0/part_placements/main|part|left|thigh/1", + "/profiles/0/part_placements/main|part|left|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/10/placement/translation/0", + "/body/parts/10/placement/translation/1", + "/body/parts/10/placement/translation/2", + "/body/landmarks/16/position/0", + "/body/landmarks/16/position/1", + "/body/landmarks/16/position/2" + ] + } + }, + "right": { + "centre": { + "derivation": "profile.world-part-plus-thigh-start.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|right|thigh/0", + "/profiles/0/part_placements/main|part|right|thigh/1", + "/profiles/0/part_placements/main|part|right|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/13/placement/translation/0", + "/body/parts/13/placement/translation/1", + "/body/parts/13/placement/translation/2", + "/body/landmarks/19/position/0", + "/body/landmarks/19/position/1", + "/body/landmarks/19/position/2" + ] + }, + "frame": { + "interpretation": "identity frame admitted; no rig or joint resolution", + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "source_pointers": [ + "/body/frames/10/transform" + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "joint_hint": { + "distal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "interpretation": "source hint retained for provenance; not interpreted as a solved skeleton", + "proximal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "source_pointer": "/body/joints/12" + }, + "knee": { + "derivation": "profile.world-part-plus-source-knee.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|right|thigh/0", + "/profiles/0/part_placements/main|part|right|thigh/1", + "/profiles/0/part_placements/main|part|right|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/13/placement/translation/0", + "/body/parts/13/placement/translation/1", + "/body/parts/13/placement/translation/2", + "/body/landmarks/21/position/0", + "/body/landmarks/21/position/1", + "/body/landmarks/21/position/2" + ] + } + } + }, + "claim": "numeric perturbation declaration only; no geometry executed", + "expected_change": { + "direction": "left x spacing -0.05, z offset +0.05, left lateral start radius +5%" + }, + "profile": { + "base_case": "standard_neutral_reference", + "path": "experiments/current-form-surface-preview/structural_profile_candidates.json", + "sha256": "a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640" + }, + "source": { + "path": "examples/body-documents/stylized-digitigrade-biped-authored-form.json", + "sha256": "82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14" + } + }, + "role": "predeclared_neutral_perturbation" + }, + { + "attachments": { + "left": { + "centre": [ + -0.2, + -1.0, + 0.0 + ], + "knee": [ + -0.2, + -2.0, + 0.0 + ] + }, + "right": { + "centre": [ + 0.2, + -1.0, + 0.0 + ], + "knee": [ + 0.2, + -2.0, + 0.0 + ] + } + }, + "components": { + "hips.left.P_s.x": -0.2, + "hips.left.P_s.y": -1.0, + "hips.left.P_s.z": 0.0, + "hips.left.r_x": 0.35, + "hips.left.r_y": 0.28, + "hips.left.r_z": 0.3, + "hips.right.P_s.x": 0.2, + "hips.right.P_s.y": -1.0, + "hips.right.P_s.z": 0.0, + "hips.right.r_x": 0.35, + "hips.right.r_y": 0.28, + "hips.right.r_z": 0.3, + "shoulders.left.arm_origin.x": -1.0, + "shoulders.left.arm_origin.y": 2.0, + "shoulders.left.arm_origin.z": 0.0, + "shoulders.left.axilla.x": -1.1, + "shoulders.left.axilla.y": 1.7, + "shoulders.left.axilla.z": 0.0, + "shoulders.left.peak.x": -1.1, + "shoulders.left.peak.y": 2.15, + "shoulders.left.peak.z": 0.0, + "shoulders.left.shoulder_depth": 0.35, + "shoulders.left.start_forward": 0.32, + "shoulders.left.start_lateral": 0.35, + "shoulders.left.start_up": 0.3, + "shoulders.right.arm_origin.x": 1.0, + "shoulders.right.arm_origin.y": 2.0, + "shoulders.right.arm_origin.z": 0.0, + "shoulders.right.axilla.x": 1.1, + "shoulders.right.axilla.y": 1.7, + "shoulders.right.axilla.z": 0.0, + "shoulders.right.peak.x": 1.1, + "shoulders.right.peak.y": 2.15, + "shoulders.right.peak.z": 0.0, + "shoulders.right.shoulder_depth": 0.35, + "shoulders.right.start_forward": 0.32, + "shoulders.right.start_lateral": 0.35, + "shoulders.right.start_up": 0.3, + "stations.lower_abdomen.C.x": 0.0, + "stations.lower_abdomen.C.y": 0.25, + "stations.lower_abdomen.C.z": 0.0, + "stations.lower_abdomen.rA": 0.68, + "stations.lower_abdomen.rL": 1.125, + "stations.lower_abdomen.rP": 0.54, + "stations.lower_pelvis.C.x": 0.0, + "stations.lower_pelvis.C.y": -0.45, + "stations.lower_pelvis.C.z": 0.0, + "stations.lower_pelvis.rA": 0.85, + "stations.lower_pelvis.rL": 1.5, + "stations.lower_pelvis.rP": 0.6, + "stations.lower_ribcage.C.x": 0.0, + "stations.lower_ribcage.C.y": 1.05, + "stations.lower_ribcage.C.z": 0.0, + "stations.lower_ribcage.rA": 0.875, + "stations.lower_ribcage.rL": 1.45, + "stations.lower_ribcage.rP": 0.675, + "stations.neck_collar.C.x": 0.0, + "stations.neck_collar.C.y": 2.15, + "stations.neck_collar.C.z": 0.0, + "stations.neck_collar.rA": 0.4, + "stations.neck_collar.rL": 0.42, + "stations.neck_collar.rP": 0.4, + "stations.neck_upper.C.x": 0.0, + "stations.neck_upper.C.y": 2.55, + "stations.neck_upper.C.z": 0.0, + "stations.neck_upper.rA": 0.33, + "stations.neck_upper.rL": 0.34, + "stations.neck_upper.rP": 0.33, + "stations.upper_abdomen.C.x": 0.0, + "stations.upper_abdomen.C.y": 0.8, + "stations.upper_abdomen.C.z": 0.0, + "stations.upper_abdomen.rA": 0.725, + "stations.upper_abdomen.rL": 1.225, + "stations.upper_abdomen.rP": 0.56, + "stations.upper_pelvis.C.x": 0.0, + "stations.upper_pelvis.C.y": -0.2, + "stations.upper_pelvis.C.z": 0.0, + "stations.upper_pelvis.rA": 0.78, + "stations.upper_pelvis.rL": 1.35, + "stations.upper_pelvis.rP": 0.56, + "stations.upper_ribcage_shoulder.C.x": 0.0, + "stations.upper_ribcage_shoulder.C.y": 1.95, + "stations.upper_ribcage_shoulder.C.z": 0.0, + "stations.upper_ribcage_shoulder.rA": 0.9, + "stations.upper_ribcage_shoulder.rL": 1.5, + "stations.upper_ribcage_shoulder.rP": 0.7, + "stations.waist_abdomen.C.x": 0.0, + "stations.waist_abdomen.C.y": 0.5, + "stations.waist_abdomen.C.z": 0.0, + "stations.waist_abdomen.rA": 0.5, + "stations.waist_abdomen.rL": 0.875, + "stations.waist_abdomen.rP": 0.4 + }, + "id": "neutral_invalid_close_thick", + "provenance": { + "bindings": { + "left": { + "centre": { + "derivation": "profile.world-part-plus-thigh-start.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|left|thigh/0", + "/profiles/0/part_placements/main|part|left|thigh/1", + "/profiles/0/part_placements/main|part|left|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/10/placement/translation/0", + "/body/parts/10/placement/translation/1", + "/body/parts/10/placement/translation/2", + "/body/landmarks/14/position/0", + "/body/landmarks/14/position/1", + "/body/landmarks/14/position/2" + ] + }, + "frame": { + "interpretation": "identity frame admitted; no rig or joint resolution", + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "source_pointers": [ + "/body/frames/8/transform" + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "joint_hint": { + "distal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "interpretation": "source hint retained for provenance; not interpreted as a solved skeleton", + "proximal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "source_pointer": "/body/joints/9" + }, + "knee": { + "derivation": "profile.world-part-plus-source-knee.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|left|thigh/0", + "/profiles/0/part_placements/main|part|left|thigh/1", + "/profiles/0/part_placements/main|part|left|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/10/placement/translation/0", + "/body/parts/10/placement/translation/1", + "/body/parts/10/placement/translation/2", + "/body/landmarks/16/position/0", + "/body/landmarks/16/position/1", + "/body/landmarks/16/position/2" + ] + } + }, + "right": { + "centre": { + "derivation": "profile.world-part-plus-thigh-start.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|right|thigh/0", + "/profiles/0/part_placements/main|part|right|thigh/1", + "/profiles/0/part_placements/main|part|right|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/13/placement/translation/0", + "/body/parts/13/placement/translation/1", + "/body/parts/13/placement/translation/2", + "/body/landmarks/19/position/0", + "/body/landmarks/19/position/1", + "/body/landmarks/19/position/2" + ] + }, + "frame": { + "interpretation": "identity frame admitted; no rig or joint resolution", + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "source_pointers": [ + "/body/frames/10/transform" + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "joint_hint": { + "distal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "interpretation": "source hint retained for provenance; not interpreted as a solved skeleton", + "proximal_frame": { + "rotation_xyzw": [ + 0, + 0, + 0, + 1 + ], + "translation": [ + 0, + 0, + 0 + ] + }, + "source_pointer": "/body/joints/12" + }, + "knee": { + "derivation": "profile.world-part-plus-source-knee.v1", + "profile_pointers": [ + "/profiles/0/part_placements/main|part||pelvis/0", + "/profiles/0/part_placements/main|part||pelvis/1", + "/profiles/0/part_placements/main|part||pelvis/2", + "/profiles/0/part_placements/main|part|right|thigh/0", + "/profiles/0/part_placements/main|part|right|thigh/1", + "/profiles/0/part_placements/main|part|right|thigh/2" + ], + "source_pointers": [ + "/body/parts/0/placement/translation/0", + "/body/parts/0/placement/translation/1", + "/body/parts/0/placement/translation/2", + "/body/parts/13/placement/translation/0", + "/body/parts/13/placement/translation/1", + "/body/parts/13/placement/translation/2", + "/body/landmarks/21/position/0", + "/body/landmarks/21/position/1", + "/body/landmarks/21/position/2" + ] + } + } + }, + "claim": "numeric perturbation declaration only; no geometry executed", + "expected_change": { + "direction": "deliberately incompatible medial overlap; expected rejection" + }, + "profile": { + "base_case": "standard_neutral_reference", + "path": "experiments/current-form-surface-preview/structural_profile_candidates.json", + "sha256": "a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640" + }, + "source": { + "path": "examples/body-documents/stylized-digitigrade-biped-authored-form.json", + "sha256": "82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14" + } + }, + "role": "predeclared_neutral_perturbation" + } + ], + "component_ids": [ + "hips.left.P_s.x", + "hips.left.P_s.y", + "hips.left.P_s.z", + "hips.left.r_x", + "hips.left.r_y", + "hips.left.r_z", + "hips.right.P_s.x", + "hips.right.P_s.y", + "hips.right.P_s.z", + "hips.right.r_x", + "hips.right.r_y", + "hips.right.r_z", + "shoulders.left.arm_origin.x", + "shoulders.left.arm_origin.y", + "shoulders.left.arm_origin.z", + "shoulders.left.axilla.x", + "shoulders.left.axilla.y", + "shoulders.left.axilla.z", + "shoulders.left.peak.x", + "shoulders.left.peak.y", + "shoulders.left.peak.z", + "shoulders.left.shoulder_depth", + "shoulders.left.start_forward", + "shoulders.left.start_lateral", + "shoulders.left.start_up", + "shoulders.right.arm_origin.x", + "shoulders.right.arm_origin.y", + "shoulders.right.arm_origin.z", + "shoulders.right.axilla.x", + "shoulders.right.axilla.y", + "shoulders.right.axilla.z", + "shoulders.right.peak.x", + "shoulders.right.peak.y", + "shoulders.right.peak.z", + "shoulders.right.shoulder_depth", + "shoulders.right.start_forward", + "shoulders.right.start_lateral", + "shoulders.right.start_up", + "stations.lower_abdomen.C.x", + "stations.lower_abdomen.C.y", + "stations.lower_abdomen.C.z", + "stations.lower_abdomen.rA", + "stations.lower_abdomen.rL", + "stations.lower_abdomen.rP", + "stations.lower_pelvis.C.x", + "stations.lower_pelvis.C.y", + "stations.lower_pelvis.C.z", + "stations.lower_pelvis.rA", + "stations.lower_pelvis.rL", + "stations.lower_pelvis.rP", + "stations.lower_ribcage.C.x", + "stations.lower_ribcage.C.y", + "stations.lower_ribcage.C.z", + "stations.lower_ribcage.rA", + "stations.lower_ribcage.rL", + "stations.lower_ribcage.rP", + "stations.neck_collar.C.x", + "stations.neck_collar.C.y", + "stations.neck_collar.C.z", + "stations.neck_collar.rA", + "stations.neck_collar.rL", + "stations.neck_collar.rP", + "stations.neck_upper.C.x", + "stations.neck_upper.C.y", + "stations.neck_upper.C.z", + "stations.neck_upper.rA", + "stations.neck_upper.rL", + "stations.neck_upper.rP", + "stations.upper_abdomen.C.x", + "stations.upper_abdomen.C.y", + "stations.upper_abdomen.C.z", + "stations.upper_abdomen.rA", + "stations.upper_abdomen.rL", + "stations.upper_abdomen.rP", + "stations.upper_pelvis.C.x", + "stations.upper_pelvis.C.y", + "stations.upper_pelvis.C.z", + "stations.upper_pelvis.rA", + "stations.upper_pelvis.rL", + "stations.upper_pelvis.rP", + "stations.upper_ribcage_shoulder.C.x", + "stations.upper_ribcage_shoulder.C.y", + "stations.upper_ribcage_shoulder.C.z", + "stations.upper_ribcage_shoulder.rA", + "stations.upper_ribcage_shoulder.rL", + "stations.upper_ribcage_shoulder.rP", + "stations.waist_abdomen.C.x", + "stations.waist_abdomen.C.y", + "stations.waist_abdomen.C.z", + "stations.waist_abdomen.rA", + "stations.waist_abdomen.rL", + "stations.waist_abdomen.rP" + ], + "immutability": "mandatory fixtures and perturbations are fixed once this file is written", + "mandatory_case_ids": [ + "standard_neutral_reference", + "compact_broad_short_limb_large_head", + "tall_narrow_long_legged", + "slender_long_limb", + "stocky_broad_chested", + "ordinary_human_reference" + ], + "perturbation_case_ids": [ + "neutral_pelvis_width_plus_10pct", + "neutral_left_spacing_minus_005", + "neutral_left_direction_tilt_5deg", + "neutral_left_front_offset_plus_005", + "neutral_left_asymmetric_xz_and_radius", + "neutral_invalid_close_thick" + ], + "profile_table": { + "path": "experiments/current-form-surface-preview/structural_profile_candidates.json", + "sha256": "a5fba6643d0031bac83c08e9093e11fd7945806963509fa939865866112d9640" + }, + "schema": "creature-kernel.pelvis-thigh-transition-inputs.v1", + "source": { + "path": "examples/body-documents/stylized-digitigrade-biped-authored-form.json", + "sha256": "82269e843555ff1aad3c66399e3fcaeb11bbee81d72b69d15765ea9c4e7aff14" + } +} diff --git a/experiments/pelvis-thigh-transition/preserve_evidence.py b/experiments/pelvis-thigh-transition/preserve_evidence.py new file mode 100644 index 0000000..2d7476c --- /dev/null +++ b/experiments/pelvis-thigh-transition/preserve_evidence.py @@ -0,0 +1,492 @@ +#!/usr/bin/env python3 +"""Preserve the failed hip pre-filter evidence and snapshot its inputs. + +This tool deliberately does not import or execute experiment geometry code. +""" + +from __future__ import annotations + +import argparse +import hashlib +import importlib +import importlib.metadata +import json +import os +from pathlib import Path +import platform +import site +import shutil +import stat +import subprocess +import sys +from typing import Iterable + + +TRIAL_ROOT = Path("/tmp/ck-hip-prefilter-trial-20260905-a") +PRESERVE_ROOT = Path( + "/home/ben/.cache/creature-kernel/pelvis-thigh-transition/failed-prefilter-20260905" +) + +# These are source/input support areas, not an instruction to capture their +# generated output. The suffix and excluded-directory rules are intentional +# so a snapshot stays small and reviewable. +DIRECTORY_RULES = ( + ("experiments/pelvis-thigh-transition", (".py", ".json", ".md", ".sh")), + ("experiments/owned-root-assembly-successor", (".py", ".sh", ".md", ".sha256")), + ("experiments/owned-root-assembly-successor-exact-five", (".py", ".sh", ".md", ".sha256")), + ("experiments/programmatic-root-complex-surface", (".py", ".sh", ".md", ".json")), + ("examples/body-documents", (".json",)), +) +EXPLICIT_FILES = ( + "experiments/current-form-surface-preview/requirements.txt", + "experiments/current-form-surface-preview/structural_profile_candidates.json", + "experiments/current-form-surface-preview/surface_preview_launcher.sh", + "experiments/current-form-surface-preview/generate_structural_profile_sources.py", + "experiments/current-form-surface-preview/structural_atomic_publish.py", +) +EXCLUDED_PARTS = { + "__pycache__", + "results", + "generated", + "images", + "captures", + "cache", + ".git", +} +COMPILED_IMPORTS = ( + "numpy", + "scipy", + "skimage", + "PIL", + "imageio", + "networkx", + "tifffile", +) + + +def fail(message: str) -> "NoReturn": + raise SystemExit(f"preserve_evidence.py: error: {message}") + + +def sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def regular_file(path: Path) -> None: + info = path.lstat() + if stat.S_ISLNK(info.st_mode): + fail(f"symlink is not allowed: {path}") + if not stat.S_ISREG(info.st_mode): + fail(f"non-regular file is not allowed: {path}") + + +def fresh_directory(path: Path) -> None: + if not path.is_absolute(): + fail(f"output must be an absolute path: {path}") + if os.path.lexists(path): + fail(f"output must be fresh and absent: {path}") + path.parent.mkdir(parents=True, exist_ok=True) + path.mkdir() + + +def inventory(root: Path, paths: Iterable[Path]) -> list[dict[str, object]]: + rows = [] + for path in sorted(paths, key=lambda item: item.as_posix().encode()): + regular_file(path) + rows.append( + { + "path": path.relative_to(root).as_posix(), + "bytes": path.stat().st_size, + "sha256": sha256_file(path), + } + ) + return rows + + +def trial_files() -> list[Path]: + if not TRIAL_ROOT.is_dir() or TRIAL_ROOT.is_symlink(): + fail(f"exact original trial directory is unavailable: {TRIAL_ROOT}") + found = [] + for path in sorted(TRIAL_ROOT.rglob("*"), key=lambda item: item.as_posix().encode()): + if path.is_symlink(): + fail(f"trial corpus contains a symlink: {path}") + if path.is_file(): + regular_file(path) + found.append(path) + return found + + +def source_files(root: Path) -> list[Path]: + selected: set[Path] = set() + for relative, suffixes in DIRECTORY_RULES: + directory = root / relative + if not directory.is_dir() or directory.is_symlink(): + fail(f"allowlisted source directory is unavailable: {directory}") + for path in directory.rglob("*"): + relative_to_directory = path.relative_to(directory) + if any(part in EXCLUDED_PARTS for part in relative_to_directory.parts): + continue + if path.is_symlink(): + fail(f"allowlisted source tree contains a symlink: {path}") + if path.is_file() and path.suffix in suffixes: + regular_file(path) + selected.add(path) + for relative in EXPLICIT_FILES: + path = root / relative + if not path.is_file() or path.is_symlink(): + fail(f"allowlisted source file is unavailable or is a symlink: {path}") + regular_file(path) + selected.add(path) + return sorted(selected, key=lambda item: item.relative_to(root).as_posix().encode()) + + +def copy_files(root: Path, files: list[Path], destination: Path) -> list[dict[str, object]]: + before = inventory(root, files) + for path, row in zip(files, before): + relative = path.relative_to(root) + target = destination / relative + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(path, target) + regular_file(target) + copied_bytes = target.stat().st_size + copied_sha256 = sha256_file(target) + if copied_bytes != row["bytes"] or copied_sha256 != row["sha256"]: + fail(f"copied bytes differ from source-before inventory: {target}") + after = inventory(root, files) + if before != after: + fail("source changed while being copied; discard this output and retry") + copied = [] + for row in before: + target = destination / str(row["path"]) + copied.append({**row, "snapshot_path": target.relative_to(destination.parent).as_posix()}) + return copied + + +def directory_files(directory: Path) -> list[Path]: + if not directory.is_dir() or directory.is_symlink(): + fail(f"runtime directory is unavailable or is a symlink: {directory}") + files = [] + for path in sorted(directory.rglob("*"), key=lambda item: item.relative_to(directory).as_posix().encode()): + if path.is_symlink(): + fail(f"runtime tree contains a symlink: {path}") + if path.is_file(): + regular_file(path) + files.append(path) + return files + + +def inventory_digest(rows: list[dict[str, object]]) -> str: + encoded = json.dumps(rows, sort_keys=True, separators=(",", ":")).encode("utf-8") + return hashlib.sha256(encoded).hexdigest() + + +def copy_one_checked(source: Path, target: Path) -> dict[str, object]: + regular_file(source) + source_before = { + "bytes": source.stat().st_size, + "sha256": sha256_file(source), + } + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, target) + shutil.copymode(source, target) + regular_file(target) + target_after = { + "bytes": target.stat().st_size, + "sha256": sha256_file(target), + } + if target_after != source_before: + fail(f"copied runtime bytes differ from source-before identity: {target}") + source_after = { + "bytes": source.stat().st_size, + "sha256": sha256_file(source), + } + if source_after != source_before: + fail(f"runtime source changed while being copied: {source}") + return { + "source_path": str(source), + "bytes": source_before["bytes"], + "sha256": source_before["sha256"], + "runtime_sha256": target_after["sha256"], + } + + +def copy_runtime_tree( + source: Path, target: Path, runtime_root: Path +) -> tuple[list[dict[str, object]], list[dict[str, object]], list[dict[str, object]]]: + source_files = directory_files(source) + before = inventory(source, source_files) + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copytree(source, target, symlinks=False) + target_files = directory_files(target) + copied = inventory(target, target_files) + expected = before + if copied != expected: + fail(f"copied runtime tree differs from source-before inventory: {target}") + after = inventory(source, source_files) + if before != after: + fail(f"runtime package source changed while being copied: {source}") + runtime_rows = [] + for row in before: + runtime_path = (target / str(row["path"])).relative_to(runtime_root).as_posix() + runtime_rows.append( + { + "path": runtime_path, + "source_path": str(source / str(row["path"])), + "bytes": row["bytes"], + "sha256": row["sha256"], + "runtime_sha256": row["sha256"], + } + ) + return runtime_rows, before, after + + +def runtime_site_packages(prefix: Path) -> Path: + candidates = [] + for candidate in site.getsitepackages(): + path = Path(candidate) + try: + path.relative_to(prefix) + except ValueError: + continue + if path.is_dir() and not path.is_symlink(): + candidates.append(path) + if len(candidates) != 1: + fail(f"expected exactly one in-venv site-packages directory, found: {candidates}") + return candidates[0] + + +def clone_runtime(destination: Path) -> dict[str, object]: + if sys.prefix == sys.base_prefix: + fail("snapshot requires a virtual environment; sys.prefix equals sys.base_prefix") + prefix = Path(sys.prefix).resolve() + executable = Path(sys.executable).resolve() + base_executable = Path(getattr(sys, "_base_executable", sys.executable)).resolve() + pyvenv = prefix / "pyvenv.cfg" + site_packages = runtime_site_packages(prefix) + regular_file(executable) + regular_file(base_executable) + regular_file(pyvenv) + + if destination.exists() or destination.is_symlink(): + fail(f"runtime clone destination must be absent: {destination}") + destination.mkdir(parents=True) + runtime_rows = [] + executable_row = copy_one_checked(executable, destination / "bin" / "python") + executable_row["path"] = "bin/python" + runtime_rows.append(executable_row) + pyvenv_row = copy_one_checked(pyvenv, destination / "pyvenv.cfg") + pyvenv_row["path"] = "pyvenv.cfg" + runtime_rows.append(pyvenv_row) + + package_target = destination / site_packages.relative_to(prefix) + package_rows, package_before, package_after = copy_runtime_tree( + site_packages, package_target, destination + ) + runtime_rows.extend(package_rows) + return { + "clone_root": str(destination), + "executable": str(destination / "bin" / "python"), + "source_prefix": str(prefix), + "source_executable": str(executable), + "source_executable_sha256": sha256_file(executable), + "base_prefix": sys.base_prefix, + "base_executable": str(base_executable), + "base_executable_sha256": sha256_file(base_executable), + "platform": { + "platform": platform.platform(), + "machine": platform.machine(), + "python_implementation": platform.python_implementation(), + "python_version": platform.python_version(), + }, + "site_packages": str(site_packages), + "source_packages_before": { + "files": package_before, + "inventory_sha256": inventory_digest(package_before), + }, + "source_packages_after": { + "files": package_after, + "inventory_sha256": inventory_digest(package_after), + }, + "files": sorted(runtime_rows, key=lambda row: str(row["path"]).encode()), + "candidate_environment": { + "variable": "CK_CURRENT_FORM_SURFACE_PYTHON", + "value": str(destination / "bin" / "python"), + }, + } + + +def package_versions() -> dict[str, str | None]: + names = ( + "imageio", + "lazy-loader", + "networkx", + "numpy", + "packaging", + "Pillow", + "scikit-image", + "scipy", + "tifffile", + ) + result: dict[str, str | None] = {} + for name in names: + try: + result[name] = importlib.metadata.version(name) + except importlib.metadata.PackageNotFoundError: + result[name] = None + return result + + +def environment_snapshot() -> dict[str, object]: + freeze = subprocess.run( + [sys.executable, "-m", "pip", "freeze"], + check=False, + capture_output=True, + text=True, + ) + loaded_errors = {} + for name in COMPILED_IMPORTS: + try: + importlib.import_module(name) + except Exception as exc: # An inventory should remain useful if optional deps are absent. + loaded_errors[name] = f"{type(exc).__name__}: {exc}" + + extensions = [] + for module_name, module in sorted(sys.modules.items()): + origin = getattr(module, "__file__", None) + if not origin or not origin.endswith((".so", ".so.1", ".pyd", ".dylib")): + continue + path = Path(origin) + row: dict[str, object] = {"module": module_name, "path": str(path)} + if path.is_file() and not path.is_symlink(): + row["bytes"] = path.stat().st_size + row["sha256"] = sha256_file(path) + else: + row["hash_unavailable"] = True + extensions.append(row) + return { + "python_executable": sys.executable, + "python_version": platform.python_version(), + "python_implementation": platform.python_implementation(), + "platform": platform.platform(), + "sys_prefix": sys.prefix, + "package_versions": package_versions(), + "pip_freeze_returncode": freeze.returncode, + "pip_freeze": freeze.stdout.splitlines(), + "pip_freeze_stderr": freeze.stderr.splitlines(), + "pip_freeze_sha256": hashlib.sha256(freeze.stdout.encode()).hexdigest(), + "loaded_compiled_extensions": extensions, + "compiled_import_errors": loaded_errors, + } + + +def write_json(path: Path, value: object) -> None: + with path.open("x", encoding="utf-8") as handle: + json.dump(value, handle, indent=2, sort_keys=True) + handle.write("\n") + + +def preserve(output: Path) -> None: + if output != PRESERVE_ROOT: + fail(f"preservation output must be the exact requested cache path: {PRESERVE_ROOT}") + fresh_directory(output) + raw_paths = trial_files() + raw_rows = inventory(TRIAL_ROOT, raw_paths) + raw_destination = output / "original-trial" + raw_rows = copy_files(TRIAL_ROOT, raw_paths, raw_destination) + + root = Path.cwd().resolve() + source_paths = source_files(root) + recovery_destination = output / "recovery" / "source" + recovery_rows = copy_files(root, source_paths, recovery_destination) + environment = environment_snapshot() + write_json(output / "recovery" / "environment.json", environment) + + final = next((row for row in raw_rows if row["path"] == "final-diagnostics2.json"), None) + render_suffixes = {".png", ".jpg", ".jpeg", ".webp", ".svg"} + render_files = [row["path"] for row in raw_rows if Path(str(row["path"])).suffix.lower() in render_suffixes] + manifest = { + "schema": "pelvis-thigh-transition-failed-prefilter-preservation.v1", + "status": "preserved", + "preserved_at": "2026-09-05", + "original_trial_root": str(TRIAL_ROOT), + "raw_retained_location": str(raw_destination), + "raw_files": raw_rows, + "final_diagnostics2": final, + "recovery_snapshot": { + "label": "RECOVERY", + "not_original_executing_snapshot": True, + "repository_root": str(root), + "location": str(recovery_destination), + "files": recovery_rows, + "environment_location": str(output / "recovery" / "environment.json"), + }, + "known_limits": { + "original_concurrent_edits": "The trial probe imported mutable worktree files by absolute path; no immutable executing-source snapshot was captured. Current source copies are recovery snapshots only.", + "missing_import_snapshots": "The original run did not retain a module/import snapshot. This preservation records current package/runtime data and best-effort loaded extension hashes, not the original import state.", + "trial_surface_renders": "No surface-render files were present in the original trial directory; numeric diagnostics and probes only were retained.", + "pending_fixes": "Pending worktree fixes were not edited, reverted, or inferred by this tool; preservation outputs are separate from the worktree.", + "geometry_execution": "No old trial, geometry builder, renderer, or geometry import was executed by this tool.", + }, + "render_files_found": render_files, + "command": [sys.executable, str(Path(__file__).resolve()), "--preserve-prefilter", str(output)], + } + write_json(output / "preservation-manifest.json", manifest) + print(f"preserved {len(raw_rows)} raw files at {raw_destination}") + print(f"recovery snapshot: {recovery_destination}") + print(f"manifest: {output / 'preservation-manifest.json'}") + + +def snapshot(root: Path, output: Path) -> None: + root = root.resolve() + if not root.is_dir() or root.is_symlink(): + fail(f"snapshot root is unavailable: {root}") + output = output.absolute() + if output == root or root in output.parents: + fail("snapshot output must not be inside the source root") + fresh_directory(output) + files = source_files(root) + rows = copy_files(root, files, output / "source") + environment = environment_snapshot() + runtime = clone_runtime(output / "runtime") + environment["runtime_clone"] = runtime + write_json(output / "environment.json", environment) + write_json( + output / "manifest.json", + { + "schema": "pelvis-thigh-transition-source-snapshot.v1", + "source_root": str(root), + "source": rows, + "environment": "environment.json", + "runtime": runtime, + "exclusions": sorted(EXCLUDED_PARTS), + "symlinks": "rejected", + "source_hashing": "inventory hashed before and after copy; copied bytes are compared to source-before identity; drift fails closed", + }, + ) + print(f"snapshotted {len(rows)} files at {output / 'source'}") + print(f"manifest: {output / 'manifest.json'}") + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + modes = parser.add_mutually_exclusive_group(required=True) + modes.add_argument("--preserve-prefilter", metavar="OUT") + modes.add_argument("--snapshot", metavar="ROOT") + parser.add_argument("--output", metavar="OUT") + args = parser.parse_args() + if args.preserve_prefilter: + if args.output: + parser.error("--output is only valid with --snapshot") + preserve(Path(args.preserve_prefilter).absolute()) + else: + if not args.output: + parser.error("--snapshot requires --output OUT") + snapshot(Path(args.snapshot), Path(args.output)) + + +if __name__ == "__main__": + main() diff --git a/experiments/pelvis-thigh-transition/preview_only.py b/experiments/pelvis-thigh-transition/preview_only.py new file mode 100644 index 0000000..1cad077 --- /dev/null +++ b/experiments/pelvis-thigh-transition/preview_only.py @@ -0,0 +1,64 @@ +"""Capture UNVERIFIED surfaces before the independent numeric checks finish. + +This is the geometry/render phase of an attempt, not a passing result. The +complete mesh is retained for inspection and later comparison. No fallbacks. +""" +import argparse +from concurrent.futures import ProcessPoolExecutor +import json +from pathlib import Path + +import construction +import render + + +def capture(job): + case, destination = job + destination = Path(destination) + destination.mkdir() + report = {"case": case["id"], "technical": "unverified", "visual": "pending"} + try: + levels = construction.evaluate(construction.build( + case["components"], case["attachments"], diagnostic=True), levels=2) + for index, mesh in enumerate(levels): + (destination / f"mesh-level-{index}.json").write_text( + json.dumps(mesh, sort_keys=True, allow_nan=False) + "\n") + human = case["role"] == "executable_cross_family_challenge" + bounds = ((-.30, -.42, -.20), (.30, .16, .20)) if human else ( + (-2.40, -2.70, -1.30), (2.40, 1.00, 1.30)) + overlays = [{"start": row["centre"], "end": row["knee"], + "color": [40, 100, 210], "label": f"{side} source intention"} + for side, row in case["attachments"].items()] + report["admission"] = levels[0]["metadata"]["admission_status"] + status = "REJECTED INPUT" if report["admission"] == "rejected" else "UNVERIFIED" + report["render"] = render.render_views( + levels[-1]["vertices"], levels[-1]["quads"], destination / "surface.png", + case["id"], status, bounds=bounds, overlays=overlays, + allow_crop=True, underside=True) + except Exception as exc: + report["error"] = f"{type(exc).__name__}: {exc}" + (destination / "preview-report.json").write_text( + json.dumps(report, sort_keys=True, indent=2, allow_nan=False) + "\n") + print(f"{case['id']}: {report.get('error', 'unverified surface captured')}", flush=True) + return report + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--inputs", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if not args.output.is_absolute() or args.output.exists(): + parser.error("output must be an absent absolute path") + document = json.loads(args.inputs.read_text()) + args.output.mkdir() + (args.output / "inputs.json").write_bytes(args.inputs.read_bytes()) + with ProcessPoolExecutor(max_workers=2) as pool: + reports = list(pool.map(capture, [(case, str(args.output / case["id"])) + for case in document["cases"]])) + (args.output / "preview-report.json").write_text(json.dumps( + {"technical": "unverified", "cases": reports}, sort_keys=True, indent=2) + "\n") + + +if __name__ == "__main__": + main() diff --git a/experiments/pelvis-thigh-transition/render.py b/experiments/pelvis-thigh-transition/render.py new file mode 100644 index 0000000..0d07132 --- /dev/null +++ b/experiments/pelvis-thigh-transition/render.py @@ -0,0 +1,440 @@ +"""Small deterministic headless renderer for the pelvis/thigh experiment. + +The renderer consumes the evaluated surface directly. It has no geometry +repair, silhouette adjustment, hidden structure, or profile-specific path. +""" +from __future__ import annotations + +import math +from pathlib import Path +from typing import Any + +import numpy as np +from PIL import Image, ImageDraw + + +class RenderError(ValueError): + """Raised when a render input is unsafe or outside this local interface.""" + + +CANVAS_SIZE = (1600, 550) +BACKGROUND = (239, 238, 234) +CLAY = np.array((190.0, 184.0, 174.0), dtype=np.float64) +# Actual fixed experiment lights: a directional key and a softer fill from +# the opposite direction. These affect colour only; they never move geometry. +AMBIENT = 0.25 +KEY_DIFFUSE = 0.60 +FILL_DIFFUSE = 0.15 +KEY_LIGHT_DIRECTION = np.array((-0.45, 0.78, 0.42), dtype=np.float64) +KEY_LIGHT_DIRECTION /= np.linalg.norm(KEY_LIGHT_DIRECTION) +FILL_LIGHT_DIRECTION = -KEY_LIGHT_DIRECTION +PIXEL_CENTER = 0.5 +EPSILON = 1.0e-12 + + +def _reject(condition: bool, message: str) -> None: + if condition: + raise RenderError(message) + + +def _vertices(value: Any) -> np.ndarray: + try: + array = np.asarray(value) + except (TypeError, ValueError) as exc: + raise RenderError("vertices must be a numeric N x 3 sequence") from exc + _reject(array.ndim != 2 or array.shape[1] != 3 or array.shape[0] == 0, + "vertices must be a non-empty N x 3 sequence") + _reject(np.iscomplexobj(array) or not np.issubdtype(array.dtype, np.number), + "vertices must contain real numeric values") + try: + points = np.asarray(array, dtype=np.float64) + except (TypeError, ValueError, OverflowError) as exc: + raise RenderError("vertices must contain real numeric values") from exc + _reject(not np.isfinite(points).all(), "vertices must be finite") + return points + + +def _quads(value: Any, vertex_count: int) -> np.ndarray: + if isinstance(value, (list, tuple)): + for row in value: + if isinstance(row, (list, tuple)) and any( + isinstance(item, (bool, np.bool_)) for item in row): + raise RenderError("quad indices must be integers, not booleans") + try: + array = np.asarray(value) + except (TypeError, ValueError) as exc: + raise RenderError("quads must be an integer N x 4 sequence") from exc + _reject(array.ndim != 2 or array.shape[1] != 4 or array.shape[0] == 0, + "quads must be a non-empty N x 4 sequence") + _reject(np.iscomplexobj(array) or not np.issubdtype(array.dtype, np.integer) + or np.issubdtype(array.dtype, np.bool_), + "quad indices must be integers") + indices = np.asarray(array, dtype=np.int64) + _reject(bool((indices < 0).any()) or bool((indices >= vertex_count).any()), + "quad index is outside vertices") + _reject(any(len(set(row.tolist())) != 4 for row in indices), + "a quad must reference four distinct vertices") + return indices + + +def _aabb(value: Any, points: np.ndarray, *, allow_crop: bool) -> tuple[np.ndarray, np.ndarray]: + if value is None: + low = points.min(axis=0) + high = points.max(axis=0) + elif isinstance(value, dict): + _reject(set(value) != {"min", "max"}, + "bounds mapping must contain only min and max") + low = value["min"] + high = value["max"] + else: + try: + array = np.asarray(value) + except (TypeError, ValueError) as exc: + raise RenderError("bounds must be ((xmin, ymin, zmin), (xmax, ymax, zmax))") from exc + _reject(array.shape != (2, 3), + "bounds must be ((xmin, ymin, zmin), (xmax, ymax, zmax))") + low, high = array[0], array[1] + try: + low = np.asarray(low, dtype=np.float64) + high = np.asarray(high, dtype=np.float64) + except (TypeError, ValueError, OverflowError) as exc: + raise RenderError("bounds must contain finite numeric values") from exc + _reject(low.shape != (3,) or high.shape != (3,), + "bounds must contain two vector3 values") + _reject(not np.isfinite(low).all() or not np.isfinite(high).all(), + "bounds must be finite") + _reject(bool((high < low).any()), "bounds max must not be below bounds min") + if not allow_crop: + _reject(bool((points < low).any()) or bool((points > high).any()), + "vertices must lie inside bounds; pass allow_crop=True for a camera crop") + return low, high + + +def _overlay(value: Any, index: int) -> dict[str, Any]: + _reject(not isinstance(value, dict), f"overlay {index} must be a mapping") + _reject(set(value) - {"start", "end", "color", "label"} + or not {"start", "end", "color"}.issubset(value), + f"overlay {index} has invalid fields") + try: + start = np.asarray(value["start"], dtype=np.float64) + end = np.asarray(value["end"], dtype=np.float64) + color = np.asarray(value["color"]) + except (TypeError, ValueError, OverflowError) as exc: + raise RenderError(f"overlay {index} has invalid values") from exc + _reject(start.shape != (3,) or end.shape != (3,), + f"overlay {index} endpoints must be vector3 values") + _reject(not np.isfinite(start).all() or not np.isfinite(end).all(), + f"overlay {index} endpoints must be finite") + _reject(color.shape != (3,) or np.iscomplexobj(color) + or not np.issubdtype(color.dtype, np.integer), + f"overlay {index} color must contain three integers") + color = np.asarray(color, dtype=np.int64) + _reject(bool((color < 0).any()) or bool((color > 255).any()), + f"overlay {index} color must be in 0..255") + label = value.get("label", "") + _reject(not isinstance(label, str), f"overlay {index} label must be text") + return {"start": start, "end": end, "color": tuple(int(item) for item in color), + "label": label} + + +def _validated_inputs(vertices: Any, quads: Any, bounds: Any, overlays: Any, *, allow_crop: bool) -> tuple[ + np.ndarray, np.ndarray, np.ndarray, np.ndarray, tuple[dict[str, Any], ...]]: + points = _vertices(vertices) + faces = _quads(quads, len(points)) + low, high = _aabb(bounds, points, allow_crop=allow_crop) + if overlays is None: + checked_overlays: tuple[dict[str, Any], ...] = () + else: + _reject(not isinstance(overlays, (list, tuple)), + "overlays must be a list or tuple of segment mappings") + checked_overlays = tuple(_overlay(item, index) + for index, item in enumerate(overlays)) + return points, faces, low, high, checked_overlays + + +def _camera(name: str, view: tuple[float, float, float]) -> tuple[str, np.ndarray, np.ndarray, np.ndarray]: + depth = np.asarray(view, dtype=np.float64) + depth /= np.linalg.norm(depth) + world_up = np.array((0.0, 1.0, 0.0), dtype=np.float64) + right = np.cross(world_up, depth) + right /= np.linalg.norm(right) + up = np.cross(depth, right) + up /= np.linalg.norm(up) + return name, right, up, depth + + +CAMERAS = ( + _camera("front", (0.0, 0.0, 1.0)), + _camera("side", (1.0, 0.0, 0.0)), + _camera("rear-three-quarter", (1.0, 0.2, -1.0)), +) +UNDERSIDE_CAMERA = _camera("underside", (0.0, -1.0, 0.4)) + + +def _corners(low: np.ndarray, high: np.ndarray) -> np.ndarray: + return np.asarray([(x, y, z) for x in (low[0], high[0]) + for y in (low[1], high[1]) + for z in (low[2], high[2])], dtype=np.float64) + + +def _extent(corners: np.ndarray, cameras: tuple[tuple[str, np.ndarray, np.ndarray, np.ndarray], ...]) -> float: + midpoint = (corners[0] + corners[-1]) * 0.5 + relative = corners - midpoint + extent = 0.0 + for _, right, up, _ in cameras: + extent = max(extent, float(np.abs(relative @ right).max()), + float(np.abs(relative @ up).max())) + _reject(not math.isfinite(extent) or extent <= 0.0, + "bounds do not produce a positive camera extent") + return extent + + +def _project(points: np.ndarray, midpoint: np.ndarray, + camera: tuple[str, np.ndarray, np.ndarray, np.ndarray], + scale: float, origin: tuple[float, float], + viewport: tuple[int, int, int, int]) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + _, right, up, depth = camera + relative = points - midpoint + u = relative @ right + v = relative @ up + z = relative @ depth + x0, y0, width, height = viewport + centre_x = x0 + width * 0.5 + centre_y = y0 + height * 0.5 + projected = (centre_x + scale * u, centre_y - scale * v, z) + _reject(not all(np.isfinite(item).all() for item in projected), + "camera projection is non-finite") + return projected + + +def _triangle_colour(points: np.ndarray, triangle: tuple[int, int, int]) -> tuple[int, int, int]: + a, b, c = points[list(triangle)] + normal = np.cross(b - a, c - a) + length = float(np.linalg.norm(normal)) + _reject(not math.isfinite(length) or length <= 1.0e-15, + "quad contains a degenerate triangle") + normal /= length + key = max(0.0, float(np.dot(normal, KEY_LIGHT_DIRECTION))) + fill = max(0.0, float(np.dot(normal, FILL_LIGHT_DIRECTION))) + illumination = AMBIENT + KEY_DIFFUSE * key + FILL_DIFFUSE * fill + colour = np.clip(np.rint(CLAY * illumination), 0.0, 255.0).astype(np.uint8) + return tuple(int(item) for item in colour) + + +def _rasterize(pixel_array: np.ndarray, points: np.ndarray, faces: np.ndarray, + midpoint: np.ndarray, camera: tuple[str, np.ndarray, np.ndarray, np.ndarray], + scale: float, viewport: tuple[int, int, int, int]) -> int: + x0, y0, width, height = viewport + screen_x, screen_y, depth = _project(points, midpoint, camera, scale, (x0, y0), viewport) + z_buffer = np.full((height, width), -np.inf, dtype=np.float64) + visible_pixels = 0 + # Keep quad split order grouped by quad, so equal-depth ties are stable. + triangles = [item for pair in zip( + ((int(face[0]), int(face[1]), int(face[2])) for face in faces), + ((int(face[0]), int(face[2]), int(face[3])) for face in faces)) + for item in pair] + for triangle in triangles: + ia, ib, ic = triangle + ax, ay, az = float(screen_x[ia]), float(screen_y[ia]), float(depth[ia]) + bx, by, bz = float(screen_x[ib]), float(screen_y[ib]), float(depth[ib]) + cx, cy, cz = float(screen_x[ic]), float(screen_y[ic]), float(depth[ic]) + denominator = (by - cy) * (ax - cx) + (cx - bx) * (ay - cy) + _reject(not math.isfinite(denominator), "triangle projection is non-finite") + if abs(denominator) <= 1.0e-15: + # A valid 3D face may be edge-on in one orthographic camera. + continue + left = max(x0, int(math.ceil(min(ax, bx, cx) - PIXEL_CENTER))) + right = min(x0 + width - 1, int(math.floor(max(ax, bx, cx) - PIXEL_CENTER))) + top = max(y0, int(math.ceil(min(ay, by, cy) - PIXEL_CENTER))) + bottom = min(y0 + height - 1, int(math.floor(max(ay, by, cy) - PIXEL_CENTER))) + if left > right or top > bottom: + continue + columns = np.arange(left, right + 1, dtype=np.float64) + PIXEL_CENTER + rows = np.arange(top, bottom + 1, dtype=np.float64) + PIXEL_CENTER + px, py = np.meshgrid(columns, rows) + w0 = ((by - cy) * (px - cx) + (cx - bx) * (py - cy)) / denominator + w1 = ((cy - ay) * (px - cx) + (ax - cx) * (py - cy)) / denominator + w2 = 1.0 - w0 - w1 + inside = (w0 >= -EPSILON) & (w1 >= -EPSILON) & (w2 >= -EPSILON) + if not inside.any(): + continue + sample_depth = w0 * az + w1 * bz + w2 * cz + local_z = z_buffer[top - y0:bottom - y0 + 1, left - x0:right - x0 + 1] + wins = inside & (sample_depth > local_z) + if not wins.any(): + continue + colour = _triangle_colour(points, triangle) + local_z[wins] = sample_depth[wins] + pixel_array[top:bottom + 1, left:right + 1][wins] = colour + visible_pixels += int(wins.sum()) + return visible_pixels + + +def _viewports(view_count: int, canvas_size: tuple[int, int]) -> tuple[tuple[int, int, int, int], ...]: + canvas_width, canvas_height = canvas_size + top = 40 + bottom = 30 + panel_height = canvas_height - top - bottom + widths = [canvas_width // view_count] * view_count + for index in range(canvas_width % view_count): + widths[index] += 1 + viewports = [] + left = 0 + for width in widths: + viewports.append((left, top, width, panel_height)) + left += width + return tuple(viewports) + + +def _draw_text(image: Image.Image, title: str, status: str, + view_names: tuple[str, ...], viewports: tuple[tuple[int, int, int, int], ...], + overlays: tuple[dict[str, Any], ...] = ()) -> None: + draw = ImageDraw.Draw(image) + draw.rectangle((0, 0, image.width, 35), fill=(32, 34, 37)) + draw.text((14, 9), title, fill=(248, 248, 248)) + status_text = f"{status} | VISUAL PENDING" + status_width = draw.textbbox((0, 0), status_text)[2] + draw.text((image.width - status_width - 14, 9), status_text, fill=(248, 221, 135)) + for index, (name, (left, top, width, height)) in enumerate(zip(view_names, viewports)): + if index: + draw.line((left, top, left, top + height), fill=(206, 204, 198), width=1) + label_width = draw.textbbox((0, 0), name)[2] + draw.text((left + (width - label_width) // 2, image.height - 23), name, + fill=(65, 66, 68)) + if overlays: + x = 14 + y = image.height - 24 + for item in overlays: + label = item["label"] or "overlay" + text = f" {label}" + draw.rectangle((x, y + 4, x + 8, y + 12), fill=item["color"]) + draw.text((x + 10, y), text, fill=(65, 66, 68)) + x += draw.textbbox((0, 0), text)[2] + 18 + if x >= image.width - 100: + break + + +def _draw_overlays(image: Image.Image, overlays: tuple[dict[str, Any], ...], midpoint: np.ndarray, + scale: float, cameras: tuple[tuple[str, np.ndarray, np.ndarray, np.ndarray], ...], + viewports: tuple[tuple[int, int, int, int], ...]) -> None: + draw = ImageDraw.Draw(image) + for camera, viewport in zip(cameras, viewports): + for item in overlays: + projected_start = _project(item["start"][None, :], midpoint, camera, scale, (0, 0), viewport) + projected_end = _project(item["end"][None, :], midpoint, camera, scale, (0, 0), viewport) + start = (int(round(projected_start[0][0])), int(round(projected_start[1][0]))) + end = (int(round(projected_end[0][0])), int(round(projected_end[1][0]))) + draw.line((*start, *end), fill=item["color"], width=2) + radius = 3 + draw.ellipse((start[0] - radius, start[1] - radius, + start[0] + radius, start[1] + radius), fill=item["color"]) + draw.ellipse((end[0] - radius, end[1] - radius, + end[0] + radius, end[1] + radius), fill=item["color"]) + + +def _save_png(image: Image.Image, output_path: Path) -> None: + _reject(output_path.suffix.lower() != ".png", "output_path must end in .png") + try: + with output_path.open("wb") as handle: + image.save(handle, format="PNG", compress_level=9, optimize=False) + except OSError as exc: + raise RenderError(f"unable to write {output_path}") from exc + + +def _render_image(points: np.ndarray, faces: np.ndarray, low: np.ndarray, high: np.ndarray, + title: str, status: str, cameras: tuple[tuple[str, np.ndarray, np.ndarray, np.ndarray], ...], + overlays: tuple[dict[str, Any], ...], canvas_size: tuple[int, int]) -> tuple[Image.Image, int]: + pixel_array = np.empty((canvas_size[1], canvas_size[0], 3), dtype=np.uint8) + pixel_array[:, :] = BACKGROUND + midpoint = (low + high) * 0.5 + extent = _extent(_corners(low, high), cameras) + top = 40 + bottom = 30 + panel_height = canvas_size[1] - top - bottom + panel_width = canvas_size[0] // len(cameras) + usable = min(panel_width - 36, panel_height - 24) + scale = usable / (2.0 * extent) + viewports = _viewports(len(cameras), canvas_size) + visible_pixels = 0 + for camera, viewport in zip(cameras, viewports): + visible_pixels += _rasterize(pixel_array, points, faces, midpoint, camera, scale, viewport) + image = Image.fromarray(pixel_array, mode="RGB") + _draw_text(image, title, status, tuple(camera[0] for camera in cameras), viewports, overlays) + if overlays: + _draw_overlays(image, overlays, midpoint, scale, cameras, viewports) + return image, visible_pixels + + +def _underside_path(output_path: Path) -> Path: + suffix = output_path.suffix or ".png" + return output_path.with_name(f"{output_path.stem}-underside{suffix}") + + +def render_views(vertices: Any, quads: Any, output_path: str | Path, title: str, status: str, + bounds: Any = None, overlays: Any = None, *, underside: bool = False, + allow_crop: bool = False) -> dict[str, Any]: + """Render matched direct views and return stable, non-acceptance metadata. + + ``bounds`` is an optional world AABB, represented as ``(min_xyz, max_xyz)`` + or ``{"min": min_xyz, "max": max_xyz}``. Supplying it fixes the camera + frame for comparisons. ``allow_crop=True`` changes only camera framing; + the complete input vertices/quads still go through validation and raster + clipping. ``underside=True`` writes a separate sibling PNG; the primary + artifact remains the fixed 1600x550 three-view capture. + """ + _reject(not isinstance(title, str) or not title.strip(), "title must be non-empty text") + _reject(not isinstance(status, str) or not status.strip(), "status must be non-empty text") + _reject(not isinstance(underside, bool), "underside must be a boolean") + _reject(not isinstance(allow_crop, bool), "allow_crop must be a boolean") + points, faces, low, high, checked_overlays = _validated_inputs( + vertices, quads, bounds, overlays, allow_crop=allow_crop) + try: + path = Path(output_path) + except TypeError as exc: + raise RenderError("output_path must be a filesystem path") from exc + _reject(path.suffix.lower() != ".png", "output_path must end in .png") + _reject(path.exists() and path.is_dir(), "output_path must not be a directory") + cameras = CAMERAS + image, visible_pixels = _render_image(points, faces, low, high, title, status, + cameras, (), CANVAS_SIZE) + _save_png(image, path) + underside_path: Path | None = None + underside_visible = None + diagnostic_path: Path | None = None + if checked_overlays: + diagnostic_path = path.with_name(f"{path.stem}-diagnostic.png") + diagnostic_image, _ = _render_image( + points, faces, low, high, title, status, cameras, checked_overlays, CANVAS_SIZE) + _save_png(diagnostic_image, diagnostic_path) + if underside: + underside_path = _underside_path(path) + underside_image, underside_visible = _render_image( + points, faces, low, high, title, status, (UNDERSIDE_CAMERA,), (), + CANVAS_SIZE) + _save_png(underside_image, underside_path) + return { + "output_path": str(path), + "diagnostic_path": str(diagnostic_path) if diagnostic_path else None, + "underside_path": str(underside_path) if underside_path else None, + "width": CANVAS_SIZE[0], + "height": CANVAS_SIZE[1], + "views": [camera[0] for camera in cameras], + "triangle_count": len(faces) * 2, + "visible_pixels": visible_pixels, + "underside_visible_pixels": underside_visible, + "bounds": [low.tolist(), high.tolist()], + "allow_crop": allow_crop, + "status": status, + "visual_status": "pending", + "overlay_count": len(checked_overlays), + "lighting": { + "ambient": AMBIENT, + "key_direction": KEY_LIGHT_DIRECTION.tolist(), + "key_weight": KEY_DIFFUSE, + "fill_direction": FILL_LIGHT_DIRECTION.tolist(), + "fill_weight": FILL_DIFFUSE, + }, + } + + +__all__ = ["RenderError", "render_views"] diff --git a/experiments/pelvis-thigh-transition/results/prefilter-closure.json b/experiments/pelvis-thigh-transition/results/prefilter-closure.json new file mode 100644 index 0000000..c785d0a --- /dev/null +++ b/experiments/pelvis-thigh-transition/results/prefilter-closure.json @@ -0,0 +1,40 @@ +{ + "schema": "pelvis-thigh-transition-prefilter-closure.v1", + "trial_status": "failed-prefilter-evidence-preserved", + "evidence_closure": "incomplete", + "technology_outcome": "none", + "raw_retained_location": "/home/ben/.cache/creature-kernel/pelvis-thigh-transition/failed-prefilter-20260905/original-trial", + "preservation_manifest": "/home/ben/.cache/creature-kernel/pelvis-thigh-transition/failed-prefilter-20260905/preservation-manifest.json", + "raw_files": [ + {"path": "final-diagnostics2.json", "bytes": 36561, "sha256": "685337985297ce62ce306b22c6bbde8773c80bb98a106747c5b4ea082c1cd808"}, + {"path": "gates.json", "bytes": 9230, "sha256": "b70537922e56b059da3ed0fa113760c117fbeeb251a4452f6ad110ce1e55e3d2"}, + {"path": "gates2.json", "bytes": 9158, "sha256": "a4f500a91a67351fdfd584c958a19ad6051dcb1605db96403fc0a0687bf2f10a"}, + {"path": "gates3.json", "bytes": 9206, "sha256": "994e92eefd2d0c23f54391b4fb765bff2c22efcc9e07a9271d7a39b7bf44e431"}, + {"path": "gates4.json", "bytes": 12778, "sha256": "13314332786a51fa765d8d5fbdc5588473d1e93f63a80515b044d1d1963f3f79"}, + {"path": "stencil.json", "bytes": 21792, "sha256": "c8b7064401e3adc435bd392f43d2d07ebb0cc59a5b5ee6f761e060ce1fc43460"}, + {"path": "stencil3.json", "bytes": 21792, "sha256": "c8b7064401e3adc435bd392f43d2d07ebb0cc59a5b5ee6f761e060ce1fc43460"}, + {"path": "stencil_probe.py", "bytes": 2978, "sha256": "7562c3fb97655719b456db32ab624ce71344682f8c3a6ef6ac002f0d3c620be0"}, + {"path": "summarize.py", "bytes": 1317, "sha256": "4137276cdf0d21d8ad1cf396983c56fbed9a2e234d9549f68ce9c6682cb79ddf"}, + {"path": "summary.txt", "bytes": 9683, "sha256": "113590f8df1e3065828b08bf63d89951735497d26422fd44afb4083636a687d5"}, + {"path": "trial_gate_probe.py", "bytes": 16759, "sha256": "35f73212e8783b3b10227b1ba3d4ce5f22ef6f59bf6427c0682bf5243927bf9f"} + ], + "final_diagnostics2": { + "path": "final-diagnostics2.json", + "bytes": 36561, + "sha256": "685337985297ce62ce306b22c6bbde8773c80bb98a106747c5b4ea082c1cd808" + }, + "known_limits": { + "original_concurrent_edits": "The trial probe imported mutable worktree files by absolute path; no immutable executing-source snapshot was captured. Current source copies are RECOVERY snapshots only.", + "missing_import_snapshots": "The original run did not retain a module/import snapshot. Current package/runtime data and best-effort loaded extension hashes do not reconstruct the original import state.", + "trial_surface_renders": "No surface-render files were present in the original trial directory; numeric diagnostics and probes only were retained.", + "pending_fixes": "Pending fixes remain untouched; the preservation tool did not edit, revert, or infer them.", + "scope": "This preserves failed local pelvis-to-thigh evidence and isolation inputs only; it accepts no whole-body architecture or product direction." + }, + "recovery_snapshot": { + "label": "RECOVERY", + "not_original_executing_snapshot": true, + "location": "/home/ben/.cache/creature-kernel/pelvis-thigh-transition/failed-prefilter-20260905/recovery/source", + "environment": "/home/ben/.cache/creature-kernel/pelvis-thigh-transition/failed-prefilter-20260905/recovery/environment.json", + "files": 41 + } +} diff --git a/experiments/pelvis-thigh-transition/runner.py b/experiments/pelvis-thigh-transition/runner.py new file mode 100644 index 0000000..e8061be --- /dev/null +++ b/experiments/pelvis-thigh-transition/runner.py @@ -0,0 +1,568 @@ +"""Bounded pelvis/thigh experiment runner. + +This runner is an evidence harness, not a geometry contract. It consumes a +captured ``inputs.json``, requires the successor construction/check API, and +keeps unverified render evidence separate from later technical status views. +It never writes back to the source worktree. +""" +from __future__ import annotations + +import argparse +from concurrent.futures import ProcessPoolExecutor, as_completed +import hashlib +import json +import math +import os +from pathlib import Path +import re +import sys +from typing import Any, Mapping + + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +NEUTRAL_PACKAGE = ROOT / "experiments/owned-root-assembly-successor" +for module_path in (str(HERE), str(NEUTRAL_PACKAGE)): + if module_path not in sys.path: + sys.path.insert(0, module_path) + +import render +try: # The authoritative registered-document module; absence is fail-closed. + import cases # type: ignore +except ImportError: # pragma: no cover - exercised through the admission test + cases = None + +try: # Tests may replace these exact successor-local modules with mocks. + import construction # type: ignore +except ImportError: # pragma: no cover - fail-closed in _require_apis + construction = None +try: + import checks # type: ignore +except ImportError: # pragma: no cover - fail-closed in _require_apis + checks = None + + +class RunnerError(ValueError): + """Raised for runner admission or output-contract failures.""" + + +PROFILE_CASE_IDS = ( + "standard_neutral_reference", + "compact_broad_short_limb_large_head", + "tall_narrow_long_legged", + "slender_long_limb", + "stocky_broad_chested", +) +HUMAN_CASE_ID = "ordinary_human_reference" +MAX_WORKERS = 2 +CASE_ID = re.compile(r"[^A-Za-z0-9._-]+") +REGISTERED_INPUT_SHA256 = "23132147711c792d3617963323d29e86323ed8539c64dbe9f18b32ce6be43db1" + + +def _reject(condition: bool, message: str) -> None: + if condition: + raise RunnerError(message) + + +def _json_bytes(value: Any) -> bytes: + try: + return (json.dumps(value, sort_keys=True, indent=2, separators=(",", ": "), + ensure_ascii=True, allow_nan=False) + "\n").encode("utf-8") + except (TypeError, ValueError, OverflowError) as exc: + raise RunnerError("value is not deterministic finite JSON") from exc + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _write(path: Path, data: bytes) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + try: + path.write_bytes(data) + except OSError as exc: + raise RunnerError(f"unable to write {path}") from exc + + +def _write_json(path: Path, value: Any) -> None: + _write(path, _json_bytes(value)) + + +def _read_json(path: Path) -> tuple[Any, bytes]: + try: + raw = _regular_input(path) + value = json.loads(raw.decode("utf-8"), parse_constant=lambda token: (_ for _ in ()).throw(ValueError(token))) + except (OSError, UnicodeDecodeError, json.JSONDecodeError, ValueError) as exc: + raise RunnerError(f"inputs are not strict finite UTF-8 JSON: {path}") from exc + return value, raw + + +def _canonical_path(value: Any, label: str) -> Path: + _reject(not isinstance(value, (str, os.PathLike)), f"{label} must be a filesystem path") + path = Path(value) + _reject(not path.is_absolute() or os.path.normpath(str(path)) != str(path), + f"{label} must be an absolute canonical path") + return path + + +def _regular_input(path: Path) -> bytes: + _reject(path.is_symlink() or not path.is_file(), f"inputs file is not a regular file: {path}") + try: + raw = path.read_bytes() + except OSError as exc: + raise RunnerError(f"unable to read inputs: {path}") from exc + _reject(len(raw) > 16 * 1024 * 1024, "inputs exceed the bounded 16 MiB limit") + return raw + + +def _slug(case_id: str) -> str: + result = CASE_ID.sub("-", case_id).strip("-._") or "case" + return result[:96] + + +def _bounded(value: Any, depth: int = 0) -> Any: + # Real gate diagnostics include levels, frame reports, rays and hit pairs. + # This serialization safety bound is not a geometry acceptance threshold. + _reject(depth > 64, "check result nesting exceeds the bounded depth") + if value is None or isinstance(value, (str, bool, int)): + return value + if isinstance(value, float): + _reject(not math.isfinite(value), "check result contains a non-finite number") + return value + if isinstance(value, Mapping): + return {str(key): _bounded(item, depth + 1) for key, item in sorted(value.items(), key=lambda pair: str(pair[0]))} + if isinstance(value, (list, tuple)): + return [_bounded(item, depth + 1) for item in value] + return str(value) + + +def _require_apis() -> tuple[Any, Any, Any, Any]: + """Admit only the successor's exact construction and checker API.""" + if construction is None: + raise RunnerError("successor construction module is unavailable") + if checks is None: + raise RunnerError("successor checks module is unavailable") + try: + build = construction.build + evaluate = construction.evaluate + except AttributeError as exc: + raise RunnerError("successor construction must provide build/evaluate") from exc + try: + check = checks.check_case + compare = checks.compare_perturbation + except AttributeError as exc: + raise RunnerError("successor checks must provide check_case/compare_perturbation") from exc + if not all(callable(function) for function in (build, evaluate, check, compare)): + raise RunnerError("successor construction/check entrypoints must be callable") + return build, evaluate, check, compare + + +def build_case(case: Mapping[str, Any]) -> Any: + """Build through the exact successor API; case IDs never enter geometry.""" + build, _, _, _ = _require_apis() + return build(case["components"], case["attachments"], diagnostic=True) + + +def evaluate_case(built: Any, case: Mapping[str, Any]) -> Any: + """Evaluate exactly L0/L1/L2 through the successor API.""" + _, evaluate, _, _ = _require_apis() + return evaluate(built, levels=2) + + +def _levels(evaluation: Any) -> tuple[Any, ...]: + if type(evaluation) is not list or len(evaluation) != 3: + raise RunnerError("construction.evaluate must return [L0, L1, L2]") + return tuple(evaluation) + + +def _mesh_parts(mesh: Any) -> tuple[tuple[tuple[float, float, float], ...], tuple[tuple[int, int, int, int], ...]]: + _reject(not isinstance(mesh, Mapping), "mesh level must be a mapping") + vertices, quads = mesh["vertices"], mesh["quads"] + _reject(not (isinstance(vertices, (list, tuple)) and isinstance(quads, (list, tuple))), + "mesh must expose concrete vertices and quads") + points = [] + for index, point in enumerate(vertices): + _reject(not (isinstance(point, (list, tuple)) and len(point) == 3), + f"mesh vertex {index} is not a vector3") + converted = tuple(float(value) for value in point) + _reject(not all(math.isfinite(value) for value in converted), + f"mesh vertex {index} is non-finite") + points.append(converted) + _reject(not points, "mesh has no vertices") + faces = [] + for index, face in enumerate(quads): + _reject(not (isinstance(face, (list, tuple)) and len(face) == 4), + f"mesh quad {index} is not a quad") + _reject(not all(type(value) is int for value in face), + f"mesh quad {index} has a non-integer index") + converted = tuple(face) + _reject(not (len(set(converted)) == 4 and all(0 <= value < len(points) for value in converted)), + f"mesh quad {index} has invalid indices") + faces.append(converted) + _reject(not faces, "mesh has no quads") + return tuple(points), tuple(faces) + + +def _mesh_record(mesh: Any, level: int) -> tuple[dict[str, Any], tuple[tuple[float, float, float], ...], tuple[tuple[int, int, int, int], ...]]: + points, faces = _mesh_parts(mesh) + required_metadata = ("face_owners", "control_owners", "loops", + "base_stencils", "frames", "metadata") + _reject(not isinstance(mesh, Mapping), "mesh level must be a mapping") + for key in required_metadata: + _reject(key not in mesh, f"mesh level is missing required metadata: {key}") + record = {"schema": "creature-kernel.pelvis-thigh-transition-mesh.v1", + "level": level, "vertices": [list(point) for point in points], + "quads": [list(face) for face in faces]} + record.update({key: _bounded(mesh[key]) for key in required_metadata}) + return record, points, faces + + +def check_case(case: Mapping[str, Any], levels: Any) -> Any: + """Run the exact successor checker.""" + _, _, check, _ = _require_apis() + return check(case, levels) + + +def compare_perturbation(base_case: Mapping[str, Any], base_levels: Any, + perturbation_case: Mapping[str, Any], levels: Any) -> Any: + """Run the exact successor perturbation checker.""" + _, _, _, compare = _require_apis() + return compare(base_case, base_levels, perturbation_case, levels) + + +def _case_bounds(case_id: str) -> dict[str, Any]: + if case_id == HUMAN_CASE_ID: + lower = [[-0.30, -0.42, -0.20], [0.30, 0.16, 0.20]] + full = [[-0.56, -0.48, -0.32], [0.56, 0.80, 0.32]] + return {"lowercrop": lower, "fullroot": full, + "physical_scale": "human reference uses intentional 0.16 physical scale; not an anthropomorphic size claim"} + return {"lowercrop": [[-2.40, -2.70, -1.30], [2.40, 1.00, 1.30]], + "fullroot": [[-3.50, -3.00, -2.00], [3.50, 5.00, 2.00]], + "physical_scale": "anthropomorphic shared source frame"} + + +def _source_overlays(case: Mapping[str, Any]) -> list[dict[str, Any]]: + attachments = case.get("attachments", {}) + overlays = [] + colours = {"left": [48, 112, 210], "right": [210, 72, 56]} + if isinstance(attachments, Mapping): + for side in ("left", "right"): + item = attachments.get(side) + if not isinstance(item, Mapping) or "centre" not in item or "knee" not in item: + continue + overlays.append({"start": list(item["centre"]), "end": list(item["knee"]), + "color": colours[side], + "label": f"source {side} thigh direction intent"}) + return overlays + + +def _check_outcome(value: Any) -> tuple[str, Any]: + checked = _bounded(value) + _reject(not isinstance(checked, Mapping), "checker report must be a mapping") + _reject(not isinstance(checked.get("schema"), str) or not checked["schema"], + "checker report is missing schema") + if checked["schema"] == "pelvis-thigh-transition/checks-v1": + technical = checked.get("technical") + rendering = checked.get("render") + _reject(not isinstance(technical, Mapping) or type(technical.get("pass")) is not bool, + "checker report is missing technical.pass") + _reject(not isinstance(rendering, Mapping) or type(rendering.get("safe")) is not bool, + "checker report is missing render.safe") + return ("technical_pass" if technical["pass"] else "rejected"), checked + outcome = checked.get("outcome") + _reject(outcome not in ("pass", "reject"), + "checker report is missing explicit outcome pass/reject") + return ("technical_pass" if outcome == "pass" else "rejected"), checked + + +def _exception(value: BaseException, phase: str) -> dict[str, str]: + return {"phase": phase, "type": type(value).__name__, "message": str(value)[:2000]} + + +def _render_status(case_dir: Path, points: Any, faces: Any, bounds: dict[str, Any], + overlays: list[dict[str, Any]], title: str, status: str, + suffix: str) -> tuple[list[dict[str, Any]], list[dict[str, str]]]: + renders, errors = [], [] + for frame_name, allow_crop in (("lowercrop", True), ("fullroot", False)): + output = case_dir / f"{frame_name}-{suffix}.png" + try: + metadata = render.render_views( + points, faces, output, title, status, + bounds=bounds[frame_name], overlays=overlays, + underside=True, allow_crop=allow_crop) + metadata = dict(metadata) + for key in ("output_path", "diagnostic_path", "underside_path"): + value = metadata.get(key) + if value is not None: + metadata[key] = Path(value).relative_to(case_dir).as_posix() + renders.append({"frame": frame_name, "status": status, + "allow_crop": allow_crop, "metadata": metadata}) + except Exception as exc: # retain render failure and continue the case/check path + errors.append(_exception(exc, f"render.{frame_name}.{suffix}")) + return renders, errors + + +def _case_directory(root: Path, index: int, case_id: str) -> Path: + path = root / "cases" / f"case-{index:02d}-{_slug(case_id)}" + _reject(path.exists() or path.is_symlink(), f"case output already exists: {path}") + path.mkdir(parents=True) + return path + + +def _case_manifest(case_dir: Path) -> list[dict[str, Any]]: + rows = [] + for path in sorted(case_dir.rglob("*"), key=lambda item: item.relative_to(case_dir).as_posix().encode("utf-8")): + if path.is_file() and path.name != "case-manifest.json": + data = path.read_bytes() + rows.append({"path": path.relative_to(case_dir).as_posix(), + "bytes": len(data), "sha256": _sha256(data)}) + _write_json(case_dir / "case-manifest.json", {"schema": "creature-kernel.pelvis-thigh-transition-case-manifest.v1", "files": rows}) + return rows + + +def _execute_case(index: int, case: Mapping[str, Any], case_dir: Path) -> dict[str, Any]: + case_id = str(case.get("id", f"case-{index:02d}")) + expected_rejection = "invalid" in case_id.lower() + bounds = _case_bounds(case_id) + base = {"index": index, "case_id": case_id, "role": case.get("role"), + "expected_rejection": expected_rejection, "bounds": bounds, + "overlay_semantics": "source-intention segments only; not bones or hidden structure", + "exceptions": [], "renders": [], "artifacts": []} + try: + built = build_case(case) + evaluation = evaluate_case(built, case) + levels = _levels(evaluation) + mesh_rows = [] + mesh_arrays = [] + for level, mesh in enumerate(levels): + record, points, faces = _mesh_record(mesh, level) + _write_json(case_dir / f"mesh-level-{level}.json", record) + mesh_rows.append({"level": level, "path": f"mesh-level-{level}.json"}) + mesh_arrays.append((points, faces)) + points, faces = mesh_arrays[-1] + overlays = _source_overlays(case) + base["source_frame_segments"] = overlays + unverified, render_errors = _render_status( + case_dir, points, faces, bounds, overlays, case_id, + "UNVERIFIED - VISUAL PENDING", "unverified") + base["renders"] = unverified + base["exceptions"].extend(render_errors) + base["artifacts"] = mesh_rows + base["phase"] = "render_ready" + _write_json(case_dir / "case-report-unverified.json", base) + print(f"case {case_id}: renderready", flush=True) + except Exception as exc: + base["exceptions"].append(_exception(exc, "build-or-serialize")) + base["outcome"] = "error" + base["phase"] = "checkscomplete" + _write_json(case_dir / "case-report.json", base) + _case_manifest(case_dir) + print(f"case {case_id}: checkscomplete error", flush=True) + return base + + try: + raw_check = check_case(case, levels) + technical_outcome, checked = _check_outcome(raw_check) + except Exception as exc: + base["exceptions"].append(_exception(exc, "checks.check_case")) + technical_outcome, checked = "error", { + "schema": "creature-kernel.pelvis-thigh-transition-runner-error.v1", + "outcome": "error", "exception": base["exceptions"][-1]} + if expected_rejection and technical_outcome == "technical_pass": + technical_outcome = "unexpected_pass" + accepted_status = "TECHNICAL PASS - VISUAL PENDING" if technical_outcome == "technical_pass" else "REJECTED" + final_renders, render_errors = _render_status( + case_dir, points, faces, bounds, overlays, case_id, accepted_status, "final") + base["exceptions"].extend(render_errors) + base.update({"outcome": technical_outcome, "expected_rejection_met": expected_rejection and technical_outcome == "rejected", + "check_result": checked, "renders_final": final_renders, "phase": "checkscomplete"}) + _write_json(case_dir / "case-report.json", base) + _case_manifest(case_dir) + print(f"case {case_id}: checkscomplete {technical_outcome}", flush=True) + return base + + +def _load_mesh_record(case_dir: Path, level: int = 2) -> dict[str, Any]: + value, _ = _read_json(case_dir / f"mesh-level-{level}.json") + _reject(not isinstance(value, Mapping), "persisted mesh record is not an object") + return dict(value) + + +def _load_levels(case_dir: Path) -> list[dict[str, Any]]: + levels = [_load_mesh_record(case_dir, level) for level in range(3)] + _levels(levels) + return levels + + +def _comparison_pass(value: Any) -> tuple[bool, Any]: + checked = _bounded(value) + _reject(not isinstance(checked, Mapping), "perturbation checker report must be a mapping") + _reject(not isinstance(checked.get("schema"), str) or not checked["schema"], + "perturbation checker report is missing schema") + if checked["schema"] == "pelvis-thigh-transition/perturbation-checks-v1": + _reject(type(checked.get("pass")) is not bool, + "perturbation checker report is missing pass") + return checked["pass"], checked + outcome = checked.get("outcome") + if outcome in ("pass", "reject"): + return outcome == "pass", checked + _reject(type(checked.get("pass")) is not bool, + "perturbation checker report is missing explicit pass/reject") + return checked["pass"], checked + + +def _validate_registered_inputs(input_path: Path, input_raw: bytes) -> None: + """Require the exact cases.py-generated document and registered digest.""" + _reject(_sha256(input_raw) != REGISTERED_INPUT_SHA256, + "inputs do not match the registered inputs SHA-256") + if cases is None: + raise RunnerError("registered cases.py module is unavailable") + try: + result = cases.main(["--check-inputs", str(input_path)]) + except Exception as exc: + raise RunnerError("inputs do not match the exact cases.py document/schema/inventory") from exc + _reject(result != 0, "cases.py rejected the registered inputs") + + +def _compare_perturbations(root: Path, cases: list[Mapping[str, Any]], results: list[Mapping[str, Any]], + input_value: Mapping[str, Any]) -> list[dict[str, Any]]: + by_id = {str(case.get("id")): (case, result) for case, result in zip(cases, results)} + baseline_id = "standard_neutral_reference" + _reject(baseline_id not in by_id, "registered inputs are missing the standard neutral baseline") + baseline_case, baseline_result = by_id[baseline_id] + if baseline_result.get("outcome") == "error": + rows = [{"case_id": str(case.get("id")), "outcome": "unverified", + "reason": "baseline case did not load"} + for case in cases if case.get("id") in input_value["perturbation_case_ids"]] + _write_json(root / "perturbation-comparisons.json", { + "schema": "creature-kernel.pelvis-thigh-transition-perturbation-comparisons.v1", + "rows": rows, "failure_count": len(rows)}) + return rows + baseline_dir = root / "cases" / f"case-{int(baseline_result['index']):02d}-{_slug(baseline_id)}" + baseline_levels = _load_levels(baseline_dir) + rows = [] + perturbation_ids = input_value["perturbation_case_ids"] + for case in cases: + case_id = str(case.get("id")) + if case_id not in perturbation_ids: + continue + result = by_id.get(case_id, (case, {}))[1] + row = {"case_id": case_id, "expected_rejection": "invalid" in case_id.lower()} + if result.get("outcome") == "error": + row.update({"outcome": "unverified", "reason": "perturbation case did not load"}) + else: + directory = root / "cases" / f"case-{int(result['index']):02d}-{_slug(case_id)}" + try: + comparison_pass, comparison = _comparison_pass(compare_perturbation( + baseline_case, baseline_levels, case, _load_levels(directory))) + technical_outcome = result.get("outcome") + row.update({"outcome": ("rejected" if technical_outcome == "rejected" else "unexpected_pass") + if row["expected_rejection"] else ("compared" if comparison_pass else "failed"), + "comparison_pass": comparison_pass, + "expected_rejection_met": (not row["expected_rejection"] or technical_outcome == "rejected"), + "comparison": _bounded(comparison), + "technical_case_outcome": technical_outcome}) + except Exception as exc: + row.update({"outcome": "error", "exception": _exception(exc, "compare_perturbation")}) + rows.append(row) + _write_json(root / "perturbation-comparisons.json", { + "schema": "creature-kernel.pelvis-thigh-transition-perturbation-comparisons.v1", + "rows": rows, + "failure_count": sum(1 for row in rows + if row.get("comparison_pass") is not True + or row.get("outcome") in {"error", "unverified", "unexpected_pass"}), + }) + return rows + + +def _root_manifest(root: Path) -> list[dict[str, Any]]: + rows = [] + for path in sorted(root.rglob("*"), key=lambda item: item.relative_to(root).as_posix().encode("utf-8")): + if path.is_file() and path.name != "stable-manifest.json": + data = path.read_bytes() + rows.append({"path": path.relative_to(root).as_posix(), "bytes": len(data), "sha256": _sha256(data)}) + return rows + + +def run(inputs: str | os.PathLike[str], output: str | os.PathLike[str], attempt: int, workers: int = 2) -> dict[str, Any]: + """Run captured cases into a fresh output directory; never mutate inputs/worktree.""" + _require_apis() + input_path = _canonical_path(inputs, "inputs") + output_path = _canonical_path(output, "output") + _reject(not (type(attempt) is int and attempt in (0, 1, 2)), "attempt must be 0, 1, or 2") + _reject(not (type(workers) is int and 1 <= workers <= MAX_WORKERS), "workers must be 1 or 2") + input_value, input_raw = _read_json(input_path) + _reject(not (isinstance(input_value, Mapping) and isinstance(input_value.get("cases"), list)), + "inputs must be an object with a cases list") + cases = list(input_value["cases"]) + _reject(not (cases and all(isinstance(case, Mapping) and isinstance(case.get("id"), str) for case in cases)), + "inputs cases must be non-empty mappings with string IDs") + _validate_registered_inputs(input_path, input_raw) + _reject(os.path.lexists(output_path), "output must be absent before the run") + _reject(not output_path.parent.is_dir() or output_path.parent.is_symlink(), + "output parent must be a regular existing directory") + output_path.mkdir() + _write(output_path / "inputs.json", input_raw) + _write(output_path / "runner-source.py", Path(__file__).read_bytes()) + case_root = output_path / "cases" + case_root.mkdir() + jobs = [] + for index, case in enumerate(cases): + jobs.append((index, case, _case_directory(output_path, index, str(case["id"])))) + if workers == 1: + results = [_execute_case(index, case, directory) for index, case, directory in jobs] + else: + results_by_index = {} + with ProcessPoolExecutor(max_workers=workers) as pool: + futures = {pool.submit(_execute_case, index, case, directory): index + for index, case, directory in jobs} + for future in as_completed(futures): + index = futures[future] + try: + results_by_index[index] = future.result() + except Exception as exc: + results_by_index[index] = {"index": index, "case_id": str(cases[index]["id"]), + "outcome": "error", "exceptions": [_exception(exc, "worker")], + "phase": "checkscomplete"} + print(f"case {cases[index]['id']}: checkscomplete worker-error", flush=True) + results = [results_by_index[index] for index in range(len(cases))] + comparisons = _compare_perturbations(output_path, cases, results, input_value) + comparison_failures = sum(1 for row in comparisons + if row.get("comparison_pass") is not True + or row.get("outcome") in {"error", "unverified", "unexpected_pass"}) + case_failures = sum(1 for case_result in results + if case_result.get("outcome") != "technical_pass" + and not case_result.get("expected_rejection_met")) + root_outcome = "pass" if case_failures == 0 and comparison_failures == 0 else "failed" + report = {"schema": "creature-kernel.pelvis-thigh-transition-run-report.v1", + "attempt": attempt, "inputs": {"path": input_path.name, "bytes": len(input_raw), "sha256": _sha256(input_raw)}, + "workers": workers, "case_count": len(cases), + "cases": results, "perturbation_comparisons": comparisons, + "outcome": root_outcome, "case_failure_count": case_failures, + "comparison_failure_count": comparison_failures, + "visual_acceptance": "pending; parent-owned visual manifest required", + "candidate_execution": "not performed by validation; this report is produced only when explicitly invoked"} + _write_json(output_path / "run-report.json", report) + manifest = {"schema": "creature-kernel.pelvis-thigh-transition-stable-manifest.v1", + "attempt": attempt, "files": _root_manifest(output_path)} + _write_json(output_path / "stable-manifest.json", manifest) + return report + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Run the bounded pelvis/thigh transition evidence harness") + parser.add_argument("--inputs", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--attempt", required=True, type=int, choices=(0, 1, 2)) + parser.add_argument("--workers", type=int, default=2, choices=(1, 2)) + args = parser.parse_args(argv) + try: + run(args.inputs, args.output, args.attempt, args.workers) + except Exception as exc: + print(f"runner.py: error: {exc}", file=sys.stderr, flush=True) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/experiments/pelvis-thigh-transition/tests/test_checks.py b/experiments/pelvis-thigh-transition/tests/test_checks.py new file mode 100644 index 0000000..78a288d --- /dev/null +++ b/experiments/pelvis-thigh-transition/tests/test_checks.py @@ -0,0 +1,278 @@ +from __future__ import annotations + +import copy +import json +from pathlib import Path +import sys +import unittest +from types import SimpleNamespace +from unittest.mock import Mock, patch + + +HERE = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(HERE)) +import checks + + +class CheckerTests(unittest.TestCase): + def test_canonical_thigh_exits_selected_amid_five_ports(self): + parsed = {"loops": { + "port.neck": (0, 1, 2), + "port.left_arm": (3, 4, 5), + "port.right_arm": (6, 7, 8), + "port.left_thigh": (9, 10, 11), + "port.right_thigh": (12, 13, 14), + }} + self.assertEqual(checks._exit_loop_names({}, parsed), + ["port.left_thigh", "port.right_thigh"]) + del parsed["loops"]["port.right_thigh"] + self.assertEqual(checks._exit_loop_names({}, parsed), []) + + def test_real_generic_intersection_module_loads_on_small_triangles(self): + vertices = ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0), + (3.0, 0.0, 0.0), (4.0, 0.0, 0.0), (3.0, 1.0, 0.0), + (6.0, 0.0, 0.0), (7.0, 0.0, 0.0), (6.0, 1.0, 0.0), + (100.0, 100.0, 100.0)) + triangles = ((0, 1, 2), (3, 4, 5), (6, 7, 8)) + with patch.dict(sys.modules): + sys.modules.pop("owned_root_generic_mesh_correctness", None) + result = checks._intersection_report(vertices, triangles, (0, 1, 2), ("pelvis",) * 3) + self.assertTrue(result["available"], result) + self.assertIn("owned_root_generic_mesh_correctness", sys.modules) + self.assertTrue(result["pair_policy_complete"], result) + self.assertTrue(result["pass"], result) + self.assertEqual(result["hit_pairs"], []) + self.assertEqual(len(result["calls"]), 3) + self.assertEqual(result["unreferenced_vertex_count"], 1) + + def test_ray_intersection_returns_positive_distance(self): + vertices = ((2.0, -1.0, -1.0), (2.0, 1.0, -1.0), (2.0, 0.0, 1.0)) + distance = checks._ray_triangle((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), vertices, (0, 1, 2)) + self.assertEqual(distance, 2.0) + self.assertEqual(checks._deduplicate_hits((2.0, 2.0 + 5.0e-7, 3.0), 1.0e-6), [2.0, 3.0]) + + def test_directed_open_exit_loop_uses_negated_newell_normal_for_outward(self): + case = self._case_with_direction((0.0, 0.0, -1.0)) + parsed = self._exit_parsed(wrong_plane=False) + result = checks._exit_checks(case, parsed, checks._source_dimensions(case)) + self.assertAlmostEqual(result["loops"]["left_exit"]["outward_dot_direction"], 1.0) + for value, expected in zip(result["loops"]["left_exit"]["plane_normal"], (0.0, 0.0, 1.0)): + self.assertAlmostEqual(value, expected) + for value, expected in zip(result["loops"]["left_exit"]["outward_normal"], (0.0, 0.0, -1.0)): + self.assertAlmostEqual(value, expected) + + def test_invalid_mesh_is_a_json_diagnostic_not_an_exception(self): + bad_mesh = { + "vertices": ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)), + "quads": ((0, 1, 2, 99),), + "face_owners": ("pelvis",), + "control_owners": ("pelvis", "pelvis", "pelvis"), + "loops": {"only": (0, 1, 2)}, + "base_stencils": (), + "frames": {}, + } + report = checks.check_case(self._case(), [bad_mesh, bad_mesh, bad_mesh]) + json.dumps(report, allow_nan=False) + self.assertFalse(report["technical"]["pass"]) + self.assertFalse(report["render"]["safe"]) + self.assertTrue(any(row["code"] == "invalid_mesh" + for row in report["technical"]["levels"][0]["errors"])) + + def test_lower_quad_triangle_normal_orientation_is_a_gate(self): + parsed = { + "vertices": ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), + (0.0, 1.0, 0.0), (1.0, 1.0, 0.0)), + "quads": ((0, 1, 2, 3),), + "face_owners": ("pelvis",), + } + result = checks._lower_quad_normal_checks(parsed) + self.assertFalse(result["pass"]) + self.assertEqual(result["failure_count"], 1) + self.assertLess(result["failures"][0]["normal_dot"], 0.0) + + def test_boundary_declaration_requires_five_loops(self): + mesh = { + "vertices": ((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0), (0.0, 1.0, 0.0), + (0.0, 0.0, 1.0), (1.0, 0.0, 1.0), (1.0, 1.0, 1.0), (0.0, 1.0, 1.0)), + "quads": ((0, 1, 2, 3), (4, 7, 6, 5), (0, 4, 5, 1), + (1, 5, 6, 2), (2, 6, 7, 3), (4, 0, 3, 7)), + "face_owners": ("pelvis",) * 6, + "control_owners": ("pelvis",) * 8, + "loops": {"one": (0, 1, 2, 3)}, + "base_stencils": (), + "frames": {}, + } + level_report, _ = checks._mesh_structural_checks(0, mesh, None) + self.assertFalse(level_report["pass"]) + self.assertTrue(any(row["code"] == "invalid_mesh" for row in level_report["errors"])) + + def test_negative_clearance_keeps_finite_mesh_renderable_but_fails_admission(self): + mesh = self._small_mesh() + case = self._case() + case["attachments"]["left"]["centre"] = [-0.2, -1.0, 0.0] + case["attachments"]["right"]["centre"] = [0.2, -1.0, 0.0] + case["components"]["hips.left.r_x"] = 0.35 + case["components"]["hips.right.r_x"] = 0.35 + case["admission_failures"] = ["nominal_medial_clearance"] + report = checks.check_case(case, [mesh, mesh, mesh]) + self.assertFalse(report["technical"]["pass"]) + self.assertTrue(report["render"]["safe"]) + self.assertFalse(report["admission"]["pass"]) + self.assertTrue(report["admission"]["failures"]) + + def test_tilt_response_uses_actual_exit_plane_not_correct_frame_metadata(self): + base_case = self._case_with_direction((0.0, 0.0, -1.0)) + case = dict(base_case) + case["id"] = "neutral_left_direction_tilt_5deg" + case["provenance"] = {"expected_change": {"direction": "left thigh direction tilts"}} + base_levels = [self._exit_mesh(False)] * 3 + new_levels = [self._exit_mesh(True)] * 3 + result = checks.compare_perturbation(base_case, base_levels, case, new_levels) + self.assertIn("direction_tilt_response", result["checks"], result) + self.assertFalse(result["pass"]) + self.assertFalse(result["checks"]["direction_tilt_response"]["pass"]) + + def test_asymmetric_response_requires_actual_L2_radius_increase(self): + base_case = self._case_with_direction((0.0, 0.0, -1.0)) + case = copy.deepcopy(base_case) + case["id"] = "neutral_left_asymmetric_xz_and_radius" + case["declared_response"] = "left asymmetric translation and radius" + case["components"]["hips.left.r_x"] *= 1.05 + delta = (0.04, 0.0, 0.05) + for key in ("centre", "knee"): + case["attachments"]["left"][key] = checks._vec_add(case["attachments"]["left"][key], delta) + base_mesh = self._exit_mesh(False) + for factor, expected_pass in ((1.0, False), (1.05, True), (1.10, False)): + with self.subTest(actual_radius_factor=factor): + new_mesh = copy.deepcopy(base_mesh) + new_mesh["vertices"] = tuple( + (x * factor + delta[0], y, z + delta[2]) if index < 4 else (x, y, z) + for index, (x, y, z) in enumerate(base_mesh["vertices"])) + # L0/L1 and metadata cannot substitute for measured L2 response. + with patch.object(checks, "check_case", side_effect=AssertionError("full check rerun")): + result = checks.compare_perturbation( + base_case, [base_mesh] * 3, case, [base_mesh, base_mesh, new_mesh]) + self.assertTrue(result["checks"]["exit_centroid_response"]["pass"], result) + self.assertEqual(result["checks"]["asymmetric_lateral_span_response"]["pass"], expected_pass, result) + self.assertEqual(result["pass"], expected_pass, result) + json.dumps(result, allow_nan=False) + + def test_containment_rays_start_at_source_H_despite_wrong_output_H(self): + case = self._case_with_direction((0.0, 0.0, -1.0)) + parsed = self._exit_parsed(False) + for record in parsed["frames"].values(): + record["H"] = (100.0, 200.0, 300.0) + info = checks._source_dimensions(case) + with patch.object(checks, "_ray_triangle", return_value=None) as ray: + result = checks._containment_checks(case, parsed, info) + for side in ("left", "right"): + self.assertEqual(result["rays"][side + ":summary"]["H"], info["H_by_side"][side]) + self.assertTrue(any(call.args[0] == info["H_by_side"][side] for call in ray.call_args_list)) + self.assertFalse(any(call.args[0] == (100.0, 200.0, 300.0) for call in ray.call_args_list)) + + def test_truncated_upper_hits_fail_closed_for_lower_collision_inventory(self): + diagnostic = Mock(return_value={"pair_policy_complete": True, + "intersection_hit_count": 65, + "hit_pairs": [(0, 1)], "hit_pairs_truncated": True}) + module = SimpleNamespace(intersection_diagnostics=diagnostic) + spec = SimpleNamespace(name="owned_root_generic_mesh_correctness", + loader=SimpleNamespace(exec_module=lambda module: None)) + parsed = self._exit_parsed(False) + parsed["face_owners"] = ["upper_arm"] * len(parsed["quads"]) + with patch.dict(sys.modules), \ + patch.object(checks.importlib.util, "spec_from_file_location", return_value=spec), \ + patch.object(checks.importlib.util, "module_from_spec", return_value=module): + result = checks._level_intersection_and_geometry(2, parsed, checks._source_dimensions(self._case())) + inventory = result["intersections"] + self.assertEqual(diagnostic.call_count, 3) + self.assertFalse(inventory["collision_inventory_complete"]) + self.assertFalse(inventory["pass"]) + self.assertFalse(result["nonadjacent_lower_intersections"]["pass"]) + self.assertEqual(inventory["lower_hit_pairs"], []) + self.assertTrue(any(row["code"] == "incomplete_collision_inventory" for row in inventory["errors"])) + + @staticmethod + def _case(): + return { + "id": "synthetic", + "attachments": { + "left": {"centre": [-1.0, 0.0, 0.0], "knee": [-1.0, -1.0, 0.0]}, + "right": {"centre": [1.0, 0.0, 0.0], "knee": [1.0, -1.0, 0.0]}, + }, + "components": { + "stations.lower_pelvis.rL": 1.0, + "hips.left.r_x": 0.3, "hips.left.r_y": 0.3, "hips.left.r_z": 0.3, + "hips.right.r_x": 0.3, "hips.right.r_y": 0.3, "hips.right.r_z": 0.3, + }, + } + + @classmethod + def _case_with_direction(cls, direction): + case = cls._case() + case["attachments"] = { + "left": {"centre": [-1.0, 0.0, 0.0], "knee": [-1.0, 0.0, direction[2]]}, + "right": {"centre": [1.0, 0.0, 0.0], "knee": [1.0, 0.0, direction[2]]}, + } + return case + + @staticmethod + def _exit_parsed(wrong_plane): + mesh = CheckerTests._exit_mesh(wrong_plane) + level_report, parsed = checks._mesh_structural_checks(2, mesh, None) + if parsed is None: + raise AssertionError(level_report) + return parsed + + @staticmethod + def _exit_mesh(wrong_plane): + left = ((-0.3, -0.3, -0.45), (0.3, -0.3, -0.45), + (0.3, 0.3, -0.45), (-0.3, 0.3, -0.45)) + if wrong_plane: + right = ((-0.3, -0.3, 0.0), (0.3, -0.3, 0.0), + (0.3, -0.3, 0.6), (-0.3, -0.3, 0.6)) + else: + right = tuple((x + 2.0, y, z) for x, y, z in left) + extras = ( + ((-0.2, -0.2, 0.2), (0.2, -0.2, 0.2), (0.2, 0.2, 0.2), (-0.2, 0.2, 0.2)), + ((1.8, -0.2, 0.2), (2.2, -0.2, 0.2), (2.2, 0.2, 0.2), (1.8, 0.2, 0.2)), + ((3.8, -0.2, 0.2), (4.2, -0.2, 0.2), (4.2, 0.2, 0.2), (3.8, 0.2, 0.2)), + ) + vertices = left + right + tuple(point for group in extras for point in group) + loops = {"left_exit": (0, 1, 2, 3), "right_exit": (4, 5, 6, 7), + "socket": (8, 9, 10, 11), "upper": (12, 13, 14, 15), + "lower": (16, 17, 18, 19)} + quads = tuple(loops.values()) + frames = { + "left": {"H": (0.0, 0.0, 0.0), "knee": (0.0, 0.0, -1.0), "length": 1.0, + "d": (0.0, 0.0, -1.0), "X": (1.0, 0.0, 0.0), "U": (0.0, 0.0, 1.0), + "F": (0.0, -1.0, 0.0), "exit": (0.0, 0.0, -0.45)}, + "right": {"H": (0.0, 0.0, 0.0), "knee": (0.0, 0.0, -1.0), "length": 1.0, + "d": (0.0, 0.0, -1.0), "X": (1.0, 0.0, 0.0), "U": (0.0, 0.0, 1.0), + "F": (0.0, -1.0, 0.0), "exit": (0.0, 0.0, -0.45)}, + } + return {"vertices": vertices, "quads": quads, "face_owners": ("pelvis",) * 5, + "control_owners": ("pelvis",) * 20, "loops": loops, + "base_stencils": tuple(((index, 1.0),) for index in range(20)), + "frames": frames} + + @staticmethod + def _small_mesh(): + vertices = tuple(point for index in range(8) + for point in ((float(index), 0.0, 0.10 * index), + (float(index), 1.0, 0.10 * index + 0.2))) + quads = tuple((2 * index, 2 * index + 1, 2 * index + 3, 2 * index + 2) + for index in range(7)) + return { + "vertices": vertices, + "quads": quads, + "face_owners": ("pelvis",) * len(quads), + "control_owners": ("pelvis",) * len(vertices), + "loops": {"a": (0, 1, 2), "b": (3, 4, 5), "c": (6, 7, 8), + "d": (9, 10, 11), "e": (12, 13, 14)}, + "base_stencils": tuple(((index, 1.0),) for index in range(len(vertices))), + "frames": {}, + } + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/pelvis-thigh-transition/tests/test_construction.py b/experiments/pelvis-thigh-transition/tests/test_construction.py new file mode 100644 index 0000000..2d8c2c2 --- /dev/null +++ b/experiments/pelvis-thigh-transition/tests/test_construction.py @@ -0,0 +1,171 @@ +"""Synthetic-only tests for the generic Catmull--Clark evaluator.""" +from __future__ import annotations + +from pathlib import Path +import sys +import unittest + + +PACKAGE_DIR = Path(__file__).resolve().parents[1] +if str(PACKAGE_DIR) not in sys.path: + sys.path.insert(0, str(PACKAGE_DIR)) + +import construction # noqa: E402 + + +class SyntheticGridTests(unittest.TestCase): + """Exercise subdivision without loading or constructing a real case.""" + + def setUp(self) -> None: + # A 3x3 x/z grid, with four consistently wound planar quads. + vertices = tuple( + (float(x), 0.0, float(z)) + for z in range(3) + for x in range(3) + ) + quads = ( + (0, 1, 4, 3), + (1, 2, 5, 4), + (3, 4, 7, 6), + (4, 5, 8, 7), + ) + base_owners = tuple("synthetic.grid" for _ in vertices) + dummy_frame = { + "H": (0.0, 0.0, 0.0), + "knee": (0.0, -1.0, 0.0), + "length": 1.0, + "d": (0.0, -1.0, 0.0), + "X": (1.0, 0.0, 0.0), + "U": (0.0, 1.0, 0.0), + "F": (0.0, 0.0, 1.0), + "exit": (0.0, -0.45, 0.0), + } + self.mesh = { + "vertices": vertices, + "quads": quads, + "face_owners": tuple("synthetic.grid" for _ in quads), + "control_owners": base_owners, + "loops": { + "outer": (0, 1, 2, 5, 8, 7, 6, 3), + }, + "base_stencils": tuple(((index, 1.0),) for index in range(9)), + "frames": { + "left": dict(dummy_frame), + "right": dict(dummy_frame), + }, + "metadata": { + "level": 0, + "admission_status": "accepted", + "admission_failures": (), + "base_control_owners": base_owners, + "dominant_owner_label": ( + "display representative only; authoritative ownership is " + "base_control_owners plus full base_stencils" + ), + }, + } + + def test_all_sixteen_child_quads_and_loop(self) -> None: + evaluated = construction.evaluate(self.mesh, levels=1) + level_one = evaluated[1] + expected_quads = ( + (0, 9, 21, 10), + (1, 12, 21, 9), + (4, 14, 21, 12), + (3, 10, 21, 14), + (1, 11, 22, 12), + (2, 13, 22, 11), + (5, 16, 22, 13), + (4, 12, 22, 16), + (3, 14, 23, 15), + (4, 17, 23, 14), + (7, 19, 23, 17), + (6, 15, 23, 19), + (4, 16, 24, 17), + (5, 18, 24, 16), + (8, 20, 24, 18), + (7, 17, 24, 20), + ) + self.assertEqual(level_one["quads"], expected_quads) + self.assertEqual(level_one["face_owners"], ("synthetic.grid",) * 16) + self.assertEqual(level_one["loops"]["outer"], + (0, 9, 1, 11, 2, 13, 5, 18, + 8, 20, 7, 19, 6, 15, 3, 10)) + + def test_affine_reproduction_partition_and_planarity(self) -> None: + evaluated = construction.evaluate(self.mesh, levels=2) + base_vertices = self.mesh["vertices"] + for mesh in evaluated: + self.assertTrue(all( + abs(sum(weight for _index, weight in stencil) - 1.0) + <= 1.0e-12 + for stencil in mesh["base_stencils"] + )) + self.assertTrue(all( + weight >= -1.0e-12 + for stencil in mesh["base_stencils"] + for _index, weight in stencil + )) + for point, stencil in zip(mesh["vertices"], + mesh["base_stencils"]): + reproduced = tuple( + sum(base_vertices[index][axis] * weight + for index, weight in stencil) + for axis in range(3) + ) + self.assertEqual(point[1], 0.0) + for actual, expected in zip(point, reproduced): + self.assertAlmostEqual(actual, expected, places=12) + + def test_translation_reproduction_and_owner_metadata(self) -> None: + translation = (2.5, -3.0, 4.0) + translated = dict(self.mesh) + translated["vertices"] = tuple( + tuple(point[axis] + translation[axis] for axis in range(3)) + for point in self.mesh["vertices"] + ) + original_levels = construction.evaluate(self.mesh, levels=2) + translated_levels = construction.evaluate(translated, levels=2) + for original, shifted in zip(original_levels, translated_levels): + self.assertEqual( + shifted["metadata"]["dominant_owner_label"], + "display representative only; authoritative ownership is " + "base_control_owners plus full base_stencils", + ) + self.assertEqual(original["metadata"]["base_control_owners"], + shifted["metadata"]["base_control_owners"]) + for original_point, shifted_point in zip( + original["vertices"], shifted["vertices"] + ): + for actual, expected in zip( + shifted_point, + (original_point[axis] + translation[axis] + for axis in range(3)), + ): + self.assertAlmostEqual(actual, expected, places=12) + + def test_shared_edges_have_opposite_winding(self) -> None: + level_one = construction.evaluate(self.mesh, levels=1)[1] + directed = {} + for face_index, face in enumerate(level_one["quads"]): + for slot, left in enumerate(face): + right = face[(slot + 1) % 4] + edge = tuple(sorted((left, right))) + directed.setdefault(edge, []).append((face_index, left, right)) + + boundary = {edge for edge, rows in directed.items() if len(rows) == 1} + self.assertEqual(boundary, { + tuple(sorted((left, right))) + for index, left in enumerate(level_one["loops"]["outer"]) + for right in (level_one["loops"]["outer"] + [(index + 1) % len(level_one["loops"]["outer"])],) + }) + for rows in directed.values(): + self.assertIn(len(rows), (1, 2)) + if len(rows) == 2: + self.assertEqual((rows[0][1], rows[0][2]), + (rows[1][2], rows[1][1])) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/pelvis-thigh-transition/tests/test_render.py b/experiments/pelvis-thigh-transition/tests/test_render.py new file mode 100644 index 0000000..60753fd --- /dev/null +++ b/experiments/pelvis-thigh-transition/tests/test_render.py @@ -0,0 +1,119 @@ +from __future__ import annotations + +from pathlib import Path +import sys +import tempfile +import unittest + +from PIL import Image + +HERE = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(HERE)) +import render + + +def _occluding_quads(): + # The horizontal quad is behind the nearer quad in +Z. The nearer quad is + # deliberately tilted, so its directional-light colour differs. + vertices = ( + (-0.8, -0.7, 0.0), (0.8, -0.7, 0.0), (0.8, 0.8, 0.0), (-0.8, 0.8, 0.0), + (-0.8, -0.7, 0.7), (0.8, -0.7, 0.9), (0.8, 0.8, 0.8), (-0.8, 0.8, 0.6), + ) + return vertices, ((0, 1, 2, 3), (4, 5, 6, 7)) + + +class RenderTests(unittest.TestCase): + def test_three_named_views_have_fixed_layout_and_pending_status(self): + vertices, quads = _occluding_quads() + with tempfile.TemporaryDirectory() as directory: + metadata = render.render_views(vertices, quads, Path(directory) / "views.png", + "Pelvis transition", "NOT APPRAISED") + self.assertEqual((metadata["width"], metadata["height"]), (1600, 550)) + self.assertEqual(metadata["views"], ["front", "side", "rear-three-quarter"]) + self.assertEqual(metadata["visual_status"], "pending") + with Image.open(metadata["output_path"]) as image: + self.assertEqual((image.mode, image.size), ("RGB", (1600, 550))) + + def test_z_buffer_is_order_independent_for_overlapping_quads(self): + vertices, quads = _occluding_quads() + with tempfile.TemporaryDirectory() as directory: + first = Path(directory) / "first.png" + second = Path(directory) / "second.png" + nearer = Path(directory) / "nearer.png" + farther = Path(directory) / "farther.png" + render.render_views(vertices, quads, first, "same", "PASS technical") + render.render_views(vertices, tuple(reversed(quads)), second, "same", "PASS technical") + render.render_views(vertices, (quads[1],), nearer, "same", "PASS technical") + render.render_views(vertices, (quads[0],), farther, "same", "PASS technical") + # Reversing the face order does not change the visible nearer surface. + with Image.open(first) as first_image, Image.open(second) as second_image: + self.assertEqual(first_image.tobytes(), second_image.tobytes()) + # The tilted nearer quad wins at an interior sample, and its colour + # differs from the farther horizontal quad. + with Image.open(first) as first_image, Image.open(nearer) as nearer_image, Image.open(farther) as farther_image: + self.assertEqual(first_image.getpixel((267, 280)), + nearer_image.getpixel((267, 280))) + self.assertNotEqual(first_image.getpixel((267, 280)), + farther_image.getpixel((267, 280))) + + def test_repeated_render_is_byte_deterministic_and_underside_is_separate(self): + vertices, quads = _occluding_quads() + with tempfile.TemporaryDirectory() as directory: + first = Path(directory) / "first.png" + second = Path(directory) / "second.png" + first_meta = render.render_views(vertices, quads, first, "same", "REJECTED", + underside=True) + second_meta = render.render_views(vertices, quads, second, "same", "REJECTED", + underside=True) + self.assertEqual(first.read_bytes(), second.read_bytes()) + self.assertEqual(Path(first_meta["underside_path"]).read_bytes(), + Path(second_meta["underside_path"]).read_bytes()) + self.assertNotEqual(first_meta["output_path"], first_meta["underside_path"]) + self.assertEqual(first_meta["underside_visible_pixels"] > 0, True) + + def test_explicit_bounds_keep_comparison_frame_and_overlays_make_diagnostic(self): + vertices, quads = _occluding_quads() + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / "views.png" + metadata = render.render_views( + vertices, quads, output, "frame", "NOT APPRAISED", + bounds=((-1.0, -1.0, -1.0), (1.0, 1.0, 1.0)), + overlays=[{"start": [-1.0, 0.0, 0.0], "end": [1.0, 0.0, 0.0], + "color": [210, 40, 40], "label": "hip frame"}], + ) + diagnostic = output.with_name("views-diagnostic.png") + self.assertEqual(metadata["diagnostic_path"], str(diagnostic)) + self.assertTrue(diagnostic.exists()) + self.assertEqual(metadata["bounds"], [[-1.0, -1.0, -1.0], [1.0, 1.0, 1.0]]) + + def test_crop_requires_explicit_opt_in_and_keeps_full_geometry_inputs(self): + vertices = ((-2.0, -0.5, 0.0), (2.0, -0.5, 0.0), + (2.0, 0.5, 0.0), (-2.0, 0.5, 0.0)) + quads = ((0, 1, 2, 3),) + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / "cropped.png" + with self.assertRaises(render.RenderError): + render.render_views(vertices, quads, output, "crop", "NOT APPRAISED", + bounds=((-1.0, -1.0, -1.0), (1.0, 1.0, 1.0))) + metadata = render.render_views( + vertices, quads, output, "crop", "NOT APPRAISED", + bounds=((-1.0, -1.0, -1.0), (1.0, 1.0, 1.0)), allow_crop=True) + self.assertTrue(metadata["allow_crop"]) + self.assertEqual(metadata["triangle_count"], 2) + + def test_nonfinite_vertices_and_invalid_indices_are_rejected(self): + vertices = ((-1.0, -1.0, 0.0), (1.0, -1.0, 0.0), (0.0, 1.0, 0.0), + (-1.0, -1.0, 1.0)) + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / "invalid.png" + with self.assertRaises(render.RenderError): + render.render_views(((float("nan"), 0.0, 0.0), *vertices[1:]), + ((0, 1, 2, 3),), output, "bad", "REJECTED") + with self.assertRaises(render.RenderError): + render.render_views(vertices, ((0, 1, 2, 99),), output, "bad", "REJECTED") + with self.assertRaises(render.RenderError): + render.render_views(vertices, ((0, 1, True, 3),), output, "bad", "REJECTED") + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/pelvis-thigh-transition/tests/test_runner.py b/experiments/pelvis-thigh-transition/tests/test_runner.py new file mode 100644 index 0000000..ed0671d --- /dev/null +++ b/experiments/pelvis-thigh-transition/tests/test_runner.py @@ -0,0 +1,247 @@ +from __future__ import annotations + +import json +import hashlib +from pathlib import Path +import sys +import tempfile +import unittest +from types import SimpleNamespace +from unittest.mock import patch + +HERE = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(HERE)) +import runner + + +def _cube(offset: float = 0.0): + vertices = ( + (-0.6, -0.4, -0.5 + offset), (0.6, -0.4, -0.5 + offset), + (0.6, 0.4, -0.5 + offset), (-0.6, 0.4, -0.5 + offset), + (-0.6, -0.4, 0.5 + offset), (0.6, -0.4, 0.5 + offset), + (0.6, 0.4, 0.5 + offset), (-0.6, 0.4, 0.5 + offset), + ) + quads = ((0, 1, 2, 3), (4, 7, 6, 5), (0, 4, 5, 1), + (1, 5, 6, 2), (2, 6, 7, 3), (4, 0, 3, 7)) + return { + "vertices": vertices, "quads": quads, + "face_owners": ("synthetic",) * len(quads), + "control_owners": ("synthetic",) * len(vertices), + "loops": {"synthetic": (0, 1, 2, 3)}, + "base_stencils": tuple((((index, 1.0),),) for index in range(len(vertices))), + "frames": {"synthetic": {"axis": (0.0, -1.0, 0.0)}}, + "metadata": {"synthetic": True}, + } + + +def _inputs(path: Path): + cases = [ + {"id": "standard_neutral_reference", "role": "mandatory", "components": {"x": 0.0}, + "attachments": {"left": {"centre": [-0.2, 0.0, 0.0], "knee": [-0.2, -0.3, 0.0]}, + "right": {"centre": [0.2, 0.0, 0.0], "knee": [0.2, -0.3, 0.0]}}}, + {"id": "ordinary_human_reference", "role": "mandatory", "components": {"x": 0.0}, + "attachments": {}}, + {"id": "neutral_pelvis_width", "role": "predeclared_neutral_perturbation", "components": {"x": 0.1}, + "attachments": {}}, + {"id": "neutral_invalid_close_thick", "role": "predeclared_neutral_perturbation", "components": {"x": 1.0}, + "attachments": {}}, + ] + path.write_text(json.dumps({"perturbation_case_ids": [cases[2]["id"], cases[3]["id"]], "cases": cases}), encoding="utf-8") + + +class RunnerTests(unittest.TestCase): + def test_depth12_gate_report_preserves_diagnostics_and_technical_outcome(self): + # The barycentric scalars are at depth 12 (report root is depth 0). + # Frame/ray/hit nesting previously exceeded the serialization limit 8. + for passed in (True, False): + with self.subTest(technical_pass=passed): + report = { + "schema": "pelvis-thigh-transition/checks-v1", + "technical": { + "pass": passed, + "levels": [{"frames": {"left": {"containment": { + "rays": {"+X": {"hits": [{ + "barycentric": [0.25, 0.25, 0.5], + "distance": 0.125, + "face_pair": [17, 42], + "pass": passed, + }]}} + }}}}], + }, + "render": {"safe": True}, + } + outcome, retained = runner._check_outcome(report) + self.assertEqual(outcome, "technical_pass" if passed else "rejected") + self.assertEqual(retained, report) + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "case-report.json" + runner._write_json(path, retained) + self.assertEqual(json.loads(path.read_text(encoding="utf-8")), report) + + def test_bounded_serialization_rejects_depth65_after_accepting_depth64(self): + value = {"pass": False} + for _ in range(63): + value = [value] + self.assertEqual(runner._bounded(value), value) + with self.assertRaisesRegex(runner.RunnerError, "nesting exceeds the bounded depth"): + runner._bounded([value]) + + def _mock_apis(self, check_outcome=None, comparison_pass=True): + calls = [] + + def build(components, attachments, diagnostic=False): + calls.append(("build", components, attachments, diagnostic)) + return {"id": "synthetic"} + + def evaluate(built, levels=2): + calls.append(("evaluate", built, levels)) + mesh = _cube() + return [mesh, mesh, mesh] + + def check(case, levels): + calls.append(("check", case, levels)) + if check_outcome is not None: + return check_outcome + return {"schema": "synthetic-checks-v1", + "outcome": "reject" if "invalid" in case["id"] else "pass", + "numeric": "synthetic"} + + def compare(base_case, base_levels, case, levels): + calls.append(("compare", base_case, base_levels, case, levels)) + return {"schema": "synthetic-perturbation-v1", "pass": comparison_pass} + + construction = SimpleNamespace(build=build, evaluate=evaluate) + checker = SimpleNamespace(check_case=check, + compare_perturbation=compare) + return patch.multiple(runner, construction=construction, checks=checker, + _validate_registered_inputs=lambda *_args: None), calls + + def test_mock_run_persists_unverified_final_and_complete_mesh_metadata(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + inputs, output = root / "inputs.json", root / "run" + _inputs(inputs) + context, calls = self._mock_apis() + with context: + report = runner.run(inputs, output, attempt=0, workers=1) + invalid = output / "cases" / "case-03-neutral_invalid_close_thick" + self.assertEqual(report["case_count"], 4) + self.assertEqual(report["outcome"], "pass") + self.assertTrue((output / "inputs.json").is_file()) + self.assertTrue((output / "runner-source.py").is_file()) + self.assertTrue((output / "stable-manifest.json").is_file()) + mesh = json.loads((invalid / "mesh-level-2.json").read_text(encoding="utf-8")) + for key in ("face_owners", "control_owners", "loops", "base_stencils", "frames", "metadata"): + self.assertIn(key, mesh) + self.assertTrue((invalid / "lowercrop-unverified.png").is_file()) + self.assertTrue((invalid / "lowercrop-unverified-underside.png").is_file()) + self.assertTrue((invalid / "lowercrop-final.png").is_file()) + self.assertTrue((invalid / "fullroot-final.png").is_file()) + self.assertTrue((invalid / "case-report-unverified.json").is_file()) + self.assertTrue((invalid / "case-report.json").is_file()) + self.assertEqual(report["cases"][3]["outcome"], "rejected") + self.assertTrue(report["cases"][3]["expected_rejection_met"]) + self.assertEqual(calls[0][0:2], ("build", {"x": 0.0})) + self.assertIs(calls[0][3], True) + self.assertEqual(calls[1][0:3], ("evaluate", {"id": "synthetic"}, 2)) + + def test_bounds_and_comparison_are_input_driven_and_manifest_is_stable(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + inputs, output_a, output_b = root / "inputs.json", root / "a", root / "b" + _inputs(inputs) + with self._mock_apis()[0]: + first = runner.run(inputs, output_a, attempt=1, workers=1) + with self._mock_apis()[0]: + second = runner.run(inputs, output_b, attempt=1, workers=1) + self.assertEqual(first["perturbation_comparisons"][0]["outcome"], "compared") + self.assertEqual(first["cases"][0]["bounds"]["lowercrop"], + [[-2.4, -2.7, -1.3], [2.4, 1.0, 1.3]]) + self.assertTrue(first["cases"][1]["bounds"]["physical_scale"].startswith("human reference")) + self.assertEqual((output_a / "stable-manifest.json").read_bytes(), + (output_b / "stable-manifest.json").read_bytes()) + + def test_failed_valid_comparison_propagates_to_root_and_is_not_compared(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + inputs, output = root / "inputs.json", root / "run" + _inputs(inputs) + with self._mock_apis(comparison_pass=False)[0]: + report = runner.run(inputs, output, attempt=0, workers=1) + self.assertEqual(report["outcome"], "failed") + self.assertEqual(report["comparison_failure_count"], 2) + self.assertEqual(report["perturbation_comparisons"][0]["outcome"], "failed") + self.assertFalse(report["perturbation_comparisons"][0]["comparison_pass"]) + + def test_missing_outcome_is_an_error_not_an_implicit_pass(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + inputs, output = root / "inputs.json", root / "run" + _inputs(inputs) + with self._mock_apis(check_outcome={"schema": "synthetic-checks-v1"})[0]: + report = runner.run(inputs, output, attempt=0, workers=1) + self.assertTrue(all(case["outcome"] == "error" for case in report["cases"])) + self.assertEqual(report["outcome"], "failed") + self.assertTrue(any(item["phase"] == "checks.check_case" + for item in report["cases"][0]["exceptions"])) + + def test_missing_checker_fails_before_output(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + inputs, output = root / "inputs.json", root / "run" + _inputs(inputs) + construction = SimpleNamespace(build=lambda *_args, **_kwargs: {}, + evaluate=lambda *_args, **_kwargs: []) + with patch.object(runner, "construction", construction), patch.object(runner, "checks", None), self.assertRaises(runner.RunnerError): + runner.run(inputs, output, attempt=0, workers=1) + self.assertFalse(output.exists()) + + def test_missing_construction_or_build_fails_closed_before_output(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + inputs, output = root / "inputs.json", root / "run" + _inputs(inputs) + checks = SimpleNamespace(check_case=lambda *_args: {}, + compare_perturbation=lambda *_args: {}) + for construction in (None, SimpleNamespace(evaluate=lambda *_args: [])): + with self.subTest(construction=construction): + with patch.object(runner, "construction", construction), patch.object(runner, "checks", checks), self.assertRaises(runner.RunnerError): + runner.run(inputs, output, attempt=0, workers=1) + self.assertFalse(output.exists()) + + def test_output_must_be_absent(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + inputs, output = root / "inputs.json", root / "run" + _inputs(inputs) + output.mkdir() + with self._mock_apis()[0], self.assertRaises(runner.RunnerError): + runner.run(inputs, output, attempt=0, workers=1) + + def test_modified_or_missing_registered_inputs_fail_before_output(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + inputs, output = root / "inputs.json", root / "run" + _inputs(inputs) + with self.assertRaises(runner.RunnerError): + runner.run(inputs, output, attempt=0, workers=1) + self.assertFalse(output.exists()) + inputs.unlink() + with self.assertRaises(runner.RunnerError): + runner.run(inputs, output, attempt=0, workers=1) + self.assertFalse(output.exists()) + + def test_cases_py_exact_document_check_is_required_after_digest(self): + raw = b'{"registered":true}\n' + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "inputs.json" + path.write_bytes(raw) + fake_cases = SimpleNamespace(main=lambda argv: (_ for _ in ()).throw(ValueError("modified"))) + with patch.object(runner, "REGISTERED_INPUT_SHA256", hashlib.sha256(raw).hexdigest()), \ + patch.object(runner, "cases", fake_cases), \ + self.assertRaises(runner.RunnerError): + runner._validate_registered_inputs(path, raw) + + +if __name__ == "__main__": + unittest.main()