Repository navigation
Support array unknowns on a completed system for every problem type - #5131
Conversation
…quire released deps Review changes for SciML#1165: - `discretize` calls `complete` instead of `mtkcompile`: the network parameters stay array unknowns of the `OptimizationProblem`, which needs ModelingToolkitBase 1.72 (SciML/ModelingToolkit.jl#5131). With `mtkcompile` the scalarization made problem generation grow with the parameter count (a 4,417-parameter network did not finish in 1h39m; `complete` builds it in 16 s). - The first PDE tutorial and the 3rd-order ODE example evaluate the solution with `sol[u(x, y)]` on `sol[x]`, `sol[y]` first, and show `sol(x, y; dv = ...)` for arbitrary points afterwards. - Compat bounds point at the released SciMLBase 3.54, SymbolicUtils 4.46.6 and Optimization 5.9.1 (OptimizationBase 5.6). Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]> Agent-Harness: Claude Code 2.1.269 Agent-Model: claude-fable-5-1 Agent-Session: https://claude.ai/code/session_01WYPUXLxE9jVu2jXLFRd8ax Claude-Session: https://claude.ai/code/session_01WYPUXLxE9jVu2jXLFRd8ax
| Unlike the other problem types, `OptimizationProblem` and `OptimizationFunction` accept a | ||
| system whose unknowns include array variables without requiring `mtkcompile` to scalarize | ||
| them; `complete` is enough. The state vector `u` is the concatenation of the unknowns in |
There was a problem hiding this comment.
We should make all problem types handle this?
| Unlike the other problem types, `OptimizationProblem` and `OptimizationFunction` accept a | |
| system whose unknowns include array variables without requiring `mtkcompile` to scalarize | |
| them; `complete` is enough. The state vector `u` is the concatenation of the unknowns in | |
| The state vector `u` is the concatenation of the unknowns in |
There was a problem hiding this comment.
DAEProblem already does.
There was a problem hiding this comment.
Checked on this branch (the DAE path is untouched by the PR, so this is master behaviour): DAEProblem(complete(sys), op, tspan) with an array unknown does not work today, it only skips the mtkcompile check through implicit_dae and then fails further down.
D(x) ~ -a .* x(array equation):MethodError: no method matching vec(::Bool)inadd_observed_equations!→get_possibly_indexed(atomic_array_dict.jl:163).D(x[1]) ~ ...(scalar equations overx[1:3]):TypeError: expected ParameterIndex{Initials, Int64}, got ParameterIndex{Initials, UnitRange{Int64}}inSetInitialUnknowns(problem_utils.jl:1526).
With the trait forced true for every constructor, ODEProblem, DAEProblem and NonlinearProblem all stop at that same SetInitialUnknowns typeassert. So the gate exists because optimization problems have no initialization system; that is the only constructor where flattening u is sufficient as of now. The argument names are not shared with the DAE path either, DAE has no such flag.
Making it unconditional means teaching the initialization index handling (Initials ranges for array unknowns) and the observed-equation lookup to accept array unknowns. Working on that now, so the trait and the kwarg go away and u is the concatenation of the unknowns for every problem type.
There was a problem hiding this comment.
Correction to my previous reply, after running MethodOfLines' own DAEProblem(pdesys, disc) (MethodOfLines 1.5.0, ModelingToolkitBase 1.71.1): its discretized system has scalarized unknowns (unknowns(sys) == [u(t)[1], …, u(t)[6]]) while the equations stay array-valued (D(u(t)[2:5]) ~ … over slices), and that builds and evaluates fine. So the DAE path already handles array equations over indexed unknowns, as you say.
What fails everywhere, DAE included, is an unscalarized array symbolic in unknowns(sys) itself (@variables x(t)[1:3], unknowns(sys) == [x, y]): u0 construction (varmap_to_vars, problem_utils.jl:459, Cannot convert Vector{Float64} to Float64) and the initialization setters (SetInitialUnknowns, ParameterIndex{Initials, UnitRange}). That is the NeuralPDE case (the network parameters are one array unknown) and what this PR flattens for optimization. The PR is being widened so every constructor treats u as the flat concatenation of unknowns(sys), with initialization enabled, and the trait/kwarg go away.
There was a problem hiding this comment.
But this is a temporary limitation, so we shouldn't document it like this is something we expect.
3840ae7 to
da77a66
Compare
OptimizationProblem/OptimizationFunctioncompleted system for every problem type
A `complete`d `System` whose `unknowns` contain array symbolics now behaves exactly as if those entries were scalarized in place: `u` is the flat concatenation of the unknowns in `unknowns(sys)` order, an array unknown contributing `length(x)` consecutive entries, and the generated code reconstructs it as a view into `u` via the existing `array_variable_assignments` machinery. `mtkcompile` is no longer required to scalarize them for any constructor. `check_array_equations_unknowns` becomes `check_array_equations` (array *equations* still need `mtkcompile` outside the implicit-DAE path), every state-vector position takes the new `flat_unknowns(sys)`, and initialization was taught the same layout: `SetInitialUnknowns`/`GetUpdatedU0` index the scalar `Initials` entries instead of asserting an `Int` index for an array unknown, and array-valued dummy derivatives get an array of guesses rather than a scalar stored under an array-shaped key. Motivated by the NeuralPDE PDE pipeline in SciML/NeuralPDE.jl#1165, whose unknowns are the neural-network parameter arrays. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]> Agent-Harness: Claude Code 2.1.269 Agent-Model: claude-fable-5-1 Agent-Session: https://claude.ai/code/session_01WYPUXLxE9jVu2jXLFRd8ax Claude-Session: https://claude.ai/code/session_01WYPUXLxE9jVu2jXLFRd8ax
da77a66 to
2bd4c8f
Compare
| guesses[ttk] = BSImpl.Const{VartypeT}(fill(unwrap_const(guess), size(ttk))) | ||
| else | ||
| write_possibly_indexed_array!(guesses, ttk, guess, COMMON_NOTHING) | ||
| end |
There was a problem hiding this comment.
We should probably make array-shaped values happen in write_possibly_indexed_array!, but I'll accept this workaround to get the greater NeuralPDE.jl change in. But this should be documented as a hack / workaround to be removed.
There was a problem hiding this comment.
Documented as a workaround in the docstring, with the removal tracked in #5147.
…te_possibly_indexed_array! Tracked in SciML#5147. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]> Agent-Harness: Claude Code 2.1.269 Agent-Model: claude-fable-5-1 Agent-Session: https://claude.ai/code/session_01WYPUXLxE9jVu2jXLFRd8ax Claude-Session: https://claude.ai/code/session_01WYPUXLxE9jVu2jXLFRd8ax
…quire released deps Review changes for SciML#1165: - `discretize` calls `complete` instead of `mtkcompile`: the network parameters stay array unknowns of the `OptimizationProblem`, which needs ModelingToolkitBase 1.72 (SciML/ModelingToolkit.jl#5131). With `mtkcompile` the scalarization made problem generation grow with the parameter count (a 4,417-parameter network did not finish in 1h39m; `complete` builds it in 16 s). - The first PDE tutorial and the 3rd-order ODE example evaluate the solution with `sol[u(x, y)]` on `sol[x]`, `sol[y]` first, and show `sol(x, y; dv = ...)` for arbitrary points afterwards. - Compat bounds point at the released SciMLBase 3.54, SymbolicUtils 4.46.6 and Optimization 5.9.1 (OptimizationBase 5.6). Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]> Agent-Harness: Claude Code 2.1.269 Agent-Model: claude-fable-5-1 Agent-Session: https://claude.ai/code/session_01WYPUXLxE9jVu2jXLFRd8ax Claude-Session: https://claude.ai/code/session_01WYPUXLxE9jVu2jXLFRd8ax
Stacked on SciML#5049: array *equations* are accepted by the implicit-DAE and nonlinear paths, but the opt-in is a hardcoded `!implicit_dae && !(constructor <: NonlinearFunction)` test in `__process_SciMLProblem` — a codegen flag and a constructor-type check doing capability duty. This treats accepting array equations as a named, per-constructor capability. - `accepts_array_equations(constructor)` gates `__process_SciMLProblem`. `DAEFunction` and `NonlinearFunction` opt in, matching SciML#5049's behavior exactly (`HomotopyProblem` inherits nonlinear support through the same constructor). Every other problem type still needs `mtkcompile`, and opting a new constructor in is a one-line method. - `has_array_equations(eqs)` gets a docstring; it is the shared, shape-based detection predicate behind `check_array_equations` and the Jacobian guards. - `DAEFunction` throws the same `ArgumentError` for `jac = true` / `sparse = true` on array residuals that `NonlinearFunction` gets: today `jac = true` dies inside `executediff` and `sparse = true` silently builds a wrong-shaped `jac_prototype` (one row per equation instead of one per residual row). Related: SciML#4983, SciML#5049, SciML#5131, SciML#5136. 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 Max Agent-Session: local Devin CLI session, no shareable URL (workspace /home/crackauc/sandbox/tmp_20260913_101544_55869)
…ESolution (#1165) * Rewrite the PDE parser: PDESystem -> System -> OptimizationProblem -> PDESolution `PhysicsInformedNN` is now a `PDEBase.AbstractOptimizationSystemDiscretization`. `symbolic_discretize` runs PDEBase's optimization-system driver and returns a `ModelingToolkit.System`: every dependent variable is a `ModelingToolkitNeuralNets.SymbolicNeuralNetwork` whose flat parameter vector is an array unknown, every equation and boundary condition is a residual block evaluated on its own non-tunable collocation matrix parameter (`u(x, t)` lowers to a batched network evaluation on `P * xs .+ c`, so literal arguments, periodic and point conditions need no special cases), derivatives lower to central finite-difference stencils on the network inputs, scalar operations are broadcast, and the residual is a lazy symbolic array whose size is independent of the number of points. Costs are mean or quadrature-weighted squared residuals; boundary conditions are penalties or, with `boundary_policy = :constraints`, equality constraints; `param_estim` promotes the `PDESystem` parameters to unknowns; `additional_loss` is a callable parameter cost. `discretize` is `mtkcompile` + sampling + `OptimizationProblem(sys, op; adtype, weights, ...)`, so ModelingToolkit's weights and adtype keywords replace the old adaptive-loss and logging closures; `remake` warm-starts or replaces collocation points and `resample!` redraws them from a callback. `solve` returns a `PDENoTimeSolution` through the `problem_type` metadata (`sol[u(x, y)]`, `sol(x, y; dv = u(x, y))`, `sol.original_sol`). `QuadratureTraining` for PDEs uses fixed Gauss-Legendre rules. Removed with the old Expr-level parser: `PINNRepresentation`, `Phi`, the adaptive losses, the logger extension, `neural_adapter`, the Bayesian PDE solver and integro-differential support (see the follow-up issue). `SDEPINN` and `DeepGalerkin` are ported; the ODE solvers are unchanged. The default AD backend is Zygote: Enzyme with runtime activity overwrote arrays captured by an `additional_loss` closure, and without it the static activity analysis rejects the generated objective. The first tutorial compiles the objective and its Enzyme gradient with Reactant. Breaking; version 7.0.0. Depends on SymbolicUtils 4.46.6, SciMLBase 3.54, OptimizationBase 5.6, ModelingToolkitBase 1.70 and PDEBase 0.1.36. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]> Agent-Harness: 2.1.269 (Claude Code) Agent-Model: claude-fable-5-1 Agent-Session: https://claude.ai/code/session_01WYPUXLxE9jVu2jXLFRd8ax Claude-Session: https://claude.ai/code/session_01WYPUXLxE9jVu2jXLFRd8ax * Accept Lux NamedTuple and ComponentArray initial parameters `PhysicsInformedNN(chain, strategy; init_params)` only accepted flat vectors, so the `SDEPINN` OU test on master, which passes `Lux.initialparameters(StableRNG(100), chain)`, failed with `MethodError: no method matching _param_eltype(::NamedTuple)`. The initial parameters are now normalized to one flat vector per network, accepting a flat vector, a Lux parameter `NamedTuple` or a `ComponentArray`, or a vector of those. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]> Agent-Harness: Claude Code 2.1.269 Agent-Model: claude-fable-5-1 Agent-Session: https://claude.ai/code/session_01WYPUXLxE9jVu2jXLFRd8ax Claude-Session: https://claude.ai/code/session_01WYPUXLxE9jVu2jXLFRd8ax * Build the problem with complete, lead tutorials with sol[u(x, y)], require released deps Review changes for #1165: - `discretize` calls `complete` instead of `mtkcompile`: the network parameters stay array unknowns of the `OptimizationProblem`, which needs ModelingToolkitBase 1.72 (SciML/ModelingToolkit.jl#5131). With `mtkcompile` the scalarization made problem generation grow with the parameter count (a 4,417-parameter network did not finish in 1h39m; `complete` builds it in 16 s). - The first PDE tutorial and the 3rd-order ODE example evaluate the solution with `sol[u(x, y)]` on `sol[x]`, `sol[y]` first, and show `sol(x, y; dv = ...)` for arbitrary points afterwards. - Compat bounds point at the released SciMLBase 3.54, SymbolicUtils 4.46.6 and Optimization 5.9.1 (OptimizationBase 5.6). Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]> Agent-Harness: Claude Code 2.1.269 Agent-Model: claude-fable-5-1 Agent-Session: https://claude.ai/code/session_01WYPUXLxE9jVu2jXLFRd8ax Claude-Session: https://claude.ai/code/session_01WYPUXLxE9jVu2jXLFRd8ax * Train the Lorenz parameter-estimation test from the first weight draw Every `symbolic_discretize` or `discretize` call draws fresh network weights from `disc.rng`, and the test called `symbolic_discretize` before `discretize`, so training started from the second draw. From those weights 13 of 16 training schedules (Adam iterations, BFGS iterations, data density, line search, L-BFGS) end in a poor local minimum with objective in the hundreds or thousands, and the one that passed did so only by luck: an 8e-15 relative change in gradient summation order between two ModelingToolkitBase branch versions sends it to a different basin. From the first draw all six schedules converge to an objective of about 0.0025 on both versions. The test now discretizes first and also asserts the objective converged, so a lucky estimate at a bad minimum cannot pass. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]> Agent-Harness: Claude Code 2.1.269 Agent-Model: claude-fable-5-1 Agent-Session: https://claude.ai/code/session_01WYPUXLxE9jVu2jXLFRd8ax Claude-Session: https://claude.ai/code/session_01WYPUXLxE9jVu2jXLFRd8ax --------- Co-authored-by: ChrisRackauckas-Claude <[email protected]> Co-authored-by: Claude Fable 5.1 <[email protected]>
Post-SciML#5131 `flat_unknowns` handles the array unknown unconditionally, so an array equation over `u(t)[1:4]` declared as `[u]` constructs and evaluates rather than throwing "array unknowns". 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 Max Agent-Session: local Devin CLI session, no shareable URL (workspace /home/crackauc/sandbox/tmp_20260913_101544_55869)
…ODE support and MultiObjectiveOptimizationFunction (#5148) * feat: accept array equations on the NonlinearProblem path * fix: keep array-equation downgrade CI on DiffEqBase 7.18.1 Import unwrap explicitly in the new NL tests and raise the DiffEqBase floor so nested AutoDespecialize accepts already-unwrapped parameters. * ci: retrigger checks * Apply suggestion from @ChrisRackauckas * Zero the derivatives of array unknowns before expanding slices * Test that array unknowns carry an array equation * Gate array equations on a per-constructor capability trait Stacked on #5049: array *equations* are accepted by the implicit-DAE and nonlinear paths, but the opt-in is a hardcoded `!implicit_dae && !(constructor <: NonlinearFunction)` test in `__process_SciMLProblem` — a codegen flag and a constructor-type check doing capability duty. This treats accepting array equations as a named, per-constructor capability. - `accepts_array_equations(constructor)` gates `__process_SciMLProblem`. `DAEFunction` and `NonlinearFunction` opt in, matching #5049's behavior exactly (`HomotopyProblem` inherits nonlinear support through the same constructor). Every other problem type still needs `mtkcompile`, and opting a new constructor in is a one-line method. - `has_array_equations(eqs)` gets a docstring; it is the shared, shape-based detection predicate behind `check_array_equations` and the Jacobian guards. - `DAEFunction` throws the same `ArgumentError` for `jac = true` / `sparse = true` on array residuals that `NonlinearFunction` gets: today `jac = true` dies inside `executediff` and `sparse = true` silently builds a wrong-shaped `jac_prototype` (one row per equation instead of one per residual row). Related: #4983, #5049, #5131, #5136. 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 Max Agent-Session: local Devin CLI session, no shareable URL (workspace /home/crackauc/sandbox/tmp_20260913_101544_55869) * Build `ODEProblem` from array differential equations without `mtkcompile` `complete(sys)` followed by `ODEProblem` rejected array equations such as `D(u[2:n-1]) ~ lap(u)`, forcing the finite-difference use case through the scalarizing `mtkcompile`, whose output and compile time grow with the grid. `DAEProblem` already accepts them, so give the explicit ODE path the same treatment: the right-hand side of an array equation is written to a contiguous block of `du` through `array_residual_maker`, the mass matrix gets one row per element, and the residual form `D(x) .- f ~ 0` emitted by MethodOfLines is rewritten to `D(x) ~ f` first. The generated code is independent of the array length. `full_equations` expands array equations into scalar rows so that the symbolic jacobian, sparsity and initialization paths keep one equation per row, and `ODEFunction` only computes the W sparsity pattern when `sparse` or `sparsity` asks for it. Co-authored-by: Cursor <[email protected]> * Update lib/ModelingToolkitBase/src/utils.jl Co-authored-by: Aayush Sabharwal <[email protected]> * Expect ODEProblem to accept array equations over scalar unknowns in the #2597 test Co-authored-by: Cursor <[email protected]> * Assert the operator type when re-applying a slice derivative to its elements Co-authored-by: Cursor <[email protected]> * Solve the array-equation DAE tests from a consistent du0 instead of BrownFullBasicInit The downgrade CI environment (DiffEqBase 7.15) trips a despecialization wrapper assertion inside BrownFullBasicInit for DAEFunctions, which aborted the InterfaceII group before the new ODEProblem tests could run. The tests only need a solve to compare against the analytic solution, so hand the solver a consistent du0 and skip DAE initialization. Co-authored-by: Cursor <[email protected]> * Share the array-equation predicate and accept them on the ODE path `is_array_equation` (from the ODE array-equation support) and `has_array_equations` were two spellings of the same shape check; keep the per-equation predicate in `utils.jl` and make `has_array_equations` delegate to it. `ODEFunction` opts into `accepts_array_equations`, matching what its `generate_rhs` branch already assembles through `array_residual_maker`. 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 Max Agent-Session: local Devin CLI session, no shareable URL (workspace /home/crackauc/sandbox/tmp_20260913_101544_55869) * Expect array unknowns to flatten in the ODE array-equation tests Post-#5131 `flat_unknowns` handles the array unknown unconditionally, so an array equation over `u(t)[1:4]` declared as `[u]` constructs and evaluates rather than throwing "array unknowns". 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 Max Agent-Session: local Devin CLI session, no shareable URL (workspace /home/crackauc/sandbox/tmp_20260913_101544_55869) * Update rejection tests for the ODE array-equation capability `ODEProblem` accepts array equations now, so it no longer belongs in the "still require scalarized equations" testset (`SDEProblem` rejection remains covered in the same file), and a `D(u) ~ -u` system over the array unknown `u` constructs because `flat_unknowns` handles it. 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 Max Agent-Session: local Devin CLI session, no shareable URL (workspace /home/crackauc/sandbox/tmp_20260913_101544_55869) * Reject residual-form array differential equations on the ODE path The scalar path only accepts `D(x) ~ f` from `complete`; `D(x) - f ~ 0` is a DAE and needs `mtkcompile` or `DAEProblem`. Treat `D(u[2:4]) .- f ~ 0` the same way instead of pattern-matching it back into explicit form in every consumer. Also drop the duplicate InterfaceII include of `array_equation_dae.jl` (InterfaceI already runs it) and scope the docs note about `jac`/`sparse` to array equations. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]> Agent-Harness: Claude Code Agent-Model: claude-fable-5-1 Agent-Session: https://claude.ai/code/session_01VorhgJYhDasyVLpGNrviga Claude-Session: https://claude.ai/code/session_01VorhgJYhDasyVLpGNrviga * Construct MultiObjectiveOptimizationFunction from a system's cost vector `OptimizationProblem` accepts `f::MultiObjectiveOptimizationFunction` in SciMLBase, but MTK could never produce one: `generate_cost` always folds `get_costs(sys)` through `consolidate` into a scalar. - `costs(sys)` returns the unconsolidated objective vector: the system's own costs plus the consolidated cost of each subsystem, namespaced. - `MultiObjectiveOptimizationFunction(sys)` generates a vector-valued objective over `costs(sys)`. `jac` builds the objective jacobian; `hess` is a vector with one generated hessian function per objective, the shape `OptimizationBase.instantiate_function` iterates. - The constraint fields are assembled by `generate_constraint_fields`, shared with `OptimizationFunction` instead of duplicated. - `OptimizationProblem(sys, op; multiobjective = true)` routes through it. `weights` cannot combine with it. Also drop the `jac`/`sparse` guards on `NonlinearFunction` and `DAEFunction` for array equations: since `full_equations` scalarizes array equations, the symbolic jacobian and sparsity pattern already come out with one row per residual, so both now work and are tested against ForwardDiff and the analytic stencil. The array-residual DAE tests go back to `BrownFullBasicInit`, which runs on the DiffEqBase 7.18.1 floor. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-Authored-By: Claude Fable 5.1 <[email protected]> Agent-Harness: Claude Code Agent-Model: claude-fable-5-1 Agent-Session: https://claude.ai/code/session_01VorhgJYhDasyVLpGNrviga Claude-Session: https://claude.ai/code/session_01VorhgJYhDasyVLpGNrviga * Approve the multi-objective names as ModelingToolkit reexports `costs` and the `generate_multiobjective_*` / `calculate_multiobjective_*` functions are exported from ModelingToolkitBase and therefore reexported by the ModelingToolkit facade; list them in the root QA allow-list. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]> Agent-Harness: Claude Code Agent-Model: claude-fable-5-1 Agent-Session: https://claude.ai/code/session_01VorhgJYhDasyVLpGNrviga Claude-Session: https://claude.ai/code/session_01VorhgJYhDasyVLpGNrviga --------- Co-authored-by: utkuyilmaz1903 <[email protected]> Co-authored-by: Christopher Rackauckas <[email protected]> Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Cursor <[email protected]> Co-authored-by: Aayush Sabharwal <[email protected]> Co-authored-by: Claude Fable 5.1 <[email protected]>
The expression-graph test builds an OptimizationProblem from a completed system with array unknowns, which ModelingToolkitBase supports from 1.72 (SciML/ModelingToolkit.jl#5131). The downgrade job resolved 1.52 and threw "The system has array unknowns". Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Agent-Harness: Claude Code (subagent of ci-green head) Agent-Model: claude-opus-5-5[1m] Agent-Session: https://claude.ai/code/session_011aK5Xvp9NpdkzKuEwtiMGd
…nts; fix SymbolifiedExprs MethodError (#1364) * OptimizationMOI: expression graph for array constraints and array unknowns/parameters process_system_exprs sized cons_expr by constraints(sys); an array-valued constraint contributes one row per element, so iterate the rows of f.cons_expr instead. get_expr_map mapped each unknown/parameter by its position in unknowns(sys)/parameters(sys) and resolved p[i] as tunable[i], which is wrong as soon as an array parameter is present (silently wrong solver input), and never matched elements of array unknowns/parameters. Map every scalar element to its variable_index/parameter_index, resolve parameters with parameter_values, keep all indices in repl_getindex!, and match the getindex form that OptimizationBase's symbolify leaves. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude <[email protected]> Agent-Harness: Claude Code 2.1.280 Agent-Model: claude-opus-5-5 Agent-Session: local session, transcript at /home/crackauc/sandbox/agent-jobs/ModelingToolkit.jl/jobs/5151-claude/log.txt on amdci2.julia.csail.mit.edu * OptimizationMOI: build system expressions only when :ExprGraph is requested The NLP evaluator of a system-based problem now defers process_system_exprs to MOI.initialize, and only runs it when the solver requests :ExprGraph. Solvers such as Ipopt that only evaluate the generated functions no longer scalarize the constraints (ModelingToolkit builds cons_expr lazily). Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude <[email protected]> Agent-Harness: Claude Code 2.1.280 Agent-Model: claude-opus-5-5 Agent-Session: local session, transcript at /home/crackauc/sandbox/agent-jobs/ModelingToolkit.jl/jobs/5151-claude/log.txt on amdci2.julia.csail.mit.edu * OptimizationBase: symbolify a lazy cons_expr on access in NoAD instantiation The NoAD instantiate_function methods (single- and multi-objective) broadcast symbolify over f.cons_expr, which forces a lazily built cons_expr (ModelingToolkit) on every solve even when no expression-graph consumer reads it. Non-Vector cons_expr is now wrapped so each element is symbolified when read; plain Vectors are unchanged. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude <[email protected]> Agent-Harness: Claude Code 2.1.280 Agent-Model: claude-opus-5-5 Agent-Session: local session, transcript at /home/crackauc/sandbox/agent-jobs/ModelingToolkit.jl/jobs/5151-claude/log.txt on amdci2.julia.csail.mit.edu * OptimizationMOI: drop unused SciMLStructures import _replace_parameter_indices! no longer calls SciMLStructures.canonicalize. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Cursor Agent <[email protected]> Agent-Harness: Cursor Agent CLI 2026.09.26-dd393fe Agent-Model: auto Agent-Session: local session, transcript at /home/crackauc/sandbox/agent-jobs/Opt-1364/jobs/1364-cursor/log.txt on amdci2.julia.csail.mit.edu * OptimizationBase: defer symbolify of lazy cons_expr in AutoSymbolics Match the NoAD path: use symbolify_exprs so AutoSymbolics / AutoSparse{AutoSymbolics} do not force a lazy AbstractVector cons_expr during instantiation. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Cursor Agent <[email protected]> Agent-Harness: Cursor Agent CLI 2026.09.26-dd393fe Agent-Model: auto Agent-Session: local session, transcript at /home/crackauc/sandbox/agent-jobs/Opt-1364/jobs/1364-cursor/log.txt on amdci2.julia.csail.mit.edu * OptimizationMOI: accept AbstractVector{Expr} cons_expr in NLP evaluator SymbolifiedExprs from NoAD instantiation is not a Vector{Expr}, so storing it in MOIOptimizationNLPEvaluator threw MethodError on every MOI NLP solve of a non-system problem with a custom/lazy cons_expr. Widen the field and add regression tests for the reviewer's minrepro and for array-valued system constraints. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Cursor Agent <[email protected]> Agent-Harness: Cursor Agent CLI 2026.09.26-dd393fe Agent-Model: auto Agent-Session: local session, transcript at /home/crackauc/sandbox/agent-jobs/Opt-1364/jobs/1364-cursor/log.txt on amdci2.julia.csail.mit.edu * OptimizationMOI: use bound-baked cons_expr in AbstractVector NLP test AmplNLWriter requires :call/:comparison cons_expr forms; supply hess so Ipopt can solve the same NoAD problem. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Cursor Agent <[email protected]> Agent-Harness: Cursor Agent CLI 2026.09.26-dd393fe Agent-Model: auto Agent-Session: local session, transcript at /home/crackauc/sandbox/agent-jobs/Opt-1364/jobs/1364-cursor/log.txt on amdci2.julia.csail.mit.edu * OptimizationMOI: fix typo in AbstractVector cons_expr test comment Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Cursor Agent <[email protected]> Agent-Harness: Cursor Agent CLI 2026.09.26-dd393fe Agent-Model: auto Agent-Session: local session, transcript at /home/crackauc/sandbox/agent-jobs/Opt-1364/jobs/1364-cursor/log.txt on amdci2.julia.csail.mit.edu * OptimizationMOI: use exported NoAD in AbstractVector cons_expr test SafeTestsets isolate Main; SciMLBase was loaded but not imported. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Cursor Agent <[email protected]> Agent-Harness: Cursor Agent CLI 2026.09.26-dd393fe Agent-Model: auto Agent-Session: local session, transcript at /home/crackauc/sandbox/agent-jobs/Opt-1364/jobs/1364-cursor/log.txt on amdci2.julia.csail.mit.edu * OptimizationBase: lazy-wrap only AbstractVector{Expr} in symbolify_exprs Non-Expr eltype AbstractVectors (e.g. AbstractVector{Any} holding Exprs) must fall through to symbolify.(exprs) so MOI NLP gets Vector{Expr}; lazy SymbolifiedExprs would inherit Any and MethodError at evaluator construction. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Cursor Agent <[email protected]> Agent-Harness: Cursor Agent CLI 2026.09.28-64d2043 Agent-Model: auto Agent-Session: local session, transcript at /home/crackauc/sandbox/agent-jobs/Opt-1364/jobs/1364-cursor/log-cont1.txt on amdci2.julia.csail.mit.edu * OptimizationMOI: raise ModelingToolkitBase floor to 1.72 The expression-graph test builds an OptimizationProblem from a completed system with array unknowns, which ModelingToolkitBase supports from 1.72 (SciML/ModelingToolkit.jl#5131). The downgrade job resolved 1.52 and threw "The system has array unknowns". Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Agent-Harness: Claude Code (subagent of ci-green head) Agent-Model: claude-opus-5-5[1m] Agent-Session: https://claude.ai/code/session_011aK5Xvp9NpdkzKuEwtiMGd * OptimizationMOI: raise ModelingToolkitBase floor to 1.77 The array-constraint expression-graph test (`[[u2, v2] ~ [1.0, 2.0]]`) needs array-valued constraints, added in ModelingToolkit#5189 and first released as ModelingToolkitBase 1.77.0. At 1.72 the downgrade job errors with `Cannot equate an array of different sizes`. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Agent-Harness: Claude Code (subagent of ci-green head) Agent-Model: claude-opus-5-5[1m] Agent-Session: https://claude.ai/code/session_011aK5Xvp9NpdkzKuEwtiMGd --------- Co-authored-by: ChrisRackauckas-Claude <[email protected]> Co-authored-by: Claude <[email protected]> Co-authored-by: Cursor Agent <[email protected]>
Since #5131 (ModelingToolkitBase 1.72.0) a `complete`d system may have unscalarized array unknowns, but the jump dependency maps and the compiled jump affects index the state by position in `unknowns(sys)` instead of the flat state, which gave silently wrong results (#5428). As a hotfix, `JumpProblem` rejects such systems again, as before 1.72.0. Jump rates are now scalarized before their dependencies are collected, so a rate using an array as a whole, e.g. `sum(X)`, depends on its scalarized elements. The `@test_nowarn` in "Proper substitution in `JumpSysMajParamWrapper`", which caught JumpProcesses 10.2's deprecation warning for the dependency map keywords, is replaced with a check of the substituted rate. Co-Authored-By: Claude Opus 5.5 <[email protected]>
What changed and why
A
completedSystemwhoseunknownscontain array symbolics now behaves exactly as if those entries were scalarized in place, for every problem type:uis the flat concatenation of the unknowns inunknowns(sys)order (an array unknown contributinglength(x)consecutive entries — the layoutIndexCachealready assigns them), the generated code reconstructs each array unknown as a view intouthrough the existingarray_variable_assignmentsmachinery, and initialization,du0,differential_vars,lb/uband symbolic indexing all use the same layout.mtkcompileis no longer required to scalarize them for any constructor.Motivated by the NeuralPDE PDE pipeline in SciML/NeuralPDE.jl#1165, whose unknowns are the neural-network parameter arrays and which currently has to call
mtkcompileonly to scalarize them.Implementation. There is no trait and no opt-in keyword; the behaviour is unconditional.
check_array_equations_unknowns→check_array_equations: it no longer rejects array unknowns at all. (Array equations still needmtkcompileoutside the implicit-DAE path — see "Still open" below.)flat_unknowns(sys) = scalarized_vars(unknowns(sys))(systems.jl, next toscalarized_vars) replacesunknowns(sys)in every state-vector position:__process_SciMLProblem'sdvs(sou0,du0andcheck_eqs_u0are flat),generate_rhs/generate_jacobian/generate_tgrad/generate_W/generate_dae_jacobian/jacobian_sparsity/the cost and constraint generators/build_explicit_observed_function/generate_custom_function, and thedvsof theODE/DAE/SDE/Nonlinear/Discrete/ImplicitDiscrete/BVP/Jump/Optimizationproblem constructors. For a systemmtkcompilehas already scalarized it returns an equal vector, so nothing else changes.SetInitialUnknowns/GetUpdatedU0builtInitial.(unknowns(sys));parameter_indexreturns aParameterIndex{Initials, UnitRange}for an array unknown and the::ParameterIndex{Initials, Int}assert threw. They now useflat_unknowns, so each entry is the scalarInitialsindex, andGetUpdatedU0's guess mask is per-element (it is used asview(buffer, guessvars)over the flatu0) and looks values up withget_possibly_indexed.generate_initializesystem_timevaryingstored the dummy-derivative guess withwrite_possibly_indexed_array!(guesses, ttk, ...). An array-valuedttk(xˍt(t)for@variables x(t)[1:3]) is not an indexed symbolic, so a scalarfalsewas stored under an array-shaped key and the nextget_possibly_indexedon an element of it hitMethodError: no method matching vec(::Bool). Newwrite_dd_guess!storesfill(guess, size(ttk))in that case, mirroring whatadd_initials!already does.solved_unknownsandremake_initialization_data'sto_varmap(u0, dvs)also takeflat_unknowns, otherwiseinitializeprobmaprebuiltu0as a 2-element nested vector andto_varmapmismatched lengths.DAEProblem'sdifferential_varsnow marks an array unknown's elements differential whenD(x)over the whole array appears.ModelingToolkitBase1.71.1 → 1.72.0. No new public names. The docs change follows @ChrisRackauckas's review: the paragraph is now a single general statement in "The state vector and parameter object" rather than an "unlike the other problem types" note under optimization.What works now, per problem type
All with default initialization settings (no
build_initializeprob = false),@variables x(t)[1:3] y(t),unknowns(sys) == [x, y]:ODEProblemArgumentError: The system has array unknowns.length(u0) == 4,f(u0, p, 0)and theTsit5solution match the analytic solution andmtkcompileDAEProblem(scalar equations)TypeError: ... expected ParameterIndex{Initials, Int64}, got ParameterIndex{Initials, UnitRange{Int64}}length(u0) == 4, consistentdu0,all(differential_vars),DFBDFsolution matches the analytic oneDAEProblem(array equationD(x) ~ -a .* x)MethodError: no method matching vec(::Bool)length(u0) == 4NonlinearProblemArgumentError: The system has array unknowns.length(u0) == 4,NewtonRaphsonsolves,sol[z] == [1, 2, 6]SDEProblemArgumentError: The system has array unknowns.length(u0) == 4,f/gmatchmtkcompile,SOSRIsolvesOptimizationProblemArgumentError: The system has array unknowns.lb/ubfromboundsmetadata,AutoForwardDiffsolveSymbolic indexing is unchanged throughout:
prob[x]returns the 3-vector,prob[x[2]]the element,variable_index(sys, x) == 1:3, and observed expressions over array unknowns (sum(x) + y,x[3] * y) read the same flat layout.Verification
Julia 1.11.9, scratch environment with
ModelingToolkitBasedeved from this branch (SciMLBase 3.54.0, Symbolics 7.39.2, SymbolicUtils 4.46.6, OrdinaryDiffEq 7.8.1, NonlinearSolve 4.30.0, StochasticDiffEq 7.2.0, Optimization 5.9.1).Failing before / passing after
The four new testsets, extracted verbatim into standalone files and run against an unmodified
origin/masterworktree (8875e77) and against this branch. Same files, same environment, onlyModelingToolkitBasediffers.Before — all four error out of the
@testset:After:
The two initialization bugs are only reachable once the guard is gone, so they do not appear in the "before" column above. Forcing the guard off on master reproduces them exactly as quoted in the table (
SetInitialUnknownsatproblem_utils.jl:1526,get_possibly_indexedatatomic_array_dict.jl:163←add_observed_equations!atproblem_utils.jl:196← the initialization problem's own__process_SciMLProblem).Test groups
Each file in its own
juliaprocess,using Test, SciMLBase; include(file):Initialization—guess_propagation.jlexit=0,initializationsystem.jlexit=0,initial_values.jlexit=0. (3/3)InterfaceI— all 35 files exit=0:abstractsystem,abstractsystem_interface,abstractcollocation,variable_scope,variable_parsing,linearity,binding_semantics,input_output_handling,system_building,simple_mtkcompile,mtkcomplete,odesystem,system_tspan,dq_units,mass_matrix,split_parameters,static_arrays,components,error_handling,basic_transformations,changeofvariables,symbolic_events,stream_connectors,domain_connectors,dep_graphs,function_registration,precompile_test,dae_jacobian,array_equation_dae,jacobiansparsity,modelingtoolkitize,constants,parameter_bindings,equation_type_accessors,accessor_functions,complex.nonlinearsystem.jlexit=0,sdesystem.jlexit=0,optimization/optimizationsystem.jlexit=0,array_equation_dae.jlexit=0 (all pass:array equations reach DAEProblem6/6,other problem types still require scalarized equations1/1,array-equation DAE solves to the analytic solution2/2,array equations over a 2D slice keep their shape2/2,array equations written as `D(slice) ~ rhs`4/4).QA—JET Tests54/54 pass;Aqua Tests20 pass / 1 fail. Identical on an unmodifiedorigin/masterworktree (I ran both): the failure isQuality Assurance: JET-test failed at JET/src/JETBase.jl:1046with═════ 38 toplevel errors found ═════, allArgumentError: Package StaticArraysCore not found in current path—JET.report_packagecannot resolveModelingToolkitBase's dependencies from theqaproject in this local setup. Pre-existing, and this diff adds no imports and no dependencies.array_equation_dae.jlexisted in the repo but was not referenced fromruntests.jl; since it is the regression guard for the DAE array-equation codegen this PR touches (generate_rhs'sdvs), and for the MethodOfLines shape (scalarized unknowns, array equations over slices), it is now wired intoInterfaceI.Runicandtyposare clean on every changed file.Existing test updated
odesystem.jl's@testset "Issue #2597"pinned the removed limitation — it asserted thatODEProblemthrows for array unknowns as well as array equations. It now asserts the new contract: scalar equations over an array unknown build a problem with the rightlength(u0), an array equation still throws.Still open
Array equations still require
mtkcompilefor every constructor except the implicit-DAE path, andcheck_array_equationskeeps that guard. Making them work is not contained: the explicit path ingenerate_rhsbuildsrhss = [eq.rhs for eq in eqs]with noexpand_array_derivatives!/array_residual_makertreatment, andcalculate_jacobian,calculate_tgrad,calculate_hessian,jacobian_sparsityand the mass-matrix construction all differentiate that vector againstdvsassuming one scalar row per equation. That is a separate change with its own test surface, so I left it alone rather than half-doing it.A system with array equations over slices cannot build its initialization problem, with or without this PR.
DAEProblem(complete(sys), op, tspan)on the MethodOfLines shape (broadcast(-, D(u[2:5]), lap) ~ zeros(4)with scalarized unknowns) fails ati.e.
mtkcompileof the initialization system does not accept a derivative of a slice. I verified this reproduces byte-for-byte on unmodifiedorigin/master, so it is pre-existing and orthogonal to array unknowns (that system's unknowns are already scalarized). It is why MethodOfLines passesbuild_initializeprob = falsetoday. I did not document that keyword anywhere as a way to use array unknowns; this is reported here as the open problem it is. The whole-array formD(x) ~ -a .* xover an array unknown does work with default initialization, and is tested.Not verified
InterfaceII,Extensions,Downstream,SymbolicIndexingInterface,FMIand GPU groups were not run — this scratch environment does not resolve their dependency sets.InterfaceIIin particular containscode_generation.jl,index_cache.jlanddiscrete_system.jl, which are the closest remaining neighbours of this diff; CI is what will cover them.JumpProblem,BVProblem,DiscreteProblem,ImplicitDiscreteProblemandLinearProblemgot the sameflat_unknownstreatment for consistency, but I did not write array-unknown tests for them — only ODE/DAE/SDE/Nonlinear/Optimization are covered.Worth pushing back on
flat_unknownsallocates a fresh vector on every call, including for systems that have no array unknowns. It is noise next to code generation, but it is a real (small) regression on hot paths that call these generators repeatedly.grad = true/hess = trueover a lazy array cost is silently wrong, and this PR does not fix it:Symbolics.gradient(sum(abs2, x .- a), [x[1], x[2], x[3], y])returns[0, 0, 0, …]because themapreduceterm is not scalarized before differentiation, andsum((x .- a) .^ 2)throwsArgumentError: invalid index: _1insideSymbolicUtils.scalarize. This reproduces identically on master viacalculate_cost_gradient(mtkcompile(sys)). The new optimization tests therefore exercise symbolicgrad/hesswith an explicitly indexed cost and the lazy array costs through anadtype. Happy to reduce it to a SciML-free MWE and file it upstream if you want.Rebase (2026-09-13)
Rebased onto master at ModelingToolkitBase 1.71.3 (conflict: version number only, kept 1.72.0). Re-ran on the rebased commit, each file in its own process:
test/optimization/optimizationsystem.jl,test/odesystem.jl,test/nonlinearsystem.jl,test/sdesystem.jl,test/array_equation_dae.jl,test/initializationsystem.jl,test/initial_values.jl,test/guess_propagation.jl: all pass. (odesystem.jl's "full_equationsdoesn't recurse infinitely" 180 s subprocess check failed once while eight other Julia processes were running on the machine and passed on a standalone re-run.) NeuralPDE's PDE test files and docs pages were re-run against the rebased branch: all pass except one parameter-estimation test whose BFGS trajectory diverges from an 8e-15 relative difference in gradient summation order between this branch and its first version; forward objective values are bit-identical. That is a fragility of that test, tracked on the NeuralPDE side.🤖 Generated with Claude Code (model: claude-fable-5-1)
https://claude.ai/code/session_01WYPUXLxE9jVu2jXLFRd8ax