#!/usr/bin/env python3
"""Original synthetic binary-forecast lesson. Standard library; no network.

Probabilities are fractions. The web calculator's separate text input uses
percentages. These examples do not estimate a venue's or model's performance.
"""
from fractions import Fraction as F
from collections import defaultdict

ROWS = [(F(p), int(i < yes_count))
        for p, yes_count in [('0.2', 0), ('0.4', 1), ('0.6', 3), ('0.8', 5)]
        for i in range(5)]


def reliability_points(rows, n_bins=10):
    if not rows or not isinstance(n_bins, int) or isinstance(n_bins, bool) or n_bins < 1:
        raise ValueError('Use nonempty binary records and a positive bin count')
    groups = defaultdict(list)
    for p, y in rows:
        if not 0 <= p <= 1 or y not in (0, 1):
            raise ValueError('Probability must be in [0,1]; outcome must be 0 or 1')
        # Lower-inclusive intervals, with 1 in the final bin. Exact fractions.
        index = min(n_bins - 1, int(p * n_bins))
        groups[index].append((p, y))
    return [(index, len(g), sum(p for p, _ in g)/len(g),
             F(sum(y for _, y in g), len(g)))
            for index, g in sorted(groups.items())]


def exact_value_decomposition(rows):
    """Group by identical forecast values, not arbitrary coarse bin means."""
    n = len(rows)
    q = F(sum(y for _, y in rows), n)
    groups = defaultdict(list)
    for p, y in rows:
        groups[p].append(y)
    rel = sum(F(len(ys), n) * (p - F(sum(ys), len(ys)))**2
              for p, ys in groups.items())
    res = sum(F(len(ys), n) * (F(sum(ys), len(ys)) - q)**2
              for ys in groups.values())
    unc = q * (1 - q)
    raw = sum((p-y)**2 for p, y in rows) / n
    return raw, rel, res, unc


def main():
    points = reliability_points(ROWS)
    gap = sum(F(count, len(ROWS)) * abs(p-y) for _, count, p, y in points)
    print('bin,count,mean_p,yes_frequency')
    for index, count, p, y in points:
        print(f'{index},{count},{float(p):.2f},{float(y):.2f}')
    raw, rel, res, unc = exact_value_decomposition(ROWS)
    assert [(p, y) for _, _, p, y in points] == [
        (F(1,5), F(0)), (F(2,5), F(1,5)), (F(3,5), F(3,5)), (F(4,5), F(1))]
    assert gap == F(3, 20)
    assert (raw, rel, res, unc) == (F(13,100), F(3,100), F(59,400), F(99,400))
    assert raw == rel - res + unc
    pair = [(F(2,5), 1), (F(3,5), 0)]
    coarse = reliability_points(pair, 1)
    fine = reliability_points(pair, 2)
    coarse_gap = sum(F(n,2)*abs(p-y) for _, n, p, y in coarse)
    fine_gap = sum(F(n,2)*abs(p-y) for _, n, p, y in fine)
    assert coarse_gap == 0 and fine_gap == F(3,5)
    assert reliability_points([(F(0),0),(F(1,5),1),(F(1),1)],10)[-1][0] == 9
    print(f'Weighted absolute Yes-probability gap: {float(gap):.6f}')
    print(f'Brier score: {float(raw):.6f}')
    print(f'Exact decomposition: {float(rel):.6f} - {float(res):.6f} + {float(unc):.6f}')
    print(f'Two-record gap: one bin={float(coarse_gap):.2f}, two bins={float(fine_gap):.2f}')
    print('All exact synthetic checks passed; no population or trading claim.')


if __name__ == '__main__':
    main()
