Skip to content

Hamiltonians of a model: pseudo_hamiltonian(ocp), hamiltonian(ocp[, u]) - #538

Merged
ocots merged 12 commits into
mainfrom
feat/532-model-hamiltonians
Nov 25, 2026
Merged

ocots merged 12 commits into
mainfrom
feat/532-model-hamiltonians

Conversation

@ocots

@ocots ocots commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

Closes #532. PR B of the plan tracked in #536.

Public getters for the Hamiltonians of an optimal control problem, as methods of the CTBase.Data generic functions. They replace the private builders of CTFlows, which will use them in a follow-up.

Conventions: ct-conventions v0.14.0, ct-agents v0.5.0.

Phases

  • B1: getters without constraints
    • pseudo_hamiltonian(ocp; p0)
    • hamiltonian(ocp; p0) for a control-free problem
    • hamiltonian(ocp, u; p0)
  • B2: constraints by label, in the dual convention of the solution
    • pseudo_hamiltonian(ocp; constraints=…)
    • hamiltonian(ocp, u; multipliers=…)
  • B3: tests of B2: units, spies, AD, non-regression, integration
  • B4: documentation: a docs page, docstrings, examples, CHANGELOG

Each phase is one commit with an explanatory comment.

Depends on control-toolbox/CTBase.jl#663 (not released yet)

Project.toml has a temporary [sources] entry that points CTBase to the branch of control-toolbox/CTBase.jl#663. It serves for local testing and for the CI of this PR.

  • To remove before merge, together with raising the compat to CTBase = "0.30.15" once that version is released.
  • Julia 1.10 ignores [sources]. A CI job on 1.10 will fail until then.

Release

No release from this PR alone. CTBase 0.30.15 and CTModels 0.21.3 come after the ecosystem validation described in #536.

🤖 Generated with Claude Code

…rs (B1)

- Data.pseudo_hamiltonian(ocp; p0): H̃ = p·f + p0·ℓ as a CTBase PseudoHamiltonian
  (requires a control).
- Data.hamiltonian(ocp; p0): Hamiltonian of a control-free problem.
- Data.hamiltonian(ocp, u; p0): ComposedHamiltonian with a DynClosedLoop law or a
  raw function (arity checked).
- p0 defaults to -1 (:min) / +1 (:max), 0 is the abnormal case, a sign that
  contradicts the criterion is rejected (SGN4).
- Functors moved from CTFlows (same behaviour, zero-filled buffer); the getters
  are methods of the CTBase.Data generic functions, re-exported by Models.
- Tests (unit, spies, AD, type stability, golden values, integration, errors),
  JET hot path; ForwardDiff added to the test deps.
- [sources] points CTBase to control-toolbox/CTBase.jl#663 until its release
  (to be removed before merge).

Refs #532, #536

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

ocots commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Phase B1 — getters without constraints (7b41422)

API

Call Model Returns
pseudo_hamiltonian(ocp; p0) with control Data.PseudoHamiltonian, H̃ = p·f + p⁰ℓ
hamiltonian(ocp; p0) control-free Data.Hamiltonian, H = p·f + p⁰ℓ
hamiltonian(ocp, u; p0) with control Data.ComposedHamiltonian, H = H̃(…, u(t,x,p,v), …)
  • Generic functions. These are methods of CTBase.Data.pseudo_hamiltonian and CTBase.Data.hamiltonian, re-exported by CTModels.Models, so Models.pseudo_hamiltonian === Data.pseudo_hamiltonian.
  • p0 (SGN4): -1 for :min and +1 for :max by default, 0 for the abnormal case.
    • A p0 whose sign contradicts the criterion raises IncorrectArgument, and so does NaN or Inf.
    • min ∫ℓ and max ∫(−ℓ) give the same pseudo-Hamiltonian; this is tested.
  • u is a Data.DynClosedLoop law, or a raw function.
    • A raw function gets the traits of the problem, and its arity is checked when it has a single method (code moved from CTFlows).
    • An open-loop or closed-loop law raises IncorrectArgument.
  • Errors in the wrong case (PreconditionError): pseudo_hamiltonian and hamiltonian(ocp, u) on a control-free model point to hamiltonian(ocp); hamiltonian(ocp) on a model with a control points to hamiltonian(ocp, u).

Implementation

The functors PseudoHamiltonianFunction and HamiltonianFunction come from CTFlows' OCPPseudoHamiltonianFunction and OCPHamiltonianFunction, with the same behaviour:

  • the natural arity is selected by the TD/VD type parameters;
  • x, u and v are passed to the model functions as received (scalar in 1-D, DIM1);
  • t = 0 for an autonomous model, and an empty variable for a model without one;
  • the derivative buffer is built like the state (similar, so it stays on the GPU).

The one change: the buffer is now zero-filled, so a dynamics that does not write every component never reads uninitialised memory.

Cross-check against CTFlows

The old builders CTFlows.Flows._ocp_pseudo_hamiltonian and _ocp_hamiltonian were compared with the new getters on 32 configurations: with or without control, with or without variable, autonomous or not, :min or :max, Lagrange or Mayer only. Over 640 random evaluations, the values are bit-for-bit identical and the wrapper types are the same.

Tests

test/suite/models/test_hamiltonians.jl has 108 tests:

  • Unit: traits and the four arities; Mayer, Lagrange and Bolza; p0 (default, abnormal, scaled, any Real); control-free models; raw and DynClosedLoop laws, with traits joined; a law with several methods, which is not checked.
  • Spies: the dynamics and the Lagrange cost record what they receive. Checked: t = 0, empty variable, scalars stay scalars, t and v forwarded, buffer type (Float32 state gives a Float32 buffer), and the empty control of a control-free model.
  • AD (ForwardDiff, new test dependency): gradients in x, p, u and v against closed forms. The total derivative of hamiltonian(ocp, u) differs from the partial derivative of H̃ as expected.
  • Type stability: @inferred, and the two functors added to the JET hot-path checks.
  • Non-regression: golden values computed by hand.
  • Integration: the Beam problem (boundary constraints, state box, control box), H̃ = p·f + p⁰ℓ computed independently.
  • Contract: re-exports, and nothing exported at the top level (MOD8).
  • Errors: every exception above, with key message fields.

suite/models and suite/meta/test_code_quality (Aqua, piracy, JET) pass: 401/401.

- pseudo_hamiltonian(ocp; constraints=labels): ConstrainedPseudoHamiltonian
  H(t,x,p,u,μ,v) = H̃ + Σ terms, μ an explicit argument stacked in label order.
- hamiltonian(ocp, u; multipliers=label => μ): ComposedConstrainedHamiltonian with
  the multipliers in feedback form (Pair, tuple, NamedTuple or Dict; raw function
  with arity check, or Data.Multiplier).
- Terms in the dual convention of the solution (SGN2/SGN3): y(c − lb), y(ub − c),
  −y(c − b) with b = ub if y > 0 else lb; continuous at y = 0.
- Path constraints, state boxes and control boxes by label; boundary constraints
  and variable boxes rejected; dimension checks at call time.
- Control-free hamiltonian(ocp; multipliers) rejected (PreconditionError).
- Arity check skips variadic functions.
- Fix: re-export the CTBase functions through the CTBase top level (MOD3).
- Tests: kinds of terms, SGN5 path vs box, label order, multiplier forms, spies,
  AD total vs partial, KKT on a saturated control box, JET, golden values, errors.

Refs #532, #536

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

ocots commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Phase B2 — constraints by label (804108a), with its tests

API

H = pseudo_hamiltonian(ocp; constraints=(:vmax, :mixed))   # μ explicit, stacked in label order
H(x, p, u, μ[, v])                                         # Data.ConstrainedPseudoHamiltonian

h = hamiltonian(ocp, u; multipliers=(:vmax => μ1, :mixed => μ2))   # μ in feedback form
h(x, p[, v])                                               # Data.ComposedConstrainedHamiltonian
  • Which labels. Path constraints (state, control or mixed), state boxes and control boxes are accepted by label.

    • A boundary constraint or a variable box raises IncorrectArgument: they give the transversality conditions, not a term of H.
    • An unknown label, or a label given twice, raises IncorrectArgument.
  • The term of each label, component by component, uses the sign convention of the duals of a solution (SGN2, SGN3):

    Bounds of the component Term Multiplier y
    lower only y (c − lb) y ≥ 0
    upper only y (ub − c) y ≥ 0
    both, or an equality −y (c − b), b = ub if y > 0, lb otherwise signed
    • This is μ·g, with g ≥ 0 the constraint on its active side and μ ≥ 0.
    • The active side of a constraint with two bounds is read from the sign of y, so it never has to be given; the term is continuous at y = 0.
    • The multiplier is the same object as the dual of the label in a solution, so a direct solution can be compared with an indirect one (SGN5).
    • Labels not given are inactive.
  • multipliers can be a Pair, a tuple or vector of pairs, a NamedTuple or a Dict.

    • Each μ is a Data.Multiplier, or a raw function with the natural arity of the problem (arity checked).
    • The traits of h are the join of those of the problem, the law and the multipliers.
  • Dimensions are checked at the call: the stacked μ, and each multiplier in feedback form against its constraint.

  • Control-free problem: hamiltonian(ocp; multipliers) raises PreconditionError, as agreed.

Implementation notes

  • Path constraint values are computed with SubPathConstraint on a vector of rows. Box values go through a small _BoxValue{:state|:control} functor. Both return a vector whatever the dimension, so the hot path stays type-stable.
  • Heterogeneous tuples (one term per label, one multiplier per label) are walked with map, not a loop. JET @test_opt is clean on the constrained call.
  • Arity check: it now also skips variadic functions, besides functions with several methods. The CTFlows version wrongly rejected (args...) -> ….
  • Fix of B1. The re-export used using CTBase.Data: …, which test_no_import rejects (MOD3). It now uses using CTBase: hamiltonian, pseudo_hamiltonian, the names being bound at the CTBase top level. Commit 7b41422 alone fails that test; this commit fixes it.

Tests added to test/suite/models/test_hamiltonians.jl (192 tests in this file)

  • Unit:
    • the term of each kind: lower only, upper only, two bounds with both signs, control box with both signs, a vector label (upper only and an equality);
    • continuity at y = 0; a zero μ gives back H̃;
    • label order and stacking; freeze_multiplier on the result; p0 with constraints.
  • SGN5: x ≥ 0.1 written as a path constraint and as a state box gives the same H.
  • SGN4: min ∫x² and max ∫(−x²) give the same constrained H.
  • Feedback form: every form of multipliers, Data.Multiplier input, trait join with a time-varying multiplier.
  • Control box (KKT): on a saturated arc u = ub, the term and its x and p derivatives vanish (h = h without it). The multiplier is the one of stationarity, μ = ∂H̃/∂u.
  • Spies: a path constraint receives (t, x, u, v), with t = 0, scalars kept as scalars, and an empty v. Each multiplier is called once, with its natural arguments.
  • AD (ForwardDiff): gradients in x, p, u and μ against closed forms. The total derivative of h minus the partial derivative of H is exactly g·∂μ/∂x.
  • Type stability: @inferred on constrained and composed calls; JET @test_opt on a call with four labels of every kind.
  • Non-regression: on the boundary arc of the docs example (x = lb, u = 0, μ = 2x), total = partial = 0, so ṗ = 0; golden values.
  • Errors: boundary and variable box labels (message checked), a label given twice, an unknown label, wrong dimensions (stacked and per multiplier), an unsupported multipliers form, a non-function multiplier, a wrong arity, and constraints on a control-free problem.

Status

The full CTModels suite passes locally: 5655/5655.

B3 is covered by the tests of B1 and B2. What is left is B4: the documentation page, a review of the docstrings, examples and the CHANGELOG.

@ocots ocots added the run ci github-runner Trigger the CI workflow on GitHub-hosted runners label Nov 22, 2026
ocots and others added 2 commits November 22, 2026 21:58
- New page docs/src/model/hamiltonians.md (OCP Model section): pseudo-Hamiltonian,
  sign of p0 (SGN4), Hamiltonian for a control law, constraints by label and the
  dual convention, which constraints enter H, multipliers in feedback form,
  partial vs total derivatives, control-free problems, errors; runnable examples
  on the order-one state-constraint problem.
- Docstrings for every functor call group and helper (DOC1, DOC6); tables with
  stated alignment (SITE19).
- API reference lists hamiltonians.jl and constraint_terms.jl.
- CHANGELOG entries.
- docs/Project.toml: temporary [sources] for CTBase (CTBase.jl#663), to remove
  with the one of Project.toml once CTBase 0.30.15 is released.

Refs #532, #536

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ocots ocots added the run documentation Trigger the Documentation workflow on this PR label Nov 22, 2026
@ocots

ocots commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Phase B4 — documentation (add95d2), and merge of main (b7f07f2)

New page: OCP Model → Hamiltonians (docs/src/model/hamiltonians.md)

Every example on the page runs. They use the problem with a state constraint of order one of the OptimalControl docs: ẋ = u, ∫x² → min, |u| ≤ 1, x ≥ 0.1. The sections are:

  1. The pseudo-Hamiltonian: natural and uniform calls.
  2. The sign of p⁰ (SGN4): a table for :min and :max, the abnormal case, and the error for a wrong sign.
  3. The Hamiltonian for a control law: the law and how its arity is checked (best effort).
  4. Constraints by label:
    • μ as an explicit argument;
    • the table of the dual sign convention;
    • the control box on its bounds;
    • which kinds enter H, and why boundary constraints and variable boxes do not;
    • why a control box is inert in the flow;
    • multipliers in feedback form, on the boundary arc u = 0, μ = 2x.
  5. Partial and total derivatives: what freeze_multiplier gives, and the extra terms of the total derivative.
  6. Control-free problems.
  7. Errors: a table of situations and exceptions.

Docstrings

  • DOC1, DOC6: one docstring per group of call operators (the pseudo-Hamiltonian, Hamiltonian, constrained pseudo-Hamiltonian and stacked-multiplier functors), and docstrings for the helpers and for the side constants _LOWER, _UPPER and _BOTH.
  • SITE19: every new table states the alignment of its columns. ct-conventions v0.15.0 is now pinned on main and merged here.

Other changes

  • hamiltonians.jl and constraint_terms.jl are added to the API reference.
  • CHANGELOG.md: New Features, Documentation and Dependencies entries.
  • docs/Project.toml gets a temporary [sources] for CTBase, for the same reason as Project.toml. Both are to be removed when CTBase 0.30.15 is released.

Checks

  • Docs build locally. The only remaining warnings are two external links to the new CTBase symbols (Data.ComposedConstrainedHamiltonian, Data.multiplier), from the CTBase docstrings shown on the API page. They resolve once CTBase is released, and the build tolerates them meanwhile (warnonly).
  • Full suite: 5655/5655 locally.
  • CI: run ci github-runner and run documentation are set.
    • The Julia 1.10 test job fails: 1.10 ignores [sources], so it loads the released CTBase 0.30.14, which has no hamiltonian. Fail-fast then cancels the other jobs.
    • This is expected until CTBase 0.30.15 is released. Until then, the 1.12 suite above is the reference.

All phases B1–B4 are done. Next in #536 is the validation in the CTFlows worktree: plugging CTFlows onto these getters and running its full suite.

CTFlows calls the Hamiltonians with a Matrix state, one column per point
(CTFlows#358). The derivative buffer is now n × batch for such a state,
as in CTFlows; the value sums the columns, so AD gives one gradient per
column. Found by running the CTFlows suite on the getters.

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

ocots commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Validation in the CTFlows worktree, and a fix for batched states (71ed659)

What was run

CTFlows was plugged onto the getters: _ocp_pseudo_hamiltonian(ocp) and _ocp_hamiltonian(ocp) now call pseudo_hamiltonian(ocp) and hamiltonian(ocp). Its full suite then ran against the CTBase and CTModels branches.

  • First run: 8777 passed, 3 errors, 2 broken (already broken on main).
  • The 3 errors were all batched calls: a Matrix state, one column per point (CTFlows#358). The CTFlows buffer helper has an AbstractMatrix method that allocates n × batch; the one moved here did not.

Fix

  • _buffer_like(::AbstractMatrix, T, n) allocates a zero-filled n × batch buffer. The value sums the columns, so AD gives one gradient per column, exactly as in CTFlows.
  • New tests (test_hamiltonians.jl):
    • a spy checks the buffer shape;
    • the batched value equals the sum of the values of the columns, for the pseudo-Hamiltonian and for a control-free Hamiltonian;
    • the batched gradient equals the gradient of each column.

Checks

  • CTModels suite/models and suite/meta: 621/621.
  • The 3 failing CTFlows files rerun: 228/228.
  • Old against new, with the CTFlows builders as they are on main:
    • unconstrained: 640 evaluations, 0 differences (bit-identical);
    • constrained (path labels, both sides, equality, vector, several labels; H̃ + μ·g, the :partial and :total gradients): 1920 quantities, 0 differences, worst relative gap 7e-16.

The constrained cross-check uses admissible multipliers. With μ < 0 on a two-sided constraint given as label => side, CTFlows keeps the chosen bound while the getters take the bound given by the sign of y. It was decided to keep the dual convention and drop label => side in CTFlows (see #536 and CTFlows#531).

_stacked_multiplier joins the traits of the multipliers with
CTBase.Traits.join_time_dependence and join_variable_dependence
(control-toolbox/CTBase.jl#667) instead of private copies. [sources] points
to CTBase main, where #663 and #667 are merged; the branch of #663 is deleted.

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

ocots commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

Public CTBase trait joins (7714221)

Follow-up of the review in #536 (point 5) and of control-toolbox/CTBase.jl#667, now merged.

Changes

  • The trait join of the stacked multiplier now uses the public functions of CTBase:
    TD = Traits.join_time_dependence(map(Traits.time_dependence, μs)...)
    VD = Traits.join_variable_dependence(map(Traits.variable_dependence, μs)...)
    • It is in _stacked_multiplier.
    • The private copies _join_td and _join_vd of src/Models/constraint_terms.jl are deleted.
    • There is no change of behaviour.
  • [sources], in Project.toml and docs/Project.toml, points to CTBase main.
    • CTBase#663 and CTBase#667 are merged there.
    • The branch feat/constrained-pseudo-hamiltonian it pointed to before is deleted.
    • It stays temporary: it goes away when CTBase 0.30.15 is released.

Checks

  • suite/models and suite/meta: 621/621.
  • Full suite, against CTBase main: 5662/5662.
  • CI: the Julia 1.10 job still fails, because 1.10 ignores [sources]. This lasts until CTBase 0.30.15 is released.

Still open from the review in #536

  • Point 4: a box component adjoined twice through two labels.
  • Point 6: batched states with constraints.
  • Point 7: the cost on the hot path.

CTBase 0.30.15 is registered (control-toolbox/CTBase.jl#669): drop the
[sources] entry and require it in Project.toml and docs/Project.toml.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ocots added a commit to control-toolbox/CTFlows.jl that referenced this pull request Nov 24, 2026
CTBase 0.30.15 is registered (control-toolbox/CTBase.jl#669): drop its
[sources] entry and require it. CTModels stays on the branch of
control-toolbox/CTModels.jl#538 until CTModels 0.21.3 is released.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The bounds of a box component declared under several labels are
intersected, so each label gives the same effective box: adjoining two
of them added its term twice. _constraint_terms now rejects them with an
IncorrectArgument. The docs say that a box label gives the effective
bounds, so a one-sided label can give a two-sided term with a signed
multiplier. Review point 4 of #536.

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

ocots commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

Review of #536: phases 0 and 1 of the plan for points 4, 6 and 7

Plan: phase 0 for CTBase 0.30.15, phase 1 for point 4 (a box component adjoined twice), phase 2 for point 6 (batched states, option A: extend the broadcast contract), phase 3 for point 7 (measure, then guard allocations). Conventions: ct-conventions v0.15.0, ct-agents v0.5.0.

Phase 0: CTBase 0.30.15 (606a425). CTBase 0.30.15 is registered (control-toolbox/CTBase.jl#669), so the [sources] entry is dropped and the compat is CTBase = "0.30.15" in Project.toml and docs/Project.toml. The Julia 1.10 job should now resolve. suite/models and suite/meta pass against the registered release, 621/621. CTFlows#534 got the same change (50883549); its CTModels entry stays until CTModels 0.21.3.

Phase 1: two labels of the same box component (e45b886).

  • _constraint_terms rejects two box labels of the same slot that share a component, with an IncorrectArgument naming both labels and the component. With x₁ ≥ 0, (a) and x₁ ≤ 1, (b), constraints=(:a, :b) used to add the term of 0 ≤ x₁ ≤ 1 twice. Path constraints are not checked: two distinct nonlinear constraints are legitimate.
  • Flow(ocp, law; constraint=(:a, :b)) in CTFlows builds through pseudo_hamiltonian(ocp; constraints=labels), so the same check covers it.
  • Docs (docstrings of pseudo_hamiltonian and hamiltonian, page Hamiltonians): a box label gives the effective, intersected bounds. A label written one-sided can give a two-sided term, with a signed multiplier.
  • Tests: the effective box of :a and :b, disjoint labels (:a, :c), and the error from both getters. suite/models and suite/meta pass, 633/633.

Next: phase 2 (batched states with constraints).

A batched state (a Matrix, one column per point, as in CTFlows batched
flows) is accepted with constraints, as it already was without:
- a box takes the rows of the batched state or control;
- a path constraint fills an n x batch buffer (SubPathConstraint and
  CompositeConstraint{:path} get a matrix method);
- a multiplier is a d x batch matrix, or a number or vector shared by
  all the points; a batched multiplier without one column per point is
  an IncorrectArgument;
- the value sums the points, so the gradient is taken column by column.
The functions of the model are written on the columns, as the dynamics
already was. Review point 6 of #536.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ocots added a commit to control-toolbox/CTFlows.jl that referenced this pull request Nov 24, 2026
A constrained flow (a path constraint and a state box, by label) with a
batched Matrix state gives, column by column, the flow of each point,
in :total and :partial modes. Relies on the batched constrained
Hamiltonians of control-toolbox/CTModels.jl#538.

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

ocots commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

Phase 2: batched states with constraints (review point 6 of #536, option A)

0ba230e. Option A extends the batched contract already used for the dynamics: a quantity of dimension d per point is a d × batch matrix, the functions of the model are written on the columns, and the value of the Hamiltonian is the sum over the points, so its gradient is taken column by column.

  • Boxes: _BoxValue takes the rows of a batched state or control.
  • Path constraints: SubPathConstraint and CompositeConstraint{:path} get a matrix method, so each constraint fills its rows of an n × batch buffer built like the state. That buffer is GPU-friendly, with no loop over the columns.
  • Multipliers: a multiplier is a d × batch matrix, or a number or vector shared by all the points. This holds for pseudo_hamiltonian(ocp; constraints) and for hamiltonian(ocp, u; multipliers).
  • New error: a batched multiplier without one column per point raises an IncorrectArgument. Before, it was a DimensionMismatch or a MethodError.
  • Lagrange cost: it receives the whole matrices and must return the sum over the points, for example 0.5 * sum(abs2, u). The docs say so. A cost that is not written on the columns gives a wrong value, as it already did before this PR.

Tests, compared with the sum of the per-point evaluations:

  • the value with two path constraints, a state box and a control box, and with a single path constraint, whose function gets the buffer itself;
  • the gradient, column by column;
  • a shared multiplier;
  • constraint(ocp, :label) on a batched state;
  • hamiltonian(ocp, u; multipliers);
  • @inferred and JET @test_opt on the batched call;
  • the errors.

Docs: a new section Batched states on the Hamiltonians page, and a sentence in the docstrings.

CTFlows (control-toolbox/CTFlows.jl#534, e51920d4): a constrained flow by label, with a path constraint and a state box, on a Matrix state gives the flow of each point column by column, in :total and :partial modes.

Results: the full CTModels suite passes, 5688/5688.

Next: phase 3, cost on the hot path.

ocots and others added 2 commits November 24, 2026 23:19
The constrained pseudo-Hamiltonian built the empty variable of a problem
without variable twice, and summed the terms of a constraint through a
temporary array. The variable is now built once and shared with the
pseudo-Hamiltonian, and the terms are summed lazily. Allocation
contract in test/suite/meta/test_performance.jl: the CTBase wrappers
allocate what the CTModels functor does, and the Hamiltonian with
multipliers in feedback form what the composition written by hand does.
The duplicate sections of [Unreleased] are merged in the order of CHG2.
Review point 7 of #536.

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

ocots commented Nov 25, 2026

Copy link
Copy Markdown
Member Author

Phase 3: cost on the hot path (review point 7 of #536)

Benchmark. One point call of a constrained flow by label, CTFlows main against the branch of control-toolbox/CTFlows.jl#534 with this PR. BenchmarkTools, 300 samples, reltol = abstol = 1e-10, Julia 1.12.7. The values are identical on both sides. The script is not committed.

Case main: allocs branch: allocs main: median branch: median
1-D, one label (x ≥ 0.1), :total 525 465 (−11 %) 21.1 μs 24.6 μs
1-D, one label, :partial 497 467 (−6 %) 27.1 μs 22.6 μs
2-D, two labels, :total 20946 15468 (−26 %) 594.9 μs 329.4 μs
2-D, two labels, :partial 10256 7154 (−30 %) 234.8 μs 251.0 μs

The allocation counts are deterministic. The times vary by up to about ±25 % between runs on this machine. In an earlier run, the 2-D :partial case was 242 μs on main and 179 μs on the branch. The branch allocates less in every case and is not slower.

Optimisation (304bd97). The benchmark did not show a regression, but two avoidable allocations per evaluation were found while writing the allocation guard:

  • the empty variable of a problem without a variable was built twice, once by _pseudo_H and once for the constraints. It is now built once and shared.
  • the terms of a constraint were summed through a temporary array, sum(_side_term.(…)). The sum is now a lazy broadcast. It still works for batched states.

After this change, a constrained evaluation on the 1-D model allocates exactly what the pseudo-Hamiltonian and the raw constraint allocate: 13 = 8 + 5 allocations, against 15 before.

Allocation contract (test/suite/meta/test_performance.jl, PERF5). The guards compare a wrapper with its raw side:

  • Data.ConstrainedPseudoHamiltonian allocates what its CTModels functor does, with one label and with two;
  • hamiltonian(ocp, u; multipliers) allocates what the composition H(x, p, u(x, p), μ(x, p)) written by hand does.

A guard of the form "≤ H̃ + raw constraint" was tried and dropped. Measured alone, H̃ and the constraint benefit from the compiler's allocation elimination, while they do not inside H. The comparison would then measure an optimiser artefact, as PERF5 warns.

Results:

  • full CTModels suite: 5691/5691;
  • full CTFlows suite against this commit: 8915 passed, plus the 2 GPU tests already marked broken;
  • docs build: clean, after two passes;
  • changelog lint: ✅. The duplicate sections of [Unreleased], left by the merge of main, are merged in the order of CHG2.

Review points 4, 6 and 7 of #536 are done.

- The buffer of the dynamics takes the type of t when t is not a plain
  number, so ForwardDiff in t of a non-autonomous problem no longer
  writes a Dual into a Float64 buffer. A Float32 state keeps a Float32
  buffer.
- pseudo_hamiltonian(ocp; constraints) raises an IncorrectArgument,
  not a MethodError, for constraints not given by labels (a String,
  nothing, a tuple holding a String, ...).
Minor points of the review of #536.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ocots
ocots marked this pull request as ready for review November 25, 2026 08:47
@ocots
ocots merged commit 2311aa0 into main Nov 25, 2026
20 checks passed
@ocots
ocots deleted the feat/532-model-hamiltonians branch November 25, 2026 09:05
@github-actions github-actions Bot mentioned this pull request Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

run ci github-runner Trigger the CI workflow on GitHub-hosted runners run documentation Trigger the Documentation workflow on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Public pseudo_hamiltonian(ocp) on the model

1 participant