"""Authored point/global, contextual residual, and contiguous-window anomaly rules; no universal detector."""
from fractions import Fraction as F
import json
CONTEXT=['low']*3+['high']*3
REFERENCE=[(c,v) for _ in range(2) for c,v in zip(CONTEXT,[F(2)]*3+[F(10)]*3)]
def demo():
    means={c:sum((v for k,v in REFERENCE if k==c),F(0))/sum(k==c for k,v in REFERENCE) for c in ['low','high']}
    lo=min(v for c,v in REFERENCE);hi=max(v for c,v in REFERENCE)
    cases={'normal':[F(2)]*3+[F(10)]*3,'point':[F(30),F(2),F(2)]+[F(10)]*3,'context':[F(10),F(2),F(2)]+[F(10)]*3,'collective':[F(7,2)]*3+[F(10)]*3};rows=[]
    for name,values in cases.items():
        residual=[v-means[c] for c,v in zip(CONTEXT,values)]
        global_flags=[i for i,v in enumerate(values) if v<lo or v>hi]
        contextual=[i for i,r in enumerate(residual) if abs(r)>3]
        windows=[{'start_index':i,'end_index_inclusive':i+2,'mean_residual':str(sum(residual[i:i+3],F(0))/3),'flag':abs(sum(residual[i:i+3],F(0))/3)>1} for i in range(4)]
        rows.append({'case':name,'values':[str(v) for v in values],'contexts':CONTEXT,'residuals':[str(r) for r in residual],'global_outside_reference_min_max_indices':global_flags,'absolute_context_residual_gt3_indices':contextual,'three_contiguous_point_windows':windows})
    by={r['case']:r for r in rows}
    assert not by['normal']['global_outside_reference_min_max_indices'] and not any(w['flag'] for w in by['normal']['three_contiguous_point_windows'])
    assert by['point']['global_outside_reference_min_max_indices']==[0]
    assert not by['context']['global_outside_reference_min_max_indices'] and by['context']['absolute_context_residual_gt3_indices']==[0]
    assert not by['collective']['global_outside_reference_min_max_indices'] and not by['collective']['absolute_context_residual_gt3_indices']
    assert by['collective']['three_contiguous_point_windows'][0]['mean_residual']=='3/2' and by['collective']['three_contiguous_point_windows'][0]['flag']
    return {'authored_reference':[{'context':c,'value':str(v)} for c,v in REFERENCE],'context_means_fit_on_reference_only':{c:str(v) for c,v in means.items()},'global_closed_reference_range':[str(lo),str(hi)],'authored_thresholds_not_error_rate_calibrated':{'point':'outside reference min/max','context':'abs(residual)>3','collective':'abs(mean residual of3 contiguous points)>1'},'rows':rows,'rules_mutually_exclusive':False,'semantic_anomaly_truth_or_false_alarm_rate_measured':False,'forecast_or_ml_library_executed':False}
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2))
