-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmalaria.py
1439 lines (1137 loc) · 58.3 KB
/
malaria.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
"""
this is the malaria module which assigns malaria infections to the population: asymptomatic, clinical and severe
it also holds the hsi events pertaining to malaria testing and treatment
including the malaria RDT using DxTest
"""
from pathlib import Path
import pandas as pd
from tlo import DateOffset, Module, Parameter, Property, Types, logging
from tlo.events import Event, IndividualScopeEventMixin, PopulationScopeEventMixin, RegularEvent
from tlo.methods import Metadata, demography
from tlo.methods.causes import Cause
from tlo.methods.dxmanager import DxTest
from tlo.methods.healthsystem import HSI_Event
from tlo.methods.symptommanager import Symptom
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class Malaria(Module):
def __init__(self, name=None, resourcefilepath=None):
"""Create instance of Malaria module
:param name: Name of this module (optional, defaults to name of class)
:param resourcefilepath: Path to the TLOmodel `resources` directory
"""
super().__init__(name)
self.resourcefilepath = Path(resourcefilepath)
# cleaned coverage values for IRS and ITN (populated in `read_parameters`)
self.itn_irs = None
self.all_inc = None
INIT_DEPENDENCIES = {
'Contraception', 'Demography', 'HealthSystem', 'SymptomManager'
}
METADATA = {
Metadata.DISEASE_MODULE,
Metadata.USES_HEALTHSYSTEM,
Metadata.USES_HEALTHBURDEN,
Metadata.USES_SYMPTOMMANAGER
}
# Declare Causes of Death
CAUSES_OF_DEATH = {
'Malaria': Cause(gbd_causes='Malaria', label='Malaria'),
}
# Declare Causes of Disability
CAUSES_OF_DISABILITY = {
'Malaria': Cause(gbd_causes='Malaria', label='Malaria')
}
PARAMETERS = {
"mal_inc": Parameter(Types.REAL, "monthly incidence of malaria in all ages"),
"interv": Parameter(Types.REAL, "data frame of intervention coverage by year"),
"clin_inc": Parameter(
Types.REAL,
"data frame of clinical incidence by age, district, intervention coverage",
),
"inf_inc": Parameter(
Types.REAL,
"data frame of infection incidence by age, district, intervention coverage",
),
"sev_inc": Parameter(
Types.REAL,
"data frame of severe case incidence by age, district, intervention coverage",
),
"itn_district": Parameter(
Types.REAL, "data frame of ITN usage rates by district"
),
"irs_district": Parameter(
Types.REAL, "data frame of IRS usage rates by district"
),
"sev_symp_prob": Parameter(
Types.REAL, "probabilities of each symptom for severe malaria cases"
),
# "p_infection": Parameter(
# Types.REAL, "Probability that an uninfected individual becomes infected"
# ),
"sensitivity_rdt": Parameter(Types.REAL, "Sensitivity of rdt"),
"cfr": Parameter(Types.REAL, "case-fatality rate for severe malaria"),
"dur_asym": Parameter(Types.REAL, "duration (days) of asymptomatic malaria"),
"dur_clin": Parameter(
Types.REAL, "duration (days) of clinical symptoms of malaria"
),
"dur_clin_para": Parameter(
Types.REAL, "duration (days) of parasitaemia for clinical malaria cases"
),
"rr_hiv": Parameter(
Types.REAL, "relative risk of clinical malaria if hiv-positive"
),
"treatment_adjustment": Parameter(
Types.REAL, "probability of death from severe malaria if on treatment"
),
"p_sev_anaemia_preg": Parameter(
Types.REAL,
"probability of severe anaemia in pregnant women with clinical malaria",
),
"itn_proj": Parameter(
Types.REAL, "coverage of ITN for projections 2020 onwards"
),
"mortality_adjust": Parameter(
Types.REAL, "adjustment of case-fatality rate to match WHO/MAP"
),
"data_end": Parameter(
Types.REAL, "final year of ICL malaria model outputs, after 2018 = projections"
),
# "prob_sev": Parameter(
# Types.REAL, "probability of infected case becoming severe"
# ),
"irs_rates_boundary": Parameter(
Types.REAL, "threshold for indoor residual spraying coverage"
),
"irs_rates_upper": Parameter(
Types.REAL, "indoor residual spraying high coverage"
),
"irs_rates_lower": Parameter(
Types.REAL, "indoor residual spraying low coverage"
),
"testing_adj": Parameter(
Types.REAL, "adjusted testing rates to match rdt/tx levels"
),
"itn": Parameter(
Types.REAL, "projected future itn coverage"
),
}
PROPERTIES = {
"ma_is_infected": Property(Types.BOOL, "Current status of malaria"),
"ma_date_infected": Property(Types.DATE, "Date of latest infection"),
"ma_date_symptoms": Property(
Types.DATE, "Date of symptom start for clinical infection"
),
"ma_date_death": Property(Types.DATE, "Date of scheduled death due to malaria"),
"ma_tx": Property(Types.BOOL, "Currently on anti-malarial treatment"),
"ma_date_tx": Property(
Types.DATE, "Date treatment started for most recent malaria episode"
),
"ma_inf_type": Property(
Types.CATEGORICAL,
"specific symptoms with malaria infection",
categories=["none", "asym", "clinical", "severe"],
),
"ma_age_edited": Property(
Types.REAL, "age values redefined to match with malaria data"
),
"ma_clinical_counter": Property(
Types.INT, "annual counter for malaria clinical episodes"
),
"ma_tx_counter": Property(
Types.INT, "annual counter for malaria treatment episodes"
),
"ma_clinical_preg_counter": Property(
Types.INT, "annual counter for malaria clinical episodes in pregnant women"
),
"ma_iptp": Property(Types.BOOL, "if woman has IPTp in current pregnancy"),
}
# TODO reset ma_iptp after delivery
def read_parameters(self, data_folder):
workbook = pd.read_excel(self.resourcefilepath / "ResourceFile_malaria.xlsx", sheet_name=None)
self.load_parameters_from_dataframe(workbook["parameters"])
p = self.parameters
# baseline characteristics
p["mal_inc"] = workbook["incidence"]
p["interv"] = workbook["interventions"]
p["itn_district"] = workbook["MAP_ITNrates"]
p["irs_district"] = workbook["MAP_IRSrates"]
p["sev_symp_prob"] = workbook["severe_symptoms"]
p["inf_inc"] = pd.read_csv(self.resourcefilepath / "ResourceFile_malaria_InfInc_expanded.csv")
p["clin_inc"] = pd.read_csv(self.resourcefilepath / "ResourceFile_malaria_ClinInc_expanded.csv")
p["sev_inc"] = pd.read_csv(self.resourcefilepath / "ResourceFile_malaria_SevInc_expanded.csv")
# check itn projected values are <=0.7 and rounded to 1dp for matching to incidence tables
p["itn"] = round(p["itn"], 1)
assert (p["itn"] <= 0.7)
# ===============================================================================
# single dataframe for itn and irs district/year data; set index for fast lookup
# ===============================================================================
itn_curr = p["itn_district"]
itn_curr.rename(columns={"itn_rates": "itn_rate"}, inplace=True)
itn_curr["itn_rate"] = itn_curr["itn_rate"].round(decimals=1)
# maximum itn is 0.7; see comment https://github.com/UCL/TLOmodel/pull/165#issuecomment-699625290
itn_curr.loc[itn_curr.itn_rate > 0.7, "itn_rate"] = 0.7
itn_curr = itn_curr.set_index(["District", "Year"])
irs_curr = p["irs_district"]
irs_curr.rename(columns={"irs_rates": "irs_rate"}, inplace=True)
irs_curr.drop(["Region"], axis=1, inplace=True)
irs_curr["irs_rate"] = irs_curr["irs_rate"].round(decimals=1)
irs_curr.loc[irs_curr.irs_rate > p["irs_rates_boundary"], "irs_rate"] = p["irs_rates_upper"]
irs_curr.loc[irs_curr.irs_rate <= p["irs_rates_boundary"], "irs_rate"] = p["irs_rates_lower"]
irs_curr = irs_curr.set_index(["District", "Year"])
itn_irs = pd.concat([itn_curr, irs_curr], axis=1)
# Subsitute District Num for District Name
mapper_district_name_to_num = \
{v: k for k, v in self.sim.modules['Demography'].parameters['district_num_to_district_name'].items()}
self.itn_irs = itn_irs.reset_index().assign(
District_Num=lambda x: x['District'].map(mapper_district_name_to_num)
).drop(columns=['District']).set_index(['District_Num', 'Year'])
# ===============================================================================
# put the all incidence data into single table with month/admin/llin/irs index
# ===============================================================================
inf_inc = p["inf_inc"].set_index(["month", "admin", "llin", "irs", "age"])
inf_inc = inf_inc.loc[:, ["monthly_prob_inf"]]
clin_inc = p["clin_inc"].set_index(["month", "admin", "llin", "irs", "age"])
clin_inc = clin_inc.loc[:, ["monthly_prob_clin"]]
sev_inc = p["sev_inc"].set_index(["month", "admin", "llin", "irs", "age"])
sev_inc = sev_inc.loc[:, ["monthly_prob_sev"]]
all_inc = pd.concat([inf_inc, clin_inc, sev_inc], axis=1)
# we don't want age to be part of index
all_inc = all_inc.reset_index()
all_inc['district_num'] = all_inc['admin'].map(mapper_district_name_to_num)
assert not all_inc['district_num'].isna().any()
self.all_inc = all_inc.drop(columns=['admin']).set_index(["month", "district_num", "llin", "irs"])
# get the DALY weight that this module will use from the weight database
if "HealthBurden" in self.sim.modules:
p["daly_wt_clinical"] = self.sim.modules["HealthBurden"].get_daly_weight(218)
p["daly_wt_severe"] = self.sim.modules["HealthBurden"].get_daly_weight(213)
# ----------------------------------- DECLARE THE SYMPTOMS -------------------------------------------
self.sim.modules['SymptomManager'].register_symptom(
Symptom("jaundice"), # nb. will cause care seeking as much as a typical symptom
Symptom("severe_anaemia"), # nb. will cause care seeking as much as a typical symptom
Symptom("acidosis", emergency_in_children=True, emergency_in_adults=True),
Symptom("coma_convulsions", emergency_in_children=True, emergency_in_adults=True),
Symptom("renal_failure", emergency_in_children=True, emergency_in_adults=True),
Symptom("shock", emergency_in_children=True, emergency_in_adults=True)
)
def initialise_population(self, population):
df = population.props
# ----------------------------------- INITIALISE THE POPULATION-----------------------------------
# Set default for properties
df.loc[df.is_alive, "ma_is_infected"] = False
df.loc[df.is_alive, "ma_date_infected"] = pd.NaT
df.loc[df.is_alive, "ma_date_symptoms"] = pd.NaT
df.loc[df.is_alive, "ma_date_death"] = pd.NaT
df.loc[df.is_alive, "ma_tx"] = False
df.loc[df.is_alive, "ma_date_tx"] = pd.NaT
df.loc[df.is_alive, "ma_inf_type"] = "none"
df.loc[df.is_alive, "ma_age_edited"] = 0.0
df.loc[df.is_alive, "ma_clinical_counter"] = 0
df.loc[df.is_alive, "ma_tx_counter"] = 0
df.loc[df.is_alive, "ma_clinical_preg_counter"] = 0
df.loc[df.is_alive, "ma_iptp"] = False
self.malaria_poll2(population)
def malaria_poll2(self, population):
df = population.props
p = self.parameters
now = self.sim.date
rng = self.rng
# ----------------------------------- DISTRICT INTERVENTION COVERAGE -----------------------------------
# fix values for 2018 onwards
current_year = min(now.year, p["data_end"])
# get itn_irs rows for current year; slice multiindex for all districts & current_year
itn_irs_curr = self.itn_irs.loc[pd.IndexSlice[:, current_year], :]
itn_irs_curr = itn_irs_curr.reset_index().drop("Year", axis=1) # we don"t use the year column
itn_irs_curr.insert(0, "month", now.month) # add current month for the incidence index lookup
# replace itn coverage with projected coverage levels from 2019 onwards
if now.year > p["data_end"]:
itn_irs_curr['itn_rate'] = self.itn
month_districtnum_itn_irs_lookup = [
tuple(r) for r in itn_irs_curr.values] # every row is a key in incidence table
# ----------------------------------- DISTRICT INCIDENCE ESTIMATES -----------------------------------
# get all corresponding rows from the incidence table; drop unneeded column; set new index
curr_inc = self.all_inc.loc[month_districtnum_itn_irs_lookup]
curr_inc = curr_inc.reset_index().drop(["month", "llin", "irs"], axis=1).set_index(["district_num", "age"])
# ----------------------------------- DISTRICT NEW INFECTIONS -----------------------------------
def _draw_incidence_for(_col, _where):
"""a helper function to perform random draw for selected individuals on column of probabilities"""
# create an index from the individuals to lookup entries in the current incidence table
district_age_lookup = df[_where].set_index(["district_num_of_residence", "ma_age_edited"]).index
# get the monthly incidence probabilities for these individuals
monthly_prob = curr_inc.loc[district_age_lookup, _col]
# update the index so it"s the same as the original population dataframe for these individuals
monthly_prob = monthly_prob.set_axis(df.index[_where], inplace=False)
# select individuals for infection
random_draw = rng.random_sample(_where.sum()) < monthly_prob
selected = _where & random_draw
return selected
# we don't have incidence data for over 80s
alive = df.is_alive & (df.age_years < 80)
alive_over_one = alive & (df.age_exact_years >= 1)
df.loc[alive & df.age_exact_years.between(0, 0.5), "ma_age_edited"] = 0.0
df.loc[alive & df.age_exact_years.between(0.5, 1), "ma_age_edited"] = 0.5
df.loc[alive_over_one, "ma_age_edited"] = df.loc[alive_over_one, "age_years"].astype(float)
alive_uninfected = alive & ~df.ma_is_infected
now_infected = _draw_incidence_for("monthly_prob_inf", alive_uninfected)
df.loc[now_infected, "ma_is_infected"] = True
df.loc[now_infected, "ma_date_infected"] = now # TODO: scatter dates across month
df.loc[now_infected, "ma_inf_type"] = "asym"
alive_infected = alive & df.ma_is_infected
alive_infected_asym = alive_infected & (df.ma_inf_type == "asym")
now_clinical = _draw_incidence_for("monthly_prob_clin", alive_infected_asym)
df.loc[now_clinical, "ma_inf_type"] = "clinical"
df.loc[now_clinical, "ma_date_symptoms"] = now
df.loc[now_clinical, "ma_clinical_counter"] += 1
alive_infected_clinical = alive_infected & (df.ma_inf_type == "clinical")
now_severe = _draw_incidence_for("monthly_prob_sev", alive_infected_clinical)
df.loc[now_severe, "ma_inf_type"] = "severe"
df.loc[now_severe, "ma_date_symptoms"] = now
alive_now_infected_pregnant = alive_infected_clinical & (df.ma_date_infected == now) & df.is_pregnant
df.loc[alive_now_infected_pregnant, "ma_clinical_preg_counter"] += 1
# ----------------------------------- CLINICAL MALARIA SYMPTOMS -----------------------------------
# clinical - can't use now_clinical, because some clinical may have become severe
clin = df.index[df.is_alive & (df.ma_inf_type == "clinical") & (df.ma_date_symptoms == now)]
# update clinical symptoms for all new clinical infections
self.clinical_symptoms(df, clin)
# ----------------------------------- SEVERE MALARIA SYMPTOMS -----------------------------------
# SEVERE CASES
severe = df.is_alive & (df.ma_inf_type == "severe") & (df.ma_date_symptoms == now)
children = severe & (df.age_exact_years < 5)
adult = severe & (df.age_exact_years >= 5)
# update symptoms for all new severe infections
self.severe_symptoms(df, df.index[children], child=True)
self.severe_symptoms(df, df.index[adult], child=False)
# ----------------------------------- SCHEDULED DEATHS -----------------------------------
# schedule deaths within the next week
# Assign time of infections across the month
# the cfr applies to all severe malaria
random_draw = rng.random_sample(size=severe.sum())
death = df.index[severe][random_draw < (p["cfr"] * p["mortality_adjust"])]
for person in death:
logger.debug(key='message',
data=f'MalariaEvent: scheduling malaria death for person {person}')
random_date = rng.randint(low=0, high=7)
random_days = pd.to_timedelta(random_date, unit="d")
death_event = MalariaDeathEvent(
self, individual_id=person, cause="Malaria"
) # make that death event
self.sim.schedule_event(
death_event, self.sim.date + random_days
) # schedule the death
def initialise_simulation(self, sim):
sim.schedule_event(MalariaPollingEventDistrict(self), sim.date + DateOffset(months=1))
sim.schedule_event(MalariaScheduleTesting(self), sim.date + DateOffset(days=1))
sim.schedule_event(MalariaIPTp(self), sim.date + DateOffset(days=30.5))
sim.schedule_event(MalariaCureEvent(self), sim.date + DateOffset(days=5))
sim.schedule_event(MalariaParasiteClearanceEvent(self), sim.date + DateOffset(days=30.5))
sim.schedule_event(MalariaResetCounterEvent(self), sim.date + DateOffset(days=365)) # 01 jan each year
# add an event to log to screen - 31st Dec each year
sim.schedule_event(MalariaLoggingEvent(self), sim.date + DateOffset(days=364))
sim.schedule_event(MalariaTxLoggingEvent(self), sim.date + DateOffset(days=364))
sim.schedule_event(MalariaPrevDistrictLoggingEvent(self), sim.date + DateOffset(days=30.5))
# ----------------------------------- DIAGNOSTIC TESTS -----------------------------------
# Create the diagnostic test representing the use of RDT for malaria diagnosis
# and registers it with the Diagnostic Test Manager
consumables = self.sim.modules["HealthSystem"].parameters["Consumables"]
# need to convert this from int64 to int for the dx_manager using tolist()
item_code1 = pd.unique(
consumables.loc[
consumables["Items"] == "Malaria test kit (RDT)",
"Item_Code",
]
)[0].tolist()
self.sim.modules['HealthSystem'].dx_manager.register_dx_test(
malaria_rdt=DxTest(
property='ma_is_infected',
cons_req_as_item_code=item_code1,
sensitivity=self.parameters['sensitivity_rdt'],
)
)
def on_birth(self, mother_id, child_id):
df = self.sim.population.props
df.at[child_id, "ma_is_infected"] = False
df.at[child_id, "ma_date_infected"] = pd.NaT
df.at[child_id, "ma_date_symptoms"] = pd.NaT
df.at[child_id, "ma_date_death"] = pd.NaT
df.at[child_id, "ma_tx"] = False
df.at[child_id, "ma_date_tx"] = pd.NaT
df.at[child_id, "ma_inf_type"] = "none"
df.at[child_id, "ma_age_edited"] = 0.0
df.at[child_id, "ma_clinical_counter"] = 0
df.at[child_id, "ma_clinical_preg_counter"] = 0
df.at[child_id, "ma_tx_counter"] = 0
df.at[child_id, "ma_iptp"] = False
def on_hsi_alert(self, person_id, treatment_id):
"""This is called whenever there is an HSI event commissioned by one of the other disease modules.
"""
logger.debug(key='message',
data=f'This is Malaria, being alerted about a health system interaction for person'
f'{person_id} and treatment {treatment_id}')
def report_daly_values(self):
# This must send back a pd.Series or pd.DataFrame that reports on the average daly-weights that have been
# experienced by persons in the previous month. Only rows for alive-persons must be returned.
# The names of the series of columns is taken to be the label of the cause of this disability.
# It will be recorded by the healthburden module as <ModuleName>_<Cause>.
logger.debug(key='message',
data='This is malaria reporting my health values')
df = self.sim.population.props # shortcut to population properties dataframe
p = self.parameters
health_values = df.loc[df.is_alive, "ma_inf_type"].map(
{
"none": 0,
"asym": 0,
"clinical": p["daly_wt_clinical"],
"severe": p["daly_wt_severe"],
}
)
health_values.name = "Malaria" # label the cause of this disability
return health_values.loc[df.is_alive] # returns the series
def clinical_symptoms(self, population, clinical_index):
"""assign clinical symptoms to new clinical malaria cases and schedule symptom resolution
:param population:
:param clinical_index:
"""
df = population
p = self.parameters
rng = self.rng
now = self.sim.date
# TODO this schedules symptom onset on 1st of each month for everybody
df.loc[clinical_index, "ma_date_symptoms"] = now
symptom_list = {"fever", "headache", "vomiting", "stomachache"}
for symptom in symptom_list:
# this also schedules symptom resolution in 5 days
self.sim.modules["SymptomManager"].change_symptom(
person_id=list(clinical_index),
symptom_string=symptom,
add_or_remove="+",
disease_module=self,
duration_in_days=p["dur_clin"],
)
# additional risk of severe anaemia in pregnancy
pregnant_infected = df.is_alive & (df.ma_inf_type == "clinical") & (df.ma_date_infected == now) & df.is_pregnant
if pregnant_infected.sum() > 0:
random_draw = rng.random_sample(size=pregnant_infected.sum())
preg_infected = df.index[pregnant_infected][random_draw < p["p_sev_anaemia_preg"]]
if len(preg_infected) > 0:
self.sim.modules["SymptomManager"].change_symptom(
person_id=list(preg_infected),
symptom_string="severe_anaemia",
add_or_remove="+",
disease_module=self,
duration_in_days=None,
)
def severe_symptoms(self, population, severe_index, child=False):
"""assign clinical symptoms to new severe malaria cases. Symptoms can only be resolved by treatment
handles both adult and child (using the child parameter) symptoms
:param population: the population dataframe
:param severe_index: the indices of new clinical cases
:param child: to apply severe symptoms to children (otherwise applied to adults)
"""
df = population
p = self.parameters
rng = self.rng
now = self.sim.date
df.loc[severe_index, "ma_date_symptoms"] = now
# general symptoms - applied to all
symptom_list = {"fever", "headache", "vomiting", "stomachache"}
for symptom in symptom_list:
self.sim.modules["SymptomManager"].change_symptom(
person_id=list(severe_index),
symptom_string=symptom,
add_or_remove="+",
disease_module=self,
duration_in_days=None,
)
# symptoms specific to severe cases
# get range of probabilities of each symptom for severe cases for children and adults
range_symp = p["sev_symp_prob"]
if child:
range_symp = range_symp.loc[range_symp.age_group == "0_5"]
else:
range_symp = range_symp.loc[range_symp.age_group == "5_60"]
symptom_list_severe = list(range_symp.symptom)
# assign symptoms
for person in severe_index:
for symptom in symptom_list_severe:
# random sample whether child will have symptom
symptom_probability = rng.uniform(
low=range_symp.loc[range_symp.symptom == symptom, "prop_lower"],
high=range_symp.loc[range_symp.symptom == symptom, "prop_upper"],
size=1
)[0]
if self.rng.random_sample(size=1) < symptom_probability:
# schedule symptom onset
self.sim.modules["SymptomManager"].change_symptom(
person_id=person,
symptom_string=symptom,
add_or_remove="+",
disease_module=self,
duration_in_days=None,
)
class MalariaPollingEventDistrict(RegularEvent, PopulationScopeEventMixin):
def __init__(self, module):
super().__init__(module, frequency=DateOffset(months=1))
def apply(self, population):
logger.debug(key='message', data='MalariaEvent: tracking the disease progression of the population')
self.module.malaria_poll2(population)
class MalariaScheduleTesting(RegularEvent, PopulationScopeEventMixin):
""" additional malaria testing happening outside the symptom-driven generic HSI event
to increase tx coverage up to reported levels
"""
def __init__(self, module):
super().__init__(module, frequency=DateOffset(months=1))
def apply(self, population):
df = population.props
now = self.sim.date
p = self.module.parameters
# select people to go for testing (and subsequent tx)
# random sample 0.4 to match clinical case tx coverage
# this sample will include asymptomatic infections too to account for
# unnecessary treatments and uninfected people
alive = df.is_alive
test = df.index[alive][self.module.rng.random_sample(size=alive.sum()) < p["testing_adj"]]
for person_index in test:
logger.debug(key='message',
data=f'MalariaScheduleTesting: scheduling HSI_Malaria_rdt for person {person_index}')
self.sim.modules["HealthSystem"].schedule_hsi_event(
HSI_Malaria_rdt(self.module, person_id=person_index),
priority=1,
topen=now, tclose=None
)
# TODO link this with ANC appts
class MalariaIPTp(RegularEvent, PopulationScopeEventMixin):
""" malaria prophylaxis for pregnant women
"""
def __init__(self, module):
super().__init__(module, frequency=DateOffset(months=1))
def apply(self, population):
df = population.props
now = self.sim.date
# select currently pregnant women without IPTp, malaria-negative
p1 = df.index[df.is_alive & df.is_pregnant & ~df.ma_is_infected & ~df.ma_iptp]
for person_index in p1:
logger.debug(key='message',
data=f'MalariaIPTp: scheduling HSI_Malaria_IPTp for person {person_index}')
event = HSI_MalariaIPTp(self.module, person_id=person_index)
self.sim.modules["HealthSystem"].schedule_hsi_event(
event, priority=1, topen=now, tclose=None
)
class MalariaDeathEvent(Event, IndividualScopeEventMixin):
"""
Performs the Death operation on an individual and logs it.
"""
def __init__(self, module, individual_id, cause):
super().__init__(module, person_id=individual_id)
self.cause = cause
def apply(self, individual_id):
df = self.sim.population.props
if not df.at[individual_id, "is_alive"]:
return
# if on treatment, will reduce probability of death
# use random number generator - currently param treatment_adjustment set to 0.5
if df.at[individual_id, "ma_tx"]:
prob = self.module.rng.rand()
if prob < self.module.parameters["treatment_adjustment"]:
self.sim.schedule_event(
demography.InstantaneousDeath(
self.module, individual_id, cause=self.cause
),
self.sim.date,
)
df.at[individual_id, "ma_date_death"] = self.sim.date
else:
self.sim.schedule_event(
demography.InstantaneousDeath(
self.module, individual_id, cause=self.cause
),
self.sim.date,
)
df.at[individual_id, "ma_date_death"] = self.sim.date
# ---------------------------------------------------------------------------------
# Health System Interaction Events
# ---------------------------------------------------------------------------------
class HSI_Malaria_rdt(HSI_Event, IndividualScopeEventMixin):
"""
this is a point-of-care malaria rapid diagnostic test, with results within 2 minutes
"""
def __init__(self, module, person_id):
super().__init__(module, person_id=person_id)
assert isinstance(module, Malaria)
# Get a blank footprint and then edit to define call on resources of this treatment event
the_appt_footprint = self.sim.modules["HealthSystem"].get_blank_appt_footprint()
the_appt_footprint["LabPOC"] = 1
# print(the_appt_footprint)
# Define the necessary information for an HSI
self.TREATMENT_ID = "Malaria_RDT"
self.EXPECTED_APPT_FOOTPRINT = the_appt_footprint
self.ACCEPTED_FACILITY_LEVEL = 1
self.ALERT_OTHER_DISEASES = []
def apply(self, person_id, squeeze_factor):
df = self.sim.population.props
params = self.module.parameters
hs = self.sim.modules["HealthSystem"]
# Ignore this event if the person is no longer alive:
if not df.at[person_id, 'is_alive']:
return hs.get_blank_appt_footprint()
district = df.at[person_id, "district_num_of_residence"]
logger.debug(key='message',
data=f'HSI_Malaria_rdt: rdt test for person {person_id} '
f'in district num {district}')
# call the DxTest RDT to diagnose malaria
dx_result = hs.dx_manager.run_dx_test(
dx_tests_to_run='malaria_rdt',
hsi_event=self
)
if dx_result:
# check if currently on treatment
if not df.at[person_id, "ma_tx"]:
# ----------------------------------- SEVERE MALARIA -----------------------------------
# if severe malaria, treat for complicated malaria
if df.at[person_id, "ma_inf_type"] == "severe":
# paediatric severe malaria case
if df.at[person_id, "age_years"] < 15:
logger.debug(key='message',
data=f'HSI_Malaria_rdt: scheduling HSI_Malaria_tx_compl_child {person_id}'
f'on date {self.sim.date}')
treat = HSI_Malaria_complicated_treatment_child(
self.sim.modules["Malaria"], person_id=person_id
)
self.sim.modules["HealthSystem"].schedule_hsi_event(
treat, priority=1, topen=self.sim.date, tclose=None
)
else:
# adult severe malaria case
logger.debug(key='message',
data='HSI_Malaria_rdt: scheduling HSI_Malaria_tx_compl_adult for person '
f'{person_id} on date {self.sim.date}')
treat = HSI_Malaria_complicated_treatment_adult(
self.module, person_id=person_id
)
self.sim.modules["HealthSystem"].schedule_hsi_event(
treat, priority=1, topen=self.sim.date, tclose=None
)
# ----------------------------------- TREATMENT CLINICAL DISEASE -----------------------------------
# clinical malaria - not severe
elif df.at[person_id, "ma_inf_type"] == "clinical":
# diagnosis of clinical disease dependent on RDT sensitivity
diagnosed = self.sim.rng.choice(
[True, False],
size=1,
p=[params["sensitivity_rdt"], (1 - params["sensitivity_rdt"])],
)
# diagnosis / treatment for children <5
if diagnosed & (df.at[person_id, "age_years"] < 5):
logger.debug(key='message',
data=f'HSI_Malaria_rdt scheduling HSI_Malaria_tx_0_5 for person {person_id}'
f'on date {self.sim.date}')
treat = HSI_Malaria_non_complicated_treatment_age0_5(self.module, person_id=person_id)
self.sim.modules["HealthSystem"].schedule_hsi_event(
treat, priority=1, topen=self.sim.date, tclose=None
)
# diagnosis / treatment for children 5-15
if diagnosed & (df.at[person_id, "age_years"] >= 5) & (df.at[person_id, "age_years"] < 15):
logger.debug(key='message',
data=f'HSI_Malaria_rdt: scheduling HSI_Malaria_tx_5_15 for person {person_id}'
f'on date {self.sim.date}')
treat = HSI_Malaria_non_complicated_treatment_age5_15(self.module, person_id=person_id)
self.sim.modules["HealthSystem"].schedule_hsi_event(
treat, priority=1, topen=self.sim.date, tclose=None
)
# diagnosis / treatment for adults
if diagnosed & (df.at[person_id, "age_years"] >= 15):
logger.debug(key='message',
data=f'HSI_Malaria_rdt: scheduling HSI_Malaria_tx_adult for person {person_id}'
f'on date {self.sim.date}')
treat = HSI_Malaria_non_complicated_treatment_adult(self.module, person_id=person_id)
self.sim.modules["HealthSystem"].schedule_hsi_event(
treat, priority=1, topen=self.sim.date, tclose=None
)
def did_not_run(self):
logger.debug(key='message',
data='HSI_Malaria_rdt: did not run')
pass
class HSI_Malaria_non_complicated_treatment_age0_5(HSI_Event, IndividualScopeEventMixin):
"""
this is anti-malarial treatment for children <15 kg. Includes treatment plus one rdt
"""
def __init__(self, module, person_id):
super().__init__(module, person_id=person_id)
assert isinstance(module, Malaria)
# Get a blank footprint and then edit to define call on resources of this treatment event
the_appt_footprint = self.sim.modules["HealthSystem"].get_blank_appt_footprint()
the_appt_footprint["Under5OPD"] = 1 # This requires one out patient
# Define the necessary information for an HSI
self.TREATMENT_ID = "Malaria_treatment_child0_5"
self.EXPECTED_APPT_FOOTPRINT = the_appt_footprint
self.ACCEPTED_FACILITY_LEVEL = 1
self.ALERT_OTHER_DISEASES = []
def apply(self, person_id, squeeze_factor):
df = self.sim.population.props
if not df.at[person_id, "ma_tx"]:
logger.debug(key='message',
data=f'HSI_Malaria_tx_0_5: requesting malaria treatment for child {person_id}')
consumables = self.sim.modules["HealthSystem"].parameters["Consumables"]
pkg_code1 = pd.unique(
consumables.loc[
consumables["Intervention_Pkg"]
== "Uncomplicated (children, <15 kg)",
"Intervention_Pkg_Code",
]
)[
0
] # this pkg_code includes another rdt
the_cons_footprint = {
"Intervention_Package_Code": {pkg_code1: 1},
"Item_Code": {},
}
# request the treatment
outcome_of_request_for_consumables = self.sim.modules[
"HealthSystem"
].request_consumables(
hsi_event=self, cons_req_as_footprint=the_cons_footprint
)
if outcome_of_request_for_consumables:
logger.debug(key='message',
data=f'HSI_Malaria_tx_0_5: giving malaria treatment for child {person_id}')
if df.at[person_id, "is_alive"]:
df.at[person_id, "ma_tx"] = True
df.at[person_id, "ma_date_tx"] = self.sim.date
df.at[person_id, "ma_tx_counter"] += 1
def did_not_run(self):
logger.debug(key='message',
data='HSI_Malaria_tx_0_5: did not run')
pass
class HSI_Malaria_non_complicated_treatment_age5_15(HSI_Event, IndividualScopeEventMixin):
"""
this is anti-malarial treatment for children >15 kg. Includes treatment plus one rdt
"""
def __init__(self, module, person_id):
super().__init__(module, person_id=person_id)
assert isinstance(module, Malaria)
# Get a blank footprint and then edit to define call on resources of this treatment event
the_appt_footprint = self.sim.modules["HealthSystem"].get_blank_appt_footprint()
the_appt_footprint["Under5OPD"] = 1 # This requires one out patient
# Define the necessary information for an HSI
self.TREATMENT_ID = "Malaria_treatment_child5_15"
self.EXPECTED_APPT_FOOTPRINT = the_appt_footprint
self.ACCEPTED_FACILITY_LEVEL = 1
self.ALERT_OTHER_DISEASES = []
def apply(self, person_id, squeeze_factor):
df = self.sim.population.props
if not df.at[person_id, "ma_tx"]:
logger.debug(key='message',
data=f'HSI_Malaria_tx_5_15: requesting malaria treatment for child {person_id}')
consumables = self.sim.modules["HealthSystem"].parameters["Consumables"]
pkg_code1 = pd.unique(
consumables.loc[
consumables["Intervention_Pkg"]
== "Uncomplicated (children, >15 kg)",
"Intervention_Pkg_Code",
]
)[
0
] # this pkg_code includes another rdt
the_cons_footprint = {
"Intervention_Package_Code": {pkg_code1: 1},
"Item_Code": {},
}
# request the treatment
outcome_of_request_for_consumables = self.sim.modules[
"HealthSystem"
].request_consumables(
hsi_event=self, cons_req_as_footprint=the_cons_footprint
)
if outcome_of_request_for_consumables:
logger.debug(key='message',
data=f'HSI_Malaria_tx_5_15: giving malaria treatment for child {person_id}')
if df.at[person_id, "is_alive"]:
df.at[person_id, "ma_tx"] = True
df.at[person_id, "ma_date_tx"] = self.sim.date
df.at[person_id, "ma_tx_counter"] += 1
def did_not_run(self):
logger.debug(key='message',
data='HSI_Malaria_tx_5_15: did not run')
pass
class HSI_Malaria_non_complicated_treatment_adult(HSI_Event, IndividualScopeEventMixin):
"""
this is anti-malarial treatment for adults. Includes treatment plus one rdt
"""
def __init__(self, module, person_id):
super().__init__(module, person_id=person_id)
assert isinstance(module, Malaria)
# Get a blank footprint and then edit to define call on resources of this treatment event
the_appt_footprint = self.sim.modules["HealthSystem"].get_blank_appt_footprint()
the_appt_footprint["Over5OPD"] = 1 # This requires one out patient
# Define the necessary information for an HSI
self.TREATMENT_ID = "Malaria_treatment_adult"
self.EXPECTED_APPT_FOOTPRINT = the_appt_footprint
self.ACCEPTED_FACILITY_LEVEL = 1
self.ALERT_OTHER_DISEASES = []
def apply(self, person_id, squeeze_factor):
df = self.sim.population.props
if not df.at[person_id, "ma_tx"]:
logger.debug(key='message',
data=f'HSI_Malaria_tx_adult: requesting malaria treatment for person {person_id}')
consumables = self.sim.modules["HealthSystem"].parameters["Consumables"]
pkg_code1 = pd.unique(
consumables.loc[
consumables["Intervention_Pkg"] == "Uncomplicated (adult, >36 kg)",
"Intervention_Pkg_Code",
]
)[
0
] # this pkg_code includes another rdt
the_cons_footprint = {
"Intervention_Package_Code": {pkg_code1: 1},
"Item_Code": {},
}
# request the treatment
outcome_of_request_for_consumables = self.sim.modules[
"HealthSystem"
].request_consumables(
hsi_event=self, cons_req_as_footprint=the_cons_footprint, to_log=False
)
if outcome_of_request_for_consumables:
logger.debug(key='message',
data=f'HSI_Malaria_tx_adult: giving malaria treatment for person {person_id}')
if df.at[person_id, "is_alive"]:
df.at[person_id, "ma_tx"] = True
df.at[person_id, "ma_date_tx"] = self.sim.date
df.at[person_id, "ma_tx_counter"] += 1
def did_not_run(self):
logger.debug(key='message',
data='HSI_Malaria_tx_adult: did not run')