Draw ages for existing population from a population pyramid.
Context: I have an agent based model of disease transmission which is initialized with a number of living agents. I need to initialize these agents with age according to an existing population pyramid (potentially ignoring sex, potentially considering sex). We will use Vose's algorithm for aliasing to setup for efficient sampling from the population age distribution.
See pyramid_alias.py
for the code.
See explore.ipynb
for an example and the result of sampling from the distribution.
Note: this pseudo-code uses probabilities. The implementation in pyramid_alias.py
depends on the integer counts in each bin (which, helpfully, avoids floating point accuracy issues).
Initialization:
- Create arrays
Alias
andProb
, each of sizen
- Create two worklists,
Small
andLarge
- Multiply each probability by
n
- For each scaled probability pi
- If pi < 1, add
i
toSmall
- Otherwise (pi ≥ 1), add
i
toLarge
- If pi < 1, add
- While
Small
is not empty:- Remove the first element from
Small
; call itl
- Remove the first element from
Large
; call itg
- Set
Prob[l]
= pl - Set
Alias[l]
= g - Set pg = pg − (1 − pl)
- If pg < 1, add
g
toSmall
- Otherwise (pg ≥ 1), add
g
toLarge
- Remove the first element from
- While
Large
is not empty:- Remove the first element from
Large
; call itg
- Set
Prob[g]
= 1
- Remove the first element from
Generation:
- Generate a fair die roll from an n-sided die; call the side
i
- Flip a biased coin that comes up heads with probability
Prob[i]
- If the coin comes up "heads," return
i
- Otherwise, return
Alias[i]