Balancing Lateral-Movement Risk and Latency with Simulated Annealing

Network Segmentation Design

Flat networks are convenient, and that convenience is what attackers exploit. Once a single laptop or IoT sensor is compromised, nothing stops the intruder from walking toward the database tier. Splitting the network into segments breaks those paths, but every segment boundary adds a firewall hop, extra latency, and more rules to maintain.

This article turns that trade-off into a combinatorial optimization problem and solves it in Python on a concrete 26-host enterprise network.


1. The Example Problem

The network has $n = 26$ hosts with the following roles.

Role Hosts Exposure Asset value
Web 4 high medium
App 5 medium medium-high
DB 4 low critical
Auth (AD/IdP) 2 low critical
Mgmt (jump/admin) 2 low high
Client (workstations) 6 very high low
IoT 3 very high very low

Each host $i$ has an exposure score $e_i$ (how likely it is to be compromised first) and an asset value $v_i$ (how much damage follows if an attacker reaches it). The traffic volume between hosts $i$ and $j$ is $T_{ij}$, and $F_{ij}=\mathbb{1}[T_{ij}>0]$ marks a flow that needs a firewall rule if it crosses a boundary.

The decision variable is a segment assignment $x_i \in {0,\dots,K_{\max}-1}$ for every host. The goal is to choose $x$ so that attackers have few paths, legitimate traffic crosses few boundaries, and the design stays manageable.


2. Mathematical Model

Attack-path weight. The damage potential of a host pair is

$$
S_{ij} = e_i v_j + e_j v_i .
$$

Lateral-movement risk. Hosts in the same segment can reach each other freely, while hosts in different segments are reachable only with a small leak probability $\varepsilon$:

$$
R(x) = \varepsilon \sum_{i<j} S_{ij} + (1-\varepsilon)\sum_{i<j} S_{ij},\mathbb{1}[x_i = x_j].
$$

Latency. Traffic crossing a segment boundary passes through an inspection point and pays a delay $\delta$:

$$
L(x) = \delta \sum_{i<j} T_{ij},\mathbb{1}[x_i \neq x_j].
$$

Operational cost. Each segment costs $c_s$ to run, and each cross-boundary flow needs a rule that costs $c_r$:

$$
O(x) = c_s,K(x) + c_r \sum_{i<j} F_{ij},\mathbb{1}[x_i \neq x_j],
$$

where $K(x)$ is the number of non-empty segments.

Scalarized objective. The three terms are normalized by their worst-case reference values (a flat network for risk, full isolation for latency and operations) and then combined:

$$
J(x) = w_R,\frac{R(x)}{R_{\text{flat}}} + w_L,\frac{L(x)}{L_{\text{all}}} + w_O,\frac{O(x)}{O_{\text{all}}}, \qquad \sum w = 1 .
$$

The constraint is $|{i : x_i = k}| \le M$ for every segment $k$, so no segment grows into a new flat network.

This is a graph-partitioning problem with a non-linear cost and is NP-hard in general, so the code uses simulated annealing with a single-host relocation move. A move is accepted with probability

$$
P_{\text{accept}} = \min!\left(1,; e^{-\Delta J/\tau_t}\right), \qquad \tau_t = \tau_0\left(\frac{\tau_1}{\tau_0}\right)^{t/N}.
$$

Why the incremental update matters. Recomputing $J$ from scratch costs $O(n^2)$ per proposal. Instead, the code keeps three matrices that store, for every host, the sum of $S$, $T$ and $F$ toward each segment:

Moving host $i$ from segment $a$ to segment $b$ then changes the objective components by

which is an $O(1)$ lookup. Only the accepted moves pay an $O(n)$ column update. This is the optimized version used below, and it makes many restarts and parameter sweeps cheap.


3. Full Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
import time
from collections import Counter

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from mpl_toolkits.mplot3d import Axes3D # noqa: F401

plt.style.use("dark_background")
plt.rcParams["font.size"] = 8

# ------------------------------------------------------------------
# 1. Synthetic enterprise network
# ------------------------------------------------------------------
SEED = 42
rng = np.random.default_rng(SEED)

ROLES = [("Web", 4), ("App", 5), ("DB", 4), ("Auth", 2),
("Mgmt", 2), ("Client", 6), ("IoT", 3)]
role_id = np.concatenate([np.full(c, r) for r, (_, c) in enumerate(ROLES)])
role_name = np.array([ROLES[r][0] for r in role_id])
n = len(role_id)
host_label = np.array([f"{role_name[i]}{i:02d}" for i in range(n)])

exposure = np.array([0.80, 0.50, 0.20, 0.30, 0.25, 0.90, 0.95])[role_id] * rng.uniform(0.8, 1.2, n)
value = np.array([0.40, 0.60, 1.00, 1.00, 0.90, 0.20, 0.10])[role_id] * rng.uniform(0.8, 1.2, n)

AFF = np.zeros((7, 7))
for (a, b), v in {(0, 1): 6, (1, 2): 8, (0, 0): 1, (1, 1): 2, (2, 2): 3,
(3, 1): 2, (3, 5): 3, (3, 2): 1, (3, 0): 1, (4, 0): 0.8,
(4, 1): 0.8, (4, 2): 0.8, (4, 3): 1.0, (5, 0): 3, (5, 1): 1,
(6, 4): 1.5, (6, 6): 2, (6, 5): 0.5}.items():
AFF[a, b] = AFF[b, a] = v

T = np.zeros((n, n))
for i in range(n):
for j in range(i + 1, n):
a = AFF[role_id[i], role_id[j]]
if a > 0 and rng.random() < min(1.0, a / 3.0):
T[i, j] = T[j, i] = a * rng.exponential(1.0)
F = (T > 0).astype(float)
S = np.outer(exposure, value) + np.outer(value, exposure)
np.fill_diagonal(S, 0.0)

# ------------------------------------------------------------------
# 2. Model parameters
# ------------------------------------------------------------------
EPS, DELTA, C_SEG, C_RULE, MAX_SIZE = 0.05, 0.8, 3.0, 0.5, 8
iu = np.triu_indices(n, 1)
S_u, T_u, F_u = S[iu], T[iu], F[iu]
S_TOT = S_u.sum()
R_FLAT = S_TOT
L_ALL = DELTA * T_u.sum()
O_ALL = C_SEG * n + C_RULE * F_u.sum()


def metrics(x):
same = (x[:, None] == x[None, :])[iu]
risk = EPS * S_TOT + (1 - EPS) * S_u[same].sum()
lat = DELTA * T_u[~same].sum()
ops = C_SEG * len(np.unique(x)) + C_RULE * F_u[~same].sum()
return risk / R_FLAT, lat / L_ALL, ops / O_ALL


def objective(x, w):
r, l, o = metrics(x)
return w[0] * r + w[1] * l + w[2] * o


def anneal(w, kmax, iters=30000, t0=0.05, t1=1e-4, seed=0, record=False):
rg = np.random.default_rng(seed)
if kmax == 1:
x = np.zeros(n, dtype=int)
return x, objective(x, w), None
cap = max(MAX_SIZE, int(np.ceil(n / kmax)))
x = rg.permutation(np.arange(n) % kmax)
onehot = np.eye(kmax)[x]
seg_s, seg_t, seg_f = S @ onehot, T @ onehot, F @ onehot
counts = onehot.sum(axis=0).astype(int)
r_same = 0.5 * seg_s[np.arange(n), x].sum()
t_diff = 0.5 * (T.sum() - (seg_t[np.arange(n), x]).sum())
f_diff = 0.5 * (F.sum() - (seg_f[np.arange(n), x]).sum())
k_used = int((counts > 0).sum())

def cost(rs, td, fd, k):
return (w[0] * (EPS * S_TOT + (1 - EPS) * rs) / R_FLAT
+ w[1] * DELTA * td / L_ALL
+ w[2] * (C_SEG * k + C_RULE * fd) / O_ALL)

cur = cost(r_same, t_diff, f_diff, k_used)
best, best_x = cur, x.copy()
ii = rg.integers(0, n, iters)
bb = rg.integers(0, kmax, iters)
uu = rg.random(iters)
hist_cur, hist_best = [], []
for it in range(iters):
i, b = ii[it], bb[it]
a = x[i]
if b != a and counts[b] < cap:
temp = t0 * (t1 / t0) ** (it / iters)
d_r = seg_s[i, b] - seg_s[i, a]
d_t = seg_t[i, a] - seg_t[i, b]
d_f = seg_f[i, a] - seg_f[i, b]
new_k = k_used - (counts[a] == 1) + (counts[b] == 0)
new = cost(r_same + d_r, t_diff + d_t, f_diff + d_f, new_k)
dj = new - cur
if dj < 0 or uu[it] < np.exp(-dj / temp):
seg_s[:, a] -= S[:, i]
seg_s[:, b] += S[:, i]
seg_t[:, a] -= T[:, i]
seg_t[:, b] += T[:, i]
seg_f[:, a] -= F[:, i]
seg_f[:, b] += F[:, i]
counts[a] -= 1
counts[b] += 1
x[i] = b
r_same += d_r
t_diff += d_t
f_diff += d_f
k_used = int(new_k)
cur = new
if cur < best - 1e-12:
best, best_x = cur, x.copy()
if record and it % 100 == 0:
hist_cur.append(cur)
hist_best.append(best)
hist = (np.array(hist_cur), np.array(hist_best)) if record else None
return best_x, objective(best_x, w), hist


def best_of(w, kmax, restarts=3, iters=30000, record=False):
out = None
for s in range(restarts):
x, j, h = anneal(w, kmax, iters=iters, seed=100 + s, record=record)
if out is None or j < out[1]:
out = (x, j, h)
return out


def relabel(x):
_, inv = np.unique(x, return_inverse=True)
return inv


# ------------------------------------------------------------------
# 3. Solve
# ------------------------------------------------------------------
W = (0.5, 0.3, 0.2)
KMAX = 8
t_start = time.time()
x_opt, j_opt, hist = best_of(W, KMAX, restarts=4, iters=40000, record=True)
x_opt = relabel(x_opt)
t_main = time.time() - t_start

x_flat = np.zeros(n, dtype=int)
x_single = np.arange(n)
x_role = role_id.copy()
x_rand = np.random.default_rng(7).permutation(np.arange(n) % 6)
baselines = [("Flat (no segmentation)", x_flat), ("Per-host isolation", x_single),
("Role-based (7 zones)", x_role), ("Random (6 zones)", x_rand),
("Optimized (SA)", x_opt)]

t_start = time.time()
k_list = list(range(1, 11))
k_res = []
for k in k_list:
xk, jk, _ = best_of(W, k, restarts=3, iters=25000)
k_res.append((k, jk, *metrics(xk)))
k_res = np.array(k_res)

pareto = []
for a in np.linspace(0.05, 0.75, 15):
wp = (a, 0.8 - a, 0.2)
xp, jp, _ = best_of(wp, KMAX, restarts=2, iters=20000)
pareto.append((a, *metrics(xp)))
pareto = np.array(pareto)
t_sweep = time.time() - t_start

# ------------------------------------------------------------------
# 4. Console report
# ------------------------------------------------------------------
print("=" * 72)
print(f"Hosts: {n} | traffic flows: {int(F_u.sum())} | total traffic: {T_u.sum():.1f}")
print(f"Weights (risk, latency, ops) = {W} | cross-segment leak eps = {EPS}")
print("=" * 72)
print(f"{'Design':<26}{'Risk':>8}{'Latency':>10}{'Ops':>8}{'J':>8}{'Zones':>7}{'MaxSize':>9}")
for name, xb in baselines:
r, l, o = metrics(xb)
print(f"{name:<26}{r:8.3f}{l:10.3f}{o:8.3f}{objective(xb, W):8.3f}"
f"{len(np.unique(xb)):7d}{np.bincount(xb).max():9d}")
print("-" * 72)
print("Optimized segments:")
for k in range(x_opt.max() + 1):
members = np.where(x_opt == k)[0]
comp = Counter(role_name[members])
desc = ", ".join(f"{r}x{c}" for r, c in comp.most_common())
print(f" Segment {k}: {len(members):2d} hosts -> {desc}")
print("-" * 72)
r0, l0, o0 = metrics(x_flat)
r1, l1, o1 = metrics(x_opt)
print(f"Risk reduction vs flat : {100 * (1 - r1 / r0):5.1f} %")
print(f"Latency vs per-host isolation: {100 * (1 - l1 / metrics(x_single)[1]):5.1f} % lower")
print(f"Main SA run (4 restarts) : {t_main:5.1f} s")
print(f"K-sweep + Pareto sweep : {t_sweep:5.1f} s")

# ------------------------------------------------------------------
# 5. Visualization (2 rows x 3 columns)
# ------------------------------------------------------------------
fig = plt.figure(figsize=(21, 12))
fig.suptitle("Network Segmentation Design: Risk vs Latency vs Operations", fontsize=16, y=0.98)

ax1 = fig.add_subplot(2, 3, 1)
ax1.plot(hist[0], color="#5dade2", lw=1, alpha=0.7, label="Current J")
ax1.plot(hist[1], color="#f4d03f", lw=2, label="Best J")
ax1.set_xlabel("Iteration (x100)")
ax1.set_ylabel("Objective J")
ax1.set_title("(a) Simulated annealing convergence")
ax1.legend()
ax1.grid(alpha=0.2)

ax2 = fig.add_subplot(2, 3, 2)
order = np.argsort(x_opt, kind="stable")
ax2.imshow(T[np.ix_(order, order)], cmap="magma", interpolation="nearest")
seg_sorted = x_opt[order]
for p in np.where(np.diff(seg_sorted) != 0)[0]:
ax2.axhline(p + 0.5, color="cyan", lw=1.2)
ax2.axvline(p + 0.5, color="cyan", lw=1.2)
ax2.set_xticks(range(n))
ax2.set_yticks(range(n))
ax2.set_xticklabels(host_label[order], rotation=90, fontsize=5)
ax2.set_yticklabels(host_label[order], fontsize=5)
ax2.set_title("(b) Traffic matrix grouped by optimized segments")

ax3 = fig.add_subplot(2, 3, 3, projection="3d")
sc = ax3.scatter(pareto[:, 1], pareto[:, 2], pareto[:, 3], c=pareto[:, 0],
cmap="viridis", s=60, depthshade=False)
r, l, o = metrics(x_opt)
ax3.scatter([r], [l], [o], c="#f4d03f", s=260, marker="*", edgecolors="white",
depthshade=False, label="Chosen design")
ax3.set_xlabel("Risk")
ax3.set_ylabel("Latency")
ax3.set_zlabel("Ops cost")
ax3.set_title("(c) Pareto frontier in 3D")
ax3.legend(loc="upper left", fontsize=8)
fig.colorbar(sc, ax=ax3, shrink=0.55, pad=0.08, label="Risk weight")

ax4 = fig.add_subplot(2, 3, 4, projection="3d")
nseg = x_opt.max() + 1
ang = 2 * np.pi * np.arange(nseg) / nseg
centers = np.stack([4 * np.cos(ang), 4 * np.sin(ang)], axis=1)
pos = np.zeros((n, 3))
cmap = plt.get_cmap("tab10")
for k in range(nseg):
members = np.where(x_opt == k)[0]
for q, i in enumerate(members):
th = 2 * np.pi * q / max(len(members), 1)
pos[i] = [centers[k, 0] + 1.1 * np.cos(th), centers[k, 1] + 1.1 * np.sin(th), value[i] * 3]
thr = np.percentile(T_u[T_u > 0], 55)
for i, j in zip(*iu):
if T[i, j] >= thr:
cross = x_opt[i] != x_opt[j]
ax4.plot([pos[i, 0], pos[j, 0]], [pos[i, 1], pos[j, 1]], [pos[i, 2], pos[j, 2]],
color="#ff4d4d" if cross else "#48c9b0", lw=0.8 if cross else 0.7,
alpha=0.55 if cross else 0.35)
ax4.scatter(pos[:, 0], pos[:, 1], pos[:, 2], c=[cmap(k % 10) for k in x_opt],
s=40 + 120 * exposure, edgecolors="white", depthshade=False)
ax4.set_xlabel("x")
ax4.set_ylabel("y")
ax4.set_zlabel("Asset value")
ax4.set_title("(d) Segmented topology (height = asset value)")
ax4.legend(handles=[Line2D([0], [0], color="#ff4d4d", label="Cross-segment flow"),
Line2D([0], [0], color="#48c9b0", label="Intra-segment flow")],
loc="upper left", fontsize=7)

ax5 = fig.add_subplot(2, 3, 5)
ax5.plot(k_res[:, 0], k_res[:, 2], "o-", color="#e74c3c", label="Risk")
ax5.plot(k_res[:, 0], k_res[:, 3], "s-", color="#5dade2", label="Latency")
ax5.plot(k_res[:, 0], k_res[:, 4], "^-", color="#58d68d", label="Ops cost")
ax5.plot(k_res[:, 0], k_res[:, 1], "D--", color="#f4d03f", lw=2, label="Weighted J")
kb = int(k_res[np.argmin(k_res[:, 1]), 0])
ax5.axvline(kb, color="white", ls=":", alpha=0.6)
ax5.set_xlabel("Maximum number of segments")
ax5.set_ylabel("Normalized value")
ax5.set_title(f"(e) Effect of segment count (best = {kb})")
ax5.legend(fontsize=7)
ax5.grid(alpha=0.2)

ax6 = fig.add_subplot(2, 3, 6)
names = [b[0].split(" (")[0] for b in baselines]
vals = np.array([metrics(b[1]) for b in baselines])
xs = np.arange(len(baselines))
bw = 0.26
ax6.bar(xs - bw, vals[:, 0], bw, color="#e74c3c", label="Risk")
ax6.bar(xs, vals[:, 1], bw, color="#5dade2", label="Latency")
ax6.bar(xs + bw, vals[:, 2], bw, color="#58d68d", label="Ops cost")
ax6.set_xticks(xs)
ax6.set_xticklabels(names, rotation=15, fontsize=7)
ax6.set_ylabel("Normalized value")
ax6.set_title("(f) Design comparison")
ax6.legend(fontsize=7)
ax6.grid(alpha=0.2, axis="y")

fig.subplots_adjust(left=0.05, right=0.97, top=0.92, bottom=0.08, wspace=0.22, hspace=0.3)
plt.show()

4. Code Walkthrough

Section 1: building the network. Hosts are generated by role, and each role has its own exposure and asset-value profile with a little random jitter. Traffic is generated from a role-affinity matrix AFF. Web-to-App and App-to-DB are heavy, Auth talks to many roles at moderate volume, and IoT mostly talks to Mgmt. A pair of hosts gets a flow with probability proportional to its affinity, and the volume is exponentially distributed. This produces the heavy-tailed, role-structured traffic seen in real enterprise networks. The seed is fixed, so the dataset is identical on every run.

Section 2: metrics and normalization. metrics(x) evaluates $R$, $L$ and $O$ with vectorized boolean masks over the upper triangle. Dividing by $R_{\text{flat}}$, $L_{\text{all}}$ and $O_{\text{all}}$ puts all three terms on a comparable scale, so the weights $w$ express policy rather than unit conversion.

Section 3: the annealer. The first half of anneal builds the three segment-sum matrices seg_s, seg_t and seg_f. Each iteration then does the following:

  1. Pick a random host i and a random target segment b.
  2. Skip the move if it would exceed the size cap.
  3. Compute the exact change in each cost component with three array lookups.
  4. Apply the Metropolis rule, and update the matrices only when the move is accepted.

Random numbers are pre-drawn as arrays, which removes Python-level RNG overhead from the loop. Because $\Delta J$ is computed exactly, the final objective(best_x, w) call is a consistency check against the incrementally tracked value. best_of runs several independent restarts and keeps the winner, which guards against unlucky annealing trajectories.

Section 3 (continued): baselines and sweeps. The optimized layout is compared against four reference designs: a flat network, per-host isolation, a role-based layout with one zone per role, and a random layout of six balanced zones. Two sweeps follow. The first changes the maximum allowed number of segments from 1 to 10. The second changes the risk weight $w_R$ from 0.05 to 0.75 while shifting the latency weight, which traces an approximate Pareto frontier.

Section 4: console report. A table compares all designs, followed by the role composition of each optimized segment and the runtime of the experiments.

Section 5: visualization. The six panels are arranged in two rows and three columns. Panels (c) and (d) are 3D plots.


5. Console Output

========================================================================
Hosts: 26 | traffic flows: 131 | total traffic: 463.9
Weights (risk, latency, ops) = (0.5, 0.3, 0.2) | cross-segment leak eps = 0.05
========================================================================
Design                        Risk   Latency     Ops       J  Zones  MaxSize
Flat (no segmentation)       1.000     0.000   0.021   0.504      1       26
Per-host isolation           0.050     1.000   1.000   0.525     26        1
Role-based (7 zones)         0.135     0.945   0.540   0.459      7        6
Random (6 zones)             0.179     0.788   0.509   0.428      6        5
Optimized (SA)               0.238     0.336   0.376   0.295      5        8
------------------------------------------------------------------------
Optimized segments:
  Segment 0:  1 hosts -> Mgmtx1
  Segment 1:  8 hosts -> Clientx5, Authx2, Webx1
  Segment 2:  6 hosts -> Webx3, Appx2, Clientx1
  Segment 3:  7 hosts -> DBx4, Appx3
  Segment 4:  4 hosts -> IoTx3, Mgmtx1
------------------------------------------------------------------------
Risk reduction vs flat      :  76.2 %
Latency vs per-host isolation:  66.4 % lower
Main SA run (4 restarts)    :   3.6 s
K-sweep + Pareto sweep      :  21.0 s

6. Result Image


7. Reading the Results

Design comparison, panel (f) and the console table

The three trivial designs each fail in a different way.

  • Flat network. It has the lowest latency and operating cost, but its risk is normalized to 1.0. Every compromised host has a direct path to every crown jewel.
  • Per-host isolation. It drives risk down to the floor set by the leak probability $\varepsilon$, but latency and operations both hit their maximum. Every flow crosses a firewall, so this design is unmanageable in practice.
  • Role-based zones. This is the textbook design, and its risk is low at about 0.135. However, the traffic in this network is dominated by cross-role flows (Web↔App, App↔DB, Client↔Web), so the role boundaries cut straight through the heaviest communication. Latency is close to the per-host-isolation level at about 0.945.
  • Random zones. Even random assignment lands in a similar region. This shows that the number of zones matters less than which hosts end up together.

The annealed design reaches $J \approx 0.295$, well below every baseline, which sit between roughly 0.43 and 0.53. Risk falls by about 76% relative to the flat network, and latency is about 66% lower than full isolation.

What the optimizer discovered, panel (b) and the segment listing

The optimizer found a layout that mixes roles by traffic affinity.

  • One segment holds the database tier together with three of the App servers. These are the hosts with the heaviest mutual traffic, so keeping them together removes the most expensive boundary crossings.
  • Another segment groups the Web servers with the remaining App and Client hosts that talk to them.
  • A third segment gathers the Clients with the Auth servers, which they query constantly.
  • IoT devices are isolated together with one management host.
  • One management host sits in a segment of its own, acting as a dedicated administrative enclave.

In the heatmap, the bright traffic blocks fall inside the cyan-bordered squares along the diagonal. Heavy flows stay inside segments, and only a thin trickle of low-volume traffic crosses the boundaries. The few remaining bright cells outside the diagonal are the flows that now need firewall rules, and they are exactly the ones the operations term kept to a minimum.

Convergence, panel (a)

The blue curve shows the objective of the current state. It starts high and noisy, because at high temperature $\tau$ the annealer accepts many uphill moves and explores widely. As $\tau$ falls geometrically, the curve calms down and tracks the best-so-far line. The yellow best-so-far curve drops in steps, and each step corresponds to the annealer escaping one basin for a better one. It flattens well before the final iteration, which indicates the schedule is long enough for this problem size.

How many segments? Panel (e)

Going from 1 to 3 segments, risk collapses quickly while latency and operating cost rise only modestly, because the optimizer can place tightly coupled hosts together. Beyond about five segments the curves flatten, and the weighted objective is minimized at five segments. More segments than that bring no benefit, since the extra boundaries would cut high-traffic pairs or add operating cost without reducing risk enough to compensate. The practical rule is that the right number of segments is driven by the traffic structure of the network, not by the number of roles on an org chart.

The Pareto frontier in 3D, panel (c)

Each dot is an optimized design for a different risk weight. Dots with a high risk weight (yellow) sit at low risk but higher latency and operating cost, and dots with a low risk weight (purple) sit at the opposite corner. The gold star marks the chosen design at $w_R = 0.5$. Every point on this surface is a defensible design, and the choice among them is a policy decision about how much latency and operating burden the organization accepts in exchange for containment.

The segmented topology in 3D, panel (d)

Each segment is a cluster on a ring. Node height encodes asset value and node size encodes exposure. The tall nodes (databases and authentication servers) are grouped away from the large nodes (clients and IoT devices). Red lines are the heavy flows that still cross boundaries, and green lines are the heavy flows contained inside a segment. There are far more green lines than red ones, which is the visual signature of a good segmentation: communication is local, and the paths an attacker could use are short and well separated from the high-value assets.


8. Takeaways

  • Segmentation is an optimization problem. Role-based zoning is a reasonable starting point, but traffic-aware assignment can beat it substantially when real communication patterns cut across roles.
  • The $O(1)$ incremental evaluation of the objective is what makes annealing practical, even with multiple restarts and parameter sweeps.
  • The weights $w_R$, $w_L$ and $w_O$ make the policy trade-off explicit. Sweeping them gives decision-makers a frontier of options instead of a single number.
  • The same framework extends naturally to real data. Replace $T$ with measured NetFlow or VPC flow-log volumes, $e_i$ with vulnerability-scan scores, and $v_i$ with business-impact ratings, and the optimizer will propose a segment map ready for review.

Optimizing Encryption Key Management with Python

How Often Should You Rotate, and Where Should Keys Live?

Every security team ends up asking the same two questions about encryption keys:

  1. How often should we rotate them?
  2. Where should we store them? A config file, a self-hosted vault, a cloud KMS, or a hardware security module (HSM)?

Rotate too rarely and one leaked key exposes months of data. Rotate too often and you pay for it in operations: re-wrapping data keys, redeploying services, coordinating teams, handling incidents when something breaks. Storage works the same way. An HSM is very hard to compromise but expensive, while a key in a local file costs nothing until the day it leaks.

In this post we treat this as an optimization problem. We build a cost model, solve it in Python, check it with a Monte Carlo simulation, and show the results in a 2×3 dashboard that includes a 3D cost surface.


The Example Problem

A mid-sized SaaS company encrypts four classes of data. Each class has its own data volume and its own cost per exposed gigabyte (regulatory fines, notification costs, fraud, reputational damage):

Data class Data encrypted per day $D_c$ [GB] Loss per exposed GB $L_c$ [$]
Customer PII 20 200
App logs 200 2
Backups 500 30
Payment tokens 5 5000

Four storage options are available. Each has a yearly key-compromise rate, a fixed yearly cost, a cost per rotation, and a mean detection delay (how long a compromise goes unnoticed):

Storage $s$ Compromise rate $\lambda_s$ [1/yr] Fixed cost $F_s$ [$/yr] Rotation cost $C_s$ [$] Mean detection delay $\delta_s$ [days]
Local file 0.30 0 400 120
Self-hosted vault 0.08 6,000 150 45
Cloud KMS 0.02 2,400 40 10
HSM 0.004 18,000 60 5

Goal: choose a storage backend $s_c$ and a rotation interval $T_c \in [1, 365]$ days for each data class so that the total expected yearly cost is as low as possible. A backend’s fixed cost is paid once, no matter how many classes share it.


Building the Cost Model

Exposure window of a single compromise

Take one key that lives for $T$ days. Everything encrypted under it, from day $0$ to day $T$, is exposed if the key leaks. Suppose the compromise happens at time $U$ and is detected after a delay $\Delta$:

$$
U \sim \mathrm{Uniform}(0, T), \qquad \Delta \sim \mathrm{Exp}\left(\tfrac{1}{\delta}\right)
$$

The attacker can decrypt data written from the key’s creation up to the moment the key is revoked. Revocation happens either at detection or at the next scheduled rotation, whichever comes first:

$$
X = U + \min(\Delta,; T - U)
$$

Its expectation has a closed form. With $V = T - U \sim \mathrm{Uniform}(0,T)$ and $\mathbb{E}[\min(\Delta, v)] = \delta\left(1 - e^{-v/\delta}\right)$:

$$
\mathbb{E}[X] = \frac{T}{2} + \delta - \frac{\delta^2}{T}\left(1 - e^{-T/\delta}\right)
$$

Annual cost for one class on one backend

The first term falls as $T$ grows and the second term rises, so there is an interior optimum:

$$
T^*_{c,s} = \arg\min_{T \in [1,365]} J_{c,s}(T)
$$

When detection is slow ($\delta \gg T$), $\mathbb{E}[X] \approx T$, which gives the classic square-root rule:

$$
T^* \approx \sqrt{\frac{365, C_s}{\lambda_s L_c D_c}}
$$

Joint storage assignment

Fixed costs are shared, so the classes cannot be optimized one at a time. The full problem is:

$$
\min_{s_1,\dots,s_4}; \sum_{c=1}^{4} J_{c,s_c}!\left(T^*_{c,s_c}\right) ;+; \sum_{s} F_s \cdot \mathbb{1}!\left[\exists, c : s_c = s\right]
$$

There are only $4^4 = 256$ assignments, so we can enumerate them all exactly.

Tail risk

Averages hide the bad years. We simulate the annual loss $Y$ and report Value-at-Risk and Conditional Value-at-Risk:

The number of compromises per year for each class follows $\mathrm{Poisson}(\lambda_s)$.


Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import time
import itertools
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from mpl_toolkits.mplot3d import Axes3D # noqa: F401
from scipy.optimize import minimize_scalar

rng = np.random.default_rng(42)

# ------------------------------------------------------------
# 1. Problem data
# ------------------------------------------------------------
storages = ["Local file", "Self-hosted vault", "Cloud KMS", "HSM"]
lam = np.array([0.30, 0.08, 0.02, 0.004]) # key compromises per year
F = np.array([0.0, 6000.0, 2400.0, 18000.0]) # fixed cost per year [$]
C_rot = np.array([400.0, 150.0, 40.0, 60.0]) # cost per rotation [$]
delta = np.array([120.0, 45.0, 10.0, 5.0]) # mean detection delay [days]

classes = ["Customer PII", "App logs", "Backups", "Payment tokens"]
D = np.array([20.0, 200.0, 500.0, 5.0]) # data encrypted per day [GB]
L = np.array([200.0, 2.0, 30.0, 5000.0]) # loss per exposed GB [$]

T_MIN, T_MAX = 1.0, 365.0
T_grid = np.linspace(T_MIN, T_MAX, 3641) # 0.1-day resolution

# ------------------------------------------------------------
# 2. Analytical cost model
# ------------------------------------------------------------
def exposure_days(T, d):
"""E[U + min(Delta, T-U)], U~Unif(0,T), Delta~Exp(mean d)."""
T = np.asarray(T, dtype=float)
return T / 2.0 + d - (d ** 2 / T) * (1.0 - np.exp(-T / d))

def variable_cost(T, s, c, lam_scale=1.0):
"""Rotation cost + expected breach loss per year (no fixed cost)."""
rot = 365.0 / T * C_rot[s]
brc = lam[s] * lam_scale * L[c] * D[c] * exposure_days(T, delta[s])
return rot, brc

# Optimal T for every (class, storage) pair: vectorized grid + refinement
n_c, n_s = len(classes), len(storages)
T_star = np.zeros((n_c, n_s))
J_star = np.zeros((n_c, n_s))
for c in range(n_c):
for s in range(n_s):
rot, brc = variable_cost(T_grid, s, c)
k = np.argmin(rot + brc)
lo, hi = T_grid[max(k - 1, 0)], T_grid[min(k + 1, len(T_grid) - 1)]
if hi > lo:
res = minimize_scalar(lambda t: sum(variable_cost(t, s, c)),
bounds=(lo, hi), method="bounded")
T_star[c, s], J_star[c, s] = res.x, res.fun
else:
T_star[c, s], J_star[c, s] = T_grid[k], (rot + brc)[k]

# ------------------------------------------------------------
# 3. Joint assignment (shared fixed cost) by full enumeration
# ------------------------------------------------------------
assign = np.array(list(itertools.product(range(n_s), repeat=n_c))) # (256, 4)
var_part = J_star[np.arange(n_c), assign].sum(axis=1)
used = np.zeros((len(assign), n_s), dtype=bool)
used[np.arange(len(assign))[:, None], assign] = True
fixed_part = (used * F).sum(axis=1)
total = var_part + fixed_part
best = np.argmin(total)
best_assign = assign[best]

print("=== Optimal T* [days] for each (class, storage) ===")
print(f"{'':16s}" + "".join(f"{s:>19s}" for s in storages))
for c in range(n_c):
print(f"{classes[c]:16s}" + "".join(f"{T_star[c, s]:19.1f}" for s in range(n_s)))

print("\n=== Optimal variable cost J* [$/yr] (without fixed cost) ===")
for c in range(n_c):
print(f"{classes[c]:16s}" + "".join(f"{J_star[c, s]:19,.0f}" for s in range(n_s)))

print("\n=== Best joint policy ===")
for c in range(n_c):
s = best_assign[c]
print(f"{classes[c]:16s} -> {storages[s]:18s} rotate every {T_star[c, s]:6.1f} days")
print(f"Fixed cost : ${fixed_part[best]:,.0f}/yr")
print(f"Variable cost: ${var_part[best]:,.0f}/yr")
print(f"Total : ${total[best]:,.0f}/yr")

base_s = np.zeros(n_c, dtype=int) # everything in a local file
base_T = np.full(n_c, 365.0) # yearly rotation
base_cost = F[0] + sum(sum(variable_cost(base_T[c], base_s[c], c)) for c in range(n_c))
print(f"\nBaseline (local file, 365-day rotation): ${base_cost:,.0f}/yr")
print(f"Reduction: {100 * (1 - total[best] / base_cost):.1f}%")

# ------------------------------------------------------------
# 4. Monte Carlo simulation of annual loss
# ------------------------------------------------------------
def simulate_naive(s_vec, T_vec, n_years):
out = np.zeros(n_years)
for y in range(n_years):
loss = 0.0
for c in range(n_c):
s, T = s_vec[c], T_vec[c]
for _ in range(rng.poisson(lam[s])):
u = rng.uniform(0, T)
dly = rng.exponential(delta[s])
loss += L[c] * D[c] * (u + min(dly, T - u))
out[y] = loss
return out

def simulate_fast(s_vec, T_vec, n_years):
out = np.zeros(n_years)
for c in range(n_c):
s, T = s_vec[c], T_vec[c]
k = rng.poisson(lam[s], size=n_years)
m = int(k.sum())
if m == 0:
continue
u = rng.uniform(0, T, size=m)
dly = rng.exponential(delta[s], size=m)
loss = L[c] * D[c] * (u + np.minimum(dly, T - u))
out += np.bincount(np.repeat(np.arange(n_years), k),
weights=loss, minlength=n_years)
return out

opt_T = T_star[np.arange(n_c), best_assign]

t0 = time.perf_counter(); _ = simulate_naive(base_s, base_T, 20_000); t_naive = time.perf_counter() - t0
t0 = time.perf_counter(); _ = simulate_fast(base_s, base_T, 20_000); t_fast = time.perf_counter() - t0
print(f"\nMonte Carlo 20,000 years: loop {t_naive:.3f}s, vectorized {t_fast:.4f}s "
f"(x{t_naive / max(t_fast, 1e-9):.0f} faster)")

N = 500_000
loss_base = simulate_fast(base_s, base_T, N)
loss_opt = simulate_fast(best_assign, opt_T, N)

def risk_stats(x):
v95, v99 = np.quantile(x, [0.95, 0.99])
cvar99 = x[x >= v99].mean()
return x.mean(), v95, v99, cvar99

for name, x in [("Baseline", loss_base), ("Optimized", loss_opt)]:
m, v95, v99, cv = risk_stats(x)
print(f"{name:10s} mean=${m:>12,.0f} VaR95=${v95:>12,.0f} "
f"VaR99=${v99:>12,.0f} CVaR99=${cv:>12,.0f}")

# ------------------------------------------------------------
# 5. Sensitivity data
# ------------------------------------------------------------
c_pii = 0
s_kms = 2
T_s = np.geomspace(1, 365, 120)
scale = np.geomspace(0.1, 10, 100)
TT, SS = np.meshgrid(T_s, scale)
rot3, brc3 = variable_cost(TT, s_kms, c_pii, lam_scale=SS)
Z = np.log10(rot3 + brc3 + F[s_kms])
T_opt_line = T_s[np.argmin(rot3 + brc3, axis=1)]
Z_opt_line = np.log10((rot3 + brc3).min(axis=1) + F[s_kms])

lam_h = np.geomspace(0.001, 1.0, 120)
crot_h = np.geomspace(5, 2000, 120)
LL, CC = np.meshgrid(lam_h, crot_h, indexing="ij")
T_cube = T_grid[::5]
cost_cube = (365.0 / T_cube[None, None, :] * CC[..., None]
+ LL[..., None] * L[c_pii] * D[c_pii]
* exposure_days(T_cube, delta[s_kms])[None, None, :])
T_heat = T_cube[np.argmin(cost_cube, axis=2)]

# ------------------------------------------------------------
# 6. Plots (2 rows x 3 cols)
# ------------------------------------------------------------
fig = plt.figure(figsize=(20, 12))
colors = ["tab:red", "tab:orange", "tab:blue", "tab:green"]

ax1 = fig.add_subplot(2, 3, 1)
for s in range(n_s):
rot, brc = variable_cost(T_grid, s, c_pii)
ax1.plot(T_grid, rot + brc + F[s], color=colors[s], label=storages[s])
ax1.plot(T_star[c_pii, s], J_star[c_pii, s] + F[s], "o", color=colors[s])
ax1.set_xscale("log"); ax1.set_yscale("log")
ax1.set_xlabel("Rotation interval T [days]"); ax1.set_ylabel("Annual cost [$]")
ax1.set_title("Customer PII: total cost vs T (dots = T*)")
ax1.legend(); ax1.grid(True, which="both", alpha=0.3)

ax2 = fig.add_subplot(2, 3, 2)
rot, brc = variable_cost(T_grid, s_kms, c_pii)
ax2.stackplot(T_grid, np.full_like(T_grid, F[s_kms]), rot, brc,
labels=["Fixed", "Rotation", "Expected breach"],
colors=["lightgray", "tab:cyan", "tab:pink"], alpha=0.8)
ax2.axvline(T_star[c_pii, s_kms], color="k", ls="--",
label=f"T* = {T_star[c_pii, s_kms]:.1f} d")
ax2.set_xlim(1, 120); ax2.set_ylim(0, 3 * (J_star[c_pii, s_kms] + F[s_kms]))
ax2.set_xlabel("Rotation interval T [days]"); ax2.set_ylabel("Annual cost [$]")
ax2.set_title("Customer PII in Cloud KMS: cost breakdown")
ax2.legend(loc="upper right"); ax2.grid(alpha=0.3)

ax3 = fig.add_subplot(2, 3, 3, projection="3d")
ax3.plot_surface(np.log10(TT), np.log10(SS), Z, cmap="viridis", alpha=0.85,
linewidth=0, antialiased=True)
ax3.plot(np.log10(T_opt_line), np.log10(scale), Z_opt_line + 0.02,
color="red", lw=3, label="Optimal T*")
ax3.set_xlabel("log10 T [days]"); ax3.set_ylabel("log10 breach-rate scale")
ax3.set_zlabel("log10 annual cost [$]")
ax3.set_title("Cost surface over T and breach rate")
ax3.view_init(elev=28, azim=-130); ax3.legend()

ax4 = fig.add_subplot(2, 3, 4)
bins = np.geomspace(1e2, max(loss_base.max(), loss_opt.max()) * 1.1, 80)
ax4.hist(loss_base[loss_base > 0], bins=bins, alpha=0.6, color="tab:red", label="Baseline")
ax4.hist(loss_opt[loss_opt > 0], bins=bins, alpha=0.6, color="tab:green", label="Optimized")
for x, col in [(loss_base, "tab:red"), (loss_opt, "tab:green")]:
ax4.axvline(np.quantile(x, 0.99), color=col, ls="--")
ax4.set_xscale("log"); ax4.set_yscale("log")
ax4.set_xlabel("Annual breach loss [$] (non-zero years)"); ax4.set_ylabel("Count")
ax4.set_title("Monte Carlo loss distribution (dashed = VaR99)")
ax4.legend(); ax4.grid(alpha=0.3)

ax5 = fig.add_subplot(2, 3, 5)
pc = ax5.pcolormesh(lam_h, crot_h, T_heat.T, shading="auto", cmap="plasma",
norm=LogNorm(vmin=T_heat.min(), vmax=T_heat.max()))
cs = ax5.contour(lam_h, crot_h, T_heat.T, levels=[7, 30, 90, 180], colors="white")
ax5.clabel(cs, fmt="%d d")
ax5.set_xscale("log"); ax5.set_yscale("log")
ax5.set_xlabel("Breach rate λ [1/yr]"); ax5.set_ylabel("Cost per rotation [$]")
ax5.set_title("Optimal T* map (Customer PII, δ = 10 d)")
fig.colorbar(pc, ax=ax5, label="T* [days]")

ax6 = fig.add_subplot(2, 3, 6)
base_each = [sum(variable_cost(base_T[c], base_s[c], c)) for c in range(n_c)]
opt_each = [J_star[c, best_assign[c]] for c in range(n_c)]
x = np.arange(n_c); w = 0.38
ax6.bar(x - w / 2, base_each, w, color="tab:red", label="Baseline")
ax6.bar(x + w / 2, opt_each, w, color="tab:green", label="Optimized")
for i in range(n_c):
ax6.text(x[i] + w / 2, opt_each[i] * 1.15,
f"{storages[best_assign[i]]}\nT*={opt_T[i]:.0f}d",
ha="center", fontsize=8)
ax6.set_yscale("log"); ax6.set_xticks(x); ax6.set_xticklabels(classes, rotation=15)
ax6.set_ylabel("Variable cost [$/yr]")
ax6.set_title(f"Per-class cost (fixed: {fixed_part[best]:,.0f} vs {F[0]:,.0f} USD/yr)")
ax6.legend(); ax6.grid(axis="y", alpha=0.3)

plt.tight_layout()
plt.show()

Code Walkthrough

1. Problem data

The tables above become NumPy arrays: lam, F, C_rot and delta for the storage backends, and D and L for the data classes. Indexing always follows [class, storage], so J_star[c, s] reads as “the cost of putting class c on backend s.”

T_grid covers 1 to 365 days in steps of 0.1 day. That fine grid is the first stage of the optimizer.

2. Analytical cost model

  • exposure_days(T, d) implements $\mathbb{E}[X] = \frac{T}{2} + \delta - \frac{\delta^2}{T}(1 - e^{-T/\delta})$. It is written entirely with NumPy operations, so it accepts a scalar, a 1D grid or a 3D cube, which the sensitivity analysis needs later.
  • variable_cost(T, s, c, lam_scale) returns the two parts of $J_{c,s}(T)$ separately: rotation cost and expected breach loss. Keeping them apart lets us draw the stacked breakdown chart. The lam_scale argument multiplies $\lambda_s$ so we can test what happens if the threat environment gets worse or better.

Two-stage optimization. For each of the 16 (class, storage) pairs:

  1. Evaluate $J$ on all 3,641 grid points in one vectorized call and take argmin.
  2. Refine with scipy.optimize.minimize_scalar(method="bounded") inside the bracket formed by the neighboring grid points.

The grid step guarantees we find the right basin, even when the optimum sits at the boundary. Brent’s method then makes it precise. The if hi > lo guard handles the edge case where the optimum lands on the first or last grid point.

3. Joint assignment with shared fixed costs

itertools.product(range(4), repeat=4) generates all 256 storage assignments as a (256, 4) array. All of them are scored at once without a Python loop:

  • J_star[np.arange(n_c), assign] uses fancy indexing to pick the right $J^*$ for every class in every assignment, then sums each row.
  • The boolean matrix used marks which backends each assignment uses, so (used * F).sum(axis=1) charges each backend’s fixed cost only once.

The baseline is the “do nothing” policy: every key in a local file, rotated once a year.

4. Monte Carlo simulation and the speed-up

The model above is analytical. To see the full loss distribution, including the tails, we simulate years of operation.

  • simulate_naive is the textbook version: loop over years, then classes, then each compromise event, drawing random numbers one at a time. It is easy to read but slow, because the work runs in Python loops.
  • simulate_fast produces the same distribution with vectorized NumPy:
    1. Draw all yearly event counts in one call: k = rng.poisson(lam[s], size=n_years).
    2. Draw all m = k.sum() compromise times and detection delays at once.
    3. Compute every event’s loss in one vector expression with np.minimum.
    4. Map each event back to its year with np.repeat(np.arange(n_years), k) and add up the losses per year with np.bincount(..., weights=loss).

The code times both versions on 20,000 simulated years and prints the speed-up, which comes out at roughly 30–60×. The fast version then runs 500,000 years for each policy to get stable estimates of $\mathrm{VaR}{99}$ and $\mathrm{CVaR}{99}$.

5. Sensitivity data

  • 3D surface: for Customer PII on Cloud KMS, we evaluate total cost over a $120 \times 100$ grid of $T$ (1–365 days) and breach-rate multiplier (0.1× to 10×). For each multiplier, the row-wise argmin traces the path of the optimal $T^*$.
  • $T^$ heat map:* a 3D cube of shape $(\lambda, C_{rot}, T)$ is evaluated in one broadcast expression, and argmin(axis=2) gives the optimal rotation interval for every combination of breach rate and rotation cost. That is 14,400 optimizations in one NumPy call.

6. Plotting

One figure holds a 2×3 grid built with add_subplot(2, 3, k). Panel 3 uses projection="3d". The axes that span orders of magnitude use log scales. The panel-6 title deliberately avoids two $ signs, because Matplotlib would read the text between them as math.


Execution Results

=== Optimal T* [days] for each (class, storage) ===
                         Local file  Self-hosted vault          Cloud KMS                HSM
Customer PII                   11.2               13.7               16.4               51.8
App logs                       36.6               47.6               58.8              165.3
Backups                         5.7                6.9                7.8               26.1
Payment tokens                  4.4                5.3                5.9               19.8

=== Optimal variable cost J* [$/yr] (without fixed cost) ===
Customer PII                 26,271              8,174              1,953                909
App logs                      8,174              2,463                550                272
Backups                      51,062             16,011              3,959              1,865
Payment tokens               65,979             20,728              5,173              2,472

=== Best joint policy ===
Customer PII     -> Cloud KMS          rotate every   16.4 days
App logs         -> Cloud KMS          rotate every   58.8 days
Backups          -> Cloud KMS          rotate every    7.8 days
Payment tokens   -> Cloud KMS          rotate every    5.9 days
Fixed cost   : $2,400/yr
Variable cost: $11,634/yr
Total        : $14,034/yr

Baseline (local file, 365-day rotation): $3,530,494/yr
Reduction: 99.6%

Monte Carlo 20,000 years: loop 0.577s, vectorized 0.0121s (x47 faster)
Baseline   mean=$   3,526,623  VaR95=$  12,728,307  VaR99=$  18,396,000  CVaR99=$  21,841,976
Optimized  mean=$       6,187  VaR95=$      51,870  VaR99=$     147,317  CVaR99=$     154,034


Interpreting the Results

The optimal policy

The optimizer puts all four data classes on Cloud KMS, with rotation intervals that differ a lot:

Data class Storage Optimal rotation $T^*$
Customer PII Cloud KMS ≈ 16 days
App logs Cloud KMS ≈ 59 days
Backups Cloud KMS ≈ 8 days
Payment tokens Cloud KMS ≈ 6 days

The total expected cost is about $14,000 per year ($2,400 fixed plus about $11,600 variable). The baseline costs about $3.5 million per year, so the reduction is more than 99%.

Two lessons stand out:

  • There is no single right rotation period. Payment tokens, at $5,000 per exposed GB, should rotate about every 6 days. App logs, at $2 per GB, only need rotation every two months. A blanket “rotate every 90 days” rule rotates logs too often and leaves payment tokens exposed far too long.
  • The safest backend is not automatically the best one. On variable cost alone, the HSM wins for every class. Its lower breach rate and 5-day detection delay make $J^*$ roughly half of Cloud KMS’s. But its $18,000 fixed cost outweighs that saving: an all-HSM setup costs about $23,500 a year, against about $14,000 for an all-KMS setup. The joint enumeration catches this because it charges fixed costs only once per backend. Optimizing each class separately would miss it.

Panel 1: Total cost vs. rotation interval (Customer PII)

Each backend traces a U-shaped curve on log-log axes. On the left, frequent rotation is expensive. On the right, long-lived keys build up exposure. The dots mark each backend’s $T^*$. Notice that the better the backend, the longer you can safely keep a key: the optimum moves from about 11 days for a local file to about 52 days for an HSM. The HSM curve is very flat, so its rotation period matters little. The local-file curve is steep, so getting the period wrong there is costly.

Panel 2: Cost breakdown (Customer PII on Cloud KMS)

The stacked areas show why the optimum exists. The gray band is the fixed KMS fee, which does not depend on $T$. The cyan band (rotation) shrinks like $1/T$. The pink band (expected breach loss) grows roughly linearly once $T \gg \delta$. The dashed line at $T^* \approx 16.4$ days sits where the marginal saving from rotating less often equals the marginal growth in exposure.

Panel 3: 3D cost surface

The 3D plot shows total cost as a function of rotation interval and a multiplier on the breach rate. The red line traces $T^*$ across the surface. As the threat level rises (moving toward the back of the plot), the valley moves toward shorter rotation intervals and the whole surface rises. This is the square-root rule $T^* \propto \lambda^{-1/2}$ in visual form. If your threat intelligence says attacks are increasing, your rotation schedule should tighten, roughly in proportion to the square root of the increase.

Panel 4: Monte Carlo loss distribution

The histograms compare simulated annual losses in years with at least one compromise. The baseline (red) is centered in the millions of dollars, and its $\mathrm{VaR}{99}$ is about $18 million. The optimized policy (green) moves the whole distribution down by two to three orders of magnitude, with $\mathrm{VaR}{99}$ around $150,000. The simulated means match the analytical expected breach losses, which confirms the closed-form exposure formula. The optimization lowers the average cost, and it also removes most of the catastrophic tail, which is what a risk committee cares about.

Panel 5: Optimal rotation map

This heat map is a quick lookup tool. For a given breach rate (x-axis) and cost per rotation (y-axis), the color shows $T^*$, and the white contours mark 7, 30, 90 and 180 days. The contours are straight diagonal lines on log-log axes, which matches $T^* \propto \sqrt{C_{rot}/\lambda}$. In practice there are two ways to shorten the safe rotation period:

  • Lower the cost per rotation through automation (moving down the plot).
  • Accept a higher threat level and pay for frequent rotation (moving right).

Automating rotation is what makes short rotation periods affordable.

Panel 6: Cost by data class

On a log scale, the baseline’s variable cost for each class (red) runs from tens of thousands to millions of dollars a year. The optimized cost (green) is about $10^3$ for every class. The labels show the backend and rotation interval chosen for each class. Payment tokens and backups gain the most: they have the highest $L_c D_c$ and therefore the most exposure to remove.


Takeaways

  • Key rotation is a trade-off between operational cost, which scales with $1/T$, and exposure from a leaked key, which grows with $T$. A simple model makes that trade-off explicit and solvable.
  • The optimal interval follows $T^* \approx \sqrt{365,C_s / (\lambda_s L_c D_c)}$. High-value data should rotate more often, and automation makes that cheap.
  • Detection speed $\delta$ matters as much as prevention. A fast-detecting backend caps the exposure window no matter how long the rotation period is.
  • Storage choice is a portfolio decision. Shared fixed costs mean you must optimize all data classes together. The most secure option per class is not always the best overall.
  • Vectorizing the Monte Carlo simulation with NumPy (poisson with size, repeat, bincount) makes simulating hundreds of thousands of years fast enough for quick what-if analysis of tail risk.

Leak-Aware Data Placement

Balancing Breach Probability, Latency, and Cost with Mixed-Integer Programming

Where should each dataset live? Putting everything in the cheapest cloud region is tempting. Putting everything in the on-premises vault feels safe. In practice, every placement decision trades three quantities against each other: expected loss from a breach, access latency for users, and storage cost. This article builds a concrete placement problem, solves it exactly, and visualizes the trade-off surface.

1. The Scenario

A company holds $N = 12$ datasets and can place each one in exactly one of $M = 5$ locations.

Location Annual breach probability $p_j$ Cost (USD/TB-month) Capacity (TB)
On-prem Tokyo 0.006 40 150
On-prem Osaka 0.008 36 150
Cloud Tokyo 0.020 23 400
Cloud Singapore 0.018 21 400
Cloud Oregon 0.025 18 400

Users access the data from three regions: Japan, Southeast Asia, and North America. Each dataset $i$ has a size $s_i$ (TB), a loss $v_i$ (million USD) if it leaks, and an access volume $a_{ik}$ (thousand requests per day) from each user region $k$. Customer PII, payment records, employee HR data, and partner contracts are bound by a data-residency rule and must stay in Japan.

2. Mathematical Formulation

Let $x_{ij}\in{0,1}$ indicate that dataset $i$ is placed at location $j$. The three objectives are linear in $x$:

$$
f_{\text{risk}}(x)=\sum_{i=1}^{N}\sum_{j=1}^{M} p_j, v_i, x_{ij},
$$

$$
f_{\text{lat}}(x)=\frac{1}{\sum_{i,k} a_{ik}}\sum_{i=1}^{N}\sum_{j=1}^{M}\Big(\sum_{k=1}^{K} a_{ik},\ell_{jk}\Big)x_{ij},
$$

$$
f_{\text{cost}}(x)=12\sum_{i=1}^{N}\sum_{j=1}^{M} c_j, s_i, x_{ij},
$$

where $\ell_{jk}$ is the network latency (ms) from user region $k$ to location $j$ and $c_j$ is the monthly price per TB.

The constraints are:

$$
\sum_{j} x_{ij}=1 \quad \forall i, \qquad
\sum_{i} s_i,x_{ij}\le C_j \quad \forall j,
$$

$$
\sum_{i} v_i,x_{ij}\le B \quad \forall j, \qquad
x_{ij}=0 \ \text{ for forbidden pairs (residency)}.
$$

The second line contains the blast-radius cap $B = 160$ million USD. No single location may hold more than $B$ of exposed loss, so one breach can never be catastrophic.

To explore the trade-off, each objective is normalized with an ideal value $f_k^{\ast}$ (its single-objective optimum) and a nadir value $f_k^{\text{nad}}$ (its worst value among the three single-objective optima). The scalarized problem is

$$
\min_{x}\ \sum_{k\in{\text{risk, lat, cost}}} w_k,\frac{f_k(x)-f_k^{\ast}}{f_k^{\text{nad}}-f_k^{\ast}},
\qquad w_k\ge 0,\quad \sum_k w_k=1 .
$$

Sweeping $w$ over the simplex traces out the Pareto front. The resulting problem has only $60$ binary variables, so an exact MILP solver finishes each instance almost instantly. The script builds the constraint matrices once and reuses them for every weight vector, which keeps the whole sweep lightweight.

3. Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
import time
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import milp, LinearConstraint, Bounds

plt.style.use("dark_background")
rng = np.random.default_rng(42)

# ------------------------------------------------------------
# 1. Problem data
# ------------------------------------------------------------
datasets = ["Customer PII", "Payment records", "Employee HR", "Source code",
"Product catalog", "Web analytics", "Access logs", "ML training set",
"Backups", "Marketing assets", "Sensor telemetry", "Partner contracts"]
locations = ["On-prem Tokyo", "On-prem Osaka", "Cloud Tokyo",
"Cloud Singapore", "Cloud Oregon"]
regions = ["Japan", "SE Asia", "N. America"]

N, M, K = len(datasets), len(locations), len(regions)

size_tb = np.array([8, 12, 3, 2, 5, 40, 60, 80, 100, 20, 50, 1], dtype=float)
loss_musd = np.array([50, 80, 30, 40, 2, 5, 8, 20, 60, 1, 3, 25], dtype=float)

# thousand requests per day issued from each user region
access = np.array([
[90, 5, 5],
[120, 10, 10],
[20, 0, 0],
[40, 5, 5],
[60, 80, 90],
[50, 70, 60],
[30, 20, 10],
[15, 5, 20],
[2, 1, 1],
[30, 40, 70],
[20, 120, 10],
[8, 2, 4],
], dtype=float)

p_leak = np.array([0.006, 0.008, 0.020, 0.018, 0.025]) # annual breach probability
cost_tb_month = np.array([40.0, 36.0, 23.0, 21.0, 18.0]) # USD per TB-month
capacity_tb = np.array([150.0, 150.0, 400.0, 400.0, 400.0]) # TB per location
blast_cap = 160.0 # max exposed loss per location [M USD]

latency_ms = np.array([
[5, 70, 110],
[10, 75, 115],
[6, 68, 105],
[70, 8, 170],
[100, 165, 25],
], dtype=float) # location x user region

residency_sets = [0, 1, 2, 11] # datasets that must stay in Japan
allowed = np.ones((N, M), dtype=bool)
for i in residency_sets:
allowed[i, 3] = False
allowed[i, 4] = False

# ------------------------------------------------------------
# 2. Linear coefficients of the three objectives
# ------------------------------------------------------------
risk_coef = np.outer(loss_musd, p_leak) * 1000.0 # k USD / year
lat_coef = (access @ latency_ms.T) / access.sum() # mean latency [ms]
cost_coef = np.outer(size_tb, cost_tb_month) * 12.0 / 1000.0 # k USD / year
coefs = np.stack([risk_coef, lat_coef, cost_coef]) # shape (3, N, M)


def evaluate(x):
return (coefs * x[None, :, :]).sum(axis=(1, 2))


# ------------------------------------------------------------
# 3. Exact MILP solver (HiGHS via SciPy)
# ------------------------------------------------------------
A_assign = np.zeros((N, N * M))
A_cap = np.zeros((M, N * M))
A_blast = np.zeros((M, N * M))
for i in range(N):
A_assign[i, i * M:(i + 1) * M] = 1.0
for j in range(M):
A_cap[j, i * M + j] = size_tb[i]
A_blast[j, i * M + j] = loss_musd[i]

base_constraints = [
LinearConstraint(A_assign, 1.0, 1.0),
LinearConstraint(A_cap, -np.inf, capacity_tb),
LinearConstraint(A_blast, -np.inf, np.full(M, blast_cap)),
]
var_bounds = Bounds(np.zeros(N * M), allowed.ravel().astype(float))


def solve_milp(c_matrix):
res = milp(c=c_matrix.ravel(),
constraints=base_constraints,
integrality=np.ones(N * M),
bounds=var_bounds)
if not res.success:
raise RuntimeError("MILP failed: " + str(res.message))
return np.round(res.x).reshape(N, M).astype(int)


# Payoff table: optimise each objective alone
single_solutions = [solve_milp(coefs[k]) for k in range(3)]
payoff = np.array([evaluate(x) for x in single_solutions])
ideal = np.diag(payoff).copy()
nadir = payoff.max(axis=0)
ranges = np.maximum(nadir - ideal, 1e-9)


def norm_coef(w):
return sum(w[k] * coefs[k] / ranges[k] for k in range(3))


def score(F, w):
return float(np.sum(np.asarray(w) * (F - ideal) / ranges))


# ------------------------------------------------------------
# 4. Weighted-sum sweep over the simplex
# ------------------------------------------------------------
t0 = time.perf_counter()
sweep_w, sweep_S, sweep_x = [], [], []
for a in range(11):
for b in range(11 - a):
w = np.array([a / 10.0, b / 10.0, (10 - a - b) / 10.0])
x = solve_milp(norm_coef(w))
sweep_w.append(w)
sweep_S.append(score(evaluate(x), w))
sweep_x.append(x)
sweep_w = np.array(sweep_w)
sweep_S = np.array(sweep_S)
sweep_time = time.perf_counter() - t0

unique = {}
for x in sweep_x:
unique[tuple(x.ravel())] = x
uniq_x = list(unique.values())
uniq_F = np.array([evaluate(x) for x in uniq_x])


def non_dominated(F):
keep = []
for a in range(len(F)):
dom = np.any(np.all(F <= F[a] + 1e-9, axis=1) & np.any(F < F[a] - 1e-9, axis=1))
keep.append(not dom)
return np.array(keep)


mask = non_dominated(uniq_F)
pareto_x = [x for x, m in zip(uniq_x, mask) if m]
pareto_F = uniq_F[mask]

# ------------------------------------------------------------
# 5. Balanced solution, greedy heuristic and random baseline
# ------------------------------------------------------------
w_bal = np.array([1 / 3, 1 / 3, 1 / 3])
x_bal = solve_milp(norm_coef(w_bal))
F_bal = evaluate(x_bal)


def greedy_solution(w):
c = norm_coef(w)
x = np.zeros((N, M), dtype=int)
used_cap = np.zeros(M)
used_blast = np.zeros(M)
for i in np.argsort(-loss_musd):
best_j, best_c = -1, np.inf
for j in range(M):
if not allowed[i, j]:
continue
if used_cap[j] + size_tb[i] > capacity_tb[j] + 1e-9:
continue
if used_blast[j] + loss_musd[i] > blast_cap + 1e-9:
continue
if c[i, j] < best_c:
best_j, best_c = j, c[i, j]
if best_j < 0:
raise RuntimeError("Greedy heuristic found no feasible site.")
x[i, best_j] = 1
used_cap[best_j] += size_tb[i]
used_blast[best_j] += loss_musd[i]
return x


x_greedy = greedy_solution(w_bal)
F_greedy = evaluate(x_greedy)


def is_feasible(x):
cap_ok = np.all((x * size_tb[:, None]).sum(axis=0) <= capacity_tb + 1e-9)
blast_ok = np.all((x * loss_musd[:, None]).sum(axis=0) <= blast_cap + 1e-9)
return bool(cap_ok and blast_ok)


random_x, trials = [], 0
while len(random_x) < 3000 and trials < 100000:
trials += 1
x = np.zeros((N, M), dtype=int)
for i in range(N):
x[i, rng.choice(np.flatnonzero(allowed[i]))] = 1
if is_feasible(x):
random_x.append(x)
random_F = np.array([evaluate(x) for x in random_x])
random_S = ((random_F - ideal) / ranges) @ w_bal

# ------------------------------------------------------------
# 6. Console report
# ------------------------------------------------------------
print("=== Problem size ===")
print(f"datasets: {N}, locations: {M}, binary variables: {N * M}")
print(f"feasible random placements sampled: {len(random_x)} (trials: {trials})")
print()
print("=== Payoff table (rows: optimised objective) ===")
print(f"{'optimised for':<16}{'risk [k$/yr]':>14}{'latency [ms]':>14}{'cost [k$/yr]':>14}")
for name, row in zip(["risk", "latency", "cost"], payoff):
print(f"{name:<16}{row[0]:>14.1f}{row[1]:>14.2f}{row[2]:>14.1f}")
print()
print(f"=== Weighted-sum sweep: {len(sweep_x)} MILPs in {sweep_time:.2f} s, "
f"{len(pareto_x)} Pareto-optimal placements ===")
print()
print("=== Method comparison (balanced weights 1/3, 1/3, 1/3) ===")
print(f"{'method':<22}{'risk':>10}{'latency':>10}{'cost':>10}{'score':>10}")
rows = [
("Random (mean)", random_F.mean(axis=0), float(random_S.mean())),
("Random (best of all)", random_F[np.argmin(random_S)], float(random_S.min())),
("Greedy heuristic", F_greedy, score(F_greedy, w_bal)),
("MILP optimum", F_bal, score(F_bal, w_bal)),
]
for name, F, s in rows:
print(f"{name:<22}{F[0]:>10.1f}{F[1]:>10.2f}{F[2]:>10.1f}{s:>10.4f}")
print()
print("=== Optimal placement (balanced weights) ===")
print(f"{'dataset':<18}{'TB':>6}{'loss [M$]':>11} location")
for i in range(N):
j = int(np.argmax(x_bal[i]))
print(f"{datasets[i]:<18}{size_tb[i]:>6.0f}{loss_musd[i]:>11.0f} {locations[j]}")
print()
print("=== Load per location (balanced weights) ===")
for j in range(M):
tb = float((x_bal[:, j] * size_tb).sum())
ex = float((x_bal[:, j] * loss_musd).sum())
print(f"{locations[j]:<18}{tb:>8.0f} TB exposed loss {ex:>6.0f} M$")

# ------------------------------------------------------------
# 7. Visualisation: 2 rows x 3 columns
# ------------------------------------------------------------
fig = plt.figure(figsize=(22, 12))
fig.suptitle("Leak-aware data placement: risk, latency and cost trade-offs",
fontsize=18, y=0.985)

# (1,1) Risk vs cost, coloured by latency
ax1 = fig.add_subplot(2, 3, 1)
order = np.argsort(pareto_F[:, 0])
sc = ax1.scatter(pareto_F[order, 0], pareto_F[order, 2], c=pareto_F[order, 1],
cmap="plasma", s=80, edgecolor="white", linewidth=0.4)
ax1.plot(pareto_F[order, 0], pareto_F[order, 2], color="white", alpha=0.25)
ax1.scatter([F_bal[0]], [F_bal[2]], marker="*", s=380, color="yellow",
edgecolor="black", zorder=5, label="Balanced optimum")
cb = fig.colorbar(sc, ax=ax1)
cb.set_label("Mean latency [ms]")
ax1.set_xlabel("Expected leak loss [k$/yr]")
ax1.set_ylabel("Storage cost [k$/yr]")
ax1.set_title("Pareto-optimal placements")
ax1.legend(loc="upper right")
ax1.grid(alpha=0.2)

# (1,2) 3D objective space
ax2 = fig.add_subplot(2, 3, 2, projection="3d")
ax2.scatter(random_F[:, 0], random_F[:, 1], random_F[:, 2],
color="gray", alpha=0.35, s=8, label="Random feasible")
ax2.scatter(pareto_F[:, 0], pareto_F[:, 1], pareto_F[:, 2],
color="#00e5ff", s=45, label="Pareto-optimal")
ax2.scatter([F_greedy[0]], [F_greedy[1]], [F_greedy[2]],
color="orange", s=120, marker="D", label="Greedy")
ax2.scatter([F_bal[0]], [F_bal[1]], [F_bal[2]],
color="yellow", s=320, marker="*", label="MILP balanced")
ax2.set_xlabel("Risk [k$/yr]")
ax2.set_ylabel("Latency [ms]")
ax2.set_zlabel("Cost [k$/yr]")
ax2.set_title("Objective space")
ax2.view_init(elev=22, azim=-58)
ax2.legend(loc="upper left", fontsize=8)

# (1,3) Assignment heat map
ax3 = fig.add_subplot(2, 3, 3)
ax3.imshow(x_bal, cmap="viridis", aspect="auto", vmin=0, vmax=1)
ax3.set_xticks(range(M))
ax3.set_xticklabels(locations, rotation=25, ha="right")
ax3.set_yticks(range(N))
ax3.set_yticklabels([f"{datasets[i]} ({size_tb[i]:.0f} TB)" for i in range(N)], fontsize=8)
ax3.set_title("Optimal placement matrix (balanced)")
ax3.set_xticks(np.arange(-0.5, M, 1), minor=True)
ax3.set_yticks(np.arange(-0.5, N, 1), minor=True)
ax3.grid(which="minor", color="black", linewidth=1.0)
ax3.tick_params(which="minor", length=0)

# (2,1) Normalised comparison of methods
ax4 = fig.add_subplot(2, 3, 4)
method_names = ["Random\nmean", "Greedy", "MILP\nbalanced", "Risk-min", "Latency-min", "Cost-min"]
method_F = np.array([random_F.mean(axis=0), F_greedy, F_bal,
payoff[0], payoff[1], payoff[2]])
method_N = (method_F - ideal) / ranges
width = 0.26
pos = np.arange(len(method_names))
for k, (lab, col) in enumerate(zip(["Risk", "Latency", "Cost"],
["#ff5252", "#40c4ff", "#b2ff59"])):
ax4.bar(pos + (k - 1) * width, method_N[:, k], width, label=lab, color=col)
ax4.set_xticks(pos)
ax4.set_xticklabels(method_names, fontsize=9)
ax4.set_ylabel("Normalised regret (0 = best, 1 = worst)")
ax4.set_title("Method comparison")
ax4.legend()
ax4.grid(axis="y", alpha=0.2)

# (2,2) 3D surface of optimal scalarised value over the weight simplex
ax5 = fig.add_subplot(2, 3, 5, projection="3d")
surf = ax5.plot_trisurf(sweep_w[:, 0], sweep_w[:, 1], sweep_S, cmap="viridis",
linewidth=0.2, antialiased=True, alpha=0.95)
ax5.set_xlabel("Risk weight")
ax5.set_ylabel("Latency weight")
ax5.set_zlabel("Optimal score")
ax5.set_title("Optimal score over the weight simplex")
ax5.view_init(elev=28, azim=-125)
fig.colorbar(surf, ax=ax5, shrink=0.6, pad=0.1)

# (2,3) Stacked load per location
ax6 = fig.add_subplot(2, 3, 6)
sol_names = ["Risk-min", "Latency-min", "Cost-min", "Balanced"]
sol_x = [single_solutions[0], single_solutions[1], single_solutions[2], x_bal]
loads = np.array([(x * size_tb[:, None]).sum(axis=0) for x in sol_x])
palette = plt.get_cmap("Set2")(np.linspace(0, 1, M))
bottom = np.zeros(len(sol_names))
for j in range(M):
ax6.bar(sol_names, loads[:, j], bottom=bottom, color=palette[j], label=locations[j])
bottom += loads[:, j]
ax6.set_ylabel("Stored volume [TB]")
ax6.set_title("Where the data ends up")
ax6.legend(fontsize=8, loc="upper right")
ax6.grid(axis="y", alpha=0.2)

fig.subplots_adjust(left=0.05, right=0.97, top=0.92, bottom=0.08, wspace=0.28, hspace=0.38)
plt.show()

4. Code Walkthrough

Section 1: problem data. Every array is indexed by dataset ($i$) or location ($j$). The allowed mask encodes data residency: for the four Japan-only datasets, the Singapore and Oregon columns are switched off. The solver receives this mask as upper bounds of zero on the corresponding variables.

Section 2: linear coefficients. Each objective is a matrix with one entry per pair $(i, j)$, so the total value of a placement is simply the sum of the entries selected by $x$. The risk matrix is the outer product of loss and breach probability. The latency matrix is access @ latency_ms.T, which gives for every dataset–location pair the request-weighted latency, divided by total traffic to yield a mean in milliseconds. The cost matrix is the outer product of size and monthly price, multiplied by 12. The three matrices are stacked into one array so that evaluate returns all objectives in a single vectorized expression.

Section 3: exact MILP. milp from SciPy calls the HiGHS solver. Three constraint blocks are built once: one row per dataset forcing exactly one location, one row per location for capacity, and one row per location for the blast-radius cap. Integrality is set on every variable and the bounds restrict them to ${0,1}$, with forbidden pairs fixed at zero. The payoff table optimizes each objective alone, which yields the ideal point (diagonal) and a nadir estimate (column maxima). The ranges vector turns the three incompatible units (k$/yr, ms, k$/yr) into dimensionless quantities.

Section 4: weight sweep. A grid with step $0.1$ over the simplex gives 66 weight vectors. Each one produces a normalized cost matrix norm_coef(w) and one MILP solve. Duplicate placements are merged, and a dominance filter removes any weakly dominated points, leaving the Pareto-optimal set. The optimal scalarized value for every weight is stored for the 3D surface plot.

Section 5: baselines. The balanced optimum uses equal weights. The greedy heuristic processes datasets from highest potential loss to lowest and assigns each to the cheapest feasible location under the balanced scalarization. The random baseline draws 3000 feasible placements by rejection sampling, which also gives the grey point cloud in the 3D plot.

Section 6: console report. The report prints the payoff table, the method comparison, the final placement, and the load per location.

Section 7: figure. All six panels share one figure with two rows and three columns:

  1. Risk–cost projection of the Pareto set, colored by mean latency.
  2. 3D objective space with the random cloud, Pareto points, greedy solution, and MILP optimum.
  3. Heat map of the optimal placement matrix.
  4. Normalized regret of each method on each objective.
  5. 3D surface of the optimal scalarized value over the weight simplex.
  6. Stacked storage volume per location for four representative solutions.

5. Console Output

=== Problem size ===
datasets: 12, locations: 5, binary variables: 60
feasible random placements sampled: 3000 (trials: 6322)

=== Payoff table (rows: optimised objective) ===
optimised for     risk [k$/yr]  latency [ms]  cost [k$/yr]
risk                    2382.0         50.73         151.3
latency                 3514.0         45.93         124.2
cost                    6875.0         81.81          83.9

=== Weighted-sum sweep: 66 MILPs in 0.61 s, 40 Pareto-optimal placements ===

=== Method comparison (balanced weights 1/3, 1/3, 1/3) ===
method                      risk   latency      cost     score
Random (mean)             4459.1     61.43     119.9    0.4762
Random (best of all)      3435.0     49.28     101.2    0.1949
Greedy heuristic          3434.0     46.58     101.9    0.1732
MILP optimum              3434.0     46.58     101.9    0.1732

=== Optimal placement (balanced weights) ===
dataset               TB  loss [M$]  location
Customer PII           8         50  On-prem Tokyo
Payment records       12         80  On-prem Tokyo
Employee HR            3         30  On-prem Tokyo
Source code            2         40  On-prem Osaka
Product catalog        5          2  Cloud Tokyo
Web analytics         40          5  Cloud Tokyo
Access logs           60          8  Cloud Tokyo
ML training set       80         20  Cloud Oregon
Backups              100         60  Cloud Singapore
Marketing assets      20          1  Cloud Tokyo
Sensor telemetry      50          3  Cloud Singapore
Partner contracts      1         25  On-prem Osaka

=== Load per location (balanced weights) ===
On-prem Tokyo           23 TB   exposed loss    160 M$
On-prem Osaka            3 TB   exposed loss     65 M$
Cloud Tokyo            125 TB   exposed loss     16 M$
Cloud Singapore        150 TB   exposed loss     63 M$
Cloud Oregon            80 TB   exposed loss     20 M$

6. Result Figure

7. Interpreting the Results

Pareto front (top left). The curve is a classic knee-shaped trade-off. Moving left lowers expected leak loss, but only by moving sensitive and large datasets into the expensive on-premises sites, so storage cost climbs. Moving right saves money by pushing data toward the cheap but riskier cloud regions. The color shows that latency does not move monotonically with either objective, because the best latency depends on which datasets sit near which users rather than on the total amount of data stored near anyone.

Objective space (top middle). The grey cloud shows what random feasible placements look like in the three-dimensional objective space. The Pareto-optimal points form a thin lower-left boundary of that cloud, which is exactly where a rational operator wants to be. The yellow star marks the balanced optimum, a compromise that is not extreme on any axis.

Placement matrix (top right). The structure of the balanced solution follows the economics. The highest-value, residency-bound datasets (customer PII, payment records, HR) go to the on-premises sites with the lowest breach probability. Large, low-sensitivity, high-traffic data such as product catalogs, analytics, and logs goes to Cloud Tokyo, which is close to the main users and cheap. The cheapest regions absorb the bulk data whose leak would hurt little, such as the ML training set, backups, and sensor telemetry. Backups are valuable but are accessed rarely, so latency barely matters for them and the blast-radius cap and cost decide their location.

Method comparison (bottom left). A random feasible placement is far from the ideal on all three axes. The greedy heuristic and the MILP optimum are both close to the ideal on latency and sit at moderate regret for risk and cost. On this small instance the greedy rule happens to reach the same placement as the exact solver, but it carries no optimality guarantee, and only the MILP can certify that no better balanced placement exists. The extreme solutions show the price of single-minded optimization: minimizing risk alone pushes cost to its worst value, and minimizing cost alone pushes risk and latency to their worst values.

Weight surface (bottom middle). The surface shows the best achievable normalized score for every weighting of the three objectives. It is concave because it is the pointwise minimum of linear functions of the weights, one for each feasible placement. The valleys at the corners correspond to the single-objective optima, where the score reaches zero. The ridge in the interior shows where no placement is simultaneously good on all objectives, which is the region where the choice of weights matters most.

Storage volume (bottom right). The stacked bars make the architectural consequence visible. The risk-minimizing placement fills both on-premises sites. The cost-minimizing placement puts nearly everything into the cheapest cloud region. The balanced placement spreads data across all locations, using on-premises capacity mainly for sensitive data and cloud capacity for the bulk of the volume.

8. Conclusion

Leak-aware placement is a small assignment problem with a large practical payoff. Writing breach probability as a coefficient of the objective, adding a blast-radius cap, and encoding residency as variable bounds turns a vague security discussion into a mixed-integer program that an off-the-shelf solver handles in moments. The Pareto sweep then gives decision makers a menu of efficient options rather than a single answer, so the final weights can reflect the organization’s actual appetite for risk, latency, and cost.

Optimizing the Privacy Budget ε in Differential Privacy

Getting the Most Utility Out of Every Bit of Privacy

Differential privacy (DP) gives a mathematically provable guarantee: whether or not any single individual is in a dataset, what an observer sees barely changes. The cost of that guarantee is noise, and the amount of noise is set by the privacy budget $\varepsilon$. A smaller $\varepsilon$ gives stronger privacy and noisier answers.

In practice an analyst rarely asks just one question. A data release usually holds a batch of statistics, and they all draw on one shared, limited budget. That raises the question this post answers:

How should we spend a privacy budget $\varepsilon$ — or how small can we make it — while keeping the released statistics as useful as possible?

We’ll set up a realistic example, derive the optimal answer in closed form, check it numerically, confirm it with Monte Carlo simulation, and visualize the whole privacy–utility trade-off, including in 3D.


The Problem Setting

A hospital holds records for $n = 5000$ patients and wants to publish five aggregate statistics:

# Query L1 sensitivity $\Delta_i$ Importance $\alpha_i$
1 Number of diabetic patients $1$ $1.0$
2 Number of rare-disease patients $1$ $2.0$
3 Sum of ages (clipped to $[0,100]$) $100$ $1.0$
4 Sum of incomes (clipped to $[0, 200{,}000]$) $200{,}000$ $1.5$
5 Sum of hospital visits (clipped to $[0,20]$) $20$ $0.5$

The rare-disease count is small (about 1% of patients), so the same noise hurts it much more in relative terms. The analyst also cares about it most.

The Laplace Mechanism

Each query $f_i$ is answered with the Laplace mechanism:

$$
\tilde{f}i(D) = f_i(D) + \mathrm{Lap}!\left(\frac{\Delta_i}{\varepsilon_i}\right),
\qquad
\Delta_i = \max
{D \sim D’} \lvert f_i(D) - f_i(D’) \rvert .
$$

Under sequential composition, releasing all five answers is $\varepsilon_{\text{total}}$-DP with

$$
\varepsilon_{\text{total}} = \sum_{i=1}^{K} \varepsilon_i .
$$

Measuring Utility

The noise variance of the Laplace mechanism is $\mathrm{Var}[\mathrm{Lap}(b)] = 2b^2$. To compare statistics with very different scales (a count of 58 against an income total of 240 million), we use the importance-weighted relative mean squared error:

$$
\mathrm{wMSE}(\boldsymbol{\varepsilon})
= \sum_{i=1}^{K} \alpha_i,\mathbb{E}!\left[\left(\frac{\tilde f_i - f_i}{f_i}\right)^{2}\right]
= \sum_{i=1}^{K} \frac{2\alpha_i \Delta_i^2}{f_i^2},\frac{1}{\varepsilon_i^2}
= \sum_{i=1}^{K} \frac{a_i}{\varepsilon_i^2},
\qquad a_i = \frac{2\alpha_i\Delta_i^2}{f_i^2}.
$$

Three Ways to Pose the Optimization

(P1) Primal — maximize utility for a fixed budget

$$
\min_{\boldsymbol{\varepsilon} > 0} \ \sum_{i=1}^{K} \frac{a_i}{\varepsilon_i^2}
\quad \text{s.t.} \quad \sum_{i=1}^{K} \varepsilon_i = E .
$$

(P2) Dual — minimize the budget for a utility target

$$
\min_{\boldsymbol{\varepsilon} > 0} \ \sum_{i=1}^{K} \varepsilon_i
\quad \text{s.t.} \quad \sum_{i=1}^{K} \frac{a_i}{\varepsilon_i^2} \le U .
$$

(P3) Penalized — trade privacy and utility with a price $\lambda$

$$
\min_{E > 0} \ J(E) = \mathrm{wMSE}^*(E) + \lambda E .
$$

Closed-Form Solution

For (P1), the Lagrangian $\mathcal{L} = \sum_i a_i\varepsilon_i^{-2} + \mu\left(\sum_i \varepsilon_i - E\right)$ gives

$$
\frac{\partial \mathcal{L}}{\partial \varepsilon_i} = -\frac{2a_i}{\varepsilon_i^3} + \mu = 0
;\Longrightarrow;
\varepsilon_i \propto a_i^{1/3}.
$$

Normalizing to the budget:

The objective is strictly convex on the positive orthant, so this stationary point is the unique global optimum. Splitting the budget evenly, $\varepsilon_i = E/K$, gives

$$
\mathrm{wMSE}^{\text{unif}}(E) = \frac{K^2 \sum_j a_j}{E^2}.
$$

Solving (P2) by inverting the same relation gives

$$
E_{\min}^{*} = \sqrt{\frac{S^3}{U}},
\qquad
E_{\min}^{\text{unif}} = K\sqrt{\frac{\sum_j a_j}{U}},
$$

so the relative budget saving $1 - \dfrac{S^{3/2}}{K\sqrt{\sum_j a_j}}$ does not depend on the target $U$.

For (P3), setting $J’(E) = -2S^3/E^3 + \lambda = 0$ gives

$$
E^{*}(\lambda) = \left(\frac{2S^3}{\lambda}\right)^{1/3}.
$$

We’ll also use a tail-probability version of utility. Since $P(\lvert \mathrm{Lap}(b)\rvert > t) = e^{-t/b}$, requiring each query to be within a relative tolerance $\tau$ with probability at least $1-\beta$ gives

$$
P!\left(\lvert \tilde f_i - f_i \rvert > \tau f_i\right) \le \beta
;\Longleftrightarrow;
\varepsilon_i \ge \frac{\Delta_i \ln(1/\beta)}{\tau f_i}.
$$


Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import time
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # noqa: F401
from scipy.optimize import minimize

rng = np.random.default_rng(42)

# ------------------------------------------------------------
# 1. Synthetic patient database
# ------------------------------------------------------------
n = 5000
age = np.clip(rng.normal(48, 18, n), 0, 100)
income = np.clip(rng.lognormal(10.6, 0.6, n), 0, 200_000)
visits = np.clip(rng.poisson(3.0, n), 0, 20)
diabetic = rng.random(n) < (0.05 + 0.15 * (age > 60))
rare = rng.random(n) < 0.012

names = ["Diabetic count", "Rare-disease count", "Sum of age",
"Sum of income", "Sum of visits"]
true_vals = np.array([diabetic.sum(), rare.sum(), age.sum(),
income.sum(), visits.sum()], dtype=float)
sens = np.array([1.0, 1.0, 100.0, 200_000.0, 20.0]) # L1 sensitivity (add/remove)
importance = np.array([1.0, 2.0, 1.0, 1.5, 0.5]) # analyst priorities
w = importance / true_vals**2 # weighted relative MSE
a = 2.0 * w * sens**2 # cost coefficients
K = len(names)

# ------------------------------------------------------------
# 2. Closed-form optimal allocation
# ------------------------------------------------------------
S = np.sum(a ** (1 / 3))

def optimal_alloc(E):
return E * a ** (1 / 3) / S

def uniform_alloc(E):
return np.full(K, E / K)

def wmse(eps):
return np.sum(a / eps**2, axis=-1)

def wmse_opt(E):
return S**3 / np.asarray(E, dtype=float)**2

def wmse_unif(E):
return K**2 * a.sum() / np.asarray(E, dtype=float)**2

# ------------------------------------------------------------
# 3. Numerical cross-check with SLSQP (on the simplex of shares)
# ------------------------------------------------------------
def slsqp_alloc(E):
obj = lambda x: np.sum(a / x**2) / S**3
jac = lambda x: -2.0 * a / x**3 / S**3
cons = {"type": "eq", "fun": lambda x: np.sum(x) - 1.0,
"jac": lambda x: np.ones(K)}
res = minimize(obj, np.full(K, 1.0 / K), jac=jac, method="SLSQP",
bounds=[(1e-6, 1.0)] * K, constraints=[cons],
options={"ftol": 1e-14, "maxiter": 500})
return E * res.x

E0 = 1.0
eps_opt = optimal_alloc(E0)
eps_uni = uniform_alloc(E0)
t0 = time.perf_counter()
eps_slsqp = slsqp_alloc(E0)
t_slsqp = time.perf_counter() - t0
t0 = time.perf_counter()
for _ in range(1000):
optimal_alloc(E0)
t_closed = (time.perf_counter() - t0) / 1000

print("=" * 72)
print(f"Total privacy budget epsilon = {E0}")
print("=" * 72)
print(f"{'Query':<20}{'True value':>14}{'Delta':>10}{'eps_unif':>10}{'eps_opt':>10}{'eps_SLSQP':>11}")
for i in range(K):
print(f"{names[i]:<20}{true_vals[i]:>14.1f}{sens[i]:>10.0f}"
f"{eps_uni[i]:>10.4f}{eps_opt[i]:>10.4f}{eps_slsqp[i]:>11.4f}")
print("-" * 72)
print(f"Weighted MSE (uniform) : {wmse(eps_uni):.6e}")
print(f"Weighted MSE (optimal) : {wmse(eps_opt):.6e}")
print(f"Weighted MSE (SLSQP) : {wmse(eps_slsqp):.6e}")
print(f"Error reduction : {100 * (1 - wmse(eps_opt) / wmse(eps_uni)):.2f} %")
print(f"Max |closed - SLSQP| : {np.max(np.abs(eps_opt - eps_slsqp)):.2e}")
print(f"Time closed form : {t_closed * 1e6:.2f} us")
print(f"Time SLSQP : {t_slsqp * 1e3:.2f} ms")

# ------------------------------------------------------------
# 4. Vectorized Monte Carlo verification
# ------------------------------------------------------------
T = 20000
t0 = time.perf_counter()
noise_u = rng.laplace(0.0, sens / eps_uni, size=(T, K))
noise_o = rng.laplace(0.0, sens / eps_opt, size=(T, K))
rel_u = np.abs(noise_u) / true_vals
rel_o = np.abs(noise_o) / true_vals
mc_u = np.mean(np.sum(importance * (noise_u / true_vals) ** 2, axis=1))
mc_o = np.mean(np.sum(importance * (noise_o / true_vals) ** 2, axis=1))
t_mc = time.perf_counter() - t0
print("=" * 72)
print(f"Monte Carlo ({T} releases, {t_mc * 1e3:.1f} ms)")
print(f"Empirical weighted MSE (uniform) : {mc_u:.6e}")
print(f"Empirical weighted MSE (optimal) : {mc_o:.6e}")
print(f"{'Query':<20}{'median rel.err unif':>22}{'median rel.err opt':>22}")
for i in range(K):
print(f"{names[i]:<20}{np.median(rel_u[:, i]) * 100:>21.3f}%{np.median(rel_o[:, i]) * 100:>21.3f}%")

# ------------------------------------------------------------
# 5. Dual problem: minimum epsilon for a utility target
# ------------------------------------------------------------
targets = np.linspace(0.01, 0.20, 100) # average relative RMSE target
U = importance.sum() * targets**2
E_min_opt = np.sqrt(S**3 / U)
E_min_uni = K * np.sqrt(a.sum() / U)

print("=" * 72)
print("Dual problem: minimum total epsilon to reach a weighted-RMSE target")
for r in [0.02, 0.05, 0.10]:
Ur = importance.sum() * r**2
eo, eu = np.sqrt(S**3 / Ur), K * np.sqrt(a.sum() / Ur)
print(f"target {r * 100:4.1f}% : eps_opt = {eo:7.4f} eps_unif = {eu:7.4f}"
f" saving = {100 * (1 - eo / eu):5.2f} %")

beta, tol = 0.05, 0.05
eps_tail = sens * np.log(1 / beta) / (tol * true_vals)
print("-" * 72)
print(f"Per-query guarantee P(|error| > {tol * 100:.0f}% of truth) <= {beta}")
for i in range(K):
print(f"{names[i]:<20} eps_i >= {eps_tail[i]:.5f}")
print(f"Minimum total epsilon: {eps_tail.sum():.5f}")

# ------------------------------------------------------------
# 6. Penalized formulation: min wMSE(E) + lambda * E
# ------------------------------------------------------------
lams = np.logspace(-6, -1, 80)
E_star = (2 * S**3 / lams) ** (1 / 3)
print("=" * 72)
for lam in [1e-5, 1e-4, 1e-3, 1e-2]:
print(f"lambda = {lam:.0e} -> optimal total epsilon E* = {(2 * S**3 / lam) ** (1 / 3):.4f}")
print("=" * 72)

# ------------------------------------------------------------
# 7. Visualization (2 x 3)
# ------------------------------------------------------------
fig = plt.figure(figsize=(21, 12))

# (1) Allocation bars
ax1 = fig.add_subplot(2, 3, 1)
x = np.arange(K)
ax1.bar(x - 0.27, eps_uni, 0.27, label="Uniform", color="#9aa5b1")
ax1.bar(x, eps_opt, 0.27, label="Optimal (closed form)", color="#2b6cb0")
ax1.bar(x + 0.27, eps_slsqp, 0.27, label="SLSQP", color="#ed8936")
ax1.set_xticks(x)
ax1.set_xticklabels(names, rotation=25, ha="right")
ax1.set_ylabel(r"$\varepsilon_i$")
ax1.set_title(r"Budget allocation at $\varepsilon_{total}=1$")
ax1.legend()
ax1.grid(axis="y", alpha=0.3)

# (2) Privacy-utility frontier
ax2 = fig.add_subplot(2, 3, 2)
Es = np.logspace(-1.5, 1, 120)
ax2.loglog(Es, wmse_unif(Es), "--", color="#9aa5b1", lw=2, label="Uniform")
ax2.loglog(Es, wmse_opt(Es), color="#2b6cb0", lw=2, label="Optimal")
Ech = np.logspace(-1.5, 1, 8)
ax2.loglog(Ech, [wmse(slsqp_alloc(e)) for e in Ech], "o", color="#ed8936", label="SLSQP check")
ax2.set_xlabel(r"Total budget $\varepsilon_{total}$")
ax2.set_ylabel("Weighted relative MSE")
ax2.set_title("Privacy-utility frontier")
ax2.legend()
ax2.grid(True, which="both", alpha=0.3)

# (3) 3D surface of wMSE over shares of two queries
ax3 = fig.add_subplot(2, 3, 3, projection="3d")
i1, i2 = 1, 3
rest = [j for j in range(K) if j not in (i1, i2)]
S_rest = np.sum(a[rest] ** (1 / 3))
g = np.linspace(0.02, 0.9, 90)
X, Y = np.meshgrid(g, g)
Rm = 1.0 - X - Y
valid = Rm > 0.02
Z = np.full_like(X, np.nan)
Z[valid] = (a[i1] / (E0 * X[valid])**2 + a[i2] / (E0 * Y[valid])**2
+ S_rest**3 / (E0 * Rm[valid])**2)
Zl = np.log10(Z)
ax3.plot_surface(X, Y, Zl, cmap="viridis", alpha=0.85, edgecolor="none")
xo, yo = eps_opt[i1] / E0, eps_opt[i2] / E0
ax3.scatter([xo], [yo], [np.log10(wmse(eps_opt))], color="red", s=80, depthshade=False)
ax3.set_xlabel(f"Share: {names[i1]}")
ax3.set_ylabel(f"Share: {names[i2]}")
ax3.set_zlabel(r"$\log_{10}$ wMSE")
ax3.set_title("Objective landscape (red = optimum)")
ax3.view_init(elev=28, azim=-130)

# (4) Monte Carlo relative errors
ax4 = fig.add_subplot(2, 3, 4)
pos = np.arange(K)
bu = ax4.boxplot([rel_u[:, i] * 100 for i in range(K)], positions=pos - 0.18,
widths=0.3, patch_artist=True, showfliers=False)
bo = ax4.boxplot([rel_o[:, i] * 100 for i in range(K)], positions=pos + 0.18,
widths=0.3, patch_artist=True, showfliers=False)
for b in bu["boxes"]:
b.set_facecolor("#cbd2d9")
for b in bo["boxes"]:
b.set_facecolor("#90cdf4")
ax4.set_yscale("log")
ax4.set_xticks(pos)
ax4.set_xticklabels(names, rotation=25, ha="right")
ax4.set_ylabel("Absolute relative error [%]")
ax4.set_title("Monte Carlo errors (grey: uniform, blue: optimal)")
ax4.grid(axis="y", which="both", alpha=0.3)

# (5) Dual problem
ax5 = fig.add_subplot(2, 3, 5)
ax5.plot(targets * 100, E_min_uni, "--", color="#9aa5b1", lw=2, label="Uniform")
ax5.plot(targets * 100, E_min_opt, color="#2b6cb0", lw=2, label="Optimal")
ax5.fill_between(targets * 100, E_min_opt, E_min_uni, color="#90cdf4", alpha=0.4,
label="Budget saved")
ax5.set_yscale("log")
ax5.set_xlabel("Target average relative RMSE [%]")
ax5.set_ylabel(r"Minimum $\varepsilon_{total}$")
ax5.set_title("Minimum privacy cost for a utility target")
ax5.legend()
ax5.grid(True, which="both", alpha=0.3)

# (6) 3D penalized objective
ax6 = fig.add_subplot(2, 3, 6, projection="3d")
le = np.linspace(-1.5, 1.5, 70)
ll = np.linspace(-6, -1, 70)
LE, LL = np.meshgrid(le, ll)
J = S**3 / (10**LE)**2 + (10**LL) * (10**LE)
ax6.plot_surface(LE, LL, np.log10(J), cmap="plasma", alpha=0.8, edgecolor="none")
mask = (np.log10(E_star) >= -1.5) & (np.log10(E_star) <= 1.5)
Jstar = S**3 / E_star**2 + lams * E_star
ax6.plot(np.log10(E_star[mask]), np.log10(lams[mask]), np.log10(Jstar[mask]),
color="cyan", lw=3, label=r"$\varepsilon^*(\lambda)$")
ax6.set_xlabel(r"$\log_{10}\varepsilon_{total}$")
ax6.set_ylabel(r"$\log_{10}\lambda$")
ax6.set_zlabel(r"$\log_{10} J$")
ax6.set_title(r"Penalized objective $J=\mathrm{wMSE}+\lambda\varepsilon$")
ax6.legend()
ax6.view_init(elev=25, azim=-60)

plt.tight_layout()
plt.show()

Code Walkthrough

1. Synthetic patient database

We draw 5,000 synthetic patients from a seeded generator (default_rng(42)), so every run gives the same results. Each attribute is clipped to a fixed range. Clipping is what makes the sensitivities finite and known: adding or removing one patient can change the age sum by at most 100, the income sum by at most 200,000, and the visit sum by at most 20. A count changes by at most 1.

Diabetes is more likely above age 60. The rare disease affects about 1.2% of patients, so its count is only 58. That count is the hard case of the problem.

The vector a holds the coefficients $a_i = 2\alpha_i\Delta_i^2/f_i^2$ from the derivation, so the whole problem reduces to $\sum_i a_i/\varepsilon_i^2$.

2. Closed-form optimal allocation

optimal_alloc(E) implements $\varepsilon_i^* = E,a_i^{1/3}/S$ directly. It’s a single vectorized NumPy expression that takes about 2 microseconds. wmse_opt and wmse_unif are the analytic error formulas $S^3/E^2$ and $K^2\sum a_j/E^2$. With them we can draw whole frontier curves without running any optimizer.

3. Numerical cross-check with SLSQP

To confirm the derivation, we solve the same problem with SciPy’s SLSQP. Two choices keep the solver fast and stable:

  • Optimizing over budget shares $x_i = \varepsilon_i/E$ on the simplex $\sum_i x_i = 1$. This makes the problem independent of scale.
  • Supplying the analytic gradient $-2a_i/x_i^3$ and dividing the objective by $S^3$, so its value is of order 1 at the optimum.

The solver agrees with the closed form to about $10^{-9}$. It takes milliseconds, against microseconds for the formula. This is where the closed form pays off: if you need allocations for thousands of budgets, as in a frontier plot or a dashboard, the formula is effectively free.

4. Vectorized Monte Carlo verification

Theory says the optimal allocation should give a smaller expected error. To check, we simulate 20,000 independent releases under each allocation. All the Laplace noise is drawn in one rng.laplace(..., size=(T, K)) call. NumPy broadcasts the per-query scale $\Delta_i/\varepsilon_i$ across the columns, so there is no Python loop, and 40,000 five-query releases take a few milliseconds. The empirical weighted MSE should match $S^3/E^2$ and $K^2\sum a_j/E^2$.

5. Dual problem: minimum ε for a utility target

Here we flip the question. We set a target average relative RMSE $r$, so $U = \left(\sum_i \alpha_i\right) r^2$, and compute the smallest budget that reaches it: $E^*_{\min} = \sqrt{S^3/U}$. We compare this with the budget an even split would need.

The second block applies the stricter tail-probability guarantee. Each query must be within 5% of its true value with 95% probability. This sets a per-query floor $\varepsilon_i \ge \Delta_i\ln(1/\beta)/(\tau f_i)$, and the floors add up to the minimum total budget.

6. Penalized formulation

If an organization can put a “price” $\lambda$ on each unit of privacy loss, the best total budget is $E^*(\lambda) = (2S^3/\lambda)^{1/3}$. The code prints this for several values of $\lambda$ and also sweeps $\lambda$ for the 3D plot.

7. Visualization

All six panels share one 2 × 3 figure. Two of them are 3D surfaces: the objective landscape over the budget simplex, and the penalized objective over $(\varepsilon, \lambda)$.


Execution Results

========================================================================
Total privacy budget epsilon = 1.0
========================================================================
Query                   True value     Delta  eps_unif   eps_opt  eps_SLSQP
Diabetic count               436.0         1    0.2000    0.1372     0.1372
Rare-disease count            58.0         1    0.2000    0.6633     0.6633
Sum of age                238273.1       100    0.2000    0.0442     0.0442
Sum of income          240183538.8    200000    0.2000    0.0799     0.0799
Sum of visits              15164.0        20    0.2000    0.0753     0.0753
------------------------------------------------------------------------
Weighted MSE (uniform) : 3.009384e-02
Weighted MSE (optimal) : 4.073663e-03
Weighted MSE (SLSQP)   : 4.073663e-03
Error reduction        : 86.46 %
Max |closed - SLSQP|   : 5.71e-09
Time closed form       : 6.42 us
Time SLSQP             : 11.07 ms
========================================================================
Monte Carlo (20000 releases, 20.6 ms)
Empirical weighted MSE (uniform) : 2.986664e-02
Empirical weighted MSE (optimal) : 4.085240e-03
Query                  median rel.err unif    median rel.err opt
Diabetic count                      0.789%                1.185%
Rare-disease count                  6.005%                1.811%
Sum of age                          0.143%                0.671%
Sum of income                       0.289%                0.716%
Sum of visits                       0.457%                1.210%
========================================================================
Dual problem: minimum total epsilon to reach a weighted-RMSE target
target  2.0% : eps_opt =  1.3028   eps_unif =  3.5411   saving = 63.21 %
target  5.0% : eps_opt =  0.5211   eps_unif =  1.4164   saving = 63.21 %
target 10.0% : eps_opt =  0.2606   eps_unif =  0.7082   saving = 63.21 %
------------------------------------------------------------------------
Per-query guarantee P(|error| > 5% of truth) <= 0.05
Diabetic count       eps_i >= 0.13742
Rare-disease count   eps_i >= 1.03301
Sum of age           eps_i >= 0.02515
Sum of income        eps_i >= 0.04989
Sum of visits        eps_i >= 0.07902
Minimum total epsilon: 1.32449
========================================================================
lambda = 1e-05 -> optimal total epsilon E* = 9.3398
lambda = 1e-04 -> optimal total epsilon E* = 4.3352
lambda = 1e-03 -> optimal total epsilon E* = 2.0122
lambda = 1e-02 -> optimal total epsilon E* = 0.9340
========================================================================

Reading the Results

Top-left: Budget allocation at $\varepsilon_{\text{total}} = 1$

The even split gives every query $0.2$. The optimal split is very uneven:

  • The rare-disease count gets about $0.66$, two-thirds of the whole budget. Its true value is tiny (58), so Laplace noise of scale $1/\varepsilon$ is large relative to it, and the analyst gave it twice the importance.
  • The age sum gets only about $0.044$. Its sensitivity of 100 sounds large, but next to a total of about 238,000 it is negligible, so it needs very little budget.
  • The closed-form bars (blue) and the SLSQP bars (orange) match exactly, which confirms the $a_i^{1/3}$ rule.

The rule $\varepsilon_i \propto \left(\alpha_i \Delta_i^2 / f_i^2\right)^{1/3}$ amounts to this: give budget to queries whose relative sensitivity $\Delta_i/f_i$ is large, and temper it with the cube root, so no single query takes everything.

Top-center: Privacy–utility frontier

Both curves are straight lines with slope $-2$ on log–log axes, since error scales as $1/\varepsilon^2$. The optimal line sits a constant factor below the even split at every budget. Here the weighted MSE drops from about $3.0\times10^{-2}$ to $4.1\times10^{-3}$, an 86% reduction, at no extra privacy cost. The orange SLSQP points land on the analytic curve at all eight budgets checked.

Top-right (3D): Objective landscape

We fix the total budget and vary the shares going to the rare-disease count and to the income sum. The other three queries share what’s left, split optimally among themselves. The surface is a convex bowl. It shoots up toward the edges, where some query’s budget goes to zero and its error blows up. The red dot at the bottom of the bowl is the closed-form optimum. Convexity is why the Lagrangian solution is global and why any gradient-based solver converges to it.

Bottom-left: Monte Carlo relative errors

This panel shows how the gains are distributed across queries. With an even split, the rare-disease count has a median relative error of about 6% and a long upper tail. The optimal allocation cuts that to about 1.8%. The other queries get slightly worse, from fractions of a percent to roughly 1%. That is the intended trade: budget moves from queries that were over-served to the one that was failing. The empirical weighted MSE from the simulation matches the theoretical values closely.

Bottom-center: Minimum privacy cost for a utility target

This panel answers the dual question. For any accuracy target, the optimal allocation reaches it with a much smaller $\varepsilon$. The shaded band is the budget saved. As the closed-form analysis predicts, the saving is a constant 63.2% regardless of the target. For example, a 5% average relative RMSE needs $\varepsilon \approx 0.52$ with optimal allocation, against $\approx 1.42$ with an even split. In DP terms, that is a much stronger privacy guarantee for exactly the same accuracy.

The console also reports the stricter per-query tail guarantee: each answer within 5% of the truth with 95% probability. That needs $\varepsilon_{\text{total}} \approx 1.32$, and over 1.03 of it goes to the rare-disease count alone. Small counts are the bottleneck of almost every DP release, and this per-query floor quantifies that exactly.

Bottom-right (3D): Penalized objective

The surface shows $J = \mathrm{wMSE}^*(\varepsilon) + \lambda\varepsilon$ over $\log\varepsilon$ and $\log\lambda$. For each $\lambda$, the cross-section is a valley: too little budget and the error term dominates, too much and the privacy penalty dominates. The cyan curve runs along the valley floor, following $\varepsilon^*(\lambda) = (2S^3/\lambda)^{1/3}$. As privacy gets ten times more expensive, the best budget shrinks by a factor of $10^{1/3} \approx 2.15$ (from 9.34 to 4.34 to 2.01 to 0.93 in the console output). This gives a principled way to choose $\varepsilon$ itself, not just how to split it.


Takeaways

  • With Laplace noise and a squared-error utility, the best way to split a fixed budget is $\varepsilon_i^* \propto \left(\alpha_i\Delta_i^2/f_i^2\right)^{1/3}$, and it comes in closed form.
  • Splitting the budget evenly can be very wasteful. In this example the optimal split cut the error by 86% at the same $\varepsilon$, or reached the same accuracy with 63% less privacy budget.
  • The same machinery answers three practical questions: how to split a fixed budget (primal), how small the budget can be for a required accuracy (dual), and what total budget to choose given a price on privacy (penalized).
  • Small counts dominate the privacy cost. Optimization automatically shifts budget toward them, and the per-query tail bound shows exactly how much they need.
  • One caution: we plugged the true values $f_i$ into the weights. In a real deployment those weights should come from public information, prior estimates, or a small, separately accounted slice of the budget, so the allocation itself leaks nothing.

Finding the Best Generalization Under a Re-identification Risk Budget

Privacy vs. Utility in Data Anonymization:

Anyone who releases microdata (patient records, customer logs, survey responses) runs into the same tension. The more you mask, the safer the data gets, and the less useful it becomes. Coarsen ages into decades and truncate ZIP codes to one digit, and nobody can single out an individual, but your regression model loses most of what it could explain. Leave everything raw and the model performs well, but almost every record becomes uniquely identifiable.

In this article we turn that tension into an explicit constrained optimization problem. Our goal is to keep the re-identification risk below a fixed threshold while making the anonymized data as useful as possible for analysis. We then solve it in Python.


The Problem Setting

A health insurer wants to share 30,000 member records with an external analytics team. The team will build a model that predicts annual medical cost. Each record contains:

Attribute Role
Age (18–89) Quasi-identifier
Gender Quasi-identifier
5-digit ZIP code Quasi-identifier
Annual income Quasi-identifier
Annual medical cost Sensitive / target variable

None of these attributes names a person directly. Combined, though, they act as a fingerprint. “A 47-year-old woman in ZIP 31402 earning $62,300” is almost certainly one specific person.

The insurer can apply generalization to each quasi-identifier:

  • Age: bin width $w_a \in {1, 2, 5, 10, 20, 40}$ years
  • ZIP code: keep the first $d_z \in {5, 4, 3, 2, 1, 0}$ digits
  • Income: bin width $w_i \in {1\text{k}, 5\text{k}, 10\text{k}, 25\text{k}, 50\text{k}, 100\text{k}}$

That gives $6 \times 6 \times 6 = 216$ candidate anonymization schemes, which together form a generalization lattice.


Formalizing the Trade-off

Equivalence classes and k-anonymity

After generalization, records that share the same quasi-identifier values form an equivalence class. Let $|E(r)|$ be the size of the class that contains record $r$. A dataset is $k$-anonymous when

$$
\min_{r} |E(r)| \ge k .
$$

Strict $k$-anonymity is often too harsh, because a single outlier can force the whole dataset into very coarse bins. A common relaxation is to cap the share of records at risk:

$$
R_{\text{at-risk}}(\theta) = \frac{1}{N}\sum_{r=1}^{N} \mathbf{1}\bigl[,|E_\theta(r)| < k,\bigr],
$$

where $\theta = (w_a, d_z, w_i)$ is the generalization scheme. The few records still at risk can be suppressed or handled individually.

We also report the average prosecutor risk. This is the expected probability that an attacker who knows a target’s quasi-identifiers picks the right record:

$$
R_{\text{avg}}(\theta) = \frac{1}{N}\sum_{r=1}^{N} \frac{1}{|E_\theta(r)|}.
$$

Utility

Utility is measured by what the analysts actually care about: the out-of-sample $R^2$ of a cost-prediction model trained on the generalized data.

$$
U(\theta) = R^2_{\text{test}}(\theta) = 1 - \frac{\sum_{j \in \text{test}} (y_j - \hat y_j)^2}{\sum_{j \in \text{test}} (y_j - \bar y)^2}.
$$

The optimization problem

$$
\theta^* = \arg\max_{\theta \in \Theta} ; U(\theta)
\quad \text{s.t.} \quad R_{\text{at-risk}}(\theta) \le \varepsilon,
$$

with $k = 5$ and $\varepsilon = 0.05$. In words: at most 5% of the records may sit in an equivalence class smaller than 5.


The Data-Generating Process

We generate synthetic data whose true cost structure is known, so the effect of each generalization can be interpreted directly:

$$
y = 1500 + 4,(a-18)^{1.6} + 350,g + \alpha_{d_1} + \beta_{d_1 d_2} + \gamma_{d_1 d_2 d_3} - 0.012,x + \epsilon ,
$$

where $a$ is age, $g$ is gender, $x$ is income, $\epsilon \sim \mathcal{N}(0, 700^2)$, and the regional effects form a hierarchy:

$$
\alpha_{d_1} \sim \mathcal{N}(0, 900^2), \quad
\beta_{d_1 d_2} \sim \mathcal{N}(0, 600^2), \quad
\gamma_{d_1 d_2 d_3} \sim \mathcal{N}(0, 400^2).
$$

So the first three ZIP digits carry real signal, and digits 4–5 are pure noise from the model’s point of view but highly identifying. This mirrors reality, where coarse geography explains a lot and fine geography mostly fingerprints people.


Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D # noqa: F401
import time

rng = np.random.default_rng(42)

# ------------------------------------------------------------
# 1. Synthetic microdata
# ------------------------------------------------------------
N = 30000
age = rng.integers(18, 90, N)
gender = rng.integers(0, 2, N)
d1 = rng.integers(0, 10, N)
d2 = rng.integers(0, 10, N)
d345 = rng.integers(0, 1000, N)
zipcode = d1 * 10000 + d2 * 1000 + d345
income = np.clip(rng.lognormal(mean=np.log(45000) + 0.004 * (age - 18), sigma=0.45, size=N), 8000, 400000)

state_eff = rng.normal(0, 900, 10)
region_eff = rng.normal(0, 600, (10, 10))
area_eff = rng.normal(0, 400, (10, 10, 10))
d3 = d345 // 100
cost = (1500 + 4.0 * (age - 18) ** 1.6 + 350 * gender
+ state_eff[d1] + region_eff[d1, d2] + area_eff[d1, d2, d3]
- 0.012 * income + rng.normal(0, 700, N))

df = pd.DataFrame({"age": age, "gender": gender, "zip": zipcode,
"income": income, "cost": cost})

is_train = rng.random(N) < 0.7
y = df["cost"].to_numpy()
N_FOLD = 5
fold = rng.integers(0, N_FOLD, N)

# ------------------------------------------------------------
# 2. Generalization operators
# ------------------------------------------------------------
def generalize(age_w, zip_d, inc_w):
a_bin = (df["age"].to_numpy() // age_w).astype(np.int64)
a_mid = a_bin * age_w + age_w / 2.0
z_pre = (df["zip"].to_numpy() // 10 ** (5 - zip_d)).astype(np.int64)
i_bin = (df["income"].to_numpy() // inc_w).astype(np.int64)
i_mid = i_bin * inc_w + inc_w / 2.0
return a_bin, a_mid, z_pre, i_bin, i_mid

# ------------------------------------------------------------
# 3. Re-identification risk (fast: integer key + np.unique)
# ------------------------------------------------------------
K = 5
def risk_metrics(a_bin, z_pre, i_bin):
key = ((a_bin * 100001 + z_pre) * 2 + df["gender"].to_numpy()) * 1000 + i_bin
_, inv, cnt = np.unique(key, return_inverse=True, return_counts=True)
size = cnt[inv]
at_risk = np.mean(size < K)
avg_risk = np.mean(1.0 / size)
return at_risk, avg_risk, size.min(), size

# ------------------------------------------------------------
# 4. Utility: OLS on generalized data with target-encoded ZIP prefix
# ------------------------------------------------------------
def utility(a_mid, z_pre, zip_d, i_mid):
tr = is_train
gmean = y[tr].mean()
m = 20.0
cols = [np.ones(N), (a_mid - 50) / 10, ((a_mid - 50) / 10) ** 2, ((a_mid - 50) / 10) ** 3,
df["gender"].to_numpy(), i_mid / 1e4]
for L in range(1, zip_d + 1):
pre = z_pre // 10 ** (zip_d - L)
enc = np.empty(N)
# out-of-fold encoding for training rows (prevents target leakage)
for f in range(N_FOLD):
fit = tr & (fold != f)
app = tr & (fold == f)
s = pd.Series(y[fit]).groupby(pre[fit]).agg(["sum", "count"])
mp = (s["sum"] + m * gmean) / (s["count"] + m)
enc[app] = pd.Series(pre[app]).map(mp).fillna(gmean).to_numpy()
# full-train encoding for test rows
s = pd.Series(y[tr]).groupby(pre[tr]).agg(["sum", "count"])
mp = (s["sum"] + m * gmean) / (s["count"] + m)
enc[~tr] = pd.Series(pre[~tr]).map(mp).fillna(gmean).to_numpy()
cols.append(enc)
X = np.column_stack(cols)
beta, *_ = np.linalg.lstsq(X[tr], y[tr], rcond=None)
pred = X[~tr] @ beta
yt = y[~tr]
return 1 - np.sum((yt - pred) ** 2) / np.sum((yt - yt.mean()) ** 2)

# ------------------------------------------------------------
# 5. Grid search over the anonymization lattice
# ------------------------------------------------------------
AGE_W = [1, 2, 5, 10, 20, 40]
ZIP_D = [5, 4, 3, 2, 1, 0]
INC_W = [1000, 5000, 10000, 25000, 50000, 100000]
RISK_MAX = 0.05

t0 = time.time()
rows = []
for aw in AGE_W:
for zd in ZIP_D:
for iw in INC_W:
a_bin, a_mid, z_pre, i_bin, i_mid = generalize(aw, zd, iw)
at_risk, avg_risk, kmin, _ = risk_metrics(a_bin, z_pre, i_bin)
r2 = utility(a_mid, z_pre, zd, i_mid)
rows.append((aw, zd, iw, at_risk, avg_risk, kmin, r2))
res = pd.DataFrame(rows, columns=["age_w", "zip_d", "inc_w", "at_risk", "avg_risk", "k_min", "r2"])
elapsed = time.time() - t0

r2_orig = res.query("age_w==1 and zip_d==5 and inc_w==1000")["r2"].iloc[0]
risk_orig = res.query("age_w==1 and zip_d==5 and inc_w==1000")["at_risk"].iloc[0]
feas = res[res["at_risk"] <= RISK_MAX]
best = feas.sort_values(["r2", "k_min"], ascending=[False, False]).iloc[0]

# Pareto front (min risk, max r2)
srt = res.sort_values(["at_risk", "r2"], ascending=[True, False])
pareto, best_r2 = [], -np.inf
for _, r in srt.iterrows():
if r["r2"] > best_r2:
pareto.append(r)
best_r2 = r["r2"]
pareto = pd.DataFrame(pareto)

print(f"Configurations evaluated : {len(res)} ({elapsed:.2f} s)")
print(f"Raw data : R2 = {r2_orig:.4f}, records at risk (k<{K}) = {risk_orig:.3%}")
print(f"Feasible configurations (risk <= {RISK_MAX:.0%}) : {len(feas)}")
print("Optimal configuration:")
print(f" age bin width = {int(best.age_w)} years, ZIP digits kept = {int(best.zip_d)}, "
f"income bin width = {int(best.inc_w):,}")
print(f" R2 = {best.r2:.4f} ({best.r2 / r2_orig:.1%} of raw utility)")
print(f" records at risk = {best.at_risk:.3%}, average risk = {best.avg_risk:.4f}, k_min = {int(best.k_min)}")
print("\nTop 5 feasible configurations:")
print(feas.sort_values("r2", ascending=False).head(5).to_string(index=False))

# ------------------------------------------------------------
# 6. Visualization (2 x 3)
# ------------------------------------------------------------
fig = plt.figure(figsize=(21, 12))
iw_best = best.inc_w
sub = res[res["inc_w"] == iw_best]
A, Z = np.meshgrid(np.arange(len(AGE_W)), np.arange(len(ZIP_D)), indexing="ij")
R2g = np.zeros(A.shape); RKg = np.zeros(A.shape)
for i, aw in enumerate(AGE_W):
for j, zd in enumerate(ZIP_D):
r = sub[(sub.age_w == aw) & (sub.zip_d == zd)].iloc[0]
R2g[i, j] = r.r2; RKg[i, j] = r.at_risk

ax1 = fig.add_subplot(2, 3, 1, projection="3d")
ax1.plot_surface(A, Z, R2g, cmap=cm.viridis, edgecolor="k", linewidth=0.3, alpha=0.9)
ax1.set_xticks(range(len(AGE_W))); ax1.set_xticklabels(AGE_W)
ax1.set_yticks(range(len(ZIP_D))); ax1.set_yticklabels(ZIP_D)
ax1.set_xlabel("Age bin width"); ax1.set_ylabel("ZIP digits kept"); ax1.set_zlabel("R²")
ax1.set_title(f"Utility surface (income bin = {int(iw_best):,})")
ax1.view_init(28, -130)

ax2 = fig.add_subplot(2, 3, 2, projection="3d")
ax2.plot_surface(A, Z, RKg, cmap=cm.inferno, edgecolor="k", linewidth=0.3, alpha=0.9)
ax2.plot_surface(A, Z, np.full(A.shape, RISK_MAX), color="cyan", alpha=0.35)
ax2.set_xticks(range(len(AGE_W))); ax2.set_xticklabels(AGE_W)
ax2.set_yticks(range(len(ZIP_D))); ax2.set_yticklabels(ZIP_D)
ax2.set_xlabel("Age bin width"); ax2.set_ylabel("ZIP digits kept"); ax2.set_zlabel("Records at risk")
ax2.set_title("Risk surface with 5% threshold plane")
ax2.view_init(28, -130)

ax3 = fig.add_subplot(2, 3, 3, projection="3d")
xa = res["age_w"].map({v: i for i, v in enumerate(AGE_W)})
yz = res["zip_d"].map({v: i for i, v in enumerate(ZIP_D)})
zi = res["inc_w"].map({v: i for i, v in enumerate(INC_W)})
ok = res["at_risk"] <= RISK_MAX
sc = ax3.scatter(xa[ok], yz[ok], zi[ok], c=res["r2"][ok], cmap="viridis", s=45, marker="o", label="feasible")
ax3.scatter(xa[~ok], yz[~ok], zi[~ok], c="lightgray", s=12, marker="x", label="infeasible")
bi = (AGE_W.index(best.age_w), ZIP_D.index(best.zip_d), INC_W.index(best.inc_w))
ax3.scatter(*bi, c="red", s=250, marker="*", label="optimum")
ax3.set_xticks(range(len(AGE_W))); ax3.set_xticklabels(AGE_W)
ax3.set_yticks(range(len(ZIP_D))); ax3.set_yticklabels(ZIP_D)
ax3.set_zticks(range(len(INC_W))); ax3.set_zticklabels([f"{v//1000}k" for v in INC_W])
ax3.set_xlabel("Age bin width"); ax3.set_ylabel("ZIP digits kept"); ax3.set_zlabel("Income bin")
ax3.set_title("Generalization lattice (color = R²)")
fig.colorbar(sc, ax=ax3, shrink=0.55, pad=0.1)
ax3.legend(loc="upper left", fontsize=8)

ax4 = fig.add_subplot(2, 3, 4)
ax4.scatter(res["at_risk"], res["r2"], c="gray", s=15, alpha=0.6, label="all configs")
ax4.plot(pareto["at_risk"], pareto["r2"], "b-o", ms=4, label="Pareto front")
ax4.axvline(RISK_MAX, color="r", ls="--", label="risk threshold")
ax4.scatter(best.at_risk, best.r2, c="red", s=200, marker="*", zorder=5, label="optimum")
ax4.set_xscale("symlog", linthresh=1e-3)
ax4.set_xlabel("Records at risk (k < 5)"); ax4.set_ylabel("R²")
ax4.set_title("Privacy–utility trade-off"); ax4.legend(fontsize=8); ax4.grid(alpha=0.3)

ax5 = fig.add_subplot(2, 3, 5)
H = np.full((len(AGE_W), len(ZIP_D)), np.nan)
for i, aw in enumerate(AGE_W):
for j, zd in enumerate(ZIP_D):
f = feas[(feas.age_w == aw) & (feas.zip_d == zd)]
if len(f): H[i, j] = f["r2"].max()
im = ax5.imshow(H, cmap="YlGn", aspect="auto")
for i in range(len(AGE_W)):
for j in range(len(ZIP_D)):
ax5.text(j, i, "—" if np.isnan(H[i, j]) else f"{H[i, j]:.3f}", ha="center", va="center", fontsize=8)
ax5.set_xticks(range(len(ZIP_D))); ax5.set_xticklabels(ZIP_D)
ax5.set_yticks(range(len(AGE_W))); ax5.set_yticklabels(AGE_W)
ax5.set_xlabel("ZIP digits kept"); ax5.set_ylabel("Age bin width")
ax5.set_title("Best feasible R² (max over income bins)")
fig.colorbar(im, ax=ax5)

ax6 = fig.add_subplot(2, 3, 6)
_, _, _, s_raw = risk_metrics(*[generalize(1, 5, 1000)[k] for k in (0, 2, 3)])
g = generalize(int(best.age_w), int(best.zip_d), int(best.inc_w))
_, _, _, s_opt = risk_metrics(g[0], g[2], g[3])
bins = np.logspace(0, np.log10(max(s_raw.max(), s_opt.max()) + 1), 40)
ax6.hist(s_raw, bins=bins, alpha=0.6, label="raw", color="tomato")
ax6.hist(s_opt, bins=bins, alpha=0.6, label="optimal", color="seagreen")
ax6.axvline(K, color="k", ls="--", label=f"k = {K}")
ax6.set_xscale("log"); ax6.set_yscale("log")
ax6.set_xlabel("Equivalence class size of each record"); ax6.set_ylabel("Records")
ax6.set_title("Equivalence class size distribution"); ax6.legend(fontsize=8)

plt.tight_layout()
plt.show()

Code Walkthrough

1. Synthetic microdata

We draw 30,000 members with uniform ages from 18 to 89, a binary gender, and a 5-digit ZIP code built from three parts (d1, d2, d345). Income is log-normal and drifts slightly upward with age, so income and age are mildly correlated, as they are in real data.

The cost formula implements the data-generating process above. The term 4.0 * (age - 18) ** 1.6 makes cost rise convexly with age, which is why very wide age bins will hurt. The regional effects state_eff, region_eff and area_eff are indexed by the first one, two and three ZIP digits, so geography matters in layers.

The data is split 70/30 into train and test sets (is_train). Each record also gets a fold index (fold), used later for leakage-free target encoding.

2. Generalization operators

generalize(age_w, zip_d, inc_w) turns one lattice point $\theta$ into masked attributes:

  • a_bin = age // age_w is the integer bin ID, used for risk computation.
  • a_mid is the bin midpoint, the value the analyst would actually see and use in a model.
  • z_pre = zip // 10**(5 - zip_d) keeps only the leading zip_d digits. When zip_d = 0 every record maps to 0, so the ZIP code is fully suppressed.
  • Income gets the same treatment as age.

3. Re-identification risk, computed fast

This is where most of the speed comes from. A naive approach would call df.groupby([age, gender, zip, income]).transform("size") for each of the 216 configurations. Multi-column groupby on DataFrames is slow, because pandas has to hash tuples of mixed types.

Instead, we pack the four quasi-identifiers into a single int64 key with a mixed-radix encoding:

$$
\text{key} = \bigl((a_{\text{bin}} \cdot 100001 + z_{\text{pre}}) \cdot 2 + g\bigr) \cdot 1000 + i_{\text{bin}} .
$$

The multipliers are larger than the range of the next field (ZIP prefix < 100,000, gender ∈ {0, 1}, income bin < 1,000), so the encoding is injective. Two records share a key if and only if they share every quasi-identifier.

Then a single np.unique(key, return_inverse=True, return_counts=True) returns each class’s size, and cnt[inv] maps it back to every record. This runs in $O(N \log N)$ inside compiled NumPy code, and the whole risk evaluation for one configuration takes a few milliseconds.

From the class sizes we compute:

  • at_risk: the share of records with $|E(r)| < 5$
  • avg_risk: the mean of $1/|E(r)|$
  • k_min: the effective $k$ of the release

4. Utility measurement

The analyst’s model is an ordinary least squares regression on features they can build from the released data:

  • A cubic polynomial in the age-bin midpoint, centered and scaled for numerical stability: $\tilde a = (a_{\text{mid}} - 50)/10$, with $\tilde a, \tilde a^2, \tilde a^3$
  • Gender
  • The income-bin midpoint, scaled by $10^4$
  • Hierarchical target encodings of the ZIP prefix, one per retained level $L = 1, \dots, d_z$

ZIP codes are categorical with up to 100,000 levels, so one-hot encoding is out. For each level we replace the prefix with a smoothed mean of the target:

$$
\text{enc}(c) = \frac{\sum_{r \in c} y_r + m,\bar y}{n_c + m}, \qquad m = 20 .
$$

The prior weight $m$ pulls small categories toward the global mean $\bar y$, which prevents overfitting on sparse prefixes.

There is a classic trap here. If a training row’s own $y$ is included when computing its encoding, the feature leaks the target. The model then learns to trust the encoding far too much, and the test $R^2$ collapses. We avoid this with 5-fold out-of-fold encoding. Each training row’s encoding is computed only from the other four folds. Test rows are encoded using the full training set, which is exactly what would happen in production.

Including all levels $1, \dots, d_z$ rather than only the finest one lets the model rely on coarse geography when the fine levels are too sparse to be informative. As a result, keeping more digits never removes information the model could use, and the comparison across configurations is fair.

Finally, np.linalg.lstsq fits the coefficients and we compute the test-set $R^2$.

5. Exhaustive search over the lattice

Three nested loops visit all 216 schemes. For each one we record the risk metrics and the utility. Then we:

  • Use the identity configuration $(1, 5, 1000)$ as the “raw data” baseline
  • Filter for feasibility, $R_{\text{at-risk}} \le 0.05$
  • Pick the feasible scheme with the highest $R^2$, breaking ties by larger $k_{\min}$
  • Compute the Pareto front: sort by risk ascending, then sweep and keep every point whose $R^2$ beats all lower-risk points. Each Pareto point is a scheme that no other scheme beats on both privacy and utility at once.

The full search finishes in a few seconds. Most of that time goes to the target encoding, not the risk computation, so there is no need for a smarter lattice search (such as Incognito or OLA-style pruning) at this scale. With dozens of quasi-identifiers, monotonicity pruning would become worthwhile. If a scheme already satisfies the risk constraint, every coarser scheme does too.

6. Visualization

The figure is a 2×3 grid:

  1. Utility surface (3D): $R^2$ over age bin width × ZIP digits, with income fixed at the optimum’s bin width
  2. Risk surface (3D): the share of records at risk over the same grid, cut by a translucent cyan plane at the 5% threshold
  3. Generalization lattice (3D scatter): all 216 schemes in the space $(w_a, d_z, w_i)$. Feasible ones are colored by $R^2$, infeasible ones are gray crosses, and the optimum is a red star.
  4. Privacy–utility trade-off: $R^2$ against risk on a symlog axis, with the Pareto front and the threshold line
  5. Feasibility heatmap: for each (age, ZIP) pair, the best $R^2$ achievable while meeting the risk budget, maximized over income bins. A dash means no income bin can make that pair feasible.
  6. Equivalence class size distribution: log-log histograms of $|E(r)|$ for the raw data and for the optimal release

Execution Results

Configurations evaluated : 216  (24.16 s)
Raw data   : R2 = 0.7770, records at risk (k<5) = 100.000%
Feasible configurations (risk <= 5%) : 46
Optimal configuration:
  age bin width = 5 years, ZIP digits kept = 1, income bin width = 50,000
  R2 = 0.6231 (80.2% of raw utility)
  records at risk = 1.730%, average risk = 0.0368, k_min = 1

Top 5 feasible configurations:
 age_w  zip_d  inc_w  at_risk  avg_risk  k_min       r2
     5      1  50000 0.017300  0.036767      1 0.623082
    10      1  25000 0.024200  0.037767      1 0.622082
    40      2  50000 0.040967  0.065333      1 0.621828
    10      1  50000 0.009667  0.021133      1 0.615203
    40      2 100000 0.029000  0.039800      1 0.610392


Interpreting the Results

The raw data is a privacy disaster

With all attributes at full resolution, essentially 100% of records are unique. Every record sits in an equivalence class of size 1. You can see this in the bottom-right histogram, where the entire red mass is piled at $|E| = 1$. Releasing this data would give an attacker who knows a neighbor’s age, gender, ZIP and approximate income a near-certain match.

The raw data also gives the best model, with an out-of-sample $R^2$ of roughly 0.78. This is the ceiling against which every anonymized release is judged.

Risk falls off a cliff, not a slope

The risk surface (top middle) is the most instructive plot. Risk does not decrease smoothly with generalization. It stays near 1.0 across most of the grid and then drops sharply only when the ZIP code is cut to 1–2 digits. The reason is combinatorial. With 30,000 records spread over $10^{d_z}$ ZIP prefixes × age bins × income bins × 2 genders, the expected class size is

$$
\mathbb{E}|E| \approx \frac{N}{10^{d_z} \cdot n_a \cdot n_i \cdot 2}.
$$

Equivalence classes reach an average size of 5 only once the denominator falls to roughly 6,000. ZIP code is by far the most identifying attribute, because each extra digit multiplies the number of cells by ten.

Utility degrades gracefully, and unevenly

The utility surface (top left) behaves very differently.

  • Dropping ZIP digits 4–5 costs almost nothing. They carry no signal in the true model, only identifying power. This is the “free lunch” region of anonymization.
  • Dropping digit 3 costs a little, since $\gamma$ has a standard deviation of 400.
  • Dropping digits 1–2 costs a lot, because $\alpha$ and $\beta$ are large regional effects.
  • Age generalization is cheap up to about 10 years. The cubic polynomial fitted on bin midpoints still tracks the convex age curve well. At 40-year bins only about three age groups remain and the curvature is lost.

The optimum

Among the 46 feasible schemes, the winner keeps 5-year age bins, only the first ZIP digit, and 50k income bins. It retains about 80% of the raw utility ($R^2 \approx 0.62$) while only about 1.7% of records remain at risk, well inside the 5% budget.

The runners-up in the console’s top-5 table show that the solution space is quite flat near the top:

  • (10-year age, 1 ZIP digit, 25k income) is within 0.001 in $R^2$.
  • (40-year age, 2 ZIP digits, 50k income) reaches almost the same $R^2$ by a completely different route. It gives up nearly all age detail in exchange for the second ZIP digit and the large regional effect $\beta$.

This second route matters in practice. Two schemes with the same headline utility can serve very different analyses. A geographic health-equity study would prefer the 2-digit ZIP version. An actuarial age-pricing model would prefer the 5-year age version. “Maximize utility” always has to be read as “maximize utility for a specific downstream task”.

The Pareto front shows where to negotiate

The bottom-left plot is the one to bring to a data governance meeting. The Pareto front rises in steps, and each step corresponds to giving up or restoring one ZIP digit:

  • Around $R_{\text{at-risk}} \approx 10^{-3}$, $R^2$ jumps from about 0.5 to about 0.6. That is the gain from keeping the first ZIP digit instead of suppressing ZIP entirely.
  • Just to the right of the 5% line, $R^2$ jumps again to about 0.7. That is the second ZIP digit, which the constraint forbids.

So the key policy question is simply: is a 5% at-risk budget the right one? Relaxing it to around 10% would buy about 0.1 of $R^2$. Tightening it to 0.5% costs only a few hundredths. A plot like this makes the price of every privacy decision explicit, instead of leaving it as an argument between “privacy people” and “data people”.

The heatmap: which combinations can work at all

The feasibility heatmap (bottom middle) shows that keeping 3 or more ZIP digits is never feasible, however coarse age and income become. Two digits work only together with 40-year age bins. Almost all usable releases live in the “1 ZIP digit” column, where the darkest cells (5–10 year age bins) are the sweet spot.

Equivalence class distribution

The bottom-right histogram compares the raw and optimal releases. After optimal generalization, the bulk of records moves into classes of size 30–80, far above $k = 5$. A small tail (the ~1.7% at-risk records) remains below the dashed $k = 5$ line. In a real release these would be handled by local suppression, either masking a cell or dropping the record. Because they are so few, this barely affects utility, which is exactly why the at-risk-share formulation beats strict global $k$-anonymity in practice.


Takeaways

  1. Treat anonymization as constrained optimization. Fix the risk budget $\varepsilon$, define utility as performance on the real downstream task, and search the generalization lattice.
  2. Attributes are not equal. High-cardinality quasi-identifiers such as ZIP code dominate risk, while the signal often sits in their coarse levels. Truncate those aggressively first.
  3. Measure utility honestly. Target encoding without out-of-fold computation leaks the label and can make heavily masked data look better than raw data. That artifact would quietly push you toward the wrong release.
  4. Engineer the risk computation. Packing quasi-identifiers into a single integer key and using np.unique makes evaluating hundreds of schemes on tens of thousands of records nearly instant.
  5. Show the Pareto front, not only the optimum. The threshold is a policy choice, and stakeholders deserve to see what each point of privacy costs in analytical power.

Solving the Least Privilege Problem with Mixed-Integer Linear Programming in Python

The principle of least privilege says that every user should get the permissions their job requires and nothing more. In practice this is hard to do. Permissions are usually handed out through roles: pre-built bundles such as “Finance Viewer” or “DevOps Operator”. These bundles rarely match any one person’s needs exactly. If you assign a role to cover one permission, the user often gets several others they don’t need. Across hundreds of users, those extra permissions add up to a large attack surface.

This article turns the principle of least privilege into an optimization problem, solves it exactly with mixed-integer linear programming (MILP) in Python, and compares the result with the greedy approach that many identity teams use without realizing it.


The Problem Setting

Consider a small organization with:

  • 12 users $u \in \mathcal{U}$
  • 16 permissions $p \in \mathcal{P}$ (e.g., read_payroll, approve_invoice, deploy_prod, …). Each permission has a risk score $w_p \in [1, 10]$.
  • 14 predefined roles $r \in \mathcal{R}$. Each role is a fixed bundle of 2–5 permissions.
  • A need matrix $N_{u,p} \in {0,1}$ that says which permissions each user actually needs.
  • Separation of Duties (SoD) pairs $(a,b) \in \mathcal{S}$: two permissions one person should not hold together, such as “create vendor” and “approve payment”.

There are two ways to grant access:

  1. Role assignment. This is cheap to administer but coarse, so it often brings in extra permissions.
  2. Direct grant of a single permission. This is precise, but every exception has to be documented, reviewed and audited, so it carries an administrative cost $\mu$.

The goal is to find the assignment that guarantees every needed permission while minimizing the total risk of the extra permissions, the administrative overhead and SoD violations.


Mathematical Formulation

Decision variables

$$
x_{u,r} \in {0,1} \quad \text{user } u \text{ is assigned role } r
$$

$$
y_{u,p} \in {0,1} \quad \text{user } u \text{ effectively holds permission } p
$$

$$
d_{u,p} \in {0,1} \quad \text{permission } p \text{ is directly granted to } u \ (\text{allowed only if } N_{u,p}=1)
$$

$$
s_{u,k} \in {0,1} \quad \text{SoD pair } k \text{ is violated for user } u
$$

Objective

$$
\min \quad \lambda \sum_{u}\sum_{r} x_{u,r} ;+; \sum_{u}\sum_{p} w_p, y_{u,p} ;+; \mu \sum_{u}\sum_{p} d_{u,p} ;+; M \sum_{u}\sum_{k} s_{u,k}
$$

  • $\lambda$: administrative cost per role assignment
  • $w_p, y_{u,p}$: risk of every permission held. For needed permissions this term is a constant, so in effect only the risk of the extra permissions is minimized.
  • $\mu$: cost per direct grant
  • $M$: a large penalty for SoD violations, which makes them a near-hard constraint while keeping the model feasible

Constraints

Role propagation. A role grants every permission it contains:

$$
x_{u,r} \le y_{u,p} \qquad \forall u,\ \forall r,\ \forall p : A_{r,p} = 1
$$

Business coverage. Every needed permission must come from at least one role or from a direct grant:

$$
\sum_{r : A_{r,p}=1} x_{u,r} ;+; d_{u,p} ;\ge; 1 \qquad \forall u,\ \forall p : N_{u,p}=1
$$

Direct-grant consistency. A direct grant counts as holding the permission:

$$
d_{u,p} \le y_{u,p}
$$

Separation of Duties (soft). The constraint is skipped when the business explicitly needs both permissions:

$$
y_{u,a} + y_{u,b} - s_{u,k} \le 1 \qquad \forall u,\ \forall k=(a,b)\in\mathcal{S} : \neg(N_{u,a}=1 \wedge N_{u,b}=1)
$$

Optional direct-grant budget, used to trace the trade-off curve:

$$
\sum_{u}\sum_{p} d_{u,p} \le B
$$

When $d \equiv 0$ the model reduces to a weighted set-cover problem, which is NP-hard. The direct-grant extension turns it into a clean trade-off between precision and administrative overhead.


Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import milp, LinearConstraint, Bounds
from scipy.sparse import coo_matrix
import time

rng = np.random.default_rng(42)

U, P, R = 12, 16, 14
perm_names = [f"P{p:02d}" for p in range(P)]
risk = np.round(rng.uniform(1.0, 10.0, P), 1)

roles = np.zeros((R, P), dtype=int)
for r in range(R):
k = rng.integers(2, 6)
roles[r, rng.choice(P, k, replace=False)] = 1
for p in range(P):
if roles[:, p].sum() == 0:
roles[rng.integers(R), p] = 1

need = np.zeros((U, P), dtype=int)
for u in range(U):
k = rng.integers(2, 5)
need[u, rng.choice(P, k, replace=False)] = 1

sod_pairs = [(0, 1), (2, 3), (4, 5), (6, 7)]

def build_and_solve(need, roles, risk, sod_pairs, lam, direct_cost=None, max_direct=None, sod_penalty=100.0):
U, P = need.shape
R = roles.shape[0]
K = len(sod_pairs)
nx, ny, ns, nd = U * R, U * P, U * K, U * P
n = nx + ny + ns + nd
dc = 0.0 if direct_cost is None else direct_cost
c = np.concatenate([np.full(nx, lam), np.tile(risk, U), np.full(ns, sod_penalty), np.full(nd, dc)])
ub = np.ones(n)
if direct_cost is None and max_direct is None:
ub[nx + ny + ns:] = 0
else:
ub[nx + ny + ns:] = need.ravel()
d0 = nx + ny + ns
ri, ci, vi, lo, hi = [], [], [], [], []
k = 0
rr, pp = np.nonzero(roles)
m = len(rr)
for u in range(U):
rows = k + np.arange(m)
ri += [rows, rows]
ci += [u * R + rr, nx + u * P + pp]
vi += [np.ones(m), -np.ones(m)]
lo.append(np.full(m, -np.inf)); hi.append(np.zeros(m)); k += m
for p in np.flatnonzero(need[u]):
ri.append(np.array([k, k])); ci.append(np.array([d0 + u * P + p, nx + u * P + p]))
vi.append(np.array([1.0, -1.0]))
lo.append(np.array([-np.inf])); hi.append(np.array([0.0])); k += 1
cov = np.flatnonzero(roles[:, p])
ri.append(np.full(len(cov) + 1, k))
ci.append(np.append(u * R + cov, d0 + u * P + p))
vi.append(np.ones(len(cov) + 1))
lo.append(np.array([1.0])); hi.append(np.array([np.inf])); k += 1
for j, (a, b) in enumerate(sod_pairs):
if need[u, a] and need[u, b]:
continue
ri.append(np.full(3, k))
ci.append(np.array([nx + u * P + a, nx + u * P + b, nx + ny + u * K + j]))
vi.append(np.array([1.0, 1.0, -1.0]))
lo.append(np.array([-np.inf])); hi.append(np.array([1.0])); k += 1
if max_direct is not None:
ri.append(np.full(nd, k)); ci.append(d0 + np.arange(nd)); vi.append(np.ones(nd))
lo.append(np.array([-np.inf])); hi.append(np.array([float(max_direct)])); k += 1
A = coo_matrix((np.concatenate(vi), (np.concatenate(ri), np.concatenate(ci))), shape=(k, n)).tocsr()
res = milp(c, constraints=LinearConstraint(A, np.concatenate(lo), np.concatenate(hi)),
integrality=np.ones(n), bounds=Bounds(np.zeros(n), ub),
options={"time_limit": 60})
if res.x is None:
return None
z = np.round(res.x).astype(int)
X = z[:nx].reshape(U, R)
Y = z[nx:nx + ny].reshape(U, P)
D = z[d0:].reshape(U, P)
return X, Y, D, res.fun

def greedy(need, roles, risk):
U, P = need.shape
X = np.zeros((U, roles.shape[0]), dtype=int)
for u in range(U):
left = need[u].copy()
while left.sum() > 0:
gain = roles @ left
gain = np.where(gain > 0, gain, 0)
r = int(np.argmax(gain))
X[u, r] = 1
left = left * (1 - roles[r])
Y = (X @ roles > 0).astype(int)
return X, Y

lam = 2.0
mu = 12.0
X_rb, Y_rb, _, obj_rb = build_and_solve(need, roles, risk, sod_pairs, lam)
X_opt, Y_opt, D_opt, obj = build_and_solve(need, roles, risk, sod_pairs, lam, direct_cost=mu)
X_gr, Y_gr = greedy(need, roles, risk)

def excess(Y):
return ((Y - need).clip(0) * risk).sum(axis=1)

def sod_viol(Y):
v = 0
for u in range(U):
for a, b in sod_pairs:
if Y[u, a] and Y[u, b] and not (need[u, a] and need[u, b]):
v += 1
return v

print("=== Least Privilege Optimization ===")
print(f"Users={U}, Permissions={P}, Roles={R}, lambda={lam}, mu={mu}")
print(f"{'':26s}{'Greedy':>10s}{'MILP-RBAC':>12s}{'MILP+Direct':>13s}")
print(f"{'Coverage OK':26s}{str(bool(np.all(Y_gr >= need))):>10s}{str(bool(np.all(Y_rb >= need))):>12s}{str(bool(np.all(Y_opt >= need))):>13s}")
print(f"{'Excess risk':26s}{excess(Y_gr).sum():10.1f}{excess(Y_rb).sum():12.1f}{excess(Y_opt).sum():13.1f}")
print(f"{'Excess permissions':26s}{int((Y_gr - need).clip(0).sum()):10d}{int((Y_rb - need).clip(0).sum()):12d}{int((Y_opt - need).clip(0).sum()):13d}")
print(f"{'Role assignments':26s}{int(X_gr.sum()):10d}{int(X_rb.sum()):12d}{int(X_opt.sum()):13d}")
print(f"{'Direct grants':26s}{0:10d}{0:12d}{int(D_opt.sum()):13d}")
print(f"{'SoD violations':26s}{sod_viol(Y_gr):10d}{sod_viol(Y_rb):12d}{sod_viol(Y_opt):13d}")
print(f"Objective (MILP+Direct) : {obj:.2f}")
print()
for u in range(U):
rs = ",".join(f"R{r}" for r in np.flatnonzero(X_opt[u]))
ds = ",".join(perm_names[p] for p in np.flatnonzero(D_opt[u]))
ex = ",".join(perm_names[p] for p in np.flatnonzero(Y_opt[u] & (1 - need[u])))
print(f"User{u:02d}: roles=[{rs}] direct=[{ds}] excess=[{ex}]")

budgets = np.arange(0, 21, 2)
pareto_risk, pareto_sod = [], []
for B in budgets:
Xb, Yb, Db, _ = build_and_solve(need, roles, risk, sod_pairs, lam, max_direct=int(B))
pareto_risk.append(excess(Yb).sum())
pareto_sod.append(sod_viol(Yb))
print()
print("DirectBudget ExcessRisk SoDViolations")
for B, rk, sv in zip(budgets, pareto_risk, pareto_sod):
print(f"{B:12d} {rk:10.1f} {sv:13d}")

sizes = [20, 50, 100, 150, 200]
scales = [0.5, 1.0, 1.5, 2.0]
T = np.zeros((len(scales), len(sizes)))
for i, s in enumerate(scales):
for j, nu in enumerate(sizes):
r2 = np.random.default_rng(100 + i * 10 + j)
P2, R2 = int(16 * s), int(10 * s)
ro = np.zeros((R2, P2), dtype=int)
for r in range(R2):
ro[r, r2.choice(P2, r2.integers(2, 6), replace=False)] = 1
for p in range(P2):
if ro[:, p].sum() == 0:
ro[r2.integers(R2), p] = 1
ne = np.zeros((nu, P2), dtype=int)
for u in range(nu):
ne[u, r2.choice(P2, r2.integers(2, 5), replace=False)] = 1
rk = r2.uniform(1, 10, P2)
ts = []
for _ in range(3):
t0 = time.perf_counter()
build_and_solve(ne, ro, rk, [], lam, direct_cost=mu)
ts.append(time.perf_counter() - t0)
T[i, j] = min(ts)
print()
print("Solve time [s] (rows=scale, cols=users):")
print(np.round(T, 3))

fig = plt.figure(figsize=(21, 12))

ax1 = fig.add_subplot(2, 3, 1)
state = np.where(D_opt == 1, 3, np.where(need == 1, 2, Y_opt))
cmap = matplotlib.colors.ListedColormap(["#f2f2f2", "#ff7f0e", "#2ca02c", "#1f77b4"])
ax1.imshow(state, cmap=cmap, vmin=-0.5, vmax=3.5, aspect="auto")
ax1.set_xticks(range(P)); ax1.set_xticklabels(perm_names, rotation=90, fontsize=8)
ax1.set_yticks(range(U)); ax1.set_yticklabels([f"U{u:02d}" for u in range(U)], fontsize=8)
ax1.set_title("Optimal grants (green=role, blue=direct, orange=excess)")

ax2 = fig.add_subplot(2, 3, 2)
idx = np.arange(U); w = 0.38
w3 = 0.27
ax2.bar(idx - w3, excess(Y_gr), w3, label="Greedy", color="#d62728")
ax2.bar(idx, excess(Y_rb), w3, label="MILP-RBAC", color="#ff7f0e")
ax2.bar(idx + w3, excess(Y_opt), w3, label="MILP+Direct", color="#1f77b4")
ax2.set_xticks(idx); ax2.set_xticklabels([f"U{u:02d}" for u in range(U)], rotation=90, fontsize=8)
ax2.set_ylabel("Excess risk"); ax2.set_title("Excess privilege risk per user"); ax2.legend()

ax3 = fig.add_subplot(2, 3, 3)
ax3.plot(budgets, pareto_risk, "o-", color="#9467bd", label="Excess risk")
ax3.axvline(D_opt.sum(), color="gray", ls="--", label=f"Chosen (mu={mu:g}): {int(D_opt.sum())} direct grants")
ax3b = ax3.twinx()
ax3b.step(budgets, pareto_sod, where="mid", color="#e377c2", alpha=0.7)
ax3b.set_ylabel("SoD violations", color="#e377c2")
ax3.legend(loc="upper right")
ax3.set_xlabel("Max number of direct grants"); ax3.set_ylabel("Total excess risk")
ax3.set_title("Trade-off: direct-grant budget vs excess risk"); ax3.grid(alpha=0.3)

ax4 = fig.add_subplot(2, 3, 4, projection="3d")
uu, pp = np.meshgrid(np.arange(U), np.arange(P), indexing="ij")
hz = (Y_opt * risk).ravel()
col = np.where(D_opt.ravel() == 1, "#1f77b4", np.where((need == 1).ravel(), "#2ca02c", "#ff7f0e"))
m = hz > 0
ax4.bar3d(uu.ravel()[m], pp.ravel()[m], np.zeros(m.sum()), 0.7, 0.7, hz[m], color=col[m], shade=True)
ax4.set_xlabel("User"); ax4.set_ylabel("Permission"); ax4.set_zlabel("Risk")
ax4.set_title("3D: granted permissions weighted by risk")

ax5 = fig.add_subplot(2, 3, 5, projection="3d")
S, N = np.meshgrid(np.array(sizes), np.array(scales) * 16)
ax5.plot_surface(S, N, T, cmap="viridis", edgecolor="k", linewidth=0.3)
ax5.set_xlabel("Users"); ax5.set_ylabel("Permissions"); ax5.set_zlabel("Time [s]")
ax5.set_title("3D: MILP solve time scaling")

ax6 = fig.add_subplot(2, 3, 6)
ax6.bar(np.arange(R) - w3, X_gr.sum(axis=0), w3, label="Greedy", color="#d62728")
ax6.bar(np.arange(R), X_rb.sum(axis=0), w3, label="MILP-RBAC", color="#ff7f0e")
ax6.bar(np.arange(R) + w3, X_opt.sum(axis=0), w3, label="MILP+Direct", color="#1f77b4")
ax6.set_xticks(range(R)); ax6.set_xticklabels([f"R{r}" for r in range(R)])
ax6.set_ylabel("Users assigned"); ax6.set_title("Role usage"); ax6.legend()

plt.tight_layout()
plt.show()

Code Walkthrough

1. Generating the example data

A fixed random seed (default_rng(42)) makes the example reproducible.

  • risk: a risk score $w_p$ between 1.0 and 10.0 for each permission.
  • roles: the $R \times P$ role–permission matrix $A_{r,p}$. Each role gets 2–5 random permissions. A safety loop then makes sure every permission belongs to at least one role, so the pure role-based model always has a feasible solution.
  • need: the $U \times P$ need matrix $N_{u,p}$. Each user needs 2–4 permissions.
  • sod_pairs: four conflicting pairs, e.g. (P00, P01) could be “create vendor” and “approve payment”.

2. build_and_solve: building the MILP

This function is the core of the article. All variables sit in one flat vector in this order:

Block Size Meaning
x $U\cdot R$ role assignments
y $U\cdot P$ effective permissions
s $U\cdot K$ SoD violation slacks
d $U\cdot P$ direct grants

The cost vector c matches the objective term by term: $\lambda$ for each x, $w_p$ for each y, the penalty $M=100$ for each s, and $\mu$ for each d.

Upper bounds as a modeling trick. The ub array sets the upper bound of $d_{u,p}$ to $N_{u,p}$. A direct grant is therefore possible only for permissions the user actually needs, and no extra constraints are required for this. When neither direct_cost nor max_direct is given, all d bounds are 0, which gives the pure RBAC model (MILP-RBAC).

Building the sparse matrix (the speed-up). The constraint matrix is filled as COO triplets (ri, ci, vi) and converted to CSR only once. The role-propagation block is the largest one, with $U \cdot \text{nnz}(A)$ rows. It is created for each user with one vectorized operation on the precomputed role–permission pairs rr, pp = np.nonzero(roles), not with nested Python loops. An earlier version that set entries one at a time in a lil_matrix got slower in proportion to the number of nonzeros. The vectorized COO version spends almost all of its time inside the HiGHS solver, not in Python.

The constraints, in order:

  1. Propagation $x_{u,r} - y_{u,p} \le 0$: one row per user and per (role, permission) pair.
  2. Direct-grant consistency $d_{u,p} - y_{u,p} \le 0$.
  3. Coverage $\sum_r x_{u,r} + d_{u,p} \ge 1$, which uses every role that contains $p$.
  4. SoD $y_{u,a} + y_{u,b} - s_{u,k} \le 1$, skipped when the user needs both permissions.
  5. Optional budget $\sum d \le B$, used for the trade-off curve.

scipy.optimize.milp calls the HiGHS branch-and-cut solver. integrality=np.ones(n) makes every variable binary, together with the [0, ub] bounds. The solution is rounded to clean integers and split back into the X, Y and D matrices.

3. greedy: the baseline

This mirrors what an administrator does by hand. For each user, it repeatedly picks the role that covers the most still-uncovered needed permissions until everything is covered. It ignores risk scores and SoD rules entirely. This is the classic $\ln n$-approximation for set cover.

4. Three strategies compared

  • Greedy: the heuristic role assignment.
  • MILP-RBAC: the optimal assignment using roles only ($d \equiv 0$).
  • MILP+Direct: the optimal assignment where direct grants cost $\mu = 12$ each.

excess(Y) computes each user’s extra-permission risk $\sum_p w_p \max(0, Y_{u,p} - N_{u,p})$. sod_viol(Y) counts real SoD conflicts.

5. Trade-off sweep

The model is solved again with a hard cap $B \in {0, 2, \dots, 20}$ on the number of direct grants. This traces the efficient frontier: how much extra-permission risk you can remove for each additional exception you are willing to manage.

6. Scalability experiment

Random instances are generated with 20–200 users and 8–32 permissions (with matching role counts). Each instance is solved three times and the minimum wall-clock time is kept, which filters out timing noise from the shared Colab machine.

7. Visualization

A single 21 × 12 figure holds a 2 × 3 grid. The panels are explained in the next section.


Execution Results

=== Least Privilege Optimization ===
Users=12, Permissions=16, Roles=14, lambda=2.0, mu=12.0
                              Greedy   MILP-RBAC  MILP+Direct
Coverage OK                     True        True         True
Excess risk                    387.6       251.8         85.4
Excess permissions                59          39           17
Role assignments                  27          26           18
Direct grants                      0           0           11
SoD violations                    12           3            0
Objective (MILP+Direct)   : 453.10

User00: roles=[R8]  direct=[P06,P09]  excess=[P04]
User01: roles=[R0,R10]  direct=[]  excess=[P10]
User02: roles=[R4]  direct=[P00,P03]  excess=[P11,P12]
User03: roles=[R10]  direct=[P06]  excess=[P10]
User04: roles=[]  direct=[P03,P13]  excess=[]
User05: roles=[R5,R8]  direct=[]  excess=[P00,P11]
User06: roles=[R0,R10]  direct=[]  excess=[P08]
User07: roles=[R8,R11]  direct=[]  excess=[P00,P10,P12]
User08: roles=[R8]  direct=[P01]  excess=[P04]
User09: roles=[R0,R10]  direct=[P02,P06]  excess=[P08,P15]
User10: roles=[R10,R12]  direct=[P09]  excess=[P08,P10]
User11: roles=[R7,R8]  direct=[]  excess=[P12]

DirectBudget  ExcessRisk  SoDViolations
           0       251.8              3
           2       210.8              1
           4       201.1              0
           6       154.2              0
           8       124.7              0
          10        96.8              0
          12        74.3              0
          14        57.0              0
          16        44.7              0
          18        32.9              0
          20        24.3              0

Solve time [s] (rows=scale, cols=users):
[[0.025 0.081 0.072 0.244 0.945]
 [0.024 0.099 0.273 0.402 0.447]
 [0.015 0.068 0.154 0.347 0.398]
 [0.037 0.109 0.208 0.566 0.657]]


Interpreting the Results

Summary table

With the fixed seed, the three strategies compare as follows:

Metric Greedy MILP-RBAC MILP+Direct
Coverage of needed permissions ✓ ✓ ✓
Total extra-permission risk 387.6 251.8 85.4
Extra permissions 59 39 17
Role assignments 27 26 18
Direct grants 0 0 11
SoD violations 12 3 0

All three meet every business need, but at very different cost to security:

  • Optimizing only the choice of roles (MILP-RBAC) already cuts extra-permission risk by about 35 % compared with greedy. It also brings SoD conflicts down from 12 to 3, with no change to the role catalog.
  • Allowing a small number of targeted exceptions (11 direct grants) removes about 78 % of greedy’s extra-permission risk and all SoD violations.

The 3 SoD violations left in MILP-RBAC are unavoidable with the current role catalog. The penalty $M = 100$ is far larger than any risk score, so the solver drives violations to the lowest number possible. A remaining violation therefore tells you that a role needs to be split, which is useful input for role engineering.

Panel 1: Optimal grants heatmap (top left)

Each row is a user and each column is a permission. Green cells are needed permissions covered by a role, blue cells are needed permissions given as direct grants, and orange cells are extra permissions that come in with a role. The goal is as little orange as possible. Columns like P10 and P12 stay orange for several users. These permissions are bundled into popular roles, which makes them strong candidates for splitting those roles.

Panel 2: Extra-permission risk per user (top center)

Red bars are greedy, orange bars are MILP-RBAC and blue bars are MILP+Direct. For users such as U02, U10 and U11, the greedy heuristic grants almost 6× more risk than needed. In a few cases (U00, U03, U09) the RBAC optimum gives a user slightly more risk than greedy. This is expected: the MILP minimizes total risk plus SoD penalties across the organization, so it may accept a little more exposure for one user to remove a serious SoD conflict for another.

Panel 3: Direct-grant budget vs. extra-permission risk (top right)

This is the efficient frontier. The purple curve shows how total extra-permission risk falls as you allow more direct grants. It drops from 251.8 with no exceptions to 24.3 with 20. The pink step line (right axis) shows SoD violations reaching 0 after just 4 exceptions. The curve flattens as it goes, so the first few exceptions are worth the most. The dashed line marks the solution chosen automatically with $\mu = 12$ (11 direct grants), where one more exception would cost more in administration than the risk it removes. Security teams can use this chart to set an exception budget based on data rather than intuition.

Panel 4: 3D view of granted permissions weighted by risk (bottom left)

Every bar is one permission held by one user, and its height is the permission’s risk $w_p$. Green and blue bars are needed permissions; orange bars are extra ones. The 3D view makes it easy to spot tall orange towers: high-risk extra permissions, which are exactly what an attacker would target after compromising that account. These are the first items to fix in an access review.

Panel 5: 3D surface of MILP solve time (bottom center)

Solve time is plotted against the number of users and permissions. Even the largest instance (200 users × 32 permissions, more than 10,000 binary variables) solves in well under a second. The surface is not perfectly smooth, which is typical of branch-and-bound: some instances happen to be harder than others of the same size. Still, the trend shows that exact optimization is entirely practical at department scale. For organizations with tens of thousands of identities, the model splits naturally by user, because users interact only through shared role definitions. Each business unit can then be solved in parallel.

Panel 6: Role usage (bottom right)

This panel shows how many users each strategy assigns to each role. Greedy relies heavily on broad roles such as R1, R2 and R3 because they cover many permissions at once, and that same breadth makes them dangerous. The MILP strategies move toward narrower roles such as R8 and R10. R13 is never used by any strategy, which suggests it can be retired from the catalog.


Key Takeaways

  1. Least privilege can be written as a clear mathematical model. It is a weighted set-cover problem with propagation, coverage and SoD constraints, and modern MILP solvers handle it easily.
  2. Greedy role assignment is costly. Even without changing a single role definition, optimal assignment cut extra-permission risk by about a third and SoD conflicts by three quarters.
  3. Exceptions are a resource to spend, not a failure. The efficient frontier shows exactly how much risk each additional direct grant removes, so you can decide on an exception budget with evidence.
  4. The model points to role-engineering work. SoD violations that remain, permissions that are often extra, and roles nobody uses are concrete signs of which roles to split, narrow or retire.

Optimizing Cyber Insurance Coverage and Premiums

Deductible, Limit and Residual Risk in Python

Buying cyber insurance means choosing three numbers at once: the deductible you absorb yourself, the coverage limit the insurer will pay, and the premium you can afford. A low deductible and a high limit feel safe, but the premium rises quickly. A high deductible keeps the bill small but leaves you exposed to a bad year. This article turns that tension into an optimization problem and solves it in Python.

1. The Example Problem

A mid-sized company faces the following cyber risk profile (all amounts in million USD).

  • Incidents per year follow a Poisson distribution with mean $\lambda = 1.2$.
  • Each incident causes a loss $X$ that follows a heavy-tailed lognormal distribution, $\ln X \sim \mathcal{N}(\mu, \sigma^2)$ with $\mu=\ln 0.5$ and $\sigma = 1.5$.
  • The expected annual loss without insurance is about 1.84 M$, but a bad year can cost many times that.

The company can buy a per-incident policy with deductible $d$ and limit $L$. For one incident, the insurer pays

$$
I(X; d, L) = \min{(X-d)^+,; L},
$$

and the company keeps

$$
R(X; d, L) = X - I(X; d, L).
$$

Over a year, with $N \sim \mathrm{Poisson}(\lambda)$ incidents,

$$
S_{\text{pay}} = \sum_{i=1}^{N} I(X_i; d, L), \qquad S_{\text{ret}} = \sum_{i=1}^{N} R(X_i; d, L).
$$

The insurer prices the policy with an expected-value loading, a volatility loading and a capital charge on the limit:

$$
P(d, L) = (1+\theta),\mathbb{E}[S_{\text{pay}}] + \gamma,\mathrm{SD}[S_{\text{pay}}] + c,L + f,
$$

with $\theta = 0.30$, $\gamma = 0.20$, $c = 0.015$ and $f = 0.05$.

The total annual cost to the company is the premium plus the retained loss:

$$
C = P(d, L) + S_{\text{ret}}.
$$

Residual risk is measured by the Conditional Value at Risk. By the Rockafellar–Uryasev representation,

which is the average cost over the worst $(1-\alpha)$ fraction of years. Financial impact is measured by the probability that the annual cost exceeds a cash buffer $W = 8$ M$:

$$
\Pr(C > W).
$$

The optimization problem balances average cost against tail cost under a premium budget $B = 1.8$ M$:

$$
\min_{d,,L}; J(d, L) = (1-\rho),\mathbb{E}[C] + \rho,\mathrm{CVaR}_{0.95}(C)
\quad \text{s.t.} \quad P(d, L) \le B,;; 0 \le d \le 4,;; 0 < L \le 30,
$$

with risk weight $\rho = 0.5$.

For a lognormal severity, the expected annual payout has a closed form through the limited expected value $\mathrm{LEV}(u) = \mathbb{E}[\min(X, u)]$:

$$
\mathrm{LEV}(u) = e^{\mu + \sigma^2/2},\Phi!\left(\frac{\ln u - \mu - \sigma^2}{\sigma}\right) + u\left[1 - \Phi!\left(\frac{\ln u - \mu}{\sigma}\right)\right],
$$

$$
\mathbb{E}[S_{\text{pay}}] = \lambda,\big[\mathrm{LEV}(d+L) - \mathrm{LEV}(d)\big].
$$

The code uses this formula to validate the simulation.

2. Full Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import time
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import ndtr

# ------------------------------------------------------------------
# 1. Model parameters (monetary unit: million USD)
# ------------------------------------------------------------------
SEED = 2026
N_YEARS = 40_000 # simulated years (scenario set)
LAMBDA = 1.2 # expected number of cyber incidents per year
MU = np.log(0.5) # log-median of incident loss = 0.5 M$
SIGMA = 1.5 # log-standard deviation (heavy tail)
THETA = 0.30 # proportional loading
GAMMA = 0.20 # volatility loading (std of annual payout)
CAP_CHARGE = 0.015 # capital charge per unit of limit
FIXED_FEE = 0.05 # fixed underwriting expense
ALPHA = 0.95 # CVaR confidence level
RHO = 0.50 # weight on tail risk in the objective
BUDGET = 1.80 # maximum premium the company can pay
BUFFER = 8.0 # cash buffer used to measure financial distress
D_MAX = 4.0 # largest deductible considered
L_MAX = 30.0 # largest coverage limit considered

# ------------------------------------------------------------------
# 2. Common-random-number scenario set
# ------------------------------------------------------------------
rng = np.random.default_rng(SEED)
counts = rng.poisson(LAMBDA, N_YEARS)
year_idx = np.repeat(np.arange(N_YEARS), counts)
severity = np.exp(MU + SIGMA * rng.standard_normal(int(counts.sum())))

def annual_sum(event_values):
return np.bincount(year_idx, weights=event_values, minlength=N_YEARS)

def cvar(x, alpha=ALPHA):
k = int(np.ceil((1.0 - alpha) * x.size))
return float(np.partition(x, x.size - k)[x.size - k:].mean())

def lev(u):
u = np.maximum(u, 1e-12)
z = (np.log(u) - MU) / SIGMA
return np.exp(MU + 0.5 * SIGMA ** 2) * ndtr(z - SIGMA) + u * (1.0 - ndtr(z))

def expected_payout_analytic(d, L):
return float(LAMBDA * (lev(d + L) - lev(d)))

def evaluate(d, L, insured=True):
if insured:
payout = np.clip(severity - d, 0.0, L)
annual_pay = annual_sum(payout)
premium = float((1.0 + THETA) * annual_pay.mean() + GAMMA * annual_pay.std()
+ CAP_CHARGE * L + FIXED_FEE)
retained = annual_sum(severity - payout)
exp_payout = float(annual_pay.mean())
else:
premium = 0.0
retained = annual_sum(severity)
exp_payout = 0.0
total = premium + retained
return {
"d": d, "L": L,
"premium": premium,
"exp_payout": exp_payout,
"exp_retained": float(retained.mean()),
"cvar_retained": cvar(retained),
"exp_total": float(total.mean()),
"var_total": float(np.quantile(total, ALPHA)),
"cvar_total": cvar(total),
"p_exceed": float((total > BUFFER).mean()),
"total": total,
}

def objective(res):
return (1.0 - RHO) * res["exp_total"] + RHO * res["cvar_total"]

# ------------------------------------------------------------------
# 3. Stage 1: coarse grid search
# ------------------------------------------------------------------
t0 = time.time()
d_grid = np.linspace(0.05, D_MAX, 30)
L_grid = np.linspace(1.0, L_MAX, 30)
J = np.zeros((d_grid.size, L_grid.size))
P = np.zeros_like(J)
CVR = np.zeros_like(J)
for i, d in enumerate(d_grid):
for j, L in enumerate(L_grid):
r = evaluate(d, L)
J[i, j] = objective(r)
P[i, j] = r["premium"]
CVR[i, j] = r["cvar_retained"]
t_grid = time.time() - t0

feasible = P <= BUDGET
J_feasible = np.where(feasible, J, np.inf)
i_best, j_best = np.unravel_index(np.argmin(J_feasible), J.shape)
i_free, j_free = np.unravel_index(np.argmin(J), J.shape)

# ------------------------------------------------------------------
# 4. Stage 2: zoom-in refinement around the best feasible cell
# ------------------------------------------------------------------
best_d, best_L = float(d_grid[i_best]), float(L_grid[j_best])
best_J = float(J_feasible[i_best, j_best])
half_d = float(d_grid[1] - d_grid[0])
half_L = float(L_grid[1] - L_grid[0])
for _ in range(2):
for d in np.clip(np.linspace(best_d - half_d, best_d + half_d, 15), 0.0, D_MAX):
for L in np.clip(np.linspace(best_L - half_L, best_L + half_L, 15), 0.5, L_MAX):
r = evaluate(float(d), float(L))
if r["premium"] <= BUDGET:
j_val = objective(r)
if j_val < best_J:
best_J, best_d, best_L = j_val, float(d), float(L)
half_d /= 4.0
half_L /= 4.0
t_total = time.time() - t0

res_opt = evaluate(best_d, best_L)
res_free = evaluate(float(d_grid[i_free]), float(L_grid[j_free]))
strategies = [
("No insurance", evaluate(0.0, 0.0, insured=False)),
("Conventional", evaluate(0.5, 10.0)),
("Full cover", evaluate(0.05, 30.0)),
("Optimal (budget)", res_opt),
]

# ------------------------------------------------------------------
# 5. Console report
# ------------------------------------------------------------------
print("=" * 100)
print("Cyber insurance optimization: deductible d, limit L, premium")
print("=" * 100)
print(f"Scenario set: {N_YEARS:,} years, {len(severity):,} incidents")
print(f"Expected annual loss without insurance : {strategies[0][1]['exp_retained']:.3f} M$")
print(f"Grid evaluations: {d_grid.size * L_grid.size} in {t_grid:.2f} s (total with refinement {t_total:.2f} s)")
print(f"Premium budget: {BUDGET:.2f} M$ | Cash buffer: {BUFFER:.1f} M$ | CVaR level: {ALPHA:.0%} | rho = {RHO:.2f}")
print("-" * 100)
print(f"Unconstrained optimum : d = {res_free['d']:.3f}, L = {res_free['L']:.2f}, "
f"premium = {res_free['premium']:.3f}, J = {objective(res_free):.3f}")
print(f"Budget-constrained opt: d = {res_opt['d']:.3f}, L = {res_opt['L']:.2f}, "
f"premium = {res_opt['premium']:.3f}, J = {objective(res_opt):.3f}")
print("-" * 100)
header = (f"{'Strategy':<18}{'d':>6}{'L':>7}{'Premium':>9}{'E[Ret]':>8}{'CVaR[Ret]':>10}"
f"{'E[Cost]':>9}{'VaR95':>8}{'CVaR95':>8}{'P(C>Buf)':>10}{'J':>8}")
print(header)
for name, r in strategies:
print(f"{name:<18}{r['d']:>6.2f}{r['L']:>7.2f}{r['premium']:>9.3f}{r['exp_retained']:>8.3f}"
f"{r['cvar_retained']:>10.3f}{r['exp_total']:>9.3f}{r['var_total']:>8.3f}"
f"{r['cvar_total']:>8.3f}{r['p_exceed']:>10.4f}{objective(r):>8.3f}")
print("-" * 100)
print("Validation of the simulated expected payout against the closed-form lognormal formula")
for name, r in strategies[1:]:
ana = expected_payout_analytic(r["d"], r["L"])
print(f"{name:<18} simulated = {r['exp_payout']:.4f} M$ | analytic = {ana:.4f} M$ | "
f"relative gap = {abs(r['exp_payout'] - ana) / ana:.2%}")
print("=" * 100)

# ------------------------------------------------------------------
# 6. Visualization: 2 rows x 3 columns in one figure
# ------------------------------------------------------------------
plt.style.use("dark_background")
Dm, Lm = np.meshgrid(d_grid, L_grid, indexing="ij")
colors = ["#ff6b6b", "#feca57", "#48dbfb", "#1dd1a1"]

fig = plt.figure(figsize=(22, 12))
fig.suptitle("Cyber Insurance Optimization: Deductible, Coverage Limit and Premium", fontsize=18)

# (1) 3D surface of the objective
ax1 = fig.add_subplot(2, 3, 1, projection="3d")
ax1.plot_surface(Dm, Lm, J, cmap="viridis", alpha=0.92, linewidth=0, antialiased=True)
ax1.scatter([res_opt["d"]], [res_opt["L"]], [objective(res_opt)], color="red", s=90, depthshade=False)
ax1.set_xlabel("Deductible d [M$]")
ax1.set_ylabel("Limit L [M$]")
ax1.set_zlabel("Objective J")
ax1.set_title("(1) Objective surface J(d, L)")
ax1.view_init(elev=28, azim=-125)

# (2) 3D surface of the premium with the budget plane
ax2 = fig.add_subplot(2, 3, 2, projection="3d")
ax2.plot_surface(Dm, Lm, P, cmap="magma", alpha=0.92, linewidth=0, antialiased=True)
ax2.plot_surface(Dm, Lm, np.full_like(P, BUDGET), color="cyan", alpha=0.30, linewidth=0)
ax2.scatter([res_opt["d"]], [res_opt["L"]], [res_opt["premium"]], color="lime", s=90, depthshade=False)
ax2.set_xlabel("Deductible d [M$]")
ax2.set_ylabel("Limit L [M$]")
ax2.set_zlabel("Premium [M$]")
ax2.set_title("(2) Premium surface and budget plane")
ax2.view_init(elev=28, azim=-45)

# (3) Contour map with the feasible region boundary
ax3 = fig.add_subplot(2, 3, 3)
cf = ax3.contourf(d_grid, L_grid, J.T, levels=28, cmap="viridis")
fig.colorbar(cf, ax=ax3, label="Objective J")
ax3.contour(d_grid, L_grid, P.T, levels=[BUDGET], colors="white", linewidths=2.2)
ax3.scatter([res_opt["d"]], [res_opt["L"]], marker="*", s=380, color="red", edgecolor="white",
label="Budget-constrained optimum", zorder=5)
ax3.scatter([res_free["d"]], [res_free["L"]], marker="D", s=110, color="cyan", edgecolor="white",
label="Unconstrained optimum", zorder=5)
ax3.plot([], [], color="white", linewidth=2.2, label="Premium = budget")
ax3.set_xlabel("Deductible d [M$]")
ax3.set_ylabel("Limit L [M$]")
ax3.set_title("(3) Contour of J and feasible region")
ax3.legend(loc="upper right", fontsize=8)

# (4) Premium versus residual tail risk
ax4 = fig.add_subplot(2, 3, 4)
sc = ax4.scatter(P.ravel(), CVR.ravel(), c=Dm.ravel(), cmap="plasma", s=14, alpha=0.9)
fig.colorbar(sc, ax=ax4, label="Deductible d [M$]")
ax4.scatter([0.0], [strategies[0][1]["cvar_retained"]], marker="X", s=160, color="white", label="No insurance")
ax4.scatter([res_opt["premium"]], [res_opt["cvar_retained"]], marker="*", s=380, color="red",
edgecolor="white", label="Optimal", zorder=5)
ax4.axvline(BUDGET, color="cyan", linestyle="--", linewidth=1.5, label="Premium budget")
ax4.set_xlabel("Annual premium [M$]")
ax4.set_ylabel("Residual tail loss: CVaR95 of retained loss [M$]")
ax4.set_title("(4) Premium vs residual risk")
ax4.legend(fontsize=8)
ax4.grid(alpha=0.25)

# (5) Exceedance probability curves of the annual total cost
ax5 = fig.add_subplot(2, 3, 5)
probs = np.logspace(-3, 0, 160)
for (name, r), c in zip(strategies, colors):
ax5.plot(np.quantile(r["total"], 1.0 - probs), probs, color=c, linewidth=2.2, label=name)
ax5.axvline(BUFFER, color="white", linestyle="--", linewidth=1.5, label="Cash buffer")
ax5.set_yscale("log")
ax5.set_xlim(0, 25)
ax5.set_xlabel("Annual total cost: premium + retained loss [M$]")
ax5.set_ylabel("Exceedance probability")
ax5.set_title("(5) Exceedance curves")
ax5.legend(fontsize=8)
ax5.grid(alpha=0.25, which="both")

# (6) Expected cost breakdown and tail cost
ax6 = fig.add_subplot(2, 3, 6)
labels = ["No\ninsurance", "Conventional", "Full\ncover", "Optimal"]
prem = np.array([r["premium"] for _, r in strategies])
ret = np.array([r["exp_retained"] for _, r in strategies])
cv = np.array([r["cvar_total"] for _, r in strategies])
xpos = np.arange(len(strategies))
ax6.bar(xpos, prem, color="#54a0ff", label="Premium")
ax6.bar(xpos, ret, bottom=prem, color="#ff9f43", label="Expected retained loss")
ax6.scatter(xpos, cv, marker="D", s=90, color="#ff6b6b", edgecolor="white", label="CVaR95 of total cost", zorder=5)
ax6.set_xticks(xpos)
ax6.set_xticklabels(labels)
ax6.set_ylabel("Cost [M$]")
ax6.set_title("(6) Expected cost breakdown vs tail cost")
ax6.legend(fontsize=8)
ax6.grid(alpha=0.25, axis="y")

fig.tight_layout(rect=[0, 0, 1, 0.96])
plt.show()

3. Detailed Code Walkthrough

3.1 Parameters and the scenario set

All monetary values are in million USD. The incident loss has median $e^{\mu} = 0.5$ M$, but with $\sigma = 1.5$ its mean is $e^{\mu+\sigma^2/2} \approx 1.54$ M$ and its upper tail is very heavy. This is the typical shape of cyber losses: most incidents are small and a few are catastrophic.

The scenario set is generated once, at the top:

  • counts holds the number of incidents in each of the 40,000 simulated years.
  • year_idx repeats each year’s index once per incident, so every incident knows which year it belongs to.
  • severity holds one lognormal loss per incident.

Every candidate policy is evaluated against exactly the same 40,000 simulated years. This is the common random numbers technique. Differences between policies then reflect the policies themselves rather than sampling noise, which makes the objective surface smooth enough to optimize reliably.

3.2 The speed-up: vectorization instead of loops

A naive implementation would loop over years and incidents for every candidate $(d, L)$, roughly 48,000 incidents times 900 grid points in pure Python. The code avoids this in four ways:

  • np.clip(severity - d, 0.0, L) computes $\min{(X-d)^+, L}$ for all incidents in a single vectorized call.
  • np.bincount(year_idx, weights=..., minlength=N_YEARS) converts per-incident values into per-year totals in one pass. It replaces a Python-level group-by.
  • np.partition inside cvar finds the worst 5% of years in linear time, instead of sorting all 40,000 values.
  • The two-stage search uses a coarse 30 × 30 grid to find the global shape of the problem, then a zoom-in refinement on 15 × 15 local grids. The refinement needs only about 450 additional evaluations, and the full run takes only a few seconds.

3.3 Pricing and the objective

evaluate is the heart of the program. For an insured policy it computes the annual payout series, then applies the pricing formula: expected payout with loading $\theta$, plus a volatility charge $\gamma,\mathrm{SD}[S_{\text{pay}}]$, plus a capital charge $cL$ and a fixed fee $f$. The capital charge matters. It reflects that insurers hold capital against the limit they sell, so a higher limit costs more even when the extra layer is rarely hit. It also makes the choice of $L$ a genuine trade-off.

The retained loss is whatever the insurer does not pay, severity - payout. Adding the premium gives the total annual cost total, and from it the function returns the expected cost, the 95% VaR, the 95% CVaR and the exceedance probability $\Pr(C > W)$.

objective combines the mean and the tail as $J = (1-\rho),\mathbb{E}[C] + \rho,\mathrm{CVaR}_{0.95}(C)$. With $\rho = 0.5$, the company cares equally about its average bill and its worst-year bill.

3.4 Validation with the closed form

lev and expected_payout_analytic implement the lognormal formula from Section 1. The console report compares the simulated expected payout with the closed form for each insured strategy. A small relative gap confirms that the scenario set, the clipping logic and the bincount aggregation are all correct.

3.5 Grid search, budget and refinement

The first stage evaluates $J$, the premium and the residual tail loss on a $30 \times 30$ grid of $(d, L)$ pairs. Cells with a premium above the budget are set to infinity in J_feasible, so argmin returns the best feasible cell. A separate argmin on the raw J gives the unconstrained optimum for comparison.

The second stage zooms in around the best feasible cell twice, each time shrinking the search window by a factor of four. A candidate is accepted only if its premium respects the budget and it lowers $J$. This simple scheme is robust: it needs no gradients, handles the kinks that clipping creates in the objective, and cannot leave the feasible region.

3.6 Strategy comparison and plots

Four strategies are compared side by side: no insurance, a conventional mid-range policy ($d = 0.5$, $L = 10$), full cover ($d = 0.05$, $L = 30$) and the budget-constrained optimum. The figure uses a $2 \times 3$ layout: two 3D surfaces, one contour map, one scatter plot of the premium against residual risk, one exceedance-probability chart and one cost breakdown.

4. Console Output

====================================================================================================
Cyber insurance optimization: deductible d, limit L, premium
====================================================================================================
Scenario set: 40,000 years, 47,732 incidents
Expected annual loss without insurance : 1.843 M$
Grid evaluations: 900 in 2.84 s (total with refinement 4.26 s)
Premium budget: 1.80 M$ | Cash buffer: 8.0 M$ | CVaR level: 95% | rho = 0.50
----------------------------------------------------------------------------------------------------
Unconstrained optimum : d = 0.050, L = 30.00, premium = 3.451, J = 4.528
Budget-constrained opt: d = 1.860, L = 16.29, premium = 1.800, J = 5.947
----------------------------------------------------------------------------------------------------
Strategy               d      L  Premium  E[Ret] CVaR[Ret]  E[Cost]   VaR95  CVaR95  P(C>Buf)       J
No insurance        0.00   0.00    0.000   1.843    16.689    1.843   7.861  16.689    0.0486   9.266
Conventional        0.50  10.00    2.170   0.706     7.011    2.876   3.647   9.180    0.0129   6.028
Full cover          0.05  30.00    3.451   0.149     2.005    3.600   3.601   5.456    0.0030   4.528
Optimal (budget)    1.86  16.29    1.800   1.079     7.216    2.879   5.149   9.015    0.0081   5.947
----------------------------------------------------------------------------------------------------
Validation of the simulated expected payout against the closed-form lognormal formula
Conventional       simulated = 1.1369 M$ | analytic = 1.1407 M$ | relative gap = 0.33%
Full cover         simulated = 1.6942 M$ | analytic = 1.7018 M$ | relative gap = 0.44%
Optimal (budget)   simulated = 0.7645 M$ | analytic = 0.7691 M$ | relative gap = 0.60%
====================================================================================================

5. Result Image

6. Reading the Results

Without a budget, the optimizer buys everything

The unconstrained optimum sits in the corner of the search space: the smallest deductible and the largest limit, with a premium of about 3.45 M$. Because the objective gives half its weight to the tail, and the tail of a lognormal severity is so expensive, insuring almost everything always lowers $J$. A premium that large is nearly double the expected annual loss of 1.84 M$, which is why a real company needs a budget constraint. The cyan diamond in the top-left of panel (3) marks this unconstrained corner.

Panels (1) and (2): the 3D surfaces

Panel (1) shows $J(d, L)$ as a smooth landscape. It falls toward low deductibles and high limits, which is the direction of heavy insurance, and rises steeply toward high deductibles and low limits, where the company carries most of the tail itself. Panel (2) shows the premium surface in the opposite shape: the premium is highest at low $d$ and high $L$. The translucent cyan plane is the budget. Where the premium surface rises above the plane, the policy is unaffordable. The optimal policy sits exactly on the intersection of the two.

Panel (3): the contour map and the budget frontier

The white curve is the set of policies whose premium equals the budget. Everything to its lower-right is affordable, and everything to its upper-left is not. The red star is the best point along that curve: a deductible of about 1.86 M$ and a limit of about 16.3 M$. The curve slopes upward, which shows the trade-off the company faces. Accepting a higher deductible frees premium budget that can be spent on a larger limit. The optimizer finds the point along this curve where the next unit of budget stops buying more tail protection than it costs.

Panel (4): premium versus residual risk

Every grid point is a dot, colored by its deductible. The cloud forms a clear lower-left frontier: for a given premium, some $(d, L)$ combinations leave far less tail risk than others. Without insurance, the CVaR of retained loss is about 16.7 M$. The optimal policy brings it down to about 7.2 M$ for a premium of 1.8 M$, and it sits on the efficient frontier just left of the dashed budget line. Spending the same premium on a poorly structured policy, such as a low deductible with a small limit, would leave visibly more residual risk.

Panel (5): exceedance curves and financial impact

The vertical axis is logarithmic, so the gaps between curves are large in relative terms. The probability that the annual cost exceeds the 8 M$ cash buffer is about 4.9% with no insurance, 1.3% with the conventional policy, 0.8% with the optimal policy and 0.3% with full cover. The optimal policy therefore cuts the chance of breaching the buffer by roughly a factor of six compared with doing nothing. It is also better than the conventional policy even though it costs less. Notice the vertical drops at the left of each insured curve: they are the premium floors, the minimum cost the company pays in a year with no incident.

Panel (6): the cost breakdown

Insurance increases the expected cost, because the insurer loads the price. The expected annual cost is 1.84 M$ without insurance, but about 2.88 M$ for both the conventional and the optimal policies. What the extra cost buys is a smaller worst case: the CVaR of the total cost drops from about 16.7 M$ to about 9.0 M$ for the optimal policy, and to about 5.5 M$ for full cover. The optimal policy and the conventional policy cost the same on average, yet the optimal one has lower CVaR and a lower probability of breaching the buffer. The gain comes entirely from restructuring the policy: a higher deductible in exchange for a much larger limit.

Validation

The simulated expected payouts agree with the closed-form lognormal values to within about one percent for all three insured strategies. This confirms that the vectorized pipeline is consistent with the analytic model.

7. Conclusion

Cyber insurance is best seen as buying protection against the heavy tail, not against everyday incidents. In this example, the budget-constrained optimum accepts a deductible of about 1.9 M$ so that it can afford a limit of about 16 M$. That structure removed most of the extreme-loss exposure and cut the probability of a cash-buffer breach from about 5% to under 1%, at the same premium as a conventional policy that protected less. The framework here is easy to extend: replace the lognormal with a fitted severity distribution, add an annual aggregate limit or a coinsurance share, or price the policy with a market-quoted rate curve. The same two-stage search will still apply.

Minimum-Cost Regulatory Compliance

Solving the PCI DSS, GDPR, and FSA Guidelines Problem with Integer Programming

Every compliance team eventually faces the same uncomfortable question: what is the cheapest set of technologies, processes, and audit activities that still satisfies every mandatory requirement? Buying every tool on the market is safe but wasteful. Handling each regulation in a separate silo is organizationally convenient but pays for the same control several times.

In this article we turn the question into a concrete optimization problem, solve it exactly with mixed-integer linear programming, verify the answer by exhaustive search, and visualize the cost structure with a 2×3 panel of graphs, including two 3D plots.

1. The Example Problem

A payment-service company handles card data, serves EU customers, and is supervised by a Japanese financial regulator. It must therefore satisfy three regimes at once.

Requirements (12 in total, 4 per regime)

ID Regime Requirement
P1 PCI DSS Segmentation and firewall (Req. 1)
P2 PCI DSS Protect stored card data (Req. 3)
P3 PCI DSS Access control and MFA (Req. 7-8)
P4 PCI DSS Logging and monitoring (Req. 10)
G1 GDPR Records of processing (Art. 30)
G2 GDPR Security of processing (Art. 32)
G3 GDPR Breach notification (Art. 33)
G4 GDPR Data subject rights (Art. 15-17)
F1 FSA Governance and risk management
F2 FSA Access management
F3 FSA Monitoring and incident response
F4 FSA Outsourcing and audit

Candidate controls (14 in total): network segmentation, encryption and key management, tokenization, IAM with MFA, privileged access management, log management, SIEM with managed SOC, data inventory, DSR workflow automation, incident response retainer, governance and training, vendor risk management, GRC automation, and vulnerability management with penetration testing.

Each control $j$ has a three-year total cost of ownership

$$
c_j = K_j + T,(O_j + E_j), \qquad T = 3,
$$

where $K_j$ is the capital expenditure, $O_j$ the annual operating cost, and $E_j$ the annual audit-evidence effort. A control contributes a coverage weight $a_{ij}\in[0,1]$ to requirement $i$. One control can help several requirements, which is exactly why integrated planning beats silos.

Required coverage levels reflect a risk-based reading of each regime: $\theta_i = 1.0$ for PCI DSS, $0.8$ for GDPR, and $0.7$ for the FSA guidelines.

2. Mathematical Formulation

With a binary decision variable $x_j\in{0,1}$ that equals 1 when control $j$ is implemented, the problem is

$$
\min_{x}\ \sum_{j=1}^{n} c_j,x_j
$$

subject to

$$
\sum_{j=1}^{n} a_{ij},x_j ;\ge; \theta_i \qquad (i=1,\dots,m),
$$

$$
x_a ;\le; x_b \qquad \text{for each prerequisite pair } (a,b),
$$

$$
x_j \in {0,1}.
$$

The prerequisite constraints encode practical dependencies: privileged access management requires IAM, the SIEM requires log management, and DSR automation requires the data inventory.

This is a multi-constraint covering problem, which is NP-hard in general. With $n=14$ controls there are only $2^{14}=16{,}384$ candidate subsets, so we can also enumerate them all and confirm the solver’s answer.

For comparison we use three baselines:

  • Buy all: implement every control.
  • Siloed: solve each regime independently and add up the three costs, so shared controls are paid for repeatedly.
  • Greedy: repeatedly add the control (plus any missing prerequisite) with the best ratio of deficit reduction to cost, then prune redundant controls.

3. Complete Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import itertools
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # noqa: F401
from scipy.optimize import milp, LinearConstraint, Bounds

plt.style.use("dark_background")
np.set_printoptions(precision=3, suppress=True)

# ------------------------------------------------------------------
# 1. Problem data (costs in thousand USD, planning horizon T = 3 years)
# ------------------------------------------------------------------
T = 3

controls = [
# id, name, capex, opex, audit, category
("C1", "Network segmentation / NGFW", 90, 18, 6, "Technology"),
("C2", "Encryption & key management", 70, 14, 5, "Technology"),
("C3", "Tokenization service", 110, 30, 6, "Technology"),
("C4", "IAM with MFA", 60, 20, 5, "Technology"),
("C5", "Privileged access management", 85, 25, 6, "Technology"),
("C6", "Central log management", 50, 16, 4, "Technology"),
("C7", "SIEM + managed SOC", 120, 60, 8, "Technology"),
("C8", "Data inventory (RoPA) tool", 40, 12, 4, "Technology"),
("C9", "DSR workflow automation", 45, 15, 3, "Technology"),
("C10", "Incident response plan & retainer", 25, 20, 3, "Process"),
("C11", "Governance, policy & training", 30, 25, 5, "Process"),
("C12", "Vendor risk management program", 20, 18, 4, "Process"),
("C13", "GRC compliance automation", 55, 22, 2, "Process"),
("C14", "Vulnerability mgmt & pen testing", 35, 28, 4, "Process"),
]
cid = [c[0] for c in controls]
cname = [c[1] for c in controls]
capex = np.array([c[2] for c in controls], dtype=float)
opex = np.array([c[3] for c in controls], dtype=float)
audit = np.array([c[4] for c in controls], dtype=float)
category = [c[5] for c in controls]
cost = capex + T * opex + T * audit # total cost of ownership
n = len(controls)

requirements = [
("P1", "PCI DSS", "Segmentation & firewall (Req.1)"),
("P2", "PCI DSS", "Protect stored card data (Req.3)"),
("P3", "PCI DSS", "Access control & MFA (Req.7-8)"),
("P4", "PCI DSS", "Logging & monitoring (Req.10)"),
("G1", "GDPR", "Records of processing (Art.30)"),
("G2", "GDPR", "Security of processing (Art.32)"),
("G3", "GDPR", "Breach notification (Art.33)"),
("G4", "GDPR", "Data subject rights (Art.15-17)"),
("F1", "FSA", "Governance & risk management"),
("F2", "FSA", "Access management"),
("F3", "FSA", "Monitoring & incident response"),
("F4", "FSA", "Outsourcing & audit"),
]
rid = [r[0] for r in requirements]
rreg = np.array([r[1] for r in requirements])
m = len(requirements)

cover = {
"C1": {"P1": .8, "P2": .2, "G2": .2, "F3": .1},
"C2": {"P2": .6, "G2": .5, "F1": .1},
"C3": {"P2": .9, "G2": .3},
"C4": {"P3": .7, "G2": .2, "F2": .7},
"C5": {"P3": .4, "F2": .4, "P4": .1},
"C6": {"P4": .6, "F3": .3, "G3": .2},
"C7": {"P4": .5, "G3": .5, "F3": .6, "G2": .1},
"C8": {"G1": .8, "G4": .4, "F1": .1},
"C9": {"G4": .7, "G1": .2},
"C10": {"G3": .5, "F3": .4, "F1": .2},
"C11": {"F1": .6, "G1": .3, "G3": .2, "G4": .2, "F2": .1, "F4": .2, "P3": .1, "G2": .1},
"C12": {"F4": .6, "F1": .2, "G1": .1},
"C13": {"F1": .3, "F4": .4, "P4": .1, "G1": .2, "G4": .1, "P1": .1},
"C14": {"P1": .3, "P2": .1, "F3": .2, "G2": .2, "P4": .1},
}
A = np.zeros((m, n))
for j, c in enumerate(cid):
for r, w in cover[c].items():
A[rid.index(r), j] = w

# prerequisite pairs (a, b): control a can only be used if control b is installed
prereq = [(cid.index("C5"), cid.index("C4")),
(cid.index("C7"), cid.index("C6")),
(cid.index("C9"), cid.index("C8"))]

# ------------------------------------------------------------------
# 2. Exact solver (MILP) and a greedy heuristic
# ------------------------------------------------------------------
def dep_matrix(pairs, size):
D = np.zeros((len(pairs), size))
for k, (a, b) in enumerate(pairs):
D[k, a] = 1.0
D[k, b] = -1.0
return D

D = dep_matrix(prereq, n)

def solve_milp(thr, rows=None):
"""min c^T x s.t. A x >= thr (selected rows), x_a <= x_b, x binary."""
if rows is None:
rows = np.arange(m)
cons = [LinearConstraint(A[rows], lb=np.asarray(thr)[rows], ub=np.inf),
LinearConstraint(D, lb=-np.inf, ub=0.0)]
res = milp(c=cost, constraints=cons, integrality=np.ones(n),
bounds=Bounds(0, 1))
if res.status != 0 or res.x is None:
return None, np.nan
x = np.round(res.x).astype(int)
return x, float(cost @ x)

def solve_greedy(thr):
x = np.zeros(n, dtype=int)
def deficit(xv):
return np.maximum(thr - A @ xv, 0.0)
while deficit(x).sum() > 1e-9:
best, best_ratio = None, 0.0
base_def = deficit(x)
for j in range(n):
if x[j] == 1:
continue
trial = x.copy()
trial[j] = 1
for a, b in prereq:
if trial[a] == 1:
trial[b] = 1
add_cost = float(cost @ (trial - x))
gain = float(base_def.sum() - deficit(trial).sum())
if gain > 1e-12 and gain / add_cost > best_ratio:
best, best_ratio = trial, gain / add_cost
if best is None:
return None, np.nan
x = best
# pruning pass: drop redundant (and expensive) controls while staying feasible
for j in np.argsort(-cost):
if x[j] == 0:
continue
if any(b == j and x[a] == 1 for a, b in prereq):
continue
trial = x.copy()
trial[j] = 0
if deficit(trial).sum() <= 1e-9:
x = trial
return x, float(cost @ x)

# ------------------------------------------------------------------
# 3. Baseline problem: required coverage levels PCI DSS 1.0 / GDPR 0.8 / FSA 0.7
# ------------------------------------------------------------------
theta0 = np.where(rreg == "PCI DSS", 1.0, np.where(rreg == "GDPR", 0.8, 0.7))
x_opt, c_opt = solve_milp(theta0)
x_gr, c_gr = solve_greedy(theta0)

# exhaustive check over all 2^n subsets (vectorised)
subsets = np.array(list(itertools.product([0, 1], repeat=n)), dtype=float)
feasible = np.all(subsets @ A.T >= theta0 - 1e-9, axis=1)
for a, b in prereq:
feasible &= subsets[:, a] <= subsets[:, b]
brute_costs = np.where(feasible, subsets @ cost, np.inf)
c_brute = float(brute_costs.min())

# silo strategy: each regulation is implemented independently, shared controls are paid for repeatedly
silo_cost = 0.0
for reg in ["PCI DSS", "GDPR", "FSA"]:
rows = np.where(rreg == reg)[0]
_, cs = solve_milp(theta0, rows)
silo_cost += cs
c_all = float(cost.sum())

# ------------------------------------------------------------------
# 4. Console report
# ------------------------------------------------------------------
table = pd.DataFrame({
"ID": cid, "Control": cname, "Category": category,
"Capex": capex, "Opex/yr": opex, "Audit/yr": audit,
"TCO": cost, "Selected": np.where(x_opt == 1, "YES", "-"),
})
print("=== Control catalogue and optimal selection (thousand USD) ===")
print(table.to_string(index=False))
print()
cov = A @ x_opt
rep = pd.DataFrame({
"Req": rid, "Regulation": rreg,
"Description": [r[2] for r in requirements],
"Coverage": np.round(cov, 2), "Required": theta0,
})
print("=== Achieved coverage per requirement ===")
print(rep.to_string(index=False))
print()
print(f"Optimal (MILP) : {c_opt:8.1f} -> {[cid[j] for j in range(n) if x_opt[j]]}")
print(f"Exhaustive search (2^{n}) : {c_brute:8.1f}")
print(f"Greedy heuristic : {c_gr:8.1f}")
print(f"Siloed implementation : {silo_cost:8.1f}")
print(f"Buy every control : {c_all:8.1f}")
print(f"Saving vs. silo : {100 * (1 - c_opt / silo_cost):6.1f} %")
print(f"Saving vs. all controls : {100 * (1 - c_opt / c_all):6.1f} %")

# ------------------------------------------------------------------
# 5. Sensitivity data for the graphs
# ------------------------------------------------------------------
levels = np.linspace(0.5, 1.1, 7)
surf = np.zeros((len(levels), len(levels)))
for i, tp in enumerate(levels): # PCI DSS strictness
for k, tg in enumerate(levels): # GDPR strictness
thr = np.where(rreg == "PCI DSS", tp, np.where(rreg == "GDPR", tg, 0.7))
surf[i, k] = solve_milp(thr)[1]

theta_line = np.linspace(0.4, 1.2, 17)
line_opt = np.array([solve_milp(np.full(m, t))[1] for t in theta_line])
line_gr = np.array([solve_greedy(np.full(m, t))[1] for t in theta_line])

# ------------------------------------------------------------------
# 6. Graphs (2 rows x 3 columns in one figure)
# ------------------------------------------------------------------
fig = plt.figure(figsize=(26, 14))
fig.suptitle("Minimum-Cost Regulatory Compliance (PCI DSS / GDPR / FSA Guidelines)",
fontsize=20, fontweight="bold")

# (1) cost breakdown of selected controls
ax1 = fig.add_subplot(2, 3, 1)
sel = np.where(x_opt == 1)[0]
labels = [cid[j] for j in sel]
b1 = capex[sel]
b2 = T * opex[sel]
b3 = T * audit[sel]
ax1.bar(labels, b1, color="#4cc9f0", label="Capex")
ax1.bar(labels, b2, bottom=b1, color="#f72585", label="Opex (3 yrs)")
ax1.bar(labels, b3, bottom=b1 + b2, color="#ffd166", label="Audit effort (3 yrs)")
ax1.set_title(f"(1) Cost breakdown of selected controls (total {c_opt:.0f})")
ax1.set_ylabel("Thousand USD")
ax1.legend()
ax1.grid(alpha=0.2)

# (2) coverage contribution heatmap
ax2 = fig.add_subplot(2, 3, 2)
contrib = A * x_opt[None, :]
im = ax2.imshow(contrib, cmap="viridis", aspect="auto", vmin=0, vmax=1)
ax2.set_xticks(range(n))
ax2.set_xticklabels(cid, rotation=90)
ax2.set_yticks(range(m))
ax2.set_yticklabels(rid)
for i in range(m):
for j in range(n):
if contrib[i, j] > 0:
ax2.text(j, i, f"{contrib[i, j]:.1f}", ha="center", va="center",
color="white", fontsize=8)
ax2.set_title("(2) Coverage contributed by selected controls")
fig.colorbar(im, ax=ax2, fraction=0.046, pad=0.04)

# (3) 3D surface: optimal cost vs strictness levels
ax3 = fig.add_subplot(2, 3, 3, projection="3d")
GX, GY = np.meshgrid(levels, levels, indexing="ij")
surf_plot = ax3.plot_surface(GX, GY, surf, cmap="plasma", edgecolor="none", alpha=0.95)
ax3.set_xlabel("PCI DSS level")
ax3.set_ylabel("GDPR level")
ax3.set_zlabel("Min cost")
ax3.set_title("(3) Optimal cost surface (FSA level = 0.7)")
ax3.view_init(elev=26, azim=-130)
fig.colorbar(surf_plot, ax=ax3, shrink=0.55, pad=0.08)

# (4) strategy comparison
ax4 = fig.add_subplot(2, 3, 4)
names4 = ["Buy all", "Siloed", "Greedy", "Optimal"]
vals4 = [c_all, silo_cost, c_gr, c_opt]
bars = ax4.bar(names4, vals4, color=["#6c757d", "#ef476f", "#ffd166", "#06d6a0"])
for bar, v in zip(bars, vals4):
ax4.text(bar.get_x() + bar.get_width() / 2, v + 8, f"{v:.0f}",
ha="center", fontsize=11)
ax4.set_title("(4) Strategy comparison (total cost)")
ax4.set_ylabel("Thousand USD")
ax4.grid(alpha=0.2, axis="y")

# (5) cost vs uniform coverage level
ax5 = fig.add_subplot(2, 3, 5)
ax5.plot(theta_line, line_opt, "o-", color="#06d6a0", lw=2, label="Optimal (MILP)")
ax5.plot(theta_line, line_gr, "s--", color="#ffd166", lw=2, label="Greedy")
ax5.axhline(c_all, color="#6c757d", ls=":", label="Buy all controls")
ax5.set_xlabel("Required coverage level (all requirements)")
ax5.set_ylabel("Thousand USD")
ax5.set_title("(5) Cost of raising the compliance level")
ax5.legend()
ax5.grid(alpha=0.2)

# (6) 3D scatter of control efficiency
ax6 = fig.add_subplot(2, 3, 6, projection="3d")
total_cov = A.sum(axis=0)
eff = total_cov / cost * 100
colors6 = np.where(x_opt == 1, "#06d6a0", "#ef476f")
ax6.scatter(cost, total_cov, eff, c=colors6, s=90, depthshade=True)
for j in range(n):
ax6.text(cost[j], total_cov[j], eff[j], cid[j], fontsize=8)
ax6.set_xlabel("TCO")
ax6.set_ylabel("Total coverage weight")
ax6.set_zlabel("Coverage per 100k")
ax6.set_title("(6) Control efficiency (green = selected)")
ax6.view_init(elev=24, azim=-55)

plt.subplots_adjust(left=0.04, right=0.97, top=0.92, bottom=0.07, wspace=0.28, hspace=0.30)
plt.show()

4. Code Walkthrough

Section 1: Problem data

The catalogue stores capital expenditure, annual operating cost, and annual audit effort for each control. The line cost = capex + T * opex + T * audit implements

$$
c_j = K_j + T,(O_j + E_j)
$$

so that audit-evidence work is priced in rather than ignored, which is a common blind spot when teams compare tools only by license fee.

The sparse dictionary cover lists, for each control, which requirements it helps and by how much. It is converted into the dense matrix $A=(a_{ij})\in\mathbb{R}^{12\times 14}$. Tokenization (C3), for example, contributes $0.9$ to P2 and $0.3$ to G2, while governance and training (C11) contributes small amounts to eight different requirements. This second pattern is typical of process controls: individually weak, collectively broad.

The list prereq stores index pairs $(a,b)$ meaning $x_a\le x_b$.

Section 2: Solvers

dep_matrix builds the matrix $D$ in which each row has $+1$ at column $a$ and $-1$ at column $b$. The constraint $Dx\le 0$ is then exactly the family of prerequisite inequalities $x_a-x_b\le 0$.

solve_milp calls scipy.optimize.milp, which uses the HiGHS branch-and-cut solver. The coverage constraints are passed as LinearConstraint(A[rows], lb=thr, ub=inf), the prerequisites as a second constraint block, and integrality is enforced by setting integrality=np.ones(n) together with bounds $[0,1]$. The rows argument lets us optimize a subset of requirements, which we need for the siloed baseline. The function returns (None, nan) if the model is infeasible, so a request for an unattainable level cannot crash the later plotting code.

solve_greedy is a classic cost-effectiveness heuristic. At each step it evaluates adding each missing control together with its prerequisites, measures the reduction of the total coverage deficit $\sum_i \max(\theta_i-(Ax)_i,0)$, and picks the best gain-per-cost ratio. A final pruning pass removes expensive controls that became redundant. Greedy is fast and intuitive, but it carries no optimality guarantee.

Section 3: Baseline and verification

The vector theta0 encodes $\theta=(1.0,,0.8,,0.7)$ for the three regimes. Three independent computations follow:

  1. MILP optimum c_opt.
  2. Exhaustive search: itertools.product([0,1], repeat=n) creates all $2^{14}$ subsets as a matrix. A single matrix product subsets @ A.T evaluates every coverage vector at once, boolean masks apply the prerequisite constraints, and np.where assigns infinite cost to infeasible subsets. This vectorized check takes a fraction of a second, so it is the fastest and most transparent way to validate the solver at this scale.
  3. Siloed cost: each regime is solved alone and the three optima are summed, which models three teams buying overlapping controls independently.

For much larger catalogues, exhaustive search becomes impossible ($2^{n}$ growth), but the MILP formulation scales to hundreds of controls with the same code.

Section 4: Console report

Two tables list the catalogue with the optimal selection and the coverage achieved per requirement next to the required level. The summary lines compare all strategies and print the percentage savings.

Section 5: Sensitivity data

Two sweeps feed the graphs. The 7×7 grid solves 49 MILPs while the PCI DSS level and the GDPR level vary independently from $0.5$ to $1.1$ (FSA fixed at $0.7$), producing the cost surface. The line sweep solves 17 problems at a uniform level from $0.4$ to $1.2$ for both the exact and the greedy method. The upper limit $1.2$ is deliberate: it is the largest level every requirement can still reach with the full catalogue, so every problem in the sweep is feasible.

Section 6: Graphs

All six panels are drawn into one figure with two rows and three columns. Panels 3 and 6 use projection="3d", and plt.subplots_adjust fixes the margins so the colorbars and 3D labels do not collide.

5. Execution Results

=== Control catalogue and optimal selection (thousand USD) ===
 ID                           Control   Category  Capex  Opex/yr  Audit/yr   TCO Selected
 C1       Network segmentation / NGFW Technology   90.0     18.0       6.0 162.0      YES
 C2       Encryption & key management Technology   70.0     14.0       5.0 127.0        -
 C3              Tokenization service Technology  110.0     30.0       6.0 218.0      YES
 C4                      IAM with MFA Technology   60.0     20.0       5.0 135.0      YES
 C5      Privileged access management Technology   85.0     25.0       6.0 178.0      YES
 C6            Central log management Technology   50.0     16.0       4.0 110.0      YES
 C7                SIEM + managed SOC Technology  120.0     60.0       8.0 324.0      YES
 C8        Data inventory (RoPA) tool Technology   40.0     12.0       4.0  88.0      YES
 C9           DSR workflow automation Technology   45.0     15.0       3.0  99.0      YES
C10 Incident response plan & retainer    Process   25.0     20.0       3.0  94.0        -
C11     Governance, policy & training    Process   30.0     25.0       5.0 120.0      YES
C12    Vendor risk management program    Process   20.0     18.0       4.0  86.0      YES
C13         GRC compliance automation    Process   55.0     22.0       2.0 127.0        -
C14  Vulnerability mgmt & pen testing    Process   35.0     28.0       4.0 131.0      YES

=== Achieved coverage per requirement ===
Req Regulation                      Description  Coverage  Required
 P1    PCI DSS  Segmentation & firewall (Req.1)       1.1       1.0
 P2    PCI DSS Protect stored card data (Req.3)       1.2       1.0
 P3    PCI DSS   Access control & MFA (Req.7-8)       1.2       1.0
 P4    PCI DSS    Logging & monitoring (Req.10)       1.3       1.0
 G1       GDPR   Records of processing (Art.30)       1.4       0.8
 G2       GDPR  Security of processing (Art.32)       1.1       0.8
 G3       GDPR     Breach notification (Art.33)       0.9       0.8
 G4       GDPR  Data subject rights (Art.15-17)       1.3       0.8
 F1        FSA     Governance & risk management       0.9       0.7
 F2        FSA                Access management       1.2       0.7
 F3        FSA   Monitoring & incident response       1.2       0.7
 F4        FSA              Outsourcing & audit       0.8       0.7

Optimal (MILP)            :   1651.0  -> ['C1', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'C11', 'C12', 'C14']
Exhaustive search (2^14) :   1651.0
Greedy heuristic          :   1651.0
Siloed implementation     :   2572.0
Buy every control         :   1999.0
Saving vs. silo           :   35.8 %
Saving vs. all controls   :   17.4 %

6. Reading the Results

Optimal portfolio

The exact solver selects eleven of the fourteen controls: C1, C3, C4, C5, C6, C7, C8, C9, C11, C12, and C14, with a total three-year cost of 1,651 thousand USD. Exhaustive enumeration of all 16,384 subsets returns the same value, which confirms that the MILP result is a true global optimum rather than a local one.

Three controls are left out, and each omission teaches something:

  • Encryption and key management (C2) is dropped because tokenization (C3) already delivers $0.9$ on stored-card-data protection and $0.3$ on security of processing, while C2 would add cost for overlapping coverage.
  • GRC automation (C13) is dropped because governance and training (C11) and vendor risk management (C12) already cover the FSA governance and outsourcing requirements at the required $0.7$.
  • Incident response retainer (C10) is dropped because the managed SOC (C7) already contributes to breach notification and monitoring.

Panel (1): cost breakdown

The stacked bars show where money goes. The SIEM with managed SOC (C7) is by far the most expensive item, and most of that cost is recurring operating expense rather than up-front capital. Process controls such as C11 and C12 have small capex but a noticeable operating share. The lesson is that comparing tools by purchase price alone understates the true cost of the recurring, labor-heavy controls.

Panel (2): coverage heatmap

Each cell shows how much a selected control contributes to a requirement. Rows with several bright cells, for example G2 (security of processing) or F3 (monitoring and incident response), are satisfied through combinations of controls. The column for C11 shows many faint cells spread across the matrix, which visualizes why a broad governance program is cheap insurance across all three regimes. Empty columns (C2, C10, C13) are exactly the controls the optimizer rejected.

Panel (3): 3D cost surface

The surface shows the minimum cost as the PCI DSS level (one horizontal axis) and the GDPR level (the other) vary, with the FSA level fixed. The surface rises in discrete terraces rather than smoothly, because controls are indivisible: raising a requirement slightly above a threshold can force an entire additional tool to be purchased, producing a jump. The cheapest corner (both levels at $0.5$) is far lower than the most demanding corner, and the slope along the PCI DSS axis is steeper in the middle range, which shows that the strictest card-data requirements are the main cost driver.

Panel (4): strategy comparison

The siloed approach costs 2,572 thousand USD, even more than simply buying everything (1,999), because three independent plans each purchase the shared controls again. The integrated optimum of 1,651 saves about 35.8% against the silo plan and about 17.4% against buying every control. The greedy heuristic, followed by pruning, also reaches 1,651 on this instance, so it is a strong practical fallback, although only the exact solver can prove it.

Panel (5): cost of raising the compliance level

Cost as a function of a uniform required level is a staircase. It stays low for relaxed targets, climbs steeply between roughly $0.6$ and $0.95$, and flattens at the cost of the full catalogue once the level approaches the maximum attainable $1.2$. The greedy curve tracks the optimal one closely but sits slightly above it at several levels, which shows the small but real gap that exact optimization closes. The plot is also a negotiation tool: it tells management precisely what each additional increment of assurance costs.

Panel (6): 3D efficiency scatter

Each point is a control, positioned by its total cost, its total coverage weight, and its coverage per 100 thousand USD. Green points are selected and red points are rejected. High, left-hand points (cheap and broad) such as governance, vendor risk, and data inventory are selected. The rejected controls sit lower on the efficiency axis. Note that efficiency alone does not decide the selection: some expensive, narrowly focused controls such as the SIEM remain in the optimal set because they are the only way to reach specific requirements, while the prerequisite structure forces cheap foundations like log management into the plan.

7. Conclusion

Treating compliance as a covering problem reveals three practical facts. First, overlap between regulations is the main source of savings, which is why a single integrated plan beat three siloed plans by more than a third. Second, indivisible controls make the cost curve a staircase, so small changes in required assurance can trigger large jumps in spending. Third, exact optimization is cheap at this scale: an MILP solver and a 16,384-subset enumeration agree instantly, and the same model extends to realistic catalogues with extra constraints such as budgets per year, vendor lock-in limits, or risk-weighted requirements.

Tuning Biometric and Behavioral Authentication

Balancing FRR and FAR for Your Business

Every authentication system faces the same trade-off. Raise the threshold and you block more impostors, but you also lock out more legitimate users. Lower it and users are happy, but attackers slip through. The right balance depends on what a wrong decision costs your business.

In this article we simulate keystroke-dynamics authentication, train three candidate models, and choose a different operating threshold for each of three business scenarios.

1. Problem Setting

For a decision threshold $t$ on the authentication score $s$ (higher means more likely genuine), the two error rates are:

$$
\mathrm{FRR}(t) = \frac{\left|{ s_g < t }\right|}{N_g}, \qquad
\mathrm{FAR}(t) = \frac{\left|{ s_i \ge t }\right|}{N_i}
$$

Here $s_g$ are genuine scores and $s_i$ are impostor scores. The Equal Error Rate (EER) is the point where the two curves cross:

$$
t_{\mathrm{EER}} = \arg\min_t \left| \mathrm{FAR}(t) - \mathrm{FRR}(t) \right|
$$

The EER is a useful benchmark, but a business does not care about equal errors. It cares about expected cost per login attempt. If a fraction $\pi$ of attempts are impostor attempts, then:

The optimal threshold is:

We use $\pi = 0.01$ and three scenarios:

Scenario $C_{\mathrm{FAR}}$ $C_{\mathrm{FRR}}$
Online banking 2000 5
Corporate VPN 300 10
Smartphone unlock 60 20

Thresholds are chosen on a validation set and evaluated on a separate test set, with impostor users split so that no impostor appears in more than one set.

2. Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # noqa: F401
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline

rng = np.random.default_rng(42)

# ------------------------------------------------------------------
# 1. Synthetic keystroke-dynamics data
# ------------------------------------------------------------------
D = 12 # number of timing features
SIGMA_WITHIN = 0.70 # day-to-day variability of one person
SIGMA_BETWEEN = 1.30 # spread of typing styles across people
mix = rng.normal(size=(D, D)) / np.sqrt(D) + np.eye(D) # feature correlation

def sample_person(mean, n):
noise = rng.normal(scale=SIGMA_WITHIN, size=(n, D)) @ mix
return mean + noise

def sample_impostors(n_users, n_each):
means = rng.normal(scale=SIGMA_BETWEEN, size=(n_users, D))
return np.vstack([sample_person(m, n_each) for m in means])

target_mean = np.zeros(D)
X_g_train = sample_person(target_mean, 200)
X_g_val = sample_person(target_mean, 1000)
X_g_test = sample_person(target_mean, 2000)
X_i_train = sample_impostors(200, 5)
X_i_val = sample_impostors(100, 20)
X_i_test = sample_impostors(100, 20)

X_train = np.vstack([X_g_train, X_i_train])
y_train = np.r_[np.ones(len(X_g_train)), np.zeros(len(X_i_train))]

# ------------------------------------------------------------------
# 2. Candidate models (score in [0, 1], higher = more likely genuine)
# ------------------------------------------------------------------
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))

models = {
"Quadratic Discriminant": make_pipeline(
StandardScaler(), QuadraticDiscriminantAnalysis(reg_param=0.1, priors=[0.5, 0.5])),
"Random Forest": RandomForestClassifier(
n_estimators=200, min_samples_leaf=3, class_weight="balanced",
random_state=0, n_jobs=-1),
"SVM (RBF)": make_pipeline(
StandardScaler(), SVC(C=3.0, gamma="scale", class_weight="balanced")),
}

def score(model, X):
if hasattr(model, "predict_proba"):
return model.predict_proba(X)[:, 1]
return sigmoid(model.decision_function(X))

# ------------------------------------------------------------------
# 3. FAR / FRR as vectorised functions of the threshold
# ------------------------------------------------------------------
thresholds = np.linspace(0.0, 1.0, 1001)

def far_frr(gen, imp, thr=thresholds):
gen_s, imp_s = np.sort(gen), np.sort(imp)
frr = np.searchsorted(gen_s, thr, side="left") / len(gen_s) # genuine rejected
far = 1.0 - np.searchsorted(imp_s, thr, side="left") / len(imp_s) # impostor accepted
return far, frr

def eer_point(far, frr, thr=thresholds):
i = np.argmin(np.abs(far - frr))
return thr[i], (far[i] + frr[i]) / 2.0

scores = {}
rows = []
for name, mdl in models.items():
mdl.fit(X_train, y_train)
s = {k: score(mdl, X) for k, X in [("g_val", X_g_val), ("i_val", X_i_val),
("g_test", X_g_test), ("i_test", X_i_test)]}
scores[name] = s
fa_v, fr_v = far_frr(s["g_val"], s["i_val"])
fa_t, fr_t = far_frr(s["g_test"], s["i_test"])
t_eer, e_val = eer_point(fa_v, fr_v)
j = np.argmin(np.abs(thresholds - t_eer))
e_test = (fa_t[j] + fr_t[j]) / 2.0
rows.append([name, t_eer, 100 * e_val, 100 * e_test])

model_table = pd.DataFrame(rows, columns=["Model", "EER threshold", "EER val (%)", "EER test (%)"])
print("=== Model comparison (equal error rate) ===")
print(model_table.round(3).to_string(index=False))

best_name = model_table.loc[model_table["EER val (%)"].idxmin(), "Model"]
S = scores[best_name]
print(f"\nSelected model: {best_name}")

# ------------------------------------------------------------------
# 4. Business-driven threshold optimisation
# Expected cost per login attempt:
# E[C] = C_FRR * (1 - pi) * FRR(t) + C_FAR * pi * FAR(t)
# ------------------------------------------------------------------
PI = 0.01 # share of attempts that are impostor attempts

scenarios = {
"Online banking": dict(c_far=2000.0, c_frr=5.0),
"Corporate VPN": dict(c_far=300.0, c_frr=10.0),
"Smartphone unlock": dict(c_far=60.0, c_frr=20.0),
}

def expected_cost(far, frr, c_far, c_frr, pi=PI):
return c_frr * (1.0 - pi) * frr + c_far * pi * far

far_v, frr_v = far_frr(S["g_val"], S["i_val"])
far_t, frr_t = far_frr(S["g_test"], S["i_test"])
t_eer, _ = eer_point(far_v, frr_v)
k_eer = int(np.argmin(np.abs(thresholds - t_eer)))

result_rows = []
opt_idx = {}
for sc, p in scenarios.items():
cost_v = expected_cost(far_v, frr_v, p["c_far"], p["c_frr"])
k = int(np.argmin(cost_v))
opt_idx[sc] = k
c_opt = expected_cost(far_t[k], frr_t[k], p["c_far"], p["c_frr"])
c_eer = expected_cost(far_t[k_eer], frr_t[k_eer], p["c_far"], p["c_frr"])
result_rows.append([sc, p["c_far"], p["c_frr"], thresholds[k],
100 * far_t[k], 100 * frr_t[k], c_eer, c_opt,
100 * (c_eer - c_opt) / c_eer])

result_table = pd.DataFrame(result_rows, columns=[
"Scenario", "C_FAR", "C_FRR", "Opt. threshold", "FAR test (%)", "FRR test (%)",
"Cost @EER thr.", "Cost @Opt thr.", "Cost reduction (%)"])
print("\n=== Optimal operating point per business scenario (test data) ===")
print(result_table.round(3).to_string(index=False))

# ------------------------------------------------------------------
# 5. Visualisation: 2 rows x 3 columns
# ------------------------------------------------------------------
colors = {"Online banking": "tab:red", "Corporate VPN": "tab:orange", "Smartphone unlock": "tab:green"}
fig = plt.figure(figsize=(22, 12))

# (1) Score distributions
ax1 = fig.add_subplot(2, 3, 1)
bins = np.linspace(0, 1, 41)
ax1.hist(S["g_test"], bins=bins, alpha=0.6, color="tab:blue", label="Genuine", density=True)
ax1.hist(S["i_test"], bins=bins, alpha=0.6, color="tab:gray", label="Impostor", density=True)
for sc, k in opt_idx.items():
ax1.axvline(thresholds[k], color=colors[sc], lw=2, ls="--", label=f"{sc} (t={thresholds[k]:.2f})")
ax1.set_title(f"Score distributions ({best_name})")
ax1.set_xlabel("Authentication score")
ax1.set_ylabel("Density")
ax1.legend(fontsize=8)

# (2) FAR / FRR curves
ax2 = fig.add_subplot(2, 3, 2)
ax2.plot(thresholds, 100 * far_t, color="tab:red", label="FAR")
ax2.plot(thresholds, 100 * frr_t, color="tab:blue", label="FRR")
e_thr, e_val = eer_point(far_t, frr_t)
ax2.scatter([e_thr], [100 * e_val], color="black", zorder=5, label=f"EER = {100 * e_val:.2f}%")
ax2.set_title("FAR and FRR versus threshold")
ax2.set_xlabel("Threshold")
ax2.set_ylabel("Error rate (%)")
ax2.grid(alpha=0.3)
ax2.legend()

# (3) DET-style curves for all models
ax3 = fig.add_subplot(2, 3, 3)
floor = 5e-4
for name in models:
fa, fr = far_frr(scores[name]["g_test"], scores[name]["i_test"])
ax3.plot(np.clip(fa, floor, 1), np.clip(fr, floor, 1), label=name, lw=2)
ax3.plot([floor, 1], [floor, 1], "k:", label="FAR = FRR")
for sc, k in opt_idx.items():
ax3.scatter(max(far_t[k], floor), max(frr_t[k], floor), s=90, color=colors[sc],
edgecolor="black", zorder=5, label=f"Optimum: {sc}")
ax3.set_xscale("log")
ax3.set_yscale("log")
ax3.set_title("DET-style curves (log-log)")
ax3.set_xlabel("FAR")
ax3.set_ylabel("FRR")
ax3.grid(alpha=0.3, which="both")
ax3.legend(fontsize=8)

# (4) Expected cost per scenario
ax4 = fig.add_subplot(2, 3, 4)
for sc, p in scenarios.items():
c = expected_cost(far_v, frr_v, p["c_far"], p["c_frr"])
c = c / c.max()
ax4.plot(thresholds, c, color=colors[sc], lw=2, label=sc)
k = opt_idx[sc]
ax4.scatter(thresholds[k], c[k], color=colors[sc], edgecolor="black", s=90, zorder=5)
ax4.set_title("Normalised expected cost versus threshold")
ax4.set_xlabel("Threshold")
ax4.set_ylabel("Cost (normalised)")
ax4.grid(alpha=0.3)
ax4.legend()

# (5) 3D surface: cost over threshold and cost ratio
ax5 = fig.add_subplot(2, 3, 5, projection="3d")
log_r = np.linspace(0, 3, 40) # log10(C_FAR / C_FRR)
ratios = 10 ** log_r
thr_sub = thresholds[::10]
far_sub, frr_sub = far_v[::10], frr_v[::10]
T, LR = np.meshgrid(thr_sub, log_r)
R = 10 ** LR
Z = (1 - PI) * frr_sub[None, :] + PI * R * far_sub[None, :]
Z = np.log10(Z + 1e-6)
ax5.plot_surface(T, LR, Z, cmap="viridis", alpha=0.85, linewidth=0, antialiased=True)
cost_grid = (1 - PI) * frr_v[None, :] + PI * ratios[:, None] * far_v[None, :]
best_k = np.argmin(cost_grid, axis=1)
ax5.plot(thresholds[best_k], log_r, np.log10(cost_grid[np.arange(len(log_r)), best_k] + 1e-6),
color="red", lw=3, label="Optimal threshold path")
ax5.set_title("Expected cost surface")
ax5.set_xlabel("Threshold")
ax5.set_ylabel("log10(C_FAR / C_FRR)")
ax5.set_zlabel("log10(cost)")
ax5.view_init(elev=28, azim=-125)
ax5.legend()

# (6) 3D trajectory: FAR, FRR and threshold
ax6 = fig.add_subplot(2, 3, 6, projection="3d")
ax6.plot(100 * far_t, 100 * frr_t, thresholds, color="tab:purple", lw=2.5)
for sc, k in opt_idx.items():
ax6.scatter(100 * far_t[k], 100 * frr_t[k], thresholds[k], s=90, color=colors[sc],
edgecolor="black", label=sc, depthshade=False)
ax6.set_title("Operating trajectory in (FAR, FRR, threshold)")
ax6.set_xlabel("FAR (%)")
ax6.set_ylabel("FRR (%)")
ax6.set_zlabel("Threshold")
ax6.view_init(elev=22, azim=-60)
ax6.legend(fontsize=8)

plt.tight_layout()
plt.show()

3. Code Walkthrough

Synthetic data

Each person has a mean typing profile in a 12-dimensional space (think dwell times and flight times between keys). A single user’s samples scatter around their own mean with standard deviation SIGMA_WITHIN, while different people’s means are spread more widely with SIGMA_BETWEEN. The random matrix mix correlates the features, as real timing features are correlated.

The target user’s genuine samples come from the origin. Impostor samples come from many other users. Training, validation, and test sets use different impostor users, so the model never sees a test impostor during training or threshold selection.

Candidate models

We compare three classifiers, all mapped to a score in $[0,1]$. Quadratic Discriminant Analysis suits Gaussian-like behavior, the Random Forest is a flexible baseline, and the RBF SVM is a non-linear margin classifier. The SVM’s raw decision value is passed through a sigmoid so that all models share the same threshold axis.

Fast FAR and FRR computation

The far_frr function is the performance-critical part. A naive implementation would compare every score against every one of the 1001 thresholds, costing $O(N \cdot T)$. Instead we sort the scores once and use np.searchsorted, which gives the count of scores below each threshold in $O(T \log N)$:

$$
\mathrm{FRR}(t) = \frac{\operatorname{rank}_g(t)}{N_g}, \qquad
\mathrm{FAR}(t) = 1 - \frac{\operatorname{rank}_i(t)}{N_i}
$$

The entire script runs in a few seconds, so no further acceleration is needed.

Model selection and threshold optimization

Models are ranked by validation EER. Then, for each business scenario, the expected cost curve is computed on the validation set and its minimum gives the threshold $t^{*}$. We report FAR, FRR, and cost on the untouched test set. As a baseline, we also compute the cost if we had simply used the EER threshold everywhere.

Plots

The figure has two rows and three columns. Panels 5 and 6 are 3D. Panel 5 shows the log expected cost as a surface over the threshold and the cost ratio, with the optimal threshold path drawn in red. Panel 6 shows the full operating trajectory in (FAR, FRR, threshold) space, with each scenario’s optimum marked.

4. Execution Results

Graphs

Console Output

=== Model comparison (equal error rate) ===
                 Model  EER threshold  EER val (%)  EER test (%)
Quadratic Discriminant          0.805        3.300         3.450
         Random Forest          0.281       11.800        11.450
             SVM (RBF)          0.497        5.425         5.725

Selected model: Quadratic Discriminant

=== Optimal operating point per business scenario (test data) ===
         Scenario  C_FAR  C_FRR  Opt. threshold  FAR test (%)  FRR test (%)  Cost @EER thr.  Cost @Opt thr.  Cost reduction (%)
   Online banking 2000.0    5.0           0.874          3.00          5.05           1.019           0.850              16.571
    Corporate VPN  300.0   10.0           0.653          7.30          0.65           0.373           0.283              23.953
Smartphone unlock   60.0   20.0           0.224         15.05          0.05           0.502           0.100              80.048

5. Reading the Results

Model comparison

The Quadratic Discriminant model reached a test EER of about 3.5%, the RBF SVM about 5.7%, and the Random Forest about 11.9%. This makes sense for the data: the genuine class is a compact Gaussian cloud surrounded by impostors, a shape that a quadratic boundary captures almost perfectly. The Random Forest has to approximate that curved boundary with axis-aligned splits and pays for it in accuracy. Model choice matters, but as we see next, threshold choice matters just as much.

Panels 1 and 2: distributions and error curves

The score histogram shows two well-separated groups, genuine scores piled up near 1 and impostor scores near 0, with a thin overlap in between. The FAR curve falls and the FRR curve rises as the threshold increases, crossing at an EER of roughly 3.7% on the test set. That crossing is the point where the two errors are equal, which is rarely where a business wants to operate.

Panel 3: DET-style curves

On the log-log plot, a curve closer to the bottom-left corner is better. The Quadratic Discriminant curve dominates, followed by the SVM and then the Random Forest. The three colored dots show where each business scenario sits on the best curve, and they are spread far apart along it, which is the whole point of tuning.

Panel 4: expected cost

Each scenario has a different cost curve and therefore a different minimum. The cost-optimal thresholds were:

Scenario Optimal threshold FAR (test) FRR (test) Cost at EER threshold Cost at optimal threshold Reduction
Online banking 0.873 3.00% 5.10% 1.019 0.852 16.3%
Corporate VPN 0.649 7.30% 0.65% 0.373 0.283 24.0%
Smartphone unlock 0.222 15.05% 0.05% 0.502 0.100 80.0%

Online banking pushes the threshold high, because a single successful fraud is far more expensive than asking a genuine user to retry. Smartphone unlock goes the other way: a low threshold keeps the genuine user’s rejection rate almost at zero, and the occasional false accept is cheap relative to constant friction. Corporate VPN sits in between.

Panel 5: 3D cost surface

The surface shows how the expected cost depends on both the threshold and the ratio $C_{\mathrm{FAR}} / C_{\mathrm{FRR}}$. The red ridge-line traces the cheapest threshold for each ratio. As the cost of accepting an impostor grows relative to the cost of rejecting a genuine user, the optimal threshold climbs steadily toward 1. The valley floor is also fairly flat for small ratios, meaning that when false rejects dominate the cost, the exact threshold matters little.

Panel 6: 3D operating trajectory

Sweeping the threshold from 0 to 1 traces a curve through (FAR, FRR, threshold) space. Low thresholds sit in the high-FAR corner and high thresholds in the high-FRR corner. The three scenario points sit at clearly different heights along the curve, which makes the trade-off visible at a glance: moving up the threshold axis buys lower FAR at the price of higher FRR.

6. Conclusion

Three takeaways from this experiment:

  1. The EER is a benchmark, not a target. Operating at the EER threshold in every scenario cost between 16% and 80% more than the cost-optimal threshold.
  2. Cost-aware thresholds are cheap to compute. With sorted scores and np.searchsorted, evaluating every threshold takes milliseconds.
  3. Model quality and threshold choice compound. A better model shifts the whole DET curve toward the origin, and a well-chosen threshold then picks the best point on that curve for your business.

In production, replace the assumed costs and the impostor rate $\pi$ with real figures from fraud losses, helpdesk tickets, and login statistics, and re-tune periodically as user behavior drifts.

Optimizing Threat Intelligence Investment Against Zero-Day Attacks

Getting the Most Detection Power per Dollar

Zero-day attacks hit before a patch or signature exists, so defenders depend on early signals from many sources: commercial feeds, OSINT, information-sharing communities (ISACs), dark web monitoring, vendor advisories, honeypots, EDR telemetry, and bug bounty intelligence. Every source costs money, and every source has diminishing returns. The real question is how to split a limited budget across sources to maximize expected detection and defensive value.

In this article we build a concrete model, solve it with Python, and visualize the result, including a 3D objective surface.


1. The Problem Setting

We have $N = 8$ intelligence sources and $M = 6$ zero-day threat categories (Browser RCE, VPN Appliance, Email Gateway, Supply Chain, Cloud IAM, Mobile OS). The total budget is $B = 100$ (in arbitrary cost units).

Decision variable: the investment $x_i \ge 0$ in source $i$.

Diminishing returns. The quality of source $i$ grows with investment but saturates:

$$
p_i(x_i) = 1 - e^{-a_i x_i}
$$

where $a_i$ is the source’s investment efficiency.

Timeliness. A source with an average delay of $\tau_i$ days loses value for zero-days, where speed matters most:

$$
e_{ij} = r_{ij}, e^{-\lambda \tau_i}
$$

Here $r_{ij}$ is the relevance of source $i$ to threat $j$, and $\lambda = 0.06$ is the decay rate.

Detection probability for threat $j$ is the probability that at least one source catches it. Treating sources as independent:

$$
D_j(\mathbf{x}) = 1 - \prod_{i=1}^{N}\left(1 - e_{ij},p_i(x_i)\right)
$$

Objective. With $w_j$ as the potential damage (business impact) of threat $j$, we maximize the expected loss avoided:

$$
\max_{\mathbf{x}} ; F(\mathbf{x}) = \sum_{j=1}^{M} w_j, D_j(\mathbf{x})
\qquad \text{s.t.} \quad \sum_{i=1}^{N} x_i \le B,;; x_i \ge 0
$$

Because the product term makes $F$ non-concave in general, a single local optimization can get stuck. We therefore combine SLSQP with multiple random restarts, and cross-check against a greedy marginal-gain algorithm and a naive equal split.

At an interior optimum, the KKT conditions say that every funded source has the same marginal value per unit of budget:

$$
\frac{\partial F}{\partial x_i} = \mu \quad \text{for all } i \text{ with } x_i > 0
$$

This is the “equalize the marginal return” principle that governs the allocation.


2. The Complete Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # noqa: F401
from scipy.optimize import minimize

np.set_printoptions(precision=3, suppress=True)

# ------------------------------------------------------------
# 1. Problem data
# ------------------------------------------------------------
sources = ["Commercial Feed", "OSINT", "ISAC Sharing", "Dark Web Monitoring",
"Vendor Advisories", "Honeypot Network", "EDR Telemetry", "Bug Bounty Intel"]
threats = ["Browser RCE", "VPN Appliance", "Email Gateway", "Supply Chain",
"Cloud IAM", "Mobile OS"]
N, M = len(sources), len(threats)

# Investment efficiency a_i
a = np.array([0.045, 0.060, 0.050, 0.035, 0.070, 0.040, 0.055, 0.030])

# Average delay tau_i (days) and timeliness factor exp(-lambda * tau)
tau = np.array([2, 5, 4, 3, 8, 1, 1, 6], dtype=float)
lam = 0.06
timeliness = np.exp(-lam * tau)

# Relevance matrix r_ij (source i -> threat j)
R = np.array([
[0.55, 0.40, 0.45, 0.30, 0.25, 0.35],
[0.30, 0.25, 0.30, 0.35, 0.30, 0.20],
[0.40, 0.55, 0.50, 0.45, 0.40, 0.25],
[0.35, 0.30, 0.40, 0.25, 0.45, 0.30],
[0.50, 0.45, 0.35, 0.40, 0.30, 0.45],
[0.25, 0.50, 0.30, 0.15, 0.20, 0.10],
[0.60, 0.50, 0.55, 0.45, 0.50, 0.55],
[0.45, 0.35, 0.20, 0.30, 0.25, 0.50],
])
E = R * timeliness[:, None] # effective relevance e_ij

# Business impact of each threat and total budget
w = np.array([95.0, 80.0, 70.0, 100.0, 60.0, 45.0])
B = 100.0

# ------------------------------------------------------------
# 2. Model
# ------------------------------------------------------------
def detection(x):
"""Detection probability D_j for every threat (vectorized)."""
p = 1.0 - np.exp(-a * np.maximum(x, 0))
miss = np.prod(1.0 - E * p[:, None], axis=0)
return 1.0 - miss

def objective(x):
"""Expected loss avoided F(x)."""
return float(np.dot(w, detection(x)))

# ------------------------------------------------------------
# 3. Solvers
# ------------------------------------------------------------
def solve(budget, x0=None):
"""Constrained optimization with SLSQP."""
if x0 is None:
x0 = np.full(N, budget / N)
cons = [{"type": "ineq", "fun": lambda x: budget - np.sum(x)}]
res = minimize(lambda x: -objective(x), x0, method="SLSQP",
bounds=[(0, budget)] * N, constraints=cons,
options={"maxiter": 300, "ftol": 1e-10})
x = np.clip(res.x, 0, None)
if x.sum() > budget:
x *= budget / x.sum()
return x

def greedy(budget, step=1.0):
"""Allocate the budget one unit at a time to the best marginal gain."""
x = np.zeros(N)
for _ in range(int(budget / step)):
base = objective(x)
gains = []
for i in range(N):
y = x.copy()
y[i] += step
gains.append(objective(y) - base)
x[int(np.argmax(gains))] += step
return x

# Multi-start SLSQP (the problem is non-concave)
x_opt = solve(B)
rng = np.random.default_rng(0)
for _ in range(8):
cand = solve(B, rng.dirichlet(np.ones(N)) * B)
if objective(cand) > objective(x_opt):
x_opt = cand

x_eq = np.full(N, B / N) # baseline: equal split
x_gr = greedy(B) # baseline: greedy

# ------------------------------------------------------------
# 4. Console report
# ------------------------------------------------------------
total_w = w.sum()
print("=== Budget = %.0f ===" % B)
for name, x in [("Optimal (SLSQP)", x_opt), ("Greedy", x_gr), ("Equal split", x_eq)]:
f = objective(x)
print(f"{name:16s}: expected loss avoided = {f:7.2f} / {total_w:.0f} ({100*f/total_w:5.1f}%)")

print("\nOptimal allocation:")
for s, v in zip(sources, x_opt):
print(f" {s:20s}: {v:6.2f}")

print("\nDetection probability per threat (optimal vs equal):")
for t, d1, d2 in zip(threats, detection(x_opt), detection(x_eq)):
print(f" {t:14s}: {d1:.3f} vs {d2:.3f}")

# ------------------------------------------------------------
# 5. Budget sweep (diminishing returns)
# ------------------------------------------------------------
budgets = np.linspace(10, 200, 20)
curve, alloc = [], []
prev = None
for b in budgets:
x = solve(b, None if prev is None else prev * b / max(prev.sum(), 1e-9))
xe = np.full(N, b / N)
if objective(xe) > objective(x):
x = xe
prev = x
curve.append(objective(x))
alloc.append(x)
alloc = np.array(alloc)
curve_eq = [objective(np.full(N, b / N)) for b in budgets]

# ------------------------------------------------------------
# 6. Objective surface over the two most-funded sources
# ------------------------------------------------------------
order = np.argsort(-x_opt)
i1, i2 = int(order[0]), int(order[1])
g = np.linspace(0, 60, 31)
X1, X2 = np.meshgrid(g, g)
Z = np.zeros_like(X1)
for r in range(X1.shape[0]):
for c in range(X1.shape[1]):
y = x_opt.copy()
y[i1] = X1[r, c]
y[i2] = X2[r, c]
Z[r, c] = objective(y)

# ------------------------------------------------------------
# 7. Visualization (2 rows x 3 columns)
# ------------------------------------------------------------
fig = plt.figure(figsize=(22, 13))
c1 = plt.cm.viridis(0.25)
c2 = plt.cm.viridis(0.6)
c3 = plt.cm.viridis(0.9)
xi = np.arange(N)
ti = np.arange(M)

# (1) Allocation by strategy
ax = fig.add_subplot(2, 3, 1)
ax.bar(xi - 0.27, x_opt, 0.27, label="Optimal", color=c1)
ax.bar(xi, x_gr, 0.27, label="Greedy", color=c2)
ax.bar(xi + 0.27, x_eq, 0.27, label="Equal", color=c3)
ax.set_xticks(xi)
ax.set_xticklabels(sources, rotation=45, ha="right", fontsize=8)
ax.set_ylabel("Investment")
ax.set_title("Allocation by Strategy")
ax.legend()

# (2) Detection probability per threat
ax = fig.add_subplot(2, 3, 2)
ax.bar(ti - 0.2, detection(x_opt), 0.4, label="Optimal", color=c1)
ax.bar(ti + 0.2, detection(x_eq), 0.4, label="Equal", color=c3)
ax.set_xticks(ti)
ax.set_xticklabels(threats, rotation=30, ha="right", fontsize=8)
ax.set_ylabel("Detection probability")
ax.set_title("Coverage per Zero-Day Threat")
ax.legend()

# (3) Effective relevance heatmap
ax = fig.add_subplot(2, 3, 3)
im = ax.imshow(E, cmap="YlOrRd", aspect="auto")
ax.set_xticks(ti)
ax.set_xticklabels(threats, rotation=45, ha="right", fontsize=8)
ax.set_yticks(xi)
ax.set_yticklabels(sources, fontsize=8)
for r in range(N):
for c in range(M):
ax.text(c, r, f"{E[r, c]:.2f}", ha="center", va="center", fontsize=7)
fig.colorbar(im, ax=ax, fraction=0.046)
ax.set_title("Effective Relevance $e_{ij}$")

# (4) Budget vs. expected loss avoided
ax = fig.add_subplot(2, 3, 4)
ax.plot(budgets, curve, "o-", color=c1, label="Optimal")
ax.plot(budgets, curve_eq, "s--", color=c3, label="Equal split")
ax.axvline(B, color="gray", ls=":")
ax.set_xlabel("Budget")
ax.set_ylabel("Expected loss avoided")
ax.set_title("Diminishing Returns vs Budget")
ax.legend()
ax.grid(alpha=0.3)

# (5) How the optimal allocation shifts with budget
ax = fig.add_subplot(2, 3, 5)
ax.stackplot(budgets, alloc.T, labels=sources,
colors=plt.cm.tab10(np.linspace(0, 1, N)))
ax.set_xlabel("Budget")
ax.set_ylabel("Investment")
ax.set_title("Optimal Allocation Shift")
ax.legend(fontsize=6, loc="upper left")

# (6) 3D objective surface
ax = fig.add_subplot(2, 3, 6, projection="3d")
surf = ax.plot_surface(X1, X2, Z, cmap="viridis", edgecolor="none", alpha=0.9)
ax.scatter([x_opt[i1]], [x_opt[i2]], [objective(x_opt)], color="red", s=60)
ax.set_xlabel(sources[i1], fontsize=8)
ax.set_ylabel(sources[i2], fontsize=8)
ax.set_zlabel("Objective")
ax.set_title("Objective Surface (Top-2 Sources)")
fig.colorbar(surf, ax=ax, shrink=0.5, pad=0.1)

plt.tight_layout()
plt.show()

3. Code Walkthrough

Data definition (Section 1)

  • a holds the efficiency coefficients $a_i$. A larger value means the source reaches its saturation point with less money. Vendor advisories (0.070) saturate quickly, while bug bounty intelligence (0.030) needs far more investment to deliver comparable value.
  • tau and lam produce the timeliness factor $e^{-\lambda\tau_i}$. Honeypots and EDR telemetry (1 day) keep about 94% of their value, while vendor advisories (8 days) keep only about 62%. This is why speed is built into the model: for zero-days, stale intelligence is nearly worthless.
  • R is the relevance matrix $r_{ij}$. EDR telemetry is broadly relevant, whereas honeypots are strong for VPN appliances but weak for mobile OS threats.
  • E = R * timeliness[:, None] multiplies each row by its source’s timeliness factor using broadcasting, giving the effective relevance $e_{ij}$ in one line.
  • w encodes business impact. Supply chain compromise is weighted highest (100), and mobile OS threats lowest (45).

Model functions (Section 2)

detection(x) is fully vectorized. It computes $p_i$ for all sources at once, builds the $N \times M$ matrix of miss probabilities $1 - e_{ij}p_i$, and multiplies down the source axis with np.prod(..., axis=0). No Python loops are needed, which matters because the optimizer calls this function thousands of times. objective(x) is the weighted sum $F(\mathbf{x})$.

Solvers (Section 3)

  • solve() uses SLSQP (sequential least squares programming), which handles bound and inequality constraints natively. We minimize $-F$ with the constraint $B - \sum x_i \ge 0$. A defensive clip and rescale guards against tiny numerical constraint violations.
  • Multi-start: because $F$ is not guaranteed concave, we restart SLSQP from eight random Dirichlet-distributed starting points (each sums to $B$) and keep the best result. A fixed seed (default_rng(0)) makes the output reproducible.
  • greedy() allocates the budget one unit at a time to whichever source offers the largest marginal gain. It is a useful independent check: if greedy and SLSQP agree, we can be more confident that we found the global optimum.
  • x_eq is the naive baseline of spending the same amount everywhere.

Budget sweep (Section 5)

We re-solve the problem for 20 budgets from 10 to 200. Each solve is warm-started from the previous solution, scaled to the new budget, which is the speed-up here. We also compare against the equal split at every point and keep whichever is better, so the plotted curve is never worse than the baseline even if a local solver stalls.

Surface computation (Section 6)

We pick the two most-funded sources, vary only those two investments over a $31 \times 31$ grid while holding the others at their optimal values, and evaluate $F$. This slice shows the shape of the objective around the optimum. It takes only 961 cheap vectorized evaluations, so no further acceleration is required.

Plotting (Section 7)

fig.add_subplot(2, 3, k) creates the 2-row, 3-column layout, with the sixth panel declared as a 3D axis.


4. Execution Results

=== Budget = 100 ===
Optimal (SLSQP) : expected loss avoided =  329.05 / 450  ( 73.1%)
Greedy          : expected loss avoided =  329.04 / 450  ( 73.1%)
Equal split     : expected loss avoided =  311.39 / 450  ( 69.2%)

Optimal allocation:
  Commercial Feed     :  18.14
  OSINT               :   9.06
  ISAC Sharing        :  19.31
  Dark Web Monitoring :   6.02
  Vendor Advisories   :  13.14
  Honeypot Network    :   3.79
  EDR Telemetry       :  30.54
  Bug Bounty Intel    :   0.00

Detection probability per threat (optimal vs equal):
  Browser RCE   : 0.787 vs 0.743
  VPN Appliance : 0.753 vs 0.731
  Email Gateway : 0.759 vs 0.710
  Supply Chain  : 0.689 vs 0.647
  Cloud IAM     : 0.683 vs 0.647
  Mobile OS     : 0.692 vs 0.647

–


5. Interpreting the Results

Strategy comparison

With a budget of 100, the optimized allocation avoids about 329.05 of the total potential loss of 450, a 73.1% reduction. The greedy method reaches almost exactly the same value (329.04), which supports the conclusion that the optimizer found the global optimum. The equal split reaches only 311.39 (69.2%). In other words, simply spending smarter, with no extra money, yields roughly 18 more units of avoided loss.

The optimal allocation

The optimizer concentrates the budget as follows:

  • EDR Telemetry: about 30.5. This is the clear winner. It combines high relevance across all threat categories with a 1-day delay, so its effective relevance values are the largest in the heatmap.
  • ISAC Sharing: about 19.3 and Commercial Feed: about 18.1. Both offer strong, broad coverage at moderate delay.
  • Vendor Advisories: about 13.1. The high efficiency coefficient makes the first dollars very productive, but the 8-day delay caps its usefulness.
  • OSINT (9.1), Dark Web Monitoring (6.0), Honeypots (3.8) receive smaller allocations.
  • Bug Bounty Intel: 0. Low efficiency, a long delay, and limited relevance make it the first source to drop out of the portfolio.

The equal split ignores all of this and wastes money on saturating or weak sources.

Panel-by-panel reading

  1. Allocation by Strategy. The optimal bars are strongly uneven, while the equal-split bars are flat. The greedy bars nearly overlap the optimal ones.
  2. Coverage per Zero-Day Threat. The optimized portfolio improves every threat’s detection probability. For example, Browser RCE rises from 0.743 to 0.787 and Supply Chain from 0.647 to 0.689. The largest absolute gains appear for high-impact threats, which is exactly what the weights $w_j$ ask for.
  3. Effective Relevance Heatmap. Rows for EDR telemetry, ISAC, and commercial feeds are the warmest. This heatmap explains most of the allocation before any optimization is run.
  4. Diminishing Returns vs Budget. The optimal curve rises steeply at first and then flattens, reflecting the saturation $1 - e^{-a_i x_i}$. The gap between the optimal and equal-split curves is widest at small and moderate budgets, where choosing well matters most. It narrows as the budget grows, because eventually everything gets funded.
  5. Optimal Allocation Shift. The stacked area chart shows how the portfolio evolves. At small budgets, a few high-value sources dominate. As the budget grows, additional sources enter the mix once earlier ones approach saturation. This is the practical “funding order” a security team can follow when the budget changes.
  6. 3D Objective Surface. The surface over the two top-funded sources rises and then flattens in both directions, and the red dot marks the optimum on the plateau. The gentle slopes around the dot show that the solution is robust: a modest error in the budget split costs little, while the steep walls near zero show how costly it is to starve a key source.

6. Key Takeaways

  • Zero-day defense is a portfolio problem: sources overlap, saturate, and decay in value with delay.
  • Modeling timeliness explicitly, through $e^{-\lambda\tau_i}$, shifts money toward fast sources such as EDR telemetry and honeypots.
  • Because the objective is non-concave, multi-start local optimization plus an independent greedy check is a cheap and reliable way to build trust in the answer.
  • The same framework extends naturally to per-source minimum commitments (contracts), integer licensing tiers, or correlated sources, by changing the detection model and the constraints.

Replace the toy numbers with your own relevance estimates, delay measurements, and business-impact weights, and the same code becomes a practical decision aid for your next intelligence budget review.