"""TL-T1-154-E2 · sensibilidad declarada (no enmienda): contratos de V1 E2 con más de una fecha de formalización distinta entre TODAS las versiones guardadas de resultados. La medida (14_medida_e2) cuenta n_ff solo en la última versión; el lector ve todas. Impl. 1 (DuckDB). Uso: 15_ff_versiones.py 2024 2025""" import sys, json, time, duckdb D, Hh = int(sys.argv[1]), int(sys.argv[2]); T0 = time.time() H = '/h/nacional/salida/licitaciones_completo_2012_2026' c = duckdb.connect(); c.execute("SET memory_limit='1500MB'; SET threads=2; SET enable_progress_bar=false") c.execute(f"CREATE TEMP TABLE v AS SELECT id, tarde, anio FROM read_parquet('/o/priv/medida_e2_{D}_{Hh}.parquet') WHERE base_v1") c.execute(f"""CREATE TEMP TABLE f AS SELECT id, count(DISTINCT fecha_formalizacion::DATE) n_todas, count(DISTINCT fecha_formalizacion::DATE) FILTER (WHERE NOT coalesce(entrada_repetida, FALSE)) n_sin_rep FROM read_parquet('{H}_resultados.parquet') WHERE conjunto='licitaciones' AND fecha_formalizacion IS NOT NULL AND id IN (SELECT id FROM v) GROUP BY id""") c.execute("CREATE TEMP TABLE g AS SELECT v.*, coalesce(n_todas,0) n_todas, coalesce(n_sin_rep,0) n_sin_rep FROM v LEFT JOIN f USING(id)") def agr(w): n, k = c.execute(f"SELECT count(*), count(*) FILTER (WHERE tarde) FROM g WHERE {w}").fetchone(); return dict(n=n, k=k, pct=round(100 * k / n, 2) if n else None) tot = agr('TRUE'); out = dict(desde=D, hasta=Hh, V1=tot) for s in ('n_todas', 'n_sin_rep'): b = agr(f'{s} > 1'); sin = agr(f'{s} <= 1') out[s] = dict(bloque=b, sin=sin, pct_tardios_en_bloque=round(100 * b['k'] / tot['k'], 2), delta_puntos=round(tot['pct'] - sin['pct'], 2), por_anio={a: agr(f'{s} > 1 AND anio={a}') for a in range(D, Hh + 1)}) out['n_todas_cero'] = agr('n_todas = 0') out['testigo_caso7'] = c.execute("SELECT n_todas, n_sin_rep, tarde FROM g WHERE id LIKE '%/licitacionesPerfilContratante/17449924'").fetchall() c.execute(f"COPY (SELECT id, n_todas, n_sin_rep FROM g WHERE n_todas > 1 OR n_sin_rep > 1) TO '/o/priv/ff_versiones_impl1_{D}_{Hh}.parquet' (FORMAT PARQUET)") out['segundos'] = round(time.time() - T0) json.dump(out, open(f'/o/salidas/15_ff_versiones_{D}_{Hh}.json', 'w'), ensure_ascii=False, indent=1); print(json.dumps(out, ensure_ascii=False))