-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreamlit_app.py
More file actions
2925 lines (2453 loc) · 126 KB
/
streamlit_app.py
File metadata and controls
2925 lines (2453 loc) · 126 KB
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
"""
Streamlit Web Interface for Hypertension Microsimulation Model.
Cost-Effectiveness Analysis comparing IXA-001 vs Spironolactone
in adults with resistant hypertension.
Enhanced version with full parameter exposure.
"""
import streamlit as st
import numpy as np
import pandas as pd
from typing import Optional, Dict, List, Any
from io import BytesIO
import sys
from pathlib import Path
from dataclasses import dataclass, field
# Add src to path
sys.path.insert(0, str(Path(__file__).parent))
from src import run_cea, CEAResults, Treatment
from src.population import PopulationParams, PopulationGenerator
from src.patient import Patient, CardiacState, RenalState, NeuroState
from src.simulation import Simulation, SimulationConfig, SimulationResults
from src.risk_assessment import BaselineRiskProfile
from src.costs.costs import CostInputs, US_COSTS, UK_COSTS
from src.psa import (
PSARunner, PSAResults, PSAIteration,
ParameterDistribution, CorrelationGroup, CholeskySampler,
get_default_parameter_distributions, get_default_correlation_groups
)
# Page configuration
st.set_page_config(
page_title="CEA Microsimulation - IXA-001",
page_icon="🫀",
layout="wide",
initial_sidebar_state="expanded",
)
# Custom CSS
st.markdown("""
<style>
.main-header {
font-size: 2rem;
font-weight: bold;
color: #1F4E79;
margin-bottom: 0.5rem;
}
.sub-header {
font-size: 1.2rem;
color: #666;
margin-bottom: 2rem;
}
.metric-card {
background-color: #f8f9fa;
border-radius: 8px;
padding: 1rem;
margin: 0.5rem 0;
}
.risk-high { color: #dc3545; font-weight: bold; }
.risk-moderate { color: #fd7e14; }
.risk-low { color: #28a745; }
.param-section {
border-left: 3px solid #1F4E79;
padding-left: 10px;
margin: 10px 0;
}
</style>
""", unsafe_allow_html=True)
@dataclass
class ExtendedPopulationParams(PopulationParams):
"""Extended population parameters with additional comorbidities."""
# Additional comorbidities
copd_prev: float = 0.17
depression_prev: float = 0.27
anxiety_prev: float = 0.17
substance_use_prev: float = 0.10
smi_prev: float = 0.04
afib_prev: float = 0.10
pad_prev: float = 0.15
# SGLT2i settings
sglt2_uptake_rate: float = 0.40
# Additional bounds
age_min: float = 40.0
age_max: float = 85.0
sbp_min: float = 140.0
sbp_max: float = 200.0
egfr_min: float = 15.0
egfr_max: float = 120.0
@dataclass
class TreatmentParams:
"""Configurable treatment effect parameters."""
# IXA-001
ixa_sbp_reduction: float = 20.0
ixa_sbp_reduction_sd: float = 8.0
ixa_discontinuation_rate: float = 0.12
# Spironolactone
spiro_sbp_reduction: float = 9.0
spiro_sbp_reduction_sd: float = 6.0
spiro_discontinuation_rate: float = 0.15
# Standard care
standard_sbp_reduction: float = 3.0
standard_discontinuation_rate: float = 0.10
# Adherence
adherence_effect_multiplier: float = 0.30 # Effect when non-adherent
@dataclass
class ClinicalParams:
"""Configurable clinical parameters."""
# Case fatality rates (30-day mortality)
cfr_mi: float = 0.08
cfr_ischemic_stroke: float = 0.10
cfr_hemorrhagic_stroke: float = 0.25
cfr_hf: float = 0.05
# Stroke distribution
stroke_ischemic_fraction: float = 0.85
# Post-event mortality (annual)
post_mi_year1_mortality: float = 0.05
post_mi_thereafter_mortality: float = 0.03
post_stroke_year1_mortality: float = 0.10
post_stroke_thereafter_mortality: float = 0.05
hf_annual_mortality: float = 0.08
esrd_annual_mortality: float = 0.15
# Prior event risk multipliers
prior_mi_multiplier: float = 2.5
prior_stroke_multiplier: float = 3.0
prior_hf_multiplier: float = 2.0
prior_tia_multiplier: float = 2.0
# Cognitive decline rates (annual)
normal_to_mci_rate: float = 0.02
mci_to_dementia_rate: float = 0.10
normal_to_dementia_rate: float = 0.005
# eGFR decline (annual mL/min)
egfr_decline_under_40: float = 0.0
egfr_decline_40_65: float = 1.0
egfr_decline_over_65: float = 1.5
# Safety thresholds
hyperkalemia_threshold: float = 5.5 # K+ mmol/L
@dataclass
class UtilityParams:
"""Configurable utility/QALY parameters."""
# Baseline by age
baseline_utility_40: float = 0.90
baseline_utility_50: float = 0.87
baseline_utility_60: float = 0.84
baseline_utility_70: float = 0.80
baseline_utility_80: float = 0.75
baseline_utility_90: float = 0.70
# Disutilities (decrements)
disutility_uncontrolled_htn: float = 0.04
disutility_post_mi: float = 0.12
disutility_post_stroke: float = 0.18
disutility_acute_hf: float = 0.25
disutility_chronic_hf: float = 0.15
disutility_ckd_3a: float = 0.01
disutility_ckd_3b: float = 0.03
disutility_ckd_4: float = 0.06
disutility_esrd: float = 0.35
disutility_diabetes: float = 0.04
# Acute event disutilities
acute_disutility_mi: float = 0.20
acute_disutility_stroke: float = 0.40
acute_disutility_hf: float = 0.25
@dataclass
class CustomCostInputs:
"""Custom cost inputs allowing user modification."""
# Drug costs (monthly)
ixa_001_monthly: float = 500.0
spironolactone_monthly: float = 15.0
sglt2_inhibitor_monthly: float = 450.0
background_therapy_monthly: float = 75.0
lab_test_cost_k: float = 15.0
# Acute event costs
mi_acute: float = 25000.0
ischemic_stroke_acute: float = 15200.0
hemorrhagic_stroke_acute: float = 22500.0
tia_acute: float = 2100.0
hf_admission: float = 18000.0
# Annual management costs
controlled_htn_annual: float = 800.0
uncontrolled_htn_annual: float = 1200.0
post_mi_annual: float = 5500.0
post_stroke_annual: float = 12000.0
heart_failure_annual: float = 15000.0
ckd_stage_3a_annual: float = 2500.0
ckd_stage_3b_annual: float = 4500.0
ckd_stage_4_annual: float = 8000.0
esrd_annual: float = 90000.0
# Indirect costs
daily_wage: float = 240.0
absenteeism_mi_days: int = 7
absenteeism_stroke_days: int = 30
absenteeism_hf_days: int = 5
disability_multiplier_stroke: float = 0.20
disability_multiplier_hf: float = 0.15
def format_currency(value: float, symbol: str = "$") -> str:
"""Format currency value."""
if abs(value) >= 1_000_000:
return f"{symbol}{value/1_000_000:,.1f}M"
elif abs(value) >= 1_000:
return f"{symbol}{value/1_000:,.1f}K"
else:
return f"{symbol}{value:,.0f}"
def run_simulation_with_progress(
n_patients: int,
time_horizon: int,
perspective: str,
seed: int,
discount_rate: float,
pop_params: PopulationParams,
status_container,
custom_costs: Optional[CustomCostInputs] = None,
treatment_params: Optional[TreatmentParams] = None,
clinical_params: Optional[ClinicalParams] = None,
) -> tuple:
"""Run the CEA simulation with progress indicators."""
# Update population params
pop_params.n_patients = n_patients
pop_params.seed = seed
total_cycles = time_horizon * 12 # Monthly cycles
# Create simulation config
config = SimulationConfig(
n_patients=n_patients,
time_horizon_months=total_cycles,
seed=seed,
cost_perspective=perspective,
discount_rate=discount_rate,
show_progress=False
)
# Create progress elements inside the status container using write
progress_placeholder = status_container.empty()
def update_progress(phase: str, pct: int, detail: str):
"""Update progress display."""
progress_placeholder.markdown(f"""
**{phase}**
{detail}
{'█' * (pct // 5)}{'░' * (20 - pct // 5)} {pct}%
""")
# ===== Phase 1: Generate IXA-001 Population =====
update_progress("Phase 1/5: Generating IXA-001 population", 0, "Creating patient cohort...")
generator = PopulationGenerator(pop_params)
patients_ixa = generator.generate()
baseline_profiles_ixa = [p.baseline_risk_profile for p in patients_ixa]
update_progress("Phase 1/5: Generating IXA-001 population", 100, f"Generated {n_patients} patients")
# ===== Phase 2: Run IXA-001 Simulation =====
sim = Simulation(config)
# Apply custom costs if provided
if custom_costs:
_apply_custom_costs(sim, custom_costs)
# Run simulation with progress updates
results_ixa = _run_simulation_with_callback(
sim, patients_ixa, Treatment.IXA_001, total_cycles,
lambda pct, txt: update_progress("Phase 2/5: Simulating IXA-001 arm", pct, txt),
"IXA-001", treatment_params, clinical_params
)
# ===== Phase 3: Generate Spironolactone Population =====
update_progress("Phase 3/5: Generating Spironolactone population", 0, "Creating comparator cohort...")
pop_params_comp = PopulationParams(
n_patients=n_patients, seed=seed,
age_mean=pop_params.age_mean, age_sd=pop_params.age_sd,
prop_male=pop_params.prop_male,
sbp_mean=pop_params.sbp_mean, sbp_sd=pop_params.sbp_sd,
egfr_mean=pop_params.egfr_mean, egfr_sd=pop_params.egfr_sd,
uacr_mean=pop_params.uacr_mean, uacr_sd=pop_params.uacr_sd,
total_chol_mean=pop_params.total_chol_mean, hdl_chol_mean=pop_params.hdl_chol_mean,
bmi_mean=pop_params.bmi_mean, bmi_sd=pop_params.bmi_sd,
diabetes_prev=pop_params.diabetes_prev, smoker_prev=pop_params.smoker_prev,
dyslipidemia_prev=pop_params.dyslipidemia_prev,
prior_mi_prev=pop_params.prior_mi_prev, prior_stroke_prev=pop_params.prior_stroke_prev,
heart_failure_prev=pop_params.heart_failure_prev,
adherence_prob=pop_params.adherence_prob,
)
generator_comp = PopulationGenerator(pop_params_comp)
patients_spi = generator_comp.generate()
baseline_profiles_spi = [p.baseline_risk_profile for p in patients_spi]
update_progress("Phase 3/5: Generating Spironolactone population", 100, f"Generated {n_patients} patients")
# ===== Phase 4: Run Spironolactone Simulation =====
results_spi = _run_simulation_with_callback(
sim, patients_spi, Treatment.SPIRONOLACTONE, total_cycles,
lambda pct, txt: update_progress("Phase 4/5: Simulating Spironolactone arm", pct, txt),
"Spironolactone", treatment_params, clinical_params
)
# ===== Phase 5: Calculate Results =====
update_progress("Phase 5/5: Calculating cost-effectiveness", 50, "Computing ICER and outcomes...")
cea = CEAResults(intervention=results_ixa, comparator=results_spi)
cea.calculate_icer()
update_progress("Phase 5/5: Calculating cost-effectiveness", 100, "Analysis complete!")
# Clear progress and show completion
progress_placeholder.empty()
status_container.update(label="Simulation complete!", state="complete")
return cea, patients_ixa, patients_spi, baseline_profiles_ixa
def _apply_custom_costs(sim: Simulation, custom_costs: CustomCostInputs):
"""Apply custom cost parameters to simulation."""
sim.costs.ixa_001_monthly = custom_costs.ixa_001_monthly
sim.costs.spironolactone_monthly = custom_costs.spironolactone_monthly
sim.costs.sglt2_inhibitor_monthly = custom_costs.sglt2_inhibitor_monthly
sim.costs.background_therapy_monthly = custom_costs.background_therapy_monthly
sim.costs.lab_test_cost_k = custom_costs.lab_test_cost_k
sim.costs.mi_acute = custom_costs.mi_acute
sim.costs.ischemic_stroke_acute = custom_costs.ischemic_stroke_acute
sim.costs.hemorrhagic_stroke_acute = custom_costs.hemorrhagic_stroke_acute
sim.costs.tia_acute = custom_costs.tia_acute
sim.costs.hf_admission = custom_costs.hf_admission
sim.costs.controlled_htn_annual = custom_costs.controlled_htn_annual
sim.costs.uncontrolled_htn_annual = custom_costs.uncontrolled_htn_annual
sim.costs.post_mi_annual = custom_costs.post_mi_annual
sim.costs.post_stroke_annual = custom_costs.post_stroke_annual
sim.costs.heart_failure_annual = custom_costs.heart_failure_annual
sim.costs.ckd_stage_3a_annual = custom_costs.ckd_stage_3a_annual
sim.costs.ckd_stage_3b_annual = custom_costs.ckd_stage_3b_annual
sim.costs.ckd_stage_4_annual = custom_costs.ckd_stage_4_annual
sim.costs.esrd_annual = custom_costs.esrd_annual
sim.costs.daily_wage = custom_costs.daily_wage
sim.costs.absenteeism_acute_mi_days = custom_costs.absenteeism_mi_days
sim.costs.absenteeism_stroke_days = custom_costs.absenteeism_stroke_days
sim.costs.absenteeism_hf_days = custom_costs.absenteeism_hf_days
sim.costs.disability_multiplier_stroke = custom_costs.disability_multiplier_stroke
sim.costs.disability_multiplier_hf = custom_costs.disability_multiplier_hf
def _run_simulation_with_callback(sim, patients, treatment, total_cycles, progress_callback, arm_name,
treatment_params=None, clinical_params=None, n_sample_patients=5):
"""Run simulation with progress updates and detailed logging for sample patients."""
from src.patient import Treatment as TreatmentEnum
results = SimulationResults(treatment=treatment, n_patients=len(patients))
# Initialize detailed simulation log for sample patients
sample_ids = list(range(min(n_sample_patients, len(patients))))
simulation_log = {pid: {
'patient_id': pid,
'initial_age': patients[pid].age,
'initial_sbp': patients[pid].current_sbp,
'initial_egfr': patients[pid].egfr,
'treatment': treatment.value,
'has_diabetes': patients[pid].has_diabetes,
'has_hf': patients[pid].has_heart_failure,
'cycles': []
} for pid in sample_ids}
# Assign treatment to all patients
for patient in patients:
sim.treatment_mgr.assign_treatment(patient, treatment)
if patient.on_sglt2_inhibitor:
results.sglt2_users += 1
n_cycles = int(sim.config.time_horizon_months / sim.config.cycle_length_months)
update_interval = max(1, n_cycles // 20) # Update progress ~20 times
log_interval = max(1, n_cycles // 60) # Log ~60 times (every ~8 months for 40yr sim)
for cycle in range(n_cycles):
# Update progress bar periodically
if cycle % update_interval == 0:
progress_pct = int((cycle / n_cycles) * 100)
years_simulated = cycle / 12
progress_callback(progress_pct, f"Simulating {arm_name}: Year {years_simulated:.1f}/{sim.config.time_horizon_months/12:.0f}")
for patient in patients:
if not patient.is_alive:
continue
# Check adherence
adherence_changed = sim.adherence_transition.check_adherence_change(patient)
if adherence_changed:
sim.treatment_mgr.update_effect_for_adherence(patient)
# Safety checks for Spironolactone
is_quarterly = (int(patient.time_in_simulation) % 3 == 0)
hyperkalemia_stop = False
if is_quarterly and patient.treatment == TreatmentEnum.SPIRONOLACTONE:
patient.accrue_costs(sim.costs.lab_test_cost_k)
if sim.treatment_mgr.check_safety_stop_rules(patient):
sim.treatment_mgr.assign_treatment(patient, TreatmentEnum.STANDARD_CARE)
patient.hyperkalemia_history += 1
hyperkalemia_stop = True
# Neuro progression
old_neuro = patient.neuro_state
sim.neuro_transition.check_neuro_progression(patient)
neuro_changed = patient.neuro_state != old_neuro
if neuro_changed and patient.neuro_state.value == "dementia":
results.dementia_cases += 1
# Cardiac events - calculate transition probabilities
probs = sim.transition_calc.calculate_transitions(patient)
new_event = sim.transition_calc.sample_event(patient, probs)
# Log detailed calculations for sample patients
if patient.patient_id in sample_ids and cycle % log_interval == 0:
cycle_log = {
'cycle': cycle,
'year': cycle / 12,
'age': patient.age,
'sbp': patient.current_sbp,
'true_sbp': getattr(patient, 'true_mean_sbp', patient.current_sbp),
'egfr': patient.egfr,
'is_adherent': patient.is_adherent,
'adherence_changed': adherence_changed,
'cardiac_state': patient.cardiac_state.value if hasattr(patient.cardiac_state, 'value') else str(patient.cardiac_state),
'renal_state': patient.renal_state.value if hasattr(patient.renal_state, 'value') else str(patient.renal_state),
'neuro_state': patient.neuro_state.value if hasattr(patient.neuro_state, 'value') else str(patient.neuro_state),
'probs': {
'p_mi': probs.to_mi,
'p_ischemic_stroke': probs.to_ischemic_stroke,
'p_hemorrhagic_stroke': probs.to_hemorrhagic_stroke,
'p_tia': probs.to_tia,
'p_hf': probs.to_hf,
'p_cv_death': probs.to_cv_death,
'p_non_cv_death': probs.to_non_cv_death,
},
'event': new_event.value if hasattr(new_event, 'value') else str(new_event) if new_event else None,
'neuro_changed': neuro_changed,
'hyperkalemia_stop': hyperkalemia_stop,
'cumulative_costs': patient.cumulative_costs,
'cumulative_qalys': patient.cumulative_qalys,
'treatment_effect': patient._treatment_effect_mmhg,
}
simulation_log[patient.patient_id]['cycles'].append(cycle_log)
if new_event:
if new_event == CardiacState.NON_CV_DEATH:
results.non_cv_deaths += 1
patient.cardiac_state = CardiacState.NON_CV_DEATH
else:
sim._record_event(new_event, results)
patient.transition_cardiac(new_event)
from src.costs.costs import get_event_cost, get_acute_absenteeism_cost
event_cost = get_event_cost(new_event.value, sim.costs)
absenteeism_cost = get_acute_absenteeism_cost(new_event.value, sim.costs, patient.age)
years = patient.time_in_simulation / 12
discount = 1 / ((1 + sim.config.discount_rate) ** years)
patient.accrue_costs(event_cost * discount)
results.total_costs += event_cost * discount
results.total_indirect_costs += absenteeism_cost * discount
if not patient.is_alive:
continue
# Accrue outcomes
sim._accrue_outcomes(patient, results)
# Update SBP
old_sbp = patient.current_sbp
patient.update_sbp(patient._treatment_effect_mmhg, sim.rng)
# Advance time and check renal
old_renal = patient.renal_state
patient.advance_time(sim.config.cycle_length_months)
from src.patient import RenalState
if patient.renal_state != old_renal:
if patient.renal_state == RenalState.ESRD:
results.esrd_events += 1
elif patient.renal_state == RenalState.CKD_STAGE_4:
results.ckd_4_events += 1
# Check discontinuation
if sim.treatment_mgr.check_discontinuation(patient):
patient.treatment = TreatmentEnum.STANDARD_CARE
# Final progress update
progress_callback(100, f"{arm_name} simulation complete!")
# Store patient results
for patient in patients:
results.patient_results.append(patient.to_dict())
results.calculate_means()
# Attach simulation log to results
results.simulation_log = simulation_log
return results
def analyze_subgroups(patients: List[Patient], results: SimulationResults, profiles: List[BaselineRiskProfile]) -> Dict:
"""Analyze results by subgroups."""
subgroup_data = {
'framingham': {'Low': [], 'Borderline': [], 'Intermediate': [], 'High': []},
'kdigo': {'Low': [], 'Moderate': [], 'High': [], 'Very High': []},
'gcua': {'I': [], 'II': [], 'III': [], 'IV': [], 'Moderate': [], 'Low': []},
'eocri': {'A': [], 'B': [], 'C': [], 'Low': []},
'age': {'<60': [], '60-70': [], '70-80': [], '80+': []},
'ckd_stage': {'Stage 1-2': [], 'Stage 3a': [], 'Stage 3b': [], 'Stage 4': [], 'ESRD': []},
'primary_aldosteronism': {'With PA': [], 'Without PA': []}, # IXA-001 target population
'secondary_htn_etiology': {'PA': [], 'RAS': [], 'Pheo': [], 'OSA': [], 'Essential': []}, # All secondary causes
}
for i, (patient, profile) in enumerate(zip(patients, profiles)):
patient_data = results.patient_results[i] if i < len(results.patient_results) else {}
# Framingham category
if profile.framingham_category:
if profile.framingham_category in subgroup_data['framingham']:
subgroup_data['framingham'][profile.framingham_category].append(patient_data)
# KDIGO risk level
if profile.kdigo_risk_level:
if profile.kdigo_risk_level in subgroup_data['kdigo']:
subgroup_data['kdigo'][profile.kdigo_risk_level].append(patient_data)
# GCUA phenotype
if profile.gcua_phenotype:
if profile.gcua_phenotype in subgroup_data['gcua']:
subgroup_data['gcua'][profile.gcua_phenotype].append(patient_data)
# EOCRI phenotype (age 18-59, eGFR >60)
if profile.eocri_phenotype:
if profile.eocri_phenotype in subgroup_data['eocri']:
subgroup_data['eocri'][profile.eocri_phenotype].append(patient_data)
# Age groups
age = patient_data.get('age', patient.age)
if age < 60:
subgroup_data['age']['<60'].append(patient_data)
elif age < 70:
subgroup_data['age']['60-70'].append(patient_data)
elif age < 80:
subgroup_data['age']['70-80'].append(patient_data)
else:
subgroup_data['age']['80+'].append(patient_data)
# CKD stage
renal = patient_data.get('renal_state', patient.renal_state.value if hasattr(patient.renal_state, 'value') else str(patient.renal_state))
if 'stage_1_2' in str(renal).lower() or 'ckd_stage_1_2' in str(renal).lower():
subgroup_data['ckd_stage']['Stage 1-2'].append(patient_data)
elif 'stage_3a' in str(renal).lower():
subgroup_data['ckd_stage']['Stage 3a'].append(patient_data)
elif 'stage_3b' in str(renal).lower():
subgroup_data['ckd_stage']['Stage 3b'].append(patient_data)
elif 'stage_4' in str(renal).lower():
subgroup_data['ckd_stage']['Stage 4'].append(patient_data)
elif 'esrd' in str(renal).lower():
subgroup_data['ckd_stage']['ESRD'].append(patient_data)
# Primary Aldosteronism (IXA-001 target population - 15-20% of resistant HTN)
has_pa = getattr(patient, 'has_primary_aldosteronism', False)
if has_pa:
subgroup_data['primary_aldosteronism']['With PA'].append(patient_data)
else:
subgroup_data['primary_aldosteronism']['Without PA'].append(patient_data)
# Secondary HTN Etiology (PA, RAS, Pheo, OSA, Essential)
etiology = getattr(profile, 'secondary_htn_etiology', None)
if etiology and etiology in subgroup_data['secondary_htn_etiology']:
subgroup_data['secondary_htn_etiology'][etiology].append(patient_data)
elif not etiology:
# Fallback: determine from patient attributes
if getattr(patient, 'has_pheochromocytoma', False):
subgroup_data['secondary_htn_etiology']['Pheo'].append(patient_data)
elif getattr(patient, 'has_primary_aldosteronism', False):
subgroup_data['secondary_htn_etiology']['PA'].append(patient_data)
elif getattr(patient, 'has_renal_artery_stenosis', False):
subgroup_data['secondary_htn_etiology']['RAS'].append(patient_data)
elif getattr(patient, 'has_obstructive_sleep_apnea', False) and getattr(patient, 'osa_severity', '') == 'severe':
subgroup_data['secondary_htn_etiology']['OSA'].append(patient_data)
else:
subgroup_data['secondary_htn_etiology']['Essential'].append(patient_data)
return subgroup_data
def generate_excel_report(cea: CEAResults, pop_params: PopulationParams,
subgroup_data: Dict, currency: str,
custom_costs: Optional[CustomCostInputs] = None,
treatment_params: Optional[TreatmentParams] = None,
clinical_params: Optional[ClinicalParams] = None) -> BytesIO:
"""Generate comprehensive Excel report with charts and formatting."""
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side, NamedStyle
from openpyxl.chart import BarChart, LineChart, Reference
from openpyxl.utils import get_column_letter
wb = Workbook()
# ===== Professional color palette =====
PRIMARY_DARK = "1F4E79"
PRIMARY_MED = "2E75B6"
PRIMARY_LIGHT = "BDD7EE"
ACCENT_GREEN = "C6EFCE"
ACCENT_GREEN_DARK = "006100"
ACCENT_YELLOW = "FFEB9C"
ACCENT_RED = "FFC7CE"
ACCENT_RED_DARK = "9C0006"
NEUTRAL_LIGHT = "F2F2F2"
# ===== Style definitions =====
header_font = Font(bold=True, color="FFFFFF", size=11)
header_fill = PatternFill(start_color=PRIMARY_DARK, end_color=PRIMARY_DARK, fill_type="solid")
subheader_fill = PatternFill(start_color=PRIMARY_MED, end_color=PRIMARY_MED, fill_type="solid")
subheader_font = Font(bold=True, color="FFFFFF", size=10)
alt_row_fill = PatternFill(start_color=NEUTRAL_LIGHT, end_color=NEUTRAL_LIGHT, fill_type="solid")
highlight_fill = PatternFill(start_color=ACCENT_GREEN, end_color=ACCENT_GREEN, fill_type="solid")
warning_fill = PatternFill(start_color=ACCENT_YELLOW, end_color=ACCENT_YELLOW, fill_type="solid")
error_fill = PatternFill(start_color=ACCENT_RED, end_color=ACCENT_RED, fill_type="solid")
result_fill = PatternFill(start_color="E2EFDA", end_color="E2EFDA", fill_type="solid")
title_font = Font(bold=True, size=20, color=PRIMARY_DARK)
subtitle_font = Font(bold=True, size=14, color=PRIMARY_MED)
border = Border(
left=Side(style='thin', color='B4B4B4'),
right=Side(style='thin', color='B4B4B4'),
top=Side(style='thin', color='B4B4B4'),
bottom=Side(style='thin', color='B4B4B4')
)
thick_border = Border(
left=Side(style='medium', color=PRIMARY_DARK),
right=Side(style='medium', color=PRIMARY_DARK),
top=Side(style='medium', color=PRIMARY_DARK),
bottom=Side(style='medium', color=PRIMARY_DARK)
)
center_align = Alignment(horizontal='center', vertical='center')
right_align = Alignment(horizontal='right', vertical='center')
currency_sym = currency
def apply_table_style(ws, start_row, end_row, num_cols, start_col=1):
for row_idx in range(start_row, end_row + 1):
for col_idx in range(start_col, start_col + num_cols):
cell = ws.cell(row=row_idx, column=col_idx)
cell.border = border
if row_idx == start_row:
cell.font = header_font
cell.fill = header_fill
cell.alignment = center_align
elif (row_idx - start_row) % 2 == 0:
cell.fill = alt_row_fill
def create_section_header(ws, text, row, col=1, span=4):
ws.merge_cells(start_row=row, start_column=col, end_row=row, end_column=col + span - 1)
cell = ws.cell(row=row, column=col, value=text)
cell.font = header_font
cell.fill = header_fill
cell.alignment = center_align
return row + 1
# ========== Sheet 1: Executive Summary ==========
ws = wb.active
ws.title = "Executive Summary"
# Header banner
for col in range(1, 6):
ws.cell(row=1, column=col).fill = header_fill
ws.cell(row=2, column=col).fill = header_fill
ws.merge_cells('A1:E1')
ws['A1'] = "COST-EFFECTIVENESS ANALYSIS REPORT"
ws['A1'].font = Font(bold=True, size=20, color="FFFFFF")
ws['A1'].alignment = center_align
ws.merge_cells('A2:E2')
ws['A2'] = "IXA-001 vs Spironolactone in Resistant Hypertension | v4.0"
ws['A2'].font = Font(bold=False, size=12, color="FFFFFF", italic=True)
ws['A2'].alignment = center_align
# Key Results Section
row = 4
ws.merge_cells(f'A{row}:C{row}')
ws[f'A{row}'] = "KEY RESULTS"
ws[f'A{row}'].font = header_font
ws[f'A{row}'].fill = header_fill
ws[f'A{row}'].alignment = center_align
# Determine cost-effectiveness interpretation
is_dominant = cea.icer is None or (cea.incremental_costs < 0 and cea.incremental_qalys > 0)
is_cost_effective = cea.icer and cea.icer < 100000
is_marginally_ce = cea.icer and 100000 <= cea.icer < 150000
if is_dominant:
interpretation = "DOMINANT (Lower cost, better outcomes)"
interp_fill = highlight_fill
interp_color = ACCENT_GREEN_DARK
elif is_cost_effective:
interpretation = "COST-EFFECTIVE (ICER < $100,000/QALY)"
interp_fill = highlight_fill
interp_color = ACCENT_GREEN_DARK
elif is_marginally_ce:
interpretation = "MARGINAL ($100K-$150K/QALY)"
interp_fill = warning_fill
interp_color = "9C5700"
else:
interpretation = "REVIEW REQUIRED (ICER > $150,000/QALY)"
interp_fill = error_fill
interp_color = ACCENT_RED_DARK
results_data = [
("Incremental Costs", f"{currency_sym}{cea.incremental_costs:,.0f}", None),
("Incremental QALYs", f"{cea.incremental_qalys:.3f}", None),
("ICER", f"{currency_sym}{cea.icer:,.0f}/QALY" if cea.icer else "DOMINANT", highlight_fill if is_dominant else None),
("Interpretation", interpretation, interp_fill),
]
for i, (label, value, fill) in enumerate(results_data, start=5):
cell_label = ws.cell(row=i, column=1, value=label)
cell_label.font = Font(bold=True, color=PRIMARY_DARK)
cell_label.border = border
cell_value = ws.cell(row=i, column=2, value=value)
cell_value.border = border
cell_value.alignment = right_align
if fill:
cell_value.fill = fill
if "DOMINANT" in str(value) or "COST-EFFECTIVE" in str(value):
cell_value.font = Font(bold=True, color=ACCENT_GREEN_DARK)
elif "MARGINAL" in str(value):
cell_value.font = Font(bold=True, color="9C5700")
elif "REVIEW" in str(value):
cell_value.font = Font(bold=True, color=ACCENT_RED_DARK)
else:
cell_value.fill = result_fill
cell_value.font = Font(bold=True)
# Extend value cell
ws.merge_cells(f'B{i}:C{i}')
# Population Summary Section
pop_row = 10
ws.merge_cells(f'A{pop_row}:C{pop_row}')
ws[f'A{pop_row}'] = "POPULATION CHARACTERISTICS"
ws[f'A{pop_row}'].font = header_font
ws[f'A{pop_row}'].fill = header_fill
ws[f'A{pop_row}'].alignment = center_align
pop_data = [
("Cohort Size", f"{pop_params.n_patients:,} per arm"),
("Mean Age", f"{pop_params.age_mean:.0f} years (SD {pop_params.age_sd:.0f})"),
("% Male", f"{pop_params.prop_male*100:.0f}%"),
("Mean SBP", f"{pop_params.sbp_mean:.0f} mmHg"),
("Mean eGFR", f"{pop_params.egfr_mean:.0f} mL/min/1.73m²"),
("Diabetes", f"{pop_params.diabetes_prev*100:.0f}%"),
("Prior MI", f"{pop_params.prior_mi_prev*100:.0f}%"),
("Heart Failure", f"{pop_params.heart_failure_prev*100:.0f}%"),
]
for i, (label, value) in enumerate(pop_data, start=pop_row+1):
cell_label = ws.cell(row=i, column=1, value=label)
cell_label.border = border
cell_value = ws.cell(row=i, column=2, value=value)
cell_value.border = border
if (i - pop_row) % 2 == 0:
cell_label.fill = alt_row_fill
cell_value.fill = alt_row_fill
# Set column widths
ws.column_dimensions['A'].width = 25
ws.column_dimensions['B'].width = 30
ws.column_dimensions['C'].width = 20
# Freeze header
ws.freeze_panes = 'A4'
# ========== Sheet 2: Clinical Events ==========
ws2 = wb.create_sheet("Clinical Events")
ws2['A1'] = "Clinical Events Comparison"
ws2['A1'].font = title_font
events_header = ["Event", "IXA-001", "Spironolactone", "Difference"]
events_data = [
["MI", cea.intervention.mi_events, cea.comparator.mi_events],
["Stroke (Total)", cea.intervention.stroke_events, cea.comparator.stroke_events],
[" Ischemic", cea.intervention.ischemic_stroke_events, cea.comparator.ischemic_stroke_events],
[" Hemorrhagic", cea.intervention.hemorrhagic_stroke_events, cea.comparator.hemorrhagic_stroke_events],
["TIA", cea.intervention.tia_events, cea.comparator.tia_events],
["Heart Failure", cea.intervention.hf_events, cea.comparator.hf_events],
["CV Death", cea.intervention.cv_deaths, cea.comparator.cv_deaths],
["Non-CV Death", cea.intervention.non_cv_deaths, cea.comparator.non_cv_deaths],
["CKD Stage 4", cea.intervention.ckd_4_events, cea.comparator.ckd_4_events],
["ESRD", cea.intervention.esrd_events, cea.comparator.esrd_events],
["Dementia", cea.intervention.dementia_cases, cea.comparator.dementia_cases],
]
ws2.append([])
ws2.append(events_header)
for row in events_data:
diff = row[2] - row[1] # Comparator - Intervention (positive = events avoided)
ws2.append([row[0], row[1], row[2], diff])
apply_table_style(ws2, 3, 3 + len(events_data), 4)
# Bar chart
chart = BarChart()
chart.type = "col"
chart.grouping = "clustered"
chart.title = "Clinical Events per 1000 Patients"
chart.y_axis.title = "Number of Events"
chart.style = 10
data = Reference(ws2, min_col=2, min_row=3, max_col=3, max_row=9)
cats = Reference(ws2, min_col=1, min_row=4, max_row=9)
chart.add_data(data, titles_from_data=True)
chart.set_categories(cats)
chart.width = 15
chart.height = 10
ws2.add_chart(chart, "F3")
ws2.column_dimensions['A'].width = 20
ws2.column_dimensions['B'].width = 15
ws2.column_dimensions['C'].width = 15
ws2.column_dimensions['D'].width = 15
# ========== Sheet 3: Cost Analysis ==========
ws3 = wb.create_sheet("Cost Analysis")
ws3['A1'] = "Cost Breakdown Analysis"
ws3['A1'].font = title_font
direct_ixa = cea.intervention.mean_costs - (cea.intervention.total_indirect_costs / cea.intervention.n_patients)
indirect_ixa = cea.intervention.total_indirect_costs / cea.intervention.n_patients
direct_spi = cea.comparator.mean_costs - (cea.comparator.total_indirect_costs / cea.comparator.n_patients)
indirect_spi = cea.comparator.total_indirect_costs / cea.comparator.n_patients
cost_header = ["Cost Category", "IXA-001", "Spironolactone", "Difference"]
cost_data = [
["Direct Costs", f"{currency_sym}{direct_ixa:,.0f}", f"{currency_sym}{direct_spi:,.0f}", f"{currency_sym}{direct_ixa - direct_spi:,.0f}"],
["Indirect Costs", f"{currency_sym}{indirect_ixa:,.0f}", f"{currency_sym}{indirect_spi:,.0f}", f"{currency_sym}{indirect_ixa - indirect_spi:,.0f}"],
["Total Costs", f"{currency_sym}{cea.intervention.mean_costs:,.0f}", f"{currency_sym}{cea.comparator.mean_costs:,.0f}", f"{currency_sym}{cea.incremental_costs:,.0f}"],
]
ws3.append([])
ws3.append(cost_header)
for row in cost_data:
ws3.append(row)
apply_table_style(ws3, 3, 3 + len(cost_data), 4)
# Cost parameters used (if custom)
if custom_costs:
ws3['A10'] = "COST PARAMETERS USED"
ws3['A10'].font = subtitle_font
cost_params = [
["Parameter", "Value"],
["IXA-001 Monthly", f"{currency_sym}{custom_costs.ixa_001_monthly:,.0f}"],
["Spironolactone Monthly", f"{currency_sym}{custom_costs.spironolactone_monthly:,.0f}"],
["SGLT2i Monthly", f"{currency_sym}{custom_costs.sglt2_inhibitor_monthly:,.0f}"],
["MI Acute", f"{currency_sym}{custom_costs.mi_acute:,.0f}"],
["Stroke (Ischemic)", f"{currency_sym}{custom_costs.ischemic_stroke_acute:,.0f}"],
["Stroke (Hemorrhagic)", f"{currency_sym}{custom_costs.hemorrhagic_stroke_acute:,.0f}"],
["HF Admission", f"{currency_sym}{custom_costs.hf_admission:,.0f}"],
["ESRD Annual", f"{currency_sym}{custom_costs.esrd_annual:,.0f}"],
]
for i, row in enumerate(cost_params, start=11):
for j, val in enumerate(row, start=1):
cell = ws3.cell(row=i, column=j, value=val)
if i == 11:
cell.font = header_font
cell.fill = subheader_fill
ws3.column_dimensions['A'].width = 25
ws3.column_dimensions['B'].width = 20
ws3.column_dimensions['C'].width = 20
ws3.column_dimensions['D'].width = 20
# ========== Sheet 4: Subgroup Analysis ==========
ws4 = wb.create_sheet("Subgroup Analysis")
ws4['A1'] = "Subgroup Analysis"
ws4['A1'].font = title_font
current_row = 3
for subgroup_name, subgroup_cats in [
("Age Group", subgroup_data['age']),
("Framingham CVD Risk", subgroup_data['framingham']),
("KDIGO Risk Level", subgroup_data['kdigo']),
("GCUA Phenotype", subgroup_data['gcua']),
]:
ws4.cell(row=current_row, column=1, value=f"By {subgroup_name}").font = subtitle_font
current_row += 1
ws4.cell(row=current_row, column=1, value="Category")
ws4.cell(row=current_row, column=2, value="N Patients")
ws4.cell(row=current_row, column=3, value="Mean Costs")
ws4.cell(row=current_row, column=4, value="Mean QALYs")
header_row = current_row
for cat, patients in subgroup_cats.items():
n = len(patients)
if n > 0:
current_row += 1
mean_costs = np.mean([p.get('cumulative_costs', 0) for p in patients])
mean_qalys = np.mean([p.get('cumulative_qalys', 0) for p in patients])
ws4.cell(row=current_row, column=1, value=cat)
ws4.cell(row=current_row, column=2, value=n)
ws4.cell(row=current_row, column=3, value=f"{currency_sym}{mean_costs:,.0f}")
ws4.cell(row=current_row, column=4, value=f"{mean_qalys:.3f}")
apply_table_style(ws4, header_row, current_row, 4)
current_row += 2
ws4.column_dimensions['A'].width = 20
ws4.column_dimensions['B'].width = 15
ws4.column_dimensions['C'].width = 15
ws4.column_dimensions['D'].width = 15
# ========== Sheet 5: WTP Analysis ==========
ws5 = wb.create_sheet("WTP Analysis")
ws5['A1'] = "Willingness-to-Pay Analysis"
ws5['A1'].font = title_font
ws5.append([])
wtp_header = ["WTP Threshold", "NMB IXA-001", "NMB Spironolactone", "Incremental NMB", "Cost-Effective?"]
ws5.append(wtp_header)
wtp_values = [0, 25000, 50000, 75000, 100000, 150000, 200000]
for wtp in wtp_values:
nmb_ixa = cea.intervention.mean_qalys * wtp - cea.intervention.mean_costs
nmb_spi = cea.comparator.mean_qalys * wtp - cea.comparator.mean_costs
inc_nmb = nmb_ixa - nmb_spi
ce = "Yes" if inc_nmb > 0 else "No"
ws5.append([f"{currency_sym}{wtp:,}/QALY", f"{currency_sym}{nmb_ixa:,.0f}", f"{currency_sym}{nmb_spi:,.0f}", f"{currency_sym}{inc_nmb:,.0f}", ce])
apply_table_style(ws5, 3, 3 + len(wtp_values), 5)
# Highlight cost-effective rows
for row in range(4, 4 + len(wtp_values)):
if ws5.cell(row=row, column=5).value == "Yes":
for col in range(1, 6):
ws5.cell(row=row, column=col).fill = highlight_fill
for col in ['A', 'B', 'C', 'D', 'E']:
ws5.column_dimensions[col].width = 18
# ========== Sheet 6: Parameters ==========
ws6 = wb.create_sheet("Parameters")
ws6['A1'] = "Simulation Parameters"
ws6['A1'].font = title_font
current_row = 3
# Demographics
ws6.cell(row=current_row, column=1, value="DEMOGRAPHICS").font = Font(bold=True, color="FFFFFF")
ws6.cell(row=current_row, column=1).fill = header_fill
ws6.merge_cells(f'A{current_row}:B{current_row}')
current_row += 1
demo_params = [
["Mean Age (years)", f"{pop_params.age_mean:.0f} (SD {pop_params.age_sd:.0f})"],
["Age Range", f"{pop_params.age_min:.0f} - {pop_params.age_max:.0f}"],
["% Male", f"{pop_params.prop_male*100:.0f}%"],
["Mean BMI", f"{pop_params.bmi_mean:.1f}"],
]