Module contents
Lesson 1 of 27Core 100 min

Mathematical modeling: from phenomenon to equation

Before discretizing, decide which equation to simulate. Explore the modeling cycle, conservation and constitutive laws, nondimensionalization, deterministic and stochastic models, and a hierarchy of model fidelity.

After this lesson you can

  • Follow the modeling cycle for a concrete phenomenon, stating assumptions and their range of validity.
  • Derive a PDE from integral conservation and a constitutive relation such as Fick, Fourier or Darcy.
  • Nondimensionalize a model and obtain dimensionless groups using Buckingham's Pi theorem.
  • Construct and simulate SIR and Lotka–Volterra compartment models and analyze equilibria.
  • Choose between deterministic and stochastic models based on population size and objective.

Before you start

The equation is a decision

Suppose you want to predict an outbreak, the movement of a pollutant or an asset price. Before choosing an integrator, decide what the state represents, what exchanges it allows and which observations can test it. A very accurate numerical solution to an inappropriate equation does not answer the original question.

The modeling cycle begins with a question and domain of application. Formulate assumptions, construct equations and initial and boundary conditions, analyze their consequences, simulate, compare with independent observations and revise assumptions or parameters. Comparison can show that a model fails, but not which assumption is responsible. For example, well-mixed SIR can be a first approximation to a homogeneous population and fail when age, mobility or heterogeneous contacts matter. Each extension needs data that distinguish its parameters.

An ODE initial-value problem defines evolution from a state; under the Picard–Lindelöf theorem assumptions, that evolution is locally unique. Mathematical existence does not prove the assumptions describe the phenomenon. For a plume in a river, mass and its flux offer a more controllable starting point.

Balance before discretization

The figure uses an exact one-dimensional diffusion solution, c(x,t)=1+e−tcos⁡xc(x,t)=1+e^{-t}\cos x, with diffusivity D=1D=1. The rightward flux is j=−D∂xc=e−tsin⁡xj=-D\partial_x c=e^{-t}\sin x. If the interval is [a,b][a,b], mass per unit cross-section is M=∫abc  ⁣dxM=\int_a^b c\,\dd x and its derivative is exactly j(a)−j(b)j(a)-j(b). The values are not river data: they are a constructed solution for inspecting the balance.

InteractiveA region gaining or losing mass
0.20
Flux at left endpoint j(a)j(a)0.587
Flux at right endpoint j(b)j(b)0.490
Total change dM/dtdM/dt0.097
Change per length0.057
Drag both endpoints and change time. Flux on the left counts as input and on the right as output; their signs indicate direction. As length decreases, change per length approaches the local time derivative.

Balance does not determine flux: a constitutive relation is needed. For Fick diffusion, j=−D∇c\vb{j}=-D\nabla c with D>0D>0, so ∂tc=∇⋅(D∇c)+q\partial_t c=\nabla\cdot(D\nabla c)+q. If DD is constant this becomes DΔcD\Delta c. Fourier’s law uses the same sign for heat flux q=−k∇T\vb{q}=-k\nabla T, but the conserved density is energy rather than temperature: with constant volumetric capacity CC, C∂tT=∇⋅(k∇T)+QC\partial_t T=\nabla\cdot(k\nabla T)+Q. Darcy relates volumetric flux in porous media to the pressure gradient, u=−(κ/μ)∇p\vb{u}=-(\kappa/\mu)\nabla p, within its validity regime. A pressure equation also needs storage and mass balance. These relations are material approximations, not universal consequences of conservation.

The local limit of the first figure follows directly. Divide j(a)−j(b)j(a)-j(b) by b−ab-a and let both endpoints approach xx: the quotient tends to −∂xj(x,t)-\partial_xj(x,t) while average mass change tends to ∂tc(x,t)\partial_t c(x,t). Equality requires regularity; with discontinuities, the integral formulation remains meaningful even if classical derivatives do not exist. This distinction is essential for waves and shocks.

The PDE alone also does not close a diffusion problem. Specify c(x,0)c(x,0) and what happens at the boundary. A prescribed concentration fixes cc; prescribed flux fixes j⋅n\vb{j}\cdot\vb{n}; an impermeable boundary has zero normal flux. With an insulated boundary and no source, whole-domain balance conserves total mass even as concentration redistributes. If an algorithm loses mass there, discretization may be failing even when the curve looks smooth.

Scales and groups independent of units

For advection, diffusion and reaction, take c=Cc∗c=Cc^*, x=Lx∗x=Lx^* and t=(L/U)t∗t=(L/U)t^*, with U,L,C>0U,L,C>0. In ∂tc+U∂xc=D∂xxc−kc\partial_t c+U\partial_x c=D\partial_{xx}c-kc this gives

∂t∗c∗+∂x∗c∗=1Pe∂x∗x∗c∗−Da c∗,Pe=ULD,Da=kLU.\partial_{t^*}c^*+\partial_{x^*}c^*=\frac{1}{\mathrm{Pe}}\partial_{x^*x^*}c^*-\mathrm{Da}\,c^*,\qquad \mathrm{Pe}=\frac{UL}{D},\quad \mathrm{Da}=\frac{kL}{U}.

Nondimensionalization compares terms independently of meters or seconds. Péclet compares advective transport with diffusion, and Damköhler here compares transport time with reaction time. In fluids, Re=ρUL/μ\mathrm{Re}=\rho UL/\mu compares inertia and viscosity. Large or small values suggest dominant regimes, but do not justify deleting a term everywhere: small diffusion may still be decisive in a boundary layer. Changing the time scale to L2/DL^2/D changes coefficients and can be more informative when diffusion dominates.

Check units before calculating: UU has length per time, DD length squared per time and kk inverse time. Both UL/DUL/D and kL/UkL/U are pure numbers. The choice L/UL/U compares travel time L/UL/U with diffusion time L2/DL^2/D and reaction time 1/k1/k. If Pe=40\mathrm{Pe}=40, diffusion needs forty times the transport time to cover that scale, but this interpretation refers to the chosen model and scale, not every point in the domain.

A useful scale also accounts for numerical magnitudes. If one typical variable is 10610^6 and another 10−610^{-6}, one absolute threshold may be too strict for one and too loose for the other. Variables of order one make consistent tolerances easier to choose. There is no universal optimal scale: a thin layer may require another characteristic length specifically resolving that region.

InteractiveTwo bases, two descriptions of the same groups

Columns: force F, density ρ, velocity U, diameter d and viscosity μ. Rows: mass, length, time.

1.001.000.000.001.001.00−3.001.001.00−1.00−2.000.00−1.000.00−1.00

Null-space basis: each column contains exponents of a group.

1.000.00−1.001.00−2.001.00−2.001.000.00−1.00

Π₁ = F/(ρU²d²); Π₂ = ρUd/μ

Problem
Null-space basis
Rank3
Number of groups5 − 3 = 2
Change problem and basis. For the sphere, the second group is Reynolds and the first combines force with inertial scales; multiplying them gives another dimensionless group. For the pendulum, the alternate basis inverts the only group. The number of independent groups does not change.
Proof

The monomial’s dimension is Da\mat{D}\vb{a}, so it is dimensionless exactly when a∈null⁡D\vb{a}\in\nullsp\mat{D}. Rank–nullity gives n−kn-k independent exponents. Set z=log⁡q\vb{z}=\log\vb{q}: a change of units shifts z\vb{z} by a vector in im⁡D⊤\operatorname{im}\mat{D}\T. Invariance makes the relation constant on each orbit of those shifts. Coordinates aj⊤z=log⁡Πj\vb{a}_j\T\vb{z}=\log\Pi_j separate those orbits, since their joint kernel is im⁡D⊤\operatorname{im}\mat{D}\T. Therefore the relation depends only on Πj\Pi_j. The Pi theorem does not determine the function between groups or empirical coefficients.

∎

For example, for (F,ρ,U,d,μ)(F,\rho,U,d,\mu), with fundamental dimensions mass, length and time, the interactive’s matrix has rank 3. One basis produces F/(ρU2d2)F/(\rho U^2d^2) and ρUd/μ\rho Ud/\mu. Multiplying the first by the second changes basis through an invertible transformation without changing information. The null space and rank make the count explicit.

You can check the first group column by column. FF has dimensions MLT−2MLT^{-2}, while ρU2d2\rho U^2d^2 has (ML−3)(L2T−2)(L2)=MLT−2(ML^{-3})(L^2T^{-2})(L^2)=MLT^{-2}. In the second, ρUd\rho Ud and μ\mu both have dimensions ML−1T−1ML^{-1}T^{-1}. If force depends only on the other four quantities and the model is dimensionally homogeneous, this gives F/(ρU2d2)=f(Re)F/(\rho U^2d^2)=f(\mathrm{Re}) for some function ff. The analysis does not specify that function or guarantee four inputs suffice: a nearby wall or added roughness introduces other lengths and groups.

Compartments: population, predators and drug

A compartmental model assigns an aggregate state to each population or reservoir and describes their exchanges. In closed SIR, S,I,RS,I,R are susceptible, infected and recovered people; N=S+I+RN=S+I+R is constant. Homogeneous mixing and constant rates give

S˙=−βSI/N,I˙=βSI/N−γI,R˙=γI.\dot S=-\beta SI/N,\qquad \dot I=\beta SI/N-\gamma I,\qquad \dot R=\gamma I.

Each infection moves a person from SS to II, each recovery from II to RR. The three equations sum to zero. With β,γ>0\beta,\gamma>0, the equilibrium set in the physical region is I=0I=0. Near (S∗,0,N−S∗)(S_*,0,N-S_*), the initial rate of a small II is βS∗/N−γ\beta S_*/N-\gamma: it grows if R0S∗/N>1R_0S_*/N>1, with R0=β/γR_0=\beta/\gamma. In a fully susceptible population this is the mean number of secondary infections under these assumptions. At the threshold, linearization alone does not decide nonlinear dynamics; see stability by linearization and equilibria.

Units help avoid losing a population factor: β\beta and γ\gamma are rates per time in this incidence convention βSI/N\beta SI/N. If incidence is instead written bSIbSI, then bb has units of inverse person per time and R0=bN/γR_0=bN/\gamma at the start of a fully susceptible population. The two formulations describe the same equation when b=β/Nb=\beta/N; copying a parameter between conventions without that conversion changes the model.

For I>0I>0, dividing S˙\dot S by R˙\dot R eliminates time and gives  ⁣dS/ ⁣dR=−(β/γ)S/N\dd S/\dd R=-(\beta/\gamma)S/N. Integrating between the initial and a later state,

log⁡S(t)S(0)=−R0N(R(t)−R(0)).\log\frac{S(t)}{S(0)}=-\frac{R_0}{N}\bigl(R(t)-R(0)\bigr).

This relation lets us check the numerical unvaccinated SIR solution against an independent identity; it does not hold for the lab’s vaccinated extension. The infection peak, if it occurs in the interior of the trajectory, satisfies S=N/R0S=N/R_0. It does not guarantee the system crosses that value: if it already starts below, II decreases from the beginning. Nor does it say when the peak occurs; time must be recovered by integrating the dynamics.

For predators and prey, the classical Lotka–Volterra system x˙=αx−βxy\dot x=\alpha x-\beta xy, y˙=δxy−γy\dot y=\delta xy-\gamma y has positive parameters and states x,yx,y nondimensionalized with fixed population scales. Its equilibria are (0,0)(0,0) and (γ/δ,α/β)(\gamma/\delta,\alpha/\beta). In the positive interior it conserves

H(x,y)=δx−γln⁡x+βy−αln⁡y.H(x,y)=\delta x-\gamma\ln x+\beta y-\alpha\ln y.

The derivative of HH along the field is zero, as you will show below. Its nonminimal levels are closed curves around the interior equilibrium: the phase portrait consists of neutral cycles rather than an attracting spiral. Adding competition or seasonality can change this conclusion.

To see where equilibrium comes from, set x(α−βy)x(\alpha-\beta y) and y(δx−γ)y(\delta x-\gamma) to zero. In the interior, neither factor x,yx,y can vanish, so necessarily y=α/βy=\alpha/\beta and x=γ/δx=\gamma/\delta. The Jacobian there has zero diagonal and product of off-diagonal terms −αγ-\alpha\gamma, so its eigenvalues are ±iαγ\pm i\sqrt{\alpha\gamma}. This suggests oscillations but does not prove they are closed: that conclusion needs the first integral and compactness of its levels. At the origin, eigenvalues are α\alpha and −γ-\gamma, with opposite signs.

A one-compartment pharmacokinetic description with first-order elimination has A˙=−kA\dot A=-kA, where AA is amount and kk has inverse-time dimension. To introduce vaccination into SIR, suppose normalized amount q=A/A0q=A/A_0 decays as q˙=−kq\dot q=-kq and the susceptible vaccination rate is vqSvqS. This chosen law is a mechanistic example, not a clinical claim: it requires validation and a measurable definition of vv.

One trajectory or a distribution

In jump SIR, transitions (S,I)→(S−1,I+1)(S,I)\to(S-1,I+1) and (S,I)→(S,I−1)(S,I)\to(S,I-1) occur at rates βSI/N\beta SI/N and γI\gamma I. Between events, waiting time is exponential with the sum of rates. Deterministic and stochastic models answer different questions: the ODE gives an aggregate trajectory; the process gives a distribution of trajectories and extinction probabilities.

InteractiveSIR: ODE and jump processes
  • 24 jump trajectories
  • ODE
100
2.0
Initial state
No secondary infections8/24
Initial infected fraction0.010
Change NN, R0R_0 and the initial state. The 24 trajectories use the exponential waiting-time algorithm and the ODE uses RK4. Compare one infected person with an initial fraction of 5%: the counter records trajectories with no secondary infections, not all small outbreaks.

With one initially infected person, even for R0>1R_0>1 the first transition can be recovery. Its exact probability is γ/(γ+β(N−1)/N)\gamma/(\gamma+\beta(N-1)/N); it does not disappear as NN grows. Under density scaling with a fixed positive initial fraction, finite horizons and regularity conditions, typical fraction fluctuations instead have order N−1/2N^{-1/2} and the ODE is the large-population limit. Do not extrapolate that concentration to a single initially infected person: early dynamics there remain dominated by chance. Nor confuse E[SI]\E[SI] with E[S]E[I]\E[S]\E[I]: in general the process mean does not exactly satisfy the nonlinear ODE.

The difference between the two means appears directly in the moment equation. For the jump process, the expected rate of change of II is βE[SI]/N−γE[I]\beta\E[SI]/N-\gamma\E[I]. Since E[SI]=E[S]E[I]+Cov⁡(S,I)\E[SI]=\E[S]\E[I]+\Cov(S,I), replacing the product with the product of means discards covariance created by the dynamics themselves. Only under a closure approximation or suitable limit does the deterministic equation for fractions emerge. Dispersion across 24 trajectories illustrates the phenomenon, but that small set cannot precisely estimate a rare probability.

Lab: null space and SIR with vaccination

First compute a numerical null-space basis by SVD. Columns can contain fractional exponents and change sign or rotate between runs; check residual and dimension, not a particular basis. The calculation is small and runs in the browser.

[ ]Pi groups by SVDBrowser
import numpy as np

def kernel_svd(D):
    D = np.asarray(D, dtype=float)
    _, s, vh = np.linalg.svd(D, full_matrices=True)
    tol = max(D.shape) * np.finfo(float).eps * (s[0] if len(s) else 0)
    rank = np.count_nonzero(s > tol)
    return vh[rank:].T

D = np.array([[1, 1, 0, 0, 1], [1, -3, 1, 1, -1], [-2, 0, -1, 0, -1]])
B = kernel_svd(D)
print('forma de la base:', B.shape)
print('residuo máximo:', np.max(np.abs(D @ B)))

Now solve vaccinated SIR in dimensional and nondimensional form. With s=S/Ns=S/N, i=I/Ni=I/N, r=R/Nr=R/N, τ=γt\tau=\gamma t and q=A/A0q=A/A_0, this leaves R0=β/γR_0=\beta/\gamma, ν=v/γ\nu=v/\gamma and κ=k/γ\kappa=k/\gamma. Eliminating the time scale reduces the original four rates to three ratios. The sum s+i+r=1s+i+r=1 independently checks both solutions.

[ ]Vaccination and time scalingBrowser
from scipy.integrate import solve_ivp
import numpy as np

beta, gamma, v, k = 0.4, 0.2, 0.1, 0.05
N = 1000.0
initial = np.array([990.0, 10.0, 0.0, 1.0])
def dimensional(t, y):
    S, I, R, q = y
    inf = beta*S*I/N
    vac = v*q*S
    return [-inf-vac, inf-gamma*I, gamma*I+vac, -k*q]

def scaled(tau, y):
    s, i, r, q = y
    inf = (beta/gamma)*s*i
    vac = (v/gamma)*q*s
    return [-inf-vac, inf-i, i+vac, -(k/gamma)*q]

times = np.linspace(0, 30, 121)
opts = dict(rtol=1e-10, atol=1e-12)
dim = solve_ivp(dimensional, (0, 30), initial, t_eval=times, **opts).y
adim = solve_ivp(scaled, (0, gamma*30), initial/np.array([N,N,N,1]), t_eval=gamma*times, **opts).y
converted = dim / np.array([N,N,N,1])[:,None]
print('error máximo entre sistemas:', np.max(np.abs(converted-adim)))
print('error máximo de conservación:', np.max(np.abs(adim[:3].sum(axis=0)-1)))
print('estado final s, i, r, q:', np.round(adim[:,-1], 6))

Numerical agreement verifies that this implementation was transformed correctly for this case. It does not validate the vaccination law against real data. To test a real model, separate data used to estimate parameters from data reserved to evaluate predictions; document observation uncertainty and regime changes.

The second experiment integrates Lotka–Volterra from a positive point and checks conservation of HH along the trajectory. The numerical curve can show small drift: finite tolerance does not make the integrator exactly conserve that quantity. Compare with a coarser tolerance and repeat, rather than interpreting drift as actual population mortality.

[ ]Lotka–Volterra orbit and conservationBrowser
from scipy.integrate import solve_ivp
import numpy as np

alpha, beta_lv, gamma_lv, delta = 1.0, 0.5, 0.75, 0.25
def predator_prey(t, z):
    x, y = z
    return [alpha*x-beta_lv*x*y, delta*x*y-gamma_lv*y]

ts = np.linspace(0, 30, 301)
orbit = solve_ivp(predator_prey, (0, 30), [4.0, 1.0], t_eval=ts, rtol=1e-9, atol=1e-11)
assert orbit.success and np.all(orbit.y > 0)
x, y = orbit.y
H = delta*x-gamma_lv*np.log(x)+beta_lv*y-alpha*np.log(y)
print('equilibrio interior:', gamma_lv/delta, alpha/beta_lv)
print('desviación máxima de H:', np.max(np.abs(H-H[0])))
print('rangos x e y:', np.round([x.min(), x.max(), y.min(), y.max()], 5))

This checks that trajectory and tolerance; it does not measure observed populations. A family of initial conditions produces different levels of HH; their amplitudes cannot be inferred from equilibrium alone.

Fidelity and interpretation errors

A fidelity hierarchy gathers models with different costs and approximations for the same quantity of interest. A detailed spatial simulation can be high fidelity relative to a well-mixed ODE; a reduced model retains selected simulation modes, and a surrogate learns or interpolates its response. Fidelity is relative to the question and data: increasing resolution does not fix incorrect physics. Cheap models help explore parameters, but must be checked where they are used.

Cost is not the only axis. A spatial PDE may introduce unknown transport coefficients, geometry and boundary conditions; if two parameter combinations give indistinguishable predictions for available observations, those parameters are not identifiable from that experiment. A less detailed model may predict better over the observed interval and fail when extrapolated. Record the intended quantity to predict, which data calibrate each parameter and which observations are reserved for comparison.

Exercises

ProofWhy there are n minus k groups
Prove: Justify the Pi theorem for positive quantities and a dimensional matrix of rank k.
0
A change of units shifts the logarithm of quantities in the image of the transpose of the dimensional matrix.

Step 1 of 3. What condition makes a monomial dimensionless?

NumericPollutant in a river
With velocity U=0.2U=0.2 m/s, length L=100L=100 m and effective diffusivity D=0.5D=0.5 m²/s, calculate Pe=UL/D\mathrm{Pe}=UL/D.
CodeAn integer null-space basis
Implement dimensionless_groups(D): return a matrix whose columns form an integer null-space basis of the integer dimensional matrix D. Integer multiples of rational basis vectors are accepted; a primitive lattice basis is not required.
def dimensionless_groups(D):
  pass
Shift+Enter to run
QuizWhen does discreteness matter?
You compare tumor populations of 3000 and 10⁹ cells. You care about the probability that a subpopulation of a few cells disappears. Which choice is justified?
ProofThe first integral
Prove: Prove H is conserved in the positive interior and its nonminimal levels are closed orbits.
0
Let α, β, γ, δ be positive and x, y positive.

Step 1 of 3. What is the derivative along a solution?

What remains

Key idea
A model is a chain of testable decisions: conservation fixes the balance, constitutive laws close it, scales reveal regimes and observations test the whole.

Dimensional analysis reduces variables but does not invent a law. An ODE and a jump process can share rates and answer different questions. The next lesson studies solving an ODE with error control; that numerical verification remains distinct from validation against the phenomenon.