Source code for corr_vars.core.codebook

"""Privacy-safe codebook of a cohort: types, missingness and coarse distributions.

The codebook describes the *shape* of ``obs`` and ``obsm`` without any
patient-level value, so it can leave the server and be read by an analyst or a
coding agent that has no access to the data:

- every column: dtype, n, % missing, n unique;
- numeric and duration columns: percentiles from p1 / p25 / p50 / p75 / p99,
  no min or max. A percentile is published only when at least ``min_count``
  values lie on each side of it (p25 / p75 need ``4 * min_count`` values, p1 /
  p99 ``100 * min_count``), and it is an observed value (nearest rank), never
  an interpolation between two values;
- numeric columns with at most ``MAX_NUMERIC_LEVELS`` distinct values (0/1
  flags, scores, years): counts per value like a categorical column, because
  percentiles of a few distinct values reveal counts;
- categorical and boolean columns: counts per level. Levels seen fewer than
  ``min_count`` times are not named, only counted (``n_levels_suppressed``);
- datetimes: the month of p1 … p99 under the same rule, and counts per year
  (rare years suppressed like levels). No per-month counts;
- dates of birth (a date/datetime column named like ``birthdate`` or
  ``date_of_birth``): dtype and missingness only, as for ID-like and free-text
  columns;
- struct columns (``*_detail``): one entry per field;
- ``obsm`` frames: only rows of observations still in ``obs``.

Suppression is complementary: when the suppressed levels add up to fewer than
``min_count``, the next-smallest published levels are suppressed as well, so a
small count cannot be read off as the total minus the published counts. It can
still be bounded; the codebook is a safeguard against accidental disclosure,
not a formal anonymisation.
"""

from __future__ import annotations

import json
import re
from pathlib import Path

import polars as pl

from corr_vars.definitions.typing import ObsLevel
from typing import TYPE_CHECKING, Any, Final

if TYPE_CHECKING:
    from os import PathLike

    from collections.abc import Mapping

DEFAULT_MIN_COUNT: Final[int] = 10
"""Smallest count published; smaller level, year and sample counts are suppressed."""

MAX_LEVELS: Final[int] = 50
"""A string column with more distinct values than this is treated as free text."""

MAX_NUMERIC_LEVELS: Final[int] = 10
"""A numeric column with at most this many distinct values is summarised by
counts per value instead of percentiles."""

QUANTILES: Final[tuple[float, ...]] = (0.01, 0.25, 0.5, 0.75, 0.99)
"""Percentiles reported for numeric columns (no min/max: those are single values).
Each needs ``min_count`` values on either side; see :func:`_quantile_ranks`."""

_BIRTH_DATE: Final[re.Pattern[str]] = re.compile(
    r"birth|^dob$|_dob$|^dob_|geburt", re.IGNORECASE
)
"""Name of a date/datetime column treated as a date of birth (no distribution)."""


def _is_id_like(name: str) -> bool:
    return name in ObsLevel.primary_keys() or name.endswith("_id")


def _quantile_ranks(n: int, min_count: int) -> dict[str, int]:
    """Nearest-rank index of each percentile with ``min_count`` values on each side."""
    return {
        f"p{round(q * 100)}": round(q * (n - 1))
        for q in QUANTILES
        if n and min(q, 1 - q) * n >= min_count
    }


def _quantiles(values: pl.Series, min_count: int) -> dict[str, float] | None:
    values = values.drop_nulls()
    if values.dtype == pl.Boolean:
        return None
    if values.dtype.is_float():
        values = values.filter(values.is_finite())
    ranks = _quantile_ranks(values.len(), min_count)
    if not ranks:
        return None
    ordered = values.sort()
    return {label: float(ordered[i]) for label, i in ranks.items()}


def _month_quantiles(values: pl.Series, min_count: int) -> dict[str, str] | None:
    ordered = values.drop_nulls().sort()
    ranks = _quantile_ranks(ordered.len(), min_count)
    if not ranks:
        return None
    months = ordered.dt.strftime("%Y-%m")
    return {label: months[i] for label, i in ranks.items()}


def _counts(values: pl.Series, min_count: int) -> tuple[dict[str, int], int]:
    """Count each non-null level; rare levels are dropped and only counted.

    Returns the published ``{level: n}`` (most frequent first) and the number
    of suppressed levels. A level seen fewer than `min_count` times is never
    named. When the suppressed levels add up to fewer than `min_count` values,
    the smallest published levels are suppressed too, so the total minus the
    published counts does not reveal a small count.
    """
    rows = values.drop_nulls().cast(pl.String).value_counts(sort=True, name="n").rows()
    shown = [(str(level), n) for level, n in rows if n >= min_count]
    n_hidden_levels = len(rows) - len(shown)
    n_hidden = sum(n for _, n in rows if n < min_count)
    while shown and 0 < n_hidden < min_count:
        n_hidden += shown.pop()[1]
        n_hidden_levels += 1
    return dict(shown), n_hidden_levels


def _kind(series: pl.Series, n_unique: int) -> str:
    dtype = series.dtype
    if _is_id_like(series.name):
        return "id"
    if dtype == pl.Boolean:
        return "boolean"
    if dtype.is_numeric():
        return "numeric"
    if dtype == pl.Duration:
        return "duration"
    if dtype == pl.Date or isinstance(dtype, pl.Datetime):
        return "date_of_birth" if _BIRTH_DATE.search(series.name) else "datetime"
    if dtype in (pl.String, pl.Categorical) or isinstance(dtype, pl.Enum):
        return "categorical" if n_unique <= MAX_LEVELS else "free_text"
    if isinstance(dtype, pl.Struct):
        return "struct"
    return "other"


[docs] def summarise_column( series: pl.Series, *, min_count: int = DEFAULT_MIN_COUNT ) -> dict[str, Any]: """Describe one column without any patient-level value. Args: series (pl.Series): The column. min_count (int): Smallest count published. Returns: dict[str, Any]: ``dtype``, ``kind``, ``n``, ``pct_missing``, ``n_unique`` and, by kind: - numeric: ``quantiles``, or ``levels`` + ``n_levels_suppressed`` when it has at most ``MAX_NUMERIC_LEVELS`` distinct values; - duration: ``quantiles_hours``; - categorical, boolean: ``levels`` + ``n_levels_suppressed``; - datetime: ``quantiles_month`` (``"YYYY-MM"``) and ``years`` + ``n_years_suppressed``; - struct: ``fields``; - id, date_of_birth, free_text, other: nothing more. """ n = series.len() n_missing = series.null_count() n_unique = series.drop_nulls().n_unique() if n > n_missing else 0 kind = _kind(series, n_unique) entry: dict[str, Any] = { "dtype": str(series.dtype), "kind": kind, "n": n, "pct_missing": round(100 * n_missing / n, 1) if n else None, "n_unique": n_unique, } if kind == "numeric" and n_unique <= MAX_NUMERIC_LEVELS: entry["levels"], entry["n_levels_suppressed"] = _counts(series, min_count) elif kind == "numeric": entry["quantiles"] = _quantiles(series, min_count) elif kind == "duration": hours = series.dt.total_seconds() / 3600 entry["quantiles_hours"] = _quantiles(hours, min_count) elif kind in ("categorical", "boolean"): entry["levels"], entry["n_levels_suppressed"] = _counts(series, min_count) elif kind == "datetime": entry["quantiles_month"] = _month_quantiles(series, min_count) years, entry["n_years_suppressed"] = _counts(series.dt.year(), min_count) entry["years"] = dict(sorted(years.items())) elif kind == "struct": entry["fields"] = { field: summarise_column(series.struct.field(field), min_count=min_count) for field in series.struct.fields } return entry
def _rows_per_observation( frame: pl.DataFrame, obs_keys: pl.Series, primary_key: str, min_count: int ) -> dict[str, Any]: per_key = frame.group_by(primary_key).len() return { "n_with_rows": per_key.height, "pct_with_rows": ( round(100 * per_key.height / obs_keys.len(), 1) if obs_keys.len() else None ), "quantiles": _quantiles(per_key["len"], min_count), } def _hours_from_anchor( frame: pl.DataFrame, obs: pl.DataFrame, primary_key: str, anchor: str, min_count: int, ) -> dict[str, float] | None: if "recordtime" not in frame.columns or anchor not in obs.columns: return None joined = frame.select(primary_key, "recordtime").join( obs.select(primary_key, anchor), on=primary_key, how="inner" ) hours = (joined["recordtime"] - joined[anchor]).dt.total_seconds() / 3600 return _quantiles(hours, min_count)
[docs] def summarise_frame( frame: pl.DataFrame, obs: pl.DataFrame, *, primary_key: str, anchor: str, min_count: int = DEFAULT_MIN_COUNT, ) -> dict[str, Any]: """Describe one ``obsm`` frame. Args: frame (pl.DataFrame): The time-series frame. obs (pl.DataFrame): The cohort's ``obs`` (for the keys and the anchor). primary_key (str): Primary key column. anchor (str): ``obs`` column the record times are measured from. min_count (int): Smallest count published. Returns: dict[str, Any]: Columns and dtypes, rows per observation, hours from the anchor and summaries of ``value`` and ``value_unit``, all counted over the rows whose `primary_key` is in `obs` (``obsm`` can still hold rows of observations excluded after extraction). """ if primary_key in frame.columns: frame = frame.join(obs.select(primary_key).unique(), on=primary_key, how="semi") entry: dict[str, Any] = { "n_rows": frame.height, "columns": {name: str(dtype) for name, dtype in frame.schema.items()}, "rows_per_observation": _rows_per_observation( frame, obs[primary_key], primary_key, min_count ), "anchor": anchor, "hours_from_anchor": _hours_from_anchor( frame, obs, primary_key, anchor, min_count ), } for column in ("value", "value_unit"): if column in frame.columns: entry[column] = summarise_column(frame[column], min_count=min_count) return entry
[docs] def build_codebook( obs: pl.DataFrame, obsm: Mapping[str, pl.DataFrame], *, primary_key: str, anchor: str, min_count: int = DEFAULT_MIN_COUNT, concept_versions: Mapping[str, Any] | None = None, ) -> dict[str, Any]: """Build the codebook of a cohort's ``obs`` and ``obsm``. Args: obs (pl.DataFrame): One row per observation. obsm (Mapping[str, pl.DataFrame]): Time-series frames by variable. primary_key (str): Primary key column of `obs`. anchor (str): ``obs`` column the ``obsm`` record times are measured from. min_count (int): Smallest count published. concept_versions (Mapping[str, Any] | None): ``Cohort.concept_versions``; each variable's concept, source and version are copied in. Returns: dict[str, Any]: ``{"min_count", "n_observations", "obs", "obsm"}``. """ versions = concept_versions or {} def provenance(name: str) -> list[dict[str, Any]] | None: records = versions.get(name) if not records: return None keys = ("source", "taxonomy", "name", "concept_id", "version") return [{k: r.get(k) for k in keys if k in r} for r in records] obs_entries = {} for name in obs.columns: obs_entries[name] = summarise_column(obs[name], min_count=min_count) if (concept := provenance(name)) is not None: obs_entries[name]["concept"] = concept obsm_entries = {} for name, frame in obsm.items(): obsm_entries[name] = summarise_frame( frame, obs, primary_key=primary_key, anchor=anchor, min_count=min_count ) if (concept := provenance(name)) is not None: obsm_entries[name]["concept"] = concept return { "min_count": min_count, "primary_key": primary_key, "n_observations": obs.height, "obs": obs_entries, "obsm": obsm_entries, }
def _fmt(value: Any) -> str: if value is None: return "" if isinstance(value, float): return f"{value:.4g}" return str(value) def _fmt_quantiles(quantiles: Mapping[str, Any] | None) -> str: if not quantiles: return "" return " / ".join(f"{label} {_fmt(v)}" for label, v in quantiles.items()) def _fmt_counts( counts: Mapping[str, int], n_suppressed: int, noun: str = "level", limit: int = 12 ) -> str: shown = [f"{level}: {n}" for level, n in counts.items()] text = ", ".join(shown[:limit]) if len(shown) > limit: text += f", … ({len(shown) - limit} more)" if n_suppressed: plural = "" if n_suppressed == 1 else "s" text += f" ({n_suppressed} {noun}{plural} suppressed)" return text.strip() def _describe(entry: Mapping[str, Any]) -> str: if "quantiles" in entry: return _fmt_quantiles(entry["quantiles"]) if "quantiles_hours" in entry: return f"hours: {_fmt_quantiles(entry['quantiles_hours'])}" if "levels" in entry: return _fmt_counts(entry["levels"], entry.get("n_levels_suppressed", 0)) if "quantiles_month" in entry: parts = [] if entry["quantiles_month"]: parts.append(f"months: {_fmt_quantiles(entry['quantiles_month'])}") years = _fmt_counts(entry["years"], entry["n_years_suppressed"], "year") if years: parts.append(f"years: {years}") return "; ".join(parts) return "" def _obs_rows(name: str, entry: Mapping[str, Any]) -> list[str]: row = ( f"| `{name}` | {entry['dtype']} | {entry['kind']} | {entry['n']} | " f"{_fmt(entry['pct_missing'])} | {entry['n_unique']} | {_describe(entry)} |" ) rows = [row.replace("\n", " ")] for field, sub in (entry.get("fields") or {}).items(): rows.extend(_obs_rows(f"{name}.{field}", sub)) return rows
[docs] def codebook_markdown(codebook: Mapping[str, Any]) -> str: """Render a codebook as Markdown, for people and coding agents. Args: codebook (Mapping[str, Any]): A result of :func:`build_codebook`. Returns: str: The Markdown document. """ k = codebook["min_count"] lines = [ "# Codebook", "", ( f"{codebook['n_observations']} observations (`{codebook['primary_key']}`). " f"No patient-level values: counts below {k} are suppressed (level names " f"too), percentiles (p1 … p99, nearest rank) are shown only with at least " f"{k} values on each side, datetimes as the month of those percentiles " "and counts per year, dates of birth not at all. obsm frames count only " "rows of observations in obs." ), "", "## obs", "", "| column | dtype | kind | n | % missing | n unique | distribution |", "|---|---|---|---|---|---|---|", ] for name, entry in codebook["obs"].items(): lines.extend(_obs_rows(name, entry)) lines += ["", "## obsm", ""] for name, entry in codebook["obsm"].items(): rows = entry["rows_per_observation"] lines += [ f"### `{name}`", "", ( f"- rows: {entry['n_rows']}, observations with rows: " f"{rows['n_with_rows']} ({_fmt(rows['pct_with_rows'])} %), rows per " f"observation: {_fmt_quantiles(rows['quantiles'])}" ), ( f"- hours from `{entry['anchor']}`: " f"{_fmt_quantiles(entry['hours_from_anchor'])}" ), "- columns: " + ", ".join(f"`{c}` {t}" for c, t in entry["columns"].items()), ] for column in ("value", "value_unit"): if column in entry: lines.append(f"- {column}: {_describe(entry[column])}") if "concept" in entry: lines.append(f"- concept: {json.dumps(entry['concept'], default=str)}") lines.append("") return "\n".join(lines).rstrip() + "\n"
[docs] def write_codebook( codebook: Mapping[str, Any], output_dir: str | PathLike[str] ) -> tuple[Path, Path]: """Write ``codebook.md`` and ``codebook.json`` into `output_dir`. Args: codebook (Mapping[str, Any]): A result of :func:`build_codebook`. output_dir (str | PathLike[str]): Target directory, created if missing. Returns: tuple[Path, Path]: The Markdown and JSON paths. """ out = Path(output_dir) out.mkdir(parents=True, exist_ok=True) md_path, json_path = out / "codebook.md", out / "codebook.json" md_path.write_text(codebook_markdown(codebook), encoding="utf-8") json_path.write_text(json.dumps(codebook, indent=2, default=str), encoding="utf-8") return md_path, json_path