Skip to content

API Reference

This section provides comprehensive API documentation for all TBsim modules and components, automatically generated from Python docstrings.

Core Modules

Original agent-based TB natural history model with state-based progression and transmission.

tbsim.tb_emod.TBS

Bases: IntEnum

Tuberculosis disease states enumeration.

with respect to tuberculosis infection and disease progression. It is based on the tb natural history model from https://www.pnas.org/doi/full/10.1073/pnas.0901720106 and updated with rates from TB natural history literature (e.g., PMID: 32766718, 9363017)

Enumeration
State Value Description
NONE -1 No TB infection (susceptible)
LATENT_SLOW 0 Latent TB with slow progression to active disease
LATENT_FAST 1 Latent TB with fast progression to active disease
ACTIVE_PRESYMP 2 Active TB in pre-symptomatic phase
ACTIVE_SMPOS 3 Active TB, smear positive (most infectious)
ACTIVE_SMNEG 4 Active TB, smear negative (moderately infectious)
ACTIVE_EXPTB 5 Active TB, extra-pulmonary (least infectious)
DEAD 8 Death from TB
PROTECTED 100 Protected from TB (e.g., from BCG vaccination)

Methods:

Name Description
all

Get all TB states including special states

all_active

Get all active TB states

all_latent

Get all latent TB states

all_infected

Get all states that represent TB infection (excluding NONE, DEAD, and PROTECTED)

tbsim.tb_emod.TBS.all() staticmethod

Get all TB states including special states.

Returns:

Type Description

numpy.ndarray: All TB states including NONE, LATENT_SLOW, LATENT_FAST, ACTIVE_PRESYMP, ACTIVE_SMPOS, ACTIVE_SMNEG, ACTIVE_EXPTB, DEAD, and PROTECTED.

tbsim.tb_emod.TBS.all_active() staticmethod

Get all active TB states.

Returns:

Type Description

numpy.ndarray: Active TB states including ACTIVE_PRESYMP, ACTIVE_SMPOS, ACTIVE_SMNEG, and ACTIVE_EXPTB.

tbsim.tb_emod.TBS.all_infected() staticmethod

Get all states that represent TB infection (excluding NONE, DEAD, and PROTECTED).

Returns:

Type Description

numpy.ndarray: TB infection states including LATENT_SLOW, LATENT_FAST, ACTIVE_PRESYMP, ACTIVE_SMPOS, ACTIVE_SMNEG, and ACTIVE_EXPTB.

tbsim.tb_emod.TBS.all_latent() staticmethod

Get all latent TB states.

Returns:

Type Description

numpy.ndarray: Latent TB states including LATENT_SLOW and LATENT_FAST.

tbsim.tb_emod.TBS.care_seeking_eligible() staticmethod

Get active TB states eligible for care-seeking (excludes ACTIVE_PRESYMP).

tbsim.tb_emod.TB_EMOD(pars=None, **kwargs)

Bases: BaseTB

Tuberculosis disease model for TBsim simulations.

This class implements a comprehensive tuberculosis simulation model that tracks individuals through various disease states including latent infection, active disease, and treatment. The model includes:

  • Multiple latent TB states (slow vs. fast progression)
  • Pre-symptomatic active TB phase
  • Different active TB forms (smear positive/negative, extra-pulmonary)
  • Treatment effects on transmission and mortality
  • Age-specific reporting (15+ years)

The model follows a state transition approach where individuals move between states based on probabilistic transitions that depend on their current state, treatment status, and individual risk factors.

Attributes:

Name Type Description
state

Current TB state for each individual

latent_tb_state

Specific latent state (slow/fast) for each individual

active_tb_state

Specific active state (smear pos/neg, extra-pulmonary) for each individual

on_treatment

Boolean indicating if individual is currently on treatment

ever_infected

Boolean indicating if individual has ever been infected

rr_activation

Relative risk multiplier for latent-to-active transition

rr_clearance

Relative risk multiplier for active-to-clearance transition

rr_death

Relative risk multiplier for active-to-death transition

reltrans_het

Individual-level heterogeneity in infectiousness

Example::

import starsim as ss
import tbsim

sim = ss.Sim(diseases=tbsim.TB_EMOD())
sim.run()
sim.plot()

Initialize the TB disease model.

Parameters:

Name Type Description Default
pars

Dictionary of parameters to override defaults

None
**kwargs

Additional keyword arguments for parameters

{}

tbsim.tb_emod.TB_EMOD.infectious property

Determine which individuals are currently infectious.

An individual is considered infectious if they are in any active TB state or currently on treatment. This property is used by the Starsim transmission system to calculate transmission rates and for contact tracing.

Infectious States: - ACTIVE_PRESYMP: Pre-symptomatic active TB (low transmissibility) - ACTIVE_SMPOS: Smear positive pulmonary TB (highest transmissibility) - ACTIVE_SMNEG: Smear negative pulmonary TB (moderate transmissibility) - ACTIVE_EXPTB: Extra-pulmonary TB (lowest transmissibility) - on_treatment: Currently receiving treatment (reduced transmissibility)

Transmission Rates: The relative transmissibility of each state is defined by: - rel_trans_presymp = 0.1 (10% of baseline) - rel_trans_smpos = 1.0 (baseline, 100%) - rel_trans_smneg = 0.3 (30% of baseline) - rel_trans_exptb = 0.05 (5% of baseline) - rel_trans_treatment = 0.5 (50% reduction for treated individuals)

Returns:

Type Description

numpy.ndarray: Boolean array indicating infectious status for each individual

Example

infectious_uids = tb.infectious.uids print(f"Number of infectious individuals: {len(infectious_uids)}")

tbsim.tb_emod.TB_EMOD.finalize_results()

Finalize result calculations after simulation completion.

This method is called by the Starsim framework after the simulation has completed to calculate cumulative measures and finalize any results that depend on the complete simulation history.

Cumulative Calculations: - cum_deaths: Cumulative TB deaths = cumsum(new_deaths) - cum_deaths_15+: Cumulative TB deaths for adults 15+ = cumsum(new_deaths_15+) - cum_active: Cumulative active TB cases = cumsum(new_active) - cum_active_15+: Cumulative active TB cases for adults 15+ = cumsum(new_active_15+)

Purpose: - Provides total burden measures over the entire simulation period - Enables calculation of cumulative incidence and mortality rates - Supports long-term epidemiological analysis and program evaluation

Usage: - Called automatically by Starsim at simulation end - Results are available in self.results after completion - Used for final analysis and reporting

Integration: - Calls super().finalize_results() to handle base class finalization - Ensures compatibility with Starsim result system

This method is called automatically by the Starsim framework at the end of simulation and should not be called manually.

tbsim.tb_emod.TB_EMOD.init_results()

Initialize result tracking variables for TB epidemiological outcomes.

This method sets up all the result variables used to track TB-specific epidemiological outcomes throughout the simulation. It defines both basic state counts and derived epidemiological indicators.

State Count Results: - n_latent_slow, n_latent_fast: Counts of individuals in latent states - n_active_presymp, n_active_smpos, n_active_smneg, n_active_exptb: Active state counts - n_active: Combined count of all active TB cases - n_infectious: Total number of infectious individuals

Age-Specific Results (15+ years): - All active state counts have 15+ variants for adult-focused analysis - new_active_15+, new_deaths_15+: Age-specific incidence and mortality - new_notifications_15+: Treatment initiations for adults - n_detectable_15+: Detectable cases including CXR screening

Incidence and Cumulative Measures: - new_active, new_deaths: Daily incidence of new cases and deaths - cum_active, cum_deaths: Cumulative counts over simulation period - cum_active_15+, cum_deaths_15+: Age-specific cumulative measures

Derived Epidemiological Indicators: - prevalence_active: Active TB prevalence (active cases / total population) - incidence_kpy: Incidence per 1,000 person-years - deaths_ppy: Death rate per person-year - n_reinfected: Number of reinfection events

Detection and Treatment Metrics: - new_notifications_15+: New TB notifications (treatment initiations) - n_detectable_15+: Detectable cases (smear pos/neg + CXR-screened pre-symptomatic)

This method is called automatically by the Starsim framework during simulation initialization and should not be called manually.

tbsim.tb_emod.TB_EMOD.p_active_to_clear(sim, uids) staticmethod

Calculate probability of active TB → clearance (natural or treatment).

tbsim.tb_emod.TB_EMOD.p_active_to_death(sim, uids) staticmethod

Calculate probability of active TB → death (varies by TB type).

tbsim.tb_emod.TB_EMOD.p_latent_to_presym(sim, uids) staticmethod

Calculate probability of latent → pre-symptomatic transition.

tbsim.tb_emod.TB_EMOD.p_presym_to_active(sim, uids) staticmethod

Calculate probability of pre-symptomatic → active TB transition.

tbsim.tb_emod.TB_EMOD.p_presym_to_clear(sim, uids) staticmethod

Calculate probability of pre-symptomatic → clearance (treatment only).

tbsim.tb_emod.TB_EMOD.plot()

Create a basic plot of all TB simulation results.

This method generates a matplotlib figure showing the time series of all tracked TB epidemiological measures over the simulation period. It provides a quick visual overview of the simulation outcomes.

Plot Contents: - Time Series: All result variables plotted against simulation time - Multiple Metrics: Includes state counts, incidence, mortality, and prevalence - Legend: Each result variable is labeled in the legend - Automatic Scaling: Matplotlib handles axis scaling automatically

Excluded Variables: - timevec: Excluded as it represents the x-axis (time) - All other result variables are included in the plot

Plot Features: - Line Plot: Each result variable plotted as a separate line - Legend: Automatic legend with result variable names - Time Axis: X-axis represents simulation time steps - Value Axis: Y-axis represents result variable values

Usage: - Useful for quick visual inspection of simulation results - Can be customized by modifying the returned figure - Suitable for basic analysis and presentation

Limitations: - All variables on same plot may have different scales - No automatic subplot organization - Basic styling without customization

Returns:

Type Description

matplotlib.figure.Figure: Figure containing the time series plot of all TB results

Example

fig = tb.plot() fig.show() # Display the plot fig.savefig('tb_results.png') # Save to file

tbsim.tb_emod.TB_EMOD.set_prognoses(uids, sources=None)

Set initial prognoses for newly infected individuals.

This method is called by the Starsim framework when individuals first become infected with TB. It determines their latent TB progression type, sets their initial state, and configures individual risk factors and heterogeneity.

Progression Type Assignment: - Fast progressors (10%): p_latent_fast = 0.1, progress rapidly to active disease - Slow progressors (90%): p_latent_slow = 0.9, progress slowly or remain latent

State Initialization: - Fast progressors: Set to TBS.LATENT_FAST, become non-susceptible - Slow progressors: Set to TBS.LATENT_SLOW, remain susceptible to reinfection

Individual Risk Factors: - rr_activation: Multiplier for latent-to-active transition (default 1.0) - rr_clearance: Multiplier for active-to-clearance transition (default 1.0) - rr_death: Multiplier for active-to-death transition (default 1.0) - reltrans_het: Individual transmission heterogeneity (default 1.0)

Active State Pre-assignment: - active_tb_state: Pre-determined active state for future progression - Distribution: 10% SMPOS, 10% SMNEG, 60% SMNEG, 20% EXPTB

Reinfection Handling: - Tracks new infections vs. reinfections separately - Slow progressors maintain susceptibility for reinfection - Fast progressors become non-susceptible after infection

Parameters:

Name Type Description Default
uids ndarray

Array of individual IDs to set prognoses for

required
sources ndarray

Source of infection (not used in current implementation)

None
Example

Called automatically by Starsim when new infections occur

tb.set_prognoses(new_infected_uids)

Individuals are now assigned to latent states with risk factors

tbsim.tb_emod.TB_EMOD.start_treatment(uids)

Start treatment for individuals with active TB.

This method initiates TB treatment for specified individuals, implementing the key effects of treatment on disease progression and transmission.

Treatment Effects: - Mortality Prevention: Sets rr_death = 0 (treatment prevents TB death) - Transmission Reduction: Applies rel_trans_treatment = 0.5 (50% reduction) - Clearance Enhancement: Uses rate_treatment_to_clear = 6/year (2-month duration) - State Tracking: Marks individuals as on_treatment = True

Eligibility Requirements: Only individuals in active TB states can start treatment: - ACTIVE_PRESYMP: Pre-symptomatic active TB - ACTIVE_SMPOS: Smear positive pulmonary TB - ACTIVE_SMNEG: Smear negative pulmonary TB - ACTIVE_EXPTB: Extra-pulmonary TB

Notification Tracking: - Tracks new_notifications_15+ for individuals 15+ years old - Used for epidemiological reporting and program evaluation

Treatment Duration: - Treatment continues until clearance (rate_treatment_to_clear) - Average treatment duration: 2 months (6 per year) - Treatment effects persist throughout the treatment period

Parameters:

Name Type Description Default
uids ndarray

Array of individual IDs to start treatment for

required

Returns:

Name Type Description
int

Number of individuals who actually started treatment (only active TB cases)

Example

Start treatment for detected active TB cases

n_treated = tb.start_treatment(detected_uids) print(f"Started treatment for {n_treated} individuals")

tbsim.tb_emod.TB_EMOD.step()

Execute one simulation time step for TB disease progression.

This method is called by the Starsim framework at each simulation time step and handles all TB-specific state transitions and updates. It processes state transitions in a specific order to ensure proper disease progression.

State Transition Sequence: 1. Latent → Pre-symptomatic: Slow/fast progressors advance to active disease 2. Pre-symptomatic → Active/Clear: Progression to symptomatic or treatment clearance 3. Active → Clear: Natural recovery or treatment-induced clearance 4. Active → Death: TB mortality (varies by active state type) 5. Transmission Updates: Update relative transmission rates for all states 6. Risk Reset: Reset individual risk modifiers for next time step

Key Features: - Age-specific tracking: Separate counts for individuals 15+ years old - Treatment effects: Treated individuals have reduced transmission and zero death risk - State-specific rates: Different progression rates for each TB state - Individual heterogeneity: Applies individual risk modifiers and transmission heterogeneity - Result tracking: Updates all epidemiological metrics for analysis

Transmission Rate Updates: - Resets all relative transmission rates to 1.0 - Applies state-specific transmission rates (presymp, smpos, smneg, exptb) - Applies individual transmission heterogeneity - Reduces transmission for treated individuals

Result Updates: - new_active, new_active_15+: New cases of active TB - new_deaths, new_deaths_15+: New TB deaths - new_notifications_15+: New treatment initiations (15+ years)

This method is the core of the TB disease model and must be called at each simulation time step by the Starsim framework.

tbsim.tb_emod.TB_EMOD.step_die(uids)

Handle death events for TB-infected individuals.

This method is called by the Starsim framework when individuals die from any cause (TB-related or other). It ensures that deceased individuals cannot transmit TB or become infected after death.

State Cleanup: - Susceptibility: Sets susceptible = False (cannot be infected) - Infection Status: Sets infected = False (no longer infected) - Transmission: Sets rel_trans = 0 (cannot transmit to others)

Death Sources: - TB Deaths: Individuals who died from active TB (TBS.DEAD state) - Other Deaths: Individuals who died from other causes while infected

Framework Integration: - Calls super().step_die(uids) to handle base class death processing - Ensures proper cleanup of TB-specific states - Maintains consistency with Starsim death handling

Important Notes: - This method handles ALL deaths, not just TB deaths - TB-specific death tracking is handled in the step() method - Deceased individuals are removed from all TB calculations

Parameters:

Name Type Description Default
uids ndarray

Array of individual IDs who have died

required
Example

Called automatically by Starsim when deaths occur

tb.step_die(deceased_uids)

Deceased individuals are now removed from TB transmission

tbsim.tb_emod.TB_EMOD.update_results()

Update result tracking variables for the current time step.

This method is called by the Starsim framework at each time step to calculate and store all TB-specific epidemiological metrics. It updates both basic state counts and derived epidemiological indicators.

State Count Updates: - Counts individuals in each TB state (latent, active, infectious) - Calculates age-specific counts for individuals 15+ years old - Updates total active TB and infectious case counts

Detection Metrics: - n_detectable_15+: Calculates detectable cases including: * All smear positive and negative cases (100% detectable) * CXR-screened pre-symptomatic cases (cxr_asymp_sens sensitivity)

Derived Epidemiological Indicators: - prevalence_active: Active TB prevalence = n_active / total_alive_population - incidence_kpy: Incidence per 1,000 person-years = 1000 * new_infections / (alive_pop * dt_year) - deaths_ppy: Death rate per person-year = new_deaths / (alive_pop * dt_year)

Age-Specific Calculations: - All 15+ metrics use age >= 15 filter for adult-focused analysis - Important for TB epidemiology as adult cases are typically more severe

Population Scaling: - Uses sim.people.alive to get current living population - Accounts for deaths and births during simulation - Ensures rates are calculated relative to current population

Time Step Integration: - Uses sim.t.dt_year for time-based rate calculations - Ensures consistent units across different time step sizes

This method is called automatically by the Starsim framework at each time step and should not be called manually.

LSHTM TB natural history model. State definitions and transition diagram are in the API docs (tbsim.tb_lshtm).

tbsim.tb_lshtm.BaseTB

Bases: Infection

Base class for TB natural history models.

tbsim.tb_lshtm.TBSL

Bases: IntEnum

TB state labels for the LSHTM model.

  • Each agent is in exactly one of these states.
  • Transitions are driven by exponential rates in TB_LSHTM (and TB_LSHTM_Acute).

tbsim.tb_lshtm.TBSL.care_seeking_eligible() staticmethod

States eligible for care-seeking: only SYMPTOMATIC. Only individuals with clinical symptoms (cough, fever, night sweats, etc.) recognise their illness and seek healthcare.

tbsim.tb_lshtm.TB_LSHTM(pars=None, **kwargs)

Bases: BaseTB

Agent-based TB natural history adapting the LSHTM compartmental structure [1] (Schwalb et al. 2025). States in TBSL span the spectrum from susceptibility to active disease and treatment. Infectious states are TBSL.ASYMPTOMATIC and TBSL.SYMPTOMATIC; the force of infection depends on pars.beta and the prevalence of those states, with pars.trans_asymp (kappa) giving the relative infectiousness of asymptomatic vs symptomatic TB. Reinfectable states (TBSL.CLEARED, TBSL.RECOVERED, TBSL.TREATED) use pars.rr_rec (pi) and pars.rr_treat (rho). Per-agent modifiers rr_activation, rr_clearance, rr_death scale selected rates. Interventions call start_treatment.

Args (pars): Transmission and reinfection

- ``init_prev``:   Initial seed infections (prevalence).
- ``beta``:        Transmission rate per year.
- ``trans_asymp``: Relative transmissibility, asymptomatic vs symptomatic. (kappa)
- ``rr_rec``:      Relative risk of reinfection for RECOVERED.  (pi)
- ``rr_treat``:    Relative risk of reinfection for TREATED. (rho)

*From INFECTION (latent)*

- ``inf_cle``:     Infection -> Cleared (no active TB).
- ``inf_non``:     Infection -> Non-infectious TB.
- ``inf_asy``:     Infection -> Asymptomatic TB.

*From NON_INFECTIOUS*

- ``non_rec``:    Non-infectious -> Recovered.
- ``non_asy``:    Non-infectious -> Asymptomatic.

*From ASYMPTOMATIC*

- ``asy_non``:    Asymptomatic -> Non-infectious.
- ``asy_sym``:    Asymptomatic -> Symptomatic.

*From SYMPTOMATIC*

- ``sym_asy``:     Symptomatic -> Asymptomatic.
- ``sym_treat``:   Symptomatic -> Treatment. (theta)
- ``sym_dead``:    Symptomatic -> Dead (TB-specific mortality, mu_TB).

*From TREATMENT*

- ``fail_rate``:     Treatment -> Symptomatic (failure). (phi)
- ``complete_rate``: Treatment -> Treated (completion).  (delta)

*Background (general mortality is handled by* ``ss.Deaths`` *demographics, not this module)*

- ``cxr_asymp_sens``:   CXR sensitivity for screening asymptomatic (0-1).

Attributes:

Name Type Description
- ``susceptible`` (BoolState, default=True

Whether the agent is susceptible to TB.

- ``infected`` (BoolState, default=False

Whether the agent is currently infected.

- ``ever_infected`` (BoolState, default=False

Whether the agent has ever been infected.

- ``on_treatment`` (BoolState, default=False

Whether the agent is on TB treatment.

- ``state`` (FloatArr, default=TBSL.SUSCEPTIBLE

Current TB state (TBSL value).

- ``ti_infected`` (FloatArr, default=-inf

Time of infection (never infected = -inf).

- ``rel_sus`` (FloatArr, default=1.0

Relative susceptibility to TB.

- ``rel_trans`` (FloatArr, default=1.0

Relative transmissibility of TB.

- ``rr_activation`` (FloatArr, default=1.0

Multiplier on INFECTION -> NON_INFECTIOUS / ASYMPTOMATIC.

- ``rr_clearance`` (FloatArr, default=1.0

Multiplier on NON_INFECTIOUS -> RECOVERED.

- ``rr_death`` (FloatArr, default=1.0

Multiplier on SYMPTOMATIC -> DEAD.

Example

::

import starsim as ss
import tbsim

sim = ss.Sim(diseases=tbsim.TB_LSHTM(), pars=dict(start='2000', stop='2020'))
sim.run()
sim.plot()
References

[1] Schwalb et al. (2025) Potential impact, costs, and benefits of population-wide screening interventions for tuberculosis in Viet Nam. PLOS Glob Public Health. https://doi.org/10.1371/journal.pgph.0005050

Initialize with default LSHTM natural history parameters; override via pars.

tbsim.tb_lshtm.TB_LSHTM.infectious property

Boolean array: True for agents who can transmit TB.

In this model only ASYMPTOMATIC and SYMPTOMATIC states are infectious. Used by the base starsim.Infection for transmission.

tbsim.tb_lshtm.TB_LSHTM.finalize_results()

Compute cumulative series from new-event series after the run.

tbsim.tb_lshtm.TB_LSHTM.init_results()

Define result time series.

tbsim.tb_lshtm.TB_LSHTM.plot()

Plot all result time series on one figure.

tbsim.tb_lshtm.TB_LSHTM.set_prognoses(uids, sources=None)

Set prognoses for newly infected agents (called when transmission occurs).

The base starsim.Infection calls this when a susceptible agent acquires infection. We mark agents infected and set state to INFECTION (latent). Transitions are evaluated per dt each timestep in step.

tbsim.tb_lshtm.TB_LSHTM.start_treatment(uids)

Move specified agents onto TB treatment (or clear latent infection).

Called by interventions (e.g. screening/case-finding) when an agent is identified for treatment. State is changed immediately.

  • Latent (INFECTION): cleared without treatment (→ CLEARED).
  • Active (NON_INFECTIOUS, ASYMPTOMATIC, SYMPTOMATIC): moved to TREATMENT.
  • Records new notifications (15+) for active cases starting treatment.

tbsim.tb_lshtm.TB_LSHTM.step()

Advance TB state machine one timestep.

  1. Transmission (via super().step()): handles force of infection.
  2. Reset RR multipliers for all agents (interventions set fresh each step).
  3. Evaluate transitions: for each state group, evaluate competing-risk transitions and apply immediately. Agents may cascade through multiple states in one step.
  4. Bookkeeping: update flags, modifiers, deaths, results.

tbsim.tb_lshtm.TB_LSHTM.step_die(uids)

Apply death for the given agents and update TB state.

Called by the framework when agents die (e.g. background mortality). Sets state to DEAD, clears flags, and stops transmission.

tbsim.tb_lshtm.TB_LSHTM.transition(uids, to, rng)

Evaluate competing exponential transitions over one dt and apply immediately.

For each agent in uids, computes the probability of transitioning to each destination in to during one timestep. Uses a single uniform draw per agent to decide (a) whether the agent transitions and (b) which destination it goes to. State is updated immediately.

tbsim.tb_lshtm.TB_LSHTM.update_results()

Record current time-step values for all result series.

tbsim.tb_lshtm.TB_LSHTM_Acute(pars=None, **kwargs)

Bases: TB_LSHTM

LSHTM TB model with an acute infection state immediately after exposure.

Extends TB_LSHTM by inserting an ACUTE state between infection and the usual INFECTION (latent) state. New infections enter ACUTE first, then transition to INFECTION at rate pars.rate_acute_latent. Acute cases are infectious with relative transmissibility pars.trans_acute (alpha).

tbsim.tb_lshtm.TB_LSHTM_Acute.infectious property

Includes ACUTE in addition to ASYMPTOMATIC and SYMPTOMATIC.

tbsim.tb_lshtm.TB_LSHTM_Acute.set_prognoses(uids, sources=None)

New infections enter ACUTE (not INFECTION).

tbsim.tb_lshtm.TB_LSHTM_Acute.start_treatment(uids)

ACUTE or INFECTION -> CLEARED; active -> TREATMENT.

tbsim.tb_lshtm.TB_LSHTM_Acute.step()

Advance TB state machine one timestep (acute variant).

Same single-pass structure as TB_LSHTM.step, but adds ACUTE -> INFECTION transition and treats ACUTE as infectious.

tbsim.tb_lshtm.get_tb(sim, which=None)

Helper to get the TB_LSHTM infection module from a sim

Parameters:

Name Type Description Default
sim Sim

the simulation to search for the TB module

required
which type

the class of TB module to get (e.g. TB_LSHTM; if None, returns the first BaseTB subclass found

None

Custom contact networks

tbsim.networks.HouseholdNet(hhs=None, pars=None, **kwargs)

Bases: Network

A household-level contact network for agent-based simulations using Starsim.

This network constructs complete graphs among household members and supports dynamically adding newborns to the simulation and linking them to their household based on the parent-child relationship. It is especially useful in intervention trials where household structure and arm assignment are important.

Parameters:

Name Type Description Default
hhs list of lists or arrays of int

A list of households, where each household is represented by a list or array of agent UIDs.

None
pars dict

Dictionary of network parameters. Supports: - add_newborns (bool): Whether to dynamically add newborns to households.

None
**kwargs dict

Additional keyword arguments passed to the Network base class.

{}

Attributes:

Name Type Description
hhs list

List of household UID groups.

pars objdict

Dictionary-like container of network parameters.

edges Starsim EdgeStruct

Container for the network's edges (p1, p2, and beta arrays).

Methods:

Name Description
add_hh

Add a complete graph among the given UIDs to the network.

init_pre

Initialize the network prior to simulation start. Adds initial household connections.

step

During simulation, adds newborns to the network by linking them to their household contacts and assigning household-level attributes (e.g., hhid, trial arm).

Example

::

import starsim as ss
import tbsim

tb  = tbsim.TB_LSHTM()
net = tbsim.HouseholdNet()
sim = ss.Sim(diseases=tb, networks=net, pars=dict(start='2000', stop='2020'))
sim.run()

Initialize with an optional list of households (each a list of agent UIDs).

tbsim.networks.HouseholdNet.add_hh(uids)

Add a complete graph among the given UIDs to the network.

tbsim.networks.HouseholdNet.init_pre(sim)

Initialize the network prior to simulation start. Adds initial household connections.

tbsim.networks.HouseholdNet.step()

Adds newborns to the trial population, including hhid, arm, and household contacts.

tbsim.networks.HouseholdNetRationsTrial(hhs=None, pars=None, **kwargs)

Bases: Network

RATIONS trial network. A household-level contact network for agent-based simulations using Starsim.

This network constructs complete graphs among household members and supports dynamically adding newborns to the simulation and linking them to their household based on the parent-child relationship. It is especially useful in intervention trials where household structure and arm assignment are important (e.g., RATIONS trial).

Parameters:

Name Type Description Default
hhs list of lists or arrays of int

A list of households, where each household is represented by a list or array of agent UIDs.

None
pars dict

Dictionary of network parameters. Supports: - add_newborns (bool): Whether to dynamically add newborns to households.

None
**kwargs dict

Additional keyword arguments passed to the Network base class.

{}

Attributes:

Name Type Description
hhs list

List of household UID groups.

pars objdict

Dictionary-like container of network parameters.

edges Starsim EdgeStruct

Container for the network's edges (p1, p2, and beta arrays).

Methods:

Name Description
add_hh

Add a complete graph among the given UIDs to the network.

init_pre

Initialize the network prior to simulation start. Adds initial household connections.

step

During simulation, adds newborns to the network by linking them to their household contacts and assigning household-level attributes (e.g., hhid, trial arm).

Initialize with an optional list of households (each a list of agent UIDs).

tbsim.networks.HouseholdNetRationsTrial.add_hh(uids)

Add a household by creating complete-graph edges among its member UIDs.

tbsim.networks.HouseholdNetRationsTrial.init_pre(sim)

Build initial network edges from all households.

tbsim.networks.HouseholdNetRationsTrial.step()

Adds newborns to the trial population, including hhid, arm, and household contacts

tbsim.networks.plot_household_structure(households, title='Household Network Structure', figsize=(12, 8))

Plot the structure of household networks showing connections within households.

This function creates a network visualization where: - Nodes represent individual agents - Edges represent household connections (complete graphs within households) - Different colors represent different households - Node size is proportional to household size

Parameters:

Name Type Description Default
households list

List of lists, where each inner list contains agent UIDs in a household

required
title str

Title for the plot

'Household Network Structure'
figsize tuple

Figure size (width, height)

(12, 8)

Returns:

Type Description

networkx.Graph: The NetworkX graph object for further analysis

Example

from tbsim.networks import plot_household_structure households = [[0, 1, 2], [3, 4], [5, 6, 7, 8]] G = plot_household_structure(households, "My Household Network")

Analysis and Visualization

TBsim custom analyzers

tbsim.analyzers.DwellTime(data=None, file_path=None, directory=None, prefix='', states_ennumerator=None, scenario_name='', debug=False)

Bases: Analyzer

Unified dwell-time analysis, aggregation, and visualization.

Constructor mode is auto-detected from the arguments supplied:

  • Plotter mode -- pass data (DataFrame) or file_path (CSV path).
  • Aggregate mode -- pass directory (and optional prefix).
  • Analyzer mode -- pass none of the above; the instance will be attached to a Starsim simulation and record dwell times at each step.

Parameters:

Name Type Description Default
data DataFrame

Pre-loaded dwell-time DataFrame.

None
file_path str

Path to a single CSV file with dwell-time data.

None
directory str

Directory containing CSV result files for aggregation.

None
prefix str

File prefix filter used with directory.

''
states_ennumerator IntEnum

State enumeration class (default tbsim.TBS).

None
scenario_name str

Label for the simulation scenario.

''
debug bool

Enable verbose output.

False

Visualization types (via plot(kind=...)):

  • 'histogram' -- Histograms with KDE per state
  • 'kaplan_meier' -- Kaplan-Meier survival curves
  • 'network' -- Directed graph of state transitions
  • 'validation' -- Observed dwell-time histograms for validation

Example:

Aggregating multiple runs::

    dt = DwellTime(directory='results', prefix='Baseline')
    dt.plot('network')

During simulation::

    sim = ss.Sim(diseases=[TB_EMOD()], analyzers=DwellTime(scenario_name="Baseline"))
    sim.run()
    sim.analyzers[0].plot('validation')

Auto-detect mode (plotter, aggregate, or analyzer) from the supplied arguments.

tbsim.analyzers.DwellTime.finalize()

Finalize the analysis: map state names and save to file.

tbsim.analyzers.DwellTime.plot(kind='histogram', **kwargs)

Create a visualization of the dwell-time data.

Parameters:

Name Type Description Default
kind str

One of 'histogram', 'kaplan_meier', 'network', 'validation'.

'histogram'
**kwargs

Forwarded to the underlying plot method.

{}

Raises:

Type Description
ValueError

If kind is not recognised.

tbsim.analyzers.DwellTime.save_combined_dataframe(output_file)

Save the combined DataFrame to a CSV file.

tbsim.analyzers.DwellTime.step()

Execute one time step of dwell time analysis.

tbsim.analyzers.DwellTime.validate_dwell_time_distributions(expected_distributions=None)

Validate dwell time distributions using KS tests.

Plotting utilities for visualizing TB simulation results

tbsim.plots.FILTERS

Predefined metric-name filters for use with plot_results.

tbsim.plots.out_to(outdir)

Return a timestamped output file path inside outdir, creating the directory if needed.

tbsim.plots.plot_combined(flat_results, keywords=None, exclude=('None',), n_cols=7, dark=True, cmap='plasma', heightfold=2, style='default', savefig=False, outdir=None, plot_type='line', marker_styles=None, alpha=0.85, grid_alpha=0.4, title_fontsize=10, legend_fontsize=7, line_width=0.3, marker_size=2, markeredgewidth=0.2, grid_linewidth=0.5, spine_linewidth=0.5, label_fontsize=6, tick_fontsize=6, filter=None, title='', shared_legend=True, legend_position='upper left')

Visualize simulation outputs from multiple scenarios in a structured grid layout.

Parameters:

Name Type Description Default
flat_results dict

Nested dictionary of the form: { 'Scenario A': {'metric1': Result, 'metric2': Result, ...}, 'Scenario B': {'metric1': Result, 'metric2': Result, ...}, ... } Each Result must have timevec and values attributes representing time series data for a given metric.

required
keywords list[str]

If provided, only plot metrics containing at least one of these substrings.

None
exclude tuple[str]

Substrings of metric names to skip. Default is ('15',).

('None',)
n_cols int

Number of columns in the plot grid. Default is 5.

7
dark bool

If True (default), uses a gray-on-dark theme for improved contrast.

True
cmap str

Name of a matplotlib colormap (e.g., 'viridis', 'tab10', 'plasma'). Default is 'plasma'.

'plasma'
heightfold int

Height multiplier per row of subplots. Default is 3.

2
style str

Matplotlib style to apply. Defaults to 'default'. Falls back to 'default' if not found.

'default'
savefig bool

If True, saves the figure as a PNG file with a timestamped filename.

False
outdir str

Directory to save the figure. If None, saves in the current script's directory under 'results'.

None
plot_type str

Type of plot to use for each metric ('line' or 'scatter'). Default is 'line'.

'line'
marker_styles list[str]

List of marker styles for scatter plots. Defaults to a preset list.

None
alpha float

Transparency for lines/markers. Default is 0.85.

0.85
grid_alpha float

Transparency for grid lines. Default is 0.4.

0.4
title_fontsize int

Font size for subplot titles. Default is 10.

10
legend_fontsize int

Font size for legends. Default is 6.

7
line_width float

Line width for line plots. Default is 0.2.

0.3
marker_size int

Marker size for scatter and line plots. Default is 3.

2
markeredgewidth float

Marker edge width. Default is 0.5.

0.2
grid_linewidth float

Grid line width. Default is 0.5.

0.5
spine_linewidth float

Axis spine line width. Default is 0.5.

0.5
label_fontsize int

Font size for axis labels. Default is 9.

6
tick_fontsize int

Font size for axis tick labels. Default is 5.

6
shared_legend bool

If True, creates a single shared legend for all subplots. Default is True.

True
legend_position str

Position for the shared legend. Options: 'upper right', 'upper left', 'lower right', 'lower left', 'center', etc. Default is 'upper right'.

'upper left'

Returns:

Name Type Description
None

The figure is displayed and also saved as a PNG with a timestamped filename.

Workflow
  1. Collects all metric names across scenarios.
  2. Filters metrics based on keywords and exclude.
  3. Lays out subplots based on the number of metrics and specified n_cols.
  4. Iterates over each metric and plots it across all scenarios.
  5. Adjusts appearance (background, style, gridlines, labels).
  6. Saves the figure as 'scenarios_.png'.
Example

results = { ... 'BCG': { ... 'incidence': Result(timevec=[0, 1, 2], values=[0.1, 0.2, 0.3]), ... 'mortality': Result(timevec=[0, 1, 2], values=[0.05, 0.07, 0.1]) ... }, ... 'TPT': { ... 'incidence': Result(timevec=[0, 1, 2], values=[0.08, 0.15, 0.25]), ... 'mortality': Result(timevec=[0, 1, 2], values=[0.03, 0.05, 0.08]) ... } ... } plot_results(results, keywords=['incidence'], n_cols=2, dark=False, cmap='viridis', plot_type='scatter')

NOTE:

This plotting utility assumes results have already been flattened, such that each scenario maps to a dictionary of named time series outputs. This structure enables clean side-by-side comparisons of metrics like incidence or mortality across scenarios in a single visual layout.

FLATTENING RESULTS:

This line: >>> results['Any_Name'] = sim.results.flatten() <-- The name will be used for the series name

Converts the simulation's time series outputs into a flat dictionary or DataFrame. Makes results easier to compare across scenarios (e.g., plotting incidence over time). The results dictionary now maps scenario names to their flattened outputs: { 'BCG': , 'TPT': , ... }

tbsim.plots.plot_results(flat_results, keywords=None, exclude=('None',), n_cols=5, dark=True, cmap='tab20', heightfold=2, style='default', savefig=True, outdir=None, metric_filter=None, title='', shared_legend=True, legend_position='upper right')

Visualize simulation outputs from multiple scenarios in a structured grid layout.

Parameters:

Name Type Description Default
flat_results dict

Nested dictionary of the form: { 'Scenario A': {'metric1': Result, 'metric2': Result, ...}, 'Scenario B': {'metric1': Result, 'metric2': Result, ...}, ... } Each Result must have timevec and values attributes representing time series data for a given metric.

required
keywords list[str]

If provided, only plot metrics containing at least one of these substrings.

None
exclude tuple[str]

Substrings of metric names to skip. Default is ('15',).

('None',)
n_cols int

Number of columns in the plot grid. Default is 5.

5
dark bool

If True (default), uses a gray-on-dark theme for improved contrast.

True
cmap str

Name of a matplotlib colormap (e.g., 'viridis', 'tab10'). Default is 'tab20'.

'tab20'
heightfold int

Height multiplier per row of subplots. Default is 3.

2
style str

Matplotlib style to apply. Defaults to 'default'. Falls back to 'default' if not found.

'default'
savefig bool

If True (default), saves the figure as a PNG file with a timestamped filename.

True
outdir str

Directory to save the figure. If None, saves in the current script's directory under 'results'.

None
metric_filter list[str]

List of metric names to plot. If provided, only these metrics will be plotted.

None
shared_legend bool

If True, creates a single shared legend for all subplots. Default is True.

True
legend_position str

Position for the shared legend. Options: 'upper right', 'upper left', 'lower right', 'lower left', 'center', etc. Default is 'upper right'.

'upper right'

Returns:

Name Type Description
None

The figure is displayed and also saved as a PNG with a timestamped filename.

Workflow
  1. Collects all metric names across scenarios.
  2. Filters metrics based on keywords and exclude.
  3. Lays out subplots based on the number of metrics and specified n_cols.
  4. Iterates over each metric and plots it across all scenarios.
  5. Adjusts appearance (background, style, gridlines, labels).
  6. Saves the figure as 'scenarios_.png'.
Example

results = { ... 'BCG': { ... 'incidence': Result(timevec=[0, 1, 2], values=[0.1, 0.2, 0.3]), ... 'mortality': Result(timevec=[0, 1, 2], values=[0.05, 0.07, 0.1]) ... }, ... 'TPT': { ... 'incidence': Result(timevec=[0, 1, 2], values=[0.08, 0.15, 0.25]), ... 'mortality': Result(timevec=[0, 1, 2], values=[0.03, 0.05, 0.08]) ... } ... } plot_results(results, keywords=['incidence'], n_cols=2, dark=False, cmap='viridis')

NOTE:

This plotting utility assumes results have already been flattened, such that each scenario maps to a dictionary of named time series outputs. This structure enables clean side-by-side comparisons of metrics like incidence or mortality across scenarios in a single visual layout.

FLATTENING RESULTS:

This line: >>> results['Any_Name'] = sim.results.flatten() <-- The name will be used for the series name

Converts the simulation's time series outputs into a flat dictionary or DataFrame. Makes results easier to compare across scenarios (e.g., plotting incidence over time). The results dictionary now maps scenario names to their flattened outputs: { 'BCG': , 'TPT': , ... }

Interventions

TBsim Interventions Module

This module contains all intervention classes for the TB simulation.

tbsim.interventions.BCGRoutine(product=None, pars=None, **kwargs)

Bases: TBProductRoutine

Routine BCG vaccination delivery.

Thin wrapper over :class:TBProductRoutine with pediatric defaults (age 0–5, 50 % coverage). Creates a :class:BCGVx product automatically if none is provided.

Parameters:

Name Type Description Default
product BCGVx

The BCG vaccine product (created automatically if not provided).

None
pars dict

Overrides for delivery parameters (coverage, age_range, start, stop).

None

Example::

import starsim as ss
import tbsim
from tbsim.interventions.bcg import BCGRoutine

tb  = tbsim.TB_LSHTM(name='tb')
bcg = BCGRoutine()
sim = ss.Sim(diseases=tb, interventions=bcg, pars=dict(start='2000', stop='2020'))
sim.run()

Initialize BCG routine delivery; defaults to age 0-5 with a standard BCGVx product.

tbsim.interventions.BCGRoutine.update_results()

Record number of currently protected individuals.

tbsim.interventions.BCGVx(pars=None, **kwargs)

Bases: Vx

BCG vaccine product.

Handles immunological take, per-agent modifier sampling, protection duration tracking, and per-step modifier application to disease rr_activation, rr_clearance, and rr_death arrays.

Parameters:

Name Type Description Default
disease str

Key of the disease module to target (default 'tb').

required
p_take bernoulli

Probability of immunological response post-vaccination.

required
dur_immune Dist

Duration of protection (sampled per individual).

required
activation_modifier / clearance_modifier / death_modifier Dist

Per-individual risk-modifier distributions.

required

Initialize BCG product with default efficacy and duration parameters.

tbsim.interventions.BCGVx.administer(people, uids)

Administer BCG to uids (already accepted by the delivery intervention).

Applies p_take filter, samples per-agent modifiers, and sets protection expiry. Does not touch rr_* arrays — that happens in :meth:apply_protection each step.

Returns:

Type Description

ss.uids: UIDs of agents who responded immunologically.

tbsim.interventions.BCGVx.apply_protection()

Multiply rr_* arrays for all currently protected agents.

tbsim.interventions.BCGVx.update_roster()

Expire protection for agents past their expiry time.

tbsim.interventions.BetaByYear(pars=None, *args, **kwargs)

Bases: Intervention

A transmission reduction intervention that modifies the tuberculosis transmission rate (beta) at specified time points during the simulation.

This intervention allows for modeling population-wide changes that affect disease transmission, such as policy changes, behavioral modifications, environmental improvements, or calibration scenarios. The intervention multiplies the current beta value by a specified factor at each target year, creating a sustained reduction in transmission rates.

IMPORTANT:

The modifier (x_beta) is always applied to the current/latest value of beta at the time of intervention, not the original or baseline value. This means that if multiple interventions are scheduled, each one will multiply the beta value as it exists after all previous modifications. The effect is cumulative and multiplicative.

For example
  • If beta starts at 0.01, and x_beta=0.5 is applied in 2000, beta becomes 0.005.
  • If another x_beta=0.8 is applied in 2010, beta becomes 0.004 (0.005 * 0.8).
  • This is NOT a reset to the original value; each change compounds on the last.

Attributes:

Name Type Description
years list

List of years when the intervention should be applied. Default is [2000].

x_beta float or list

Multiplicative factor(s) to apply to the current beta value. - If a single value, it is applied to all years. - If a list, it must be the same length as years, and each value is applied to the corresponding year.

applied_years set

(Deprecated) No longer used; interventions are now removed after application.

Behavior
  • Each (year, x_beta) pair is applied only once. After application, both are removed from their lists.
  • If x_beta is a list, its length must match years, or a ValueError is raised.
  • Changes are applied to both the main disease beta parameter and all mixing pools in the network to ensure consistency.
  • This is a multiplicative change, not additive. For example, x_beta=0.5 reduces transmission by 50%, while x_beta=0.8 reduces it by 20%.
  • Multiple interventions compound: Each new x_beta is applied to the already-modified beta value.

Examples:

# Reduce transmission by 50% in 2000
intervention = BetaByYear(pars={'years': [2000], 'x_beta': 0.5})

# Reduce transmission by 30% in multiple years (same factor)
intervention = BetaByYear(pars={'years': [2000, 2010, 2020], 'x_beta': 0.7})

# Use different factors for each year
intervention = BetaByYear(pars={'years': [2000, 2010, 2020], 'x_beta': [0.7, 0.8, 0.9]})

# Increase transmission by 20% in 2015
intervention = BetaByYear(pars={'years': [2015], 'x_beta': 1.2})

Initialize the BetaByYear intervention.

Parameters:

Name Type Description Default
pars dict

Dictionary containing intervention parameters. - 'years' (list of ints): Years to apply the intervention. - 'x_beta' (float or list): Multiplicative factor(s) for beta. If a list, must match years.

None
*args

Additional positional arguments passed to parent class

()
**kwargs

Additional keyword arguments passed to parent class

{}

Raises:

Type Description
ValueError

If x_beta is a list and its length does not match years.

tbsim.interventions.BetaByYear.step()

Execute the intervention step, applying beta modifications at specified years.

tbsim.interventions.EnhancedTBDiagnostic(pars=None, **kwargs)

Bases: Intervention

Enhanced TB diagnostic intervention that combines detailed parameter stratification from interventions_updated.py with health-seeking integration from tb_diagnostic.py.

This intervention provides: 1. Age and TB state-specific sensitivity/specificity parameters 2. HIV-stratified parameters for LAM testing 3. Integration with health-seeking behavior 4. False negative handling with care-seeking multipliers 5. Comprehensive result tracking

Initialize with age/HIV-stratified sensitivity and specificity for multiple diagnostic methods.

tbsim.interventions.EnhancedTBDiagnostic.init_results()

Define result channels for test counts by outcome and diagnostic method.

tbsim.interventions.EnhancedTBDiagnostic.p_test_positive(sim, uids) staticmethod

Calculate per-individual probability of a positive test result.

tbsim.interventions.EnhancedTBDiagnostic.step()

Test care-seekers using the appropriate diagnostic method and record results.

tbsim.interventions.EnhancedTBDiagnostic.update_results()

Record per-step and cumulative test counts by outcome and method.

tbsim.interventions.EnhancedTBTreatment(pars=None, **kwargs)

Bases: Intervention

Enhanced TB treatment intervention that implements configurable drug types and treatment protocols.

This intervention manages the treatment of diagnosed TB cases by: - Selecting eligible individuals for treatment - Applying drug-specific treatment protocols - Tracking treatment outcomes (success/failure) - Managing post-treatment care-seeking behavior - Recording comprehensive treatment statistics

Parameters:

Name Type Description Default
drug_type TBDrugType

The type of drug regimen to use for treatment. Options include: - DOTS: Standard DOTS protocol - DOTS_IMPROVED: Enhanced DOTS with better adherence - FIRST_LINE_COMBO: First-line combination therapy

required
treatment_success_rate float, default 0.85

Base treatment success rate (can be overridden by drug-specific parameters)

required
reseek_multiplier float, default 2.0

Multiplier applied to care-seeking probability after treatment failure

required
reset_flags bool, default True

Whether to reset diagnosis and testing flags after treatment failure

required

Attributes:

Name Type Description
drug_parameters TBDrugTypeParameters

Drug-specific parameters including cure rates and side effects

new_treated list

List of UIDs of individuals who started treatment in the current timestep

successes list

List of UIDs of individuals who successfully completed treatment

failures list

List of UIDs of individuals who failed treatment

drug_type_assignments dict

Mapping of individual UIDs to assigned drug types

Examples: Create a standard DOTS treatment intervention:

treatment = EnhancedTBTreatment(drug_type=TBDrugType.DOTS)

Create a first-line combination treatment with custom parameters:

treatment = EnhancedTBTreatment( ... drug_type=TBDrugType.FIRST_LINE_COMBO, ... reseek_multiplier=3.0, ... reset_flags=False ... )

Track treatment outcomes over time:

treatment = EnhancedTBTreatment()

After running simulation

cumulative_success = treatment.results['cum_treatment_success'] treatment_failures = treatment.results['n_treatment_failure']

Initialize the enhanced TB treatment intervention.

Parameters:

Name Type Description Default
pars dict

Dictionary of parameters to override defaults

None
**kwargs

Additional keyword arguments passed to parent class

{}

tbsim.interventions.EnhancedTBTreatment.init_results()

Initialize results tracking for the intervention.

This method sets up the data structures needed to track: - Number of individuals treated per timestep - Treatment success and failure counts - Cumulative treatment outcomes over time - Drug type used in each timestep

The results are designed to facilitate epidemiological analysis and intervention effectiveness evaluation.

tbsim.interventions.EnhancedTBTreatment.step()

Execute one timestep of enhanced TB treatment.

This method performs the following operations: 1. Identifies eligible individuals (diagnosed with active TB) 2. Initiates treatment for eligible cases 3. Determines treatment outcomes based on drug-specific success rates 4. Updates individual states and flags based on outcomes 5. Manages post-treatment care-seeking behavior 6. Records treatment statistics for analysis

The treatment process follows standard TB treatment protocols where: - Successful treatment clears TB infection and restores susceptibility - Failed treatment triggers renewed care-seeking with increased probability - Treatment history is tracked for epidemiological analysis

tbsim.interventions.EnhancedTBTreatment.update_results()

Update results for the current timestep.

This method records the treatment outcomes from the current timestep and maintains running totals for cumulative analysis. It processes: - Current timestep treatment counts - Success and failure outcomes - Drug type information - Cumulative totals for epidemiological analysis

The results are stored in the intervention's results dictionary and can be accessed for post-simulation analysis and visualization.

tbsim.interventions.HealthSeekingBehavior(pars=None, **kwargs)

Bases: Intervention

Eligible agents (symptomatic in LSHTM; smear+/smear-/EPTB in legacy TB) seek care at a rate per timestep. If the people object has a sought_care attribute, it is set to True for agents who seek care (for use by downstream interventions).

Example

::

import starsim as ss
import tbsim
from tbsim.interventions.tb_health_seeking import HealthSeekingBehavior

tb  = tbsim.TB_LSHTM()
hsb = HealthSeekingBehavior()
sim = ss.Sim(diseases=tb, interventions=hsb, pars=dict(start='2000', stop='2020'))
sim.run()

Initialize with care-seeking rate, retry logic, and eligible-state configuration.

tbsim.interventions.HealthSeekingBehavior.tbsl property

Shortcut to the TBSL state enum.

tbsim.interventions.HealthSeekingBehavior.init_post()

Locate the TB disease module and resolve eligible states.

tbsim.interventions.HealthSeekingBehavior.init_results()

Define result channels for care-seeking counts.

tbsim.interventions.HealthSeekingBehavior.step()

Identify eligible symptomatic agents and stochastically trigger care-seeking.

tbsim.interventions.HealthSeekingBehavior.update_results()

Record new, current, and cumulative care-seeking counts.

tbsim.interventions.TBDiagnostic(pars=None, **kwargs)

Bases: Intervention

TB diagnostic intervention that performs testing on individuals who seek care.

This intervention simulates TB diagnostic testing with configurable sensitivity and specificity. It is triggered when individuals seek care and can handle false negatives by allowing retesting with increased care-seeking probability.

The intervention models the diagnostic cascade in TB care, where individuals who seek healthcare are tested for TB using diagnostic tests with known sensitivity and specificity. The intervention handles both true positive/negative results and false positive/negative results, with special logic for false negatives to allow retesting.

Use Cases:

  • Simulating TB diagnostic programs in healthcare settings
  • Evaluating the impact of diagnostic test performance on TB case detection
  • Modeling diagnostic coverage and its effect on TB transmission
  • Assessing the role of false negatives in TB care-seeking behavior
  • Studying the effectiveness of different diagnostic strategies

Inputs/Requirements:

The intervention requires the following to be present in the simulation: - TB disease module (accessed via tbsim.get_tb(sim)) with active TB states - Health seeking behavior intervention that sets the 'sought_care' flag - Person states: 'sought_care', 'tested', 'diagnosed', 'n_times_tested', 'test_result', 'care_seeking_multiplier', 'multiplier_applied' - TB states: ACTIVE_SMPOS, ACTIVE_SMNEG, ACTIVE_EXPTB for active TB cases

Parameters:

coverage (float or Dist): Fraction of those who sought care who get tested. Can be a fixed probability or a distribution. Range: 0.0 to 1.0. Default: 1.0 (all eligible get tested). sensitivity (float): Probability that a test is positive given the person has TB. Range: 0.0 to 1.0. Higher values mean fewer false negatives. Default: 0.9 (90% sensitivity). specificity (float): Probability that a test is negative given the person does not have TB. Range: 0.0 to 1.0. Higher values mean fewer false positives. Default: 0.95 (95% specificity). reset_flag (bool): Whether to reset the sought_care flag after testing. Default: False (allows for retesting). care_seeking_multiplier (float): Multiplier applied to care-seeking probability for individuals with false negative results. Default: 1.0 (no change).

Outputs/Reports:

The intervention generates the following results that can be accessed via sim.results: - n_tested (int): Number of people tested at each timestep - n_test_positive (int): Number of positive test results at each timestep - n_test_negative (int): Number of negative test results at each timestep - cum_test_positive (int): Cumulative number of positive test results - cum_test_negative (int): Cumulative number of negative test results

Person States Modified:

The intervention modifies the following person states: - tested (bool): Set to True for all tested individuals - n_times_tested (int): Incremented for each test performed - test_result (bool): True for positive results, False for negative results - diagnosed (bool): Set to True for positive test results - care_seeking_multiplier (float): Multiplied by care_seeking_multiplier parameter for false negative cases to increase future care-seeking - multiplier_applied (bool): Tracks whether multiplier has been applied to prevent multiple applications - sought_care (bool): Reset to False for false negative cases to allow retesting

Algorithm:

  1. Identify eligible individuals (sought care, not diagnosed, alive)
  2. Apply coverage filter to select who gets tested
  3. Determine TB status for selected individuals
  4. Apply test sensitivity and specificity logic:
  5. True TB cases: test positive with probability = sensitivity
  6. Non-TB cases: test positive with probability = (1 - specificity)
  7. Update person states based on test results
  8. Handle false negatives by:
  9. Increasing care-seeking probability for future attempts
  10. Resetting care-seeking and testing flags to allow retesting

Example:

sim = ss.Sim( ... interventions=[ ... tbsim.HealthSeekingBehavior(pars={'initial_care_seeking_rate': ss.perday(0.1)}), ... tbsim.TBDiagnostic(pars={ ... 'coverage': 0.8, ... 'sensitivity': 0.85, ... 'specificity': 0.95, ... 'care_seeking_multiplier': 2.0 ... }) ... ] ... )

Initialize the TB diagnostic intervention.

This method sets up the diagnostic intervention with default parameters and initializes temporary storage for result tracking. The intervention is ready to be added to a simulation after initialization.

Parameters:

Name Type Description Default
pars dict

Dictionary of parameters to override defaults. Valid keys: 'coverage', 'sensitivity', 'specificity', 'reset_flag', 'care_seeking_multiplier'.

None
**kwargs

Additional keyword arguments passed to parent class.

{}

Default Parameters:

  • coverage: 1.0 (all eligible individuals get tested)
  • sensitivity: 0.9 (90% sensitivity)
  • specificity: 0.95 (95% specificity)
  • reset_flag: False (allows retesting)
  • care_seeking_multiplier: 1.0 (no change to care-seeking probability)

Raises:

ValueError: If parameter values are outside valid ranges (0.0-1.0 for probabilities).

Note:

The intervention requires specific person states to be present in the simulation. These are typically initialized by the TB disease module and health seeking behavior intervention.

tbsim.interventions.TBDiagnostic.init_results()

Initialize result tracking for the diagnostic intervention.

This method sets up the result tracking system for the diagnostic intervention. It defines the metrics that will be recorded at each timestep and makes them available for analysis and reporting.

Result Metrics:
  • n_tested (int): Number of people tested at each timestep
  • n_test_positive (int): Number of positive test results at each timestep
  • n_test_negative (int): Number of negative test results at each timestep
  • cum_test_positive (int): Cumulative number of positive test results
  • cum_test_negative (int): Cumulative number of negative test results
Usage:

Results can be accessed after simulation completion via: - sim.results['TBDiagnostic']['n_tested'] - sim.results['TBDiagnostic']['n_test_positive'] - etc.

Note:

This method is called automatically by the simulation framework during initialization. The results are updated each timestep by update_results().

tbsim.interventions.TBDiagnostic.step()

Execute one timestep of TB diagnostic testing.

This method performs the core diagnostic testing logic for each simulation timestep. It identifies eligible individuals, applies diagnostic tests with specified sensitivity and specificity, and handles the consequences of test results including false negatives.

Process Flow:
  1. Identify eligible individuals (sought care, not diagnosed, alive)
  2. Apply coverage filter to select who gets tested
  3. Determine TB status and apply test sensitivity/specificity
  4. Update person states based on test results
  5. Handle false negatives by allowing retesting with increased care-seeking probability
Eligibility Criteria:
  • Individual must have sought care (sought_care = True)
  • Individual must not be already diagnosed (diagnosed = False)
  • Individual must be alive (alive = True)
Test Logic:
  • True TB cases: test positive with probability = sensitivity
  • Non-TB cases: test positive with probability = (1 - specificity)
False Negative Handling:
  • Individuals with TB who test negative are identified as false negatives
  • Their care-seeking probability is increased by the care_seeking_multiplier
  • Their care-seeking and testing flags are reset to allow retesting
  • The multiplier is only applied once per individual to prevent infinite boosting
Side Effects:
  • Updates person states: tested, n_times_tested, test_result, diagnosed
  • Modifies care_seeking_multiplier and multiplier_applied for false negatives
  • Resets sought_care and tested flags for false negatives
  • Stores results for update_results method
Returns:

None

Note:

This method is called automatically by the simulation framework at each timestep. The intervention must be added to the simulation's interventions list to be executed.

tbsim.interventions.TBDiagnostic.update_results()

Update result tracking for the current timestep.

This method records the diagnostic testing results for the current timestep and updates cumulative totals. It processes the temporary storage from the step() method and stores the results in the intervention's result arrays.

Process:
  1. Calculate per-step counts from temporary storage
  2. Record current timestep results
  3. Update cumulative totals (add to previous step's cumulative)
  4. Reset temporary storage for next timestep
Calculations:
  • n_tested: Total number of people tested this timestep
  • n_test_positive: Number of positive test results this timestep
  • n_test_negative: Number of negative test results this timestep
  • cum_test_positive: Cumulative positive results (previous + current)
  • cum_test_negative: Cumulative negative results (previous + current)
Data Sources:
  • self.tested_this_step: Array of UIDs tested this timestep
  • self.test_result_this_step: Array of test results (True/False)
Note:

This method is called automatically by the simulation framework after each timestep. The temporary storage is reset after processing to prepare for the next timestep.

tbsim.interventions.TBDrugParameters(drug_name, drug_type)

Base class for TB drug parameters.

This class defines the standard parameters that all TB drugs have, similar to EMOD-Generic's TBDrugTypeParameters. It provides a consistent interface for accessing drug-specific effects and characteristics.

Attributes:

Name Type Description
drug_name

Human-readable name of the drug regimen

drug_type

TBDrugType enum value for this drug

inactivation_rate

Rate at which the drug inactivates TB bacteria

cure_prob

Probability of successful cure with this drug

resistance_rate

Rate at which resistance develops to this drug

relapse_rate

Rate of relapse after successful treatment

mortality_rate

Reduction in mortality rate due to treatment

primary_decay_time_constant

Time constant for drug effectiveness decay

duration

Standard treatment duration in days

adherence_rate

Expected adherence rate for this regimen

cost_per_course

Cost per complete treatment course in USD

Example

params = TBDrugParameters("Test Drug", TBDrugType.DOTS) params.configure({'cure_prob': 0.85, 'duration': 180}) print(f"Cure rate: {params.cure_prob}")

Initialize drug parameters.

Parameters:

Name Type Description Default
drug_name

Name of the drug regimen (e.g., "DOTS", "First Line Combo")

required
drug_type

Type of drug from TBDrugType enum

required
Example

params = TBDrugParameters("DOTS", TBDrugType.DOTS) params.drug_name 'DOTS' params.drug_type

tbsim.interventions.TBDrugParameters.__repr__()

String representation of the drug parameters.

Returns:

Type Description

String showing drug name and type

Example

params = TBDrugParameters("DOTS", TBDrugType.DOTS) repr(params) 'TBDrugParameters(DOTS, type=DOTS)'

tbsim.interventions.TBDrugParameters.configure(parameters)

Configure drug parameters from a dictionary.

This method allows setting multiple parameters at once by providing a dictionary of parameter names and values. Only parameters that exist as attributes of the object will be set.

Parameters:

Name Type Description Default
parameters

Dictionary containing parameter values to set

required
Example

params = TBDrugParameters("Test", TBDrugType.DOTS) params.configure({ ... 'cure_prob': 0.85, ... 'duration': 180, ... 'cost_per_course': 100 ... }) params.cure_prob 0.85

tbsim.interventions.TBDrugParameters.get_effectiveness(time_on_treatment)

Calculate drug effectiveness based on time on treatment.

This method models how drug effectiveness changes over time during treatment. Effectiveness typically increases initially as the drug builds up in the system, then may decay due to various factors like bacterial adaptation or drug metabolism.

Mathematical Model
  • Days 0-30: Linear increase from 0 to 1.0 (drug building up)
  • Days 30+: Exponential decay with time constant
  • Minimum effectiveness: 10% (drug never completely loses effect)

Parameters:

Name Type Description Default
time_on_treatment

Time in days since treatment started

required

Returns:

Type Description

Effectiveness multiplier (0.0 to 1.0) where 1.0 = 100% effective

Example

params = TBDrugParameters("Test", TBDrugType.DOTS) params.get_effectiveness(0) 0.0 params.get_effectiveness(30) 1.0 params.get_effectiveness(60) 0.368 # Approximately e^(-1)

tbsim.interventions.TBDrugType

Bases: IntEnum

TB Drug Types enumeration matching EMOD-Generic's TBDrugType.

This enum defines the different types of TB drug regimens available, with the same values as EMOD-Generic for compatibility. Each drug type represents a different treatment approach with varying efficacy, cost, and side effect profiles.

Attributes:

Name Type Description
DOTS

Standard Directly Observed Treatment, Short-course (most common)

DOTS_IMPROVED

Enhanced DOTS with better support and monitoring

EMPIRIC_TREATMENT

Treatment without confirmed drug sensitivity

FIRST_LINE_COMBO

First-line combination therapy for drug-sensitive TB

SECOND_LINE_COMBO

Second-line therapy for MDR-TB

THIRD_LINE_COMBO

Third-line therapy for XDR-TB

LATENT_TREATMENT

Treatment for latent TB infection

Example

drug_type = TBDrugType.DOTS print(drug_type.name) # 'DOTS' print(drug_type.value) # 1

tbsim.interventions.TBDrugType.get_all_types() classmethod

Get all drug types as a list.

Returns:

Type Description

List of all TBDrugType enum values

Example

types = TBDrugType.get_all_types() len(types) 7 TBDrugType.DOTS in types True

tbsim.interventions.TBDrugType.get_name(value) classmethod

Get the string name for a drug type value.

Parameters:

Name Type Description Default
value

Integer value of the drug type

required

Returns:

Type Description

String name of the drug type, or 'UNKNOWN_X' if not found

Example

TBDrugType.get_name(1) 'DOTS' TBDrugType.get_name(999) 'UNKNOWN_999'

tbsim.interventions.TBDrugTypeParameters

Factory class for creating drug parameters for different drug types.

This class provides predefined parameter sets for each drug type, similar to how EMOD-Generic configures different drug regimens. Each factory method creates a TBDrugParameters object with realistic values based on clinical evidence and WHO guidelines.

The parameter values are based on: - WHO treatment guidelines - Clinical trial results - Cost-effectiveness studies - Real-world implementation data

Example

dots_params = TBDrugTypeParameters.create_dots_parameters() print(f"DOTS cure rate: {dots_params.cure_prob}") all_params = TBDrugTypeParameters.get_all_parameter_sets() len(all_params) 7

tbsim.interventions.TBDrugTypeParameters.create_dots_improved_parameters() staticmethod

Create parameters for improved DOTS regimen.

Improved DOTS includes enhanced support mechanisms, better patient education, and improved monitoring compared to standard DOTS.

Parameter values based on: - Enhanced DOTS program evaluations - Patient support intervention studies - Improved monitoring system data

Returns:

Type Description

TBDrugParameters object configured for improved DOTS treatment

Example

params = TBDrugTypeParameters.create_dots_improved_parameters() params.cure_prob 0.9 params.adherence_rate 0.9

tbsim.interventions.TBDrugTypeParameters.create_dots_parameters() staticmethod

Create parameters for DOTS regimen.

DOTS (Directly Observed Treatment, Short-course) is the standard TB treatment regimen recommended by WHO. It involves directly observed therapy to ensure adherence and completion.

Parameter values based on: - WHO DOTS guidelines - Meta-analysis of DOTS effectiveness - Cost studies from multiple countries

Returns:

Type Description

TBDrugParameters object configured for DOTS treatment

Example

params = TBDrugTypeParameters.create_dots_parameters() params.cure_prob 0.85 params.duration 180.0

tbsim.interventions.TBDrugTypeParameters.create_empiric_treatment_parameters() staticmethod

Create parameters for empiric treatment.

Empiric treatment is given when drug sensitivity is unknown, typically in emergency situations or when diagnostic testing is not available.

Parameter values based on: - Empiric treatment guidelines - Emergency TB treatment protocols - Unknown sensitivity scenario modeling

Returns:

Type Description

TBDrugParameters object configured for empiric treatment

Example

params = TBDrugTypeParameters.create_empiric_treatment_parameters() params.cure_prob 0.7 params.resistance_rate 0.05

tbsim.interventions.TBDrugTypeParameters.create_first_line_combo_parameters() staticmethod

Create parameters for first-line combination therapy.

First-line combination therapy uses multiple drugs with different mechanisms of action to maximize efficacy and minimize resistance development.

Parameter values based on: - First-line combination therapy trials - Multi-drug regimen effectiveness studies - Resistance prevention data

Returns:

Type Description

TBDrugParameters object configured for first-line combination therapy

Example

params = TBDrugTypeParameters.create_first_line_combo_parameters() params.cure_prob 0.95 params.resistance_rate 0.01

tbsim.interventions.TBDrugTypeParameters.create_latent_treatment_parameters() staticmethod

Create parameters for latent TB treatment.

Latent TB treatment (also called preventive therapy) is given to people with latent TB infection to prevent progression to active disease.

Parameter values based on: - Latent TB treatment guidelines - Preventive therapy efficacy studies - Latent TB treatment outcomes

Returns:

Type Description

TBDrugParameters object configured for latent TB treatment

Example

params = TBDrugTypeParameters.create_latent_treatment_parameters() params.cure_prob 0.9 params.duration 90.0

tbsim.interventions.TBDrugTypeParameters.create_parameters_for_type(drug_type) staticmethod

Create parameters for a specific drug type.

This is the main factory method that routes to the appropriate specific factory method based on the drug type provided.

Parameters:

Name Type Description Default
drug_type

The drug type to create parameters for

required

Returns:

Type Description

TBDrugParameters object with appropriate values

Raises:

Type Description
ValueError

If the drug type is not recognized

Example

params = TBDrugTypeParameters.create_parameters_for_type(TBDrugType.DOTS) params.drug_type params.cure_prob 0.85

tbsim.interventions.TBDrugTypeParameters.create_second_line_combo_parameters() staticmethod

Create parameters for second-line combination therapy.

Second-line therapy is used for MDR-TB cases that have failed first-line treatment or are resistant to first-line drugs.

Parameter values based on: - MDR-TB treatment protocols - Second-line drug efficacy studies - MDR-TB treatment outcomes

Returns:

Type Description

TBDrugParameters object configured for second-line combination therapy

Example

params = TBDrugTypeParameters.create_second_line_combo_parameters() params.cure_prob 0.75 params.duration 240.0

tbsim.interventions.TBDrugTypeParameters.create_third_line_combo_parameters() staticmethod

Create parameters for third-line combination therapy.

Third-line therapy is used for XDR-TB cases that have failed both first and second-line treatments.

Parameter values based on: - XDR-TB treatment protocols - Third-line drug availability and efficacy - XDR-TB treatment outcomes

Returns:

Type Description

TBDrugParameters object configured for third-line combination therapy

Example

params = TBDrugTypeParameters.create_third_line_combo_parameters() params.cure_prob 0.6 params.cost_per_course 1000.0

tbsim.interventions.TBDrugTypeParameters.get_all_parameter_sets() staticmethod

Get all predefined parameter sets.

This method creates parameter sets for all drug types and returns them as a dictionary for easy access and comparison.

Returns:

Type Description

Dictionary mapping drug types to their parameters

Example

all_params = TBDrugTypeParameters.get_all_parameter_sets() len(all_params) 7 all_params[TBDrugType.DOTS].cure_prob 0.85 all_params[TBDrugType.FIRST_LINE_COMBO].cure_prob 0.95

tbsim.interventions.TBProductRoutine(product=None, pars=None, **kwargs)

Bases: Intervention

Generic routine delivery for TB vaccine/treatment products.

Handles date-windowed delivery with composable eligibility filters (age range, disease state, user-provided callable) and orchestrates per-step product operations.

Any product that exposes update_roster(), administer(people, uids), and apply_protection() can be plugged into this delivery.

Parameters:

Name Type Description Default
product Vx

The vaccine/treatment product.

None
coverage bernoulli

Fraction of eligible individuals who accept (applied once per person).

required
start / stop date

Campaign window.

required
age_range list or None

[min_age, max_age] filter, or None to skip.

required
eligible_states list or None

List of disease-state values (e.g. [TBSL.INFECTION]) to filter on, or None to skip.

required
eligibility callable or None

User-provided fn(sim) -> BoolArr | uids for custom filtering (passed through to ss.Intervention).

required

Initialize with a product and delivery parameters (coverage, age range, date window).

tbsim.interventions.TBProductRoutine.check_eligibility()

Combine built-in filters (age, disease state) with optional user-provided eligibility callable. Coverage applied once per person.

tbsim.interventions.TBProductRoutine.init_results()

Define result channels for newly initiated and currently protected counts.

tbsim.interventions.TBProductRoutine.step()

Routine delivery step:

  1. Check date window.
  2. Product handles internal phase transitions (update_roster).
  3. Find and deliver to newly eligible agents.
  4. Product applies rr_* modifiers for all currently protected.

tbsim.interventions.TBProductRoutine.update_results()

Record number of newly initiated individuals this timestep.

tbsim.interventions.TBTreatment(pars=None, **kwargs)

Bases: Intervention

Starts TB treatment for diagnosed individuals and applies treatment success/failure logic.

Requires HealthSeekingBehavior and TBDiagnostic to run upstream in the same simulation; see tbsim_examples/run_tb_interventions.py for a full example.

Parameters:

Name Type Description Default
treatment_success_rate float or Dist

Probability of cure if treated.

required
reseek_multiplier float

Care-seeking multiplier applied after failure.

required
reset_flags bool

Whether to reset tested/diagnosed flags after failure.

required

Initialize with treatment success probability and failure-handling parameters.

tbsim.interventions.TBTreatment.init_results()

Define result channels for treatment counts and outcomes.

tbsim.interventions.TBTreatment.step()

Treat diagnosed active-TB individuals

tbsim.interventions.TBTreatment.update_results()

Record per-step and cumulative treatment success/failure counts.

tbsim.interventions.TPTHousehold(product=None, pars=None, **kwargs)

Bases: TBProductRoutine

Household contact tracing TPT delivery.

Detects new TB treatment starts each step, traces household contacts of followed-up index cases, and offers TPT to all contacts (product handles eligibility filtering).

Requires a household network with household_ids (e.g. HouseholdDHSNet or EvolvingHouseholdDHSNet from starsim_examples).

Parameters:

Name Type Description Default
product TPTTx

The TPT treatment product (created automatically if not provided).

None
pars dict

Overrides. coverage controls the probability that a given index case's household is followed up (per-index-case Bernoulli).

None

Initialize household contact-tracing TPT delivery.

tbsim.interventions.TPTHousehold.check_eligibility()

Detect new treatment starts → follow up index cases → trace household contacts.

tbsim.interventions.TPTHousehold.find_household_net()

Find the network that has household_ids.

tbsim.interventions.TPTHousehold.shrink()

Delete link to household net

tbsim.interventions.TPTHousehold.update_results()

Record number of currently protected individuals.

tbsim.interventions.TPTSimple(product=None, pars=None, **kwargs)

Bases: TBProductRoutine

Simple TPT delivery targeting latently infected agents.

Thin wrapper over :class:TBProductRoutine that defaults to targeting agents in TBSL.INFECTION state (latent TB). Creates a :class:TPTTx product automatically if none is provided.

Parameters:

Name Type Description Default
product TPTTx

The TPT treatment product (created automatically if not provided).

None
pars dict

Overrides for delivery parameters (coverage, age_range, eligible_states, start, stop).

None

Example::

import starsim as ss
import tbsim
from tbsim.interventions.tpt import TPTSimple

tb  = tbsim.TB_LSHTM(name='tb')
tpt = TPTSimple()
sim = ss.Sim(diseases=tb, interventions=tpt, pars=dict(start='2000', stop='2020'))
sim.run()

Initialize simple TPT delivery; defaults to targeting latently infected agents.

tbsim.interventions.TPTSimple.update_results()

Record number of currently protected individuals.

tbsim.interventions.TPTTx(pars=None, **kwargs)

Bases: Product

TPT treatment product.

Models a two-phase intervention: a treatment phase (antibiotic course) followed by a protection phase (residual risk reduction via rr_* modifiers). During treatment, no protection is applied; after treatment completes, rr_activation, rr_clearance, and rr_death are modified each step until protection expires.

Parameters:

Name Type Description Default
disease str

Key of the disease module to target (default 'tb').

required
dur_treatment Dist

Duration of the antibiotic course (default 3 months).

required
dur_protection Dist

Duration of post-treatment protection (default 2 years).

required
activation_modifier / clearance_modifier / death_modifier Dist

Per-individual risk-modifier distributions.

required
exclude_on_treatment bool

If True, skip agents currently on TB treatment (default True).

required

Initialize TPT product with default treatment duration and efficacy parameters.

tbsim.interventions.TPTTx.administer(people, uids)

Start TPT for uids.

Filters out ineligible agents (already on TB treatment, already protected), then samples per-agent modifiers and schedules the protection window.

Returns:

Type Description

ss.uids: UIDs of agents who actually started TPT.

tbsim.interventions.TPTTx.apply_protection()

Multiply rr_* arrays for all currently protected agents.

tbsim.interventions.TPTTx.update_roster()

Start protection for agents whose treatment completed; expire protection for agents past their expiry time.

Comorbidities

tbsim.comorbidities.HIV(pars=None, **kwargs)

Bases: Disease

A simplified agent-based HIV disease model for use with the Starsim framework.

This model tracks HIV state progression through ACUTE, LATENT, and AIDS phases, influenced by whether the agent is receiving ART (antiretroviral therapy).

Parameters:

Name Type Description Default
- init_prev

Initial probability of infection (ACUTE).

required
- init_onart

Probability of being on ART at initialization (if infected).

required
- acute_to_latent

Daily transition probability from ACUTE to LATENT.

required
- latent_to_aids

Daily transition probability from LATENT to AIDS.

required
- aids_to_dead

Daily transition probability from AIDS to DEAD (unused).

required
- art_progression_factor

Multiplier applied to progression probabilities for agents on ART.

required
States
  • state: HIV progression state (ATRISK, ACUTE, LATENT, AIDS, DEAD).
  • on_ART: Boolean indicating whether agent is on ART.
Results
  • hiv_prevalence: Proportion of total agents with HIV.
  • infected: Total number of HIV-positive agents.
  • on_art: Number of agents on ART.
  • atrisk, acute, latent, aids: Percent of population in each state.
  • n_active: Total number of agents in ACUTE, LATENT, or AIDS states.

Example

::

import starsim as ss
from tbsim.comorbidities.hiv import HIV

sim = ss.Sim(diseases=HIV(), pars=dict(start='2000', stop='2020'))
sim.run()

Initialize with default HIV progression parameters; override via pars.

tbsim.comorbidities.HIV.init_results()

Define HIV result channels (prevalence, state counts, ART coverage).

tbsim.comorbidities.HIV.p_acute_to_latent(sim, uids) staticmethod

Calculate probability of HIV ACUTE → LATENT transition.

tbsim.comorbidities.HIV.p_latent_to_aids(sim, uids) staticmethod

Calculate probability of HIV LATENT → AIDS transition.

tbsim.comorbidities.HIV.set_prognoses()

Assign initial HIV infection and ART status (called at t=0).

tbsim.comorbidities.HIV.step()

Progress HIV states; ART reduces transition probabilities.

tbsim.comorbidities.HIV.update_results()

Record HIV state distribution and ART counts for the current timestep.

tbsim.comorbidities.HIVState

Bases: IntEnum

HIV states: uninfected through advanced disease.

tbsim.comorbidities.HivInterventions(pars=None, **kwargs)

Bases: Intervention

Adjust HIV prevalence and/or ART coverage in a simulated population at each timestep within a date window.

Initialize with target prevalence and ART coverage parameters.

tbsim.comorbidities.HivInterventions.step()

Adjust HIV prevalence and ART coverage to match targets each timestep.

tbsim.comorbidities.Malnutrition(pars=None, **kwargs)

Bases: Disease

Malnutrition disease model for tuberculosis simulation studies.

Tracks anthropometric measurements (weight, height) using the LMS (Lambda-Mu-Sigma) method and simulates effects of nutritional interventions on growth and development.

Uses Cole's LMS method for growth reference curves and implements random walk processes for weight percentile evolution.

Parameters:

Name Type Description Default
pars dict

Parameter overrides ('beta', 'init_prev')

None
**kwargs

Additional keyword arguments passed to ss.Disease

{}
States

receiving_macro (bool): Whether individual receives macronutrient supplementation receiving_micro (bool): Whether individual receives micronutrient supplementation height_percentile (float): Height percentile (0-1), assumed constant weight_percentile (float): Weight percentile (0-1), evolves over time micro (float): Micronutrient status z-score, evolves over time

Example

::

import starsim as ss
import tbsim
from tbsim.comorbidities.malnutrition import Malnutrition, TB_Nutrition_Connector

tb   = tbsim.TB_LSHTM(name='tb')
mn   = Malnutrition(name='malnutrition')
conn = TB_Nutrition_Connector()
sim  = ss.Sim(diseases=[tb, mn], connectors=conn,
              pars=dict(start='2000', stop='2020'))
sim.run()

References: - https://www.ncbi.nlm.nih.gov/pmc/articles/PMC10876842/ - https://www.ncbi.nlm.nih.gov/pmc/articles/PMC9971264/

Initialize with default malnutrition parameters; override via pars.

tbsim.comorbidities.Malnutrition.dweight_scale(sim, uids) staticmethod

Scale parameter for weight change distribution: 0.01 * time_index.

tbsim.comorbidities.Malnutrition.height(uids=None)

Calculate height (cm) from height percentiles using LMS method.

tbsim.comorbidities.Malnutrition.init_results()

Initialize results tracking.

tbsim.comorbidities.Malnutrition.lms(percentile, uids=None, metric='Weight')

Calculate anthropometric measurements using the LMS method.

Converts percentiles to actual measurements (weight/height) using age- and sex-specific LMS parameters interpolated from reference data.

Parameters:

Name Type Description Default
percentile ndarray

Percentile values (0-1)

required
uids ndarray

Individual IDs (default: all alive)

None
metric str

'Weight', 'Height', 'Length', or 'BMI'

'Weight'

Returns:

Type Description

np.ndarray: Measurements in native units (kg, cm, or kg/m^2)

tbsim.comorbidities.Malnutrition.set_initial_states(sim)

Set initial state values (placeholder for future correlated weight/height).

tbsim.comorbidities.Malnutrition.step()

Update weight percentiles via random walk each time step.

tbsim.comorbidities.Malnutrition.update_results()

Record proportion of individuals alive at this time step.

tbsim.comorbidities.Malnutrition.weight(uids=None)

Calculate weight (kg) from weight percentiles using LMS method.

tbsim.comorbidities.TB_HIV_Connector(pars=None, **kwargs)

Bases: Connector

Connector between TB and HIV: multiplies TB activation risk by HIV-state-dependent relative risk factors (ACUTE: 1.2202, LATENT: 1.9001, AIDS: 2.5955).

Example

::

import starsim as ss
import tbsim
from tbsim.comorbidities.hiv import HIV, HivInterventions, TB_HIV_Connector

tb   = tbsim.TB_LSHTM(name='tb')
hiv  = HIV(name='hiv')
conn = TB_HIV_Connector()
intv = HivInterventions()
sim  = ss.Sim(diseases=[tb, hiv], connectors=conn, interventions=intv,
              pars=dict(start='2000', stop='2020'))
sim.run()

Initialize with HIV-state-dependent TB risk multipliers.

tbsim.comorbidities.TB_HIV_Connector.compute_tb_hiv_risk_rr(tb, hiv, uids, base_factor=1.0) staticmethod

Compute per-agent TB relative risk multiplier based on HIV state.

tbsim.comorbidities.TB_HIV_Connector.step()

Apply HIV-based risk multipliers to TB activation rates.

tbsim.comorbidities.TB_Nutrition_Connector(pars=None, **kwargs)

Bases: Connector

Connector between TB and Malnutrition disease models.

Modifies TB transition rates based on nutritional status: - Activation risk ratio: how malnutrition affects latent-to-active TB - Clearance risk ratio: how malnutrition affects TB recovery - Relative susceptibility: how malnutrition affects new TB infection risk

Parameters:

Name Type Description Default
pars dict

Override functions for 'rr_activation_func', 'rr_clearance_func', 'relsus_func'

None
**kwargs

Additional keyword arguments passed to ss.Connector

{}

Initialize with pluggable risk-ratio and relative-susceptibility functions.

tbsim.comorbidities.TB_Nutrition_Connector.compute_relsus(tb, mn, uids) staticmethod

Relative susceptibility: 2x if micronutrient status < 0.2, else 1x.

tbsim.comorbidities.TB_Nutrition_Connector.lonnroth_bmi_rr(tb, mn, uids, scale=2, slope=3, bmi50=25) staticmethod

Sigmoid BMI-based risk ratio following Lonnroth et al. log-linear relationship.

tbsim.comorbidities.TB_Nutrition_Connector.ones_rr(tb, mn, uids) staticmethod

Neutral risk ratios (all ones, no effect).

tbsim.comorbidities.TB_Nutrition_Connector.step()

Apply nutritional effects to TB transition rates each time step.

tbsim.comorbidities.TB_Nutrition_Connector.supplementation_rr(tb, mn, uids, rate_ratio=0.5) staticmethod

Risk ratio based on supplementation: rate_ratio for those receiving both macro+micro, else 1.