"""Exact Gram-fibre probabilities for small sign matrices. Normalize the first entry of each column to 1. Its remaining entries are uniform independent signs, and this does not change any pair product. Enumerate column multiplicities, assigning each its exact multinomial weight. No sampling is used. Default cases take about a minute on a typical laptop. """ from collections import defaultdict from itertools import product, combinations from math import comb, log import json from pathlib import Path def gram_fibres(height, width): pairs = list(combinations(range(height), 2)) columns = [(1,) + v for v in product((-1, 1), repeat=height - 1)] increments = [tuple(c[i] * c[j] for i, j in pairs) for c in columns] fibres = defaultdict(int) d = len(pairs) last = len(columns) - 1 compositions = 0 def visit(a, remaining, total, weight): nonlocal compositions v = increments[a] if a == last: key = tuple(x + remaining * y for x, y in zip(total, v)) fibres[key] += weight compositions += 1 return for n in range(remaining + 1): visit(a + 1, remaining - n, tuple(x + n * y for x, y in zip(total, v)), weight * comb(remaining, n)) visit(0, width, (0,) * d, 1) denominator = len(columns) ** width assert sum(fibres.values()) == denominator assert compositions == comb(width + len(columns) - 1, len(columns) - 1) peak = max(fibres.values()) zero = fibres.get((0,) * d, 0) return dict(height=height, width=width, compositions=compositions, distinct_grams=len(fibres), maximum_numerator=peak, zero_numerator=zero, denominator=denominator, maximum_at_zero=(peak == zero), example_maximizer=next(list(k) for k, v in fibres.items() if v == peak), normalized_log_bound=(log(peak / denominator) + d / 2 * log(width)) / height ** 2) if __name__ == '__main__': cases = [(3, 12), (4, 4), (4, 8), (4, 12), (4, 16), (4, 20), (5, 8)] results = [] for h, n in cases: result = gram_fibres(h, n) results.append(result) print(json.dumps(result), flush=True) Path(__file__).with_name('gram_fibres.json').write_text( json.dumps(results, indent=2) + '\n')