Defines the Sim class, the core class of the FP model (FPsim).
- class People(pars, n=None, **kwargs)¶
Class for all the people in the simulation.
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.
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.
If eligible (age 15-49 and not pregnant), choose new method or stay with current one
Decide if person dies at a timestep
Decide if an agent has reached their age at first partnership. Age-based data from DHS.
Decide if agent is sexually active based either on month postpartum or age if not postpartum. Postpartum and general age-based data from DHS.
Decide if person (female) becomes pregnant at a timestep.
Update the selected agents to be pregnant
Check to see if postpartum agent meets criteria for LAM in this time step
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.
Track duration of extended postpartum period (0-24 months after birth). Only enter this function if agent is postpartum
Advance pregnancy in time and check for miscarriage
Stop breastfeeding, calculate total lifetime duration so far, and reset lactation episode to zero
Check for probability of maternal mortality
Check for probability of infant mortality (death < 1 year of age)
Decide if pregnant woman gives birth and explore maternal mortality and child mortality
Advance age in the simulation
Advance education attainment in the simulation, determine if agents have completed their educationm,
Interrupt education due to pregnancy. This method hinders education progression if a woman is pregnant and towards the end of the first trimester
# Basic mechanism to resume education post-pregnancy: # If education was interrupted due to pregnancy, resume after 9 months pospartum () #TODO: check if there’s any evidence supporting this assumption
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)¶
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 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 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
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)¶
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.
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
sim = fp.Sim() sim = fp.Sim(n_agents=10e3, location='senegal', label='My small Seneagl sim')
For an ex nihilo person, figure out if they are male and female, and how old
- initialize_urban(n, urban_prop)¶
Get initial distribution of urban
- initialize_empowerment(n, ages, sexes)¶
Get initial distribution of women’s empowerment metrics/attributes
- initialize_education(n, ages, sexes, urban)¶
Get initial distribution of education goal, attainment and whether a woman has reached their education goal
- initialize_partnered(n, ages, sexes)¶
Get initial distribution of age at first partnership
- 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 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 infant and maternal mortality for the sim’s current year. Update general mortality trend as this uses a spline interpolation instead of an array
Add link between newly added individuals and their mothers
Apply each intervention in the model
Apply each analyzer in the model
Make any final updates to interventions (e.g. to shrink)
Make any final updates to analyzers (e.g. to shrink)
Run the simulation
Stores snapshot of who is currently pregnant, their parity, and various postpartum states in final step of model for use in calibration
Export all sim results to a dataframe
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)¶
- 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)¶
Plot the results – can supply arguments for both the figure and the plots.
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
ncolsfor 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')¶
Plot age at first birth
fig_args (dict) – arguments to pass to
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
Computes method mix proportions from a sim object
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)¶
Outputs a dataframe for method mix plotting for either a single year or a timeseries
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
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)¶
The MultiSim class handles the running of multiple simulations
- run(compute_stats=True, **kwargs)¶
Run all simulations in the MultiSim
- 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.
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
a new MultiSim object
- Return type:
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.
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
A list of MultiSim objects
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)¶
Split a sim, compute stats, and re-merge.
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)¶
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)¶
Plot the MultiSim
plot_sims (bool) – whether to plot individual sims (else, plot with uncertainty bands)
sim.plot()for additional args.
- plot_age_first_birth(do_show=False, do_save=True, output_file='age_first_birth_multi.png')¶
- parallel(*args, **kwargs)¶
A shortcut to
fp.MultiSim(), allowing the quick running of multiple simulations at once.
args (list) – The simulations to run
kwargs (dict) – passed to multi_run()
A run MultiSim object.
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)