Insurance
Description of the problem
The insurance problem is a benchmark in optimal control inspired by health and financial economics. It consists of controlling insurance coverage, expenses, revenue, health, and utility over a fixed horizon to maximise expected utility. The system dynamics model the evolution of insurance participation, expenses, and auxiliary variables, while respecting bounds on all state and control variables. The controls represent health investments, insurance revenue, health outcomes, and utility contributions.
Mathematical formulation
The objective is to maximise expected utility:
\[\max_{I, m, x_3, h, R, H, U, dU/dR, P} \quad \int_0^{t_f} U(t) \, f_x(t) \, dt\]
where $f_x(t)$ is the probability density of illness events.
State, control, and auxiliary bounds
The variables are subject to:
\[\begin{aligned} \text{State bounds:} & \quad 0 \le I(t) \le 1.5, \quad 0 \le m(t) \le 1.5, \quad 0 \le x_3(t), \\ \text{Control bounds:} & \quad 0 \le h(t) \le 25, \\ \text{Auxiliary bounds:} & \quad 0 \le R(t), \quad 0 \le H(t), \quad 0.001 \le \frac{dU}{dR}(t), \quad 0 \le P. \end{aligned}\]
Initial and terminal conditions
\[(I, m, x_3)|_{t=0} = (0, 0.001, 0), \quad P - x_3(t_f) = 0\]
Dynamics
\[\dot{x}(t) = \begin{bmatrix} \dot{I}(t) \\[1mm] \dot{m}(t) \\[1mm] \dot{x}_3(t) \end{bmatrix} = \begin{bmatrix} (1 - \gamma t \, v'/dU/dR(t)) \, h(t) \\[1mm] h(t) \\[1mm] (1 + \sigma) I(t) f_x(t) \end{bmatrix}\]
with the expense transformation:
\[v = \frac{m(t)^{\alpha/2}}{1 + m(t)^{\alpha/2}}, \quad v' = \frac{\alpha}{2} \frac{m(t)^{\alpha/2 - 1}}{(1 + m(t)^{\alpha/2})^2}.\]
Algebraic / auxiliary constraints
\[\begin{aligned} R(t) &= w - P + I(t) - m(t) - \varepsilon(t), \\ H(t) &= h_0 - \gamma t (1 - v), \\ U(t) &= 1 - e^{-s R(t)} + H(t), \\ \frac{dU}{dR}(t) &= s \, e^{-s R(t)}, \\ f_x(t) &= \lambda e^{-\lambda t} + \frac{e^{-\lambda t_f}}{t_f}, \\ \varepsilon(t) &= k \frac{t}{t_f - t + 1}. \end{aligned}\]
These constraints encode revenue balance, health evolution, utility computation, and auxiliary relationships.
System parameters
Parameter | Symbol | Value | Description |
---|---|---|---|
Risk aversion | $\gamma$ | 0.2 | Health cost scaling |
Illness rate | $\lambda$ | 0.25 | Hazard parameter |
Baseline health | $h_0$ | 1.5 | Initial health level |
Weight factor | $w$ | 1 | Revenue baseline |
Sensitivity | $s$ | 10 | Utility sensitivity to revenue |
Exponent | $\alpha$ | 4 | Expense nonlinearity |
Expense rate | $k$ | 0 | Time-varying adjustment |
Shock | $\sigma$ | 0 | Auxiliary multiplier |
Final time | $t_f$ | 10 | s |
Qualitative behaviour
- The optimal strategy balances insurance coverage, health investment, and expenses to maximise utility under constraints.
- Revenue and health constraints link controls and states nonlinearly.
- The dynamics incorporate moral hazard effects and diminishing returns on expenses.
- Auxiliary variables track utility and revenue derivatives, ensuring consistent constraints.
Characteristics
- Nonlinear three-dimensional state dynamics with five control variables and one auxiliary.
- Fixed final time with state and control bounds.
- Models health insurance optimisation under ex post moral hazard and risk-sensitive utility.
- Serves as a benchmark for testing constrained nonlinear OCP solvers.
References
Martinon, P., Picard, P., & Raj, A. (2018). On the design of optimal health insurance contracts under ex post moral hazard. The Geneva Risk and Insurance Review, 43, 127–155. doi:10.1057/s10713-018-0034-y Provides a theoretical framework for optimal health insurance design under moral hazard, which inspired the benchmark problem formulation.
Bocop Repository: Insurance Example. github.com/control-toolbox/bocop/tree/main/bocop Contains the implementation of the insurance optimal control problem used for testing direct transcription methods and NLP solvers.
Numerical set-up
In this section, we prepare the numerical environment required to study the problem. We begin by importing the relevant Julia packages and then initialise the data frames that will store the results of our simulations and computations. These structures provide the foundation for solving the problem and for comparing the different solution strategies in a consistent way.
using OptimalControlProblems # to access the Beam model
using OptimalControl # to import the OptimalControl model
using NLPModelsIpopt # to solve the model with Ipopt
import DataFrames: DataFrame # to store data
using NLPModels # to retrieve data from the NLP solution
using Plots # to plot the trajectories
using Plots.PlotMeasures # for leftmargin, bottommargin
using JuMP # to import the JuMP model
using Ipopt # to solve the JuMP model with Ipopt
using Printf # to print
data_pb = DataFrame( # to store data about the problem
Problem=Symbol[],
Grid_Size=Int[],
Variables=Int[],
Constraints=Int[],
)
data_re = DataFrame( # to store data about the resolutions
Model=Symbol[],
Flag=Any[],
Iterations=Int[],
Objective=Float64[],
)
Metadata
The default number of time steps is:
metadata(:insurance)[:grid_size]
500
The default values of the parameters are:
metadata(:insurance)[:parameters]
Parameter = Value
------------------
t0 = 0.0000e+00
tf = 1.0000e+01
γ = 2.0000e-01
λ = 2.5000e-01
h0 = 1.5000e+00
w = 1.0000e+00
s = 1.0000e+01
k = 0.0000e+00
σ = 0.0000e+00
α = 4.0000e+00
I_l = 0.0000e+00
I_u = 1.5000e+00
m_l = 0.0000e+00
m_u = 1.5000e+00
h_l = 0.0000e+00
h_u = 2.5000e+01
R_l = 0.0000e+00
H_l = 0.0000e+00
U_l = 0.0000e+00
dUdR_l = 1.0000e-03
P_l = 0.0000e+00
I_t0 = 0.0000e+00
m_t0 = 1.0000e-03
x₃_t0 = 0.0000e+00
Initial guess
Before solving the problem, it is often useful to inspect the initial guess (sometimes called the first iterate). This guess is obtained by running the NLP solver with max_iter = 0
, which evaluates the problem formulation without performing any optimisation steps.
We plot the resulting trajectories for both the OptimalControl and JuMP models. Since both backends represent the same mathematical problem, their initial guesses should coincide, providing a useful consistency check before moving on to the optimised solution.
Click to unfold and see the code for plotting the initial guess.
function plot_initial_guess(problem)
# -----------------------------
# Build OptimalControl problem
# -----------------------------
docp = eval(problem)(OptimalControlBackend())
nlp_oc = nlp_model(docp)
ocp_oc = ocp_model(docp)
# Solve NLP with zero iterations (initial guess)
nlp_oc_sol = NLPModelsIpopt.ipopt(nlp_oc; max_iter=0)
# Build OptimalControl solution
ocp_sol = build_ocp_solution(docp, nlp_oc_sol)
# get dimensions
n = state_dimension(ocp_oc)
m = control_dimension(ocp_oc)
# -----------------------------
# Plot OptimalControl solution
# -----------------------------
plt = plot(
ocp_sol;
state_style=(color=1,),
costate_style=(color=1, legend=:none),
control_style=(color=1, legend=:none),
path_style=(color=1, legend=:none),
dual_style=(color=1, legend=:none),
size=(816, 220*(n+m)),
label="OptimalControl",
leftmargin=20mm,
)
# Hide legend for additional state plots
for i in 2:n
plot!(plt[i]; legend=:none)
end
# -----------------------------
# Build JuMP model
# -----------------------------
nlp_jp = eval(problem)(JuMPBackend())
# Solve NLP with zero iterations (initial guess)
set_optimizer(nlp_jp, Ipopt.Optimizer)
set_optimizer_attribute(nlp_jp, "max_iter", 0)
optimize!(nlp_jp)
# Extract trajectories
t_grid = time_grid(nlp_jp)
x_fun = state(nlp_jp)
u_fun = control(nlp_jp)
p_fun = costate(nlp_jp)
# -----------------------------
# Plot JuMP solution on top
# -----------------------------
# States
for i in 1:n
label = i == 1 ? "JuMP" : :none
plot!(plt[i], t_grid, t -> x_fun(t)[i]; color=2, linestyle=:dash, label=label)
end
# Costates
for i in 1:n
plot!(plt[n+i], t_grid, t -> -p_fun(t)[i]; color=2, linestyle=:dash, label=:none)
end
# Controls
for i in 1:m
plot!(plt[2*n+i], t_grid, t -> u_fun(t)[i]; color=2, linestyle=:dash, label=:none)
end
return plt
end
plot_initial_guess(:insurance)
Solving the problem
To solve an optimal control problem, we can rely on two complementary formulations: the OptimalControl
backend, which works directly with the discretised control problem, and the JuMP
backend, which leverages JuMP’s flexible modelling framework.
Both approaches generate equivalent NLPs that can be solved with Ipopt, and comparing them ensures consistency between the two formulations.
Before solving, we can inspect the discretisation details of the problem. The table below reports the number of grid points, decision variables, and constraints associated with the chosen formulation.
push!(data_pb,(
Problem=:insurance,
Grid_Size=metadata(:insurance)[:grid_size],
Variables=get_nvar(nlp_model(insurance(OptimalControlBackend()))),
Constraints=get_ncon(nlp_model(insurance(OptimalControlBackend()))),
))
Row | Problem | Grid_Size | Variables | Constraints |
---|---|---|---|---|
Symbol | Int64 | Int64 | Int64 | |
1 | insurance | 500 | 4009 | 3508 |
OptimalControl model
We first solve the problem using the OptimalControl
backend. The process begins by importing the problem definition and constructing the associated nonlinear programming (NLP) model. This NLP is then passed to the Ipopt solver, with standard options for tolerance and barrier parameter strategy.
# import DOCP model
docp = insurance(OptimalControlBackend())
# get NLP model
nlp_oc = nlp_model(docp)
# solve
nlp_oc_sol = NLPModelsIpopt.ipopt(
nlp_oc;
print_level=4,
tol=1e-8,
mu_strategy="adaptive",
sb="yes",
)
Total number of variables............................: 4009
variables with only lower bounds: 2005
variables with lower and upper bounds: 1503
variables with only upper bounds: 0
Total number of equality constraints.................: 3508
Total number of inequality constraints...............: 0
inequality constraints with only lower bounds: 0
inequality constraints with lower and upper bounds: 0
inequality constraints with only upper bounds: 0
Number of Iterations....: 87
(scaled) (unscaled)
Objective...............: -2.0592075947617858e+00 2.0592075947617858e+00
Dual infeasibility......: 2.1911962089697485e-09 2.1911962089697485e-09
Constraint violation....: 5.0235515747232284e-09 5.0235515747232284e-09
Variable bound violation: 2.2704477968016824e-40 2.2704477968016824e-40
Complementarity.........: 1.0094854529806641e-11 1.0094854529806641e-11
Overall NLP error.......: 5.0235515747232284e-09 5.0235515747232284e-09
Number of objective function evaluations = 89
Number of objective gradient evaluations = 88
Number of equality constraint evaluations = 89
Number of inequality constraint evaluations = 0
Number of equality constraint Jacobian evaluations = 88
Number of inequality constraint Jacobian evaluations = 0
Number of Lagrangian Hessian evaluations = 87
Total seconds in IPOPT = 2.316
EXIT: Optimal Solution Found.
JuMP model
We now repeat the procedure using the JuMP
backend. Here, the problem is reformulated as a JuMP model, which offers a flexible and widely used framework for nonlinear optimisation in Julia. The solver settings are chosen to mirror those used previously, so that the results can be compared on an equal footing.
# import model
nlp_jp = insurance(JuMPBackend())
# solve with Ipopt
set_optimizer(nlp_jp, Ipopt.Optimizer)
set_optimizer_attribute(nlp_jp, "print_level", 4)
set_optimizer_attribute(nlp_jp, "tol", 1e-8)
set_optimizer_attribute(nlp_jp, "mu_strategy", "adaptive")
set_optimizer_attribute(nlp_jp, "linear_solver", "mumps")
set_optimizer_attribute(nlp_jp, "sb", "yes")
optimize!(nlp_jp)
Total number of variables............................: 4009
variables with only lower bounds: 2005
variables with lower and upper bounds: 1503
variables with only upper bounds: 0
Total number of equality constraints.................: 3508
Total number of inequality constraints...............: 0
inequality constraints with only lower bounds: 0
inequality constraints with lower and upper bounds: 0
inequality constraints with only upper bounds: 0
Number of Iterations....: 89
(scaled) (unscaled)
Objective...............: -2.0592075949520563e+00 2.0592075949520563e+00
Dual infeasibility......: 3.5007078055282814e-09 3.5007078055282814e-09
Constraint violation....: 2.4173274493222152e-09 2.4173274493222152e-09
Variable bound violation: 6.5203202272173760e-39 6.5203202272173760e-39
Complementarity.........: 1.0998158239592038e-11 1.0998158239592038e-11
Overall NLP error.......: 3.5007078055282814e-09 3.5007078055282814e-09
Number of objective function evaluations = 92
Number of objective gradient evaluations = 90
Number of equality constraint evaluations = 92
Number of inequality constraint evaluations = 0
Number of equality constraint Jacobian evaluations = 90
Number of inequality constraint Jacobian evaluations = 0
Number of Lagrangian Hessian evaluations = 89
Total seconds in IPOPT = 1.151
EXIT: Optimal Solution Found.
Numerical comparisons
In this section, we examine the results of the problem resolutions. We extract the solver status (flag), the number of iterations, and the objective value for each model. This provides a first overview of how each approach performs and sets the stage for a more detailed comparison of the solution trajectories.
# from OptimalControl model
push!(data_re,(
Model=:OptimalControl,
Flag=nlp_oc_sol.status,
Iterations=nlp_oc_sol.iter,
Objective=nlp_oc_sol.objective,
))
# from JuMP model
push!(data_re,(
Model=:JuMP,
Flag=termination_status(nlp_jp),
Iterations=barrier_iterations(nlp_jp),
Objective=objective_value(nlp_jp),
))
Row | Model | Flag | Iterations | Objective |
---|---|---|---|---|
Symbol | Any | Int64 | Float64 | |
1 | OptimalControl | first_order | 87 | 2.05921 |
2 | JuMP | LOCALLY_SOLVED | 89 | 2.05921 |
We compare the solutions obtained from the OptimalControl and JuMP models by examining the number of iterations required for convergence, the $L^2$-norms of the differences in states, controls, and additional variables, and the corresponding objective values. Both absolute and relative errors are reported, providing a clear quantitative measure of the agreement between the two approaches.
Click to unfold and get the code of the numerical comparisons.
function L2_norm(T, X)
# T and X are supposed to be one dimensional
s = 0.0
for i in 1:(length(T) - 1)
s += 0.5 * (X[i]^2 + X[i + 1]^2) * (T[i + 1]-T[i])
end
return √(s)
end
function print_numerical_comparisons(problem, docp, nlp_oc_sol, nlp_jp)
# get relevant data from OptimalControl model
ocp_sol = build_ocp_solution(docp, nlp_oc_sol)
t_oc = time_grid(ocp_sol)
x_oc = state(ocp_sol).(t_oc)
u_oc = control(ocp_sol).(t_oc)
v_oc = variable(ocp_sol)
o_oc = objective(ocp_sol)
i_oc = iterations(ocp_sol)
# get relevant data from JuMP model
t_jp = time_grid(nlp_jp)
x_jp = state(nlp_jp).(t_jp)
u_jp = control(nlp_jp).(t_jp)
o_jp = objective(nlp_jp)
v_jp = variable(nlp_jp)
i_jp = iterations(nlp_jp)
x_vars = state_components(nlp_jp)
u_vars = control_components(nlp_jp)
v_vars = variable_components(nlp_jp)
println("┌─ ", string(problem))
println("│")
println("├─ Number of Iterations")
@printf("│ OptimalControl : %d JuMP : %d\n", i_oc, i_jp)
# States
println("├─ States (L2 Norms)")
for i in eachindex(x_vars)
xi_oc = [x_oc[k][i] for k in eachindex(t_oc)]
xi_jp = [x_jp[k][i] for k in eachindex(t_jp)]
L2_ae = L2_norm(t_oc, xi_oc - xi_jp)
L2_re = L2_ae / (0.5 * (L2_norm(t_oc, xi_oc) + L2_norm(t_oc, xi_jp)))
@printf("│ %-6s Abs: %.3e Rel: %.3e\n", x_vars[i], L2_ae, L2_re)
end
# Controls
println("├─ Controls (L2 Norms)")
for i in eachindex(u_vars)
ui_oc = [u_oc[k][i] for k in eachindex(t_oc)]
ui_jp = [u_jp[k][i] for k in eachindex(t_jp)]
L2_ae = L2_norm(t_oc, ui_oc - ui_jp)
L2_re = L2_ae / (0.5 * (L2_norm(t_oc, ui_oc) + L2_norm(t_oc, ui_jp)))
@printf("│ %-6s Abs: %.3e Rel: %.3e\n", u_vars[i], L2_ae, L2_re)
end
# Variables
if !isnothing(v_vars)
println("├─ Variables")
for i in eachindex(v_vars)
vi_oc = v_oc[i]
vi_jp = v_jp[i]
vi_ae = abs(vi_oc - vi_jp)
vi_re = vi_ae / (0.5 * (abs(vi_oc) + abs(vi_jp)))
@printf("│ %-6s Abs: %.3e Rel: %.3e\n", v_vars[i], vi_ae, vi_re)
end
end
# Objective
o_ae = abs(o_oc - o_jp)
o_re = o_ae / (0.5 * (abs(o_oc) + abs(o_jp)))
println("├─ Objective")
@printf("│ Abs: %.3e Rel: %.3e\n", o_ae, o_re)
println("└─")
return nothing
end
print_numerical_comparisons(:insurance, docp, nlp_oc_sol, nlp_jp)
┌─ insurance
│
├─ Number of Iterations
│ OptimalControl : 87 JuMP : 89
├─ States (L2 Norms)
│ I Abs: 1.416e-05 Rel: 6.623e-06
│ m Abs: 2.087e-05 Rel: 7.260e-06
│ x₃ Abs: 2.878e-08 Rel: 2.503e-08
├─ Controls (L2 Norms)
│ h Abs: 7.332e-03 Rel: 3.814e-03
│ R Abs: 6.718e-06 Rel: 8.631e-06
│ H Abs: 8.404e-06 Rel: 2.603e-06
│ U Abs: 6.780e-08 Rel: 1.131e-08
│ dUdR Abs: 8.403e-05 Rel: 2.326e-05
├─ Variables
│ P Abs: 1.050e-10 Rel: 1.936e-10
├─ Objective
│ Abs: 1.903e-10 Rel: 9.240e-11
└─
Plotting the solutions
In this section, we visualise the trajectories of the states, costates, and controls obtained from both the OptimalControl and JuMP solutions. The plots provide an intuitive way to compare the two approaches and to observe how the constraints and the optimal control influence the system dynamics.
For each variable, the OptimalControl solution is shown in solid lines, while the JuMP solution is overlaid using dashed lines. Since both models represent the same mathematical problem, their trajectories should closely coincide, highlighting the consistency between the two formulations.
# build an ocp solution to use the plot from OptimalControl package
ocp_sol = build_ocp_solution(docp, nlp_oc_sol)
# dimensions
n = state_dimension(ocp_sol)
m = control_dimension(ocp_sol)
# from OptimalControl solution
plt = plot(
ocp_sol;
color=1,
size=(816, 240*(n+m)),
label="OptimalControl",
leftmargin=20mm,
)
for i in 2:length(plt)
plot!(plt[i]; legend=:none)
end
# from JuMP solution
t = time_grid(nlp_jp) # t0, ..., tN = tf
x = state(nlp_jp) # function of time
u = control(nlp_jp) # function of time
p = costate(nlp_jp) # function of time
for i in 1:n # state
label = i == 1 ? "JuMP" : :none
plot!(plt[i], t, t -> x(t)[i]; color=2, linestyle=:dash, label=label)
end
for i in 1:n # costate
plot!(plt[n+i], t, t -> -p(t)[i]; color=2, linestyle=:dash, label=:none)
end
for i in 1:m # control
plot!(plt[2n+i], t, t -> u(t)[i]; color=2, linestyle=:dash, label=:none)
end