TB Interventions

This module provides various intervention strategies for tuberculosis control and prevention.

Main Interventions Module

TBsim Interventions Module

This module contains all intervention classes for the TB simulation.

class tbsim.interventions.TPTInitiation(pars=None, **kwargs)[source]

Bases: Intervention

Tuberculosis Preventive Therapy (TPT) intervention for household contacts of care-seeking individuals.

This intervention identifies households where at least one member sought care, and offers TPT to all other members of those households who meet the following eligibility criteria:

Requirements:
  • Must have been in a previous intervention which updates sought_care, non_symptomatic, and symptomatic attributes

Eligibility criteria:
  • Must reside in a household where at least one member sought care

  • Must not have symptoms (non_symptomatic = True and symptomatic = False)

  • Must not have active TB (not in ACTIVE_PRESYMP, ACTIVE_SMPOS, ACTIVE_SMNEG, or ACTIVE_EXPTB states)

  • Must not already be on TB treatment themselves

  • Must be within the specified age_range (list: [min_age, max_age], default: [0, 100])

  • Must meet HIV status threshold (if set and hiv_positive attribute present)

Treatment logic:
  • A Bernoulli trial (p_tpt) is used to determine which eligible individuals initiate TPT

  • If initiated, individuals are flagged as on_tpt for the treatment duration (tpt_treatment_duration)

  • After completing treatment, individuals become protected (tb.state = TBS.PROTECTED) for a fixed duration (tpt_protection_duration)

  • Protection is tracked using tpt_protection_until and is automatically removed when expired (tb.state set to TBS.NONE)

Parameters:
  • p_tpt (float or ss.Bernoulli) – Probability of initiating TPT for an eligible individual

  • age_range (list) – [min_age, max_age] for eligibility (default: [0, 100])

  • hiv_status_threshold (bool) – If True, only HIV-positive individuals are eligible (requires ‘hiv_positive’ attribute)

  • tpt_treatment_duration (float) – Duration of TPT administration (e.g., 3 months)

  • tpt_protection_duration (float) – Duration of post-treatment protection (e.g., 2 years)

  • start (ss.date) – Start date for offering TPT

  • stop (ss.date) – Stop date for offering TPT

Results tracked:

n_eligible (int): Number of individuals meeting criteria n_tpt_initiated (int): Number of individuals who started TPT

Notes

  • Requires ‘hhid’, ‘on_tpt’, ‘received_tpt’, ‘sought_care’, ‘non_symptomatic’, ‘symptomatic’ attributes on people

  • Assumes household structure is available (e.g., via HouseHoldNet)

  • TB disease model must support ‘protected_from_tb’, ‘tpt_treatment_until’, and ‘tpt_protection_until’ states

  • Protection logic mirrors BCG: tb.state is set to TBS.PROTECTED for the immunity period, then reset to TBS.NONE

  • Uses care-seeking individuals as the index population for household contact tracing

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

Initialize the TPTInitiation intervention.

Parameters:
  • pars (dict, optional) – Dictionary containing intervention parameters.

  • 'p_tpt' (-) – Probability of initiating TPT

  • 'age_range' (-) – [min_age, max_age] for eligibility (default: [0, 100])

  • 'hiv_status_threshold' (-) – If True, only HIV-positive individuals are eligible

  • 'tpt_treatment_duration' (-) – Duration of TPT administration

  • 'tpt_protection_duration' (-) – Duration of post-treatment protection

  • 'start' (-) – Start date for offering TPT

  • 'stop' (-) – Stop date for offering TPT

  • **kwargs – Additional keyword arguments passed to parent class

step()[source]

Execute the TPT intervention step, applying TPT and protection logic at each timestep.

  • Removes protection for individuals whose TPT protection has expired (tb.state set to TBS.NONE)

  • Identifies agents who sought care (INDEX list)

  • For all INDEX UIDs, identifies household members

  • Filters household members for eligibility: no symptoms, no active TB, not on_treatment

  • Uses a Bernoulli trial to select candidates for TPT

  • Sets on_tpt and received_tpt flags for those who start TPT

  • Sets tpt_treatment_until and tpt_protection_until for those who start TPT

  • Sets tb.state to TBS.PROTECTED for the protection period after treatment

  • Tracks results for eligibility and initiation

init_results()[source]

Initialize results output; called during init_pre()

By default, modules all report on counts for any explicitly defined “States”, e.g. if a disease contains an ss.BoolState called ‘susceptible’ it will automatically contain a Result for ‘n_susceptible’. For identical behavior that does not automatically generate results, use ss.BoolArr instead of ss.BoolState.

update_results()[source]

Update results; by default, compute counts of each state at each point in time

This function is executed after transmission in all modules has been resolved. This allows result updates at this point to capture outcomes dependent on multiple modules, where relevant.

class tbsim.interventions.BCGProtection(pars={}, **kwargs)[source]

Bases: Intervention

Simulates BCG-like vaccination for tuberculosis prevention in individuals within a specified age range.

This intervention identifies individuals within a configurable age range who have not yet been vaccinated. At each timestep, a proportion of these eligible individuals is selected based on the coverage parameter to receive simulated BCG protection. Once vaccinated, individuals are considered protected for a fixed number of years (immunity_period). While protected, their TB-related risk modifiers — activation, clearance, and death — are adjusted using scaled and sampled values from BCG-specific probability distributions.

Use Cases

  1. Pediatric BCG Vaccination Programs
    • Newborn vaccination: Target infants 0-1 years with high coverage (80-95%)

    • Childhood vaccination: Target children 1-5 years with moderate coverage (60-80%)

    • School-age vaccination: Target children 5-15 years with lower coverage (40-60%)

  2. Adult BCG Vaccination Strategies
    • Healthcare worker vaccination: Target adults 18-65 years with moderate coverage (40-70%)

    • High-risk population vaccination: Target specific age groups with elevated TB risk

    • Mass vaccination campaigns: Target broad age ranges during outbreak responses

  3. Research and Policy Analysis
    • Vaccine effectiveness studies: Compare different efficacy levels and protection durations

    • Coverage optimization: Evaluate optimal vaccination coverage for population-level impact

    • Age-stratified analysis: Assess vaccination strategies across different age groups

    • Economic evaluation: Model cost-effectiveness of different vaccination scenarios

  4. Scenario Modeling
    • Baseline vs intervention: Compare TB outcomes with and without BCG vaccination

    • Combined interventions: Model BCG alongside other TB interventions (TPT, treatment, diagnostics)

    • Sensitivity analysis: Test robustness across different parameter ranges

    • Policy planning: Evaluate vaccination strategies for different populations and settings

Inputs and Requirements

Required Dependencies
  • TB Disease Model: The simulation must include a TB disease model with the following attributes: - rr_activation: Risk ratio for TB activation (modified by BCG) - rr_clearance: Risk ratio for bacterial clearance (modified by BCG) - rr_death: Risk ratio for TB mortality (modified by BCG) - state: TB disease states (set to TBS.PROTECTED for vaccinated individuals)

  • Population: Must have age information accessible via sim.people.age

  • Starsim Framework: Requires starsim probability distributions and date handling

Required TB States (TBS enum)
  • TBS.PROTECTED (100): Special state for BCG-protected individuals

  • TBS.NONE (-1): Default state for unprotected individuals

  • Standard TB states: LATENT_SLOW, LATENT_FAST, ACTIVE_PRESYMP, ACTIVE_SMPOS, ACTIVE_SMNEG, ACTIVE_EXPTB, DEAD

Simulation Requirements
  • Timestep compatibility: Works with any timestep duration (automatically converts immunity_period from years to timesteps)

  • Date handling: Requires proper date objects for start/stop parameters

  • Population size: Compatible with any population size (tested with 500+ individuals)

Outputs and Reports

Real-time Metrics (Updated Each Timestep)
Vaccination Metrics:
  • n_vaccinated: Total number of vaccinated individuals

  • n_eligible: Number of eligible individuals in current timestep

  • n_newly_vaccinated: Number of newly vaccinated individuals

  • n_vaccine_responders: Number of individuals who responded to vaccine

Protection Status:
  • n_protected: Currently protected individuals

  • n_protection_expired: Individuals whose protection has expired

Coverage and Effectiveness:
  • vaccination_coverage: Coverage rate (vaccinated/eligible)

  • protection_coverage: Protection rate (protected/total_population)

  • vaccine_effectiveness: Response rate (responders/vaccinated)

Cumulative Metrics
Cumulative Totals:
  • cumulative_vaccinated: Total ever vaccinated

  • cumulative_responders: Total ever responded to vaccine

  • cumulative_expired: Total ever expired protection

Intervention Timing:
  • avg_age_at_vaccination: Average age when vaccinated

  • avg_protection_duration: Average protection period

TB Impact Assessment
Disease Outcomes (via calculate_tb_impact()):
  • vaccinated_tb_deaths: TB deaths among vaccinated individuals

  • unvaccinated_tb_deaths: TB deaths among unvaccinated individuals

  • vaccinated_tb_cases: TB cases among vaccinated individuals

  • unvaccinated_tb_cases: TB cases among unvaccinated individuals

  • deaths_averted: Estimated deaths prevented by vaccination

  • cases_averted: Estimated cases prevented by vaccination

Risk Modifiers:
  • vaccinated_death_modifier: Average death risk modifier for vaccinated

  • unvaccinated_death_modifier: Average death risk modifier for unvaccinated

Summary Statistics (via get_summary_stats())
  • total_vaccinated: Final count of vaccinated individuals

  • total_responders: Final count of vaccine responders

  • final_coverage: Final population coverage

  • vaccine_effectiveness: Overall vaccine effectiveness

  • total_population: Total population size

Debug Information (via debug_population())
  • Population demographics by age group

  • Vaccination status by age range

  • Eligibility counts for targeted age groups

param Core Parameters:
  • coverage (float): Fraction of eligible individuals vaccinated per timestep (default: 0.5)

  • start (str/datetime.date): Start date for the intervention (default: ‘1900-01-01’)

  • stop (str/datetime.date): Stop date for the intervention (default: ‘2100-12-31’)

  • efficacy (float): Probability of effective vaccine response (default: 0.8)

  • immunity_period (int): Immunity period in years (default: 10)

  • age_range (tuple): Age range (min_age, max_age) for eligibility (default: (0, 5))

param Risk Modifier Distributions:
  • activation_modifier (ss.uniform): TB activation risk modifier (default: uniform(0.5, 0.65))

  • clearance_modifier (ss.uniform): Bacterial clearance modifier (default: uniform(1.3, 1.5))

  • death_modifier (ss.uniform): TB mortality modifier (default: uniform(0.05, 0.15))

param Usage Examples:

param ————–:

param Basic Pediatric Vaccination:::

# Standard newborn BCG vaccination bcg = BCGProtection(pars={

‘coverage’: 0.9, ‘age_range’: (0, 1), ‘efficacy’: 0.8, ‘immunity_period’: 10

})

param School-age Vaccination Campaign:::

# School-based vaccination program bcg = BCGProtection(pars={

‘coverage’: 0.7, ‘start’: ‘2020-01-01’, ‘stop’: ‘2025-12-31’, ‘age_range’: (5, 15), ‘efficacy’: 0.75, ‘immunity_period’: 8

})

param Adult Healthcare Worker Vaccination:::

# Healthcare worker vaccination bcg = BCGProtection(pars={

‘coverage’: 0.6, ‘age_range’: (18, 65), ‘efficacy’: 0.7, ‘immunity_period’: 5

})

param Research Scenario with Custom Distributions:::

# Research scenario with custom risk modifiers bcg = BCGProtection(pars={

‘activation_modifier’: ss.uniform(0.4, 0.6), ‘clearance_modifier’: ss.uniform(1.2, 1.6), ‘death_modifier’: ss.uniform(0.03, 0.12)

})

Core Attributes
  • coverage_dist (ss.bernoulli): Probability distribution for vaccination coverage

  • eligible (np.ndarray): Boolean mask of currently eligible individuals

  • n_eligible (int): Number of individuals eligible for vaccination in current step

  • p_vaccine_response (ss.bernoulli): Probability distribution for vaccine response

  • start (datetime.date): Start date for the intervention

  • stop (datetime.date): Stop date for the intervention

  • min_age (float): Minimum age for vaccination eligibility

  • max_age (float): Maximum age for vaccination eligibility

Individual States
  • is_bcg_vaccinated (bool): Whether individual has received BCG vaccine

  • ti_bcg_vaccinated (float): Timestep when individual was vaccinated

  • ti_bcg_protection_expires (float): Timestep when protection expires

  • age_at_vaccination (float): Age when individual was vaccinated

  • bcg_activation_modifier_applied (float): Activation risk modifier applied

  • bcg_clearance_modifier_applied (float): Clearance modifier applied

  • bcg_death_modifier_applied (float): Death risk modifier applied

Core Methods
  • check_eligibility(): Identify and randomly select eligible individuals for vaccination

  • is_protected(uids, current_time): Return boolean mask indicating protected individuals

  • step(): Apply BCG protection and adjust TB risk modifiers accordingly

Protection Management
  • _apply_protection_effects(protected_uids): Apply BCG protection effects to TB risk modifiers

  • _remove_protection(expired_uids): Remove BCG protection effects when protection expires

  • _maintain_ongoing_protection(current_time): Maintain protection effects for all currently protected individuals

Results and Analysis
  • init_results(): Define simulation result metrics

  • update_results(): Record vaccination and eligibility metrics each timestep

  • get_summary_stats(): Get summary statistics for the intervention

  • debug_population(): Debug method to check population demographics and vaccination status

  • calculate_tb_impact(tb_model): Calculate the impact of BCG vaccination on TB outcomes

Notes

This intervention assumes the presence of a TB disease model attached to the simulation and modifies its rr_activation, rr_clearance, and rr_death arrays. The intervention uses starsim probability distributions for stochastic modeling and proper date handling for temporal eligibility checks. The age_range parameter allows targeting of any age group, making this intervention suitable for both pediatric and adult vaccination strategies.

The intervention automatically handles protection expiration and re-application of effects each timestep, ensuring that BCG protection persists throughout the immunity period. Risk modifiers are applied individually to each vaccinated person, allowing for heterogeneity in vaccine response.

__init__(pars={}, **kwargs)[source]

Initialize a BCGProtection intervention instance.

This constructor sets up the BCG vaccination intervention with user-specified or default parameters. It defines the probability distributions for coverage, efficacy, and risk modifiers, as well as the age range and timing for eligibility. It also initializes the state arrays that track vaccination and protection status for each individual in the simulation.

Parameters:
  • pars (dict, optional) – Dictionary of intervention parameters. See class docstring for details.

  • **kwargs – Additional keyword arguments passed to the parent Intervention class.

init_pre(sim)[source]

Initialize the intervention before the simulation starts.

init_post()[source]

Initialize the intervention after the simulation starts.

check_eligibility()[source]

Identify and randomly select eligible individuals for BCG vaccination in the current timestep.

This method uses starsim’s efficient indexing to find individuals who are within the configured age range and have not yet been vaccinated. It then applies the coverage probability to randomly select a subset of these eligible individuals for vaccination.

Returns:

Array of UIDs selected for vaccination in this timestep.

Return type:

ss.uids

is_protected(uids, current_time)[source]

Return boolean array indicating protection status.

Parameters:
  • uids (array-like) – Array of UIDs to check for protection status

  • current_time (float) – Current simulation timestep

Returns:

True if still protected (within immunity_period), else False

Return type:

bool array

step()[source]

Executes BCG vaccination during the current simulation timestep.

This method implements a targeted Bacille Calmette-Guérin (BCG) immunization strategy for individuals within a specified age range. It models age-filtered eligibility, stochastic coverage, and vaccine-induced protection with time-limited efficacy.

Notes

This intervention performs the following operations:

  1. Temporal eligibility check: Verifies the current simulation time falls within the intervention window (start/stop dates).

  2. Protection expiration management: Checks for previously vaccinated individuals whose protection has expired and removes their protection effects from TB risk modifiers.

  3. Eligibility determination: Identifies individuals meeting age criteria (within age_range) who have not been vaccinated.

  4. Vaccination assignment: Randomly selects eligible individuals based on coverage probability and marks them as vaccinated, recording the vaccination timestep and age at vaccination.

  5. Vaccine response modeling: Simulates individual vaccine response using efficacy probability. Only responders receive protection benefits.

  6. Protection immunity_period assignment: Sets expiration timestep for vaccine responders based on protection immunity_period.

  7. TB risk modification: Applies BCG-specific modifiers to TB activation, clearance, and death rates using starsim probability distributions for individual heterogeneity.

  8. Ongoing protection maintenance: Ensures protection effects persist for all currently protected individuals.

The method uses starsim indexing and probability distributions for efficient population-level operations and stochastic modeling.

begin_step()[source]

Called at the very start of each simulation timestep, before any disease model steps.

Ensures that BCG protection effects are applied to all currently protected individuals before the TB model uses the risk modifiers.

init_results()[source]

Define simulation result metrics for the BCG intervention.

This method sets up all the result tracking arrays including:

  • Basic vaccination metrics (total, eligible, newly vaccinated, responders)

  • Protection status metrics (protected, expired)

  • Coverage and effectiveness metrics

  • Age-specific metrics for 1-5, 5-15, and 15+ years

  • Cumulative metrics

  • Intervention timing metrics (average age at vaccination, protection immunity_period)

  • TB impact metrics (cases and deaths averted)

update_results()[source]

Update all result metrics for the current timestep.

This method calculates and stores all the intervention metrics including:

  • Basic vaccination counts and rates

  • Protection status for vaccinated individuals

  • Age-specific coverage metrics for 1-5, 5-15, and 15+ years

  • Cumulative totals

  • Average age at vaccination and protection immunity_period

  • TB impact estimates (now calculated, not placeholder)

get_summary_stats()[source]

Get summary statistics for the intervention.

Returns:

Dictionary containing summary statistics

Return type:

dict

debug_population()[source]

Debug method to check population demographics and vaccination status.

This method provides detailed information about the population age distribution, vaccination status by age group, and eligibility counts for debugging purposes.

Returns:

Dictionary containing debug information about population demographics

Return type:

dict

calculate_tb_impact(tb_model)[source]

Calculate the impact of BCG vaccination on TB outcomes.

Parameters:

tb_model (object) – The TB disease model

Returns:

Dictionary containing TB impact metrics

Return type:

dict

class tbsim.interventions.TBTreatment(pars=None, **kwargs)[source]

Bases: Intervention

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

Parameters:
  • treatment_success_rate (float or Dist) – Probability of cure if treated.

  • reseek_multiplier (float) – Care-seeking multiplier applied after failure.

  • reset_flags (bool) – Whether to reset tested/diagnosed flags after failure.

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

Define how the module updates over time – the key part of Starsim!!

init_results()[source]

Initialize results output; called during init_pre()

By default, modules all report on counts for any explicitly defined “States”, e.g. if a disease contains an ss.BoolState called ‘susceptible’ it will automatically contain a Result for ‘n_susceptible’. For identical behavior that does not automatically generate results, use ss.BoolArr instead of ss.BoolState.

update_results()[source]

Update results; by default, compute counts of each state at each point in time

This function is executed after transmission in all modules has been resolved. This allows result updates at this point to capture outcomes dependent on multiple modules, where relevant.

class tbsim.interventions.EnhancedTBTreatment(pars=None, **kwargs)[source]

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:
  • 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

  • treatment_success_rate (float, default 0.85) – Base treatment success rate (can be overridden by drug-specific parameters)

  • reseek_multiplier (float, default 2.0) – Multiplier applied to care-seeking probability after treatment failure

  • reset_flags (bool, default True) – Whether to reset diagnosis and testing flags after treatment failure

drug_parameters

Drug-specific parameters including cure rates and side effects

Type:

TBDrugTypeParameters

new_treated

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

Type:

list

successes

List of UIDs of individuals who successfully completed treatment

Type:

list

failures

List of UIDs of individuals who failed treatment

Type:

list

drug_type_assignments

Mapping of individual UIDs to assigned drug types

Type:

dict

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']
__init__(pars=None, **kwargs)[source]

Initialize the enhanced TB treatment intervention.

Parameters:
  • pars (dict, optional) – Dictionary of parameters to override defaults

  • **kwargs – Additional keyword arguments passed to parent class

step()[source]

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

init_results()[source]

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.

update_results()[source]

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.

class tbsim.interventions.TBDrugType(value)[source]

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.

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
DOTS = 1
DOTS_IMPROVED = 2
EMPIRIC_TREATMENT = 3
FIRST_LINE_COMBO = 4
SECOND_LINE_COMBO = 5
THIRD_LINE_COMBO = 6
LATENT_TREATMENT = 7
classmethod get_name(value: int) str[source]

Get the string name for a drug type value.

Parameters:

value – Integer value of the drug type

Returns:

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

Example

>>> TBDrugType.get_name(1)
'DOTS'
>>> TBDrugType.get_name(999)
'UNKNOWN_999'
classmethod get_all_types() list[source]

Get all drug types as a list.

Returns:

List of all TBDrugType enum values

Example

>>> types = TBDrugType.get_all_types()
>>> len(types)
7
>>> TBDrugType.DOTS in types
True
class tbsim.interventions.TBDrugParameters(drug_name: str, drug_type: TBDrugType)[source]

Bases: object

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.

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_rate

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_rate': 0.85, 'duration': 180})
>>> print(f"Cure rate: {params.cure_rate}")
__init__(drug_name: str, drug_type: TBDrugType)[source]

Initialize drug parameters.

Parameters:
  • drug_name – Name of the drug regimen (e.g., “DOTS”, “First Line Combo”)

  • drug_type – Type of drug from TBDrugType enum

Example

>>> params = TBDrugParameters("DOTS", TBDrugType.DOTS)
>>> params.drug_name
'DOTS'
>>> params.drug_type
<TBDrugType.DOTS: 1>
configure(parameters: Dict[str, Any]) None[source]

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:

parameters – Dictionary containing parameter values to set

Example

>>> params = TBDrugParameters("Test", TBDrugType.DOTS)
>>> params.configure({
...     'cure_rate': 0.85,
...     'duration': 180,
...     'cost_per_course': 100
... })
>>> params.cure_rate
0.85
get_effectiveness(time_on_treatment: float) float[source]

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:

time_on_treatment – Time in days since treatment started

Returns:

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

String representation of the drug parameters.

Returns:

String showing drug name and type

Example

>>> params = TBDrugParameters("DOTS", TBDrugType.DOTS)
>>> repr(params)
'TBDrugParameters(DOTS, type=DOTS)'
class tbsim.interventions.TBDrugTypeParameters[source]

Bases: object

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_rate}")
>>> all_params = TBDrugTypeParameters.get_all_parameter_sets()
>>> len(all_params)
7
static create_dots_parameters() TBDrugParameters[source]

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:

TBDrugParameters object configured for DOTS treatment

Example

>>> params = TBDrugTypeParameters.create_dots_parameters()
>>> params.cure_rate
0.85
>>> params.duration
180.0
static create_dots_improved_parameters() TBDrugParameters[source]

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:

TBDrugParameters object configured for improved DOTS treatment

Example

>>> params = TBDrugTypeParameters.create_dots_improved_parameters()
>>> params.cure_rate
0.9
>>> params.adherence_rate
0.9
static create_empiric_treatment_parameters() TBDrugParameters[source]

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:

TBDrugParameters object configured for empiric treatment

Example

>>> params = TBDrugTypeParameters.create_empiric_treatment_parameters()
>>> params.cure_rate
0.7
>>> params.resistance_rate
0.05
static create_first_line_combo_parameters() TBDrugParameters[source]

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:

TBDrugParameters object configured for first-line combination therapy

Example

>>> params = TBDrugTypeParameters.create_first_line_combo_parameters()
>>> params.cure_rate
0.95
>>> params.resistance_rate
0.01
static create_second_line_combo_parameters() TBDrugParameters[source]

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:

TBDrugParameters object configured for second-line combination therapy

Example

>>> params = TBDrugTypeParameters.create_second_line_combo_parameters()
>>> params.cure_rate
0.75
>>> params.duration
240.0
static create_third_line_combo_parameters() TBDrugParameters[source]

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:

TBDrugParameters object configured for third-line combination therapy

Example

>>> params = TBDrugTypeParameters.create_third_line_combo_parameters()
>>> params.cure_rate
0.6
>>> params.cost_per_course
1000.0
static create_latent_treatment_parameters() TBDrugParameters[source]

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:

TBDrugParameters object configured for latent TB treatment

Example

>>> params = TBDrugTypeParameters.create_latent_treatment_parameters()
>>> params.cure_rate
0.9
>>> params.duration
90.0
static create_parameters_for_type(drug_type: TBDrugType) TBDrugParameters[source]

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:

drug_type – The drug type to create parameters for

Returns:

TBDrugParameters object with appropriate values

Raises:

ValueError – If the drug type is not recognized

Example

>>> params = TBDrugTypeParameters.create_parameters_for_type(TBDrugType.DOTS)
>>> params.drug_type
<TBDrugType.DOTS: 1>
>>> params.cure_rate
0.85
static get_all_parameter_sets() Dict[TBDrugType, TBDrugParameters][source]

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:

Dictionary mapping drug types to their parameters

Example

>>> all_params = TBDrugTypeParameters.get_all_parameter_sets()
>>> len(all_params)
7
>>> all_params[TBDrugType.DOTS].cure_rate
0.85
>>> all_params[TBDrugType.FIRST_LINE_COMBO].cure_rate
0.95
tbsim.interventions.create_dots_treatment(pars=None, **kwargs) EnhancedTBTreatment[source]

Create a standard DOTS treatment intervention.

This function provides a convenient way to create a DOTS treatment intervention with standard parameters. DOTS (Directly Observed Treatment, Short-course) is the WHO-recommended strategy for TB control.

Parameters:
  • pars (dict, optional) – Additional parameters to override defaults

  • **kwargs – Additional keyword arguments passed to EnhancedTBTreatment

Returns:

Configured DOTS treatment intervention

Return type:

EnhancedTBTreatment

Examples

>>> dots_treatment = create_dots_treatment()
>>> dots_treatment.pars.drug_type
TBDrugType.DOTS
tbsim.interventions.create_dots_improved_treatment(pars=None, **kwargs) EnhancedTBTreatment[source]

Create an improved DOTS treatment intervention.

This function creates a DOTS treatment intervention with enhanced parameters that may include better adherence monitoring, improved drug formulations, or enhanced patient support systems.

Parameters:
  • pars (dict, optional) – Additional parameters to override defaults

  • **kwargs – Additional keyword arguments passed to EnhancedTBTreatment

Returns:

Configured improved DOTS treatment intervention

Return type:

EnhancedTBTreatment

Examples

>>> improved_dots = create_dots_improved_treatment(
...     reseek_multiplier=2.5,
...     reset_flags=False
... )
tbsim.interventions.create_first_line_treatment(pars=None, **kwargs) EnhancedTBTreatment[source]

Create a first-line combination treatment intervention.

This function creates a treatment intervention using first-line combination therapy, which typically includes multiple drugs to prevent resistance development and improve treatment outcomes.

Parameters:
  • pars (dict, optional) – Additional parameters to override defaults

  • **kwargs – Additional keyword arguments passed to EnhancedTBTreatment

Returns:

Configured first-line combination treatment intervention

Return type:

EnhancedTBTreatment

Examples

>>> first_line = create_first_line_treatment(
...     treatment_success_rate=0.90,
...     reseek_multiplier=1.5
... )
tbsim.interventions.get_dots_parameters() TBDrugParameters[source]

Get DOTS parameters.

Convenience function to quickly access DOTS treatment parameters.

Returns:

TBDrugParameters object configured for DOTS treatment

Example

>>> dots_params = get_dots_parameters()
>>> print(f"DOTS cure rate: {dots_params.cure_rate}")
>>> print(f"DOTS duration: {dots_params.duration} days")
tbsim.interventions.get_drug_parameters(drug_type: TBDrugType) TBDrugParameters[source]

Get parameters for a specific drug type.

Convenience function to quickly access parameters for any drug type.

Parameters:

drug_type – The drug type to get parameters for

Returns:

TBDrugParameters object configured for the specified drug type

Example

>>> first_line_params = get_drug_parameters(TBDrugType.FIRST_LINE_COMBO)
>>> print(f"First line cure rate: {first_line_params.cure_rate}")
>>> print(f"First line cost: ${first_line_params.cost_per_course}")
tbsim.interventions.get_all_drug_parameters() Dict[TBDrugType, TBDrugParameters][source]

Get all drug parameter sets.

Convenience function to get parameters for all drug types at once. Useful for comparing different treatment options or creating comprehensive treatment analysis.

Returns:

Dictionary mapping all drug types to their parameters

Example

>>> all_params = get_all_drug_parameters()
>>> for drug_type, params in all_params.items():
...     print(f"{drug_type.name}: {params.cure_rate:.3f} cure rate, ${params.cost_per_course:.0f} cost")
class tbsim.interventions.HealthSeekingBehavior(pars=None, **kwargs)[source]

Bases: Intervention

Trigger care-seeking behavior for individuals with active TB.

Parameters:
  • prob (float) – Probability of seeking care per unit time.

  • single_use (bool) – Whether to expire the intervention after success.

  • actual (Intervention) – Optional downstream intervention (e.g. testing or treatment).

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

Calculate the probability of care-seeking for individuals.

step()[source]

Define how the module updates over time – the key part of Starsim!!

init_results()[source]

Define metrics to track over time.

update_results()[source]

Record who was eligible and who sought care at this timestep.

class tbsim.interventions.TBDiagnostic(pars=None, **kwargs)[source]

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 (sim.diseases.tb) 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: - True TB cases: test positive with probability = sensitivity - Non-TB cases: test positive with probability = (1 - specificity)

  5. Update person states based on test results

  6. Handle false negatives by: - Increasing care-seeking probability for future attempts - Resetting care-seeking and testing flags to allow retesting

Example:

>>> sim = ss.Sim(
...     interventions=[
...         mtb.HealthSeekingBehavior(pars={'initial_care_seeking_rate': ss.perday(0.1)}),
...         mtb.TBDiagnostic(pars={
...             'coverage': 0.8,
...             'sensitivity': 0.85,
...             'specificity': 0.95,
...             'care_seeking_multiplier': 2.0
...         })
...     ]
... )
__init__(pars=None, **kwargs)[source]

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:
  • pars (dict, optional) – Dictionary of parameters to override defaults. Valid keys: ‘coverage’, ‘sensitivity’, ‘specificity’, ‘reset_flag’, ‘care_seeking_multiplier’.

  • **kwargs – Additional keyword arguments passed to parent class.

  • Parameters (Default)

  • -------------------

  • coverage (-)

  • sensitivity (-)

  • specificity (-)

  • reset_flag (-)

  • care_seeking_multiplier (-)

  • Raises

  • -------

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

  • Note

  • -----

  • simulation. (The intervention requires specific person states to be present in the)

  • seeking (These are typically initialized by the TB disease module and health)

  • intervention. (behavior)

step()[source]

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.

init_results()[source]

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

update_results()[source]

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.

class tbsim.interventions.EnhancedTBDiagnostic(pars=None, **kwargs)[source]

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

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

Define how the module updates over time – the key part of Starsim!!

init_results()[source]

Initialize results output; called during init_pre()

By default, modules all report on counts for any explicitly defined “States”, e.g. if a disease contains an ss.BoolState called ‘susceptible’ it will automatically contain a Result for ‘n_susceptible’. For identical behavior that does not automatically generate results, use ss.BoolArr instead of ss.BoolState.

update_results()[source]

Update results; by default, compute counts of each state at each point in time

This function is executed after transmission in all modules has been resolved. This allows result updates at this point to capture outcomes dependent on multiple modules, where relevant.

class tbsim.interventions.TBDiagnosticErrors[source]

Bases: object

Error messages and validation for TBDiagnostic intervention

SOUGHT_CARE_MISSING = "TBDiagnostic requires 'sought_care' attribute on people object. This is typically provided by a HealthSeekingBehavior intervention. Please add a health seeking behavior intervention to your simulation."
DIAGNOSED_MISSING = "TBDiagnostic requires 'diagnosed' attribute on people object. This should be automatically created by the TB disease module. Please ensure TB disease is properly configured in your simulation."
ALIVE_MISSING = "TBDiagnostic requires 'alive' attribute on people object. This should be automatically created by the simulation framework. Please check your simulation setup."
TESTED_MISSING = "TBDiagnostic requires 'tested' attribute on people object. This should be automatically created by the TB disease module. Please ensure TB disease is properly configured in your simulation."
N_TIMES_TESTED_MISSING = "TBDiagnostic requires 'n_times_tested' attribute on people object. This should be automatically created by the TB disease module. Please ensure TB disease is properly configured in your simulation."
TEST_RESULT_MISSING = "TBDiagnostic requires 'test_result' attribute on people object. This should be automatically created by the TB disease module. Please ensure TB disease is properly configured in your simulation."
CARE_SEEKING_MULTIPLIER_MISSING = "TBDiagnostic requires 'care_seeking_multiplier' attribute on people object. This should be automatically created by the TB disease module. Please ensure TB disease is properly configured in your simulation."
MULTIPLIER_APPLIED_MISSING = "TBDiagnostic requires 'multiplier_applied' attribute on people object. This should be automatically created by the TB disease module. Please ensure TB disease is properly configured in your simulation."
DISEASES_MISSING = 'TBDiagnostic requires diseases to be present in simulation. Please add TB disease to your simulation: sim = ss.Sim(diseases=[tb], ...)'
TB_DISEASE_MISSING = 'TBDiagnostic requires TB disease module. Please add TB disease to your simulation: sim = ss.Sim(diseases=[tb], ...)'
TB_STATE_MISSING = "TBDiagnostic requires TB disease to have 'state' attribute. Please ensure TB disease is properly initialized in your simulation."
static coverage_invalid(value)[source]
static sensitivity_invalid(value)[source]
static specificity_invalid(value)[source]
static care_seeking_multiplier_invalid(value)[source]
static coverage_filter_failed(error, coverage_value)[source]
static coverage_filter_invalid_selection(eligible_count, selected_count)[source]
static coverage_filter_wrong_selection()[source]
static tb_status_failed(error)[source]
static tb_state_length_mismatch(selected_count, tb_states_count)[source]
static sensitivity_test_failed(error, sensitivity)[source]
static specificity_test_failed(error, specificity)[source]
static test_result_length_mismatch(selected_count, test_results_count)[source]
static test_result_wrong_type(dtype)[source]
static person_state_update_failed(error)[source]
static sought_care_reset_failed(error)[source]
static multiplier_filter_failed(error)[source]
static multiplier_application_failed(error)[source]
static false_negative_reset_failed(error)[source]
static false_negative_count_invalid(selected_count, false_negative_count)[source]
static unboosted_count_invalid(false_negative_count, unboosted_count)[source]
static results_init_failed(error)[source]
RESULTS_ATTR_MISSING = 'TBDiagnostic results attribute not created. This indicates a problem with result initialization in the simulation framework.'
static result_missing(result_name, available_results)[source]
RESULTS_NOT_INITIALIZED = 'TBDiagnostic results not initialized. Please ensure init_results() was called before update_results().'
TI_MISSING = 'TBDiagnostic timestep index (ti) not available. This indicates a problem with the simulation framework.'
TESTED_THIS_STEP_MISSING = 'TBDiagnostic tested_this_step not initialized. This indicates a problem with intervention initialization.'
TEST_RESULT_THIS_STEP_MISSING = 'TBDiagnostic test_result_this_step not initialized. This indicates a problem with intervention initialization.'
static data_inconsistency(tested_length, test_result_length)[source]
static result_calculation_failed(error)[source]
static negative_tested_count(count)[source]
static negative_positive_count(count)[source]
static negative_negative_count(count)[source]
static result_count_mismatch(positive_count, negative_count, tested_count)[source]
static current_timestep_record_failed(error)[source]
static cumulative_update_failed(error)[source]
static cumulative_positive_decreased(previous, current)[source]
static cumulative_negative_decreased(previous, current)[source]
tbsim.interventions.HealthSeeking

alias of HealthSeekingBehavior

class tbsim.interventions.TBVaccinationCampaign(year=1900, product=None, rate=.015, target_gender='All', target_age=10, target_state=None, new_value_fraction=1, prob=None, *args, **kwargs)[source]

Bases: Intervention

Base class for any intervention that uses campaign delivery; handles interpolation of input years.

__init__(year=1900, product=None, rate=.015, target_gender='All', target_age=10, target_state=None, new_value_fraction=1, prob=None, *args, **kwargs)[source]
init_pre(sim)[source]

Perform initialization steps

This method is called once, as part of initializing a Sim. Note: after initialization, initialized=False until init_vals() is called (which is after distributions are initialized).

update(sim)[source]

Available Intervention Types

BCG Vaccination (tbsim.interventions.bcg)

Bacillus Calmette-Guérin vaccination for TB prevention

Treatment Protocols (tbsim.interventions.interventions)

Various TB treatment regimens and protocols

Enhanced Treatment (tbsim.interventions.enhanced_tb_treatment)

Advanced treatment with configurable drug types and protocols

Basic Treatment (tbsim.interventions.tb_treatment)

Basic TB treatment with success/failure logic

Diagnostic Testing (tbsim.interventions.tb_diagnostic)

TB diagnostic testing with configurable accuracy

Enhanced Diagnostics (tbsim.interventions.enhanced_tb_diagnostic)

Advanced diagnostics with stratified parameters and multiple methods

Health-Seeking Behavior (tbsim.interventions.healthseeking)

Modeling of care-seeking behavior for TB cases

TB Health-Seeking (tbsim.interventions.tb_health_seeking)

TB-specific health-seeking with rate-based probabilities

Drug Types and Parameters (tbsim.interventions.tb_drug_types)

Comprehensive TB drug regimen definitions and parameters

Preventive Therapy (tbsim.interventions.tpt)

Isoniazid preventive therapy (IPT) implementation

Diagnostic Tools (tbsim.interventions.tb_diagnostic)

Enhanced case detection and diagnostic methods

Health Seeking (tbsim.interventions.tb_health_seeking)

Modeling of healthcare-seeking behavior

Treatment Management (tbsim.interventions.tb_treatment)

Treatment adherence and outcome modeling

Beta Interventions (tbsim.interventions.beta)

Time-varying intervention parameters

Subpackages

Usage Examples

Adding BCG vaccination:

from tbsim.interventions.bcg import BCG
from tbsim import TB

tb = TB()
bcg = BCG()

sim = ss.Sim(
    diseases=tb,
    interventions=bcg
)
sim.run()

Implementing preventive therapy:

from tbsim.interventions.tpt import TPT

tpt = TPT()
sim = ss.Sim(interventions=tpt)

Key Features

  • Modular Design: Mix and match different intervention types

  • Configurable Parameters: Adjust intervention effectiveness and coverage

  • Time-Varying Implementation: Model interventions that change over time

  • Integration: Seamlessly integrate with TB and comorbidity models

  • Evaluation: Built-in tools for assessing intervention impact

For detailed information about specific intervention types, see the individual subpackage documentation above.