API reference

The public API is called through the OM module (functions are qualified, e.g. OM.simulate).

Simulation and translation

OM.simulate — Function
simulate(modelName, modelFile; startTime=0.0, stopTime=1.0, MSL=false,
         libraries=String[], solver=OMBackend.defaultSolver(), mode=OMBackend.DEFAULT_BACKEND_MODE[], ...)

Translate and simulate a file-based Modelica model in one step. Equivalent to translate(modelName, modelFile; ...) followed by OMBackend.simulateModel(modelName; ...). Returns the simulation result.

Keyword arguments

  • startTime, stopTime: simulation time span (default 0.0 to 1.0).

  • MSL: set true to also load the Modelica Standard Library.

  • MSL_Version: MSL version string (default: a loaded library with the package Modelica, else DEFAULT_MSL_VERSION, "MSL:4.1.0"; another version than a loaded one is an error).

  • libraries: cache keys or file/directory paths for user libraries (see loadLibrary / loadPackage / loadInstalledLibrary).

  • solver: ODE solver (default OMBackend.defaultSolver(): Rodas5P with finite-difference Jacobians).

  • mode: backend mode (default IMTK_MODE).

  • warnMissingStartValues: override missing-start-value warnings.

  • eliminateNonDynamic: elimination of non-dynamic variables before MTK code generation, reducing ODEProblem compilation time. Accepts:

    • true (default): eliminate variables not reachable from state derivatives
    • nothing or false: disable elimination
    • EliminationOptions(...): fine-grained control (see EliminationOptions)

    Eliminated variables are bookkept for potential later reconstruction (e.g. 3D visualization). The optimization is automatically skipped for VSS models and models with structural transitions.

  • observedFilter: filter which alias variables generate observed equations. Reduces MTK compilation time by limiting the observed function size. Accepts nothing (keep all, default), Vector{String} (regex patterns), or Vector{Regex}. Only alias entries whose eliminatedName matches at least one pattern are kept.

  • directRHS: toggle direct-RHS code generation (default reads OMBackend.DIRECT_RHS_GENERATION[]).

  • scalarize: scalarize arrays in the frontend (default OM.SCALARIZE[], false: arrays are kept and the loops reach the generated code where possible, see OM.SCALARIZE).

  • overwriteCache: force re-evaluation of generated code even if the model is already compiled (default false).

Additional keyword arguments are forwarded to OMBackend.simulateModel.

source
simulate(modelName; MSL_Version=nothing, startTime=0.0, stopTime=1.0, ...)

Translate and simulate a model by name, an MSL model or one of libraries. Defaults to MSL=true.

Keyword arguments

  • startTime, stopTime: simulation time span (default 0.0 to 1.0)

  • MSL_Version: MSL version string (default: a loaded library with the package Modelica, else DEFAULT_MSL_VERSION, "MSL:4.1.0"; another version than a loaded one is an error)

  • libraries: the libraries the model is in, instead of the MSL: cache keys (loadInstalledLibrary, loadLibrary, loadPackage) or file/directory paths. The libraries an installed library uses come along with its key.

  • solver: ODE solver (default OMBackend.defaultSolver(): Rodas5P with finite-difference Jacobians)

  • mode: backend mode (default IMTK_MODE)

  • warnMissingStartValues: override missing-start-value warnings

  • eliminateNonDynamic: elimination of non-dynamic variables before MTK code generation, reducing ODEProblem compilation time. Accepts:

    • true (default): eliminate variables not reachable from state derivatives
    • nothing or false: disable elimination
    • EliminationOptions(...): fine-grained control (see EliminationOptions)

    Eliminated variables are bookkept for potential later reconstruction (e.g., 3D visualization). The optimization is automatically skipped for VSS models and models with structural transitions.

  • observedFilter: filter which alias variables generate observed equations. Reduces MTK compilation time by limiting the observed function size. Accepts nothing (keep all, default), Vector{String} (regex patterns), or Vector{Regex}. Only alias entries whose eliminatedName matches at least one pattern are kept. Use component-level patterns like ["^rev_", "^body_"] to observe specific components.

  • overwriteCache: force re-translation and re-evaluation even if the model is already compiled (default false). Useful when code generation logic has changed and the cached compiled model is stale.

A translation of the model from earlier in the session is reused when it had the same scalarize, MSL version, libraries, observedFilter and eliminateNonDynamic; else the model is translated again.

Example

sol = OM.simulate("Modelica.Mechanics.MultiBody.Examples.Elementary.Pendulum"; stopTime=1.0)
# On MSL 3.2.3:
sol = OM.simulate("Modelica.Mechanics.MultiBody.Examples.Elementary.Pendulum";
                  MSL_Version="MSL:3.2.3", stopTime=1.0)
# With observed filter for faster compilation:
sol = OM.simulate("Modelica.Mechanics.MultiBody.Examples.Elementary.Pendulum"; stopTime=1.0,
                  observedFilter=["^rev_", "^body_"])
# Force re-translation (e.g. after code generation changes):
sol = OM.simulate("Modelica.Mechanics.MultiBody.Examples.Elementary.Pendulum"; overwriteCache=true)
# A model of an installed library:
key = OM.loadInstalledLibrary("Buildings"; version = "13.0.0")
sol = OM.simulate("Buildings.Controls.OBC.CDL.Reals.Validation.Add"; libraries = [key])
source
OM.translate — Function
translate(modelName, modelFile; MSL=false, libraries=String[], ...)

Translate a Modelica model from a file and load it in memory. The model can be simulated at a later stage by calling simulate with the name of the model.

If MSL = true the compiler will use the Modelica Standard Library (MSL) version 4.1.0 by default. The bundled versions are MSL:4.1.0 and MSL:3.2.3.

Keyword arguments

  • MSL::Bool = false: whether to load the MSL alongside the model file.

  • MSL_Version: which MSL version to use: by default a loaded library with the package Modelica (loadedLibraries), else DEFAULT_MSL_VERSION ("MSL:4.1.0"); another version than a loaded one is an error.

  • libraries::Vector{String} = String[]: cache keys or file paths for user libraries to load alongside the model. Load libraries first with OM.loadLibrary or pass .mo file paths directly.

  • mode: backend mode (default IMTK_MODE).

  • tunableParameters::Vector{String} = String[]: parameters kept as parameters of the compiled model instead of being folded into its equations (["body.m", "k"]; an array as a whole), so simulate(...; parameters) can set them without translating again; isTunable, pristineParameters. A parameter the compiler needs as a constant (an array size, a structural condition) stays folded (isTunable is false).

  • warnMissingStartValues: control warnings for missing start values.

  • eliminateNonDynamic::EliminationSetting = true: elimination of variables that do not influence the dynamic states, before MTK code generation (shorter ODEProblem compilation). Accepts:

    • true (default): eliminate the variables not reachable backward from the state derivatives
    • nothing or false: no elimination
    • EliminationOptions(...): fine-grained control (see EliminationOptions)

    Eliminated equations are bookkept in the SIM_CODE for later reconstruction (e.g. 3D visualization). This optimization is automatically skipped for models with structural transitions (VSS models).

Examples

OM.translate("CircuitExamples.Circuit", "circuit.mo")

# Without the elimination of non-dynamic variables (on by default):
OM.translate("MyModel", "model.mo"; eliminateNonDynamic=false)
source
translate(modelName; MSL_Version=nothing, libraries=String[], mode, eliminateNonDynamic=true)

Translate a model by name, an MSL model or one of libraries, and load it in memory.

Keyword arguments

  • MSL_Version: which MSL version to use: by default a loaded library with the package Modelica (loadedLibraries), else DEFAULT_MSL_VERSION ("MSL:4.1.0"); another version than a loaded one is an error.

  • libraries: the libraries the model is in, instead of the MSL: cache keys (loadInstalledLibrary, loadLibrary, loadPackage) or file/directory paths. The libraries an installed library uses come along with its key.

  • mode: backend mode (default IMTK_MODE).

  • tunableParameters::Vector{String} = String[]: parameters kept as parameters of the compiled model instead of being folded into its equations (["body.m", "k"]; an array as a whole), so simulate(...; parameters) can set them without translating again; isTunable, pristineParameters. A parameter the compiler needs as a constant (an array size, a structural condition) stays folded (isTunable is false).

  • warnMissingStartValues: control warnings for missing start values.

  • eliminateNonDynamic::EliminationSetting = true: elimination of variables that do not influence the dynamic states, before MTK code generation (shorter ODEProblem compilation). Accepts:

    • true (default): eliminate the variables not reachable backward from the state derivatives
    • nothing or false: no elimination
    • EliminationOptions(...): fine-grained control (see EliminationOptions)

    Eliminated equations are bookkept in the SIM_CODE for later reconstruction (e.g. 3D visualization). This optimization is automatically skipped for models with structural transitions (VSS models).

Examples

OM.translate("Modelica.Mechanics.MultiBody.Examples.Elementary.Pendulum")

# Without the elimination of non-dynamic variables (on by default):
OM.translate("Modelica.Mechanics.MultiBody.Examples.Elementary.Pendulum";
             eliminateNonDynamic=false)
source
OM.flatten — Function
flatten(modelName, modelFile; repr=:FM, scalarize=true, MSL=false,
        MSL_Version=nothing, libraries=String[])

Flatten a Modelica model from a file. Returns a Tuple of the flattened representation and the function cache.

Keyword arguments

  • repr: output representation, :FM (FlatModel, default) or :DAE
  • scalarize: scalarize arrays (default true; false keeps array variables, array equations and for-equations, as omc's -d=-nfScalarize; only applies to :FM)
  • MSL: load the Modelica Standard Library alongside the model file
  • MSL_Version: MSL version string (default: a loaded library with the package Modelica, else DEFAULT_MSL_VERSION, "MSL:4.1.0"; another version than a loaded one is an error)
  • libraries: cache keys or file/directory paths for user libraries

Examples

OM.flatten("HelloWorld", "HelloWorld.mo")
OM.flatten("HelloWorld", "HelloWorld.mo"; repr=:DAE)
OM.flatten("MyModel", "model.mo"; MSL=true)
OM.flatten("MyModel", "model.mo"; libraries=["MyLib"])
source
flatten(modelName; MSL_Version=nothing, libraries=String[], scalarize=true)

Flatten a model by name: an MSL model, one of libraries, or one of the loaded libraries (loadedLibraries). Returns a Tuple of the flattened representation and the function cache.

  • libraries: the libraries the model is in, instead of the MSL: cache keys (loadInstalledLibrary, loadLibrary, loadPackage) or file/directory paths. The libraries an installed library uses come along with its key.
  • MSL_Version: default: a loaded library with the package Modelica, else DEFAULT_MSL_VERSION.

Examples

OM.flatten("Modelica.Mechanics.MultiBody.Examples.Elementary.Pendulum")
OM.flatten("Modelica.Mechanics.MultiBody.Examples.Elementary.Pendulum";
           MSL_Version="MSL:3.2.3")
key = OM.loadInstalledLibrary("Buildings"; version = "13.0.0")
OM.flatten("Buildings.Controls.OBC.CDL.Reals.Validation.Add"; libraries = [key])
source
OM.getMTKProblem — Function
getMTKProblem(modelName; tspan=(0.0, 1.0), overwriteCache=false) -> Tuple

Build the problem of an already-translated model without solving it. The model must first be compiled via translate (or implicitly by a prior simulate). Returns the tuple of the generated model function; its first two elements are the ODEProblem and the model's event callbacks, which a solve needs too:

prob, callbacks = OM.getMTKProblem("LotkaVolterra"; tspan = (0.0, 30.0))
sol = solve(prob, Rodas5P(); callback = callbacks)

Keyword arguments

  • tspan: time span used when constructing the problem.
  • overwriteCache: rebuild the problem even if a cached one exists.
source
OM.resimulate — Function
resimulate(modelName; startTime=0.0, stopTime=1.0,
           solver=OMBackend.defaultSolver(), parameters=Dict(), kwargs...)

Re-run an already-compiled model without rebuilding the MTK problem. The model must have been compiled with translate (or implicitly by an earlier simulate) first. parameters (name => value) changes parameters that were kept tunable at compile time (OMBackend.withTunableParameters); other keyword arguments go to the solver. Returns the simulation result.

When the model is not found, the available compiled model names are printed and the underlying error is logged.

source

Tunable parameters

OM.isTunable — Function
isTunable(modelName, names) -> Bool

Whether the compiled modelName has all names as tunable parameters (translate(...; tunableParameters)), so that simulate(...; parameters) can set them. names are Modelica names (body.m) or OM.jl's (body_m, canonicalName). False without a compiled build, or after the model was translated again with other tunable parameters.

OM.translate("LotkaVolterra", "lv.mo"; tunableParameters = ["alpha", "beta"])
OM.isTunable("LotkaVolterra", ["alpha", "beta"])   # true
OM.simulate("LotkaVolterra"; MSL = false, parameters = Dict(:alpha => 1.2), tspan = (0.0, 10.0))
source
OM.pristineParameters — Function
pristineParameters(modelName) -> Union{Nothing, Vector}

The parameter vector the simulations of the compiled modelName start from. A solution's problem (sol.prob.p) carries the values its event callbacks left, so a problem solved again starts from this one (remake(sol.prob; p = OM.pristineParameters(name))). nothing without a compiled build (the default mode, IMTK_MODE, keeps one from translate).

source
OM.eventCount — Function
eventCount(modelName; problem = nothing, tspan = (0.0, 1.0)) -> Int

The number of event callbacks of the compiled modelName: of its build (a problem built for tspan without one), or of problem's own callbacks (problem.kwargs[:callback]), whichever is larger. OMBackend's step control of algebraic variables only limits steps: no event.

source
OM.canonicalName — Function
canonicalName(name) -> String

The name of a Modelica variable or parameter (body.m, der(x), a[2].b) in OM.jl's problems and solutions (body_m, der(x), a[2]_b), as a Symbol indexes them: sol[Symbol(OM.canonicalName("body.m"))].

source
OM.IMTK_MODE — Constant

The backend modes the mode keyword of translate and simulate takes: IMTK_MODE (the default: the ModelingToolkit system built and simplified at translate time, its build kept for every simulation), MTK_MODE (built at each simulate). A model translated with its arrays kept (scalarize = false, the default) that arrayPreserveDE takes runs its own DifferentialEquations.jl module, whatever the mode.

source

Libraries

OM.loadLibrary — Function
loadLibrary(libraryPath::String; name=nothing)

Load a Modelica library from a single .mo file into the session. Returns its cache key.

The library stays loaded (as omc's loadFile): later translate, simulate, flatten and exportModelica calls see it without libraries, until unloadLibrary. Loading the file again replaces it. Another loaded library with one of its top-level classes is an error naming both (loadedLibraries).

If name is not provided, the key is derived from the top-level class name.

Example

OM.loadLibrary("path/to/MyLib.mo")
OM.translate("MyModel", "model.mo")   # MyModel uses MyLib
source
OM.loadPackage — Function
loadPackage(dirPath::String; name=nothing)

Load a Modelica library organized as a directory tree with package.mo files into the session. Returns its cache key. It stays loaded, as loadLibrary's.

Each .mo file is parsed individually and its within clause determines where the class is placed in the package hierarchy.

Example

OM.loadPackage("path/to/MyLibrary/")
OM.simulate("UserModel", "model.mo")   # UserModel uses MyLibrary
source
OM.loadInstalledLibrary — Function
loadInstalledLibrary(name; version=nothing, forceReload=false, autodeps=true, installDir=nothing) -> String

Load a Modelica library discovered via libraries() into the session, with the libraries it uses. Returns its cache key. It stays loaded, as loadLibrary's: loading Modelica 3.2.3 while Modelica 4.1.0 is loaded is an error naming both; unloadLibrary unloads one.

Keyword arguments

  • version: pin to a specific installed version (e.g. "4.1.0"): an exact match, else a prefix ("4.1"). When nothing, the first one libraries() lists (OM.jl's directory before OpenModelica's).
  • forceReload: re-parse the library even if it is already cached.
  • autodeps: also load the libraries its uses annotation names (e.g. ModelicaServices, Complex), resolved before it is parsed; a missing one is an error naming it.
  • installDir: look only in this directory of installed libraries (one installLibrary(...; dest) installed into).

Example

OM.loadInstalledLibrary("Modelica"; version = "4.1.0")
OM.simulate("Modelica.Blocks.Continuous.Integrator")   # the loaded Modelica 4.1.0
source
OM.loadedLibraries — Function
loadedLibraries() -> Vector{String}

The keys of the libraries loaded into the session (loadLibrary, loadPackage, loadInstalledLibrary, loadMSL), in load order, each followed by the libraries it uses. Every translate, simulate, flatten and exportModelica sees them without libraries; a model's own file comes first. A loaded library with the package Modelica is the MSL of every call that uses one (MSL = true, models by name, a model using Modelica without loading it).

source
OM.unloadLibrary — Function
unloadLibrary(key) -> Vector{String}

Unload the loaded library key and the libraries only it used (loadedLibraries): later calls no longer see them. The models translated while one of them was loaded are forgotten (a simulate translates them again), and so are their in-memory parses; the disk cache keeps the parses, so loading one again is fast. An error when key is not loaded, or is loaded only as a library another loaded library uses. Returns the keys no longer loaded.

OM.loadInstalledLibrary("Modelica"; version = "3.2.3")
OM.unloadLibrary("Modelica_3_2_3")
OM.loadInstalledLibrary("Modelica"; version = "4.1.0")
source
OM.installLibrary — Function
installLibrary(name; version, url = nothing, tag = nothing, subdir = nothing, dest = nothing) -> String

Install the Modelica library name into ~/OMJL/libraries/ (Windows: %APPDATA%\OMJL\libraries; or dest) as <name> <version>/, from a shallow git clone of its release tag (OMFrontend.installLibrary). url is its git repository (a GitHub URL, say); without it a registered library (Buildings) comes from its own. tag defaults to v<version>, then <version>; subdir to the folder name with a package.mo, else the repository's root. The package is checked to be name, its version annotation against version, and the libraries it uses are listed as available or missing.

After installation libraries() discovers it and loadInstalledLibrary loads it.

Example

OM.installLibrary("Buildings"; version = "13.0.0")
OM.installLibrary("ExternData"; version = "3.2.0", url = "https://github.com/modelica-3rdparty/ExternData")
key = OM.loadInstalledLibrary("Buildings")
source
OM.libraries — Function
libraries(; installDir = nothing) -> Dict{String, Vector{NamedTuple}}

Return all Modelica libraries discovered in the directories of installed libraries, OM.jl's (~/OMJL/libraries, where installLibrary installs) before OpenModelica's (~/.openmodelica/libraries; on Windows both under %APPDATA%), or only in installDir when it is given, and in OMFrontend's bundled lib/Modelica/ folder (excluding the pre-packaged MSL_* files).

Each value is a vector of (version, path, source) named tuples.

Example

avail = OM.libraries()
# avail["Modelica"] => [(version="4.1.0", path="...", source=:installed), ...]
source

Output and inspection

OM.exportCSV — Function
exportCSV(modelName, sol; filePath = nothing)

Write an OMEdit-compatible CSV with the state variables of sol and, when available, the observed (algebraic / alias) variables. If filePath is omitted, the file is written to <modelName>_res.csv in the current directory. Returns the path written.

To view the result in OMEdit, choose File > Open Result(s) file.

source
exportCSV(modelName, sols::Vector; filePath = nothing, coalesce = false)

Write one OMEdit-compatible CSV per solution in sols. This form is intended for variable structure systems (VSS), where simulation produces several subsolutions across mode transitions. Each subsolution is written to <modelName>_part<i>.csv.

Keyword arguments

  • filePath: when coalesce = true, the path of the merged file. The directory portion is also used as the destination for the per-part files.
  • coalesce: when true, the per-part files are concatenated into filePath (or <modelName>_res.csv if filePath is nothing).
source
OM.writeModelToFile — Function
writeModelToFile(modelName, modelFile, filePath; MSL=false, MSL_Version=nothing,
                 mode=OMBackend.DEFAULT_BACKEND_MODE[], keepComments=true, keepBeginBlocks=true)

Translate a file-based Modelica model and write the generated Julia code to filePath for inspection or debugging. Equivalent to calling translate followed by OMBackend.writeModelToFile.

Keyword arguments

  • MSL, MSL_Version, mode: forwarded to translate.
  • keepComments: keep # ... comments in the emitted code.
  • keepBeginBlocks: keep redundant begin ... end blocks in the emitted code.

Example

OM.writeModelToFile("MyModel", "MyModel.mo", "/tmp/MyModel_debug.jl")
source
writeModelToFile(modelName, filePath; MSL_Version=nothing,
                 mode=OMBackend.DEFAULT_BACKEND_MODE[], keepComments=true, keepBeginBlocks=true)

Translate an MSL model by name and write the generated Julia code to filePath. See writeModelToFile(modelName, modelFile, filePath; ...) for the file-based form.

Example

OM.writeModelToFile("Modelica.Mechanics.MultiBody.Examples.Elementary.Pendulum",
                    "/tmp/pendulum_debug.jl")
source
OM.exportModelica — Function
exportModelica(modelName, file; MSL=false, MSL_Version=nothing,
               libraries=String[], printBindingTypes=false, scalarize=false)

Returns the flat Modelica representation as a String.

Keyword arguments

  • MSL: load the Modelica Standard Library alongside the model file
  • MSL_Version: MSL version string (default: a loaded library with the package Modelica, else DEFAULT_MSL_VERSION, "MSL:4.1.0"; bundled: 4.1.0 and 3.2.3)
  • libraries: cache keys or file/directory paths for user libraries
  • printBindingTypes: include type annotations in bindings (debugging only)
  • scalarize: enable scalarization (default false). Note that the omc of which this is based does not scalarize flat Modelica. Running with scalarization might produce incorrect code.

Examples

OM.exportModelica("MyModel", "model.mo")
OM.exportModelica("MyModel", "model.mo"; MSL=true, MSL_Version="MSL:3.2.3")
OM.exportModelica("MyModel", "model.mo"; libraries=["MyLib"])
source
exportModelica(modelName; MSL_Version=nothing, printBindingTypes=false, scalarize=false)

Export flat Modelica for an MSL model by name.

Examples

OM.exportModelica("Modelica.Mechanics.MultiBody.Examples.Elementary.Pendulum")
source
OM.componentInterface — Function
componentInterface(modelName, [modelFile]; component, MSL = modelFile === nothing,
                   MSL_Version = nothing, libraries = String[]) -> NamedTuple

The interface of component (its name in the model: "spring", "engine.damper") in the flattened modelName, as plain values (no frontend types):

  • class: the full name of the component's class;
  • connectors: its own connectors, name => (class, variables), each variable a flat name and its role (:flow, :stream, :input, :output or :potential);
  • variables: the flat names of all its variables;
  • equations: the flat model's equations that read it, as flat Modelica;
  • declaration: where it is declared (info: fileName, lineNumberStart, columnNumberStart, lineNumberEnd, columnNumberEnd), the name of the class declaring it (parent) and that class's span (parent_info);
  • graphics: its class's icon as Modelica text, to draw a replacement like it (OMFrontend.componentGraphics): coordinateSystem ("coordinateSystem(...)", or empty), items (the graphic items, its base classes' first, as tools draw them) and placements (connector => its "Placement(...)" annotation).

An error if the model has no component of that name.

Examples

OM.componentInterface("Modelica.Mechanics.Rotational.Examples.First"; component = "spring")
source

Scripting

See Scripting (.mos) for the full engine description.

OM.runScript — Function
runScript(path; context=nothing, output=stdout, maxLoopIterations=1_000_000, stopOnError=nothing)
    -> MosScripting.ScriptResult

Execute an OpenModelica-style .mos script. Relative paths used by scripting commands are resolved from the script's directory. As in omc, a failing model command (loadFile, loadModel, simulate, translateModel, buildModel, ...) records its message for getErrorString() and returns its failure value (false, an empty SimulationResult), and the script goes on; stopOnError = true stops at it with a MosExecutionError instead (the context's setting when nothing; a new context goes on). A supplied MosScripting.ScriptContext may be reused to preserve variables, loaded libraries, and the last simulation between scripts.

The returned ScriptResult contains each evaluated statement value, the final script variables, and the execution context.

Example

result = OM.runScript("experiment.mos")
result.variables
source