"""Exact residual cases for codimensions four to six. Requires NumPy and SciPy."""
from collections import Counter
from functools import reduce
from itertools import combinations
from math import factorial, gcd
import numpy as np
from scipy.sparse import csr_array
from scipy.sparse.csgraph import maximum_flow


def denominator(positions):
    previous = -2
    run_size = 0
    value = 1
    for position in positions:
        if position != previous + 1:
            value *= factorial(run_size + 1)
            run_size = 0
        run_size += 1
        previous = position
    return value * factorial(run_size + 1)


def rank(m, k):
    entries = sorted((sum(1 << i for i in p), denominator(p))
                     for p in combinations(range(m), k))
    common = reduce(lambda a, b: a * b // gcd(a, b),
                    Counter(d for _, d in entries), 1)
    return (np.array([s for s, _ in entries], dtype=np.int64),
            np.array([common // d for _, d in entries], dtype=np.int64))


def verify(m, k):
    small, left = rank(m, k)
    large, right = rank(m, k + 1)
    a, b = int(left.sum()), int(right.sum())
    g = gcd(a, b)
    left *= b // g
    right *= a // g
    total = a * (b // g)
    nr, nc = len(large), len(small)
    source, sink = 0, 1
    rows = np.arange(2, 2 + nr, dtype=np.int32)
    cols = np.arange(2 + nr, 2 + nr + nc, dtype=np.int32)
    tails, heads, caps = [], [], []
    next_node = 2 + nr + nc
    cap_limit = (1 << 31) - 1

    def add(x, y, z):
        """SciPy uses signed 32-bit single-edge flows. Split larger edges."""
        nonlocal next_node
        while np.any(z > cap_limit):
            high = z > cap_limit
            mid = np.arange(next_node, next_node + int(high.sum()), dtype=np.int32)
            next_node += len(mid)
            one = np.full(len(mid), cap_limit, dtype=np.int32)
            tails.extend([x[high], mid])
            heads.extend([mid, y[high]])
            caps.extend([one, one])
            z = z - np.where(high, cap_limit, 0)
        tails.append(x)
        heads.append(y)
        caps.append(z.astype(np.int32))

    add(np.full(nr, source, np.int32), rows, right)
    add(cols, np.full(nc, sink, np.int32), left)
    unseen = large.copy()
    for _ in range(k + 1):
        removable = unseen & -unseen
        submasks = large ^ removable
        idx = np.searchsorted(small, submasks)
        assert np.array_equal(small[idx], submasks)
        add(rows, cols[idx], np.minimum(right, left[idx]))
        unseen ^= removable
    assert not np.any(unseen)
    graph = csr_array((np.concatenate(caps), (np.concatenate(tails),
                       np.concatenate(heads))), shape=(next_node, next_node))
    result = maximum_flow(graph, source, sink, method="dinic")
    assert int(result.flow_value) == total
    # Check the solver's returned flow as an independent integer certificate.
    flow = result.flow.astype(np.int64)
    assert (flow + flow.T).nnz == 0
    assert (flow - graph.astype(np.int64)).max() <= 0
    balances = np.asarray(flow.sum(axis=1)).reshape(-1)
    assert balances[source] == total and balances[sink] == -total
    assert not balances[2:].any()
    return total


if __name__ == "__main__":
    for k in (3, 4, 5):
        m = k + 1
        count = 0
        while 3 * m < 10 * k or (3 * m - 10 * k) ** 2 < 35 * k * k:
            total = verify(m, k)
            count += 1
            m += 1
        print("k=%d, %d finite cases through m=%d, largest saturated flow %d" %
              (k, count, m-1, total), flush=True)
