"""Compare schematic station groups. Run on a CSV with GTFS stops.txt columns.""" import csv import json import sys import unicodedata from collections import defaultdict from decimal import Decimal, ROUND_HALF_EVEN def station_groups(rows): rows = list(rows) if len({row['stop_id'] for row in rows}) != len(rows): raise ValueError('stop_id must be unique') stations = {r['stop_id'] for r in rows if r.get('location_type') == '1'} groups = defaultdict(list) for row in rows: if row.get('location_type', '') not in ('', '0'): continue parent = row.get('parent_station', '').strip() if parent: if parent not in stations: raise ValueError('Missing station row for ' + parent) key = ('parent_station', parent) else: name = ' '.join(unicodedata.normalize('NFC', row['stop_name']).casefold().split()) coords = [Decimal(row[k]).quantize(Decimal('0.00001'), rounding=ROUND_HALF_EVEN) for k in ('stop_lat','stop_lon')] if not name or not all(value.is_finite() for value in coords): raise ValueError('A stop without a parent requires a name and two finite coordinates') key = ('name_and_point', name, *(format(abs(v) if not v else v, 'f') for v in coords)) groups[key].append(row['stop_id']) return [{'basis':key[0], 'group':list(key[1:]), 'platforms':sorted(platforms)} for key, platforms in sorted(groups.items())] if __name__ == '__main__': with open(sys.argv[1], encoding='utf-8-sig', newline='') as source: print(json.dumps(station_groups(csv.DictReader(source)),indent=2,ensure_ascii=False))