"""Case 008: deterministic scoring and structure example. NumPy only.
256 equally weighted combinations, not sampled participants or ordinal items.
"""
import itertools
import numpy as np
dat=np.array(list(itertools.product([-1.,1.],repeat=8)))
f1,f2=dat[:,0],dat[:,1]
errors=dat[:,2:]
one_factor=errors+f1[:,None]
two_factor=errors+np.column_stack([f1,f1,f1,f2,f2,f2])
miskeyed=two_factor.copy()
miskeyed[:,0]*=-1  # deliberately wrong direction
def alpha(items):
    S=np.cov(items,rowvar=False,ddof=1)
    k=items.shape[1]
    assert k>1 and S.sum()>0
    return k/(k-1)*(1-np.trace(S)/S.sum())
results=np.array([alpha(one_factor),alpha(one_factor[:,:3]),alpha(two_factor),
                  alpha(miskeyed),alpha(two_factor[:,:3]),alpha(two_factor[:,3:])])
print("one_factor_6 one_factor_3 two_factor_6 wrong_key_6 subscale_1 subscale_2")
print(np.round(results,6))
print("Two-factor item correlations:\n",np.round(np.corrcoef(two_factor,rowvar=False),3))
corrected=miskeyed.copy()
corrected[:,0]*=-1  # correct only the known coding error
print("after_known_key_correction:",round(alpha(corrected),6))
assert len(dat)==256
assert np.allclose(results,[6/7,.75,.6,.3,.75,.75],atol=1e-10,rtol=0)
assert np.isclose(alpha(corrected),.6,atol=1e-10,rtol=0)
print("All assertions passed; NumPy",np.__version__)
