|
| 1 | +"""Produce plots to show the impact each the healthcare system (overall health impact) when running under different |
| 2 | +scenarios (scenario_impact_of_healthsystem.py)""" |
| 3 | + |
| 4 | +import argparse |
| 5 | +import textwrap |
| 6 | +from pathlib import Path |
| 7 | +from typing import Tuple |
| 8 | + |
| 9 | +import numpy as np |
| 10 | +import pandas as pd |
| 11 | +from matplotlib import pyplot as plt |
| 12 | + |
| 13 | +from tlo import Date |
| 14 | +from tlo.analysis.utils import extract_results, make_age_grp_lookup, summarize |
| 15 | + |
| 16 | + |
| 17 | +def apply(results_folder: Path, output_folder: Path, resourcefilepath: Path = None): |
| 18 | + """Produce standard set of plots describing the effect of each TREATMENT_ID. |
| 19 | + - We estimate the epidemiological impact as the EXTRA deaths that would occur if that treatment did not occur. |
| 20 | + - We estimate the draw on healthcare system resources as the FEWER appointments when that treatment does not occur. |
| 21 | + """ |
| 22 | + |
| 23 | + TARGET_PERIOD = (Date(2020, 1, 1), Date(2030, 12, 31)) |
| 24 | + |
| 25 | + # Definitions of general helper functions |
| 26 | + make_graph_file_name = lambda stub: output_folder / f"{stub.replace('*', '_star_')}.png" # noqa: E731 |
| 27 | + |
| 28 | + _, age_grp_lookup = make_age_grp_lookup() |
| 29 | + |
| 30 | + def target_period() -> str: |
| 31 | + """Returns the target period as a string of the form YYYY-YYYY""" |
| 32 | + return "-".join(str(t.year) for t in TARGET_PERIOD) |
| 33 | + |
| 34 | + def get_parameter_names_from_scenario_file() -> Tuple[str]: |
| 35 | + """Get the tuple of names of the scenarios from `Scenario` class used to create the results.""" |
| 36 | + from scripts.comparison_of_horizontal_and_vertical_programs.scenario_hss_elements import ( |
| 37 | + HSSElements, |
| 38 | + ) |
| 39 | + e = HSSElements() |
| 40 | + return tuple(e._scenarios.keys()) |
| 41 | + |
| 42 | + def get_num_deaths(_df): |
| 43 | + """Return total number of Deaths (total within the TARGET_PERIOD)""" |
| 44 | + return pd.Series(data=len(_df.loc[pd.to_datetime(_df.date).between(*TARGET_PERIOD)])) |
| 45 | + |
| 46 | + def get_num_dalys(_df): |
| 47 | + """Return total number of DALYS (Stacked) by label (total within the TARGET_PERIOD). |
| 48 | + Throw error if not a record for every year in the TARGET PERIOD (to guard against inadvertently using |
| 49 | + results from runs that crashed mid-way through the simulation. |
| 50 | + """ |
| 51 | + years_needed = [i.year for i in TARGET_PERIOD] |
| 52 | + assert set(_df.year.unique()).issuperset(years_needed), "Some years are not recorded." |
| 53 | + return pd.Series( |
| 54 | + data=_df |
| 55 | + .loc[_df.year.between(*years_needed)] |
| 56 | + .drop(columns=['date', 'sex', 'age_range', 'year']) |
| 57 | + .sum().sum() |
| 58 | + ) |
| 59 | + |
| 60 | + def set_param_names_as_column_index_level_0(_df): |
| 61 | + """Set the columns index (level 0) as the param_names.""" |
| 62 | + ordered_param_names_no_prefix = {i: x for i, x in enumerate(param_names)} |
| 63 | + names_of_cols_level0 = [ordered_param_names_no_prefix.get(col) for col in _df.columns.levels[0]] |
| 64 | + assert len(names_of_cols_level0) == len(_df.columns.levels[0]) |
| 65 | + _df.columns = _df.columns.set_levels(names_of_cols_level0, level=0) |
| 66 | + return _df |
| 67 | + |
| 68 | + def find_difference_relative_to_comparison(_ser: pd.Series, |
| 69 | + comparison: str, |
| 70 | + scaled: bool = False, |
| 71 | + drop_comparison: bool = True, |
| 72 | + ): |
| 73 | + """Find the difference in the values in a pd.Series with a multi-index, between the draws (level 0) |
| 74 | + within the runs (level 1), relative to where draw = `comparison`. |
| 75 | + The comparison is `X - COMPARISON`.""" |
| 76 | + return _ser \ |
| 77 | + .unstack(level=0) \ |
| 78 | + .apply(lambda x: (x - x[comparison]) / (x[comparison] if scaled else 1.0), axis=1) \ |
| 79 | + .drop(columns=([comparison] if drop_comparison else [])) \ |
| 80 | + .stack() |
| 81 | + |
| 82 | + def do_bar_plot_with_ci(_df, annotations=None, xticklabels_horizontal_and_wrapped=False, put_labels_in_legend=True): |
| 83 | + """Make a vertical bar plot for each row of _df, using the columns to identify the height of the bar and the |
| 84 | + extent of the error bar.""" |
| 85 | + |
| 86 | + substitute_labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' |
| 87 | + |
| 88 | + yerr = np.array([ |
| 89 | + (_df['mean'] - _df['lower']).values, |
| 90 | + (_df['upper'] - _df['mean']).values, |
| 91 | + ]) |
| 92 | + |
| 93 | + xticks = {(i + 0.5): k for i, k in enumerate(_df.index)} |
| 94 | + |
| 95 | + # Define colormap (used only with option `put_labels_in_legend=True`) |
| 96 | + cmap = plt.get_cmap("tab20") |
| 97 | + rescale = lambda y: (y - np.min(y)) / (np.max(y) - np.min(y)) # noqa: E731 |
| 98 | + colors = list(map(cmap, rescale(np.array(list(xticks.keys()))))) if put_labels_in_legend else None |
| 99 | + |
| 100 | + fig, ax = plt.subplots(figsize=(10, 5)) |
| 101 | + ax.bar( |
| 102 | + xticks.keys(), |
| 103 | + _df['mean'].values, |
| 104 | + yerr=yerr, |
| 105 | + alpha=0.8, |
| 106 | + ecolor='black', |
| 107 | + color=colors, |
| 108 | + capsize=10, |
| 109 | + label=xticks.values() |
| 110 | + ) |
| 111 | + if annotations: |
| 112 | + for xpos, ypos, text in zip(xticks.keys(), _df['upper'].values, annotations): |
| 113 | + ax.text(xpos, ypos*1.15, text, horizontalalignment='center', rotation='vertical', fontsize='x-small') |
| 114 | + ax.set_xticks(list(xticks.keys())) |
| 115 | + |
| 116 | + if put_labels_in_legend: |
| 117 | + # Update xticks label with substitute labels |
| 118 | + # Insert legend with updated labels that shows correspondence between substitute label and original label |
| 119 | + xtick_values = [letter for letter, label in zip(substitute_labels, xticks.values())] |
| 120 | + xtick_legend = [f'{letter}: {label}' for letter, label in zip(substitute_labels, xticks.values())] |
| 121 | + h, legs = ax.get_legend_handles_labels() |
| 122 | + ax.legend(h, xtick_legend, loc='center left', fontsize='small', bbox_to_anchor=(1, 0.5)) |
| 123 | + ax.set_xticklabels(list(xtick_values)) |
| 124 | + else: |
| 125 | + if not xticklabels_horizontal_and_wrapped: |
| 126 | + # xticklabels will be vertical and not wrapped |
| 127 | + ax.set_xticklabels(list(xticks.values()), rotation=90) |
| 128 | + else: |
| 129 | + wrapped_labs = ["\n".join(textwrap.wrap(_lab, 20)) for _lab in xticks.values()] |
| 130 | + ax.set_xticklabels(wrapped_labs) |
| 131 | + |
| 132 | + ax.grid(axis="y") |
| 133 | + ax.spines['top'].set_visible(False) |
| 134 | + ax.spines['right'].set_visible(False) |
| 135 | + fig.tight_layout() |
| 136 | + |
| 137 | + return fig, ax |
| 138 | + |
| 139 | + # %% Define parameter names |
| 140 | + param_names = get_parameter_names_from_scenario_file() |
| 141 | + |
| 142 | + # %% Quantify the health gains associated with all interventions combined. |
| 143 | + |
| 144 | + # Absolute Number of Deaths and DALYs |
| 145 | + num_deaths = extract_results( |
| 146 | + results_folder, |
| 147 | + module='tlo.methods.demography', |
| 148 | + key='death', |
| 149 | + custom_generate_series=get_num_deaths, |
| 150 | + do_scaling=True |
| 151 | + ).pipe(set_param_names_as_column_index_level_0) |
| 152 | + |
| 153 | + num_dalys = extract_results( |
| 154 | + results_folder, |
| 155 | + module='tlo.methods.healthburden', |
| 156 | + key='dalys_stacked', |
| 157 | + custom_generate_series=get_num_dalys, |
| 158 | + do_scaling=True |
| 159 | + ).pipe(set_param_names_as_column_index_level_0) |
| 160 | + |
| 161 | + # %% Charts of total numbers of deaths / DALYS |
| 162 | + num_dalys_summarized = summarize(num_dalys).loc[0].unstack().reindex(param_names) |
| 163 | + num_deaths_summarized = summarize(num_deaths).loc[0].unstack().reindex(param_names) |
| 164 | + |
| 165 | + name_of_plot = f'Deaths, {target_period()}' |
| 166 | + fig, ax = do_bar_plot_with_ci(num_deaths_summarized / 1e6) |
| 167 | + ax.set_title(name_of_plot) |
| 168 | + ax.set_ylabel('(Millions)') |
| 169 | + fig.tight_layout() |
| 170 | + ax.axhline(num_deaths_summarized.loc['Baseline', 'mean']/1e6, color='black', alpha=0.5) |
| 171 | + fig.savefig(make_graph_file_name(name_of_plot.replace(' ', '_').replace(',', ''))) |
| 172 | + fig.show() |
| 173 | + plt.close(fig) |
| 174 | + |
| 175 | + name_of_plot = f'All Scenarios: DALYs, {target_period()}' |
| 176 | + fig, ax = do_bar_plot_with_ci(num_dalys_summarized / 1e6) |
| 177 | + ax.set_title(name_of_plot) |
| 178 | + ax.set_ylabel('(Millions)') |
| 179 | + ax.axhline(num_dalys_summarized.loc['Baseline', 'mean']/1e6, color='black', alpha=0.5) |
| 180 | + fig.tight_layout() |
| 181 | + fig.savefig(make_graph_file_name(name_of_plot.replace(' ', '_').replace(',', ''))) |
| 182 | + fig.show() |
| 183 | + plt.close(fig) |
| 184 | + |
| 185 | + |
| 186 | + # %% Deaths and DALYS averted relative to Status Quo |
| 187 | + num_deaths_averted = summarize( |
| 188 | + -1.0 * |
| 189 | + pd.DataFrame( |
| 190 | + find_difference_relative_to_comparison( |
| 191 | + num_deaths.loc[0], |
| 192 | + comparison='Baseline') |
| 193 | + ).T |
| 194 | + ).iloc[0].unstack().reindex(param_names).drop(['Baseline']) |
| 195 | + |
| 196 | + pc_deaths_averted = 100.0 * summarize( |
| 197 | + -1.0 * |
| 198 | + pd.DataFrame( |
| 199 | + find_difference_relative_to_comparison( |
| 200 | + num_deaths.loc[0], |
| 201 | + comparison='Baseline', |
| 202 | + scaled=True) |
| 203 | + ).T |
| 204 | + ).iloc[0].unstack().reindex(param_names).drop(['Baseline']) |
| 205 | + |
| 206 | + num_dalys_averted = summarize( |
| 207 | + -1.0 * |
| 208 | + pd.DataFrame( |
| 209 | + find_difference_relative_to_comparison( |
| 210 | + num_dalys.loc[0], |
| 211 | + comparison='Baseline') |
| 212 | + ).T |
| 213 | + ).iloc[0].unstack().reindex(param_names).drop(['Baseline']) |
| 214 | + |
| 215 | + pc_dalys_averted = 100.0 * summarize( |
| 216 | + -1.0 * |
| 217 | + pd.DataFrame( |
| 218 | + find_difference_relative_to_comparison( |
| 219 | + num_dalys.loc[0], |
| 220 | + comparison='Baseline', |
| 221 | + scaled=True) |
| 222 | + ).T |
| 223 | + ).iloc[0].unstack().reindex(param_names).drop(['Baseline']) |
| 224 | + |
| 225 | + # DEATHS |
| 226 | + name_of_plot = f'Additional Deaths Averted vs Baseline, {target_period()}' |
| 227 | + fig, ax = do_bar_plot_with_ci( |
| 228 | + num_deaths_averted.clip(lower=0.0), |
| 229 | + annotations=[ |
| 230 | + f"{round(row['mean'], 0)} ({round(row['lower'], 1)}-{round(row['upper'], 1)}) %" |
| 231 | + for _, row in pc_deaths_averted.clip(lower=0.0).iterrows() |
| 232 | + ] |
| 233 | + ) |
| 234 | + ax.set_title(name_of_plot) |
| 235 | + ax.set_ylabel('Additional Deaths Averted') |
| 236 | + fig.tight_layout() |
| 237 | + fig.savefig(make_graph_file_name(name_of_plot.replace(' ', '_').replace(',', ''))) |
| 238 | + fig.show() |
| 239 | + plt.close(fig) |
| 240 | + |
| 241 | + # DALYS |
| 242 | + name_of_plot = f'Additional DALYs Averted vs Baseline, {target_period()}' |
| 243 | + fig, ax = do_bar_plot_with_ci( |
| 244 | + (num_dalys_averted / 1e6).clip(lower=0.0), |
| 245 | + annotations=[ |
| 246 | + f"{round(row['mean'])} ({round(row['lower'], 1)}-{round(row['upper'], 1)}) %" |
| 247 | + for _, row in pc_dalys_averted.clip(lower=0.0).iterrows() |
| 248 | + ] |
| 249 | + ) |
| 250 | + ax.set_title(name_of_plot) |
| 251 | + ax.set_ylabel('Additional DALYS Averted \n(Millions)') |
| 252 | + fig.tight_layout() |
| 253 | + fig.savefig(make_graph_file_name(name_of_plot.replace(' ', '_').replace(',', ''))) |
| 254 | + fig.show() |
| 255 | + plt.close(fig) |
| 256 | + |
| 257 | + # todo: Neaten graphs |
| 258 | + # todo: Graph showing difference broken down by disease (this can be cribbed from the calcs about wealth from the |
| 259 | + # third set of analyses in the overview paper). |
| 260 | + # todo: other metrics of health |
| 261 | + # todo: other graphs, broken down by age/sex (this can also be cribbed from overview paper stuff) |
| 262 | + |
| 263 | +if __name__ == "__main__": |
| 264 | + parser = argparse.ArgumentParser() |
| 265 | + parser.add_argument("results_folder", type=Path) # outputs/horizontal_and_vertical_programs-2024-05-16 |
| 266 | + args = parser.parse_args() |
| 267 | + |
| 268 | + apply( |
| 269 | + results_folder=args.results_folder, |
| 270 | + output_folder=args.results_folder, |
| 271 | + resourcefilepath=Path('./resources') |
| 272 | + ) |
0 commit comments