Reference Guide

Module pyctrl

class pyctrl.Controller(**kwargs)

Bases: pyctrl.block.container.Container

pyctrl.Controller provides functionality for running signal flow tasks.

A Controller can be in one of three states:

  1. IDLE
  2. RUNNING
  3. EXITING

Upon initialization a Controller state is set to IDLE.

Parameters:kwargs – should be left empty
Raises:pyctrl.ControllerException if any parameters are passed to py:data`**kwargs`
reset()

Stop the controller, remove all devices, sources, sinks, filters, and all signals except is_running and duty.

Objects that inherit from Controller can customize reset() by overloading the private method _reset().

get_state()

Return the current state of the Controller.

Returns:the state of the Controller
set_state(state)

Set the current state of the Controller.

Parameters:state – the state of the controller
start()

Start Controller loop.

stop()

Stop Controller loop.

join()

Wait for Controller thread to terminate.

add_device(label, device_module, device_class, **kwargs)

Add device to Container.

Parameters:
  • label (str) – the device label
  • device_module (str) – the device module
  • device_class (str) – the device class
  • enable (bool) – if the device needs to be enable and disabled when calling set_enable (default False)
  • inputs (list) – a list of input signals (default [])
  • outputs (list) – a list of output signals (default [])
  • verbose (bool) – if verbose issue warning (default False)
  • type (BlockType) – the device type; only required if BlockType.timer (default None)
  • kwargs (kwargs) – other keyword arguments to be passed to the device class initialization
add_filter(label, filter_, inputs, outputs, **kwargs)

Add filter to Container.

Parameters:
  • label (str) – the filter label
  • filter (pyctrl.block) – the filter block
  • inputs (list) – a list of input signals
  • outputs (list) – a list of output signals
  • order (int) – if positive, set execution order, otherwise add as last (default -1)
add_signal(label)

Add signal to Container.

Parameters:label (str) – the signal label
add_signals(*labels)

Add multiple signal to Container.

Parameters:labels (vargs) – the signal labels
add_sink(label, sink, inputs, **kwargs)

Add sink to Container.

Parameters:
  • label (str) – the sink label
  • sink (pyctrl.block) – the sink block
  • inputs (list) – a list of input signals
  • order (int) – if positive, set execution order, otherwise add as last (default -1)
add_source(label, source, outputs, **kwargs)

Add source to Container.

Parameters:
  • label (str) – the source label
  • source (pyctrl.block) – the source block
  • outputs (list) – a list of output signals
  • order (int) – if positive, set execution order, otherwise add as last (default -1)
add_timer(label, blk, inputs, outputs, period, repeat=True, **kwargs)

Add timer to Container.

Parameters:
  • label (str) – the timer label
  • blk (pyctrl.block) – the timer block
  • inputs (list) – a list of input signals
  • outputs (list) – a list of output signals
  • period (int) – run timer in period seconds
  • repeat (bool) – repeat if True (default True)
find_filter(value)

Return label if object value is a filter. Otherwise return None.

Returns:the filter label
Return type:str
find_sink(value)

Return label if object value is a sink. Otherwise return None.

Returns:the sink label
Return type:str
find_source(value)

Return label if object value is a source. Otherwise return None.

Returns:the source label
Return type:str
find_timer(value)

Return label if object value is a timer. Otherwise return None.

Returns:the timer label
Return type:str
get_filter(label, *keys)

Get attributes from filter. Call method pyctrl.block.Block.get().

Parameters:
  • label (str) – the filter label
  • keys (vargs) – the keys of the attributes to get
Returns:

dictionary of attributes

Return type:

dict

get_parent()

Get controlller reference.

Returns:parent
get_signal(label)

Get the value of signal.

Parameters:label (str) – the signal label
Returns:the signal value
get_signals(*labels)

Get the values of signals.

Parameters:labels (vargs) – the signal labels
Returns:the signal values
Return type:list
get_sink(label, *keys)

Get attributes from sink. Call method pyctrl.block.Block.get().

Parameters:
  • label (str) – the sink label
  • keys (vargs) – the keys of the attributes to get
Returns:

dictionary of attributes

Return type:

dict

get_source(label, *keys)

Get attributes from source. Call method pyctrl.block.Block.get().

Parameters:
  • label (str) – the source label
  • keys (vargs) – the keys of the attributes to get
Returns:

dictionary of attributes or single value

Return type:

dict or value

get_timer(label, *keys)

Get attributes from timer. Call method pyctrl.block.Block.get().

Parameters:
  • label (str) – the timer label
  • keys (vargs) – the keys of the attributes to get
Returns:

dictionary of attributes

Return type:

dict

get_type()

Get block type. type is a member of class pyctrl.block.BlockType

Returns:type
html(*keys)

Format pyctrl.block.Block in HTML.

By default uses the result of pyctrl.block.Block.get().

Parameters:keys – string or tuple of strings with property names
Raise:KeyError if key is not defined
info(*vargs, **kwargs)

Returns a string with information on the Container.

Parameters:options – can be one of signals, devices, sources, filters, sinks, timers, all, summary, or class
Returns:string with information on the Container
is_enabled()

Return enabled state.

Returns:enabled
list_filters()

List of the filters currently on Container.

Returns:a list of filter labels
Return type:list
list_signals()

List of the signals currently on Container.

Returns:a list of signal labels
Return type:list
list_sinks()

List of the sinks currently on Container.

Returns:a list of sink labels
Return type:list
list_sources()

List of the sources currently on Container.

Returns:a list of source labels
Return type:list
list_timers()

List of the timers currently on Container.

Returns:a list of timer labels
Return type:list
read()

Read from pyctrl.block.container.Container.

Returns:values
Retype:tuple
Raise:pyctrl.block.container.ContainerException if block does not support read
read_filter(label)

Read from filter. Call method method pyctrl.block.Block.read().

Parameters:label (str) – the filter label
read_source(label)

Read from source. Call method pyctrl.block.Block.read().

Parameters:label (str) – the source label
remove_filter(label)

Remove filter from Container.

Parameters:label (str) – the filter label
remove_signal(label)

Remove signal from Container.

Parameters:label (str) – the signal label to be removed
remove_sink(label)

Remove sink from Container.

Parameters:label (str) – the sink label
remove_source(label)

Remove source from Container.

Parameters:label (str) – the source label
remove_timer(label)

Remove timer from Container.

Parameters:label (str) – the timer label
set(exclude=(), **kwargs)

Set properties of pyctrl.block.Block.

Parameters:
  • exclude (tuple) – attributes to exclude (default ())
  • reset (bool) – if True calls reset()
  • enabled (bool) – set enabled attribute
  • parent (pyctrl.block.container.Container) – set parent attribute
  • kwargs (kwargs) – other keyword arguments
Raise:

pyctrl.block.BlockException if any of the kwargs is left unprocessed

set_enabled(enabled=True)

Enable Container.

set_filter(label, **kwargs)

Set filter attributes. Call method pyctrl.block.Block.set().

All attributes must be passed as key-value pairs and vary depending on the type of block.

Parameters:
  • label (str) – the filter label
  • inputs (list) – set filter input signals
  • outputs (list) – set filter output signals
  • kwargs (kwargs) – other key-value pairs of attributes
set_parent(parent)

Set controlller reference.

:param pyctrl.block.containter.Container parent: parent container

set_signal(label, value)

Set the value of signal. Call method pyctrl.block.Block.set().

Parameters:
  • label (str) – the signal label
  • value – the value to be set
set_sink(label, **kwargs)

Set sink attributes. Call method pyctrl.block.Block.set().

All attributes must be passed as key-value pairs and vary depending on the type of block.

Parameters:
  • label (str) – the sink label
  • inputs (list) – set sink input signals
  • kwargs (kwargs) – other key-value pairs of attributes
set_source(label, **kwargs)

Set source attributes. Call method pyctrl.block.Block.set().

All attributes must be passed as key-value pairs and vary depending on the type of block.

Parameters:
  • label (str) – the source label
  • outputs (list) – set source output signals
  • kwargs (kwargs) – other key-value pairs of attributes
set_timer(label, **kwargs)

Set timer attributes. Call method pyctrl.block.Block.set().

All attributes must be passed as key-value pairs and vary depending on the type of block.

Parameters:
  • label (str) – the timer label
  • inputs (list) – set timer input signals
  • outputs (list) – set timer output signals
  • kwargs (kwargs) – other key-value pairs of attributes
write(*values)

Write to pyctrl.block.container.Container.

Parameters:values (vararg) – values
Raise:pyctrl.block.container.ContainerException if block does not support write
write_filter(label, *values)

Write to filter. Call method method pyctrl.block.Block.write().

Parameters:
  • label (str) – the filter label
  • values (vargs) – the values to write to filter
write_sink(label, *values)

Write to sink. Call method pyctrl.block.Block.write().

Parameters:
  • label (str) – the sink label
  • values (vargs) – the values to write to sink

Module pyctrl.timer

class pyctrl.timer.Controller(**kwargs)

Bases: pyctrl.Controller

pyctrl.timer.Controller implements a controller with a pyctrl.block.clock.TimerClock.

The clock is enabled and disabled automatically when calling start() and stop().

Parameters:period – the clock period (default 0.01)

Module pyctrl.client

class pyctrl.client.Controller(**kwargs)

Bases: pyctrl.Controller

pyctrl.client.Controller provides a controller that can remotely interact with a server.

Parameters:
  • host – host name or id address (default: ‘localhost’)
  • port – port numer (default: 9999)

Module pyctrl.server

pyctrl.server.verbose(value=1)

Set verbose level

Parameters:value – verbose level (default = 1)
pyctrl.server.version()

Return server version

Returns:server version
Retype:str
pyctrl.server.help(key)

Return help on available commands

Parameters:key – command key
pyctrl.server.reset(**kwargs)

Reset controller

Parameters:
  • module (str) – name of the controller module (default = ‘pyctrl’)
  • pyctrl_class (str) – name of the controller class (default = ‘Controller’)
  • kwargs (kwargs) – other key-value pairs of attributes
pyctrl.server.set_controller(_controller=<class 'pyctrl.Controller'> with: 0 timer(s), 2 signal(s), 0 source(s), 0 filter(s), and 0 sink(s))

Set controller commands

Parameters:_controller – an instance of pyctrl.Controller
class pyctrl.server.Handler(request, client_address, server)

Bases: socketserver.StreamRequestHandler

Handles socket controller requests

Module pyctrl.block

This module provides the basic building blocks for implementing controllers.

class pyctrl.block.BlockType

Bases: enum.Enum

An enumeration.

exception pyctrl.block.BlockException

Bases: Exception

Exception class for blocks

exception pyctrl.block.BlockWarning

Bases: Warning

Warning class for blocks

class pyctrl.block.Source(**kwargs)

Bases: object

Base class for all source blocks.

get_type()

Get block type. type is a member of class pyctrl.block.BlockType

Returns:type
write(*values)

Write to pyctrl.block.Block.

Parameters:values (vararg) – values
Raise:pyctrl.block.BlockException if block does not support write
class pyctrl.block.Sink(**kwargs)

Bases: object

Base class for all sink blocks.

get_type()

Get block type. type is a member of class pyctrl.block.BlockType

Returns:type
read()

Read from pyctrl.block.Block.

Returns:values
Retype:tuple
Raise:pyctrl.block.BlockException if block does not support read
class pyctrl.block.Filter(**kwargs)

Bases: object

Base class for all filter blocks.

get_type()

Get block type. type is a member of class pyctrl.block.BlockType

Returns:type
class pyctrl.block.Block(**kwargs)

Bases: object

pyctrl.block.Block provides the basic functionality for all types of blocks.

pyctrl.block.Block does not take any parameters other than enable

Parameters:
  • enable (bool) – set block as enabled (default True)
  • kwargs (kwargs) – additional keyword arguments
Raise:

pyctrl.block.BlockException if any of the kwargs is left unprocessed

is_enabled()

Return enabled state.

Returns:enabled
set_enabled(enabled=True)

Set enabled state.

Parameters:enabled (bool) – True or False (default True)
set_parent(parent)

Set controlller reference.

:param pyctrl.block.containter.Container parent: parent container

get_parent()

Get controlller reference.

Returns:parent
reset()

Reset pyctrl.block.Block.

Does nothing here but allows another pyctrl.block.Block to reset itself.

set(exclude=(), **kwargs)

Set properties of pyctrl.block.Block.

Parameters:
  • exclude (tuple) – attributes to exclude (default ())
  • reset (bool) – if True calls reset()
  • enabled (bool) – set enabled attribute
  • parent (pyctrl.block.container.Container) – set parent attribute
  • kwargs (kwargs) – other keyword arguments
Raise:

pyctrl.block.BlockException if any of the kwargs is left unprocessed

get(*keys, exclude=())

Get properties of blocks. For example:

block.get('enabled')

will retrieve the value of the property enabled. Returns a tuple with key values if argument keys is a list.

Parameters:
  • keys – string or tuple of strings with property names
  • exclude (tuple) – tuple with keys never to be returned (Default ())
Raise:

KeyError if key is not defined

html(*keys)

Format pyctrl.block.Block in HTML.

By default uses the result of pyctrl.block.Block.get().

Parameters:keys – string or tuple of strings with property names
Raise:KeyError if key is not defined
read()

Read from pyctrl.block.Block.

Returns:values
Retype:tuple
Raise:pyctrl.block.BlockException if block does not support read
write(*values)

Write to pyctrl.block.Block.

Parameters:values (vararg) – values
Raise:pyctrl.block.BlockException if block does not support write
class pyctrl.block.BufferBlock(**kwargs)

Bases: pyctrl.block.Block

pyctrl.block.BufferBlock provides the basic functionality for blocks that implement pyctrl.block.Block.read and pyctrl.block.Block.write through a local buffer buffer.

A pyctrl.block.BufferBlock has the property buffer.

Writing to a pyctrl.block.BufferBlock writes to the buffer.

Reading from a pyctrl.block.BufferBlock reads from the buffer.

Multiplexing and demultiplexing options are available.

If mux is False (demux is False) then pyctrl.block.BufferBlock.read() (pyctrl.block.BufferBlock.write()) are simply copied to (from) the buffer.

If mux is True then pyctrl.block.BufferBlock.read() writes a numpy array with the contents of :py:data`*values` to buffer.

If demux is True then pyctrl.block.BufferBlock.write() splits buffer into a tuple with scalar entries.

Parameters:
  • mux (bool) – mux flag (default False)
  • demux (bool) – demux flag (default False)
get(*keys, exclude=())

Get properties of a pyctrl.block.BufferBlock.

This method excludes buffer from the list of properties.

Parameters:
  • keys – string or tuple of strings with property names
  • exclude (tuple) – tuple with keys never to be returned (Default ())
set(exclude=(), **kwargs)

Set properties of a pyctrl.block.BufferBlock.

This method excludes buffer from the list of properties.

Parameters:
  • exclude (tuple) – attributes to exclude (default ())
  • kwargs (kwargs) – other keyword arguments
write(*values)

Writes to the private buffer property.

If mux is False then *values are simply copied to the buffer.

If mux is True then *values writes a numpy array with the contents of *values to the first entry of buffer.

Parameters:values (vararg) – list of values
read()

Returns the private buffer property.

If demux is False then read returns a copy of the local buffer.

If demux is True then buffer is split into a tuple with scalar entries.

Returns:buffer
class pyctrl.block.ShortCircuit(**kwargs)

Bases: pyctrl.block.Filter, pyctrl.block.BufferBlock

pyctrl.block.ShortCircuit copies input to the output, that is

\(y = u\)

class pyctrl.block.Printer(**kwargs)

Bases: pyctrl.block.Sink, pyctrl.block.Block

pyctrl.block.Printer prints the values of its input signals.

Parameters:
  • endln (str) – end-of-line character (default ‘\n’)
  • frmt (str) – format string (default {: 12.4f})
  • sep (str) – field separator (default ‘ ‘)
  • message (str) – message to print (default None)
  • file (file) – file to print on (default sys.stdout)
set(exclude=(), **kwargs)

Set properties of pyctrl.block.Printer.

Parameters:
  • exclude (tuple) – attributes to exclude (default ())
  • endl (str) – end-of-line character
  • frmt (str) – format string
  • sep (str) – field separator
  • message (str) – message to print
  • file (file) – file to print on
  • kwargs (kwargs) – other keyword arguments
write(*values)

Write formated entries of values to file.

class pyctrl.block.Constant(**kwargs)

Bases: pyctrl.block.Source, pyctrl.block.BufferBlock

pyctrl.block.Constant outputs a constant.

Parameters:value – constant
set(exclude=(), **kwargs)

Set properties of pyctrl.block.Constant.

Parameters:
  • exclude (tuple) – attributes to exclude (default ())
  • value – value or list with values
  • kwargs (kwargs) – other keyword arguments
class pyctrl.block.Signal(**kwargs)

Bases: pyctrl.block.Source, pyctrl.block.BufferBlock

pyctrl.block.Signal outputs values corresponding to its attribute signal sequentially each time pyctrl.block.BufferBlock.read() is called.

If repeat is True, signal repeats periodically.

Parameters:
  • signalnumpy.ndarray or list with values
  • repeat (bool) – if True then signal repeats periodically
reset()

Reset pyctrl.block.Signal index back to 0.

set(exclude=(), **kwargs)

Set properties of pyctrl.block.Signal.

Parameters:
  • exclude (tuple) – attributes to exclude (default ())
  • signalnumpy.ndarray or list with values
  • repeat (bool) – if True then signal repeats periodically
  • kwargs (kwargs) – other keyword arguments
read()

Read from pyctrl.block.Signal.

If repeat is True, index becomes 0 after end of signal.

Returns:current value of signal and increments current index.
class pyctrl.block.Interp(**kwargs)

Bases: pyctrl.block.Filter, pyctrl.block.BufferBlock

pyctrl.block.Interp outputs values of a vector fp interpolated according to the vector xp each time pyctrl.block.BufferBlock.read() is called.

If repeat is True, signal repeats periodically.

Parameters:
  • xpnumpy.ndarray or list with the x-coordinates of the data points, must be increasing
  • fpnumpy.ndarray or list with the y-coordinates
  • left (float) – value to return for x < xp[0] (default is fp[0]).
  • right (float) – value to return for x > xp[-1] (default is fp[-1]).
  • period (float) – a period for the x-coordinates; parameters left and right are ignored if period is specified (default None)
reset()

Reset pyctrl.block.Interp so that the input of the next call to pyctrl.block.Signal.read() become the origin.

set(exclude=(), **kwargs)

Set properties of pyctrl.block.Interp.

Parameters:
  • exclude (tuple) – attributes to exclude (default ())
  • xpnumpy.ndarray or list with the x-coordinates of the data points, must be increasing
  • fpnumpy.ndarray or list with the y-coordinates
  • left (float) – value to return for x < xp[0]
  • right (float) – value to return for x > xp[-1]
  • period (float) – a period for the x-coordinates; parameters left and right are ignored if period is specified
  • kwargs (kwargs) – other keyword arguments
write(*values)

Writes input to the private buffer. Input is the interpolating variable.

read()

Read from pyctrl.block.Interp.

Returns:current interpolated value using numpy.iterp().
class pyctrl.block.Fade(**kwargs)

Bases: pyctrl.block.Filter, pyctrl.block.BufferBlock

pyctrl.block.FadeIn outputs values of a vector fp interpolated according to the vector xp each time pyctrl.block.BufferBlock.read() is called.

If repeat is True, signal repeats periodically.

Parameters:period (float) – a period for the x-coordinates; parameters left and right are ignored if period is specified (default None)
reset()

Reset pyctrl.block.Interp so that the input of the next call to pyctrl.block.Signal.read() become the origin.

set(exclude=(), **kwargs)

Set properties of pyctrl.block.Interp.

Parameters:
  • exclude (tuple) – attributes to exclude (default ())
  • period (float) – a period for the x-coordinates; parameters left and right are ignored if period is specified
  • kwargs (kwargs) – other keyword arguments
write(*values)

Writes input to the private buffer. First input is the interpolating variable.

read()

Read from pyctrl.block.Signal.

Returns:current interpolated value using numpy.iterp().
class pyctrl.block.Map(**kwargs)

Bases: pyctrl.block.Filter, pyctrl.block.BufferBlock

A pyctrl.block.Map block applies ‘function’ to each input and returns tuple with results.

Parameters:function – the function to be applied (default identity)
write(*values)

pyctrl.block.Map write.

Returns:tuple with the result of function applied to each input.
class pyctrl.block.Apply(**kwargs)

Bases: pyctrl.block.Filter, pyctrl.block.BufferBlock

The Block pyctrl.block.Apply applies function to all inputs and returns a tuple with the result.

Parameters:function – the function to be applied (default identity)
write(*values)

pyctrl.block.Apply write.

Returns:tuple with the result of function applied to all inputs.
class pyctrl.block.Logger(number_of_rows=12000, number_of_columns=0, **kwargs)

Bases: pyctrl.block.Sink, pyctrl.block.Block

pyctrl.block.Logger stores signals into an array.

Parameters:
  • number_of_rows (int) – number of stored rows (default 12000)
  • number_of_columns (int) – number of columns (default 0)
  • labels (list) – list with labels
  • auto_reset (bool) – auto reset flag
get(*keys, exclude=())

Get properties of pyctrl.block.Logger.

The special key log can be used to retrieve the current stored entries. It calls the method pyctrl.block.Logger.get_log().

Parameters:
  • keys – string or tuple of strings with property names
  • exclude (tuple) – tuple with keys never to be returned (Default ())
Raise:

KeyError if key is not defined

set(exclude=(), **kwargs)

Set properties of pyctrl.block.Logger.

Parameters:
  • labels (list) – list with labels
  • auto_reset (bool) – auto reset flag
  • exclude (tuple) – attributes to exclude
  • kwargs (kwargs) – other keyword arguments
Raise:

BlockException if any of the kwargs is left unprocessed

get_log()

Retrieve current entries of pyctrl.block.Logger.

If property labels is set return entries as a dictionary with keys from labels.

If property labels is None return entries in an array where each column correspond to an input. Inputs which are vectors are flattened.

Returns:dictionary or numpy array with current entries.
class pyctrl.block.Wrap(**kwargs)

Bases: pyctrl.block.Filter, pyctrl.block.BufferBlock

pyctrl.block.Wrap attempt to make a possible discontinuous angular signal into a continuous one.

Use the attribute scaling to change units. Default is radians.

Parameters:
  • turns (int) – the current number of turns
  • theta (float) – current unwraped value of the signal
  • threshold (int) – the threshold to use when deciding whether a discontinuity has been reached (Default 0.25 * scaling)
  • scaling (float) – scaling factor (default 2*pi)

Module pyctrl.block.container

This module provides the basic building blocks for implementing Containers.

class pyctrl.block.container.Input(**kwargs)

Bases: pyctrl.block.Source, pyctrl.block.BufferBlock

pyctrl.block.container.Input provides a block that connects a container input signals to local container signals .

class pyctrl.block.container.Output(**kwargs)

Bases: pyctrl.block.Sink, pyctrl.block.BufferBlock

pyctrl.block.container.Output provides a block that connects local container signals to a container output signals.

class pyctrl.block.container.Container(**kwargs)

Bases: pyctrl.block.Filter, pyctrl.block.Block

pyctrl.block.container.Container provides a block that can contain other blocks.

reset()

Reset all sources, sinks, filters, and timers.

html(*keys)

Format pyctrl.block.Block in HTML.

By default uses the result of pyctrl.block.Block.get().

Parameters:keys – string or tuple of strings with property names
Raise:KeyError if key is not defined
info(*vargs, **kwargs)

Returns a string with information on the Container.

Parameters:options – can be one of signals, devices, sources, filters, sinks, timers, all, summary, or class
Returns:string with information on the Container
add_signal(label)

Add signal to Container.

Parameters:label (str) – the signal label
add_signals(*labels)

Add multiple signal to Container.

Parameters:labels (vargs) – the signal labels
remove_signal(label)

Remove signal from Container.

Parameters:label (str) – the signal label to be removed
set_signal(label, value)

Set the value of signal. Call method pyctrl.block.Block.set().

Parameters:
  • label (str) – the signal label
  • value – the value to be set
get_signal(label)

Get the value of signal.

Parameters:label (str) – the signal label
Returns:the signal value
get_signals(*labels)

Get the values of signals.

Parameters:labels (vargs) – the signal labels
Returns:the signal values
Return type:list
list_signals()

List of the signals currently on Container.

Returns:a list of signal labels
Return type:list
add_source(label, source, outputs, **kwargs)

Add source to Container.

Parameters:
  • label (str) – the source label
  • source (pyctrl.block) – the source block
  • outputs (list) – a list of output signals
  • order (int) – if positive, set execution order, otherwise add as last (default -1)
remove_source(label)

Remove source from Container.

Parameters:label (str) – the source label
set_source(label, **kwargs)

Set source attributes. Call method pyctrl.block.Block.set().

All attributes must be passed as key-value pairs and vary depending on the type of block.

Parameters:
  • label (str) – the source label
  • outputs (list) – set source output signals
  • kwargs (kwargs) – other key-value pairs of attributes
get_source(label, *keys)

Get attributes from source. Call method pyctrl.block.Block.get().

Parameters:
  • label (str) – the source label
  • keys (vargs) – the keys of the attributes to get
Returns:

dictionary of attributes or single value

Return type:

dict or value

read_source(label)

Read from source. Call method pyctrl.block.Block.read().

Parameters:label (str) – the source label
list_sources()

List of the sources currently on Container.

Returns:a list of source labels
Return type:list
add_sink(label, sink, inputs, **kwargs)

Add sink to Container.

Parameters:
  • label (str) – the sink label
  • sink (pyctrl.block) – the sink block
  • inputs (list) – a list of input signals
  • order (int) – if positive, set execution order, otherwise add as last (default -1)
remove_sink(label)

Remove sink from Container.

Parameters:label (str) – the sink label
set_sink(label, **kwargs)

Set sink attributes. Call method pyctrl.block.Block.set().

All attributes must be passed as key-value pairs and vary depending on the type of block.

Parameters:
  • label (str) – the sink label
  • inputs (list) – set sink input signals
  • kwargs (kwargs) – other key-value pairs of attributes
get_sink(label, *keys)

Get attributes from sink. Call method pyctrl.block.Block.get().

Parameters:
  • label (str) – the sink label
  • keys (vargs) – the keys of the attributes to get
Returns:

dictionary of attributes

Return type:

dict

find_sink(value)

Return label if object value is a sink. Otherwise return None.

Returns:the sink label
Return type:str
find_filter(value)

Return label if object value is a filter. Otherwise return None.

Returns:the filter label
Return type:str
find_source(value)

Return label if object value is a source. Otherwise return None.

Returns:the source label
Return type:str
find_timer(value)

Return label if object value is a timer. Otherwise return None.

Returns:the timer label
Return type:str
write_sink(label, *values)

Write to sink. Call method pyctrl.block.Block.write().

Parameters:
  • label (str) – the sink label
  • values (vargs) – the values to write to sink
list_sinks()

List of the sinks currently on Container.

Returns:a list of sink labels
Return type:list
add_filter(label, filter_, inputs, outputs, **kwargs)

Add filter to Container.

Parameters:
  • label (str) – the filter label
  • filter (pyctrl.block) – the filter block
  • inputs (list) – a list of input signals
  • outputs (list) – a list of output signals
  • order (int) – if positive, set execution order, otherwise add as last (default -1)
remove_filter(label)

Remove filter from Container.

Parameters:label (str) – the filter label
set_filter(label, **kwargs)

Set filter attributes. Call method pyctrl.block.Block.set().

All attributes must be passed as key-value pairs and vary depending on the type of block.

Parameters:
  • label (str) – the filter label
  • inputs (list) – set filter input signals
  • outputs (list) – set filter output signals
  • kwargs (kwargs) – other key-value pairs of attributes
get_filter(label, *keys)

Get attributes from filter. Call method pyctrl.block.Block.get().

Parameters:
  • label (str) – the filter label
  • keys (vargs) – the keys of the attributes to get
Returns:

dictionary of attributes

Return type:

dict

read_filter(label)

Read from filter. Call method method pyctrl.block.Block.read().

Parameters:label (str) – the filter label
write_filter(label, *values)

Write to filter. Call method method pyctrl.block.Block.write().

Parameters:
  • label (str) – the filter label
  • values (vargs) – the values to write to filter
list_filters()

List of the filters currently on Container.

Returns:a list of filter labels
Return type:list
add_device(label, device_module, device_class, **kwargs)

Add device to Container.

Parameters:
  • label (str) – the device label
  • device_module (str) – the device module
  • device_class (str) – the device class
  • enable (bool) – if the device needs to be enable and disabled when calling set_enable (default False)
  • inputs (list) – a list of input signals (default [])
  • outputs (list) – a list of output signals (default [])
  • verbose (bool) – if verbose issue warning (default False)
  • type (BlockType) – the device type; only required if BlockType.timer (default None)
  • kwargs (kwargs) – other keyword arguments to be passed to the device class initialization
add_timer(label, blk, inputs, outputs, period, repeat=True, **kwargs)

Add timer to Container.

Parameters:
  • label (str) – the timer label
  • blk (pyctrl.block) – the timer block
  • inputs (list) – a list of input signals
  • outputs (list) – a list of output signals
  • period (int) – run timer in period seconds
  • repeat (bool) – repeat if True (default True)
remove_timer(label)

Remove timer from Container.

Parameters:label (str) – the timer label
set_timer(label, **kwargs)

Set timer attributes. Call method pyctrl.block.Block.set().

All attributes must be passed as key-value pairs and vary depending on the type of block.

Parameters:
  • label (str) – the timer label
  • inputs (list) – set timer input signals
  • outputs (list) – set timer output signals
  • kwargs (kwargs) – other key-value pairs of attributes
get_timer(label, *keys)

Get attributes from timer. Call method pyctrl.block.Block.get().

Parameters:
  • label (str) – the timer label
  • keys (vargs) – the keys of the attributes to get
Returns:

dictionary of attributes

Return type:

dict

list_timers()

List of the timers currently on Container.

Returns:a list of timer labels
Return type:list
write(*values)

Write to pyctrl.block.container.Container.

Parameters:values (vararg) – values
Raise:pyctrl.block.container.ContainerException if block does not support write
read()

Read from pyctrl.block.container.Container.

Returns:values
Retype:tuple
Raise:pyctrl.block.container.ContainerException if block does not support read
set_enabled(enabled=True)

Enable Container.

Module pyctrl.block.clock

class pyctrl.block.clock.Clock(**kwargs)

Bases: pyctrl.block.Source, pyctrl.block.Block

pyctrl.block.clock.Clock provides a basic clock that writes the current time to its output.

reset()

Reset pyctrl.block.clock.Clock by setting the origin of time to the present time and the clock count to zero.

get(*keys, exclude=())

Get properties of pyctrl.block.clock.Clock.

Available attributes are:

  1. average_period
  2. time_origin
  3. count

The elapsed time since initialization or last reset can be obtained using the method pyctrl.block.clock.Clock.read().

Parameters:
  • keys – string or tuple of strings with property names
  • exclude (tuple) – keys never to be returned (default ())
read()

Read from pyctrl.block.clock.Clock.

Returns:tuple with elapsed time since initialization or last reset
calculate_average_period()

Calculate the average period since pyctrl.block.clock.Clock was initialized or reset.

Returns:average period
Retype:float
calibrate(eps=0.01, N=100, K=20)

Calibration routine that attempts to callibrate clock by fine tuning the clock’s period.

pyctrl.block.clock.Clock must support get(‘period’) and set(period = float) must be able to accept arbitrary floats as periods.

class pyctrl.block.clock.TimerClock(**kwargs)

Bases: pyctrl.block.clock.Clock

pyctrl.block.clock.TimerClock provides a clock that reads the current time periodically.

Parameters:period (float) – period in seconds
set(exclude=(), **kwargs)

Set properties of pyctrl.block.clock.TimerClock.

Parameters:
  • exclude (tuple) – attributes to exclude
  • period (float) – clock period
  • kwargs (kwargs) – other keyword arguments
Raise:

pyctrl.block.BlockException if any of the kwargs is left unprocessed

get(*keys, exclude=())

Get properties of pyctrl.block.clock.TimerClock.

Available attributes are those from pyctrl.block.clock.Clock.get() and:

  1. period

The elapsed time since initialization or last reset can be obtained using the method pyctrl.block.clock.TimerClock.read().

Parameters:
  • keys – string or tuple of strings with property names
  • exclude (tuple) – keys never to be returned (Default ())
set_enabled(enabled=True)

Set pyctrl.block.clock.TimerClock enabled state.

Parameters:enabled (bool) – True or False (default True)
read()

Read from pyctrl.block.clock.TimerClock.

Returns:tuple with elapsed time since initialization or last reset

Module pyctrl.block.system

This module provides blocks for dynamic systems.

class pyctrl.block.system.System(**kwargs)

Bases: pyctrl.block.Filter, pyctrl.block.BufferBlock

pyctrl.block.system.System is a wrapper for a time-invariant dynamic system model.

Inputs of this block are always multiplexed.

Parameters:model – an instance of pyctrl.system.System
set(exclude=(), **kwargs)

Set properties of pyctrl.block.system.System block.

Parameters:model – an instance of pyctrl.system.System
reset()

Reset pyctrl.block.system.System block.

Calls pyctrl.system.System.set_output() for model with 0.

write(*values)

Update model and write to the private buffer.

Parameters:values (vararg) – values
class pyctrl.block.system.TimeVaryingSystem(**kwargs)

Bases: pyctrl.block.Filter, pyctrl.block.BufferBlock

pyctrl.block.system.TimeVarying is a wrapper for a time-varying dynamic system model.

The first signal must be a clock.

Parameters:model – an instance of pyctrl.system.TVSystem
set(exclude=(), **kwargs)

Set properties of pyctrl.block.system.TimeVarying block.

Parameters:model – an instance of pyctrl.system.TVSystem
reset()

Reset pyctrl.block.system.TimeVarying block.

Calls pyctrl.system.System.set_output() for model with (0,0).

write(*values)

Update model and write to the private buffer.

The first signal must be a clock.

Parameters:values (vararg) – values
class pyctrl.block.system.Gain(**kwargs)

Bases: pyctrl.block.Filter, pyctrl.block.BufferBlock

Gain multiplies input by a constant gain, that is

\(y = a u\),

where \(a\) is the gain.

Parameters:gain – multiplier (default 1)
set(exclude=(), **kwargs)

Set properties of pyctrl.block.system.Gain block.

Parameters:
  • gain – multiplier (default 1)
  • kwargs (kwargs) – other keyword arguments
write(*values)

Writes product of gain times current input to the private buffer.

Parameters:values (vararg) – values
class pyctrl.block.system.Affine(**kwargs)

Bases: pyctrl.block.system.Gain

Affine multiplies and offset input by a constant gain and offset, that is

\(y = a u + b\),

where \(a\) is the gain and \(b\) is the offset.

Parameters:
  • gain (float) – multiplier (default 1)
  • offset (float) – offset (default 0)
set(exclude=(), **kwargs)

Set properties of pyctrl.block.system.Affine block.

Parameters:
  • gain (float) – multiplier (default 1)
  • offset (float) – offset (default 0)
  • kwargs (kwargs) – other keyword arguments
write(*values)

Writes product of gain times current input plus offset to the private buffer.

Parameters:values (vararg) – values
class pyctrl.block.system.Differentiator(**kwargs)

Bases: pyctrl.block.Filter, pyctrl.block.BufferBlock

Differentiator differentiates the input, that is

\(y = {\displaystyle \frac{u_k - u_{k-1}}{t_k - t_{k-1}}} \approx \dot{u}\).

The first signal must be a clock.

write(*values)

Writes finite difference derivative to the private buffer.

The first signal must be a clock.

Parameters:values (vararg) – values
class pyctrl.block.system.Feedback(**kwargs)

Bases: pyctrl.block.Filter, pyctrl.block.BufferBlock

pyctrl.system.Feedback creates a general feedback connection for a given block, that is

\[y = G e, \quad e = \gamma u[m:] + \rho u[:m],\]

where \(G\) represents the block, \(\gamma\) and \(\rho\) are a constant gains, and \(m\) is the number of inputs and references.

For the default configuration the first \(m\) signals are measurements and the last \(m\) signals are references under standard unit negative feedback.

Parameters:
  • block – an instance of pyctrl.block.Block
  • gamma – a constant gain (default 1)
  • rho – a constant gain (default -1)
  • m – number of inputs (default 1)
reset()

Reset Feedback block.

Calls block.reset().

write(*values)

Writes feedback signal to the private buffer.

Parameters:values (vararg) – values
class pyctrl.block.system.Average(**kwargs)

Bases: pyctrl.block.Filter, pyctrl.block.BufferBlock

pyctrl.block.system.Average calculates the (weighted) average of all inputs, that is

\(y = \sum_{i = 0}^{m-1} w[i] u[i]\),

where \(w\) is a vector of weights

Parameters:weights – weights (default \(1/m\))
set(exclude=(), **kwargs)

Set properties of Sum block.

Parameters:weights – multiplier
write(*values)

Writes average of the current input to the private buffer.

Parameters:values (vararg) – list of values
Returns:tuple with scaled input
class pyctrl.block.system.Sum(**kwargs)

Bases: pyctrl.block.system.Gain

pyctrl.block.system.Sum adds all inputs and multiplies the result by a constant gain, that is

\(y = a \sum_{i = 0}^{m-1} u[m]\),

where \(a\) is the gain.

Parameters:gain (float) – multiplier (default 1)
write(*values)

Writes product of gain times the sum of the current input to the private buffer.

Parameters:values (vararg) – list of values
Returns:tuple with scaled input
class pyctrl.block.system.Subtract(**kwargs)

Bases: pyctrl.block.system.Gain

pyctrl.block.system.Subtract subtracts first input as in

\(y = a \sum_{i = 1}^{m-1} u[m] - u[0]\),

where \(a\) is the gain.

Parameters:gain (float) – multiplier (default 1)
write(*values)

Writes product of gain times the difference of the current input to the private buffer.

Parameters:values (vararg) – list of values
Returns:tuple with scaled input

Module pyctrl.block.nl

class pyctrl.block.nl.ControlledCombination(**kwargs)

Bases: pyctrl.block.Filter, pyctrl.block.BufferBlock

pyctrl.block.nl.ControlledCombination implements the combination:

\(y = \alpha \, u[1:m+1] + (1 - \alpha) \, u[m+1:], \quad \alpha = \frac{u[0]}{K}\)

where \(K\) is a gain multiplier.

Parameters:
  • gain (float) – multiplier (default 1)
  • m (int) – number of inputs to combine (default 1)
set(exclude=(), **kwargs)

Set properties of pyctrl.block.nl.ControlledCombination.

Parameters:
  • gain (float) – multiplier (default 1)
  • m (int) – number of inputs to combine (default 1)
  • kwargs (kwargs) – other keyword arguments
write(*values)

Writes combination of inputs to the private buffer.

Parameters:values (vararg) – list of values
class pyctrl.block.nl.Product(**kwargs)

Bases: pyctrl.block.Filter, pyctrl.block.BufferBlock

pyctrl.block.nl.Product implements the product:

\(y = u[:m] u[m:]\)

Parameters:m (int) – number of inputs to control (default 1)
set(exclude=(), **kwargs)

Set properties of pyctrl.block.nl.Product.

Parameters:
  • m (int) – number of inputs to combine (default 1)
  • kwargs (kwargs) – other keyword arguments
write(*values)

Writes product of inputs to the private buffer.

Parameters:values (vararg) – list of values
class pyctrl.block.nl.DeadZone(**kwargs)

Bases: pyctrl.block.Filter, pyctrl.block.BufferBlock

pyctrl.block.nl.DeadZone implements the piecewise function:

\[\begin{split}y = f_{XY}(u) = \begin{cases} a u + b, & u > X, \\ a u - b, & u < -X, \\ c u, & -X \leq u \leq X \end{cases}\end{split}\]

where

\[\begin{split}a &= \frac{100-Y}{100-X} \\ b &= 100 \frac{Y-X}{100-X} \\ c &= \frac{Y}{X}\end{split}\]

This is a generalized dead-zone nonlinearity.

The classic dead-zone nonlinearity has \(Y = 0\).

The inverse can be obtained by swapping the arguments, that is \(f_{XY}^{-1} = f^{}_{YX}\).

When \(X = 0\) then \(c\) is NaN.

Parameters:
  • X (float) – parameter \(X\) (default 1)
  • Y (float) – parameter \(Y\) (default 0)
set(exclude=(), **kwargs)

Set properties of pyctrl.block.nl.DeadZone.

Parameters:
  • X (float) – parameter \(X\)
  • Y (float) – parameter \(Y\)
  • kwargs (kwargs) – other keyword arguments
write(*values)

Writes the intput transformed by the dead-zone to the private buffer.

Parameters:values (vararg) – list of values

Module pyctrl.block.logic

This module provide logic blocks.

class pyctrl.block.logic.State

Bases: enum.IntEnum

An enumeration.

class pyctrl.block.logic.Compare(**kwargs)

Bases: pyctrl.block.Filter, pyctrl.block.BufferBlock

pyctrl.block.logic.Compare compares inputs.

Produces an output with the result of the test

\(y[:m] = (u[m:] >= u[:m] + \gamma)\)

Output is 1 if test return True and 0 otherwise.

Parameters:
  • threshold (float) – the threshold \(\gamma\) (default 0)
  • m (int) – number of inputs to test (default 1)
set(exclude=(), **kwargs)

Set properties of pyctrl.block.logic.Compare.

Parameters:
  • threshold (float) – threshold
  • m (int) – number of inputs to combine
  • kwargs (kwargs) – other keyword arguments
write(*values)

Writes result of comparison to the private buffer.

Parameters:values (vararg) – values
class pyctrl.block.logic.CompareWithHysterisis(**kwargs)

Bases: pyctrl.block.logic.Compare

pyctrl.block.logic.CompareWithHysterisis compares inputs with histerisis.

Produces an output with the result of the test

\begin{align*} y[:m] = \left\{ \begin{array}{ll} (u[m:] >= u[:m] + \gamma + \mu), & \text{if } \text{state}[:m] \\ (u[m:] >= u[:m] + \gamma - \mu), & \text{if } ! \text{state}[:m] \end{array} \right . \end{align*}

and update the state as follows:

\[\begin{split}\text{state}[:m] = \begin{cases} 1, & \text{if } \text{state} \, \& \, (u[m:] < u[:m] + \gamma + \mu) \\ 0, & \text{if } \text{state} \, \& \, (u[m:] >= u[:m] + \gamma + \mu) \\ 0, & \text{if } ! \text{state} \, \& \, (u[m:] >= u[:m] + \gamma - \mu) \\ 1, & \text{if } ! \text{state} \, \& \, (u[m:] < u[:m] + \gamma - \mu) \end{cases}\end{split}\]

Output is 1 if test return True and 0 otherwise.

Parameters:
  • threshold (float) – the threshold \(\gamma\) (default 0)
  • hysterisis (float) – the hysterisis \(\mu\) (default 0.1)
  • m (int) – number of inputs to test (default 1)
set(exclude=(), **kwargs)

Set properties of pyctrl.block.logic.CompareWithHysterisis.

Parameters:
  • threshold (float) – threshold
  • m (int) – number of inputs to combine
  • hysterisis (float) – hysterisis
  • kwargs (kwargs) – other keyword arguments
write(*values)

Writes result of comparison to the private buffer.

Parameters:values (vararg) – values
class pyctrl.block.logic.CompareAbs(**kwargs)

Bases: pyctrl.block.Filter, pyctrl.block.BufferBlock

pyctrl.block.logic.CompareAbs compares the absolute value of its inputs.

Produces an output with the result of the test

\(y[:] = (|u[:]| <= \gamma)\)

Output is 1 if test return True and 0 otherwise.

If invert is True performs the test:

\(y[:] = (|u[:]| >= \gamma)\)

Parameters:
  • threshold (float) – the threshold \(\gamma\) (default 0.5)
  • invert (bool) – whether to invert the sign of the test
set(exclude=(), **kwargs)

Set properties of pyctrl.block.logic.CompareAbs.

Parameters:
  • threshold (float) – the threshold \(\gamma\) (default 0.5)
  • invert (bool) – whether to invert the sign of the test
  • kwargs (kwargs) – other keyword arguments
write(*values)

Writes result of comparison to the private buffer.

Parameters:values (vararg) – values
class pyctrl.block.logic.CompareAbsWithHysterisis(**kwargs)

Bases: pyctrl.block.logic.CompareAbs

pyctrl.block.logic.CompareAbsWithHysterisis compares the absolute value of its inputs with Hysterisis.

Produces an output with the result of the test:

\[\begin{split}y[:m] = \begin{cases} (|u[:] - \alpha| <= \gamma - \mu), & \text{if } \text{state}[:] \\ (|u[:] - \alpha| <= \gamma + \mu), & \text{if } ! \text{state}[:] \end{cases}\end{split}\]

and update the state as follows:

\[\begin{split}\text{state}[:m] = \begin{cases} 1, & \text{if } \text{state} \, \& \, (u[:] < \gamma + \mu) \\ 0, & \text{if } \text{state} \, \& \, (u[:] >= \gamma + \mu) \\ 0, & \text{if } ! \text{state} \, \& \, (u[:] >= \gamma - \mu) \\ 1, & \text{if } ! \text{state} \, \& \, (u[:] < \gamma - \mu) \end{cases}\end{split}\]

Output is 1 if test return True and 0 otherwise.

If invert is True performs the test:

\(y[:] = (|u[:]| >= \gamma)\)

Parameters:
  • threshold (float) – the threshold \(\gamma\) (default 0.5)
  • offset (float) – the offset \(\alpha\) (default 0.0)
  • hysterisis (float) – the hysterisis \(\mu\) (default 0.1)
  • invert (bool) – whether to invert the sign of the test
set(exclude=(), **kwargs)

Set properties of pyctrl.block.logic.CompareAbsWithHisterisis.

Parameters:
  • threshold (float) – the threshold \(\gamma\) (default 0.5)
  • hysterisis (float) – the hysterisis \(\mu\) (default 0.1)
  • invert (bool) – whether to invert the sign of the test
  • kwargs (kwargs) – other keyword arguments
write(*values)

Writes result of comparison to the private buffer.

Parameters:values (vararg) – values
class pyctrl.block.logic.Trigger(**kwargs)

Bases: pyctrl.block.Filter, pyctrl.block.BufferBlock

pyctrl.block.logic.Trigger can be used to switch signals on or off.

Produces the output

\(y[:-1] = \gamma \, u[1:]\)

where \(\gamma = 1\) or \(\gamma = 0\).

The value of \(\gamma\) depends on the attribute state as follows

\[\begin{split}\gamma = \begin{cases} 1, & \text{if } \text{state} \, \& \, f(u[0]) \\ 0, & \text{if } ! \text{state} \end{cases}\end{split}\]

Once \(f(u[0])\) becomes True state is set to True and must be reset manually.

Parameters:
  • function – test function (default identity)
  • state (bool) – initial state (default State.LOW)
reset()

Reset pyctrl.block.logic.Trigger attribute state to False.

write(*values)

Writes result of trigger to the private buffer.

Parameters:values (vararg) – values
class pyctrl.block.logic.Event(**kwargs)

Bases: pyctrl.block.Sink, pyctrl.block.BufferBlock

pyctrl.block.logic.Event runs actions based on event.

Produces no output but calls pyctrl.block.logic.Event.rise_event() if

state is pyctrl.block.logic.State.LOW and \(u[m:] >= high\)

or pyctrl.block.logic.Event.fall_event() if

state is pyctrl.block.logic.State.HIGH and \(u[m:] <= low\)

Parameters:
  • low (float) – the low threshold
  • high (float) – the high threshold
set(exclude=(), **kwargs)

Set properties of pyctrl.block.logic.Event.

Parameters:
  • low (float) – low threshold
  • high (float) – high threshold
  • state – state (HIGH or LOW)
  • kwargs (kwargs) – other keyword arguments
write(*values)

Writes result of comparison to the private buffer.

Parameters:values (vararg) – values
class pyctrl.block.logic.SetBlock(**kwargs)

Bases: pyctrl.block.logic.Event

pyctrl.block.logic.SetBlock set block based on event.

set(exclude=(), **kwargs)

Set properties of pyctrl.block.logic.Event.

Parameters:
  • blocktype (pyctrl.BlockType) – block type (source, sink, filter, timer)
  • kwargs (kwargs) – other keyword arguments

Module pyctrl.block.random

class pyctrl.block.random.Uniform(**kwargs)

Bases: pyctrl.block.Source, pyctrl.block.BufferBlock

pyctrl.block.random.Uniform produces an output with random entries uniformly distributed between low and high.

pyctrl.block.random.Uniform uses numpy.random.uniform().

Parameters:
  • low (float) – lowest value (default 0)
  • high (float) – highest value (default 1)
  • m (int) – number of output (default 1)
  • seed – seed (default None)
reset()

Resets pyctrl.block.random.Uniform by reseeding generator.

set(exclude=(), **kwargs)

Set properties of pyctrl.block.random.Uniform.

Parameters:
  • low (float) – lowest value
  • high (float) – highest value
  • m (int) – number of outputs
  • seed – seed
read()

Writes random numbers to private buffer.

class pyctrl.block.random.Gaussian(**kwargs)

Bases: pyctrl.block.Source, pyctrl.block.BufferBlock

pyctrl.block.random.Gaussian produces an output with random entries normally distributed with parameters mu and sigma.

pyctrl.block.random.Gaussian uses numpy.random.normal().

Parameters:
  • mu (float) – mean (default 0)
  • sigma (float) – variance (default 1)
  • m (int) – number of outputs (default 1)
  • seed – seed (default None)
reset()

Resets pyctrl.block.random.Gaussian by reseeding generator.

set(exclude=(), **kwargs)

Set properties of pyctrl.block.random.Gaussian.

Parameters:
  • mu (float) – mean
  • sigma (float) – variance
  • m (int) – number of outputs
  • seed – seed
read()

Writes random numbers to private buffer.

Module pyctrl.rc

This module supports the hardware on the Robotics Cape running on a Beaglebone Black or a Beaglebone Blue. It also provides a controller suited for the configuration of the Educational MIP (Mobile Inverted Pendulum) kit. For installation instructions see Section Installation.

class pyctrl.rc.Controller(**kwargs)
Bases:pyctrl.Controller

pyctrl.rc.Controller initializes a controller for the Robotics Cape equiped with a clock based on the MPU9250 periodic interrupts.

Parameters:
  • period (float) – period in seconds (default 0.01)
  • kwargs – other keyword parameters

Module pyctrl.rc.encoder

class pyctrl.rc.encoder.Encoder(**kwargs)
Bases:pyctrl.block.Block

pyctrl.rc.encoder.Encoder provides an interface to the Beaglebone Black and Beaglebone Blue 3 hardware encoder counters.

Thanks to the Robotics Cape library a fourth encoder counter is available through one of the PRUs.

The attribute ratio can be used to set to the desired reading units.

Parameters:
  • ratio (float) – multiplier (default 48 * 172)
  • encoder (int) – encoder channel, 1 through 4 (default 2)
  • kwargs – other keyword parameters
reset()

Reset pyctrl.rc.encoder.Encoder.

This function writes 0 to the current encoder count register.

write(*values)

Write to Encoder.

Set encoder count register to value[0] multiplied by ratio.

Parameters:values (varag) – values
read()

Read from Encoder.

When encoder is enabled, returns the current encoder count register divided by ratio.

Module pyctrl.rc.motor

class pyctrl.rc.motor.Motor(**kwargs)
Bases:pyctrl.block.Block

pyctrl.rc.motor.Motor provides an interface to the Robotics Cape 4 hardware PWM motor channels.

With the default ratio, PWM values are from -100 to 100 but can be changed by modifying the attribute ratio.

Parameters:
  • ratio (float) – ratio factor by which PMW is divided (default 100)
  • motor (int) – motor channel, 1 through 4 (default 2)
  • kwargs – other keyword parameters
set_enabled(enabled = True)

Set enabled state.

This function writes 0 to the corresponding PWM channel when enabled is False.

Parameters:enabledTrue or False (default True)
write(*values)

Write to Motor.

When motor is enabled, sets motor PWM value[0] divided by ratio.

Parameters:values (varag) – values

Module pyctrl.rc.mpu9250

class pyctrl.rc.mpu9250.MPU9250(**kwargs)
Bases:pyctrl.block.clock.Clock

pyctrl.rc.mpu9250.MPU9250 provides an interface to the Robotics Cape MPU9250 IMU.

It inherits from pyctrl.block.clock.Clock and can be used as a clock.

Parameters:
  • accel_fsr (int) – accelerometer full scale resolution
  • gyro_fsr (int) – gyroscope full scale resolution
  • accel_dlpf (int) – acellerometer low pass cutoff filter
  • gyro_dlpf (int) – gyroscope low pass cutoff filter
  • orientation (int) – orientation
  • compass_time_constant (float) – compass time constant
  • dmp_interrupt_priority (int) – DMP interrupt priority
  • period (int) – DMP period in seconds
  • enable_magnetometer (bool) – enable magnetometer
  • enable_dmp (bool) – enable Digital Motion Processor
  • enable_fusion (bool) – enable fusion algorithm
  • show_warnings (bool) – show warnings
  • kwargs – other keyword parameters
get_data():

Return the data read by the IMU.

Returns:the IMU data
read()

Read MPU9250.

WARNING: This function does not return any IMU data, just a timestamp. Use get_data() to get IMU data.

Returns:time
class pyctrl.rc.mpu9250.Raw(**kwargs)
Bases:pyctrl.block.BufferBlock

pyctrl.rc.mpu9250.Raw reads raw accelerometer and gyroscope angular velocity from the MPU9250 IMU.

read()

Read from IMU.

When enabled, returns the current IMU linear acceleration and gyroscope angular velocities.

Returns:tuple with IMU acceleration and gyroscope angular velocities.
class pyctrl.rc.mpu9250.Inclinometer(**kwargs)
Bases:pyctrl.rc.mpu9250.Raw

pyctrl.rc.mpu9250.Inclinometer reads the output from pyctrl.rc.mpu9250.Inclinometer and returns the angle and angualar velocity with respect to the vertical.

Parameters:
  • turns (int) – current number of turns (default 0)
  • threshold (float) – used to detect that the IMU has been fliped more than 1 turn (360 degrees) (default 0.25 turns (90 deg))
read()

Read inclinometer.

When enabled, returns the current angle and angular velocity measured with respect to the vertical.

Returns:tuple with angle and angular velocity.

Module pyctrl.rc.mip

class pyctrl.rc.mip.Controller(**kwargs)
Bases:pyctrl.rc.Controller

pyctrl.rc.Controller initializes a controller to be used with the Educational MIP connected to a Robotics Cape.

The following devices are installed:

  1. Clock, clock, based on interrupts generated by the MPU9250; installed as a source; output is the clock;
  2. Inclinometer, inclinometer, based on the MPU9250 IMU; installed as a source; outputs are the signals theta and theta_dot, which correspond to the angular position and velocity of the MIP; units are cycles and cycles/s;
  3. Two encoders, encoder1, and encoder2, installed as sources; outputs are the signals encoder1 and encoder2, which correspond to relative angular displacement between the body of MIP and the axis of the left and right motors; units are cycles;
  4. Two motors, motor1, and motor2; installed as sinks; inputs are the PWM signals pwm1 and py:data:`pwm2 driving the left and right motors of the MIP; range is from -100 to 100.
Parameters:
  • period (float) – period in seconds (default 0.01)
  • kwargs – other keyword parameters

Module pyctrl.system

This module provides objects that can be used to represent time-invariant and time-varying dynamic systems.

class pyctrl.system.System

Bases: object

Base class for dynamic time-invariant systems.

set_output(yk)

Sets the internal state of the pyctrl.system.System so that a call to pyctrl.system.System.update() with uk = 0 yields yk.

Parameters:yk – scalar desired yk
shape()

Shape of a pyctrl.system.System

Returns:tuple with number of inputs, number of outputs and order
update(uk)

Time update pyctrl.system.System model.

Parameters:uk – the input uk
Returns:the output of the model
class pyctrl.system.TVSystem

Bases: pyctrl.system.System

Base class for dynamic time-varying systems.

set_output(tk, yk)

Sets the internal state of the pyctrl.system.TVSystem so that a call to pyctrl.system.System.update() with uk = 0 and tk yields yk.

Parameters:yk – scalar desired yk
shape()

Shape of a pyctrl.system.System

Returns:tuple with number of inputs, number of outputs and order
update(tk, uk)

Time update pyctrl.system.System model.

Parameters:
  • tk – the time tk
  • uk – the input uk
Returns:

the output of the model

exception pyctrl.system.SystemException

Bases: Exception

Exception class for module pyctrl.system.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

Module pyctrl.system.tf

class pyctrl.system.tf.DTTF(num=array([1]), den=array([1]), state=None)

Bases: pyctrl.system.System

pyctrl.system.DTTF implements a single-input-single-output (SISO) transfer-function.

The underlying model is of the form:

\[den[0] y_k + den[1] y_{k-1} + \cdots + den[n] y_{k-n} = num[0] uk + num[1] u_{k-1} + \cdots + num[m] u_{k-m}\]

which corresponds to the transfer-function:

\[G(z) = \frac{\sum_{i = 0}^m z^{-i} num[i]}{\sum_{i = 0}^n z^{-i} den[i]}\]

Denominator is always normalized so that \(den[0] = 1\).

Model is implementated in terms of the auxiliary variable $z$ as follows. Let

\[z_k + den[1] z_{k-1} + \cdots + den[n] z_{k-n} = u_k \]

By linearity:

\[y_k = num[0] z_k + num[1] z_{k-1} + \cdots + den[n] z_{k-n}\]
Parameters:
  • num – numpy m-dimensional 1D-vector numerator (default [1])
  • den – numpy n-dimensional 1D-vector denominator (default [1])
  • state – numpy n-dimensional 1D-vector representing vector z (default None)
set_output(yk)

Sets the internal state of the pyctrl.system.DTTF so that a call to update with uk = 0 yields yk.

It is calculated as follows. With \(u_k = 0\)

\[z_k + den[1] z_{k-1} + \cdots + den[n] z_{k-n} = 0\]

and

\[\begin{split}y_k &= num[0] z_k + num[1] z_{k-1} + \cdots + num[n] z_{k-n} \\ &= num[1] z_{k-1} + \cdots + num[n] z_{k-n} - num[0] (den[1] z_{k-1} + \cdots + den[n] z_{k-n}) \\\end{split}\]

and \(y_k =\) yk if \(num[1] \neq num[0] den[1]\) and

\[z_{k-1} = \frac{y_k - \sum_{i = 2}^{n} (num[i] - num[0] den[i]) z_{k-i}}{num[1] - num[0] den[1]}\]

TODO: if \(num[1] \neq num[0] den[1]\) then choose next nonzero coefficient.

Parameters:yk – scalar desired yk
update(uk)

Update pyctrl.system.DTTF model. Implements the recursion:

\[\begin{split}z_k + den[1] z_{k-1} + \cdots + den[n] z_{k-n} &= u_k \\ y_k &= num[0] z_k + num[1] z_{k-1} + \cdots + den[n] z_{k-n}\end{split}\]
Parameters:uk (numpy.array) – input at time k
as_DTSS()
Returns:a state-space representation (pyctrl.system.DTSS) of the pyctrl.system.DTTF.
pyctrl.system.tf.zDTTF(num, den, state=None)

pyctrl.system.zDTTF implements a single-input-single-output (SISO) transfer-function.

The underlying model is of the form corresponds to the transfer-function:

\[G(z) = \frac{\sum_{i = 0}^m z^{i} num[i]}{\sum_{i = 0}^n z^{i} den[i]}\]

This is a convinience constructor that transforms a model in the form zDTTF into a pyctrl.system.DTTF

class pyctrl.system.tf.PID(Kp, Ki=0, Kd=0, period=0, state=None)

Bases: pyctrl.system.tf.DTTF

pyctrl.system.PID implements a Proportional-Integral-Derivative (PID) controller.

A continuous-time PID implements the following function:

\[u(t) = K_p e(t) + K_i \int_0^t{e(t) \, dt} + K_d \frac{d}{dt} e(t)\]

We provice the following discrete-time version:

\[\begin{split}x_k &= x_{k-1} +\frac{T}{2} (e_k + e_{k-1}) \\ u_k &= K_p e_k + K_i x_k + \frac{K_d}{T} (e_k - e_{k-1})\end{split}\]

In terms of a transfer-function

\[X(z) = \frac{T}{2} \frac{1 + z^{-1}}{1 - z^{-1}} E(z)\]

so that

\[\begin{split}U(z) &= Kp E(z) + K_i X(z) + \frac{K_d}{T} (1 - z^{-1}) E(z) \\ &= \left ( K_p + \frac{K_i T}{2} \frac{1 + z^{-1}}{1 - z^{-1}} + \frac{K_d}{T} (1 - z^{-1}) \right) E(z) \\ &= \frac{K_p (1 - z^{-1}) + \frac{K_i T}{2} (1 + z^{-1}) + \frac{K_d}{T} (1 - z^{-1})^2}{1 - z^{-1}} E(z) \\ &= G(z) E(z)\end{split}\]

where

\[G(z) = \frac{K_p + \frac{K_i T}{2} + \frac{Kd}{T} + z^{-1} \left ( \frac{K_i T}{2} - K_p - 2 \frac{K_d}{T} \right ) + z^{-2} \left ( \frac{K_d}{T} \right ) }{1 - z^{-1}}\]

A PD controller is the special case when Ki = 0:

\[\begin{split}U(z) &= \left ( K_p + \frac{Kd}{T} (1 - z^{-1}) \right ) E(z) \\ &= \frac{K_p + + \frac{Kd}{T} - z^{-1} \frac{Kd}{T}}{1} E(z)\end{split}\]

This is a convinience constructor that returs a PID as a pyctrl.systems.DTTF.

Parameters:
  • Kp – proportional gain
  • Ki – integral gain (default = 0)
  • Kd – derivative gain (default = 0)
  • period – sampling period (default = 0)
  • state – internal state representation (default = None)
class pyctrl.system.tf.LPF(fc, period, gain=1, order=1, state=None)

Bases: pyctrl.system.tf.DTTF

pyctrl.system.LPF implements a low pass-filter based on pyctrl.system.DTTF.

The first-order filter is a discretized version os the continuous-time filter with transfer-function:

\[T(s) = \frac{K \omega_c}{s + \omega_c}, \quad \omega_c = 2 \pi f_c\]

where \(f_c\) is the cutoff frequency and \(K\) is the filter gain. The zero-order hold equivalent transfer-function is:

\[T(z) = \frac{K (1 - a)}{z - a}, \quad a = e^{-\omega_c T_s}\]

where \(T_s\) is the sampling period.

TODO: filters of order higher than 1

Parameters:
  • fc – cuttof frequency in Hz
  • Ts – sampling period in seconds
  • gain – gain (default = 1)
  • order – order (default = 1)
  • state – initial state (default = None)

Module pyctrl.system.ss

class pyctrl.system.ss.DTSS(A=array([], shape=(1, 0), dtype=float64), B=array([[0]]), C=array([], shape=(1, 0), dtype=float64), D=array([[1]]), state=None)

Bases: pyctrl.system.System

DTSS implements a discrete-time state-space model of the form:

\[\begin{split}x_{k+1} &= A x_k + B u_k \\ y_k &= C x_k + D u_k\end{split}\]
Parameters:
  • A (numpy.array) – state space matrix \(A\) (Default = [])
  • B (numpy.array) – state space matrix \(B\) (Default = [[0]])
  • C (numpy.array) – state space matrix \(C\) (Default = [])
  • D (numpy.array) – state space matrix \(D\) (Default = [[1]])
  • state (numpy.array) – initial value of the state vector
set_output(yk)

Sets the internal state of the pyctrl.system.DTSS so that a call to update with uk = 0 yields yk.

It is calculated as follows:

\[x_{k} = C^\dag y_{k}\]

where \(C^\dag\) is the pseudo-inverse of \(C\), which leads to

\[y_k &= C x_k = y_k\]

when \(u_k = 0\)

Parameters:yk (numpy.array) – desired yk
update(uk)

Update pyctrl.system.SSTF model. Calculates:

\[y_k &= C x_k + D u_k\]

then updates

\[x_{k+1} &= A x_k + B u_k\]
Parameters:uk (numpy.array) – input at time k

Module pyctrl.system.ode

class pyctrl.system.ode.ODEBase(shape, f, g=<function identity>, x0=array([0]), t0=-1, pars=())

Bases: pyctrl.system.TVSystem

pyctrl.system.ODEBase implements a general nonlinear time-varying continuous-time state-space model of the form:

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

This base class does not implement any methods.

Parameters:
  • shape (tuple) – (m,p) where m is the number of inputs and p is the number of outputs
  • f – nonlinear state function \(f\)
  • g – nonlinear state function \(g\)
  • x0 (numpy.array) – initial value of the state vector
  • t0 (float) – initial time
  • pars (vargs) – variable positional arguments to be passed to f and g
set_output(tk, yk)

Sets the internal state of the pyctrl.system.ODE so that a call to update with uk = 0 yields yk.

Solves the equation:

\[g(x_{k}) = y_{k}\]

which leads to

\[y_k &= g(x_k) = y_k\]

when \(u_k = 0\)

Parameters:yk (numpy.array) – desired yk
class pyctrl.system.ode.ODE(shape, f, g=<function identity>, x0=0, t0=-1, pars=())

Bases: pyctrl.system.ode.ODEBase

pyctrl.system.ODE implements a general nonlinear time-varying continuous-time state-space model of the form:

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

Integration is performed using scipy.integrate.ode.

Parameters:
  • shape (tuple) – (m,p) where m is the number of inputs and p is the number of outputs
  • f – nonlinear state function \(f\)
  • g – nonlinear state function \(g\)
  • x0 (numpy.array) – initial value of the state vector
  • t0 (float) – initial time
  • pars (vargs) – variable positional arguments to be passed to f and g
set_output(tk, yk)

Sets the internal state of the pyctrl.system.ODE so that a call to update with uk = 0 yields yk.

Solves the equation:

\[g(x_{k}) = y_{k}\]

which leads to

\[y_k &= g(x_k) = y_k\]

when \(u_k = 0\)

Parameters:yk (numpy.array) – desired yk
class pyctrl.system.ode.ODEINT(shape, f, g=<function identity>, x0=0, t0=-1, pars=())

Bases: pyctrl.system.ode.ODEBase

pyctrl.system.ODEINT implements a general nonlinear time-varying continuous-time state-space model of the form:

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

Integration is performed using scipy.integrate.odeint.

Parameters:
  • shape (tuple) – (m,p) where m is the number of inputs and p is the number of outputs
  • f – nonlinear state function \(f\)
  • g – nonlinear state function \(g\)
  • x0 (numpy.array) – initial value of the state vector
  • t0 (float) – initial time
  • pars (vargs) – variable positional arguments to be passed to f and g
set_output(tk, yk)

Sets the internal state of the pyctrl.system.ODE so that a call to update with uk = 0 yields yk.

Solves the equation:

\[g(x_{k}) = y_{k}\]

which leads to

\[y_k &= g(x_k) = y_k\]

when \(u_k = 0\)

Parameters:yk (numpy.array) – desired yk