1.3. Posterior maximization

The mode step of estimation – maximizing the posterior kernel (or, with flat priors, the likelihood) – is run by an optimizer. RISE ships several and lets you plug in your own; the same machinery is used by maximum-likelihood and Bayesian estimation, by optimal simple rules, and by indirect inference (all of which reduce to “minimize an objective over a bounded parameter vector”).

1.3.1. Choosing an optimizer

The optimizer is selected with the estim_optimizer option, either when building the model or when calling estimate:

m=set(m,estim_optimizer='fmincon');   % the default

mest=estimate(m,data=db,estim_priors=priors,estim_optimizer='wcsminwel');

To pass options to the chosen optimizer, give a cell: the optimizer first, then either one options struct or name/value pairs:

opt=optimset('fmincon');

opt.MaxIter=2000;

opt.TolFun=1e-8;

opt.TolX=1e-8;

opt.Display='iter';

mest=estimate(m,data=db,estim_priors=priors,estim_optimizer={'fmincon',opt});

mest=estimate(m,data=db,estim_priors=priors,estim_optimizer={'fmincon','MaxIter',2000});

The cell holds one optimizer: {'rise_lshade','wcsminwel'} is read as the optimizer rise_lshade with one unpaired option and stops with “arguments should come in pairs”.

Each optimizer reads the controls it knows (MaxIter, MaxFunEvals, MaxTime, TolFun, TolX, Display, MaxNodes, …) and ignores the others; see Options and their defaults below for which. estimate also reports which optimizer was used in print_estimation_results.

1.3.2. Bundled optimizers

  • MATLAB’s fmincon (the default; SQP), and fminunc / fminsearch – the unconstrained ones are used through bounded wrappers (fminunc_bnd / fminsearch_bnd) so that the parameter bounds are respected. patternsearch is available if you have the Global Optimization Toolbox.

  • wcsminwel – a robust quasi-Newton optimizer (Sims’s csminwel, with a restart heuristic) that copes well with awkward likelihood surfaces.

  • wnewrat – a Newton-type optimizer with a numerically computed Hessian.

  • wgmhmaxlik – a Metropolis-Hastings-based optimizer that explores the surface while climbing it (useful as a robust pre-conditioner before a local method). It runs at most MaxIter rounds (three by default), scales its proposals down to a finite MaxFunEvals, and stops when MaxFunEvals or MaxTime runs out, returning the best point it evaluated with exitflag 0.

  • bee_gate – the artificial bee-colony algorithm, a population-based global metaheuristic; see also Stochastic Global Optimization for the broader family of nature-inspired global optimizers.

  • a simulated-annealing optimizer.

  • blockwise_optimization – optimizes the parameters block by block, which helps when there are many of them.

These live in the m/optimizers/ folder of the toolbox.

Quick reference

Optimizer

Family

Scope

Uses Hessian

Parallel

Typical use case

fmincon

SQP / interior-point

local

approximated

via UseParallel

default; smooth, well-scaled likelihoods

fminunc_bnd

quasi-Newton (BFGS)

local

approximated

no

smooth, no constraints needed beyond bounds

fminsearch_bnd

Nelder-Mead simplex

local

no

no

very small problems; non-smooth objectives

patternsearch

direct search (GPS / MADS)

local

no

via Global Opt Toolbox

non-smooth / noisy objectives (requires Global Opt Toolbox)

wcsminwel

quasi-Newton (Sims) + restart

local

returned at end

no

robust on awkward DSGE likelihood surfaces; common default choice after fmincon

wnewrat

Newton with numerical Hessian (Ratto)

local

numerical

no

mode polishing after a global pass

wgmhmaxlik

MH-driven climb (Adjemian)

local-with-exploration

no

no

pre-conditioner before a local method on multi-modal surfaces

bee_gate

artificial bee colony

global (population)

finite-difference at end

yes

older global default; superseded by the +globalopt family

rise_lshade / rise_jso / rise_cma_es / rise_de / rise_abc / rise_aco / rise_bbo / rise_agsk / rise_mads

+globalopt family

global (population, or deterministic for rise_mads)

finite-difference at end

yes (per algorithm)

global mode search; see Stochastic Global Optimization for the per-algorithm philosophy and hyperparameters

simulated annealing (sa.gmhmaxlik)

thermal random walk

global

no

no

robust, slow; legacy

blockwise_optimization

dispatcher

same as inner

same as inner

same as inner

wraps any of the above to optimize parameters block-by-block; triggered automatically when estim_blocks is non-empty

Options and their defaults

Every optimizer receives one MATLAB-style options struct: MATLAB’s defaults for the chosen optimizer (those of fmincon for an optimizer that is not MATLAB’s), with the following fields set by the estimation (fmincon also gets Algorithm = 'sqp'):

Field

Meaning

Default

MaxIter

iteration cap

1000

MaxFunEvals

total function-eval cap

Inf

MaxTime

wall-clock cap (seconds)

7200

TolFun

objective tolerance

sqrt(eps)

TolX

step tolerance

sqrt(eps)

Display

'iter' / 'on' / 'off'

'iter'

MaxNodes

population size (population methods only)

20

ObjectiveLimit

early-stop floor for the objective

-1e12

TypicalX, MATLAB’s option, is not set by the estimation: fmincon and fminunc get yours when you give it (see Finite-difference steps below).

Each optimizer reads the fields it knows and ignores the rest; no field is enforced for all of them. fmincon, fminunc and fminsearch read MATLAB’s fields and have no wall-clock cap (MaxTime and MaxNodes are ignored); wcsminwel reads MaxIter and TolFun, wnewrat these and Display; bee_gate and the +globalopt family read MaxIter, MaxFunEvals and MaxTime.

The +globalopt family stops at the evaluation that would exceed MaxFunEvals or MaxTime, not at the end of a generation, and reports why in exitflag (1 its own goal, 0 a budget, -1 a manual abort). wcsminwel, wnewrat and wgmhmaxlik return exitflag = 1 when the optimizer’s own criterion is met, 0 at the iteration limit and -2 when the start or the end point has no usable objective (not finite, or outside the bounds). bee_gate needs MaxNodes of at least 3.

Algorithm-specific hyperparameters (F, CR for rise_de; sigma0 for rise_cma_es; limit for rise_abc; etc.) are not part of this common surface. They are documented per algorithm in Stochastic Global Optimization and can be threaded through estimate by writing a thin wrapper that closes over the desired hyper struct.

1.3.3. Points the model rejects

The posterior kernel rejects a point when a check fails: the steady state is not found, the model has no solution, the solution is not mean-square stable (with solve_check_stability true, the default), the filter breaks down, or a restriction is violated under estim_barrier. The samplers, the Hessian at the mode and log_posterior_kernel see such a point as before: it has the value estim_penalty and zero density, so the posterior does not change. The optimizer of the mode search sees more, so that a search does not stall against a flat wall.

Beyond the stability boundary, the kernel is continued. Where the kernel can be evaluated at a point that is not stable once the check is off (a VAR, whose likelihood needs no stationarity, or a switching DSGE whose filter starts from the diffuse factor), the search sees that value minus a penalty proportional to how far the point is from stability:

w * (radius - stability_criterion),   w = max(|log posterior|, estim_penalty_factor)

with radius the spectral radius of the second-moment operator. The objective is continuous at the boundary, so the finite-difference gradients of fmincon stay meaningful there. The continuation stops 0.1 beyond the criterion: further out, the graded values below apply, so that the search does not wander deep into the explosive region (where a VAR whose prior pulled hard on its constants went, to end at a poor stable point). The estimate must still be stable: when the search ends beyond the boundary, w is multiplied by 10 and the search restarts from there, three times at most. A search that still ends at a point that fails a check returns the best point it evaluated that passes every check, and says so in the list of issues. That point comes without the optimizer’s matrix (NaN under estim_hessian_type = 'optimizer'), which belongs to the end point. A search that evaluated no such point returns its end point, which fails a check, and the issues say so.

The restrictions an optimizer enforces are checks too. With estim_barrier false, fmincon (without estimation blocks) and bee_gate receive the nonlinear restrictions as constraints and enforce them; they are not in the objective. A point passes every check only where they hold: within fmincon’s ConstraintTolerance, with no violation at all for bee_gate. Under estim_barrier the kernel rejects any violation, and any restriction whose value is not a real finite number (code 4). With any other optimizer the restrictions are a penalty in the value, not a check.

Elsewhere, feasibility first, graded. Where the kernel cannot be evaluated (no steady state, no solution, a covariance that is not positive definite), every rejected point is valued above every accepted point, and two rejected points are ranked:

  1. by how far the evaluation got: a point that fails in the filter is better than one that fails the stability check, which is better than one with no solution, which is better than one that fails earlier (its steady state, its derivatives, its prior, its restrictions);

  2. within that phase, by how far the point is from passing the check that rejected it, when the check can say:

    Rejection (code)

    Measure

    steady state not found (1)

    the largest residual at the steady-state solver’s best point, above the acceptance tolerance

    a VAR regime without steady state: a unit root with a drift (21)

    the residual of its least-squares steady state, relative to the constant

    wrong number of stable roots, constant-parameter solvers (21, 24)

    the distance to the unit circle of the root that would have to cross it

    fixed-point solvers of switching models out of iterations (21)

    the residual of their last iterate

    not mean-square stable (25), where the kernel cannot be continued

    the radius above stability_criterion

    reduced-form VAR covariance not positive definite (264)

    minus its smallest eigenvalue, relative to its largest

    restrictions violated under estim_barrier (4)

    the sum of the violations

    NaN, Inf or complex values, a failed derivative, definition, transition matrix, Lyapunov equation or filter, a singular A0, a prior density that is not finite

    none: a wall, the top of its phase

A search that starts in, or wanders into, the rejected region is thus driven back to the accepted one, and a search that has seen an accepted point never settles among rejected ones.

Bounds are not penalized: the optimizers respect them. fmincon takes lb/ub (its finite differences included); fminunc, fminsearch and wcsminwel search unbounded coordinates that map inside the bounds (log or logit, one map for all of them, utils.optim.bounded_map: a start on a bound, a narrow interval and a fixed parameter with equal bounds included: a start on a bound is moved inside by sqrt(eps)*max(1,|bound|), at most to the middle of the interval, and the map back is anchored at the nearer bound and kept inside it; with this map and the optimizers’ default finite differences, an interval much narrower than its magnitude cannot be resolved: at the middle of [1, 1+1e-10], csminwel’s step moves the parameter by about 0.68 units of rounding and fminunc’s by about 0.0017, while larger steps or another scaling of the coordinate could resolve it); wnewrat projects its points onto them; wgmhmaxlik never evaluates a proposal outside them; bee_gate and the +globalopt family bring their candidates back inside; the blockwise optimization gives each block its bounds, and searches mapped coordinates with fminunc and fminsearch. A user-defined optimizer must respect the bounds itself.

1.3.4. Finite-difference steps

When the posterior of a reduced-form VAR on the direct likelihood route qualifies, fmincon and fminunc receive its exact score instead of finite differences of the objective: see Exact score of switching VARs. The rest of this section is about the searches that difference the objective.

fmincon differentiates the objective with the step FiniteDifferenceStepSize*max(|x|,TypicalX). With MATLAB’s default, TypicalX = 1, that is an absolute 1.5e-8 for any parameter below 1: far too coarse for a residual variance of 1e-5 (data in decimals), whose gradient it gets wrong by orders of magnitude.

The estimation sets no TypicalX: the steps are fmincon’s own. Give TypicalX (one entry per estimated parameter) to choose them yourself; fminunc takes it in its bounded coordinates (a parameter without bounds is its own coordinate), and the blockwise optimization gives its fmincon and fminunc children the entries of their block. RISE’s own optimizers (wcsminwel, wnewrat) do not read TypicalX and refuse it. An automatic TypicalX from the scale of each parameter was tried and dropped: on data in thousandths it ended the search at a worse mode than fmincon’s default steps. Resolving the derivatives of small-scale parameters is an open problem.

1.3.5. Where a switching search starts

A regime-switching model, DSGE or VAR, whose start does not distinguish the regimes starts its search from the mode of its constant-parameter version. The start does not distinguish the regimes when every switching parameter has the same start value in every state of its chain: the usual case, with the starts of the priors or the OLS seeds of a VAR.

  1. The constant-parameter version is searched first: every switching parameter tied across the states of its chain, the transition probabilities held at their start values (with all regimes equal, the likelihood does not depend on them), with the same kernel, checks and optimizer.

  2. At that mode the regimes are equal, and the switching likelihood is flat in the transition probabilities and symmetric in the regime differences: its gradient vanishes there. The regimes are separated, deterministically. The parameter of the state of rank r among k moves by delta*s*(2*(r-1)/(k-1)-1), from -delta*s to +delta*s. s is the smaller of the parameter’s scale (above) and its posterior standard deviation in the constant-parameter version (the curvature at its mode): the prior scale alone is not enough, since a VAR coefficient under the default flat prior has scale 1. delta starts at 0.5, is halved while the model rejects the separated point, and is doubled while the log posterior rises along the separation (five times at most).

  3. The states are ranked by the medians of their priors (the ordering the priors imply), and by their index where those are equal or where the priors imply no ordering at all. There is one start, and one switching search: whether it reaches the highest mode is the optimizer’s business, not the start’s.

The estimation blocks (estim_blocks) apply to the constant-parameter search too: each block becomes the tied coordinates that move its parameters (a block of transition probabilities only drops out).

A start that distinguishes the regimes is the user’s and is kept: prior starts or parameter values that differ across states, a start from a previous mode (estim_start_from_mode), and estim_svar_start = 'concentrated', whose start perturbs the switching blocks. What happened is recorded in posterior_maximization.constant_start (applied, reason, log_post_constant, separation, ordering, log_post_start, log_post_mode, time and funevals). The stage costs one more search, in fewer coordinates, and the evaluations of the separation. The integrated-lags search (estim_svar_integrate_lags) has its own start and does not run it.

1.3.6. Running several optimizers in turn

A common strategy is to locate the right basin with a global search and then polish the mode with a fast local method. estim_optimizer holds a single optimizer, so run estimate once per optimizer, each call starting from the mode the previous one found (estim_start_from_mode = true):

mglob=estimate(m,data=db,estim_priors=priors,estim_optimizer='rise_lshade');

mest=estimate(mglob,estim_optimizer='wcsminwel',estim_start_from_mode=true);

Each call prints its own current run time and the cumulative total time since the first call started. The cumulative interval includes time between calls. Both clocks are stored in estimation.posterior_maximization; see Estimation for the fields and their units. The current interval ends before final filtering and smoothing, at the same boundary as the cumulative interval.

1.3.7. User-defined optimizers

estim_optimizer may also be a function (a function name or a handle) implementing RISE’s optimizer interface:

[x,f,exitflag,H]=myOptimizer(objfun,x0,lb,ub,options)

where objfun(x) returns the value to minimize, x0 is the starting point, lb/ub the bounds, options the options struct, and H the Hessian of objfun at x (or []). The fourth output is that matrix, not a MATLAB-style output struct. Any of the bundled optimizers (e.g. wcsminwel.m) is a usable template.

Interface specification

The exact call of the estimation engine (rise.engine.estimation.optimization.estimation_engine):

[xfinal,ffinal,exitflag,H]=optimizer(fh,x0,lb,ub,options)

An optimizer with exactly three outputs is called as [xfinal,ffinal,exitflag]=optimizer(fh,x0,lb,ub,options); one with fewer is refused.

Inputs:

  • fh – function handle. The engine calls fval = fh(x) where x is a column vector inside [lb, ub]. RISE wraps the posterior kernel here, so fh returns a scalar to be minimized (the negative log posterior). The wrapper handles all the bookkeeping (parameter assignment, model resolve, filter, prior, penalties for general restrictions); the optimizer just sees a scalar objective on a box.

  • x0 – starting point as a column vector, dimension n.

  • lb, ub – column vectors of lower and upper bounds, also dimension n. RISE guarantees lb <= x0 <= ub.

  • options – struct with the MATLAB-style fields listed in the Options and their defaults table above. Optimizers should read what they understand and ignore the rest. The options given in the estim_optimizer cell are already merged in: with estim_optimizer = {@myOptimizer, 'MaxFunEvals', 1000}, options.MaxFunEvals is 1000. Nothing is passed after options.

Outputs:

  • xfinal – column vector of length n with the best parameter vector found. Must satisfy lb <= xfinal <= ub.

  • ffinal – scalar value fh(xfinal).

  • exitflag – integer, in the style of MATLAB’s optimizers (1 = converged successfully, 0 = budget exhausted, negative = failed).

  • H – n x n matrix, the Hessian of fh at xfinal, or [] if the optimizer has none. It must be the Hessian itself, not its inverse and not a struct. It is used only under estim_hessian_type = 'optimizer', where it gives the standard errors ([] or a matrix of the wrong size then gives NaN). Under the default, 'fd', the estimation computes the Hessian at the mode by finite differences whatever the optimizer returns, and keeps H in posterior_maximization.hessian_optimizer.

RISE-added options

The options struct is a MATLAB-style optimization options struct with the fields of the table above. For any optimizer other than fmincon, RISE also puts the nonlinear-restriction function in options.nonlcon (fmincon gets it as its own argument). The estimation call has a separate option, estim_blocks: when non-empty, the engine routes the user-chosen optimizer through blockwise_optimization, which calls the optimizer once per parameter block. The optimizer sees a smaller x0 / lb / ub corresponding to one block at a time, but its own interface is unchanged.

Manual stopping is honored by every optimizer in the +globalopt family (rise_lshade etc.): drop a file named ManualStoppingFile.txt in the working directory and the next iteration boundary returns the current best.

Minimal worked example

A trivial user-defined optimizer that wraps fmincon and prints a banner before delegating. The pattern is the same for anything more elaborate:

function [xfinal, ffinal, exitflag, H] = myOptimizer(fh, x0, lb, ub, options, varargin)

fprintf('myOptimizer: %d parameters, MaxIter=%d\n', ...
        numel(x0), options.MaxIter);

opt = optimoptions('fmincon', ...
    'MaxIterations',           options.MaxIter, ...
    'MaxFunctionEvaluations',  options.MaxFunEvals, ...
    'OptimalityTolerance',     options.TolFun, ...
    'StepTolerance',           options.TolX, ...
    'Display',                 options.Display);

[xfinal, ffinal, exitflag, ~, ~, ~, H] = ...
    fmincon(fh, x0, [], [], [], [], lb, ub, [], opt);

end

Plug in by name (the function must be on the MATLAB path) or by handle:

m=estimate(m,data=db,estim_priors=priors,estim_optimizer=@myOptimizer);

Any of the bundled wrappers (wcsminwel.m, wnewrat.m, wgmhmaxlik.m, bee_gate.m) is a fuller worked example of the same pattern, including the translation between RISE option names and the underlying solver’s argument list.