WOLFRAM

Advanced Real-Time Simulation

IntroductionSimulation Data
Building and LaunchingVisualization
Connection ControlSimulation Input Sources

Introduction

The function WSMRealTimeSimulate is used to simulate models from Wolfram SystemModeler. It automates the most common use case of building and simulating a model in real time.

In many cases, it can be useful to gain greater control over the real-time simulation. This tutorial describes how to control the simulation in greater detail, how to interact with it using inputs and outputs, and how to visualize simulation data.

This is a hands-on tutorial. You are expected to evaluate all the input lines as you reach them and watch what happens. The accompanying text will not make sense without evaluating as you read.

To use functionality from Wolfram SystemModeler Link, load the package:

This tutorial will use the model "InputAdd" in the "DocumentationExamples" package. The model is a simple addition of a sine wave and an input.

Building and Launching

When simulating a model with WSMRealTimeSimulate, the Modelica model is first translated into a simulation executable. A simulation file is also generated, which is used to control parameter values, initial values, and options for the simulation. The simulation executable is then started with the simulation file as input, and a connection between the simulation and the Wolfram Language is established. This connection uses a custom protocol built on TCP/IP. The simulation is now ready to be started.

To accomplish this first step, the following functions are available.

WSMRealTimeSimulate[mmodel,]build and launch a simulation
WSMRealTimeConnect[port]connect to a running simulation on port
WSMRealTimeConnect["ip",port]connect to a simulation on "ip":port

Get a connection to a simulation executable.

The WSMRealTimeSimulate function takes the same arguments as WSMSimulate. Instead of continuing the process of simulating and retrieving result data, this function instead returns a WSMSimulationConnection object, allowing more detailed control over the simulation. Build and start a real-time simulation of a basic model with inputs and an output.

It is possible to connect to a running simulation with its IP and port number. Create a second connection to the just-launched simulation using WSMRealTimeConnect.

Configuring IP and Port

When launching a simulation, it is also possible to specify a specific interface and a port to listen to. This makes it possible to start a simulation on one computer and control it from another. The two relevant options are "IP" and "Port".

Automaticlisten on local host
Alllisten on all interfaces
"ip"listen on ip

Possible settings for "IP".

Automaticautomatically choose a port
portlisten on port

Possible settings for "Port".

Start a simulation listening on port number 55000, on all interfaces.

The connection is still listening on the localhost IP 127.0.0.1.

It is also possible to connect to it through the public IP found in $MachineAddresses:

Connection Control

Information Properties

The connection object conn representing the simulation can be queried for a number of properties.

conn["State"]current simulation state
conn["Time"]current simulation time
conn["StopTime"]simulation stop time
conn["ModelName"]name of simulated model
conn["NumberOfEvents"]number of events generated
conn["NumberOfEvaluations"]number of evaluations performed
conn["IP"]IP address of the simulation
conn["Port"]port of the simulation
conn["Diagram"]dynamic diagram of the model
conn["VariableNames"]list of variable names
conn["ParameterNames"]list of parameter names
conn["InputVariables"]list of input variables

Information of a running simulation.

The simulation launched above is not yet started.

There are a fixed number of possible simulation states, shown in this table.

"Unknown"the simulation is in an unknown state
"NotStarted"the initial state, when simulation time is 0
"Running"simulation time is increasing
"Paused"simulation is paused
"Disconnected"the Wolfram Language is disconnected from simulation

Simulation states.

Simulation time is initially at 0.

The "Diagram" property of a connection will return the model diagram. If there are dynamic graphics in the diagram, these will use data for the time point conn[Time]. If the simulation is in a Disconnected state, the diagram will show the static version of any dynamic graphics.

Control Properties

The connection object conn can be used to control the simulation.

conn["Start"]start or resume the simulation
conn["Pause"]pause the simulation
conn["Stop"]stop the simulation
conn["Close"]disconnect the Wolfram Language from the simulation

Controlling a simulation.

Start the simulation, let one second pass, and pause it again.

As the simulation is in real time, the simulation time has also increased by a little over one second.

The simulation is now in a Paused state.

Stopping the simulation will stop the simulation at the current simulation time, quit the simulation executable, and close the connection to the Wolfram Language.

Closing the connection to the simulation will leave the simulation in its current state but remove the connection between the Wolfram Language and the simulation.

Simulation Data

Reading Simulation Data

The connection to a simulation allows retrieving simulation result data while the simulation is running. The latest data point for a variable or list of variables can be retrieved.

conn[{"v1",}]variable values for vi
conn["SimulationData"]create a WSMSimulationData object

Retrieve simulation data.

Start a new simulation and let it run for one second.

Retrieve the current values for the input and output of the running simulation.

When the simulation has stopped or is otherwise unreachable, the result of conn[{v1,}] is {None,}.

A complete WSMSimulationData object can be retrieved.

Another possibility is to register a function that will be called every time the data from the simulation is updated.

WSMLink`Simulate`AddDataMonitor[conn,fn,vars]call fn with time and values for vars each simulation step
WSMLink`Simulate`DeleteDataMonitor[dm]remove the data monitor dm

Handling simulation data monitors.

Start a new simulation.

Add a data monitor that stops the simulation when the value of "y goes below -0.5.

Resume the simulation and let it run until the data monitor above stops it.

Plotting again will read in the new data from the result file.

The simulation data object can only be retrieved if the simulation was launched by WSMRealTimeSimulate. In other cases, the Wolfram Language has no control over where the file with the results is, so it cannot return a full result object. Start one simulation with WSMRealTimeSimulate and connect to it with WSMRealTimeConnect.

Run the simulation for a short while.

Retrieving a result object from the connection received from WSMRealTimeSimulate works.

The connection received from WSMRealTimeConnect lacks the necessary information.

Writing Simulation Data

It is also possible to feed input to a simulation from the Wolfram Language, in a couple of different ways. Either an input can be set once to a given value, or a function can be specified that is called regularly to set an input. It is also possible to set parameter values through the Wolfram Language.

Setting Input Variables

The simplest way to change an input variable in a running simulation is by setting it directly. First, launch a new simulation.

Start the simulation, and after 2 seconds, change the input variable "u" to 1. Let it simulate for 2 more seconds, and then stop the simulation.

Plot the input "u" and output "y" in the resulting simulation.

An input variable can also be continuously updated from the Wolfram Language by giving a function as an argument to WSMLink`Simulate`SetInputs. In that case, the function will be evaluated for each communication with the simulation, and the resulting value will be fed back to the simulation.

In this basic example, after 2 seconds, continuously update the input "u" with a random number.

Show the result in a plot.

If the RefreshRate option is not given, the update will occur every time the Wolfram Language communicates with the simulation. This is controlled by the RefreshRate option given to WSMRealTimeSimulate.

It is also possible to set how often a sample of the input function is sent to the simulation, using the RefreshRate option to WSMLink`Simulate`SetInputs.

Send a new random number every 0.5 seconds.

The RefreshRate default is Automatic, updating on every standard communication with the simulation. Above that, RefreshRate->timespec allows any timespec supported by RunScheduledTask.

Setting Parameter Values

To set a parameter in a simulation, use WSMLink`Simulate`SetParameters.

Start the simulation, and after 2 seconds, change the input variable "u" to 1. Let it simulate for 2 more seconds, and then stop the simulation.

Plot the input "u" and output "y" in the resulting simulation.

It is also possible to give a list of parameters to change.

Change both the amplitude and the offset.

Visualization

The live connection to the simulation can be used to visualize data from a simulation interactively. This section gives a few examples of possible visualizations, but the Wolfram Language offers many ways to visualize data that are not covered here.

WSMPlot

The plotting function WSMPlot has built-in support for simulation connections. You can take a simulation connection and directly plot simulation data.

WSMPlot[conn,{v1,v2,}]plot vi from the connection conn
WSMPlot[conn,{},{tmin,tmax}]plot from tmin to tmax

Plotting directly from a simulation connection.

Launch a real-time simulation of a Newton cradle.

Run the simulation for 4 seconds and then plot the variables x1 through x5.

Plot just the first 2 seconds.

When the simulation progresses, new calls to WSMPlot will use the new results available. Run the simulation for 5 more seconds and plot again.

It is also possible to use WSMRealTimePlot to create plots updating in real time.

Start the simulation and see the plot above update when the simulation progresses.

Gauges

Gauges can be used to dynamically display values from a simulation. Launch a new simulation of the Newton cradle.

Display a dynamic angular gauge, refreshing every 0.1 seconds and displaying the angles of the first and fifth ball in the Newton cradle.

Click the play button above or evaluate this to start the simulation.

Observe how the balls bounce against each other, transferring all their momentum in the collision.

Dynamic Diagrams

Showing dynamic diagrams from a running simulation is straightforward, using Dynamic and Refresh to control the updating frequency. First, launch a simulation of a tank system with controllers.

Display the dynamic diagram of the simulation, refreshing every 0.05 seconds. Click the start button above to start the simulation.

Simulation Input Sources

Gauges

In the Wolfram Language, gauges can be used for input as well as output. This allows gauges to be used as an interactive way to control the input in a running simulation.

Launch a new simulation.

Display an input gauge, controlling the variable newU.

Set the input "u" in the simulation to the variable newU. Use a function that returns newU to continually update the value.

Display the output "y" in a separate gauge.

Finally, start the simulation by clicking the play button above, then drag the handle in the first gauge and see how the output in the second gauge changes.

Control

Similarly to how you can use a gauge to control input, you can also use any type of Control.

Start the simulation by clicking the play button, then drag the control slider to watch the output change in the gauge.

Gamepad and Device Input

The Wolfram Language supports a wide variety of hardware controller and input devices, which can all be used to control inputs to SystemModeler simulations. The principle is the same as with gauges and Control objects above.