controllab package

controllab.XXSim class

XXSim

alias of controllab.xxsim.XXSimWrapper

class XXSimWrapper(*args, **kwargs)[source]

20-sim scripting interface for Python.

This is a Python wrapper for 20-sim’s XML-RPC interface.

errorlevel

The level of errors that should be raised.

class Simulator(xxsim)[source]

This dummy object makes the interface more similar to the old Octave interface and the underlying XML-RPC interface.

It does this by giving the XXSimwrapper a simulator attribute.

add_curve_to_plot(window, plot, variable, x_variable='time', label_name='', key_values=[])[source]

Add a new curve to the specified plot

Parameters:
  • window (int or str) – Name or The ID corresponding to the window to which the curve will be added.
  • plot (int or str) – Name or ID corresponding to the plot to which the curve will be added.
  • variable (str) – Path of the 20-sim variable that is plotted in the curve.
  • x_variable (str, optional) – The variable plotted on the X-axis of the curve (default: ‘time’).
  • label_name (str, optional) – The label of the curve as shown in the legend of the plot. If empty, the variable name is taken. Default is variable name.
  • key_values (structured array) –

    Structured array that contains key-value pairs. Accepted keys:

    • colorR: The red component of the RGB color that the curve should have. Valid range: 0-255. Default*: 0
    • colorG: The green component of the RGB color that the curve should have. Valid range: 0-255. Default*: 0
    • colorB: The blue component of the RGB color that the curve should have. Valid range: 0-255. Default*: 0
    • thickness: The line thickness. Valid range is 1-50.

    Note: If no color is specified, 20-sim will select the next color from its internal list.

Returns:

a unique ID corresponding to the curve that was created.

Return type:

int

Example:

>>> xxsim.add_curve_to_plot('PlotWindow','Plot','time')
0
>>> xxsim.add_curve_to_plot('PlotWindow','Plot','time','SomeTime')
1
>>> xxsim.add_curve_to_plot('PlotWindow','Plot','time','Sometime',
    [{'key':'colorB','value':'255'}])
2
add_plot_to_window(window, plot_name)[source]

For the given plotName, this method will create a plot with that name in the window specified by window. The return value is the plot ID as assigned by 20-sim.

Parameters:
  • window (str, int) – Name or ID of the plot window to which the plot should be added.
  • plot_name (str) – Name of the to be created plot.
Returns:

a unique ID corresponding to the plot that was created.

Return type:

int

Example:

>>> xxsim.add_plot_to_window('Test','Demo')
1
>>> xxsim.add_plot_to_window(1,'Demo')
2
add_plot_window(window_name)[source]
For the given name, this method will create a plotting window with that name.
The return value is the window ID as assigned by 20-sim.
Parameters:window_name (str) – Name of the to be added plot window.
Returns:a unique ID corresponding to the window that was created.
Return type:int

Example:

>>> xxsim.add_plot_window('Test')
1
clear_all_runs()[source]

Clear all simulation runs.

Shortcut for: clear_run(0)

Returns:True on success, False otherwise.
Return type:bool

Example:

>>> xxsim.clear_all_runs()
True
clear_last_run()[source]

Clear only the last simulation run.

Shortcut for: clear_run(1)

Returns:True on success, False otherwise.
Return type:bool

Example:

>>> xxsim.clear_last_run()
True
clear_previous_runs()[source]

Clear all runs except the last one.

Shortcut for: clear_run(2)

Returns:True on success, False otherwise.
Return type:bool

Example:

>>> xxsim.clear_previous_runs()
True
clear_run(action=0)[source]

Clear one or more runs.

Parameters:action (int) –

Value indicating what action to take:

  • 0 = clear all runs (also default if argument is omitted)
  • 1 = clear last run
  • 2 = clear previous runs
Returns:True on success, False otherwise.
Return type:bool

Example:

>>> xxsim.clear_run(0)
True
close()[source]

Close 20-sim (without saving changes to any opened models).

Returns:True if successful, False otherwise.
Return type:bool

Example:

>>> result = xxsim.close()
close_model(close_editor=False)[source]

Close the active 20-sim model without saving changes.

Parameters:close_editor (bool, optional) – Set to True to also close the 20-sim editor. Defaults to False which keeps the editor open. In any case this will never close the final editor window because it would close 20-sim entirely. That functionality is provided by XXSim.close()
Returns:True when closed properly, False otherwise.
Return type:bool

Example:

>>> xxsim.close_model(True)
True
connect(uri='http://localhost:5580', **kwargs)[source]

Create a connection with 20-sim using XML-RPC.

Parameters:
  • uri (str) – The URI to connect to. (default: http://localhost:5580)
  • autostart (bool) – Start an instance of the 20-sim application, if none is running. If no version is supplied, the latest version will be started. (optional, default: True)
  • version (str, optional) – Only connect if the running 20-sim instance is this version. If omitted, it will also open a scripting session against other versions of 20-sim. Combined with autostart, this version of 20-sim will be started if no 20-sim is running.
Returns:

True if successful, False otherwise.

Return type:

bool

Examples: Connect to 20-sim on the local machine:

>>> xxsim.connect('http://localhost:5580')
True

Connect to 20-sim on a remote server. Requires that the firewall of the remote server allows incoming TCP connections on port 5580.

>>> xxsim.connect('http://www.example.com:5580')
True

Try to connect to 20-sim version 4.7, when server is running on a different version:

>>> xxsim.connect('http://localhost:5580', version='4.7')
False

Try to connect to 20-sim, when no instance is running:

>>> xxsim.connect('http://localhost:5580', True)
disconnect()[source]

Disable the 20-sim script mode and close the connection.

Returns:True on success.
Return type:bool

Example:

>>> xxsim.disconnect()
errorhandler(error)

This function simplifies error handling.

Given an error, depending on the self.errorlevel of the class, the error is either re-raised, or formatted to a more human readable format and printed while execution continues.

You can set errorlevel to RAISEERRORS.NONE for human use, where no errors are raised, but the user will be informed in a sensible way.

For scripting you can use RAISERRORS.ALL to ensure that errors are raised to the calling script, the script programmer can decide how the error should be handled in each case.

Parameters:error (Exception) – The error

Example

>>> try:
...     1/0
... except ZeroDivisionError as error:
...     self.errorhandler(error)
generate_c_code(target_name, output_directory, submodel_name='', template_directory='')[source]

Generate C-Code for the active model using the specified C-code target template

Parameters:
  • target_name (str) – The name of the code generation template to use. Use get_c_code_targets() to fetch the list of available C-code targets.
  • output_directory (str) – The output directory where the generated C-Code should be generated
  • submodel_name (str, optional) – The name of the submodel for submodel code generation templates only. You should omit this parameter if you are using a ‘model’ code generation template.
  • template_directory (str, optional) – The directory where the template is located. If omitted, 20-sim will search for the template in the standard list of C-code folders.
Returns:

False on failure, on success a dict with the

following fields:

  • warnings list of warning messages.
  • result True
  • errors list of error messages.

Return type:

bool or dict

Examples

>>> result = generate_c_code(
        target_name='CFunction',
        output_directory='c:\temp\%SUBMODEL_NAME%',
        submodel_name='MySubmodel')
>>> result = generate_c_code(
        target_name='StandAloneC',
        output_directory='c:\temp\%MODEL_NAME%')
generate_matlab_code(target_name, output_directory, submodel_name='', template_directory='')[source]

Generate Matlab/Simulink code for the active model using the specified Matlab or Simulink M-code target template

Parameters:
  • target_name (str) – The name of the code generation template to use. Use get_matlab_code_targets() to fetch the list of available Matlab-code targets.
  • output_directory (str) – The output directory where the generated Matlab code should be generated.
  • submodel_name (str, optional) – For submodel code generation templates only: the name of the submodel. You should omit this parameter if you are using a ‘model’ code generation template.
  • template_directory (str, optional) – The directory where the template is located. If omitted, 20-sim will search for the template in the standard list of M-code folders.
Returns:

False on failure, on success a dict with the

following fields:

  • warnings list of warning messages.
  • result True
  • errors list of error messages.

Return type:

bool or dict

Examples

>>> result = generate_matlab_code(
        target_name='Matlab',
        output_directory='c:\\temp\\%SUBMODEL_NAME%',
        submodel_name='MySubmodel')
>>> result = generate_matlab_code(
        target_name='StandAloneSimulink',
        output_directory='c:\\temp\\%MODEL_NAME%')
get_active_model()[source]

Return the name and unique identifier of the model that is active in 20-sim.

Returns:The information on the active model.
Return type:xxsim.ModelInfo

Example: >>> xxsim.get_active_model() ModelInfo(name=’C:\temp\my_model.emx’, identifier=2)

get_c_code_targets()[source]

Retrieve a list of C-code targets

Returns:List of CodeTarget objects, one for each available target. False in case of a failure
Return type:list

Example:

>>> xxsim.get_c_code_targets()
[CodeTarget(name='20simDLL', submodelselection=True),
CodeTarget(name='Arduino', submodelselection=True),
CodeTarget(name='CFunction', submodelselection=True),
CodeTarget(name='CppClass', submodelselection=True),
CodeTarget(name='Simulink', submodelselection=True),
CodeTarget(name='StandAloneC', submodelselection=False)]
get_curves_from_plot(window, plot)[source]
Returns an array of structs that each represent a curve in the specified plot.
These structs have the curve path and variable ID of each specific variable.
Parameters:
  • window (int or str) – Name or ID from the plot window where the curve is added to.
  • plot (int or str) – Name or ID from the plot where the curve is added to.
Returns:

list with all curves in the specified plot window with the following fields:

  • curveID: int the ID of the curve.
  • xPath: str the path of the 20-sim variable on the X-axis.
  • yPath: str the path of the 20-sim variable on the Y-axis.
  • zPath: str the path of the 20-sim variable on the Z-axis.
  • isHidden: bool boolean that indicates if the curve is hidden.

Return type:

list of dict

get_implementations(submodel_name)[source]

Returns the implementations of a particular submodel

Parameters:name (string) – the hierarchical name of the submodel for the implementations that should be requested
Returns:
Dictionary with:
  • activeImplementation
  • list of all implementation names.
Return type:dict

Example:

>>> implementations = xxsim.get_implementations('Submodel1')
>>> implementations['activeImplementations']
get_initial_values(variables=None)[source]

Get the initial values of the given variables.

This is just a shorthand for the equivalent call to get_variables)

Parameters:variables (list, optional) – List of variable names (str). If no variables are passed, all variables are retrieved. When getting a single variable, this value can be passed as a string.
Returns:
The output is a list of initial value dicts with the following
fields:
  • name: the name of the retrieved parameter(s)
  • size: the size of the parameter(s)
  • values: the values of the retrieved parameter(s)
  • properties: the properties of the parameter(s)

This function will return False in case of a failure

Return type:list

Examples

>>> xxsim.get_initial_values('PID.pdstate_initial')
[{'name': 'PID.pdstate_initial',
  'values': [0.0],
  'size': [1],
  'properties': [{'key': 'initialValue', 'value': 'true'},
   {'key': 'arithmetictype', 'value': 'real'},
   {'key': 'quantity', 'value': ''},
   {'key': 'unit', 'value': ''},
   {'key': 'unitSymbol', 'value': ''}]}]

The following are equivalent:

>>> xxsim.get_initial_values(['PID.pdstate_initial'])
>>> xxsim.get_variables(['PID.pdstate_initial'],['initialValue'])
get_log_values(variables=None)[source]

Fetch the values which are logged during a simulation run of the active model.

Parameters:variables (list) – List of strings with the names of the logged variables to fetch. If empty, values of all logged variables are fetched. For a single variable name, a string can be given. (default: [])
Returns:
A list of dictionaries, one for each requested logged
variable, with keys the name of the variable and its values.
Return type:list
get_matlab_code_targets()[source]

Retrieve a list of Matlab code targets

Returns:list of CodeTarget objects, one for each available target. False in case of a failure.
Return type:list

Example:

>>> xxsim.get_matlab_code_targets()
[CodeTarget(name='Matlab', submodelselection=True),
CodeTarget(name='StandAloneMatlab', submodelselection=False),
CodeTarget(name='Simulink', submodelselection=True),
CodeTarget(name='StandAloneSimulink', submodelselection=False)]
get_memory_usage()[source]

Retrieve the memory usage of 20-sim and the available system memory

Returns:
resource usage dictionary
with the following fields:
  • success bool is True on a successful call
  • USERObjects int the number of USER objects
  • GDIObjects int the number of GDI objects
  • WorkingSetMemory float the current memory usage
    in megabytes (MB)
  • PeakWorkingSetMemory float the peak memory usage
    in megabytes (MB)
  • AvailablePhysicalMemory float the available physical
    memory on the system
Return type:dict

Example:

>>> xxsim.get_memory_usage()
{'WorkingSetMemory': 95.7109375,
 'PeakWorkingSetMemory': 109.328125,
 'GDIObjects': 781,
 'AvailablePhysicalMemory': 4251.203125,
 'success': True,
 'USERObjects': 71}
get_models()[source]

Return information on all the models that are open in 20-sim.

Returns:
A list of ModelInfo objects, one per model, containing the
following fields:
  • name str: the file name of the model
  • identifier int: the identifier for this model in the
    current 20-sim session.

False is returned on a failure.

Return type:list

Example:

>>> xxsim.get_models()
[ModelInfo(name='C:\temp\my_model.emx', identifier=2),
 ModelInfo(name='C:\temp\another_model.emx', identifier=3)]
get_parameters(submodel_names=None)[source]

Returns a list with the specified parameters

Parameters:submodel_names (str -or- list) – (optional) A single name of a parameter, a list with parameter names or a list with submodel names. All parameter names should contain the full hierarchy e.g PID.Kp. When passing a submodel name, all parameters of this submodel will be returned. When this argument is omitted, this function will return all parameters of the active model.
Returns:
list with a variables dict
(when retrieving more than one parameter)

False is returned on a failure

Return type:list or None

Examples

To retrieve a list of parameters found in the submodels PID and Amplifier, you can use:

>>> params = xxsim.get_parameters(['PID','Amplifier'])

The output is a list of parameter dicts with the following fields:

  • name: the name of the retrieved parameter(s)
  • size: the size of the parameter(s)
  • values: the values of the retrieved parameter(s)
  • properties: the properties of the parameter(s)

To retrieve a single of parameter you can use

>>> xxsim.get_parameters('PID.kp')
[{'name': 'PID.kp',
'size': [1],
'values': [1.0],
'properties': [{'key': 'parameter', 'value': 'true'},
 {'key': 'arithmetictype', 'value': 'real'},
 {'key': 'quantity', 'value': 'Magnitude'},
 {'key': 'unit', 'value': 'none'},
 {'key': 'unitSymbol', 'value': ''},
 {'key': 'description', 'value': 'Proportional gain'}]}]
get_parameters_with_properties(submodel_names=None)[source]

Identical to get_parameters, but the data from 20-sim is returned as a list of namedtuple ValueWithProperties

Parameters:submodel_names (str -or- list) – (optional) A single name of a parameter, a list with parameter names or a list with submodel names. All parameter names should contain the full hierarchy e.g PID.Kp. When passing a submodel name, all parameters of this submodel will be returned. When this argument is omitted, this function will return all parameters of the active model.
Returns:list with ValueWithProperties namedtuple
Return type:list or None

Examples

To retrieve a list of parameters found in the submodels PID and Amplifier, you can use:

>>> params = xxsim.get_parameters(['PID','Amplifier'])

The output is a list of ValueWithPropertie namedtuples with the following fields:

  • name: the name of the retrieved parameter
  • value: the value(s) of the retrieved parameter
  • unit: the unit of the parameter (e.g. ‘meter’)
  • quantity: the quantity of the parameter (e.g ‘Length’)
  • unitSymbol: the unit symbol (e.g. ‘m’)
  • arithmetictype: the parameter type (e.g. ‘real’)
  • description: the description of the parameter

To retrieve a single of parameter you can use:

>>> xxsim.get_parameters('PID.kp')
[ValueWithProperties(name='PID.kp',
                     value=0.2,
                     unit='none',
                     quantity='Magnitude',
                     unitSymbol='',
                     arithmetictype='real',
                     description='Proportional gain')]
get_plot_id_from_name(window_name, plot_name)[source]

Find the corresponding plot ID for a certain window and plot name.

Parameters:
  • window_name (str -or- int) – The name of the plot window (str, case sensitive) or the plot window id (int)
  • plot_name (str) – The name of the plot (case sensitive)
Returns:

The ID of the plot (when an ID is specified as plot_name, then it returns this

ID). The return value is -1 if the plot does not exist.

Return type:

int

Example:

>>> xxsim.get_plot_id_from_name('Crank Rod - Plots', 'omega')
10
get_plot_window_id_from_name(window_name)[source]

Find the corresponding window ID for a certain window name.

Parameters:window_name (str, int) – The name of the plot window (case sensitive) or its ID.
Returns:
The ID of the window (when an ID is specified as window_name, then it returns this
ID). The return value is -1 if the window does not exist.
Return type:int

Example:

>>> xxsim.get_plot_window_id_from_name('3D Animation')
2
>>> xxsim.get_plot_window_id_from_name(2)
2
get_plot_windows()[source]
Get all currently available plot windows that are present in the
simulator by both name and ID.
Returns:
list with all plot windows for the current model
with the following fields:
  • windowName str the name of the plot window
  • windowID int the corresponding plot identifier
Return type:list of dict

Example:

>>> xxsim.get_plot_windows()
[{'windowName': 'Crank Rod - Plots', 'windowID': 1},
 {'windowName': '3D Animation', 'windowID': 2},
 {'windowName': 'Window 3', 'windowID': 3}]
get_plots()[source]

Get all plots in all plot windows that are present in the simulator.

Returns:
list with all plots for the current model
with the following fields:
  • windowName str the name of the plot window
  • windowID int the corresponding plot identifier
  • plotName str the name of the plot
  • plotID int the id of the plot
Return type:list of dict

Example:

>>> xxsim.get_plots()
[{'windowName': 'Crank Rod - Plots',
    'plotName': '3D Animation','windowID': 1,'plotID': 6},
 {'windowName': 'Crank Rod - Plots',
     'plotName': 'x (load)','windowID': 1,'plotID': 7},
 {'windowName': 'Crank Rod - Plots',
     'plotName': 'x (sledge)','windowID': 1,'plotID': 8},
 {'windowName': 'Crank Rod - Plots',
     'plotName': 'T (motor)','windowID': 1,'plotID': 9},
 {'windowName': 'Crank Rod - Plots',
     'plotName': 'omega','windowID': 1,'plotID': 10},
 {'windowName': '3D Animation',
     'plotName': '3D Animation','windowID': 2,'plotID': 4},
 {'windowName': 'Window 3',
     'plotName': '3D Animation','windowID': 3,'plotID': 5}]
get_plots_from_window(window)[source]
Get all currently available plots that are present in the specified
window by both name and ID.
Parameters:window (str -or- int) – The id or name of the plot window for which the plots should be returned
Returns:
list with all plots in the specified plot window
with the following fields:
  • plotName: str the name of the plot
  • plotID: int the id of the plot
Return type:list of dict

Example:

>>> xxsim.get_plots_from_window(1)
[{'plotName': '3D Animation', 'plotID': 6},
{'plotName': 'x (load)', 'plotID': 7},
{'plotName': 'x (sledge)', 'plotID': 8},
{'plotName': 'T (motor)', 'plotID': 9},
{'plotName': 'omega', 'plotID': 10}]
get_submodel_properties(submodel_name='', properties={})[source]

Get the submodel properties description fields.

Parameters:
  • submodel_name (str, optional) – The hierarchical submodel name. If no name is given or the name is the empty string, then the top-level model is used.
  • properties (str or dict, optional) – The specific set of properties that is returned. If left empty or not specified, all properties will be returned, otherwise only the given set of properties is returned. See the return section about what keys can be queried.
Returns:

Submodel properties description fields:

  • name str the submodel name
  • description str the description field
  • title str the title field
  • keywords str the keywords field
  • version dict dict with fields ‘major’, ‘minor’, and ‘patch’
  • author str the author field
  • manager str the manager field
  • project str the project field
  • company str the company field
  • department str the string field
  • helppage str the helppage field

Return type:

dict

Example:

>>> result = xxsim.get_submodel_properties('CrankRod')
{'name':'CrankRod',
    'description':'A submodel of a crankrod mechanism.',
    'title':'CrankRod',
    'keywords':'mechanics',
    'version':{'major':'1','minor':'0','patch':'0'},
    'author':'Dummy',
    'manager':'Dummy',
    'project':'Crank Rod Mechanism with Sledge',
    'company':'Controllab Products B.V.',
    'department':'Software',
    'helppage':''}
>>> result = xxsim.get_submodel_properties('CrankRod','name')
{'name':'CrankRod'}
get_value(var_name)[source]

Retrieves the value of the specified variable or parameter name.

Note: For matrices, use get_variables or get_value_with_properties, otherwise you will get the values as a list, but will not get the information about the shape of the matrix.

Parameters:var_name (str) – the name of the variable or parameter
Returns:
The value of the variable. None is returned in
case the variable or parameter could not be found.

False is returned on a failure

Return type:float or None

Example

>>> xxsim.get_value('PID.kp')
1.0
get_value_with_properties(var_name)[source]

Retrieves the value of the specified variable or parameter name

Parameters:var_name (str) – the name of the variable or parameter
Returns:
The value of the variable and the variable
properties stored in a ValueWithProperties object None is returned in case the variable or parameter could not be found.

False is returned on a failure

Return type:ValueWithProperties

Example:

>>> xxsim.get_value_with_properties('PID.pdstate')
ValueWithProperties(name='PID.pdstate',
                    value=0.0,
                    unit='',
                    quantity='',
                    unitSymbol='',
                    arithmetictype='real',
                    description='')

The output is a ValueWithProperties namedtuple with the following fields:

  • name: the name of the retrieved parameter
  • value: the value(s) of the retrieved parameter
  • unit: the unit of the parameter (e.g. ‘meter’)
  • quantity: the quantity of the parameter (e.g ‘Length’)
  • unitSymbol: the unit symbol (e.g. ‘m’)
  • arithmetictype: the parameter type (e.g. ‘real’)
  • description: the description of the parameter
get_variables(names=None, kinds=None)

Returns a list of dicts with the specified variables

Parameters:
  • names (str or list of str) – A single name of a variable or a list with variable names. Names must contain the full hierarchy e.g PID.Kp. If omitted, this function will return all available variables from the active model
  • kinds (str or list of str, optional) –

    The kinds of variable requested. Choose one or more from:

    • parameter
    • variable
    • state
    • rate
    • initialValue
    • dependentRate
    • algebraic
    • algebraicin
    • algebraicout
    • constraint
    • constraintin
    • constraintout

    Note: If no kind is specified, all kinds are retrieved.

Returns:

A list of dicts with the following fields:

  • name str The name of the retrieved variable
  • size The size of the variable
  • values list of float The values of the variable
  • properties The properties of the variable(s)

Return type:

list or bool

Examples

To retrieve a list of parameters and state variables found in the submodels PID and Amplifier, you can use:

>>> variables = get_variables(
        ['PID','Amplifier'],
        ['parameter','state'])
get_version()[source]

Get the version number of the 20-sim instance with which a connection was made.

Returns:A dictionary with the following fields:
  • major: The major number of the version number.
  • minor: The minor number of the version number.
  • patch: The patch number of the version number.
  • build: The build number of the version number.

False: On failure.

Return type:dict

Example:

>>> xxsim.get_version()
{'major': 4,
 'minor': 7,
 'patch': 2,
 'build': 7336}
get_window_size()[source]

Returns the current size of the last opened window

Parameters:
  • left (int) –
  • top (int) –
  • width (int) –
  • height (int) –
Returns:

size information with the following fields:

  • left int distance from the left screen border
  • top int distance from the top screen border
  • width int the width of the window
  • height int the height of the window

Return type:

dict

Example:

>>> xxsim.get_window_size()
{'top': 0, 'height': 480, 'left': 0, 'width': 640}
goto_submodel(submodel)[source]

Select the provided submodel in the tree and show its contents

Parameters:submodel (str) – The hierarchical submodel name
Returns:True on success, False otherwise
Return type:bool

Example:

>>> result = xxsim.goto_submodel('mysubmodel')
hide_curve(window, plot, curve, hidden)[source]

Hides the curve if isHidden is true, and otherwise shows it.

Parameters:
  • window (int or str) – Name or ID corresponding to the plot window in which the curve should be hidden or shown.
  • plot (int or str) – Name or ID corresponding to the plot in which the curve should be hidden or shown.
  • curve (int) – ID corresponding to the curve that is either hidden or shown.
  • hidden (bool) – Boolean indicating if the given curve will be hidden (true) or shown (false).
Returns:

True if if the simulator opened without errors,

False otherwise.

Return type:

bool

hide_plot(window, plot, hidden)[source]

Hides the plot if hidden is true, and otherwise shows it.

Parameters:
  • window (int or str) – Name or ID corresponding to the plot window in which the plot should be hidden or shown.
  • plot (int or str) – Name or ID corresponding to the plot that is either hidden or shown.
  • hidden (bool) – Boolean indicating if the given plot will be hidden (true) or shown (false).
Returns:

True if if the plot was hidden without any errors,

False otherwise.

Return type:

bool

hide_plot_window(window, hidden)[source]

Hides the plot window if isHidden is true, and otherwise shows it.

Parameters:
  • window (int or str) – Name or ID corresponding to the window that is either hidden or shown.
  • hidden (bool) – Boolean indicating if the given plot window will be hidden (true) or shown (false).
Returns:

True if if the plot window was hidden without any errors,

False otherwise.

Return type:

bool

is_connected(maxtries=10)

Internal function, do not call externally. This function is used to wait until the tool has started. It tries to call the tool’s XML-RPC server once every second for a given number of tries and returns false in case of failure.

This function requires self.server to be set.

Parameters:maxtries (int, optional) – Number of times to try the connection. Default is 10.
Returns:True on success, false on failure.
Return type:bool

Example

Use the default number of 10 tries.

>>> is_connected()
True

A trivial case. Trying 0 or less times will always fail.

>>> is_connected(0)
False
linearize_model(u, y, symbolic=True, at_current_time=True, closed_loop=False, abs_error=1e-05, rel_error=1e-05, use_abs_when_needed=True)[source]

Linearize a part of the model (SISO and MIMO)

Parameters:
  • u (str -or- list of str) – The fully qualified name(s) of the input variable(s).
  • y (str -or- list of str) – The fully qualified name(s) of the output variable(s).
  • symbolic (bool, optional) – True indicates that a symbolic linearisation should be done, False performs a numerical linearisation. Defaults to True
  • at_current_time (bool, optional) – Linearise at the current time if True. Linearise at the start time if False. Defaults to True.
  • closed_loop (bool, optional) – Do closed loop linearisation if True. Do open loop linearisation if False. Defaults to False.
  • abs_error (float, optional) – The absolute change in states. Defaults to 1.0e-5
  • rel_error (float, optional) – The relative change in states. Defaults to 1.0e-5
  • use_abs_when_needed (bool, optional) – Use the absolute error margin for states that are aproximately 0.0
Returns:

Matrices

Return type:

A, B, C, D

log2csv(path, variables=None)[source]

Write the logged variables from 20-sim to a CSV on the file system.

Parameters:
  • path (string) – The path and file name of the csv file.
  • variables (list, optional) – The list of variables names that should be stored in this csv file. Default (=None) stores all variables marked for logging with set_log_variables()
new_model()[source]

Opens a new empty 20-sim model

Returns:True on success, False otherwise
Return type:bool

Example:

>>> result = xxsim.new_model()
open_model(model, new_instance=False)[source]

Open a 20-sim model file from its path. After opening, the model is activated and initialized.

Parameters:
  • model (str) – Name of the file to load.
  • new_instance (bool) – Set to True to open a new model instance. Set to False to close the current model and open a new model. (default: False)
Returns:

The identifier of the model (1 or higher, 0=error).

It can be used to select the active model.

Return type:

int

Example:

>>> model_id = xxsim.open_model('C:\\temp\\my_model.emx', False)
open_simulator()[source]

Open the simulator window for the current model

Returns:
True if if the simulator opened without errors,
False otherwise.
Return type:bool

Example:

>>> xxsim.open_simulator()
True
process_model()[source]

Process the active 20-sim model.

Returns:A dictionary with the processing results on success with the following fields:
  • errors list of str: processing errors
  • results list of dict: key, value pairs with the
    processing results (model characteristics)
  • warnings list of str: processing warnings

False on failure.

Return type:dict

Example:

>>> xxsim.process_model()
{'errors': [],
 'results': [{'key': 'constraints', 'value': '0'},
             {'key': 'states', 'value': '0'},
             {'key': 'variables', 'value': '21'},
             {'key': 'algebraic loop variables', 'value': '0'},
             {'key': 'equations', 'value': '4'},
             {'key': 'submodels', 'value': '1'},
             {'key': 'discrete states', 'value': '0'},
             {'key': 'dependent states', 'value': '0'},
             {'key': 'discrete systems', 'value': '0'}],
 'warnings': ['[LogVarTest] warning: LogVarTest\p1 is never used',
              '[LogVarTest] warning: LogVarTest\p2 is never used']}
query_implementations()[source]

Returns a list of submodels names with multiple implementations and their active implementation.

Returns:List of ImplementationInfo objects, one for each submodel, with the following fields:
  • name str: the name of the submodel
  • implementation str: the name of the active implementation
  • implementations list of str: list of all available
    implementations for this submodel

False is returned on a failure

Return type:list

Example:

>>> implementations = xxsim.query_implementations()
query_settings(settings_names=())[source]

Queries the active 20-sim model for the settings

Parameters:settings_names – (optional) A string, or list of strings, containing the names of the settings that are to be queried. Defaults to an empty tuple. This will query all available settings.
Returns:
A list of dicts with the following fields:
  • value str: the value of the setting (as string)
  • type str: original type of the value
  • description str: description of the setting
  • key str: setting name
  • enumerations list:
  • properties list: list of key-value dicts

False is returned on a failure

Return type:list

Example

>>> xxsim.query_settings('model.simulator.finishtime')
[{'value': '10',
'properties': [{'value': '0.0', 'key': 'lowerbound'}],
'enumerations': [],
'type': 'double',
'key': 'model.simulator.finishtime',
'description': ''}]
remove_curve_from_plot(window, plot, curve)[source]

For the specified plot window name or ID and plot name or ID, remove the given curve of the plot.

Parameters:
  • window (int or str) – Name or ID corresponding to the window to which in the specified plot the specified curve will be removed.
  • plot (int or str) – Name or ID corresponding to the plot of which the curve will be removed.
  • curve (int) – ID corresponding to the to be deleted curve.
Returns:

True if if the simulator opened without errors,

False otherwise.

Return type:

bool

remove_plot_from_window(window, plot)[source]

For the specified plot window name or ID, the plot with plot name or ID will be removed.

Parameters:
  • window (int or str) – Name or ID corresponding to the window of which the plot will be removed.
  • plot (int or str) – Name or ID corresponding to the plot that should be deleted.
Returns:

True if if the plot was removed from the window without errors,

False otherwise.

Return type:

bool

remove_plot_window(window)[source]

For the given window name or ID, the corresponding plot window will be removed.

Parameters:window (int or str) – Name or ID of the to be removed window.
Returns:
True if if the plot window was removed without any errors,
False otherwise.
Return type:bool
replace_submodel(submodel, filename, implementation='')[source]

Replace an existing submodel with the version from the provided file

Parameters:
  • submodel (str) – The hierarchical submodel name
  • filename (str) – The filename (with full path) that should be used to save the selected submodel.
  • implementation (str, optional) – The implementation that should be made active when the stored submodel has multiple implementations
Returns:

True on success, False otherwise

Return type:

bool

Example:

>>> result = xxsim.replace_submodel('mysubmodel',
                                    'c:\\temp\\mysubmodel.emx')
>>> result = xxsim.replace_submodel('mysubmodel',
                                    'c:\\temp\\mysubmodel.emx',
                                    'mysubmodel implementation')
run(continue_simulation=False)[source]

Run the active 20-sim model with saved settings.

Parameters:continue_simulation (bool, optional) – Set to True to attempt to continue the simulation. Set to False to start a new run. (default: False)
Returns:A dictionary with the following fields:
  • result: 1 if the model runs without errors.
  • info: a list with key-value dicts with information on.
    the simulation run, e.g. total simulation time, number of model calculations, number of output points.
  • warning: warning(s) during running the model, if any
  • errors: error(s) during running the model, if any

False: On failure.

Return type:dict

Example:

>>> xxsim.run(False)
{'errors': [],
 'info': [{'key': 'Total simulation time', 'value': '0.003'},
          {'key': 'Number of Model Calculations', 'value': '1002'},
          {'key': 'Number of Output Points', 'value': '1002'},
          {'key': 'Average Steps per Second', 'value': '334000'}],
 'result': 1,
 'warnings': []}
save_model(filename=None)[source]

Saves the changes made to active 20-sim model

Parameters:filename (str, optional) – The filename that should be used to save the active model. If omitted, 20-sim will save the model under its current name if it has any.
Returns:True on success, False otherwise
Return type:bool

Example:

>>> result = xxsim.save_model('c:\\temp\\mymodel.emx')
save_plot_as_bitmap(filename, window, plot=-1, width=-1, height=-1, dpi=-1)[source]

Save a plot or plot window as bitmap. Supported formats: png, bmp, jpg, gif

Parameters:
  • filename (str) – Filename of the bitmap to store. Supported file extensions: .png, .bmp, .jpg, .gif
  • window (str -or- int) – The name or id of the plot window to select
  • plot (str -or- int, , optional) – The name or id of the plot to save. Leave empty to store all plots in this plot window (default).
  • width (int, optional) – The preferred width of the plot in pixels. 0 or negative => use same size as the plot (default).
  • height (int, optional) – The preferred height of the plot in pixels. 0 or negative => use same size as the plot (default).
  • dpi (int, optional) – The dpi the bitmap should be stored in (e.g. 300). Zero or negative means: use the resolution of the screen (default).
Returns:

True when the plot was saved successfully, False otherwise.

Return type:

bool

Example:

>>> xxsim.save_plot_as_bitmap('c:\temp\myplot.png',
                              'Window 1',
                              'plot 1',
                              640,
                              480)
True
save_submodel(submodel, filename, save_encrypted=0)[source]

Save the given submodel as a separate file

Parameters:
  • submodel (str) – The hierarchical submodel name
  • filename (str) – The filename (with full path) that should be used to save the selected submodel.
  • save_encrypted (int, optional) – 2 if the submodel should be encrypted and C-code generation is allowed, 1 if the submodel should be encrypted, but C-code generation is not allowed, 0 if the submodel should not be encrypted. Default is 0.
Returns:

True on success, False otherwise

Return type:

bool

Example:

>>> result = xxsim.save_submodel('mysubmodel',
                                 'c:\\temp\\mysubmodel.emx')
set_active_model(model)[source]

Sets one of the opened 20-sim models as active. If no active model is chosen, the model opened last is automatically set as active. if only one model is opened, it is set as active model by default.

Parameters:model (str -or- int -or- ModelInfo) – model name or the model id or a ModelInfo dict
Returns:True on success, False otherwise
Return type:bool

Example:

>>> xxsim.set_active_model('C:\temp\PID.emx')
True
>>> xxsim.set_active_model(3)
True
set_implementations(submodel_names, implementation_names=None, process_model=True)[source]

Change the implementation of one or more submodels

Parameters:
  • submodel_names (str, list or dict) – a string or list of strings with the submodel names or a dict with the submodel names as key and the implementation name as value
  • implementation_names (str, optional) – string or list of strings with the corresponding implementation to set. This argument should be omitted when you pass a dict to submodel_names.
  • process_model (bool, optional) – boolean to indicate whether the model should be processed afterwards. Defaults to true
Returns:

True on success, False on failure

Return type:

bool

Examples

>>> xxsim.set_implementations('Submodel1', 'implementationA')
>>> xxsim.set_implementations('Submodel1', 'implementationA',
...     False)

The following are equivalent:

>>> xxsim.set_implementations(['Submodel1', 'Submodel2'],
...                    ['implementationA','implementationB'])
>>> xxsim.set_implementations({'Submodel1': 'implementationA',
...                     'Submodel2': 'implementationB'})
set_initial_values(names, values)[source]

Set the specified initial values.

Parameters:
  • names (list) – a list of strings with the names of the initial values to be set (or a string for a single initial value)
  • values (list) – a list of floats with the new values of the initial values (or a float for a single new value)
Returns:

True if the initial values are set properly, False otherwise.

Return type:

bool

Example

To set a single initial value, you can use:

>>> xxsim.set_initial_values('PID.pdstate_initial', 1.0)

For multiple initial values, you can use:

>>> xxsim.set_initial_values(['PID.pdstate_initial',
                              'PID.pistate_initial'],
                              [1.0, 2.0])
True
set_log_variables(log_variables)[source]

logs specified variables while running active model

Parameters:log_variables (list -or- str) –

list of variables or a single variable name

Note: make sure the variable name exists in active model. If not, an error message will be returned

Returns:True on success, False otherwise
Return type:bool

Examples:

>>> xxsim.set_log_variables('PID.error')
True
>>> xxsim.set_log_variables(['PID.error', 'PID.output'])
True
set_parameters(names, values)[source]

Sets the specified parameters to a new value

Parameters:
  • names (str or list) – string (single parameter only) or a list of strings with the names of the parameters to be set
  • values (float or list) – the new values of the parameters
Returns:

Returns True if the parameters are set properly,

False otherwise

Return type:

bool

Examples

To set a single parameter, you can use:

>>> xsim.set_parameters('PID.kp', 0.2)
True

To set multiple parameters, you can use:

>>> xxsim.set_parameters(['PID.kp', 'Amplifier.Gain'], [0.3, 5])
True
set_scriptmode(scriptmode=True)[source]

Turn On/Off 20-sim scripting mode. Scripting mode deactivates all buttons on simulation window except the stop button.

Parameters:scriptmode (bool,optional) – True sets 20-sim in scripting mode (default), False resets 20-sim back to normal mode
Returns:True on success, False otherwise
Return type:bool

Example:

>>> xxsim.set_scriptmode(True)
True
set_settings(keys, values)

Sets model settings to the provided value. To set only a single setting, you can pass the key and value as strings. For the list of available settings, call query_settings() once.

Parameters:
  • keys (list) – The list of settings.
  • values (list) – The values for the settings. Individual values will be converted to a string.
Returns:

True on success, False on failure.

Return type:

bool

Examples

>>> set_settings(['testsetting1','testsetting2'],
...             ['value1','value2'])
True

The following are equivalent:

>>> set_settings(['testsetting1'],['value1'])
>>> set_settings('testsetting1','value1')
set_variables(names, values)

Sets the specified variable(s) to a new value

Parameters:
  • names (list) – names of the variables to be set.
  • values (list) –

    the new values of the variables. Supported objects for the values list are:

    • Numbers
    • Strings (e.g. ‘Hello World!’)
    • Python lists of numbers for vectors (e.g. [1, 2, 3, 4])
    • Python lists of lists of numbers for matrices (e.g. [[1,2],[3,4]])
    • Any Numpy object that is a (sub)instance of numpy.ndarray provided it has no more than 2 dimensions.

    If only a single variable is to be set, the name and the object can be passed as strings, there’s no need to explicitly encapsulate them in lists.

Returns:

True on success, False otherwise

Return type:

bool

Example

To set the ‘Controller_Continuous.kp’ and ‘Controller_Discrete.kp’ to 3 and 4 respectively you can use:

>>> result = set_variables(
['Controller_Continuous.kp', 'Controller_Discrete.kp'],
[3.0, 4.0])
To set a string ‘Hello World!’ and a matrix
[[1.0, 3.5], [12.5,3.0]]:
>>> set_variables(
...    [ 'astring', 'somematrix' ],
...    [ 'Hello World!', [[1.0, 3.5], [12.5,3.0]] ])
set_window_size(left, top, width, height)[source]

Set the size of the last opened window

Parameters:
  • left (int) –
  • top (int) –
  • width (int) –
  • height (int) –
Returns:

True on success, False otherwise

Return type:

bool

Example:

>>> result = xxsim.set_window_size(0, 0, 640, 480)
simulator_copy_states_to_initials()[source]

Copy current states to initial values

Returns:True on success, False otherwise.
Return type:bool

Example:

>>> xxsim.simulator_copy_states_to_initials()
True
simulator_get_fast_mode()[source]

Check whether the simulator is in ‘fast mode’.

Returns:True if the simulator is in ‘fast mode’, False otherwise.
Return type:bool

Example

>>> xxsim.simulator_get_fast_mode()
True
simulator_get_finish_time()[source]

Get the finish time used by the simulator.

Returns:
The finish time used by the simulator.
A return value of False indicates an error has occurred.
Return type:float

Example

>>> xxsim.simulator_get_finish_time()
10.0
simulator_get_output_after_each()[source]

Gets the current value of the simulator ‘Output After Each’ Run property

Returns:
The ‘output after each’ time on success.
A value of -1.0 indicates an error has occurred.

False is returned on a failure

Return type:float

Example

>>> xxsim.simulator_get_output_after_each()
0.0
simulator_get_start_time()[source]

Get the start time used by the simulator.

Returns:The start time used by the simulator.

False is returned on a failure

Return type:float

Example

>>> xxsim.simulator_get_start_time()
2.0
simulator_is_simulating()[source]

Check whether the simulator is running.

WARNING: If the function fails and the error handling is set to not raise that error (the default), the function will print an error for the user and return False. In this case, the function returns False even when the simulator is running. If you initialise XXSim with RAISEERRORS.ALL it will always raise an error that can be caught by the calling script. This is the recommended way for automation.

Returns:True if the simulator is running, otherwise False.
Return type:bool

Example:

>>> xxsim.simulator_is_simulating()
False
simulator_set_fast_mode(fastmode=True)[source]

Change the simulator mode to ‘fast mode’ or ‘debug mode’

Parameters:fastmode (bool, optional) – True = fast mode (default), False = debug mode
Returns:True on success, False otherwise
Return type:bool

Example

>>> xxsim.simulator_set_fast_mode(True)
True
simulator_set_finish_time(finishtime)[source]

Set the finish time of the simulator:

Parameters:finishtime (float) – The new finish time for the simulator.
Returns:True on success, False on failure.
Return type:bool

Example

>>> xxsim.simulator_set_finish_time(10.0)
True
simulator_set_output_after_each(output_time)[source]

Change the ‘Output After Each’ Run property in the simulator

Parameters:output_time (float) – Set the ‘output after each’ option of the simulator.to this value.
Returns:True on success, False on failure.
Return type:bool

Example

>>> result = xxsim.simulator_set_output_after_each()
simulator_set_start_time(starttime)[source]

Set the start time for the simulator:

Parameters:starttime (float) – The new start time for the simulator.
Returns:True on of success, False on failure.
Return type:bool

Example

>>> xxsim.simulator_set_start_time(2.0)
True
simulator_single_step()[source]

Execute a single simulation step for the active 20-sim model.

Returns:simulation results dictionary with the following fields:
  • result int:
  • info list of dict: list with key, value pairs with simulation statistics
  • warnings list of str: list of warnings that occured during the simulation step
  • errors list of str: list of warnings that occured during the simulation step

False on failure.

Return type:dict

Example:

>>> xxsim.simulator_single_step()
{'errors': [],
 'info': [{'key': 'Total simulation time', 'value': '0.02'},
          {'key': 'Number of Model Calculations', 'value': '2'},
          {'key': 'Number of Output Points', 'value': '1'},
          {'key': 'Average Steps per Second', 'value': '100'}],
 'result': 0,
 'warnings': []}
simulator_start()[source]

Start the simulation. The simulation will run until it reaches its finish time, or until the simulator_stop() function is called.

Returns:True on success, False otherwise.
Return type:bool

Example

>>> xxsim.simulator_start()
True
simulator_stop()[source]

Stop the simulation.

Returns:True on success, False otherwise.
Return type:bool

Example

>>> xxsim.simulator_stop()
True