Skip to content

FMIComponent: events, non-real ports, FMU-computed initial states, and correct results across solves - #5431

Open
tom-juliahub wants to merge 15 commits into
SciML:masterfrom
tom-juliahub:fmi-component-fixes
Open

tom-juliahub wants to merge 15 commits into
SciML:masterfrom
tom-juliahub:fmi-component-fixes

Conversation

@tom-juliahub

Copy link
Copy Markdown

These fixes came out of adding FMU import to Dyad, which builds its FMU components on
FMIComponent.

FMIComponent runs only a narrow set of FMUs today: real-valued ports, no events, and
initial 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 remake used the old
parameter 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 its
reason 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.

  • States are created in the order of the model description. Before, they were created in
    the iteration order of a Dict. The FMU's state functions take and return states by
    position, so an FMU with several states could pair a state with another state's
    derivative and run without an error.
  • The derivatives are read in the model description's order too. FMIBase asks the FMU for
    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 Dict order differed, and VanDerPol and
    BouncingBall paired each state with the wrong derivative.
  • A state that is also an output is one variable marked as an output, not two variables.
  • Integer, enumeration and boolean inputs, outputs and parameters become Float64
    variables. Each group is read and written with the FMI function for its type.
  • String, binary and clock variables are left out with a warning.

Model Exchange events.

  • The FMU's event indicators and its next time event drive a continuous callback. The
    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.
  • Initialization runs the full event iteration, instead of asserting that none is needed.
  • Discrete outputs are discrete variables, updated at each event. Before, a solution's
    outputs were recomputed after the solve by a fresh instance that never saw the events.
  • Discrete inputs are written in Event Mode, and only when they change.
  • An FMU with no continuous states gets one irreducible placeholder state with zero
    derivative. Without it, the event callback cannot compile, because a continuous
    callback needs at least one unknown.

Co-Simulation.

  • States are written only to start the FMU. The standard does not allow setting them on
    a running FMU, and BouncingBall rejects it.
  • The periodic callback does not fire at the final time, so a second discrete callback
    (the callable parameter CSFinalStepDue) takes the last step. It also covers a final
    time that falls between two steps. That callback passes the component's
    reinitializealg.
  • Each solve gives the FMU its own end time unless stop_time is set. Before, a remade
    problem with a longer tspan stepped past the first solve's stop time.

Each solve sees its own parameters.

  • When a Model Exchange solve starts, any instance left over from reading an earlier
    solution is freed.
  • Between solves, an instance created with other parameter values is replaced.
  • During a solve the instance is kept, so the FMU's internal state survives.

Automatic differentiation.

  • Calls with ForwardDiff dual numbers no longer fail. The wrapper evaluates the FMU at
    the primal values and takes a forward finite difference along each dual direction:
    what AutoFiniteDiff would compute. Rodas5P and other stiff solvers then work with
    their default autodiff.
  • Derivatives with respect to parameters are effective only when all of the FMU's
    parameters are real.

Initial states from the FMU.

  • Each continuous state's default is a callable parameter, FMUInitialStates. It
    initializes an FMU instance with the system's parameters and inputs, and reads the
    states back.
  • So an FMU whose states have no start (initial = "calculated", like the existing
    SimpleArrayModel.fmu) runs without the caller guessing them, and a start that
    depends on parameters is right.
  • A value given to the problem still overrides it.
  • Co-Simulation sets only the states that have a start value. The standard does not
    allow setting calculated ones.

Vector types. The FMU is handed a plain Vector{Float64} whatever vector type it is
called with. FMIBase stores the values it writes in Vector{Float64} fields, so it failed
on anything else, such as the static vectors that code-generation passes supplied through
the optimize option can produce. Plain ModelingToolkit code generation does not do
this, so there is no test for it here.

The docstring is updated to match.

Behaviour a user may notice

  • States now have defaults. Code that passes initial values for every state works as
    before; code that passed none now runs instead of failing.
  • Co-Simulation results at the final time change by one communication step. They now
    match FMI.jl.
  • A Model Exchange FMU with no states has an extra unknown, __mtk_internal_placeholder.
  • The existing tests in test/fmi/fmi.jl pass 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 needs
a number, and an ImperativeAffect that modifies states writes into the immutable state
vector.

Tests

test/fmi/reference_fmus.jl is a new file in the FMI group, run by a second
@safetestset line in test/group_fmi.jl. It uses Reference FMUs v0.0.39, downloaded by
FMIZoo, plus the two FMUs already in test/fmi/fmus/. v0.0.39 is the newest release
FMIZoo can download, because later releases name their archive differently. Each test set fails without the fixes it
covers:

Test set FMUs Covers
States and outputs match FMI.jl, FMI 2 and 3, both modes, no initial values given VanDerPol, BouncingBall, Dahlquist State and derivative order, outputs that are states, events, the last Co-Simulation step, FMU-computed initial states
Integer, boolean and enumeration ports Feedthrough Non-real ports, FMUs with no states
Time events and step-like outputs, again after a re-solve and a shorter span Stair Discrete outputs, time events, a fresh instance per solve
Co-Simulation over a longer span, and ending between two steps VanDerPol Per-solve stop time, last step
Initial states come from the FMU, and a given value wins Dahlquist, SimpleArrayModel FMU-computed initial states
Solving again after changing a parameter SimpleAdder A fresh instance per solve
Stiff solvers with ForwardDiff VanDerPol, BouncingBall Automatic differentiation

Verified:

  • The FMI group through the repository's runner on this branch (master plus these
    commits): GROUP=FMI, Pkg.test(), Julia 1.12, Linux: 195 of 195, including the 60
    existing tests.
  • Without the ext/MTKFMIExt.jl changes, every new test set fails. The one check that
    passes 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.
  • Runic: the changed files pass --check.

🤖 Generated with Claude Code

scratch and others added 15 commits November 21, 2026 14:36
…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
tom-juliahub marked this pull request as ready for review November 22, 2026 01:00

This branch has not been deployed

No deployments
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.

1 participant