Homological algebra without elements
Homology was born in topology and grew up in algebra: chain complexes of abelian groups or modules, exact sequences, long exact sequences, derived functors. By the early 1950s the same constructions were needed for sheaves on a topological space, for representations of groups and Lie algebras, for graded and filtered objects. Each setting had its own proofs of the same lemmas — the five lemma, the snake lemma, the existence of long exact sequences — usually by chasing elements around diagrams.
In 1955 David Buchsbaum, and in 1957 Alexander Grothendieck in his "Tôhoku" paper, asked what a category must satisfy for all this to work. The answer is short: morphisms can be added; there are kernels and cokernels; and the two possible notions of "image" agree. Categories satisfying these axioms are abelian. Modules over any ring are the model example, sheaves of abelian groups on any space are the motivating one, and the Freyd–Mitchell theorem says, in a precise sense, that every small abelian category looks like a category of modules — so that element chases are legitimate everywhere.
This lesson assumes limits and colimits and modules, including exact sequences of modules.
Two images that must agree
In , a homomorphism has a kernel , a cokernel , and the first isomorphism theorem . Category-theoretically, kernels and cokernels are limits and colimits, but "image" and "" have to be expressed through them:
- the image of is the kernel of its cokernel, — the part of that the cokernel kills;
- the coimage of is the cokernel of its kernel, — with the kernel collapsed.
There is always a canonical morphism . The first isomorphism theorem says it is an isomorphism. An abelian category is, essentially, an additive category with kernels and cokernels in which the first isomorphism theorem holds for every morphism. When it fails, strange things happen: a morphism can be monic and epic without being invertible, and diagram chases break down.
Additive and abelian categories
Definition— preadditive and additive category
A category is preadditive (or -enriched) if each hom-set is an abelian group and composition is bilinear: and . It is additive if moreover it has a zero object (both initial and terminal) and all binary biproducts: objects with maps into and out of it such that , , , and . In a preadditive category a biproduct is simultaneously a product and a coproduct (see products and coproducts).
Definition— kernel, cokernel, image, coimage
In a category with a zero object, a kernel of is a morphism with that is universal: every with factors uniquely as . A cokernel is dually a universal with . When they exist, and , and factors as .
Definition— abelian category
An abelian category is an additive category in which every morphism has a kernel and a cokernel, every monomorphism is a kernel (of some morphism) and every epimorphism is a cokernel. Equivalently: an additive category with kernels and cokernels in which the canonical map is an isomorphism for every .
Definition— exact sequence; exact functor
In an abelian category, is exact at if and the induced map is an isomorphism. A short exact sequence is exact at , and . An additive functor between abelian categories is exact if it preserves short exact sequences, left exact if it sends exact to exact, and right exact dually.
In an abelian category a morphism is monic iff its kernel is and epic iff its cokernel is , and every morphism factors as an epimorphism followed by a monomorphism (through its image). These follow from the axioms with a little work; see Freyd, Abelian Categories, Chapter 2, or Weibel, An Introduction to Homological Algebra, Appendix A.
Examples and non-examples
Example— Modules, and categories built from them
For any ring , is abelian (proved below), in particular and . Full subcategories closed under kernels, cokernels and finite direct sums are abelian too: finite abelian groups, finite-dimensional vector spaces, finitely generated modules over a noetherian ring. Chain complexes of objects of an abelian category, representations of a group, and functor categories (kernels and cokernels computed objectwise) are abelian.
Example— Sheaves of abelian groups
For a topological space , sheaves of abelian groups form an abelian category. The kernel of is computed openwise, , which is again a sheaf. The cokernel is not openwise: is only a presheaf, and the cokernel in sheaves is its sheafification. A sequence of sheaves is exact if and only if it is exact on every stalk. Grothendieck proved that satisfies his axiom AB5 and has a generator, hence has enough injectives — which is what makes sheaf cohomology , the right derived functors of global sections, possible (see sheaves).
Example— The exponential sequence
On let be the sheaf of holomorphic functions and that of nowhere-vanishing ones (a sheaf of groups under multiplication). The sequence
is exact as a sequence of sheaves: on a small disc every nonvanishing holomorphic function has a logarithm. But on global sections, is not surjective: the function has no holomorphic logarithm on , since that would force , whereas the integral is . So the global-sections functor is left exact but not exact; the failure is measured by , and the obstruction attached to is its winding number.
Example— Additive but not abelian: free abelian groups
The full subcategory of free abelian groups is additive (direct sums of free groups are free) and has kernels (subgroups of free abelian groups are free); its full subcategory of finitely generated free groups even has cokernels (see the second experiment). But multiplication by on is monic (injective) and epic in : if with free and , then because has no 2-torsion. It is not an isomorphism, so by Proposition 3 below is not abelian. The cokernel of in is , which is missing from ; its cokernel in is (every map to a free group killing is zero), and the canonical map is , not an isomorphism. The second experiment computes this torsion for many integer matrices.
Example— More non-examples
- Banach spaces with bounded linear maps: the inclusion is injective (monic) and has dense image (epic: two bounded maps agreeing on a dense subspace agree), but is not surjective, so it is not an isomorphism.
- Filtered vector spaces with filtration-preserving maps: the identity of , from the filtration to the filtration , is monic and epic but its inverse does not preserve the filtrations. (This is why Hodge theory needs strict morphisms.)
- Vector bundles on : multiplication by on the trivial line bundle is monic, and epic among vector bundles (bundles have no torsion, so forces ), but not an isomorphism; its cokernel in sheaves is the skyscraper sheaf at , which is not a bundle. Coherent sheaves fix this: they form an abelian category containing the vector bundles.
- is not even additive: hom-sets are not abelian groups in a way compatible with composition.
Theorems
Theorem— Proposition 1 (R-Mod is abelian)
For every ring , the category of left -modules is abelian.
Proof
Hom-sets are abelian groups under pointwise addition and composition is bilinear; is a zero object and with the usual inclusions and projections is a biproduct. The kernel of is the inclusion of and the cokernel is the projection ; their universal properties are the usual factorisation properties of submodules and quotients. If is a monomorphism it is injective (test with maps ), and then is the kernel of : a map with image in factors uniquely through . If is an epimorphism it is surjective (test with the two maps given by the projection and ), and then it is the cokernel of by the first isomorphism theorem.
∎
Theorem— Proposition 2 (mono + epi = iso)
In an abelian category, a morphism that is both a monomorphism and an epimorphism is an isomorphism.
Proof
Let be monic and epic. Being monic, is the kernel of some ; in particular , and since is epic, . Now satisfies , so by the universal property of the kernel there is with . Then , and since is monic, .
∎
Theorem— Corollary 3 (free abelian groups do not form an abelian category)
is additive but not abelian.
Proof
As explained in the examples, is monic and epic in but not an isomorphism (it is not surjective, and an isomorphism in a full subcategory of is a bijection). By Proposition 2, is not abelian. The same argument works for torsion-free abelian groups.
∎
Now the two great diagram lemmas, proved for modules by chasing elements.
Theorem— Theorem 4 (the five lemma)
Consider a commutative diagram of -modules with exact rows
If and are isomorphisms, is surjective and is injective, then is an isomorphism.
Proof
Injective. Let . Then , so ( injective) and by exactness at . Then , so (exactness at ), and ( surjective). Now , so ( injective), and .
Surjective. Let . Write ( surjective). Then , so ( injective) and . Now , so with ( surjective), and .
∎
The proof splits into two "four lemmas": injectivity used only that are injective and surjective; surjectivity only that are surjective and injective.
Theorem— Theorem 5 (the snake lemma)
Consider a commutative diagram of -modules with exact rows
Then there is a homomorphism such that
is exact. If is injective so is the first map, and if is surjective so is the last.
Proof
The maps on kernels and cokernels are induced by (commutativity makes them well defined).
Construction of . Let . Choose with ( surjective). Then , so for a unique ( injective, row exact). Put . If is another choice, for some , so and : the class is independent of the choice. Linearity follows from the same independence.
Exactness at . If and , then , and gives . Conversely .
Exactness at . If with , then and . Conversely, if then , and lies in with .
Exactness at . . Conversely, if in , then for some ; satisfies , and using as the lift, .
Exactness at . . If in , write ; then , so .
The statements about the end maps are immediate.
∎
Applied to a short exact sequence of chain complexes, the snake lemma produces the connecting homomorphisms of the long exact sequence in homology — the engine behind Mayer–Vietoris and the long exact sequences of pairs in topology.
Theorem— Theorem 6 (Freyd–Mitchell embedding theorem; Freyd 1964, Mitchell 1964)
Every small abelian category admits a full, faithful and exact functor for some ring .
The proof (Freyd's book, Chapter 7; Kashiwara–Schapira §9.6; Mathlib) embeds into a Grothendieck abelian category — left exact functors , or — where an injective cogenerator exists, and then takes a hom functor out of a suitable projective generator.
What it allows. To prove a diagram lemma in an arbitrary abelian category — any statement about finitely many objects and morphisms, commutativity, exactness, monos, epis and isomorphisms, and the existence of morphisms between such objects — it suffices to prove it in module categories. Indeed: (1) the objects and morphisms of the diagram lie in a small full abelian subcategory whose inclusion is exact (close the diagram under finite biproducts, kernels and cokernels, countably many times); (2) Freyd–Mitchell gives full, faithful and exact; (3) exact functors preserve exactness and commutativity, and a faithful exact functor also reflects them (it sends to , and exactness is the vanishing of homology objects), as well as monos, epis and isomorphisms; (4) a morphism such as , constructed between images of objects in , comes from a unique morphism of because is full and faithful. So Theorems 4 and 5 hold in every abelian category — in particular in and in .
What it does not allow. The embedding is not canonical, preserves only finite limits and colimits (not infinite products or direct sums), and does not preserve projective or injective objects, so groups and derived functors are not computed by it. It is a theorem about small categories: for a large category like one either applies it to small subcategories as in (1), or — as Mathlib does — enlarges the universe so that the ring is itself "large". And it says nothing about non-abelian categories: in or Banach spaces, element-wise reasoning about images and cokernels gives wrong answers.
Alternatively, one can chase "generalised elements" (morphisms ) or Mac Lane's members directly in ; Mathlib proves both lemmas this way, without the embedding.
Abelian categories in Lean
Proposition 2 is formalised from the axiom "every monomorphism is a kernel", following the human proof line by line:
/-- **In an abelian category, a morphism that is monic and epic is an isomorphism.**
Human proof. Since `f : X ⟶ Y` is monic and the category is abelian, `f` is the kernel of some
`g : Y ⟶ Z` (Mathlib: `normalMonoOfMono`). Then `f ≫ g = 0 = f ≫ 0`, and `f` is epic,
so `g = 0`. The identity `𝟙 Y` satisfies `𝟙 Y ≫ g = 0`, so by the universal property of the
kernel it factors as `h ≫ f` for some `h : Y ⟶ X`. Finally `(f ≫ h) ≫ f = f ≫ (h ≫ f) = f`, and
cancelling the monomorphism `f` gives `f ≫ h = 𝟙 X`. So `h` is a two-sided inverse.
(Mathlib's one-line version is `isIso_of_mono_of_epi`, valid in any balanced category.) -/
theorem isIso_of_mono_of_epi {X Y : C} (f : X ⟶ Y) [Mono f] [Epi f] : IsIso f := by
let nm := normalMonoOfMono f
-- `f` is a kernel of `nm.g`; since `f` is epic, `nm.g = 0`.
have hg : nm.g = 0 := by
rw [← cancel_epi f, nm.w, comp_zero]
-- factor the identity through the kernel `f`
let h : Y ⟶ X := KernelFork.IsLimit.lift' nm.isLimit (𝟙 Y) (by rw [hg, comp_zero]) |>.1
have hf : h ≫ f = 𝟙 Y :=
KernelFork.IsLimit.lift' nm.isLimit (𝟙 Y) (by rw [hg, comp_zero]) |>.2
refine ⟨⟨h, ?_, hf⟩⟩
rw [← cancel_mono f, Category.assoc, hf, Category.comp_id, Category.id_comp]For the counterexample we formalise the maps, not the category : multiplication by 2 is injective and not surjective; it is cancellable on the right among homomorphisms into torsion-free groups (that is, epic among free abelian groups); but it is not cancellable among homomorphisms into .
/-- Multiplication by `2` on `ℤ` is injective (so it is a monomorphism, also among free abelian
groups: its kernel is `0`). -/
theorem two_mul_injective : Function.Injective (fun n : ℤ => 2 * n) := by
intro a b h
simpa using h/-- Multiplication by `2` on `ℤ` is not surjective: `1` is not even. So it is not an isomorphism. -/
theorem two_mul_not_surjective : ¬ Function.Surjective (fun n : ℤ => 2 * n) := by
intro h
obtain ⟨n, hn⟩ := h 1
simp only at hn
omega/-- **Multiplication by `2` is an epimorphism among torsion-free abelian groups** (in particular
among free abelian groups): if two homomorphisms `g, h : ℤ → G` into a torsion-free group agree
after `2 ·`, they are equal. Proof: `2 • g 1 = g 2 = h 2 = 2 • h 1`, so `g 1 = h 1` by
torsion-freeness, and a homomorphism out of `ℤ` is determined by its value at `1`. -/
theorem two_mul_epi_torsion_free {G : Type u} [AddCommGroup G] [IsAddTorsionFree G]
(g h : ℤ →+ G) (hgh : ∀ n : ℤ, g (2 * n) = h (2 * n)) : g = h := by
have h2 : (2 : ℕ) • g 1 = (2 : ℕ) • h 1 := by
have := hgh 1
rw [mul_one] at this
rw [← map_nsmul, ← map_nsmul]
simpa using this
have h1 : g 1 = h 1 :=
IsAddTorsionFree.eq_of_nsmul_eq_nsmul_of_addCommute two_ne_zero (AddCommute.all _ _) h2
exact AddMonoidHom.ext_int h1/-- **…but not an epimorphism of abelian groups.** The reduction map `ℤ → ℤ/2` and the zero map
differ, yet agree after multiplication by `2`. So in `Ab` the map `2 ·` is monic but not epic —
consistent with `Ab` being abelian — and its cokernel `ℤ/2` is exactly what the category of free
abelian groups is missing. -/
theorem two_mul_not_epi_ab :
∃ g h : ℤ →+ ZMod 2, g ≠ h ∧ ∀ n : ℤ, g (2 * n) = h (2 * n) := by
refine ⟨Int.castAddHom (ZMod 2), 0, ?_, ?_⟩
· intro hgh
have := congrArg (fun φ : ℤ →+ ZMod 2 => φ 1) hgh
simp at this
· intro n
simp only [Int.coe_castAddHom, Int.cast_mul, AddMonoidHom.zero_apply]
have : ((2 : ℤ) : ZMod 2) = 0 := rfl
rw [this, zero_mul]The short five lemma (the case of Theorem 4) by element chasing, using Mathlib's Function.Exact:
/-- **Short five lemma, injectivity half.** Given a commutative diagram of modules
```
A --f--> B --g--> D
|α |β |γ
A' --f'--> B' --g'--> D'
```
with the top row exact at `B`, `f'` injective, and `α`, `γ` injective, the middle map `β` is
injective. Element chase: if `β b = 0` then `γ (g b) = g' (β b) = 0`, so `g b = 0`, so `b = f a`;
then `f' (α a) = β (f a) = 0`, so `α a = 0`, so `a = 0` and `b = 0`. -/
theorem short_five_injective (f : A →ₗ[R] B) (g : B →ₗ[R] D) (f' : A' →ₗ[R] B')
(g' : B' →ₗ[R] D') (α : A →ₗ[R] A') (β : B →ₗ[R] B') (γ : D →ₗ[R] D')
(hfg : Function.Exact f g) (hf' : Function.Injective f')
(comm₁ : ∀ a, β (f a) = f' (α a)) (comm₂ : ∀ b, γ (g b) = g' (β b))
(hα : Function.Injective α) (hγ : Function.Injective γ) : Function.Injective β := by
rw [← LinearMap.ker_eq_bot, LinearMap.ker_eq_bot']
intro b hb
have hgb : g b = 0 := by
apply hγ
rw [comm₂, hb, map_zero, map_zero]
obtain ⟨a, rfl⟩ := (hfg b).mp hgb
have ha : α a = 0 := by
apply hf'
rw [← comm₁, hb, map_zero]
have : a = 0 := hα (by rw [ha, map_zero])
rw [this, map_zero]/-- **Short five lemma, surjectivity half.** In the same diagram, if `g` is surjective, the bottom
row is exact at `B'`, and `α`, `γ` are surjective, then `β` is surjective. Element chase: given
`b'`, write `g' b' = γ d` and `d = g b`; then `g' (b' - β b) = 0`, so `b' - β b = f' a'` with
`a' = α a`, and `b' = β (b + f a)`. -/
theorem short_five_surjective (f : A →ₗ[R] B) (g : B →ₗ[R] D) (f' : A' →ₗ[R] B')
(g' : B' →ₗ[R] D') (α : A →ₗ[R] A') (β : B →ₗ[R] B') (γ : D →ₗ[R] D')
(hg : Function.Surjective g) (hfg' : Function.Exact f' g')
(comm₁ : ∀ a, β (f a) = f' (α a)) (comm₂ : ∀ b, γ (g b) = g' (β b))
(hα : Function.Surjective α) (hγ : Function.Surjective γ) : Function.Surjective β := by
intro b'
obtain ⟨d, hd⟩ := hγ (g' b')
obtain ⟨b, rfl⟩ := hg d
have hker : g' (b' - β b) = 0 := by
rw [map_sub, ← comm₂, hd, sub_self]
obtain ⟨a', ha'⟩ := (hfg' _).mp hker
obtain ⟨a, rfl⟩ := hα a'
refine ⟨b + f a, ?_⟩
rw [map_add, comm₁, ha', add_sub_cancel]Mathlib's abelian categories, with the general five lemma, snake lemma and Freyd–Mitchell theorem (proved in Mathlib by Markus Himmel in 2025):
/-- **`R`-modules form an abelian category**, for every ring `R` (Mathlib's instance
`ModuleCat.abelian`): kernels and cokernels are the usual ones, and every monomorphism is the
kernel of its cokernel by the first isomorphism theorem. -/
theorem module_cat_abelian (R : Type u) [Ring R] : Nonempty (Abelian (ModuleCat.{v} R)) :=
⟨inferInstance⟩/-- **Sheaves with values in an abelian category form an abelian category**, whenever
sheafification exists (Mathlib's `sheafIsAbelian`). Kernels are computed sectionwise; cokernels
are sheafifications of the presheaf cokernels. This covers sheaves of abelian groups on a
topological space. -/
theorem sheaves_abelian {C : Type u} [Category.{v} C] (J : GrothendieckTopology C)
(D : Type w) [Category.{w'} D] [Abelian D] [HasSheafify J D] :
Nonempty (Abelian (Sheaf J D)) :=
⟨inferInstance⟩/-- **Sheaves of abelian groups on a topological space `X` form an abelian category**
(Mathlib's instance `TopCat.Sheaf.instAbelian`, a special case of the previous theorem). -/
theorem sheaves_on_space_abelian (X : TopCat.{u}) :
Nonempty (Abelian (TopCat.Sheaf AddCommGrpCat.{u} X)) :=
⟨inferInstance⟩/-- **The five lemma** in an arbitrary abelian category (Mathlib's
`Abelian.isIso_of_epi_of_isIso_of_isIso_of_mono`). The rows are exact sequences of length five
(`ComposableArrows C 4`), `φ` is a morphism between them (a commutative ladder), and if the
outer maps are epi, iso, iso, mono, then the middle map is an isomorphism. -/
theorem five_lemma {R₁ R₂ : ComposableArrows C 4} (hR₁ : R₁.Exact) (hR₂ : R₂.Exact)
(φ : R₁ ⟶ R₂) (h₀ : Epi (ComposableArrows.app' φ 0))
(h₁ : IsIso (ComposableArrows.app' φ 1)) (h₃ : IsIso (ComposableArrows.app' φ 3))
(h₄ : Mono (ComposableArrows.app' φ 4)) : IsIso (ComposableArrows.app' φ 2) :=
Abelian.isIso_of_epi_of_isIso_of_isIso_of_mono hR₁ hR₂ φ h₀ h₁ h₃ h₄/-- **The snake lemma** in an arbitrary abelian category (Mathlib's
`ShortComplex.SnakeInput.snake_lemma`). A `SnakeInput` packages the commutative diagram with
exact rows and the kernels and cokernels of the vertical maps; the conclusion is that the
six-term sequence `ker α → ker β → ker γ --δ--> coker α → coker β → coker γ` is exact. -/
theorem snake_lemma (S : ShortComplex.SnakeInput C) : S.composableArrows.Exact :=
S.snake_lemma/-- **The Freyd–Mitchell embedding theorem** (Mathlib's `Abelian.FreydMitchell.functor`, proved
by Markus Himmel in 2025). Every abelian category `C` admits a full, faithful, exact functor into
the category of modules over some ring. Classically `C` must be small; Mathlib handles a
locally small `C` by letting the ring live in the larger universe `max u v`. -/
theorem freyd_mitchell :
∃ (R : Type (max u v)) (_ : Ring R) (F : C ⥤ ModuleCat.{max u v} R),
F.Full ∧ F.Faithful ∧ PreservesFiniteLimits F ∧ PreservesFiniteColimits F :=
⟨Abelian.FreydMitchell.EmbeddingRing C, inferInstance, Abelian.FreydMitchell.functor C,
inferInstance, inferInstance, inferInstance, inferInstance⟩What is and is not formalised. Independently proved here: Proposition 2, the arithmetic of the counterexample, and the short five lemma for modules. From Mathlib: that modules and sheaves form abelian categories, the five and snake lemmas in arbitrary abelian categories, and Freyd–Mitchell. Not formalised here: the category as a category (and hence Corollary 3 as a statement about it), the exponential sequence, and the transfer argument of Theorem 6 (Mathlib proves the diagram lemmas directly, so it does not need it).
Snakes and torsion, computed
The first experiment builds random morphisms of short exact sequences of vector spaces over , computes all kernels and cokernels and the connecting map by exact row reduction, and checks the six-term exact sequence at every term. (Over a field every short exact sequence splits, so the middle map has the block form , and is the class of — the snake's construction made concrete.)
"""The snake lemma, computed: kernels, cokernels and the connecting map mod p.
Vector spaces over F_p form an abelian category in which every short exact
sequence splits, so every morphism of short exact sequences
0 -> A -> B -> C -> 0 to 0 -> A' -> B' -> C' -> 0 is, up to isomorphism,
B = A + C, B' = A' + C' with the middle map in block form
beta = [[alpha, x], [0, gamma]], x : C -> A' arbitrary.
For random such diagrams we compute ker and coker of alpha, beta, gamma,
the connecting map delta(w) = [x w] in coker(alpha), and check that the
six-term sequence
0 -> ker a -> ker b -> ker c --delta--> coker a -> coker b -> coker c -> 0
is exact at every term (image dimension = kernel dimension, composites 0).
Exact modular arithmetic; seeded random examples.
"""
import random
P = 5
def rank(cols, p=P):
"""Rank over F_p of the matrix whose columns are the given vectors."""
rows = [list(r) for r in zip(*cols)] if cols else []
r = 0
ncols = len(cols)
for c in range(ncols):
pivot = next((i for i in range(r, len(rows)) if rows[i][c] % p), None)
if pivot is None:
continue
rows[r], rows[pivot] = rows[pivot], rows[r]
inv = pow(rows[r][c], p - 2, p)
rows[r] = [v * inv % p for v in rows[r]]
for i in range(len(rows)):
if i != r and rows[i][c] % p:
k = rows[i][c]
rows[i] = [(a - k * b) % p for a, b in zip(rows[i], rows[r])]
r += 1
return r
def apply(mat, vec, p=P):
"""Matrix (list of rows) times column vector, mod p."""
return [sum(a * b for a, b in zip(row, vec)) % p for row in mat]
def columns(mat):
"""The columns of a matrix given as a list of rows."""
return [list(c) for c in zip(*mat)] if mat and mat[0] else []
def identity(n):
"""The n x n identity matrix."""
return [[int(i == j) for j in range(n)] for i in range(n)]
def kernel_basis(mat, n, p=P):
"""A basis of the kernel of mat : F_p^n -> F_p^m (mat has n columns)."""
rows = [list(r) for r in mat]
pivots = []
r = 0
for c in range(n):
pivot = next((i for i in range(r, len(rows)) if rows[i][c] % p), None)
if pivot is None:
continue
rows[r], rows[pivot] = rows[pivot], rows[r]
inv = pow(rows[r][c], p - 2, p)
rows[r] = [v * inv % p for v in rows[r]]
for i in range(len(rows)):
if i != r and rows[i][c] % p:
k = rows[i][c]
rows[i] = [(a - k * b) % p for a, b in zip(rows[i], rows[r])]
pivots.append(c)
r += 1
basis = []
for free in (c for c in range(n) if c not in pivots):
v = [0] * n
v[free] = 1
for i, c in enumerate(pivots):
v[c] = -rows[i][free] % p
basis.append(v)
return basis
def rank_into_quotient(vectors, sub):
"""Rank of the span of vectors in the quotient by span(sub)."""
return rank(vectors + sub) - rank(sub)
def random_matrix(m, n, rng, p=P, sparse=0.5):
"""A random m x n matrix over F_p with many zeros (to get kernels)."""
return [[rng.randrange(p) if rng.random() > sparse else 0
for _ in range(n)] for _ in range(m)]
def snake_data(a, c, a2, c2, rng):
"""Random diagram; returns dims and ranks of the six-term sequence."""
alpha = random_matrix(a2, a, rng)
gamma = random_matrix(c2, c, rng)
x = random_matrix(a2, c, rng, sparse=0.2)
beta = ([alpha[i] + x[i] for i in range(a2)]
+ [[0] * a + gamma[j] for j in range(c2)])
ka, kb, kc = (kernel_basis(alpha, a), kernel_basis(beta, a + c),
kernel_basis(gamma, c))
im_a, im_b, im_c = columns(alpha), columns(beta), columns(gamma)
f_ka = [v + [0] * c for v in ka] # ker a -> ker b
g_kb = [v[a:] for v in kb] # ker b -> ker c
delta = [apply(x, w) for w in kc] # ker c -> coker a
fp = [e + [0] * c2 for e in identity(a2)] # f' : A' -> B'
gp = [e[a2:] for e in identity(a2 + c2)] # g' : B' -> C'
dims = [len(ka), len(kb), len(kc), a2 - rank(im_a),
a2 + c2 - rank(im_b), c2 - rank(im_c)]
ranks = [rank(f_ka), rank(g_kb), rank_into_quotient(delta, im_a),
rank_into_quotient(fp, im_b), rank_into_quotient(gp, im_c)]
zero_composites = (
rank_into_quotient([apply(x, v[a:]) for v in kb], im_a) == 0
and rank_into_quotient([apply(x, w) + [0] * c2 for w in kc], im_b)
== 0)
return dims, ranks, zero_composites
def is_exact(dims, ranks):
"""Exactness of 0 -> V1 -> ... -> V6 -> 0 from dims and map ranks."""
incoming = [0] + ranks # rank of the map into each term
outgoing = ranks + [0] # rank of the map out of each term
return all(i == d - o for i, d, o in zip(incoming, dims, outgoing))
def main():
rng = random.Random(2025)
trials, exact, nonzero_delta, euler_ok = 300, 0, 0, 0
example = None
for t in range(trials):
a, c, a2, c2 = (rng.randint(1, 4) for _ in range(4))
dims, ranks, zero = snake_data(a, c, a2, c2, rng)
exact += is_exact(dims, ranks) and zero
nonzero_delta += ranks[2] > 0
alt = dims[0] - dims[1] + dims[2] - dims[3] + dims[4] - dims[5]
euler_ok += alt == 0
if example is None and ranks[2] > 0 and min(dims) > 0:
example = (a, c, a2, c2, dims, ranks)
print(f"Snake lemma over F_{P}: {trials} random morphisms of short exact "
"sequences")
print(f" six-term sequence exact at all six terms: {exact} / {trials}")
print(f" connecting map delta nonzero: {nonzero_delta}")
print(f" alternating sum of dimensions equal to 0: {euler_ok} / {trials}")
if example:
a, c, a2, c2, dims, ranks = example
names = ["ker a", "ker b", "ker c", "coker a", "coker b", "coker c"]
print(f"Example with dim A, C, A', C' = {a}, {c}, {a2}, {c2}:")
print(" dimensions: " + ", ".join(
f"{n} = {d}" for n, d in zip(names[:3], dims[:3])))
print(" " + ", ".join(
f"{n} = {d}" for n, d in zip(names[3:], dims[3:])))
print(f" ranks of the five maps (delta in the middle): {ranks}")
print()
print("Epistemic status: exact arithmetic in F_5, so each check is a true "
"statement\nabout the diagram tested; 300 random diagrams are "
"evidence, not proof. The\nsnake lemma itself is proved in the "
"lesson (and in Mathlib) for every\nabelian category.")
if __name__ == "__main__":
main()The second experiment measures how badly fails to be abelian: for every integer matrix with small entries it computes the invariant factors, hence the cokernel in (with torsion) and in (without), and the index of the image in its saturation — the failure of to be an isomorphism.
"""Where free abelian groups fail to be abelian: torsion in cokernels.
In the category F of finitely generated free abelian groups, a map
phi : Z^m -> Z^n has a kernel (subgroups of free groups are free), but its
cokernel in F is Z^n modulo the *saturation* of im(phi): the torsion of the
abelian-group cokernel Z^n / im(phi) is invisible. The canonical map
coimage -> image is then the inclusion im(phi) -> sat(im(phi)), of index
d_1 d_2 ... d_r (the invariant factors of phi), and it is an isomorphism
exactly when every invariant factor is 1. We compute invariant factors from
determinantal divisors (gcds of minors) for every 2 x 2 integer matrix with
entries in -2..2, and count how often F's coimage -> image map fails to be an
isomorphism - i.e. how often the abelian-category axiom fails.
"""
import itertools
import math
def det(mat):
"""Determinant of a small square integer matrix (Leibniz formula)."""
n = len(mat)
total = 0
for perm in itertools.permutations(range(n)):
sign = 1
for i in range(n):
for j in range(i + 1, n):
if perm[i] > perm[j]:
sign = -sign
term = sign
for i in range(n):
term *= mat[i][perm[i]]
total += term
return total
def determinantal_divisors(mat):
"""[D_1, D_2, ...]: D_k = gcd of all k x k minors (0 if all vanish)."""
m, n = len(mat), len(mat[0])
out = []
for k in range(1, min(m, n) + 1):
g = 0
for rows in itertools.combinations(range(m), k):
for cols in itertools.combinations(range(n), k):
g = math.gcd(g, det([[mat[r][c] for c in cols] for r in rows]))
out.append(g)
return out
def invariant_factors(mat):
"""Nonzero invariant factors d_1 | d_2 | ... of an integer matrix."""
divisors = [1] + [d for d in determinantal_divisors(mat) if d != 0]
return [divisors[k] // divisors[k - 1] for k in range(1, len(divisors))]
def cokernels(mat):
"""(Ab-cokernel description, F-cokernel rank) for mat : Z^cols -> Z^rows.
Ab: list of torsion orders d > 1 plus a free rank; F: the free rank only.
"""
factors = invariant_factors(mat)
free_rank = len(mat) - len(factors)
torsion = [d for d in factors if d > 1]
return (torsion, free_rank), free_rank
def coimage_to_image_index(mat):
"""Index of im(phi) in its saturation: the product of invariant factors."""
return math.prod(invariant_factors(mat))
def describe(torsion, free_rank):
"""A readable name such as 'Z/2 + Z' for an abelian group."""
parts = [f"Z/{d}" for d in torsion] + ["Z"] * free_rank
return " + ".join(parts) if parts else "0"
def main():
print("Multiplication by k on Z, as a map of free abelian groups:")
for k in [1, 2, 3, 0]:
(tors, free), f_rank = cokernels([[k]])
print(f" k = {k}: cokernel in Ab = {describe(tors, free):<4}"
f" cokernel in F = {describe([], f_rank):<2}"
f" coim -> im index = {coimage_to_image_index([[k]])}")
entries = range(-2, 3)
mats = [[[a, b], [c, d]] for a, b, c, d in itertools.product(entries,
repeat=4)]
by_index = {}
for mat in mats:
idx = coimage_to_image_index(mat)
by_index[idx] = by_index.get(idx, 0) + 1
bad = sum(n for idx, n in by_index.items() if idx > 1)
print(f"All {len(mats)} integer 2 x 2 matrices with entries in -2..2:")
for idx in sorted(by_index):
print(f" index [sat(im) : im] = {idx}: {by_index[idx]:3d} matrices")
print(f" coimage -> image not an isomorphism in F: {bad} matrices")
example = [[2, 0], [0, 2]]
(tors, free), _ = cokernels(example)
print(f" e.g. 2 * identity: cokernel in Ab = {describe(tors, free)}, "
"cokernel in F = 0:")
print(" monic and epic in F, but not invertible")
print()
print("Epistemic status: exact integer arithmetic, exhaustive over the "
"625\nmatrices shown. It illustrates the theorem that F is additive "
"but not\nabelian; the proof (and the Lean file) handle the general "
"case.")
if __name__ == "__main__":
main()Exercises
1. Abelian categories
Warm-upHumanWhich of these categories are abelian? (Choose all that apply.)
2. Abelian categories
CoreHumanIn the proof that a monic epimorphism in an abelian category is an isomorphism, we write for some and conclude . Which fact gives ?
3. Abelian categories
CoreHumanA morphism of short exact sequences of finite-dimensional vector spaces has , , , and . What is ?
4. Abelian categories
CoreHumanIn the five lemma (rows and , vertical maps ), which hypotheses does the proof that is injective use?
5. Abelian categories
StretchHumanWhich of the following are legitimate uses of the Freyd–Mitchell embedding theorem? (Choose all that apply.)
6. Abelian categories
CoreHumanOn consider . Which statement is true?
7. Abelian categories
CoreFormalThe Lean theorem short_five_injective concludes Function.Injective β. Which set of hypotheses (besides commutativity) does it use?
8. Abelian categories
StretchComputationalFor an integer matrix , viewed as a map , the cokernel in is (with ), where and (if , the cokernel is ). Write cokernel_2x2(a, b, c, d) returning (torsion, free_rank): the sorted list of torsion orders greater than , and the rank of the free part.
Common misconceptions
Misconception
"Every additive category is abelian." Additivity only gives addition of morphisms, a zero object and biproducts. Free abelian groups, Banach spaces, filtered vector spaces and vector bundles are additive (several even have kernels and cokernels), yet each has a monic epimorphism that is not an isomorphism, which Proposition 2 forbids in an abelian category.
Misconception
"Freyd–Mitchell lets us treat any abelian category as a category of modules." It applies to small abelian categories, gives a non-canonical embedding, and preserves only finite limits and colimits. It is safe for finite diagram lemmas (via a small abelian subcategory containing the diagram), but not for statements about infinite products, injective or projective objects, or derived functors of a large category such as .
Misconception
"In sheaves, cokernels (and surjectivity) can be checked on sections over each open set." Kernels can; cokernels cannot. on is an epimorphism of sheaves although it is not surjective on global sections. Epimorphisms of sheaves are the locally surjective maps (equivalently, surjective on stalks).
Misconception
"An epimorphism is a surjective map." In yes, but "epic" depends on the category: is epic in , and is epic among Banach spaces, though neither is surjective. In an abelian category, epic means "cokernel zero".
Viewpoints
Topology— Long exact sequences and sheaf cohomology
The snake lemma is the algebraic core of algebraic topology's long exact sequences. A short exact sequence of chain complexes (for example, for a pair , or for an open cover ) gives, by the snake lemma applied degreewise, the long exact sequence , which yields Mayer–Vietoris and excision computations (see algebraic topology). Sheaf cohomology lives in the abelian category : the exponential sequence above gives , sending a nonvanishing function to its winding number around the origin.
Geometry— Coherent sheaves versus vector bundles
In algebraic and complex geometry, vector bundles are the natural objects but they do not form an abelian category: a map of bundles can change rank at special points, and its kernel and cokernel are then not bundles (multiplication by on the trivial line bundle over has cokernel supported at the origin). Serre's coherent sheaves (1955) are the abelian envelope that fixes this: on a noetherian scheme or complex manifold they form an abelian category containing the vector bundles (locally free sheaves) and closed under kernels and cokernels. Much of modern geometry — derived categories of coherent sheaves, stability conditions, moduli of sheaves — starts here (see algebraic geometry and vector bundles).
Analysis— Banach spaces are quasi-abelian
Functional analysis lives in additive categories that are not abelian. In Banach spaces, every bounded map has a kernel (the closed null space ) and a cokernel ( modulo the closure of ), so and . The canonical map is injective with dense image, and by the open mapping theorem it is an isomorphism exactly when has closed range. So the failure of the abelian axiom is concentrated in maps with non-closed range, like . Such categories are quasi-abelian (Schneiders 1999), and homological algebra still works there with a modified notion of exactness ("strict" morphisms), as in the theory of Fréchet and nuclear spaces (see functional analysis).
Algebra— Modules over everything
Freyd–Mitchell says abelian categories are categories of modules "up to exact embedding", but many important abelian categories are module categories on the nose or nearly: representations of a quiver are modules over its path algebra (see path algebras); is ; and by Gabriel–Popescu every Grothendieck abelian category is a localisation of a module category. Morita theory asks when (for example and ), showing that the category remembers less than the ring. Homological algebra — , , derived functors — is built entirely from the abelian structure (see homological algebra).
Category theory— Exactness as a property of limits
The abelian axioms are statements about finite limits and colimits plus enrichment in (see enriched categories). Barr's exact categories isolate the non-additive part — regular categories in which every equivalence relation is a kernel pair — and Tierney's theorem says that the abelian categories are exactly the additive Barr-exact categories. Elementary topoi are Barr-exact too, one reason why sheaves of sets and sheaves of abelian groups behave so similarly. Two refinements drive modern work: Grothendieck abelian categories (with exact filtered colimits and a generator, so with enough injectives) and derived categories , in which quasi-isomorphisms are inverted and the long exact sequences become distinguished triangles (see derived categories).
History and global context
- Exact sequences and diagram chasing grew out of algebraic topology in the 1940s (Hurewicz; Eilenberg and Steenrod's axioms for homology, 1945–52). Henri Cartan and Samuel Eilenberg's Homological Algebra (1956) developed derived functors for modules.
- David Buchsbaum (thesis 1954, published 1955) introduced "exact categories" close to today's abelian categories; Alexander Grothendieck's "Sur quelques points d'algèbre homologique" (Tôhoku Mathematical Journal, 1957) gave the modern axioms, the conditions AB1–AB6, and the existence of enough injectives in categories of sheaves — making sheaf cohomology a derived functor.
- Jean-Pierre Serre introduced coherent sheaves (1955); Pierre Gabriel's thesis (1962) developed abelian categories for algebraic geometry.
- Peter Freyd and Barry Mitchell proved the embedding theorem (1964); Freyd's book Abelian Categories appeared the same year. Saunders Mac Lane gave the "members" approach to diagram chasing in Homology (1963).
- Mathlib's formalisation of the snake lemma and the five lemma in general abelian categories, and of the Freyd–Mitchell theorem (completed by Markus Himmel in 2025), shows that these classical arguments can be checked by machine without passing to modules.
Further reading
- Charles A. Weibel, An Introduction to Homological Algebra (1994) — Chapter 1 and Appendix A on abelian categories and Freyd–Mitchell.
- Peter Freyd, Abelian Categories (1964) — the original monograph, including the embedding theorem.
- Masaki Kashiwara and Pierre Schapira, Categories and Sheaves (2006) — abelian and Grothendieck categories, Chapters 8–9.
- Saunders Mac Lane, Homology (1963) and Categories for the Working Mathematician, Chapter VIII — diagram chasing with members.
- Alexander Grothendieck, "Sur quelques points d'algèbre homologique", Tôhoku Mathematical Journal 9 (1957).
- Robin Hartshorne, Algebraic Geometry (1977), Chapters II–III — sheaves of modules and sheaf cohomology.