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,MVTBStubsBlock diagram class. This object is the parent of all blocks and wires in the system.
- Variables:
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,
Noneuntil given one. A main diagram is namedmainwhen first compiled; a subsystem diagram’s name is the stem of its instances’ names, seeBDSim.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:
- Raises:
RuntimeError – various block diagram errors
- Returns:
Compile status
- Return type:
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:
- Return type:
Connect blocks together. The start block can be connected to one or more end blocks.
Blocks are added to the block diagram’s
blocklistif 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. Thewirelistis a list of things that will be connected later.
- dotfile(filename, shapes=None)
Write a GraphViz dot file representing the network.
- Parameters:
- Return type:
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
SUMandPRODblocks have the sign or operation of their input wires labeled.
The file can be processed using
dot:% dot -Tpng -o out.png dotfile.dot
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
shapesthat maps block class (sink, source, graphics, function, transfer) to the names of GraphViz shapes.- Seealso:
- functions(inputs=None, outputs=None, *, full=False)
The diagram as the functions \(f\) and \(g\) of a nonlinear system
- Overloads:
inputs (
list[Block|Plug|str] |None) =..., outputs (list[Block|Plug|str] |None) =..., *, full (Literal[False]) =...→tuple[SystemFunction,SystemFunction]inputs (
list[Block|Plug|str] |None) =..., outputs (list[Block|Plug|str] |None) =..., *, full (Literal[True]) →SystemFunctionsinputs (
list[Block|Plug|str] |None) =..., outputs (list[Block|Plug|str] |None) =..., *, full (bool) →tuple[SystemFunction,SystemFunction] |SystemFunctions
- 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 exceptTIMEand 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 aSystemFunctionsobject, 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 aSystemFunctionsobject iffull, which also unpacks asf, g- Raises:
NotImplementedError – the diagram has sampled (discrete-time) blocks
RuntimeError – the diagram has not been compiled
\[\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\),
TIMEsupplies \(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 inbd.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,
demandall its outputs
a port of a source block,
demand[0]that output
Source blocks that are not selected keep producing their own values.
TIMEcannot be an input, it is the argumentt. To add a signal into the middle of a diagram, which has no input there, insert aSUMblock and aCONSTANT(0)block at that point: the constant is then an input.Entry of
outputs\(y\) contains
any other block,
plantall its outputs
a port of a block,
plant[0]that output
a sink block,
scopethe 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
uindexandyindexsay 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,uandyare made of, and how long they are, ask for the full object, aslinearizedoes withfull=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 statex0,u_at(t)for the natural input at a time, anduindexandyindexfor the inputs and outputs.fandgeach evaluate the diagram, sofgis 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:
- 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 Noneshapes (
Any) – optional DOT block shape mapping (DOT output only)
- Returns:
rendered graph text
- Return type:
If
filenameis provided the rendered text is also written to it."mermaid_fenced"is identical to"mermaid"but wraps the output in a\`\`\`mermaidfenced 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 (
dotandmermaidonly)Block kind
DOT shape
Mermaid shape
source
recordrectangle
[label]stateful (continuous, sampled, or
hasstate)box3dsubroutine
[[label]]sum / prod
(default ellipse)
circle
((label))graphics / display
Mrecordasymmetric
>label]sink
Mrecordrectangle
[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
displayfunction:from IPython.display import Markdown, display display(Markdown(bd.graph(format="mermaid_fenced"))) # Render dynamically via Jupyter's built-in Mermaid engine
- Seealso:
- 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:
x (
ArrayLike|None) =..., u (ArrayLike|None) =..., t (float) =..., *, inputs (list[Block|Plug|str] |None) =..., outputs (list[Block|Plug|str] |None) =..., h (float|None) =..., scale (ArrayLike|None) =..., estimate_error (bool) =..., full (Literal[False]) =...→tuple[NDArray,NDArray,NDArray,NDArray]x (
ArrayLike|None) =..., u (ArrayLike|None) =..., t (float) =..., *, inputs (list[Block|Plug|str] |None) =..., outputs (list[Block|Plug|str] |None) =..., h (float|None) =..., scale (ArrayLike|None) =..., estimate_error (bool) =..., full (Literal[True]) →Linearizationx (
ArrayLike|None) =..., u (ArrayLike|None) =..., t (float) =..., *, inputs (list[Block|Plug|str] |None) =..., outputs (list[Block|Plug|str] |None) =..., h (float|None) =..., scale (ArrayLike|None) =..., estimate_error (bool) =..., full (bool) →tuple[NDArray,NDArray,NDArray,NDArray] |Linearization
- Parameters:
x (
ArrayLike|None) – state of the operating point, defaults to the initial state of the diagram. After a run useout.x[-1].u (
ArrayLike|None) – input of the operating point, defaults to the natural input of the sources attt (
float) – time of the operating pointinputs (
list[Block|Plug|str] |None) – the source blocks or ports that are the input, seefunctions()outputs (
list[Block|Plug|str] |None) – the blocks or ports whose signals are the output, seefunctions()h (
float|None) – step of the numerical derivative, defaults to a size chosen for each variablescale (
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 enoughfull (
bool) – return aLinearization, 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 theLinearizationiffull- 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=Truereturns 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_SSblock. 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
Kfrom theAandBand feed the state back with aStateblock,F = -K * bd.STATE(). The state of that block is in the order of the states of this method, soKapplies directly, and linearizing the closed loop gives \(A - BK\). The state of a clocked block is available fromState_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_errora warning says that the estimate is not reliable.- Seealso:
- report_lists(**kwargs)
Print a tabular report about the block diagram.
- Parameters:
kwargs (
Any) – options passed toansitable.table.ANSIMatrix.print()- Return type:
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:
fixed (
bool) – also list the parameters that are fixed when the block is created, defaults to Falsekwargs (
Any) – options passed toansitable.table.ANSIMatrix.print()
- Return type:
The first column is the name exactly as it is used by the
--setoption,block:param, and byset_param(). The columns arethe name,
block:paramthe current value, abbreviated if it is long
its type, as the signature of the value
when it can be set:
anytime,setup(before the run starts), ornever(only withfixed=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 asPID, 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--paramoption prints this table when the diagram is compiled.- Seealso:
- report_schedule(**kwargs)
Display execution schedule in tabular form
- Parameters:
kwargs (
Any) – options passed toansitable.table.ANSIMatrix.print()- Seealso:
- Return type:
- report_subsystems(**kwargs)
Print a table of the inputs and outputs of the subsystems.
- Parameters:
kwargs (
Any) – options passed toansitable.table.ANSIMatrix.print()- Return type:
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
the port, such as
pid.0[1], which is what can be watchedinoroutthe 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
the type of the signal, as the signature recorded when the diagram was compiled
- 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 Truekwargs (
Any) – options passed toansitable.table.ANSIMatrix.print()
- Raises:
ValueError –
sortbyis not “name” or “type”- Return type:
Print a table with 4 columns:
Block name, sorted in alphabetical order
The input port (if not a source block)
The block driving this port (if not a source block)
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 * xorx + 1, whose names start with_. They are listed after all the other blocks, sorted in the same way, or hidden ifimplicitis False.
- schedule_dotfile(filename)
Write a GraphViz dot file representing the execution schedule
The file can be processed using neato or dot:
% dot -Tpng -o out.png dotfile.dot
Display execution plan as a dataflow graph.
- Seealso:
- 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 byrun()asout.x, and output by aStateblock are all in this order.The names are those a block gave its states, with
snames, and otherwise the block’s name, orname[k]for thek-th of several.bd.statenamesnames the same elements in the same order, in the formname:x_k, which is also whatout.xnamesholds.
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:
objectContains 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 withfull=True. It unpacks as the two functions, which are the pair thatfunctions()returns by default:sysf = bd.functions(full=True) f, g = sysf xdot = f(x, u, t) y = g(x, u, t)
x,uandyare Numpy arrays andtis a float.fg()computes both from one propagation through the diagram, which is half the work of callingfand theng.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
NotImplementedErrornames 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 theinputsoffunctions(), so that what the sampled blocks would have output becomes part of \(u\).- Seealso:
- u_at(t=0.0)[source]
The values of the inputs at time
t, flattened.- Parameters:
t (
float) – time- Return type:
- 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.
- class bdsim.analysis.Linearization(A, B, C, D, f0, g0, x, u, t, xindex, uindex, yindex, error=None)[source]
Bases:
objectA 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
printshows the model with each matrix labelled by the names of the signals that are its rows and columns, see__str__().polesare the eigenvalues ofA.- Seealso:
- error: dict[str, NDArray] | None = None
estimated error of each of
A, B, C, D, as a dict with those keys, orNoneifestimate_errorwas not requested
- 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:
- Returns:
a
control.StateSpacewith the matricesA, B, C, Dof this model, and with the names of the states, inputs and outputs as its signal names, taken fromxindex,uindexandyindex- 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.0is the signal_gain_0.xindex,uindexandyindexkeep the names bdsim gave.python-control is an optional dependency, imported when this method is called:
pip install control, or install bdsim with thecontrolextra. 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. Usepolesfor an autonomous system like that.- Seealso:
- 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
printshows. 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:
- class bdsim.analysis.Index(entries, names=None)[source]
Bases:
objectMaps 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. AnIndexsays which elements belong to which block.index[block]orindex["name"]is thesliceof the vector holding that block’s elements, andindex.labels[i]is the(block, k)of elementi, wherekis the position within the block. Blocks with no elements have no entry.
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 Truepackages (
str|None) – colon-separated list of folders to search for blocksload (
bool) – dynamically load blocks from libraries, defaults to Truesysargs (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:
If
sysargsis True, process command line arguments and passed options. Command line arguments have precedence.Command line switch
Argument
Default
Behaviour
--graphics,+ggraphics
True
enable graphical display
--no-graphics,-ggraphics
True
disable graphical display
--animation,+aanimation
False
update graphics at each time step
--no-animation,-aanimation
False
don’t update graphics at each time step
--hold,+Hhold
True
hold graphics in done()
--no-hold,-Hhold
True
do not hold graphics in done()
--altscreen,+Aaltscreen
True
display plots on second monitor
--no-altscreen,-Aaltscreen
True
do not display plots on second monitor
--no-progressprogress
True
do not display simulation progress bar
--no-checkcheck
True
do not check block outputs and derivatives during the run (faster)
--backend BE,-b BEbackend
None
matplotlib backend
--tiles SPEC,-t SPECtiles
None
arrange figure tiles as RxC or square/wide/tall
--shape WxHshape
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-moviesmovies
None
disable automatic movie recording
--blocksblocks
False
display block list at startup
--paramparam
False
display the parameters of all blocks, as used by
--set, and their values after compiling--debug F,-d Fdebug
''debug flags: p/ropagate, s/tate, d/eriv, i/nteractive, g/raphics-diagnostics
--animation-rate Ranimation_rate
20.0
target update rate for animation/debugger, per second of simulated time (Hz)
--max-frames Nmax_frames
1000
most frames a live animation shows in one run, 0 for no limit
--simtime T[,dt],-Ssimtime
None
simulation time as T or T,dt
--dt DTdt
None
output sample interval (build solve_ivp t_eval)
--max-step DTmax_step
None
maximum solve_ivp integration step
--atol ATOLatol
None
absolute tolerance for solve_ivp
--rtol RTOLrtol
None
relative tolerance for solve_ivp
--method NAMEmethod
None
solve_ivp method (RK45, DOP853, Radau, BDF, LSODA)
--verbose,-vverbose
False
be verbose
--quiet,-qquiet
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
.npzarchive (default: bd.npz)--set P,-s Psetparam
[]override block parameter:
block:param=value--global Gsetglob
[]override global parameter:
var=valueNote
animationandgraphicsoptions are coupled. Ifgraphics=False, all graphics is suppressed. Ifgraphics=Truethen graphics are shown and the behaviour depends onanimation.animation=Falseshows graphs at the end of the simulation, whileanimation=Truewill animate the graphs during simulation.- Seealso:
- 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 aBlockDiagram.
- 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:
This object describes the connectivity of a set of blocks and wires.
A diagram is used in one of two ways, and
namemeans 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
mainwhen 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
INPORTandOUTPORTblocks, that is instantiated inside another diagram by theSUBSYSTEMblock. 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 ofgain.0,gain.1and 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, givingsubsystem.0,subsystem.1and so on. A subsystem loaded from a.bdfile uses the file name without its extension, and one imported from a module uses the variable name of the diagram. Passingname=toSUBSYSTEMoverrides 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 examplething.0/gain.0.It is an instantiation of the
BlockDiagramclass 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.GAINinvokes the constructor for theGainclass.If the block library was not loaded,
BDSim(load=False), the diagram has no factory methods and calling one, for examplebd.GAIN(2), raisesNotImplementedError. Import the block classes directly and pass the diagram asbdinstead:- Seealso:
- 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:
- done(bd, block=False)[source]
Enter the matplotlib event loop and clean up after simulation.
Called after
run()to allow interactive use of displayedSCOPEfigures. If theholdoption is set (the default), this blocks until the user closes all figure windows; otherwise it returns immediately after flushing pending GUI events.- Parameters:
- Return type:
Note
This method can be called after
run()has returned (i.e. outside the simulation context) — for example when the script callssim.run(..., block=False)and then does post-processing before handing control back to the user. In that case theholdoption is read fromsim.optionsdirectly.
- report(bd, type='summary', **kwargs)[source]
Print block diagram report
- Parameters:
- Return type:
Single method wrapper for various block diagram reports. Obeys the
-qoption to suppress all reports at runtime.
- 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 5dt (
float|None) – output sample interval; used to build at_evalgrid forsolve_ivpso results are recorded at uniform stepsmax_step (
float|None) – maximum integration step passed to solve_ivpsolver (
str) – solve_ivp method name, defaults toRK45solver_args (
dict[str,Any] |None) – extra keyword arguments forscipy.integrate.solve_ivpdebug (
str) – debug flags string (see below), defaults to''block (
bool|None) – matplotlib block-at-end behaviour, default Falsecheck (
bool|None) – check block outputs and derivatives as they are computed (output form,NaNorInf, change of signature, derivative shape), defaults to thecheckoption which is True.--no-checkturns it off, which is faster.minstepsize (
float) – minimum step length guard, default 1e-12watch (
Any) – list of signals to log (see below)threaded (
bool) – run in a worker thread (disables graphics), default Falseoptions (
Unpack[RunOptions]) – any of the options ofRunOptions, for this run only, for exampleanimation=Trueorprogress=False
- Returns:
simulation results container
- Return type:
- Raises:
TypeError – for an option that is unknown, or that can only be set when
BDSimis constructed, such asblocksorverboseRuntimeError – for a
backendthat matplotlib cannot switch to
The system is simulated from time 0 to
T.Options. The keyword arguments after
threadedare options, the same ones thatBDSimtakes and that the command line sets. Each overrides the value given toBDSimfor this run only. An option given on the command line always wins, includingdt,max_step,checkandblock, and a message says that the value from the code was ignored. The options that cannot differ from run to run, such asblocksorverbose, raiseTypeError.Warning
setparamchanges 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 secondrunwithoutsetparamuses the values the first one set.setparam={"gain:K": 3}is the same as callingset_param("K", 3)on the block namedgainbefore 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 itsidas for-s, and the values are Python objects, not text. Each change is reported, old value to new, unlessquiet. This is new and may change.Changed in version next: The options of
RunOptionscan be given torunas keyword arguments, and tosubmit, which passes them on. An option given on the command line now also wins overdt,max_step,checkandblockgiven torun, 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. Thesolverargument selects the method (e.g.RK45,DOP853,Radau,BDF,LSODA). Finer control — tolerances, first step, etc. — can be passed viasolver_args.The output
dtcontrols the time resolution of logged output. When given,solve_ivpis called with a matchingt_evalgrid so thatout.tcontains uniformly-spaced points. If omitted,solve_ivpchooses its own internal steps and all accepted points are recorded.Results are returned in a
BDStructwith attributes:t— time vector: ndarray, shape=(M,)x— continuous state matrix: ndarray, shape=(M,N)xnames— list of state names corresponding to columns ofx, e.g."plant.x0"(set via the block’ssnamesargument)clockN—BDStructfor each clock (clock0,clock1, …) with sub-attributestandxholding the discrete time history; a legacy alias using the clock’s name is also added when possibleyN— logged signal for the N-th entry inwatchynames— list of names of the watched ports, same order aswatch.stats—BDStructwith integration statistics:integration_time_points,run_interval_calls,ydot_calls,integrator_wall_time,animation_frames,events_detected_total,events_detected_by_source
The
watchargument is a list of one or more signals whose value during simulation will be recorded. Each element can be:a
Blockreference, interpreted as output port 0a
Plugreference (block with port index)a string of the form
"blockname[i]"— port i of the named block
The
debugstring 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
The command line option
--global var=valuecan be used to request the change of global variables. However, actually changing them requires explicit code support in the user’s program after theBDSimconstructor.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,checkanddebugare also options, but are named parameters ofrun(), andblockis the same setting ashold.- 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]
- 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:
UserDictA 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)
- __str__()[source]
Display struct as a string
- Returns:
struct in indented string format
- Return type:
The struct is rendered with one line per element, and substructures are indented. Keys whose names start with ‘.’ are hidden (internal metadata fields).
- 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
BDStructinstances are recursively converted to plain dicts.
- dump_npz(outfile)[source]
Write the struct to a NumPy
.npzarchive.Every entry is stored as one array, so the archive is compact, keeps full
float64precision, 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 asclock0/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).Noneand 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- __init__(banner=True, packages=None, load=True, toolboxes=True, **kwargs)[source]
- Parameters:
banner (
bool) – display docstring banner, defaults to Truepackages (
str|None) – colon-separated list of folders to search for blocksload (
bool) – dynamically load blocks from libraries, defaults to Truesysargs (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:
If
sysargsis True, process command line arguments and passed options. Command line arguments have precedence.Command line switch
Argument
Default
Behaviour
--graphics,+ggraphics
True
enable graphical display
--no-graphics,-ggraphics
True
disable graphical display
--animation,+aanimation
False
update graphics at each time step
--no-animation,-aanimation
False
don’t update graphics at each time step
--hold,+Hhold
True
hold graphics in done()
--no-hold,-Hhold
True
do not hold graphics in done()
--altscreen,+Aaltscreen
True
display plots on second monitor
--no-altscreen,-Aaltscreen
True
do not display plots on second monitor
--no-progressprogress
True
do not display simulation progress bar
--no-checkcheck
True
do not check block outputs and derivatives during the run (faster)
--backend BE,-b BEbackend
None
matplotlib backend
--tiles SPEC,-t SPECtiles
None
arrange figure tiles as RxC or square/wide/tall
--shape WxHshape
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-moviesmovies
None
disable automatic movie recording
--blocksblocks
False
display block list at startup
--paramparam
False
display the parameters of all blocks, as used by
--set, and their values after compiling--debug F,-d Fdebug
''debug flags: p/ropagate, s/tate, d/eriv, i/nteractive, g/raphics-diagnostics
--animation-rate Ranimation_rate
20.0
target update rate for animation/debugger, per second of simulated time (Hz)
--max-frames Nmax_frames
1000
most frames a live animation shows in one run, 0 for no limit
--simtime T[,dt],-Ssimtime
None
simulation time as T or T,dt
--dt DTdt
None
output sample interval (build solve_ivp t_eval)
--max-step DTmax_step
None
maximum solve_ivp integration step
--atol ATOLatol
None
absolute tolerance for solve_ivp
--rtol RTOLrtol
None
relative tolerance for solve_ivp
--method NAMEmethod
None
solve_ivp method (RK45, DOP853, Radau, BDF, LSODA)
--verbose,-vverbose
False
be verbose
--quiet,-qquiet
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
.npzarchive (default: bd.npz)--set P,-s Psetparam
[]override block parameter:
block:param=value--global Gsetglob
[]override global parameter:
var=valueNote
animationandgraphicsoptions are coupled. Ifgraphics=False, all graphics is suppressed. Ifgraphics=Truethen graphics are shown and the behaviour depends onanimation.animation=Falseshows graphs at the end of the simulation, whileanimation=Truewill animate the graphs during simulation.- Seealso:
- 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 aBlockDiagram.
- 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:
This object describes the connectivity of a set of blocks and wires.
A diagram is used in one of two ways, and
namemeans 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
mainwhen 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
INPORTandOUTPORTblocks, that is instantiated inside another diagram by theSUBSYSTEMblock. 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 ofgain.0,gain.1and 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, givingsubsystem.0,subsystem.1and so on. A subsystem loaded from a.bdfile uses the file name without its extension, and one imported from a module uses the variable name of the diagram. Passingname=toSUBSYSTEMoverrides 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 examplething.0/gain.0.It is an instantiation of the
BlockDiagramclass 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.GAINinvokes the constructor for theGainclass.If the block library was not loaded,
BDSim(load=False), the diagram has no factory methods and calling one, for examplebd.GAIN(2), raisesNotImplementedError. Import the block classes directly and pass the diagram asbdinstead:- Seealso:
- blockinfo(block=None)[source]
Return info about all blocks.
Deprecated since version Use:
block_libraryinstead.sim.blockinfo()is equivalent tosim.block_library;sim.blockinfo(name)is equivalent tosim.block_library[name].- Return type:
- 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:
- done(bd, block=False)[source]
Enter the matplotlib event loop and clean up after simulation.
Called after
run()to allow interactive use of displayedSCOPEfigures. If theholdoption is set (the default), this blocks until the user closes all figure windows; otherwise it returns immediately after flushing pending GUI events.- Parameters:
- Return type:
Note
This method can be called after
run()has returned (i.e. outside the simulation context) — for example when the script callssim.run(..., block=False)and then does post-processing before handing control back to the user. In that case theholdoption is read fromsim.optionsdirectly.
- fatal(message, retval=1)[source]
Fatal simulation error
- Parameters:
- Return type:
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:
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: -
pathto the folder holding the Python file defining the block -classname-blockname, upper case version ofclassname-urlof online documentation for the block -packagecontaining the block - doc is the docstring from the class constructor
- report(bd, type='summary', **kwargs)[source]
Print block diagram report
- Parameters:
- Return type:
Single method wrapper for various block diagram reports. Obeys the
-qoption to suppress all reports at runtime.
- 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 5dt (
float|None) – output sample interval; used to build at_evalgrid forsolve_ivpso results are recorded at uniform stepsmax_step (
float|None) – maximum integration step passed to solve_ivpsolver (
str) – solve_ivp method name, defaults toRK45solver_args (
dict[str,Any] |None) – extra keyword arguments forscipy.integrate.solve_ivpdebug (
str) – debug flags string (see below), defaults to''block (
bool|None) – matplotlib block-at-end behaviour, default Falsecheck (
bool|None) – check block outputs and derivatives as they are computed (output form,NaNorInf, change of signature, derivative shape), defaults to thecheckoption which is True.--no-checkturns it off, which is faster.minstepsize (
float) – minimum step length guard, default 1e-12watch (
Any) – list of signals to log (see below)threaded (
bool) – run in a worker thread (disables graphics), default Falseoptions (
Unpack[RunOptions]) – any of the options ofRunOptions, for this run only, for exampleanimation=Trueorprogress=False
- Returns:
simulation results container
- Return type:
- Raises:
TypeError – for an option that is unknown, or that can only be set when
BDSimis constructed, such asblocksorverboseRuntimeError – for a
backendthat matplotlib cannot switch to
The system is simulated from time 0 to
T.Options. The keyword arguments after
threadedare options, the same ones thatBDSimtakes and that the command line sets. Each overrides the value given toBDSimfor this run only. An option given on the command line always wins, includingdt,max_step,checkandblock, and a message says that the value from the code was ignored. The options that cannot differ from run to run, such asblocksorverbose, raiseTypeError.Warning
setparamchanges 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 secondrunwithoutsetparamuses the values the first one set.setparam={"gain:K": 3}is the same as callingset_param("K", 3)on the block namedgainbefore 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 itsidas for-s, and the values are Python objects, not text. Each change is reported, old value to new, unlessquiet. This is new and may change.Changed in version next: The options of
RunOptionscan be given torunas keyword arguments, and tosubmit, which passes them on. An option given on the command line now also wins overdt,max_step,checkandblockgiven torun, 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. Thesolverargument selects the method (e.g.RK45,DOP853,Radau,BDF,LSODA). Finer control — tolerances, first step, etc. — can be passed viasolver_args.The output
dtcontrols the time resolution of logged output. When given,solve_ivpis called with a matchingt_evalgrid so thatout.tcontains uniformly-spaced points. If omitted,solve_ivpchooses its own internal steps and all accepted points are recorded.Results are returned in a
BDStructwith attributes:t— time vector: ndarray, shape=(M,)x— continuous state matrix: ndarray, shape=(M,N)xnames— list of state names corresponding to columns ofx, e.g."plant.x0"(set via the block’ssnamesargument)clockN—BDStructfor each clock (clock0,clock1, …) with sub-attributestandxholding the discrete time history; a legacy alias using the clock’s name is also added when possibleyN— logged signal for the N-th entry inwatchynames— list of names of the watched ports, same order aswatch.stats—BDStructwith integration statistics:integration_time_points,run_interval_calls,ydot_calls,integrator_wall_time,animation_frames,events_detected_total,events_detected_by_source
The
watchargument is a list of one or more signals whose value during simulation will be recorded. Each element can be:a
Blockreference, interpreted as output port 0a
Plugreference (block with port index)a string of the form
"blockname[i]"— port i of the named block
The
debugstring 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 savedfilename (
str|None) – output filename without extension; defaults to the block’s nameformat (
str) – image format passed tomatplotlib.Figure.savefig, defaults to'pdf'kwargs (
Any) – additional keyword arguments forwarded to the block’ssavefigmethod
- Return type:
- savefigs(bd, format='pdf', **kwargs)[source]
Save figures from all graphics blocks in a block diagram.
Iterates over every block in bd and calls
savefigon eachGraphicsBlock, using the block’s name as the filename stem.
- set_globals(globs)[source]
Set globals as specified by command line
The command line option
--global var=valuecan be used to request the change of global variables. However, actually changing them requires explicit code support in the user’s program after theBDSimconstructor.Example:
sim.set_globals(globals())
Messages are displayed by defaulting, indicating which variables are changed, and their old and new values.
- 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 anddotto be onPATH.- Parameters:
bd (
Any) – compiled block diagram to renderkwargs (
Any) – additional keyword arguments forwarded toBlockDiagram.dotfile()
- Return type:
- submit(bd, **kwargs)[source]
- Return type:
- update_parameters(bd, values=None)[source]
Set value of parameters according to arguments to the run and the command line
- Parameters:
- Return type:
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=valueare stored as list items in
options.setparamblockcan be either:the block’s name as a string, either user assigned or bdsim assigned
the block
idas displayed by thereportmethod
paramis the name of the parameter used in the constructor. It must be a registered parameter that can be set before the run starts, seeadd_param(), and the new value must be of the same kind as the current one, seeset_param().report_params()lists the parameters and their current values.valueis the new value of the variable: an integer, a float, a matrix written1 2; 3 4, or a NumPy dtype literal such asfloat32([1, 2])oruint16(5), seebdsim.literals
- class bdsim.BDStruct(name='BDStruct2', **kwargs)[source]
Bases:
UserDictA 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]
- dump(outfile)[source]
Pickle the struct to a file.
- 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
BDStructinstances are recursively converted to plain dicts.
- dump_npz(outfile)[source]
Write the struct to a NumPy
.npzarchive.Every entry is stored as one array, so the archive is compact, keeps full
float64precision, 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 asclock0/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).Noneand 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,MVTBStubsBlock diagram class. This object is the parent of all blocks and wires in the system.
- Variables:
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,
Noneuntil given one. A main diagram is namedmainwhen first compiled; a subsystem diagram’s name is the stem of its instances’ names, seeBDSim.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:
- Raises:
RuntimeError – various block diagram errors
- Returns:
Compile status
- Return type:
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:
- Return type:
Connect blocks together. The start block can be connected to one or more end blocks.
Blocks are added to the block diagram’s
blocklistif 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. Thewirelistis a list of things that will be connected later.
- dotfile(filename, shapes=None)
Write a GraphViz dot file representing the network.
- Parameters:
- Return type:
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
SUMandPRODblocks have the sign or operation of their input wires labeled.
The file can be processed using
dot:% dot -Tpng -o out.png dotfile.dot
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
shapesthat maps block class (sink, source, graphics, function, transfer) to the names of GraphViz shapes.- Seealso:
- functions(inputs=None, outputs=None, *, full=False)
The diagram as the functions \(f\) and \(g\) of a nonlinear system
- Overloads:
inputs (
list[Block|Plug|str] |None) =..., outputs (list[Block|Plug|str] |None) =..., *, full (Literal[False]) =...→tuple[SystemFunction,SystemFunction]inputs (
list[Block|Plug|str] |None) =..., outputs (list[Block|Plug|str] |None) =..., *, full (Literal[True]) →SystemFunctionsinputs (
list[Block|Plug|str] |None) =..., outputs (list[Block|Plug|str] |None) =..., *, full (bool) →tuple[SystemFunction,SystemFunction] |SystemFunctions
- 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 exceptTIMEand 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 aSystemFunctionsobject, 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 aSystemFunctionsobject iffull, which also unpacks asf, g- Raises:
NotImplementedError – the diagram has sampled (discrete-time) blocks
RuntimeError – the diagram has not been compiled
\[\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\),
TIMEsupplies \(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 inbd.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,
demandall its outputs
a port of a source block,
demand[0]that output
Source blocks that are not selected keep producing their own values.
TIMEcannot be an input, it is the argumentt. To add a signal into the middle of a diagram, which has no input there, insert aSUMblock and aCONSTANT(0)block at that point: the constant is then an input.Entry of
outputs\(y\) contains
any other block,
plantall its outputs
a port of a block,
plant[0]that output
a sink block,
scopethe 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
uindexandyindexsay 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,uandyare made of, and how long they are, ask for the full object, aslinearizedoes withfull=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 statex0,u_at(t)for the natural input at a time, anduindexandyindexfor the inputs and outputs.fandgeach evaluate the diagram, sofgis 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:
- 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 Noneshapes (
Any) – optional DOT block shape mapping (DOT output only)
- Returns:
rendered graph text
- Return type:
If
filenameis provided the rendered text is also written to it."mermaid_fenced"is identical to"mermaid"but wraps the output in a\`\`\`mermaidfenced 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 (
dotandmermaidonly)Block kind
DOT shape
Mermaid shape
source
recordrectangle
[label]stateful (continuous, sampled, or
hasstate)box3dsubroutine
[[label]]sum / prod
(default ellipse)
circle
((label))graphics / display
Mrecordasymmetric
>label]sink
Mrecordrectangle
[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
displayfunction:from IPython.display import Markdown, display display(Markdown(bd.graph(format="mermaid_fenced"))) # Render dynamically via Jupyter's built-in Mermaid engine
- Seealso:
- 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:
x (
ArrayLike|None) =..., u (ArrayLike|None) =..., t (float) =..., *, inputs (list[Block|Plug|str] |None) =..., outputs (list[Block|Plug|str] |None) =..., h (float|None) =..., scale (ArrayLike|None) =..., estimate_error (bool) =..., full (Literal[False]) =...→tuple[NDArray,NDArray,NDArray,NDArray]x (
ArrayLike|None) =..., u (ArrayLike|None) =..., t (float) =..., *, inputs (list[Block|Plug|str] |None) =..., outputs (list[Block|Plug|str] |None) =..., h (float|None) =..., scale (ArrayLike|None) =..., estimate_error (bool) =..., full (Literal[True]) →Linearizationx (
ArrayLike|None) =..., u (ArrayLike|None) =..., t (float) =..., *, inputs (list[Block|Plug|str] |None) =..., outputs (list[Block|Plug|str] |None) =..., h (float|None) =..., scale (ArrayLike|None) =..., estimate_error (bool) =..., full (bool) →tuple[NDArray,NDArray,NDArray,NDArray] |Linearization
- Parameters:
x (
ArrayLike|None) – state of the operating point, defaults to the initial state of the diagram. After a run useout.x[-1].u (
ArrayLike|None) – input of the operating point, defaults to the natural input of the sources attt (
float) – time of the operating pointinputs (
list[Block|Plug|str] |None) – the source blocks or ports that are the input, seefunctions()outputs (
list[Block|Plug|str] |None) – the blocks or ports whose signals are the output, seefunctions()h (
float|None) – step of the numerical derivative, defaults to a size chosen for each variablescale (
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 enoughfull (
bool) – return aLinearization, 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 theLinearizationiffull- 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=Truereturns 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_SSblock. 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
Kfrom theAandBand feed the state back with aStateblock,F = -K * bd.STATE(). The state of that block is in the order of the states of this method, soKapplies directly, and linearizing the closed loop gives \(A - BK\). The state of a clocked block is available fromState_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_errora warning says that the estimate is not reliable.- Seealso:
- report_lists(**kwargs)
Print a tabular report about the block diagram.
- Parameters:
kwargs (
Any) – options passed toansitable.table.ANSIMatrix.print()- Return type:
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:
fixed (
bool) – also list the parameters that are fixed when the block is created, defaults to Falsekwargs (
Any) – options passed toansitable.table.ANSIMatrix.print()
- Return type:
The first column is the name exactly as it is used by the
--setoption,block:param, and byset_param(). The columns arethe name,
block:paramthe current value, abbreviated if it is long
its type, as the signature of the value
when it can be set:
anytime,setup(before the run starts), ornever(only withfixed=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 asPID, 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--paramoption prints this table when the diagram is compiled.- Seealso:
- report_schedule(**kwargs)
Display execution schedule in tabular form
- Parameters:
kwargs (
Any) – options passed toansitable.table.ANSIMatrix.print()- Seealso:
- Return type:
- report_subsystems(**kwargs)
Print a table of the inputs and outputs of the subsystems.
- Parameters:
kwargs (
Any) – options passed toansitable.table.ANSIMatrix.print()- Return type:
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
the port, such as
pid.0[1], which is what can be watchedinoroutthe 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
the type of the signal, as the signature recorded when the diagram was compiled
- 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 Truekwargs (
Any) – options passed toansitable.table.ANSIMatrix.print()
- Raises:
ValueError –
sortbyis not “name” or “type”- Return type:
Print a table with 4 columns:
Block name, sorted in alphabetical order
The input port (if not a source block)
The block driving this port (if not a source block)
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 * xorx + 1, whose names start with_. They are listed after all the other blocks, sorted in the same way, or hidden ifimplicitis False.
- schedule_dotfile(filename)
Write a GraphViz dot file representing the execution schedule
The file can be processed using neato or dot:
% dot -Tpng -o out.png dotfile.dot
Display execution plan as a dataflow graph.
- Seealso:
- 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 byrun()asout.x, and output by aStateblock are all in this order.The names are those a block gave its states, with
snames, and otherwise the block’s name, orname[k]for thek-th of several.bd.statenamesnames the same elements in the same order, in the formname:x_k, which is also whatout.xnamesholds.
Components
Wire
- class bdsim.Wire(start, end, name=None)[source]
Bases:
objectCreate a wire.
- Parameters:
- Returns:
A wire object
- Return type:
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.
- property fullname: str
Display wire connection details.
- Returns:
Wire name
- Return type:
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:
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.
Plug
- class bdsim.Plug(block, port=0, kind=None, *, type=None)[source]
Bases:
PortCreate a plug.
- Parameters:
- Returns:
Plug object
- Return type:
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
kindargument sets thetypeattribute, which indicates if thePlugis 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.
- __annotations__ = {'block': 'Block', 'port': 'int | slice', 'type': 'str'}
Port
Signal slot
Signal signature
- class bdsim.signature.Signature(type, shape=None, dtype=None)[source]
Bases:
objectThe type of the signal on a wire.
- Parameters:
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,floatornumpy.float64. A 1-D array of size 1 is presented by bdsim as a scalar, so it does not appear as a signature.- Seealso:
- matches(other)[source]
Is
otherthe 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,floatorcomplex, so a Pythonfloatand anumpy.float64agree but anintand afloatdo not. Any other type must be exactly the same type.- Return type:
- matches_value(value)[source]
Does
valuehave this signature? Same rule asmatches(), without making aSignaturefor the value.- Return type:
Event source and crossing detection
- class bdsim.crossing.CrossingMixin[source]
Bases:
objectMixin 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()withdeclare_crossing()and overridescrossing_event()to respond. Detectors are sized inconfigure(), whereinsigis known, and any mode kept by the block is restored inreset().A block changes mode only in
crossing_event(), which runs between solve_ivp calls. It must not change mode inderivor 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 witht_crossing (
float) – time of the crossingy_crossing (
Any) – continuous state vector of the whole diagram at the crossingstate_map (
dict[Any,Any]) – block to state map, the diagram already evaluated at the crossing; write intostate_map[self]to change this block’s statesimstate (
Any) – the run’s simulation state
- Return type:
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 tostartfunc (
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 intervaldirection (
float) –+1fires on a rising zero crossing,-1on a falling one,0on eithertag (
Any) – identifies the detector, handed back tocrossing_event()when it fires; must not beNone
- Return type:
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:
- Return type:
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.
Simulation state and jobs
- class bdsim.components.Runner[source]
Bases:
objectBase class for simulation runners (offline, realtime, etc.).
- class bdsim.components.SimulationState[source]
Bases:
objectBase 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
Clockinstance.
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]
-
Block is the superclass of all blocks in the simulation environment. It defines the common properties of all blocks:
ninthe number of input portsnoutthe number of output portsnstatesthe number of continuous-time state variablesndstatesthe number of discrete-time state variablesnamethe unique name of the blockblockclassa string indicating the block class, eg. ‘sink’, ‘source’, ‘function’, ‘transfer’, ‘subsystem’, ‘clocked’, etc.typea 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 arraysetstate(x): sets the state of the block to the given statexand returns any remaining state for the next block in the clock sequencenext(t, u, x): computes the next state of the block given the current timet, input valuesinputs, and current statexoutput(t, u, x): returns the output value of the block at output portigiven the current state and inputs. The outputs are cached and can be accessed byblock.output_value(i)deriv(t, u, x): returns the derivative of the state variables for continuous-time blocksreset(): restores the block’s own initial state, once per runconfigure(): prepares the block for a run using the signatures of its wires, once per run, afterreset()and beforestart()done(): performs any cleanup at end of the simulationadd_param(name, when=, validate=, coerce=): registers a parameter, one call per__init__argument, with when it can be set (anytime,setupornever)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 valueparameters(): the parameters that can be set, with their current valuesinfo(): displays information about the block for debugging purposes
Ports can be accessed by index, eg.
block.input_value(i)orblock.output_value(i), or by name, eg.block.inport("in1")orblock.outport("out1")if the block has named ports.input_value(i): returns the value of the input port at indexioutput_value(i): returns the value of the output port at indexiinport_name(i): returns the name of the input port at indexioutport_name(i): returns the name of the output port at indexi
- __abstractmethods__ = frozenset({})
- __add__(other)[source]
Overloaded + operator for implicit block creation.
- Parameters:
- Returns:
SUM block
- Return type:
This method is implicitly invoked by the + operator when the right operand is a
Blockand the left operand is aPlug,Blockor constant:result = X + Y result = X + Y[j] result = X + C
where
XandYare blocks andCis a Python or NumPy constant.Creates a
SUM("++") block named ``_sum.Nwhose inputs are the left and right operands. For the third case, a newCONSTANT(C)block named_const.Nis also created.Note
The inputs to the summing junction are reversed: right then left operand.
The
modeis None, regular addition
- Seealso:
- __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:
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.
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 aPlugby 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:
inputs (
Block|tuple[Block|Plug,...] |list[Block|Plug] |None) – Optional incoming connectionsinames (
list[str] |None) – Names of input ports, defaults to Noneonames (
list[str] |None) – Names of output ports, defaults to Nonesnames (
list[str] |None) – Names of states, defaults to Nonepos (
tuple[float,float] |None) – Position of block on the canvas, defaults to Nonebd (
BlockDiagram|None) – Parent block diagram, defaults to Nonekwargs (
Any) – Unused arguments
- Returns:
A Block superclass
- Return type:
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:
- Return type:
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:
This method is implicitly invoked by the * operator when the left operand is a
Blockand the right operand is aPlug,Blockor constant:result = X * Y result = X * Y[j] result = X * C
where
XandYare blocks andCis a Python or NumPy constant.Create a
PROD("**")block named_prod.Nwhose inputs are the left and right operands.For the third case, create a
GAIN(C)block named_gain.N.Note
Ccan be a scalar or ndarray.- Seealso:
- __neg__()[source]
Overloaded unary minus operator for implicit block creation.
This method is implicitly invoked by the - operator for unary minus when the operand is a
Block:result = -X
where
Xis a block.Creates a
GAIN(-1)block named_gain.Nwhose input is the operand.- Seealso:
- __pow__(p)[source]
Overloaded unary power operator for implicit block creation.
This method is implicitly invoked by the ** operator for unary power when the operand is a
Block:result = X**3
where
Xis a block.Creates a
POW(3)block named_pow.Nwhose input is the operand.- Seealso:
- __radd__(other)[source]
Overloaded + operator for implicit block creation.
- Parameters:
- Returns:
SUM block
- Return type:
This method is implicitly invoked by the + operator when the right operand is a
Blockand the left operand is aPlug,Blockor constant:result = X + Y[j] result = X[i] + Y[j] result = C + Y[j]
where
XandYare blocks andCis a Python or NumPy constant.Creates a
SUM("++") block named ``_sum.Nwhose inputs are the left and right operands. For the third case, a newCONSTANT(C)block named_const.Nis also created.Note
The inputs to the summing junction are reversed: right then left operand.
The
modeis None, regular addition
- Seealso:
- __rmul__(other)[source]
Overloaded * operator for implicit block creation.
- Parameters:
- Returns:
PROD or GAIN block
- Return type:
This method is implicitly invoked by the * operator when the right operand is a
Blockand the left operand is aPlug,Blockor constant:result = X * Y result = X[i] * Y result = C * Y
where
XandYare blocks andCis a Python or NumPy constant.For the first two cases, a
PROD("**")block named_prod.Nwhose inputs are the left and right operands.For the third case, create a
GAIN(C)block named_gain.N.Note
Ccan be a scalar or ndarray.- Seealso:
- __rshift__(right)[source]
Operator for implicit wiring.
- Parameters:
- Returns:
right- Return type:
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 offuncwill be assigned toa. To specify a different outport port onfuncwe 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 offuncwill be assigned toa.- Seealso:
Plug.__rshift__
- __rsub__(other)[source]
Overloaded - operator for implicit block creation.
- Parameters:
- Returns:
SUM block
- Return type:
This method is implicitly invoked by the - operator when the left operand is a
Blockand the right operand is aPlug,Blockor constant:result = X - Y result = X[i] - Y result = C - Y
where
XandYare blocks andCis a Python or NumPy constant.Creates a
SUM("+-")block named_sum.Nwhose inputs are the left and right operands. For the third case, a newCONSTANT(C)block named_const.Nis also created.Note
The inputs to the summing junction are reversed: right then left operand.
The
modeis None, regular addition
- Seealso:
- __rtruediv__(other)[source]
Overloaded / operator for implicit block creation.
- Parameters:
- Returns:
PROD block
- Return type:
This method is implicitly invoked by the / operator when the right operand is a
Blockand the left operand is aPlug,Blockor constant:result = X / Y result = X[i] / Y result = C / Y
where
XandYare blocks andCis a Python or NumPy constant.For the first two cases, a
PROD("*/")block named_prod.Nwhose inputs are the left and right operands. For the third case, a new CONSTANT block named_const.Nis also created.Note
Ccan be a scalar or ndarray.- Seealso:
- __setattr__(name, value)[source]
Convert a LHS block name reference to a wire.
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
xto port ‘u’ of the constant blockc.+—+ +—+ | x | ——–> u- | c | +—+ +—+
Notes:
this overloaded method handles all instances of
setattrand implements normal functionality as well, only creating a wire ifnameis a known port name.
- __setitem__(port, src)[source]
Convert a LHS block slice reference to a wire.
Used to create a wired connection by assignment, for example:
X[0] = Y
where
XandYare blocks. This method is implicitly invoked and creates a wire fromYto input port 0 ofX.Note
The square brackets on the left-hand-side is critical, and
X = Ywill simply overwrite the reference toX.
- __sub__(other)[source]
Overloaded - operator for implicit block creation.
- Parameters:
- Returns:
SUM block
- Return type:
This method is implicitly invoked by the - operator when the left operand is a
Blockand the right operand is aPlug,Blockor constant:result = X - Y result = X - Y[j] result = X - C
where
XandYare blocks andCis a Python or NumPy constant.Creates a
SUM("+-")block named_sum.Nwhose inputs are the left and right operands. For the third case, a newCONSTANT(C)block named_const.Nis also created.- Seealso:
- __truediv__(other)[source]
Overloaded / operator for implicit block creation.
- Parameters:
- Returns:
PROD or GAIN block
- Return type:
This method is implicitly invoked by the / operator when the left operand is a
Blockand the right operand is aPlug,Blockor constant:result = X / Y result = X / Y[j] result = X / C
where
XandYare blocks andCis a Python or NumPy constant.Create a
PROD("**")block named_prod.Nwhose inputs are the left and right operands.For the third case, create a
GAIN(1/C)block named_gain.N.Note
Ccan be a scalar or ndarray.- Seealso:
- 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 isgetattr(self, name), so it is a plain attribute or a Pythonpropertywhen (
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, becausestart()has used the value to build something such as an event or a figure"never": not after the block is created, for structure such asninorclock
validate (
Optional[Callable[[Any],Any]]) – a function of the new value that raisesValueErrororTypeErrorif 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 notNonethat replaces the new value, which lets a check that has to keep two parameters consistent promote them togethercoerce (
bool) – check the new value against the type of the current one, seeset_param(), defaults to True. GiveFalsefor 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 thepropertysetter orvalidatedeal with the valueforward (
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, soset_paramand 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 withI=0: the reason, which is the message if someone tries to set it
- Return type:
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 apropertyof the class: the getter finds the value and the setter applies it.- Seealso:
- property bd: BlockDiagram
- Setter accepts:
- compile()[source]
Compile the block for execution.
This method is called at compile time to initialize the attributes required for compilation.
- Seealso:
- Return type:
- configure()[source]
Prepare the block for a run, using what compile() learned about its wires.
Called once per run, after
reset()and beforestart(). This is the place to readinsigandoutsig, for example to size per-element detectors or allocate buffers. The signatures are those observed by the trial evaluation incompile(). They areNoneif the diagram was compiled withevaluate=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:
- 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 * 3orx + 1, and you can give it to a block of your own. Private blocks are listed last in reports, are left out byreport_summary(implicit=False)and are not taken to be inputs bylinearize().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.
- inport_name(i)[source]
Get the name of an input port.
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:
- inport_names(names)[source]
Set input port names (legacy method for backward compatibility).
- Return type:
- inport_value(i)[source]
Get the value applied to specified input port.
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:
- 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:
- 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:
- 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 isNoneif the port is unconnected or the wire has not yet been observed.
- property isclocked: bool
Test if block is clocked
- Returns:
True if block is clocked
- Return type:
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:
- 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=3take.
- outport_name(i)[source]
Get the name of an output port.
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:
- outport_names(names)[source]
Set output port names (legacy method for backward compatibility).
- Return type:
- outport_value(i)[source]
Get the value of an output port.
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 lengthnout. These values are set when the block’soutputmethod is evaluated.- Seealso:
- property outsig: list[Signature | None]
Signatures of the output ports.
An entry is
NoneuntilBlockDiagram.compile()has observed the wire.
- 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:
- Seealso:
- 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, sincestepitself may be called only periodically for display-refresh purposes.
- remove_param(name)[source]
Remove a registered parameter, for a subclass whose parent registers one that does not apply to it.
- 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 fromgetstate0.The values on the block’s ports are not touched.
- Return type:
- set_param(name, newvalue)[source]
Set a registered parameter of the block.
- Parameters:
- Return type:
- 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:
- source_name(port)[source]
Get the name of output port driving this input port.
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:
- 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:
- test_deriv(*inputs, t=0.0, x=None)[source]
Evaluate a block for unit testing.
- Parameters:
- Returns:
Block derivative value
- Return type:
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:
- Returns:
Block next state value
- Return type:
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:
- Returns:
Block output port values
- Return type:
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.
Source block
- class bdsim.SourceBlock(**blockargs)[source]
Bases:
BlockA 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:
This is the parent class of all source blocks.
- __module__ = 'bdsim.block'
Sink block
- class bdsim.SinkBlock(**blockargs)[source]
Bases:
BlockA 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:
This is the parent class of all sink blocks.
- __module__ = 'bdsim.block'
Function block
- class bdsim.FunctionBlock(**blockargs)[source]
Bases:
BlockA 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:
This is the parent class of all function blocks.
- __module__ = 'bdsim.block'
Continuous-time block
- class bdsim.ContinuousBlock(nstates=0, x0=None, feedthrough=False, **blockargs)[source]
Bases:
BlockA 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:
This is the parent class of all continuous-time dynamic blocks.
- __module__ = 'bdsim.block'
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:
BlockA 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:
This is the parent class of all sampled-time blocks.
- class bdsim.Clock(arg, unit='s', offset=0, name=None)[source]
Bases:
object- property index: Index
Which elements of the clock’s state vector belong to which block.
- Returns:
an
Indexof the discrete state of the blocks on this clock, in the order of its state vector
This is for the discrete state what
bd.xindexis for the continuous state. The names are those a block gave its states, withsnames, and otherwise the block’s name, orname[k]for thek-th of several.clock.statenamesnames the same elements in the formname: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:
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.
- class bdsim.TimeQ[source]
Bases:
objectTime-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.
Subsystem block
- class bdsim.SubsystemBlock(subsystem, **blockargs)[source]
Bases:
BlockA 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:
subsystem (
BlockDiagram) – the subsystem to wrapblockargs (
Any) – common Block options
- Returns:
subsystem block base class
- Return type:
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.
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:
This is how the output of a subsystem is watched:
watch=[pid]orwatch=[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:
SinkBlockA 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 Nonetimestamp (
bool|None) – Overlay simulation time on rendered graphics frames; if None, use class variableTIMESTAMPtimestamp_fmt (
str|None) – Format string used for timestamp text, defaults toTIMESTAMP_FORMATwatch (
bool) – add this block’s input signal(s) to the watchlist, defaults to Falseblockargs (
Any) – common Block options
- Returns:
transfer function block base class
- Return type:
This is the parent class of all graphic display blocks.
- __module__ = 'bdsim.graphics_block'
Block parameters
- class bdsim.block.Parameter(name, when='anytime', validate=None, coerce=True, forward=None, unavailable=None)[source]
Bases:
objectA parameter of a block, see
add_param().- Parameters:
name (
str) – the name, which is the__init__argument of the blockwhen (
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 acceptablecoerce (
bool) – check the new value against the type of the current oneforward (
tuple[Block,str] |None) –(block, name), the parameter of another block that this one stands for, seeadd_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
- validate
- when
Options
- class bdsim.run_sim.Options(sysargs=True, **options)[source]
Bases:
OptionsBase
- class bdsim.components.OptionsBase(readonly=None, args=None)[source]
Bases:
UserDictA struct like object for option handling
Maintains an internal dict to keep options and their values. Some of these values, names in the
_prioritylist are read-only and cannot be changed.Values can be read/written as attributes, or the
setmethod can take a sequence ofoption=valuearguments.
Exceptions
Centralized exception types for bdsim runtime and block APIs.
- exception bdsim.exceptions.BDSimError[source]
Bases:
RuntimeErrorBase class for bdsim-specific runtime errors.
- exception bdsim.exceptions.BlockApiError(*args, traceback=True)[source]
Bases:
TypeErrorRaised when a block class violates bdsim block API rules.
- exception bdsim.exceptions.BlockCreationError[source]
Bases:
BDSimErrorRaised when block construction fails via a runtime factory.
- exception bdsim.exceptions.BlockRuntimeError(*, operation, block, cause, t=None, inputs=None, state=None)[source]
Bases:
RuntimeErrorRaised when execution of a block callback fails at runtime.
- exception bdsim.exceptions.EventProbeOutsideIntervalError(*, probe_t, t0, t1)[source]
Bases:
BDSimErrorRaised 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:
BDSimErrorRaised when numerical integration fails for a simulation interval.
- exception bdsim.exceptions.SimulationContextError[source]
Bases:
BDSimErrorRaised when runtime code is called outside an active simulation context.