Minimizing Third-Party Data Sharing with Python

Share Only What Each Vendor’s Contract Requires

Most companies send customer data to outside vendors: a marketing analytics agency, a fraud-scoring service, a university research team. The easy option is to export the whole customer table and let each vendor take what it needs. It is also the riskiest option. Every extra column, every extra row and every extra digit of precision adds exposure, and data protection laws such as GDPR’s data minimisation principle (Art. 5(1)(c)) say you should share only what is “adequate, relevant and limited to what is necessary.”

This article turns that principle into an optimization problem and solves it in Python. Each vendor contract sets out which attributes the vendor needs, how precise they must be, how large anonymity groups must be, and how identifiers are handled. For each vendor, the code finds the smallest release that still meets every one of those terms.


The Problem Setup

We start from a synthetic customer master table with 60,000 records:

Column Type
customer_id, name, email, phone Direct identifiers
age, zip, gender, income, purchase_total Quasi-identifiers (QIs)
consent_marketing, consent_research, fraud_scope Purpose / consent flags

Three vendors each have a contract:

Vendor Rows allowed Required attributes (coarsest acceptable level) Min. class size $k$ Max. suppression Identifiers
Marketing Analytics marketing consent only age ≤ 10-yr band, ZIP ≤ 3 digits, gender raw, purchase ≤ $500 band 10 5% dropped
Fraud Scoring in-scope accounts only ZIP ≤ 4 digits, purchase ≤ $500 band 3 5% pseudonymized token
Academic Research research consent only age ≤ 20-yr band, income ≤ $50k band, gender optional 25 1% dropped

The goal is to find the release for each vendor that shares the least data while meeting its contract.


Mathematical Formulation

Generalization lattice

Each quasi-identifier $j$ has a generalization hierarchy with levels $\ell_j \in {0, 1, \dots, L_j - 1}$. Level $0$ is the raw value and level $L_j - 1$ means the column is removed (suppressed):

  • age: exact → 5-yr → 10-yr → 20-yr → removed ($L=5$)
  • zip: 5 digits → 4 digits → 3 digits → removed ($L=4$)
  • gender: raw → removed ($L=2$)
  • income: $1k → $10k → $50k bands → removed ($L=4$)
  • purchase_total: $1 → $100 → $500 bands → removed ($L=4$)

One candidate release is a vector $\boldsymbol{\ell} = (\ell_{\text{age}}, \ell_{\text{zip}}, \ell_{\text{gender}}, \ell_{\text{income}}, \ell_{\text{purchase}})$. The full lattice has

$$
|\mathcal{L}| = \prod_j L_j = 5 \times 4 \times 2 \times 4 \times 4 = 640
$$

nodes.

Equivalence classes and re-identification risk

For a release $\boldsymbol{\ell}$, two records belong to the same equivalence class if their generalized QI values are identical. Let $|EC(i)|$ be the size of the class that contains record $i$. Under the prosecutor attack model, the probability of re-identifying record $i$ is

$$
r_i(\boldsymbol{\ell}) = \frac{1}{|EC(i)|}.
$$

The release is $k$-anonymous when $\min_i |EC(i)| \ge k$. Records in classes smaller than $k$ may be suppressed, up to the contractual limit $s_{\max}$:

$$
\frac{1}{n}\sum_{i=1}^{n} \mathbf{1}\big[,|EC(i)| < k,\big] \le s_{\max}.
$$

The mean re-identification risk over the records that are actually released ($\mathcal{K}$) is

$$
\bar{R}(\boldsymbol{\ell}) = \frac{1}{|\mathcal{K}|}\sum_{i \in \mathcal{K}} \frac{1}{|EC(i)|}.
$$

Disclosure score and contract utility

Each attribute has a sensitivity weight $w_j$ (income and ZIP count most). The precision kept for an attribute is $1 - \ell_j/(L_j-1)$, so the disclosure score is

$$
D(\boldsymbol{\ell}) = \sum_{j} w_j \left(1 - \frac{\ell_j}{L_j - 1}\right).
$$

Contract utility is the mean retained precision over the attributes the vendor requires, $\mathcal{R}_v$:

Optimization problem

For vendor $v$, with precision limits $\ell_j^{\max}$, anonymity threshold $k_v$ and suppression limit $s_v$:

with $\lambda = 20$. Attributes the vendor does not need have no upper limit on $\ell_j$, so the optimizer always drops them: removing a column lowers $D$ and never raises $\bar{R}$. Two more steps sit outside the lattice and shrink the release further:

  1. Row minimization: only records with the right consent or purpose flag are considered ($n \to n_v$).
  2. Identifier handling: direct identifiers are dropped, or replaced with a vendor-specific keyed hash $\text{token}_v(i) = \text{HMAC-SHA256}(K_v, i)$, so two vendors cannot join their datasets on a shared ID.

The expensive step is counting equivalence-class sizes for every lattice node. The straightforward approach rebuilds a generalized DataFrame for each node and runs groupby(...).transform("size").

The faster version does two things:

  1. Pre-encodes every attribute at every generalization level once, as dense integer codes (np.unique(..., return_inverse=True)).
  2. For each node, combines the codes into a single int64 key with mixed-radix arithmetic,

where $B_j$ is the number of distinct codes for attribute $j$ at its chosen level. A single np.unique(..., return_counts=True) call then gives every record’s class size.

The script runs both methods on the same nodes, uses an assert to check that they return identical results, and prints the measured speed-up. The full search covers 640 nodes for each of the three vendors.


Source Code

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

# ------------------------------------------------------------
# 1. Synthetic customer master table
# ------------------------------------------------------------
rng = np.random.default_rng(42)
N = 60_000

zip_prefix = rng.choice(np.arange(100, 125), size=N)
zip5 = zip_prefix * 100 + rng.integers(0, 100, size=N)
age = np.clip(rng.normal(44, 15, size=N).round(), 18, 95).astype(int)
gender = rng.choice([0, 1], size=N)
income = np.clip(rng.lognormal(np.log(55_000), 0.5, size=N), 8_000, 600_000).round(-3).astype(int)
purchase = np.clip(rng.gamma(2.0, 180.0, size=N), 1, 8_000).round(2)
consent_marketing = rng.random(N) < 0.62
consent_research = rng.random(N) < 0.48
active_fraud_scope = rng.random(N) < 0.35

df = pd.DataFrame({
"customer_id": np.arange(1, N + 1),
"name": [f"Customer {i}" for i in range(1, N + 1)],
"email": [f"user{i}@example.com" for i in range(1, N + 1)],
"phone": [f"+1-555-{i:07d}" for i in range(1, N + 1)],
"age": age,
"zip": zip5,
"gender": gender,
"income": income,
"purchase_total": purchase,
"consent_marketing": consent_marketing,
"consent_research": consent_research,
"fraud_scope": active_fraud_scope,
})

# ------------------------------------------------------------
# 2. Generalization hierarchies (level 0 = raw, last level = suppressed)
# ------------------------------------------------------------
QI = ["age", "zip", "gender", "income", "purchase_total"]
LEVELS = {"age": 5, "zip": 4, "gender": 2, "income": 4, "purchase_total": 4}
SENSITIVITY = {"age": 1.0, "zip": 1.5, "gender": 0.5, "income": 2.0, "purchase_total": 1.0}


def generalize(col, values, level):
v = np.asarray(values)
if col == "age":
widths = [1, 5, 10, 20]
if level == 4:
return np.zeros_like(v)
return (v // widths[level]) * widths[level]
if col == "zip":
divs = [1, 10, 100]
if level == 3:
return np.zeros_like(v)
return v // divs[level]
if col == "gender":
return v if level == 0 else np.zeros_like(v)
if col == "income":
widths = [1_000, 10_000, 50_000]
if level == 3:
return np.zeros_like(v)
return (v // widths[level]) * widths[level]
if col == "purchase_total":
widths = [1, 100, 500]
if level == 3:
return np.zeros_like(v, dtype=np.int64)
return (np.floor(v / widths[level]) * widths[level]).astype(np.int64)
raise ValueError(col)


def label_value(col, values, level):
g = generalize(col, values, level)
last = LEVELS[col] - 1
if level == last:
return None
if col == "age" and level > 0:
w = [1, 5, 10, 20][level]
return pd.Series(g).astype(str) + "-" + pd.Series(g + w - 1).astype(str)
if col == "zip" and level > 0:
return pd.Series(g).astype(str) + "*" * level
if col == "income" and level > 0:
w = [1_000, 10_000, 50_000][level]
return pd.Series(g).astype(str) + "-" + pd.Series(g + w - 1).astype(str)
if col == "purchase_total" and level > 0:
w = [1, 100, 500][level]
return pd.Series(g).astype(str) + "-" + pd.Series(g + w).astype(str)
return pd.Series(g)


# ------------------------------------------------------------
# 3. Vendor contracts
# max_level : required attributes and the coarsest level still acceptable
# k : minimum equivalence-class size
# supp : max fraction of records that may be suppressed
# id_mode : "drop" / "pseudonym" / "raw" for direct identifiers
# ------------------------------------------------------------
CONTRACTS = {
"Marketing Analytics": {
"row_filter": "consent_marketing",
"max_level": {"age": 2, "zip": 2, "gender": 0, "purchase_total": 2},
"k": 10, "supp": 0.05, "id_mode": "drop",
},
"Fraud Scoring": {
"row_filter": "fraud_scope",
"max_level": {"zip": 1, "purchase_total": 2},
"k": 3, "supp": 0.05, "id_mode": "pseudonym",
},
"Academic Research": {
"row_filter": "consent_research",
"max_level": {"age": 3, "income": 2, "gender": 1},
"k": 25, "supp": 0.01, "id_mode": "drop",
},
}
LAMBDA = 20.0 # weight of re-identification risk in the disclosure score


# ------------------------------------------------------------
# 4. Equivalence-class statistics: naive (pandas groupby) vs fast (integer keys)
# ------------------------------------------------------------
def class_sizes_naive(frame, levels):
tmp = pd.DataFrame({c: generalize(c, frame[c].values, l) for c, l in zip(QI, levels)})
return tmp.groupby(QI, sort=False)[QI[0]].transform("size").values


def build_codes(frame):
codes = {}
for c in QI:
codes[c] = []
for l in range(LEVELS[c]):
_, inv = np.unique(generalize(c, frame[c].values, l), return_inverse=True)
codes[c].append(inv.astype(np.int64).ravel())
return codes


def class_sizes_fast(codes, levels):
key = np.zeros_like(codes[QI[0]][0])
for c, l in zip(QI, levels):
arr = codes[c][l]
key = key * (int(arr.max()) + 1) + arr
_, inv, cnt = np.unique(key, return_inverse=True, return_counts=True)
return cnt[inv.ravel()]


def evaluate(sizes, k, supp, n):
small = sizes < k
n_supp = int(small.sum())
kept = sizes[~small]
k_min = int(kept.min()) if kept.size else 0
risk = float(np.mean(1.0 / kept)) if kept.size else 1.0
max_risk = float(1.0 / k_min) if k_min else 1.0
return {"k_min": k_min, "supp_rate": n_supp / n, "mean_risk": risk,
"raw_risk": float(np.mean(1.0 / sizes)),
"max_risk": max_risk, "feasible_k": n_supp <= supp * n}


def disclosure(levels):
return sum(SENSITIVITY[c] * (1 - l / (LEVELS[c] - 1)) for c, l in zip(QI, levels))


def utility(levels, contract):
req = contract["max_level"]
vals = [1 - l / (LEVELS[c] - 1) for c, l in zip(QI, levels) if c in req]
return float(np.mean(vals))


LATTICE = list(itertools.product(*[range(LEVELS[c]) for c in QI]))

# ------------------------------------------------------------
# 5. Speed comparison on the full dataset
# ------------------------------------------------------------
sample_nodes = LATTICE[:40]
t0 = time.perf_counter()
for node in sample_nodes:
class_sizes_naive(df, node)
t_naive = (time.perf_counter() - t0) / len(sample_nodes)

codes_all = build_codes(df)
t0 = time.perf_counter()
for node in sample_nodes:
class_sizes_fast(codes_all, node)
t_fast = (time.perf_counter() - t0) / len(sample_nodes)

check_node = (1, 2, 0, 1, 2)
assert np.array_equal(class_sizes_naive(df, check_node), class_sizes_fast(codes_all, check_node))

print("=== Performance ===")
print(f"Lattice nodes : {len(LATTICE)}")
print(f"Naive groupby per node : {t_naive * 1000:8.2f} ms")
print(f"Fast integer-key per node : {t_fast * 1000:8.2f} ms")
print(f"Speed-up : {t_naive / t_fast:8.1f}x")
print(f"Estimated full-lattice naive : {t_naive * len(LATTICE):8.2f} s")


# ------------------------------------------------------------
# 6. Search the lattice for each vendor
# ------------------------------------------------------------
def pseudonymize(ids, vendor):
key = hashlib.sha256(("vendor-secret::" + vendor).encode()).digest()
return [hmac.new(key, str(i).encode(), hashlib.sha256).hexdigest()[:16] for i in ids]


results = {}
tables = {}
for vendor, ct in CONTRACTS.items():
sub = df[df[ct["row_filter"]]].reset_index(drop=True)
n = len(sub)
codes = build_codes(sub)
rows = []
for node in LATTICE:
lv = dict(zip(QI, node))
precision_ok = all(lv[c] <= ct["max_level"].get(c, LEVELS[c] - 1) for c in QI)
sizes = class_sizes_fast(codes, node)
ev = evaluate(sizes, ct["k"], ct["supp"], n)
d = disclosure(node)
rows.append({"node": node, **lv, "disclosure": d,
"utility": utility(node, ct),
"score": d + LAMBDA * ev["mean_risk"],
"precision_ok": precision_ok,
"feasible": precision_ok and ev["feasible_k"], **ev})
tab = pd.DataFrame(rows)
feas = tab[tab["feasible"]].sort_values(["score", "mean_risk"])
if feas.empty:
raise RuntimeError(f"No feasible release for {vendor}")
best = feas.iloc[0]
tables[vendor] = tab

node = best["node"]
sizes = class_sizes_fast(codes, node)
keep = sizes >= ct["k"]
release = pd.DataFrame(index=np.arange(n))
if ct["id_mode"] == "pseudonym":
release["token"] = pseudonymize(sub["customer_id"].values, vendor)
for c, l in zip(QI, node):
lab = label_value(c, sub[c].values, l)
if lab is not None:
release[c] = lab.values
release = release[keep].reset_index(drop=True)

raw_sizes = class_sizes_fast(codes, (0, 0, 0, 0, 0))
results[vendor] = {
"best": best, "release": release, "n_rows_in": n, "sizes": sizes[keep],
"raw_sizes": raw_sizes,
"full_cells": N * (len(df.columns) - 4),
"min_cells": release.shape[0] * release.shape[1],
}

print("\n=== Minimized releases ===")
for vendor, r in results.items():
b = r["best"]
ct = CONTRACTS[vendor]
print(f"\n[{vendor}] k>={ct['k']}, identifiers={ct['id_mode']}")
print(" levels :", {c: int(b[c]) for c in QI})
print(f" rows : {N} -> {r['n_rows_in']} (purpose filter) -> {len(r['release'])} (after suppression)")
print(f" columns : {len(df.columns) - 4} -> {r['release'].shape[1]} {list(r['release'].columns)}")
print(f" cells : {r['full_cells']:,} -> {r['min_cells']:,} "
f"({100 * (1 - r['min_cells'] / r['full_cells']):.1f}% reduction)")
print(f" k_min={b['k_min']}, mean re-id risk={b['mean_risk']:.4f}, "
f"max risk={b['max_risk']:.4f}, suppressed={100 * b['supp_rate']:.2f}%")
print(f" raw-QI mean re-id risk={np.mean(1 / r['raw_sizes']):.4f}")
print(" sample:")
print(r["release"].head(3).to_string(index=False))

# ------------------------------------------------------------
# 7. Visualization (2 rows x 3 columns)
# ------------------------------------------------------------
vendors = list(CONTRACTS)
short = ["Marketing", "Fraud", "Research"]
colors = ["#1f77b4", "#ff7f0e", "#2ca02c"]

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

# (1) Cells shared: full export vs minimized
ax1 = fig.add_subplot(2, 3, 1)
x = np.arange(len(vendors))
full = [results[v]["full_cells"] / 1e3 for v in vendors]
mini = [results[v]["min_cells"] / 1e3 for v in vendors]
ax1.bar(x - 0.2, full, 0.4, label="Full export", color="#bbbbbb")
ax1.bar(x + 0.2, mini, 0.4, label="Minimized", color=colors)
for i in range(len(vendors)):
ax1.text(x[i] + 0.2, mini[i], f"-{100 * (1 - mini[i] / full[i]):.0f}%", ha="center", va="bottom")
ax1.set_xticks(x)
ax1.set_xticklabels(short)
ax1.set_ylabel("Data cells shared (thousands)")
ax1.set_title("(1) Data volume: full export vs minimized")
ax1.legend()

# (2) Disclosure vs risk (Marketing)
ax2 = fig.add_subplot(2, 3, 2)
tab = tables[vendors[0]]
b = results[vendors[0]]["best"]
m_coarse = ~tab.precision_ok
m_kfail = tab.precision_ok & ~tab.feasible
m_ok = tab.feasible
ax2.scatter(tab.loc[m_coarse, "disclosure"], tab.loc[m_coarse, "raw_risk"],
s=10, c="#cccccc", label="Too coarse for contract")
ax2.scatter(tab.loc[m_kfail, "disclosure"], tab.loc[m_kfail, "raw_risk"],
s=30, c="#ff7f0e", label="Fails k-anonymity")
ax2.scatter(tab.loc[m_ok, "disclosure"], tab.loc[m_ok, "raw_risk"],
s=40, c="#1f77b4", label="Fully compliant")
ax2.scatter([b["disclosure"]], [b["raw_risk"]], s=300, marker="*", c="red", label="Selected", zorder=5)
ax2.set_yscale("log")
ax2.set_xlabel("Disclosure score D")
ax2.set_ylabel("Mean re-identification risk")
ax2.set_title("(2) Lattice search: Marketing Analytics")
ax2.legend()

# (3) 3D surface: risk vs age/zip generalization
ax3 = fig.add_subplot(2, 3, 3, projection="3d")
fixed = {c: int(b[c]) for c in ["gender", "income", "purchase_total"]}
sub_t = tab[(tab.gender == fixed["gender"]) & (tab.income == fixed["income"]) &
(tab.purchase_total == fixed["purchase_total"])]
A, Z = np.meshgrid(np.arange(LEVELS["age"]), np.arange(LEVELS["zip"]))
R = np.zeros_like(A, dtype=float)
for _, r in sub_t.iterrows():
R[int(r.zip), int(r.age)] = np.log10(r.raw_risk)
ax3.plot_surface(A, Z, R, cmap="viridis", edgecolor="k", linewidth=0.3, alpha=0.9)
ax3.scatter([b["age"]], [b["zip"]], [np.log10(b["raw_risk"])], c="red", s=200, marker="*")
ax3.set_xlabel("Age level")
ax3.set_ylabel("ZIP level")
ax3.set_zlabel("log10 mean risk")
ax3.set_title("(3) Risk surface (Marketing)")
ax3.view_init(elev=28, azim=-135)

# (4) Equivalence class size distribution
ax4 = fig.add_subplot(2, 3, 4)
bins = np.logspace(0, 4, 40)
ax4.hist(results[vendors[0]]["raw_sizes"], bins=bins, alpha=0.6, color="#999999", label="Raw quasi-identifiers")
for v, c, s in zip(vendors, colors, short):
ax4.hist(results[v]["sizes"], bins=bins, histtype="step", lw=2, color=c, label=s)
ax4.set_xscale("log")
ax4.set_yscale("log")
ax4.set_xlabel("Equivalence class size (records)")
ax4.set_ylabel("Number of records")
ax4.set_title("(4) Equivalence class sizes")
ax4.legend()

# (5) Heatmap of retained precision
ax5 = fig.add_subplot(2, 3, 5)
attrs = ["name/email/phone"] + QI
M = np.zeros((len(vendors), len(attrs)))
for i, v in enumerate(vendors):
mode = CONTRACTS[v]["id_mode"]
M[i, 0] = {"raw": 1.0, "pseudonym": 0.5, "drop": 0.0}[mode]
for j, c in enumerate(QI):
M[i, j + 1] = 1 - results[v]["best"][c] / (LEVELS[c] - 1)
im = ax5.imshow(M, cmap="RdYlGn_r", vmin=0, vmax=1, aspect="auto")
for i in range(M.shape[0]):
for j in range(M.shape[1]):
ax5.text(j, i, f"{M[i, j]:.2f}", ha="center", va="center", fontsize=10)
ax5.set_xticks(range(len(attrs)))
ax5.set_xticklabels(attrs, rotation=30, ha="right")
ax5.set_yticks(range(len(vendors)))
ax5.set_yticklabels(short)
ax5.set_title("(5) Retained precision per vendor (0 = removed)")
fig.colorbar(im, ax=ax5, fraction=0.046)

# (6) 3D scatter: utility / disclosure / risk for all vendors
ax6 = fig.add_subplot(2, 3, 6, projection="3d")
for v, c, s in zip(vendors, colors, short):
t = tables[v]
f = t[t.precision_ok]
ax6.scatter(f["utility"], f["disclosure"], np.log10(f["raw_risk"]), s=14, c=c, alpha=0.5, label=s)
bb = results[v]["best"]
ax6.scatter([bb["utility"]], [bb["disclosure"]], [np.log10(bb["raw_risk"])],
s=220, c=c, marker="*", edgecolor="k")
ax6.set_xlabel("Contract utility U")
ax6.set_ylabel("Disclosure D")
ax6.set_zlabel("log10 mean risk")
ax6.set_title("(6) Granularity-compliant candidates (stars = selected)")
ax6.legend()

plt.tight_layout()
plt.show()

Code Walkthrough

1. Synthetic customer master table

np.random.default_rng(42) makes the run reproducible. Ages follow a clipped normal distribution, income a log-normal and purchase totals a gamma distribution, which gives realistic long tails. Those tails are exactly the records that end up in small, risky equivalence classes. ZIP codes are built from 25 three-digit prefixes plus two random digits, so coarsening ZIP has a real effect. The three boolean flags stand for consent and business purpose. They drive row-level minimization: a vendor never sees a customer who has not consented to that use.

2. Generalization hierarchies

generalize(col, values, level) maps raw values to their generalized form with vectorized NumPy arithmetic only:

  • Banding is integer floor division followed by multiplication: (v // w) * w.
  • ZIP truncation is v // 10**d.
  • The last level of each hierarchy returns a constant array, which means the column is effectively removed.

label_value turns the generalized numbers into readable labels such as 40-59, 102** or 100000-149999 for the actual vendor file. It returns None for suppressed columns, so they never appear in the release.

SENSITIVITY holds the weights $w_j$: income (2.0) and ZIP (1.5) are treated as most sensitive, gender (0.5) as least sensitive.

3. Vendor contracts

Each contract is a plain dictionary, so legal and compliance staff can review it without reading the algorithm:

  • row_filter: the consent or purpose column that decides which rows the vendor may receive.
  • max_level: the required attributes and the coarsest level each one may be generalized to. Any attribute missing from this dictionary is not required, so the optimizer is free to remove it.
  • k and supp: the $k$-anonymity threshold and the share of records that may be suppressed.
  • id_mode: whether direct identifiers are dropped or replaced with pseudonyms.

4. Equivalence-class computation (naive vs fast)

  • class_sizes_naive is the textbook implementation: build a new DataFrame, run groupby on all QIs and broadcast the group size back to each row.
  • build_codes runs once per dataset. For every attribute and level it stores a dense integer code array, so no generalization work is repeated inside the lattice loop.
  • class_sizes_fast folds the five code arrays into one int64 key with the mixed-radix formula above. One np.unique(..., return_counts=True) then returns all class sizes, and cnt[inv] maps each count back to its record.
  • evaluate derives the contract metrics: records that must be suppressed, $k_{\min}$ after suppression, the mean risk $\bar{R}$ over released records, the pre-suppression risk raw_risk (used for the plots), and whether the suppression limit is met.

5. Performance check

Both methods run on the same 40 lattice nodes. The script reports the time per node and the speed-up, and an assert confirms the two methods give identical class sizes. You get the faster code with a built-in correctness check.

6. Lattice search and release construction

For each vendor:

  1. Apply the row filter (purpose limitation).
  2. Pre-encode the filtered data.
  3. Evaluate all 640 nodes and record $D$, $U_v$, $\bar{R}$, $J$, and whether the node passes the precision limits and the $k$/suppression limits.
  4. Sort the feasible nodes by $J = D + \lambda\bar{R}$ and take the best.
  5. Build the actual release. Add an HMAC pseudonym if the contract allows one, emit only the columns that were not suppressed, and drop the records in classes smaller than $k$.

The HMAC key is derived per vendor, so the same customer gets a different token at each vendor. That blocks cross-vendor linkage while still letting the fraud vendor track a customer across its own submissions.

full_cells is the “export everything” baseline: 60,000 rows × 8 content columns. min_cells is the size of the minimized file.

7. Visualization

plt.figure(figsize=(21, 13)) with add_subplot(2, 3, k) produces one figure with six panels in two rows of three. Two of the panels are 3D (projection="3d").


Execution Results

=== Performance ===
Lattice nodes                : 640
Naive groupby per node       :    32.59 ms
Fast integer-key per node    :     5.83 ms
Speed-up                     :      5.6x
Estimated full-lattice naive :    20.86 s

=== Minimized releases ===

[Marketing Analytics]  k>=10, identifiers=drop
  levels  : {'age': 2, 'zip': 2, 'gender': 0, 'income': 3, 'purchase_total': 2}
  rows    : 60000 -> 37250 (purpose filter) -> 35445 (after suppression)
  columns : 8 -> 4  ['age', 'zip', 'gender', 'purchase_total']
  cells   : 480,000 -> 141,780 (70.5% reduction)
  k_min=10, mean re-id risk=0.0175, max risk=0.1000, suppressed=4.85%
  raw-QI mean re-id risk=1.0000
  sample:
  age   zip  gender purchase_total
50-59 102**       1          0-500
50-59 110**       1          0-500
20-29 102**       0          0-500

[Fraud Scoring]  k>=3, identifiers=pseudonym
  levels  : {'age': 4, 'zip': 1, 'gender': 1, 'income': 3, 'purchase_total': 2}
  rows    : 60000 -> 21149 (purpose filter) -> 20897 (after suppression)
  columns : 8 -> 3  ['token', 'zip', 'purchase_total']
  cells   : 480,000 -> 62,691 (86.9% reduction)
  k_min=3, mean re-id risk=0.0273, max risk=0.3333, suppressed=1.19%
  raw-QI mean re-id risk=1.0000
  sample:
           token   zip purchase_total
f13a38a4aedca985 1020*          0-500
844389cf91ac3c23 1193*          0-500
469545886617eb34 1101*          0-500

[Academic Research]  k>=25, identifiers=drop
  levels  : {'age': 3, 'zip': 3, 'gender': 1, 'income': 2, 'purchase_total': 3}
  rows    : 60000 -> 29017 (purpose filter) -> 28900 (after suppression)
  columns : 8 -> 2  ['age', 'income']
  cells   : 480,000 -> 57,800 (88.0% reduction)
  k_min=36, mean re-id risk=0.0007, max risk=0.0278, suppressed=0.40%
  raw-QI mean re-id risk=1.0000
  sample:
  age        income
40-59 100000-149999
20-39       0-49999
20-39       0-49999


Interpreting the Results

Console output

The performance section shows that the integer-key method is several times faster per lattice node than the pandas groupby version. Exact timings depend on the runtime. The search evaluates $3 \times 640 = 1{,}920$ nodes in total. At this data size the naive version still finishes in seconds, but the gap widens with larger tables, more QIs and deeper hierarchies, where lattices quickly reach tens of thousands of nodes.

The minimized-release section shows how much less each vendor receives:

Vendor Rows Columns Cells shared $k_{\min}$ Suppressed
Marketing Analytics 60,000 → 37,250 → 35,445 8 → 4 −70.5% 10 4.85%
Fraud Scoring 60,000 → 21,149 → 20,897 8 → 3 (token + 2) −86.9% 3 1.19%
Academic Research 60,000 → 29,017 → 28,900 8 → 2 −88.0% 36 0.40%

On the raw quasi-identifiers the mean re-identification risk is $\bar{R} = 1.0$: every customer is unique on age + 5-digit ZIP + gender + exact income + exact purchase. After minimization, risk falls to about 0.0175 for Marketing, about 0.027 for Fraud and about 0.0007 for Research. Each contract’s $k$ bound also limits the worst-case risk to at most $1/k$.

Some details to note:

  • Marketing keeps gender at full precision because the contract requires it. That forces age into 10-year bands and ZIP to 3 digits. Income, which the contract does not require, is removed even though it is the most sensitive attribute.
  • Fraud Scoring receives only a vendor-specific token, a 4-digit ZIP and a $500 purchase band. Age, gender and income are removed because the contract does not need them.
  • Research needs only age and income bands. Gender is optional under its contract, so the optimizer drops it. With such a high $k$ (25), every extra attribute would cost suppressed records.

Graph (1): Data volume

The grey bars show the full export (480,000 cells per vendor) and the colored bars show the minimized release. The labels give a 70–88% reduction. This is the most direct measure of data minimization: every cell that is not shared cannot leak.

Graph (2): Lattice search for Marketing Analytics

Each dot is one of the 640 candidate releases, plotted as disclosure score $D$ against pre-suppression mean risk (log scale). The two quantities rise together: the more precision you share, the more unique each record becomes.

  • Grey nodes are too coarse; they fail the contract’s precision requirement.
  • Orange nodes keep enough precision but fail $k$-anonymity within the 5% suppression budget.
  • The red star is the only release that meets both: the minimum-disclosure release that is still useful under the contract.

Graph (3): 3D risk surface

With gender, income and purchase fixed at the chosen levels, the surface shows $\log_{10}\bar{R}$ as age generalization (x-axis) and ZIP generalization (y-axis) vary. Risk falls steadily as either attribute is coarsened, and the two attributes partly substitute for each other. The red star marks the corner the contract allows: the finest age and ZIP precision the vendor needs, made acceptable by the $k = 10$ requirement and the suppression budget.

Graph (4): Equivalence-class sizes

On log-log axes, the grey bar at size 1 shows the raw data: almost every record is in a class of one, so it is uniquely identifiable. After minimization, the class-size distributions shift to the right. Marketing and Fraud classes cluster around tens to hundreds of records. Research classes run into the thousands because it receives only two coarse attributes. No released record falls below its contract’s $k$.

Graph (5): Retained-precision heatmap

Rows are vendors and columns are attributes. Each cell is the share of precision kept: 1.00 means raw, 0.00 means removed, and 0.50 for identifiers means pseudonymized. The heatmap makes a good summary of the outcome for a data protection impact assessment (DPIA) or a vendor audit. Most of it is green (removed), with red or orange only where a contract needs precision: gender for Marketing, ZIP and the pseudonym for Fraud.

Graph (6): 3D utility–disclosure–risk space

Every candidate that meets a vendor’s precision requirements is plotted by contract utility $U_v$, disclosure $D$ and $\log_{10}$ risk. Within each vendor’s cloud, higher disclosure brings higher risk. The selected releases (stars) sit at the low-disclosure, low-risk edge of their clouds. Research sits furthest toward the low-risk corner because its contract asks for the least information and sets the highest $k$.


Takeaways

  • Data minimization can be computed. Once contract requirements are written as precision limits, a $k$-anonymity threshold and a suppression budget, finding the minimal release becomes a constrained search over a generalization lattice.
  • Minimize on three axes: rows (purpose and consent filters), columns (drop anything not required) and precision (generalize to the coarsest acceptable level).
  • Pseudonymize per vendor. Keyed HMAC tokens with a different key for each vendor let a vendor link its own records without letting vendors link to each other.
  • Optimize the hot loop. Pre-encoding attributes and computing class sizes from a single integer key per node gives the same answer as groupby in a fraction of the time, which matters once the lattice or dataset grows.
  • Use the outputs as audit evidence. The disclosure score, $k_{\min}$, suppression rate and retained-precision heatmap show that each third-party release is limited to what the contract needs.