
ML bridge: omop-learn, scikit-learn, SARD and OHDSI PLP
Source:vignettes/ml_bridge.Rmd
ml_bridge.RmdHand OMOP data to scikit-learn, omop-learn, OHDSI PatientLevelPrediction / DeepPLP and tidymodels.
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.
omop-duck-db connects an OMOP-on-DuckDB database to three modelling
ecosystems without ad-hoc SQL or per-patient query loops. Every
extractor runs as one set-based DuckDB query over the whole cohort, and
every window is strictly before the index date by
default ([index - lookback_days, index)), so nothing at or
after the index leaks into the features. Concept id 0 (“No
matching concept”) is always dropped.
| You use | Entry point |
|---|---|
| scikit-learn / glmnet / LASSO |
extract_sparse_concept_matrix() (Python:
scipy.sparse.csr_matrix; R:
Matrix::dgCMatrix) |
| SARD / sequence models |
extract_sard_visit_tensors() (padded
(N, max_nvisits, max_visit_len); Python
only - R has extract_longitudinal_tensors()) |
omop-learn (OMOPDataset, its torch / sparse / windowed
datasets and models) |
DuckDBBackend, a DuckDB implementation of omop-learn’s
backend interface |
| OHDSI PatientLevelPrediction / DeepPatientLevelPrediction |
plp_database_details(), hades_preflight(),
as_plp_data()
|
| tidymodels / in-database scoring |
as_tidymodels_data(), model_concepts(),
materialize_concept_features()
|
1. Sparse concept matrix and SARD visit tensors
Both take a cohort parquet (one row per index event; person id and
index date columns are auto-detected, an outcome column is carried
through) and return arrays whose row i is parquet row
i.
import duckdb
from omop_etl import extract_sparse_concept_matrix, extract_sard_visit_tensors
con = duckdb.connect("derived/omop_duckdb/omop_site1.duckdb", read_only=True)
con.execute("ATTACH 'derived/omop_duckdb/central_vocabulary.duckdb' AS central_vocab (READ_ONLY)")
cohort = "derived/ederri_features/ederri_features_site1.parquet"
res = extract_sparse_concept_matrix(con, cohort, min_patient_freq=50)
res["X"].shape # (N, V) csr_matrix; res["concepts"] has names, domains, patient counts
sard = extract_sard_visit_tensors(con, cohort, min_patient_freq=50)
sard["concept_tensor"].shape # (N, max_nvisits, max_visit_len); also visit_lengths, n_visits, times
library(DBI); library(duckdb)
con <- dbConnect(duckdb::duckdb(), "derived/omop_duckdb/omop_site1.duckdb", read_only = TRUE)
dbExecute(con, "ATTACH 'derived/omop_duckdb/central_vocabulary.duckdb' AS central_vocab (READ_ONLY);")
res <- extract_sparse_concept_matrix(con, "derived/ederri_features/ederri_features_site1.parquet",
min_patient_freq = 50)
dim(res$X)Conventions follow omop-learn so outputs drop into its models:
special tokens [BOS]=0 [EOS]=1 [SEP]=2 [PAD]=3 [UNK]=4,
concept tokens from 5
("<concept_id> - <domain> - <concept_name>",
sorted like omop-learn’s ConceptTokenizer), visit times as
days since 1900-01-01 with -1 padding. Pass a train
result’s tokenizer (R: tokens) to a test
cohort to get identical columns; pass explicit max_nvisits
/ max_visit_len for a fixed tensor shape.
pip install "omop-duck-db[ml]" adds scipy.
2. omop-learn backend
omop-learn ships Postgres, BigQuery and Spark backends behind one
interface; DuckDBBackend adds DuckDB. omop-learn’s
per-patient feature SQL runs as a single LATERAL join
instead of one query per patient (about 70x faster in our benchmark),
with DuckDB-dialect feature SQL bundled in
inst/sql/omop_learn.
from pathlib import Path
from omop_learn.omop import OMOPDataset
from omop_learn.utils.config import Config
from omop_etl import DuckDBBackend, default_features, cohort_from_parquet
backend = DuckDBBackend(con=con)
dataset = OMOPDataset(name="temple", config=Config({"cdm_schema": "main"}),
cohort=cohort_from_parquet(con, cohort), features=default_features(),
backend=backend, data_dir=Path("datasets"))
torch_ds = dataset.to_torch() # omop-learn's own datasets and models from here onomop-learn is not on PyPI:
pip install git+https://github.com/clinicalml/omop-learn.
3. OHDSI PatientLevelPrediction and DeepPatientLevelPrediction
PLP, DeepPLP and FeatureExtraction read the CDM through
DatabaseConnector, which opens the DuckDB file itself and cannot
ATTACH a central vocabulary. The vocabulary tables
must therefore be inside the file. It also opens the file read-write, so
no other process (for example a Python session that still has
the database open, even read-only) may hold it.
hades_preflight() checks both, from a fresh connection.
Files distributed for read-only use must be cleanly closed and
checkpointed (omop-duckdb checkpoint site.duckdb,
omop_etl.checkpoint_database() or
omopduckdb::checkpoint_database()): if a
.duckdb.wal sits beside the file,
ATTACH ... (READ_ONLY) fails with “WAL replay is required”.
Hand-written cohort SQL does not create inclusion-rule statistics
tables, so call
CohortGenerator::generateCohortSet(..., generateStats = FALSE):
hades_preflight("omop_site1.duckdb")
db <- plp_database_details("omop_site1.duckdb", target_id = 1, outcome_ids = 2)
# Native OHDSI features (including DeepPLP's temporal transformer input):
plp <- PatientLevelPrediction::getPlpData(db, FeatureExtraction::createCovariateSettings(
useConditionOccurrenceLongTerm = TRUE, longTermStartDays = -365, endDays = -1),
PatientLevelPrediction::createRestrictPlpDataSettings())
# ...or hand PLP / DeepPLP the very same matrix you used in Python or glmnet:
res <- extract_sparse_concept_matrix(con, cohort_parquet, value = "binary")
plp <- as_plp_data(res, con, target_id = 1, outcome_id = 2)as_plp_data() uses covariate ids
concept_id * 1000 + analysis_id with FeatureExtraction’s
long-term analysis ids (102 / 302 / 502), so they match natively
extracted covariates for the 365-day window (verified against
FeatureExtraction in the test suite).
4. tidymodels and in-database scoring (orbital, tidypredict)
as_tidymodels_data() bridges sparse concept matrices
into a tibble ready for tidymodels (rsample,
recipes, parsnip, workflows,
yardstick), with outcome y formatted with the
event as the first factor level (event_level = "first"),
and concept predictors named
<domain>_<concept_id>.
Once a model or workflow is fitted, model_concepts()
identifies which concepts have non-zero coefficients.
materialize_concept_features() exports matching wide
feature tables inside DuckDB using identical windowing logic. Scoring
can then run directly in-database with orbital::orbital()
or tidypredict without feature drift:
library(tidymodels)
res <- extract_sparse_concept_matrix(con, "cohort.parquet", min_patient_freq = 50, value = "binary")
dat <- as_tidymodels_data(res)
split <- rsample::group_initial_split(dat, group = person_id)
rec <- recipes::recipe(y ~ ., data = rsample::training(split)) |>
recipes::update_role(person_id, index_date, new_role = "id")
spec <- parsnip::logistic_reg(penalty = 0.01, mixture = 1) |> parsnip::set_engine("glmnet")
fit <- workflows::workflow(rec, spec) |> parsnip::fit(rsample::training(split))
# In-database scoring on new patients without feature drift:
used <- model_concepts(fit, res$concepts)
materialize_concept_features(con, "new_cohort.parquet", used, table = "to_score", value = "binary")
orb <- orbital::orbital(fit)
scores <- orbital::augment(orb, dplyr::tbl(con, "to_score")) |> dplyr::collect()