1.6. Solving

solve is the gateway between a parsed model and everything else. You pass it a model object and a handful of options; you get back a solved model and a return code. This chapter is the reference for the option surface, the return-code discipline, and the diagnostic protocol when a solve fails.

1.6.1. The signature

[m, retcode] = solve(m, name = value, name = value, ...);

The first input is a model object. Subsequent arguments are name-value pairs validated by an arguments block on solve.

The first output is the model object with the solution attached; downstream methods (irf, simulate, estimate, filter, …) consume it. The second output is the retcode – always capture it and always check it.

1.6.2. The retcode pattern

The retcode is the single source of truth about whether the solve succeeded:

[m, retcode] = solve(m);
assert(retcode == 0, decipher(retcode));
  • retcode == 0 – the model is solved.

  • retcode > 0 – the solve failed in a specific, named way.

  • decipher(retcode) returns the human-readable explanation.

Never read the model object’s solution fields without first checking retcode. A non-zero retcode can leave the solution empty or partially populated; downstream methods will then return empty results or raise unrelated errors.

A complete list of return codes appears at the end of this chapter.

1.6.3. Picking a solver

The solver option selects the underlying algorithm. For constant-parameter models RISE picks a sensible default. For switching models it defaults to mfi (functional iteration). You may force a specific solver by prefixing the name with +:

m = solve(m, solver = '+mn');     % force Newton, no auto-pick

With the solver option left empty, RISE makes the choice at every solve, from the system it solves: rise_1 when every regime has the same first-order system (outside discretion), mfi otherwise. The solver used is recorded with the solution, in m.model_data.state_space{1}.solver, and print_solution names it. m.model_data.options.solver{1} keeps what you set, so a model re-solved at other parameters chooses again.

The available solvers:

Name

Family

Notes

mfi

Functional iteration (switching default)

Cheapest per iteration. Can miss solutions where the operator is not a contraction; see the diagnostic protocol below.

mafia

Multisecant-accelerated functional iteration

Iterates the same map as mfi with safeguarded, windowed Anderson acceleration and no Jacobian.

mn

Newton (switching), no Kronecker

Robust to non-contraction. Use when mfi returns retcode 21.

mnk

Newton (switching), with Kronecker

Same robustness as mn with a different inner solve; sometimes faster on larger systems.

mfi_full, mn_full, mnk_full

Full (non-sparse) variants

Use when sparsity exploitation in the standard variants causes numerical issues.

fwz

Farmer-Waggoner-Zha Newton

Their algorithm; sometimes finds solutions the others miss, sometimes the reverse.

dsge_groebner

Groebner-basis all-solutions

Finds every solution. Can be very slow (minutes to never) on non-trivial models. Do not include in a default diagnostic sweep.

dsge_udc

Undetermined coefficients

For switching models.

dsge_schur

Schur decomposition

Only with the Maih-Waggoner perturbation strategy.

rise_1

Constant-parameter default

Generalized Schur / QZ decomposition.

klein

Klein’s method

Constant-parameter; classical reference algorithm.

cr, cyclic_reduction

Cyclic reduction

Constant-parameter.

AIM

AIM solver

Constant-parameter.

A user-defined solver – a function handle with a specific signature – is also accepted; see the solve doc-comment for the required inputs and outputs.

1.6.4. Bound arguments for a user solver

A callback may be named by a character vector or a function handle. To bind payloads, put the callback and its arguments in an inner cell, then pair that cell with the solver options:

specification={{@my_solver,configuration,weights},struct('MaxIter',10)};
[m,retcode]=solve(m,'solver',specification);

The callback receives the standard six inputs Gplus01,A0,Aminus,B,Q,steady_state, followed by configuration,weights in that order, unchanged. The outer options struct is distinct from these bound arguments; it is not automatically appended to the callback inputs. If a callback needs options, bind the required value explicitly. A character name can replace @my_solver with the same payload contract. See the bounded example in WorkingWithAModel/user_solver_arguments.

1.6.5. Solver options

solver may be a plain string or a two-element cell {name, opts} where opts is a struct that RISE passes through to the inner iterator. The fields use MATLAB-standard option names:

opts = struct( ...
    MaxIter        = 1e6, ...
    TolFun         = 1e-10, ...
    Display        = 'iter', ...
    ObjectiveLimit = 1e+12);

[m, retcode] = solve(m, solver = {'mn', opts});

Field

Default

Role

MaxIter

1000

Maximum number of iterations.

TolFun

sqrt(eps)

Convergence tolerance on the residual.

Display

'off'

Set to 'iter' to print convergence per iteration.

ObjectiveLimit

1e+12

Treat the iteration as divergent if the residual exceeds this.

Note

The legacy toolbox accepted the same options under the names fix_point_maxiter, fix_point_TolFun, fix_point_verbose, fix_point_explosion_limit. The modern convention is the MATLAB-standard names above; the legacy names have been retired as user-facing options and passing them now errors as an unknown option.

1.6.6. Order of approximation

solve_order controls the order of the perturbation expansion:

m = solve(m, solve_order = 3);

Supported orders are 1 through 5. With the default symbolic derivatives (solve_derivatives_type = 'symbolic'), the derivatives are computed when the model is parsed, up to max_deriv_order (default 1), so an order above 1 requires that the model was parsed with at least the matching max_deriv_order:

m = dsge_model('mymodel.rs', max_deriv_order = 3);
m = solve(m, solve_order = 3);

Asking for a higher order than was parsed stops with an error that says so. Re-parse the model, or use derivatives that are computed when the model is solved, for whatever order is asked: 'automatic', 'numerical' or 'matlab' need no re-parsing:

m=solve(m,solve_order=3,solve_derivatives_type='automatic');

See Higher-order perturbation.

The derivatives of order \(k\) are held as sparse matrices with \(n_v^k\) columns, \(n_v\) being the number of variables the equations are differentiated with respect to (the leads, the current values, the lags and the shocks). A sparse matrix in MATLAB keeps one pointer for each column, however few of its entries are not zero: eight bytes per column, for each matrix and each pair of regimes. With 53 variables that is 63 MB at order 4 and 3.3 GB at order 5; with 300 variables, 216 MB at order 3 and 65 GB at order 4. Pick solve_order with the number of variables in mind: the orders above 3 are for models of a few tens of variables.

At order \(\geq 2\) a simulated path can diverge. Simulation pruning is an explicit opt-in for keeping such paths bounded, off by default and enabled through the simul_pruned option; see Forecasting and simulation.

1.6.7. Reducing the size of the system

solve_prune_hank_constants removes variables whose equations pin their first-order deviations at exactly zero at the evaluated steady state – saturated interpolation weights, slack multipliers, pinned policies, fixed aggregates – solves the smaller system, and re-inflates the solution with exact zeros. The answer is identical with the option on or off; only the cost of the solve changes. It is binary, parameter-free, off by default, and applies at first order. Its habitat is heterogeneous-agent models, where the expansion manufactures such constants in bulk; see Heterogeneous agents (HANK).

Note

Three distinct things in RISE are called “pruning”; they do not overlap.

  • solve_prune_hank_constants drops variables that are constant in the linearized model. First-order solving. Exact – the solution is unchanged.

  • simul_pruned drops explosive higher-order cross-terms when simulating an already-solved model. Coefficients untouched.

  • Distribution/state reduction (Reiter, Bayer–Lütticke) replaces the histogram by a low-dimensional parameterization. An approximation, available through the option solve_reduction (see Model reduction).

1.6.8. Optimal policy

Two orthogonal options control optimal-policy solutions:

Option

Values

Default

solve_policy_type

'ramsey', 'discretion' (case-insensitive)

'ramsey'

solve_policy_equilibrium

'OLE', 'MPE' (case-insensitive)

'OLE'

solve_policy_type controls commitment versus discretion:

  • 'ramsey' – full commitment; the planner re-optimizes only at t = 0.

  • 'discretion' – time-consistent / Markov-perfect policy; the planner re-optimizes every period.

solve_policy_equilibrium controls the equilibrium concept in multi-player games:

  • 'OLE' (open-loop equilibrium) – the classical Lagrangian formulation in which each player takes the opponent’s path as given.

  • 'MPE' (Markov-perfect equilibrium) – each player takes the opponent’s policy function as given.

All four combinations are supported. Both options are passed to solve – they are not declared in the model file. Loose commitment and stochastic replanning are also available through a small extension of this surface; see Optimal policy in the Modeling chapter for the model-side syntax.

1.6.9. Occasionally-binding constraints

The piecewise-linear (OccBin) solve of an occasionally-binding constraint is provided by the occbin.paradigm solve paradigm, activated through the solve_paradigm option:

C = { {'R>=1','ocb'} };   % constraint R >= 1 on the 'ocb' chain
m = set(m,'solve_paradigm',{@occbin.paradigm,'ref',1,'constraints',C});
m = solve(m);

The model-side construction (the binding chain and the convex-combination equation) is covered in Occasionally-binding constraints, and the paradigm interface – the constraint-cell grammar and its options – in Extending RISE through paradigms.

1.6.10. Perturbation strategy

solve_perturbation_type selects how a switching model is expanded when its parameters, and possibly its steady state, switch across regimes. The types, their syntax, what to expect from each and the guidance on choosing one are on their own page, Perturbation types for regime-switching models; in short:

Value

Strategy

'm' or {'m','curvature'} (default)

Self-consistent expansion points of the shock-free switching economy, with curvature higher orders. 'maih' is the same as 'm'.

{'m','joint'}

Joint fixed point over the expansion points and all orders.

{'m','isolated'}

Former plain M: isolated regime steady states with the existing sstate_unique behavior.

'maih_waggoner' or 'mw'

Maih and Waggoner (2018): the transition probabilities of all chains perturbed along with the shocks.

{'mw', mkv_list}

As above but only the chains in mkv_list have their probabilities perturbed.

'frwz'

Foerster, Rubio-Ramirez, Waggoner and Zha (2016): unique steady state at the ergodic mean of the parameters, perturbing all switching parameters (their naive form).

{'frwz', part_list}

As above but only the parameters in part_list are perturbed (their recommended form: the parameters that move the steady state).

'bm'

Barthelemy and Marx (2016): the P-weighted steady state of their Assumption 2, then the standard perturbation engine.

mkv_list and part_list may also be {'*none'}, {'*all'}, {'*all_but'}, or {'*all_but', 'v1', 'v2', ...}. The M variant comes second and settings follow it as name-value pairs, for example {'m','joint','Continuation',false}; no options object is used. The curvature variant is the default. The isolated variant takes no setting. Unknown, duplicate, inactive, and invalid settings are rejected. Continuation applies only to the joint variant.

The former keys ExpansionPoint and HigherOrders raise a migration error in new calls that names the positional form. Former separate-method spellings, cell payloads, and constructor objects also raise migration errors. Older saved models translate on loading. See Perturbation types for regime-switching models for all settings, defaults, saved-model migration, and the unchanged algorithms. When steady states or growth rates switch, the restrictions described in When the steady state or the growth rate switches, change the type apply to the explicit regime-steady-state configuration. They do not describe the new default.

Evaluate the model’s residuals with rise.engine.dsge_tools.accuracy.perturbation_report. The report uses the stored type, including its inline settings, unless types is supplied explicitly. Report timings include the public solve call.

1.6.11. Other options worth knowing

Option

Role

solve_linear

true to use more efficient steady-state algorithms when the model is truly linear.

solve_bgp

true to solve the model as non-stationary along a balanced growth path.

solve_derivatives_only

true to compute the symbolic derivatives but skip the solve. Useful for diagnostics.

solve_kill_g

true to kill off the growth element in the first-order solution.

solve_automatic_differentiator

Function handle for the automatic differentiator engine (default: @adolm.diff).

solve_user_defined_shocks

Struct describing non-Gaussian shock distributions. See the solve doc-comment.

solve_qz_criterium

Eigenvalue cutoff for constant-parameter QZ-based solvers (default: sqrt(eps)).

solve_replicate_future_regime

true (the default) to evaluate one derivative block per current regime instead of one per pair of regimes where the model’s structure allows it, filling the rest of each row by scaling with the transition probabilities. The answer is the same to rounding; only the cost changes. A block is reused only when the parser has proved that it is a multiple of the other: the transition probability depends neither on the variables nor on the perturbation parameter, the equations do not read the next period’s regime, and both pairs are evaluated at the same point. Maih-Waggoner, optimal-policy and endogenous-switching models therefore evaluate every pair. derivative_evaluations in the third output of solve counts the blocks evaluated, and false evaluates every pair. See the tutorial WorkingWithAModel/derivative_reuse/howto.m.

1.6.12. The diagnostic protocol when solve fails

When solve returns a non-zero retcode, work down this list in order; each step is cheap and rules out a class of causes:

  1. Read the retcode. decipher(retcode) gives the human-readable reason. If the message is specific (e.g. “Complex solution”, “Cannot take a log-expansion of a variable whose steady state is close to 0”), fix the model, not the solver settings.

  2. If retcode is 21 (“Maximum Number of iterations reached or multiple solutions”), raise the iteration cap first. It is the cheapest test and rules out simple truncation:

    opts = struct(MaxIter = 1e8);
    [m, retcode] = solve(m, solver = {'mfi', opts});
    

    If retcode == 0, you were just being truncated.

  3. If retcode is still 21, switch to a Newton solver. mfi’s functional iteration is not a contraction on every model; Newton solvers are robust to that and find fixed points mfi cannot reach:

    [m, retcode] = solve(m, solver = '+mn');
    % or
    [m, retcode] = solve(m, solver = '+mnk');
    
  4. If Newton returns retcode 25 (“System unstable”), the solution it found is not mean-square stable. That does not prove that this parameterization has no stable solution: the equations the solver solves have several solutions in general, even in a constant-parameter model, and Newton from another start can reach the stable one. Search from random starts with rise.engine.dsge_tools.stability.find_stable_solution (see Failure diagnosis: diagnose(m) and friends). If no start returns a mean-square-stable solution, investigate the calibration – vary the parameters and recheck where a stable solution is found.

  5. If retcode is 28 (“transition matrix must be diagonal”), an OBC chain has non-zero off-diagonal transition probabilities. Set them to zero – OBC switching is endogenous, not stochastic.

  6. If retcode is in the evaluation range (1-11), the failure is upstream of the solver. Read the message; it points at the steady-state file, the Jacobian, the transition matrix construction, or the parameter restrictions. Fix that before touching solve.

1.6.13. Return-code reference

The canonical table lives in utils.error.registry; this is the human-readable summary, in three groups.

Evaluation (pre-solve)

Code

Meaning

1

Steady state could not solve

11

Complex or nan steady-state residuals

2

NaNs in Jacobian

3

Problem in transition matrix

4

Parameter restrictions violated

5

Definitions are NaN, Inf, or imaginary

6

NaNs or Infs in planner objective

7

Bounds or restriction violation

8

The measurement-error covariance built from the stderr_* and corr_* parameters is not a valid covariance in some regime (a correlation outside [-1,1], correlations that cannot hold together, or a value that is not finite)

Solving

Code

Meaning

21

Maximum number of iterations reached or multiple solutions

210

Discretionary outer loop: max iterations reached

22

NaNs in solution or no solution

223

Complex solution

23

Explosion limit reached

230

Discretionary outer loop: explosion limit reached

24

Explosive solution

25

System unstable

251

DSGE-VAR solution: system unstable

26

VAR approximation to the DSGE failed

261

DSGE prior is not proper

262

DSGE-VAR solution: covariance matrix not positive definite

263

SVAR solution: matrix not invertible

27

Cannot take a log-expansion of a variable whose steady state is close to 0

28

For this solver the transition matrix must be diagonal

Filtering and likelihood (downstream of solve, listed for completeness)

Code

Meaning

301

Max iterations reached in Lyapunov solution

302

NaNs in Lyapunov solution

303

Explosion limit reached in Lyapunov solution

304

Failure of covariance in sigma-points determination

305

Covariance of forecast errors not positive definite

306

Unlikely parameter vector

307

NaN/Inf/complex in log prior

308

Inconsistent ergodic probabilities

309

Error in user-defined endogenous priors

310

NaNs or Inf in initial conditions for the state vector

311

NaNs or Inf in initial covariance matrix

312

NaN/Inf/complex likelihood

313

Forecast covariance positive definite but determinant = 0

1.6.14. Deferred higher-order fallback storage

After an iterative higher-order solve fails, the HOPS Sylvester path may try a second solver. If its state-transition blocks are deferred function handles, their sparsity is unknown until those handles are evaluated. The fallback now checks the total possible storage of all those square blocks before evaluating any handle. Above 1 GiB at eight bytes per possible entry, it skips that fallback and preserves the iterative solver’s failed iterate and nonzero return code. This is the same allowance used for all-solutions candidate storage.

This is a conservative admission check: a large block that would turn out to be sparse can also be refused. Already materialized blocks follow the existing fallback path. The threshold is separate from the reduced operator’s nonzero limit; neither is a bound on total process memory, intermediate allocations, or factorization workspaces. A nonzero return code remains a failed solve.

1.6.15. The retcode-aware pattern

The pattern is the same for every solve in a script:

[m, retcode] = solve(m, solver = '+mn');

if retcode ~= 0
    warning('solve failed: %s -- trying mfi with raised MaxIter', ...
            decipher(retcode));
    opts = struct(MaxIter = 1e8);
    [m, retcode] = solve(m, solver = {'mfi', opts});
end

assert(retcode == 0, decipher(retcode));
print_solution(m);

Always capture the retcode; always decipher on failure; do not read the solution fields until retcode == 0. See Teaser Example for the canonical worked solve on the standard documentation model.