Skip to content

[RTR] feat(models): add name_q, name_qdot and normalize_q to the BioModel protocol (refs #1037) - #1118

Merged
pariterre merged 36 commits into
pyomeca:masterfrom
Ipuch:feat/configuration-manifold-protocol
Oct 26, 2026
Merged

pariterre merged 36 commits into
pyomeca:masterfrom
Ipuch:feat/configuration-manifold-protocol

Conversation

@Ipuch

@Ipuch Ipuch commented Oct 20, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

First part of the configuration-manifold refactor of #1037. Models should describe their configuration space Q (nb_q coordinates) and its tangent space TQ (nb_qdot), so that the OCP, dynamics and plot layers can stop parsing DoF names (QuatW, Rot, Trans) and reading nb_quaternions.
This PR contains the import fix, characterization tests with bug reproducers, two bug fixes, and the new protocol members with Euclidean defaults. No consumer is migrated yet (later PRs).

Refs #1037.
Depends on #1114 (must merge first).

Commits (7)

Import fix

  • 82352928 fix(models): defer annotations so bioptim imports on Python <= 3.13. f6f8af26 moved the biorbd imports under TYPE_CHECKING while some annotations are still evaluated at definition time (NameError: GeneralizedCoordinates). Adds from __future__ import annotations to 9 modules (dynamics/dynamics_functions.py, models/biorbd/{biorbd_model,holonomic_biorbd_model,model_dynamics,multi_biorbd_model,variational_biorbd_model}.py, models/pinocchio/pinocchio_model.py, models/protocols/{biomodel,holonomic_biomodel}.py).

Tests (new file tests/shard6/test_configuration_manifold.py, no production code)

  • 0afd33f5 test: characterize q/qdot/tau names and shapes for Euclidean and quaternion models (Biorbd quaternion torque model, free-floating base, quaternion norm after RK4, custom model, Pinocchio free-flyer / spherical / RUBX).
  • a43da0a0 test: add strict-xfail reproducers for known quaternion bugs. Each asserts the correct behaviour and is xfail(strict=True), so fixing a bug turns the test red until the marker is removed.

Fixes

  • 319db300 fix(dynamics): size qddot_joints with nb_qdot instead of nb_q (ConfigureVariables.configure_qddot_joints; B2).
  • 2ceb5296 fix(dynamics): use reshape_qdot for dq/dt in joint-acceleration dynamics (JointAccelerationDynamics, in dxdt and in the collocation defect; B2b). Removes the B2 and B2b xfails (the B2 test also needs the B2b fix).

Protocol

  • 7d316c6b feat(models): add name_q, name_qdot and normalize_q to the BioModel protocol (models/protocols/biomodel.py).
  • b58b405d feat(models): Euclidean defaults through StateDynamics (new models/protocols/configuration_space.py, StateDynamics in dynamics/state_space_dynamics/abstract_dynamics.py, new tests/shard6/test_configuration_space_defaults.py).

API changes

New BioModel members:

Member Meaning Default
name_q one label per configuration coordinate (length nb_q) protocol stub returns (); EuclideanConfigurationSpace: tuple(name_dofs)
name_qdot one label per tangent coordinate (length nb_qdot); also used for qddot, qdddot, tau, taudot, residual_tau protocol stub returns (); Euclidean: name_q; raises NotImplementedError if nb_q != nb_qdot
normalize_q() CasADi Function projecting q onto Q (e.g. unit quaternions) protocol: docstring-only stub (like the other function members); Euclidean: identity q -> q, usable with MX and SX
nb_q, nb_qdot (docstrings only on the protocol) size of Q / of TQ Euclidean: len(name_q) for both (avoids recursion through name_qdot)

name_dofs is documented as an alias of name_q, and reshape_qdot as "(q, qdot, parameters) -> dq/dt (size nb_q)". Docstrings of the protocol also state the quaternion ordering conventions (Biorbd: x, y, z in place in the segment block and all w at the end of q; Pinocchio: x, y, z, w contiguous).

Mixin and MRO: the new EuclideanConfigurationSpace (not re-exported from bioptim/__init__.py, internal) is a base of StateDynamics, so every Backend + dynamics mixin model and every custom model gets the Euclidean defaults. The mixin has no __init__ (safe for cooperative inheritance) and normalize_q is not wrapped in cache_function (custom models have no _cached_functions). Backends come first in the MRO (class TorqueBiorbdModel(BiorbdModel, TorqueDynamics)), so their own name_q/nb_q/... win; test_no_mro_clash checks that no exported class is shadowed. Until the Biorbd backend implements the new members (later PR), name_qdot of a Biorbd quaternion model raises NotImplementedError; nothing reads it yet.

Deprecations: nb_quaternions and normalize_state_quaternions are marked deprecated in their protocol docstrings only. There is no runtime warning yet: one deprecation wave is planned later, together with name_dofs.

Breaking? No, so docs/breaking_change_template.md is not used. New members are additive with defaults and nothing in the package consumes them yet; the only behaviour change (joint-acceleration dynamics, qddot_joints sizing) concerns quaternion models, which could not build such an OCP before (B2 raised IndexError), and is identical for Euclidean models.

Bugs

Fixed here

ID Bug
B2 JointAccelerationDynamics + quaternions: IndexError in configure_qddot_joints (nb_q used instead of nb_qdot)
B2b Joint-acceleration dynamics used qdot as dq/dt instead of reshape_qdot (dynamics and collocation defect)

Reproduced as strict xfail (10 tests, all asserting the correct behaviour)

ID Bug
B3 Two phases with different models: phase-mapping indices into the cross-phase union are used on per-phase names (IndexError)
B4 (x3) Pinocchio free-flyer: OCP declares q with nb_qdot instead of nb_q; quaternion not kept unit after a solve; reshape_qdot returns qdot (nv) instead of dq/dt (nq)
B5 (x3) Pinocchio nb_quaternions over-counts RUBX and Planar joints; RX+RUBX normalization gives NaN
B6 residual_tau of a quaternion model is sized/named 6 instead of 12 (OCP does not build)
B7 Plot phase mappings of qdot/tau have nb_q entries for nb_qdot-sized variables
B10 Quaternion root with a free-floating base (out of scope of #1037, follow-up)

Excluded or deferred

Tests run

Environment: Python 3.13.15, casadi 3.7.2, biorbd_casadi 1.12.2, pinocchio 4.0.0 (bioptim-pin conda env), black 26.5.1.

python -m pytest -q -p no:cacheprovider tests/shard6/test_configuration_manifold.py tests/shard6/test_configuration_space_defaults.py tests/shard5/test_custom_model.py
  • On the branch tip b58b405d as pushed: collection fails, 3 errors in 0.77s (NameError: name 'Bool' is not defined from abstract_dynamics.py).
  • On a copy of b58b405d where only the import from ...misc.parameters_types import Bool, CXOptional is restored in abstract_dynamics.py (not committed): 17 passed, 10 xfailed, 7 warnings in 2.69s (the 10 xfails are the strict reproducers listed above).
  • black -l120 --check on the 15 changed files: clean.
  • The full CI suite (shards 1 to 6) has not been run on this version and will be run when the PR leaves draft. Numbers from the earlier stack (based on master e7ee2f73) are not claimed here.

Remaining TODO before [RTR]

  • Restore Bool in the imports of bioptim/dynamics/state_space_dynamics/abstract_dynamics.py (still used by has_continuous_dynamics; removed by mistake in b58b405d). Blocker: import bioptim fails at the tip.
  • agent-context/OVERVIEW.md, section "Things worth knowing": remove the note saying import bioptim fails before Python 3.14 (fixed by 82352928; RULES.md asks for it in the same PR).
  • Add NumPy-style docstrings to the EuclideanConfigurationSpace properties/method (name_q, nb_q, nb_qdot, name_qdot, normalize_q), as required by RULES.md.
  • Run the full CI suite when the PR leaves draft; document the new protocol members in agent-context/OVERVIEW.md ("How models and dynamics fit together").

Checklist

All Submissions:

New Feature Submissions:

  1. Does your submission pass the tests (if not please explain why this is intended)? (the tip fails at import because of the missing Bool import; passes once fixed, see "Tests run")
  2. Did you write a proper documentation (docstrings and ReadMe) (protocol members documented; EuclideanConfigurationSpace docstrings and the OVERVIEW note are TODO; no README change, the public API is unchanged)
  3. Have you linted your code locally prior to submission (using the command: black . -l120 --exclude "external/*")? (checked on the 15 changed files with black 26.5.1)

Changes to Core Features:

  • Have you added an explanation of what your changes do and why you'd like us to include them?
  • Have you written new examples for your core changes, as applicable? (no example yet, see TODO)
  • Have you written new tests for your core changes, as applicable? (test_configuration_manifold.py, test_configuration_space_defaults.py)

This change is Reviewable

Ipuch and others added 30 commits October 20, 2026 18:02
…e None when it does not modify the model

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…declare the parameters its discretisation needs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…eter and that a parameter can be declared without model function

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nd qdot_end instead of the variational ocp, removing the dummy qdot_function

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…t model function, user parameters are not mutated and reserved names are rejected

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… checking so dynamics does not depend on optimization at runtime

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… by discrete equations can skip the ode configuration

ConfigureProblem.initialize no longer calls the dynamics of a model that
declares has_continuous_dynamics as False, so nlp.dynamics_func and
nlp.dynamics_defects_func stay None instead of being filled by a dummy ode.
The default is True, hence no change for the existing models.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… OdeSolver.VARIATIONAL under their own nlp attributes

The three casadi functions were built by ConfigureVariables.configure_variational_functions
through the model extra configuration and stored in nlp.dynamics_defects_func,
an attribute also read by the ode solvers as the implicit ode with another
signature, and in two ad-hoc attributes. They are now built by the solver when
it prepares the integrators and stored in nlp.variational_three_nodes_func,
nlp.variational_first_node_func and nlp.variational_last_node_func, declared
in NonLinearProgram. The variational ocp reads the new attributes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… ode solver and do not hijack the dynamics defects

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… with an honest placeholder integrator

OdeSolver.VARIATIONAL no longer subclasses RK (it had an irrelevant
n_integration_steps) and declares its properties explicitly: direct shooting,
one cx, no defect type, and the new integrates_ode property set to False.
The integrator is no longer a fake RK4 that silently integrated a null ode:
it only describes one value per node (no intermediate point) and raises a
NotImplementedError if it is called.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…de solver that integrates an ode for a model without one

VariationalTorqueDynamics declares has_continuous_dynamics as False, so its
dynamics (which returned dxdt equal to zero only to satisfy the framework) is
never called and nlp.dynamics_func stays None. dynamics now raises a
NotImplementedError, as StateDynamics requires it to exist. Using such a model
with an ode solver whose integrates_ode is True now raises a clear ValueError
instead of integrating a null ode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ion of an ode solver without ode and use the nodes as stepwise states

sol.integrate returned plausible but wrong values for OdeSolver.VARIATIONAL,
which integrated a null ode. It now raises a NotImplementedError. The stepwise
states of such a solver are the decision states, as the states have no
intermediate point (stepwise_time already equals decision_time since the
placeholder integrator has a single time per node), instead of an invented
ramp of sub-steps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… stepwise outputs are the nodes and that print and graphs still work

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…AL a fake ode solver

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…e states inside a phase

OdeSolverBase.declare_continuity holds the state continuity (constraint or
objective) that OptimalControlProgram._declare_inner_phase_continuity used to
build, and OdeSolver.COLLOCATION adds the helper constraint on the duplicated
starting point. The ocp keeps the skip_continuity check and the continuity
between phases. The declared penalties are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…apezoidal and collocation, as constraint or objective

These pass unchanged before and after the declare_continuity hook.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…stead of CUSTOM

PenaltyOption already names a custom penalty after its function, but the
multinode list overwrote it with the name of the CUSTOM enum for all of them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s from OdeSolver.VARIATIONAL instead of the variational ocp

OdeSolver.VARIATIONAL.declare_continuity registers the N-1 three-node
equations and the initial and final boundary conditions as internal multinode
constraints of its own phase (nlp.phase_idx, not 0). The variational ocp no
longer skips the continuity, builds these constraints nor copies the multinode
constraints of the user, that are now passed untouched. The penalties are
now named after their function.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…aints declared by the ode solver

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…RIATIONAL and use the control type of the ocp

The model no longer stores the discretization: discrete_approximation,
control_type and control_discrete_approximation are removed from the
constructors of VariationalBiorbdModel and VariationalTorqueBiorbdModel and
given to its discretization methods (explicit arguments, keyword-only for
the composite equations so that the position of lambdas is unchanged). The
numbers computed by the model for a given rule are unchanged, which the
updated model test checks.

OdeSolver.VARIATIONAL(discrete_approximation, control_discrete_approximation)
holds the rules and passes them, together with nlp.control_type, when it
builds the discrete functions. It raises a NotImplementedError for a control
type that cannot provide the controls of the last node needed by the final
condition (only LINEAR_CONTINUOUS and CONSTANT_WITH_LAST_NODE are supported).
VariationalOptimalControlProgram accepts an optional ode_solver to choose them.

This intentionally changes the results of the variational ocp: the model used
to default to ControlType.CONSTANT while the ocp forces LINEAR_CONTINUOUS, so
the forcing was discretized as piecewise constant whereas the controls are
linear. The linear control approximation is now really applied. The regression
values are re-derived in the next commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…inear control approximation is applied

Each case was solved with MX and SX: IPOPT reports a converged optimal
solution (status 0, 28 iterations for the pendulum and 26 with the holonomic
constraint) and MX and SX agree to 1e-13. The boundary conditions hold: q start
and end are exact, qdot_start and qdot_end are 0 (pendulum) or +-0.01 within the
bounds of the example (holonomic).

Pendulum (old -> new):
- q[:, 10]: [-0.325654, 0.514318] -> [-0.227192, 0.417948]
- tau[:, 0]: 9.952650 -> 11.973897
- tau[:, 20]: 1.326124 -> -19.644559
- tau[:, -4]: -24.871395 -> 9.998765

Pendulum with holonomic constraint (old -> new):
- lambdas[:, 0]: -16.478903 -> -12.569973
- lambdas[:, -1]: 7.242878 -> 22.847931
- q[:, 10]: [-0.530772, 0, 0.705247] -> [-0.232981, 0, 0.430259]
- tau[:, 0]: 10.502854 -> 11.370709
- tau[:, 20]: 12.717297 -> -18.763179
- tau[:, -4]: -19.131171 -> 9.347683
- qdot_start: [0.01000001, 0, 0.01000001] unchanged to 1e-8
- qdot_end: [-0.01000001, 0, 0.01000001] unchanged to 1e-8

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…of the options and that the quadrature rules reach the discrete equations

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…e test runs on headless CI

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
f6f8af2 moved the biorbd imports under TYPE_CHECKING, but the annotations
that reference them (e.g. GeneralizedCoordinates in HolonomicBioModel,
`-> biorbd` in biorbd_model._import_biorbd) are still evaluated at
definition time on Python <= 3.13, so `import bioptim` raised NameError.
Postpone annotation evaluation in every module that relies on
TYPE_CHECKING-only names.

Prerequisite for pyomeca#1037.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ernion models

Pin the current behaviour of q, qdot and tau sizes and labels for Euclidean and quaternion biorbd models, the free-floating-base quaternion example, quaternion normalization in the integrator, custom models and Pinocchio normalization, so that the configuration-manifold refactor can be checked against it.

Refs pyomeca#1037

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add one strict xfail test per known bug (B2, B2b, B3, B4, B5, B6, B7, B10), each asserting the correct behaviour so that it flips to XPASS (and fails the suite) as soon as the bug is fixed and the marker must be removed.

Refs pyomeca#1037

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
qddot lives in the tangent (velocity) space of size nb_qdot. Slicing the
names and building the axes mapping with nb_q breaks models with quaternions.
The B2 reproducer still xfails here because it is blocked by the dq/dt
shape bug fixed in the next commit.

Refs pyomeca#1037

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Ipuch and others added 6 commits October 20, 2026 18:05
dq/dt was set to qdot, which has the wrong size for models with quaternions
(nb_q > nb_qdot). Use DynamicsFunctions.compute_qdot (model.reshape_qdot),
as torque dynamics does, for both dxdt and the collocation defects.
Also unblocks the B2 reproducer, whose xfail is removed here as well.

Refs pyomeca#1037

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rotocol

Protocol stubs and docstring updates only; nb_quaternions and
normalize_state_quaternions are documented as deprecated.

Refs pyomeca#1037

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…StateDynamics

Add the EuclideanConfigurationSpace mixin (name_q, name_qdot, nb_q, nb_qdot,
identity normalize_q) inherited by StateDynamics, with tests including an
MRO/shadowing check.

Refs pyomeca#1037

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The rebase of b58b405 onto feat/variational-solver-quadrature dropped Bool
from the parameters_types import of abstract_dynamics.py while
StateDynamics.has_continuous_dynamics still annotates its return with it, so
`import bioptim` raised NameError.

Refs pyomeca#1037

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add module and NumPy-style docstrings for name_q, nb_q, nb_qdot, name_qdot, normalize_q.

Refs pyomeca#1037

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…model protocol

Document nb_q/name_q, nb_qdot/name_qdot, normalize_q and EuclideanConfigurationSpace in OVERVIEW.md.

Refs pyomeca#1037

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Ipuch Ipuch added enhancement New feature or request 15 minutes review A 15 minutes PR, including careful reading of the code by a human and revision guidelines. labels Oct 20, 2026
@Ipuch Ipuch changed the title [WIP] feat(models): add name_q, name_qdot and normalize_q to the BioModel protocol (refs #1037) [RTR] feat(models): add name_q, name_qdot and normalize_q to the BioModel protocol (refs #1037) Oct 20, 2026
@pariterre
pariterre marked this pull request as ready for review October 20, 2026 20:27
@pariterre
pariterre enabled auto-merge October 20, 2026 20:27
@codecov

codecov Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.37097% with 9 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.37%. Comparing base (89d43cc) to head (4eb13c6).
⚠️ Report is 38 commits behind head on master.

Files with missing lines Patch % Lines
bioptim/dynamics/integrator.py 84.00% 4 Missing ⚠️
bioptim/models/biorbd/variational_biorbd_model.py 88.23% 2 Missing ⚠️
bioptim/models/protocols/biomodel.py 77.77% 2 Missing ⚠️
...tate_space_dynamics/torque_dynamics_variational.py 83.33% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1118      +/-   ##
==========================================
+ Coverage   78.25%   78.37%   +0.12%     
==========================================
  Files         198      199       +1     
  Lines       21747    21882     +135     
==========================================
+ Hits        17019    17151     +132     
- Misses       4728     4731       +3     
Flag Coverage Δ
unittests 78.37% <96.37%> (+0.12%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Ipuch

Ipuch commented Oct 20, 2026 •

Copy link
Copy Markdown
Collaborator Author
  • EuclidianSpace object is not the good approach
  • Instead name_dofs_derivative by default name_dofs
  • EuclidianSpace should be in a TorqueDynamics as plain methods, otherwise we don't have a fully generic class for any ODE.

@pariterre pariterre left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

:lgtm:

@pariterre reviewed 34 files and all commit messages, and made 1 comment.
Reviewable status: :shipit: complete! all files reviewed, all discussions resolved (waiting on Ipuch).

@pariterre
pariterre merged commit 7e418fe into pyomeca:master Oct 26, 2026
27 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

15 minutes review A 15 minutes PR, including careful reading of the code by a human and revision guidelines. enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants