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, , with diffusivity . The rightward flux is . If the interval is , mass per unit cross-section is and its derivative is exactly . The values are not river data: they are a constructed solution for inspecting the balance.
Balance does not determine flux: a constitutive relation is needed. For Fick diffusion, with , so . If is constant this becomes . Fourier’s law uses the same sign for heat flux , but the conserved density is energy rather than temperature: with constant volumetric capacity , . Darcy relates volumetric flux in porous media to the pressure gradient, , 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 by and let both endpoints approach : the quotient tends to while average mass change tends to . 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 and what happens at the boundary. A prescribed concentration fixes ; prescribed flux fixes ; 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 , and , with . In this gives
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, 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 changes coefficients and can be more informative when diffusion dominates.
Check units before calculating: has length per time, length squared per time and inverse time. Both and are pure numbers. The choice compares travel time with diffusion time and reaction time . If , 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 and another , 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.
Proof
The monomial’s dimension is , so it is dimensionless exactly when . Rank–nullity gives independent exponents. Set : a change of units shifts by a vector in . Invariance makes the relation constant on each orbit of those shifts. Coordinates separate those orbits, since their joint kernel is . Therefore the relation depends only on . The Pi theorem does not determine the function between groups or empirical coefficients.
∎For example, for , with fundamental dimensions mass, length and time, the interactive’s matrix has rank 3. One basis produces and . 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. has dimensions , while has . In the second, and both have dimensions . If force depends only on the other four quantities and the model is dimensionally homogeneous, this gives for some function . 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, are susceptible, infected and recovered people; is constant. Homogeneous mixing and constant rates give
Each infection moves a person from to , each recovery from to . The three equations sum to zero. With , the equilibrium set in the physical region is . Near , the initial rate of a small is : it grows if , with . 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: and are rates per time in this incidence convention . If incidence is instead written , then has units of inverse person per time and at the start of a fully susceptible population. The two formulations describe the same equation when ; copying a parameter between conventions without that conversion changes the model.
For , dividing by eliminates time and gives . Integrating between the initial and a later state,
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 . It does not guarantee the system crosses that value: if it already starts below, 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 , has positive parameters and states nondimensionalized with fixed population scales. Its equilibria are and . In the positive interior it conserves
The derivative of 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 and to zero. In the interior, neither factor can vanish, so necessarily and . The Jacobian there has zero diagonal and product of off-diagonal terms , so its eigenvalues are . 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 and , with opposite signs.
A one-compartment pharmacokinetic description with first-order elimination has , where is amount and has inverse-time dimension. To introduce vaccination into SIR, suppose normalized amount decays as and the susceptible vaccination rate is . This chosen law is a mechanistic example, not a clinical claim: it requires validation and a measurable definition of .
One trajectory or a distribution
In jump SIR, transitions and occur at rates and . 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.
With one initially infected person, even for the first transition can be recovery. Its exact probability is ; it does not disappear as grows. Under density scaling with a fixed positive initial fraction, finite horizons and regularity conditions, typical fraction fluctuations instead have order 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 with : 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 is . Since , 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.
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 , , , and , this leaves , and . Eliminating the time scale reduces the original four rates to three ratios. The sum independently checks both solutions.
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 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.
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 ; 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
Step 1 of 3. What condition makes a monomial dimensionless?
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):
passStep 1 of 3. What is the derivative along a solution?
What remains
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.