Skip to content

Support Symbolic Struct handling in mtkcompile and solve calls - #5008

Merged
AayushSabharwal merged 34 commits into
SciML:masterfrom
Shreyas-Ekanathan:struct-support
Nov 5, 2026
Merged

AayushSabharwal merged 34 commits into
SciML:masterfrom
Shreyas-Ekanathan:struct-support

Conversation

@Shreyas-Ekanathan

Copy link
Copy Markdown
Contributor

Checklist

  • Appropriate tests were added
  • Any code changes were done in a way that does not break public API
  • All documentation related to code changes were updated
  • The new code follows the
    contributor guidelines, in particular the SciML Style Guide and
    COLPRAC.
  • Any new documentation only uses public API

Additional context

depends on JuliaComputing/StateSelection.jl#153 and JuliaSymbolics/Symbolics.jl#1959

if !fast_path
op = operating_point_preprocess(sys, op)
end
split_record_entries!(op)

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.

I'm really not sold on this approach. Ideally struct variables should be considered atomic the same way arrays are. AtomicArrayDict should validate that keys are not field accesses. Otherwise, people can specify struct initial conditions in multiple ways: foo => MyStruct(..) or [foo.x => 1, foo.y => [2, 3] and so on. An even worse case is foo.x[1].y.z => 3. Maintaining atomicity simplifies it a bit. I think fixpoint_sub with constant-folding should work if foo is substituted for a concrete value.

Comment thread lib/ModelingToolkitBase/src/utils.jl Resolved
Comment on lines +264 to +265
which stays whole because ordinary array atomicity already covers it. It is the same
granularity `Initial` uses, which is what the initialization system pairs `op` keys with.

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.

Initial and AtomicArrayDict should agree about atomicity, otherwise e.g. root is atomic but Initial(root) isn't. Downstream should just work if SymbolicGetproperty constant-folds properly? Does it not?

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.

This isn't addressed yet.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

  1. They do agree about atomicity, lowering drops to the individual fields to apply init conditions and build equations.
  2. We don't fold, and there are many weird cases here (as it stands, initial(P).x is different from initial(P.x), we design so that we apply conditions to the individual fields, rather than providing one full initial struct).

Comment thread lib/ModelingToolkitBase/src/utils.jl Resolved
end
# Records are the right granularity for resolving what was asked for, but nothing
# downstream expects a record key, so lower before returning.
lower_record_entries!(dd, default)

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.

As in #5008 (comment), I think structs should be considered atomic here. What breaks if they are not?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

So from a user perspective, at the moment, ICs can be passed both as a full struct or as individual components. I think this is reasonable, because if the whole struct is known, then they give that directly, otherwise if they have some guesses they can mix that in individually as well. On the output side, we currently only give per-component solution states. I think this second half motivates the lack of atomicity and the decomposition here. We can reassemble the full state after as a later feature, but since we integrate per component, I believe lowering is reasonable here. The distinction between this and arrays is that I can always integrate a numeric array directly, but a struct has to be flattened into something array-like before I can integrate it.

@AayushSabharwal AayushSabharwal Sep 18, 2026 •

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.

The reason atomicity exists is to avoid edge cases and unintentional abuse of API. If you have a struct variable and don't make it atomic, people can add all sorts of weird initial conditions/bindings. They might bind the entire struct and then add an initial condition for a field, which is wrong and an edge case we need to catch here that I don't think we do. There can be many such cases that need to be handled in many different places, and we cannot rely on future development work to always account for this.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I've applied a fix, it utilizes JuliaSymbolics/Symbolics.jl#1997 to construct the literal object. If you could review when you have a chance, that would be amazing!

@ChrisRackauckas

Copy link
Copy Markdown
Member

🤖 Automated review from an AI agent running as @ChrisRackauckas — not written or reviewed by Chris. It is posted so that you can act on it. Chris or a maintainer may disagree.

Verdict: changes needed before merge (reviewed at ab5ef09).

Adds support for @symstruct-typed variables in ModelingToolkitBase. Struct unknowns are lowered to their leaf fields for mtkcompile, initial conditions, connections, namespacing and symbolic indexing, with a new struct_variables.jl test file and a struct-pendulum index-reduction test. It can't land yet: it depends on three unmerged upstream PRs (Symbolics #1997 has changes requested, Symbolics #1959 has merge conflicts, StateSelection #153 has no approval), so its own new tests error in CI. It also fails QA, Runic and typos. AayushSabharwal still has changes requested on the core design question of whether records are atomic.

Risk assessment

  • Risk: high
  • Blast radius: All of ModelingToolkitBase. The diff changes shared code that every system goes through: AtomicArrayDict (setindex!, as_atomic_dict_with_defaults, get_possibly_indexed, has_possibly_indexed_key), scalarized_vars, renamespace, detime_dvs/retime_dvs/underscore_to_D, collect_var_to_name!, find_all_parameter_equations, connector expansion and ShiftIndex. It also changes precedence between whole-array and per-element initial conditions for plain arrays.
  • Evidence: CI on the head ab5ef09, run 2026-09-22. I compared each failure against master 0459027:
    • New failures, caused by the PR:
      • sublibrary-ci / lib/ModelingToolkitBase [InterfaceI] (Julia 1 and lts). Result: 1765 passed, 8 errored. All 8 errors are the PR's new struct_variables.jl testsets, failing with UndefVarError: record_literal not defined in Symbolics, which is supplied by the unmerged Symbolics bump SymbolicIndexingInterface to 0.2 #1997. This check passes on master.
      • tests / InterfaceI (julia 1, lts, x86). Result: 1 errored, in the PR's new pendulum block in test/structural_transformation/index_reduction.jl: ArgumentError: p(t).λ is present in the system but p(t).λ is not an unknown. This most likely needs the unmerged StateSelection Add easy possibility to create array of variables #153. Passes on master.
      • Downgrade / Downgrade Tests - InterfaceI: same p(t).x ... is not an unknown error. Passes on master.
      • downgrade-mtkbase (InterfaceI): same record_literal UndefVarError. Passes on master.
      • sublibrary-ci ... [QA] / Julia 1: a new ExplicitImports error on top of the Aqua failure master already has. The error says SymbolicGetproperty, field_name and issymstruct are not public in Symbolics. Master shows 20 pass / 1 fail; the PR shows 19 pass / 1 fail / 1 error.
      • Runic / Runic Format Check: diffs in atomic_array_dict.jl, connectors.jl, utils.jl, struct_variables.jl and index_reduction.jl. Passes on master.
      • Spell Check with Typos: anc should be and (the variable anc in get_possibly_indexed).
    • Pre-existing or unrelated:
      • sublibrary-ci [InterfaceII]: Evaluated: 121 == 29, which is identical on the master run of 2026-09-22 and has since been fixed on master.
      • tests / QA, SciMLBase.jl/SymbolicIndexingInterface, SciMLSensitivity.jl/Core8, NeuralPDE.jl/NNPDE2: all also fail on master 0459027.
      • build (docs): Documenter linkcheck got a 403 on https://docs.sciml.ai/PDEBase/stable/interface/, an external link. Master's build passes, so this is likely a transient failure.
      • Benchmarks: not compared.
    • Upstream PR states, checked via gh api:
    • Local runs:
      • I did not run the test suite locally. The PR only works on top of two separate Symbolics branches plus a StateSelection branch, and one of the Symbolics branches conflicts with Symbolics master. Any local result would test my merge of those branches, not the PR.
      • I checked that a struct inside a top-level let block (used by the new index-reduction test) is accepted on Julia 1.10, 1.11 and 1.12. It is.
  • Merge: needs changes. Findings 1–5 block the merge; 6–8 should be fixed before it lands.

Findings

  1. Upstream PRs are unmerged and no compat bump exists. Symbolics add test for multi-rate system #1959, Symbolics bump SymbolicIndexingInterface to 0.2 #1997 and StateSelection Add easy possibility to create array of variables #153 must be merged and released first. Then lib/ModelingToolkitBase/Project.toml (Symbolics) and the root Project.toml (StateSelection) need their compat lower bounds raised in this PR. Until then the new tests error in CI, and a Symbolics version without record_literal would still satisfy the current compat and break at runtime. Fix: land upstream, then bump compat.
  2. The design is still disputed by the maintainer.
    • The code in question is lib/ModelingToolkitBase/src/atomic_array_dict.jl (Base.setindex! → __aad_setindex_record!, as_atomic_dict_with_defaults, lower_record_entries!).
    • AayushSabharwal's open CHANGES_REQUESTED review (on e28a694, threads r3861267952 and the one on line 230) asks for records to be atomic: AtomicArrayDict should reject field-access keys, so an initial condition has exactly one spelling, and "bind the entire struct and then add an initial condition for a field" should be an error.
    • The head does the opposite. It accepts n => Nested(...), n.x => ..., av.v => ... and av.v[2] => ..., lowers record keys to leaves, and resolves mixed specs by specificity.
    • The new tests make this the intended behavior: "An explicit leaf entry overrides the record it came from" and "Precedence is by specificity" in struct_variables.jl.
    • Commit b6d6f54, "properly enforce atomicity of records", does not add a key validation. validate_atomic_array_key still only rejects array indices.
    • Aayush has not reviewed since 2026-09-18. Fix: settle the design with him before any further polish.
  3. It uses non-public Symbolics internals. Symbolics.issymstruct, Symbolics.SymbolicGetproperty, Symbolics.field_name and Symbolics.is_symstruct_type (used in utils.jl, atomic_array_dict.jl, connectors.jl, systems.jl, index_cache.jl and codegen.jl) are not declared @public in Symbolics master. ExplicitImports flags the first three in QA. Fix: have Symbolics mark these names @public, e.g. in add test for multi-rate system #1959 or bump SymbolicIndexingInterface to 0.2 #1997, the way bump SymbolicIndexingInterface to 0.2 #1997 already does for record_literal, is_record_literal and RecordLiteral.
  4. Runic fails on atomic_array_dict.jl, connectors.jl, utils.jl, test/struct_variables.jl and test/structural_transformation/index_reduction.jl. Fix: run julia --project=@runic -m Runic -i on those files.
  5. Typos fails. atomic_array_dict.jl, in get_possibly_indexed, uses the variable name anc. Fix: rename it (e.g. ancestor).
  6. An array behavior change is bundled in without a test.
    • The change is in as_atomic_dict_with_defaults (atomic_array_dict.jl, hunk at old line 87).
    • Per-element writes to a plain array are now applied on top of an existing whole-array entry.
    • Before, the element buffer was filled with default and replaced the whole-array entry outright. So with [u => [1,2], u[2] => 99], u[1] was lost or kept depending on dict iteration order.
    • The new behavior is probably a real fix, but it changes public behavior for every array user, and no test covers it. The array variables are unaffected testset doesn't mix whole-array and element entries.
    • Fix: split it into its own PR with a test that fails before and passes after, or at least add that test here.
  7. Changes to the time-variable helpers are untested. In utils.jl, detime_dvs and underscore_to_D now use symtype(op) instead of Real. retime_dvs pairs FnType{..., symtype(op)} with a scalar ShapeVecT(). For an array variable, symtype is Vector{...}, so that builds a symbol whose type is an array but whose shape is scalar. Fix: preserve the shape, or restrict the new behavior to struct symtypes, and add a test covering an array variable through these helpers.
  8. Comment and documentation issues.
    • test/struct_variables.jl ("record entries with symbolic leaves are kept") has the comment "previously the entry was silently dropped". That is history and belongs in the commit message.
    • The diff has a high density of comments that narrate the code.
    • None of the PR checklist boxes are ticked. A new user-facing capability (struct-typed unknowns in mtkcompile/ODEProblem) has no docs page or tutorial entry.
    • Fix: trim the comments and add a short docs section once the design in finding 2 is settled.

Push a fix and the PR is reviewed again automatically at the new head.


🤖 Posted by an AI agent — harness: Claude Code · model: claude-opus-5-5[1m] (fleet master); review by Devin CLI (Mac) / fusion-claude-opus-5-5-high-sidekick-swe-2-medium
Conversation: local Claude Code session 3cd6500a-1f81-46b5-ac0b-c466e15b6a53 on Chris's Mac (session ID, no URL)

@AayushSabharwal AayushSabharwal 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.

Apart from this, the general discussion about atomic structs is still pending iirc.

Comment thread lib/ModelingToolkitBase/src/utils.jl Resolved
Comment thread lib/ModelingToolkitBase/src/utils.jl Resolved
Comment thread lib/ModelingToolkitBase/src/utils.jl Resolved

@AayushSabharwal AayushSabharwal 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.

This might be a bit annoying 😅 I think I wasn't clear in my communication earlier. We should store records in an atomic manner, and initial_conditions and bindings can thus only be atomic. However, users can specify late initial conditions (ones passed to ODEProblem) partially.

To give an example, consider:

@variables x(t)[1:2]
@mtkcompile sys = System([D(x[1]) ~ t, x[2] ~ 2x[1]], t)

Here, x[1] is an unknown but x[2] is an observed. If the user can only specify an initial condition for x as a whole, it is impossible to build a fully determined initialization. So we allow ODEProblem(sys, [x[1] => 1], ...). Technically I think MTK will be fine with

@mtkcompile sys = System([D(x[1]) ~ t, x[2] ~ 2x[1]], t; initial_conditions = [x => [1, nothing]])

as well. This is not something I advertise, because the immediate follow up is (among many other edge cases) typically "is this possible for bindings" which it isn't. The reason we enforce atomic storage is because MTK then knows it has exactly one place to look for the initial value of x[i] for any i. Otherwise, when building the operating point we have to reconcile things like the user storing x in initial conditions but providing a partial override in ODEProblem or vice versa (there are more edge cases here too). This leads to a slow mess like https://github.com/SciML/ModelingToolkit.jl/blob/backport-v10/src/systems/problem_utils.jl#L121, which took several iterations to get right and does not scale well to large arrays.

MTK handles this for arrays by getting AtomicArrayDict to ensure its keys are atomic, and then providing the get_possibly_indexed and write_possibly_indexed! helpers to do partial reads/writes. I believe that extending the atomicity validation to structs, and updating these helpers and other similar utilities in that file to handle partial struct inputs should be all we need for this PR. validate_whole_record_keys then is also not necessary.

Thanks for persisting with this. We're almost across the finish line. Please feel free to ping me as frequently as you need.

"""
function nearest_present_ancestor(dd::AtomicArrayDict, k::SymbolicT)
x = k
while iscall(x)

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.

The @match pattern is applicable here too.

Comment thread lib/ModelingToolkitBase/src/utils.jl Outdated
Comment on lines +1890 to +1901
f = operation(leaf)
args = arguments(leaf)
base = record_leaf_entry(args[1]::SymbolicT, node, value)
isconst = SU.isconst(base)
if f isa Symbolics.SymbolicGetproperty
isconst || return f(base)::SymbolicT
return BSImpl.Const{VartypeT}(getproperty(unwrap_const(base), Symbolics.field_name(f)::Symbol))
elseif f === getindex
idxs = unwrap_const.(@view args[2:end])
isconst || return base[idxs...]::SymbolicT
return BSImpl.Const{VartypeT}(unwrap_const(base)[idxs...])
end

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.

@match can be used here.

@AayushSabharwal AayushSabharwal 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.

Apart from the existing comments and these ones, I think this looks great! Scalarizing in generate_initializesystem_* is not ideal but I also can't think of a cleaner solution right now, so I think it's acceptable.

@AayushSabharwal

Copy link
Copy Markdown
Member

@AayushSabharwal

Copy link
Copy Markdown
Member

@Shreyas-Ekanathan

Copy link
Copy Markdown
Contributor Author

https://github.com/SciML/ModelingToolkit.jl/actions/runs/39806548544/job/119921610466?pr=5008#step:12:1238 Still test failures

Yeah this is fixed with the state selection PR, trying to see if someone can review that so we have a sanity check before merging.

@AayushSabharwal

Copy link
Copy Markdown
Member

Does that PR not depend on this one?

@AayushSabharwal

Copy link
Copy Markdown
Member

Typically the way I've done this is to merge the MTKBase changes first, then stateselection/mtktearing, then MTK. So the pieces are released in dependency order with compat bumps.

@Shreyas-Ekanathan

Copy link
Copy Markdown
Contributor Author

No, that PR is independent, the dep is only one way.

@AayushSabharwal AayushSabharwal 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.

Also InterfaceI is failing

Comment thread lib/ModelingToolkitBase/src/utils.jl Resolved
@Shreyas-Ekanathan

Copy link
Copy Markdown
Contributor Author

@AayushSabharwal this should be all set now!

@AayushSabharwal

Copy link
Copy Markdown
Member

Amazing, thank you for persisting through this. One final change: please format 😅 to keep Runic happy. I'll merge immediately after.

@AayushSabharwal
AayushSabharwal merged commit 4364c2e into SciML:master Nov 5, 2026
108 of 111 checks passed
@kpamnany

kpamnany commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Amazing! Thanks for the hard work @Shreyas-Ekanathan!

Can we get a patch release @AayushSabharwal? 🥺

@AayushSabharwal

Copy link
Copy Markdown
Member

I triggered registration

@Shreyas-Ekanathan

Copy link
Copy Markdown
Contributor Author

Amazing! Thanks for the hard work @Shreyas-Ekanathan!

More to come 😁

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.

4 participants