Skip to contents

The cohort engine, comorbidity profiling, measurement sanitisation, readmission cohorts, temporal features, concept rollups, Table 1 and benchmark reconciliation.

Code blocks on this page are illustrative and are not run when the package is built. R and Python examples are labelled; a feature marked “Python only” has no R counterpart.

The package provides an end-to-end epidemiological pipeline for observational studies, featuring flexible index stay definition, validated comorbidity profiling, physiologic range sanitization, Athena concept hierarchy rollups, LOINC laboratory consolidation, and publication Table 1 generation.

1. Unified Study Cohort Engine (define_study_cohort)

Generalizes acute inpatient, emergency department, and outpatient index cohorts with customizable wash-in windows, right-censoring verification, and outcome definitions:

library(omopduckdb)

con <- DBI::dbConnect(duckdb::duckdb(), "omop_cdm.duckdb")

# Build general study cohort (or specialized build_readmission_cohort / build_end_of_life_cohort)
cohort_df <- define_study_cohort(
  con,
  visit_type = "inpatient",
  washin_days = 365,
  followup_days = 30,
  min_age = 18,
  min_los_days = 1,
  sampling_rule = "first",
  require_verified_followup = TRUE,
  table_name = "cohort"
)

In Python:

from omop_etl import define_study_cohort

cohort_df = define_study_cohort(
    con,
    visit_type="inpatient",
    washin_days=365,
    followup_days=30,
    min_age=18,
    min_los_days=1,
    sampling_rule="first",
    require_verified_followup=True,
    table_name="cohort"
)

2. Comorbidity Profiling: 31 Elixhauser Domains & Charlson Index

Computes validated comorbidity profiles in one set-based DuckDB query over the cohort with zero object leakage on read-only connections. Automatically evaluates both ICD-9/10 prefixes (condition_source_value) and SNOMED descendants (condition_concept_id):

# Extract 31 Elixhauser domains + composite van Walraven score
elix_df <- extract_elixhauser_comorbidities(con, cohort_table = "cohort", lookback_days = 365)

# Extract 17 Quan-Charlson categories + Charlson Comorbidity Index
cci_df <- extract_charlson_index(con, cohort_table = "cohort", lookback_days = 365)

In Python:

from omop_etl import extract_elixhauser_comorbidities, extract_charlson_index

elix_df = extract_elixhauser_comorbidities(con, cohort_table="cohort", lookback_days=365)
cci_df = extract_charlson_index(con, cohort_table="cohort", lookback_days=365)

3. Physiologic Measurement Sanitization & Outlier Winsorization (sanitize_measurements)

Cleans laboratory and vital measurements against 136 standard OHDSI DataQualityDashboard biological plausibility limits or statistical IQR/z-score winsorization:

# Clamps out-of-bounds measurements to DQD biological plausibility limits
clean_labs <- sanitize_measurements(
  con,
  method = "dqd_biologic_limits",
  action = "clamp"
)

In Python:

from omop_etl import sanitize_measurements

clean_labs = sanitize_measurements(
    con,
    method="dqd_biologic_limits",
    action="clamp"
)

4. Build Inpatient Readmission Cohort (build_readmission_cohort)

Constructs index inpatient stays (visit_concept_id = 9201) among adult patients (≥18\ge 18) with length of stay ≥1\ge 1 day, discharged alive, and verified 30-day follow-up (requiring either a readmission or confirmed clinical contact ≥30\ge 30 days post-discharge to prevent right-censoring):

library(omopduckdb)

con <- DBI::dbConnect(duckdb::duckdb(), "omop_cdm.duckdb")

# Build cohort into OMOP cohort table (cohort_definition_id = 1)
cohort_df <- build_readmission_cohort(
  con,
  washin_days = 365,
  followup_window_days = 30,
  index_selection_rule = "random",
  random_state = 42,
  require_verified_followup = TRUE,
  table_name = "cohort"
)

In Python:

import duckdb
from omop_etl import build_readmission_cohort

con = duckdb.connect("omop_cdm.duckdb")
cohort_df = build_readmission_cohort(
    con,
    washin_days=365,
    followup_window_days=30,
    index_selection_rule="random",
    random_state=42,
    require_verified_followup=True,
    table_name="cohort"
)

5. Extract Temporal Utilization & Demographic Features

Aggregates windowed baseline healthcare utilization (IP, ED, OP encounter counts, days since prior visit, prior 30-day readmissions in lookback), index length of stay, discharge disposition, and demographics:

temporal_features <- extract_temporal_features(
  con,
  cohort_table = "cohort",
  cohort_id = 1,
  lookback_days = 365
)

In Python:

from omop_etl import extract_temporal_features

temporal_features = extract_temporal_features(
    con,
    cohort_table="cohort",
    cohort_id=1,
    lookback_days=365
)

6. Athena Concept Hierarchy Rollup & Consolidated Measurements

Traverse Athena’s concept_ancestor table to aggregate medication or condition classes, and extract consolidated lab panels and physical vitals using acute pre-discharge aggregation strategies:

# Aggregate medication exposure using Athena ancestor traversal
med_features <- aggregate_concept_sets(
  con,
  cohort_table = "cohort",
  cohort_id = 1,
  domain = "drug",
  concept_sets = DEFAULT_MEDICATION_CONCEPTS,
  lookback_days = 365
)

# Extract acute pre-discharge laboratory and vital measurements
lab_features <- extract_measurements(
  con,
  cohort_table = "cohort",
  cohort_id = 1,
  loinc_map = DEFAULT_LAB_LOINCS,
  strategy = "last_before_discharge"
)

In Python:

from omop_etl import (
    aggregate_concept_sets,
    extract_measurements,
    DEFAULT_MEDICATION_CONCEPTS,
    DEFAULT_LAB_LOINCS
)

med_features = aggregate_concept_sets(
    con,
    cohort_table="cohort",
    cohort_id=1,
    domain="drug",
    concept_sets=DEFAULT_MEDICATION_CONCEPTS,
    lookback_days=365
)

lab_features = extract_measurements(
    con,
    cohort_table="cohort",
    cohort_id=1,
    loinc_map=DEFAULT_LAB_LOINCS,
    strategy="last_before_discharge"
)

7. Stratified Table 1 Generation & Completeness Matrix

Generates baseline descriptive tables (continuous: Mean +/- SD, Median IQRIQR; categorical: N %) stratified by outcome (e.g., readmitted_30d), calculating Standardized Mean Differences (SMD) and statistical tests, along with a Table 1b completeness audit:

table1_out <- generate_table1(
  patient_df,
  strata_col = "readmitted_30d",
  continuous_vars = c("age_at_admission", "los_days", "prior_ed_visits"),
  categorical_vars = c("gender", "race", "tobacco_status")
)

# Baseline summary with SMD and p-values
print(table1_out$table1)

# Missingness and completeness audit
print(table1_out$table1b)

In Python:

from omop_etl import generate_table1

res = generate_table1(
    patient_df,
    strata_col="readmitted_30d",
    continuous_vars=["age_at_admission", "los_days", "prior_ed_visits"],
    categorical_vars=["gender", "race", "tobacco_status"]
)
t1_df, t1b_df = res["table1"], res["table1b"]

8. Benchmark Reconciliation & Validation Harness

Validates prospective OMOP Table 1 statistics against benchmark datasets with configurable absolute tolerance thresholds, flagging distribution drift and missing features:

reconciliation <- validate_table1_reconciliation(
  omop_table1 = table1_out$table1,
  source_table1 = benchmark_table1,
  tolerance = 0.05
)

if (!isTRUE(reconciliation$is_concordant)) {
  warning("Table 1 discrepancy detected!")
  print(reconciliation$feature_comparisons)
}

In Python:

from omop_etl import validate_table1_reconciliation

reconciliation = validate_table1_reconciliation(
    omop_table1=t1_df,
    source_table1=benchmark_table1,
    tolerance=0.05
)
print("Reconciliation passed:", reconciliation["is_concordant"])

Portable eDERRI cohort definitions (FR-D1, FR-D2)

Files in inst/cohorts/:

File Purpose
target_cohort.sql Adult IP and ED-to-IP index stays, one per patient (OHDSI SQL / SqlRender)
outcome_cohort.sql Inpatient admissions (outcome events)
*.circe.json ATLAS/Circe versions (see caveat below)
metformin_only_prediabetes_pcos_{icd10,snomed,both}.circe.json Patients with prediabetes or PCOS whose only diabetes drug is metformin and who never had a diabetes diagnosis (patient-level exclusion; the PCOS concept set differs per file). Generated by omop_etl.circe_definitions; tested against find_metformin_only_prediabetes_pcos()
diabetes_phenotype.circe.json Adult with a diabetes diagnosis, a diabetes drug (ATC A10) or HbA1c >= 6.5 (the SAS extraction’s rule)
run_plp_example.R SqlRender render + translate, then PatientLevelPrediction::runPlp() (writes main.cohort; needs a writable CDM)
run_plp_readonly_example.R Same on a read-only CDM: attached READ_ONLY, cohort rows written to a scratch DuckDB
omopduckdb::cohort_definition_set() CohortGenerator cohortDefinitionSet (cohortId, cohortName, sql, json)

Parameters

Both SQL files use CohortGenerator’s names: @cdm_database_schema, @target_database_schema, @target_cohort_table, @target_cohort_id. The target cohort also takes @followup_days (30) and @min_age (18); cohort_definition_set() renders those two into the SQL so CohortGenerator::generateCohortSet() only has to fill the four above. The SQL creates no inclusion-rule statistics tables, so always pass generateStats = FALSE; the default fails. (v0.8.2 used cohort_database_schema, cohort_table and outcome_cohort_id; rename them in your own calls.)

Target cohort

  1. Index stay: visit_concept_id 9201 (Inpatient) or 262 (ER and Inpatient) with a discharge (visit_end_date).
  2. Adult: YEAR(discharge) - year_of_birth >= 18 (@min_age).
  3. Discharge exclusions: discharged_to_concept_id = 4216643 (Patient died), or any death record on or before discharge.
  4. Verified follow-up: an observation_period covering discharge through discharge + 30 days (@followup_days), or death inside that window. Sites with real enrolment windows (N3): with build_observation_period(use_enrollment = TRUE) / etl_pcornet(use_enrollment=) the periods are the enrolment spans, so this rule requires continuous enrolment for the whole window and drops patients who leave early. With event-span periods (the default for sources without an ENROLLMENT file) the period ends at the last event, so the rule is nearly always true when any record follows discharge. The two give the same answer only when periods are event spans. Compare them on your data with @followup_evidence = 'observation_period_or_event' (also accepts a later record) or compare_cohort_definitions() before trusting a count across sites. On the consortium data (event-span periods) the two differed for 27 of 59,117 readmissions.
  5. One index per patient (FR-D2): the earliest qualifying stay, ties broken by the lowest visit_occurrence_id. No random number generator, so every engine and rebuild picks the same stay.
  6. Cohort start = cohort end = discharge date.

Outcome cohort

Every IP/ED-to-IP admission, start = admission date, end = discharge date. A 30-day readmission is the first outcome in (cohort_start_date + 1, cohort_start_date + 30]; set this with createStudyPopulationSettings(riskWindowStart = 1, riskWindowEnd = 30, startAnchor = "cohort start", endAnchor = "cohort start").

Relation to define_study_cohort()

define_study_cohort(sampling_rule="earliest") selects the same index stay (earliest start, lowest id), but also applies its own wash-in, minimum stay length and evidence rules; the SQL above does not, so counts differ unless those are switched off. sampling_rule="random" uses DuckDB hash(), which is not stable across DuckDB versions; use "earliest" or "stable_random" (MD5-based) for results that must reproduce across versions, and persist_index_visits(con) to freeze the chosen stays in an index_visit table.

Verification status

  • tests/test_v082_features.py renders the SQL, translates it with sqlglot (T-SQL to DuckDB) and checks the cohorts on a fixture on DuckDB.
  • v0.8.3: the SQL also runs with the CDM attached READ_ONLY and the cohort table in a separate database (tested on DuckDB).
  • Verified on servers (v0.8.5): the live-db workflow runs both files, translated with sqlglot, on PostgreSQL 16 and SQL Server 2022 and gets the DuckDB cohorts. Not verified: execution on Oracle (use SqlRender::translate(..., targetDialect = "oracle"), never sqlglot, which renders DATEADD wrongly for Oracle), and translation by SqlRender itself (sqlglot stands in for it).
  • readonly_connect_wrapper() (the DatabaseConnector::connect wrapper used by run_plp_readonly_example.R) is tested against a real read-only DuckDB file. Patching DatabaseConnector::connect with HADES running on top, and cohort_definition_set() with SqlRender, are not covered by the Python tests; tests/testthat/test-cohortgenerator-integration.R runs CohortGenerator when it is installed.
  • tests/test_v082_features.py checks the Circe JSON structurally and against the SQL (same visit concepts, age and follow-up defaults, and that the JSON carries the documented rule-3 gap). That is a consistency test, not an ATLAS import.
  • The SQL is authoritative; the Circe JSON is not a verified equivalent (FR-D5). The JSON was written by hand. scripts/atlas/import_circe.py imports it into ATLAS WebAPI 2.14/2.15, reads it back and renders SQL from it, but ATLAS cannot generate cohorts on a DuckDB CDM (WebAPI rejects the dialect), so the cohort an ATLAS user builds from it has never been compared with the SQL’s cohort. Circe cannot test discharged_to_concept_id (4216643, died), so an ATLAS-built cohort keeps patients who died on the index visit; the SQL is authoritative. DateAdjustment (start at visit end) needs Circe/ATLAS 2.12 or later.