# CANT-1 · cotejo impl1 (Python puro) frente a impl2 (SQL de DuckDB), con las tolerancias del §6 del pre-registro. import pyarrow.parquet as pq, json, math M1 = json.load(open('/c/interno/motivos_impl1.json')) S1 = {r['id_contrato']: r for r in pq.read_table('/c/interno/screens_impl1.parquet').to_pylist() if r['conjunto'] == 'P'} T2 = pq.read_table('/c/interno/screens_impl2.parquet').to_pylist() M2 = {r['id_contrato']: r['motivo'] for r in T2} S2 = {r['id_contrato']: r for r in T2 if r['motivo'] == 'P'} J1 = json.load(open('/c/interno/impl1.json')); J2 = json.load(open('/c/interno/impl2.json')) L = ["# 22 · Cotejo de las dos implementaciones (impl1 Python puro · impl2 SQL de DuckDB)", ""] dm = [k for k in M1 if M1[k] != M2.get(k)] L.append(f"- Motivo de exclusión por contrato: {len(M1):,} contratos, **{len(dm)} diferencias**; P: {len(S1)} frente a {len(S2)} " f"(mismos ids: {set(S1) == set(S2)}).") def rel(a, b): if a is None and b is None: return 0.0 if a is None or b is None: return float('inf') if math.isinf(a) or math.isinf(b): return 0.0 if a == b else float('inf') return abs(a - b) / max(abs(a), abs(b), 1e-300) if (a or b) else 0.0 peor = {} for k in ('CV', 'DIFFP', 'RD', 'SKEW', 'KURTO', 'SPD', 'RDALT', 'RDNOR', 'DIFFP_ADJ'): peor[k] = max(rel(S1[i][k], S2[i][k]) for i in S1 if i in S2) peor_pct = {} for k in ('pct_CV', 'pct_DIFFP', 'pct_RD', 'pct_SKEW', 'pct_KURTO', 'pct_SPD', 'S'): peor_pct[k] = max(abs((S1[i][k] or 0) - (S2[i][k] or 0)) + (0 if (S1[i][k] is None) == (S2[i][k] is None) else 1) for i in S1 if i in S2) bin_dif = {k: sum(1 for i in S1 if i in S2 and S1[i][k] != S2[i][k]) for k in ('ADJ_NO_MIN', 'HUECO')} L.append("- Screens por contrato, |Δ relativo| máximo (tolerancia 1e−9): " + ', '.join(f"{k} {v:.1e}" for k, v in peor.items())) L.append("- Percentiles y S, |Δ| máximo (tolerancia 1e−9): " + ', '.join(f"{k} {v:.1e}" for k, v in peor_pct.items())) L.append(f"- Binarios por contrato distintos: {bin_dif}") # agregados def plano1(d): out = dict(n=d['n'], organos=d['organos'], ofertas_media=d['ofertas_media'], RD_med=d['RD']['med'], ADJ_NO_MIN=d['ADJ_NO_MIN'], HUECO=d['HUECO'], DIFFP_ADJ_med=d['DIFFP_ADJ_med'], CV_lt_0325=d['CV_lt_0325'], CV_lt_0951=d['CV_lt_0951']) for s in ('CV', 'DIFFP', 'SKEW', 'KURTO', 'SPD'): out[f'{s}_p25'] = d[s]['p25']; out[f'{s}_med'] = d[s]['med']; out[f'{s}_p75'] = d[s]['p75'] return out peor_ag, n_ag, malos = 0.0, 0, [] for bloque in ('por_mercado', 'ambito', 'resto_por_mercado', 'por_tramo', 'por_consejeria'): for g, d1 in J1[bloque].items(): if not d1.get('n'): continue a, b = plano1(d1), J2[bloque].get(g) if b is None: malos.append(f'{bloque}/{g} falta en impl2'); continue for k, v in a.items(): n_ag += 1; e = rel(v, b.get(k)) if e > 1e-9: malos.append(f'{bloque}/{g}/{k}: {v} vs {b.get(k)}') peor_ag = max(peor_ag, e if e != float('inf') else 1) a, b = plano1(J1['P_todo']), J2['P_todo'] for k, v in a.items(): n_ag += 1; e = rel(v, b.get(k)) if e > 1e-9: malos.append(f'P_todo/{k}: {v} vs {b.get(k)}') L.append(f"- Descriptivos del §4 (medianas, cuartiles, %): {n_ag} cifras, |Δ relativo| máximo {peor_ag:.1e}; fuera de tolerancia: {len(malos)}") L.extend(f" - {m}" for m in malos[:30]) pm = 0 for bloque in ('presencia_mercado', 'presencia_consejeria'): for g, d1 in J1[bloque].items(): d2 = J2[bloque].get(g, {}) for k, v in d1.items(): pm += 1; e = rel(v, d2.get(k)) if e > 1e-9: malos.append(f'{bloque}/{g}/{k}: {v} vs {d2.get(k)}') for k, v in J1['presencia_todo'].items(): pm += 1; e = rel(v, J2['presencia_todo'].get(k)) if e > 1e-9: malos.append(f'presencia_todo/{k}: {v} vs {J2["presencia_todo"].get(k)}') L.append(f"- Descriptores de presencia: {pm} cifras; fuera de tolerancia (acumulado con lo anterior): {len(malos)}") L.extend(f" - {m}" for m in malos[30:60]) L.append(f"- Tercera comprobación (asimetría y curtosis nativas de DuckDB frente a la fórmula explícita): |Δ| máx {J2['nativas']['max_dif_skew']:.1e} y " f"{J2['nativas']['max_dif_kurt']:.1e} (las nativas son de un paso: error numérico con importes grandes; las dos explícitas coinciden).") ok = not dm and set(S1) == set(S2) and max(peor.values()) <= 1e-9 and max(peor_pct.values()) <= 1e-9 and not malos and not any(bin_dif.values()) L += ["", f"**Veredicto del cotejo: {'COINCIDEN dentro de tolerancia' if ok else 'DISCREPAN (ver arriba; manda la lectura conservadora)'}.** " "Los IC del bootstrap solo existen en impl1 (§6 del pre-registro)."] open('/c/salidas/22_cotejo.md', 'w').write('\n'.join(L) + '\n'); print('\n'.join(L))