0% found this document useful (0 votes)
130 views34 pages

MPC Ug Removed

Uploaded by

leey3870
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
130 views34 pages

MPC Ug Removed

Uploaded by

leey3870
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

9 Nonlinear MPC

Nonlinear MPC
As in traditional linear MPC, nonlinear MPC calculates control actions at each control interval using a
combination of model-based prediction and constrained optimization. The key differences are:

• The prediction model can be nonlinear and include time-varying parameters.


• The equality and inequality constraints can be nonlinear.
• The scalar cost function to be minimized can be a nonquadratic (linear or nonlinear) function of
the decision variables.

Using nonlinear MPC, you can:

• Simulate closed-loop control of nonlinear plants under nonlinear costs and constraints.
• Plan optimal trajectories by solving an open-loop constrained nonlinear optimization problem.

By default, nonlinear MPC controllers solve a nonlinear programming problem using the fmincon
function with the SQP algorithm, which requires Optimization Toolbox™ software. If you do not have
Optimization Toolbox software, you can specify your own custom nonlinear solver. For more
information on configuring the fmincon solver and specifying a custom solver, see “Configure
Optimization Solver for Nonlinear MPC” on page 9-30. For more information about using the
FORCESPRO NLP solver with nonlinear MPC controllers, see “Implement MPC Controllers Using
Embotech FORCESPRO Solvers” on page 10-73.

Note The MPC Designer app does not support the design of nonlinear MPC controllers.

Generic Nonlinear MPC


To implement generic nonlinear MPC, create an nlmpc object, and specify:

• State and output functions that define your prediction model. For more information, see “Specify
Prediction Model for Nonlinear MPC” on page 9-5.
• A custom cost function that can replace or augment the standard MPC cost function. For more
information, see “Specify Cost Function for Nonlinear MPC” on page 9-13.
• Standard bounds on inputs, outputs, and states.
• Additional custom equality and inequality constraints, which can include linear and nonlinear
combinations of inputs, outputs, and states. For more information, see “Specify Constraints for
Generic Nonlinear MPC” on page 9-20.
• Passivity inequality constraints, which can include linear and nonlinear combinations of inputs and
states. For more information, see “Specify Constraints for Generic Nonlinear MPC” on page 9-20
and the Passivity property of the nlmpc object. For examples about passivity, see “Control
Quadruple-Tank Using Passivity-Based Nonlinear MPC” on page 9-182 and “Control Robot
Manipulator Using Passivity-Based Nonlinear MPC” on page 9-187.

You can simulate generic nonlinear MPC controllers:

• In Simulink using the Nonlinear MPC Controller block


• At the command line using nlmpcmove

9-2
Nonlinear MPC

Multistage Nonlinear MPC


A multistage MPC problem is an MPC problem in which cost and constraint functions are stage-
based. Specifically, a multistage MPC controller with a prediction horizon of length p has p+1 stages,
where the first stage corresponds to the current time and the last (terminal) stage corresponds to the
last prediction step.

For a multistage MPC controller, each stage has its own decision variables and parameters, as well as
its own nonlinear cost and constraints. More importantly, cost and constraint functions at a specific
stage are functions only of the decision variables and parameters at that stage. Other than make it
easier to write Jacobian functions, this feature allows for a much more efficient data structure, which
in turn significantly reduces computation times compared to the same problem solved using a generic
NLMPC controller. The fact that slack variables are stage-based allows for more design flexibility, and
disabling the use of manipulated variable rates as decision variables yields an even leaner problem
formulation.

For these reason, if your nonlinear MPC problem has cost and constraint functions that do not involve
cross-stage terms, and if you do not need to enforce passivity, use multistage nonlinear MPC
controller in your design.

To implement a multistage nonlinear MPC controller, first create an nlmpcMultistage object, and
then specify:

• State functions that define your prediction model. For discrete-time models, make sure
Model.IsContinuousTime is set to false.
• Cost and constraint functions at the desired stages. You must specify the cost function for at least
one stage.
• Hard upper and lower bounds on states, manipulated variables, and manipulated variable rates, if
needed.

When designing your controller, consider the following points.

• Anonymous functions are not supported for nlmpcMultistage objects.


• Specifying Jacobians when they are available is the best practice, otherwise the solver must
compute them numerically at each step. You can use generateJacobianFunction to
automatically generate a MATLAB function that calculates the Jacobians.
• Unlike in generic nonlinear MPC, plant outputs, weights, ECR values, and scale factors are not
present in an nlmpcMultistage object. You can implement them directly in your cost and
constraint functions.
• The control horizon is also omitted in nlmpcMultistage objects. To implement block moves, set
RateMin and RateMax to zero at desired prediction steps.

You can simulate multistage nonlinear MPC controllers:

• In Simulink using the Multistage Nonlinear MPC Controller block


• At the MATLAB command line using nlmpcmove

Code generation from a nonlinear multistage controller is supported in both MATLAB (using
mpcmoveCodeGeneration) and Simulink.

For examples on how to create and use a multistage MPC controller, see “Create and Simulate
Multistage Nonlinear MPC Controller”, “Simulate Multistage Nonlinear MPC Controller Using Initial

9-3
9 Nonlinear MPC

Guesses”, and “Truck and Trailer Automatic Parking Using Multistage Nonlinear MPC” on page 9-
158.

See Also
Functions
generateJacobianFunction | validateFcns | nlmpcmove

Objects
nlmpc | nlmpcMultistage | nlmpcmoveopt

Blocks
Nonlinear MPC Controller | Multistage Nonlinear MPC Controller

Related Examples
• “Trajectory Optimization and Control of Flying Robot Using Nonlinear MPC” on page 9-54
• “Control of Quadrotor Using Nonlinear Model Predictive Control” on page 9-141
• “Nonlinear Model Predictive Control of an Exothermic Chemical Reactor” on page 9-90
• “Swing-Up Control of a Pendulum Using Nonlinear Model Predictive Control” on page 9-76
• “Control Quadruple-Tank Using Passivity-Based Nonlinear MPC” on page 9-182
• “Plan and Execute Task- and Joint-Space Trajectories Using KINOVA Gen3 Manipulator”
(Robotics System Toolbox)
• “Landing a Vehicle Using Multistage Nonlinear MPC” on page 9-172
• “Truck and Trailer Automatic Parking Using Multistage Nonlinear MPC” on page 9-158

More About
• “Economic MPC” on page 9-148
• “Specify Prediction Model for Nonlinear MPC” on page 9-5
• “Specify Cost Function for Nonlinear MPC” on page 9-13
• “Specify Constraints for Generic Nonlinear MPC” on page 9-20
• “What is Model Predictive Control?”

9-4
Specify Prediction Model for Nonlinear MPC

Specify Prediction Model for Nonlinear MPC


The prediction model of a nonlinear MPC controller consists of the following user-defined functions:

• State function — Predicts how the plant states evolve over time
• Output function — Calculates plant outputs in terms of state and input variables

You can specify either a continuous-time or a discrete-time prediction model.

Before simulating your controller, it is best practice to validate your custom functions, including the
state function, output function, and their Jacobians using the validateFcns command.

For an example on how to use a neural state-space model identified from data as a prediction model
for a multistage nonlinear MPC problem, see “Control House Heating System Using Nonlinear Model
Predictive Control With Neural State-Space Prediction Model” on page 9-192.

State Function
You can specify either a continuous-time or a discrete-time state function. For a:

• Continuous-time prediction model, the state function is the state derivative function.

dx/dt = f x, u
• Discrete-time prediction model, the state function is the state update function.

x k + 1 = f x k ,u k

Since a nonlinear MPC controller is a discrete-time controller, if your state function is continuous-
time, the controller automatically discretizes the model using the implicit trapezoidal rule. This
method can handle moderately stiff models, and its prediction accuracy depends on the controller
sample time; that is, a large sample time can potentially lead to inaccurate prediction.

If the default discretization method does not provide satisfactory prediction for your application, you
can specify your own discrete-time prediction model that uses a different method. To do so, you can
integrate a continuous-time state function from the given initial condition, xk, to the next state, xk+1.
When doing so numerically, avoid approaches that require iterations, such as some variable-step-size
methods, because these methods introduce numerical noise that degrades solver performance. An
explicit multistep Euler method with sufficiently small step size is often the best method to try first.
For an example, see “Swing-Up Control of a Pendulum Using Nonlinear Model Predictive Control” on
page 9-76.

You can specify your state function in one of the following ways.

• Name of a function in the current working folder or on the MATLAB path, specified as a string or
character vector

Model.StateFcn = "myStateFunction";
• Handle to a local function, or a function defined in the current working folder or on the MATLAB
path

Model.StateFcn = @myStateFunction;

For more information on local functions, see “Local Functions”.

9-5
9 Nonlinear MPC

• Anonymous function

Model.StateFcn = @(x,u,params) myStateFunction(x,u,params)

For more information on anonymous functions, see “Anonymous Functions”.

Note Only functions defined in a separate file in the current folder or on the MATLAB path are
supported for C/C++ code generation. Therefore, specifying state, output, cost, or constraint
functions (or their Jacobians) as local or anonymous functions is not recommended.

Your state function must have one of the following signatures.

• If your controller does not use optional parameters:

function z = myStateFunction(x,u)
• If your controller uses parameters. Here, params is a comma-separated list of parameters:

function z = myStateFunction(x,u,params)

This table describes the inputs and outputs of this function, where:

• Nx is the number of states and is equal to the Dimensions.NumberOfStates property of the


controller.
• Nu is the number of inputs, including all manipulated variables, measured disturbances, and
unmeasured disturbances, and is equal to the Dimensions.NumberOfInputs property of the
controller.

Argument Input/Output Description


x Input Current states, specified as a column vector of length Nx.
u Input Current inputs, specified as a column vector of length Nu.
params Input Optional parameters, specified as a comma-separated list (for
example p1,p2,p3). The same parameters are passed to the
prediction model, custom cost function, and custom constraint
functions of the controller.

If your model uses optional parameters, you must specify the


number of parameters using the Model.NumberOfParameters
property of the controller.
z Output State function output, returned as a column vector of length Nx.
For a continuous-time prediction model, z contains the state
derivatives, dx/dt, and for discrete-time prediction models, z
contains the next states, x(k+1).

As an example of a state function, consider the continuous-time model with the following state
equations:

9-6
Specify Prediction Model for Nonlinear MPC

ẋ 1 = x4
ẋ 2 = x5
ẋ 3 = x6
ẋ 4 = u1 − u2 + u3 − u4 cos x3
ẋ 5 = u1 − u2 + u3 − u4 sin x3
ẋ 6 = 0.2 u1 − u2 − u3 + u4

You can specify the state function as follows:


z = zeros(6,1);
z(1) = x(4);
z(2) = x(5);
z(3) = x(6);
z(4) = (u(1) - u(2) + u(3) - u(4))*cos(x(3));
z(5) = (u(1) - u(2) + u(3) - u(4))*sin(x(3));
z(6) = 0.2*(u(1) - u(2) - u(3) + u(4));

State Function Jacobians

To improve computational efficiency, it is best practice to specify an analytical Jacobian for your state
function. If you do not specify a Jacobian, the controller computes the Jacobian using numerical
perturbation. To specify a Jacobian for your state function, set the Jacobian.StateFcn property of
the controller to one of the following.

• Name of a function in the current working folder or on the MATLAB path, specified as a string or
character vector
Jacobian.StateFcn = "myStateJacobian";
• Handle to a local function, or a function defined in the current working folder or on the MATLAB
path
Jacobian.StateFcn = @myStateJacobian;

For more information on local functions, see “Local Functions”.


• Anonymous function
Jacobian.StateFcn = @(x,u,params) myStateJacobian(x,u,params)

For more information on anonymous functions, see “Anonymous Functions”.

Note Only functions defined in a separate file in the current folder or on the MATLAB path are
supported for C/C++ code generation. Therefore, specifying state, output, cost, or constraint
functions (or their Jacobians) as local or anonymous functions is not recommended.

Your state Jacobian function must have one of the following signatures.

• If your controller does not use optional parameters:


function [A,Bmv] = myStateJacobian(x,u)
• If your controller uses parameters. Here params is a comma-separated list of parameters:
function [A,Bmv] = myStateJacobian(x,u,params)

9-7
9 Nonlinear MPC

The input arguments of the state Jacobian function are the same as the inputs of the state function.
This table describes the outputs of the Jacobian function, where:

• Nx is the number of states and is equal to the Dimensions.NumberOfStates property of the


controller
• Nu is the number of inputs, including all manipulated variables, measured disturbances, and
unmeasured disturbances, and is equal to the Dimensions.NumberOfInputs property of the
controller

Argument Description
A Jacobian of the state function output, z, with respect to x, returned as an Nx-by-
Nx array, where A i, j = ∂z i / ∂x j .
Bmv Jacobian of the state function output with respect to the manipulated variables,
specified as an Nx-by-Nmv array, where Bmv i, j = ∂z i / ∂u MV j and MV(j) is
the jth MV index in the Dimensions.MVIndex controller property. Bmv
contains the gradients with respect to only the manipulated variables in u, since
the measured and unmeasured disturbances are not decision variables.

Consider again, the state function with the following state equations:

ẋ 1 = x4
ẋ 2 = x5
ẋ 3 = x6
ẋ 4 = u1 − u2 + u3 − u4 cos x3
ẋ 5 = u1 − u2 + u3 − u4 sin x3
ẋ 6 = 0.2 u1 − u2 − u3 + u4

To find the Jacobians, compute the partial derivatives of the state equations with respect to the states
and manipulated variables, assuming that all four inputs are manipulated variables.
A = zeros(6,6);
A(1,4) = 1;
A(2,5) = 1;
A(3,6) = 1;
A(4,3) = -(u(1) - u(2) + u(3) - u(4))*sin(x(3));
A(5,3) = (u(1) - u(2) + u(3) - u(4))*cos(x(3));
B = zeros(6,4);
B(4,:) = cos(x(3))*[1 -1 1 -1];
B(5,:) = sin(x(3))*[1 -1 1 -1];
B(6,:) = 0.2*[1 -1 -1 1];

Note For multistage nonlinear MPC, you can automatically generate a state Jacobian function using
generateJacobianFunction.

Output Function
The output function of your prediction model relates the states and inputs at the current control
interval to the outputs. If the number of states and outputs of the prediction model are the same, you
can omit OutputFcn, which implies that all states are measurable; that is, each output corresponds
to one state.

9-8
Specify Prediction Model for Nonlinear MPC

Note OutputFcn cannot have direct feedthrough from any manipulated variable to any output at
any time; in other words, nonlinear MPC always assumes Dmv = 0.

You can specify your output function in one of the following ways.

• Name of a function in the current working folder or on the MATLAB path, specified as a string or
character vector

Model.OutputFcn = "myOutputFunction";
• Handle to a local function, or a function defined in the current working folder or on the MATLAB
path

Model.OutputFcn = @myOutputFunction;

For more information on local functions, see “Local Functions”.


• Anonymous function

Model.OutputFcn = @(x,u,params) myOutputFunction(x,u,params)

For more information on anonymous functions, see “Anonymous Functions”.

Note Only functions defined in a separate file in the current folder or on the MATLAB path are
supported for C/C++ code generation. Therefore, specifying state, output, cost, or constraint
functions (or their Jacobians) as local or anonymous functions is not recommended.

Your output function must have one of the following signatures.

• If your controller does not use optional parameters:

function y = myOutputFunction(x,u)
• If your controller uses parameters. Here, params is a comma-separated list of parameters:

function y = myOutputFunction(x,u,params)

This table describes the inputs and outputs of this function, where:

• Nx is the number of states and is equal to the Dimensions.NumberOfStates property of the


controller.
• Nu is the number of inputs, including all manipulated variables, measured disturbances, and
unmeasured disturbances, and is equal to the Dimensions.NumberOfInputs of the controller.
• NY is the number of outputs and is equal to the Dimensions.NumberOfOutputs property of the
controller.

Argument Input/Output Description


x Input Current states, specified as a column vector of length Nx.
u Input Current inputs, specified as a column vector of length Nu.

9-9
9 Nonlinear MPC

Argument Input/Output Description


params Input Optional parameters, specified as a comma-separated list (for
example p1,p2,p3). The same parameters are passed to the
prediction model, custom cost function, and custom constraint
functions of the controller.

If your model uses optional parameters, you must specify the


number of parameters using Model.NumberOfParameters.
y Output Current outputs, returned as a column vector of length Ny.

As an example of an output function, consider the following output equations. Recall, that your output
function cannot have direct feedthrough from any manipulated variable to any output at any time.

y1 = x1
y2 = x2 + 0.2x3
y3 = x3 ⋅ x4

You can specify the output function as follows:


y = zeros(6,1);
y(1) = x(1);
y(2) = x(2)+0.2*x(3);
y(3) = x(3)*x(4);

Output Function Jacobians

To improve computational efficiency, it is best practice to specify an analytical Jacobian for your
output function. If you do not specify a Jacobian, the controller computes the Jacobian using
numerical perturbation. To specify a Jacobian for your output function, set the
Jacobian.OutputFcn property of the controller to one of the following.

• Name of a function in the current working folder or on the MATLAB path, specified as a string or
character vector
Jacobian.OutputFcn = "myOutputJacobian";
• Handle to a local function, or a function defined in the current working folder or on the MATLAB
path
Jacobian.OutputFcn = @myOutputJacobian;

For more information on local functions, see “Local Functions”.


• Anonymous function
Jacobian.OutputFcn = @(x,u,params) myOutputJacobian(x,u,params)

For more information on anonymous functions, see “Anonymous Functions”.

Note Only functions defined in a separate file in the current folder or on the MATLAB path are
supported for C/C++ code generation. Therefore, specifying state, output, cost, or constraint
functions (or their Jacobians) as local or anonymous functions is not recommended.

Your output Jacobian function must have one of the following signatures.

9-10
Specify Prediction Model for Nonlinear MPC

• If your controller does not use optional parameters:


function C = myOutputJacobian(x,u)
• If your controller uses parameters. Here, params is a comma-separated list of parameters:
function C = myOutputJacobian(x,u,params)

The input arguments of the output Jacobian function are the same as the inputs of the output
function. This table describes the output of the Jacobian function. Since the output function cannot
have direct feedthrough from any manipulated variable to any output, the output Jacobian function
returns only the gradients of the output function with respect to the model states.

Argument Description
C Jacobian of the output function, returned as an Ny-by-Nx array, where
C i, j = ∂y i / ∂x j .

Consider again, the model with the following output equations:

y1 = x1
y2 = x2 + 0.2x3
y3 = x3 ⋅ x4

To find the Jacobians, compute the partial derivatives of the output equations with respect to the
states. Since the output function cannot have direct feedthrough from any manipulated variable to
any output at any time, you do not compute the Jacobian with respect to the manipulated variables.
C = zeros(3,4);
C(1,1) = 1;
C(2,2) = 1;
C(2,3) = 0.2;
C(3,3) = x(4);
C(3,4) = x(3);

Specify Optional Model Parameters


You can specify optional parameters for your nonlinear MPC prediction model, cost function, and
custom constraints. To do so, pass a comma-separated list of parameter arguments to your custom
functions (for example p1,p2,p3). These parameters must be numerical values. Also, you must
specify the number of model parameters using the Model.NumberOfParameters property of the
controller.

The same parameters are passed to the prediction model, custom cost function, custom constraint
functions, and their respective Jacobians. For example, even if the state function uses only parameter
p1, the constraint functions use only parameter p2, and the cost function uses only parameter p3,
you must still define three parameters. All of these parameters are passed into all of these functions,
and you must choose the correct parameter to use in each function.

For an example that specifies the sample time of a discrete-time state function as a parameter, see
“Swing-Up Control of a Pendulum Using Nonlinear Model Predictive Control” on page 9-76.

Augment Prediction Model with Unmeasured Disturbances


You can augment your prediction model to include unmeasured disturbances. For example, if your
plant does not have an integrator and you want to reject a certain unmeasured disturbance, augment

9-11
9 Nonlinear MPC

your plan with a disturbance model. Doing so allows the external state estimator to detect the
disturbance and thus give the nonlinear MPC controller enough information to reject it.

During simulation, the controller passes a zero to each unmeasured disturbance input channel, since
the signals are unmeasured and assumed to be zero-mean by default.

To augment your prediction model, you must designate one or more input signals as unmeasured
disturbances when creating a controller using nlmpc. For example, create a controller where the first
two inputs are manipulated variables and the third input is an unmeasured disturbance (UD).

nlobj = nlmpc(nx,ny,'MV',[1 2],'UD',3);

Specify the unmeasured disturbance model in the state and output functions of your prediction
model. This unmeasured disturbance model can be any arbitrary model that accurately captures the
effect of the disturbance on your plant. For example:

• If you expect a step-like UD at a plant output, then specify the UD model as an integrator in your
state function, and add the integrator state to the plant output in your output function.
• If you expect a ramp-like UD at a plant input, then specify the UD model as an integrator and add
the integrator output to the input signal in your state function.

Any states that you add when specifying the unmeasured disturbance model are included in the
prediction model state vector. The values in these unmeasured disturbance model states reflect the
disturbance behavior during simulation. This state vector corresponds to the x input argument of
your state function and the X input argument to your custom cost and constraint functions.

For an example that augments the prediction model for random step-like output disturbances, see
“Nonlinear Model Predictive Control of an Exothermic Chemical Reactor” on page 9-90.

See Also
Functions
validateFcns | nlmpcmove

Objects
nlmpc

Related Examples
• “Control of Quadrotor Using Nonlinear Model Predictive Control” on page 9-141

More About
• “Nonlinear MPC” on page 9-2
• “Specify Cost Function for Nonlinear MPC” on page 9-13
• “Specify Constraints for Generic Nonlinear MPC” on page 9-20

9-12
Specify Cost Function for Nonlinear MPC

Specify Cost Function for Nonlinear MPC


While traditional linear MPC controllers optimize control actions to minimize a quadratic cost
function, nonlinear MPC controllers support generic custom cost functions. For example, you can
specify your cost function as a combination of linear or nonlinear functions of the system states and
inputs. To improve computational efficiency, you can also specify an analytical Jacobian for your
custom cost function.

Using a custom cost function, you can, for example:

• Maximize profitability
• Minimize energy consumption

When you specify a custom cost function for your nonlinear MPC controller, you can choose to either
replace or augment the standard quadratic MPC cost function. By default, an nlmpc controller
replaces the standard cost function with your custom cost function. In this case, the controller
ignores the standard tuning weights in its Weights property.

To use an objective function that is the sum of the standard costs and your custom costs, set the
Optimization.ReplaceStandardCost property of your nlmpc object to false. In this case, the
standard tuning weights specified in the Weights property of the controller contribute to the cost
function. However, you can eliminate any of the standard cost function terms by setting the
corresponding penalty weight to zero. For more information on the standard MPC cost function, see
“Standard Cost Function” on page 1-7.

For a multistage MPC controller, each stage has its own cost function, which is a function only of the
decision variables and parameters at that stage.

Before simulating your controller, it is best practice to validate your custom functions, including the
cost function and its Jacobian, using the validateFcns command.

Custom Cost Function


To configure your nonlinear MPC controller to use a custom cost function, set its
Optimization.CustomCostFcn property to one of the following.

• Name of a function in the current working folder or on the MATLAB path, specified as a string or
character vector

Optimization.CustomCostFcn = "myCostFunction";
• Handle to a function in the current working folder or on the MATLAB path

Optimization.CustomCostFcn = @myCostFunction;

For more information on local functions, see “Local Functions”.


• Anonymous function
Optimization.CustomCostFcn = @(X,U,e,data,params) myCostFunction(X,U,e,data,params);

For more information on anonymous functions, see “Anonymous Functions”.

9-13
9 Nonlinear MPC

Note Only functions defined in a separate file in the current folder or on the MATLAB path are
supported for C/C++ code generation. Therefore, specifying state, output, cost, or constraint
functions (or their Jacobians) as local or anonymous functions is not recommended.

Your custom cost function must have one of the following signatures.

• If your controller does not use optional parameters:

function J = myCostFunction(X,U,e,data)
• If your controller uses parameters. Here, params is a comma-separated list of parameters:

function J = myCostFunction(X,U,e,data,params)

This table describes the inputs and outputs of this function, where:

• Nx is the number of states and is equal to the Dimensions.NumberOfStates property of the


controller.
• Nu is the number of inputs, including all manipulated variables, measured disturbances, and
unmeasured disturbances, and is equal to the Dimensions.NumberOfInputs property of the
controller.
• p is the prediction horizon.
• k is the current time.

Argument Input/Output Description


X Input State trajectory from time k to time k+p, specified as a (p+1)-by-Nx
array. The first row of X contains the current state values, which
means that the solver does not use the values in X(1,:) as
decision variables during optimization.
U Input Input trajectory from time k to time k+p, specified as a (p+1)-by-
Nu array. The final row of U is always a duplicate of the preceding
row; that is, U(end,:) = U(end-1,:). Therefore, the values in
the final row of U are not independent decision variables during
optimization.
e Input Slack variable for constraint softening, specified as a nonnegative
scalar. e is zero if there are no soft constraints in your controller.

If you have nonlinear soft constraints defined in your inequality


constraint function (Model.CustomIneqConFcn), use a positive
penalty weight on e and make them part of the cost function.

9-14
Specify Cost Function for Nonlinear MPC

Argument Input/Output Description


data Input Additional signals, specified as a structure with the following
fields:

Field Description
Ts Prediction model sample time, as defined in
the Ts property of the controller
CurrentStates Current prediction model states, as specified
in the x input argument of nlmpcmove
LastMV MV moves used in previous control interval,
as specified in the lastmv input argument
of nlmpcmove
References Reference values for plant outputs, as
specified in the ref input argument of
nlmpcmove
MVTarget Manipulated variable targets, as specified in
the MVTarget property of an
nlmpcmoveopt object
PredictionHoriz Prediction horizon, as defined in the
on PredictionHorizon property of the
controller
NumOfStates Number of states, as defined in the
Dimensions.NumberOfStates property of
the controller
NumOfOutputs Number of outputs, as defined in the
Dimensions.NumberOfOutputs property
of the controller
NumOfInputs Number of inputs, as defined in the
Dimensions.NumberOfInputs property of
the controller
MVIndex Manipulated variables indices, as defined in
the Dimensions.MVIndex property of the
controller
MDIndex Measured disturbance indices, as defined in
the Dimensions.MDIndex property of the
controller
UDIndex Unmeasured disturbance indices, as defined
in the Dimensions.UDIndex property of
the controller

9-15
9 Nonlinear MPC

Argument Input/Output Description


params Input Optional parameters, specified as a comma-separated list (for
example p1,p2,p3). The same parameters are passed to the
prediction model, custom cost function, and custom constraint
functions of the controller. For example, if the state function uses
only parameter p1, the constraint functions use only parameter p2,
and the cost function uses only parameter p3, then all three
parameters are passed to all of these functions.

If your model uses optional parameters, you must specify the


number of parameters using the Model.NumberOfParameters
property of the controller.
J Output Computed cost, returned as a scalar

Your custom cost function must:

• Be a continuous, finite function of U, X, and e and have finite first derivatives


• Increase as the slack variable e increases or be independent of it

To use output variable values in your cost function, you must first derive them from the state and
input arguments using the prediction model output function, as specified in the Model.OutputFcn
property of the controller. For example, to compute the output trajectory Y from time k to time k+p,
use:

p = data.PredictionHorizon;
for i=1:p+1
Y(i,:) = myOutputFunction(X(i,:)',U(i,:)',params)';
end

For more information on the prediction model output function, see “Specify Prediction Model for
Nonlinear MPC” on page 9-5.

Typically, you optimize control actions to minimize the cost function across the prediction horizon.
Since the cost function value must be a scalar, you compute the cost function at each prediction
horizon step and add the results together. For example, suppose that the stage cost function is:

J = 10u12 + 5x23 + x1

That is, you want to minimize the difference between the first output and its reference value, and the
product of the first manipulated variable and the second state. To compute the total cost function
across the prediction horizon, use:

p = data.PredictionHorizon;
U1 = U(1:p,data.MVIndex(1));
X1 = X(2:p+1,1);
X2 = X(2:p+1,2);
J = 10*sum(U1.^2) + 5*sum(X2.^3) + sum(X1);

In general, for cost functions, do not use the following values, since they are not part of the decision
variables used by the solver:

• U(end,:) — This row is a duplicate of the preceding row.


• X(1,:) — This row contains the current state values.

9-16
Specify Cost Function for Nonlinear MPC

Since this example cost function is relatively simple, you can specify it using an anonymous function
handle.

For relatively simple costs, you can specify the cost function using an anonymous function handle. For
example, to specify an anonymous function that implements just the first term of the preceding cost
function, use:
Optimization.CustomCostFcn = @(X,U,data) 10*sum(U(1:end-1,data.MVIndex(1)).^2);

Cost Function Jacobian


To improve computational efficiency, it is best practice to specify an analytical Jacobian for your
custom cost function. If you do not specify a Jacobian, the controller computes the Jacobian using
numerical perturbation. To specify a Jacobian for your cost function, set the
Jacobian.CustomCostFcn property of the controller to one of the following.

• Name of a function in the current working folder or on the MATLAB path, specified as a string or
character vector

Jacobian.CustomCostFcn = "myCostJacobian";
• Handle to a local function, or a function defined in the current working folder or on the MATLAB
path

Jacobian.CustomCostFcn = @myCostJacobian;

For more information on local functions, see “Local Functions”.


• Anonymous function
Jacobian.CustomCostFcn = @(X,U,e,data,params) myCostJacobian(X,U,e,data,params)

For more information on anonymous functions, see “Anonymous Functions”.

Note Only functions defined in a separate file in the current folder or on the MATLAB path are
supported for C/C++ code generation. Therefore, specifying state, output, cost, or constraint
functions (or their Jacobians) as local or anonymous functions is not recommended.

Your cost Jacobian function must have one of the following signatures.

• If your controller does not use optional parameters:

function [G,Gmv,Ge] = myCostJacobian(X,U,e,data)


• If your controller uses parameters. Here, params is a comma-separated list of parameters:

function [G,Gmv,Ge] = myCostJacobian(X,U,e,data,params)

The input arguments of the cost Jacobian function are the same as the inputs of the custom cost
function. This table describes the outputs of the Jacobian function, where:

• Nx is the number of states and is equal to the Dimensions.NumberOfStates property of the


controller.
• Nmv is the number of manipulated variables.
• p is the prediction horizon.

9-17
9 Nonlinear MPC

Argument Description
G Jacobian of the cost function with respect to the state trajectories, returned as a
p-by-Nx array, where G i, j = ∂J / ∂X i + 1, j . Compute G based on X from the
second row to row p+1, ignoring the first row.
Gmv Jacobian of the cost function with respect to the manipulated variable
trajectories, returned as a p-by-Nmv array, where Gmv i, j = ∂ J/ ∂U i, MV j and
MV(j) is the jth MV index in data.MVIndex.

Since the controller forces U(p+1,:) to equal U(p,:), if your cost function
uses U(p+1,:), you must include the impact of both U(p,:) and U(p+1,:) in
the Jacobian for U(p,:).
Ge Jacobian of the cost function with respect to the slack variable, e, returned as a
scalar, where Ge = ∂J / ∂e.

To use output variable values and their Jacobians in your cost Jacobian function, you must first derive
them from the state and input arguments. To do so, use the Jacobian of the prediction model output
function, as specified in the Jacobian.OutputFcn property of the controller. For example, to
compute the output variables Y and their Jacobians Yjacob from time k to time k+p, use:

p = data.PredictionHorizon;
for i=1:p+1
Y(i,:) = myOutputFunction(X(i,:)',U(i,:)',params)';
end
for i=1:p+1
Yjacob(i,:) = myOutputJacobian(X(i,:)',U(i,:)',params)';
end

Since prediction model output functions do not support direct feedthrough from inputs to outputs, the
output function Jacobian contains partial derivatives with respect to only the states in X. For more
information on the output function Jacobian, see “Specify Prediction Model for Nonlinear MPC” on
page 9-5.

To find the Jacobians, compute the partial derivatives of the cost function with respect to the state
trajectories, manipulated variable trajectories, and slack variable. For example, suppose that your
cost function is as follows, where u1 is the first manipulated variable.

J = 10u12 + 5x23 + x1

To compute the Jacobian with respect to the state trajectories, use the following. Recall that you
compute G based on X from the second row to row p+1, ignoring the first row.

p = data.PredictionHorizon;
Nx = data.NumOfStates;
U1 = U(1:p,data.MVIndex(1));
X2 = X(2:p+1,2);

G = zeros(p,Nx);
G(1:p,1) = 1;
G(1:p,2) = 15*X2.^2;

To compute the Jacobian with respect to the manipulated variable trajectories, use:

Nmv = length(data.MVIndex);

9-18
Specify Cost Function for Nonlinear MPC

Gmv = zeros(p,Nmv);
Gmv(1:p,1) = 20*U1;

In this case, the derivative with respect to the slack variable is Ge = 0.

Note For multistage nonlinear MPC, you can automatically generate a stage cost Jacobian function
using generateJacobianFunction.

See Also
Functions
generateJacobianFunction | validateFcns | nlmpcmove

Objects
nlmpc

Related Examples
• “Economic MPC Control of Ethylene Oxide Production” on page 9-150

More About
• “Nonlinear MPC” on page 9-2
• “Economic MPC” on page 9-148
• “Specify Prediction Model for Nonlinear MPC” on page 9-5
• “Specify Constraints for Generic Nonlinear MPC” on page 9-20

9-19
9 Nonlinear MPC

Specify Constraints for Generic Nonlinear MPC


When you create a nonlinear MPC controller using an nlmpc object, you can define any of the
following constraints:

• Standard linear constraints on states, outputs, manipulated variables, and manipulated variable
rates of change
• Custom equality constraints, specified as linear or nonlinear functions of the prediction model
system states and inputs
• Custom inequality constraints, specified as linear or nonlinear functions of the prediction model
system states and inputs
• Passivity inequality constraints, specified as linear or nonlinear functions of the prediction model
states and inputs

The controller optimizes its control moves to satisfy all of these constraints; that is, the custom
constraints supplement the standard linear constraints.

To improve computational efficiency, you can also specify analytical Jacobians for your custom
equality and inequality constraints.

By specifying custom equality or inequality constraints, you can, for example:

• Require the plant to reach a target state at the end of the prediction horizon
• Require cumulative resource consumption to stay within specified limits

If your plant is passive, enforcing controller passivity guarantees that the resulting closed loop
system is stable. You can enforce controller passivity by specifying passivity constraints.

For a multistage MPC controller, each stage has its own constraints, and each constraint for a specific
stage is function only of the decision variables and parameters at that stage. Passivity constraints are
not supported for nlmpcMultistage objects.

Before simulating your controller, it is best practice to validate your custom functions, including the
constraint functions and their Jacobians, using the validateFcns command.

Linear MPC controllers have properties for defining custom constraints on linear combinations of
inputs and outputs, as discussed in “Constraints on Linear Combinations of Inputs and Outputs” on
page 5-6. These properties are not available for nonlinear MPC controllers. Instead, you implement
such constraints within your custom equality or inequality constraint functions.

Standard Linear Constraints


The following table shows the standard linear constraints supported by nonlinear MPC controllers.
For each of these constraints, you can specify a single bound that applies across the entire prediction
horizon, or you can vary each constraint over the prediction horizon. For more information on setting
controller linear constraint properties, see nlmpc.

Constraint Controller Property Constraint Softening


Lower bounds on state i States(i).Min > -Inf Not applicable. State bounds
are always hard.

9-20
Specify Constraints for Generic Nonlinear MPC

Constraint Controller Property Constraint Softening


Upper bounds on state i States(i).Max < Inf Not applicable. State bounds
are always hard.
Lower bounds on output OutputVariables(i).Min > OutputVariables(i).MinEC
variable i -Inf R > 0

Default: 1 (soft)
Upper bounds on output OutputVariables(i).Max < OutputVariables(i).MaxEC
variable i Inf R > 0

Default: 1 (soft)
Lower bounds on manipulated ManipulatedVariables(i). ManipulatedVariables(i).
variable i Min > -Inf MinECR > 0

Default: 0 (hard)
Upper bounds on manipulated ManipulatedVariables(i). ManipulatedVariables(i).
variable i Max < Inf MaxECR > 0

Default: 0 (hard)
Lower bounds on manipulated ManipulatedVariables(i). ManipulatedVariables(i).
variable i rate of change RateMin > -Inf RateMinECR > 0

Default: 0 (hard)
Lower bounds on manipulated ManipulatedVariables(i). ManipulatedVariables(i).
variable i rate of change RateMax < Inf RateMaxECR > 0

Default: 0 (hard)

Custom Constraints
You can specify custom equality and inequality constraints for a nonlinear MPC controller. To
configure your nonlinear MPC controller to use custom equality or inequality constraints, set its
Optimization.CustomEqConFcn or Optimization.CustomIneqConFcn respectively. To do so,
specify the custom functions as one of the following.

• Name of a function in the current working folder or on the MATLAB path, specified as a string or
character vector

Optimization.CustomEqConFcn = "myEqConFunction";
Optimization.CustomIneqConFcn = "myIneqConFunction";
• Handle to a function in the current working folder or on the MATLAB path

Optimization.CustomEqConFcn = @myEqConFunction;
Optimization.CustomIneqConFcn = @myIneqConFunction;

For more information on local functions, see “Local Functions”.


• Anonymous function
Optimization.CustomEqConFcn = ...
@(X,U,data,params) myEqConFunction(X,U,data,params);
Optimization.CustomIneqConFcn = ...
@(X,U,e,data,params) myIneqConFunction(X,U,e,data,params);

9-21
9 Nonlinear MPC

For more information on anonymous functions, see “Anonymous Functions”.

Note Only functions defined in a separate file in the current folder or on the MATLAB path are
supported for C/C++ code generation. Therefore, specifying state, output, cost, or constraint
functions (or their Jacobians) as local or anonymous functions is not recommended.

Your constraint functions must have one of the following signatures.

• If your controller does not use optional parameters:

function ceq = myEqConFunction(X,U,data)


function cineq = myIneqConFunction(X,U,e,data)
• If your controller uses parameters. Here, params is a comma-separated list of parameters:

function ceq = myEqConFunction(X,U,data,params)


function cineq = myIneqConFunction(X,U,e,data,params)

This table describes the inputs and outputs of these functions, where:

• Nx is the number of states and is equal to the Dimensions.NumberOfStates property of the


controller.
• Nu is the number of inputs, including all manipulated variables, measured disturbances, and
unmeasured disturbances, and is equal to the Dimensions.NumberOfInputs property of the
controller.
• Nceq is the number of equality constraints.
• Ncineq is the number of inequality constraints.
• p is the prediction horizon.
• k is the current time.

Argument Input/Output Description


X Input State trajectory from time k to time k+p, specified as a (p+1)-by-Nx
array. The first row of X contains the current state values, which
means that the solver does not use the values in X(1,:) as
decision variables during optimization.
U Input Input trajectory from time k to time k+p, specified as a (p+1)-by-
Nu array. The final row of U is always a duplicate of the preceding
row; that is, U(end,:) = U(end-1,:). Therefore, the values in
the final row of U are not independent decision variables during
optimization.
e Input Slack variable for constraint softening, specified as a positive
scalar. Since all equality constraints are hard, this input argument
applies to only the inequality constraint function.

9-22
Specify Constraints for Generic Nonlinear MPC

Argument Input/Output Description


data Input Additional signals, specified as a structure with the following
fields:

Field Description
Ts Prediction model sample time, as defined in
the Ts property of the controller
CurrentStates Current prediction model states, as specified
in the x input argument of nlmpcmove
LastMV MV moves used in previous control, as
specified in the lastmv input argument of
nlmpcmove interval
References Reference values for plant outputs, as
specified in the ref input argument of
nlmpcmove
MVTarget Manipulated variable targets, as specified in
the MVTarget property of an
nlmpcmoveopt object
PredictionHoriz Prediction horizon, as defined in the
on PredictionHorizon property of the
controller
NumOfStates Number of states, as defined in the
Dimensions.NumberOfStates property of
the controller
NumOfOutputs Number of outputs, as defined in the
Dimensions.NumberOfOutputs property
of the controller
NumOfInputs Number of inputs, as defined in the
Dimensions.NumberOfInputs property of
the controller
MVIndex Manipulated variables indices, as defined in
the Dimensions.MVIndex property of the
controller
MDIndex Measured disturbance indices, as defined in
the Dimensions.MDIndex property of the
controller
UDIndex Unmeasured disturbance indices, as defined
in the Dimensions.UDIndex property of
the controller

9-23
9 Nonlinear MPC

Argument Input/Output Description


params Input Optional parameters, specified as a comma-separated list (for
example p1,p2,p3). The same parameters are passed to the
prediction model, custom cost function, and custom constraint
functions of the controller. For example, if the state function uses
only parameter p1, the constraint functions use only parameter p2,
and the cost function uses only parameter p3, then all three
parameters are passed to all of these functions.

If your model uses optional parameters, you must specify the


number of parameters using Model.NumberOfParameters. At
simulation time, you then pass these parameters to the Nonlinear
MPC Controller block (in Simulink) or to a simulation function such
as nlmpcmove (in MATLAB).
ceq Output Computed equality constraint values, returned as a column vector
of length Nceq. An equality constraint is satisfied when the
corresponding output is 0.
cineq Output Computed inequality constraint values, returned as a column
vector of length Ncineq. An inequality constraint is satisfied when
the corresponding output is less than or equal to 0.

To use output variable values in your constraint functions, you must first derive them from the state
and input arguments using the prediction model output function, as specified in the
Model.OutputFcn property of the controller. For example, to compute the output trajectory Y from
time k to time k+p, use:

p = data.PredictionHorizon;
for i=1:p+1
Y(i,:) = myOutputFunction(X(i,:)',U(i,:)',params)';
end

For more information on the prediction model output function, see “Specify Prediction Model for
Nonlinear MPC” on page 9-5.

In general:

• All equality constraints are hard.


• To define soft inequality constraints, use the slack variable input argument, e. For more
information on constraint softening in MPC, see “Constraint Softening” on page 2-7.
• Equality constraints should be continuous and have continuous first derivatives with respect to the
decision variables.

You can define custom constraints that apply across the entire prediction horizon. For example,
suppose that you want to satisfy the following inequality constraints across the prediction horizon,
where u1 is the first manipulated variable:

2x12 − 3x2 − 10 ≤ 0
u12 − 5 ≤ 0

To define the constraint values across the prediction horizon, use:

9-24
Specify Constraints for Generic Nonlinear MPC

p = data.PredictionHorizon;
U1 = U(1:p,data.MVIndex(1));
X1 = X(2:p+1,1);
X2 = X(2:p+1,2);

cineq = [2*X1.^2 - 3*X2 - 10;


U1.^2 - 5];

Applying these two constraints across p prediction horizon steps produces a column vector with 2*p
inequality constraints. These inequality constraints are satisfied when the corresponding element of
cineq is less than or equal to zero.

Alternatively, you can define constraints that apply at specific prediction horizon steps. For example,
suppose that you want the states of a third-order plant to be:

x1 = 5
x2 = − 3
x3 = 0

To specify these state values as constraints on only the final prediction horizon step, use:

ceq = [X(p+1,1) - 5;
X(p+1,2) + 3;
X(p+1,3)];

These equality constraints are satisfied when the corresponding element of ceq is equal to zero.

For relatively simple constraints, you can specify the constraint function using an anonymous function
handle. For example, to specify an anonymous function that implements the equality constraints, use:
Optimization.CustomEqConFcn = @(X,U,data) [X(p+1,1) - 5; X(p+1,2) + 3; X(p+1,3)];

Custom Constraint Jacobians


To improve computational efficiency, it is best practice to specify analytical Jacobians for your custom
constraint functions. If you do not specify Jacobians, the controller computes the Jacobians using
numerical perturbation.

To specify a Jacobian for your equality or inequality constraint functions, set the respective
Jacobian.CustomEqConFcn or Jacobian.CustomIneqConFcn property of the controller to one of
the following.

• Name of a function in the current working folder or on the MATLAB path, specified as a string or
character vector

Jacobian.CustomEqConFcn = "myEqConJacobian";
Jacobian.CustomIneqConFcn = "myIneqConJacobian";
• Handle to a local function, or a function defined in the current working folder or on the MATLAB
path

Jacobian.CustomEqConFcn = @myEqConJacobian;
Jacobian.CustomIneqConFcn = @myIneqConJacobian;

For more information on local functions, see “Local Functions”.

9-25
9 Nonlinear MPC

• Anonymous function
Jacobian.CustomEqConFcn = @(X,U,data,params) myEqConJacobian(X,U,data,params);
Jacobian.CustomInqConFcn = @(X,U,e,data,params) myIneqConJacobian(X,U,e,data,params);

For more information on anonymous functions, see “Anonymous Functions”.

Note Only functions defined in a separate file in the current folder or on the MATLAB path are
supported for C/C++ code generation. Therefore, specifying state, output, cost, or constraint
functions (or their Jacobians) as local or anonymous functions is not recommended.

Your constraint Jacobian functions must have one of the following signatures.

• If your controller does not use optional parameters:


function [Geq,Gmv] = myEqConJacobian(X,U,data)
function [Geq,Gmv,Ge] = myIneqConJacobian(X,U,e,data)
• If your controller uses parameters. Here, params is a comma-separated list of parameters:
function [Geq,Gmv] = myEqConJacobian(X,U,data,params)
function [Geq,Gmv,Ge] = myIneqConJacobian(X,U,e,data,params)

The input arguments of the constraint Jacobian functions are the same as the inputs of their
respective custom constraint functions. This table describes the outputs of the Jacobian functions,
where:

• Nx is the number of states and is equal to the Dimensions.NumberOfStates property of the


controller.
• Nmv is the number of manipulated variables.
• Nc is the number of constraints (either equality or inequality constraints, depending on the
constraint function).
• p is the prediction horizon.

Argument Description
G Jacobian of the equality or inequality constraints with respect to the state
trajectories, returned as a p-by-Nx-by-Nc array, where
G i, j, l = ∂c l / ∂X i + 1, j . Compute G based on X from the second row to row p
+1, ignoring the first row.
Gmv Jacobian of the equality or inequality constraints with respect to the
manipulated variable trajectories, returned as a p-by-Nmv-by-Nc array, where
Gmv i, j, l = ∂c l / ∂U i, MV j and MV(j) is the jth MV index in data.MVIndex.

Since the controller forces U(p+1,:) to equal U(p,:), if your constraints use
U(p+1,:), you must include the impact of both U(p,:) and U(p+1,:) in the
Jacobian for U(p,:).
Ge Jacobian of the inequality constraints with respect to the slack variable, e,
returned as a row vector of length Nc, where Ge l = ∂c l / ∂e

To use output variable Jacobians in your constraint Jacobian functions, you must first derive them
from the state and input arguments using the Jacobian of the prediction model output function, as
specified in the Jacobian.OutputFcn property of the controller. For example, to compute the
output variable Jacobians Yjacob from time k to time k+p, use:

9-26
Specify Constraints for Generic Nonlinear MPC

p = data.PredictionHorizon;
for i=1:p+1
Y(i,:) = myOutputFunction(X(i,:)',U(i,:)',params)';
end
for i=1:p+1
Yjacob(i,:) = myOutputJacobian(X(i,:)',U(i,:)',params)';
end

Since prediction model output functions do not support direct feedthrough from inputs to outputs, the
output function Jacobian contains partial derivatives with respect to only the states in X. For more
information on the output function Jacobian, see “Specify Prediction Model for Nonlinear MPC” on
page 9-5.

To find the Jacobians, compute the partial derivatives of the constraint functions with respect to the
state trajectories, manipulated variable trajectories, and slack variable. For example, suppose that
your constraint function is as follows, where u1 is the first manipulated variable.

2x12 − 3x2 − 10 ≤ 0
u12 − 5 ≤ 0

To compute the Jacobian with respect to the state trajectories, use:


Nx = data.NumOfStates;
Nc = 2*p;
G = zeros(p,Nx,Nc);
G(1:p,2,1:p) = diag(2*X1 - 3);

To compute the Jacobian with respect to the manipulated variable trajectories, use:
Nmv = length(data.MVIndex);
Gmv = zeros(p,Nmv,Nc);
Gmv(1:p,1,p+1:2*p) = diag(2*u(1:p,data.MVIndex(1)));

In this case, the derivative with respect to the slack variable is Ge = zeros(20,1).

Note For multistage nonlinear MPC, you can automatically generate a stage constraint Jacobian
function using generateJacobianFunction.

Passivity Constraints
You can specify passivity inequality constraints for a general nonlinear MPC controller (multistage
MPC controllers do not support passivity constraints). To use passivity constraints, set these
properties of your nlmpc object as follows:

• Passivity.EnforceConstraint — true
• Passivity.OutputPassivityIndex — A desired nonnegative scalar
• Passivity.InputPassivityIndex — A desired nonnegative scalar
• Passivity.OutputFcn — Name of the desired passivity output function yp(x,u)
• Passivity.InputFcn — Name of the desired passivity input function up(x,u)

When your nonlinear MPC controller is configured to use passivity constraints, at each step the
optimization algorithm tries to enforce the inequality constraint:

9-27
9 Nonlinear MPC

T T T
yp(x, u) up(x, u) + νy yp(x, u) yp(x, u) + νu up(x, u) up(x, u) ≤ 0.

Here, νy is the output passivity index, νu is the input passivity index, up(x,u) is the passivity input
function, and yp(x,u) is the passivity output function. The variables x and u are the current state and
input of the prediction model.

Assuming that the plant is already passive with respect to the input-output pair up and yp, if these two
inequalities are verified, then (under mild conditions) the resulting closed loop system tends to
dissipate energy over time, and therefore has a stable equilibrium. For more information on passivity
in the context of linear systems, see “About Passivity and Passivity Indices”.

To improve computational efficiency, you can specify analytical Jacobians for your passivity constraint
functions. To do so, specify the Passivity.OutputJacobianFcn and
Passivity.InputJacobianFcn properties.

You can specify the passivity functions and their Jacobians as one of the following:

• Name of a function in the current working folder or on the MATLAB path, specified as a string or
character vector.
• Handle to a local function, or a function defined in the current working folder or on the MATLAB
path. For more information on local functions, see “Local Functions”.
• Anonymous function. For more information on anonymous functions, see “Anonymous Functions”.

Note Only functions defined in a separate file in the current folder or on the MATLAB path are
supported for C/C++ code generation. Therefore, specifying state, output, cost, or constraint
functions (or their Jacobians) as local or anonymous functions is not recommended.

The passivity functions and their Jacobians must accept as first and second input arguments the
current state and input of the prediction model, respectively. After the first two input arguments, you
can also pass an optional comma separated list of parameters (for example p1,p2,p3) that might be
needed by the function you specify.

If any of your functions use optional parameters, you must specify the number of parameters using
Model.NumberOfParameters. At run time, in Simulink, you then pass these parameters to the
Nonlinear MPC Controller block. In MATLAB, you pass the parameters to a simulation function (such
as nlmpcmove, using an nlmpcmoveopt option set object).

The function specified in Passivity.OutputJacobianFcn (if any) must return as a first output
argument the Jacobian matrix of the output passivity function with respect to the current state (an
Nyp-by-Nx matrix) and as a second output argument the Jacobian matrix of the output passivity
function with respect to the manipulated variables (an Nyp by Nmv matrix).

Similarly, the function specified in Passivity.InputJacobianFcn (if any) must return as a first
output argument the Jacobian of the input passivity function with respect to the current state (an Nup-
by-Nx matrix) and as a second output argument the Jacobian of the input passivity function with
respect to the manipulated variables (an Nup by Nmv matrix).

Here, Nx is the number of state variables of the prediction model, Nmv is the number of manipulated
variables, Nyp is the number of outputs of the passivity output function, and Nup is the number of
outputs of the passivity input function.

9-28
Specify Constraints for Generic Nonlinear MPC

For more detail, see the Passivity property of nlmpc. For examples, see “Control Quadruple-Tank
Using Passivity-Based Nonlinear MPC” on page 9-182 and “Control Robot Manipulator Using
Passivity-Based Nonlinear MPC” on page 9-187.

See Also
Functions
generateJacobianFunction | validateFcns | nlmpcmove

Objects
nlmpc | nlmpcMultistage

Blocks
Nonlinear MPC Controller

Related Examples
• “Control of Quadrotor Using Nonlinear Model Predictive Control” on page 9-141
• “Control Quadruple-Tank Using Passivity-Based Nonlinear MPC” on page 9-182

More About
• “Nonlinear MPC” on page 9-2
• “Specify Prediction Model for Nonlinear MPC” on page 9-5
• “Specify Cost Function for Nonlinear MPC” on page 9-13

9-29
9 Nonlinear MPC

Configure Optimization Solver for Nonlinear MPC


By default, nonlinear MPC controllers solve a nonlinear programming problem using the fmincon
function with the SQP algorithm, which requires Optimization Toolbox software. Alternatively, you
can specify a continuation/generalized minimum residual (C/GMRES) solver or your own custom
nonlinear solver, neither of which require Optimization Toolbox software.

Solver Decision Variables


For nonlinear MPC controllers at time tk, the nonlinear optimization problem uses the following
decision variables:

• Predicted state values from time tk+1 to tk+p. These values correspond to rows 2 through p+1 of
the X input argument of your cost and constraint functions, where p is the prediction horizon.
• Predicted manipulated variables from time tk to tk+p-1. These values correspond to the manipulated
variable columns in rows 1 through p of the U input argument of your cost and constraint
functions.

Therefore, the number of decision variables NZ is equal to p(Nx+Nmv) + 1, Nx is the number of states,
Nmv is the number of manipulated variables, and the +1 accounts for the global slack variable.

Specify Initial Guesses


A properly configured standard linear MPC optimization problem has a unique solution. However,
nonlinear MPC optimization problems often allow multiple solutions (local minima), and finding a
solution can be difficult for the solver. In such cases, it is important to provide a good starting point
near the global optimum.

During closed-loop simulations, it is best practice to warm start your nonlinear solver. To do so, use
the predicted state and manipulated variable trajectories from the previous control interval as the
initial guesses for the current control interval. In Simulink, the Nonlinear MPC Controller block is
configured to use these trajectories as initial guesses by default. To use these trajectories as initial
guesses at the command line:

1 Return the opt output argument when calling nlmpcmove. This nlmpcmoveopt object contains
any run-time options you specified in the previous call to nlmpcmove. It also includes the initial
guesses for the state (opt.X0) and manipulated variable (opt.MV0) trajectories, and the global
slack variable (opt.Slack0).
2 Pass this object in as the options input argument to nlmpcmove for the next control interval.

These command-line simulation steps are best practices, even if you do not specify any other run-time
options.

Configure fmincon Options


By default, nonlinear MPC controllers optimize their control move using the fmincon function from
the Optimization Toolbox. When you first create your controller, the
Optimization.SolverOptions property of the nlmpc object contains the standard fmincon
options with the following nondefault settings:

• Use the SQP algorithm (SolverOptions.Algorithm = 'sqp')

9-30
Configure Optimization Solver for Nonlinear MPC

• Use objective function gradients (SolverOptions.SpecifyObjectiveGradient = 'true')


• Use constraint gradients (SolverOptions.SpecifyConstraintGradient = 'true')
• Do not display optimization messages to the command window (SolverOptions.Display =
'none')

These nondefault options typically improve the performance of the nonlinear MPC controller.

You can modify the solver options for your application. For example, to specify the maximum number
of solver iterations for your application, set SolverOptions.MaxIter. For more information on the
available solver options, see fmincon.

In general, you should not modify the SpecifyObjectiveGradient and


SpecifyConstraintGradient solver options, since doing so can significantly affect controller
performance. For example, the constraint gradient matrices are sparse, and setting
SpecifyConstraintGradient to false would cause the solver to calculate gradients that are
known to be zero.

Configure C/GMRES Solver Options


The C/GMRES method is another built-in option for optimization. The computational efficiency and
convergence properties of the C/GMRES method are particularly useful when applied to large scale
systems and systems that exhibit nonlinear and non-convex constraints.

To use the C/GMRES method to solve multistage nonlinear MPC problems, specify the
Optimization.Solver property of your multistage nonlinear MPC object as "cgmres". When you
do so, the software stores a default C/GMRES options object in the Optimization.SolverOptions
property of your multistage MPC object.

The C/GMRES options object has the following properties, which you can modify using dot notation.

• BarrierParameter — Parameter barrier value. This is a positive scalar representing the


strength of the penalty term added to the constraints in the barrier function method for nonlinear
model predictive control. The penalty term is used to penalize lower and upped bounds constraint
violations. The default value is 0.1.
• Display — Level of display. This is a string or character vector specified as either "iter" or
"none". Use "iter" to display solver information at every iteration, and use "none" to suppress
any solver display. The default value is "none".
• FiniteDifferenceStepSize — Step size used for finite differences. This is a positive scalar
representing the step size that the forward finite difference scheme uses to approximate the
Jacobian in the optimization problem. A larger step size can result in faster convergence but may
also lead to numerical instability. The default value is 1e-8.
• MaxIterations — Maximum number of iterations allowed. This is a positive integer representing
the maximum number of inner-loop iterations allowed for the solver. The default value is 100.
• Restart — Number of outer-loop iterations. This is a nonnegative integer representing the
maximum number of outer-loop iterations for the solver. The default value is 10.
• StabilizationParameter — Stabilization parameter. This is a positive scalar representing a
forcing term that you can use to control the step size and improve the numerical stability of the
solver.

In inexact Newton methods, the Newton direction is typically approximated using an iterative
linear solver, such as the conjugate gradient method or the GMRES method. However, due to

9-31
9 Nonlinear MPC

computational limitations or other factors, the iterative solver may not find an exact solution to
the linear system within a specified tolerance. The forcing term is introduced to compensate for
the inexactness of the Newton direction. It adjusts the step size taken in each iteration to ensure
convergence, even when the Newton direction is not accurate enough. The forcing term can be
viewed as a trust region radius that limits the step size based on the accuracy of the Newton
direction. Therefore a decrease of the stabilization parameter normally leads to a decrease of the
step size.

If the StabilizationParameter is too large, it may cause overcorrection and oscillations,


leading to slow convergence or even divergence. On the other hand, if the
StabilizationParameter is too small, it may result in slow convergence as the step size is
overly conservative. To enhance algorithm convergence, it is advisable to select a
StabilizationParameter value of 1/Ts, where Ts represents the model sampling time. This
parameter should not exceed 2/Ts.

The default value is 1e3.


• TerminationTolerance — Termination tolerance. This is a positive scalar representing the
termination tolerance for the solver. The solver stops when the relative error between two
consecutive iterations is less than the termination tolerance. The default value is 1e-6.

For an example on how to use the C/GMRES solver, see “Control Robot Manipulator Using C/GMRES
Solver” on page 9-36.

Specify Custom Solver


As an alternative to the fmincon function and C/GMRES method, you can specify your own custom
nonlinear solver. To do so, create a custom wrapper function that converts the interface of your solver
function to match the interface expected by the nonlinear MPC controller. Your custom function must
be a MATLAB script or MAT-file on the MATLAB path. For an example that shows a template custom
solver wrapper function, see “Optimizing Tuberculosis Treatment Using Nonlinear MPC with a
Custom Solver” on page 9-97.

You can use the Nonlinear Programming solver developed by Embotech AG to simulate and generate
code for nonlinear MPC controllers. For more information, see “Implement MPC Controllers Using
Embotech FORCESPRO Solvers” on page 10-73.

To configure your nlmpc object to use your custom solver wrapper function, set its
Optimization.CustomSolverFcn property in one of the following ways:

• Name of a function in the current working folder or on the MATLAB path, specified as a string or
character vector

Optimization.CustomSolverFcn = "myNLPSolver";
• Handle to a function in the current working folder or on the MATLAB path

Optimization.CustomSolverFcn = @myNLPSolver;

Your custom solver wrapper function must have the signature:

function [zopt,cost,flag] = myNLPSolver(FUN,z0,A,B,Aeq,Beq,LB,UB,NLCON)

This table describes the inputs and outputs of this function, where:

9-32
Configure Optimization Solver for Nonlinear MPC

• NZ is the number of decision variables.


• Mcineq is the number of linear inequality constraints.
• Mceq is the number of linear equality constraints.
• Ncineq is the number of nonlinear inequality constraints.
• Nceq is the number of nonlinear equality constraints.

Argument Input/Output Description


FUN Input Nonlinear cost function to minimize, specified as a handle to a
function with the signature:

[F,G] = FUN(z)

and arguments:

• z — Decision variables, specified as a vector of length NZ.


• F — Cost, returned as a scalar.
• G — Cost function gradients with respect to the decision
variables, returned as a column vector of length NZ, where
G i = ∂F/ ∂z i .
z0 Input Initial guesses for decision variable values, specified as a vector of
length NZ
A Input Linear inequality constraint array, specified as an Mcineq-by-NZ
array. Together, A and B define constraints of the form A ⋅ z ≤ B.
B Input Linear inequality constraint vector, specified as a column vector of
length Mcineq. Together, A and B define constraints of the form
A ⋅ z ≤ B.
Aeq Input Linear equality constraint array, specified as an Mceq-by-NZ array.
Together, Aeq and Beq define constraints of the form
Aeq ⋅ z = Beq.
Beq Input Linear equality constraint vector, specified as a column vector of
length Mceq. Together, Aeq and Beq define constraints of the form
Aeq ⋅ z = Beq.
LB Input Lower bounds for decision variables, specified as a column vector
of length NZ, where LB i ≤ z i .
UB Input Upper bounds for decision variables, specified as a column vector
of length NZ, where z i ≤ UB i .

9-33
9 Nonlinear MPC

Argument Input/Output Description


NLCON Input Nonlinear constraint function, specified as a handle to a function
with the signature:

[cineq,c,Gineq,Geq] = NLCON(z)

and arguments:

• z — Decision variables, specified as a vector of length NZ.


• cineq — Nonlinear inequality constraint values, returned as a
column vector of length Ncineq.
• ceq — Nonlinear equality constraint values, returned as a
column vector of length Nceq.
• Gineq — Nonlinear inequality constraint gradients with respect
to the decision variables, returned as an NZ-by-Ncineq array,
where Gineq i, j = ∂cineq j / ∂z i .
• Geq — Nonlinear equality constraint gradients with respect to
the decision variables, returned as an NZ-by-Nceq array, where
Geq i, j = ∂ceq j / ∂z i .
zopt Output Optimal decision variable values, returned as a vector of length NZ.
cost Output Optimal cost, returned as a scalar.
flag Output Exit flag, returned as one of the following:

• 1 — Optimization successful (first order optimization conditions


satisfied)
• 0 — Suboptimal solution (maximum number of iterations
reached)
• Negative value — Optimization failed

When you implement your custom solver function, it is best practice to have your solver use the cost
and constraint gradient information provided by the nonlinear MPC controller.

If you are unable to obtain a solution using your custom solver, try to identify a special condition for
which you know the solution, and start the solver at this condition. If the solver diverges from this
initial guess:

• Check the validity of the state and output functions in your prediction model.
• If you are using a custom cost function, make sure it is correct.
• If you are using the standard MPC cost function, verify the controller tuning weights.
• Make sure that all constraints are feasible at the initial guess.
• If you are providing custom Jacobian functions, validate your Jacobians using validateFcns.

See Also
Functions
fmincon | validateFcns

Objects
nlmpc

9-34
Configure Optimization Solver for Nonlinear MPC

Related Examples
• “Optimizing Tuberculosis Treatment Using Nonlinear MPC with a Custom Solver” on page 9-97

More About
• “Nonlinear MPC” on page 9-2
• “Specify Cost Function for Nonlinear MPC” on page 9-13

9-35

You might also like