"""E7 · medidas del pre-registro, paso 2: la SEGUNDA implementación, en Python sin DuckDB (solo la biblioteca estándar), desde lotes.csv y pe.csv (el universo que escribe m1_base.py), y la comparación con lo que calcula el módulo (modulo.json): E7-1 (b) embudo de OU1 por órgano × división, 2022-2025: n, k, tasa esperada, z_D y posición de cada órgano × división E7-1 (a) la estabilidad 2018-2021 → 2022-2025 (OR con IC de Woolf), con los embudos del módulo E7-2 (a) rotación en 30 celdas sorteadas (división × comunidad × año 2019-2025 con 10 proveedores o más) E7-3 (a) cuota del primero, cuatro primeros y HHI en 30 celdas sorteadas (división × comunidad y división × España) E7-4 (b) histograma, mediana de la baja y mediana de la dispersión en 20 celdas sorteadas (división × territorio) Semilla de las muestras: 20261027 (pre-registro). Escribe resultados/segunda.json (agregado: sin claves) y /med/muestras.json (las celdas y proveedores sorteados, para el cotejo con unified de m3_cotejo.py). Uso: python3 -I medidas/m2_segunda.py""" import csv import json import math import random import statistics from pathlib import Path E7 = Path(__file__).resolve().parents[1] MED = E7 / "tmp" / "med" RES = E7 / "resultados" SEMILLA = 20261027 A, NMIN, Z95, Z998 = 50.0, 30, 1.959964, 3.090232 def percentil(v, q): s = sorted(v) if not s: return float("nan") x = (len(s) - 1) * q i = int(math.floor(x)) return s[i] if i + 1 >= len(s) else s[i] + (x - i) * (s[i + 1] - s[i]) def embudo(lotes): """lotes: (org, cpv, tipo, anio, y). Devuelve {cpv: {org: (n, k, esperada, zd, pos)}}.""" nt, kt, nm, km, no, ko = {}, {}, {}, {}, {}, {} for o, d, t, a, y in lotes: for D, K, key in ((nt, kt, (t, a)), (nm, km, (d, t, a)), (no, ko, (o, d, t, a))): D[key] = D.get(key, 0) + 1 K[key] = K.get(key, 0) + y agg = {} for (o, d, t, a), n_mo in no.items(): k_mo = ko[(o, d, t, a)] p = (km[(d, t, a)] - k_mo + A * kt[(t, a)] / nt[(t, a)]) / (nm[(d, t, a)] - n_mo + A) s = agg.setdefault((o, d), [0, 0, 0.0, 0.0]) s[0] += n_mo s[1] += k_mo s[2] += n_mo * p s[3] += n_mo * p * (1 - p) por = {} for (o, d), v in agg.items(): por.setdefault(d, {})[o] = v out = {} for d, orgs in por.items(): filas = [(k / n, E / n, math.sqrt(V) / n) for n, k, E, V in orgs.values() if n >= NMIN] zs = [(r - e) / s for r, e, s in filas if s > 0] t2 = 0.0 if len(zs) >= 2: lo, hi = percentil(zs, 0.10), percentil(zs, 0.90) phi = sum(min(max(z, lo), hi) ** 2 for z in zs) / len(zs) w = [1 / (s * s) for r, e, s in filas if s > 0] sw, sw2 = sum(w), sum(x * x for x in w) n = len(zs) t2 = max((n * phi - (n - 1)) / (sw - sw2 / sw), 0.0) if n * phi > n - 1 else 0.0 res = {} for o, (n, k, E, V) in orgs.items(): if n < NMIN: continue r, e, sd = k / n, E / n, math.sqrt(V) / n zd = (r - e) / math.sqrt(sd * sd + t2) if (sd > 0 or t2 > 0) else 0.0 pos = 0 if zd > Z998 else 1 if zd > Z95 else 2 if zd >= -Z95 else 3 if zd >= -Z998 else 4 res[o] = (n, k, e, zd, pos) out[d] = res return out def leer_lotes(): with (MED / "lotes.csv").open() as f: return list(csv.DictReader(f)) def main(): mod = json.loads((MED / "modulo.json").read_text()) L = leer_lotes() rng = random.Random(SEMILLA) R = {"semilla": SEMILLA} # ── E7-1 (b): embudo 2022-2025 ─────────────────────────────────────────────────────────────────────────────── lw = [(r["org"], r["cpv"], r["tipo"], int(r["anio"]), 1 if r["nof"] == "1" else 0) for r in L if 2022 <= int(r["anio"]) <= 2025 and r["cpv"] != "??"] seg = embudo(lw) tot = dif = 0 ejemplos = [] for d, e in mod["embudo_2022_2025"].items(): for o, n, k, esp, zd, pos in e["puntos"]: tot += 1 s = seg.get(d, {}).get(o) ok = s is not None and s[0] == n and s[1] == k and abs(s[2] - esp) <= 1e-9 and abs(s[3] - zd) <= 1e-6 and s[4] == pos if not ok: dif += 1 if len(ejemplos) < 5: ejemplos.append({"div": d, "modulo": [n, k, esp, zd, pos], "segunda": list(s) if s else None}) extra = sum(len(v) for v in seg.values()) - tot R["e7_1_b"] = {"organo_division": tot, "diferencias": dif, "pct": round(100 * dif / tot, 4) if tot else None, "solo_en_segunda": extra, "ejemplos": ejemplos} # ── E7-1 (a): estabilidad con los embudos del módulo ───────────────────────────────────────────────────────── e1 = {(d, p[0]): p[5] == 0 for d, e in mod["embudo_2018_2021"].items() for p in e["puntos"]} e2 = {(d, p[0]): p[5] == 0 for d, e in mod["embudo_2022_2025"].items() for p in e["puntos"]} comunes = sorted(set(e1) & set(e2)) a = sum(1 for x in comunes if e1[x] and e2[x]) b = sum(1 for x in comunes if e1[x] and not e2[x]) c = sum(1 for x in comunes if not e1[x] and e2[x]) dd = sum(1 for x in comunes if not e1[x] and not e2[x]) aa, bb, cc, ddd = (v + 0.5 for v in (a, b, c, dd)) if 0 in (a, b, c, dd) else (a, b, c, dd) OR = (aa * ddd) / (bb * cc) se = math.sqrt(1 / aa + 1 / bb + 1 / cc + 1 / ddd) R["e7_1_a"] = {"organo_division_en_las_dos": len(comunes), "fuera_1_y_2": a, "fuera_1_no_2": b, "no_1_fuera_2": c, "no_1_no_2": dd, "fuera_2018_2021": a + b, "OR": round(OR, 3), "ic95": [round(math.exp(math.log(OR) - 1.959964 * se), 3), round(math.exp(math.log(OR) + 1.959964 * se), 3)], "medio_anadido": 0 in (a, b, c, dd), "dentro": "dentro = no está por encima del 99,8 % (el hecho, binario)"} # ── E7-2 (a) y E7-3 (a): desde pe.csv ──────────────────────────────────────────────────────────────────────── pe: dict = {} with (MED / "pe.csv").open() as f: for r in csv.DictReader(f): for t in (r["ccaa"], "ES"): k = (r["cpv"], t, int(r["anio"]), r["emp"]) pe[k] = pe.get(k, 0.0) + float(r["imp"]) por_celda_anio: dict = {} for (d, t, an, e), imp in pe.items(): por_celda_anio.setdefault((d, t, an), {})[e] = por_celda_anio.setdefault((d, t, an), {}).get(e, 0.0) + imp # celdas de comunidad (no España ni «sin comunidad»), 2019-2025, con 10 proveedores o más (las que da el módulo) cand = sorted({(k, int(an)) for k, v in mod["rot"].items() if not k.endswith(("|ES", "|SIN")) for an in v if 2019 <= int(an) <= 2025}) muestra_rot = rng.sample(cand, 30) ok_rot, filas_rot, nuevos = 0, [], [] for k, an in muestra_rot: d, t = k.split("|") act, ant = por_celda_anio.get((d, t, an), {}), por_celda_anio.get((d, t, an - 1), {}) imp = sum(act.values()) nuevo = [e for e in act if e not in ant] v2 = round(sum(act[e] for e in nuevo) / imp, 4) if imp else None v1 = mod["rot"][k][str(an)][2] bien = v1 is not None and v2 is not None and abs(v1 - v2) <= 0.0001 + 1e-12 ok_rot += bien filas_rot.append({"celda": f"{d}|{t}|{an}", "modulo": v1, "segunda": v2, "proveedores": len(act), "nuevos": len(nuevo), "igual": bien}) nuevos += [(d, t, an, e) for e in nuevo] R["e7_2_a"] = {"celdas": 30, "iguales": ok_rot, "filas": filas_rot} muestra_nuevos = rng.sample(sorted(nuevos), 20) # E7-3 (a) cand3 = sorted(k for k, v in mod["conc"].items() if not v.get("suprimido") and not k.endswith("|SIN")) muestra_conc = rng.sample(cand3, 30) ok3, filas3 = 0, [] for k in muestra_conc: d, t = k.split("|") imp: dict = {} for an in range(2022, 2026): for e, v in por_celda_anio.get((d, t, an), {}).items(): imp[e] = imp.get(e, 0.0) + v vals = sorted(imp.values(), reverse=True) tt = sum(vals) s = {"top1": round(vals[0] / tt, 4), "cr4": round(sum(vals[:4]) / tt, 4), "hhi": round(sum((x / tt) ** 2 for x in vals), 4)} m = mod["conc"][k] bien = all(abs(m[c] - s[c]) <= 0.0001 + 1e-12 for c in s) and m["proveedores"] == len(vals) ok3 += bien filas3.append({"celda": k, "modulo": {c: m[c] for c in s}, "segunda": s, "igual": bien}) R["e7_3_a"] = {"celdas": 30, "iguales": ok3, "filas": filas3} muestra_conc_b = rng.sample(muestra_conc, 20) # ── E7-4 (b): histograma y medianas ────────────────────────────────────────────────────────────────────────── mmx: dict = {} for r in L: if not (2022 <= int(r["anio"]) <= 2025) or r["cpv"] == "??" or not r["lic"] or not r["omin"] or not r["omax"]: continue nof, lic, omin, omax = int(r["nof"]), float(r["lic"]), float(r["omin"]), float(r["omax"]) if nof < 2 or lic <= 0 or omin <= 0 or omax < omin or not (0.1 <= omin / lic <= 1.2) or r["en_sobre"] == "True": continue baja, disp = 100 * (1 - omin / lic), 100 * (omax - omin) / lic for t in (r["ccaa"], "ES"): mmx.setdefault((r["cpv"], t), []).append((baja, disp)) cand4 = sorted(k for k, v in mod["minmax"].items() if v["lotes"] > 0 and not k.endswith("|SIN")) muestra4 = rng.sample(cand4, 20) ok4, filas4 = 0, [] for k in muestra4: d, t = k.split("|") v = mmx.get((d, t), []) hist = [0] * 15 for baja, _ in v: hist[min(max(math.floor(baja / 5) + 1, 0), 14)] += 1 s = {"lotes": len(v), "hist": hist, "baja_mediana": round(statistics.median(b for b, _ in v), 2), "dispersion_mediana": round(statistics.median(x for _, x in v), 2)} m = mod["minmax"][k] bien = (m["lotes"] == s["lotes"] and m["hist"] == s["hist"] and abs(m["baja_mediana"] - s["baja_mediana"]) <= 0.0051 and abs(m["dispersion_mediana"] - s["dispersion_mediana"]) <= 0.0051) ok4 += bien filas4.append({"celda": k, "modulo": {c: m[c] for c in s}, "segunda": s, "igual": bien}) R["e7_4_b"] = {"celdas": 20, "iguales": ok4, "filas": filas4} cand_lotes = sorted({(r["licitacion_id"], r["lote_u"]) for r in L if 2022 <= int(r["anio"]) <= 2025 and r["cpv"] != "??" and r["en_sobre"] == "False" and r["lic"] and r["omin"] and r["omax"] and int(r["nof"]) >= 2 and float(r["lic"]) > 0 and float(r["omin"]) > 0 and float(r["omax"]) >= float(r["omin"]) and 0.1 <= float(r["omin"]) / float(r["lic"]) <= 1.2}) muestra_lotes = rng.sample(cand_lotes, 20) RES.mkdir(exist_ok=True) (RES / "segunda.json").write_text(json.dumps(R, ensure_ascii=False, indent=1), encoding="utf-8") (MED / "muestras.json").write_text(json.dumps({"nuevos": muestra_nuevos, "conc": muestra_conc_b, "lotes": muestra_lotes, "lotes_valores": {f"{a}|{b}": next([r["lic"], r["omin"], r["omax"]] for r in L if (r["licitacion_id"], r["lote_u"]) == (a, b)) for a, b in muestra_lotes}}, ensure_ascii=False), encoding="utf-8") print(json.dumps({k: (v if not isinstance(v, dict) else {kk: vv for kk, vv in v.items() if kk not in ("filas", "ejemplos")}) for k, v in R.items()}, ensure_ascii=False, indent=1)) if __name__ == "__main__": main()