Algorithm Search⌘K

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 nt=(n1,t,…,nk,t)n_t = (n_{1,t}, \ldots, n_{k,t}) holds the number of individuals in each of kk age classes at census tt, and one step is nt+1=Lntn_{t+1} = L n_t. The first row of LL holds the fertilities FiF_i, the number of newborns per individual of class ii that enter class 1 at the next census. The subdiagonal holds the survival rates PiP_i, the chance that an individual of class ii lives to class i+1i + 1. 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 LL. Because LL 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 nt∈R≥0kn_t \in \mathbb{R}_{\ge 0}^k. The entry ni,tn_{i,t} is the number of individuals, usually females only, in age class ii at census tt. Each class is one time step wide, so class ii holds the individuals of age i−1i - 1 to ii steps.

The parameters. The fertilities F1,…,Fk≥0F_1, \ldots, F_k \ge 0, in newborns per individual per step, counted as the newborns that are alive at the next census. The survival rates P1,…,Pk−1∈(0,1]P_1, \ldots, P_{k-1} \in (0, 1], with no unit. The survivorship to class ii is l1=1l_1 = 1 and li=P1P2⋯Pi−1l_i = P_1 P_2 \cdots P_{i-1}.

The update rule. nt+1=Lntn_{t+1} = L n_t with

L=(F1F2⋯Fk−1FkP10⋯000P2⋯00⋮⋱⋮00⋯Pk−10),L = \begin{pmatrix} F_1 & F_2 & \cdots & F_{k-1} & F_k \\ P_1 & 0 & \cdots & 0 & 0 \\ 0 & P_2 & \cdots & 0 & 0 \\ \vdots & & \ddots & & \vdots \\ 0 & 0 & \cdots & P_{k-1} & 0 \end{pmatrix},

that is, n1,t+1=∑iFini,tn_{1,t+1} = \sum_i F_i n_{i,t} and ni+1,t+1=Pini,tn_{i+1,t+1} = P_i n_{i,t}.

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 kk. The model is deterministic: it gives expected numbers. The value of FiF_i 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.

  1. PROJECT(F, P, n_0, T)
  2. 1n ← n_0
  3. 2for t ← 1 to T do
  4. 3n ← (F_1 n_1 + ... + F_k n_k, P_1 n_1, ..., P_(k-1) n_(k-1)) that is, n ← L n
  5. 4record n_t ← n
  6. 5return n_1, ..., n_T

Line L3 uses the structure of LL: it costs Θ(k)\Theta(k) per step, not the Θ(k2)\Theta(k^2) of a general matrix times a vector. So TT steps cost Θ(kT)\Theta(kT).

What it counts

  • The vector ntn_t and the total population Nt=∑ini,tN_t = \sum_i n_{i,t}.
  • The asymptotic growth rate λ1\lambda_1 per step, the dominant eigenvalue of LL. The population grows when λ1>1\lambda_1 > 1 and declines when λ1<1\lambda_1 < 1.
  • The stable age distribution ww, the right eigenvector of λ1\lambda_1, scaled to sum 1.
  • The reproductive values vv, the left eigenvector of λ1\lambda_1, scaled so that v1=1v_1 = 1. The value viv_i is the relative contribution of one individual of class ii to the future population.
  • The net reproductive rate R0=∑iFiliR_0 = \sum_i F_i l_i, the expected number of offspring of a newborn over its whole life.
  • The generation time Tˉ=∑iiFiliλ1−i\bar T = \sum_i i F_i l_i \lambda_1^{-i}, the mean age of the mothers of the newborns in the stable population.
  • The damping ratio λ1/∣λ2∣\lambda_1 / |\lambda_2|, which sets how fast the age structure approaches ww.
  • The sensitivities sij=∂λ1/∂Lijs_{ij} = \partial \lambda_1 / \partial L_{ij} and the elasticities eij=(Lij/λ1)sije_{ij} = (L_{ij} / \lambda_1) s_{ij}.

Relation to other models

  • Power iteration. Projecting the population is power iteration on LL. The ratio Nt+1/NtN_{t+1}/N_t tends to λ1\lambda_1, and nt/Ntn_t / N_t tends to ww, at the rate ∣λ2/λ1∣t|\lambda_2 / \lambda_1|^t.
  • Characteristic polynomial. For a Leslie matrix it has a closed form, λk−∑iFiliλk−i\lambda^k - \sum_i F_i l_i \lambda^{k-i}, 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, R0=∑iFiliR_0 = \sum_i F_i l_i is the next-generation count of newborns per newborn, and λ1>1\lambda_1 > 1 exactly when R0>1R_0 > 1.
  • Galton-Watson process. In a branching process with several types, where an individual of class ii has a random number of offspring with mean FiF_i and survives with probability PiP_i, the expected numbers follow the Leslie model, by linearity of expectation.
  • Markov chain. The survival part of LL 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. nt=Ltn0n_t = L^t n_0. Repeated squaring gives LtL^t in O(k3log⁡t)O(k^3 \log t) operations, which helps for large tt 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). det⁡(λI−L)=λk−∑i=1kFiliλk−i\det(\lambda I - L) = \lambda^k - \sum_{i=1}^{k} F_i l_i \lambda^{k-i}. For λ≠0\lambda \ne 0 the equation det⁡(λI−L)=0\det(\lambda I - L) = 0 is the Euler-Lotka equation ∑iFiliλ−i=1\sum_i F_i l_i \lambda^{-i} = 1. If some Fi>0F_i > 0, it has exactly one positive root, and the eigenvector of this root is wi∝liλ−(i−1)w_i \propto l_i \lambda^{-(i-1)}.

Proof. Expand det⁡(λI−L)\det(\lambda I - L) along the first row. If row 1 and column ii are removed, the rest is block diagonal with two triangular blocks, with −P1,…,−Pi−1-P_1, \ldots, -P_{i-1} and then k−ik - i copies of λ\lambda on the diagonal. So the minor is (−1)i−1liλk−i(-1)^{i-1} l_i \lambda^{k-i}, and with the sign (−1)1+i(-1)^{1+i} of the cofactor the expansion is λ⋅λk−1−∑iFiliλk−i\lambda \cdot \lambda^{k-1} - \sum_i F_i l_i \lambda^{k-i}. Division by λk\lambda^k gives the Euler-Lotka form. For the eigenvector, suppose Lw=λwL w = \lambda w with λ≠0\lambda \ne 0. The rows 2 to kk give wi+1=Piwi/λw_{i+1} = P_i w_i / \lambda, so wi=liλ−(i−1)w1w_i = l_i \lambda^{-(i-1)} w_1. The function φ(λ)=∑iFiliλ−i\varphi(\lambda) = \sum_i F_i l_i \lambda^{-i} is strictly decreasing on (0,∞)(0, \infty) from +∞+\infty to 0, so it takes the value 1 exactly once. □\square

The threshold (theorem). λ1>1\lambda_1 > 1 if and only if R0>1R_0 > 1, and λ1=1\lambda_1 = 1 if and only if R0=1R_0 = 1.

Proof. φ(1)=R0\varphi(1) = R_0 and φ\varphi is decreasing, so its root lies above 1 exactly when φ(1)>1\varphi(1) > 1. □\square

Perron-Frobenius for Leslie matrices (theorem and known result). If Fk>0F_k > 0, then LL is irreducible: every class leads to every other class. By the Perron-Frobenius theorem, λ1\lambda_1 is then positive and simple, no other eigenvalue has a larger modulus, and ww and vv are positive. If LL is also primitive, then ∣λj∣<λ1|\lambda_j| < \lambda_1 for every other eigenvalue and, for every nonzero n0≥0n_0 \ge 0, nt/λ1t→(v⊤n0/v⊤w) wn_t / \lambda_1^t \to (v^\top n_0 / v^\top w)\, w (theorem). It is a known result that an irreducible Leslie matrix is primitive exactly when the greatest common divisor of the ages ii with Fi>0F_i > 0 is 1. In particular, two adjacent fertile classes are enough.

Sensitivity and elasticity (theorem). ∂λ1/∂Lij=viwj/(v⊤w)\partial \lambda_1 / \partial L_{ij} = v_i w_j / (v^\top w), and the elasticities sum to 1.

Proof. Differentiate Lw=λ1wL w = \lambda_1 w and multiply on the left by v⊤v^\top. The terms with the derivative of ww cancel because v⊤L=λ1v⊤v^\top L = \lambda_1 v^\top, which leaves v⊤(∂L)w=(∂λ1) v⊤wv^\top (\partial L) w = (\partial \lambda_1)\, v^\top w. The sum of the elasticities is ∑ijLijviwj/(λ1v⊤w)=v⊤Lw/(λ1v⊤w)=1\sum_{ij} L_{ij} v_i w_j / (\lambda_1 v^\top w) = v^\top L w / (\lambda_1 v^\top w) = 1. □\square

An example with three classes. Take F=(0,1.5,1.0)F = (0, 1.5, 1.0) and P=(0.5,0.25)P = (0.5, 0.25), so

L=(01.51.00.50000.250),l=(1,0.5,0.125).L = \begin{pmatrix} 0 & 1.5 & 1.0 \\ 0.5 & 0 & 0 \\ 0 & 0.25 & 0 \end{pmatrix}, \qquad l = (1, 0.5, 0.125).

The characteristic equation is λ3−0.75λ−0.125=0\lambda^3 - 0.75 \lambda - 0.125 = 0. Multiplied by 4 it is 4λ3−3λ=0.54\lambda^3 - 3\lambda = 0.5, and with λ=cos⁡θ\lambda = \cos\theta the identity 4cos⁡3θ−3cos⁡θ=cos⁡3θ4\cos^3\theta - 3\cos\theta = \cos 3\theta gives cos⁡3θ=1/2\cos 3\theta = 1/2. So the eigenvalues are cos⁡(π/9)=0.939693\cos(\pi/9) = 0.939693, cos⁡(7π/9)=−0.766044\cos(7\pi/9) = -0.766044 and cos⁡(13π/9)=−0.173648\cos(13\pi/9) = -0.173648 (theorem). The net reproductive rate is R0=0.75+0.125=0.875<1R_0 = 0.75 + 0.125 = 0.875 < 1, and as the threshold theorem says, λ1<1\lambda_1 < 1: the population declines by about 6 percent per step. The fertile ages are 2 and 3 with greatest common divisor 1, so LL is primitive.

  • The stable age distribution is w=(0.597497,0.317922,0.084581)w = (0.597497, 0.317922, 0.084581).
  • The reproductive values are v=(1,1.879385,1.064178)v = (1, 1.879385, 1.064178). 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 Tˉ=2.150644\bar T = 2.150644 steps.
  • The elasticities of λ1\lambda_1 are 0.4649770.464977 for P1P_1, 0.3949310.394931 for F2F_2, and 0.0700460.070046 for both F3F_3 and P2P_2. So a given relative change in the survival of the young changes the growth rate most.
  • The damping ratio is 0.939693/0.766044=1.2266820.939693 / 0.766044 = 1.226682.

From n0=(100,0,0)n_0 = (100, 0, 0) the projection gives:

tt n1,tn_{1,t} n2,tn_{2,t} n3,tn_{3,t} NtN_t
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 λ2=−0.766044\lambda_2 = -0.766044 is negative and not much smaller than λ1\lambda_1 in modulus. The oscillation dies out only by a factor of about 1.231.23 per step.

An imprimitive example (theorem). Take F=(0,0,6)F = (0, 0, 6) and P=(1/2,1/3)P = (1/2, 1/3). Then L3=F3P1P2I=IL^3 = F_3 P_1 P_2 I = I, so the population repeats with period 3 and never reaches a stable distribution: (6,0,0)(6, 0, 0), (0,3,0)(0, 3, 0), (0,0,1)(0, 0, 1), (6,0,0)(6, 0, 0), and so on. Here R0=1R_0 = 1, λ1=1\lambda_1 = 1, 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, F=(0,2.481212,0,0.603468,0.973731,2.571316)F = (0, 2.481212, 0, 0.603468, 0.973731, 2.571316) and P=(0.739222,0.363252,0.069093,0.588705,0.566179)P = (0.739222, 0.363252, 0.069093, 0.588705, 0.566179), 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 Nt+1/NtN_{t+1}/N_t was 1.3698661.369866, still 0.70.7 percent away from λ1=1.359817\lambda_1 = 1.359817. 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.

leslie_matrix.pyI0RawGitHub
# 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

  1. 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)
  2. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/V3XCAW/text.yaml