# SPDX-License-Identifier: Apache-2.0 """Two categoricals over one set of codes that mostly hold the same value in a row are modelled as a pair (marginals.same_value_pairs, TableModel same_as). Classes of data: stays and episodes with a first and a last unit, ward or status (ICU stays, hospital transfers, support tickets), and orders whose shipping country or city is usually the billing one. Through the copula alone the two columns keep their dependence only through a latent order of the levels, so with more than a handful of levels neighbouring levels swap and the equal share falls far below the source's. """ from __future__ import annotations import copy import sqlite3 import numpy as np import pandas as pd import pytest import relsynth as rs from relsynth.table_model import SAME, _same_value_pairs, same_decode UNITS = [f"unit_{i:02d}" for i in range(12)] def _stays_db(tmp_path, n=1500, seed=4, codes=None): rng = np.random.default_rng(seed) codes = codes or UNITS p = rng.dirichlet(np.full(len(codes), 3.0)) first = rng.choice(len(codes), n, p=p) moved = rng.random(n) < 0.1 last = np.where(moved, rng.choice(len(codes), n, p=p), first) # length of stay depends on the unit and is longer when the patient moved eff = rng.uniform(0.5, 3.0, len(codes)) los = np.round(rng.gamma(2.0, eff[first] + 2.0 * moved), 3) df = pd.DataFrame({"stay_id": np.arange(1, n + 1), "first_unit": [codes[i] for i in first], "last_unit": [codes[i] for i in last], "los": los}) db = tmp_path / "stays.db" with sqlite3.connect(db) as con: df.to_sql("stays", con, index=False) return db, df def _stays_spec(db, share=None): spec = {"version": 1, "name": "stays", "source": {"kind": "sqlite", "path": str(db)}, "tables": {"stays": {"role": "entity", "primary_key": "stay_id", "columns": {"stay_id": {"type": "id"}, "first_unit": {"type": "categorical"}, "last_unit": {"type": "categorical"}, "los": {"type": "float"}}}}, "relationships": []} if share is not None: spec["synthesis"] = {"marginals": {"same_value_pairs": share}} return spec def _run(spec, seed): return rs.run(copy.deepcopy(spec), write=False, privacy=False, seed=seed, privacy_check=False).data["stays"] def _same(df): return float((df.first_unit == df.last_unit).mean()) @pytest.mark.parametrize("seed", [1, 2]) def test_stays_keep_the_share_of_equal_units(tmp_path, seed): db, src = _stays_db(tmp_path) off = _run(_stays_spec(db), seed) on = _run(_stays_spec(db, 0.5), seed) real = _same(src) assert real > 0.88 assert _same(off) < real - 0.1 # the copula alone loses it (fails before) assert abs(_same(on) - real) < 0.04 # each column keeps its own law, and the moved stays stay longer for c in ("first_unit", "last_unit"): tvd = 0.5 * (src[c].value_counts(normalize=True) .sub(on[c].value_counts(normalize=True), fill_value=0).abs().sum()) assert tvd < 0.08, c moved = on.first_unit != on.last_unit assert on.los[moved].median() > on.los[~moved].median() def test_integer_codes_and_nulls(tmp_path): codes = list(range(100, 112)) db, src = _stays_db(tmp_path, codes=codes, seed=5) with sqlite3.connect(db) as con: # a tenth of the last units unknown con.execute("update stays set last_unit = null where stay_id % 10 = 0") on = _run(_stays_spec(db, 0.5), 3) assert SAME not in set(on.last_unit.dropna().astype(str)) assert set(on.last_unit.dropna().astype(int)) <= set(codes) assert 0.05 < on.last_unit.isna().mean() < 0.15 ok = on.last_unit.notna() assert ((on.first_unit[ok].astype(int) == on.last_unit[ok].astype(int)).mean()) > 0.85 def test_default_off_and_detection(): rng = np.random.default_rng(0) n = 2000 a = rng.choice(list("ABCDEFGH"), n) df = pd.DataFrame({"a": a, "b": np.where(rng.random(n) < 0.8, a, rng.choice(list("ABCDEFGH"), n)), "indep": rng.choice(list("ABCDEFGH"), n), "other": rng.choice(list("XYZ"), n)}) cols = ["a", "b", "indep", "other"] assert _same_value_pairs(df, cols, 0.0, 5) == {} # off by default assert _same_value_pairs(df, cols, 0.5, 5) == {"b": "a"} # not indep (chance), not other (no shared codes) # a dominant level alone is chance, not a pair: equal share below twice the chance share d2 = pd.DataFrame({"a": np.where(rng.random(n) < 0.9, "X", "Y"), "b": np.where(rng.random(n) < 0.9, "X", "Y")}) assert _same_value_pairs(d2, ["a", "b"], 0.5, 5) == {} def test_same_decode(): cols = {"a": np.array(["x", "y", None], dtype=object), "b": np.array([SAME, "z", SAME], dtype=object)} same_decode(cols, {"b": "a"}) assert list(cols["b"]) == ["x", "z", "z"] # a null partner: b from its own rows def test_same_decode_draws_from_the_fitted_values_when_the_batch_has_none(): # a batch of only a = null, b = marker: b takes a fitted value of its own, never a null from relsynth.table_model import same_pool pool = {"b": same_pool(pd.Series(["x"] * 6 + ["y"] * 6 + ["z"] * 2), kmin=5)} assert pool["b"] == [["x", "y"], [0.5, 0.5]] # levels below kmin stay out cols = {"a": np.array([None, None], dtype=object), "b": np.array([SAME, SAME], dtype=object)} same_decode(cols, {"b": "a"}, np.random.default_rng(0), pool=pool) assert set(cols["b"]) <= {"x", "y"} def test_model_export_and_replica_keep_the_pair(tmp_path): import json from relsynth.replica import generate db, src = _stays_db(tmp_path, n=1000) assert rs.fit(_stays_spec(db, 0.5), seed=1).synthesizer.tm["stays"].same_as == {"last_unit": "first_unit"} rs.export_model(_stays_spec(db, 0.5), tmp_path / "m", formats=("json",), draws=1, replica_check=False) model = json.loads(next((tmp_path / "m").glob("*.json")).read_text()) assert model["structure"]["attributes"]["stays"]["same_as"] == {"last_unit": "first_unit"} assert model["structure"]["attributes"]["stays"]["same_pool"]["last_unit"][0] st = generate(model, seed=2)["stays"] assert SAME not in set(st.last_unit.astype(str)) assert abs(_same(st) - _same(src)) < 0.05 def test_a_null_partner_never_makes_a_null(): rng = np.random.default_rng(0) cols = {"a": np.array(["x", None, None, "y"], dtype=object), "b": np.array([SAME, SAME, "z", SAME], dtype=object)} same_decode(cols, {"b": "a"}, rng) assert cols["b"][0] == "x" and cols["b"][3] == "y" and cols["b"][1] == "z" def test_a_column_holding_the_marker_is_not_paired(): n = 200 a = np.array(list("ABCD") * (n // 4), dtype=object) b = a.copy() b[:10] = SAME df = pd.DataFrame({"a": a, "b": b}) assert _same_value_pairs(df, ["a", "b"], 0.5, 5) == {}