Algorithm Search⌘K

Algorithmadvanced

O(k) approximation for k-anonymity

Also called Aggarwal k-anonymity approximation.

Groups records into clusters of at least k by a forest construction and suppresses differing cells, within O(k) of the fewest suppressions.

Time
O(n^2 d + n^2 log n) worst
Space
O(n^2) extra
Where
d = the number of columns; k = the least size of a cluster; n = the number of rows
Origin
Gagan Aggarwal, Tomas Feder, Krishnaram Kenthapadi, Rajeev Motwani, Rina Panigrahy, Dilys Thomas, An Zhu, 2005

The O(k) approximation of Aggarwal et al. (2005) makes a table k-anonymous by suppressing cells, and it suppresses at most 3k−33k - 3 times the fewest possible cells. Finding the fewest is NP-hard for k≥3k \ge 3. The algorithm sees the rows as the vertices of a complete graph, with the Hamming distance as the weight of an edge. It grows a forest in which each tree has at least kk vertices and whose total weight is at most the optimum. Then it splits each tree with more than 3k−33k - 3 rows into smaller trees. Each final tree is a cluster, and in each cluster the cells of each column where its rows differ are replaced by a star.

In plain words

Two rows that differ in few columns are cheap to put together, because only those columns must be hidden. So let each small group of rows reach out to the nearest row outside it, and join that row's group. Stop when every group has at least kk rows. A group can become too big, which makes it costly: a column is hidden in all its rows when any two of them differ. So cut each big group into parts of at least kk rows, and at most 3k−33k - 3.

The cost of one group is at most its number of rows times the total length of its edges, and the total length of all edges is no more than the best possible cost. That gives the factor 3k−33k - 3.

The problem

The input is a table of nn rows v1,…,vnv_1, \ldots, v_n, each with dd values, and an integer kk with 2≤k≤n2 \le k \le n. A release replaces some cells by ∗* so that each row is equal to at least k−1k - 1 other rows. Its cost is the number of stars, and OPT is the least cost. For a set CC of rows, δ(C)\delta(C) is the number of columns on which not all rows of CC are equal. The output is a partition of the rows into clusters of at least kk rows; each cluster CC is released with its δ(C)\delta(C) differing columns suppressed, at a cost of ∣C∣ δ(C)|C| \, \delta(C). The value of kk is a policy choice.

The algorithm

  1. ANONYMIZE(V, k)
  2. 1w(x, y) ← the number of columns where rows x and y differ, for all pairs
  3. 2F ← n trees of one vertex each; each vertex is the root of its tree
  4. 3while some tree of F has fewer than k vertices do
  5. 4T ← such a tree, with the least root; u ← root(T)
  6. 5x ← the vertex outside T with the least w(u, x), ties to the lower index
  7. 6add the edge u → x; T joins the tree of x, whose root stays the root
  8. 7P ← the trees of F
  9. 8while some tree of P has more than 3k - 3 row vertices do
  10. 9replace that tree by the two trees of DECOMPOSE(tree, k)
  11. 10for each tree of P, with rows C: replace by * the cells of C in the δ(C) columns where C differs
  12. 11return the clusters, the released table and its cost
  13. DECOMPOSE(T, k) ▷ s = the number of row vertices of T, s ≥ 3k - 2
  14. 12u ← the row vertex of least index; root T at u
  15. 13c ← the neighbor of u with the most row vertices on its side of the edge u-c; φ ← that number
  16. 14if φ > s - k then u ← c and go to L13
  17. 15if φ ≥ k then return the two trees made by cutting the edge u-c
  18. 16A ← the sides of the neighbors of u, largest first, until their row vertices number at least k
  19. 17return (A joined to a new Steiner copy of u, the rest with u)

A Steiner vertex is a copy of the values of a row, but it is not a row. It joins the parts of AA with the same edge weights they had to uu. Line L13 counts only row vertices. Ties in line L13 go to the neighbor of lower index. The walk of lines L13 and L14 only goes down in the tree rooted at the start vertex.

Example

Take 7 binary rows with 4 columns and k=3k = 3: row 1 = 0000, row 2 = 0001, row 3 = 0011, row 4 = 1111, row 5 = 1110, row 6 = 1100 and row 7 = 0101.

step small tree, root uu nearest row outside edge weight
1 {1}, root 1 2 1 → 2 1
2 {1, 2}, root 2 3 2 → 3 1
3 {4}, root 4 5 4 → 5 1
4 {4, 5}, root 5 6 5 → 6 1
5 {7}, root 7 2 7 → 2 1

The forest has the trees {1, 2, 3, 7} and {4, 5, 6}, with total weight 5. Both have at most 3k−3=63k - 3 = 6 rows, so DECOMPOSE is not needed. The cluster {1, 2, 3, 7} differs in columns 2, 3 and 4, and the cluster {4, 5, 6} in columns 3 and 4. So rows 1, 2, 3 and 7 become 0***, and rows 4, 5 and 6 become 11**. The cost is 4⋅3+3⋅2=184 \cdot 3 + 3 \cdot 2 = 18. A search over all partitions into clusters of at least 3 rows shows that 18 is the optimum here. The proven bound is only (3k−3)⋅5=30(3k - 3) \cdot 5 = 30.

Correctness

The proof has three steps. The full proof is in proofs/correctness.md.

  1. The forest is cheap. Let dk−1(u)d_{k-1}(u) be the distance from uu to its (k−1)(k - 1)-th nearest other row. When line L6 adds the edge from uu, its tree has at most k−1k - 1 vertices, so one of the k−1k - 1 rows nearest to uu is outside, and w(u,x)≤dk−1(u)w(u, x) \le d_{k-1}(u). Each vertex starts at most one edge, because it stops being a root. In an optimal release the cluster of uu has k−1k - 1 other rows, and its number of differing columns is at least dk−1(u)d_{k-1}(u). Each row of that cluster pays at least that much, so the weight of the forest is at most OPT.
  2. A split keeps both parts large and adds no weight. The walk of line L14 stops at a vertex where each side has at most s−ks - k row vertices. If one side has at least kk, line L15 cuts it off. If not, line L16 collects sides until it has between kk and 2k−22k - 2 rows, and the rest keeps at least s−(2k−2)≥ks - (2k - 2) \ge k rows. The Steiner copy has the values of uu, so no edge gets heavier.
  3. A cluster costs at most its tree. Each column where two rows of a cluster CC differ changes along some edge of the path between them, so δ(C)\delta(C) is at most the weight of the tree. With at most 3k−33k - 3 rows per cluster, the cost is at most (3k−3)(3k - 3) times the weight of the forest, which is at most (3k−3) (3k - 3)\,OPT.
Proof: The forest algorithm is k-anonymous and within 3k - 3 of the fewest suppressionsfull

The input is nn rows of dd values each, and 2≤k≤n2 \le k \le n. For rows xx and yy, w(x,y)w(x, y) is the number of columns where they differ. For a set CC of rows, δ(C)\delta(C) is the number of columns where not all rows of CC are equal. The algorithm releases each row of a cluster CC with its cells in these δ(C)\delta(C) columns suppressed, so its cost is ∑C∣C∣ δ(C)\sum_C |C| \, \delta(C).

Lemma 1 (the optimum). Let OPT be the fewest suppressed cells in a k-anonymous release of the rows. Then OPT =min⁡∑C∣C∣ δ(C)= \min \sum_C |C| \, \delta(C), over all partitions of the rows into clusters of at least kk rows.

Proof. Take an optimal release, and group the rows by their released row. Each group has at least kk rows. The rows of a group are equal after suppression, so in each column where the group differs, each of its rows has a suppressed cell. So the cost is at least ∑C∣C∣ δ(C)\sum_C |C| \, \delta(C) for this partition. Conversely, suppressing the differing columns of each cluster of a partition gives a k-anonymous release with this cost. □\square

For a row uu, let dk−1(u)d_{k-1}(u) be the (k−1)(k - 1)-th smallest value of w(u,y)w(u, y) over the other rows yy.

Lemma 2 (the forest). Lines L1 to L6 stop with a forest FF on the rows, each tree of FF has at least kk vertices, and the total weight W(F)W(F) is at most OPT.

Proof. Each step of line L6 adds an edge between two different trees, so FF stays a forest, and the number of trees goes down by one. So the loop stops, and then no tree has fewer than kk vertices. A tree has exactly one root, the vertex with no outgoing edge. Line L6 adds an edge from the root uu of the small tree, and the root of the merged tree is the root of the tree of xx. So uu is never a root again, and each vertex is the start of at most one edge.

When line L6 adds the edge (u,x)(u, x), the tree TT of uu has at most k−1k - 1 vertices. At most k−2k - 2 of the k−1k - 1 rows nearest to uu are in TT, so one of them is outside TT, and line L5 gives w(u,x)≤dk−1(u)w(u, x) \le d_{k-1}(u).

In an optimal partition (Lemma 1), the cluster CC of uu has at least k−1k - 1 other rows, and δ(C)≥w(u,y)\delta(C) \ge w(u, y) for each y∈Cy \in C. So δ(C)\delta(C) is at least the largest of these k−1k - 1 or more distances, which is at least dk−1(u)d_{k-1}(u). Each vertex starts at most one edge, so $W(F) \le \sum_u d_{k-1}(u) \le \sum_u \delta(C_u) = $ OPT, where CuC_u is the cluster of uu. □\square

In the next part, a tree may also have Steiner vertices. A Steiner vertex is a copy of the vector of some vertex, and it is not a row. The size of a tree is its number of row vertices.

Lemma 3 (one split). Let a tree have size s≥3k−2s \ge 3k - 2. DECOMPOSE returns two trees of size at least kk each, whose row vertices are a partition of the row vertices of the tree, and whose total weight is at most the weight of the tree.

Proof. For a vertex uu and a neighbor yy, let side(y)(y) be the size of the part that holds yy when the edge uu-yy is cut. Root the tree at the start vertex rr of line L12. Lines L13 and L14 move uu to the neighbor cc with the largest side while that side is more than s−ks - k. If the walk moves from uu to cc, then the part of cc that holds uu has size s−side(c)<k≤s−ks - \mathrm{side}(c) < k \le s - k, because s≥2ks \ge 2k. So the walk never moves back, it goes down in the tree rooted at rr, and it stops. A move needs a side of at least s−k+1≥2s - k + 1 \ge 2, so the walk never reaches a leaf, and uu always has a neighbor. When the walk stops, each neighbor of uu has side at most s−ks - k.

If the largest side φ\varphi is at least kk (line L15), cutting the edge uu-cc gives a tree of size φ\varphi and a tree of size s−φs - \varphi, and both are at least kk.

Otherwise each side is at most k−1k - 1. The sides add up to ss or s−1s - 1, which is at least 3k−3≥k3k - 3 \ge k, so line L16 can take sides until their total is at least kk. The total before the last one is at most k−1k - 1, so the final total is at most 2k−22k - 2. The rest, with uu, has size at least s−(2k−2)≥ks - (2k - 2) \ge k. Line L17 joins the taken parts to a Steiner copy of uu and not to uu. Each new edge has the weight of the edge it replaces, because the copy has the vector of uu. Both new trees are connected, and both have size at least kk.

In both cases no edge gets a larger weight, and one edge goes away in the first case. □\square

Lemma 4 (a cluster and its tree). If the rows of a cluster CC are the row vertices of a tree TCT_C, possibly with Steiner vertices, then δ(C)≤W(TC)\delta(C) \le W(T_C).

Proof. Take a column jj where two rows x,y∈Cx, y \in C differ. The path from xx to yy in TCT_C has an edge whose two ends differ in column jj. Map jj to this edge. Different columns give different pairs (edge, column), and an edge ee is in at most w(e)w(e) such pairs. So δ(C)≤∑ew(e)=W(TC)\delta(C) \le \sum_e w(e) = W(T_C). □\square

Theorem. ANONYMIZE returns clusters that partition the rows, each with between kk and 3k−33k - 3 rows. The released table is k-anonymous, and its cost is at most (3k−3) (3k - 3)\,OPT.

Proof. By Lemma 2, line L7 starts with trees of size at least kk. Line L8 splits a tree only when its size is more than 3k−33k - 3, and by Lemma 3 both parts have size at least kk, so both are smaller than the tree. So the loop stops, and each final tree has a size between kk and 3k−33k - 3. Note that k≤3k−3k \le 3k - 3 because k≥2k \ge 2. The row vertices of the final trees are a partition of the rows.

Line L10 suppresses, in each row of a cluster CC, the δ(C)\delta(C) columns where CC differs. Then all rows of CC are equal, and CC has at least kk rows, so the table is k-anonymous. By Lemma 4, Lemma 3 and Lemma 2, the cost is

∑C∣C∣ δ(C)≤(3k−3)∑CW(TC)≤(3k−3) W(F)≤(3k−3) OPT.■\sum_C |C| \, \delta(C) \le (3k - 3) \sum_C W(T_C) \le (3k - 3)\, W(F) \le (3k - 3)\,\mathrm{OPT}. \qquad \blacksquare

Complexity

Let nn be the number of rows and dd the number of columns. The model is the word RAM.

  • Line L1 computes n2n^2 distances in O(n2d)O(n^2 d) time and keeps them in O(n2)O(n^2) space.
  • Lines L3 to L6 merge at most n−1n - 1 times, and each merge scans the nn rows: O(n2)O(n^2).
  • A split of a tree with tt vertices takes O(tlog⁡t)O(t \log t) for the rooting, the walk and the sort of line L16, and it adds at most one Steiner vertex. Each split removes at least kk rows from a large tree, so at most n/kn / k splits happen, each on at most 2n2n vertices: O(n2log⁡n)O(n^2 \log n) in total.
  • Line L10 takes O(nd)O(n d).

In total O(n2d+n2log⁡n)O(n^2 d + n^2 \log n) time and O(n2)O(n^2) space.

Properties

  • Ratio 3k−33k - 3. This is a theorem for all inputs with k≥2k \ge 2. With a finer split, Aggarwal et al. (2005) improve the ratio to max⁡(2k−1,3k−5)\max(2k - 1, 3k - 5), and they give better ratios for small cases: 1.5 for k=2k = 2, and 2 for k=3k = 3 with binary values.
  • Cluster sizes. Each cluster has between kk and 3k−33k - 3 rows. Small clusters keep more detail.
  • Limit of the method. The algorithm uses only the distances between rows. Aggarwal et al. (2005) show two tables with the same distances whose optimal costs differ by a factor of order kk. So no algorithm that sees only the distances can have a ratio better than order kk.
  • Measured quality. The ratio is a worst case. On the example above, the result is optimal. How far it is from the optimum on real tables is a question of measurement, not of this proof.

Variants and improvements

  • Meyerson and Williams (2004). An O(klog⁡k)O(k \log k) ratio, 3k(1+ln⁡2k)3k(1 + \ln 2k), by greedy set cover over candidate clusters, in time exponential in kk, and an O(klog⁡d)O(k \log d) ratio in polynomial time.
  • Park and Shim (2007). An O(log⁡k)O(\log k) ratio; see their paper for the conditions on the running time.
  • Generalization in place of suppression. The same clustering idea works with ranges or hierarchy values in place of stars, as in Mondrian, but the bound above is only for suppression.
  • Clustering with means. Microaggregation, for example by MDAV, forms clusters of at least kk rows by distances and releases the means. It is a heuristic for numeric data.

When to use it

Use it when the release must keep cells exactly or hide them, with no generalization hierarchy, and a provable bound on the loss is wanted, for example for categorical data with many columns. For numeric data, or when ranges are acceptable, Mondrian is faster and usually keeps more detail. For a uniform coding of each column, use full-domain generalization.

Pitfalls

  • Any vertex as the start of the edge in line L4. The proof charges each edge to the vertex where it starts, once. If line L4 takes a vertex of TT that is not the root, one vertex can start two edges, and the bound W(F)≤W(F) \le OPT fails.
  • The nearest vertex inside TT in line L5. If line L5 looks at all rows, the nearest one can be in TT itself. The edge then closes a cycle and the tree does not grow, so the loop never ends. Take the nearest vertex outside TT.
  • Joining AA to uu itself in line L17. The parts of AA were joined only through uu, and so were the other parts. If AA takes uu, the rest falls apart into several pieces, which are not a tree, and the weight argument fails. Use a Steiner copy of uu, which is not a row.
  • k=1k = 1 in line L8. Then 3k−3=03k - 3 = 0, and line L8 tries to split each tree forever. For k=1k = 1 the table is already 1-anonymous with no stars, so return it.

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.

k_anonymity_approximation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/k-anonymity-approximation/. The authors are listed in prov/3CXF3J.jsonl.
"""The forest algorithm of Aggarwal et al. for k-anonymity by cell suppression, with ratio 3k - 3.

The input is a list of n rows, each a tuple of d values. The output groups the rows into
clusters of k to 3k - 3 rows and replaces by None each cell of a column on which the rows
of its cluster differ. The tree splitting uses explicit stacks, not recursion.
"""

from typing import Hashable, Optional, Sequence

Row = tuple[Hashable, ...]


def hamming(x: Sequence[Hashable], y: Sequence[Hashable]) -> int:
    """The number of positions where x and y differ."""
    return sum(1 for a, b in zip(x, y) if a != b)


def build_forest(rows: Sequence[Row], k: int) -> list[tuple[int, int]]:
    """Return the directed edges (u, x) of the forest: each tree has at least k vertices,
    and its total weight is at most the cost of an optimal k-anonymous suppression.

    Precondition: 2 <= k <= len(rows).
    Cost: O(n^2 d) time for the weights and O(n^2) for the n - 1 merges at most.
    """
    n = len(rows)
    w = [[hamming(rows[i], rows[j]) for j in range(n)] for i in range(n)]  # @line L1
    label = list(range(n))  # @line L2
    root = list(range(n))  # root[t] is the vertex of tree t with no outgoing edge
    edges: list[tuple[int, int]] = []
    while True:
        size: dict[int, int] = {}
        for t in label:
            size[t] = size.get(t, 0) + 1
        small = [t for t in size if size[t] < k]
        if not small:  # @line L3
            break
        t = min(small, key=lambda s: root[s])
        u = root[t]  # @line L4
        x = min((v for v in range(n) if label[v] != t), key=lambda v: (w[u][v], v))  # @line L5
        edges.append((u, x))  # @line L6
        target = label[x]
        for v in range(n):
            if label[v] == t:
                label[v] = target
    return edges


def _decompose(vec: list[Row], real: list[bool], adj: dict[int, set[int]], k: int) -> tuple[set[int], set[int]]:
    """Split one tree (the vertex set of adj) with s >= 3k - 2 row vertices into two trees,
    each with at least k row vertices. May add one Steiner vertex to vec, real and adj.
    The walk only goes down in the tree rooted at r, so one call takes O(t log t) time
    for a tree of t vertices.
    """
    s = sum(1 for v in adj if real[v])
    r = min(v for v in adj if real[v])
    # Root the tree at r once, with an explicit stack, and count the row vertices of each subtree.
    parent = {r: -1}
    order = [r]
    stack = [r]
    while stack:
        v = stack.pop()
        for y in adj[v]:
            if y not in parent:
                parent[y] = v
                order.append(y)
                stack.append(y)
    cnt = {v: (1 if real[v] else 0) for v in order}
    for v in reversed(order):
        if parent[v] >= 0:
            cnt[parent[v]] += cnt[v]
    u = r  # @line L12

    def side(y: int) -> int:
        """The row vertices on the side of y when the edge u-y is cut."""
        return cnt[y] if parent[y] == u else s - cnt[u]

    while True:
        c = min(adj[u], key=lambda y: (-side(y), y))
        phi = side(c)  # @line L13
        if phi <= s - k:  # @line L14
            break
        u = c
    children = sorted(adj[u], key=lambda y: (-side(y), y))

    def subtree(top: int) -> set[int]:
        """The vertices on the side of top when the edge u-top is cut."""
        out = {top}
        st = [top]
        while st:
            v = st.pop()
            for y in adj[v]:
                if y != u and y not in out:
                    out.add(y)
                    st.append(y)
        return out

    if phi >= k:  # @line L15
        part = subtree(c)
        adj[u].discard(c)
        adj[c].discard(u)
        return part, set(adj) - part
    group: set[int] = set()  # @line L16
    taken: list[int] = []
    got = 0
    for y in children:
        if got >= k:
            break
        group |= subtree(y)
        taken.append(y)
        got += side(y)
    steiner = len(vec)  # @line L17
    vec.append(vec[u])
    real.append(False)
    adj[steiner] = set()
    for y in taken:
        adj[u].discard(y)
        adj[y].discard(u)
        adj[y].add(steiner)
        adj[steiner].add(y)
    group.add(steiner)
    return group, set(adj) - group


def anonymize(rows: Sequence[Row], k: int) -> tuple[list[list[int]], list[tuple[Optional[Hashable], ...]], int]:
    """Return (clusters, table, cost). The clusters partition the row indices; each has
    between k and 3k - 3 rows. In table, each cell of a column on which the rows
    of its cluster differ is None. The cost is the number of None cells, and it is at
    most (3k - 3) times the optimal cost.

    Precondition: 2 <= k <= len(rows), and all rows have the same length d.
    Cost: O(n^2 d) time for the weights and the forest, O(n^2 log n) time for at most
    n / k splits of O(n log n) each, and O(n^2) space.
    """
    n = len(rows)
    edges = build_forest(rows, k)
    vec: list[Row] = list(rows)
    real = [True] * n
    adj_all: dict[int, set[int]] = {v: set() for v in range(n)}
    for u, x in edges:
        adj_all[u].add(x)
        adj_all[x].add(u)
    seen: set[int] = set()
    trees: list[set[int]] = []  # @line L7
    for v in range(n):
        if v not in seen:
            comp = {v}
            st = [v]
            while st:
                y = st.pop()
                for z in adj_all[y]:
                    if z not in comp:
                        comp.add(z)
                        st.append(z)
            seen |= comp
            trees.append(comp)
    done: list[set[int]] = []
    work = trees
    while work:  # @line L8
        t = work.pop()
        if sum(1 for v in t if real[v]) <= 3 * k - 3:
            done.append(t)
            continue
        adj = {v: set(y for y in adj_all[v] if y in t) for v in t}
        a, b = _decompose(vec, real, adj, k)  # @line L9
        for v in adj:
            adj_all[v] = adj[v]
        work.append(a)
        work.append(b)
    clusters = sorted(sorted(v for v in t if real[v]) for t in done)
    table: list[tuple[Optional[Hashable], ...]] = [tuple(r) for r in rows]
    cost = 0
    d = len(rows[0])
    for cl in clusters:  # @line L10
        differ = [j for j in range(d) if len({rows[i][j] for i in cl}) > 1]
        cost += len(cl) * len(differ)
        for i in cl:
            table[i] = tuple(None if j in differ else rows[i][j] for j in range(d))
    return clusters, table, cost  # @line L11
test_k_anonymity_approximation.py 107 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/k-anonymity-approximation/. The authors are listed in prov/3CXF3J.jsonl.
import random
from collections import Counter

from k_anonymity_approximation import anonymize, build_forest, hamming

ROWS = [
    (0, 0, 0, 0),
    (0, 0, 0, 1),
    (0, 0, 1, 1),
    (1, 1, 1, 1),
    (1, 1, 1, 0),
    (1, 1, 0, 0),
    (0, 1, 0, 1),
]


def block_cost(rows, block):
    d = len(rows[0])
    return len(block) * sum(1 for j in range(d) if len({rows[i][j] for i in block}) > 1)


def partitions(items):
    if not items:
        yield []
        return
    first, rest = items[0], items[1:]
    for part in partitions(rest):
        for i in range(len(part)):
            yield part[:i] + [[first] + part[i]] + part[i + 1:]
        yield [[first]] + part


def optimum(rows, k):
    return min(
        sum(block_cost(rows, b) for b in part)
        for part in partitions(list(range(len(rows))))
        if all(len(b) >= k for b in part)
    )


def forest_weight(rows, edges):
    return sum(hamming(rows[u], rows[x]) for u, x in edges)


def check(rows, k):
    clusters, table, cost = anonymize(rows, k)
    n = len(rows)
    assert sorted(i for c in clusters for i in c) == list(range(n))
    assert all(k <= len(c) <= 3 * k - 3 for c in clusters)
    assert cost == sum(block_cost(rows, c) for c in clusters)
    assert cost == sum(1 for r in table for x in r if x is None)
    counts = Counter(table)
    assert all(counts[r] >= k for r in table)
    for i in range(n):
        assert all(table[i][j] is None or table[i][j] == rows[i][j] for j in range(len(rows[i])))
    return clusters, cost


def test_page_example() -> None:
    edges = build_forest(ROWS, 3)
    assert edges == [(0, 1), (1, 2), (3, 4), (4, 5), (6, 1)]
    assert forest_weight(ROWS, edges) == 5
    clusters, cost = check(ROWS, 3)
    assert clusters == [[0, 1, 2, 6], [3, 4, 5]]
    assert cost == 4 * 3 + 3 * 2
    assert optimum(ROWS, 3) == 18


def test_split_of_a_large_tree() -> None:
    rows = [(i,) for i in range(8)]
    clusters, cost = check(rows, 2)
    assert all(len(c) <= 3 for c in clusters)
    assert cost <= 3 * optimum(rows, 2)


def test_edge_cases() -> None:
    assert anonymize([(1, 2), (1, 2)], 2) == ([[0, 1]], [(1, 2), (1, 2)], 0)
    assert anonymize([(1, 2), (3, 4)], 2) == ([[0, 1]], [(None, None), (None, None)], 4)
    same = [(5, 5, 5)] * 9
    clusters, cost = check(same, 2)
    assert cost == 0


def test_random_against_brute_force() -> None:
    rng = random.Random(2005)
    for _ in range(500):
        k = rng.randint(2, 3)
        n = rng.randint(k, 7)
        d = rng.randint(1, 4)
        sigma = rng.randint(2, 3)
        rows = [tuple(rng.randrange(sigma) for _ in range(d)) for _ in range(n)]
        _, cost = check(rows, k)
        opt = optimum(rows, k)
        assert forest_weight(rows, build_forest(rows, k)) <= opt
        assert cost <= (3 * k - 3) * opt


def test_random_larger_tables() -> None:
    rng = random.Random(77)
    for _ in range(200):
        k = rng.randint(2, 5)
        n = rng.randint(k, 30)
        d = rng.randint(1, 4)
        rows = [tuple(rng.randrange(3) for _ in range(d)) for _ in range(n)]
        check(rows, k)

History

Meyerson and Williams (2004) proved that k-anonymity by suppression is NP-hard and gave the first approximation algorithms, with ratio O(klog⁡k)O(k \log k). Aggarwal, Feder, Kenthapadi, Motwani, Panigrahy, Thomas and Zhu (ICDT 2005) gave the forest algorithm with ratio O(k)O(k), showed that a ternary alphabet is enough for NP-hardness, and showed that O(k)O(k) is the best ratio for methods that use only the distances. Park and Shim (2007) later lowered the ratio to O(log⁡k)O(\log k).

References

  1. Gagan Aggarwal, Tomas Feder, Krishnaram Kenthapadi, Rajeev Motwani, Rina Panigrahy, Dilys Thomas and An Zhu, Anonymizing tables, Proceedings of ICDT 2005, LNCS 3363, pp. 246 to 258, the graph representation, the forest algorithm, the decomposition of large trees, the ratio 3k - 3 and its improvement to max(2k - 1, 3k - 5), and the lower bound for the graph representation
  2. Adam Meyerson and Ryan Williams, On the complexity of optimal k-anonymity, Proceedings of the 23rd ACM Symposium on Principles of Database Systems (PODS 2004), pp. 223 to 228, Section 4, the O(k log k) and O(k log m) approximations and the bound of Lemma 4.1
  3. Hyoungmin Park and Kyuseok Shim, Approximate algorithms for k-anonymity, Proceedings of ACM SIGMOD 2007, pp. 67 to 78, the O(log k) approximation

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