CAVEAT logo: a waterfall flowing into a networkCAVEATCascades in linked event data
A waterfall that turns into flowing water and then into a network of linked nodes
Supplementary material

Package format and validation

Overview › Data acquisition › Package format

Every data set reaches CAVEAT as a cascade package: a folder of JSON files that an adapter writes and a validator checks. This page describes the format, how to write, validate and load a package, and the common scripts.

1. What a package contains

FileContent
manifest.jsonWhat the data set is: adapter, domain.event_definition and time_meaning, sources with licence, observation window, coverage procedure (full, query, snowball, sample) and known gaps, vocabularies (event kinds, entity types, roles, link kinds with default window, maximum gap, direction rule, evidence levels and lag declaration), rules, parameters, judges, attribute roles, statistics, warnings, limitations, and the record count and SHA-256 of every file
events.jsonlOne event per line: id, kind, title, time (start, optional end, precision from second to year, basis recorded, derived or imputed), refs (entity and role; one of them is the anchor), optional weight with unit, attrs, provenance (sources, extraction method and rule ids, confidence, merged-from), flags, link_coverage
entities.jsonl, entity_relations.jsonlThe entities that events refer to (stations, trains, packages, papers, repositories) and the relations among them (for example adjacent_to, depends_on). Optional
links.jsonlOne directed link per line: from, to, kind, optional relation, propagates, direction (time or evidence), gap_seconds, optional lag_seconds, and evidence with the level (given, rule, model, judged), the basis, the rule id or the judge, a text and a reference into the source
omitted.jsonlWhat the adapter could not keep and why (for example no_destination_event, backward_in_time), at most 10,000 listed per reason; the counts in the manifest are complete

File rules: events are sorted by start time and then by id as text, links by from, to, kind. Links that do not propagate, or whose relation is not assessed, are context links: shown as evidence, not followed. The meaning of time and of the attributes is declared, not guessed: domain.time_meaning says what an event time stands for, and attribute_roles says which attributes play the roles time of day, position, impact and category.

2. Writing a package

The package builders of the pilot show how each package was written from the output of its adapter. They are pilot scripts with fixed paths. The rail builder is superseded by rail_pipeline.py (see Rail), which writes the rail packages directly.

tools/package_builders/pkgkit.py60 lines · pilot scriptdownload
import json,os,gzip,hashlib,collections,subprocess,sys,io
CREATED='2026-10-22T10:00:00Z'
def dumps(o): return json.dumps(o,ensure_ascii=False,separators=(',',':'))
def write_lines(path,records,gz):
    raw=('\n'.join(dumps(r) for r in records)+('\n' if records else '')).encode('utf-8')
    h=hashlib.sha256(raw).hexdigest()
    if gz:
        with open(path+'.gz','wb') as f:
            with gzip.GzipFile(fileobj=f,mode='wb',mtime=0,compresslevel=9) as g: g.write(raw)
    else:
        open(path,'wb').write(raw)
    return h
def write_package(outdir,manifest,events,entities,relations,links,omitted,omitted_counts,gz=()):
    os.makedirs(outdir,exist_ok=True)
    for f in os.listdir(outdir): os.remove(os.path.join(outdir,f))
    events=sorted(events,key=lambda e:(e['time']['start'],e['id']))
    entities=sorted(entities,key=lambda e:e['id'])
    relations=sorted(relations,key=lambda r:(r['source'],r['target'],r['type']))
    links=sorted(links,key=lambda l:(l['from'],l['to'],l['kind'],l.get('relation','')))
    files={}
    for name,recs in (('events.jsonl',events),('entities.jsonl',entities),('entity_relations.jsonl',relations),('links.jsonl',links),('omitted.jsonl',omitted)):
        if name in('entity_relations.jsonl','omitted.jsonl') and not recs: continue
        h=write_lines(os.path.join(outdir,name),recs,name in gz)
        files[name]=dict(records=len(recs),sha256=h)
    ev_ids={e['id'] for e in events};ref=set(r['entity'] for e in events for r in e['refs'])
    has=set();bk=collections.Counter();bl=collections.Counter();br=collections.Counter();prop=0
    for l in links:
        has.add(l['from']);has.add(l['to']);bk[l['kind']]+=1;bl[l['evidence']['existence']['level']]+=1
        if 'relation' in l: br[l['relation']]+=1
        if l['propagates']: prop+=1
    st=dict(events=len(events),entities=len(entities),entity_relations=len(relations),
      links=dict(total=len(links),propagating=prop,by_kind=dict(bk),by_level=dict(bl)),
      omitted=dict(by_reason=dict(omitted_counts)),events_without_links=len([e for e in ev_ids if e not in has]),
      unreferenced_entities=len([e for e in entities if e['id'] not in ref]),
      merged_duplicates=sum(len(e['provenance'].get('merged_from',[])) for e in events))
    if br: st['links']['by_relation']=dict(br)
    manifest=dict(manifest);manifest['statistics']=st;manifest['files']=files;manifest.setdefault('warnings',[]);manifest['created_at']=CREATED
    json.dump(manifest,open(os.path.join(outdir,'manifest.json'),'w',encoding='utf-8'),ensure_ascii=False,indent=1)
    return st
def validate(outdir,report=None):
    r=subprocess.run([sys.executable,'/home/claude/pkg/validate_package.py',outdir,'--schema','/home/claude/pkg/cascade_package.schema.json','--max-messages','4']+(['--report',report] if report else []),capture_output=True,text=True)
    return r.returncode,r.stdout

EXPL={'cycle':"Pairs or groups of events at the same minute or year that link to each other in both directions. The links carry direction 'evidence'; the algorithm contracts such a cycle into one compound event",
 'statistics':"omitted.jsonl lists at most 10,000 items per reason; the counts in statistics.omitted are complete",
 'window':"Some events lie just outside the stated window because of the operating-day convention or imputed year dates; the window is the range of the source files",
 'direction':"Links between events that are not simultaneous at the stated precision but carry direction 'evidence' because the evidence gives the order",
 'judge':"Judge type is unspecified for some links",'truncated_evidence':"Evidence text ends with an ellipsis",'flags':"Imputed time without the flag time_imputed",'order':"Events are not sorted by start time",'propagation':"Propagation differs from the declared default",'relation':"Link of a kind with relations carries no relation",'pii':"String that looks like an e-mail address or credential; checked by hand",'provenance':"Event without source ids"}
def finalize(outdir,extra=None):
    rc,o=validate(outdir,outdir+'.report.json')
    rep=json.load(open(outdir+'.report.json'))
    m=json.load(open(os.path.join(outdir,'manifest.json')))
    ex=dict(EXPL);ex.update(extra or {})
    m['warnings']=[dict(code=k,message=ex.get(k,'See validator output'),count=v) for k,v in sorted(rep['summary']['warnings'].items())]
    json.dump(m,open(os.path.join(outdir,'manifest.json'),'w',encoding='utf-8'),ensure_ascii=False,indent=1)
    import jsonschema
    sch=json.load(open('/home/claude/pkg/cascade_package.schema.json'))
    jsonschema.Draft202012Validator({'$schema':sch['$schema'],'$defs':sch['$defs'],'$ref':'#/$defs/manifest'}).validate(m)
    return rc,rep['summary']
tools/package_builders/policy_pkg.py68 lines · pilot scriptdownload
import sys,os,json,re,collections;sys.path.insert(0,'/home/claude/pkg')
os.chdir('/home/claude/pol');sys.path.insert(0,'/home/claude/pol')
import compare2 as C
from pkgkit import *
os.chdir('/home/claude/pkg')
P=json.load(open('/home/claude/proto/policy.json'));E=P['events'];L=P['links']
docs=[]
for pi,(k,(lab,a,b)) in enumerate(C.PER.items()):
    trade=C.select([x for x in C.ALL if a<=x['date']<=b],{'Presidential','USTR','BIS'})
    for d in trade: docs.append(d|{'period':pi,'term':k})
assert len(docs)==len(E['t']) and all(d['title'][:130]==t for d,t in zip(docs,E['title'])),'document order mismatch'
SRC=['Presidential','USTR','BIS'];ISS=['presidential','ustr','bis']
KIND={'EO':'executive_order','PROC':'proclamation','NOTICE':'agency_notice','OTHER':'other_document'}
sid='federal_register'
ents=[]
for i,pl in enumerate(P['places']):
    ents.append(dict(id=f'topic:{i}',type='topic_region',label=pl['label'],attrs=dict(coords=dict(space='policy_topic_map_tsne_unit',x=pl['x'],y=pl['y']),documents=pl['n']),provenance=dict(source_ids=[],derived=True,method='k-means (k=10, 10 restarts, seed 0) on TF-IDF (8000 features, sublinear tf) reduced by SVD to 50 dimensions of title plus the first 2500 characters of text (scikit-learn); regions named by their top title terms and the majority issuer')))
for k,n in zip(ISS,['Presidential documents','US Trade Representative notices','Bureau of Industry and Security notices']):
    ents.append(dict(id=f'issuer:{k}',type='issuer',label=n,attrs={},provenance=dict(source_ids=[dict(source=sid,id=f'issuer:{k}')],derived=False)))
events=[]
for i,d in enumerate(docs):
    a=dict(document_number=d['id'],term=d['term'],issuer=ISS[E['src'][i]],coords=dict(space='policy_topic_map_tsne_unit',x=P['nodes']['x'][i],y=P['nodes']['y'][i]))
    if d['num']: a['instrument_number']=d['num']
    if d['vol']: a['federal_register_volume']=int(d['vol']);a['start_page']=int(d['sp'])
    ev=dict(id=d['id'],kind=KIND[d['kind']],title=d['title'].strip() or f"Untitled {d['kind']} {d['id']}",time=dict(start=d['date']+'T00:00:00Z',precision='day',basis='recorded'),
      refs=[dict(entity=f"topic:{E['pl'][i]}",role='anchor'),dict(entity=f"issuer:{ISS[E['src'][i]]}",role='participant')],attrs=a,
      provenance=dict(source_ids=[dict(source=sid,id=d['id'])],extraction=dict(method='trade or tariff pattern in the title, or at least three matches in the text',rule_ids=['R_TRADE_TEXT']),confidence=None),link_coverage='complete')
    if d['url']: ev['url']=d['url']
    events.append(ev)
links=[];om=[];oc=collections.Counter();seen=set()
def clean(s):
    lead=s.startswith('…');trail=s.endswith('…');w=re.sub(r'\s+',' ',s.strip('…').strip()).split(' ')
    if lead and len(w)>1: w=w[1:]
    if trail and len(w)>1: w=w[:-1]
    return ' '.join(w)
for a,b,ty,gap,ev in zip(L['a'],L['b'],L['ty'],L['gap'],L['ev']):
    f,t=docs[a]['id'],docs[b]['id'];kind='amendment_reference' if ty==0 else 'plain_reference'
    if gap<0: oc['backward_in_time']+=1;om.append(dict(item_type='link',reason='backward_in_time',id=f'{f}>{t}:{kind}',**{'from':f,'to':t}));continue
    if (f,t,kind) in seen: continue
    seen.add((f,t,kind))
    rule='R_CITE_NUMBER' if re.search(r'Executive Order|E\.O\.|Proclamation',ev['ref'],re.I) else 'R_CITE_FRPAGE'
    verb=f" near the verb stem '{ev['verb'].lower()}'" if ev['verb'] else ' with no modifying verb nearby'
    links.append({'id':f'{f}>{t}:{kind}','from':f,'to':t,'kind':kind,'propagates':ty==0,'direction':'evidence' if gap==0 else 'time','gap_seconds':int(gap)*86400,
      'evidence':{'existence':{'level':'rule','basis':'text_pattern','rule_id':rule,'text':f"The later document names {ev['ref']}{verb}: {clean(ev['snip'])}",'source_ref':dict(source=sid,id=f'{t}>{f}')}},'attrs':dict(reference=ev['ref'])})
M=dict(spec_version='0.1',package_id='policy-us-trade-0.1',created_at=CREATED,
 adapter=dict(name='federal_register_trade_adapter',version='0.1',domain='policy',code_ref=None,produced_by='Claude, from the policy pilot scripts and Federal Register documents'),
 domain=dict(event_definition='A presidential document, or a USTR or BIS notice, in the Federal Register that concerns tariffs or trade, dated by its publication day',entity_description='Derived topic regions of the document text, and the issuing bodies (presidential documents, USTR, BIS)'),
 sources=[dict(id=sid,name='Federal Register documents (presidential documents, USTR and BIS rules and notices), document text and metadata',url='https://www.federalregister.gov',accessed_at='2026-10',version='download of October 2026',license='US federal government works; the Federal Register site states no copyright restriction on its documents (to be confirmed before sharing)')],
 observation_window=dict(start='2017-01-20',end='2026-10-18',collected_at='2026-10',right_censored=True),
 coverage=dict(procedure='query',description='Documents of the three terms (Trump first term from 2017-01-20, Biden, Trump second term to 2026-10-18) that match a tariff and trade pattern; links are searched only among the selected documents of the same term',seeds=[],depth_limit=None,selection_rules=['R_TRADE_TEXT'],
  known_gaps=['Documents that concern trade but do not match the pattern are missing','Links are found only by an explicit citation of an executive order or proclamation number or of a Federal Register page; amendments that name neither are missing','Citations are searched inside one term, so no link crosses a change of administration','Other agencies than USTR and BIS are not included','Recent documents have had little time to attract references']),
 event_kinds=[dict(id='executive_order',label='Executive order',description='Presidential executive order'),dict(id='proclamation',label='Proclamation',description='Presidential proclamation'),dict(id='agency_notice',label='Agency notice',description='USTR or BIS notice or rule'),dict(id='other_document',label='Other document',description='Other presidential document')],
 entity_types=[dict(id='topic_region',label='Topic region',description='Cluster of documents with similar words in title and text; derived'),dict(id='issuer',label='Issuing body',description='Presidential documents, USTR or BIS')],
 entity_relation_types=[],roles=[],
 link_kinds=[dict(id='amendment_reference',core_kind='reference',description='A later document names an earlier executive order or proclamation, or cites its Federal Register page, near a verb such as amend, extend or suspend',propagates_default=True,default_window_seconds=5184000,max_gap_seconds=None,direction_rule='From the cited document to the citing document; documents of the same day use evidence',levels=['rule']),
   dict(id='plain_reference',core_kind='reference',description='A later document names an earlier executive order or proclamation, or cites its page, without a modifying verb nearby',propagates_default=False,default_window_seconds=None,max_gap_seconds=None,direction_rule='From the cited document to the citing document; documents of the same day use evidence',levels=['rule'])],
 evidence_bases=[dict(id='text_pattern',label='Text pattern',description='Pattern match in the text of the citing document, with the surrounding words as reason')],
 rules=[dict(id='R_TRADE_TEXT',description='Title matches the trade pattern, or the text has at least three matches (tariff, ad valorem, harmonized tariff, section 232, section 301, reciprocal, de minimis, duties)',parameters=dict(min_text_matches=3),applies_to='event'),
   dict(id='R_CITE_NUMBER',description='The text names Executive Order or Proclamation with a number of an earlier selected document',parameters={},applies_to='link'),
   dict(id='R_CITE_FRPAGE',description='The text cites a Federal Register page (volume FR page) that falls in an earlier selected document',parameters={},applies_to='link')],
 parameters=dict(time_precision=dict(value='day',description='Documents are dated to the day of publication in the Federal Register; start is midnight UTC of that day and documents of one day are simultaneous'),modifying_verb_pattern=dict(value='amend, modif, supplement, revok, terminat, suspend, extend, continu, replac, rescind, end, adjust, expand, clarif, exempt, reduc, increas, implement, in response, retaliat, further to, exclusion, inclusion',description='Verb stems within 220 characters of the citation that make a link an amendment reference'),
   default_window_days=dict(value=60,description='Window used in the pilot for amendment references; the percolation sweep showed the steepest growth before it'),
   coords_space=dict(value='policy_topic_map_tsne_unit',description='attrs.coords hold a t-SNE layout of title and text in the unit square; layout hint only')),
 limitations=['Relations are typed by a verb pattern, not judged by a reader','The 60-day window of the pilot lies after the steepest growth of the giant component and may be too wide','Documents of one day are simultaneous at day precision; their links carry direction evidence','The topic regions are descriptive and derived from words','Only 601 documents; cascades are few and small'],
 notes='Hand check: the text of a link quotes the citing document around the citation; the cited number or page identifies the earlier document.')
od='/home/claude/pkg/out/policy-us-trade'
st=write_package(od,M,events,ents,[],links,om,oc);print(json.dumps(st)[:500]);print(finalize(od))
tools/package_builders/software_pkg.py68 lines · pilot scriptdownload
import sys,json,re,collections,datetime as dt;sys.path.insert(0,'/home/claude/pkg')
from pkgkit import *
src=open('/home/claude/sw/crawl.py').read();SEEDS=eval(re.search(r'SEEDS=(\[.*?\])\n',src,re.S).group(1))
D=json.load(open('/home/claude/sw/npm_sample.json'));MIN=json.load(open('/home/claude/sw/minv.json'))
def norm(u):
    u=u.lower().strip();u=re.sub(r'^git\+','',u);u=re.sub(r'\.git$','',u);u=re.sub(r'^(ssh://)?git@github\.com[:/]','https://github.com/',u);return u.replace('git://','https://').replace('http://','https://').replace('www.','')
LO,HI='2025-01-01','2026-10-01'
def secs(t): return int(dt.datetime.fromisoformat(t.replace('Z','+00:00')).timestamp())
def iso(s): return dt.datetime.fromtimestamp(s,dt.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
ev=[];idx={}
for p,c in D.items():
    rel=sorted([r for r in c['rel'] if '-' not in r['v']],key=lambda r:r['t']);c['_rel']=rel
    for r in rel:
        if LO<=r['t']<HI: idx[(p,r['v'])]=len(ev);ev.append((p,r['v'],r['t']))
TS=[secs(e[2]) for e in ev];TF=[dt.datetime.fromisoformat(e[2].replace('Z','+00:00')).timestamp() for e in ev]
links=[]
for p,c in D.items():
    rel=c['_rel']
    for i,w in enumerate(rel):
        if not (LO<=w['t']<HI) or i==0: continue
        prev=rel[i-1]
        for a,rg in w['d'].items():
            if a not in D or a==p: continue
            pr=prev['d'].get(a)
            if pr is None or pr==rg: continue
            m=MIN.get(rg)
            if not m or MIN.get(pr)==m: continue
            u=idx.get((a,m))
            if u is None: continue
            iw=idx[(p,w['v'])];g=(TF[iw]-TF[u])/86400
            if g<=0 or g>30: continue
            same=bool(norm(D[a]['repo'])) and norm(D[a]['repo'])==norm(c['repo'])
            links.append((u,iw,same,dict(pkg=a,rng=rg,prev=pr,min=m)))
links=list({(l[0],l[1]):l for l in links}.values());print('events',len(ev),'links',len(links),'packages',len(D))
sid='npm_registry'
ents=[dict(id=f'pkg:{p}',type='package',label=p,attrs=dict(latest_version=c['latest']) if c['latest'] else {},provenance=dict(source_ids=[dict(source=sid,id=p)],derived=False)) for p,c in D.items()]
rels=[]
for p,c in D.items():
    for a in c['ldeps']:
        if a in D and a!=p: rels.append(dict(id=f'dep:{p}>{a}',source=f'pkg:{p}',target=f'pkg:{a}',type='depends_on',directed=True,attrs={},provenance=dict(source_ids=[dict(source=sid,id=p)],derived=False)))
events=[dict(id=f'{p}@{v}',kind='release',title=f'{p} {v}',time=dict(start=iso(TS[i]),precision='second',basis='recorded'),refs=[dict(entity=f'pkg:{p}',role='anchor')],attrs=dict(version=v),
  provenance=dict(source_ids=[dict(source=sid,id=f'{p}@{v}')],extraction=dict(method='stable release (no pre-release suffix) published inside the window',rule_ids=['R_STABLE_RELEASE']),confidence=None),link_coverage='partial') for i,(p,v,t) in enumerate(ev)]
L=[]
for u,iw,same,a in links:
    f=f'{ev[u][0]}@{ev[u][1]}';t=f'{ev[iw][0]}@{ev[iw][1]}';gs=TS[iw]-TS[u];days=(TF[iw]-TF[u])/86400
    L.append({'id':f'{f}>{t}','from':f,'to':t,'kind':'hand_off' if same else 'dependency','propagates':True,'direction':'evidence' if gs==0 else 'time','gap_seconds':gs,
      'evidence':{'existence':{'level':'rule','basis':'manifest_diff','rule_id':'R_MIN_VERSION_RAISED','text':f"{ev[iw][0]} {ev[iw][1]} raises its range for {a['pkg']} from {a['prev']} to {a['rng']}, whose lowest version is {a['min']}; {a['pkg']} {a['min']} was published {days:.2f} days earlier",'source_ref':dict(source=sid,id=f'{ev[iw][0]}@{ev[iw][1]}')}},
      'attrs':dict(dependency=a['pkg'],range_before=a['prev'],range_after=a['rng'],lowest_version=a['min']),**({'flags':['same_owner']} if same else {})})
M=dict(spec_version='0.1',package_id='software-npm-0.1',created_at=CREATED,
 adapter=dict(name='npm_release_adapter',version='0.1',domain='software',code_ref=None,produced_by='Claude, from the npm release pilot scripts (crawl.py, d_sw.py)'),
 domain=dict(event_definition='A stable release (a version without a pre-release suffix) of an npm package, published between 2025-01-01 and 2026-09-30, dated by its publish time',entity_description='npm packages; package relations follow the dependencies declared by the latest version'),
 sources=[dict(id=sid,name='npm registry package documents (versions, publish times, declared dependencies, repository)',url='https://registry.npmjs.org',accessed_at='2026-10',version='crawl of October 2026',license='npm registry metadata; terms not recorded in the pilot, to be filled in before the package is shared',notes='The release rows keep publisher user names out of this package')],
 observation_window=dict(start='2025-01-01',end='2026-09-30',collected_at='2026-10',right_censored=True),
 coverage=dict(procedure='snowball',description=f'Breadth-first crawl from {len(SEEDS)} well-known packages along the dependencies of the latest version, capped at 2500 packages (2544 packages reached); all stable releases of these packages in the window are events',seeds=SEEDS,depth_limit=None,selection_rules=['R_STABLE_RELEASE'],
  known_gaps=['Only packages reached by the capped crawl; dependents outside the sample are not seen, so links of heavily used packages are undercounted','Dependencies are the declared ranges of each release; a bump that happens through a lock file is not seen','Pre-release versions are excluded','The last release before each window start is not an event','The dependency relation among packages uses only the latest version of each package']),
 event_kinds=[dict(id='release',label='Release',description='A stable release of a package')],
 entity_types=[dict(id='package',label='Package',description='An npm package')],entity_relation_types=[],roles=[],
 link_kinds=[dict(id='hand_off',core_kind='hand_off',description='A release raises the minimum version of a dependency to exactly an upstream release of the same repository (release train)',propagates_default=True,default_window_seconds=604800,max_gap_seconds=2592000,direction_rule='From the upstream release to the dependent release in time',levels=['rule']),
   dict(id='dependency',core_kind='dependency',description='A release raises the minimum version of a declared dependency to exactly an upstream release of another repository',propagates_default=True,default_window_seconds=604800,max_gap_seconds=2592000,direction_rule='From the upstream release to the dependent release in time',levels=['rule'])],
 evidence_bases=[dict(id='manifest_diff',label='Manifest difference',description='Difference between the declared dependency ranges of consecutive stable releases')],
 rules=[dict(id='R_STABLE_RELEASE',description='Version without a pre-release suffix published inside the window',parameters=dict(window_start=LO,window_end='2026-10-01'),applies_to='event'),
   dict(id='R_MIN_VERSION_RAISED',description='A release changes the declared range of a package in the sample so that its lowest version rises and equals an upstream stable release published 0 to 30 days before',parameters=dict(max_gap_days=30),applies_to='link')],
 parameters=dict(max_gap_days=dict(value=30,description='Longest gap between the upstream release and the dependent release'),default_window_days=dict(value=7,description='Default window of the pilot'),same_repository_flag=dict(value='repository url equal after normalisation',description='Links inside one repository use kind hand_off and the flag same_owner')),
 limitations=['The sample is a capped snowball and not the whole registry','Only links where the new minimum version equals an upstream release in the sample are emitted','The link states that a release adopted an upstream release, not that it was caused by it','Publish times are the registry time stamps, second precision; two releases in one second would be simultaneous','Mass releases inside one repository create many links of the same pattern','Licence of the registry metadata is not recorded'],
 notes='Hand check: for any link, open the dependent release manifest and compare the range of the named dependency with the previous release.')
od='/home/claude/pkg/out/software-npm'
st=write_package(od,M,events,ents,rels,L,[],{},gz=('events.jsonl','links.jsonl','entity_relations.jsonl'));print(json.dumps(st)[:500]);print(finalize(od))
tools/package_builders/lens_pkg.py106 lines · pilot scriptdownload
import sys,os,json,re,collections;sys.path.insert(0,'/home/claude/pkg')
from pkgkit import *
os.chdir('/home/claude/sch');sys.path.insert(0,'/home/claude/sch')
src=open('/home/claude/sch/build_scholar_orig.py').read();ns={'__name__':'bs'}
exec(compile(src[:src.index('rows={}')],'build_scholar_head','exec'),ns)
corpus=ns['corpus'];ids=ns['ids'];places=ns['places'];pos=ns['pos'];cellof=ns['cellof'];rev=ns['rev'];c=ns['c'];ROLE=ns['E']['role'];ROLES=['technique','application','study','synthesis']
os.chdir('/home/claude/pkg')
SURV='e684fc96a0bff8e79594ed8ce4a1830d86c03c65'
G=re.compile(r'^(ieee|acm|proceedings|eurographics|computer graphics forum|human factors|international (conference|symposium|journal)|symposium|journal|transactions|conference)',re.I)
def source_of(p): return 'openalex' if p.startswith('oa:') else 'semantic_scholar'
def sid_of(p): return p[3:] if p.startswith('oa:') else p
# links first (needed for imputed years)
C=json.load(open('/home/claude/sch/corpus2.json'))
rows={}
for s,rs in c.items():
    for r in rs:
        a=(r['citingPaper'] or {}).get('paperId')
        if a in corpus: rows[(s,a)]=r
for a,b in C['links']: rows.setdefault((a,b),None)
def yr0(p):
    q=corpus[p];y=q.get('year')
    if y: return int(y)
    d=q.get('publicationDate')
    return int(d[:4]) if d else None
year={p:yr0(p) for p in ids};imp={}
earliest=collections.defaultdict(lambda:9999)
for (s,p) in rows:
    if s in corpus and p in corpus and year.get(p): earliest[s]=min(earliest[s],year[p])
for p in ids:
    if year[p]: continue
    t=corpus[p].get('title') or '';m=re.search(r'\b(19[89]\d|20[0-2]\d)\b',t)
    if m: year[p]=int(m.group(1));imp[p]='title'
    elif earliest[p]<9999: year[p]=earliest[p];imp[p]='earliest_citer'
    else: year[p]=2000;imp[p]='default'
print('imputed years',collections.Counter(imp.values()))
# merged duplicates among survey citers
merged=collections.defaultdict(list)
doi2id={((q.get('externalIds') or {}).get('DOI') or '').lower():p for p,q in corpus.items() if (q.get('externalIds') or {}).get('DOI')}
t2id={(q.get('title') or '').lower()[:60]:p for p,q in corpus.items()}
for r in json.load(open('/home/claude/sch/survey_citers.json')):
    ident=r['s2'] or ('oa:'+(r.get('oa') or '').split('/')[-1])
    if r['s2'] in corpus: continue
    pid=doi2id.get((r.get('doi') or '').lower()) or t2id.get((r['title'] or '').lower()[:60])
    if pid and pid!=ident and ident not in merged[pid]: merged[pid].append(ident)
expanded=set(json.load(open('/home/claude/sch/gen2_citations.json')))|{SURV}|set(c)
events=[]
for p in ids:
    q=corpus[p];doi=(q.get('externalIds') or {}).get('DOI')
    title=(q.get('title') or '').strip() or f'Untitled record {sid_of(p)}'
    fl=['time_coarse']
    if p in imp: fl.append('time_imputed')
    if G.search(title) or not (q.get('title') or '').strip(): fl.append('title_garbled')
    if p in merged: fl.append('duplicate_merged')
    a=dict(role=ROLES[ROLE[ids.index(p)]] if False else None);a={}
    a['venue']=(q.get('venue') or '')[:80];a['citation_count']=q.get('citationCount') or 0;a['coords']=dict(space='lens_topic_map_tsne_unit',x=round(pos[p][0],4),y=round(pos[p][1],4))
    if doi: a['doi']=doi
    if p in imp: a['year_imputed_by']=imp[p]
    pv=dict(source_ids=[dict(source=source_of(p),id=sid_of(p))],extraction=dict(method='paper in the citation neighbourhood of the survey reference list',rule_ids=['R_SNOWBALL']),confidence=None)
    if p in merged: pv['merged_from']=merged[p]
    ev=dict(id=p,kind='paper',title=title,time=dict(start=f'{year[p]}-01-01T00:00:00Z',precision='year',basis='imputed' if p in imp else 'recorded'),refs=[dict(entity=f'topic:{cellof[p]}',role='anchor')],attrs=a,provenance=pv,flags=fl,link_coverage='partial' if p in expanded else 'none')
    if doi: ev['url']='https://doi.org/'+doi
    events.append(ev)
ents=[dict(id=f'topic:{i}',type='topic_region',label=pl['label'],attrs=dict(coords=dict(space='lens_topic_map_tsne_unit',x=pl['x'],y=pl['y']),papers=pl['n']),provenance=dict(source_ids=[],derived=True,method='k-means (k=14, 10 restarts, seed 0) on TF-IDF (sublinear tf, min_df 2, max_df 0.35) reduced by SVD to 40 dimensions of title plus the first 600 characters of the abstract (scikit-learn); regions named by their top title terms')) for i,pl in enumerate(places)]
def words(s,n=14):
    s=re.sub(r'\s+',' ',s.replace('[abstract]','')).strip().strip('…').strip();w=s.split(' ');return ' '.join(w[:n])
RAT={'D':'The citing paper develops a new or extended technique or concept from the cited idea','A':'The citing paper uses the cited idea in a system or study','M':'The citing paper cites the cited paper as general background'}
REL={'D':'develops','A':'applies','M':'background'}
links=[];om=[];oc=collections.Counter()
for (s,p),r in rows.items():
    if s not in corpus or p not in corpus or s==p: continue
    dy=year[p]-year[s];kindid='reference';lid=f'{s}>{p}'
    if dy<0: oc['backward_in_time']+=1;om.append(dict(item_type='link',reason='backward_in_time',id=lid,**{'from':s,'to':p},detail=f'citing paper dated {year[p]}, cited paper dated {year[s]}'));continue
    srcname='openalex' if (s.startswith('oa:') or p.startswith('oa:')) else 'semantic_scholar'
    ex=dict(level='given',basis='citation_record',source_ref=dict(source=srcname,id=f'{sid_of(s)}>{sid_of(p)}'))
    L=dict(id=lid,**{'from':s,'to':p},kind=kindid,propagates=False,direction='evidence' if dy==0 else 'time',gap_seconds=0 if dy==0 else int((__import__('datetime').date(year[p],1,1)-__import__('datetime').date(year[s],1,1)).total_seconds()),evidence=dict(existence=ex))
    if p==SURV:
        L['relation']='described_in_survey';L['evidence']['relation']=dict(level='given',basis='citation_record',text='The survey cites this earlier paper in its reference list',source_ref=dict(source=srcname,id=f'{sid_of(s)}>{sid_of(p)}'))
    elif (s,p) in rev:
        lab,ctx,sr=rev[(s,p)];L['relation']=REL[lab];L['propagates']=lab in 'DA'
        sent=bool(ctx) and not ctx.startswith('[abstract]');w=words(ctx) if sent else ''
        txt=RAT[lab]+('. Read from the citing sentence' if sent else '. Read from the title and abstract of the citing paper')+(f'. Excerpt: “{w}”' if w else '')
        L['evidence']['relation']=dict(level='judged',basis='citing_sentence' if sent else 'title_and_abstract',text=txt,judge=dict(type='model',id='claude_reader',date='2026-10',unit='link'))
        L.setdefault('attrs',{})['review_set']=sr
    else: L['flags']=['unassessed']
    links.append(L)
print('links',len(links),collections.Counter(l.get('relation','-') for l in links),dict(oc))
omc=collections.Counter(oc);om=sorted(om,key=lambda o:o['id'])[:10000]
M=dict(spec_version='0.1',package_id='lens-survey-0.1',created_at=CREATED,
 adapter=dict(name='bibliometric_lens_adapter',version='0.1',domain='bibliometrics',code_ref=None,produced_by='Claude, from the lens pilot data (Semantic Scholar and OpenAlex records) and the judgements of the lens study'),
 domain=dict(event_definition='A paper in the citation neighbourhood of the references of the interactive-lenses survey by Tominski et al., dated by publication year',entity_description='Topic regions derived by clustering the words of titles and abstracts'),
 sources=[dict(id='semantic_scholar',name='Semantic Scholar Academic Graph (papers, citation lists, citing sentences)',url='https://api.semanticscholar.org',accessed_at='2026-10',license='Semantic Scholar API licence; to be confirmed before sharing, citing sentences are not stored in full in this package'),
   dict(id='openalex',name='OpenAlex works (records of papers not found in Semantic Scholar, publication dates)',url='https://openalex.org',accessed_at='2026-10',license='CC0 (OpenAlex data)')],
 observation_window=dict(start=f'{min(year.values())}-01-01',end='2026-10-21',collected_at='2026-10',right_censored=True),
 coverage=dict(procedure='snowball',description='Seeds are the 92 papers on lenses and focus+context cited by the survey. First generation: papers citing a seed (Semantic Scholar, lens-related by title or abstract). The survey itself and the papers citing it were added, then the papers citing the survey papers that develop or apply a lens idea (second generation)',seeds=[s['title'] for s in json.load(open('/home/claude/sch/seeds.json'))],depth_limit=2,selection_rules=['R_SNOWBALL'],
  known_gaps=['Starts from the references of one survey; lens papers that cite none of them are missing','Second generation collected only for the 69 papers that develop or apply a survey idea','The 2020s are incomplete because recent papers have had little time to be cited','Only a selection of links was judged: 358 links selected by a keyword rule (strict), 140 random other links to estimate the precision of the rule, 175 links from the survey to its citing papers and 156 second-generation links; all other links carry the flag unassessed','Dates are reduced to the publication year; 31 records without a year or date were given a year by rule and carry the flag time_imputed','About 11 records have a garbled title in the source and carry the flag title_garbled','Merging of duplicate records in the first collection stage used DOI and title matching and is not listed; only merges of the survey citers are listed in merged_from','Citation lists of Semantic Scholar and OpenAlex differ; the union was used for the survey']),
 event_kinds=[dict(id='paper',label='Paper',description='A publication')],
 entity_types=[dict(id='topic_region',label='Topic region',description='Cluster of papers with similar title and abstract words; derived')],entity_relation_types=[],roles=[],
 link_kinds=[dict(id='reference',core_kind='reference',description='The citing paper cites the cited paper',relations=[dict(id='develops',description='The citing paper develops a new or extended technique or concept from the cited idea',propagates_default=True),dict(id='applies',description='The citing paper uses the idea in a system or study',propagates_default=True),dict(id='background',description='The citing paper cites the idea as background',propagates_default=False),dict(id='described_in_survey',description='The survey cites and describes the earlier paper',propagates_default=False)],propagates_default=False,default_window_seconds=None,max_gap_seconds=None,direction_rule='From the cited paper to the citing paper; papers of the same year use evidence',levels=['given'])],
 evidence_bases=[dict(id='citation_record',label='Citation record',description='Citation listed by Semantic Scholar or OpenAlex'),dict(id='citing_sentence',label='Citing sentence',description='The sentence of the citing paper that cites the cited paper'),dict(id='title_and_abstract',label='Title and abstract',description='Title and abstract of the citing paper, used where no citing sentence exists')],
 rules=[dict(id='R_SNOWBALL',description='Paper cites a seed or a paper already in the set, or is cited by the survey, and deals with lenses, magnification or focus+context',parameters={},applies_to='event')],
 judges=[dict(id='claude_reader',type='model',description='Claude (an Anthropic language model) read the citing sentence, or the title and abstract where none exists, and typed the link as develops, applies or background; one reader, no second reader',agreement=dict(measured=False))],
 flags=[],parameters=dict(time_precision=dict(value='year',description='All papers are dated to the first instant of their publication year; papers of one year are simultaneous'),coords_space=dict(value='lens_topic_map_tsne_unit',description='attrs.coords hold a t-SNE layout of title and abstract words in the unit square; layout hint only')),
 limitations=['One reader judged the links and agreement was not measured; the reader is a language model','Evidence texts hold a rationale and an excerpt of at most 14 words, not the full citing sentence; the full sentence can be retrieved through source_ref','Links are typed only for a selection; the keyword selection favours papers with cue words','The survey is the root of a cascade because the links into it are non-propagating; switch them on to see it as a hub','Citation counts are those of Semantic Scholar at collection time','Year precision hides the order of papers within a year'],
 notes='Hand check: take a develops link; open the citing paper and find the sentence that cites the earlier paper.')
od='/home/claude/pkg/out/lens-survey';st=write_package(od,M,events,ents,[],links,om,omc);print(json.dumps(st)[:600]);print(finalize(od))
tools/package_builders/scagn_pkg.py115 lines · pilot scriptdownload
import sys,os,json,re,collections,datetime as dtm;sys.path.insert(0,'/home/claude/pkg')
from pkgkit import *
os.chdir('/home/claude/sca')
src=open('/home/claude/sca/build_scagn_orig.py').read();ns={'__name__':'bs'}
exec(compile(src[:src.index('E=dict(t=[]')],'build_scagn_head','exec'),ns)
P=ns['P'];ids=ns['ids'];places=ns['places'];pos=ns['pos'];cellof=ns['cellof'];rows=ns['rows'];g2r=ns['g2r'];G2key=ns['G2key'];g2lab=ns['g2lab'];S=ns['S'];items=ns['items'];lab=ns['lab'];T=ns['T']
FL=json.load(open('/home/claude/val/final_labels.json'));LBL={tuple(k.split('|')):v for k,v in FL.items()}
seedid={k:v['seed']['paperId'] for k,v in S.items()};paperlab={items[int(i)]['p']:v for i,v in lab.items()};flagged={(k,p) for key in ('A','B') for k,p,*_ in T[key]}
os.chdir('/home/claude/pkg')
GR=re.compile(r'^(ieee|acm|proceedings|eurographics|computer graphics forum|human factors|international (conference|symposium|journal)|symposium|journal|transactions|conference)',re.I)
strong=re.compile(r'scagnostic|pargnostic',re.I)
def yr0(p):
    q=P[p];y=q.get('year')
    if y: return int(y)
    d=q.get('publicationDate');return int(d[:4]) if d else None
year={p:yr0(p) for p in ids};imp={}
earliest=collections.defaultdict(lambda:9999)
for (s,p) in list(rows)+list(g2r):
    if s in P and p in P and year.get(p): earliest[s]=min(earliest[s],year[p])
for p in ids:
    if year[p]: continue
    m=re.search(r'\b(19[89]\d|20[0-2]\d)\b',P[p].get('title') or '')
    if m: year[p]=int(m.group(1));imp[p]='title'
    elif earliest[p]<9999: year[p]=earliest[p];imp[p]='earliest_citer'
    else: year[p]=2010;imp[p]='default'
print('imputed',collections.Counter(imp.values()))
seeds_meta=json.load(open('/home/claude/sca/seeds.json'));seedpids={v['seed']['paperId'] for v in S.values()}
expanded=seedpids|set(json.load(open('/home/claude/sca/gen2_sca.json')))
import difflib
def nt(t): return re.sub(r'[^a-z0-9]','',(t or '').lower())
canon={p:p for p in ids};bykey=collections.defaultdict(list)
for p in ids: bykey[nt(P[p].get('title'))[:22]].append(p)
def score(x): return (bool((P[x].get('externalIds') or {}).get('DOI')),P[x].get('citationCount') or 0)
for kk,g in bykey.items():
    for i in range(len(g)):
        for j in range(i+1,len(g)):
            a,b=g[i],g[j]
            if canon[a]!=a or canon[b]!=b: continue
            ta,tb=nt(P[a].get('title')),nt(P[b].get('title'))
            import os as _os
            rr=difflib.SequenceMatcher(None,ta,tb).ratio();cp=len(_os.path.commonprefix([ta,tb]));sh=min(ta,tb,key=len);lo=max(ta,tb,key=len)
            if len(ta)>=20 and len(tb)>=20 and (rr>=0.92 or (rr>=0.88 and cp>=30) or (len(sh)>=30 and lo.startswith(sh))) and abs(year[a]-year[b])<=2:
                keep,drop=(a,b) if score(a)>=score(b) else (b,a);canon[drop]=keep
merged=collections.defaultdict(list)
for p,c in canon.items():
    if p!=c: merged[c].append(p)
print('merged duplicate records',sum(len(v) for v in merged.values()),[ (P[c]['title'][:40],len(v)) for c,v in merged.items()])
events=[]
for p in [x for x in ids if canon[x]==x]:
    q=P[p];doi=(q.get('externalIds') or {}).get('DOI');title=(q.get('title') or '').strip() or f'Untitled record {p}'
    fl=['time_coarse']+(['time_imputed'] if p in imp else [])+(['title_garbled'] if (GR.search(title) or title.lower().startswith('of ')) else [])+(['duplicate_merged'] if p in merged else [])
    a=dict(venue=(q.get('venue') or '')[:80],citation_count=q.get('citationCount') or 0,coords=dict(space='scagnostics_topic_map_tsne_unit',x=round(pos[p][0],4),y=round(pos[p][1],4)))
    if doi: a['doi']=doi
    if p in seedpids: a['seed']=True
    if p in imp: a['year_imputed_by']=imp[p]
    if title.startswith('ClustML'): a['pdf_check']='Journal version: Information Visualization 2024, 23(2); the year of the first appearance is kept'
    ev=dict(id=p,kind='paper',title=title,time=dict(start=f'{year[p]}-01-01T00:00:00Z',precision='year',basis='imputed' if p in imp else 'recorded'),refs=[dict(entity=f'topic:{cellof[p]}',role='anchor')],attrs=a,
      provenance=dict(source_ids=[dict(source='semantic_scholar',id=p)]+[dict(source='semantic_scholar',id=d) for d in merged.get(p,[])],extraction=dict(method='seed paper, or paper citing a seed and judged relevant to scagnostics or visual quality metrics',rule_ids=['R_SNOWBALL']),confidence=None,**({'merged_from':merged[p]} if p in merged else {})),flags=fl,link_coverage='partial' if p in expanded else 'none')
    if doi: ev['url']='https://doi.org/'+doi
    events.append(ev)
ents=[dict(id=f'topic:{i}',type='topic_region',label=pl['label'],attrs=dict(coords=dict(space='scagnostics_topic_map_tsne_unit',x=pl['x'],y=pl['y']),papers=pl['n']),provenance=dict(source_ids=[],derived=True,method='k-means (k=12, 10 restarts, seed 0) on TF-IDF (sublinear tf, min_df 2, max_df 0.35) reduced by SVD to 40 dimensions of title plus the first 600 characters of the abstract (scikit-learn); regions named by their top title terms')) for i,pl in enumerate(places)]
def best(r):
    cs=[c for c in (r.get('contexts') or []) if c] if r else []
    return max(cs,key=lambda c:(bool(strong.search(c)),len(c))) if cs else ''
def words(s,n=14):
    s=re.sub(r'\s+',' ',s).strip();return ' '.join(s.split(' ')[:n])
RAT={'D':'The citing paper develops a new or extended measure, technique or concept from the cited idea','A':'The citing paper uses scagnostics or a quality metric from the cited work in a system or study','M':'The citing paper cites the cited work as general background'}
REL={'D':'develops','A':'applies','M':'background'}
links=[];om=[];oc=collections.Counter();seen=set()
def add(s,p,r,label,unit,review,basis=None):
    if s not in P or p not in P or s==p or (s,p) in seen: return
    seen.add((s,p));dy=year[p]-year[s];lid=f'{s}>{p}'
    if dy<0: oc['backward_in_time']+=1;om.append(dict(item_type='link',reason='backward_in_time',id=lid,**{'from':s,'to':p},detail=f'citing paper dated {year[p]}, cited paper dated {year[s]}'));return
    L=dict(id=lid,**{'from':s,'to':p},kind='reference',propagates=False,direction='evidence' if dy==0 else 'time',gap_seconds=0 if dy==0 else int((dtm.date(year[p],1,1)-dtm.date(year[s],1,1)).total_seconds()),
      evidence=dict(existence=dict(level='given',basis='citation_record',source_ref=dict(source='semantic_scholar',id=f'{s}>{p}'))))
    if label:
        L['relation']=REL[label];L['propagates']=label in 'DA'
        if basis=='full_text': ctx='';sent=False;how='. Read from the full text of the citing paper';bs='full_text'
        elif basis=='title_and_abstract': ctx='';sent=False;how='. Read from the title and abstract of the citing paper';bs='title_and_abstract'
        else:
            ctx=best(r);sent=bool(ctx);how='. Read from the citing sentence' if sent else '. Read from the title and abstract of the citing paper';bs='citing_sentence' if sent else 'title_and_abstract'
        txt=RAT[label]+how+(f'. Excerpt: “{words(ctx)}”' if sent else '')
        L['evidence']['relation']=dict(level='judged',basis=bs,text=txt,judge=dict(type='model',id='claude_reader',date='2026-10',unit=unit));L['attrs']=dict(review_set=review)
    else: L['flags']=['unassessed']
    links.append(L)
cand={}
def cadd(s,p,r,label,unit,review,basis=None):
    s=canon.get(s,s);p=canon.get(p,p);rank={'D':3,'A':2,'M':1,None:0}[label]
    if (s,p) not in cand or rank>cand[(s,p)][0]: cand[(s,p)]=(rank,(s,p,r,label,unit,review,basis))
for (k,p),r in rows.items():
    s=seedid[k];v=LBL.get((s,p))
    if v and v[0]: cadd(s,p,r,v[0],'link','first_generation_selection',v[1])
    else: cadd(s,p,r,None,'link','')
for (cited,p),r in g2r.items(): cadd(cited,p,r,g2lab[str(G2key[(cited,p)])],'link','second_generation')
for key in sorted(cand): add(*cand[key][1])
print('links',len(links),collections.Counter(l.get('relation','-') for l in links),dict(oc))
omc=collections.Counter(oc);om=sorted(om,key=lambda o:o['id'])[:10000]
M=dict(spec_version='0.1',package_id='scagnostics-0.2',created_at=CREATED,
 adapter=dict(name='bibliometric_scagnostics_adapter',version='0.2',domain='bibliometrics',code_ref=None,produced_by='Claude, from the scagnostics pilot data (Semantic Scholar) and the judgements of the scagnostics study'),
 domain=dict(event_definition='A paper that cites scagnostics, an extension of it to other graphics, or a related visual quality metric, dated by publication year',entity_description='Topic regions derived by clustering the words of titles and abstracts'),
 sources=[dict(id='semantic_scholar',name='Semantic Scholar Academic Graph (papers, citation lists, citing sentences)',url='https://api.semanticscholar.org',accessed_at='2026-10',license='Semantic Scholar API licence; to be confirmed before sharing, citing sentences are not stored in full in this package')],
 observation_window=dict(start=f'{min(year.values())}-01-01',end='2026-10-21',collected_at='2026-10',right_censored=True),
 coverage=dict(procedure='snowball',description='Seeds are 22 papers: ten on scagnostics and its extensions (scatterplots, parallel coordinates, time series) and twelve on related visual quality metrics. First generation: papers citing a seed that cite a scagnostics seed or deal with scatterplots, visual quality measures or view selection. Second generation: papers citing the papers that develop an idea',seeds=[s['short'] for s in seeds_meta],depth_limit=2,selection_rules=['R_SNOWBALL'],
  known_gaps=['The seeds were chosen by the analyst; papers on scagnostics that cite none of them are missing; Tukey and Tukey (1985) is not in the data','Only a selection of links was judged: links of papers flagged by a keyword rule (cue words, influential citations, mentions of scagnostics in title or abstract) were read one by one, 570 links in all (500 from the citing sentence or the title and abstract, 70 from the full text of 12 papers); 11 of them have no citing sentence and stay unassessed; all other links carry the flag unassessed','The first version typed each citing paper once and applied the type to its links. A check against the full text of 12 papers showed that only 16 of 41 develops or applies links were supported, so all flagged first-generation links were judged again one by one in this version','Second-generation links were collected only for the papers that develop an idea and judged for 332 links (cue-selected after the first 70)','The 2020s are incomplete because recent papers have had little time to be cited','Dates are reduced to the publication year; records without a year were given a year by rule and carry the flag time_imputed','Only Semantic Scholar was used for the citation lists; OpenCitations lists fewer citing papers']),
 event_kinds=[dict(id='paper',label='Paper',description='A publication')],
 entity_types=[dict(id='topic_region',label='Topic region',description='Cluster of papers with similar title and abstract words; derived')],entity_relation_types=[],roles=[],
 link_kinds=[dict(id='reference',core_kind='reference',description='The citing paper cites the cited paper',relations=[dict(id='develops',description='The citing paper develops a new or extended measure, technique or concept from the cited idea',propagates_default=True),dict(id='applies',description='The citing paper uses scagnostics or a quality metric in a system or study',propagates_default=True),dict(id='background',description='The citing paper cites the cited work as background',propagates_default=False)],propagates_default=False,default_window_seconds=None,max_gap_seconds=None,direction_rule='From the cited paper to the citing paper; papers of the same year use evidence',levels=['given'])],
 evidence_bases=[dict(id='full_text',label='Full text',description='Full text (PDF) of the citing paper, read by the judge'),dict(id='citation_record',label='Citation record',description='Citation listed by Semantic Scholar'),dict(id='citing_sentence',label='Citing sentence',description='The sentence of the citing paper that cites the cited paper'),dict(id='title_and_abstract',label='Title and abstract',description='Title and abstract of the citing paper, used where no citing sentence exists')],
 rules=[dict(id='R_SNOWBALL',description='Paper is a seed, or cites a seed and cites scagnostics or deals with scatterplots, visual quality measures or view selection',parameters={},applies_to='event')],
 judges=[dict(id='claude_reader',type='model',description='Claude (an Anthropic language model) read the citing sentence, or the title and abstract where none exists, and typed the citing paper as develops, applies or background; one reader, no second reader',agreement=dict(measured=False))],
 flags=[],parameters=dict(time_precision=dict(value='year',description='All papers are dated to the first instant of their publication year; papers of one year are simultaneous'),coords_space=dict(value='scagnostics_topic_map_tsne_unit',description='attrs.coords hold a t-SNE layout of title and abstract words in the unit square; layout hint only')),
 limitations=['One reader judged the papers and agreement was not measured; the reader is a language model','Evidence texts hold a rationale and an excerpt of at most 14 words, not the full citing sentence; the full sentence can be retrieved through source_ref','First-generation links are judged one by one; a link is develops only if the citing paper builds on the cited work itself, and applies only if it uses the cited measure, tool or data (a baseline comparison counts as applies); related-work mentions are background','Cascades overlap because a paper citing several seeds belongs to each of their cascades','The seeds were chosen by the analyst and include related quality-metric work, so the set is wider than scagnostics proper','Year precision hides the order of papers within a year'],
 notes='Hand check: take a develops link; open the citing paper and find the sentence that cites the earlier paper.')
od='/home/claude/pkg/out/scagnostics';st=write_package(od,M,events,ents,[],links,om,omc);print(json.dumps(st)[:600]);print(finalize(od))
tools/package_builders/rail_pkg.py92 lines · pilot script, supersededdownload
import sys,json,collections,datetime as dt;sys.path.insert(0,'/home/claude/pkg')
import pandas as pd,numpy as np
from pkgkit import *
CFG={'DE':dict(dir='/home/claude/cdsde/cascade_dataset_de',tz='Europe/Berlin',name='Germany, long-distance trains',src_name='Rebuilt German delay atlas data set (monthly files of the Deutsche Bahn timetable API collected by piebro/deutsche-bahn-data), 2024-07 to 2026-09',lic='CC BY 4.0 (stated for the source files in the data set README); the derived atlas tables carry no separate licence yet',start='2024-07-01',end='2026-09-30',train='all long-distance types of the source (ICE, IC, EC, ECE, EN, NJ, RJ, RJX, FLX, TGV, ES, EUR, EST, WB, IR, D); S-Bahn and regional trains are not included',gaps=['Coverage step on 3 Nov 2025 (day 490): the source monitored about 100 stations before and about 320 after, so events per day rise by about 12 %','Delays come from planned and changed times in whole minutes','The rebuilt layer holds no reconstructed train runs, so the clock time of an event is derived and not checked against raw times','The German network is the fast, sparse network of long-distance trains; counts per day are not comparable with the all-passenger NL and BE data']),
 'NL':dict(dir='/home/claude/cds/cascade_dataset',tz='Europe/Amsterdam',name='Netherlands, all passenger trains',src_name='Rijden de Treinen train archive (services-2025-01 to services-2026-09)',lic='not recorded in the pilot; to be filled in before the package is shared',start='2025-01-01',end='2026-09-30',train='all passenger services in the archive',gaps=['The clock time of an event is derived and not checked against raw times','Delays are whole minutes']),
 'BE':dict(dir='/home/claude/cds/cascade_dataset',tz='Europe/Brussels',name='Belgium, all passenger trains',src_name='Infrabel punctuality data (2025-01 to 2026-09)',lic='not recorded in the pilot; to be filled in before the package is shared',start='2025-01-01',end='2026-09-30',train='all passenger trains in the Infrabel punctuality data',gaps=['The clock time of an event is derived and not checked against raw times','Delays are whole minutes']),
 'CH':dict(dir='/home/claude/cds/cascade_dataset',tz='Europe/Zurich',name='Switzerland, SBB passenger trains',src_name='SBB / opentransportdata.swiss Istdaten (2025-01 to 2026-10-03)',lic='not recorded in the pilot; to be filled in before the package is shared',start='2025-01-01',end='2026-10-03',train='trains in the SBB Istdaten',gaps=['The clock time of an event is derived and not checked against raw times','Very few events and cascades compared with the other countries','Delays are whole minutes'])}
MECH={'origin':'the train starts 15 or more minutes late','transit':'delay grows by 15 or more minutes on a stretch between two stops','dwell_after_late_connection':'extra dwell of 15 or more minutes after a late incoming train','dwell_unexplained':'extra dwell of 15 or more minutes with no late incoming train found'}
def build(cc,outdir):
    c=CFG[cc];D=c['dir'];sid=f'delay_atlas_{cc.lower()}'
    ev=pd.read_csv(f'{D}/events.csv');ev=ev[ev.country==cc].copy()
    ed=pd.read_csv(f'{D}/edges.csv');ed=ed[ed.country==cc].copy()
    st=pd.read_csv(f'{D}/stations.csv');st=st[st.country==cc]
    lk=pd.read_csv(f'{D}/links.csv');lk=lk[lk.country==cc]
    shift=np.where(ev.minute_of_day<300,1440,0)
    local=pd.to_datetime(ev.date)+pd.to_timedelta(ev.minute_of_day+shift,unit='m')
    utc=local.dt.tz_localize(c['tz'],ambiguous=np.ones(len(ev),dtype=bool),nonexistent='shift_forward').dt.tz_convert('UTC')
    ev['start']=utc.dt.strftime('%Y-%m-%dT%H:%M:%SZ');ev['ep']=((utc-pd.Timestamp('1970-01-01',tz='UTC')).dt.total_seconds()).round().astype('int64').values
    ev['eid']=cc+':'+ev.date+':'+ev.event_id.astype(str)
    ents={};
    for r in st.itertuples():
        ents[f'{cc}:station:{r.station_id}']=dict(id=f'{cc}:station:{r.station_id}',type='station',label=r.name,attrs=dict(lat=r.lat,lon=r.lon,stops=int(r.n_stops),core=bool(r.core)),provenance=dict(source_ids=[dict(source=sid,id=f'station:{r.station_id}')],derived=False))
    for r in ev[['station_id','station_name']].drop_duplicates().itertuples():
        k=f'{cc}:station:{r.station_id}'
        if k not in ents: ents[k]=dict(id=k,type='station',label=r.station_name,attrs={},provenance=dict(source_ids=[dict(source=sid,id=f'station:{r.station_id}')],derived=False))
    for tn in sorted(ev.train_number.unique()):
        k=f'{cc}:train:{tn}';ents[k]=dict(id=k,type='train',label=f'Train {tn}',attrs={},provenance=dict(source_ids=[dict(source=sid,id=f'train:{tn}')],derived=False))
    stub=ed[ed.dst_event_id<0].groupby(['day','src_event_id']).delay_min.sum().to_dict()
    events=[]
    for r in ev.itertuples():
        a=dict(mechanism=r.mechanism,train_number=int(r.train_number),scheduled_time_utc=r.start)
        s=stub.get((r.day,r.event_id))
        if s: a['stub_delay_min']=int(s)
        events.append(dict(id=r.eid,kind='delay_growth',title=f'Train {r.train_number} at {r.station_name}: delay grows by {r.growth_min} min ({r.mechanism})',
          time=dict(start=r.date+'T00:00:00Z',precision='day',basis='recorded'),refs=[dict(entity=f'{cc}:station:{r.station_id}',role='anchor'),dict(entity=f'{cc}:train:{r.train_number}',role='participant')],
          weight=int(r.growth_min),weight_unit='min',attrs=a,provenance=dict(source_ids=[dict(source=sid,id=f'{r.date}/{r.event_id}')],extraction=dict(method=MECH[r.mechanism],rule_ids=['R_EVENT_15']),confidence=None),link_coverage='complete'))
    # relations
    rels={};
    for r in lk.itertuples():
        a,b=sorted((r.from_station_id,r.to_station_id));k=(a,b)
        if k in rels: rels[k]['attrs']['sched_time_min']=min(rels[k]['attrs']['sched_time_min'],float(r.sched_time_min));continue
        rels[k]=dict(id=f'{cc}:adj:{a}-{b}',source=f'{cc}:station:{a}',target=f'{cc}:station:{b}',type='adjacent_to',directed=False,attrs=dict(sched_time_min=float(r.sched_time_min)),provenance=dict(source_ids=[dict(source=sid,id=f'link:{r.link_id}')],derived=False))
    rels=[v for v in rels.values() if v['source'] in ents and v['target'] in ents]
    # links
    KIND={'same_track':('adjacency','R_SAME_TRACK'),'connection':('hand_off','R_CONNECTION'),'explains':('explains','R_EXPLAINS')}
    EP=dict(zip(ev.eid,ev.ep));links=[];omitted=[];oc=collections.Counter()
    dayd=dict(zip(zip(ev.day,ev.event_id),ev.date))
    seen=set()
    for r in ed.itertuples():
        kind,rule=KIND[r.kind];date=dayd.get((r.day,r.src_event_id))
        lid=f'{cc}:{date}:{r.src_event_id}>{r.dst_event_id}:{r.kind}'
        if r.dst_event_id<0:
            oc['no_destination_event']+=1;omitted.append(dict(item_type='link',reason='no_destination_event',id=lid,**{'from':f'{cc}:{date}:{r.src_event_id}'},detail=f'{r.kind} edge reaches a following train that has no event; delay {int(r.delay_min)} min is kept as stub_delay_min of the event'));continue
        f=f'{cc}:{date}:{r.src_event_id}';t=f'{cc}:{date}:{r.dst_event_id}'
        if f not in EP or t not in EP: oc['missing_endpoint']+=1;omitted.append(dict(item_type='link',reason='missing_endpoint',id=lid,**{'from':f,'to':t}));continue
        if (f,t,kind) in seen: oc['duplicate_link']+=1;continue
        seen.add((f,t,kind))
        txt={'same_track':f'Next train on the same stretch, {int(r.gap_min)} min behind, arrives {int(r.delay_min)} min late (window 90 min, arrival delay at least 10 min)','connection':f'Train leaves the same stop 1 to 30 min after the arrival and its departure delay grows by {int(r.delay_min)} min (growth at least 10 min)','explains':f'Dwell traced to a late incoming train that arrives {int(r.gap_min)} min before the departure, arrival delay {int(r.delay_min)} min (at least 10 min)'}[r.kind]
        links.append(dict(id=lid,**{'from':f,'to':t},kind=kind,propagates=(r.kind!='explains'),direction='evidence',gap_seconds=0,
          evidence=dict(existence=dict(level='rule',basis='schedule_rule',rule_id=rule,text=txt,source_ref=dict(source=sid,id=f'{r.day}/{r.src_event_id}>{r.dst_event_id}:{r.kind}'))),attrs=dict(delay_min=int(r.delay_min),rule_gap_minutes=int(r.gap_min))))
    # omitted sample cap
    om=[];cnt=collections.Counter()
    for o in sorted(omitted,key=lambda o:(o['reason'],o['id'])):
        if cnt[o['reason']]<10000: om.append(o);cnt[o['reason']]+=1
    c=dict(c);c['end']=max(c['end'],ev.start.max()[:10]);M=manifest(cc,c,sid,oc)
    return write_package(outdir,M,events,list(ents.values()),rels,links,om,oc,gz=('events.jsonl','links.jsonl','omitted.jsonl') if len(events)>50000 else ())
def manifest(cc,c,sid,oc):
    dm=pd.read_csv(f"{c['dir']}/dataset_meta.csv");dm=dm[dm.country==cc].iloc[0]
    return dict(spec_version='0.1',package_id=f'rail-{cc.lower()}-0.1',created_at=CREATED,
     adapter=dict(name='rail_delay_atlas_adapter',version='0.1',domain='rail',code_ref=None,produced_by='Claude, from the rebuilt delay atlas CSV tables of the cascade project'),
     domain=dict(event_definition='A delay growth of 15 or more minutes of one train: at its origin, on a stretch between two stops, or as extra dwell at a stop. Each event is anchored at the stop where it shows',entity_description='Stations and train numbers; stations are related by adjacency along the network stretches'),
     sources=[dict(id=sid,name=c['src_name'],accessed_at='2026-10',version=f"data set built 2026-10-18 ({dm['n_runs']:,} runs)",license=c['lic'],notes='Tables events.csv, edges.csv, stations.csv, links.csv of the cascade data set')],
     observation_window=dict(start=c['start'],end=c['end'],collected_at='2026-10',right_censored=False),
     coverage=dict(procedure='full',description=f"All events that meet the definition in the monitored stations and train set: {c['train']}",seeds=[],depth_limit=None,selection_rules=['R_EVENT_15'],known_gaps=c['gaps']+['Edges to a following train that has no event (stubs) have no destination and are listed in omitted.jsonl; their delay is kept on the event as stub_delay_min','Events are dated to the operating day only: the schedule-derived clock time cannot order the rule links (for example, a same-track link described as 11 minutes behind has a clock gap of 58 minutes in the atlas), so it is kept as attrs.scheduled_time_utc and not used as the event time','The rule gaps in minutes (headway, connection gap, wait before departure) are in attrs.rule_gap_minutes of each link; gap_seconds is 0 because the two events share the operating day','The rule windows (90 and 30 minutes) were applied by the source rules and cannot be swept again, because the source layer holds no links beyond them']),
     event_kinds=[dict(id='delay_growth',label='Delay growth',description='A train delay grows by 15 or more minutes; the mechanism is in attrs.mechanism')],
     entity_types=[dict(id='station',label='Station',description='Passenger station with coordinates'),dict(id='train',label='Train number',description='A train number; the same number runs on many days')],
     entity_relation_types=[],roles=[],
     link_kinds=[dict(id='adjacency',core_kind='adjacency',description='The delay of an event reaches the next train that follows on the same stretch within 90 minutes',propagates_default=True,default_window_seconds=None,max_gap_seconds=None,direction_rule='From the event of the leading train to the event of the following train; both lie on one operating day, so the direction comes from the evidence (rule R_SAME_TRACK); the rule window is 90 minutes and is stored as attrs.rule_gap_minutes',levels=['rule']),
       dict(id='hand_off',core_kind='hand_off',description='A train leaves the same stop 1 to 30 minutes after the arrival of a late train and its departure delay grows',propagates_default=True,default_window_seconds=None,max_gap_seconds=None,direction_rule='From the feeder event to the connecting event; both lie on one operating day, so the direction comes from the evidence (rule R_CONNECTION); the rule window is 1 to 30 minutes and is stored as attrs.rule_gap_minutes',levels=['rule']),
       dict(id='explains',core_kind='other',description='A dwell event is related to the late incoming train it waited for; annotative, not a passing on of delay',propagates_default=False,default_window_seconds=None,max_gap_seconds=None,direction_rule='From the late incoming train event to the dwell event; both lie on one operating day, so the direction comes from the evidence (rule R_EXPLAINS)',levels=['rule'])],
     evidence_bases=[dict(id='schedule_rule',label='Schedule rule',description='Deterministic rule over the stop-by-stop delays of the train runs')],
     rules=[dict(id='R_EVENT_15',description='Delay growth of at least 15 minutes at the origin, on a stretch or as dwell',parameters=dict(ROOT_TH=15),applies_to='event'),
       dict(id='R_SAME_TRACK',description='Next train on the same stretch within 90 minutes that arrives at least 10 minutes late',parameters=dict(LEG_WINDOW=90,PROP_TH=10),applies_to='link'),
       dict(id='R_CONNECTION',description='Train leaving the same stop 1 to 30 minutes after the arrival whose departure delay grew by at least 10 minutes',parameters=dict(CONN_MIN_GAP=1,CONN_MAX_GAP=30,PROP_TH=10),applies_to='link'),
       dict(id='R_EXPLAINS',description='Dwell event traced to the best late incoming train arriving 1 to 30 minutes before departure with arrival delay of at least 10 minutes',parameters=dict(min_gap=1,max_gap=30,min_arrival_delay=10),applies_to='link')],
     parameters=dict(time_precision=dict(value='day',description='Events are dated to the operating day (start is midnight UTC of the date); events of one day are simultaneous and their links carry direction evidence'),ROOT_TH=dict(value=15,description='Minimum delay growth in minutes that defines an event'),PROP_TH=dict(value=10,description='Minimum delay of a following train or growth at a connection in minutes'),LEG_WINDOW=dict(value=90,description='Window in minutes for the next train on a stretch'),CONN_MIN_GAP=dict(value=1,description='Shortest connection gap in minutes'),CONN_MAX_GAP=dict(value=30,description='Longest connection gap in minutes'),operating_day_cut_minute=dict(value=300,description='For attrs.scheduled_time_utc: clock minutes before 05:00 belong to the calendar day after the operating day (the convention of the atlas cascade tables)'),local_time_zone=dict(value=c['tz'],description='Clock minutes of attrs.scheduled_time_utc are local times converted to UTC')),
     limitations=['Events are dated to the operating day because the available clock time is the scheduled time at the station (schedule plus booked running time) and not the time the delay occurred; it disagrees with the rule gaps for most links and cannot order them','Within a day no ordering of events by time is possible; the order of a link comes from its rule (evidence), and the rule gap in minutes is in attrs.rule_gap_minutes','Time-of-day, tempo and window descriptors cannot be computed from event times; use attrs.scheduled_time_utc only for a rough time of day','Rule windows (90 and 30 minutes) are fixed in the source layer; window sweeps are not possible','Many same-track links join an event to the first event of the following train, which can lie at another station than the leading event; the link states that the following train was hit, not where','Cycles among propagating links exist (pairs of events that follow each other); the algorithm contracts them as simultaneous events','Events a day or more apart are not joined by this rule set','The 05:00 operating-day convention can place very early trains one day late in attrs.scheduled_time_utc','Licence of the source is not recorded for every country','Delays are whole minutes and negative when a train runs early; only growth of 15 minutes or more is an event'],
     warnings=[],
     notes='Hand check: pick any link in links.jsonl; the text states the rule; the two events must share the stretch or the stop named in the anchors.')
if __name__=='__main__':
    cc=sys.argv[1];od=f'/home/claude/pkg/out/rail-{cc.lower()}';st=build(cc,od);print(cc,json.dumps(st)[:300]);print(finalize(od))

3. Declaring the lag of a link kind

For the rail packages the lag of adjacency, hand_off and explains is attrs.rule_gap_minutes (unit minute). The script adds the declaration and the default windows to a manifest without touching the data files:

python add_lag_mapping.py PACKAGE_DIR --map adjacency=rule_gap_minutes:minute \
    --map hand_off=rule_gap_minutes:minute --map explains=rule_gap_minutes:minute \
    --window adjacency=5400,5400 --window hand_off=1800,1800
tools/add_lag_mapping.py50 linesdownload
#!/usr/bin/env python3
"""Declare where a link kind takes its lag from, and optionally its windows, in a package manifest.

This changes manifest.json only. The data files are not touched, so nothing has to be regenerated
(the manifest does not hash itself).

Usage:
    python add_lag_mapping.py PACKAGE_DIR --map adjacency=rule_gap_minutes:minute \
        --map hand_off=rule_gap_minutes:minute --window adjacency=5400,5400 --window hand_off=1800,1800 [--out DIR]

--map KIND=ATTR:UNIT       the lag of KIND is attrs.ATTR of each link, in UNIT (second, minute, hour, day, year)
--window KIND=DEFAULT,MAX  default_window_seconds and max_gap_seconds of KIND (use 'null' for unbounded)
--out DIR                  write the patched manifest.json into DIR instead of PACKAGE_DIR
"""
import argparse, json, os, sys

def num(s):
    return None if s == "null" else float(s)

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("package")
    ap.add_argument("--map", action="append", default=[])
    ap.add_argument("--window", action="append", default=[])
    ap.add_argument("--out")
    a = ap.parse_args()
    path = os.path.join(a.package, "manifest.json")
    m = json.load(open(path, encoding="utf-8"))
    kinds = {k["id"]: k for k in m["link_kinds"]}
    for spec in a.map:
        kind, rest = spec.split("=", 1)
        attr, unit = rest.rsplit(":", 1)
        if kind not in kinds:
            sys.exit(f"unknown link kind {kind}")
        kinds[kind]["lag"] = {"source": "attr", "attr": attr, "unit": unit}
    for spec in a.window:
        kind, rest = spec.split("=", 1)
        d, mx = rest.split(",")
        if kind not in kinds:
            sys.exit(f"unknown link kind {kind}")
        kinds[kind]["default_window_seconds"] = num(d)
        kinds[kind]["max_gap_seconds"] = num(mx)
    out = a.out or a.package
    os.makedirs(out, exist_ok=True)
    json.dump(m, open(os.path.join(out, "manifest.json"), "w", encoding="utf-8"), indent=1, ensure_ascii=False)
    print("patched", os.path.join(out, "manifest.json"))

if __name__ == "__main__":
    main()

4. Validating a package

pip install jsonschema
python validate_package.py packages/policy-us-trade --schema cascade_package.schema.json

The validator reads the manifest, the schema and the files and reports errors and warnings. It checks the schema, the vocabularies declared in the manifest, references between records, the lag of the links, cycles among the links and the hashes of the files. The last line is a summary such as 0 error(s), 0 warning(s). The eight packages of the archive pass with 0 errors. The rail packages have warnings for cycles (events of one operating day that follow each other in a loop through rule links); the algorithm contracts each cycle into one compound event.

tools/validate_package.py529 lines · validatordownload
#!/usr/bin/env python3
"""Validate a cascade package against specification v0.1.

Usage:
    python validate_package.py PACKAGE_DIR [--schema cascade_package.schema.json]
                               [--report report.json] [--max-messages 20]

Exit code 0 if there are no errors (warnings are allowed), 1 otherwise.
Requires: pip install jsonschema
"""
import argparse
import calendar
import collections
import datetime
import gzip
import hashlib
import json
import os
import re
import sys

try:
    import jsonschema
except ImportError:  # pragma: no cover
    sys.exit("This validator needs the jsonschema package: pip install jsonschema")

PRECISIONS = ["second", "minute", "hour", "day", "month", "year"]
LAG_UNIT_SECONDS = {"second": 1, "minute": 60, "hour": 3600, "day": 86400, "year": 31557600}
CORE_ROLES = {"anchor", "source", "target", "participant"}
CORE_FLAGS = {
    "time_imputed", "time_coarse", "title_garbled", "low_confidence",
    "duplicate_merged", "unassessed", "same_owner", "coordinated",
    "propagation_override",
}
FILES = {
    "events": ("events.jsonl", True),
    "entities": ("entities.jsonl", True),
    "entity_relations": ("entity_relations.jsonl", False),
    "links": ("links.jsonl", True),
    "omitted": ("omitted.jsonl", False),
}
PII_PATTERNS = [
    (re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"), "e-mail address"),
    (re.compile(r"(?i)\b(password|passwd|api[_-]?key|secret|token)\s*[=:]\s*\S+"), "possible credential"),
    (re.compile(r"(?<![\d.])(?:10\.\d{1,3}|192\.168|172\.(?:1[6-9]|2\d|3[01]))\.\d{1,3}\.\d{1,3}(?![\d.])"), "private IP address"),
]


class Report:
    def __init__(self, max_messages):
        self.errors = collections.defaultdict(list)
        self.warnings = collections.defaultdict(list)
        self.max_messages = max_messages

    def error(self, code, msg):
        self.errors[code].append(msg)

    def warn(self, code, msg):
        self.warnings[code].append(msg)

    def summary(self):
        return {
            "errors": {k: len(v) for k, v in self.errors.items()},
            "warnings": {k: len(v) for k, v in self.warnings.items()},
        }

    def print(self):
        for kind, store in (("ERROR", self.errors), ("WARNING", self.warnings)):
            for code, msgs in sorted(store.items()):
                print(f"{kind} {code}: {len(msgs)} case(s)")
                for m in msgs[: self.max_messages]:
                    print(f"    {m}")
                if len(msgs) > self.max_messages:
                    print(f"    ... {len(msgs) - self.max_messages} more")
        ne = sum(len(v) for v in self.errors.values())
        nw = sum(len(v) for v in self.warnings.values())
        print(f"\n{ne} error(s), {nw} warning(s)")


def open_maybe_gz(path):
    if os.path.exists(path):
        return open(path, "rb")
    if os.path.exists(path + ".gz"):
        return gzip.open(path + ".gz", "rb")
    return None


def read_jsonl(pkg, name, report):
    path = os.path.join(pkg, name)
    fh = open_maybe_gz(path)
    if fh is None:
        return None, None
    records, raw = [], hashlib.sha256()
    with fh:
        for n, line in enumerate(fh, 1):
            raw.update(line)
            line = line.strip()
            if not line:
                continue
            try:
                records.append((n, json.loads(line.decode("utf-8"))))
            except Exception as exc:  # noqa: BLE001
                report.error("json", f"{name} line {n}: {exc}")
    return records, raw.hexdigest()


def parse_time(s):
    return datetime.datetime.strptime(s[:19], "%Y-%m-%dT%H:%M:%S").replace(
        tzinfo=datetime.timezone.utc
    ) + datetime.timedelta(seconds=float("0" + s[19:-1]) if len(s) > 20 else 0)


def epoch(s):
    dt = parse_time(s)
    return calendar.timegm(dt.timetuple()) + dt.microsecond / 1e6


def truncate(s, precision):
    d = s[:19]
    cut = {"year": 4, "month": 7, "day": 10, "hour": 13, "minute": 16, "second": 19}[precision]
    return d[:cut]


def coarser(p, q):
    return p if PRECISIONS.index(p) >= PRECISIONS.index(q) else q


def simultaneous(ev_a, ev_b):
    pa, pb = ev_a["time"]["precision"], ev_b["time"]["precision"]
    p = coarser(pa, pb)
    return truncate(ev_a["time"]["start"], p) == truncate(ev_b["time"]["start"], p)


def scan_text_for_pii(obj, where, report):
    text = json.dumps(obj, ensure_ascii=False)
    for pat, label in PII_PATTERNS:
        m = pat.search(text)
        if m:
            report.warn("pii", f"{where}: {label} found ({m.group(0)[:40]})")


def validate_schema(records, definition, schema, name, report):
    wrapper = {"$schema": schema["$schema"], "$defs": schema["$defs"], "$ref": f"#/$defs/{definition}"}
    validator = jsonschema.Draft202012Validator(wrapper)
    bad = 0
    for n, rec in records:
        for err in validator.iter_errors(rec):
            bad += 1
            path = "/".join(str(p) for p in err.absolute_path)
            report.error("schema", f"{name} line {n} {path}: {err.message[:160]}")
            break
    return bad


def tarjan_scc(nodes, adj):
    """Iterative Tarjan; returns list of components."""
    index, low, on, stack, comps, idx = {}, {}, set(), [], [], [0]
    for root in nodes:
        if root in index:
            continue
        work = [(root, iter(adj.get(root, ())))]
        index[root] = low[root] = idx[0]
        idx[0] += 1
        stack.append(root)
        on.add(root)
        while work:
            v, it = work[-1]
            advanced = False
            for w in it:
                if w not in index:
                    index[w] = low[w] = idx[0]
                    idx[0] += 1
                    stack.append(w)
                    on.add(w)
                    work.append((w, iter(adj.get(w, ()))))
                    advanced = True
                    break
                if w in on:
                    low[v] = min(low[v], index[w])
            if advanced:
                continue
            work.pop()
            if work:
                low[work[-1][0]] = min(low[work[-1][0]], low[v])
            if low[v] == index[v]:
                comp = []
                while True:
                    w = stack.pop()
                    on.discard(w)
                    comp.append(w)
                    if w == v:
                        break
                comps.append(comp)
    return comps


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("package")
    ap.add_argument("--schema", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "cascade_package.schema.json"))
    ap.add_argument("--report")
    ap.add_argument("--max-messages", type=int, default=20)
    args = ap.parse_args()

    rep = Report(args.max_messages)
    schema = json.load(open(args.schema, encoding="utf-8"))

    # ---- manifest -------------------------------------------------------
    mpath = os.path.join(args.package, "manifest.json")
    if not os.path.exists(mpath):
        rep.error("files", "manifest.json is missing")
        rep.print()
        return 1
    manifest = json.load(open(mpath, encoding="utf-8"))
    validate_schema([(0, manifest)], "manifest", schema, "manifest.json", rep)

    # ---- read files -----------------------------------------------------
    data, hashes = {}, {}
    for key, (fname, required) in FILES.items():
        recs, digest = read_jsonl(args.package, fname, rep)
        if recs is None:
            if required:
                rep.error("files", f"{fname} is missing")
            data[key], hashes[key] = [], None
        else:
            data[key], hashes[key] = recs, digest

    defs = {"events": "event", "entities": "entity", "entity_relations": "entity_relation", "links": "link", "omitted": "omitted"}
    for key, definition in defs.items():
        validate_schema(data[key], definition, schema, FILES[key][0], rep)
    if rep.errors.get("schema") or rep.errors.get("json"):
        # structural problems make the cross-file checks unreliable
        rep.warn("skipped", "cross-file checks skipped because of schema or JSON errors")
        rep.print()
        return 1

    events = {}
    for n, e in data["events"]:
        if e["id"] in events:
            rep.error("duplicate_id", f"events.jsonl line {n}: duplicate event id {e['id']}")
        events[e["id"]] = e
    entities = {}
    for n, e in data["entities"]:
        if e["id"] in entities:
            rep.error("duplicate_id", f"entities.jsonl line {n}: duplicate entity id {e['id']}")
        entities[e["id"]] = e
    links = {}
    for n, l in data["links"]:
        if l["id"] in links:
            rep.error("duplicate_id", f"links.jsonl line {n}: duplicate link id {l['id']}")
        links[l["id"]] = l

    # ---- vocabularies ---------------------------------------------------
    ev_kinds = {v["id"] for v in manifest["event_kinds"]}
    ent_types = {v["id"] for v in manifest["entity_types"]}
    rel_types = {v["id"] for v in manifest.get("entity_relation_types", [])}
    roles = CORE_ROLES | {v["id"] for v in manifest.get("roles", [])}
    lk = {k["id"]: k for k in manifest["link_kinds"]}
    bases = {v["id"] for v in manifest.get("evidence_bases", [])}
    rules = {r["id"] for r in manifest.get("rules", [])}
    judges = {j["id"]: j for j in manifest.get("judges", [])}
    flags_ok = CORE_FLAGS | {f["id"] for f in manifest.get("flags", [])}
    sources = {s["id"] for s in manifest["sources"]}

    def check_source_ids(items, where):
        for si in items:
            if si["source"] not in sources:
                rep.error("vocabulary", f"{where}: source '{si['source']}' is not declared in manifest.sources")

    # ---- entities -------------------------------------------------------
    for n, e in data["entities"]:
        if e["type"] not in ent_types:
            rep.error("vocabulary", f"entity {e['id']}: type '{e['type']}' not declared")
        check_source_ids(e["provenance"]["source_ids"], f"entity {e['id']}")
    for n, r in data["entity_relations"]:
        for end in ("source", "target"):
            if r[end] not in entities:
                rep.error("reference", f"entity relation line {n}: {end} '{r[end]}' is not an entity")
        if r["type"] not in rel_types and r["type"] not in {"part_of", "adjacent_to", "depends_on", "member_of", "other"}:
            rep.error("vocabulary", f"entity relation line {n}: type '{r['type']}' not declared")

    # ---- events ---------------------------------------------------------
    referenced = set()
    first_ts, last_ts = None, None
    for n, e in data["events"]:
        eid = e["id"]
        if e["kind"] not in ev_kinds:
            rep.error("vocabulary", f"event {eid}: kind '{e['kind']}' not declared")
        anchors = [r for r in e["refs"] if r["role"] == "anchor"]
        if len(anchors) != 1:
            rep.error("anchor", f"event {eid}: needs exactly one anchor reference, found {len(anchors)}")
        for r in e["refs"]:
            if r["entity"] not in entities:
                rep.error("reference", f"event {eid}: entity '{r['entity']}' does not exist")
            else:
                referenced.add(r["entity"])
            if r["role"] not in roles:
                rep.error("vocabulary", f"event {eid}: role '{r['role']}' not declared")
        t = e["time"]
        try:
            s_ep = epoch(t["start"])
        except Exception:  # noqa: BLE001
            rep.error("time", f"event {eid}: start '{t['start']}' cannot be parsed")
            continue
        if t.get("end"):
            try:
                if epoch(t["end"]) < s_ep:
                    rep.error("time", f"event {eid}: end is before start")
            except Exception:  # noqa: BLE001
                rep.error("time", f"event {eid}: end '{t['end']}' cannot be parsed")
        if t["basis"] == "imputed" and "time_imputed" not in e.get("flags", []):
            rep.warn("flags", f"event {eid}: time basis is imputed but flag time_imputed is missing")
        for f in e.get("flags", []):
            if f not in flags_ok:
                rep.error("vocabulary", f"event {eid}: flag '{f}' not declared in manifest.flags")
        check_source_ids(e["provenance"]["source_ids"], f"event {eid}")
        if not e["provenance"]["source_ids"]:
            rep.warn("provenance", f"event {eid}: no source ids")
        for rid in e["provenance"].get("extraction", {}).get("rule_ids", []):
            if rid not in rules:
                rep.error("vocabulary", f"event {eid}: rule '{rid}' not declared")
        scan_text_for_pii({"title": e["title"], "attrs": e.get("attrs", {})}, f"event {eid}", rep)
        first_ts = s_ep if first_ts is None else min(first_ts, s_ep)
        last_ts = s_ep if last_ts is None else max(last_ts, s_ep)
    # ids sorted?
    starts = [e["time"]["start"] for _, e in data["events"]]
    if starts != sorted(starts):
        rep.warn("order", "events.jsonl is not sorted by start time")

    # ---- observation window --------------------------------------------
    ow = manifest["observation_window"]
    try:
        ws = epoch(ow["start"] if "T" in ow["start"] else ow["start"] + "T00:00:00Z")
        we = epoch(ow["end"] if "T" in ow["end"] else ow["end"] + "T23:59:59Z")
        if first_ts is not None and (first_ts < ws or last_ts > we):
            rep.warn("window", "some events lie outside manifest.observation_window")
    except Exception:  # noqa: BLE001
        rep.warn("window", "observation_window start or end is not an ISO date")

    # ---- links ----------------------------------------------------------
    seen_pairs = collections.Counter()
    lag_total, lag_zero = collections.Counter(), collections.Counter()
    adj = collections.defaultdict(list)
    has_link = set()
    by_kind, by_level, by_relation, propagating = collections.Counter(), collections.Counter(), collections.Counter(), 0
    for n, l in data["links"]:
        lid = l["id"]
        for end in ("from", "to"):
            if l[end] not in events:
                rep.error("reference", f"link {lid}: {end} '{l[end]}' is not an event")
        if l["from"] == l["to"]:
            rep.error("link", f"link {lid}: from and to are the same event")
        if l["from"] not in events or l["to"] not in events or l["from"] == l["to"]:
            continue
        a, b = events[l["from"]], events[l["to"]]
        k = lk.get(l["kind"])
        # lag: explicit lag_seconds, else the kind's declared attribute, else the timestamp gap
        lag = l["gap_seconds"]
        spec = (k or {}).get("lag", {})
        mapped = None
        if spec.get("source") == "attr":
            val = l.get("attrs", {}).get(spec["attr"])
            if isinstance(val, (int, float)) and not isinstance(val, bool) and val >= 0:
                mapped = val * LAG_UNIT_SECONDS[spec["unit"]]
            else:
                rep.error("lag", f"link {lid}: kind '{l['kind']}' takes its lag from attrs.{spec['attr']}, which is missing or not a non-negative number")
        if "lag_seconds" in l:
            lag = l["lag_seconds"]
            if mapped is not None and abs(mapped - lag) > 1.0:
                rep.warn("lag", f"link {lid}: lag_seconds differs from the lag mapped from attrs.{spec['attr']}")
        elif mapped is not None:
            lag = mapped
        lag_total[l["kind"]] += 1
        if spec.get("source", "timestamp") == "timestamp" and l["gap_seconds"] == 0 and "lag_seconds" not in l:
            lag_zero[l["kind"]] += 1
        if k is None:
            rep.error("vocabulary", f"link {lid}: kind '{l['kind']}' not declared in manifest.link_kinds")
        else:
            rels = {r["id"]: r for r in k.get("relations", [])}
            if "relation" in l:
                if l["relation"] not in rels:
                    rep.error("vocabulary", f"link {lid}: relation '{l['relation']}' not declared for kind '{l['kind']}'")
                default = rels.get(l["relation"], {}).get("propagates_default", k["propagates_default"])
            else:
                default = k["propagates_default"]
            if l["propagates"] != default and "propagation_override" not in l.get("flags", []):
                rep.warn("propagation", f"link {lid}: propagates={l['propagates']} differs from the declared default; add flag propagation_override with a reason in attrs")
            if k["max_gap_seconds"] is not None and lag > k["max_gap_seconds"]:
                rep.error("window", f"link {lid}: lag {lag:.0f} s exceeds max_gap_seconds of kind '{l['kind']}'")
            if k["default_window_seconds"] is not None and k["max_gap_seconds"] is not None and k["default_window_seconds"] > k["max_gap_seconds"]:
                rep.error("window", f"kind '{l['kind']}': default_window_seconds is larger than max_gap_seconds")
            if l["evidence"]["existence"]["level"] not in k["levels"]:
                rep.warn("evidence", f"link {lid}: existence level '{l['evidence']['existence']['level']}' is not listed for kind '{l['kind']}'")
        sim = simultaneous(a, b)
        gap = epoch(b["time"]["start"]) - epoch(a["time"]["start"])
        if not sim and gap < 0:
            rep.error("time_order", f"link {lid}: points backwards in time ({a['time']['start']} to {b['time']['start']}); list it in omitted.jsonl")
        elif sim and l["direction"] != "evidence":
            rep.error("tie_rule", f"link {lid}: events are simultaneous at the coarser precision, direction must be 'evidence'")
        elif l["direction"] == "evidence" and not sim:
            rep.warn("direction", f"link {lid}: direction 'evidence' used although the events are not simultaneous")
        if abs(gap - l["gap_seconds"]) > 1.0 and not (sim and gap < 0):
            rep.error("gap", f"link {lid}: gap_seconds {l['gap_seconds']} differs from the event times ({gap:.0f} s)")
        for part in ("existence", "relation"):
            item = l["evidence"].get(part)
            if not item:
                continue
            if item["basis"] not in bases:
                rep.error("vocabulary", f"link {lid}: evidence basis '{item['basis']}' not declared in manifest.evidence_bases")
            if item["level"] == "rule" and item.get("rule_id") not in rules:
                rep.error("vocabulary", f"link {lid}: rule '{item.get('rule_id')}' not declared in manifest.rules")
            if item["level"] == "judged":
                j = item["judge"]
                if j["id"] not in judges:
                    rep.error("vocabulary", f"link {lid}: judge '{j['id']}' not declared in manifest.judges")
                if j["type"] == "unspecified":
                    rep.warn("judge", f"link {lid}: judge type is unspecified")
            if item.get("text", "").rstrip().endswith("\u2026"):
                rep.warn("truncated_evidence", f"link {lid}: evidence text looks truncated (ends with an ellipsis)")
            if "source_ref" in item and item["source_ref"]["source"] not in sources:
                rep.error("vocabulary", f"link {lid}: source '{item['source_ref']['source']}' not declared")
        for f in l.get("flags", []):
            if f not in flags_ok:
                rep.error("vocabulary", f"link {lid}: flag '{f}' not declared in manifest.flags")
        if "relation" not in l and "unassessed" not in l.get("flags", []) and l["evidence"].get("relation") is None and k and k.get("relations"):
            rep.warn("relation", f"link {lid}: kind '{l['kind']}' has relations but the link has none; add flag unassessed if it was not judged")
        key = (l["from"], l["to"], l["kind"], l.get("relation"))
        seen_pairs[key] += 1
        if seen_pairs[key] == 2:
            rep.error("duplicate_link", f"link {lid}: duplicate of an earlier link {key}")
        has_link.update((l["from"], l["to"]))
        by_kind[l["kind"]] += 1
        by_level[l["evidence"]["existence"]["level"]] += 1
        if "relation" in l:
            by_relation[l["relation"]] += 1
        if l["propagates"]:
            propagating += 1
            adj[l["from"]].append(l["to"])
        scan_text_for_pii({"text": [i.get("text", "") for i in l["evidence"].values() if i]}, f"link {lid}", rep)

    for kind, total in lag_total.items():
        kk = lk.get(kind)
        if kk and kk.get("lag", {}).get("source", "timestamp") == "timestamp" and kk["default_window_seconds"] is not None and total and lag_zero[kind] / total >= 0.95:
            rep.warn("lag_uninformative", f"kind '{kind}': {lag_zero[kind] / total:.0%} of its links have a zero timestamp gap, so its window cannot act; declare a lag source")

    # ---- attribute roles and the meaning of time ---------------------------
    if "time_meaning" not in manifest["domain"]:
        rep.warn("time_meaning", "manifest.domain.time_meaning is missing: state what the event time stands for")
    attr_keys = {"event": set(), "entity": set(), "link": set()}
    for _, e in data["events"]:
        attr_keys["event"].update(e.get("attrs", {}))
    for _, e in data["entities"]:
        attr_keys["entity"].update(e.get("attrs", {}))
    for _, l in data["links"]:
        attr_keys["link"].update(l.get("attrs", {}))
    role_ids = set()
    for r in manifest.get("attribute_roles", []):
        if r["id"] in role_ids:
            rep.error("attribute_role", f"attribute role id '{r['id']}' is used twice")
        role_ids.add(r["id"])
        names = [r["attr"]] if isinstance(r["attr"], str) else r["attr"]
        for nm in names:
            if nm not in attr_keys[r["applies_to"]]:
                rep.error("attribute_role", f"attribute role '{r['id']}': no {r['applies_to']} has the attribute '{nm}'")
        if r["role"] == "position" and len(names) not in (1, 2):
            rep.error("attribute_role", f"attribute role '{r['id']}': a position names one attribute (coordinates object) or two (lat, lon)")
        if r["role"] == "time_of_day":
            try:
                from zoneinfo import ZoneInfo
                ZoneInfo(r["time_zone"])
            except Exception:  # noqa: BLE001
                rep.warn("attribute_role", f"attribute role '{r['id']}': time zone '{r['time_zone']}' is not recognised (or the time zone database is missing)")

    # ---- cycles among propagating links --------------------------------
    for comp in tarjan_scc(list(events), adj):
        if len(comp) > 1:
            same = all(simultaneous(events[comp[0]], events[c]) for c in comp[1:])
            if same:
                rep.warn("cycle", f"cycle among simultaneous events {comp[:6]}; the algorithm contracts it into a compound event")
            else:
                rep.error("cycle", f"cycle among events at different times {comp[:6]}")

    # ---- omitted --------------------------------------------------------
    omitted_by_reason = collections.Counter(o["reason"] for _, o in data["omitted"])

    # ---- manifest statistics and file hashes ---------------------------
    st = manifest["statistics"]
    def expect(name, claimed, actual):
        if claimed != actual:
            rep.error("statistics", f"manifest statistics {name} is {claimed}, the files give {actual}")
    expect("events", st["events"], len(events))
    expect("entities", st["entities"], len(entities))
    expect("entity_relations", st["entity_relations"], len(data["entity_relations"]))
    expect("links.total", st["links"]["total"], len(links))
    expect("links.propagating", st["links"]["propagating"], propagating)
    expect("links.by_kind", st["links"]["by_kind"], dict(by_kind))
    expect("links.by_level", st["links"]["by_level"], dict(by_level))
    if "by_relation" in st["links"]:
        expect("links.by_relation", st["links"]["by_relation"], dict(by_relation))
    expect("events_without_links", st["events_without_links"], len([e for e in events if e not in has_link]))
    expect("unreferenced_entities", st["unreferenced_entities"], len([e for e in entities if e not in referenced]))
    expect("merged_duplicates", st["merged_duplicates"], sum(len(e["provenance"].get("merged_from", [])) for e in events.values()))
    if st["omitted"]["by_reason"] != dict(omitted_by_reason):
        total_claimed = sum(st["omitted"]["by_reason"].values())
        if total_claimed < len(data["omitted"]):
            rep.error("statistics", "omitted.jsonl lists more items than manifest statistics.omitted claims")
        else:
            rep.warn("statistics", "omitted.jsonl is a sample; counts in manifest are larger than the listed items")
    for key, (fname, _) in FILES.items():
        entry = manifest["files"].get(fname)
        if hashes[key] is None:
            continue
        if entry is None:
            rep.error("files", f"manifest.files has no entry for {fname}")
            continue
        if entry["sha256"] != hashes[key]:
            rep.error("files", f"{fname}: sha256 in manifest does not match the file")
        if entry["records"] != len(data[key]):
            rep.error("files", f"{fname}: record count in manifest ({entry['records']}) does not match ({len(data[key])})")

    rep.print()
    if args.report:
        json.dump({"summary": rep.summary(), "errors": rep.errors, "warnings": rep.warnings}, open(args.report, "w"), indent=1)
    return 1 if rep.errors else 0


if __name__ == "__main__":
    sys.exit(main())

cascade_package.schema.json (the schema, 31 KB)

5. Re-running the link extraction

The download cascade_link_extraction.zip holds, for each data set, the input events, a description of the algorithm, the script and the output links. verify_all.py in its root runs all scripts and compares the results with the shipped outputs.

unzip cascade_link_extraction.zip
cd cascade_link_extraction
python verify_all.py        # last line: ALL IDENTICAL
The rail folders of this download describe stage 2 only (rule edges to links) and their ALGORITHM.md files are superseded by code/rail/extraction/ALGORITHM.md, which describes the whole chain from the run table to the package and states where the earlier text was wrong.
tools/verify_all.py55 linesdownload
#!/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()

6. Loading a package in CAVEAT

CAVEAT lists the packages from system/data/index.json (or from the directory listing of system/data/) and reads each package folder: manifest.json first, then the files named in it, gzip files included. It computes the SHA-256 of every file and compares it with the manifest, and the page Package identity shows whether the hashes match. The index has, for each package: id, title, package_id, domain, adapter_version, event_definition, observation_window, coverage_procedure, path, counts, and the list of files with name, role, gzip flag, size, SHA-256 and record count. To add a data set, put its package folder under system/data/ and add its entry to index.json.

7. Building cascades outside the tool

A small reference engine turns a package into episodes, cascades and descriptors in a few lines, and the sweep script shows how the episodes grow when the window of a link kind is widened. Both use only the standard library (the engine also numpy).

python example_run_on_package.py packages/policy-us-trade
python example_run_on_package.py packages/scagnostics --scale 0.5
python window_sweep.py packages/software-npm --json sweep.json
analysis/window_sweep.py72 lines · window sweep of any packagedownload
#!/usr/bin/env python3
"""Window sweep of a cascade package: how the episodes grow when the window of a link kind is widened.

  python window_sweep.py PACKAGE_DIR                       # default windows (days or the unit of the lag), all propagating links
  python window_sweep.py PACKAGE_DIR --windows 3600,21600,86400,604800,2592000 --json sweep.json

For every window w (in seconds) the links whose LAG is at most w are kept and the events are joined into episodes (weakly connected
components, union-find).  Reported: links kept, episodes of at least 3 events, size of the largest episode, share of events in it.
Lag of a link: `lag_seconds` if the link has it, else the lag declared in the manifest for its kind (attribute and unit), else
`gap_seconds`.  Only propagating links count; links without a lag are skipped.  Only the Python standard library is used.
"""
import argparse, collections, gzip, json, os, sys

UNIT = {'second': 1, 'minute': 60, 'hour': 3600, 'day': 86400, 'year': 365.25 * 86400}


def read(path):
    if os.path.exists(path + '.gz'): path += '.gz'
    op = gzip.open if path.endswith('.gz') else open
    with op(path, 'rt', encoding='utf8') as f:
        for line in f:
            if line.strip(): yield json.loads(line)


def lag_seconds(link, lagdecl):
    if link.get('lag_seconds') is not None: return link['lag_seconds']
    d = lagdecl.get(link['kind'])
    if d and d.get('source') == 'attr':
        v = (link.get('attrs') or {}).get(d['attr'])
        return None if v is None else v * UNIT[d['unit']]
    return link.get('gap_seconds')


def sweep(pkg, windows):
    man = json.load(open(os.path.join(pkg, 'manifest.json'), encoding='utf8'))
    lagdecl = {k['id']: k.get('lag') for k in man['link_kinds']}
    ids = [e['id'] for e in read(os.path.join(pkg, 'events.jsonl'))]
    links = [(lag_seconds(l, lagdecl), l['from'], l['to']) for l in read(os.path.join(pkg, 'links.jsonl')) if l['propagates']]
    links = sorted(x for x in links if x[0] is not None)
    rows = []
    for w in windows:
        par = {i: i for i in ids}
        def find(x):
            while par[x] != x:
                par[x] = par[par[x]]; x = par[x]
            return x
        k = 0
        for lag, a, b in links:
            if lag > w: break
            k += 1; ra, rb = find(a), find(b)
            if ra != rb: par[ra] = rb
        size = collections.Counter(find(i) for i in ids).values()
        rows.append(dict(window_seconds=w, links=k, episodes_ge3=sum(1 for s in size if s >= 3), largest=max(size), largest_share=round(max(size) / len(ids), 4)))
    return dict(package=man['package_id'], events=len(ids), propagating_links=len(links), rows=rows)


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument('package'); ap.add_argument('--windows', default='3600,21600,86400,172800,259200,432000,604800,1209600,2592000')
    ap.add_argument('--json')
    a = ap.parse_args()
    res = sweep(a.package, [float(x) for x in a.windows.split(',')])
    print(f"{res['package']}: {res['events']} events, {res['propagating_links']} propagating links with a lag")
    print(f"{'window (s)':>12} {'links':>8} {'episodes>=3':>12} {'largest':>8} {'share':>7}")
    for r in res['rows']:
        print(f"{r['window_seconds']:>12.0f} {r['links']:>8} {r['episodes_ge3']:>12} {r['largest']:>8} {r['largest_share']:>7.1%}")
    if a.json: json.dump(res, open(a.json, 'w'), indent=1)


if __name__ == '__main__':
    main()
core/example_run_on_package.py69 linesdownload
#!/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()
core/cascade_core.py322 lines · reference enginedownload
"""Reference implementation of candidate-cascade detection on an event graph.

Domain-independent. A domain adapter supplies events, entities and typed
candidate links with evidence. This module applies per-link-type windows,
resolves time order and ties, builds the event DAG, and derives episodes
(connected components, a partition) and cascades (reach from a root, an
overlapping cover). It also computes size-independent descriptors, null-model
diagnostics and window sweeps. Detected cascades are candidates for human
assessment, not claims of causation.
"""
from __future__ import annotations
import collections, hashlib, json, math, random
from dataclasses import dataclass, field
from typing import Dict, Iterable, List, Optional, Tuple

VERSION = "0.1"


@dataclass
class Event:
    id: str
    time: float                      # instant, or start of an interval (any consistent unit)
    end: Optional[float] = None      # optional end of an interval
    type: str = ""
    entities: Tuple[Tuple[str, str], ...] = ()   # (entity_id, role)
    attrs: dict = field(default_factory=dict)


@dataclass
class Link:
    src: str
    dst: str
    type: str                        # link type, decides window and meaning
    provenance: str = "derived"      # given | derived | inferred
    direction_basis: str = "time"    # time | evidence
    evidence: dict = field(default_factory=dict)
    weight: Optional[float] = None   # optional


@dataclass
class Config:
    # link type -> (min_gap, max_gap); gap = time(dst) - time(src) after orientation
    windows: Dict[str, Tuple[float, float]] = field(default_factory=dict)
    default_window: Tuple[float, float] = (0.0, math.inf)
    tie_rule: str = "drop"           # drop | by_id  (applies to links with direction_basis "time")
    giant_fraction: float = 0.2      # warn if the largest episode holds more than this share of events
    allowed_provenance: Optional[Tuple[str, ...]] = None   # e.g. ("given",) to use data-given links only

    def window(self, link_type: str) -> Tuple[float, float]:
        return self.windows.get(link_type, self.default_window)


class CycleError(ValueError):
    pass


class Graph:
    """Result of building: kept links, episodes and lazily computed cascades."""

    def __init__(self, events: List[Event], links: List[Link], cfg: Config):
        self.events = {e.id: e for e in events}
        if len(self.events) != len(events):
            raise ValueError("duplicate event ids")
        self.cfg = cfg
        self.kept: List[dict] = []
        self.dropped = collections.Counter()
        for l in links:
            if l.src not in self.events or l.dst not in self.events:
                self.dropped["unknown_endpoint"] += 1
                continue
            if cfg.allowed_provenance and l.provenance not in cfg.allowed_provenance:
                self.dropped["provenance_filtered"] += 1
                continue
            o = self._orient(l)
            if o is None:
                continue
            a, b, gap = o
            lo, hi = cfg.window(l.type)
            if not (lo <= gap <= hi):
                self.dropped["outside_window"] += 1
                continue
            self.kept.append(dict(src=a, dst=b, type=l.type, gap=gap, provenance=l.provenance,
                                  direction_basis=l.direction_basis, evidence=l.evidence, weight=l.weight))
        self.out = collections.defaultdict(list)
        self.indeg = collections.Counter()
        for k in self.kept:
            self.out[k["src"]].append(k)
            self.indeg[k["dst"]] += 1
        self._check_dag()
        self._episodes()

    # ---- time order and ties -------------------------------------------------
    def _orient(self, l: Link):
        ta, tb = self.events[l.src].time, self.events[l.dst].time
        if l.direction_basis == "evidence":
            gap = tb - ta
            if gap < 0:
                self.dropped["evidence_contradicts_time"] += 1
                return None
            return l.src, l.dst, gap
        gap = tb - ta
        if gap > 0:
            return l.src, l.dst, gap
        if gap < 0:
            return l.dst, l.src, -gap
        # tie
        if self.cfg.tie_rule == "by_id":
            a, b = sorted((l.src, l.dst))
            return a, b, 0.0
        self.dropped["tie_dropped"] += 1
        return None

    # ---- structure -----------------------------------------------------------
    def _check_dag(self):
        indeg = collections.Counter(self.indeg)
        queue = [e for e in self.events if indeg[e] == 0]
        seen = 0
        while queue:
            u = queue.pop()
            seen += 1
            for k in self.out[u]:
                indeg[k["dst"]] -= 1
                if indeg[k["dst"]] == 0:
                    queue.append(k["dst"])
        if seen != len(self.events):
            raise CycleError("kept links contain a cycle; check tie rule and evidence-directed links")

    def _episodes(self):
        parent = {e: e for e in self.events}

        def find(x):
            while parent[x] != x:
                parent[x] = parent[parent[x]]
                x = parent[x]
            return x
        for k in self.kept:
            ra, rb = find(k["src"]), find(k["dst"])
            if ra != rb:
                parent[ra] = rb
        groups = collections.defaultdict(list)
        for e in self.events:
            groups[find(e)].append(e)
        self.episodes = sorted(groups.values(), key=lambda g: (-len(g), g[0]))
        self.episode_of = {e: i for i, g in enumerate(self.episodes) for e in g}

    @property
    def roots(self) -> List[str]:
        """Events with no incoming kept link (including isolated events)."""
        return [e for e in self.events if self.indeg[e] == 0]

    def cascade(self, root: str) -> List[str]:
        seen, stack = {root}, [root]
        while stack:
            u = stack.pop()
            for k in self.out[u]:
                if k["dst"] not in seen:
                    seen.add(k["dst"])
                    stack.append(k["dst"])
        return sorted(seen, key=lambda e: (self.events[e].time, e))

    def cascades(self, min_size: int = 1) -> Iterable[Tuple[str, List[str]]]:
        """Lazily yield (root, members). min_size is a display filter, not part of the definition."""
        for r in self.roots:
            m = self.cascade(r)
            if len(m) >= min_size:
                yield r, m

    def diagnostics(self) -> dict:
        n = len(self.events)
        big = len(self.episodes[0]) if self.episodes else 0
        return dict(events=n, kept_links=len(self.kept), dropped=dict(self.dropped), episodes=len(self.episodes),
                    episodes_ge3=sum(1 for g in self.episodes if len(g) >= 3), largest_episode=big,
                    largest_fraction=big / n if n else 0.0,
                    giant_warning=bool(n and big / n > self.cfg.giant_fraction))

    # ---- descriptors -----------------------------------------------------------
    def descriptors(self, members: List[str], root: str) -> dict:
        ms = set(members)
        edges = [k for e in members for k in self.out[e] if k["dst"] in ms]
        lvl, tree_children = {root: 0}, collections.Counter()
        q = collections.deque([root])
        while q:
            u = q.popleft()
            for k in self.out[u]:
                v = k["dst"]
                if v in ms and v not in lvl:
                    lvl[v] = lvl[u] + 1
                    tree_children[u] += 1
                    q.append(v)
        n = len(ms)
        depth = max(lvl.values())
        fan_tree = max(tree_children.values(), default=0)
        breadth = max(collections.Counter(lvl.values()).values())
        extra = len(edges) - (n - 1)
        times = [self.events[e].time for e in members]
        ents = {e for m in members for e, _ in self.events[m].entities}
        etypes = {self.events[m].type for m in members}
        mix = collections.Counter(k["type"] for k in edges)
        vir = None
        if 2 < n <= 300:                       # mean path length relative to a chain of the same size
            adj = collections.defaultdict(list)
            for k in edges:
                adj[k["src"]].append(k["dst"])
                adj[k["dst"]].append(k["src"])
            tot, cnt = 0, 0
            for s in members:
                dist = {s: 0}
                dq = collections.deque([s])
                while dq:
                    u = dq.popleft()
                    for v in adj[u]:
                        if v not in dist:
                            dist[v] = dist[u] + 1
                            dq.append(v)
                tot += sum(dist.values())
                cnt += len(dist) - 1
            vir = (tot / cnt) / ((n + 1) / 3) if cnt else None
        shape = "Relay" if depth >= n - 1 else ("Broadcast" if depth <= 1 else "Branching")
        return dict(size=n, depth=depth, depth_ratio=depth / (n - 1) if n > 1 else 0.0,
                    fan_tree=fan_tree, fan_ratio=fan_tree / (n - 1) if n > 1 else 0.0,
                    breadth_ratio=breadth / n, extra_edges=extra, joined=extra >= 1,
                    path_length_ratio=vir, duration=max(times) - min(times),
                    entity_spread=len(ents), event_type_spread=len(etypes),
                    link_type_mix={t: c / len(edges) for t, c in mix.items()} if edges else {},
                    shape=shape)

    def candidate_record(self, root: str, members: Optional[List[str]] = None) -> dict:
        members = members or self.cascade(root)
        ms = set(members)
        links = [dict(src=k["src"], dst=k["dst"], type=k["type"], gap=k["gap"], provenance=k["provenance"],
                      direction_basis=k["direction_basis"], evidence=k["evidence"])
                 for e in members for k in self.out[e] if k["dst"] in ms]
        return dict(root=root, members=members, episode=self.episode_of[root], links=links,
                    descriptors=self.descriptors(members, root), parameters=params_record(self.cfg))


def params_record(cfg: Config) -> dict:
    return dict(version=VERSION, windows={k: list(v) for k, v in cfg.windows.items()},
                default_window=list(cfg.default_window), tie_rule=cfg.tie_rule,
                allowed_provenance=list(cfg.allowed_provenance) if cfg.allowed_provenance else None)


def run_hash(events: List[Event], links: List[Link], cfg: Config) -> str:
    blob = json.dumps(dict(p=params_record(cfg), e=sorted((e.id, e.time) for e in events),
                           l=sorted((l.src, l.dst, l.type) for l in links)), sort_keys=True, default=str)
    return hashlib.sha256(blob.encode()).hexdigest()[:16]


# ---- null models (ranking aid, not a hypothesis test) ------------------------------------
def _shuffled(events: List[Event], scheme: str, rng: random.Random, block: float = 7.0,
              group_key=lambda e: e.entities[0][0] if e.entities else "") -> List[Event]:
    t = [e.time for e in events]
    if scheme == "global":
        rng.shuffle(t)
        times = t
    elif scheme == "block":                       # permute times within blocks of the given length
        t0 = min(t)
        buckets = collections.defaultdict(list)
        for i, x in enumerate(t):
            buckets[int((x - t0) // block)].append(i)
        times = list(t)
        for idx in buckets.values():
            vals = [t[i] for i in idx]
            rng.shuffle(vals)
            for i, v in zip(idx, vals):
                times[i] = v
    elif scheme == "entity_shift":                # circular shift of each entity's whole timeline
        t0, span = min(t), (max(t) - min(t)) or 1.0
        off = {}
        times = []
        for e in events:
            g = group_key(e)
            off.setdefault(g, rng.uniform(0, span))
            times.append(t0 + ((e.time - t0) + off[g]) % span)
    else:
        raise ValueError(scheme)
    return [Event(e.id, x, e.end, e.type, e.entities, e.attrs) for e, x in zip(events, times)]


def null_diagnostics(events, links, cfg, scheme="block", reps=200, seed=0, **kw) -> dict:
    rng = random.Random(seed)
    rows = []
    for _ in range(reps):
        try:
            g = Graph(_shuffled(events, scheme, rng, **kw), links, cfg)
        except CycleError:
            continue
        d = g.diagnostics()
        rows.append((d["kept_links"], d["episodes_ge3"], d["largest_episode"]))
    return dict(scheme=scheme, reps=len(rows), links=[r[0] for r in rows], episodes_ge3=[r[1] for r in rows],
                largest=[r[2] for r in rows])


def tail_p(null_values: List[float], observed: float) -> float:
    """Empirical tail probability, never below 1/(R+1)."""
    r = len(null_values)
    return (1 + sum(1 for v in null_values if v >= observed)) / (r + 1)


# ---- parameter control: window sweep -----------------------------------------------
def window_sweep(events, links, cfg, scales=(0.25, 0.5, 1, 2, 4, 8)) -> List[dict]:
    out = []
    for s in scales:
        c = Config(windows={k: (lo, hi * s) for k, (lo, hi) in cfg.windows.items()},
                   default_window=(cfg.default_window[0], cfg.default_window[1] * s),
                   tie_rule=cfg.tie_rule, giant_fraction=cfg.giant_fraction, allowed_provenance=cfg.allowed_provenance)
        d = Graph(events, links, c).diagnostics()
        d["scale"] = s
        out.append(d)
    return out


def suggest_scale(sweep: List[dict]) -> Optional[float]:
    """Largest window scale below the steepest log-log growth of the largest episode (percolation onset)."""
    best, arg = -1.0, None
    for a, b in zip(sweep, sweep[1:]):
        if a["largest_episode"] > 0 and b["largest_episode"] > 0:
            slope = (math.log(b["largest_episode"]) - math.log(a["largest_episode"])) / (math.log(b["scale"]) - math.log(a["scale"]))
            if slope > best:
                best, arg = slope, a["scale"]
    return arg
core/test_cascade_core.py237 lines · testsdownload
"""Tests on synthetic event graphs with planted cascades. No domain data, no domain ground truth.

Run: python3 test_cascade_core.py
"""
import collections, random, sys
sys.path.insert(0, ".")
from cascade_core import (Config, CycleError, Event, Graph, Link, null_diagnostics, run_hash, suggest_scale,
                          tail_p, window_sweep)

CFG = Config(windows={"A": (0.0, 10.0), "B": (0.0, 50.0)})


def plant(rng, n_cascades=40, noise_events=200, horizon=5000.0, shapes=("relay", "broadcast", "branching"), in_window_noise=0, entity_mode="station"):
    """Plant cascades far apart in time, add isolated noise events and out-of-window noise links."""
    events, links, planted = [], [], []
    eid = 0
    for c in range(n_cascades):
        shape = shapes[c % len(shapes)]
        size = rng.randint(3, 9)
        t0 = 100.0 * c + rng.uniform(0, 5)
        ids = []
        for _ in range(size):
            ids.append(f"e{eid}")
            eid += 1
        times = {ids[0]: t0}
        lt = "A" if c % 2 == 0 else "B"
        w = 10.0 if lt == "A" else 50.0
        for i in range(1, size):
            parent = ids[i - 1] if shape == "relay" else (ids[0] if shape == "broadcast" else ids[rng.randrange(0, i)])
            times[ids[i]] = times[parent] + rng.uniform(0.5, w * 0.9) * (0.2 if shape == "relay" else 1.0)
            links.append(Link(parent, ids[i], lt, direction_basis="time"))
        for i in ids:
            ent = f"station{c % 7}" if entity_mode == "station" else f"ent{rng.randrange(30)}"
            events.append(Event(i, times[i], entities=((ent, "at"),)))
        planted.append((ids[0], set(ids), shape))
    for _ in range(noise_events):
        events.append(Event(f"n{eid}", rng.uniform(0, horizon), entities=((f"ent{rng.randrange(30)}" if entity_mode != "station" else "noise", "at"),)))
        eid += 1
    noise = [e for e in events if e.id.startswith("n")]
    for _ in range(in_window_noise):
        a, b = rng.sample(noise, 2)
        events_t = abs(a.time - b.time)
        if events_t <= 10:
            links.append(Link(a.id, b.id, "A"))
    for _ in range(300):                 # out-of-window noise links among noise events (must be dropped)
        a, b = rng.sample(noise, 2)
        links.append(Link(a.id, b.id, "A"))
    return events, links, planted


def test_invariants():
    rng = random.Random(1)
    events, links, _ = plant(rng, in_window_noise=2000)
    g = Graph(events, links, CFG)                       # raises if not a DAG
    flat = [e for ep in g.episodes for e in ep]
    assert len(flat) == len(set(flat)) == len(events), "episodes must partition the events"
    for root, members in g.cascades():
        assert g.indeg[root] == 0, "root has an incoming link"
        eps = {g.episode_of[m] for m in members}
        assert len(eps) == 1, "cascade must lie inside one episode"
    for k in g.kept:
        assert g.events[k["src"]].time <= g.events[k["dst"]].time
    return "invariants hold (DAG, partition, cascade inside one episode, roots, time order)"


def test_recovery_exact():
    rng = random.Random(2)
    events, links, planted = plant(rng, in_window_noise=0)
    g = Graph(events, links, CFG)
    found = {r: set(m) for r, m in g.cascades(min_size=2)}
    hit = sum(1 for root, mem, _ in planted if found.get(root) == mem)
    assert hit == len(planted), f"recovered {hit} of {len(planted)}"
    shapes_ok = 0
    for root, mem, shape in planted:
        d = g.descriptors(sorted(mem), root)
        expected = {"relay": "Relay", "broadcast": "Broadcast", "branching": None}[shape]
        if expected is None or d["shape"] == expected:
            shapes_ok += 1
    assert shapes_ok == len(planted)
    return f"all {len(planted)} planted cascades recovered exactly; strict shape labels agree for relay and broadcast"


def test_recovery_with_noise():
    rng = random.Random(3)
    events, links, planted = plant(rng, in_window_noise=3000)
    g = Graph(events, links, CFG)
    found = {r: set(m) for r, m in g.cascades(min_size=2)}
    hit = sum(1 for root, mem, _ in planted if found.get(root) == mem)
    noise_cascades = [m for r, m in g.cascades(min_size=2) if r.startswith("n")]
    assert hit == len(planted)
    return f"planted cascades unaffected by in-window noise ({hit}/{len(planted)}); {len(noise_cascades)} noise candidates appear, median size {sorted(len(m) for m in noise_cascades)[len(noise_cascades)//2] if noise_cascades else 0}"


def test_window_per_type():
    ev = [Event("a", 0), Event("b", 20), Event("c", 0), Event("d", 20)]
    ln = [Link("a", "b", "A"), Link("c", "d", "B")]
    g = Graph(ev, ln, CFG)
    kept = {(k["src"], k["dst"]) for k in g.kept}
    assert kept == {("c", "d")}, kept
    assert g.dropped["outside_window"] == 1
    return "gap 20 is dropped for type A (window 10) and kept for type B (window 50)"


def test_ties():
    ev = [Event("a", 5), Event("b", 5)]
    g1 = Graph(ev, [Link("a", "b", "A")], Config(windows={"A": (0, 10)}, tie_rule="drop"))
    assert not g1.kept and g1.dropped["tie_dropped"] == 1
    g2 = Graph(ev, [Link("a", "b", "A", direction_basis="evidence")], Config(windows={"A": (0, 10)}))
    assert len(g2.kept) == 1 and g2.kept[0]["src"] == "a"
    g3 = Graph([Event("a", 5), Event("b", 1)], [Link("a", "b", "A", direction_basis="evidence")], CFG)
    assert not g3.kept and g3.dropped["evidence_contradicts_time"] == 1
    return "same-time link: dropped under 'drop', kept when the evidence gives the direction, contradiction reported"


def test_cycle_detection():
    ev = [Event("a", 1), Event("b", 1), Event("c", 1)]
    ln = [Link(x, y, "A", direction_basis="evidence") for x, y in [("a", "b"), ("b", "c"), ("c", "a")]]
    try:
        Graph(ev, ln, Config(windows={"A": (0, 10)}))
    except CycleError:
        return "evidence-directed cycle at equal times raises CycleError"
    raise AssertionError("cycle not detected")


def test_descriptors():
    def build(edges, times):
        ev = [Event(i, t) for i, t in times.items()]
        return Graph(ev, [Link(a, b, "A") for a, b in edges], Config(windows={"A": (0, 100)}))
    path = build([("a", "b"), ("b", "c"), ("c", "d")], dict(a=0, b=1, c=2, d=3))
    d = path.descriptors(["a", "b", "c", "d"], "a")
    assert d["shape"] == "Relay" and d["depth_ratio"] == 1.0 and not d["joined"] and abs(d["path_length_ratio"] - 1.0) < 1e-9
    star = build([("a", "b"), ("a", "c"), ("a", "d")], dict(a=0, b=1, c=2, d=3))
    d = star.descriptors(["a", "b", "c", "d"], "a")
    assert d["shape"] == "Broadcast" and d["fan_ratio"] == 1.0 and d["path_length_ratio"] < 1.0
    ff = build([("a", "b"), ("a", "c"), ("b", "c")], dict(a=0, b=1, c=2))
    d = ff.descriptors(["a", "b", "c"], "a")
    assert d["shape"] == "Broadcast" and d["joined"] and d["extra_edges"] == 1
    tree = build([("a", "b"), ("a", "c"), ("b", "d"), ("c", "e")], dict(a=0, b=1, c=2, d=3, e=4))
    d = tree.descriptors(["a", "b", "c", "d", "e"], "a")
    assert d["shape"] == "Branching"
    return "chain, star and feed-forward triangle (the three 3-event motifs) and a tree get the expected shape, joins and ratios"


def test_min_size_is_display_only():
    rng = random.Random(4)
    events, links, _ = plant(rng, in_window_noise=0)
    g = Graph(events, links, CFG)
    sizes_all = [len(m) for _, m in g.cascades()]
    assert 1 in sizes_all and len(sizes_all) > len([1 for s in sizes_all if s >= 3])
    assert sum(len(ep) for ep in g.episodes) == len(events)
    return f"{sum(1 for s in sizes_all if s == 1)} single-event cascades are kept in the output; size filtering is left to the caller"


def test_giant_warning_and_sweep():
    rng = random.Random(5)
    events = [Event(f"x{i}", rng.uniform(0, 1000)) for i in range(400)]
    links = [Link(f"x{rng.randrange(400)}", f"x{rng.randrange(400)}", "A") for _ in range(1200)]
    links = [l for l in links if l.src != l.dst]
    cfg = Config(windows={"A": (0, 5)}, giant_fraction=0.2)
    sweep = window_sweep(events, links, cfg, scales=(0.25, 0.5, 1, 2, 4, 8, 16, 32, 64))
    frac = [round(s["largest_fraction"], 2) for s in sweep]
    assert frac[-1] > frac[0] and sweep[-1]["giant_warning"] and not sweep[0]["giant_warning"]
    s = suggest_scale(sweep)
    assert s is not None
    return f"largest-episode fraction grows {frac} over the window scales; giant warning off at scale 0.25 and on at 64; suggested scale {s}"


def test_null_models():
    rng = random.Random(6)
    events, links, planted = plant(rng, n_cascades=40, noise_events=400, in_window_noise=0, entity_mode="mixed")
    cfg = CFG
    obs = Graph(events, links, cfg).diagnostics()
    rows = []
    for scheme, kw in [("global", {}), ("block", dict(block=500.0)), ("entity_shift", {})]:
        nd = null_diagnostics(events, links, cfg, scheme=scheme, reps=100, seed=1, **kw)
        p = tail_p(nd["episodes_ge3"], obs["episodes_ge3"])
        rows.append((scheme, round(sum(nd["episodes_ge3"]) / len(nd["episodes_ge3"]), 1), round(p, 3)))
        assert nd["reps"] > 0
    # pure noise: same pipeline on events with no planted structure must not look surprising
    noise_ev = [Event(f"z{i}", rng.uniform(0, 5000), entities=((f"ent{rng.randrange(30)}", "at"),)) for i in range(400)]
    noise_ln = [Link(f"z{rng.randrange(400)}", f"z{rng.randrange(400)}", "A") for _ in range(400)]
    noise_ln = [l for l in noise_ln if l.src != l.dst]
    o2 = Graph(noise_ev, noise_ln, cfg).diagnostics()
    nd2 = null_diagnostics(noise_ev, noise_ln, cfg, scheme="global", reps=100, seed=2)
    p2 = tail_p(nd2["episodes_ge3"], o2["episodes_ge3"])
    assert all(p <= 0.05 for _, _, p in rows), rows
    assert p2 > 0.05, p2
    return f"cross-entity planted data (observed episodes of 3+: {obs['episodes_ge3']}); null mean and tail p {rows}; pure noise tail p {p2:.2f}. p is bounded below by 1/(R+1)"


def test_entity_shift_semantics():
    """Per-entity circular shift keeps each entity's own timeline. It rejects only cross-entity alignment."""
    rng = random.Random(8)
    ev_in, ln_in, _ = plant(rng, n_cascades=40, noise_events=400, entity_mode="station")   # cascades inside one entity
    obs_in = Graph(ev_in, ln_in, CFG).diagnostics()
    nd_in = null_diagnostics(ev_in, ln_in, CFG, scheme="entity_shift", reps=100, seed=3)
    p_in = tail_p(nd_in["episodes_ge3"], obs_in["episodes_ge3"])
    assert p_in > 0.05, p_in
    return f"cascades that live inside one entity's rhythm are not rejected by the entity-shift null (tail p {p_in:.2f}): the strict null measures cross-entity alignment only"


def test_reproducibility():
    rng = random.Random(7)
    events, links, _ = plant(rng)
    h1, h2 = run_hash(events, links, CFG), run_hash(events, links, CFG)
    g1, g2 = Graph(events, links, CFG), Graph(events, links, CFG)
    assert h1 == h2 and [k["src"] for k in g1.kept] == [k["src"] for k in g2.kept]
    root, members = next(iter(g1.cascades(min_size=3)))
    rec = g1.candidate_record(root, members)
    assert rec["parameters"]["windows"]["A"] == [0.0, 10.0] and rec["links"] and "gap" in rec["links"][0]
    return f"run hash {h1}; candidate record carries members, typed links with gaps and the parameters used"


def test_provenance_filter():
    ev = [Event("a", 0), Event("b", 1), Event("c", 2)]
    ln = [Link("a", "b", "A", provenance="given"), Link("b", "c", "A", provenance="inferred")]
    full = Graph(ev, ln, CFG)
    given = Graph(ev, ln, Config(windows=CFG.windows, allowed_provenance=("given",)))
    assert len(full.episodes[0]) == 3 and len(given.episodes[0]) == 2
    return "cascades can be recomputed from data-given links only (3 events with all links, 2 with given links)"


if __name__ == "__main__":
    tests = [test_invariants, test_recovery_exact, test_recovery_with_noise, test_window_per_type, test_ties,
             test_cycle_detection, test_descriptors, test_min_size_is_display_only, test_giant_warning_and_sweep,
             test_null_models, test_entity_shift_semantics, test_reproducibility, test_provenance_filter]
    failed = 0
    for t in tests:
        try:
            msg = t()
            print(f"PASS {t.__name__}: {msg}")
        except Exception as e:
            failed += 1
            print(f"FAIL {t.__name__}: {type(e).__name__}: {e}")
    print(f"{len(tests) - failed} of {len(tests)} tests passed")
    sys.exit(1 if failed else 0)