"""FUENTES-A-LA-CADENA · comprobación mecánica del paquete UE (no es la lectura): con las reglas del PROMPT sobre los originales ya enmascarados de para_lector, ¿la tabla de cada caso cuadra? Esperado: cabeza y positivos sí; negativos no. Solo recuentos. Host, biblioteca estándar.""" import csv, json, re from collections import Counter, defaultdict from pathlib import Path X = Path(__file__).resolve().parent; PL = X / "lotes/ue/para_lector" SR = ("100 % of the amount is displayed with the coordinator", "attributed to a single beneficiary", "divided by the number of beneficiaries") PM = {"H2020": "Horizonte 2020", "HORIZON": "Horizonte Europa"} def num(s, coma=False): s = (s or "").strip() if not s: return None s = s.replace(",", ".") if coma and "," in s and "." not in s else s.replace(",", "") try: return float(s) except ValueError: # «*****»: la Comisión no publica ese importe return None def suma(xs): xs = [x for x in xs if x is not None] return round(sum(xs), 2) if xs else None mapa = {int(r["ref"]): r for r in csv.DictReader(open(X / "lotes/ue/mapa/grupos.tsv", encoding="utf-8"), delimiter="\t")} sel = json.load(open(X / "priv/sel_ue.json"))["casos"] res = {"cabeza": [0, 0], "positivo": [0, 0], "negativo": [0, 0]} for ref, m in mapa.items(): cel = {} d1 = PL / "originales" / f"{ref}_1" if d1.exists(): lin = defaultdict(list) for f in sorted(d1.glob("fts_*.csv")): for r in csv.DictReader(open(f, encoding="utf-8")): lin[int(r["Year"])].append(r) for a, rs in lin.items(): ia = next(k for k in rs[0] if k.startswith("Beneficiary") and k.endswith("s contracted amount (EUR)")) srs = [r for r in rs if any(s.lower() in (r["Source of (estimated) detailed amount"] or "").lower() for s in SR)] crs = [r for r in rs if r not in srs] pr = Counter((r["Programme name"] or "").strip() or "sin programa" for r in rs) cel[("fts", a)] = (len(rs), suma(num(r[ia]) for r in crs), len(srs), suma(num(r[ia]) for r in srs), "|".join(f"{p}:{k}" for p, k in sorted(pr.items(), key=lambda x: (-x[1], x[0]))), None) d2 = PL / "originales" / f"{ref}_2" if d2.exists(): por = defaultdict(lambda: {"p": set(), "c": set(), "imp": [], "pm": defaultdict(set)}) for et in ("H2020", "HORIZON"): po, pp = d2 / f"cordis_{et}_organization.csv", d2 / f"cordis_{et}_project.csv" if not po.exists(): continue firma = {r["id"]: int(r["ecSignatureDate"][:4]) for r in csv.DictReader(open(pp, encoding="utf-8")) if re.match(r"\d{4}", r["ecSignatureDate"] or "")} for r in csv.DictReader(open(po, encoding="utf-8")): if r["projectID"] not in firma: continue x = por[firma[r["projectID"]]] x["p"].add(r["projectID"]); x["imp"].append(num(r["ecContribution"], True)); x["pm"][et].add(r["projectID"]) if r["role"] == "coordinator": x["c"].add(r["projectID"]) for a, x in por.items(): cel[("cordis", a)] = (len(x["p"]), suma(x["imp"]), None, None, "|".join(f"{p}:{len(s)}" for p, s in sorted(x["pm"].items(), key=lambda z: (-len(z[1]), z[0]))), len(x["c"])) caso = next(c for c in sel if c["nif"] == m["clave"] and (c["grupo"], c["subgrupo"]) == (m["grupo"], m["subgrupo"])) afi = {} for x in caso["celdas"]: afi[(x["fuente"], x["anio"])] = (x["n"], round(x["importe"], 2) if x["importe"] is not None else None, x["sin_reparto"], round(x["importe_sin_reparto"], 2) if x["importe_sin_reparto"] is not None else None, x["programas"], x["coord"] if x["fuente"] == "cordis" else None) ig = lambda a, b: all((p is None and q is None) or (isinstance(p, float) and q is not None and abs(p - q) <= 0.01) or p == q for p, q in zip(a, b)) ok = set(afi) == set(cel) and all(ig(afi[k], cel[k]) for k in afi) g = "cabeza" if m["grupo"] == "cabeza" else m["subgrupo"] res[g][0] += ok; res[g][1] += 1 print(res)