Repository navigation
FMIComponent: events, non-real ports, FMU-computed initial states, and correct results across solves - #5431
Open
tom-juliahub wants to merge 15 commits into
Open
FMIComponent: events, non-real ports, FMU-computed initial states, and correct results across solves#5431tom-juliahub wants to merge 15 commits into
tom-juliahub wants to merge 15 commits into
Conversation
…hat is also an output instead of declaring it twice
Integer, enumeration and boolean inputs, outputs and parameters were created as typed symbolic variables and read or written with the real-only FMI functions, so FMUs with them failed to compile or the FMU rejected the call. Every numeric port is now a Float64 variable; typed groups pick the matching FMI getter or setter. String, binary and clock variables are left out with a warning. Model Exchange discrete inputs are written only when they change, in Event Mode, as the FMI standard requires.
… CS FMU Co-Simulation: get_instance_CS! wrote the states into the FMU before every step. The FMI standard allows that only before initialization ends, and BouncingBall rejects it. States are now written only to start the FMU. Model Exchange: event indicators and the next time event were ignored, so BouncingBall fell through the floor with no error. The ME evaluation now also returns the event indicators and a function that crosses zero at the next time event; a continuous callback (right-side root finding, as the standard expects) runs the FMU's event iteration and writes back any state it reset. Initialization runs the full event iteration instead of asserting that none is needed.
A solution's outputs were recomputed after the solve by a fresh FMU instance, which never saw the solve's events: Stair's counter, advanced by time events, read 1 throughout. Discrete outputs of an ME FMU are now discrete variables, set during initialization, after each FMU event, and after a step in which a discrete input changed, so the solution keeps what the FMU reported.
The event callback added for Model Exchange FMUs is a continuous callback, which ModelingToolkit cannot compile for a system with no unknowns. An FMU with no continuous states now gets one irreducible state with zero derivative, so it runs without other states in the model. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…d with
FMIBase stores the values it writes in Vector{Float64} fields, so a Model Exchange FMU
failed whenever it was called with another vector type, such as the static vectors that
code-generation passes supplied through the `optimize` option can produce. Convert
states, inputs and parameters at the FMU boundary, only when needed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The periodic callback that steps a CS FMU does not fire at the final time, so the step ending there was never taken and the solution's last values were one communication step behind (Dahlquist CS 0.9^9 instead of 0.9^10). A second discrete callback, whose condition is the callable parameter CSFinalStepDue, steps the FMU from where it last stepped to the final time; it also covers a final time that is not a multiple of the step. Each solve now also tells the FMU its own end time unless stop_time was given, so a remade problem with a longer tspan no longer steps past the stop time of the first. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The final-step callback did not pass FMIComponent's reinitializealg, so a system with algebraic equations around a CS FMU failed the default initialization check after the last step (ModelingToolkit's IO Model CS tests). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Reading a solution evaluates the FMU, which created an instance with that solution's parameters; a later solve of a remade problem reused it and silently ran with the old values (SimpleAdder value 1 -> 5 gave 8.0 instead of 16.0). The instance management callback now frees any leftover instance when a solve starts, and between solves an instance created with other parameter values is replaced (the wrapper records them). During a solve the instance is kept, so a parameter changed mid-solve does not discard the FMU's internal state. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Solvers that build Jacobians with ForwardDiff (the default solver's stiff methods, so every Dyad TransientAnalysis that switches to one) called the FMU with dual numbers and failed. The FMU is compiled code, so the wrapper now takes the value from the dual numbers' values and each derivative by a forward finite difference in that dual direction: what AutoFiniteDiff would compute. Rodas5P with ForwardDiff matches FiniteDiff and Tsit5 on Roberts, VanDerPol, BouncingBall and Dahlquist. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
FMIComponent left the states' initial values to the caller, so an FMU whose states have no start attribute (initial = "calculated", such as SimpleArrayModel) could not run without the caller guessing them, and a state whose start depends on parameters used a stale number. Each state's default initial value is now a callable parameter that initializes a fresh instance with the system's parameters and inputs and reads the states back; a value given by the caller still overrides it. For CoSimulation, only states with a start value (initial exact or approx) are written before initialization: the FMI standard does not let the caller set calculated ones. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Events, non-real ports, automatic differentiation and FMU-computed initial states are now supported; the docstring still said otherwise.
FMIBase asks the FMU for all derivatives at once, and the FMU returns them in the order of its model description, whatever order the references are given in. The derivative variables were built in the iteration order of a Dict, so when that order differed (it does on Julia 1.12), each state was paired with another state's derivative: VanDerPol and BouncingBall ran without error and gave wrong results.
Each test set fails without the fix it covers: Model Exchange events, integer, boolean and enumeration ports, FMUs without states, outputs that are states, Co-Simulation's last step and stop time, FMU-computed initial states, re-solving after remake, and ForwardDiff solvers. The Reference FMUs (v0.0.39, the newest FMIZoo can download) come from FMIZoo.
tom-juliahub
marked this pull request as ready for review
November 22, 2026 01:00
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
These fixes came out of adding FMU import to Dyad, which builds its FMU components on
FMIComponent.FMIComponentruns only a narrow set of FMUs today: real-valued ports, no events, andinitial states supplied by the caller. When we ran the FMI standard's
Reference FMUs (v0.0.42) through it, 22 of the
26 file-and-mode combinations that FMI.jl can load failed to build or solve. The other 4 have
no states to compare. Behind those failures were problems that give wrong answers without
an error. Once an FMU got past the failures, Model Exchange BouncingBall fell through the
floor, Stair's counter stayed at 1, and Co-Simulation results were one communication step
behind. Separately, a Model Exchange problem re-solved after
remakeused the oldparameter values (SimpleAdder, from this repository's tests).
With this PR all 26 match FMI.jl's own simulator: Model Exchange within 4×10⁻⁷, Co-Simulation
exactly. The two Reference FMUs still out of reach need FMI 3 arrays (StateSpace) or
Scheduled Execution (Clocks). Both need work in FMIImport first.
The changes are all in
ext/MTKFMIExt.jl, plus tests. Each commit is one fix with itsreason in the message, in an order where later fixes build on earlier ones, so the PR can
be read commit by commit.
What changes
Variables match the FMU.
the iteration order of a
Dict. The FMU's state functions take and return states byposition, so an FMU with several states could pair a state with another state's
derivative and run without an error.
all of them at once, and the FMU returns them in that order whatever order their
references are given in. On Julia 1.12 the
Dictorder differed, and VanDerPol andBouncingBall paired each state with the wrong derivative.
Float64variables. Each group is read and written with the FMI function for its type.
Model Exchange events.
callback uses right-side root finding, as the FMI standard expects. It runs the FMU's
event iteration and writes back any state the FMU reset.
outputs were recomputed after the solve by a fresh instance that never saw the events.
derivative. Without it, the event callback cannot compile, because a continuous
callback needs at least one unknown.
Co-Simulation.
a running FMU, and BouncingBall rejects it.
(the callable parameter
CSFinalStepDue) takes the last step. It also covers a finaltime that falls between two steps. That callback passes the component's
reinitializealg.stop_timeis set. Before, a remadeproblem with a longer
tspanstepped past the first solve's stop time.Each solve sees its own parameters.
solution is freed.
Automatic differentiation.
the primal values and takes a forward finite difference along each dual direction:
what
AutoFiniteDiffwould compute. Rodas5P and other stiff solvers then work withtheir default
autodiff.parameters are real.
Initial states from the FMU.
FMUInitialStates. Itinitializes an FMU instance with the system's parameters and inputs, and reads the
states back.
start(initial = "calculated", like the existingSimpleArrayModel.fmu) runs without the caller guessing them, and a start thatdepends on parameters is right.
allow setting calculated ones.
Vector types. The FMU is handed a plain
Vector{Float64}whatever vector type it iscalled with. FMIBase stores the values it writes in
Vector{Float64}fields, so it failedon anything else, such as the static vectors that code-generation passes supplied through
the
optimizeoption can produce. PlainModelingToolkitcode generation does not dothis, so there is no test for it here.
The docstring is updated to match.
Behaviour a user may notice
before; code that passed none now runs instead of failing.
match FMI.jl.
__mtk_internal_placeholder.test/fmi/fmi.jlpass unchanged.Out-of-place problems with a static vector of states still do not work for Model Exchange
FMUs. Two limits in ModelingToolkit itself block them, with or without an FMU: a
continuous callback with a single condition returns an
SVector{1}where the solver needsa number, and an
ImperativeAffectthat modifies states writes into the immutable statevector.
Tests
test/fmi/reference_fmus.jlis a new file in the FMI group, run by a second@safetestsetline intest/group_fmi.jl. It uses Reference FMUs v0.0.39, downloaded byFMIZoo, plus the two FMUs already in
test/fmi/fmus/. v0.0.39 is the newest releaseFMIZoo can download, because later releases name their archive differently. Each test set fails without the fixes it
covers:
Verified:
commits):
GROUP=FMI,Pkg.test(), Julia 1.12, Linux: 195 of 195, including the 60existing tests.
ext/MTKFMIExt.jlchanges, every new test set fails. The one check thatpasses either way is the Co-Simulation case of the re-solve test, which never had the
bug and is kept as a check. Checked the same way, on master with master's
ext/MTKFMIExt.jl: the 60 existing tests still pass.--check.🤖 Generated with Claude Code