Differentially Private Optimization — Problems 2 and 3¶
Run the cells from top to bottom with a Julia kernel.
We solve $\min_x c^\top x$ subject to $\mathbf1^\top x=d$ and $0\leq x\leq a$. The reference signal $d$ matches the notation in the PDF.
a,c,x: upper bounds, objective coefficients, and optimization variables.tilde_a0: noisy upper bounds before post-processing;tilde_a: post-processed upper bounds.tilde_c: noisy objective target;c_opt: the original optimal objective;c_pp: the optimal objective under post-processed bounds.f_pp: the complete squared-error objective minimized during post-processing.tilde_a_hist[:, k+1]andc_pp_hist[:, k+1]: saved bounds and objective values at iterationk.
If needed, install once: import Pkg; Pkg.add(["JuMP", "Ipopt", "Gurobi", "Distributions", "CairoMakie"]).
Problem 2(c)¶
Use the original a = [5, 10, 15], d = 20, and ε0 = ε1 = 1. The upper-bound noise scale is 5 and the objective-value noise scale is 10.
using JuMP, Ipopt, Gurobi, Distributions, CairoMakie, Random, Statistics, LinearAlgebra, Base64, Markdown
a = [5.0, 10.0, 15.0]
c = [1.0, 2.0, 3.0]
d = 20.0
α = 5.0
ε0 = ε1 = ε2 = 1.0
Δ = α * (maximum(c) - minimum(c)) # 10
n_trials = 100
# Reuse one Gurobi environment for the post-processing models.
gurobi_env = Gurobi.Env()
Set parameter Username Academic license - for non-commercial use only - expires 2027-01-27
Gurobi.Env(Ptr{Nothing} @0x0000000325b77400, false, 0)
Solve the original optimization with JuMP and Ipopt¶
Define x, minimize cᵀx, impose ones(N)' * x = d and 0 ≤ x ≤ a, and solve. The same solver function evaluates the objective under synthetic upper bounds in Problem 3.
function solve_optimization(a, c, d)
N = length(a)
# These original constraints are infeasible for such inputs.
if any(a .< 0) || (ones(N)' * a) < d - 1e-8
return (x=fill(NaN, N), c_opt=NaN)
end
model = Model(Ipopt.Optimizer)
set_silent(model)
set_optimizer_attribute(model, "tol", 1e-9)
set_optimizer_attribute(model, "bound_relax_factor", 0.0)
@variable(model, 0 <= x[i=1:N] <= a[i])
@objective(model, Min, c' * x)
@constraint(model, ones(N)' * x == d)
optimize!(model)
return (x=value.(x), c_opt=objective_value(model))
end
original = solve_optimization(a, c, d)
println("Original solution: ", original.x)
println("Original objective value: ", original.c_opt)
Original solution: [4.999999999954546, 9.999999999909091, 5.000000000136365] Original objective value: 40.00000000018183
Standard post-processing with KKT conditions¶
function post_process(tilde_a0, tilde_c, c, d)
N = length(c)
model = Model(() -> Gurobi.Optimizer(gurobi_env))
set_silent(model)
# Upper-level variables and lower-level primal variables.
@variable(model, tilde_a[1:N] >= 0)
@variable(model, x[1:N] >= 0)
# Lower-level dual variables and auxiliary variable.
@variable(model, λ)
@variable(model, μ_lower[1:N] >= 0)
@variable(model, μ_upper[1:N] >= 0)
# this aux variable is for complimentary constraints
@variable(model, aux[1:N] >= 0)
@constraint(model, aux .== tilde_a - x)
@objective(model, Min,
0.5 * (c' * x - tilde_c)^2 +
(tilde_a - tilde_a0)' * (tilde_a - tilde_a0))
# Primal feasibility.
@constraint(model, ones(N)' * x == d)
# Stationarity and complementary slackness (KKT conditions).
@constraint(model, c + λ * ones(N) - μ_lower + μ_upper .== 0)
@constraint(model, [i=1:N], [μ_lower[i], x[i]] in SOS1())
@constraint(model, [i=1:N], [μ_upper[i], aux[i]] in SOS1())
optimize!(model)
return (
tilde_a=value.(tilde_a), x=value.(x),
c_pp=c' * value.(x), f_pp=objective_value(model),
)
end
function post_processing_trial(rng)
# DP obfuscation
tilde_a0 = a + rand(rng, Laplace(0, α / ε0), length(a))
tilde_c = original.c_opt + rand(rng, Laplace(0, Δ / ε1))
# post-processing
result = post_process(tilde_a0, tilde_c, c, d)
return (tilde_a0=tilde_a0, tilde_c=tilde_c, result=result)
end
post_processing_trial (generic function with 1 method)
Run one trial¶
Draw noisy upper limits and a noisy objective target, then solve the post-processing problem.
single_pp = post_processing_trial(MersenneTwister(10))
println("tilde_a0 = ", single_pp.tilde_a0)
println("tilde_c = ", single_pp.tilde_c)
println("tilde_a = ", single_pp.result.tilde_a)
println("c_pp = ", single_pp.result.c_pp)
println("f_pp = ", single_pp.result.f_pp)
tilde_a0 = [3.218915687592933, 7.313120005161929, 13.667446959225078] tilde_c = 35.92429699931285 tilde_a = [6.168844721975606, 8.788084522353262, 13.667446959225078] c_pp = 38.87422603369552 f_pp = 15.228642288814513
Problem 2(d): run 100 trials¶
Draw fresh noise in each trial. Report the mean and 90% interval (5th–95th percentiles) for c_pp and f_pp, matching the updated question.
function trial_summary(samples)
return (mean=mean(samples), lower=quantile(samples, 0.05),
upper=quantile(samples, 0.95))
end
rng2 = MersenneTwister(20)
trials_pp = [post_processing_trial(rng2) for trial in 1:n_trials]
summary_c = trial_summary([trial.result.c_pp for trial in trials_pp])
summary_f = trial_summary([trial.result.f_pp for trial in trials_pp])
println("Objective value: ", summary_c)
println("Post-processing objective: ", summary_f)
Objective value: (mean = 39.48704076826744, lower = 26.183431178697795, upper = 51.967105591820754) Post-processing objective: (mean = 76.80993531604979, lower = 0.190987283660877, upper = 298.0124492513959)
Problem 3¶
Use references $d\in\{2,4,\ldots,20\}$ and K = 3 updates.
Note: an infeasible optimization has no objective value, so the code returns NaN and stops that trial if any reference is infeasible. Failed trials are counted explicitly.
d_set = collect(2.0:2.0:20.0)
K = 3
# generate the list of real c_pp for different d
c_real = [solve_optimization(a, c, d).c_opt for d in d_set]
ε1 =1.0
# function for selecting the worst-case d. c_synthetic is the c_pp from synthetic dataset.
function select_worst_case(rng, c_real, c_synthetic)
ΔC = abs.(c_real - c_synthetic)
tilde_ΔC = ΔC + rand(rng, Laplace(0, 2 * Δ / ε1), length(ΔC))
return argmax(tilde_ΔC)
end
select_worst_case (generic function with 1 method)
ε2 = 1.0
function EM_trial(rng)
N = length(a)
I = length(d_set)
tilde_a_hist = fill(NaN, N, K + 1) # column k+1 stores tilde_a^k
c_pp_hist = fill(NaN, I, K + 1)
selected_d = fill(NaN, K)
tilde_a0 = a + rand(rng, Laplace(0, α / ε0), N)
tilde_a_hist[:, 1] = tilde_a0
for i in 1:I
c_pp_hist[i, 1] = solve_optimization(tilde_a_hist[:, 1], c, d_set[i]).c_opt
end
# if tilde_a0 renders the problem infeasible, mark it in status.
if any(isnan, c_pp_hist[:, 1])
return (tilde_a_hist=tilde_a_hist, c_pp_hist=c_pp_hist,
selected_d=selected_d, status="infeasible")
end
for k in 1:K
tilde_a_prev = tilde_a_hist[:, k]
j = select_worst_case(rng, c_real, c_pp_hist[:, k])
d = d_set[j]
tilde_c = c_real[j] + rand(rng, Laplace(0, Δ / ε2))
result = post_process(tilde_a_prev, tilde_c, c, d)
tilde_a_hist[:, k + 1] = result.tilde_a
selected_d[k] = d
for i in 1:I
c_pp_hist[i, k + 1] = solve_optimization(result.tilde_a, c, d_set[i]).c_opt
end
# A completed trial must be feasible at every reference and iteration.
if any(isnan, c_pp_hist[:, k + 1])
return (tilde_a_hist=tilde_a_hist, c_pp_hist=c_pp_hist,
selected_d=selected_d, status="infeasible")
end
end
return (tilde_a_hist=tilde_a_hist, c_pp_hist=c_pp_hist,
selected_d=selected_d, status="completed")
end
EM_trial (generic function with 1 method)
Problem 3(d): run one trial¶
Set K = 3 and ε0 = ε1 = ε2 = 1. Store all synthetic upper limits and objective values before plotting. Column k + 1 stores iteration k; column 1 is the raw initial noisy vector. The real upper limits are a; c_real contains the real objective values at all ten references.
iterations = collect(0:K)
trial = EM_trial(MersenneTwister(60))
println("Trial status: ", trial.status)
println("Selected references = ", trial.selected_d)
println("Final synthetic limits = ", trial.tilde_a_hist[:, end])
println("Objective values at d=20 through iterations = ", trial.c_pp_hist[end, :])
# Columns: reference, real objective, and synthetic objectives at iterations 0–3.
println("Columns: d, real c, c_pp at iterations 0, 1, 2, 3")
display(hcat(d_set, c_real, trial.c_pp_hist))
10×6 Matrix{Float64}:
2.0 2.0 2.0 2.02973 2.0 2.0
4.0 4.0 4.0 6.02973 4.0 4.0
6.0 7.0 6.39797 10.0297 7.78288 6.41533
8.0 11.0 10.398 14.0297 11.7829 10.4153
10.0 15.0 14.398 18.1129 15.7829 14.4153
12.0 19.0 18.398 24.1129 19.7829 18.4153
14.0 23.0 22.398 30.1129 24.4958 22.4153
16.0 28.0 27.0335 36.1129 30.4958 27.7607
18.0 34.0 33.0335 42.1129 36.4958 33.7607
20.0 40.0 39.0335 48.1129 42.4958 39.7607
Trial status: completed Selected references = [16.0, 18.0, 8.0] Final synthetic limits = [5.584667256968894, 9.069967732193744, 14.051614155206225] Objective values at d=20 through iterations = [39.03351854188822, 48.1129137142048, 42.49579647950975, 39.76069775405029] Columns: d, real c, c_pp at iterations 0, 1, 2, 3
let
# Render directly as HTML to avoid Markdown's LaTeX tabular output.
headers = vcat(["d", "Real objective"], ["Iteration $k" for k in iterations])
objective_table = "<table><thead><tr>" *
join(["<th>$header</th>" for header in headers]) * "</tr></thead><tbody>"
for i in eachindex(d_set)
values = vcat(d_set[i], c_real[i], trial.c_pp_hist[i, :])
objective_table *= "<tr>" *
join(["<td>$(round(value; digits=4))</td>" for value in values]) * "</tr>"
end
objective_table *= "</tbody></table>"
display(HTML(objective_table))
end
| d | Real objective | Iteration 0 | Iteration 1 | Iteration 2 | Iteration 3 |
|---|---|---|---|---|---|
| 2.0 | 2.0 | 2.0 | 2.0297 | 2.0 | 2.0 |
| 4.0 | 4.0 | 4.0 | 6.0297 | 4.0 | 4.0 |
| 6.0 | 7.0 | 6.398 | 10.0297 | 7.7829 | 6.4153 |
| 8.0 | 11.0 | 10.398 | 14.0297 | 11.7829 | 10.4153 |
| 10.0 | 15.0 | 14.398 | 18.1129 | 15.7829 | 14.4153 |
| 12.0 | 19.0 | 18.398 | 24.1129 | 19.7829 | 18.4153 |
| 14.0 | 23.0 | 22.398 | 30.1129 | 24.4958 | 22.4153 |
| 16.0 | 28.0 | 27.0335 | 36.1129 | 30.4958 | 27.7607 |
| 18.0 | 34.0 | 33.0335 | 42.1129 | 36.4958 | 33.7607 |
| 20.0 | 40.0 | 39.0335 | 48.1129 | 42.4958 | 39.7607 |
Prepare the plots¶
The next cell sets up the plotting style and output folder. Problem 3(d) uses the animated bar plots below. The table above reports the real and synthetic objective values at every reference and iteration. The objective plot below compares their trajectories.
CairoMakie.activate!()
set_theme!(Theme(fontsize=14))
figure_directory = joinpath(pwd(), "figures", "dp_opt")
mkpath(figure_directory)
"/Users/syseanwu/University of Michigan Dropbox/Shengyang Wu/UMich/26 fall/DTU DP Course/code/figures/dp_opt"
Animate the saved upper bounds as bar plots¶
# Animate the single trial from Problem 3(d).
bar_figure = Figure(size=(760, 460))
bar_axis = Axis(bar_figure[1, 1], xlabel="Variable index", ylabel="Upper bound",
xticks=(1:3, ["a1", "a2", "a3"]), title="Iteration 0")
barplot!(bar_axis, (1:3) .- 0.18, a, width=0.32, color=:gray65, label="Real")
bar_a = Observable(trial.tilde_a_hist[:, 1])
barplot!(bar_axis, (1:3) .+ 0.18, bar_a,
width=0.32, color=:royalblue, label="Synthetic")
ylims!(bar_axis, 0, 1.2 * max(maximum(a), maximum(trial.tilde_a_hist)))
axislegend(bar_axis, position=:lt)
single_animation_path = joinpath(figure_directory, "Q3d_upper_bounds.gif")
record(bar_figure, single_animation_path, iterations; framerate=1) do k
bar_a[] = trial.tilde_a_hist[:, k + 1]
bar_axis.title = "One trial — iteration $k"
end
# Show all four animation frames in the PDF as well.
single_bar_frames = Figure(size=(1150, 320))
for k in iterations
ax = Axis(single_bar_frames[1, k + 1], title="Iteration $k", xlabel="Variable index",
ylabel="Upper bound", xticks=(1:3, ["a1", "a2", "a3"]))
barplot!(ax, (1:3) .- 0.18, a, width=0.32, color=:gray65, label="Real")
barplot!(ax, (1:3) .+ 0.18, trial.tilde_a_hist[:, k + 1], width=0.32, color=:royalblue, label="Synthetic")
axislegend(ax, position=:lt, labelsize=11)
ylims!(ax, 0, 1.2 * max(maximum(a), maximum(trial.tilde_a_hist)))
end
save(joinpath(figure_directory, "Q3d_bar_frames.png"), single_bar_frames)
display(HTML("<img alt='Real and synthetic upper bounds through iterations' src='data:image/gif;base64,$(base64encode(read(single_animation_path)))'>"))
Objective values through iterations¶
Each panel shows one reference d. Blue points and lines show the saved synthetic objective values at iterations 0–3; the dashed black line shows the real objective.
objective_figure = Figure(size=(1250, 620))
for i in eachindex(d_set)
row, col = divrem(i - 1, 5)
ax = Axis(objective_figure[row + 1, col + 1], title="d = $(Int(d_set[i]))",
xlabel="Iteration", ylabel="Objective value", xticks=iterations)
lines!(ax, iterations, trial.c_pp_hist[i, :], color=:royalblue, label="Synthetic")
scatter!(ax, iterations, trial.c_pp_hist[i, :], color=:royalblue)
hlines!(ax, [c_real[i]], color=:black, linestyle=:dash, label="Real")
if i == 1
axislegend(ax, position=:lt, labelsize=10)
end
end
save(joinpath(figure_directory, "Q3d_objectives.png"), objective_figure)
display(objective_figure)
CairoMakie.Screen{IMAGE}
Problem 3(e): attempt 100 trials¶
Attempt all 100 trials and print how many complete all three iterations. Calculate the mean and 80% interval across completed trials only. Infeasible trials have no final result; the figures do not describe the unconditional distribution of all 100 attempts. The real bounds remain fixed at a.
rng3 = MersenneTwister(1)
trials = [EM_trial(rng3) for trial in 1:n_trials]
completed_trials = [result for result in trials if result.status == "completed"]
n_completed = length(completed_trials)
println("Completed trials: ", n_completed, " / ", n_trials)
println("Trials stopped for infeasibility: ", n_trials - n_completed)
mean_a = zeros(length(a), K + 1)
low_a = similar(mean_a)
high_a = similar(mean_a)
for k in 1:(K + 1)
for i in eachindex(a)
samples = [result.tilde_a_hist[i, k] for result in completed_trials]
mean_a[i, k] = mean(samples)
low_a[i, k] = quantile(samples, 0.10)
high_a[i, k] = quantile(samples, 0.90)
end
end
# The real vector does not change between trials or iterations.
mean_real = repeat(a, 1, K + 1)
low_real = copy(mean_real)
high_real = copy(mean_real)
for k in 1:(K + 1)
println("Iteration ", k - 1, ": synthetic mean = ", round.(mean_a[:, k]; digits=4),
"; real mean = ", mean_real[:, k])
end
Completed trials: 58 / 100 Trials stopped for infeasibility: 42 Iteration 0: synthetic mean = [7.68, 11.9141, 16.8755]; real mean = [5.0, 10.0, 15.0] Iteration 1: synthetic mean = [7.2334, 11.5368, 16.9568]; real mean = [5.0, 10.0, 15.0] Iteration 2: synthetic mean = [6.367, 11.0729, 16.9568]; real mean = [5.0, 10.0, 15.0] Iteration 3: synthetic mean = [6.776, 10.9373, 16.9895]; real mean = [5.0, 10.0, 15.0]
Plot the real and synthetic upper bounds¶
Each panel shows one upper bound. The blue line is the synthetic mean and the blue band is its 80% interval. The dashed black line is the real upper bound; its 80% interval is the same line.
The statistics use only the reported completed trials.
capacity_band_figure = Figure(size=(1100, 380))
for i in eachindex(a)
ax = Axis(capacity_band_figure[1, i], xlabel="Iteration", ylabel="Upper bound",
xticks=iterations, title="Upper bound a$i")
band!(ax, iterations, low_a[i, :], high_a[i, :],
color=(:royalblue, 0.18), label="Synthetic 80% interval")
lines!(ax, iterations, mean_a[i, :], color=:royalblue, label="Synthetic mean")
scatter!(ax, iterations, mean_a[i, :], color=:royalblue)
lines!(ax, iterations, mean_real[i, :], color=:black, linestyle=:dash,
label="Real mean")
if i == 1
axislegend(ax, position=:lt, labelsize=11)
end
end
Label(capacity_band_figure[2, 1:3], "$n_completed of $n_trials trials completed; statistics use completed trials only")
save(joinpath(figure_directory, "Q3e_capacity.png"), capacity_band_figure)
display(capacity_band_figure)
CairoMakie.Screen{IMAGE}
Animate the 100-trial means and intervals¶
Gray bars are the real means. Blue bars are the synthetic means, with black whiskers showing their 80% intervals. The real intervals have zero width because a is fixed.
# Animate the means and 80% intervals from Problem 3(e).
mean_bar_figure = Figure(size=(760, 460))
mean_bar_axis = Axis(mean_bar_figure[1, 1], xlabel="Variable index", ylabel="Upper bound",
xticks=(1:3, ["a1", "a2", "a3"]), title="Iteration 0")
barplot!(mean_bar_axis, (1:3) .- 0.18, a, width=0.32, color=:gray65,
label="Real mean (fixed)")
bar_mean = Observable(mean_a[:, 1])
bar_low = Observable(low_a[:, 1])
bar_high = Observable(high_a[:, 1])
barplot!(mean_bar_axis, (1:3) .+ 0.18, bar_mean, width=0.32,
color=:royalblue, label="Synthetic mean")
rangebars!(mean_bar_axis, (1:3) .+ 0.18, bar_low, bar_high,
color=:black, whiskerwidth=14, label="Synthetic 80% interval")
ylims!(mean_bar_axis, 0, 1.2 * max(maximum(a), maximum(high_a)))
axislegend(mean_bar_axis, position=:lt)
mean_animation_path = joinpath(figure_directory, "Q3e_upper_bounds.gif")
record(mean_bar_figure, mean_animation_path, iterations; framerate=1) do k
bar_mean[] = mean_a[:, k + 1]
bar_low[] = low_a[:, k + 1]
bar_high[] = high_a[:, k + 1]
mean_bar_axis.title = "$n_completed of $n_trials trials completed — iteration $k"
end
mean_bar_frames = Figure(size=(1150, 320))
for k in iterations
ax = Axis(mean_bar_frames[1, k + 1], title="Iteration $k", xlabel="Variable index",
ylabel="Upper bound", xticks=(1:3, ["a1", "a2", "a3"]))
barplot!(ax, (1:3) .- 0.18, a, width=0.32, color=:gray65, label="Real mean")
barplot!(ax, (1:3) .+ 0.18, mean_a[:, k + 1], width=0.32, color=:royalblue, label="Synthetic mean")
rangebars!(ax, (1:3) .+ 0.18, low_a[:, k + 1], high_a[:, k + 1],
color=:black, whiskerwidth=10, label="Synthetic 80% interval")
axislegend(ax, position=:lt, labelsize=9)
ylims!(ax, 0, 1.2 * max(maximum(a), maximum(high_a)))
end
save(joinpath(figure_directory, "Q3e_bar_frames.png"), mean_bar_frames)
display(HTML("<img alt='Real and synthetic means with 80 percent intervals' src='data:image/gif;base64,$(base64encode(read(mean_animation_path)))'>"))
Distribution of objective values through iterations¶
Each panel shows the distribution across completed trials for one reference d, separately at iterations 0–3. Boxes span the 25th–75th percentiles, their middle line is the median, whiskers extend to the most extreme observations within 1.5 interquartile ranges, and points beyond the whiskers are outliers. The dashed black line is the real objective. The same completed trials are used at every iteration.
objective_distribution_figure = Figure(size=(1250, 700))
for i in eachindex(d_set)
row, col = divrem(i - 1, 5)
ax = Axis(objective_distribution_figure[row + 1, col + 1],
title="d = $(Int(d_set[i]))", xlabel="Iteration",
ylabel="Objective value", xticks=iterations)
for k in iterations
samples = [result.c_pp_hist[i, k + 1] for result in completed_trials]
boxplot!(ax, fill(k, length(samples)), samples, color=(:royalblue, 0.55),
width=0.55, show_outliers=true, label=k == 0 ? "Synthetic" : nothing)
end
hlines!(ax, [c_real[i]], color=:black, linestyle=:dash, label="Real")
if i == 1
axislegend(ax, position=:lt, labelsize=10)
end
end
Label(objective_distribution_figure[3, 1:5],
"$n_completed of $n_trials trials completed; distributions use completed trials only")
save(joinpath(figure_directory, "Q3e_objective_distribution.png"), objective_distribution_figure)
display(objective_distribution_figure)
CairoMakie.Screen{IMAGE}