import json
import numpy as np
from scipy.stats import norm
from p01trials import register,run_trials,deflated_sharpe,pbo,stationary_indices,reality_spa,effective_trials,cluster_count
def test_register(tmp_path):
    x=np.arange(30.).reshape(10,3);m=register(tmp_path/'trials.npz',x,[{'id':i} for i in range(3)],11)
    assert m['shape']==[10,3] and json.loads((tmp_path/'trials.json').read_text())['sha256']==m['sha256']
    assert np.array_equal(np.load(tmp_path/'trials.npz')['returns'],x)
    generated,m2=run_trials(tmp_path/'generated.npz',[{'i':0},{'i':1}],lambda c:np.arange(5)+c['i'],9)
    assert generated.shape==(5,2) and len(m2['configurations'])==2
def test_dsr_one_trial():
    x=np.random.default_rng(1).normal(.1,1,100)
    val,threshold=deflated_sharpe(x,[x.mean()/x.std(ddof=1)])
    assert 0<=val<=1 and threshold==0
def test_blocks_and_pbo():
    rng=np.random.default_rng(2); x=rng.normal(size=(120,5))
    prob,logits=pbo(x);assert 0<=prob<=1 and len(logits)==20
    idx=stationary_indices(120,10,6,rng);assert idx.shape==(10,120) and idx.min()>=0 and idx.max()<120
    assert 1<=effective_trials(x)<=5.000001
    assert cluster_count(np.c_[x[:,0],x[:,0],x[:,1]],.7)==2
def test_bootstrap_pvalues():
    d=np.random.default_rng(3).normal(size=(100,4));p,q=reality_spa(d,b=19,mean_block=5)
    assert .05<=p<=1 and .05<=q<=1
