Simulink Design Optimization
Simulink Design Optimization
User's Guide
R2015b
How to Contact MathWorks
Phone: 508-647-7000
v
Parameter Estimation
2
What Is an Experiment? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
vi Contents
Select Results for Validation . . . . . . . . . . . . . . . . . . . . . . . . . 2-49
vii
Write a Cost Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-83
Cost Function Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-83
Convenience Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-84
Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-85
Evaluate Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-86
Outputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-87
viii Contents
Response Optimization
3
How the Optimization Algorithm Formulates Minimization
Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3
Feasibility Problem and Constraint Formulation . . . . . . . . . . 3-3
Tracking Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6
Gradient Descent Method Problem Formulations . . . . . . . . . 3-7
Simplex Search Method Problem Formulations . . . . . . . . . . . 3-8
Pattern Search Method Problem Formulations . . . . . . . . . . . 3-9
Gradient Computations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-10
ix
Specify Piecewise-Linear Upper and Lower Bounds on Singular
Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-51
Specify Step Response Characteristics . . . . . . . . . . . . . . . . . 3-13
Specify Custom Requirements . . . . . . . . . . . . . . . . . . . . . . . 3-32
x Contents
Design Optimization to Meet Time- and Frequency-Domain
Requirements (GUI) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-93
xi
Optimize Design Using Parallel Computing (Code) . . . . . . 3-224
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-225
xii Contents
Reverting to Initial Parameter Values . . . . . . . . . . . . . . . . 3-240
How do I quit an optimization and revert to my initial
parameter values? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-240
Sensitivity Analysis
4
What Is Sensitivity Analysis? . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
xiii
Design Exploration using Parameter Sampling (Code) . . . 4-20
xiv Contents
Optimize LTI System to Meet Frequency-Domain
Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-44
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-44
Design Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-44
Creating an LTI Plant Model . . . . . . . . . . . . . . . . . . . . . . . 5-45
Creating Design and Analysis Plots . . . . . . . . . . . . . . . . . . 5-46
Creating a Response Optimization Task . . . . . . . . . . . . . . . 5-48
Selecting Tunable Compensator Elements . . . . . . . . . . . . . . 5-50
Adding Design Requirements . . . . . . . . . . . . . . . . . . . . . . . 5-51
Optimizing the System's Response . . . . . . . . . . . . . . . . . . . 5-59
Creating and Displaying the Closed-Loop System . . . . . . . . 5-62
Lookup Tables
6
What are Adaptive Lookup Tables? . . . . . . . . . . . . . . . . . . . . . 6-2
Lookup Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2
Adaptive Lookup Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2
xv
Selecting an Adaptation Method . . . . . . . . . . . . . . . . . . . . . . 6-43
Sample Mean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-43
Sample Mean with Forgetting . . . . . . . . . . . . . . . . . . . . . . . 6-44
xvi Contents
1
In this section...
“Select Input Signals” on page 1-3
“Select Output Signals” on page 1-4
Before you can analyze and preprocess the estimation data, you must assign the data to
the model ports or signals. In order to assign the data, the Simulink® model must contain
one of the following elements:
Note: You do not need an Inport block if your model already contains a fixed input
block, such as a Step block.
• Top-level Outport block
• Logged signal, which can be a top-level signal in the model or a signal in a model
subsystem
To enable signal logging for a signal, in the Simulink Editor, select the signal, click
the Simulation Data Inspector button arrow and click Log Selected Signals to
Workspace. For more information, see “Export Signal Data Using Signal Logging” in
the Simulink documentation.
1-2
Model Requirements for Importing Data
Similarly, the rows in the Outputs panel correspond to either the top-level Outport
blocks or logged signals in the model.
Using the dialog box, you can import the input data by typing, for example,
[time,iodata(:,1)] in the Inputs panel. To learn more about importing data, see
Import Data.
1-3
1 Data Analysis and Processing
Using the dialog box, you can import the output data by typing, for example,
[time,iodata(:,2)] in the Inputs panel. To learn more about importing data, see
Import Data.
Related Examples
• “Import Data” on page 1-6
1-4
Model Requirements for Importing Data
More About
• “What Is an Experiment?” on page 2-3
1-5
1 Data Analysis and Processing
Import Data
In this section...
“Create Experiment” on page 1-6
“Time-Domain Data” on page 1-8
“Time-Series Data” on page 1-11
“Complex Data” on page 1-12
Create Experiment
Before you begin data import, create an experiment. Simulink Design Optimization™
software provides a tool for setting up the estimation session.
1 At the MATLAB® prompt, open the nonlinear idle speed model of an automotive
engine by typing :
engine_idle_speed
The model contains the Inport block BPAV and Outport block Engine Speed
for importing input and output data, respectively. To learn more, see “Model
Requirements for Importing Data” on page 1-2.
2 In the Simulink model window, open the Parameter Estimation tool by selecting
Analysis > Parameter Estimation.
1-6
Import Data
You can organize the estimation and validation tasks inside Experiments under
Data Browser panel on the left. You can assign each experiment to an estimation
task or validation task.
1-7
1 Data Analysis and Processing
This creates an experiment called Exp under Experiments. To change the name of
the experiment, right-click and select Rename. Call it NewData.
Note: The Simulink model must remain open to perform parameter estimation tasks.
Time-Domain Data
Experiments are collections of signal data, specifically input and output signal data.
After you create an experiment, as described in “Create Experiment” on page 1-6,
you can import data into your experiment from various sources including MATLAB®
variables, MAT-files, Excel® files, or comma-separated-value files.
To import data into your experiment right-click and select Edit.... This will launch the
experiment editor. In the experiment editor, you can define the signals contained in the
experiment.
1-8
Import Data
For example, the rows in the Inputs panel of the editor correspond to Inport block BPAV
in the engine_idle_speed model.
The rows in the Outputs panel correspond to Outport block Engine Speed. You can
import signal data from files or MATLAB workspace.
Note: The Simulink model must contain an Inport or Outport block or logged signals to
enable importing data. For more information, see “Model Requirements for Importing
Data” on page 1-2. To select more output signals to specify data for, click Select
Measured Output Signals in the Outputs panel.
The idle-speed model of an automotive engine contains the measured data stored in the
iodata array in the workspace. The array contains two columns: the first for input data,
and the second for output data. The time data is in the time array in the workspace. You
can import the input data by typing [time,iodata(:,1)] in the Inputs panel.
1-9
1 Data Analysis and Processing
You can import the output data by typing [time,iodata(:,2)] in the Outputs panel.
You can view the data by clicking . The input data should look like this:
1-10
Import Data
After importing the data for NewData experiment, the experiment editor looks like this:
To learn more about the Edit Experiment: dialog box, see “Edit Experiment Data” on
page 2-21.
Time-Series Data
Time-series data is stored in time-series objects. For more information, see “Time Series
Objects” in the MATLAB documentation.
1-11
1 Data Analysis and Processing
When you import input data from a time-series object, t, for parameter estimation, you
must specify the time vector and data as [t.time,t.inputdata] in the Inport signal
dialog box. Similarly, to import output data, you must specify the time vector and data
as [t.time,t.outputdata] in the Outport signal dialog box. For more information on
how to import data into the experiment, see “Time-Domain Data” on page 1-8.
Complex Data
Complex-valued data is data whose value is a complex number. For example, a signal
with the value 1+2j is complex. You can use complex data to estimate parameters of
electrical systems, such as the magnitude and phase.
Note: You must sample the real and imaginary parts of the data as a function of the
same time vector.
1 Split the data into two data sets that contain the real and imaginary parts. To split
the data, use the MATLAB functions real, and imag.
2 Create two signals, one for the real part and one for the imaginary part for the
Inport or Outport block.
3 Select both signals in the experiment editor.
4 Import the data to the corresponding signal as described in “Time-Domain Data” on
page 1-8.
Related Examples
• “Plot and Analyze Data” on page 1-13
• “Preprocessing Data” on page 1-16
More About
• “Model Requirements for Importing Data” on page 1-2
1-12
Plot and Analyze Data
Plot Data
Use an experiment plot to visualize experiment data. First, create an experiment and
import data as described in “Import Data” on page 1-6. To create an experiment plot, in
the Parameter Estimation tool, on the Parameter Estimation tab, click Add Plot, and
select NewData under Experiment Plots.
This creates plots of the input signal for the Inport block BPAV and output signal for
the Outport block Engine Speed for the engine_idle_speed model (see “Create
Experiment” on page 1-6).
1-13
1 Data Analysis and Processing
You can also plot the experiment data by right-clicking NewData and selecting Plot
measured experiment data from the list.
Using the time plot, you can examine the data characteristics such as noise, outliers and
portions of the data to use for estimating parameters. After you analyze the data, you can
preprocess it as described in “Preprocessing Data” on page 1-16.
Related Examples
• “Import Data” on page 1-6
• “Preprocessing Data” on page 1-16
1-14
Plot and Analyze Data
More About
• “Model Requirements for Importing Data” on page 1-2
1-15
1 Data Analysis and Processing
Preprocessing Data
In this section...
“Ways to Preprocess Data” on page 1-16
“Remove Offset” on page 1-17
“Scale Data” on page 1-17
“Extract Data” on page 1-18
“Filter Data” on page 1-19
“Resample Data” on page 1-20
“Replace Data” on page 1-20
After importing the estimation data as described in “Import Data” on page 1-6, you can
perform the following preprocessing operations:
1-16
Preprocessing Data
• “Resample Data” on page 1-20 –– Resample data using zero-order hold or linear
interpolation.
• “Replace Data” on page 1-20 –– Replace data with a constant value, region initial
value, region final value, or a line. You can use this functionality to replace outliers.
You can perform as many preprocessing operations on your data as are required for your
application. For instance, you can both filter the data and remove an offset.
Remove Offset
On the Experiment Plot tab, click Remove Offset.
It is important for good estimation results to remove data offsets. In the Remove Offset
tab, you can remove offset from all signals at once or select a particular signal using
the Remove offset from signal drop down list. Specify the value to remove using the
Offset to remove drop down list. The options are:
As you change the offset value, the modified data is shown in preview in the plot.
After making choices, update the existing data with the preprocessed data by clicking
Or, to save the modified data values in a new experiment, click and select
Scale Data
On the Experiment Plot tab, click Scale Data.
1-17
1 Data Analysis and Processing
In the Scale Data tab, you can choose to scale all signals or specify a signal to scale.
Select the scaling value from the Scale to use drop-down list. The options are:
As you change the scaling, the modified data is shown in preview in the plot.
After making choices, update the existing data with the preprocessed data by clicking
Or, to save the modified data values in a new experiment, click and select
Extract Data
To extract a portion of your data to use in the estimation process, on the Experiment
Plot tab, click Extract Data.
1-18
Preprocessing Data
Select a subset of data to use for estimation in Extract Data tab. You can extract data
graphically or by specifying start time and end time. To extract data graphically, click
and drag the vertical bars to select a region of the data to use.
After you choose the data to extract, you can save in a new experiment by clicking Save
As.
Filter Data
You can filter your data using a low-pass, high-pass, or band-pass filter. A low-pass
filter blocks high frequency signals, a high-pass filter blocks low frequency signals, and
a band-pass filter combines the properties of both low- and high-pass filters. On the
Experiment Plot tab click one of the Low-Pass Filter, High-Pass Filter, or Band-
Pass Filter to open a new tab. For example, the low-pass filter tab appears as shown:
On the Low-Pass Filter, High-Pass Filter, or Band-Pass Filter tab, you can choose
to filter all signals or specify a particular signal. For the low-pass and high-pass filtering,
you can specify the normalized cutoff frequency of the signal. For the band-pass filter,
you can specify the normalized start and end frequencies. Specify the frequencies by
either entering the value in the associated field on the tab. Alternatively, you can specify
filter frequencies graphically, by dragging the vertical bars in the frequency-domain plot
of your data.
Click Options to specify the filter order, and select zero-phase shift filter.
After making choices, update the existing data with the preprocessed data by clicking
Or, to save the modified data values in a new experiment, click and select
1-19
1 Data Analysis and Processing
Resample Data
On the Experiment Plot tab, click the Resample Data button.
In the Resample Data tab, specify the sampling period using the Resample
with sample period: field. You can resample your data using one of the following
interpolation methods:
• Zero-order hold — Fill the missing data sample with the data value immediately
preceding it.
• Linear interpolation — Fill the missing data using a line that connects the two
data points.
By default, the resampling method is set to zero-order hold. You can select the
linear interpolation method from the Resample Using drop-down list.
After making choices, update the existing data with the preprocessed data by clicking
Or, to save the modified data values in a new experiment, click and select
Replace Data
On the Experiment Plot tab click the Replace Data button.
1-20
Preprocessing Data
In the Replace Data tab, select data to replace by dragging across a region in the plot.
Once you select data, choose how to replace it using the Replace selected data drop-
down list. You can replace the data you select with one of these options:
• A constant value
• Region initial value
• Region final value
• A line
The replaced preview data changes color and the replacement data appears on the plot.
At any time before updating, click Clear preview to clear the data you replaced and
start over.
After making choices, update the existing data with the preprocessed data by clicking
Or, to save the modified data values in a new experiment, click and select
Replace Data can be useful, for example, to replace outliers. Outliers are data values
that deviate from the mean by more than three standard deviations. When estimating
parameters from data containing outliers, the results may not be accurate. Hence, you
might choose to replace the outliers in the data before you estimate the parameters.
Related Examples
• “Import Data” on page 1-6
1-21
1 Data Analysis and Processing
More About
• “Model Requirements for Importing Data” on page 1-2
1-22
Add Preprocessed Data Sets to Estimation Project (GUI)
In this section...
“Overwriting an Existing Data Set” on page 1-23
“Creating a New Data Set” on page 1-24
1 In the Write results to area of the Data Preprocessing Tool GUI, select the
existing dataset option.
2 Choose the data set you want to overwrite from the drop-down list.
3 Click Add.
This action overwrites the selected data set with the modified data in the Control
and Estimation Tools Manager GUI.
1-23
1 Data Analysis and Processing
Tip You can export the preprocessed data to the MATLAB Workspace, as described in
“Export Prepared Data to the MATLAB Workspace” on page 1-26.
1 In the Write results to area of the Data Preprocessing Tool GUI, select the new
dataset option.
2 Specify the name of the data set in the adjacent field.
1-24
Add Preprocessed Data Sets to Estimation Project (GUI)
3 Click Add.
This action adds a new data node in the Control and Estimation Tools Manager GUI
containing the modified data.
Tip You can export the preprocessed data to the MATLAB Workspace, as described in
“Export Prepared Data to the MATLAB Workspace” on page 1-26.
1-25
1 Data Analysis and Processing
1 In the Transient Data node of the Control and Estimation Tools Manager GUI,
select the node containing the prepared data set.
2 Right-click the table Data cell containing the data that you want to export, and
select Export.
4 Click OK.
The resulting MATLAB variables data and time4 appear in the MATLAB
Workspace browser.
1-26
2
Parameter Estimation
2-2
What Is an Experiment?
What Is an Experiment?
To estimate unknown parameter values of a Simulink model, first create an experiment.
An experiment specifies measured input and output data. During estimation, the
experiment input data is used to simulate the model and the model output is compared
with the measured experiment output data. For more information about creating
experiments and importing data, see “Specify Estimation Data” on page 2-4.
In an experiment, you can specify initial-state values. To do so, specify the model initial
states for each experiment. You can optionally specify an initial guess for the initial state
values for any experiment. For more information, see “Specify Known Initial States” on
page 2-17.
To use experiments for validating the estimated parameter values, see “Model
Validation” on page 2-45.
Related Examples
• “Specify Estimation Data” on page 2-4
• “Specify Parameters for Estimation” on page 2-8
• “Specify Known Initial States” on page 2-17
• “Specify Experiments for Estimation” on page 2-23
More About
• “Edit Experiment Data” on page 2-21
2-3
2 Parameter Estimation
In this section...
“Create Experiment” on page 2-4
“Specify Data” on page 2-6
Create Experiment
Before you specify estimation data, create an experiment. At the MATLAB prompt, open
the nonlinear idle speed model of an automotive engine by typing
engine_idle_speed
In the Simulink model window, open the Parameter Estimation tool by selecting
Analysis > Parameter Estimation.
2-4
Specify Estimation Data
In the Parameter Estimation tool, on the Parameter Estimation tab, click New
Experiment.
This action creates an experiment called Exp in the Experiments list in the Data
Browser panel and opens the experiment editor. To change the name of the experiment,
right-click Exp and select Rename. If you rename it NewData, the Experiments list
now looks like this:
2-5
2 Parameter Estimation
To learn more about how to further modify an experiment using the experiment editor,
see “Edit Experiment Data” on page 2-21.
Specify Data
After you create the experiment, you can import the estimation data into the experiment.
Launch the experiment editor by right-clicking on NewData and selecting Edit....
The rows in the Inputs panel of the editor correspond to Inport block BPAV in the
engine_idle_speed model. See “Import Data” on page 1-6.
The rows in the Outputs panel correspond to Outport block Engine Speed. You can
import signal data from files or MATLAB workspace.
The idle-speed model of an automotive engine contains the measured data stored in the
iodata array in the workspace. The array contains two columns: the first for input data,
and the second for output data. The time data is in the time array in the workspace.
You can import the input data by typing [time,iodata(:,1)] in the dialog box in the
Inputs panel.
You can import the output data by typing [time,iodata(:,2)] in the dialog box in the
Outputs panel.
2-6
Specify Estimation Data
Note: You can have more than one input or output signal, but you can have only one data
set for a signal. If you have multiple data sets, create multiple experiments.
Related Examples
• “Specify Parameters for Estimation” on page 2-8
• “Specify Known Initial States” on page 2-17
More About
• “What Is an Experiment?” on page 2-3
• “Edit Experiment Data” on page 2-21
2-7
2 Parameter Estimation
In this section...
“Choosing Which Parameters to Estimate First” on page 2-8
“Add Model Parameters as Variables for Estimation” on page 2-8
“Specify Parameters for Estimation” on page 2-11
2-8
Specify Parameters for Estimation
• Add the variables to the model workspace, and specify initial values.
2-9
2 Parameter Estimation
• Write initialization code in the PreloadFcn callback of the model. For more
information, see “Model Callbacks”.
gain1 = 100
2 Specify the block parameter as variable gain1 in the Transfer Fcn block dialog box.
2-10
Specify Parameters for Estimation
You can now select gain1 for estimation. See, “Specify Parameters for Estimation” on
page 2-11.
You can also specify independent parameters that do not appear explicitly in the model
as variables for estimation. However, you cannot use this workflow with Simulink fast
restart.
Suppose that a model parameter Kint is related to independent parameters x and y such
that Kint = x+y. To estimate x and y instead of Kint:
• Create the independent variables x and y by adding them to the model workspace and
specifying initial values. This ensures that the variables are used by the model.
• Write code in the InitFcn callback of the model that defines the relationship between
Kint, x, and y. You must first use the get_param function to get the variables x and
y from the model workspace before you can use them to define Kint.
wks = get_param(gcs,'ModelWorkspace')
x = evalin(wks,'x')
y = evalin(wks,'y')
Kint = x+y;
You can now select x and y for estimation. Do not estimate the independent and
dependent parameters simultaneously. Doing so can lead to incorrect results. For
example, do not estimate Kint, x and y together.
To select parameters for all experiments, click Select Parameters in the Parameters
Tuned for all Experiments panel. This opens the Select model variables dialog.
2-11
2 Parameter Estimation
Here you can select the parameters you want to estimate by clicking the check box next
to it or specifying an expression. For more information see “Select Parameters Using
Select Model Variables Dialog Box” on page 2-14.
For example, in the engine_idle_speed model, select freq1, freq2, freq3, gain1,
gain2, gain3 and mean_speed for estimation. You do not need to estimate the
parameters all at once. You can first select all the parameters you are interested in,
and then later select a subset to estimate. By default, all the parameters are selected
for estimation. To deselect the ones you do not want to estimate, clear the Estimate
check box for a parameter. For this example, only estimate gain1, gain2, gain3 and
2-12
Specify Parameters for Estimation
mean_speed. Set their initial values 10, 100, 50, and 500, respectively, and then click
OK. The Edit: Estimated Parameters dialog box looks like
To learn how to specify initial values and upper and lower bounds of the parameters, see
“Specifying Initial Guesses and Upper/Lower Bounds” on page 2-15.
To select the parameters to estimate in a specific experiment, first, select the experiment
for estimation as described in “Specify Experiments for Estimation” on page 2-23.
Then, you can use the Edit:Estimated Parameters dialog to select parameters to
estimate for that experiment. Select the experiment name from the Experiment: combo
2-13
2 Parameter Estimation
box in the Parameters and Initial States Tuned per Experiment panel. Then click
Edit experiment to launch the experiment editor for the experiment you select.
Alternatively, you can right click the experiment name in the Experiments list
and select Edit.... In the experiment editor, click the Select parameters button in
the Parameters panel. In the Select model variables dialog, you can select the
parameters you want to estimate in this experiment by checking the box next to it or
specifying an expression. For more information see “Select Parameters Using Select
Model Variables Dialog Box” on page 2-14.
Use this dialog box to specify parameters to estimate. The table lists all the variables in
the model workspace and the MATLAB workspace that the model uses, whether tunable
or not. Select the parameters to estimate by clicking the check box next to each variable.
If your model contains a large number of variables, filter the list by typing in the Filter
by variable name field.
The Used By column lists the blocks in the model where each variable is used. When a
parameter is used in more than one block, all blocks are listed. To locate blocks in which
a parameter is used, click the block name to highlight the block in the model.
2-14
Specify Parameters for Estimation
• Initial guess — The value the estimation uses to start the process.
• Minimum — The smallest allowable parameter value. The default is -Inf.
• Maximum — The largest allowable parameter value. The default is +Inf.
You can enter the initial value in the dialog box below the parameter name. You can
specify the minimum and maximum value fields by clicking the arrow . The default
minimum and maximum values are -Inf and +Inf, respectively, but you can select
any range you want.
2-15
2 Parameter Estimation
If you believe a parameter lies within a finite range, it is best not to use the default
minimum and maximum values. Often, there are computational advantages in
specifying finite bounds. It can be very important to specify lower and upper bounds.
For example, if a parameter specifies the weight of a part, be sure to specify 0 as the
absolute lower bound if better information is unavailable.
Note: When you specify the minimum and maximum values for the parameters, it
does not affect your settings in the Parameters list under Data Browser pane. You
make these choices for each experiment.
• Scale — Scale is used for normalization, in situations, for example, when parameters
are in different units.
Related Examples
• “Specify Known Initial States” on page 2-17
More About
• “What Is an Experiment?” on page 2-3
2-16
Specify Known Initial States
In this section...
“When to Specify Initial States Versus Estimate Initial States” on page 2-17
“Specify Model Initial States” on page 2-17
You can use the Parameter Estimation tool to estimate the initial conditions using
procedures that are similar to those you use to estimate parameters. You can then use
these initial condition estimates as a basis for estimating parameters for your Simulink
model.
The Select Model States dialog for the engine_idle_speed model looks like
2-17
2 Parameter Estimation
Click the check box next to the state you would like to modify. For example, if you select
engine_idle_speed/Transfer Fcn and enter the initial values -0.2 and 0, the Initial
States panel now looks like
Click Select Parameters in the Parameter Estimation tab. After you also select the
parameters as described in “Specify Parameters for Estimation” on page 2-8, the Edit:
Estimated Parameters dialog looks like the following figure.
2-18
Specify Known Initial States
Related Examples
• “Specify Estimation Data” on page 2-4
• “Specify Parameters for Estimation” on page 2-8
2-19
2 Parameter Estimation
More About
• “Edit Experiment Data” on page 2-21
2-20
Edit Experiment Data
The experiment editor has four panels. You can select output signals and import output
data in the Outputs panel. You can select input signals and import input data in the
Inputs panel. You can specify model initial states in the Initial States panel. And you
can specify parameters to estimate in the Parameters panel.
2-21
2 Parameter Estimation
Related Examples
• “Specify Estimation Data” on page 2-4
• “Specify Parameters for Estimation” on page 2-8
• “Specify Known Initial States” on page 2-17
• “Specify Experiments for Estimation” on page 2-23
More About
• “What Is an Experiment?” on page 2-3
2-22
Specify Experiments for Estimation
For more information, see “Specify Experiments for Validation” on page 2-47
Related Examples
• “Specify Estimation Data” on page 2-4
• “Specify Parameters for Estimation” on page 2-8
• “Specify Known Initial States” on page 2-17
• “Specify Experiments for Validation” on page 2-47
More About
• “What Is an Experiment?” on page 2-3
2-23
2 Parameter Estimation
Progress Plots
In this section...
“Types of Plots” on page 2-24
“Basic Steps for Creating Plots” on page 2-24
Types of Plots
The following types of plots are available for viewing and evaluating the estimation:
• Cost function — Plot the cost function value as it changes during estimation.
• Measured and simulated — Plot empirical data against simulated data.
• Parameter trajectory — Plot the parameter values as they change.
• Residuals — Plot the error between the experimental data and the simulated
output.
Note: An experiment must be created and selected for estimation before creating views.
To learn more, see “Create Experiment” on page 2-4 and “Specify Experiments for
Estimation” on page 2-23.
You can plot the measured data by clicking Add Plot on the Parameter Estimation
tab and selecting the experiment to use for estimation under Experiment Plots of the
drop down list. You can then add the simulated response on top of the measured data
plot by clicking Plot Model Response on the Parameter Estimation tab. Another way
of plotting the measured and simulated data is to right-click the experiment name, for
this example, NewData, and select Plot measured & simulated data from the list. The
plot looks like this:
2-24
Progress Plots
You can see that the measured and simulated data do not match. You can edit the labels,
adjust the limits, change the units, and the font style of the plot in the Property Editor.
To launch the editor, right-click the experiment plot and select Properties from the list.
2-25
2 Parameter Estimation
You can also add a plot for the expected estimation cost by clicking Add Plot on the
Parameter Estimation tab and selecting Estimation Cost from the list. You can close
the message “There is no data for ExpCost, run the optimization to
update the plot”, by clicking the left arrow toggle to the left of the message. The plot
looks like this:
2-26
Progress Plots
When you right-click the estimated parameters or expected cost plots, you can choose to
add the scaled values or save iteration data from the list.
2-27
2 Parameter Estimation
Add the progress plots by clicking the Add Plot button on the Parameter Estimation
tab and selecting the plot in the list. Selecting Parameter Trajectory adds the
following plot to the tool.
Use the View tab of the Parameter Estimation tool to arrange the layout of the plots, so
that Experiment plot: NewData, Iteration plot 1, and Iteration plot 2 are
all visible.
2-28
Progress Plots
2-29
2 Parameter Estimation
Estimation Options
In this section...
“Access Estimation Options” on page 2-30
“General Options” on page 2-30
“Optimization Options” on page 2-32
“Specify Goodness of Fit Criteria (Cost Function)” on page 2-35
You can access other estimation options by clicking the More Options button.
Note: Parallel Options (see “Estimate Parameters Using Parallel Computing in the
Parameter Estimation Tool” on page 2-61).
General Options
You can set optimization progress and result options for your estimation task in the
Estimation Options dialog box.
2-30
Estimation Options
Progress Options
Show estimation progress window during estimation option opens an estimation
progress window. The window displays iteration information, such as the cost function,
and the termination information, such as whether the optimization converged.
Create a parameter trajectory plot during estimation option creates a plot that
shows how the parameter values change by iteration.
Update plots during optimization option updates the progress plots such a cost
function and parameter trajectory plot and estimation plots during estimation.
Result Options
Update model at the end of estimation option updates the parameter values in the
Simulink model after the estimation terminates.
2-31
2 Parameter Estimation
Overwrite estimation result with new estimated values option overwrites any
estimation results or experiments with the new estimated values.
Save estimated values as new estimation result option creates a new variable that
contains the estimated parameter values.
Optimization Options
Both the Method and Algorithm options define the optimization method.
2-32
Estimation Options
For the Nonlinear least squares and Gradient descent estimation methods
• “Trust-Region-
Reflective Least
Squares Algorithm”
• “Levenberg-
Marquardt Method”
Gradient descent • Trust-Region-Reflective In the Optimization
(default) Toolbox documentation,
• Interior-Point see:
2-33
2 Parameter Estimation
By varying these parameters, you can force the optimization to continue searching for a
solution or to continue searching for a more accurate solution.
• Display level — Specify the form of the output that appears in the MATLAB
Command Window. The options are:
Refer to the Optimization Toolbox documentation for more information on what type
of iterative output each method displays.
2-34
Estimation Options
The default cost function is Sum Squared Error (sum of squared errors), which uses
a least-squares approach. You can also use Sum-Absolute Error, the sum of absolute
errors.
You can select the robust cost option from the Optimization Options tab of the
Estimation Options editor. To launch the dialog box click More Options... on the
Parameter Estimation tool. Use robust cost option makes the optimizer use a robust
cost function instead of the default least-squares cost. This is useful if the experimental
data has many outliers, or if your data is noisy.
2-35
2 Parameter Estimation
The report displays the iteration number (Iteration), the number of times the objective
function is calculated (F-count), and cost function value (f(x)) by default. You can
change by clicking Display Options.
2-36
Progress Display Options
Clear a check box to remove it from the display table. To learn more about the display
table, see “Iterative Display” in the Optimization Toolbox documentation.
2-37
2 Parameter Estimation
Run Estimation
Before you begin estimating the parameters, you must have configured the estimation
data, selected parameters, and specified estimation options, as described in “Specify
Estimation Data” on page 2-4, “Specify Parameters for Estimation” on page 2-8, and
“Estimation Options” on page 2-30, respectively.
When starting the estimation, a progress window displays. At the end of the estimation,
the Estimation Progress Report window should resemble the following:
The estimation results are saved in EstimatedParams in the Results list on the Browse
Data pane.
2-38
Run Estimation
Right-click EstimatedParams and select Open... from the menu. The window looks like
the following figure.
The EstimatedParams includes the values of the parameters, the cost function value,
and information about the stopping criteria for the estimation. The optimization stops
because the successive function values are less than the specified value 1e-3.
The Estimation Progress Report includes the change in the cost function in the
column titled NewData(Minimize). To see a plot of the change in the cost function
2-39
2 Parameter Estimation
during estimation, add the cost function plot by clicking the Add Plot button on the
Parameter Estimation tab and selecting Estimation Cost from the list. After the
estimation process completes, the cost function minimization plot appears as shown in
the following figure.
Usually, a lower cost function value indicates a successful estimation, meaning that the
experimental data matches the model simulation with the estimated parameters. If the
optimization went well, you should see your cost function converge on a minimum value.
The lower the cost, the more successful is the estimation.
For information on types of problems you may encounter using optimization solvers, see
the following topics in the Optimization Toolbox documentation:
2-40
Run Estimation
The estimated parameters graph shows the change in the estimated value of the
parameters by iteration.
The values of the parameters are recorded with the estimated values.
2-41
2 Parameter Estimation
The values of the estimated parameters are also updated in the MATLAB workspace.
You can also examine the measured versus simulated data plot to see how closely
the simulated data matches the measured estimation data. The next figure shows
the measured versus simulated data plot generated by running the estimation of the
engine_idle_speed model (for engine_idle_speed model, see “Create Experiment”
on page 2-4). Now, the simulated values match the measured output signal better.
2-42
Run Estimation
Related Examples
• “Specify Estimation Data” on page 2-4
• “Specify Parameters for Estimation” on page 2-8
• “Specify Known Initial States” on page 2-17
• “Specify Experiments for Estimation” on page 2-23
• “Progress Plots” on page 2-24
• “Estimation Options” on page 2-30
2-43
2 Parameter Estimation
More About
• “What Is an Experiment?” on page 2-3
• “Model Validation” on page 2-45
2-44
Model Validation
Model Validation
After you complete estimating parameters as described in “Run Estimation” on page
2-38, validate the results against another set of data.
1 Add a new experiment in the Experiments list in the Data Browser pane.
2 Import the validation data set to the experiment you want to use for validation. To
do this right-click the experiment name and select Edit....
3 Select the experiment for validation.
4 Select the results to use in the validation.
5 Select the plots to display at the end of validation.
6 Run validation and compare the measured validation data against the model output
simulated with the estimated parameter to see if they match.
You can run validation after the estimation is complete. Validations can use other
validation data sets for comparison with the model response. You must set up all
estimation plots before an estimation, and you can watch the views update in real time.
Validations appear after you have completed an estimation and do not update.
You can validate data by comparing measured and simulated data for your estimation
and validation experiments.
Also, it is useful to compare residuals of measured and simulated data in the same way.
Related Examples
• “Load and Import Validation Data” on page 2-46
• “Specify Experiments for Validation” on page 2-47
• “Select Results for Validation” on page 2-49
• “Compare Measured and Simulated Responses” on page 2-53
More About
• “What Is an Experiment?” on page 2-3
2-45
2 Parameter Estimation
At the MATLAB prompt, load the validation data into the MATLAB workspace by typing
load iodataval
Import this data into the validation experiment in the Parameter Estimation tool.
1 Add a new experiment in the Experiments list in the Data Browser pane. You can
rename the experiment by right-clicking and selecting Rename from the list.
2 Right click the experiment name and select Edit...
3 Type [time,iodataval(:,1)] in the dialog box in the Inputs panel.
4 Type [time,iodataval(:,2)] in the dialog box in the Outputs panel.
Related Examples
• “Import Data” on page 1-6
• “Specify Experiments for Validation” on page 2-47
• “Select Results for Validation” on page 2-49
• “Compare Measured and Simulated Responses” on page 2-53
More About
• “Model Validation” on page 2-45
2-46
Specify Experiments for Validation
Related Examples
• “Load and Import Validation Data” on page 2-46
• “Select Results for Validation” on page 2-49
• “Compare Measured and Simulated Responses” on page 2-53
2-47
2 Parameter Estimation
More About
• “Model Validation” on page 2-45
2-48
Select Results for Validation
Related Examples
• “Load and Import Validation Data” on page 2-46
• “Specify Experiments for Validation” on page 2-47
2-49
2 Parameter Estimation
More About
• “Model Validation” on page 2-45
2-50
Select Plots and Run Validation
To perform the validation, on the Validation tab, click Validate. The Validation
Progress Report shows the status of the validation.
2-51
2 Parameter Estimation
Related Examples
• “Load and Import Validation Data” on page 2-46
• “Specify Experiments for Validation” on page 2-47
• “Select Results for Validation” on page 2-49
• “Compare Measured and Simulated Responses” on page 2-53
More About
• “What Is an Experiment?” on page 2-3
• “Model Validation” on page 2-45
2-52
Compare Measured and Simulated Responses
Experiment Plot
The Parameter Estimation tool by default displays the experiment plot for each
experiment selected for validation. Each experiment plot shows the measured data,
as well as data from simulation using each set of results selected. For example, the
following figure shows the experiment plot for the ValidationExp data.
2-53
2 Parameter Estimation
Residuals Plot
After comparing the measured and simulated responses for an estimation, examine the
residuals. The residuals plot shows the difference between the simulated response and
measured data. To indicate a good fit between the simulated output and measured data,
the residuals should:
For example, you can see from the following figure that the residuals for
ValidationExp data satisfy both criteria.
2-54
Compare Measured and Simulated Responses
Related Examples
• “Load and Import Validation Data” on page 2-46
• “Specify Experiments for Validation” on page 2-47
• “Select Results for Validation” on page 2-49
More About
• “Model Validation” on page 2-45
2-55
2 Parameter Estimation
• The model contains a large number parameters to estimate, and the estimation
method is specified as either Nonlinear least squares or Gradient descent.
• The Pattern search method is selected as the estimation method.
• The model is complex and takes a long time to simulate.
When you use parallel computing, the software distributes independent simulations
to run them in parallel on multiple MATLAB sessions, also known as workers. The
time required to simulate the model dominates the total estimation time. Therefore,
distributing the simulations significantly reduces the estimation time.
For information on how the software distributes the simulations and the expected
speedup, see “How Parallel Computing Speeds Up Estimation” on page 2-56.
For information on configuring your system and using parallel computing, see “How to
Use Parallel Computing for Parameter Estimation” on page 2-60.
• “Parallel Computing with Nonlinear least squares and Gradient descent Methods” on
page 2-57
• “Parallel Computing with the Pattern search Method” on page 2-58
2-56
Speed Up Parameter Estimation Using Parallel Computing
Parallel Computing with Nonlinear least squares and Gradient descent Methods
When you select Gradient descent as the estimation method, the model is simulated
during the following computations:
The total time, Ttotal , taken per iteration to perform these simulations is given by the
following equation:
where T is the time taken to simulate the model and is assumed to be equal for all
simulations, Np is the number of parameters to estimate, and Nls is the number of line
searches. Nls is difficult to estimate and you generally assume it to be equal to one, two,
or three.
When you use parallel computing, the software distributes the simulations required
for objective gradient computations. The simulation time taken per iteration when the
gradient computations are performed in parallel, TtotalP , is approximately given by the
following equation:
Ê Np ˆ Ê Np ˆ
TtotalP =T + ( ceil Á ˜ ¥ 2 ¥ T ) + ( Nls ¥ T ) = T ¥ (1 + 2 ¥ ceil Á ˜ + Nls)
Ë Nw ¯ Ë Nw ¯
Note: The equation does not include the time overheads associated with configuring the
system for parallel computing and loading Simulink software on the remote MATLAB
workers.
The expected reduction of the total estimation time is given by the following equation:
2-57
2 Parameter Estimation
Ê Np ˆ
1 + 2 ¥ ceil Á ˜ + Nls
TtotalP
= Ë Nw ¯
Ttotal 1 + ( 2 ¥ Np) + Nls
For example, for a model with Np=3, Nw=4, and Nls=3, the expected reduction of the total
Ê3ˆ
1 + 2 ¥ ceil Á ˜ + 3
estimation time equals Ë4¯ = 0.6 .
1 + (2 ¥ 3) + 3
The Pattern search method uses search and poll sets to create and compute a set of
candidate solutions at each estimation iteration.
The total time, Ttotal , taken per iteration to perform these simulations, is given by the
following equation:
where T is the time taken to simulate the model and is assumed to be equal for all
simulations, Np is the number of parameters to estimate, Nss is a factor for the search
set size, and Nps is a factor for the poll set size. Nss and Nps are typically proportional
to Np .
When you use parallel computing, Simulink Design Optimization software distributes
the simulations required for the search and poll set computations, which are evaluated in
separate parfor loops. The simulation time taken per iteration when the search and poll
sets are computed in parallel, TtotalP , is given by the following equation:
Nss Nps
TtotalP = ( T ¥ ceil( Np ¥ )) + ( T ¥ ceil( Np ¥ ))
Nw Nw
Nss Nps
= T ¥ ( ceil( Np ¥ ) + ceil( Np ¥ ))
Nw Nw
2-58
Speed Up Parameter Estimation Using Parallel Computing
Note: The equation does not include the time overheads associated with configuring the
system for parallel computing and loading Simulink software on the remote MATLAB
workers.
The expected speed up for the total estimation time is given by the following equation:
Nss Nps
ceil( Np ¥ ) + ceil( Np ¥ )
TtotalP Nw Nw
=
Ttotal Np ¥ ( Nss + Nps)
For example, for a model with Np=3, Nw=4, Nss=15, and Nps=2, the expected speedup
15 2
ceil(3 ¥ ) + ceil(3 ¥ )
equals 4 4 = 0 .27 .
3 ¥ (15 + 2)
Using the Pattern search method with parallel computing may not speed up the
estimation time. When you do not use parallel computing, the method stops searching
for a candidate solution at each iteration as soon as it finds a solution better than the
current solution. When you use parallel computing, the candidate solution search is more
comprehensive. Although the number of iterations may be larger, the estimation without
using parallel computing may be faster.
Related Examples
• “How to Use Parallel Computing for Parameter Estimation” on page 2-60
2-59
2 Parameter Estimation
When you estimate model parameters using parallel computing, the software uses the
available parallel pool. If none is available, and you select Automatically create a
parallel pool in your Parallel Computing Toolbox preferences, the software starts a
parallel pool using the settings in those preferences. To open a parallel pool that uses a
specific cluster profile, use:
parpool(MyProfile);
For information regarding creating a cluster profile, see “Create and Modify Cluster
Profiles” in the Parallel Computing Toolbox documentation.
Model Dependencies
Model dependencies are any referenced models, data such as model variables, S-
functions, and additional files necessary to run the model. Before starting the
optimization, verify that the model dependencies are complete. Otherwise, you may get
unexpected results.
2-60
How to Use Parallel Computing for Parameter Estimation
When you use parallel computing, the Simulink Design Optimization software helps you
identify model dependencies. To do so, the software uses the Simulink Manifest Tools.
The dependency analysis may not find all the files required by your model. To learn
more, see “Scope of Dependency Analysis” in the Simulink documentation. If your model
has dependencies that are undetected or inaccessible by the parallel pool workers, then
add them to the list of model dependencies.
The dependencies are made accessible to the parallel pool workers by specifying one of
the following:
• File dependencies: the model dependency files are copied to the parallel pool workers.
• Path dependencies: the paths to the model dependencies are specified to the parallel
pool workers. If you are working in a multi-platform scenario, ensure that the paths
are compatible across platforms.
1 Ensure that the software can access parallel pool workers that use the appropriate
cluster profile.
For more information, see “Configure Your System for Parallel Computing” on page
2-60.
2 Open the Parameter Estimation tool for the Simulink model.
2-61
2 Parameter Estimation
3 Configure the estimation data, estimation parameters and states, and, optionally,
estimation settings.
For more information, see “Specify Estimation Data” on page 2-4, “Specify
Parameters for Estimation” on page 2-8, and “Optimization Options” on page 2-32.
4
On the Parameter Estimation tab, click More Options to open the
Estimation Options dialog box.
5 Select the Parallel Options tab.
6 Select the Use the parallel pool during optimization check box.
This option checks for dependencies in your Simulink model. The file dependencies
are displayed in the Model file dependencies list box, and corresponding
path to the files in Model path dependencies. The files listed in Model file
dependencies are copied to the remote workers.
Note: The automatic dependencies check may not detect all the dependencies in your
model.
2-62
How to Use Parallel Computing for Parameter Estimation
For more information, see “Model Dependencies” on page 2-60. In this case, add
the undetected dependencies manually.
7 Add any file dependencies that the automatic check does not detect.
Specify the files in the Model file dependencies list box separated by semicolons
or on separate lines.
Alternatively, click Add file dependency to open a dialog box, and select the file to
add.
Note: If you do not want to copy the files to the remote workers, delete all entries in
the Model file dependencies list box. Populate the Model path dependencies
list box by clicking the Sync path dependencies from model, and add any
undetected path dependencies. In addition, in the list box, update the paths on local
drives to make them accessible to remote workers. For example, change C:\ to \\\
\hostname\\C$\\.
8 If you modify the Simulink model, resync the dependencies to ensure that any new
dependencies are detected. Click Sync file dependencies from model in the
Parallel Options tab to rerun the automatic dependency check for your model.
2-63
2 Parameter Estimation
This action updates the Model file dependencies list box with any new file
dependency found in the model.
9 Click OK.
10 In the Parameter Estimation tab, click Estimate to estimate the model
parameters using parallel computing.
1 Ensure that the software can access parallel pool workers that use the appropriate
cluster profile.
For more information, see “Configure Your System for Parallel Computing” on page
2-60.
2 Open the model.
3 Configure an estimation experiment. For example, see “Estimate Model Parameter
Values (Code)” on page 2-92.
4 Enable parallel computing using an optimization option set, opt.
opt = sdo.OptimizeOptions;
opt.UseParallel = 'always';
5 Find the model dependencies.
[dirs,files] = sdo.getModelDependencies(modelname)
files = vertcat(files,'C:\matlab\work\filename.m')
2-64
How to Use Parallel Computing for Parameter Estimation
Note: If you do not want to copy the files to the remote workers, use the path
dependencies. Add any undetected path dependencies to dirs and update
the paths on local drives to make them accessible to remote workers. See
sdo.getModelDependencies for more details.
7 Add the file dependencies for optimization.
opt.ParallelFileDependencies = files;
8 Run the optimization.
[pOpt,opt_info] = sdo.optimize(opt_fcn,param,opt);
Troubleshooting
• “Why Are the Estimation Results With and Without Parallel Computing Different?”
on page 2-65
• “Why Didn’t the Estimation Speed up Using Parallel Computing?” on page 2-65
• “Why Doesn’t the Estimation Using Parallel Computing Make Any Progress?” on page
2-66
• “Why Does the Estimation Using Parallel Computing Continue When I Click Stop?”
on page 2-66
Why Are the Estimation Results With and Without Parallel Computing Different?
• Different numerical precision on the client and worker machines can produce
marginally different simulation results. Thus, the optimization method can take a
different solution path and produce a different result.
• When you use parallel computing with the Pattern search method, the search
is more comprehensive and can result in a different solution. To learn more, see
“Parallel Computing with the Pattern search Method” on page 2-58.
• When you estimate a few parameters or when the model does not take long to
simulate, you do not see a speedup in the estimation time. In such cases, the overhead
2-65
2 Parameter Estimation
associated with creating and distributing the parallel tasks outweighs the benefits of
running the estimation in parallel.
• Using the Pattern search method with parallel computing might not speed up the
optimization time. Without parallel computing, the method stops the search at each
iteration as soon as it finds a solution better than the current solution. The candidate
solution search is more comprehensive when you use parallel computing. Although
the number of iterations might be larger, the optimization without using parallel
computing might be faster.
To learn more about the expected speedup, see “Parallel Computing with the Pattern
search Method” on page 2-58.
Why Doesn’t the Estimation Using Parallel Computing Make Any Progress?
1 Run the optimization for a few iterations without parallel computing to see if the
optimization progresses.
2 Check whether the remote workers have access to all model dependencies. Model
dependencies include data variables and files required by the model to run.
Why Does the Estimation Using Parallel Computing Continue When I Click Stop?
When you use parallel computing with the Pattern search method, the software must
wait until the current optimization iteration completes before it notifies the workers
to stop. The optimization does not terminate immediately when you click Stop, and,
instead, appears to continue running.
See Also
sdo.OptimizeOptions | parpool | sdo.getModelDependencies | sdo.optimize
More About
• “Speed Up Parameter Estimation Using Parallel Computing” on page 2-56
• “Ways to Speed Up Design Optimization Tasks”
2-66
Use Fast Restart Mode During Parameter Estimation
This topic shows how to speed up parameter estimation using Simulink fast restart. You
can use the fast restart feature to speed up parameter estimation of tunable parameters
of a model.
Fast restart enables you to perform iterative simulations without compiling a model or
terminating the simulation each time. Using fast restart, you compile a model only once.
You can then tune parameters and simulate the model again without spending time on
compiling. Fast restart associates multiple simulation phases with a single compile phase
to make iterative simulations more efficient. You see a speedup of design optimization
tasks using fast restart in models that have a long compilation phase. See “How Fast
Restart Improves Iterative Simulations” in the Simulink documentation.
When you enable fast restart, you can only change tunable properties of the model during
simulation. For more information about the limitations, see “Factors Affecting Fast
Restart”.
You can perform parameter estimation using fast restart in the Parameter Estimation
tool or at the command line.
2-67
2 Parameter Estimation
For more information, see “Specify Estimation Data” on page 2-4, “Specify
Parameters for Estimation” on page 2-8, and “Optimization Options” on page 2-32.
5 In the Parameter Estimation tab, click Estimate to estimate the model
parameters in fast restart mode.
6 Disable fast restart.
Store the measured input/output data in Exp. For example, see “Estimate Model
Parameter Values (Code)” on page 2-92.
4 Create a model simulator from the experiment.
Simulator = createSimulator(Exp);
Note: You must create a simulation scenario with logging information before
configuring the model for fast restart. You cannot modify logging information once
the model has been compiled for fast restart.
5 Configure the simulator and model for fast restart.
Simulator = fastRestart(Simulator,'on');
6 Create an estimation cost function, myCostfcn, and pass Simulator to the cost
function as an input. For more information, see “Write a Cost Function” on page
2-83. In the cost function, the simulator configured for fast restart is used to
update the model parameters, simulate the model, and log signals.
2-68
Use Fast Restart Mode During Parameter Estimation
Troubleshooting
Why Don’t I See the Estimation Speedup I Expected Using Fast Restart?
You see a speedup of design optimization tasks using fast restart in models that have a
long compilation phase. If the compilation phase of your model is not long, you do not see
a significant change in estimation speed.
See Also
fastRestart | sdo.Experiment | sdo.optimize
Related Examples
• “Improving Optimization Performance using Fast Restart (GUI)” on page 2-198
• “Improving Optimization Performance using Fast Restart (Code)” on page 2-206
More About
• “Ways to Speed Up Design Optimization Tasks”
2-69
2 Parameter Estimation
To tune the ICs of an integrator block with external ICs, you must modify the model to
make the external signal into a tunable parameter. For example, you can set the IC block
that feeds into the integrator to be a tunable variable and estimate it.
2-70
Estimation Sessions
Estimation Sessions
In this section...
“Structure of an Estimation Session” on page 2-71
“Save Parameter Estimation Tool Sessions” on page 2-71
“Load Parameter Estimation Tool Sessions” on page 2-72
“Load Legacy Projects” on page 2-72
The default session name is the same as the Simulink model name. The session name is
shown on the title pane of Parameter Estimation tool.
2-71
2 Parameter Estimation
You have the options to browse to the location where you want to save the session using
the Save to file option, or save to model workspace or MATLAB workspace.
You have the option to browse to where the session file is, or open a session from model
workspace or the MATLAB workspace. All sessions are MAT-files.
2-72
How the Software Formulates Parameter Estimation as an Optimization Problem
The optimization solver tunes the values of the design variables to satisfy the specified
objectives and constraints. The exact formulation of the optimization depends on the
optimization method that you use.
Cost Function
• “Types” on page 2-74
• “Time Base” on page 2-74
The software tunes the model parameters to obtain a simulated response (ysim) that
tracks the measured response or reference signal (yref). To do so, the solver minimizes the
cost function or estimation error, a measure of the difference between the simulated and
measured responses. The cost function, F(x), is the objective function of the optimization
problem.
2-73
2 Parameter Estimation
Types
The raw estimation error, e(t), is defined as:
Simulink Design Optimization software provides you the following cost functions to
process e(t):
Cost Function Formulation Option Name in GUI or
Command Line
Sum squared error (default) tN 'SSE'
F( x) = Â e(t) ¥ e(t)
t =0
Time Base
The software evaluates the cost function for a specific time interval. This interval is
dependent on the measured signal time base and the simulated signal time base.
• The measured signal time base consists of all the time points for which the measured
signal is specified. In case of multiple measured signals, this time base is the union of
the time points of all the measured signals.
2-74
How the Software Formulates Parameter Estimation as an Optimization Problem
• The simulated signal time base consists of all the time points for which the model is
simulated.
If the model uses a variable-step solver, then the simulated signal time base can change
from one optimization iteration to another. The simulated and measured signal time
bases can be different. The software evaluates the cost function for only the time interval
that is common to both. By default, the software uses only the time points specified by
the measured signal in the common time interval.
• In the GUI, you can specify the simulation start and stop times in the Simulation
time area of the Simulation Options dialog box.
• At the command line, the software specifies the simulation stop time as the last
point of the measured signal time base. For example, the following code simulates
the model until the end time of the longest running output signal of exp, an
sdo.Experiment object:
sim_obj = createSimulator(exp);
sim_obj = sim(sim_obj);
sim_obj contains the simulated response for the model associated with exp.
x£ x£x
x and x are the lower and upper bounds for the design variables.
For example, in a battery discharging experiment, the estimated battery initial charge
must be greater than zero and less than Inf. These bounds are expressed as:
0< x<•
For an example of how to specify these types of bounds, see “Estimate Model Parameters
and Initial States (Code)” on page 2-104.
You can also specify other constraints, C(x), on the design variables at the command line.
C(x) can be linear or nonlinear and can describe equalities or inequalities. C(x) can also
specify multiparameter constraints. For example, for a simple friction model, C(x) can
2-75
2 Parameter Estimation
specify that the static friction coefficient must be greater than or equal to the dynamic
friction coefficient. One way of expressing this constraint is:
C( x) : x1 - x2
C( x) £ 0
For an example of how to specify a constraint, see “Estimate Model Parameters with
Parameter Constraints (Code)” on page 2-142.
The optimization method that you specify determines the formulation of the estimation
problem. The software provides the following optimization methods:
2-76
How the Software Formulates Parameter Estimation as an Optimization Problem
2-77
2 Parameter Estimation
min g
[ x,g ]
s.t. C( x) £ g
x£ x£ x
g £0
2-78
How the Software Formulates Parameter Estimation as an Optimization Problem
min 0
x
s.t. C( x) £ 0
x£ x£ x
2-79
2 Parameter Estimation
Feasibility Problem
min max ( C ( x ) )
x
2-80
How the Software Formulates Parameter Estimation as an Optimization Problem
min G( x)
x
s.t. x £ x £ x
where
Ï• if max ( C( x) ) > 0
G( x) = Ì
Ó F ( x) otherwise.
Feasibility Problem
min max ( C ( x ) )
x
s.t. x£ x£ x
2-81
2 Parameter Estimation
See Also
fminbnd | fmincon | fminsearch | lsqnonlin | patternsearch | sdo.Experiment
| sdo.requirements.SignalTracking | sdo.requirements.SignalTracking |
sdo.SimulationTest
Related Examples
• “Estimate Model Parameter Values (Code)” on page 2-92
• “Estimate Model Parameters with Parameter Constraints (Code)” on page 2-142
• “Estimate Parameters from Measured Data”
More About
• “Write a Cost Function” on page 2-83
2-82
Write a Cost Function
The cost function can also be used for global sensitivity analysis. You generate
samples of the model parameters and evaluate the cost function for each sample using
sdo.evaluate.
• (Required) vals , a structure with one or more fields that specify the values of the
cost and constraint violations.
• (Optional) derivs, a structure with one or more fields that specify the values of
the gradients of the cost and constraint violations.
2-83
2 Parameter Estimation
Here, myCostFunc is the name of the MATLAB function and param is a vector of the
design variables.
Convenience Objects
The software provides you with the following convenience objects that can you can use in
the cost function:
2-84
Write a Cost Function
Inputs
• “Model Parameters and States” on page 2-85
• “Multiple Inputs” on page 2-86
2-85
2 Parameter Estimation
param_val = p(1).Value;
Multiple Inputs
sdo.optimize requires that the cost function accept only one input argument, params.
However, you might want your cost function to use additional inputs. For instance,
you could make the model name an input argument and configure the function to
be used for multiple models. To call sdo.optimize and use a function that accepts
more than one input argument, you use an anonymous function. For example, suppose
myCostFunc_mult_inputs is a cost function that takes param, arg1, and arg2 as
inputs. Then, assuming that all input arguments are variables in the workspace, you
enter:
Additional inputs can also help reduce code redundancy and computation cost, given that
the function is called repeatedly by sdo.optimize during optimization. If you use a
convenience object in your function, you can create it once, before calling sdo.optimize.
For example, you can create a simulator (sdo.SimulationTest object) to simulate your
model, and pass it to your cost function.
simulator = sdo.SimulationTest(model)
myCostFunc = @(param) myCostFunc_mult_inputs(param,arg1,arg2,simulator);
[param_opt,opt_info] = sdo.optimize(@myCostFunc,param);
Evaluate Requirements
The core of the cost function is where you evaluate how well the current design variables
satisfy the design requirements. You can use MATLAB functions to do so. You can also
use the requirements objects that the Simulink Design Optimization software provides.
These objects enable you to specify requirements such as step-response characteristics,
gain/phase margin bounds, Bode magnitude bounds, etc.
2-86
Write a Cost Function
• Parameter-only requirements — Extract the design variable values and compute the
requirement values.
For example, you can minimize the cylinder cross-sectional area, a design variable, in
a hydraulic cylinder. See “Design Optimization to Meet a Custom Objective (Code)” on
page 3-126.
• Model signal-based requirements — Simulate the model using the current design
variable values, extract the model response, and compute the requirement values.
• Using an sdo.SimulationTest object. You update the model parameter values using
the simulator’s Parameters property. Then, you use the sim method to simulate
the model and extract the logged signals from the simulator that are of interest.
For an example, see “Design Optimization to Meet a Custom Objective (Code)” on
page 3-126.
Note: In fast restart mode, you cannot use the linearize command. Use the
SystemLoggingInfo property of the sdo.SimulationTest object, to specify linear
systems to log when simulating the model. For an example, see “Design Optimization
to Meet Frequency-Domain Requirements (Code)” on page 3-252.
Outputs
• “Cost and Constraint Values” on page 2-88
2-87
2 Parameter Estimation
Your cost function must return a structure containing the cost and constraint values
for the current design variables. This structure must have one or more of the following
fields, as required by your optimization problem:
• F — Cost value.
• Cleq, Ceq — Nonlinear constraint values. The solver satisfies Cleq ≤ 0 and Ceq = 0.
• leq, eq — Linear constraint values. The solver satisfies leq ≤ 0 and eq = 0.
If you have multiple constraints of one type, concatenate the values into a vector,
and specify this vector as the corresponding field value. For instance, if you have a
hydraulic cylinder, you can specify nonlinear inequality constraints on the piston position
(Cleq1) and cylinder pressure (Cleq2). In this case, specify the Cleq field of the output
structure, vals, as:
For an example, see “Design Optimization to Meet a Custom Objective (Code)” on page
3-126.
By default, the software computes the cost and constraint gradients using numeric
perturbation. However, you can specify the gradients and return them as an additional
output. This output must be a structure with one or more of the following fields, as
required by your optimization problem:
• F — Cost derivatives.
• Cleq — Nonlinear inequality constraints derivatives.
• Ceq — Nonlinear equality constraints derivatives.
You must also set the GradFcn property of the optimization option set to 'on'.
Multiple Objectives
2-88
Write a Cost Function
least squares method, used for parameter estimation, requires that you return the error
residuals as a vector. In this case, the software minimizes the sum square of this vector.
If you are tracking multiple signals and using lsqnonlin, then you must concatenate
the error residuals for the different signals into one vector. Specify this vector as the F
field value.
For an example of single objective optimization using the gradient descent method, see
“Design Optimization to Meet a Custom Objective (Code)” on page 3-126.
For an example of multiple objective optimization using the nonlinear least squares
method, see “Estimate Model Parameters Per Experiment (Code)” on page 2-128.
See Also
sdo.OptimizeOptions | param.Continuous | sdo.SimulationTest | sdo.Experiment |
sdo.evaluate | sdo.optimize | sdo.setValueInModel
Related Examples
• “Design Optimization to Meet a Custom Objective (Code)” on page 3-126
• “Estimate Model Parameter Values (Code)” on page 2-92
More About
• “How the Optimization Algorithm Formulates Minimization Problems” on page
3-3
• “How the Software Formulates Parameter Estimation as an Optimization Problem”
on page 2-73
2-89
2 Parameter Estimation
Gradient Computations
For the Gradient descent (fmincon) optimization solver, the gradients are computed
using numerical perturbation:
Ê 1 ˆ
dx = 3 eps ¥ max Á| x|, xtypical ˜
Ë 10 ¯
dL = max ( x - dx, xmin )
dR = min ( x + d x, xmax )
FL = opt _ fcn(dL)
FR = opt _ fcn(dR)
dF ( FL - FR )
=
dx ( dL - dR )
If you want to compute the gradients in any other way, you can do so in the cost function
you write for performing design optimization programmatically. See sdo.optimize and
GradFcn of sdo.OptimizeOptions for more information.
See Also
fmincon
More About
• “How the Software Formulates Parameter Estimation as an Optimization Problem”
on page 2-73
2-90
Gradient Computations
2-91
2 Parameter Estimation
Aircraft Model
open_system('sdoAircraftEstimation')
Estimation Problem
You use measured data to estimate the aircraft model parameters and states.
2-92
Estimate Model Parameter Values (Code)
Parameters:
State:
[time,iodata] = sdoAircraftEstimation_Experiment;
Exp = sdo.Experiment('sdoAircraftEstimation');
PilotG = Simulink.SimulationData.Signal;
PilotG.Name = 'PilotG';
PilotG.BlockPath = 'sdoAircraftEstimation/Pilot G-force calculation';
PilotG.PortType = 'outport';
PilotG.PortIndex = 1;
PilotG.Values = timeseries(iodata(:,2),time);
2-93
2 Parameter Estimation
AoA = Simulink.SimulationData.Signal;
AoA.Name = 'AngleOfAttack';
AoA.BlockPath = 'sdoAircraftEstimation/Aircraft Dynamics Model';
AoA.PortType = 'outport';
AoA.PortIndex = 4;
AoA.Values = timeseries(iodata(:,1),time);
Add the measured pilot G-Force and angle of attack data to the experiment as the
expected output data.
Exp.OutputData = [...
PilotG; ...
AoA];
Add the initial state for the Actuator Model block to the experiment. Set its Free field
to true so that it is estimated.
Create a simulation scenario using the experiment and obtain the simulated output.
Simulator = createSimulator(Exp);
Simulator = sim(Simulator);
Search for the pilot G-Force and angle of attack signals in the logged simulation data.
SimLog = find(Simulator.LoggedData,get_param('sdoAircraftEstimation','SignalLoggi
PilotGSignal = find(SimLog,'PilotG');
AoASignal = find(SimLog,'AngleOfAttack');
As expected, the model response does not match the experimental output data.
2-94
Estimate Model Parameter Values (Code)
Select the model parameters that describe the flight control actuation system. Specify
bounds for the estimated parameter values based on our understanding of the actuation
system.
p = sdo.getParameterFromModel('sdoAircraftEstimation',{'Ta','Md','Zd'});
p(1).Minimum = 0.01; %Ta
p(1).Maximum = 1;
p(2).Minimum = -10; %Md
p(2).Maximum = 0;
p(3).Minimum = -100; %Zd
p(3).Maximum = 0;
2-95
2 Parameter Estimation
Get the actuator initial state value that is to be estimated from the experiment.
s = getValuesToEstimate(Exp);
v = [p;s]
v(1,1) =
Name: 'Ta'
Value: 0.5000
Minimum: 0.0100
Maximum: 1
Free: 1
Scale: 0.5000
Info: [1x1 struct]
v(2,1) =
Name: 'Md'
Value: -1
Minimum: -10
Maximum: 0
Free: 1
Scale: 1
Info: [1x1 struct]
v(3,1) =
Name: 'Zd'
Value: -80
Minimum: -100
Maximum: 0
Free: 1
Scale: 128
Info: [1x1 struct]
v(4,1) =
Name: 'sdoAircraftEstimation/Actuator...'
2-96
Estimate Model Parameter Values (Code)
Value: 0
Minimum: 0
Maximum: Inf
Free: 1
Scale: 1
dxValue: 0
dxFree: 1
Info: [1x1 struct]
4x1 param.Continuous
Create an estimation objective function to evaluate how closely the simulation output,
generated using the estimated parameter values, matches the measured data.
Use an anonymous function with one input argument that calls the
sdoAircraftEstimation_Objective function. We pass the anonymous function to
sdo.optimize, which evaluates the function at each optimization iteration.
estFcn = @(v) sdoAircraftEstimation_Objective(v,Simulator,Exp);
• Has one input argument that specifies the actuator parameter values and the
actuator initial state.
• Has one input argument that specifies the experiment object containing the measured
data.
2-97
2 Parameter Estimation
%%
% Define a signal tracking requirement to compute how well the model output
% matches the experiment data. Configure the tracking requirement so that
% it returns the tracking error residuals (rather than the
% sum-squared-error) and does not normalize the errors.
%
r = sdo.requirements.SignalTracking;
r.Type = '==';
r.Method = 'Residuals';
r.Normalize = 'off';
2-98
Estimate Model Parameter Values (Code)
%%
% Update the experiments with the estimated parameter values.
%
Exp = setEstimatedValues(Exp,v);
%%
% Simulate the model and compare model outputs with measured experiment
% data.
%
Simulator = createSimulator(Exp,Simulator);
Simulator = sim(Simulator);
SimLog = find(Simulator.LoggedData,get_param('sdoAircraftEstimation','SignalLoggi
PilotGSignal = find(SimLog,'PilotG');
AoASignal = find(SimLog,'AngleOfAttack');
PilotGError = evalRequirement(r,PilotGSignal.Values,Exp.OutputData(1).Values);
AoAError = evalRequirement(r,AoASignal.Values,Exp.OutputData(2).Values);
%%
% Return the residual errors to the optimization solver.
%
vals.F = [PilotGError(:); AoAError(:)];
end
Use the sdo.optimize function to estimate the actuator parameter values and initial
state.
2-99
2 Parameter Estimation
Step-size First-order
Iter F-count f(x) optimality
0 8 27972.2 1
1 17 10124.8 0.4744 5.69e+04
2 26 3127.92 0.3854 1.24e+04
3 35 872.751 0.4286 2.81e+03
4 44 238.66 0.5147 618
5 53 71.9182 0.493 147
6 62 17.2194 0.4163 44.9
7 71 1.82827 0.3069 11.4
8 80 0.0440753 0.1321 1.38
9 89 0.0020167 0.03129 0.0871
10 98 0.000244535 0.008145 0.119
11 107 5.74974e-05 0.005686 0.00522
Local minimum possible.
lsqnonlin stopped because the final change in the sum of squares relative to
its initial value is less than the selected value of the function tolerance.
vOpt(1,1) =
Name: 'Ta'
Value: 0.0500
Minimum: 0.0100
Maximum: 1
Free: 1
Scale: 0.5000
Info: [1x1 struct]
vOpt(2,1) =
Name: 'Md'
Value: -6.8848
Minimum: -10
Maximum: 0
Free: 1
Scale: 1
Info: [1x1 struct]
vOpt(3,1) =
2-100
Estimate Model Parameter Values (Code)
Name: 'Zd'
Value: -63.9983
Minimum: -100
Maximum: 0
Free: 1
Scale: 128
Info: [1x1 struct]
vOpt(4,1) =
Name: 'sdoAircraftEstimation/Actuator...'
Value: 6.3839e-05
Minimum: 0
Maximum: Inf
Free: 1
Scale: 1
dxValue: 0
dxFree: 1
Info: [1x1 struct]
4x1 param.Continuous
Exp = setEstimatedValues(Exp,vOpt);
Simulate the model using the updated experiment and compare the simulated output
with the experimental data.
The model response using the estimated parameter values closely matches the
experiment output data.
Simulator = createSimulator(Exp,Simulator);
Simulator = sim(Simulator);
SimLog = find(Simulator.LoggedData,get_param('sdoAircraftEstimation','SignalLoggi
PilotGSignal = find(SimLog,'PilotG');
AoASignal = find(SimLog,'AngleOfAttack');
2-101
2 Parameter Estimation
AoASignal.Values.Time,AoASignal.Values.Data,'-.', ...
PilotGSignal.Values.Time,PilotGSignal.Values.Data,'--')
title('Simulated and Measured Responses After Estimation')
legend('Measured angle of attack', 'Measured pilot g force', ...
'Simulated angle of attack', 'Simulated pilot g force');
Update the model with the estimated actuator parameter values. Do not update
the model actuator initial state (fourth element of vOpt) as it is dependent on the
experiment.
sdo.setValueInModel('sdoAircraftEstimation',vOpt(1:3));
2-102
Estimate Model Parameter Values (Code)
Related Examples
To learn how to estimate model parameters using the Parameter Estimation Tool, see
"Estimate Model Parameter Values (GUI)".
2-103
2 Parameter Estimation
RC Circuit Model
Estimation Problem
You use the measured data to estimate the RC model parameter and state values.
Parameter:
State:
2-104
Estimate Model Parameters and Initial States (Code)
The variables time and data are loaded into the workspace, where data is the
measured capacitor voltage for times time.
Add the measured capacitor data to the experiment as the expected output data.
Exp.OutputData = Voltage;
Create a simulation scenario using the experiment and obtain the simulated output.
Simulator = createSimulator(Exp);
Simulator = sim(Simulator);
The model response does not match the experimental output data.
plot(time,data,'ro',Voltage.Values.Time,Voltage.Values.Data,'b')
title('Simulated and Measured Responses Before Estimation')
2-105
2 Parameter Estimation
Select the capacitance parameter from the model. Specify an initial guess for the
capacitance value (460 uF) and a minimum bound (0 F).
p = sdo.getParameterFromModel('sdoRCCircuit','C1');
p.Value = 460e-6;
p.Minimum = 0;
Create an estimation objective function to evaluate how closely the simulation output,
generated using the estimated parameter value, matches the measured data.
2-106
Estimate Model Parameters and Initial States (Code)
Use an anonymous function with one input argument that calls the
sdoRCCircuit_Objective function. We pass the anonymous function to
sdo.optimize, which evaluates the function at each optimization iteration.
estFcn = @(v) sdoRCCircuit_Objective(v,Simulator,Exp);
• Has one input argument that specifies the estimated circuit capacitance value.
• Has one input argument that specifies the experiment object containing the measured
data.
The optimization solver minimizes the residual errors. For more details on how to write
an objective/constraint function to use with the sdo.optimize command, type help
sdoExampleCostFunction at the MATLAB command prompt.
2-107
2 Parameter Estimation
%
% The |Exp| input argument contains the estimation experiment data.
%
% The |vals| return argument contains information about how well the
% model simulation results match the experimental data and is used by
% the |sdo.optimize| function to estimate the model parameters.
%
% See also sdo.optimize, sdoExampleCostFunction, sdoRCCircuit_cmddemo
%
%%
% Define a signal tracking requirement to compute how well the model output
% matches the experiment data. Configure the tracking requirement so that
% it returns the tracking error residuals (rather than the
% sum-squared-error) and does not normalize the errors.
%
r = sdo.requirements.SignalTracking;
r.Type = '==';
r.Method = 'Residuals';
r.Normalize = 'off';
%%
% Update the experiments with the estimated parameter values.
%
Exp = setEstimatedValues(Exp,v);
%%
% Simulate the model and compare model outputs with measured experiment
% data.
%
Simulator = createSimulator(Exp,Simulator);
Simulator = sim(Simulator);
SimLog = find(Simulator.LoggedData,get_param('sdoRCCircuit','SignalLoggingName'));
Voltage = find(SimLog,'Voltage');
VoltageError = evalRequirement(r,Voltage.Values,Exp.OutputData(1).Values);
%%
% Return the residual errors to the optimization solver.
%
vals.F = VoltageError(:);
2-108
Estimate Model Parameters and Initial States (Code)
end
opt = sdo.OptimizeOptions;
opt.Method = 'lsqnonlin';
pOpt = sdo.optimize(estFcn,p,opt)
Step-size First-order
Iter F-count f(x) optimality
0 3 55.0041 1
1 6 21.0161 0.2124 17.2
2 9 11.5085 0.1272 6.08
3 12 9.56468 0.06553 1.99
4 15 9.27666 0.02744 0.442
5 18 9.27666 0.00717 0.442
6 21 9.27131 0.001793 0.356
Local minimum possible.
lsqnonlin stopped because the final change in the sum of squares relative to
its initial value is less than the selected value of the function tolerance.
pOpt =
Name: 'C1'
Value: 1.1600e-04
Minimum: 0
Maximum: Inf
Free: 1
Scale: 0.0020
Info: [1x1 struct]
2-109
2 Parameter Estimation
1x1 param.Continuous
Exp = setEstimatedValues(Exp,pOpt);
Create a simulation scenario using the experiment and obtain the simulated output.
Simulator = createSimulator(Exp,Simulator);
Simulator = sim(Simulator);
SimLog = find(Simulator.LoggedData,get_param('sdoRCCircuit','SignalLoggingName'));
Voltage = find(SimLog,'Voltage');
The simulated and measured signals match well, except for near time zero. This
mismatch is because the capacitor initial voltage defined in the model does not match the
initial voltage from the experiment.
plot(time,data,'ro',Voltage.Values.Time,Voltage.Values.Data,'b')
title('Simulated and Measured Responses After Estimation')
legend('Measured Voltage','Simulated Voltage')
2-110
Estimate Model Parameters and Initial States (Code)
Add the capacitor initial voltage for the C1 block to the experiment. Set its initial guess
value to 1 V.
Exp.InitialStates = sdo.getStateFromModel('sdoRCCircuit','C1');
Exp.InitialStates.Value = 1;
Recreate the estimation function to use the experiment with initial state estimation
Get the initial state and capacitance value that is to be estimated from the experiment.
2-111
2 Parameter Estimation
v = getValuesToEstimate(Exp);
Step-size First-order
Iter F-count f(x) optimality
0 5 4.66337 1
1 10 2.01883 1.533 21
2 15 1.34889 0.1257 0.0803
3 20 1.34365 0.0525 0.12
4 25 1.34363 0.001294 0.000711
Local minimum found.
vOpt(1,1) =
Name: 'sdoRCCircuit/C1:sdoRCCircuit.C1.vc'
Value: 2.3596
Minimum: -Inf
Maximum: Inf
Free: 1
Scale: 1
dxValue: 0
dxFree: 1
Info: [1x1 struct]
vOpt(2,1) =
Name: 'C1'
Value: 2.2638e-04
Minimum: 0
Maximum: Inf
Free: 1
Scale: 0.0020
Info: [1x1 struct]
2-112
Estimate Model Parameters and Initial States (Code)
2x1 param.Continuous
Update the experiment with the estimated capacitance and capacitor initial voltage
values.
Exp = setEstimatedValues(Exp,vOpt);
Simulate the model with the estimated initial-state and parameter values and compare
the simulated output with the experiment data.
Simulator = createSimulator(Exp,Simulator);
Simulator = sim(Simulator);
SimLog = find(Simulator.LoggedData,get_param('sdoRCCircuit','SignalLoggingName'));
Voltage = find(SimLog,'Voltage');
plot(time,data,'ro',Voltage.Values.Time,Voltage.Values.Data,'b')
title('Simulated and Measured Responses After Initial State and Model Parameter Estimat
legend('Measured Voltage','Simulated Voltage')
2-113
2 Parameter Estimation
Update the model with the estimated capacitance value. Do not update the model
capacitor initial voltage (first element of vOpt) as it is dependent on the experiment.
sdo.setValueInModel('sdoRCCircuit',vOpt(2));
Related Examples
To learn how to estimate model parameters using the sdo.optimize command, see
"Estimate Model Parameters and Initial States (GUI)".
2-114
Estimate Model Parameters and Initial States (Code)
bdclose('sdoRCCircuit')
2-115
2 Parameter Estimation
This example uses the sdoMassSpringDamper model. The model includes two
integrators to model the velocity and position of a mass in a mass-spring-damper system.
open_system('sdoMassSpringDamper');
load sdoMassSpringDamper_ExperimentData
The variables texp1, yexp1, texp2, and yexp2 are loaded into the workspace. yexp1
and yexp2 describe the mass position for times texp1 and texp2 respectively.
2-116
Estimate Model Parameters using Multiple Experiments (Code)
Create a 2-element array of experiment objects to store the measured data for the two
experiments.
Exp = sdo.Experiment('sdoMassSpringDamper');
MeasuredPos = Simulink.SimulationData.Signal;
MeasuredPos.Values = timeseries(yexp1,texp1);
MeasuredPos.BlockPath = 'sdoMassSpringDamper/Position';
MeasuredPos.PortType = 'outport';
MeasuredPos.PortIndex = 1;
MeasuredPos.Name = 'Position';
Add the measured mass position data to the experiment as the expected output data.
Exp.OutputData = MeasuredPos;
Create an object to specify the initial state for the Velocity block. The initial velocity of
the mass is 0 m/s.
sVel = sdo.getStateFromModel('sdoMassSpringDamper','Velocity');
sVel.Value = 0;
sVel.Free = false;
sVel.Free is set to false because the initial velocity is known and does not need to be
estimated.
Create an object to specify the initial state for the Position block. Specify a guess for
the initial mass position. Set the Free field of the initial position object to true so that it
is estimated.
sPos = sdo.getStateFromModel('sdoMassSpringDamper','Position');
sPos.Free = true;
sPos.Value = -0.1;
Exp.InitialStates = [sVel;sPos];
2-117
2 Parameter Estimation
Create a 2-element array of experiments. As the two experiments are identical except for
the expected output data, copy the first experiment twice.
Exp = [Exp; Exp];
Modify the expected output data of the second experiment object in Exp.
Exp(2).OutputData.Values = timeseries(yexp2,texp2);
Create a simulation scenario using the first experiment and obtain the simulated output.
Simulator = createSimulator(Exp(1));
Simulator = sim(Simulator);
The model response does not match the experimental output data.
subplot(211)
plot(...
Position(1).Values.Time,Position(1).Values.Data, ...
Exp(1).OutputData.Values.Time, Exp(1).OutputData.Values.Data,'--')
title('Experiment 1: Simulated and Measured Responses Before Estimation')
ylabel('Position')
legend('Measured Position','Simulated Position','Location','SouthEast')
subplot(212)
plot(...
Position(2).Values.Time,Position(2).Values.Data, ...
Exp(2).OutputData.Values.Time, Exp(2).OutputData.Values.Data,'--')
title('Experiment 2: Simulated and Measured Responses Before Estimation')
xlabel('Time (seconds)')
ylabel('Position')
2-118
Estimate Model Parameters using Multiple Experiments (Code)
Select the mass m, spring constant k, and damping coefficient b parameters from the
model. Specify that the estimated values for these parameters must be positive.
p = sdo.getParameterFromModel('sdoMassSpringDamper', {'b', 'k', 'm'});
p(1).Minimum = 0;
p(2).Minimum = 0;
p(3).Minimum = 0;
Get the position initial state values to be estimated from the experiment.
s = getValuesToEstimate(Exp);
2-119
2 Parameter Estimation
s contains two initial state objects, both for the Position block. Each object corresponds
to an experiment in Exp.
v(1,1) =
Name: 'b'
Value: 100
Minimum: 0
Maximum: Inf
Free: 1
Scale: 128
Info: [1x1 struct]
v(2,1) =
Name: 'k'
Value: 500
Minimum: 0
Maximum: Inf
Free: 1
Scale: 512
Info: [1x1 struct]
v(3,1) =
Name: 'm'
Value: 8
Minimum: 0
Maximum: Inf
Free: 1
Scale: 8
Info: [1x1 struct]
v(4,1) =
Name: 'sdoMassSpringDamper/Position'
Value: -0.1000
2-120
Estimate Model Parameters using Multiple Experiments (Code)
Minimum: -Inf
Maximum: Inf
Free: 1
Scale: 0.1250
dxValue: 0
dxFree: 1
Info: [1x1 struct]
v(5,1) =
Name: 'sdoMassSpringDamper/Position'
Value: -0.1000
Minimum: -Inf
Maximum: Inf
Free: 1
Scale: 0.1250
dxValue: 0
dxFree: 1
Info: [1x1 struct]
5x1 param.Continuous
Create an estimation objective function to evaluate how closely the simulation output,
generated using the estimated parameter values, matches the measured data.
Use an anonymous function with one input argument that calls the
sdoMassSpringDamper_Objective function. We pass the anonymous function to
sdo.optimize, which evaluates the function at each optimization iteration.
estFcn = @(v) sdoMassSpringDamper_Objective(v,Simulator,Exp);
• Has one input argument that specifies the mass, spring constant and damper values
as well as the initial mass position.
• Has one input argument that specifies the experiment object containing the measured
data.
2-121
2 Parameter Estimation
2-122
Estimate Model Parameters using Multiple Experiments (Code)
%%
% Define a signal tracking requirement to compute how well the model output
% matches the experiment data. Configure the tracking requirement so that
% it returns the tracking error residuals (rather than the
% sum-squared-error) and does not normalize the errors.
%
r = sdo.requirements.SignalTracking;
r.Type = '==';
r.Method = 'Residuals';
r.Normalize = 'off';
%%
% Update the experiments with the estimated parameter values.
%
Exp = setEstimatedValues(Exp,v);
%%
% Simulate the model and compare model outputs with measured experiment
% data.
%
Error = [];
for ct=1:numel(Exp)
Simulator = createSimulator(Exp(ct),Simulator);
Simulator = sim(Simulator);
SimLog = find(Simulator.LoggedData,get_param('sdoMassSpringDamper','SignalLoggingN
Position = find(SimLog,'Position');
PositionError = evalRequirement(r,Position.Values,Exp(ct).OutputData.Values);
%%
% Return the residual errors to the optimization solver.
%
vals.F = Error(:);
end
Use the sdo.optimize function to estimate the actuator parameter values and initial
state.
2-123
2 Parameter Estimation
Estimate the parameters. Notice that the initial mass position is estimated twice, once
for each experiment.
vOpt = sdo.optimize(estFcn,v,opt)
Step-size First-order
Iter F-count f(x) optimality
0 11 0.777696 1
1 22 0.00413099 3.696 0.00648
2 33 0.00118327 0.3194 0.00243
3 44 0.0011106 0.06718 5.09e-05
Local minimum found.
vOpt(1,1) =
Name: 'b'
Value: 58.1959
Minimum: 0
Maximum: Inf
Free: 1
Scale: 128
Info: [1x1 struct]
vOpt(2,1) =
Name: 'k'
Value: 399.9452
Minimum: 0
Maximum: Inf
Free: 1
2-124
Estimate Model Parameters using Multiple Experiments (Code)
Scale: 512
Info: [1x1 struct]
vOpt(3,1) =
Name: 'm'
Value: 9.7225
Minimum: 0
Maximum: Inf
Free: 1
Scale: 8
Info: [1x1 struct]
vOpt(4,1) =
Name: 'sdoMassSpringDamper/Position'
Value: 0.2995
Minimum: -Inf
Maximum: Inf
Free: 1
Scale: 0.1250
dxValue: 0
dxFree: 1
Info: [1x1 struct]
vOpt(5,1) =
Name: 'sdoMassSpringDamper/Position'
Value: 0.0994
Minimum: -Inf
Maximum: Inf
Free: 1
Scale: 0.1250
dxValue: 0
dxFree: 1
Info: [1x1 struct]
5x1 param.Continuous
2-125
2 Parameter Estimation
Exp = setEstimatedValues(Exp,vOpt);
Simulator = createSimulator(Exp(1),Simulator);
Simulator = sim(Simulator);
SimLog = find(Simulator.LoggedData,get_param('sdoMassSpringDamper','SignalLoggingN
Position(1) = find(SimLog,'Position');
Simulator = createSimulator(Exp(2),Simulator);
Simulator = sim(Simulator);
SimLog = find(Simulator.LoggedData,get_param('sdoMassSpringDamper','SignalLoggingN
Position(2) = find(SimLog,'Position');
The model response using the estimated parameter values nicely matches the output
data for the experiments.
subplot(211)
plot(...
Position(1).Values.Time,Position(1).Values.Data, ...
Exp(1).OutputData.Values.Time, Exp(1).OutputData.Values.Data,'--')
title('Experiment 1: Simulated and Measured Responses After Estimation')
ylabel('Position')
legend('Measured Position','Simulated Position','Location','NorthEast')
subplot(212)
plot(...
Position(2).Values.Time,Position(2).Values.Data, ...
Exp(2).OutputData.Values.Time, Exp(2).OutputData.Values.Data,'--')
title('Experiment 2: Simulated and Measured Responses After Estimation')
xlabel('Time (seconds)')
ylabel('Voltage')
legend('Measured Position','Simulated Position','Location','SouthEast')
2-126
Estimate Model Parameters using Multiple Experiments (Code)
Update the model m, k, and b parameter values. Do not update the model initial position
value as this is dependent on the experiment.
sdo.setValueInModel('sdoMassSpringDamper',vOpt(1:3));
2-127
2 Parameter Estimation
open_system('sdoBattery');
2-128
Estimate Model Parameters Per Experiment (Code)
Where:
• is the battery charge state, with 1 being fully charged and 0 zero charge.The battery
state-of-charge is computed from the integral of the battery current with a +ve
current indicating discharge and a -ve current indicating charging. The battery initial
state-of-charge is specified by in Ampere-Hour.
V, K, Qmax, Q0, and Loss are variables defined in the model workspace.
Load the experiment data. A 1.2V (6500mAh) battery was subjected to a discharge
experiment and a charging experiment.
load sdoBattery_ExperimentData
The variables Charge_Data and DCharge_Data are loaded into the workspace. The
first column of Charge_Data contains time data. The second and third columns of
Charge_Data describe the current and voltage during a battery charging experiment.
DCharge_Data is similarly structured and contains data for a battery discharging
experiment.
2-129
2 Parameter Estimation
plot(Charge_Data(:,1)/3600,Charge_Data(:,2))
title('Experiment: Charge')
xlabel('Time (hours)')
ylabel('Current (A)')
subplot(224)
plot(Charge_Data(:,1)/3600,Charge_Data(:,3))
xlabel('Time (hours)')
ylabel('Voltage (V)')
Create a 2-element array of experiment objects to specify the measured data for the two
experiments.
2-130
Estimate Model Parameters Per Experiment (Code)
Create an experiment object for the battery discharge experiment. The measured current
data is specified as a timeseries in the experiment object.
DCharge_Exp = sdo.Experiment('sdoBattery');
Add the voltage signal to the discharge experiment as the expected output data.
DCharge_Exp.OutputData = VoltageSig;
Specify the battery initial charge state for the experiment. The battery charge state
is modeled by the Q (Ah) block and it's initial value is specified by the variable Q0.
Create a parameter for the Q0 variable and add the parameter to the experiment. Q0 is
experiment dependent and assumes different values in the discharging and charging
experiments.
Q0 = sdo.getParameterFromModel('sdoBattery','Q0');
Q0.Value = 6.5;
Q0.Free = false;
Q0.Free is set to false because the initial battery charge is known and does not need to
be estimated.
Create an experiment object to store the charging experiment data. Add the measured
current input and measured voltage output data to the object.
Charge_Exp = sdo.Experiment('sdoBattery');
Charge_Exp.InputData = timeseries(Charge_Data(:,2),Charge_Data(:,1));
VoltageSig.Values = timeseries(Charge_Data(:,3),Charge_Data(:,1));
2-131
2 Parameter Estimation
Charge_Exp.OutputData = VoltageSig;
Add the battery initial charge and charging loss fraction parameters to the experiment.
For this experiment, the initial charge (Q0) is known (0 Ah), but the value of the charging
loss fraction (Loss) is not known.
Q0.Value = 0;
Loss = sdo.getParameterFromModel('sdoBattery','Loss');
Loss.Free = true;
Loss.Minimum = 0;
Loss.Maximum = 0.5;
Charge_Exp.Parameters = [Q0;Loss];
Create a simulation scenario using the first (discharging) experiment and obtain the
simulated output.
Simulator = createSimulator(Exp(1));
Simulator = sim(Simulator);
Obtain the simulated voltage signal for the second (charging) experiment.
Simulator = createSimulator(Exp(2),Simulator);
Simulator = sim(Simulator);
SimLog = find(Simulator.LoggedData,get_param('sdoBattery','SignalLoggingName'));
Voltage(2) = find(SimLog,'Voltage');
The model response does not match the experimental output data.
subplot(211)
2-132
Estimate Model Parameters Per Experiment (Code)
plot(...
Voltage(1).Values.Time/3600,Voltage(1).Values.Data, ...
Exp(1).OutputData.Values.Time/3600, Exp(1).OutputData.Values.Data,'-.')
title('Discharging Experiment: Simulated and Measured Responses Before Estimation')
ylabel('Voltage (V)')
legend('Simulated Voltage','Measured Voltage','Location','SouthWest')
subplot(212)
plot(...
Voltage(2).Values.Time/3600,Voltage(2).Values.Data, ...
Exp(2).OutputData.Values.Time/3600, Exp(2).OutputData.Values.Data,'-.')
title('Charging Experiment: Simulated and Measured Responses Before Estimation')
xlabel('Time (hours)')
ylabel('Voltage (V)')
legend('Simulated Voltage','Measured Voltage','Location','SouthEast')
2-133
2 Parameter Estimation
Estimate the values of the battery voltage V, the battery polarization resistance K, and
the charging loss fraction Loss. The V and K parameters are estimated using all the
experiment data while the Loss parameter is estimated using only the charging data.
Select the battery voltage V and the battery polarization resistance K parameters from
the model. Specify minimum and maximum bounds for these parameters.
p = sdo.getParameterFromModel('sdoBattery',{'V','K'});
p(1).Minimum = 0;
p(1).Maximum = 2;
p(2).Minimum = 1e-6;
p(2).Maximum = 1e-1;
s = getValuesToEstimate(Exp);
v = [p;s]
v(1,1) =
Name: 'V'
Value: 1.2000
Minimum: 0
Maximum: 2
Free: 1
Scale: 2
Info: [1x1 struct]
v(2,1) =
Name: 'K'
Value: 1.0000e-03
Minimum: 1.0000e-06
Maximum: 0.1000
Free: 1
2-134
Estimate Model Parameters Per Experiment (Code)
Scale: 0.0020
Info: [1x1 struct]
v(3,1) =
Name: 'Loss'
Value: 0.0100
Minimum: 0
Maximum: 0.5000
Free: 1
Scale: 0.0156
Info: [1x1 struct]
3x1 param.Continuous
Create an estimation objective function to evaluate how closely the simulation output,
generated using the estimated parameter values, matches the measured data.
Use an anonymous function with one input argument that calls the
sdoBattery_Objective function. We pass the anonymous function to sdo.optimize,
which evaluates the function at each optimization iteration.
estFcn = @(v) sdoBattery_Objective(v,Simulator,Exp);
• Has one input argument that specifies the estimated battery parameter values.
• Has one input argument that specifies the experiment object containing the measured
data.
2-135
2 Parameter Estimation
type sdoBattery_Objective
%%
% Define a signal tracking requirement to compute how well the model output
% matches the experiment data. Configure the tracking requirement so that
% it returns the tracking error residuals (rather than the
% sum-squared-error) and does not normalize the errors.
%
r = sdo.requirements.SignalTracking;
2-136
Estimate Model Parameters Per Experiment (Code)
r.Type = '==';
r.Method = 'Residuals';
r.Normalize = 'off';
%%
% Update the experiments with the estimated parameter values.
%
Exp = setEstimatedValues(Exp,v);
%%
% Simulate the model and compare model outputs with measured experiment
% data.
%
Error = [];
for ct=1:numel(Exp)
Simulator = createSimulator(Exp(ct),Simulator);
Simulator = sim(Simulator);
SimLog = find(Simulator.LoggedData,get_param('sdoBattery','SignalLoggingName'));
Voltage = find(SimLog,'Voltage');
VoltageError = evalRequirement(r,Voltage.Values,Exp(ct).OutputData(1).Values);
%%
% Return the residual errors to the optimization solver.
%
vals.F = Error(:);
end
2-137
2 Parameter Estimation
vOpt = sdo.optimize(estFcn,v,opt)
Step-size First-order
Iter F-count f(x) optimality
0 7 3272.22 1
1 14 619.356 0.1634 3.15e+05
2 21 411.131 0.2175 28.7
3 28 405.529 0.3838 2.16e+03
4 35 403.727 0.2767 15.2
5 42 403.379 0.1645 1.14e+03
Local minimum possible.
lsqnonlin stopped because the final change in the sum of squares relative to
its initial value is less than the selected value of the function tolerance.
vOpt(1,1) =
Name: 'V'
Value: 1.3083
Minimum: 0
Maximum: 2
Free: 1
Scale: 2
Info: [1x1 struct]
vOpt(2,1) =
Name: 'K'
Value: 0.0010
Minimum: 1.0000e-06
Maximum: 0.1000
Free: 1
Scale: 0.0020
Info: [1x1 struct]
vOpt(3,1) =
Name: 'Loss'
Value: 5.1801e-05
Minimum: 0
2-138
Estimate Model Parameters Per Experiment (Code)
Maximum: 0.5000
Free: 1
Scale: 0.0156
Info: [1x1 struct]
3x1 param.Continuous
The simulation results match the experimental data well except in the regions when
the battery is fully charged. This is not unexpected as the simple battery model does not
model the exponential voltage drop when the battery is fully charged.
subplot(211)
plot(...
Voltage(1).Values.Time/3600,Voltage(1).Values.Data, ...
Exp(1).OutputData.Values.Time/3600, Exp(1).OutputData.Values.Data,'-.')
title('Discharging Experiment: Simulated and Measured Responses After Estimation')
ylabel('Voltage (V)')
legend('Simulated Voltage','Measured Voltage','Location','SouthWest')
subplot(212)
plot(...
Voltage(2).Values.Time/3600,Voltage(2).Values.Data, ...
Exp(2).OutputData.Values.Time/3600, Exp(2).OutputData.Values.Data,'-.')
2-139
2 Parameter Estimation
Related Examples
To learn how to estimate the battery parameters using the Parameter Estimation Tool,
see "Estimate Model Parameters Per Experiment (GUI)".
2-140
Estimate Model Parameters Per Experiment (Code)
2-141
2 Parameter Estimation
You estimate dynamic and static friction coefficients of a simple friction system.
This example estimates parameters for a simple friction system, sdoFriction. The
model input is the force applied to a mass and the model outputs are the mass position
and velocity.
open_system('sdoFriction');
The model is based on a mass sliding on a surface. The mass is subject to a static friction
that must be overcome before the mass moves and a dynamic friction once the mass
moves. The static friction, u_static, is a fraction of the mass normal force; similarly the
dynamic friction, u_dynamic, is a fraction of the mass normal force.
2-142
Estimate Model Parameters with Parameter Constraints (Code)
Load the experiment data. The mass was subjected to an applied force and its position
recorded.
load sdoFriction_ExperimentData
The variables AppliedForce, Position, and Velocity are loaded into the workspace.
The first column of each of these variables represents time and the second column
represents the measured data. Because velocity is the first derivative of position, we only
use the position measurements for this example.
subplot(211),
plot(AppliedForce(:,1),AppliedForce(:,2))
title('Measured Applied Force Input for Simple Friction System');
ylabel('Applied Force (N)')
subplot(212)
plot(Position(:,1),Position(:,2))
title('Measured Mass Position for Simple Friction System');
xlabel('Time (seconds)')
ylabel('Position (m)')
2-143
2 Parameter Estimation
Exp = sdo.Experiment('sdoFriction');
Exp.InputData = timeseries(AppliedForce(:,2),AppliedForce(:,1));
PositionSig = Simulink.SimulationData.Signal;
2-144
Estimate Model Parameters with Parameter Constraints (Code)
PositionSig.Name = 'Position';
PositionSig.BlockPath = 'sdoFriction/x';
PositionSig.PortType = 'outport';
PositionSig.PortIndex = 1;
PositionSig.Values = timeseries(Position(:,2),Position(:,1));
Add the measured mass position data to the experiment as the expected output data.
Exp.OutputData = PositionSig;
Create a simulation scenario using the experiment and obtain the simulated output.
Simulator = createSimulator(Exp);
Simulator = sim(Simulator);
SimLog = find(Simulator.LoggedData,get_param('sdoFriction','SignalLoggingName'));
Position = find(SimLog,'Position');
As expected, the model response does not match the experimental output data.
figure
plot(...
Position.Values.Time,Position.Values.Data, ...
Exp.OutputData.Values.Time, Exp.OutputData.Values.Data,'-.')
title('Simulated and Measured Responses Before Estimation')
ylabel('Position (m)')
xlabel('Time (seconds)')
legend('Simulated Position','Measured Position','Location','NorthWest')
2-145
2 Parameter Estimation
Estimate the u_static and u_dynamic friction coefficients using the experiment data.
These coefficients are used as gains in the Static Friction and Dynamic Friction
blocks, respectively. Physics indicates that friction coefficients should be constrained
so that u_static u_dynamic; this parameter constraint is implemented in the
estimation objective function.
Select the u_static and u_dynamic model parameters. Specify bounds for the
estimated parameter values. Both coefficients are limited to the range [0 1].
p = sdo.getParameterFromModel('sdoFriction',{'u_static','u_dynamic'});
2-146
Estimate Model Parameters with Parameter Constraints (Code)
p(1).Minimum = 0;
p(1).Maximum = 1;
p(2).Minimum = 0;
p(2).Maximum = 1;
Create an estimation objective function to evaluate how closely the simulation output,
generated using the estimated parameter values, matches the measured data.
Use an anonymous function with one input argument that calls the
sdoFriction_Objective function. We pass the anonymous function to
sdo.optimize, which evaluates the function at each optimization iteration.
• Has one input argument that specifies the estimated friction coefficients.
• Has one input argument that specifies the experiment object containing the measured
data.
2-147
2 Parameter Estimation
type sdoFriction_Objective
%%
% Define a signal tracking requirement to compute how well the model output
% matches the experiment data. Configure the tracking requirement so that
% it returns the sum-squared-error.
%
r = sdo.requirements.SignalTracking;
r.Type = '==';
r.Method = 'SSE';
%%
% Update the experiments with the estimated parameter values.
%
Exp = setEstimatedValues(Exp,p);
%%
% Simulate the model and compare model outputs with measured experiment
2-148
Estimate Model Parameters with Parameter Constraints (Code)
% data.
%
Simulator = createSimulator(Exp,Simulator);
Simulator = sim(Simulator);
SimLog = find(Simulator.LoggedData,get_param('sdoFriction','SignalLoggingName'));
Position = find(SimLog,'Position');
PositionError = evalRequirement(r,Position.Values,Exp.OutputData(1).Values);
%%
% Measure how well the parameters satisfy the friction coefficient constraint,
% |u_static| >= |u_dynamic|. Note that constraints are returned to the
% optimizer in a c <=0 format. The friction coefficient constraint is
% rewritten accordingly.
PConstr = p(2).Value - p(1).Value; % u_dynamic - u_static <= 0
%%
% Return the sum-squared-error and constraint violation to the optimization
% solver.
%
vals.F = PositionError(:);
vals.Cleq = PConstr;
end
Use the sdo.optimize function to estimate the friction model parameter values.
2-149
2 Parameter Estimation
fmincon stopped because the size of the current step is less than
the selected value of the step size tolerance and constraints are
satisfied to within the selected value of the constraint tolerance.
pOpt(1,1) =
Name: 'u_static'
Value: 0.7973
Minimum: 0
Maximum: 1
Free: 1
Scale: 0.5000
Info: [1x1 struct]
pOpt(2,1) =
Name: 'u_dynamic'
Value: 0.4021
Minimum: 0
Maximum: 1
Free: 1
Scale: 0.2500
Info: [1x1 struct]
2-150
Estimate Model Parameters with Parameter Constraints (Code)
2x1 param.Continuous
Exp = setEstimatedValues(Exp,pOpt);
Simulator = createSimulator(Exp,Simulator);
Simulator = sim(Simulator);
SimLog = find(Simulator.LoggedData,get_param('sdoFriction','SignalLoggingName'));
Position = find(SimLog,'Position');
It can be seen that the model response using the estimated parameter values nicely
matches the experiment output data.
plot(...
Position.Values.Time,Position.Values.Data, ...
Exp.OutputData.Values.Time, Exp.OutputData.Values.Data,'-.')
title('Simulated and Measured Responses After Model Parameter Estimation')
ylabel('Position (m)')
xlabel('Time (seconds)')
legend('Simulated Position','Measured Position','Location','NorthWest')
2-151
2 Parameter Estimation
sdo.setValueInModel('sdoFriction',pOpt);
2-152
Estimate Model Parameter Values (GUI)
The Simulink® model for the engine throttle system, spe_engine_throttle, is shown
below.
The throttle controls the air mass flow into the intake manifold of an engine. The
throttle body contains a butterfly valve that opens when the driver presses down on the
accelerator pedal. This lets more air enter the cylinders and causes the engine to produce
more torque.
A DC motor controls the opening angle of the butterfly valve. There is also a spring
attached to the valve to return it to its closed position when the DC motor is de-
2-153
2 Parameter Estimation
The motor is modeled as a torque gain and a time-delay input with parameters Kt
and input_delay. The butterfly valve is modeled as a mass-spring-damper system with
parameters J, c and k. This system is augmented with hard stops to limit the valve
opening to 90 degrees. We know the model components, however, the parameter values of
the system are not known accurately.
Double-click the Parameter Estimation GUI with preloaded data block in the
model to open a pre-configured estimation GUI session.
The signal data for the experiments can be imported from various sources including
MATLAB® variables, MAT files, Excel® files, or comma-separated-value files. See
"Importing and Preprocessing Experiment Data (GUI)" for more information.
2-154
Estimate Model Parameter Values (GUI)
The experiment plot is also used to see how well the measured data matches the current
model. Click Plot Model Response to display simulated signal data on the experiment
plots.
2-155
2 Parameter Estimation
The simulation results show that the model does not match the measured data and that
model parameters need to be estimated.
Estimated Parameters
The next step is to define the parameter to estimate. Click Select Parameters to open
a dialog to select model parameters to estimate. In this example we have preselected the
four unknown parameters; the butterfly valve inertia, J; the damping coefficient, c; the
return spring constant, k; and the time lag in motor response, input_delay.
2-156
Estimate Model Parameter Values (GUI)
Since we know from physical insight that all of these parameters have positive
values, we set their lower limits to zero. We also put an upper bound of 0.1 sec on the
input_delay parameter. We can also select an initial value for the parameters. These
may come from some quick calculations of some formulas that determine the parameters.
Click the right arrow toggle button to modify the parameter minimum and maximum
bounds.
2-157
2 Parameter Estimation
With the parameters for estimation selected we select experiments to use for estimation.
Click Select Experiments and select EstimationData for estimation.
2-158
Estimate Model Parameter Values (GUI)
We are now almost ready to start our estimation but first create plots to monitor the
estimation progress. Click Add Plot and select Parameter Trajectory. This creates
a plot that shows how the estimated parameter values change during estimation. Click
the View tab to layout the plots so that the Experiment plot:EstimationData and
Iteration plot 1 are both visible.
2-159
2 Parameter Estimation
Click the Estimate button to start the estimation. You can modify estimation options by
setting the Cost Function combobox and clicking More Options....
While the estimation is running the plots update and a dialog showing estimation
progress appears. The progress dialog shows the estimation iterations, the number of
times the model has been evaluated (F-count), and the estimation cost at each iteration.
2-160
Estimate Model Parameter Values (GUI)
2-161
2 Parameter Estimation
After a number of iterations the estimation converges and terminates. The model is
updated with the estimated parameters and the estimation results are saved in the
data browser. Right click EstimatedParams and select Open... to see details of the
estimation result.
2-162
Estimate Model Parameter Values (GUI)
Validation
Click the Validation tab and click Select Experiments to select experiments for
validation. Select both ValidationData1 and ValidationData2 for validation.
2-163
2 Parameter Estimation
Click Select Results to select the estimation result(s) to use for validation. Select
EstimatedParams and deselect Use current parameter values.
Click Validate to validate the estimation result against the validation experiments.
Validation simulates the model using the estimated parameters and selected
experiments and creates plots showing the measured and simulation data. Use the
View tab to layout the plots so that the Experiment plot:ValidationData1 and
Experiment plot:ValidationData2 are both visible.
2-164
Estimate Model Parameter Values (GUI)
The valdiation plots confirm that our estimation was successful, showing that the
estimated parameters are robust enough to handle a variety of inputs.
Related Examples
To learn how to estimate model parameters using the sdo.optimize command, see
"Estimate Model Parameter Values (Code)".
2-165
2 Parameter Estimation
open_system('sdoBattery');
2-166
Estimate Model Parameters Per Experiment (GUI)
Where:
• is the battery charge state, with 1 being fully charged and 0 zero charge.The battery
state-of-charge is computed from the integral of the battery current with a +ve
current indicating discharge and a -ve current indicating charging. The battery initial
state-of-charge is specified by in Ampere-Hour.
V, K, Qmax, Q0, and Loss are variables defined in the model workspace.
A 1.2V (6500mAh) battery was subjected to a discharge and a charging experiment. This
experiment data has been loaded into a preconfigured estimation tool session.
From the sdoBattery model click Analysis and select the Parameter Estimation...
menu item to launch the Parameter Estimation tool. From the Parameter Estimation
tool click Open Session and select Open from model workspace and open the
sdoBattery_sdosession session. The measured charge and discharge experiment data
are loaded and plotted.
Click the View tab to layout the plots so that the Experiment plot:Charge_Exp and
Experiment plot:DCharge_Exp are both visible. Click Plot Model Response to see
how well the model simulation matches the measured experiment data.
2-167
2 Parameter Estimation
The plots show that the battery initial charge Q0 is not set correctly for the Charge_Exp
experiment and that the model V, K, and Loss parameters need to be estimated.
The previous plot indicates that the Charge_Exp battery initial charge, Q0, is not set
correctly. Add the initial charge to both experiments.
Right click Charge_Exp and select Edit.... A dialog to edit the experiment opens.
2-168
Estimate Model Parameters Per Experiment (GUI)
Click Select Parameters to open a dialog to add model parameters to the experiment.
Select Loss and Q0 to add to the experiment. Select Loss as we need to estimate this
parameter using only the Charge_Exp experiment. Click Ok to add the Q0 and Loss
parameters to the experiment.
2-169
2 Parameter Estimation
Set the battery initial charge Q0 in the Charge_Exp to 0, i.e. there is no initial charge.
2-170
Estimate Model Parameters Per Experiment (GUI)
Similarly add the battery initial charge Q0 to the DCharge_Exp experiment and set the
initial charge to 6.5., i.e. for this experiment there is an initial charge.
2-171
2 Parameter Estimation
Now that the experiements are updated with the correct initial battery charge click Plot
Model Response to simulate the model and compare measured and simuated data.
2-172
Estimate Model Parameters Per Experiment (GUI)
The experiment plots show that the experiment initial conditions match but the battery
response does not. The next step is to estimate the K and V model parameters.
The previous plot showed that the model response does not match the measured data and
we need to etimate the model V and K parameters.
2-173
2 Parameter Estimation
The upper portion of the select parameters dialog has a section for parameters that
are tuned using all experiments. Click Select Parameters and add the V and K model
parameters to the estimated parameters. Set the V minimum to 0 and the maximumn to
2, similarly set the K minimum to 1e-6 and maximum to 0.1.
2-174
Estimate Model Parameters Per Experiment (GUI)
2-175
2 Parameter Estimation
The lower section of the dialog has a section for initial states and parameters that are
tuned using individual experiments.
For the Charge_Exp we tune the Loss parameter and set its minimum to 0 maximum
to 0.5. The battery initial charge Q0 is fixed to 0 and should not be estimated; uncheck
Estimate.
2-176
Estimate Model Parameters Per Experiment (GUI)
Select DCharge_Exp from the Experiment combobox to view the parameter settings for
the DCharge_Exp experiment. The battery initial charge Q0 is fixed to 6.5 and should
not be estimated; uncheck Estimate
The experiments and estimated parameters are configured and we a ready to run the
estimation. First create a plot to monitor the estimation progress. Click Add Plot
and select Parameter Trajectory. This creates a plot that shows how the estimated
parameter values change during estimation. Click the View tab to layout the plots so
that the experiment and parameter trajectory plots are all visible.
2-177
2 Parameter Estimation
Click the Estimate button to start the estimation. You can modify estimation options by
setting the Cost Function combobox and clicking More Options....
While the estimation is running the plots update and a dialog showing estimation
progress appears. The progress dialog shows the estimation iterations, the number of
times the model has been evaluated (F-count), and the estimation cost at each iteration.
2-178
Estimate Model Parameters Per Experiment (GUI)
2-179
2 Parameter Estimation
After a number of iterations the estimation converges and terminates. The experiement
plots show the measured and simlation data matching well. The EstimatedParams plot
shows the V, K, and Loss parameters changing during the estimation; the scale of V and
K, Loss are different, right click on the plot and select Show scaled values to see how
all the parameters changed from their original values.
Related Examples
To learn how to estimate parameters per expriment using the sdo.optimize command,
see "Estimate Model Parameters Per Experiment (GUI)".
2-180
Estimate Model Parameters and Initial States (GUI)
The Simulink model for the mass-spring-damper system, msd_system, is shown below.
The model's output is the displacement response (position) of the mass in a mass-spring-
damper system, subject to a constant force (F), and an initial displacement (x0). x0 is the
initial condition of the Position integrator block. Run the simulation once to observe the
response of the model to a nominal set of parameter values.
2-181
2 Parameter Estimation
For estimation of the model parameters (m, b and k), two sets of experimental data are
used. These data sets were obtained using two different initial positions (0.1 and 0.3),
and contain additive noise. A plot of these data sets is shown below (orange and cyan
curves), along with the simulated response (yellow curve) of the Simulink model for
x0=-0.1 and a nominal set of parameter values (m=8, k=500, b=100).
The model has three parameters (k, b, m) that appear in the Gain blocks of the Simulink
model msd_system. We estimate these parameters using Parameter Estimation.
2-182
Estimate Model Parameters and Initial States (GUI)
The tool has been configured to estimate the model parameters using both data_exp1
and data_exp2 experiments, click Select Parameters to see the selected parameters
and Select Experiments to see the experiments selected for estimation.
Click Estimate to start the estimation. You can modify estimation options by setting the
Cost Function combobox and clicking More Options....
While the estimation is running the plots update and a dialog showing estimation
progress appears. The progress dialog shows the estimation iterations, the numberof
times the model has been evaluated (F-count), and the estimation cost at each iteration.
2-183
2 Parameter Estimation
2-184
Estimate Model Parameters and Initial States (GUI)
After a number of iterations the estimation converges and terminates. The model is
updated with the estimated parameters and the estimation results are saved in the data
browser.
The data_exp1 and data_exp2 experiment plots show that the model parameters
have been tuned to match the measured experiment data as closely as possible. The
simulated measured signals match well from the 2 second mark onward but don't match
well before 2 seconds. The simulation results for both experiments start at -0.1. This is
the initial condition of the model which was not estimated; these plots show that the
initial condition should also be estimated.
2-185
2 Parameter Estimation
The data_exp1 and data_exp2 experiments specify the measured output data but as
seen above must also specify the model initial state. We now add the initial states to the
experiments and estimate them.
Right click data_exp1 and select Edit... to open a dialog to configure the experiment.
Click Select Initial States and select the position state. Click OK to close the state
selector and add the selected state to the experiment.
2-186
Estimate Model Parameters and Initial States (GUI)
2-187
2 Parameter Estimation
Right click data_exp2 and select Edit.. and add the position state to the experiment.
The experiments are now configured to include initial states that can be estimated. Click
Select Parameters.
2-188
Estimate Model Parameters and Initial States (GUI)
The upper portion of the select parameters dialog has a section for parameters that are
tuned using all experiments selected for estimation. The lower section of the dialog has
a combo-box to select an experiment and widgets to specify initial states and parameters
that are tuned using only the selected experiment. For this problem the data_exp1 and
data_exp2 experiments estimate the model initial state for each experiment.
Now we are ready to start our estimation but first create plots to monitor the estimation
progress. Click Add Plot and select Parameter Trajectory, right click the plot and
select Show scaled values. This creates a plot that shows how the estimated parameter
values change during estimation. Click the View tab to layout the plots so that the
2-189
2 Parameter Estimation
After a number of iterations the estimation converges and terminates. The data_exp1
and data_exp2 experiment plots show how estimating the initial value inproves the
estimation fit. The EstimatedParams plot shows the estimated initial state for the two
experiments, the plot also shows that the estimated k value did not change while b and m
changed slightly. You can confirm this by clicking EstimatedParams and examining the
preview pane and then clicking EstimatedParams1 and examining the preview pane.
2-190
Estimate Model Parameters and Initial States (GUI)
Alternatively right click EstimatedParams and select Open... to open a dialog to view
the results.
This example shows that it is important to independently estimate initial states for each
experiment in order to obtain the correct estimates of the model parameters.
Related Examples
To learn how to estimate model parameters and initial states using the sdo.optimize
command, see "Estimate Model Parameters and Initial States (Code)".
2-191
2 Parameter Estimation
The "Estimate Model Parameters and Initial States" example shows how to use the
Parameter Estimation tool to estimate parameters of a mass-spring-damper model. In
this example we load a pre-configured Parameter Estimation tool session based on that
example.
load sdoMassSpringDamper_sdosession
spetool(SDOSessionData)
2-192
Generate MATLAB Code for Parameter Estimation Problems (GUI)
2-193
2 Parameter Estimation
2-194
Generate MATLAB Code for Parameter Estimation Problems (GUI)
The generated code is added to the MATLAB editor as an unsaved MATLAB function.
2-195
2 Parameter Estimation
Select Save from the MATLAB editor to save the generated function.
The first output argument, pOpt, contains the optimized parameter values and the
second output argument, optInfo, contains optimization information.
You can:
2-196
Generate MATLAB Code for Parameter Estimation Problems (GUI)
2-197
2 Parameter Estimation
Models where compilation is a significant portion of overall simulation time benefit the
most from Fast Restart. Further once a model is compiled not all model parameters can
be changed, specifically only tunable parameters can be changed, see "Factors Affecting
Fast Restart" in the Simulink documentation for more information.
Load the model and click the "Parameter Estimation with preloaded data" block to load
a preconfigured parameter estimation problem. The goal is to tune the parameters of an
engine throttle model to match measured data. For details on the problem setup see the
"Estimate Model Parameter Values (GUI)" example.
open_system('spe_engine_throttle')
2-198
Improving Optimization Performance using Fast Restart (GUI)
2-199
2 Parameter Estimation
To compare the estimation with and without fast restart, change the estimation options
in the tool to not update the model with estimated values.
Click Model Options... in the Parameter Estimation tool and clear Update model at
end of estimation, and select Save estimated values as new estimation result.
2-200
Improving Optimization Performance using Fast Restart (GUI)
Click Estimate in the tool to estimate the model parameter values. The estimation
progress report shows the estimation start and end time.
2-201
2 Parameter Estimation
To configure the model to use Fast Restart during simulation, click Enable Fast
Restart in the Simulink model.
2-202
Improving Optimization Performance using Fast Restart (GUI)
Click Estimate in the Parameter Estimation tool. The estimation progress report shows
the estimation start and end time. Note the reduction in total estimation time compared
to the estimation without using fast restart, in this case around 28 seconds or 45% of the
original estimation time.
2-203
2 Parameter Estimation
Related Examples
The Generate MATLAB Code feature of the Parameter Estimation and Response
Optimization tool will generate the MATLAB code to configure the model for fast restart
if the tool is configured to use fast restart.
To learn how to use Fast Restart at the command line see "Improving Optimization
Performance using Fast Restart (Code)".
2-204
Improving Optimization Performance using Fast Restart (GUI)
bdclose('spe_engine_throttle')
Related Examples
• “Improving Optimization Performance using Fast Restart (Code)” on page 2-206
• “Use Fast Restart Mode During Response Optimization” on page 3-227
• “Use Fast Restart Mode During Parameter Estimation” on page 2-67
• “Use Fast Restart Mode During Sensitivity Analysis” on page 4-17
More About
• “Ways to Speed Up Design Optimization Tasks”
2-205
2 Parameter Estimation
Models where compilation is a significant portion of overall simulation time benefit the
most from Fast Restart. Further once a model is compiled not all model parameters can
be changed, specifically only tunable parameters can be changed, see "Factors Affecting
Fast Restart" in the Simulink documentation for more information.
Open Model
Load the engine throttle model. The goal is to tune the parameters of the model to match
measured data. For details on the problem setup see the "Estimate Model Parameter
Values (GUI)" example.
open_system('spe_engine_throttle')
2-206
Improving Optimization Performance using Fast Restart (Code)
This examples focusses on the command line interface for using Fast Restart during
estimation. For a detailed description of the estimation command line interface see
"Estimate Model Parameter Values (Code)".
Specify the model parameter values to estimate and any parameter bounds .
p = sdo.getParameterFromModel('spe_engine_throttle',{'J','c','input_delay','k'});
p(1).Minimum = 0;
p(2).Minimum = 0;
p(3).Minimum = 0;
p(3).Maximum = 0.1;
p(4).Minimum = 0;
Define the estimation experiment. The measured experiment data is loaded from the
sdoFastRestart_ExperimentData MATLAB file. The MATLAB file contains a
Input_SignalData and Output_SignalData variable specifying the experiment input
and output signal data.
load spe_engine_throttle_ExperimentData
2-207
2 Parameter Estimation
Exp = sdo.Experiment('spe_engine_throttle');
Input = Simulink.SimulationData.Signal;
Input.Values = Input_SignalData;
Input.BlockPath = 'spe_engine_throttle/Input';
Input.PortType = 'inport';
Input.PortIndex = 1;
Input.Name = 'spe_engine_throttle/Input:1';
Exp.InputData = Input;
Output = Simulink.SimulationData.Signal;
Output.Values = Output_SignalData;
Output.BlockPath = 'spe_engine_throttle/Throttle';
Output.PortType = 'outport';
Output.PortIndex = 1;
Output.Name = 'spe_engine_throttle/Throttle:1';
Exp.OutputData = Output;
The simulator controls whether the model is simulated using fast restart or not. The
fastRestart command is used to configure the simulator to use Fast Restart.
The spe_engine_throttle model uses a variable-step solver, and may not output
values at the times in the measured experiment data. To output values at the times of
the measured data, use the set_param command to specify the model logging output
times as a workspace variable. In the estimation objective function, the variable is then
used to specify output times to be the same as the measured experiment data. The model
OutputTimes is set before configuring the simualtor for fast restart, as once the model is
configured for fast restart, the model logging configuration can not change.
set_param('spe_engine_throttle','OutputOption','SpecifiedOutputTimes','OutputTimes','Ou
Simulator = fastRestart(Simulator,'on');
The simulator can now be used during estimation, and the model will be simulated using
fast restart.
2-208
Improving Optimization Performance using Fast Restart (Code)
Step-size First-order
Iter F-count f(x) optimality
0 9 32.048 1
1 18 12.24 0.6495 18
2 27 3.59416 0.3919 8.65
3 36 1.11975 0.1879 3.11
4 45 0.649091 0.1966 1.25
5 54 0.287581 1.297 1.15
6 63 0.147631 0.2294 0.403
7 72 0.0874265 0.5347 0.1
8 81 0.0677538 0.3657 0.266
9 90 0.0677538 10 0.266
10 99 0.0677538 2.293 0.266
11 108 0.0673433 0.1971 0.185
Local minimum possible.
lsqnonlin stopped because the final change in the sum of squares relative to
its initial value is less than the selected value of the function tolerance.
Restore the simulator fast restart settings. This clears the logging and other settings
used for the optimization problem.
Simulator = fastRestart(Simulator,'off');
set_param('spe_engine_throttle','OutputOption','RefineOutputTimes','OutputTimes','[]');
Related Examples
You can also generate code to configure you model for fast restart in the Parameter
Estimation and Response Optimization tools. Configure the model for fast restart as
2-209
2 Parameter Estimation
described in "Improving Optimization Performance using Fast Restart (GUI)". Then use
the Generate MATLAB Code feature of the tool.
See Also
sdo.SimulationTest | fastRestart
Related Examples
• “Improving Optimization Performance using Fast Restart (GUI)” on page 2-198
• “Use Fast Restart Mode During Response Optimization” on page 3-227
• “Use Fast Restart Mode During Parameter Estimation” on page 2-67
• “Use Fast Restart Mode During Sensitivity Analysis” on page 4-17
More About
• “Ways to Speed Up Design Optimization Tasks”
2-210
3
Response Optimization
3-2
How the Optimization Algorithm Formulates Minimization Problems
This topic describes how the software formulates the constrained optimization problem
used by the optimization algorithms. For each optimization algorithm, the software
formulates one of the following types of minimization problems:
• Feasibility
• Tracking
• Mixed feasibility and tracking
For more information on how each optimization algorithm formulates these problems,
see:
In the following figure, x1, x3, and xn represent a combination of parameter values P1 and
P2 and are feasible solutions because they do not violate the lower bound constraint.
3-3
3 Response Optimization
P2
x2 x3
x1
xn
Violation Lower
Bound
P1
In a Simulink model, you constrain a signal by specifying lower and upper bounds in a
Check block (Check Step Response Characteristics, ...) or a requirement object
(sdo.requirements.StepResponseEnvelope, ...), as shown in the following figure.
Upper Bounds
Lower Bounds
These constraints are piecewise linear bounds. A piecewise linear bound ybnd with n edges
can be represented as:
Ï y1 ( t) t1 £ t £ t2
Ô y (t) t £ t £ t
Ô
ybnd ( t) = Ì 2 2 3
,
Ô M M
ÔÓ yn (t) tn £ t £ tn+1
The software computes the signed distance between the simulated response and the edge.
The signed distance for lower bounds is:
3-4
How the Optimization Algorithm Formulates Minimization Problems
where ysim is the simulated response and is a function of the parameters being optimized.
At the command line, opt_fcn supplies c directly from the Cleq field of vals.
If all the constraints are met (c ≤ 0) for some combination of parameter values, then that
solution is said to be feasible. In the following figure, x1 and x3 are feasible solutions.
P2
Violation
x2
x3
x1
xn
P1
When your model has multiple requirements or vector signals feeding a requirement, the
constraint vector is extended with the constraint violations for each signal and bound:
C = [ c1 ; c2 ;L ; cn ] .
3-5
3 Response Optimization
Tracking Problem
In addition to lower and upper bounds, you can specify a reference signal in a Check
Against Reference block or sdo.requirements.SignalTracking object, which the
Simulink model output can track. The tracking objective is a sum-squared-error tracking
objective.
A new time base, tnew, is formed from the union of the elements of tref and tsim. Elements
that are not within the minimum-maximum range of both tref and tsim are omitted:
Using linear interpolation, the software computes the values of yref and ysim at the time
points in tnew and then computes the scaled error:
e( tnew ) =
( ysim (tnew ) - yref (tnew )) .
max yref
tnew
f = w ( t ) e( t) 2 dt.
Ú
Note: The weight w(t) is 1 by default. You can specify a different value of weight only at
the command line.
3-6
How the Optimization Algorithm Formulates Minimization Problems
When your model has requirements or vector signals feeding a requirement, the tracking
objective equals the sum of the individual tracking integral errors for each signal:
F= Â fi .
min g
[ x,g ]
s.t. C( x) £ g
x£ x£ x
g £0
min 0
x
s.t. C( x) £ 0
x£ x£ x
Tracking Problem The software formulates the tracking objective F(x) as described in
“Tracking Problem” on page 3-6 and minimizes the tracking
objective:
3-7
3 Response Optimization
min max ( C ( x ) )
x
Tracking Problem The software formulates the tracking objective F(x) as described in
“Tracking Problem” on page 3-6 and then minimizes the tracking
objective:
min F( x)
x
Mixed Feasibility and The software formulates the problem in two steps:
Tracking Problem
3-8
How the Optimization Algorithm Formulates Minimization Problems
min max ( C ( x ) )
x
min G ( x)
x
where
Ï• if max ( C( x) ) > 0
G( x) = Ì
Ó F ( x) otherwise.
min max ( C ( x ) )
x
s.t. x£ x£ x
Tracking Problem The software formulates the tracking objective F(x) as described in
“Tracking Problem” on page 3-6 and then minimizes the tracking
objective:
min F( x)
x
s.t. x£ x£ x
3-9
3 Response Optimization
min max ( C ( x ) )
x
s.t. x£ x£ x
min G( x)
x
s.t. x £ x £ x
where
Ï• if max ( C( x) ) > 0
G( x) = Ì
Ó F( x) otherwise.
Gradient Computations
For the Gradient descent (fmincon) optimization solver, the gradients are computed
using numerical perturbation:
Ê 1 ˆ
dx = 3 eps ¥ max Á| x|, xtypical ˜
Ë 10 ¯
dL = max ( x - dx, xmin )
dR = min ( x + d x, xmax )
FL = opt _ fcn(dL)
FR = opt _ fcn(dR)
dF ( FL - FR )
=
dx ( dL - dR )
3-10
How the Optimization Algorithm Formulates Minimization Problems
If you want to compute the gradients in any other way, you can do so in the cost function
you write for performing design optimization programmatically. See sdo.optimize and
GradFcn of sdo.OptimizeOptions for more information.
3-11
3 Response Optimization
1 In the Response Optimization tool, select Signal in the New drop-down list. A
window opens where you select a signal to log.
2 In the Simulink model window, click the signal to which you want to add a
requirement.
The window updates and displays the name of the block and the port number where
the selected signal is located.
3
Select the signal and click to add it to the signal set.
4 In the Signal set box, enter a name for the selected signal set.
Click OK. A new variable, with the specified name, appears in the Data area of the
Response Optimization tool window.
See Also
3-12
Specifying Step Response Characteristics
1 You can apply this requirement to either a signal or a linearization of your model.
A window opens where you specify the step response requirements on a signal, or
system.
2 Specify a requirement name in the Name box.
3 Specify the step response characteristics:
% Overshoot
% Settling
Final Value
% Rise
Amplitude
% Undershoot
Initial Value
3-13
3 Response Optimization
In the Select Signals to Bound area, select a logged signal to which you will
apply the requirement.
a
Click . A window opens where you specify the logged signal.
b In the Simulink model window, click the signal to which you want to add a
requirement.
3-14
Specifying Step Response Characteristics
The window updates and displays the name of the block and the port number
where the selected signal is located.
c
Select the signal and click to add it to the signal set.
d In the Signal set box, enter a name for the selected signal set.
Click OK. A new variable, with the specified name, appears in the Data area
of the Response Optimization tool window.
• Apply this requirement to a linear system.
Linear systems are defined by snapshot times at which the model is linearized
and sets of linearization I/O points defining the system inputs and outputs.
a Specify the simulation time at which the model is linearized using the
Snapshot Times box. For multiple simulation snapshot times, specify a
vector.
b Select the linearization input/output set from the Linearization I/O area.
3-15
3 Response Optimization
For more information on using this dialog box, see “Create Linearization I/O
Sets” on page 3-77.
A variable with the specified requirement name appears in the Data area of the tool.
A graphical display of the requirement also appears in the Response Optimization
tool window.
Alternatively, you can use the Check Step Response Characteristics block to
specify step response bounds for a signal.
See Also
More About
• “Specify Time-Domain Design Requirements” on page 3-23
• “Specify Frequency-Domain Design Requirements” on page 3-39
3-16
Specifying Custom Requirements
1 In the Response Optimization tool, select Custom Requirement in the New list. A
window opens where you specify the custom requirement.
2 Specify a requirement name in the Name box.
3 Specify the requirement type using the Type list.
4 Specify the name of the function that contains the custom requirement in the
Function box. The field must be specified as a function handle using @. The function
If the function does not exist, clicking opens a template MATLAB file.
Use this file to implement the custom requirement. The default function name is
myCustomRequirement.
5 (Optional) If you want to prevent the solver from considering specific parameter
combinations, select the Error if constraint is violated check box. Use this option
for parameter-only constraints.
During an optimization iteration, the solver evaluates requirements with this option
selected first.
For more information, see “Skip Model Simulation Based on Parameter Constraint
Violation (GUI)” on page 3-188.
Note: If you select this check box, then do not specify signals or systems to bound. If
you do specify signals or systems, then this check box is ignored.
6 (Optional) Specify the signal or system, or both, to be bound.
3-17
3 Response Optimization
You can apply this requirement to model signals, or a linearization of your Simulink
model (requires Simulink Control Design software), or both.
Click Select Signals and Systems to Bound (Optional) to view the signal and
linearization I/O selection area.
In the Signal area, select a logged signal to which you will apply the
requirement.
a
Click . A window opens where you specify the logged signal.
b In the Simulink model window, click the signal to which you want to add a
requirement.
The window updates and displays the name of the block and the port number
where the selected signal is located.
c
Select the signal and click to add it to the signal set.
d In the Signal set box, enter a name for the selected signal set.
3-18
Specifying Custom Requirements
Click OK. A new variable, with the specified name, appears in the Data area
of the Response Optimization tool window.
• Apply this requirement to a linear system.
Linear systems are defined by snapshot times at which the model is linearized
and sets of linearization I/O points defining the system inputs and outputs.
a Specify the simulation time at which the model is linearized using the
Snapshot Times box. For multiple simulation snapshot times, specify a
vector.
b Select the linearization input/output set from the Linearization I/O area.
A new variable, with the specified name, appears in the Data area of the Response
Optimization tool. A graphical display of the requirement also appears in the
Response Optimization tool window.
Related Examples
• “Design Optimization to Meet a Custom Objective (GUI)” on page 3-108
• “Design Optimization to Meet Custom Signal Requirements (GUI)” on page 3-135
• “Specify Time-Domain Design Requirements” on page 3-23
• “Specify Frequency-Domain Design Requirements” on page 3-39
3-19
3 Response Optimization
Move Constraints
In this section...
“Move Constraints Graphically” on page 3-20
“Position Constraints Exactly” on page 3-21
3-20
Move Constraints
change to a four-way arrow. While still holding the button down, drag the pointer to
the target location, and release the mouse button. Note that the edges on either side
of the boundary might not maintain their slopes.
To move a constraint edge to a perfectly horizontal or vertical position, hold down the
Shift key while clicking and dragging the constraint edge. This causes the constraint
edge to snap to a horizontal or vertical position.
When moving constraint bound edges, it is sometimes helpful to display gridlines on the
axes for careful alignment of the constraint bound edges. To turn the gridlines on or off,
right-click within the axes and select Grid.
Note: You can move a lower bound constraint edge above an upper bound constraint
edge, or vice versa, but this produces an error when you attempt to run the optimization.
1 Position the pointer over the edge you want to move and right-click. Select Edit to
open the Edit Design Requirement dialog box.
3-21
3 Response Optimization
2 Specify the position of each constraint edge in the Time and Amplitude columns.
More About
• “Specify Time-Domain Design Requirements” on page 3-23
• “Specify Frequency-Domain Design Requirements” on page 3-39
3-22
Specify Time-Domain Design Requirements
1 In the Response Optimization tool, select Signal Bound in the New drop-down list.
A window opens where you specify upper or lower bounds on a signal.
2 Specify a requirement name in the Name box.
3 Select the requirement type using the Type list.
4 Specify the edge start and end times and corresponding amplitude in the Time (s)
and Amplitude columns.
5
Click to specify additional bound edges.
If you have already selected signals, as described in “Specify Signals to Log” on page
3-12, they appear in the list. Select the corresponding check-box.
a
Click . A window opens where you specify the logged signal.
b In the Simulink model window, click the signal to which you want to add a
requirement.
3-23
3 Response Optimization
The window updates and displays the name of the block and the port number
where the selected signal is located.
c
Select the signal and click to add it to the signal set.
d In the Signal set box, enter a name for the selected signal set.
Click OK. A new variable, with the specified name, appears in the Data area of
the Response Optimization tool window.
7 Click OK.
A variable with the specified requirement name appears in the Data area of the tool.
A graphical display of the requirement also appears in the Response Optimization
tool window.
8 (Optional) In the graphical display, you can:
Alternatively, you can add a Check Custom Bounds block to your model to specify
piecewise-linear bounds.
3-24
Specify Time-Domain Design Requirements
1 In the Response Optimization tool, select Signal Property in the New drop-down
list. The Create Requirement window opens where you specify signal property
requirements.
2 In the Name box, specify a requirement name.
3 In the Specify Property area, specify a signal property requirement using the
Property and Type lists and the Bound box.
Property List
For a signal S(t0 ),º, S(tN ) you can specify one of the following properties using the
Property list:
• tN
Signal sum square — Â S(i)2
i =t 0
• tN
Signal sum absolute — Â S(i)
i =t 0
You can add a custom signal property to the Property list by editing the function
sdo.requirements.signalPropertyFcns.
3-25
3 Response Optimization
a
Click . The Create Signal Set window opens where you specify the logged
signal.
b In the Simulink model window, click the signal to which you want to add a
requirement.
The window updates and displays the name of the block and the port number
where the selected signal is located.
c
Select the signal and click to add it to the signal set.
d In the Signal set box, enter a name for the selected signal set.
3-26
Specify Time-Domain Design Requirements
Click OK. A new variable, with the specified name, appears in the Data area of
the Response Optimization tool window.
5 Click OK.
A variable with the specified requirement name appears in the Data area of the tool.
An iteration plot depicting the signal property for each iteration also appears in the
Response Optimization tool window.
1 You can apply this requirement to either a signal or a linearization of your model.
A window opens where you specify the step response requirements on a signal, or
system.
2 Specify a requirement name in the Name box.
3 Specify the step response characteristics:
3-27
3 Response Optimization
% Overshoot
% Settling
Final Value
% Rise
Amplitude
% Undershoot
Initial Value
3-28
Specify Time-Domain Design Requirements
In the Select Signals to Bound area, select a logged signal to which you will
apply the requirement.
a
Click . A window opens where you specify the logged signal.
b In the Simulink model window, click the signal to which you want to add a
requirement.
The window updates and displays the name of the block and the port number
where the selected signal is located.
c
Select the signal and click to add it to the signal set.
d In the Signal set box, enter a name for the selected signal set.
3-29
3 Response Optimization
Click OK. A new variable, with the specified name, appears in the Data area
of the Response Optimization tool window.
• Apply this requirement to a linear system.
Linear systems are defined by snapshot times at which the model is linearized
and sets of linearization I/O points defining the system inputs and outputs.
a Specify the simulation time at which the model is linearized using the
Snapshot Times box. For multiple simulation snapshot times, specify a
vector.
b Select the linearization input/output set from the Linearization I/O area.
For more information on using this dialog box, see “Create Linearization I/O
Sets” on page 3-77.
A variable with the specified requirement name appears in the Data area of the tool.
A graphical display of the requirement also appears in the Response Optimization
tool window.
Alternatively, you can use the Check Step Response Characteristics block to
specify step response bounds for a signal.
See Also
3-30
Specify Time-Domain Design Requirements
1 In the Response Optimization tool, select Signal Tracking in the New drop-down
list. A window opens where you specify the reference signal to track.
2 Specify a requirement name in the Name box.
3 Define the reference signal by entering vectors, or variables from the workspace, in
the Time vector and Amplitude fields.
Click Update reference signal data to use the new amplitude and time vector as
the reference signal.
4 Specify how the optimization solver minimizes the error between the reference and
model signals using the Tracking Method list:
a
Click . A window opens where you specify the logged signal.
b In the Simulink model window, click the signal to which you want to add a
requirement.
3-31
3 Response Optimization
The window updates and displays the name of the block and the port number
where the selected signal is located.
c
Select the signal and click to add it to the signal set.
d In the Signal set box, enter a name for the selected signal set.
Click OK. A new variable, with the specified name, appears in the Data area of
the Response Optimization tool window.
e Select the check-box corresponding to the signal and click OK.
A variable with the specified requirement name appears in the Data area of the tool.
A graphical display of the signal bound also appears in the Response Optimization
tool window.
Note: When tracking a reference signal, the software ignores the maximally feasible
solution option. For more information on this option, see “Selecting Optimization
Termination Options” on page 3-74.
Alternatively, you can use the Check Against Reference block to specify a reference
signal to track.
See Also
1 In the Response Optimization tool, select Custom Requirement in the New list. A
window opens where you specify the custom requirement.
2 Specify a requirement name in the Name box.
3 Specify the requirement type using the Type list.
4 Specify the name of the function that contains the custom requirement in the
Function box. The field must be specified as a function handle using @. The function
3-32
Specify Time-Domain Design Requirements
If the function does not exist, clicking opens a template MATLAB file.
Use this file to implement the custom requirement. The default function name is
myCustomRequirement.
5 (Optional) If you want to prevent the solver from considering specific parameter
combinations, select the Error if constraint is violated check box. Use this option
for parameter-only constraints.
During an optimization iteration, the solver evaluates requirements with this option
selected first.
For more information, see “Skip Model Simulation Based on Parameter Constraint
Violation (GUI)” on page 3-188.
Note: If you select this check box, then do not specify signals or systems to bound. If
you do specify signals or systems, then this check box is ignored.
6 (Optional) Specify the signal or system, or both, to be bound.
You can apply this requirement to model signals, or a linearization of your Simulink
model (requires Simulink Control Design software), or both.
Click Select Signals and Systems to Bound (Optional) to view the signal and
linearization I/O selection area.
In the Signal area, select a logged signal to which you will apply the
requirement.
3-33
3 Response Optimization
a
Click . A window opens where you specify the logged signal.
b In the Simulink model window, click the signal to which you want to add a
requirement.
The window updates and displays the name of the block and the port number
where the selected signal is located.
c
Select the signal and click to add it to the signal set.
d In the Signal set box, enter a name for the selected signal set.
Click OK. A new variable, with the specified name, appears in the Data area
of the Response Optimization tool window.
• Apply this requirement to a linear system.
Linear systems are defined by snapshot times at which the model is linearized
and sets of linearization I/O points defining the system inputs and outputs.
a Specify the simulation time at which the model is linearized using the
Snapshot Times box. For multiple simulation snapshot times, specify a
vector.
b Select the linearization input/output set from the Linearization I/O area.
3-34
Specify Time-Domain Design Requirements
A new variable, with the specified name, appears in the Data area of the Response
Optimization tool. A graphical display of the requirement also appears in the
Response Optimization tool window.
See Also
The upper panel of the Edit Design Requirement dialog box resembles the image in the
following figure.
In the context of the SISO Tool in Control System Toolbox™ software, Design
requirement refers to both the particular editor within the SISO Tool that contains the
requirement and the particular requirement within that editor. To edit other constraints
within the SISO Tool, select another design requirement from the drop-down menu.
The particular parameters shown within the lower panel of the Edit Design Requirement
dialog box depend on the type of constraint/requirement. In some cases, the lower panel
3-35
3 Response Optimization
contains a grid with one row for each segment and one column for each constraint
parameter. The following table summarizes the various constraint parameters.
3-36
Edit Design Requirements
The upper panel of the Edit Design Requirement dialog box resembles the image in the
following figure.
In the context of the SISO Tool in Control System Toolbox software, Design
requirement refers to both the particular editor within the SISO Tool that contains the
requirement and the particular requirement within that editor. To edit other constraints
within the SISO Tool, select another design requirement from the drop-down menu.
3-37
3 Response Optimization
3-38
Specify Frequency-Domain Design Requirements
In this section...
“Specify Lower Bounds on Gain and Phase Margin” on page 3-39
“Specify Piecewise-Linear Lower and Upper Bounds on Frequency Response” on page
3-41
“Specify Bound on Closed-Loop Peak Gain” on page 3-43
“Specify Lower Bound on Damping Ratio” on page 3-45
“Specify Upper and Lower Bounds on Natural Frequency” on page 3-47
“Specify Upper Bound on Approximate Settling Time” on page 3-49
“Specify Piecewise-Linear Upper and Lower Bounds on Singular Values” on page
3-51
“Specify Step Response Characteristics” on page 3-13
“Specify Custom Requirements” on page 3-32
1 In the Response Optimization tool, select Gain and Phase Margin in the New list.
A window opens where you specify lower bounds on the gain and phase margin of
your linear system.
2 Specify a requirement name in Name.
3 Specify bounds on the gain margin or phase margin, or both.
3-39
3 Response Optimization
• Gain margin — Amount of gain increase or decrease required to make the loop
gain unity at the frequency where the phase angle is –180°.
• Phase margin — Amount of phase increase or decrease required to make the
phase angle –180° when the loop gain is 1.0
To specify a lower bound on the gain margin or phase margin, or both, select the
corresponding check box and enter the lower bound value.
4 In the Select Systems to Bound section, select the linear systems to which this
requirement applies.
Linear systems are defined by snapshot times at which the model is linearized and
sets of linearization I/O points defining the system inputs and outputs.
a Specify the simulation time at which the model is linearized using the
Snapshot Times box. For multiple simulation snapshot times, specify a vector.
b Select the linearization input/output set from the Linearization I/O area.
If you have already created a linearization input/output set, it will appear in the
list. Select the corresponding check box.
3-40
Specify Frequency-Domain Design Requirements
If you have not created a linearization input/output set, click to open the
Create linearization I/O set dialog box.
For more information on using this dialog box, see “Create Linearization I/O
Sets” on page 3-77.
A variable with the specified requirement name appears in the Data area of the tool.
A graphical display of the requirement also appears in the Response Optimization
tool window.
6 (Optional) In the graphical display, you can:
Alternatively, you can use the Check Gain and Phase Margins block to specify
bounds on the gain and phase margin. (Requires Simulink Control Design.)
1 In the Response Optimization tool, select Bode Magnitude in the New list. A
window opens where you specify the lower or upper bounds on the magnitude of the
system response.
2 Specify a requirement name in the Name box.
3 Specify the requirement type using the Type list.
4 Specify the edge start and end frequencies and corresponding magnitude in the
Frequency and Magnitude columns.
5 Insert or delete bound edges.
3-41
3 Response Optimization
Linear systems are defined by snapshot times at which the model is linearized and
sets of linearization I/O points defining the system inputs and outputs.
a Specify the simulation time at which the model is linearized using the
Snapshot Times box. For multiple simulation snapshot times, specify a vector.
b Select the linearization input/output set from the Linearization I/O area.
If you have already created a linearization input/output set, it will appear in the
list. Select the corresponding check box.
If you have not created a linearization input/output set, click to open the
Create linearization I/O set dialog box.
For more information on using this dialog box, see “Create Linearization I/O
Sets” on page 3-77.
A new variable with the specified name appears in the Data area of the Response
Optimization tool window. A graphical display of the requirement also appears in the
Response Optimization tool window.
3-42
Specify Frequency-Domain Design Requirements
Alternatively, you can use the Check Bode Characteristics block to specify bounds
on the magnitude of the system response. (Requires Simulink Control Design.)
1 In the Response Optimization tool, select Closed-Loop Peak Gain in the New list.
A window opens where you specify an upper bound on the closed-loop peak gain of
the system.
2 Specify a requirement name in the Name box.
3 Specify the upper bound on the closed-loop peak gain in the Closed-Loop peak
gain box.
3-43
3 Response Optimization
4 In the Select Systems to Bound section, select the linear systems to which this
requirement applies.
Linear systems are defined by snapshot times at which the model is linearized and
sets of linearization I/O points defining the system inputs and outputs.
a Specify the simulation time at which the model is linearized using the
Snapshot Times box. For multiple simulation snapshot times, specify a vector.
b Select the linearization input/output set from the Linearization I/O area.
If you have already created a linearization input/output set, it will appear in the
list. Select the corresponding check box.
If you have not created a linearization input/output set, click to open the
Create linearization I/O set dialog box.
For more information on using this dialog box, see “Create Linearization I/O
Sets” on page 3-77.
A new variable with the specified name appears in the Data area of the Response
Optimization tool window. A graphical display of the requirement also appears in the
Response Optimization tool window.
3-44
Specify Frequency-Domain Design Requirements
Alternatively, you can use the Check Nichols Characteristics block to specify
bounds on the magnitude of the system response. (Requires Simulink Control Design.)
1 In the Response Optimization tool, select Damping Ratio in the New list. A
window opens where you specify an upper bound on the damping ratio of the system.
2 Specify a requirement name in the Name box.
3 Specify the lower bound on the damping ratio in the Damping ratio box.
3-45
3 Response Optimization
4 In the Select Systems to Bound section, select the linear systems to which this
requirement applies.
Linear systems are defined by snapshot times at which the model is linearized and
sets of linearization I/O points defining the system inputs and outputs.
a Specify the simulation time at which the model is linearized using the
Snapshot Times box. For multiple simulation snapshot times, specify a vector.
b Select the linearization input/output set from the Linearization I/O area.
If you have already created a linearization input/output set, it will appear in the
list. Select the corresponding check box.
If you have not created a linearization input/output set, click to open the
Create linearization I/O set dialog box.
For more information on using this dialog box, see “Create Linearization I/O
Sets” on page 3-77.
A new variable with the specified name appears in the Data area of the Response
Optimization tool. A graphical display of the requirement also appears in the
Response Optimization tool window.
3-46
Specify Frequency-Domain Design Requirements
Alternatively, you can use the Check Pole-Zero Characteristics block to specify a
bound on the damping ratio. (Requires Simulink Control Design.)
1 In the Response Optimization tool, select Natural Frequency in the New list. A
window opens where you specify a bound on the natural frequency of the system.
2 Specify a requirement name in the Name box.
3-47
3 Response Optimization
3 Specify a lower or upper bound on the natural frequency in the Natural frequency
box.
4 In the Select Systems to Bound section, select the linear systems to which this
requirement applies.
Linear systems are defined by snapshot times at which the model is linearized and
sets of linearization I/O points defining the system inputs and outputs.
a Specify the simulation time at which the model is linearized using the
Snapshot Times box. For multiple simulation snapshot times, specify a vector.
b Select the linearization input/output set from the Linearization I/O area.
If you have already created a linearization input/output set, it will appear in the
list. Select the corresponding check box.
If you have not created a linearization input/output set, click to open the
Create linearization I/O set dialog box.
For more information on using this dialog box, see “Create Linearization I/O
Sets” on page 3-77.
A new variable with the specified name appears in the Data area of the Response
Optimization tool. A graphical display of the requirement also appears in the
Response Optimization tool window.
3-48
Specify Frequency-Domain Design Requirements
Alternatively, you can use the Check Pole-Zero Characteristics block to specify a
bound on the natural frequency. (Requires Simulink Control Design.)
1 In the Response Optimization tool, select Settling Time in the New list. A window
opens where you specify an upper bound on the approximate settling time of the
system.
2 Specify a requirement name in the Name box.
3-49
3 Response Optimization
3 Specify the upper bound on the approximate settling time in the Settling time box.
4 In the Select Systems to Bound section, select the linear systems to which this
requirement applies.
Linear systems are defined by snapshot times at which the model is linearized and
sets of linearization I/O points defining the system inputs and outputs.
a Specify the simulation time at which the model is linearized using the
Snapshot Times box. For multiple simulation snapshot times, specify a vector.
b Select the linearization input/output set from the Linearization I/O area.
If you have already created a linearization input/output set, it will appear in the
list. Select the corresponding check box.
If you have not created a linearization input/output set, click to open the
Create linearization I/O set dialog box.
For more information on using this dialog box, see “Create Linearization I/O
Sets” on page 3-77.
A new variable with the specified name appears in the Data area of the Response
Optimization tool. A graphical display of the requirement also appears in the
Response Optimization tool window.
3-50
Specify Frequency-Domain Design Requirements
Alternatively, you can use the Check Pole-Zero Characteristics block to specify
the approximate settling time. (Requires Simulink Control Design.)
1 In the Response Optimization tool, select Singular Values in the New list. A
window opens where you specify the lower or upper bounds on the singular values of
the system.
2 Specify a requirement name in the Name box.
3-51
3 Response Optimization
Linear systems are defined by snapshot times at which the model is linearized and
sets of linearization I/O points defining the system inputs and outputs.
a Specify the simulation time at which the model is linearized using the
Snapshot Times box. For multiple simulation snapshot times, specify a vector.
b Select the linearization input/output set from the Linearization I/O area.
If you have already created a linearization input/output set, it will appear in the
list. Select the corresponding check box.
If you have not created a linearization input/output set, click to open the
Create linearization I/O set dialog box.
For more information on using this dialog box, see “Create Linearization I/O
Sets” on page 3-77.
A new variable with the specified name appears in the Data area of the Response
Optimization tool. A graphical display of the requirement also appears in the
Response Optimization tool window.
3-52
Specify Frequency-Domain Design Requirements
Alternatively, you can use the Check Singular Value Characteristics block to
specify bounds on the singular value. (Requires Simulink Control Design.)
1 You can apply this requirement to either a signal or a linearization of your model.
3-53
3 Response Optimization
A window opens where you specify the step response requirements on a signal, or
system.
2 Specify a requirement name in the Name box.
3 Specify the step response characteristics:
% Overshoot
% Settling
Final Value
% Rise
Amplitude
% Undershoot
Initial Value
3-54
Specify Frequency-Domain Design Requirements
• Settling time: The time taken until the response signal settles within a specified
region around the final value. This settling region is defined as the final step
value plus or minus the specified percentage of the final value.
• % Settling: The percentage used in the settling time.
• % Overshoot: The amount by which the response signal can exceed the final
value. This amount is specified as a percentage of the step's range. The step's
range is the difference between the final and initial values.
• % Undershoot: The amount by which the response signal can undershoot the
initial value. This amount is specified as a percentage of the step's range. The
step's range is the difference between the final and initial values.
4 Specify the signals or systems to be bound.
In the Select Signals to Bound area, select a logged signal to which you will
apply the requirement.
a
Click . A window opens where you specify the logged signal.
b In the Simulink model window, click the signal to which you want to add a
requirement.
3-55
3 Response Optimization
The window updates and displays the name of the block and the port number
where the selected signal is located.
c
Select the signal and click to add it to the signal set.
d In the Signal set box, enter a name for the selected signal set.
Click OK. A new variable, with the specified name, appears in the Data area
of the Response Optimization tool window.
• Apply this requirement to a linear system.
Linear systems are defined by snapshot times at which the model is linearized
and sets of linearization I/O points defining the system inputs and outputs.
a Specify the simulation time at which the model is linearized using the
Snapshot Times box. For multiple simulation snapshot times, specify a
vector.
b Select the linearization input/output set from the Linearization I/O area.
3-56
Specify Frequency-Domain Design Requirements
For more information on using this dialog box, see “Create Linearization I/O
Sets” on page 3-77.
A variable with the specified requirement name appears in the Data area of the tool.
A graphical display of the requirement also appears in the Response Optimization
tool window.
Alternatively, you can use the Check Step Response Characteristics block to
specify step response bounds for a signal.
See Also
1 In the Response Optimization tool, select Custom Requirement in the New list. A
window opens where you specify the custom requirement.
2 Specify a requirement name in the Name box.
3 Specify the requirement type using the Type list.
4 Specify the name of the function that contains the custom requirement in the
Function box. The field must be specified as a function handle using @. The function
If the function does not exist, clicking opens a template MATLAB file.
Use this file to implement the custom requirement. The default function name is
myCustomRequirement.
5 (Optional) If you want to prevent the solver from considering specific parameter
combinations, select the Error if constraint is violated check box. Use this option
for parameter-only constraints.
During an optimization iteration, the solver evaluates requirements with this option
selected first.
3-57
3 Response Optimization
For more information, see “Skip Model Simulation Based on Parameter Constraint
Violation (GUI)” on page 3-188.
Note: If you select this check box, then do not specify signals or systems to bound. If
you do specify signals or systems, then this check box is ignored.
6 (Optional) Specify the signal or system, or both, to be bound.
You can apply this requirement to model signals, or a linearization of your Simulink
model (requires Simulink Control Design software), or both.
Click Select Signals and Systems to Bound (Optional) to view the signal and
linearization I/O selection area.
In the Signal area, select a logged signal to which you will apply the
requirement.
a
Click . A window opens where you specify the logged signal.
b In the Simulink model window, click the signal to which you want to add a
requirement.
3-58
Specify Frequency-Domain Design Requirements
The window updates and displays the name of the block and the port number
where the selected signal is located.
c
Select the signal and click to add it to the signal set.
d In the Signal set box, enter a name for the selected signal set.
Click OK. A new variable, with the specified name, appears in the Data area
of the Response Optimization tool window.
• Apply this requirement to a linear system.
Linear systems are defined by snapshot times at which the model is linearized
and sets of linearization I/O points defining the system inputs and outputs.
a Specify the simulation time at which the model is linearized using the
Snapshot Times box. For multiple simulation snapshot times, specify a
vector.
b Select the linearization input/output set from the Linearization I/O area.
3-59
3 Response Optimization
A new variable, with the specified name, appears in the Data area of the Response
Optimization tool. A graphical display of the requirement also appears in the
Response Optimization tool window.
See Also
3-60
Specify Design Variables
Before running the optimization, you must specify the model parameters to optimize.
These parameters form the design variables set for optimization. By tuning these
parameters, Simulink Design Optimization software attempts to make the signals meet
the requirements.
Simulink Design Optimization software optimizes the response signals of the model
by varying the tuned parameters so that the response signals lie within the constraint
bound segments or closely match a specified reference signal. The design variables can be
scalar, vector, matrix, or an expression that evaluates to one of these values.
In this section...
“Add Model Parameters as Variables for Optimization” on page 3-61
“Specify Design Variables” on page 3-64
In this figure, the Proportional (P) and Integral (I) gain parameters of a PID
Controller block are specified as numerical values.
3-61
3 Response Optimization
• Add the variables to the model workspace, and specify initial values.
3-62
Specify Design Variables
• Write initialization code in the PreloadFcn callback of the model. For more
information, see “Model Callbacks”.
Kp = 1;
Ki = 1;
2 Specify the gain parameters as the variables Kp and Ki in the PID Controller block
dialog box.
3-63
3 Response Optimization
You can now select Kp and Ki for optimization. See, “Specify Design Variables” on page
3-64.
You can also specify independent parameters that do not appear explicitly in the model
as variables for optimization. However, you cannot use this workflow with Simulink fast
restart.
Suppose that a model parameter Kint is related to independent parameters x and y such
that Kint = x+y. To optimize x and y instead of Kint:
• Create the independent variables x and y by adding them to the model workspace and
specifying initial values. This ensures that the variables are used by the model.
• Write code in the InitFcn callback of the model that defines the relationship between
Kint, x, and y. You must first use the get_param function to get the variables x and
y from the model workspace before you can use them to define Kint.
wks = get_param(gcs,'ModelWorkspace')
x = evalin(wks,'x')
y = evalin(wks,'y')
Kint = x+y;
You can now select x and y for optimization. Do not optmize the independent and
dependent parameters simultaneously. Doing so can lead to incorrect results. For
example, do not optimize Kint, x and y together.
A window opens where you specify design variables. All parameters in use by the
model are displayed in this window.
2 Select one or more parameter names and click
3-64
Specify Design Variables
Note: You can add the same parameter to multiple design variable sets.
3 (Optional) Specify design variable settings.
Expand Variable Detail to see the block in the model that contains this parameter.
4 Click OK to create a design variable set.
Related Examples
• “Optimize Parameters for Robustness (GUI)” on page 3-206
• “Update Model with Design Variables Set” on page 3-66
• “Export Design Variable Values for Specific Iteration” on page 3-91
3-65
3 Response Optimization
Open the Simulink model and load the pre-configured Response Optimization tool
session.
load('pidtune_demo_sdosession_update_dv.mat')
sdotool(SDOSessionData)
The Response Optimization tool opens and loads the preconfigured session. In the Data
area, DesignVars1 is a set of tuned design variables.
In the Design Variables Set list, select the design variable set, DesignVars1.
3-66
Update Model with Design Variables Set
Related Examples
• “Export Design Variable Values for Specific Iteration” on page 3-91
3-67
3 Response Optimization
General Options
In this section...
“Accessing General Options” on page 3-68
“Progress Options” on page 3-68
“Result Options” on page 3-69
Progress Options
You can specify options related to optimization progress using the options in the
Progress Options area.
3-68
General Options
Updates model response and design variable plots at each optimization iteration.
Result Options
You can specify options for optimization results in the Result Options area.
Updates optimized parameter values in the Simulink model after the optimization
terminates.
• Save optimization termination information
3-69
3 Response Optimization
The value is a mx1 vector. Positive values indicate that the constraint has not been
satisfied. Check exitflag to confirm that the optimization succeeded.
• Ceq — Optimized nonlinear equality constraint violations.
The value is a double rx1 vector. Any nonzero values indicate that the constraint
has not been satisfied. Check exitflag to confirm that the optimization
succeeded.
• Gradients — Cost and constraint gradients at the optimized parameter values.
See “How the Optimization Algorithm Formulates Minimization Problems” on
page 3-3 on how the solver computes gradients.
3-70
General Options
Overwrites the optimized model parameter values in the design variable set
variable used in the optimization. You can see the updated values in the Value
field.
Creates a new variable in the Data area of the tool that contains the optimized
parameter values. To update the model with the optimized parameter values,
select the variable in the Design Variables Set list. Open the Edit dialog box
3-71
3 Response Optimization
Optimization Options
In this section...
“Accessing Optimization Options” on page 3-72
“Selecting Optimization Methods” on page 3-73
“Selecting Optimization Termination Options” on page 3-74
“Selecting Additional Optimization Options” on page 3-75
To set optimization options, click Options in the Response Optimization tool. A window
opens. Select the Optimization Options tab.
3-72
Optimization Options
For more information on the problem formulations for each optimization method, see
“How the Optimization Algorithm Formulates Minimization Problems” on page 3-3.
3-73
3 Response Optimization
Note: If selected, the software ignores this option when tracking a reference signal.
By varying these parameters you can force the optimization to continue searching for a
solution or to continue searching for a more accurate solution.
3-74
Optimization Options
Display Level
The Display level option specifies the form of the output that appears in the
Optimization Progress window. The options are:
For more information on the type of iterative output that appears for the method you
selected in Method, see the discussion of output for the corresponding function.
3-75
3 Response Optimization
Restarts
In some optimizations, the Hessian may become ill-conditioned and the optimization does
not converge. In these cases, it is sometimes useful to restart the optimization after it
stops, using the endpoint of the previous optimization as the starting point for the next
one. To automatically restart the optimization, indicate the number of times you want to
restart in this field.
3-76
Create Linearization I/O Sets
You create a linearization input/output set using the Create Linearization I/O Set dialog
box. This dialog box may be accessed in two ways:
• In the Response Optimization tool, select Linearization I/Os in the New drop-down
list.
•
In a requirement dialog box, in the Select Systems to Bound area, click .
1 In your Simulink model, select one or more signals that you want to define as a
linearization input or output point.
The selected signals appear in the Create linearization I/O set dialog box under
Currently selected signals.
2 In the Create linearization I/O set dialog box, click a signal name under Currently
selected signals.
3-77
3 Response Optimization
4 Select the linearization point type for a signal from the Configuration drop-down
list for that signal. For example:
• If you want the selected signal to be a linearization output point, select Output
Measurement.
• If you want the signal to be an open-loop output point, select Open-loop
Output.
5 Repeat steps 1–4 for any other signals you want to define as linearization I/O points.
Tip To highlight in the Simulink model the location of any signal in the current list
of analysis I/O points, select the I/O point in the list and click Highlight.
6 After you define all the signals for the I/O set, enter a name for the I/O set in the
Variable name field located at the top-left of the window.
7 Click OK.
3-78
Linearization Options
Linearization Options
In this section...
“Accessing Linearization Options” on page 3-79
“Configuring Linearization Options” on page 3-79
To set linearization options, click Options in the Response Optimization tool. A window
opens. Select the Linearization Options tab.
Simulink Control Design lets you choose whether to linearize models using exact
representation or Pade approximation of continuous time delays. How you treat time
delays during linearization depends on your nonlinear model.
3-79
3 Response Optimization
By default, linearization uses Pade approximation for representing time delays in your
linear model.
• Applying more advanced control design techniques to your linear plant, such as LQR
or H-infinity control design.
• Minimizing the time to compute a linear model.
The software treats discrete-time delays as internal delays in the linearized model.
Such delays do not appear as additional states in the linearized model.
To specify whether the linearization should approximate delays or use them exactly, set
the Use exact delays check box appropriately.
To specify the sampling time of the linearized model, use the Linear system sample
time box. By default, the software chooses the slowest applicable sampling time. Use 0 to
specify a continuous-time linear model.
When you linearize models with multiple sample times, such as a discrete controller with
a continuous plant, a rate conversion algorithm generates a single-rate linear model. The
rate conversion algorithm affects linearization results.
3-80
Linearization Options
3-81
3 Response Optimization
Right-click the white space in a plot and select Axes Properties to open the Property
Editor dialog box.
This figure shows the Property Editor dialog box for a step response.
3-82
Plots in the Response Optimization Tool
To specify new text for plot titles and axis labels, type the new string in the field next
to the label you want to change. The label changes immediately as you type, so you
can see how the new text looks as you are typing.
• Limits — Numerical ranges of the x- and y- axes
Default values for the axes limits make sure that the maximum and minimum x and y
values are displayed. If you want to override the default settings, change the values in
the Limits pane fields. The Auto-Scale check box automatically clears if you click a
different field. The new limits appear immediately in the response plot.
To reestablish the default values, select the Auto-Scale check box again.
• Units — Units where applicable (e.g., rad/s to Hertz). If you cannot customize units,
the Property Editor displays that no units are available for the selected plot.
• Style — Show a grid, adjust font properties, such as font size, bold and italics, and
change the axes foreground color
• Options — Change options where applicable. These include peak response, settling
time, phase and gain margins, etc. Plot options change with each plot response
type. The Property Editor displays only the options that make sense for the selected
response plot. For example, phase and gain margins are not available for step
responses.
3-83
3 Response Optimization
Plot Types
• “Response Plots” on page 3-84
• “Spider Plots” on page 3-85
• “Iteration Plots” on page 3-86
Response Plots
You can view model signals and the requirements applied to the signal using a response
plot. You can also plot the frequency response of a system (requires Simulink Control
Design).
The response plot shows the system response as it varies during optimization. You can
also view the uncertain system responses in the plot.
3-84
Plots in the Response Optimization Tool
Tip To select the responses and systems displayed in a given plot, right-click on the plot
and use the Systems and Responses menu.
Spider Plots
You can compare the values of design variable sets or evaluated requirements using a
spider plot.
Spider plots depict multivariate data using an axis for each variable. The various axes
are arranged clockwise and have a common intersecting point, as this example shows:
Tip To view only some of the requirement values in a given plot, right-click on the plot
and select the requirements in the Show list.
3-85
3 Response Optimization
For information on using a spider plot to compare design variables sets or evaluated
requirements, see “Compare Requirements and Design Variables Using Spider Plot” on
page 3-88
Iteration Plots
You can plot the values of design variables and requirements as they vary during
optimization using an iteration plot.
Iteration plots depict the value of the plot variable(s) for each iteration. The x-axis
represents the iteration number, as this example shows:
You can export the values of a plotted variable for a given iteration. For more
information, see “Export Design Variables and Requirement Values for an Iteration” on
page 3-87.
Tip To view scaled values of the plotted variable(s), right-click on the plot and select
Show scaled values.
3-86
Plots in the Response Optimization Tool
Click OK. The exported data variable appears in the Data area.
Note: The iteration number is added as a suffix to the exported data variable name.
3-87
3 Response Optimization
Open the Simulink model and load the pre-configured Response Optimization Tool session.
For this example, which uses a distillation column model, the step response requirements
are preconfigured and loaded in the model workspace.
Click the Response Optimization tab. In the Open Session drop-down list, select
Open from model workspace. A window opens where you select the Response
Optimization Tool session to load. Select distillation_optim and click OK.
When optimizing the model response, you create a set of requirements that it must
satisfy. If the requirements are violated, meaning that they evaluate to nonnegative
values, the design variables must be optimized. After the optimization, you can compare
the original requirement value with the requirement evaluated using the optimized
design variable values.
3-88
Compare Requirements and Design Variables Using Spider Plot
The plot has an axis for each edge-and-signal combination defined in the
distillation_demo/Desired Step Response check block. Points on each axis
represent the violation for that signal-edge combination and the plot connects these
points to form a closed polygon representing the initial design. Note that some points
are negative, representing satisfied constraints, and some positive, representing violated
constraints.
Click Optimize.
A new variable, ReqValues1, containing the evaluation of the requirements using the
optimized design variables appears in the Data area.
3-89
3 Response Optimization
The optimized requirement values, ReqValues1, are all negative or zero, indicating that
all the constraints are satisfied.
More About
• “Export Design Variable Values for Specific Iteration” on page 3-91
3-90
Export Design Variable Values for Specific Iteration
During optimization, the optimization solver simulates the model using a different set of
design variables at each iteration. After the optimization completes, you can export the
values for an iteration from the iteration plot of the design variable set.
For this example, load a preconfigured Response Optimization tool session. Optimize the
model, and export the design variable set values for the third iteration.
Open the Simulink model and load the preconfigured Response Optimization tool session.
load('distillation_demo_sdosession_export_iter_dv.mat')
sdotool(SDOSessionData)
The Response Optimization tool opens and loads the preconfigured session. Iteration
Plot 1 is configured to plot the values of DesignVars for each optimization iteration.
Click Optimize.
3-91
3 Response Optimization
Export the design variable values set to the Data area of the tool.
Click OK. The exported data variable, DesignVars_iter_3, appears in the Data.
Note: You will see the iteration number suffixed to the exported data variable name.
Related Examples
• “Update Model with Design Variables Set” on page 3-66
• “Compare Requirements and Design Variables Using Spider Plot” on page 3-88
More About
• “Iteration Plots” on page 3-86
3-92
Design Optimization to Meet Time- and Frequency-Domain Requirements (GUI)
sys = 'sdoAircraft';
open_system(sys);
3-93
3 Response Optimization
The aircraft model is based on the Simulink slexAircraftExample model. The model
includes:
• A step change applied to the aircraft joystick at 1 second into the simulation that
causes the aircraft to pitch upward.
You tune the controller gains to meet the following time- and frequency-domain design
requirements:
• Angle-of-attack alpha response to a step change in the joystick has a rise time of less
than 1 second, less than 1% overshoot, and settles to within 1% of steady state within
less than 5 seconds
• Pitch-rate control loop has good tracking below 1 rad/s and 20 dB noise rejection
above 100 rad/s
• Closed loop response from joystick to pilot G-Force is below 0 dB above 5 rad/s.
These requirements reduce the high frequency G-forces experienced by the pilot in
response to joystick changes while still maintaining flight performance.
The model includes the following blocks (from Simulink® Design Optimization™ and
Simulink Control Design Model Verification libraries):
3-94
Design Optimization to Meet Time- and Frequency-Domain Requirements (GUI)
The linearization inputs/outputs are already selected in the Linearizations tab. The
pitch-rate loop starts from the input of the controller (the controller error signal) and
ends at the output of the pitch-rate sensor. The angle-of-attack loop is opened signal so
that the block only computes the pitch-rate loop response. The linear system is computed
at a simulation time of 0.
3-95
3 Response Optimization
3-96
Design Optimization to Meet Time- and Frequency-Domain Requirements (GUI)
The Bounds tab specifies the following pitch-rate loop shape requirements:
• Less than -20 dB over the range 100 rad/s to 1000 rad/s
3-97
3 Response Optimization
The linearization inputs/outputs are already selected in the Linearizations tab. The
linear system is computed at a simulation time of 0.
3-98
Design Optimization to Meet Time- and Frequency-Domain Requirements (GUI)
3-99
3 Response Optimization
The Bounds tab specifies the G-force requirements of less than 0 dB over the range 5
rad/s 100 rad/s.
3-100
Design Optimization to Meet Time- and Frequency-Domain Requirements (GUI)
Open the Response Optimization tool to configure and run design optimization problems
interactively. Click Response Optimization on the Block Parameters dialog of Alpha
Response, Pitch Rate Loop or Pilot G Response block. Alternatively, type
sdotool('sdoAircraft'). To show multiple requirement plots at the same time, use
the View tab in the tool.
The tool detects the requirements specified in the Model Verification blocks and
automatically includes them as requirements to satisfy.
3-101
3 Response Optimization
In the Design Variables Set drop-down list, select New. A dialog to select model
parameters for optimization opens.
Select Ki, Kf, Kq and Ka. Click << to add the selected parameters to the design variables
set.
Specify minimum and maximum gain values, the Ki and Kf values must remain negative
while Ka and Kq must remain positive.
Click OK. A new variable DesignVars appears in the Response Optimization Tool
Workspace.
3-102
Design Optimization to Meet Time- and Frequency-Domain Requirements (GUI)
Click Plot Model Response to simulate the model and check how well the initial design
satisfies the design requirements.
The plots indicate that the current design does not satisfy the pilot G-force requirement
and the alpha step response overshoot requirement is violated.
Create a plot to display how the controller variables are modified during the
optimization. In the Data To Plot drop-down list, select DesignVars, which contains
3-103
3 Response Optimization
the optimization design variables Ki, Kf, Kq and Ka. In the Add Plot drop-down list,
select Iteration plot.
Click Optimize.
3-104
Design Optimization to Meet Time- and Frequency-Domain Requirements (GUI)
3-105
3 Response Optimization
To load a pre-configured file and run the optimization, click Open in the Response
Optimization tab and select sdoAircraft_sdosession.mat. Alternatively load the
project by typing:
>> sdotool(SDOSessionData)
The optimization progress window updates at each iteration and shows that the
optimization converged after 5 iterations.
The Alpha Response and Pilot G Response plots indicate that the design
requirements are satisfied. The DesignVars plot shows that the controller gains
converged to new values.
3-106
Design Optimization to Meet Time- and Frequency-Domain Requirements (GUI)
To view the optimized design variable values, click DesignVars in the Response
Optimization Tool Workspace. The optimized values of the design variables are
automatically updated in the Simulink model.
% Close the model
bdclose('sdoAircraft')
3-107
3 Response Optimization
The hydraulic cylinder model is based on the Simulink model sldemo_hydcyl. The
model includes:
• A step change applied to the cylinder control valve orifice area that causes the
cylinder piston position to change.
You tune the cylinder cross-sectional area and piston spring constant to meet the
following design requirements:
• Ensure that the piston position has a step response rise time of less than 0.04 seconds
and setting time of less than 0.05 seconds.
Open the Response Optimization tool to configure and run design optimization problems
interactively.
sdotool('sdoHydraulicCylinder')
3-108
Design Optimization to Meet a Custom Objective (GUI)
3-109
3 Response Optimization
In the Design Variables Set drop-down list, select New. A dialog to select model
parameters for optimization opens.
3-110
Design Optimization to Meet a Custom Objective (GUI)
Select Ac and K. Click <- to add the selected parameters to the design variables set.
Limit the cylinder cross-sectional area to circular area with radius between 1 and 2
centimeters and the piston spring constant to a range of 1e4 to 10e4 N/m. To do so,
specify the maximum and minimum for the corresponding variable in the Maximum and
Minimum columns.
Because the variable values are different orders of magnitude, scale Ac by 1e-3 and K by
1e5.
Click OK. A new variable DesignVars appears in the Response Optimization Tool
Workspace.
3-111
3 Response Optimization
The design requirements require logged model signals. During optimization, the model is
simulated using the current value of the design variables and the logged signal is used to
evaluate the design requirements.
Log the cylinder pressures, which is the first output port of the Cylinder Assembly
block.
In the New drop-down list, select Signal. A dialog to select model signals to log opens.
3-112
Design Optimization to Meet a Custom Objective (GUI)
Enter Pressures as the signal name in the Signal set field. Then, in the Simulink
model, click the first output port of the Cylinder Assembly block named Pressure.
The dialog updates to display the selected signal.
Select the signal in the dialog and click -> to add it to the signal set.
Click OK. A new variable Pressures appears in the Response Optimization Tool
Workspace.
Similarly, log the piston position, which is the second output of the Cylinder Assembly
block, in a variable named PistonPosition.
3-113
3 Response Optimization
Specify the maximum cylinder pressure requirement of less than 1.75e6 N/m.
In the New drop-down list, select Signal Bound. A dialog to create a signal bound
requirement opens.
3-114
Design Optimization to Meet a Custom Objective (GUI)
Designate the Requirement Name as MaxPressure. In both the start and end
Amplitude columns, enter the maximum pressure requirement of 1.75e6 N/m, and set
the Edge End Time to 0.1 s. In the Select Signals to Bound area, select Pressures,
the signal on which this requirement applies.
3-115
3 Response Optimization
Click OK.
3-116
Design Optimization to Meet a Custom Objective (GUI)
Specify the piston position step response requirement of rise time of less than 0.04
seconds and a settling time of less than 0.05 seconds.
In the New drop-down list of the Response Optimization tab, select Step Response
Envelope. A dialog to create a step response requirement opens.
Specify a requirement named PistonResponse, and the required rise and settling time
bounds. Select PistonPosition as the signal to apply the step response requirement to.
3-117
3 Response Optimization
Click OK.
In the New drop-down list, select Custom Requirement. A dialog to create custom
requirement opens.
3-118
Design Optimization to Meet a Custom Objective (GUI)
3-119
3 Response Optimization
type sdoHydraulicCylinder_customObjective
3-120
Design Optimization to Meet a Custom Objective (GUI)
Click Plot Model Response to simulate the model and check how well the initial design
satisfies the design requirements. To show both requirement plots at the same time, use
the plot layout widgets in the View tab.
3-121
3 Response Optimization
From the plots, see that the maximum pressure requirement is satisfied but the piston
position step response requirement is not satisfied.
Create a plot to display how the cylinder cross-sectional area and piston spring constant
are modified during optimization.
In the Data to Plot drop-down list, select DesignVars, which contains the optimization
design variables Ac and K. In the Add Plot drop-down, create a new iteration plot to
show the design variable trajectories. For this new plot, click Show scaled values in the
Iteration Plot tab, to facilitate viewing the two trajectories on the same axes.
3-122
Design Optimization to Meet a Custom Objective (GUI)
3-123
3 Response Optimization
The optimization progress window updates at each iteration and shows that the
optimization converged after 4 iterations.
The Pressures and PistonPosition plots indicate that the design requirements
are satisfied. The MinimizeAC plot shows that the cylinder cross-sectional area Ac is
minimized.
To view the optimized design variable values, click the variable name in the Response
Optimization Tool Workspace. The optimized values of the design variables are
automatically updated in the Simulink model.
3-124
Design Optimization to Meet a Custom Objective (GUI)
Related Examples
To learn how to optimize the cylinder design using the sdo.optimize command, see
"Design Optimization to Meet Custom Objective (Code)".
% Close the model
delete(sdotool('sdoHydraulicCylinder'))
bdclose('sdoHydraulicCylinder')
3-125
3 Response Optimization
sys = 'sdoHydraulicCylinder';
open_system(sys);
The hydraulic cylinder model is based on the Simulink model sldemo_hydcyl. The
model includes:
• A step change applied to the cylinder control valve orifice area that causes the
cylinder piston position to change.
3-126
Design Optimization to Meet a Custom Objective (Code)
You tune the cylinder cross-sectional area and piston spring constant to meet the
following design requirements:
• Ensure that the piston position has a step response rise time of less than 0.04 seconds
and setting time of less than 0.05 seconds.
Ac = sdo.getParameterFromModel('sdoHydraulicCylinder','Ac');
K = sdo.getParameterFromModel('sdoHydraulicCylinder','K');
Limit the cylinder cross-sectional area to a circular area with radius between 1 and 2
centimeters.
The design requirements require logged model signals. During optimization, the model is
simulated using the current value of the design variables and the logged signal is used to
evaluate the design requirements.
• Cylinder pressures, available at the first output port of the Cylinder Assembly
block
3-127
3 Response Optimization
Pressures = Simulink.SimulationData.SignalLoggingInfo;
Pressures.BlockPath = 'sdoHydraulicCylinder/Cylinder Assembly';
Pressures.OutputPortIndex = 1;
• Piston position, available at the second output port of the Cylinder Assembly block
PistonPosition = Simulink.SimulationData.SignalLoggingInfo;
PistonPosition.BlockPath = 'sdoHydraulicCylinder/Cylinder Assembly';
PistonPosition.OutputPortIndex = 2;
Create an object to store the logging information and use later to simulate the model
simulator = sdo.SimulationTest('sdoHydraulicCylinder');
simulator.LoggingInfo.Signals = [PistonPosition,Pressures];
Specify the piston position step response requirement of rise time of less than 0.04
seconds and settling time less than of 0.05 seconds.
PistonResponse = sdo.requirements.StepResponseEnvelope;
set(PistonResponse, ...
'RiseTime', 0.04, ...
'FinalValue', 0.04, ...
'SettlingTime', 0.05, ...
'PercentSettling', 1);
Specify the maximum cylinder pressure requirement of less than 1.75e6 N/m.
MaxPressure = sdo.requirements.SignalBound;
set(MaxPressure, ...
'BoundTimes', [0 0.1], ...
'BoundMagnitudes', [1.75e6 1.75e6], ...
'Type', '<=');
For convenience, collect the performance requirements into a single structure to use
later.
requirements = struct(...
'PistonResponse', PistonResponse, ...
'MaxPressure', MaxPressure);
To optimize the cylinder cross-sectional area and piston spring constant, create a
function to evaluate the cylinder design. This function is called at each optimization
iteration.
3-128
Design Optimization to Meet a Custom Objective (Code)
Here, use an anonymous function with one argument that calls the
sdoHydraulicCylinder_design function.
evalDesign = @(p) sdoHydraulicCylinder_design(p,simulator,requirements);
The function:
• Has one input argument that specifies the cylinder cross-sectional area and piston
spring constant values.
• Returns the optimization objective value and optimization constraint violation values.
3-129
3 Response Optimization
Call the objective function with the initial cylinder cross-sectional area and initial piston
spring constant.
initDesign = evalDesign([Ac;K]);
3-130
Design Optimization to Meet a Custom Objective (Code)
The function simulates the model and evaluates the design requirements. The scope
shows that the maximum pressure requirement is satisfied but the piston position step
response requirement is not satisfied.
• Cleq shows that some of the inequality constraints are positive indicating they are
not satisfied by the initial design.
initDesign.Cleq
ans =
-0.3839
-0.1861
-0.1836
-1.0000
0.3033
0.2909
0.1671
0.2326
-0.0480
-0.0480
• F shows the optimization objective value (in this case the cylinder cross-sectional
area). The initial design cross-sectional area, as expected, has the same value as the
initial cross-sectional area parameter Ac.
initDesign.F
ans =
1.0000e-03
Pass the objective function, initial cross-sectional area and piston spring constant values
to sdo.optimize.
[pOpt,optInfo] = sdo.optimize(evalDesign,[Ac;K]);
3-131
3 Response Optimization
The optimization repeatedly evaluates the cylinder design by adjusting the cross-
sectional area and piston spring constant to meet the design requirements. From the
scope, see that the maximum pressure and piston response requirements are met.
• pOpt shows the optimized cross-sectional area and piston spring constant values.
pOpt
pOpt(1,1) =
Name: 'Ac'
Value: 3.7855e-04
Minimum: 3.1416e-04
Maximum: 0.0013
Free: 1
Scale: 0.0020
Info: [1x1 struct]
pOpt(2,1) =
Name: 'K'
Value: 1.5816e+04
Minimum: 10000
Maximum: 100000
3-132
Design Optimization to Meet a Custom Objective (Code)
Free: 1
Scale: 65536
Info: [1x1 struct]
2x1 param.Continuous
optInfo =
For example, the Cleq field shows the optimized non-linear inequality constraints are all
non-positive to with-in optimization tolerances, indicating that the maximum pressure
and piston response requirements are satisfied.
optInfo.Cleq
ans =
-0.0968
-0.0126
-0.0126
-1.0000
-0.2067
-0.0052
-0.0074
-0.0004
-0.0476
-0.0476
3-133
3 Response Optimization
The F field contains the optimized cross-sectional area. The optimized cross-sectional
area value is nearly 50% less that the initial value.
optInfo.F
ans =
3.7855e-04
By default, the model variables Ac and K are not updated at the end of optimization. Use
the setValueInModel command to update the model variable values.
sdo.setValueInModel('sdoHydraulicCylinder',pOpt)
Related Examples
To learn how to optimize the cylinder design using the Response Optimization tool, see
"Design Optimization to Meet Custom Objective (GUI)".
% Close the model
bdclose('sdoHydraulicCylinder')
3-134
Design Optimization to Meet Custom Signal Requirements (GUI)
load sldo_model1_custom_signal_session
sdotool(SDOSessionData);
The Response Optimization tool, configured with the following settings, also opens:
• Step response characteristics, specified on the output of the Plant block, that the
model output must satisfy:
• Maximum overshoot of 5%
• Maximum rise time of 10 seconds
• Maximum settling time of 30 seconds
• Design variable set with the controller parameters Kp, Ki and Kd. These
parameters have a minimum value of 0.
• The variables for step requirements (PlantResponse), logged signal
(PlantOutput) and design variables (DesignVars) which appear in the Data
area.
3-135
3 Response Optimization
2 Specify a signal to log. You apply the custom requirement on this logged signal.
3-136
Design Optimization to Meet Custom Signal Requirements (GUI)
• An input argument data which is a structure with fields for the design variables
in the Data area. Signals are logged for the nominal and uncertain parameter
values if there are any.
• Returns the objective value to be minimized.
3-137
3 Response Optimization
4 In the Select Signals and Systems to Bound area, select the PlantActuator
check box to associate the custom requirement with that signal.
Click OK. A new variable appears in the Data area of the tool. The window also
updates to graphically display the custom signal requirement.
5 Click Optimize.
3-138
Design Optimization to Meet Custom Signal Requirements (GUI)
After a few iterations, the optimization converges to meet both the custom signal and
step response requirements.
setOption(sdotool('sldo_model1'),'NoPromptClose',true)
bdclose('sldo_model1')
3-139
3 Response Optimization
Related Examples
• “Design Optimization Using Frequency-Domain Check Blocks (GUI)”
3-140
Design Optimization to Meet Frequency-Domain Requirements (GUI)
Suspension Model
Mass-spring-damper models represent simple suspension systems and for this example
we tune the system to meet typical suspension requirements. The model implements
3-141
3 Response Optimization
the second order system representing a mass-spring-damper using Simulink blocks and
includes:
• a Mass gain block parameterized by the total suspended mass, m0+mLoad. The total
mass is the sum of a nominal mass,|m0|, and a variable load mass, mLoad.
Simulate the model to view the system response to the applied disturbance force.
3-142
Design Optimization to Meet Frequency-Domain Requirements (GUI)
Design Problem
The initial system has a bandwidth that is too high. This can be seen from the
spiky position signal. You tune the spring and damper values to meet the following
requirements:
• The damping ratio of the system must be less than 1/sqrt(2). This ensures that no
frequencies in pass band are amplified by the system.
• Minimize the expected failure rate of the system. The expected failure rate is
described by a Weibull distribution dependent on the mass, spring, and damper
values.
• These requirements must all be satisfied as the load mass ranges from 0 to 20.
In the Design Variables Set list, select New. Add the b and k model variables to the
design variable set.
• Specify the Minimum and Maximum values for the b variable as 100 and 10000
respectively.
• Specify the Minimum and Maximum values for the k variable as 10000 and 100000
respectively.
3-143
3 Response Optimization
Click OK. A new variable, DesignVars, appears in the Response Optimization Tool
Workspace.
In the Uncertain Variables Set list, select New. Add the mLoad variable to the
uncertain variables set.
• Specify the Uncertain Values value for the mLoad variable as [10 15 20]
Click OK. A new variable, UncVars, appears in the Response Optimization Tool
Workspace.
Specify the input/output points defining the linear system used to compute the
bandwidth and damping ratio.
• In the Simulink model, click the signal at the output of the Band-Limited
Disturbance Force block. The Create linearization I/O set dialog box is updated
and the chosen signal appears in it.
• In the Create linearization I/O dialog box, select the signal and click Add.
• In the Configuration list for the selected signal, choose Input Perturbation to
specify it as an input signal.
3-144
Design Optimization to Meet Frequency-Domain Requirements (GUI)
• Similarly, add the pos signal from the Simulink model. Specify this signal as an
output. In the Configuration list, select Output Measurement.
3-145
3 Response Optimization
• Click OK. A new variable, IOs, appears in the Response Optimization Tool
Workspace.
Tune the spring and damper values to satisfy bandwidth and damping ratio
requirements.
• Open a dialog to specify bounds on the Bode magnitude. In the New list, select Bode
Magnitude.
• Specify the edge start frequency and magnitude as 10 rad/s and -3db, respectively.
• Specify the edge end frequency and magnitude as 100 rad/s and -3db, respectively.
• Specify the input/output set to which the requirement applies by clicking Select
Systems to Bound. Select the IOs check box .
3-146
Design Optimization to Meet Frequency-Domain Requirements (GUI)
3-147
3 Response Optimization
• Open a dialog to specify bounds on the damping ratio. In the New list, select
Damping Ratio.
• Specify the input/output set to which the requirement applies by clicking Select
Systems to Bound. Select the IOs check box .
3-148
Design Optimization to Meet Frequency-Domain Requirements (GUI)
Tune the spring and damper values to minimize the expected failure rate over a lifetime
of 100e3 miles. The failure rate is computed using a Weibull distribution on the damping
ratio of the system. As the damping ratio increases the failure rate is expected to
increase.
• Open a dialog box to specify the custom requirements. In the New list, select Custom
Requirement.
• In the Specify Function area, select Minimize the function output from the
Type list.
3-149
3 Response Optimization
type sdoSuspension_FailureRate
3-150
Design Optimization to Meet Frequency-Domain Requirements (GUI)
Before running the optimization be sure to have completed the earlier steps.
Alternatively, you can load the sdoSimpleSuspension_sdosession from the model
workspace into the Response Optimization tool.
To save the initial design variable values and later compare them with the optimized
values configure the optimization.
• Click Options.
• Select the Save optimized variable values as new design variable set
option.
To evaluate the requirements at the initial design point, click Evaluate Requirements
. The requirement plots are updated and a ReqValues variable is added to the
Response Optimization Tool Workspace.
3-151
3 Response Optimization
To optimize the design, click Optimize. The plots are updated during optimization.
At the end of optimization, the optimal design values are written to the DesignVars1
variable. The requirement values for the optimized design are written to the
ReqValues1 variable.
3-152
Design Optimization to Meet Frequency-Domain Requirements (GUI)
3-153
3 Response Optimization
• To add the optimized design variables to the same plot, select DesignVars1 in
the Response Optimization Tool Workspace and drag it onto the Spider plot.
Alternatively, in the Data to Plot list, select DesignVars1. Then, in the Add Plot
list, select Spider plot 1 from the Add to Existing Plot section.
3-154
Design Optimization to Meet Frequency-Domain Requirements (GUI)
The plot shows that the optimizer reduced both the k and b values for the optimal design.
3-155
3 Response Optimization
• To add the optimized requirement values to the same plot, select ReqValues1 in
the Response Optimization Tool Workspace and drag it onto the Spider plot.
Alternatively, in the Data to Plot list, select ReqValues1. Then, in the Add Plot
list, select Spider plot 2 from the Add to Existing Plot section.
3-156
Design Optimization to Meet Frequency-Domain Requirements (GUI)
3-157
3 Response Optimization
The plot shows that the optimal design has a lower failure rate (the MinFailureRate axis)
and better satisfies the bandwidth requirement. The value plotted on the bandwidth
axis is the difference between the bandwidth bound and the bandwidth value. The
optimization satisfies the bound by keeping this value negative; a more negative value
indicates better satisfaction of the bound.
The improved reliability and bandwidth are achieved by pushing the damping ratio
closer to the damping ratio bound. The plot has two axes for the damping ratio
requirement, one for each system pole, and the plotted values are the difference between
the damping ratio bound and the damping ratio value. The optimization satisfies the
bound by keeping this value negative.
Finally the simulated mass position is smoother than the initial position response
(indication of a lower bandwidth as required) at the expense of larger position deflection.
Related Examples
To learn how to optimize the suspension design using the sdo.optimize command, see
"Design Optimization to Meet Frequency-Domain Requirements (Code)".
3-158
Design Optimization to Meet Frequency-Domain Requirements (GUI)
3-159
3 Response Optimization
The Simulink model sdoPopulation models a simple two-organism ecology using the
competitive Lotka-Volterra equations:
• is the proximity of the two populations and how strongly they affect each other.
open_system('sdoPopulation')
3-160
Specify Custom Signal Objective with Uncertain Variable (GUI)
3-161
3 Response Optimization
3-162
Specify Custom Signal Objective with Uncertain Variable (GUI)
The two-dimensional signal, P, models the population sizes for P1 (first element) and P2
(second element). The model is initially configured with one organism, P1, dominating
the ecology. The Population scope shows the P1 population oscillating between high
and low values, while P2 is constant at 0.1. The Population Phase Portrait block
shows the population sizes of the two organisms in relation to each other.
• Minimize the population range, that is, the maximum difference between P1 and P2.
• Stabilize P1 and P2, that is, ensure that neither organism population dies off or grows
extremely large.
You must tune the parameters for different values of the carrying capacity, . This
ensures robustness to environment carrying-capacity uncertainty.
Double-click the Open Optimization Tool block in the model to open a pre configured
Response Optimization tool session. The session specifies the following variables:
3-163
3 Response Optimization
Specify a custom requirement to minimize the maximum difference between the two
population sizes. Apply this requirement to the P1 and P2 model signals.
1 Open the Create Requirement dialog box. In the New list, select Custom
Requirement.
2 Specify the following in the Create Requirement dialog box:
3-164
Specify Custom Signal Objective with Uncertain Variable (GUI)
3-165
3 Response Optimization
3. Click OK.
Input/Output
• Nominal - Logged signal data, obtained by simulating the model using parameter
values specified by data.DesignVars and nominal values for all other parameters.
The Nominal field is itself a structure with fields for each logged signal. The field
names are the logged signal names. The custom requirement uses the logged signals,
P1 and P2. Therefore, data.Nominal.P1 and data.Nominal.P2 are timeseries
objects corresponding to P1 and P2.
• Uncertain - Logged signal data, obtained by simulating the model using the
sample values of the uncertain variable K_unc. The Uncertain field is a vector of N
structures, where N is the number of sample values specified for K_unc. Each element
of this vector is similar to data.Nominal and contains simulation results obtained
from a corresponding sample value specified for K_unc.
The function returns the maximum difference between the population sizes across
different carrying capacities. The following code snippet in the function performs this
action:
val = max(maxP(1)-minP(2),maxP(2)-minP(1));
3-166
Specify Custom Signal Objective with Uncertain Variable (GUI)
When computing the design goals, discard the initial population growth data to eliminate
biases from the initial-condition. The following code snippet in the function performs this
action:
iTime represents the time interval of interest, and the columns of sigData contain P1
and P2 data for this interval.
The function includes the effects of varying the carrying capacity by iterating through the
elements of data.Uncertain. The following code snippet in the function performs this
action:
...
for ct=1:numel(data.Uncertain)
iTime = data.Uncertain(ct).P1.Time > tMin;
sigData = [data.Uncertain(ct).P1.Data(iTime), data.Uncertain(ct).P2.Data(iTime)];
The maximum and minimal populations are obtained across all the simulations
contained in data.Uncertain.
Optimize Design
Click Optimize.
3-167
3 Response Optimization
The P1,P2 plot shows the population dynamics, with the first organism population in
blue and the second organism population in red. The dotted lines indicate the population
dynamics for different environment capacity values. The PopulationRange plot shows
that the maximum difference between the two organism populations reduces over time.
3-168
Specify Custom Signal Objective with Uncertain Variable (GUI)
The Population Phase Portrait block shows the populations initially varying, but
they eventually converge to stable population sizes.
3-169
3 Response Optimization
3-170
Design Optimization with Uncertain Variables (Code)
Continuously Stirred Tank Reactors (CSTRs) are common in the process industry. The
Simulink model, sdoCSTR, models a jacketed diabatic (i.e., non-adiabatic) tank reactor
described in [1]. The CSTR is assumed to be perfectly mixed, with a single first-order
exothermic and irreversible reaction, . , the reactant, is converted to , the
product.
In this example, you use the following two-state CSTR model, which uses basic
accounting and energy conservation principles:
• and - Volumetric flow rate [m^3/h] and the density of the material in the CSTR
[1/m^3]
• and - Height [m] and heated cross-sectional area [m^2] of the CSTR.
3-171
3 Response Optimization
• and - Heat capacity [kcal/K] and heat transfer coefficients [kcal/(m^2 * K * h)]
The model includes a cascaded PID controller in the Controller subsystem. The
controller regulates the reactor temperature, , and reactor residual concentration, .
Assume that the CSTR is cylindrical, with the coolant applied to the base of the cylinder.
Tune the CSTR cross-sectional area, , and CSTR height, , to meet the following design
goals:
3-172
Design Optimization with Uncertain Variables (Code)
• Minimize the mean coolant temperature . Heating or cooling the jacket coolant
temperature is expensive. Minimizing the mean coolant temperature improves CSTR
profit.
The design must allow for variations in the quality of supply feed concentration, ,
and feed temperature, . The CSTR is fed with feed from different suppliers. The
quality of the feed differs from supplier to supplier and also varies within each supply
batch.
• Cylinder height
p = sdo.getParameterFromModel('sdoCSTR',{'A','h'});
p(1).Minimum = 1;
p(1).Maximum = 2;
p(2).Minimum = 1;
p(2).Maximum = 3;
Select the feed concentration and feed temperature as uncertain variables. You evaluate
the design using different values of feed temperature and concentration.
pUnc = sdo.getParameterFromModel('sdoCSTR',{'FeedCon0','FeedTemp0'});
Create a parameter space for the uncertain variables. Use normal distributions for both
variables. Specify the mean as the current parameter value. Specify a variance of 5% of
the mean for the feed concentration and 1% of the mean for the temperature.
uSpace = sdo.ParameterSpace(pUnc);
uSpace = setDistribution(uSpace,'FeedCon0',makedist('normal',pUnc(1).Value,0.05*pUnc(1)
uSpace = setDistribution(uSpace,'FeedTemp0',makedist('normal',pUnc(2).Value,0.01*pUnc(2
3-173
3 Response Optimization
The feed concentration is inversely correlated with the feed temperature. Add this
information to the parameter space.
%uSpace.RankCorrelation = [1 -0.6; -0.6 1];
The rank correlation matrix has a row and column for each parameter with the (i,j) entry
specifying the correlation between the i and j parameters.
Sample the parameter space. The scatter plot shows the correlation between
concentration and temperature.
rng('default'); %For reproducibility
uSmpl = sdo.sample(uSpace,60);
sdo.scatterPlot(uSmpl)
3-174
Design Optimization with Uncertain Variables (Code)
Ideally you want to evaluate the design for every combination of points in the design and
uncertain spaces, which implies 30*60 = 1800 simulations. Each simulation takes around
0.5 sec. You can use parallel computing to speed up the evaluation. For this example
you instead only use the samples that have maximum & minimum concentration and
temperature values, reducing the evaluation time to around 1 min.
[~,iminC] = min(uSmpl.FeedCon0);
[~,imaxC] = max(uSmpl.FeedCon0);
[~,iminT] = min(uSmpl.FeedTemp0);
[~,imaxT] = max(uSmpl.FeedTemp0);
uSmpl = uSmpl(unique([iminC,imaxC,iminT,imaxT]) ,:);
The design requirements require logging model signals. During optimization, the model
is simulated using the current value of the design variables. Logged signals are used to
evaluate the design requirements.
• CSTR concentration, available at the second output port of the sdoCSTR/CSTR block
Conc = Simulink.SimulationData.SignalLoggingInfo;
Conc.BlockPath = 'sdoCSTR/CSTR';
Conc.OutputPortIndex = 2;
Conc.LoggingInfo.NameMode = 1;
Conc.LoggingInfo.LoggingName = 'Concentration';
Create and configure a simulation test object to log the required signals.
simulator = sdo.SimulationTest('sdoCSTR');
simulator.LoggingInfo.Signals = [Conc,Coolant];
Create a function to evaluate the CSTR design. This function is called at each
optimization iteration.
3-175
3 Response Optimization
Use an anonymous function with one argument that calls the sdoCSTR_design function.
The sdoCSTR_design function uses a for loop that iterates through the sample values
specified for the feed concentration. Within the loop, the function:
• Simulates the model using the current iterate, feed concentration, and feed
temperature values
dInit = evalDesign(p)
dInit =
F: 11.3358
costConc: 6.4387
costCoolant: 4.8971
Plot the model response for the initial design. Simulate the model using the sample feed
concentration values. The plot shows the variation in the residual concentration and
coolant temperature.
sdoCSTR_plotModelResponse(p,simulator,pUnc,uSmpl);
3-176
Design Optimization with Uncertain Variables (Code)
Optimize Design
Pass the objective function and initial CSTR dimensions to sdo.optimize.
pOpt = sdo.optimize(evalDesign,p)
3-177
3 Response Optimization
fmincon stopped because the size of the current step is less than
the selected value of the step size tolerance and constraints are
satisfied to within the selected value of the constraint tolerance.
pOpt(1,1) =
Name: 'A'
Value: 2
Minimum: 1
Maximum: 2
Free: 1
Scale: 0.5000
Info: [1x1 struct]
pOpt(2,1) =
Name: 'h'
Value: 2.2093
Minimum: 1
Maximum: 3
Free: 1
Scale: 2
Info: [1x1 struct]
2x1 param.Continuous
3-178
Design Optimization with Uncertain Variables (Code)
dFinal = evalDesign(pOpt)
dFinal =
F: 2.4644
costConc: 1.4454
costCoolant: 1.0191
Plot the model response for the optimized design. Simulate the model using the sample
feed concentration values. The optimized design reduces the residual concentration
variation and average coolant temperature for different feed stocks.
sdoCSTR_plotModelResponse(pOpt,simulator,pUnc,uSmpl);
3-179
3 Response Optimization
Related Examples
To learn how to use sensitivity analysis to explore the CSTR design space and select
an initial design for optimization, see "Design Optimization with Uncertain Variables
(Code)".
References
[1] Bequette, B.W. Process Dynamics: Modeling, Analysis and Simulation. 1st ed. Upper
Saddle River, NJ: Prentice Hall, 1998.
% Close the model
bdclose('sdoCSTR')
3-180
Generate MATLAB Code for Design Optimization Problems (GUI)
The "Design Optimization to Meet a Custom Objective Using the Response Optimization
Tool" example shows how to use the Response Optimization tool to optimize a cylinder
design. In this example we load a pre-configured Response Optimization tool session
based on that example.
load sdoHydraulicCylinder_sdosession
sdotool(SDOSessionData)
3-181
3 Response Optimization
3-182
Generate MATLAB Code for Design Optimization Problems (GUI)
3-183
3 Response Optimization
The generated code is added to the MATLAB editor as an unsaved MATLAB function.
3-184
Generate MATLAB Code for Design Optimization Problems (GUI)
3-185
3 Response Optimization
Select Save from the MATLAB editor to save the generated function.
The first output argument, pOpt, contains the optimized parameter values and the
second output argument, optInfo, contains optimization information.
You can:
3-186
Generate MATLAB Code for Design Optimization Problems (GUI)
3-187
3 Response Optimization
During optimization, the solver may try a design variable set that results in a model
simulation error, which can be computationally expensive. If you can define a parameter-
only constraint that identifies such a design variable set, then the solver can use the
constraint to skip such sets. In other words, you can configure the optimization to be
more efficient by disallowing design variable sets that lead to simulation errors.
Thermostat Model
open_system('sdoThermostat');
3-188
Skip Model Simulation Based on Parameter Constraint Violation (GUI)
The model describes a simple heater & thermostat that regulate the temperature of a
room. The room is subject to external temperature fluctuations. The room temperature is
computed using a first-order heat-flow equation:
Where:
The heater is controlled by a thermostat that turns on when the difference between the
room temperature and temperature set-point exceeds a threshold. The heater turns off
when the error drops below a threshold.
3-189
3 Response Optimization
The heater operation is displayed in the Heater use scope. The upper axis is the
delivered heat and the lower axis shows the times when the heater is switched on.
3-190
Skip Model Simulation Based on Parameter Constraint Violation (GUI)
You tune the thermostat turn-on and turn-off temperature thresholds, and also the
heater power. The Thermostat switch block specifies the turn-on and turn-off
thresholds using the variables H_on and H_off. The Heater block specifies the heater
power using the variable Hgain.
• Minimize the difference between the room temperature and temperature set-point
over a 24 hour period.
• The heater must not turn on more than 12 times during the 24 hour period.
• The thermostat turn-on temperature must be greater than the thermostat turn-
off temperature. If this constraint is violated, the model is invalid and cannot be
simulated or evaluated.
load sdoThermostat_sdosession
sdotool(SDOSessionData)
3-191
3 Response Optimization
3-192
Skip Model Simulation Based on Parameter Constraint Violation (GUI)
3-193
3 Response Optimization
• DesignVars - Design variables set for the H_on, H_off, and Hgain model
parameters.
• Minimize_T_error - Requirement to minimize the temperature deviation from the
set-point.
• LimitH_on - Requirement to limit the number of times the thermostat is turned on.
• H_on_sig and T_error - Logged signals. H_on_sig represents when the heater is
on. T_error is the difference between the room temperature and the set-point.
3-194
Skip Model Simulation Based on Parameter Constraint Violation (GUI)
The H_on > H_off requirement is not yet defined. Use a custom requirement to specify
this constraint and configure the requirement to error if it is not satisfied.
In the New drop-down list, select Custom Requirement. The Create Requirement
dialog opens.
• Name - SwitchConstraint.
• Type - Select Constrain the function output to be >= 0 from the Type list.
• Function - @sdoThermostat_SwitchingConstraint.
3-195
3 Response Optimization
The software evaluates custom requirements that test parameter-only constraints, such
as SwitchConstraint, before simulating the model and evaluating the remaining
requirements.
• If the constraint is violated while the Error if constraint is violated check box
is selected, the software does not simulate the model to evaluate the remaining
requirements. Instead, the solver assigns the cost function a NaN value for this
iteration, evaluates the terminating conditions, and continues.
• If the constraint is violated while the Error if constraint is violated check box
is cleared, the solver will attempt to simulate the model to evaluate the remaining
requirements. Simulating the model may lead to a hard error; for example, simulating
the thermostat model when SwitchConstraint is violated will lead to an error. In
this case, the solver assigns the cost function a NaN value for this iteration, evaluates
the terminating conditions, and continues.
Click Optimize.
3-196
Skip Model Simulation Based on Parameter Constraint Violation (GUI)
3-197
3 Response Optimization
The Optimization Progress window appears and updates at each iteration. The
optimization successfully minimizes the temperature error while satisfying the switching
constraints.
During this optimization, the H_on and H_off values never approach the H_on > H_off
constraint boundary. So, there is never a danger of violating the constraint. However,
changing the optimization algorithm may produce different behavior. For example,
changing the optimization algorithm from the one used here, 'Interior-Point', to 'Active-
Set' results in H_on and H_off values that are at the constraint boundary. This violation
3-198
Skip Model Simulation Based on Parameter Constraint Violation (GUI)
triggers the SwitchConstraint requirement and prevents model simulation for the
relevant iterations.
Simulate the model with the optimized thermostat settings. The optimized heater
operation is displayed in the Heater use scope where the upper axis is the delivered
heat and the lower axis the heater switch on times.
3-199
3 Response Optimization
3-200
Optimizing Parameters for Robustness
What Is Robustness?
A design is robust when it's response does not violate design requirements under
model parameter variations. Your model may contain parameters whose values are not
precisely known. Such parameters vary over a given range of values and are defined as
uncertain parameters. You may know the nominal value and the range of values in which
these uncertain parameters vary.
You can use Simulink Design Optimization software to incorporate the parameter
uncertainty to test the robustness of your design. When you optimize parameters for
robustness, the optimization solver uses the responses computed using all the uncertain
parameter values to adjust the design variable values.
You can specify the same parameter both as a design and uncertain variable. However,
you cannot use a parameter both as a design and uncertain variable in the same
optimization run. Also, you cannot add uncertainty to controller or plant parameters
during optimization-based control design in the SISO Design Tool.
You can test and optimize parameters for model robustness in the following ways:
3-201
3 Response Optimization
Related Examples
More About
a
0 3
2.5
There are two methods to determine the number of sample values to use during
optimization:
3-202
Optimizing Parameters for Robustness
0 a 3
2.5
• Combination of the entire set of values (all solid dots in the previous figure)
Tip Using only the minimum and maximum values during optimization increases the
computation speed when compared to using the entire set of values.
For the previous example, there are 4 combinations using the minimum and maximum
values and 16 combinations if you use all sample values.
In the Response Optimization tool, you specify the sampling method using the options as
shown in the following figure.
3-203
3 Response Optimization
3-204
Optimizing Parameters for Robustness
Related Examples
More About
3-205
3 Response Optimization
load sldo_model1_desreq_optim_sdosession;
sdotool(SDOSessionData);
The sdotool command opens the following Simulink model and a saved Response
Optimization tool session.
The parameters of this model, Kp, Ki and Kd, have already been optimized to meet
the following step response requirements:
• Maximum overshoot of 5%
• Maximum rise time of 10 seconds
• Maximum settling time of 30 seconds
2 Specify parameter uncertainty.
3-207
3 Response Optimization
The check-box indicates that the parameter is included in the uncertain variable
set. The default uncertain variable set name is UncVars.
Click OK. A new variable UncVars appears in Data area of the Response
Optimization tool.
A window opens where you specify the range and the number of samples.
3-208
Optimizing Parameters for Robustness
3-209
3 Response Optimization
• The solid curve corresponds to the model response computed using the
optimized parameters and nominal values of the uncertain parameter.
• The four dashed curves correspond to the model response with the minimum
and maximum values of the uncertain parameters.
The dashed plot lines show that the response during the period of 10 to 20
seconds violates the design requirements.
4 Optimize the parameters for model robustness. Click Optimize.
The Optimization Progress window opens which displays the optimization iterations.
3-210
Optimizing Parameters for Robustness
Tip To view only the final responses of the model, right-click the white area in the
plot and uncheck Responses > Show Iteration Responses.
3-211
3 Response Optimization
The final responses appear as the thick solid and dashed curves. The nominal and
uncertain responses with parameter variations now meet the design requirements.
More About
Related Examples
• “Design Optimization with Uncertain Variables (Code)” on page 3-171
3-212
How to Use Accelerator Mode During Simulations
The default simulation mode is Normal. In this mode, Simulink uses interpreted code,
rather than compiled C code during simulations.
Limitations
You cannot use the Accelerator mode if your model contains algebraic loops. If the
model contains MATLAB function blocks, you must either remove them or replace them
with Fcn blocks.
If the model structure changes during optimization, the model is compiled to regenerate
the C code for each iteration. In this case, using the Accelerator mode increases the
computation time. To learn more about code regeneration, see “Code Regeneration in
Accelerated Models” in the Simulink documentation.
3-213
3 Response Optimization
• Choose Accelerator from the drop-down list as shown in the next figure.
Tip To obtain the maximum performance from the Accelerator mode, close all
Scope blocks in your model.
More About
• “Ways to Speed Up Design Optimization Tasks”
3-214
Speed Up Response Optimization Using Parallel Computing
• The model contains a large number of tuned parameters, and the Gradient
descent method is selected for optimization.
• The Pattern search method is selected for optimization.
• The model contains a large number of uncertain parameters and uncertain parameter
values.
• The model is complex and takes a long time to simulate.
When you use parallel computing, the software distributes independent simulations to
run them in parallel on multiple MATLAB sessions, also known as workers. Distributing
the simulations significantly reduces the optimization time because the time required to
simulate the model dominates the total optimization time.
For information on how the software distributes the simulations and the expected
speedup, see “How Parallel Computing Speeds Up Optimization” on page 3-215.
For information on configuring your system and using parallel computing, see “How to
Use Parallel Computing for Response Optimization” on page 3-219.
3-215
3 Response Optimization
When you select Gradient descent as the optimization method, the model is simulated
during the following computations:
The total time, Ttotal , taken per iteration to perform these simulations is given by the
following equation:
where T is the time taken to simulate the model and is assumed to be equal for all
simulations, Np is the number of tuned parameters, and Nls is the number of line
searches. Nls is difficult to estimate and you generally assume it to be equal to one, two,
or three.
When you use parallel computing, the software distributes the simulations required for
constraint and objective gradient computations. The simulation time taken per iteration
when the gradient computations are performed in parallel, TtotalP , is approximately
given by the following equation:
Ê Np ˆ Ê Np ˆ
TtotalP =T + ( ceil Á ˜ ¥ 2 ¥ T ) + ( Nls ¥ T ) = T ¥ (1 + 2 ¥ ceil Á ˜ + Nls)
Ë Nw ¯ Ë Nw ¯
Note: The equation does not include the time overheads associated with configuring the
system for parallel computing and loading Simulink software on the remote MATLAB
workers.
3-216
Speed Up Response Optimization Using Parallel Computing
The expected speedup for the total optimization time is given by the following equation:
Ê Np ˆ
1 + 2 ¥ ceil Á ˜ + Nls
TtotalP
= Ë Nw ¯
Ttotal 1 + ( 2 ¥ Np) + Nls
For example, for a model with Np=3, Nw=4, and Nls=3, the expected speedup equals
Ê3ˆ
1 + 2 ¥ ceil Á ˜ + 3
Ë4¯ = 0.6 .
1 + (2 ¥ 3) + 3
For an example of the performance improvement achieved with the Gradient descent
method, see Improving Optimization Performance Using Parallel Computing.
The Pattern search optimization method uses search and poll sets to create and
compute a set of candidate solutions at each optimization iteration.
The total time, Ttotal , taken per iteration to perform these simulations, is given by the
following equation:
where T is the time taken to simulate the model and is assumed to be equal for all
simulations, Np is the number of tuned parameters, Nss is a factor for the search set
size, and Nps is a factor for the poll set size. Nss and Nps are typically proportional to
Np .
When you use parallel computing, Simulink Design Optimization software distributes
the simulations required for the search and poll set computations, which are evaluated in
separate parfor loops. The simulation time taken per iteration when the search and poll
sets are computed in parallel, TtotalP , is given by the following equation:
Nss Nps
TtotalP = ( T ¥ ceil( Np ¥ )) + ( T ¥ ceil( Np ¥ ))
Nw Nw
Nss Nps
= T ¥ ( ceil( Np ¥ ) + ceil( Np ¥ ))
Nw Nw
3-217
3 Response Optimization
Note: The equation does not include the time overheads associated with configuring the
system for parallel computing and loading Simulink software on the remote MATLAB
workers.
The expected speed up for the total optimization time is given by the following equation:
Nss Nps
ceil( Np ¥ ) + ceil( Np ¥ )
TtotalP Nw Nw
=
Ttotal Np ¥ ( Nss + Nps)
For example, for a model with Np=3, Nw=4, Nss=15, and Nps=2, the expected speedup
15 2
ceil(3 ¥ ) + ceil(3 ¥ )
equals 4 4 = 0 .27 .
3 ¥ (15 + 2)
Note: Using the Pattern search method with parallel computing may not speed up
the optimization time. To learn more, see “Why do I not see the optimization speedup I
expected using parallel computing?” on page 3-236
For an example of the performance improvement achieved with the Pattern search
method, see Improving Optimization Performance Using Parallel Computing.
Related Examples
• “How to Use Parallel Computing for Response Optimization” on page 3-219
3-218
How to Use Parallel Computing for Response Optimization
In this section...
“Configure Your System for Parallel Computing” on page 3-219
“Model Dependencies” on page 3-219
“Optimize Design Using Parallel Computing (GUI)” on page 3-220
“Optimize Design Using Parallel Computing (Code)” on page 3-224
“Troubleshooting” on page 3-225
When you optimize model parameters using parallel computing, the software uses the
available parallel pool. If none is available, and you select Automatically create a
parallel pool in your Parallel Computing Toolbox preferences, the software starts a
parallel pool using the settings in those preferences. To open a parallel pool that uses a
specific cluster profile, use:
parpool(MyProfile);
For information regarding creating a cluster profile, see “Create and Modify Cluster
Profiles” in the Parallel Computing Toolbox documentation.
Model Dependencies
Model dependencies are any referenced models, data such as model variables, S-
functions, and additional files necessary to run the model. Before starting the
optimization, verify that the model dependencies are complete. Otherwise, you may get
unexpected results.
3-219
3 Response Optimization
When you use parallel computing, the Simulink Design Optimization software helps you
identify model dependencies. To do so, the software uses the Simulink Manifest Tools.
The dependency analysis may not find all the files required by your model. To learn
more, see “Scope of Dependency Analysis” in the Simulink documentation. If your model
has dependencies that are undetected or inaccessible by the parallel pool workers, then
add them to the list of model dependencies.
The dependencies are made accessible to the parallel pool workers by specifying one of
the following:
• File dependencies: the model dependency files are copied to the parallel pool workers.
• Path dependencies: the paths to the model dependencies are specified to the parallel
pool workers. If you are working in a multi-platform scenario, ensure that the paths
are compatible across platforms.
1 Ensure that the software can access parallel pool workers that use the appropriate
cluster profile.
For more information, see “Configure Your System for Parallel Computing” on page
3-219.
2 Open the Response Optimization tool for the Simulink model.
3 Configure the design variables, design requirements, and, optionally, optimization
settings.
3-220
How to Use Parallel Computing for Response Optimization
For more information, see “Specify Design Variables” on page 3-61, “Specify Time-
Domain Design Requirements” on page 3-23, “Specify Frequency-Domain Design
Requirements” on page 3-39, and “Optimization Options” on page 3-72.
4
On the Response Optimization tab, click Options to open the Response
Optimization Options dialog box.
5 Select the Parallel Options tab.
6 Select the Use the parallel pool during optimization check box.
This option checks for dependencies in your Simulink model. The file dependencies
are displayed in the Model file dependencies list box, and corresponding
path to the files in Model path dependencies. The files listed in Model file
dependencies are copied to the remote workers.
Note: The automatic dependencies check may not detect all the dependencies in your
model.
3-221
3 Response Optimization
For more information, see “Model Dependencies” on page 3-219. In this case, add
the undetected dependencies manually.
7 Add any file dependencies that the automatic check does not detect.
Specify the files in the Model file dependencies list box separated by semicolons
or on separate lines.
3-222
How to Use Parallel Computing for Response Optimization
Alternatively, click Add file dependency to open a dialog box, and select the file to
add.
Note: If you do not want to copy the files to the remote workers, delete all entries in
the Model file dependencies list box. Populate the Model path dependencies
list box by clicking the Sync path dependencies from model, and add any
undetected path dependencies. In addition, in the list box, update the paths on local
drives to make them accessible to remote workers. For example, change C:\ to \\\
\hostname\\C$\\.
8 If you modify the Simulink model, resync the dependencies to ensure that any new
dependencies are detected. Click Sync file dependencies from model in the
Parallel Options tab to rerun the automatic dependency check for your model.
This action updates the Model file dependencies list box with any new file
dependency found in the model.
9 Click OK.
10 In the Response Optimization tool, click Optimize to optimize the model response
using parallel computing.
3-223
3 Response Optimization
1 Ensure that the software can access parallel pool workers that use the appropriate
cluster profile.
For more information, see “Configure Your System for Parallel Computing” on page
3-219.
2 Open the model.
3 Specify design requirements and design variables. For example see, “Design
Optimization to Meet Step Response Requirements (Code)”.
4 Enable parallel computing using an optimization option set, opt.
opt = sdo.OptimizeOptions;
opt.UseParallel = 'always';
5 Find the model dependencies.
[dirs,files] = sdo.getModelDependencies(modelname)
Note: If you do not want to copy the files to the remote workers, use the path
dependencies. Add any undetected path dependencies to dirs and update
the paths on local drives to make them accessible to remote workers. See
sdo.getModelDependencies for more details.
7 Add the file dependencies for optimization.
opt.ParallelFileDependencies = files;
3-224
How to Use Parallel Computing for Response Optimization
[pOpt,opt_info] = sdo.optimize(opt_fcn,param,opt);
Troubleshooting
• “Why Are the Optimization Results With and Without Using Parallel Computing
Different?” on page 3-225
• “Why Don’t I See the Optimization Speed up I Expected Using Parallel Computing?”
on page 3-225
• “Why Doesn’t the Optimization Using Parallel Computing Make Any Progress?” on
page 3-226
• “Why Doesn’t the Optimization Using Parallel Computing Stop When I Click the Stop
Optimization Button?” on page 3-226
Why Are the Optimization Results With and Without Using Parallel Computing Different?
• Different numerical precision on the client and worker machines can produce
marginally different simulation results. Thus, the optimization method can take a
different solution path and produce a different result.
• When you use parallel computing with the Pattern search method, the search is
more comprehensive and can result in a different solution.
To learn more, see “Parallel Computing with the Pattern Search Method” on page
3-217.
Why Don’t I See the Optimization Speed up I Expected Using Parallel Computing?
• When you optimize a model that does not have a large number of parameters or does
not take long to simulate, you might not see a speedup in the optimization time. In
such cases, the overhead associated with creating and distributing the parallel tasks
outweighs the benefits of running the optimization in parallel.
• Using the Pattern search method with parallel computing might not speed up
the optimization time. Without parallel computing, the method stops the search at
each iteration when it finds a solution better than the current solution. The candidate
solution search is more comprehensive when you use parallel computing. Although
3-225
3 Response Optimization
the number of iterations might be larger, the optimization without using parallel
computing might be faster.
To learn more about the expected speedup, see “Parallel Computing with the Pattern
Search Method” on page 3-217.
Why Doesn’t the Optimization Using Parallel Computing Make Any Progress?
1 Run the optimization for a few iterations without parallel computing to see if the
optimization progresses.
2 Check whether the remote workers have access to all model dependencies. Model
dependencies include data variables and files required by the model to run.
Why Doesn’t the Optimization Using Parallel Computing Stop When I Click the Stop
Optimization Button?
When you use parallel computing with the Pattern search method, the software must
wait until the current optimization iteration completes before it notifies the workers
to stop. The optimization does not terminate immediately when you click Stop, and,
instead, appears to continue running.
See Also
sdo.OptimizeOptions | parpool | sdo.getModelDependencies | sdo.optimize
Related Examples
• “Optimizing Time-Domain Response of Simulink® Models Using Parallel
Computing” on page 3-243
More About
• “Speed Up Response Optimization Using Parallel Computing” on page 3-215
• “Ways to Speed Up Design Optimization Tasks”
3-226
Use Fast Restart Mode During Response Optimization
This topic shows how to speed up response optimization using Simulink fast restart. You
can use the fast restart feature to speed up response optimization of tunable parameters
of a model.
Fast restart enables you to perform iterative simulations without compiling a model or
terminating the simulation each time. Using fast restart, you compile a model only once.
You can then tune parameters and simulate the model again without spending time on
compiling. Fast restart associates multiple simulation phases with a single compile phase
to make iterative simulations more efficient. You see a speedup of design optimization
tasks using fast restart in models that have a long compilation phase. See “How Fast
Restart Improves Iterative Simulations” in the Simulink documentation.
When you enable fast restart, you can only change tunable properties of the model during
simulation. For more information about the limitations, see “Factors Affecting Fast
Restart”.
You can optimize using fast restart in the Response Optimization tool or at the command
line.
3-227
3 Response Optimization
For more information, see “Specify Design Variables” on page 3-61, “Specify Time-
Domain Design Requirements” on page 3-23, “Specify Frequency-Domain Design
Requirements” on page 3-39, and “Optimization Options” on page 3-72.
5 Click Optimize to optimize the model response in fast restart mode.
6 Disable fast restart.
Simulator = sdo.SimulationTest('model');
Note: In fast restart mode, you cannot use the linearize command from Simulink
Control Design to specify and compute linear systems. Using linearize generates
an error.
3 Specify design requirements, Requirements, and design variables, param. For and
example, see “Design Optimization to Meet Step Response Requirements (Code)”.
4 Configure the model and simulation scenario for fast restart.
Simulator = fastRestart(Simulator,'on');
3-228
Use Fast Restart Mode During Response Optimization
5 Create an optimization cost function, myCostfcn, and pass Simulator to the cost
function as an input. For more information, see “Write a Cost Function” on page
2-83. In the cost function, the simulator configured for fast restart is used to update
the model parameters, simulate the model, and log signals.
Here, myCostfcn is a cost function that takes design variables, param, simulation
scenario, Simulator, and design requirements, Requirements, as inputs.
6 Run the optimization.
[param_opt,opt_info] = sdo.optimize(optimfcn,param);
7 Restore the simulator fast restart settings.
Simulator = fastRestart(Simulator,'off');
Troubleshooting
Why Don’t I See the Optimization Speedup I Expected Using Fast Restart?
You see a speedup of design optimization tasks using fast restart in models that have a
long compilation phase. If the compilation phase of your model is not long, you do not see
a significant change in optimization speed.
See Also
fastRestart | sdo.optimize | sdo.SimulationTest
Related Examples
• “Improving Optimization Performance using Fast Restart (GUI)” on page 2-198
• “Improving Optimization Performance using Fast Restart (Code)” on page 2-206
More About
• “Ways to Speed Up Design Optimization Tasks”
3-229
3 Response Optimization
Should I worry about the scale of my responses and how constraints and
design requirements are discretized?
No. Simulink Design Optimization software automatically normalizes constraints, design
requirement and response data.
3-230
Optimization Does Not Make Progress
3-231
3 Response Optimization
Optimization Convergence
In this section...
“What to do if the optimization does not get close to an acceptable solution?” on page
3-232
“Why does the optimization terminate before exceeding the maximum number
of iterations, with a solution that does not satisfy all the constraints or design
requirements?” on page 3-233
“What to do if the optimization takes a long time to converge even though it is close to a
solution?” on page 3-233
“What to do if the response becomes unstable and does not recover?” on page 3-234
3-232
Optimization Convergence
command line. EvalErrors has two fields, Errors and DesignVars, containing
the errors encountered during optimization and the corresponding design variable
values. To reproduce a specific error, use sdo.setValueInModel to run the
model using the design variables that correspond to the error.
• At the command line, the second output of sdo.optimize, opt_info,
is a structure that provides information regarding the optimization.
opt_info.exitflag identifies the reason the optimization terminated. For more
information regarding exit flags, see “Exit Flags and Exit Messages”.
When you use a SISO Design Task, click Stop Optimization in the Optimization
panel of the Response Optimization node in the Control and Estimation Tools
Manager, when you think the current optimized response signals are acceptable.
• If you use the gradient descent method, try restarting the optimization. Restarting
resets the Hessian estimate and might speed up convergence.
• Increase the convergence tolerances in the Optimization Options dialog to force
earlier termination.
• Relax some of the constraints or design requirements to increase the size of the
feasibility region.
3-233
3 Response Optimization
• Add or tighten the lower and upper bounds on compensator element and parameter
values. Instability often occurs when you allow some parameter values to become too
large.
• Use a search-based method to find parameter values that stabilize the response
signals and then start the gradient-based method using these initial values.
• When optimizing responses in a SISO Design Task, you can try adding additional
design requirements that achieve the same or similar goal. For example, in addition
to a settling time design requirement on a step response plot, you could add a settling
time design requirement on a root-locus plot that restricts the location of the real
parts of the poles. By adding overlapping design requirements in this way, you can
force the optimization to meet the requirements.
3-234
Optimization Speed and Parallel Computing
In this section...
“How can I speed up the optimization?” on page 3-235
“Why are the optimization results with and without using parallel computing different?”
on page 3-236
“Why do I not see the optimization speedup I expected using parallel computing?” on
page 3-236
“Why does the optimization using parallel computing not make any progress?” on page
3-236
“Why does the optimization using parallel computing not stop when I click the Stop
optimization button?” on page 3-237
Note: The Rapid Accelerator mode in Simulink software is not supported for speeding
up the optimization. For more information, see “How to Use Accelerator Mode During
Simulations” on page 3-213.
• The choice of ODE solver can also significantly affect the overall optimization time.
Use a stiff solver when the simulation takes many small steps, and use a fixed-step
solver when such solvers yield accurate enough simulations for your model. (These
solvers must be accurate in the entire parameter search space.)
• Reduce the number of tuned compensator elements or parameters and constrain their
range to narrow the search space.
• When specifying parameter uncertainty (not available when optimizing responses in
a SISO Design Task), keep the number of sample values small since the number of
simulations grows exponentially with the number of samples. For example, a grid of 3
parameters with 10 sample values for each parameter requires 103=1000 simulations
per iteration.
3-235
3 Response Optimization
Why are the optimization results with and without using parallel
computing different?
• Different numerical precision on the client and worker machines can produce
marginally different simulation results. Thus, the optimization method can take a
different solution path and produce a different result.
• When you use parallel computing with the Pattern search method, the search is
more comprehensive and can result in a different solution.
To learn more, see “Parallel Computing with the Pattern Search Method” on page
3-217.
To learn more about the expected speedup, see “Parallel Computing with the Pattern
Search Method” on page 3-217.
Why does the optimization using parallel computing not make any
progress?
To troubleshoot the problem:
1 Run the optimization for a few iterations without parallel computing to see if the
optimization progresses.
2 Check whether the remote workers have access to all model dependencies. Model
dependencies include data variables and files required by the model to run.
3-236
Optimization Speed and Parallel Computing
Why does the optimization using parallel computing not stop when I click
the Stop optimization button?
When you use parallel computing with the Pattern search method, the software must
wait until the current optimization iteration completes before it notifies the workers
to stop. The optimization does not terminate immediately when you click Stop, and,
instead, appears to continue running.
3-237
3 Response Optimization
This information helps guide the optimization method towards a reasonable solution.
• Specify initial guesses that are within the range of desirable values.
• In the Compensators pane in a SISO Design Task, verify that no integrators/
differentiators are selected for optimization. Optimizing the pole/zero location of
integrators/differentiators can result in drastic changes in the system gain and lead to
undesirable values.
• Specify a different value for the parameter bound and restart the optimization. A
guideline is to adjust the bound by 1% of the typical value.
For example, for a parameter with a typical value of 1 and lower bound of 0, change
the lower bound to 0.01.
• Relax the signal constraints and restart the optimization. This approach results in a
different solution path for the Gradient descent method.
3-238
Undesirable Parameter Values
For example, run the optimization using the Simplex search method. This
method satisfies the signal constraints but does not support the bounds on
parameter values. The results obtained using this method provide the starting
point for the optimization performed in the next step. To learn more about this
method, see the fminsearch function reference page in the Optimization Toolbox
documentation.
2 Reconfigure the optimization by selecting a different optimization method to
satisfy both the signal constraints and the parameter bounds.
For example, change the optimization method to Gradient descent and run
the optimization again.
Tip If Global Optimization Toolbox software is installed, you can select the Pattern
search optimization method to optimize the model response.
3-239
3 Response Optimization
• In the Response Optimization tool, click Options. Uncheck Update model at end
of optimization in the General Options tab.
• In the Response Optimization tool, click Options. Select Save optimized
variable values as new design variable set in the General Options tab.
• Make a copy of the design variable set in the Data area.
If you want to revert to the initial parameter values after the optimization terminates
or you stop the optimization by clicking Stop, select the design variable that contains
the initial values in the Design Variable Set drop-down list and click adjacent
to Design variables Set. Select the design variables in the dialog box and click
Update model variable values to revert the model parameters to their original
values.
• When using a SISO Design Task, the Start Optimization button becomes a Stop
Optimization button after the optimization has begun. To quit the optimization,
click the Stop Optimization button. To revert to the initial parameter values, select
Edit > Undo Optimize compensators from the menu in the SISO Design Tool
window.
3-240
Manage Response Optimization Tool Session
Save a Session
Saving a session lets you reuse your settings and optimization results later. These
settings include design requirements, design and uncertain variables, plots and
optimization settings. Each Response Optimization tool session is associated with a
Simulink model.
• To save the session as a MAT-file, in the Save Session drop-down list, click Save
to file in the Response Optimization tab. A window opens where you specify the
MAT-file name.
• To save the session as a model or MATLAB workspace variable, select Save to model
workspace or Save to MATLAB workspace in the Save Session drop-down list.
Load a Session
You can load a saved MAT-file or workspace session:
3-241
3 Response Optimization
To load a workspace variable, select Open from model workspace or Open from
MATLAB workspace in the Open Session drop-down list.
3-242
Optimizing Time-Domain Response of Simulink® Models Using Parallel Computing
The Simulink model consists of a boiler model and a discrete PI controller. When using
parallel computing, Simulink Design Optimization performs a model dependency check,
which recognizes the boiler model library as an installed library.
In order to illustrate how model dependencies are handled when using parallel
computing, we copy the boiler model and library block to a temporary folder before
opening the model.
3-243
3 Response Optimization
Design Requirements
The boiler pressure is regulated by a discrete PI controller. The design requirement for
the controller is to limit the pressure variation of the boiler within +-%5 of the nominal
pressure.
The initial controller has fairly good regulation characteristics but in the presence of
additional heat disturbances, modeled by the Heat Disturbance block, we want to tune
the controller performance to provide tighter pressure regulation.
Double-click the 'Response Optimization GUI with preloaded data' block in the Simulink
model to open a pre-configured Response Optimization Tool. The Response Optimization
Tool is configured with:
1. Upper and lower bounds representing a +-5% allowable range on the drum pressure
2. A reference tracking objective to minimize the deviation of the drum pressure from
nominal
3-244
Optimizing Time-Domain Response of Simulink® Models Using Parallel Computing
Click Plot Model Response to display the drum pressure variations with the initial
controller.
Configuring and Running the Optimization in the GUI Using Parallel Computing
When computing the model response with the initial controller, this complex model took
a long time to simulate. Using parallel computing can reduce the optimization time
by simulating the model in parallel. For more information on parallel computing and
optimization performance see the tutorial "Improving Optimization Performance Using
Parallel Computing".
To configure the optimization problem to use parallel computing click Options in the
Response Optimization Tool and select the Parallel Options tab. Select the "Use the
3-245
3 Response Optimization
parallel pool during optimization" option. This triggers an automated search for any
model dependencies. In this example, the Steam table library (libsteam.slx) is found
as a model dependency (in addition to the boilerpressure_demo model itself), and is
displayed in the Model file dependencies list box.
To run the optimization click the Optimize button. A progress window opens displaying
optimization progress and the plots update to show the optimized response.
3-246
Optimizing Time-Domain Response of Simulink® Models Using Parallel Computing
The final response shows that the optimized regulator tracks the reference pressure
much more closely and the drum pressure constraints are satisfied.
You can also use the command line functions to configure the optimization to use parallel
computing and run the optimization.
Select the model variables for optimization and set lower limits
p = sdo.getParameterFromModel('boilerpressure_demo',{'Kp','Ki'});
p(1).Minimum = 0.001;
p(2).Minimum = 0.001;
3-247
3 Response Optimization
Select the model signal to bound and create a simulator to simulate the model.
nPressure = Simulink.SimulationData.SignalLoggingInfo;
nPressure.BlockPath = 'boilerpressure_demo/1//y0';
nPressure.OutputPortIndex = 1;
nPressure.LoggingInfo.NameMode = 1;
nPressure.LoggingInfo.LoggingName = 'nPressure';
simulator = sdo.SimulationTest('boilerpressure_demo');
simulator.LoggingInfo.Signals = nPressure;
Get the optimization requirements defined by the check blocks in the model so that we
can use them in the optimization problem.
bnds = getbounds('boilerpressure_demo/Drum pressure constraint');
PressureLimits = [bnds{:}];
bnds = getbounds('boilerpressure_demo/Drum pressure constraint(Reference Tracking)');
PressureRegulation = [bnds{:}];
requirements = struct(...
'PressureLimits', PressureLimits, ...
'PressureRegulation', PressureRegulation);
Define the function called during optimization. Notice that the function uses the
simulator and requirements defined earlier to evaluate the design.
evalDesign = @(p) boilerpressure_design(p,simulator,requirements);
type boilerpressure_design
3-248
Optimizing Time-Domain Response of Simulink® Models Using Parallel Computing
% the design.
%
% see also sdo.optimize, sdoExampleCostFunction
3-249
3 Response Optimization
%%
% Use the PressureRegulation requirement as an objective for optimization.
design.F = f;
end
Setup optimization options to use the parallel pool and specify the model and model files
dependencies.
opt = sdo.OptimizeOptions;
opt.UseParallel = 'always';
opt.OptimizedModel = 'boilerpressure_demo';
[dirs,files] = sdo.getModelDependencies('boilerpressure_demo');
opt.ParallelFileDependencies = files;
To run the optimization using the parallel pool pass the optimization options, opt, to the
sdo.optimize command.
3-250
Optimizing Time-Domain Response of Simulink® Models Using Parallel Computing
After the model is optimized, we remove the boiler model and library file from the
temporary folder.
bdclose('boilerpressure_demo')
rmpath(pathToLib)
boilerpressure_cleanup(pathToLib)
3-251
3 Response Optimization
Suspension Model
Mass-spring-damper models represent simple suspension systems and for this example
we tune the system to meet typical suspension requirements. The model implements
3-252
Design Optimization to Meet Frequency-Domain Requirements (Code)
the second order system representing a mass-spring-damper using Simulink blocks and
includes:
• a Mass gain block parameterized by the total suspended mass, m0+mLoad. The total
mass is the sum of a nominal mass, m0, and a variable load mass, mLoad.
Simulate the model to view the system response to the applied disturbance force.
3-253
3 Response Optimization
Design Problem
The initial system has a bandwidth that is too high. This can be seen from the
spiky position signal. You tune the spring and damper values to meet the following
requirements:
• The damping ratio of the system must be less than 1/sqrt(2). This ensures that no
frequencies in pass band are amplified by the system.
• Minimize the expected failure rate of the system. The expected failure rate is
described by a Weibull distribution dependent on the mass, spring, and damper
values.
• These requirements must all be satisfied as the load mass ranges from 0 to 20 kg.
DesignVars = sdo.getParameterFromModel('sdoSimpleSuspension',{'b','k'});
DesignVars(1).Minimum = 100;
DesignVars(1).Maximum = 10000;
DesignVars(2).Minimum = 10000;
DesignVars(2).Maximum = 100000;
Specify mLoad, the load mass, as an uncertian variable. This will ensure the optimal
solution is robust to variations in load mass.
UncVars = sdo.getParameterFromModel('sdoSimpleSuspension','mLoad');
UncVars_Values = {...
10; ...
20};
Requirements = struct;
Requirements.Bandwidth = sdo.requirements.BodeMagnitude(...
'BoundFrequencies', [10 100], ...
'BoundMagnitudes', [-3 -3]);
Requirements.DampingRatio = sdo.requirements.PZDampingRatio;
3-254
Design Optimization to Meet Frequency-Domain Requirements (Code)
Linearization Definition
The design requirements use the bandwidth and damping ratio of the system, these
frequency domain characteristics require linearizing the model. Create a simulator
for the model and use the simulator to compute the linear systems used by the
requirements.
Simulator = sdo.SimulationTest('sdoSimpleSuspension');
Specify linear systems to compute by specifying the linearization inputs and outputs of
the system. The linear system input is the output of the Band-Limited Disturbance
Force block and the linear system output is the output of the x_dot block (the
position signal).
sys1 = sdo.SystemLoggingInfo;
sys1.Source = 'IOs';
sys1.LoggingName = 'IOs';
sys1.LinearizationIOs = IOs;
sys1.SnapshotTimes = 0;
Add the system logging info to the simulator. When the simulator is used to run the
model, the linear system defined by the specifed linearization IOs is computed and added
to the simulation log with the specified logging name.
Simulator.SystemLoggingInfo = sys1;
Create a function that is called at each optimization iteration to evaluate the design
requirements.
3-255
3 Response Optimization
3-256
Design Optimization to Meet Frequency-Domain Requirements (Code)
wksp = get_param('sdoSimpleSuspension','ModelWorkspace');
m = evalin(wksp,'m0');
%% Nominal Evaluation
%
% Evaluate the model and requirements with uncertain parameters set to their
% nominal values.
%% Uncertain Evaluation
%
% Evaluate the model and requirements for all combinations of uncertain
% parameter values.
for ct=1:size(UncVars_Values,1)
UncVars(1).Value = UncVars_Values{ct,1};
3-257
3 Response Optimization
%% Return Values.
%
% Collect the evaluated design requirement values in a structure to
% return to the optimization solver.
Vals.F = pFailure;
Vals.Cleq = [...
Cleq_Bandwidth(:); ...
Cleq_DampingRatio(:)];
end
Optimization Options
Options = sdo.OptimizeOptions;
Options.MethodOptions.MaxFunEvals = [];
Options.MethodOptions.Algorithm = 'active-set';
Options.MethodOptions.LargeScale = 'on';
Options.MethodOptions.TolGradCon = 1e-06;
Call sdo.optimize with the objective function handle, parameters to optimize, and
options.
[Optimized_DesignVars,Info] = sdo.optimize(optimfcn,DesignVars,Options);
3-258
Design Optimization to Meet Frequency-Domain Requirements (Code)
Related Examples
To learn how to optimize the suspension system using the Response Optimization tool,
see "Design Optimization to Meet Frequency-Domain Requirements (GUI)".
3-259
4
Sensitivity Analysis
1 Sample the model parameters using experimental design principles. That is, for each
parameter, generate multiple values that the parameter can assume. Define the
parameter sample space by specifying probability distributions for each parameter.
You can also specify parameter correlations.
4-2
What Is Sensitivity Analysis?
For information about the analysis methods, see “Sensitivity Analysis Methods” on
page 4-11.
References
[1] Saltelli, A., Ratto, M., Andres, T., Campolongo, F., Cariboni, J., Gatelli, D., Saisana,
M., and Tarantola, S. Global Sensitivity Analysis. The Primer, John Wiley and
Sons, 2008.
See Also
sdo.analyze | sdo.evaluate | sdo.sample | sdo.scatterPlot
Related Examples
• “Design Exploration using Parameter Sampling (Code)” on page 4-20
• “Identify Key Parameters for Estimation (Code)” on page 4-36
More About
• “Sensitivity Analysis Methods” on page 4-11
• “Sampling Parameters for Sensitivity Analysis” on page 4-4
4-3
4 Sensitivity Analysis
Each model evaluation has a computational expense and can be time intensive.
Therefore, ideally, you want to use the smallest sample set that yields useful results. You
can use techniques such as design of experiments (DOE) (also referred to as experimental
design) to choose an efficient sample set for sensitivity analysis.
Use sdo.ParameterSpace to define the parameter space. This object specifies the
probability distributions and correlations for the parameters. Use this object as an input
to sdo.sample to generate samples from the specified parameter space.
Probability Distribution
Specify the probability distribution function that is best suited for each parameter.
Use your knowledge of the system (empirical or theoretical) to choose the probability
distribution for the parameter.
The Simulink Design Optimization software allows you to specify uniform (default) and
normal distributions. If you have a Statistics and Machine Learning Toolbox license, you
can also specify any univariate probability distribution that the toolbox provides.
4-4
Sampling Parameters for Sensitivity Analysis
Bounds
Specify the upper and lower bounds of the value of a parameter. These bounds define the
sampling range for the parameter. Use your knowledge of the parameter’s range of likely
values to choose the bounds.
To specify the bounds of a parameter, use the Minimum and Maximum properties of a
param.Continuous object. Use this updated param.Continuous object when you specify
the parameter space using an sdo.ParameterSpace object.
Number of Samples
Ideally, you want to use the smallest number of samples that yield useful results,
because each sample requires a model evaluation.
As the number of parameters increases, the number of samples needed to explore the
design space generally increases. For correlation or regression analysis, consider using
10Np samples, where Np is the number of parameters.
Method of Sampling
After specifying the probability distributions and bounds for the parameters, you
generate samples for the specified parameter space. You can specify the method used
to generate these samples using the Method property of an sdo.SampleOptions object.
Use this object as an input to sdo.sample to specify the sampling options. Specify the
sampling method as one of the following:
• 'random' — Random samples drawn from the probability distributions specified for
the parameters.
4-5
4 Sensitivity Analysis
• 'lhs' — Latin hypercube samples drawn from the probability distributions specified
for the parameters. Use this option for a more systematic space-filling approach
than random sampling. The following figure shows the difference between random
sampling and Latin hybercube design-based sampling.
The figure shows 8 samples for 2 parameters, drawn from a uniform distribution, in
the interval from 0 to 1. Random sampling can result in the clustering of samples (see
the top right-hand corner of the plot). Latin hypercube designs, with their stratified
approach to sampling, are better able to avoid such clustering.
You can use either a Gaussian copula (default) or a t copula. Specify the choice of
copula using the MethodOptions property of the sdo.SampleOptions object.
Use t copulas when the probability of extreme parameter values is not negligible.
You must specify the degrees of freedom for a t copula. As you increase the degrees
of freedom, the t copula converges to the Gaussian copula, and the probability of
4-6
Sampling Parameters for Sensitivity Analysis
extreme parameter values becomes negligible. The following figure shows 1000
samples drawn for 2 parameters, in the interval from 0 to 1, using the Gaussian and t
copulas.
In comparison to the Gaussian copula, the t copula has more samples that represent
the extreme values of the parameters.
You can specify the correlation type as either Spearman’s rank correlation or
Kendall’s rank correlation.
For the 'copula' method, you must also specify the value of the RankCorrelation
property of the sdo.ParameterSpace object that you use for sampling.
R = param.Continuous('R',10);
4-7
4 Sensitivity Analysis
Sample R in the 5% range of its nominal value. However, resistors of 1% tolerance are
removed. So, you do not need to sample R in the 1% range. You can use the following
approaches:
To visualize the samples and validate the sample space, use sdo.scatterPlot.
Use a customized probability distribution to configure the parameter space and generate
samples.
You can use tools provided by the Statistics and Machine Learning Toolbox software to
create customized probability distributions. For example,
pdR = makedist('PiecewiseLinear','x',x,'Fx',F);
4-8
Sampling Parameters for Sensitivity Analysis
The call to makedist specifies a piecewise linear distribution for the resistor value, with
a “hole” in the 1% range.
Specify pdR as the probability distribution for the R parameter when you create the
sdo.ParameterSpace object to define the parameter space.
ps = sdo.ParameterSpace(R,pdR);
Create a table of the custom samples. Specify one column for each parameter, and one
row for each sample. The column name must be the same as the parameter name.
For example:
Rval = R.Value;
4-9
4 Sensitivity Analysis
Ns = 1000;
x = table([linspace(.95*Rval,.99*Rval,Ns*.5) ...
linspace(1.01*Rval,1.05*Rval,Ns*.5)]','VariableNames',{'R'});
Consider another example, where you have two model parameters, A and B.
A = param.Continuous('A',1);
B = param.Continuous('B',10);
Vary A for the following values: 2,3,4. Vary B for the following values: 20,30,40. Generate
a table of samples for every combination of A and B.
Avals = [2 3 4];
Bvals = [20 30 40];
[Agrid,Bgrid] = meshgrid(Avals,Bvals);
x = table(Agrid(:),Bgrid(:),'VariableNames',{'A','B'});
See Also
sdo.SampleOptions | sdo.sample
Related Examples
• “Design Exploration using Parameter Sampling (Code)” on page 4-20
More About
• “What Is Sensitivity Analysis?” on page 4-2
4-10
Sensitivity Analysis Methods
Visual Analysis
Plot the cost function evaluations against the parameter samples to identify trends. This
method is informal and provides visual intuition about how the various parameters affect
the cost function.
• sdo.scatterPlot — Scatter plot of the parameter samples against the cost function
evaluation
• surf, mesh — 3-D plot of samples of two parameters against the cost function
evaluation
Quantitative Analysis
Obtain summary statistics using sdo.analyze. This function performs linear
correlation analysis by default. You can specify other analysis method(s) using an
sdo.AnalyzeOptions options object.
4-11
4 Sensitivity Analysis
• Linear analysis, also referred to as Pearson analysis — Uses raw data for analysis.
Best suited when you expect a linear relation between the parameters and cost
function.
• Ranked analysis, also referred to as Spearman analysis and ranked transformation —
Uses ranks of data for analysis. Best suited when you expect a nonlinear monotonic
relation between the parameters and the cost function.
For an example of ranked analysis, suppose you had the following data set:
x1 x2 y
9 20 340
5 60 106
2.3 50.4 870.5
Here x1 and x2 are model parameters, and y is the cost function. Each row represents
a sample and the associated cost function evaluation.
The data is ranked on a per column basis. For example, when you rank the data in
column 1 (x1), which contains the entries 9, 5, and 2.3, the ranked data is equal to 3, 2,
and 1. The ranked data set for the samples of x1, x2 and y are as follows:
x1 x2 y
3 1 2
2 3 1
1 2 3
4-12
Sensitivity Analysis Methods
The ranked data set can be used for correlation, partial correlation, or standardized
regression analysis.
Linear analysis retains information about intervals between data values, whereas
ranked analysis does not.
See Also
sdo.AnalyzeOptions | sdo.analyze | sdo.evaluate | sdo.sample
Related Examples
• “Identify Key Parameters for Estimation (Code)” on page 4-36
More About
• “What Is Sensitivity Analysis?” on page 4-2
4-13
4 Sensitivity Analysis
In this section...
“Configure Your System for Parallel Computing” on page 4-14
“Model Dependencies” on page 4-14
“Perform Sensitivity Analysis Using Parallel Computing (Code)” on page 4-15
“Troubleshooting” on page 4-16
When you call sdo.evaluate with the parallel computing option enabled, the software
uses the available parallel pool. If none is available, and Automatically create a
parallel pool is selected in your Parallel Computing Toolbox preferences, the software
starts a parallel pool using the settings in those preferences. To open a parallel pool that
uses a specific cluster profile, use:
parpool(MyProfile);
For information regarding creating a cluster profile, see “Create and Modify Cluster
Profiles” in the Parallel Computing Toolbox documentation.
Model Dependencies
Model dependencies are any referenced models, data such as model variables, S-
functions, or additional files necessary to run the model. Before starting the parallel
model evaluation, verify that the model dependencies are complete. Otherwise, you may
get unexpected results.
4-14
How to Use Parallel Computing for Sensitivity Analysis
When you use parallel computing, the Simulink Design Optimization software helps you
identify model dependencies. To do so, the software uses the Simulink Manifest Tools.
The dependency analysis may not find all the files required by your model. To learn
more, see “Scope of Dependency Analysis” in the Simulink documentation. If your model
has dependencies that are undetected or inaccessible by the parallel pool workers, then
add them to the list of model dependencies.
The dependencies are made accessible to the parallel pool workers by specifying one of
the following:
• File dependencies: the model dependency files are copied to the parallel pool workers.
• Path dependencies: the paths to the model dependencies are specified to the parallel
pool workers. If you are working in a multi-platform scenario, ensure that the paths
are compatible across platforms.
1 Ensure that the software can access parallel pool workers that use the appropriate
cluster profile.
For more information, see “Configure Your System for Parallel Computing” on page
4-14.
2 Open the model.
3 Specify the cost function and generate parameter samples for sensitivity analysis.
For example, see “Design Exploration using Parameter Sampling (Code)” on page
4-20.
4 Enable parallel computing using an evaluation option set.
opt = sdo.EvaluateOptions;
opt.UseParallel = 'always';
5 Find the model dependencies.
4-15
4 Sensitivity Analysis
[dirs,files] = sdo.getModelDependencies(modelname)
Note: If you do not want to copy the files to the remote workers, add any undetected
path dependencies to dirs and update the paths on local drives to make them
accessible to remote workers. See sdo.getModelDependencies for more details.
7 Add the file dependencies for evaluation.
opt.ParallelFileDependencies = files;
8 Specify the name of the model to be evaluated in parallel.
opt.EvaluatedModel = modelname;
9 Evaluate the model.
[pOpt,opt_info] = sdo.evaluate(fcn,samples,opt);
Troubleshooting
Why Don’t I See the Evaluation Speed up I Expected Using Parallel Computing?
When you evaluate a model that does not have a large number of evaluations or does not
take long to simulate, you might not see a speedup in the evaluation time. In such cases,
the overhead associated with creating and distributing the parallel tasks outweighs the
benefits of running the evaluation in parallel.
See Also
sdo.EvaluateOptions | parpool | sdo.evaluate | sdo.getModelDependencies
More About
• “Ways to Speed Up Design Optimization Tasks”
4-16
Use Fast Restart Mode During Sensitivity Analysis
Fast restart enables you to perform iterative simulations without compiling a model or
terminating the simulation each time. Using fast restart, you compile a model only once.
You can then tune parameters and simulate the model again without spending time on
compiling. Fast restart associates multiple simulation phases with a single compile phase
to make iterative simulations more efficient. You see a speedup of design optimization
tasks using fast restart in models that have a long compilation phase. See “How Fast
Restart Improves Iterative Simulations” in the Simulink documentation.
When you enable fast restart, you can only change tunable properties of the model during
simulation. For more information about the limitations, see “Factors Affecting Fast
Restart”.
You can use sensitivity analysis to evaluate which model parameters most influence a
cost function. You can use these parameters during parameter estimation or response
optimization. Suppose that you want to use sensitivity analysis to reduce the number of
parameters that you need to estimate to fit a model.
To evaluate the model in fast restart mode using a cost function aimed at parameter
estimation:
Store the measured input-output data in Exp. For an example, see “Identify Key
Parameters for Estimation (Code)” on page 4-36.
4 Create a model simulator from the experiment.
Simulator = createSimulator(Exp);
4-17
4 Sensitivity Analysis
Note: You must create a simulation scenario with logging information before
configuring the model for fast restart. You cannot modify logging information once
the model has been compiled for fast restart.
5 Configure the model and simulator for fast restart.
Simulator = fastRestart(Simulator,'on');
6 Create a cost function, myCostfcn, and pass Simulator to the cost function as
an input. For more information, see “Write a Cost Function” on page 2-83. In the
cost function, the simulator configured for fast restart is used to update the model
parameters, simulate the model, and log signals.
The fast restart workflow is similar for sensitivity analysis that identifies design
variables using a cost function aimed at response optimization. See “Use Fast Restart
Mode During Response Optimization” on page 3-227.
Troubleshooting
Why Don’t I See the Evaluation Speedup I Expected Using Fast Restart?
You see a speedup of design optimization tasks using fast restart in models that have a
long compilation phase. If the compilation phase of your model is not long, you do not see
a significant change in estimation speed.
See Also
fastRestart | sdo.evaluate | sdo.SimulationTest
Related Examples
• “Improving Optimization Performance using Fast Restart (GUI)” on page 2-198
4-18
Use Fast Restart Mode During Sensitivity Analysis
More About
• “Ways to Speed Up Design Optimization Tasks”
4-19
4 Sensitivity Analysis
You explore the CSTR design by characterizing design parameters using probability
distributions. You use the distributions to generate random samples in the design space
and perform Monte-Carlo evaluation of the design at these sample points. You then
create plots to visualize the design space and select the best design. You can then use the
best design as an initial guess for optimization of the design.
You can also use the sampled design space and Monte-Carlo evaluation output to analyze
the influence of design parameters on the design, see "Sensitivity Analysis for Parameter
Estimation (Code)"
Continuously Stirred Tank Reactors (CSTRs) are common in the process industry. The
Simulink model, sdoCSTR, models a jacketed diabatic (i.e., non-adiabatic) tank reactor
described in [1]. The CSTR is assumed to be perfectly mixed, with a single first-order
exothermic and irreversible reaction, . , the reactant, is converted to , the
product.
In this example, you use the following two-state CSTR model, which uses basic
accounting and energy conservation principles:
• and - Volumetric flow rate [m^3/h] and the density of the material in the CSTR
[1/m^3]
4-20
Design Exploration using Parameter Sampling (Code)
• and - Height [m] and heated cross-sectional area [m^2] of the CSTR.
• and - Heat capacity [kcal/K] and heat transfer coefficients [kcal/(m^2 * K * h)]
Assume that the CSTR is cylindrical, with the coolant applied to the base of the cylinder.
Tune the CSTR cross-sectional area, , and CSTR height, , to meet the following design
goals:
4-21
4 Sensitivity Analysis
• Minimize the mean coolant temperature . Heating or cooling the jacket coolant
temperature is expensive. Minimizing the mean coolant temperature improves CSTR
profit.
The design must allow for variations in the quality of supply feed concentration, ,
and feed temperature, . The CSTR is fed with feed from different suppliers. The
quality of the feed differs from supplier to supplier and also varies within each supply
batch.
• Cylinder height
p = sdo.getParameterFromModel('sdoCSTR',{'A','h'});
Create a parameter space for the design variables. The parameter space characterizes
the allowable parameter values and combinations of parameter values.
pSpace = sdo.ParameterSpace(p);
The parameter space uses default uniform distributions for the design variables. The
distribution lower and upper bounds are set to the design variable minimum and
maximum value respectively.
Use the sdo.sample function to generate samples from the parameter space. You use
the samples to evaluate the model and explore the design space.
rng default; % For reproducibility
4-22
Design Exploration using Parameter Sampling (Code)
pSmpl = sdo.sample(pSpace,30);
Use the sdo.scatterPlot command to visualize the sampled parameter space. The
scatter plot shows the parameter distributions on the diagonal subplots and pairwise
parameter combinations on the off diagonal subplots.
figure, sdo.scatterPlot(pSmpl)
Select the feed concentration and feed temperature as uncertain variables. You evaluate
the design using different values of feed temperature and concentration.
pUnc = sdo.getParameterFromModel('sdoCSTR',{'FeedCon0','FeedTemp0'});
4-23
4 Sensitivity Analysis
Create a parameter space for the uncertain variables. Use normal distributions for both
variables. Specify the mean as the current parameter value. Specify a variance of 5% of
the mean for the feed concentration and 1% of the mean for the temperature.
uSpace = sdo.ParameterSpace(pUnc);
uSpace = setDistribution(uSpace,'FeedCon0',makedist('normal',pUnc(1).Value,0.05*pUnc(1)
uSpace = setDistribution(uSpace,'FeedTemp0',makedist('normal',pUnc(2).Value,0.01*pUnc(2
The feed concentration is inversely correlated with the feed temperature. Add this
information to the parameter space.
The rank correlation matrix has a row and column for each parameter with the (i,j) entry
specifying the correlation between the i and j parameters.
Sample the parameter space. The scatter plot shows the correlation between
concentration and temperature.
uSmpl = sdo.sample(uSpace,60);
sdo.scatterPlot(uSmpl)
4-24
Design Exploration using Parameter Sampling (Code)
Ideally you want to evaluate the design for every combination of points in the design and
uncertain spaces, which implies 30*60 = 1800 simulations. Each simulation takes around
0.5 sec. You can use parallel computing to speed up the evaluation. For this example
you instead only use the samples that have maximum & minimum concentration and
temperature values, reducing the evaluation time to around 1 min.
[~,iminC] = min(uSmpl.FeedCon0);
[~,imaxC] = max(uSmpl.FeedCon0);
[~,iminT] = min(uSmpl.FeedTemp0);
[~,imaxT] = max(uSmpl.FeedTemp0);
uSmpl = uSmpl(unique([iminC,imaxC,iminT,imaxT]) ,:)
uSmpl =
4-25
4 Sensitivity Analysis
FeedCon0 FeedTemp0
________ _________
9.4555 303.58
11.175 288.13
11.293 290.73
8.9308 294.16
Create a function that evaluates the design for a given sample point in the design space.
The design is evaluated on how well it minimizes the variation in residual concentration
and mean coolant temperature.
Evaluating a point in the design space requires logging model signals. Logged signals are
used to evaluate the design requirements.
• CSTR concentration, available at the second output port of the sdoCSTR/CSTR block
Conc = Simulink.SimulationData.SignalLoggingInfo;
Conc.BlockPath = 'sdoCSTR/CSTR';
Conc.OutputPortIndex = 2;
Conc.LoggingInfo.NameMode = 1;
Conc.LoggingInfo.LoggingName = 'Concentration';
Create and configure a simulation test object to log the required signals.
simulator = sdo.SimulationTest('sdoCSTR');
simulator.LoggingInfo.Signals = [Conc,Coolant];
Evaluation Function
4-26
Design Exploration using Parameter Sampling (Code)
Use an anonymous function with one argument that calls the sdoCSTR_design function.
evalDesign = @(p) sdoCSTR_design(p,simulator,pUnc,uSmpl);
The sdoCSTR_design function uses a for loop that iterates through the sample values
specified for the feed concentration and temperature. Within the loop, the function:
• Simulates the model using the current design point, feed concentration, and feed
temperature values
4-27
4 Sensitivity Analysis
%Simulate model
simulator.Parameters = [p; pUnc];
simulator = sim(simulator);
logName = get_param('sdoCSTR','SignalLoggingName');
simLog = get(simulator.LoggedData,logName);
%%
% Add the individual cost terms to the return argument. These are not used
% by the optimizer, but included for convenience.
design.costConc = costConc;
design.costCoolant = costCoolant;
end
4-28
Design Exploration using Parameter Sampling (Code)
Evaluate
Use the sdo.evaluate command to evaluate the model at the sample design points.
y = sdo.evaluate(evalDesign,p,pSmpl);
View the results of the evaluation using a scatter plot. The scatter plot shows pairwise
plots for each design variable (A,h) and design cost. The plot include the total cost, F, as
well as coolant and concentration costs, costCoolant and costConc respectively.
sdo.scatterPlot(pSmpl,y);
4-29
4 Sensitivity Analysis
The plot shows that larger cross-sectional areas result in lower total costs. However it is
difficult to tell how the height influences the total cost.
Ftotal = scatteredInterpolant(pSmpl.A,pSmpl.h,y.F);
xR = linspace(min(pSmpl.A),max(pSmpl.A),60);
yR = linspace(min(pSmpl.h),max(pSmpl.h),60);
[xx,yy] = meshgrid(xR,yR);
zz = Ftotal(xx,yy);
mesh(xx,yy,zz)
view(56,30)
title('Total cost as function of A and h')
zlabel('Ftotal')
xlabel(p(1).Name), ylabel(p(2).Name);
4-30
Design Exploration using Parameter Sampling (Code)
The plot shows that high values of A and h result in lower costs. The best design in the
sampled space corresponds to the design with the lowest cost value.
[~,idx] = min(y.F);
pBest = [y(idx,:), pSmpl(idx,:)]
pBest =
F costConc costCoolant A h
______ ________ ___________ ______ ______
4-31
4 Sensitivity Analysis
The total cost surface plot shows that low cost designs are designs with A in the range
[1.5 2] and h in the range [2 3]. Modify the parameter space distributions for A and h and
resample the design space to focus on this region.
pSpace = setDistribution(pSpace,'A',makedist('uniform',1.5,2));
pSpace = setDistribution(pSpace,'h',makedist('uniform',2,3));
pSmpl = sdo.sample(pSpace,30);
Add the pBest found earlier to the new samples so that it is part of the refined design
space.
pSmpl = [pSmpl;pBest(:,4:5)];
sdo.scatterPlot(pSmpl)
4-32
Design Exploration using Parameter Sampling (Code)
y = sdo.evaluate(evalDesign,p,pSmpl);
Create a mesh plot for this section of the design space. The surface indicates that better
designs are near the A = 1.9, h = 2.1 point.
Ftotal = scatteredInterpolant(pSmpl.A,pSmpl.h,y.F);
xR = linspace(min(pSmpl.A),max(pSmpl.A),60);
yR = linspace(min(pSmpl.h),max(pSmpl.h),60);
[xx,yy] = meshgrid(xR,yR);
zz = Ftotal(xx,yy);
mesh(xx,yy,zz)
view(56,30)
title('Total cost as function of A and h')
zlabel('Ftotal')
xlabel(p(1).Name), ylabel(p(2).Name);
4-33
4 Sensitivity Analysis
Find the best design from the new design space and compare with the best design point
found earlier.
[~,idx] = min(y.F);
pBest = [pBest; [y(idx,:), pSmpl(idx,:)]]
pBest =
F costConc costCoolant A h
______ ________ ___________ ______ ______
4-34
Design Exploration using Parameter Sampling (Code)
The best design in the refined design space is better than the design found earlier. This
indicates that there may be better designs in the same region and warrants refining the
design space further. Alternatively you can use the best design point as an initial guess
for optimization.
Related Examples
To learn how to optimize the CSTR design using the sdo.optimize command, see
"Design Optimization with Uncertain Variables (Code)".
To learn how to analyze the influence of design parameters on the design using the
sdo.analyze command, see "Sensitivity Analysis for Parameter Estimation (Code)"
References
[1] Bequette, B.W. Process Dynamics: Modeling, Analysis and Simulation. 1st ed. Upper
Saddle River, NJ: Prentice Hall, 1998.
4-35
4 Sensitivity Analysis
Model Description
The vestibulo-ocular reflex (VOR) enables the eyes to move at the same speed and in the
opposite direction as the head, so that vision is not blurred when the head moves during
normal activity. For example, if the head turns in one direction, the eyes turn in the
opposite direction, with the same speed. This happens even in the dark. In fact, the VOR
is most easily characterized by measurements in the dark, to ensure that eye movements
are predominantly driven by the VOR.
The file sdoVOR_Data.mat contains uniformly sampled data of stimulation and eye
movements. If the VOR were perfectly compensatory, then a plot of eye movement data,
when flipped vertically, would overlay exactly on top of a plot of head motion data. Such
a system would be described by a gain of 1 and a phase of 180 degrees. However, when
we plot the data in the file sdoVOR_Data.mat, the eye movements are close, but not
perfectly compensatory.
4-36
Identify Key Parameters for Estimation (Code)
The eye movement data does not perfectly overlay the head motion data, and this can be
modeled by several factors. Head rotation is sensed by organs in the inner ears, known as
semicircular canals. These detect head motion and transmit signals about head motion
to the brain, which sends motor commands to the eye muscles, so that eye movements
compensate for head motion. We would like to use this eye movement data to estimate
the parameters in the models for these various stages. The model we will use is shown
below. There are four parameters in the model: Delay, Gain, Tc, and Tp.
model_name = 'sdoVOR';
open_system(model_name)
4-37
4 Sensitivity Analysis
The Delay parameter models the fact that there is some delay in communicating the
signals from the inner ear to the brain and the eyes. This delay is due to the time needed
for chemical neurotransmitters to traverse the synaptic clefts between nerve cells. Based
on the number of synapses involved in the vestibulo-ocular reflex, this delay is expected
to be around 5 ms. For estimation purposes, we will assume it is between 2 and 9 ms.
The Gain parameter models the fact that the the eyes do not move quite as much as the
head does. We will use 0.8 as our initial guess, and assume it is between 0.6 and 1.
The Tc parameter models the dynamics associated with the semicircular canals, as well
as some additional neural processing. The canals are high-pass filters, because after a
subject has been put into rotational motion, the neurally active membranes in the canals
slowly relax back to resting position, so the canals stop sensing motion. Thus in the plot
above, after the stimulation undergoes transition edges, the eye movements tend to
depart from the stimulation over time. Based on mechanical characteristics of the canals,
combined with additional neural processing which prolongs this time constant to improve
4-38
Identify Key Parameters for Estimation (Code)
the accuracy of the VOR, we will estimate the Tc parameter to be 15 seconds, and assume
it is between 10 and 30 seconds.
Tc = sdo.getParameterFromModel(model_name, 'Tc');
Tc.Value = 15;
Tc.Minimum = 10;
Tc.Maximum = 30;
Finally, the Tp parameter models the dynamics of the oculomotor plant, i.e. the eye and
the muscles and tissues attached to it. The plant can be modeled by two poles, however
it is believed that the pole with the larger time constant is cancelled by precompensation
in the brain, to enable the eye to make quick movements. Thus in the plot, when the
stimulation undergoes transition edges, the eye movements follow with only a little
delay. For the Tp parameter, we will use 0.01 seconds as our initial guess, and assume it
is between 0.005 and 0.05 seconds.
Tp = sdo.getParameterFromModel(model_name, 'Tp');
Tp.Value = 0.01;
Tp.Minimum = 0.005;
Tp.Maximum = 0.05;
Exp = sdo.Experiment(model_name);
Exp.InputData = timeseries(HeadData, Time);
EyeMotion = Simulink.SimulationData.Signal;
EyeMotion.Name = 'EyeMotion';
EyeMotion.BlockPath = [model_name '/Oculomotor Plant'];
EyeMotion.PortType = 'outport';
EyeMotion.PortIndex = 1;
EyeMotion.Values = timeseries(EyeData, Time);
Exp.OutputData = EyeMotion;
4-39
4 Sensitivity Analysis
stop_time = Time(end);
set_param(gcs, 'StopTime', num2str(stop_time));
dt = Time(2) - Time(1);
set_param(gcs, 'FixedStep', num2str(dt))
Create a simulation scenario using the experiment, and obtain the simulated output.
The model output does not match the data very well, as shown by the residual, which we
can compute by calling the objective function.
4-40
Identify Key Parameters for Estimation (Code)
type sdoVOR_Objective.m
4-41
4 Sensitivity Analysis
% Requirement setup
req = sdo.requirements.SignalTracking;
req.Type = '==';
req.Method = Method;
Sensitivity Analysis
4-42
Identify Key Parameters for Estimation (Code)
The sampling above used default options, and these are reflected in the plots above.
Parameter values were selected at random from distributions that were uniform over the
range of each parameter. Consequently, the histogram plots along the diagonal appear
approximately uniform. If Statistics and Machine Learning Toolbox™ is available, a
number of distributions may be used in addition to uniform and normal, and sampling
can be done in a Latin hypercube pattern.
The off-diagonal plots above show scatter plots between pairs of different variables.
Since we did not specify a RankCorrelation matrix in ps, the scatter plots do not indicate
correlations. However, if parameters were believed to be correlated, this can be specified
using the RankCorrelation property of ps.
4-43
4 Sensitivity Analysis
For sensitivity analysis, it is simpler to use a scalar objective, so we will specify the sum
of squared errors, "SSE":
estFcn = @(v) sdoVOR_Objective(v, Simulator, Exp, 'SSE');
y = sdo.evaluate(estFcn, ps, x);
Other types of analysis include correlation and, if Statistics and Machine Learning
Toolbox is available, partial correlation.
F
_________
Delay 0.01303
Gain -0.90873
Tc -0.044395
Tp 0.19919
For standardized regression, parameters that highly influence the model output have
sensitivity magnitudes close to 1. On the other hand, less influential parameters have
smaller sensitivity magnitudes. We see that this objective function is sensitive to changes
in the Gain and Tp parameters, but much less sensitive to changes in the Delay and Tc
parameters.
You can validate sensitivity analysis results by resampling and reevaluating the
objective function for the samples. You can also use engineering intuition for a quick
analysis. For example, in this model, the time constant Tc ranges from 10 to 30 seconds.
Even the minimum value of 10 seconds is large compared to the 2-second duration
for which the head motion stimulation is held at constant velocity. Therefore, Tc is
not expected to affect the output greatly. However, even when this kind of intuition
4-44
Identify Key Parameters for Estimation (Code)
is not readily available in other models, sensitivity analysis can help highlight which
parameters are influential.
Based on the results of sensitivity analysis, designate the Delay and Tc parameters
as fixed when optimizing. This reduction in the number of free parameters speeds up
optimization.
Delay.Free = false;
Tc.Free = false;
Optimization
We can use the minimum from sensitivity analysis as the initial guess for optimization.
[fval, idx_min] = min(y.F);
Delay.Value = x.Delay(idx_min);
Gain.Value = x.Gain(idx_min);
Tc.Value = x.Tc(idx_min);
Tp.Value = x.Tp(idx_min);
%
v = [Delay Gain Tc Tp];
opts = sdo.OptimizeOptions;
opts.Method = 'fmincon';
As was the case with model evaluations in sensitivity analysis, parallel computing could
be used to speed up the optimization.
vOpt = sdo.optimize(estFcn, v, opts);
disp(vOpt)
fmincon stopped because the size of the current step is less than
4-45
4 Sensitivity Analysis
the selected value of the step size tolerance and constraints are
satisfied to within the selected value of the constraint tolerance.
(1,1) =
Name: 'Delay'
Value: 0.0038
Minimum: 0.0020
Maximum: 0.0090
Free: 0
Scale: 0.0078
Info: [1x1 struct]
(1,2) =
Name: 'Gain'
Value: 0.9012
Minimum: 0.6000
Maximum: 1
Free: 1
Scale: 1
Info: [1x1 struct]
(1,3) =
Name: 'Tc'
Value: 16.6833
Minimum: 10
Maximum: 30
Free: 0
Scale: 16
Info: [1x1 struct]
(1,4) =
Name: 'Tp'
Value: 0.0157
Minimum: 0.0050
Maximum: 0.0500
Free: 1
Scale: 0.0156
4-46
Identify Key Parameters for Estimation (Code)
1x4 param.Continuous
Obtain the model response after estimation. Search for the model_residual signal in the
logged simulation data.
Comparing the measured eye data with the optimized model response shows that the
residuals are much smaller.
4-47
4 Sensitivity Analysis
4-48
5
If you have Control System Toolbox software installed, you can also design and optimize
control systems by tuning controller elements or parameters within a SISO Design Task
in the Control and Estimation Tools Manager. You can tune elements or parameters such
as poles, zeros, and gains within any controller in the system and optimize the open and
closed loop responses to meet time- and frequency-domain requirements.
Optimize the responses of systems in the SISO Design Task to meet both time- and
frequency-domain performance requirements by graphically constraining signals:
You can use optimization methods in a SISO Design Task in the Control and Estimation
Tools Manager to tune both command-line LTI models as well as Simulink models:
• Create an LTI model using the Control System Toolbox command-line functions
and use the controlSystemDesigner function to create a SISO Design Task for
the model. For an example, see “Optimize LTI System to Meet Frequency-Domain
Requirements” on page 5-44.
• Use a Simulink Compensator Design task (from Simulink Control Design software) to
automatically analyze the model and then create a SISO Design Task for a linearized
version of the model. You can then use the optimization techniques in the SISO
Design Task to tune the response of the linearized Simulink model. For an example,
see “Design Optimization-Based PID Controller for Linearized Simulink Model
(GUI)”.
Note: When using response optimization within a SISO Design Task you cannot add
uncertainty to system parameters.
When using a SISO Design Task, Simulink Design Optimization software automatically
sets the model's simulation start and stop time and you cannot directly change them.
5-2
Overview of Optimization-Based Compensator Design
By default, the simulation starts at 0 and continues until the SISO Design Task
determines that the dynamics of the model have settled out. In addition, when the design
requirements extend beyond this point, the simulation continues to the extent of the
design requirements. Although you cannot directly adjust the start or stop time of the
simulation, you can adjust the design requirements to extend further in time and thus
force the simulation to continue to a certain point.
5-3
5 Optimization-Based Control Design
In this section...
“Specify Piecewise-Linear Lower and Upper Bounds” on page 5-23
“Specify Step Response Characteristics” on page 5-13
“Track Reference Signals” on page 5-30
“Specify Custom Requirements” on page 5-32
“Edit Design Requirements” on page 5-35
1 In the Response Optimization tool, select Signal Bound in the New drop-down list.
A window opens where you specify upper or lower bounds on a signal.
2 Specify a requirement name in the Name box.
3 Select the requirement type using the Type list.
4 Specify the edge start and end times and corresponding amplitude in the Time (s)
and Amplitude columns.
5
Click to specify additional bound edges.
If you have already selected signals, as described in “Specify Signals to Log” on page
3-12, they appear in the list. Select the corresponding check-box.
a
Click . A window opens where you specify the logged signal.
b In the Simulink model window, click the signal to which you want to add a
requirement.
5-4
Time-Domain Design Requirements in Simulink
The window updates and displays the name of the block and the port number
where the selected signal is located.
c
Select the signal and click to add it to the signal set.
d In the Signal set box, enter a name for the selected signal set.
Click OK. A new variable, with the specified name, appears in the Data area of
the Response Optimization tool window.
7 Click OK.
A variable with the specified requirement name appears in the Data area of the tool.
A graphical display of the requirement also appears in the Response Optimization
tool window.
8 (Optional) In the graphical display, you can:
Alternatively, you can add a Check Custom Bounds block to your model to specify
piecewise-linear bounds.
5-5
5 Optimization-Based Control Design
1 You can apply this requirement to either a signal or a linearization of your model.
A window opens where you specify the step response requirements on a signal, or
system.
2 Specify a requirement name in the Name box.
3 Specify the step response characteristics:
% Overshoot
% Settling
Final Value
% Rise
Amplitude
% Undershoot
Initial Value
5-6
Time-Domain Design Requirements in Simulink
• Rise time: The time taken for the response signal to reach a specified percentage
of the step's range. The step's range is the difference between the final and initial
values.
• % Rise: The percentage used in the rise time.
• Settling time: The time taken until the response signal settles within a specified
region around the final value. This settling region is defined as the final step
value plus or minus the specified percentage of the final value.
• % Settling: The percentage used in the settling time.
• % Overshoot: The amount by which the response signal can exceed the final
value. This amount is specified as a percentage of the step's range. The step's
range is the difference between the final and initial values.
• % Undershoot: The amount by which the response signal can undershoot the
initial value. This amount is specified as a percentage of the step's range. The
step's range is the difference between the final and initial values.
4 Specify the signals or systems to be bound.
In the Select Signals to Bound area, select a logged signal to which you will
apply the requirement.
a
Click . A window opens where you specify the logged signal.
b In the Simulink model window, click the signal to which you want to add a
requirement.
5-7
5 Optimization-Based Control Design
The window updates and displays the name of the block and the port number
where the selected signal is located.
c
Select the signal and click to add it to the signal set.
d In the Signal set box, enter a name for the selected signal set.
Click OK. A new variable, with the specified name, appears in the Data area
of the Response Optimization tool window.
• Apply this requirement to a linear system.
Linear systems are defined by snapshot times at which the model is linearized
and sets of linearization I/O points defining the system inputs and outputs.
a Specify the simulation time at which the model is linearized using the
Snapshot Times box. For multiple simulation snapshot times, specify a
vector.
b Select the linearization input/output set from the Linearization I/O area.
5-8
Time-Domain Design Requirements in Simulink
For more information on using this dialog box, see “Create Linearization I/O
Sets” on page 3-77.
A variable with the specified requirement name appears in the Data area of the tool.
A graphical display of the requirement also appears in the Response Optimization
tool window.
Alternatively, you can use the Check Step Response Characteristics block to
specify step response bounds for a signal.
See Also
1 In the Response Optimization tool, select Signal Tracking in the New drop-down
list. A window opens where you specify the reference signal to track.
2 Specify a requirement name in the Name box.
3 Define the reference signal by entering vectors, or variables from the workspace, in
the Time vector and Amplitude fields.
Click Update reference signal data to use the new amplitude and time vector as
the reference signal.
4 Specify how the optimization solver minimizes the error between the reference and
model signals using the Tracking Method list:
5-9
5 Optimization-Based Control Design
a
Click . A window opens where you specify the logged signal.
b In the Simulink model window, click the signal to which you want to add a
requirement.
The window updates and displays the name of the block and the port number
where the selected signal is located.
c
Select the signal and click to add it to the signal set.
d In the Signal set box, enter a name for the selected signal set.
Click OK. A new variable, with the specified name, appears in the Data area of
the Response Optimization tool window.
e Select the check-box corresponding to the signal and click OK.
A variable with the specified requirement name appears in the Data area of the tool.
A graphical display of the signal bound also appears in the Response Optimization
tool window.
5-10
Time-Domain Design Requirements in Simulink
Note: When tracking a reference signal, the software ignores the maximally feasible
solution option. For more information on this option, see “Selecting Optimization
Termination Options” on page 3-74.
Alternatively, you can use the Check Against Reference block to specify a reference
signal to track.
See Also
1 In the Response Optimization tool, select Custom Requirement in the New list. A
window opens where you specify the custom requirement.
2 Specify a requirement name in the Name box.
3 Specify the requirement type using the Type list.
4 Specify the name of the function that contains the custom requirement in the
Function box. The field must be specified as a function handle using @. The function
If the function does not exist, clicking opens a template MATLAB file.
Use this file to implement the custom requirement. The default function name is
myCustomRequirement.
5 (Optional) If you want to prevent the solver from considering specific parameter
combinations, select the Error if constraint is violated check box. Use this option
for parameter-only constraints.
During an optimization iteration, the solver evaluates requirements with this option
selected first.
5-11
5 Optimization-Based Control Design
• If the constraint is not violated, the solver evaluates the remaining requirements
for the current iterate. If any of the remaining requirements bound signals or
systems, then the solver simulates the model .
For more information, see “Skip Model Simulation Based on Parameter Constraint
Violation (GUI)” on page 3-188.
Note: If you select this check box, then do not specify signals or systems to bound. If
you do specify signals or systems, then this check box is ignored.
6 (Optional) Specify the signal or system, or both, to be bound.
You can apply this requirement to model signals, or a linearization of your Simulink
model (requires Simulink Control Design software), or both.
Click Select Signals and Systems to Bound (Optional) to view the signal and
linearization I/O selection area.
In the Signal area, select a logged signal to which you will apply the
requirement.
a
Click . A window opens where you specify the logged signal.
b In the Simulink model window, click the signal to which you want to add a
requirement.
5-12
Time-Domain Design Requirements in Simulink
The window updates and displays the name of the block and the port number
where the selected signal is located.
c
Select the signal and click to add it to the signal set.
d In the Signal set box, enter a name for the selected signal set.
Click OK. A new variable, with the specified name, appears in the Data area
of the Response Optimization tool window.
• Apply this requirement to a linear system.
Linear systems are defined by snapshot times at which the model is linearized
and sets of linearization I/O points defining the system inputs and outputs.
a Specify the simulation time at which the model is linearized using the
Snapshot Times box. For multiple simulation snapshot times, specify a
vector.
b Select the linearization input/output set from the Linearization I/O area.
5-13
5 Optimization-Based Control Design
A new variable, with the specified name, appears in the Data area of the Response
Optimization tool. A graphical display of the requirement also appears in the
Response Optimization tool window.
See Also
The upper panel of the Edit Design Requirement dialog box resembles the image in the
following figure.
In the context of the SISO Tool in Control System Toolbox software, Design
requirement refers to both the particular editor within the SISO Tool that contains the
requirement and the particular requirement within that editor. To edit other constraints
within the SISO Tool, select another design requirement from the drop-down menu.
The particular parameters shown within the lower panel of the Edit Design Requirement
dialog box depend on the type of constraint/requirement. In some cases, the lower panel
contains a grid with one row for each segment and one column for each constraint
parameter. The following table summarizes the various constraint parameters.
5-14
Time-Domain Design Requirements in Simulink
5-15
5 Optimization-Based Control Design
In this section...
“Specify Lower Bounds on Gain and Phase Margin” on page 5-39
“Specify Piecewise-Linear Lower and Upper Bounds on Frequency Response” on page
5-41
“Specify Bound on Closed-Loop Peak Gain” on page 5-43
“Specify Lower Bound on Damping Ratio” on page 5-45
“Specify Upper and Lower Bounds on Natural Frequency” on page 5-47
“Specify Upper Bound on Approximate Settling Time” on page 5-49
“Specify Piecewise-Linear Upper and Lower Bounds on Singular Values” on page 5-51
“Specify Step Response Characteristics” on page 5-13
“Specify Custom Requirements” on page 5-32
1 In the Response Optimization tool, select Gain and Phase Margin in the New list.
A window opens where you specify lower bounds on the gain and phase margin of
your linear system.
2 Specify a requirement name in Name.
3 Specify bounds on the gain margin or phase margin, or both.
5-16
Frequency-Domain Design Requirements in Simulink
• Gain margin — Amount of gain increase or decrease required to make the loop
gain unity at the frequency where the phase angle is –180°.
• Phase margin — Amount of phase increase or decrease required to make the
phase angle –180° when the loop gain is 1.0
To specify a lower bound on the gain margin or phase margin, or both, select the
corresponding check box and enter the lower bound value.
4 In the Select Systems to Bound section, select the linear systems to which this
requirement applies.
Linear systems are defined by snapshot times at which the model is linearized and
sets of linearization I/O points defining the system inputs and outputs.
a Specify the simulation time at which the model is linearized using the
Snapshot Times box. For multiple simulation snapshot times, specify a vector.
b Select the linearization input/output set from the Linearization I/O area.
If you have already created a linearization input/output set, it will appear in the
list. Select the corresponding check box.
5-17
5 Optimization-Based Control Design
If you have not created a linearization input/output set, click to open the
Create linearization I/O set dialog box.
For more information on using this dialog box, see “Create Linearization I/O
Sets” on page 3-77.
A variable with the specified requirement name appears in the Data area of the tool.
A graphical display of the requirement also appears in the Response Optimization
tool window.
6 (Optional) In the graphical display, you can:
Alternatively, you can use the Check Gain and Phase Margins block to specify
bounds on the gain and phase margin. (Requires Simulink Control Design.)
1 In the Response Optimization tool, select Bode Magnitude in the New list. A
window opens where you specify the lower or upper bounds on the magnitude of the
system response.
2 Specify a requirement name in the Name box.
3 Specify the requirement type using the Type list.
4 Specify the edge start and end frequencies and corresponding magnitude in the
Frequency and Magnitude columns.
5 Insert or delete bound edges.
5-18
Frequency-Domain Design Requirements in Simulink
Linear systems are defined by snapshot times at which the model is linearized and
sets of linearization I/O points defining the system inputs and outputs.
a Specify the simulation time at which the model is linearized using the
Snapshot Times box. For multiple simulation snapshot times, specify a vector.
b Select the linearization input/output set from the Linearization I/O area.
If you have already created a linearization input/output set, it will appear in the
list. Select the corresponding check box.
If you have not created a linearization input/output set, click to open the
Create linearization I/O set dialog box.
For more information on using this dialog box, see “Create Linearization I/O
Sets” on page 3-77.
A new variable with the specified name appears in the Data area of the Response
Optimization tool window. A graphical display of the requirement also appears in the
Response Optimization tool window.
5-19
5 Optimization-Based Control Design
Alternatively, you can use the Check Bode Characteristics block to specify bounds
on the magnitude of the system response. (Requires Simulink Control Design.)
1 In the Response Optimization tool, select Closed-Loop Peak Gain in the New list.
A window opens where you specify an upper bound on the closed-loop peak gain of
the system.
2 Specify a requirement name in the Name box.
3 Specify the upper bound on the closed-loop peak gain in the Closed-Loop peak
gain box.
5-20
Frequency-Domain Design Requirements in Simulink
4 In the Select Systems to Bound section, select the linear systems to which this
requirement applies.
Linear systems are defined by snapshot times at which the model is linearized and
sets of linearization I/O points defining the system inputs and outputs.
a Specify the simulation time at which the model is linearized using the
Snapshot Times box. For multiple simulation snapshot times, specify a vector.
b Select the linearization input/output set from the Linearization I/O area.
If you have already created a linearization input/output set, it will appear in the
list. Select the corresponding check box.
If you have not created a linearization input/output set, click to open the
Create linearization I/O set dialog box.
For more information on using this dialog box, see “Create Linearization I/O
Sets” on page 3-77.
A new variable with the specified name appears in the Data area of the Response
Optimization tool window. A graphical display of the requirement also appears in the
Response Optimization tool window.
5-21
5 Optimization-Based Control Design
Alternatively, you can use the Check Nichols Characteristics block to specify
bounds on the magnitude of the system response. (Requires Simulink Control Design.)
1 In the Response Optimization tool, select Damping Ratio in the New list. A
window opens where you specify an upper bound on the damping ratio of the system.
2 Specify a requirement name in the Name box.
3 Specify the lower bound on the damping ratio in the Damping ratio box.
5-22
Frequency-Domain Design Requirements in Simulink
4 In the Select Systems to Bound section, select the linear systems to which this
requirement applies.
Linear systems are defined by snapshot times at which the model is linearized and
sets of linearization I/O points defining the system inputs and outputs.
a Specify the simulation time at which the model is linearized using the
Snapshot Times box. For multiple simulation snapshot times, specify a vector.
b Select the linearization input/output set from the Linearization I/O area.
If you have already created a linearization input/output set, it will appear in the
list. Select the corresponding check box.
If you have not created a linearization input/output set, click to open the
Create linearization I/O set dialog box.
For more information on using this dialog box, see “Create Linearization I/O
Sets” on page 3-77.
A new variable with the specified name appears in the Data area of the Response
Optimization tool. A graphical display of the requirement also appears in the
Response Optimization tool window.
5-23
5 Optimization-Based Control Design
Alternatively, you can use the Check Pole-Zero Characteristics block to specify a
bound on the damping ratio. (Requires Simulink Control Design.)
1 In the Response Optimization tool, select Natural Frequency in the New list. A
window opens where you specify a bound on the natural frequency of the system.
2 Specify a requirement name in the Name box.
5-24
Frequency-Domain Design Requirements in Simulink
3 Specify a lower or upper bound on the natural frequency in the Natural frequency
box.
4 In the Select Systems to Bound section, select the linear systems to which this
requirement applies.
Linear systems are defined by snapshot times at which the model is linearized and
sets of linearization I/O points defining the system inputs and outputs.
a Specify the simulation time at which the model is linearized using the
Snapshot Times box. For multiple simulation snapshot times, specify a vector.
b Select the linearization input/output set from the Linearization I/O area.
If you have already created a linearization input/output set, it will appear in the
list. Select the corresponding check box.
If you have not created a linearization input/output set, click to open the
Create linearization I/O set dialog box.
For more information on using this dialog box, see “Create Linearization I/O
Sets” on page 3-77.
A new variable with the specified name appears in the Data area of the Response
Optimization tool. A graphical display of the requirement also appears in the
Response Optimization tool window.
5-25
5 Optimization-Based Control Design
Alternatively, you can use the Check Pole-Zero Characteristics block to specify a
bound on the natural frequency. (Requires Simulink Control Design.)
1 In the Response Optimization tool, select Settling Time in the New list. A window
opens where you specify an upper bound on the approximate settling time of the
system.
2 Specify a requirement name in the Name box.
5-26
Frequency-Domain Design Requirements in Simulink
3 Specify the upper bound on the approximate settling time in the Settling time box.
4 In the Select Systems to Bound section, select the linear systems to which this
requirement applies.
Linear systems are defined by snapshot times at which the model is linearized and
sets of linearization I/O points defining the system inputs and outputs.
a Specify the simulation time at which the model is linearized using the
Snapshot Times box. For multiple simulation snapshot times, specify a vector.
b Select the linearization input/output set from the Linearization I/O area.
If you have already created a linearization input/output set, it will appear in the
list. Select the corresponding check box.
If you have not created a linearization input/output set, click to open the
Create linearization I/O set dialog box.
For more information on using this dialog box, see “Create Linearization I/O
Sets” on page 3-77.
A new variable with the specified name appears in the Data area of the Response
Optimization tool. A graphical display of the requirement also appears in the
Response Optimization tool window.
5-27
5 Optimization-Based Control Design
Alternatively, you can use the Check Pole-Zero Characteristics block to specify
the approximate settling time. (Requires Simulink Control Design.)
1 In the Response Optimization tool, select Singular Values in the New list. A
window opens where you specify the lower or upper bounds on the singular values of
the system.
2 Specify a requirement name in the Name box.
5-28
Frequency-Domain Design Requirements in Simulink
Linear systems are defined by snapshot times at which the model is linearized and
sets of linearization I/O points defining the system inputs and outputs.
a Specify the simulation time at which the model is linearized using the
Snapshot Times box. For multiple simulation snapshot times, specify a vector.
b Select the linearization input/output set from the Linearization I/O area.
If you have already created a linearization input/output set, it will appear in the
list. Select the corresponding check box.
If you have not created a linearization input/output set, click to open the
Create linearization I/O set dialog box.
For more information on using this dialog box, see “Create Linearization I/O
Sets” on page 3-77.
A new variable with the specified name appears in the Data area of the Response
Optimization tool. A graphical display of the requirement also appears in the
Response Optimization tool window.
5-29
5 Optimization-Based Control Design
Alternatively, you can use the Check Singular Value Characteristics block to
specify bounds on the singular value. (Requires Simulink Control Design.)
1 You can apply this requirement to either a signal or a linearization of your model.
5-30
Frequency-Domain Design Requirements in Simulink
A window opens where you specify the step response requirements on a signal, or
system.
2 Specify a requirement name in the Name box.
3 Specify the step response characteristics:
% Overshoot
% Settling
Final Value
% Rise
Amplitude
% Undershoot
Initial Value
5-31
5 Optimization-Based Control Design
• Settling time: The time taken until the response signal settles within a specified
region around the final value. This settling region is defined as the final step
value plus or minus the specified percentage of the final value.
• % Settling: The percentage used in the settling time.
• % Overshoot: The amount by which the response signal can exceed the final
value. This amount is specified as a percentage of the step's range. The step's
range is the difference between the final and initial values.
• % Undershoot: The amount by which the response signal can undershoot the
initial value. This amount is specified as a percentage of the step's range. The
step's range is the difference between the final and initial values.
4 Specify the signals or systems to be bound.
In the Select Signals to Bound area, select a logged signal to which you will
apply the requirement.
a
Click . A window opens where you specify the logged signal.
b In the Simulink model window, click the signal to which you want to add a
requirement.
5-32
Frequency-Domain Design Requirements in Simulink
The window updates and displays the name of the block and the port number
where the selected signal is located.
c
Select the signal and click to add it to the signal set.
d In the Signal set box, enter a name for the selected signal set.
Click OK. A new variable, with the specified name, appears in the Data area
of the Response Optimization tool window.
• Apply this requirement to a linear system.
Linear systems are defined by snapshot times at which the model is linearized
and sets of linearization I/O points defining the system inputs and outputs.
a Specify the simulation time at which the model is linearized using the
Snapshot Times box. For multiple simulation snapshot times, specify a
vector.
b Select the linearization input/output set from the Linearization I/O area.
5-33
5 Optimization-Based Control Design
For more information on using this dialog box, see “Create Linearization I/O
Sets” on page 3-77.
A variable with the specified requirement name appears in the Data area of the tool.
A graphical display of the requirement also appears in the Response Optimization
tool window.
Alternatively, you can use the Check Step Response Characteristics block to
specify step response bounds for a signal.
See Also
1 In the Response Optimization tool, select Custom Requirement in the New list. A
window opens where you specify the custom requirement.
2 Specify a requirement name in the Name box.
3 Specify the requirement type using the Type list.
4 Specify the name of the function that contains the custom requirement in the
Function box. The field must be specified as a function handle using @. The function
If the function does not exist, clicking opens a template MATLAB file.
Use this file to implement the custom requirement. The default function name is
myCustomRequirement.
5 (Optional) If you want to prevent the solver from considering specific parameter
combinations, select the Error if constraint is violated check box. Use this option
for parameter-only constraints.
During an optimization iteration, the solver evaluates requirements with this option
selected first.
5-34
Frequency-Domain Design Requirements in Simulink
For more information, see “Skip Model Simulation Based on Parameter Constraint
Violation (GUI)” on page 3-188.
Note: If you select this check box, then do not specify signals or systems to bound. If
you do specify signals or systems, then this check box is ignored.
6 (Optional) Specify the signal or system, or both, to be bound.
You can apply this requirement to model signals, or a linearization of your Simulink
model (requires Simulink Control Design software), or both.
Click Select Signals and Systems to Bound (Optional) to view the signal and
linearization I/O selection area.
In the Signal area, select a logged signal to which you will apply the
requirement.
a
Click . A window opens where you specify the logged signal.
b In the Simulink model window, click the signal to which you want to add a
requirement.
5-35
5 Optimization-Based Control Design
The window updates and displays the name of the block and the port number
where the selected signal is located.
c
Select the signal and click to add it to the signal set.
d In the Signal set box, enter a name for the selected signal set.
Click OK. A new variable, with the specified name, appears in the Data area
of the Response Optimization tool window.
• Apply this requirement to a linear system.
Linear systems are defined by snapshot times at which the model is linearized
and sets of linearization I/O points defining the system inputs and outputs.
a Specify the simulation time at which the model is linearized using the
Snapshot Times box. For multiple simulation snapshot times, specify a
vector.
b Select the linearization input/output set from the Linearization I/O area.
5-36
Frequency-Domain Design Requirements in Simulink
A new variable, with the specified name, appears in the Data area of the Response
Optimization tool. A graphical display of the requirement also appears in the
Response Optimization tool window.
See Also
5-37
5 Optimization-Based Control Design
Settling Time
If you specify a settling time in the continuous-time root locus, a vertical line appears on
the root locus plot at the pole locations associated with the value provided (using a first-
order approximation). In the discrete-time case, the constraint is a curved line.
It is required that Re{ pole} < -4 .6 / Tsettling for continuous systems and
log( abs( pole)) / Tdiscrete < -4 .6 / Tsettling for discrete systems. This is an approximation of
the settling time based on second-order dominant systems.
Percent Overshoot
Specifying percent overshoot in the continuous-time root locus causes two rays, starting
at the root locus origin, to appear. These rays are the locus of poles associated with
the percent value (using a second-order approximation). In the discrete-time case, the
constraint appears as two curves originating at (1,0) and meeting on the real axis in the
left-hand plane.
The percent overshoot p.o constraint can be expressed in terms of the damping ratio, as
in this equation:
5-38
Time- and Frequency-Domain Requirements in SISO Design Tool
2
p.o. = 100 e-pz / 1-z
Damping Ratio
Specifying a damping ratio in the continuous-time root locus causes two rays, starting
at the root locus origin, to appear. These rays are the locus of poles associated with
the damping ratio. In the discrete-time case, the constraint appears as curved lines
originating at (1,0) and meeting on the real axis in the left-hand plane.
The damping ratio defines a requirement on - Re{ pole} / abs( pole) for continuous
systems and on
r = abs( pSys)
t = angle( pSys)
Natural Frequency
If you specify a natural frequency, a semicircle centered around the root locus origin
appears. The radius equals the natural frequency.
The natural frequency defines a requirement on abs(pole) for continuous systems and on
r = abs( pSys)
t = angle( pSys)
Region Constraint
Specifies an exclusion region in the complex plane, causing a line to appear between the
two specified points with a shaded region below the line. The poles must not lie in the
shaded region.
5-39
5 Optimization-Based Control Design
You can specify an upper gain limit, which appears as a straight line on the Bode
magnitude curve. You must select frequency limits, the upper gain limit in decibels, and
the slope in dB/decade.
Specify the lower gain limit in the same fashion as the upper gain limit.
Phase Margin
While displayed graphically at only one location around a multiple of -180 degrees, this
requirement applies to phase margin regardless of actual phase (i.e., it is interpreted for
all multiples of -180).
Gain Margin
While displayed graphically at only one location around a multiple of -180 degrees, this
requirement applies to gain margin regardless of actual phase (i.e., it is interpreted for
all multiples of -180).
5-40
Time- and Frequency-Domain Requirements in SISO Design Tool
Specify a peak closed-loop gain at a given location. The specified value can be positive
or negative in dB. The constraint follows the curves of the Nichols plot grid, so it is
recommended that you have the grid on when using this feature.
While displayed graphically at only one location around a multiple of -180 degrees, this
requirement applies to gain margin regardless of actual phase (i.e., it is interpreted for
all multiples of -180).
Gain-Phase Requirement
Specifies an exclusion region for the response on the Nichols plot. The response must not
pass through the shaded region.
Related Examples
• “How to Design Optimization-Based Controllers for LTI Systems” on page 5-43
• “Optimize LTI System to Meet Frequency-Domain Requirements” on page 5-44
• “Design Optimization-Based PID Controller for Linearized Simulink Model (GUI)”
5-41
5 Optimization-Based Control Design
5-42
How to Design Optimization-Based Controllers for LTI Systems
1 Create and import a linear model into a SISO Design Task. You can create an LTI
model at the MATLAB command line, as described in “Creating an LTI Plant Model”
on page 5-45.
2 Create a SISO Design Task with design and analysis plots, as described in “Creating
Design and Analysis Plots” on page 5-46.
To learn more about SISO Design Tool, see “Using the SISO Design Task in
the Controls & Estimation Tools Manager” in the Control System Toolbox
documentation.
3 Under Automated Tuning select Optimization based tuning as the Design
Method and then click the Optimize Compensators button to create a Response
Optimization task within the Control and Estimation Tools Manager. See
“Creating a Response Optimization Task” on page 5-48 for more information.
4 Within the Response Optimization node, select the Compensators pane to select
and configure the compensator elements you want to tune during the response
optimization. See “Selecting Tunable Compensator Elements” on page 5-50 for
more information.
Note: Compensator elements or parameters cannot have uncertainty when used with
frequency-domain based response optimization.
5 Under Design requirements in the Response Optimization node, select
the design requirements you want the system to satisfy. See “Adding Design
Requirements” on page 5-51 for more information.
6 Click the Start Optimization button within the Response Optimization node.
The optimization progress results appear under Optimization. The Compensators
pane contains the new, optimized compensator element values. See “Optimizing the
System's Response” on page 5-59 for more information.
5-43
5 Optimization-Based Control Design
In this section...
“Introduction” on page 5-44
“Design Requirements” on page 5-44
“Creating an LTI Plant Model” on page 5-45
“Creating Design and Analysis Plots” on page 5-46
“Creating a Response Optimization Task” on page 5-48
“Selecting Tunable Compensator Elements” on page 5-50
“Adding Design Requirements” on page 5-51
“Optimizing the System's Response” on page 5-59
“Creating and Displaying the Closed-Loop System” on page 5-62
Introduction
When you have Control System Toolbox software, you can place Simulink Design
Optimization design requirements or constraints on plots in the SISO Design Tool
graphical tuning editor and analysis plots that are part of a SISO Design Task. This
allows you to include design requirements for response optimization in the frequency-
domain in addition to the time-domain. This topic guides you through an example using
frequency-domain design requirements to optimize the response of a system in the SISO
Design Task.
You can specify frequency-domain design requirements to optimize response signals for
any model that you can design within a SISO Design Task:
• Command-line LTI models created with the Control System Toolbox commands
• Simulink models that have been linearized using Simulink Control Design software
Design Requirements
In this example, you use a linearized version of the following Simulink model.
5-44
Optimize LTI System to Meet Frequency-Domain Requirements
You use optimization methods to design a compensator so that the closed loop system
meets the following design specifications when you excite the system with a unit step
input:
You want to design the compensator for the open loop transfer function of the linearized
srotut1 model. The linearized srotut1 plant model is composed of the gain, an
unlimited integrator, the transfer function, and a Padé approximation to the transport
delay.
To create an open loop transfer function based on the linearized srotut1 model, enter
the following commands:
w0 = 1;
zeta = 1;
Kint = 0.5;
Tdelay = 1;
[delayNum,delayDen] = pade(Tdelay,1);
integrator = tf(Kint,[1 0]);
transfer_fcn = tf(w0^2,[1 2*w0*zeta w0^2]);
delay_block = tf(delayNum,delayDen);
open_loopTF = integrator*transfer_fcn*delay_block;
If the plant model is an array of models, the controller is designed for a nominal model
only but you can analyze the control design for the remaining models in the array. For
5-45
5 Optimization-Based Control Design
more information, see “Control Design Analysis of Multiple Models” in the Control
System Toolbox documentation.
Tip You can directly linearize the Simulink model using Simulink Control Design
software.
controlSystemDesigner('rlocus',open_loopTF)
A SISO Design Task is created within the Control and Estimation Tools Manager, as
shown in the following figure.
5-46
Optimize LTI System to Meet Frequency-Domain Requirements
The Control and Estimation Tools Manager is a graphical environment for managing
and performing tasks such as designing SISO systems. The SISO Design Task node
contains five panels that perform actions related to designing SISO control systems. For
more information, see “Using the SISO Design Task in the Controls & Estimation Tools
Manager” in Control System Toolbox documentation.
The Architecture pane, within the SISO Design Task node, lets you choose the
architecture for the control system you are designing. This example uses the default
architecture. In this system, the plant model, G, is the open loop transfer function
open_loopTF, the prefilter, F, and the sensor, H, are set to 1, and the compensator, C, is
the compensator that will be designed using response optimization methods.
The SISO Design Task also contains a root locus diagram in the SISO Design Tool
graphical tuning editor.
5-47
5 Optimization-Based Control Design
In addition to the root-locus diagram, it is helpful to visualize the response of the system
with a step response plot. To add a step response:
1 Select the Analysis Plots pane with the SISO Design Task node of the Control
and Estimation Tool Manager.
2 Select Step for the Plot Type of Plot 1.
3 Under Contents of Plots, select the check box in column 1 for the response Closed
Loop r to y.
A step response plot appears in an Linear System Analyzer. The plot shows the response
of the closed loop system from r (input to the prefilter, F) to y (output of the plant model,
G):
5-48
Optimize LTI System to Meet Frequency-Domain Requirements
and analysis plots as discussed in “Creating Design and Analysis Plots” on page 5-46,
you are ready to start a response optimization task to design the compensator.
1 Select the Automated Tuning pane within the SISO Design Task node in the
Control and Estimation Tools Manager.
2 In the Automated Tuning pane, select Optimization based tuning as the
Design Method.
3 Click the Optimize Compensators button to create the Response Optimization
node under the SISO Design Task node in the tree browser in the left pane of the
Control and Estimation Tools Manager.
The Response Optimization node contains four panes as shown in the next figure.
5-49
5 Optimization-Based Control Design
With the exception of the first pane, each corresponds to a step in the response
optimization process:
Note: When optimizing responses in a SISO Design Task, you cannot add uncertainty to
parameters or compensator elements.
In this example, to tune the Gain in the compensator C, select the check box next to
this element, as shown in the following figure.
5-50
Optimize LTI System to Meet Frequency-Domain Requirements
Note: Compensator elements or parameters cannot have uncertainty when used with
frequency-domain based response optimization.
5-51
5 Optimization-Based Control Design
This example uses the design specifications described in “Design Requirements” on page
5-44. The following sections each create a new design requirement to meet these
specifications:
After you add the design requirements, you can select a subset of requirements for
controller design, as described in “Selecting the Design Requirements to Use During
Response Optimization” on page 5-59.
The first design specification for this example is to have a settling time of 30 seconds or
less. This specification can be represented on a root-locus diagram as a constraint on the
real parts of the poles of the open loop system.
1 Select the Design requirements pane within the Response Optimization node of
the Control and Estimation Tools Manager.
2 Click the Add new design requirement button. This opens the New Design
Requirement dialog box.
Within this dialog box you can specify new design requirements and add them to a
new or existing design or analysis plot.
3 Add a design requirement to the existing root-locus diagram:
A vertical line should appear on the root-locus diagram, as shown in the following
figure.
5-52
Optimize LTI System to Meet Frequency-Domain Requirements
The second design specification for this example is to have a percentage overshoot of
10% or less. This specification is related to the damping ratio on a root-locus diagram.
In addition to adding a design requirement with the Add new design requirement
button, you can also right-click directly on the design or analysis plots to add the
requirement, as shown next.
1 Right-click anywhere within the white space of the root-locus diagram in the SISO
Design Tool window. Select Design Requirements > New to open the New Design
Requirement dialog box.
5-53
5 Optimization-Based Control Design
2 Select Percent overshoot as the Design requirement type and enter 10 as the
Percent overshoot.
3 Click OK to add the design requirement to the root-locus diagram. The design
requirement appears as two lines radiating at an angle from the origin, as shown in
the following figure.
The third design specification for this example is to have a rise time of 10 seconds or less.
This specification is related to a lower limit on a Bode Magnitude diagram.
5-54
Optimize LTI System to Meet Frequency-Domain Requirements
1 Select the Graphical Tuning pane in the SISO Design Task node of the Control
and Estimation Tools Manager.
2 For Plot 2, set Plot Type to Open-Loop Bode.
3 Right-click anywhere within the white space of the open-loop bode diagram in the
SISO Design Tool window. Select Design Requirements > New to open the New
Design Requirement dialog box.
4 Create a design requirement to represent the rise time and add it to the new Bode
plot:
a Select Lower gain limit from the Design requirement type menu.
b Enter 1e-2 to 0.17 for the Frequency range.
c Enter 0 to 0 for the Magnitude range.
d Click OK.
A Bode diagram appears within the SISO Design Tool window. The magnitude plot
of the Bode diagram includes a horizontal line representing the design requirement,
as shown in the following figure.
5-55
5 Optimization-Based Control Design
The fourth design specification for this example is to limit the actuator signal to within
±0.7. To add this design requirement:
1 Select the Design requirements pane in the Response Optimization node of the
Control and Estimation Tools Manager.
2 Click the Add new design requirement button to open the New Design
Requirement dialog box.
3 Create a time-domain design requirement to represent the upper limit on the
actuator signal, and add it to a new step response plot in the Linear System
Analyzer:
5-56
Optimize LTI System to Meet Frequency-Domain Requirements
To add the corresponding design requirement for the lower limit on the actuator signal:
5-57
5 Optimization-Based Control Design
1 Select the Design requirements pane in the Response Optimization node of the
Control and Estimation Tools Manager.
2 Click the Add new design requirement button to open the New Design
Requirement dialog box.
3 Create a time-domain design requirement to represent the lower limit on the
actuator signal, and add it to the step response plot in the Linear System Analyzer:
5-58
Optimize LTI System to Meet Frequency-Domain Requirements
The design requirements give constraints on the dynamics of the system and the
values of response signals. The table in the Design requirements tab lists all design
requirements in the design and analysis plots. Select the check boxes next to the design
requirements you want to use in the response optimization. This example uses all the
current design requirements.
The Optimization pane within the Response Optimization node of the Control and
Estimation Tools Manager displays the progress of the response optimization. The pane
5-59
5 Optimization-Based Control Design
also contains options to configure the types of progress information displayed during the
optimization and options to configure the optimization methods and algorithms.
To optimize the response of the system in this example, click the Start Optimization
button.
The Optimization pane displays the progress of the optimization, iteration by iteration,
as shown next. Termination messages from the optimization method and suggestions for
improving convergence also appear here.
The optimized signals in the design and analysis plots appear as follows:
5-60
Optimize LTI System to Meet Frequency-Domain Requirements
5-61
5 Optimization-Based Control Design
1 Within the SISO Design Tool window, select File > Export to open the SISO Tool
Export dialog box.
2 Select the compensator you designed, Compensator C, and then click the Export
to Workspace button.
At the command line, enter the following command to create the closed-loop system, CL,
from the open-loop transfer function, open_loopTF, and the compensator, C:
CL=feedback(C*open_loopTF,1)
5-62
Optimize LTI System to Meet Frequency-Domain Requirements
To create a step response plot of the closed loop system, enter the following command:
step(CL);
5-63
5 Optimization-Based Control Design
You can use Simulink Control Design software to configure SISO Design Tool with
compensators, inputs, outputs, and loops computed from a Simulink model. For
more information, see “Creating a SISO Design Task” in Simulink Control Design
documentation.
After you configure the SISO Design Tool, use Simulink Design Optimization software to
optimize the controller parameters of the linearized Simulink model. For an example of
optimization-based control design for a model linearized using Simulink Control Design
software, see “Design Optimization-Based PID Controller for Linearized Simulink Model
(GUI)”.
There is only one difference when tuning compensators derived from Simulink Control
Design software: The tuning of compensators from a Simulink model is done through
the masks of the Simulink blocks representing each compensator. When selecting
parameters to optimize, users can tune the compensator in the pole, zero, or gain format,
or in a format consistent with the Simulink block mask as shown in the following figure.
Changing the compensator format is not possible when optimizing pure SISO Tool
models (those not derived using Simulink Control Design software).
5-64
Designing Linear Controllers for Simulink Models
5-65
5 Optimization-Based Control Design
5-66
6
Lookup Tables
After you create a lookup table using the input and output measurements as described
previously, you can use the corresponding multidimensional array of values in
applications without having to remeasure the system outputs. In fact, you need only
the input data to locate the appropriate array elements in the lookup table because the
software reads the approximate system output from the data stored at these locations.
Therefore, a lookup table provides a suitable means of capturing the input-output
mapping of a static system in the form of numeric data stored at predetermined array
locations.
6-2
What are Adaptive Lookup Tables?
physical system. Conversely, the behavior of actual physical systems often varies with
time due to wear, environmental conditions, and manufacturing tolerances. With such
variations, the static mapping of input-output behavior of a plant described by the lookup
table may no longer provide a valid representation of the plant characteristics.
Adaptive lookup tables incorporate the time-varying behavior of physical plants into the
lookup table generation and maintenance process while providing all of the functionality
of a regular lookup table.
The adaptive lookup table receives the input and output measurements of a plant's
behavior, which are then used to dynamically create and update the content of the
underlying lookup table. In addition to requiring the input data to create the lookup
table, the adaptive lookup table also uses the output data of the plant to recalculate the
table values. For example, you can collect the output data of the plant by placing sensors
at appropriate locations in a physical system.
The software uses the input measurements to locate the array elements by comparing
these input values with the breakpoints defined for each indexing variable. Next, it
uses the output measurements to recalculate the numeric value stored at these array
locations. However, unlike a regular table, which only stores the array data before the
actual use of the lookup table, the adaptive table continuously improves the content of
the lookup table. This continuous improvement of the table data is referred to as the
adaptation process or learning process.
The adaptation process involves statistical and signal processing algorithms to recapture
the input-output behavior of the plant. The adaptive lookup table always tries to provide
a valid representation of the plant dynamics even though the plant behavior may be time
varying. The underlying signal processing algorithms are also robust against reasonable
measurement noise and they provide appropriate filtering of noisy output measurements.
See Also
Adaptive Lookup Table (1D Stair-Fit) | Adaptive Lookup Table (2D
Stair-Fit) | Adaptive Lookup Table (nD Stair-Fit)
Related Examples
• “Model Engine Using n-D Adaptive Lookup Table” on page 6-45
More About
• “About Lookup Table Blocks”
6-3
6 Lookup Tables
6-4
How to Estimate Lookup Table Values
Related Examples
• “Estimate Lookup Table Values from Data” on page 6-23
• “Estimate Constrained Values of a Lookup Table” on page 6-6
6-5
6 Lookup Tables
Objectives
This example shows how to estimate constrained values of a lookup table. Apply
monotonically increasing constraints to the lookup table output values, and use the
Parameter Estimation tool to estimate the table values.
• xdata1 — Input data consisting of 602 uniformly sampled data points in the range
[-5,5].
• ydata1 — Output data corresponding to the input data samples.
• time1 — Time vector.
Use the I/O data to estimate monotonically increasing output values of the lookup table
in the lookup_increasing Simulink model.
This command opens the Simulink model, and loads the estimation data in the
MATLAB workspace.
6-6
Estimate Constrained Values of a Lookup Table
2 View the table output values by double-clicking the Lookup Table block.
The table contains 11 output values at breakpoints [-5:5], specified in the Function
Block Parameters dialog box. To learn more about how to specify the table values,
see “Enter Breakpoints and Table Data” in the Simulink documentation.
6-7
6 Lookup Tables
The Table data field shows that the table output values are the cumulative sum
of the values stored in variable ydelta. Thus, if yn are the 11 table output values,
ydelta is (y1, y2–y1, y3–y2, ..., y11–y10). The initial ydelta values are loaded from
lookup_increasing.mat.
The initial table output values are not monotonically increasing. To ensure
monotonically increasing table output values, the difference between adjacent
table output values should be positive. To do so, estimate ydelta in the
Parameter Estimation tool using the measured I/O estimation data, and constrain
ydelta(2:end) to be positive during estimation.
In the Simulink model, select Analysis > Parameter Estimation to open a session
with the name lookup_increasing in the Parameter Estimation tool.
6-8
Estimate Constrained Values of a Lookup Table
6-9
6 Lookup Tables
3 Run an initial simulation to view the measured data, simulated model values, and
the initial table values by typing the following commands at the MATLAB prompt.
sim('lookup_increasing')
figure(1); plot(xdata1,ydata1,'m*',xout,yout,'b^')
hold on; plot(-5:5,cumsum(ydelta),'k','LineWidth',2)
xlabel('Input Data'); ylabel('Output Data');
legend('Measured data','Initial simulated data','Initial table output')
6-10
Estimate Constrained Values of a Lookup Table
The initial table output values and simulated data do not match the measured data.
4 Select parameter for estimation.
On the Parameter Estimation tab, click Select Parameters. The Edit: Estimated
Parameters dialog box opens. In the Parameters Tuned for all Experiments
panel, click Select parameters to open the Select Model Variables dialog box.
Check the box next to ydelta, and click OK.
6-11
6 Lookup Tables
The ydelta values are selected for estimation by default in the Edit: Estimated
Parameters dialog box.
6-12
Estimate Constrained Values of a Lookup Table
5 Apply a monotonically increasing constraint on the table output values. For more
details about the table, see “Lookup Table Output” on page 6-6.
In the Edit: Estimated Parameters dialog box, click the arrow next to the
ydelta values. In the expanded menu, set Minimum ydelta values to [-
Inf,zeros(1,10)]. Thus, while the first value in ydelta can by anything,
subsequent values which are the difference between adjacent table output values,
must be positive.
6-13
6 Lookup Tables
The Parameter Trajectory plot shows the change in the parameter values at each
iteration.
6-14
Estimate Constrained Values of a Lookup Table
The Estimation Progress Report shows the iteration number, number of times the
objective function is evaluated, and value of the cost function at the end of each
iteration.
6-15
6 Lookup Tables
6-16
Estimate Constrained Values of a Lookup Table
The estimated ydelta(2:end) values are positive. Thus, the output of the table,
which is the cumulative sum of the values stored in ydelta, is monotonically
increasing.
• Residuals plot
• Measured and simulated data plots
1 Create an experiment to use for validation and import the validation I/O data.
6-17
6 Lookup Tables
On the Validation tab, click Select Results to Validate. Clear Use current
parameter values, select EstimatedParams, and click OK.
6-18
Estimate Constrained Values of a Lookup Table
The Parameter Estimation tool displays the experiment plot after validation by
default. Add the residuals plot by selecting the corresponding box on the Validation
tab.
Click Validate.
5 Examine the plots.
a The experiment plot shows the data simulated using estimated parameters
agrees with the measured validation data.
6-19
6 Lookup Tables
6-20
Estimate Constrained Values of a Lookup Table
The residuals, which show the difference between the simulated and measured
data, lie within 15% of the maximum output variation. This indicates a good
match between the measured and simulated table data values.
c Plot and examine the validation data, simulated data, and estimated table
values.
sim('lookup_increasing')
figure(2); plot(xdata2,ydata2,'m*',xout,yout,'b^')
hold on; plot(-5:5,cumsum(ydelta),'k','LineWidth', 2)
xlabel('Input Data'); ylabel('Output Data');
legend('Validation data','Simulated data','Table output values');
6-21
6 Lookup Tables
The table output values match both the measured data and the simulated table
values. The table output values cover the entire range of input values, which
indicates that all the lookup table values have been estimated.
Related Examples
• “Estimate Lookup Table Values from Data” on page 6-23
6-22
Estimate Lookup Table Values from Data
Objectives
This example shows how to estimate lookup table values from time-domain input-output
(I/O) data.
Use the I/O data to estimate the lookup table values in the lookup_regular Simulink
model. The lookup table in the model contains ten values, which are stored in the
MATLAB variable table. The initial table values comprise a vector of 0s. To learn more
about how to model a system using lookup tables, see “Guidelines for Choosing a Lookup
Table” in the Simulink documentation.
1 Open the lookup table model by typing the following command at the MATLAB
prompt:
6-23
6 Lookup Tables
lookup_regular
This command opens the Simulink model, and loads the estimation data into the
MATLAB workspace.
2 In the Simulink model, select Analysis > Parameter Estimation to open a new
session with name lookup_regular in the Parameter Estimation tool.
6-24
Estimate Lookup Table Values from Data
6-25
6 Lookup Tables
2 Run an initial simulation to view the I/O data, simulated output, and the initial
table values. To do so, type the following commands at the MATLAB prompt:
sim('lookup_regular')
figure(1); plot(xdata1,ydata1, 'm*', xout, yout,'b^')
hold on; plot(linspace(0,6.5,10), table, 'k', 'LineWidth', 2);
legend('Measured data','Initial simulation data','Initial table values');
6-26
Estimate Lookup Table Values from Data
The x-axis and y-axis of the figure represent the input and output data, respectively.
The figure shows the following plots:
You can see that the initial table values and simulated data do not match with the
measured data.
3 To select the table values to estimate, on the Parameter Estimation tab, click the
Select Parameters button to open the Edit:Estimated Parameters dialog. In
the Parameters Tuned for all Experiments panel, click Select parameters to
launch the Select Model Variables dialog. Check the box next to table, and click OK.
6-27
6 Lookup Tables
The Edit:Estimated Parameters window now looks as follows. The table values
are selected for estimation by default.
6-28
Estimate Lookup Table Values from Data
6-29
6 Lookup Tables
5 To estimate the table values using the default settings, on the Parameter
Estimation tab, click Estimate to open the Parameter Trajectory plot and
Estimation Progress Report window. The Parameter Trajectory plot shows the
change in the parameter values at each iteration.
After the estimation converges, the Parameter Trajectory plot looks like this:
6-30
Estimate Lookup Table Values from Data
The Estimation Progress Report shows the iteration number, number of times
the objective function is evaluated, and the value of the cost function at the end of
each iteration. After the estimation converges, the Estimation Progress Report
looks like this:
6-31
6 Lookup Tables
6-32
Estimate Lookup Table Values from Data
This report includes the estimated parameter values, the final value of the cost
function, and other optimization results. You can see that the optimization stopped
when the size of the gradient, 1.18e-14 was less than the criteria value, 1e-3.
• Residuals plot
• Measured and simulated data plots
6-33
6 Lookup Tables
3 To select results to use, on the Validation tab, click Select Results to Validate.
Deselect Use current parameter values and select EstimatedParams, and
click OK.
6-34
Estimate Lookup Table Values from Data
4 The Parameter Estimation tool, by default, displays the experiment plot after
validation. Add the residuals plot by checking the corresponding box on the
Validation tab.
a Experiment plot
6-35
6 Lookup Tables
You can see that the data simulated using the estimated parameters agrees with
the measured validation data.
b Click Residual plot: ValidationData to open the residuals plot.
6-36
Estimate Lookup Table Values from Data
The residuals, which show the difference between the simulated and measured
data, lie in the range [-0.15,0.15]— within 15% of the maximum output
variation. This indicates a good match between the measured and the simulated
table data values.
c Plot and examine the estimated table values against the validation data set and
the simulated table values by typing the following commands at the MATLAB
prompt.
sim('lookup_regular')
figure(2); plot(xdata2,ydata2, 'm*', xout, yout,'b^')
hold on; plot(linspace(0,6.5,10), table, 'k', 'LineWidth', 2)
6-37
6 Lookup Tables
The plot shows that the table values, displayed as the black line, match both
the validation data and the simulated table values. The table data values cover
the entire range of input values, which indicates that all the lookup table values
have been estimated.
Related Examples
• “Estimate Constrained Values of a Lookup Table” on page 6-6
6-38
Building Models Using Adaptive Lookup Table Blocks
Note: Use the Adaptive Lookup Table (nD Stair-Fit) block to create lookup tables of
three or more dimensions.
6-39
6 Lookup Tables
By default, the Adaptive Lookup Table blocks have two inputs and outputs. You can
display additional inputs and outputs in a block by selecting the corresponding options in
the Function Block Parameters dialog box. To learn more about the options, see the block
reference pages.
The 2-D Adaptive Lookup Table block has the following inputs and outputs:
• u and y — Input and output data of the system being modeled, respectively.
6-40
Building Models Using Adaptive Lookup Table Blocks
For example, to model an engine's efficiency as a function of engine rpm and manifold
pressure, specify u as the rpm, y as the pressure, and y as the efficiency signals.
• Tin — The initial table data.
• Enable — Signal to enable, disable, or reset the adaptation process.
• Lock — Signal to update only specified cells in the table.
• y — Value of the cell currently being adapted.
• N — Number of the cell currently being adapted.
• Tout — Values of the adapted table data.
For more information on how to use adaptive lookup tables, see “Model Engine Using n-D
Adaptive Lookup Table” on page 6-45.
A typical Simulink diagram using an adaptive lookup table block is shown in the next
figure.
In this figure, the Experiment Data block imports a set of experimental data into
Simulink through MATLAB workspace variables. The initial table is specified in the
block mask parameters. When the simulation runs, the initial table begins to adapt to
new data inputs and the resulting table is copied to the block's output.
See Also
Adaptive Lookup Table (1D Stair-Fit) | Adaptive Lookup Table (2D
Stair-Fit) | Adaptive Lookup Table (nD Stair-Fit)
Related Examples
• “Model Engine Using n-D Adaptive Lookup Table” on page 6-45
6-41
6 Lookup Tables
More About
• “What are Adaptive Lookup Tables?” on page 6-2
• “Selecting an Adaptation Method” on page 6-43
6-42
Selecting an Adaptation Method
Sample Mean
Sample mean provides the average value of n output data samples and is defined as:
n
$y( n) = 1
Â
n i =1
y( i)
where y(i) is the ith measurement collected within a particular cell. For each input
data u, the sample mean at the corresponding cell is updated using the output data
measurement, y. Instead of accumulating n samples of data for each cell, a recursive
relation is used to calculate the sample mean. The recursive expression is obtained by the
following equation:
È n -1 ˘ n - 1 È 1 n -1 ˘ 1 n -1 $
$y( n) = 1 Í 1
Â
n ÍÎ i =1
y( i) + y(n) ˙ =
˙˚
Í Â
n ÍÎ n - 1 i=1
y(i) ˙ + y( n) =
˙˚ n n
y( n - 1) + y(n)
n
Defining a priori estimation error as e( n) = y(n) - $y( n - 1) , the recursive relation can be
written as:
$y( n) = $y(n - 1) + 1 e( n)
n
In this expression, only the number of samples, n, for each cell— rather than n data
samples—is stored in memory.
6-43
6 Lookup Tables
n
1
$y( n) =
 l n-i y(i)
 l n- i i =1
n
i =1
1 Èn -1 ˘ s( n - 1)
n -i $y(n - 1) + 1 y( n)
= Â
Í l y(i) + y(n) ˙ =
Â
n
i =1
l n- i ÍÎ i =1 ˙˚ s(n) s( n)
k
where l Œ [ 0,1 ] is the Adaptation gain and s( k) =  l n -i .
i =1
Defining a priori estimation error as e( n) = y(n) - $y( n - 1) , where n ≥ 1 and the initial
A small value of λ results in faster adaptation. A value of 0 indicates short memory (last
data becomes the table value), and a value of 1 indicates long memory (average all data
received in a cell).
6-44
Model Engine Using n-D Adaptive Lookup Table
Objectives
In this example, you learn how to capture the time-varying behavior of an engine using
an n-D adaptive lookup table. You accomplish the following tasks using the Simulink
software:
To learn more about breakpoints and table data, see “Anatomy of a Lookup Table” in
the Simulink documentation.
The output volumetric efficiency of the engine is time varying, and a function of two
inputs—intake manifold pressure and engine speed. The data in the MAT-file is used to
generate the time-varying input and output (I/O) data for the engine.
6-45
6 Lookup Tables
1 Open a preconfigured Simulink model by typing the model name at the MATLAB
prompt:
enginetable1_data
This command also loads the variables X, Y and Z into the MATLAB workspace. To
learn more about this data, see “About the Data” on page 6-45.
2 Add an Adaptive Lookup Table block to the Simulink model.
6-46
Model Engine Using n-D Adaptive Lookup Table
d Drag and drop the Adaptive Lookup Table (nD Stair-Fit) block from the
Adaptive Lookup Tables library to the Simulink model window.
3 Double-click the Adaptive Lookup Table (nD Stair-Fit) block to open the Function
Block Parameters: Adaptive Lookup Table (nD Stair-Fit) dialog box.
6-47
6 Lookup Tables
6-48
Model Engine Using n-D Adaptive Lookup Table
This action adds a new port named Tout to the Adaptive Lookup Table block.
You use this port to plot the table values as they are being adapted.
e Select the Add adaptation enable/disable/reset port check box.
This action adds a new port named Enable to the Adaptive Lookup Table block.
You use this port to enable or disable the adaptation process.
f Select the Add cell lock enable/disable port check box.
This action adds a new port named Lock to the Adaptive Lookup Table block.
You use this port to lock a cell during the adaptation process.
g Verify that Ignore is selected in the Action for out-of-range drop-down list.
This selection specifies that the software ignores any time-varying inputs
outside the range of input breakpoints during adaptation.
Tip To learn more, see Adaptive Lookup Table (nD Stair-Fit) block
reference page.
After you configure the parameters, the block parameters dialog box looks like
the following figure.
6-49
6 Lookup Tables
6-50
Model Engine Using n-D Adaptive Lookup Table
5 Assign the input and output data to the engine model by connecting the U and Y
ports of the Experimental Data block to the u and y ports of the Adaptive Lookup
Table block, respectively.
Tip To learn how to connect blocks in the Simulink model window, see “Block and
Signal Line Shortcuts and Actions” in the Simulink documentation.
6 Design a logic using Simulink blocks to enable or disable the adaptation process.
Connect the logic to the Adaptive Lookup Table block, as shown in the following
figure.
This logic outputs an initial value of 1 which enables the adaptation process.
7 Design a logic to lock a cell during adaptation. Connect the logic to the Adaptive
Lookup Table block, as shown in the following figure.
6-51
6 Lookup Tables
8 In the Simulink Library Browser, select the Simulink > Sinks library, and drag
Display blocks to the model window. Connect the blocks, as shown in the following
figure.
• Display block — Shows the value of the current cell being adapted.
• Display1 block — Shows the number of the current cell being adapted.
9 Write a MATLAB function to plot the lookup table values as they adapt during
simulation.
6-52
Model Engine Using n-D Adaptive Lookup Table
a In the Simulink Library Browser, select the Simulink > Sinks library, and drag
the To Workspace block to the model window.
To learn more about this block, see the To Workspace block reference page in the
Simulink documentation.
b Double-click the To Workspace block to open the Sink Block Parameters dialog
box, and type Tout in the Variable name field.
6-53
6 Lookup Tables
c Click OK.
d Connect the To Workspace block to the adaptive lookup table output signal
Tout, as shown in the next figure.
6-54
Model Engine Using n-D Adaptive Lookup Table
You have now built the model for updating and viewing the adaptive lookup table values.
You must now simulate the model to start the adaptation, as described in “Adapting the
Lookup Table Values Using Time-Varying I/O Data” on page 6-55.
You must have already built the Simulink model, as described “Building a Model Using
Adaptive Lookup Table Blocks” on page 6-46.
The simulation time of infinity specifies that the adaptation process continues as
long as the input and output values of the engine change.
2 In the Simulink Editor, select Simulation > Run to start the adaptation process.
A figure window opens that shows the volumetric efficiency of the engine as a
function of the intake manifold pressure and engine speed:
• The left plot shows the measured volumetric efficiency as a function of intake
manifold pressure and engine speed.
• The right plot shows the volumetric efficiency as it adapts with the time-varying
intake manifold pressure and engine speed.
6-55
6 Lookup Tables
During simulation, the lookup table values displayed on the right plot adapt to the
variations in the I/O data. The left and the right plots resemble each other after a
few seconds, as shown in the next figure.
6-56
Model Engine Using n-D Adaptive Lookup Table
Tip During simulation, the Cell Number and Adaptive Table Outputs blocks in
the Simulink model display the cell number, and the adapted lookup table value in
the cell, respectively.
3 Pause the simulation by selecting Simulation > Pause.
This action also exports the adapted table values Tout to the MATLAB workspace.
Note: After you pause the simulation, the adapted table values are stored in the
Adaptive Lookup Table block.
4 Examine that the left and the right plots match. This resemblance indicates that the
table values have adapted to the time-varying I/O data.
5 Lock a table cell so that only one cell adapts. You may find this feature useful if a
portion of the data is highly erratic or otherwise difficult for the algorithm to handle.
You can view the number of the locked cell in the Cell Number block in the
Simulink model.
6 After the table values adapt to the time-varying I/O data, you can continue to use the
Adaptive Lookup Table block as a static lookup table:
a In the Simulink model window, double-click the Enable block. This action
toggles the switch, and disables the adaptation.
b Select Simulation > Run to restart the simulation, if it is not already running.
During simulation, the Adaptive Lookup Table block works like a static lookup
table, and continues to estimate the output values as the input values change.
You can see the current lookup table value in the Adaptive Table Outputs
block in the Simulink model window.
6-57
6 Lookup Tables
Note: After you disable the adaptation, the Adaptive Lookup Table block does not
update the stored table values, and the figure that displays the table values does not
update.
See Also
Adaptive Lookup Table (nD Stair-Fit)
More About
• “What are Adaptive Lookup Tables?” on page 6-2
6-58
Using Adaptive Lookup Tables in Real-Time Environment
You can also use the Adaptive Lookup Table block in a real-time environment, where
some time-varying properties of a system need to be captured. To do so, generate C code
using Simulink Coder™ code generation software that can then be run in Simulink Real-
Time™ or dSPACE® software. Because you can start, stop, or reset the adaptation if you
want, use logic to enable the adaptation of the table data only when it is desired. The
cell number output N, and the Enable and Lock inputs facilitate this process. Use the
Enable input to start and stop the adaptation and the Lock input to update only one of
the table cells. The Lock input combined with some logic using the cell number output N
provide the means for updating only the desired table cells during a simulation run.
See Also
Adaptive Lookup Table (1D Stair-Fit) | Adaptive Lookup Table (2D
Stair-Fit) | Adaptive Lookup Table (nD Stair-Fit)
Related Examples
• “Model Engine Using n-D Adaptive Lookup Table” on page 6-45
More About
• “What are Adaptive Lookup Tables?” on page 6-2
6-59