
Study-design features: add your own person-level features to an OMOP study
Source:vignettes/study_features.Rmd
study_features.RmdThe OMOP CDM does not define everything a protocol needs. An area deprivation index, the rural-urban code of the home ZIP, the median household income of the census tract, a site’s own comorbidity score: none of these is a standard concept, so the OHDSI tools (FeatureExtraction, PatientLevelPrediction, DeepPatientLevelPrediction) cannot see them.
A study-design feature is such a feature.
omopduckdb ships a small framework, not a data set:
| You write | The package does |
|---|---|
a study_feature() (or a built-in:
ruca_feature(), sdi_feature(),
area_feature(), sql_feature(),
custom_feature()) |
resolves the address in effect at admission once, computes every feature for the index stays, keeps the fitted state |
a feature_set() you extend with
add_feature()
|
writes the values as measurement rows under
site-defined concepts and builds the FeatureExtraction covariate
settings |
| the reference table (ACS income, RUCA, SDI) | never bundles it: you supply it, the package only does the join, the transform and the missingness handling |
The same API exists in Python (omop_etl.study_features),
and the manifest and fitted state are interchangeable between the
two.
A small synthetic CDM
Six patients with a dated address history and one inpatient stay each. Everything below is synthetic.
db_path <- tempfile(fileext = ".duckdb")
build_schema(db_path)
#> duckdb keeps downloaded extensions and secrets in a temporary directory:
#> ℹ /tmp/Rtmp8CWD6i/duckdb
#> This is removed when the R session ends.
#> • Extensions are re-downloaded each session.
#> • Secrets are lost.
#> ℹ Run duckdb(shared_home = TRUE) (or create ~/.duckdb) to keep them (suitable for most users).
#> ℹ Run duckdb(shared_home = FALSE) to accept the temporary directory (and silence this message).
#> ℹ See ?duckdb_storage for details and alternatives.
#> Schema built at /tmp/Rtmp8CWD6i/file391766968c7.duckdb
con <- DBI::dbConnect(duckdb::duckdb(), dbdir = db_path)
#> duckdb keeps downloaded extensions and secrets in a temporary directory:
#> ℹ /tmp/Rtmp8CWD6i/duckdb
#> This is removed when the R session ends.
#> • Extensions are re-downloaded each session.
#> • Secrets are lost.
#> ℹ Run duckdb(shared_home = TRUE) (or create ~/.duckdb) to keep them (suitable for most users).
#> ℹ Run duckdb(shared_home = FALSE) to accept the temporary directory (and silence this message).
#> ℹ See ?duckdb_storage for details and alternatives.
zips <- c("19104", "15213", "08101", "17821", "19104", "99999") # 99999 is in no reference table
for (i in 1:6) {
DBI::dbExecute(con, sprintf("INSERT INTO person (person_id, gender_concept_id, year_of_birth, race_concept_id, ethnicity_concept_id)
VALUES (%d, 8507, 1960, 0, 0)", i))
DBI::dbExecute(con, sprintf("INSERT INTO visit_occurrence (visit_occurrence_id, person_id, visit_concept_id, visit_start_date,
visit_end_date, visit_type_concept_id) VALUES (%d, %d, 9201, DATE '2018-0%d-10', DATE '2018-0%d-14', 0)",
i, i, i, i))
}
DBI::dbExecute(con, "CREATE TABLE person_address_history (person_id BIGINT, location_id BIGINT, zip5 VARCHAR,
address_start DATE, address_end DATE, preferred VARCHAR)")
#> [1] 0
for (i in 1:6) DBI::dbExecute(con, sprintf("INSERT INTO person_address_history VALUES (%d, %d, '%s', DATE '2010-01-01', NULL, 'Y')", i, i, zips[i]))The reference tables are plain data frames (or CSV paths). The column names are matched case-insensitively.
ruca <- data.frame(ZIPCODE = c("19104", "15213", "08101", "17821"), RUCA_CODE = c("1", "2.1", "4", "99"))
sdi <- data.frame(ZCTA5_FIPS = c("19104", "15213", "08101", "17821"), SDI_score = c(95, 40, 10, 70))
income <- data.frame(zcta = c("19104", "15213", "08101", "17821"), median_income = c(31000, 88000, 61000, 54000))
sdi_cuts <- c(20, 45, 65, 85) # the training cohort's fixed SDI cut pointsBuild a feature set
A feature set is extended one feature at a time, so a study can start with geography and add features later.
fs <- feature_set() |>
add_feature(ruca_feature(ruca)) |>
add_feature(sdi_feature(sdi, cut_points = sdi_cuts))
fs
#> <feature_set> 2 feature(s): ruca, sdi
feature_set_columns(fs)
#> [1] "ruca_code" "ruca_group" "sdi_score" "sdi_quintile"area_feature() turns any ZIP-keyed number into
a feature. Median household income is right-skewed, so use
log1p; a percentile transform instead puts
every site on the training distribution (see “Across sites” below).
add_feature(fs, area_feature("income", income, "median_income", transform = "log1p"))
feature_set_columns(fs)
#> [1] "ruca_code" "ruca_group" "sdi_score" "sdi_quintile"
#> [5] "income" "income_missing"Compute for the index stays
stays_from_cohort() turns a cohort table into the index
stays; here we use every inpatient visit (the default).
wide <- compute_features(fs, con)
wide[order(wide$stay_id), ]
#> person_id stay_id admit_date ruca_code ruca_group sdi_score sdi_quintile
#> 1 1 1 2018-01-10 1 1 95 5
#> 2 2 2 2018-02-10 2 2 40 2
#> 3 3 3 2018-03-10 4 3 10 1
#> 4 4 4 2018-04-10 99 NA 70 4
#> 5 5 5 2018-05-10 1 1 95 5
#> 6 6 6 2018-06-10 NA NA NA NA
#> income income_missing
#> 1 10.34177 0
#> 2 11.38510 0
#> 3 11.01865 0
#> 4 10.89676 0
#> 5 10.34177 0
#> 6 NA 1- The address is the one in effect at admission (the
rule of
derive_geography_features()), never a later one. - A ZIP missing from a table gives
NAandincome_missing = 1(patient 6); turn the indicator off withmissing_indicator = FALSEor fill with the training median usingimpute = TRUE. - RUCA 99 (“not coded”) lands in small town / rural as in the
reference study; pass
code_99_missing = TRUEto treat it as unknown.
Make it visible to OHDSI tools
write_feature_set() stores each value as a
measurement row dated the admission date, under a
site-defined concept (>= 2,000,000,000). SDI and RUCA keep the ids of
GEOGRAPHY_CONCEPT_IDS, so earlier work stays compatible;
everything else is registered for you.
concepts <- write_feature_set(fs, con, wide)
format(vapply(concepts, function(x) as.numeric(x[[1]]), numeric(1)), scientific = FALSE)
#> ruca_code sdi_score sdi_quintile ruca_group income
#> "2000100003" "2000100001" "2000100002" "2001000000" "2001000001"
#> income_missing
#> "2001000002"
cat(feature_set_extraction_r(fs, concepts))
#> covariateSettings <- FeatureExtraction::createCovariateSettings(
#> useMeasurementValueLongTerm = TRUE,
#> longTermStartDays = -365, endDays = 0,
#> includedCovariateConceptIds = c(2000100003, 2001000000, 2000100001, 2000100002, 2001000001, 2001000002)) # ruca_code, ruca_group, sdi_score, sdi_quintile, income, income_missingfeature_set_covariate_settings(fs, concepts) returns the
same thing as a real FeatureExtraction object:
DBI::dbExecute(con, "DROP TABLE IF EXISTS cohort")
#> [1] 0
DBI::dbExecute(con, "CREATE TABLE cohort (cohort_definition_id INT, subject_id BIGINT, cohort_start_date DATE, cohort_end_date DATE)")
#> [1] 0
DBI::dbExecute(con, "INSERT INTO cohort SELECT 1, person_id, visit_start_date, visit_end_date FROM visit_occurrence")
#> [1] 6
DBI::dbDisconnect(con, shutdown = TRUE)
conn <- DatabaseConnector::connect(DatabaseConnector::createConnectionDetails(dbms = "duckdb", server = db_path))
#> Connecting using DuckDB driver
#> duckdb keeps downloaded extensions and secrets in a temporary directory:
#> ℹ /tmp/Rtmp8CWD6i/duckdb
#> This is removed when the R session ends.
#> • Extensions are re-downloaded each session.
#> • Secrets are lost.
#> ℹ Run duckdb(shared_home = TRUE) (or create ~/.duckdb) to keep them (suitable for most users).
#> ℹ Run duckdb(shared_home = FALSE) to accept the temporary directory (and silence this message).
#> ℹ See ?duckdb_storage for details and alternatives.
#> Warning in connectDuckdb(connectionDetails): The ICU extension of DuckDB is not
#> installed. Attempting to install it.
#> | | | 0% | |======================================================================| 100%
#> Executing SQL took 0.324 secs
#> | | | 0% | |======================================================================| 100%
#> Executing SQL took 0.0425 secs
cov <- FeatureExtraction::getDbCovariateData(
connection = conn, cdmDatabaseSchema = "main", cohortTable = "cohort", cohortDatabaseSchema = "main",
cohortIds = 1, rowIdField = "subject_id", aggregated = FALSE,
covariateSettings = feature_set_covariate_settings(fs, concepts))
#> Sending temp tables to server
#> Inserting data took 0.0879 secs
#> Constructing features on server
#> | | | 0% | |==== | 6% | |========= | 12% | |============= | 19% | |================== | 25% | |====================== | 31% | |========================== | 38% | |=============================== | 44% | |=================================== | 50% | |======================================= | 56% | |============================================ | 62% | |================================================ | 69% | |==================================================== | 75% | |========================================================= | 81% | |============================================================= | 88% | |================================================================== | 94% | |======================================================================| 100%
#> Executing SQL took 0.0435 secs
#> Fetching data from server
#> duckdb keeps downloaded extensions and secrets in a temporary directory:
#> ℹ /tmp/Rtmp8CWD6i/duckdb
#> This is removed when the R session ends.
#> • Extensions are re-downloaded each session.
#> • Secrets are lost.
#> ℹ Run duckdb(shared_home = TRUE) (or create ~/.duckdb) to keep them (suitable for most users).
#> ℹ Run duckdb(shared_home = FALSE) to accept the temporary directory (and silence this message).
#> ℹ See ?duckdb_storage for details and alternatives.
#> Fetching data took 0.47 secs
DatabaseConnector::disconnect(conn)
head(as.data.frame(cov$covariateRef)[, c("covariateId", "covariateName")])
#> covariateId
#> 1 2.0001e+15
#> 2 2.0001e+15
#> 3 2.0001e+15
#> 4 2.0010e+15
#> 5 2.0010e+15
#> 6 2.0010e+15
#> covariateName
#> 1 measurement value during day -365 through 0 days relative to index: RUCA primary code of the residence ZIP at admission ()
#> 2 measurement value during day -365 through 0 days relative to index: SDI score of the residence ZIP at admission ()
#> 3 measurement value during day -365 through 0 days relative to index: SDI quintile (1 least to 5 most deprived) at admission ()
#> 4 measurement value during day -365 through 0 days relative to index: RUCA group (1 metro, 2 micro, 3 small town/rural) at admission ()
#> 5 measurement value during day -365 through 0 days relative to index: income (log1p) of the residence ZIP at admission ()
#> 6 measurement value during day -365 through 0 days relative to index: income unavailable (1 = ZIP not in the area table) ()From there the covariates feed PatientLevelPrediction exactly like
any other FeatureExtraction output. SQL-defined or custom-R
features (below) take the same path.
Your own feature
Three ways, from least to most code:
# 1. A SQL query over the OMOP tables, reading the view `_stays` (person_id, stay_id, admit_date)
prior_ed <- sql_feature("n_prior_ed", "
SELECT s.stay_id, CAST(count(*) AS DOUBLE) AS n_prior_ed
FROM _stays s JOIN visit_occurrence v
ON v.person_id = s.person_id AND v.visit_concept_id = 9203 AND v.visit_start_date < s.admit_date
GROUP BY 1", columns = "n_prior_ed")
# 2. Your own R function: fn(con, stays) -> stay_id + the numeric columns
frailty <- custom_feature("frailty", "frailty_index", function(con, stays) my_frailty_index(con, stays))
# 3. A complete study_feature() with fitted state, requirements and concept ids (see ?study_feature)The contract is the author’s: a feature may only use data dated before the index date (or during the stay when the protocol says so). Nothing in the framework reads events after discharge.
The same API in Python
These examples are illustrative and are not run when the package is built.
omop_etl.study_features is the Python twin of the R API
described above. Names map one to one (add_feature is
FeatureSet.add, compute_features is
FeatureSet.compute, write_feature_set is
FeatureSet.write, …), the manifest format is the same, and
fitted state moves freely between the languages: fit in Python, apply in
R, or the other way.
Build, compute, write
import duckdb, pandas as pd
from omop_etl import FeatureSet, ruca_feature, sdi_feature, area_feature, stays_from_cohort
con = duckdb.connect("omop.duckdb")
fs = (FeatureSet()
.add(ruca_feature("ruca_crosswalk.csv"))
.add(sdi_feature("sdi.csv", cut_points=[20.8, 40.6, 60.4, 80.2])) # the training cohort's fixed cuts
.add(area_feature("income", "acs_b19013.csv", "median_income", transform="log1p")))
stays = stays_from_cohort(con, "cohort") # person_id, stay_id, admit_date (cohort order)
wide = fs.compute(con, stays) # one row per stay, input order
concepts = fs.write(con, wide) # measurement rows under site-defined concepts
print(fs.feature_extraction_r(concepts)) # the FeatureExtraction covariate settings, as R codefs.compute returns the fitted state in
wide.attrs["feature_state"] and the manifest in
wide.attrs["feature_provenance"].
Fit once, apply everywhere
fs_train = FeatureSet([sdi_feature("sdi.csv"),
area_feature("income", "acs_b19013.csv", "median_income", transform="percentile", impute=True)])
fs_train.compute(con_train, stays_train, fit=True) # learns cut points, percentile grid, median fill
fs_train.export_manifest("study_features.json")
fs_site = FeatureSet([sdi_feature("sdi.csv"),
area_feature("income", "acs_b19013.csv", "median_income", transform="percentile", impute=True)])
fs_site.load_state("study_features.json") # no local fitting; without it the transforms raise
site = fs_site.compute(con_site, stays_site)Your own features in Python
from omop_etl import sql_feature, custom_feature
prior_ed = sql_feature("n_prior_ed", """
SELECT s.stay_id, count(*)::DOUBLE AS n_prior_ed
FROM _stays s JOIN visit_occurrence v
ON v.person_id = s.person_id AND v.visit_concept_id = 9203 AND v.visit_start_date < s.admit_date
GROUP BY 1""", ["n_prior_ed"])
frailty = custom_feature("frailty", ["frailty_index"], lambda con, stays: my_frailty(con, stays))
fs.add(prior_ed).add(frailty)A package or a study can also register a whole kind of feature and name lists of them:
from omop_etl.study_features import register_feature_factory, FEATURE_LISTS, feature_list
register_feature_factory("frailty", frailty_factory)
FEATURE_LISTS["my_protocol"] = ("ruca", "sdi", "frailty")
fs = feature_list("my_protocol", ruca={"crosswalk": ...}, sdi={"table": ..., "cut_points": cuts}, frailty={...})Deep-learning datasets
Area features are static, so they go to the dense block of
extract_multimodal_deep_dataset(). Use
transform="percentile" or "zscore" with
training state, keep <name>_missing, and
avoid raw dollars: a high-capacity sequence model can otherwise use the
income scale to recognise the site (see “Across sites” below).
Across sites: fitted state, manifests and deep models
A model that uses an area-level feature must compute it the same way at every site. Two things go wrong silently:
- Quantile drift. Cutting SDI into quintiles at the local quantiles moves patients between quintiles whenever a site’s deprivation distribution differs from training.
- Scale drift. Raw income in dollars differs by an order of magnitude between an urban and a rural network. A high-capacity model can use it to recognise the site instead of learning disease risk.
The framework therefore separates fitting from
applying. A transform that learns from data (SDI cut points, a
percentile grid, a mean and sd, an imputation median) is fitted
once, on the training sites, with
fit = TRUE, stored as the feature’s
state, shipped in a manifest, and reused unchanged elsewhere.
Without state a learned transform refuses to run.
Two synthetic sites
make_site <- function(zips, year = 2018) {
path <- tempfile(fileext = ".duckdb")
build_schema(path)
con <- DBI::dbConnect(duckdb::duckdb(), dbdir = path)
DBI::dbExecute(con, "CREATE TABLE person_address_history (person_id BIGINT, location_id BIGINT, zip5 VARCHAR,
address_start DATE, address_end DATE, preferred VARCHAR)")
for (i in seq_along(zips)) {
DBI::dbExecute(con, sprintf("INSERT INTO person (person_id, gender_concept_id, year_of_birth, race_concept_id, ethnicity_concept_id)
VALUES (%d, 8507, 1960, 0, 0)", i))
DBI::dbExecute(con, sprintf("INSERT INTO visit_occurrence (visit_occurrence_id, person_id, visit_concept_id, visit_start_date,
visit_end_date, visit_type_concept_id) VALUES (%d, %d, 9201, DATE '%d-03-01', DATE '%d-03-04', 0)",
i, i, year, year))
DBI::dbExecute(con, sprintf("INSERT INTO person_address_history VALUES (%d, %d, '%s', DATE '2000-01-01', NULL, 'Y')", i, i, zips[i]))
}
list(con = con, path = path)
}
# the reference tables are national, so both sites use the same ones
area <- data.frame(zcta = sprintf("%05d", 10000 + 0:59),
sdi = seq(5, 100, length.out = 60),
income = seq(24000, 190000, length.out = 60))
training <- make_site(area$zcta) # a large mixed network: the whole range
#> duckdb keeps downloaded extensions and secrets in a temporary directory:
#> ℹ /tmp/Rtmp8CWD6i/duckdb
#> This is removed when the R session ends.
#> • Extensions are re-downloaded each session.
#> • Secrets are lost.
#> ℹ Run duckdb(shared_home = TRUE) (or create ~/.duckdb) to keep them (suitable for most users).
#> ℹ Run duckdb(shared_home = FALSE) to accept the temporary directory (and silence this message).
#> ℹ See ?duckdb_storage for details and alternatives.
#> Schema built at /tmp/Rtmp8CWD6i/file3917505b3751.duckdb
#> duckdb keeps downloaded extensions and secrets in a temporary directory:
#> ℹ /tmp/Rtmp8CWD6i/duckdb
#> This is removed when the R session ends.
#> • Extensions are re-downloaded each session.
#> • Secrets are lost.
#> ℹ Run duckdb(shared_home = TRUE) (or create ~/.duckdb) to keep them (suitable for most users).
#> ℹ Run duckdb(shared_home = FALSE) to accept the temporary directory (and silence this message).
#> ℹ See ?duckdb_storage for details and alternatives.
new_site <- make_site(area$zcta[41:60]) # a smaller network drawn from the deprived, low-income end
#> duckdb keeps downloaded extensions and secrets in a temporary directory:
#> ℹ /tmp/Rtmp8CWD6i/duckdb
#> This is removed when the R session ends.
#> • Extensions are re-downloaded each session.
#> • Secrets are lost.
#> ℹ Run duckdb(shared_home = TRUE) (or create ~/.duckdb) to keep them (suitable for most users).
#> ℹ Run duckdb(shared_home = FALSE) to accept the temporary directory (and silence this message).
#> ℹ See ?duckdb_storage for details and alternatives.
#> Schema built at /tmp/Rtmp8CWD6i/file39172db4503a.duckdb
#> duckdb keeps downloaded extensions and secrets in a temporary directory:
#> ℹ /tmp/Rtmp8CWD6i/duckdb
#> This is removed when the R session ends.
#> • Extensions are re-downloaded each session.
#> • Secrets are lost.
#> ℹ Run duckdb(shared_home = TRUE) (or create ~/.duckdb) to keep them (suitable for most users).
#> ℹ Run duckdb(shared_home = FALSE) to accept the temporary directory (and silence this message).
#> ℹ See ?duckdb_storage for details and alternatives.Fit on the training site
build_set <- function() {
feature_set(
sdi_feature(area[, c("zcta", "sdi")]), # no cut points yet
area_feature("income", area[, c("zcta", "income")], "income", transform = "percentile", impute = TRUE))
}
fs_train <- build_set()
train <- compute_features(fs_train, training$con, fit = TRUE)
st <- feature_set_state(fs_train)
st$sdi$cut_points
#> [1] 24 43 62 81
length(st$income$percentile_grid)
#> [1] 101fit can also name features
(fit = "income"), so one feature can be refit without
touching the others.
Ship the manifest with the model
manifest <- tempfile(fileext = ".json")
export_feature_manifest(fs_train, manifest)
substr(paste(readLines(manifest, n = 22), collapse = "\n"), 1, 520)
#> [1] "{\n \"format\": \"omop-duck-db/study-feature-set\",\n \"format_version\": 1,\n \"omop_duck_db_version\": \"0.36.0\",\n \"features\": [\n {\n \"name\": \"sdi\",\n \"description\": \"Social Deprivation Index of the residence ZIP at admission\",\n \"columns\": [\n \"sdi_score\",\n \"sdi_quintile\"\n ],\n \"requires\": [\n \"person\"\n ],\n \"params\": [],\n \"state\": {\n \"cut_points\": [24, 43, 62, 81]\n },\n \"concept_ids\": {\n \"sdi_score\": 2000100001,\n \"sdi_quintile\": 2000"The manifest records every feature’s columns, required tables, parameters, fitted state and the concept ids. It contains nothing about patients.
Apply at the new site
fs_new <- build_set()
load_feature_state(fs_new, manifest) # also accepts a manifest written by Python
new <- compute_features(fs_new, new_site$con)
# the same SDI score gets the same quintile at both sites
table(train$sdi_quintile)
#>
#> 1 2 3 4 5
#> 12 12 12 12 12
table(new$sdi_quintile)
#>
#> 4 5
#> 8 12
# income is a position in the *training* distribution, so it is comparable
range(train$income); range(new$income)
#> [1] 0 1
#> [1] 0.6779661 1.0000000The new site sits in the top two SDI quintiles and the upper third of the training income distribution, as it should. Local quantiles would have spread it over all five quintiles and hidden exactly the difference the model needs to see.
Skip the state and the learned transforms refuse:
compute_features(build_set(), new_site$con)
#> Error:
#> ! sdi_feature needs the training cohort's cut_points (or fit = TRUE when building the training reference); local quantiles would change quintiles between sites.Deep models
extract_multimodal_deep_dataset() keeps temporal
sequence tokens apart from static covariates
(dense_covariates). Area features are static, so they
belong in the dense block, and three rules follow from the above:
-
Scale them. Dollars would dominate token
embeddings. Use
percentileorzscorewith training state, never the statistics of the batch or the site. - Prefer relative scales across sites. A percentile of the national distribution transports; raw income can act as a site identifier.
-
Keep the missing indicator.
<name>_missinglets the network tell “unmapped ZIP” from “average ZIP” after imputation.
wide <- compute_features(fs_new, new_site$con, stays_from_cohort(new_site$con, "cohort"))
# merge on visit_occurrence_id, then give the numeric columns to the dense blockSharing concept ids
Concept ids for registered features are per database. For a consortium, pin them with a shared registry so every site writes the same ids:
export_custom_concept_registry(con_lead, "custom_concepts.json") # lead site
write_feature_set(fs, con, wide, registry = "custom_concepts.json") # every other site
check_custom_concepts(con, "custom_concepts.json") # catches a mismatch before anything is written