modelKalmanFilter

Kalman filter implemented in Python and called from Modelica

Extends from Modelica.Icons.Example (Icon for runnable examples).

Information

This example demonstrates the implementation of a Kalman filter in Python. The model generates a uniform random number, which is computed in the Python file KalmanFilter.py by the function random(seed). This random number is added to a sine wave and then sent to the function filter(u) in the above Python file. The function filter(u) implements a Kalman filter that estimates and returns the state. The function saves its temporary variables to a file called tmp-kalman.json.

When simulating this model, the figure below will be generated which shows the sine wave, the sine wave plus noise, which is input to the Kalman filter, and the estimated state which is the output of the Kalman filter.

image

Implementation

The code is based on http://www.scipy.org/Cookbook/KalmanFiltering.

Parameters

TypeNameDefaultDescription
Modelica.Units.SI.TimesamplePeriod0.001Sample period of component

Components

TypeNameDefaultDescription
Python_3_12.Real_RealranGenerate a random number in Python
Modelica.Blocks.Sources.ContinuousClockclock
Python_3_12.Real_RealkalFilKalman filter in Python
Modelica.Blocks.Sources.SinesineSine wave
Modelica.Blocks.Math.AddaddAddition of signals before sending it to the Kalman filter

Revisions

  • September 19, 2025, by Michael Wetter:
    Updated to Python 3.12.
  • August 27, 2021, by Michael Wetter:
    Updated to Python 3.8.
  • April 10, 2020, by Jianjun Hu and Michael Wetter:
    Updated to Python 3.6.
  • October 24, 2019, by Antoine Gautier:
    Changed the temporary file format from pickle to json as the former can trigger a segfault with JModelica simulation run in a subprocess.
    This is for Buildings, #1587.
  • February 5, 2013, by Michael Wetter:
    First implementation.