"""Constructed teaching cases only. Run: python3 causal_design_lab.py"""
from math import sqrt
old_n=1000;old_yes=600;new_n=1000;new_yes=650
p_old=old_yes/old_n;p_new=new_yes/new_n
rd=p_new-p_old
se=sqrt(p_old*(1-p_old)/old_n+p_new*(1-p_new)/new_n)
lo=rd-1.96*se;hi=rd+1.96*se
assert abs(rd-.05)<1e-12
assert abs(se-.021621748310439653)<1e-12
assert abs(lo-.007621373311538282)<1e-12
assert abs(hi-.09237862668846172)<1e-12
new_missing=100;old_missing=50
new_seen_yes=585;old_seen_yes=570
bound_lo=new_seen_yes/1000-(old_seen_yes+old_missing)/1000
bound_hi=(new_seen_yes+new_missing)/1000-old_seen_yes/1000
assert abs(bound_lo+.035)<1e-12 and abs(bound_hi-.115)<1e-12
did=(.75-.60)-(.80-.70)
assert abs(did-.05)<1e-12
routine_old=40/50;routine_new=45/50
complex_old=10/50;complex_new=20/50
standardised=.5*(routine_new+complex_new)-.5*(routine_old+complex_old)
assert abs(standardised-.15)<1e-12
old_month=(80*.8+20*.2)/100
new_month=(20*.9+80*.4)/100
common_mix_old=.5*.8+.5*.2
common_mix_new=.5*.9+.5*.4
assert abs(old_month-.68)<1e-12 and abs(new_month-.50)<1e-12
assert abs(common_mix_new-common_mix_old-.15)<1e-12
assert abs(new_month-old_month+.18)<1e-12
rare_comparator_weight=1/(1-.99)
assert abs(rare_comparator_weight-100)<1e-10
print('TRIAL RATE OLD',p_old,'NEW',p_new,'DIFFERENCE',round(rd,4))
print('INDEPENDENT-CASE APPROXIMATE SE',round(se,6),'95% INTERVAL',round(lo,6),round(hi,6))
print('CRUDE MISSING-OUTCOME CONTRAST BOUNDS',round(bound_lo,4),round(bound_hi,4))
print('DIFFERENCE-IN-DIFFERENCES',round(did,4))
print('EQUAL-MIX DESCRIPTIVE CONTRAST',round(standardised,4))
print('CHANGING-MIX CRUDE OLD',round(old_month,4),'NEW',round(new_month,4),'DIFFERENCE',round(new_month-old_month,4))
print('CHANGING-MIX COMMON-MIX CONTRAST',round(common_mix_new-common_mix_old,4))
print('RARE COMPARATOR WEIGHT AT e=0.99',round(rare_comparator_weight,4))
print('CAUSAL DESIGN ARITHMETIC CHECKS PASS')
