"""Rebuild the local WalStat joined data, estimates and chart data from pinned sources.""" import argparse from collections import Counter, defaultdict import csv from datetime import datetime from decimal import Decimal, InvalidOperation from hashlib import file_digest import json from math import expm1, fsum, log, log1p, sqrt from pathlib import Path import re from zoneinfo import ZoneInfo ROOT = Path(__file__).resolve().parent YEARS = range(2013, 2025) PRE_MERGER = {'82003', '82005'} MERGED = '82039' LICENSE = 'https://walstat.iweps.be/walstat.php?action=open-data' BANDS = ((5000, '< 5,000'), (10000, '5,000–9,999'), (20000, '10,000–19,999'), (50000, '20,000–49,999'), (float('inf'), '50,000+')) SERIES = { 'ordinary': ('811501_1', 'ordinary-811501_1.csv', 'https://walstat.iweps.be/walstat-catalogue.php?indicateur_id=811501&ordre=1', 'Ordinary municipal expenditure, booked, current EUR per resident'), 'extraordinary': ('811501_2', 'extraordinary-811501_2.csv', 'https://walstat.iweps.be/walstat-catalogue.php?indicateur_id=811501&ordre=2', 'Extraordinary municipal expenditure, booked, current EUR per resident'), 'overnight': ('812501_0', 'walstat-812501_0-overnights-communes-all.csv', 'https://walstat.iweps.be/walstat-catalogue.php?indicateur_id=812501&niveau_agre=C&ordre=0&sel_niveau_catalogue=T&theme_id=11', 'Tourist accommodation overnight stays, number'), 'population': ('200300_0', 'walstat-200300_0-population-communes-all.csv', 'https://walstat.iweps.be/walstat-catalogue.php?indicateur_id=200300&niveau_agre=C&ordre=0', 'Legal population at 1 January, persons'), } MISSING = {'non disponible': 'unavailable', 'non diffusé': 'withheld_not_disseminated', "pas assez d'établissements": 'withheld_too_few_establishments'} def digest(path): with path.open('rb') as handle: return file_digest(handle, 'sha256').hexdigest() def save_json(path, data): path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + '\n', encoding='utf-8') def source_manifest(): files = {} for name, (indicator, file, definition, measure) in SERIES.items(): path = ROOT/'sources'/file files[name] = { 'indicator': indicator, 'file': 'sources/'+file, 'sha256': digest(path), 'bytes': path.stat().st_size, 'captured_at_brussels': datetime.fromtimestamp(path.stat().st_mtime, ZoneInfo('Europe/Brussels')).isoformat(), 'url': f'https://opendata.iweps.be/api/data/csv/{indicator}/com+period=all', 'definition': definition, 'measure': measure, } for name in ('ordinary', 'extraordinary'): path = (ROOT/files[name]['file']).with_suffix('.json') files[name]['publisher_json'] = {'file': str(path.relative_to(ROOT)), 'sha256': digest(path), 'url': files[name]['url'].replace('/csv/', '/json/')} return {'publisher': 'IWEPS WalStat', 'reuse': 'CC0', 'reuse_evidence': LICENSE, 'capture_note': 'Publisher responses generated on request and pinned by SHA-256.', 'series':files} def value_state(token): try: value = Decimal(token) except InvalidOperation: if token not in MISSING: raise ValueError(f'Unknown publisher value marker {token!r}') from None return None, MISSING[token] if not value.is_finite() or value < 0: raise ValueError(f'Unexpected numeric publisher value {token!r}') return value, 'observed_zero' if value == 0 else 'observed' def read_series(name, source): path = ROOT/source['file'] assert digest(path)==source['sha256'], path rows = {} with path.open(newline='',encoding='utf-8-sig') as handle: records = csv.reader(handle) # IWEPS CSV has a blank value-column heading. JSON names it valeur. assert next(records)==['ins','type_entite','entite','periode'], path for row_number, fields in enumerate(records, 2): assert len(fields)==5, (path, row_number) ins, level, commune, period, token = fields assert re.fullmatch(r'\d{5}',ins) and level=='Commune', (path, row_number) year = int(period[-4:]) if year not in YEARS: continue coordinate = ins, year assert coordinate not in rows, (name, coordinate) value, state = value_state(token.strip()) if name in ('population','overnight') and value is not None: assert value == value.to_integral_value(), (name, coordinate) rows[coordinate] = (commune, value, state, row_number, token.strip(), period) if 'publisher_json' in source: other = ROOT/source['publisher_json']['file'] assert digest(other)==source['publisher_json']['sha256'] publisher = {(item['ins'], int(item['periode'][-4:])):(item['entite'], item['valeur']) for item in json.loads(other.read_text(encoding='utf-8'))} assert publisher == {key:(row[0],row[4]) for key,row in rows.items()}, name return rows def size_band(population): if population is None or population <= 0: return '' return next(label for upper, label in BANDS if population < upper) def assemble(series): rows = [] union = set().union(*(source.keys() for source in series.values())) for ins, year in sorted(union, key=lambda key:(key[1], key[0])): matched = {name: source.get((ins,year)) for name, source in series.items()} names = {item[0] for item in matched.values() if item} assert len(names)==1, (ins,year,names) row = {'ins':ins,'commune':names.pop(),'year':year} for name,item in matched.items(): _, value, state, line, raw, period = item or ('',None,'key_absent',None,'','') row[name] = value row[name+'_status'] = state row[name+'_raw'] = raw row[name+'_source_row'] = line row[name+'_publisher_period'] = period row['population_band'] = size_band(row['population']) row['geography'] = 'merged_overlap_excluded' if ins == MERGED else ( 'merger_year_component' if ins in PRE_MERGER and year==2024 else 'historical_commune') if ins == MERGED: row['scope'] = 'excluded_merged_duplicate' elif year < 2015: row['scope'] = 'before_tourism_series_break' elif row['geography']=='merger_year_component': row['scope'] = 'excluded_merger_transition_year' elif any(row[name] is None for name in SERIES): row['scope'] = 'missing_measure' elif row['ordinary'] <= 0 or row['population'] <= 0: row['scope'] = 'ineligible_scale' else: row['scope'] = 'eligible' rows.append(row) return rows def dot(left, right): return fsum(a*b for a,b in zip(left,right)) def demean(values, groups): sums = defaultdict(list) for group, value in zip(groups, values): sums[group].append(value) means = {group:fsum(items)/len(items) for group,items in sums.items()} return [value-means[group] for group,value in zip(groups,values)] def strip_controls(vector, controls): if not controls: return vector first = controls[0] coefficient = dot(vector,first)/dot(first,first) residual = [value-coefficient*control for value,control in zip(vector,first)] if len(controls)==1: return residual second = strip_controls(controls[1], [first]) return strip_controls(residual, [second]) def estimate(rows, adjustment): groups = [r['year'] if adjustment==0 else (r['year'],r['population_band']) for r in rows] towns = [r['ins'] for r in rows] x = demean([log(r['ordinary']) for r in rows], groups) y = demean([log1p(r['overnight']) for r in rows], groups) controls = [] if adjustment >= 1: controls.append(demean([log(r['population']) for r in rows],groups)) if adjustment == 2: controls.append(demean([log1p(r['extraordinary']) for r in rows],groups)) x = strip_controls(x, controls) y = strip_controls(y, controls) squared = dot(x,x) slope = dot(x,y)/squared scores = defaultdict(float) for town, xv, yv in zip(towns,x,y): scores[town] += xv*(yv-slope*xv) n, g = len(rows),len(scores) p = len(set(groups))+len(controls)+1 variance = fsum(score*score for score in scores.values())/(squared*squared)*g/(g-1)*(n-1)/(n-p) se = sqrt(variance) ci = [slope-1.96*se,slope+1.96*se] return {'n_commune_years':n,'n_communes':g,'slope':slope,'cluster_robust_se':se,'approx_95_ci':ci, 'percent_in_1_plus_overnights_for_10_percent_ordinary':100*expm1(slope*log1p(.10)), 'first_year':min(r['year'] for r in rows),'last_year':max(r['year'] for r in rows)} def qualify(rows): # Arithmetic witness. A pair is never summed while also counting its merged footprint. assert len(rows)==263*12 historical = [r for r in rows if r['ins']!=MERGED] assert len(historical)==262*12 for year in YEARS: period = {r['ins']:r for r in rows if r['year']==year} assert len(period)==263 assert period[MERGED]['population']==sum(period[code]['population'] for code in PRE_MERGER) fit = [r for r in historical if r['scope']=='eligible'] train = [r for r in fit if r['year'] <= 2021] holdout = [r for r in fit if r['year'] >= 2022] counts = Counter(r['ins'] for r in fit) balanced = [r for r in fit if counts[r['ins']]==10] estimates = { 'development_year_only':estimate(train,0), 'development_population_adjusted':estimate(train,1), 'development_population_and_extraordinary':estimate(train,2), 'holdout_population_and_extraordinary':estimate(holdout,2), 'pooled_population_and_extraordinary':estimate(fit,2), 'development_excluding_2020_and_2021':estimate([r for r in train if r['year'] < 2020],2), 'pooled_published_positive_only':estimate([r for r in fit if r['overnight']>0],2), 'pooled_excluding_bastogne_components':estimate([r for r in fit if r['ins'] not in PRE_MERGER],2), 'pooled_excluding_vise_boundary':estimate([r for r in fit if r['ins']!='62108'],2), 'pooled_balanced_disclosure':estimate(balanced,2), } by_year=[] for year in YEARS: subset = [r for r in historical if r['year']==year] counts = Counter(r['overnight_status'] for r in subset) by_year.append({'year':year,'historical_communes':len(subset),'overnights_published_including_zero':counts['observed']+counts['observed_zero'], 'overnights_zero':counts['observed_zero'],'withheld_not_disseminated':counts['withheld_not_disseminated'], 'withheld_too_few_establishments':counts['withheld_too_few_establishments'], 'ordinary_unavailable':sum(r['ordinary'] is None for r in subset),'eligible_model_rows':sum(r['scope']=='eligible' for r in subset)}) return historical, {'status':'Passed','source_union_rows':len(rows),'historical_rows':len(historical), 'excluded_overlapping_rows':len(rows)-len(historical), 'observed_overlap_historical':sum(all(r[name] is not None for name in SERIES) for r in historical), 'eligible_rows':len(fit),'counts_by_year':by_year, 'estimates':estimates, 'status_by_measure':{name:dict(Counter(r[name+'_status'] for r in historical)) for name in SERIES}, 'scope_counts':dict(Counter(r['scope'] for r in historical))} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--capture', action='store_true', help='Record this input delivery as a new source lock.') arguments = parser.parse_args() manifest_path = ROOT/'SOURCE_CAPTURE.json' if arguments.capture: assert not manifest_path.exists() save_json(manifest_path,source_manifest()) manifest = json.loads(manifest_path.read_text(encoding='utf-8')) series = {name:read_series(name,manifest['series'][name]) for name in SERIES} rows = assemble(series) historical, result = qualify(rows) joined = ROOT/'walstat-joined-2013-2024.csv' with joined.open('w',newline='',encoding='utf-8') as handle: writer = csv.DictWriter(handle, fieldnames=rows[0].keys()) writer.writeheader() writer.writerows(rows) result['joined_csv'] = {'path':joined.name,'sha256':digest(joined),'bytes':joined.stat().st_size} save_json(ROOT/'WALSTAT_STUDY_RESULTS.json',result) compact = [[r['ins'],r['commune'],r['year'],*(str(r[name]) if r[name] is not None else None for name in SERIES), r['population_band'],r['overnight_status'],r['scope']] for r in historical] study = {'rows':compact,'summary':result,'sources':manifest['series']} payload = json.dumps(study,ensure_ascii=False,separators=(',',':')) (ROOT/'study-data.js').write_text('window.WalstatStudy = '+payload+';\n',encoding='utf-8') print(json.dumps({'status':result['status'],'observed_overlap':result['observed_overlap_historical'],'eligible':result['eligible_rows'], 'sha256':result['joined_csv']['sha256']})) if __name__ == '__main__': main()