Algorithm Search⌘K

Algorithmcore

Datafly

Also called Datafly algorithm.

Greedily generalizes the quasi-identifier attribute with the most distinct values until few records violate k-anonymity, then suppresses those.

Time
O(h n d) worst
Space
O(n d) extra
Where
d = the number of quasi-identifier attributes; h = the sum of the hierarchy heights; n = the number of rows
Origin
Latanya Sweeney, 1997

Datafly is the greedy algorithm of Sweeney for k-anonymity by full-domain generalization and suppression. It starts from the raw table. While more than kk rows are in classes of fewer than kk rows, it raises by one level the quasi-identifier attribute that has the most distinct values. Then it suppresses the rows that are still in small classes. The release is always k-anonymous, and the algorithm is fast, but the result is not always a minimal generalization: it is a greedy heuristic for the choice of the levels.

In plain words

The attribute with the most different values is the one that makes rows look different from each other, such as a full date of birth. So coarsen it first: write the date as year and month. Look again at the table. If many rows are still alone or in very small groups, coarsen the attribute that now has the most different values. Stop when only a few rows, at most kk, are still in small groups. Delete those rows and release the rest.

Each step is a good local move, but it does not look ahead. It can coarsen an attribute that did not need it.

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, where level hah_a maps all values to one value, and an integer k≥1k \ge 1. The output is a vector vv with 0≤va≤ha0 \le v_a \le h_a and a set ss of at most kk rows such that TT generalized by vv, without the rows of ss, is k-anonymous. Let h=∑ahah = \sum_a h_a. The value of kk is a policy choice.

The algorithm

  1. DATAFLY(T, H, k)
  2. 1v ← (0, ..., 0)
  3. 2loop
  4. 3T' ← T generalized by v
  5. 4s ← the rows of T' whose tuple occurs fewer than k times in T'
  6. 5if |s| ≤ k then exit the loop
  7. 6a ← the attribute with the most distinct values in T', ties to the lowest index
  8. 7v_a ← v_a + 1
  9. 8return (v, s)

The release is T′T' without the rows of ss, in a random order. Line L4 counts the tuples with a hash table.

Sweeney's Figure 8 has a further step. Her version replaces the values of the suppressed rows by stars and keeps the rows, so these rows form a class of their own, and a last step makes that class k-anonymous too. The version here removes the suppressed rows, so that step is not needed. The stop test of line L5 bounds the number of removed rows by kk.

Example

Take the 9 rows of Ciriani et al. (2007), with race, date of birth (yy/mm/dd), sex and ZIP:

row race birth sex ZIP
1 asian 64/04/12 F 94142
2 asian 64/09/13 F 94141
3 asian 64/04/15 F 94139
4 asian 63/03/13 M 94139
5 asian 63/03/18 M 94139
6 black 64/09/27 F 94138
7 black 64/09/27 F 94139
8 white 64/09/27 F 94139
9 white 64/09/27 F 94141

The hierarchies are: race to person; birth to yy/mm, to yy, to *; sex to *; ZIP to 4 digits and a star, to 3 digits, to *. Let k=2k = 2.

v (race, birth, sex, ZIP) distinct values rows in small classes action
(0, 0, 0, 0) 3, 6, 2, 4 9 raise birth
(0, 1, 0, 0) 3, 3, 2, 4 7 raise ZIP
(0, 1, 0, 1) 3, 3, 2, 2 5 raise race (tie with birth, lower index)
(1, 1, 0, 1) 1, 3, 2, 2 2 stop, suppress rows 1 and 3

The release has the classes {2,9}\{2, 9\} = (person, 64/09, F, 9414*), {4,5}\{4, 5\} = (person, 63/03, M, 9413*) and {6,7,8}\{6, 7, 8\} = (person, 64/09, F, 9413*). With k=3k = 3 the run goes on to (1, 2, 0, 1) and suppresses rows 4 and 5.

The vector (0, 1, 0, 2), of the same height 3, keeps the race and leaves only 1 row to suppress. Datafly does not find it, because at the third step it raised race and not ZIP.

Correctness

If the loop goes on, some attribute has at least 2 distinct values in T′T'. Otherwise all rows of T′T' are equal, and ∣s∣|s| is 0 (when n≥kn \ge k) or n<kn < k, so line L5 stops. Line L6 then picks an attribute with at least 2 values, which is not at its top level, because the top level has one value. So line L7 keeps va≤hav_a \le h_a, and the height grows by one in each round. The loop stops after at most h+1h + 1 rounds. At the stop, each row outside ss is in a class of at least kk rows of T′T', and all rows of that class are outside ss, so the release is k-anonymous. The full proof is in proofs/correctness.md.

Proof: Datafly stops and releases a k-anonymous tablefull

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 level hah_a maps every value of aa to one value. Let h=∑ahah = \sum_a h_a, and let k≥1k \ge 1. We write TvT_v for TT generalized by the vector vv. Line L4 computes ss, the set of rows of TvT_v whose combination of values occurs fewer than kk times in TvT_v.

Lemma 1. If line L5 does not stop the loop, then line L6 picks an attribute aa with va<hav_a < h_a.

Proof. Assume that each attribute has one distinct value in TvT_v. Then all the nn rows of TvT_v are equal. If n≥kn \ge k, no row is in a group of fewer than kk rows, so ∣s∣=0|s| = 0. If n<kn < k, all rows are in ss, so ∣s∣=n<k|s| = n < k. In both cases ∣s∣≤k|s| \le k, and line L5 stops the loop. So if the loop goes on, some attribute has at least 2 distinct values in TvT_v, and line L6 picks an attribute aa with the most distinct values, so with at least 2. Level hah_a gives one value, so va<hav_a < h_a. □\square

Theorem. DATAFLY stops after at most h+1h + 1 rounds of the loop of line L2. It returns (v,s)(v, s) with 0≤va≤ha0 \le v_a \le h_a for each aa and ∣s∣≤k|s| \le k, and the table TvT_v without the rows of ss is k-anonymous.

Proof. Line L1 sets v=(0,…,0)v = (0, \ldots, 0). By Lemma 1, each round that does not stop raises one level vav_a by one with va<hav_a < h_a before the step (line L7). So 0≤va≤ha0 \le v_a \le h_a stays true, and the height ∑ava\sum_a v_a goes up by one in each such round. The height is at most hh, so at most hh rounds go on, and the next round stops. This gives at most h+1h + 1 rounds.

The loop stops only at line L5, so ∣s∣≤k|s| \le k at line L8. Let RR be the rows of TvT_v that are not in ss. Each row of RR has a combination of values that occurs at least kk times in TvT_v. All the rows with this combination are outside ss, because ss holds a row exactly when its combination occurs fewer than kk times. So each combination of RR occurs at least kk times in RR, and RR is k-anonymous. ■\blacksquare

Remark. The theorem says nothing about the quality of vv. The page gives a table where Datafly returns a vector of height 2 while a vector of height 1 also has at most kk rows to suppress. Datafly is a heuristic for the choice of vv, and only the k-anonymity of the release is a theorem.

Complexity

Let nn be the number of rows, dd the number of attributes and hh the sum of the hierarchy heights. The model is the word RAM with hashing.

  • One round generalizes the nn rows (line L3), counts the tuples (line L4) and counts the distinct values per attribute (line L6): O(nd)O(n d) expected time.
  • There are at most h+1h + 1 rounds, so the time is O(hnd)O(h n d) expected, and the space is O(nd)O(n d).

This is much less than the O(ndglog⁡h)O(n d g \log h) of Samarati's algorithm, where gg is the size of the lattice, because Datafly follows one path up the lattice.

Properties

  • Always k-anonymous. This is a theorem, for each input.
  • Not minimal. The result is a heuristic choice. Sweeney (2002) says that Datafly can generalize more than needed. A small case: attribute A with values 0 to 3 and levels (value, value div 2, *), attribute B with values 0 to 2 and levels (value, *), and the rows (3, 0), (2, 2), (1, 0), (2, 1), (0, 0), (0, 0) with k=2k = 2. Datafly returns (1, 1). The lower vector (0, 1) leaves only rows 1 and 3 to suppress, which is at most kk.
  • At most k suppressed rows. The limit on suppression is tied to kk and is not a separate parameter, as MaxSup is in Samarati's algorithm.
  • Deterministic, with the tie rule of line L6.

Variants and improvements

  • The Datafly system. Sweeney (1997) describes a whole system for the release of medical records, with more inputs and choices than the core algorithm. The core algorithm here is the part that Sweeney (2002) analyzes.
  • Other greedy rules. Choose the attribute that most reduces the number of rows in small classes, or that loses the least precision per step. These are also heuristics.
  • Exact searches. Samarati's algorithm finds a vector of least height, and Incognito finds all k-anonymous vectors.
  • Multidimensional cuts. Mondrian is also greedy, but it cuts boxes of the value space and loses less detail on numeric data.

When to use it

Use Datafly when the lattice is too large to search, a fast and always k-anonymous answer is enough, and some extra generalization is acceptable. It is also a good baseline for the exact algorithms. If the least generalization matters, use Samarati's algorithm or Incognito on the same hierarchies.

Pitfalls

  • A table with at most k rows. If n≤kn \le k, then ∣s∣≤n≤k|s| \le n \le k at once, and line L5 stops at the raw table with every row in ss. Nothing is released. Check n>kn > k first.
  • Distinct values of the raw table in line L6. The counts must come from the current table T′T'. With the counts of the raw table, the same attribute stays the largest, and line L7 raises it to its top before it looks at any other.
  • Keeping the suppressed rows with stars in line L8. If the rows of ss are released with all quasi-identifier values replaced by stars, they form one class of ∣s∣|s| rows, and ∣s∣|s| can be less than kk. Remove them, or add the last step of Sweeney's Figure 8.
  • A top level with more than one value. Then line L7 can push vav_a past hah_a. Each hierarchy must end in a single value.

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.

datafly.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/datafly/. The authors are listed in prov/JK6NEV.jsonl.
"""Sweeney's Datafly heuristic for k-anonymity by full-domain generalization and row suppression.

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, hierarchy[a][0] is the identity,
and the last level maps every value of the attribute to one value.
"""

from collections import Counter
from typing import Hashable, Sequence

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


def datafly(table: Sequence[Row], hierarchy: Hierarchy, k: int) -> tuple[tuple[int, ...], list[int]]:
    """Return (v, s): the generalization vector chosen by Datafly and the sorted indices of the
    rows to suppress. The table generalized by v, without the rows in s, is k-anonymous,
    and s has at most k rows.

    Precondition: k >= 1, every row has d values, and the top level of each hierarchy
    maps all values of its attribute to one value.
    Cost: at most h + 1 rounds, where h is the sum of the hierarchy heights, and
    O(n d) expected time per round for n rows and d attributes.
    """
    d = len(hierarchy)
    v = [0] * d  # @line L1
    while True:  # @line L2
        gen = [tuple(hierarchy[a][v[a]][row[a]] for a in range(d)) for row in table]  # @line L3
        counts = Counter(gen)
        s = [i for i, g in enumerate(gen) if counts[g] < k]  # @line L4
        if len(s) <= k:  # @line L5
            break
        distinct = [len({g[a] for g in gen}) for a in range(d)]
        best = max(range(d), key=lambda a: (distinct[a], -a))  # @line L6
        v[best] += 1  # @line L7
    return tuple(v), s  # @line L8
test_datafly.py 107 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/datafly/. The authors are listed in prov/JK6NEV.jsonl.
import random

from datafly import datafly

ROWS = [
    ("asian", "64/04/12", "F", "94142"),
    ("asian", "64/09/13", "F", "94141"),
    ("asian", "64/04/15", "F", "94139"),
    ("asian", "63/03/13", "M", "94139"),
    ("asian", "63/03/18", "M", "94139"),
    ("black", "64/09/27", "F", "94138"),
    ("black", "64/09/27", "F", "94139"),
    ("white", "64/09/27", "F", "94139"),
    ("white", "64/09/27", "F", "94141"),
]
RACES = ["asian", "black", "white"]
DOBS = sorted({r[1] for r in ROWS})
ZIPS = sorted({r[3] for r in ROWS})
HIER = [
    [{x: x for x in RACES}, {x: "person" for x in RACES}],
    [{x: x for x in DOBS}, {x: x[:5] for x in DOBS}, {x: x[:2] for x in DOBS}, {x: "*" for x in DOBS}],
    [{"F": "F", "M": "M"}, {"F": "*", "M": "*"}],
    [{z: z for z in ZIPS}, {z: z[:4] + "*" for z in ZIPS}, {z: z[:3] + "**" for z in ZIPS}, {z: "*" for z in ZIPS}],
]


def test_page_example() -> None:
    assert datafly(ROWS, HIER, 2) == ((1, 1, 0, 1), [0, 2])
    assert datafly(ROWS, HIER, 3) == ((1, 2, 0, 1), [3, 4])


def test_not_minimal() -> None:
    hier = [
        [{i: i for i in range(4)}, {i: i // 2 for i in range(4)}, {i: 0 for i in range(4)}],
        [{i: i for i in range(3)}, {i: 0 for i in range(3)}],
    ]
    rows = [(3, 0), (2, 2), (1, 0), (2, 1), (0, 0), (0, 0)]
    assert datafly(rows, hier, 2) == ((1, 1), [])
    # The vector (0, 1) is strictly lower and leaves only 2 = k rows to suppress.
    assert violators(rows, hier, (0, 1), 2) == [0, 2]


def test_edge_cases() -> None:
    assert datafly([], HIER, 2) == ((0, 0, 0, 0), [])
    assert datafly(ROWS[:1], HIER, 2) == ((0, 0, 0, 0), [0])
    assert datafly(ROWS, HIER, 1) == ((0, 0, 0, 0), [])
    same = [ROWS[0]] * 5
    assert datafly(same, HIER, 5) == ((0, 0, 0, 0), [])
    assert datafly(same, HIER, 6) == ((0, 0, 0, 0), [0, 1, 2, 3, 4])
    assert datafly(ROWS, HIER, 8) == ((1, 3, 1, 2), [])
    # With n <= k the stop test holds at once, and every row is suppressed.
    assert datafly(ROWS, HIER, 9) == ((0, 0, 0, 0), list(range(9)))


def violators(rows, hier, v, k):
    keys = [tuple(hier[a][v[a]][r[a]] for a in range(len(v))) for r in rows]
    return [i for i, key in enumerate(keys) if keys.count(key) < k]


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(rows, hier, k):
    """Datafly from its definition, with the stop test and the choice written out again."""
    d = len(hier)
    v = [0] * d
    while len(violators(rows, hier, v, k)) > k:
        keys = [tuple(hier[a][v[a]][r[a]] for a in range(d)) for r in rows]
        best, best_count = 0, -1
        for a in range(d):
            count = len(set(key[a] for key in keys))
            if count > best_count:
                best, best_count = a, count
        v[best] += 1
    return tuple(v), violators(rows, hier, v, k)


def test_random_against_definition() -> None:
    rng = random.Random(1997)
    for _ in range(800):
        d = rng.randint(1, 4)
        sizes = [rng.randint(1, 5) for _ in range(d)]
        hier = [random_hierarchy(rng, r) for r in sizes]
        n = rng.randint(0, 20)
        rows = [tuple(rng.randrange(r) for r in sizes) for _ in range(n)]
        k = rng.randint(1, 5)
        v, s = datafly(rows, hier, k)
        assert (v, s) == oracle(rows, hier, k)
        assert len(s) <= k
        assert all(0 <= v[a] < len(hier[a]) for a in range(d))
        kept = [r for i, r in enumerate(rows) if i not in set(s)]
        keys = [tuple(hier[a][v[a]][r[a]] for a in range(d)) for r in kept]
        assert all(keys.count(key) >= k for key in keys)

History

Sweeney built the Datafly system for the release of medical records and described it at the AMIA symposium in 1997. In 2002 she gave the core Datafly algorithm, together with the exact but slow MinGen, and showed that Datafly can generalize more than a minimal generalization. Later work, such as Incognito (2005), compared exact full-domain search with such greedy methods.

References

  1. Latanya Sweeney, Guaranteeing anonymity when sharing medical data, the Datafly system, Proceedings of the AMIA Annual Fall Symposium, 1997, pp. 51 to 55, the Datafly system and its generalization of the attributes with the most distinct values
  2. 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, Figure 8, the core Datafly algorithm, and the discussion of why its result need not be minimal
  3. 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, the summary of the greedy algorithm of Sweeney among the algorithms for k-anonymity
  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 discussion of greedy full-domain algorithms that do not find a minimal 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