methods

methods

Contraceptive methods

Idea

A method selector should be a generic class (an intervention?). We want the existing matrix-based method and the new duration-based method to both be instances of this.

Classes

Name Description
ContraceptiveChoice Base class for contraceptive choice modules.
Method A contraceptive method.
RandomChoice Choose a method uniformly at random.
SimpleChoice Choose a method based on age and previous method.
StandardChoice Choose a method based on age, education, wealth, parity and prior use.

ContraceptiveChoice

methods.ContraceptiveChoice(pars=None, **kwargs)

Base class for contraceptive choice modules.

A choice module owns the list of available methods and decides, for each woman at each decision point, whether she uses contraception and which method. Subclasses differ only in how that probability is computed; see RandomChoice, SimpleChoice and StandardChoice.

The module is reached at sim.connectors.contraception during and after a run. Note this is distinct from the FP module itself, which lives at sim.people.fp.

Parameters

Name Type Description Default
pars dict parameters for the choice module None
kwargs dict passed to ss.Connector {}

Attributes

Name Description
n_options Number of contraceptive methods defined

Methods

Name Description
add_method Add a new contraceptive method to the simulation.
copy_switching_from_method Copy all switching probabilities FROM a method (entire row block).
copy_switching_probs Copy switching probability from one method pair to another.
copy_switching_to_method Copy all switching probabilities TO a method (entire column).
extend_method_choice_pars Extend method_choice_pars to include a new method.
get_contra_users Select contraception users, return boolean array
get_method Get a method by name (first) or label (second).
get_method_by_label Extract method according to its label / long name
get_switching_matrix Get switching matrix for a particular postpartum status across all age groups.
get_switching_prob Get switching probability from one method to another.
init_contraception Used for all agents at the start of a sim and for newly active agents throughout
init_post Decide who will start using contraception, when, which contraception method and the
init_results Initialize results for this module
make_empty_method_choice_pars Create an empty method_choice_pars structure with zero entries.
renormalize_method_choice_pars Renormalize all probability arrays in method_choice_pars to sum to 1.
set_init_dist If no initial distribution has been provided, use the method_choice_pars to set one.
set_method Wrapper for choosing method and assigning duration of use
set_switching_prob Set switching probability from one method to another.
start_contra Wrapper method to start contraception for a set of users
update_contra Update contraceptive choices for a set of users.
update_intent_to_use Intent is optional, so pass if not implemented for a given ContraceptiveChoice
update_results Note that we are not including LAM users in mCPR as this model counts
add_method
methods.ContraceptiveChoice.add_method(method, copy_from=None)

Add a new contraceptive method to the simulation.

Parameters
Name Type Description Default
method Method object to add (must have name, label, csv_name, efficacy, modern, dur_use) required
copy_from Optional method name/label to copy switching probabilities from None
copy_switching_from_method
methods.ContraceptiveChoice.copy_switching_from_method(
    source_from_method,
    dest_from_method,
    postpartum=None,
    age_grp=None,
    renormalize=False,
)

Copy all switching probabilities FROM a method (entire row block). Example: Copy all probabilities of switching from pill to other methods to be the probabilities of switching from implant to other methods. This makes implant users switch like pill users.

copy_switching_probs
methods.ContraceptiveChoice.copy_switching_probs(
    from_method_source,
    to_method_source,
    from_method_dest,
    to_method_dest,
    postpartum=None,
    age_grp=None,
    renormalize=False,
)

Copy switching probability from one method pair to another. Example: Copy the probability of switching from pill->iud to the probability of switching from condom->implant

copy_switching_to_method
methods.ContraceptiveChoice.copy_switching_to_method(
    source_to_method,
    dest_to_method,
    split_shares=None,
    postpartum=None,
    age_grp=None,
    renormalize=False,
)

Copy all switching probabilities TO a method (entire column). Example: Copy all probabilities of switching to IUD to be the probabilities of switching to implant.

extend_method_choice_pars
methods.ContraceptiveChoice.extend_method_choice_pars(
    new_method_name,
    copy_from_method=None,
)

Extend method_choice_pars to include a new method.

Parameters
Name Type Description Default
new_method_name str Name of the new method being added required
copy_from_method str or None Name of existing method to copy probabilities from. If None, initialize with zeros. None
get_contra_users
methods.ContraceptiveChoice.get_contra_users(uids, event=None)

Select contraception users, return boolean array

get_method
methods.ContraceptiveChoice.get_method(identifier)

Get a method by name (first) or label (second). Args: identifier (str): Method name (e.g., ‘impl’) or label (e.g., ‘Implants’) Returns: Method: The matching method object

get_method_by_label
methods.ContraceptiveChoice.get_method_by_label(method_label)

Extract method according to its label / long name

get_switching_matrix
methods.ContraceptiveChoice.get_switching_matrix(postpartum, from_method=None)

Get switching matrix for a particular postpartum status across all age groups. Args: postpartum (int): Postpartum state (0, 1, or 6) from_method (str or None): Method name for pp=0 or 6

Returns
Name Type Description
dict Dictionary keyed by age group with probability arrays
get_switching_prob
methods.ContraceptiveChoice.get_switching_prob(
    from_method,
    to_method,
    postpartum,
    age_grp,
)

Get switching probability from one method to another. Args: from_method (str): Method name to switch from to_method (str): Method name to switch to postpartum (int): Postpartum state (0, 1, or 6) age_grp (str): Age group

Returns
Name Type Description
float Probability value
init_contraception
methods.ContraceptiveChoice.init_contraception(uids)

Used for all agents at the start of a sim and for newly active agents throughout

init_post
methods.ContraceptiveChoice.init_post()

Decide who will start using contraception, when, which contraception method and the duration on that method. This method is called by the simulation to initialize the people object at the beginning of the simulation and new people born during the simulation.

init_results
methods.ContraceptiveChoice.init_results()

Initialize results for this module

make_empty_method_choice_pars
methods.ContraceptiveChoice.make_empty_method_choice_pars()

Create an empty method_choice_pars structure with zero entries. Useful for creating new simulations without location data.

renormalize_method_choice_pars
methods.ContraceptiveChoice.renormalize_method_choice_pars()

Renormalize all probability arrays in method_choice_pars to sum to 1. Replaces Switching.renormalize_all()

set_init_dist
methods.ContraceptiveChoice.set_init_dist()

If no initial distribution has been provided, use the method_choice_pars to set one. The initial distribution will be the probabilities of switching from no method

set_method
methods.ContraceptiveChoice.set_method(uids)

Wrapper for choosing method and assigning duration of use

set_switching_prob
methods.ContraceptiveChoice.set_switching_prob(
    from_method,
    to_method,
    value,
    postpartum=None,
    age_grp=None,
    renormalize=False,
)

Set switching probability from one method to another. Args: from_method (str): Method name to switch from to_method (str): Method name to switch to value (float): Probability value postpartum (int or list or None): Postpartum state(s) (0, 1, or 6). None = all. age_grp (str or list or None): Age group(s). None = all. renormalize (bool): Whether to renormalize after setting

start_contra
methods.ContraceptiveChoice.start_contra(uids)

Wrapper method to start contraception for a set of users

update_contra
methods.ContraceptiveChoice.update_contra(uids)

Update contraceptive choices for a set of users.

update_intent_to_use
methods.ContraceptiveChoice.update_intent_to_use(uids)

Intent is optional, so pass if not implemented for a given ContraceptiveChoice

update_results
methods.ContraceptiveChoice.update_results()

Note that we are not including LAM users in mCPR as this model counts all women passively using LAM but DHS data records only women who self-report LAM which is much lower. Follows the DHS definition of mCPR.

Method

methods.Method(
    name=None,
    label=None,
    idx=None,
    efficacy=None,
    modern=None,
    dur_use=None,
    rel_dur_use=1,
    csv_name=None,
    _source_dur=None,
)

A contraceptive method.

Methods are held by a contraceptive choice module, which decides who uses which one. A woman re-chooses when her current method’s dur_use elapses, so dur_use shapes the long-run method mix as much as efficacy does.

Note that name and label are not interchangeable: code indexes the method dictionary by name (cm.methods['inj']), while interventions that take method identifiers look them up by label ('Injectables').

Parameters

Name Type Description Default
name str short identifier used in code, e.g. 'inj' None
label str display name used in plots and interventions, e.g. 'Injectables' None
idx int position in the method list; set automatically when added to a module None
efficacy float proportional reduction in conception probability while using None
modern bool whether this counts towards modern contraceptive prevalence (mCPR) None
dur_use Dist distribution of duration of use before re-choosing None
rel_dur_use float multiplier on dur_use, for scaling a copied method 1
csv_name str name used for this method in the input data files None

Example:

```python
import starsim as ss
import fpsim.methods as fpm

dmpasc = fpm.Method(name='dmpasc', label='DMPA-SC', efficacy=0.983, modern=True,
                    dur_use=ss.lognorm_ex(ss.years(2), ss.years(1)))
```

Note

To introduce a method partway through a simulation, use the add_method intervention rather than building the method list by hand.

Methods

Name Description
expon_scale_callback Sample from exponential distribution with age factors
gamma_scale_callback Sample from gamma distribution with age factors
llogis_scale_callback Sample from log-logistic distribution with age factors
lognorm_mean_callback Sample from lognormal distribution with age factors
set_dur_use Set the duration of use for this method.
weibull_scale_callback Sample from Weibull distribution with age factors
expon_scale_callback
methods.Method.expon_scale_callback(sim, uids)

Sample from exponential distribution with age factors

gamma_scale_callback
methods.Method.gamma_scale_callback(sim, uids)

Sample from gamma distribution with age factors

llogis_scale_callback
methods.Method.llogis_scale_callback(sim, uids)

Sample from log-logistic distribution with age factors

lognorm_mean_callback
methods.Method.lognorm_mean_callback(sim, uids)

Sample from lognormal distribution with age factors

set_dur_use
methods.Method.set_dur_use(
    dist_type,
    par1=None,
    par2=None,
    age_factors=None,
    **kwargs,
)

Set the duration of use for this method. Args: dist_type: Type of distribution to use (e.g., ‘lognorm’, ‘gamma’, etc.) par1: First parameter for the distribution (e.g., mean for lognorm, shape for gamma) par2: Second parameter for the distribution (e.g., std for lognorm, scale for gamma) age_factors: Optional age factors to apply to the duration kwargs: Additional parameters for the distribution

weibull_scale_callback
methods.Method.weibull_scale_callback(sim, uids)

Sample from Weibull distribution with age factors

RandomChoice

methods.RandomChoice(pars=None, **kwargs)

Choose a method uniformly at random.

Intended for testing model mechanics, not for producing realistic method mix. Because it needs no fitted data, it is the only choice module that accepts a method list containing methods with no per-method data – useful when checking that a new method behaves sensibly before wiring up its uptake.

Parameters

Name Type Description Default
pars dict parameters for the choice module None
kwargs dict passed to ContraceptiveChoice {}

Example:

```python
import fpsim as fp
import fpsim.methods as fpm

methods = fpm.make_methods()
methods += fpm.Method(name='dmpasc', label='DMPA-SC', efficacy=0.983, modern=True,
                      dur_use=ss.lognorm_ex(ss.years(2), ss.years(1)))
sim = fp.Sim(location='kenya', contraception_module=fpm.RandomChoice(methods=methods))
```

SimpleChoice

methods.SimpleChoice(
    pars=None,
    location=None,
    data=None,
    contra_mod='simple',
    **kwargs,
)

Choose a method based on age and previous method.

Uses location-specific fitted data, so it must be initialized with either a location string or a data dictionary. Because the fit is per method, passing a method list that contains a method with no fitted duration data raises an IndexError; to introduce a new method use the add_method intervention with copy_from, which inherits an existing method’s behavior.

Parameters

Name Type Description Default
pars dict parameters for the choice module None
location str location whose fitted coefficients to load, e.g. 'kenya' None
data dict pre-loaded data, used instead of loading from location None
contra_mod str which fitted coefficient set to use 'simple'
kwargs dict passed to RandomChoice {}

Example:

```python
import fpsim as fp
import fpsim.methods as fpm

sim = fp.Sim(location='kenya', contraception_module=fpm.SimpleChoice(location='kenya'))
```

Attributes

Name Description
method_idx Return list of method indices from the method choice pars

Methods

Name Description
get_prob_use Return an array of probabilities that each woman will use contraception.
set_dur_method Time on method depends on age and method
get_prob_use
methods.SimpleChoice.get_prob_use(uids, event=None)

Return an array of probabilities that each woman will use contraception.

set_dur_method
methods.SimpleChoice.set_dur_method(uids, method_used=None)

Time on method depends on age and method

StandardChoice

methods.StandardChoice(
    pars=None,
    location=None,
    data=None,
    contra_mod='mid',
    **kwargs,
)

Choose a method based on age, education, wealth, parity and prior use.

This is the default choice module, used when no contraception_module is passed to Sim. It extends SimpleChoice with education and wealth, and carries the same requirement for per-method fitted data.

Parameters

Name Type Description Default
pars dict parameters for the choice module None
location str location whose fitted coefficients to load, e.g. 'kenya' None
data dict pre-loaded data, used instead of loading from location None
contra_mod str which fitted coefficient set to use 'mid'
kwargs dict passed to SimpleChoice {}

Example:

```python
import fpsim as fp

# Used automatically, so these are equivalent
sim = fp.Sim(location='kenya')
sim = fp.Sim(location='kenya',
             contraception_module=fp.StandardChoice(location='kenya'))
```

Methods

Name Description
get_prob_use Return an array of probabilities that each woman will use contraception.
update_intent_to_use Update intent to use contraception based on regression coefficients
get_prob_use
methods.StandardChoice.get_prob_use(uids, event=None)

Return an array of probabilities that each woman will use contraception.

update_intent_to_use
methods.StandardChoice.update_intent_to_use(uids)

Update intent to use contraception based on regression coefficients

Functions

Name Description
make_contra_pars Shortcut for making a new instance of ContraPars
make_method_list Create methods from a DataFrame.
make_methods Build the default method list as an ndict keyed by method name.

make_contra_pars

methods.make_contra_pars()

Shortcut for making a new instance of ContraPars

make_method_list

methods.make_method_list(methods_df)

Create methods from a DataFrame. Args: methods_df: DataFrame with columns: name, label, csv_name, efficacy, modern, Returns: method_list: List of Method objects

make_methods

methods.make_methods(method_list=None, method_df=None)

Build the default method list as an ndict keyed by method name.

Call this when you want to start from the standard ten methods and add your own, rather than constructing the full list by hand.

Parameters

Name Type Description Default
method_list list explicit list of Method objects None
method_df DataFrame method definitions to build from, instead of the defaults None

Returns

Name Type Description
ndict methods keyed by name

Example:

```python
import fpsim.methods as fpm

methods = fpm.make_methods()
print(list(methods.keys()))  # ['none', 'pill', 'iud', 'inj', ...]
```