From 8f9ac521a165c93ea0f6c5c0435d8ed805521cf8 Mon Sep 17 00:00:00 2001 From: haoyu-haoyu <85037553+haoyu-haoyu@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:15:33 +0000 Subject: [PATCH] Fix false matches in MIMIC concept comparisons --- .github/workflows/transpile.yml | 5 +- src/mimic_utils/compare_concepts.py | 190 +++++++++++++++++----------- tests/test_compare_concepts.py | 135 +++++++++++++++++++- 3 files changed, 250 insertions(+), 80 deletions(-) diff --git a/.github/workflows/transpile.yml b/.github/workflows/transpile.yml index 4d75074ea..a0aa79b76 100644 --- a/.github/workflows/transpile.yml +++ b/.github/workflows/transpile.yml @@ -4,7 +4,6 @@ on: - pull_request jobs: - # Unit tests for the transpiler. unit-tests: name: Transpile unit tests runs-on: ubuntu-latest @@ -17,8 +16,8 @@ jobs: run: pip install -r requirements-lock.txt - name: Install package run: pip install -e . --no-deps - - name: Run transpiler unit tests - run: pytest tests/test_transpile.py -q + - name: Test the transpiler and concept comparisons + run: pytest -q tests/test_transpile.py tests/test_compare_concepts.py generated-up-to-date: name: Check cross-dialect concepts match BQ diff --git a/src/mimic_utils/compare_concepts.py b/src/mimic_utils/compare_concepts.py index 2c345e9d6..eadc83fd9 100644 --- a/src/mimic_utils/compare_concepts.py +++ b/src/mimic_utils/compare_concepts.py @@ -6,8 +6,8 @@ Each table is compared on: * presence in both engines, * row count, - * content -- rows are canonicalised (numeric columns rounded, then all columns - sorted) and aligned, then compared cell-by-cell with a float tolerance. + * content -- rows are aligned and compared cell-by-cell. Integers and text + are compared exactly. Tolerances apply to continuous numeric values. The comparison returns a non-zero exit code if any non-ignored table differs, so it can gate CI. @@ -19,6 +19,9 @@ [--schema mimiciv_derived] [--rtol 1e-6] [--atol 1e-9] \ [--ignore table_a,table_b] """ +from decimal import Decimal +from fractions import Fraction + import numpy as np import pandas as pd @@ -28,13 +31,43 @@ def _fetch_df(cursor_or_rel, table, schema, engine): if engine == "postgres": cursor_or_rel.execute(f'SELECT * FROM {schema}."{table}"') cols = [c[0] for c in cursor_or_rel.description] - df = pd.DataFrame(cursor_or_rel.fetchall(), columns=cols) + # Inference turns an integer column containing NULL into float64. + df = pd.DataFrame(cursor_or_rel.fetchall(), columns=cols, dtype=object) else: # duckdb - df = cursor_or_rel.sql(f'SELECT * FROM {schema}."{table}"').df() + rel = cursor_or_rel.sql(f'SELECT * FROM {schema}."{table}"') + # NumPy narrows DECIMAL and wide integers (including nullable BIGINT + # in older DuckDB). Keep df() for columns such as TIMESTAMP_NS. + converters = { + "decimal": Decimal, "bigint": int, "ubigint": int, + "hugeint": int, "uhugeint": int, "bignum": int, + "uuid": str, # psycopg2 returns UUID as text by default. + } + restore = {} + replacements = [] + for name, sql_type in zip(rel.columns, rel.types): + if str(sql_type) == "JSON": + # psycopg2 decodes JSON numbers, while DuckDB returns text. + # Only an unquoted JSON number gets numeric comparison. + restore[name] = _json_number_or_text + elif sql_type.id in converters: + quoted = '"' + name.replace('"', '""') + '"' + replacements.append(f"CAST({quoted} AS VARCHAR) AS {quoted}") + restore[name] = converters[sql_type.id] + if replacements: + rel = rel.project(f"* REPLACE ({', '.join(replacements)})") + df = rel.df() + for name, convert in restore.items(): + df[name] = pd.Series( + [None if pd.isna(v) else convert(v) for v in df[name]], dtype=object, index=df.index + ) df.columns = [c.lower() for c in df.columns] return df +def _json_number_or_text(value): + return Decimal(value) if value.lstrip().startswith(tuple("-0123456789")) else value + + def _list_tables_pg(cur, schema): cur.execute( "SELECT table_name FROM information_schema.tables " @@ -53,61 +86,68 @@ def _list_tables_duckdb(con, schema): return [r[0] for r in rows] -def _as_numeric(series): - """Return a float Series if every non-null value coerces, else None.""" - if _is_datetime_like_series(series): - return None - coerced = pd.to_numeric(series, errors="coerce") - if coerced.isna().sum() == series.isna().sum(): - return coerced.astype(float) - return None - - -def _is_datetime_like_series(series): - """Return True when values are already datetimes, even if stored as object dtype.""" - if pd.api.types.is_datetime64_any_dtype(series.dtype) or pd.api.types.is_datetime64tz_dtype(series.dtype): +def _comparison_kind(left, right): + # Classify native values from the drivers. A VARCHAR that looks like a + # number or date is still text; integer widths can differ across engines. + # DataFrames with a nullable identifier can arrive with a float dtype. + if isinstance(left.name, str) and left.name.endswith("_id"): + return "exact" + # Some pandas versions infer mixed-integer-float for native floats plus None. + kinds = {pd.api.types.infer_dtype(s.dropna()) for s in (left, right)} - {"empty"} + if "mixed" in kinds or "mixed-integer" in kinds: + # Lists, mappings and other driver objects need sortable values. + return "string" + if kinds and kinds <= {"date", "datetime", "datetime64"}: + return "datetime" + if kinds and kinds <= {"floating", "decimal"}: + return "decimal" if "decimal" in kinds else "float" + return "exact" + + +def _wall_time(series): + if pd.api.types.is_datetime64_any_dtype(series.dtype): + return series.dt.tz_localize(None) + return series.map(lambda value: pd.Timestamp(value).tz_localize(None), na_action="ignore") + + +def _align_rows(frame, kinds, atol, use_tolerance): + aligned = frame.copy(deep=False) + for col, kind in kinds.items(): + if kind == "datetime": + aligned[col] = _wall_time(frame[col]) + elif kind == "string": + aligned[col] = frame[col].astype("string") + + # Exact columns identify rows before approximate measurements break ties. + order = sorted(kinds, key=lambda col: kinds[col] in {"float", "decimal"}) + + def sort_key(series): + if use_tolerance and kinds[series.name] in {"float", "decimal"}: + decimals = max(0, int(round(-np.log10(atol)))) if atol > 0 else 9 + return series.astype(float).round(decimals) + return series + + # Start in native value order so that rounded-key ties are independent + # of the input order. Compare the original values after alignment. + aligned = aligned.sort_values(by=order, kind="mergesort", na_position="first") + if use_tolerance and any(k in {"float", "decimal"} for k in kinds.values()): + aligned = aligned.sort_values(by=order, key=sort_key, kind="mergesort", na_position="first") + return aligned.reset_index(drop=True) + + +def _decimal_close(a, b, rtol, atol): + # Subtract before narrowing either operand to a binary float. A DECIMAL + # can have many more significant digits than float64. + a = a if isinstance(a, Decimal) else Decimal.from_float(float(a)) + b = b if isinstance(b, Decimal) else Decimal.from_float(float(b)) + if a == b: return True - non_null = series.dropna() - if non_null.empty: + if not (a.is_finite() and b.is_finite()): return False - sample = non_null.iloc[0] - return isinstance(sample, (pd.Timestamp, np.datetime64)) or hasattr(sample, "tzinfo") - - -def _as_datetime(series): - """Return a datetime Series if every non-null value parses, else None.""" - import warnings - with warnings.catch_warnings(): - warnings.simplefilter("ignore") # silence per-element parse fallback notices - coerced = pd.to_datetime(series, errors="coerce") - if coerced.isna().sum() == series.isna().sum(): - if pd.api.types.is_datetime64tz_dtype(coerced.dtype): - coerced = coerced.dt.tz_localize(None) - return coerced - return None - - -def _column_kinds(pg_df, dk_df): - """Classify each column jointly as 'num', 'dt' or 'str' (numeric tried first - so integer ids are not mistaken for datetimes).""" - kinds = {} - for col in pg_df.columns: - if _as_numeric(pg_df[col]) is not None and _as_numeric(dk_df[col]) is not None: - kinds[col] = "num" - elif _as_datetime(pg_df[col]) is not None and _as_datetime(dk_df[col]) is not None: - kinds[col] = "dt" - else: - kinds[col] = "str" - return kinds - - -def _canon(series, kind, decimals): - """Canonical, type-correct representation used for both sorting and comparison.""" - if kind == "num": - return _as_numeric(series).round(decimals) - if kind == "dt": - return _as_datetime(series) - return series.astype("string").fillna("\x00") + # Decimal arithmetic rounds to the active context (usually 28 digits). + # The stored operands and the tolerance boundary can exceed that precision. + a, b = Fraction(a), Fraction(b) + return abs(a - b) <= atol + rtol * abs(b) def compare_table(pg_df, duck_df, rtol, atol): @@ -121,29 +161,29 @@ def compare_table(pg_df, duck_df, rtol, atol): return False, f"row count differs: postgres={len(pg_df)} duckdb={len(duck_df)}" duck_df = duck_df[pg_df.columns] # align column order - kinds = _column_kinds(pg_df, duck_df) - # round numerics to a tolerance-consistent #decimals so tiny float diffs do - # not reorder rows during the sort-align step - decimals = max(0, int(round(-np.log10(atol)))) if atol > 0 else 9 - - pg_c = pd.DataFrame({c: _canon(pg_df[c], kinds[c], decimals) for c in pg_df.columns}) - dk_c = pd.DataFrame({c: _canon(duck_df[c], kinds[c], decimals) for c in pg_df.columns}) - - order = list(pg_c.columns) - pg_c = pg_c.sort_values(by=order, kind="mergesort", na_position="first").reset_index(drop=True) - dk_c = dk_c.sort_values(by=order, kind="mergesort", na_position="first").reset_index(drop=True) + kinds = {col: _comparison_kind(pg_df[col], duck_df[col]) for col in pg_df} + use_tolerance = rtol != 0 or atol != 0 + pg_c = _align_rows(pg_df, kinds, atol, use_tolerance) + dk_c = _align_rows(duck_df, kinds, atol, use_tolerance) mismatched_cells = 0 bad_cols = [] - for col in order: + for col, kind in kinds.items(): a, b = pg_c[col], dk_c[col] - if kinds[col] == "num": - close = np.isclose(a.to_numpy(float), b.to_numpy(float), rtol=rtol, atol=atol, equal_nan=True) - elif kinds[col] == "dt": - close = (a.to_numpy() == b.to_numpy()) | (a.isna().to_numpy() & b.isna().to_numpy()) + missing_a, missing_b = a.isna(), b.isna() + n_bad = int((missing_a != missing_b).sum()) + present = ~(missing_a | missing_b) + a, b = a[present], b[present] + if use_tolerance and kind == "float": + close = np.isclose(a.to_numpy(float), b.to_numpy(float), rtol=rtol, atol=atol) + n_bad += int((~close).sum()) + elif use_tolerance and kind == "decimal": + rel, abs_tol = Fraction(float(rtol)), Fraction(float(atol)) + n_bad += sum(not _decimal_close(x, y, rel, abs_tol) for x, y in zip(a, b)) else: - close = (a == b).to_numpy() - n_bad = int((~close).sum()) + # Object comparison avoids promoting int64 or Decimal to float64 + # when the other engine returned a different numeric type. + n_bad += int((a.astype(object) != b.astype(object)).sum()) if n_bad: mismatched_cells += n_bad bad_cols.append(f"{col}({n_bad})") diff --git a/tests/test_compare_concepts.py b/tests/test_compare_concepts.py index 5ad98e28b..da660ecd1 100644 --- a/tests/test_compare_concepts.py +++ b/tests/test_compare_concepts.py @@ -1,8 +1,11 @@ from datetime import datetime, timedelta, timezone +from decimal import Decimal +from unittest.mock import Mock import pandas as pd +import pytest -from mimic_utils.compare_concepts import compare_table +from mimic_utils.compare_concepts import compare_concepts, compare_table def test_compare_table_treats_same_wall_time_as_equal_across_timezones(): @@ -19,4 +22,132 @@ def test_compare_table_flags_different_wall_times_even_if_instants_match(): assert compare_table(pg, duck, 1e-6, 1e-9) == ( False, "1 differing cells in columns: charttime(1)", - ) \ No newline at end of file + ) + + +@pytest.mark.parametrize( + "column, pg_value, duck_value", + [ + ("hadm_id", 20_000_000, 20_000_001), + ("code", "001", "1"), + ("label", "2025-01-01", "2025-01-01 00:00:00"), + ], +) +def test_discrete_values_match_exactly_with_default_tolerance(column, pg_value, duck_value): + pg = pd.DataFrame({column: [pg_value]}) + duck = pd.DataFrame({column: [duck_value]}) + + assert compare_table(pg, duck, 1e-6, 1e-9) == ( + False, f"1 differing cells in columns: {column}(1)" + ) + + +def test_reordered_rows_with_nullable_ids_and_text_still_match(): + pg = pd.DataFrame({ + "stay_id": pd.array([23, None, 23], dtype="Int32"), + "code": ["01", "1", None], + }) + duck = pg.iloc[::-1].astype({"stay_id": "Int64"}) + + assert compare_table(pg, duck, 1e-6, 1e-9) == (True, "3 rows OK") + + +def test_nullable_hadm_id_inferred_as_float_still_matches_exactly(): + pg = pd.DataFrame({"hadm_id": [20_000_000, None]}) + duck = pd.DataFrame({"hadm_id": [20_000_001, None]}) + + assert compare_table(pg, duck, 1e-6, 1e-9) == ( + False, "1 differing cells in columns: hadm_id(1)" + ) + + +def test_nullable_float_measurements_keep_their_tolerance(): + pg = pd.DataFrame({"value": pd.Series([37.12345, None], dtype=object)}) + duck = pd.DataFrame({"value": pd.Series([None, 37.12345], dtype="float32")}) + + assert compare_table(pg, duck, 1e-6, 1e-9) == (True, "2 rows OK") + + +def test_reordered_precise_decimal_values_match_with_absolute_tolerance(): + pg = pd.DataFrame({"value": [ + Decimal("12345678901234567890.0000000001"), + Decimal("12345678901234567890.0000000002"), + ]}) + duck = pg.iloc[::-1] + + assert compare_table(pg, duck, rtol=0, atol=1e-13) == (True, "2 rows OK") + + +@pytest.mark.parametrize( + "pg_value, duck_value, rtol, atol, expected", + [ + (1.0, 1.0000000004, 0, 0, False), + (1.0, 1.0000000004, 0, 1e-9, True), + (Decimal("37"), 37.000001, 1e-6, 1e-9, True), + (Decimal("2.5"), 2.5, 0, 0, True), + (Decimal("1.00000000000000000000000000001"), Decimal("0"), 0, 1, False), + ], +) +def test_measurement_tolerance(pg_value, duck_value, rtol, atol, expected): + pg = pd.DataFrame({"value": [pg_value]}) + duck = pd.DataFrame({"value": [duck_value]}) + + ok, _ = compare_table(pg, duck, rtol, atol) + assert ok == expected + + +@pytest.mark.parametrize( + "sql_type, pg_oid, pg_value, duck_value, equal", + [ + ("BIGINT", 20, 2**53 + 1, 2**53, False), + ("BIGINT", 20, 2**53, 2**53 + 1, False), + ("DECIMAL(25,10)", 1700, + Decimal("1234567890.0000000001"), Decimal("1234567890.0000000002"), False), + ("JSON", 114, [1, 2], "[1, 2]", True), + ("JSON", 3802, None, "null", False), + ("JSON", 114, 1000, "1e3", True), + ("UUID", 2950, "00000000-0000-0000-0000-000000000001", + "00000000-0000-0000-0000-000000000001", True), + ("UUID", 2950, "00000000-0000-0000-0000-000000000001", + "00000000-0000-0000-0000-000000000002", False), + ("TIMESTAMP_NS", 1114, datetime(2150, 1, 2, 3, 4, 5, 123456), + "2150-01-02 03:04:05.123456000", True), + ("TIMESTAMP_NS", 1114, datetime(2150, 1, 2, 3, 4, 5, 123456), + "2150-01-02 03:04:05.123456001", False), + ], +) +def test_database_reads_preserve_exact_values_with_nulls( + tmp_path, monkeypatch, capsys, sql_type, pg_oid, pg_value, duck_value, equal +): + duckdb = pytest.importorskip("duckdb") + psycopg2 = pytest.importorskip("psycopg2") + path = tmp_path / "concepts.duckdb" + with duckdb.connect(str(path)) as conn: + if sql_type == "JSON": + # Some old DuckDB distributions ship JSON as a separate extension. + conn.execute("SET autoinstall_known_extensions = false") + try: + conn.execute("SELECT CAST('{}' AS JSON)").fetchone() + except duckdb.Error as exc: + pytest.skip(f"DuckDB JSON extension unavailable: {exc}") + conn.execute("CREATE SCHEMA derived") + conn.execute(f"CREATE TABLE derived.sample (value {sql_type})") + if sql_type == "TIMESTAMP_NS": + # Older DuckDB releases truncate a timestamp string on input. + stamps = pd.Series([duck_value, None], dtype="datetime64[ns]") + conn.register("stamps", stamps.to_frame("value")) + conn.execute("INSERT INTO derived.sample SELECT value FROM stamps") + else: + conn.execute("INSERT INTO derived.sample VALUES (?), (NULL)", [duck_value]) + + # Use the native values and column description a psycopg2 cursor returns. + pg = Mock() + cursor = pg.cursor.return_value + cursor.description = [psycopg2.extensions.Column("value", pg_oid)] + cursor.fetchall.side_effect = [[("sample",)], [(pg_value,), (None,)]] + monkeypatch.setattr(psycopg2, "connect", lambda dsn: pg) + + result = compare_concepts("", str(path), "derived", rtol=0, atol=0) + assert result == (0 if equal else 1) + message = "2 rows OK" if equal else "1 differing cells in columns: value(1)" + assert message in capsys.readouterr().out