Read the checking program (88 lines of Python)
"""Check a sum of rank-one terms equals the matrix multiplication tensor and count terms."""
import json
import sys
import re
from itertools import product
MAX_BYTES = 86046
SHAPE = (4, 4, 4)
MAX_TERMS = 64
PATTERN = b'-?[0-9]{1,12}(:-?[0-9]{1,12})?'
def check_tensor(m, n, p, denominator, terms):
# On each pair of elementary input matrices, accumulate the full output
# tensor in Gaussian integers. The common denominator is denominator**3.
stride = m * p
real = [0] * (m * n * n * p * stride)
imaginary = [0] * len(real)
for left, right, output in terms:
for i, (a, b) in left:
for j, (c, d) in right:
x, y = a*c - b*d, a*d + b*c
offset = (i * n * p + j) * stride
for k, (u, v) in output:
index = offset + k
real[index] += x*u - y*v
imaginary[index] += x*v + y*u
target = [0] * len(real)
for i, j, k in product(range(m), range(n), range(p)):
left = i * n + j
right = j * p + k
output = i * p + k
target[(left * n * p + right) * stride + output] = denominator**3
return real == target and not any(imaginary)
def verify(data):
lines = data.splitlines()
if not 2 <= len(lines) <= MAX_TERMS + 1:
raise ValueError("The submission has the wrong number of terms.")
if re.fullmatch(rb"[1-9][0-9]{0,11}", lines[0]) is None:
raise ValueError("The first line must be a positive denominator of up to 12 digits.")
denominator = int(lines[0])
m, n, p = SHAPE
left_size, right_size, out_size = m*n, n*p, m*p
terms = []
for line in lines[1:]:
tokens = line.split()
if len(tokens) != left_size + right_size + out_size:
raise ValueError("Each term must specify all three coefficient vectors.")
coefficients = []
for token in tokens:
if re.fullmatch(PATTERN, token) is None:
raise ValueError("A coefficient has an invalid numerator.")
real, separator, imaginary = token.partition(b":")
coefficients.append((int(real), int(imaginary) if separator else 0))
cuts = (0, left_size, left_size + right_size, len(coefficients))
term = [
[(i, pair) for i, pair in enumerate(coefficients[start:end]) if pair != (0, 0)]
for start, end in zip(cuts, cuts[1:])
]
if not all(term):
raise ValueError("A rank one term has an identically zero factor.")
terms.append(term)
if not check_tensor(m, n, p, denominator, terms):
raise ValueError("The rank one terms do not sum to the matrix multiplication tensor.")
return len(terms)
def main():
data = sys.stdin.buffer.read(MAX_BYTES + 1)
try:
if len(data) > MAX_BYTES:
raise ValueError("Submission exceeds the byte limit.")
if not data.isascii() or any(c < 32 and c not in (9, 10, 13) for c in data):
raise ValueError("Use plain ASCII text.")
score = verify(data)
except ValueError as error:
result = {"valid": False, "score": None, "message": str(error)}
else:
result = {"valid": True, "score": score, "message": "The construction is valid."}
print(json.dumps(result, separators=(",", ":")))
if __name__ == "__main__":
main()