LSMA

LONDON SCHOOL OF MULTIOMICS & AI

Free course

Free course

0 of 73 lessons

Lesson 7 of 9

Module 7 · From genes to function

Simulating biology: models, agents and digital twins

Simulating biology: models, agents and digital twins

Simulating biology: models, agents and digital twins

Equation models follow averages; agent-based models follow individual cells, with space and chance. Build a tiny infection model in Python, see where such models are used in immunology and vaccines, and learn how a model earns trust.

⏱ 16 min readModule 7 · From genes to functionFree
Lesson at a glance8 steps · about 16 min
  1. Why simulate biology
  2. Equation models: counting groups
  3. Agent-based models: simulating individuals
  4. A tiny agent-based model
  5. The equation version
  6. Where these models are used in immunology and vaccines
  7. Digital twins
  8. Can we trust a model? Validation and regulation

Why simulate biology

The lessons from Finding genes and annotating a genome to Why multi-omics, and how layers are integrated described what is in a cell and how the parts connect. A model goes one step further: it writes down, explicitly, how the parts behave, so that a computer can run the system forward in time. A good model lets you ask "what if?" questions that would be slow, costly or unethical to test directly. What if the vaccine dose were halved? What if immune cells arrived a day later? A model is never the real system. It is a precise statement of what you believe, and running it shows whether those beliefs produce what is actually seen.

There are two main families, and the difference between them is the subject of this lesson.

The models here are mechanistic: each part of them stands for something real, such as a rate of infection or a cell's chance of being cleared. That sets them apart from the statistical models used in enrichment analysis (Pathways and enrichment analysis) or the machine-learning models of the next module, which find patterns in data without saying how the system works. A mechanistic model can be wrong in instructive ways: when its prediction misses, you can ask which rule or rate was mistaken, and that question is itself a hypothesis to test.

Models also extend the networks of Biological networks and systems biology. A network says which proteins connect; a model of the same pathway adds how fast each step runs, so that you can ask what happens over time when one node is blocked, rather than only whether the network falls apart.

Equation models: counting groups

An equation model divides the system into groups, often called compartments, and writes how fast individuals move between them. A classic example from infectious disease is the SIR model: people are Susceptible, Infected or Recovered, and two rates say how fast infection spreads and how fast people recover. Because the equations describe change over time, they are called differential equations.

The rates have a plain meaning that helps when you choose them. If the recovery rate is 0.2 per day, then on average a person stays infected for 1 ÷ 0.2 = 5 days. If a model gives a period of infection far from what is seen in patients, one of its rates is wrong, whatever else it gets right. Checking each parameter against something measurable in this way is one of the simplest ways to catch a faulty model before you trust its predictions.

Equation models are fast, need few parameters and can often be solved on paper. The SIR model gives the famous basic reproduction number, R0, the average number of new infections caused by one infected individual in a fully susceptible population. If R0 is 4, then vaccinating a share of 1 − 1/4 = 75% of the population stops sustained spread; this is the herd-immunity threshold. Equation models of how a drug is absorbed, spread through the body and removed (pharmacokinetics) are a routine part of drug development.

Their key assumption is that each group is well mixed: every individual is equally likely to meet every other, and everyone in a group is the same. The equations follow averages. They have no individuals, no space and no luck.

This assumption is often good enough. In a large, well-mixed population, such as a virus spreading through the bloodstream or a drug dissolved in plasma, chance evens out and averages describe the system well. It breaks down when numbers are small, when position matters, or when individuals differ a great deal: the first few infected cells in a tissue, a tumour pushing into its surroundings, or a disease spreading through a population where a few people have far more contacts than the rest.

The SIR framework goes back to Kermack and McKendrick 1927, Proceedings of the Royal Society of London A. The standard textbook is Anderson and May 1991, Infectious Diseases of Humans, Oxford University Press. Read the herd-immunity formula with its assumptions in mind. The threshold 1 − 1/R0 assumes a well-mixed population and a vaccine that fully blocks transmission. If a vaccine prevents only a share E of infections, the coverage needed rises to (1 − 1/R0) ÷ E: for R0 = 4 and E = 0.9, about 83%. R0 itself is not a fixed property of a pathogen; it depends on the population and its behaviour.

Agent-based models: simulating individuals

An agent-based model (ABM) simulates each individual, or agent, separately. An agent can be a cell, a virus particle, a person or a bacterium. Each agent follows simple rules ("if a neighbour is infected, become infected with probability 0.3"), lives in a space, and can differ from the others. Random chance enters through the rules, so the model is stochastic: two runs with the same rules can turn out differently.

The appeal is emergence: patterns at the level of the whole, such as the shape of a tumour or the spread of an infection through tissue, arise from local rules that never mention them. The cost is that ABMs have many parameters, are slow to run, and must be run many times to see the range of outcomes.

Many parameters bring a specific pitfall. With enough adjustable rules, an agent-based model can be tuned to reproduce almost any pattern, which is the modelling version of overfitting from Why multi-omics, and how layers are integrated. So a good ABM keeps its rules few, takes as many parameters as possible from measurements, such as how fast a particular cell type moves or divides, and leaves only a small number to be fitted.

Simulating biology: models, agents and digital twins · LSMA free course Left: an equation model with three boxes, healthy, infected and cleared, joined by arrows labelled with rates; it tracks only the number in each box. Right: an agent-based model drawn as a grid of cells, with a patch of infected cells in the centre surrounded by cleared cells and healthy cells further out; each cell follows rules about its four neighbours. 1 · EQUATION MODEL 2 · AGENT-BASED MODEL HealthyInfectedCleared countcountcount spread rateclearing rate Tracks three numbers over time. Assumes everyone meets everyone; same result every run. healthy infected cleared Each cell checks its 4 neighbours. Chance enters every step.
The same infection seen two ways. The equation model keeps only three totals. The agent-based model keeps every cell and where it sits, so infection can only move to neighbours, and cleared cells in the middle block its path. Schematic.

How to read this figure

On the left, arrows show movement between groups, and each arrow has one rate. On the right, each square is one epithelial cell, an agent. The infection started in the centre; the grey cells there have been cleared by the immune system, and the infected cells have moved to the edge of the patch. Nothing in the rules says "make a ring"; the ring emerges because infection can only reach neighbours.

A tiny agent-based model

The code below needs only numpy, already in Colab. It simulates a sheet of 31 × 31 = 961 cells. One cell in the middle starts infected. At each step, every infected cell tries to infect each healthy neighbour with probability p_spread, and is then killed by an immune cell with probability p_clear. The rules are made up for teaching and are not fitted to any real virus.

Python
import numpy as np

HEALTHY, INFECTED, DEAD = 0, 1, 2

def run(p_spread, p_clear, seed, size=31, steps=30):
    rng = np.random.default_rng(seed)
    grid = np.zeros((size, size), dtype=int)       # every cell is an agent
    grid[size // 2, size // 2] = INFECTED          # one infected cell
    for _ in range(steps):
        new = grid.copy()
        for r, c in zip(*np.where(grid == INFECTED)):
            for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:   # 4 neighbours
                rr, cc = r + dr, c + dc
                if 0 <= rr < size and 0 <= cc < size and grid[rr, cc] == HEALTHY:
                    if rng.random() < p_spread:
                        new[rr, cc] = INFECTED
            if rng.random() < p_clear:             # killed by an immune cell
                new[r, c] = DEAD
        grid = new
    return (grid == INFECTED).sum(), (grid == DEAD).sum()

infected, dead = run(p_spread=0.3, p_clear=0.2, seed=1)
print("After 30 steps:", infected, "infected,", dead, "cleared, of", 31 * 31)

What this does

  • HEALTHY, INFECTED, DEAD = 0, 1, 2 gives names to the three states, stored as numbers in a grid.
  • run is a function: a named block of code you can call again with different settings. np.zeros((size, size)) makes the grid, all healthy, and one centre cell is set to infected.
  • Each step works on a copy, new, so that cells infected during a step only start spreading on the next one. np.where(grid == INFECTED) finds the row and column of every infected cell.
  • The inner loop visits the four neighbours above, below, left and right. 0 <= rr < size stops cells at the edge looking off the grid. rng.random() draws a number between 0 and 1; if it is below p_spread, the neighbour is infected.
  • The function returns how many cells are infected and how many have been cleared at the end.
After 30 steps: 131 infected, 316 cleared, of 961

Reading the output

After 30 steps, 131 cells are still infected and 316 have been cleared, so 447 of the 961 cells, just under half, have been infected at some point. The infection is still spreading at the edge of the patch. With seed=1 you will get exactly these numbers; with another seed you will not, which the next block explores.

Python
for p_clear in [0.2, 0.5]:
    hit = [sum(run(0.3, p_clear, seed)) for seed in range(20)]
    died_out = sum(h < 10 for h in hit)
    print(f"p_clear {p_clear}: cells ever infected, median {int(np.median(hit))},"
          f" range {min(hit)}-{max(hit)}; died out early in {died_out} of 20 runs")

What this does

  • For two clearing rates, the model is run 20 times with seeds 0 to 19, and sum(...) adds infected and cleared to give the number of cells ever infected in each run.
  • sum(h < 10 for h in hit) counts the runs in which fewer than 10 cells were ever infected: the infection died out almost at once.
p_clear 0.2: cells ever infected, median 391, range 1-513; died out early in 1 of 20 runs p_clear 0.5: cells ever infected, median 18, range 1-107; died out early in 7 of 20 runs

Reading the output

With slow clearing (0.2), the infection usually spreads widely, with a median of 391 cells, but even here one run in 20 died out at once; a range starting at 1 means the first cell was cleared before it infected anyone. With fast clearing (0.5), the median falls to 18 cells and 7 of 20 infections fizzle out. Same rules, very different fates: this is chance acting on small numbers, and it matters in biology because every infection begins with a few cells. Always report the spread of many runs, never one.

The equation version

For comparison, here is a well-mixed equation model with matched settings. Each infected cell has 4 neighbours and infects each with probability 0.3, so it makes 4 × 0.3 = 1.2 contacts that count per step.

Python
def equations(beta, p_clear, n=961, steps=30):
    s, i, d = n - 1.0, 1.0, 0.0                 # healthy, infected, cleared
    for _ in range(steps):
        new_inf = beta * i * s / n              # contacts with healthy cells
        new_clear = p_clear * i
        s, i, d = s - new_inf, i + new_inf - new_clear, d + new_clear
    return round(i + d)

for p_clear in [0.2, 0.5]:
    print(f"p_clear {p_clear}: cells ever infected = {equations(1.2, p_clear)}")

What this does

  • s, i and d are the numbers healthy, infected and cleared. They are decimals, because equations track averages, not whole cells.
  • Each step, new infections are beta * i * s / n: proportional to the infected, and to the share of the population still healthy, as if any cell could meet any other. A share p_clear of the infected is cleared.
p_clear 0.2: cells ever infected = 961 p_clear 0.5: cells ever infected = 879

Reading the output

The equation model predicts that infection sweeps through all 961 cells with slow clearing and 879 even with fast clearing, every time, because it has no chance and no space. The agent-based model gave medians of 391 and 18. The difference comes from the well-mixed assumption: in the grid, an infected cell is soon surrounded by cells that are already infected or cleared, so it has few healthy neighbours left to infect. Neither model is "right"; the question is which assumptions fit the tissue you are studying.

Worked example · how many cells does one infected cell infect?

chance a neighbour is infected before the cell is cleared = 0.3 ÷ (1 − 0.7 × (1 − p_clear))
p_clear 0.2: 0.3 ÷ 0.44 = 0.68 · × 3 free neighbours = 2.0
p_clear 0.5: 0.3 ÷ 0.65 = 0.46 · × 3 free neighbours = 1.4

This is the grid's version of a reproduction number: the average number of cells one infected cell goes on to infect.

Step by step. Take one healthy neighbour. Each step, it is infected with probability 0.3. If not (0.7), the infected cell must also survive clearing, with probability 1 − pclear, for there to be another try. With pclear = 0.2, the chance of another try is 0.7 × 0.8 = 0.56, and adding up all the tries gives 0.3 ÷ (1 − 0.56) = 0.68. With pclear = 0.5, it is 0.7 × 0.5 = 0.35, giving 0.3 ÷ 0.65 = 0.46. A newly infected cell usually has at most 3 healthy neighbours, because one neighbour infected it. Multiply by 3.

What the answer means. In the grid, each infected cell infects at most about 2.0 or 1.4 others, and fewer once neighbours are used up. A value of 1.4 is only just above 1, so an early run of bad luck often ends the infection, which is why 7 of 20 runs fizzled. The well-mixed equations assume 1.2 ÷ 0.5 = 2.4 and 1.2 ÷ 0.2 = 6, and never run out of fresh contacts. Space alone changes the outcome.

Go deeper: why step size matters

The equation model here moves forward in whole steps: it works out the change in one step and adds it on. This is the simplest way to solve differential equations, called Euler's method. It works when the changes per step are small. When rates are large, it can overshoot: with a high enough infection rate, the code could remove more healthy cells in one step than exist, giving negative numbers.

The real equations describe smooth, continuous change. Proper solvers, such as solve_ivp in SciPy, take many small steps and shrink them automatically where things change quickly. A quick check for any home-made model is to halve the step size and run again. If the answer changes noticeably, the steps were too large, and the result reflects the method rather than the biology.

Where these models are used in immunology and vaccines

  • Inside the body. Agent-based simulators of the immune system represent antigen-presenting cells, T cells, B cells and antibodies, and are used to explore how a vaccine's dose, timing and adjuvant (an ingredient that strengthens the immune response) might change the response.
  • Tumours and immunotherapy. Models of tumour cells meeting immune cells in tissue help explore why some tumours shut immune cells out and how treatments might change that.
  • Virtual patients. Running a model many times with varied settings creates a population of simulated patients, an in silico trial ("in silico" means done by computer). Such trials can help design real trials and reduce animal testing, though they do not replace either.
  • Populations. Equation models and agent-based models of whole populations are used to plan vaccination campaigns and estimate herd-immunity thresholds.

Increasingly, omics data feed these models: expression data can set which cells respond, and predicted epitopes (the small parts of a pathogen that the immune system recognises) can set what they respond to. Tools you may meet include PhysiCell for multicellular simulations, and NetLogo and the Python package Mesa for general agent-based models.

Digital twins

A digital twin is a model of one specific individual, kept up to date with that individual's own data, so that it can be used to forecast their course and test choices before they are made. The idea comes from engineering, where twins of engines are fed live sensor data. In medicine, the most developed examples are models of individual hearts built from scans. A digital twin of a patient's immune system is a research goal, not a clinical tool; the immune system has too many unmeasured parts. Treat claims of a "patient digital twin" as a question to ask: what data update it, and how was it validated?

What makes a model a twin, rather than just a model, is the loop. The model makes a forecast for one patient; new measurements from that patient arrive; the model's settings are updated to match them; and it forecasts again. Without that loop, a model personalised once from a single scan is a patient-specific model, useful but static. Heart models built from a patient's own images are used in research to explore, for example, where a treatment that destroys a small area of faulty heart tissue might work best, because the heart's electrical behaviour is well understood and its shape can be measured precisely. The immune system has neither advantage: most of its cells cannot be imaged, and their state changes from day to day.

Can we trust a model? Validation and regulation

Three checks are kept separate. Verification asks whether the code does what the modellers intended. Calibration adjusts parameters until the model matches some data. Validation asks whether the calibrated model predicts other data that it was not fitted to; matching the fitting data proves little, just as in Why multi-omics, and how layers are integrated. For stochastic models, results are given as ranges over many runs, and a sensitivity analysis shows which parameters change the answer most.

Sensitivity analysis also tells you what to measure next. If the outcome of the tiny model in this lesson hardly changes when p_spread varies, but swings widely with p_clear, then a better measurement of how fast immune cells clear infected cells is worth more than any other experiment. In this way, a model that is still uncertain can still be useful: it points to the gaps in knowledge that matter most.

Regulators judge a model by its context of use: the specific question it is used to answer, and how much rides on the answer. The European Medicines Agency and the US Food and Drug Administration already accept modelling evidence in drug development, and the FDA uses a credibility framework based on the ASME V&V 40 standard for computational models in medical devices. The more a decision depends on a model, the stronger its validation must be. Transparent assumptions, shared code, and careful handling of any patient data under privacy law are part of that evidence.

Key point

Equation models follow averages in well-mixed groups; agent-based models follow individuals in space, with chance. Choose by which assumptions fit the biology, run stochastic models many times, and trust a model only as far as it has been validated on data it was not fitted to.

A second example: a model of T cells entering a tumour is calibrated so that it reproduces the tumour sizes seen in one mouse study. That shows the model can be made to fit. It becomes useful evidence only when, with its settings fixed, it correctly predicts the result of a different experiment, such as a different dose or a different mouse strain.

Further reading · Module 7Mesa documentation: building agent-based models in Python. · NetLogo: a free environment with a library of ready-made models to explore. · All reading for this course

Check your understanding

1. An agent-based model gives a different answer every time it is run. What should you report?

2. Why did the well-mixed equations predict far more infected cells than the grid model?

3. A model reproduces the tumour sizes it was fitted to. What has been shown?

Up next

Lesson 8

Microbiomes and metagenomics

Ask BioTutor

Create a free website with Framer, the website builder loved by startups, designers and agencies.