"""Exact finite checks of rank boxes for positive homothetic vertex cubes."""
from collections import defaultdict
from itertools import combinations, product
from math import comb


def axis_values(points):
    return [sorted(set(axis)) for axis in zip(*points)]


def ranks(points, axes):
    rank = [{v:i for i,v in enumerate(axis)} for axis in axes]
    return {tuple(r[v] for r,v in zip(rank,p)): p for p in points}


def sections_are_intervals(ranked, d):
    for i in range(d):
        sections = defaultdict(list)
        for p in ranked:
            sections[p[:i]+p[i+1:]].append(p[i])
        if any(max(v)-min(v)+1 != len(v) for v in sections.values()):
            return False
    return True


def cube_counts(points, axes, ranked):
    d = len(axes)
    corners = list(product((0,1), repeat=d))
    counts = {}
    for key, p in ranked.items():
        total = 0
        for value in axes[0]:
            side = value-p[0]
            if side <= 0:
                continue
            if all(tuple(x+side*b for x,b in zip(p,bits)) in points
                   for bits in corners):
                total += 1
        counts[key] = total
    return counts


def check(points):
    axes = axis_values(points)
    d = len(axes)
    ranked = ranks(points, axes)
    if not sections_are_intervals(ranked,d):
        return False
    counts = cube_counts(points,axes,ranked)
    for t in range(1,max(counts.values(),default=0)+1):
        anchors = {p for p,c in counts.items() if c >= t}
        box = list(product(range(t+1),repeat=d))
        expanded = {tuple(x+s for x,s in zip(p,b)) for p in anchors for b in box}
        assert expanded <= ranked.keys()
        # Projection inequalities imply the real-root bound using integers only.
        lower = 0
        for k in range(d+1):
            subtotal = sum(len({tuple(p[i] for i in subset) for p in anchors})
                           for subset in combinations(range(d),k))
            assert subtotal**d >= comb(d,k)**d * len(anchors)**k
            lower += subtotal*t**(d-k)
        assert len(expanded) >= lower
    for n in range(1, len(points)+1):
        if n**d > len(points):
            break
        if len(points) != n**d:
            continue
        target = sum(j**d for j in range(n))
        assert sum(counts.values()) <= target
        if sum(counts.values()) == target and n >= 2:
            assert d >= 2 and all(len(axis)==n for axis in axes)
            h = axes[0][1]-axes[0][0]
            assert all(all(b-a == h for a,b in zip(axis,axis[1:])) for axis in axes)
    return True


def all_nonempty_subsets(axes):
    grid = list(product(*axes))
    count = 0
    for mask in range(1,1<<len(grid)):
        points = {p for i,p in enumerate(grid) if mask>>i & 1}
        count += check(points)
    return count


def run():
    print('2D and 3D coordinate-section-convex sets checked:',
          all_nonempty_subsets([[0,1,3],[0,1,3]]),
          all_nonempty_subsets([[0,1],[1,2],[0,1,3]]))
    for n in range(2,6):
        for axis in [list(range(n)),[i*i for i in range(n)]]:
            for cut in [2*(n-1),3*(n-1),4*(n-1)]:
                points={tuple(axis[i] for i in v) for v in product(range(n),repeat=4)
                        if sum(v) <= cut}
                assert check(points)
    print('24 four-dimensional products and nonproduct truncations checked.')
    star = {tuple(s*b for b in bits) for s in [1,2,3]
            for bits in product((0,1),repeat=4)}
    axes=axis_values(star); ranked=ranks(star,axes)
    assert len(star)==46 and not sections_are_intervals(ranked,4)
    assert cube_counts(star,axes,ranked)[(0,)*4]==3 and 3**4>len(star)
    print('The unrestricted 46-point example has an anchor supporting 3 scales.')


if __name__ == '__main__':
    run()
