Modelcore
Leslie matrix
Also called Leslie matrix model.
An age-structured population model n_(t+1) = L n_t with fertilities in the first row and survival rates below the diagonal.
The Leslie matrix model follows a population that is divided into age classes. The vector holds the number of individuals in each of age classes at census , and one step is . The first row of holds the fertilities , the number of newborns per individual of class that enter class 1 at the next census. The subdiagonal holds the survival rates , the chance that an individual of class lives to class . Leslie (1945) set out this matrix form and showed that the long-run growth rate and the stable age distribution are the dominant eigenvalue and eigenvector of . Because is nonnegative, the Perron-Frobenius theorem tells when this dominant eigenvalue exists and when every start converges to the stable distribution.
The machine
The state. A vector . The entry is the number of individuals, usually females only, in age class at census . Each class is one time step wide, so class holds the individuals of age to steps.
The parameters. The fertilities , in newborns per individual per step, counted as the newborns that are alive at the next census. The survival rates , with no unit. The survivorship to class is and .
The update rule. with
that is, and .
The assumptions. The rates are constant in time and do not depend on the density, so the model is linear. The population is closed. No individual lives past class . The model is deterministic: it gives expected numbers. The value of depends on when the census is taken relative to the breeding season, and it must include the survival of the newborns to the next census.
PROJECT(F, P, n_0, T)- 1
n ← n_0 - 2
for t ← 1 to T do - 3
n ← (F_1 n_1 + ... + F_k n_k, P_1 n_1, ..., P_(k-1) n_(k-1)) that is, n ← L n - 4
record n_t ← n - 5
return n_1, ..., n_T
Line L3 uses the structure of : it costs per step, not the of a general matrix times a vector. So steps cost .
What it counts
- The vector and the total population .
- The asymptotic growth rate per step, the dominant eigenvalue of . The population grows when and declines when .
- The stable age distribution , the right eigenvector of , scaled to sum 1.
- The reproductive values , the left eigenvector of , scaled so that . The value is the relative contribution of one individual of class to the future population.
- The net reproductive rate , the expected number of offspring of a newborn over its whole life.
- The generation time , the mean age of the mothers of the newborns in the stable population.
- The damping ratio , which sets how fast the age structure approaches .
- The sensitivities and the elasticities .
Relation to other models
- Power iteration. Projecting the population is power iteration on . The ratio tends to , and tends to , at the rate .
- Characteristic polynomial. For a Leslie matrix it has a closed form, , so the growth rate is the root of one equation in one unknown.
- Next-generation matrix. Both models have a threshold at 1. For the Leslie model, is the next-generation count of newborns per newborn, and exactly when .
- Galton-Watson process. In a branching process with several types, where an individual of class has a random number of offspring with mean and survives with probability , the expected numbers follow the Leslie model, by linearity of expectation.
- Markov chain. The survival part of is the transition matrix of the life of one individual, with death as an absorbing state. Its columns sum to less than 1.
- Matrix power. . Repeated squaring gives in operations, which helps for large and exact rational entries.
- Logistic map and Ricker model. These models have one class but density dependence. If the fertilities of the Leslie model fall with the density, the age-structured model can also have cycles and chaos (heuristic).
Known results in the model
The characteristic equation (theorem). . For the equation is the Euler-Lotka equation . If some , it has exactly one positive root, and the eigenvector of this root is .
Proof. Expand along the first row. If row 1 and column are removed, the rest is block diagonal with two triangular blocks, with and then copies of on the diagonal. So the minor is , and with the sign of the cofactor the expansion is . Division by gives the Euler-Lotka form. For the eigenvector, suppose with . The rows 2 to give , so . The function is strictly decreasing on from to 0, so it takes the value 1 exactly once.
The threshold (theorem). if and only if , and if and only if .
Proof. and is decreasing, so its root lies above 1 exactly when .
Perron-Frobenius for Leslie matrices (theorem and known result). If , then is irreducible: every class leads to every other class. By the Perron-Frobenius theorem, is then positive and simple, no other eigenvalue has a larger modulus, and and are positive. If is also primitive, then for every other eigenvalue and, for every nonzero , (theorem). It is a known result that an irreducible Leslie matrix is primitive exactly when the greatest common divisor of the ages with is 1. In particular, two adjacent fertile classes are enough.
Sensitivity and elasticity (theorem). , and the elasticities sum to 1.
Proof. Differentiate and multiply on the left by . The terms with the derivative of cancel because , which leaves . The sum of the elasticities is .
An example with three classes. Take and , so
The characteristic equation is . Multiplied by 4 it is , and with the identity gives . So the eigenvalues are , and (theorem). The net reproductive rate is , and as the threshold theorem says, : the population declines by about 6 percent per step. The fertile ages are 2 and 3 with greatest common divisor 1, so is primitive.
- The stable age distribution is .
- The reproductive values are . An individual of class 2 is worth almost two newborns, because it is about to breed and a newborn may die first.
- The generation time is steps.
- The elasticities of are for , for , and for both and . So a given relative change in the survival of the young changes the growth rate most.
- The damping ratio is .
From the projection gives:
| 1 | 0 | 50 | 0 | 50 |
| 2 | 75 | 0 | 12.5 | 87.5 |
| 3 | 12.5 | 37.5 | 0 | 50 |
| 4 | 56.25 | 6.25 | 9.375 | 71.875 |
| 5 | 18.75 | 28.125 | 1.5625 | 48.4375 |
The total oscillates because is negative and not much smaller than in modulus. The oscillation dies out only by a factor of about per step.
An imprimitive example (theorem). Take and . Then , so the population repeats with period 3 and never reaches a stable distribution: , , , , and so on. Here , , and the other two eigenvalues are the complex cube roots of 1, with the same modulus.
Slow convergence near an imprimitive matrix (measurement). In a random test with six classes, and , the matrix is primitive, since the fertile ages 2, 4, 5 and 6 have greatest common divisor 1. But the odd ages add very little, and after 2000 steps the ratio was , still percent away from . For such matrices, solve the Euler-Lotka equation, for example by the bisection method, in place of projection.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/leslie-matrix/. The authors are listed in prov/V3XCAW.jsonl.
"""The Leslie matrix model n_(t+1) = L n_t of an age-structured population.
The model is given by the fertilities F_1, ..., F_k (the first row of L)
and the survival rates P_1, ..., P_(k-1) (the subdiagonal). project uses
this structure, so one step costs Theta(k) and not Theta(k^2). The other
functions give the characteristic polynomial with exact coefficients, the
growth rate from the Euler-Lotka equation and by power iteration, the
stable age distribution, the reproductive values, R_0, the sensitivities
and elasticities of the growth rate, and a test for primitivity.
"""
from __future__ import annotations
import math
from fractions import Fraction
from typing import List, Sequence, Tuple
def _check(F: Sequence, P: Sequence) -> None:
if len(F) < 1 or len(P) != len(F) - 1:
raise ValueError("need k >= 1 fertilities and k - 1 survival rates")
if any(f < 0 for f in F) or any(not 0 < p <= 1 for p in P):
raise ValueError("need F_i >= 0 and 0 < P_i <= 1")
def leslie(F: Sequence[float], P: Sequence[float]) -> List[List[float]]:
"""The k by k Leslie matrix."""
_check(F, P)
k = len(F)
L = [[0 * F[0] for _ in range(k)] for _ in range(k)]
L[0] = list(F)
for i, p in enumerate(P):
L[i + 1][i] = p
return L
def project(F: Sequence[float], P: Sequence[float], n0: Sequence[float], steps: int) -> List[List[float]]:
"""The vectors n_1, ..., n_steps from n_0."""
_check(F, P)
if len(n0) != len(F) or steps < 0:
raise ValueError("need len(n0) == k and steps >= 0")
n = list(n0) # @line L1
out: List[List[float]] = []
for _ in range(steps): # @line L2
n = [sum(f * x for f, x in zip(F, n))] + [p * x for p, x in zip(P, n)] # @line L3
out.append(n) # @line L4
return out # @line L5
def survivorship(P: Sequence) -> List:
"""l_1 = 1 and l_i = P_1 ... P_(i-1)."""
l = [1 + 0 * (P[0] if P else 0)]
for p in P:
l.append(l[-1] * p)
return l
def characteristic(F: Sequence, P: Sequence) -> List:
"""Coefficients c_0..c_k of det(lambda I - L) = sum c_j lambda^(k - j)."""
_check(F, P)
l = survivorship(P)
return [1] + [-f * li for f, li in zip(F, l)]
def net_reproductive_rate(F: Sequence, P: Sequence):
"""R_0 = sum F_i l_i, the expected offspring of a newborn over its life."""
_check(F, P)
return sum(f * li for f, li in zip(F, survivorship(P)))
def euler_lotka_root(F: Sequence[float], P: Sequence[float], tol: float = 1e-15) -> float:
"""The positive root of sum F_i l_i lambda^(-i) = 1, by bisection."""
_check(F, P)
l = survivorship(P)
terms = [(i + 1, float(f * li)) for i, (f, li) in enumerate(zip(F, l)) if f > 0]
if not terms:
raise ValueError("need some F_i > 0")
phi = lambda x: sum(c / x ** i for i, c in terms)
lo, hi = 0.0, 1.0
while phi(hi) > 1:
hi *= 2
lo = hi / 2
while phi(lo) < 1:
lo /= 2
while hi - lo > tol * hi:
mid = (lo + hi) / 2
if phi(mid) > 1:
lo = mid
else:
hi = mid
return (lo + hi) / 2
def stable_distribution(F: Sequence[float], P: Sequence[float]) -> List[float]:
"""w_i proportional to l_i lambda^(-(i - 1)), with sum 1."""
lam = euler_lotka_root(F, P)
w = [float(li) / lam ** i for i, li in enumerate(survivorship(P))]
s = sum(w)
return [x / s for x in w]
def reproductive_values(F: Sequence[float], P: Sequence[float]) -> List[float]:
"""v_i = (lambda^(i - 1) / l_i) sum_(j >= i) F_j l_j lambda^(-j), so v_1 = 1."""
lam = euler_lotka_root(F, P)
l = [float(x) for x in survivorship(P)]
k = len(F)
return [lam ** i / l[i] * sum(F[j] * l[j] / lam ** (j + 1) for j in range(i, k)) for i in range(k)]
def power_iteration(F: Sequence[float], P: Sequence[float], iters: int = 10000,
tol: float = 1e-13) -> Tuple[float, List[float]]:
"""lambda_1 and w by repeated projection with normalisation to sum 1."""
k = len(F)
w = [1.0 / k] * k
lam = 0.0
for _ in range(iters):
x = project(F, P, w, 1)[0]
s = sum(x)
x = [v / s for v in x]
done = abs(s - lam) < tol * s and max(abs(a - b) for a, b in zip(x, w)) < tol
lam, w = s, x
if done:
break
return lam, w
def sensitivities(F: Sequence[float], P: Sequence[float]) -> Tuple[List[List[float]], List[List[float]]]:
"""s_ij = v_i w_j / <v, w> and the elasticities e_ij = a_ij s_ij / lambda."""
lam = euler_lotka_root(F, P)
w = stable_distribution(F, P)
v = reproductive_values(F, P)
vw = sum(a * b for a, b in zip(v, w))
A = leslie(F, P)
k = len(F)
s = [[v[i] * w[j] / vw for j in range(k)] for i in range(k)]
e = [[A[i][j] * s[i][j] / lam for j in range(k)] for i in range(k)]
return s, e
def is_primitive(F: Sequence, P: Sequence) -> bool:
"""Some power of L is positive. Wielandt: checking power (k - 1)^2 + 1 is enough."""
A = leslie(F, P)
k = len(F)
B = [[A[i][j] > 0 for j in range(k)] for i in range(k)]
M = [row[:] for row in B]
for _ in range((k - 1) ** 2):
M = [[any(M[i][t] and B[t][j] for t in range(k)) for j in range(k)] for i in range(k)]
return all(all(row) for row in M)
def gcd_rule(F: Sequence, P: Sequence) -> bool:
"""For F_k > 0: L is primitive iff the gcd of the ages i with F_i > 0 is 1."""
if not F[-1] > 0:
raise ValueError("the rule needs F_k > 0")
g = 0
for i, f in enumerate(F, start=1):
if f > 0:
g = math.gcd(g, i)
return g == 1
test_leslie_matrix.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/leslie-matrix/. The authors are listed in prov/V3XCAW.jsonl.
"""Tests of the Leslie model against the page example, exact Fraction
arithmetic, the closed forms, and random matrices with fixed seeds."""
import math
import random
from fractions import Fraction
import pytest
from leslie_matrix import (
characteristic,
euler_lotka_root,
gcd_rule,
is_primitive,
leslie,
net_reproductive_rate,
power_iteration,
project,
reproductive_values,
sensitivities,
stable_distribution,
)
F = [0, 1.5, 1.0]
P = [0.5, 0.25]
def close(xs, ys, tol=1e-6):
return len(xs) == len(ys) and all(abs(a - b) < tol for a, b in zip(xs, ys))
def matvec(A, x):
return [sum(a * b for a, b in zip(row, x)) for row in A]
def test_page_projection_exact():
Fq = [Fraction(0), Fraction(3, 2), Fraction(1)]
Pq = [Fraction(1, 2), Fraction(1, 4)]
path = project(Fq, Pq, [100, 0, 0], 5)
assert path == [[0, 50, 0], [75, 0, Fraction(25, 2)], [Fraction(25, 2), Fraction(75, 2), 0],
[Fraction(225, 4), Fraction(25, 4), Fraction(75, 8)],
[Fraction(75, 4), Fraction(225, 8), Fraction(25, 16)]]
assert [sum(n) for n in path] == [50, Fraction(175, 2), 50, Fraction(575, 8), Fraction(775, 16)]
A = leslie(Fq, Pq)
n = [100, 0, 0]
for step in path:
n = matvec(A, n)
assert n == step
assert characteristic(Fq, Pq) == [1, 0, Fraction(-3, 4), Fraction(-1, 8)]
assert net_reproductive_rate(Fq, Pq) == Fraction(7, 8)
def test_page_eigen_values():
lam = euler_lotka_root(F, P)
assert abs(lam - math.cos(math.pi / 9)) < 1e-12
for theta in (math.pi / 9, 7 * math.pi / 9, 13 * math.pi / 9):
x = math.cos(theta)
assert abs(x ** 3 - 0.75 * x - 0.125) < 1e-12
assert abs(math.cos(7 * math.pi / 9) + 0.766044) < 1e-6
assert abs(math.cos(13 * math.pi / 9) + 0.173648) < 1e-6
assert close(stable_distribution(F, P), [0.597497, 0.317922, 0.084581])
assert close(reproductive_values(F, P), [1, 1.879385, 1.064178])
lam_p, w_p = power_iteration(F, P)
assert abs(lam_p - lam) < 1e-10 and close(w_p, stable_distribution(F, P), tol=1e-9)
def test_eigenvectors_and_elasticities():
A = leslie(F, P)
lam = euler_lotka_root(F, P)
w = stable_distribution(F, P)
v = reproductive_values(F, P)
assert close(matvec(A, w), [lam * x for x in w], tol=1e-12)
At = [list(col) for col in zip(*A)]
assert close(matvec(At, v), [lam * x for x in v], tol=1e-12)
s, e = sensitivities(F, P)
assert abs(sum(map(sum, e)) - 1) < 1e-12
assert abs(e[0][1] - 0.394931) < 1e-6 and abs(e[0][2] - 0.070046) < 1e-6
assert abs(e[1][0] - 0.464977) < 1e-6 and abs(e[2][1] - 0.070046) < 1e-6
h = 1e-6
for i, j in ((0, 1), (0, 2), (1, 0), (2, 1)):
F2, P2 = list(F), list(P)
if i == 0:
F2[j] += h
else:
P2[j] += h
assert abs((euler_lotka_root(F2, P2) - lam) / h - s[i][j]) < 1e-5
def test_random_matrices():
rng = random.Random(71)
for _ in range(300):
k = rng.randint(2, 6)
Fr = [rng.choice([0, rng.uniform(0, 3)]) for _ in range(k - 1)] + [rng.uniform(0.1, 3)]
Pr = [rng.uniform(0.05, 1) for _ in range(k - 1)]
lam = euler_lotka_root(Fr, Pr)
coeffs = characteristic(Fr, Pr)
assert abs(sum(c * lam ** (k - j) for j, c in enumerate(coeffs))) < 1e-9 * max(1, lam ** k)
A = leslie(Fr, Pr)
w = stable_distribution(Fr, Pr)
assert close(matvec(A, w), [lam * x for x in w], tol=1e-9)
r0 = net_reproductive_rate(Fr, Pr)
assert (lam > 1) == (r0 > 1) and (lam < 1) == (r0 < 1)
assert is_primitive(Fr, Pr) == gcd_rule(Fr, Pr)
n = [1.0] + [0.0] * (k - 1)
log_growth = 0.0
for t in range(600):
m = project(Fr, Pr, n, 1)[0]
if t >= 300:
log_growth += math.log(sum(m) / sum(n))
n = [x / sum(m) for x in m]
assert abs(log_growth / 300 - math.log(lam)) < 0.02
def test_imprimitive_example_cycles():
Fq = [0, 0, Fraction(6)]
Pq = [Fraction(1, 2), Fraction(1, 3)]
assert not is_primitive(Fq, Pq) and not gcd_rule(Fq, Pq)
assert net_reproductive_rate(Fq, Pq) == 1
path = project(Fq, Pq, [6, 0, 0], 6)
assert path[2] == [6, 0, 0] and path[5] == [6, 0, 0]
assert path[0] == [0, 3, 0] and path[1] == [0, 0, 1]
assert is_primitive(F, P)
def test_input_checks():
with pytest.raises(ValueError):
leslie([1, 2], [0.5, 0.5])
with pytest.raises(ValueError):
project(F, [1.5, 0.2], [1, 0, 0], 1)
with pytest.raises(ValueError):
euler_lotka_root([0, 0], [0.5])
assert project(F, P, [1, 2, 3], 0) == []
References
- P. H. Leslie, On the use of matrices in certain population mathematics, Biometrika 33(3), 1945, pages 183 to 212 (the matrix of fertilities and survival rates, its latent roots and the stable age distribution)
- Hal Caswell, Matrix Population Models, Construction, Analysis, and Interpretation, 2nd ed., Sinauer Associates, 2001, the chapters on age-classified models, on the growth rate and stable structure, and on sensitivity analysis
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag V3XCAW Edit this page History Report an error Markdown