Algorithm Search⌘K

Algorithmadvanced

TANE

Also called TANE algorithm.

Find all minimal functional dependencies of a relation by a levelwise search over attribute sets. Stripped partitions test each candidate, and candidate sets and keys prune the search.

Time
O((n + m^2.5) 2^m) worstO(s (n + m^2) + q m^3) averageO(m n + m^3) best
Space
O((n + m) 2^m / sqrt(m)) extra
Where
m = the number of attributes; n = the number of tuples; q = the number of superkeys met in the search; s = the number of attribute sets in all levels
Properties
deterministicexactnot externalnot in placeofflineiterative
Origin
Yka Huhtala, Juha Kärkkäinen, Pasi Porkka, Hannu Toivonen, 1998

TANE finds all minimal functional dependencies X→AX \to A that hold in one relation instance. It visits the attribute sets level by level, from small sets to large ones, as on the lattice of all subsets. For each set XX it keeps the stripped partition of the tuples by their values on XX, and X∖{A}→AX \setminus \{A\} \to A holds exactly when the partitions of X∖{A}X \setminus \{A\} and XX have the same number of classes. Sets of right-hand side candidates C+(X)C^+(X) and key pruning cut the levels. The page functional dependency discovery states the problem and compares TANE with the methods that work from pairs of rows. TANE is the levelwise method: its time is linear in the number of tuples and exponential in the number of attributes.

In plain words

You have a table and you want every rule of the form "these columns decide that column". TANE starts with single columns, then pairs, then triples. For each group of columns it sorts the rows into piles, with one pile for each combination of values. If adding a column to a group does not split any pile, the group decides that column. It throws away piles with one row, because they can never break a rule. It also stops growing a group when nothing useful can come from it: when the group already decides every column, or when no column is left that could still give a new, shortest rule. Each rule it reports is as short as possible, and it reports each one once.

The problem

The input is a relation rr with nn tuples over a set RR of mm attributes, under set semantics, with no nulls. The output is every non-trivial dependency X→AX \to A (A∉XA \notin X) that holds in rr and is minimal: no proper subset of XX determines AA. The output can have size exponential in mm, as shown on the problem page, so no method is polynomial in mm in the worst case.

Partitions. Two tuples are equivalent on XX if they agree on every attribute of XX. The classes of this relation form the partition πX\pi_X. The stripped partition π^X\hat\pi_X drops the classes of size 1. Write ∥π^X∥\|\hat\pi_X\| for the number of tuples in its classes and e(X)=∥π^X∥−∣π^X∣e(X) = \|\hat\pi_X\| - |\hat\pi_X|. The paper divides e(X)e(X) by nn; the integer form used here also works for n=0n = 0. The test is Lemma 3.5 of Huhtala et al.: X→AX \to A holds if and only if e(X)=e(X∪{A})e(X) = e(X \cup \{A\}). XX is a superkey if and only if e(X)=0e(X) = 0.

Candidates. For a set XX,

C+(X)={A∈R:X∖{A,B}→B fails for every B∈X}.C^+(X) = \{ A \in R : X \setminus \{A, B\} \to B \text{ fails for every } B \in X \}.

If X∖{A}→AX \setminus \{A\} \to A holds, it is minimal if and only if A∈C+(X∖{B})A \in C^+(X \setminus \{B\}) for every B∈XB \in X (Lemma 3.1). C+C^+ can only shrink as XX grows.

The algorithm

  1. TANE(r, R)
  2. 1L_0 ← {∅}; C+(∅) ← R; the partition of ∅ has one class with all tuples
  3. 2L_1 ← {{A} : A ∈ R}, with the stripped partition of each {A} read from r
  4. 3ℓ ← 1
  5. 4while L_ℓ ≠ ∅ do
  6. 5COMPUTE-DEPENDENCIES(L_ℓ)
  7. 6PRUNE(L_ℓ)
  8. 7L_(ℓ+1) ← GENERATE-NEXT-LEVEL(L_ℓ); ℓ ← ℓ + 1
  9. COMPUTE-DEPENDENCIES(L_ℓ)
  10. 8for each X ∈ L_ℓ do C+(X) ← the intersection of C+(X \ {A}) over all A ∈ X
  11. 9for each X ∈ L_ℓ and each A ∈ X ∩ C+(X) do
  12. 10if e(X \ {A}) = e(X) then ▷ X \ {A} → A holds
  13. 11output X \ {A} → A
  14. 12remove A and every B ∈ R \ X from C+(X)
  15. PRUNE(L_ℓ)
  16. 13for each X ∈ L_ℓ do
  17. 14if C+(X) = ∅ then delete X from L_ℓ
  18. 15else if e(X) = 0 then ▷ X is a superkey
  19. 16for each A ∈ C+(X) \ X with A ∈ C+(X ∪ {A} \ {B}) for all B ∈ X do output X → A
  20. 17delete X from L_ℓ
  21. GENERATE-NEXT-LEVEL(L_ℓ)
  22. 18for each pair Y, Z ∈ L_ℓ that differ only in their last attribute do
  23. 19X ← Y ∪ Z; if X \ {A} ∈ L_ℓ for every A ∈ X then add X to L_(ℓ+1), with partition(Y) · partition(Z)

Line L8 starts C+(X)C^+(X) from its subsets. Line L10 tests one candidate with two numbers. Line L12 has two parts: AA leaves because X∖{A}→AX \setminus \{A\} \to A is now known, and every attribute outside XX leaves because a larger left side that holds XX cannot be minimal for it (Lemma 3.2). Line L14 drops a set with no candidates, since no superset can give a new dependency. Lines L15 to L17 are key pruning: every superset of a superkey is a superkey and gives only non-minimal dependencies, so XX is deleted, and the dependencies X→AX \to A that the next level would have found are output at once. Line L19 is the stripped product: it builds π^X\hat\pi_X from the two parents in time linear in their size, with one table of nn entries. The test in line L16 reads C+(X∪{A}∖{B})C^+(X \cup \{A\} \setminus \{B\}); when that set was never made, the code tests X∖{B}→AX \setminus \{B\} \to A directly, as explained under Pitfalls.

Example

The relation has 5 tuples over A,B,C,DA, B, C, D.

tuple A B C D
t1 1 a x 1
t2 1 a y 2
t3 2 b x 1
t4 2 b y 3
t5 3 b x 1

The stripped partitions of level 1 are π^A={{1,2},{3,4}}\hat\pi_A = \{\{1,2\},\{3,4\}\}, π^B={{1,2},{3,4,5}}\hat\pi_B = \{\{1,2\},\{3,4,5\}\}, π^C={{1,3,5},{2,4}}\hat\pi_C = \{\{1,3,5\},\{2,4\}\} and π^D={{1,3,5}}\hat\pi_D = \{\{1,3,5\}\}, so e=2,3,3,2e = 2, 3, 3, 2, and e(∅)=4e(\emptyset) = 4. No column is constant, so level 1 finds nothing, and no single attribute is a key.

level set e dependency at L10 C+ after L12 PRUNE
2 AB 2 A→BA \to B, since e(A)=2e(A) = 2 {A} kept
2 AC 0 none {A, B, C, D} superkey: output AC→DAC \to D, delete
2 AD 0 none {A, B, C, D} superkey: no output, delete
2 BC 1 none {A, B, C, D} kept
2 BD 1 none {A, B, C, D} kept
2 CD 2 D→CD \to C, since e(D)=2e(D) = 2 {D} kept
3 BCD 1 BC→DBC \to D, since e(BC)=1e(BC) = 1 {} delete

At the superkey ACAC, line L16 accepts DD because D∈C+(CD)D \in C^+(CD) and D∈C+(AD)D \in C^+(AD), and rejects BB because B∉C+(AB)B \notin C^+(AB): A→BA \to B already holds. At ADAD it rejects BB for the same reason and CC because C∉C+(CD)C \notin C^+(CD). Level 3 is made from the kept sets AB,BC,BD,CDAB, BC, BD, CD: only BCBC and BDBD share a prefix, and the three subsets of BCDBCD are all kept. C+(BCD)={D}C^+(BCD) = \{D\}, so only BC→DBC \to D is tested. The output is A→BA \to B, D→CD \to C, AC→DAC \to D and BC→DBC \to D, and the run handles 12 of the 16 attribute sets.

Correctness

The main fact is that the stored C+(X)C^+(X) is exactly the set of the definition for every set that the run handles: line L8 gives the part that comes from the subsets, and lines L9 to L12 remove the rest. With this, an output at line L11 is minimal because no X∖{A,B}X \setminus \{A, B\} determines AA, and an output at line L16 is minimal because no X∖{B}X \setminus \{B\} does. A minimal Y→AY \to A is found at line L11 on Y∪{A}Y \cup \{A\} unless some subset is a superkey; then YY itself is a key, and line L16 finds it there. Lemmas 4.1 and 4.2 of the paper state these two parts. The full proof, for the version with the direct test in line L16, is in the proof page.

Proof: TANE outputs each minimal functional dependency exactly oncefull

We use the pseudocode of the page for exact dependencies (ε=0\varepsilon = 0, key pruning on). The relation rr has nn tuples over the attribute set RR. All dependencies are non-trivial, so in Y→AY \to A we have A∉YA \notin Y. Y→AY \to A is minimal if it holds and Z→AZ \to A fails for each proper subset Z⊊YZ \subsetneq Y. A set is processed if it is in some level LℓL_\ell when line L5 runs, and kept if it is still in LℓL_\ell after line L6. We write D(X)D(X) for the set that the algorithm stores as C+(X)C^+(X), and C+(X)C^+(X) for the set of the definition:

C+(X)={A∈R:X∖{A,B}→B fails for every B∈X}.C^+(X) = \{ A \in R : X \setminus \{A, B\} \to B \text{ fails for every } B \in X \}.

We use two facts about dependencies. (Augmentation) If Z→BZ \to B holds and Z⊆Z′Z \subseteq Z', then Z′→BZ' \to B holds. (Transitivity) If Z→BZ \to B holds for each B∈WB \in W and W→AW \to A holds, then Z→AZ \to A holds.

Lemma 1 (the test of line L10). For attribute sets ZZ and an attribute AA, Z→AZ \to A holds if and only if e(Z)=e(Z∪{A})e(Z) = e(Z \cup \{A\}), where e(X)=∥π^X∥−∣π^X∣e(X) = \|\hat\pi_X\| - |\hat\pi_X|.

Proof. A class of size 1 adds 1−1=01 - 1 = 0 to ∑c(∣c∣−1)\sum_c (|c| - 1), so e(X)=n−∣πX∣e(X) = n - |\pi_X|, where πX\pi_X is the full partition of the tuples by their values on XX. Each class of πZ∪{A}\pi_{Z \cup \{A\}} lies inside one class of πZ\pi_Z, so ∣πZ∪{A}∣≥∣πZ∣|\pi_{Z \cup \{A\}}| \ge |\pi_Z|, with equality if and only if the two partitions are equal. They are equal if and only if two tuples that agree on ZZ always agree on AA, which is Z→AZ \to A. □\square

The stripped product of line L19 returns π^Y∪Z\hat\pi_{Y \cup Z} from π^Y\hat\pi_Y and π^Z\hat\pi_Z: two tuples are in one class of πY∪Z\pi_{Y \cup Z} if and only if they share a class of πY\pi_Y and a class of πZ\pi_Z, and classes of size 1 can be dropped from either input because a tuple alone in its class is alone in the product too. So every ee value of the run is the right one.

Lemma 2 (antimonotone). If X⊆X′X \subseteq X', then C+(X′)⊆C+(X)C^+(X') \subseteq C^+(X).

Proof. Let A∈C+(X′)A \in C^+(X') and B∈XB \in X. Then X∖{A,B}⊆X′∖{A,B}X \setminus \{A, B\} \subseteq X' \setminus \{A, B\}. If X∖{A,B}→BX \setminus \{A, B\} \to B held, augmentation would give X′∖{A,B}→BX' \setminus \{A, B\} \to B with B∈X′B \in X', which is false. □\square

Lemma 3 (generation). Every subset of a processed set is processed. A set X≠∅X \neq \emptyset is processed if every set X∖{B}X \setminus \{B\} with B∈XB \in X is processed and kept.

Proof. Line L19 adds XX only when every X∖{A}X \setminus \{A\} is kept, and level 1 holds all singletons, whose only proper subset ∅\emptyset is in L0L_0. Induction on the size gives the first part. For the second part, let ∣X∣=ℓ+1≥2|X| = \ell + 1 \ge 2 and let YY and ZZ be XX without its largest and without its second largest attribute. YY and ZZ are kept sets of level ℓ\ell with the same first ℓ−1\ell - 1 attributes, so line L18 meets the pair, and line L19 adds XX. For ∣X∣=1|X| = 1, line L2 puts XX in L1L_1. □\square

Lemma 4 (the stored sets are exact). For every processed set XX, after line L12 has handled XX, D(X)=C+(X)D(X) = C^+(X).

Proof. By induction on ∣X∣|X|. For X=∅X = \emptyset, D(∅)=R=C+(∅)D(\emptyset) = R = C^+(\emptyset), because the condition is empty. Let ∣X∣≥1|X| \ge 1. By Lemma 3 every X∖{B}X \setminus \{B\} is processed, so by induction line L8 sets D(X)=ID(X) = I with I=⋂B∈XC+(X∖{B})I = \bigcap_{B \in X} C^+(X \setminus \{B\}). By Lemma 2, C+(X)⊆IC^+(X) \subseteq I. We show that lines L9 to L12 remove exactly the elements of I∖C+(X)I \setminus C^+(X).

Elements A∈XA \in X. Here A∈C+(X)A \in C^+(X) means: X∖{A,B}→BX \setminus \{A, B\} \to B fails for every B∈X∖{A}B \in X \setminus \{A\}, and X∖{A}→AX \setminus \{A\} \to A fails. The term B=AB = A of II is C+(X∖{A})C^+(X \setminus \{A\}), and A∈C+(X∖{A})A \in C^+(X \setminus \{A\}) says exactly that X∖{A,B}→BX \setminus \{A, B\} \to B fails for every B∈X∖{A}B \in X \setminus \{A\}. So for A∈X∩IA \in X \cap I, A∈C+(X)A \in C^+(X) if and only if X∖{A}→AX \setminus \{A\} \to A fails. Line L9 visits every A∈X∩IA \in X \cap I (line L12 removes only AA itself and attributes outside XX, so no other element of XX leaves the loop), line L10 tests X∖{A}→AX \setminus \{A\} \to A by Lemma 1, and line L12 removes AA when it holds.

Elements A∉XA \notin X. Here X∖{A,B}=X∖{B}X \setminus \{A, B\} = X \setminus \{B\}, so A∈C+(X)A \in C^+(X) if and only if XX has no attribute CC with X∖{C}→CX \setminus \{C\} \to C; call such an XX irredundant. This condition does not depend on AA. If XX is irredundant, line L12 must remove nothing outside XX, and indeed it removes R∖XR \setminus X only after line L10 finds some C∈XC \in X with X∖{C}→CX \setminus \{C\} \to C. If XX is not irredundant, every A∉XA \notin X must go. There are two cases. (a) Some X∖{B}X \setminus \{B\} with B∈XB \in X is not irredundant. Then A∉C+(X∖{B})A \notin C^+(X \setminus \{B\}) for each A∉XA \notin X, because A∉X∖{B}A \notin X \setminus \{B\}; so A∉IA \notin I already. (b) Every X∖{B}X \setminus \{B\} is irredundant, and some C∈XC \in X has X∖{C}→CX \setminus \{C\} \to C. We show C∈IC \in I; then line L10 tests CC, finds the dependency, and line L12 removes R∖XR \setminus X. The term B=CB = C: C∉X∖{C}C \notin X \setminus \{C\}, so C∈C+(X∖{C})C \in C^+(X \setminus \{C\}) because X∖{C}X \setminus \{C\} is irredundant. A term B≠CB \neq C: let W=X∖{B}W = X \setminus \{B\}, which holds CC and is irredundant. For B′∈WB' \in W, the set W∖{C,B′}W \setminus \{C, B'\} is a subset of W∖{B′}W \setminus \{B'\}, and W∖{B′}→B′W \setminus \{B'\} \to B' fails, so by augmentation W∖{C,B′}→B′W \setminus \{C, B'\} \to B' fails too. Hence C∈C+(W)C \in C^+(W). □\square

Lemma 5. Let Y→AY \to A be minimal and X=Y∪{A}X = Y \cup \{A\}. Then A∈C+(Z)A \in C^+(Z) for every proper subset Z⊊XZ \subsetneq X, and A∈C+(Y∖{B}∪{A})A \in C^+(Y \setminus \{B\} \cup \{A\}) for every B∈YB \in Y.

Proof. First, YY is irredundant: if Y∖{C}→CY \setminus \{C\} \to C for some C∈YC \in Y, then Y∖{C}Y \setminus \{C\} determines every attribute of YY, and transitivity gives Y∖{C}→AY \setminus \{C\} \to A, against minimality. So A∈C+(Y)A \in C^+(Y), as in the second case of Lemma 4. Next let B∈YB \in Y and W=Y∖{B}∪{A}W = Y \setminus \{B\} \cup \{A\}. For C=AC = A: W∖{A}=Y∖{B}W \setminus \{A\} = Y \setminus \{B\}, and Y∖{B}→AY \setminus \{B\} \to A fails by minimality. For C∈Y∖{B}C \in Y \setminus \{B\}: W∖{A,C}=Y∖{B,C}W \setminus \{A, C\} = Y \setminus \{B, C\}, and if it determined CC, augmentation would give Y∖{C}→CY \setminus \{C\} \to C, against irredundance. So A∈C+(W)A \in C^+(W). The sets YY and WW are exactly the sets X∖{B′}X \setminus \{B'\} for B′∈XB' \in X, so by Lemma 2 every proper subset of XX has AA in its C+C^+. □\square

Soundness. Each output is a minimal dependency.

Line L11. It outputs X∖{A}→AX \setminus \{A\} \to A after line L10 has shown that it holds. Before line L12, A∈I⊆C+(X∖{B})A \in I \subseteq C^+(X \setminus \{B\}) for each B∈X∖{A}B \in X \setminus \{A\}. The set Z=X∖{B}Z = X \setminus \{B\} holds AA and is processed, and by Lemma 4 A∈C+(Z)A \in C^+(Z) means in particular that Z∖{A}→AZ \setminus \{A\} \to A fails. So X∖{A,B}→AX \setminus \{A, B\} \to A fails for every BB. A proper subset of X∖{A}X \setminus \{A\} lies inside some X∖{A,B}X \setminus \{A, B\}, so by augmentation it does not determine AA. The dependency is minimal.

Line L16. XX is a superkey, so X→AX \to A holds. For each B∈XB \in X, let YB=X∖{B}∪{A}Y_B = X \setminus \{B\} \cup \{A\}. If YBY_B was processed, the test reads A∈D(YB)=C+(YB)A \in D(Y_B) = C^+(Y_B) by Lemma 4, and the condition for the attribute AA itself says that YB∖{A}=X∖{B}Y_B \setminus \{A\} = X \setminus \{B\} does not determine AA. If YBY_B was not processed, the code tests directly that X∖{B}→AX \setminus \{B\} \to A fails. Either way no X∖{B}X \setminus \{B\} determines AA, and by augmentation no proper subset of XX does. The dependency is minimal.

Completeness. Let Y→AY \to A be minimal and X=Y∪{A}X = Y \cup \{A\}. By Lemma 5 and Lemma 4, every processed proper subset of XX has a non-empty stored set, so line L14 deletes none of them.

Case 1: no proper subset of XX is a superkey. Then line L17 deletes none of them either, and Lemma 3 by induction on the size shows that every proper subset of XX is processed and kept, and that XX is processed. At line L8, A∈IA \in I by Lemma 5, and A∈XA \in X, so line L9 visits AA; line L10 finds that Y→AY \to A holds, and line L11 outputs it.

Case 2: some proper subset Z⊊XZ \subsetneq X is a superkey. If A∉ZA \notin Z, then Z⊆YZ \subseteq Y and Z→AZ \to A, so Z=YZ = Y by minimality. If A∈ZA \in Z, then Z∖{A}⊆YZ \setminus \{A\} \subseteq Y, and YY determines every attribute of ZZ (those of YY trivially, and AA by assumption), so YY is a superkey by transitivity. Either way YY is a superkey. No proper subset WW of YY is a superkey, because W→AW \to A would contradict minimality. So, as in Case 1, every proper subset of YY is processed and kept and YY is processed. D(Y)=C+(Y)D(Y) = C^+(Y) holds AA by Lemma 5, so line L14 keeps YY, and line L15 finds that YY is a superkey. At line L16, A∈D(Y)∖YA \in D(Y) \setminus Y. For each B∈YB \in Y, if YBY_B was processed, then A∈C+(YB)A \in C^+(Y_B) by Lemma 5; if not, the direct test succeeds because Y∖{B}→AY \setminus \{B\} \to A fails. So line L16 outputs Y→AY \to A.

No dependency is output twice. Line L11 outputs Y→AY \to A only while it processes Y∪{A}Y \cup \{A\}, and line L16 only while it processes YY, and each set is processed at most once, in the level of its size. If line L16 outputs Y→AY \to A, then line L17 deletes YY, so by Lemma 3 the set Y∪{A}Y \cup \{A\} is never processed, and line L11 never outputs Y→AY \to A.

Termination. Level ℓ\ell holds only sets of size ℓ\ell, and line L7 moves to the next size. A level of size ∣R∣+1|R| + 1 is empty, so the loop of line L4 runs at most ∣R∣+1|R| + 1 times, and each pass handles finitely many sets. ■\blacksquare

The approximate version. With ε>0\varepsilon > 0, line L10 tests e(X∖{A}→A)≤εe(X \setminus \{A\} \to A) \le \varepsilon, line L12 removes R∖XR \setminus X only when the dependency holds exactly, and key pruning is off. This proof does not cover that version. Lemma 4 uses augmentation and transitivity of exact dependencies, and approximate dependencies are not transitive.

Complexity

The analysis is that of Section 5.1 of the paper, on a word RAM. Let ss be the number of sets in all levels and qq the number of superkeys met.

  • Partitions. Each of the ss sets gets one stripped product, O(n)O(n) each, so O(sn)O(s n).
  • Lattice work. Lines L8, L16 and L19 look up O(m)O(m) neighbours of each set, and each lookup costs O(m)O(m). This gives O(sm2+qm3)O(s m^2 + q m^3).
  • Total. O(s(n+m2)+qm3)O(s (n + m^2) + q m^3). The levels hold at most 2m2^m sets, and the largest level at most O(2m/m)O(2^m / \sqrt{m}), which gives Theorem 5.1: time O((n+m2.5)2m)O((n + m^{2.5}) 2^m) and space O((n+m)2m/m)O((n + m) 2^m / \sqrt{m}). The space bound holds because only two levels and their partitions are kept at a time.
  • Best case. If every attribute is a key, all of level 1 is deleted, and the run costs O(mn+m3)O(m n + m^3).

For a fixed set of dependencies the time is linear in nn. The exponential factor in mm cannot be removed in general, because the output itself can be that large.

Properties

  • Exact and complete. It returns all minimal dependencies and nothing else, each once.
  • Linear in the tuples. Each validity test is a comparison of two integers, after the partitions are built.
  • Memory bound. It keeps two levels of partitions. On wide relations the middle levels are the limit, not the time.
  • Approximate dependencies. The same search finds dependencies with a small g3 error, the least fraction of tuples to delete so that the dependency holds (Kivinen and Mannila's measure).

Variants and improvements

  • Approximate TANE. Section 4.6 of the paper changes line L10 to e(X∖{A}→A)≤εe(X \setminus \{A\} \to A) \le \varepsilon, and runs the second part of line L12 only when the dependency holds exactly. The g3 error comes from π^X∖{A}\hat\pi_{X \setminus \{A\}} and π^X\hat\pi_X in linear time: for each class of the first, keep its largest subclass in the second. The bounds e(X)−e(X∪{A})≤e(X→A)≤e(X)e(X) - e(X \cup \{A\}) \le e(X \to A) \le e(X) often decide the test without that pass. Key pruning must be off in this version (see Pitfalls).
  • Other lattice methods. FUN and FD_Mine also walk the lattice level by level, with other pruning rules. DFD walks it depth first with random walks.
  • Row-based methods. Dep-Miner and FastFDs compute the agree sets of all pairs of tuples and derive the dependencies from them, and FDEP induces them from the pairs that disagree. They are quadratic in nn but less sensitive to mm. Papenbrock et al. (2015) measured all seven on the same data sets.
  • Related constraints. Conditional functional dependencies and denial constraints are found by extensions of the same lattice and agree-set ideas.

When to use it

Use it to profile a table with many rows and few columns, to find candidate keys and dependencies before normalization or data cleaning. For wide tables with few rows, a row-based method is usually faster. Each result is a fact about this one instance, not about the schema: a dependency can hold by chance, so a human or a domain rule has to confirm it before it becomes a constraint.

Pitfalls

  • A missing neighbour in line L16. The set X∪{A}∖{B}X \cup \{A\} \setminus \{B\} may never have been made, because one of its subsets was deleted as a superkey. Reading a missing set as an empty C+C^+ loses dependencies. For a superkey XX and A∉XA \notin X, A∈C+(X∪{A}∖{B})A \in C^+(X \cup \{A\} \setminus \{B\}) if and only if X∖{B}→AX \setminus \{B\} \to A fails, so the code tests that directly when the set is missing.
  • Key pruning with approximate dependencies. Key pruning is safe only for exact dependencies. Take the tuples (1,0),(0,0),(2,2)(1, 0), (0, 0), (2, 2) over A,BA, B and ε=1/3\varepsilon = 1/3. {A}\{A\} is a key, so key pruning deletes it at level 1, the set {A,B}\{A, B\} is never made, and the minimal approximate dependency B→AB \to A (delete one tuple) is lost. The paper changes only lines L10 and L12 for this version; the implementation here also switches key pruning off.
  • Stale C+C^+. Line L9 must use the value of line L8 for the whole loop on XX, and line L12 must not remove attributes of XX other than AA. Otherwise some candidates are never tested.
  • Dividing by nn. With the fraction e(X)/ne(X)/n an empty relation divides by zero. The integer form avoids this, and with n≤1n \le 1 every attribute is constant, so every ∅→A\emptyset \to A holds.
  • Reading the output as constraints. On a sample, many dependencies hold only by chance. The output describes the instance.

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.

tane_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tane-algorithm/. The authors are listed in prov/HRXFKG.jsonl.
"""TANE: levelwise discovery of the minimal functional dependencies of a relation.

A relation is a list of rows, each row a tuple of hashable values, and the
attributes are the column numbers 0 .. k - 1. An attribute set is a frozenset of
column numbers. A dependency is a pair (X, A) that stands for X -> A, with A not
in X. The function tane returns the minimal non-trivial dependencies in sorted
order. With eps > 0 it returns the minimal approximate dependencies, those with
a g3 error of at most eps.

The error e(X) of the page is the integer ||p|| - |p| of the stripped
partition p of X: the number of tuples in its classes minus the number of
classes. The paper divides it by |r|; the integer form also works for |r| = 0.
"""

from fractions import Fraction


def single_partition(rows, a):
    """The stripped partition of the one attribute a: classes of size >= 2."""
    groups = {}
    for t, row in enumerate(rows):
        groups.setdefault(row[a], []).append(t)
    return [g for g in groups.values() if len(g) > 1]


def partition_of(rows, attrs):
    """The stripped partition of a set of attributes, computed from the rows."""
    order = sorted(attrs)
    groups = {}
    for t, row in enumerate(rows):
        groups.setdefault(tuple(row[a] for a in order), []).append(t)
    return [g for g in groups.values() if len(g) > 1]


def stripped_product(p1, p2, n):
    """The stripped partition of X union Y from those of X and Y, in linear time."""
    owner = [None] * n
    for i, c in enumerate(p1):
        for t in c:
            owner[t] = i
    bucket = [[] for _ in p1]
    out = []
    for c in p2:
        for t in c:
            if owner[t] is not None:
                bucket[owner[t]].append(t)
        for t in c:
            i = owner[t]
            if i is not None:
                if len(bucket[i]) >= 2:
                    out.append(bucket[i])
                bucket[i] = []
    return out


def error_count(p):
    """e(X) as an integer: ||p|| - |p|. It is 0 if and only if X is a superkey."""
    return sum(len(c) for c in p) - len(p)


def g3_count(p_lhs, p_both):
    """The least number of tuples to delete so that X -> A holds (g3 times |r|)."""
    size = {}
    for c in p_both:
        for t in c:
            size[t] = len(c)
    removed = 0
    for c in p_lhs:
        removed += len(c) - max(size.get(t, 1) for t in c)
    return removed


def tane(rows, k, eps=0, key_pruning=None):
    """Return the sorted list of minimal dependencies (X, A) of the relation.

    Key pruning (lines L15 to L17) is on for exact dependencies only. With
    eps > 0 it can lose minimal approximate dependencies, so it is off by
    default; pass key_pruning=True to get the literal version of the paper.
    """
    n = len(rows)
    R = frozenset(range(k))
    limit = Fraction(eps) * n
    exact = eps == 0
    if key_pruning is None:
        key_pruning = exact
    part = {frozenset(): [list(range(n))] if n >= 2 else []}  # @line L1
    cplus = {frozenset(): R}  # @line L1
    singles = {a: single_partition(rows, a) for a in range(k)}
    for a in range(k):
        part[frozenset([a])] = singles[a]  # @line L2
    level = [frozenset([a]) for a in range(k)]  # @line L2
    fds = []

    def get_part(Y):
        if Y not in part:
            base = max(Y)
            part[Y] = stripped_product(get_part(Y - {base}), singles[base], n)
        return part[Y]

    def holds(lhs, a):
        both = lhs | {a}
        if exact:
            return error_count(get_part(lhs)) == error_count(get_part(both))
        return g3_count(get_part(lhs), get_part(both)) <= limit

    ell = 1  # @line L3
    while level:  # @line L4
        # COMPUTE-DEPENDENCIES
        for X in level:  # @line L5
            c = R
            for a in X:
                c = c & cplus[X - {a}]  # @line L8
            cplus[X] = c
        for X in level:
            for a in sorted(X & cplus[X]):  # @line L9
                if holds(X - {a}, a):  # @line L10
                    fds.append((X - {a}, a))  # @line L11
                    cplus[X] = cplus[X] - {a}  # @line L12
                    if exact or error_count(part[X - {a}]) == error_count(part[X]):
                        cplus[X] = cplus[X] - (R - X)  # @line L12
        # PRUNE
        kept = []
        for X in level:  # @line L6
            if not cplus[X]:  # @line L13
                continue  # @line L14
            if key_pruning and error_count(part[X]) == 0:  # @line L15
                for a in sorted(cplus[X] - X):
                    ok = True
                    for b in sorted(X):
                        Y = (X - {b}) | {a}
                        if Y in cplus:
                            inside = a in cplus[Y]  # @line L16
                        else:
                            # Y was never generated; then a is in C+(Y) exactly
                            # when X - {b} -> a fails (see the Pitfalls section).
                            inside = not holds(X - {b}, a)  # @line L16
                        if not inside:
                            ok = False
                            break
                    if ok:
                        fds.append((X, a))  # @line L16
                continue  # @line L17
            kept.append(X)
        # GENERATE-NEXT-LEVEL
        kept_set = set(kept)
        blocks = {}
        for X in sorted(tuple(sorted(X)) for X in kept):
            blocks.setdefault(X[:-1], []).append(X)
        nxt = []
        for prefix in sorted(blocks):  # @line L7
            block = blocks[prefix]
            for i in range(len(block)):
                for j in range(i + 1, len(block)):  # @line L18
                    Y, Z = frozenset(block[i]), frozenset(block[j])
                    X = Y | Z  # @line L19
                    if all(X - {a} in kept_set for a in X):  # @line L19
                        part[X] = stripped_product(part[Y], part[Z], n)  # @line L19
                        nxt.append(X)
        level = nxt  # @line L7
        ell += 1  # @line L7
    return sorted(fds, key=lambda d: (len(d[0]), sorted(d[0]), d[1]))


def format_fd(fd, names=None):
    """Write (X, A) as a string such as 'AB -> C'."""
    lhs, a = fd
    if names is None:
        names = [chr(ord("A") + i) for i in range(max(list(lhs) + [a]) + 1)]
    left = "".join(names[i] for i in sorted(lhs)) or "{}"
    return left + " -> " + names[a]
test_tane_algorithm.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tane-algorithm/. The authors are listed in prov/HRXFKG.jsonl.

import itertools
import random
from fractions import Fraction

from tane_algorithm import (
    error_count,
    format_fd,
    g3_count,
    partition_of,
    stripped_product,
    tane,
)


def fd_holds(rows, lhs, a):
    """X -> A by the definition: two rows that agree on X agree on A."""
    for r, s in itertools.combinations(rows, 2):
        if all(r[b] == s[b] for b in lhs) and r[a] != s[a]:
            return False
    return True


def g3_brute(rows, lhs, a):
    """The least number of rows to delete so that X -> A holds, by trying all subsets."""
    n = len(rows)
    for m in range(n + 1):
        for drop in itertools.combinations(range(n), m):
            rest = [rows[i] for i in range(n) if i not in drop]
            if fd_holds(rest, lhs, a):
                return m
    return n


def brute_minimal_fds(rows, k, test):
    """All minimal non-trivial X -> A, by checking every X and every subset."""
    out = []
    for a in range(k):
        others = [b for b in range(k) if b != a]
        for size in range(len(others) + 1):
            for lhs in itertools.combinations(others, size):
                X = frozenset(lhs)
                if test(X, a) and all(not test(X - {b}, a) for b in X):
                    out.append((X, a))
    return sorted(out, key=lambda d: (len(d[0]), sorted(d[0]), d[1]))


def random_rows(rng, n, k, dom):
    return [tuple(rng.randrange(dom) for _ in range(k)) for _ in range(n)]


def as_set(fds):
    return {(frozenset(x), a) for x, a in fds}


def test_page_example():
    rows = [(1, "a", "x", 1), (1, "a", "y", 2), (2, "b", "x", 1), (2, "b", "y", 3), (3, "b", "x", 1)]
    got = [format_fd(d) for d in tane(rows, 4)]
    assert got == ["A -> B", "D -> C", "AC -> D", "BC -> D"]
    assert as_set(tane(rows, 4)) == as_set(brute_minimal_fds(rows, 4, lambda X, a: fd_holds(rows, X, a)))
    assert [error_count(partition_of(rows, X)) for X in ([], [0], [1], [2], [3])] == [4, 2, 3, 3, 2]


def test_key_pruning_loses_approximate_dependencies():
    rows = [(1, 0), (0, 0), (2, 2)]
    eps = Fraction(1, 3)
    assert [format_fd(d) for d in tane(rows, 2, eps)] == ["{} -> B", "B -> A"]
    assert [format_fd(d) for d in tane(rows, 2, eps, key_pruning=True)] == ["{} -> B"]


def test_against_brute_force_exact():
    rng = random.Random(20261118)
    for trial in range(300):
        k = rng.randint(1, 6)
        n = rng.randint(0, 14)
        dom = rng.randint(3, 5)
        rows = random_rows(rng, n, k, dom)
        expected = brute_minimal_fds(rows, k, lambda X, a: fd_holds(rows, X, a))
        assert tane(rows, k) == expected, (trial, rows)


def test_larger_relations():
    rng = random.Random(7)
    for trial in range(10):
        k = 6
        n = rng.choice([40, 120, 200])
        rows = random_rows(rng, n, k, 3)
        # plant two dependencies: column 4 is a function of columns 0 and 1,
        # column 5 is a function of column 2
        rows = [r[:4] + ((r[0] + 2 * r[1]) % 3, r[2] % 2) for r in rows]
        expected = brute_minimal_fds(rows, k, lambda X, a: fd_holds(rows, X, a))
        got = tane(rows, k)
        assert got == expected
        assert (frozenset([2]), 5) in as_set(got)


def test_empty_and_one_row():
    for rows in ([], [(1, 2, 3)]):
        assert tane(rows, 3) == [(frozenset(), 0), (frozenset(), 1), (frozenset(), 2)]


def test_exponential_family():
    # pairs (0, 1) and (2, 3), and the row id in column 4
    rows = [(0, 0, 0, 0, 0), (1, 1, 0, 0, 1), (0, 0, 1, 1, 2)]
    lhs_of_id = sorted(sorted(x) for x, a in tane(rows, 5) if a == 4)
    assert lhs_of_id == [[0, 2], [0, 3], [1, 2], [1, 3]]


def test_stripped_product():
    rng = random.Random(3)
    for _ in range(200):
        k = 4
        n = rng.randint(0, 20)
        rows = random_rows(rng, n, k, 3)
        X = frozenset(rng.sample(range(k), 2))
        Y = frozenset(rng.sample(range(k), 2))
        got = stripped_product(partition_of(rows, X), partition_of(rows, Y), n)
        want = partition_of(rows, X | Y)
        assert sorted(map(sorted, got)) == sorted(map(sorted, want))
        assert error_count(got) == error_count(want)


def test_g3_against_deletion():
    rng = random.Random(11)
    for _ in range(150):
        k = 3
        n = rng.randint(0, 8)
        rows = random_rows(rng, n, k, 3)
        lhs = frozenset(rng.sample(range(1, k), rng.randint(0, 2)))
        got = g3_count(partition_of(rows, lhs), partition_of(rows, lhs | {0}))
        assert got == g3_brute(rows, lhs, 0)


def test_approximate_against_brute_force():
    rng = random.Random(5)
    for trial in range(120):
        k = rng.randint(1, 5)
        n = rng.randint(0, 12)
        rows = random_rows(rng, n, k, rng.randint(3, 4))
        eps = rng.choice([Fraction(1, 10), Fraction(1, 5), Fraction(1, 3)])

        def approx(X, a):
            p, q = partition_of(rows, X), partition_of(rows, X | {a})
            return g3_count(p, q) <= eps * n

        assert tane(rows, k, eps) == brute_minimal_fds(rows, k, approx), (trial, rows, eps)

History

Mannila and Räihä studied the inference of functional dependencies from relations in the 1980s and showed that the number of minimal dependencies can be exponential in the number of attributes. Huhtala, Kärkkäinen, Porkka and Toivonen presented TANE at ICDE in 1998 and the full version in The Computer Journal in 1999. Its small-to-large search follows the levelwise search that Mannila and Toivonen described for data mining tasks, and its tests with partitions gave speed-ups of several orders of magnitude over earlier published run times on benchmark data. The 2015 study of Papenbrock et al. reimplemented TANE with six other algorithms on common data sets and compared their run times and memory use.

References

  1. Yka Huhtala, Juha Kärkkäinen, Pasi Porkka and Hannu Toivonen, TANE: an efficient algorithm for discovering functional and approximate dependencies, The Computer Journal 42(2), 1999, pages 100 to 111, Section 2 (partitions, Lemmas 2.1 and 2.2), Section 3 (the sets C+, key pruning, stripped partitions and Lemma 3.5), Section 4 (the algorithm, Lemmas 4.1 and 4.2, the stripped product and the approximate version in Section 4.6), Section 5.1 (worst case analysis, Theorem 5.1)
  2. Yka Huhtala, Juha Kärkkäinen, Pasi Porkka and Hannu Toivonen, Efficient discovery of functional and approximate dependencies using partitions, Proceedings of the 14th International Conference on Data Engineering (ICDE), 1998, pages 392 to 401, the first version of the algorithm
  3. Thorsten Papenbrock, Jens Ehrlich, Jannik Marten, Tommy Neubert, Jan-Peer Rudolph, Martin Schönberg, Jakob Zwiener and Felix Naumann, Functional dependency discovery: an experimental evaluation of seven algorithms, PVLDB 8(10), 2015, pages 1082 to 1093, the description of TANE and the measured run times and memory use of the seven algorithms

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.average
  • a full proof of time.best
  • 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