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))