Simulation Scripts
Running simulations from a script allows you to examine the effect of varying parameters or to post-process the simulation results to extract relevant information.
In PLECS Blockset scripts are written in the Matlab environment. Simulink offers a scripting interface to modify parameters and run simulations from a script. A detailed description of the Simulink scripting options is out of the scope of this manual, please refer to the documentation for Simulink instead. PLECS Blockset offers additional commands to control the parameters of PLECS circuits.
PLECS Standalone offers two different scripting methods:
- Scripts can be executed directly in PLECS Standalone. The scripts use a syntax which is very similar to Matlab.
- PLECS offers an XML-RPC interface that allows any other program that can send XML-RPC requests to control PLECS. Many scripting languages support XML-RPC out of the box, for example Python or Ruby. Other scripting language extensions for XML-RPC support are available for free on the internet.
The scripting options for PLECS Standalone are described in section Simulation Scripts in PLECS Standalone.
Command Line Interface in PLECS Blockset
PLECS offers a Command Line Interface (CLI) to access component and circuit parameters from scripts or, in case of PLECS Blockset, also directly from the MATLAB command line. The command syntax is
plecs('cmd', 'parameter1', 'parameter2', ...)
where cmd is one of the following commands: get, set, scope, thermal, export, version, hostid.
Reading and Setting Parameters of Components
The command
plecs('get', 'componentPath')
plecs('get', 'componentPath', 'parameter')
returns the value of parameter of the PLECS component indicated by the componentPath as a string. If parameter is omitted a cell array with all available parameters is returned.
plecs('set', 'componentPath', 'parameter', 'value')
sets the value of parameter of the PLECS component indicated by the componentPath to value.
The special parameter 'CurrentCircuit' can be used to query the path to the current PLECS Circuit. The component path has to be an empty string:
plecs('get', '', 'CurrentCircuit')
This command can only be used in the initialization commands of subsystems.
Handling of Traces in Scopes
plecs('scope', 'scopePath', 'HoldTrace') plecs('scope', 'scopePath', 'HoldTrace', 'traceName')
saves the values of the last simulation run to a new trace in the scope indicated by the scopePath. If given and unique, traceName is used as the name for the new trace, otherwise a default name is assigned. In both cases the method returns the name given to the trace.
plecs('scope', 'scopePath', 'RemoveTrace', 'traceName')
removes the trace named traceName from the scope indicated by the scopePath.
plecs('scope', 'scopePath', 'ClearTraces')
clears all traces in the scope indicated by the scopePath.
plecs('scope', 'scopePath', 'SaveTraces', 'fileName')
Saves the trace data of the scope at scopePath to the file fileName for later reference. The fileName should contain an absolute file path and have the extension '.trace'.
plecs('scope', 'scopePath', 'LoadTraces', 'fileName')
Loads the trace data from the file fileName into the scope at scopePath. The fileName should contain an absolute file path and have the extension '.trace'.
Converting Thermal Descriptions
plecs('thermal', 'import', valVon, valEon, valEoff)
plecs('thermal', 'import', valVon, valEon, valEoff, ...
valCauer)
imports the on-state voltage drop valVon, the switching losses valEon, valEoff and the cauer chain elements valCauer into the thermal editor. The parameter valVon has to be a struct with two index vectors i, T and an output matrix v. The parameters valEon and valEoff have to be structs with three index vectors v, i, T and an output array E. The optional argument valCauer has to be a struct with two array elements, C and R. The command can be used to import thermal descriptions as used in PLECS 1.x into the thermal library of PLECS 2.x and later.
plecs('thermal', 'export', 'filename')
reads the thermal data sheet from filename and returns a struct with the fields Von, Eon, Eoff, CauerChain and Comment containing the respective data from the thermal data sheet. The parameter filename has to be an absolute filename to the data sheet including the .xml extension.
plecs('thermal', 'export', 'filename', 'modelName')
reads the thermal data sheet from filename and returns a struct with the fields Von, Eon, Eoff, CauerChain and Comment containing the respective data from the thermal data sheet. The parameter filename has to be a relative filename to the data sheet without the .xml extension.
Export for PLECS Viewer
plecs('export', 'modelName')
plecs('export', 'modelName', hideSchematics)
plecs('export', 'modelName', hideSchematics, 'filename')
exports the model modelName for the PLECS Viewer. By setting the optional argument hideSchematics to true all PLECS circuits are marked as non-viewable. If argument filename is given it is used as the exported model's filename, otherwise you are prompted for a filename.
Other CLI Commands
To retrieve the version information from PLECS as a string, enter
plecs('version')
To retrieve a struct with host ID and MATLAB license information, enter
plecs('hostid')
To check out a license for PLECS, enter
[success, message] = plecs('checkout')
If the check-out succeeds, the return variable success will be set to 1 and message will be an empty string. Else, success will be set to 0 and message will contain a detailed error message. When called without left-hand side arguments, the command will raise a MATLAB error upon an unsuccessful check-out and else execute silently.
Examples
Some examples for using the command line interface in PLECS Blockset:
plecs('get', 'mdl/Circuit1')
returns the parameters of Circuit1 in the simulink model mdl.
plecs('get', 'mdl/Circuit1', 'Name')
returns the name of Circuit1.
plecs('get', 'mdl/Circuit1', 'CircuitModel')
returns the circuit simulation method of Circuit1.
plecs('get', 'mdl/Circuit1/R1')
returns the parameters of component R1 in circuit Circuit1.
plecs('set', 'mdl/Circuit1/R1', 'R', '2')
sets the resistance of component R1 in circuit Circuit1 to 2.
plecs('export', 'mdl', true, 'exported.mdl')
exports the model mdl to the model file exported.mdl which can be opened with the PLECS Viewer. The contents of all PLECS schematics are hidden.
data =
plecs('thermal', 'export', 'Infineon/SDP04S60', ...
'plSMPS_CCM')
assigns the thermal description from library element Infineon/SDP04S60 in model plSMPS_CCM to the variable data in the MATLAB workspace.
Simulation Scripts in PLECS Standalone
Simulation scripts are managed in the Simulation Scripts dialog shown below. To open the dialog, select Simulation scripts... from the Simulation menu of the schematic editor.
The left hand side of the dialog window shows a list of the scripts that are currently configured for the model. To add a new script, click the button marked + below the list. To remove the currently selected script, click on the button marked -. You can reorder the scripts by clicking and dragging an entry up and down in the list.
The right hand side of the dialog window shows the script in an editor window. Each script must have a unique Description.
The button Run/Stop starts the currently selected script or aborts the script that is currently running.
To make changes to the script without running it, press the Accept button. The Revert button takes back any changes that have been made after the Accept or Run button was pressed.
PLECS Standalone uses GNU Octave to execute simulation scripts. The Octave language is very similar to Matlab. A full syntax description of the Octave scripting language is available in the Octave documentation.
Overview of PLECS Scripting Extensions
In addition to generic Octave commands you can use the following commands to control PLECS from within a simulation script.
Reading and Setting Component Parameters
The command
plecs('get', 'componentPath')
plecs('get', 'componentPath', 'parameter')
returns the value of parameter of the PLECS component indicated by the componentPath as a string. If parameter is omitted a struct array with all available parameters is returned.
plecs('set', 'componentPath', 'parameter', 'value')
sets the value of parameter of the PLECS component indicated by the componentPath to value.
The special parameter 'CurrentCircuit' can be used to query the name of the model that contains the script which is currently executed. The component path has to be an empty string:
plecs('get', '', 'CurrentCircuit')
This command is useful for constructing a component path that does not depend on the model name.
Handling of Traces in Scopes
plecs('scope', 'scopePath', 'HoldTrace')
plecs('scope', 'scopePath', 'HoldTrace', 'traceName')
saves the values of the last simulation to a new trace in the scope indicated by the scopePath. If given and unique, traceName is used as the name for the new trace, otherwise a default name is assigned. In both cases the method returns the name given to the trace.
plecs('scope', 'scopePath', 'RemoveTrace', 'traceName')
removes the trace named traceName from the scope indicated by the scopePath.
plecs('scope', 'scopePath', 'ClearTraces')
clears all traces in the scope indicated by the scopePath.
plecs('scope', 'scopePath', 'SaveTraces', 'fileName')
Saves the trace data of the scope at scopePath to the file fileName for later reference. The fileName should contain an absolute file path and have the extension '.trace'.
plecs('scope', 'scopePath', 'LoadTraces', 'fileName')
Loads the trace data from the file fileName into the scope at scopePath. The fileName should contain an absolute file path and have the extension '.trace'.
The scopePath is the path to the scope within the model including the model name, e.g. 'DTC/Mechanical'. To access Bode plots from the analysis tools, use the model name followed by '/Analyses/' followed by the name of the analysis, e.g. 'BuckOpenLoop/Analyses/Control to Output TF (AC Sweep)'.
Starting a Simulation
plecs('simulate')
plecs('simulate', optStruct)
starts a simulation. The optional argument optStruct can be used to override model parameters; for detailed information see section Scripted Simulation and Analysis Options.
If any outports exist on the top level of the simulated model, the command returns a struct consisting of two fields, Time and Values. Time is a vector that contains the simulation time for each simulation step. The rows of the array Values consist of the signal values at the outports. The order of the signals is determined by the port numbers.
Starting an Analysis
plecs('analyze', 'analysisName')
plecs('analyze', 'analysisName', optStruct)
starts the analysis defined in the Analysis Tools dialog under the name analysisName. The optional argument optStruct can be used to override model parameters; for detailed information see section Scripted Simulation and Analysis Options.
For a Steady-State Analysis, if any outports exist on the top level of the simulated model, the command returns a struct consisting of two fields, Time and Values as described above. The signal values at the outports are captured after a steady-state operating point has been obtained.
For an AC Sweep or an Impulse Response Analysis, the command returns a struct consisting of three fields, F, Gr and Gi. F is a vector that contains the perturbation frequencies of the analysis. The rows of the arrays Gr and Gi consist of the real and imaginary part of the transfer function as defined in the analysis.
Example Script
The following script runs a parameter sweep by setting the variable varL to the values in inductorValues. It is used in the demo model BuckParamSweep.
scope = [mdl '/Scope'];
mdlVars = struct('varL', 50e-6);
opts = struct('ModelVars', mdlVars);
plecs('scope',scope, 'ClearTraces');
inductorValues = [50, 100, 200];
for ix = 1:length(inductorValues)
opts.ModelVars.varL=inductorValues(ix) * 1e-6;
out = plecs('simulate', opts);
plecs('scope', scope, 'HoldTrace', ...
['L=' mat2str(inductorValues(ix)) 'uH']);
[maxv, maxidx] = max(out.Values(1,:));
printf('Max current for L=%duH: %f at %fs\n', ...
inductorValues(ix), maxv, out.Time(maxidx));
end
The first two lines construct the path to the component Scope. By using the CurrentCircuit to build the path the script does not depend on a specific model name.
The next two lines create a struct ModelVars with one field, varL. The struct is embedded into another struct named opts, which will be used later to initialize the simulation parameters.
Inside of the for-loop each value of inductorValues is assigned successively to the structure member variable varL. A new simulation is started, the result is saved in variable out for post-processing. By holding the trace in the scope the scope output will remain visible when a new simulation is started. The name of the trace is the inductance value.
The script then searches for the peak current in the simulation results and outputs the value and the time, at which it occurred, in the Octave Console.
XML-RPC Interface in PLECS Standalone
The XML-RPC interface allows you to control PLECS Standalone from an external program. PLECS acts as an XML-RPC server which processes requests from an XML-RPC client.
XML-RPC is a lightweight protocol that is supported by numerous scripting languages. For the following description, Python 2.x syntax and script excerpts are used.
Establishing an XML-RPC Connection to PLECS
The XML-RPC interface in PLECS is disabled by default. It must be enabled in the PLECS preferences before a connection can be established. The TCP port to use can also be configured in the PLECS preferences.
The following Python code initiates an XML-RPC connection to PLECS:
import xmlrpclib
server = xmlrpclib.Server("http://localhost:1080/RPC2")
The code assumes that PLECS is configured to use TCP port 1080 for XML-RPC. Note that the URL must end with "/RPC2", which is an XML-RPC convention.
Note XML-RPC connections to PLECS are only allowed from clients running on the same machine as PLECS. Therefore, the connection should always be initiated using localhost in the server URL.
Overview of XML-RPC Commands
Commands for PLECS start with plecs followed by a dot. In Python they are invoked on the server object, for example
server.plecs.load("myModel.plecs")
Opening and Closing a Model
The command
plecs.load('mdlFileName')
opens the model with the given mdlFileName. The filename should contain the absolute path to the file.
The command
plecs.close('mdlName')
closes the model with the given name. The model will be closed unconditionally without being saved, even when changes have been made.
Reading and Setting Component Parameters
The command
plecs.get('componentPath')
plecs.get('componentPath', 'parameter')
returns the value of parameter of the PLECS component indicated by the componentPath as a string. If parameter is omitted a struct array with all available parameters is returned.
plecs.set('componentPath', 'parameter', 'value')
sets the value of parameter of the PLECS component indicated by the componentPath to value.
Handling of Traces in Scopes
plecs.scope('scopePath', 'HoldTrace')
plecs.scope('scopePath', 'HoldTrace', 'traceName')
saves the values of the last simulation to a new trace in the scope indicated by the scopePath. If given, traceName is used as the name for the new trace, otherwise a default name is assigned.
plecs.scope('scopePath', 'RemoveTrace', 'traceName')
removes the trace named traceName from the scope indicated by the scopePath.
plecs.scope('scopePath', 'ClearTraces')
clears all traces in the scope indicated by the scopePath.
plecs.scope('scopePath', 'SaveTraces', 'fileName')
Saves the trace data of the scope at scopePath to the file fileName for later reference. The fileName should contain an absolute file path and have the extension '.trace'.
plecs.scope('scopePath', 'LoadTraces', 'fileName')
Loads the trace data from the file fileName into the scope at scopePath. The fileName should contain an absolute file path and have the extension '.trace'.
The scopePath is the path to the scope within the model including the model name, e.g. 'DTC/Mechanical'. To access Bode plots from the analysis tools, use the model name followed by '/Analyses/' followed by the name of the analysis, e.g. 'BuckOpenLoop/Analyses/Control to Output TF (AC Sweep)'.
Starting a Simulation
The command
plecs.simulate('mdlName')
plecs.simulate('mdlName', optStruct)
starts a simulation of the model named mdlName. The optional argument optStruct can be used to override model parameters; for detailed information see section Scripted Simulation and Analysis Options.
If any outports exist on the top level of the simulated model, the command returns a struct consisting of two fields, Time and Values. Time is a vector that contains the simulation time for each simulation step. The rows of the array Values consist of the signal values at the outports. The order of the signals is determined by the port numbers.
Starting an Analysis
The command
plecs.analyze('mdlName', 'analysisName')
plecs.analyze('mdlName', 'analysisName', optStruct)
starts the analysis named analysisName in the model named mdlName. The optional argument optStruct can be used to override model parameters; for detailed information see section Scripted Simulation and Analysis Options.
For a Steady-State Analysis, if any outports exist on the top level of the simulated model, the command returns a struct consisting of two fields, Time and Values as described above. The signal values at the outports are captured after a steady-state operating point has been obtained.
For an AC Sweep or an Impulse Response Analysis, the command returns a struct consisting of three fields, F, Gr and Gi. F is a vector that contains the perturbation frequencies of the analysis. The rows of the arrays Gr and Gi consist of the real and imaginary part of the transfer function as defined in the analysis.
Example Script
The following Python script establishes an XML-RPC connection, loads a model and simulates it twice. The scope output from each simulation is preserved by holding the traces in the scope.
server = xmlrpclib.Server("http://localhost:1080/RPC2")
server.plecs.load("C:/Models/BuckParamSweep.plecs")
server.plecs.scope('BuckParamSweep/Scope', 'ClearTraces')
opts = {'ModelVars' : { 'varL' : 50e-6 } }
result = server.plecs.simulate("BuckParamSweep", opts)
server.plecs.scope('BuckParamSweep/Scope',
'HoldTrace', 'L=50uH')
opts['ModelVars']['varL'] = 100e-6;
result = server.plecs.simulate("BuckParamSweep", opts)
server.plecs.scope('BuckParamSweep/Scope',
'HoldTrace', 'L=100uH')
Scripted Simulation and Analysis Options
When you start a simulation or analysis from a Simulation Script or via XML-RPC, you can pass an optional argument optStruct in order to override parameter settings defined in the model. This enables you to run simulations for different scenarios without having to modify the model file.
The argument optStruct is a struct that may contain the fields ModelVars, SolverOpts and - when starting an analysis - AnalysisOpts, which are again structs as described below.
ModelVars The optional field ModelVars is a struct variable that allows you to override variable values defined by the model initialization commands. Each field name is treated as a variable name; the field value is assigned to the corresponding variable.
The override values are applied after the model initialization commands have been evaluated and before the component parameters are evaluated as shown in the figure below.
Execution order for Simulation Scripts (left) and XML-RPC (right)
SolverOpts The optional field SolverOpts is a struct variable that allows you to override the solver settings specified in the Simulation Parameters dialog. Each field name is treated as a solver parameter name; the field value is assigned to the corresponding solver parameter. The following table lists the possible parameters.
Parameter | Description |
Solver | The solver to use for the simulation. Possible values are dopri for a non-stiff variable step solver, radau for a stiff variable step solver and discrete for a fixed step solver. See section Standalone Parameters for more details. |
StartTime | The start time specifies the initial value of the simulation time variable t at the beginning of a simulation, in seconds. |
StopTime | The simulation ends when the simulation time has advanced to the specified stop time. |
MaxStep | See parameter Max Step Size in section Standalone Parameters. This parameter is only evaluated for variable step solvers. |
InitStep | See parameter Initial Step Size in section Standalone Parameters. This parameter is only evaluated for variable step solvers. |
FixedStep | This parameter specifies the fixed time increments for the solver and also the sample time used for the state-space discretization of the physical model. It is only evaluated for the fixed step solver. |
AbsTol | See the description for Tolerances in section Standalone Parameters. |
RelTol | See the description for Tolerances in section Standalone Parameters. |
Refine | See parameter Refine factor in section Standalone Parameters. |
AnalysisOpts For an analysis the optional field AnalysisOpts is a struct variable that allows you to override the analysis settings defined in the Analysis Tools dialog. Each field name is treated as an analysis parameter name, the field value is assigned to the corresponding analysis parameter. The following tables list the possible parameters
Parameter | Description |
TimeSpan | System period length; this is the least common multiple of the periods of independent sources in the system. |
StartTime | Simulation start time. |
Tolerance | Relative error tolerance used in the convergence criterion of a steady-state analysis. |
MaxIter | Maximum number of iterations allowed in a steady-state analysis. |
JacobianPerturbation | Relative perturbation of the state variables used to calculate the approximate Jacobian matrix. |
JacobianCalculation | Controls the way the Jacobian matrix is calculated (full, fast). The default is fast. |
InitCycles | Number of cycle-by-cycle simulations that should be performed before the actual analysis. This parameter can be used to provide the initial steady-state analysis with a better starting point. |
ShowCycles | Number of steady-state cycles that should be simulated at the end of an analysis. This parameter is evaluated only for a steady-state analysis. |
FrequencyRange | Range of the perturbation frequencies. This parameter is evaluated only for a small-signal analysis. |
FrequencyScale | Specifies whether the sweep frequencies should be distributed on a linear or logarithmic scale. This parameter is evaluated only for a small-signal analysis. |
AdditionalFreqs | A vector specifying frequencies to be swept in addition to the automatically distributed frequencies. This parameter is evaluated only for a small-signal analysis. |
NumPoints | The number of automatically distributed perturbation frequencies. This parameter is evaluated only for a small-signal analysis. |
Perturbation | The full block path (excluding the model name) of the Small Signal Perturbation block that will be active during an analysis. This parameter is evaluated only for a small-signal analysis. |
Response | The full block path (excluding the model name) of the Small Signal Response block that will record the system response during an analysis. This parameter is evaluated only for a small-signal analysis. |
AmplitudeRange | The amplitude range of the sinusoidal perturbation signals for an ac sweep. This parameter is evaluated only for an ac sweep. |
Amplitude | The amplitude of the discrete pulse perturbation for an impulse response analysis. This parameter is evaluated only for an impulse response analysis. |