"""Authored exhaustive paired-label swap test of mean difference under specified exchangeability; not bootstrap."""
from fractions import Fraction as F
from itertools import product
import json
PAIRS=[(F(3),F(1)),(F(2),F(1)),(F(4),F(3)),(F(1),F(2))]
def exact(differences):
    observed=sum(differences,F(0))/len(differences);rows=[]
    for signs in product([-1,1],repeat=len(differences)):
        stat=sum((s*d for s,d in zip(signs,differences)),F(0))/len(differences)
        rows.append({'signs':list(signs),'mean_difference':str(stat),'absolute_at_least_observed':abs(stat)>=abs(observed)})
    p=F(sum(r['absolute_at_least_observed'] for r in rows),len(rows));return observed,p,rows
def demo():
    differences=[a-b for a,b in PAIRS];observed,p,rows=exact(differences)
    assert observed==F(3,4) and p==F(1,2) and len(rows)==16
    assert exact([-d for d in differences])[1]==p
    assert exact([F(0)]*4)[1]==1 and exact([F(1)]*4)[1]==F(1,8)
    return {'authored_paired_scores':[[str(a),str(b)] for a,b in PAIRS],'differences_A_minus_B':[str(d) for d in differences],'observed_mean_difference':str(observed),'exhaustive_sign_assignments':rows,'null_tail_count':sum(r['absolute_at_least_observed'] for r in rows),'null_assignments':len(rows),'two_sided_absolute_tail_p':str(p),'all_four_positive_smallest_example_p':'1/8','all_zero_example_p':'1','null_assumptions_not_verified_by_authored_table':['A/B labels exchangeable within each pair under the null','valid independent paired experimental units or corresponding valid randomization design'],'sign_assignments_count_with_multiplicity_not_unique_statistics':True,'Monte_Carlo_plus_one_adjustment_not_used_because_all_assignments_enumerated':True,'bootstrap_CI_or_scipy_or_real_model_test':False}
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2))
