using Optim
using Plots
using Printf
using Random
using StatisticsDynamic Discrete Choice
1. Motivation
- Dynamic discrete choices are forward-looking because today’s action changes tomorrow’s state.
- In a minimal version of Rust’s replacement problem, an owner chooses whether to keep a costly machine or replace it and reset its condition.
- With one state, two choices, and two cost parameters, the model introduces value functions, conditional choice probabilities, and NFXP estimation.
2. Dynamic Discrete Choice Theory
2.1 Model Setup
- Single agent and infinite-horizon discrete time: \(t=0,1,2,\ldots\).
- The observed state is the machine condition:
\[ x_t \in \mathcal{X}=\{0,1,\ldots,K\}, \]
- A larger state means a machine in worse condition.
- The owner chooses:
\[ d_t \in \mathcal{D}=\{0,1\}, \]
\(d_t=0\) means keep; and
\(d_t=1\) means replace.
Timing within each period:
- The owner observes \(x_t\) and the choice shocks \(\boldsymbol{\varepsilon}_t=(\varepsilon_{t0},\varepsilon_{t1})\).
- The owner chooses \(d_t\).
- The owner receives current utility.
- The next state \(x_{t+1}\) is drawn from the transition distribution associated with the chosen action.
Period utility from action \(d\) is:
\[ u(x,d;\theta)+\varepsilon_d, \qquad \theta=(c,RC), \]
- Mean utilities are:
\[ u(x,0;\theta)=-cx, \qquad u(x,1;\theta)=-RC. \]
The parameter \(c>0\) determines how quickly operating costs increase with the condition state.
The parameter \(RC>0\) is the replacement cost.
If the owner keeps the machine, its condition stays unchanged or deteriorates by one step:
\[ x_{t+1} = \min\{x_t+z_{t+1},K\}, \qquad z_{t+1}\sim\operatorname{Bernoulli}(p). \]
If the owner replaces the machine, the next state is \(x_{t+1}=0\).
Let \(P_d(x' \mid x)\) denote the transition probability under action \(d\).
We treat the following objects as known:
- the discount factor \(\beta\in(0,1)\); and
- the deterioration probability \(p\).
We estimate \(c\) and \(RC\).
Choice shocks are:
- independent across time, actions, and owners;
- Type I extreme value; and
- independent of the state transitions.
2.2 Choice-Specific Value Function
- The choice-specific value of choosing action \(d\) today is:
\[ v_d(x;\theta) = u(x,d;\theta) + \beta \sum_{x'\in\mathcal{X}} P_d(x'\mid x)V(x';\theta). \]
- For keep:
\[ v_0(x;\theta) = -cx + \beta \sum_{x'\in\mathcal{X}} P_0(x'\mid x)V(x';\theta) \]
- For replace:
\[ v_1(x;\theta) = -RC+\beta V(0;\theta). \]
- Each choice-specific value equals:
- current mean utility; plus
- the expected discounted continuation value.
2.3 Integrated Value Function
- Before the choice shocks are observed, the value of state \(x\) is:
\[ V(x;\theta) = \mathbb{E}_{\boldsymbol{\varepsilon}} \left[ \max_{d\in\{0,1\}} \left\{ v_d(x;\theta)+\varepsilon_d \right\} \right]. \]
- Type I extreme value shocks give the log-sum-exp formula:
\[ V(x;\theta) = \log \left[ \exp\{v_0(x;\theta)\} + \exp\{v_1(x;\theta)\} \right]. \]
- We omit Euler’s constant:
- it is choice-independent; and
- removing it does not change choice probabilities.
- Because each \(v_d\) contains the future value function, this equation is a fixed point.
- For a given parameter vector \(\theta\), value-function iteration applies:
\[ V^{(k+1)}(x) = \log \left[ \exp\{v_0^{(k)}(x;\theta)\} + \exp\{v_1^{(k)}(x;\theta)\} \right] \]
- Stop when \(V^{(k+1)}\) and \(V^{(k)}\) are sufficiently close.
- With \(\beta\in(0,1)\), the Bellman operator is a contraction, so the fixed point is unique.
2.4 Conditional Choice Probabilities
- A conditional choice probability (CCP) is the probability of an action given the observed state.
- Type I extreme value shocks imply:
\[ \Pr(d_t=d\mid x_t=x;\theta) = \frac{ \exp\{v_d(x;\theta)\} }{ \exp\{v_0(x;\theta)\} + \exp\{v_1(x;\theta)\} }. \]
- The replacement probability is:
\[ \Pr(d_t=1\mid x_t=x;\theta) = \frac{ \exp\{v_1(x;\theta)\} }{ \exp\{v_0(x;\theta)\} + \exp\{v_1(x;\theta)\} }. \]
- This is the usual logit formula:
- dynamics enter through the choice-specific values; and
- replacement becomes more likely as its value rises relative to the keep value.
2.5 Estimation with the NFXP Algorithm
- The data contain \((x_i,d_i)\) for \(i=1,\ldots,N\).
- Conditional on the observed states, the log-likelihood is:
\[ \ell(\theta) = \sum_{i=1}^{N} \log \Pr(d_i\mid x_i;\theta). \]
NFXP evaluates the likelihood through two loops:
- Inner loop: For a trial value of \(\theta\), solve the integrated value function fixed point and compute the CCPs.
- Outer loop: Use the resulting CCPs to evaluate \(\ell(\theta)\) and update \(\theta\) with a numerical optimizer.
Each likelihood evaluation follows:
\[ \theta \longrightarrow V_{\theta} \longrightarrow \Pr_{\theta}(d\mid x) \longrightarrow \ell(\theta). \]
- NFXP is direct but can be costly because the fixed point is solved at every trial parameter vector.
3. Julia Coding Demo
- The code follows the same order as the theory:
- Construct the model.
- Solve its dynamic program.
- Simulate a synthetic panel.
- Inspect one-dimensional objective profiles.
- Estimate the two cost parameters by NFXP.
3.1 Packages and Model Constructor
- This cell only loads the packages used in the demo. It does not implement a model equation.
- The next cell implements the state transitions from Section 2.1:
\[ x_{t+1} = \begin{cases} \min\{x_t+z_{t+1},K\}, & d_t=0,\\ 0, & d_t=1, \end{cases} \qquad z_{t+1}\sim\operatorname{Bernoulli}(p). \]
transition_matrices: Builds \(P_0\) and \(P_1\).- Rows represent the current state.
- Columns represent the next state.
ReplacementModel: Stores the state-space size, \(\beta\), \(p\), and the two transition matrices.
struct ReplacementModel
n_states::Int
discount_factor::Float64
deterioration_probability::Float64
transition_keep::Matrix{Float64}
transition_replace::Matrix{Float64}
end
function transition_matrices(; n_states, deterioration_probability)
transition_keep = zeros(n_states, n_states)
transition_replace = zeros(n_states, n_states)
maximum_state = n_states - 1
for state in 0:maximum_state
row = state + 1
next_state = min(state + 1, maximum_state)
transition_keep[row, row] += 1 - deterioration_probability
transition_keep[row, next_state + 1] +=
deterioration_probability
transition_replace[row, 1] = 1.0
end
return transition_keep, transition_replace
end
function ReplacementModel(;
n_states = 8,
discount_factor = 0.95,
deterioration_probability = 0.65,
)
transition_keep, transition_replace = transition_matrices(
n_states = n_states,
deterioration_probability = deterioration_probability,
)
return ReplacementModel(
n_states,
discount_factor,
deterioration_probability,
transition_keep,
transition_replace,
)
end
model = ReplacementModel()
@show sum(model.transition_keep; dims = 2)
@show sum(model.transition_replace; dims = 2)
nothingsum(model.transition_keep; dims = 2) = [1.0; 1.0; 1.0; 1.0; 1.0; 1.0; 1.0; 1.0;;]
sum(model.transition_replace; dims = 2) = [1.0; 1.0; 1.0; 1.0; 1.0; 1.0; 1.0; 1.0;;]
- Check: Each row sums to one, as required for a transition probability.
3.2 Choice-Specific Values
- This cell implements the choice-specific values from Section 2.2:
\[ \begin{aligned} v_0(x;\theta) &= -cx + \beta \sum_{x'\in\mathcal{X}} P_0(x'\mid x)V(x';\theta),\\ v_1(x;\theta) &= -RC+\beta V(0;\theta). \end{aligned} \]
- Current utility:
utility_keepcomputes \(-cx\), andutility_replacecomputes \(-RC\). - Continuation value: Each transition matrix multiplies the current guess of \(V\).
- Output: The two columns contain \(v_0(x;\theta)\) and \(v_1(x;\theta)\).
function choice_specific_values(; model, parameters, value)
operating_cost, replacement_cost = parameters
states = collect(0:(model.n_states - 1))
utility_keep = -operating_cost .* states
utility_replace = fill(-replacement_cost, model.n_states)
value_keep =
utility_keep +
model.discount_factor .* (model.transition_keep * value)
value_replace =
utility_replace +
model.discount_factor .* (model.transition_replace * value)
return hcat(value_keep, value_replace)
endchoice_specific_values (generic function with 1 method)
3.3 Integrated Value and CCPs
- This cell implements the integrated value from Section 2.3:
\[ V(x;\theta) = \log \left[ \exp\{v_0(x;\theta)\} + \exp\{v_1(x;\theta)\} \right]. \]
- It also implements the CCPs from Section 2.4:
\[ \Pr(d_t=d\mid x_t=x;\theta) = \frac{ \exp\{v_d(x;\theta)\} }{ \exp\{v_0(x;\theta)\} + \exp\{v_1(x;\theta)\} }. \]
integrated_value: Uses a stable log-sum-exp calculation.log_choice_probabilities: Computes \(\log\Pr(d\mid x;\theta)=v_d(x;\theta)-V(x;\theta)\).choice_probabilities: Exponentiates the log CCPs.
function integrated_value(; choice_values)
row_maximum = maximum(choice_values; dims = 2)
return vec(
row_maximum +
log.(sum(exp.(choice_values .- row_maximum); dims = 2)),
)
end
function log_choice_probabilities(; choice_values)
value = integrated_value(choice_values = choice_values)
return choice_values .- reshape(value, :, 1)
end
function choice_probabilities(; choice_values)
return exp.(
log_choice_probabilities(choice_values = choice_values),
)
endchoice_probabilities (generic function with 1 method)
3.4 Value-Function Iteration
- This cell implements the fixed-point iteration from Section 2.3:
\[ V^{(k+1)}(x) = \log \left[ \exp\{v_0^{(k)}(x;\theta)\} + \exp\{v_1^{(k)}(x;\theta)\} \right]. \]
- The stopping rule is:
\[ \left\lVert V^{(k+1)}-V^{(k)} \right\rVert_{\infty} < \text{tolerance}. \]
solve_value_function: Alternates between choice-specific values and the integrated value until the stopping rule holds.solve_model: Uses the converged value function to return the choice-specific values and CCPs.
function solve_value_function(;
model,
parameters,
tolerance = 1.0e-10,
maximum_iterations = 10_000,
)
value = zeros(model.n_states)
for iteration in 1:maximum_iterations
choice_values = choice_specific_values(
model = model,
parameters = parameters,
value = value,
)
updated_value = integrated_value(
choice_values = choice_values,
)
if maximum(abs.(updated_value .- value)) < tolerance
return (
value = updated_value,
iterations = iteration,
)
end
value = updated_value
end
error("Value-function iteration did not converge.")
end
function solve_model(; model, parameters)
solution = solve_value_function(
model = model,
parameters = parameters,
)
choice_values = choice_specific_values(
model = model,
parameters = parameters,
value = solution.value,
)
return (
value = solution.value,
choice_values = choice_values,
choice_probabilities = choice_probabilities(
choice_values = choice_values,
),
iterations = solution.iterations,
)
endsolve_model (generic function with 1 method)
3.5 Simulating a Synthetic Panel
- This cell generates data using the CCPs and state transitions:
\[ d_t \sim \operatorname{Bernoulli} \left( \Pr(d_t=1\mid x_t;\theta) \right), \qquad x_{t+1} \sim P_{d_t}(\cdot\mid x_t). \]
- First, solve the model at the true parameter values.
- For each machine and period:
- draw the action from the replacement probability; and
- draw the next state using the transition rule.
- Every simulated machine begins in state zero.
function simulate_panel(;
model,
parameters,
n_units = 2_000,
n_periods = 30,
seed = 2026,
)
rng = MersenneTwister(seed)
solution = solve_model(
model = model,
parameters = parameters,
)
probabilities = solution.choice_probabilities
n_observations = n_units * n_periods
states = Vector{Int}(undef, n_observations)
actions = Vector{Int}(undef, n_observations)
observation = 0
for unit in 1:n_units
state = 0
for period in 1:n_periods
observation += 1
replacement_probability = probabilities[state + 1, 2]
action = rand(rng) < replacement_probability ? 1 : 0
states[observation] = state
actions[observation] = action
if action == 1
state = 0
else
deteriorates =
rand(rng) < model.deterioration_probability
state = min(
state + deteriorates,
model.n_states - 1,
)
end
end
end
return (states = states, actions = actions)
end
true_parameters = [0.35, 4.0]
data = simulate_panel(
model = model,
parameters = true_parameters,
)
@show length(data.actions)
@show mean(data.actions)
nothinglength(data.actions) = 60000
mean(data.actions) = 0.1833
3.6 Log-Likelihood and NFXP Estimation
- This cell implements the log-likelihood from Section 2.5:
\[ \ell(\theta) = \sum_{i=1}^{N} \log \Pr(d_i\mid x_i;\theta). \]
- Each NFXP likelihood evaluation follows:
\[ \theta \longrightarrow V_{\theta} \longrightarrow \Pr_{\theta}(d\mid x) \longrightarrow \ell(\theta). \]
log_likelihood: Solves the inner fixed point and sums the log CCPs.estimate_nfxp: Runs the outer optimization.- The optimizer works with log parameters so that both costs remain positive.
function log_likelihood(; model, parameters, states, actions)
solution = solve_value_function(
model = model,
parameters = parameters,
)
choice_values = choice_specific_values(
model = model,
parameters = parameters,
value = solution.value,
)
log_probabilities = log_choice_probabilities(
choice_values = choice_values,
)
objective = 0.0
for observation in eachindex(states)
objective += log_probabilities[
states[observation] + 1,
actions[observation] + 1,
]
end
return objective
end
function estimate_nfxp(;
model,
states,
actions,
initial_parameters = [0.25, 3.0],
)
function negative_log_likelihood(log_parameters)
parameters = exp.(log_parameters)
return -log_likelihood(
model = model,
parameters = parameters,
states = states,
actions = actions,
)
end
result = Optim.optimize(
negative_log_likelihood,
log.(initial_parameters),
Optim.NelderMead(),
Optim.Options(
iterations = 1_000,
x_abstol = 1.0e-8,
f_abstol = 1.0e-8,
),
)
return (
parameters = exp.(Optim.minimizer(result)),
result = result,
)
endestimate_nfxp (generic function with 1 method)
Objective Profiles
- Before optimizing both parameters, inspect two one-dimensional profiles:
\[ Q_c(c) = -\ell(c,RC_0), \qquad Q_{RC}(RC) = -\ell(c_0,RC), \]
where \(c_0\) and \(RC_0\) are the true values. - Each profile varies one parameter and holds the other at its true value. - The dashed line marks the true value. - In a finite sample, the minimum should be near, but need not equal, the true value.
operating_cost_grid = range(0.20, 0.50; length = 41)
replacement_cost_grid = range(3.0, 5.0; length = 41)
operating_cost_profile = [
-log_likelihood(
model = model,
parameters = [operating_cost, true_parameters[2]],
states = data.states,
actions = data.actions,
)
for operating_cost in operating_cost_grid
]
replacement_cost_profile = [
-log_likelihood(
model = model,
parameters = [true_parameters[1], replacement_cost],
states = data.states,
actions = data.actions,
)
for replacement_cost in replacement_cost_grid
]
operating_cost_plot = plot(
operating_cost_grid,
operating_cost_profile .- minimum(operating_cost_profile);
color = :steelblue,
linewidth = 2,
label = "",
xlabel = "Operating-cost slope c",
ylabel = "Negative log-likelihood\n(relative to minimum)",
title = "Profile in c",
grid = false,
)
vline!(
operating_cost_plot,
[true_parameters[1]];
color = :black,
linestyle = :dash,
linewidth = 2,
label = "True value",
)
replacement_cost_plot = plot(
replacement_cost_grid,
replacement_cost_profile .- minimum(replacement_cost_profile);
color = :darkorange,
linewidth = 2,
label = "",
xlabel = "Replacement cost RC",
ylabel = "Negative log-likelihood\n(relative to minimum)",
title = "Profile in RC",
grid = false,
)
vline!(
replacement_cost_plot,
[true_parameters[2]];
color = :black,
linestyle = :dash,
linewidth = 2,
label = "True value",
)
profile_minimizer_operating_cost =
operating_cost_grid[argmin(operating_cost_profile)]
profile_minimizer_replacement_cost =
replacement_cost_grid[argmin(replacement_cost_profile)]
@show profile_minimizer_operating_cost
@show profile_minimizer_replacement_cost
plot(
operating_cost_plot,
replacement_cost_plot;
layout = (1, 2),
size = (900, 360),
)profile_minimizer_operating_cost = 0.35
profile_minimizer_replacement_cost = 4.0
NFXP Estimates
- The final cell estimates both parameters jointly.
estimate = estimate_nfxp(
model = model,
states = data.states,
actions = data.actions,
)
estimated_parameters = estimate.parameters
@printf(
"%-20s %10s %10s\n",
"Parameter",
"True",
"Estimate",
)
@printf(
"%-20s %10.3f %10.3f\n",
"Operating cost",
true_parameters[1],
estimated_parameters[1],
)
@printf(
"%-20s %10.3f %10.3f\n",
"Replacement cost",
true_parameters[2],
estimated_parameters[2],
)
@show Optim.converged(estimate.result)
nothingParameter True Estimate
Operating cost 0.350 0.357
Replacement cost 4.000 4.039
Optim.converged(estimate.result) = true
3.7 Numerical Checks
- These are implementation checks for this synthetic example, not statistical inference.
- The cell checks:
\[ \left\lVert \mathcal{T}_{\widehat{\theta}}\widehat{V} -\widehat{V} \right\rVert_{\infty} < 10^{-8}, \qquad \left\lVert \widehat{\theta}-\theta_0 \right\rVert_{\infty} < 0.25. \]
- It also checks that the outer optimizer reports convergence.
estimated_solution = solve_model(
model = model,
parameters = estimated_parameters,
)
bellman_update = integrated_value(
choice_values = choice_specific_values(
model = model,
parameters = estimated_parameters,
value = estimated_solution.value,
),
)
bellman_residual = maximum(
abs.(bellman_update .- estimated_solution.value),
)
maximum_parameter_error = maximum(
abs.(estimated_parameters .- true_parameters),
)
@show estimated_solution.iterations
@show bellman_residual
@show maximum_parameter_error
@assert Optim.converged(estimate.result)
@assert bellman_residual < 1.0e-8
@assert maximum_parameter_error < 0.25
nothingestimated_solution.iterations = 445
bellman_residual = 9.135803225035488e-11
maximum_parameter_error = 0.039337351509356466
- The Bellman residual checks the inner solution.
- Parameter recovery checks the full simulation-to-estimation path.
- With a finite sample, the estimates need not equal the true parameters exactly.