#!/usr/bin/env python3
"""Original Brier skill score illustrations. Standard library; no network.

All records and group means are hypothetical. Fraction arithmetic preserves
exact values; this is an educational worksheet, not an inference package.
"""
from fractions import Fraction as F

OUTCOMES = [1, 1] + [0] * 8


def brier(probabilities, outcomes):
    if not outcomes or len(probabilities) != len(outcomes):
        raise ValueError('Use equally sized, nonempty matched records')
    if any(not 0 <= p <= 1 for p in probabilities) or any(y not in (0,1) for y in outcomes):
        raise ValueError('Use probabilities in [0,1] and binary outcomes')
    return sum((p-y)**2 for p,y in zip(probabilities, outcomes)) / len(outcomes)


def skill(model_bs, reference_bs):
    if model_bs < 0 or reference_bs < 0:
        raise ValueError('Mean squared errors cannot be negative')
    return None if reference_bs == 0 else 1 - model_bs / reference_bs


def main():
    model = brier([F(3,10)]*10, OUTCOMES)
    ref_50 = brier([F(1,2)]*10, OUTCOMES)
    ref_20 = brier([F(1,5)]*10, OUTCOMES)
    score_50, score_20 = skill(model,ref_50), skill(model,ref_20)
    assert (model,ref_50,ref_20) == (F(17,100),F(1,4),F(4,25))
    assert score_50 == F(8,25) and score_20 == F(-1,16)
    # Equal-sized hypothetical groups: pool error means before taking a ratio.
    model_groups = [F(2,100), F(20,100)]
    ref_groups = [F(4,100), F(25,100)]
    macro = sum(skill(m,r) for m,r in zip(model_groups,ref_groups))/2
    pooled = skill(sum(model_groups)/2, sum(ref_groups)/2)
    assert macro == F(7,20) and pooled == F(7,29)
    assert skill(F(0),F(0)) is None and skill(F(1,10),F(0)) is None
    assert skill(F(0), F(1,10)) == 1
    # Constant-reference identity for arbitrary declared c on this same sample.
    q = F(sum(OUTCOMES), len(OUTCOMES))
    for c in [F(0), F(1,5), F(3,10), F(1,2), F(1)]:
        assert brier([c]*10,OUTCOMES) == q*(1-q)+(c-q)**2
    print(f'Model BS={float(model):.6f}')
    print(f'50% reference BS={float(ref_50):.6f}; BSS={float(score_50):.6%}')
    print(f'20% reference BS={float(ref_20):.6f}; BSS={float(score_20):.6%}')
    print(f'Group macro-average={float(macro):.6%}; pooled={float(pooled):.6%}')
    print('Zero reference: BSS undefined, including 0/0.')
    print('All exact synthetic checks passed; no statistical superiority or return claim.')


if __name__ == '__main__':
    main()
