"""Bit-packed prefix grid and worst-case checks for selective merging (Python 3.10+)."""
import json
from math import exp, sqrt, prod, fsum

A0 = 2.5 / (2 * (1 + sqrt(.5))**2)
DELTA = .5 - A0


def leading(h, size, ones):
    return exp(-(2.5*(h-size) + A0*size + DELTA*ones)/h)


def grid_width(h, k, tolerance):
    if h <= 0 or k < 0 or tolerance < 0:
        raise ValueError("positive H and nonnegative k and tolerance required")
    return h+1 if k == 0 else 1 + int(tolerance*h/(2*DELTA*k))


def encode(word, width):
    """Pack one threshold crossing per complete grid cell, low bit first."""
    if width < 1 or any(x not in (0, 1) for x in word):
        raise ValueError("a positive width and binary symbols are required")
    payload = bytearray((len(word)//width + 7)//8)
    previous = total = 0
    for i, bit in enumerate(word, 1):
        total += bit
        if i % width == 0:
            block = i//width - 1
            crossing = total//width - previous
            payload[block//8] |= crossing << (block % 8)
            previous = total//width
    return bytes(payload)


def estimate(h, width, payload, intervals):
    """Sorted disjoint half-open intervals; rows and queries use zero-based indices."""
    if width < 1 or h < 1 or len(payload) != (h//width+7)//8:
        raise ValueError("invalid message dimensions")
    def prefix(end):
        n = end//width
        full, tail = divmod(n, 8)
        bits = sum(byte.bit_count() for byte in payload[:full])
        if tail:
            bits += (payload[full] & ((1<<tail)-1)).bit_count()
        return width*bits
    total = size = end = 0
    for left, right in intervals:
        if not end <= left < right <= h:
            raise ValueError("invalid interval")
        total += prefix(right)-prefix(left)
        size += right-left
        end = right
    return min(size,max(0,total))


def runs(mask, h):
    intervals = []
    for i in range(h):
        if mask >> i & 1:
            if intervals and intervals[-1][1] == i:
                intervals[-1] = (intervals[-1][0], i+1)
            else:
                intervals.append((i,i+1))
    return intervals


def blocks(h, word, selection):
    for i in range(h):
        rates = (1,2,1,2) if word >> i & 1 else (1,1,2,2)
        if selection >> i & 1:
            yield rates[:2]
            yield rates[2:]
        else:
            for a in rates:
                yield (a,)


def canonical(h, word, selection):
    b = 1/(h*h*sqrt(h))
    q = 1.
    terms = []
    for rates in blocks(h,word,selection):
        B = sum(rates)
        C = sum(a*a for a in rates)
        r = C/B**2
        mass = (1-1/h**2)/(2*h) * q*q*(C/B)**2
        terms.append(mass/(2*(1+sqrt(1-r))**2))
        q *= prod(1-a*b for a in rates)
    return exp(-fsum(terms))


def run():
    h = 8
    queries = [(mask,runs(mask,h)) for mask in range(1<<h)]
    tests = []
    for d in (2,4):
        output = {k: dict(error=-1, count_error=0, pairs=0) for k in (1,2,4)}
        for v in range(1<<h):
            payload = encode([(v>>j)&1 for j in range(h)],d)
            for mask, intervals in queries:
                size = mask.bit_count()
                count = (mask & v).bit_count()
                est = estimate(h,d,payload,intervals)
                gap = abs(leading(h,size,est)-leading(h,size,count))
                for k,rec in output.items():
                    if len(intervals)>k:
                        continue
                    assert abs(count-est)<=2*k*(d-1)
                    rec["pairs"] += 1
                    rec["count_error"] = max(rec["count_error"],abs(count-est))
                    if gap > rec["error"]:
                        rec.update(error=gap,word=v,mask=mask,decoded=est,actual=count)
        for k,rec in output.items():
            rec["error"] = round(rec["error"],12)
            tests.append(dict(k=k,width=d,bits=h//d,**rec))
    # Collision with the empty word on a single contiguous query for width four.
    word = [1,1,1,0,0,0,0,0]
    assert encode(word,4)==encode([0]*8,4)
    collision = round(abs(leading(8,3,3)-leading(8,3,0)),12)
    return dict(h=h, exhaustive=tests, collision=dict(words=[0,7],mask=7,width=4,gap=collision),
                example=dict(h=1000000,k=1,epsilon=.001,
                             bits=1000000//grid_width(1000000,1,.001)))


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