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.

Balancing Third-Party Security Assessment Cost and Risk Reduction

Optimizing Vendor Selection and Monitoring Intensity in the Supply Chain

Supply chain attacks rarely start at your own perimeter. They start at a payment gateway, a SaaS provider, or a log analytics vendor that you trust. Every vendor can be assessed more deeply through questionnaires, continuous attack surface scanning, penetration test reports, and SOC 2 evidence reviews. But every extra layer of monitoring costs money and staff time.

This article formulates the trade-off as an optimization problem. It then solves it exactly in Python with dynamic programming, verifies the answer by brute force, and visualizes the result, including 3D plots.


1. Problem Setting

A company outsources $S = 5$ services (cloud hosting, payment gateway, customer CRM, HR/payroll SaaS, log analytics). For each service there are $V = 3$ candidate vendors, and exactly one vendor must be chosen per service. For each chosen vendor, a monitoring level $m \in {0,1,2,3,4}$ must be chosen. Level 0 means no monitoring, and level 4 means the most intensive monitoring.

Each vendor $v$ of service $s$ has the following attributes:

  • $a_{s,v}$: annual contract cost (k$). Cheaper vendors tend to be less secure.
  • $p_{s,v}$: annual breach probability without monitoring.
  • $w_{s,v}$: monitoring cost per level (k$).
  • $\lambda_{s,v}$: effectiveness of monitoring (how fast the risk decays).
  • $I_s$: loss if the service is breached (k$).
  • $f$: one-time setup cost of starting any monitoring program ($m>0$).

Risk reduction model. Monitoring reduces the breach probability exponentially, with diminishing returns:

$$
p_{s,v}(m) = p_{s,v}, e^{-\lambda_{s,v} m}
$$

Cost of one option $(v, m)$ for service $s$, and its expected loss:

$$
c_{s,v,m} = a_{s,v} + f,\mathbb{1}[m>0] + w_{s,v}, m, \qquad
\ell_{s,v,m} = I_s , p_{s,v}, e^{-\lambda_{s,v} m}
$$

Optimization problem. The goal is to minimize total expected cost, which is security spend plus expected residual loss:

Under a cash budget $B$, the constrained version is:

$$
\min \sum_{s=1}^{S} \ell_{s,v_s,m_s} \quad \text{s.t.} \quad \sum_{s=1}^{S} c_{s,v_s,m_s} \le B
$$

Continuous intuition. If the monitoring level were continuous and the vendor fixed, setting the derivative to zero gives

The optimal intensity grows logarithmically with the impact $I$. Monitor more where a breach hurts more, and where monitoring is cheap and effective.

Exact solution by dynamic programming. The budget-constrained problem is a multiple-choice knapsack. Let $F_s(b)$ be the minimum expected loss of the first $s$ services with spend at most $b$. Then

where $\mathcal{O}$ is the set of all $V \times L = 15$ (vendor, level) options. Sweeping $b$ yields the entire Pareto frontier at once, and the economically optimal budget is


2. Python 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
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from mpl_toolkits.mplot3d import Axes3D # noqa: F401

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

# ------------------------------------------------------------
# 1. Problem data
# ------------------------------------------------------------
services = ["Cloud hosting", "Payment gateway", "Customer CRM", "HR/payroll SaaS", "Log analytics"]
short = ["Cloud", "Payment", "CRM", "HR", "Logs"]
vendors = ["A", "B", "C"]
S, V, L = 5, 3, 5
levels = np.arange(L)
f_setup = 8 # setup cost of a monitoring program (k$)
impact = np.array([1200., 1800., 900., 600., 400.]) # loss if breached (k$)

p = rng.uniform(0.04, 0.28, size=(S, V)) # annual breach probability
a = np.round(30 + 350 * (0.30 - p) + rng.uniform(0, 12, size=(S, V))).astype(int) # contract cost
w = rng.integers(6, 21, size=(S, V)) # monitoring cost per level
lam = rng.uniform(0.35, 0.75, size=(S, V)) # monitoring effectiveness

# ------------------------------------------------------------
# 2. Option table: every (vendor, level) pair for every service
# ------------------------------------------------------------
O = V * L
opt_v = np.repeat(np.arange(V), L)
opt_m = np.tile(levels, V)
cost = (a[:, opt_v] + np.where(opt_m > 0, f_setup, 0)[None, :] + w[:, opt_v] * opt_m[None, :]).astype(int)
loss = impact[:, None] * p[:, opt_v] * np.exp(-lam[:, opt_v] * opt_m[None, :])

# ------------------------------------------------------------
# 3. Dynamic programming (multiple-choice knapsack)
# ------------------------------------------------------------
Bmin = int(cost.min(axis=1).sum())
Bcap = int(cost.max(axis=1).sum())
dp = np.zeros(Bcap + 1)
choices = np.full((S, Bcap + 1), -1, dtype=int)
for s in range(S):
new = np.full(Bcap + 1, np.inf)
for o in range(O):
c = int(cost[s, o])
cand = np.full(Bcap + 1, np.inf)
cand[c:] = dp[:Bcap + 1 - c] + loss[s, o]
better = cand < new
new = np.where(better, cand, new)
choices[s] = np.where(better, o, choices[s])
dp = new

def backtrack(B):
sel, b = [], B
for s in range(S - 1, -1, -1):
o = int(choices[s, b])
sel.append(o)
b -= int(cost[s, o])
return sel[::-1]

budgets = np.arange(Bmin, Bcap + 1)
frontier = dp[Bmin:]
total_J = budgets + frontier
i_opt = int(np.argmin(total_J))
B_opt = int(budgets[i_opt])
sel_opt = backtrack(B_opt)

# ------------------------------------------------------------
# 4. Brute-force verification (15^5 = 759,375 combinations, vectorized)
# ------------------------------------------------------------
grid_cost = np.zeros(1)
grid_loss = np.zeros(1)
for s in range(S):
grid_cost = np.add.outer(grid_cost, cost[s]).ravel()
grid_loss = np.add.outer(grid_loss, loss[s]).ravel()
bf_best = float((grid_cost + grid_loss).min())
dp_spend = float(sum(cost[s, sel_opt[s]] for s in range(S)))
dp_loss = float(sum(loss[s, sel_opt[s]] for s in range(S)))
bf_budget_best = float(grid_loss[grid_cost <= B_opt].min())

# ------------------------------------------------------------
# 5. Baseline strategies
# ------------------------------------------------------------
cheap_v = a.argmin(axis=1)
safe_v = p.argmin(axis=1)
strategies = {
"Cheapest,\nno monitoring": [int(cheap_v[s] * L) for s in range(S)],
"Safest vendor,\nno monitoring": [int(safe_v[s] * L) for s in range(S)],
"Cheapest,\nlevel 3 all": [int(cheap_v[s] * L + 3) for s in range(S)],
"Safest,\nlevel 2 all": [int(safe_v[s] * L + 2) for s in range(S)],
"Optimized": sel_opt,
}
results = {}
for name, sel in strategies.items():
results[name] = (float(sum(cost[s, sel[s]] for s in range(S))),
float(sum(loss[s, sel[s]] for s in range(S))))

# ------------------------------------------------------------
# 6. Console report
# ------------------------------------------------------------
print("=== Vendor candidates ===")
for s in range(S):
for v in range(V):
print(f"{services[s]:<17} {vendors[v]:<2} p={p[s, v]:.3f} contract={a[s, v]:>4d} "
f"w={w[s, v]:>3d} lambda={lam[s, v]:.2f}")
print()
print(f"Budget sweep range: {Bmin} .. {Bcap} (k$)")
print(f"Economically optimal budget b* = {B_opt} k$")
print()
print("=== Optimal plan ===")
print(f"{'Service':<17} {'Vendor':<7} {'Level':<6} {'Spend':>8} {'Exp.loss':>10}")
for s in range(S):
o = sel_opt[s]
print(f"{services[s]:<17} {vendors[o // L]:<7} {o % L:<6d} {cost[s, o]:>8d} {loss[s, o]:>10.1f}")
print()
print(f"Total spend : {dp_spend:.1f} k$")
print(f"Total expected loss : {dp_loss:.1f} k$")
print(f"Total expected cost : {dp_spend + dp_loss:.1f} k$")
print()
print("=== Verification by brute force ===")
print(f"DP optimum : {dp_spend + dp_loss:.4f}")
print(f"Brute-force optimum : {bf_best:.4f}")
print(f"Unconstrained match : {bool(np.isclose(dp_spend + dp_loss, bf_best))}")
print(f"Budget-b* loss (DP) : {dp_loss:.4f} / brute force: {bf_budget_best:.4f}")
print(f"Budget-b* match : {bool(np.isclose(dp_loss, bf_budget_best))}")
print()
print("=== Strategy comparison ===")
base_total = sum(results["Cheapest,\nno monitoring"])
for name, (sp, ls) in results.items():
tag = name.replace("\n", " ")
print(f"{tag:<32} spend={sp:>7.1f} loss={ls:>8.1f} total={sp + ls:>8.1f} "
f"vs cheapest: {100 * (sp + ls - base_total) / base_total:+.1f}%")

# ------------------------------------------------------------
# 7. One combined figure
# ------------------------------------------------------------
fig = plt.figure(figsize=(21, 12))
gs = GridSpec(2, 3, figure=fig)

# (a) Pareto frontier and total cost
ax1 = fig.add_subplot(gs[0, 0])
ax1.plot(budgets, frontier, color='cyan', lw=2.5, label='Min expected loss F(b)')
ax1.plot(budgets, total_J, color='orange', lw=2.5, label='Spend + loss b + F(b)')
ax1.axvline(B_opt, color='gold', ls='--', lw=1.5)
ax1.scatter([B_opt], [total_J[i_opt]], color='gold', s=120, zorder=5, marker='*')
markers = ['o', 's', '^', 'D']
colors = ['#ff6b6b', '#c792ea', '#7fdbca', '#f78c6c']
for (name, (sp, ls)), mk, col in zip(list(results.items())[:4], markers, colors):
ax1.scatter([sp], [ls], marker=mk, s=90, color=col, edgecolor='white', zorder=6,
label=name.replace("\n", " "))
ax1.set_xlabel('Security spend b (k$)')
ax1.set_ylabel('Expected loss (k$)')
ax1.set_title('Pareto frontier and optimal budget')
ax1.legend(fontsize=8)
ax1.grid(alpha=0.25)

# (b) Strategy comparison
ax2 = fig.add_subplot(gs[0, 1])
names = list(results.keys())
sp_arr = np.array([results[n][0] for n in names])
ls_arr = np.array([results[n][1] for n in names])
xs = np.arange(len(names))
ax2.bar(xs, sp_arr, color='#4ecdc4', label='Spend (contract + monitoring)')
ax2.bar(xs, ls_arr, bottom=sp_arr, color='#ff6b6b', label='Expected residual loss')
for i in range(len(names)):
ax2.text(xs[i], sp_arr[i] + ls_arr[i] + 15, f"{sp_arr[i] + ls_arr[i]:.0f}",
ha='center', fontsize=10, color='white')
ax2.set_xticks(xs)
ax2.set_xticklabels(names, fontsize=8)
ax2.set_ylabel('Total expected cost (k$)')
ax2.set_title('Strategy comparison')
ax2.legend(fontsize=8)
ax2.grid(alpha=0.25, axis='y')

# (c) 3D cost surface: monitoring intensity x impact
ax3 = fig.add_subplot(gs[0, 2], projection='3d')
sj = 1
vj = sel_opt[sj] // L
m_grid = np.linspace(0, 4, 81)
I_grid = np.linspace(200, 2400, 60)
MM, II = np.meshgrid(m_grid, I_grid)
T = a[sj, vj] + np.where(MM > 0, f_setup, 0) + w[sj, vj] * MM + II * p[sj, vj] * np.exp(-lam[sj, vj] * MM)
m_star = m_grid[T.argmin(axis=1)]
T_min = T.min(axis=1)
ax3.plot_surface(MM, II, T, cmap='viridis', alpha=0.88, linewidth=0, antialiased=True)
ax3.plot(m_star, I_grid, T_min, color='red', lw=3.5)
ax3.set_xlabel('Monitoring m')
ax3.set_ylabel('Impact I (k$)')
ax3.set_zlabel('Total cost (k$)')
ax3.set_title(f'Cost surface: {services[sj]}, vendor {vendors[vj]}')
ax3.view_init(elev=25, azim=-60)

# (d) 3D bar chart of the optimal plan
ax4 = fig.add_subplot(gs[1, 0], projection='3d')
bx, by, bdz, bcol = [], [], [], []
for s in range(S):
for v in range(V):
bx.append(v)
by.append(s)
if sel_opt[s] // L == v:
m_here = sel_opt[s] % L
bdz.append(max(m_here, 0.08))
bcol.append(plt.cm.plasma(m_here / (L - 1)))
else:
bdz.append(0.05)
bcol.append((0.45, 0.45, 0.45, 0.5))
ax4.bar3d(np.array(bx), np.array(by), np.zeros(len(bx)), 0.6, 0.6, np.array(bdz), color=bcol, shade=True)
ax4.set_xticks(np.arange(V) + 0.3)
ax4.set_xticklabels(vendors)
ax4.set_yticks(np.arange(S) + 0.3)
ax4.set_yticklabels(short, fontsize=8)
ax4.set_xlabel('Vendor')
ax4.set_zlabel('Monitoring level')
ax4.set_title('Optimal plan: selected vendor and intensity')
ax4.view_init(elev=28, azim=-55)

# (e) Heatmap of total cost for the selected vendors
ax5 = fig.add_subplot(gs[1, 1])
H = np.zeros((S, L))
for s in range(S):
v = sel_opt[s] // L
for m in range(L):
H[s, m] = cost[s, v * L + m] + loss[s, v * L + m]
im = ax5.imshow(H, aspect='auto', cmap='magma')
for s in range(S):
for m in range(L):
ax5.text(m, s, f"{H[s, m]:.0f}", ha='center', va='center', color='white', fontsize=9)
ax5.add_patch(plt.Rectangle((sel_opt[s] % L - 0.5, s - 0.5), 1, 1,
fill=False, edgecolor='cyan', lw=3))
ax5.set_xticks(levels)
ax5.set_yticks(np.arange(S))
ax5.set_yticklabels(short)
ax5.set_xlabel('Monitoring level')
ax5.set_title('Total cost by level (cyan = chosen)')
fig.colorbar(im, ax=ax5, fraction=0.046, pad=0.04)

# (f) Cost breakdown of the optimal plan
ax6 = fig.add_subplot(gs[1, 2])
contract = np.array([a[s, sel_opt[s] // L] for s in range(S)], dtype=float)
monit = np.array([cost[s, sel_opt[s]] for s in range(S)], dtype=float) - contract
resid = np.array([loss[s, sel_opt[s]] for s in range(S)])
ys = np.arange(S)
ax6.barh(ys, contract, color='#4ecdc4', label='Contract')
ax6.barh(ys, monit, left=contract, color='#ffd166', label='Monitoring')
ax6.barh(ys, resid, left=contract + monit, color='#ff6b6b', label='Residual expected loss')
ax6.set_yticks(ys)
ax6.set_yticklabels(short)
ax6.invert_yaxis()
ax6.set_xlabel('k$')
ax6.set_title('Cost breakdown of the optimal plan')
ax6.legend(fontsize=8)
ax6.grid(alpha=0.25, axis='x')

fig.suptitle('Supply Chain Risk: Vendor Selection and Monitoring Intensity Optimization', fontsize=17)
fig.tight_layout(rect=[0, 0, 1, 0.95])
plt.show()

3. Code Walkthrough

3.1 Data generation

The block under “Problem data” creates the scenario. The loss $I_s$ is set by hand to reflect business criticality. The payment gateway has the largest impact and log analytics the smallest. The breach probabilities $p_{s,v}$ are drawn uniformly. The contract cost is deliberately anti-correlated with $p_{s,v}$ through 350 * (0.30 - p), so a safer vendor costs more. This matches reality, where premium providers invest more in security and charge accordingly. The monitoring cost per level $w$ and the effectiveness $\lambda$ are random integers and floats, respectively. The fixed seed makes the article reproducible.

3.2 Option table

For every service, all $V \times L = 15$ combinations of vendor and monitoring level are enumerated with NumPy broadcasting. opt_v and opt_m list the vendor and level of each option column. The arrays cost and loss then implement $c_{s,v,m}$ and $\ell_{s,v,m}$ exactly as defined in Section 1. Costs are integers on purpose, because the dynamic program indexes an array by budget.

3.3 Dynamic programming

dp[b] stores $F_s(b)$, the minimum expected loss with spend at most $b$. It starts as zeros because with no services there is no loss. For each service, every option $o$ is tried. The candidate array cand is the shifted previous table plus the option’s loss, and the entries below the option’s cost remain infinite because they are infeasible. np.where(better, ...) keeps the elementwise minimum and records which option achieved it in choices.

The loops are only over 5 services and 15 options. The budget dimension is handled by vector operations, so the whole table is built in milliseconds. backtrack walks from the last service to the first, reading the stored choice and subtracting its cost from the remaining budget, which reconstructs the actual plan.

Since dp encodes “spend at most $b$”, the last table $F_S$ gives the whole Pareto frontier in a single pass. The economically optimal budget is the minimizer of $b + F_S(b)$, which is the point where one more dollar of security spend no longer buys a dollar of expected loss reduction.

3.4 Brute-force verification

np.add.outer repeatedly builds the cost and loss of all $15^5 = 759{,}375$ combinations without Python loops. The minimum of cost plus loss must equal the DP optimum, and the minimum loss among combinations with cost at most $b^*$ must equal the DP loss at that budget. The console prints both comparisons as True or False. This is exhaustive enumeration at a size that stays fast, so no further speed-up is required. For hundreds of vendors, where enumeration is impossible, the DP scales linearly in the number of services, which is why it is the main solver and enumeration is only the audit.

3.5 Baseline strategies

Four intuitive policies are compared against the optimum. The first picks the cheapest vendors and monitors nothing. The second picks the lowest-risk vendors without monitoring. The third picks the cheapest vendors and monitors everything at level 3. The fourth picks the safest vendors and monitors everything at level 2. These represent common real-world habits: minimize procurement cost, buy the best reputation, or apply a uniform compliance rule to every vendor.


4. Execution Results

=== Vendor candidates ===
Cloud hosting     A  p=0.226  contract=  59  w= 19  lambda=0.44
Cloud hosting     B  p=0.145  contract=  91  w= 17  lambda=0.62
Cloud hosting     C  p=0.246  contract=  50  w= 11  lambda=0.52
Payment gateway   A  p=0.207  contract=  72  w= 20  lambda=0.68
Payment gateway   B  p=0.063  contract= 121  w= 12  lambda=0.63
Payment gateway   C  p=0.274  contract=  48  w= 10  lambda=0.47
Customer CRM      A  p=0.223  contract=  61  w= 19  lambda=0.68
Customer CRM      B  p=0.229  contract=  67  w= 11  lambda=0.67
Customer CRM      C  p=0.071  contract= 121  w=  7  lambda=0.50
HR/payroll SaaS   A  p=0.148  contract=  93  w= 13  lambda=0.47
HR/payroll SaaS   B  p=0.129  contract=  92  w= 17  lambda=0.62
HR/payroll SaaS   C  p=0.262  contract=  49  w=  8  lambda=0.41
Log analytics     A  p=0.195  contract=  67  w= 12  lambda=0.43
Log analytics     B  p=0.237  contract=  54  w=  7  lambda=0.35
Log analytics     C  p=0.146  contract=  92  w= 16  lambda=0.66

Budget sweep range: 262 .. 833 (k$)
Economically optimal budget b* = 496 k$

=== Optimal plan ===
Service           Vendor  Level     Spend   Exp.loss
Cloud hosting     C       4           102       36.2
Payment gateway   C       4            96       73.8
Customer CRM      B       4           119       14.0
HR/payroll SaaS   C       4            89       31.0
Log analytics     B       4            90       23.1

Total spend         : 496.0 k$
Total expected loss : 178.2 k$
Total expected cost : 674.2 k$

=== Verification by brute force ===
DP optimum          : 674.2009
Brute-force optimum : 674.2009
Unconstrained match : True
Budget-b* loss (DP) : 178.2009  / brute force: 178.2009
Budget-b* match     : True

=== Strategy comparison ===
Cheapest, no monitoring          spend=  262.0  loss=  1241.6  total=  1503.6  vs cheapest: +0.0%
Safest vendor, no monitoring     spend=  517.0  loss=   486.7  total=  1003.7  vs cheapest: -33.2%
Cheapest, level 3 all            spend=  467.0  loss=   285.2  total=   752.2  vs cheapest: -50.0%
Safest, level 2 all              spend=  695.0  loss=   143.6  total=   838.6  vs cheapest: -44.2%
Optimized                        spend=  496.0  loss=   178.2  total=   674.2  vs cheapest: -55.2%

/tmp/ipykernel_868/1924791915.py:254: UserWarning: Tight layout not applied. tight_layout cannot make Axes width small enough to accommodate all Axes decorations
  fig.tight_layout(rect=[0, 0, 1, 0.95])


5. Reading the Graphs

All six panels are drawn in a single figure.

(a) Pareto frontier and optimal budget (top left). The cyan curve is $F(b)$, the lowest achievable expected loss for a given security budget. It falls steeply at first and then flattens, which is the diminishing-returns effect of the exponential risk model. The orange curve adds the spend itself, $b + F(b)$. It is U-shaped. Spending too little leaves large expected losses, and spending too much wastes money on protection that reduces little risk. The gold star marks the minimum of that curve, the economically optimal budget $b^*$. The colored markers are the four naive strategies. Points lying above the cyan curve are dominated, meaning the optimizer can achieve a lower loss for the same spend, or the same loss for less spend.

(b) Strategy comparison (top middle). Each bar is split into spend (teal) and residual expected loss (red). The cheapest-and-unmonitored policy has the lowest spend but the tallest red segment. Uniform monitoring policies shrink the red portion, but they pay the same monitoring price for a low-impact HR system as for the payment gateway. The optimized plan has the lowest total height because it shifts effort to where the loss per monitoring dollar is highest.

(c) 3D cost surface (top right). For the payment gateway vendor in the optimal plan, the surface shows total cost over monitoring intensity $m$ and breach impact $I$. At low impact the surface is lowest at $m=0$, because monitoring is not worth its price. As impact grows, a valley forms and moves toward higher $m$. The red ridge traces the cost-minimizing intensity for each impact. It follows the logarithmic law $m^{*} = \frac{1}{\lambda}\ln\frac{I p \lambda}{w}$ derived in Section 1, rising quickly at first and then slowly. This is the geometric picture of why critical vendors deserve deeper assessment while peripheral ones do not.

(d) 3D bar chart of the optimal plan (bottom left). The horizontal axes are vendors and services, and the height is the monitoring level of the selected vendor. Gray flat bars are rejected vendors. Colored towers are the selected ones, with color following the level. A well-optimized plan has uneven towers: tall for high-impact services and short or absent for low-impact ones. This shows the plan is not a uniform policy.

(e) Heatmap of total cost per level (bottom middle). Each row is a service with its selected vendor, and each column is a monitoring level. Cell values are spend plus expected loss. The cyan frame marks the chosen level, which sits at the cheapest cell of each row. The shape of each row is a convex bowl. Rows for important services have their minimum further to the right.

(f) Cost breakdown (bottom right). Contract cost, monitoring cost, and residual expected loss are stacked per service. High-impact services carry a visible monitoring share, while low-impact services are dominated by the contract cost. Residual loss is intentionally not driven to zero. Eliminating the last fraction of risk would cost more than it saves, which is the central lesson of risk-based vendor management.


6. Conclusion

Vendor risk management is often run as a checklist: every vendor gets the same questionnaire, or the cheapest vendor wins. Framing it as a multiple-choice knapsack shows that:

  • The right monitoring intensity depends on impact, breach probability, monitoring cost, and monitoring effectiveness, and it grows only logarithmically with impact.
  • Vendor selection and monitoring must be decided together, since a cheaper but riskier vendor may need expensive monitoring that erases its price advantage.
  • The Pareto frontier gives a defensible budget conversation. Instead of arguing about a number, you can show exactly how much expected loss each additional dollar removes, and stop at the point where it no longer pays.

The same code extends naturally to more vendors, finer monitoring levels, or additional constraints such as a staff-hours budget, which would simply add another dimension to the DP table.

How Much Should You Pre-Allocate to Each Incident Response Phase?

An Optimization Walkthrough in Python

When a breach hits, the quality of your response is largely decided before the incident starts. Every security team has a finite number of analysts and a finite tool budget, and these have to be split across four phases: Detection, Containment, Recovery, and Notification. Spread them evenly and you waste money on phases that need little. Starve the wrong phase and the damage compounds while the clock runs.

In this post we turn that question into a small optimization problem, solve it exactly by brute force, cross-check it with a continuous optimizer, and visualize the result with 2D and 3D plots.

The Problem Setup

A mid-sized company has:

  • 20 responders to assign across the four phases (at least 1 per phase)
  • $100k of tool budget to allocate, in $5k increments

We want the split that minimizes the expected loss from an incident.

Phase duration model

More people and better tooling shorten each phase, but with diminishing returns. For phase $i$ with $n_i$ staff and $m_i$ (in $k) of tools:

$$
T_i(n_i, m_i) = T^{\min}_i + \frac{T^{0}_i - T^{\min}_i}{1 + g_i , n_i^{\alpha} \left(\dfrac{m_i}{10}\right)^{\beta}}
$$

  • $T^{0}_i$ is the duration with essentially no investment.
  • $T^{\min}_i$ is the floor that no amount of investment can break (for example, regulators’ review windows).
  • $g_i$ is how responsive the phase is to investment.
  • $\alpha = 0.6$ and $\beta = 0.4$ control the diminishing returns on people and tools.
Phase $T^0$ (h) $T^{\min}$ (h) $g$
Detection 120 1 0.50
Containment 48 2 0.60
Recovery 96 8 0.30
Notification 60 6 0.80

Loss model

There are three incident scenarios with probabilities $p = (0.40, 0.35, 0.25)$: data theft, ransomware, and insider misuse. Each has a different cost rate while the attacker is undetected or uncontained ($a_s$), while systems are down ($b_s$), and a different regulatory penalty weight. Averaging over scenarios gives

$$
\bar a = \sum_s p_s a_s = 9.25, \qquad \bar b = \sum_s p_s b_s = 13.75, \qquad \bar P = 500 \sum_s p_s \pi_s = 297.5
$$

in $k per hour (or $k for the penalty). The expected loss is

$$
L(\mathbf n, \mathbf m) = \bar a ,(T_D + T_C) + \bar b ,(T_C + T_R) + \bar P \cdot \sigma!\left(T_D + T_C + T_N - 72\right)
$$

where the notification deadline is 72 hours and $\sigma$ is a smooth penalty (a scaled softplus):

$$
\sigma(x) = \frac{6}{72},\ln!\left(1 + e^{x/6}\right)
$$

The full optimization problem is

$$
\min_{\mathbf n,, \mathbf m} ; L(\mathbf n, \mathbf m) \quad \text{s.t.} \quad \sum_{i=1}^{4} n_i = 20,;; n_i \ge 1,;; \sum_{i=1}^{4} m_i = 100,;; m_i \in {0, 5, 10, \dots}
$$

The Source Code

The search space contains $969 \times 1771 = 1{,}716{,}099$ combinations. A naive nested Python loop would take minutes, so the code below evaluates all combinations at once with NumPy broadcasting.

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
import itertools
import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.optimize import minimize
from mpl_toolkits.mplot3d import Axes3D # noqa: F401

plt.rcParams["figure.dpi"] = 110
plt.rcParams["axes.grid"] = True

PHASES = ["Detection", "Containment", "Recovery", "Notification"]
T0 = np.array([120.0, 48.0, 96.0, 60.0])
TMIN = np.array([1.0, 2.0, 8.0, 6.0])
G = np.array([0.50, 0.60, 0.30, 0.80])
ALPHA, BETA = 0.6, 0.4
DEADLINE = 72.0
SMOOTH = 6.0

p = np.array([0.40, 0.35, 0.25])
a = np.array([5.0, 15.0, 8.0])
b = np.array([25.0, 5.0, 8.0])
pen = np.array([0.3, 1.0, 0.5])
P_BASE = 500.0
A_BAR = float(p @ a)
B_BAR = float(p @ b)
P_BAR = float(p @ pen) * P_BASE

N_STAFF = 20
M_TOOLS = 100.0
TOOL_STEP = 5

def phase_times(n, m):
n = np.asarray(n, dtype=float)
m = np.asarray(m, dtype=float)
e = np.power(n, ALPHA) * np.power(m / 10.0, BETA)
return TMIN + (T0 - TMIN) / (1.0 + G * e)

def soft_excess(x):
return SMOOTH * np.logaddexp(0.0, x / SMOOTH) / DEADLINE

def loss_from_times(T):
td, tc, tr, tn = T[..., 0], T[..., 1], T[..., 2], T[..., 3]
return (A_BAR * (td + tc) + B_BAR * (tc + tr)
+ P_BAR * soft_excess(td + tc + tn - DEADLINE))

def total_loss(n, m):
return loss_from_times(phase_times(n, m))

def compositions(total, parts, minimum=0):
rest = total - parts * minimum
rows = []
for c in itertools.combinations(range(rest + parts - 1), parts - 1):
prev = -1
row = []
for x in c:
row.append(x - prev - 1 + minimum)
prev = x
row.append(rest + parts - 1 - prev - 1 + minimum)
rows.append(row)
return np.array(rows, dtype=float)

t_start = time.time()
S = compositions(N_STAFF, 4, minimum=1)
units = int(M_TOOLS // TOOL_STEP)
Mt = compositions(units, 4, minimum=0) * TOOL_STEP
E = np.power(S[:, None, :], ALPHA) * np.power(Mt[None, :, :] / 10.0, BETA)
T_all = TMIN + (T0 - TMIN) / (1.0 + G * E)
L_all = loss_from_times(T_all)
i, j = np.unravel_index(np.argmin(L_all), L_all.shape)
best_n, best_m = S[i], Mt[j]
best_loss = float(L_all[i, j])
elapsed = time.time() - t_start

equal_n = np.full(4, N_STAFF / 4)
equal_m = np.full(4, M_TOOLS / 4)
equal_loss = float(total_loss(equal_n, equal_m))

def solve_continuous(N, M, n_starts=4, seed=0):
rng = np.random.default_rng(seed)
cons = [{"type": "eq", "fun": lambda x: np.sum(x[:4]) - N},
{"type": "eq", "fun": lambda x: np.sum(x[4:]) - M}]
bounds = [(1.0, float(N))] * 4 + [(1e-3, float(M))] * 4
x_eq = np.concatenate([np.full(4, N / 4), np.full(4, M / 4)])
best_x, best_f = x_eq, float(total_loss(x_eq[:4], x_eq[4:]))
for k in range(n_starts):
if k == 0:
wn = np.full(4, 0.25); wm = np.full(4, 0.25)
else:
wn = rng.dirichlet(np.ones(4)); wm = rng.dirichlet(np.ones(4))
x0 = np.concatenate([1.0 + (N - 4.0) * wn, np.maximum(M * wm, 1e-2)])
res = minimize(lambda x: float(total_loss(x[:4], x[4:])), x0,
method="SLSQP", bounds=bounds, constraints=cons,
options={"maxiter": 300, "ftol": 1e-10})
ok = (abs(np.sum(res.x[:4]) - N) < 1e-3) and (abs(np.sum(res.x[4:]) - M) < 1e-3)
if ok and res.fun < best_f:
best_x, best_f = res.x, float(res.fun)
return best_x, best_f

cont_x, cont_loss = solve_continuous(N_STAFF, M_TOOLS)

T_equal = phase_times(equal_n, equal_m)
T_best = phase_times(best_n, best_m)

table = pd.DataFrame({
"Phase": PHASES,
"Staff (equal)": equal_n, "Staff (optimal)": best_n,
"Tools $k (equal)": equal_m, "Tools $k (optimal)": best_m,
"Hours (equal)": np.round(T_equal, 1), "Hours (optimal)": np.round(T_best, 1),
})
print("Search space size:", S.shape[0] * Mt.shape[0], "combinations, solved in", round(elapsed, 2), "s")
print(table.to_string(index=False))
print()
print("Expected loss, equal split : %.1f ($k)" % equal_loss)
print("Expected loss, continuous opt. : %.1f ($k)" % cont_loss)
print("Expected loss, integer optimum : %.1f ($k)" % best_loss)
print("Reduction vs equal split : %.1f %%" % (100 * (1 - best_loss / equal_loss)))
print("Total time, equal / optimal : %.1f h / %.1f h" % (T_equal.sum(), T_best.sum()))

sd = np.linspace(1, N_STAFF - 3, 30)
md = np.linspace(0, 70, 30)
SD, MD = np.meshgrid(sd, md)
rest_n = best_n[1:] / best_n[1:].sum()
rest_m = best_m[1:] / best_m[1:].sum()
n_grid = np.concatenate([SD[..., None], (N_STAFF - SD)[..., None] * rest_n], axis=-1)
m_grid = np.concatenate([MD[..., None], (M_TOOLS - MD)[..., None] * rest_m], axis=-1)
Z_slice = total_loss(n_grid, m_grid)

N_vals = np.arange(8, 33, 4)
M_vals = np.arange(40, 161, 20)
NN, MM = np.meshgrid(N_vals, M_vals)
Z_nm = np.zeros(NN.shape)
for r in range(NN.shape[0]):
for c in range(NN.shape[1]):
Z_nm[r, c] = solve_continuous(int(NN[r, c]), float(MM[r, c]), n_starts=3, seed=r * 10 + c)[1]

fig = plt.figure(figsize=(20, 12))
x = np.arange(4); w = 0.38

ax1 = fig.add_subplot(2, 3, 1)
ax1.bar(x - w / 2, equal_n, w, label="Equal split")
ax1.bar(x + w / 2, best_n, w, label="Optimal")
ax1.set_xticks(x); ax1.set_xticklabels(PHASES)
ax1.set_ylabel("Staff (people)"); ax1.set_title("(a) Staff allocation"); ax1.legend()

ax2 = fig.add_subplot(2, 3, 2)
ax2.bar(x - w / 2, equal_m, w, label="Equal split")
ax2.bar(x + w / 2, best_m, w, label="Optimal")
ax2.set_xticks(x); ax2.set_xticklabels(PHASES)
ax2.set_ylabel("Tool budget ($k)"); ax2.set_title("(b) Tool budget allocation"); ax2.legend()

ax3 = fig.add_subplot(2, 3, 3)
labels = ["Equal split", "Optimal"]
bottom = np.zeros(2)
for k, ph in enumerate(PHASES):
vals = np.array([T_equal[k], T_best[k]])
ax3.bar(labels, vals, bottom=bottom, label=ph)
bottom += vals
ax3.axhline(DEADLINE, color="red", linestyle="--", label="72 h deadline")
ax3.set_ylabel("Hours"); ax3.set_title("(c) Time spent in each phase"); ax3.legend()

ax4 = fig.add_subplot(2, 3, 4, projection="3d")
ax4.plot_surface(SD, MD, Z_slice, cmap="viridis", alpha=0.9, linewidth=0)
ax4.scatter([best_n[0]], [best_m[0]], [best_loss], color="red", s=60)
ax4.set_xlabel("Detection staff"); ax4.set_ylabel("Detection tools ($k)")
ax4.set_zlabel("Expected loss ($k)"); ax4.set_title("(d) Loss vs. detection resources")

ax5 = fig.add_subplot(2, 3, 5, projection="3d")
ax5.plot_surface(NN, MM, Z_nm, cmap="plasma", alpha=0.9, linewidth=0)
ax5.set_xlabel("Total staff"); ax5.set_ylabel("Total tool budget ($k)")
ax5.set_zlabel("Optimal loss ($k)"); ax5.set_title("(e) Optimal loss vs. total resources")

ax6 = fig.add_subplot(2, 3, 6)
names = ["Equal split", "Continuous\noptimum", "Integer\noptimum"]
vals = [equal_loss, cont_loss, best_loss]
bars = ax6.bar(names, vals, color=["#999999", "#4c78a8", "#e45756"])
for bar_, v in zip(bars, vals):
ax6.text(bar_.get_x() + bar_.get_width() / 2, v, "%.0f" % v, ha="center", va="bottom")
ax6.set_ylabel("Expected loss ($k)"); ax6.set_title("(f) Expected loss comparison")

fig.suptitle("Incident Response Resource Allocation", fontsize=18)
fig.tight_layout(rect=[0, 0, 1, 0.97])
plt.show()

Code Walkthrough

1. Parameters

The first block defines everything about the scenario: the base durations T0, the floors TMIN, the responsiveness G, and the exponents ALPHA and BETA. The scenario arrays p, a, b, and pen are collapsed into the three scalars A_BAR, B_BAR, and P_BAR using the probability-weighted averages shown earlier. Because the loss is linear in the scenario parameters, averaging first gives exactly the same expected loss as averaging at the end, and it is much cheaper.

2. The model functions

  • phase_times(n, m) implements $T_i(n_i, m_i)$ directly. It works on a single allocation of shape (4,) and also on huge arrays, because every operation is element-wise and the last axis always holds the four phases.
  • soft_excess(x) implements $\sigma(x)$. np.logaddexp(0, z) computes $\ln(1+e^{z})$ without overflow, which matters when the optimizer wanders into extreme regions.
  • loss_from_times(T) slices the last axis (T[..., 0] and so on), so it accepts any array shape. This is what lets us evaluate 1.7 million allocations in a single call.

I chose a smooth penalty rather than a hard max(0, x) on purpose. The continuous optimizer (SLSQP) relies on gradients, and a smooth function keeps it well-behaved while still being very close to the hard deadline rule.

3. Enumerating every allocation

compositions(total, parts, minimum) lists every way to split total units into parts non-negative integers (after reserving minimum for each part) using the classic stars-and-bars construction. For 20 staff in 4 phases with at least 1 each, that is 969 rows. For $100k in $5k units, that is 1,771 rows.

4. The speed-up: broadcasting instead of loops

The key lines are:

1
E = np.power(S[:, None, :], ALPHA) * np.power(Mt[None, :, :] / 10.0, BETA)

S[:, None, :] has shape (969, 1, 4) and Mt[None, :, :] has shape (1, 1771, 4). NumPy broadcasts them into a (969, 1771, 4) array, which is every staff split paired with every tool split, without a single Python loop. A nested loop would call the Python interpreter 1.7 million times; broadcasting pushes the entire computation into compiled C code, which brings the run time down from minutes to a fraction of a second. np.unravel_index(np.argmin(L_all), L_all.shape) then converts the flat position of the minimum back into a (staff row, tool row) pair.

5. Baseline and continuous optimum

The “equal split” baseline gives 5 people and $25k to every phase. For the continuous solution, solve_continuous runs SLSQP with two equality constraints (total staff and total budget) and box bounds. It starts from several initial points (one uniform, the rest random draws from a Dirichlet distribution) and keeps the best feasible result, so a single unlucky start cannot trap it in a poor local minimum. Feasibility of the constraints is verified explicitly before a result is accepted. The continuous optimum is a lower bound for the integer problem, so it tells us how much we lose by having to use whole people and $5k steps.

6. Surfaces for the 3D plots

Panel (d) slices the problem: it varies detection staff and detection tools on a grid, and distributes the remaining people and budget over the other three phases in the same proportions as the optimal solution. Panel (e) re-solves the continuous problem for a grid of total staff and total budget values, showing how the best achievable loss improves as you scale up resources.

Execution Results

Search space size: 1716099 combinations, solved in 0.21 s
       Phase  Staff (equal)  Staff (optimal)  Tools $k (equal)  Tools $k (optimal)  Hours (equal)  Hours (optimal)
   Detection            5.0              7.0              25.0                35.0           42.1             33.6
 Containment            5.0              6.0              25.0                25.0           16.1             15.0
    Recovery            5.0              6.0              25.0                35.0           49.2             43.9
Notification            5.0              1.0              25.0                 5.0           19.4             39.6

Expected loss, equal split     : 1466.2  ($k)
Expected loss, continuous opt. : 1326.0  ($k)
Expected loss, integer optimum : 1328.1  ($k)
Reduction vs equal split       : 9.4 %
Total time, equal / optimal    : 126.7 h / 132.1 h

Interpreting the Results

The optimum beats the even split by roughly 9%. The brute-force search over all 1,716,099 allocations finds an expected loss of about $1,328k, against about $1,466k for the equal split. The continuous optimum is about $1,326k, so rounding to whole people and $5k steps costs only about $2k. That is a strong sign the integer solution is essentially optimal.

The best allocation is strongly uneven. Detection ends up with 7 people and $35k, Containment with 6 people and $25k, Recovery with 6 people and $35k, and Notification with just 1 person and $5k. Detection and Recovery attract the largest budgets, while Notification is pushed to the minimum.

Why Notification gets so little. Look at the marginal economics. An extra hour in Detection or Containment costs $\bar a = 9.25$ $k, and Containment and Recovery hours each carry an additional $\bar b = 13.75$ $k. A late notification, by contrast, only incurs the deadline penalty, whose slope is about $\bar P / 72 \approx 4.1$ $k per hour past the deadline. Spending scarce resources on shaving notification hours buys less than spending them upstream. Panel (c) shows the consequence: the optimal plan has a longer Notification phase than the equal split, and it spends more of its time over the 72-hour line, but the total loss is still lower.

Minimizing time is not the same as minimizing loss. The optimal plan’s total duration is actually slightly longer than that of the equal split (about 132 h versus about 127 h). The optimizer does not try to make every phase fast; it makes the expensive hours fast. This is the central lesson for pre-allocation: weigh each phase by what an hour of delay actually costs, not by how long the phase takes.

The 3D surface in panel (d) shows diminishing returns. Starting from the corner with little detection staff and little tooling, the loss falls steeply, then flattens as both inputs increase. The red marker sits in the flat basin. Pushing detection resources further would take them from the other phases, whose loss then rises faster than detection’s falls. This is what a well-balanced allocation looks like: no phase can gain without another losing more.

The 3D surface in panel (e) shows how the best achievable loss changes with total resources. It decreases in both directions, but the slope shrinks as the totals grow, because of the exponents $\alpha = 0.6$ and $\beta = 0.4$ and the duration floors $T^{\min}_i$. This is useful for budgeting: if you are choosing between hiring two more analysts and buying more tooling, this surface lets you read off which lever lowers the optimal loss more at your current operating point.

Panel (f) confirms the ordering: equal split, then continuous optimum, then integer optimum, with the last two nearly identical.

Takeaways

  1. Model each phase with diminishing returns and a hard floor. Real incident work does not scale linearly with headcount.
  2. Allocate by cost per hour of delay, not by phase length.
  3. For small discrete problems like this one, exhaustive search with NumPy broadcasting gives a guaranteed global optimum in well under a second, and a continuous solver provides an independent check.
  4. Re-run the model with your own numbers. Changing the scenario probabilities or the deadline penalty can shift the optimum noticeably, which is exactly why this analysis is worth doing before the incident rather than during it.

Balancing Misconfiguration Risk Against Availability Loss with Python

Optimal CSPM Configuration

Introduction

Cloud Security Posture Management (CSPM) tools continuously compare your cloud configuration against a security baseline. Every control they enforce, such as MFA, public-access blocking, SSH restrictions, egress filtering, or auto-remediation, creates a tension.

  • Too loose: misconfigurations such as public buckets, over-privileged roles, and open management ports stay exploitable, and expected breach losses grow.
  • Too strict: legitimate deployments are blocked, auto-remediation breaks running services, and engineers hit friction. Downtime and lost productivity grow, and the SLA is at risk.

Neither “turn everything to maximum” nor “keep everything permissive” is optimal. In this article we formulate the problem as a convex optimization, solve it in Python, and visualize the trade-off with a Pareto frontier and 3D cost landscapes.


1. Problem Formulation

Consider $n = 10$ security controls. For each control $i$, we choose an enforcement strictness $s_i \in [0, 1]$, where $0$ means “audit only” and $1$ means “block everything non-compliant”.

Residual misconfiguration risk. If control $i$ is left unenforced, the expected annual loss is $R_i^0$ (in k$/year). Stricter enforcement removes risk exponentially:

$$
R_i(s_i) = R_i^0 , e^{-\kappa_i s_i}
$$

where $\kappa_i$ is the effectiveness of the control.

Availability loss. Strict enforcement causes false-positive blocks and broken deployments. The cost grows quadratically, because the last few percent of strictness are the most disruptive:

$$
A_i(s_i) = c_i , s_i^{2}, \qquad D(\mathbf{s}) = \sum_{i=1}^{n} A_i(s_i)
$$

SLA constraint (soft). The organization has an annual downtime-cost budget $B$. Exceeding it triggers a quadratic penalty with coefficient $\rho$:

$$
\Pi(\mathbf{s}) = \rho ,\bigl[\max(0,; D(\mathbf{s}) - B)\bigr]^2
$$

Objective. Minimize the total expected cost:

$$
\min_{\mathbf{s} \in [0,1]^n} ; J(\mathbf{s}) = \sum_{i=1}^{n} R_i^0 e^{-\kappa_i s_i} ;+; D(\mathbf{s}) ;+; \rho ,\bigl[\max(0,, D(\mathbf{s}) - B)\bigr]^2
$$

Optimality condition. For an interior solution, setting $\partial J / \partial s_i = 0$ gives

$$
R_i^0 , \kappa_i , e^{-\kappa_i s_i} ;=; 2 c_i s_i \Bigl(1 + 2\rho \max(0, D - B)\Bigr)
$$

The left side is the marginal risk reduction and the right side is the marginal availability cost. When the SLA budget is exceeded, the factor $1 + 2\rho,(D - B)$ acts as an automatic “price of downtime” that pushes every control toward a more relaxed setting. Each term of $J$ is convex, and $\max(0,\cdot)^2$ of a convex function is convex, so $J$ is convex and has a unique global minimum.

Pareto frontier. To see the whole trade-off curve, we also solve the weighted problem

$$
\min_{\mathbf{s}} ; \sum_{i} R_i(s_i) + \lambda , D(\mathbf{s}), \qquad \lambda \in [0.1,; 25]
$$

Each $\lambda$ produces one efficient (risk, downtime) pair.


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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
import time
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize

plt.style.use("dark_background")

# ------------------------------------------------------------------
# 1. Problem data (k$ per year)
# ------------------------------------------------------------------
names = [
"MFA enforcement",
"Public storage access block",
"Encryption at rest",
"SSH/RDP source restriction",
"Least-privilege IAM",
"Network egress filtering",
"Audit logging enforcement",
"Key rotation policy",
"Baseline/patch enforcement",
"Auto-remediation (auto-block)",
]
short = [
"MFA", "Public block", "Encryption", "SSH/RDP limit", "Least-priv IAM",
"Egress filter", "Audit logging", "Key rotation", "Baseline enforce", "Auto-remediate",
]

R0 = np.array([420.0, 380.0, 250.0, 300.0, 450.0, 180.0, 120.0, 140.0, 260.0, 220.0])
k = np.array([3.0, 4.0, 3.5, 3.0, 2.5, 2.5, 2.0, 2.5, 2.8, 2.2])
c = np.array([60.0, 30.0, 45.0, 110.0, 150.0, 160.0, 40.0, 90.0, 130.0, 200.0])
n = len(names)

B = 250.0 # annual downtime-cost budget (k$)
P = 0.02 # SLA penalty coefficient


# ------------------------------------------------------------------
# 2. Cost model
# ------------------------------------------------------------------
def components(s):
s = np.asarray(s, dtype=float)
risk = float(np.sum(R0 * np.exp(-k * s)))
down = float(np.sum(c * s ** 2))
pen = float(P * max(0.0, down - B) ** 2)
return risk, down, pen


def total_cost_grad(s):
s = np.asarray(s, dtype=float)
e = np.exp(-k * s)
risk = np.sum(R0 * e)
down = np.sum(c * s ** 2)
excess = max(0.0, down - B)
value = risk + down + P * excess ** 2
grad = -R0 * k * e + 2.0 * c * s * (1.0 + 2.0 * P * excess)
return value, grad


def weighted_cost_grad(s, lam):
s = np.asarray(s, dtype=float)
e = np.exp(-k * s)
value = np.sum(R0 * e) + lam * np.sum(c * s ** 2)
grad = -R0 * k * e + lam * 2.0 * c * s
return value, grad


# ------------------------------------------------------------------
# 3. Solve: SLA-aware optimum (L-BFGS-B with analytic gradient)
# ------------------------------------------------------------------
t0 = time.perf_counter()
bounds = [(0.0, 1.0)] * n
x0 = np.full(n, 0.5)

res = minimize(
total_cost_grad, x0, jac=True, method="L-BFGS-B", bounds=bounds,
options={"ftol": 1e-12, "gtol": 1e-9, "maxiter": 500},
)
s_opt = res.x
r_opt, d_opt, p_opt = components(s_opt)
j_opt = r_opt + d_opt + p_opt

# ------------------------------------------------------------------
# 4. Pareto frontier via the weighted problem
# ------------------------------------------------------------------
lams = np.logspace(-1.0, np.log10(25.0), 60)
S = np.zeros((n, lams.size))
front_R = np.zeros(lams.size)
front_D = np.zeros(lams.size)
for j, lam in enumerate(lams):
rj = minimize(
weighted_cost_grad, x0, args=(lam,), jac=True,
method="L-BFGS-B", bounds=bounds,
)
S[:, j] = rj.x
front_R[j], front_D[j], _ = components(rj.x)

# ------------------------------------------------------------------
# 5. Naive policies for comparison
# ------------------------------------------------------------------
policies = {
"Permissive\n(s = 0.2)": np.full(n, 0.2),
"Uniform\n(s = 0.6)": np.full(n, 0.6),
"Max strict\n(s = 1.0)": np.full(n, 1.0),
"Optimized": s_opt,
}
pol_comp = {name: components(sv) for name, sv in policies.items()}
pol_total = {name: sum(v) for name, v in pol_comp.items()}
best_naive = min(v for name, v in pol_total.items() if name != "Optimized")
elapsed = time.perf_counter() - t0

# ------------------------------------------------------------------
# 6. Console report
# ------------------------------------------------------------------
print("=" * 82)
print("CSPM OPTIMAL CONFIGURATION REPORT (all costs in k$ per year)")
print("=" * 82)
print(f"Solver success : {res.success}")
print(f"Iterations : {res.nit}")
print(f"Solver message : {res.message}")
print(f"Elapsed time : {elapsed:.3f} s (optimum + {lams.size}-point Pareto sweep)")
print("-" * 82)
print(f"{'Control':<32}{'Strictness':>11}{'Residual risk':>16}{'Downtime cost':>16}")
print("-" * 82)
for i in range(n):
rr = R0[i] * np.exp(-k[i] * s_opt[i])
dd = c[i] * s_opt[i] ** 2
print(f"{names[i]:<32}{s_opt[i]:>11.3f}{rr:>16.2f}{dd:>16.2f}")
print("-" * 82)
print(f"{'TOTAL':<32}{'':>11}{r_opt:>16.2f}{d_opt:>16.2f}")
print(f"Downtime budget B = {B:.1f} | SLA penalty at optimum = {p_opt:.2f}")
print(f"Total expected cost J* = {j_opt:.2f}")
print("=" * 82)
print(f"{'Policy':<24}{'Risk':>12}{'Downtime':>12}{'SLA penalty':>14}{'Total':>12}")
print("-" * 82)
for name, (rk, dn, pn) in pol_comp.items():
label = name.replace("\n", " ")
print(f"{label:<24}{rk:>12.2f}{dn:>12.2f}{pn:>14.2f}{rk + dn + pn:>12.2f}")
print("-" * 82)
saving = 100.0 * (best_naive - j_opt) / best_naive
print(f"Cost reduction of the optimized policy vs. best naive policy: {saving:.2f} %")
print("=" * 82)

# ------------------------------------------------------------------
# 7. Visualization (single figure, six panels)
# ------------------------------------------------------------------
fig = plt.figure(figsize=(22, 12.5))
gs = fig.add_gridspec(2, 3, wspace=0.30, hspace=0.38)
fig.subplots_adjust(left=0.07, right=0.96, top=0.91, bottom=0.07)
fig.suptitle("CSPM Optimal Configuration: Misconfiguration Risk vs. Availability Loss",
fontsize=18, fontweight="bold")

# (a) optimal strictness per control
ax1 = fig.add_subplot(gs[0, 0])
colors = plt.get_cmap("plasma")(np.clip(s_opt, 0.0, 1.0))
ax1.barh(np.arange(n), s_opt, color=colors, edgecolor="white", linewidth=0.5)
for idx, v in enumerate(s_opt):
ax1.text(v + 0.015, idx, f"{v:.2f}", va="center", fontsize=9)
ax1.set_yticks(np.arange(n))
ax1.set_yticklabels(short, fontsize=9)
ax1.invert_yaxis()
ax1.set_xlim(0, 1.15)
ax1.set_xlabel("Optimal enforcement strictness $s_i^*$")
ax1.set_title("(a) Optimal strictness per control")
ax1.grid(axis="x", alpha=0.25)

# (b) 3D cost landscape for two controls (others fixed at optimum)
i1, i2 = 0, 4
g1 = np.linspace(0.0, 1.0, 70)
g2 = np.linspace(0.0, 1.0, 70)
G1, G2 = np.meshgrid(g1, g2)
mask = np.ones(n, dtype=bool)
mask[[i1, i2]] = False
risk_rest = np.sum(R0[mask] * np.exp(-k[mask] * s_opt[mask]))
down_rest = np.sum(c[mask] * s_opt[mask] ** 2)
risk_s = R0[i1] * np.exp(-k[i1] * G1) + R0[i2] * np.exp(-k[i2] * G2)
down_s = down_rest + c[i1] * G1 ** 2 + c[i2] * G2 ** 2
Z = risk_rest + risk_s + down_s + P * np.maximum(0.0, down_s - B) ** 2

ax2 = fig.add_subplot(gs[0, 1], projection="3d")
surf = ax2.plot_surface(G1, G2, Z, cmap="viridis", alpha=0.92,
linewidth=0, antialiased=True)
ax2.scatter([s_opt[i1]], [s_opt[i2]], [j_opt], color="red", s=90,
depthshade=False, label="Optimum")
ax2.set_xlabel(f"$s$: {short[i1]}")
ax2.set_ylabel(f"$s$: {short[i2]}")
ax2.set_zlabel("Total cost $J$ (k$/yr)")
ax2.set_title("(b) 3D cost landscape (two controls varied)")
ax2.view_init(elev=28, azim=-58)
ax2.legend(loc="upper left")
fig.colorbar(surf, ax=ax2, shrink=0.55, pad=0.10, label="$J$ (k$/yr)")

# (c) Pareto frontier
ax3 = fig.add_subplot(gs[0, 2])
ax3.plot(front_D, front_R, "-o", color="cyan", ms=3, lw=1.5, label="Pareto frontier")
pol_colors = ["#7fff7f", "#ffd24d", "#ff7f7f", "red"]
for (name, (rk, dn, pn)), col in zip(pol_comp.items(), pol_colors):
label = name.replace("\n", " ")
if name == "Optimized":
ax3.scatter([dn], [rk], marker="*", s=300, color=col, edgecolor="white",
zorder=5, label=label)
else:
ax3.scatter([dn], [rk], marker="s", s=80, color=col, edgecolor="white",
zorder=5, label=label)
ax3.axvline(B, color="orange", ls="--", lw=1.3, label="Downtime budget $B$")
ax3.set_xlabel("Downtime cost $D$ (k$/yr)")
ax3.set_ylabel("Residual risk $\\sum R_i$ (k$/yr)")
ax3.set_title("(c) Pareto frontier: risk vs. availability")
ax3.grid(alpha=0.25)
ax3.legend(fontsize=8)

# (d) stacked cost comparison
ax4 = fig.add_subplot(gs[1, 0])
labels = list(pol_comp.keys())
risk_v = np.array([pol_comp[l][0] for l in labels])
down_v = np.array([pol_comp[l][1] for l in labels])
pen_v = np.array([pol_comp[l][2] for l in labels])
xpos = np.arange(len(labels))
ax4.bar(xpos, risk_v, color="#ff6b6b", label="Residual risk")
ax4.bar(xpos, down_v, bottom=risk_v, color="#4dabf7", label="Downtime cost")
ax4.bar(xpos, pen_v, bottom=risk_v + down_v, color="#ffd43b", label="SLA penalty")
for xi, tot in zip(xpos, risk_v + down_v + pen_v):
ax4.text(xi, tot + 15, f"{tot:.0f}", ha="center", fontsize=10, fontweight="bold")
ax4.set_xticks(xpos)
ax4.set_xticklabels(labels, fontsize=9)
ax4.set_ylabel("Expected annual cost (k$)")
ax4.set_title("(d) Total cost by policy")
ax4.legend(fontsize=9)
ax4.grid(axis="y", alpha=0.25)

# (e) heat map: optimal strictness vs. lambda
ax5 = fig.add_subplot(gs[1, 1])
im = ax5.imshow(S, aspect="auto", origin="lower", cmap="magma", vmin=0.0, vmax=1.0,
extent=[np.log10(lams[0]), np.log10(lams[-1]), -0.5, n - 0.5])
ax5.set_yticks(np.arange(n))
ax5.set_yticklabels(short, fontsize=9)
ax5.set_xlabel("$\\log_{10}\\lambda$ (price of downtime)")
ax5.set_title("(e) How strictness relaxes as downtime gets pricier")
fig.colorbar(im, ax=ax5, pad=0.02, label="Strictness $s_i$")

# (f) efficiency map: risk reduction vs. availability cost at the optimum
ax6 = fig.add_subplot(gs[1, 2])
gain = R0 * (1.0 - np.exp(-k * s_opt))
cost = c * s_opt ** 2
sc = ax6.scatter(cost, gain, c=s_opt, cmap="plasma", s=140, edgecolor="white",
vmin=0.0, vmax=1.0)
for i in range(n):
ax6.annotate(short[i], (cost[i], gain[i]), textcoords="offset points",
xytext=(6, 5), fontsize=8)
ax6.set_xlabel("Availability cost at optimum (k$/yr)")
ax6.set_ylabel("Risk reduction at optimum (k$/yr)")
ax6.set_title("(f) Return on strictness per control")
ax6.grid(alpha=0.25)
fig.colorbar(sc, ax=ax6, pad=0.02, label="Strictness $s_i^*$")

plt.show()

3. Code Walkthrough

3.1 Problem data

Each of the ten controls has three parameters. R0 is the expected annual loss if the control is not enforced, k is the effectiveness $\kappa_i$ (how quickly risk falls with strictness), and c is the availability cost $c_i$ at full strictness. Controls such as least-privilege IAM and auto-remediation have large c because their enforcement can break workloads. Controls such as public-access blocking and audit logging are cheap to enforce. The budget B and the penalty coefficient P correspond to $B$ and $\rho$ in the formulation.

3.2 Cost model

components() returns the three cost pieces separately (risk, downtime, SLA penalty), which the report and the plots reuse. total_cost_grad() returns the objective value and its analytic gradient in one call, which is what minimize(..., jac=True) expects:

$$
\frac{\partial J}{\partial s_i} = -R_i^0 \kappa_i e^{-\kappa_i s_i} + 2 c_i s_i \bigl(1 + 2\rho \max(0, D-B)\bigr)
$$

The penalty enters the gradient only through the shared factor $1 + 2\rho\max(0, D-B)$. This is how one control’s strictness affects every other control’s optimum. weighted_cost_grad() is the same idea for the Pareto problem, with the constant price $\lambda$ replacing that factor.

3.3 Solving the problem

The solver is L-BFGS-B, a quasi-Newton method that natively supports the box constraints $0 \le s_i \le 1$. Because $J$ is convex, it converges to the unique global optimum from any starting point, so no multi-start is needed. Supplying the exact gradient avoids finite-difference evaluations, and the vectorized NumPy expressions evaluate all ten controls at once, so the optimization is very fast.

3.4 Pareto sweep

We sweep $\lambda$ over a logarithmic grid and solve the weighted problem for each value. The result is stored in S (strictness per control per $\lambda$) together with the achieved risk and downtime. Plotting risk against downtime yields the efficient frontier. Every point on it is a configuration that cannot lower risk without adding downtime, and vice versa.

3.5 Baseline policies

Three common heuristics are compared against the optimum: a permissive policy ($s_i = 0.2$), a uniform medium policy ($s_i = 0.6$), and a “maximum strictness” policy ($s_i = 1$). All four are scored with the same cost function, so the comparison is fair.

3.6 Visualization

All six panels are drawn in a single figure:

  • (a) shows the optimal strictness of each control.
  • (b) is a 3D surface of the total cost as two controls (MFA and least-privilege IAM) vary while the other eight stay at their optimal values. The red marker is the minimum. The surface is not separable because the SLA penalty couples the two controls through the shared downtime $D$.
  • (c) shows the Pareto frontier, with the policies and the optimum marked and the downtime budget drawn as a dashed line.
  • (d) is a stacked bar chart splitting each policy’s cost into risk, downtime, and SLA penalty.
  • (e) is a heat map of how every control’s optimal strictness relaxes as the price of downtime $\lambda$ rises.
  • (f) plots the risk reduction each control buys against the availability it costs at the optimum.

4. Execution Results

Result Figure

Console Output

==================================================================================
CSPM OPTIMAL CONFIGURATION REPORT  (all costs in k$ per year)
==================================================================================
Solver success : True
Iterations     : 17
Solver message : CONVERGENCE: RELATIVE REDUCTION OF F <= FACTR*EPSMCH
Elapsed time   : 1.286 s (optimum + 60-point Pareto sweep)
----------------------------------------------------------------------------------
Control                          Strictness   Residual risk   Downtime cost
----------------------------------------------------------------------------------
MFA enforcement                       0.745           44.93           33.31
Public storage access block           0.771           17.43           17.81
Encryption at rest                    0.654           25.35           19.24
SSH/RDP source restriction            0.539           59.58           31.94
Least-privilege IAM                   0.581          105.19           50.71
Network egress filtering              0.370           71.39           21.90
Audit logging enforcement             0.600           36.17           14.39
Key rotation policy                   0.435           47.20           17.02
Baseline/patch enforcement            0.482           67.46           30.18
Auto-remediation (auto-block)         0.362           99.22           26.20
----------------------------------------------------------------------------------
TOTAL                                                573.90          262.69
Downtime budget B = 250.0 | SLA penalty at optimum = 3.22
Total expected cost J* = 839.81
==================================================================================
Policy                          Risk    Downtime   SLA penalty       Total
----------------------------------------------------------------------------------
Permissive (s = 0.2)         1527.71       40.60          0.00     1568.31
Uniform (s = 0.6)             499.28      365.40        266.34     1131.03
Max strict (s = 1.0)          169.99     1015.00      11704.50    12889.49
Optimized                     573.90      262.69          3.22      839.81
----------------------------------------------------------------------------------
Cost reduction of the optimized policy vs. best naive policy: 25.75 %
==================================================================================

5. Interpreting the Graphs

Panel (a): optimal strictness. The optimum is a graded policy. Controls with a high ratio of risk to availability cost, such as public-access blocking, MFA, and encryption, end up with high strictness. Controls that are expensive to enforce relative to the risk they remove, such as egress filtering and auto-remediation, are held at a moderate level. Maximum strictness everywhere would be wasteful, because the quadratic availability term makes the last increments of strictness very costly.

Panel (b): 3D cost landscape. The surface is bowl-shaped, as expected from convexity. Moving toward $s = 0$ on either axis climbs the “risk wall” of unprotected exposure. Moving toward $s = 1$ climbs the “availability wall” of downtime, and it steepens further once the SLA budget is exceeded. The red marker sits at the bottom of the valley. Because the penalty couples the controls, the valley floor is tilted. Tightening one control shifts the best setting of the other.

Panel (c): Pareto frontier. Risk falls steeply at first when a little downtime is accepted, and then flattens, which is the law of diminishing returns. The permissive policy sits far above the frontier on the risk axis, and the maximum-strict policy sits far to the right on the downtime axis. The optimized configuration lies on the efficient curve near the budget line, where the marginal risk reduction equals the marginal price of downtime.

Panel (d): cost decomposition. The permissive policy is dominated by residual risk, while the maximum-strict policy is dominated by downtime cost and SLA penalty. The optimized policy balances both components, and the console report quantifies its total saving against the best naive policy.

Panel (e): sensitivity heat map. Moving right along the $\lambda$ axis, every control relaxes, but at different speeds. Controls with a high $R_i^0 \kappa_i / c_i$ ratio stay bright (strict) even when downtime is expensive, while low-ratio controls fade quickly. This gives a prioritization rule: when the availability budget shrinks, relax the low-ratio controls first.

Panel (f): return on strictness. Controls in the upper left of the plot deliver a large risk reduction for little availability cost and should be enforced firmly. Controls in the lower right are candidates for relaxation, compensating controls, or monitoring-only modes.


6. Conclusion

CSPM tuning is a constrained trade-off, not a binary “secure vs. usable” decision. With a simple exponential-risk and quadratic-downtime model, the problem becomes a convex program with a unique global optimum that a quasi-Newton solver finds almost instantly.

  • The optimum equalizes marginal risk reduction with the marginal price of downtime across all controls.
  • The SLA budget acts as a shared price signal that couples all controls.
  • The Pareto frontier shows exactly how much risk each additional unit of availability budget can buy.

In practice, $R_i^0$, $\kappa_i$, and $c_i$ can be estimated from incident history, CSPM finding statistics, and change-failure data, and the same framework then scales to hundreds of controls.

Optimizing Phishing Defense

How Should You Split Your Budget Between Email Filters and User Training?

Every security team eventually faces the same budget question. Do we buy a better email filter, or do we run more awareness training and phishing simulations? Technical controls scale silently but never reach 100% detection. Human controls are adaptive but suffer from diminishing returns and training fatigue. This article builds a small quantitative model of that trade-off and solves it as a constrained nonlinear optimization problem in Python.

1. The Problem

A company wants to spend a fixed annual security budget on two kinds of controls.

  • Technical control: an email filtering stack (gateway, sandboxing, URL rewriting). Spending $x$ (in thousand USD per year) reduces the fraction of phishing emails that slip through.
  • Human control: security awareness training (sessions per year $f$) and simulated phishing campaigns (campaigns per year $s$). Both reduce the probability that an employee clicks a malicious link that reaches the inbox.

Example scenario

Parameter Symbol Value
Annual budget $B$ 200 k USD
Phishing emails targeted at the organization per year $E$ 3000
Average loss per successful compromise $L$ 4 k USD
Cost per training session $c_T$ 8 k USD
Cost per simulation campaign $c_S$ 5 k USD
Maximum training sessions per year $f_{\max}$ 12
Maximum simulation campaigns per year $s_{\max}$ 24

2. Mathematical Model

Filter miss rate. Filter performance saturates: there is always a residual miss rate $m_\infty$ that no budget can remove.

$$
m(x) = m_\infty + (m_0 - m_\infty),e^{-x/a}
$$

Click probability. Training and simulation reinforce each other through the interaction term $\gamma f s$. Too many touches cause fatigue, which is modeled by the quadratic penalty with coefficient $\kappa$.

$$
c(f,s) = c_\infty + (c_0 - c_\infty)\exp!\big[-(\alpha f + \beta s + \gamma f s)\big] + \kappa,(f+s)^2
$$

Expected annual loss. Compromises require both a filter miss and a click:

$$
\mathcal{L}(x,f,s) = E,L;m(x);c(f,s)
$$

Optimization problem.

$$
\min_{x,f,s}\ \mathcal{L}(x,f,s)
\quad \text{s.t.} \quad
x + c_T f + c_S s \le B,\quad
x \ge 0,\ \ 0 \le f \le f_{\max},\ \ 0 \le s \le s_{\max}
$$

Optimality condition. Because $\log\mathcal{L} = \log(EL) + \log m(x) + \log c(f,s)$, the technical and human layers contribute multiplicatively. At an interior optimum the marginal loss reduction per extra dollar must be equal across all three instruments, with $\lambda$ the shadow price of the budget:

$$
-\frac{\partial \mathcal{L}}{\partial x}
= -\frac{1}{c_T}\frac{\partial \mathcal{L}}{\partial f}
= -\frac{1}{c_S}\frac{\partial \mathcal{L}}{\partial s}
= \lambda
$$

Any variable sitting at a bound (for example $f = f_{\max}$) has a marginal value that differs from $\lambda$.

3. Solution Strategy

  1. Solve the problem with SLSQP from many random feasible starting points (multi-start) to avoid poor local solutions.
  2. Cross-check the answer with a fully vectorized brute-force grid over the technical share $\theta = x/B$ and the training fraction $\phi$ of the human budget.
  3. Compare the optimum against five naive strategies.
  4. Re-solve the problem for a range of budgets to see how the optimal mix shifts.

All grid evaluations use NumPy broadcasting with no Python loops, so the whole script runs in a few seconds.

4. 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
import time
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from mpl_toolkits.mplot3d import Axes3D # noqa: F401
from scipy.optimize import minimize

plt.style.use('dark_background')
t_start = time.time()

# ------------------------------------------------------------------
# Parameters
# ------------------------------------------------------------------
B = 200.0 # annual budget (k USD)
E = 3000.0 # phishing emails targeted at the organization per year
L = 4.0 # average loss per successful compromise (k USD)
C_TRAIN = 8.0 # cost per training session (k USD)
C_SIM = 5.0 # cost per simulation campaign (k USD)
F_MAX = 12.0 # max training sessions per year
S_MAX = 24.0 # max simulation campaigns per year

M0, M_INF, A_TECH = 0.20, 0.02, 60.0 # filter miss-rate model
K0, K_INF = 0.30, 0.03 # click-rate model (base, floor)
A_F, A_S, A_FS = 0.40, 0.25, 0.03 # learning effects (training, simulation, synergy)
FATIGUE = 0.0002 # fatigue penalty coefficient


# ------------------------------------------------------------------
# Model
# ------------------------------------------------------------------
def miss_rate(x):
return M_INF + (M0 - M_INF) * np.exp(-x / A_TECH)


def click_rate(f, s):
learn = np.exp(-(A_F * f + A_S * s + A_FS * f * s))
return K_INF + (K0 - K_INF) * learn + FATIGUE * (f + s) ** 2


def expected_loss(x, f, s):
return E * L * miss_rate(x) * click_rate(f, s)


def spend_of(x, f, s):
return x + C_TRAIN * f + C_SIM * s


def marginal_gains(x, f, s, h=1e-4):
gx = -(expected_loss(x + h, f, s) - expected_loss(x - h, f, s)) / (2 * h)
gf = -(expected_loss(x, f + h, s) - expected_loss(x, f - h, s)) / (2 * h) / C_TRAIN
gs = -(expected_loss(x, f, s + h) - expected_loss(x, f, s - h)) / (2 * h) / C_SIM
return gx, gf, gs


# ------------------------------------------------------------------
# Multi-start SLSQP solver
# ------------------------------------------------------------------
def solve(budget, x_bounds=None, n_starts=24, seed=0):
rng = np.random.default_rng(seed)
xb = (0.0, float(budget)) if x_bounds is None else x_bounds
bounds = [xb, (0.0, F_MAX), (0.0, S_MAX)]
cons = [{'type': 'ineq',
'fun': lambda v: budget - spend_of(v[0], v[1], v[2])}]

def obj(v):
return float(expected_loss(v[0], v[1], v[2]))

lower = np.array([xb[0], 0.0, 0.0])
upper = np.array([xb[1], F_MAX, S_MAX])
best_v, best_val = None, np.inf

for _ in range(n_starts):
w = rng.dirichlet(np.ones(3))
x0 = np.array([w[0] * budget, w[1] * budget / C_TRAIN, w[2] * budget / C_SIM])
x0 = np.clip(x0, lower, upper)
res = minimize(obj, x0, method='SLSQP', bounds=bounds,
constraints=cons, options={'maxiter': 500, 'ftol': 1e-12})
v = np.clip(res.x, lower, upper)
if spend_of(v[0], v[1], v[2]) > budget + 1e-6:
continue
val = obj(v)
if val < best_val:
best_val, best_v = val, v

if best_v is None:
best_v = np.array([min(budget, xb[1]), 0.0, 0.0])

x, f, s = float(best_v[0]), float(best_v[1]), float(best_v[2])
return {'x': x, 'f': f, 's': s,
'loss': float(expected_loss(x, f, s)),
'spend': float(spend_of(x, f, s))}


# ------------------------------------------------------------------
# 1) Optimal solution
# ------------------------------------------------------------------
opt = solve(B, n_starts=30, seed=42)
human_spend_opt = C_TRAIN * opt['f'] + C_SIM * opt['s']
theta_opt = opt['x'] / B
phi_opt = C_TRAIN * opt['f'] / human_spend_opt if human_spend_opt > 1e-9 else 0.0
baseline_loss = float(expected_loss(0.0, 0.0, 0.0))

print('=' * 74)
print('PHISHING DEFENSE: BUDGET ALLOCATION OPTIMIZATION')
print('=' * 74)
print(f'Budget B = {B:.0f} k USD | emails E = {E:.0f} | loss per compromise L = {L:.1f} k USD')
print('-' * 74)
print('OPTIMAL ALLOCATION (SLSQP, multi-start)')
print(f' Email filter spend x : {opt["x"]:8.2f} k USD ({100 * theta_opt:5.1f}% of budget)')
print(f' Training sessions f : {opt["f"]:8.3f} per year -> {C_TRAIN * opt["f"]:7.2f} k USD')
print(f' Simulation campaigns s : {opt["s"]:8.3f} per year -> {C_SIM * opt["s"]:7.2f} k USD')
print(f' Total spend : {opt["spend"]:8.2f} k USD')
print(f' Filter miss rate m(x) : {100 * miss_rate(opt["x"]):8.3f} %')
print(f' Employee click rate c(f,s) : {100 * click_rate(opt["f"], opt["s"]):8.3f} %')
print(f' Expected annual loss : {opt["loss"]:8.2f} k USD')
print(f' Loss with no investment : {baseline_loss:8.2f} k USD')

gx, gf, gs = marginal_gains(opt['x'], opt['f'], opt['s'])
print('-' * 74)
print('MARGINAL LOSS REDUCTION PER EXTRA 1 k USD (equal for interior variables)')
print(f' Email filter : {gx:10.4f}')
print(f' Training sessions : {gf:10.4f}')
print(f' Simulation campaigns : {gs:10.4f}')

# ------------------------------------------------------------------
# 2) Vectorized grid search (cross-check and 3D surface)
# ------------------------------------------------------------------
theta = np.linspace(0.0, 1.0, 81)
phi = np.linspace(0.0, 1.0, 81)
TH, PH = np.meshgrid(theta, phi)


def alloc_from_shares(th, ph, budget):
x = th * budget
h = (1.0 - th) * budget
f = np.minimum(ph * h / C_TRAIN, F_MAX)
s = np.minimum((1.0 - ph) * h / C_SIM, S_MAX)
return x, f, s


GX, GF, GS = alloc_from_shares(TH, PH, B)
LOSS_GRID = expected_loss(GX, GF, GS)
ZLOG = np.log10(LOSS_GRID)
gi, gj = np.unravel_index(np.argmin(LOSS_GRID), LOSS_GRID.shape)
grid_best = float(LOSS_GRID[gi, gj])
print('-' * 74)
print('GRID CROSS-CHECK (81 x 81 allocations, vectorized)')
print(f' Best grid loss : {grid_best:8.2f} k USD '
f'(theta = {theta[gj]:.3f}, phi = {phi[gi]:.3f})')
print(f' Solver loss : {opt["loss"]:8.2f} k USD')
print(f' Solver minus grid : {opt["loss"] - grid_best:8.4f} k USD (<= 0 means solver is at least as good)')

profile = LOSS_GRID.min(axis=0)
phi_half_idx = int(np.argmin(np.abs(phi - 0.5)))
profile_half = LOSS_GRID[phi_half_idx, :]

# ------------------------------------------------------------------
# 3) Strategy comparison
# ------------------------------------------------------------------
human_only = solve(B, x_bounds=(0.0, 1e-6), n_starts=20, seed=7)
strategies = {
'No\ninvestment': (0.0, 0.0, 0.0),
'Tech\nonly': (B, 0.0, 0.0),
'Human\nonly': (human_only['x'], human_only['f'], human_only['s']),
'Even\nsplit': (0.5 * B, 0.25 * B / C_TRAIN, 0.25 * B / C_SIM),
'Tech-heavy\n80/20': (0.8 * B, 0.10 * B / C_TRAIN, 0.10 * B / C_SIM),
'Optimized': (opt['x'], opt['f'], opt['s']),
}
print('-' * 74)
print('STRATEGY COMPARISON')
print(f' {"Strategy":<18}{"Tech":>9}{"Train":>9}{"Sim":>9}{"Loss":>11}{"Reduction":>12}')
for name, (x, f, s) in strategies.items():
loss = float(expected_loss(x, f, s))
red = 100.0 * (1.0 - loss / baseline_loss)
print(f' {name.replace(chr(10), " "):<18}{x:9.1f}{C_TRAIN * f:9.1f}{C_SIM * s:9.1f}{loss:11.2f}{red:11.1f}%')

# ------------------------------------------------------------------
# 4) Budget sensitivity
# ------------------------------------------------------------------
budgets = np.arange(50.0, 401.0, 25.0)
sweep = [solve(b, n_starts=10, seed=1) for b in budgets]
sweep_loss = np.array([r['loss'] for r in sweep])
sweep_share = np.array([100.0 * r['x'] / max(r['spend'], 1e-9) for r in sweep])
print('-' * 74)
print('BUDGET SENSITIVITY')
print(f' {"Budget":>8}{"Tech share %":>15}{"Training f":>13}{"Simulation s":>15}{"Loss":>10}')
for b, r, sh in zip(budgets, sweep, sweep_share):
print(f' {b:8.0f}{sh:15.1f}{r["f"]:13.2f}{r["s"]:15.2f}{r["loss"]:10.2f}')

# ------------------------------------------------------------------
# 5) Visualization (single figure)
# ------------------------------------------------------------------
fig = plt.figure(figsize=(21, 12))
gs_layout = GridSpec(2, 3, figure=fig, hspace=0.32, wspace=0.28)

# (a) 3D surface: technical share vs training fraction
ax1 = fig.add_subplot(gs_layout[0, 0], projection='3d')
ax1.plot_surface(TH, PH, ZLOG, cmap='viridis', linewidth=0,
antialiased=True, rstride=1, cstride=1, alpha=0.95)
ax1.scatter([theta_opt], [phi_opt], [np.log10(opt['loss'])],
color='red', s=90, depthshade=False, label='Optimum')
ax1.set_xlabel('Technical share')
ax1.set_ylabel('Training fraction')
ax1.set_zlabel('log10 loss (k USD)')
ax1.set_title('(a) Loss surface over allocation shares')
ax1.view_init(elev=28, azim=-125)
ax1.legend(loc='upper left')

# (b) 3D surface: training vs simulation (remaining budget to the filter)
fg = np.linspace(0.0, F_MAX, 61)
sg = np.linspace(0.0, S_MAX, 61)
FG, SG = np.meshgrid(fg, sg)
mask = (C_TRAIN * FG + C_SIM * SG) <= B
FM, SM = FG[mask], SG[mask]
XM = B - C_TRAIN * FM - C_SIM * SM
ZM = np.log10(expected_loss(XM, FM, SM))
ax2 = fig.add_subplot(gs_layout[0, 1], projection='3d')
ax2.plot_trisurf(FM, SM, ZM, cmap='plasma', linewidth=0.1, antialiased=True, alpha=0.95)
ax2.scatter([opt['f']], [opt['s']], [np.log10(opt['loss'])],
color='cyan', s=90, depthshade=False, label='Optimum')
ax2.set_xlabel('Training sessions f')
ax2.set_ylabel('Simulation campaigns s')
ax2.set_zlabel('log10 loss (k USD)')
ax2.set_title('(b) Loss vs human program (rest to filter)')
ax2.view_init(elev=30, azim=-60)
ax2.legend(loc='upper left')

# (c) Contour map of the allocation surface
ax3 = fig.add_subplot(gs_layout[0, 2])
cf = ax3.contourf(TH, PH, ZLOG, levels=30, cmap='viridis')
ax3.contour(TH, PH, ZLOG, levels=12, colors='white', linewidths=0.4, alpha=0.5)
ax3.scatter([theta_opt], [phi_opt], marker='*', s=300, color='red',
edgecolor='white', zorder=5, label='Solver optimum')
ax3.scatter([theta[gj]], [phi[gi]], marker='o', s=80, facecolor='none',
edgecolor='yellow', linewidth=2, zorder=6, label='Grid optimum')
cbar = fig.colorbar(cf, ax=ax3, pad=0.02)
cbar.set_label('log10 loss (k USD)')
ax3.set_xlabel(r'Technical share $\theta = x/B$')
ax3.set_ylabel(r'Training fraction $\phi$ of human budget')
ax3.set_title('(c) Contour map and optimum')
ax3.legend(loc='upper right')

# (d) Loss profile along the technical share
ax4 = fig.add_subplot(gs_layout[1, 0])
ax4.plot(theta * 100, profile, color='lime', linewidth=2.5, label=r'Best $\phi$ for each $\theta$')
ax4.plot(theta * 100, profile_half, color='orange', linewidth=1.8, linestyle='--',
label=r'Fixed $\phi = 0.5$')
ax4.axvline(100 * theta_opt, color='red', linestyle=':', linewidth=1.8,
label=f'Optimum: {100 * theta_opt:.1f}% technical')
ax4.set_yscale('log')
ax4.set_xlabel('Share of budget on email filtering (%)')
ax4.set_ylabel('Expected annual loss (k USD, log scale)')
ax4.set_title('(d) Loss profile along the technical share')
ax4.grid(alpha=0.25)
ax4.legend()

# (e) Strategy comparison
ax5 = fig.add_subplot(gs_layout[1, 1])
names = list(strategies.keys())
tech_c = [strategies[k][0] for k in names]
train_c = [C_TRAIN * strategies[k][1] for k in names]
sim_c = [C_SIM * strategies[k][2] for k in names]
losses = [float(expected_loss(*strategies[k])) for k in names]
idx = np.arange(len(names))
ax5.bar(idx, tech_c, color='#4cc9f0', label='Email filter')
ax5.bar(idx, train_c, bottom=tech_c, color='#f72585', label='Training')
ax5.bar(idx, sim_c, bottom=np.array(tech_c) + np.array(train_c), color='#ffd166', label='Simulation')
for i, ls in enumerate(losses):
top = tech_c[i] + train_c[i] + sim_c[i]
ax5.text(i, top + 4, f'Loss\n{ls:.0f}', ha='center', va='bottom', fontsize=9, color='white')
ax5.set_xticks(idx)
ax5.set_xticklabels(names, fontsize=9)
ax5.set_ylim(0, B * 1.3)
ax5.set_ylabel('Spend (k USD)')
ax5.set_title('(e) Spend breakdown and expected loss per strategy')
ax5.legend(loc='upper left')
ax5.grid(axis='y', alpha=0.25)

# (f) Budget sensitivity
ax6 = fig.add_subplot(gs_layout[1, 2])
ax6.plot(budgets, sweep_loss, 'o-', color='#ff6b6b', linewidth=2.2, label='Optimal expected loss')
ax6.set_xlabel('Annual budget (k USD)')
ax6.set_ylabel('Expected annual loss (k USD)', color='#ff6b6b')
ax6.tick_params(axis='y', labelcolor='#ff6b6b')
ax6.grid(alpha=0.25)
ax6b = ax6.twinx()
ax6b.plot(budgets, sweep_share, 's--', color='#4cc9f0', linewidth=2.0, label='Technical share of spend')
ax6b.set_ylabel('Technical share of spend (%)', color='#4cc9f0')
ax6b.tick_params(axis='y', labelcolor='#4cc9f0')
ax6b.set_ylim(0, 105)
ax6.set_title('(f) How the optimal mix changes with budget')

fig.suptitle('Phishing Defense Budget Allocation: Email Filtering vs. User Training',
fontsize=17, y=0.98)
fig.subplots_adjust(left=0.04, right=0.95, top=0.92, bottom=0.07)
plt.show()

print('-' * 74)
print(f'Total runtime: {time.time() - t_start:.2f} s')

5. Code Walkthrough

Parameters and model functions. The constants at the top define the scenario from Section 1 plus the shape parameters of the two response curves. miss_rate, click_rate, and expected_loss implement the equations of Section 2 directly. They are written with NumPy operations only, so the same function evaluates a single point, a whole grid, or an array of budgets without modification. This is the main speed-up: the 81 × 81 allocation grid and the 61 × 61 surface for the 3D plots are each evaluated in a single vectorized call.

solve: multi-start SLSQP. The objective is non-convex because of the interaction term $\gamma f s$ and the fatigue penalty, so a single starting point could end in a local minimum. The function draws random Dirichlet weights, converts them into a feasible starting allocation (technical spend, sessions, campaigns), clips it into the bounds, and runs SLSQP with the budget as an inequality constraint. Each result is clipped back into the bounds, rejected if it overspends, and the best objective value across all starts wins. A fixed random seed makes the run reproducible. If every start failed, a safe fallback allocation is returned, so the script cannot crash on a bad solve.

Optimal solution and marginal values. After solving, the script prints the allocation, the resulting filter miss rate and click rate, and the expected loss against the no-investment baseline. marginal_gains uses central finite differences to compute the loss reduction per additional thousand dollars on each instrument. This verifies the optimality condition: variables strictly inside their bounds should show nearly identical marginal values, while a variable pinned at a bound can differ.

Grid cross-check. alloc_from_shares reparametrizes the problem with two intuitive numbers: the technical share $\theta$ and the fraction $\phi$ of the human budget given to training. The remainder of the human budget goes to simulations, and the caps $f_{\max}$ and $s_{\max}$ are applied with np.minimum. Evaluating the loss on the full $(\theta,\phi)$ grid gives an independent brute-force estimate of the optimum. The printed difference between solver and grid losses confirms that the solver is at least as good as the best grid point.

Strategy comparison. The optimum is compared against a no-investment baseline, spending everything on filters, spending everything on humans (solved with the technical spend pinned to practically zero), an even split, and an 80/20 technical-heavy split. These are the plans a team might choose by intuition or habit, so the gap to the optimized plan is the value of doing the analysis.

Budget sensitivity. The solver is re-run for budgets from 50 to 400 k USD. This shows how both the achievable loss and the optimal technical share of spending move as the budget changes, which is useful for budget negotiations.

Visualization. All six panels share one figure with a dark theme. Panel (a) is a 3D surface of $\log_{10}\mathcal{L}$ over the allocation shares with the optimum marked. Panel (b) is a 3D triangulated surface over training sessions and simulation campaigns, where the remaining budget automatically goes to the filter. Only the feasible, convex region is triangulated, which avoids gaps and rendering errors. Panel (c) is the contour view of panel (a), with the solver optimum (star) and the grid optimum (circle). Panel (d) is the loss profile along the technical share. Panel (e) is a stacked bar chart of how each strategy spends the budget, with its loss written above each bar. Panel (f) is the budget sensitivity curve with a twin axis for the technical share.

6. Execution Results

==========================================================================
PHISHING DEFENSE: BUDGET ALLOCATION OPTIMIZATION
==========================================================================
Budget B = 200 k USD | emails E = 3000 | loss per compromise L = 4.0 k USD
--------------------------------------------------------------------------
OPTIMAL ALLOCATION (SLSQP, multi-start)
  Email filter spend x        :   147.32 k USD ( 73.7% of budget)
  Training sessions f         :    4.786 per year ->   38.29 k USD
  Simulation campaigns s      :    2.877 per year ->   14.39 k USD
  Total spend                 :   200.00 k USD
  Filter miss rate m(x)       :    3.545 %
  Employee click rate c(f,s)  :    5.457 %
  Expected annual loss        :    23.21 k USD
  Loss with no investment     :   720.00 k USD
--------------------------------------------------------------------------
MARGINAL LOSS REDUCTION PER EXTRA 1 k USD (equal for interior variables)
  Email filter                :     0.1686
  Training sessions           :     0.1686
  Simulation campaigns        :     0.1686
--------------------------------------------------------------------------
GRID CROSS-CHECK (81 x 81 allocations, vectorized)
  Best grid loss              :    23.21 k USD (theta = 0.738, phi = 0.725)
  Solver loss                 :    23.21 k USD
  Solver minus grid           :  -0.0004 k USD (<= 0 means solver is at least as good)
--------------------------------------------------------------------------
STRATEGY COMPARISON
  Strategy               Tech    Train      Sim       Loss   Reduction
  No investment           0.0      0.0      0.0     720.00        0.0%
  Tech only             200.0      0.0      0.0      95.12       86.8%
  Human only              0.0     54.7      9.2     126.34       82.5%
  Even split            100.0     50.0     50.0      53.84       92.5%
  Tech-heavy 80/20      160.0     20.0     20.0      25.56       96.5%
  Optimized             147.3     38.3     14.4      23.21       96.8%
--------------------------------------------------------------------------
BUDGET SENSITIVITY
    Budget   Tech share %   Training f   Simulation s      Loss
        50            9.4         3.70           3.15    132.31
        75           38.7         3.78           3.14     92.04
       100           53.2         3.90           3.12     65.44
       125           61.6         4.06           3.10     47.84
       150           67.1         4.26           3.05     36.17
       175           70.9         4.51           2.98     28.40
       200           73.7         4.79           2.88     23.21
       225           75.8         5.09           2.75     19.74
       250           77.5         5.40           2.61     17.40
       275           78.9         5.70           2.46     15.83
       300           80.2         5.97           2.32     14.77
       325           81.4         6.20           2.20     14.06
       350           82.4         6.38           2.10     13.58
       375           83.4         6.51           2.02     13.26
       400           84.3         6.61           1.96     13.05

--------------------------------------------------------------------------
Total runtime: 6.16 s

7. Reading the Graphs

(a) 3D loss surface over allocation shares. The horizontal axes are the share of the budget given to the email filter and the fraction of the remaining human budget given to training rather than simulation. The vertical axis is $\log_{10}$ of the expected annual loss, so each unit of height is a tenfold change. The surface is high where the technical share is near zero, because the filter then misses a fifth of all phishing mail, and it is also raised on the all-technical edge, where the human layer is missing completely. The valley between them is where both layers work together, and the red marker sits at the bottom of that valley.

(b) 3D loss over the human program. Here the axes are the number of training sessions and simulation campaigns per year, and every point implicitly gives whatever budget is left over to the filter. This panel shows two effects. Spending more on the human program lowers the click rate with diminishing returns, because of the exponential learning term. It also takes money away from the filter, and at high intensity the fatigue penalty pushes the click rate back up. The surface therefore has a basin rather than a slope running to the corner, and the cyan marker shows where the optimum lies in it.

(c) Contour map. The same surface from above. The closed contours around the optimum show how flat or steep the neighborhood is. A long, narrow valley means that several nearby allocations are almost equally good, so a team can shift a little between training and simulation without losing much protection. The star (solver) and the circle (brute-force grid) should land on top of each other.

(d) Loss profile along the technical share. For every technical share, the solid line uses the best possible training fraction, while the dashed line fixes it at 50%. The curve is U-shaped on a log scale: spending nothing on filters and spending everything on filters are both clearly worse than a balanced mix. The gap between the solid and dashed lines shows how much is gained by choosing the training/simulation split deliberately instead of defaulting to half and half.

(e) Strategy comparison. The stacked bars show how each plan divides the budget among filter, training, and simulation, with the expected loss above each bar. The no-investment bar sets the baseline. The tech-only bar shows the limit of a purely technical approach, since the filter can never remove the residual miss rate, and the human-only bar shows the limit of relying on people alone. The optimized bar sits below every intuitive alternative.

(f) Budget sensitivity. The red line is the best achievable loss at each budget, and the blue dashed line is the share of spending that goes to the filter. The red curve falls as the budget grows, with diminishing returns once both layers are strong. The blue curve shows whether the optimal mix shifts toward technology or toward people as the budget gets larger, which is the practical answer to the question “if we get more money next year, where should it go?”

8. Conclusion

Phishing defense is a multiplicative problem. A compromise needs a filter miss and a human click, so reducing either factor shrinks the expected loss proportionally. Because both layers show diminishing returns, the best plan is almost never a single-layer plan. The optimum equalizes the marginal loss reduction per dollar across filter spending, training sessions, and simulation campaigns, subject to the practical caps on program intensity. A multi-start SLSQP solver finds that point quickly, and a vectorized grid confirms it independently.

The same framework extends naturally to richer settings, such as role-based risk weights for high-value targets, adaptive attackers whose success rate rises when filters improve, or time-varying budgets across quarters. All of these can be added by modifying the model functions while the solver and plotting code stay unchanged.