"""Original Lawfare Academy mathematics lab. All arithmetic uses fictional data."""
import math
from statistics import mean

def dot(x, w):
    if len(x) != len(w):
        raise ValueError('Mismatched shapes')
    return sum(a*b for a,b in zip(x,w))

def central_difference(f, x, h=1e-4):
    return (f(x+h)-f(x-h))/(2*h)

def counts(prevalence, sensitivity, specificity, n=10000):
    positives = n*prevalence
    tp = positives*sensitivity
    fp = (n-positives)*(1-specificity)
    return tp, fp, tp/(tp+fp)

def metrics(truth, scores, threshold):
    predicted = [s >= threshold for s in scores]
    tp = sum(y == 1 and p for y,p in zip(truth,predicted))
    fp = sum(y == 0 and p for y,p in zip(truth,predicted))
    fn = sum(y == 1 and not p for y,p in zip(truth,predicted))
    return {'alerts':tp+fp, 'precision':tp/(tp+fp) if tp+fp else None,
            'recall':tp/(tp+fn) if tp+fn else None}

def main():
    assert dot([2,3],[10,5]) == 35
    try:
        dot([1],[2,3])
        raise AssertionError('shape guard failed')
    except ValueError:
        pass
    loss = lambda w:(2*w-6)**2
    assert math.isclose(central_difference(loss,1),-16,rel_tol=1e-8)
    assert math.isclose(counts(.01,.8,.9)[2],80/1070)
    assert math.isclose(counts(.2,.8,.9)[2],2/3)
    training, heldout = [2,None,6], [100,None]
    fill = mean(x for x in training if x is not None)
    assert [fill if x is None else x for x in heldout] == [100,4]
    truth, scores = [0,1,0,1], [.2,.4,.6,.8]
    low,high=metrics(truth,scores,.3),metrics(truth,scores,.7)
    assert low == {'alerts':3,'precision':2/3,'recall':1}
    assert high == {'alerts':1,'precision':1,'recall':.5}
    print('PASS: shapes, gradient check, prevalence sensitivity, train-only imputation and threshold metrics')

if __name__ == '__main__':
    main()
