bf-rasp-minimal-13 / code /validate.py
turtlecannon's picture
bf-rasp-minimal-13: all outputs of bf-rasp programs up to length 13
222d213 verified
Raw History Blame Contribute Delete
4.42 kB
"""Check an exported (or downloaded) copy of the bf-rasp dataset.
Usage: python3 validate.py DATASET_DIR [--rows-per-file 200] [--expected stats/classes_by_length.tsv]
For every Parquet file under DATASET_DIR/data: checks that all rows have the file's length and that programs are
distinct and sorted in enumeration order; re-runs a random sample of rows and checks zlib_size, the measures
(depth, n_attn, width) and the period (the output from preperiod on repeats with that period). With --expected (the
classes_by_length.tsv in stats/), the rows per length and class must match. Exits non-zero on any failure.
Runs the outputs with code/libbfrasp_run.so if it exists (cc -O2 -shared -fPIC -o code/libbfrasp_run.so
code/bfrasp_run.c), else with the pure-Python bfrasp.generate (slower).
"""
import argparse, ctypes, glob, os, re, sys, zlib
import numpy as np, pyarrow.parquet as pq
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import bfrasp
T = 4095
RANK = np.zeros(256, np.uint8)
for i, c in enumerate(bfrasp.ALPHABET):
RANK[ord(c)] = i + 1
CLASSES = ["ends_in_zeros", "eventually_constant", "polynomial", "recurrence_1", "recurrence_2",
"eventually_periodic", "not_periodic_in_window"]
def runner():
lib = os.path.join(HERE, 'libbfrasp_run.so')
if os.path.exists(lib):
so = ctypes.CDLL(lib); buf = ctypes.create_string_buffer(T)
def run(p):
assert so.bfrasp_generate(p.encode(), T, buf)
return buf.raw
return run
return lambda p: bfrasp.generate(p, T)
def main():
ap = argparse.ArgumentParser(); ap.add_argument('root')
ap.add_argument('--rows-per-file', type=int, default=200); ap.add_argument('--expected')
a = ap.parse_args(); rng = np.random.default_rng(0); run = runner()
files = sorted(glob.glob(os.path.join(a.root, 'data', 'length_*', '*.parquet')))
rows, classes, failures = {}, {}, 0
for path in files:
L = int(re.search(r'length_(\d+)', path).group(1))
t = pq.read_table(path)
progs = t.column('program').to_pylist()
ok = all(len(p) == L for p in progs) and set(t.column('length').to_pylist()) == {L}
if ok and len(progs) > 1: # sorted and distinct
r = RANK[np.frombuffer(''.join(progs).encode(), np.uint8).reshape(-1, L)]
diff = r[1:] != r[:-1]; first = diff.argmax(1); k = np.arange(len(first))
ok &= bool(diff.any(1).all() and (r[1:][k, first] > r[:-1][k, first]).all())
if not ok:
failures += 1; print(f"{path}: wrong length, order or duplicates")
col = {c: t.column(c).to_numpy() for c in ('depth', 'n_attn', 'width', 'preperiod', 'period', 'zlib_size')}
cls = t.column('output_class').to_pandas().astype(str).to_numpy()
for i in rng.choice(len(progs), min(len(progs), a.rows_per_file), replace=False):
p = progs[i]; y = run(p)
m = bfrasp.measures(p)
nz = len(y.rstrip(b'\0'))
pre, per = int(col['preperiod'][i]), int(col['period'][i])
checks = [(m['depth'], col['depth'][i]), (m['n_attn'], col['n_attn'][i]), (m['width'], col['width'][i]),
(len(zlib.compress(y[:nz], 6)), col['zlib_size'][i])]
bad = [c for c in checks if c[0] != c[1]]
if per and y[pre + per:] != y[pre:T - per]:
bad.append(('period', per))
if (cls[i] == 'not_periodic_in_window') != (per == 0):
bad.append(('class', cls[i]))
if bad:
failures += 1; print(f"{path}: {p}: {bad}")
rows[L] = rows.get(L, 0) + t.num_rows
for c, n in zip(*np.unique(cls, return_counts=True)):
classes[(L, c)] = classes.get((L, c), 0) + int(n)
for L in sorted(rows):
print(f"length {L}: {rows[L]:,} rows")
print(f"total: {sum(rows.values()):,} rows in {len(files)} files")
if a.expected:
for line in open(a.expected).read().splitlines()[1:]:
v = list(map(int, line.split()))
for c, n in zip(CLASSES, v[1:]):
if classes.get((v[0], c), 0) != n:
failures += 1; print(f"length {v[0]} {c}: {classes.get((v[0], c), 0)} rows, expected {n}")
print("OK" if not failures else f"{failures} FAILURES"); sys.exit(1 if failures else 0)
if __name__ == '__main__':
main()