Relations: equivalences, orders and well-foundedness
Binary relations as mathematical objects and Boolean matrices: properties, transitive closure, equivalences and partitions, congruence modulo n, partial orders, linear extensions and well-founded relations. Lattices provide a foundation for fixed points and static analysis.
After this lesson you can
- Check relation properties and calculate closures with Boolean matrices
- Prove the correspondence between equivalence relations and partitions, and calculate in Z_n
- Draw and interpret Hasse diagrams, chains, antichains and linear extensions
- Prove an order well-founded, such as lexicographic order on N × N, and use it to prove termination
- Recognize lattices and complete lattices in programming examples such as fact sets and intervals
Before you start
Motivation: three questions with the same form
In almost any system you build, these three questions eventually arise:
- What order should I use? A build system has tasks depending on others; PyTorch’s backward pass must process each computation graph node after all nodes depending on it; a data pipeline cannot train before tokenizing. “ must precede ” does not order everything against everything: some tasks are independent. What we have is a partial order, and what runs is one of its linear extensions, a sequence respecting every dependency.
- When are two things the same? In chess, “1. e4 e5 2. Cf3” and “1. Cf3 e5 2. e4” reach the same position. A search engine should not evaluate the same thing twice, so it identifies move sequences ending at the same board with a transposition table (see Zobrist hashing). Identifying means defining an equivalence relation, and the object we work with is its quotient: positions, not sequences.
- Does it terminate? A loop that sometimes increases a variable without a previous bound cannot be analyzed by “this quantity decreases on every pass.” What does work is finding an order in which the state always decreases and which admits no infinite descent: a well-founded order.
A fourth appears when analyzing code: if in one branch you know and in the other , what do you know after they join? The answer, , is a supremum in a lattice, the basic operation of static analysis.
All four are the same structure, a binary relation with different properties. This lesson studies it as a mathematical object and a Boolean matrix, proves the theorems making each answer work, and converts them into code.
Binary relations: set, matrix and graph
Examples are equality, on , “divides” on (written : there is with ), “is a prefix of” between strings, “depends on” between tasks, or “there is an edge from to ” in a directed graph. A function is a special relation, , with exactly one pair per .
On a finite set , a relation has three equivalent representations, each highlighting something different:
- The set of pairs, which is the definition.
- The Boolean matrix , where if and only if . The row is the source and the column the destination.
- The directed graph with vertices and an edge for each pair. A pair is a loop.
Set operations become matrix operations. Union and intersection are entrywise logical or and and, complement negates all entries, and the inverse relation is the transpose, . The interesting operation is composition.
In matrices, if there is a with and . This is matrix multiplication with in place of addition and in place of multiplication, written :
Notice the order: with “row = source,” the first step is on the left, opposite to linear-map matrices. In particular : belongs to exactly when the graph has a length- path from to . In code, Boolean product is computed using ordinary integer multiplication and comparison > 0, because a sum of products of zeros and ones is positive exactly when some summand is 1.
The four properties that matter
Each property is visible at a glance in the matrix and graph. In the table, , is the identity, and between Boolean matrices is entrywise:
| Property | In the matrix | In the graph |
|---|---|---|
| reflexive | : the entire diagonal is 1 | a loop at each vertex |
| symmetric | every edge has its reverse | |
| antisymmetric | no edge between distinct vertices has its reverse | |
| transitive | every two-step path has a direct shortcut |
Transitivity deserves a line: marks pairs connected by a two-step path, and the condition says all were already in .
Counting relations with each property tests understanding. On a set of elements there are relations, one per way to fill the matrix. A reflexive relation has a fixed diagonal, giving . A symmetric one is determined by the diagonal and upper triangle: . For an antisymmetric one, each pair with has three configurations (neither pair, only , only ), with free diagonal: . No closed formula is known for transitivity: there are transitive relations on 3 elements and on 4, and they can be counted by enumeration only for small . You will check by brute force in the lab.
What you should have seen:
- The initial relation is antisymmetric but not transitive. The witness is without direct edge . Adding it reveals another witness, and then another: fixing transitivity by hand is tedious, which is why an algorithm exists.
- A relation both symmetric and antisymmetric must be contained in the diagonal, that is, part of equality: any off-diagonal pair breaks one of the two.
- “Same parity” and “Order ≤” are the lesson’s two models. The first is reflexive, symmetric and transitive, and its matrix, after reordering elements to group evens and odds, consists of blocks of ones. The second is reflexive, antisymmetric and transitive, and its matrix is triangular.
Closures and Warshall’s algorithm
If a relation lacks a property, naturally we add exactly the pairs necessary to make it hold.
Closure exists whenever has the property and the property is preserved by arbitrary intersections: simply intersect all relations containing and having it. Reflexivity, symmetry and transitivity satisfy both conditions, antisymmetry does not ( is not antisymmetric as soon as has two elements). The first two closures are immediate: the reflexive closure is , with the diagonal, and the symmetric closure is . The third has more substance.
Proof
is transitive and contains . The latter is the term. If and , concatenating the two paths yields .
It is the smallest. Let be transitive. Prove by induction on . For this is the hypothesis. If and , there is a with and , so and , and transitivity gives . Thus .
Paths of length at most suffice. Let and take a shortest path from to of length , with vertices . If , among the vertices two are equal by the pigeonhole principle, with , and removing the segment between them leaves a shorter path from to . Contradiction.
∎The proof already suggests an algorithm, unioning Boolean powers, costing products of each, totaling . In 1962 Stephen Warshall published a method with a different idea: instead of lengthening paths, expand the set of vertices paths are allowed to pass through.
Proof
Induct on . For no intermediate vertices are allowed, so paths are edges: . Assume the claim for and let be a path from to with intermediates in . If does not pass through as an intermediate vertex, its intermediates lie in and . Otherwise cut it at the first and last appearance of : the initial segment goes from to and the final from to , neither has as an intermediate, so . Conversely, if , concatenating the paths yields one from to adding only as an intermediate. With any vertex can be intermediate, and by the preceding theorem this is .
∎Each step is an outer product: column (who reaches ) times row (where one goes from ), unioned with what was there. In NumPy it is one line, W |= np.outer(W[:, k], W[k, :]), and a detail permits doing it in place: during step , neither row nor column changes, because . With rows stored as bits in 64-bit words, cost falls to roughly word operations.
Return to the previous figure, switch to “Warshall” and step through. With the initial relation, adds , because ; adds and , the latter via (using the newly added ); adds five pairs including and ; and and add nothing, because no edge leaves and none reaches . Going around the cycle is a path from each cycle vertex to itself. The transitive closure of a relation with cycles is not irreflexive, a detail key to well-foundedness.
Equivalence relations and partitions
An equivalence says “these objects are the same for my purposes.” Examples that recur in this course:
- Same function value. For any , the relation is an equivalence, the kernel of , and its classes are the fibers from preimages. Two move sequences are equivalent if they produce the same position; two strings if they match after lowercasing.
- Similar matrices. if for invertible : they represent the same operator in two bases. This is similarity.
- Indistinguishable words. Two words are equivalent for a language if no continuation distinguishes them; the number of classes is the number of states in the minimal automaton (the Myhill–Nerode theorem).
The first result says an equivalence and a partition are exactly the same, viewed from two sides. Recall that a partition of is a family of nonempty subsets, called blocks, pairwise disjoint and with union .
The proof is short but has a delicate point, showing two classes that touch coincide; you do it:
Step 1 of 5. Why is each class nonempty and their union ?
The theorem has a constantly useful reading: every equivalence is the kernel of a function, the canonical projection , , because . In practice, deciding equivalence means calculating a canonical representative of each object and comparing them: the final chess position, an expression’s normal form, the minimal automaton. Counting equivalences means counting partitions, the Bell numbers , studied with Stirling and Bell numbers: , , , growing faster than every exponential.
Take care defining something on classes. A function induces with if and only if is constant on each class, that is, . Otherwise “the class value” depends on the chosen representative and is not well-defined. For example, on integer classes with equal remainder modulo 4, “remainder modulo 2” is well-defined but “remainder modulo 3” is not: and lie in the same class and give remainders 1 and 2. This is the question to ask in the next section.
Congruence modulo n
This is an equivalence: gives reflexivity; if , then ; and if and , then divides their sum, . By Euclidean division every integer is with a unique , and , so there are exactly classes, . This is clock arithmetic.
What makes useful is that we can calculate in it. Addition and multiplication of classes are defined using representatives, and , and as you saw this requires checking that the result does not depend on the representatives chosen.
Proof
By a direct proof: is a sum of multiples of , and is too. Algebraic laws hold for representatives, hence for classes.
∎Not everything passes to the quotient. Powers do, since they are repeated products, but the exponent cannot be reduced modulo : modulo 3, , but and . Always check whether an operation “works modulo .”
Division: when an inverse exists
In we add, subtract and multiply. Dividing by means multiplying by an inverse of , a class with , and one need not exist: modulo 12, can only be or . The greatest common divisor gives the exact condition, and proving it requires a lemma from the well-ordering principle.
Proof
The set is nonempty (it contains or ), so by well-ordering it has a minimum . Divide: with . Then has the same form, and if positive would be in and smaller than . Hence and ; similarly . Every common divisor of and divides . Thus is the greatest common divisor.
∎Proof
- If , Bézout gives , that is, . Conversely, if , then for some , and every common divisor of and divides , so . Uniqueness: if , then .
- Consider , . Since divides and , the remainder of modulo is a multiple of ; Bézout gives with , so for every . Thus the image of is exactly the multiples of in . Also if and only if , so each attained value’s fiber is a translate of kernel , and all fibers have size . Since the fibers partition the elements of , each has . Therefore has solutions if and none otherwise.
Notice what part 2 says when : with . Multiplication by sends something other than to , so it is not injective and cannot be undone. This is visible on the clock.
What you should have seen:
- Bijective or colliding, with no middle ground. For each , either all hours receive an arrow, or each reached hour receives arrows. This is part 2: fibers of are translates of the kernel.
- With prime , every gives a permutation. Thus is a field: one can divide by every nonzero class. With composite , divisors of and their multiples spoil division.
- The inverse is visible in the diagram. With and , the arrow reaching leaves : . With , , each arrow from returns to after two applications, because : is its own inverse.
To compute inverses in practice, do not use brute force: the extended Euclidean algorithm produces Bézout coefficients in steps (you will study its invariant in gcd and Bézout). It runs downward by division and back upward by substitution; for example, for :
The permutation picture also gives a classical theorem almost for free.
Proof
Let be the set of units. The product of units is a unit (the product of their inverses is an inverse), so maps into , and is injective because is invertible. An injection from a finite set to itself is a bijection: . Multiplying all elements of both sides, , and since a product of units is invertible it can be cancelled.
∎For : the units are , multiplication by permutes them (), and . A practical consequence: , another way to calculate inverses when is known.
Partial orders
A strict order is automatically asymmetric: and would give . The versions correspond one-to-one, and , so use whichever is convenient.
Partial orders are everywhere, mostly not total:
- Inclusion on the power set : and are incomparable.
- Divisibility on : and are incomparable. On it is no longer an order: and with break antisymmetry.
- Pareto dominance on : if in every coordinate. Comparing models by (error, latency), one with less error and more latency than another is incomparable with it, and the Pareto frontier is the set of minimal elements.
- Prefix on strings, and dependencies between tasks (“ must run before ”), the reflexive and transitive closure of edges in an acyclic graph.
- The Loewner order on symmetric matrices, if is positive semidefinite, used to compare covariances (see Loewner order).
Drawing a finite order does not require drawing every pair. The minimal jumps suffice.
Proof
A chain of covers gives by transitivity. Conversely, if , among all strict chains take one of maximum length; it exists because the are distinct and is finite. If some step were not a cover, an intermediate would lengthen the chain. Thus all steps are covers.
∎The Hasse diagram is the order’s transitive reduction: the minimum to store for reconstruction. On an infinite set it may be useless: has no covers, since another rational lies between any two.
Minimal elements, least elements, chains and antichains
The least element, if it exists, is unique and the only minimal element. The converse fails: in under divisibility the minimal elements are primes and there is no least element. Minimal means “nothing lies below”; least means “lies below everything,” very different in a non-total order.
Proof
For any , is finite and nonempty. Choose there with the fewest strictly smaller elements. If , would belong to the set and have fewer elements below it than (everything below is below , as is ). Thus is minimal in and . With a unique minimal , for each , hence for every .
∎Finiteness is essential for the second part: in , with the usual order on and incomparable with everything, is the unique minimal element ( has none) but is not least.
Chains and antichains measure opposites. If elements are tasks and the order dependencies, a chain consists of tasks that must run sequentially and an antichain of tasks that may run together. Two theorems connect them.
Proof
Both share the easy inequality: a chain and an antichain share at most one element. Thus a partition into antichains needs at least as many as there are elements in the longest chain, and a partition into chains at least as many as in the largest antichain.
For Mirsky it remains to construct the partition. Define the level of as the number of elements in the longest chain ending at , minus one. If , any chain ending at extends with , so has higher level: two elements at the same level are incomparable, and each level is an antichain. Levels run from to height minus one.
The hard part of Dilworth, constructing the chain partition, follows from a maximum matching in a bipartite graph, studied with König’s theorem.
∎Mirsky directly describes scheduling: with unlimited workers, the minimum rounds to execute all tasks is the height, the length of the critical path, and levels form an optimal schedule. Dilworth says the minimum number of sequential “production lines.”
Linear extensions and topological order
Proof
Induct on . If is empty, the empty enumeration works. Otherwise has a minimal element , and with restricted order has by induction a linear extension . The enumeration is compatible: no is below , since is minimal. Conversely, the first element of any linear extension must be minimal (anything below it would come first), and what remains is a linear extension of without it.
∎The proof’s procedure is topological sort of acyclic graphs in Kahn’s version: count each element’s unplaced predecessors and remove those reaching zero, in time linear in vertices plus edges (see topological sort). In PyTorch the backward pass traverses the computation graph in reverse topological order (see the tape and its order), and every incremental build system does the same with dependencies. For infinite sets the result remains true, as Szpilrajn’s theorem (1930), but cannot be proved without some form of the axiom of choice (the weaker ultrafilter lemma suffices).
The theorem’s second half gives a recursion for counting them. If is the number of linear extensions,
A chain has and an antichain of elements has . Memoizing over the set of already placed elements, recursion visits only downward-closed sets (if an element is placed, everything below it is too), and these are as numerous as antichains: 20 for divisors of 30 instead of subsets, and 50 for divisors of 60 instead of 4096. In general the problem is hard: counting linear extensions is #P-complete (Brightwell and Winkler, 1991), and the number of downward-closed sets may be exponential.
What you should have seen:
- With the diagram is a cube, that of under inclusion: a divisor selects primes. It has linear extensions, and the first step is always , the unique minimal element.
- With the order is a chain, with one linear extension. With it is an grid, whose linear extensions are standard Young tableaux of a rectangle of that size (label each point by its position in the extension: labels increase along both grid directions), counted by the hook-length formula: for , for , for . With three primes the number shoots up: for .
- Rows in the drawing are antichains, and a chain from to touches each row once: Mirsky, with height equal to the number of prime factors of counted with multiplicity, plus one. Width is the most populated row: that no antichain exceeds the largest row is not obvious, and for divisors of any was proved by de Bruijn, Tengbergen and Kruyswijk in 1951.
- Removing a minimal element never leaves you without options. While elements remain there is at least one available minimal element: the theorem says you cannot go wrong along the way.
Well-founded relations
The well-ordering principle says every nonempty subset of has a minimum, and in the previous lesson was equivalent to induction. The property making it work does not depend on a total order or on the elements being numbers.
Proof
If such a sequence existed, would have no minimal element, because below each is . Conversely, if a nonempty has no minimal element, choose ; since it is not minimal, there is with ; since that is not minimal, there is , and so on. This construction makes infinitely many dependent choices, formally justified by dependent choice, a weak form of the axiom of choice.
∎Examples and counterexamples:
- is well-founded: the well-ordering principle. is not, by , nor is , by .
- Strict divisibility on is well-founded though not total: in a descent each term is a proper divisor of the previous, so values decrease in .
- Strict inclusion among finite sets is well-founded, since cardinality decreases. Among arbitrary subsets of it is not: .
- “Being a proper subterm” among expressions (or proper subtree among trees) is well-founded: this justifies well-founded induction and the next lesson’s structural induction.
On a finite set, well-foundedness has a characterization checkable with what you already know how to calculate.
Proof
A cycle traversed backward repeatedly is an infinite descent. Conversely, an infinite descent in a finite set repeats some element, with , and the segment between them is a cycle. A cycle goes through exactly when .
∎Lexicographic order
It is a total order. Surprisingly, has infinitely many elements below it, all , yet there are no infinite descents: from one may jump to , but from there at most descending steps remain.
Step 1 of 4. Let be the first coordinates. Why does it have a least element ?
Proving a loop terminates
The general principle fits one line: if every iteration takes state to state with , where is well-founded, the loop terminates, because an infinite execution would give infinite descent. The function is a variant or ranking function; in algorithm correctness you will use it systematically (see variant function). When is on , it is the familiar argument “this positive integer decreases.” Lexicographic order allows more.
What you should have seen:
- You cannot win. Each reset lets you pick a huge , but spends one of the remaining rows below. You can lengthen the loop arbitrarily, but not make it infinite.
- The next state always falls in the shaded region, even if it jumps far right: descending a row beats any column.
- No natural quantity fixed in advance would have sufficed. With “y ← t”, the number of steps roughly doubles on each reset, and with the adversary there is no bound. The next theorem makes this precise.
Proof
Since and takes strictly increasing natural values on that chain, for every (by induction). But for every , so for every , impossible.
∎The proof compares only pairs that are loop steps, from to and from to , so it says more: no decreases even just along possible executions. To prove termination whatever the reset rule, no measure in works: a well-founded order longer than is needed. In ordinal theory is the ordinal , and difficult termination proofs use larger ordinals. The classical example is Ackermann’s function, , and : each recursive call decreases lexicographically (in the last, the inner call decreases and the outer decreases , with a gigantic second argument), so it always terminates, although already has 19729 digits.
Multiset order
Many processes decrease not a pair but a bag of tasks: processing a task of size can generate any finite number of subtasks smaller than (a quicksort partition, a branch and bound branch, a subdividing work queue). Queue length can grow, so it cannot serve as a variant. What decreases is the bag itself, under the appropriate order.
Proof
No step introduces an element greater than the largest removed, so all have elements in , with . Associate each multiset with its count vector , where counts copies of . In a step from to , let be the largest element of . Above nothing is removed (everything removed is ) or added (everything added is smaller than some element of , hence smaller than ), and the count of decreases, because at least one copy is removed and none added. Thus in , which is well-founded by the previous exercise generalized to coordinates.
∎The bag can become (one is replaced by five smaller elements, ) and grow for a while, but eventually empties. The lab checks the count vector at every step.
Lattices
Return to the fourth motivating question. In a poset, an upper bound of and is a with and . If the upper bounds have a least one, it is the supremum of and , written (join). Similarly, the infimum (meet) is the greatest common lower bound.
Important examples:
- , with and , is a complete lattice: arbitrary unions and intersections exist. This is the data-flow analysis lattice: “set of variables that may be uninitialized,” “set of definitions that may reach this point.”
- The divisors of under divisibility, with and . This is “Sup and inf” in the Hasse diagram figure. All of is a complete lattice with a surprise: least element and greatest element , because every natural divides .
- Every total order is a lattice, with and . is complete; is not, because all of has no supremum.
- Intervals: closed with endpoints in , plus the empty set, ordered by inclusion. The infimum is intersection, but the supremum is not union, usually not an interval: it is the hull . It is a complete lattice used by abstract interpretation to bound a variable. Joining branches and gives : we lose , the price of summarizing with intervals.
Not every poset is a lattice. In under divisibility, and have no common upper bound. In with and , and nothing else, and have two incomparable minimal upper bounds, and , and no supremum.
Proof
For nonempty , bounds every above and is below any other upper bound, by induction on : if bounds all, it bounds by the induction hypothesis and , hence their supremum. For , every bound is valid and the supremum is the least element of , which exists: it is , the infimum of the whole finite set . Infima are symmetric.
∎Lattices can also be viewed as algebras: and are commutative, associative and idempotent, satisfy absorption, , and recover the order as . If also distributive and each element has a complement, they are exactly Boolean algebras.
Static analysis uses complete lattices because of Knaster–Tarski, studied next lesson as the least fixed point: every monotone function from a complete lattice to itself has a least fixed point. It is calculated by iterating from the bottom, , and well-foundedness returns: iteration stabilizes in finitely many steps if the lattice has no infinite strictly ascending chains, that is, if the reverse order is well-founded. In with finite , a strict chain has at most elements. Intervals have chains like , so interval analyzers need a widening operator to jump directly to .
Implementation from scratch: relations as Boolean matrices
We write everything in NumPy: Boolean matrices, the product, property checks and Warshall. Elements are numbered from 0 in code and 1 in text.
import numpy as np
import itertools
def bmm(P, Q):
"""Producto booleano: (P ⊙ Q)[i, j] = OR_k (P[i, k] AND Q[k, j])."""
return (P.astype(np.int64) @ Q.astype(np.int64)) > 0
def from_pairs(n, pares):
M = np.zeros((n, n), dtype=bool)
for i, j in pares:
M[i, j] = True
return M
def es_reflexiva(M): return bool(M.diagonal().all())
def es_simetrica(M): return bool((M == M.T).all())
def es_antisimetrica(M): return not (M & M.T & ~np.eye(len(M), dtype=bool)).any()
def es_transitiva(M): return not (bmm(M, M) & ~M).any()
def warshall(M):
W = M.copy()
for k in range(len(W)):
W |= np.outer(W[:, k], W[k, :]) # i -> k -> j; la fila y la columna k no cambian en este paso
return W
def clausura_por_potencias(M):
acc, P = M.copy(), M.copy()
for _ in range(len(M) - 1):
P = bmm(P, M)
acc |= P
return acc
R = from_pairs(5, [(0, 1), (1, 2), (2, 0), (2, 3), (4, 3)]) # la relación inicial de la figura
for nombre, f in [("reflexiva", es_reflexiva), ("simétrica", es_simetrica),
("antisimétrica", es_antisimetrica), ("transitiva", es_transitiva)]:
print(f"{nombre:14s}", f(R))
W = warshall(R)
print("R⁺ (Warshall):\n", W.astype(int))
print("igual que R ∪ R² ∪ ... ∪ R⁵:", np.array_equal(W, clausura_por_potencias(R)), "| transitiva:", es_transitiva(W))
rng = np.random.default_rng(0)
for _ in range(200):
n = rng.integers(2, 9)
M = rng.random((n, n)) < 0.25
assert np.array_equal(warshall(M), clausura_por_potencias(M))
print("Warshall coincide con la unión de potencias en 200 relaciones aleatorias")
# las 2^9 = 512 relaciones sobre 3 elementos, a la vez: un tensor (512, 3, 3)
n = 3
todas = ((np.arange(2 ** (n * n))[:, None] >> np.arange(n * n)) & 1).astype(bool).reshape(-1, n, n)
I = np.eye(n, dtype=bool)
refl = todas[:, I].all(axis=1)
sim = (todas == todas.transpose(0, 2, 1)).all(axis=(1, 2))
anti = ~((todas & todas.transpose(0, 2, 1)) & ~I).any(axis=(1, 2))
cuad = np.einsum("rik,rkj->rij", todas.astype(np.int64), todas.astype(np.int64)) > 0
trans = ~(cuad & ~todas).any(axis=(1, 2))
print(f"\nrelaciones sobre {n} elementos: {len(todas)}")
print(f"reflexivas {refl.sum():4d} fórmula 2^(n²−n) = {2 ** (n * n - n)}")
print(f"simétricas {sim.sum():4d} fórmula 2^(n(n+1)/2) = {2 ** (n * (n + 1) // 2)}")
print(f"antisimétricas {anti.sum():4d} fórmula 2^n · 3^(n(n−1)/2) = {2 ** n * 3 ** (n * (n - 1) // 2)}")
print(f"transitivas {trans.sum():4d} (sin fórmula cerrada conocida)")
print(f"equivalencias {(refl & sim & trans).sum():4d} órdenes parciales {(refl & anti & trans).sum()}")The final line gives equivalences on 3 elements, the partitions, and partial orders. Note the brute-force trick: instead of looping over 512 relations, build a tensor of all of them and check each property simultaneously across the batch, as with a batch of neural-network examples.
The quotient is computed with union-find. As a toy version of the motivating equivalence, consider length-6 sequences of N (north) and E (east), where two consecutive different moves can be swapped without changing the final position. That is the relation’s generator; the equivalence is its closure, which we check agrees with “same final position.”
from collections import defaultdict
class UnionFind:
def __init__(self, elementos):
self.padre = {x: x for x in elementos}
self.tam = {x: 1 for x in elementos}
def find(self, x):
raiz = x
while self.padre[raiz] != raiz:
raiz = self.padre[raiz]
while self.padre[x] != raiz: # compresión de caminos
self.padre[x], x = raiz, self.padre[x]
return raiz
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False
if self.tam[ra] < self.tam[rb]:
ra, rb = rb, ra
self.padre[rb] = ra # unión por tamaño
self.tam[ra] += self.tam[rb]
return True
def clases(self):
grupos = defaultdict(list)
for x in self.padre:
grupos[self.find(x)].append(x)
return list(grupos.values())
L = 6
secuencias = ["".join(s) for s in itertools.product("NE", repeat=L)]
uf = UnionFind(secuencias)
for s in secuencias:
for i in range(L - 1):
if s[i] != s[i + 1]: # intercambiar dos movimientos vecinos distintos
uf.union(s, s[:i] + s[i + 1] + s[i] + s[i + 2:])
clases = uf.clases()
posicion = lambda s: (s.count("E"), s.count("N"))
print(f"{len(secuencias)} secuencias de {L} movimientos, {len(clases)} clases")
print("cada clase está dentro de una fibra de 'posición final':", all(len({posicion(s) for s in c}) == 1 for c in clases))
print("y clases distintas tienen posiciones distintas:", len({posicion(c[0]) for c in clases}) == len(clases))
print("tamaños de las clases:", sorted(len(c) for c in clases), "= binomiales C(6, k)")
# la misma equivalencia con matrices: clausura transitiva de la reflexiva-simétrica
idx = {s: i for i, s in enumerate(secuencias)}
G = np.zeros((len(secuencias),) * 2, dtype=bool)
for s in secuencias:
for i in range(L - 1):
if s[i] != s[i + 1]:
G[idx[s], idx[s[:i] + s[i + 1] + s[i] + s[i + 2:]]] = True
E = warshall(G | G.T | np.eye(len(G), dtype=bool))
misma_clase = np.array([[uf.find(a) == uf.find(b) for b in secuencias] for a in secuencias])
print("union-find coincide con (R ∪ R⁻¹ ∪ Δ)⁺:", np.array_equal(E, misma_clase))
def particiones(n):
"""Cadenas de crecimiento restringido: a[0] = 0 y a[i] <= 1 + max(a[:i]). Una por partición."""
def rec(a):
if len(a) == n:
yield tuple(a)
return
for b in range(max(a) + 2):
yield from rec(a + [b])
yield from rec([0])
print("particiones de 1, 2 y 3 elementos:", [sum(1 for _ in particiones(n)) for n in (1, 2, 3)])The 64 sequences fall into 7 classes, one per final position , of sizes . Each class lying within a fiber is easy (swapping moves does not change position); each fiber being one class is the interesting claim: sequences with the same moves transform into one another through neighboring swaps, as in bubble sort. Union-find and matrix closure give the same partition, but the matrix takes entries and union-find only .
Now : extended Euclid, inverses and the theorem’s two claims, checked exhaustively for small .
from math import gcd
def euclides_extendido(a, b):
"""Devuelve (d, x, y) con d = mcd(a, b) = a·x + b·y."""
x0, x1, y0, y1 = 1, 0, 0, 1
while b:
q = a // b
a, b = b, a - q * b
x0, x1 = x1, x0 - q * x1
y0, y1 = y1, y0 - q * y1
return a, x0, y0
def inverso(a, n):
d, x, _ = euclides_extendido(a % n, n)
if d != 1:
raise ValueError(f"{a} no es invertible módulo {n}: mcd = {d}")
return x % n
print("3⁻¹ mod 10 =", inverso(3, 10), "| 11⁻¹ mod 26 =", inverso(11, 26), "| 5⁻¹ mod 12 =", inverso(5, 12))
try:
inverso(4, 12)
except ValueError as e:
print("error esperado:", e)
ok = True
for n in range(2, 60):
for a in range(n):
existe = any(a * x % n == 1 for x in range(n))
ok &= existe == (gcd(a, n) == 1)
if existe:
ok &= inverso(a, n) == pow(a, -1, n)
print("existe inverso ⇔ mcd(a, n) = 1, comprobado para n < 60:", ok)
def soluciones(a, b, n):
return [x for x in range(n) if (a * x - b) % n == 0]
print("4x ≡ 6 (mod 10):", soluciones(4, 6, 10), "| 4x ≡ 5 (mod 10):", soluciones(4, 5, 10))
ok = all(len(soluciones(a, b, n)) == (gcd(a, n) if b % gcd(a, n) == 0 else 0)
for n in range(1, 25) for a in range(n) for b in range(n))
print("a·x ≡ b tiene mcd(a, n) soluciones si mcd | b, y ninguna si no (n < 25):", ok)
ok = True
for n in range(2, 200):
unidades = [u for u in range(n) if gcd(u, n) == 1]
ok &= all(pow(a, len(unidades), n) == 1 for a in unidades)
print("Euler: a^φ(n) ≡ 1 para todo a invertible, n < 200:", ok)
x = np.array([250, 200, 17], dtype=np.uint8)
print("uint8: [250, 200, 17] + 10 =", x + np.uint8(10), " (aritmética en Z_256)")
w = 16
xs = np.arange(2 ** w, dtype=np.uint32)
for a in (40503, 40502):
imagenes = (xs * np.uint32(a)) & np.uint32(2 ** w - 1)
print(f"x -> {a}·x mod 2^{w}: {len(np.unique(imagenes))} imágenes distintas de {2 ** w}")The odd multiplier gives a permutation of the values; even collapses half, exactly elements per image.
Orders: transitive reduction (the Hasse diagram), Kahn, enumeration of linear extensions following the proof, and Mirsky levels.
def divisores(n):
return [d for d in range(1, n + 1) if n % d == 0]
def poset_divisibilidad(n):
D = divisores(n)
menor = np.array([[a != b and b % a == 0 for b in D] for a in D]) # orden estricto: menor[i, j] = D[i] < D[j]
return D, menor
def coberturas(menor):
"""Reducción transitiva: a ⋖ b si a < b y no hay c con a < c < b, es decir, < menos (< ⊙ <)."""
return menor & ~bmm(menor, menor)
def kahn(menor):
"""Orden topológico: retirar repetidamente un elemento sin predecesores pendientes."""
pendientes = menor.sum(axis=0).astype(int)
libres = [j for j in range(len(menor)) if pendientes[j] == 0]
orden = []
while libres:
i = libres.pop()
orden.append(i)
for j in np.flatnonzero(menor[i]):
pendientes[j] -= 1
if pendientes[j] == 0:
libres.append(j)
if len(orden) < len(menor):
raise ValueError("hay un ciclo: no existe orden topológico")
return orden
def extensiones_lineales(menor):
"""Todas las extensiones lineales: en cada paso, cualquier minimal de lo que queda."""
k = len(menor)
def rec(colocados, prefijo):
if len(prefijo) == k:
yield list(prefijo)
return
for i in range(k):
if i not in colocados and all(j in colocados for j in np.flatnonzero(menor[:, i])):
colocados.add(i); prefijo.append(i)
yield from rec(colocados, prefijo)
colocados.discard(i); prefijo.pop()
yield from rec(set(), [])
def niveles_mirsky(menor, orden):
nivel = np.zeros(len(menor), dtype=int)
for j in orden: # en orden topológico, los predecesores ya tienen nivel
preds = np.flatnonzero(menor[:, j])
if len(preds):
nivel[j] = nivel[preds].max() + 1
return nivel
D, menor = poset_divisibilidad(30)
print("coberturas de los divisores de 30:", [(D[i], D[j]) for i, j in zip(*np.nonzero(coberturas(menor)))])
print("una extensión lineal (Kahn):", [D[i] for i in kahn(menor)])
for n in (12, 30, 60):
D, menor = poset_divisibilidad(n)
exts = list(extensiones_lineales(menor))
assert all(p.index(i) < p.index(j) for p in exts for i, j in zip(*np.nonzero(menor)))
nivel = niveles_mirsky(menor, kahn(menor))
print(f"n = {n:2d}: {len(D):2d} divisores, {len(exts):4d} extensiones lineales, "
f"anticadenas de Mirsky {[[D[i] for i in np.flatnonzero(nivel == l)] for l in range(nivel.max() + 1)]}")The enumeration for generates the extensions one by one, checking each against every pair in the order. To count without generating them, memoize; that is an exercise.
Finally well-foundedness: the diagonal test for , the lexicographic loop with increasingly aggressive reset rules, and the multiset process with its count vector.
def bien_fundada_finita(M):
"""Una relación finita es bien fundada si y solo si su grafo no tiene ciclos: diagonal de R⁺ nula."""
return not warshall(M).diagonal().any()
N = 30
div_estricta = np.array([[a != b and b % a == 0 for b in range(1, N + 1)] for a in range(1, N + 1)])
print("divisibilidad estricta en {1..30}:", bien_fundada_finita(div_estricta))
print("la relación R, con el ciclo 1 → 2 → 3 → 1:", bien_fundada_finita(R))
def bucle(x, y, elegir):
"""El bucle de la figura. Recorre cada fila de golpe (y pasos) para poder usar y enormes."""
pasos, subidas = 0, 0
while (x, y) != (0, 0):
antes = (x, y)
if y > 0:
pasos, y = pasos + y, 0 # y pasos de y -= 1, todos dentro de la fila
else:
x, y = x - 1, elegir(x - 1, pasos)
pasos += 1
subidas += (x + y) > sum(antes)
assert (x, y) < antes # las tuplas de Python se comparan en orden lexicográfico
return pasos, subidas
for nombre, elegir in [("y ← 0", lambda x, t: 0), ("y ← 10", lambda x, t: 10),
("y ← t (pasos dados)", lambda x, t: t), ("y ← 2^t", lambda x, t: 2 ** t)]:
pasos, subidas = bucle(3, 2, elegir)
cifra = f"{pasos:d}" if pasos < 10 ** 9 else f"{pasos:.2e}"
print(f"{nombre:20s} termina en {cifra:>9s} pasos; x + y sube {subidas} veces")
def vector_cuentas(M, m):
return tuple(M.count(v) for v in range(m, -1, -1)) # (c_m, ..., c_0)
for semilla in range(3):
g = np.random.default_rng(semilla)
M = [4, 4, 3]
m, pasos, mayor = max(M), 0, len(M)
while M:
antes = vector_cuentas(M, m)
k = M.pop(int(g.integers(len(M)))) # se procesa una tarea de tamaño k...
if k > 0:
M.extend(g.integers(0, k, size=int(g.integers(0, 5))).tolist()) # ...y genera hasta 4 menores
assert vector_cuentas(M, m) < antes # baja en orden lexicográfico en N^(m+1)
pasos, mayor = pasos + 1, max(mayor, len(M))
print(f"semilla {semilla}: la bolsa [4, 4, 3] se vacía en {pasos} pasos (llegó a tener {mayor} tareas)")With “y ← 2^t” the loop takes about steps (the final reset sets ) and still terminates, and the assert confirms each segment decreases lexicographically; hence the cell traverses each row at once rather than step by step. The exact count is irrelevant: the termination proof does not depend on it.
The library version
| Tool | What it does | Watch out for |
|---|---|---|
networkx.transitive_closure(G, reflexive=False) | by traversals from each vertex | reflexive=None removes from cycles and True gives |
networkx.transitive_reduction(G) | transitive reduction (Hasse) | only for acyclic graphs |
networkx.topological_sort, all_topological_sorts | one or all linear extensions | the second is exponential |
networkx.is_directed_acyclic_graph(G) | well-foundedness of a finite relation | |
scipy.cluster.hierarchy.DisjointSet | union-find | |
pow(a, -1, n) | modular inverse (Python 3.8 or later) | raises ValueError if |
import networkx as nx
import time
from scipy.cluster.hierarchy import DisjointSet
def a_grafo(M, etiquetas=None):
G = nx.DiGraph()
et = etiquetas or list(range(len(M)))
G.add_nodes_from(et)
G.add_edges_from((et[i], et[j]) for i, j in zip(*np.nonzero(M)))
return G
G = a_grafo(R, [1, 2, 3, 4, 5])
for refl in (False, None):
TC = nx.transitive_closure(G, reflexive=refl)
iguales = np.array_equal(nx.to_numpy_array(TC, nodelist=[1, 2, 3, 4, 5], dtype=bool), warshall(R))
print(f"transitive_closure(reflexive={refl}) == warshall: {iguales}")
print("¿R es acíclica, es decir, bien fundada?", nx.is_directed_acyclic_graph(G))
D, menor = poset_divisibilidad(30)
P30 = a_grafo(menor, D)
hasse = nx.transitive_reduction(P30)
print("transitive_reduction == nuestras coberturas:",
sorted(hasse.edges()) == sorted((D[i], D[j]) for i, j in zip(*np.nonzero(coberturas(menor)))))
print("extensiones lineales de 30 con all_topological_sorts:", sum(1 for _ in nx.all_topological_sorts(P30)))
print("anticadenas de los divisores de 30, incluida la vacía:", sum(1 for _ in nx.antichains(P30)))
ds = DisjointSet(secuencias)
for s in secuencias:
for i in range(L - 1):
if s[i] != s[i + 1]:
ds.merge(s, s[:i] + s[i + 1] + s[i] + s[i + 2:])
print("scipy DisjointSet:", ds.n_subsets, "clases; mismos tamaños que nuestro union-find:",
sorted(map(len, ds.subsets())) == sorted(map(len, uf.clases())))
print("pow(3, -1, 10) =", pow(3, -1, 10), "| pow(11, -1, 26) =", pow(11, -1, 26))
g = np.random.default_rng(0)
n = 250
A = np.triu(g.random((n, n)) < 0.02, k=1) # DAG aleatorio: solo aristas i -> j con i < j
t0 = time.perf_counter(); W = warshall(A); t1 = time.perf_counter()
TC = nx.transitive_closure_dag(a_grafo(A)); t2 = time.perf_counter()
print(f"n = {n}: Warshall con NumPy {1e3 * (t1 - t0):.0f} ms, networkx {1e3 * (t2 - t1):.0f} ms, "
f"misma clausura: {np.array_equal(W, nx.to_numpy_array(TC, nodelist=range(n), dtype=bool))}")The first check demonstrates the table’s trap: with reflexive=None, networkx removes pairs arising from a cycle, so closure ceases to match . The 20 antichains of divisors of 30 are the 20 states visited by memoized linear-extension recursion. Timing depends on density: Warshall always performs well-vectorized Boolean operations, while transitive_closure_dag traverses the graph and cost grows with closure size. On this sparse graph both take tens of milliseconds, and in the browser, where NumPy has neither BLAS nor multiple threads, networkx traversal often wins. The denser the closure, the more traversal work, while Warshall’s work is unchanged.
Common mistakes
Exercises
More than one answer may be correct.
More than one answer may be correct.
count_linear_extensions(poset). The poset is a dictionary assigning each element the set of elements that must come before it (their transitive closure need only be the strict order: you may receive only direct predecessors). Return the number of linear extensions. Use recursion memoized over the set of already placed elements: enumerating permutations does not finish in time for divisors of 60, which have 12 elements.def count_linear_extensions(poset):
# poset: {x: conjunto de elementos que deben ir antes que x}
passMore than one answer may be correct.
More than one answer may be correct.
Step 1 of 3. Why can we fix at the beginning?
Summary
- Matrices: , and transitive closure comprises paths of lengths through . Warshall calculates it in by expanding permitted intermediate vertices step by step.
- Equivalences: classes and blocks coincide; every equivalence is the kernel of projection to the quotient; union-find maintains the equivalence generated by a list of pairs. On elements there are , the Bell number.
- : addition and multiplication are well-defined; is invertible if and only if , and has or solutions. Euler: for invertible .
- Orders: the Hasse diagram consists of covers; minimal is not least; height is the minimum number of antichains (Mirsky), width of chains (Dilworth). Every finite order has linear extensions (topological order), generally hard to count.
- Well-foundedness: no infinite descents; for finite sets, acyclicity. Lexicographic order on and multiset order are well-founded and prove termination where no measure in suffices.
- Lattices: supremum and infimum for each pair; in these are and , for divisors lcm and gcd, for intervals the hull and intersection. They host fixed points and static analysis.