-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcontraception.py
1387 lines (1121 loc) · 70.8 KB
/
contraception.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import warnings
from pathlib import Path
import numpy as np
import pandas as pd
from tlo import Date, DateOffset, Module, Parameter, Property, Types, logging
from tlo.analysis.utils import flatten_multi_index_series_into_dict_for_logging
from tlo.events import Event, IndividualScopeEventMixin, PopulationScopeEventMixin, RegularEvent
from tlo.methods.healthsystem import HSI_Event
from tlo.util import random_date, sample_outcome, transition_states
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class Contraception(Module):
"""Contraception module covering baseline contraception methods use, failure (i.e., pregnancy),
Switching contraceptive methods, and discontinuation rates by age.
Calibration is done in two stages:
(i) A scaling factor on the risk of pregnancy (`scaling_factor_on_monthly_risk_of_pregnancy`) is used to induce the
correct number of age-specific births initially, given the initial pattern of contraceptive use;
(ii) Trends over time in the risk of starting (`time_age_trend_in_initiation`) and stopping
(`time_age_trend_in_stopping`) of contraceptives are used to induce the correct trend in the number of births."""
INIT_DEPENDENCIES = {'Demography'}
OPTIONAL_INIT_DEPENDENCIES = {'HealthSystem'}
ADDITIONAL_DEPENDENCIES = {'Labour', 'Hiv'}
METADATA = {}
PARAMETERS = {
'Method_Use_In_2010': Parameter(Types.DATA_FRAME,
'Proportion of women using each method in 2010, by age.'),
'Pregnancy_NotUsing_In_2010': Parameter(Types.DATA_FRAME,
'Probability per year of a women not on contraceptive becoming '
'pregnant, by age.'),
'Pregnancy_NotUsing_HIVeffect': Parameter(Types.DATA_FRAME,
'Relative probability of becoming pregnant whilst not using a '
'a contraceptive for HIV-positive women compared to HIV-negative '
'women.'),
'Failure_ByMethod': Parameter(Types.DATA_FRAME,
'Probability per month of a women on a contraceptive becoming pregnant, by '
'method.'),
'rr_fail_under25': Parameter(Types.REAL,
'The relative risk of becoming pregnant whilst using a contraceptive for woman '
'younger than 25 years compared to older women.'),
'Initiation_ByMethod': Parameter(Types.DATA_FRAME,
'Probability per month of a women who is not using any contraceptive method of'
' starting use of a method, by method.'),
'Interventions_Pop': Parameter(Types.DATA_FRAME,
'Pop (population scale contraception intervention) intervention multiplier.'),
'Interventions_PPFP': Parameter(Types.DATA_FRAME,
'PPFP (post-partum family planning) intervention multiplier.'),
'Initiation_ByAge': Parameter(Types.DATA_FRAME,
'The effect of age on the probability of starting use of contraceptive (add one '
'for multiplicative effect).'),
'Initiation_AfterBirth': Parameter(Types.DATA_FRAME,
'The probability of a woman starting a contraceptive immidiately after birth'
', by method.'),
'Discontinuation_ByMethod': Parameter(Types.DATA_FRAME,
'The probability per month of discontinuing use of a method, by method.'),
'Discontinuation_ByAge': Parameter(Types.DATA_FRAME,
'The effect of age on the probability of discontinuing use of contraceptive '
'(add one for multiplicative effect).'),
'Prob_Switch_From': Parameter(Types.DATA_FRAME,
'The probability per month that a women switches from one form of contraceptive '
'to another, conditional that she will not discontinue use of the method.'),
'Prob_Switch_From_And_To': Parameter(Types.DATA_FRAME,
'The probability of switching to a new method, by method, conditional that'
' the woman will switch to a new method.'),
'days_between_appts_for_maintenance': Parameter(Types.LIST,
'The number of days between successive family planning '
'appointments for women that are maintaining the use of a '
'method (for each method in'
'sorted(self.states_that_may_require_HSI_to_maintain_on), i.e.'
'[IUD, implant, injections, other_modern, pill]).'),
'age_specific_fertility_rates': Parameter(
Types.DATA_FRAME, 'Data table from official source (WPP) for age-specific fertility rates and calendar '
'period.'),
'scaling_factor_on_monthly_risk_of_pregnancy': Parameter(
Types.LIST, "Scaling factor (by age-group: 15-19, 20-24, ..., 45-49) on the monthly risk of pregnancy and "
"contraceptive failure rate. This value is found through calibration so that, at the beginning "
"of the simulation, the age-specific monthly probability of a woman having a live birth matches"
" the WPP age-specific fertility rate value for the same year."),
'max_number_of_runs_of_hsi_if_consumable_not_available': Parameter(
Types.INT, "The maximum number of time an HSI can run (repeats occur if the consumables are not "
"available)."),
'max_days_delay_between_decision_to_change_method_and_hsi_scheduled': Parameter(
Types.INT, "The maximum delay (in days) between the decision for a contraceptive to change and the `topen` "
"date of the HSI that is scheduled to effect the change (when using the healthsystem)."),
'use_interventions': Parameter(
Types.BOOL, "if True: FP interventions (pop & ppfp) are simulated from the date 'interventions_start_date',"
" if False: FP interventions (pop & ppfp) are not simulated."),
'interventions_start_date': Parameter(
Types.DATE, "The date since which the FP interventions (pop & ppfp) are implemented, if at all (ie, if "
"use_interventions==True")
}
all_contraception_states = {
'not_using', 'pill', 'IUD', 'injections', 'implant', 'male_condom', 'female_sterilization', 'other_modern',
'periodic_abstinence', 'withdrawal', 'other_traditional'
}
# These are the 11 categories of contraception ('not_using' + 10 methods) from the DHS analysis of initiation,
# discontinuation, failure and switching rates.
# 'other modern' includes Male sterilization, Female Condom, Emergency contraception;
# 'other traditional' includes lactational amenohroea (LAM), standard days method (SDM), 'other traditional
# method').
contraceptives_initiated_with_additional_items = {
'pill', 'IUD', 'injections', 'implant', 'female_sterilization'
}
# These are methods for which additional items ('co_initiation') are used to initiate the method after not using any
# contraceptive or after using a method which is not in this category.
PROPERTIES = {
'co_contraception': Property(Types.CATEGORICAL, 'Current contraceptive method',
categories=sorted(all_contraception_states)),
'is_pregnant': Property(Types.BOOL, 'Whether this individual is currently pregnant'),
'date_of_last_pregnancy': Property(Types.DATE, 'Date that the most recent or current pregnancy began.'),
'co_unintended_preg': Property(Types.BOOL, 'Whether the most recent or current pregnancy was unintended.'),
'co_date_of_last_fp_appt': Property(Types.DATE,
'The date of the most recent Family Planning appointment. This is used to '
'determine if a Family Planning appointment is needed to maintain the '
'person on their current contraceptive. If the person is to maintain use of'
' the current contraceptive, they will have an HSI only if the days elapsed'
' since this value exceeds the method-specific parameter '
'`days_between_appts_for_maintenance`.'
)
}
def __init__(self, name=None, resourcefilepath=None, use_healthsystem=True, run_update_contraceptive=True):
super().__init__(name)
self.resourcefilepath = resourcefilepath
self.use_healthsystem = use_healthsystem # if True: initiation and switches to contraception require an HSI;
# if False: initiation and switching do not occur through an HSI
self.run_update_contraceptive = run_update_contraceptive # If 'False' prevents any logic occurring for
# updating/changing/maintaining contraceptive methods.
self.states_that_may_require_HSI_to_switch_to = {'male_condom', 'injections', 'other_modern', 'IUD', 'pill',
'female_sterilization', 'implant'}
self.states_that_may_require_HSI_to_maintain_on = {'male_condom', 'injections', 'other_modern', 'IUD', 'pill',
'implant'}
assert self.states_that_may_require_HSI_to_switch_to.issubset(self.all_contraception_states)
assert self.states_that_may_require_HSI_to_maintain_on.issubset(self.states_that_may_require_HSI_to_switch_to)
self.processed_params = dict() # (Will store the processed data for rates/probabilities of outcomes).
self.cons_codes = dict() # (Will store the consumables codes for use in the HSI)
self.rng2 = None # (Will be a second random number generator, used for things to do with scheduling HSI)
self._women_ids_sterilized_below30 = set() # The ids of women who had female sterilization initiated when they
# were less than 30 years old.
def read_parameters(self, data_folder):
"""Import the relevant sheets from the ResourceFile (excel workbook) and declare values for other parameters
(CSV ResourceFile).
"""
workbook = pd.read_excel(Path(self.resourcefilepath) / 'contraception' / 'ResourceFile_Contraception.xlsx', sheet_name=None)
# Import selected sheets from the workbook as the parameters
sheet_names = [
'Method_Use_In_2010',
'Pregnancy_NotUsing_In_2010',
'Pregnancy_NotUsing_HIVeffect',
'Failure_ByMethod',
'Initiation_ByAge',
'Initiation_ByMethod',
'Interventions_Pop',
'Interventions_PPFP',
'Initiation_AfterBirth',
'Discontinuation_ByMethod',
'Discontinuation_ByAge',
'Prob_Switch_From',
'Prob_Switch_From_And_To',
]
for sheet in sheet_names:
self.parameters[sheet] = workbook[sheet]
# Declare values for other parameters
self.load_parameters_from_dataframe(pd.read_csv(
Path(self.resourcefilepath) / 'contraception' / 'ResourceFile_ContraceptionParams.csv'
))
# Import the Age-specific fertility rate data from WPP
self.parameters['age_specific_fertility_rates'] = \
pd.read_csv(Path(self.resourcefilepath) / 'demography' / 'ResourceFile_ASFR_WPP.csv')
# Import 2010 pop and count numbs of women 15-49 & 30-49
pop_2010 = self.sim.modules["Demography"].parameters["pop_2010"]
n_females_aged_15_to_49_in_2010 = pop_2010[
(pop_2010.Sex == "F") & (pop_2010.Age >= 15) & (pop_2010.Age <= 49)
].Count.sum()
n_females_aged_30_to_49_in_2010 = pop_2010[
(pop_2010.Sex == "F") & (pop_2010.Age >= 30) & (pop_2010.Age <= 49)
].Count.sum()
self.ratio_n_females_30_49_to_15_49_in_2010 = (
n_females_aged_30_to_49_in_2010 / n_females_aged_15_to_49_in_2010
)
def pre_initialise_population(self):
"""Process parameters before initialising population and simulation"""
self.processed_params = self.process_params()
def initialise_population(self, population):
"""Set initial values for properties"""
# 1) Set default values for properties
df = population.props
df.loc[df.is_alive, 'co_contraception'] = 'not_using'
df.loc[df.is_alive, 'is_pregnant'] = False
df.loc[df.is_alive, 'date_of_last_pregnancy'] = pd.NaT
df.loc[df.is_alive, 'co_unintended_preg'] = False
df.loc[df.is_alive, 'co_date_of_last_fp_appt'] = pd.NaT
# 2) Assign contraception method
# Select females aged 15-49 from population, for current year
females1549 = df.is_alive & (df.sex == 'F') & df.age_years.between(15, 49)
p_method = self.processed_params['initial_method_use']
df.loc[females1549, 'co_contraception'] = df.loc[females1549, 'age_years'].apply(
lambda _age_years: self.rng.choice(p_method.columns, p=p_method.loc[_age_years])
)
# 3) Give a notional date on which the last appointment occurred for those that need them
needs_appts = females1549 & df['co_contraception'].isin(self.states_that_may_require_HSI_to_maintain_on)
states_to_maintain_on = sorted(self.states_that_may_require_HSI_to_maintain_on)
df.loc[needs_appts, 'co_date_of_last_fp_appt'] = df.loc[needs_appts, 'co_contraception'].astype('string').apply(
lambda _co_contraception: random_date(
self.sim.date - pd.DateOffset(
days=self.parameters['days_between_appts_for_maintenance']
[states_to_maintain_on.index(_co_contraception)]),
self.sim.date - pd.DateOffset(days=1),
self.rng
)
)
def initialise_simulation(self, sim):
"""
* Schedule the ContraceptionPoll and ContraceptionLoggingEvent
* Retrieve the consumables codes for the consumables used
* Create second random number generator
* Schedule births to occur during the first 9 months of the simulation
"""
# Schedule the first occurrence of the Logging event to occur at the beginning of the simulation
sim.schedule_event(ContraceptionLoggingEvent(self), sim.date)
# Schedule first occurrences of Contraception Poll to occur at the beginning of the simulation
sim.schedule_event(ContraceptionPoll(self, run_update_contraceptive=self.run_update_contraceptive), sim.date)
# Retrieve the consumables codes for the consumables used
if self.use_healthsystem:
self.cons_codes = self.get_item_code_for_each_contraceptive()
# Create second random number generator
self.rng2 = np.random.RandomState(self.rng.randint(2 ** 31 - 1))
# Schedule births to occur during the first 9 months of the simulation
self.schedule_births_for_first_9_months()
if self.parameters['use_interventions']:
# Schedule StartInterventions event to update parameters when FP interventions are introduced
sim.schedule_event(StartInterventions(self), Date(self.parameters['interventions_start_date']))
# Log initiation date of interventions and implementation costs
logger.info(key='interventions_start_date',
data={
'date_co_interv_implemented': self.parameters['interventions_start_date']
},
description='The date when parameters are updated to enable the FP interventions.'
)
def on_birth(self, mother_id, child_id):
"""
* 1) Formally end the pregnancy
* 2) Initialise properties for the newborn
"""
df = self.sim.population.props
if mother_id >= 0: # check if direct birth look for positive mother ids
self.end_pregnancy(person_id=mother_id)
# Initialise child's properties:
new_properties = {
'co_contraception': 'not_using',
'is_pregnant': False,
'date_of_last_pregnancy': pd.NaT,
'co_unintended_preg': False,
'co_date_of_last_fp_appt': pd.NaT,
}
df.loc[child_id, new_properties.keys()] = new_properties.values()
def end_pregnancy(self, person_id):
"""End the pregnancy. Reset pregnancy status and may initiate a contraceptive method.
This is called by `on_birth` in this module and by Labour/Pregnancy modules for births that do result in live
birth."""
assert self.sim.population.props.at[person_id, 'co_contraception'] \
not in self.contraceptives_initiated_with_additional_items
# TODO: Shouldn't it be even == "not_using"?
# It is not always the case when used along with Joe's rmnch modules, why?
self.sim.population.props.at[person_id, 'is_pregnant'] = False
person_age = self.sim.population.props.at[person_id, 'age_years']
self.select_contraceptive_following_birth(person_id, person_age)
def process_params(self):
"""Process parameters that have been read-in."""
processed_params = dict()
def expand_to_age_years(values_by_age_groups, ages_by_year):
_d = dict(zip(['15-19', '20-24', '25-29', '30-34', '35-39', '40-44', '45-49'], values_by_age_groups))
return np.array(
[_d[self.sim.modules['Demography'].AGE_RANGE_LOOKUP[_age_year]] for _age_year in ages_by_year]
)
def initial_method_use():
"""Generate the distribution of method use by age for the start of the simulation."""
p_method = self.parameters['Method_Use_In_2010'].set_index('age').rename_axis('age_years')
# Normalise so that the sum within each age is 1.0
p_method = p_method.div(p_method.sum(axis=1), axis=0)
assert np.isclose(1.0, p_method.sum(axis=1)).all()
# Check correct format
assert set(p_method.columns) == set(self.all_contraception_states)
assert (p_method.index == range(15, 50)).all()
return p_method
def avoid_sterilization_below30(probs):
"""Prevent women below 30 years having female sterilization and adjust the probability for women 30 and over
to preserve the overall probability of initiating sterilization."""
# Input 'probs' must include probs for all methods including 'not_using'
assert set(probs.index) == set(self.all_contraception_states)
# Prevent women below 30 years having 'female_sterilization'
probs_below30 = probs.copy()
probs_below30['female_sterilization'] = 0.0
# Scale so that the probability of all outcomes sum to 1.0
probs_below30 = probs_below30 / probs_below30.sum()
assert np.isclose(1.0, probs_below30.sum())
# Increase prob of 'female_sterilization' in older women accordingly
probs_30plus = probs.copy()
probs_30plus['female_sterilization'] = (
probs.loc['female_sterilization'] /
self.ratio_n_females_30_49_to_15_49_in_2010
)
# Scale so that the probability of all outcomes sum to 1.0
probs_30plus = probs_30plus / probs_30plus.sum()
assert np.isclose(1.0, probs_30plus.sum())
return probs_below30, probs_30plus
def contraception_initiation():
"""Generate the probability per month of a woman initiating onto each contraceptive, by the age (in whole
years)."""
# Probability of initiation by method per month (average over all ages)
p_init_by_method = self.parameters['Initiation_ByMethod'].loc[0]
# Prevent women below 30 years having 'female_sterilization' while preserving the overall probability of
# 'female_sterilization' initiation
p_init_by_method_below30, p_init_by_method_30plus = avoid_sterilization_below30(p_init_by_method)
# Effect of age
age_effect = 1.0 + self.parameters['Initiation_ByAge'].set_index('age')['r_init1_age'].rename_axis(
"age_years")
# Year effect
year_effect = time_age_trend_in_initiation()
def apply_age_year_effects(probs_below30, probs_30plus):
# Assemble into age-specific data-frame:
probs_by_method_below30 = probs_below30.copy().drop('not_using')
probs_by_method_30plus = probs_30plus.copy().drop('not_using')
p_init = dict()
for year in year_effect.index:
p_init_this_year = dict()
for a in age_effect.index:
if a < 30:
p_init_this_year[a] = probs_by_method_below30 * age_effect.at[a] * year_effect.at[year, a]
else:
p_init_this_year[a] = probs_by_method_30plus * age_effect.at[a] * year_effect.at[year, a]
p_init_this_year_df = pd.DataFrame.from_dict(p_init_this_year, orient='index')
# Check correct format of age/method data-frame
assert set(p_init_this_year_df.columns) == set(self.all_contraception_states - {'not_using'})
assert (p_init_this_year_df.index == range(15, 50)).all()
assert (p_init_this_year_df >= 0.0).all().all()
p_init[year] = p_init_this_year_df
return p_init
return apply_age_year_effects(p_init_by_method_below30, p_init_by_method_30plus)
def contraception_switch():
"""Get the probability per month of a woman switching to contraceptive method, given that she is currently
using a different one."""
# Get the probability per month of the woman making a switch (to anything)
p_switch_from = self.parameters['Prob_Switch_From'].loc[0]
# Get the probability that the woman switches to a new contraceptive (given that she will switch to
# something different).
# Columns = "current method"; Row = "new method"
switching_matrix = self.parameters['Prob_Switch_From_And_To'].set_index('switchfrom').transpose()
# Prevent women below 30 years having 'female_sterilization'
switching_matrix_below30 = switching_matrix.copy()
switching_matrix_below30.loc['female_sterilization', :] = 0.0
switching_matrix_below30 = switching_matrix_below30.apply(lambda col: col / col.sum())
assert set(switching_matrix_below30.columns) == (
self.all_contraception_states - {"not_using", "female_sterilization"})
assert set(switching_matrix_below30.index) == (self.all_contraception_states - {"not_using"})
assert np.isclose(1.0, switching_matrix_below30.sum(axis=0)).all()
# Increase prob of 'female_sterilization' in older women accordingly
new_fs_probs_30plus = (
switching_matrix.loc['female_sterilization', :] /
self.ratio_n_females_30_49_to_15_49_in_2010
)
switching_matrix_except_fs = switching_matrix.loc[switching_matrix.index != 'female_sterilization']
switching_matrix_30plus = switching_matrix_except_fs.apply(lambda col: col / col.sum())
switching_matrix_30plus = switching_matrix_30plus * (1 - new_fs_probs_30plus)
switching_matrix_30plus.loc[new_fs_probs_30plus.name] = new_fs_probs_30plus
assert set(switching_matrix_30plus.columns) == (
self.all_contraception_states - {"not_using", "female_sterilization"})
assert set(switching_matrix_30plus.index) == (self.all_contraception_states - {"not_using"})
assert np.isclose(1.0, switching_matrix_30plus.sum(axis=0)).all()
return p_switch_from, switching_matrix_below30, switching_matrix_30plus
def contraception_stop():
"""Get the probability per month of a woman stopping use of contraceptive method."""
# Get data from read-in Excel sheets
p_stop_by_method = self.parameters['Discontinuation_ByMethod'].loc[0]
age_effect = 1.0 + self.parameters['Discontinuation_ByAge'].set_index('age')['r_discont_age'].rename_axis(
"age_years")
year_effect = time_age_trend_in_stopping()
# Probability of initiation by age for each method
p_stop = dict()
for year in year_effect.index:
p_stop_this_year = dict()
for a in age_effect.index:
p_stop_this_year[a] = p_stop_by_method * age_effect.at[a] * year_effect.at[year, a]
p_stop_this_year_df = pd.DataFrame.from_dict(p_stop_this_year, orient='index')
# Check correct format of age/method data-frame
assert set(p_stop_this_year_df.columns) == set(self.all_contraception_states - {'not_using'})
assert (p_stop_this_year_df.index == range(15, 50)).all()
assert (p_stop_this_year_df >= 0.0).all().all()
p_stop[year] = p_stop_this_year_df
return p_stop
def time_age_trend_in_initiation():
"""The age-specific effect of calendar year on the probability of starting use of contraceptive
(multiplicative effect). Values are chosen to induce a trend in age-specific fertility consistent with
the WPP estimates."""
_years = np.arange(2010, 2101)
_ages = np.arange(15, 50)
_init_over_time = np.exp(+0.05 * np.minimum(2020 - 2010, (_years - 2010))) * np.maximum(1.0, np.exp(
+0.01 * (_years - 2020)))
_init_over_time_modification_by_age = 1.0 / expand_to_age_years([1.0, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5], _ages)
_init = np.outer(_init_over_time, _init_over_time_modification_by_age)
return pd.DataFrame(index=_years, columns=_ages, data=_init)
def time_age_trend_in_stopping():
"""The age-specific effect of calendar year on the probability of discontinuing use of contraceptive
(multiplicative effect). Values are chosen to induce a trend in age-specific fertility consistent with
the WPP estimates."""
_years = np.arange(2010, 2101)
_ages = np.arange(15, 50)
_discont_over_time = np.exp(-0.05 * np.minimum(2020 - 2010, (_years - 2010))) * np.minimum(1.0, np.exp(
-0.01 * (_years - 2020)))
_discont_over_time_modification_by_age = expand_to_age_years([1.0, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5], _ages)
_discont = np.outer(_discont_over_time, _discont_over_time_modification_by_age)
return pd.DataFrame(index=_years, columns=_ages, data=_discont)
def contraception_initiation_after_birth():
"""Get the probability of a woman starting a contraceptive following giving birth. Avoid sterilization in
women below 30 years old."""
# Get data from read-in Excel sheets
p_start_after_birth = self.parameters['Initiation_AfterBirth'].loc[0]
return avoid_sterilization_below30(p_start_after_birth)
def scaling_factor_on_monthly_risk_of_pregnancy():
"""A scaling factor on the monthly risk of pregnancy, chosen to give the correct number of live-births
initially, given the initial pattern of contraceptive use."""
# first scaling factor is that worked out from the calibration script
scaling_factor_as_dict = dict(zip(
['15-19', '20-24', '25-29', '30-34', '35-39', '40-44', '45-49'],
self.parameters['scaling_factor_on_monthly_risk_of_pregnancy']
))
AGE_RANGE_LOOKUP = self.sim.modules['Demography'].AGE_RANGE_LOOKUP
_ages = range(15, 50)
return pd.Series(
index=_ages,
data=[scaling_factor_as_dict[AGE_RANGE_LOOKUP[_age_year]] for _age_year in _ages]
)
def pregnancy_no_contraception():
"""Get the probability per month of a woman becoming pregnant if she is not using any contraceptive method.
"""
# Get the probability of being pregnant if not HIV-positive
p_pregnancy_no_contraception_per_month_nohiv = self.parameters['Pregnancy_NotUsing_In_2010'] \
.set_index('age')['AnnualProb'].rename_axis('age_years').apply(convert_annual_prob_to_monthly_prob)
# Compute the probability of being pregnant if HIV-positive
p_pregnancy_no_contraception_per_month_hiv = (
p_pregnancy_no_contraception_per_month_nohiv *
self.parameters['Pregnancy_NotUsing_HIVeffect'].set_index('age_')['RR_pregnancy']
)
# Create combined dataframe
p_pregnancy_no_contraception_per_month = pd.concat({
'hv_inf_False': p_pregnancy_no_contraception_per_month_nohiv,
'hv_inf_True': p_pregnancy_no_contraception_per_month_hiv}, axis=1)
assert (p_pregnancy_no_contraception_per_month.index == range(15, 50)).all()
assert set(p_pregnancy_no_contraception_per_month.columns) == {'hv_inf_True', 'hv_inf_False'}
assert np.isclose(
self.parameters['Pregnancy_NotUsing_In_2010']['AnnualProb'].values,
1.0 - np.power(1.0 - p_pregnancy_no_contraception_per_month['hv_inf_False'], 12)
).all()
return p_pregnancy_no_contraception_per_month.mul(scaling_factor_on_monthly_risk_of_pregnancy(), axis=0)
def pregnancy_with_contraception():
"""Get the probability per month of a woman becoming pregnant if she is using a contraceptive method."""
p_pregnancy_by_method_per_month = self.parameters['Failure_ByMethod'].loc[0]
# Create rates that are age-specific (using self.parameters['rr_fail_under25'])
p_pregnancy_with_contraception_per_month = pd.DataFrame(
index=range(15, 50),
columns=sorted(self.all_contraception_states - {"not_using"})
)
p_pregnancy_with_contraception_per_month.loc[15, :] = p_pregnancy_by_method_per_month
p_pregnancy_with_contraception_per_month.ffill(inplace=True)
p_pregnancy_with_contraception_per_month.loc[
p_pregnancy_with_contraception_per_month.index < 25
] *= self.parameters['rr_fail_under25']
assert (p_pregnancy_with_contraception_per_month.index == range(15, 50)).all()
assert set(p_pregnancy_with_contraception_per_month.columns) == set(
self.all_contraception_states - {"not_using"})
assert (0.0 == p_pregnancy_with_contraception_per_month['female_sterilization']).all()
return p_pregnancy_with_contraception_per_month.mul(scaling_factor_on_monthly_risk_of_pregnancy(), axis=0)
processed_params['initial_method_use'] = initial_method_use()
processed_params['p_start_per_month'] = contraception_initiation()
processed_params['p_switch_from_per_month'], \
processed_params['p_switching_to_below30'], processed_params['p_switching_to_30plus'] =\
contraception_switch()
processed_params['p_stop_per_month'] = contraception_stop()
processed_params['p_start_after_birth_below30'], processed_params['p_start_after_birth_30plus'] =\
contraception_initiation_after_birth()
processed_params['p_pregnancy_no_contraception_per_month'] = pregnancy_no_contraception()
processed_params['p_pregnancy_with_contraception_per_month'] = pregnancy_with_contraception()
return processed_params
def update_params_for_interventions(self):
"""Updates process parameters to enable FP interventions."""
processed_params = self.processed_params
def contraception_initiation_with_interv(p_start_per_month_without_interv):
"""Increase the probabilities of a woman starting modern contraceptives due to Pop intervention being
applied."""
p_start_per_month_with_interv = {}
for year, age_method_df in p_start_per_month_without_interv.items():
if year >= self.sim.date.year:
p_start_per_month_with_interv[year] = age_method_df * self.parameters['Interventions_Pop'].loc[0]
return p_start_per_month_with_interv
def contraception_initiation_after_birth_with_interv(p_start_after_birth_without_interv):
"""Increase the probabilities of a woman starting modern contraceptives following giving birth due to PPFP
intervention being applied."""
# Exclude prob of 'not_using'
p_start_after_birth_with_interv = p_start_after_birth_without_interv.copy().drop('not_using')
# Apply PPFP intervention multipliers (ie increase probs of modern methods)
p_start_after_birth_with_interv = \
p_start_after_birth_with_interv.mul(self.parameters['Interventions_PPFP'].loc[0])
# Return reduced prob of 'not_using'
p_start_after_birth_with_interv = pd.Series((1.0 - p_start_after_birth_with_interv.sum()),
index=['not_using']).append(p_start_after_birth_with_interv)
return p_start_after_birth_with_interv
processed_params['p_start_per_month'] = \
contraception_initiation_with_interv(processed_params['p_start_per_month'])
processed_params['p_start_after_birth_below30'] = \
contraception_initiation_after_birth_with_interv(processed_params['p_start_after_birth_below30'])
processed_params['p_start_after_birth_30plus'] = \
contraception_initiation_after_birth_with_interv(processed_params['p_start_after_birth_30plus'])
return processed_params
def select_contraceptive_following_birth(self, mother_id, mother_age):
"""Initiation of mother's contraception after birth."""
# Allocate the woman to a contraceptive status
if mother_age < 30:
probs_below30 = self.processed_params['p_start_after_birth_below30']
new_contraceptive = self.rng.choice(probs_below30.index, p=probs_below30.values)
else:
probs_30plus = self.processed_params['p_start_after_birth_30plus']
new_contraceptive = self.rng.choice(probs_30plus.index, p=probs_30plus.values)
# Do the change in contraceptive
self.schedule_batch_of_contraceptive_changes(ids=[mother_id], old=['not_using'], new=[new_contraceptive])
def get_item_code_for_each_contraceptive(self):
"""Get the item_code for each contraceptive and for contraceptive initiation."""
# TODO: update with optional items (currently all considered essential)
get_items_from_pkg = self.sim.modules['HealthSystem'].get_item_codes_from_package_name
_cons_codes = dict()
# items for each method that requires an HSI to switch to
_cons_codes['pill'] = get_items_from_pkg('Pill')
_cons_codes['male_condom'] = get_items_from_pkg('Male condom')
_cons_codes['other_modern'] = get_items_from_pkg('Female Condom')
# NB. The consumable female condom is used for the contraceptive state of "other_modern method"
_cons_codes['IUD'] = get_items_from_pkg('IUD')
_cons_codes['injections'] = get_items_from_pkg('Injectable')
_cons_codes['implant'] = get_items_from_pkg('Implant')
_cons_codes['female_sterilization'] = get_items_from_pkg('Female sterilization')
assert set(_cons_codes.keys()) == set(self.states_that_may_require_HSI_to_switch_to)
# items used when initiating a modern reliable method after not using or switching from non-reliable method
_cons_codes['co_initiation'] = get_items_from_pkg('Contraception initiation')
return _cons_codes
def schedule_batch_of_contraceptive_changes(self, ids, old, new):
"""Enact the change in contraception, either through editing properties instantaneously or by scheduling HSI.
ids: pd.Index of the woman for whom the contraceptive state is changing
old: iterable giving the corresponding contraceptive state being switched from
new: iterable giving the corresponding contraceptive state being switched to
It is assumed that even with the option `self.use_healthsystem=True` that switches to certain methods do not
require the use of HSI (these are not in `states_that_may_require_HSI_to_switch_to`)."""
df = self.sim.population.props
date_today = self.sim.date
days_between_appts = self.parameters['days_between_appts_for_maintenance']
date_of_last_appt = df.loc[ids, "co_date_of_last_fp_appt"].to_dict()
states_to_maintain_on = sorted(self.states_that_may_require_HSI_to_maintain_on)
for _woman_id, _old, _new in zip(ids, old, new):
if (_new == 'female_sterilization') and (df.loc[_woman_id, 'age_years'] < 30):
self._women_ids_sterilized_below30.add(_woman_id)
# Does this change require an HSI?
is_a_switch = _old != _new
reqs_appt = _new in self.states_that_may_require_HSI_to_switch_to if is_a_switch \
else _new in self.states_that_may_require_HSI_to_maintain_on
if (not is_a_switch) & reqs_appt:
due_appt = (pd.isnull(date_of_last_appt[_woman_id]) or
(date_today - date_of_last_appt[_woman_id]).days >=
days_between_appts[states_to_maintain_on.index(_old)]
)
do_appt = self.use_healthsystem and reqs_appt and (is_a_switch or due_appt)
# If the new method requires an HSI to be implemented, schedule the HSI:
if do_appt:
# If this is a change, or its maintenance and time for an appointment, schedule an appointment
self.sim.modules['HealthSystem'].schedule_hsi_event(
hsi_event=HSI_Contraception_FamilyPlanningAppt(
person_id=_woman_id,
module=self,
new_contraceptive=_new
),
# select start_date for 0 max day delay; start_date or later for >=1 max day delay:
topen=random_date(
self.sim.date,
self.sim.date + pd.DateOffset(
days=self.parameters[
'max_days_delay_between_decision_to_change_method_and_hsi_scheduled'] + 1),
self.rng2),
tclose=None,
priority=1
)
else:
# Otherwise, implement the change immediately:
if _old != _new:
self.do_and_log_individual_contraception_change(woman_id=_woman_id, old=_old, new=_new)
else:
pass # No need to do anything if the old is the same as the new and no HSI needed.
def do_and_log_individual_contraception_change(self, woman_id: int, old, new):
"""Implement and then log a start / stop / switch of contraception. """
assert old in self.all_contraception_states
assert new in self.all_contraception_states
df = self.sim.population.props
# Do the change
df.at[woman_id, "co_contraception"] = new
# Log the change
logger.info(key='contraception_change',
data={
'woman_id': woman_id,
'age_years': df.at[woman_id, 'age_years'],
'switch_from': old,
'switch_to': new,
},
description='All changes in contraception use'
)
def schedule_births_for_first_9_months(self):
"""Schedule births to occur during the first 9 months of the simulation. This is necessary because at initiation
no women are pregnant, so the first births generated endogenously (through pregnancy -> gestation -> labour)
occur after 9 months of simulation time. This method examines age-specific fertility rate data and causes there
to be the appropriate number of births, scattered uniformly over the first 9 months of the simulation. These are
"direct live births" that are not subjected to any of the processes (e.g. risk of loss of pregnancy, or risk of
death to mother) represented in the `PregnancySupervisor`, `CareOfWomenDuringPregnancy` or `Labour`.
When initialising population ensured person_id=0 is a man, so can safely exclude person_id=0 from choice of
direct birth mothers without loss of generality."""
risk_of_birth = get_medium_variant_asfr_from_wpp_resourcefile(
dat=self.parameters['age_specific_fertility_rates'], months_exposure=9)
df = self.sim.population.props
# don't use person_id=0 for direct birth mother
prob_birth = df.loc[(df.index != 0) & (df.sex == 'F') & df.is_alive & ~df.is_pregnant]['age_range'].map(
risk_of_birth[self.sim.date.year]).fillna(0)
# determine which women will get pregnant
give_birth_women_ids = prob_birth.index[
(self.rng.random_sample(size=len(prob_birth)) < prob_birth)
]
# schedule births, passing negative of mother's id:
for _id in give_birth_women_ids:
self.sim.schedule_event(DirectBirth(person_id=_id * (-1), module=self),
random_date(self.sim.date, self.sim.date + pd.DateOffset(months=9), self.rng)
)
def on_simulation_end(self):
"""Do tasks at the end of the simulation: Raise warning and enter to log about women_ids who are sterilized
when under 30 years old."""
if self._women_ids_sterilized_below30:
warnings.warn(UserWarning(f"IDs of women for whom sterilization was initiated when they were under 30:/n"
f"{self._women_ids_sterilized_below30}"))
logger.info(
key="women_ids_sterilized_below30",
data={"ids": self._women_ids_sterilized_below30}
)
class DirectBirth(Event, IndividualScopeEventMixin):
"""Do birth, with the mother_id set to person_id*(-1) to reflect that this was a `DirectBirth`."""
def __init__(self, module, person_id):
super().__init__(module, person_id=person_id)
def apply(self, person_id):
assert person_id < 0 # check that mother is correctly logged as direct birth mother
self.sim.do_birth(person_id) # use actual id for mother
class ContraceptionPoll(RegularEvent, PopulationScopeEventMixin):
"""The regular poll (monthly) for the Contraceptive Module:
* Determines contraceptive start / stops / switches
* Determines the onset of pregnancy
"""
def __init__(self, module, run_do_pregnancy=True, run_update_contraceptive=True):
super().__init__(module, frequency=DateOffset(months=1))
self.age_low = 15
self.age_high = 49
self.run_do_pregnancy = run_do_pregnancy # (Provided for testing only)
self.run_update_contraceptive = run_update_contraceptive # (Provided for testing only)
def apply(self, population):
"""Determine who will become pregnant and update contraceptive method."""
# Determine who will become pregnant, given current contraceptive method
if self.run_do_pregnancy:
self.update_pregnancy()
# Update contraception method
if self.run_update_contraceptive:
self.update_contraceptive()
def update_contraceptive(self):
""" Determine women that will start, stop or switch contraceptive method."""
df = self.sim.population.props
possible_co_users = ((df.sex == 'F') &
df.is_alive &
df.age_years.between(self.age_low, self.age_high) &
~df.is_pregnant)
currently_using_co = df.index[possible_co_users &
~df.co_contraception.isin(['not_using', 'female_sterilization'])]
currently_not_using_co = df.index[possible_co_users & (df.co_contraception == 'not_using')]
# initiating: not using -> using
self.initiate(currently_not_using_co)
# continue/discontinue/switch: using --> using/not using
self.discontinue_switch_or_continue(currently_using_co)
# put everyone older than `age_high` onto not_using:
df.loc[
(df.sex == 'F') &
df.is_alive &
(df.age_years > self.age_high) &
(df.co_contraception != 'not_using'),
'co_contraception'] = 'not_using'
def initiate(self, individuals_not_using: pd.Index):
"""Check all females not using contraception to determine if contraception starts
(i.e. category change from 'not_using' to something else).
"""
# Exit if there are no individuals currently not using a contraceptive:
if not len(individuals_not_using):
return
df = self.sim.population.props
pp = self.module.processed_params
rng = self.module.rng
# Get probability of each individual starting on each contraceptive
probs = df.loc[individuals_not_using, ['age_years']].merge(
pp['p_start_per_month'][self.sim.date.year],
how='left',
left_on='age_years',
right_index=True
).drop(columns=['age_years'])
# Determine if individual will start contraceptive
will_initiate = sample_outcome(probs=probs, rng=rng)
# Do the contraceptive change
if len(will_initiate) > 0:
self.module.schedule_batch_of_contraceptive_changes(
ids=list(will_initiate),
old=['not_using'] * len(will_initiate),
new=list(will_initiate.values())
)
def discontinue_switch_or_continue(self, individuals_using: pd.Index):
"""Check all females currently using contraception to determine if they discontinue it, switch to a different
one, or keep using the same one."""
# Exit if there are no individuals currently using a contraceptive:
if not len(individuals_using):
return
df = self.sim.population.props
pp = self.module.processed_params
rng = self.module.rng
# Get the probability of discontinuation for each individual (depends on age and current method)
prob = df.loc[individuals_using, ['age_years', 'co_contraception']].apply(
lambda row: pp['p_stop_per_month'][self.sim.date.year].at[row.age_years, row.co_contraception],
axis=1
)
# Determine if each individual will discontinue
will_stop_idx = prob.index[prob > rng.rand(len(prob))]
# Do the contraceptive change
if len(will_stop_idx) > 0:
self.module.schedule_batch_of_contraceptive_changes(
ids=will_stop_idx,
old=df.loc[will_stop_idx, 'co_contraception'].values,
new=['not_using'] * len(will_stop_idx)
)
# 2) -- Switches and Continuations for those who do not Discontinue:
individuals_eligible_for_continue_or_switch = individuals_using.drop(will_stop_idx)
# Get the probability of switching contraceptive for all those currently using
switch_prob = df.loc[individuals_eligible_for_continue_or_switch, 'co_contraception'].map(
pp['p_switch_from_per_month']
)
# Randomly select who will switch contraceptive and who will remain on their current contraceptive
will_switch = switch_prob > rng.random_sample(size=len(individuals_eligible_for_continue_or_switch))
switch_idx = individuals_eligible_for_continue_or_switch[will_switch]
switch_idx_below30 = switch_idx[df.loc[switch_idx, 'age_years'] < 30]
switch_idx_30plus = switch_idx.drop(switch_idx_below30)
continue_idx = individuals_eligible_for_continue_or_switch[~will_switch]
# For that do switch, select the new contraceptive using switching matrix
new_co_below30 = transition_states(
df.loc[switch_idx_below30, 'co_contraception'], pp['p_switching_to_below30'], rng
)
new_co_30plus = transition_states(
df.loc[switch_idx_30plus, 'co_contraception'], pp['p_switching_to_30plus'], rng
)
new_co = pd.concat([new_co_below30, new_co_30plus])
# Do the contraceptive change for those switching
if len(new_co) > 0:
self.module.schedule_batch_of_contraceptive_changes(
ids=new_co.index,
old=df.loc[new_co.index, 'co_contraception'].values,
new=new_co.values
)
# Do the contraceptive "change" for those not switching (this is so that an HSI may be logged and if the HSI
# cannot occur the person discontinues use of the method).
if len(continue_idx) > 0:
current_contraception = df.loc[continue_idx, 'co_contraception'].values
self.module.schedule_batch_of_contraceptive_changes(
ids=continue_idx,
old=current_contraception,
new=current_contraception
)
def update_pregnancy(self):
"""Determine who will become pregnant"""
# Determine pregnancy for those on a contraceptive ("unintentional pregnancy")
self.pregnancy_for_those_on_contraceptive()
# Determine pregnancy for those not on contraceptive ("intentional pregnancy")
self.pregnancy_for_those_not_on_contraceptive()
def pregnancy_for_those_on_contraceptive(self):
"""Look across all women who are using a contraception method to determine if they become pregnant (i.e., the
method fails)."""
df = self.module.sim.population.props
pp = self.module.processed_params
rng = self.module.rng
prob_failure_per_month = pp['p_pregnancy_with_contraception_per_month']
# Get the women who are using a contraceptive that may fail and who may become pregnant (i.e., women who
# are not in labour, have been pregnant in the last month, have previously had a hysterectomy, can get
# pregnant.)
possible_to_fail = (
df.is_alive
& (df.sex == 'F')
& ~df.is_pregnant
& df.age_years.between(self.age_low, self.age_high)
& ~df.co_contraception.isin(['not_using', 'female_sterilization'])
& ~df.la_currently_in_labour
& ~df.la_has_had_hysterectomy
& ~df.la_is_postpartum
& ~df.ps_ectopic_pregnancy.isin(['not_ruptured', 'ruptured'])
)
if possible_to_fail.sum():
# Get probability of method failure for each individual
prob_of_failure = df.loc[possible_to_fail, ['age_years', 'co_contraception']].apply(
lambda row: prob_failure_per_month.at[row.age_years, row.co_contraception],
axis=1
)
# Determine if there will be a contraceptive failure for each individual
idx_failure = prob_of_failure.index[prob_of_failure > rng.random_sample(size=len(prob_of_failure))]
# Effect these women to be pregnant
self.set_new_pregnancy(women_id=idx_failure)