fpsim.sim module

Defines the Sim class, the core class of the FP model (FPsim).

class fpsim.sim.People(pars, n=None, **kwargs)

Bases: fpsim.base.BasePeople

Class for all the people in the simulation.

update_method()

Uses a switching matrix from DHS data to decide based on a person’s original method their probability of changing to a new method and assigns them the new method. Currently allows switching on whole calendar years to enter function. Matrix serves as an initiation, discontinuation, continuation, and switching matrix. Transition probabilities are for 1 year and only for women who have not given birth within the last 6 months.

update_method_pp()

Utilizes data from birth to allow agent to initiate a method postpartum coming from birth by 3 months postpartum and then initiate, continue, or discontinue a method by 6 months postpartum. Next opportunity to switch methods will be on whole calendar years, whenever that falls.

update_methods()

If eligible (age 15-49 and not pregnant), choose new method or stay with current one

check_mortality()

Decide if person dies at a timestep

check_sexually_active()

Decide if agent is sexually active based either on month postpartum or age if not postpartum. Postpartum and general age-based data from DHS.

check_conception()

Decide if person (female) becomes pregnant at a timestep.

make_pregnant()

Update the selected agents to be pregnant

check_lam()

Check to see if postpartum agent meets criteria for LAM in this time step

update_breastfeeding()

Track breastfeeding, and update time of breastfeeding for individual pregnancy. Agents are randomly assigned a duration value based on a gumbel distribution drawn from the 2018 DHS variable for breastfeeding months. The mean (mu) and the std dev (beta) are both drawn from that distribution in the DHS data.

update_postpartum()

Track duration of extended postpartum period (0-24 months after birth). Only enter this function if agent is postpartum

update_pregnancy()

Advance pregnancy in time and check for miscarriage

reset_breastfeeding()

Stop breastfeeding, calculate total lifetime duration so far, and reset lactation episode to zero

check_maternal_mortality()

Check for probability of maternal mortality

check_infant_mortality()

Check for probability of infant mortality (death < 1 year of age)

check_delivery()

Decide if pregnant woman gives birth and explore maternal mortality and child mortality

update_age()

Advance age in the simulation

update_age_bin_totals()

Count how many total live women in each 5-year age bin 10-50, for tabulating ASFR

track_mcpr()

Track for purposes of calculating mCPR at the end of the timestep after all people are updated 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

track_cpr()

Track for purposes of calculating newer ways to conceptualize contraceptive prevalence at the end of the timestep after all people are updated Includes women using any method of contraception, including LAM Denominator of possible users includes all women aged 15-49

track_acpr()

Track for purposes of calculating newer ways to conceptualize contraceptive prevalence at the end of the timestep after all people are updated Denominator of possible users excludes pregnant women and those not sexually active in the last 4 weeks Used to compare new metrics of contraceptive prevalence and eventually unmet need to traditional mCPR definitions

init_step_results()
update()

Update the person’s state for the given timestep. t is the time in the simulation in years (ie, 0-60), y is years of simulation (ie, 1960-2010)

class fpsim.sim.Sim(pars=None, location=None, label=None, mother_ids=False, **kwargs)

Bases: fpsim.base.BaseSim

The Sim class handles the running of the simulation

initialize(force=False)
init_results()
get_age_sex(n)

For an ex nihilo person, figure out if they are male and female, and how old

make_people(n=1, age=None, sex=None, method=None, debut_age=None)

Set up each person

init_people(output=False, **kwargs)

Create the people

update_methods()

Update all contraceptive method matrices to have probabilities that follow a trend closest to the year the sim is on based on mCPR in that year

update_mortality()

Update infant and maternal mortality for the sim’s current year. Update general mortality trend as this uses a spline interpolation instead of an array

update_mothers()

Add link between newly added individuals and their mothers

apply_interventions()

Apply each intervention in the model

apply_analyzers()

Apply each analyzer in the model

run(verbose=None)

Run the simulation

store_postpartum()

Stores snapshot of who is currently pregnant, their parity, and various postpartum states in final step of model for use in calibration

to_df()

Export all sim results to a dataframe

plot(do_save=None, do_show=True, fig_args=None, plot_args=None, axis_args=None, fill_args=None, label=None, new_fig=True)

Plot the results – can supply arguments for both the figure and the plots.

Parameters
  • dosave (bool) – Whether or not to save the figure. If a string, save to that filename.

  • doshow (bool) – Whether to show the plots at the end

  • figargs (dict) – Passed to pl.figure()

  • plot_args (dict) – Passed to pl.plot()

  • axis_args (dict) – Passed to pl.subplots_adjust()

  • fill_args (dict) – Passed to pl.fill_between())

  • label (str) – Label to override default

  • new_fig (bool) – whether to create a new figure (true unless part of a multisim)

plot_cpr(do_save=None, do_show=True, fig_args=None, plot_args=None, axis_args=None, fill_args=None, label=None, new_fig=True)

Plot the results – can supply arguments for both the figure and the plots.

Parameters
  • dosave (bool) – Whether or not to save the figure. If a string, save to that filename.

  • doshow (bool) – Whether to show the plots at the end

  • figargs (dict) – Passed to pl.figure()

  • plot_args (dict) – Passed to pl.plot()

  • axis_args (dict) – Passed to pl.subplots_adjust()

  • fill_args (dict) – Passed to pl.fill_between())

  • label (str) – Label to override default

  • new_fig (bool) – whether to create a new figure (true unless part of a multisim)

plot_age_first_birth(do_show=False, do_save=True, output_file='first_birth_age.png')
plot_people()

Use imshow() to show all individuals as rows, with time as columns, one pixel per timestep per person

log_daily_totals()
save_daily_totals()
class fpsim.sim.MultiSim(sims=None, base_sim=None, label=None, n=None, **kwargs)

Bases: sciris.sc_utils.prettyobj

The MultiSim class handles the running of multiple simulations

run(compute_stats=True, **kwargs)
compute_stats(return_raw=False, quantiles=None, use_mean=False, bounds=None)

Compute statistics across multiple sims

static merge(*args, base=False)

Convenience method for merging two MultiSim objects.

Parameters
  • args (MultiSim) – the MultiSims to merge (either a list, or separate)

  • base (bool) – if True, make a new list of sims from the multisim’s two base sims; otherwise, merge the multisim’s lists of sims

Returns

a new MultiSim object

Return type

msim (MultiSim)

Examples:

mm1 = fp.MultiSim.merge(msim1, msim2, base=True) mm2 = fp.MultiSim.merge([m1, m2, m3, m4], base=False)

split(inds=None, chunks=None)

Convenience method for splitting one MultiSim into several. You can specify either individual indices of simulations to extract, via inds, or consecutive chunks of indices, via chunks. If this function is called on a merged MultiSim, the chunks can be retrieved automatically and no arguments are necessary.

Parameters
  • inds (list) – a list of lists of indices, with each list turned into a MultiSim

  • chunks (int or list) – if an int, split the MultiSim into that many chunks; if a list return chunks of that many sims

Returns

A list of MultiSim objects

Examples:

m1 = fp.MultiSim(fp.Sim(label='sim1'))
m2 = fp.MultiSim(fp.Sim(label='sim2'))
m3 = fp.MultiSim.merge(m1, m2)
m3.run()
m1b, m2b = m3.split()

msim = fp.MultiSim(fp.Sim(), n_runs=6)
msim.run()
m1, m2 = msim.split(inds=[[0,2,4], [1,3,5]])
mlist1 = msim.split(chunks=[2,4]) # Equivalent to inds=[[0,1], [2,3,4,5]]
mlist2 = msim.split(chunks=2) # Equivalent to inds=[[0,1,2], [3,4,5]]
remerge(base=True, **kwargs)

Split a sim, compute stats, and re-merge.

Parameters
  • base (bool) – whether to use the base sim (otherwise, has no effect)

  • kwargs (dict) – passed to msim.split()

Note: returns a new MultiSim object (if that concerns you).

to_df()

Export all individual sim results to a dataframe

plot(do_show=True, plot_sims=True, fig_args=None, plot_args=None, plot_cpr=False, **kwargs)

Plot the MultiSim

plot_cpr(*args, **kwargs)

Plot the contraceptive prevalence rate

plot_method_mix(n_sims=10, do_show=False, do_save=True, filepath='method_mix.png')

Plots the average method mix for n_sims runs

Parameters
  • n_sims (int) – The number of sims you want to run to calculate average mix and standard deviation.

  • do_show (bool) – Whether or not the user wants to show the output plot.

  • do_save (bool) – Whether or not the user wants to save the plot to filepath.

  • filepath (str) – The name of the path to output the plot.

plot_age_first_birth(do_show=False, do_save=True, output_file='age_first_birth_multi.png')
fpsim.sim.parallel(*args, **kwargs)

A shortcut to fp.MultiSim(), allowing the quick running of multiple simulations at once.

Parameters
  • args (list) – The simulations to run

  • kwargs (dict) – passed to multi_run()

Returns

A run MultiSim object.

Examples:

s1 = fp.Sim(exposure_factor=0.5, label='Low')
s2 = fp.Sim(exposure_factor=2.0, label='High')
fp.parallel(s1, s2).plot()
msim = fp.parallel(s1, s2)