"""Correlations, partial correlations (controlling for log income) and standardised OLS on the 2022 cross-section."""
import sys, numpy as np, pandas as pd
from scipy import stats
import statsmodels.api as sm
cs = pd.read_csv(sys.argv[1] + '/cs2022.csv', index_col=0)
cs['log_gdp'] = np.log(cs.gdp_pc)
cs['log_pat'] = np.log1p(cs.patents_pm)
cs['gov'] = cs.gov_imf
OUT = ['log_gdp', 'life_exp', 'infant_mort', 'hdi', 'happiness', 'gini', 'top10', 'poverty', 'rnd', 'log_pat', 'civ_lib', 'libdem']

def partial(d, x, y, z):
    rx = sm.OLS(d[x], sm.add_constant(d[z])).fit().resid
    ry = sm.OLS(d[y], sm.add_constant(d[z])).fit().resid
    return stats.pearsonr(rx, ry)

rows = []
for y in OUT:
    for x in ['efw', 'gov']:
        d = cs[list(dict.fromkeys([x, y, 'log_gdp']))].dropna()
        r, p = stats.pearsonr(d[x], d[y]); rho, _ = stats.spearmanr(d[x], d[y])
        pr, pp = partial(d, x, y, ['log_gdp']) if y != 'log_gdp' else (np.nan, np.nan)
        rows.append(dict(outcome=y, x=x, n=len(d), r=r, p=p, rho=rho, partial_r=pr, partial_p=pp))
    d = cs[list(dict.fromkeys(['efw', 'gov', 'log_gdp', y]))].dropna()
    X = d[['efw', 'gov'] + ([] if y == 'log_gdp' else ['log_gdp'])]
    m = sm.OLS((d[y] - d[y].mean()) / d[y].std(), sm.add_constant((X - X.mean()) / X.std())).fit(cov_type='HC3')
    rows[-1]['ols'] = '; '.join(f"{k}={m.params[k]:+.2f}{'*' if m.pvalues[k] < .05 else ''}" for k in X.columns) + f' R2={m.rsquared:.2f} n={len(d)}'
res = pd.DataFrame(rows)
pd.set_option('display.width', 250)
print(res.round(3).to_string(index=False))
res.to_csv(sys.argv[1] + '/correlations.csv', index=False)

rich = cs[cs.gdp_pc > 30000]
print('\nRich countries (GDP pc PPP > 30k), n=', len(rich))
for y in ['life_exp', 'hdi', 'happiness', 'gini', 'top10', 'infant_mort', 'libdem']:
    for x in ['efw', 'gov']:
        d = rich[[x, y]].dropna()
        if len(d) > 8:
            r, p = stats.pearsonr(d[x], d[y]); print(f'  {y:12s} ~ {x:3s} r={r:+.2f} p={p:.3f} n={len(d)}')
nord = ['DNK', 'FIN', 'ISL', 'NOR', 'SWE']
print('\nNordics:'); print(cs.loc[cs.index.intersection(nord), ['country', 'efw', 'gov', 'gdp_pc', 'gini', 'happiness', 'hdi']].round(2).to_string())
print('EFW rank of Nordics:', {c: int(cs.efw.rank(ascending=False)[c]) for c in nord if c in cs.index}, 'of', cs.efw.notna().sum())
print('Gov rank of Nordics:', {c: int(cs.gov.rank(ascending=False)[c]) for c in nord if c in cs.index and pd.notna(cs.gov[c])}, 'of', cs.gov.notna().sum())
print('medians efw %.2f gov %.1f' % (cs.efw.median(), cs.gov.median()))
