"""Reproduce aggregate registered burn-ICU stocks; source bytes stay private/local. This public replay accepts only the reviewed source SHA; there are no network requests. Download the exact original linked archive manually, then supply --source and --out. No patient records, institution names, addresses, phone/email or hospital rankings are written. Counts describe one administrative edition, never actual vacancies. """ from pathlib import Path from collections import Counter, defaultdict import csv, hashlib, io, json, zipfile import argparse parser = argparse.ArgumentParser(description="Reproduz a edição congelada de 2025 do CNES, sem rede e sem exportar identificadores ou contatos.") parser.add_argument("--source", type=Path, default=Path("Leitos_csv_2025.zip")) parser.add_argument("--out", type=Path, default=Path("reproduced")) args = parser.parse_args() SOURCE_PATH = args.source HERE = args.out.resolve() HERE.mkdir(parents=True, exist_ok=True) SOURCE_SHA = "88d64426b9363862d30579966e66604be37e98d645e5ea85c4740c25c3999468" MONTHS = [f"2025{m:02}" for m in range(1, 13)] MEASURES = {"EXIST": "UTI_QUEIMADO_EXIST", "SUS": "UTI_QUEIMADO_SUS"} def write_csv(name, rows, fields): with (HERE / "data" / name).open("w", newline="", encoding="utf-8") as f: w = csv.DictWriter(f, fieldnames=fields); w.writeheader(); w.writerows(rows) def main(): audit = {} raw = SOURCE_PATH.read_bytes() if hashlib.sha256(raw).hexdigest() != SOURCE_SHA: raise SystemExit("HOLD: source differs from frozen edition") z = zipfile.ZipFile(io.BytesIO(raw)) rd = csv.DictReader(io.StringIO(z.read("Leitos_2025.csv").decode("cp1252")), delimiter=";") panel = defaultdict(dict) month_rows = Counter() # Retain only source key, regional labels and two registered bed quantities. for r in rd: month, code = r["COMP"].strip(), r["CNES"].strip() v = {"UF": r["UF"].strip(), "REGIAO": r["REGIAO"].strip(), **{m: int(r[f].strip()) for m, f in MEASURES.items()}} if month in panel[code]: raise ValueError("Unexpected duplicate source key") panel[code][month] = v month_rows[month] += 1 data_dir = HERE / "data"; data_dir.mkdir(exist_ok=True) monthly, uf_monthly = [], [] for month in MONTHS: rows = [v[month] for v in panel.values() if month in v] out = {"competence": month, "source_establishments_observed": len(rows)} for m in MEASURES: out[m + "_registered_beds"] = sum(r[m] for r in rows) out[m + "_establishments_positive"] = sum(r[m] > 0 for r in rows) monthly.append(out) ufs = sorted({r["UF"] for r in rows}) for uf in ufs: group = [r for r in rows if r["UF"] == uf] d = {"competence": month, "UF": uf, "region": group[0]["REGIAO"], "source_establishments_observed": len(group)} for m in MEASURES: d[m + "_registered_beds"] = sum(r[m] for r in group) d[m + "_establishments_positive"] = sum(r[m] > 0 for r in group) uf_monthly.append(d) persistence, transitions, coverages, summary = [], [], [], {} for measure in MEASURES: universe = {c: ms for c, ms in panel.items() if any(v[measure] > 0 for v in ms.values())} dist = Counter() states = Counter() pairs = Counter() complete_pairs = Counter() complete = 0 for code, months in universe.items(): positive = sum(v[measure] > 0 for v in months.values()) zero = sum(v[measure] == 0 for v in months.values()) missing = len(MONTHS) - len(months) dist[(positive, zero, missing)] += 1 if missing == 0: complete += 1 for a, b in zip(MONTHS, MONTHS[1:]): if a not in months or b not in months: label = "missing_row_pair" else: label = ("positive" if months[a][measure] > 0 else "zero") + "_to_" + ("positive" if months[b][measure] > 0 else "zero") pairs[label] += 1 if missing == 0: complete_pairs[label] += 1 for month in MONTHS: if month not in months: states[(month, "missing_row")] += 1 elif months[month][measure] > 0: states[(month, "positive")] += 1 else: states[(month, "observed_zero")] += 1 for (p, zero, missing), n in sorted(dist.items()): persistence.append({"measure": measure, "positive_months": p, "observed_zero_months": zero, "missing_row_months": missing, "establishments": n}) for label, n in sorted(pairs.items()): transitions.append({"measure": measure, "panel": "ever_positive_union", "transition": label, "adjacent_pairs": n}) for label, n in sorted(complete_pairs.items()): transitions.append({"measure": measure, "panel": "complete_twelve_month_subset", "transition": label, "adjacent_pairs": n}) for (month, state), n in sorted(states.items()): coverages.append({"measure": measure, "competence": month, "state": state, "establishments": n}) totals = [r[measure + "_registered_beds"] for r in monthly] summary[measure] = { "ever_positive_establishments": len(universe), "complete_twelve_month_establishments": complete, "positive_all_twelve_months": sum(n for (p, z, m), n in dist.items() if p == 12), "at_least_one_observed_zero_month": sum(n for (p, z, m), n in dist.items() if z > 0), "at_least_one_missing_record_month": sum(n for (p, z, m), n in dist.items() if m > 0), "min_monthly_registered_beds": min(totals), "max_monthly_registered_beds": max(totals), "january_registered_beds": totals[0], "december_registered_beds": totals[-1], "december_minus_january_registered_beds": totals[-1] - totals[0], "observed_adjacent_transitions": dict(pairs), "complete_case_secondary_transitions": dict(complete_pairs) } write_csv("monthly-national.csv", monthly, list(monthly[0])) write_csv("monthly-uf.csv", uf_monthly, list(uf_monthly[0])) write_csv("persistence-distribution.csv", persistence, list(persistence[0])) write_csv("adjacent-transitions.csv", transitions, list(transitions[0])) write_csv("ever-positive-monthly-coverage.csv", coverages, list(coverages[0])) result = {"source_sha256": SOURCE_SHA, "period": "202501–202512", "unit": "registered burn-ICU bed stocks and distinct CNES identifiers; not patients or available beds", "source_rows": sum(len(v) for v in panel.values()), "measures": summary, "annual_monthly_sum_intentionally_not_reported": True, "institution_names_or_contacts_exported": False, "no_active_status_inference": True} (data_dir / "results.json").write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf8") print(json.dumps(result, ensure_ascii=False, indent=2)) if __name__ == "__main__": main()