"""A finite decision rule valid for both admissible twin counts; independent mass reader."""
from collections import defaultdict
from fractions import Fraction
from pathlib import Path
import json

from compteurs15 import interval

HERE = Path(__file__).resolve().parent


def read(raw, keep_time):
    probabilities = defaultdict(Fraction)
    for label, numerator in raw['lower_numerators'].items():
        a,b,c,d = map(int,label.split(','))
        observation = (a,b,c,d) if keep_time else (a+c,b+d)
        probabilities[observation] += Fraction(int(numerator),int(raw['denominator']))
    return probabilities


def run():
    windows = json.loads((HERE/'masses15.json').read_bytes())['windows']
    dual = json.loads((HERE/'compteurs15.json').read_bytes())['windows']
    results = []
    for sample, reference in zip(windows,dual):
        laws = sample['laws']
        low,high = sorted(int(n) for n in laws if n!='J')
        decisions = {}
        for sensor in ('marked','widths'):
            j,s0,s1 = [read(laws[n],sensor=='marked') for n in ('J',str(low),str(high))]
            missing = 1-sum(j.values())
            points = sorted(j.keys()|s0.keys()|s1.keys())
            # Use the lower twin count to choose a single decision region.
            region = [point for point in points if s0[point]>j[point]]
            def advantage(s):
                return sum(s[point]-j[point] for point in region)
            # A fixed rule gives a lower bound on minimax success. The optimum
            # against the lower twin count alone gives an upper bound.
            lower = (1+min(advantage(s0),advantage(s1))-missing)/2
            upper = (1+sum(max(Fraction(0),s0[p]-j[p]) for p in points))/2
            assert upper-lower < Fraction(1,10**16)
            lo,hi = map(Fraction,reference['mixtures']['minimax_accuracy'][sensor])
            assert lower <= hi and upper >= lo
            decisions[sensor] = dict(default_on_support='S',choose_J=sorted(set(points)-set(region)),
                                     support_size=len(points),guaranteed_accuracy=interval(lower,upper))
        results.append(dict(k=sample['k'],population=sample['population'],sensors=decisions))
    return results


if __name__ == '__main__':
    print(json.dumps(run(),indent=2))
