Simulation-user API

This section describes the public API for users of bdsim. This is the API that is intended to be stable and supported across versions. It includes the classes and methods that are used to build and simulate block diagrams.

BlockDiagram class

A collection of blocks and wires that can be “executed” by run(). See the wiki’s Connecting blocks and Blocks, wires and plugs pages for how this fits together conceptually.

class bdsim.BlockDiagram(name=None, **kwargs)[source]

Bases: AnalysisMixin, GraphMixin, ReportMixin, BlockFactoryStubs, RTBStubs, MVTBStubs

Block diagram class. This object is the parent of all blocks and wires in the system.

Variables:
  • wirelist (list[Wire]) – all wires in the diagram

  • blocklist (list[Block]) – all blocks in the diagram

  • x (numpy.ndarray) – state vector

  • compiled (bool) – diagram has successfully compiled

  • blockcounter (collections.defaultdict) – unique counter for each block type

  • blockdict (dict) – index of all blocks by category

  • name (str or None) – name of this diagram, None until given one. A main diagram is named main when first compiled; a subsystem diagram’s name is the stem of its instances’ names, see BDSim.blockdiagram()

This object:

  • holds all the blocks and wires that comprise the system

  • manages continuous- and discrete-time state vector for the whole system, splitting it across blocks as required

  • evaluates the entire diagram as a function to compute \(\dot{x} = f(x, t)\)

compile(subsystem=False, doimport=True, evaluate=True, report=False, verbose=False)[source]

Compile the block diagram

Parameters:
  • subsystem (bool) – importing a subsystems, defaults to False

  • doimport (bool) – import subsystems, defaults to True

Raises:

RuntimeError – various block diagram errors

Returns:

Compile status

Return type:

bool

Performs a number of operations:

  • Check sanity of block parameters

  • Recursively clone and import subsystems

  • Check for loops without dynamics

  • Check for inputs driven by more than one wire

  • Check for unconnected inputs and outputs

  • Link all output ports to outgoing wires

  • Link all input ports to incoming wires

  • Evaluate all blocks in the network

connect(start, *ends, name=None)[source]

Connect blocks

Parameters:
  • start (Port) – The output port that the wire starts from.

  • ends (Port) – The input port(s) that the wire ends at. Can be one or more.

  • name (str | None) – The name of the wire, defaults to None

Return type:

None

Connect blocks together. The start block can be connected to one or more end blocks.

Blocks are added to the block diagram’s blocklist if they are not already part of it.

The wires are added to the diagram’s wirelist, but the connections are not actually made until compile time. The wirelist is a list of things that will be connected later.

dotfile(filename, shapes=None)

Write a GraphViz dot file representing the network.

Parameters:
  • file (str, file handle) – Name of file to write to, or file handle

  • shapes (Any) – block shapes

Return type:

None

Create a GraphViz format file for procesing by dot. The graph is:

  • directed graph, drawn left to right

  • source blocks are in the first column

  • sink and graphics blocks are in the last column

  • SUM and PROD blocks have the sign or operation of their input wires labeled.

The file can be processed using dot:

% dot -Tpng -o out.png dotfile.dot
Block diagram represented as a mathematical graph

Note

By default all blocks have the default shape, with source blocks shown as a rectangle (“record”), and sink/graphics blocks as a rounded rectangle (“Mrecord”). This can be overriden by provide a dictionary shapes that maps block class (sink, source, graphics, function, transfer) to the names of GraphViz shapes.

Seealso:

graph() showgraph()

functions(inputs=None, outputs=None, *, full=False)

The diagram as the functions \(f\) and \(g\) of a nonlinear system

Overloads:
Parameters:
  • inputs (list[Block | Plug | str] | None) – the source blocks, or the outputs of them, that are the input \(u\), see below. Defaults to every source block except TIME and the constants bdsim creates for numbers written in expressions, which are parameters, not inputs.

  • outputs (list[Block | Plug | str] | None) – the signals that are the output \(y\), see below. Defaults to the signal into every sink input.

  • full (bool) – return a SystemFunctions object, which also has the sizes of the vectors and the maps that say what they are made of, instead of just the two functions

Returns:

the pair (f, g), or a SystemFunctions object if full, which also unpacks as f, g

Raises:
\[\dot{x} = f(x, u, t), \qquad y = g(x, u, t)\]

The diagram must be compiled. The source blocks are replaced by the values of \(u\), TIME supplies \(t\), and \(y\) is read from the diagram. The sink blocks are not executed (nothing is plotted, printed or logged). \(x\) is the continuous state in the order the blocks were added to the diagram, as in bd.statenames.

Choosing the input and the output

Both are lists. An entry is a block, one of its ports (a plug, such as plant[0]), or the name of a block (such as "plant").

Entry of inputs

\(u\) contains

a source block, demand

all its outputs

a port of a source block, demand[0]

that output

Source blocks that are not selected keep producing their own values. TIME cannot be an input, it is the argument t. To add a signal into the middle of a diagram, which has no input there, insert a SUM block and a CONSTANT(0) block at that point: the constant is then an input.

Entry of outputs

\(y\) contains

any other block, plant

all its outputs

a port of a block, plant[0]

that output

a sink block, scope

the signals wired into all its inputs

a port of a sink block, scope[1]

the signal wired into that input

The output is a signal, named by the block and port that produce it. A sink has no outputs, so naming a sink means the signals it receives. This is also how the default is made, and a signal that is wired to several sinks is included once.

The elements of \(u\) and \(y\) are ordered by the order in which the blocks were added to the diagram, and then by port, whatever the order of the lists. A block’s array output is flattened, and uindex and yindex say where each block’s elements are.

For example:

f, g = bd.functions()
xdot = f(x, u, t)
y = g(x, u, t)

To check what x, u and y are made of, and how long they are, ask for the full object, as linearize does with full=True:

sysf = bd.functions(full=True)
sysf.xindex  # which states belong to which block
sysf.nu, sysf.ny  # the lengths of u and y
f, g = sysf  # the same two functions
xdot, y = sysf.fg(x, u, t)  # both, from one evaluation of the diagram

The object also has nx, the initial state x0, u_at(t) for the natural input at a time, and uindex and yindex for the inputs and outputs. f and g each evaluate the diagram, so fg is half the work when both are needed at the same point.

The state of the blocks is as the last run left it. After a run, for example, an integrator held at its limit is still held, so the model is that of the diagram at the end of the run. A diagram that has not been run has its blocks reset first. Do not call the functions during a simulation: they overwrite the values on the wires.

Seealso:

linearize() SystemFunctions State State_S

graph(format='dot', filename=None, shapes=None)

Render diagram text in DOT, Mermaid, GraphML, or ELK JSON format.

Parameters:
  • format (str) – graph output format: "dot", "mermaid", "mermaid_fenced", "graphml" or "elk"

  • filename (str | TextIOWrapper | None) – destination path or open text stream, defaults to None

  • shapes (Any) – optional DOT block shape mapping (DOT output only)

Returns:

rendered graph text

Return type:

str

If filename is provided the rendered text is also written to it.

"mermaid_fenced" is identical to "mermaid" but wraps the output in a \`\`\`mermaid fenced code block, ready to paste into Markdown or a Jupyter notebook cell.

Mermaid format can be rendered in Markdown files and on GitHub, and GraphML and ELK JSON can be imported into graph visualization tools such as yEd and Eclipse ELK respectively.

Node shapes by block kind (dot and mermaid only)

Block kind

DOT shape

Mermaid shape

source

record

rectangle [label]

stateful (continuous, sampled, or hasstate)

box3d

subroutine [[label]]

sum / prod

(default ellipse)

circle ((label))

graphics / display

Mrecord

asymmetric >label]

sink

Mrecord

rectangle [label]

function / other

(default ellipse)

rectangle [label]

In a Jupyter notebook, the graph can be rendered directly by exporting in mermaid_fenced format and using using IPython’s display function:

from IPython.display import Markdown, display

display(Markdown(bd.graph(format="mermaid_fenced"))) # Render dynamically via Jupyter's built-in Mermaid engine
Seealso:

dotfile()

linearize(x=None, u=None, t=0.0, *, inputs=None, outputs=None, h=None, scale=None, estimate_error=False, full=False)

Linearize the diagram about an operating point

Overloads:
Parameters:
  • x (ArrayLike | None) – state of the operating point, defaults to the initial state of the diagram. After a run use out.x[-1].

  • u (ArrayLike | None) – input of the operating point, defaults to the natural input of the sources at t

  • t (float) – time of the operating point

  • inputs (list[Block | Plug | str] | None) – the source blocks or ports that are the input, see functions()

  • outputs (list[Block | Plug | str] | None) – the blocks or ports whose signals are the output, see functions()

  • h (float | None) – step of the numerical derivative, defaults to a size chosen for each variable

  • scale (ArrayLike | None) – typical size of the variables, a number or an array with one element for each state and then each input, defaults to 1. Give it when a variable is far from 1 in size and zero at the point.

  • estimate_error (bool) – also differentiate with twice the step, to estimate the error and warn where a block is not smooth enough

  • full (bool) – return a Linearization, which also has the operating point and the names of the states, inputs and outputs, and prints as a labelled model, see __str__()

Returns:

(A, B, C, D), or the Linearization if full

Raises:

NotImplementedError – the diagram has sampled (discrete-time) blocks

The matrices of the local linear model are the Jacobians

\[A = \frac{\partial f}{\partial x},\quad B = \frac{\partial f}{\partial u},\quad C = \frac{\partial g}{\partial x},\quad D = \frac{\partial g}{\partial u}\]

of the functions \(f\) and \(g\) of functions(), estimated by central differences with a step \(h \approx \epsilon^{1/3} \max(|v|, s)\) for a variable \(v\) of typical size \(s\), where \(\epsilon\) is the machine precision.

A state reached part way through a simulation is not usually an equilibrium, so \(f \neq 0\) there and the model is \(\delta\dot{x} = A\,\delta x + B\,\delta u + f_0\). The result does not include \(f_0\), but full=True returns it with \(g_0\).

The result has the form of the matrices of a linear time-invariant system and can be used directly to make a LTI_SS block. For control system design, including poles, stability and optimal control, see the python-control package, https://github.com/python-control/python-control, which takes the same (A, B, C, D).

For example, to linearize at the end of a simulation:

out = sim.run(bd, T=5)
A, B, C, D = bd.linearize(out.x[-1])

To design state feedback from the result, take a gain matrix K from the A and B and feed the state back with a State block, F = -K * bd.STATE(). The state of that block is in the order of the states of this method, so K applies directly, and linearizing the closed loop gives \(A - BK\). The state of a clocked block is available from State_S.

If the operating point is at a corner of a non-smooth block (a limit, a dead band, a switch) the derivative is not defined there. The result is then the slope across the step; with estimate_error a warning says that the estimate is not reliable.

Seealso:

functions() LTI_SS State State_S

report_lists(**kwargs)

Print a tabular report about the block diagram.

Parameters:

kwargs (Any) – options passed to ansitable.table.ANSIMatrix.print()

Return type:

None

Print the important lists in pretty format.

  • block list, all blocks

  • wire list, all wires

  • clock list, all discrete time clocks

report_params(fixed=False, **kwargs)

Print a table of the parameters of all blocks and their current values.

Parameters:
Return type:

None

The first column is the name exactly as it is used by the --set option, block:param, and by set_param(). The columns are

  1. the name, block:param

  2. the current value, abbreviated if it is long

  3. its type, as the signature of the value

  4. when it can be set: anytime, setup (before the run starts), or never (only with fixed=True)

Blocks inside a subsystem are listed with the path of the subsystem, such as sub/gain.0:K. A subsystem block that declares parameters of its own, such as PID, is listed by its own name, pid.0:P, instead of the blocks inside it, which can still be set by their own names. The --param option prints this table when the diagram is compiled.

Seealso:

add_param() set_param()

report_schedule(**kwargs)

Display execution schedule in tabular form

Parameters:

kwargs (Any) – options passed to ansitable.table.ANSIMatrix.print()

Seealso:

schedule_dotfile()

Return type:

None

report_subsystems(**kwargs)

Print a table of the inputs and outputs of the subsystems.

Parameters:

kwargs (Any) – options passed to ansitable.table.ANSIMatrix.print()

Return type:

None

A subsystem block is not part of the compiled network, and its INPORT and OUTPORT blocks have been replaced by wires, so the signals that cross its boundary are listed here. The columns are

  1. the port, such as pid.0[1], which is what can be watched

  2. in or out

  3. the block and port that the signal comes from, the source, which for an output is a block inside the subsystem (looking through nested subsystems) and for an input is a block outside it

  4. the type of the signal, as the signature recorded when the diagram was compiled

Seealso:

SubsystemBlock.inports SubsystemBlock.outports

report_summary(sortby='name', depth=None, implicit=True, **kwargs)

Print a summary of block diagram.

Parameters:
  • sortby (str) – sort rows by specified block attribute: “name” [default] or “type”

  • depth (int | None) – only show blocks with subsystem depth less than or equal to this value, defaults to None (show all)

  • implicit (bool) – show implicit blocks, defaults to True

  • kwargs (Any) – options passed to ansitable.table.ANSIMatrix.print()

Raises:

ValueError – sortby is not “name” or “type”

Return type:

None

Print a table with 4 columns:

  1. Block name, sorted in alphabetical order

  2. The input port (if not a source block)

  3. The block driving this port (if not a source block)

  4. The type of value driving this port (if not a source block)

If the block is an event source, add a @ suffix.

Implicit blocks are those created for the user, such as the constants and gains made by writing 2 * x or x + 1, whose names start with _. They are listed after all the other blocks, sorted in the same way, or hidden if implicit is False.

schedule_dotfile(filename)

Write a GraphViz dot file representing the execution schedule

Parameters:

file (str) – Name of file to write to

Return type:

None

The file can be processed using neato or dot:

% dot -Tpng -o out.png dotfile.dot

Display execution plan as a dataflow graph.

Seealso:

report_schedule()

showgraph()

Display diagram as a graph in browser tab

Seealso:

dotfile() graph()

Return type:

None

property xindex: Index

Which elements of the continuous state vector belong to which block.

Returns:

an Index

This is the one definition of the layout of the state \(x\) of the diagram, the vector the solver advances: the states of the blocks that have continuous state, in the order the blocks were added. The state passed to functions(), returned by run() as out.x, and output by a State block are all in this order.

The names are those a block gave its states, with snames, and otherwise the block’s name, or name[k] for the k-th of several. bd.statenames names the same elements in the same order, in the form name:x_k, which is also what out.xnames holds.

Functions and linearization

functions() returns a compiled diagram as the non-linear functions \(f\) and \(g\), and linearize() estimates its local linear model \((A, B, C, D)\).

class bdsim.analysis.SystemFunctions(bd, inputs=None, outputs=None)[source]

Bases: object

Contains the non-linear system functions of a block diagram

\[\begin{split}\dot{x} &= f(x, u, t), \\ y &= g(x, u, t)\end{split}\]

along with the sizes and the maps that say what the vectors are made of.

Returned by functions() when it is called with full=True. It unpacks as the two functions, which are the pair that functions() returns by default:

sysf = bd.functions(full=True)
f, g = sysf
xdot = f(x, u, t)
y = g(x, u, t)

x, u and y are Numpy arrays and t is a float.

fg() computes both from one propagation through the diagram, which is half the work of calling f and then g.

Calling it evaluates the diagram, so it is not meant to be used during a simulation: the values on the wires and the diagram’s state map are overwritten.

Note

A hybrid system, which has blocks with discrete (clocked) state as well as continuous state, has no such pair of functions: its next discrete state is not a function of \((x, u, t)\) alone, since it depends on the state of the clocks and the discrete state itself. Such a diagram is not accepted, and NotImplementedError names the sampled blocks that are the reason. To analyse the continuous-time part of a hybrid diagram, build it with source blocks in place of the sampled blocks and make those sources the inputs of functions(), so that what the sampled blocks would have output becomes part of \(u\).

Seealso:

functions() Linearization

nu: int

number of inputs

ny: int

number of outputs

uindex: Index

which inputs are the outputs of which source block

yindex: Index

which outputs are the signals of which block

xindex: Index

which states belong to which block

nx: int

number of continuous states

x0: NDArray

initial continuous state of the diagram

u_at(t=0.0)[source]

The values of the inputs at time t, flattened.

Parameters:

t (float) – time

Return type:

NDArray

Returns:

what the selected source blocks output at time t

This is the natural input of the diagram at t, a good point to linearize about.

fg(x, u, t=0.0)[source]

Evaluate \(\dot{x} = f(x, u, t)\) and \(y = g(x, u, t)\) together.

Parameters:
Return type:

tuple[NDArray, NDArray]

Returns:

\((\dot{x}, y)\)

f(x, u, t=0.0)[source]

State derivative \(\dot{x} = f(x, u, t)\).

Return type:

NDArray

g(x, u, t=0.0)[source]

Output \(y = g(x, u, t)\).

Return type:

NDArray

class bdsim.analysis.Linearization(A, B, C, D, f0, g0, x, u, t, xindex, uindex, yindex, error=None)[source]

Bases: object

A local linear model of a block diagram, from linearize().

The model is

\[\begin{split}\begin{aligned} \frac{d}{dt}(\delta x) &= A\,\delta x + B\,\delta u + f_0 \\ y &= C\,\delta x + D\,\delta u + g_0 \end{aligned}\end{split}\]

where \(\delta x\) and \(\delta u\) are the deviations of the state and the input from the operating point, and \(f_0\) and \(g_0\) are the functions \(f\) and \(g\) at the operating point. The matrices are attributes, as are the operating point and the maps that say which signal each row and column is.

It unpacks as A, B, C, D:

lin = bd.linearize(outputs=[x, theta], full=True)
A, B, C, D = lin

print shows the model with each matrix labelled by the names of the signals that are its rows and columns, see __str__(). poles are the eigenvalues of A.

Seealso:

linearize() SystemFunctions

A: NDArray

\(\partial f / \partial x\), shape (nx, nx)

B: NDArray

\(\partial f / \partial u\), shape (nx, nu)

C: NDArray

\(\partial g / \partial x\), shape (ny, nx)

D: NDArray

\(\partial g / \partial u\), shape (ny, nu)

f0: NDArray

\(f(x, u, t)\) at the operating point, zero at an equilibrium

g0: NDArray

\(g(x, u, t)\) at the operating point

x: NDArray

state of the operating point

u: NDArray

input of the operating point

t: float

time of the operating point

xindex: Index

names the rows and columns of A and the columns of C

uindex: Index

names the columns of B and D

yindex: Index

names the rows of C and D

error: dict[str, NDArray] | None = None

estimated error of each of A, B, C, D, as a dict with those keys, or None if estimate_error was not requested

__iter__()[source]

Unpack as A, B, C, D.

Return type:

Iterator[NDArray]

ss(name=None)[source]

The model as a python-control state-space system.

Parameters:

name (str | None) – name of the system, defaults to one chosen by python-control

Return type:

Any

Returns:

a control.StateSpace with the matrices A, B, C, D of this model, and with the names of the states, inputs and outputs as its signal names, taken from xindex, uindex and yindex

Raises:

ImportError – python-control is not installed

python-control is the usual package for the design of control systems, and this is the way to use it on a diagram. For example, to design a linear quadratic regulator (control.lqr()) for a cart and pole and apply it:

import control

lin = bd.linearize(outputs=[x, theta], full=True)
sys = lin.ss()
K, S, E = control.lqr(sys, Q, R)
F = -K * bd.STATE()

The signal names carry through, so that systems made this way can be connected by name with control.interconnect(). python-control does not allow a . in a signal name, so it is replaced by _: the output of the implicit block _gain.0 is the signal _gain_0. xindex, uindex and yindex keep the names bdsim gave.

python-control is an optional dependency, imported when this method is called: pip install control, or install bdsim with the control extra. Version 0.10 or later is needed, for the signal names.

The system is linear and time invariant, which is the model \(\delta\dot{x} = A\,\delta x + B\,\delta u\). The offset \(f_0\) of an operating point that is not an equilibrium, the output \(g_0\), and the operating point itself are not part of it, and stay on this object. The values of the matrices are those of the numerical derivative, so an element that is zero may be of the order of 1e-10, which can matter for tests of rank such as control.ctrb().

Note

python-control cannot make a system that has no inputs and a single state or a single output, because it mistakes a matrix of shape (1, 0) for an empty one. Use poles for an autonomous system like that.

Seealso:

linearize() LTI_SS

property poles: NDArray

The poles of the model, the eigenvalues of A, sorted by real part.

Returns:

array of length nx, real if all the poles are real, otherwise complex

__str__()[source]

The model, with each matrix labelled by the signals that are its rows and columns.

This is what print shows. For a cart and pole with the force on the cart as the input and the cart position and pole angle as the outputs:

Linearization at t = 0

states  x (4): x_dot, x, theta_dot, theta
inputs  u (1): disturbance
outputs y (2): x, theta

A = df/dx  (4x4)
  rows and columns: x_dot, x, theta_dot, theta
[[-10.   ,   0.   ,   0.   ,  -0.981],
 [  1.   ,   0.   ,   0.   ,   0.   ],
 [ 20.   ,   0.   ,   0.   ,  21.582],
 [  0.   ,   0.   ,   1.   ,   0.   ]]

B = df/du  (4x1)
  rows: x_dot, x, theta_dot, theta
  columns: disturbance
[[ 1.],
 [ 0.],
 [-2.],
 [ 0.]]

C = dg/dx  (2x4)
  rows: x, theta
  columns: x_dot, x, theta_dot, theta
[[0., 1., 0., 0.],
 [0., 0., 0., 1.]]

D = dg/du  (2x1)
  rows: x, theta
  columns: disturbance
[[0.],
 [0.]]

poles: [-10.24, -4.262, 0, 4.498]

The names are those of the blocks that are the states, inputs and outputs, or the names a block gave its states. A value smaller than about 5e-5 is shown as 0, which hides the noise of the numerical derivative; the matrices themselves are not changed. The poles are listed as real numbers if they all are.

If the operating point is not an equilibrium, so that \(f_0\) is not zero, a last line says so, because the model then includes \(f_0\).

Return type:

str

class bdsim.analysis.Index(entries, names=None)[source]

Bases: object

Maps the elements of a flattened vector to the blocks they belong to.

The vectors \(x\), \(u\) and \(y\) of functions() are the values of several blocks, flattened and concatenated in the order the blocks were added to the diagram. An Index says which elements belong to which block.

index[block] or index["name"] is the slice of the vector holding that block’s elements, and index.labels[i] is the (block, k) of element i, where k is the position within the block. Blocks with no elements have no entry.

labels: list[tuple[Block, int]]

(block, k) for each element, in order

slices: dict[Block, slice]

the slice of the vector holding each block’s elements

classmethod of_states(blocks, width)[source]

The index of the state of some blocks, in the order given.

Parameters:
  • blocks (Iterable[Block]) – the blocks

  • width (Callable[[Block], int]) – the number of states of a block, nstates for continuous state and ndstates for discrete

Return type:

Index

Returns:

an index whose names are the ones a block gave its states, with snames=, and otherwise the block’s name, or name[k] for the k-th of several

name(i)[source]

Name of element i for display, for example "integrator.0[1]".

Return type:

str

property names: list[str]

The display name of every element.

BDSim class

The run-time environment for executing a block diagram. See the wiki’s Running and Runtime options pages for CLI/code options and how to invoke it.

class bdsim.BDSim(banner=True, packages=None, load=True, toolboxes=True, **kwargs)[source]

Bases: Runner

__init__(banner=True, packages=None, load=True, toolboxes=True, **kwargs)[source]
Parameters:
  • banner (bool) – display docstring banner, defaults to True

  • packages (str | None) – colon-separated list of folders to search for blocks

  • load (bool) – dynamically load blocks from libraries, defaults to True

  • sysargs (bool, optional) – process options from sys.argv, defaults to True

  • graphics (bool, optional) – enable graphics, defaults to True

  • animation (bool, optional) – enable animation, defaults to False

  • progress (bool, optional) – enable progress bar, defaults to True

  • debug (str, optional) – debug options, defaults to None

  • backend (str, optional) – matplotlib backend, defaults to ‘Qt5Agg’

  • tiles (str, optional) – figure tile layout on monitor, defaults to None

Raises:

ImportError – syntax error in block

Returns:

parent object for blockdiagram simulation

Return type:

BDSim

If sysargs is True, process command line arguments and passed options. Command line arguments have precedence.

Command line switch

Argument

Default

Behaviour

--graphics, +g

graphics

True

enable graphical display

--no-graphics, -g

graphics

True

disable graphical display

--animation, +a

animation

False

update graphics at each time step

--no-animation, -a

animation

False

don’t update graphics at each time step

--hold, +H

hold

True

hold graphics in done()

--no-hold, -H

hold

True

do not hold graphics in done()

--altscreen, +A

altscreen

True

display plots on second monitor

--no-altscreen, -A

altscreen

True

do not display plots on second monitor

--no-progress

progress

True

do not display simulation progress bar

--no-check

check

True

do not check block outputs and derivatives during the run (faster)

--backend BE, -b BE

backend

None

matplotlib backend

--tiles SPEC, -t SPEC

tiles

None

arrange figure tiles as RxC or square/wide/tall

--shape WxH

shape

None

window size (default: matplotlib default)

--movies [DIR], -m [DIR]

movies

None

record all graphics blocks to MP4 files in DIR (default: .), sampled at animation_rate

--no-movies

movies

None

disable automatic movie recording

--blocks

blocks

False

display block list at startup

--param

param

False

display the parameters of all blocks, as used by --set, and their values after compiling

--debug F, -d F

debug

''

debug flags: p/ropagate, s/tate, d/eriv, i/nteractive, g/raphics-diagnostics

--animation-rate R

animation_rate

20.0

target update rate for animation/debugger, per second of simulated time (Hz)

--max-frames N

max_frames

1000

most frames a live animation shows in one run, 0 for no limit

--simtime T[,dt], -S

simtime

None

simulation time as T or T,dt

--dt DT

dt

None

output sample interval (build solve_ivp t_eval)

--max-step DT

max_step

None

maximum solve_ivp integration step

--atol ATOL

atol

None

absolute tolerance for solve_ivp

--rtol RTOL

rtol

None

relative tolerance for solve_ivp

--method NAME

method

None

solve_ivp method (RK45, DOP853, Radau, BDF, LSODA)

--verbose, -v

verbose

False

be verbose

--quiet, -q

quiet

False

suppress reports and progress bar

-p [FILE], --pickle [FILE]

outfile

None

output pickled results (default: bd.out)

-o [FILE], --out [FILE]

outfile

None

(deprecated, use -p/–pickle)

-j [FILE], --json [FILE]

jsonfile

None

output JSON results (default: bd.json)

--npz [FILE]

npzfile

None

output results as a NumPy .npz archive (default: bd.npz)

--set P, -s P

setparam

[]

override block parameter: block:param=value

--global G

setglob

[]

override global parameter: var=value

Note

animation and graphics options are coupled. If graphics=False, all graphics is suppressed. If graphics=True then graphics are shown and the behaviour depends on animation. animation=False shows graphs at the end of the simulation, while animation=True will animate the graphs during simulation.

Seealso:

set_globals()

property block_library: dict[str, dict[str, Any]]

Read-only view of the loaded block registry, excluding deprecated blocks.

Returns a dict keyed by upper-case block name (e.g. "GAIN"). Each value is a metadata dict with keys: path, classname, url, class, module, package, params, inputs, outputs, nin, nout, blockclass.

Deprecated blocks (decorated with deprecated_block) are excluded so they don’t appear in editor menus. They remain in the internal registry and are still accessible as factory methods on a BlockDiagram.

blockdiagram(name=None)[source]

Instantiate a new block diagram object.

Parameters:

name (str | None) – diagram name, defaults to None. See below for how the name is used.

Returns:

parent object for blockdiagram

Return type:

BlockDiagram

This object describes the connectivity of a set of blocks and wires.

A diagram is used in one of two ways, and name means something different in each.

Main diagram. The top-level diagram that is compiled and run. It is not a block, so its name cannot clash with a block name. The name is only a label that appears in messages and reports. If none is given the diagram is named main when it is first compiled:

bd = sim.blockdiagram()  # bd.name is None until compile() gives it "main"
bd = sim.blockdiagram(name="plant")  # shown as 'plant'

Subsystem. A diagram, containing INPORT and OUTPORT blocks, that is instantiated inside another diagram by the SUBSYSTEM block. Each instance is a block, so it needs a name that is unique within the parent diagram. The diagram’s name is the stem of the default instance name, in the same way that the block type is the stem of gain.0, gain.1 and so on:

ss = sim.blockdiagram(name="thing")
...
a = bd.SUBSYSTEM(ss)  # named "thing.0"
b = bd.SUBSYSTEM(ss)  # named "thing.1"

If the subsystem diagram has no name, the stem is subsystem, giving subsystem.0, subsystem.1 and so on. A subsystem loaded from a .bd file uses the file name without its extension, and one imported from a module uses the variable name of the diagram. Passing name= to SUBSYSTEM overrides the default, but must be unique in the parent diagram. The instance name becomes the prefix of the names of the blocks cloned from the subsystem into the parent when it is compiled, for example thing.0/gain.0.

It is an instantiation of the BlockDiagram class with a factory method for every dynamically loaded block which returns an instance of the block. These factory methods have names which are all upper case, for example, the method .GAIN invokes the constructor for the Gain class.

If the block library was not loaded, BDSim(load=False), the diagram has no factory methods and calling one, for example bd.GAIN(2), raises NotImplementedError. Import the block classes directly and pass the diagram as bd instead:

from bdsim.blocks import Gain

gain = Gain(2, bd=bd)
Seealso:

BlockDiagram()

blocks()[source]

List all loaded blocks.

Example:

73  blocks loaded
bdsim.blocks.functions..................: SUM PROD GAIN CLIP FUNCTION INTERPOLATE
bdsim.blocks.sources....................: CONSTANT TIME WAVEFORM PIECEWISE STEP RAMP
bdsim.blocks.sinks......................: PRINT STOP NULL WATCH
bdsim.blocks.continuous.................: INTEGRATOR POSEINTEGRATOR LTI_SS LTI_SISO
bdsim.blocks.sampled....................: ZOH INTEGRATOR_S POSEINTEGRATOR_S
bdsim.blocks.linalg.....................: INVERSE TRANSPOSE NORM FLATTEN SLICE2 SLICE1 DET COND
bdsim.blocks.displays...................: SCOPE SCOPEXY SCOPEXY1
bdsim.blocks.connections................: ITEM DICT MUX DEMUX INDEX SUBSYSTEM INPORT OUTPORT
roboticstoolbox.blocks.arm..............: FKine IKine Jacobian Tr2Delta Delta2Tr Point2Tr TR2T FDyn IDyn Gravload
........................................: Inertia Inertia_X FDyn_X ArmPlot Traj JTraj LSPB CTraj CirclePath
roboticstoolbox.blocks.mobile...........: Bicycle Unicycle DiffSteer VehiclePlot
roboticstoolbox.blocks.uav..............: MultiRotor MultiRotorMixer MultiRotorPlot
machinevisiontoolbox.blocks.camera......: Camera Visjac_p EstPose_p ImagePlane
Return type:

None

done(bd, block=False)[source]

Enter the matplotlib event loop and clean up after simulation.

Called after run() to allow interactive use of displayed SCOPE figures. If the hold option is set (the default), this blocks until the user closes all figure windows; otherwise it returns immediately after flushing pending GUI events.

Parameters:
  • bd (Any) – block diagram whose blocks are to be finalised

  • block (bool) – if True, block until all figures are closed; if False, flush events and return immediately. Overridden by sim.options.hold.

Return type:

None

Note

This method can be called after run() has returned (i.e. outside the simulation context) — for example when the script calls sim.run(..., block=False) and then does post-processing before handing control back to the user. In that case the hold option is read from sim.options directly.

report(bd, type='summary', **kwargs)[source]

Print block diagram report

Parameters:
  • bd (Any) – the block diagram to be reported

  • type (str) – report type, one of: “summary” (default), “lists”, “schedule”, “params”, “subsystems”

  • style (str) – table style, one of: ansi (default), markdown, latex

Return type:

None

Single method wrapper for various block diagram reports. Obeys the -q option to suppress all reports at runtime.

Seealso:

report_summary() report_lists() report_schedule() report_params() report_subsystems()

run(bd, T=5, dt=None, max_step=None, solver='RK45', solver_args=None, debug='', block=None, check=None, checkfinite=None, minstepsize=1e-12, watch=None, threaded=False, **options)[source]

Run a compiled block diagram.

Parameters:
  • T (float) – simulation horizon, defaults to 5

  • dt (float | None) – output sample interval; used to build a t_eval grid for solve_ivp so results are recorded at uniform steps

  • max_step (float | None) – maximum integration step passed to solve_ivp

  • solver (str) – solve_ivp method name, defaults to RK45

  • solver_args (dict[str, Any] | None) – extra keyword arguments for scipy.integrate.solve_ivp

  • debug (str) – debug flags string (see below), defaults to ''

  • block (bool | None) – matplotlib block-at-end behaviour, default False

  • check (bool | None) – check block outputs and derivatives as they are computed (output form, NaN or Inf, change of signature, derivative shape), defaults to the check option which is True. --no-check turns it off, which is faster.

  • checkfinite (bool | None) – deprecated, use check

  • minstepsize (float) – minimum step length guard, default 1e-12

  • watch (Any) – list of signals to log (see below)

  • threaded (bool) – run in a worker thread (disables graphics), default False

  • options (Unpack[RunOptions]) – any of the options of RunOptions, for this run only, for example animation=True or progress=False

Returns:

simulation results container

Return type:

BDStruct

Raises:
  • TypeError – for an option that is unknown, or that can only be set when BDSim is constructed, such as blocks or verbose

  • RuntimeError – for a backend that matplotlib cannot switch to

The system is simulated from time 0 to T.

Options. The keyword arguments after threaded are options, the same ones that BDSim takes and that the command line sets. Each overrides the value given to BDSim for this run only. An option given on the command line always wins, including dt, max_step, check and block, and a message says that the value from the code was ignored. The options that cannot differ from run to run, such as blocks or verbose, raise TypeError.

Warning

setparam changes the parameters of the blocks, and they stay changed after the run. It is not a setting for this run only, unlike the other options: a second run without setparam uses the values the first one set. setparam={"gain:K": 3} is the same as calling set_param("K", 3) on the block named gain before the run, but is done after the command line has been read, and so can be overridden by -s gain:K=4. The keys are "block:param", with the block’s name or its id as for -s, and the values are Python objects, not text. Each change is reported, old value to new, unless quiet. This is new and may change.

Changed in version next: The options of RunOptions can be given to run as keyword arguments, and to submit, which passes them on. An option given on the command line now also wins over dt, max_step, check and block given to run, which used to override it, and a message says that the value from the code was ignored.

The integration backend is always scipy.integrate.solve_ivp. The solver argument selects the method (e.g. RK45, DOP853, Radau, BDF, LSODA). Finer control — tolerances, first step, etc. — can be passed via solver_args.

The output dt controls the time resolution of logged output. When given, solve_ivp is called with a matching t_eval grid so that out.t contains uniformly-spaced points. If omitted, solve_ivp chooses its own internal steps and all accepted points are recorded.

Results are returned in a BDStruct with attributes:

  • t — time vector: ndarray, shape=(M,)

  • x — continuous state matrix: ndarray, shape=(M,N)

  • xnames — list of state names corresponding to columns of x, e.g. "plant.x0" (set via the block’s snames argument)

  • clockN — BDStruct for each clock (clock0, clock1, …) with sub-attributes t and x holding the discrete time history; a legacy alias using the clock’s name is also added when possible

  • yN — logged signal for the N-th entry in watch

  • ynames — list of names of the watched ports, same order as watch

  • .stats — BDStruct with integration statistics: integration_time_points, run_interval_calls, ydot_calls, integrator_wall_time, animation_frames, events_detected_total, events_detected_by_source

The watch argument is a list of one or more signals whose value during simulation will be recorded. Each element can be:

  • a Block reference, interpreted as output port 0

  • a Plug reference (block with port index)

  • a string of the form "blockname[i]" — port i of the named block

The debug string contains single-character flags:

  • 'p' — trace network value propagation

  • 's' — trace state vector

  • 'd' — trace state derivative

  • 'i' — interactive step-by-step debugger

  • 'g' — graphics/window diagnostics (figure creation, tiling, notebook display handles)

Note

Simulation stops if the step size falls below minstepsize, which typically indicates the solver is struggling with a very stiff or discontinuous system.

set_globals(globs)[source]

Set globals as specified by command line

Parameters:

globs (dict[str, Any]) – global variables

Return type:

None

The command line option --global var=value can be used to request the change of global variables. However, actually changing them requires explicit code support in the user’s program after the BDSim constructor.

Example:

sim.set_globals(globals())

Messages are displayed by defaulting, indicating which variables are changed, and their old and new values.

The keyword options that run() takes, for that run only:

class bdsim.RunOptions[source]

Options that run() accepts as keyword arguments.

These are the options that can differ from one run to the next. Each one overrides the value given to BDSim (or the default) for that run only, unless it was set on the command line, which always wins.

dt, max_step, check and debug are also options, but are named parameters of run(), and block is the same setting as hold.

altscreen: NotRequired[bool]
animation: NotRequired[bool]
animation_rate: NotRequired[float]
atol: NotRequired[float | None]
backend: NotRequired[str | None]
graphics: NotRequired[bool]
hold: NotRequired[bool]
jsonfile: NotRequired[str | None]
max_frames: NotRequired[int]
movies: NotRequired[bool | str | PathLike[str] | None]
npzfile: NotRequired[str | None]
outfile: NotRequired[str | None]
progress: NotRequired[bool]
quiet: NotRequired[bool]
rtol: NotRequired[float | None]
setparam: NotRequired[dict[str, Any]]
shape: NotRequired[str | None]
tiles: NotRequired[str | None]

BDStruct class

A struct-like container for storing simulation data, returned by run(). See the wiki’s Simulation results page for the full layout — continuous vs. discrete/clocked state, watched signals, and the deprecated per-signal accessors — rather than duplicating that explanation here.

class bdsim.BDStruct(name='BDStruct2', **kwargs)[source]

Bases: UserDict

A simple data container object that allows items to be added by attribute or by index.

For example:

>>> d = BDStruct('thing')
>>> d.foo = 1
>>> d.foo
1
>>> d["foo"]
]
>>> d["bar"] = 2
>>> d.bar
>>> d
bar   = 2 (int)
foo   = 1 (int)
__init__(name='BDStruct2', **kwargs)[source]
__str__()[source]

Display struct as a string

Returns:

struct in indented string format

Return type:

str

The struct is rendered with one line per element, and substructures are indented. Keys whose names start with ‘.’ are hidden (internal metadata fields).

add(name, value)[source]
Return type:

None

dump(outfile)[source]

Pickle the struct to a file.

Parameters:

outfile (str) – path to the output file

Return type:

None

dump_json(outfile)[source]

Serialise the struct to a JSON file.

NumPy arrays are converted to nested lists and NumPy scalars are unwrapped to their Python equivalents. Nested BDStruct instances are recursively converted to plain dicts.

Parameters:

outfile (str) – path to the output file

Return type:

None

dump_npz(outfile)[source]

Write the struct to a NumPy .npz archive.

Parameters:

outfile (str) – path to the output file, used exactly as given

Return type:

None

Every entry is stored as one array, so the archive is compact, keeps full float64 precision, and can be read without pickle:

data = np.load("bd.npz", allow_pickle=False)
data["t"], data["x"], data["xnames"]

Nested structs (for example a clock’s results) become keys joined by /, such as clock0/X, and hidden fields keep their leading dot, such as .stats/ydot_calls. A list that makes a rectangular array is stored as one array, a ragged list element by element (.ywatch/0, .ywatch/1). None and other objects that are not data are left out.

Developer API

This section describes the internal API for developers of bdsim. This includes classes and methods that are used internally by the library, and may not be stable or supported across versions. It is intended for developers who want to understand or modify the internals of bdsim.

BDSim, full listing

Full member listing for BDSim/BDStruct — see their descriptions and wiki links under Simulation-user API above; this section differs only in showing every member, not the curated public subset.

class bdsim.BDSim(banner=True, packages=None, load=True, toolboxes=True, **kwargs)[source]

Bases: Runner

DEBUG(debug, fmt, *args)[source]
Return type:

None

__init__(banner=True, packages=None, load=True, toolboxes=True, **kwargs)[source]
Parameters:
  • banner (bool) – display docstring banner, defaults to True

  • packages (str | None) – colon-separated list of folders to search for blocks

  • load (bool) – dynamically load blocks from libraries, defaults to True

  • sysargs (bool, optional) – process options from sys.argv, defaults to True

  • graphics (bool, optional) – enable graphics, defaults to True

  • animation (bool, optional) – enable animation, defaults to False

  • progress (bool, optional) – enable progress bar, defaults to True

  • debug (str, optional) – debug options, defaults to None

  • backend (str, optional) – matplotlib backend, defaults to ‘Qt5Agg’

  • tiles (str, optional) – figure tile layout on monitor, defaults to None

Raises:

ImportError – syntax error in block

Returns:

parent object for blockdiagram simulation

Return type:

BDSim

If sysargs is True, process command line arguments and passed options. Command line arguments have precedence.

Command line switch

Argument

Default

Behaviour

--graphics, +g

graphics

True

enable graphical display

--no-graphics, -g

graphics

True

disable graphical display

--animation, +a

animation

False

update graphics at each time step

--no-animation, -a

animation

False

don’t update graphics at each time step

--hold, +H

hold

True

hold graphics in done()

--no-hold, -H

hold

True

do not hold graphics in done()

--altscreen, +A

altscreen

True

display plots on second monitor

--no-altscreen, -A

altscreen

True

do not display plots on second monitor

--no-progress

progress

True

do not display simulation progress bar

--no-check

check

True

do not check block outputs and derivatives during the run (faster)

--backend BE, -b BE

backend

None

matplotlib backend

--tiles SPEC, -t SPEC

tiles

None

arrange figure tiles as RxC or square/wide/tall

--shape WxH

shape

None

window size (default: matplotlib default)

--movies [DIR], -m [DIR]

movies

None

record all graphics blocks to MP4 files in DIR (default: .), sampled at animation_rate

--no-movies

movies

None

disable automatic movie recording

--blocks

blocks

False

display block list at startup

--param

param

False

display the parameters of all blocks, as used by --set, and their values after compiling

--debug F, -d F

debug

''

debug flags: p/ropagate, s/tate, d/eriv, i/nteractive, g/raphics-diagnostics

--animation-rate R

animation_rate

20.0

target update rate for animation/debugger, per second of simulated time (Hz)

--max-frames N

max_frames

1000

most frames a live animation shows in one run, 0 for no limit

--simtime T[,dt], -S

simtime

None

simulation time as T or T,dt

--dt DT

dt

None

output sample interval (build solve_ivp t_eval)

--max-step DT

max_step

None

maximum solve_ivp integration step

--atol ATOL

atol

None

absolute tolerance for solve_ivp

--rtol RTOL

rtol

None

relative tolerance for solve_ivp

--method NAME

method

None

solve_ivp method (RK45, DOP853, Radau, BDF, LSODA)

--verbose, -v

verbose

False

be verbose

--quiet, -q

quiet

False

suppress reports and progress bar

-p [FILE], --pickle [FILE]

outfile

None

output pickled results (default: bd.out)

-o [FILE], --out [FILE]

outfile

None

(deprecated, use -p/–pickle)

-j [FILE], --json [FILE]

jsonfile

None

output JSON results (default: bd.json)

--npz [FILE]

npzfile

None

output results as a NumPy .npz archive (default: bd.npz)

--set P, -s P

setparam

[]

override block parameter: block:param=value

--global G

setglob

[]

override global parameter: var=value

Note

animation and graphics options are coupled. If graphics=False, all graphics is suppressed. If graphics=True then graphics are shown and the behaviour depends on animation. animation=False shows graphs at the end of the simulation, while animation=True will animate the graphs during simulation.

Seealso:

set_globals()

property block_library: dict[str, dict[str, Any]]

Read-only view of the loaded block registry, excluding deprecated blocks.

Returns a dict keyed by upper-case block name (e.g. "GAIN"). Each value is a metadata dict with keys: path, classname, url, class, module, package, params, inputs, outputs, nin, nout, blockclass.

Deprecated blocks (decorated with deprecated_block) are excluded so they don’t appear in editor menus. They remain in the internal registry and are still accessible as factory methods on a BlockDiagram.

blockdiagram(name=None)[source]

Instantiate a new block diagram object.

Parameters:

name (str | None) – diagram name, defaults to None. See below for how the name is used.

Returns:

parent object for blockdiagram

Return type:

BlockDiagram

This object describes the connectivity of a set of blocks and wires.

A diagram is used in one of two ways, and name means something different in each.

Main diagram. The top-level diagram that is compiled and run. It is not a block, so its name cannot clash with a block name. The name is only a label that appears in messages and reports. If none is given the diagram is named main when it is first compiled:

bd = sim.blockdiagram()  # bd.name is None until compile() gives it "main"
bd = sim.blockdiagram(name="plant")  # shown as 'plant'

Subsystem. A diagram, containing INPORT and OUTPORT blocks, that is instantiated inside another diagram by the SUBSYSTEM block. Each instance is a block, so it needs a name that is unique within the parent diagram. The diagram’s name is the stem of the default instance name, in the same way that the block type is the stem of gain.0, gain.1 and so on:

ss = sim.blockdiagram(name="thing")
...
a = bd.SUBSYSTEM(ss)  # named "thing.0"
b = bd.SUBSYSTEM(ss)  # named "thing.1"

If the subsystem diagram has no name, the stem is subsystem, giving subsystem.0, subsystem.1 and so on. A subsystem loaded from a .bd file uses the file name without its extension, and one imported from a module uses the variable name of the diagram. Passing name= to SUBSYSTEM overrides the default, but must be unique in the parent diagram. The instance name becomes the prefix of the names of the blocks cloned from the subsystem into the parent when it is compiled, for example thing.0/gain.0.

It is an instantiation of the BlockDiagram class with a factory method for every dynamically loaded block which returns an instance of the block. These factory methods have names which are all upper case, for example, the method .GAIN invokes the constructor for the Gain class.

If the block library was not loaded, BDSim(load=False), the diagram has no factory methods and calling one, for example bd.GAIN(2), raises NotImplementedError. Import the block classes directly and pass the diagram as bd instead:

from bdsim.blocks import Gain

gain = Gain(2, bd=bd)
Seealso:

BlockDiagram()

blockinfo(block=None)[source]

Return info about all blocks.

Deprecated since version Use: block_library instead. sim.blockinfo() is equivalent to sim.block_library; sim.blockinfo(name) is equivalent to sim.block_library[name].

Return type:

Any

blocks()[source]

List all loaded blocks.

Example:

73  blocks loaded
bdsim.blocks.functions..................: SUM PROD GAIN CLIP FUNCTION INTERPOLATE
bdsim.blocks.sources....................: CONSTANT TIME WAVEFORM PIECEWISE STEP RAMP
bdsim.blocks.sinks......................: PRINT STOP NULL WATCH
bdsim.blocks.continuous.................: INTEGRATOR POSEINTEGRATOR LTI_SS LTI_SISO
bdsim.blocks.sampled....................: ZOH INTEGRATOR_S POSEINTEGRATOR_S
bdsim.blocks.linalg.....................: INVERSE TRANSPOSE NORM FLATTEN SLICE2 SLICE1 DET COND
bdsim.blocks.displays...................: SCOPE SCOPEXY SCOPEXY1
bdsim.blocks.connections................: ITEM DICT MUX DEMUX INDEX SUBSYSTEM INPORT OUTPORT
roboticstoolbox.blocks.arm..............: FKine IKine Jacobian Tr2Delta Delta2Tr Point2Tr TR2T FDyn IDyn Gravload
........................................: Inertia Inertia_X FDyn_X ArmPlot Traj JTraj LSPB CTraj CirclePath
roboticstoolbox.blocks.mobile...........: Bicycle Unicycle DiffSteer VehiclePlot
roboticstoolbox.blocks.uav..............: MultiRotor MultiRotorMixer MultiRotorPlot
machinevisiontoolbox.blocks.camera......: Camera Visjac_p EstPose_p ImagePlane
Return type:

None

closefigs()[source]
Return type:

None

done(bd, block=False)[source]

Enter the matplotlib event loop and clean up after simulation.

Called after run() to allow interactive use of displayed SCOPE figures. If the hold option is set (the default), this blocks until the user closes all figure windows; otherwise it returns immediately after flushing pending GUI events.

Parameters:
  • bd (Any) – block diagram whose blocks are to be finalised

  • block (bool) – if True, block until all figures are closed; if False, flush events and return immediately. Overridden by sim.options.hold.

Return type:

None

Note

This method can be called after run() has returned (i.e. outside the simulation context) — for example when the script calls sim.run(..., block=False) and then does post-processing before handing control back to the user. In that case the hold option is read from sim.options directly.

fatal(message, retval=1)[source]

Fatal simulation error

Parameters:
  • message (str) – Error message

  • retval (int) – system return value (*nix only) defaults to 1

Return type:

NoReturn

Display the error message then terminate the process. For operating systems that support it, return an integer code.

load_blocks(verbose=True, toolboxes=True)[source]

Dynamically load all block definitions.

Raises:

ImportError – module could not be imported

Returns:

dictionary of block metadata

Return type:

dict[str, dict[str, Any]]

Reads blocks from .py files found in bdsim/bdsim/blocks, folders given by colon separated list in envariable BDSIMPATH, and the command line option packages.

The result is a dict indexed by the upper-case block name with elements: - path to the folder holding the Python file defining the block - classname - blockname, upper case version of classname - url of online documentation for the block - package containing the block - doc is the docstring from the class constructor

report(bd, type='summary', **kwargs)[source]

Print block diagram report

Parameters:
  • bd (Any) – the block diagram to be reported

  • type (str) – report type, one of: “summary” (default), “lists”, “schedule”, “params”, “subsystems”

  • style (str) – table style, one of: ansi (default), markdown, latex

Return type:

None

Single method wrapper for various block diagram reports. Obeys the -q option to suppress all reports at runtime.

Seealso:

report_summary() report_lists() report_schedule() report_params() report_subsystems()

run(bd, T=5, dt=None, max_step=None, solver='RK45', solver_args=None, debug='', block=None, check=None, checkfinite=None, minstepsize=1e-12, watch=None, threaded=False, **options)[source]

Run a compiled block diagram.

Parameters:
  • T (float) – simulation horizon, defaults to 5

  • dt (float | None) – output sample interval; used to build a t_eval grid for solve_ivp so results are recorded at uniform steps

  • max_step (float | None) – maximum integration step passed to solve_ivp

  • solver (str) – solve_ivp method name, defaults to RK45

  • solver_args (dict[str, Any] | None) – extra keyword arguments for scipy.integrate.solve_ivp

  • debug (str) – debug flags string (see below), defaults to ''

  • block (bool | None) – matplotlib block-at-end behaviour, default False

  • check (bool | None) – check block outputs and derivatives as they are computed (output form, NaN or Inf, change of signature, derivative shape), defaults to the check option which is True. --no-check turns it off, which is faster.

  • checkfinite (bool | None) – deprecated, use check

  • minstepsize (float) – minimum step length guard, default 1e-12

  • watch (Any) – list of signals to log (see below)

  • threaded (bool) – run in a worker thread (disables graphics), default False

  • options (Unpack[RunOptions]) – any of the options of RunOptions, for this run only, for example animation=True or progress=False

Returns:

simulation results container

Return type:

BDStruct

Raises:
  • TypeError – for an option that is unknown, or that can only be set when BDSim is constructed, such as blocks or verbose

  • RuntimeError – for a backend that matplotlib cannot switch to

The system is simulated from time 0 to T.

Options. The keyword arguments after threaded are options, the same ones that BDSim takes and that the command line sets. Each overrides the value given to BDSim for this run only. An option given on the command line always wins, including dt, max_step, check and block, and a message says that the value from the code was ignored. The options that cannot differ from run to run, such as blocks or verbose, raise TypeError.

Warning

setparam changes the parameters of the blocks, and they stay changed after the run. It is not a setting for this run only, unlike the other options: a second run without setparam uses the values the first one set. setparam={"gain:K": 3} is the same as calling set_param("K", 3) on the block named gain before the run, but is done after the command line has been read, and so can be overridden by -s gain:K=4. The keys are "block:param", with the block’s name or its id as for -s, and the values are Python objects, not text. Each change is reported, old value to new, unless quiet. This is new and may change.

Changed in version next: The options of RunOptions can be given to run as keyword arguments, and to submit, which passes them on. An option given on the command line now also wins over dt, max_step, check and block given to run, which used to override it, and a message says that the value from the code was ignored.

The integration backend is always scipy.integrate.solve_ivp. The solver argument selects the method (e.g. RK45, DOP853, Radau, BDF, LSODA). Finer control — tolerances, first step, etc. — can be passed via solver_args.

The output dt controls the time resolution of logged output. When given, solve_ivp is called with a matching t_eval grid so that out.t contains uniformly-spaced points. If omitted, solve_ivp chooses its own internal steps and all accepted points are recorded.

Results are returned in a BDStruct with attributes:

  • t — time vector: ndarray, shape=(M,)

  • x — continuous state matrix: ndarray, shape=(M,N)

  • xnames — list of state names corresponding to columns of x, e.g. "plant.x0" (set via the block’s snames argument)

  • clockN — BDStruct for each clock (clock0, clock1, …) with sub-attributes t and x holding the discrete time history; a legacy alias using the clock’s name is also added when possible

  • yN — logged signal for the N-th entry in watch

  • ynames — list of names of the watched ports, same order as watch

  • .stats — BDStruct with integration statistics: integration_time_points, run_interval_calls, ydot_calls, integrator_wall_time, animation_frames, events_detected_total, events_detected_by_source

The watch argument is a list of one or more signals whose value during simulation will be recorded. Each element can be:

  • a Block reference, interpreted as output port 0

  • a Plug reference (block with port index)

  • a string of the form "blockname[i]" — port i of the named block

The debug string contains single-character flags:

  • 'p' — trace network value propagation

  • 's' — trace state vector

  • 'd' — trace state derivative

  • 'i' — interactive step-by-step debugger

  • 'g' — graphics/window diagnostics (figure creation, tiling, notebook display handles)

Note

Simulation stops if the step size falls below minstepsize, which typically indicates the solver is struggling with a very stiff or discontinuous system.

savefig(block, filename=None, format='pdf', **kwargs)[source]

Save the figure from a single graphics block to a file.

Parameters:
  • block (Any) – graphics block whose figure is to be saved

  • filename (str | None) – output filename without extension; defaults to the block’s name

  • format (str) – image format passed to matplotlib.Figure.savefig, defaults to 'pdf'

  • kwargs (Any) – additional keyword arguments forwarded to the block’s savefig method

Return type:

None

savefigs(bd, format='pdf', **kwargs)[source]

Save figures from all graphics blocks in a block diagram.

Iterates over every block in bd and calls savefig on each GraphicsBlock, using the block’s name as the filename stem.

Parameters:
  • bd (Any) – compiled block diagram

  • format (str) – image format passed to matplotlib.Figure.savefig, defaults to 'pdf'

  • kwargs (Any) – additional keyword arguments forwarded to each block’s savefig method

Return type:

None

set_globals(globs)[source]

Set globals as specified by command line

Parameters:

globs (dict[str, Any]) – global variables

Return type:

None

The command line option --global var=value can be used to request the change of global variables. However, actually changing them requires explicit code support in the user’s program after the BDSim constructor.

Example:

sim.set_globals(globals())

Messages are displayed by defaulting, indicating which variables are changed, and their old and new values.

set_options(**options)[source]
Return type:

None

showgraph(bd, **kwargs)[source]

Display the block diagram as a graph in the system browser.

Renders the block diagram to a Graphviz DOT file, converts it to PDF using dot, and opens the result in the default browser. Requires Graphviz to be installed and dot to be on PATH.

Parameters:
Return type:

None

submit(bd, **kwargs)[source]
Return type:

SimulationJob

update_parameters(bd, values=None)[source]

Set value of parameters according to arguments to the run and the command line

Parameters:
  • bd (Any) – the compiled block diagram

  • values (dict[str, Any] | None) – parameter values from code, {"block:param": value}, the setparam argument of run()

Return type:

None

The values from code are set first, then those from the command line, so the command line has the last word. A value from code is used as it is, the text of a command line value is read according to the kind of the current value. The parameters are changed in the blocks and stay changed after the run.

Command line arguments of the form:

-s block:param=value --set block:param=value

are stored as list items in options.setparam

block can be either:

  • the block’s name as a string, either user assigned or bdsim assigned

  • the block id as displayed by the report method

param is the name of the parameter used in the constructor. It must be a registered parameter that can be set before the run starts, see add_param(), and the new value must be of the same kind as the current one, see set_param(). report_params() lists the parameters and their current values.

value is the new value of the variable: an integer, a float, a matrix written 1 2; 3 4, or a NumPy dtype literal such as float32([1, 2]) or uint16(5), see bdsim.literals

class bdsim.BDStruct(name='BDStruct2', **kwargs)[source]

Bases: UserDict

A simple data container object that allows items to be added by attribute or by index.

For example:

>>> d = BDStruct('thing')
>>> d.foo = 1
>>> d.foo
1
>>> d["foo"]
]
>>> d["bar"] = 2
>>> d.bar
>>> d
bar   = 2 (int)
foo   = 1 (int)
__init__(name='BDStruct2', **kwargs)[source]
add(name, value)[source]
Return type:

None

dump(outfile)[source]

Pickle the struct to a file.

Parameters:

outfile (str) – path to the output file

Return type:

None

dump_json(outfile)[source]

Serialise the struct to a JSON file.

NumPy arrays are converted to nested lists and NumPy scalars are unwrapped to their Python equivalents. Nested BDStruct instances are recursively converted to plain dicts.

Parameters:

outfile (str) – path to the output file

Return type:

None

dump_npz(outfile)[source]

Write the struct to a NumPy .npz archive.

Parameters:

outfile (str) – path to the output file, used exactly as given

Return type:

None

Every entry is stored as one array, so the archive is compact, keeps full float64 precision, and can be read without pickle:

data = np.load("bd.npz", allow_pickle=False)
data["t"], data["x"], data["xnames"]

Nested structs (for example a clock’s results) become keys joined by /, such as clock0/X, and hidden fields keep their leading dot, such as .stats/ydot_calls. A list that makes a rectangular array is stored as one array, a ragged list element by element (.ywatch/0, .ywatch/1). None and other objects that are not data are left out.

BlockDiagram, full listing

Full member listing for BlockDiagram — see its description and wiki links under Simulation-user API above.

class bdsim.BlockDiagram(name=None, **kwargs)[source]

Bases: AnalysisMixin, GraphMixin, ReportMixin, BlockFactoryStubs, RTBStubs, MVTBStubs

Block diagram class. This object is the parent of all blocks and wires in the system.

Variables:
  • wirelist (list[Wire]) – all wires in the diagram

  • blocklist (list[Block]) – all blocks in the diagram

  • x (numpy.ndarray) – state vector

  • compiled (bool) – diagram has successfully compiled

  • blockcounter (collections.defaultdict) – unique counter for each block type

  • blockdict (dict) – index of all blocks by category

  • name (str or None) – name of this diagram, None until given one. A main diagram is named main when first compiled; a subsystem diagram’s name is the stem of its instances’ names, see BDSim.blockdiagram()

This object:

  • holds all the blocks and wires that comprise the system

  • manages continuous- and discrete-time state vector for the whole system, splitting it across blocks as required

  • evaluates the entire diagram as a function to compute \(\dot{x} = f(x, t)\)

compile(subsystem=False, doimport=True, evaluate=True, report=False, verbose=False)[source]

Compile the block diagram

Parameters:
  • subsystem (bool) – importing a subsystems, defaults to False

  • doimport (bool) – import subsystems, defaults to True

Raises:

RuntimeError – various block diagram errors

Returns:

Compile status

Return type:

bool

Performs a number of operations:

  • Check sanity of block parameters

  • Recursively clone and import subsystems

  • Check for loops without dynamics

  • Check for inputs driven by more than one wire

  • Check for unconnected inputs and outputs

  • Link all output ports to outgoing wires

  • Link all input ports to incoming wires

  • Evaluate all blocks in the network

connect(start, *ends, name=None)[source]

Connect blocks

Parameters:
  • start (Port) – The output port that the wire starts from.

  • ends (Port) – The input port(s) that the wire ends at. Can be one or more.

  • name (str | None) – The name of the wire, defaults to None

Return type:

None

Connect blocks together. The start block can be connected to one or more end blocks.

Blocks are added to the block diagram’s blocklist if they are not already part of it.

The wires are added to the diagram’s wirelist, but the connections are not actually made until compile time. The wirelist is a list of things that will be connected later.

dotfile(filename, shapes=None)

Write a GraphViz dot file representing the network.

Parameters:
  • file (str, file handle) – Name of file to write to, or file handle

  • shapes (Any) – block shapes

Return type:

None

Create a GraphViz format file for procesing by dot. The graph is:

  • directed graph, drawn left to right

  • source blocks are in the first column

  • sink and graphics blocks are in the last column

  • SUM and PROD blocks have the sign or operation of their input wires labeled.

The file can be processed using dot:

% dot -Tpng -o out.png dotfile.dot
Block diagram represented as a mathematical graph

Note

By default all blocks have the default shape, with source blocks shown as a rectangle (“record”), and sink/graphics blocks as a rounded rectangle (“Mrecord”). This can be overriden by provide a dictionary shapes that maps block class (sink, source, graphics, function, transfer) to the names of GraphViz shapes.

Seealso:

graph() showgraph()

functions(inputs=None, outputs=None, *, full=False)

The diagram as the functions \(f\) and \(g\) of a nonlinear system

Overloads:
Parameters:
  • inputs (list[Block | Plug | str] | None) – the source blocks, or the outputs of them, that are the input \(u\), see below. Defaults to every source block except TIME and the constants bdsim creates for numbers written in expressions, which are parameters, not inputs.

  • outputs (list[Block | Plug | str] | None) – the signals that are the output \(y\), see below. Defaults to the signal into every sink input.

  • full (bool) – return a SystemFunctions object, which also has the sizes of the vectors and the maps that say what they are made of, instead of just the two functions

Returns:

the pair (f, g), or a SystemFunctions object if full, which also unpacks as f, g

Raises:
\[\dot{x} = f(x, u, t), \qquad y = g(x, u, t)\]

The diagram must be compiled. The source blocks are replaced by the values of \(u\), TIME supplies \(t\), and \(y\) is read from the diagram. The sink blocks are not executed (nothing is plotted, printed or logged). \(x\) is the continuous state in the order the blocks were added to the diagram, as in bd.statenames.

Choosing the input and the output

Both are lists. An entry is a block, one of its ports (a plug, such as plant[0]), or the name of a block (such as "plant").

Entry of inputs

\(u\) contains

a source block, demand

all its outputs

a port of a source block, demand[0]

that output

Source blocks that are not selected keep producing their own values. TIME cannot be an input, it is the argument t. To add a signal into the middle of a diagram, which has no input there, insert a SUM block and a CONSTANT(0) block at that point: the constant is then an input.

Entry of outputs

\(y\) contains

any other block, plant

all its outputs

a port of a block, plant[0]

that output

a sink block, scope

the signals wired into all its inputs

a port of a sink block, scope[1]

the signal wired into that input

The output is a signal, named by the block and port that produce it. A sink has no outputs, so naming a sink means the signals it receives. This is also how the default is made, and a signal that is wired to several sinks is included once.

The elements of \(u\) and \(y\) are ordered by the order in which the blocks were added to the diagram, and then by port, whatever the order of the lists. A block’s array output is flattened, and uindex and yindex say where each block’s elements are.

For example:

f, g = bd.functions()
xdot = f(x, u, t)
y = g(x, u, t)

To check what x, u and y are made of, and how long they are, ask for the full object, as linearize does with full=True:

sysf = bd.functions(full=True)
sysf.xindex  # which states belong to which block
sysf.nu, sysf.ny  # the lengths of u and y
f, g = sysf  # the same two functions
xdot, y = sysf.fg(x, u, t)  # both, from one evaluation of the diagram

The object also has nx, the initial state x0, u_at(t) for the natural input at a time, and uindex and yindex for the inputs and outputs. f and g each evaluate the diagram, so fg is half the work when both are needed at the same point.

The state of the blocks is as the last run left it. After a run, for example, an integrator held at its limit is still held, so the model is that of the diagram at the end of the run. A diagram that has not been run has its blocks reset first. Do not call the functions during a simulation: they overwrite the values on the wires.

Seealso:

linearize() SystemFunctions State State_S

graph(format='dot', filename=None, shapes=None)

Render diagram text in DOT, Mermaid, GraphML, or ELK JSON format.

Parameters:
  • format (str) – graph output format: "dot", "mermaid", "mermaid_fenced", "graphml" or "elk"

  • filename (str | TextIOWrapper | None) – destination path or open text stream, defaults to None

  • shapes (Any) – optional DOT block shape mapping (DOT output only)

Returns:

rendered graph text

Return type:

str

If filename is provided the rendered text is also written to it.

"mermaid_fenced" is identical to "mermaid" but wraps the output in a \`\`\`mermaid fenced code block, ready to paste into Markdown or a Jupyter notebook cell.

Mermaid format can be rendered in Markdown files and on GitHub, and GraphML and ELK JSON can be imported into graph visualization tools such as yEd and Eclipse ELK respectively.

Node shapes by block kind (dot and mermaid only)

Block kind

DOT shape

Mermaid shape

source

record

rectangle [label]

stateful (continuous, sampled, or hasstate)

box3d

subroutine [[label]]

sum / prod

(default ellipse)

circle ((label))

graphics / display

Mrecord

asymmetric >label]

sink

Mrecord

rectangle [label]

function / other

(default ellipse)

rectangle [label]

In a Jupyter notebook, the graph can be rendered directly by exporting in mermaid_fenced format and using using IPython’s display function:

from IPython.display import Markdown, display

display(Markdown(bd.graph(format="mermaid_fenced"))) # Render dynamically via Jupyter's built-in Mermaid engine
Seealso:

dotfile()

linearize(x=None, u=None, t=0.0, *, inputs=None, outputs=None, h=None, scale=None, estimate_error=False, full=False)

Linearize the diagram about an operating point

Overloads:
Parameters:
  • x (ArrayLike | None) – state of the operating point, defaults to the initial state of the diagram. After a run use out.x[-1].

  • u (ArrayLike | None) – input of the operating point, defaults to the natural input of the sources at t

  • t (float) – time of the operating point

  • inputs (list[Block | Plug | str] | None) – the source blocks or ports that are the input, see functions()

  • outputs (list[Block | Plug | str] | None) – the blocks or ports whose signals are the output, see functions()

  • h (float | None) – step of the numerical derivative, defaults to a size chosen for each variable

  • scale (ArrayLike | None) – typical size of the variables, a number or an array with one element for each state and then each input, defaults to 1. Give it when a variable is far from 1 in size and zero at the point.

  • estimate_error (bool) – also differentiate with twice the step, to estimate the error and warn where a block is not smooth enough

  • full (bool) – return a Linearization, which also has the operating point and the names of the states, inputs and outputs, and prints as a labelled model, see __str__()

Returns:

(A, B, C, D), or the Linearization if full

Raises:

NotImplementedError – the diagram has sampled (discrete-time) blocks

The matrices of the local linear model are the Jacobians

\[A = \frac{\partial f}{\partial x},\quad B = \frac{\partial f}{\partial u},\quad C = \frac{\partial g}{\partial x},\quad D = \frac{\partial g}{\partial u}\]

of the functions \(f\) and \(g\) of functions(), estimated by central differences with a step \(h \approx \epsilon^{1/3} \max(|v|, s)\) for a variable \(v\) of typical size \(s\), where \(\epsilon\) is the machine precision.

A state reached part way through a simulation is not usually an equilibrium, so \(f \neq 0\) there and the model is \(\delta\dot{x} = A\,\delta x + B\,\delta u + f_0\). The result does not include \(f_0\), but full=True returns it with \(g_0\).

The result has the form of the matrices of a linear time-invariant system and can be used directly to make a LTI_SS block. For control system design, including poles, stability and optimal control, see the python-control package, https://github.com/python-control/python-control, which takes the same (A, B, C, D).

For example, to linearize at the end of a simulation:

out = sim.run(bd, T=5)
A, B, C, D = bd.linearize(out.x[-1])

To design state feedback from the result, take a gain matrix K from the A and B and feed the state back with a State block, F = -K * bd.STATE(). The state of that block is in the order of the states of this method, so K applies directly, and linearizing the closed loop gives \(A - BK\). The state of a clocked block is available from State_S.

If the operating point is at a corner of a non-smooth block (a limit, a dead band, a switch) the derivative is not defined there. The result is then the slope across the step; with estimate_error a warning says that the estimate is not reliable.

Seealso:

functions() LTI_SS State State_S

report_lists(**kwargs)

Print a tabular report about the block diagram.

Parameters:

kwargs (Any) – options passed to ansitable.table.ANSIMatrix.print()

Return type:

None

Print the important lists in pretty format.

  • block list, all blocks

  • wire list, all wires

  • clock list, all discrete time clocks

report_params(fixed=False, **kwargs)

Print a table of the parameters of all blocks and their current values.

Parameters:
Return type:

None

The first column is the name exactly as it is used by the --set option, block:param, and by set_param(). The columns are

  1. the name, block:param

  2. the current value, abbreviated if it is long

  3. its type, as the signature of the value

  4. when it can be set: anytime, setup (before the run starts), or never (only with fixed=True)

Blocks inside a subsystem are listed with the path of the subsystem, such as sub/gain.0:K. A subsystem block that declares parameters of its own, such as PID, is listed by its own name, pid.0:P, instead of the blocks inside it, which can still be set by their own names. The --param option prints this table when the diagram is compiled.

Seealso:

add_param() set_param()

report_schedule(**kwargs)

Display execution schedule in tabular form

Parameters:

kwargs (Any) – options passed to ansitable.table.ANSIMatrix.print()

Seealso:

schedule_dotfile()

Return type:

None

report_subsystems(**kwargs)

Print a table of the inputs and outputs of the subsystems.

Parameters:

kwargs (Any) – options passed to ansitable.table.ANSIMatrix.print()

Return type:

None

A subsystem block is not part of the compiled network, and its INPORT and OUTPORT blocks have been replaced by wires, so the signals that cross its boundary are listed here. The columns are

  1. the port, such as pid.0[1], which is what can be watched

  2. in or out

  3. the block and port that the signal comes from, the source, which for an output is a block inside the subsystem (looking through nested subsystems) and for an input is a block outside it

  4. the type of the signal, as the signature recorded when the diagram was compiled

Seealso:

SubsystemBlock.inports SubsystemBlock.outports

report_summary(sortby='name', depth=None, implicit=True, **kwargs)

Print a summary of block diagram.

Parameters:
  • sortby (str) – sort rows by specified block attribute: “name” [default] or “type”

  • depth (int | None) – only show blocks with subsystem depth less than or equal to this value, defaults to None (show all)

  • implicit (bool) – show implicit blocks, defaults to True

  • kwargs (Any) – options passed to ansitable.table.ANSIMatrix.print()

Raises:

ValueError – sortby is not “name” or “type”

Return type:

None

Print a table with 4 columns:

  1. Block name, sorted in alphabetical order

  2. The input port (if not a source block)

  3. The block driving this port (if not a source block)

  4. The type of value driving this port (if not a source block)

If the block is an event source, add a @ suffix.

Implicit blocks are those created for the user, such as the constants and gains made by writing 2 * x or x + 1, whose names start with _. They are listed after all the other blocks, sorted in the same way, or hidden if implicit is False.

schedule_dotfile(filename)

Write a GraphViz dot file representing the execution schedule

Parameters:

file (str) – Name of file to write to

Return type:

None

The file can be processed using neato or dot:

% dot -Tpng -o out.png dotfile.dot

Display execution plan as a dataflow graph.

Seealso:

report_schedule()

showgraph()

Display diagram as a graph in browser tab

Seealso:

dotfile() graph()

Return type:

None

property xindex: Index

Which elements of the continuous state vector belong to which block.

Returns:

an Index

This is the one definition of the layout of the state \(x\) of the diagram, the vector the solver advances: the states of the blocks that have continuous state, in the order the blocks were added. The state passed to functions(), returned by run() as out.x, and output by a State block are all in this order.

The names are those a block gave its states, with snames, and otherwise the block’s name, or name[k] for the k-th of several. bd.statenames names the same elements in the same order, in the form name:x_k, which is also what out.xnames holds.

Components

Wire

class bdsim.Wire(start, end, name=None)[source]

Bases: object

Create a wire.

Parameters:
  • start (Plug) – Plug at the start of a wire

  • end (Plug) – Plug at the end of a wire

  • name (str | None) – Name of wire, defaults to None

Returns:

A wire object

Return type:

Wire

A Wire object connects two block ports. A Wire has a reference to the start and end ports.

A wire records all the connections defined by the user. At compile time wires are used to build inter-block references.

Between two blocks, a wire can connect one or more ports, ie. it can connect a set of output ports on one block to a same sized set of input ports on another block.

bind_slot(slot)[source]
Return type:

None

property fullname: str

Display wire connection details.

Returns:

Wire name

Return type:

str

String format:

d2goal[0] --> Kv[0]
property info: None

Interactive display of wire properties.

Displays all attributes of the wire for debugging purposes.

newstart(plug)[source]

Change the output port that the wire starts at.

Parameters:

plug (Plug) – the new start of the wire

Raises:

RuntimeError – the wire is already connected to its blocks

Return type:

None

The wire takes a copy of the plug, so that changing one wire can never change another that shares the plug. It is used while the diagram is being flattened, before BlockDiagram.compile() connects the wires to the blocks.

property value: Any

Plug

class bdsim.Plug(block, port=0, kind=None, *, type=None)[source]

Bases: Port

Create a plug.

Parameters:
  • block (Block) – The block being plugged into

  • port (int | slice) – The port on the block, defaults to 0

  • kind (str | None) – ‘start’ or ‘end’, defaults to None

  • type (str | None) – deprecated, use kind

Returns:

Plug object

Return type:

Plug

Plugs are the interface between a wire and block and have information about port number and wire end. Plugs are on the end of each wire, and connect a Wire to a specific port on a Block.

The kind argument sets the type attribute, which indicates if the Plug is at:
  • the start of a wire, ie. the port is an output port

  • the end of a wire, ie. the port is an input port

A plug can specify a set of ports on a block.

__add__(other)[source]
Return type:

Block

__annotations__ = {'block': 'Block', 'port': 'int | slice', 'type': 'str'}
__getitem__(i)[source]
Return type:

Self

__init__(block, port=0, kind=None, *, type=None)[source]
__mul__(other)[source]
Return type:

Block

__neg__()[source]
Return type:

Block

__pow__(p)[source]
Return type:

Block

__radd__(other)[source]
Return type:

Block

__repr__()[source]

Return repr(self).

Return type:

str

__rmul__(other)[source]
Return type:

Block | Any

__rshift__(right)[source]
Return type:

Plug | Block

__rsub__(other)[source]
Return type:

Block

__rtruediv__(other)[source]
Return type:

Block

__str__()[source]

Return str(self).

Return type:

str

__sub__(other)[source]
Return type:

Block

__truediv__(other)[source]
Return type:

Block

block: Block
property isslice: bool
port: int | slice
property portlist: list[int] | range
type: str
property width: int

Port

class bdsim.connect.Port[source]

Bases: object

A common base class for blocks and plugs, to allow operator overloading for implicit block creation.

Signal slot

class bdsim.block.PortValueSlot[source]

Bases: object

The signal on one wire.

The slot of an output port is shared with every input port wired to it, so value and signature are the producer’s and every consumer’s view of the same wire. signature is None until compile() has observed the wire.

signature: Signature | None
value: Any

Signal signature

class bdsim.signature.Signature(type, shape=None, dtype=None)[source]

Bases: object

The type of the signal on a wire.

Parameters:
  • type (type) – Python type of the value

  • shape (tuple[int, ...] | None) – shape, only if type is ndarray, otherwise None

  • dtype (dtype | None) – element type, only if type is ndarray, otherwise None

Create one from a value with of(). Signatures are immutable and compare by value.

A Python or NumPy scalar has no shape: its signature is just its type, for example int, float or numpy.float64. A 1-D array of size 1 is presented by bdsim as a scalar, so it does not appear as a signature.

Seealso:

of()

dtype: dtype | None
matches(other)[source]

Is other the same kind of signal as this one?

Arrays must have the same shape and dtype. Scalars match if they are the same kind, bool, int, float or complex, so a Python float and a numpy.float64 agree but an int and a float do not. Any other type must be exactly the same type.

Return type:

bool

matches_value(value)[source]

Does value have this signature? Same rule as matches(), without making a Signature for the value.

Return type:

bool

classmethod of(value)[source]

Signature of a value.

Parameters:

value (Any) – any Python object

Return type:

Signature

Returns:

its signature

shape: tuple[int, ...] | None
type: type

Event source and crossing detection

class bdsim.block.EventSource[source]

Bases: object

class bdsim.crossing.CrossingMixin[source]

Bases: object

Mixin for blocks that register zero-crossing detectors.

Blocks that do not need events do not inherit from this and pay nothing.

A subclass registers detectors from start() with declare_crossing() and overrides crossing_event() to respond. Detectors are sized in configure(), where insig is known, and any mode kept by the block is restored in reset().

A block changes mode only in crossing_event(), which runs between solve_ivp calls. It must not change mode in deriv or in a detector, since the solver would then see a discontinuous right-hand side within a step.

crossing_event(tag, t_crossing, y_crossing, state_map, simstate)[source]

Respond to a detector firing.

Parameters:
  • tag (Any) – the tag the detector was declared with

  • t_crossing (float) – time of the crossing

  • y_crossing (Any) – continuous state vector of the whole diagram at the crossing

  • state_map (dict[Any, Any]) – block to state map, the diagram already evaluated at the crossing; write into state_map[self] to change this block’s state

  • simstate (Any) – the run’s simulation state

Return type:

None

The solver restarts from the state map after this returns.

The default does nothing for the threshold crossings declared by declare_thresholds() and raises for anything else.

declare_crossing(simstate, func, direction, tag)[source]

Register one terminal scalar detector.

Parameters:
  • simstate (Any) – the run’s simulation state, as passed to start

  • func (Callable[[ndarray, list[Any], bool], float]) – func(x, u, at_start) -> float, given the block’s state vector, its input port values at the probe point, and whether the probe is the first point of the solver interval

  • direction (float) – +1 fires on a rising zero crossing, -1 on a falling one, 0 on either

  • tag (Any) – identifies the detector, handed back to crossing_event() when it fires; must not be None

Return type:

None

A detector that is currently inactive should return a nonzero constant, not zero: solve_ivp counts a value of exactly zero at the start of an interval as a crossing.

The solver reports only the earliest of several simultaneous crossings and restarts just beyond it, so another detector may by then be past its threshold and would never fire. At the start of an interval, and only there, a detector that is already past its threshold in its direction should return exactly zero, which reports the crossing at once. Elsewhere it must return the true value, or the root is found at the step end and not at the crossing.

declare_thresholds(simstate, thresholds, port=0)[source]

Break the solver step wherever an input signal crosses a threshold.

Parameters:
  • simstate (Any) – the run’s simulation state, as passed to start

  • thresholds (Sequence[tuple[int, float]]) – (element, value) pairs; infinite values are skipped

  • port (int) – input port whose signal is watched, defaults to 0

Return type:

None

For a stateless block whose output is continuous but whose slope jumps (CLIP, DEADBAND, ABS) or whose output jumps (SIGN) at a threshold. Nothing changes at the crossing: the point is that the solver restarts exactly there, so no step straddles the corner. Crossings in either direction are found, and a signal exactly on a threshold counts as above it.

Several thresholds crossed at the same instant are harmless: the restart is just beyond the earliest, and the others lie within that gap.

signal_size(port=0)[source]

Number of elements in the signal on an input port.

Parameters:

port (int) – input port index, defaults to 0

Return type:

int

Returns:

1 for a scalar, the size of an array otherwise; 1 if the diagram has not been compiled with evaluation, so the signal is unknown

Simulation state and jobs

class bdsim.components.Runner[source]

Bases: object

Base class for simulation runners (offline, realtime, etc.).

DEBUG(debug, fmt, *args)[source]
Return type:

None

closefigs()[source]
Return type:

None

done(bd, block=False)[source]
Return type:

None

report(bd, type='summary', **kwargs)[source]
Return type:

None

class bdsim.components.SimulationState[source]

Bases: object

Base class for per-run execution state.

Attributes

x

Current continuous-state vector view used by the active runner path.

tf

Requested simulation horizon for the current run.

t

Current simulation time.

fignum

Count of open/allocated graphics figures.

stop

Stop-request source (typically a block instance) or None.

check

If True, check block outputs and derivatives as they are computed.

debugger

Legacy debugger enable flag used by some runner/debug paths.

t_stop

Optional pending stop time marker.

eventq

Time-ordered queue of scheduled events/callbacks.

options

Effective per-run options object.

clock_states

Per-clock sampled runtime states keyed by Clock instance.

declare_event(block, t)[source]
Return type:

None

hasdebug()[source]

Return True if any debug flags are set.

Return type:

bool

isdebug(flag)[source]

Return True if flag appears in the debug option string.

Return type:

bool

class bdsim.run_context.SimulationJob(future)[source]

Bases: object

Thin wrapper around a submitted simulation future.

cancel()[source]
Return type:

bool

done()[source]
Return type:

bool

exception(timeout=None)[source]
Return type:

BaseException | None

result(timeout=None)[source]
Return type:

Any

wait(timeout=None)[source]
Return type:

None

Blocks

class bdsim.Block(name=None, nin=None, nout=None, nstates=0, ndstates=0, x0=None, inputs=None, inames=None, onames=None, snames=None, clock=None, pos=None, bd=None, type=None, blockclass=None, **kwargs)[source]

Bases: ABC, Port

Block is the superclass of all blocks in the simulation environment. It defines the common properties of all blocks:

  • nin the number of input ports

  • nout the number of output ports

  • nstates the number of continuous-time state variables

  • ndstates the number of discrete-time state variables

  • name the unique name of the block

  • blockclass a string indicating the block class, eg. ‘sink’, ‘source’, ‘function’, ‘transfer’, ‘subsystem’, ‘clocked’, etc.

  • type a string indicating the block type, eg. ‘gain’, ‘sum’, ‘integrator’, etc.

The simulation engine uses these methods:

  • getstate0(): returns the initial state of the block as a NumPy array

  • setstate(x): sets the state of the block to the given state x and returns any remaining state for the next block in the clock sequence

  • next(t, u, x): computes the next state of the block given the current time t, input values inputs, and current state x

  • output(t, u, x): returns the output value of the block at output port i given the current state and inputs. The outputs are cached and can be accessed by block.output_value(i)

  • deriv(t, u, x): returns the derivative of the state variables for continuous-time blocks

  • reset(): restores the block’s own initial state, once per run

  • configure(): prepares the block for a run using the signatures of its wires, once per run, after reset() and before start()

  • done(): performs any cleanup at end of the simulation

  • add_param(name, when=, validate=, coerce=): registers a parameter, one call per __init__ argument, with when it can be set (anytime, setup or never)

  • set_param(name, value): sets a registered parameter, checking that the value is of the same kind as the current one, and returns the old value

  • parameters(): the parameters that can be set, with their current values

  • info(): displays information about the block for debugging purposes

Ports can be accessed by index, eg. block.input_value(i) or block.output_value(i), or by name, eg. block.inport("in1") or block.outport("out1") if the block has named ports.

  • input_value(i): returns the value of the input port at index i

  • output_value(i): returns the value of the output port at index i

  • inport_name(i): returns the name of the input port at index i

  • outport_name(i): returns the name of the output port at index i

__abstractmethods__ = frozenset({})
__add__(other)[source]

Overloaded + operator for implicit block creation.

Parameters:
  • self (Block) – A signal (block) to be added

  • other (Block or Plug) – A signal (block or plug) to be added

Returns:

SUM block

Return type:

Block

This method is implicitly invoked by the + operator when the right operand is a Block and the left operand is a Plug, Block or constant:

result = X + Y
result = X + Y[j]
result = X + C

where X and Y are blocks and C is a Python or NumPy constant.

Creates a SUM("++") block named ``_sum.N whose inputs are the left and right operands. For the third case, a new CONSTANT(C) block named _const.N is also created.

Note

  • The inputs to the summing junction are reversed: right then left operand.

  • The mode is None, regular addition

Seealso:

Block.__radd__() Plug.__add__()

__annotations__ = {'_bd': 'BlockDiagram | None', '_blockclass': 'str', '_clock': 'Clock | None', '_clocked': 'bool', '_display_param': 'str | None', '_graphics': 'bool', '_id': 'int | None', '_initd': 'bool', '_inport_names': 'list[str] | None', '_inport_slots': 'list[PortValueSlot | None]', '_input_wires': 'list[Wire | None]', '_name': 'str | None', '_name_tex': 'str | None', '_outport_names': 'list[str] | None', '_outport_slots': 'list[PortValueSlot]', '_output_values': 'list | None', '_output_wires': 'list[list[Wire]]', '_parameters': 'dict[str, Parameter]', '_parents': 'list[Plug | None]', '_pos': 'tuple[float, float] | None', '_running': 'bool', '_sequence': 'int | None', '_state_names': 'list[str] | None', '_type': 'str', '_x_view': 'np.ndarray | None', 'inlabels': 'list[str] | tuple[str, ...] | None', 'nin': 'int', 'nout': 'int', 'outlabels': 'list[str] | tuple[str, ...] | None'}
__getattr__(name)[source]

Convert a RHS block name reference to a Plug.

Parameters:

name (str) – Port name

Returns:

Block or plug for specified block port name

Return type:

Any

Used to create a wired connection by assignment, for example:

c = bd.CONSTANT(1, onames=['v'])

y = c.v

    ┌───┐               ┌───┐
    │ c ├ v ──────────▶ │ y │
    └───┘               └───┘

Also used for assignments using connect, for example:

bd.connect(x, c.v)  # connect output of x to input port v of block c
bd.connect(c.v, x)  # connect output port v of block c to input of x

Warning

to avoid infinite recursion, this method must use super().__getattribute__ to access attributes of the block, and only create a Plug if the name is in the list of port names.

__getitem__(port)[source]

Convert a RHS block slice reference to a Plug.

Parameters:

port (int | slice) – Port number

Returns:

A port plug

Return type:

Plug

Invoked whenever a block is referenced as a slice, for example:

c = bd.CONSTANT(1)

bd.connect(x, c[0])
bd.connect(c[0], x)

In both cases c[0] is converted to a Plug by this method.

__init__(name=None, nin=None, nout=None, nstates=0, ndstates=0, x0=None, inputs=None, inames=None, onames=None, snames=None, clock=None, pos=None, bd=None, type=None, blockclass=None, **kwargs)[source]

Construct a new block object.

Parameters:
  • name (str | None) – Name of the block, defaults to None

  • nin (int | None) – Number of inputs, defaults to None

  • nout (int | None) – Number of outputs, defaults to None

  • inputs (Block | tuple[Block | Plug, ...] | list[Block | Plug] | None) – Optional incoming connections

  • inames (list[str] | None) – Names of input ports, defaults to None

  • onames (list[str] | None) – Names of output ports, defaults to None

  • snames (list[str] | None) – Names of states, defaults to None

  • pos (tuple[float, float] | None) – Position of block on the canvas, defaults to None

  • bd (BlockDiagram | None) – Parent block diagram, defaults to None

  • kwargs (Any) – Unused arguments

Returns:

A Block superclass

Return type:

Block

A block object is the superclass of all blocks in the simulation environment.

This is the top-level initializer, and handles most options passed to the superclass initializer for each block in the library.

classmethod __init_subclass__(**kwargs)[source]

Initialize a subclass of Block.

Parameters:
  • cls (type) – The subclass being initialized

  • kwargs (Any) – keyword args passed to subclass definition

Return type:

None

This method is called when a new subclass of Block is defined, not when it is instantiated. Here we check that the subclass does not define methods that are inconsistent with its block class, and raise an error if it does. This is a sanity check to prevent blocks from being defined with methods that will never be called by the simulation engine, which would indicate a misunderstanding of the block API.

__mul__(other)[source]

Overloaded * operator for implicit block creation.

Parameters:
Returns:

PROD or GAIN block

Return type:

Block

This method is implicitly invoked by the * operator when the left operand is a Block and the right operand is a Plug, Block or constant:

result = X * Y
result = X * Y[j]
result = X * C

where X and Y are blocks and C is a Python or NumPy constant.

Create a PROD("**") block named _prod.N whose inputs are the left and right operands.

For the third case, create a GAIN(C) block named _gain.N.

Note

C can be a scalar or ndarray.

Seealso:

Block.__rmul__() Plug.__mul__()

__neg__()[source]

Overloaded unary minus operator for implicit block creation.

Parameters:

self (Block) – A signal (block) to be negated

Returns:

GAIN block

Return type:

Block

This method is implicitly invoked by the - operator for unary minus when the operand is a Block:

result = -X

where X is a block.

Creates a GAIN(-1) block named _gain.N whose input is the operand.

Seealso:

Plug.__neg__()

__pow__(p)[source]

Overloaded unary power operator for implicit block creation.

Parameters:

self (Block) – A signal (block) to be negated

Returns:

POW block

Return type:

Block

This method is implicitly invoked by the ** operator for unary power when the operand is a Block:

result = X**3

where X is a block.

Creates a POW(3) block named _pow.N whose input is the operand.

Seealso:

Plug.__pow__()

__radd__(other)[source]

Overloaded + operator for implicit block creation.

Parameters:
Returns:

SUM block

Return type:

Block

This method is implicitly invoked by the + operator when the right operand is a Block and the left operand is a Plug, Block or constant:

result = X + Y[j]
result = X[i] + Y[j]
result = C + Y[j]

where X and Y are blocks and C is a Python or NumPy constant.

Creates a SUM("++") block named ``_sum.N whose inputs are the left and right operands. For the third case, a new CONSTANT(C) block named _const.N is also created.

Note

  • The inputs to the summing junction are reversed: right then left operand.

  • The mode is None, regular addition

Seealso:

Block.__add__() Plug.__radd__()

__repr__()[source]

Return repr(self).

Return type:

str

__rmul__(other)[source]

Overloaded * operator for implicit block creation.

Parameters:
  • self (Block) – A signal (block) to be multiplied

  • other (int | float | ndarray) – A signal (block or plug) to be multiplied

Returns:

PROD or GAIN block

Return type:

Block | None

This method is implicitly invoked by the * operator when the right operand is a Block and the left operand is a Plug, Block or constant:

result = X * Y
result = X[i] * Y
result = C * Y

where X and Y are blocks and C is a Python or NumPy constant.

For the first two cases, a PROD("**") block named _prod.N whose inputs are the left and right operands.

For the third case, create a GAIN(C) block named _gain.N.

Note

C can be a scalar or ndarray.

Seealso:

Block.__mul__() Plug.__rmul__()

__rshift__(right)[source]

Operator for implicit wiring.

Parameters:
  • left (Block) – A block to be wired from

  • right (Block | Plug) – A block or plugto be wired to

Returns:

right

Return type:

Block | Plug

Implements implicit wiring, for example:

a = bd.CONSTANT(1) >> bd.GAIN(2)

will connect the output of the CONSTANT block to the input of the GAIN block. The result will be GAIN block, whose output in this case will be assigned to a.

Note that:

a = bd.CONSTANT(1) >> func[1]

will connect port 0 of CONSTANT to port 1 of func, and port 1 of func will be assigned to a. To specify a different outport port on func we need to use parentheses:

a = (bd.CONSTANT(1) >> func[1])[0]

which will connect port 0 of CONSTANT ` to port 1 of func, and port 0 of func will be assigned to a.

Seealso:

Plug.__rshift__

__rsub__(other)[source]

Overloaded - operator for implicit block creation.

Parameters:
  • self (Block) – A signal (block) to be added (minuend)

  • other (Block | Plug | int | float | ndarray) – A signal (block or plug) to be subtracted (subtrahend)

Returns:

SUM block

Return type:

Block

This method is implicitly invoked by the - operator when the left operand is a Block and the right operand is a Plug, Block or constant:

result = X - Y
result = X[i] - Y
result = C - Y

where X and Y are blocks and C is a Python or NumPy constant.

Creates a SUM("+-") block named _sum.N whose inputs are the left and right operands. For the third case, a new CONSTANT(C) block named _const.N is also created.

Note

  • The inputs to the summing junction are reversed: right then left operand.

  • The mode is None, regular addition

Seealso:

Block.__sub__() Plug.__rsub__()

__rtruediv__(other)[source]

Overloaded / operator for implicit block creation.

Parameters:
  • self (Block) – A signal (block) to be multiplied (dividend)

  • other (Block | Plug | int | float | ndarray) – A signal (block or plug) to be divided (divisor)

Returns:

PROD block

Return type:

Block

This method is implicitly invoked by the / operator when the right operand is a Block and the left operand is a Plug, Block or constant:

result = X / Y
result = X[i] / Y
result = C / Y

where X and Y are blocks and C is a Python or NumPy constant.

For the first two cases, a PROD("*/") block named _prod.N whose inputs are the left and right operands. For the third case, a new CONSTANT block named _const.N is also created.

Note

C can be a scalar or ndarray.

Seealso:

Block.__truediv__() Plug.__rtruediv__()

__setattr__(name, value)[source]

Convert a LHS block name reference to a wire.

Parameters:
  • name (str) – Port name

  • value (Any) – the RHS

Return type:

None

Used to create a wired connection by assignment, for example:

c = bd.CONSTANT(1, inames=['u'])

c.u = x

Ths method is invoked to create a wire from x to port ‘u’ of the constant block c.

+—+ +—+ | x | ——–> u- | c | +—+ +—+

Notes:

  • this overloaded method handles all instances of setattr and implements normal functionality as well, only creating a wire if name is a known port name.

__setitem__(port, src)[source]

Convert a LHS block slice reference to a wire.

Parameters:
Return type:

None

Used to create a wired connection by assignment, for example:

X[0] = Y

where X and Y are blocks. This method is implicitly invoked and creates a wire from Y to input port 0 of X.

Note

The square brackets on the left-hand-side is critical, and X = Y will simply overwrite the reference to X.

__sub__(other)[source]

Overloaded - operator for implicit block creation.

Parameters:
  • self (Block) – A signal (block) to be added (minuend)

  • other (Block | Plug | int | float | ndarray) – A signal (block or plug) to be subtracted (subtrahend)

Returns:

SUM block

Return type:

Block

This method is implicitly invoked by the - operator when the left operand is a Block and the right operand is a Plug, Block or constant:

result = X - Y
result = X - Y[j]
result = X - C

where X and Y are blocks and C is a Python or NumPy constant.

Creates a SUM("+-") block named _sum.N whose inputs are the left and right operands. For the third case, a new CONSTANT(C) block named _const.N is also created.

Seealso:

Block.__rsub__() Plug.__sub__()

__truediv__(other)[source]

Overloaded / operator for implicit block creation.

Parameters:
  • self (Block) – A signal (block) to be multiplied (dividend)

  • other (Block | Plug | int | float | ndarray) – A signal (block or plug) to be divided (divisor)

Returns:

PROD or GAIN block

Return type:

Block

This method is implicitly invoked by the / operator when the left operand is a Block and the right operand is a Plug, Block or constant:

result = X / Y
result = X / Y[j]
result = X / C

where X and Y are blocks and C is a Python or NumPy constant.

Create a PROD("**") block named _prod.N whose inputs are the left and right operands.

For the third case, create a GAIN(1/C) block named _gain.N.

Note

C can be a scalar or ndarray.

Seealso:

Block.__rtruediv__() Plug.__truediv__()

add_input_wire(w)[source]
Return type:

None

add_output_wire(w)[source]
Return type:

None

add_param(name, *, when='anytime', validate=None, coerce=True, forward=None, unavailable=None)[source]

Register a parameter of the block, one per call.

Parameters:
  • name (str) – the name of the parameter, which is the name of the __init__ argument. The block’s current value is getattr(self, name), so it is a plain attribute or a Python property

  • when (Literal['anytime', 'setup', 'never']) –

    when the parameter can be set, one of

    • "anytime": at any time, between evaluations (default)

    • "setup": before the run starts, including from --set, but not while it runs, because start() has used the value to build something such as an event or a figure

    • "never": not after the block is created, for structure such as nin or clock

  • validate (Optional[Callable[[Any], Any]]) – a function of the new value that raises ValueError or TypeError if it is not acceptable, for example a bound method of the block, called after the type has been checked. If it returns a value that is not None that replaces the new value, which lets a check that has to keep two parameters consistent promote them together

  • coerce (bool) – check the new value against the type of the current one, see set_param(), defaults to True. Give False for a parameter that legitimately takes several forms or changes shape, such as a polynomial that may be given as coefficients or as factors, and let the property setter or validate deal with the value

  • forward (tuple[Block, str] | None) – for a block made of other blocks, such as a subsystem: the parameter of an inner block that this one stands for, as (block, name). The value lives in the inner block, which does all the checking, so set_param and the current value are simply passed on. The inner parameter can itself be forwarded, so subsystems nest. The block is given as an object, which stays the right one when the subsystem is flattened into its parent diagram and its blocks are renamed.

  • unavailable (str | None) – for a parameter that belongs to a part the block was built without, such as the integral term of a PID block with I=0: the reason, which is the message if someone tries to set it

Return type:

None

Every __init__ argument of a block is registered, each with a decision about when it can be set. A parameter whose value is not kept under its own name, because the block built other blocks or derived state from it, is a property of the class: the getter finds the value and the setter applies it.

Seealso:

set_param() parameters()

property bd: BlockDiagram
Setter accepts:

BlockDiagram | None

bind_input_slot(i, slot)[source]
Return type:

None

property blockclass: str
check()[source]
Return type:

None

check_safe()[source]
Return type:

None

compile()[source]

Compile the block for execution.

This method is called at compile time to initialize the attributes required for compilation.

Seealso:

BlockDiagram.compile()

Return type:

None

configure()[source]

Prepare the block for a run, using what compile() learned about its wires.

Called once per run, after reset() and before start(). This is the place to read insig and outsig, for example to size per-element detectors or allocate buffers. The signatures are those observed by the trial evaluation in compile(). They are None if the diagram was compiled with evaluate=False, in which case the block should not assume anything about its wires.

The default does nothing. start() keeps its meaning: acquire resources and register with the simulation.

Return type:

None

configure_safe()[source]
Return type:

None

deriv_safe(t, u, x)[source]
Return type:

Any

done(**kwargs)[source]
Return type:

None

done_safe(**kwargs)[source]
Return type:

None

property fullname: str
getstate0_safe()[source]
Return type:

Any

property hasstate: bool

True if the block owns continuous or discrete state.

property id: int | None
property implicit: bool

True if the block is private, which means its name starts with _.

bdsim gives this kind of name to the blocks it creates for an expression such as x * 3 or x + 1, and you can give it to a block of your own. Private blocks are listed last in reports, are left out by report_summary(implicit=False) and are not taken to be inputs by linearize().

Only the last part of the name counts, since a block of a subsystem has the name of the subsystem in front of its own, for example sub/_gain.0.

property info: None

Interactive display of block properties.

Displays all attributes of the block for debugging purposes.

property initd: bool
inlabels: list[str] | tuple[str, ...] | None = None
inport_name(i)[source]

Get the name of an input port.

Parameters:

i (int) – Input port index

Return type:

str

Get the name of an input port by index. By default the name is the port number in square brackets, but if the block has named ports then the name is taken from the list of input port names.

Seealso:

outport_name() source_name()

inport_names(names)[source]

Set input port names (legacy method for backward compatibility).

Return type:

None

inport_value(i)[source]

Get the value applied to specified input port.

Parameters:

i (int) – Input port index

Returns:

Input port value

Return type:

Any

Get the value of the signal applied to port i.

Note

The value is read from a pre-bound input slot. For compatibility with direct unit tests (without compile), it falls back to predecessor block output lookup.

Seealso:

inport_values()

property inport_values: list[Any]

Get inport values as a list

Returns:

list of input to block

Return type:

list of length nin

Returns a list of values corresponding to the input ports of the block. The types of the elements are dictated by the blocks connected to the input ports.

Note

Values are read from pre-bound input slots. For compatibility with direct unit tests (without compile), if an input slot is not bound yet the value is read from the predecessor block.

Seealso:

inport_value()

property inports: list[Plug]

List of output plugs feeding into this block.

Returns:

List of source plugs

Return type:

list of Plug, of length nin

Returns the list of plugs that describe the outout ports (block and port) that feed into this block.

This is determined at compile time by the connections in the block diagram. It is used to determine the order of block execution.

Seealso:

inports()

property insig: list[Signature | None]

Signatures of the input ports.

The input port is bound to the slot of the output port that drives it, so this is that producer’s outsig. An entry is None if the port is unconnected or the wire has not yet been observed.

Seealso:

Signature outsig

property isclocked: bool

Test if block is clocked

Returns:

True if block is clocked

Return type:

bool

True if block is clocked, False if it is continuous time.

property isgraphics: bool

Test if block does graphics

Returns:

True if block does graphics

Return type:

bool

property label: str

The name for display: for an implicit block, the name with its value.

An implicit constant, gain or power block is only known by a counter, for example _gain.0, so its label also shows the value that makes it recognizable, _gain.0(3). The value is the current one, not the one the block was created with. A block with a name of its own has the name as its label.

The name, not the label, identifies the block: it is what bd["_gain.0"] and --set _gain.0:K=3 take.

property name: str | None
property name_tex: str | None
property ndstates: int
next_safe(t, u, x)[source]
Return type:

Any

nin: int = 0
nout: int = 0
property nstates: int
outlabels: list[str] | tuple[str, ...] | None = None
outport_name(i)[source]

Get the name of an output port.

Parameters:

i (int) – Output port index

Return type:

str

Get the name of an output port by index. By default the name is the port number in square brackets, but if the block has named ports then the name is taken from the list of output port names.

Seealso:

inport_name() source_name()

outport_names(names)[source]

Set output port names (legacy method for backward compatibility).

Return type:

None

outport_slot(i)[source]
Return type:

PortValueSlot

outport_value(i)[source]

Get the value of an output port.

Parameters:

i (int) – Output port index

Returns:

Output port value

Return type:

Any

Get the value of the signal at output port i.

Note

The value is obtained from the block’s output values which are stored in the attribute _output_values – a list of length nout. These values are set when the block’s output method is evaluated.

Seealso:

inport_value()

output_safe(t, u, x)[source]
Return type:

Any

property outsig: list[Signature | None]

Signatures of the output ports.

An entry is None until BlockDiagram.compile() has observed the wire.

Seealso:

Signature insig

parameters()[source]

The parameters that can be set, with their current values.

Returns:

{name: value} for every registered parameter that is not fixed

Return type:

dict[str, Any]

Seealso:

add_param() set_param()

property pos: tuple[float, float] | None
record(t, u)[source]

Record one accepted sample, independent of graphics/animation throttling.

Default is a no-op. Sink blocks that log signal data (e.g. Scope) override this to append at full simulation resolution, since step itself may be called only periodically for display-refresh purposes.

Parameters:
  • t (float) – simulation time

  • u (list[Any]) – block input port values

Return type:

None

record_safe(t, u)[source]
Return type:

None

remove_param(name)[source]

Remove a registered parameter, for a subclass whose parent registers one that does not apply to it.

Parameters:

name (str) – the name of the parameter

Return type:

None

reset()[source]

Restore the block’s initial internal state.

Called once per run, before start(), so that nothing the compile-time trial evaluation or a previous run did to the block is visible to the run about to start. A block that keeps state of its own in Python, for example a random number generator or a mode flag, must override this and restore it. Continuous and discrete state vectors are not part of this: they are restored from getstate0.

The values on the block’s ports are not touched.

Return type:

None

reset_safe()[source]
Return type:

None

savefig(*pos, **kwargs)[source]
Return type:

None

set_param(name, newvalue)[source]

Set a registered parameter of the block.

Parameters:
  • name (str) – the name of the parameter

  • newvalue (Any) – the new value

Return type:

Any

Returns:

the old value

Raises:
  • ValueError – no such parameter, it is fixed, it cannot be set while the run is going, or the value is not acceptable

  • TypeError – the value is of the wrong type

The new value must be of the same kind as the current one, see _coerce_parameter: an array keeps its shape and dtype, a number can widen from integer to float but not narrow, and so on. A list of numbers is converted to an array if the parameter is an array.

Seealso:

add_param() parameters()

source_name(port)[source]

Get the name of output port driving this input port.

Parameters:

port (int) – Input port

Returns:

Port name

Return type:

str

Get the name of the output port that drives the specified input port. By default the name is the port number in square brackets, but if the block has named ports then the name is taken from the list of input port names.

Seealso:

outport_name() inport_name()

property sources: list[Block]

List of source blocks feeding into this block.

Returns:

List of source blocks

Return type:

list of Block, of length nin

Returns the list of source blocks, those that feed input signals into this block.

This is determined at compile time by the connections in the block diagram. It is used to determine the order of block execution.

Seealso:

sources() source_name()

start(simstate)[source]
Return type:

None

start_safe(simstate)[source]
Return type:

None

state_names(names)[source]
Return type:

None

step_safe(t, u)[source]
Return type:

None

test_deriv(*inputs, t=0.0, x=None)[source]

Evaluate a block for unit testing.

Parameters:
  • inputs (Any) – input port values

  • t (float) – Simulation time, defaults to 0.0

  • x (ndarray | None) – state vector

Returns:

Block derivative value

Return type:

ndarray

The derivative of the block is evaluated for a given set of input port values. Input port values are treated as lists.

Mostly used for making concise unit tests.

test_next(*inputs, t=0.0, x=None)[source]

Evaluate a block for unit testing.

Parameters:
  • inputs (Any) – input port values

  • t (float) – Simulation time, defaults to 0.0

  • x (ndarray | None) – state vector

Returns:

Block next state value

Return type:

ndarray

The next value of a discrete time block is evaluated for a given set of input port values. Input port values are treated as lists.

Mostly used for making concise unit tests.

test_output(*inputs, t=0.0, x=None)[source]

Evaluate a block for unit testing.

Parameters:
  • inputs (Any) – Input port values

  • t (float) – Simulation time, defaults to 0.0

  • x (ndarray | None) – state vector

Returns:

Block output port values

Return type:

list[Any]

The output ports of the block are evaluated for a given simulation time and set of input port values. Input ports are assigned to consecutive inputs, output port values are a list.

Mostly used for making concise unit tests.

test_start(simstate=None)[source]
Return type:

SimulationState

test_step(*inputs, t=0.0)[source]

Step a block for unit testing.

Parameters:
  • inputs (Any) – input port values

  • t (float) – Simulation time, defaults to 0.0

Return type:

None

Step the block for a given set of input port values. Input port values are treated as lists.

Mostly used for making concise unit tests.

property type: str
validate_start()[source]

Validate block initialization completed after start.

Return type:

None

validate_start_safe()[source]
Return type:

None

Source block

class bdsim.SourceBlock(**blockargs)[source]

Bases: Block

A SourceBlock is a subclass of Block that represents a block that has outputs but no inputs. Its output is a function of parameters and time.

__abstractmethods__ = frozenset({'output'})
__annotations__ = {'_not_an_input': 'str | None', '_reads_state': 'bool'}
__init__(**blockargs)[source]

Create a source block.

Parameters:

blockargs (Any) – common Block options

Returns:

source block base class

Return type:

SourceBlock

This is the parent class of all source blocks.

__module__ = 'bdsim.block'
abstractmethod output(t, u, x)[source]
Return type:

list[Any]

Sink block

class bdsim.SinkBlock(**blockargs)[source]

Bases: Block

A SinkBlock is a subclass of Block that represents a block that has inputs but no outputs. Typically used to save data to a variable, file or graphics.

__abstractmethods__ = frozenset({'step'})
__annotations__ = {}
__init__(**blockargs)[source]

Create a sink block.

Parameters:

blockargs (Any) – common Block options

Returns:

sink block base class

Return type:

SinkBlock

This is the parent class of all sink blocks.

__module__ = 'bdsim.block'
abstractmethod step(t, u)[source]
Return type:

None

Function block

class bdsim.FunctionBlock(**blockargs)[source]

Bases: Block

A FunctionBlock is a subclass of Block that represents a block that has inputs and outputs but no state variables. Typically used to describe operations such as gain, summation or various mappings.

__abstractmethods__ = frozenset({'output'})
__annotations__ = {}
__init__(**blockargs)[source]

Create a function block.

Parameters:

blockargs (Any) – common Block options

Returns:

function block base class

Return type:

FunctionBlock

This is the parent class of all function blocks.

__module__ = 'bdsim.block'
abstractmethod output(t, u, x)[source]
Return type:

list[Any]

Continuous-time block

class bdsim.ContinuousBlock(nstates=0, x0=None, feedthrough=False, **blockargs)[source]

Bases: Block

A ContinuousBlock is a subclass of Block that represents a block with inputs, outputs and states. Typically used to describe a continuous-time dynamic system, either linear or nonlinear.

__abstractmethods__ = frozenset({'deriv', 'output'})
__annotations__ = {'_x0': 'np.ndarray'}
__init__(nstates=0, x0=None, feedthrough=False, **blockargs)[source]

Create a continuous-time block.

Parameters:
Returns:

continuous-time block base class

Return type:

ContinuousBlock

This is the parent class of all continuous-time dynamic blocks.

__module__ = 'bdsim.block'
check()[source]
Return type:

None

abstractmethod deriv(t, u, x)[source]
Return type:

ndarray

property feedthrough: bool

True if the output depends directly on the input at the same instant.

Fixed when the block is created, because it decides the block’s place in the execution order: a block with feedthrough can be part of an algebraic loop. Read-only, and not a parameter.

getstate0()[source]
Return type:

ndarray

abstractmethod output(t, u, x)[source]
Return type:

list[Any]

setstate(x)[source]
Return type:

ndarray

property x0: ndarray

Initial state vector. It can be set until the run starts.

Setter accepts:

Any

Discrete-time block

See the wiki’s Time stepping page for how Clock/TimeQ drive the scheduled-event queue that also carries animation/movie frames.

class bdsim.SampledBlock(clock, *, ndstates=None, x0=None, feedthrough=False, **blockargs)[source]

Bases: Block

A SampledBlock is a subclass of Block that represents a block with inputs, outputs and discrete states. Typically used to describe a sampled-time dynamic system, either linear or nonlinear.

__init__(clock, *, ndstates=None, x0=None, feedthrough=False, **blockargs)[source]

Create a clocked block.

param clock:

the clock that governs the block’s discrete time updates

Parameters:
Returns:

clocked block base class

Return type:

SampledBlock

This is the parent class of all sampled-time blocks.

check()[source]
Return type:

None

property feedthrough: bool

True if the output depends directly on the input at the same instant.

Fixed when the block is created, because it decides the block’s place in the execution order: a block with feedthrough can be part of an algebraic loop. Read-only, and not a parameter.

getstate0()[source]
Return type:

ndarray

setstate(x)[source]
Return type:

ndarray

property x0: ndarray

Initial state vector. It can be set until the run starts.

Setter accepts:

Any

class bdsim.Clock(arg, unit='s', offset=0, name=None)[source]

Bases: object

__init__(arg, unit='s', offset=0, name=None)[source]
add_block(block)[source]
Return type:

None

getlog(simstate=None)[source]
Return type:

tuple[list, list]

getstate(t)[source]
Return type:

ndarray[tuple[Any, ...], dtype[Any]]

getstate0()[source]
Return type:

ndarray[tuple[Any, ...], dtype[Any]]

property index: Index

Which elements of the clock’s state vector belong to which block.

Returns:

an Index of the discrete state of the blocks on this clock, in the order of its state vector

This is for the discrete state what bd.xindex is for the continuous state. The names are those a block gave its states, with snames, and otherwise the block’s name, or name[k] for the k-th of several. clock.statenames names the same elements in the form name:X_k.

next_event(simstate)[source]

Schedule the next event

Parameters:

simstate (SimulationState) – the simulation state, which holds the clock’s state and the queue of events

Return type:

None

The time of the k’th clock tick is

$t_k = k*T + t_o$

where ‘k’, the clock index, is part of the clock state within the Simstate object.

savestate(t, simstate=None, x=None)[source]
Return type:

None

setstate(simstate=None)[source]
Return type:

None

start(simstate)[source]
Return type:

None

tick_realtime(t, simstate)[source]

Handle one realtime clock tick without event-queue rescheduling.

Realtime scheduling is owned by timer backends; unlike __call__ this method does not enqueue the next event in simstate.eventq.

Return type:

None

time(k)[source]
Return type:

float

class bdsim.TimeQ[source]

Bases: object

Time-ordered queue for events.

The list comprises tuples of (time, seq, block) to reflect an event associated with the specified block at the specified time. seq is a monotonic counter used as a tie-breaker to ensure a deterministic order of events with the same time, and is generated by an internal counter.

__init__()[source]
pop(dt=0.0)[source]
Return type:

tuple[float | None, list[Any]]

pop_until(t)[source]
Return type:

list[tuple[float, Any]]

push(value)[source]
Return type:

None

Subsystem block

class bdsim.SubsystemBlock(subsystem, **blockargs)[source]

Bases: Block

A SubSystem is a subclass of Block that represents a block that has inputs and outputs but no state variables. Typically used to describe operations such as gain, summation or various mappings.

__abstractmethods__ = frozenset({})
__annotations__ = {'_source_inports': 'list[Plug | None]', '_source_outports': 'list[Plug | None]'}
__init__(subsystem, **blockargs)[source]

Create a subsystem block.

Parameters:
Returns:

subsystem block base class

Return type:

SubsystemBlock

This is the parent class of all subsystem blocks.

__module__ = 'bdsim.block'
property inports: list[Plug]

The output ports that feed the inputs of the subsystem.

Returns:

one plug per input, the block and port that drives it

Return type:

list of Plug

Like Block.inports, but the subsystem block is not part of the compiled network. Available after the diagram has been compiled.

property outports: list[Plug]

The output ports that generate the outputs of the subsystem.

Returns:

one plug per output, the block and port inside the subsystem whose value is the output. Nested subsystems are looked through.

Return type:

list of Plug

This is how the output of a subsystem is watched: watch=[pid] or watch=[pid[0]] watch the plug found here. Available after the diagram has been compiled.

Graphics block

class bdsim.GraphicsBlock(movie=None, timestamp=None, timestamp_fmt=None, watch=False, **blockargs)[source]

Bases: SinkBlock

A GraphicsBlock is a subclass of SinkBlock that represents a block that has inputs but no outputs and creates/updates a graphical display.

PLOT3D = False
TIMESTAMP = False
TIMESTAMP_FORMAT = 't={t:.3f}'
__abstractmethods__ = frozenset({})
__annotations__ = {'_fig': 'matplotlib.figure.Figure | None', '_graphics_start_in_progress_run_id': 'int | None', '_tile_subplotspec': 'Any', '_timestamp_artist': 'Any', 'ax': 'Any'}
__init__(movie=None, timestamp=None, timestamp_fmt=None, watch=False, **blockargs)[source]

Create a graphical display block.

Parameters:
  • movie (str | None) – Save animation in this file in MP4 format, defaults to None

  • timestamp (bool | None) – Overlay simulation time on rendered graphics frames; if None, use class variable TIMESTAMP

  • timestamp_fmt (str | None) – Format string used for timestamp text, defaults to TIMESTAMP_FORMAT

  • watch (bool) – add this block’s input signal(s) to the watchlist, defaults to False

  • blockargs (Any) – common Block options

Returns:

transfer function block base class

Return type:

GraphicsBlock

This is the parent class of all graphic display blocks.

__module__ = 'bdsim.graphics_block'
ax: Any
create_figure(state)[source]
Return type:

Figure

done(block=False, **kwargs)[source]
Return type:

None

property fig: Figure | None
property movie: str | None
savefig(filename=None, format='pdf', **kwargs)[source]

Save the figure as an image file

Parameters:
  • fname (str) – Name of file to save graphics to

  • **kwargs – Options passed to savefig

Return type:

None

The file format is taken from the file extension and can be jpeg, png or pdf.

start(simstate)[source]
Return type:

None

step(t, inports)[source]
Return type:

None

validate_start()[source]

Validate block initialization completed after start.

Return type:

None

property writer: Any

Block parameters

class bdsim.block.Parameter(name, when='anytime', validate=None, coerce=True, forward=None, unavailable=None)[source]

Bases: object

A parameter of a block, see add_param().

Parameters:
  • name (str) – the name, which is the __init__ argument of the block

  • when (Literal['anytime', 'setup', 'never']) – "anytime", "setup" or "never"

  • validate (Optional[Callable[[Any], Any]]) – optional check of a new value, which raises if it is not acceptable

  • coerce (bool) – check the new value against the type of the current one

  • forward (tuple[Block, str] | None) – (block, name), the parameter of another block that this one stands for, see add_param()

  • unavailable (str | None) – why the parameter cannot be used, for a block that was built without the part it belongs to

coerce
forward
name
unavailable
validate
when

Options

class bdsim.run_sim.Options(sysargs=True, **options)[source]

Bases: OptionsBase

help()[source]

Return the CLI help text as a string (empty string if not in CLI mode).

Return type:

str

print_help()[source]

Print the CLI help text to stdout.

Return type:

None

sanity(options)[source]
Return type:

dict[str, Any]

class bdsim.components.OptionsBase(readonly=None, args=None)[source]

Bases: UserDict

A struct like object for option handling

Maintains an internal dict to keep options and their values. Some of these values, names in the _priority list are read-only and cannot be changed.

Values can be read/written as attributes, or the set method can take a sequence of option=value arguments.

copy()[source]
Return type:

OptionsBase

items()[source]
Return type:

Any

sanity(options)[source]
Return type:

dict[str, Any]

set(**changes)[source]
Return type:

None

Exceptions

Centralized exception types for bdsim runtime and block APIs.

exception bdsim.exceptions.BDSimError[source]

Bases: RuntimeError

Base class for bdsim-specific runtime errors.

exception bdsim.exceptions.BlockApiError(*args, traceback=True)[source]

Bases: TypeError

Raised when a block class violates bdsim block API rules.

exception bdsim.exceptions.BlockCreationError[source]

Bases: BDSimError

Raised when block construction fails via a runtime factory.

exception bdsim.exceptions.BlockRuntimeError(*, operation, block, cause, t=None, inputs=None, state=None)[source]

Bases: RuntimeError

Raised when execution of a block callback fails at runtime.

exception bdsim.exceptions.EventProbeOutsideIntervalError(*, probe_t, t0, t1)[source]

Bases: BDSimError

Raised when solve_ivp probes events outside the active interval.

Sampled-state values are only well-defined between the last clock tick and the next scheduled boundary for the current interval.

exception bdsim.exceptions.IntegrationFailureError(*, t0, tf, status, message)[source]

Bases: BDSimError

Raised when numerical integration fails for a simulation interval.

exception bdsim.exceptions.SimulationContextError[source]

Bases: BDSimError

Raised when runtime code is called outside an active simulation context.