simulator

Modules

simulator module

class Simulator(model)[source]

Bases: object

A simulator for building digital twins.

This class simulates Model or SimulationModel in a time-stepping manner. It takes a prepared model with a predetermined execution order and runs the simulation by calling each component in sequence for each timestep.

The simulator handles the coordination between components, ensuring that outputs from one component are properly passed as inputs to connected components during each simulation timestep.

Parameters:

model (Model) – The model to be simulated.

Mathematical Formulation:

The simulator operates on a directed multigraph \(G = (V, E, \iota, \alpha, \beta)\) comprising:

\[V = \{c_1, c_2, ..., c_n\}\]
\[E = \{e_1, e_2, e_3, ...\}\]
\[\iota: E \rightarrow V \times V\]
\[\alpha: E \rightarrow \text{Ports}\]
\[\beta: E \rightarrow \text{Ports}\]
where:
  • \(V\) is the set of vertices (components)

  • \(E\) is the set of edge identifiers (connections between components)

  • \(\iota\) is the incidence function mapping edges to vertex pairs

  • \(\alpha\) maps each edge to an input port

  • \(\beta\) maps each edge to an output port

  • Each edge \(e_a \in E\) with \(\iota(e_a) = (c_i, c_j)\) indicates that component \(c_i\) provides input to component \(c_j\)

  • Multiple edges can map to the same vertex pair (multigraph): \(\iota(e_a) = \iota(e_b) = (c_i, c_j)\)

Execution Sequence:

The execution sequence is determined by the model preparation phase (see SimulationModel):

\[L = (c_1, c_2, ..., c_n)\]

Time-Stepping Simulation:

For each timestep \(t \in (t_{start}, t_{start} + \Delta t, ..., t_{end})\), the simulator executes each component \(c_j\) in the specified order \(L\).

First, for component \(c_j\), collect inputs from all connected components:

Component \(c_j\) has input vector \(\mathbf{x}_j \in \mathbb{R}^{n_j^{in}}\) and output vector \(\mathbf{y}_j \in \mathbb{R}^{n_j^{out}}\) where \(n_j^{in}\) and \(n_j^{out}\) are the numbers of input and output ports respectively.

For each input edge of component \(c_j\): \(e_i \in E\) with \(\iota(e_i) = (c_i, c_j)\):

\[x_{j,\alpha(e_i)} = y_{i,\beta(e_i)}\]

where:

  • \(\alpha(e_i)\) and \(\beta(e_i)\) are the input and output ports for edge \(e_i\)

After collecting the inputs, execute the step function of the component:

\[\mathbf{y}_{j,t} = f_j(\mathbf{x}_{j,t}, \mathbf{s}_{j,t}, t, \Delta t)\]

where:

  • \(\mathbf{x}_{j,t}\) is the input sequence for component \(j\) at time \(t\)

  • \(\mathbf{y}_{j,t}\) is the output sequence from component \(j\) at time \(t\)

  • \(\mathbf{s}_{j,t}\) is the internal state of component \(j\) at time \(t\)

  • \(f_j\) is the component’s dynamics function

  • \(\alpha(e)\) and \(\beta(e)\) define the specific input/output ports for edge \(e\)

Shorthand Notation:

The complete simulation process described above can be represented using the compact notation:

\[\boldsymbol{\hat{Y}} = \mathcal{M}(\boldsymbol{X}, \boldsymbol{t}, \boldsymbol{\theta})\]
where:
  • \(\mathcal{M}\) represents the complete simulation model (this Simulator class)

  • \(\boldsymbol{X} \in \mathbb{R}^{n_x \times n_t}\) are the input variables (disturbances, setpoints, etc.)

  • \(\boldsymbol{t} \in \mathbb{R}^{n_t}\) are the simulation timesteps

  • \(\boldsymbol{\theta} \in \mathbb{R}^{n_p}\) are the model parameters

  • \(\boldsymbol{\hat{Y}} \in \mathbb{R}^{n_y \times n_t}\) are the system outputs (predictions, performance metrics)

This notation encapsulates the entire time-stepping simulation process including component execution order, input gathering, and temporal evolution as described in the sections above. This is what happens when we call simulate. We will use this notation in other parts of the documentation.

Examples

Basic simulation execution:

>>> import twin4build as tb
>>> import datetime
>>>
>>> # Create and prepare model
>>> model = tb.SimulationModel(id="building_model")
>>> # ... add components and connections ...
>>> model.load()  # Prepares execution order
>>>
>>> # Create simulator and run simulation
>>> simulator = tb.Simulator(model)
>>> start_time = datetime.datetime(2024, 1, 1, 0, 0, 0)
>>> end_time = datetime.datetime(2024, 1, 2, 0, 0, 0)
>>> step_size = 3600  # 1 hour
>>>
>>> simulator.simulate(
...     start_time=start_time,
...     end_time=end_time,
...     step_size=step_size
... )
>>>
>>> # Access simulation results
>>> results = simulator.get_simulation_readings()
get_actual_readings(start_time, end_time, step_size, reading_type='all')[source]

Get actual sensor and meter readings from physical devices.

Retrieves historical data from physical sensors and meters within the specified time period. Currently reads from CSV files, but designed to be extended for other data sources like quantumLeap.

Parameters:
  • start_time (datetime) – Start time of the readings.

  • end_time (datetime) – End time of the readings.

  • step_size (int) – Step size in seconds.

  • reading_type (str, optional) – Type of readings to retrieve: - “all”: Get readings from all devices - “input”: Get readings only from input devices Defaults to “all”.

Returns:

DataFrame containing actual readings with columns:
  • time: Timestamp index

  • {device_id}: Reading values for each device

Return type:

pd.DataFrame

Raises:

AssertionError – If reading_type is not one of [“all”, “input”].

get_simulation_readings()[source]

Get simulation readings for sensors and meters.

Collects the simulation results from all sensors and meters in the model and organizes them into a pandas DataFrame with timestamps as index.

Returns:

DataFrame containing simulation readings with columns:
  • time: Timestamp index

  • {sensor_id}: Reading values for each sensor

  • {meter_id}: Reading values for each meter

Return type:

pd.DataFrame

get_simulation_timesteps(start_time, end_time, step_size)[source]

Generate simulation timesteps between start and end times.

Creates lists of both second-based and datetime-based timesteps for the simulation period using the specified step size.

Parameters:
  • start_time (datetime) – Start time of the simulation.

  • end_time (datetime) – End time of the simulation.

  • step_size (int) – Step size in seconds.

Notes

Updates the following instance attributes: - secondTimeSteps: List of timesteps in seconds - dateTimeSteps: List of timesteps as datetime objects

simulate(start_time=None, end_time=None, step_size=None, show_progress_bar=True, debug=False, **kwargs)[source]

Simulate the model between the specified dates with the given timestep.

This method:
  1. Initializes the model and simulation parameters

  2. Generates simulation timesteps

  3. Executes the simulation loop with optional progress bar

  4. Updates component states at each timestep

Parameters:
  • start_time – Start time of the simulation.

  • end_time – End time of the simulation.

  • step_size – Step size in seconds.

  • show_progress_bar – Whether to show a progress bar during simulation.

Raises:
  • AssertionError – If input parameters are invalid or missing timezone info.

  • FMICallException – If the FMU simulation fails.