"""Finite timing information in persistent twin classes. Standard Python 3.10+.

python compteurs15.py prints the release checks and results.
python compteurs15.py --laws prints all point masses for the two smaller windows.
The S numerator is exact. Each J numerator is a lower bound over a common grid.
"""
import argparse
import json
from collections import defaultdict
from fractions import Fraction as F
from itertools import product
from math import ceil, comb, factorial, floor, log, prod, sqrt
from pathlib import Path

from collisions14 import block_by_survival
from detection14 import windows

GRID = 1 << 80
HERE = Path(__file__).resolve().parent


def exclusive_row(s, t, primes):
    """Integer counts of residue draws, grouped by the surviving classes."""
    paths = {(s, t): 1}
    for p in primes:
        nxt = defaultdict(int)
        for (a, b), mass in paths.items():
            if p > a + b:
                nxt[a, b] += (p - a - b) * mass
            if a:
                nxt[a - 1, b] += a * mass
            if b:
                nxt[a, b - 1] += b * mass
        paths = nxt
    return paths


def independent_row(s, primes):
    denominator = prod(primes)
    survive = prod(p - 1 for p in primes)
    hit = denominator - survive
    num = survive**s
    scale = denominator**s
    row = {}
    for d in range(s + 1):
        weight = GRID * num // scale
        if weight:
            row[s - d, 0] = weight
        if d < s:
            num = num * (s - d) * hit // ((d + 1) * survive)
    return row


def counts(code):
    return tuple((code >> shift) & 255 for shift in (0, 8, 16, 24))


def law(model, population, twins, schedule, cap=None):
    """A cap merges outcomes above that total into a single overflow outcome."""
    assert model in ('S', 'J') and (model == 'S' or twins == 0)
    assert len(schedule) < 256
    states = {(population - 2 * twins, twins): {0: 1 if model == 'S' else GRID}}
    denominator = 1 if model == 'S' else GRID
    peaks = []
    for i, (primes, band) in enumerate(schedule):
        if band is None and i == len(schedule) - 1:
            break  # The last unobserved wheels preserve every counter mass.
        delta = 0 if band is None else 1 << (8 * (2 * band + (len(primes) == 4)))
        updated = defaultdict(lambda: defaultdict(int))
        advances = {}
        if model == 'S':
            denominator *= prod(primes)
        for (s, t), marks in states.items():
            kernel = exclusive_row(s, t, primes) if model == 'S' else independent_row(s, primes)
            for (a, b), numerator in kernel.items():
                dest = updated[a, b]
                marked = delta and s - a + 2 * (t - b) == 2
                if not marked:
                    for code, mass in marks.items():
                        dest[code] += mass * numerator
                else:
                    for code, mass in marks.items():
                        if code not in advances:
                            overflow = code == -1 or (cap is not None and sum(counts(code)) >= cap)
                            advances[code] = -1 if overflow else code + delta
                        dest[advances[code]] += mass * numerator
        if model == 'S':
            states = updated
        else:
            states = {}
            for pair, group in updated.items():
                retained = {key: value // GRID for key, value in group.items() if value >= GRID}
                if retained:
                    states[pair] = retained
        peaks.append(sum(map(len, states.values())))
    numerators = defaultdict(int)
    for group in states.values():
        for code, mass in group.items():
            numerators[code] += mass
    assert sum(numerators.values()) <= denominator
    assert model == 'J' or sum(numerators.values()) == denominator
    return dict(numerators), denominator, max(peaks, default=1)


def masses(raw):
    numerators, denominator, _ = raw
    return {key: F(n, denominator) for key, n in numerators.items()}


def project(law_, kind):
    result = defaultdict(F)
    for code, mass in law_.items():
        a, b, c, d = counts(code)
        key = {'marked': (a, b, c, d), 'widths': (a+c, b+d), 'bands': (a+b,c+d),
               'lamps': (int(a+b>0),int(c+d>0)), 'global_lamp': int(a+b+c+d>0),
               'total': a+b+c+d}[kind]
        result[key] += mass
    return result


def tv(left, right, missing):
    point = sum(abs(left.get(x, 0) - right.get(x, 0)) for x in left.keys() | right.keys()) / 2
    return max(F(0), point - missing/2), min(F(1), point + missing/2)


def formatted(x, upper=False, places=12):
    scale = 10**places
    n = ceil(scale*x) if upper else floor(scale*x)
    i, r = divmod(abs(n), scale)
    return ('-' if n < 0 else '') + f'{i}.{r:0{places}d}'


def interval(lo, hi):
    return [formatted(lo), formatted(hi, True)]


def log_bounds(x):
    """Enclose log(x) for x in [1,2] by the atanh series."""
    y = (x-1)/(x+1)
    terms = 30
    lo = 2 * sum(y**(2*n+1)/(2*n+1) for n in range(terms))
    tail = 2*y**(2*terms+1)/((2*terms+1)*(1-y*y))
    return lo, lo+tail


def poisson_cells(model):
    # Both compensated limit vectors have total mean 10/3.
    total = F(10,3)
    grid = 10**18
    e_hi = sum((-total)**i/factorial(i) for i in range(61))
    e_lo = e_hi + (-total)**61/factorial(61)
    e = F(floor(e_lo*grid),grid), F(ceil(e_hi*grid),grid)
    h_lo,h_hi = log_bounds(F(2))
    rates = []
    for start,end in ((F(1),F(3,2)),(F(3,2),F(2))):
        x,y = log_bounds(end/start)
        for width in (2,4):
            base = 2*(width-(model=='S'))*(1/start-1/end)
            lo,hi = (base+x/h_hi,base+y/h_lo) if model=='S' else (base,base)
            share = F(width,6)
            rates.append((F(floor(grid*share*lo),grid),F(ceil(grid*share*hi),grid)))
    return rates, e


def poisson_error(distribution, missing, model):
    """TV = 1 - overlap. Finite support makes a Poisson tail cutoff unnecessary."""
    rates,e = poisson_cells(model)
    overlap_lo = overlap_hi = F(0)
    for code,p in distribution.items():
        lo,hi = e
        for n, (a,b) in zip(counts(code),rates):
            lo *= a**n / factorial(n)
            hi *= b**n / factorial(n)
        overlap_lo += min(p,lo)
        overlap_hi += min(p,hi)
    return interval(max(F(0),1-overlap_hi-missing),1-overlap_lo)


def witness(s_laws, j_law, missing):
    """Opposite signs throughout a mixture of the supplied S alternatives."""
    fibres = defaultdict(list)
    for code in set(j_law).union(*s_laws):
        if code == -1:
            continue
        a,b,c,d = counts(code)
        values = [law_.get(code,0)-j_law.get(code,0) for law_ in s_laws]
        fibres[a+c,b+d].append((counts(code),min(values)-missing,max(values)))
    best = None
    for label, rows in sorted(fibres.items()):
        positive = max(rows, key=lambda r:(r[1],r[0]))
        negative = min(rows, key=lambda r:(r[2],r[0]))
        bound = min(positive[1],-negative[2])
        if bound > 0 and (best is None or bound > best[0]):
            best = bound,label,positive,negative
    if best is None:
        return None
    score,label,positive,negative = best
    return dict(width_totals=label,positive=positive[0],S_minus_J_positive=interval(*positive[1:]),
                negative=negative[0],S_minus_J_negative=interval(*negative[1:]),
                tv_gain_at_least=formatted(score))


def no_loss(s_law, j_law, missing, schedule):
    # Enumerate the entire possible observation box, even for an empty DP cell.
    limits = [sum(band == b and len(ps) == m for ps,band in schedule)
              for b in (0,1) for m in (2,4)]
    signs = defaultdict(list)
    for point in product(*(range(n+1) for n in limits)):
        code = sum(n << (8*i) for i,n in enumerate(point))
        upper = s_law.get(code,0) - j_law.get(code,0)
        signs[point[0]+point[2],point[1]+point[3]].append((upper-missing,upper))
    return all(len(rows)==1 or all(lo>=0 for lo,_ in rows) or all(hi<=0 for _,hi in rows)
               for rows in signs.values())


def mixture_range(s_laws, j_law, missing):
    # With prior weight w for the upper twin count, every difference is affine.
    # Absolute values change slope only at roots of fine or projected differences.
    lines = {'marked': [], 'widths': []}
    breaks = {F(0), F(1)}
    for kind in lines:
        lower,upper = [project(law_,kind) for law_ in s_laws]
        base = project(j_law,kind)
        for point in lower.keys() | upper.keys() | base.keys():
            start = lower[point] - base[point]
            slope = upper[point] - lower[point]
            lines[kind].append((start,slope))
            if slope and 0 < -start/slope < 1:
                breaks.add(-start/slope)
    distances = {kind:[sum(abs(start+w*slope) for start,slope in terms)/2
                       for w in sorted(breaks)] for kind,terms in lines.items()}
    values = [a-b for a,b in zip(distances['marked'],distances['widths'])]
    # The L1 defect of the lower grid law is 'missing' before and after projection.
    low, high = min(values), max(values)
    minima = {kind:min(ds) for kind,ds in distances.items()}
    # Minimax theorem for this finite game: minimize TV over the S mixture
    # separately for each sensor to find the best guaranteed test accuracy.
    advantage = (minima['marked']-minima['widths'])/2
    guaranteed = {kind:interval((1+v)/2-missing/4,(1+v)/2+missing/4)
                  for kind,v in minima.items()}
    return dict(breakpoints=len(breaks),minimum_tv_gain=interval(max(0,low-missing),low+missing),
                maximum_tv_gain=interval(max(0,high-missing),high+missing),
                minimax_accuracy=guaranteed,
                minimax_accuracy_gain=interval(max(0,advantage-missing/2),advantage+missing/2))


def certify(k, save_laws=False, cap=None):
    population = round(2*sqrt(k*log(k)))
    t0 = floor(log(k)/log(2))
    schedule = windows(k)
    j_raw = law('J',population,0,schedule,cap)
    j_law = masses(j_raw)
    missing = 1-sum(j_law.values())
    s_laws, alternatives = [], []
    complete = cap is None
    j_limit = poisson_error(j_law,missing,'J') if complete else None
    raw_laws = {'J':j_raw}
    previous = json.loads((HERE/'detection14.json').read_bytes())
    previous = next(row for row in previous['trials'] if row['k']==k)
    for twins in (t0,t0+1):
        raw = law('S',population,twins,schedule,cap)
        raw_laws[str(twins)] = raw
        s_law = masses(raw)
        s_laws.append(s_law)
        result = dict(twins=twins,peak_states=raw[2],witness=witness([s_law],j_law,missing))
        if complete:
            comparison = {}
            for kind in ('marked','widths','bands','lamps','global_lamp','total'):
                comparison[kind] = tv(project(s_law,kind),project(j_law,kind),missing)
            fine,coarse = comparison['marked'], comparison['widths']
            result['distances'] = {kind:interval(*bounds) for kind,bounds in comparison.items()}
            result['gain'] = interval(max(F(0),fine[0]-coarse[1]),fine[1]-coarse[0])
            result['exact_zero_certified'] = no_loss(s_law,j_law,missing,schedule)
            if result['exact_zero_certified']:
                result['gain'] = interval(F(0),F(0))
            result['S_to_limit'] = poisson_error(s_law,F(0),'S')
            if twins == previous['twins_S']:
                s_lamps,j_lamps = project(s_law,'lamps'),project(j_law,'lamps')
                for kind,select in [('whole',any),('early',lambda x:x[0]),('late',lambda x:x[1])]:
                    ref = previous['events'][kind]
                    for model,dist,err in [('S',s_lamps,0),('J',j_lamps,missing)]:
                        event = sum(p for x,p in dist.items() if select(x))
                        assert F(ref[model][0]) <= event+err and event <= F(ref[model][1])
        alternatives.append(result)
    if save_laws:
        weights = {key:dict(denominator=str(value[1]), lower_numerators={
            ','.join(map(str,counts(i))) if i!=-1 else 'overflow':str(v) for i,v in sorted(value[0].items())})
            for key,value in raw_laws.items()}
        return dict(k=k,population=population,counts_order=['early 2','early 4','late 2','late 4'],
                    laws=weights)
    result = dict(k=k,population=population,cap=cap,missing_J=str(missing),peak_J=j_raw[2],
                  J_to_limit=j_limit,alternatives=alternatives,
                  common_witness=witness(s_laws,j_law,missing))
    if complete:
        result['mixtures'] = mixture_range(s_laws,j_law,missing)
        if any(r['exact_zero_certified'] for r in alternatives):
            result['mixtures']['minimum_tv_gain'] = interval(F(0),F(0))
    return result


def labelled(sites, groups, model):
    initial = (1 << len(sites))-1
    states = {(initial,0):F(1)}
    for primes,band in groups:
        step = defaultdict(F)
        delta = 1 << (8*(2*band+(len(primes)==4)))
        kernels = {mask:block_by_survival(sites,primes,(),model,mask) for mask,_ in states}
        for (mask,code), mass in states.items():
            for keep,probability in kernels[mask].items():
                losses = mask.bit_count()-keep.bit_count()
                step[keep,code+(delta if losses==2 else 0)] += mass*probability
        states = step
    result = defaultdict(F)
    for (_,code),mass in states.items():
        result[code] += mass
    return result


def small_checks():
    primes = [5,7,11,13,17,19]
    groups = [(primes[:2],0),(primes[2:],1)]
    product_ = prod(primes)
    # Fixed pairs (site 0 with site 3), and a pair that changes from 0 to 1.
    rotating = next(i for i in range(0,product_+1,35) if i%prod(primes[2:])==1)
    differences = {}
    for model in ('S','J'):
        persistent = labelled((0,1,2,product_),groups,model)
        moved = labelled((0,1,2,rotating),groups,model)
        differences[model] = str(tv(persistent,moved,F(0))[0])
        assert differences[model] != '0'
        sites = (0,1,2,product_) if model=='S' else (0,1,2,3)
        reference = labelled(sites,groups,model)
        lower = masses(law(model,4,int(model=='S'),groups))
        assert all(lower.get(i,0)<=reference.get(i,0) for i in set(lower)|set(reference))
        assert 1-sum(lower.values()) < F(1,10**18)
    return dict(primes=primes,rotating_site=rotating,fixed_site=product_,tv_fixed_rotating=differences)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--laws',action='store_true')
    parser.add_argument('--target',type=int,choices=(100,250,1000),
                        help='test only outcomes totalling at most one double')
    options = parser.parse_args()
    if options.target:
        answer = certify(options.target,cap=1)
    else:
        answer = dict(small=small_checks(),windows=[certify(k,options.laws) for k in (100,250)])
    print(json.dumps(answer,indent=2))
