How PLECS Works
PLECS is a software package for modeling and simulating dynamic systems. As with any other software package, in order to make the best use of it you should have a basic understanding of its working principles. Before delving into the question how PLECS works, however, it is worthwhile to distinguish between the terms modeling and simulation.
The term modeling refers to the process of extracting knowledge from the system to be simulated and representing this knowledge in some formal way. The second part – i.e. the representation of knowledge – can be more or less straightforward depending on the formalism used. PLECS offers three different formalisms – equations (implemented as C-code), block diagrams and physical models – that can be used in the same modeling environment. They are described in the following section.
The term simulation refers to the process of performing experiments on a model in order to predict how the real system would behave under the same conditions. More specifically, in the context of PLECS, it refers to the computation of the trajectories of the model’s states and outputs over time by means of an ordinary differential equation (ODE) solver. This is described in the second section.
Modeling Dynamic Systems
A system can be thought of as a black box as depicted in Fig. 21. The system does not exchange energy with its environment but only information: It accepts input signals \(u\), and its reactions can be observed by the output signals \(y\).
Fig. 21 Example of a dynamic system
A system can have internal state variables that store information about the system’s past and influence its current behavior. Such state variables can be continuous, i.e. they are governed by differential equations, or discrete, i.e. they change only at certain instants. An example of a continuous state variable is the flux or current of an inductor; an example of a discrete state variable is the state of a flip flop.
System Equations
One way to describe a system is by mathematical equations. Typical system equations are listed below:
An output function describes the system’s outputs in terms of the current time, the system’s inputs and its internal states.
If the system has discrete states, an update function determines if and how they change at a given time for the current inputs and internal states.
If the system has continuous states, a derivative function describes their derivatives with respect to time.
Symbolically, these functions can be expressed as follows:
Such a description is most convenient for implementation in a procedural programming language like C.
Block Diagrams
A more graphic modeling method that is commonly used in control engineering is a block diagram such as the one in Fig. 22, which shows a low pass filter.
Fig. 22 Block diagram implementation of a low pass filter
Each of the three blocks is again a dynamic system in itself, that can be described with its own set of system equations. The blocks are interconnected with directed lines to form a larger system. The direction of the connections determines the order in which the equations of the individual blocks must be evaluated.
Physical Models
Block diagrams are very convenient to model control structures where it is clear what the input and output of a block should be. This distinction is less clear or impossible for physical systems.
For instance, an electrical resistor relates the quantities voltage and current according to Ohm’s law. But does it conduct a current because a voltage is applied to it, or does it produce a voltage because a current is flowing through it? Whether the first or the second formulation is more appropriate depends on the context, e.g. whether the resistor is connected in series with an inductor or in parallel with a capacitor. This means that it is not possible to create a single block that represents an electrical resistor.
Therefore, block diagrams with their directed connections are usually not very useful for modeling physical systems. Physical systems are more conveniently modeled using schematics in which the connections between individual components do not imply a computational order.
PLECS currently supports physical models in the electrical, magnetic, mechanical and thermal domains (in the form of lumped parameter models).
Simulating Dynamic Systems
A simulation is performed in two phases – initialization and execution – that are described in this section.
From the Simulation menu, you can run a complete simulation, via Start, or the initialization phase only, via Evaluate Parameters.
Model Initialization
Physical Model Equations
PLECS first sets up the system equations for the physical model according to e.g. Kirchhoff’s current and voltage laws. If the physical model contains only ideal linear and/or switching elements, it can be described by a set of piece-wise linear state-space equations:
The subscript \(\sigma\) is due to the fact that each state-change of a switching element leads to a new set of state-space matrices.
The complete physical model is thus represented by a single, atomic subsystem. The following figure shows the interaction between the physical subsystem, the surrounding block diagram and the ODE solver.
Fig. 23 Switched state-space implementation
The physical subsystem accepts external input signals for controllable sources and for switching elements and it provides an output signal containing the values of physical measurements. During the simulation, the derivatives of the physical state variables are calculated and handed over to the solver which in turn calculates the momentary values of these state variables.
The Switch Manager monitors the gate signals and the internal measurements and decides whether a switching action is necessary. The Switch Manager also provides auxiliary signals – so-called zero-crossing signals – to the solver for proper location of the exact instants when a switching should occur.
A flowchart of the Switch Manager is shown in the figure below. In every simulation step, after the physical measurements have been calculated, the Switch Manager evaluates the switching conditions of all switches in the physical model. If a switching action is necessary, it initiates the calculation of a new set of state-space matrices or fetches a previously calculated set from a cache. Afterwards, it recalculates the physical measurements with the new state-space matrices to check whether further switching actions of naturally commutated devices are required. It will iterate through this process until all switches have reached a stable position. If a set of switch states \(\sigma\) is encountered repeatedly in this process, PLECS is unable to determine stable conditions and aborts the simulation.
Fig. 24 Switch Manager flowchart
Block Sorting
After the setup of the physical model, PLECS determines the execution order of the block diagram. As noted above, the physical model is treated as a single atomic subsystem of the block diagram. The execution order is governed by the following computational causality:
If the output function of a block depends on the current value of one or more input signals, the output functions of the blocks that provide these input signals must be evaluated first.
Direct feedthrough
The property of an input port whether or not its current signal values are required to compute the output function is called direct feedthrough. For example, the output function of a linear gain is
and so the input signal of the gain has direct feedthrough. In contrast, the output function of an integrator is
i.e. the integrator just outputs its current state regardless of the current input. The integrator input therefore does not have direct feedthrough.
Algebraic loops
An algebraic loop is a group of one or more blocks that are connected in a circular manner, so that the output of one block is connected to a direct feedthrough input of the next one.
For such a group it is impossible to find a sequence in which to compute their output functions because each computation involves an unknown variable (the output of the previous block). Instead, the output functions of these blocks must be solved simultaneously. PLECS uses a Newton-type equation solver for this purpose. Since the solver performs iterations in order to find a solution consistent with all blocks, models with algebraic loops may run more slowly than models without algebraic loops. Failure to find a solution brings the simulation to a halt with an error message.
See Simulation Parameters for a list of parameters that influence the solution of algebraic loops.
The block Initial Condition can be used to provide a guess to the equation solver at the start of a simulation.
Model Execution
Fig. 25 illustrates the workflow of the actual simulation.
Fig. 25 Simulation loop
Main Loop
The main simulation loop – also called a major time step – consists of two actions:
The output functions of all blocks are evaluated in the execution order that was determined during block sorting. If a model contains scopes, they will be updated at this point.
The update functions of blocks with discrete state variables are executed to compute the discrete state values for the next simulation step.
Depending on the model and the solver settings, the solver may enter one or both of the following minor loops.
Integration Loop
If a model has continuous state variables, it is the task of the solver to numerically integrate the time derivatives of the state variables (provided by the model) in order to calculate the momentary values of the states variables.
Depending on the solver algorithm, an integration step is performed in multiple stages – also called minor time steps – in order to increase the accuracy of the numerical integration. In each stage the solver calculates the derivatives at a different intermediate time. Since the derivative function of a block can depend on the block’s inputs – i.e. on other blocks’ outputs – the solver must first execute all output functions for that particular time.
Having completed an integration step for the current step size, a variable-step solver checks whether the local integration error remains within the specified tolerance. If not, the current integration step is discarded and a new integration is initiated with a reduced step size.
Event Detection Loop
If a model contains discontinuities, i.e. instants at which the model behavior changes abruptly, it may register auxiliary event functions to aid a variable-step solver in locating these instants. Event functions are block functions and are specified implicitly as zero-crossing functions depending on the current time and the block’s inputs and internal states.
For instance, if a physical model contains a diode, it will register two event functions, \(f_\mathrm{turn~on} = v_D\) and \(f_\mathrm{turn~off} = i_D\), depending on the diode voltage and current, so that the solver can locate the exact instants at which the diode should turn on and off.
If one or more event functions change sign during the current simulation step, the solver performs a bisection search to locate the time of the first zero-crossing. This search involves the evaluation of the event functions at different intermediate times. Since the event function of a block – like the derivative function – can depend on the block’s inputs, the solver must first execute all output functions for a particular time. Also these intermediate time steps are called minor time steps.
Having located the first event, the solver will reduce the current step size so that the next major time step is taken just after the event.
Fixed-Step Simulation
As indicated in the previous paragraphs, certain important aspects of the minor simulation loops require a variable-step solver that can change its step size during a simulation. Using a solver with a fixed step size has two serious implications.
Integration Error:
A fixed-step solver does not have any control over the integration error. The integration error is a function of the model time constants, the step size and the integration method. The first parameter is obviously given by the model, but the second and possibly the third parameter must be provided by the user. One strategy for determining an appropriate step size is to iteratively run simulations and reduce the step size until the simulation results stabilize.
Event Handling:
Discontinuities in a physical model – such as the turn-on or turn-off of a diode or the transition from static to dynamic friction – typically do not coincide with a fixed simulation step. Postponing such non-sampled events until the following fixed simulation step will produce jitter and may lead to subsequent runtime errors, e.g. because a physical state variable becomes discontinuous.
For these reasons it is generally recommended to use a variable-step solver.
Physical Model Discretization
In order to mitigate the problems due to non-sampled events, PLECS transforms the physical model into a discrete state-space model when it is simulated with a fixed-step solver. The continuous state-space equations of the electrical and magnetic domains are discretized and replaced with the following update rule:
By default, a first-order hold is applied to the input signals, i.e. it is assumed that the inputs change linearly from \(\mathbf{u}_{n-1}\) in the previous step to \(\mathbf{u}_{n}\) in the current step. As a consequence, the inputs of the electro-magnetic model now have direct feedthrough because their current values must be known before the current model states and the model output can be calculated. This will result in an algebraic loop if the value of a controlled voltage or current source depends on a measurement in the electro-magnetic model.
To avoid this problem, the Current Source (Controlled) and the Voltage Source (Controlled) can be configured to apply a zero-order hold on the input signal when the model is discretized. In this case only the input value from the previous simulation step \(u^{(i)}_{n-1}\) is required to calculate the current state values.
By default, the discrete state-space matrices \(\mathbf{A}_\mathrm{d}\), \(\mathbf{B}_\mathrm{d1}\) and \(\mathbf{B}_\mathrm{d2}\) are calculated from the continuous matrices \(\mathbf{A}\) and \(\mathbf{B}\) using a fifth-order accurate fully-implicit three-stage Runge-Kutta formula (Radau IIA). Alternatively, the bilinear transformation known as Tustin’s method can be chosen. It is only 2nd order accurate and has poor damping characteristics for time constants that are smaller than the discretization step size, but it is cheaper to compute because \(\mathbf{B}_\mathrm{d1}\) equals \(\mathbf{B}_\mathrm{d2}\). Therefore, it can be useful for real-time simulations where the calculation time is essential. The discretization method can be chosen in the Simulation Parameters dialog.
Note that this applies only to the discretization of physical domains. The state variables from the control block diagram are integrated with Euler’s method.
Interpolation of Non-Sampled Switching Events
With the physical model discretized like this, non-sampled switching events can be handled efficiently using the following algorithm:
Check whether the solver has stepped over a non-sampled switching event in the last simulation step.
If so, determine the time of the event and calculate the model state just after the event using linear interpolation and handle the event, i.e. toggle one or more switches.
Perform one full forward step.
Linearly interpolate the model states back to the actual simulation time.
This algorithm is illustrated using the example of a half-wave rectifier shown below. The two graphs show the commutation of the dc current from diode D3 (shown in gray) to diode D1 (shown in black). The solid lines show the results from a simulation with a variable-step solver, large dots mark the steps of the fixed-step simulation, and small dots mark the internal interpolation steps.
Commutation starts when the voltage across D1 becomes positive. The fixed-step solver first steps well beyond the zero-crossing of the voltage (1). PLECS then internally steps back to the zero-crossing (2) and turns on D1. With the new set of state-space equations, it performs an internal full step forward (3) and then interpolates back to the actual simulation time (4). Next, the solver steps beyond the zero-crossing of the current through D3 (1). Again, PLECS internally steps back to the zero-crossing (2) and turns off D3. With the new set of state-space equations, it performs an internal full step forward (3) and then interpolates back to the actual simulation time (4).
Fig. 26 Interpolation of non-sampled switching events
Note that without this interpolation scheme, D3 would have been turned off at point (1). This would have caused the current through the inductor in phase 3 to become discontinuous. Such a non-physical behavior can lead to gross simulation errors and should therefore be avoided.
Sampled Data Systems
PLECS allows you to model sampled data systems, i.e. discrete systems that change only at distinct times. You can model systems that are sampled periodically or at variable intervals, systems that contain blocks with different sample rates, and systems that mix continuous and discrete blocks.
Sample Times
Sample times are assigned on a per-block basis. Some blocks may have more than one sample time, and they may associate assign different sample times to different input or output terminals. PLECS distinguishes between the following sample time types:
- Continuous
A continuous sample time is used for blocks that must be updated in every major and minor time step. This includes all blocks that have continuous state variables, such as the Integrator or Transfer Function.
- Semi-Continuous
A semi-continuous sample time is used for blocks that must be updated in every major time step but whose output does not change during minor time steps. This applies for instance to the Memory block, which always outputs the input value of the previous major time step.
- Discrete-Periodic
A periodic sample time is used for blocks that are updated during major time steps at regular intervals.
- Discrete-Variable
A variable sample time is used for blocks that must be updated during major time steps at variable intervals which are specified by the blocks themselves.
- Inherited
An inherited sample time is used for blocks that do not have a sample time of their own but may adopt the sample time from other blocks connected to them. This includes blocks such as Gain, Sum and Product.
- Constant
A constant sample time is used for blocks that are updated only once at the beginning of a simulation. The only block that explicitly uses a constant sample time is the Constant block. However, other blocks may inherit a constant sample time.
For most block types the sample time is automatically assigned. Discrete blocks and the C-Script block have a parameter Sample Time allowing you to specify the sample time explicitly. A sample time is specified as a two-element vector consisting of the sample period and an offset time. The offset time can be omitted if it is zero.
The table below lists the different sample time types and their corresponding parameter values.
Type |
Value |
|
|---|---|---|
Continuous |
|
|
Semi-Continuous |
|
|
Discrete-Periodic |
|
|
Discrete-Variable |
|
|
Inherited |
|
|
Constant |
|
Sample Time Inheritance
For blocks with an inherited sample time, PLECS employs the following propagation scheme to determine an appropriate sample time:
Propagate the sample times forward along the block execution order (see Block Sorting). A block with an inherited sample time will be assigned a sample time based on the sample times of the blocks that are connected to the block’s inputs.
Propagate the sample times backward along the block execution order. A block with an inherited sample time will be assigned a sample time based on the sample times of the blocks that are connected to the block’s outputs.
Loop until there are no inherited sample times left or until no inherited sample time can be resolved.
Sample times are assigned according to the following rules:
If any sample time is inherited, the block sample time also remains inherited.
Else, if all sample times are constant, the block sample time is set to constant.
Else, if any sample time is continuous, the block sample time is set to continuous.
Else, if all sample times are fixed-step discrete or constant and the fastest sample time is a valid base sample time of the other non-constant sample times, the block sample time is set to the fastest sample time.
Else, the block sample time is set to semi-continuous.
Any block sample time that cannot be resolved using this propagation scheme is set to continuous.
Continuous Sample Time Conflicts
A continuous sample time conflict arises when a continuous signal is fed into a block that expects a discrete input or when a discrete signal is fed into a block that expects a continuous input. Such a situation typically indicates a modeling error that produces undesirable results.
- Example 1
A user attempts to break an algebraic loop by inserting a Memory block. This is problematic if the loop involves a continuous-time signal because Memory is a discrete block and converts the continuous signal into a piece-wise constant signal. It also introduces a variable-step delay when used with a variable-step solver. In order to mitigate the negative effects of this, the user may be tempted to limit the maximum step size of the variable-step solver or switch to the fixed-step solver with a small time step, which leads to very long simulation times.
The proper way to break a continuous algebraic loop is by inserting a continuous low pass filter.
- Example 2
A user attempts to produce phase-shifted gate signals for an interleaved converter with a Transport Delay block. This is problematic because Transport Delay is a continuous block and produces the delayed output signal by interpolating between past samples of the input signal. A rectangular input signal is thus converted into a trapezoidal signal where the slope depends on the solver step size. Again, they user may be tempted to limit the maximum step size of the variable-step solver or switch to the fixed-step solver with a small time step.
The proper block to delay a rectangular or any other discrete signal is the Pulse Delay.
PLECS will detect such continuous sample time conflicts and flag an appropriate diagnostic warning or error. This is controlled with the solver option Continuous sample time conflict on the Diagnostics tab of the Simulation Parameters dialog.
Multirate Systems
Systems that contain blocks with multiple different discrete-periodic sample times are called multirate systems. For such systems, PLECS calculates a base sample time as the greatest common divisor of the periods and offsets of the individual sample times. The individual periods and offsets are then expressed as integer multiples of the base sample time.
This is necessary in order to avoid synchronization problems between blocks with different sample times that would occur when the sample hits are calculated using floating-point arithmetic. For instance, in double precision floating-point arithmetic 3*1e-4 is not equal to 3e-4 (even though the difference is only about \(5.4\times10^{-20}\)).
In order to find the greatest common divisor, PLECS may slightly adjust individual sample periods or offsets within a relative tolerance of approximately \(\pm 10^{-8}\). PLECS does not allow the base sample time to become smaller than \(10^{-6}\) times the largest sample period in order to avoid overflows in the integer arithmetic.
Troubleshooting
If PLECS fails to find an appropriate base sample time, it will show a corresponding error message. There are three possibilities to resolve the problem:
Adjusting the sample times:
Adjust the sample times of the individual blocks in the system so that PLECS can find a base sample time within the above constraints. Whenever possible, specify sample times as rational numbers instead of decimal fractions. For instance, for a block that is sampled with a frequency of \(30\,\mathrm{kHz}\) enter
1/30e3instead of3.3333e-5.Allow multiple base sample times:
You can allow PLECS to use different base sample rates for different groups of block sample times. To do so, uncheck the option Use single base sample rate in the simulation parameters dialog. Only block sample times within the same group are then guaranteed to be synchronized with each other.
Disable sample time synchronization:
You can disable the sample time synchronization altogether by unchecking the option Synchronize fixed-step sample times in the simulation parameters dialog. This is generally not recommended.
The last two options are only available when using a continuous state-space model with a variable-step solver.
Data Types
PLECS can use different data types to store the value of a signal. Boolean, integer and floating-point data types are listed in the table below. Additionally fixed-point data types are supported (see next section).
Name |
Description |
|---|---|
|
Boolean |
|
Unsigned 8-bit integer |
|
Signed 8-bit integer |
|
Unsigned 16-bit integer |
|
Signed 16-bit integer |
|
Unsigned 32-bit integer |
|
Signed 32-bit integer |
|
Single-precision floating point |
|
Double-precision floating point |
|
A pseudo data type that resolves to single-precision or double-precision floating point depending on the simulation target. For normal simulations and when using the PLECS Blockset Coder, this type resolves to |
Fixed-Point Data Types
PLECS supports signed and unsigned fixed-point numbers with a word length of 8, 16 or 32 bits. The scaling and interpretation of the fixed-point value is defined by the number of fractional bits. The results of arithmetic operations are rounded to the closest representable number in direction of negative infinity (two’s complement truncation).
When you select a Fixed-point number data type, additional control elements appear. The signedness and word length are set by selecting the base data type from the combo box. The number of fractional bits can be specified with the spin box. The resulting range and precision of the current settings are displayed underneath.
A fixed-point data type can also be passed with a reference variable by specifying its properties as a structure. E.g. struct('Signed', 1, 'WordLength', 32, 'FractionLength', 16) specifies a signed 32-bit fixed-point data type with 16 fractional bits.
Setting the global model parameter Use floating-point data type for fixed-point signals (see Simulation Parameters) overwrites all fixed-point data types with the target floating-point data type. This can be used to easily compare the accuracy of fixed-point operations with floating-point operations.
Blocks with an Implicit Output Data Type
Certain blocks have an implicit output data type. For instance, all physical meters use the target output type, and a logical operator always outputs a Boolean signal. Other blocks with implicit output data types are listed below:
Comparator,
boolCompare to Constant,
boolEdge Detection,
boolFMU, according to the FMU description
Hit Crossing,
boolLogical Operator,
boolMonoflop,
boolRelational Operator,
boolSignum,
int32_tTrigger,
bool
Specifying an Output Data Type
The following blocks let you specify the data type of their output signals:
Some of these blocks also let you choose to inherit the output data type from the input signal(s).
Data Type Inheritance
The following blocks implicitly inherit the output data type from the input signals:
Abs, the unsigned input data type is set as output data type
If the input signals have heterogeneous data types, an error message is generated, unless there is at least one floating-point data type and no fixed-point data type. In this case the floating-point data type is inherited. To explicitly set the data type of one of the above blocks, insert a Data Type block in front of the block.
Earlier versions of PLECS implemented more relaxed data type inheritance rules by choosing the data type with the greatest order (as defined in the table above). These rules can be applied to legacy models by changing the global model parameter Datatype inheritance conflict (see Simulation Parameters).
Data Type Overflows
Data type overflows are handled individually per block, according to the following parameter:
- Data type overflow handling
This parameter applies to simulations and generated code. The options are:
- Unchecked
Overflows are ignored, the resulting value is dependent on the platform and the compiler used. The most efficient code is generated with this option.
- Saturate
Overflows/underflows are clamped to the maximum/minimum representable value of the data type.
- Assert with error
The simulation or program execution is aborted with an error if an overflow is detected.
With the global model parameter Datatype overflow (see Simulation Parameters), warning/error messages on data type overflow can be enabled independent from the individual block settings. This parameter only affects simulations and not code generation.