Algorithm Search⌘K

Algorithmcore

Post-randomization method

Also called PRAM masking.

Replaces each categorical value by a random value drawn from a published Markov matrix, so that analysts can correct for it.

Time
O(n K + K^3) worst
Space
O(K^2) extra
Where
K = the number of categories; n = the number of records
Origin
Peter Kooiman, Leon Willenborg, Jose Gouweleeuw, 1997

The post-randomization method (PRAM) masks a categorical attribute of a microdata file. The agency replaces each value kk by a random value ll, drawn with probability pklp_{kl} from row kk of a transition matrix PP, independently for each record, and it publishes PP together with the data. A person who links a released record to a known person cannot trust its value, because it may be a random replacement. An analyst can still estimate the true counts without bias by solving PTT^=T∗P^{\mathsf T} \hat T = T^*, where T∗T^* are the released counts. It is the agency side of randomized response, where the respondent does the random step. A variant called invariant PRAM chooses the matrix so that the expected released counts equal the true counts. PRAM with a matrix that has no zero entries is also locally differentially private, with ε\varepsilon set by the largest ratio in a column.

In plain words

An office releases a file where each person has a region. Before it publishes, it rolls a die for each person. Most of the time the region stays the same. Sometimes it changes to another region, with chances that the office fixes in a table. The office publishes the table of chances with the data.

A reader who finds a line that looks like a neighbor cannot be sure of the region on that line. But a researcher who counts the people in each region can undo the effect on average. She knows how many people the die moves out of each region and into it, so she can solve for the counts before the die.

The more the die changes, the more privacy, and the noisier the corrected counts.

The problem

The input is a list of nn values x1,…,xnx_1, \ldots, x_n of a categorical attribute with KK categories 1,…,K1, \ldots, K, and a K×KK \times K matrix PP with pkl≥0p_{kl} \ge 0 and ∑lpkl=1\sum_l p_{kl} = 1 for each kk. Such a matrix is the transition matrix of a Markov chain. The output is a released list y1,…,yny_1, \ldots, y_n with Pr⁡[yi=l∣xi=k]=pkl\Pr[y_i = l \mid x_i = k] = p_{kl}, independently for each ii. An analyst who has yy and PP wants the true counts Tk=∣{i:xi=k}∣T_k = |\{i : x_i = k\}|. The choice of PP is a policy choice of the agency: large diagonal entries keep the data close to the truth, small ones protect more.

The algorithm

  1. PRAM(x, P)
  2. 1for i ← 1 to n do
  3. 2k ← x_i
  4. 3u ← a uniform random number in [0, 1)
  5. 4l ← the least l with p_k1 + p_k2 + ... + p_kl > u
  6. 5y_i ← l
  7. 6return y
  8. ESTIMATE(y, P)
  9. 7T* ← the count of each category in y
  10. 8solve P^T T̂ = T* for T̂ ▷ by Gaussian elimination; P must be invertible
  11. 9return T̂

Lines L1 to L6 run at the agency, and lines L7 to L9 at the analyst. Line L4 is the inverse of the cumulative distribution of row kk. The test is strict, so a category with pkl=0p_{kl} = 0 is never chosen. With the cumulative sums stored, a binary search makes line L4 take O(log⁡K)O(\log K) time.

Invariant PRAM. Let TT be the true counts and λl=∑jpjlTj\lambda_l = \sum_j p_{jl} T_j the expected released count of ll. Gouweleeuw et al. (1998, Section 5) define qlk=pklTk/λlq_{lk} = p_{kl} T_k / \lambda_l and the matrix R=PQR = P Q. Then TTR=TTT^{\mathsf T} R = T^{\mathsf T}: PRAM with RR releases counts whose expectation is the truth, so the analyst can use the released counts directly. The matrix RR depends on the data. The agency computes it from the true counts and applies PRAM with RR in place of PP.

Example

Three regions, with the matrix

true \ released 1 2 3
1 4/5 1/10 1/10
2 1/10 4/5 1/10
3 0 1/5 4/5

and the true counts T=(50,30,20)T = (50, 30, 20). By the linearity of expectation, the expected released counts are PTT=(40+3+0, 5+24+4, 5+3+16)=(43,33,24)P^{\mathsf T} T = (40 + 3 + 0,\ 5 + 24 + 4,\ 5 + 3 + 16) = (43, 33, 24). The raw released counts are biased: region 1 seems smaller than it is.

Say one run releases T∗=(45,31,24)T^* = (45, 31, 24). Line L8 solves

45T^1+110T^2=45,110T^1+45T^2+15T^3=31,110T^1+110T^2+45T^3=24,\tfrac{4}{5} \hat T_1 + \tfrac{1}{10} \hat T_2 = 45, \quad \tfrac{1}{10} \hat T_1 + \tfrac{4}{5} \hat T_2 + \tfrac{1}{5} \hat T_3 = 31, \quad \tfrac{1}{10} \hat T_1 + \tfrac{1}{10} \hat T_2 + \tfrac{4}{5} \hat T_3 = 24,

which gives T^=(370/7,190/7,20)≈(52.9,27.1,20)\hat T = (370/7, 190/7, 20) \approx (52.9, 27.1, 20). Each released count can differ from its mean by a few units, and the inverse spreads the error over the estimate. On the mean T∗=(43,33,24)T^* = (43, 33, 24), the solve gives back (50,30,20)(50, 30, 20) exactly.

For invariant PRAM, take two categories, the matrix of randomized response with p=3/4p = 3/4, and T=(60,20)T = (60, 20):

PP λ\lambda QQ R=PQR = P Q
row 1 (3/4, 1/4) 50 (9/10, 1/10) (4/5, 1/5)
row 2 (1/4, 3/4) 30 (1/2, 1/2) (3/5, 2/5)

The check is 60⋅(4/5,1/5)+20⋅(3/5,2/5)=(60,20)60 \cdot (4/5, 1/5) + 20 \cdot (3/5, 2/5) = (60, 20). The ratios in the columns are 3 for PP and 2 for RR, so as a local mechanism PP is ln⁡3\ln 3-private and RR is ln⁡2\ln 2-private. The matrix of the example with three regions has a 0 in a column with positive entries, so it is not locally private for any ε\varepsilon: a released 1 proves that the true region was not 3.

Correctness

By the inverse of the distribution function, lines L3 to L5 give yi=ly_i = l exactly when uu falls in an interval of length pklp_{kl}, so Pr⁡[yi=l]=pkl\Pr[y_i = l] = p_{kl}. By linearity, E[T∗]=PTT\mathbb{E}[T^*] = P^{\mathsf T} T. The solve of line L8 is a linear map, so E[T^]=(PT)−1PTT=T\mathbb{E}[\hat T] = (P^{\mathsf T})^{-1} P^{\mathsf T} T = T, and T^\hat T is unbiased. For invariant PRAM, (TTP)l=λl(T^{\mathsf T} P)_l = \lambda_l and ∑lλlqlk=Tk\sum_l \lambda_l q_{lk} = T_k. The full proofs, with the covariance of T^\hat T and the local privacy bound, are in proofs/correctness.md.

Proof: PRAM draws from the rows of P, and the inverse of P gives unbiased countsfull

The categories are 1,…,K1, \ldots, K. The PRAM matrix P=(pkl)P = (p_{kl}) has pkl≥0p_{kl} \ge 0 and ∑lpkl=1\sum_l p_{kl} = 1 for each kk. The input is a list of nn values x1,…,xnx_1, \ldots, x_n, and TkT_k is the number of ii with xi=kx_i = k. Lines L1 to L9 are those of the page. Line L3 draws uu uniformly from [0,1)[0, 1), independently for each record. We write ck0=0c_{k0} = 0 and ckl=pk1+⋯+pklc_{kl} = p_{k1} + \cdots + p_{kl}, so ckK=1c_{kK} = 1.

Lemma 1 (one draw). For a record with xi=kx_i = k, lines L3 to L5 set yi=ly_i = l with probability exactly pklp_{kl}.

Proof. Line L4 picks the least ll with ckl>uc_{kl} > u. Since ckK=1>uc_{kK} = 1 > u, such an ll exists. The least such ll is ll exactly when ck,l−1≤u<cklc_{k,l-1} \le u < c_{kl}, because the sums do not decrease. The probability of this interval under the uniform law is ckl−ck,l−1=pklc_{kl} - c_{k,l-1} = p_{kl}. If pkl=0p_{kl} = 0 the interval is empty, and ll is never chosen. □\square

Theorem 1 (the expected released counts). Let Tl∗T^*_l be the number of ii with yi=ly_i = l, as at line L7. Then E[T∗]=PTT\mathbb{E}[T^*] = P^{\mathsf T} T, that is, E[Tl∗]=∑kpklTk\mathbb{E}[T^*_l] = \sum_k p_{kl} T_k.

Proof. Tl∗=∑i[yi=l]T^*_l = \sum_i [y_i = l]. By Lemma 1 and the linearity of expectation, E[Tl∗]=∑ipxil=∑kTkpkl\mathbb{E}[T^*_l] = \sum_i p_{x_i l} = \sum_k T_k p_{kl}. □\square

Theorem 2 (the estimate). If PP is invertible, the vector T^\hat T of lines L8 and L9, the solution of PTT^=T∗P^{\mathsf T} \hat T = T^*, satisfies E[T^]=T\mathbb{E}[\hat T] = T. Its covariance is Cov(T^)=(PT)−1VP−1\mathrm{Cov}(\hat T) = (P^{\mathsf T})^{-1} V P^{-1}, where V=∑kTk(diag(pk)−pkpkT)V = \sum_k T_k (\mathrm{diag}(p_k) - p_k p_k^{\mathsf T}) and pkp_k is row kk of PP as a column vector.

Proof. PTP^{\mathsf T} is invertible together with PP, so line L8 has the unique solution T^=(PT)−1T∗\hat T = (P^{\mathsf T})^{-1} T^*. This map is linear, so by Theorem 1, E[T^]=(PT)−1PTT=T\mathbb{E}[\hat T] = (P^{\mathsf T})^{-1} P^{\mathsf T} T = T. The released indicator vectors eyie_{y_i} are independent. For a record with value kk, eyie_{y_i} is a draw of a multinomial with one trial and probabilities pkp_k, with covariance diag(pk)−pkpkT\mathrm{diag}(p_k) - p_k p_k^{\mathsf T}. Summing over the records gives Cov(T∗)=V\mathrm{Cov}(T^*) = V, and a linear map AA gives Cov(AT∗)=AVAT\mathrm{Cov}(A T^*) = A V A^{\mathsf T} with A=(PT)−1A = (P^{\mathsf T})^{-1}. □\square

Theorem 3 (invariant PRAM). Let λl=∑jpjlTj\lambda_l = \sum_j p_{jl} T_j. Define Q=(qlk)Q = (q_{lk}) by qlk=pklTk/λlq_{lk} = p_{kl} T_k / \lambda_l when λl>0\lambda_l > 0, and qlk=[k=l]q_{lk} = [k = l] when λl=0\lambda_l = 0. Then R=PQR = P Q is a PRAM matrix, and TTR=TTT^{\mathsf T} R = T^{\mathsf T}. So PRAM with RR has E[T∗]=T\mathbb{E}[T^*] = T, and the released counts need no correction.

Proof. Each row of QQ is a probability vector: for λl>0\lambda_l > 0, ∑kpklTk/λl=1\sum_k p_{kl} T_k / \lambda_l = 1, and for λl=0\lambda_l = 0 it is a unit vector. A product of two matrices whose rows are probability vectors has the same property, so RR is a PRAM matrix. Next, (TTP)l=λl(T^{\mathsf T} P)_l = \lambda_l, so

(TTR)k=∑lλlqlk=∑l:λl>0pklTk=Tk∑l:λl>0pkl.(T^{\mathsf T} R)_k = \sum_l \lambda_l q_{lk} = \sum_{l : \lambda_l > 0} p_{kl} T_k = T_k \sum_{l : \lambda_l > 0} p_{kl}.

If Tk=0T_k = 0 both sides are 0. If Tk>0T_k > 0, then pkl>0p_{kl} > 0 implies λl≥pklTk>0\lambda_l \ge p_{kl} T_k > 0, so the last sum runs over all ll with pkl>0p_{kl} > 0 and equals 1. Hence (TTR)k=Tk(T^{\mathsf T} R)_k = T_k. By Theorem 1 with RR in place of PP, E[T∗]=RTT=T\mathbb{E}[T^*] = R^{\mathsf T} T = T. □\square

Theorem 4 (local differential privacy). Assume that each column of PP is either all zero or all positive, and let c=max⁡lmax⁡k,k′pkl/pk′lc = \max_l \max_{k, k'} p_{kl} / p_{k'l} over the positive columns. Then the release of one record by lines L3 to L5 is ε\varepsilon-locally differentially private with ε=ln⁡c\varepsilon = \ln c, and no smaller ε\varepsilon holds. If some column has both a zero and a positive entry, no finite ε\varepsilon holds.

Proof. By Lemma 1, the output law for the input kk is row pkp_k. For outputs ll in a positive column, Pr⁡[y=l∣k]=pkl≤c pk′l=cPr⁡[y=l∣k′]\Pr[y = l \mid k] = p_{kl} \le c\, p_{k'l} = c \Pr[y = l \mid k'], and outputs in a zero column have probability 0 for every input. So the bound holds for every set of outputs, which is the definition with eε=ce^{\varepsilon} = c. The pair k,k′k, k' and the column ll where the maximum is reached give equality, so a smaller ε\varepsilon fails. If pkl>0=pk′lp_{kl} > 0 = p_{k'l}, the output ll is possible under kk and impossible under k′k', and no factor eεe^{\varepsilon} bounds the ratio. ■\blacksquare

Remark. Theorem 4 is about one record and the matrix only. The privacy of a release by PRAM in the sense of statistical disclosure control is a policy question, and the matrix is chosen by the agency. Theorem 2 is the reason why the matrix is published.

Complexity

The model is the word RAM, with one step for each operation on a probability.

  • Lines L1 to L6 take O(nK)O(n K) time with a linear scan at line L4, or O(K2+nlog⁡K)O(K^2 + n \log K) with stored cumulative sums and a binary search.
  • Line L7 takes O(n+K)O(n + K) time, and line L8 takes O(K3)O(K^3) by Gaussian elimination.
  • The extra space is O(K2)O(K^2) for the matrix and the elimination.

The matrix RR of invariant PRAM takes O(K3)O(K^3) time to compute.

Properties

  • Unbiased estimate. E[T^]=T\mathbb{E}[\hat T] = T when PP is invertible. This is a theorem.
  • The cost of the noise. Cov(T^)=(PT)−1VP−1\mathrm{Cov}(\hat T) = (P^{\mathsf T})^{-1} V P^{-1} with V=∑kTk(diag(pk)−pkpkT)V = \sum_k T_k (\mathrm{diag}(p_k) - p_k p_k^{\mathsf T}). A matrix close to singular makes the variance large. This is also a theorem.
  • Invariant PRAM keeps the expected counts. Univariate counts need no correction. Cross tables of the masked attribute with other attributes still need one.
  • Local privacy. With all entries positive, the release of one record is ε\varepsilon-locally differentially private with ε=max⁡lln⁡(max⁡kpkl/min⁡kpkl)\varepsilon = \max_l \ln(\max_k p_{kl} / \min_k p_{kl}), and this value is tight.
  • Independent of the other records. Each draw depends only on the value of its own record, unlike data swapping, where a change needs a partner.

Variants and improvements

  • PRAM on several attributes together. Apply one matrix to the combinations of two attributes, so that combinations that cannot occur, such as an age of 5 with a status of married, are never released.
  • PRAM in strata. Use a different matrix for each value of another attribute, for example for each region. The analyst corrects within each stratum.
  • Maximum likelihood. The moment estimate of line L8 can have negative entries. A maximum likelihood estimate, for example by expectation-maximization, stays in the set of valid counts.
  • Randomized response. Randomized response uses the same matrix at the collection step, by the respondent. The estimate is the same.
  • Local differential privacy. Choosing PP to minimize the variance of T^\hat T for a given ε\varepsilon is the design problem of local differential privacy.

When to use it

Use PRAM to mask categorical attributes of a public use file when analysts need unbiased frequency tables and accept more variance, and when the agency is willing to publish the matrix. Use invariant PRAM when most users will not correct the counts. If most of the risk comes from a few rare combinations, generalization and suppression or data swapping of those records can lose less. For a formal guarantee over all records and all analyses, use a mechanism designed for differential privacy and account for its total privacy loss.

Pitfalls

  • P instead of P^T at line L8. The released counts are PTTP^{\mathsf T} T, so the system to solve is PTT^=T∗P^{\mathsf T} \hat T = T^*. Solving PT^=T∗P \hat T = T^* is wrong whenever PP is not symmetric. In the example, on the mean released counts (43,33,24)(43, 33, 24), it gives (2300/49,1600/49,1070/49)≈(46.9,32.7,21.8)(2300/49, 1600/49, 1070/49) \approx (46.9, 32.7, 21.8) instead of (50,30,20)(50, 30, 20).
  • A test with ≥ at line L4. With the test pk1+⋯+pkl≥up_{k1} + \cdots + p_{kl} \ge u, a draw of u=0u = 0 picks the first category even when its probability is 0. The test must be strict.
  • Negative estimates. With small counts, line L8 can give T^k<0\hat T_k < 0. Do not round to 0 and keep the rest, because the total then changes. Report the moment estimate with its variance, or use a maximum likelihood estimate.
  • A secret matrix. If PP is not published, the bias cannot be corrected, and PRAM becomes a form of noise with unknown effect. The protection must come from the randomness of the draws, not from the secrecy of PP.
  • A weak random source. The tests use a seeded generator so that they repeat. A release needs a cryptographic source, because an attacker who can predict uu can undo the masking.
  • Impossible combinations. PRAM on one attribute ignores the others. A released record can be a combination that cannot occur, which shows that it was changed and harms the analysis of cross tables.

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.

post_randomization_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/post-randomization-method/. The authors are listed in prov/4VVPMW.jsonl.
"""The post-randomization method (PRAM) of Gouweleeuw, Kooiman, Willenborg and de Wolf.

Categories are the integers 0 .. K-1. A PRAM matrix P is a list of K rows, where
P[k][l] is the probability that a true value k is released as l. Each row sums to 1.
Use Fraction entries for exact results. The rng argument needs only a method
random() that returns a number in [0, 1); random.Random is fine for tests, but a
real release needs a cryptographic source of randomness.
"""

from fractions import Fraction
from typing import Optional, Protocol, Sequence, Union

Number = Union[int, Fraction]
Matrix = Sequence[Sequence[Number]]


class UniformSource(Protocol):
    def random(self) -> float: ...


def check_matrix(P: Matrix) -> None:
    """Raise ValueError unless P is a square matrix of probabilities with rows that sum to 1."""
    size = len(P)
    if size == 0 or any(len(row) != size for row in P):
        raise ValueError("P must be a non-empty square matrix")
    for row in P:
        if any(p < 0 for p in row) or sum(row) != 1:
            raise ValueError("each row of P must be a probability vector")


def pram(values: Sequence[int], P: Matrix, rng: UniformSource) -> list[int]:
    """Release each value k as l with probability P[k][l], independently.

    Precondition: P passes check_matrix and each value is in 0 .. K-1.
    Cost: O(n K) time for n values, O(n) space for the output.
    """
    check_matrix(P)
    out: list[int] = []
    for k in values:  # @line L1
        row = P[k]  # @line L2
        u = rng.random()  # @line L3
        acc: Number = 0
        y = len(row) - 1
        for j, p in enumerate(row):  # @line L4
            acc += p
            if acc > u:
                y = j
                break
        out.append(y)  # @line L5
    return out  # @line L6


def counts(values: Sequence[int], size: int) -> list[int]:
    """The frequency of each category 0 .. size-1. Cost: O(n + size)."""
    t = [0] * size
    for v in values:
        t[v] += 1
    return t


def transpose_times(P: Matrix, t: Sequence[Number]) -> list[Number]:
    """P^T t, the expected released counts for true counts t. Cost: O(K^2)."""
    size = len(P)
    return [sum(P[k][l] * t[k] for k in range(size)) for l in range(size)]


def solve(A: Matrix, b: Sequence[Number]) -> Optional[list[Fraction]]:
    """Solve A z = b exactly by Gaussian elimination; None if A is singular.

    Cost: O(K^3) arithmetic operations on fractions.
    """
    size = len(A)
    m = [[Fraction(A[i][j]) for j in range(size)] + [Fraction(b[i])] for i in range(size)]
    for col in range(size):
        piv = next((r for r in range(col, size) if m[r][col] != 0), None)
        if piv is None:
            return None
        m[col], m[piv] = m[piv], m[col]
        for r in range(size):
            if r != col and m[r][col] != 0:
                f = m[r][col] / m[col][col]
                m[r] = [a - f * c for a, c in zip(m[r], m[col])]
    return [m[i][size] / m[i][i] for i in range(size)]


def estimate(released: Sequence[int], P: Matrix) -> Optional[list[Fraction]]:
    """The unbiased estimate of the true counts: solve P^T T = T* for T.

    Returns None if P is singular. The estimate can have negative entries.
    Precondition: P passes check_matrix. Cost: O(n + K^3).
    """
    check_matrix(P)
    size = len(P)
    t_star = counts(released, size)  # @line L7
    pt = [[P[k][l] for k in range(size)] for l in range(size)]
    t_hat = solve(pt, t_star)  # @line L8
    return t_hat  # @line L9


def invariant_matrix(P: Matrix, t: Sequence[Number]) -> list[list[Fraction]]:
    """R = P Q with Q[l][k] = P[k][l] t[k] / sum_j P[j][l] t[j], so that t^T R = t^T.

    Precondition: P passes check_matrix, t has K entries >= 0, and every category with
    t[k] > 0 has some released value. A column l with no mass gets Q[l] = unit vector l.
    Cost: O(K^3).
    """
    check_matrix(P)
    size = len(P)
    col = [sum(Fraction(P[j][l]) * t[j] for j in range(size)) for l in range(size)]
    q = []
    for l in range(size):
        if col[l] == 0:
            q.append([Fraction(int(k == l)) for k in range(size)])
        else:
            q.append([Fraction(P[k][l]) * t[k] / col[l] for k in range(size)])
    return [[sum(Fraction(P[i][l]) * q[l][j] for l in range(size)) for j in range(size)] for i in range(size)]


def ldp_ratio(P: Matrix) -> Optional[Fraction]:
    """The least c with P[k][l] <= c P[k'][l] for all k, k', l; None if no c exists.

    PRAM with matrix P is epsilon-locally differentially private for epsilon = ln c.
    A column of zeros is a value that is never released and is skipped.
    Cost: O(K^2).
    """
    check_matrix(P)
    worst = Fraction(1)
    for l in range(len(P)):
        column = [Fraction(row[l]) for row in P]
        hi, lo = max(column), min(column)
        if hi == 0:
            continue
        if lo == 0:
            return None
        worst = max(worst, hi / lo)
    return worst
test_post_randomization_method.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/post-randomization-method/. The authors are listed in prov/4VVPMW.jsonl.
import itertools
import random
from fractions import Fraction as F

import pytest

from post_randomization_method import (
    check_matrix,
    counts,
    estimate,
    invariant_matrix,
    ldp_ratio,
    pram,
    solve,
    transpose_times,
)

P3 = [[F(4, 5), F(1, 10), F(1, 10)], [F(1, 10), F(4, 5), F(1, 10)], [F(0), F(1, 5), F(4, 5)]]
RR = [[F(3, 4), F(1, 4)], [F(1, 4), F(3, 4)]]


class Fixed:
    def __init__(self, us):
        self.us = list(us)

    def random(self) -> float:
        return self.us.pop(0)


def det(a):
    """The Leibniz formula, independent of the elimination in solve."""
    size = len(a)
    total = F(0)
    for perm in itertools.permutations(range(size)):
        inv = sum(1 for i in range(size) for j in range(i + 1, size) if perm[i] > perm[j])
        term = F(-1) ** inv
        for i in range(size):
            term *= a[i][perm[i]]
        total += term
    return total


def cramer(a, b):
    d = det(a)
    if d == 0:
        return None
    out = []
    for c in range(len(a)):
        m = [[b[i] if j == c else a[i][j] for j in range(len(a))] for i in range(len(a))]
        out.append(det(m) / d)
    return out


def random_matrix(rng, size):
    rows = []
    for _ in range(size):
        w = [rng.randint(0, 6) for _ in range(size)]
        if sum(w) == 0:
            w[rng.randrange(size)] = 1
        rows.append([F(x, sum(w)) for x in w])
    return rows


def test_page_example() -> None:
    assert transpose_times(P3, [50, 30, 20]) == [43, 33, 24]
    released = [0] * 45 + [1] * 31 + [2] * 24
    assert estimate(released, P3) == [F(370, 7), F(190, 7), F(20)]
    assert estimate([0] * 43 + [1] * 33 + [2] * 24, P3) == [50, 30, 20]
    r = invariant_matrix(RR, [60, 20])
    assert r == [[F(4, 5), F(1, 5)], [F(3, 5), F(2, 5)]]
    assert transpose_times(r, [60, 20]) == [60, 20]
    assert ldp_ratio(RR) == 3
    assert ldp_ratio(r) == 2
    assert ldp_ratio(P3) is None


def test_sampling_boundaries() -> None:
    # Row 0 of P3 has the cumulative sums 4/5, 9/10, 1.
    assert pram([0, 0, 0, 0, 0], P3, Fixed([0.0, 0.79, 0.8, 0.85, 0.9])) == [0, 0, 1, 1, 2]
    # A zero entry is never chosen.
    assert pram([2, 2], P3, Fixed([0.0, 0.19])) == [1, 1]
    assert pram([], P3, Fixed([])) == []


def test_bad_matrix() -> None:
    with pytest.raises(ValueError):
        check_matrix([[F(1, 2), F(1, 3)], [F(1, 2), F(1, 2)]])
    with pytest.raises(ValueError):
        check_matrix([[F(3, 2), F(-1, 2)], [F(0), F(1)]])
    with pytest.raises(ValueError):
        check_matrix([[F(1)], [F(1)]])
    assert solve([[F(1, 2), F(1, 2)], [F(1, 2), F(1, 2)]], [1, 1]) is None
    assert estimate([0, 1], [[F(1, 2), F(1, 2)], [F(1, 2), F(1, 2)]]) is None


def test_against_oracles() -> None:
    rng = random.Random(1998)
    for _ in range(600):
        size = rng.randint(1, 3)
        p = random_matrix(rng, size)
        t = [rng.randint(0, 9) for _ in range(size)]
        pt = [[p[k][l] for k in range(size)] for l in range(size)]
        t_star = [rng.randint(0, 9) for _ in range(size)]
        released = [l for l in range(size) for _ in range(t_star[l])]
        rng.shuffle(released)
        assert counts(released, size) == t_star
        assert estimate(released, p) == cramer(pt, t_star)
        if det(pt) != 0:
            expected = transpose_times(p, t)
            assert solve(pt, expected) == t
        if sum(t) > 0:
            r = invariant_matrix(p, t)
            assert all(sum(row) == 1 and min(row) >= 0 for row in r)
            assert transpose_times(r, t) == t
        ratio = ldp_ratio(p)
        pairs = [(p[a][l], p[b][l]) for a in range(size) for b in range(size) for l in range(size)]
        if any(x > 0 and y == 0 for x, y in pairs):
            assert ratio is None
        else:
            assert ratio == max([F(1)] + [x / y for x, y in pairs if y > 0])


def test_sampling_matches_inverse_cdf() -> None:
    rng = random.Random(4)
    for _ in range(500):
        size = rng.randint(1, 4)
        p = random_matrix(rng, size)
        values = [rng.randrange(size) for _ in range(rng.randint(0, 8))]
        seed = rng.randrange(10**9)
        got = pram(values, p, random.Random(seed))
        twin = random.Random(seed)
        want = []
        for k in values:
            u = twin.random()
            cum = list(itertools.accumulate(p[k]))
            want.append(min(l for l in range(size) if cum[l] > u))
        assert got == want


def test_frequencies() -> None:
    # 2000 draws from row 0 of P3. By the Hoeffding inequality, each frequency is
    # within 0.05 of its probability except with probability 2 exp(-10) < 1e-4.
    out = pram([0] * 2000, P3, random.Random(77))
    for l, p in enumerate(P3[0]):
        assert abs(out.count(l) / 2000 - float(p)) < 0.05
    # The estimate from a large release is close to the truth.
    truth = [0] * 1000 + [1] * 600 + [2] * 400
    t_hat = estimate(pram(truth, P3, random.Random(5)), P3)
    assert all(abs(float(a) - b) < 60 for a, b in zip(t_hat, [1000, 600, 400]))

History

Warner (1965) proposed randomized response, where a respondent answers a sensitive question with a known random change, and gave the unbiased estimate. Kooiman, Willenborg and Gouweleeuw (1997) at Statistics Netherlands moved the random step to the agency, after the data is collected, and named it PRAM. Gouweleeuw, Kooiman, Willenborg and de Wolf (1998) gave the theory, the moment estimate with the inverse matrix, and invariant PRAM. PRAM is one of the methods of the mu-Argus software and of the textbook of Hundepool et al. (2012). Later work on local differential privacy studies the same matrices with a formal privacy bound.

References

  1. Jose M. Gouweleeuw, Peter Kooiman, Leon C. R. J. Willenborg and Peter-Paul de Wolf, Post randomisation for statistical disclosure control, theory and implementation, Journal of Official Statistics 14(4), 1998, pp. 463 to 478, the PRAM matrix, the unbiased moment estimate with the inverse of the matrix, and invariant PRAM in Section 5
  2. Peter Kooiman, Leon Willenborg and Jose Gouweleeuw, PRAM, a method for disclosure limitation of microdata, Research paper 9705, Statistics Netherlands, 1997, the first description of the method
  3. Anco Hundepool, Josep Domingo-Ferrer, Luisa Franconi, Sarah Giessing, Eric Schulte Nordholt, Keith Spicer and Peter-Paul de Wolf, Statistical Disclosure Control, Wiley, 2012, Chapter 3, Microdata, the section on PRAM among the perturbative masking methods for categorical data
  4. Leon Willenborg and Ton de Waal, Elements of Statistical Disclosure Control, Lecture Notes in Statistics 155, Springer, 2001, the chapters on perturbative methods for microdata
  5. Stanley L. Warner, Randomized response, a survey technique for eliminating evasive answer bias, Journal of the American Statistical Association 60(309), 1965, pp. 63 to 69, the randomized response design and its unbiased estimate

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