"""Expand increasing-pattern-avoiding peak functions using integer monomials."""

from bisect import bisect_left
from collections import Counter
from fractions import Fraction
from functools import cache
from itertools import permutations
from sys import argv


def compositions(size):
    if size == 0:
        yield ()
    for first in range(1, size + 1):
        for rest in compositions(size - first):
            yield (first, *rest)


def peak_data(size):
    counts = [Counter() for _ in range(size + 1)]
    for word in permutations(range(size)):
        tails = []
        for value in word:
            index = bisect_left(tails, value)
            if index == len(tails):
                tails.append(value)
            else:
                tails[index] = value
        peaks = sum(1 << i for i in range(1, size - 1)
                    if word[i-1] < word[i] > word[i+1])
        counts[len(tails)][peaks] += 1
    return counts


def monomials(size, counts):
    result = {}
    for alpha in compositions(size):
        cuts = 0
        prefix = 0
        for part in alpha[:-1]:
            prefix += part
            cuts |= 1 << (prefix - 1)
        allowed = cuts | (cuts << 1)
        coefficient = (1 << len(alpha)) * sum(
            count for peaks, count in counts.items() if not (peaks & ~allowed)
        )
        partition = tuple(sorted(alpha, reverse=True))
        assert result.setdefault(partition, coefficient) == coefficient
    return result


@cache
def q_products(shape):
    """Expand a Schur Q Pfaffian into products of one-row q-functions."""
    if not shape:
        return {(): 1}
    if len(shape) % 2:
        return q_products((*shape, 0))
    a = shape[0]
    result = Counter()
    for j in range(1, len(shape)):
        b = shape[j]
        rest = (*shape[1:j], *shape[j+1:])
        for factors, coefficient in q_products(rest).items():
            for i in range(b + 1):
                sign = (-1) ** (j-1+i)
                row_factor = 1 if i == 0 else 2
                product = tuple(sorted((*factors, a+i, b-i), reverse=True))
                result[tuple(x for x in product if x)] += coefficient * sign * row_factor
    return result


def splits(value, caps):
    if not caps:
        if value == 0:
            yield ()
        return
    for first in range(min(value, caps[0]) + 1):
        for rest in splits(value - first, caps[1:]):
            yield (first, *rest)


@cache
def q_monomial(factors, exponents):
    if not exponents:
        return int(not factors)
    result = 0
    for parts in splits(exponents[0], factors):
        next_factors = tuple(sorted((f-p for f, p in zip(factors, parts) if f > p),
                                    reverse=True))
        result += (1 << sum(p > 0 for p in parts)) * q_monomial(next_factors, exponents[1:])
    return result


def expand_in_q(monomial):
    partitions = sorted(monomial, reverse=True)
    strict = [shape for shape in partitions if len(set(shape)) == len(shape)]
    matrix = [[Fraction(sum(c * q_monomial(factors, exponents)
                           for factors, c in q_products(shape).items()))
               for shape in strict] + [Fraction(monomial[exponents])]
              for exponents in partitions]
    for j in range(len(strict)):
        pivot = next(i for i in range(j, len(matrix)) if matrix[i][j])
        matrix[j], matrix[pivot] = matrix[pivot], matrix[j]
        matrix[j] = [value / matrix[j][j] for value in matrix[j]]
        for i, row in enumerate(matrix):
            if i != j and row[j]:
                matrix[i] = [a - row[j] * b for a, b in zip(row, matrix[j])]
    assert all(not any(row) for row in matrix[len(strict):])
    answer = {}
    for shape, row in zip(strict, matrix):
        coefficient = row[-1]
        assert coefficient.denominator == 1 and coefficient >= 0
        if coefficient:
            answer[shape] = int(coefficient)
    return answer


if __name__ == "__main__":
    limit = int(argv[1]) if len(argv) > 1 else 9
    for size in range(1, limit + 1):
        counts_by_lis = peak_data(size)
        counts = Counter()
        for k in range(1, size + 2):
            counts.update(counts_by_lis[k-1])
            expansion = expand_in_q(monomials(size, counts))
            if k in (4, 5) or (size == 3 and k == 4):
                print(size, k, expansion, flush=True)
            if size == 3 and k == 4:
                assert expansion == {(3,): 4, (2,1): 2}
    print("All exact monomial comparisons and Schur Q expansions passed.")

