#!/usr/bin/env python3 """Re-run the link extraction of every use case and compare with the shipped output_links.json. Also tests the --layer path of the rail scripts on the first days of one railway country. Usage: python verify_all.py [--rail-layer-test-all] """ import json, os, subprocess, sys, tempfile ROOT = os.path.dirname(os.path.abspath(__file__)) FOLDERS = sorted(d for d in os.listdir(ROOT) if os.path.exists(os.path.join(ROOT, d, 'build_links.py'))) KIND_CODE = ['same_track', 'connection', 'explains'] def run(folder, args): return subprocess.run([sys.executable, 'build_links.py'] + args, cwd=os.path.join(ROOT, folder), capture_output=True, text=True) def main(): ok = True for f in FOLDERS: with tempfile.TemporaryDirectory() as tmp: out = os.path.join(tmp, 'links.json') r = run(f, ['--output', out]) new = json.load(open(out, encoding='utf8')) old = json.load(open(os.path.join(ROOT, f, 'output_links.json'), encoding='utf8')) same = new['links'] == old['links'] and new['omitted'] == old['omitted'] ok &= same and r.returncode == 0 print(f'{f:18s} {len(new["links"]):>7,} links identical to shipped output: {same}') # layer path of the rail scripts: build a layer file in the format of stage1_extraction/rerun_cascades.py from the first 5 days for f in [x for x in FOLDERS if x.startswith('rail-')]: if f != 'rail-ch' and '--rail-layer-test-all' not in sys.argv: continue inp = json.load(open(os.path.join(ROOT, f, 'input_events.json'), encoding='utf8')) days = sorted({r[0] for r in inp['rule_edges']['rows']})[:5] layer = {'days': {str(d): {'ed': {'src': [], 'dst': [], 'kind': [], 'w': [], 'gap': []}} for d in days}} for day, s, t, k, w, g in inp['rule_edges']['rows']: if day in days: e = layer['days'][str(day)]['ed'] e['src'].append(s); e['dst'].append(t); e['kind'].append(KIND_CODE.index(k)); e['w'].append(w); e['gap'].append(g) with tempfile.TemporaryDirectory() as tmp: lf, out = os.path.join(tmp, 'layer.json'), os.path.join(tmp, 'links.json') json.dump(layer, open(lf, 'w')) r = run(f, ['--layer', lf, '--output', out]) new = json.load(open(out, encoding='utf8'))['links'] old = [l for l in json.load(open(os.path.join(ROOT, f, 'output_links.json'), encoding='utf8'))['links'] if int(l['evidence']['existence']['source_ref']['id'].split('/')[0]) in days] same = new == old ok &= same print(f'{f:18s} --layer test on days {days[0]}..{days[-1]}: {len(new)} links identical to shipped links of those days: {same}') print('ALL IDENTICAL' if ok else 'DIFFERENCES FOUND') sys.exit(0 if ok else 1) if __name__ == '__main__': main()