Relations and orders
A relation is a set of ordered pairs. Whether it is reflexive, symmetric or transitive is a finite check, and when a property fails the answer names the pairs that break it. Partial orders get their own tools: Hasse diagrams, chains and antichains, linear extensions, and the Möbius function.
Relations
import { relation, fromPartition } from "@ratmath/discrete";
const R = relation([1, 2, 3, 4], [[1, 2], [2, 3]]);
R.properties().transitive; // { holds: false, witness: [1, 2, 3] }: 1R2, 2R3, but not 1R3
String(R.transitiveClosure()); // "{(1, 2), (1, 3), (2, 3)}"
relation([1, 2, 3], (a, b) => (a - b) % 2 === 0).classes(); // [[1, 3], [2]]
Each property comes with a witness when it fails: an element not related to itself, a pair whose reverse is missing, or the three elements that break transitivity. The transitive closure is computed by Warshall's algorithm. An equivalence relation and a partition are the same thing, and classes() and fromPartition go between them.
Partial orders
import { poset, divisorLattice } from "@ratmath/discrete";
const D = divisorLattice(60);
D.hasse().length; // 20 covering pairs
D.levels().map((l) => l.length); // [1, 3, 4, 3, 1]
D.width(); // { width: 4, antichain: [4, 6, 10, 15], chains: [[1,2,4,12,60], [3,6,30], [5,10,20], [15]] }
A partial order is reflexive, antisymmetric and transitive; poset takes generating pairs, closes them, and refuses a cycle with the two elements that would be equal. Dilworth's theorem says the largest antichain has the same size as the fewest chains covering the order. Both are found together from a maximum bipartite matching between "lower" and "upper" copies of the elements, so each is a certificate for the other.
Linear extensions and the Möbius function
import { booleanLattice, partitionLattice } from "@ratmath/discrete";
booleanLattice(3).countLinearExtensions(); // 48n
D.mobius(1, 30); // −1: the number-theoretic μ(30)
partitionLattice(4).mobius("1|2|3|4", "1234"); // −6 = (−1)^3·3!
A linear extension is a total order compatible with the partial one; they are counted by dynamic programming over down-sets. The Möbius function is defined by and for . It inverts sums over the order:
which on divisors is Möbius inversion of number theory and on subsets is inclusion–exclusion.
Lattices
const N5 = poset(["0", "a", "b", "c", "1"], [["0", "a"], ["a", "b"], ["0", "c"], ["b", "1"], ["c", "1"]]);
N5.isLattice(); // { lattice: true }
N5.isDistributive(); // { distributive: false, witness: ["b", "a", "c"] }
A lattice has a meet and a join for every pair. It is distributive exactly when it contains neither the pentagon nor the diamond ; when the law fails, the three elements are given.
@ratmath/discrete and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.