Merge origin/rebuild into parity/T1-merge (models)
Per PLAN-feature-parity §2.1/2.2/2.4: non-TEA from rebuild, TEA backend from tea/parity. - tea/association.py, tea/jobs.py, tea/eeg/reference.py: tea/parity's (tea-lib association checked against the reference; reference-cohort training; execution.map). rebuild's ruled-out training and its own association go; T3 adds the site cohort as a training source in tea/parity's design. - cluster.py deleted: tea/parity's persistance.cluster + models.execution run every batch. The optional [dask] extra goes with it (Persistance depends on dask directly). - definitions.py: tea/parity's jobs (tea_eeg, preview, bundles, sensor) plus rebuild's backup job and nightly schedule. Scoring takes Jobs.routine(); rebuild's scored() was the same list, so it is not kept as a second name. - graph.py: tea/parity's edf reader node plus rebuild's file_format and otherwise-routes. - jobs.py: rebuild's (every model is routine; no reference-trained branch). - tests: tea/parity's logic tests kept where both changed (test_eeg, test_recurrence, test_silver); test_survival_seer stays deleted (P7).
This commit is contained in:
@@ -0,0 +1,135 @@
|
||||
"""The two public cohorts the recurrence model is proved on, METABRIC and SCAN-B, each as a
|
||||
`Cohort` from its dataset as the `cama_reference` pipeline loads it (every value as written,
|
||||
column names as dlt names them, `line` the order the file is published in)."""
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from models.cama import recurrence
|
||||
from models.cama.recurrence import site
|
||||
from models.cama.recurrence.cohorts import (
|
||||
AGE,
|
||||
DAYS_PER_MONTH,
|
||||
GRADES,
|
||||
NODES,
|
||||
SIZE,
|
||||
Cohort,
|
||||
_band,
|
||||
_number,
|
||||
_text,
|
||||
collinear,
|
||||
)
|
||||
|
||||
SOURCES = ("metabric", "scanb")
|
||||
SAVED = "metabric"
|
||||
N_BOOTSTRAP = {"metabric": 100, "scanb": 40, "site": 40}
|
||||
LABELS = {"metabric": "METABRIC", "scanb": "SCAN-B"}
|
||||
SAMPLING = {
|
||||
"criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres",
|
||||
"origen": "METABRIC y SCAN-B (externas)",
|
||||
}
|
||||
SCENARIOS = {
|
||||
"metabric": {
|
||||
"RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
|
||||
"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["0"],
|
||||
"Tamano_tumor": ["<=20 mm"]},
|
||||
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
|
||||
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
|
||||
"< 45 años": {"Edad": ["<45"]},
|
||||
"≥ 75 años": {"Edad": ["75+"]},
|
||||
"Basal (PAM50)": {"Subtipo_PAM50": ["Basal"]},
|
||||
"HER2 (PAM50)": {"Subtipo_PAM50": ["Her2"]},
|
||||
"Luminal B (PAM50)": {"Subtipo_PAM50": ["LumB"]},
|
||||
"RE+ · 1-3 ganglios · cirugía conservadora": {
|
||||
"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["1-3"],
|
||||
"Cirugia": ["BREAST CONSERVING"]},
|
||||
"RE− · grado 3": {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]},
|
||||
},
|
||||
"scanb": site.SCENARIOS,
|
||||
} # fmt: skip
|
||||
FIXED = {
|
||||
"metabric": ["paciente", "tiempo_meses", "evento"],
|
||||
"scanb": ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"],
|
||||
}
|
||||
TREATMENT = {
|
||||
"metabric": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"],
|
||||
"scanb": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"],
|
||||
}
|
||||
# Covariates taken as they come (our name: the dataset's column).
|
||||
PASSTHROUGH = {
|
||||
"metabric": {
|
||||
"Receptor_estrogeno": "er_status", "Receptor_progesterona": "pr_status",
|
||||
"HER2": "her2_status", "Subtipo_PAM50": "pam50_x_claudin_low_subtype",
|
||||
"Tipo_histologico": "cancer_type_detailed", "Celularidad": "cellularity",
|
||||
"Estado_menopausico": "inferred_menopausal_state",
|
||||
"Cluster_integrativo": "integrative_cluster", "Lateralidad": "primary_tumor_laterality",
|
||||
"Cirugia": "type_of_breast_surgery", "Quimioterapia": "chemotherapy",
|
||||
"Radioterapia": "radio_therapy", "Hormonoterapia": "hormone_therapy",
|
||||
},
|
||||
"scanb": {
|
||||
"Receptor_estrogeno": "er", "Receptor_progesterona": "pr", "HER2": "her2",
|
||||
"Ki67": "ki67", "Subtipo_clinico": "clinical_subtype", "Tipo_histologico": "histology",
|
||||
"Estado_menopausico": "menopause_status_bin", "Lateralidad": "laterality",
|
||||
"Estadio_clinico": "tnm_clinical_stage", "Cirugia": "surgery_type",
|
||||
"Quimioterapia": "chemotherapy", "Radioterapia": "radiation",
|
||||
"Hormonoterapia": "endocrine", "AntiHER2": "anti_her2",
|
||||
},
|
||||
} # fmt: skip
|
||||
SCANB_NODES = {"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"}
|
||||
SCANB_GRADES = {"Grade1": "1", "Grade2": "2", "Grade3": "3"}
|
||||
|
||||
|
||||
def _in_order(rows: pd.DataFrame) -> pd.DataFrame:
|
||||
return rows.sort_values("line", kind="stable").reset_index(drop=True)
|
||||
|
||||
|
||||
def _metabric(rows: pd.DataFrame) -> pd.DataFrame:
|
||||
d = _in_order(rows).dropna(subset=["relapse_free_status", "relapse_free_status_monthsx"])
|
||||
d = d.reset_index(drop=True)
|
||||
out = pd.DataFrame({"paciente": d["patient_id"]})
|
||||
out["tiempo_meses"] = _number(d["relapse_free_status_monthsx"])
|
||||
out["evento"] = d["relapse_free_status"].str.startswith("1").astype(int)
|
||||
out["Edad"] = _band(_number(d["age_at_diagnosis"]), *AGE)
|
||||
out["Tamano_tumor"] = _band(_number(d["tumor_size"]), *SIZE)
|
||||
out["Ganglios_positivos"] = _band(_number(d["lymph_nodes_examined_positive"]), *NODES)
|
||||
out["Grado_histologico"] = _text(d["neoplasm_histologic_grade"].map(GRADES))
|
||||
# Mutational load in tertiles of this cohort; a value on a cut falls in the lower band.
|
||||
load = _number(d["mutation_count"])
|
||||
q1, q2 = load.quantile([1 / 3, 2 / 3]).to_numpy()
|
||||
edges = [-1, q1 + 1e-9, q2 + 1e-9, 1e6]
|
||||
out["Carga_mutacional"] = _band(load, edges, ["baja", "media", "alta"])
|
||||
for name, column in PASSTHROUGH["metabric"].items():
|
||||
out[name] = _text(d[column])
|
||||
return out
|
||||
|
||||
|
||||
def _scanb(rows: pd.DataFrame) -> pd.DataFrame:
|
||||
d = _in_order(rows)
|
||||
d = d[d["gender"] == "F"].dropna(subset=["rfi_event", "rfi_days"]).reset_index(drop=True)
|
||||
rfi, died = _number(d["rfi_event"]), _number(d["os_event"])
|
||||
out = pd.DataFrame({"paciente": d["patient_name"]})
|
||||
out["tiempo_meses"] = _number(d["rfi_days"]) / DAYS_PER_MONTH
|
||||
out["evento"] = rfi.astype(int)
|
||||
out["muerte_sin_recaida"] = ((died == 1) & (rfi == 0)).astype(int)
|
||||
out["Edad"] = _band(_number(d["age_5year_bin"]) - 2, *AGE) # the 5-year bin's middle
|
||||
out["Tamano_tumor"] = _band(_number(d["tumor_size_mm"]), *SIZE)
|
||||
out["Ganglios_positivos"] = _text(d["node_met_spec"].map(SCANB_NODES))
|
||||
out["Grado_histologico"] = _text(d["nhg"].map(SCANB_GRADES))
|
||||
for name, column in PASSTHROUGH["scanb"].items():
|
||||
out[name] = _text(d[column])
|
||||
return out
|
||||
|
||||
|
||||
def prepare(source: str, raw: pd.DataFrame) -> Cohort:
|
||||
full = {"metabric": _metabric, "scanb": _scanb}[source](raw)
|
||||
fixed, treatment = FIXED[source], TREATMENT[source]
|
||||
covariates = [c for c in full.columns if c not in fixed]
|
||||
dropped = collinear(full, [c for c in covariates if c not in treatment])
|
||||
kept = [c for c in covariates if c not in dropped]
|
||||
return Cohort(source, full[fixed + kept], kept, [c for c in treatment if c in kept], dropped,
|
||||
LABELS[source], SCENARIOS[source], SAMPLING) # fmt: skip
|
||||
|
||||
|
||||
def train(raws: dict[str, pd.DataFrame], bootstrap: bool = True) -> tuple:
|
||||
"""Both cohorts' models, validation, calculator and risk factors; METABRIC's is kept."""
|
||||
found = {s: prepare(s, raws[s]) for s in SOURCES}
|
||||
return recurrence.fit(found, SAVED, "metabric+scanb", N_BOOTSTRAP if bootstrap else {})
|
||||
@@ -0,0 +1,51 @@
|
||||
"""A reviewer's "they are different people" is about the persons: it holds when more records
|
||||
join one of them, whichever record the person is known by afterwards."""
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
|
||||
PEOPLE = [("1001", "ANA LOPEZ RUIZ", "1980-01-01"), ("2002", "BEATRIZ MORA DIAZ", "1980-01-01")]
|
||||
PEOPLE += [(f"9{k:03d}", f"PERSONA {k} DE RELLENO", f"19{50 + k}-0{1 + k % 9}-11")
|
||||
for k in range(30)] # fmt: skip
|
||||
|
||||
|
||||
def graph(db) -> dict:
|
||||
fields = {"record_number": "num", "full_name": "nombre", "birth_date": "nac", "nss": "nss"}
|
||||
return {"nodes": [
|
||||
{"id": "people", "kind": "source", "source": "dlt.sources.sql_database:sql_table",
|
||||
"args": {"credentials": f"sqlite:///{db}", "table": "people"}},
|
||||
{"id": "identity", "kind": "map", "inputs": ["people"], "fields": fields},
|
||||
{"id": "persons", "kind": "link", "inputs": ["identity"], "fields": list(fields)},
|
||||
]} # fmt: skip
|
||||
|
||||
|
||||
def insert(db, rows) -> None:
|
||||
with sqlite3.connect(db) as con:
|
||||
con.execute(
|
||||
"create table if not exists people "
|
||||
"(id integer primary key, num text, nombre text, nac text, nss text)"
|
||||
)
|
||||
con.executemany("insert into people (num, nombre, nac, nss) values (?, ?, ?, ?)", rows)
|
||||
|
||||
|
||||
def test_an_answer_outlives_the_record_a_person_was_known_by(platform, tmp_path):
|
||||
db, drawn = tmp_path / "people.db", tmp_path / "pipeline.json"
|
||||
insert(db, [(*p, None) for p in PEOPLE])
|
||||
drawn.write_text(json.dumps(graph(db)))
|
||||
platform.save("pipelines", "site", drawn)
|
||||
platform.ingest()
|
||||
queue = "select person, candidate from bronze.n__site__persons__review"
|
||||
((a, b),) = platform.query(queue)
|
||||
platform.run("python", "-c", "from persistance import nodes; "
|
||||
f"nodes.decide_persons({a!r}, {b!r}, False, 'reviewer')") # fmt: skip
|
||||
platform.ingest()
|
||||
assert platform.query(queue) == []
|
||||
|
||||
# Forty more documents of each woman: whichever of her records her person was known by,
|
||||
# one of these is (almost surely) it now.
|
||||
insert(db, [(num, None, None, f"{num}{k:07d}") for num in ("1001", "2002") for k in range(40)])
|
||||
platform.ingest()
|
||||
lowest = "select min(_record) from bronze.n__site__persons where record_number = '{}'"
|
||||
known = {platform.query(lowest.format(n))[0][0] for n in ("1001", "2002")}
|
||||
assert known != {a, b}
|
||||
assert platform.query(queue) == []
|
||||
Reference in New Issue
Block a user