Algorithmcore
Samarati's algorithm
Also called binary search over the generalization lattice.
Binary searches the heights of the full-domain generalization lattice for the lowest height with a k-anonymous node within a suppression limit.
- Time
- O(n d g log h) worst
- Space
- O(n d + g d) extra
- Where
- d = the number of quasi-identifier attributes; g = the number of vectors of the lattice; h = the height of the top vector; n = the number of rows
- Model
- Word RAM
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Pierangela Samarati, 2001
Samarati's algorithm finds a full-domain generalization of a table that is k-anonymous after the removal of at most MaxSup rows, and that generalizes as little as possible. It searches the lattice of generalization vectors, where the height of a vector is the total number of generalization steps. The number of removed rows can only fall when a vector goes up, so the algorithm does a binary search on the height. The result has the least height, and no vector strictly below it works, so it is a k-minimal generalization in the sense of Samarati (2001).
In plain words
Each quasi-identifier attribute can be written at several levels of detail, from the raw value to a single star. Choose a level for each attribute, and add up the levels: that is the height of the choice. A low height keeps much detail. At each height there are several choices. Test them: a choice works if, after the table is coarsened, at most MaxSup rows are in groups of fewer than equal rows. Those rows are deleted.
If some choice works at a height, then some choice works at each greater height, because coarser values only make groups bigger. So the heights split into a low part where nothing works and a high part where something works. Binary search finds the boundary. Then return the first working choice at that height.
The problem
The input is a table of rows with quasi-identifier attributes, a tree hierarchy for each attribute with levels (see generalization and suppression), an integer and a limit MaxSup . A vector with satisfies if, in generalized by , at most MaxSup rows are in classes of fewer than rows. The output is a satisfying vector of least height , or NIL if no vector satisfies. The top vector is with height , and the lattice has vectors. and MaxSup are policy choices.
The algorithm
SAMARATI(T, H, k, MaxSup)- 1
if not SATISFIES(T, top, k, MaxSup) then return NIL - 2
low ← 0, high ← height(top) - 3
sol ← top - 4
while low < high do - 5
try ← ⌊(low + high) / 2⌋ - 6
found ← NIL - 7
for each vector v with height(v) = try, in lexicographic order do - 8
if SATISFIES(T, v, k, MaxSup) then found ← v; exit the loop - 9
if found ≠ NIL then sol ← found, high ← try - 10
else low ← try + 1 - 11
return sol SATISFIES(T, v, k, MaxSup)- 12
count the rows of each tuple of T generalized by v, in a hash table - 13
s ← the number of rows whose tuple has a count < k - 14
return s ≤ MaxSup
Line L1 tests the top vector first. If even the top fails, no vector can satisfy. Lines L4 to L10 keep the least satisfying height in , and sol is always a satisfying vector at height . The release is the table generalized by sol without the rows of line L13.
Samarati (2001) adds a matrix of distance vectors between the tuples of , which lets the test skip vectors that cannot work. It is an optimization and does not change the answer.
Example
Take the 9 rows of Ciriani et al. (2007): asian 94142, asian 94141, three rows of asian 94139, black 94138, black 94139, white 94139 and white 94141. Race has levels R0 and R1 (person), and ZIP has levels Z0 (5 digits), Z1 (9414* or 9413*) and Z2 (941**), so . Let and MaxSup = 2.
| step | low | high | try | vectors tested at try | rows to suppress | sol |
|---|---|---|---|---|---|---|
| L1 | (1, 2) | 0 | ||||
| start | 0 | 3 | (1, 2) | |||
| 1 | 0 | 3 | 1 | (0, 1) | 2: white 9413*, white 9414* | (0, 1) |
| 2 | 0 | 1 | 0 | (0, 0) | 6 | (0, 1) |
| end | 1 | 1 | (0, 1) |
The result is (0, 1): keep the race and cut the ZIP to 4 digits, and suppress the two white rows. The vector (1, 0) also has height 1 and suppresses 2 rows, so it is also 2-minimal. The algorithm returns (0, 1) only because it comes first in lexicographic order. With MaxSup = 0, the answer is (0, 2), and with MaxSup = 9 it is (0, 0).
Correctness
The proof rests on monotonicity. With tree hierarchies, if then each class of at is a union of classes at , so a row that is not suppressed at is not suppressed at . So if a vector of height satisfies, raising one of its levels gives a satisfying vector of height . The predicate "some vector of height satisfies" is false below the least height and true from to . The loop of line L4 keeps the invariant , with sol the first satisfying vector at height . Each step halves the range, and at the end . No satisfying vector lies strictly below sol, because it would have a smaller height. The full proof is in proofs/correctness.md.
Proof: Samarati's algorithm returns a k-minimal generalization of minimal heightfull
We use the notation of the page. The table has rows and quasi-identifier attributes. Attribute has a hierarchy with levels , and each level coarsens the level below it: the value at level is a function of the value at level . A vector has for each , its height is , and means for each . The top vector is and . We write for generalized by , and for the number of rows of whose combination of values occurs fewer than times. Lines L12 and L13 compute , so SATISFIES is true if and only if . We say that satisfies when this is true.
Lemma 1 (monotonicity). If , then .
Proof. Because each level is a function of the level below it, the value of a row at level is a function of its value at level . So two rows that are equal in are equal in , and each group of equal rows of is a union of groups of . A row that is in a group of at least rows in is therefore in a group of at least rows in . So the rows counted by are a subset of the rows counted by .
Let be the statement "some vector of height satisfies".
Lemma 2. If is true and , then is true.
Proof. Let satisfy with . Then for some . The vector that is with has height and , so by Lemma 1.
Theorem. If no vector satisfies, SAMARATI returns NIL. Otherwise it returns the first vector in lexicographic order among the satisfying vectors of the least height , and no satisfying vector has sol and sol.
Proof. Each vector has , so by Lemma 1. If does not satisfy, then no vector satisfies, and line L1 returns NIL. This is correct.
Now assume that satisfies, so is true and exists. By Lemma 2, is false for and true for . We use this invariant for the loop of line L4:
(B) , and sol is the first satisfying vector in lexicographic order at height .
Lines L2 and L3 make (B) true: , , and is the only vector of height .
In one step of the loop, , so line L5 gives . Line L7 visits all the vectors of height in lexicographic order, and line L8 stops at the first one that satisfies. If one is found, is true, so , and line L9 sets and sol to that vector. Then (B) holds. If none is found, is false, so , and line L10 sets . Then (B) holds, and sol has not changed. In both cases goes down by at least 1, so the loop stops.
When the loop stops, , so (B) gives . Line L11 returns the first satisfying vector of height in lexicographic order. If a satisfying had sol and sol, then , and this contradicts the choice of .
Remark. The loop of line L4 runs at most times, because the range has heights at the start and loses at least half of them in each step.
Complexity
Let be the number of rows, the number of attributes, the number of vectors and the height of the top vector. The model is the word RAM, with expected time per hash table operation.
- One call of SATISFIES generalizes rows of values and counts them: expected time.
- The loop of line L4 runs at most times. Each round tests at most the number of vectors of one height, which is less than .
- In total, expected time in the worst case. The space is for the generalized table and for the list of vectors of one height.
In practice is the main factor. For 4 attributes with hierarchies of heights 2, 3, 3 and 4, , but each round tests only the vectors of one height. Finding a vector with the fewest suppressed columns, in place of the least height, is NP-hard for even with hierarchies of two levels, the value and a star (NP-hardness of optimal k-anonymity).
Properties
- Least height, k-minimal. The result has the least height among the satisfying vectors, and no satisfying vector is strictly below it. It need not be the vector of least loss for other measures, such as precision or discernibility.
- Deterministic. The order of line L7 fixes the result among the vectors of the least height.
- One level per attribute. Each value of an attribute is generalized to the same level, which keeps the columns uniform for analysis.
- Tuple suppression. Whole rows are removed, up to MaxSup. A larger MaxSup gives a lower vector.
Variants and improvements
- Preference criteria. Ciriani et al. (2007) list rules for the choice among several k-minimal vectors: the least absolute distance (height), the least relative distance, the largest distribution of the values, and the least suppression.
- All minimal vectors. Incognito finds every k-anonymous vector with a bottom-up search and a priori pruning, and was faster than the binary search in the experiments of LeFevre et al. (2005).
- Greedy search. Datafly raises one attribute at a time and may stop above the least height.
- Multidimensional generalization. Mondrian gives boxes of values instead of one level per attribute, and loses less detail.
When to use it
Use it when the release must use one level of detail per attribute, the hierarchies are given, and the lattice is small enough to enumerate the vectors of a height. It gives a provable answer to "the least total generalization". If all minimal vectors are needed, to choose by another measure, use Incognito. If the quasi-identifier is numeric and many-valued, Mondrian usually keeps more detail.
Pitfalls
- A ceiling in line L5. With , the case gives , and if it is found, line L9 sets to the same value. The loop never ends. Use the floor.
- Skipping line L1. Without it, sol starts at the top vector and is returned when nothing satisfies, so the caller gets a vector that is not k-anonymous within MaxSup.
- Counting classes in line L13. MaxSup bounds the number of rows removed, not the number of classes. Counting the classes of fewer than rows removes too many rows.
- A hierarchy that is not a tree. Then monotonicity fails, and lines L9 and L10 can discard the part of the range that holds the answer.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/samarati-algorithm/. The authors are listed in prov/FM4D27.jsonl.
"""Samarati's binary search over the heights of a full-domain generalization lattice.
A table is a list of rows. Each row is a tuple of d quasi-identifier values.
A hierarchy for attribute a is a list of dicts: hierarchy[a][l] maps each raw
value of attribute a to its value at level l, and hierarchy[a][0] is the
identity. A generalization vector v gives one level v[a] per attribute.
"""
from collections import Counter
from itertools import product
from typing import Hashable, Optional, Sequence
Row = tuple[Hashable, ...]
Hierarchy = Sequence[Sequence[dict[Hashable, Hashable]]]
Vector = tuple[int, ...]
def generalize(table: Sequence[Row], hierarchy: Hierarchy, v: Vector) -> list[Row]:
"""Return the table with each value of attribute a replaced by its value at level v[a]."""
return [tuple(hierarchy[a][v[a]][row[a]] for a in range(len(v))) for row in table]
def suppressed_count(table: Sequence[Row], hierarchy: Hierarchy, v: Vector, k: int) -> int:
"""Return the number of rows that are in a group of fewer than k equal rows at vector v."""
gen = generalize(table, hierarchy, v)
counts = Counter(gen) # @line L12
return sum(c for c in counts.values() if c < k) # @line L13
def satisfies(table: Sequence[Row], hierarchy: Hierarchy, v: Vector, k: int, max_sup: int) -> bool:
"""True when the table generalized by v is k-anonymous after removing at most max_sup rows."""
return suppressed_count(table, hierarchy, v, k) <= max_sup # @line L14
def vectors_at_height(heights: Sequence[int], h: int) -> list[Vector]:
"""All vectors v with 0 <= v[a] <= heights[a] and sum(v) == h, in lexicographic order."""
return [v for v in product(*(range(t + 1) for t in heights)) if sum(v) == h]
def samarati(table: Sequence[Row], hierarchy: Hierarchy, k: int, max_sup: int) -> Optional[Vector]:
"""Return a generalization vector of minimal height that satisfies k-anonymity with at most
max_sup suppressed rows, or None when even the top vector does not satisfy it.
Among the satisfying vectors of minimal height, the result is the first one in
lexicographic order. Such a vector is k-minimal: no satisfying vector lies strictly below it.
Precondition: k >= 1, max_sup >= 0, each hierarchy[a] has at least one level, and
each hierarchy is a tree (each level coarsens the one below), so that the number
of suppressed rows can only fall when a level goes up.
Cost: at most ceil(log2(h + 1)) + 1 rounds, where h is the height of the top vector.
Each round tests at most g vectors, where g is the number of vectors of the lattice,
and each test takes O(n d) expected time for n rows and d attributes.
"""
heights = [len(levels) - 1 for levels in hierarchy]
top: Vector = tuple(heights)
if not satisfies(table, hierarchy, top, k, max_sup): # @line L1
return None
low, high = 0, sum(heights) # @line L2
sol: Vector = top # @line L3
while low < high: # @line L4
try_h = (low + high) // 2 # @line L5
found: Optional[Vector] = None # @line L6
for v in vectors_at_height(heights, try_h): # @line L7
if satisfies(table, hierarchy, v, k, max_sup): # @line L8
found = v
break
if found is not None: # @line L9
sol, high = found, try_h
else: # @line L10
low = try_h + 1
return sol # @line L11
test_samarati_algorithm.py 98 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/samarati-algorithm/. The authors are listed in prov/FM4D27.jsonl.
import random
from itertools import product
from samarati_algorithm import samarati, suppressed_count
RACE = [
{"asian": "asian", "black": "black", "white": "white"},
{"asian": "person", "black": "person", "white": "person"},
]
ZIPS = ["94138", "94139", "94141", "94142"]
ZIP = [{z: z for z in ZIPS}, {z: z[:4] + "*" for z in ZIPS}, {z: z[:3] + "**" for z in ZIPS}]
TABLE = [
("asian", "94142"),
("asian", "94141"),
("asian", "94139"),
("asian", "94139"),
("asian", "94139"),
("black", "94138"),
("black", "94139"),
("white", "94139"),
("white", "94141"),
]
def test_page_example() -> None:
h = [RACE, ZIP]
assert suppressed_count(TABLE, h, (0, 0), 2) == 6
assert suppressed_count(TABLE, h, (0, 1), 2) == 2
assert suppressed_count(TABLE, h, (1, 0), 2) == 2
assert suppressed_count(TABLE, h, (1, 1), 2) == 0
assert samarati(TABLE, h, 2, 2) == (0, 1)
assert suppressed_count(TABLE, h, (0, 2), 2) == 0
assert samarati(TABLE, h, 2, 0) == (0, 2)
assert samarati(TABLE, h, 2, 9) == (0, 0)
def test_edge_cases() -> None:
h = [RACE, ZIP]
assert samarati([], h, 3, 0) == (0, 0)
assert samarati(TABLE[:1], h, 2, 0) is None
assert samarati(TABLE[:1], h, 2, 1) == (0, 0)
assert samarati(TABLE, h, 1, 0) == (0, 0)
same = [("asian", "94139")] * 4
assert samarati(same, h, 4, 0) == (0, 0)
assert samarati(same, h, 5, 0) is None
def random_hierarchy(rng: random.Random, r: int) -> list[dict[int, int]]:
"""A chain of coarser and coarser partitions of range(r), ending in one block."""
block = list(range(r))
levels = [dict(enumerate(block))]
while len(set(block)) > 1:
labels = sorted(set(block))
rng.shuffle(labels)
cut = rng.randint(2, len(labels))
merged = set(labels[:cut])
new_label = min(merged)
block = [new_label if b in merged else b for b in block]
levels.append(dict(enumerate(block)))
return levels
def oracle(table, hierarchy, k, max_sup):
heights = [len(x) - 1 for x in hierarchy]
good = []
for v in product(*(range(t + 1) for t in heights)):
groups: dict = {}
for row in table:
key = tuple(hierarchy[a][v[a]][row[a]] for a in range(len(v)))
groups[key] = groups.get(key, 0) + 1
if sum(c for c in groups.values() if c < k) <= max_sup:
good.append(v)
if not good:
return None
best = min(sum(v) for v in good)
return min(v for v in good if sum(v) == best)
def test_random_against_brute_force() -> None:
rng = random.Random(20240601)
for _ in range(600):
d = rng.randint(1, 3)
sizes = [rng.randint(1, 4) for _ in range(d)]
hierarchy = [random_hierarchy(rng, r) for r in sizes]
n = rng.randint(0, 12)
table = [tuple(rng.randrange(r) for r in sizes) for _ in range(n)]
k = rng.randint(1, 4)
max_sup = rng.randint(0, 3)
got = samarati(table, hierarchy, k, max_sup)
want = oracle(table, hierarchy, k, max_sup)
assert got == want
if got is not None:
for a in range(d):
if got[a] > 0:
lower = got[:a] + (got[a] - 1,) + got[a + 1:]
assert suppressed_count(table, hierarchy, lower, k) > max_sup
History
Samarati and Sweeney described k-anonymity with generalization and suppression in a 1998 report. Samarati (2001) gave the formal model: domain generalization hierarchies, the lattice of distance vectors, the minimal generalization with a suppression threshold, and the binary search on the height. Sweeney (2002) gave the precision measure and the greedy Datafly. LeFevre, DeWitt and Ramakrishnan (2005) used the binary search as a baseline for Incognito.
References
- Pierangela Samarati, Protecting respondents' identities in microdata release, IEEE Transactions on Knowledge and Data Engineering 13(6), 2001, pp. 1010 to 1027, generalization hierarchies, the lattice of distance vectors, k-minimal generalization with suppression, and the binary search on the height
- Valentina Ciriani, Sabrina De Capitani di Vimercati, Sara Foresti and Pierangela Samarati, k-Anonymity, in Secure Data Management in Decentralized Systems, Springer, Advances in Information Security, 2007, Section 4.1, the algorithm of Samarati, with the race and ZIP example and its two 2-minimal generalizations
- Latanya Sweeney, Achieving k-anonymity privacy protection using generalization and suppression, International Journal of Uncertainty, Fuzziness and Knowledge-Based Systems 10(5), 2002, pp. 571 to 588, minimal generalization and the comparison with Datafly
- Kristen LeFevre, David J. DeWitt and Raghu Ramakrishnan, Incognito, efficient full-domain k-anonymity, Proceedings of ACM SIGMOD 2005, pp. 49 to 60, the comparison with the binary search of Samarati in the experiments
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag FM4D27 Edit this page History Report an error Markdown