Module contents
Lesson 6 of 22Core 105 min

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. “aa must precede bb” 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 x∈[0,5]x \in [0, 5] and in the other x∈[10,12]x \in [10, 12], what do you know after they join? The answer, x∈[0,12]x \in [0, 12], 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, ≤\le on R\R, “divides” on N\N (written a∣ba \mid b: there is k∈Nk \in \N with b=kab = ka), “is a prefix of” between strings, “depends on” between tasks, or “there is an edge from uu to vv” in a directed graph. A function f:A→Bf: A \to B is a special relation, {(a,f(a)):a∈A}\{(a, f(a)) : a \in A\}, with exactly one pair per aa.

On a finite set A={a1,…,an}A = \{a_1, \dots, a_n\}, a relation has three equivalent representations, each highlighting something different:

  1. The set of pairs, which is the definition.
  2. The Boolean matrix MR∈{0,1}n×n\mat{M}_R \in \{0, 1\}^{n \times n}, where (MR)ij=1(\mat{M}_R)_{ij} = 1 if and only if ai R aja_i \, R \, a_j. The row is the source and the column the destination.
  3. The directed graph with vertices a1,…,ana_1, \dots, a_n and an edge ai→aja_i \to a_j for each pair. A pair (ai,ai)(a_i, a_i) 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 R−1={(b,a):a R b}R^{-1} = \{(b, a) : a \, R \, b\} is the transpose, MR−1=MR⊤\mat{M}_{R^{-1}} = \mat{M}_R\T. The interesting operation is composition.

In matrices, (ai,ak)∈S∘R(a_i, a_k) \in S \circ R if there is a jj with (MR)ij=1(\mat{M}_R)_{ij} = 1 and (MS)jk=1(\mat{M}_S)_{jk} = 1. This is matrix multiplication with ∨\vee in place of addition and ∧\wedge in place of multiplication, written ⊙\odot:

MS∘R=MR⊙MS,(P⊙Q)ik=⋁j(Pij∧Qjk).\mat{M}_{S \circ R} = \mat{M}_R \odot \mat{M}_S, \qquad (\mat{P} \odot \mat{Q})_{ik} = \bigvee_{j} \big(P_{ij} \wedge Q_{jk}\big).

Notice the order: with “row = source,” the first step is on the left, opposite to linear-map matrices. In particular MRk=MR⊙k\mat{M}_{R^k} = \mat{M}_R^{\odot k}: (ai,aj)(a_i, a_j) belongs to RkR^k exactly when the graph has a length-kk path from aia_i to aja_j. 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, M=MR\mat{M} = \mat{M}_R, I\mat{I} is the identity, and ≤\le between Boolean matrices is entrywise:

PropertyIn the matrixIn the graph
reflexiveI≤M\mat{I} \le \mat{M}: the entire diagonal is 1a loop at each vertex
symmetricM=M⊤\mat{M} = \mat{M}\Tevery edge has its reverse
antisymmetricM∧M⊤≤I\mat{M} \wedge \mat{M}\T \le \mat{I}no edge between distinct vertices has its reverse
transitiveM⊙M≤M\mat{M} \odot \mat{M} \le \mat{M}every two-step path has a direct shortcut

Transitivity deserves a line: M⊙M=MR2\mat{M} \odot \mat{M} = \mat{M}_{R^2} marks pairs connected by a two-step path, and the condition says all were already in RR.

Counting relations with each property tests understanding. On a set of nn elements there are 2n22^{n^2} relations, one per way to fill the matrix. A reflexive relation has a fixed diagonal, giving 2n2−n2^{n^2 - n}. A symmetric one is determined by the diagonal and upper triangle: 2n(n+1)/22^{n(n+1)/2}. For an antisymmetric one, each pair {i,j}\{i, j\} with i≠ji \ne j has three configurations (neither pair, only (i,j)(i, j), only (j,i)(j, i)), with free diagonal: 2n⋅3n(n−1)/22^n \cdot 3^{n(n-1)/2}. No closed formula is known for transitivity: there are 171171 transitive relations on 3 elements and 39943994 on 4, and they can be counted by enumeration only for small nn. You will check by brute force in the lab.

InteractiveA relation's matrix and closure
destination jsource i1234512345010000010010010000000001012345
  • pair in RR
  • added by the last closure
  • witness
  • missing pair
Mode
5
Pairs in the relation5 of 25
Not transitive: 1 R 21\,R\,2 and 2 R 32\,R\,3, but (1,3)(1, 3) is missing.
Click matrix cells to add or remove pairs; the relation graph updates too. Each property says yes or no; click it to highlight its witness, the pair or triple that breaks it (orange for what exists, dashed red for what is missing). Find a relation both symmetric and antisymmetric that is nonempty. The Warshall mode and closure buttons are used in the next section.

What you should have seen:

  • The initial relation is antisymmetric but not transitive. The witness is 1→2→31 \to 2 \to 3 without direct edge 1→31 \to 3. 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 A×AA \times A has the property and the property is preserved by arbitrary intersections: simply intersect all relations containing RR and having it. Reflexivity, symmetry and transitivity satisfy both conditions, antisymmetry does not (A×AA \times A is not antisymmetric as soon as AA has two elements). The first two closures are immediate: the reflexive closure is R∪ΔAR \cup \Delta_A, with ΔA={(a,a):a∈A}\Delta_A = \{(a, a) : a \in A\} the diagonal, and the symmetric closure is R∪R−1R \cup R^{-1}. The third has more substance.

Proof

R+R^+ is transitive and contains RR. The latter is the k=1k = 1 term. If a Ri ba \, R^i \, b and b Rj cb \, R^j \, c, concatenating the two paths yields a Ri+j ca \, R^{i+j} \, c.

It is the smallest. Let T⊇RT \supseteq R be transitive. Prove Rk⊆TR^k \subseteq T by induction on k≥1k \ge 1. For k=1k = 1 this is the hypothesis. If Rk⊆TR^k \subseteq T and a Rk+1 ca \, R^{k+1} \, c, there is a bb with a Rk ba \, R^k \, b and b R cb \, R \, c, so a T ba \, T \, b and b T cb \, T \, c, and transitivity gives a T ca \, T \, c. Thus R+⊆TR^+ \subseteq T.

Paths of length at most nn suffice. Let a R+ ca \, R^+ \, c and take a shortest path from aa to cc of length kk, with vertices a=v0,v1,…,vk=ca = v_0, v_1, \dots, v_k = c. If k>nk > n, among the k≥n+1k \ge n + 1 vertices v1,…,vkv_1, \dots, v_k two are equal by the pigeonhole principle, vi=vjv_i = v_j with 1≤i<j≤k1 \le i < j \le k, and removing the segment between them leaves a shorter path from aa to cc. Contradiction.

∎

The proof already suggests an algorithm, unioning nn Boolean powers, costing n−1n - 1 products of n3n^3 each, totaling O(n4)\bigO(n^4). In 1962 Stephen Warshall published a O(n3)\bigO(n^3) method with a different idea: instead of lengthening paths, expand the set of vertices paths are allowed to pass through.

Proof

Induct on kk. For k=0k = 0 no intermediate vertices are allowed, so paths are edges: W0=MR\mat{W}_0 = \mat{M}_R. Assume the claim for k−1k - 1 and let π\pi be a path from ii to jj with intermediates in {1,…,k}\{1, \dots, k\}. If π\pi does not pass through kk as an intermediate vertex, its intermediates lie in {1,…,k−1}\{1, \dots, k-1\} and (Wk−1)ij=1(\mat{W}_{k-1})_{ij} = 1. Otherwise cut it at the first and last appearance of kk: the initial segment goes from ii to kk and the final from kk to jj, neither has kk as an intermediate, so (Wk−1)ik=(Wk−1)kj=1(\mat{W}_{k-1})_{ik} = (\mat{W}_{k-1})_{kj} = 1. Conversely, if (Wk−1)ik=(Wk−1)kj=1(\mat{W}_{k-1})_{ik} = (\mat{W}_{k-1})_{kj} = 1, concatenating the paths yields one from ii to jj adding only kk as an intermediate. With k=nk = n any vertex can be intermediate, and by the preceding theorem this is R+R^+.

∎

Each step kk is an outer product: column kk (who reaches kk) times row kk (where one goes from kk), 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 kk, neither row nor column kk changes, because Wik∨(Wik∧Wkk)=WikW_{ik} \vee (W_{ik} \wedge W_{kk}) = W_{ik}. With rows stored as bits in 64-bit words, cost falls to roughly n3/64n^3 / 64 word operations.

Return to the previous figure, switch to “Warshall” and step through. With the initial relation, k=1k = 1 adds (3,2)(3, 2), because 3→1→23 \to 1 \to 2; k=2k = 2 adds (1,3)(1, 3) and (3,3)(3, 3), the latter via 3→2→33 \to 2 \to 3 (using the newly added (3,2)(3, 2)); k=3k = 3 adds five pairs including (1,1)(1, 1) and (2,2)(2, 2); and k=4k = 4 and k=5k = 5 add nothing, because no edge leaves 44 and none reaches 55. Going around the cycle 1→2→3→11 \to 2 \to 3 \to 1 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 f:A→Bf: A \to B, the relation a∼fb  ⟺  f(a)=f(b)a \sim_f b \iff f(a) = f(b) is an equivalence, the kernel of ff, and its classes are the fibers f−1({y})f^{-1}(\{y\}) from preimages. Two move sequences are equivalent if they produce the same position; two strings if they match after lowercasing.
  • Similar matrices. A∼B\mat{A} \sim \mat{B} if B=P−1AP\mat{B} = \mat{P}\inv\mat{A}\mat{P} for invertible P\mat{P}: 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 AA is a family of nonempty subsets, called blocks, pairwise disjoint and with union AA.

The proof is short but has a delicate point, showing two classes that touch coincide; you do it:

ProofClasses and blocks
Prove: Classes of an equivalence ∼\sim on AA partition AA, and every partition Π\Pi of AA induces an equivalence ∼Π\sim_\Pi whose classes are its blocks.
0
Show classes are nonempty, cover AA, and distinct classes are disjoint; then construct the converse.

Step 1 of 5. Why is each class nonempty and their union AA?

The theorem has a constantly useful reading: every equivalence is the kernel of a function, the canonical projection π:A→A/∼\pi: A \to A/{\sim}, a↦[a]a \mapsto [a], because a∼b  ⟺  [a]=[b]a \sim b \iff [a] = [b]. 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 BnB_n, studied with Stirling and Bell numbers: B1=1B_1 = 1, B2=2B_2 = 2, B3=5B_3 = 5, growing faster than every exponential.

Take care defining something on classes. A function g:A→Bg: A \to B induces gˉ:A/∼→B\bar{g}: A/{\sim} \to B with gˉ([a])=g(a)\bar{g}([a]) = g(a) if and only if gg is constant on each class, that is, a∼b⇒g(a)=g(b)a \sim b \Rightarrow g(a) = g(b). Otherwise “the class value” depends on the chosen representative and gˉ\bar{g} 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: 11 and 55 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: n∣0n \mid 0 gives reflexivity; if n∣(a−b)n \mid (a - b), then n∣(b−a)n \mid (b - a); and if n∣(a−b)n \mid (a - b) and n∣(b−c)n \mid (b - c), then nn divides their sum, a−ca - c. By Euclidean division every integer is a=qn+ra = qn + r with a unique r∈{0,…,n−1}r \in \{0, \dots, n - 1\}, and a≡ra \equiv r, so there are exactly nn classes, Zn={[0],[1],…,[n−1]}\Z_n = \{[0], [1], \dots, [n-1]\}. This is clock arithmetic.

What makes Zn\Z_n useful is that we can calculate in it. Addition and multiplication of classes are defined using representatives, [a]+[b]=[a+b][a] + [b] = [a + b] and [a]⋅[b]=[ab][a] \cdot [b] = [ab], and as you saw this requires checking that the result does not depend on the representatives chosen.

Proof

By a direct proof: (a+b)−(a′+b′)=(a−a′)+(b−b′)(a + b) - (a' + b') = (a - a') + (b - b') is a sum of multiples of nn, and ab−a′b′=a(b−b′)+b′(a−a′)ab - a'b' = a(b - b') + b'(a - a') 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 nn: modulo 3, 1≡41 \equiv 4, but 21=22^1 = 2 and 24=16≡12^4 = 16 \equiv 1. Always check whether an operation “works modulo nn.”

Division: when an inverse exists

In Zn\Z_n we add, subtract and multiply. Dividing by aa means multiplying by an inverse of aa, a class xx with ax≡1ax \equiv 1, and one need not exist: modulo 12, 4x4x can only be 0,40, 4 or 88. The greatest common divisor gives the exact condition, and proving it requires a lemma from the well-ordering principle.

Proof

The set S={ax+ny:x,y∈Z}∩{1,2,3,… }S = \{ax + ny : x, y \in \Z\} \cap \{1, 2, 3, \dots\} is nonempty (it contains ∣a∣\abs{a} or ∣n∣\abs{n}), so by well-ordering it has a minimum d=ax0+ny0d = ax_0 + ny_0. Divide: a=qd+ra = qd + r with 0≤r<d0 \le r < d. Then r=a−q(ax0+ny0)=a(1−qx0)+n(−qy0)r = a - q(ax_0 + ny_0) = a(1 - qx_0) + n(-qy_0) has the same form, and if positive would be in SS and smaller than dd. Hence r=0r = 0 and d∣ad \mid a; similarly d∣nd \mid n. Every common divisor of aa and nn divides ax0+ny0=dax_0 + ny_0 = d. Thus dd is the greatest common divisor.

∎
Proof
  1. If d=1d = 1, Bézout gives ax0+ny0=1ax_0 + ny_0 = 1, that is, ax0≡1ax_0 \equiv 1. Conversely, if ax≡1ax \equiv 1, then ax−1=nyax - 1 = ny for some yy, and every common divisor of aa and nn divides ax−ny=1ax - ny = 1, so d=1d = 1. Uniqueness: if ax≡ax′≡1ax \equiv ax' \equiv 1, then x≡x(ax′)=(xa)x′≡x′x \equiv x(ax') = (xa)x' \equiv x'.
  2. Consider ma:Zn→Znm_a: \Z_n \to \Z_n, x↦axx \mapsto ax. Since dd divides aa and nn, the remainder of axax modulo nn is a multiple of dd; Bézout gives x0x_0 with ax0≡dax_0 \equiv d, so a(tx0)≡tda(tx_0) \equiv td for every tt. Thus the image of mam_a is exactly the n/dn/d multiples of dd in Zn\Z_n. Also ma(x)=ma(x′)m_a(x) = m_a(x') if and only if ma(x−x′)=0m_a(x - x') = 0, so each attained value’s fiber is a translate x+Kx + K of kernel K={x:ax≡0}K = \{x : ax \equiv 0\}, and all fibers have size ∣K∣\abs{K}. Since the n/dn/d fibers partition the nn elements of Zn\Z_n, each has dd. Therefore ax≡bax \equiv b has dd solutions if d∣bd \mid b and none otherwise.
∎

Notice what part 2 says when d>1d > 1: a⋅(n/d)=(a/d)⋅n≡0a \cdot (n/d) = (a/d) \cdot n \equiv 0 with n/d≢0n/d \not\equiv 0. Multiplication by aa sends something other than 00 to 00, so it is not injective and cannot be undone. This is visible on the clock.

InteractiveMultiplying on a clock
0123456789× 3 (mod 10)
x3x00132639425568718497
  • one color per permutation cycle
  • the inverse a−1a^{-1} (its arrow points to 1)
4 cycles: (0)(1  3  9  7)(2  6  8  4)(5)\text{4 cycles: } (0)(1\;3\;9\;7)(2\;6\;8\;4)(5)
10
3
gcd⁡(a,n)\gcd(a, n)1
Is x↦axx \mapsto ax bijective?yes
a−1 mod na^{-1} \bmod n7
Hours reached10 of 10
gcd⁡(3,10)=1\gcd(3, 10) = 1: each hour receives exactly one arrow, so x↦3xx \mapsto 3x is a permutation of Z10\Z_{10} and can be reversed. The inverse is the hour whose arrow points to 11: 3⋅7=21≡13 \cdot 7 = 21 \equiv 1. The colors represent the cycles of the permutation.
The nn hours are Zn\Z_n; each arrow goes from xx to ax mod na x \bmod n, and the lower strip shows the same function in two-line notation. With gcd⁡(a,n)=1\gcd(a, n) = 1 each hour receives exactly one arrow: a permutation colored by cycles, and the inverse is the highlighted hour that maps to 1. Try a=4a = 4 with n=12n = 12: arrows collide four at a time, only 00, 44 and 88 are reached, and the other nine hours receive none. Enable ‘Solve ax≡ba x \equiv b’ and check that the number of solutions can only be 00 or gcd⁡(a,n)\gcd(a, n).

What you should have seen:

  • Bijective or colliding, with no middle ground. For each aa, either all hours receive an arrow, or each reached hour receives d=gcd⁡(a,n)d = \gcd(a, n) arrows. This is part 2: fibers of mam_a are translates of the kernel.
  • With prime nn, every a≠0a \ne 0 gives a permutation. Thus Zp\Z_p is a field: one can divide by every nonzero class. With composite nn, divisors of nn and their multiples spoil division.
  • The inverse is visible in the diagram. With n=10n = 10 and a=3a = 3, the arrow reaching 11 leaves 77: 3⋅7=21≡13 \cdot 7 = 21 \equiv 1. With n=12n = 12, a=5a = 5, each arrow from xx returns to xx after two applications, because 5⋅5=25≡15 \cdot 5 = 25 \equiv 1: 55 is its own inverse.

To compute inverses in practice, do not use brute force: the extended Euclidean algorithm produces Bézout coefficients in O(log⁡n)\bigO(\log n) steps (you will study its invariant in gcd and Bézout). It runs downward by division and back upward by substitution; for example, for 11−1 mod 2611^{-1} \bmod 26:

26=2⋅11+411=2⋅4+34=1⋅3+1\begin{aligned} 26 &= 2 \cdot 11 + 4 \\ 11 &= 2 \cdot 4 + 3 \\ 4 &= 1 \cdot 3 + 1 \end{aligned}
Euclid: the last nonzero remainder is gcd⁡(11,26)=1\gcd(11, 26) = 1, so an inverse exists.
1/5

The permutation picture also gives a classical theorem almost for free.

Proof

Let U={u1,…,uφ(n)}U = \{u_1, \dots, u_{\varphi(n)}\} be the set of units. The product of units is a unit (the product of their inverses is an inverse), so mam_a maps UU into UU, and is injective because aa is invertible. An injection from a finite set to itself is a bijection: {au1,…,auφ(n)}=U\{au_1, \dots, au_{\varphi(n)}\} = U. Multiplying all elements of both sides, aφ(n)∏iui≡∏iuia^{\varphi(n)} \prod_i u_i \equiv \prod_i u_i, and since a product of units is invertible it can be cancelled.

∎

For n=10n = 10: the units are 1,3,7,91, 3, 7, 9, multiplication by 33 permutes them (3,9,1,73, 9, 1, 7), and 34=81≡13^4 = 81 \equiv 1. A practical consequence: a−1≡aφ(n)−1a^{-1} \equiv a^{\varphi(n) - 1}, another way to calculate inverses when φ(n)\varphi(n) is known.

Partial orders

A strict order is automatically asymmetric: a≺ba \prec b and b≺ab \prec a would give a≺aa \prec a. The versions correspond one-to-one, a≺b  ⟺  (a⪯b and a≠b)a \prec b \iff (a \preceq b \text{ and } a \ne b) and a⪯b  ⟺  (a≺b or a=b)a \preceq b \iff (a \prec b \text{ or } a = b), so use whichever is convenient.

Partial orders are everywhere, mostly not total:

  • Inclusion on the power set P(S)\mathcal{P}(S): {1}\{1\} and {2}\{2\} are incomparable.
  • Divisibility on N\N: 44 and 66 are incomparable. On Z\Z it is no longer an order: 2∣−22 \mid -2 and −2∣2-2 \mid 2 with 2≠−22 \ne -2 break antisymmetry.
  • Pareto dominance on Rd\R^d: x⪯y\vb{x} \preceq \vb{y} if xi≤yix_i \le y_i 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 (“aa must run before bb”), the reflexive and transitive closure of edges in an acyclic graph.
  • The Loewner order on symmetric matrices, A⪯B\mat{A} \preceq \mat{B} if B−A\mat{B} - \mat{A} 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 a≺ba \prec b by transitivity. Conversely, if a≺ba \prec b, among all strict chains a=c0≺c1≺⋯≺cm=ba = c_0 \prec c_1 \prec \dots \prec c_m = b take one of maximum length; it exists because the cic_i are distinct and PP is finite. If some step ci≺ci+1c_i \prec c_{i+1} were not a cover, an intermediate cc 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: (Q,≤)(\Q, \le) 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 {2,3,…,12}\{2, 3, \dots, 12\} under divisibility the minimal elements are primes 2,3,5,7,112, 3, 5, 7, 11 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 xx, {y:y⪯x}\{y : y \preceq x\} is finite and nonempty. Choose m′m' there with the fewest strictly smaller elements. If z≺m′z \prec m', zz would belong to the set and have fewer elements below it than m′m' (everything below zz is below m′m', as is zz). Thus m′m' is minimal in PP and m′⪯xm' \preceq x. With a unique minimal mm, m′=mm' = m for each xx, hence m⪯xm \preceq x for every xx.

∎

Finiteness is essential for the second part: in Z∪{⋆}\Z \cup \{\star\}, with the usual order on Z\Z and ⋆\star incomparable with everything, ⋆\star is the unique minimal element (Z\Z 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 xx as the number of elements in the longest chain ending at xx, minus one. If x≺yx \prec y, any chain ending at xx extends with yy, so yy has higher level: two elements at the same level are incomparable, and each level is an antichain. Levels run from 00 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 ∣P∣\abs{P}. If PP is empty, the empty enumeration works. Otherwise PP has a minimal element mm, and P∖{m}P \setminus \{m\} with restricted order has by induction a linear extension q1,…,qn−1q_1, \dots, q_{n-1}. The enumeration m,q1,…,qn−1m, q_1, \dots, q_{n-1} is compatible: no qiq_i is below mm, since mm 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 PP 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 e(P)e(P) is the number of linear extensions,

e(P)=∑m minimal in Pe(P∖{m}),e(∅)=1.e(P) = \sum_{m \text{ minimal in } P} e(P \setminus \{m\}), \qquad e(\varnothing) = 1.

A chain has e=1e = 1 and an antichain of nn elements has e=n!e = n!. 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 28=2562^8 = 256 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.

InteractiveHasse diagrams and linear extensions
30=2⋅3⋅530 = 2 \cdot 3 \cdot 5
1123256101530
Your row:1<3
  • available minimal element
  • already placed (with position)
30
Mode
Divisors of nn8
Linear extensions e(P)e(P)48
Compatible with your prefix16
Available minimal elements2
You have fixed 2 of 8. The 16 ways to finish are distributed as follows: 22 → 8, 55 → 8.
The divisors of nn ordered by divisibility, in rows by number of prime factors counted with multiplicity. In ‘Extension’, click a highlighted element (a minimal element of what remains) to place it next; the counter shows how many extensions match your prefix and how they split among the choices. ‘Complete at random’ chooses with probability proportional to those counts, producing a uniform extension. ‘Chains’ shows height and width, and ‘Sup and inf’ the gcd and lcm of two elements, used when discussing lattices. Try n=30n = 30, 6060, 6464 and 9696.

What you should have seen:

  • With n=30=2⋅3⋅5n = 30 = 2 \cdot 3 \cdot 5 the diagram is a cube, that of P({2,3,5})\mathcal{P}(\{2, 3, 5\}) under inclusion: a divisor selects primes. It has 4848 linear extensions, and the first step is always 11, the unique minimal element.
  • With n=2kn = 2^k the order is a chain, with one linear extension. With n=paqbn = p^a q^b it is an (a+1)×(b+1)(a + 1) \times (b + 1) 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: 55 for 12=22⋅312 = 2^2 \cdot 3, 1414 for 2424, 4242 for 3636. With three primes the number shoots up: 24522452 for 6060.
  • Rows in the drawing are antichains, and a chain from 11 to nn touches each row once: Mirsky, with height equal to the number of prime factors of nn 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 nn 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 N\N 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, {a0,a1,… }\{a_0, a_1, \dots\} would have no minimal element, because below each aia_i is ai+1a_{i+1}. Conversely, if a nonempty SS has no minimal element, choose a0∈Sa_0 \in S; since it is not minimal, there is a1∈Sa_1 \in S with a1 R a0a_1 \, R \, a_0; since that is not minimal, there is a2a_2, 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:

  • (N,<)(\N, <) is well-founded: the well-ordering principle. (Z,<)(\Z, <) is not, by 0>−1>−2>⋯0 > -1 > -2 > \cdots, nor is (Q≥0,<)(\Q_{\ge 0}, <), by 1>12>13>⋯1 > \tfrac12 > \tfrac13 > \cdots.
  • Strict divisibility on {1,2,3,… }\{1, 2, 3, \dots\} is well-founded though not total: in a descent a0,a1,…a_0, a_1, \dots each term is a proper divisor of the previous, so values decrease in N\N.
  • Strict inclusion among finite sets is well-founded, since cardinality decreases. Among arbitrary subsets of N\N it is not: N⊋N∖{0}⊋N∖{0,1}⊋⋯\N \supsetneq \N \setminus \{0\} \supsetneq \N \setminus \{0, 1\} \supsetneq \cdots.
  • “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 a R b R ⋯ R aa \, R \, b \, R \, \cdots \, R \, a traversed backward repeatedly is an infinite descent. Conversely, an infinite descent in a finite set repeats some element, ai=aja_i = a_j with i<ji < j, and the segment between them is a cycle. A cycle goes through aa exactly when a R+ aa \, R^+ \, a.

∎

Lexicographic order

It is a total order. Surprisingly, (1,0)(1, 0) has infinitely many elements below it, all (0,k)(0, k), yet there are no infinite descents: from (1,0)(1, 0) one may jump to (0,10100)(0, 10^{100}), but from there at most 1010010^{100} descending steps remain.

ProofLexicographic order is well-founded
Prove: Every nonempty subset S⊆N×NS \subseteq \N \times \N has a least element for <lex<_{\text{lex}}. Consequently (N×N,<lex)(\N \times \N, <_{\text{lex}}) has no infinite strictly descending sequences.
0
Let S≠∅S \ne \varnothing. Seek the minimum coordinate by coordinate in the order used by <lex<_{\text{lex}}.

Step 1 of 4. Let A={a:(a,b)∈S for some b}A = \{a : (a, b) \in S \text{ for some } b\} be the first coordinates. Why does it have a least element a∗a^*?

Proving a loop terminates

The general principle fits one line: if every iteration takes state ss to state s′s' with f(s′)≺f(s)f(s') \prec f(s), where ≺\prec is well-founded, the loop terminates, because an infinite execution would give infinite descent. The function ff is a variant or ranking function; in algorithm correctness you will use it systematically (see variant function). When ≺\prec is << on N\N, it is the familiar argument “this positive integer decreases.” Lexicographic order allows more.

InteractiveTermination by lexicographic order
while (x, y) != (0, 0): if y > 0: y -= 1 else: x -= 1; y = elegir()
x=0x=1x=2x=30123456789101112y →
x+yx + y through the loop: it increases on resets
014t →
  • pairs smaller than the current one
  • reset: xx decreases, yy jumps
  • x+yx + y increases
Who chooses the new yy?
3
2
12
Step tt4
State (x,y)(x, y)(2, 11)
x+yx + y13
Increases in x+yx + y1
Does the pair decrease at every step?yes, always
11 steps remain in this row and at most 2 resets. Each reset can extend the loop as much as you like, but cannot prevent it from ending.
The pair (x,y)(x, y) is drawn with xx in rows and yy in columns, so lexicographic order reads bottom to top and left to right. The shaded region contains pairs smaller than the current one. With ‘You’, you are the adversary: whenever yy reaches 0, choose a new yy with the slider, as large as you wish, and try to prevent termination. With ‘Random’ or ‘y ← t’ the program chooses it. Below is x+yx + y: it rises on each reset, so it is not a progress measure; the pair, however, decreases on every step.

What you should have seen:

  • You cannot win. Each reset lets you pick a huge yy, but spends one of the xx 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 (0,0)<lex(0,1)<lex(0,2)<lex⋯(0, 0) <_{\text{lex}} (0, 1) <_{\text{lex}} (0, 2) <_{\text{lex}} \cdots and ff takes strictly increasing natural values on that chain, f(0,k)≥kf(0, k) \ge k for every kk (by induction). But (0,k)<lex(1,0)(0, k) <_{\text{lex}} (1, 0) for every kk, so f(1,0)>kf(1, 0) > k for every k∈Nk \in \N, impossible.

∎

The proof compares only pairs that are loop steps, from (0,k+1)(0, k + 1) to (0,k)(0, k) and from (1,0)(1, 0) to (0,k)(0, k), so it says more: no f:N×N→Nf: \N \times \N \to \N decreases even just along possible executions. To prove termination whatever the reset rule, no measure in N\N works: a well-founded order longer than N\N is needed. In ordinal theory (N×N,<lex)(\N \times \N, <_{\text{lex}}) is the ordinal ω2\omega^2, and difficult termination proofs use larger ordinals. The classical example is Ackermann’s function, A(0,n)=n+1A(0, n) = n + 1, A(m+1,0)=A(m,1)A(m + 1, 0) = A(m, 1) and A(m+1,n+1)=A(m,A(m+1,n))A(m + 1, n + 1) = A(m, A(m + 1, n)): each recursive call decreases (m,n)(m, n) lexicographically (in the last, the inner call decreases nn and the outer decreases mm, with a gigantic second argument), so it always terminates, although A(4,2)=265536−3A(4, 2) = 2^{65536} - 3 already has 19729 digits.

Multiset order

Many processes decrease not a pair but a bag of tasks: processing a task of size kk can generate any finite number of subtasks smaller than kk (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 MiM_i have elements in {0,…,m}\{0, \dots, m\}, with m=max⁡M0m = \max M_0. Associate each multiset with its count vector c(M)=(cm,cm−1,…,c0)∈Nm+1c(M) = (c_m, c_{m-1}, \dots, c_0) \in \N^{m+1}, where cvc_v counts copies of vv. In a step from MM to NN, let xx be the largest element of XX. Above xx nothing is removed (everything removed is ≤x\le x) or added (everything added is smaller than some element of XX, hence smaller than xx), and the count of xx decreases, because at least one copy is removed and none added. Thus c(N)<lexc(M)c(N) <_{\text{lex}} c(M) in Nm+1\N^{m+1}, which is well-founded by the previous exercise generalized to kk coordinates.

∎

The bag {4,4,3}\{4, 4, 3\} can become {4,3,3,3,2,2,0}\{4, 3, 3, 3, 2, 2, 0\} (one 44 is replaced by five smaller elements, 3,3,2,2,03, 3, 2, 2, 0) 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 aa and bb is a uu with a⪯ua \preceq u and b⪯ub \preceq u. If the upper bounds have a least one, it is the supremum of aa and bb, written a∨ba \vee b (join). Similarly, the infimum a∧ba \wedge b (meet) is the greatest common lower bound.

Important examples:

  • (P(S),⊆)(\mathcal{P}(S), \subseteq), with ∨=∪\vee = \cup and ∧=∩\wedge = \cap, 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 nn under divisibility, with a∨b=lcm⁡(a,b)a \vee b = \operatorname{lcm}(a, b) and a∧b=gcd⁡(a,b)a \wedge b = \gcd(a, b). This is “Sup and inf” in the Hasse diagram figure. All of (N,∣)(\N, \mid) is a complete lattice with a surprise: least element 11 and greatest element 00, because every natural divides 00.
  • Every total order is a lattice, with max⁡\max and min⁡\min. ([0,1],≤)([0, 1], \le) is complete; (R,≤)(\R, \le) is not, because all of R\R has no supremum.
  • Intervals: closed [a,b][a, b] with endpoints in R∪{±∞}\R \cup \{\pm\infty\}, 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 [a,b]∨[c,d]=[min⁡(a,c),max⁡(b,d)][a, b] \vee [c, d] = [\min(a, c), \max(b, d)]. It is a complete lattice used by abstract interpretation to bound a variable. Joining branches x∈[0,5]x \in [0, 5] and x∈[10,12]x \in [10, 12] gives x∈[0,12]x \in [0, 12]: we lose x≠7x \ne 7, the price of summarizing with intervals.

Not every poset is a lattice. In {1,2,3}\{1, 2, 3\} under divisibility, 22 and 33 have no common upper bound. In {a,b,c,d}\{a, b, c, d\} with a,b≺ca, b \prec c and a,b≺da, b \prec d, and nothing else, aa and bb have two incomparable minimal upper bounds, cc and dd, and no supremum.

Proof

For nonempty S={s1,…,sk}S = \{s_1, \dots, s_k\}, s1∨(s2∨(⋯∨sk))s_1 \vee (s_2 \vee (\cdots \vee s_k)) bounds every sis_i above and is below any other upper bound, by induction on kk: if uu bounds all, it bounds s2∨⋯∨sks_2 \vee \cdots \vee s_k by the induction hypothesis and s1s_1, hence their supremum. For S=∅S = \varnothing, every bound is valid and the supremum is the least element of LL, which exists: it is ⋀L\bigwedge L, the infimum of the whole finite set LL. Infima are symmetric.

∎

Lattices can also be viewed as algebras: ∨\vee and ∧\wedge are commutative, associative and idempotent, satisfy absorption, a∨(a∧b)=aa \vee (a \wedge b) = a, and recover the order as a⪯b  ⟺  a∨b=ba \preceq b \iff a \vee b = b. 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 FF from a complete lattice to itself has a least fixed point. It is calculated by iterating from the bottom, ⊥⪯F(⊥)⪯F(F(⊥))⪯⋯\bot \preceq F(\bot) \preceq F(F(\bot)) \preceq \cdots, 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 P(S)\mathcal{P}(S) with finite SS, a strict chain has at most ∣S∣+1\abs{S} + 1 elements. Intervals have chains like [0,0]⊊[0,1]⊊[0,2]⊊⋯[0, 0] \subsetneq [0, 1] \subsetneq [0, 2] \subsetneq \cdots, so interval analyzers need a widening operator to jump directly to [0,+∞][0, +\infty].

Implementation from scratch: relations as Boolean matrices

We write everything in NumPy: Boolean matrices, the ⊙\odot product, property checks and Warshall. Elements are numbered from 0 in code and 1 in text.

[ ]Properties, Warshall closure and brute forceBrowser
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 55 equivalences on 3 elements, the B3=5B_3 = 5 partitions, and 1919 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.”

[ ]Quotient with union-findBrowser
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 (k,6−k)(k, 6 - k), of sizes (6k)\binom{6}{k}. 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 64264^2 entries and union-find only 6464.

Now Zn\Z_n: extended Euclid, inverses and the theorem’s two claims, checked exhaustively for small nn.

[ ]Modular arithmeticBrowser
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 4050340503 gives a permutation of the 2162^{16} values; even 40502=2⋅2025140502 = 2 \cdot 20251 collapses half, exactly gcd⁡(40502,216)=2\gcd(40502, 2^{16}) = 2 elements per image.

Orders: transitive reduction (the Hasse diagram), Kahn, enumeration of linear extensions following the proof, and Mirsky levels.

[ ]Hasse, topological order and linear extensionsBrowser
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 6060 generates the 24522452 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 R+R^+, the lexicographic loop with increasingly aggressive reset rules, and the multiset process with its count vector.

[ ]Well-foundedness and terminationBrowser
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 8.7⋅10408.7 \cdot 10^{40} steps (the final reset sets y=2136y = 2^{136}) 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

ToolWhat it doesWatch out for
networkx.transitive_closure(G, reflexive=False)R+R^+ by traversals from each vertexreflexive=None removes (a,a)(a, a) from cycles and True gives R∗R^*
networkx.transitive_reduction(G)transitive reduction (Hasse)only for acyclic graphs
networkx.topological_sort, all_topological_sortsone or all linear extensionsthe second is exponential
networkx.is_directed_acyclic_graph(G)well-foundedness of a finite relation
scipy.cluster.hierarchy.DisjointSetunion-find
pow(a, -1, n)modular inverse (Python 3.8 or later)raises ValueError if gcd⁡(a,n)≠1\gcd(a, n) \ne 1
[ ]networkx, scipy and powBrowser
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 (a,a)(a, a) arising from a cycle, so closure ceases to match R+R^+. The 20 antichains of divisors of 30 are the 20 states visited by memoized linear-extension recursion. Timing depends on density: Warshall always performs n3n^3 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

QuizWhich are partial orders?
Which of these relations are partial orders (reflexive, antisymmetric and transitive)?

More than one answer may be correct.

QuizAntisymmetric does not mean ‘not symmetric’
Which of these relations on {1,2,3}\{1, 2, 3\} are antisymmetric?

More than one answer may be correct.

NumericCounting relations
How many relations on a four-element set are both reflexive and antisymmetric?
NumericSize of a closure
Let R={(1,2),(2,3),(3,1),(4,5)}R = \{(1, 2), (2, 3), (3, 1), (4, 5)\} on {1,2,3,4,5}\{1, 2, 3, 4, 5\}. How many pairs are in its transitive closure R+R^+?
NumericEquivalences on four elements
How many equivalence relations are there on a set of 4 elements?
NumericA modular inverse
Calculate the inverse of 77 modulo 2626: the unique x∈{0,…,25}x \in \{0, \dots, 25\} with 7x≡1(mod26)7x \equiv 1 \pmod{26}.
QuizAn equation in Z_10
Which are the solutions of 6x≡4(mod10)6x \equiv 4 \pmod{10} in Z10\Z_{10}?
NumericA large power
Calculate 32026 mod 103^{2026} \bmod 10, the last digit of 320263^{2026}.
CodeCounting linear extensions
Implement 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 e(P)=∑m minimale(P∖{m})e(P) = \sum_{m \text{ minimal}} e(P \setminus \{m\}) 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}
  pass
Shift+Enter to run
NumericThe width of {1, ..., 12}
Consider {1,2,…,12}\{1, 2, \dots, 12\} ordered by divisibility. What is its width, the size of the largest antichain?
QuizWell-founded or not?
Which of these relations are well-founded?

More than one answer may be correct.

QuizDoes a number suffice?
In the termination figure's loop, with a freely chosen new yy at each reset, is there a function f:N×N→Nf: \N \times \N \to \N strictly decreasing at every step, whatever the choice?
QuizLattice or not?
Which of these posets are lattices (every pair has a supremum and infimum)?

More than one answer may be correct.

ProofThe job queue always empties
Prove: A queue contains tasks of natural sizes. At each step a task of size kk is removed and, if k>0k > 0, any finite number of tasks of sizes smaller than kk are added. The queue empties in finitely many steps, although its length may grow.
0
Let mm be the greatest initial size and c(M)=(cm,…,c0)c(M) = (c_m, \dots, c_0) the count vector: cvc_v is the number of tasks of size vv.

Step 1 of 3. Why can we fix mm at the beginning?

Summary

Key idea
A binary relation is a Boolean matrix or directed graph, and its properties can be read there. Three combinations organize the lesson: equivalences are partitions (identifying objects means quotienting, and operations on the quotient must be well-defined); partial orders always flatten into linear extensions by removing minimal elements; and well-founded relations, without infinite descents, prove a process terminates. Lattices add suprema and infima, a way to combine information.
  • Matrices: MS∘R=MR⊙MS\mat{M}_{S \circ R} = \mat{M}_R \odot \mat{M}_S, and transitive closure R+R^+ comprises paths of lengths 11 through nn. Warshall calculates it in O(n3)\bigO(n^3) 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 nn elements there are BnB_n, the Bell number.
  • Zn\Z_n: addition and multiplication are well-defined; aa is invertible if and only if gcd⁡(a,n)=1\gcd(a, n) = 1, and ax≡bax \equiv b has 00 or gcd⁡(a,n)\gcd(a, n) solutions. Euler: aφ(n)≡1a^{\varphi(n)} \equiv 1 for invertible aa.
  • 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 Nk\N^k and multiset order are well-founded and prove termination where no measure in N\N suffices.
  • Lattices: supremum and infimum for each pair; in P(S)\mathcal{P}(S) these are ∪\cup and ∩\cap, for divisors lcm and gcd, for intervals the hull and intersection. They host fixed points and static analysis.