Algorithm Search⌘K

Algorithmcore

Incognito

Also called Incognito algorithm.

Finds all k-anonymous full-domain generalizations, and the minimal ones, by a bottom-up search over growing subsets of attributes, as in a priori.

Time
O(2^d g n d) worst
Space
O(2^d g n) extra
Where
d = the number of quasi-identifier attributes; g = the number of vectors of the full lattice; n = the number of rows
Origin
Kristen LeFevre, David J. DeWitt, Raghu Ramakrishnan, 2005

Incognito finds every full-domain generalization vector that makes a table k-anonymous, and marks the minimal ones. It uses two facts. If a table is k-anonymous on a set of attributes, it is k-anonymous on each subset of it. And if a vector is k-anonymous, each vector above it is too. So Incognito first finds the k-anonymous vectors of single attributes, then of pairs, then of triples, and builds the candidates of each size only from the survivors of the size below, as the a priori algorithm does for frequent item sets. Inside each lattice it goes up by height and does not check a node that already has a k-anonymous node below it.

In plain words

First look at each attribute alone. For race, find the levels of detail at which every race value appears at least kk times. Do the same for sex and for marital status. A level that fails alone also fails with other attributes, so drop it.

Then look at pairs of attributes, but only with the levels that survived alone. Then at triples, built only from the pairs that survived. In each step, start with the most detailed choices. If a choice works, each coarser choice works too, so mark them as good without checking. If a choice fails, try the choices one step coarser.

Counting can also be saved: the counts at a coarser level come from adding up the counts at the finer level, without reading the table again.

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, and an integer k≥1k \ge 1. A node is a set AA of attributes with a level for each of them. It is k-anonymous if the projection of TT on AA, generalized to these levels, has no tuple that occurs fewer than kk times. The output is the set of all k-anonymous vectors over the dd attributes, and the subset of them that have no k-anonymous vector strictly below. The full lattice has g=∏a(ha+1)g = \prod_a (h_a + 1) vectors. The value of kk is a policy choice.

The algorithm

  1. INCOGNITO(T, H, k)
  2. 1C ← all nodes of one attribute, with each level of its hierarchy
  3. 2for i ← 1 to d do
  4. 3S ← C
  5. 4put the roots of C (nodes with no direct specialization in C) in a queue Q ordered by height
  6. 5while Q is not empty do
  7. 6node ← the node of least height in Q, removed from Q
  8. 7if node is marked then continue at L5
  9. 8F ← the frequency set of node: counted from T if node is a root, else rolled up from its parent's set
  10. 9if each count in F is at least k then
  11. 10mark each direct generalization of node
  12. 11else remove node from S
  13. 12put each direct generalization of node in C into Q, with node as its parent, unless it is in Q already
  14. 13if i < d then C ← the nodes of i + 1 attributes made by joining two nodes of S that agree on all but their last attribute, kept only if each of their subsets of i attributes is in S
  15. 14all ← S
  16. 15minimal ← the vectors of all with no direct specialization in all
  17. 16return (all, minimal)

A direct generalization raises one level by one, and a direct specialization lowers one level by one. The frequency set of a node is the count of each tuple of the generalized projection. Line L8 rolls up the set of the parent by mapping each value of one attribute to its parent value in the hierarchy and adding the counts, which is correct because the hierarchy is a tree. The priority queue of line L4 is a priority queue on the height, so the search inside one lattice goes up level by level, like a breadth-first search from the roots.

Example

Take the 9 rows of Ciriani et al. (2007) with race (R0 value, R1 person), sex (S0 value, S1 *) and marital status (M0 value, M1 been married or never married, M2 *): asian F divorced twice, asian F married, asian M married twice, black F single twice, white F single, and white F widow. Let k=2k = 2. Incognito does 11 checks.

round node checked from smallest count result
1 R0 table 2 anonymous, mark R1
1 S0 table 2 anonymous, mark S1
1 M0 table 1 (widow) remove, queue M1
1 M1 roll-up of M0 3 anonymous, mark M2
2 (R0, S0) table 2 anonymous
2 (R0, M1) table 1 (white, been married) remove, queue (R1, M1) and (R0, M2)
2 (S0, M1) table 2 anonymous
2 (R0, M2) roll-up 2 anonymous
2 (R1, M1) roll-up 3 anonymous
3 (R0, S0, M2) table 2 anonymous
3 (R1, S0, M1) table 2 anonymous

Round 1 drops only M0, so the pairs of round 2 use M1 and M2. In round 2, (R0, M1) is a root of the race and marital lattice, because its specialization (R0, M0) was pruned. Round 3 gets 6 candidates from the join of line L13. The two roots are k-anonymous, and they mark the other 4, which are never checked. The answer is the 6 vectors (0, 0, 2), (0, 1, 2), (1, 0, 1), (1, 0, 2), (1, 1, 1) and (1, 1, 2), and the minimal ones are (0, 0, 2) and (1, 0, 1).

Correctness

Two properties of k-anonymity carry the proof. Generalization: a node above a k-anonymous node is k-anonymous, because its classes are unions of classes. Subset: a k-anonymous node gives k-anonymous nodes on each subset of its attributes, for the same reason. Inside one round, a node leaves SS only after a check that fails, so no anonymous node is lost. By induction on the height, each node of CC that is not anonymous is checked: either it is a root and line L4 queues it, or each of its direct specializations in CC fails, and line L12 queues it. It is never marked, because no node below it is anonymous. So after the round SS is exactly the anonymous nodes of CC. By the subset property, the join of line L13 keeps every anonymous node of the next size. After round dd, SS is the set of all k-anonymous vectors, and a vector is minimal exactly when no direct specialization is in SS. The full proof is in proofs/correctness.md.

Proof: Incognito returns all k-anonymous full-domain generalizations and the minimal onesfull

The table TT has nn rows and dd quasi-identifier attributes. Attribute aa has a hierarchy with levels 0,…,ha0, \ldots, h_a, and each level coarsens the level below it. A node is a pair (A,l)(A, l): a set AA of attributes, written in increasing order, and a level lal_a for each a∈Aa \in A. The node is anonymous when the projection of TT on AA, with each attribute aa generalized to level lal_a, has no combination of values that occurs fewer than kk times. A direct generalization of (A,l)(A, l) raises one level by one, and a direct specialization lowers one level by one. Line L8 computes the frequency set of a node, and line L9 tests that each count is at least kk, so a check of a node is correct when its frequency set is correct.

Lemma 1 (generalization). If (A,l)(A, l) is anonymous and l≤l′l \le l' for each attribute, then (A,l′)(A, l') is anonymous.

Proof. The value at a higher level is a function of the value at a lower level, so each group of equal rows at l′l' is a union of groups at ll. A union of groups of at least kk rows has at least kk rows. □\square

Lemma 2 (subset). If (A,l)(A, l) is anonymous and B⊆AB \subseteq A, then (B,l∣B)(B, l|_B) is anonymous.

Proof. Rows that are equal on AA are equal on BB, so each group on BB is a union of groups on AA. □\square

Lemma 3 (roll-up). The roll-up of line L8 is the frequency set of the node.

Proof. A node cc gets a parent link at line L12 only from a direct specialization bb that was checked, with the frequency set of bb, at a position pp with cp=bp+1c_p = b_p + 1. Because the hierarchy of the attribute at position pp is a tree, each value at level bpb_p has one parent value at level bp+1b_p + 1. So the rows of a combination of bb all go to one combination of cc, and summing the counts of bb by the new combination gives the counts of cc. By induction on the order of the checks, the frequency set of bb is correct, so the frequency set of cc is correct. □\square

Lemma 4 (one round). Let CC be the set of candidate nodes of size ii at line L3. After the loop of line L5, S={c∈C:c is anonymous}S = \{c \in C : c \text{ is anonymous}\}.

Proof. A node leaves SS only at line L11, after a check that fails, so no anonymous node leaves SS. We show by strong induction on the height ∑ala\sum_a l_a that each node c∈Cc \in C that is not anonymous is checked, so that line L11 removes it. Two facts help. First, a node is marked at line L10 only when a direct specialization of it is checked and is anonymous, and only nodes of CC are checked. Second, by Lemma 1 a direct generalization of an anonymous node is anonymous.

Let c∈Cc \in C not be anonymous. Then no direct specialization of cc is anonymous, by Lemma 1, so cc is never marked, and line L7 does not skip it if it is ever in the queue. If cc has no direct specialization in CC, line L4 puts it in the queue. Otherwise each direct specialization b∈Cb \in C of cc has a lower height and is not anonymous, so by the induction hypothesis bb is checked and fails. Then line L12 puts cc in the queue, unless it is already there. In both cases cc is popped at line L6 and checked, and by Lemma 3 the check is correct. So cc fails the test of line L9 and leaves SS at line L11. □\square

Lemma 5 (candidates). For each ii, the candidate set CiC_i of size ii holds every anonymous node of size ii.

Proof. Line L1 puts every node of size 1 in C1C_1. Assume the claim for ii, and let N=(A,l)N = (A, l) be an anonymous node of size i+1i + 1, with attributes a1<⋯<ai+1a_1 < \cdots < a_{i+1}. By Lemma 2, each node that NN gives on ii of its attributes is anonymous. By the hypothesis and Lemma 4, all of them are in SS after round ii. Let xx be NN without ai+1a_{i+1} and yy be NN without aia_i. They agree on a1,…,ai−1a_1, \ldots, a_{i-1} and their levels, and the last attribute of xx is less than the last attribute of yy. So line L13 joins them into NN, and the test that each ii-subset of NN is in SS holds. So N∈Ci+1N \in C_{i+1}. □\square

Theorem. INCOGNITO returns the list of all vectors vv over the dd attributes such that TT generalized by vv is k-anonymous, and the list of the vectors of it that have no k-anonymous vector strictly below them.

Proof. A node of size dd is a vector over all attributes. By Lemma 5, CdC_d holds every anonymous vector, and by Lemma 4 the set SS after round dd is exactly the set of anonymous vectors. Line L14 returns it. Line L15 keeps the vectors vv of SS with no direct specialization in SS. If an anonymous uu is strictly below vv, then raise the levels of uu one at a time toward vv. The last vector before vv on this chain is a direct specialization of vv, it is at least uu, and it is anonymous by Lemma 1. So vv has no anonymous vector strictly below it if and only if it has no anonymous direct specialization. ■\blacksquare

Remark. The order of the priority queue is not used in the proof. Processing by height is what makes the marks useful. Line L12 pushes only nodes one level above the popped node, so the heights of the popped nodes never go down. So a node is popped after each of its direct specializations that is ever popped, and a mark set by any of them is seen before the check.

Complexity

Let nn be the number of rows, dd the number of attributes and gg the number of vectors of the full lattice. The model is the word RAM with hashing.

  • A node is a subset of the attributes with a vector of levels on it. There are at most 2dg2^d g nodes, because each subset lattice has at most gg vectors.
  • Each check costs O(nd)O(n d) expected time, from the table or by a roll-up of a frequency set of at most nn entries.
  • In total O(2dgnd)O(2^d g n d) expected time in the worst case, and O(2dgn)O(2^d g n) space for the stored frequency sets.

The worst case is far from typical. The pruning of line L13 and the marks of line L10 skip most nodes in practice, and LeFevre et al. (2005) measured Incognito as much faster than the binary search of Samarati on their data sets. That is a measurement on those data sets, not a bound. Any exact search for all k-anonymous vectors must output them, and there can be about gg of them.

Properties

  • Complete. It returns every k-anonymous vector, so a user can choose one by any measure of loss afterwards.
  • No suppression in the basic form. A limit on suppressed rows can be added to the test of line L9 as in Samarati's algorithm. Both properties still hold, because the rows in classes of fewer than kk rows can only become fewer on a subset of the attributes or at higher levels.
  • Any monotone test. The search is correct for each test that has the generalization and subset properties, such as the forms of l-diversity that Machanavajjhala et al. (2007) show to be monotone.
  • Deterministic. The output does not depend on the order of the queue.

Variants and improvements

  • Super-roots Incognito. Compute the frequency set of one node below all roots of a lattice once, and roll up from it, so the table is read fewer times.
  • Cube Incognito. Compute the frequency sets of the projections on all attribute subsets first, as in a data cube, and roll up from them.
  • Samarati's algorithm. Samarati's algorithm finds only one vector of least height, by binary search, and needs no per-subset lattices.
  • Greedy and multidimensional. Datafly is faster and not minimal. Mondrian leaves full-domain generalization for boxes of values.

When to use it

Use Incognito when the hierarchies are small, all minimal full-domain generalizations are wanted, and the loss measure is decided later or by a person. It is also the natural search for other monotone tests, such as l-diversity. With many attributes the 2d2^d subsets and the lattice sizes make it slow, and a greedy or multidimensional method is the practical choice.

Pitfalls

  • Roots of height 0 only in line L4. A root is a node with no direct specialization in CC, and after pruning it can have any height. In the example, (R0, M1) is a root. If line L4 queues only nodes of height 0, (R0, M1) is never checked and stays in SS, so a node that is not anonymous is returned.
  • A roll-up in line L8 with a hierarchy that is not a tree. If a value has two parents, adding the counts by parent value counts some rows twice or puts them in the wrong class.
  • Treating a marked node as removed in line L7. A marked node is anonymous and stays in SS. Removing it loses answers and breaks the join of line L13 for the next round.
  • A join without the subset test in line L13. The answer stays correct, because each candidate is checked, but the number of candidates grows, and the saving of the a priori idea is lost.

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.

incognito.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/incognito/. The authors are listed in prov/KC05HR.jsonl.
"""Incognito: all k-anonymous full-domain generalizations, by an a priori search over attribute sets.

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. Each level must be a coarsening of the level below it, so that the
hierarchy is a tree. A node is a pair (attrs, levels): a sorted tuple of
attribute indices and one level for each of them.
"""

import heapq
from collections import Counter
from typing import Hashable, Optional, Sequence

Row = tuple[Hashable, ...]
Hierarchy = Sequence[Sequence[dict[Hashable, Hashable]]]
Node = tuple[tuple[int, ...], tuple[int, ...]]


def _up_maps(hierarchy: Hierarchy) -> list[list[dict[Hashable, Hashable]]]:
    """up[a][l] maps a value of attribute a at level l to its parent value at level l + 1."""
    up = []
    for levels in hierarchy:
        maps = []
        for lv in range(len(levels) - 1):
            maps.append({levels[lv][x]: levels[lv + 1][x] for x in levels[0]})
        up.append(maps)
    return up


def _frequency(table: Sequence[Row], hierarchy: Hierarchy, node: Node) -> Counter:
    attrs, levels = node
    return Counter(tuple(hierarchy[a][lv][row[a]] for a, lv in zip(attrs, levels)) for row in table)


def _roll_up(freq: Counter, up: list[list[dict[Hashable, Hashable]]], parent: Node, pos: int) -> Counter:
    """Frequency set of the node one level above parent at position pos, from the parent's set."""
    a, lv = parent[0][pos], parent[1][pos]
    out: Counter = Counter()
    for key, c in freq.items():
        new = key[:pos] + (up[a][lv][key[pos]],) + key[pos + 1:]
        out[new] += c
    return out


def _step(node: Node, pos: int, delta: int) -> Node:
    attrs, levels = node
    return attrs, levels[:pos] + (levels[pos] + delta,) + levels[pos + 1:]


def incognito(table: Sequence[Row], hierarchy: Hierarchy, k: int) -> tuple[list[tuple[int, ...]], list[tuple[int, ...]]]:
    """Return (all, minimal): every generalization vector over all d attributes whose
    generalized table is k-anonymous, and those of them with no k-anonymous direct
    specialization. Both lists are sorted.

    Precondition: d >= 1, k >= 1, and each hierarchy is a tree (each level coarsens the one below).
    Cost: at most 2^d g nodes are created, where g is the number of vectors of the full lattice.
    Each check takes O(n d) expected time for n rows, from the table or by a roll-up.
    """
    d = len(hierarchy)
    up = _up_maps(hierarchy)
    tops = [len(levels) - 1 for levels in hierarchy]
    cand: set[Node] = {((a,), (lv,)) for a in range(d) for lv in range(tops[a] + 1)}  # @line L1
    s: set[Node] = set()
    for i in range(1, d + 1):  # @line L2
        s = set(cand)  # @line L3
        marked: set[Node] = set()
        queue: list[tuple[int, Node]] = []
        parent_of: dict[Node, tuple[Counter, Node, int]] = {}
        for node in cand:
            if all(_step(node, p, -1) not in cand for p in range(i) if node[1][p] > 0):
                heapq.heappush(queue, (sum(node[1]), node))  # @line L4
        queued = {node for _, node in queue}
        while queue:  # @line L5
            _, node = heapq.heappop(queue)  # @line L6
            if node in marked:  # @line L7
                continue
            link: Optional[tuple[Counter, Node, int]] = parent_of.get(node)
            if link is None:  # @line L8
                freq = _frequency(table, hierarchy, node)
            else:
                freq = _roll_up(link[0], up, link[1], link[2])
            if all(c >= k for c in freq.values()):  # @line L9
                for p in range(i):
                    if node[1][p] < tops[node[0][p]]:
                        marked.add(_step(node, p, 1))  # @line L10
            else:
                s.discard(node)  # @line L11
                for p in range(i):  # @line L12
                    if node[1][p] < tops[node[0][p]]:
                        gen = _step(node, p, 1)
                        if gen in cand and gen not in queued:
                            parent_of[gen] = (freq, node, p)
                            queued.add(gen)
                            heapq.heappush(queue, (sum(gen[1]), gen))
        if i < d:  # @line L13
            cand = set()
            for x in s:
                for y in s:
                    if x[0][:-1] == y[0][:-1] and x[1][:-1] == y[1][:-1] and x[0][-1] < y[0][-1]:
                        new = (x[0] + (y[0][-1],), x[1] + (y[1][-1],))
                        subsets = ((new[0][:j] + new[0][j + 1:], new[1][:j] + new[1][j + 1:]) for j in range(i + 1))
                        if all(sub in s for sub in subsets):
                            cand.add(new)
    full = sorted(levels for _, levels in s)  # @line L14
    full_set = set(full)
    minimal = [
        v for v in full
        if all(v[:p] + (v[p] - 1,) + v[p + 1:] not in full_set for p in range(d) if v[p] > 0)
    ]  # @line L15
    return full, minimal  # @line L16
test_incognito.py 90 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/incognito/. The authors are listed in prov/KC05HR.jsonl.
import random
from itertools import product

from incognito import incognito

RACES = ["asian", "black", "white"]
STATUS = ["single", "married", "divorced", "widow"]
HIER = [
    [{x: x for x in RACES}, {x: "person" for x in RACES}],
    [{"F": "F", "M": "M"}, {"F": "*", "M": "*"}],
    [
        {x: x for x in STATUS},
        {x: ("never_married" if x == "single" else "been_married") for x in STATUS},
        {x: "*" for x in STATUS},
    ],
]
ROWS = [
    ("asian", "F", "divorced"),
    ("asian", "F", "divorced"),
    ("asian", "F", "married"),
    ("asian", "M", "married"),
    ("asian", "M", "married"),
    ("black", "F", "single"),
    ("black", "F", "single"),
    ("white", "F", "single"),
    ("white", "F", "widow"),
]


def test_page_example() -> None:
    full, minimal = incognito(ROWS, HIER, 2)
    assert minimal == [(0, 0, 2), (1, 0, 1)]
    assert full == [(0, 0, 2), (0, 1, 2), (1, 0, 1), (1, 0, 2), (1, 1, 1), (1, 1, 2)]


def test_edge_cases() -> None:
    all_vectors = sorted(product(range(2), range(2), range(3)))
    assert incognito([], HIER, 3) == (all_vectors, [(0, 0, 0)])
    assert incognito(ROWS, HIER, 1) == (all_vectors, [(0, 0, 0)])
    assert incognito(ROWS[:1], HIER, 2) == ([], [])
    assert incognito(ROWS, HIER, 9) == ([(1, 1, 2)], [(1, 1, 2)])
    one = [[{0: 0, 1: 1, 2: 2}, {0: 0, 1: 0, 2: 1}, {0: 0, 1: 0, 2: 0}]]
    assert incognito([(0,), (1,), (2,), (2,)], one, 2) == ([(1,), (2,)], [(1,)])


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 brute_force(rows, hier, k):
    tops = [len(x) - 1 for x in hier]
    good = []
    for v in product(*(range(t + 1) for t in tops)):
        groups: dict = {}
        for row in rows:
            key = tuple(hier[a][v[a]][row[a]] for a in range(len(v)))
            groups[key] = groups.get(key, 0) + 1
        if all(c >= k for c in groups.values()):
            good.append(v)
    minimal = []
    for v in good:
        below = [w for w in good if w != v and all(w[a] <= v[a] for a in range(len(v)))]
        if not below:
            minimal.append(v)
    return sorted(good), sorted(minimal)


def test_random_against_brute_force() -> None:
    rng = random.Random(2005)
    for _ in range(500):
        d = rng.randint(1, 4)
        sizes = [rng.randint(1, 4) for _ in range(d)]
        hier = [random_hierarchy(rng, r) for r in sizes]
        n = rng.randint(0, 14)
        rows = [tuple(rng.randrange(r) for r in sizes) for _ in range(n)]
        k = rng.randint(1, 4)
        assert incognito(rows, hier, k) == brute_force(rows, hier, k)

History

LeFevre, DeWitt and Ramakrishnan presented Incognito at SIGMOD 2005. They took the a priori idea from frequent item set mining and the roll-up and cube ideas from data cube computation, and they showed that full-domain k-anonymity has the generalization, roll-up and subset properties. In the same year Machanavajjhala et al. used the same search for l-diversity. The authors then moved to multidimensional recoding with Mondrian in 2006.

References

  1. Kristen LeFevre, David J. DeWitt and Raghu Ramakrishnan, Incognito, efficient full-domain k-anonymity, Proceedings of ACM SIGMOD 2005, pp. 49 to 60, the generalization, rollup and subset properties, the basic Incognito algorithm, and the super-roots and cube variants
  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.3, the algorithm Incognito with a worked example on race, sex and marital status
  3. Pierangela Samarati, Protecting respondents' identities in microdata release, IEEE Transactions on Knowledge and Data Engineering 13(6), 2001, pp. 1010 to 1027, the lattice of generalization vectors and minimal generalization
  4. Ashwin Machanavajjhala, Daniel Kifer, Johannes Gehrke and Muthuramakrishnan Venkitasubramaniam, l-diversity, privacy beyond k-anonymity, ACM Transactions on Knowledge Discovery from Data 1(1), 2007, the use of the Incognito search with the l-diversity test in place of the k-anonymity test

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