TB Disease Model

This module implements the core tuberculosis disease model for TBsim simulations, including disease dynamics, state transitions, and transmission modeling.

Main TB Module

class tbsim.tb.TB(*args: Any, **kwargs: Any)[source]

Bases: Infection

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.

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

__init__(pars=None, **kwargs)[source]

Initialize the TB disease model.

Parameters:
  • pars – Dictionary of parameters to override defaults

  • **kwargs – Additional keyword arguments for parameters

p_latent_to_presym(sim, uids)[source]

Calculate probability of transition from latent to pre-symptomatic TB.

This method computes the daily probability that individuals in latent TB states will progress to active pre-symptomatic TB. The calculation uses different base rates for slow vs. fast progressors and applies individual risk modifiers.

Mathematical Details: - Slow progressors: rate_LS_to_presym = 3e-5 per day - Fast progressors: rate_LF_to_presym = 6e-3 per day - Individual risk: rate *= rr_activation[uids] - Final probability: 1 - exp(-rate * dt)

State Requirements: All individuals must be in TBS.LATENT_SLOW or TBS.LATENT_FAST states.

Parameters:
  • sim (starsim.Sim) – Simulation object containing time step information

  • uids (numpy.ndarray) – Array of individual IDs to evaluate (must be in latent states)

Returns:

Daily transition probabilities for each individual (0.0 to 1.0)

Return type:

numpy.ndarray

Raises:

AssertionError – If any individuals are not in latent states (LATENT_SLOW or LATENT_FAST)

Example

>>> probs = tb.p_latent_to_presym(sim, latent_uids)
>>> transition_mask = np.random.random(len(probs)) < probs
>>> new_presymp_uids = latent_uids[transition_mask]
p_presym_to_clear(sim, uids)[source]

Calculate probability of transition from pre-symptomatic to clearance.

This method computes the daily probability that individuals in pre-symptomatic TB will clear the infection. The probability is zero for untreated individuals and follows the treatment clearance rate for those on treatment.

Mathematical Details: - Untreated individuals: probability = 0.0 (no spontaneous clearance) - Treated individuals: rate_treatment_to_clear = 6 per year (2-month treatment duration) - Final probability: 1 - exp(-rate * dt) for treated individuals

State Requirements: All individuals must be in TBS.ACTIVE_PRESYMP state.

Treatment Dependency: This transition only occurs for individuals with on_treatment = True.

Parameters:
  • sim (starsim.Sim) – Simulation object containing time step information

  • uids (numpy.ndarray) – Array of individual IDs to evaluate (must be pre-symptomatic)

Returns:

Daily clearance probabilities for each individual (0.0 for untreated, >0.0 for treated)

Return type:

numpy.ndarray

Raises:

AssertionError – If any individuals are not in pre-symptomatic state (ACTIVE_PRESYMP)

Example

>>> probs = tb.p_presym_to_clear(sim, presym_uids)
>>> clear_mask = np.random.random(len(probs)) < probs
>>> cleared_uids = presym_uids[clear_mask]  # Only treated individuals will clear
p_presym_to_active(sim, uids)[source]

Calculate probability of transition from pre-symptomatic to active TB.

This method computes the daily probability that individuals in pre-symptomatic TB will progress to symptomatic active TB. The probability is uniform for all individuals in this state, representing the natural progression of disease.

Mathematical Details: - Base rate: rate_presym_to_active = 3e-2 per day - No individual risk modifiers applied (uniform progression) - Final probability: 1 - exp(-rate * dt)

State Requirements: All individuals must be in TBS.ACTIVE_PRESYMP state.

Active State Assignment: Upon transition, individuals are assigned to specific active states based on their pre-determined active_tb_state (SMPOS, SMNEG, or EXPTB).

Parameters:
  • sim (starsim.Sim) – Simulation object containing time step information

  • uids (numpy.ndarray) – Array of individual IDs to evaluate (must be pre-symptomatic)

Returns:

Daily progression probabilities for each individual (uniform values)

Return type:

numpy.ndarray

Raises:

AssertionError – If any individuals are not in pre-symptomatic state (ACTIVE_PRESYMP)

Example

>>> probs = tb.p_presym_to_active(sim, presym_uids)
>>> active_mask = np.random.random(len(probs)) < probs
>>> new_active_uids = presym_uids[active_mask]
>>> # Assign specific active states based on active_tb_state[new_active_uids]
p_active_to_clear(sim, uids)[source]

Calculate probability of transition from active TB to clearance.

This method computes the daily probability that individuals with active TB will clear the infection. The probability depends on treatment status and includes individual risk modifiers for natural clearance.

Mathematical Details: - Natural clearance: rate_active_to_clear = 2.4e-4 per day - Treatment clearance: rate_treatment_to_clear = 6 per year (2-month duration) - Individual risk: rate *= rr_clearance[uids] - Final probability: 1 - exp(-rate * dt)

State Requirements: All individuals must be in active TB states (ACTIVE_SMPOS, ACTIVE_SMNEG, or ACTIVE_EXPTB).

Treatment Effect: Treated individuals use the higher treatment clearance rate instead of natural clearance.

Post-Clearance State: Upon clearance, individuals return to TBS.NONE (susceptible) and can be reinfected.

Parameters:
  • sim (starsim.Sim) – Simulation object containing time step information

  • uids (numpy.ndarray) – Array of individual IDs to evaluate (must be in active states)

Returns:

Daily clearance probabilities for each individual (varies by treatment status)

Return type:

numpy.ndarray

Raises:

AssertionError – If any individuals are not in active states (SMPOS, SMNEG, or EXPTB)

Example

>>> probs = tb.p_active_to_clear(sim, active_uids)
>>> clear_mask = np.random.random(len(probs)) < probs
>>> cleared_uids = active_uids[clear_mask]
>>> # These individuals will return to susceptible state
p_active_to_death(sim, uids)[source]

Calculate probability of transition from active TB to death.

This method computes the daily probability that individuals with active TB will die from the disease. The probability varies significantly by active TB type and includes individual risk modifiers.

Mathematical Details: - Smear positive: rate_smpos_to_dead = 4.5e-4 per day (highest mortality) - Smear negative: rate_smneg_to_dead = 0.3 * 4.5e-4 per day (30% of smear positive) - Extra-pulmonary: rate_exptb_to_dead = 0.15 * 4.5e-4 per day (15% of smear positive) - Individual risk: rate *= rr_death[uids] - Final probability: 1 - exp(-rate * dt)

State Requirements: All individuals must be in active TB states (ACTIVE_SMPOS, ACTIVE_SMNEG, or ACTIVE_EXPTB).

Treatment Effect: Treated individuals have rr_death = 0, effectively preventing TB mortality.

Death Process: Upon death, individuals are marked as TBS.DEAD and removed from transmission.

Parameters:
  • sim (starsim.Sim) – Simulation object containing time step information

  • uids (numpy.ndarray) – Array of individual IDs to evaluate (must be in active states)

Returns:

Daily death probabilities for each individual (varies by TB type and treatment)

Return type:

numpy.ndarray

Raises:

AssertionError – If any individuals are not in active states (SMPOS, SMNEG, or EXPTB)

Example

>>> probs = tb.p_active_to_death(sim, active_uids)
>>> death_mask = np.random.random(len(probs)) < probs
>>> death_uids = active_uids[death_mask]
>>> # These individuals will be marked for death by the simulation framework
property infectious

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:

Boolean array indicating infectious status for each individual

Return type:

numpy.ndarray

Example

>>> infectious_uids = tb.infectious.uids
>>> print(f"Number of infectious individuals: {len(infectious_uids)}")
set_prognoses(uids, sources=None)[source]

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:
  • uids (numpy.ndarray) – Array of individual IDs to set prognoses for

  • sources (numpy.ndarray, optional) – Source of infection (not used in current implementation)

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
step()[source]

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.

start_treatment(uids)[source]

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:

uids (numpy.ndarray) – Array of individual IDs to start treatment for

Returns:

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

Return type:

int

Example

>>> # Start treatment for detected active TB cases
>>> n_treated = tb.start_treatment(detected_uids)
>>> print(f"Started treatment for {n_treated} individuals")
step_die(uids)[source]

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:

uids (numpy.ndarray) – Array of individual IDs who have died

Example

>>> # Called automatically by Starsim when deaths occur
>>> tb.step_die(deceased_uids)
>>> # Deceased individuals are now removed from TB transmission
init_results()[source]

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.

update_results()[source]

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.

finalize_results()[source]

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.

plot()[source]

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:

Figure containing the time series plot of all TB results

Return type:

matplotlib.figure.Figure

Example

>>> fig = tb.plot()
>>> fig.show()  # Display the plot
>>> fig.savefig('tb_results.png')  # Save to file
class tbsim.tb.TBS(value)[source]

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) |

all()[source]

Get all TB states including special states

all_active()[source]

Get all active TB states

all_latent()[source]

Get all latent TB states

all_infected()[source]

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

NONE = -1
LATENT_SLOW = 0
LATENT_FAST = 1
ACTIVE_PRESYMP = 2
ACTIVE_SMPOS = 3
ACTIVE_SMNEG = 4
ACTIVE_EXPTB = 5
DEAD = 8
PROTECTED = 100
static all()[source]

Get all TB states including special states.

Returns:

All TB states including NONE, LATENT_SLOW, LATENT_FAST,

ACTIVE_PRESYMP, ACTIVE_SMPOS, ACTIVE_SMNEG, ACTIVE_EXPTB, DEAD, and PROTECTED.

Return type:

numpy.ndarray

static all_active()[source]

Get all active TB states.

Returns:

Active TB states including ACTIVE_PRESYMP, ACTIVE_SMPOS,

ACTIVE_SMNEG, and ACTIVE_EXPTB.

Return type:

numpy.ndarray

static all_latent()[source]

Get all latent TB states.

Returns:

Latent TB states including LATENT_SLOW and LATENT_FAST.

Return type:

numpy.ndarray

static all_infected()[source]

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

Returns:

TB infection states including LATENT_SLOW, LATENT_FAST,

ACTIVE_PRESYMP, ACTIVE_SMPOS, ACTIVE_SMNEG, and ACTIVE_EXPTB.

Return type:

numpy.ndarray

TB State Enumeration

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) |

tbsim.tb.TBS.all()

Get all TB states including special states

tbsim.tb.TBS.all_active()

Get all active TB states

tbsim.tb.TBS.all_latent()

Get all latent TB states

tbsim.tb.TBS.all_infected()

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

TB Disease Class

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.

tbsim.tb.TB.state

Current TB state for each individual

tbsim.tb.TB.latent_tb_state

Specific latent state (slow/fast) for each individual

tbsim.tb.TB.active_tb_state

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

tbsim.tb.TB.on_treatment

Boolean indicating if individual is currently on treatment

tbsim.tb.TB.ever_infected

Boolean indicating if individual has ever been infected

tbsim.tb.TB.rr_activation

Relative risk multiplier for latent-to-active transition

tbsim.tb.TB.rr_clearance

Relative risk multiplier for active-to-clearance transition

tbsim.tb.TB.rr_death

Relative risk multiplier for active-to-death transition

tbsim.tb.TB.reltrans_het

Individual-level heterogeneity in infectiousness

tbsim.tb.TB.__delattr__(self, name, /)

Implement delattr(self, name).

tbsim.tb.TB.__dir__(self, /)

Default dir() implementation.

tbsim.tb.TB.__eq__(self, value, /)

Return self==value.

tbsim.tb.TB.__format__(self, format_spec, /)

Default object formatter.

tbsim.tb.TB.__ge__(self, value, /)

Return self>=value.

tbsim.tb.TB.__getattribute__(self, name, /)

Return getattr(self, name).

tbsim.tb.TB.__gt__(self, value, /)

Return self>value.

tbsim.tb.TB.__hash__(self, /)

Return hash(self).

tbsim.tb.TB.__init_subclass__()

This method is called when a class is subclassed.

The default implementation does nothing. It may be overridden to extend subclasses.

tbsim.tb.TB.__le__(self, value, /)

Return self<=value.

tbsim.tb.TB.__lt__(self, value, /)

Return self<value.

tbsim.tb.TB.__ne__(self, value, /)

Return self!=value.

tbsim.tb.TB.__reduce__(self, /)

Helper for pickle.

tbsim.tb.TB.__reduce_ex__(self, protocol, /)

Helper for pickle.

tbsim.tb.TB.__setattr__(self, name, value, /)

Implement setattr(self, name, value).

tbsim.tb.TB.__sizeof__(self, /)

Size of object in memory, in bytes.

tbsim.tb.TB.__str__(self, /)

Return str(self).

tbsim.tb.TB.__subclasshook__()

Abstract classes can override this to customize issubclass().

This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).

Model Overview

The TB disease model implements a comprehensive tuberculosis simulation with the following key features:

State Structure
  • Susceptible States: NONE (-1) - No TB infection

  • Latent States: LATENT_SLOW (0), LATENT_FAST (1) - TB infection without symptoms

  • Active States: ACTIVE_PRESYMP (2), ACTIVE_SMPOS (3), ACTIVE_SMNEG (4), ACTIVE_EXPTB (5)

  • Outcome States: DEAD (8) - TB-related death, PROTECTED (100) - BCG protection

Disease Progression
  • Stochastic state transitions with time-dependent probabilities

  • Latent to active progression with different rates for slow/fast progressors

  • Active disease progression through pre-symptomatic, symptomatic, and treatment phases

  • Natural clearance and recovery mechanisms

Transmission Dynamics
  • Person-to-person transmission based on infectious states

  • Network-based transmission through social contacts

  • Age and risk factor dependent transmission rates

Treatment Integration
  • Treatment initiation and management

  • Treatment effectiveness and adherence modeling

  • Treatment outcome tracking

Key Methods

State Transitions
  • p_latent_to_presym(): Latent to pre-symptomatic progression

  • p_presym_to_clear(): Natural clearance from pre-symptomatic state

  • p_presym_to_active(): Progression to active disease

  • p_active_to_clear(): Recovery from active disease

  • p_active_to_death(): TB-related mortality

Treatment Management
  • start_treatment(): Initiate treatment for eligible individuals

  • step_die(): Handle TB-related deaths

Results Tracking
  • Prevalence and incidence monitoring

  • State-specific population counts

  • Treatment coverage and outcomes

  • Mortality and recovery rates

Usage Examples

Basic TB simulation:

from tbsim import TB
import starsim as ss

sim = ss.Sim(diseases=TB())
sim.run()

With custom parameters:

from tbsim import TB

# Customize TB parameters
tb = TB(pars={
    'beta': ss.peryear(0.5),           # Transmission rate
    'init_prev': ss.bernoulli(0.01),   # Initial prevalence
})

sim = ss.Sim(diseases=tb)
sim.run()

Accessing results:

# Get current state counts
current_states = tb.state
infected_count = len(tb.infected)
active_count = len(tb.active)

# Access results
results = tb.results
prevalence = results.prevalence
incidence = results.incidence
mortality = results.mortality

State Management

State Transitions

The model implements a comprehensive state transition system where agents move between different TB states based on:

  • Natural Progression: Time-dependent transition probabilities

  • Treatment Effects: Modified progression rates under treatment

  • Network Effects: Transmission through social contacts

  • Risk Factors: Age, comorbidities, and other individual characteristics

Infection Dynamics
  • New infections occur through contact with infectious individuals

  • Latent infections can progress to active disease or clear naturally

  • Active disease can lead to treatment, recovery, or death

  • Treatment modifies progression rates and transmission potential

Population Dynamics
  • Birth and death processes affect TB dynamics

  • Age-specific risk factors influence disease progression

  • Network structure determines transmission patterns

  • Intervention effects modify disease parameters

For detailed information about specific methods and parameters, see the individual class documentation above. All methods include comprehensive mathematical models and implementation details in their docstrings.