One slope per step. Simple, but its error grows with the step, and large steps can push a compartment below zero.
Epidemic ModelingPolicy and practice
Module 12Computational considerations
The computer side of epidemic modeling. With our own code and timings, we write one agent model in four languages and check that all give the same answer, keep a model's parts apart and catch a planted bug with a conservation test, see Euler's method overshoot and go negative while Runge–Kutta holds, meet stiff models and the solvers built for them, compare exact and tau-leaping stochastic simulation, speed code up by profiling, better algorithms, batching and sparse structure, and calibrate at scale with exact gradients, emulators and history matching.
Key ideas, one per episode
- Ep. 49The same model ran about 40 times faster in C than in plain Python loops, with the same answer; a planted bug left the infection curve perfect and was caught by a one-line conservation check.
- Ep. 50Euler with 7-day steps overshot the peak by 60% and went below zero; Runge–Kutta with 4-day steps stayed within 0.1%. A stiff solver needed about 30 times fewer evaluations.
- Ep. 51A grid of cells gave the same epidemic as checking every pair, 8.6 times faster for 2,000 people; batching was 85 times faster, and a sparse network needed 12 MB instead of 80 GB.
- Ep. 52With exact gradients a 26-parameter fit took 75 runs instead of about 2,000; an emulator trained on 50 runs ruled out half of the settings in under a hundredth of a second.
Textbook: Chapter 12 of T. Lazebnik, Epidemic Modeling: Principles, Algorithms, and Applications (Academic Press, 2026). The episodes and slides follow the chapter’s topics in our own words, figures and simulations; nothing is copied from the book.
Watch
4 short episodes for this module. Pick one from the list, and open the transcript to read along: each timestamp plays the episode from there. The narration is generated with a voice clone of Teddy, used with his permission.
Episode 49 · 2:35
Languages, libraries and architecture
The computer side of epidemic modeling: one agent-based model written in plain Python, NumPy, JavaScript and C and timed, why tested libraries matter, how to keep a model's parts apart, and a planted bug that only a conservation check catches.
The same model ran about 40 times faster in C than in plain Python loops, with the same answer; a planted bug left the infection curve perfect and was caught by a one-line conservation check.
TranscriptEpisode 49
Same math, different code. The same epidemic model can take a tenth of a second to run, or a few thousandths. Same math, different code. Welcome to Module twelve: the computer side of epidemic modeling.
One model, four languages. Choosing a language is a trade between how fast the code runs and how fast you can write it. We wrote one agent based model, ten thousand people for two hundred days, four times: in plain Python, in Python with NumPy, in JavaScript, and in C. C ran a whole epidemic in under four thousandths of a second. Plain Python loops took almost forty times longer. NumPy, which hands the loops to compiled code, came within a factor of two of C. JavaScript, which runs the labs on our website, was not far behind. And all four agreed: about ninety two percent of the town infected. That's the first rule: a faster version is only worth having if it gives the same answer.
Libraries. Libraries matter as much as languages. Well used solvers, random number generators and statistics packages have been tested by thousands of people. Writing your own is a great way to learn, and a risky way to publish.
Architecture. Then architecture. Keep the parts of a model apart: the transmission mechanism, the parameters, the observation model that turns infections into reported cases, the inference code, and the outputs. Each part can then be tested, swapped and reused. Settings live in files, not inside the code, so every run records exactly what it used: the parameters, the data version, and the random seed.
Test the model. And test the model, not just the code. Here's a bug we planted on purpose: one term in an SEIR model takes recoveries from the exposed group, instead of the infectious group. The infection curve looks perfect: same peak, same day. But people are quietly disappearing. By the end, the town has lost more than a third of its population. A one line check, does everyone still add up to the whole town, flags it at the very first step. Another check compares the final size with the formula from Module three; a correct model agrees to within a millionth. Checks like these, run automatically after every change, catch exactly the errors that look plausible.
Next. Next: numerical stability, and how a bigger time step can make your epidemic go negative.
Right model, wrong solver. Your model can be right, and your solver wrong. The same equations, solved with a careless step size, can give the wrong peak, or even a negative number of people.
Euler and Runge–Kutta. Take our SIR town. R₀ is 2.5, and people stay infectious for five days. Solved with tiny steps, the epidemic peaks with twenty three percent of the town infectious, on day thirty two. Euler's method, the simplest solver, follows the slope for one whole step. With one day steps it overshoots the peak by six and a half percent. With seven day steps, by sixty percent, and the number infectious drops below zero. Runge Kutta of order four averages four slopes per step. With two day steps it lands within a hundredth of a percent of the peak; even with four day steps, within a tenth.
Stiff models. Some models are stiff: they mix very fast and very slow processes. Add a one hour triage step before hospital to our town. Euler now needs steps under two hours just to stay stable. With steps of a tenth of a day, the numbers swing and blow up. An adaptive solver built for smooth problems survives, but needs about eighteen and a half thousand evaluations for one year. Solvers built for stiff problems need about six hundred and forty, for the same answer: almost thirty times less work.
Daily steps. Discrete time models hide a quieter trap. A model that steps one day at a time is a different model, not an approximation. Turning the daily rates into daily probabilities stretched the average infectious time by half a day, to five and a half days. That quietly raised R₀ to 2.76. The continuous model had 2.5. The peak climbed too. It reached twenty seven percent instead of twenty three. Nothing crashed. The numbers were just different.
Exact and approximate randomness. Stochastic models have their own trade off. Gillespie's algorithm is exact: it simulates every single event. For a town of ten thousand, that's almost eighteen thousand events per epidemic. Tau leaping jumps ahead in fixed steps and draws many events at once. With steps of a tenth of a day, it matched the exact method closely. With four day steps, the final size rose to ninety six percent, where the exact answer is eighty nine. And most runs tried to remove more people than there were. So build in guards: no compartment below zero, everyone accounted for, and a check that a step half as long barely changes the answer.
Next. Next: making it fast. Where the time goes, and how to win it back.
Measure first. Before you make code faster, find out where the time goes. The answer is rarely where you'd guess.
The obvious version. Our town of agents lives on a map: people infect neighbors within a short distance. The first version is the obvious one. Every day, every infectious person checks every person in town. A profiler measures where the time goes. For a town of two thousand, it pointed at one place: the pair check, called more than nine million times in a single epidemic, inside a loop over every pair.
A better algorithm. So change the algorithm. Divide the map into cells as wide as the contact distance; then each person checks only the nine cells around them. We fixed every random draw in advance, so both versions must give the same epidemic, to the last person. They did. For two thousand people, the grid ran about eight and a half times faster. And the gap keeps growing: the obvious version's work grows with the square of the town, the grid's only in proportion to it.
Work in bulk. Next, let the computer work in bulk. Running a thousand parameter sets one at a time took two and a half seconds. The same thousand as one batch of arrays took three hundredths of a second: eighty five times faster, with identical numbers. Small habits matter too. Growing an array one value at a time copies it again and again: about seventy times slower than filling an array made in advance.
Structure, sparsity, parallel. And use the structure of the problem. A contact network of a hundred thousand people, with about ten contacts each, stored as a full table, needs eighty gigabytes. Stored as a list of who knows whom: twelve megabytes. One step of the epidemic then takes about a millisecond. When people mix in proportion to their activity, the mixing matrix collapses into two vectors. For three thousand groups, the force of infection came out more than a thousand times faster, with the same result. Parallel computers help with the rest, but only with the part that can run in parallel. If a twentieth of the work is serial, sixty four cores give you about fifteen times, and no number of cores gives more than twenty. Measure first, fix the algorithm, then the habits, and check the answer after every step.
Next. Next: calibration at scale, when every run of the model costs real time.
Can you afford it?. Fitting a model means running it again and again. When one run takes seconds, the question is no longer how to fit it, but whether you can afford to.
The arithmetic of runs. Here's the arithmetic. Our SIR equations take about a hundredth of a second per run. Our agent town of sixteen thousand people, about two seconds. Twenty thousand steps of a Bayesian sampler: about three minutes for the equations, about eleven hours for the agents. A million runs for approximate Bayesian computation: a couple of hours, or about three weeks.
Gradients. So make every run count. Gradients help most: they tell the optimizer which way is downhill in every direction at once. We fitted a separate transmission rate for each of twenty six weeks to half a year of noisy cases. Without gradients, Nelder Mead used twenty thousand runs and still hadn't finished. With gradients from finite differences, a quasi Newton method finished in about two thousand. With exact gradients, from sensitivity equations solved alongside the model, it took seventy five. Automatic differentiation tools can build those derivatives straight from a model's code. We checked ours against finite differences: they agreed to about one part in a billion, at the right step size.
Emulators and history matching. When even that is too slow, train an emulator: a fast statistical stand in for the simulator. We ran the agent town fifty times, at well spread settings, and fitted a Gaussian process to the results. On sixty new runs, it predicted the share infected to within about seven points on average, and its ninety percent intervals caught eighty eight percent of the truths. Then history matching: rule out every setting the emulator says cannot reproduce the observed epidemic. Half of the ten thousand settings were ruled out in under a hundredth of a second; simulating them all would take about three hours. We checked twenty of the settings it kept, and four reproduced the epidemic. Not one of twenty ruled-out settings did. History matching doesn't finish the job. It shrinks the search, safely, so the expensive runs go where they can matter.
In this order. Correct first, then stable, then fast, and only then at scale. A speed up is worth nothing if the answer changes.
Next. That closes Module twelve. Next, the final episode: where epidemic modeling goes from here.
2:35Episode 49 · 12.1Languages, libraries and architectureThe same model ran about 40 times faster in C than in plain Python loops, with the same answer; a planted bug left the infection curve perfect and was caught by a one-line conservation check.
2:55Episode 50 · 12.2Numerical stabilityEuler with 7-day steps overshot the peak by 60% and went below zero; Runge–Kutta with 4-day steps stayed within 0.1%. A stiff solver needed about 30 times fewer evaluations.
2:43Episode 51 · 12.3Making it fastA grid of cells gave the same epidemic as checking every pair, 8.6 times faster for 2,000 people; batching was 85 times faster, and a sparse network needed 12 MB instead of 80 GB.
2:38Episode 52 · 12.4Calibration at scaleWith exact gradients a 26-parameter fit took 75 runs instead of about 2,000; an emulator trained on 50 runs ruled out half of the settings in under a hundredth of a second.
Interactive lab
Step sizes and chance
Change the step size of Euler's method and of Runge–Kutta on the module's SIR town, and run hundreds of exact or tau-leaping stochastic outbreaks in towns of different sizes.
The first panel solves the module's SIR town with the step you choose and compares it with a solution made of tiny steps; the second runs 200 stochastic outbreaks, exactly or with tau-leaping. Everything runs in your browser.
Step sizes and chance
The module's SIR town solved with two classic methods, and the same town simulated person by person. Everything runs in your browser.
Four slopes per step, weighted 1, 2, 2, 1. Its error shrinks with the fourth power of the step.
Tau-leaping draws many events per fixed step instead: much faster, but big steps distort the epidemic.
Solving…
Share of the town infectious
Green: tiny steps. Orange: Euler. Blue: Runge–Kutta. Dots mark the steps.
Challenges
Each one is checked on your current settings, in its own panel.
- Make Euler push the number of infectious people below zero.
- Find a step of at least 2 days where Runge–Kutta's peak is within 1% while Euler's is off by more than 10%.
- Chance: with one first infection and R₀ = 2, run the exact method in a town of at least 1,000. About half the runs should fizzle out (between 40% and 60%).
- Chance: use tau-leaping with steps of at least 2 days and find settings where more than half the runs try to remove more people than there are.
Running…
25 runs and the equations
Thin lines: share infectious in single runs. Dark line: the equations.
