import numpy as np
from scipy.ndimage import rotate
from scipy.stats import ks_2samp, hypergeom
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression

X, y = load_digits(return_X_y=True)
X = X / 16
train, pool = train_test_split(np.arange(len(y)), test_size=.7, stratify=y, random_state=31)
cal, pool = train_test_split(pool, test_size=.8, stratify=y[pool], random_state=32)
pca = PCA(n_components=8, random_state=33).fit(X[train])
clf = LogisticRegression(max_iter=400, C=2).fit(X[train], y[train])
cal_conf = clf.predict_proba(X[cal]).max(axis=1)
cal_acc = np.mean(clf.predict(X[cal]) == y[cal])
threshold = np.quantile(cal_conf, 1-cal_acc)
print('train, cal, pool', len(train), len(cal), len(pool), 'cal_acc', round(cal_acc,4), 'ATC threshold', round(threshold,4))

def mmd2(K, i, j):
    a, b, c = K[np.ix_(i, i)], K[np.ix_(j, j)], K[np.ix_(i, j)]
    return (a.sum()-np.trace(a))/(len(i)*(len(i)-1)) + (b.sum()-np.trace(b))/(len(j)*(len(j)-1)) - 2*c.mean()

def mmd_p(X, Y, rng, B=99):
    Z = np.vstack((X, Y)); n = len(X); d = ((Z[:,None]-Z[None,:])**2).sum(axis=2)
    # Pooled distances, invariant to label permutations.
    sigma2 = np.median(d[np.triu_indices(len(Z),1)])
    K = np.exp(-d/(2*max(sigma2,1e-12)))
    i, j = np.arange(n), np.arange(n,len(Z)); obs = mmd2(K,i,j)
    vals=[]
    for _ in range(B):
        order = rng.permutation(len(Z)); vals.append(mmd2(K,order[:n],order[n:]))
    return (1+np.sum(np.array(vals)>=obs))/(B+1)

def run(mode, magnitude, n, seed):
    rng = np.random.default_rng(seed)
    # Equal class prior for reference and target except for label shift.
    a = rng.choice(pool, n, replace=False)
    rest = np.setdiff1d(pool, a)
    if mode == 'label':
        weights = np.where(y[rest] == 0, 1+9*magnitude, 1.)
        b = rng.choice(rest, n, replace=False, p=weights/weights.sum())
    else:
        b = rng.choice(rest, n, replace=False)
    A, B = X[a].copy(), X[b].copy()
    if mode == 'noise': B = np.clip(B + rng.normal(0,magnitude,B.shape),0,1)
    if mode in ('rotation','subpopulation'):
        changed = np.ones(n, dtype=bool) if mode == 'rotation' else rng.random(n) < magnitude
        angle = 24 if mode == 'subpopulation' else magnitude*30
        if np.any(changed):
            B[changed] = np.array([rotate(row.reshape(8,8), angle, reshape=False, order=1).ravel() for row in B[changed]])
    AP, BP = pca.transform(A), pca.transform(B)
    pa, pb = clf.predict_proba(A), clf.predict_proba(B)
    pca_reject = min(ks_2samp(AP[:,k], BP[:,k]).pvalue for k in range(8)) < .05/8
    bbsd_reject = min(ks_2samp(pa[:,k], pb[:,k]).pvalue for k in range(10)) < .05/10
    mmd_reject = mmd_p(AP,BP,rng) <= .05
    # Independent holdout, balanced in each domain. Condition on the predicted
    # positive count and permute the balanced domain labels analytically.
    split=n//2
    domain=LogisticRegression(max_iter=200).fit(np.vstack((AP[:split],BP[:split])),np.r_[np.zeros(split),np.ones(split)])
    pred=domain.predict(np.vstack((AP[split:],BP[split:])))
    truth=np.r_[np.zeros(n-split),np.ones(n-split)]
    positives=int(pred.sum()); hits=int(pred[n-split:].sum())
    c2st_reject=hypergeom.sf(hits-1,len(truth),positives,n-split) < .05
    return np.array([pca_reject,bbsd_reject,mmd_reject,c2st_reject],float), np.mean(clf.predict(B)==y[b]), np.mean(pb.max(axis=1)>threshold)

if __name__ == '__main__':
    import json
    from pathlib import Path
    out = {}
    for mode in ['noise','rotation','label','subpopulation']:
        out[mode] = {}
        for n in [32,64,128]:
            points=[]
            for mag in [0,.5,1]:
                scale = .35*mag if mode == 'noise' else mag
                samples = [run(mode, scale, n, 1000+i) for i in range(20)]
                points.append({'magnitude':mag, 'power':np.mean([r[0] for r in samples],axis=0).tolist(), 'accuracy':float(np.mean([r[1] for r in samples])), 'atc':float(np.mean([r[2] for r in samples]))})
            out[mode][n]=points
            print(mode,n,points,flush=True)
    Path('power.json').write_text(json.dumps(out,indent=2),encoding='utf-8')
