controllab package¶
controllab.XXSim class¶
- XXSim¶
alias of
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*: 0colorG
: The green component of the RGB color that the curve should have. Valid range: 0-255. Default*: 0colorB
: The blue component of the RGB color that the curve should have. Valid range: 0-255. Default*: 0thickness
: 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:
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:
- Returns:
a unique ID corresponding to the plot that was created.
- Return type:
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:
Example:
>>> xxsim.add_plot_window('Test') 1
- add_port(submodel_name, port_name, is_output=False, port_type=1, rows=1, columns=1, quantity='', unit='', data_type=1, domain='', across='', through='', causality='', has_separate_high_low_terminals=False, accepts_any_number_of_terminals=False, description='')[source]¶
Add a new port to the given submodel.
- Parameters:
submodel_name (str) – name of the submodel to add the port to.
port_name (str) – name of the port to add to the submodel.
is_output (bool, optional) – Is the port an output (True) or input (False)? Default: input (False).
port_type (int, optional) – Is the port a signal port (1), iconic diagram port (2) or bondgraph port (3). Default: Signal (1).
rows (int, optional) – The amount of rows for this port. If rows=1 and columns=1, then the port is a scalar. Default: 1.
columns (int, optional) – the amount of columns for this port. If rows=1 and columns=1, then the port is a scalar. Default: 1.
quantity (str, optional) – physics quantity for this port. Default: empty string. Limit: Only used when port_type == Signal (1).
unit (str, optional) – physics unit for this port. Default: empty string. Limit: Only used when port_type == Signal (1).
data_type (int, optional) – datatype of the port. Real=1, Integer=2, Bool=3, String=4. Default: Real (1). Limit: Only used when port_type == Signal (1).
domain (str, optional) – Domain of the port. Default: empty string. Limit: Only used when port_type == Iconic (2) or port_type == Bondgraph (3).
accross (str, optional) – Accross variable for this port. Default: empty string. Limit: Only used when port_type == Iconic (2) or port_type == Bondgraph (3).
through (str, optional) – Through variable for this port. Default: empty string. Limit: Only used when port_type == Iconic (2) or port_type == Bondgraph (3).
causality (str, optional) – The causality of the port. Default: empty string. Limit: Only used when port_type == Iconic (2) or port_type == Bondgraph (3).
has_separate_high_low_terminals (bool, optional) – Show separate terminals (graphical port connectors) for low and high terminals in iconic diagrams. Default: False (show as one terminal). Limit: Only used when port_type == Iconic (2).
accepts_any_number_of_terminals (bool, optional) – Accept any number of terminals when True. Default: False. Limit: Only used when port_type == Iconic (2).
description (str, optional) – Set the description for this port. Default: empty string.
- Returns:
True on success, False otherwise.
- Return type:
Example:
>>> xxsim.add_port('Controller', 'input', description="Input port for the controller.") True
>>> xxsim.add_port('Controller', 'output', is_output = True, description="Output port for the controller.") True
>>> xxsim.add_port('Controller', 'enable', data_type = 3, description="Enable port of type boolean for the controller.") True
>>> xxsim.add_port('Reference', 'RotationMatrix', rows=3, columns=3, description="3 by 3 rotation matrix for the Reference submodel") True
>>> xxsim.add_port('Inertia', 'p', port_type=2, domain="rotation", across='omega', through='T', causality='preferred flow out', accepts_any_number_of_terminals=True, description="Add rotation type port to Inertia submodel.") True
- clear_all_runs()[source]¶
Clear all simulation runs.
Shortcut for: clear_run(0)
- Returns:
True on success, False otherwise.
- Return type:
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:
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:
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:
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:
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:
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:
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)
- create_connection(source_submodel, source_port, target_submodel, target_port, intermediate_points=None)[source]¶
Create a connection between a source port on the source submodel and the target port on the target submodel.
- Parameters:
source_submodel (str) – The submodel path and name of the submodel from which the connection should start.
source_port (str) – The name of a port from the source_submodel from which the connection should start.
target_submodel (str) – The submodel path and name of the submodel at which the connection should end.
target_port (str) – The name of a port of the target_submodel at which the connection should end.
intermediate_points (list of dict, optional, default is None) – An optional list of x-y coordinates for intermedate drawing points for the connection line
- Returns:
True on success, False otherwise.
- Return type:
Example:
>>> xxsim.create_connection("Plant", "output", "Controller", "Input") True
>>> xxsim.create_connection("Plant", "output", "Controller", "Input", [{'x': 100, 'y': 100}, {'x': 150, 'y': 100}]) True
- disconnect()[source]¶
Disable the 20-sim script mode and close the connection.
- Returns:
True on success.
- Return type:
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)
- export_3d_scenery(sceneryFileName, plotWindow, plot)[source]¶
- Export a 3D scenery from a 3D plot. If the plot is not
a 3D plot, then no scenery file will be exported, but no error will be given either.
- Parameters:
sceneryFileName (str) – The name and path to where the scenery file should be exported.
plotWindow (str -or- int) – The name or ID of the plot window.
plot (str -or- int) – The name or id of the plot.
- Returns:
- True when the plot is not a 3D animation plot or the plot is a 3D
animation plot and a scenery file has been exported succesfully, False otherwise.
- Return type:
Example:
>>> xxsim.export_3d_scenery('c:\temp\myscenery.scn', 'Window 1', 'plot 1') True
- 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
Trueerrors
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
Trueerrors
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:
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:
- 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:
- get_icon_text(submodel_name)[source]¶
Get the icon text for a submodel.
- Parameters:
submodel_name (str) – Name of the submodel to obtain the icon text from.
- Returns:
the Sidops icon text
- Return type:
string
Example:
>>> result = xxsim.get_icon_text('Controller.Kp') >>> icon_text = result['icon'] >>> print(icon_text) icon bg top figures rectangle 0 0 32 32 color 0 fill 15132390; text 'K' 16 16 color 16711680 16 bold; end;
- 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:
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:
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:
- 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:
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 callUSERObjects
int the number of USER objectsGDIObjects
int the number of GDI objectsWorkingSetMemory
float the current memory usagein megabytes (MB)
PeakWorkingSetMemory
float the peak memory usagein megabytes (MB)
AvailablePhysicalMemory
float the available physicalmemory on the system
- Return type:
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 modelidentifier
int: the identifier for this model in thecurrent 20-sim session.
False is returned on a failure.
- Return type:
Example:
>>> xxsim.get_models() [ModelInfo(name='C:\temp\my_model.emx', identifier=2), ModelInfo(name='C:\temp\another_model.emx', identifier=3)]
- get_monitor_values(ids=[])[source]¶
Retrieves the selected monitor values (see set_monitor_variables). This function returns the contents of the values member in the dict list as returned by the get_monitor_variables() function. If an empty array is given, the value of every registered monitor variable will be returned, else only the provided selection.
- Parameters:
ids (list of int) – Integer list with the ids of the variables to return. The variable id is the id as returned by the set_monitor_variables function.
- Returns:
- list with the values of the monitored variables or
False on error
- Return type:
Example:
>>> xxsim.get_monitor_values() [0.0, [1.0, 2.0, 3.0, 4.0]]
- get_monitor_variables(ids=[])[source]¶
Retrieves the selected monitor variables (see set_monitor_variables). If an empty array is given, every registered monitor variable will be returned, else only the provided selection.
- Parameters:
ids (list of int) – Integer list with the ids of the variables to return. The variable id is the id as returned by the set_monitor_variables function.
- Returns:
- list with entries for each specified variable or False on
error. The dict contains the following dict members:
id
int the id for this monitor variablesize
list of int list of sizes for each dimension: rows, columnsvalues
list of float all values for this variable
- Return type:
Example:
>>> xxsim.get_monitor_variables() [{'id': 0, 'size': [1], 'values': [0.0]}, {'id': 1, 'size': [2,2], 'values': [1.0, 2.0, 3.0, 4.0]}]
- 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 parametervalue
: the value(s) of the retrieved parameterunit
: 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:
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:
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 windowwindowID
int the corresponding plot identifier
- Return type:
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 windowwindowID
int the corresponding plot identifierplotName
str the name of the plotplotID
int the id of the plot
- Return type:
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 plotplotID
: int the id of the plotisHidden
: bool True when the plot is hidden, False when shownplotType
: str the type of the plot, e.g. ‘GraphPlot’, ‘GLPlot’ or ‘FFTPlot’
- Return type:
Example:
>>> xxsim.get_plots_from_window(1) [{'plotName': '3D Animation', 'plotID': 6, isHidden}, {'plotName': 'x (load)', 'plotID': 7}, {'plotName': 'x (sledge)', 'plotID': 8}, {'plotName': 'T (motor)', 'plotID': 9}, {'plotName': 'omega', 'plotID': 10}]
- get_ports(submodel_name='')[source]¶
Get all ports for a submodel.
- Parameters:
submodel_name (str) – Name of the submodel to obtain the port definitions from.
- Returns:
list of dict: list with all ports with the following fields:
name
: str the name of this port.portType
: int 1 = Signal, 2 = Iconic, 3 = Bondgraph, -1 = unknown.size
: struct contains rows and columns fields for the port.orientationOut
: bool True if the orientation is out (output), False if in (input).quantity
: str the quantity of the port (signal-only).unit
: str the unit of the port (signal-only).dataType
: int 1=real, 2=integer, 3=boolean, 4=string, -1 = unknown (signal-only).domain
: str domain of the port (Iconic/Bondgraph-only).across
: str the across variable for this port (Iconic/Bondgraph-only).through
: str the through variable for this port (Iconic/Bondgraph-only).causality
: str the causality of the port (Iconic/Bondgraph-only).hasSeparateHighAndLowTerminals
: bool True if high and low terminals are separated, False otherwise (Iconic-only).acceptsAnyNumberOfTerminals
: bool True if any number of terminals is accepted, False otherwise (Iconic-only).description
: str the description of the port.
- Return type:
dict containing a ‘ports’ member that contains
Example:
>>> result = xxsim.get_ports('Controller.Kp')
- get_ports2(submodel_name='')[source]¶
Get all ports for a submodel. Simplified version of get_ports
- Parameters:
submodel_name (str) – Name of the submodel to obtain the port definitions from.
- Returns:
list with all ports with the following fields:
name
: str the name of this port.portType
: int 1 = Signal, 2 = Iconic, 3 = Bondgraph, -1 = unknown.size
: struct contains rows and columns fields for the port.orientationOut
: bool True if the orientation is out (output), False if in (input).quantity
: str the quantity of the port (signal-only).unit
: str the unit of the port (signal-only).dataType
: int 1=real, 2=integer, 3=boolean, 4=string, -1 = unknown (signal-only).domain
: str domain of the port (Iconic/Bondgraph-only).across
: str the across variable for this port (Iconic/Bondgraph-only).through
: str the through variable for this port (Iconic/Bondgraph-only).causality
: str the causality of the port (Iconic/Bondgraph-only).hasSeparateHighAndLowTerminals
: bool True if high and low terminals are separated, False otherwise (Iconic-only).acceptsAnyNumberOfTerminals
: bool True if any number of terminals is accepted, False otherwise (Iconic-only).description
: str the description of the port.
- Return type:
Example:
>>> result = xxsim.get_ports('Controller.Kp')
- 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 list of str, 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 namedescription
str the description fieldtitle
str the title fieldkeywords
str the keywords fieldversion
dict dict with fields ‘major’, ‘minor’, and ‘patch’author
str the author fieldmanager
str the manager fieldproject
str the project fieldcompany
str the company fielddepartment
str the string fieldhelppage
str the helppage field
- Return type:
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_submodel_tree(submodelName, recursive=False, includeSelf=False)[source]¶
Get the list of submodels underneath the specified submodel.
- Parameters:
submodelName (str) – The hierarchical submodel name or the empty string for the overall model.
recursive (bool, optional, default = False) – If True, then all submodels are recursively obtained from underneath the specified submodel, if False, then only the submodels directly underneath the current submodel are returned.
includeSelf (bool, optional, default = False) – If True, then include the submodel with name submodelName in the list of return values. If False, do not include the submodel with name submodelName in the list of return values, but only the submodels underneath.
- Returns:
- list with all submodels for the specified submodel
with the following fields:
name
str the name of the child submodelhierarchicalName
str the hierarchical model path of the child submodeltype
str the type of the child submodelcategory
int -1 if undefined, 0 if equation model, 1 is graphical modelhasMultipleImplementations
bool True if the submodel has more than 1 implementation, False otherwise.
- Return type:
Example:
>>> result = xxsim.get_submodel_tree('Controller.Kp', False)
- get_type_text(submodel_name)[source]¶
Get the type text for a submodel. This function returns the Sidops source text of the submodel interface
- Parameters:
submodel_name (str) – Name of the submodel to obtain the type text from.
- Returns:
the Sidops type text
- Return type:
string
Example:
>>> result = xxsim.get_type_text('Controller.Kp') >>> type_text = result['type'] >>> print(type_text) type Gain ports signal in input; signal out output; parameters real K = 100.0; end;
- 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='', multiplicationToSI=1.0, arithmetictype='real', description='', attributes='')
The output is a ValueWithProperties namedtuple with the following fields:
name
: the name of the retrieved variablevalue
: the value(s) of the retrieved variableunit
: the unit of the variable (e.g. ‘meter’)quantity
: the quantity of the variable (e.g ‘Length’)unitSymbol
: the unit symbol (e.g. ‘m’)arithmetictype
: the variable type (e.g. ‘real’)multiplicationToSI
: the multiplication factor to get thevalue in SI units (e.g. 0.001 with unit symbol ‘mm’)
description
: the description of the variableattributes
: the attributes defined for this variable
- 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 modelkinds (str or list of str, optional) –
The kinds of variable requested. Choose one or more from:
constant
parameter
variable
state
rate
initialValue
independentState
dependentState
independentRate
dependentRate
algebraicIn
algebraicOut
constraintIn
constraintOut
discreteState
discreteRate
discreteInitialValue
importVariable
exportVariable
autoAddedVariable
plot
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 variablesize
The size of the variablevalues
list of float The values of the variableproperties
The properties of the variable(s) as list ofkey-value dicts. Possible keys:
parameter, variable
arithmetictype
quantity
unit
unitSymbol
description
multiplicationToSI (since 20-sim 4.8)
attributes (since 20-sim 4.8)
- 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:
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
- Returns:
size information with the following fields:
left
int distance from the left screen bordertop
int distance from the top screen borderwidth
int the width of the windowheight
int the height of the window
- Return type:
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:
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:
- hide_plot(window, plot, hidden)[source]¶
Hides the plot if hidden is true, and otherwise shows it.
- Parameters:
- Returns:
- True if if the plot was hidden without any errors,
False otherwise.
- Return type:
- hide_plot_window(window, hidden)[source]¶
Hides the plot window if isHidden is true, and otherwise shows it.
- Parameters:
- Returns:
- True if if the plot window was hidden without any errors,
False otherwise.
- Return type:
- import_3d_scenery(sceneryFileName, plotWindow=None, plot=None)[source]¶
Import a 3D scenery to all 3D plots.
- Parameters:
sceneryFileName – The name and path to where the scenery file should be imported from.
- Returns:
- True when the scenery file has been imported succesfully, False
otherwise.
- Return type:
Example:
>>> xxsim.import_3d_scenery('c:\temp\myscenery.scn') True
- insert_submodel(submodel, filename, position_x, position_y, implementation='')[source]¶
Insert an new 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 to insert the model.
position_x (int) – x-position of the new submodel
position_y (int) – y-position of the new submodel
implementation (str, optional) – The implementation that should be made active when the submodel has multiple implementations
- Returns:
True on success, False otherwise
- Return type:
Example:
>>> result = xxsim.insert_submodel('mysubmodel', 'c:\\temp\\mysubmodel.emx', 200, 200) >>> result = xxsim.insert_submodel('mysubmodel', 'c:\\temp\\mysubmodel.emx', 200, 200, 'mysubmodel implementation')
- 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:
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
- load_simulation_state(filename, initialize_simulator=True)[source]¶
Loads the simulation state from file The current model is used for loading the state.
- Parameters:
- Returns:
True on success, False on failure
- Return type:
boolean
Example:
>>> result = xxsim.save_simulation_state('C:\\temp\\my_sim_state.xml', true)
- log2csv(path, variables=None, overwrite=True)[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()
overwrite (bool, optional) – Determines if an existing file should be overwritten
- new_model()[source]¶
Opens a new empty 20-sim model
- Returns:
True on success, False otherwise
- Return type:
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:
- Returns:
- The identifier of the model (1 or higher, 0=error).
It can be used to select the active model.
- Return type:
Example:
>>> model_id = xxsim.open_model('C:\\temp\\my_model.emx', False)
- open_processed_model(model)[source]¶
Open a processed 20-sim model file from its path. The current model is used for opening the processed model.
- Parameters:
model (str) – Name of the file to load (usually with extension .emp).
- Returns:
True on success, False on failure
- Return type:
boolean
Example:
>>> result = xxsim.open_processed_model('C:\\temp\\my_model.emp')
- open_simulator()[source]¶
Open the simulator window for the current model
- Returns:
- True if if the simulator opened without errors,
False otherwise.
- Return type:
Example:
>>> xxsim.open_simulator() True
- path()¶
Return the path of the current connected tool
- 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 errorsresults
list of dict: key, value pairs with theprocessing results (model characteristics)
warnings
list of str: processing warnings
False on failure.
- Return type:
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 submodelimplementation
str: the name of the active implementationimplementations
list of str: list of all availableimplementations for this submodel
False is returned on a failure
- Return type:
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 valuedescription
str: description of the settingkey
str: setting nameenumerations
list:properties
list: list of key-value dicts
False is returned on a failure
- Return type:
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:
- Returns:
- True if if the simulator opened without errors,
False otherwise.
- Return type:
- 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.
- remove_plot_window(window)[source]¶
For the given window name or ID, the corresponding plot window will be removed.
- remove_port(submodel_name, port_name)[source]¶
Remove the specified port form the specified submodel.
- Parameters:
- Returns:
True on success, False otherwise.
- Return type:
Example:
>>> xxsim.remove_port('Controller', 'output') True
- rename_submodel(submodel, newname)[source]¶
Rename an existing submodel.
- Parameters:
- Returns:
True on success, False otherwise
- Return type:
Example:
>>> result = xxsim.rename_submodel('mysubmodel', 'mynewsubmodel')
- replace_submodel(submodel, filename, implementation='')[source]¶
Replace an existing submodel with the version from the provided file
- Parameters:
- Returns:
True on success, False otherwise
- Return type:
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 anyerrors
: error(s) during running the model, if any
False: On failure.
- Return type:
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_encrypted_model(submodel_name, filename, password='', allow_edit_with_password=True, allow_processing_without_password=True, allow_edit_parameters=True, allow_code_generation=True)[source]¶
Save the given submodel encrypted 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.
password (str) – Optional password. Can be omitted if allow_processing_without_password==True and allow_edit_with_password==False. In that case 20-sim will encrypt the model with a random generated key. Default = ‘’.
allow_edit_with_password (boolean) – If True, editing of the submodel in the editer is possible when the password is given. For this case password must be given. Default = True.
allow_edit_parameters (boolean) – If True, editing of parameters of the submodel is possible with the Parameters/Initial Values dialog. Default = True.
allow_code_generation (boolean) – If True, C-Code generation and Matlab-code generation is possible for the submodel. Default = True.
- Returns:
True on success, False otherwise
- Return type:
Example:
>>> result = xxsim.save_encrypted_model('mysubmodel', 'c:\\temp\\mysubmodel.emx', password='secret', allow_code_generation=False)
- 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:
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:
Example:
>>> xxsim.save_plot_as_bitmap('c:\temp\myplot.png', 'Window 1', 'plot 1', 640, 480) True
- save_processed_model(model, onlyRunSpecs=False)[source]¶
Save a processed 20-sim model file to the given path.
- Parameters:
- Returns:
True on success, False on failure
- Return type:
boolean
Example:
>>> result = xxsim.save_processed_model('C:\\temp\\my_model.emp', True)
- save_simulation_state(filename)[source]¶
Save the simulation state to a file The current model is used for saving the state.
- Parameters:
filename (str) – Name of the file to save (usually with extension .xml).
- Returns:
True on success, False on failure
- Return type:
boolean
Example:
>>> result = xxsim.save_simulation_state('C:\\temp\\my_sim_state.xml')
- 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:
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:
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:
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:
- Returns:
True if the initial values are set properly, False otherwise.
- Return type:
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:
Examples:
>>> xxsim.set_log_variables('PID.error') True
>>> xxsim.set_log_variables(['PID.error', 'PID.output']) True
- set_monitor_variables(variables)[source]¶
Learn 20-sim a list of variables that it should monitor. Use the get_monitor_variables() function to fetch with one call all variables set using this function. Calling this function again will erase the existing list of registered monitor variables.
- Parameters:
variables (list of str) – String list with the names of all variables to monitor. Names can be specified with indices to indicate a member in a vector or matrix e.g. var1[2,3]
- Returns:
- list with 1 entry for each specified variable with the
following dict members:
id
int the identifier for this entry in the listsize
list of int sizes for each dimension: rows, columns
- Return type:
Example:
>>> xxsim.set_monitor_variables(['var1','submodel.matrix']) [{'id': 0, 'size': [1]}, {'id': 1, 'size': [2,2]}]
- set_parameters(names, values)[source]¶
Sets the specified parameters to a new value
- Parameters:
- Returns:
- Returns True if the parameters are set properly,
False otherwise
- Return type:
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:
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:
- Returns:
True on success, False on failure.
- Return type:
Examples
>>> set_settings(['testsetting1','testsetting2'], ... ['value1','value2']) True
The following are equivalent:
>>> set_settings(['testsetting1'],['value1'])
>>> set_settings('testsetting1','value1')
- set_submodel_properties(submodel_name='', properties={})[source]¶
Set the properties of a submodel.
- Parameters:
submodel_name (str) – name of the requested submodel.
properties (structured array) – key-value pairs of the properties to set.
- Returns:
True on success, False otherwise.
- Return type:
Example:
>>> result = xxsim.set_submodel_properties('BeltPulley', [{'key':'title','value':'controller'}]) True
- set_value(var_name, value, properties=None)[source]¶
Sets the value of the specified variable, initialvalue or parameter.
- Parameters:
- 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.set_value('Mass.m', 0.200) 1.0 >>> xxsim.set_value('Mass.m', 200.0, [{'key':'multiplicationToSI', 'value':'0.001'}]) 1.0
- set_variables(names, values, properties=None)¶
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.
properties (list, optional) – list of key-value dicts with optional variable properties
set (If only a single variable is to be) –
object (the name and the) –
strings (can be passed as) –
explicitly (there's no need to) –
lists. (encapsulate them in) –
- Returns:
True on success, False otherwise
- Return type:
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:
- Returns:
True on success, False otherwise
- Return type:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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 statisticswarnings
list of str: list of warnings that occured during the simulation steperrors
list of str: list of warnings that occured during the simulation step
False on failure.
- Return type:
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': []}
controllab.XXSim4C class¶
- XXSim4C¶
alias of
XXSim4CWrapper
- class XXSim4CWrapper(errorlevel=0)[source]¶
20-sim 4C scripting interface for Python.
This is a Python wrapper for 20-sim 4C’s XML-RPC interface.
- errorlevel¶
The level of errors that should be raised.
- close()¶
Close the application you are connected to.
- close_project()[source]¶
Closes active 20-sim 4C project without saving changes
- Returns:
True when closed properly, False otherwise
- Return type:
Example:
>>> result = close_project(True)
- compile()[source]¶
Compiles the 20-sim 4C sources to a target application/binary
- Parameters:
None –
- Returns:
True on success, False otherwise
- Return type:
Example:
>>> compile=compile()
- connect(uri='http://localhost:5480', version='2.2', **kwargs)[source]¶
Create a connection with 20-sim 4C using XML-RPC
- Parameters:
uri (str) – The URI to connect to. Defaults to ‘http://localhost:5480’ for connecting to 20-sim 4C.
- Returns:
True if successful, False otherwise.
Example:
- Return type:
>>> connect('http://localhost:5480') True
- disconnect()¶
Close the connection
- Returns:
True on success.
- Return type:
Example:
>>> disconnect() True
- 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)
- get_active_model()[source]¶
Returns name and unique identifier of active model
- Parameters:
None –
- Returns:
The model information
- Return type:
xxsim4c.ModelInfo
Example:
>>> modelinfo = getActive_model()
- get_active_target()[source]¶
Retrieves the active target identifier
- Parameters:
None –
- Returns:
(targetname, filename, identifier) bool: False on failure.
- Return type:
collections.namedtuple
Example:
>>> targetinfo = getActive_target()
- get_log_add_time_stamp()[source]¶
Get the addTimeStamp property for the log.
- Returns:
True if the loging is timestamped.
- Return type:
- get_log_file()[source]¶
Retrieves the properties of the log file.
- Parameters:
None –
- Returns:
- The information about the log file.
None in case of failure.
- Return type:
LogInfo
Example:
>>> logfile = get_log_file()
- get_log_frequency()[source]¶
Get the log frequency.
- Returns:
Frequency as calculated from the sampletime.
- Return type:
- get_log_omega()[source]¶
Get the log omega.
- Returns:
Omega as calculated from the sampletime.
- Return type:
- get_log_settings()[source]¶
Retrieves the settings for logging.
- Parameters:
None –
- Returns:
The timing settings for the logging.
- Return type:
TimeSettings
Example:
>>> logsettings = get_log_settings()
- get_log_show_plot()[source]¶
Get the showPlot property for the log.
- Returns:
True if the ‘Show plot after run’ option is enabled.
- Return type:
- get_models()[source]¶
Returns a list of all opened models and their model identifier
- Parameters:
None –
- Returns:
List of
xxsim4c.ModelInfo
- Return type:
- get_project()[source]¶
Returns a list of the opened project and their project identifier
- Parameters:
None –
- Returns:
List of
ProjectInfo
- Return type:
- get_run_frequency()[source]¶
Get the run frequency.
- Returns:
Frequency as calculated from the sampletime.
- Return type:
- get_run_omega()[source]¶
Get the run omega.
- Returns:
Omega as calculated from the sampletime.
- Return type:
- get_run_settings()[source]¶
Retrieves the run settings.
- Parameters:
None –
- Returns:
The run settings, None on failure
- Return type:
RunSettings
Example:
>>> run_settings = getRun_settings()
- get_settings(settings=None)[source]¶
Queries the active 20-sim 4C model for the settings
- Parameters:
settings (list, optional) – The list of names of the settings that
blank (should be retrieved. If left) –
retrieved. (all settings will be) –
setting (When querying a single) –
string. (the value can be passed as) –
- Returns:
The settings.
- get_targets()[source]¶
Retrieves list of all the targets in use in the open project
- Parameters:
None –
- Returns:
List of xxsim4c.TargetInfo
- Return type:
- get_url()[source]¶
Gets the URL of the target
- Parameters:
None –
- Returns:
URL of the target
Example:
>>> URL = get_url()
- 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 modelkinds (str or list of str, optional) –
The kinds of variable requested. Choose one or more from:
constant
parameter
variable
state
rate
initialValue
independentState
dependentState
independentRate
dependentRate
algebraicIn
algebraicOut
constraintIn
constraintOut
discreteState
discreteRate
discreteInitialValue
importVariable
exportVariable
autoAddedVariable
plot
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 variablesize
The size of the variablevalues
list of float The values of the variableproperties
The properties of the variable(s) as list ofkey-value dicts. Possible keys:
parameter, variable
arithmetictype
quantity
unit
unitSymbol
description
multiplicationToSI (since 20-sim 4.8)
attributes (since 20-sim 4.8)
- 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 4C instance to 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:
Example:
>>> xxsim4c.get_version() {'major': 2, 'minor': 2, 'patch': 0, 'build': 4700}
- 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:
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
- is_target_online()[source]¶
Checks whether the active target is online or not
- Returns:
- True when the target is on-line. False when the target is
off-line or when 20-sim 4C is still trying to connect.
- Return type:
- open_project(project)[source]¶
Opens a project file from its path.
- Parameters:
project (str) – Name of the file or project to load.
- Returns:
- The identifier of the project (1 or higher).
It can be used to select the active project Returns False on error.
- Return type:
The project is activated and initialized after opening.
Example:
>>> project_id = open_project('c:\temp\myproject.emx')
- path()¶
Return the path of the current connected tool
- query_templates()[source]¶
Queries the available Templates
- Parameters:
None –
- Returns:
The information about the templates
- Return type:
TemplateInfo
Example
>>> Templates=query_templates()
- select_template(target_file)[source]¶
Selects and sets a templates
- Parameters:
target_file (str) – the file name of the Target Configuration (TCF) of the template.
- Returns:
True indicates success.
- Return type:
Example:
>>>select_template(‘test’) True
- set_active_model(identifier)[source]¶
Returns name and unique identifier of active model
- Parameters:
Identifier (integer) –
- Returns:
True on success. False on failure.
- Return type:
Example:
>>> set_active_model(1) True
- set_active_target(identifier)[source]¶
Sets the active target
- Parameters:
Identifier (int) – The identifier of the target.
- Returns:
True on success, False on failure.
- Return type:
Example:
>>> targetinfo = set_active_target(1)
- set_log_add_time_stamp(timestamp=True)[source]¶
Set the addTimeStamp property for the log.
- Parameters:
timestamp (bool, optional) – True to add timestamps to log messages. Default is True.
- set_log_file(logname, path, overwrite=False, timestamp=True)[source]¶
Sets the LogFile
- Parameters:
- Returns:
False on failure.
- Return type:
Example:
>>> xxsim4C.set.log_file('test', r'D: emp', True) True
- set_log_filename(filename)[source]¶
Set the file name of the log file.
Args filename (str) : The file name
- set_log_frequency(frequency)[source]¶
Set the log frequency.
- Equivalent of:
self.set_settings(‘log.discreteTimeInterval’, 1 / frequency)
- Parameters:
frequency (float) – The log frequency.
- set_log_omega(omega)[source]¶
Set the log omega.
- Equivalent of:
self.set_settings(‘log.discreteTimeInterval’, 2 * math.pi / omega)
- Parameters:
omega (float) – The log omega.
- set_log_overwrite(overwrite=False)[source]¶
Set the overwrite setting for the log.
- Parameters:
overwrite (bool, optional) – True to overwrite, default is False.
- set_log_sampletime(sampletime)[source]¶
Set the log sampletime.
- Equivalent of:
self.set_settings(‘log.discreteTimeInterval’, sampletime)
- Parameters:
sampletime (float) – The log sampletime.
- set_log_settings(start, finish, sampletime=None, frequency=None, omega=None)[source]¶
Sets the LogFile
- Parameters:
One of sampletime, frequency and omega must be provided. If multiple are provided, the first one in order (sampletime, frequency, omega) will be used.
- Returns:
False on failure.
- Return type:
Example:
>>> log_settings = set_log_settings(0,1,'sampletime'=0.01)
- set_log_show_plot(show_plot=True)[source]¶
Sets the showPlot property for the log.
- Parameters:
show_plot (bool, optional) – True shows the plot with the log results after logging is ready. Default is True.
- set_log_start(start)[source]¶
Set the log start time.
- Equivalent of:
self.set_settings(‘log.starttime’, start)
- Parameters:
start (float) – The log start time.
- set_log_stop(stop)[source]¶
Set the log finish time.
- Equivalent of:
self.set_settings(‘log.finishTime’, stop)
- Parameters:
start (float) – The log finish time.
- set_run_endless(state=False)[source]¶
Set the run endless setting.
Equivalent of: set_settings(‘run.endless’, state)
- Parameters:
state (bool, optional) – Default false (run until finish time.)
- set_run_frequency(frequency)[source]¶
Set the run frequency.
- Equivalent of:
self.set_settings(‘run.discreteTimeInterval’, 1 / frequency)
- Parameters:
frequency (float) – The run frequency.
- set_run_omega(omega)[source]¶
Set the run omega.
- Equivalent of:
self.set_settings(‘run.discreteTimeInterval’, 2 * math.pi / omega)
- Parameters:
omega (float) – The run omega.
- set_run_sampletime(sampletime)[source]¶
Set the run sampletime.
- Equivalent of:
self.set_settings(‘run.discreteTimeInterval’, sampletime)
- Parameters:
sampletime (float) – The run sampletime.
- set_run_settings(start, finish, sampletime=None, frequency=None, omega=None)[source]¶
Sets the LogFile
- Parameters:
Start –
DiscreteTimeInterval (Finish and) –
- Returns:
False on failure.
- Return type:
Example:
>>> set_run_settings('0','1','0.01') True
- set_run_start(start)[source]¶
Set the run start time.
Equivalent of: set_settings(‘run.startTime’, start)
- set_run_stop(stop)[source]¶
Set the run finish time.
Equivalent of: set_settings(‘run.finishTime’, start)
- 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:
- Returns:
True on success, False on failure.
- Return type:
Examples
>>> set_settings(['testsetting1','testsetting2'], ... ['value1','value2']) True
The following are equivalent:
>>> set_settings(['testsetting1'],['value1'])
>>> set_settings('testsetting1','value1')
- set_url(url)[source]¶
Sets the url of the target
- Parameters:
url (string) –
- Returns:
False on failure.
- Return type:
Example:
>>> url = set_url('192.168.1.123')
- set_variable_flag(variables, log, monitor)[source]¶
set flags for logging and monitoring variables
- Parameters:
- Returns:
bool
Example:
>>> Flag=set_variable_flag([var1,var2], ... ['log','monitor'], ... ['True','False'])
- set_variables(names, values, properties=None)¶
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.
properties (list, optional) – list of key-value dicts with optional variable properties
set (If only a single variable is to be) –
object (the name and the) –
strings (can be passed as) –
explicitly (there's no need to) –
lists. (encapsulate them in) –
- Returns:
True on success, False otherwise
- Return type:
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]] ])
controllab.TDMech class¶
- TDMech¶
alias of
TDMechWrapper
- class TDMechWrapper(errorlevel=0)[source]¶
3D Mechanics Editor scripting interface for Python.
This is a Python wrapper for 3D Mechanics’s XML-RPC interface.
- errorlevel¶
The level of errors that should be raised.
- close()¶
Close the application you are connected to.
- close_model(close_window=False)[source]¶
Closes active 3D Mechanics model without saving changes
- Parameters:
close_window (bool, optional) – indicate if the window should be closed if other models are also still open
- Returns:
True when closed properly, False otherwise
- Return type:
Example:
>>> result = tdmech.close_model()
- connect(uri='http://localhost:5680', version='5.1', **kwargs)[source]¶
Create a connection with 3D Mechanics Editor using XML-RPC
- Parameters:
uri (str) – The URI to connect to. Defaults to ‘http://localhost:5680’ for connecting to 3D Mechanics Editor.
- Returns:
True if successful, False otherwise.
Example:
- Return type:
>>> connect('http://localhost:5680') True
- disconnect()¶
Close the connection
- Returns:
True on success.
- Return type:
Example:
>>> disconnect() True
- 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_code()[source]¶
- Generates code for the active model. It uses the current setting in the model
this will change, where we can pass arguments, like filename, option to generate scenerey generate icon, and what kind of icon
- Returns:
The 20-sim submodel filename the code has been generated in submodelname (str): The submodel name used in the scenery export, see scenery argument scenery (str): The 20-sim 3D scenery filename. This can be imported in a 3D animation plot
- Return type:
filename (str)
Example:
>>> result = tdmech.generate_code()
- generate_scenery(filename, submodelname, generateJoints=False)[source]¶
Generates submodel code for the active model.
- Parameters:
- Returns:
True when scenery has been generated properly, False otherwise
- Return type:
Example:
>>> result = tdmech.generate_scenery('myscenery.scn', 'mysubmodelin20sim')
- generate_submodel(filename, currentConfigAsInitial=False, generateIcon=1, iconFilename=None)[source]¶
Generates submodel code for the active model.
- Parameters:
filename (str) – The 20-sim submodel filename for which the code should be generated
currentConfigAsInitial (bool, optional) – should the current configuration be used as initial value
generateIcon (int, optional) – 0=no icon, 1=automatic (raytrace), 2=from file
iconFilename (str, optional) – bitmap file to be used as filename. Only used if generateIcon == 2
- Returns:
True when code has been generated properly, False otherwise
- Return type:
Example:
>>> result = tdmech.generate_submodel('mysubmodel.emx')
- get_design_parameters(parameters=None)[source]¶
Returns a list with the specified design parameters
Args: list of parameters to return. If empty return the full list
- Returns:
- list with a design parameters dict
(when retrieving more than one parameter)
False is returned on a failure
- Return type:
list or None
Examples
To retrieve a list of design parameters you can use:
>>> params = tdmech.get_design_parameters(['Body1.Ixx','Body2.PosX'])
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), for now this is always 1values
: the values of the retrieved parameter(s)unit
: the unit of the retrieved parameters(s)global
: the global boolean of the retrieved parameter(s)
To retrieve a single of parameter you can use
>>> tdmech.get_design_parameters('Body1.Ixx') [{'name': 'Body1.Ixx', 'size': [1], 'values': [1.0]}. 'unit': 'kg', 'global: True]
- 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 modelkinds (str or list of str, optional) –
The kinds of variable requested. Choose one or more from:
constant
parameter
variable
state
rate
initialValue
independentState
dependentState
independentRate
dependentRate
algebraicIn
algebraicOut
constraintIn
constraintOut
discreteState
discreteRate
discreteInitialValue
importVariable
exportVariable
autoAddedVariable
plot
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 variablesize
The size of the variablevalues
list of float The values of the variableproperties
The properties of the variable(s) as list ofkey-value dicts. Possible keys:
parameter, variable
arithmetictype
quantity
unit
unitSymbol
description
multiplicationToSI (since 20-sim 4.8)
attributes (since 20-sim 4.8)
- 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 3D Mechanics instance to 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:
Example:
>>> tdmech.get_version() {'major': 5, 'minor': 0, 'patch': 0, 'build': 10000}
- 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:
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
- open_model(model)[source]¶
Opens a model file from its path.
- Parameters:
model (str) – Name of the file or model to load.
- Returns:
- The identifier of the model (1 or higher).
It can be used to select the active model Returns False on error.
- Return type:
The model is activated and initialized after opening.
Example:
>>> model_id = tdmech.open_model('c:\\temp\\myproject.3dm')
- path()¶
Return the path of the current connected tool
- save_model(filename=None)[source]¶
Saves the changes made to active 3D Mechanics model
- Parameters:
filename (str, optional) – The filename that should be used to save the active model. If omitted, 3D Mechanics Editor will save the model under its current name if it has any.
- Returns:
True on success, False otherwise
- Return type:
Example:
>>> result = tdmech.save_model('c:\\temp\\mymodel.3dm')
- set_STL_file(body_name: str, filename: str, properties: Optional[dict] = None)[source]¶
Set/change the STL representation of a body
- Parameters:
- Returns:
True when the function succeeds, False otherwise
- set_design_parameters(parameters, values=None)[source]¶
Set a list of design parameters
Args: list of parameters to set.
- Returns:
True if the function succeeds
Examples
To set a list of design parameters you can use:
>>> tdmech.set_design_parameters([{'name': 'Body1.Ixx', 'size': [1], 'value': [1.0], 'unit': 'kg', 'global': True}, {'name': 'Body1.Iyy', 'size': [1], 'value': [2.0], 'unit': 'kg', 'global': True}])
To update an existing of parameter you can use
>>> tdmech.set_design_parameters('Body1.Ixx', 1.0) 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:
- Returns:
True on success, False on failure.
- Return type:
Examples
>>> set_settings(['testsetting1','testsetting2'], ... ['value1','value2']) True
The following are equivalent:
>>> set_settings(['testsetting1'],['value1'])
>>> set_settings('testsetting1','value1')
- set_variables(names, values, properties=None)¶
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.
properties (list, optional) – list of key-value dicts with optional variable properties
set (If only a single variable is to be) –
object (the name and the) –
strings (can be passed as) –
explicitly (there's no need to) –
lists. (encapsulate them in) –
- Returns:
True on success, False otherwise
- Return type:
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]] ])