What is claimed, what is verified, and what is next.
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.
What is in the package and what has been run:
- Loading and building: PCORnet to OMOP ETL, vocabulary loading, and building and “inflating” OMOP tables in DuckDB are the core of the package and are field-tested on five production databases (see Verification status). Inflating with a full vocabulary was not re-run for this section.
-
OHDSI tools:
vignette("ohdsi_integration")is the authority. It records what was compared against the official tools (CirceR, CohortGenerator, FeatureExtraction, Achilles, DataQualityDashboard, PhenotypeLibrary, CohortDiagnostics, PatientLevelPrediction, CohortMethod, CohortConstructor, DeepPatientLevelPrediction and omop-learn) and where the package overlaps or defers. omop-learn, scikit-learn, SARD and the PLP / DeepPLP bridge are documented in the ML bridge section. Not covered by any check in the repo: Atlas 3, Data2Evidence, Phenelope and GIS integration (reasons invignette("ohdsi_integration")). Strategus appears only as “prefer HADES for published estimates”. Treat those as planned, not delivered, until a row appears invignette("ohdsi_integration"). -
Cohort and Circe: “one random stay per patient”
cannot be written in Circe. The eligibility part is available as Circe
JSON (
target_cohort.circe.json); the random draw is a documented post-step indefine_study_cohort. -
Federation: sites run the same code locally and
share aggregate outputs. Disclosure control (
min_cell, small-cell suppression) and site summary packages exist (v0.12.0). Not yet done: a run manifest stamped into every output (package version, git commit, seed, options, vocabulary version, timings) and a check that all sites ran identical versions and options before pooling. Deep models are evaluated leave-one-site-out on pooled data; training them federated (sharing weights or gradients) is a separate design that does not exist yet. -
Defaults can drift the manuscript. The 0.18 options
(
tie_break,table5,sdi_missing_term,attrition_mode) change the published numbers. Done: the named presets in Decisions that move the numbers. Done: a golden-workbook test (synthetic, committed) andscripts/check_golden.pyfor the real delivered workbook. -
R:
derive_geography_features(tie_break=, undated=)andextract_benchmark_features(address_tie_break=, address_undated=)take the same options as Python (tested intests/testthat/test-geography.R). Not yet checked: that R and Python give identical ZIPs on the real sites underarbitrary(engine order is not guaranteed to agree). -
Deep models and the DGX Spark: see the DGX Spark
section. The CPU path is tested; the GPU path, the arm64 container tag
and real-cohort training are not. The existing SARD and DeepPLP trainers
(
pipeline/dgx_spark_sard_trainer.py,ederri_sard_deep_model.py,train_clinical_deep_dgx.py,train_residual_deep_dgx.py) still needfit_predictwrappers beforedeep_study_tablescan use them. A deep-model report builder needs a spec: there is no manuscript template for it. - Data quality: run DataQualityDashboard and Achilles on each site database and record the vocabulary version in the manifest.
-
Oracle:
to_sql,verify_transferandfrom_sqlwere verified on live Oracle 19c;tests/test_live_databases.pyagainst Oracle has not been run.
Order of work: (1) agree the similarity thresholds and run once with pinned stays (and the new Table 5 default) to separate sampling from definition changes; (2) the manuscript profile and the run manifest; (3) an integration status row for every tool named above; (4) the Spark GPU run and the SARD / DeepPLP wrappers.
Verification status
What the project’s own tests cover and what they do not:
- Python: the unit tests run on small synthetic DuckDB databases
(
pytest tests). R: the testthat suite runs on small synthetic databases. - Field-tested on five production databases: the v0.11.0 cohort
equivalence (Python). The 0.11.1 and later changes (per-table feature
aggregates,
cap_observation_period,remap_discharge_status, the attrition list) were checked on synthetic data only, and the R half of 0.11.1 and later on small synthetic databases only (the 0.11.2 R ports were run with testthat, not on production data). - Oracle (
translate_cohort_sql) and the BigQuery sync are unit-tested only.extract_patient_featurestiming on production-size cohorts:scripts/benchmark_features.py(synthetic fixture: 1.1M stays in about 4 s; a production run will differ with the number of events per patient).
Architecture, decisions and R/Python parity
Working notes on where the package came from, the decisions behind it, packaging gotchas and the R/Python parity table.
Where it came from
omop-duck-db (R package omopduckdb) builds
and populates an OMOP CDM v5.4 database in DuckDB, loads the OHDSI
Athena vocabulary, and maps PCORnet-format source data into the CDM —
with parallel R and Python ETL implementations sharing the same schema
and concept-mapping SQL, so either language gets the same result. It’s
deliberately the public/generic piece of a bigger initiative: no
institution names, no site specifics, no protected data, ever —
real-world use against production data happens entirely outside this
repo, against your own infrastructure.
Key decisions (and why)
-
License: dual
GPL-3 | MIT, changed from plain MIT on 2026-08-05 to match the rest of the public track (TempleCBE,pslongSim,ML-PScore,quarto_temple_brand). -
Schema is generated, never hand-declared.
inst/extdata/5.4/duckdb/*.sql(from OHDSI’sCommonDataModelR package) is the single source of truth for both ETL paths — this is whykyle_out_zip’s bridging script calls this package’s real entrypoint instead of writing new mapping SQL; a hand-rolled alternative (kyle_out_zip/omop_duckdb_gpu_server_integration_plan.md) diverged from this and would have produced a broken database (wrong ID scheme, wrong glob paths, invented columns). -
Consortium Zero-Copy Federation: Base table views
(
CREATE OR REPLACE VIEW {tbl} AS SELECT * FROM v_{tbl}) alongside prefixedv_{tbl}views allow standard ETL routines, scoring calculators, and measurement extractors to run transparently against attached multi-site consortia without bespoke SQL rewriting.
Capability list (written at v0.6.1, updated through v0.36.0)
Verified directly against source and comprehensive test suites:
-
Close, not full, R/Python parity (v0.36.0): the
PCORnet-to-OMOP ETL (including censored lab operator parsing,
VITAL.TOBACCOfallback, and OMOP v5.4MED_ADMINdomain routing viaroute_drug_domains()), cohort engine, comorbidity, sanitisation, Table 1 and scoring exist in both languages with near-identical signatures. Post-build database repair routines (backfill_all(),backfill_condition_concepts(),backfill_drug_concepts(),backfill_lab_values(),backfill_vital_tobacco(),backfill_med_admin(),repair_routed_med_admin_values()) live in Python (omop_etl) with Rreticulatewrappers of the same names; seevignette("sister_site_guide"). Python-only:extract_sard_visit_tensors()(R hasextract_longitudinal_tensors()),extract_multimodal_deep_dataset()and the tensor/memmap/Arrow/Zarr output, the manuscript pipeline (run_study,build_study_tables),run_achilles(),mapping_coverage_report(),site_export, FHIR and cluster helpers. R-only:as_plp_data(),load_from_bigquery(),gdrive_*, the HADES/tidymodels bridges, ONNX export. Deliberate shape differences (Python classes vs R functions/S3,format=on three extractors,generate_table1dict vs list) are listed in the README. The parity tests compare outputs, not the duplicated code tables. -
Core Capabilities (v0.6.0):
-
Staged Wide Measurements & Plausibility Bounds:
Sequential unpivot, BMI coalescing, physiologic plausible filters
(
filter_bounds,DEFAULT_PHYSIOLOGIC_BOUNDS,POPULATION_PHYSIOLOGIC_BOUNDS). -
Standardized Phenotyping & Cohorts: Composable
criterion trees (
ConditionCriteria,DrugCriteria,MeasurementCriteria), readmission cohorts (define_study_cohort), Elixhauser and Charlson comorbidity scoring with train/serve skew protection. -
Unit & Anthropometric Harmonization: Preflight
auditing, conversion (
DEFAULT_UNIT_RULES), andharmonize_anthropometrics()deriving BMI and correcting raw unit mismatches (inches/lbs vs cm/kg). -
Clinical Benchmark Heuristics: Standardized bedside score
calculators
calculate_lace_index()andcalculate_hospital_score(). -
Transitions of Care: Trajectory flags
(
extract_medication_transitions,MedicationTransitions) capturing initiation, discontinuation, and continuation across acute stay transitions. -
Multi-Site Consortium Federation: Zero-copy multi-database
connector (
FederatedConsortium/federated_consortium) generating cross-site Table 1 and Table 2 missingness audits in a single call. -
HADES & ML Bridges: Zero-copy Arrow PLP bridge
(
as_plp_arrow,plp_arrow_to_plp_data) with Windows subprocess DLL isolation, tidymodels adapter, andomop-learnbackend.
-
Staged Wide Measurements & Plausibility Bounds:
Sequential unpivot, BMI coalescing, physiologic plausible filters
(
-
v0.6.1 High-Impact Analytical Additions:
-
Consortium Bedside Scoring:
FederatedConsortium.calculate_scores()andconsortium_calculate_scores()running LACE and HOSPITAL risk stratification simultaneously across all connected federation member sites. -
Cross-Site Model Calibration & Decile Drift:
consortium_calibration()/ConsortiumCalibrationcomputing site-stratified IRLS logistic calibration curves, Greenwood-Nam-D’Agostino goodness-of-fit, Brier scores, ECE/MCE, and decile assignment drift. -
Clinical Decision Curve Analysis (DCA):
decision_curve_analysis()/DecisionCurveAnalysiscomputing Net Benefit, Standardized Net Benefit, and Net Reduction in Interventions across clinical threshold ranges, with publication-grade plotting. -
Automated European & IFCC Metric Unit Scaling:
LOINC-based automated harmonization in
harmonize_measurement_units()for European Hemoglobin mmol/L (59260-0), IFCC HbA1c mmol/mol (59261-8), and Serum Creatinine (), even when raw unit strings are missing or unstandardized. -
Competing Risks Cumulative Incidence Function (CIF):
estimate_cif(),plot_cif(), andfine_gray_estimator()providing non-parametric Aalen-Johansen CIF curves and Fine-Gray subdistribution hazard modeling for 30-day readmissions accounting for inpatient and out-of-hospital death.
-
Consortium Bedside Scoring:
CI/CD Architecture & Local Validation with act
Workflows under .github/workflows/:
-
ci.yml: On push and PR:-
r-check:R CMD check+ testthat on matrix (ubuntu-latest,windows-latest). -
python-test:pyteston matrix (ubuntu-latest,windows-latestacross Python 3.10, 3.11, 3.12). -
python-only: Runs onubuntu-latestwith no R installed to ensure standalone operation on GPU/deep-learning clusters; R-dependent parity tests cleanly skip viashutil.which("Rscript") is None. -
docker-build: Multi-stage Docker image build and in-container test execution on Linux.
-
-
pkgdown.yml: Automated documentation site build and deployment to GitHub Pages on push tomain(requires Pages source set to GitHub Actions). -
release.yml: Triggered onv*tags; executes build,twine check, and gated PyPI publishing requiring manual approval via thepypi-releaseenvironment.
Local validation with act
-
python-only: Passed locally with zero R present; standalone schema tests passed and cross-language parity tests skipped cleanly. -
docker-build: Passed; nested Docker build validated both test suites inside the image. -
r-check: Passed; fullR CMD checkviar-lib/actions/check-r-package. - Note:
actemulates Linux runners only; Windows runners and GitHub-specific secrets/environments (Pages, PyPI) remain verified via GitHub Actions runners.
Multi-Stage Containerization (Dockerfile) Lessons
Generated initially via usethis::use_dockerfile() and
customized for Python & R hybrid execution:
-
Posit Package Manager (PPM) Snapshot Pinning:
Upstream generator pinned snapshots to
Sys.Date(), which fails if clocks drift or snapshot metadata lags. Swapped to/latestrolling alias. -
PPM Linux Codename Mismatch (ICU 74 vs 70):
rocker/r-ver:4.4.2is built on Ubuntu noble (24.04), not jammy (22.04). Hardcoded__linux__/jammybinaries (e.g.stringilinked tolibicui18n.so.70) failed at runtime because noble provides ICU 74 (libicui18n.so.74). Fixed by pointing PPM tonoble. -
.dockerignoreandREADME.md: Upstream default ignoredREADME.md, breakingpip installduring the metadata build phase (pyproject.tomlreferencesreadme = "README.md"). Excluded from.dockerignore. -
.RprofileAutoloader Bypass: Project.Rprofileactivates renv by default, which can hijack.libPaths()into an unpopulated project cache inside Docker. Resolved by settingENV RENV_CONFIG_AUTOLOADER_ENABLED=FALSEin both builder and runtime stages. -
Testthat Directory Resolution in Containers:
Running
testthat::test_dir()requires the installed package under test. Fixed withR CMD INSTALL --install-tests, executingcd /build/tests && Rscript testthat.R. -
Docker Context Exclusions: Large generated assets
(
*.duckdb,vocabulary_download_v5_*,config/*.ymlcontaining cloud credentials) are strictly excluded via.dockerignore.
R & Python Packaging Gotchas
Technical lessons recorded during package build and deployment:
-
renvTarget Isolation: Installing packages afterrenv::init()without explicit library specification can inadvertently install into the ambient user library instead of the project library. Recommended practice:renv::restore()followed by explicitrenv::install(...). -
Maintainer Email in
DESCRIPTION:R CMD buildstrictly requires a valid email address inAuthors@R. -
.RbuildignoreCompleteness: Without comprehensive exclusions,R CMD buildattempts to tar large SQLite/DuckDB databases, Athena downloads, and Python environments. Maintained in.Rbuildignore. -
Windows DuckDB File Locks: Rapid close and
immediate reconnect to a DuckDB database file within a single process on
Windows can trigger transient locking conflicts
(
dbDisconnect(shutdown=TRUE)). A garbage collection call (gc()) before reconnect reliably releases the OS file lock. -
Windows
RscriptSubprocess Execution: WindowsCreateProcesscannot directly executeRscriptwhen resolved asRscript.bat. Callingsubprocess.run(["Rscript", ...], shell=True)properly delegates throughcmd.exe. -
Non-Editable Python Wheel Bundling: Relocatable
wheels cannot resolve SQL templates via git repository-relative paths.
Resolved using
pyproject.toml[tool.setuptools.package-data]/force-includecombined with a package-relative first, repo-relative fallback resource locator. -
Athena CPT4 Vocabulary: Athena downloads do not
include CPT4 descriptions directly due to AMA copyright; the Java
utility
cpt4.jar(requiring a UMLS license) or public CMS OMOP BigQuery mirrors (bigquery-public-data.cms_synthetic_patient_data_omop) are used to populate CPT4 concepts.
Secret scanning and token revocation
CI (secret-scan job) runs
scripts/secret_scan.py over tracked files, a planted-token
self-test, and gitleaks over the full history;
.pre-commit-config.yaml runs both before each commit
(pip install pre-commit && pre-commit install). If
a credential was ever committed (for example the TestPyPI token noted in
QUESTIONS B11):
- Revoke it first (TestPyPI/PyPI: Account settings -> API tokens -> Remove). Rewriting history does not un-leak a token that was pushed; revocation does.
- Find it:
gitleaks detect --source . --redact(full history). - Remove it from history:
git filter-repo --replace-text replacements.txt(a file with<the-token>==>REMOVED), then force-push all branches/tags and ask collaborators to re-clone. Re-run step 2 to confirm. - Publish with a trusted publisher / a new scoped token stored only in GitHub Actions secrets.
Shared vocabulary by reference (FR-B5)
A site file does not have to hold the 5-18 GB vocabulary.
omop-duckdb build --vocab central_vocab.duckdb creates
concept and the other vocabulary tables as
views into a catalog named central_vocab.
Any client that opens such a file must attach the vocabulary file under
exactly that name, read-only:
- Before distributing a file run
omop-duckdb checkpoint file.duckdb(orcheckpoint_database()in Python/R); a leftover.walmakesATTACH ... (READ_ONLY)fail. - Python:
omop_etl.attach_read_only(con, "site.duckdb", "central_vocab.duckdb")attaches both files read-only. - R / HADES:
omopduckdb::readonly_attach_sql("site.duckdb", "central_vocab.duckdb")returns the statements; DatabaseConnector cannot ATTACH on connect, so run them on each new connection (seeinst/cohorts/run_plp_readonly_example.R). - To make one file self-contained instead (and larger):
omop-duckdb materialize-vocab site.duckdb --vocab central_vocab.duckdbcopies the views into real tables, which needs a writable file.
Where it’s heading
- Production Consortium Deployments: Automated validation against multi-hospital health network nodes (eDERRI study).
- Extended In-Database OHDSI Analytics: Vectorized execution of Achilles characterization and DataQualityDashboard (DQD) directly inside DuckDB.
- Distributed Federated Learning: Iterative horizontal federated logistic regression and Cox proportional hazards across consortium member nodes without patient-level data sharing.
