#!/usr/bin/env python3 """Build candidate cascades from a cascade package with the reference implementation (cascade_core.py). Usage: python example_run_on_package.py PACKAGE_DIR [--types TYPE,TYPE ...] [--scale 1.0] The package is a folder with manifest.json, events.jsonl(.gz) and links.jsonl(.gz) (see the data page of the CAVEAT site). Only links that the manifest marks as propagating are used. The window of a link kind is taken from the manifest (default_window_seconds). cascade_core.py v0.1 applies windows to the timestamp gap of a link; for the rail packages, whose events are dated to the operating day, the lag of a link is declared in the manifest (attrs.rule_gap_minutes) and is not yet used by this version of the core. """ import argparse, datetime as dt, gzip, json, math, os, sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import cascade_core as cc def read_jsonl(folder, name): for path, op in ((os.path.join(folder, name + '.jsonl'), open), (os.path.join(folder, name + '.jsonl.gz'), lambda p: gzip.open(p, 'rt', encoding='utf8'))): if os.path.exists(path): with op(path) as f: return [json.loads(line) for line in f] raise FileNotFoundError(name) def epoch(iso): return dt.datetime.fromisoformat(iso.replace('Z', '+00:00')).timestamp() def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument('package') ap.add_argument('--scale', type=float, default=1.0, help='multiply all windows by this factor') a = ap.parse_args() manifest = json.load(open(os.path.join(a.package, 'manifest.json'), encoding='utf8')) events = [cc.Event(id=e['id'], time=epoch(e['time']['start']), type=e['kind'], entities=tuple((r['entity'], r['role']) for r in e.get('refs', [])), attrs=e.get('attrs', {})) for e in read_jsonl(a.package, 'events')] ids = {e.id for e in events} links = [] for l in read_jsonl(a.package, 'links'): if not l['propagates'] or l['from'] not in ids or l['to'] not in ids: continue ltype = l['kind'] + (':' + l['relation'] if l.get('relation') else '') links.append(cc.Link(src=l['from'], dst=l['to'], type=ltype, provenance='given' if l['evidence']['existence']['level'] == 'given' else 'derived', direction_basis='evidence' if l['direction'] == 'evidence' else 'time', evidence=l['evidence'])) windows = {} for k in manifest['link_kinds']: w = k.get('default_window_seconds') if w: windows[k['id']] = (0.0, w * a.scale) # a window set for a kind applies to every link type that starts with that kind cfg = cc.Config(windows={}, default_window=(0.0, math.inf), tie_rule='drop') for t in {l.type for l in links}: base = t.split(':')[0] if base in windows: cfg.windows[t] = windows[base] g = cc.Graph(events, links, cfg) d = g.diagnostics() print('package', manifest['package_id'], '| events', len(events), '| propagating links', len(links)) print('kept links', d['kept_links'], '| dropped', d['dropped'], '| episodes of 3+', d['episodes_ge3'], '| largest episode', d['largest_episode'], f"({d['largest_fraction']:.1%} of events; giant-component warning: {d['giant_warning']})") sizes = sorted((len(m) for _, m in g.cascades(min_size=3)), reverse=True) print('cascades of 3+ events:', len(sizes), '| largest', sizes[:5]) root, members = max(g.cascades(min_size=3), key=lambda x: len(x[1])) print(json.dumps(g.candidate_record(root, members)['descriptors'], indent=1)) if __name__ == '__main__': main()