How-to guides › Model physics

How-to guides

Physics: fitting, FMUs and Modelica

A physical network is a set of parts (a resistor, a motor, an inertia) linked with no direction, as on a schematic. This page shows three things you can do with one: fit its parameters to measurements, run an FMU inside it, and write it as Modelica. The equations themselves are in the specification.

A first fit#

examples/dc-motor/main.arche is a DC motor turning a load. Its model says the armature resistance r is 1 Ω, the motor constant k is 0.01 and the friction d is 0.1. Suppose the real motor is a little different. Here the "real" motor is a copy of the model, real.arche, with other values:

  part motor: DcMotor(r = 1.3Ω, k = 0.012)
  part friction: RotationalDamper(d = 0.08)

Record a run of it, then fit the model to that run:

archec physics real.arche Drive --for 3s --every 10ms --print load.w,motor.la.i --csv run.csv
archec fit main.arche Drive run.csv --params motor.r,motor.k,friction.d
✓ 301 samples of 2 variables → run.csv
fit Drive — 2 signals, 3 parameters; Levenberg–Marquardt, 7 iterations, 34 runs

  parameter   before  fitted  uncertainty (1σ)
  motor.r     1 Ω     1.3 Ω   ± 2.8e-17 Ω (2.2e-15 %)
  motor.k     0.01    0.012   ± 4.2e-18 (3.5e-14 %)
  friction.d  0.1     0.08    ± 2.9e-17 (3.6e-14 %)

  signal      samples  RMS error before  after
  motor.la.i  301      2.141 A           0 A
  load.w      301      0.1955 rad/s      7.275e-16 rad/s

  cost 1.381 → 3.806e-30 (sum of squares, each signal scaled by its spread)

The fit finds the three values back. With a real motor, the data has noise, the errors after the fit are not zero, and the uncertainty is larger.

Fitting the model to measurements#

archec fit finds the parameters of a physical network from what the real system did. This is system identification (what MuJoCo is often used for), done with the model's own network.

  1. The measured inputs drive the network.
  2. Its outputs are compared with the measured outputs.
  3. Least squares (Levenberg–Marquardt) moves the parameters until the two agree.

The data is one of:

  • a CSV: time first, then a column per signal, named as the network's variables;
  • any log that archec replay reads. Each message field is then a series named MSG.field. --signals load.w=MOTOR.speed maps a series to a variable.

A parameter is a part's (motor.r), the system's, or a parameter. A parameter is kept within its tolerance.

What it reports:

  • Two parameters that the data cannot tell apart are named (fit-correlated).
  • A parameter that the data does not see at all is left alone (fit-no-influence).

Options:

  • --write puts the fitted values in the model, and leaves the rest of the file as it was.
  • --html fit.html writes a report.
  • --json prints the result as JSON.

See docs/commands.md.

FMUs in the simulation#

An FMU (Functional Mock-up Unit) is a packaged simulation model. archec takes FMI 2.0 FMUs for co-simulation, from Modelica, Simulink, Amesim and others, or from archec fmi. An FMU can be a component's continuous behaviour:

archec import plant.fmu -o plant.arche       # writes the component below
component Plant {
  fmu "plant.fmu"
  solver 1ms
  in power: data              // an input: the flow linked into it
  var temp: float64 = 20      // an output (or a parameter): readable by Python and tests
}

How it runs:

  • The FMU is copied into the project (fmus/).
  • Arche's simulation steps it at the solver step, next to the components that have equations.
  • Its inputs take the flows that arrive at its in ports (or its variables) of the same name.
  • Its outputs go to its out ports (or its variables). A dotted name becomes an underscore: upper.level is upper_level.
  • A step uses the inputs of the step before. This one-step lag is usual in co-simulation.

It runs in arche-cli, and so in archec test, in a small native host. The host uses the FMU's binary for this platform, or builds its sources/ with the system's C compiler.

Real, Integer, Enumeration and Boolean variables are exchanged. An Integer becomes int32 and a Boolean bool. A String variable is left out, with a note.

In Modelica#

archec gen --target modelica writes the network as Modelica, for OpenModelica, Dymola or any Modelica tool.

archec gen examples/dc-motor/main.arche --target modelica -o generated
  generated/modelica/dc_motor.mo
  generated/modelica/simulate_Drive.mos

It writes:

  • one Modelica package, modelica/<project>.mo, with every system whose parts have equations or physical ports. The package is named after the project. Without a project, it is named after the file; for a main.arche, after its folder (dc_motor here).
  • an OpenModelica script per system, modelica/simulate_<System>.mos. omc simulate_Drive.mos, run in that folder, writes Drive_res.csv.
  model Drive "A DC motor turning a load"
    Modelica.Electrical.Analog.Sources.ConstantVoltage supply(V = 12);
    Modelica.Electrical.Analog.Basic.Ground gnd;
    DcMotor motor;
    Modelica.Mechanics.Rotational.Components.Inertia load(J = 0.01, w(start = 0, fixed = true), phi(start = 0, fixed = true));
    …
  equation
    connect(supply.p, motor.p);
    connect(motor.flange, load.flange_a);
    …
    annotation(experiment(StartTime = 0, StopTime = 3, Interval = 0.006, Tolerance = 1e-06));
  end Drive;

What each part becomes#

Parts.

  • A part of std/physics is the Modelica Standard Library (MSL 4.0) component it is. Its parameters are renamed, and its states are fixed at their start (see the table below).
  • The other parts are models of their own, with their parameters, variables and equations as written. These are the project's components, and the std parts that MSL has no exact match for. In their equations:
    • t is time;
    • clamp(x, lo, hi) is min(max(x, lo), hi);
    • ln is log;
    • step(x) is if x >= 0 then 1 else 0;
    • a constant is its value.
  • A composite part stays one: its parts and links are inside its own model, and its parameters are passed on (Resistor(r = r) is ra(R = r)).

Ports.

  • A physical port is MSL's connector:
    • pin is Interfaces.Pin;
    • flange is Translational.Interfaces.Flange_a;
    • shaft is Rotational.Interfaces.Flange_a;
    • heat is HeatTransfer.Interfaces.HeatPort_a.
  • MSL's mechanical connectors carry a position, so a velocity potential is its derivative: flange.v is der(flange.s), shaft.w is der(shaft.phi).
  • A port type that MSL does not have (std's fluid, or the project's own) is a connector of the package, with its potentials and flows (flow Real q).
  • A signal (an in or out of a part with equations) is a RealInput or RealOutput.
    • An input fed by several outputs takes their sum, as Arche's simulator adds them.
    • An input that nothing in the network feeds is 0.

Behaviour. A fn main that only waits and sets variables (wait 800ms; valve = 0) becomes when time >= 0.8 then valve := 0; on a discrete Real. Other code is left out, with a note: handlers, state machines, any other statement.

The experiment runs:

  • to the last time that the system's test plans check (else 1 s);
  • at its solver step (else a 500th of the run);
  • with a tolerance of 1e-6.
std/physics Modelica Standard Library parameters
Resistor Electrical.Analog.Basic.Resistor r → R
Capacitor Electrical.Analog.Basic.Capacitor c → C, v0 → v(start)
Inductor Electrical.Analog.Basic.Inductor l → L, i0 → i(start)
Ground Electrical.Analog.Basic.Ground
VoltageSource Electrical.Analog.Sources.ConstantVoltage v → V
SignalVoltage Electrical.Analog.Sources.SignalVoltage its input u is v
CurrentSource Electrical.Analog.Sources.ConstantCurrent i → I
Emf Electrical.Analog.Basic.EMF k
Mass Mechanics.Translational.Components.Mass (flange_a) m, s0 → s(start), v0 → v(start)
Damper Mechanics.Translational.Components.Damper (a, b → flange_a, flange_b) d
Fixed Mechanics.Translational.Components.Fixed
Force Mechanics.Translational.Sources.ConstantForce f → f_constant
Inertia Mechanics.Rotational.Components.Inertia (flange_a) j → J, w0 → w(start); phi starts at 0
RotationalDamper Mechanics.Rotational.Components.Damper d
FixedShaft Mechanics.Rotational.Components.Fixed
Torque Mechanics.Rotational.Sources.ConstantTorque tau → tau_constant
SpeedSensor Mechanics.Rotational.Sensors.SpeedSensor its output w
HeatCapacitor Thermal.HeatTransfer.Components.HeatCapacitor c → C, t0 → T(start); temp is T
ThermalConductor Thermal.HeatTransfer.Components.ThermalConductor (a, b → port_a, port_b) g → G; q is Q_flow
FixedTemperature Thermal.HeatTransfer.Sources.FixedTemperature temp → T
HeatSource Thermal.HeatTransfer.Sources.FixedHeatFlow q → Q_flow
Spring, RotationalSpring their own equations their extension is a state of their own, where MSL's reads it from the flanges' positions
Orifice, Volume, PressureSource their own equations, on the package's FluidPort MSL's fluids are not lumped linear parts

Checked against Modelica#

archec verify --modelica checks the network against a Modelica simulation:

  1. It simulates each system that has test plans with OpenModelica (omc on the PATH, or OMC=/path/to/omc).
  2. It reads the test plans' expectations on the results: at 600ms expect …, within, never:, always:, a step's expect at 600s: …. The names are the network's (motor.la.i) or Arche's (physics.load_w). A value between two samples is interpolated.
  3. It runs archec physics on the same network beside it, and gives each state's largest gap. The gap must stay within --tol (1 % by default) of the state's span.
archec verify examples/dc-motor/main.arche --modelica --system Drive                    # omc runs it
archec verify examples/dc-motor/main.arche --modelica --system Drive --results run.csv  # a run made elsewhere

Here run.csv comes from archec physics examples/dc-motor/main.arche Drive --for 3s --every 10ms --csv run.csv:

Drive — dc_motor.Drive, 3 s (run.csv)
  ✓ TC-SPIN The load reaches its speed (TP-DRIVE)
  ✓ archec physics beside it: 3 states, the largest gap 0.0226036 % of a span (allowed 1 %)
      motor.la.i  max |Δ| 5.699e-4 A at 6 ms, span 11.9585
      load.phi  max |Δ| 1.925e-5 rad at 204 ms, span 2.87968
      load.w  max |Δ| 2.701e-4 rad/s at 6 ms, span 1.19511

The gap is what a sample every 10 ms loses against archec physics' own run.

With no OpenModelica, it says so, writes the Modelica anyway and exits 2:

archec verify --modelica: OpenModelica is not installed (`omc` on the PATH, or OMC=/path/to/omc). The Modelica is in arche-verify/modelica/dc_motor.mo: simulate it with any Modelica tool and give its results — archec verify --modelica --results S_res.csv

Simulate it with any Modelica tool, and give its results with --results S_res.csv (and --system S). The results are a CSV: the time first (time or t), then a column per variable. A column is named by the variable's Modelica name ("motor.la.i") or the network's. OpenModelica's CSV works, and so does archec physics --csv.

Exit codes. It exits 1 when a case fails or archec physics disagrees.

The structure of the Modelica is checked without a Modelica parser, by checkModelica (in the library). It checks:

  • that classes are opened and closed in order;
  • parentheses, and each statement's ;;
  • that every class used is one of the package's, or an MSL class of the table, with the modifiers set there;
  • that every connect is between declared instances.

The tests run it on the examples, and run OpenModelica on them when it is installed.

Limits#

  • An FMU must be FMI 2.0 for co-simulation. String variables are not exchanged.
  • The Arche app in the browser cannot run an FMU, and says so.
  • In Modelica, only a fn main that waits and sets variables is written. Handlers, state machines and other statements are left out, with a note.
  • A test case that does things (do …) has no place in a Modelica run: it is an error in archec verify --modelica. So is a name that the results do not have, such as a state machine's state.
  • MSL's fluids are not lumped linear parts, so Orifice, Volume and PressureSource are written with their own equations.