demographics

demographics

Define pregnancy, deaths, migration, etc.

Classes

Name Description
Births Create births based on rates, rather than based on pregnancy.
Deaths Configure disease-independent “background” deaths.
Demographics Base class for demographic modules.
FetalHealth Track fetal health outcomes during pregnancy.
Pregnancy Create births via pregnancies for each agent.
PregnancyPars Pregnancy parameters and default values

Births

demographics.Births(
    pars=None,
    birth_rate=_,
    rel_birth=_,
    rate_units=_,
    metadata=None,
    **kwargs,
)

Create births based on rates, rather than based on pregnancy.

Births are generated using population-level birth rates that can vary by year. The number of births per timestep is determined by applying the birth rate to the current population size.

Parameters

Name Type Description Default
birth_rate float / rate / dataframe value for birth rate, or birth rate data _
rel_birth float constant used to scale all birth rates _
rate_units float units for birth rates (default assumes per 1000) _
metadata dict dict with data column mappings for birth rate data (if birth_rate is a dataframe) None

Methods

Name Description
add_births Add n_new births to each state in the sim
get_births Extract the right birth rates to use and translate it into a number of people to add.
init_pre Initialize with sim information
standardize_birth_data Standardize/validate birth rates - handled in an external file due to shared functionality
update_results Calculate new births and crude birth rate
add_births
demographics.Births.add_births()

Add n_new births to each state in the sim

get_births
demographics.Births.get_births()

Extract the right birth rates to use and translate it into a number of people to add.

init_pre
demographics.Births.init_pre(sim)

Initialize with sim information

standardize_birth_data
demographics.Births.standardize_birth_data()

Standardize/validate birth rates - handled in an external file due to shared functionality

update_results
demographics.Births.update_results()

Calculate new births and crude birth rate

Deaths

demographics.Deaths(
    pars=None,
    rel_death=_,
    death_rate=_,
    rate_units=_,
    metadata=None,
    **kwargs,
)

Configure disease-independent “background” deaths.

The probability of death for each agent on each timestep is determined by the death_rate parameter and the time step. The default value of this parameter is 0.01, indicating that all agents will face a 1% chance of death per year.

However, this function can be made more realistic by using a dataframe for the death_rate parameter, to allow it to vary by year, sex, and age. The separate ‘metadata’ argument can be used to configure the details of the input datafile.

Alternatively, it is possible to override the death_rate parameter with a bernoulli distribution containing a constant value of function of your own design.

Parameters

Name Type Description Default
pars dict with arguments including: rel_death: constant used to scale all death rates death_rate: float, dict, or pandas dataframe/series containing mortality data rate_units: units for death rates (see in-line comment on par dict below) None
metadata data about the data contained within the data input. “data_cols” is is a dictionary mapping standard keys, like “year” to the corresponding column name in data. Similar for “sex_keys”. None

Methods

Name Description
make_p_death Take in the module, sim, and uids, and return the probability of death for each UID on this timestep
standardize_death_data Standardize/validate death rates - handled in an external file due to shared functionality
step Select people to die
make_p_death
demographics.Deaths.make_p_death()

Take in the module, sim, and uids, and return the probability of death for each UID on this timestep

standardize_death_data
demographics.Deaths.standardize_death_data()

Standardize/validate death rates - handled in an external file due to shared functionality

step
demographics.Deaths.step()

Select people to die

Demographics

demographics.Demographics(name=None, label=None, **kwargs)

Base class for demographic modules.

A demographic module typically handles births/deaths/migration and takes place at the start of the timestep, before networks are updated and before any disease modules are executed. See ss.Births, ss.Deaths, and ss.Pregnancy for built-in implementations. Demographic modules modify the ss.People population and can interact with ss.Network objects (e.g. to add newborns to contact networks).

FetalHealth

demographics.FetalHealth(pars=None, **kwargs)

Track fetal health outcomes during pregnancy.

Works alongside the Pregnancy module to model birth weight outcomes (low birth weight, small for gestational age) based on fetal growth restriction. Disease-agnostic by design: external modules (connectors, interventions) modify fetal health via the public API methods.

Preterm classification is handled by the Pregnancy module (based on gestational age at birth). This module focuses on the weight/growth axis.

Integrates with Pregnancy via callbacks: Pregnancy calls on_conception when new pregnancies begin and on_delivery when births occur. External modules (e.g. disease connectors) can register their own callbacks via add_conception_callback to act on new pregnancies after baseline initialization.

During pregnancy, weight_percentile, growth_restriction, timing_shift, and n_exposures are tracked on the mother. At delivery, birth_weight, lbw, vlbw, and sga are stored on the newborn.

Each pregnancy gets a baseline weight percentile drawn at conception. Two modification levers are available:

1. **Delivery timing**: bring ``ti_delivery`` forward (preterm birth risk)
2. **Growth restriction**: accumulate fractional weight reduction

At delivery: birth_weight = baseline_for_GA × percentile × (1 - restriction)

Parameters

Name Type Description Default
weight_by_ga array Nx2 array of [gestational_age_weeks, weight_grams] required
interp_fn callable interpolation function with signature (x, xp, fp) -> array (default np.interp) required
sga_ratio float fraction of GA-appropriate weight below which SGA is declared required
lbw_threshold float birth weight in grams below which LBW is declared required
vlbw_threshold float birth weight in grams below which VLBW is declared required
min_ga dur floor for timing shifts (delivery can’t be brought before this GA) required
percentile_dist Dist distribution for baseline fetal weight percentile required

Example::

import starsim as ss

sim = ss.Sim(
    demographics=[ss.Pregnancy(fertility_rate=10), ss.Deaths(death_rate=10)],
    modules=ss.FetalHealth(),
    networks=ss.PrenatalNet(),
)
sim.run()

Methods

Name Description
add_conception_callback Register a function to be called when new pregnancies are detected.
apply_growth_restriction Apply fractional growth restriction (cumulative, diminishing).
apply_timing_shift Bring delivery forward for pregnant women.
compute_birth_weight Compute birth weight at delivery.
init_pre Register callbacks with the Pregnancy module
on_conception Initialize fetal health for new pregnancies (called by Pregnancy)
on_delivery Classify birth outcomes (called by Pregnancy).
reverse_growth_restriction Reverse a specific amount of growth restriction.
reverse_timing_shift Recover a fraction of the accumulated delivery timing shift.
add_conception_callback
demographics.FetalHealth.add_conception_callback(fn)

Register a function to be called when new pregnancies are detected. The function receives (uids,) after baseline initialization.

apply_growth_restriction
demographics.FetalHealth.apply_growth_restriction(uids, penalty)

Apply fractional growth restriction (cumulative, diminishing).

Positive penalties use diminishing returns: current + (1-current) * penalty. Negative penalties (growth boost, e.g. GDM macrosomia) are additive.

Parameters
Name Type Description Default
uids UIDs of pregnant women required
penalty float fractional weight reduction; negative = growth boost required
apply_timing_shift
demographics.FetalHealth.apply_timing_shift(uids, shift_weeks)

Bring delivery forward for pregnant women.

Uses a one-way ratchet: delivery can only be brought forward, never pushed back. The actual shift applied is tracked in timing_shift.

Parameters
Name Type Description Default
uids UIDs of pregnant women required
shift_weeks float / array shift in weeks; positive = earlier delivery required
compute_birth_weight
demographics.FetalHealth.compute_birth_weight(uids)

Compute birth weight at delivery.

Override this method to customize the birth weight formula. The interpolation function can be swapped via pars.interp_fn.

Returns
Name Type Description
tuple (birth_weights, ga_weeks) arrays
init_pre
demographics.FetalHealth.init_pre(sim)

Register callbacks with the Pregnancy module

on_conception
demographics.FetalHealth.on_conception(uids)

Initialize fetal health for new pregnancies (called by Pregnancy)

on_delivery
demographics.FetalHealth.on_delivery(mother_uids, newborn_uids)

Classify birth outcomes (called by Pregnancy).

Birth weight is computed from the mother’s pregnancy-time states (weight_percentile, growth_restriction). Outcomes (birth_weight, lbw, vlbw, sga) are stored on the newborn agents.

reverse_growth_restriction
demographics.FetalHealth.reverse_growth_restriction(uids, amount)

Reverse a specific amount of growth restriction.

Parameters
Name Type Description Default
uids UIDs of pregnant women required
amount float / array amount to reverse required
reverse_timing_shift
demographics.FetalHealth.reverse_timing_shift(uids, fraction)

Recover a fraction of the accumulated delivery timing shift.

Parameters
Name Type Description Default
uids UIDs of pregnant women required
fraction float / array fraction to recover (0-1) required

Pregnancy

demographics.Pregnancy(
    pars=None,
    fertility_rate=_,
    rel_fertility=_,
    p_infertile=_,
    min_age=_,
    max_age=_,
    rate_units=_,
    dur_pregnancy=_,
    dur_breastfeed=_,
    p_breastfeed=_,
    rr_ptb=_,
    rr_ptb_age=_,
    p_maternal_death=_,
    p_survive_maternal_death=_,
    sex_ratio=_,
    burnin=_,
    slot_scale=_,
    min_slots=_,
    trimesters=_,
    metadata=None,
    **kwargs,
)

Create births via pregnancies for each agent.

This module models conception, pregnancy, and birth at the individual level using age-specific fertility rates. Supports prenatal and postnatal transmission networks, maternal and neonatal mortality, and burn-in of existing pregnancies at simulation start.

Parameters

Name Type Description Default
fertility_rate float / dataframe value or dataframe with age-specific fertility rates _
rel_fertility float constant used to scale all fertility rates _
p_infertile bernoulli probability of primary infertility (default 0) _
min_age float minimum age for pregnancy (default 15) _
max_age float maximum age for pregnancy (default 50) _
rate_units float units for fertility rates (default assumes per 1000) _
dur_pregnancy float / dur duration of pregnancy (default: drawn from choice distribution, 32-42 weeks) _
dur_breastfeed float / dur duration of breastfeeding (default: drawn from lognormal distribution, 9±6 months) _
rr_ptb float base relative risk of pre-term birth (default normal with mean 1, std 0.1) _
rr_ptb_age array relative risk of pre-term birth by maternal age (default [[18,35,100],[1.2,1,1.2]]) _
p_maternal_death float probability of maternal death during pregnancy (default 0.0) _
p_survive_maternal_death float probability that an unborn agent will survive death of the mother (default 0) _
sex_ratio float probability of female births (default 0.5) _
burnin bool whether to seed pregnancies from before simulation start (default true) _
slot_scale float scale factor for assigning slots to newborn agents (default 5) _
min_slots int minimum number of slots for newborn agents (default 100) _
preterm_threshold dur gestational age below which preterm is declared (default 37w) required
very_preterm_threshold dur gestational age below which very preterm is declared (default 32w) required
trimesters list list of durations defining the end of each trimester _
metadata dict data column mappings for fertility rate data if a dataframe is supplied None

Attributes

Name Description
dur_gestation Return duration of gestation for currently-pregnant women in years
dur_gestation_at_birth Return duration of gestation at birth for agents born during the simulation
fecund Defined as women of childbearing age
fertile Defined as women of childbearing age who are not infertile. Includes women who may be pregnant
nulliparous Women of childbearing age who have never been pregnant
susceptible Defined as fertile women of childbearing age who are not pregnant, and so are susceptible to conception
tri1_uids Return UIDs of those in their first trimester
tri2_uids Return UIDs of those in their second trimester
tri3_uids Return UIDs of those in their third trimester

Methods

Name Description
add_conception_callback Register a function fn(uids) to be called after new pregnancies are created
add_delivery_callback Register a function fn(mother_uids, newborn_uids) to be called after delivery
compute_asfr Computes age-specific fertility rates (ASFR). Since this is calculated each timestep,
init_results Initialize results. By default, this includes:
make_embryos Make newly-conceived agents. This method calls two helper methods, which grow the population
make_p_conceive Take in the module, sim, and uids, and return the conception probability for each UID on this timestep
make_pregnancies Make pregnancies, assign durations, and determine multiples
process_delivery Handle delivery by updating all states for the mother. This method also transfers
process_maternal_deaths If any pregnant mothers die, we also process the death of the unborn agent.
process_neonatal_deaths Classify deaths of agents aged 0-28 days as neonatal deaths.
process_newborns Set states for newborn agents
process_prenatal_deaths If any deaths occur in unborn agents, classify by gestational age:
progress_pregnancies Update pregnant women: advance gestational clock, apply background pregnancy loss.
select_conceivers Select people to make pregnant
set_breastfeeding Set breastfeeding durations for new mothers. This method could be extended to
set_ptb Update relative risk of pre-term birth
set_rel_sus Set relative susceptibility to pregnancy. Note that rel_sus isn’t used in this module,
standardize_fertility_data Standardize/validate fertility rates
step Perform all updates except for deaths, which are handled in finish_step
step_die Wipe dates and states following death
update_maternal_deaths Check for maternal deaths
updates_pre This runs prior at the beginning of each timestep, prior to calculating pregnancy exposure,
add_conception_callback
demographics.Pregnancy.add_conception_callback(fn)

Register a function fn(uids) to be called after new pregnancies are created

add_delivery_callback
demographics.Pregnancy.add_delivery_callback(fn)

Register a function fn(mother_uids, newborn_uids) to be called after delivery

compute_asfr
demographics.Pregnancy.compute_asfr()

Computes age-specific fertility rates (ASFR). Since this is calculated each timestep, the annualized results should compute the sum.

init_results
demographics.Pregnancy.init_results()

Initialize results. By default, this includes: - pregnancies: number of new pregnancies on each timestep - births: number of new births on each timestep - cbr: crude birth rate on each timestep - tfr: total fertility rate on each timestep - The number of people who are fecund, (in)fertile, susceptible, postpartum, pregnant, infertile, breastfeeding

make_embryos
demographics.Pregnancy.make_embryos(conceive_uids, embryo_counts=None)

Make newly-conceived agents. This method calls two helper methods, which grow the population and set the states for the newborn agents.

make_p_conceive
demographics.Pregnancy.make_p_conceive(filter_uids=None)

Take in the module, sim, and uids, and return the conception probability for each UID on this timestep

make_pregnancies
demographics.Pregnancy.make_pregnancies(uids)

Make pregnancies, assign durations, and determine multiples

process_delivery
demographics.Pregnancy.process_delivery(mother_uids, newborn_uids)

Handle delivery by updating all states for the mother. This method also transfers recorded information stored with the mother to the newborn. During pregnancy, gestational age is tracked with the mother; at birth, this value is transferred to the newborn agent before being reset for the mother. Likewise, during pregnancy, the child UID is stored with the mother; at birth, this value is removed from the mother, although newborn agents can still be linked to the mother via the parent state.

process_maternal_deaths
demographics.Pregnancy.process_maternal_deaths(death_uids)

If any pregnant mothers die, we also process the death of the unborn agent. Default probability is set to 1 meaning we assume that unborn children do not survive.

process_neonatal_deaths
demographics.Pregnancy.process_neonatal_deaths(death_uids)

Classify deaths of agents aged 0-28 days as neonatal deaths. This is passive detection — any cause of death (disease, background mortality, etc.) that kills a newborn within 28 days of birth is recorded.

process_newborns
demographics.Pregnancy.process_newborns(uids)

Set states for newborn agents

process_prenatal_deaths
demographics.Pregnancy.process_prenatal_deaths(death_uids)

If any deaths occur in unborn agents, classify by gestational age: - <loss_threshold (default 20w): miscarriage - >=loss_threshold: stillbirth

progress_pregnancies
demographics.Pregnancy.progress_pregnancies()

Update pregnant women: advance gestational clock, apply background pregnancy loss.

select_conceivers
demographics.Pregnancy.select_conceivers(uids=None)

Select people to make pregnant

set_breastfeeding
demographics.Pregnancy.set_breastfeeding(mother_uids, newborn_uids)

Set breastfeeding durations for new mothers. This method could be extended to store duration of exclusive breastfeeding, partial breastfeeding, etc, and these properties could be stored with the infant for tracking other health outcomes.

set_ptb
demographics.Pregnancy.set_ptb()

Update relative risk of pre-term birth

set_rel_sus
demographics.Pregnancy.set_rel_sus()

Set relative susceptibility to pregnancy. Note that rel_sus isn’t used in this module, but it’s a key ingredient for derived modules that compute pregnancies based on exposure.

standardize_fertility_data
demographics.Pregnancy.standardize_fertility_data()

Standardize/validate fertility rates

step
demographics.Pregnancy.step()

Perform all updates except for deaths, which are handled in finish_step

step_die
demographics.Pregnancy.step_die(uids)

Wipe dates and states following death

update_maternal_deaths
demographics.Pregnancy.update_maternal_deaths()

Check for maternal deaths

updates_pre
demographics.Pregnancy.updates_pre(uids=None, upper_age=None)

This runs prior at the beginning of each timestep, prior to calculating pregnancy exposure, advancing pregnancies, adding new pregnancies, or determing delivery outcomes. Here we make any updates that affect the risk of pregnancy or pre-term birth on this timestep. We also set the baseline values for newborn agents.

PregnancyPars

demographics.PregnancyPars(**kwargs)

Pregnancy parameters and default values