Algorithm Search⌘K

Algorithmadvanced

Controlled tabular adjustment

Also called CTA.

Moves each sensitive cell out of its protection interval and fixes the other cells by a linear program that keeps the totals.

Time
O(2^p L) worst
Space
O(m (n + m)) extra
Where
L = the time of one linear program with m rows and 2n columns; m = the number of table relations; n = the number of cells; p = the number of sensitive cells
Origin
Ramesh A. Dandekar, Lawrence H. Cox, 2002

Controlled tabular adjustment (CTA) protects a table of magnitudes with totals by changing numbers instead of hiding them. Each sensitive cell is moved up by at least its upper protection level or down by at least its lower protection level. The other cells are then changed as little as possible, so that every total still equals the sum of its parts and every cell stays within its bounds. For a fixed choice of directions, this is a linear program that minimizes the weighted L1 distance to the true table. The exact method tries both directions for each of the pp sensitive cells, so it solves 2p2^p linear programs and keeps the cheapest. Unlike cell suppression, CTA publishes every cell, but some published values are not the true ones.

In plain words

A table shows sales by town and kind of shop, with sums for each row and each column. One number is secret, because it belongs to only two shops. Hiding it does not work well, because the sums give it back, and hiding more numbers loses a lot.

CTA prints all the numbers, but it prints a wrong value for the secret one: clearly higher or clearly lower than the true value. Then the sums do not add up. So it changes a few other numbers by small amounts until every sum is right again. It picks the changes that are as small as possible in total. A reader sees a normal table where every sum is right, but cannot know the true secret value.

The problem

The input is a table of nn cells with values a1,…,ana_1, \ldots, a_n that satisfy linear relations Ma=0M a = 0, for example that a total minus its parts is 0. The totals are cells too. Each cell has bounds lbi≤ai≤ubilb_i \le a_i \le ub_i, such as 0≤ai0 \le a_i. A set PP of pp sensitive cells is given, and each p∈Pp \in P has a lower and an upper protection level LPLp,UPLp≥0LPL_p, UPL_p \ge 0. The levels come from a sensitivity rule, as in cell suppression, and they are policy choices. Each cell has a weight wi≥0w_i \ge 0, such as 1, or 1/ai1 / a_i for a relative change.

The output is a table x=a+yx = a + y that satisfies Mx=0M x = 0 and lb≤x≤ublb \le x \le ub, protects every sensitive cell, so that xp≥ap+UPLpx_p \ge a_p + UPL_p or xp≤ap−LPLpx_p \le a_p - LPL_p, and has the least cost ∑iwi∣yi∣\sum_i w_i |y_i|. The "or" is what makes the problem hard: the set of protected tables is not convex. With a binary variable for each sensitive cell, it is a mixed-integer program.

The algorithm

Write y=z+−z−y = z^+ - z^- with z+,z−≥0z^+, z^- \ge 0, the moves up and down. For a fixed direction of each sensitive cell, the "or" goes away, and what is left is a linear program.

  1. CTA(a, M, lb, ub, w, P, LPL, UPL)
  2. 1best ← none
  3. 2for each direction vector d in {down, up}^P do
  4. 3bounds: 0 ≤ z+ ≤ ub - a and 0 ≤ z- ≤ a - lb
  5. 4for each p in P: if d_p = up then z+_p ≥ UPL_p and z-_p = 0, else z-_p ≥ LPL_p and z+_p = 0
  6. 5solve the LP: minimize Σ w_i (z+_i + z-_i) subject to M (z+ - z-) = 0 and the bounds
  7. 6if the LP is feasible and its value is less than that of best then best ← (a + z+ - z-, value, d)
  8. 7if best is none then return infeasible
  9. 8return best

Line L5 can use any LP solver. The implementation uses the simplex method with bounds on the variables and Bland's least-index rule, with exact fractions when all the inputs are rational. On a tie at line L6, the first direction vector in the order of line L2 is kept.

Example

Take the table with three rows and three columns and its totals, 16 cells in all, with weight 1 for each cell and the bounds x≥0x \ge 0. Two cells are sensitive: (r2, c1) = 5 with LPL=UPL=3LPL = UPL = 3, and (r3, c3) = 10 with LPL=UPL=2LPL = UPL = 2.

c1 c2 c3 total
r1 20 10 15 45
r2 5 25 30 60
r3 12 18 10 40
total 37 53 55 145

The four direction vectors give these optimal costs:

(r2, c1) (r3, c3) least cost
down down 12
down up 16
up down 16
up up 12

Two vectors tie at 12, and line L6 keeps the first, down and down. Its adjustment is

c1 c2 c3 total
r1 +1 -1 0 0
r2 -3 +1 +2 0
r3 +2 0 -2 0
total 0 0 0 0

and the published table is

c1 c2 c3 total
r1 21 9 15 45
r2 2 26 32 60
r3 14 18 8 40
total 37 53 55 145

Check each sum: row r2 is 2+26+32=602 + 26 + 32 = 60, column c1 is 21+2+14=3721 + 2 + 14 = 37, and column c3 is 15+32+8=5515 + 32 + 8 = 55. No total moved. The sensitive cells are at 2=5−32 = 5 - 3 and 8=10−28 = 10 - 2. The cost is 1+1+3+1+2+2+2=121 + 1 + 3 + 1 + 2 + 2 + 2 = 12. Protecting (r2, c1) alone also costs 12: the move of −2-2 at (r3, c3) comes free with the moves that balance column c1 and row r3. The test file checks all these numbers with exact fractions.

Correctness

For a fixed direction vector dd, every feasible point of the LP gives a table that satisfies the relations and the bounds and moves each sensitive cell in its direction by at least its level, with a cost of at most the LP value. Every such table also gives an LP point of equal value, by splitting each change into its positive and negative part. So the LP optimum is the least cost among the tables with directions dd. Every protected table has some direction vector, so the best of the 2p2^p optima is the optimum of the whole problem, and if no LP is feasible, no protected table exists. The simplex method with Bland's rule always ends, so each LP is solved. The full proof is in proofs/correctness.md.

Proof: The best of the 2^|P| direction LPs is an optimal L1 controlled adjustmentfull

The input is a table a∈Rna \in \mathbb{R}^n with Ma=0M a = 0, bounds lb≤a≤ublb \le a \le ub, weights w≥0w \ge 0, and a set PP of sensitive cells with levels LPLp,UPLp≥0LPL_p, UPL_p \ge 0. Lines L1 to L8 are those of the page. An adjustment is a vector y∈Rny \in \mathbb{R}^n. It is feasible if My=0M y = 0 and lb≤a+y≤ublb \le a + y \le ub, and it protects PP if, for each p∈Pp \in P, yp≥UPLpy_p \ge UPL_p or yp≤−LPLpy_p \le -LPL_p. The problem is to find a feasible adjustment that protects PP and has the least cost c(y)=∑iwi∣yi∣c(y) = \sum_i w_i |y_i|.

For a direction vector d∈{down,up}Pd \in \{\text{down}, \text{up}\}^P, let YdY_d be the set of feasible adjustments with yp≥UPLpy_p \ge UPL_p for each pp with dp=upd_p = \text{up} and yp≤−LPLpy_p \le -LPL_p for each pp with dp=downd_p = \text{down}. Let LdL_d be the linear program of lines L3 to L5: minimize ∑iwi(zi++zi−)\sum_i w_i (z^+_i + z^-_i) subject to M(z+−z−)=0M (z^+ - z^-) = 0, 0≤z+≤ub−a0 \le z^+ \le ub - a, 0≤z−≤a−lb0 \le z^- \le a - lb, and, for each p∈Pp \in P, zp+≥UPLpz^+_p \ge UPL_p and zp−=0z^-_p = 0 if dp=upd_p = \text{up}, or zp−≥LPLpz^-_p \ge LPL_p and zp+=0z^+_p = 0 if dp=downd_p = \text{down}.

Lemma 1 (from the LP to a table). If (z+,z−)(z^+, z^-) is feasible for LdL_d, then y=z+−z−y = z^+ - z^- is in YdY_d and c(y)≤∑iwi(zi++zi−)c(y) \le \sum_i w_i (z^+_i + z^-_i).

Proof. My=0M y = 0 by the first constraint. For each cell, ai+yi≤ai+zi+≤ubia_i + y_i \le a_i + z^+_i \le ub_i and ai+yi≥ai−zi−≥lbia_i + y_i \ge a_i - z^-_i \ge lb_i, so yy is feasible. If dp=upd_p = \text{up}, then zp−=0z^-_p = 0 and yp=zp+≥UPLpy_p = z^+_p \ge UPL_p. If dp=downd_p = \text{down}, then zp+=0z^+_p = 0 and yp=−zp−≤−LPLpy_p = -z^-_p \le -LPL_p. So y∈Ydy \in Y_d. Finally ∣yi∣=∣zi+−zi−∣≤zi++zi−|y_i| = |z^+_i - z^-_i| \le z^+_i + z^-_i, and wi≥0w_i \ge 0. □\square

Lemma 2 (from a table to the LP). If y∈Ydy \in Y_d, then z+=max⁡(y,0)z^+ = \max(y, 0) and z−=max⁡(−y,0)z^- = \max(-y, 0), taken entry by entry, are feasible for LdL_d with value c(y)c(y).

Proof. z+−z−=yz^+ - z^- = y, so M(z+−z−)=0M (z^+ - z^-) = 0. If yi≥0y_i \ge 0, then zi+=yi≤ubi−aiz^+_i = y_i \le ub_i - a_i and zi−=0≤ai−lbiz^-_i = 0 \le a_i - lb_i, because a+y≤uba + y \le ub and lb≤alb \le a. The case yi<0y_i < 0 is the same with the roles exchanged. If dp=upd_p = \text{up}, then yp≥UPLp≥0y_p \ge UPL_p \ge 0, so zp+=yp≥UPLpz^+_p = y_p \ge UPL_p and zp−=0z^-_p = 0. If dp=downd_p = \text{down}, then yp≤−LPLp≤0y_p \le -LPL_p \le 0, so zp−=−yp≥LPLpz^-_p = -y_p \ge LPL_p and zp+=0z^+_p = 0. The value is ∑iwi(zi++zi−)=∑iwi∣yi∣=c(y)\sum_i w_i (z^+_i + z^-_i) = \sum_i w_i |y_i| = c(y). □\square

Theorem 1 (one direction). LdL_d is feasible if and only if YdY_d is not empty. Then its optimal value equals min⁡{c(y):y∈Yd}\min \{ c(y) : y \in Y_d \}, and if (z+,z−)(z^+, z^-) is optimal for LdL_d, the adjustment z+−z−z^+ - z^- reaches this minimum.

Proof. Feasibility goes both ways by Lemmas 1 and 2. The program has a finite optimum because it is feasible and its objective is at least 0. Let vv be the optimal value and (z+,z−)(z^+, z^-) an optimal solution, and let y∗=z+−z−y^* = z^+ - z^-. By Lemma 1, y∗∈Ydy^* \in Y_d and c(y∗)≤vc(y^*) \le v. For each y∈Ydy \in Y_d, Lemma 2 gives a feasible point of value c(y)c(y), so v≤c(y)v \le c(y). With y=y∗y = y^* this gives v≤c(y∗)≤vv \le c(y^*) \le v, and for every y∈Ydy \in Y_d it gives c(y∗)=v≤c(y)c(y^*) = v \le c(y). □\square

Theorem 2 (the algorithm). If line L7 returns infeasible, no feasible adjustment protects PP. Otherwise line L8 returns x=a+yx = a + y where yy is feasible, protects PP, and has the least cost among all such adjustments.

Proof. An adjustment protects PP if and only if it lies in YdY_d for some dd: choose dp=upd_p = \text{up} when yp≥UPLpy_p \ge UPL_p and dp=downd_p = \text{down} otherwise. So the set of feasible protecting adjustments is the union of the 2∣P∣2^{|P|} sets YdY_d. Line L2 visits every dd. By Theorem 1, the LP of line L5 is infeasible exactly when YdY_d is empty. If it is infeasible for every dd, the union is empty and line L7 is correct. Otherwise, line L6 keeps a solution of the least value over the feasible dd, and by Theorem 1 that value is min⁡dmin⁡y∈Ydc(y)\min_d \min_{y \in Y_d} c(y), the least cost over the union. The kept adjustment is in its YdY_d, so it is feasible and protects PP. □\square

Theorem 3 (the LP solver). The implementation solves each LdL_d by a primal simplex method with bounds on the variables. After the substitution z←z−ℓz \leftarrow z - \ell for the lower bounds ℓ\ell of line L4, every variable lies in [0,uj][0, u_j] with uju_j possibly infinite. Phase 1 adds one artificial variable per row, starts from the basis of the artificials, and minimizes their sum. If the minimum is positive, the system has no solution. Otherwise phase 2 sets the upper bound of each artificial to 0 and minimizes the objective of LdL_d from the final basis of phase 1.

Proof sketch. Phase 1 starts from a feasible basis: the rows are multiplied by −1-1 where needed so that the right side is at least 0, and then the artificials equal the right side. Each pivot keeps all variables within their bounds, because the ratio test takes the least step at which a basic variable or the entering variable reaches a bound. When no nonbasic variable has a reduced cost of the right sign, the basis is optimal by the usual optimality test for bounded variables. With Bland's rule, the entering variable is the first eligible one, and on a tie in the ratio test the leaving variable has the least index, so no basis repeats, and both phases end after finitely many pivots. This is Bland's theorem, extended to bounds on the variables in the standard way. A step in which the entering variable moves to its other bound changes no basis. A variable at its lower bound enters only if its range is positive, so such a step strictly lowers the objective and cannot be part of a cycle. The sum of the artificials is 0 after phase 1 if and only if the system has a solution. In phase 2 their upper bound is 0, so every point of phase 2 is a solution of the original system. The objective of LdL_d is bounded below by the shifted constant, because w≥0w \ge 0, so phase 2 cannot report an unbounded program. ■\blacksquare

Remark. With exact rational arithmetic the implementation follows the proof exactly. With floating-point arithmetic and a tolerance, the result is an approximation, and the test file compares it with a brute force on small tables.

Complexity

Let nn be the number of cells, mm the number of relations and pp the number of sensitive cells. The model is the real RAM.

  • The exact method solves 2p2^p linear programs, each with mm rows and 2n2n columns. So the time is O(2pL)O(2^p L), where LL is the time of one LP.
  • An LP can be solved in time polynomial in its size by an interior-point method. The simplex method of the implementation takes O(m(n+m))O(m (n + m)) operations per pivot, and its number of pivots is exponential in the worst case.
  • The extra space is the simplex tableau, O(m(n+m))O(m (n + m)).

The factor 2p2^p is the price of exactness. With one LP for a good choice of directions, CTA scales to large tables.

Properties

  • Relations hold. Every relation holds in the published table, by the constraint My=0M y = 0. This is a theorem. A total cell can still change. To keep a total at its true value, set its bounds to lbi=ubi=ailb_i = ub_i = a_i.
  • All cells are published. No cell is blank. Analysts can use the table as it is, but some values are wrong by design.
  • Protection is by the published value. Each sensitive value is at least its level away from the truth. This is a theorem about the published value only. What a reader can infer depends on what the agency publishes about the method.
  • Optimal over all directions. The exact method finds the least weighted L1 distance. This is a theorem. A fixed rule for the directions gives a feasible table, if one exists for those directions, and an upper bound on the optimum.
  • Loss by measurement. The quality of the table for analysts, such as changes in correlations, is a measured property on test data.

Variants and improvements

  • The mixed-integer form. Instead of the 2p2^p loop, use one binary variable for the direction of each sensitive cell and solve one mixed-integer program by branch-and-cut. The optimum is the same, and the solver can skip directions whose LP relaxation is already too costly.
  • Fixed directions. Choose the directions by a rule, for example all down or alternating, and solve one LP. This is a heuristic, often used for large tables.
  • The L2 distance. Minimize ∑iwiyi2\sum_i w_i y_i^2 for fixed directions. This is a convex quadratic program. Castro (2006) studies it together with the L1 form.
  • Constraints on statistics. Add linear constraints that keep chosen means, or bounds on the change of each cell. They make the LP larger and can make it infeasible.
  • Integer tables. For tables of counts, ask for integer yy. For a two-dimensional table with totals the relations are totally unimodular, so with integer data the vertex optimum of each LP is already integer.

When to use it

Use CTA for a magnitude table with totals when cell suppression would hide too many cells, and when the users accept that some published values are not true values. It suits tables that are published with exact totals for the main relations, such as business statistics by region and industry. If there are many sensitive cells, use the mixed-integer form or a fixed rule for the directions. If the users need every published value to be true, use cell suppression. If the release must be safe against any background knowledge or many releases, neither method gives a guarantee, and methods based on differential privacy are the alternative.

Pitfalls

  • Writing the protection as one LP constraint. The condition "yp≥UPLpy_p \ge UPL_p or yp≤−LPLpy_p \le -LPL_p" is not convex. A single LP with ∣yp∣≥|y_p| \ge a level, or with ypy_p free, does not protect the cell. The direction must be fixed at line L4 or chosen by a binary variable.
  • Free z+z^+ and z−z^- at a sensitive cell. If both parts are free at line L4, the LP can set zp+=zp−=UPLpz^+_p = z^-_p = UPL_p and leave yp=0y_p = 0. One of the two parts must be fixed to 0.
  • Publishing the levels and the sensitive cells. At the optimum, a sensitive cell often sits exactly at the edge of its interval, as both cells do in the example. A reader who knows which cells are sensitive and the levels then has two candidates for each true value. Keep the levels and the list of sensitive cells confidential.
  • Bounds that are too tight at line L3. If the cells near a sensitive cell cannot move, the LP is infeasible in every direction. Check line L7 and relax the bounds or the levels.
  • Floating-point tolerance. With floats, a sensitive cell can end a little inside its interval. Check the result with exact arithmetic, or with a margin.

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.

controlled_tabular_adjustment.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/controlled-tabular-adjustment/. The authors are listed in prov/P26HSK.jsonl.
"""Controlled tabular adjustment (CTA) with the L1 distance.

A table is a list of n cell values a[i]. The table relations are linear equations
sum of coef * x[cell] = 0 that the table satisfies, for example a total minus its
parts. Each cell has bounds lower[i] <= x[i] <= upper[i]. A sensitive cell p has a
lower and an upper protection level (lpl, upl): the published value must be at most
a[p] - lpl or at least a[p] + upl. CTA finds the published table x that satisfies
the relations and the bounds, moves every sensitive cell out of its protection
interval, and has the least weighted L1 distance sum w[i] |x[i] - a[i]|.

The exact method tries both directions for every sensitive cell and solves one
linear program for each choice, so it takes 2^|P| LPs. The LP solver is a small
bounded-variable primal simplex with Bland's rule. With Fraction inputs and eps = 0
all arithmetic is exact; with floats, eps is the tolerance.
"""

from fractions import Fraction
from itertools import product
from typing import Optional, Sequence, Union

Number = Union[int, float, Fraction]
Relation = Sequence[tuple[int, Number]]
INF = float("inf")


def bounded_simplex(
    A: list[list[Number]], b: list[Number], c: list[Number], upper: list[Number], eps: Number = 0, max_iter: int = 10000
) -> Optional[tuple[Number, list[Number]]]:
    """Minimize c x subject to A x = b and 0 <= x <= upper (entries of upper may be inf).

    Returns (value, x), or None if the system has no solution. Raises ValueError if
    the LP is unbounded or the iteration cap is reached.
    Precondition: all rows of A have the length of c and upper.
    Cost: each pivot takes O(m (n + m)) operations for m rows and n columns; Bland's
    rule ensures termination, and the number of pivots is exponential only in the worst case.
    """
    m, n = len(A), len(c)
    # eps = 0 means exact arithmetic: work with fractions, so that no int division gives a float.
    num = Fraction if eps == 0 else float
    A = [[num(v) for v in row] for row in A]
    b = [num(v) for v in b]
    c = [num(v) for v in c]
    upper = [v if v == INF else num(v) for v in upper]
    rows = []
    rhs = []
    for i in range(m):
        sign = -1 if b[i] < 0 else 1
        rows.append([sign * v for v in A[i]] + [1 if j == i else 0 for j in range(m)])
        rhs.append(sign * b[i])
    total = n + m
    ub: list[Number] = list(upper) + [INF] * m
    basis = list(range(n, total))
    at_upper = [False] * total
    val: list[Number] = [0] * n + rhs

    def run(cost: list[Number]) -> None:
        d = [cost[j] - sum(cost[basis[i]] * rows[i][j] for i in range(m)) for j in range(total)]
        for _ in range(max_iter):
            enter = -1
            for j in range(total):
                if j in basis_set:
                    continue
                if (not at_upper[j] and d[j] < -eps and ub[j] > 0) or (at_upper[j] and d[j] > eps):
                    enter = j
                    break
            if enter < 0:
                return
            delta = -1 if at_upper[enter] else 1
            step = ub[enter]
            leave_row = -1
            leave_up = False
            for i in range(m):
                alpha = delta * rows[i][enter]
                if alpha > eps:
                    t = val[basis[i]] / alpha
                    up_side = False
                elif alpha < -eps and ub[basis[i]] != INF:
                    t = (ub[basis[i]] - val[basis[i]]) / (-alpha)
                    up_side = True
                else:
                    continue
                # The least step wins; on a tie, a bound flip of the entering variable, then
                # the basic variable with the lowest index (Bland's rule).
                if t < step or (t == step and leave_row >= 0 and basis[i] < basis[leave_row]):
                    step, leave_row, leave_up = t, i, up_side
            if step == INF:
                raise ValueError("unbounded linear program")
            for i in range(m):
                val[basis[i]] -= delta * step * rows[i][enter]
            val[enter] += delta * step
            if leave_row < 0:
                at_upper[enter] = not at_upper[enter]
                continue
            out = basis[leave_row]
            piv = rows[leave_row][enter]
            rows[leave_row] = [v / piv for v in rows[leave_row]]
            for i in range(m):
                if i != leave_row and rows[i][enter] != 0:
                    f = rows[i][enter]
                    rows[i] = [v - f * w for v, w in zip(rows[i], rows[leave_row])]
            f = d[enter]
            d[:] = [v - f * w for v, w in zip(d, rows[leave_row])]
            basis[leave_row] = enter
            basis_set.discard(out)
            basis_set.add(enter)
            at_upper[enter] = False
            at_upper[out] = leave_up
            val[out] = ub[out] if leave_up else 0
        raise ValueError("iteration cap reached")

    basis_set = set(basis)
    run([0] * n + [1] * m)
    if sum(val[n:]) > eps * (1 + m):
        return None
    for j in range(n, total):
        ub[j] = 0
    run(list(c) + [0] * m)
    x = val[:n]
    return sum(cj * xj for cj, xj in zip(c, x)), x


def cta(
    a: Sequence[Number],
    relations: Sequence[Relation],
    lower: Sequence[Number],
    upper: Sequence[Number],
    weights: Sequence[Number],
    sensitive: dict[int, tuple[Number, Number]],
    directions: Optional[dict[int, int]] = None,
    eps: Number = 1e-9,
) -> Optional[tuple[list[Number], Number, dict[int, int]]]:
    """The optimal L1 CTA over all directions, or over the given directions only.

    Returns (x, cost, chosen) where x is the published table, cost is sum w |x - a|,
    and chosen maps each sensitive cell to +1 (up) or -1 (down); or None if no
    choice of directions is feasible.
    Precondition: a satisfies every relation, lower <= a <= upper, weights >= 0, and
    the protection levels are >= 0. directions, if given, maps each sensitive cell to +1 or -1.
    Cost: 2^|P| linear programs with |relations| rows and 2n columns, or one LP if
    directions are given.
    """
    n = len(a)
    cells = sorted(sensitive)
    if directions is None:
        choices = list(product((-1, 1), repeat=len(cells)))
    else:
        choices = [tuple(directions[p] for p in cells)]
    best: Optional[tuple[list[Number], Number, dict[int, int]]] = None  # @line L1
    for choice in choices:  # @line L2
        # Columns 0 .. n-1 are z+ (x goes up), columns n .. 2n-1 are z- (x goes down).
        lo = [0] * (2 * n)
        hi = [upper[i] - a[i] for i in range(n)] + [a[i] - lower[i] for i in range(n)]  # @line L3
        for p, d in zip(cells, choice):  # @line L4
            lpl, upl = sensitive[p]
            if d > 0:
                lo[p], hi[n + p] = upl, 0
            else:
                lo[n + p], hi[p] = lpl, 0
        if any(lo[j] > hi[j] for j in range(2 * n)):
            continue
        A = []
        b = []
        for rel in relations:
            row = [0] * (2 * n)
            for cell, coef in rel:
                row[cell] += coef
                row[n + cell] -= coef
            A.append(row)
            b.append(-sum(row[j] * lo[j] for j in range(2 * n)))
        cost = [weights[i % n] for i in range(2 * n)]
        res = bounded_simplex(A, b, cost, [hi[j] - lo[j] for j in range(2 * n)], eps)  # @line L5
        if res is None:
            continue
        value, z = res
        z = [z[j] + lo[j] for j in range(2 * n)]
        value += sum(cost[j] * lo[j] for j in range(2 * n))
        if best is None or value < best[1] - eps:  # @line L6
            x = [a[i] + z[i] - z[n + i] for i in range(n)]
            best = (x, value, dict(zip(cells, choice)))
    if best is None:  # @line L7
        return None
    return best  # @line L8


def check(
    x: Sequence[Number],
    a: Sequence[Number],
    relations: Sequence[Relation],
    lower: Sequence[Number],
    upper: Sequence[Number],
    sensitive: dict[int, tuple[Number, Number]],
    eps: Number = 1e-9,
) -> bool:
    """True if x satisfies the relations and the bounds and protects every sensitive cell."""
    if any(abs(sum(coef * x[cell] for cell, coef in rel)) > eps for rel in relations):
        return False
    if any(x[i] < lower[i] - eps or x[i] > upper[i] + eps for i in range(len(x))):
        return False
    return all(x[p] <= a[p] - lpl + eps or x[p] >= a[p] + upl - eps for p, (lpl, upl) in sensitive.items())
test_controlled_tabular_adjustment.py 111 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/controlled-tabular-adjustment/. The authors are listed in prov/P26HSK.jsonl.
import itertools
import random
from fractions import Fraction as F

from controlled_tabular_adjustment import bounded_simplex, check, cta


def full_table(inner):
    t = [row + [sum(row)] for row in inner]
    t.append([sum(t[r][c] for r in range(len(inner))) for c in range(len(t[0]))])
    return [v for row in t for v in row]


def relations(rows, cols):
    w = cols + 1
    rel = [[(r * w + c, 1) for c in range(cols)] + [(r * w + cols, -1)] for r in range(rows + 1)]
    rel += [[(r * w + c, 1) for r in range(rows)] + [(rows * w + c, -1)] for c in range(cols + 1)]
    return rel


PAGE = [[20, 10, 15], [5, 25, 30], [12, 18, 10]]


def page_problem():
    a = [F(v) for v in full_table(PAGE)]
    n = len(a)
    return a, relations(3, 3), [F(0)] * n, [F(10**6)] * n, [1] * n


def test_page_example() -> None:
    a, rel, lo, up, w = page_problem()
    sens = {4: (F(3), F(3)), 10: (F(2), F(2))}
    x, cost, chosen = cta(a, rel, lo, up, w, sens, eps=0)
    assert cost == 12 and chosen == {4: -1, 10: -1}
    assert check(x, a, rel, lo, up, sens, eps=0)
    y = [x[i] - a[i] for i in range(16)]
    assert y == [1, -1, 0, 0, -3, 1, 2, 0, 2, 0, -2, 0, 0, 0, 0, 0]
    costs = {}
    for d in itertools.product((-1, 1), repeat=2):
        costs[d] = cta(a, rel, lo, up, w, sens, directions={4: d[0], 10: d[1]}, eps=0)[1]
    assert costs == {(-1, -1): 12, (-1, 1): 16, (1, -1): 16, (1, 1): 12}
    one = cta(a, rel, lo, up, w, {4: (F(3), F(3))}, eps=0)
    assert one[1] == 12
    # The same problem in floats gives the same cost.
    xf, cf, _ = cta([float(v) for v in a], rel, [0.0] * 16, [1e6] * 16, w, {4: (3.0, 3.0), 10: (2.0, 2.0)})
    assert abs(cf - 12) < 1e-7


def test_infeasible() -> None:
    a = [F(v) for v in full_table([[1, 2], [3, 4]])]
    rel = relations(2, 2)
    # Every cell is fixed, so no sensitive cell can move.
    assert cta(a, rel, a, a, [1] * 9, {0: (F(1), F(1))}, eps=0) is None
    # Cell 0 may only go down to 0, which is not below 1 - 2.
    lo = [v - 1 for v in a]
    up = list(a)
    assert cta(a, rel, lo, up, [1] * 9, {0: (F(2), F(1))}, eps=0) is None


def test_simplex_small() -> None:
    # minimize -x - y with x + y + s = 4, x <= 3, y <= 3: optimum -4.
    value, x = bounded_simplex([[1, 1, 1]], [4], [-1, -1, 0], [3, 3, float("inf")], eps=0)
    assert value == -4 and x[0] + x[1] == 4
    # x + y = 5 with x, y <= 2 has no solution.
    assert bounded_simplex([[1, 1]], [5], [1, 1], [2, 2], eps=0) is None
    # A redundant row.
    value, x = bounded_simplex([[1, 1], [2, 2]], [2, 4], [1, 2], [5, 5], eps=0)
    assert value == 2 and x == [2, 0]


def brute(a, lo, up, w, sens):
    """All integer adjustments of a 2 x 2 table with totals. The table relations form a
    totally unimodular matrix, so the LP optimum of each direction is an integer point."""
    best = None
    ranges = [range(int(lo[i] - a[i]), int(up[i] - a[i]) + 1) for i in (0, 1, 3, 4)]
    for y00, y01, y10, y11 in itertools.product(*ranges):
        y = [y00, y01, y00 + y01, y10, y11, y10 + y11, y00 + y10, y01 + y11, y00 + y01 + y10 + y11]
        if any(a[i] + y[i] < lo[i] or a[i] + y[i] > up[i] for i in range(9)):
            continue
        if any(not (y[p] >= upl or y[p] <= -lpl) for p, (lpl, upl) in sens.items()):
            continue
        cost = sum(w[i] * abs(y[i]) for i in range(9))
        if best is None or cost < best:
            best = cost
    return best


def test_against_brute_force() -> None:
    rng = random.Random(2006)
    rel = relations(2, 2)
    for _ in range(500):
        a = full_table([[rng.randint(0, 6) for _ in range(2)] for _ in range(2)])
        lo = [a[i] - rng.randint(0, 2) for i in range(9)]
        up = [a[i] + rng.randint(0, 2) for i in range(9)]
        w = [rng.randint(1, 3) for _ in range(9)]
        cells = rng.sample(range(9), rng.randint(1, 2))
        sens = {p: (rng.randint(1, 2), rng.randint(1, 2)) for p in cells}
        want = brute(a, lo, up, w, sens)
        res = cta([float(v) for v in a], rel, lo, up, w, sens)
        if want is None:
            assert res is None
            continue
        x, cost, chosen = res
        assert abs(cost - want) < 1e-6
        assert check(x, a, rel, lo, up, sens, eps=1e-6)
        assert abs(sum(w[i] * abs(x[i] - a[i]) for i in range(9)) - cost) < 1e-6
        fixed = cta([float(v) for v in a], rel, lo, up, w, sens, directions={p: 1 for p in cells})
        if fixed is not None:
            assert fixed[1] >= cost - 1e-6

History

Cox (1980) set up the protection of sensitive cells in tables with totals by suppression. Dandekar and Cox proposed controlled tabular adjustment in 2002 as an alternative that publishes every cell and keeps the totals. Castro (2006) studied minimum-distance adjustment of large tables with the L1 and L2 distances.

References

  1. Jordi Castro, Minimum-distance controlled perturbation methods for large-scale tabular data protection, European Journal of Operational Research 171(1), 2006, pp. 39 to 52, minimum-distance adjustment of tables with the L1 and L2 distances, for large tables
  2. Ramesh A. Dandekar and Lawrence H. Cox, Synthetic tabular data, an alternative to complementary cell suppression, manuscript, Energy Information Administration, 2002, the first statement 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 4, Magnitude tabular data, pp. 131 to 182, sensitivity rules and protection levels
  4. Lawrence H. Cox, Suppression methodology and statistical disclosure control, Journal of the American Statistical Association 75(370), 1980, pp. 377 to 385, protection of sensitive cells in tables with totals
  5. Robert G. Bland, New finite pivoting rules for the simplex method, Mathematics of Operations Research 2(2), 1977, pp. 103 to 107, the least-index rule and the proof that the simplex method then terminates

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