Algorithm Search⌘K

Algorithmcore

Mondrian multidimensional k-anonymity

Also called Mondrian.

Splits the quasi-identifier space recursively, as in a kd-tree, at the most balanced cut of one attribute that leaves at least k records on each side.

Time
O(d n^2 log n) worst
Space
O(n d) extra
Where
d = the number of quasi-identifier attributes; k = the least size of a region; n = the number of rows
Origin
Kristen LeFevre, David J. DeWitt, Raghu Ramakrishnan, 2006

Mondrian makes a table k-anonymous by cutting the space of quasi-identifier values into boxes. It starts with one box that holds all rows. It cuts a box in two along one attribute, at a value that leaves at least kk rows on each side, and it goes on with both halves until no box has such a cut. Each box is released with the range of each attribute over its rows. This is multidimensional recoding: the same age can go to different ranges for different ZIP codes, so Mondrian usually loses less detail than full-domain generalization. The cuts are those of a kd-tree that stops at kk rows.

In plain words

Put each row as a point on a map: age on one axis, ZIP code on the other. Draw a line across the map so that each side has at least kk points, and as close to half of them as you can. Pick the axis on which the points of the box are spread most widely, compared with the whole map. Then do the same inside each half, and again, until no line can be drawn that keeps at least kk points on each side.

Each final box has at least kk points. Release each point as the box it is in, written as a range of ages and a range of ZIP codes.

The problem

The input is a table TT of nn rows with dd quasi-identifier attributes, each with integer values (or any total order), and an integer kk with 1≤k≤n1 \le k \le n. A cut of a set PP of rows on attribute aa at the value xx splits PP into {t∈P:t.a≤x}\{t \in P : t.a \le x\} and {t∈P:t.a>x}\{t \in P : t.a > x\}. The cut is allowable when both sides have at least kk rows. The output is a partition of the rows into regions of at least kk rows, none of which has an allowable cut. LeFevre et al. (2006) call this a strict multidimensional partitioning. The value of kk is a policy choice.

The algorithm

  1. MONDRIAN(T, k)
  2. 1result ← an empty list; stack ← [all rows of T]
  3. 2while stack is not empty do
  4. 3P ← pop(stack)
  5. 4for each attribute a, in decreasing order of the range of a in P divided by its range in T do
  6. 5x ← the allowable cut on a that maximizes min(|{t ∈ P : t.a ≤ x}|, |{t ∈ P : t.a > x}|), ties to the smaller x; NIL if none
  7. 6if x ≠ NIL then
  8. 7push {t ∈ P : t.a > x} and {t ∈ P : t.a ≤ x}; continue at L2
  9. 8append P to result
  10. 9return result

Ties in line L4 go to the attribute of lower index. Line L5 sorts the values of aa in PP and tests the cut at each place where two neighbors differ. When the values are distinct, the best cut is at the median, as in the paper. An explicit stack replaces the recursion, because the depth can reach n/kn/k.

The release replaces the quasi-identifier values of each row by the box of its region: the pair (least, greatest) of each attribute over the rows of the region.

Example

Take 10 rows of (age, ZIP): 1 (25, 53711), 2 (25, 53712), 3 (26, 53711), 4 (27, 53710), 5 (29, 53712), 6 (61, 53706), 7 (62, 53706), 8 (63, 53710), 9 (64, 53712), 10 (64, 53711). The full ranges are 39 for age and 6 for ZIP. Let k=2k = 2.

region normalized ranges (age, ZIP) cut parts
1 to 10 1, 1 age at 29 (5 and 5) {1..5}, {6..10}
{1, 2, 3, 4, 5} 4/39, 2/6 ZIP at 53711 (3 and 2) {1, 3, 4}, {2, 5}
{1, 3, 4} 2/39, 1/6 none final
{2, 5} 4/39, 0 none final
{6, 7, 8, 9, 10} 3/39, 6/6 ZIP at 53706 (2 and 3) {6, 7}, {8, 9, 10}
{6, 7} 1/39, 0 none final
{8, 9, 10} 1/39, 2/6 none final

In the first row the two ranges tie, so age goes first. In the fifth row the cuts at 53706 and at 53710 both give a balance of 2, and the smaller value wins. The release is:

region age ZIP
{1, 3, 4} 25 to 27 53710 to 53711
{2, 5} 25 to 29 53712
{6, 7} 61 to 62 53706
{8, 9, 10} 63 to 64 53710 to 53712

The age range 25 to 27 in one region and 25 to 29 in another overlap. Full-domain generalization cannot do that, and it would need wider ranges for the same kk. With k=3k = 3 only the first cut is made, and the regions are rows 1 to 5 and rows 6 to 10.

Correctness

The invariant of the loop of line L2 is that the sets in the stack and in the result partition the rows, each has at least kk rows, and each set in the result has no allowable cut. Line L5 tests every distinct value, so it finds an allowable cut if one exists. Line L7 pushes two nonempty sets of at least kk rows, so the loop stops after at most n−1n - 1 cuts.

The size of a region is bounded. Let mm be the largest number of equal rows of TT. Theorem (LeFevre et al. 2006). A region with no allowable cut has at most 2d(k−1)+m2d(k - 1) + m rows. On each attribute, at most k−1k - 1 rows are below the median value and at most k−1k - 1 are above it, or one of the two cuts next to the median is allowable. So at most 2d(k−1)2d(k - 1) rows differ from the point of medians on some attribute, and the rest are copies of one point. The full proofs are in proofs/correctness.md.

Proof: Mondrian returns a partition into regions of at least k rows with no allowable cutfull

The table TT has n≥k≥1n \ge k \ge 1 rows, and each row has dd integer attributes. A cut of a set PP of rows on attribute aa at the value xx splits PP into {t∈P:t.a≤x}\{t \in P : t.a \le x\} and {t∈P:t.a>x}\{t \in P : t.a > x\}. The cut is allowable when both sides have at least kk rows. Let mm be the largest number of equal rows in TT.

Lemma 1 (the cut search). Line L5 returns NIL if and only if PP has no allowable cut on aa. Otherwise it returns an allowable cut.

Proof. Let u1<u2<⋯<uqu_1 < u_2 < \cdots < u_q be the distinct values of aa in PP. A cut at xx has the same two sides as the cut at the largest uj≤xu_j \le x, or puts all of PP on one side when x<u1x < u_1 or x≥uqx \ge u_q. A cut with an empty side is not allowable, because k≥1k \ge 1. So PP has an allowable cut on aa if and only if one of the cuts at u1,…,uq−1u_1, \ldots, u_{q-1} is allowable. The implementation tests exactly these cuts, at each place where two neighbors in the sorted list of values differ, and keeps the allowable one with the best balance. □\square

Lemma 2 (the size bound). If a set PP of r≥1r \ge 1 rows has no allowable cut on any attribute, then r≤2d(k−1)+mr \le 2d(k - 1) + m.

Proof. Fix an attribute aa. Sort the values of aa in PP, and let vv be the value at position ⌈r/2⌉\lceil r/2 \rceil, counted from 1. Let LL be the number of rows with t.a<vt.a < v and RR the number with t.a>vt.a > v. Then L≤⌈r/2⌉−1L \le \lceil r/2 \rceil - 1 and R≤r−⌈r/2⌉=⌊r/2⌋R \le r - \lceil r/2 \rceil = \lfloor r/2 \rfloor.

If L≥kL \ge k, let uu be the largest value below vv. The cut at uu has L≥kL \ge k rows on the left and r−L≥⌊r/2⌋+1≥⌈r/2⌉>L≥kr - L \ge \lfloor r/2 \rfloor + 1 \ge \lceil r/2 \rceil > L \ge k rows on the right, so it is allowable. If R≥kR \ge k, the cut at vv has R≥kR \ge k rows on the right and r−R≥⌈r/2⌉≥⌊r/2⌋≥R≥kr - R \ge \lceil r/2 \rceil \ge \lfloor r/2 \rfloor \ge R \ge k rows on the left, so it is allowable. PP has no allowable cut, so neither case is possible, and L≤k−1L \le k - 1 and R≤k−1R \le k - 1. At most 2(k−1)2(k - 1) rows of PP have a value of aa other than vv.

Do this for each attribute, with the values v1,…,vdv_1, \ldots, v_d. At most 2d(k−1)2d(k - 1) rows differ from (v1,…,vd)(v_1, \ldots, v_d) on some attribute. The other rows are equal to (v1,…,vd)(v_1, \ldots, v_d), and there are at most mm of them. □\square

Theorem. MONDRIAN(T,k)(T, k) stops. The sets of its result are a partition of the rows of TT. Each set has at least kk rows, has no allowable cut on any attribute, and has at most 2d(k−1)+m2d(k - 1) + m rows.

Proof. We use this invariant for the loop of line L2:

(P) The sets in the stack and in the result are disjoint, their union is the set of all rows of TT, and each of them has at least kk rows. Each set in the result has no allowable cut on any attribute.

Line L1 makes (P) true, because the stack holds all n≥kn \ge k rows and the result is empty. In a step, line L3 removes a set PP. If line L5 finds a cut on some attribute, Lemma 1 says that the cut is allowable, so line L7 pushes two disjoint sets with union PP, each with at least kk rows. Otherwise Lemma 1 says that PP has no allowable cut on any attribute, and line L8 puts PP in the result. In both cases (P) holds.

Each cut replaces a set by two sets that are smaller and not empty. So the number of cuts is at most n−1n - 1, and the number of steps is at most 2n−12n - 1. When the stack is empty, (P) says that the result is a partition into sets of at least kk rows with no allowable cut, and Lemma 2 gives the size bound. ■\blacksquare

Remark. Lemma 2 is Theorem 2 of LeFevre, DeWitt and Ramakrishnan (2006). The proof shows a point that the paper does not state: with repeated values, the cut at the median value vv can have an empty side even when the cut just below vv is allowable. That is why line L5 tests every distinct value and not only the median.

Complexity

Let nn be the number of rows and dd the number of attributes. The model is the word RAM, with values that fit in a word.

  • Lines L4 and L5 sort the rr rows of a region on up to dd attributes: O(drlog⁡r)O(d r \log r) time.
  • If each cut is near the median, as with distinct values, the depth is O(log⁡n)O(\log n), the regions of one depth have nn rows in total, and the time is O(dnlog⁡2n)O(d n \log^2 n). With a linear median-finding step in place of the sort, it is O(dnlog⁡n)O(d n \log n), which is the bound the paper gives.
  • With many equal values, an allowable cut can leave only kk rows on one side. Then the depth can be n/kn / k, and the time is O(dn2log⁡n)O(d n^2 \log n) in the worst case.
  • The space is O(nd)O(n d) for the table and the stack.

Properties

  • k-anonymous. Each region has at least kk rows, and all its rows get the same box. This is a theorem for every input.
  • A bound on the quality. By the theorem, each region has at most 2d(k−1)+m2d(k - 1) + m rows. So the discernibility cost ∑∣R∣2\sum |R|^2 of the result is at most n(2d(k−1)+m)n (2d(k - 1) + m). Each k-anonymous partition costs at least nkn k, so the greedy result is within a factor 2d+m/k2d + m/k of the least cost for this measure.
  • Not optimal. LeFevre et al. (2006) show that finding an optimal strict multidimensional partitioning is NP-hard. The greedy rule of line L4 is a heuristic.
  • Deterministic, with the tie rules of lines L4 and L5.

Variants and improvements

  • Relaxed partitioning. The regions may overlap, and the rows with one value may go to different regions. This allows cuts in the middle of a run of equal values, and the bound on region size becomes about 2d(k−1)+12d(k - 1) + 1.
  • Categorical attributes. Cut along the hierarchy of the attribute: a region of the value "person" splits into its children, if each child keeps at least kk rows.
  • Other tests. Replace "at least kk rows" in line L5 by a test on the sensitive values, such as l-diversity, as long as the test holds for a union of regions that pass it.
  • Other choices of the attribute. Choose the attribute by a workload of queries, or by the loss of a later model, in place of the widest range.
  • Clustering. Microaggregation also groups at least kk rows, but it releases the mean of each group, not its box.

When to use it

Use Mondrian for numeric or ordered quasi-identifiers with many values, such as age and ZIP code, when the users can work with ranges that differ from row to row. It is fast, simple and usually keeps more detail than full-domain methods. If each column must use one level of detail, for example because analysts expect a uniform coding, use Samarati's algorithm or Incognito.

Pitfalls

  • The median value as the cut in line L5. With repeated values, the cut at the median value can leave an empty side, while another cut is allowable. Take the values 1, 1, 1, 2, 2, 2, 2, 2 with k=3k = 3. The median value is 2, and the cut "at most 2" leaves no row on the right, so a rule that tries only the median stops here. The cut at 1 gives 3 and 5 rows and is allowable. Test every distinct value, or the size bound of the theorem fails.
  • Testing only one side in line L5. A cut with at least kk rows on the left but fewer on the right produces a region of fewer than kk rows. Check both sides.
  • Recursion in line L7. With many equal values the depth can be n/kn / k. A recursive version can run out of stack; use an explicit stack.
  • Raw ranges in line L4. Without the division by the range in TT, an attribute with large numbers, such as a ZIP code, is always cut first. This is not wrong, but the regions get narrow in one attribute and wide in the others.

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.

mondrian_anonymization.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mondrian-anonymization/. The authors are listed in prov/EV1MMH.jsonl.
"""Greedy strict multidimensional partitioning for k-anonymity (Mondrian), on integer attributes.

A table is a list of rows. Each row is a tuple of d integers, the quasi-identifier values.
The result is a partition of the row indices into regions. Each region is released with
the range [min, max] of each attribute over its rows.
"""

from fractions import Fraction
from typing import Optional, Sequence

Row = tuple[int, ...]


def best_cut(table: Sequence[Row], part: Sequence[int], a: int, k: int) -> Optional[int]:
    """Return the allowable cut value x on attribute a that maximizes
    min(#{t : t[a] <= x}, #{t : t[a] > x}) over the rows of part, ties to the smaller x.
    A cut is allowable when both sides have at least k rows. Return None when no cut is allowable.
    """
    values = sorted(table[i][a] for i in part)
    best: Optional[int] = None
    best_score = -1
    for j in range(len(values) - 1):
        if values[j] != values[j + 1]:
            left = j + 1
            right = len(values) - left
            if left >= k and right >= k and min(left, right) > best_score:
                best, best_score = values[j], min(left, right)
    return best


def mondrian(table: Sequence[Row], k: int) -> list[list[int]]:
    """Return the regions of the greedy Mondrian partition, each a sorted list of row indices.
    The regions are sorted by their first index.

    Every region has at least k rows, and no region has an allowable cut on any attribute,
    so each region has at most 2 d (k - 1) + m rows, where m is the largest number of
    equal rows of the table.

    Precondition: k >= 1 and len(table) >= k, or the table is empty.
    Cost: O(d r log r) time for a region of r rows. With distinct values the cuts are at
    the median and the total is O(d n log^2 n); in the worst case the recursion has
    n / k levels and the total is O(d n^2 log n). Space O(n). An explicit stack replaces recursion.
    """
    n = len(table)
    if n == 0:
        return []
    d = len(table[0])
    full_range = [max(r[a] for r in table) - min(r[a] for r in table) for a in range(d)]
    result: list[list[int]] = []  # @line L1
    stack: list[list[int]] = [list(range(n))]
    while stack:  # @line L2
        part = stack.pop()  # @line L3

        def norm_range(a: int) -> Fraction:
            if full_range[a] == 0:
                return Fraction(0)
            vals = [table[i][a] for i in part]
            return Fraction(max(vals) - min(vals), full_range[a])

        order = sorted(range(d), key=lambda a: (-norm_range(a), a))
        cut_done = False
        for a in order:  # @line L4
            x = best_cut(table, part, a, k)  # @line L5
            if x is not None:  # @line L6
                lhs = [i for i in part if table[i][a] <= x]
                rhs = [i for i in part if table[i][a] > x]
                stack.append(rhs)  # @line L7
                stack.append(lhs)
                cut_done = True
                break
        if not cut_done:
            result.append(sorted(part))  # @line L8
    result.sort()
    return result  # @line L9


def summarize(table: Sequence[Row], regions: Sequence[Sequence[int]]) -> list[tuple[tuple[int, int], ...]]:
    """Return the released box of each region: the pair (min, max) for each attribute."""
    d = len(table[0]) if table else 0
    return [tuple((min(table[i][a] for i in reg), max(table[i][a] for i in reg)) for a in range(d)) for reg in regions]
test_mondrian_anonymization.py 89 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mondrian-anonymization/. The authors are listed in prov/EV1MMH.jsonl.
import random
from collections import Counter

from mondrian_anonymization import best_cut, mondrian, summarize

TABLE = [
    (25, 53711), (25, 53712), (26, 53711), (27, 53710), (29, 53712),
    (61, 53706), (62, 53706), (63, 53710), (64, 53712), (64, 53711),
]


def test_page_example() -> None:
    regions = mondrian(TABLE, 2)
    assert regions == [[0, 2, 3], [1, 4], [5, 6], [7, 8, 9]]
    assert summarize(TABLE, regions) == [
        ((25, 27), (53710, 53711)),
        ((25, 29), (53712, 53712)),
        ((61, 62), (53706, 53706)),
        ((63, 64), (53710, 53712)),
    ]
    assert mondrian(TABLE, 3) == [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]


def test_duplicates_pitfall() -> None:
    rows = [(1,), (1,), (1,), (2,), (2,), (2,), (2,), (2,)]
    # The median value is 2, and the cut "<= 2" leaves nothing on the right.
    assert best_cut(rows, list(range(8)), 0, 3) == 1
    assert mondrian(rows, 3) == [[0, 1, 2], [3, 4, 5, 6, 7]]


def test_edge_cases() -> None:
    assert mondrian([], 2) == []
    assert mondrian([(5, 5)], 1) == [[0]]
    assert mondrian([(5, 5)] * 4, 2) == [[0, 1, 2, 3]]
    assert mondrian(TABLE, 1) == [[i] for i in range(10)]
    assert mondrian(TABLE, 10) == [list(range(10))]
    assert mondrian(TABLE, 6) == [list(range(10))]


def allowable(table, region, a, k):
    for x in {table[i][a] for i in region}:
        left = sum(1 for i in region if table[i][a] <= x)
        if left >= k and len(region) - left >= k:
            return True
    return False


def reference(table, region, k, full):
    """The same greedy rule, written as a plain recursion with integer comparisons."""
    d = len(table[0])

    def ratio(a):
        # IEEE division is correctly rounded, so equal ratios of small integers compare equal.
        if full[a] == 0:
            return 0.0
        return (max(table[i][a] for i in region) - min(table[i][a] for i in region)) / full[a]

    order = sorted(range(d), key=lambda a: (-ratio(a), a))
    for a in order:
        best, score = None, -1
        for x in sorted({table[i][a] for i in region}):
            left = [i for i in region if table[i][a] <= x]
            right = [i for i in region if table[i][a] > x]
            if len(left) >= k and len(right) >= k and min(len(left), len(right)) > score:
                best, score = (left, right), min(len(left), len(right))
        if best is not None:
            return reference(table, best[0], k, full) + reference(table, best[1], k, full)
    return [sorted(region)]


def test_random_against_reference_and_bound() -> None:
    rng = random.Random(2006)
    for _ in range(700):
        d = rng.randint(1, 4)
        k = rng.randint(1, 4)
        n = rng.randint(k, 30)
        spread = rng.randint(1, 6)
        table = [tuple(rng.randint(0, spread) for _ in range(d)) for _ in range(n)]
        regions = mondrian(table, k)
        assert sorted(i for reg in regions for i in reg) == list(range(n))
        m = max(Counter(table).values())
        for reg in regions:
            assert len(reg) >= k
            assert len(reg) <= 2 * d * (k - 1) + m
            assert not any(allowable(table, reg, a, k) for a in range(d))
        full = [max(r[a] for r in table) - min(r[a] for r in table) for a in range(d)]
        assert regions == sorted(reference(table, list(range(n)), k, full))

History

LeFevre, DeWitt and Ramakrishnan proposed multidimensional recoding for k-anonymity at ICDE 2006, the year after their full-domain algorithm Incognito. They showed that optimal strict multidimensional partitioning is NP-hard, proved the bound on the size of the regions of a greedy partition, and gave the greedy median algorithm, which they named after the painter Piet Mondrian for the look of its rectangles.

References

  1. Kristen LeFevre, David J. DeWitt and Raghu Ramakrishnan, Mondrian multidimensional k-anonymity, Proceedings of the 22nd International Conference on Data Engineering (ICDE 2006), p. 25, strict and relaxed multidimensional partitioning, the NP-hardness of optimal strict partitioning, the bound 2d(k-1)+m on the size of a region, and the greedy median partitioning
  2. Kristen LeFevre, David J. DeWitt and Raghu Ramakrishnan, Incognito, efficient full-domain k-anonymity, Proceedings of ACM SIGMOD 2005, pp. 49 to 60, full-domain generalization, which Mondrian is compared with
  3. Roberto J. Bayardo and Rakesh Agrawal, Data privacy through optimal k-anonymization, Proceedings of the 21st International Conference on Data Engineering (ICDE 2005), pp. 217 to 228, the discernibility metric used to compare releases
  4. Benjamin C. M. Fung, Ke Wang, Rui Chen and Philip S. Yu, Privacy-preserving data publishing, a survey of recent developments, ACM Computing Surveys 42(4), 2010, the section on multidimensional generalization

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