"""Summary of the test of the masks of q3_check (IIS-Q-0003).

usage: python3 -I work/capset/q0003/q3_masks_summary.py LOGDIR
The script reads the files LOGDIR/q3_masks_NAME.txt.  Each file has one line for each of the 308
external directions, with the mask of the direction as a decimal number (one bit for each of the
56 classes).  The files come from the command "q3_check masks 0 KIND" of run_masks_test.sh.  The
script prints the number of marks of one direction for each kind, and it tests that some masks are
subsets of other masks.  A small mask permits more families of directions.  So a table for a mask
that contains the other mask is also an upper bound for the smaller mask.
"""
import sys
from collections import Counter
from pathlib import Path

logdir = Path(sys.argv[1])
FILES = [
    ("intact", "q3_masks_intact.txt", "intact cap"),
    ("dual", "q3_masks_dual.txt", "dual mask"),
    ("s0", "q3_masks_p1s0.txt", "one class, strict rule, class 0"),
    ("s1", "q3_masks_p1s1.txt", "one class, strict rule, class 1"),
    ("w0", "q3_masks_p1w0.txt", "one class, weak rule, class 0"),
    ("p2", "q3_masks_p2.txt", "two classes, strict rule, classes 0 and 1"),
]
mask = {}
for name, file, text in FILES:
    values = [int(x) for x in (logdir / file).read_text().split()]
    if len(values) != 308 or any(not 0 <= v < (1 << 56) for v in values):
        raise SystemExit("bad file: " + file)
    mask[name] = values
    counts = Counter(bin(v).count("1") for v in values)
    print("%s: %d directions; marks in one direction: %s; total marks %d" % (
        text, len(values), ", ".join("%d in %d directions" % (n, c) for n, c in sorted(counts.items())), sum(n * c for n, c in counts.items())))


def subset(small, big):
    return all((a & b) == a for a, b in zip(mask[small], mask[big]))


print("two classes (0,1) is a subset of one class 0, strict rule: %s" % subset("p2", "s0"))
print("two classes (0,1) is a subset of one class 1, strict rule: %s" % subset("p2", "s1"))
print("weak rule is a subset of the strict rule: %s" % subset("w0", "s0"))
print("strict rule is a subset of the intact cap: %s" % subset("s0", "intact"))
