Skip to content

Add constraints_to_penalties: lower constraints to quadratic penalty costs - #5111

Merged
ChrisRackauckas merged 1 commit into
SciML:masterfrom
ChrisRackauckas-Claude:devin/constraint-penalty
Sep 12, 2026
Merged

ChrisRackauckas merged 1 commit into
SciML:masterfrom
ChrisRackauckas-Claude:devin/constraint-penalty

Conversation

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member

Summary

Adds constraints_to_penalties(sys::System; weights = 1.0) in lib/ModelingToolkitBase, a System -> System transformation that removes every constraint of sys (including subsystem constraints, recursively) and appends a weighted quadratic penalty term to costs. This is the "classical PINN" formulation of a constrained problem — all constraint residuals folded into the objective — giving an unconstrained system for optimizers that do not accept explicit cons/lcons/ucons constraints. It is deliberately available as an explicit alternative to the constrained-solver lowering used for e.g. Ipopt/MadNLP.

Motivation: SciML/NeuralPDE.jl#1161

Semantics:

  • Equation constraints l ~ r contribute weights[i] * (l - r)^2.
  • Inequality constraints contribute weights[i] * max(residual, 0)^2, where residual is the constraint rewritten in canonical residual ≲ 0 form via Symbolics.canonical_form, so only violations are penalized. max is a registered diadic symbolic function and codegens through build_function (already used in connectors.jl).
  • weights may be a scalar applied to every constraint, or a vector with one entry per element of constraints(sys) (own constraints first, then subsystem constraints, recursively). Symbolic weights that are not already parameters or unknowns are automatically added to the system's parameters; when the system has an IndexCache (completed systems) it is rebuilt so the weights are tunable through the problem's parameter object.
  • Penalty terms are appended to costs(sys) and are combined with the rest of the objective through the system's consolidate function.

The transform is implemented with @set! (the established system-rebuild pattern), so unknowns, parameters, consolidate, defaults and metadata are preserved, and a completed system stays completed.

Test plan

New constraints_to_penalties testset in lib/ModelingToolkitBase/test/optimization/optimizationsystem.jl (20 tests), run with cd lib/ModelingToolkitBase/test/optimization && julia --project=. optimizationsystem.jl:

  • min (x-2)^2 s.t. x ≲ 1 lowered with weights = 1.0: constraints emptied, costs grew by 1, OptimizationProblem has lcons === ucons === nothing and f.cons === nothing, and unconstrained Nelder-Mead finds x ≈ 1.5 = (2 + w)/(1 + w) (vs x ≈ 2 without the constraint).
  • Weight scaling: weights = 1e4 pulls the argmin to (2 + 1e4)/(1 + 1e4) ≈ 1.0001.
  • Equality constraint x ~ 0.5 gives the expected argmin 1.25.
  • Vector weights distribute across constraints; wrong-length vectors throw ArgumentError.
  • A symbolic weight is auto-added to parameters and is tunable via the problem's p.
  • Subsystem constraints are lowered recursively on unflattened systems.

Observed output:

Test Summary:            | Pass  Total  Time
constraints_to_penalties |   20     20  6.1s

All other testsets in optimizationsystem.jl pass unchanged. Runic formatting clean (Runic.main --check/--inplace produced no diff) and typos clean over the changed files. The QA group (Aqua/ExplicitImports) passes; its JET subtest reports 234 pre-existing "possible errors" (all ##And#/##Call# locals generated by Moshi @match in untouched files — none in optimizationproblem.jl or the new functions), which is a master pre-existing failure unrelated to this change. The docs build was not run locally; the change adds one @docs entry (ModelingToolkit.constraints_to_penalties, verified to resolve to ModelingToolkitBase.constraints_to_penalties).

🤖 Generated with Devin (harness: Devin CLI 3000.10.21, model: SWE-2 High, session: local Devin CLI session — no shareable URL)

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Follow-up on the JET QA failure noted in the PR body: investigated on a clean checkout of master (6ccb968, MTKBase v1.69.2) — it does not reproduce. qa/jet.jl passes 18/18 on Julia 1.12.4, 1.12.7, and 1.10.12 (the lts/1 channels CI runs), across JET 0.9.18/0.11.6/0.12.1.

The ~234 reports with ##And#/##Call# locals in Moshi @match-generated code are the known upstream JET false-positive class (JET.jl#858 / julia#62745; see also #4958 and #4974 which disabled the root-package JET lane for the same reason). The unfiltered @test_call in jet.jl means a branch-environment difference (stale test/qa/Manifest.toml or shifted deps) can push JET into Moshi's generated guards. Net: environmental to the branch test env, not caused by this change — a fresh test/qa instantiate on this branch should come back green.

Investigation run by an AI agent (Devin CLI 3000.10.21, model: SWE-2 High).

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Status on the remaining red checks — all reproduce identically on master CI (verified against the latest master runs), so none are caused by this PR:

  • lib/ModelingToolkitBase [QA] / Julia 1: the JET.report_package(mode = :typo) section fails with 234 "possible errors" — all ##And#/##Call# locals in Moshi @match-generated code. Identical failure on master's own CI. This is the known upstream JET/Julia false-positive class tracked in QA: JET package analysis exceeds the 60-minute root QA budget #4958 (and JET.jl#858 / [inference] retain undef phi for short-circuit-bound local in nested && guard JuliaLang/julia#62745). Correction to an earlier note here: it is not a stale-manifest artifact — qa/jet.jl's @test_call tests pass locally, but the report_package analysis is genuinely red on master too.
  • InterfaceI: "Split Parameters Test" fails 4× at split_parameters.jl:16–27 — identical failure set and counts (1504/4/3) on master.
  • NeuralPDE.jl/NNPDE1/1/: nnpde__pde_iv_system_of_pdes.jl:105–106 — fails on every recent master IntegrationTest run.

Verified by an AI agent (Devin CLI 3000.10.21, model: SWE-2 High; local session, no shareable URL).

…costs

Implement a System -> System transformation that rewrites every constraint
of a system (including subsystem constraints, recursively) as a weighted
quadratic penalty term appended to costs, returning a system with empty
constraints. This is the "classical PINN" formulation of a constrained
problem: all constraint residuals are folded into the objective, producing
an unconstrained system that can be solved by optimizers which do not
accept explicit cons/lcons/ucons constraints (an explicit alternative to
the constrained-solver lowering used for e.g. Ipopt/MadNLP).

- Equation constraints l ~ r contribute weights[i] * (l - r)^2.
- Inequality constraints contribute weights[i] * max(residual, 0)^2, where
  residual is the constraint in canonical residual <= 0 form via
  Symbolics.canonical_form, so only violations are penalized.
- weights may be a scalar applied to every constraint, or a vector with
  one entry per element of constraints(sys) (own constraints first, then
  subsystems' recursively). Symbolic weights that are not already
  parameters or unknowns are automatically added to the system's
  parameters, rebuilding the IndexCache when present so the transformation
  also works on completed systems.

Motivated by SciML/NeuralPDE.jl#1161

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Agent-Harness: Devin CLI 3000.10.21
Agent-Model: SWE-2 High
Agent-Session: local Devin CLI session (no shareable URL)
@ChrisRackauckas
ChrisRackauckas merged commit 887af5f into SciML:master Sep 12, 2026
101 of 110 checks passed
ChrisRackauckas added a commit that referenced this pull request Sep 12, 2026
#5116)

Three recently merged PRs widened ModelingToolkit's surface without updating
the two version-controlled QA audit lists in `test/qa/qa.jl`, which is what
those lists exist to catch:

- #4774 (`limited` operator) exports `limited`, `limitnew`, `limitold` from
  ModelingToolkitBase and reaches for `MTKBase.LimitedCtx`,
  `MTKBase.apply_limited_lowering` and `MTKBase.attach_stage_limiters` from
  the root package.
- #5111 exports `constraints_to_penalties` from ModelingToolkitBase.

The four exported names are documented public API of ModelingToolkitBase with
rendered `@docs` entries (`docs/src/basics/Limiting.md`,
`docs/src/API/problems.md`), so they are added to `REEXPORTED_API`. The three
qualified accesses are MTK/MTKBase shared implementation seams -- a metadata
registry key and two lowering entry points populated by the compiler, not
anything a user sets -- so they join `lower_homotopy` and `has_any_homotopy`,
the directly analogous names from the `homotopy` operator, in
`NONPUBLIC_QUALIFIED_ACCESSES`.



Agent-Harness: Claude Code 2.0.14
Agent-Model: claude-opus-5[1m]
Agent-Session: https://claude.ai/code/session_01FeJYXni9MkJhPFA9yxYvfn
Claude-Session: https://claude.ai/code/session_01FeJYXni9MkJhPFA9yxYvfn

Co-authored-by: ChrisRackauckas-Claude <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
ChrisRackauckas added a commit that referenced this pull request Sep 13, 2026
- Add constraints_to_penalties: lower constraints to quadratic penalty costs (#5111)
- Fix QA: approve the `limited`/`constraints_to_penalties` API additions (#5116)
- Concretize initialization problems once at construction (#5062)
- Make tovar public (#5120)
- Fix SciCompDSL model macro hygiene (#5058)
- Release ModelingToolkitBase 1.71.0 (#5126)
- Forward ProblemTypeCtx metadata to OptimizationProblem (#5115)
- Release ModelingToolkitBase 1.71.1 (#5127)



Agent-Harness: Claude Code
Agent-Model: claude-opus-5[1m]
Claude-Session: https://claude.ai/code/session_014FEzNTLFutCmTEAZ3zBg5R

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants