|
| 1 | +# Callbacks |
| 2 | + |
| 3 | +NLSolvers.jl supports user-defined callbacks that are invoked after every iteration of any optimization solver. Callbacks let you monitor progress, log intermediate state, build a convergence trace, or stop the solver early based on custom criteria. |
| 4 | + |
| 5 | +## Basic usage |
| 6 | + |
| 7 | +A callback is any function (or callable object) that takes a single `info` argument and returns a `Bool`: |
| 8 | + |
| 9 | +```julia |
| 10 | +using NLSolvers |
| 11 | + |
| 12 | +callback = info -> begin |
| 13 | + println("iter=$(info.iter), f=$(info.state.fz)") |
| 14 | + return false # continue optimization |
| 15 | +end |
| 16 | + |
| 17 | +solve(prob, x0, LineSearch(BFGS()), |
| 18 | + OptimizationOptions(callback = callback)) |
| 19 | +``` |
| 20 | + |
| 21 | +Returning `true` stops the solver early; returning `false` lets it continue. The default `callback = nothing` disables the mechanism with zero overhead. |
| 22 | + |
| 23 | +## What the callback receives |
| 24 | + |
| 25 | +The `info` argument is a `NamedTuple` with three fields: |
| 26 | + |
| 27 | +| Field | Type | Description | |
| 28 | +|---|---|---| |
| 29 | +| `iter` | `Int` | Current iteration count (1-based) | |
| 30 | +| `time` | `Float64` | Elapsed seconds since `solve` started | |
| 31 | +| `state` | `NamedTuple` | Solver-specific state (see below) | |
| 32 | + |
| 33 | +## Solver-specific `state` |
| 34 | + |
| 35 | +The contents of `info.state` depend on which solver is running. Use `haskey` if you write generic callbacks. |
| 36 | + |
| 37 | +### Line search solvers (BFGS, DBFGS, DFP, SR1, L-BFGS, CG, Gradient Descent, Newton) |
| 38 | + |
| 39 | +`state` is the internal `objvars` named tuple: |
| 40 | + |
| 41 | +| Field | Description | |
| 42 | +|---|---| |
| 43 | +| `x` | Previous iterate | |
| 44 | +| `fx` | Objective value at `x` | |
| 45 | +| `∇fx` | Gradient at `x` | |
| 46 | +| `z` | New iterate (after line search) | |
| 47 | +| `fz` | Objective value at `z` | |
| 48 | +| `∇fz` | Gradient at `z` | |
| 49 | +| `B` | Current Hessian (or inverse) approximation; `nothing` for L-BFGS/CG | |
| 50 | +| `Pg` | Preconditioned gradient if using a preconditioner; otherwise `nothing` | |
| 51 | + |
| 52 | +### Trust region solvers |
| 53 | + |
| 54 | +Same fields as line search, plus: |
| 55 | + |
| 56 | +| Field | Description | |
| 57 | +|---|---| |
| 58 | +| `Δ` | Current trust region radius | |
| 59 | +| `rejected` | `true` if the previous step was rejected by the trust region rule | |
| 60 | + |
| 61 | +### Nelder-Mead |
| 62 | + |
| 63 | +| Field | Description | |
| 64 | +|---|---| |
| 65 | +| `simplex_vector` | Vector of simplex vertices | |
| 66 | +| `simplex_value` | Function values at each vertex | |
| 67 | +| `x_centroid` | Centroid of the simplex (excluding the worst vertex) | |
| 68 | +| `nm_obj` | Convergence metric — standard deviation of `simplex_value` | |
| 69 | + |
| 70 | +### Simulated Annealing |
| 71 | + |
| 72 | +| Field | Description | |
| 73 | +|---|---| |
| 74 | +| `x_best` | Best point found so far | |
| 75 | +| `f_best` | Best objective value found so far | |
| 76 | +| `x_now` | Current state of the chain | |
| 77 | +| `f_now` | Objective value at `x_now` | |
| 78 | +| `temperature` | Current temperature | |
| 79 | + |
| 80 | +### Particle Swarm |
| 81 | + |
| 82 | +| Field | Description | |
| 83 | +|---|---| |
| 84 | +| `X` | Current particle positions | |
| 85 | +| `X_best` | Each particle's personal best | |
| 86 | +| `Fs` | Function values at `X` | |
| 87 | +| `Fs_best` | Function values at `X_best` | |
| 88 | +| `x` | Global best particle | |
| 89 | +| `best_f` | Global best objective value | |
| 90 | +| `swarm_f` | Convergence metric for the swarm | |
| 91 | + |
| 92 | +### Brent's method (univariate) |
| 93 | + |
| 94 | +| Field | Description | |
| 95 | +|---|---| |
| 96 | +| `x` | Current best point | |
| 97 | +| `fx` | Function value at `x` | |
| 98 | +| `a`, `b` | Current bracketing interval `[a, b]` | |
| 99 | +| `v`, `w` | Two previous iterates | |
| 100 | +| `fv`, `fw` | Function values at `v` and `w` | |
| 101 | + |
| 102 | +### Active Box (projected Newton) |
| 103 | + |
| 104 | +| Field | Description | |
| 105 | +|---|---| |
| 106 | +| `x` | Previous iterate | |
| 107 | +| `z` | New iterate | |
| 108 | +| `fz` | Objective value at `z` | |
| 109 | +| `∇fz` | Gradient at `z` | |
| 110 | +| `B` | Hessian approximation | |
| 111 | +| `activeset` | Boolean vector indicating active bound constraints | |
| 112 | + |
| 113 | +## Examples |
| 114 | + |
| 115 | +### Build a convergence trace |
| 116 | + |
| 117 | +```julia |
| 118 | +trace = Float64[] |
| 119 | +solve(prob, x0, LineSearch(BFGS()), |
| 120 | + OptimizationOptions( |
| 121 | + callback = info -> (push!(trace, info.state.fz); false), |
| 122 | + maxiter = 100, |
| 123 | + )) |
| 124 | +``` |
| 125 | + |
| 126 | +### Stop when the gradient is sufficiently small |
| 127 | + |
| 128 | +```julia |
| 129 | +gtol = 1e-6 |
| 130 | +solve(prob, x0, LineSearch(BFGS()), |
| 131 | + OptimizationOptions( |
| 132 | + callback = info -> norm(info.state.∇fz, Inf) < gtol, |
| 133 | + g_abstol = 0.0, # disable built-in g-tolerance so callback wins |
| 134 | + )) |
| 135 | +``` |
| 136 | + |
| 137 | +### Time-limited optimization |
| 138 | + |
| 139 | +```julia |
| 140 | +time_limit = 5.0 # seconds |
| 141 | +solve(prob, x0, LineSearch(BFGS()), |
| 142 | + OptimizationOptions(callback = info -> info.time > time_limit)) |
| 143 | +``` |
| 144 | + |
| 145 | +### Save iterates for plotting later |
| 146 | + |
| 147 | +Arrays in `info.state` (such as `z`, `∇fz`, `simplex_vector`) are aliases of live solver buffers — they will be overwritten on the next iteration. **Copy them if you need to retain them past the callback call.** |
| 148 | + |
| 149 | +```julia |
| 150 | +history = Vector{Vector{Float64}}() |
| 151 | +solve(prob, x0, LineSearch(BFGS()), |
| 152 | + OptimizationOptions( |
| 153 | + callback = info -> (push!(history, copy(info.state.z)); false), |
| 154 | + )) |
| 155 | +``` |
| 156 | + |
| 157 | +Scalar fields like `info.iter`, `info.time`, `info.state.fz` are values and do not need copying. |
| 158 | + |
| 159 | +## Performance |
| 160 | + |
| 161 | +The callback machinery has zero runtime overhead when `callback === nothing` (the default). The callback type is captured as a type parameter on `OptimizationOptions`, so the compiler eliminates the dispatch entirely. Passing a concrete callback function adds only the cost of calling that function once per iteration. |
0 commit comments