"""Offline original aggregate analysis; no network, IDs or municipalities in outputs. Usage: python reproduce.py --input authorized-local-source.csv --output output The exact public source edition must be obtained separately. Not a clinical model. Own code: MIT. Original Anvisa material is excluded from this code licence. """ import argparse import csv from collections import Counter, defaultdict from decimal import Decimal, ROUND_HALF_UP from datetime import datetime import hashlib import json from pathlib import Path import unicodedata SOURCE_SHA = 'ef78a978a15275aa92632867ca3f4f7a9cea33f1b2cafc6e034870cfbb4f4946' SOURCE_URL = 'https://dados.anvisa.gov.br/dados/DADOS_ABERTOS_TECNOVIGILANCIA.csv' PRODUCTS = {'IMPLANTES MAMARIOS', 'PROTESES MAMARIAS'} REGIONS = { 'Norte': 'AC AP AM PA RO RR TO', 'Nordeste': 'AL BA CE MA PB PE PI RN SE', 'Centro-Oeste': 'DF GO MT MS', 'Sudeste': 'ES MG RJ SP', 'Sul': 'PR RS SC', } UF_REGION = {uf: region for region, tokens in REGIONS.items() for uf in tokens.split()} PUBLIC_GROUPS = ['Norte, Nordeste e Centro-Oeste', 'Sudeste', 'Sul', 'UF não informada'] PERIODS = [('2007–2025', 2007, 2025), ('2007–2023', 2007, 2023), ('2024–2025', 2024, 2025)] STATES = [ ('mesma_uf', 'Duas UFs informadas e iguais'), ('uf_diferente', 'Duas UFs informadas e diferentes'), ('somente_notificante', 'Somente UF do notificante informada'), ('somente_ocorrencia', 'Somente UF de ocorrência informada'), ('nenhuma_uf', 'Nenhuma das duas UFs informada'), ] SCHEMA = [ 'ANO_NOTIFICACAO', 'DATA_NOTIFICACAO', 'NU_NOTIFICACAO', 'TIPO_NOTIFICACAO', 'SUBTIPO_QUEIXA', 'CATEGORIA_DISPOSITIVO', 'CODIFICACAO_EVENTO_ADVERSO', 'UF_EMPRESA_NOTIFICANTE', 'MUNICIPIO_EMP_NOTIFICANTE', 'TIPO_NOTIFICANTE', 'UF_OCORRENCIA', 'MUNICIPIO_OCORRENCIA', 'CLASSE_RISCO', 'NOME_TECNICO_PRODUTO', 'OCORRENCIA_NIVEL_1', 'OCORRENCIA_NIVEL_2', 'UF_EMPRESA_REGISTRO', 'MUNICIPIO_EMPRESA_REGISTRO', ] def require(condition, message): if not condition: raise ValueError(message) def norm(value): return ''.join(c for c in unicodedata.normalize('NFD', value.strip().upper()) if unicodedata.category(c) != 'Mn') def ratio(n, d): return None if not d else str((Decimal(n) * 100 / Decimal(d)).quantize( Decimal('0.01'), rounding=ROUND_HALF_UP)) def geo(value): value = value.strip().upper() if value == '--': return None require(value in UF_REGION, 'Unexpected location token; stop for source review') return value def state(a, b): if a and b: return 'mesma_uf' if a == b else 'uf_diferente' if a: return 'somente_notificante' if b: return 'somente_ocorrencia' return 'nenhuma_uf' def write_csv(path, fields, rows): with path.open('w', encoding='utf-8-sig', newline='') as f: writer = csv.DictWriter(f, fieldnames=fields, lineterminator='\n') writer.writeheader() writer.writerows(rows) def analyze(source, output): require(hashlib.sha256(source.read_bytes()).hexdigest() == SOURCE_SHA, 'Source edition differs; no silent update or relaxed checksum') selected, seen, all_selected_name_rows, excluded_years = [], set(), 0, Counter() raw_rows = 0 with source.open(encoding='cp1252', newline='') as f: reader = csv.DictReader(f, delimiter=';') require(reader.fieldnames == SCHEMA, 'Exact source schema mismatch') for row in reader: raw_rows += 1 if norm(row['NOME_TECNICO_PRODUTO']) not in PRODUCTS: continue all_selected_name_rows += 1 year = int(row['ANO_NOTIFICACAO']) if not 2007 <= year <= 2025: excluded_years[year] += 1 continue ident = row['NU_NOTIFICACAO'].strip() require(ident and ident not in seen, 'Empty/duplicate ID; stop, never first-row dedup') seen.add(ident) require(row['TIPO_NOTIFICACAO'] in {'Evento Adverso', 'Queixa Técnica'}, 'Unexpected notification type') # Date is for schema validation only; never copied into public output. date = row['DATA_NOTIFICACAO'].strip() require(datetime.strptime(date, '%d/%m/%Y %H:%M:%S.%f').year == year, 'Year/date consistency requires review') selected.append((year, row['TIPO_NOTIFICACAO'], geo(row['UF_EMPRESA_NOTIFICANTE']), geo(row['UF_OCORRENCIA']))) require(len(selected) == 2485 and raw_rows == 289000, 'Unexpected pinned edition population') require(set(excluded_years) == {2026} and excluded_years[2026] == 778, 'Excluded selected-name records are not exactly the expected partial2026') joint, period_summaries, types = [], [], [] for label, first, last in PERIODS: rows = [r for r in selected if first <= r[0] <= last] n = len(rows) counts = Counter(state(r[2], r[3]) for r in rows) for code, description in STATES: joint.append({'periodo_notificacao': label, 'situacao': code, 'descricao': description, 'notificacoes': counts[code], 'denominador_periodo': n, 'percentual_do_periodo': ratio(counts[code], n)}) both = counts['mesma_uf'] + counts['uf_diferente'] reporter = both + counts['somente_notificante'] occurrence = both + counts['somente_ocorrencia'] require(sum(counts.values()) == n, 'Partition does not reconcile') period_summaries.append({ 'periodo_notificacao': label, 'notificacoes': n, 'uf_notificante_informada': reporter, 'uf_ocorrencia_informada': occurrence, 'ambas_ufs_informadas': both, 'ambas_ufs_diferentes': counts['uf_diferente'], 'percentual_diferente_entre_ambas_informadas': ratio(counts['uf_diferente'], both), 'percentual_com_uf_ocorrencia': ratio(occurrence, n), 'percentual_com_uf_notificante': ratio(reporter, n), }) tc = Counter(r[1] for r in rows) for type_label in ['Evento Adverso', 'Queixa Técnica']: types.append({'periodo_notificacao': label, 'tipo': type_label, 'notificacoes': tc[type_label], 'denominador_periodo': n, 'percentual_do_periodo': ratio(tc[type_label], n)}) def public_group(uf): region = UF_REGION.get(uf, 'UF não informada') return ('Norte, Nordeste e Centro-Oeste' if region in {'Norte', 'Nordeste', 'Centro-Oeste'} else region) region_rows = [] for region in PUBLIC_GROUPS: reporter = sum(public_group(r[2]) == region for r in selected) occurrence = sum(public_group(r[3]) == region for r in selected) region_rows.append({'grupo_geografico': region, 'pela_uf_notificante': reporter, 'pela_uf_ocorrencia': occurrence, 'ocorrencia_menos_notificante': occurrence - reporter, 'denominador_comum': len(selected)}) require(sum(r['pela_uf_notificante'] for r in region_rows) == len(selected), 'Reporter marginal does not reconcile') require(sum(r['pela_uf_ocorrencia'] for r in region_rows) == len(selected), 'Occurrence marginal does not reconcile') require(sum(r['ocorrencia_menos_notificante'] for r in region_rows) == 0, 'Marginal differences do not reconcile') # Project-specific disclosure guard. A failed guard does not silently suppress # or regroup outcome-dependent cells. Root must review a new public frame. small_joint = [(r['periodo_notificacao'], r['situacao']) for r in joint if 0 < r['notificacoes'] < 5] small_types = [(r['periodo_notificacao'], r['tipo']) for r in types if 0 < r['notificacoes'] < 5] small_regions = [(r['grupo_geografico'], key) for r in region_rows for key in ['pela_uf_notificante', 'pela_uf_ocorrencia'] if 0 < r[key] < 5] result = { 'study_id': 'DF-STUDY-IMPLANT-NOTIFICATION-GEOGRAPHY-2007-2025', 'source_url': SOURCE_URL, 'source_sha256': SOURCE_SHA, 'source_last_modified': '2026-10-13T19:09:51Z', 'notification_temporalCoverage': '2007/2025', 'selection': 'Exact technical names IMPLANTES MAMARIOS and PROTESES MAMARIAS; notification years2007–2025', 'unit': 'Distinct source notification ID, not patients, implants, operations or causal clinical events', 'selected_notifications': len(selected), 'partial_2026_excluded': excluded_years[2026], 'period_summaries': period_summaries, 'joint_geography': joint, 'region_marginals': region_rows, 'notification_types': types, 'disclosure_guard': {'threshold_choice_not_regulatory_rule': 5, 'coarsening_note': 'Three named regions combined after initial private disclosure review; no fine geographic cells distributed', 'small_joint_cells': small_joint, 'small_type_cells': small_types, 'small_region_cells': small_regions, 'automatic_public_clearance': not (small_joint or small_types or small_regions)}, 'analysis_limits': ['No risk, incidence, causality, patient residence, travel or individual clinical advice', 'Unknown occurrence UF is never imputed from reporter UF', 'Current frozen edition may revise historical notification years', 'No original source raw rows, IDs, municipality, narratives or sparse UF pairs redistributed'], } output.mkdir(parents=True, exist_ok=True) (output / 'summary.json').write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n', encoding='utf-8') for name, rows in [('localizacao-conjunta.csv', joint), ('grupos-geograficos.csv', region_rows), ('tipos-notificacao.csv', types), ('resumo-periodos.csv', period_summaries)]: write_csv(output / name, list(rows[0]), rows) return result if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--input', type=Path, required=True) parser.add_argument('--output', type=Path, required=True) args = parser.parse_args() result = analyze(args.input, args.output) print(json.dumps({'notifications': result['selected_notifications'], 'period_summaries': result['period_summaries'], 'joint_geography': result['joint_geography'], 'region_marginals': result['region_marginals'], 'disclosure_guard': result['disclosure_guard']}, ensure_ascii=False, indent=2))