linkage-attack/attack.py
2026-11-02 07:38:59 -07:00

84 lines
2.6 KiB
Python

"""The attack, and the defense that fails. You write the six functions marked YOUR TASK.
A quasi-identifier (QI) is a set of fields that is not a name but narrows a
record down to a person: ZIP code, birth date, sex. `qi` below is always a
tuple of field names, such as ("zip", "dob", "sex").
Records are dicts, as data.py returns them. Nothing here may call
data.true_names(): an attacker does not have the answer key.
Python reference: https://docs.python.org/3/library/collections.html#collections.Counter
"""
from collections import Counter, defaultdict
def key(record, qi):
"""The record's values for the quasi-identifier fields, as a tuple."""
return tuple(record[f] for f in qi)
def uniqueness(records, qi):
"""The share of records that no other record matches on qi (0.0 to 1.0).
YOUR TASK. This is Sweeney's measurement: how many people are the only
one with their combination.
"""
raise NotImplementedError("uniqueness")
def link(release, roll, qi):
"""Re-identify the release by joining it to the roll on qi.
Returns a list as long as `release`: for each released record, the name of
the one roll record with the same qi values, or None when no roll record
matches or more than one does.
YOUR TASK.
"""
raise NotImplementedError("link")
def generalize(record, level):
"""A copy of the record with its quasi-identifiers coarsened.
level 0: unchanged.
level 1: dob becomes the birth year ("1962").
level 2: dob becomes the decade ("1960s") and zip keeps its first three
digits ("809**").
sex and every other field stay as they are.
YOUR TASK. This is the generalization step of k-anonymity.
"""
raise NotImplementedError("generalize")
def k_anonymity(records, qi):
"""The size of the smallest group of records sharing the same qi values.
YOUR TASK. A release is k-anonymous when this is at least k.
"""
raise NotImplementedError("k_anonymity")
def suppress(records, qi, k):
"""The records left after removing every qi group smaller than k.
Generalization plus this suppression is how k-anonymity is reached: the
result is k-anonymous, at the cost of the records dropped. Keep the
records' original order.
YOUR TASK.
"""
raise NotImplementedError("suppress")
def homogeneity(records, qi, sensitive):
"""The share of records whose qi group has only one value of `sensitive`.
For those people the attacker learns the sensitive value (a diagnosis)
without learning which row is theirs: the homogeneity attack.
YOUR TASK.
"""
raise NotImplementedError("homogeneity")