Troubleshooting your model and Safe Mode

In order to obtain the optimal solution to your control problem, DynaProg uses your system and cost function(s) with n-dimensional arrays. Some operations may produce unintended results. In order to avoid these issues, you can either follow this troubleshooting guide or enable Safe Mode.

Troubleshooting your model function

In the backward phase of the control optimization algorithm, DynaProg uses your system and cost function to evaluate updated state values, stage costs and unfeasibilities. When it does so, it passes state and control variables passes as an input in the form of n-dimensional arrays. In these arrays, each dimension is assigned to one specific state or control variable.
Consider an optimization problem with two state variables and two control variables, which are discretized on computational grids having N_(x_1), N_(x_2), N_(u_1) and N_(u_2) elements respectively. The system and cost function is defined as:
function [x_next, stage_cost, unfeas] = sysfun(x, u, ~)
a = u{1} .* u{2};
x_next{1} = x{1} + a .* dt;
x_next{2} = x{1} + (x{1} - x{2}) .* dt;
 
stage_cost = u{1};
 
unfeas = [];
end
In the backward phase, DynaProg passes as inputs:
As MATLAB evaluates each line of the system and cost function, it will expand the size of the resulting array accordingly. Therefore:
For this reason, you must ensure that all operations that you use in your system and cost function are consistent in their output when operating on n-dimensional arrays.
Example of such operations are:
Example of operations that are inconsistent are:
To see some examples of troublesome operations, and how to fix them, see this example.

Safe Mode

Safe Mode is an alternative way of dealing with the system and cost function which is meant to automatically handle potentially troublesome operations, at the cost of increased optimization time.
By default, Safe Mode is disabled. To enable Safe Mode, specify it in the constructor after the mandatory positional arguments:
prob = DynaProg(StateGrid, StateInitial, StateFinal, ControlGrid, Nstages, SysName, 'SafeMode', true);
or set the SafeMode property to true on an existing problem structure.
prob.SafeMode = true;
Safe Mode forces DynaProg to always pass the state variables, control variables, exogenous inputs and intermediate variables as full n-dimensional arrays having size where N_x_i and N_u_j are the number of grid points that discretize the state variable x_i and the control variable u_j andNX and NUare the number of state and control variables.
This effectively avoids all errors related to array indexing, but it means that many repetitive, unnecessary computations are performed. Note, however, that Safe Mode may not prevent all sorts of errors that may arise when you run the model function.