fpsim.sim module

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

class People(pars, n=None, **kwargs)[source]

Bases: BasePeople

Class for all the people in the simulation.

update_method()[source]

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

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

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

check_mortality()[source]

Decide if person dies at a timestep

check_sexually_active()[source]

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

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

make_pregnant()[source]

Update the selected agents to be pregnant

check_lam()[source]

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

update_breastfeeding()[source]

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

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

update_pregnancy()[source]

Advance pregnancy in time and check for miscarriage

reset_breastfeeding()[source]

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

check_maternal_mortality()[source]

Check for probability of maternal mortality

check_infant_mortality()[source]

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

check_delivery()[source]

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

update_age()[source]

Advance age in the simulation

update_age_bin_totals()[source]

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

log_age_split(binned_ages_t, channel, numerators, denominators=None)[source]
track_mcpr()[source]

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

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

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

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 Sim(pars=None, location=None, label=None, track_children=False, **kwargs)[source]

Bases: BaseSim

The Sim class handles the running of the simulation: the creation of the population and the dynamics of the epidemic. This class handles the mechanics of the actual simulation, while BaseSim takes care of housekeeping (saving, loading, exporting, etc.). Please see the BaseSim class for additional methods.

Parameters:
  • pars (dict) – parameters to modify from their default values

  • location (str) – name of the location (country) to look for data file to load

  • label (str) – the name of the simulation (useful to distinguish in batch runs)

  • track_children (bool) – whether to track links between mothers and their children (slow, so disabled by default)

  • kwargs (dict) – additional parameters; passed to fp.make_pars()

Examples:

sim = fp.Sim()
sim = fp.Sim(n_agents=10e3, location='senegal', label='My small Seneagl sim')
initialize(force=False)[source]
init_results()[source]
get_age_sex(n)[source]

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

Set up each person

init_people(output=False, **kwargs)[source]

Create the people

update_methods()[source]

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

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

Add link between newly added individuals and their mothers

apply_interventions()[source]

Apply each intervention in the model

apply_analyzers()[source]

Apply each analyzer in the model

finalize_interventions()[source]

Make any final updates to interventions (e.g. to shrink)

finalize_analyzers()[source]

Make any final updates to analyzers (e.g. to shrink)

run(verbose=None)[source]

Run the simulation

store_postpartum()[source]

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

to_df(include_range=False)[source]

Export all sim results to a dataframe

Parameters:

include_range (bool) – if True, and if the sim results have best, high, and low, then export all of them; else just best

conform_y_axes(figure, bottom=0, top=100)[source]
plot(to_plot=None, xlims=None, ylims=None, do_save=None, do_show=True, filename='fpsim.png', style=None, fig_args=None, plot_args=None, axis_args=None, fill_args=None, label=None, new_fig=True, colors=None)[source]

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

Parameters:
  • to_plot (str/dict) – What to plot (e.g. ‘default’ or ‘cpr’), or a dictionary of result:label pairs

  • xlims (list/dict) – passed to pl.xlim() (use [None, None] for default)

  • ylims (list/dict) – passed to pl.ylim()

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

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

  • filename (str) – If a figure is saved, use this filename

  • style (bool) – Custom style arguments

  • fig_args (dict) – Passed to pl.figure() (plus nrows and ncols for overriding defaults)

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

  • colors (list/dict) – Colors for plots with multiple lines

plot_age_first_birth(do_show=None, do_save=None, fig_args=None, filename='first_birth_age.png')[source]

Plot age at first birth

Parameters:
  • fig_args (dict) – arguments to pass to pl.figure()

  • do_show (bool) – whether or not the user wants to show the output plot (default: true)

  • do_save (bool) – whether or not the user wants to save the plot to filepath (default: false)

  • filename (str) – the name of the path to output the plot

compute_method_usage()[source]

Computes method mix proportions from a sim object

Returns:

list of lists where list[years_after_start][method_index] == proportion of fecundity aged women using that method on that year

format_method_df(method_list=None, timeseries=False)[source]

Outputs a dataframe for method mix plotting for either a single year or a timeseries

Parameters:
  • method_list (list) – list of proportions where each index is equal to the integer value of the corresponding method

  • timeseries (boolean) – if true, provides a dataframe with data from every year, otherwise a method_list is required for the year

Returns:

pandas.DataFrame with columns [“Percentage”, “Method”, “Sim”, “Seed”] and optionally “Year” if timeseries

class MultiSim(sims=None, base_sim=None, label=None, n=None, **kwargs)[source]

Bases: prettyobj

The MultiSim class handles the running of multiple simulations

run(compute_stats=True, **kwargs)[source]

Run all simulations in the MultiSim

compute_stats(return_raw=False, quantiles=None, use_mean=False, bounds=None)[source]

Compute statistics across multiple sims

static merge(*args, base=False)[source]

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

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, recompute=True, **kwargs)[source]

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(yearly=False, mean=False)[source]

Export all individual sim results to a dataframe

plot(to_plot=None, plot_sims=True, do_show=None, do_save=None, filename='fp_multisim.png', fig_args=None, axis_args=None, plot_args=None, style=None, colors=None, **kwargs)[source]

Plot the MultiSim

Parameters:

plot_sims (bool) – whether to plot individual sims (else, plot with uncertainty bands)

See sim.plot() for additional args.

plot_age_first_birth(do_show=False, do_save=True, output_file='age_first_birth_multi.png')[source]
parallel(*args, **kwargs)[source]

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)