"""Authored fixed-score threshold sweep; costs are fictional units, not monetary estimates."""
from fractions import Fraction as F
import json
SCORES=[F(v,100) for v in [95,85,75,65,55,45,35,25,15,5]]
LABELS=[1,1,0,1,0,0,0,0,1,0]
def evaluate(threshold,fp_cost,fn_cost):
    if fp_cost<0 or fn_cost<0:raise ValueError('nonnegative exercise costs')
    prediction=[int(s>=threshold) for s in SCORES]
    tp=sum(y==p==1 for y,p in zip(LABELS,prediction));tn=sum(y==p==0 for y,p in zip(LABELS,prediction));fp=sum(y==0 and p==1 for y,p in zip(LABELS,prediction));fn=sum(y==1 and p==0 for y,p in zip(LABELS,prediction))
    return {'threshold':str(threshold),'tp':tp,'tn':tn,'fp':fp,'fn':fn,'errors':fp+fn,'positive_decisions':sum(prediction),'cost':fp*fp_cost+fn*fn_cost,'accuracy':str(F(tp+tn,len(LABELS)))}
def choose(rows,key,max_positive=None):
    if max_positive is not None and (type(max_positive) is not int or not 0<=max_positive<=len(LABELS)):raise ValueError('integer capacity 0..10')
    eligible=[r for r in rows if max_positive is None or r['positive_decisions']<=max_positive]
    return min(eligible,key=lambda r:(r[key],-F(r['threshold'])))
def demo():
    rows=[evaluate(t,1,5) for t in sorted(set(SCORES+[F(1)]),reverse=True)]
    accuracy=choose(rows,'errors');cost=choose(rows,'cost');capacity=choose(rows,'cost',4)
    assert (accuracy['threshold'],accuracy['errors'],accuracy['cost'])==('17/20',2,10)
    assert (cost['threshold'],cost['errors'],cost['cost'])==('3/20',5,5)
    assert (capacity['threshold'],capacity['positive_decisions'],capacity['cost'])==('13/20',4,6)
    rejected=0
    try:evaluate(F(1,2),-1,5)
    except ValueError:rejected+=1
    try:choose(rows,'cost',True)
    except ValueError:rejected+=1
    return {'score_label_rows':[{'id':i+1,'score':str(s),'reference':y} for i,(s,y) in enumerate(zip(SCORES,LABELS))],'decision':'positive when score >= threshold','cost_units':{'false_positive':1,'false_negative':5,'unit':'arbitrary exercise unit; not currency or measured business cost'},'tie_rule':'highest threshold among equal objective values','all_thresholds':rows,'fewest_errors':accuracy,'lowest_cost':cost,'lowest_cost_with_four_positive_capacity':capacity,'rejected_invalid_contracts':rejected,'scores_are_calibrated_probabilities':False,'independent_test_performed':False,'sklearn_executed':False}
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2))
