"""What this module covers: the statistics, the suppression rule and the calculations of CaMa's descriptive analysis (`webapi.cama_analysis`), as pure functions: no database, no HTTP. Fixtures: none. The cohort rows are built here with the exact counts each test needs (`fila`), invented inputs whose expected figures are written out in the tests; nothing is read from a database. """ import math from datetime import date, timedelta import pytest from webapi.cama_analysis import calculations as calc from webapi.cama_analysis.stats import chi2_homogeneidad, chi2_sf, cuantil, wilson from webapi.cama_analysis.suppression import proporcion_publicable, suprimir_categorias, suprimir_tabla from webapi.cama_follow_up.cohort import Fila CORTE = date(2025, 12, 31) MAST = date(2025, 1, 1) MALIGNOS = {"CARCINOMA_IN_SITU", "CARCINOMA_INVASOR"} CATEGORIAS_BIRADS = [("BIRADS_4A", "BI-RADS 4A"), ("BIRADS_5", "BI-RADS 5"), ("BIRADS_6", "BI-RADS 6")] CATEGORIAS_EDAD = [("40-49", "40 a 49 años"), ("50-59", "50 a 59 años")] def fila(i, birads="BIRADS_5", edad="50-59", grado=None, con_reporte=None, dias_biopsia=None, dias_maligno=None, mast=MAST): """One patient: `grado` is the shown biopsy result, `dias_*` the days from the mammogram to the earliest biopsy report and to the earliest malignant one.""" reporte = con_reporte if con_reporte is not None else grado is not None return Fila(pac_id=i, mastografia_fecha=mast, birads=birads, grupo_edad=edad, biopsia=grado, biopsia_fecha=mast + timedelta(days=dias_biopsia or 9) if reporte else None, primera_biopsia_fecha=mast + timedelta(days=dias_biopsia) if dias_biopsia is not None else None, primer_maligno_fecha=mast + timedelta(days=dias_maligno) if dias_maligno is not None else None) def cohorte(): """70 patients: 40 with a known result (30 benign, 5 in situ, 5 invasive), 10 with a report and no grade, 20 without a biopsy. Days to the first biopsy report: 20 benign at 10 days, 6 malignant at 20 days, the other 24 with a report at 100 days.""" filas, i = [], 0 for grado, n in (("BENIGNO", 30), ("CARCINOMA_IN_SITU", 5), ("CARCINOMA_INVASOR", 5)): for _ in range(n): i += 1 filas.append(fila(i, grado=grado)) for k, f in enumerate(filas): pronto = k < 20 or (grado_es(f) and k % 10 < 6) dias = 10 if k < 20 else 20 if pronto else 100 maligno = (20 if pronto else 120) if grado_es(f) else None filas[k] = fila(f.pac_id, grado=f.biopsia, dias_biopsia=dias, dias_maligno=maligno) for _ in range(10): i += 1 filas.append(fila(i, grado=None, con_reporte=True, dias_biopsia=100)) for _ in range(20): i += 1 filas.append(fila(i)) return filas def grado_es(f): return f.biopsia in MALIGNOS def test_wilson_matches_the_closed_form_and_stays_inside_zero_and_one(): """Pins down: the Wilson interval of 10 of 40 is (14.1 %, 40.3 %), the interval of 0 of n starts at 0 and of n of n ends at 1, and it is symmetric around the midpoint of k and n-k. Fails if the formula or its continuity is changed.""" bajo, alto = wilson(10, 40) assert (bajo, alto) == pytest.approx((0.1410, 0.4028), abs=0.001) assert wilson(0, 30)[0] == 0 and wilson(30, 30)[1] == 1 assert wilson(10, 40)[0] == pytest.approx(1 - wilson(30, 40)[1]) with pytest.raises(ValueError): wilson(5, 0) @pytest.mark.parametrize("gl, critico", [(1, 3.841458820694124), (2, 5.991464547107979), (3, 7.814727903251179), (4, 9.487729036781154), (9, 16.918977604620448)]) def test_chi_square_tail_at_the_five_percent_critical_values(gl, critico): """Pins down: the tail probability at the textbook 5 % critical value of each degree of freedom is 0.05, and at 0 it is 1. Fails if the incomplete gamma function is wrong in its series or its continued fraction.""" assert chi2_sf(critico, gl) == pytest.approx(0.05, abs=1e-9) assert chi2_sf(0, gl) == 1 def test_the_homogeneity_test_gives_the_statistic_and_refuses_what_the_approximation_cannot_carry(): """Pins down: groups 20 of 40 and 8 of 40 give chi-square 7.912 with 1 degree of freedom and p 0.0049; two groups with an expected count under 5, a single group, or one outcome only are not tested, with the reason. Fails if a p-value is given where the approximation isn't valid.""" prueba = chi2_homogeneidad([(20, 40), (8, 40)]) assert prueba["valida"] and prueba["gl"] == 1 and prueba["estadistico"] == pytest.approx(7.912, abs=0.001) assert prueba["p"] == pytest.approx(0.00492, abs=0.0001) assert not chi2_homogeneidad([(1, 10), (2, 10)])["valida"] assert not chi2_homogeneidad([(20, 40)])["valida"] assert not chi2_homogeneidad([(0, 40), (0, 40)])["valida"] def test_quantiles_interpolate_between_the_order_statistics(): """Pins down: the median of 1 to 4 is 2.5 and the quartiles of 1 to 5 are 2 and 4. Fails if the interpolation changes.""" assert cuantil([4, 1, 3, 2], .5) == 2.5 assert (cuantil([1, 2, 3, 4, 5], .25), cuantil([1, 2, 3, 4, 5], .75)) == (2, 4) def test_a_proportion_is_published_only_when_the_group_the_cases_and_the_rest_are_not_small(): """Pins down: 10 of 40 is published; 3 of 40 (3 cases), 38 of 40 (2 non-cases) and 4 of 4 (a group under 5) are not; 0 of 40 is published because zero describes nobody. Fails if a small cell can be read from a proportion.""" assert proporcion_publicable(10, 40, 5) and proporcion_publicable(0, 40, 5) assert not proporcion_publicable(3, 40, 5) and not proporcion_publicable(38, 40, 5) and not proporcion_publicable(4, 4, 5) def test_a_hidden_cell_takes_the_smallest_published_one_with_it_until_the_difference_hides_nothing(): """Pins down: with cells 30, 12, 8, 2 and a published total, the 2 is hidden and so is the 8 (2 + 8 >= 5), so the difference between the total and the published cells is 10 patients and says nothing of the 2; cells with no small count hide nothing; zeros are not small. Fails if one hidden cell can be recovered by subtraction.""" assert suprimir_categorias({"a": 30, "b": 12, "c": 8, "d": 2}, 5) == {"c", "d"} assert suprimir_categorias({"a": 30, "b": 12, "c": 8, "d": 7}, 5) == set() assert suprimir_categorias({"a": 30, "b": 0, "c": 8}, 5) == set() assert suprimir_categorias({"a": 3, "b": 2}, 5) == {"a", "b"} def test_a_table_hides_along_rows_and_columns_until_no_line_gives_a_small_cell_away(): """Pins down: in a 2 x 2 table with one cell of 1, the secondary suppression covers its row and its column, so the hidden cells total at least 5 in each line. Fails if a marginal total and the visible cells reveal a hidden cell.""" conteos = {("a", "x"): 20, ("a", "y"): 1, ("b", "x"): 9, ("b", "y"): 30} ocultas = suprimir_tabla(conteos, 5) assert ("a", "y") in ocultas for fila_ in ("a", "b"): ocultos = sum(conteos[k] for k in ocultas if k[0] == fila_) assert ocultos == 0 or ocultos >= 5 for columna in ("x", "y"): ocultos = sum(conteos[k] for k in ocultas if k[1] == columna) assert ocultos == 0 or ocultos >= 5 def test_the_cards_state_their_numerator_denominator_and_interval(): """Pins down, on a cohort of 70 (40 with a known result, 10 with a report without a grade, 20 without biopsy): cohort 70; with a biopsy report 50 of 70; malignant among the known 10 of 40 (25 %) with its Wilson interval; invasive 5 of 40; a biopsy within 90 days 26 of 70; a malignant result within 90 days 6 of 70; the median days to the report 20 (n 50). Fails if a numerator, a denominator or a definition changes.""" t = {x["clave"]: x for x in calc.resumen(cohorte(), CORTE, 90, MALIGNOS, 5)} assert t["cohorte"]["valor"] == 70 assert (t["con_biopsia"]["n"], t["con_biopsia"]["denominador"]) == (50, 70) assert (t["maligno_conocido"]["n"], t["maligno_conocido"]["denominador"], t["maligno_conocido"]["valor"]) == (10, 40, 25.0) assert (t["maligno_conocido"]["ic_bajo"], t["maligno_conocido"]["ic_alto"]) == pytest.approx((14.1, 40.3), abs=0.2) assert (t["invasor_conocido"]["n"], t["invasor_conocido"]["denominador"]) == (5, 40) assert (t["biopsia_90d"]["n"], t["biopsia_90d"]["denominador"]) == (26, 70) assert (t["maligno_90d"]["n"], t["maligno_90d"]["denominador"]) == (6, 70) assert (t["dias_a_biopsia"]["valor"], t["dias_a_biopsia"]["n"]) == (20, 50) assert all(x["estado"] == "disponible" for x in t.values()) def test_a_horizon_counts_only_the_mammograms_that_have_had_the_time(): """Pins down: with a 365-day horizon and the cut-off 364 days after the mammograms nobody has had the time, so the denominator is zero and the card has no data, not a zero percent; a mammogram that is recent at the cut-off is left out of the 90-day denominator. Fails if a recent mammogram is read as one without a biopsy.""" t = {x["clave"]: x for x in calc.resumen(cohorte(), MAST + timedelta(days=364), 365, MALIGNOS, 5)} assert t["biopsia_365d"]["estado"] == "sin_datos" and t["biopsia_365d"]["valor"] is None recientes = cohorte() + [fila(900 + k, mast=CORTE - timedelta(days=10)) for k in range(6)] t = {x["clave"]: x for x in calc.resumen(recientes, CORTE, 90, MALIGNOS, 5)} assert t["biopsia_90d"]["denominador"] == 70 and t["cohorte"]["valor"] == 76 def test_a_small_numerator_or_denominator_hides_the_figure_and_its_interval(): """Pins down: 3 malignant among 20 known results, and 4 patients with a known result, are not published (state `suprimido`, no value, no interval); an empty cohort has no data. Fails if a small group is shown through a figure.""" pocas = [fila(i, grado="CARCINOMA_INVASOR") for i in range(1, 4)] + [fila(10 + i, grado="BENIGNO") for i in range(17)] t = {x["clave"]: x for x in calc.resumen(pocas, CORTE, 90, MALIGNOS, 5)} assert t["maligno_conocido"]["estado"] == "suprimido" and t["maligno_conocido"]["valor"] is None and t["maligno_conocido"]["ic_bajo"] is None cuatro = {x["clave"]: x for x in calc.resumen([fila(i, grado="BENIGNO") for i in range(4)], CORTE, 90, MALIGNOS, 5)} assert cuatro["maligno_conocido"]["estado"] == "suprimido" vacia = {x["clave"]: x for x in calc.resumen([], CORTE, 90, MALIGNOS, 5)} assert vacia["cohorte"]["valor"] == 0 and vacia["maligno_conocido"]["estado"] == "sin_datos" def test_the_distribution_adds_up_to_the_selection_and_hides_small_groups_by_complement(): """Pins down: 30 + 12 + 8 + 2 patients by BI-RADS: the total is 52, shares are of the selection with Wilson intervals, the 2 and the 8 are not published. Fails if the cells and the total disagree or a hidden cell can be subtracted.""" filas = ([fila(i, birads="BIRADS_5") for i in range(30)] + [fila(100 + i, birads="BIRADS_4A") for i in range(12)] + [fila(200 + i, birads="BIRADS_6") for i in range(2)]) d = calc.distribucion(filas, "birads", [("BIRADS_4A", "4A"), ("BIRADS_5", "5"), ("BIRADS_6", "6")], 5) por = {i["codigo"]: i for i in d["items"]} assert d["total"] == 44 and por["BIRADS_5"]["n"] == 30 and por["BIRADS_5"]["porcentaje"] == pytest.approx(68.18, abs=0.01) assert por["BIRADS_6"]["suprimido"] and por["BIRADS_6"]["n"] is None and por["BIRADS_6"]["ic_bajo"] is None assert por["BIRADS_4A"]["suprimido"], "the smallest published cell is hidden with the small one" assert sum(i["n"] for i in d["items"] if not i["suprimido"]) == 30 assert por["BIRADS_5"]["seleccion"] == {"birads": "BIRADS_5"} def test_the_comparison_shares_the_denominator_of_known_results_and_tests_only_valid_tables(): """Pins down: by BI-RADS, 20 of 40 and 8 of 40 known results are malignant (50 % and 20 %), the test is the chi-square 7.9 with p 0.005, patients without a result are not in the denominator, and a group of fewer than five known results is suppressed and left out of the test. Fails if the denominator includes patients without biopsy or the test uses a hidden group.""" filas = ([fila(i, birads="BIRADS_4A", grado="CARCINOMA_INVASOR") for i in range(20)] + [fila(30 + i, birads="BIRADS_4A", grado="BENIGNO") for i in range(20)] + [fila(100 + i, birads="BIRADS_5", grado="CARCINOMA_IN_SITU") for i in range(8)] + [fila(130 + i, birads="BIRADS_5", grado="BENIGNO") for i in range(32)] + [fila(300 + i, birads="BIRADS_5") for i in range(25)] + [fila(400 + i, birads="BIRADS_6", grado="BENIGNO") for i in range(3)]) c = calc.comparacion(filas, "birads", CATEGORIAS_BIRADS, "maligno", MALIGNOS, 5) g = {x["codigo"]: x for x in c["grupos"]} assert (g["BIRADS_4A"]["casos"], g["BIRADS_4A"]["total"], g["BIRADS_4A"]["valor"]) == (20, 40, 50.0) assert (g["BIRADS_5"]["casos"], g["BIRADS_5"]["total"], g["BIRADS_5"]["valor"]) == (8, 40, 20.0) assert g["BIRADS_6"]["estado"] == "suprimido" assert c["prueba"]["valida"] and c["prueba"]["p"] == pytest.approx(0.00492, abs=0.0001) invasor = calc.comparacion(filas, "birads", CATEGORIAS_BIRADS, "invasor", MALIGNOS, 5) assert {x["codigo"]: x["casos"] for x in invasor["grupos"]}["BIRADS_4A"] == 20 assert {x["codigo"]: x["casos"] for x in invasor["grupos"]}["BIRADS_5"] == 0 def test_the_map_crosses_two_dimensions_and_its_cells_add_up_to_the_selection(): """Pins down: BI-RADS by age group: each patient is in one cell, the published cells never exceed the selection, the proportion of a cell is among its known results and a hidden cell, secondary ones included, has neither count nor proportion. Fails if a patient is counted twice or a hidden cell leaks through its proportion.""" filas = ([fila(i, birads="BIRADS_5", edad="50-59", grado="BENIGNO") for i in range(12)] + [fila(100 + i, birads="BIRADS_5", edad="40-49", grado="CARCINOMA_INVASOR") for i in range(7)] + [fila(200 + i, birads="BIRADS_4A", edad="50-59") for i in range(9)] + [fila(300, birads="BIRADS_4A", edad="40-49")]) m = calc.mapa(filas, "birads", "grupo_edad", CATEGORIAS_BIRADS, CATEGORIAS_EDAD, "maligno", MALIGNOS, 5) celdas = {(c["fila"], c["columna"]): c for c in m["celdas"]} assert celdas[("BIRADS_5", "50-59")]["n"] == 12 and celdas[("BIRADS_5", "50-59")]["resultado"]["casos"] == 0 oculta = celdas[("BIRADS_4A", "40-49")] assert oculta["suprimido"] and oculta["n"] is None and oculta["resultado"]["valor"] is None # The 40-49 column then holds a hidden 1 and a published 7: the 7 goes with it, so the column can't give the 1 away. assert celdas[("BIRADS_5", "40-49")]["suprimido"] and celdas[("BIRADS_5", "40-49")]["resultado"]["valor"] is None assert celdas[("BIRADS_4A", "50-59")]["suprimido"], "and the 4A row hides its 9 for the same reason" assert sum(c["n"] for c in m["celdas"] if not c["suprimido"]) <= len(filas) assert celdas[("BIRADS_5", "50-59")]["seleccion"] == {"birads": "BIRADS_5", "grupo_edad": "50-59"} def test_the_catalog_of_unavailable_analyses_names_a_reason_for_each(): """Pins down: survival, recurrence, treatment adherence, the time-to-event curves and their tests, and BRCA, stage and size are listed as unavailable, each with its reason. Fails if one of them is dropped or loses its reason.""" assert {x["clave"] for x in calc.NO_DISPONIBLES} == {"supervivencia", "recaida", "adherencia_tratamiento", "curvas_tiempo_a_evento", "riesgos_proporcionales", "brca_estadio_tamano"} assert all(x["motivo"] and x["titulo"] for x in calc.NO_DISPONIBLES) assert not math.isnan(wilson(1, 2)[0])