Algorithm Search⌘K

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
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 kk 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 TT of nn rows with dd quasi-identifier attributes, a tree hierarchy for each attribute aa with levels 0,…,ha0, \ldots, h_a (see generalization and suppression), an integer k≥1k \ge 1 and a limit MaxSup ≥0\ge 0. A vector vv with 0≤va≤ha0 \le v_a \le h_a satisfies if, in TT generalized by vv, at most MaxSup rows are in classes of fewer than kk rows. The output is a satisfying vector of least height ∣v∣=∑ava|v| = \sum_a v_a, or NIL if no vector satisfies. The top vector is ⊤=(h1,…,hd)\top = (h_1, \ldots, h_d) with height hh, and the lattice has g=∏a(ha+1)g = \prod_a (h_a + 1) vectors. kk and MaxSup are policy choices.

The algorithm

  1. SAMARATI(T, H, k, MaxSup)
  2. 1if not SATISFIES(T, top, k, MaxSup) then return NIL
  3. 2low ← 0, high ← height(top)
  4. 3sol ← top
  5. 4while low < high do
  6. 5try ← ⌊(low + high) / 2⌋
  7. 6found ← NIL
  8. 7for each vector v with height(v) = try, in lexicographic order do
  9. 8if SATISFIES(T, v, k, MaxSup) then found ← v; exit the loop
  10. 9if found ≠ NIL then sol ← found, high ← try
  11. 10else low ← try + 1
  12. 11return sol
  13. SATISFIES(T, v, k, MaxSup)
  14. 12count the rows of each tuple of T generalized by v, in a hash table
  15. 13s ← the number of rows whose tuple has a count < k
  16. 14return 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 [low,high][low, high], and sol is always a satisfying vector at height highhigh. The release is the table generalized by sol without the ss rows of line L13.

Samarati (2001) adds a matrix of distance vectors between the tuples of TT, 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 h=3h = 3. Let k=2k = 2 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 v≤wv \le w then each class of TT at ww is a union of classes at vv, so a row that is not suppressed at vv is not suppressed at ww. So if a vector of height t<ht < h satisfies, raising one of its levels gives a satisfying vector of height t+1t + 1. The predicate "some vector of height tt satisfies" is false below the least height t∗t^* and true from t∗t^* to hh. The loop of line L4 keeps the invariant low≤t∗≤highlow \le t^* \le high, with sol the first satisfying vector at height highhigh. Each step halves the range, and at the end low=high=t∗low = high = t^*. 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 TT has nn rows and dd quasi-identifier attributes. Attribute aa has a hierarchy with levels 0,1,…,ha0, 1, \ldots, h_a, and each level coarsens the level below it: the value at level l+1l + 1 is a function of the value at level ll. A vector vv has 0≤va≤ha0 \le v_a \le h_a for each aa, its height is ∣v∣=∑ava|v| = \sum_a v_a, and v≤wv \le w means va≤wav_a \le w_a for each aa. The top vector is ⊤=(h1,…,hd)\top = (h_1, \ldots, h_d) and h=∣⊤∣h = |\top|. We write TvT_v for TT generalized by vv, and sup(v)\mathrm{sup}(v) for the number of rows of TvT_v whose combination of values occurs fewer than kk times. Lines L12 and L13 compute sup(v)\mathrm{sup}(v), so SATISFIES(T,v,k,MaxSup)(T, v, k, MaxSup) is true if and only if sup(v)≤MaxSup\mathrm{sup}(v) \le MaxSup. We say that vv satisfies when this is true.

Lemma 1 (monotonicity). If v≤wv \le w, then sup(w)≤sup(v)\mathrm{sup}(w) \le \mathrm{sup}(v).

Proof. Because each level is a function of the level below it, the value of a row at level waw_a is a function of its value at level vav_a. So two rows that are equal in TvT_v are equal in TwT_w, and each group of equal rows of TwT_w is a union of groups of TvT_v. A row that is in a group of at least kk rows in TvT_v is therefore in a group of at least kk rows in TwT_w. So the rows counted by sup(w)\mathrm{sup}(w) are a subset of the rows counted by sup(v)\mathrm{sup}(v). □\square

Let P(t)P(t) be the statement "some vector of height tt satisfies".

Lemma 2. If P(t)P(t) is true and t<ht < h, then P(t+1)P(t + 1) is true.

Proof. Let vv satisfy with ∣v∣=t<h|v| = t < h. Then va<hav_a < h_a for some aa. The vector ww that is vv with wa=va+1w_a = v_a + 1 has height t+1t + 1 and v≤wv \le w, so sup(w)≤sup(v)≤MaxSup\mathrm{sup}(w) \le \mathrm{sup}(v) \le MaxSup by Lemma 1. □\square

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 t∗t^*, and no satisfying vector uu has u≤u \le sol and u≠u \ne sol.

Proof. Each vector vv has v≤⊤v \le \top, so sup(⊤)≤sup(v)\mathrm{sup}(\top) \le \mathrm{sup}(v) by Lemma 1. If ⊤\top does not satisfy, then no vector satisfies, and line L1 returns NIL. This is correct.

Now assume that ⊤\top satisfies, so P(h)P(h) is true and t∗t^* exists. By Lemma 2, P(t)P(t) is false for t<t∗t < t^* and true for t∗≤t≤ht^* \le t \le h. We use this invariant for the loop of line L4:

(B) low≤t∗≤highlow \le t^* \le high, and sol is the first satisfying vector in lexicographic order at height highhigh.

Lines L2 and L3 make (B) true: low=0low = 0, high=hhigh = h, and ⊤\top is the only vector of height hh.

In one step of the loop, low<highlow < high, so line L5 gives low≤try<highlow \le try < high. Line L7 visits all the vectors of height trytry in lexicographic order, and line L8 stops at the first one that satisfies. If one is found, P(try)P(try) is true, so t∗≤tryt^* \le try, and line L9 sets high=tryhigh = try and sol to that vector. Then (B) holds. If none is found, P(try)P(try) is false, so t∗>tryt^* > try, and line L10 sets low=try+1≤t∗low = try + 1 \le t^*. Then (B) holds, and sol has not changed. In both cases high−lowhigh - low goes down by at least 1, so the loop stops.

When the loop stops, low=highlow = high, so (B) gives high=t∗high = t^*. Line L11 returns the first satisfying vector of height t∗t^* in lexicographic order. If a satisfying uu had u≤u \le sol and u≠u \ne sol, then ∣u∣<t∗|u| < t^*, and this contradicts the choice of t∗t^*. ■\blacksquare

Remark. The loop of line L4 runs at most ⌈lg⁡(h+1)⌉\lceil \lg(h + 1) \rceil times, because the range [low,high][low, high] has h+1h + 1 heights at the start and loses at least half of them in each step.

Complexity

Let nn be the number of rows, dd the number of attributes, gg the number of vectors and hh the height of the top vector. The model is the word RAM, with expected O(1)O(1) time per hash table operation.

  • One call of SATISFIES generalizes nn rows of dd values and counts them: O(nd)O(n d) expected time.
  • The loop of line L4 runs at most ⌈lg⁡(h+1)⌉\lceil \lg(h + 1) \rceil times. Each round tests at most the number of vectors of one height, which is less than gg.
  • In total, O(ndglog⁡h)O(n d g \log h) expected time in the worst case. The space is O(nd)O(n d) for the generalized table and O(gd)O(g d) for the list of vectors of one height.

In practice gg is the main factor. For 4 attributes with hierarchies of heights 2, 3, 3 and 4, g=3⋅4⋅4⋅5=240g = 3 \cdot 4 \cdot 4 \cdot 5 = 240, 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 k≥3k \ge 3 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 try=⌈(low+high)/2⌉try = \lceil (low + high)/2 \rceil, the case high=low+1high = low + 1 gives try=hightry = high, and if it is found, line L9 sets highhigh 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 kk 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.

samarati_algorithm.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example