Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initial Version of Scenario definition and other associated amendments needed for the "Horizontal vs Vertical"-type Analysis, #1288

Merged
merged 209 commits into from
Jul 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
209 commits
Select commit Hold shift + click to select a range
7590a5b
updates from paper analyses for HIV, TB and malaria
tdm32 Feb 9, 2024
22c10f0
remove unused import statements
tdm32 Feb 9, 2024
e8612a3
fix imports
tdm32 Feb 9, 2024
c6802c9
update filepath for malaria resource file
tdm32 Feb 9, 2024
8014f02
remove test_hiv_tb_scenarios.py
tdm32 Feb 9, 2024
63a364a
updated test_healthsystem.py: test_manipulation_of_service_availabili…
tdm32 Feb 13, 2024
b591b82
change ipt_coverage in TB logger as conflicts with existing parameter
tdm32 Feb 13, 2024
68b295e
updated ResourceFile_Improved_Healthsystem_And_Healthcare_Seeking.xls…
tdm32 Feb 13, 2024
7dbe7b5
remove test code
tdm32 Feb 13, 2024
09c9b26
remove test code
tdm32 Feb 13, 2024
3800748
Merge branch 'master' into tara_feb2024_updates_clean
tdm32 Feb 13, 2024
73f19da
delete tmp resourcefiles
tdm32 Feb 13, 2024
b81b2d6
malaria code use person_id consistently instead of individual_id
tdm32 Feb 13, 2024
df2b77e
use individual_id for demography.do_death()
tdm32 Feb 13, 2024
b2bd355
style change to avoid conflicts with master
tdm32 Feb 14, 2024
09b9b66
style change to avoid conflicts with master
tdm32 Feb 14, 2024
8a241e4
Merge branch 'master' into tara_feb2024_updates_clean
tdm32 Feb 14, 2024
758955e
fix conflicts with master
tdm32 Feb 14, 2024
f7ac7e2
fix conflicts with master
tdm32 Feb 14, 2024
c037a4d
Merge branch 'master' into tara_feb2024_updates_clean
tdm32 Feb 14, 2024
9690949
merge in master
tdm32 Feb 14, 2024
05c69ff
check property hv_date_last_ART correctly set
tdm32 Feb 15, 2024
3e3c0d4
Manually add PostnatalCare_Comprehensive to policy priorities
tdm32 Feb 16, 2024
cfd9166
edit fix
tdm32 Feb 16, 2024
3ff7bcb
add schisto high infection as conditional predictor for bladder cancer
tdm32 Feb 27, 2024
434147c
fix conditional predictor for active TB - should check presence of Ca…
tdm32 Feb 27, 2024
808c5ae
add 'ss' prefix to properties from schisto module referenced in bladd…
tdm32 Feb 27, 2024
218f4cf
edit praziquantel code in schisto.py to use value from CMST in place …
tdm32 Feb 27, 2024
f8ebee5
add parameter rr_depr_hiv for risk of depression with HIV infection
tdm32 Feb 27, 2024
904905d
tidy up linear models in depression, include conditional predictors f…
tdm32 Feb 27, 2024
79216db
move hv_inf into conditional predictor for depression in initial popu…
tdm32 Feb 27, 2024
ade9f57
convert lm for incident cancer (site_confined) to model with conditio…
tdm32 Feb 28, 2024
754a1bf
add parameter rr_site_confined_hiv to other_adult_cancers.py
tdm32 Feb 28, 2024
876c979
update other_adult_cancers write-up to include HIV as risk factor
tdm32 Feb 28, 2024
865aae0
update Depression.docx to include HIV as risk factor for depression
tdm32 Feb 28, 2024
5bb2560
edit HIV in depression to include only HIV cases not virally suppressed
tdm32 Feb 28, 2024
9cb1043
update other_adult_cancers.py linear model to include HIV as risk fac…
tdm32 Feb 28, 2024
1e316af
edit: HIV remains as risk factor for depression independent of treatm…
tdm32 Feb 28, 2024
85cec50
include HIV as risk factor for low grade dysplasia (oesophageal cance…
tdm32 Feb 28, 2024
6f45dc7
update linear model for low grade dysplasia to include HIV as conditi…
tdm32 Feb 28, 2024
2dbb98d
update OesophagealCancer.docx write-up to include HIV risk
tdm32 Feb 28, 2024
b6b5fdc
add condition hiv diagnosed for increased risk of depression
tdm32 Mar 4, 2024
a040823
remove hiv as risk factor for oesophageal cancer
tdm32 Mar 4, 2024
1eeff16
remove parameter for hiv as risk factor for oesophageal cancer
tdm32 Mar 4, 2024
78b73e5
update OesophagealCancer.docx to remove hiv as risk factor
tdm32 Mar 4, 2024
b899660
update value for weighted risk of other_adult_cancers with unsuppress…
tdm32 Mar 4, 2024
599580b
add rr_hiv to linear model. update ResourceFile_cmd_condition_onset.x…
tdm32 Mar 4, 2024
953502e
update resourcefiles for CMD include rr_hiv for all, no effect of maj…
tdm32 Mar 4, 2024
5fb9301
refactoring:
tbhallett Mar 4, 2024
b57a503
add diabetes as risk for active TB and relapse. add params to Resourc…
tdm32 Mar 5, 2024
465b18b
add diabetes as risk factor for tb death
tdm32 Mar 5, 2024
d573211
add diabetes as risk factor for PLHIV with active TB and on TB treatment
tdm32 Mar 5, 2024
3734acb
add diabetes as risk factor for PLHIV with active TB and on TB treatment
tdm32 Mar 5, 2024
7e5f6a6
set up run to check calibration of deaths and disability
tdm32 Mar 5, 2024
b786256
add predictor high-intensity S. haematobium infection to risk of blad…
tdm32 Mar 6, 2024
956b09a
add predictor high-intensity S. haematobium infection to risk of HIV …
tdm32 Mar 6, 2024
e375927
fix indenting in HSI_Hiv_StartOrContinueTreatment
tdm32 Mar 7, 2024
272558f
add hv_date_treated abd hv_date_last_ART to baseline_art
tdm32 Mar 7, 2024
8602f03
convert linear model in CMD to include conditional predictors
tdm32 Mar 11, 2024
2f87289
delete resourcefile created in error
tdm32 Mar 11, 2024
c8d65f4
comment out path-specific changes to analysis_cause_of_death_and_disa…
tdm32 Mar 11, 2024
1574c3a
fix CMD error if Hiv not registered
tdm32 Mar 11, 2024
7b6e3d5
Merge branch 'master' into tara_hiv_ncd_feb2024
tdm32 Mar 11, 2024
f20b151
Merge branch 'master' into tara_hiv_ncd_feb2024
tdm32 Mar 11, 2024
3e982bf
Merge remote-tracking branch 'origin/tara_hiv_ncd_feb2024' into tara_…
tdm32 Mar 11, 2024
d8374e2
initial sketch of structure
tbhallett Mar 12, 2024
5064cb5
tidy-up and fix tests
tbhallett Mar 12, 2024
8467b18
commments
tbhallett Mar 12, 2024
f0466bf
Merge branch 'master' into tara_feb2024_updates_clean
tdm32 Mar 12, 2024
9901edd
remove parameter rr_bcg_inf from tb.py
tdm32 Mar 19, 2024
62e5c04
Merge branch 'master' into tara_feb2024_updates_clean
tdm32 Mar 22, 2024
7e3e20f
edit comment in initialise_simulation
tdm32 Mar 22, 2024
7ec6efa
Merge branch 'tara_hiv_ncd_feb2024' into tara_feb2024_updates_clean
tdm32 Mar 22, 2024
922ac8e
fix parameter name error
tdm32 Mar 22, 2024
1b61aaf
update parameters
tdm32 Mar 22, 2024
3aa7b46
test runs
tdm32 Mar 22, 2024
604bd14
edit and fix flake8 errors
tdm32 Mar 22, 2024
629e2e0
fix failing test
tdm32 Mar 22, 2024
8bba11c
update ResourceFile_Improved_Healthsystem_And_Healthcare_Seeking.xlsx
tdm32 Mar 25, 2024
6543bd0
update ResourceFile_PriorityRanking_ALLPOLICIES.xlsx
tdm32 Mar 25, 2024
5edc77d
updated ResourceFile_Improved_Healthsystem_And_Healthcare_Seeking.xlsx
tdm32 Mar 25, 2024
36c4060
scenario file
tbhallett Mar 26, 2024
78e05cd
starting work on the scenario file
tbhallett Mar 26, 2024
19a3824
Merge remote-tracking branch 'origin/master' into hallett/analysis_fo…
tbhallett Mar 26, 2024
0eb7463
design and HR scenarios
tbhallett Mar 26, 2024
52bfc1f
Merge branch 'master' into hallett/analysis_for_vertical_and_horizont…
tbhallett Mar 26, 2024
634d67a
scenario for HRH
tbhallett Mar 26, 2024
49d14e7
roll back changes to ScenarioSwitcher
tbhallett Mar 26, 2024
770fd56
Revert "roll back changes to ScenarioSwitcher"
tbhallett Mar 26, 2024
0d6270d
sketch out of prposed changed for scenario_switcher
tbhallett Mar 27, 2024
de93f92
sketch out of prposed changed for scenario_switcher
tbhallett Mar 28, 2024
1e467c9
sketch out of prposed changed for scenario_switcher
tbhallett Apr 2, 2024
244189d
Merge branch 'master' into hallett/analysis_for_vertical_and_horizont…
tbhallett Apr 2, 2024
ce5277b
sketch out of prposed changed for scenario_switcher
tbhallett Apr 2, 2024
6db0f1b
sketch out of prposed changed for scenario_switcher
tbhallett Apr 2, 2024
34ac657
Add ResourceFile_Consumables_Item_Designations.csv
tbhallett Apr 3, 2024
0c8c032
create special scenarios for consumables availability based on the de…
tbhallett Apr 3, 2024
edcef4b
comment and fix imports
tbhallett Apr 3, 2024
afc6cc5
draft of scenario file
tbhallett Apr 3, 2024
9e92723
linting
tbhallett Apr 3, 2024
57c230a
increase length of scenarios and reduce reps
tbhallett Apr 3, 2024
14ee706
rename
tbhallett Apr 3, 2024
b9f1f89
correct error in specifiction of dynamic scaling scenario
tbhallett Apr 3, 2024
61ebcc7
remove trailing commas that casts return as tuple
tbhallett Apr 3, 2024
2b9256a
Initially only consider baseline and perfect healthcare seeking scena…
marghe-molaro Apr 3, 2024
08d9307
Submit remaining scenarios
marghe-molaro Apr 16, 2024
2ebea31
direct to self.module (rather than self)
tbhallett Apr 16, 2024
a1f0da9
Merge branch 'master' into tara_feb2024_updates_clean
tdm32 Apr 22, 2024
ff71d6f
Merge branch 'master' into hallett/analysis_for_vertical_and_horizont…
tbhallett Apr 24, 2024
b34d670
edit check for last ART when new dispensation occurs
tdm32 May 2, 2024
d56c3d8
update schisto risk on HIV to only include women
tdm32 May 13, 2024
9667bd3
add scale-up parameter for htm programs
tdm32 May 13, 2024
73c6abf
add catch for malaria rdt_testing_rates post-2024
tdm32 May 14, 2024
39cce9b
malaria parameters scale-up included
tdm32 May 14, 2024
38cfc52
restore `scenario_comparison_of_horizontal_and_vertical_programs` (re…
tbhallett May 16, 2024
254613b
Merge branch 'refs/heads/master' into hallett/analysis_for_vertical_a…
tbhallett May 16, 2024
ac01da8
first draft of figures
tbhallett May 20, 2024
15d63bc
set up test for HTM scenario scale-up
tdm32 May 27, 2024
e8699b8
add tests for HTM scale-up
tdm32 May 28, 2024
89435ad
check resourcefiles updated
tdm32 May 28, 2024
1f261b9
check the usage of '' versus ""
tdm32 May 28, 2024
ac58f0a
reset to single quotes to match PR #1273
tdm32 May 28, 2024
4bcb25d
remove unneeded resource files
tdm32 May 28, 2024
f67fa42
remove unneeded resource files
tdm32 May 28, 2024
7082b51
edit filepaths
tdm32 May 29, 2024
721fe0b
isort for imports
tdm32 May 29, 2024
7782350
edit ResourceFile_Improved_Healthsystem_And_Healthcare_Seeking.xlsx t…
tdm32 May 29, 2024
e2c81e2
fix filename for test_HTMscaleup.py
tdm32 May 29, 2024
a0af398
Merge branch 'refs/heads/master' into hallett/analysis_for_vertical_a…
tbhallett Jun 6, 2024
9a2f71a
update scenario file
tbhallett Jun 6, 2024
31758e1
update scenario file
tbhallett Jun 6, 2024
28d7c8c
include "scale_to_effective_capabilities": True
tbhallett Jun 6, 2024
0712781
linting
tbhallett Jun 6, 2024
cb478f1
linting
tbhallett Jun 6, 2024
243690f
reduce number of draws
tbhallett Jun 6, 2024
c21fbc3
set scaleup parameters separately in each module
tdm32 Jun 10, 2024
c2a4590
set scaleup parameters separately in each module
tdm32 Jun 10, 2024
32d2314
Merge branch 'master' into tara_scenario_switcher_updatedHTM
tdm32 Jun 10, 2024
f161de3
update resourcefiles
tdm32 Jun 10, 2024
af5d6a9
update resourcefiles
tdm32 Jun 10, 2024
7fa127f
set up script to test scenarios - scale-up of HTM programs
tdm32 Jun 10, 2024
4e8d6c0
test runs
tdm32 Jun 10, 2024
3458525
add scenario switch to malaria.py
tdm32 Jun 10, 2024
bc1a864
cherry-pick inadvertently updated files and revert
tdm32 Jun 10, 2024
b57379f
isort fixes
tdm32 Jun 10, 2024
8d13b17
Delete resources/~$ResourceFile_HIV.xlsx
tdm32 Jun 10, 2024
e6c7dcf
Delete resources/~$ResourceFile_TB.xlsx
tdm32 Jun 10, 2024
d72487e
Delete resources/malaria/~$ResourceFile_malaria.xlsx
tdm32 Jun 10, 2024
b8163d4
fix failing tests
tdm32 Jun 10, 2024
ee2c8b6
Merge remote-tracking branch 'origin/tara_scenario_switcher_updatedHT…
tdm32 Jun 10, 2024
6304c76
rollback changes to calibration_analyses/scenarios/long_run_all_disea…
tdm32 Jun 10, 2024
63a7dc6
fix error in filename
tdm32 Jun 11, 2024
d06cb84
revert timedelta format to 'M'
tdm32 Jun 11, 2024
5380d8d
add todos
tbhallett Jun 18, 2024
e63cd98
Merge branch 'master' into hallett/analysis_for_vertical_and_horizont…
tbhallett Jun 24, 2024
7580779
Merge branch 'master' into tara_scenario_switcher_updatedHTM
tdm32 Jun 25, 2024
3443603
merge in master
tdm32 Jun 25, 2024
9ba266f
set up test runs for scale-up
tdm32 Jun 25, 2024
975509c
edit scenario start date
tdm32 Jun 25, 2024
304c423
change parameter scaleup_start_date to an integer value used in DateO…
tdm32 Jun 25, 2024
01745de
change scale-up event scheduling to use new DateOffset parameter
tdm32 Jun 25, 2024
0d8d8e9
test runs
tdm32 Jun 26, 2024
acae16e
set up test runs
tdm32 Jun 26, 2024
67f2fa4
set up test runs
tdm32 Jun 26, 2024
7d668de
fix failing tests
tdm32 Jun 26, 2024
0b3e938
Update tests/test_HTMscaleup.py
tdm32 Jun 26, 2024
fcea78b
address comments on PR review
tdm32 Jun 26, 2024
1a86e9c
isort fixes
tdm32 Jun 26, 2024
a0be80c
isort fixes
tdm32 Jun 26, 2024
802939a
change np.timedelta in enhanced_lifestyle.py back to original
tdm32 Jun 26, 2024
3230a1f
Merge remote-tracking branch 'origin/hallett/analysis_for_vertical_an…
tbhallett Jun 27, 2024
7ff54e6
remove json file
tbhallett Jun 27, 2024
8e19f4f
call it 'htm_scenario_analysis' rather than just 'scenario_analysis'
tbhallett Jun 27, 2024
7ef4914
update comment
tbhallett Jun 27, 2024
d08e346
roll back change in test_tb.py
tbhallett Jun 27, 2024
08e2421
remove .py extension for clarity
tbhallett Jun 27, 2024
52949f8
roll back incidental change
tbhallett Jun 27, 2024
3e91f88
linting and editing string for clarity
tbhallett Jun 27, 2024
ea0eebe
roll back incidental changes
tbhallett Jun 27, 2024
b5ccd4d
defaults for healthsystem ok -- no need to step through each option
tbhallett Jun 27, 2024
9ae9615
remove inadvertent duplication in code
tbhallett Jun 27, 2024
419d2b4
remove comment
tbhallett Jun 27, 2024
66eecb6
use dict for ease of accessing
tbhallett Jun 27, 2024
dc0dd8b
parameter to be the YEAR (int) of the change to fit with the conventi…
tbhallett Jun 27, 2024
08dea6a
remove comment
tbhallett Jun 27, 2024
d591890
refactor module method for clarity
tbhallett Jun 27, 2024
467066d
refactor to prevent same name being used for events specific to diffe…
tbhallett Jun 27, 2024
830f83f
specify year for scale-up in analysis file
tbhallett Jun 27, 2024
d1e5b30
Merge branch 'refs/heads/tara_scenario_switcher_updatedHTM' into hall…
tbhallett Jun 27, 2024
9491e5a
rename; add note; remove comments for HTM scenarios
tbhallett Jun 27, 2024
92d0316
refacotring
tbhallett Jun 27, 2024
66236cf
rename scenario class for hss elements
tbhallett Jun 27, 2024
101fd3c
new scenario for combinations of vertical and horizontal programs
tbhallett Jun 27, 2024
417ccba
minor refactor
tbhallett Jun 27, 2024
85e7678
update docstring
tbhallett Jun 27, 2024
78fd0c8
renaming
tbhallett Jun 27, 2024
02a5133
add @property decorator
tbhallett Jun 27, 2024
c425907
Merge branch 'refs/heads/master' into hallett/analysis_for_vertical_a…
tbhallett Jun 27, 2024
846d6a2
plot DALYS averted relative to Baseline - broken down by major cause …
tbhallett Jul 3, 2024
60c9db0
Merge branch 'master' into hallett/analysis_for_vertical_and_horizont…
tbhallett Jul 3, 2024
9710546
define mini run scenario
tbhallett Jul 25, 2024
5ac3fc0
rename scenario
tbhallett Jul 29, 2024
ddbd4c1
Merge branch 'master' into hallett/analysis_for_vertical_and_horizont…
tbhallett Jul 29, 2024
6d46a5d
Merge remote-tracking branch 'origin/hallett/analysis_for_vertical_an…
tbhallett Jul 29, 2024
b57645b
lining isort
tbhallett Jul 29, 2024
204accc
linting ruff
tbhallett Jul 29, 2024
f58c9aa
delete not-yet-used file
tbhallett Jul 29, 2024
3c87559
isort again!
tbhallett Jul 29, 2024
cacdeef
Merge branch 'refs/heads/master' into hallett/analysis_for_vertical_a…
tbhallett Jul 29, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Git LFS file not shown
Original file line number Diff line number Diff line change
@@ -0,0 +1,272 @@
"""Produce plots to show the impact each the healthcare system (overall health impact) when running under different
scenarios (scenario_impact_of_healthsystem.py)"""

import argparse
import textwrap
from pathlib import Path
from typing import Tuple

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt

from tlo import Date
from tlo.analysis.utils import extract_results, make_age_grp_lookup, summarize


def apply(results_folder: Path, output_folder: Path, resourcefilepath: Path = None):
"""Produce standard set of plots describing the effect of each TREATMENT_ID.
- We estimate the epidemiological impact as the EXTRA deaths that would occur if that treatment did not occur.
- We estimate the draw on healthcare system resources as the FEWER appointments when that treatment does not occur.
"""

TARGET_PERIOD = (Date(2020, 1, 1), Date(2030, 12, 31))

# Definitions of general helper functions
make_graph_file_name = lambda stub: output_folder / f"{stub.replace('*', '_star_')}.png" # noqa: E731

_, age_grp_lookup = make_age_grp_lookup()

def target_period() -> str:
"""Returns the target period as a string of the form YYYY-YYYY"""
return "-".join(str(t.year) for t in TARGET_PERIOD)

def get_parameter_names_from_scenario_file() -> Tuple[str]:
"""Get the tuple of names of the scenarios from `Scenario` class used to create the results."""
from scripts.comparison_of_horizontal_and_vertical_programs.scenario_hss_elements import (
HSSElements,
)
e = HSSElements()
return tuple(e._scenarios.keys())

def get_num_deaths(_df):
"""Return total number of Deaths (total within the TARGET_PERIOD)"""
return pd.Series(data=len(_df.loc[pd.to_datetime(_df.date).between(*TARGET_PERIOD)]))

def get_num_dalys(_df):
"""Return total number of DALYS (Stacked) by label (total within the TARGET_PERIOD).
Throw error if not a record for every year in the TARGET PERIOD (to guard against inadvertently using
results from runs that crashed mid-way through the simulation.
"""
years_needed = [i.year for i in TARGET_PERIOD]
assert set(_df.year.unique()).issuperset(years_needed), "Some years are not recorded."
return pd.Series(
data=_df
.loc[_df.year.between(*years_needed)]
.drop(columns=['date', 'sex', 'age_range', 'year'])
.sum().sum()
)

def set_param_names_as_column_index_level_0(_df):
"""Set the columns index (level 0) as the param_names."""
ordered_param_names_no_prefix = {i: x for i, x in enumerate(param_names)}
names_of_cols_level0 = [ordered_param_names_no_prefix.get(col) for col in _df.columns.levels[0]]
assert len(names_of_cols_level0) == len(_df.columns.levels[0])
_df.columns = _df.columns.set_levels(names_of_cols_level0, level=0)
return _df

def find_difference_relative_to_comparison(_ser: pd.Series,
comparison: str,
scaled: bool = False,
drop_comparison: bool = True,
):
"""Find the difference in the values in a pd.Series with a multi-index, between the draws (level 0)
within the runs (level 1), relative to where draw = `comparison`.
The comparison is `X - COMPARISON`."""
return _ser \
.unstack(level=0) \
.apply(lambda x: (x - x[comparison]) / (x[comparison] if scaled else 1.0), axis=1) \
.drop(columns=([comparison] if drop_comparison else [])) \
.stack()

def do_bar_plot_with_ci(_df, annotations=None, xticklabels_horizontal_and_wrapped=False, put_labels_in_legend=True):
"""Make a vertical bar plot for each row of _df, using the columns to identify the height of the bar and the
extent of the error bar."""

substitute_labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

yerr = np.array([
(_df['mean'] - _df['lower']).values,
(_df['upper'] - _df['mean']).values,
])

xticks = {(i + 0.5): k for i, k in enumerate(_df.index)}

# Define colormap (used only with option `put_labels_in_legend=True`)
cmap = plt.get_cmap("tab20")
rescale = lambda y: (y - np.min(y)) / (np.max(y) - np.min(y)) # noqa: E731
colors = list(map(cmap, rescale(np.array(list(xticks.keys()))))) if put_labels_in_legend else None

fig, ax = plt.subplots(figsize=(10, 5))
ax.bar(
xticks.keys(),
_df['mean'].values,
yerr=yerr,
alpha=0.8,
ecolor='black',
color=colors,
capsize=10,
label=xticks.values()
)
if annotations:
for xpos, ypos, text in zip(xticks.keys(), _df['upper'].values, annotations):
ax.text(xpos, ypos*1.15, text, horizontalalignment='center', rotation='vertical', fontsize='x-small')
ax.set_xticks(list(xticks.keys()))

if put_labels_in_legend:
# Update xticks label with substitute labels
# Insert legend with updated labels that shows correspondence between substitute label and original label
xtick_values = [letter for letter, label in zip(substitute_labels, xticks.values())]
xtick_legend = [f'{letter}: {label}' for letter, label in zip(substitute_labels, xticks.values())]
h, legs = ax.get_legend_handles_labels()
ax.legend(h, xtick_legend, loc='center left', fontsize='small', bbox_to_anchor=(1, 0.5))
ax.set_xticklabels(list(xtick_values))
else:
if not xticklabels_horizontal_and_wrapped:
# xticklabels will be vertical and not wrapped
ax.set_xticklabels(list(xticks.values()), rotation=90)
else:
wrapped_labs = ["\n".join(textwrap.wrap(_lab, 20)) for _lab in xticks.values()]
ax.set_xticklabels(wrapped_labs)

ax.grid(axis="y")
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
fig.tight_layout()

return fig, ax

# %% Define parameter names
param_names = get_parameter_names_from_scenario_file()

# %% Quantify the health gains associated with all interventions combined.

# Absolute Number of Deaths and DALYs
num_deaths = extract_results(
results_folder,
module='tlo.methods.demography',
key='death',
custom_generate_series=get_num_deaths,
do_scaling=True
).pipe(set_param_names_as_column_index_level_0)

num_dalys = extract_results(
results_folder,
module='tlo.methods.healthburden',
key='dalys_stacked',
custom_generate_series=get_num_dalys,
do_scaling=True
).pipe(set_param_names_as_column_index_level_0)

# %% Charts of total numbers of deaths / DALYS
num_dalys_summarized = summarize(num_dalys).loc[0].unstack().reindex(param_names)
num_deaths_summarized = summarize(num_deaths).loc[0].unstack().reindex(param_names)

name_of_plot = f'Deaths, {target_period()}'
fig, ax = do_bar_plot_with_ci(num_deaths_summarized / 1e6)
ax.set_title(name_of_plot)
ax.set_ylabel('(Millions)')
fig.tight_layout()
ax.axhline(num_deaths_summarized.loc['Baseline', 'mean']/1e6, color='black', alpha=0.5)
fig.savefig(make_graph_file_name(name_of_plot.replace(' ', '_').replace(',', '')))
fig.show()
plt.close(fig)

name_of_plot = f'All Scenarios: DALYs, {target_period()}'
fig, ax = do_bar_plot_with_ci(num_dalys_summarized / 1e6)
ax.set_title(name_of_plot)
ax.set_ylabel('(Millions)')
ax.axhline(num_dalys_summarized.loc['Baseline', 'mean']/1e6, color='black', alpha=0.5)
fig.tight_layout()
fig.savefig(make_graph_file_name(name_of_plot.replace(' ', '_').replace(',', '')))
fig.show()
plt.close(fig)


# %% Deaths and DALYS averted relative to Status Quo
num_deaths_averted = summarize(
-1.0 *
pd.DataFrame(
find_difference_relative_to_comparison(
num_deaths.loc[0],
comparison='Baseline')
).T
).iloc[0].unstack().reindex(param_names).drop(['Baseline'])

pc_deaths_averted = 100.0 * summarize(
-1.0 *
pd.DataFrame(
find_difference_relative_to_comparison(
num_deaths.loc[0],
comparison='Baseline',
scaled=True)
).T
).iloc[0].unstack().reindex(param_names).drop(['Baseline'])

num_dalys_averted = summarize(
-1.0 *
pd.DataFrame(
find_difference_relative_to_comparison(
num_dalys.loc[0],
comparison='Baseline')
).T
).iloc[0].unstack().reindex(param_names).drop(['Baseline'])

pc_dalys_averted = 100.0 * summarize(
-1.0 *
pd.DataFrame(
find_difference_relative_to_comparison(
num_dalys.loc[0],
comparison='Baseline',
scaled=True)
).T
).iloc[0].unstack().reindex(param_names).drop(['Baseline'])

# DEATHS
name_of_plot = f'Additional Deaths Averted vs Baseline, {target_period()}'
fig, ax = do_bar_plot_with_ci(
num_deaths_averted.clip(lower=0.0),
annotations=[
f"{round(row['mean'], 0)} ({round(row['lower'], 1)}-{round(row['upper'], 1)}) %"
for _, row in pc_deaths_averted.clip(lower=0.0).iterrows()
]
)
ax.set_title(name_of_plot)
ax.set_ylabel('Additional Deaths Averted')
fig.tight_layout()
fig.savefig(make_graph_file_name(name_of_plot.replace(' ', '_').replace(',', '')))
fig.show()
plt.close(fig)

# DALYS
name_of_plot = f'Additional DALYs Averted vs Baseline, {target_period()}'
fig, ax = do_bar_plot_with_ci(
(num_dalys_averted / 1e6).clip(lower=0.0),
annotations=[
f"{round(row['mean'])} ({round(row['lower'], 1)}-{round(row['upper'], 1)}) %"
for _, row in pc_dalys_averted.clip(lower=0.0).iterrows()
]
)
ax.set_title(name_of_plot)
ax.set_ylabel('Additional DALYS Averted \n(Millions)')
fig.tight_layout()
fig.savefig(make_graph_file_name(name_of_plot.replace(' ', '_').replace(',', '')))
fig.show()
plt.close(fig)

# todo: Neaten graphs
# todo: Graph showing difference broken down by disease (this can be cribbed from the calcs about wealth from the
# third set of analyses in the overview paper).
# todo: other metrics of health
# todo: other graphs, broken down by age/sex (this can also be cribbed from overview paper stuff)

if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("results_folder", type=Path) # outputs/horizontal_and_vertical_programs-2024-05-16
args = parser.parse_args()

apply(
results_folder=args.results_folder,
output_folder=args.results_folder,
resourcefilepath=Path('./resources')
)
Loading