• Stars
    star
    174
  • Rank 219,104 (Top 5 %)
  • Language
    HTML
  • License
    MIT License
  • Created over 4 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Simulate dynamic systems expressed in block diagram form using Python

A Python Robotics Package QUT Centre for Robotics Open Source

PyPI version Python Version License: MIT

Build Status Coverage PyPI - Downloads GitHub stars

A Python block diagram simulation package

bdsim is Python 3 package that enables modelling and simulation of continuous-time, discrete-time or hybrid dynamic systems. Systems are conceptualized in block diagram form, but represented in terms of Python objects.

  # define the blocks
  demand = bd.STEP(T=1, name='demand')
  sum = bd.SUM('+-')
  gain = bd.GAIN(10)
  plant = bd.LTI_SISO(0.5, [2, 1])
  scope = bd.SCOPE(styles=['k', 'r--'])
  # connect the blocks
  bd.connect(demand, sum[0], scope[1])
  bd.connect(plant, sum[1])
  bd.connect(sum, gain)
  bd.connect(gain, plant)
  bd.connect(plant, scope[0])
  

Key features include:

  • The block diagram can be created easily using Python code, rather than drawing boxes and wires. This enables use of your favourite IDE, standard version control tools and development workflows.
  • Wires can communicate any Python type such as scalars, lists, dicts, NumPy arrays, objects, and functions. For robotics and vision applications using the Spatial Maths Toolbox for Python wires could send values such as SE3, UnitQuaternion or Twist3 objects.
  • Over 70 blocks for linear, nonlinear functions, display blocks, as well as continuous- and discrete-time dynamics
    • Easy to add your own block, it's simply a class
    • Subsystems are supported, and a subsystem can be independently instantiated multiple times in a system. Subsystems can also be nested.
    • Blocks from other toolboxes are automatically discovered and included. There are blocks for some functions in the Robotics Toolbox for Python (such as arm, ground and aerial robots) and Machine Vision Toolbox for Python (such as cameras). These are defined in the blocks folder of those toolboxes.
  • The diagram can be executed in a headless configuration, particularly useful on an embedded computer like a RaspberryPi.
  • A python-based graphical editor
    • allows graphical creation of block diagrams
    • the diagram is stored in a human readable/editable JSON file with extension .bd
    • creates good-quality graphics for inclusion in publications
    • can launch bdsim to import and execute the model
    • automatically discovers all bsdim and toolbbox blocks and adds them to the block library menu
    • icons can be easily created using any image creation tool or a LaTeX expression

Getting started

We first sketch the dynamic system we want to simulate as a block diagram, for example this simple first-order system

block diagram

which we can express concisely with bdsim as (see bdsim/examples/eg1.py)

     1  #!/usr/bin/env python3
     2  import bdsim	
     4  sim = bdsim.BDSim()  # create simulator
     5  bd = sim.blockdiagram()  # create an empty block diagram
     6	
     7	# define the blocks
     8	demand = bd.STEP(T=1, name='demand')
     9	sum = bd.SUM('+-')
    10	gain = bd.GAIN(10)
    11	plant = bd.LTI_SISO(0.5, [2, 1], name='plant')
    12	scope = bd.SCOPE(styles=['k', 'r--'])
    13	
    14	# connect the blocks
    15	bd.connect(demand, sum[0], scope[1])
    17	bd.connect(sum, gain)
    18	bd.connect(gain, plant)
    19	bd.connect(plant, sum[1], scope[0])
    20	
    21	bd.compile()          # check the diagram
    22
    23	sim.report(bd)   # list the system
    24  out = sim.run(bd, 5)   # simulate for 5s

which is just 15 lines of executable code.

The red block annotations on the hand-drawn diagram are used as the names of the variables holding references to the block instance. The blocks can also have user-assigned names, see lines 8 and 11, which are used in diagnostics and as labels in plots.

After the blocks are created their input and output ports need to be connected. In bdsim all wires are point to point, a one-to-many connection is implemented by many wires, for example

bd.connect(source, dest1, dest2, ...)

creates individual wires from source -> dest1, source -> dest2 and so on. Ports are designated using Python indexing notation, for example block[2] is port 2 (the third port) of block. Whether it is an input or output port depends on context. In the example above an index on the first argument refers to an output port, while on the second (or subsequent) arguments it refers to an input port. If a block has only a single input or output port then no index is required, 0 is assumed.

A group of ports can be denoted using slice notation, for example

bd.connect(source[2:5], dest[3:6)

will connect source[2] -> dest[3], source[3] -> dest[4], source[4] -> dest[5]. The number of wires in each slice must be consistent. You could even do a cross over by connecting source[2:5] to dest[6:3:-1].

Line 21 assembles all the blocks and wires, instantiates subsystems, checks connectivity to create a flat wire list, and then builds the dataflow execution plan.

Line 23 generates a report, in tabular form, showing a summary of the block diagram:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ block  β”‚   type   β”‚ inport β”‚ source β”‚ source type β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚demand@ β”‚ step     β”‚        β”‚        β”‚             β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚gain.0  β”‚ gain     β”‚ 0      β”‚ sum.0  β”‚ float64     β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚plant   β”‚ lti_siso β”‚ 0      β”‚ gain.0 β”‚ float64     β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚scope.0 β”‚ scope    β”‚ 0      β”‚ plant  β”‚ float64     β”‚
β”‚        β”‚          β”‚ 1      β”‚ demand β”‚ int         β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚sum.0   β”‚ sum      β”‚ 0      β”‚ demand β”‚ int         β”‚
β”‚        β”‚          β”‚ 1      β”‚ plant  β”‚ float64     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Line 24 runs the simulation for 5 seconds using the default variable-step RK45 solver and saves output values at least every 0.05s. It causes the following output

>>> Start simulation: T = 5.00, dt = 0.050
  Continuous state variables: 1
     x0 =  [0.]
  Discrete state variables:   0

no graphics backend specified: Qt5Agg found, using instead of MacOSX

bdsim β—‰β—‰β—‰β—‰β—‰β—‰β—‰β—‰β—‰β—‰β—‰β—‰β—‰β—‰β—‰β—‰β—‰β—‰β—‰β—‰β—‰β—‰β—‰β—‰β—‰β—‰β—‰β—‰β—‰β—‰β—‰β—‰ 100.0% - 0s

<<< Simulation complete
  block diagram evaluations: 784
  block diagram exec time:   0.075 ms
  time steps:                123
  integration intervals:     2

This provides a summary of the number of states for the complete system: the number of continuous states, the number of discrete states, and the initial value of the state vectors.

During execution a progress bar is updated and scope blocks pops up a graphical window

bdsim output

The simulation results are in a container object (BDStruct)

>>> out
t      = ndarray:float64 (123,)
x      = ndarray:float64 (123, 1)
xnames = ['plantx0'] (list)
ynames = [] (list)            

which contains an array of time values, an array of state values, and a list of the names of the state variables.

By default the .run() method at line 24 blocks blocks the script until all figure windows are closed (by pressing the operating system close button or typing "q"), or the script is killed with SIGINT. If you want to continue the script with the figures still active then the hold=False option should be set.

If we wished to also record additional outputs, we can add them as watched signals

out = sim.run(bd, watch=[demand, sum])  # simulate for 5s

and now the output is

>>> out
t      = ndarray:float64 (123,)
x      = ndarray:float64 (123, 1)
xnames = ['plantx0'] (list)
y0     = ndarray:float64 (123,)
y1     = ndarray:int64 (123,)
ynames = ['plant[0]', 'demand[0]'] (list)

where

  • t the time vector: ndarray, shape=(M,)
  • x is the state vector: ndarray, shape=(M,N), one row per timestep
  • xnames is a list of the names of the states corresponding to columns of x, eg. "plant.x0"

The watch argument is a list of outputs to log, in this case plant defaults to output port 0. This information is saved in additional variables y0, y1 etc. ynames is a list of the names of the watched variables.

An alternative system report, created by sim.report(bd, type="lists") is more detailed

Blocks::

β”Œβ”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”
β”‚id β”‚    name β”‚ nin β”‚ nout β”‚ nstate β”‚ ndstate β”‚ type  β”‚
β”œβ”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€
β”‚ 0 β”‚  demand β”‚   0 β”‚    1 β”‚      0 β”‚       0 β”‚ step  β”‚
β”‚ 1 β”‚   sum.0 β”‚   2 β”‚    1 β”‚      0 β”‚       0 β”‚ sum   β”‚
β”‚ 2 β”‚  gain.0 β”‚   1 β”‚    1 β”‚      0 β”‚       0 β”‚ gain  β”‚
β”‚ 3 β”‚   plant β”‚   1 β”‚    1 β”‚      1 β”‚       0 β”‚ LTI   β”‚
β”‚ 4 β”‚ scope.0 β”‚   2 β”‚    0 β”‚      0 β”‚       0 β”‚ scope β”‚
β””β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜

Wires::

β”Œβ”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚id β”‚ from β”‚  to  β”‚       description        β”‚  type   β”‚
β”œβ”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ 0 β”‚ 0[0] β”‚ 1[0] β”‚ demand[0] --> sum.0[0]   β”‚ int     β”‚
β”‚ 1 β”‚ 0[0] β”‚ 4[1] β”‚ demand[0] --> scope.0[1] β”‚ int     β”‚
β”‚ 2 β”‚ 3[0] β”‚ 1[1] β”‚ plant[0] --> sum.0[1]    β”‚ float64 β”‚
β”‚ 3 β”‚ 1[0] β”‚ 2[0] β”‚ sum.0[0] --> gain.0[0]   β”‚ float64 β”‚
β”‚ 4 β”‚ 2[0] β”‚ 3[0] β”‚ gain.0[0] --> plant[0]   β”‚ float64 β”‚
β”‚ 5 β”‚ 3[0] β”‚ 4[0] β”‚ plant[0] --> scope.0[0]  β”‚ float64 β”‚
β””β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

In the first table we can see key information about each block, its id (used internally), name, the number of input and output ports, the number of continuous- and discrete-time states, and the type which is the block class. Note that the name is auto-generated based on the type, except if it has been set explicitly as for the blocks demand and plant.

The second table shows all wires in point-to-point form, showing the start and end block and port (the block is represented here by its id) and the type of the object sent along the wire.

To save figures we need to make two modifications, changing line 4 to

     4  sim = bdsim.BDSim(hold=False)  # create simulator

which prevents .run() from blocking and then deleting all the figures. Then, after the .run() we add

     25 scope.savefig()  # save scope figure

If the filename is not given it defaults to the block name, in this case scope.0.pdf.

The output can be pickled and written to a file

examples/eg1.py -o
python -mpickle bd.out
t      = ndarray:float64 (123,)
x      = ndarray:float64 (123, 1)
xnames = ['plantx0'] (list)
y0     = ndarray:float64 (123,)
y1     = ndarray:int64 (123,)
ynames = ['plant[0]', 'demand[0]'] (list)

by default the results are written to bd.out, use the option --out FILE to set it to a specific value.

The block parameters can also be overridden from the command line without having to edit the code. To increase the loop gain we could write:

examples/eg1.py --set gain.0:K=20

More details on this Wiki about:

Other examples

In the folder bdsim/examples you can find a few other runnable examples:

  • eg1.py the example given above
  • waveform.py two signal generators connected to two scopes

Examples from Chapter four of Robotics, Vision & Control 2e (2017):

  • rvc4_2.py Fig 4.2 - a car-like vehicle with bicycle kinematics driven by a rectangular pulse steering signal
  • rvc4_4.py Fig 4.4 - a car-like vehicle driving to a point

RVC Figure 4.4

  • rvc4_6.py Fig 4.6 - a car-like vehicle driving to/along a line

RVC Figure 4.6

  • rvc4_8.py Fig 4.8 - a car-like vehicle using pure-pursuit trajectory following

RVC Figure 4.6

  • rvc4_11.py Fig 4.11 a car-like vehicle driving to a pose

RVC Figure 4.11

Figs 4.8 (pure pursuit) and Fig 4.21 (quadrotor control) are yet to be done.

A more concise way

Wiring, and some simple arithmetic blocks like GAIN, SUM and PROD can be implicitly generated by overloaded Python operators. This strikes a nice balance between block diagram coding and Pythonic programming.

     1  #!/usr/bin/env python3
     2
     3  import bdsim
     4
     5  sim = bdsim.BDSim()  # create simulator
     6  bd = sim.blockdiagram()  # create an empty block diagram
     7
     8  # define the blocks
     9  demand = bd.STEP(T=1, name='demand')
    10  plant = bd.LTI_SISO(0.5, [2, 1], name='plant')
    11  scope = bd.SCOPE(styles=['k', 'r--'], movie='eg1.mp4')
    12
    13  # connect the blocks using Python syntax
    14  scope[0] = plant
    15  scope[1] = demand
    16  plant[0] = 10 * (demand - plant)
    17
    18  bd.compile()   # check the diagram
    19  bd.report()    # list all blocks and wires
    20
    22  out = sim.run(bd, 5, watch=[plant,])  # simulate for 5s

This requires fewer lines of code and the code is more readable. Importantly, it results in in exactly the same block diagram in terms of blocks and wires

Wires::

β”Œβ”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚id β”‚ from β”‚  to  β”‚         description          β”‚  type   β”‚
β”œβ”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ 0 β”‚ 1[0] β”‚ 2[0] β”‚ plant[0] --> scope.0[0]      β”‚ float64 β”‚
β”‚ 1 β”‚ 0[0] β”‚ 2[1] β”‚ demand[0] --> scope.0[1]     β”‚ int     β”‚
β”‚ 2 β”‚ 0[0] β”‚ 3[0] β”‚ demand[0] --> _sum.0[0]      β”‚ int     β”‚
β”‚ 3 β”‚ 1[0] β”‚ 3[1] β”‚ plant[0] --> _sum.0[1]       β”‚ float64 β”‚
β”‚ 4 β”‚ 3[0] β”‚ 4[0] β”‚ _sum.0[0] --> _gain.0(10)[0] β”‚ float64 β”‚
β”‚ 5 β”‚ 4[0] β”‚ 1[0] β”‚ _gain.0(10)[0] --> plant[0]  β”‚ float64 β”‚
β””β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

The implicitly created blocks have names prefixed with an underscore.

bdedit: the graphical editing tool

block diagram

bdedit is a multi-platform PyQt5-based graphical tool to create, edit, render and execute block diagram models.

From the examples folder

% bdedit eg1.bd

will create a display like that shown above. Pushing the run button, top left (triangle in circle) will spawn bdrun as a subprocess which will:

  • parse the JSON file
  • instantiate all blocks and wires
  • compile and run the diagram

Screencast showing bdedit usage.

Article

I published this article on LinkedIn, which describes the thought process behind bdsim.

Limitations

There are lots! The biggest is that bdsim is based on a very standard variable-step integrator from the scipy library. For discontinuous inputs (step, square wave, triangle wave, piecewise constant) the transitions get missed. This also makes it inaccurate to simulate hybrid discrete-continuous time systems. We really need a better integrator, perhaps odedc from SciLab could be integrated.

More Repositories

1

robotics-toolbox-python

Robotics Toolbox for Python
Python
2,041
star
2

robotics-toolbox-matlab

Robotics Toolbox for MATLAB
MATLAB
1,259
star
3

spatialmath-python

Create, manipulate and convert representations of position and orientation in 2D or 3D using Python
Python
294
star
4

machinevision-toolbox-matlab

Machine Vision Toolbox for MATLAB
MATLAB
202
star
5

spatialmath-matlab

Create, manipulate and convert representations of position and orientation in 2D or 3D using Python
MATLAB
197
star
6

RVC3-python

Code examples for Robotics, Vision & Control 3rd edition in Python
Jupyter Notebook
191
star
7

machinevision-toolbox-python

Machine vision toolbox for Python
Jupyter Notebook
148
star
8

RVC3-MATLAB

New toolbox, data and examples for Robotics, Vision & Control: 3rd edition in MATLAB
MATLAB
82
star
9

toolbox-common-matlab

Common code for MATLAB toolboxes for Robotics, Machine Vision
MATLAB
57
star
10

rvc-notation

RVC notation
TeX
19
star
11

ansitable

Quick, easy and pretty display of tabular data or matrices, with optional ANSI color and borders
Python
17
star
12

pgraph-python

Simple graph classes
Python
15
star
13

simple-threads-coder

A simple POSIX threading library for MATLAB Coder
C
9
star
14

help2doc

Convert MATLAB source files to various documentation formats
Python
4
star
15

petercorke.github.io

Static web pages
3
star
16

pybib

Python class to parse/sort/filter bibtex files
Python
2
star
17

tkbibtex

Simple python/tk graphical browser/editor for BibTeX files
Shell
2
star
18

RVC3-test

For testing MATLAB Online access to GH based toolboxes and scripts
MATLAB
2
star
19

robotics-toolbox-julia

Julia port of robotics toolbox
1
star
20

arduIO

Simple and efficient Arduino I/O server and Python client
Python
1
star
21

plane-catcher

Log aircraft flying low and loud over Brisbane's Western suburbs
Python
1
star