omopduckdb 0.36.0
Hardening release for sister sites building from raw PCORnet extracts (2026-11-27). Version bump 0.35.3 to 0.36.0; manuscript template v0.36.0. Proven on the five-site C23-check audit to change zero C22 cohort model features (0 routed rows in measurement or observation, 0.0% overlap with the 166 study lab/vital concepts; raw LAB_RESULT_CM number_with_flag + percent share 0.0%–0.1% overall and <= 1.1% per lab across sites, below the 2% parser threshold).
-
M1 (
MED_ADMINdose out ofvalue_as_number):route_drug_domains()andbackfill_med_admin()now setvalue_as_number = NULLwhen routing a drug record tomeasurementorobservation, storing the administered dose text invalue_source_valueand the unit inunit_source_valueso a routed concept can never enter a numeric lab or vital feature.repair_routed_med_admin_values(con, dry_run=False)repairs databases routed under 0.35.3 (type_concept_id = 38000180). -
M2 (OMOP v5.4 domain routing inside both Python and R converters):
load_drug_exposure()in bothpython/omop_etl/build_omop_cdm.pyandR/etl_pcornet.RreadsMEDADMIN_DOSE_ADMIN,MEDADMIN_DOSE_ADMIN_UNIT, andMEDADMIN_ROUTEand callsroute_drug_domains(con)at build time, verified by a cross-language Python/R parity test coveringDrug,Device,Procedure,Observation,Measurement, and unmapped0. -
Fallback dates and undated-row drops on fresh builds (behaviour change, Python and R): when a clinical event record lacks its primary PCORnet date, the converters now fall back to secondary PCORnet or linked-encounter dates instead of failing on OMOP v5.4
NOT NULLdate constraints (DIAGNOSIS:ADMIT_DATE, thenvisit_occurrence.visit_start_date;PROCEDURES:ADMIT_DATE, thenvisit_start_date;PRESCRIBING:RX_ORDER_DATE, thenvisit_start_date;MED_ADMIN:visit_start_date;LAB_RESULT_CM:SPECIMEN_DATE, thenLAB_ORDER_DATE, as in 0.34.0), and drop rows that still have no parseable date (ENCOUNTER,DIAGNOSIS,PROCEDURES,LAB_RESULT_CM,VITAL,PRESCRIBING,MED_ADMIN,DISPENSING,DEATH). Each loader prints and returns how many rows were dated by fallback (broken down by fallback column) and how many undated rows were dropped;etl_pcornet()prints an end-of-build summary, passes the per-table report todate_audit_callback=(and setsattr(result, "date_audit")in R), andomop-duckdb build --manifestrecords each table’s counts inrun_manifest.json. Existing C22 databases built outsideetl_pcornet()are untouched. -
M3 (Checked-in reference environment & library audit):
config/reference_env.jsonrecords the reference versions of Python, DuckDB, pandas, PyArrow, scikit-learn, XGBoost, NumPy, R, and Quarto from the verified0.31.0study container (Study_Manuscript.bibof run C22);scripts/check_env.pycompares the active environment or a Docker image (--image,--policy report|pinned|compatible|exact,--skip-r) and runs inci.ymlanddocker-release.yml. -
M4 (
Dockerfile.dgxarm64 CI build):.github/workflows/dgx-build.ymlbuildsDockerfile.dgxonubuntu-24.04-arm(linux/arm64, build-only, no GPU) on pull requests touchingDockerfile.dgx/config/**/scripts/check_env.py/dgx-build.yml, weekly, on version tags, and viaworkflow_dispatch, runningscripts/check_env.py --skip-r --policy compatibleandstudy-smoke. Live DGX Spark GPU smoke result (dgx-smoke) remains a manual on-device step to record at release. -
M5 & S5 (Sister-site end-to-end walkthrough & guide):
tests/test_issue69_e2e_sister_sites.pybuilds 7 synthetic sister sites from raw PCORnet CSVs viaetl_pcornet(), runsreproduce_study.py, verifies anonymous shareable outputs (check_run_privacy.py), relabels viarelabel_study.py, and re-verifies zero privacy hits.vignettes/sister_site_guide.Rmddocuments the step-by-step path and the PCORnet table / backfill matrix;vignettes/status_and_roadmap.Rmdupdated to 0.36.0. -
S1 & S2 (
backfill_all()single entry point + Rreticulatewrappers):omop_etl.backfill_all(con, raw_dir, dry_run=True)runscondition_concepts,drug_concepts,lab_values,vital_tobacco, andmed_admin_and_routingin a fixed order on a read-only (dry_run=True) or writable connection and returns one summary DataFrame (backfill_condition_conceptsandbackfill_drug_conceptsnow also acceptdry_run=True). R exports matching wrappers (R/backfills.R) that delegate viareticulatewith a clear error when Python /omop_etlis absent, documented inREADME. -
S4 (Manuscript template v0.36.0): adds the Section 2.2 Methods sentence stating that censored laboratory results (
<0.01,>14.0) are stored at their reported numeric limit with their OMOP operator concept recorded and enter the stay mean at that limit, and reads optionalorcid(per author),funding,conflicts_of_interest(coi),bmi_by_age_note, anddischarge_limitation_notekeys from--manuscript-params.
omopduckdb 0.35.3
Run C21’s lab-text check and pre-C22 raw-to-OMOP parity audit (2026-11-26). Version bump 0.35.2 to 0.35.3; manuscript template stays v0.35.2. Kyle chose (2026-11-26) that a censored result counts at its reported limit (“<0.01” as 0.01, “>14.0” as 14.0), the OMOP convention the converter already stores, so feature extraction is unchanged.
-
omop_etl.lab_text.backfill_lab_values(con, lab_result_cm, names=..., start=, end=, dry_run=False, crosswalk=None)fillsvalue_as_numberof lab rows without a number from the rawLAB_RESULT_CMfile (.csv,.parquet, or.zip), with the converter’s rules (LAB_VALUE_SQL,LAB_OPERATOR_SQL): a censored result is stored at its limit withoperator_concept_idset, the OMOP convention; a qualitative or other text result stays NULL. ResolvesPATIDaliases (PATID,SSID,PAT_ID,PERSON_ID), optionalPATID–ssidcrosswalk.csv, andENCOUNTERID->visit_occurrence.visit_source_valuefallback. A row is matched to raw rows without a number of the same patient, LOINC (source value or the concept’s code) and date, at the same minute first when both have a time, and filled only when every matching raw row gives the same value and operator.dry_run=Truewrites nothing and runs on a read-only connection. -
omop_etl.build_omop_cdm.backfill_vital_tobacco(con, vital_path, dry_run=False)backfillsobservation(concept 43054909, LOINC 72166-2) from PCORnetVITAL.TOBACCO(01current,02never,03former) whenSMOKINGhas no status, bringing databases built before 0.34.1 into parity withload_vital(). Idempotent; accepts.csv,.parquet, or.zipandPATID/SSID/ENCOUNTERIDaliases. -
omop_etl.build_omop_cdm.backfill_med_admin(con, med_admin_path, dry_run=False)androute_drug_domains(con, dry_run=False): loads PCORnetMED_ADMIN(.csv,.parquet, or.zip;PATID/SSID/MEDADMIN_PROVIDERIDaliases) resolving RxNorm, 10/11-digit NDC, HCPCS/CPT4 and exact standard RxNorm names, and routes records by their target standard concept’s OMOP v5.4domain_id(drug_exposureforDrugand unmapped rows,device_exposureforDevice,procedure_occurrenceforProcedure,observationforObservation,measurementforMeasurement;type_concept_id= 38000180).route_drug_domains()(also called at the end ofload_drug_exposure()) applies the same OMOP domain routing todrug_exposurerows mapped to non-Drug standard concepts. -
Tests (
tests/test_lab_backfill_0353.py): duplicated censored raw rows, match by the concept’s LOINC code, ambiguous day, minute tie-break, qualitative text,SSID/crosswalk.csv/ENCOUNTERID/.zipinputs,backfill_vital_tobaccoidempotence and read-only dry run, andbackfill_med_admin+route_drug_domainsmulti-vocabulary resolution and OMOP v5.4 domain routing.
omopduckdb 0.35.2
Polish from the PR 108 and C20r audits, plus Kyle’s release gates for the final submission run (2026-11-25). Version bump 0.35.1 to 0.35.2; manuscript template v0.35.2. No feature rule changes: saved features can be reused, and the model numbers do not move.
- Section 2.3 names a counted unit once. C20r printed “10 visits of prior outpatient visits”; the example now reads “10 prior outpatient visits” (and “10 prior outpatient encounters”), while measured units keep “10 mmHg of blood pressure”. Check 14 now accepts an example whose number and unit Table 4 prints in either form.
-
The PDF and Excel agree on a rounding tie. The stay-type table (workbook Table 4, printed Table S1) stored AUC-ROC to 3 places (0.695), which Excel showed as 0.70 and the PDF printed as 0.69 (Python rounds the binary value just below 0.695). It is now stored at
METRIC_DECIMALS, as Tables 2 and 5. Every printed metric cell is rounded as Excel shows it (excel_text(), half away from zero on the written number), so a 3-place tuning-grid cell prints as Excel would round it. An int 0 in a metric column prints 0.00 and is formatted 0.00 in the workbook (it was left as 0). -
Captions stay with their tables. A table that may break across pages keeps its caption with its first rows (C20r: the Table 1 caption sat alone at the foot of page 5).
layout.jsonkeeps the stay-type, completeness and tuning-grid tables on one page, as the length-of-stay table (C20r: Table S4’s last row ran alone onto page 18). The Word file is unchanged. - The bootstrap count prints with a thousands separator (“1,000 bootstrap replicates”).
-
Release gates in
manuscript_checks(python -m omop_etl.manuscript_checks <pdf> [<xlsx>] [--docx F] [--run-json F] [--final] [--params F] [--names F];release_checks()runs everything given):- PDF checks 18 to 20: Table S4 on one page; no table caption alone at the foot of a page; no placeholder (
[not in this run: ...],[Review board statement: ...], i.e. a value the run or the--manuscript-paramsfile lacked) and no increment example that names its unit twice. -
workbook_checks(): int cells count as metric cells (bool does not); metric cells are stored with no more places than they show; the categories of each multilevel Table 1 feature (age, race, SDI, RUCA, discharge status, tobacco, BMI) sum to 100% ± 0.3 in every column; Table 1’s Missing / Unknown counts equal Table S2’s. -
pdf_workbook_checks(): the PDF prints the workbook’s cohort N, readmitted count, readmission rate, Table 2 AUC-ROCs, stay-type AUC-ROCs and leave-one-site-out mean AUC-ROC. -
docx_checks(): the Word file has the title, no placeholder, every author and the review-board statement of the params file, Table 1, 2, … and S1, S2, … without a gap, each with a Word table, and file properties that name no one on the private names list (--names: a text file, or<prefix>_run_private.json) and not this computer’s account. Names are read from the private files at run time; the package stores none. -
run_record_checks(): no saved stay list, privacy scan clean, no unexpected data-check finding, no missing document format or value, the manuscript cites the omop-duck-db version that ran; with--final, at least 1,000 bootstrap replicates and an observation-period cap. - With the PDF, workbook, Word file and run record, the gate has 35 checks (37 with
--final).
- PDF checks 18 to 20: Table S4 on one page; no table caption alone at the foot of a page; no placeholder (
-
Censored lab values keep their operator. The PCORnet converter already read “<0.01” as 0.01; it now sets
operator_concept_id(“<” 4171756, “<=” 4171754, “=” 4172703, “>=” 4171755, “>” 4172704), so the number is not read as exact. Python and R. Feature extraction still usesvalue_as_number. -
omop_etl.lab_text.lab_text_profile(con, names)says what lab rows without a number hold: blank, a number, a censored number, a number with a flag (“7.5 H”, which the converter does not read), a percentage, a range, a qualitative result, or other text, as shares of the rows without a number, withpct_parseable. It never returns the text. -
reproduce_study.py --merge-episodes-days Nruns the episode-merging sensitivity analysis (define_study_cohort(merge_episodes_days = N)) from the command line. -
inst/extdata/manuscript_params.example.json: the--manuscript-paramskeys the package reads, with placeholders only. -
Tests (
tests/test_final_release_checks_0352.py): rounding ties through the workbook and the printed table; the unpinned draw is identical for one seed and differs for another; two runs with one seed give identical tables, text and cohorts, and the text prints the run’s bootstrap count; censored and qualitative lab strings through the converter,lab_text_profile()and the site report’s funnel; the full gate on a Quarto render; a sticky caption never left alone at the foot of a page.
omopduckdb 0.35.1
Kyle’s review of run C20 (2026-11-25). Version bump 0.35.0 to 0.35.1; manuscript template v0.35.1. No feature rule changes. Kyle chose to run the final manuscript without the saved stay list (--pinned-stays), so the cohort is drawn inside OMOP (sample_stay_rule = "random", seed 42) and Figure 1 has no exclusion branch for the saved draw; that run extracts the features again.
-
A range that rounds to one value reads as one value. C20’s Discussion said “across ten repeated random draws the AUC-ROC ranged from 0.73.” because the ten seeds gave 0.7321 to 0.7346, which
fmt_range()printed as one value. A new template filterfrom_rangeprints “ranged from 0.71 to 0.74”, or “was 0.73 in every draw (0.732 to 0.735)” when both ends round to the same 2-decimal value. The seed range, the sensitivity range of Section 4, the leave-one-site-out range and the Brier range use it. -
The cohort is called self-contained only when it is. Section 2.1 said the cohort was defined “with no externally supplied list of index stays” and Section 6 printed
define_study_cohort(..., sample_stay_rule='random')although C20 reapplied a saved draw. When the run record says a saved draw was used (pinned,inputs.pinned_stays, redrawn patients, or Figure 1’s draw exclusion), Section 2.1 says the index stays are the saved draw reapplied withpin_stays(), and Section 6 printsdefine_study_cohort(..., sample_stay_rule='all')followed by thepin_stays()call. A run without a saved draw is unchanged. - Table 1 ends the SDI quintiles with “SDI Quintile: Missing / Unknown”, as Section 3.1 says each category does (C20’s quintiles summed to 99.3%).
- Prior outpatient visits are reported per 10 visits again in Table 4 (clinical increments). The row was renamed “Prior Outpatient Visit Count” in 0.34.0 and lost its increment, so it printed per 1 SD while Section 2.3 gave “10 outpatient encounters” as an example. The Section 2.3 examples are now read from Table 4: only increments it prints are named.
-
Table S1 prints AUC-ROC to 2 decimals (C20: 0.698), as Tables 2, 3 and S4; the workbook keeps 3 decimals. Table S3 prints length of stay mean ± SD to 1 decimal (
los_by_site()), as Table 1, and is kept on one page in the PDF (C20’s last row ran alone onto the next page). -
The workbook shows metric cells with 2 decimals.
export_workbook(number_formats =)sets an Excel number format per sheet; Tables 2, 4, 5 and 6 use0.00on their metric columns (every number in a column that holds a non-whole number, so 0.0 shows as 0.00; count columns are left alone), so Table 5 shows 0.60 where it showed 0.6 and Table 6’s standardized betas show 0.00 / -0.10. -
manuscript_checkshas 17 PDF checks (was 10): no range missing its upper end; no “no externally supplied list” next to a saved draw; Table 1’s SDI Missing / Unknown row; Section 2.3 increments that Table 4 prints; Table S1 AUC-ROC and Table S3 length of stay decimals; Table S3 on one page.python -m omop_etl.manuscript_checks <pdf> <workbook.xlsx>adds the workbook check (workbook_checks()).
omopduckdb 0.35.0
The follow-ups in issue 106 (Kyle’s suggestions after run C17). Version bump 0.34.2 to 0.35.0; manuscript template v0.35.0 (one Discussion sentence reads the seed sensitivity when the run has one). Items 1, 2 and 4 change model features, so the features must be extracted again.
-
Combination drugs count for every ingredient class (behaviour change). In the standard strategy,
extract_medication_classes()rollsdrug_concept_idup throughconcept_ancestor, which holds valid standard concepts only. A row left on a deprecated RxNorm drug, a Brand Name or a combination product that no single ingredient could replace (backfill_drug_concepts()leaves those) counted for no class. Withcombination_ingredients = TRUE(the default) such a row now counts for the class of each of its valid standard RxNorm ingredients (drug_strengthand the ingredient relationships, retired links included), of the valid standard drugs reached through brand and form links, and of its valid ‘Maps to’ targets. A combination product counts for every class of its ingredients. Dose-form and route exclusions still apply.drug_exposureis not changed.attr(result, "combination_flags")/result.attrs["combination_flags"]counts the (row, class) flags only this rule sets;FALSErestores the earlier behaviour.attrs["combination_flags_by_class"](Python) splits the count by class, and the run record gives, per site, the share of stays that each class reached only this way (medication_combination_share). Python and R. -
backfill_condition_concepts(con)does for diagnoses whatbackfill_drug_concepts()does for drugs. Acondition_occurrencerow whosecondition_concept_idis 0, non-standard or deprecated takes its source concept’s ‘Maps to’ target (through ‘Concept replaced by’ when the source is deprecated), a valid standard Condition concept. The source concept iscondition_source_concept_id, else the old concept, else the ICD-10-CM / ICD-9-CM code ofcondition_source_valuelooked up without its dot by the diagnosis date. A code that maps to several conditions keeps the first on its row and gets one new row for each other target (add_rows = FALSEkeeps one). The function raises when the vocabulary has no ‘Maps to’ rows and returns the countsnon_standard_before,by_maps_to,rows_added,other_domain,no_targetandnon_standard_after. Elixhauser reads ICD source codes and is not affected; phenotypes and concept-set features that readcondition_concept_idare. Python (likebackfill_drug_concepts()). -
Day-0 and overlapping readmissions. The readmission rule counts an inpatient stay that starts after the discharge day, as the legacy rule did, so a stay starting on the discharge day or inside the index stay is not a readmission.
site_quality_report.pynow always reports, as ranges across sites, the share of index stays with such a stay and their size relative to the counted readmissions (section “Readmission rule”; needs--db-dirand the run’scohort_<site>.parquet).define_study_cohort(merge_episodes_days = 0)is the sensitivity analysis: stays that start on or before the previous stay’s end day plusmerge_episodes_daysare merged into one episode (the first stay’s row, the last stay’s end and discharge), and the cohort is built on the episodes. Off by default (NULL). Python and R. -
UCUM unit conversions before the bounds (behaviour change).
extract_benchmark_features(unit_conversions = "default")converts glucose (mmol/L x 18.016) and BUN (mmol/L x 2.801) to mg/dL, creatinine (umol/L / 88.42) to mg/dL, and albumin and hemoglobin (g/L / 10) to g/dL, byunit_concept_idor, when that is 0, by the unit text. The conversion is applied before the physiologic bounds, so such values are no longer dropped or kept on the wrong scale.DEFAULT_UNIT_CONVERSIONSlists them;unit_conversions = NULL/Noneturns them off;attrs["unit_converted"]gives the converted share per lab.site_quality_report.pyflags a lab whose per-unit medians at a site still differ by a factor of 5 or more after the conversions (section “Lab units”). Python and R. -
observation_periodend-date cap.run_study(observation_period_cap = "YYYY-MM-DD")andreproduce_study.py --observation-period-capend every observation period on that date for the run (a temporary view; the site database is not changed). A site whose extract ends with a spike of period ends near its pull date otherwise looks observed until then. The cap must fall on or after the study end plus the follow-up days. The run record gives the share of periods it shortened per site; without a cap the spike check runs as before. -
reproduce_study.py --sensitivity(run_study(sensitivity = TRUE)): the features are also extracted on every eligible stay, andstay_sensitivity()fits the HistGBM on ten random one-stay-per-patient draws (seeds 1 to 10,--sensitivity-seeds) and on all eligible stays with patient-grouped folds, as in the Nov 11 deliverable. It writes<prefix>_Sensitivity.csv(seed, stays, readmission rate, AUC-ROC, Brier) and adds the summary to the run record; template v0.35.0 cites the seed range in the Discussion. Off by default; it adds roughly the time of one feature extraction and ten model fits. -
Expected and unexpected findings.
run_study(known_source_gaps =)andreproduce_study.py --known-source-gapstake the study team’s list of confirmed source gaps (a mapping, list, JSON file or text file ofcolumn # reason; a key may besite:column). Each data-check finding now has a cause:source_gap(on the list),intentional(a concept-set exclusion),etl_mapping(vocabulary, concept-set coverage, transfer and address checks) orunexplained. A listed gap no longer stops the run. The script prints unexpected findings first, and the run record counts findings by cause. A lab’s intentional concept-set exclusions (ConceptSetExclusionWarning) are listed once per study with the number of sites, not once per site.site_quality_report.py --known-source-gapsmarks those measures expected and gives each lab funnel row a likely cause (no rows with its codes, rows not mapped to its concepts, no numeric value). -
Hemoglobin estimated from hematocrit is one predictor (behaviour change, Kyle after run C18). No site’s extract has a hemoglobin row, so the eDERRI fill made
lab_hemoglobinhematocrit / 3 in every stay: a rescaled copy of hematocrit in the models. When that holds for every stay (hemoglobin_is_hematocrit()), the study run keepslab_hemoglobinand dropslab_hematocrit(and_last) as a duplicate, aslos_dayswas in 0.34.1; one measured hemoglobin keeps both. The run record hashemoglobin_from_hematocrit, and template v0.35.0 says in Section 2.2 that hemoglobin is estimated as hematocrit / 3. The concept sets stay separate (different tests). The models change, so the study must be run again; the saved features can be reused. -
Review fixes (PR 107, before merge).
- The run no longer repeats the observation-period spike as an unexplained library warning: the cohort build’s own check is silenced in the study run, which already reports it as an
observation_periodfinding (or caps the periods). With a cap, an open period (NULL end) keeps its NULL end; it took the cap date. -
backfill_condition_concepts()sets the condition and source concepts in one UPDATE: with an index oncondition_source_concept_id, DuckDB gave the row a new rowid and the second update missed it. - Episode merging: an open stay (no end date) is never the episode’s last stay, and TIMESTAMP visit dates work. Python and R. The documentation says that features extracted on merged episodes still read the first stay’s visit.
- Known source gaps: a missing file given as a
Pathraises the “does not exist” error; a column or group key no longer covers an ETL check (a listedlab_potassiumcannot hide potassium rows that exist but were not mapped; name the check to cover it); the reason text from the private file stays out of the run record; the--compare-topreset note is classified (intentional). -
--reuse-featuresrefuses features saved under older default feature rules (stale_features, new settingfeature_rules= “0.35.0”). - The sensitivity analyses use the primary cohort’s patients only (C18’s seed draws had one stay more), every seed row has a Brier score, and no seeds gives just the all-stays row. Template v0.35.0 prints the all-stays count of the sensitivity run itself.
-
site_quality_report.py: the lab funnel checks the bounds after the SI-unit conversions; a site-scoped confirmed gap is marked expected in the flags. - Medication classes:
disaggregate_combinationsalso marks a hop / ‘Maps to’ target that is itself a combination; packs (‘Contains’) and precise ingredients (‘Form of’) are followed. Python and R. - Template v0.35.0 Section 2.2 says SI-unit values are converted before the plausibility ranges.
- Run C19 review: when hemoglobin replaces hematocrit, Tables 1 and 4 print a Hemoglobin row in Hematocrit’s place (per 1 g/dL in the clinical increments); it had no row although it was a top predictor in Figure 2. The qualifying-stay count of the text is the analysed patients’ stays only, equal to the all-stays sensitivity count (C19 printed 529,826 and 529,825). Reused features from the first 0.35.0 build no longer replay the duplicated period-end warning.
site_quality_report.pynames a lab whose rows are mostly outside the physiologic bounds.
- The run no longer repeats the observation-period spike as an unexplained library warning: the cohort build’s own check is silenced in the study run, which already reports it as an
omopduckdb 0.34.2
Fixes from the run C15 close-out checks and Kyle’s remaining-gotchas review (2026-11-24). Version bump 0.34.1 to 0.34.2; manuscript template v0.34.2. The cohort and the features must be built again.
-
n_secondary_dxcounts the index visit only (Kyle’s choice). When the cohort hasvisit_occurrence_id, a diagnosis dated inside the stay but recorded on another visit (an outpatient, ED or observation encounter, or another inpatient visit) no longer counts. A diagnosis with no visit id still counts by its date. In the C15 close-out, 1 to 9% of the counted codes per site sat on another visit, and the site means would fall by 0.0 to 0.8. A cohort withoutvisit_occurrence_idkeeps the date rule. Python and R. -
backfill_drug_concepts()remaps non-standard drug concepts. A drug row whosedrug_concept_idis not a valid standard concept (non-standard, or deprecated / upgraded) now takes that concept’s ‘Maps to’ target when there is exactly one valid standard target; the old concept goes intodrug_source_concept_idwhen that is empty. The medication classes roll drug concepts up throughconcept_ancestor, which holds standard concepts only, so these rows were missed: 4 to 17% of drug rows per site in the C15 close-out, built by a builder that kept the source concept. Rows with no target or several are left as they are. The result has two new counts,non_standard_beforeandby_maps_to. The step runs before the existing concept-0 fill. -
Stays still in hospital are excluded.
define_study_cohort(still_in_hospital_status=)drops index stays whosedischarged_to_source_valueis a “still in hospital” code (PCORnet DISCHARGE_STATUSSH); it adds the attrition step “Discharged (not still in hospital)”. On in the protocol cohort (PROTOCOL_COHORT_PARAMS) and inbuild_ederri_diabetes_cohort(), off by default indefine_study_cohort(). Such a stay has no discharge, so no 30-day window after it. The legacy notebooks dropped SH with IP and EX; run C10 had 456 SH stays at three sites. OMOP has no standard concept for it, so the rule reads the source value. Template v0.34.2 says so in Section 2.1.1. Python and R. - Tobacco is the latest status up to discharge (Kyle’s choice). The level of the latest tobacco record on or before discharge decides (a PCORnet smoking status, ICD F17 / Z72.0 / 305.1 for current, Z87.891 / V15.82 for former, a never-smoker status); records on the same day go to the higher level. Until 0.34.1 any current-use record ever made the stay “Current user”, so a patient who had quit stayed current. Template v0.34.2 defines tobacco use in Section 2.2. Python and R.
-
RUCA 99 is Missing / Unknown. USDA code 99 (“not coded”: unpopulated tracts, PO-box ZIPs) is no longer counted as Small Town / Rural:
ruca_category(),derive_geography_features()andruca_feature()default tocode_99_missing = TRUE;FALSErestores the reference coding. Python and R. -
ZIP codes keep their leading zeros on the
location.zippath. The converters write a 5-digit ZIP tolocation.zip(the same rule asperson_address_history.zip5; it was the raw ZIP9 or ZIP5, so “8101” stayed 4 digits). The geography readers (geography.zip5_sql(), R.zip5_sql()) turn a stored ZIP into its 5 digits and pad a 4-digit ZIP or an 8-digit ZIP+4; a 3-digit value is left to the ZIP3 fallback, which now also reads a ZIP3 stored as is. Before, the readers took the first run of five digits, so a 4-digit ZIP was lost. Python and R. -
Drugs with no ‘Maps to’ take their single ingredient. In the C16 audit, the drug rows still on a non-standard concept after the remap were deprecated RxNorm drugs (Branded, Clinical and Quant drugs, a few Ingredients) and valid RxNorm Brand Name concepts. The vocabulary has no ‘Maps to’ or valid ‘Concept replaced by’ row for any of them.
backfill_drug_concepts()now gives such a row the concept’s single standard RxNorm Ingredient (by_ingredient) and leaves a combination product as it is. The ingredient comes from the concept itself, its clinical drug, its unquantified form or its pack contents, throughdrug_strengthor an ingredient relationship (RxNorm has ing,Has ingredient,Brand name of,Tradename of). Retired links count, because a deprecated concept keeps only those. A deprecated ingredient takes the standard ingredient of the same name. The medication classes roll up from ATC to ingredients, so an ingredient is enough. One caveat: an ingredient carries no route, so a topical form of a corticosteroid counts as systemic. The remap also raises an error whenconcept_relationshiphas no ‘Maps to’ row, and returnsnon_standard_after. -
Figure 1 fits its page. In run C17, the 12-step Figure 1 at full width pushed the last line of its caption onto the page number. A figure is now narrowed when its height at full text width would exceed 7.2 inches (
manuscript_text.figure_width(); the 12-step flowchart prints at about 90%). -
Two more manuscript checks.
omop_etl.manuscript_checksnow has 10 checks. The new ones flag a collapsed bullet (“.-”, the C15 slip) and any text less than 14 points above a page’s number (the C17 slip). -
Recorded differences from the legacy pipeline (pre-C16 audit). The audit listed four rules as unrecorded or missing. Nothing in the package changes for them:
-
Elixhauser window. The package reads all diagnosis history up to discharge with the protocol’s code lists (
profile="ederri"). This reproduced the grant-scoped deliverable’s flags at 99.99% (0.15.0). A 730-day window appears only in a legacy Table 1 script.extract_elixhauser_comorbidities(lookback_days = 730, end_inclusive = TRUE)reproduces that script. -
Sex. The models use a binary
femaleflag fromgender_concept_id8532, while the legacy Table 1 had a third “Other” level. No cohort patient has gender concept 0 at any site (audit A2c), so the level would be empty. -
BMI from ICD-10 Z68 codes. The Nov 11 feature SQL filled a BMI category from Z68.1 to Z68.4. The package fills BMI from height and weight and from the 365 days before admission (
bmi_fill = "derive_lookback", 0.34.1), which leaves 1.3% missing. A Z68 code gives only a category, not a value, so it is not used. -
Missing discharge date. A legacy helper used admission plus
ADMIT_DURATIONwhenDISCHARGE_DATEwas empty.ADMIT_DURATIONis not a PCORnet CDM field. The package converter uses the admission date, so such a stay has length 0 and fails the 1-day minimum. Run C17 reports how many stays this affects.
-
Elixhauser window. The package reads all diagnosis history up to discharge with the protocol’s code lists (
omopduckdb 0.34.1
Fixes from run C10 and Kyle’s review of the legacy per-site notebooks (2026-11-24). Version bump 0.34.0 to 0.34.1; manuscript template v0.34.1 (one added sentence in Section 2.1). Nothing changes for a database built by this package’s converter except the diagnosis lookup; the two backfill helpers repair databases built another way.
-
backfill_discharge_status(con, supplemental_csv=None)repairs the discharge status of an existing CDM database. A supplemental PCORnet-style file (ENCOUNTERID, DISCHARGE_STATUS) fills the visits whose status is NI, UN, blank or NULL. Every visit’sdischarged_to_concept_idis then set from its source value with the converter’s own mapping (discharge_status_case(),PCORNET_DISCHARGE_STATUS_CONCEPTS). Run C10 found one site whose encounter extract is all NI while the legacy pipeline joined a separate discharge file, and site databases whose builder mapped only “A” and “E”, sodischarged_to_concept_idwas 0 for every stay at every site. The features read the source value and were right, but the cohort’s in-hospital-death and transfer exclusions read the concept. -
backfill_drug_concepts(con)maps unmapped drug rows from their source value: an NDC (11 digits, or a hyphenated 10-digit form padded) through the vocabulary’s ‘Maps to’, else the exact name of a standard RxNorm concept, an ingredient preferred. C10 found a site with a fifth of its drug rows unmapped, their source values plain ingredient names such as “insulin lispro”. - Diagnosis codes are looked up without their dots, and under the other ICD revision when DX_TYPE names the wrong one (Python and R converters). A legacy notebook warned that one site’s DX_TYPE is unreliable.
-
Review fixes (Kyle, before merge).
-
backfill_discharge_status()no longer sets an existingdischarged_to_concept_idto 0 when the source value is NULL or a label the mapping does not know. It still corrects a concept when the code is known. The supplemental join compares trimmed ids. - The diagnosis lookup prefers a valid concept to a deprecated one with the same code. A missing or unknown DX_TYPE (blank, NI, UN, OT) now tries the ICD revision in use on the diagnosis date first (ICD-10-CM from 2015-10-01), then the other one. Before, no lookup was made. Python and R.
-
backfill_drug_concepts()also maps RxNorm codes (RXCUIs of up to 8 digits) to the concept of that code if it is standard, else through ‘Maps to’. The result has a newby_rxnormcount.
-
-
site_quality_report.py: text columns (ruca_category,tobacco, …) are reported by their missing share instead of printing 100% missing, and a site with no value for a measure keeps its column in the wide tables (the C10 lab funnel showed 4 of 5 sites). -
BMI from height and weight, and from the year before the admission (
bmi_fill, Kyle’s choice after run C11).extract_benchmark_features()fills a stay with no BMI recorded during the stay from the stay’s mean height and weight (kg / m^2; a value without a unit is read as inches or pounds, the PCORnet convention). Withbmi_fill="derive_lookback", the default forprofile="ederri", it then takes the latest BMI recorded in thebmi_lookback_days(365) before the admission, and then one from the latest height and weight there. That is what the legacy pipeline did. In C11, between 78% and 99% of the stays missing a BMI had one of these, and at one site most stays had a height and weight but no BMI row, because that site’s builder never computes BMI.attrs["bmi_filled"]counts the stays each step filled;bmi_fill="none"keeps the old behaviour. Python and R. It takes a feature re-extraction to apply. -
The draw samples eligible stays only (decision
ineligible_draw, Kyle after run C12). With a pinned draw (pinned_stays), a patient whose drawn stay is no longer eligible, but who has other eligible stays, now gets one of those stays at random. The draw is seeded byrandom_stateand does not depend on row order (pin_stays(redraw=True)). Before, the patient was excluded at the random-draw step. In C12 that step excluded 966 patients. For 923 of them, the drawn stay had become a transfer or an in-hospital death once the discharge status was repaired."exclude"keeps the old rule. The run record gives the pooled count (random_draw_redrawn), and manuscript template v0.34.1 adds a sentence to Section 2.1 saying how many patients were redrawn and why. The features must be extracted again. -
Behaviour change: the “os” utilization group is observation stays only (Kyle’s choice after the gotchas check).
DEFAULT_VISIT_CONCEPT_GROUPS["os"](Python and R) and theos_conceptsdefault ofextract_velocity_features()are now581385(observation). Outpatient visits (9202) are no longer inprior_os_count,prior_os_los_daysor the velocityprior_ip_os_ed_count; they are counted byprior_outpatient_count. Before, a site whose outpatient records span several days gave a meanprior_os_los_daysof about 15 days. The eDERRIprior_ip_os_ed_count(extract_protocol_history_features()) now also counts 581385 visits; it counted only the custom concept 2000000048, which no site database has, so observation stays were missed. A database whose builder mapped PCORnetOSto another concept needs those visits remapped to 581385 (the package converter already does this). Passvisit_concept_groups=/os_concepts=(9202, 581385)for the old counts. The features must be extracted again. - Run C14 text fixes. Figure 1, its caption and Section 2.1 print “1 patient” for a count of one (they printed “1 patients”). When a run both excludes patients outside the draw and redraws others, Section 2.1 explains the reused draw once; the redraw sentence starts “For N patients …”.
-
Kyle’s review of PR 104.
-
Methods match the BMI fill. The abstract and Sections 2.1, 2.2 and 3.1 of template v0.34.1 say how a missing BMI is filled (
bmi_fill, now in the run record). Section 2.2 says eGFR is computed (CKD-EPI 2021) and how a missing anion gap is filled. Appendix B no longer defines AUPRC, which is not reported. Run C15 found two slips in that Section 2.2 text, both fixed: the BMI and eGFR sentences ate the line break after their bullet, so Laboratory Measures and Medication Exposure ran into the Vital Signs item; and the anion gap sentence named chloride, an empty source column at every site, somanuscript_checksfailed (“chloride 2”). The sentence is now left out when sodium, chloride or bicarbonate is an empty column, since the fill cannot happen. -
Tobacco (behaviour change).
extract_protocol_history_features()reads the PCORnet VITAL smoking status (observation 43054909, by answer concept or PCORnet code) and the tobacco ICD codes with or without dots. A stay with no status is now"Missing / Unknown", not"Never user"; Tables 1 and 4 print that level when it occurs. The legacy Table 1b had 31.8% missing. The converters also read VITAL.TOBACCO when SMOKING has no status. Python and R. Needs a feature re-extraction. -
days_since_prior_ip_edcounts observation stays (581385), as its label “Inpatient / Obs / ED” says and asprior_ip_os_ed_countdoes. Needs a feature re-extraction. - ZIPs. The converters’ dated address table takes ADDRESS_ZIP9 when ADDRESS_ZIP5 is empty and left-pads a ZIP that lost its leading zero (“8101” -> “08101”). Before, such rows had no ZIP. Python and R.
- ‘Maps to’ ignores deprecated rows in every converter loader (Python and R).
-
BMI units. The fill reads “kg” and “cm” from
unit_source_valuewhenunit_concept_idis 0, and treats concept 9326 (the converter’s inch unit) as inches.
-
Methods match the BMI fill. The abstract and Sections 2.1, 2.2 and 3.1 of template v0.34.1 say how a missing BMI is filled (
-
Duplicate predictors leave the models (
drop_duplicate_predictors(),DUPLICATE_PREDICTORS). In C11,los_daysequalledindex_los_daysin every row, anddays_since_last_encounterequalleddays_since_prior_encounterin 82% of rows (they differ only in how a patient with no prior visit is coded). Both pairs were in the model matrix.run_study()now keepsindex_los_daysanddays_since_prior_encounteronly (Kyle’s choice). A column whose counterpart is absent is kept.
omopduckdb 0.34.0
Dr. Rubin’s review of C9 (2026-11-23), made the package defaults so every later build carries it, plus Kyle’s per-site data-quality report. Version bump 0.33.7 to 0.34.0; manuscript template v0.34.0. Models, tables and figures change in presentation only. A run needs the models again, for the SHAP plot and the rounded tables. The features must be extracted again, for the new secondary-diagnosis and outpatient columns, and the site databases rebuilt for the converter’s lab and encounter-type fixes to apply.
-
Table 1 to 1 decimal. Percentages and mean ± SD print with one decimal (
TABLE1_DECIMALS). The Nov 11 deliverable printed 2. -
Tables 2 and 3 to 2 decimals, and the text quotes the same values. The model metrics of workbook Tables 2 and 5 (printed Tables 2 and 3) are rounded to 2 places (
METRIC_DECIMALS,round_metric_text()), so the AUC-ROC, its CI, sensitivity, specificity, F1 and Brier read the same in the tables, the abstract and the Results. The leave-one-site-out mean in the text is the table’s own “Mean” row, not a mean of the rounded site values. The CSV outputs keep full precision. -
Figure 2 is a SHAP violin plot.
plot_shap_beeswarm(kind="violin")is the default. Each predictor’s violin is as tall as the density of its SHAP values and coloured by the mean feature value at each SHAP value, as the shap package’s layered violin is.kind="beeswarm"keeps the dots. The clinical labels are unchanged, and Section 3.5 describes the violins. -
Figure 1’s random-draw exclusion is explained. Section 2.1 and the Figure 1 caption say that the study scores one random draw of a stay per patient, made once and reused in every analysis, and how many patients whose qualifying stays were not in that draw are excluded at the last arrow. The count is read from
<prefix>_CONSORT_Attrition.csv. -
bmi_age_readmission(): readmission by BMI band within each age group, with the share of the age group and the insulin and metformin rates, pooled and with small cells suppressed. It answers Dr. Rubin’s obesity-paradox question. -
scripts/site_quality_report.py: per-site data quality of a run. It reports every model feature (% missing, % yes or mean ± SD [Q1, Q3]), every Table 1 category, the attrition, and, from the site databases, unmapped rows (concept 0) with their top source codes and measurements outside the physiologic limits. Detail per site stays private. A shareable JSON lists the measures where the sites differ, as ranges only. -
drop_last_lab_values()is the step that keepslab_*_lastout of the models, now a function with a test. All-empty columns (the ten measures no site extract had) never enter the model matrix. -
manuscript_checksdrops the page number at the foot of each page, so a phrase that runs onto the next page is read whole. -
Tables 2 and 3 keep trailing zeros. The workbook stores the metrics as numbers, and Excel reads 0.60 back as 0.6, so a column whose values all round to one place printed “0.6”.
metric_cells()prints every metric of the printed Tables 2 and 3 with two places (“0.60”); count columns are left alone. - Lab values the converter dropped (per-site check of Nov 23). At some sites a lab is mostly missing in the features while its LOINC is in the raw LAB_RESULT_CM file. The PCORnet converter (Python and R) now dates a lab row by RESULT_DATE, else SPECIMEN_DATE, else LAB_ORDER_DATE (it used RESULT_DATE only, and an undated row never falls in a stay). It reads the value from RESULT_NUM, else RESULT_NUM without thousands separators or a leading operator (“1,200”, “<0.01”), else RAW_RESULT when that is only a number. A text result stays empty. Rows that converted before convert the same; value_source_value keeps the original text. It takes a rebuild of the site databases to apply.
-
Secondary diagnoses, counted as their name says (
n_secondary_dx). It replacesn_secondary_dx_ccs, which counted distinct standard (SNOMED) concepts dated in the stay. That count included the principal diagnosis, and one ICD code that maps to two concepts counted twice, so it was not the CCS-category count its label claimed. The new column counts the distinct ICD-9-CM / ICD-10-CM codes recorded from admission to discharge (dots and case ignored), less the code(s) of the principal diagnosis: PCORnet PDX = “P”, or a primary condition type or status concept. Table 1 prints “Secondary Diagnosis Count (Index Stay)”, and Section 2.2 says how it is counted. Python and R. -
Prior outpatient visits (
prior_outpatient_count). Table 1 printed “Prior Outpatient / Other Encounter Count” as all prior visits minus inpatient, observation and ED. That also counted visits of other or unknown type, whose share varies by site. The new column counts outpatient (9202, 581477) and telehealth (5083) visits in the 365 days before admission. Table 1 prints it as “Prior Outpatient Visit Count”, and the models get it as a feature. The PCORnet converter now maps ENC_TYPE OT (other) to 0, as it already did NI and UN, instead of to outpatient. Python and R. -
Lab funnel in
site_quality_report.py. For each lab and site it reports the rows whose source LOINC is in the lab’s concept set, and the share that is mapped to the set, undated, without a number, or outside the feature’s bounds, plus the top three units. It shows the step where a lab goes missing. It also counts the rows mapped to the lab’s concepts whatever their source text (a site can store lab names, not LOINC codes, inmeasurement_source_value), and names the concepts that unmapped LOINC rows carry. - Table S4 at 2 decimals, and “Anion Gap” in title case, like the other printed metrics and lab names.
- Percentages at 1 decimal everywhere they are printed: Figure 1’s outcome boxes, Tables S1 and S2, and the readmission rate of the stay-type table, like Table 1 and the text (the C10 review found 10.38% in Figure 1 next to 10.4% in Table 1).
-
The lab funnel attaches the central vocabulary, as feature extraction does. Site files whose concept tables are views on
central_vocabulary.duckdbresolved only the concept-set items that carry a CONCEPT_ID, so troponin I and pCO2 (listed by LOINC code only) showed 0% mapped. The features were not affected.
omopduckdb 0.33.7
Patch release for Kyle’s list for the final draft (C9, 2026-11-23). The cohort, features, models and workbook do not change. Figure 1 is drawn again from a finished run’s files, and the manuscript is re-rendered. Version bump 0.33.6 to 0.33.7; the manuscript text template stays v0.33.6.
-
Figure 1 has one random-stay box. 0.33.5 drew the study’s random draw of one stay per patient as a box of its own (“Randomly selected qualifying stay per patient”) between the grant window and the analytic cohort, so the figure had two random-stay boxes and the patients outside the draw disappeared without an arrow. The grant protocol window box now leads straight into “Analytic cohort: one randomly drawn stay per patient”. The patients whose qualifying stay is not in the study’s draw branch off that down arrow (“Excluded: qualifying stay not in the study’s original random draw”), so every count adds up and every exclusion sits on a down arrow.
figure1_attrition()marks that step withinto_final, andplot_cohort_flowchart()draws no box for it. A run without a pinned list ends at the window step as before. -
redraw_cohort_flowchart(run_dir)draws Figure 1 again from<prefix>_CONSORT_Attrition.csvand the N row of<prefix>_Table1.csv, with no data access. It brings an older run’s figure up to date before a re-render. - Section 2.2 lab list. 0.33.6 read “the laboratories the models used” from the missingness table, which also lists columns with no values at any site. Those are now left out, so the ten empty source columns are named only in the sentence that says they are empty.
-
omop_etl.manuscript_checksturns Kyle’s text checks of a rendered PDF into a function and a command (python -m omop_etl.manuscript_checks Study_Manuscript.pdf). It checks the title on page 1; no “pinned”; no_lastlab or “(last value)”; seven reference rows in Table 4; F1 and no Brier in Table 3; References ending on the last page; each empty source column named once; and no column names in the text. It ignores line breaks inside phrases (“heart”).tests/test_manuscript_fixes_0337.pyruns it on a rendered manuscript and checks that it catches each problem.
omopduckdb 0.33.6
Patch release from a page-by-page audit of the run C8 manuscript (2026-11-22), before the draft goes to Dr. Rubin. The cohort, features, models and workbook do not change; only the printed manuscript does, so a run can be re-rendered from its saved outputs. Version bump 0.33.5 to 0.33.6; manuscript template v0.33.6.
- Counts in text cells get commas. Table 1 printed “123456 Unique Patients” and “12345 (10.00%)”: the workbook keeps those cells as text (as in the Nov 11 deliverable), and 0.33.5 grouped digits in number cells only. Whole numbers inside text cells are now grouped too; dates, ranges, codes and years in sentences are left alone. Units written with a caret print as superscripts (“5 x10^9/L” -> “5 ×10⁹/L”).
- Estimates and intervals stay on one line. Table 4 broke “1.23 (1.11–” / “1.37)” because its long feature labels took the page. In a table wider than the page, text columns are held to 26 characters (they wrap), so number columns keep their width; in the PDF an estimate with its interval, or an interval alone, is never broken across lines, in the tables or the text (the abstract broke “2.34– 2.56”).
- Text (template v0.33.6). The author list is one author per line (it ran on: “manuscript drafting.- Daniel J. Rubin”); “Elixhauser score (van Walraven)” keeps its capitals in a sentence; Section 2.2 names empty columns in words (“heart rate”, not “vital heart rate”) and lists every laboratory the models used (hemoglobin, a top SHAP predictor, was missing); “0.777–0.777” prints as “0.777”; Section 2.1 says once when every site spans the whole window; Section 2.3 gives the F1-tuned C of the logistic regression, and Appendix B says its settings are the fixed baselines; repeated phrases and the unreported AUPRC are gone. See the template’s NOTES.md.
-
Run record. When the caller passes no run record, or only part of one, the manuscript reads the rest from
<prefix>_run.jsonnext to the workbook (C8 printed no qualifying-stay count). -
Tests for these rules (
tests/test_manuscript_fixes_0336.py): no count of five or more digits without commas in any printed table, no interval broken across lines in a rendered PDF, no column names in the prose, one author per line, no template line that eats its newline.
omopduckdb 0.33.5
Patch release after Kyle’s review of run C7 (2026-11-22). The cohort and the saved features do not change; the models, Tables 2, 3 and S4, Figure 2 and the Section 3.5 text change because the models no longer see the last lab values. Version bump 0.33.4 to 0.33.5; manuscript template v0.33.5.
-
Models use index-stay mean labs only. The feature table offers each laboratory twice, as the index-stay mean (
lab_<name>) and the latest in-stay value (lab_<name>_last), and the models used both, while the Abstract, Section 2.2, Table 1 and Table 4 describe the means only (C7’s Figure 2 showed “BUN (last value)”). New decisionlast_lab_values("drop"in both presets,--last-lab-values keepto restore): the_lastcolumns are removed after the features are built, so saved features stay reusable and the run record names the choice. -
Figure 1 wording. The pinned-list step is drawn as “Randomly selected qualifying stay per patient” with no exclusion arrow (“Stay selected for the patient (pinned list)” / “Excluded: no stay on the pinned list” were internal wording). The figure’s CSV and the run record keep the step’s counts.
figure1_attrition()adds anexcluded_showncolumn, whichplot_cohort_flowchart()honours. - Printed tables are sized and formatted for reading (Kyle: C7’s Table 3 was hard to read). Every column was given the same width, so F1, sensitivity and specificity were wide while “0.765 (0.751–0.779)” wrapped. Each column of a printed table is now as wide as its content (a header may wrap onto two lines); text columns are left-aligned and number columns right-aligned; within a column decimals have the same number of places (0.52 next to 0.638 prints as 0.520, a beta of 0.3 as 0.30) and counts of 1,000 or more have thousands separators; PDF table cells are no longer justified or hyphenated (“pa- tients”). Applies to every printed table; the workbook is unchanged.
- Abstract risk factors (template v0.33.5). The two strongest clinical risk factors are still ranked by standardized beta (“by standardized effect”); the significant clinical risk factor with the largest odds ratio is named after them when it is not one of the two (C7: discharge against medical advice, OR 1.88).
omopduckdb 0.33.4
Patch release after Kyle’s review of the run C6 manuscript (2026-11-22). The cohort, features, models and workbook do not change; the printed manuscript, its title and Figure 2’s labels do. Version bump 0.33.3 to 0.33.4; manuscript template v0.33.4.
-
Title. A parameters file without a
"title"left page 1 and the DOCX’sdc:titleas “Study manuscript”. The full manuscript now falls back to its template’s title (layout.json"title": “Multi-Center Benchmark of Traditional Machine Learning Models for 30-Day Hospital Readmission Risk Prediction”); an explicittitleand the parameters’"title"still win, and the tables-only view keeps the neutral title. Newmanuscript_document.template_title(). -
Clinical feature labels. Figure 2 (SHAP) and the Section 3.5 predictor list printed model column names. New
manuscript_tables.feature_label()/FEATURE_LABELSgive each column the label Tables 1 and 4 use (e.g.lab_bun_last-> “BUN (last value)”,elix_mets-> “Metastatic Cancer”,readmission_count_twelve_months-> “Prior Readmissions in Past 12 Months”), and turn unknown columns into words.plot_shap_beeswarm()/plot_shap_panels()use it by default (labels=strkeeps the column names); the text applies it to the SHAP table, so a SHAP table from an earlier run is labelled too. The SHAP CSV keeps the column names. Section 2.2 names its utilization features in words. - Paragraphs and lists. Template lines that end in a block tag swallowed the blank line after them, so the abstract’s Results and Conclusions, the Table 1 caption and twelve other paragraphs ran on from the one before; the Section 2.4 model list was one paragraph. Fixed in template v0.33.4.
-
Short tables keep together. Tables 2 and 3 (performance, leave-one-site-out) and their captions are kept on one page in the PDF (
layout.json"keep_together").
omopduckdb 0.33.3
Patch release after Kyle’s review of the run C5 manuscript (2026-11-21). The cohort, features, models and workbook numbers do not change; Figure 1, the printed manuscript and its title page do. Version bump 0.33.2 to 0.33.3; manuscript template v0.33.3.
-
Figure 1 shows the grant protocol window and ends at the analysed cohort. With
consort_final_steps=False(thedelivered_2026_11_11preset) the window / one-stay-per-patient step was removed from the attrition before Figure 1 was drawn, so the figure went from the last eligibility rule straight to the analytic cohort with an unlabelled drop, while the text described the 2017-01-01 to 2022-09-30 window. Figure 1 now always draws every step, then a “Grant protocol window: index admissionto ” box (its exclusion arrow reads “no qualifying index admission in the grant protocol window”), then the analytic cohort, so the figure, the text and Table 1 give the same N. consort_final_stepsnow affects only the workbook’s Table S3. Newstudy_run.figure1_attrition();plot_cohort_flowchart()takes an optionalexcluded_labelcolumn. A run whose figure does not end at the analysed N records afigure1_cohortwarning. -
“Total qualifying stays” is a stay count. With patient-level CONSORT steps and no one-stay step in Table S3, the text printed the first step’s patient count as the qualifying stays (C5: the same number as Figure 1’s first box, “2.70 per patient”).
run_study()now counts the eligible stays with an index admission in the window (full-history attrition) and writesqualifying_staysto<prefix>_run.json; the text uses it, and prints nothing when it is not known. Features reused from before 0.33.3 do not carry it, so a run with--reuse-featuresleaves the sentence out. -
Printed tables (template v0.33.3). The CONSORT attrition table is no longer printed (Figure 1 carries the same steps); the workbook keeps it as delivered. The length-of-stay table is printed with the sites and “All Sites Combined” as columns and one statistic per row, like Table 1 (
layout.json"transpose"); the workbook keeps one row per site.layout.jsonnow decides what is printed: a table it does not list is left out instead of printed without a number. The paragraph after the eligibility list points to Figure 1. -
Title page from the study team’s parameters. The document title was “
manuscript” unless document_titlewas given, even when the parameters file had a title.render_manuscript_document()now takes the title, an optional subtitle and the author block (names, affiliations, e-mail, corresponding author) from the parameters (--manuscript-params); an explicittitle/authorstill wins, and with neither the neutral title stays. -
References. The literature the text cites by author and year (Pedregosa et al. 2011, Chen and Guestrin 2016, Breiman 2001, Lundberg and Lee 2017, Yuan et al. 2011) is now listed in the References with the software. The PDF uses the same citation processing as the DOCX (
citeproc: true), so both lists have the same style and order and the PDF no longer adds a second “Bibliography” heading. (The C5 PDF itself listed all 13 software entries on its last page; the list was not cut off.) -
Margins. Both formats now have US-letter pages with one-inch margins (
manuscript_document.PAGE_MARGIN). The PDF had 1.5 cm left and right and 2 cm top and bottom; the DOCX set no page size or margins, so Word used its locale’s defaults. The DOCX takes them from a reference document built from the renderer’s own Pandoc default at render time and removed afterwards.
omopduckdb 0.33.2
Patch release after a reviewer check of run C4 (2026-11-20). Table 6 (printed as Table 4) changes for the BP indicators; the prediction models, cohort and features do not change. Version bump 0.33.1 to 0.33.2; manuscript template v0.33.2.
-
Nearly identical “not measured” indicators are one term.
manuscript_regressionmerged missing-value indicators only when they were the same column. Systolic and diastolic pressure come from one reading and are missing together in all but about 120 of some 24,600 stays, so their two indicators were nearly collinear and split one effect into OR 0.41 and OR 1.92 with wide intervals. Indicators that differ in fewer than 2% of the stays where either is missing (INDICATOR_MERGE_TOLERANCE) now enter as one term, missing when any of its measures is missing, labelled with every measure it covers. - The abstract’s risk factors leave out missing-value indicators. The “strongest independent risk factors” sentence ranked every significant term with OR > 1 by standardized beta, so run C4 led with “diastolic blood pressure: not measured”. “Not measured” and “missing” terms describe whether a value was recorded and are no longer ranked.
-
SDI wording follows the run. With
sdi_missing_term=False(thedelivered_2026_11_11preset) missing SDI joins quintile 1 in the reference row, while the Methods said missing ZIPs are not assigned a reference category. The text now says which applies. The study run for the manuscript should set--sdi-missing-term(thepackagepreset already does), which gives missing SDI its own term. - Casing in the text. Labels inside a sentence lower-case only the ordinary words of the feature name: “diastolic blood pressure (mmHg)”, “prior readmissions in past 12 months”, while ALT, BMI, RUCA, HbA1c, pCO2 and the level after “:” stay as written (it printed “aLT”, “bMI”, “rUCA”).
-
The cohort call prints the seed. The Data & Code Availability call shows
random_seed(define_study_cohort’s default, 42, unless the run set one); the stay draw itself is unchanged. -
The printed grid table (Table S5) no longer shows the unrounded
auc_raw/f1_rawcolumns; the workbook sheet keeps them, as tuning selects on them and the delivered comparison reads them. The columns with no observed values are named once per measure.
omopduckdb 0.33.1
Patch release after run C3 (2026-11-20): Figure 1 and the workbook’s titles and index sheet. No number, cohort or model changes. Version bump 0.33.0 to 0.33.1.
-
Figure 1 boxes fit their text. Every text in the cohort flowchart is wrapped to the width it has, measured in the rendered font, and each box is as tall as its wrapped text (the diabetes phenotype step had three lines in a box sized for two, so its text crossed the border and the arrow). Each gap is as tall as its exclusion note, so a long note no longer runs into the next box, and step names are no longer cut after two lines.
omop_etl.study_report.flowchart_overlaps(fig)lists any text that leaves its box or overlaps another; the tests check it on the study’s step names, on very long names and on 15 steps. -
Workbook titles as delivered on 2026-11-11. Table 2 says “5-Fold Grouped CV” again (the folds are grouped by patient) and Table S2 ends with “(N =
)” from the run. Table 1’s title already matched (only its N differs, from the data). -
“Manifest & Index” sheet as delivered.
manuscript_workbook()names the index sheet “Manifest & Index” with the delivered columns (Sheet Name, Manuscript Table Title, Rows, Description / Key Dimension: “Primary Manuscript Table” or “Supplementary Material / Listing”) and a byline row under the title. New argumentsbyline(e.g. “Authors: …”; blank by default, the package stores no names) andsubtitle;run_study()fills the byline fromdocument_authorand the title fromdocument_titlewhen given.export_workbook()takesmanifest_sheet,byline,manifest_headersanddescribe; its defaults are unchanged. Readers already skip both sheet names.
omopduckdb 0.33.0
Minor release: the revisions requested on 2026-11-18 (Figure 1 drawn as a journal cohort figure, the tuning-comparison table dropped, F1 in the cross-site table, reference categories in the regression table), discharge status that tells “other” apart from “missing”, and everything prepared for 0.32.0, which was not released on its own (the versioned manuscript template, the Table 6 estimability fix and the manuscript validator). Version bump 0.31.0 to 0.33.0.
The manuscript follows the code that ran. The template and the cited omop-duck-db version come from
omop_etl.__version__, not the installed distribution’s metadata, so a newer checkout run inside an older image (as the 2026-11-18 reruns were) uses its own template and cites its own version. The utilization features name their columns (prior_IP_OS_ED_count, readmission_count_twelve_months, n_secondary_dx_ccs) as the 2026-11-11 text did, and n_secondary_dx_ccs is described as distinct condition concepts, which is what it counts.Figure 1 follows the usual journal layout (Python).
plot_cohort_flowchartdraws the steps as one column of boxes joined by down arrows, and each exclusion as a horizontal arrow that branches off the middle of the down arrow into the step it belongs to, with “Excluded: did not meet” and its patient count to the right (as in McCoy et al., JGIM 2017). The analytic cohort is joined to the last step and to the two outcome boxes. Long step names wrap instead of being cut at 46 characters. Manuscript template v0.33.0: the tuning comparison is no longer printed. The layout’s main tables are now Table 1, the model performance, the cross-site table and the regression, so the cross-site table is Table 3 and the regression Table 4 of the text, and every reference follows. The workbook keeps the “Table 3 - Tuning AUC vs F1” sheet (the text still names the configurations F1 tuning selected), and the text cites the full grid in the supplement where it cited Table 3. Section 3.2.1 is folded into 3.2.
NOTES.mdlists the changes.The cross-site table reports F1 instead of the Brier score (Python).
build_study_tablesaddsf1_050(F1 of the balanced-trained model at the 0.5 threshold on each held-out site) toLOSO_By_Site, and the workbook’s cross-site sheet shows AUC-ROC (95% CI), F1, sensitivity and specificity. A results table from an earlier release, withoutf1_050, keeps its Brier column.The regression table prints the reference category of each multilevel feature (Python). Age, race, SDI, RUCA, discharge status, tobacco use and BMI each get a row for their reference category (Increment “Reference”, OR “1.00 (reference)”, no beta or p-value) before the levels compared with it, whose Increment now reads “Vs. reference”. BMI keeps its natural order (underweight, normal as reference, overweight, obese). When the SDI missing term is left out, the reference row says that missing joins quintile 1. The fit is unchanged.
Discharge status: “Other” and “Missing / Unknown” are separate (Python). The manuscript’s “Missing / Unknown” counted every stay outside home, home health, SNF/rehab and AMA, so hospice, assisted living or a PCORnet “OT” status was reported as unknown. Under the protocol rule (
profile="ederri"), a stay is nowmissingonly when it has no concept and no informative source value (PCORnet NI, UN or blank); other statuses areother. Table 1 and the regression table show both levels; Table S2 counts only the missing ones. Newederri_disposition_levelholds the rule.Discharge status no longer depends on the source value for HH, RH and AM (Python). Since 0.11.1 the PCORnet ETL writes HH as 32215, RH as 32228 and AM as 32216, but the protocol’s concept sets did not hold these, so those stays were classified only through
discharged_to_source_value, which was compared untrimmed (a space-padded value, as Oracle CHAR columns return, fell to “other”). The concept sets now hold the ETL’s concepts, the source value is trimmed, and the genericDEFAULT_DISPOSITION_MAPmaps 32215 and 32228 too.A quick check of discharge status at each site.
scripts/check_discharge_status.pycounts, for the inpatient stays of the study window, the source values, the concepts and the class each stay gets under the 0.33.0 rule and the previous one, in one query per site. The answers JSON holds pooled counts only (under 11 suppressed); the per-site detail, under anonymous labels, stays with the data.--max-secondsstops it before the next site once the time is up.The delivered comparison finds the document’s cross-site table by its title, not by the number 5 (the manuscript numbers tables in reading order, so it can be Table 4). The concept-set fingerprint reads CRLF as LF, so saved features are not refused as stale from a Windows checkout.
The manuscript is a versioned template filled from the run (Python).
run_study(andreproduce_study.py) now writes the whole manuscript text, not a list of tables:omop_etl.manuscript_textreads the workbook,<prefix>_run.jsonand<prefix>_summary.jsoninto one context, and the Jinja template of the installed version (omop_etl/manuscript_templates/v0.32.0/) turns it into Abstract, Introduction, Methods, Results, Discussion, appendices and supplement, following the manuscript delivered on 2026-11-11. Every number is a variable; conditional phrasing follows the results (which model leads, whether discrimination transports). Table and figure numbers come from the template’slayout.json, so the regression is Table 5 of the text and every reference follows a renumbering. A value the run does not record shows as[not in this run: ...]and is listed in the run record (document.text_missing). The review-board statement, authors and title come from the study team’s own file (--manuscript-params), never from the package.--manuscript-profile tables_only(orOMOP_MANUSCRIPT_PROFILE) keeps the old tables-only document for checking runs. New dependency: jinja2.Check the text against a delivered PDF.
scripts/check_manuscript_text.py --workbook --pdfrenders the template from a workbook and compares it, sentence by sentence, with a delivered manuscript: identical, same words with other numbers, reworded, or absent, by section. The answers file holds counts only; the detail file quotes the delivered text and stays with the data. The template’s deliberate departures from the 2026-11-11 text are listed in itsNOTES.md.Table 6 no longer prints intervals it cannot estimate (Python). eGFR is computed from creatinine, so the two are missing in the same stays and their “not measured” terms were the same column: the model could not tell them apart, and the 0.31.0
packagerun printed intervals running to 10^60. Identical “not measured” terms now enter as one term named after both (“Creatinine / eGFR (2021): not measured”); a flag whose stays all share one outcome is left out; any other exact collinearity stops the run.Manuscript tables are checked before anything is written (Python).
validate_manuscript_sheets(called bymanuscript_workbook, so byrun_study) raisesManuscriptValidationErroron a NaN or infinite value, an interval with swapped bounds, an estimate outside its interval, or an odds-ratio interval above 10^6. Runs with fewer than 50 bootstrap draws skip only the estimate-inside-interval check of bootstrap intervals. Table S1 shows a dash, not “nan”, for a test that has no p-value.The manuscript text reads like the Nov 11 delivery. After the first check against the delivered PDF (90 of 210 sentences identical when rendered from the Nov 11 workbook), the template restores the delivered section numbers and “(Section 2.1.1)” references, the feature-count lead-in (columns, empty columns, binary and continuous counts, now in
<prefix>_summary.json), each model’s hyperparameters (read fromdefault_model_grid, so they match the code), the cohort bullets, the formulas of Appendix B, the odds-ratio note with a worked example, the SHAP sample size and figure captions, and thedefine_study_cohortcall (from the run record’s newcohort_params). Figures carry a Quarto id, so they are numbered once (“Figure 1”), and Pandoc now sees every heading and figure (a missing blank line had turned some into paragraph text). The check script lays the rendered text out as the PDF’s text reads and finds the run’s figures next to its workbook; lists use a serial comma as delivered.NOTES.mdlists the remaining deliberate differences.The
packagepreset follows the Nov 11 deliverable except where it was wrong.address_tie_break="first_listed",attrition_mode="full_history"andtable6_increments="clinical"now matchdelivered_2026_11_11. The package keeps its own rule forconcept_sets,table6_missing,sdi_missing_term,consort_final_stepsandaddress_undated, each a correction of the delivered workbook (see the vignette table).Delivered comparison: a site sheet with fewer than half of the delivered rows in common is listed in
14_layout_differs_sheetsinstead of being called ambiguous, andcompare_study_deltas.pyprints “N differing cells” above its summary.
omopduckdb 0.31.0
Minor release: Table 6 gives each mostly-unmeasured lab or vital a “not measured” term instead of median imputation alone (the package default; the delivered_2026_11_11 preset keeps median imputation); the delta tool lists every cell that moved; and a fixed, committed method compares a rerun with the delivered manuscript. Version bump 0.30.0 to 0.31.0.
-
Table 6 handles missing measures with a “not measured” term (Python). New decision
table6_missing(run_study(table6_missing=...),reproduce_study.py --table6-missing,manuscript_regression(missing=...)).indicator, the newpackagedefault, adds a 0/1 “not measured” term (labs and vitals) or “missing” term (other continuous measures) under each measure with at least 11 missing and 11 measured stays, and fills the missing values with the mean of the measured stays, so the measure’s OR is estimated from the stays where it was measured, per 1 SD of those stays. A lab is measured because a clinician ordered it, so whether it was measured carries risk information of its own; median imputation alone put every unmeasured stay at a typical measured value, which pulls the OR of a mostly-unmeasured lab towards 1 and moves the other terms with it (in the 0.30.0 rerun, adding the four new labs this way moved 56 of 86 Table 6 rows).mediankeeps the old rule, and thedelivered_2026_11_11preset pins it, so the comparison with the Nov 11 workbook is unchanged (checked: the median path reproduces the previous golden workbook exactly). The synthetic golden workbook is regenerated for the new default. -
The delta tool lists every cell that moved (Python).
scripts/compare_study_deltas.pyused the tolerances ofcompare_workbooks(0.01 absolute and 2% relative), so a 0.001 AUC change or a moved CI bound was not listed, and the 0.30.0 rerun needed a separate exact-string check. The script now compares exactly (every number and the text) unless--tolerant(with--atol,--rtol).compare_workbooks(..., text=True)also lists text-only changes, andworkbook_deltas/delta_summaryaddmax_abs_delta, the largest change of any number in a cell. A range written with a hyphen (0.728-0.735) is no longer read as a negative upper bound. -
A fixed method for comparing a rerun with a delivered manuscript (Python). New
omop_etl.delivered_compareandscripts/compare_with_delivered.pyanswer the standard questions of the clean-run prompts (sheets, labels, titles, cohort N, differing cells per sheet, Table 2 and LOSO AUCs, Table 3 selections, Table 6 direction and p < 0.05, site letters across sheets and in the DOCX / PDF, numbers quoted in the delivered PDF that changed, and what changed since a previous answer set). Site rows are paired by their numbers, since letters are reassigned between runs, and the pairing is reported as unambiguous or not. It writes an answers JSON with aggregates only (no site letters or per-site values) and a detail Markdown that stays with the data. Each run used to count items such as the quoted numbers with its own ad hoc script, so counts were not comparable between runs. -
Delivered comparison, after its first run on the real data. Table S3 sites are now paired by their stages (remaining stays and patients per stage) rather than by position, so a step that only one workbook has no longer makes the pairing ambiguous; the answers name the ambiguous sheets (
14_ambiguous_sheets). Item 15 checks that Table 5, S1 and S3 list the sites in the same order of size (S3’s last step is not the final cohort under the delivered layout). The “(benchmark)” suffix of the delivered workbook is ignored in Tables 3 and S4. Table S4 is compared by model and configuration, whatever its other columns (the delivered workbook lists each configuration once per selection rule), and every sheet reportscells_compared, so “0 differing” with nothing compared shows. Item 17 counts changed numbers in prose lines only (count,pages), since the PDF prints the tables and so holds every changed cell;count_all_textkeeps the old count.
omopduckdb 0.30.0
Minor release: the four 0.29.0 labs (troponin I, lactate, pCO2, pO2) reach the manuscript workbook and document; a new concept_sets decision lets presets pin the lab and vital definitions, and delivered_2026_11_11 pins the pre-0.29.0 lists; Dockerfile.dgx builds from a plain clone. Version bump 0.29.0 to 0.30.0.
-
The four 0.29.0 labs reach the manuscript (Python). Troponin I, lactate, pCO2 and pO2 entered the features, the models and the CSVs in 0.29.0 but not
MANUSCRIPT_LABS, so the workbook (Table 1, Table S2, Table 6) and the DOCX / PDF / QMD built from it left them out. They now have rows in all three tables, in alphabetical order with the other labs. Withtable6_increments="clinical"lactate is shown per 1 mmol/L and pCO2 / pO2 per 10 mmHg; troponin I stays per 1 SD, because conventional (ng/mL) and high-sensitivity (ng/L) assays differ 1000-fold in unit. Note that Table 6 median-imputes missing labs, and these four are measured in a minority of stays. -
Presets pin the lab and vital definitions (Python). New decision
concept_sets(run_study(concept_sets=...),reproduce_study.py --concept-sets):bundled(this release’s concept sets),legacy_2026_11_11(the plain LOINC lists of 0.20.0 to 0.28.1, unchanged across those releases, kept frozen inomop_etl.concept_sets.legacy_feature_codes()), or an exact bundled version such as2026.11.4, which fails on a release that ships another. Thedelivered_2026_11_11preset now pinslegacy_2026_11_11, so a rerun on 0.29.0 or later against the Nov 11 workbook compares only cohort and modelling changes, not the 0.29.0 lab expansion and the four new labs (whose rows are then absent). Under the legacy lists,concept_set_coveragefindings are allowed automatically (the old lists are known to miss codes) and still recorded. The run record’sconcept_setsnames the version used, and--reuse-featuresrefuses features built under the other definitions. Thepackagepreset is unchanged (bundled). -
Dockerfile.dgxbuilds from a plain clone. It copiedomop-learn-repo/andpipeline/from the parent eDERRI folder, sodocker buildfailed atCOPYfor anyone else. The repository is now the build context (docker build -f Dockerfile.dgx -t omop-duck-db:dgx .), and the two eDERRI folders are an optional named context (--build-context ederri=<folder that holds them>); without it the image has empty placeholders and says so. A failed omop-learn install is now reported instead of hidden by|| true. NewARG BASE_IMAGEreplaces the NGC base, for a build check without a GPU. Checked by building from a plain checkout, with and without theederricontext, on a CPU stand-in base (not the NGC image). - README and the deep-learning vignette no longer say the DGX Spark path is untested on the device or that Oracle transfers are unit-tested only; they point to
testing/tested-environments.md.
omopduckdb 0.29.0
Minor release: the Docker image runs exactly Python 3.13.17 (it was Ubuntu’s 3.12), checked in CI, the run record names the platform it ran on, and the manuscript cites omop-duck-db (with its version) and its other software; silent data gaps (an address table not found, a feature group missing for nearly every stay, unmatched pinned stays …) now stop the study run instead of passing; and lab, vital and medication features are OHDSI concept-set files resolved through the vocabulary. Version bump 0.28.1 to 0.29.0.
-
The Docker image runs an exact, pinned Python (3.13.17), checked in CI. Until now the image used whatever
python3its Ubuntu base (noble) ships, which is 3.12, while the study’s reference workstation runs 3.13; nothing pinned it. The Dockerfile now hasARG PYTHON_VERSION=3.13.17and installs that CPython build with uv (into/opt/python); the build stops if the venv reports another version, and the newscripts/check_image_python.shfails the CI and release image jobs unlesspythonandpython3in the built image are exactly the pinned version. The systempython3is no longer installed in the runtime image.Dockerfile.dgxkeeps the Python of NVIDIA’s PyTorch container, because its CUDA build of torch is compiled for that Python. -
The run record names the platform (Python).
run_environment()(theenvironmentblock of<prefix>_run.json) now also records the operating system (platform),machine,cpu_count, whether it ran in a container, the XGBoost build (compiler, OpenMP) and the BLAS / OpenMP thread pools with their thread counts (no file paths, host or user names). Same-version libraries on Windows and on Linux can still differ in the last digits of a model’s predictions, which moves threshold metrics such as sensitivity at 0.5 for a held-out site; the record now shows when two runs came from different platforms. -
The manuscript cites its software, including the exact omop-duck-db version, through grateful_py.
<prefix>_Manuscript.docx/.pdf/.qmdnow open with a Software section (“The study was run with omop-duck-db version 0.29.0 [@omopduckdb] … We used Python version 3.13.17 [@python] and the following Python packages: duckdb v…, pandas v…, scikit-learn v…, …”) and end with a References list built from the new<prefix>_Manuscript.bib. The version numbers are read from the installed packages at run time (importlib.metadata), never typed into the text, so the document names the versions that produced its numbers;relabel_outputs()re-renders it with the versions recorded in the run’s<prefix>_run.json. New helpersomop_duck_db_version()andsoftware_citations()(moduleomop_etl.package_citations);render_manuscript_document(cite_software=False)leaves the section out.grateful_py>=0.2.1is now a dependency (pure Python, needs only Jinja2) and both Docker images check at build time that it imports and that the cited omop-duck-db version matches the package. The privacy scan reads.bibfiles as text; the citations carry package metadata only (name, version, authors, homepage). -
Silent data gaps now fail the study run (Python). A run used to “pass” when
--address-table autodid not find the study’s dated address table: every stay got no ZIP, SDI / RUCA were 100% missing (sdoh_missing = 1), and the only sign was a warning that scrolled past. Now:-
Address table. New
omop_etl.geography.resolve_address_table()/find_address_tables().address_table="auto"uses the one non-empty table or view whose name containsaddressand that hasperson_id, zip5, address_start, address_end, preferred(so a study’s own<study>_address_historyis found, not onlyperson_address_history). With several it stops and names them; with none it falls back toperson.location_idonly when that holds ZIPs, and otherwise stops and lists what it looked at. A name given explicitly must exist and have those columns.run_study()resolves it per site before the cohort is built, so a missing table fails in seconds.--address-table person_locationchoosesperson.location_idon purpose. -
Data-gap gate. New module
omop_etl.data_gaps. Each site is checked as soon as it is built, and the run stops before any modelling (DataGapError;scripts/reproduce_study.pyexits with code 3 and writes<prefix>_data_gaps.json) when: a feature group is missing, or all zero, for at least 95% of the site’s stays (--data-gap-threshold); a whole group could not be computed; a single lab, vital or medication class has no concept or no value for any stay at the site (accepted by its column name, e.g.--allow-data-gaps lab_ldl); no address table was usable; at least 10% of the stays with a ZIP have one that is not in the SDI or RUCA table; the vocabulary (concept_ancestor) was not reachable; the transfer exclusion matched nothing because discharge status was never mapped; the site’s inpatient stays start more than 90 days after the study window starts or end more than 90 days before it ends; observation periods pile up on one end date (events filled with the build date); pinned stays were not found (they used to be dropped silently), or the pinned list names sites that are not in the run; a site has no stays; or--reuse-featuresfound features saved with other settings (window, address table, input files, preset …).--allow-data-gaps NAME ...(run_study(allow_data_gaps=[...]): a check, a feature group, a feature column orall) accepts a gap on purpose; it is still recorded. New--check-data(run_study(check_only=True)) builds every site, reports every gap of every site in one pass and stops before modelling; with--reuse-featuresthe next full run reuses those sites. Warnings only (recorded, not fatal): a medication class that is 0 for every stay, most addresses chosen by the “earliest after admission” fallback, and--compare-tounder the default preset. -
Run record.
<prefix>_run.jsongainsaddress_table(requested, and the table used per site label),data_checks(every finding, allowed gaps and warnings alike, by site label and as shares, never counts or names, plusshare_missing_by_group: the share of stays missing each feature group at each site, andgeography: per site, the share of stays with a ZIP, how the address was chosen, and the share of ZIPs not in the SDI / RUCA tables),inputs(file name and SHA-256 of the RUCA, SDI, pinned-stay and comparison files),sdoh,transfer_source_valuesandsite_labels(how labels were assigned). Library warnings raised while a site is built are captured into it instead of being lost, with database paths and site keys replaced by labels, and their dates and counts masked (<date>,<n>), since those messages were not written for a shareable record. The--sitesorder, label seed and full command line go to<prefix>_run_private.jsonin the private folder only: with the real names they would reveal which label is which site. -
No longer silent. The medication-class warnings (a class that resolves to no concept, so its column is all zero) were suppressed inside
extract_benchmark_features(); they are now raised. A disposition source-value column that cannot be read, and RUCA / SDI values that are not numbers (read as missing), now warn. The no-ZIP, missing-vocabulary, protocol-history-skipped and unmapped-transfer warnings areDataGapWarnings (aUserWarningsubclass), so plain library use behaves as before. -
R:
derive_geography_features(),extract_benchmark_features()and study features use the sameautorule through newresolve_address_table()/find_address_tables(). - Results are unchanged for a run whose inputs were complete. A run that relied on
autowith a differently named address table now uses that table, so its SDI / RUCA columns change from all missing to real values.
-
Address table. New
-
Labs, vitals and medication classes are OHDSI concept sets, resolved through the vocabulary (Python and R). Their definitions move from code lists in the code to concept-set files in
inst/extdata/concept_sets/<domain>/<name>.json(domainslabs,vitals,medications_ederri,medications), in the format ATLAS, Circe and Capr use, with amanifest.json(column order and version). New moduleomop_etl.concept_setsand R functionsload_concept_set(),resolve_concept_sets(),loinc_coverage()and friends resolve them the way Circe does: descendants throughconcept_ancestor,includeMappedthroughMaps to, excluded items removed, and an item given by vocabulary and code looked up inconcept.BENCHMARK_LAB_LOINCS,BENCHMARK_VITAL_LOINCS,EDERRI_MEDICATION_SPECS,DEFAULT_LAB_LOINCS,DEFAULT_VITAL_LOINCSandDEFAULT_MEDICATION_CONCEPTSare now read from those files, so Table 1 and the models use the same definitions.-
Why: a lab listed one LOINC code per specimen, so a site that codes total bilirubin in blood (34543-9) instead of serum or plasma (1975-2) had an empty
lab_bilirubin_total, and nothing said so. A LOINC test has no descendants, so codes of one analyte are linked through their LOINC parts instead. -
New check
concept_set_coverage: a lab whose in-stay rows at a site use LOINC codes outside its set (same component; 1% of the analyte’s rows or more) fails the run, naming each code, its share, and whether it is another unit type (for example umol/L) or not a blood specimen. Accept it with--allow-data-gaps lab_<name>. When the vocabulary has no LOINC part links the run warns that the check could not run. -
New
scripts/build_concept_sets.py: expands each lab set from a vocabulary (every LOINC test with the same component, property, scale and time aspect in blood, serum or plasma; molar codes never join a mass-unit set), and with--legacyshows which set holds each code of a legacy lab roll-up. It reads only vocabulary tables. -
Expanded from LOINC 2.82 (concept sets version 2026.11.4). Every lab set now holds the blood, serum and plasma codes of its analyte and unit type (for example total bilirubin 1975-2 plus 42719-5 in blood and the arterial and venous codes; sodium, potassium and chloride in venous, arterial and capillary blood; total CO2 next to bicarbonate). Red-cell, urine, cord-blood and plasma cell-count codes are left out. A set may carry
"expansion"(blood,seed_systemsornone) and"expand_from": hemoglobin grows only from 718-7 (g/dL), pO2 and pCO2 stay arterial, troponin I is not expanded because conventional and high-sensitivity assays share a property but not a unit. -
New labs matching the legacy roll-ups:
lab_troponin_i,lab_lactate,lab_pco2andlab_po2(with plausibility bounds), and fasting glucose (1558-6 and its blood codes) joinslab_glucose. - A code is resolved by its vocabulary and code first, and the stored
CONCEPT_IDis used only when the code is not in the vocabulary.concept_set_coveragefails only for a missed code of the same property in blood, serum or plasma; a code in another unit type or specimen (arterial pCO2 next to total CO2) is a plain warning. - The concept-set fingerprint is part of the
--reuse-featuressettings and of<prefix>_run.json(concept_sets). Results change: labs fill in at sites that use the added codes, and the four new labs enter the models.
-
Why: a lab listed one LOINC code per specimen, so a site that codes total bilirubin in blood (34543-9) instead of serum or plasma (1975-2) had an empty
omopduckdb 0.28.1
Patch release: Quarto failures in the run record show the cause, and runs where the usual Quarto cache folder is read only (sandboxed Windows) can still render the DOCX / PDF. No change to cohort, features or model numbers. Version bump 0.28.0 to 0.28.1.
-
Quarto failures say what went wrong, and sandboxed runs can render the DOCX / PDF (Python). When Quarto fails,
<prefix>_run.jsondocument.notenow gives the start of Quarto’s error output (where the cause is, for examplePermissionDenied ... (os error 5)) as well as its last lines, with colour codes removed and the home folder, cache folders and account name replaced; before, only the last three lines were kept, which for Quarto are its stack trace (core/cri/cri.ts). Newcache_dirinrender_manuscript_document()(document_cache_dirinrun_study()andrelabel_outputs(),--quarto-cache-dirinscripts/reproduce_study.pyandscripts/relabel_study.py, or theOMOP_QUARTO_CACHE_DIRenvironment variable) points Quarto’s cache (LOCALAPPDATA,APPDATA,XDG_CACHE_HOME,XDG_DATA_HOME,DENO_DIR) at a writable folder. Without one, a render that fails on a permission error is retried once with a temporary cache inside the private build folder, which is removed afterwards;document.cachein the run record says which cache was used. New helpersrenderer_env()andstderr_summary().
omopduckdb 0.28.0
Minor release: the PostgreSQL round trip is now a quick functional check by default (first run on real site data: all 5 sites passed in under 10 minutes).
-
PostgreSQL round trip is quick by default (Python).
scripts/postgres_roundtrip_check.pynow cuts each table to a repeatable sample of at most 10,000 rows (--sample-rows) before the round trip, so a site takes minutes instead of hours; it tests the copy code, not data volume.--fullrestores the every-row run;--backupalways copies every row. Newomop_etl.embedded_postgres.sample_site().
omopduckdb 0.27.0
Feature release: live Oracle -> DuckDB -> PostgreSQL copies proved value by value against Oracle (first run on a site’s live Oracle 19c: every table passed), the embedded PostgreSQL copy kept as a verified backup with restore helpers, and an arm64 CI job (Oracle, deep models, Delta Lake, embedded PostgreSQL) as on a DGX Spark. 0.26.0 was never tagged or published, so this release also carries everything listed under 0.26.0 below. Version bump 0.26.0 to 0.27.0.
-
The PostgreSQL copy as a real backup (Python). The round trip already left a full copy of every table in PostgreSQL; it can now be kept, refreshed, checked and restored on purpose. New in
omop_etl.embedded_postgres:backup_site()(DuckDB file -> a staging schema, checked value by value, then swapped in within one transaction, so a failed refresh never damages the previous copy;if_changed=Trueskips an unchanged file),backup_raw_files()(the same for a site’s raw text files, through PostgreSQL’sCOPY),register_backup()(adopts a schema stored by an earlier round trip after checking it against its DuckDB file, without copying again),backup_status(),verify_backup()(re-checks every table against fingerprints recorded at backup time with PostgreSQL alone, or value by value against the current DuckDB file or raw files withagainst=),restore_site()(rebuilds a DuckDB file with its views and checks it),restore_raw_files()anddrop_backup(). A manifest in schemaomop_backuprecords anonymous labels, table fingerprints and DuckDB views; no site names or source file names. Newscripts/postgres_backup.py(backup,register,status,verify,restore,drop) for any number of sites under their anonymous labels.scripts/postgres_roundtrip_check.pygains--backup(keep the copies as managed backups) and--drop-after(delete them after a check-only run). Not yet run on real site data. -
Oracle -> DuckDB copies of live site tables, proved against Oracle (Python). New module
omop_etl.oracle_roundtripandscripts/oracle_roundtrip_check.py. The live data stays in Oracle;mirror_oracle()copies tables into a new DuckDB file inside oneSET TRANSACTION READ ONLYtransaction, so Oracle refuses any write and every query sees one snapshot while the site keeps loading. Oracle computes a per-column fingerprint of each table itself (counts, exact sums / min / max, and an order-free sum of MD5 hashes of every value, with text converted to UTF-8 so aWE8MSWIN1252database hashes like DuckDB), DuckDB computes the same on the copy, and the two are compared;row_level=Truere-reads each table through python-oracledb’s Arrow path and compares row for row withEXCEPT ALL. Types are exact: unconstrainedNUMBERcolumns are probed and becomeBIGINTor the smallest exactDECIMAL(only values noDECIMAL(38, s)can hold becomeDOUBLE),DATEkeeps its time of day, andTIMESTAMP(9)values finer than a microsecond are reported as a loss instead of being truncated silently. Oracle’s fingerprint is saved next to the copy, soverify_duckdb_copy()andverify_postgres_copy()re-check the DuckDB file, a copy read back from PostgreSQL, or the embedded PostgreSQL backup (store_site) against Oracle without connecting to it.write_back()(opt-in, writes) completes Oracle -> DuckDB -> Oracle through scratch tables that are dropped afterwards. The script does it for one site under its anonymous label, with--pg-dir/--read-backfor the PostgreSQL leg (--skip-duckdb-pg-checkdropsstore_site’s slower per-column check, which the Oracle-vs-PostgreSQL fingerprint already covers), and writes a record with no schema, server, account, host or row counts. Tested against Oracle Free 23 (CI, amd64 and arm64) and on one site’s live Oracle 19c (WE8MSWIN1252, 22 PCORnet and analysis tables, read only): every table passed Oracle -> DuckDB, Oracle vs PostgreSQL and Oracle vs the DuckDB read back from PostgreSQL (testing/records/oracle-19c-live-roundtrip-2026-11-15.md). -
CI on arm64, as on a DGX Spark. The live-database workflow gains an
oracle-arm64job: the Oracle round trip against Oracle Free’s arm64 image, the deep-model, Delta Lake and embedded PostgreSQL tests with the DGX image’s extras (CPU torch), andscripts/dgx_smoke_test.pyon CPU.Dockerfile.dgximports the new module in its build-time smoke test. The GPU itself is still checked only on the Spark (gpu-check,dgx-smoke).
omopduckdb 0.26.0 (not released; included in 0.27.0)
Feature release: an embedded PostgreSQL server from Python (new [postgres-embedded] extra) with DuckDB <-> PostgreSQL round-trip checks, in both Docker images (on the DGX image run it with docker run --user omop); and model tables that no longer depend on the order of --sites (checked on a real five-site run: reversed --sites gives a workbook identical on all 11 sheets). Version bump 0.25.0 to 0.26.0.
-
PostgreSQL inside Python, and DuckDB <-> PostgreSQL round trips (Python). New optional extra
[postgres-embedded](pg0-embedded, MIT) starts a private PostgreSQL server from Python with no install and no admin rights (127.0.0.1 only, free port, generated password, data kept in a folder you choose).pgembedis supported as an alternative on Python 3.12+ (backend="pgembed");pgserverwas not used (no release since 2024, no Linux arm64). New moduleomop_etl.embedded_postgres:EmbeddedPostgres,store_site()(DuckDB -> one schema per site withCOPY, then a value-levelverify_transfer),load_site()(back into a DuckDB file with the CDM v5.4 types),compare_duckdb()(row-for-row comparison of two DuckDB files),load_text_files()(raw text files through PostgreSQL’sCOPY, checked against DuckDB’sread_csv) andsite_schema(). Newscripts/postgres_roundtrip_check.pydoes this for any number of sites under their anonymous labels, with the raw-file check and a Delta Lake version 0 vs version 1 comparison, and writes a record without site names or row counts. Guide:testing/postgres-in-python.md. New CI jobembedded-postgresruns it on Linux x64 and arm64, Windows and macOS. Both Docker images include the extra: the GHCR image (amd64 and arm64) runs as a non-root user already andscripts/container_smoke_test.pynow round-trips a table through the embedded PostgreSQL;Dockerfile.dgxgains a non-rootomopuser (docker run --user omop) andstudy-smokeswitches to it. Not yet run on real site data. -
Fixed:
verify_transfer()failed on column or table names that are reserved words (for examplenote_nlp.offseton PostgreSQL), and on mixed-case names, because it did not quote server identifiers. It now quotes them with the server dialect’s rules. -
Fixed: model tables depended on the order of
--sites.run_study()pooled the site frames in the order given, and the cross-validation folds and the upsampled training rows are drawn by row position, so the same data with--sitesin another order gave slightly different Tables 2 to 5 and S4 (a real five-site rerun changed 118 cells; the descriptive tables did not change). The pooled rows are now ordered by site key, person and stay before modelling, so the order of--sites, the anonymous labels and the order a query returns rows no longer change any model number. Results differ slightly from runs made with 0.25.0 or earlier for this reason only.
omopduckdb 0.25.0
Feature release: anonymous multi-site study runs for any number of sites, a DOCX / PDF manuscript from the run, relabelling a finished run, a privacy scan before write-out, and arm64 (DGX Spark) Docker images with Quarto. Version bump 0.24.0 to 0.25.0.
Multi-site studies that stay anonymous with any number of sites (issue 69). Python runs the study; R and Python share the label helpers.
-
What was broken. (1)
scripts/reproduce_study.py --labelspaired labels with sites withzip, so with more sites than labels (six sites, five labels) the extra site got no label and appeared in every table under its own name; a labels file missing a site did the same throughrun_study. (2)run_studywrotefeatures_<site>.parquet,cohort_<site>.parquetandattrition_<site>.csvinto the output folder, so the folder that held the results named every site and failed the privacy scan on any real run. (3) The manuscript document was built outside the package from separate hard-coded letter maps, so a re-issue under new letters could show old letters. (4) A changed mapping meant re-running the whole study. -
Labels for any number of sites.
validate_site_labels()(Python and R) refuses a site without a label, two sites with one label, an empty label and a label equal to a site name; extra entries are allowed, so one consortium-wide mapping file serves every site.run_study()andreproduce_study.pyuse it;--labelswith a count different from--sitesis an error. R gainsassign_site_labels(),save_site_labels(),load_site_labels()(same JSON file as Python),relabel_sites(),relabel_output_files()andcheck_run_privacy(). -
Shareable output folder. Per-site intermediates go to
private_dir(--private-dir, default<out>_private).reuse_features=Truemoves them out of an older output folder and applies the current labels. -
Manuscript DOCX and PDF from the run.
run_study()writes<prefix>_Manuscript.qmd,.docxand.pdfby default (omop_etl.render_manuscript_document(); Quarto, PDF through its bundled Typst; Pandoc fallback for the DOCX; without a renderer the.qmdis kept and<prefix>_run.jsonsays what was not rendered). The document is built from the run’s workbook, so its numbers and letters are the workbook’s. No author unlessdocument_author/--doc-author; the Word creator fields are cleared.--no-documentskips it. -
Privacy check before write-out. With
site_names/--names-file(and the site keys of three or more characters) the run scans its output folder and the staged DOCX / PDF; a hit raisesRunPrivacyError(the script exits 1), the manuscript is not moved into the output folder, and the run record counts hits by file only. The scanner (omop_etl.run_privacy,scripts/check_run_privacy.py) now reads DOCX paragraph text (a name split across Word runs), PDF text, metadata and attachment names (new dependencypypdf) and.typfiles. -
Relabel a finished run.
relabel_outputs()/scripts/relabel_study.pycopy a run’s shareable outputs with every label swapped in one pass (workbook cells and sheet names, CSV, JSON, Markdown, HTML, run record), rebuild the DOCX / PDF from the relabelled workbook and scan the result; the numbers do not change. Images are copied unchanged and listed. -
Tests (synthetic data): 3, 5 and 8 sites end to end with a scan of the shareable folder for the site names, a six-site run with five labels refused, a name in the document failing the run, the script’s exit code and
--no-document, a five-site relabel whose workbook, CSV, JSON, qmd and DOCX / PDF equal the original once the letters are mapped, DOCX split-run and PDF scanning; R tests for the helpers. CI installs Quarto in thepython-onlyjob so the DOCX and PDF are rendered and checked there. - Guides:
testing/run-the-study-at-your-site.md;testing/rerun-with-new-site-letters.mdcovers relabelling. -
Fixed after the first real five-site run. (1) The privacy scan read the image and font parts inside a DOCX / XLSX as text, so a short site name matched by chance inside a compressed figure and the manuscript was withheld (a false positive, not a leak). Binary parts are no longer read as text; a PNG’s text chunks (author, title, description) are scanned instead, inside zip files and for standalone PNGs (
omop_etl.run_privacy.png_text). The Rcheck_run_privacy()skips binary parts the same way. (2) When the scan withheld the manuscript,<prefix>_run.jsonstill listed the files andmissing: []; it now recordswithheld: true, no files and every format as missing. (3)<prefix>_run.jsonrecords the Python and library versions (run_environment()): two runs with the same inputs give the same workbook cell for cell (new test, real model grid), so model-performance differences between machines come from library versions such as scikit-learn or XGBoost. -
Docker images for the DGX Spark and the manuscript. The GHCR image (
Dockerfile) is now published forlinux/amd64andlinux/arm64(DGX Spark / Grace), each built on a native runner and joined under one tag. It now includes the Quarto CLI (with its bundled Pandoc and Typst, so the PDF needs no LaTeX) and the R packagesrmarkdownandknitr; the Delta Lake writer was already there through thedevextra.Dockerfile.dgxgains Quarto and thedeltaextra, and astudy-smokecommand. Newscripts/container_smoke_test.pyrenders a manuscript DOCX and PDF, scans them, writes and reads a Delta table and checks R + rmarkdown; CI builds the image on amd64 and arm64 and runs it inside both, and the release runs it before publishing.
omopduckdb 0.24.0
Feature release: run records no longer name sites, an output privacy scanner, and a live-server to_sql round-trip check. Version bump 0.23.0 to 0.24.0.
-
Run record no longer names sites (Python).
<prefix>_run.jsonkeyedtimings_secondsby real site name (site_<site>), and those timings follow site size, so a run record shared with the anonymous letters still identified the sites. The keys are now the anonymous letters (site_Site A). The per-site intermediates (features_<site>.parquet,cohort_<site>.parquet,attrition_<site>.csv) still carry the real name and stay private; they are written to the output folder for resuming, not for sharing. -
scripts/check_run_privacy.py. Scans an output folder for real site names (file names, text, zip/xlsx parts, parquet columns and values) before it is shared; reports hits by name position so the report itself is safe to paste; exit code 1 on any hit. -
scripts/verify_server_roundtrip.py. Loads a synthetic edge-case table throughto_sql, checks it withverify_transferon a live server (written for Oracle, runs on any SQLAlchemy URL), drops it and writes a record without the URL, host or user. The connection URL comes from an environment variable. Oracle’s empty-string-is-NULL difference is reported as a known difference. It passed on one live Oracle 19c server (record and limits intesting/tested-environments.md). That run also showed thatto_sqlsilently replaces non-Latin text with¿when the database character set is not Unicode (WE8MSWIN1252), which counts and sums cannot detect;verify_transfer(content=True)does. -
verify_transfer(content=True). Also compares text, DATE, TIMESTAMP and BOOLEAN columns by value with an order-independent fingerprint, so changes that counts and sums miss (non-Latin text replaced by?in a non-Unicode database, shifted dates) are caught;content_examples=nlists differing values (off by default, because they are data). -
to_sqland non-Unicode Oracle databases. On Oracle,to_sqlreadsNLS_CHARACTERSETand, for a known non-Unicode set (for exampleWE8MSWIN1252), counts text values the server cannot store and warns with column names and row counts (never values);on_unencodable="error"refuses the load and rolls it back,"ignore"skips the check. Newnvarchar=True(or a list of columns) creates text columns asNVARCHAR2/NCLOB(national character set), which keeps any text. Character-semanticsVARCHAR2(n CHAR)was already the default. The offline tests pin the warning, the error, the ignore path and the DDL;scripts/verify_server_roundtrip.py --nvarcharchecks it on a live server: on Oracle 19c withWE8MSWIN1252the Japanese test column round-trips by value withnvarchar=True. NVARCHAR2 columns are sized from the data (at most 2000 characters); longer text becomes NCLOB, and the server-side non-null count works on LOB columns. -
Fixed:
Dockerfile.dgximage faileddgx-smokewithRuntimeError: Numpy is not available. The extras upgraded NumPy to 2.x over the NGC base image’s 1.x, which its torch cannot use; NumPy is now pinned to the base image’s version. Built and run on a DGX Spark (GB10):gpu-checkanddgx-smokepass (testing/tested-environments.md). -
testing/rerun-with-new-site-letters.md. Runbook for re-issuing results under a new random site mapping.
omopduckdb 0.23.0
Feature release: Delta Lake export, age_method as a study decision, BigQuery vs DuckDB and R vs Python parity checks, and fixes for R BigQuery id precision, SQLite DECIMAL export and live SynPUF runs. Version bump 0.22.0 to 0.23.0.
-
Study run and lakehouse additions (Python only).
age_methodis a study decision:run_study(age_method=)andreproduce_study.py --age-methodchoose"completed_years"(both presets) or the deprecated"year_difference"; an explicit value overridescohort_params, and<prefix>_run.jsonrecords the rule actually used.export_to_delta_lake()(new[delta]extra) writes a DataFrame, DuckDB relation, DuckDB table or Parquet file / directory to a Delta Lake table, withscripts/export_delta_lake.pyas its command line;scripts/compare_study_deltas.pywrites<prefix>_Deltas.csv,<prefix>_Delta_Rows.csvand an optional Markdown summary for two manuscript workbooks.export_to_andromeda()registers aDecimaladapter so DuckDBDECIMALcolumns export to SQLite. R has norun_study()or Delta writer, so these stay Python-only; R’sdefine_study_cohort()already takesage_method. -
BigQuery vs DuckDB and R vs Python parity checks (R and Python, same rules).
run_duckdb_demo()builds the BigQuery demo’s cohort (native Circe compiler) and features (newinst/sql/duckdb_demo_features.sql, the DuckDB twin of the GoogleSQL template) on DuckDB;copy_demo_sample_from_bigquery()copies a fixed person sample and theconcept_ancestorrows it needs;compare_cohorts(),compare_features(),compare_column_types(),check_id_precision(),compare_demo_summaries()andcompare_demo_outputs()compare the results (Python:omop_etl.backend_parity, pluspython -m omop_etl.backend_parity compare-outputs). Offline,tests/test_backend_parity.pyruns the GoogleSQL sent to BigQuery on DuckDB (transpiled back with sqlglot) against the native DuckDB path, on a CDM with ids above 2^31 and 2^53, and runs the R and Python DuckDB paths on the same file.inst/examples/bigquery_duckdb_roundtrip.qmdfills in four of its six TODO checks (live sections 4a to 4d). Fixed: the R BigQuery demo downloaded results withbigint = "integer", which turns any id above 2^31 - 1 into NA; it now readsinteger64and keeps key ids exact. Python writes the demo SQL files byte for byte as R does. Fixed: the demo could never run live on the public SynPUF dataset, which has novisit_occurrenceormeasurementtable; both demos (R and Python) now create empty stand-ins in the scratch dataset (stub_visit_occurrence,stub_measurement) and say so in the report, so the cohort, demographics and type checks run while utilization reads 0. -
Testing plan.
testing/real-world-testing-plan.mdsets out what CI can and cannot cover forto_sqlon a live Oracle, the DGX Spark GPU image and post-0.11.1 features on non-synthetic data, and what needs a person on those machines.
omopduckdb 0.22.0
Documentation release: vignettes consolidated from 14 to 12 and grouped on the website; OHDSI_INTEGRATION.md is now the ohdsi_integration vignette; new runnable inst/examples/bigquery_duckdb_roundtrip.qmd (offline by default) checks the BigQuery demo and a BigQuery to DuckDB copy. No code changes. Version bump 0.21.0 to 0.22.0.
omopduckdb 0.21.0
Fixes from the 2026-11-12 external review of 0.20.0. Most of the critical and major findings landed first in PR #59 (first bullet below); this release adds the items listed after it. Version bump 0.20.0 to 0.21.0.
-
Review fixes after the v0.20.0 review.
parse_omop_datetime()now converts 12-hour times ('4:15 PM') to 24-hour before parsing; before, ISO dates silently dropped the AM/PM. A full-modeetl_pcornet()re-run empties the tables it fills in one transaction instead of doubling them.consortium_patient_overlap()withholds the size of any site smaller thanmin_cell_count(the self-pair row revealed the suppressed count). R gains an exportedload_vital()matching Python: fallback standard concepts (never 0), derived BMI,plausible_ranges, a returned summary. Race01/04now map to American Indian or Alaska Native (8657) and Native Hawaiian or Other Pacific Islander (8557); ethnicityNI/UN/OTmap to 0 not ‘Not Hispanic’;DX_TYPE10/SMmap to ICD10CM/SNOMED and unknown types no longer fall to ICD10CM.run_dqd(check_levels="TABLE")accepts a single string and rejects unknown levels; Pythonload_vocabularyloadsdrug_strength. The README worked examples use the real argument names and return shapes.build_schema()is re-runnable (a no-op on a complete schema, an error on a partial one), runs in a transaction, and takeskeys = TRUEto apply primary keys and indices (DuckDB cannot apply the CDM foreign keys). Era, observation-period,cdm_sourceandremap_all()rebuilds are transactional;import_omop()and the BigQuery loader no longer leave half-emptied tables. Operator-supplied table names (output_table,target_table,cohort_table, export tables, attach aliases) are validated and COPY paths and options are quote-escaped. PCORnet discharge statusAmaps to ‘Discharged alive’ (4161979), no longer Home; the AMA feature category uses 32216;remap_cdm_table()prefers the custom map, then ‘Maps to’, then standard concepts; the DQD CONCEPT check counts ids missing from the vocabulary; the Usagi import skips unreviewed and targetless rows. -
More review items. Table 1 SMD is
Inf(not 0) for perfectly separated constants (Python and R);export_site_summary()extra tables use complementary suppression (group_cols=) and are refused when they carry an unlisted count-like integer column;parse_omop_date()’s format list andDEFAULT_DATETIME_FORMATSaccept%Y%m%d; the age features, risk scores, cohort-flow age and readmission SQL macro use completed years (see Breaking below). -
OHDSI tool checks. New parity scripts
scripts/ohdsi_parity_cohortmethod.R,ohdsi_parity_cohortconstructor.Randohdsi_parity_deepplp.R(wrapped bytests/testthat/test-ohdsi-parity-scripts.R, gated onOMOP_RUN_HADES_TESTS=true) compare CohortMethod 6.0.3, CohortConstructor 0.6.3 and DeepPatientLevelPrediction 2.4.0 with direct counts,execute_circe_cohort()and the labels; the omop-learn backend was run against the real omop-learn classes. ATLAS 3, Data2Evidence, Phenelope and GIS remain unchecked (seeOHDSI_INTEGRATION.md). Fixed:as_plp_data()returned aCovariateDatawhose$did not dispatch under current Andromeda / FeatureExtraction. -
Breaking: age is now computed in completed years.
define_study_cohort(),build_readmission_cohort(),build_end_of_life_cohort()and the age features (extract_patient_features(),extract_temporal_features(), the risk scores, the cohort-flow age, the ML age column, the readmission SQL macro) useddate_diff('year', ...), which counts calendar-year boundaries and so reported people born late in the year as one year older (a 17-year-old passedmin_age = 18). The defaultage_methodis now"completed_years";"year_difference"still works to reproduce older results but warns that it is deprecated. On the randomized test CDM the RFC example drops 11 under-18 index stays (189 to 178 at the age step); the legacy-builder golden files were regenerated. Circe age criteria keep the Circe definition (year of event minus year of birth), andextract_benchmark_features()keeps its pipeline-equivalent calculation. -
Documentation. The README is now a short entry point (install, quick start, guide index, key caveats); the long walkthroughs moved to vignettes, grouped on the website (Build and operate; Cohorts and features; Clinical tools and multi-site work; Machine learning and OHDSI; Cloud and demos; Reproducibility and status).
OHDSI_INTEGRATION.mdis now theohdsi_integrationvignette;NOTES.mdandoperationsmoved intostatus_and_roadmapanddatabase_and_mapping; the three study-feature vignettes (R, Python, across sites) are onestudy_featuresvignette; the portable cohort definition notes are a section ofstudy_cohorts_and_features. New runnable exampleinst/examples/bigquery_duckdb_roundtrip.qmdchecks the BigQuery demo and a BigQuery to DuckDB copy (offline by default). README.Rmd and README.md are in sync again.
Highlights of this development version: the cohort definitions ship with the package (inst/cohorts); the native Circe compiler evaluates many more constructs and accepts 521 of the 707 PhenotypeLibrary definitions (was 368), each new construct checked against the official engine; cohort reconciliation, feature ablation, run comparison, bundle concept checks and a worked end-to-end example give a downstream study tools for the questions it meets; the DQD catalog exists in R and was compared with the official DataQualityDashboard; and the intermittent Windows R crash was traced to a failed DuckDB extension load and fixed.
omopduckdb 0.20.0
Version 0.20.0: any number of sites, parameterised aggregate-only results report (Python). Includes the unreleased manuscript-profile work (decision presets, delivered-geography rules, golden workbook, deltas, random anonymous site letters, Table 5 method). Sites: the study run, the manuscript workbook, the report facts and assign_site_labels() work for any number of sites (tested with 1, 2, 8 and 30; labels continue Site AA, Site AB, … after Site Z; the earlier 26-site limit is gone); the federation classes already took any sites mapping. Report: render_results_report() / scripts/render_manuscript.py gain sheets, exclude_sheets, formats, write_csv, write_facts, sentences, min_cell, max_rows, embed_figures and css. The report holds aggregate tables only: a sheet with an identifier column (person_id, mrn, zip, …) or more than max_rows rows is refused, counts below min_cell (default 11) print as <11, and the facts file names the workbook by file name, not path. - Decision presets, delivered-geography rules, golden workbook, deltas and results report (Python; address options also in R). STUDY_DECISIONS / STUDY_PRESETS / resolve_decisions(): every choice that moves the manuscript numbers (address_tie_break, address_undated, sdi_missing_term, table5, attrition_mode, consort_final_steps, table6_increments) is a named option; run_study(preset="package" | "delivered_2026_11_11") sets them together, explicit arguments override, the values used are written to <prefix>_run.json; reproduce_study.py --preset, per-decision flags, --list-decisions, --s1-s3-labels. Address rules: tie_break="first_listed" (the address stored first; same on every run) and undated="first" (an undated address outranks dated ones, as in the study pandas pipeline) reproduce the delivered SDI and RUCA for all 225,939 stays (0 differences); the earlier arbitrary setting matched only the totals. manuscript_regression(increments="clinical") shows continuous rows per 10 mmHg, 30 days and so on; sheet_site_labels relabels Tables S1 and S3 only. Deltas: workbook_deltas(), delta_summary(), <prefix>_Deltas.csv, scripts/check_golden.py, and a committed golden workbook with tests/test_golden_workbook.py. Anonymous labels: assign_site_labels() / save_site_labels() / load_site_labels(), run_study(site_labels="random", label_seed=, labels_out=), --labels random; the mapping is no longer written to <prefix>_run.json. Report: render_results_report() / scripts/render_manuscript.py (facts JSON, table CSVs, Markdown and HTML). With the delivered preset and pinned stays Tables 1, 2, 4, S1 and S2 match the November 11 workbook with 0 differing cells, Table 6 differs in 2 of 281 cells, Table 5 in 3 sensitivities, Table 3 in 1 cell. - Table 5 follows the delivered method (Python). build_study_tables(loso_model="tuned_xgboost") (the F1-tuned XGBoost of Table 3, median-imputed) with evaluate_loso_transport(balance_method="upsample") (minority class upsampled with replacement, as in Tables 2 to 4) is now the leave-one-site-out default; on the legacy feature file it reproduces the delivered Table 5 exactly. loso_model="hist_gbm" and balance_method="undersample" keep the previous behaviour.
omopduckdb 0.19.0
Version 0.19.0: manuscript site labels, workbook similarity checks, reproduction guide (Python). Site labels: run_study(site_labels=) takes the anonymous site labels from the caller (the site-to-label mapping is intentionally not stored in the repository, so the manuscript sites cannot be identified); without it labels follow command-line order. workbook_similarity(new, old) and SIMILARITY_TOLERANCES: named, adjustable checks (Table 2 and 5 AUCs, Table 6 odds ratio, direction and p < 0.05 verdict, Table 1 cells) for “the new run reproduces the delivered manuscript”; run_study(compare_to=...) writes <prefix>_Similarity.csv. README: Reproducing the delivered manuscript (measured differences of an unpinned default run and their causes) and Status and roadmap.
omopduckdb 0.18.0
Version 0.18.0: deep-model driver, DuckDB-to-server transfer, manuscript table options, address tie-break options (Python). Deep models (omop_etl.deep_models, [deep] extra): make_mlp_fit_predict() (torch multilayer perceptron; median imputation and scaling fitted on the training rows, early stopping, GPU when visible, seeded), deep_oof_predictions() (out-of-fold probabilities on the study_folds() folds with the balanced_training_indices() 50/50 sample the traditional models use), deep_study_tables() (a Model_Performance row with bootstrap CI and, with a site column, the leave-one-site-out table) and device_report(). evaluate_loso_transport(model_type=) now also takes "mlp" or any fit_predict(x_train, y_train, x_test) callable, so a SARD / DeepPLP training loop can be wrapped and scored with the same folds, leave-one-site-out evaluation and tables. scripts/dgx_smoke_test.py (and the dgx-smoke command in Dockerfile.dgx) prints the CUDA report and trains and scores the network; it ran here on CPU only, so the DGX Spark image and the GPU path are still unverified. DuckDB to server (omop_etl.load_sql): to_sql() copies DuckDB tables or the result of a query (a feature table, a cohort) into an Oracle / PostgreSQL / SQL Server / Snowflake schema through SQLAlchemy in chunks (portable column types, upper-cased identifiers limited to 30 characters on Oracle, if_exists fail / replace / append, credentials masked in errors) and verify_transfer() compares row counts, non-null counts and numeric sum / min / max on both sides, so a DuckDB to Oracle to DuckDB round trip can be shown lossless (the other direction already exists as import_omop() / from_sql()). Tested against SQLite and with the Oracle DDL compiled offline; never run against a live Oracle server. Manuscript table options: the leave-one-site-out table now also carries the uncalibrated balanced-trained metrics a manuscript reports (brier_uncalibrated, sensitivity_050, specificity_050); manuscript_workbook(table5="manuscript"|"calibrated") picks which Table 5 is written (default: the manuscript’s), sdi_missing_term=False leaves the SDI-missing term out of Table 6 as the manuscript did, and run_study(attrition_mode="full_history") lays Table S3 out as the manuscript does (every rule over all history, then the window and one stay per patient last; one extra cohort build per site); run_study() also returns timings. Address ties: derive_geography_features(tie_break=) / extract_benchmark_features(address_tie_break=) choose between addresses that tie on every rule key: "deterministic" (default; later start, lowest ZIP), "highest_zip", "ambiguous_missing" (no ZIP when the tied ZIPs differ) or "arbitrary" (engine order, not reproducible; closest to a pipeline with no final key). Python only; R keeps the deterministic rule. Fixed on the way: the MLP needs a few hundred gradient steps, so default lr=2e-3, batch_size=256; to_sql() once reset its own cursor by describing the table after opening it (caught by the round-trip test). Not done: training a network on the real cohort, wrapping the existing pipeline/ SARD and DeepPLP trainers, the DGX build, live Oracle tests.
omopduckdb 0.17.0
Version 0.17.0: manuscript layout, one-call study run, workbook comparison, shared folds for deep models (Python). omop_etl.manuscript_tables reshapes the generic study tables into the manuscript’s sheets: manuscript_table1() (age bands, sex, ethnicity, race, SDI, RUCA, discharge status, tobacco, BMI bands, blood pressure, the eight medication classes, 14 labs; n (%) or mean ± SD for the whole cohort, the readmitted and the not readmitted), manuscript_completeness() (Table S2), manuscript_consort() (Table S3, all sites combined then per site), manuscript_regression() (Table 6: adjusted OR (95% CI), standardised beta, p, grouped as printed), manuscript_workbook() (Tables 1-6, S1-S4 under the same sheet names as a previous deliverable) and compare_workbooks() (cell-by-cell comparison of two such workbooks by the numbers in each cell, returning a summary and every differing cell). omop_etl.run_study() (and scripts/reproduce_study.py) goes from per-site OMOP DuckDB files to the pooled feature table, tables, figures, the manuscript workbook and, with compare_to=, the comparison with a previous workbook; pin_stays() / pinned_stays= reproduce an earlier stay-per-patient draw exactly from a CSV of stay ids instead of the package’s MD5 draw. For deep models: study_folds() (the folds tune_models() uses, as index lists), balanced_training_indices() (the 50/50 training sample) and performance_from_predictions() (a Model_Performance row, with bootstrap CI, from any model’s out-of-fold probabilities) put a neural network in the same tables as the traditional models. Fixed: the generic discharge-disposition map matched nothing at sites that store the disposition as a source value (all stays came out disp_other); profile="ederri" (or disposition_map="ederri") now applies the protocol’s rule (concept sets or source value HO / HH / SN / RH / AM). Checked on the five real site databases (225,939 patients, stays pinned to the manuscript’s list, SDI/RUCA from the study’s address table, 100 bootstraps): against the current manuscript workbook, Table 2 (model performance), Table 4 (stay type) and Table S1 (length of stay) were identical, every Table 1 row outside SDI and RUCA was identical (discharge status, tobacco, BMI, blood pressure, medications and all labs included), and Table S2 differed only in the SDI-missing row. Remaining differences: SDI and RUCA rows (about 1,000 to 1,500 of 225,939 stays move between categories because the pipeline breaks address ties arbitrarily); a tie between two equally good logistic-regression settings in Table 3; Table 6 follows from the geography differences and from the package keeping an “SDI missing” term the manuscript omits (the RUCA-missing odds ratio absorbs it there); Table S3 applies the date window as step 2 instead of last; Table 5 uses calibrated leave-one-site-out metrics instead of 0.5-threshold sensitivity and specificity, and the manuscript’s Table 5 labels the sites in a different order from its Tables S1 and S3 (the same label denotes a different site in Table 5 and in Tables S1 and S3, with very different test-patient counts), which should be checked before submission. Not done: deep-model training on real data, a Docker build on the DGX Spark, live Oracle tests.
omopduckdb 0.16.0
Version 0.16.0: pkgdown site completeness and issue reporting. The reference index now lists every exported topic (the benchmark-feature, recalibration, capacity-tier and vocabulary-export helpers documented on extract_benchmark_features were missing), the site navbar links to the GitHub repository, bug reports and feature requests, and .github/ISSUE_TEMPLATE adds structured bug-report and feature-request forms. Includes the study-report additions on this branch (Table 1, logistic regression and missingness tables, extra_tables for the workbook, and the leave-one-site-out leakage fix).
omopduckdb 0.15.0
Version 0.15.0: study report tables and figures, offline Oracle tests, DGX Spark image (Python; includes the items listed under “After 0.14.0” below). New module omop_etl.study_report turns a one-stay-per-patient feature table into the aggregate tables and figures of a readmission-prediction manuscript, so a study no longer needs its own copies of these scripts. Tables: prepare_model_matrix() (dummy coding, all-NaN columns dropped), oof_predictions() (stratified or patient-grouped k-fold; median imputation, scaling and 50/50 upsampling fitted on the training fold only), default_model_grid() (logistic regression, random forest, HistGBM, XGBoost; benchmark configuration first), tune_models() (every configuration scored out of fold; benchmark vs best by AUC-ROC vs best by F1, the AUC-vs-F1 table, and the performance table of the F1-tuned models with 95% bootstrap intervals, optionally a patient cluster bootstrap), stay_type_auc() (first vs later admission), random_stay_draw() / seed_sensitivity() (the seeded one-stay-per-patient draw and its stability across seeds), los_by_site(), index_stay_dates() (observed admission and discharge dates, discharges after the window end), export_workbook() (one formatted .xlsx with a manifest sheet) and build_study_tables() (runs them and writes CSVs, a summary JSON and the workbook). Counts below min_cell are blanked in subgroup tables. Figures: plot_cohort_flowchart() (Figure 1 from an attrition table), explain_models() (SHAP for the four benchmark models on the last cross-validation fold: exact linear SHAP for logistic regression and exact tree contributions for XGBoost, so neither needs shap; random forest and HistGBM use shap.TreeExplainer when installed), shap_ranking(), plot_shap_beeswarm() and plot_shap_panels() (the 2 x 2 composite); build_study_tables(figures=True, attrition=...) writes them. Figures are drawn with matplotlib alone. Checked against a study’s existing grant-scoped outputs on 225,939 patients (about 10 minutes on one workstation): the performance table, the first-vs-later-stay table and the length-of-stay table were identical to the hand-built scripts’ output, the tuning table had identical numbers (only the row order and the “(benchmark)” label differ), and the per-site dates matched. The leave-one-site-out table in build_study_tables() uses evaluate_loso_transport() (balanced training, prior-shift calibration), which is a different estimator from an uncalibrated pooled split, so its AUCs are close to but not identical with a hand-built script’s. random_stay_draw() reproduces a numpy-seeded draw; define_study_cohort(sample_stay_rule="random") uses the MD5-based rule, and the two choose different stays. extract_benchmark_features() checked against a study’s own pipeline on one real site (about 63,000 stays), then fixed. The cohort (define_study_cohort) reproduced the pipeline’s all-stays cohort exactly (same stays, outcomes and attrition; one_per_patient=False, sampling_rule="earliest" gives its chronological stay_rank, while sample_stay_rule="all" ranks in stable random order). The features differed in four ways, now addressed: (1) physiologic bounds: single vital and lab measurements outside plausible limits are dropped before the stay mean / latest value (bounds="default", DEFAULT_BOUNDS; bounds={name: (min, max)} overrides, bounds=None turns them off; a BMI of 562000 no longer reaches the table), and WBC reported per uL is rescaled to 10^3/uL (DEFAULT_RESCALE); (2) LOINC lists: BENCHMARK_LAB_LOINCS is a superset of the core panel (ALT often arrives as 1743-4 and was missed; also glucose 41653-7, HbA1c 17856-6 / 17855-8, bicarbonate 2026-3, AST 30239-8) and adds hematocrit, alkaline_phosphatase, ldl, a measured anion_gap, and the vitals heart_rate, respiratory_rate, body_temperature, oxygen_saturation (BENCHMARK_VITAL_LOINCS); a measured anion gap is kept and Na - Cl - HCO3 only fills stays without one; (3) hematocrit_fallback fills a missing hemoglobin with hematocrit / 3; (4) profile="ederri" selects the protocol’s medication classes (EDERRI_MEDICATION_SPECS: ATC A10BA, A10A, A10BB, C09, C02, C07, H02, C10), the window [discharge - lookback_days, discharge] (medication_window="pre_discharge") the hematocrit fallback, and the protocol’s Elixhauser definitions (extract_elixhauser_comorbidities(code_table="ederri"), the ICD-9 / ICD-10 prefix lists of the study protocol in inst/extdata/comorbidity/elixhauser_codes_ederri.csv, generated from the protocol’s own SQL; weights and columns as in the Quan table; read over all history up to discharge, elixhauser_lookback_days=None; Python only). With profile="ederri" every vital, lab and medication column that both sides produce was identical to the pipeline’s on that first site (exact agreement, including the outlier-prone BMI, WBC and AST, and ALT and hemoglobin now found). The generic medication classes and the pre_admission window remain the default because they are a different clinical definition, not an error. The 31 Elixhauser flags went from 92% mean agreement with the pipeline (Quan table, 365 days; the worst flag, other neuro, 59%) to 99.99% (lowest flag 99.98%): the Quan lists and the 365-day window explained the gap (all history alone only reached 96%). The residual stays differ because the pipeline matches dotted prefixes literally (E11.9) while the package normalises dots away, so an undotted E119 is uncomplicated here and complicated there. Choosing the definitions: use, don’t use, or both. extract_benchmark_features(profile=) takes None (generic definitions), "ederri" (the study protocol’s) or "both" (generic columns as usual plus the protocol’s Elixhauser flags and medication classes under an ederri_ prefix, so the two can be compared side by side); each choice can also be made alone with elixhauser_code_table (quan / ederri / both), elixhauser_lookback_days, medication_set (generic / ederri / both), medication_window (new pre_discharge), hematocrit_fallback and include_protocol_history, and an explicit argument always wins over the profile. New extract_protocol_history_features() returns the protocol’s history columns (prior_encounters_all_count, prior_ip_os_ed_count, days_since_prior_encounter (any visit), days_since_prior_ip_ed, readmission_count_twelve_months, n_secondary_dx_ccs, elix_pre_index_conditions_count, tobacco); on that site all eight were identical to the pipeline’s. R: all of the above is ported to the R package (extract_benchmark_features(), extract_elixhauser_comorbidities(code_table=), extract_protocol_history_features(), BENCHMARK_LAB_LOINCS, BENCHMARK_VITAL_LOINCS, DEFAULT_BOUNDS, DEFAULT_RESCALE, EDERRI_MEDICATION_SPECS); on that site the R and Python tables with profile="both" were identical in all 162 columns. Other sites: the cohort reproduced the pipeline’s all-stays cohort exactly (same stays, outcomes, stay_rank and attrition) at all five sites (from about 63,000 to about 605,000 stays per site), and with profile="ederri" every comparable vital, lab, medication and Elixhauser column agreed (at least 99.9%, almost all exactly) at each of them, and the eight protocol history columns were identical (exact) at all five; the default (generic) definitions agreed on only 24 of about 60 columns, which is the reason the profile exists. SDI / RUCA checked on real data. derive_geography_features() and extract_benchmark_features(include_sdoh=True) were run on all five site databases with the study’s own RUCA crosswalk, Robert Graham Center ZCTA table, fixed cut points (25, 41, 58, 77) and dated address table (ederri_address_history) and compared with the pipeline’s geography. The address rule (in effect at admission, else latest before, else earliest after; ZIP beats no ZIP; preferred; nearest start) reproduced the pipeline exactly at two sites (ZIP, RUCA category and SDI quintile 100%) and at the other three for 64% to 99.8% of ZIPs; every one of the ZIP differences checked (all of them at two sites, a random 3,000 at the third) was an exact tie on the documented rule, two addresses with the same start date, both in effect and neither preferred, which the pipeline resolved arbitrarily. Changed: ties are now broken deterministically (later start, then lowest ZIP), so repeated runs and R and Python agree (R and Python gave identical ZIP, rule, RUCA and SDI for all stays at one of the sites); extract_benchmark_features(address_table=) (Python and R) selects the dated address table, because the default "auto" reads person_address_history, else the usually empty person.location_id, and returns no ZIP at all for a database that keeps its history elsewhere (it now warns when no stay has a ZIP); and sdoh_missing is now 1 when the SDI quintile is unknown (it was 0 for stays with no ZIP because the unknown level is the string "SDI: Missing / Unknown", not NA). Descriptive tables and the workbook. New table_one() (every column overall and by outcome, median [Q1, Q3] / n (%) with Mann-Whitney or chi-square p, counts under min_cell shown as <11), logistic_regression_table() (unpenalised multivariable fit, odds ratios with Wald 95% CIs; flags per flag, other columns per 1 SD; composites such as the Van Walraven score are left out by lr_drop_cols) and missingness_table() (percent missing overall and per site). build_study_tables(descriptive=True) adds them, plus a CONSORT_Attrition table from attrition, and extra_tables={name: DataFrame} adds any further sheet to the CSVs and the workbook. prepare_model_matrix() now also drops cohort bookkeeping and outcome-derived columns (outcome_flag, outcome_date, y, index_date, …), every date column, and any column identical to the label (with a warning): found when the first end-to-end run on a single site gave AUC 1.000 because extract_benchmark_features() returns a copy of the label as y. End to end on one site (random stay per patient, 2017-01-01 to 2022-09-30, 14,226 patients, 10.1% readmitted, profile="ederri"): cohort, 121 feature columns and all tables ran in under two minutes with 10 bootstraps, AUC-ROC 0.69 (HistGBM, XGBoost) to 0.71 (random forest, logistic regression). Pooled five-site run with repo defaults (random stay per patient, 2017-01-01 to 2022-09-30, profile="ederri", SDI/RUCA from the study’s address table, 100 bootstraps): 225,939 patients, the same total and the same per-site counts as the current grant-scoped deliverable, 10.34% readmitted (deliverable 10.00%; the package’s MD5 stay draw differs from the study’s numpy-seeded draw, so about 0.1% of stays differ). AUC-ROC HistGBM 0.732, XGBoost 0.732, random forest 0.722, logistic regression 0.722 (deliverable 0.731, 0.731, 0.721, 0.724); first-admission AUC 0.696 and later-admission 0.690 (0.695, 0.691); feature means and missingness (albumin, ALT, AST, HbA1c, LDL, BMI, blood pressure, secondary diagnoses, prior encounters) within about 0.1% of the deliverable’s feature table. Leave-one-site-out AUROC 0.71-0.73 per site (mean 0.72; deliverable mean 0.712); Brier scores differ because evaluate_loso_transport() calibrates to the held-out prevalence. Fixed on the way: the leave-one-site-out table in build_study_tables() was fitted on the raw frame and so on the label copy among its columns (AUROC 1.0); it now uses the prepared matrix. The CONSORT table here applies the date window as step 2, so intermediate counts differ from the deliverable’s, which windows last; the final N is the same. Oracle: tests/test_oracle_offline.py pins the Oracle-specific behaviour that needs no server (reflected NUMBER / DATE / VARCHAR2 / CLOB types, upper-case identifiers, credential masking, generated DDL linting and the 30-character identifier limit, DATEADD translation); it does not replace live-db.yml, and nothing here has been run against a real Oracle server. Docker: Dockerfile.dgx builds the Python side on an NGC PyTorch base for a DGX Spark (CUDA torch kept, deep / oracle / bundle / zarr / sklearn extras, omop-learn, an import smoke test and a gpu-check command); it has not been built on the device. Tested on synthetic data and a local 225,939-patient study table only. - After 0.14.0: deep-dataset and study-feature gaps (Python; the vocabulary changes also in R). Fixed [MASK] token: vocabularies built with mask_token=True (the default of extract_multimodal_deep_dataset; R build_concept_tokenizer(mask_token = TRUE)) reserve id 5 for [MASK] and start concepts at 6, so special-token embeddings line up across sites and pre-training runs. Legacy vocabularies (mask_token=False, manifest format 1) still load unchanged and keep [MASK] = vocab_size; the manifest (format 2) records n_special_tokens, mask_token_id and mask_layout, and every function reads the layout from the tokenizer. Fix: torch_dict casts y to float32 (it was int64 and broke BCEWithLogitsLoss). Deep dataset: time_deltas=True (years_before_index, delta_years), target_cols= (multi-task and survival targets), ragged=True (padding-free tokens, counts and row offsets), include_intra_measurements=True (continuous vitals/labs in the multimodal dataset). Study features: concept_feature() maps concept sets to feature columns (last/first/mean/min/max/count/any, strictly before admission); acs_feature() / fetch_acs_zcta() / acs_zip3_table() download and cache Census ACS indicators by ZIP or 3-digit ZIP (area_feature(geography='zip3')); extract_benchmark_features(feature_set=, feature_fit=) appends a FeatureSet as the study_features group. New [deep] extra (torch, pyarrow); the Docker image installs the CPU wheel.
omopduckdb 0.14.0
Version 0.14.0: study-design features (FeatureSet), plus two fixes from the 0.13.0 audit (Python and R). New: omop_etl.study_features / R study_features collect person-level features a protocol needs but OMOP does not define: feature_set() / FeatureSet extended with add_feature() / .add(); built-ins ruca_feature(), sdi_feature(), area_feature() (any ZIP-keyed numeric such as ACS median household income, with none / log1p / percentile / zscore transforms, a <name>_missing indicator and optional median imputation), sql_feature() and custom_feature(); register_feature_factory() and named feature_list(). compute_features() resolves the address in effect at admission once and returns one row per index stay; write_feature_set() stores the values as measurement rows under site-defined concepts (SDI and RUCA keep the GEOGRAPHY_CONCEPT_IDS), and feature_set_covariate_settings() / feature_set_extraction_r() give the matching OHDSI FeatureExtraction settings (checked end to end against FeatureExtraction on DuckDB). Transforms that learn from data (SDI cut points, a percentile grid, mean and sd, the imputation median) are fitted once with fit = TRUE, kept as feature state and shipped in a manifest (export_feature_manifest() / load_feature_state(); the JSON is shared by Python and R and was loaded across languages); without state they refuse to run, so quintiles and scales do not drift between sites. No reference data (Census, RUCA, SDI) is bundled. stays_from_cohort() builds the index stays from a cohort table. Three vignettes and a README section describe it. Fixed: define_study_cohort(sample_stay_rule=) accepts "first" and "last" as aliases of "earliest" and "latest"; evaluate_loso_transport(model_type="hist_gbm") drops columns that are NaN throughout the training set (scikit-learn failed on them, for example sdi_quintile in the SDoH fallback). Not changed: [MASK] stays at vocab_size as documented (the embedding needs vocab_size + 1 rows); registering it as a special token would shift every token id and break frozen vocabularies. The other audit suggestions (time scaling for sequence models, ragged tensors, concept roll-up before [UNK], small-site calibration smoothing) are not done. The R side is tested on R 4.6.1 with FeatureExtraction installed; nothing here has been run on a production database.
omopduckdb 0.13.0
Version 0.13.0: benchmark feature table, deep-learning datasets, frozen vocabulary and leave-one-site-out evaluation (Python and R, except where noted). Cohort: define_study_cohort(min_admit_date=, max_admit_date=) are inclusive calendar bounds on the admission date (shorthand for study_window, same attrition step, so dropped patients and, with sample_stay_rule="all", dropped stays are logged); sample_stay_rule ("random" = the MD5-based stable_random rule, "earliest", "latest", "all") and random_seed name the stay-per-patient choice. Both default to None, so existing calls and golden results do not change (the old sampling_rule="random" still uses DuckDB hash(); the new "random" is MD5 and identical across DuckDB versions and sites). Keys: the ETL’s hashed keys already use md5_number_lower(...) & 0x7FFFFFFFFFFFFFFF (pcornet_id, 63 bit) and every other surrogate key is a sequential ROW_NUMBER; nothing needed changing (the 53-bit pcornet_id53 is only for R doubles and is not used by default). Features: extract_benchmark_features(con, cohort_table, ...) returns one leakage-free table: demographics, 31 Elixhauser flags anchored at discharge and including the index stay’s diagnoses, 8 medication classes, index-admission vital means, lab means and latest in-stay values (lab_<name> / lab_<name>_last) with CKD-EPI 2021 eGFR and anion gap for both, prior IP / ED / OS utilization and prior readmissions, discharge disposition one-hots, and optional SDI quintile / RUCA category (include_sdoh=True needs the RUCA and SDI files and frozen cut points). No measurement dated after discharge is used (tested with a planted post-discharge value). Deep learning: extract_multimodal_deep_dataset() binds the prior-visit concept tensor to the dense covariates, label and person ids (numpy_dict, torch_dict, memmap = chunked .npy files, arrow = fixed-size nested list parquet; chunked output equals the in-memory result); extract_intra_stay_tokens() tokenizes daily lab level (L/N/H against the measurement’s reference range), lab trend, drugs started and procedures between admission and discharge; make_pretraining_targets() adds BERT-style masked-concept labels ([MASK] = vocab_size) and next-visit flags, reproducible for a seed whatever the chunk size; export_concept_vocabulary() / import_concept_vocabulary() freeze a tokenizer in a checksummed JSON manifest so token ids match across sites. output_format="zarr" writes one chunked .zarr array per output (optional zarr extra, v2 and v3 API; checked on zarr 2.18 here, v3 in the Docker build). R: define_study_cohort() has the same four new arguments (and the stable_random rule); extract_benchmark_features(), evaluate_loso_transport() (ridge logistic model only), fit_recalibrator(), platt_scaling_*, isotonic_*, adjust_for_prevalence(), capacity_threshold(), capacity_risk_tiers(), evaluate_at_capacity(), build_concept_tokenizer(), export_concept_vocabulary() / import_concept_vocabulary() (same JSON file as Python, checked both ways) and make_pretraining_targets(). Not in R: the multimodal tensor dataset, intra-stay tokens and memmap / Arrow / Zarr output (R’s extract_longitudinal_tensors() uses a different hash-based token layout), xgboost models, and Python-identical random draws (R’s sampling, bootstrap and masking use R’s RNG, so numbers differ for the same seed; the properties are tested). Transport: evaluate_loso_transport() trains on N-1 sites (optionally balanced 1:1), scores the held-out site at natural prevalence and reports AUROC, AUPRC, Brier, O/E, calibration slope and intercept, top-k PPV / sensitivity / lift, with 95% bootstrap intervals ("logistic" or "xgboost"); fit_recalibrator() / platt_scaling_* / isotonic_* / adjust_for_prevalence() map balanced scores to the natural rate; capacity_threshold(), capacity_risk_tiers() and evaluate_at_capacity() turn probabilities into “riskiest k%” tiers. The Docker image now installs the bundle extra (xgboost, onnxruntime) and scikit-learn (new sklearn extra, also in dev) for downstream modelling; the library itself does not import it, and model_type="xgboost" uses xgboost’s native API. Follow-ups from live acceptance testing on a production-format database (also in 0.13.0): (1) include_sdoh=True without the RUCA / SDI inputs no longer raises: sdoh_fallback="indicator" (default) returns NaN sdi_quintile / ruca_category and sdoh_missing = 1 with a warning ("raise" keeps the error; no national SDI cut points are bundled, because quintiles must use the training cohort’s frozen cut points). (2) evaluate_loso_transport(model_type=) also takes "hist_gbm" and "random_forest" (scikit-learn; forests fill NaN with training medians). (3) extract_benchmark_features(impute="median"|"mean", impute_values=) fills vitals and labs for models that cannot take NaN; the fill values are returned in attrs["imputation_values"] so they can be fitted on the training sites and reused. (4) extract_intra_stay_measurements() returns continuous (N, max_days, max_obs, 3) arrays of [time_offset, concept_idx, normalized_value] with a mask and the normalization used (stay window only; Python). (5) The feature table is joined once instead of column by column (no pandas fragmentation warning). (6) vocabulary_db="auto" attaches a central_vocabulary.duckdb next to the connection’s database file when concept_ancestor is unreachable (Python only; R still needs attach_central_vocabulary()). R also gets (1) and (3). Fixed on the way: R CMD check failed on undocumented arguments of the new R functions (several @param tags shared a line). All of it was tested on synthetic data only (the R side on R 4.6.1); none of it has been run on a production-size database, and the multimodal dataset has not been trained against a real model.
omopduckdb 0.12.0
Version 0.12.0: utilities migrated from a multi-site pipeline (ODD-1 to ODD-10), all written fresh with synthetic tests. Disclosure control (ODD-5): omop_etl.disclosure / R disclosure - suppress_small_counts() (threshold 11, optional complementary suppression within groups), suppress_attrition_table() (closes a CONSORT flow so no hidden count can be recovered by subtraction, checked by a randomized test), small_cell_mask(), format_count(), assert_disclosure_safe(). CONSORT (ODD-1): generate_consort_attrition() now also takes raw counts (initial_n, exclusions) and pooled sites, with min_cell suppression; the Mermaid/LaTeX/Typst/TikZ/PNG exporters print suppressed counts as <11; ConsortAttrition.to_csv(); R summarize_attrition_consort() and write_consort_csv(). Pooled multi-site output is suppressed by default. Parity (ODD-4): audit_matrix_parity(legacy_df, omop_df, key_col) (Python and R) - SMD, missingness gaps, Pearson/CCC, kappa, total variation distance and per-level counts, suppressed; key values are never written. Table 1 (ODD-6): summarize_table1_site(), pool_table1_summaries(), build_table1() - exact pooled means and SDs, SMD between two groups, small cells suppressed. Site package (ODD-7): export_site_summary() / pool_site_packages() write and verify aggregate-only packages (identifier and date columns are refused, anonymous site label, SHA-256 manifest, no local paths). Vitals (ODD-3): load_vital() falls back to the fixed standard concepts (3004249 systolic, 3012888 diastolic, 3036277 height, 3025315 weight, 3038553 BMI) instead of concept 0 when the vocabulary cannot resolve the LOINC code, derives BMI from height and weight when it is missing, can drop implausible values, and returns row counts. Mapping coverage (ODD-8): mapping_coverage_report() - share of rows and source codes mapped to a standard concept per domain table, with the most frequent unmapped codes (rare codes pooled). The condition, procedure, lab, dispensing and prescribing loaders already existed. Run manifest (ODD-10): RunManifest(con=, outputs=) records the vocabulary release and output file hashes; verify_manifest() checks them. BigQuery demo (ODD-2): run_bigquery_demo() is exported from Python as well as R; the demo itself was already complete and is unchanged (live BigQuery runs need credentials and were not repeated). ODD-9 (Achilles-style checks) is already covered by run_dqd() and sanitize_measurements(); nothing was added. R covers the disclosure helpers, CONSORT counts and the parity audit; the other items are Python only. The R functions and the Python functions were each tested on synthetic data only.
omopduckdb 0.11.2
Version 0.11.2: open items from the PR #42 field test (Python and R). check_observation_period_ends() no longer requires the latest end date to hold 1% of all periods: a pile-up of 33 ends against a typical day of 1 in 219,000 periods is now flagged, so the build-date warning fires on databases where only a few dozen periods end on the build date (F1b). cap_observation_period(dry_run = TRUE, by_end_date = TRUE) also returns the most common end dates among the periods it would shorten (F4), and its documentation now contrasts it with data_cutoff = "auto": "auto" caps only open-ended enrollment spans and keeps recorded ends, the cap shortens every period after the cutoff (O2). The federated_logistic_regression() docstring states the limits of the pre-fit separation screen (O12). R ports (F5): check_observation_period_ends() (also called by define_study_cohort() and extract_patient_features()) and consortium_duplicate_report() now exist in R; remap_discharge_status(as_view = TRUE) and the "auto" default were already ported. R has no federated regression, so the separation screen has no R counterpart. The R functions are tested on small synthetic databases only. - Field-report items (Python; the R changes are marked and untested here). Breaking: (1) build_observation_period() and the ETL’s data_cutoff now default to "auto" (latest event before today) instead of today; pass max_date = None / data_cutoff = None (CLI --data-cutoff today) for the old behaviour. The build prints the cutoff it used (O2; R default changed too, untested). (2) df.attrs['attrition'] is an AttritionRecords (a list of dicts, since 0.11.1); indexing it by column name or calling DataFrame methods still works but raises a FutureWarning, and will be removed in a later minor version. Use cohort_attrition(df) (O5). (3) consortium_multivariable_risk_factors(cluster_col = ) now defaults to regularize = False, so clustered standard errors are those of an unpenalised fit; pass regularize = True for the ridge fit (O9). New: remap_discharge_status(as_view = TRUE) recodes in a TEMP view for read-only databases (O14); check_observation_period_ends() warns from define_study_cohort() and extract_patient_features() when observation periods pile up on one end date, the build-date signature (F1); consortium_duplicate_report() returns pairs, pooled row and the disclosure policy in one object (F3); scripts/benchmark_features.py times extract_patient_features on a stay-level cohort (F2). federated_logistic_regression() screens 0/1 covariates for an empty pooled outcome cell before fitting and returns NaN with separated = True at once; continuous-covariate separation and the noise_scale > 0 case are still caught only after non-convergence (O12; no R port, R has no federated regression). README: new “Disclosure policy” and “Verification status” sections. Version policy while the package is 0.x: a breaking change may ship in a minor or patch release, and is listed here under Breaking with its replacement. - Fix (O1c): the pooled ALL row of consortium_cross_site_duplicates() also withholds n_site_1 / n_site_2 (NA) whenever the row is withheld or suppressed (Python and R). The pooled distinct count is the sum of the site sizes minus the number of patients seen at several sites, so showing it recovered a suppressed pair even with shared_patients withheld. Pair rows keep their per-site sizes. Other aggregate helpers that print site sizes next to suppressed counts have not been audited for the same complementary disclosure.
omopduckdb 0.11.1
Version 0.11.1: follow-up fixes from the five-database field report (Python and R). consortium_cross_site_duplicates() now withholds the pooled ALL row (shared_patients = "withheld", overlap_pct NA) whenever any pair is suppressed, because the pooled count minus the visible pairs recovered the suppressed pair. extract_patient_features() aggregates each clinical table separately per stay and joins the aggregates, so a stay with many conditions and many drugs no longer multiplies their rows; counts and mean_measurement_* are unchanged (a row multiplier is the same for every measurement of a stay, so it never changed an average; checked old versus new on a synthetic multi-table fixture, 38 s versus 0.06 s for 900 stays). New cap_observation_period(con, cutoff, dry_run) caps periods of an already-built database at a data cutoff, and remap_discharge_status(dry_run = TRUE) counts the visits it would recode without writing. consortium_multivariable_risk_factors(cluster_col = ) warns when used with the default ridge fit (regularize = TRUE). compute_attrition() no longer fails when only later steps carry visit_occurrence_id. Python only: df.attrs['attrition'] of define_study_cohort() is now a list of dicts so pd.concat of cohort frames works; new cohort_attrition(df) returns the DataFrame (R keeps the attribute data frame). federated_logistic_regression() also blanks covariance on detected separation. The README limitations now say that translate_cohort_sql("oracle") and the R functions are untested against Oracle and production-size data. - Fixes from v0.11.0 testing on five production databases. consortium_patient_overlap() / consortium_cross_site_duplicates() return overlap_pct = NA whenever shared_patients is suppressed (the percentage let the suppressed count be recovered; Python and R). New remap_discharge_status(con) recodes IP discharges to 8717 in databases built before the ETL mapping, and the transfer warning matches IP case-insensitively. define_study_cohort(one_per_patient=False) attrition gains stays_retained / stays_dropped. build_observation_period() warns when 1% or more of periods end on the build date and no data_cutoff was given. extract_patient_features() accepts TIMESTAMP cohort dates and joins only each stay’s lookback window (much faster on long histories). federated_logistic_regression() returns NaN coefficients with separated=True on detected separation. The person/visit DQD checks are renamed FIELD_FK_PERSON_VISIT_CONSISTENCY_<TABLE>. R gets the same fixes where the function exists there (remap_discharge_status(), case-insensitive transfer warning, stays_retained / stays_dropped, the build-date warning, TIMESTAMP cohort dates and windowed joins in extract_patient_features()); R has no federated logistic regression. Documented: cluster_col SEs equal an unpenalised fit only with regularize=False; df.attrs = {} before pd.concat of cohort frames.
omopduckdb 0.11.0
Version 0.11.0: all stays per patient, stay-keyed features and patient-clustered models (Python and R). define_study_cohort(one_per_patient = FALSE) returns every eligible stay with a stay_rank column (1 = the stay sampling_rule would pick, so the rank-1 rows equal the one-per-patient cohort); models on that output need patient-grouped folds and patient-clustered intervals, and it cannot be combined with persist_keys. A warning now appears when transfer_discharge_concept_ids matches no stay while discharges coded IP hold concept 0 (databases built before the ETL mapped them to 8717), because the transfer exclusion would silently do nothing. concept_ancestor is now found in any attached catalog, not only one named central_vocab, and the metformin-only exclusion’s warning says that descendants are not resolved when it is absent. extract_patient_features(index_key = "visit_occurrence_id") keys the feature rows by stay. consortium_cross_site_duplicates() counts patients seen at more than one site from HMAC-SHA256 pseudonyms of the identifiers, as small-cell-suppressed aggregates only. consortium_multivariable_risk_factors() gains cluster_col (patient-clustered Huber-White standard errors) and increments (odds ratio per clinical increment plus the standardized beta), and consortium_cross_site_validation() gains group_col / n_splits / random_state (the internal cell comes from patient-grouped, outcome-stratified out-of-fold predictions). Fixes: the Python duplicate “Not metformin-only prediabetes / PCOS” attrition step (steps 7 and 8) is gone; load_from_bigquery() wrote 64-bit ids as garbage with the duckdb 1.5 R client (integer64 columns are now sent as text and cast to BIGINT).
omopduckdb 0.10.0
Version 0.10.0: Table 1 precision and sections, Table 3 odds ratios, ONNX export and inpatient FHIR medications (Python and R). generate_table1(decimal_places = c(lab_creatinine = 2)) sets decimals per variable (a default entry covers the rest; a single integer behaves as before) and generate_table1(groups = list(Demographics = c(...), ...)) orders variables under section header rows (unlisted variables go under “Other”). generate_table3_odds_ratios() / export_table3() report a fitted logistic model’s odds ratios per 1 SD or a stated increment (continuous_scale = "sd" or c(systolic_bp = 10)) with Wald 95% CIs, standardized betas and p-values, to Markdown / Quarto / Typst, so a per-unit effect no longer prints as 1.00 (1.00-1.00). export_to_onnx(bundle, path) writes a bundle of logistic components (weighted blend, Platt calibration) as one standalone ONNX graph plus a .features.json with the bounds, imputation values and risk tiers the host must apply; the R version needs no ONNX library and its output was checked with the ONNX checker and onnxruntime. Isotonic calibration and TorchScript are refused rather than approximated; Python also exports a single ONNX or XGBoost component (the latter needs onnxmltools). score_fhir_bundle() now also reads MedicationAdministration (skipping not-done) and MedicationStatement (skipping not-taken) into drug_exposure; entered-in-error entries are skipped.
omopduckdb 0.9.0
Version 0.9.0: score_fhir_bundle() no longer aborts on censored, qualitative or non-date values; harmonize_contract_units() refreshes derived labs (Python and R). A lab result such as "> 60" (eGFR) or "<0.02" (troponin), or a valueQuantity.comparator, is scored at its detection limit and counted in fhir$observations_censored; qualitative or malformed values ("negative", "trace", true, NaN) are skipped and counted in observations_skipped instead of raising a ValueError for the whole bundle (a digit-stripping regex was not used: it would turn -0.5 or 1e-3 into the wrong number). Dates that are not dates ("unknown", "TBD", "null") are treated as missing: an observation without a usable date is skipped, an Encounter without one is ignored as history and no longer wins the “latest encounter” choice by string order; a missing Patient.birthDate now stops with a clear error instead of a database constraint failure. harmonize_contract_units(recompute_derived = TRUE) (the default) recomputes lab_egfr (CKD-EPI 2021, needs age and gender_concept_id) after a creatinine rescale and lab_anion_gap after a sodium / chloride / bicarbonate rescale; the stale value is cleared first because derive_labs() alone only fills a missing eGFR or one at or above 60. Refreshed columns appear in applied with rescaled = FALSE; pass recompute_derived = FALSE for the previous behaviour. Release tags (v*) now also publish the Docker image to ghcr.io/<owner>/<repo>:<version> and :latest (.github/workflows/docker-release.yml). - FHIR vocabulary resolution, unit harmonization and a CONSORT figure exporter (Python and R). score_fhir_bundle(vocab_con =, vocab_db_path =) resolves SNOMED / RxNorm / ICD-10-CM codes against the OMOP concept tables (following Maps to for non-standard codes; concept_map still wins); harmonize_contract_units() rescales the features that check_unit_sanity() traced to a named unit conversion (new suspect_factor column); export_consort_flowchart() draws the attrition table as a publication-ready png / svg / pdf. Also: FHIR blood-pressure panels (Observation.component), prior Encounters as visit history and glucose are read by score_fhir_bundle() in both languages. - Point-of-care explanations, FHIR scoring, incremental loads, drift report and unit guard (Python and R, plus CLI). score_encounter(explain = TRUE, top_k = 5) adds top_drivers: the patient-specific features pushing the risk up or down, as the change in the calibrated probability when each is set to its reference (impute) value (one-at-a-time occlusion, works for every component kind, not interaction-aware TreeSHAP). score_fhir_bundle() scores a FHIR R4 Bundle (Patient, Encounter, Observation by LOINC with creatinine/BUN unit conversion, and Condition / MedicationRequest through a concept_map; unmapped codes are listed, not guessed) without a pre-built database. etl_pcornet(mode = "append", since = "2022-10-01") adds only newly arrived patients, providers, encounters and events to an existing database with surrogate keys continuing from the current maximum (idempotent; care sites and locations are left alone; observation_period and the eras are rebuilt; encounters are selected by admit date). write_drift_report() / omop-duckdb report-drift turns the monitoring log into one self-contained HTML page (PSI trend, Brier, O/E, calibration curve). check_unit_sanity() / omop-duckdb unit-check / score_cohort(unit_check = TRUE) flag labs whose median is more than 3x off a reference median (the built-in reference medians are typical adult inpatient values, to be replaced by the consortium’s own). CLI: score-encounter --explain, score-fhir, report-drift, unit-check, build --mode append --since. - Fix: three warnings found in downstream testing. The federated logistic summary no longer overflows exp() on separable data; the test helper import_or_skip("torch") probes the import in a child process on Windows, where a CPU-only PyTorch install can die with a native access violation that no except catches. - Point-of-care scoring, drift/calibration monitoring and capacity-based risk tiers (Python and R, plus CLI commands). score_encounter(con, visit_occurrence_id, bundle) scores one encounter for a discharge alert: it builds the same feature row as score_cohort but takes the latest vital or lab recorded up to as_of instead of the admission-day value, and returns the probability, tier, the values used and the date of each reading. monitor_scores() gives a monthly table with the Population Stability Index of the predicted risk against a frozen baseline and, once a month’s 30-day outcomes have matured, observed/expected ratio, Brier score, expected calibration error, calibration slope and AUROC, with a status of ok / watch / drift / miscalibrated / insufficient_outcomes; update_monitoring_log() upserts it into a CSV (aggregates only). fit_capacity_thresholds() turns “the riskiest 10% get a nurse call” into frozen probability cut-points, map_risk_tiers() applies them (a bundle’s risk_tiers take the same shape) and tier_load() compares the flagged volume with staffing capacity. The default thresholds (PSI 0.10 / 0.25, O/E 0.8-1.25, slope 0.8-1.2) are conventions to review with the clinical owner, not validated limits. The same functions exist in R (score_encounter(), population_stability_index(), calibration_summary(), monitor_scores(), update_monitoring_log(), fit_capacity_thresholds(), map_risk_tiers(), tier_load()) and tests/test_cross_language.py checks that both languages give the same PSI, calibration statistics, cut-points and tiers. CLI: omop-duckdb score-encounter, omop-duckdb monitor (--fail-on-flag exits 2 on drift or miscalibration, for a scheduler) and omop-duckdb risk-tiers fit|apply. - The Circe compiler (Python and R) evaluates more constructs, each checked against CirceR + CohortGenerator. First (the earliest event of the concept set, taken before the window and before the other attributes), AdditionalCriteria (applied after the primary limit, like an inclusion rule), the Unit attribute, the source-concept attributes (ConditionSourceConcept, ProcedureSourceConcept, …), AT_LEAST / AT_MOST groups and nested groups. On the PhenotypeLibrary the compiler now accepts 521 of 707 definitions (368 before); on a sample of 160 it returned the same people as CirceR in all 160 and the same start dates in 158 (the others use CustomEra). Still refused with an error naming the construct: EndWindow, criteria nested inside a criterion of an inclusion rule, ValueAsConcept, OccurrenceStartDate, includeMapped, distinct-count occurrences, DrugEra / ConditionEra criteria. Inclusion-rule age was compared with CirceR and already matched (calendar-year difference); now pinned by a test. explain_cohort_gaps() names failed_additional_criteria. - The DQD catalog was compared with the official DataQualityDashboard 2.9.1. On a planted fixture the violated-row counts and denominators agree for every check both tools produce on the same table and field (pinned as golden values, Python and R). Two alignments came out of it: concept-record completeness (standardConceptRecordCompleteness, sourceConceptRecordCompleteness) divides by the rows where the concept field is not NULL, and measurePersonCompleteness / measureConditionEraCompleteness are table-level checks without a field. Differences by design are documented in run_dqd_catalog(). - Python and R are now compared on the same databases. tests/test_cross_language.py feeds identical fixtures to both and compares the Circe compiler, the DQD catalog, reconciliation, custom concept ids, the bundle concept check, the metrics and the default ridge model (a workflow runs it on changes to the shared code). It found one real difference, now fixed: R standardised the ridge model’s columns with the sample standard deviation and Python with the population one, so the two gave slightly different fits. - Faster bootstrap for ablate_feature_groups() and compare_model_runs(). A bootstrap draw is now the number of times each row appears and the metrics are computed from sort orders fixed once, which is identical to resampling rows (ties and average precision included, checked against explicitly repeated rows) but needs no sort per resample: about four times faster (500,000 patients, 500 resamples: 121 s to 33 s). The draws, and so the exact interval limits, differ from earlier versions for the same seed. scripts/benchmark_scale.py times the heavier tools on a synthetic CDM: at 1,000,000 people (2.7M stays, 3.5M measurements) the index-stay cohort takes 0.5 s, a 200,000-patient reconciliation 2 s, the whole DQD catalog 1.5 s. - Housekeeping. README section “Tools for a downstream study”. test-v056-features.R skips cleanly when the package is not installed for a child R process instead of failing under devtools::load_all. - A worked example of a whole study (inst/examples/study_walkthrough.py and .R). On a small synthetic OMOP DuckDB it runs the index-stay cohort with the native compiler, reconciles it with a legacy patient list and explains the gaps, adds a site-specific score so FeatureExtraction / PLP can read it, judges that score against noise with ablate_feature_groups() and compare_model_runs(), and packages a bundle that records the score’s concept id and refuses a site where the id differs. Each step is a few lines to copy. Both versions run in the test suite, so the example cannot rot. - A model bundle refuses to score custom concept ids that mean another feature at this site. Custom concept ids are per database, so a bundle trained at one site and scored at another could read the wrong column without an error. stamp_feature_spec_concepts() records each custom feature’s concept_id in the bundle’s feature spec when the bundle is written, validate_bundle_concepts() compares them with this site’s registry (a connection, a registry or the exported registry file) and names every feature whose id differs, is not registered here or belongs to another feature, and score_cohort(check_concepts = ) runs the check first. Features without a recorded id are not checked. Python and R. - The cohort definitions ship with the package (cohorts/ moved to inst/cohorts/). The Circe JSON and OHDSI SQL files were in a top-level folder that an installed R package does not contain, so the tests that read them (the committed Circe definitions, cohort_definition_set(), the cohort comparison) were skipped in R CMD check and in the coverage run, and the compiler code they exercise looked uncovered. They are now found everywhere: cohort_definitions_dir() (R and Python) returns the folder, cohort_definition_set() uses it by default, and the wheel bundles it. Path change for scripts that referenced cohorts/... in the repository: it is now inst/cohorts/.... - Does a feature group help, and are two model runs really different? ablate_feature_groups() (Python and R) refits a model with each named group of columns removed (or kept alone) on the same cross-validation folds and reports the change in AUROC, AUPRC and Brier score with a paired bootstrap interval, so a group such as RUCA/SDI or a site’s Charlson index is judged against noise rather than by eye. compare_model_runs() compares two sets of predictions for the same patients (for example 0.706 against 0.710): the metrics of each, the paired differences with bootstrap intervals, the Spearman correlation of the two risk scores and how much of the top-risk group both flag. The model is any fit_predict(x_train, y_train, x_test) function (scikit-learn, xgboost, a PLP model); the default is a small ridge logistic regression, ridge_logistic_fit_predict(), that needs only numpy / base R. Both return aggregate tables only, so a site can send the result back; a 0.004 AUROC gap whose interval spans zero is reported as such. - Reconcile a reference patient list with a cohort, and say why patients are missing. For a study that replaces a legacy extraction: reconcile_cohort() (Python and R) compares any list of identifiers (person_source_value or person_id, optionally with an index date) with a cohort table or a Circe definition and returns the patient-level overlap (both, reference_only, cohort_only, Jaccard) and how many matched patients share the index date. explain_cohort_gaps() gives every reference patient the first step that excludes them: not in the CDM, no observation period, no entry event, failed an entry correlated criterion, entry outside the observation window, or a named inclusion rule. It walks the Circe definition with the native compiler, whose compile_circe_to_duckdb(stage = ) now returns the events of an intermediate step. Reports are counts by reason; patient-level rows are returned only with include_person_rows, and min_cell / suppress_small_cells() blank small counts so a report can leave a site. Nothing is specific to one study. - Public BigQuery demonstration / smoke test on CMS SynPUF. run_bigquery_demo() (R, inst/scripts/run_bigquery_demo.R) and python -m omop_etl.demo_bigquery (omop-bigquery-demo) build cohorts/diabetes_phenotype.circe.json and baseline features (age, sex, race, prior_ip_os_ed_count, readmission_count_twelve_months) on bigquery-public-data.cms_synthetic_patient_data_omop in a scratch dataset of the caller’s own project and write a report with the synthetic-claims disclaimer. R compiles with CirceR + SqlRender (compile_cohort_bigquery()); Python transpiles the native compiler’s SQL to GoogleSQL with sqlglot. Labs and vital signs are reported as unavailable, never imputed. --dry-run writes the SQL without any BigQuery call. Offline tests check the generated GoogleSQL parses; a live test runs only when OMOP_BQ_BILLING_PROJECT is set. Not yet run against live BigQuery by the author of this change; see vignettes/bigquery_synthetic_demo.Rmd.
-
Fix: R sessions crashed intermittently (segfault) in the Windows R CMD check. The cause was
omop_connect_lakehouse(format = "delta")(and the Pythonomop_connect_lakehouse): it ranINSTALL delta; LOAD deltaeven for a plain parquet directory, and a failed extension install or load leaves the DuckDB R connection in a state that segfaults on disconnect or garbage collection (reproduced locally: a failedLOAD deltacrashed 5 of 8 fresh R sessions; a bad SQL statement never did). The extension is now loaded only for a table that is a Delta (_delta_log) or Iceberg (metadata) table or a remote URI; a plain parquet directory is read withread_parquet()whateverformatsays. The crashing test file now completes 6 of 6 passes of the suspect test files where it crashed on the second before. The test run also prints each test as it starts (tests/testthat.R), so a future hard crash names the test. On a machine without internet access, install the extension beforehand (INSTALL delta). -
The index-stay cohort (
cohorts/target_cohort.circe.json) is now a real Circe definition, and the native compilers evaluate it.omop_etl.circe_definitions.target_cohort_circe()builds it: the discharge date is the index date (DateAdjustmenton the end date), the age is taken at discharge, a death on or before discharge disqualifies the stay, and these rules are correlated criteria of the entry event, so the primary limit picks the earliest stay that qualifies (inclusion rules would drop a patient whose first stay failed). CirceR + CohortGenerator and the native compilers (Python and R) return the same cohort on a fixture with the awkward cases (scripts/ohdsi_parity_target_cohort.R). It differs fromcohorts/target_cohort.sql, which stays authoritative, in two documented cases that Circe cannot express: a patient discharged as died (discharged_to_concept_id4216643) without a death record, and a death within 30 days of discharge when the observation period ends at death. The native compilers now evaluateDateAdjustment, theAgeattribute andCorrelatedCriteriaon an entry event, andDeathas a domain; inclusion-rule criteria withCorrelatedCriteriaare still refused. -
DQD catalog for R.
run_dqd_catalog()andrun_dqd_full()(R) run the same schema-driven catalog as the Pythonrun_dqd_catalog, with the same check names, thresholds and result shape, and the same tests. -
Custom concept ids stay aligned across sites. A custom feature’s concept id is assigned per database, so two sites can give the same feature different ids, or one id to different features; a model that stores the id then scores the wrong column at the other site without an error.
export_custom_concept_registry()writes a site’s registry as JSON,register_custom_concepts(registry=)andwrite_custom_features(registry=)pin the ids a consortium shares, andcheck_custom_concepts()listsname_different_id,id_different_name,id_collision(another vocabulary uses the id),duplicate_idandbelow_local_rangeconflicts against other sites’ registries (raise_on_conflict/error = TRUEstops on them).write_custom_covariates()now refuses an id that a concept of another vocabulary already uses, and two features sharing one id, before writing anything. Python and R. -
DQD catalog: the missing concept-class, value and completeness checks.
run_dqd_catalog()adds, under the official check names,fkClass(drug_era.drug_concept_idanddrug_strength.ingredient_concept_idare Ingredients),plausibleValueLow/plausibleValueHigh(birth year,days_supply,quantity, and the bundled physiologic limits ofmeasurement.value_as_numberfor rows whose unit matches a limit),sourceConceptRecordCompleteness,measurePersonCompleteness(clinical tables with no row for a person),measureConditionEraCompletenessandmeasureObservationPeriodOverlap. Still not run: the per-concept checks (plausibleGender,plausibleUnitConceptIds, …). -
Fix: the native Circe compiler silently returned wrong cohorts for definitions it did not understand. Running real PhenotypeLibrary definitions through CirceR + CohortGenerator and the native compiler on the same data showed: it applied the inclusion rules before the primary-criteria limit (so a person whose first entry failed a rule could still enter later; “Type 2 diabetes indexed on diagnosis, treatment or lab result” gave 361 people instead of 231); it ignored
AdditionalCriteria, criterion attributes it does not evaluate (Unit,CorrelatedCriteria,ProcedureSourceConcept,First, …),includeMapped, nested groups andEndWindow; it had noObservationorDeviceExposuredomain, so anObservationentry event fell back to “every visit” (1,887 people instead of 0); it turned an unknown operator such asbtinto=; it did not require the entry event to fall in an observation period. It now follows the ATLAS order (observation window, primary limit, rules, end strategy, era collapse,ExpressionLimit), appliesDateOffsetend strategies, the default end of observation and era collapse withEraPad, supportsbt/!bt/!eqand theObservationandDeviceExposuredomains, ends an event without an end date the day after it starts, and raisesNotImplementedError(R: an error) naming the construct for anything that would change who is in the cohort, instead of ignoring it.CustomEraand censoring criteria only change end dates and raise a warning. Of the 707 PhenotypeLibrary definitions, 346 are accepted; on 80 sampled ones the native compiler returned the same people as CirceR + CohortGenerator in 80 and the same start dates in 79 (the other usesCustomEra).scripts/ohdsi_parity_phenotypelibrary.Rrepeats the check. Behaviour change: entry events must lie in an observation period, so a CDM withoutobservation_periodrows now returns empty cohorts;cohort_end_datefollows the end strategy (it was the event end date). -
Add your own covariates to FeatureExtraction.
write_custom_covariates()(Python and R) writes any derived feature asmeasurementrows under a site-defined concept id (>= 2,000,000,000;unit_concept_id0; registered inconcept), andcustom_covariate_settings()(R) builds the FeatureExtraction settings that read them.write_custom_features()takes a wide table (one column per feature) and gives each feature a stable named concept in the database (register_custom_concepts()), so a study adds its own Charlson, Elixhauser or frailty definition next to FeatureExtraction’s and reads both through the same covariate settings (PatientLevelPrediction and DeepPatientLevelPrediction consume the same covariate data). The package does not choose between definitions. RUCA/SDI (write_geography_measurements()) are now just one use of it; an alternative definition of an existing feature can be written under its own concept id and compared with the standard one before a study chooses. -
DQD: concept domain and standard/valid checks.
run_dqd_catalog()addsfkDomain(the concept of a clinical field is in the expected domain) andisStandardValidConcept(the concept is standard and not deprecated), both with the official DQD check names; they run whenconceptis populated.strict_domains=TRUEstops measurement and observation fields from accepting each other’s domain. Still not run:fkClass, plausible-value and gap checks,sourceConceptRecordCompleteness. -
Phenotype decisions made explicit. Gestational diabetes (SNOMED 4024659) is a descendant of “Diabetes mellitus” (201820), so a plain descendant set admitted pregnancy-only diabetes, which the SAS extraction’s ICD rule (249, 250, E08-E13) does not;
diabetes_phenotype_circe(include_gestational=False)now subtracts it (include_gestational=Truekeeps it; a person with a diabetes drug or HbA1c >= 6.5 still enters through those arms). Whether outpatient visits (9202) count inprior_ip_os_ed_countis a study choice:extract_velocity_features(os_concepts=...)takes it (default9202, 581385;os_concepts=581385counts observation stays only), now covered by a test. -
Checked against more official tools (
OHDSI_INTEGRATION.md): CohortDiagnostics and CohortGenerator report the same cohort counts asexecute_circe_cohort(); PatientLevelPrediction’s study population and outcome count equal a direct SQL count, itsgetPlpData()returns a custom covariate written withwrite_custom_covariates(), andrunPlpfinishes on the DuckDB-backed data (scripts/ohdsi_parity_plp_cohortdiagnostics.R). -
RUCA / SDI as OHDSI covariates.
write_geography_measurements()(Python and R) stores the values fromderive_geography_features()asmeasurementrows (SDI score, SDI quintile 1-5, RUCA primary code; local concept ids 2000100001-3,unit_concept_id0, registered inconcept), so FeatureExtraction and PatientLevelPrediction read them as ordinary covariates.derive_geography_features()now also returnsadmit_date. -
Checked against the official OHDSI tools (CirceR + CohortGenerator, FeatureExtraction, Achilles 1.7.2, DataQualityDashboard); see
OHDSI_INTEGRATION.md. Fixed:diabetes_phenotype.circe.jsonwas not valid Circe (age is now inDemographicCriteriaList, which the native compiler also reads);run_achilles()distribution statistics now use the sample standard deviation (NULL for one value) and discrete percentiles like Achilles; the DQD catalog counts every row of a duplicated primary key like DQD and checks end dates and datetime fields inplausibleAfterBirth/plausibleStartBeforeEnd; catalog results carrycheck_origin(plausibleFutureDateandvisitPersonMatchare not DQD checks). Not equivalent:extract_charlson_index()and FeatureExtraction’s Charlson. -
Study logic as Circe definitions.
cohorts/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) andcohorts/diabetes_phenotype.circe.json(adult with a diabetes diagnosis, a diabetes drug or HbA1c >= 6.5, the SAS extraction’s rule) are standard ATLAS/Circe JSON, so they import into ATLAS, run through CohortGenerator, and compile to DuckDB with the package’s Java-free compiler.omop_etl.circe_definitionsbuilds them (write_circe_definitions()); a test fails if the committed files drift. Tests show the compiled cohorts agree withfind_metformin_only_prediabetes_pcos()on data whose codes are mapped to standard concepts. Circe sees standard concept ids only, so records that carry just a source value are invisible to it; that is the normal OHDSI contract. -
Fix: the native Circe compiler. Excluded concept-set items (
isExcluded) were skipped instead of subtracted, so a set such as “ATC A10 without A10BA” still contained the biguanides; they are now removed with their descendants, and the concept itself is always part of anincludeDescendantsitem. A measurement entry event’sValueAsNumberfilter (HbA1c >= 6.5) was ignored for primary criteria and is now applied. Python and R. -
Fixed-level categorical encoding. New
encode_categoricals()/encoded_column_names()(Python and R) one-hot encode model features from a level list shipped with the model (feature_spec["categorical_levels"]: levels plus an optional reference level), so a site always gets the same columns in the same order, named like pandasget_dummies(<feature>_<level>).get_dummies(drop_first=True)takes its columns and reference level from the data in hand, andpd.to_numericsilently turns string features into NaN; neither is safe for a model that must score at another site. -
Fix (ETL): PCORnet
DISCHARGE_STATUS = 'HO'is home / self-care, not hospice. It was mapped to hospice (8546), so home discharges were mislabelled;HOnow maps to Home (8536) and hospice isHS. Re-run the ETL (orUPDATE visit_occurrence) on existing databases. -
Behaviour change (ETL): observation stays are no longer inpatient. PCORnet
ENC_TYPE = 'OS'was mapped to 9201 (inpatient), so observation stays could become index admissions and readmissions; it now maps to 581385 (Observation Room), whichextract_prior_utilization()counts in itsosgroup (still prior utilization, never an index stay). A PCORnet discharge to another acute-care hospital (DISCHARGE_STATUS = 'IP') now maps to 8717 (Inpatient Hospital) instead of 0. Verify both concept ids in your Athena release. Existing databases need the ETL re-run (or anUPDATE visit_occurrence); cohorts built on the old mapping include observation stays. -
Fix (ETL): AMA discharge concept. PCORnet
DISCHARGE_STATUS = 'AM'was written as 4155309, which is SNOMED “Ileal part” (an anatomic site; confirmed in Athena), so AMA was not a valid disposition and the legacy end-of-life convention(4216643, 4155309)counted AMA stays as deaths. The ETL now writes 32216 (“Left against medical advice or discontinued care”, UB04 Pt dis status 07). The legacy convention is unchanged because golden files pin it; on databases built before this fix passdeath_discharge_concept_ids=(4216643,).inst/sql/cohort_mortality.sqlno longer calls 4155309 “Hospice” (hospice is 8546). Concepts 8717 (Inpatient Hospital) and 581385 (Observation Room) were confirmed as valid standard Visit concepts. -
Fix: diabetes phenotype HbA1c set.
define_study_cohort(require_diabetes=TRUE)/build_ederri_diabetes_cohort()matched only three HbA1c concepts (LOINC 4548-4, 17856-6, 59261-8), so patients qualifying on the other HbA1c codes of the SAS extraction were missed. It now covers all of them (LOINC 17855-8, 41995-2, 55454-3, 62388-4, 71875-9, 4549-2 added; the SAS list’s549-2is a typo for 4549-2 and does not exist in the vocabulary). Still open: the medication arm only matches a short list of drug names indrug_source_value, not the RxNorm list of the extraction or an ATC A10 roll-up, and 41995-2 is a mass/volume unit (g/dL) so>= 6.5rarely applies to it. The PCORnet ETL also mapsNH-> 8676,HH-> 32215 andRH-> 32228 now (they were 0). -
Fix (ETL): PCORnet
ENC_TYPE = 'EI'(emergency-to-inpatient) was dropped. It mapped to 0, but at three of five consortium sites EI is the larger share of hospitalizations (955k EI vs 707k IP stays), so an ETL run lost over half of the inpatient stays there. EI now maps to 262 (Emergency Room and Inpatient Visit).build_ederri_diabetes_cohort()usesvisit_type=[9201, 262](IP and EI) and the phenotype’s ICD-10 prefix list now includes E12, as in the SAS extraction. The genericvisit_type="inpatient"still means 9201 only (the RFC example is pinned); pass[9201, 262]for IP + EI, andoutcome_visit_type=[9201, 262]so an EI stay counts as a readmission.IS(non-acute institutional) stays unmapped on purpose. -
Comorbidity window:
end_inclusive.extract_elixhauser_comorbidities()andextract_charlson_index()(Python and R) takeend_inclusive=(defaultFALSE) to count diagnoses dated ON the index date. A discharge-anchored window (index_date_col= the discharge date,exclude_index_diagnoses=FALSE) was already possible but stopped one day short, so diagnoses coded on the discharge day were missed; withend_inclusive=TRUEandlookback_days=730it reproduces the legacy study’s rule (condition_start_datein[discharge - 730, discharge], index stay included). The defaults are unchanged: admission anchor, window ending strictly before the index date, index-visit diagnoses excluded. -
Behaviour change: prior utilization counts EI (262) as inpatient only.
DEFAULT_VISIT_CONCEPT_GROUPS(extract_prior_utilization()) andextract_velocity_features()counted concept 262 (emergency-to-inpatient) as both an inpatient and an ED visit. The legacy study relabelled PCORnetEIasIP, so an earlier EI stay now incrementsprior_ip_countandprior_ip_os_ed_countbut notprior_ed_count(defaultsed = 9203).extract_velocity_features()also counts observation stays (581385) inprior_ip_os_ed_count; before, only 9202 (outpatient) was in its third group, so observation was missed. Outpatient (9202) is still in that group, unlike the legacy definition (inpatient + observation + ED only); passos_concepts=581385to match it. Passvisit_concept_groups=/ed_concepts=to restore the old counts. -
Metformin-only prediabetes / PCOS exclusion. New
find_metformin_only_prediabetes_pcos()(Pythonomop_etl.exclusions, R) returns the patients with prediabetes or PCOS whose only diabetes drug is metformin and who have no diabetes diagnosis (all other diabetes drugs, including metformin combinations, and any diabetes diagnosis keep a patient in).define_study_cohort(exclude_metformin_only_prediabetes_pcos=)/build_ederri_diabetes_cohort()drop them as a patient-level attrition step. The PCOS concept set is a parameter ("icd10"= ICD-10 E28.2 / SNOMED “Polycystic ovary syndrome”,"snomed"= SNOMED 69878008 / “Polycystic ovary”,"both") because the legacy file’s definition is not known; validate each against the per-site legacy file. Needs the vocabulary (concept_ancestor) for descendants; without it only the listed ids and source-value patterns match, with a warning. -
Diabetes phenotype: medication rule.
define_study_cohort(diabetes_drug_rule=)chooses the medication arm ofrequire_diabetes:"names"(default, unchanged: ten drug names indrug_source_value),"atc_a10"(concepts descending from ATC A10, which brings in brands and combinations) or"rxnorm_cuis"withdiabetes_rxnorm_cuis=(a list or a file of RxNorm CUIs, e.g. the SAS extraction’s). The last two need the vocabulary on the connection and raise an error without it. -
Transfer exclusion.
define_study_cohort(transfer_discharge_concept_ids=)(Python and R) excludes index stays discharged to another acute-care hospital and adds the attrition step “Not transferred to another acute-care hospital”; AMA discharges are kept. Off by default, so existing attrition tables (including the RFC example) are unchanged;build_ederri_diabetes_cohort()turns it on with 8717. -
Geography features (RUCA, SDI). New
derive_geography_features()(Pythonomop_etl.geography, Romopduckdb) derives a RUCA category and SDI quintile for each index stay from the address in effect at admission, a USDA ZIP -> RUCA crosswalk and a Robert Graham Center ZCTA -> SDI table that the caller supplies. SDI quintiles use the training cohort’s fixed cut points (sdi_cut_points, four ascending scores): cutting at local quantiles moves patients between quintiles whenever the local SDI distribution differs, so the function errors without cut points unlessfit_cut_points=True(training site only; the fitted cuts come back inresult.attrs["sdi_cut_points"]/attr(, "sdi_cut_points")for publication with the model).load_location()now also fillsperson_address_history(person, ZIP5, start, end, preferred) so the address in effect can be chosen;person.location_idis still a single address and is the fallback. RUCA 99 (“not coded”) is Small Town / Rural, as in the reference coding;code_99_missing=Truetreats it as unknown. The reference cut-point values and the ZIP crosswalks are not bundled.load_location()also repairs address rows whoseADDRESS_CITYholds an unquoted comma (“St. Louis, MO”); before, such rows silently shifted state, ZIP and dates into the wrong columns. -
BigQuery sync.
read_bigquery_table()now streams into a staging table inside one transaction and swaps it in, so a failed stream no longer truncates an existing table; it refuses a view target and resolves the existing table in the current schema only.skip_missing=Trueskips only not-found tables, not validation errors. The reader passes a BigQuery Storage client whengoogle-cloud-bigquery-storageis installed. Still unit-tested only; not run against a live BigQuery project. -
Achilles / DQD catalog.
run_achilles(drop_existing=False)replaces an analysis’ earlier rows instead of appending. Both Achilles and the DQD catalog read columns from the current schema only.min_cell_countremoves small cells rather than masking them as the R package does. DQD gainsvisitPersonMatch(a row’svisit_occurrence_idbelongs to the same person) and uses the CDM key fordeathand the vocabulary tables.plausibleFutureDateflagsobservation_periodends set to the build date; that is expected. -
Federated learning.
noise_scalenow also blurs the Cox event counts and the logistic log-likelihood; row and event totals stay exact bookkeeping. A noisy non-positive Cox risk-set sum raises. Logistic fits use step-halving and warn on non-convergence, naming likely (quasi-)separation. Cox covariance and log-likelihood come from the final coefficients;federated_cox(min_site_events=)added. -
Observation-period cutoff (N2).
etl_pcornet(data_cutoff=)/omop-duckdb build --data-cutoffcapobservation_periodends at an ISO date, or at the latest event dated before today with"auto", so events filled with the build date no longer set period ends. The default is unchanged (today). The R ETL has the samedata_cutoffargument, andbuild_observation_period(max_date = "auto")works there too. -
R BigQuery loader.
load_from_bigquery()passedbilling_project=tobigrquery::bq_table_download(), which only acceptsbilling=, so every call failed with “unused argument”. Fixed, and 64-bit ids are now downloaded asinteger64. New mocked test (no GCP credentials). The R loader still materializes each table in memory; usesync_vocabulary_from_bigquery()for full vocabularies. -
HADES read-only wrapper (N5). New
readonly_connect_wrapper()holds theDatabaseConnector::connectwrapper thatcohorts/run_plp_readonly_example.Rused inline; it is tested against a real read-only DuckDB file. Docs:cohorts/OMOP_COHORT_DEFINITION.mdnow says the SQL is authoritative and the Circe JSON is not generation-verified in ATLAS (FR-D5), and explains how the follow-up rule behaves with enrolment-based periods (N3). The README now states that the BigQuery sync and Oracle translation are unit-tested only. - Oracle cohort SQL. Constructs sqlglot cannot express in Oracle raise instead of emitting approximate SQL. Still not run against a real Oracle database.
-
ATLAS scripts. Compose ports bind to 127.0.0.1, the unused DuckDB JDBC mount is gone, and
import_circe.py --cleanupdeletes the definitions it creates.
omopduckdb 0.8.7
-
Python: Oracle cohort SQL. New
omop_etl.cohort_sql.translate_cohort_sql(sql, dialect); for Oracle it rewritesDATEADD(day/week tod + n, month/year toADD_MONTHS) andYEAR()toEXTRACT(YEAR FROM ...), which plain sqlglot gets wrong. The live-db cohort test now includes Oracle (not yet run against a real Oracle container; unit-tested on the generated SQL only). -
Python: Achilles in DuckDB.
run_achilles()/omop-duckdb achilleswriteachilles_results,achilles_results_distandachilles_analysiswith one set-based statement per analysis (demographics 0-5, observation periods 101/103/105/108/111-113, persons / records / by-month for the visit, condition, procedure, drug, observation, measurement and device domains, death, eras). This is a subset of the ~170 R-package analyses;achilles_analysis_catalog()lists exactly what is implemented. -
Python: DQD catalog.
run_dqd_catalog()/run_dqd_full()/omop-duckdb dqd --fullgenerate checks from the CDM DDL for every table and field (table/field existence, required, primary key, foreign key, value completeness, unmapped concepts, start-before-end, after-birth, before-death, future date) in DQD JSON shape. Concept-level checks that need vocabulary content are not included. -
Python: iterative federated learning.
federated_logistic_regression()andfederated_cox()(Breslow ties) run Newton-Raphson over per-site aggregates; results equal the pooled fit (tested against statsmodels). Optionaltime_binandnoise_scalereduce what aggregates reveal; they are not a formal differential-privacy guarantee. -
Python: BigQuery to DuckDB.
sync_vocabulary_from_bigquery()/read_bigquery_table()stream Arrow batches into DuckDB with no CSV or disk staging (pip install omop-duck-db[bigquery]). Unit-tested with a fake Arrow reader and client; not run against a live BigQuery project. -
HADES integration test.
tests/testthat/test-cohortgenerator-integration.Rruns the realCohortGenerator::generateCohortSet()oncohort_definition_set()against a DuckDB CDM through DatabaseConnector (target cohort = persons 1 and 5, outcome events = 6, the same as the Python / PostgreSQL / SQL Server runs). Optional CI:.github/workflows/hades-integration.yml. -
ATLAS.
scripts/atlas/holds a docker-compose (PostgreSQL 16, WebAPI 2.15, ATLAS 2.15 on non-default ports) andimport_circe.py, which importscohorts/*.circe.json, reads them back and has WebAPI render SQL. Verified on WebAPI 2.14.0 and 2.15.x: both definitions import, round-trip and render. Not possible today: generating cohorts inside ATLAS on a DuckDB CDM. WebAPI 2.14 and 2.15 rejectduckdbas a source dialect (“Unsupported data source dialect: duckdb”, even with the DuckDB JDBC driver mounted); WebAPI 3.0.0 did not start with this compose configuration and was not pursued.make_cdm.pywrites the fixture CDM for when a WebAPI with DuckDB support is available; useCohortGenerator(see the HADES integration test) to run the definitions on DuckDB meanwhile.
omopduckdb 0.8.6
Fix (CLI):
omop-duckdb buildtakes--key-check,--use-enrollmentand--enrollment-type-concept-id;run_manifest.jsonrecords thekey_check:*collision steps andobservation_period:enrollment_spans.Fix (R tests): the
callrchild in the Andromeda test setsandromedaThreads = 1/andromedaMemoryLimit = 0.5.Read-only distribution: new
checkpoint_database()(Python, R) andomop-duckdb checkpoint FILE...fold the.walinto the file;attach_read_only()/readonly_attach_sql()warn when a.walis present.cohort_definition_set()docs and the example scripts state thatgenerateStats = FALSEis required.Fix (R tests): removed
skip_on_os("windows")from the three Andromeda tests intest-v056-features.Rnow that thecallrchild is constrained; re-add it if the Windows runner still aborts.Docs: Oracle caveat for sqlglot
DATEADDintranslate_to_duckdb()andtarget_cohort.sql.Versions aligned at 0.8.6 across
DESCRIPTION,pyproject.tomlandomop_etl.__version__.Fix:
FeatureMatrixBuilder.to_tensor()falls back to the NumPy array when torch is installed but its DLL fails to initialise on Windows (OSError, not justImportError).Tests: no more cwd-dependent paths in
test_v080_features.py(resolved from the repo root).Tests/CI (R, Windows): Andromeda teardown.
test-hades-bridge.Rcloses everyplpData$covariateData;helper-hades.RsetsandromedaThreads = 1/andromedaMemoryLimit = 0.5(GB);duckdb_to_andromeda()flushes after chunked appends. Targets the silentR CMD checkexit on 7 GB runners.Docs: hand-written cohort SQL must be run with
CohortGenerator::generateCohortSet(..., generateStats = FALSE); read-only DuckDB files must be checkpointed (no.wal) beforeATTACH ... (READ_ONLY).Build-time key check (R):
check_key_collisions()/check_etl_keys()andetl_pcornet(key_check = "warn"|"raise"|"ignore", key_check_callback = ), ported fromomop_etl.key_checks.Enrolment-based observation periods (R):
etl_pcornet(use_enrollment = "auto"|TRUE|FALSE, enrollment_type_concept_id = ), newload_enrollment_spans(), andbuild_observation_period(use_enrollment=, enrollment_type_concept_id=); spans are clipped, merged when they overlap or touch, and people without enrolment keep the event-span period.Cohort comparison (R):
compare_cohort_definitions()andrun_cohort_sql()(SqlRender render/translate/split on DuckDB TEMP tables), ported fromomop_etl.cohort_sql.Sequence tensors (R):
extract_longitudinal_tensors(include_index_stay=, include_labs=)returns an(N x 20 x 30)integer array with the same DuckDB-hash tokens as Python; constantsMAX_LONGITUDINAL_VISITS,MAX_TOKENS_PER_VISIT,VOCAB_SIZE. All four 0.8.5 Python-only features now have R equivalents. # omopduckdb 0.8.5
Remaining requests from the 2026-10 consortium notes (FR-D6, FR-D7, FR-D8, FR-B5, FR-A7, enrolment-based observation periods).
-
FR-D7 follow-up rule option:
cohorts/target_cohort.sqltakes@followup_evidence('observation_period'by default, or'observation_period_or_event'): the second also accepts a later visit, measurement, condition or drug record dated on or after discharge +@followup_days, asdefine_study_cohort()does.cohort_definition_set(followup_evidence=)renders it. On the consortium data the two rules differ for 27 of 59,117 readmissions; sites with real enrolment windows should compare. -
FR-D8
compare_cohort_definitions()(Python): runs two target-cohort SQL files, optionally with the outcome SQL, on one CDM (TEMP table, so a read-only CDM works) and returns per-definition counts and outcome rates plus thecohort_overlap()table. Helpersrender_cohort_sql(),run_cohort_sql()andtranslate_to_duckdb()execute the shipped SQL on DuckDB without SqlRender (needspip install omop-duck-db[cohorts], i.e. sqlglot). -
FR-D6 cross-dialect test:
tests/test_live_databases.pyruns the cohort SQL on PostgreSQL and SQL Server containers (translated with sqlglot, not SqlRender) and expects the DuckDB cohorts. It runs in thelive-dbworkflow and passes on the PostgreSQL 16 and SQL Server 2022 service containers (target cohort and outcome cohort match the DuckDB result). Oracle is not covered (sqlglot rendersDATEADDwrongly for it; use SqlRender). -
Enrolment-based observation periods (Python):
etl_pcornet(use_enrollment="auto")buildsobservation_periodfrom the PCORnet ENROLLMENT file when present (clipped to[1900-01-02, today], overlapping or touching spans merged,enrollment_type_concept_idsets the period type), and keeps the event-span rule for people with no enrolment record. -
FR-A7 sequence tensors:
extract_longitudinal_tensors(include_index_stay=, include_labs=). Lab tokens combine the concept with a low/normal/high flag fromrange_low/range_high. For cohorts anchored at discharge (cohorts/target_cohort.sql) the default window already contains the index stay; the option matters for admission-anchored cohorts and carries a leakage risk. Tokens use DuckDBhash()and are stable only within one DuckDB version. -
FR-B5:
NOTES.mddocuments the one-lineATTACHfor a shared vocabulary file and the helpers.
omopduckdb 0.8.4
Requests FR-C10, FR-C12, FR-D4 and FR-D5 from the 2026-10 consortium notes. Not done: building observation_period from real enrolment data (the ETL has no PCORnet ENROLLMENT loader).
-
FR-C10 observation periods:
build_observation_period(con, min_date = "1900-01-02", max_date = NULL)(Python and R) ignores events beforemin_date(SAS/Excel zero dates,1900-01-01placeholders) or aftermax_date(default today); a person with no plausible event gets no period. Pass the source’s data cutoff asmax_datewhen events are filled with the build date. New DQD checkplausibleObservationPeriod(run_dqd(observation_period_min=)) flags starts before the minimum, ends after the extraction date and inverted periods. Rebuild existing databases to apply the rule. -
FR-C12 key check at build time (Python):
etl_pcornet(key_check="warn"|"raise"|"ignore", key_check_callback=)runscheck_etl_keys()onENCOUNTERID(andPATIDwithdisambiguate_patids), reports distinct ids against distinct keys and thevisit_occurrence/personrow count, andomop-duckdb buildwrites the results torun_manifest.jsonaskey_check:*steps. -
FR-D4 read-only vocabulary:
attach_read_only()(Python) andreadonly_attach_sql()(R) attach the CDM and the shared vocabulary fileREAD_ONLYunder the namecentral_vocab, so site files whoseconceptis a view into it work withoutmaterialize-vocab.cohorts/run_plp_readonly_example.Rtakesvocab_file. - FR-D5 Circe JSON: both cohort SQL files now state they are the authoritative definition; tests check the Circe JSON’s structure and consistency with the SQL. The JSON has still not been imported into ATLAS.
omopduckdb 0.8.3
Cohort tooling follow-up to 0.8.2 (notes N4, N7, FR-D3).
-
Renamed SQL parameters (breaking for direct callers of the cohort SQL):
cohorts/target_cohort.sqlandoutcome_cohort.sqlnow share CohortGenerator’s names@cdm_database_schema,@target_database_schema,@target_cohort_table,@target_cohort_id(was@cohort_database_schema,@cohort_table,@outcome_cohort_id). Cohort behaviour is unchanged. -
cohort_definition_set()(R) returns a CohortGenerator-stylecohortDefinitionSet(cohortId,cohortName,sql,json) with@followup_days/@min_agerendered. Not yet run throughCohortGenerator::generateCohortSet(). -
cohorts/run_plp_readonly_example.R: runs the cohorts and PatientLevelPrediction on a read-only CDM (attachedREAD_ONLY, cohort rows in a scratch DuckDB). The SQL part is tested; theDatabaseConnector::connectwrapper is not.
omopduckdb 0.8.2
Known CI gap (Windows): on the GitHub Windows runner the R process running the full test suite intermittently exits without a message (no testthat failure; output buffering hides where). It happened in 7 of 9 runs when tests wrote real Andromeda 1.x tables, and about 1 in 6 runs even with those tests skipped, always in the PatientLevelPrediction / FeatureExtraction / Andromeda / DuckDB tests (identical package versions in passing and failing runs; Ubuntu and a local Windows 11 machine are fine). The three tests that write Andromeda tables are skipped on Windows, so
duckdb_to_andromeda()is unverified on Windows CI. Re-running the Windowsr-checkjob usually passes. Cause unknown; an upstream (HADES/Andromeda/DuckDB) problem is the leading suspect.
Closes the gaps left by the 2026-10 consortium audit. Most audit items (FR-A1-A5, B1-B4, C1-C6) had already shipped in 0.7.0/0.8.x; this release adds what was missing.
-
FR-C9 (HADES):
hades_set_integer64()(R) setsdatabaseConnectorInteger64AsNumeric = FALSEso 63-bit ids no longer stopDatabaseConnector::querySql()with “integers >= 2^53”;plp_database_details()andcm_database_details()call it when the database holds ids >= 2^53 (integer64 = "auto";hades_needs_integer64()does the check), because forcinginteger64for small ids crashedgetPlpData()on Windows. Newpcornet_id53()macro (53-bit keys, safe as R doubles) for callers who need it; the ETL still usespcornet_id()and sequential person ids.materialize_vocabulary()/omop-duckdb materialize-vocabcopiescentral_vocabviews into real tables so a file opened alone resolvesconcept. -
FR-D1: portable
cohorts/target_cohort.sql,outcome_cohort.sql(OHDSI SQL), Circe JSON,cohorts/run_plp_example.Randcohorts/OMOP_COHORT_DEFINITION.md. Verified on DuckDB only; see the doc. -
FR-D2:
sampling_rule="earliest"(alias offirst) and"stable_random"(MD5-based, version-stable);persist_index_visits()writes anindex_visittable."random"is unchanged (DuckDBhash()). -
FR-C8:
check_key_collisions()compares distinct source ids with distinct surrogate keys (warn/raise). -
FR-C7: DQD
isPrimaryKeyDuplicatecheck onvisit_occurrence_id. -
Fix (R):
duckdb_to_andromeda()returned an empty Andromeda whenever DuckDB’s SQLite extension was available: it attached the Andromeda file as SQLite, but Andromeda 1.x is DuckDB-backed, so tables landed in an unrelated file. It now always writes through Andromeda’s own interface in chunks (newchunk_size;output_fileis deprecated and ignored). This was thetest-v056-features.Rfailure in R CMD check and test-coverage. -
FR-A6:
extract_standard_labs(egfr="ckd_epi_2021"|"measured", anion_gap=True); completeANION_GAP_LOINCS/EGFR_LOINCSsets (69405-9 and 77147-7 added to the Table 1 eGFR set); warns when a standard lab is empty.
omopduckdb 0.8.1
-
Fix:
pcornet_id()no longer uses DuckDBhash(). Widening to 63 bits in 0.8.0 did not help:hash()itself collides on real encounter IDs (160 of 75,804,013 and 62 of 46,990,031 distinct raw encounters lost at two large sites; zero lost with MD5). The macro is now(md5_number_lower(source_id::VARCHAR) & 9223372036854775807)::BIGINT. Databases rebuilt with 0.8.0 should be rebuilt.
omopduckdb 0.8.0
Release 0.8.0 resolves all five concrete engineering, data quality, and clinical replication gaps identified in the October 21 feature request RFC (FR-C5, FR-C6, FR-C7, FR-C8, FR-A6) and October 23 cross-site audit, enabling 120% feature-complete, autonomous, push-button replication for external consortium health systems across Python (omop_etl, omop_duck_db) and R (omopduckdb).
1. 63-Bit Signed BIGINT Surrogate Keys (FR-C8)
-
Eliminated 31-bit Integer Collision Loss: Upgraded
pcornet_id(source_id)macro ininst/sql/mapping_macros.sqlfrom(hash(source_id) % 2000000000)::INTEGERto 63-bit signed BIGINT:(hash(source_id) & 9223372036854775807)::BIGINT. -
DDL Widening: Widened all 83 surrogate and foreign key identifier columns (
*_id) inOMOPCDM_duckdb_5.4_ddl.sqlfromintegertobigint(retaining standard vocabulary concept identifiers asinteger). -
Multi-Dialect Export Alignment: Updated
export_targets.pyandexport_targets.Racross all enterprise export dialects: Oracle (NUMBER(19)), SQL Server (BIGINT), Snowflake (NUMBER(19,0)), and BigQuery (INT64). Prevents silent encounter drops and cross-patient record contamination at high-volume sites (e.g. Site D / Site E).
2. ETL Crash Vulnerabilities Eliminated (FR-C5 & FR-C6)
-
Staged Vital Inserts: Refactored
load_vitalinbuild_omop_cdm.pyandetl_pcornet.Rfrom a single massive 5-wayUNION ALLwith global sorting into 5 staged, single-analyte materializations (HT,WT,BMI,SYSTOLIC,DIASTOLIC). Completely eliminates memory exhaustion and DuckDB Windows access violations on multi-million-row vital files. -
Regex-Guarded Datetime Parsing: Re-engineered
parse_omop_datetime(d, t)with multi-pattern format matching andnormalize_time_str(t)to gracefully handle single-digit hours (e.g.1:01with01AUG2002->2002-08-01 01:01:00) and arbitrary time variants without unhandled parse crashes.
3. Study Phenotyping & Dynamic Lab Gaps Resolved (FR-A6)
-
Authoritative eDERRI Diabetes Cohort Phenotype: Added
build_ederri_diabetes_cohort()in Python and R, and exposed--type ederri_diabetes/diabetesviaomop-duckdb cohort define. Phenotype requires adult inpatient admission with wash-in, discharged alive, with explicit diabetes evidence:- ICD-9:
249,250 - ICD-10:
E08,E09,E10,E11,E13(and standard concept descendants of201820) - Antidiabetic medications (ATC A10 / RxNorm classes: insulin, metformin, sulfonylureas, GLP-1, SGLT2)
- $ ext{HbA}_{1c} %$ (LOINCs
4548-4,17856-6,4549-2, concept IDs3004410,3005673,40762352).
- ICD-9:
-
Race-Free CKD-EPI 2021 Dynamic eGFR Equation: Integrated
compute_ckd_epi_2021(creatinine, age, is_female)intoextract_velocity_featuresin Python and R. Dynamically evaluates eGFR whenever missing or capped at clinical reporting thresholds (), eliminating cross-site missingness. -
Expanded Anion Gap LOINC Set & Stoichiometric Fallback: Expanded anion gap LOINCs in
table1.py/table1.Rto include41276-7alongside1863-0and33037-3. Added dynamic stoichiometric fallbackext{Na} - ( ext{Cl} + ext{HCO}_3)toextract_velocity_features.
4. DataQualityDashboard (DQD) Person-Visit Consistency Check (FR-C7)
-
Foreign Key Person-Visit Integrity: Implemented
fkPersonVisitConsistencycheck (FIELD_FK_PERSON_VISIT_<TABLE>) in nativerun_dqd()across Python (dqd.py) and R (dqd.R). Cross-verifies thatclinical_table.person_id == visit_occurrence.person_idacrosscondition_occurrence,procedure_occurrence,drug_exposure,measurement,observation, anddevice_exposure, detecting and reporting mismatches before external validation.
5. Deep Learning Sequence Models & Tri-Model Ensemble Blend Support
Longitudinal Sequence Tensors: Added
extract_longitudinal_tensors()inomop_etl.tensorto build 3D concept token tensors directly in DuckDB from historical inpatient encounters.Model Bundle Support for Blackwell Deep Learning: Updated
model_bundle.pyto support.ptPyTorch model weights and TorchScript bundles underdeep_residualandtorchscript. Added automatic 3D tensor extraction and dispatch inModelBundle.predict_probaandomop-duckdb evaluatewhen components requireinput: "sequence_tensor".omop-duckdb evaluate(Python): one command chainscheck_source, cohort,extract_velocity_features,validate_feature_frame,score_cohort,site_telemetryand a run manifest; only the aggregate packet and manifest are written (omop_etl.evaluate.evaluate_site()).Strict JSON: every exchanged JSON file (feature specs, bundles, manifests, telemetry, DQD and integrity reports) now writes
nullinstead ofNaN/Infinity, in Python (omop_etl.jsonio) and R (na = "null"); specs that already containNaNtokens are read asnull.Live-database CI (
.github/workflows/live-db.yml,tests/test_live_databases.py): PostgreSQL 16, SQL Server 2022 and Oracle Free service containers exercise chunkedfrom_sql,import_omopand execution of the generated SQL Server / Oracle DDL. The[oracle]extra now requires SQLAlchemy 2.x.Fixed (found by the first live Oracle run):
from_sql()truncated OracleNUMBER(p,s)columns with decimals to integers (Oracle’sNUMBERtype is both Numeric and Integer); they now map to Arrow decimals.Tests: optional PyTorch tests skip cleanly when the import raises
OSError(Windows DLL initialisation failure) as well asImportError.
omopduckdb 0.7.0
Release 0.7.0 adds source-database neutrality, hash-verified model deployment, consortium telemetry, run manifests, velocity features and more export targets, in Python and (mostly) R. It also changes a few defaults; read Upgrade notes first.
Upgrade notes
-
R installs need
jsonlite(now in Imports, withstatsandutils). -
run_dqd()gains aplausibleDateRangecheck on every clinical*_datecolumn (default 1950-01-01 to the extraction date), so pass rates differ from earlier reports. Useplausible_date_range=for sites with a far-future sentinel such as 2099-12-31. -
Oracle export changed: typed
.ctlfiles withSKIP=1and explicit date masks,NUMBER(10)/VARCHAR2(n CHAR)DDL, 30-character identifier check (oracle_max_identifier=128for 12.2+), reserved words quoted,load_oracle.shexpects$ORA_CONN. Regenerate old Oracle exports. -
omop-duckdb buildandomop-duckdb cohort define --type inpatientnow work (they previously called library functions with wrong arguments).buildrunsbuild_schema, so use a new target file. - Not exercised against real PostgreSQL, Oracle, SQL Server, Snowflake or BigQuery databases, and the XGBoost/ONNX bundle paths are untested; please report problems.
What is new
Python-side additions from the 2026-10 consortium audit (FEATURE_REQUESTS_POST_0.6.8.md). R ports are included for A1 (logistic and XGBoost-JSON bundles; ONNX/TorchScript components are Python-only), A2, A3, A4 and B1/B2 (from_sql() / import_omop() take an open DBI connection instead of a SQLAlchemy URL). Bundles and telemetry packets are interchangeable between the two languages. Also ported to R: B3 (check_source(), Parquet source files, etl_pcornet(strict_source = TRUE)), A5 (run_manifest(), write_run_manifest(), verify_manifest()), C1 (run_dqd() plausibleDateRange), C2 (split_by_date()) and C3 (define_study_cohort(persist_keys=)). Not ported to R: C4 secret scanning (repository-level, language independent) and the omop-duckdb CLI commands.
-
Source-database neutrality (FR-B1/B2/B3):
omop-duckdb extract/omop_etl.extract.from_sql()streams any SQLAlchemy source to Parquet in chunks (typed from the reflected schema, lower-cased columns, case-insensitive table lookup,--table-map,env:VARURLs, secrets never logged; extras[postgres],[mssql],[oracle],[snowflake]).omop-duckdb import-omop/import_omop()copies an existing OMOP CDM from a server into DuckDB. The PCORnet ETL now reads<table>.parquetas well as.csv;omop-duckdb check-source/check_source()reports present tables/columns andetl_pcornet(strict_source=True)fails fast naming the missing column and table. -
Model deployment (FR-A1/A2/A3/A5): pickle-free, SHA-256-verified model bundles (
load_model_bundle,score_cohort,write_model_bundle; logistic JSON built in, XGBoost JSON / ONNX / TorchScript with the[bundle]extra); aggregate-onlysite_telemetry()packets (JSON-Schema validated, small-cell + secondary suppression) and a random-effectsaggregate_telemetry()(Cochran Q, I2, tau2);validate_feature_frame()with raise/clip/nullify;RunManifest/run_manifest.json,--manifest/--verify-manifestandomop-duckdb verify-manifest;omop-duckdb score. -
Features and operations (FR-A4/C1/C2/C3/C4):
engineer_clinical_features()/extract_velocity_features()(a port ofscripts/engineer_clinical_features.pysections 1-5, pinned to the script by a golden file shared by the Python and R tests; the 365-day sentinel isNO_PRIOR_VISIT_DAYS; the script’s label-leakingsite_baseline_riskis replaced by a training-rows-onlysite_baseline_risk()); DQDplausibleDateRangeon every clinical*_datecolumn;split_by_date()held-out split with per-table counts and checksums;define_study_cohort(persist_keys=..., one_per_patient=True); CIsecret-scanjob,.gitleaks.toml, pre-commit hook,scripts/secret_scan.py. -
Export targets (FR-B4, Python and R):
export_cdm()now supportssqlserver(CSV +BULK INSERT),snowflake(Parquet +PUT/COPY INTO) andbigquery(Parquet +bq load) next tooracle. DDL, data files and loader scripts are generated from the single CDM DDL file (load_cdm_schema(),generate_ddl()), andlint_ddl()(plussqlglotparsing in Python CI) checks them. Oracle: 30-character identifier check (oracle_max_identifier), reserved words quoted, explicit date masks instead ofNLS_DATE_FORMAT, and the.ctlfiles now skip the CSV header (SKIP=1) and load typed fields. - Fixed:
omop-duckdb buildandomop-duckdb cohort define --type inpatientcalled their library functions with wrong arguments.
omopduckdb 0.6.8
Release 0.6.8 introduces native tabular file and workbook loaders (.from_excel(), .from_csv(), .from_csvs(), .from_folder(), .from_bundled()) for HierarchicalRollup and RollupEngine, bundled clinical reference code lists for multi-site studies (eDERRI / antidiabetic medications), cryptographic file-hash cache invalidation for Parquet crosswalks, and legacy headerless file support with complete 1:1 cross-language parity between Python (omop_etl, omop_duck_db) and R (omopduckdb):
1. Native Tabular File and Workbook Loaders for Rollups
-
Single-Class Tabular Ingestion (
HierarchicalRollup.from_excel,HierarchicalRollup.from_csv,HierarchicalRollup.from_bundled):- Ingests single medication or condition classes directly from Excel workbook sheets or CSV files with automated column resolution (
code_col,class_col,vocabulary_col). - Native R equivalents:
hierarchical_rollup_from_excel(),hierarchical_rollup_from_csv(),hierarchical_rollup_from_bundled().
- Ingests single medication or condition classes directly from Excel workbook sheets or CSV files with automated column resolution (
-
Multi-Class Engine Loaders (
RollupEngine.from_excel,RollupEngine.from_csvs,RollupEngine.from_folder,RollupEngine.from_bundled):- Automatically splits multi-class sheets, sequences of CSV files, or entire directories of CSV files into structured batteries of
HierarchicalRollupobjects. - Multi-class exposure extraction directly tags each drug exposure with its corresponding
rollup_name. - Native R equivalents:
rollup_engine_from_excel(),rollup_engine_from_csvs(),rollup_engine_from_folder(),rollup_engine_from_bundled().
- Automatically splits multi-class sheets, sequences of CSV files, or entire directories of CSV files into structured batteries of
-
Legacy & Headerless Academic CSV Support:
- Supports 0-indexed column integer references (e.g.,
code_col=1, class_col=0) to ingest legacy two-column code lists without required headers.
- Supports 0-indexed column integer references (e.g.,
2. Bundled Clinical Reference Workbooks & Code Lists
-
Packaged Study Reference Code Lists (
inst/extdata/code_lists/):- Bundles standard clinical code lists for eDERRI antidiabetic medications (
ederri_medications.csv,diabetes_drug_categories.csv,rxnorm_categories_CUI_map_brief.csv,eDERRI_Clinical_Review_Package.xlsx). - Readily accessible via
.from_bundled("ederri_medications")in Python androllup_engine_from_bundled("ederri_medications")in R without needing external file paths.
- Bundles standard clinical code lists for eDERRI antidiabetic medications (
3. Cryptographic File-Hash Crosswalk Cache Invalidation
-
Automated Cache Invalidation:
- Stores SHA-256 digests of underlying source workbooks and CSV files within
source_file_hashesand incorporates them intospec_hash. - When an investigator updates or modifies an underlying Excel workbook or CSV code list, cached Parquet crosswalks are automatically recognized as stale and re-materialized directly in DuckDB.
- Stores SHA-256 digests of underlying source workbooks and CSV files within
omopduckdb 0.6.4
Release 0.6.4 introduces production medication classification guards, explainable strategy auditing, publication-grade data quality assertions, causal inference nearest-neighbor matching, automated negative controls, semantic concept set optimization, longitudinal trajectory features, and federated survival meta-analysis with complete 1:1 cross-language parity between Python (omop_etl, omop_duck_db) and R (omopduckdb):
1. Medication Classification Guards & Strategy Disagreement Explainer
-
Silent-Zero & Unresolved Concept Guards (
on_unresolved='raise'|'warn'):-
extract_medication_classes()detects medication classes whose ATC codes or ingredient concept IDs fail to resolve to any concepts or descendants inconcept_ancestor, preventing silent-zero exposure drop-offs. - Added
route_concept_idsandexclude_forms(e.g.['Ophthalmic', 'Topical']) to cleanly distinguish systemic from non-systemic formulations. - Added
by_type=Trueemitting per-source exposure flags (<class>_type_<id>) for prescriptions vs. administrations.
-
-
Both-Blind Auditing & Exposure Assertions (
audit_medication_strategies,assert_exposure_coverage):- Added
both_blindreason when prevalence is 0 under both source and standard strategies in sites with sufficient sample size (min_n). - Added
min_prevalencefloor checks to flag unexpected exposure absences. - Added
assert_exposure_coverage(flags, classes, min_n=1000)to prevent silent-zero exposure bugs across consortium hospital sites.
- Added
-
Disagreement Explainer with Small-Cell Suppression (
explain_medication_disagreement):- Unpacks disagreements between source crosswalks and OMOP hierarchies, reporting top unmapped source values and standard concepts.
- Automatically suppresses cells with counts under 11 (
min_cell_count=11,is_suppressed=True), enabling safe cross-site export.
-
Standardized Crosswalk Exporter (
export_medication_crosswalk):- Exports OMOP class definitions into standardized crosswalk tables (
source = 'current' | 'maps_to'). - Supports older retired RxNorm concepts (
include_retired=True) and strict validation (must_contain=[...]).
- Exports OMOP class definitions into standardized crosswalk tables (
2. Rigorous Data Quality, Plausibility, and Feature Integrity Audits
-
Code-List Coverage Audit (
audit_code_list_coverage):- Computes the proportion of clinical occurrences captured by supplied ICD/RxNorm/LOINC lists, identifying high-frequency uncaptured concepts () per site.
-
Panel Missingness Audit (
panel_missingness_audit):- Detects component missingness discordance within standard multi-analyte laboratory panels (BMP/CBC) and flags multi-site peer outliers.
-
Table-Level Physiological Plausibility Report & CI Gate (
plausibility_report):- Audits Table 1 summaries and raw feature matrices against clinical bounds (
DEFAULT_PHYSIOLOGIC_BOUNDS), extreme variance/SD ratios, negative physiological values, and impossible percentages. Supports strict validation gates (ci_gate=True).
- Audits Table 1 summaries and raw feature matrices against clinical bounds (
-
Redundant Feature Detector (
detect_redundant_features):- Detects rule-of-three linear conversions (e.g. Hematocrit = 3 * Hemoglobin), constant differences, and near-perfect multicollinearities.
-
DQD Mathematical Consistency Summary (
dqd_summary):- Recomputes total, passed, failed, and not-applicable checks to verify exact reproducibility of reported pass rates in 1/N increments.
3. Pipeline Reconciliation, Forced Index Stays, and Parity Ledger
-
Forced-Index Cohorts from External Stays (
cohort_from_index_stays):- Ingests external legacy stay files (patient ID, encounter ID, index date, end date) and maps to OMOP
person_idandvisit_occurrence_id. - Emits full audit tallies (
total_input_stays,matched_patients,unmatched_patients,patient_match_rate,matched_encounters,unmatched_encounters,encounter_match_rate). - Registers the forced cohort table in DuckDB for downstream study extraction.
- Ingests external legacy stay files (patient ID, encounter ID, index date, end date) and maps to OMOP
-
Feature-Table Parity Ledger (
compare_feature_tables):- Matches rows across legacy and new pipelines and evaluates feature-by-feature parity.
- Computes Standardized Mean Differences (SMDs), Pearson correlation / binary kappa, and missingness gaps.
- Automatically flags discrepancies with clear reason codes:
large_smd(),missingness_gap(),scale_mismatch( or SD ratio),zero_variance, andall_zero. - Supports site stratification with HIPAA/GDPR-compliant small-cell suppression () on sample counts.
-
Cohort Reconciliation & Overlap (
cohort_overlap):- Reconciles cohort membership between divergent definitions or pipelines.
- Reports counts in A-only, B-only, both, Jaccard similarity index, concordance rate, and outcome event rates in intersection and discordant strata.
-
Multi-Parameter Sensitivity Grid (
run_study_grid):- Executes study definitions across parameter grids (e.g. sampling rules, lookback windows, wash-in periods).
- Emits side-by-side N, event counts, and event rates overall and stratified by site.
4. Data Integrity, Statistical Leakage, Informative Missingness, and Provenance
-
Statistical Leakage Scan (
leakage_scan):- Flags features with perfect or near-perfect stratum separation, single-feature AUC , pure 0/1 outcome rates in non-trivial strata, and temporal sequence violations where data occurs after index date.
-
Informative Missingness Helpers (
add_missing_indicators,missingness_by_outcome):- Adds binary missingness indicator columns (
miss_<col>) and evaluates missingness proportions stratified by outcome ( vs. ). - Evaluates missingness gaps and preserves explicit fill-rule metadata across consortium summaries.
- Adds binary missingness indicator columns (
-
System Provenance Stamp (
provenance,check_vocabulary_provenance):- Captures library version, DuckDB version, active vocabulary releases per
vocabulary_id, random seed, and git commit SHA. - Compares vocabulary provenance between databases to prevent silent version drift across network sites.
- Captures library version, DuckDB version, active vocabulary releases per
-
Numbers-of-Record Manifest & Stale-Number Scanner (
numbers_of_record,scan_document_numbers):- Generates authoritative JSON manifests of cohort sample sizes and outcome event counts.
- Scans rendered manuscripts (Markdown, Quarto, LaTeX) to detect stale figures left over from older cohort runs or unverified numbers.
-
Vocabulary & Input Preflight Verification (
vocabulary_preflight):- Verifies presence of required vocabularies, ATC descendant coverage in
concept_ancestor, and unmapped concept 0 rates across clinical tables with fast-fail safety guards.
- Verifies presence of required vocabularies, ATC descendant coverage in
-
Privacy-Preserving Cross-Site Overlap (
generate_site_patient_tokens,consortium_patient_overlap):- Locally computes HMAC-SHA256 salted patient tokens without exposing raw IDs.
- Computes pairwise cross-site overlap with automated HIPAA/GDPR small-cell suppression ().
-
CMS Planned-Readmission Filter (
planned_readmission_filter):- Identifies and excludes planned maintenance chemotherapy, transplants, and elective procedures from readmission outcomes, reporting removal tallies by site.
-
Observation Period Diagnostics (
observation_period_diagnostics):- Compares patient qualification under constructed
observation_periodvs. first-observed clinical events to assess wash-in validity.
- Compares patient qualification under constructed
5. Advanced Causal Inference, Calibration, Trajectories, Survival & Synthetic Data
-
Interactive Cohort Attrition Flow & Heatmaps (
plot_consort_flow,plot_multisite_attrition_heatmap):- Interactive Plotly Sankey diagrams and camera-ready SVG alluvial flowcharts rendering sequential exclusions and retentions for publication and Quarto manuscripts.
- Multi-site attrition heatmaps highlighting outlier patient loss across consortium network partners.
-
Propensity Score Nearest-Neighbor Matching & Love Plot (
consortium_propensity_score,match_nearest_neighbor,plot_love_plot):- 1:k greedy nearest-neighbor caliper matching on logit(PS) executing directly on DuckDB feature tables.
- Camera-ready SVG Love plots verifying pre- and post-adjustment covariate balance against the SMD clinical threshold.
-
Automated Negative Controls & Empirical Calibration (
generate_negative_controls,calibrate_estimates):- Traverses OMOP concept hierarchies (
concept_ancestor,concept_relationship) to identify candidate negative control outcome sets with zero mechanistic or ancestral links. - Fits empirical Gaussian null distributions to calibrate study p-values and confidence intervals against residual systematic bias.
- Traverses OMOP concept hierarchies (
-
Semantic Concept Set Optimizer & Usagi Auto-Suggester (
optimize_concept_set):- Scans clinical occurrence co-occurrences, sibling hierarchy closures, and lexical synonyms to suggest missing clinical concepts and high-frequency unmapped source codes (
concept_id = 0).
- Scans clinical occurrence co-occurrences, sibling hierarchy closures, and lexical synonyms to suggest missing clinical concepts and high-frequency unmapped source codes (
-
Longitudinal Temporal Trajectory Features (
extract_temporal_trajectories):- Exploits DuckDB’s vectorized
regr_slope,regr_r2, andstddev_sampto compute longitudinal rates of change, goodness of fit, and volatility over look-back windows without row-by-row iteration.
- Exploits DuckDB’s vectorized
-
Multi-Site Federated Survival Meta-Analysis (
consortium_survival_meta_analysis):- DerSimonian-Laird random-effects pooling of Cox Proportional Hazard Ratios across participating sites.
- Federated non-parametric Kaplan-Meier survival curves with small-cell privacy suppression ().
-
Automated Synthetic OMOP Twin Cohort Generator (
generate_synthetic_omop_twin):- Extracts marginal concept distributions, age-sex distributions, and event timings to emit structurally identical, anonymized synthetic OMOP DuckDB databases for open benchmarking without HIPAA/PHI exposure.
-
PCORnet MED_ADMIN and DISPENSING Loading:
- Maps inpatient administrations (
MED_ADMIN) and outpatient dispensings (DISPENSING) todrug_exposurewith distinct standard type concepts (38000180and38000175), dosage units, and administration timestamps.
- Maps inpatient administrations (
-
Row-Level Provenance in Table 1 Footnotes:
- Extends
table1_to_quarto()andtable1_to_typst()with lookback windows, anchor dates, bounds, units, fill rules, and concept sets per row.
- Extends
omopduckdb 0.6.3
Release 0.6.3 delivers forward-looking consortium intelligence capabilities for federated clinical research, bridging OHDSI network standards and modern medical publishing with complete 1:1 parity between Python (omop_etl, omop_duck_db) and R (omopduckdb):
1. Complementary / Secondary Cell Suppression (secondary_suppression = True)
-
audit_cell_suppression()andconsortium_privacy_audit()(Python & R):- Prevents deductive algebraic disclosure () in multi-site summary tables with marginal totals.
- When exactly one cell in a row or column is suppressed (), automatically identifies and masks the second-smallest non-zero cell in that row/column.
- Distinguishes and tracks
primary_suppressedvs.secondary_suppressedcell counts inPrivacyAuditResultandconsortium_privacy_auditsummary diagnostics.
2. Robust Multivariable Odds Ratios with L2 / Ridge Inversion (consortium_multivariable_risk_factors)
-
consortium_multivariable_risk_factors()(Python & R) inomop_duck_db.ml:- Eliminates collinear and linearly dependent clinical features via QR orthogonalization.
- Uses L2 regularized logistic regression (ridge inversion) to guarantee an invertible parameter covariance matrix , eliminating NaN standard errors and missing 95% CIs on high-dimensional clinical feature matrices.
- Standardizes continuous features to 1-SD units (“Per 1-SD Increase”) while preserving binary indicator features (“Presence vs. Absence”).
- Emits publication-grade Table 5 outputs with domain groupings (Demographics, Comorbidities, Medications, Procedures, Laboratory & Vitals), Odds Ratios, 95% CIs, and Wald p-values.
- Includes camera-ready Forest Plot visualization (
.plot_forest(), base-Rplot()) and Quarto/Typst export.
3. Pure DuckDB OHDSI Cohort Diagnostics (consortium_cohort_diagnostics)
-
consortium_cohort_diagnostics()(Python & R):- Fully characterizes study cohorts across federated network sites directly in DuckDB without R/Java, rJava, or DatabaseConnector dependencies.
- Computes calendar-year incidence rates (new cases, person-years, incidence rate per 1,000 PY).
- Computes time-to-event and follow-up duration distributions (min, p25, median, p75, max, mean, sd).
- Generates 10-year age and sex population pyramids stratified by gender.
- Identifies top baseline concept prevalence deltas for conditions and medications in the lookback window.
- Integrates automated secondary cell suppression to guarantee HIPAA/GDPR compliance before diagnostic outputs leave local environments.
4. Internal-External Cross-Validation (IECV) Matrix (consortium_cross_site_validation)
-
consortium_cross_site_validation()(Python & R):- Fits predictive models on Site and evaluates on Site across a consortium matrix to evaluate multi-hospital transportability and domain shift.
- Computes AUROC and Brier score matrices, mean internal performance (diagonal), mean external performance (off-diagonal), and the multi-site generalization gap.
- Provides publication-ready cross-site transportability heatmaps (
.plot_heatmap()) and Quarto/Typst table exports.
5. Bidirectional OHDSI Circe JSON Exporter (export_to_circe_json)
-
export_to_circe_json()(Python & R) andCohortFlow.to_circe_json():- Exports computable cohorts defined in DuckDB/Python/R back into compliant OHDSI Circe JSON specifications.
- Seamlessly integrates with OHDSI Atlas, ATLAS Network Studies, and the OHDSI Phenotype Library.
- Achieves 100% round-trip fidelity verified against
compile_circe_to_duckdb.
6. End-to-End Manuscript Scaffold Builder (build_manuscript_scaffold)
-
build_manuscript_scaffold()(Python & R) andFederatedConsortium.build_manuscript():- Bundles generated consortium study artifacts (Table 1, Table 2 CONSORT flow, Table 5 risk factors, IECV transportability matrix, cohort diagnostics, calibration curves, DCA net benefit, and explainability) into a unified, submission-ready Quarto (
.qmd) or Typst (.typ) document. - Built-in structured formatting presets matching target journal requirements (JAMA, The Lancet Digital Health, JAMIA, and General).
- Appends an itemized 22-item TRIPOD Statement reporting compliance checklist table mapped directly to the generated study sections and figures.
- Bundles generated consortium study artifacts (Table 1, Table 2 CONSORT flow, Table 5 risk factors, IECV transportability matrix, cohort diagnostics, calibration curves, DCA net benefit, and explainability) into a unified, submission-ready Quarto (
omopduckdb 0.6.2
Release 0.6.2 adds three modular, zero-hard-dependency capabilities for federated health system intelligence, with complete 1:1 parity between Python (omop_etl, omop_duck_db) and R (omopduckdb):
1. Automated Privacy-Preserving Cell Suppression Auditor
-
audit_cell_suppression()andconsortium_privacy_audit()(Python & R):- Audits exported multi-site summary tables (Table 1, Table 2, risk factor tables, patient counts) for compliance with HIPAA Safe Harbor, CMS, and GDPR small-cell de-identification governance rules.
- Automatically identifies small cell counts (, e.g. or ) in both raw counts and formatted count/percent strings (e.g.
"5 (2.3%)"). - Preserves legitimate statistical values such as p-values, standardized mean differences (SMDs), means, medians, and IQRs.
- Returns
PrivacyAuditResult(Python) /consortium_privacy_audit(R) containing cleaned data frames, total violation counts, flagged column details, and summary audit diagnostics. - Integrated directly into
FederatedConsortium.audit_cell_suppression()/consortium$audit_privacy().
2. Direct Quarto and Typst Publication Styler
-
table1_to_quarto(),table1_to_typst(),Table1Generator.to_quarto(), andTable1Generator.to_typst()(Python & R):- Directly outputs camera-ready Quarto markdown (
tbl-colwidths,#| label,#| tbl-cap) and Typst markup (#table(columns: ..., ...)). - Formats bracketed confidence intervals and ranges cleanly (
[12.3, 45.6]). - Supports automatic superscript footnote annotations for standard LOINC codes and custom mapping metadata (
LOINC 59260-0^1). - Provides multi-level header spans and cross-site stratification without requiring manual LaTeX string post-processing.
- Integrated into
export_table1(format = "quarto" | "typst")andTable1Generatorclass/R6 instances.
- Directly outputs camera-ready Quarto markdown (
3. Built-in Tree Model Explainability & TRIPOD Reporting
-
ConsortiumExplainabilityandconsortium_explainability()(Python & R):- Provides model-agnostic and tree-based feature attribution, direction of effect, TRIPOD Item 13b / STROBE Item 15a compliant variable importance tables, and cross-site feature importance drift auditing across federated health systems.
- Zero heavy dependencies: supports SHAP (via optional
shaplibrary in Python), native tree gain/Gini importances (randomForest,rpart,feature_importances_,coef_), or robust multi-iteration permutation importance fallbacks. - Evaluates cross-site feature importance drift across member medical centers when
site_labelsare supplied, identifying ranking concordance and site-specific predictor variance. - Includes publication-grade visualization methods:
.plot_importance(),.plot_beeswarm(), and base-Rplot.consortium_explainability().
omopduckdb 0.6.1
Release 0.6.1 delivers high-impact multi-site consortium analytics, cross-site model calibration, clinical decision curve analysis, automated international unit scaling, and competing-risk cumulative incidence function modeling with complete 1:1 parity between Python (omop_etl / omop_duck_db) and R (omopduckdb).
1. Consortium-Level Bedside Scoring Wrapper
-
FederatedConsortium.calculate_scores()(Python) andconsortium_calculate_scores()(R):- Directly evaluates bedside clinical risk scores (
calculate_lace_indexandcalculate_hospital_score) across multi-center federated consortia (e.g. eDERRI studies) in a single pass. - Automatically provisions transparent base table alias views (
CREATE OR REPLACE VIEW {tbl} AS SELECT * FROM v_{tbl}) alongside prefixedv_{tbl}views, enabling standard ETL and scoring functions to run on federated DuckDB connections without query modification. - Returns
ConsortiumScoreResult(Python) /consortium_scores(R) with overall and site-stratified risk score distributions, high-risk counts, and risk tier breakdowns, supporting.summary(),.to_dataframe(), and S3 methods (print,summary,as.data.frame).
- Directly evaluates bedside clinical risk scores (
2. Cross-Site Model Calibration & Decile Drift
-
consortium_calibration()andConsortiumCalibration(Python & R):- Solves multi-site model transportability and risk miscalibration across academic medical centers and community health systems.
- Computes site-stratified logistic calibration curves via robust pure Iteratively Reweighted Least Squares (IRLS).
- Evaluates site-specific Brier scores, Expected Calibration Error (ECE), and Maximum Calibration Error (MCE).
- Implements the multi-site Greenwood-Nam-D’Agostino goodness-of-fit test assessing cross-site calibration drift.
- Quantifies decile drift matrix profiling how predicted risk bins shift across member health systems.
- Publication-grade multi-panel calibration plotting via
.plot()/plot.consortium_calibration().
3. Clinical Decision Curve Analysis (DCA)
-
decision_curve_analysis()andDecisionCurveAnalysis(Python & R):- Evaluates clinical net benefit across decision threshold ranges (Vickers et al., 2006) to demonstrate utility over “treat all” and “treat none” baseline strategies.
- Computes Net Benefit (), Standardized Net Benefit (sNB), and Net Reduction in Interventions per 100 patients.
- Outputs summary tables, optimal clinical threshold range identification, and publication-ready multi-curve plotting (
.plot()/plot.decision_curve_analysis()).
4. Automated European & IFCC Metric Unit Scaling
- Automated LOINC-aware harmonization in
harmonize_measurement_units()across Python and R:- Hemoglobin in (LOINC
59260-0): Automatic scaling factor . - HbA1c in IFCC (LOINC
59261-8): Affine formula harmonizing to NGSP percent. - Serum Creatinine in : Multiplier (with regex support for
µmol/l/μmol/l). - Automated LOINC detection applies conversions even when source EHR databases leave
unit_source_valueNULL. - Added European LOINCs
59260-0and59261-8toDEFAULT_LAB_LOINCS.
- Hemoglobin in (LOINC
5. Competing Risks Cumulative Incidence Function (CIF) & Fine-Gray Estimator
-
estimate_cif(),fine_gray_estimator(), andplot_cif()(Python & R):- Non-parametric Aalen-Johansen Cumulative Incidence Function estimation for 3-state competing risks outcomes (censored alive, 30-day acute readmission, terminal mortality).
- Computes step-wise cumulative incidences and Greenwood-type standard errors across all event types.
-
fine_gray_estimator()computes subdistribution hazard ratios using subdistribution risk-set weighting. - Multi-curve CIF visualization via
plot_cif()/plot.cif_result(), allowing direct publication of competing-risk adjusted 30-day readmission curves out of the box.
omopduckdb 0.6.0
Release 0.6.0 closes all 7 feature gaps from request 4 with complete 1:1 cross-language parity across Python (omop_etl / omop_duck_db) and R (omopduckdb).
1. Anthropometric Harmonization & Calculated BMI
-
harmonize_anthropometrics()(Python & R): standardizes raw height (inches,[in_us];m) and weight (lbs,[lb_av];oz;g). - Automatically derives BMI and optionally replaces implausible raw BMI measurements ( or ) in the created
measurement_harmonized_anthropometricsview. - Provides robust fallback handling between
measurement_datetimeandmeasurement_date.
2. Clinical Benchmark Bedside Risk Scores
-
calculate_lace_index()(Python & R): Evaluates the standard bedside LACE Index (0–19 points) for 30-day readmission and mortality risk:- L: Length of stay (, , , , , , ).
- A: Acuity of admission ( points for emergency admission).
- C: Charlson Comorbidity Index score (, , , , ).
- E: Emergency department visits in prior 6 months (, , , , ).
-
calculate_hospital_score()(Python & R): Evaluates the bedside HOSPITAL Score (0–10 points) for 30-day potentially avoidable readmissions:- H: Hemoglobin at discharge ( pt).
- O: Oncology discharge / neoplasm diagnosis in prior 365 days ( pts).
- S: Sodium level at discharge ( pt).
- P: Procedure during index stay ( pt).
- I: Index admission type urgent / emergency ( pt).
- T: Prior hospital admissions in past 12 months (, , pts).
- L: Length of stay days ( pts).
- Fixed query boundary bug where index admission ED visits were excluded from acuity evaluation.
3. Transitions-of-Care Medication Trajectories
-
extract_medication_transitions()andMedicationTransitions(Python) /medication_transitions(R):- Trajectory flags per drug class:
{cls}_initiated_inpatient,{cls}_discontinued_at_discharge,{cls}_continued_across_stay. - Consortium summary indicators:
med_initiated_inpatient,med_discontinued_at_discharge,med_continued_across_stay. - Methods
.summary()for transition rate percentages and.transition_matrix(drug_class)for contingency tables.
- Trajectory flags per drug class:
4. Multi-Site Federated Consortium Connector
-
FederatedConsortium(Python) /federated_consortium()(R): Orchestrates multi-site observational analytics across independent DuckDB databases (e.g. eDERRI studies) attached to a central Athena vocabulary. - Unified querying across federated views (
v_person,v_visit_occurrence, etc.). - One-call generation of federated Table 1 (
generate_table1()) and Table 2 missingness audits (generate_table2()). - Automated multi-site audit summaries (
site_summaries()/consortium_site_summaries()).
5. European & Alternative Unit Scaling Factors
-
DEFAULT_UNIT_RULESupdated with affine linear formulas(pattern, multiplier, intercept):- Hemoglobin in (LOINC
59260-0): multiplier . - HbA1c in IFCC (LOINC
59261-8): formula . - Creatinine in : multiplier .
- Height:
in,[in_us],m. - Weight:
lb,[lb_av],oz,g.
- Hemoglobin in (LOINC
6. Population-Specific Bounds Profiles
-
POPULATION_PHYSIOLOGIC_BOUNDSdefines physiologically calibrated ranges foradult,pediatric, andneonatalcohorts. -
filter_bounds(population="adult" | "pediatric" | "neonatal")applies age-appropriate bounds (e.g. Neonatal heart rate 60–260 bpm, systolic BP 35–130 mmHg). -
Table1Generator/table1_generator()acceptspopulation="adult" | "pediatric" | "neonatal".
omopduckdb 0.5.9
Request 2 ships with dual Python and R usage. R functions are snake_case mirrors of the Python classes: filter_bounds, harmonize_measurement_units, medication_extractor, table1_generator, cohort_flow, generate_table2, as_plp_arrow (Python: filter_bounds, harmonize_measurement_units, MedicationExtractor, Table1Generator, CohortFlow, Table2Generator, as_plp_arrow). The domain profiles live once, in inst/extdata/domain_profiles.yml, and a test keeps the Python dict in sync.
Mapping bug fixes (audited against the OMOP vocabulary)
-
LOINC
48642-3(eGFR, MDRD) was inanion_gap, giving an Anion Gap mean of ~59.5 mEq/L. Moved toegfr;anion_gapis now1863-0+33037-3. -
DEFAULT_MEDICATION_CONCEPTShad wrong concept ids (found by the same audit):insulinsheld isoniazid (1782521) and tolazamide plus the whole A10 “diabetes drugs” class;metforminheld A10B (all non-insulin glucose-lowering drugs);sulfonylureasheld nateglinide;statinsheld ACE inhibitors (C09A);raas_inhibitorsheld calcium-channel blockers (C08);antihypertensivesheld only beta blockers. Now A10A, A10BA, A10BB, C10AA, C09 and C02+C07+C08+C09. Behaviour change: flag counts for these classes will change. - Still open (not changed):
33914-3is a deprecated LOINC (kept for legacy data);59260-0hemoglobin is mmol/L, so mixing it with718-7is only safe after unit harmonization; wide-vitalHT/WTuse[in_us]/[lb_av]labels with UCUM concept ids 9326 (British inch) / 8739 (US pound);PHYSIOLOGIC_LAB_BOUNDS(e.g. potassium 1.5-10, hemoglobin 1-25) differs from the newDEFAULT_PHYSIOLOGIC_BOUNDS.
New
-
filter_bounds(df, bounds=None | {...} | False, action="nullify"|"clip"|"drop")withDEFAULT_PHYSIOLOGIC_BOUNDS; wide or long frames;.attrs["bounds_report"]. -
harmonize_measurement_units(con, ...): unit preflight report plus ameasurement_harmonizedview (cells/uL -> 10^3/uL, umol/L -> mg/dL, mmol/L glucose etc.). Unrecognized units are flagged, never guessed.extract_measurements(measurement_table=)reads from it. -
extract_medication_classes(window="pre_admission"|"inpatient"|"discharge")andMedicationExtractor(concept_ancestor track, crosswalk track, per-window flags). -
Table1GeneratorwithDOMAIN_PROFILES(heart_failure, nephrology, sepsis_icu, oncology, pulmonary, pharmacotherapy_safety),add_custom_lab, YAML/dict profiles. Profile code lists are a starting point for clinician review; LOINC and ATC codes were verified to exist in the OMOP vocabulary. -
CohortFlow(sequential steps, attrition table, Markdown/Mermaid/TikZ/Graphviz output, visit-type / anchor / follow-up preflight),Table2Generator(completeness, sentinel and zero-SD flags),as_plp_arrow(in-memory Arrow covariate tables for PatientLevelPrediction; no file round-trip). - R:
to_graphviz()for attrition tables;extract_measurements(measurement_table=);extract_medication_classes(window=, end_date_col=). R’sas_plp_arrow()builds the Arrow tables from DuckDB query results held in R memory (no files); it is not zero-copy.
External-stack integration tests
- Run against the real packages: PatientLevelPrediction 6.7.0 (+ FeatureExtraction 3.14.0, Andromeda 1.2.1): all six previously skipped
test-hades-bridge.Rtests pass. DeepPatientLevelPrediction 2.4.0 (torch 2.14.1 CPU through reticulate) fits an MLP on data fromas_plp_arrow(). omop-learn (clinicalml, cloned): the 17 backend tests pass with its real classes (OMOP_LEARN_SRC). OHDSI/OmopOnDuckDB 0.1.0: an omop-duck-db file opens throughduckdbSource()and our functions run on its connection. - New
plp_arrow_to_plp_data()turnsas_plp_arrow()output into aplpData; a realrunPlp()LASSO fit on it recovers the planted lab as its top coefficient. - Windows caveat: with R’s
arrowalready loaded, python’spyarrowfails to import (“DLL load failed while importing lib”) and DeepPLP silently produces no model. Import pyarrow first (done intests/testthat/helper-plp-arrow.R); the DeepPLP test asserts a metric exists so this failure cannot pass silently. - OmopOnDuckDB 0.1.0 is an unfinished template (placeholder DESCRIPTION,
duckdbSource()only). ItsvalidateCon()returnsNULLwhen handed an existing connection, so pass a file path. - These tests skip when the package is absent.
DeepPatientLevelPredictionandOmopOnDuckDBare GitHub-only, so they are deliberately not in Suggests (CI’s dependency solver cannot resolve them);reticulateis.
Vocabulary guards (Python and R)
- Always on: no LOINC / concept id may be assigned to two features in the default maps;
domain_profiles.ymlmust equal the Python profiles. - Opt-in, set
OMOP_VOCAB_DBto a DuckDB file holding the OMOPconcepttable: every LOINC and ATC code in the default maps and the domain profiles must exist, and itsconcept_namemust contain a keyword for the feature it is filed under (tests/fixtures/vocab_feature_keywords.csv, shared by both languages); every default medication concept id must be the drug or class it claims to be. Re-introducing the48642-3anion-gap bug or the old statin id makes these tests fail. Adding a feature without keywords also fails, by design. The guard already caught a wrong DOAC code (B01AE06is bivalirudin) in the new profiles.
omopduckdb 0.5.8
Closes the remaining items of the “outstanding requests” review of 0.5.7. Everything ships with dual Python and R usage (R functions are snake_case mirrors; Python lives in omop_etl). The readmission-cohort engine (define_study_cohort), Table 1 / missingness (generate_table1) and the Elixhauser / Charlson calculators were already present and are unchanged apart from the guard below.
load_wide_measurement(coalesce_columns=) – no more duplicate BMI rows
- Columns that carry the same measure (PCORnet
BMIandORIGINAL_BMIboth map to concept 3038553) now yield ONE measurement row per source row.coalesce_columns="auto"(default) groups columns that share aconcept_id, inconcept_mappingorder;[("ORIGINAL_BMI", "BMI")]/list(c("ORIGINAL_BMI", "BMI"))sets an explicit precedence;None/NULLrestores the 0.5.7 behaviour. The first value inside its plausibility bounds wins, so an implausible primary never masks a plausible fallback. The report gains acoalesced_intocolumn. Behaviour change: with the default mappingORIGINAL_BMIno longer inserts its own rows.
extract_inpatient_labs and extract_measurements(outlier_bounds=, strategy="worst")
- Index-stay labs per cohort row: acute labs (lactate, troponin, pO2, pCO2;
ACUTE_LAB_PANEL) come only from the stay, routine labs fromroutine_window(stay/lookback/all).selection_ruleislast_in_stay,first_in_stay,mean,median,min,maxorworst(direction per lab inWORST_LAB_DIRECTION). Physiologic outlier bounds are applied BEFORE selection. -
extract_measurementsgainsoutlier_bounds,worst_directionand theworststrategy.
extract_prior_utilization
- Prior IP / ED / OS visit counts, summed length of stay, days since the last encounter and prior 30-day readmissions in the look-back (
lookback_days, default 365) strictly before the index admission. The index visit is excluded;anchor_date="discharge"is rejected. Visit groups are configurable (DEFAULT_VISIT_CONCEPT_GROUPS).
Train/serve skew guard
-
extract_elixhauser_comorbiditiesandextract_charlson_indextakeexclude_index_diagnoses=(default on): diagnoses attached to the cohort row’s ownvisit_occurrence_idare never counted (they are coded after discharge), and a discharge-likeindex_date_col(cohort_end_date,*discharge*) is an error. Behaviour change: callers that deliberately anchored at discharge must passexclude_index_diagnoses=False. -
OMOPScoringPipeline(Python) /omop_scoring_pipeline(),fit_scoring_pipeline(),predict_scoring_pipeline()(R): a fitted imputer, scaler and model bundled with the ordered feature schema. Scoring raises on missing, unexpected or non-numeric columns and on NaN without an imputer;out_of_range/scoring_pipeline_out_of_range()is a drift check; bundles save and load (pickle / RDS – only load files you trust).
omopduckdb 0.5.7
All request-3 features ship with dual Python and R usage (R functions are snake_case mirrors in the omopduckdb package; Python lives in omop_etl).
Staged wide-table ingestion (load_wide_measurement) (Python omop_etl / R omopduckdb)
- Stages a wide table (PCORnet
vital, flowsheets, device streams) once into an integer-keyed intermediate table, then inserts intomeasurementone concept at a time with a commit between passes (batch_execution_mode="sequential"), instead of one giant uncommittedUNION ALL. Per-measurement plausibility bounds (value_plausibility_filters, e.g. SBP 30-300, DBP 10-200, BMI 5-120) and a per-column report (read / out-of-range / unmatched person / inserted).DEFAULT_VITAL_CONCEPT_MAPPINGandDEFAULT_VITAL_PLAUSIBILITY_FILTERScover PCORnet VITAL.
Vectorized datetime normalizer (vectorized_strptime) (Python omop_etl / R omopduckdb)
- One SQL expression, no UDFs: normalizes single-digit hours, missing minutes,
0415, and 12/24-hour notation, then tries a prioritized format list in a singletry_strptime(x, [...]).on_error='null' | 'default_date' | 'raise'.install_vectorized_strptime(con)registers it as a macro.
Dual-strategy medication classifier (extract_medication_classes, audit_medication_strategies) (Python omop_etl / R omopduckdb)
- Strategy A (user crosswalk of source strings/CUI/NDC to classes) and Strategy B (
concept_ancestortraversal from ATC 3/4/5 classes or RxNorm ingredients),strategy='source' | 'standard' | 'both'. - The auditor reports Cohen’s kappa, raw concordance, prevalence gap and a reason (
source_blind,standard_blind,low_kappa,low_concordance,prevalence_gap,peer_outlier) per site and class, so sites with broken drug mappings stand out.
Path sanitizer (omop_etl.paths) (Python omop_etl / R omopduckdb)
-
sanitize_sql_path,sql_path_literal,attach_database,read_csv_sql,read_parquet_sql,copy_to. All internal ATTACH /read_csv/read_parquet/COPYcall sites now go through them (Windows backslashes, spaces, single quotes; remote URIs untouched).
RAM governor and spill manager (configure_resources) (Python omop_etl / R omopduckdb)
- Sets
memory_limitto a fraction (default 75%) of available RAM, picks the temp directory on the writable volume with the most free space, and setsthreadsfrom usable cores.etl_pcornet(auto_resources=True)/--auto-resourceson the ETL CLI; explicitmemory_limit,threadsandtemp_dirstill win.
Phenotype cohort DSL (omop_etl.phenotype_dsl) (Python omop_etl / R omopduckdb)
-
ConditionCriteria(concept sets, ICD prefixes, primary/secondary),MeasurementCriteria(LOINC / thresholds / lookback),DrugCriteria(ingredients / ATC / supply days / lookback) composed with|,&,~(PhenotypeUnion,PhenotypeIntersect,PhenotypeNot,Everyone).compile_phenotypeemits one single-pass DuckDB query;execute_phenotypewrites a cohort table; dict round-trip viato_dict/phenotype_from_dict.
Roadmap gap closures
-
PCORnet
VITAL.SMOKINGis now mapped to anOBSERVATIONrow:observation_concept_id = 43054909(LOINC 72166-2, Tobacco smoking status) with the LOINC answer concept invalue_as_concept_id(01 -> 45881517, 02 -> 45884037, 03 -> 45883458, 04 -> 45879404, 05 -> 45881518, 06 -> 45885135, 07 -> 45884038, 08 -> 45878118).NI/UN/OTcarry no status and produce no row. Pythonload_vital, Retl_pcornet. -
load_vocabulary(tables =, drop_indexes =)(Python and R): reload only the named vocabulary tables, and drop / recreate user indexes around the bulk load. -
build_safe_source_view()(Python and R):src_<table>view with header aliasing and NULL padding, as specified in RFC-3. -
python -m omop_etl.quality_check --db-path ... --output dq_report.json: the Duck-DQD entry point named in RFC-5 (R:run_dqd()). -
R ETL now logs aliased and null-padded columns like the Python ETL, and
etl_pcornet()gainsauto_resources,memory_limit,threadsandtemp_dir.
omopduckdb 0.5.6
Automated OHDSI PLP Study Package Generator
-
PLP Study Package Exporter (
export_plp_study_package):- Bundles target cohorts, outcome cohorts, covariate settings, and cross-validation workflows into an end-to-end reproducible R study package adhering to standard OHDSI
PatientLevelPrediction(PLP) conventions. - Automatically generates package scaffolding including
DESCRIPTION,NAMESPACE,R/RunStudy.R,R/ShinyApp.R, pre-configured Shiny diagnostic viewers, cross-validation configurations, study JSON manifests, and an interactive CLI / Shiny launcher (extras/launch_shiny.R). - Available with full 1:1 parity in Python (
omop_etl.plp_study_package) and R (omopduckdb::export_plp_study_package).
- Bundles target cohorts, outcome cohorts, covariate settings, and cross-validation workflows into an end-to-end reproducible R study package adhering to standard OHDSI
Direct Andromeda Zero-Copy View Adapter
-
Direct Andromeda Adapter (
duckdb_to_andromeda,as_andromeda,export_to_andromeda,AndromedaAdapter):- Eliminates the SQLite disk serialization bottleneck inside OHDSI Andromeda by mounting DuckDB tables or chunked streaming into Andromeda containers without intermediate disk round-trips.
- Supports DuckDB SQLite extension virtual table registration (
sqlite_scanner) where available, with graceful streaming chunk fallback. - 1:1 cross-language parity in Python (
omop_etl.andromeda) and R (omopduckdb::duckdb_to_andromeda,omopduckdb::as_andromeda).
Automated CONSORT / STROBE Flowchart Exporters
-
CONSORT / STROBE Attrition Diagrams (
ConsortAttrition,to_typst,to_tikz,to_mermaid):- Extends
CohortExtractorwith step-by-step attrition tracking capturing starting populations, excluded counts, remaining counts, and inclusion reasons across every cohort definition step. - Native export of publication-ready flowcharts to Typst (
#block(),#rect(), arrows), LaTeX TikZ (\begin{tikzpicture},\node,\draw), and Mermaid (graph TD) for direct insertion into Quarto and LaTeX manuscripts. - Accessible via
.attrition.to_typst()/.attrition.to_tikz()onCohortExtractorin Python and S3 genericsto_typst()/to_tikz()in R.
- Extends
Foundation Model Tokenizer Integration (EHR-SHOT / CEHR-BERT / FEMR)
-
Clinical Sequence Tokenizer (
extract_clinical_sequence_tokens,to_clinical_sequence_tokens,export_clinical_sequence_tokens):- Expands
extract_sard_visit_tensors()to export HuggingFace/PyTorch-compatible clinical event token sequences (input_ids,attention_mask,token_type_ids,labels). - Configurable special tokens (
[PAD] = 0,[UNK] = 1,[CLS] = 2,[SEP] = 3,[MASK] = 4,[VISIT] = 5,[DISCHARGE] = 6). - Preserves event visit boundaries with configurable maximum sequence lengths and padding modes.
- Full parity in Python (
omop_etl.ml_features) and R (omopduckdb::extract_clinical_sequence_tokens).
- Expands
Federated Consortium Meta-Analysis Aggregator
-
Federated Meta-Analysis Aggregator (
federated_meta_analysis,FederatedMetaAnalysisResult):- Multi-site summary estimator calculating DerSimonian-Laird random-effects pooled estimates (, SE, 95% CI), Cochran’s test of heterogeneity, between-study variance (), and Higgins’ across federated DuckDB nodes without sharing patient-level data.
- Supports odds ratios (OR), relative risks (RR), hazard ratios (HR), and mean differences.
- Built-in ASCII forest plot generation (
to_forest_text()), Mermaid diagram generation (to_forest_mermaid()/to_mermaid()), and DataFrame conversion. - Full parity in Python (
omop_etl.federation) and R (omopduckdb::federated_meta_analysis).
omopduckdb 0.5.5
In-Engine Propensity Score & IPTW Weighting
-
Propensity & IPTW Module (
generate_propensity_weights,PropensityResult):- In-engine logistic regression propensity score estimation () with Newton-Raphson/IRLS and L2 stabilization.
- Generates Inverse Probability of Treatment Weighting (IPTW) for Average Treatment Effect (ATE), Average Treatment Effect on the Treated (ATT/SMR), and Stabilized ATE.
- Implements pre- and post-weighting Standardized Mean Difference (SMD) covariate balance auditing, guaranteeing maximum post-weighting SMD .
- 1:1 cross-language parity in Python (
omop_etl.propensity) and R (omopduckdb::generate_propensity_weights).
Kaplan-Meier Survival & Competing Risks Cumulative Incidence (CIF)
-
Survival & Competing Risks Estimator (
estimate_km_survival,SurvivalResult):- Non-parametric Kaplan-Meier survival curve estimation with Greenwood standard error confidence intervals (log-log and linear Wald).
- Fine-Gray / Aalen-Johansen non-parametric Cumulative Incidence Function (CIF) estimation for 3-state competing risks outcomes (censored vs. primary vs. competing mortality).
- Validated to within numerical tolerance against R
survival::survfit. - Publication-ready plotting hooks and
.to_dataframe()export in Python and R.
Delta Lake & Apache Iceberg Lakehouse Connector
-
Lakehouse Connector (
omop_connect_lakehouse):- Dynamic zero-copy querying of remote cloud object storage (S3, MinIO, Azure Blob, GCS) or local lakehouse stores.
- Registers remote/partitioned Delta Lake, Apache Iceberg, or Parquet datasets as unified OMOP views (
v_person,v_condition_occurrence, etc.) with S3 credential handling.
Federated Consortium Governance & Dynamic Differential Privacy
-
-Differential Privacy Noise Injector (
with_differential_privacy):- Injects calibrated Laplace noise () directly into dynamic DuckDB SQL views without external library overhead.
- Ensures repeated aggregate queries vary predictably within mathematical privacy bounds without leaking exact patient counts.
Deep Learning & Zero-Copy GPU Streaming
-
Zero-Copy CUDA IPC Tensors (
arrow_to_cuda_tensors):- Direct buffer streaming from DuckDB via PyArrow C Data Interface / DLPack into PyTorch GPU tensors in VRAM without intermediate host-RAM bounce buffering, with graceful fallback to CPU tensors.
Full ATLAS/CIRCE AST Compiler Expansion
-
CIRCE
InclusionRulesSupport:- Expanded
compile_circe_to_duckdbto parse multi-criteriaInclusionRulesarrays supportingDemographicCriteria(Age, Gender),ConditionOccurrence,DrugExposure,Measurement(value comparisons),ProcedureOccurrence, observation lookback/lookahead windows, andALL/ANYBoolean logic.
- Expanded
Upward-Tree Vocabulary Auto-Discovery
-
Nested Directory Traversal in
omop_connect():- Searches up to 4 parent directory levels for
central_vocabulary.duckdb,vocabulary.duckdb, orvocab.duckdb, falling back to theOMOP_CENTRAL_VOCABenvironment variable.
- Searches up to 4 parent directory levels for
Top 25 OHDSI Phenotype Library Coverage
-
Expanded Phenotypes (
list_available_phenotypes,get_phenotype_concept_set):- Expanded library from 8 to 25 standard OHDSI Phenotype Library concept bundles, adding CKD (stages 1-5, ESRD), Asthma, Rheumatoid Arthritis, Major Depressive Disorder, Dementia/Alzheimer’s, Liver Cirrhosis, Breast Cancer, Colorectal Cancer, Lung Cancer, Prostate Cancer, COVID-19, VTE/DVT/PE, PAD, IBD (Crohn’s/UC), Severe Aortic Stenosis, Atopic Dermatitis, and Osteoarthritis.
ML Cohort Extractor & Feature Matrix Builder
-
Cohort & Feature Extraction (
CohortExtractor,FeatureMatrixBuilder):- Standardized admission index cohort definition with configurable selection rules (
first,last,random_eligible) and verified post-discharge follow-up horizons. - Strict lookback window separation for demographics, prior utilization, acute inpatient labs, chronic conditions, and medications, avoiding future data leakage.
- Dual export modes for tabular modeling (
to_tabular) and 3D temporal sequence tensors (to_tensor).
- Standardized admission index cohort definition with configurable selection rules (
Standalone CLI Entry Point
-
omop-duckdbCLI:- Registered CLI console scripts
omop-duckdbandomop-duckdb-clisupporting subcommands:build,dqd,cohort,table1, andexport.
- Registered CLI console scripts
Partitioned Parquet Export & Synthetic Test Fixtures
-
export_to_parquet: Native single-file and Hive-partitioned Parquet export directly from DuckDB. -
Mock PCORnet Test Fixture Generator (
generate_mock_pcornet.py): Deterministic multi-site synthetic PCORnet data generator simulating hospital variations, header aliases (ssid,enc_id), and missing optional columns.
omopduckdb 0.5.4
Pre-compiled OHDSI Phenotype Bundles & Native CIRCE Compiler
-
Phenotype Library (
get_phenotype_concept_set,list_available_phenotypes):- Pre-compiled OHDSI-standard concept sets and ICD-10 source prefixes for core clinical conditions: Type 2 Diabetes, Heart Failure, Sepsis, COPD, Acute Kidney Injury, Atrial Fibrillation, Hypertension, and Ischemic Stroke.
-
Native CIRCE Compiler (
compile_circe_to_duckdb,execute_circe_cohort):- Compiles ATLAS/CIRCE JSON cohort definitions directly to native DuckDB SQL without requiring Java or WebAPI runtime dependencies.
Bedside Clinical Risk Scores & Core Inpatient Lab Harmonizer
-
Clinical Risk Scores (
calculate_bedside_scores):- Implemented in-engine computation for LACE Index, HOSPITAL Score, SOFA Score, and CHA2DS2-VASc risk stratifications directly from OMOP CDM tables.
-
Core 14 Inpatient Lab Harmonizer (
extract_standard_labs,CORE_14_LAB_PANEL):- Standardized measurement extraction covering the 14 essential inpatient acute labs with physiologic outlier winsorization.
Study Attrition Reporting & Longitudinal Treatment Episodes
-
CONSORT Flow Generator (
generate_consort_attrition):- Generates reproducible patient attrition funnels from sequential SQL criteria with automated rendering to Mermaid flowcharts, LaTeX tables, Markdown, and tabular data.
-
Treatment Episode Collapser (
build_treatment_episodes):- Collapses longitudinal drug dispensing/exposure records into persistent treatment episodes with customizable gap thresholds (
max_gap_days).
- Collapses longitudinal drug dispensing/exposure records into persistent treatment episodes with customizable gap thresholds (
Reporting Exporters, Heuristic Remapping & Federation Auditing
-
Publication Table 1 / Table 2 Exporters (
export_table1):- Multi-format exporter rendering baseline demographic and comorbidity comparison tables to Markdown, LaTeX, Quarto, and CSV formats.
-
Heuristic Concept Remapping (
auto_remap_unmapped):- Automated repair and normalization for unmapped source values (dot stripping, spacing normalization, Athena mapping table lookups).
-
Consortium Privacy & Discrepancy Auditing (
with_cell_suppression,check_cross_database_discrepancy):- Small-cell suppression wrapper for privacy-preserving federated analytics and cross-site vocabulary discrepancy auditing.
omopduckdb 0.5.3
Transparent Central Vocabulary Single-Store & Connection Engine
-
omop_connect():- Implemented unified connection helper in Python (
omop_etl.omop_connect) and R (omopduckdb::omop_connect). - Auto-discovers sibling or repository central vocabulary DuckDB instances (
central_vocabulary.duckdb/vocabulary.duckdb). - Attaches vocabulary read-only as
central_vocaband automatically sets DuckDB’ssearch_path = 'main,central_vocab', allowing queries to referenceconcept,concept_ancestor, and other vocabulary tables directly without schema qualification. - Automatically loads SQL macros into temporary session scope on read-only databases without throwing write errors.
- Implemented unified connection helper in Python (
Concept Ancestry & Physiologic Clamping SQL Macros
-
Recursive Hierarchy & DQD Clamping Macros (
mapping_macros.sql):-
descendants_of(ancestor_id): Table macro returning all descendant concept IDs fromconcept_ancestor(including self rows). -
ancestors_of(descendant_id): Table macro returning all ancestor concept IDs fromconcept_ancestor(including self rows). -
clamp_physiologic(val, min_val, max_val): Scalar macro for in-engine SQL boundary clamping and outlier winsorization. - Designed with name-capture protection and subquery correlation safety.
-
Standardized 31 Elixhauser Domains & Charlson Comorbidity Profiler
-
Validated Comorbidity Profilers (
extract_elixhauser_comorbidities,extract_charlson_index):- Implemented 1:1 dual-language comorbidity profiling in Python (
omop_etl.comorbidity) and R (omopduckdb::comorbidity). - Covers all 31 Elixhauser domains (AHRQ / Quan et al.) and composite van Walraven score.
- Covers all 17 Quan-Charlson categories, hierarchical condition adjustment, and composite Charlson Comorbidity Index.
- Dual matching mode: evaluates normalized ICD-9/10 prefixes via
condition_source_valueand standard SNOMED descendants viacondition_concept_id. - Bundled curated mapping tables with documented provenance in
inst/extdata/comorbidity/(elixhauser_codes.csv,charlson_codes.csv,PROVENANCE.md).
- Implemented 1:1 dual-language comorbidity profiling in Python (
Physiologic Range Sanitization & Outlier Winsorization Engine
-
DQD Measurement Range Sanitizer (
sanitize_measurements):- Implemented in Python (
omop_etl.sanitize_measurements) and R (omopduckdb::sanitize_measurements). - Bundles 136 standard biological plausibility limits derived from OHDSI DataQualityDashboard in
inst/extdata/physiologic_limits.csv. - Supports three sanitization methods:
dqd_biologic_limits,winsorize_iqr,z_score_cutoff. - Configurable actions:
nullify,clamp, ordrop_row. - Tracks sanitization audit trail with
sanitize_statusand preserves raw values invalue_as_number_raw.
- Implemented in Python (
Unified Study Cohort Template Engine
-
General Study Cohort Builder (
define_study_cohort):- Implemented in Python (
omop_etl.cohort.define_study_cohort) and R (omopduckdb::define_study_cohort). - Parameterizes arbitrary visit types (
"inpatient","emergency","outpatient", or custom concept lists), prior wash-in window, follow-up window, minimum age, and minimum length of stay. - Supports reproducible sampling rules (
"first","last","random") and verified follow-up right-censoring checks. - Unifies and powers legacy
build_readmission_cohort()andbuild_end_of_life_cohort()wrappers with row-for-row parity.
- Implemented in Python (
omopduckdb 0.5.2
Feature Engineering & Data Leakage Prevention
-
Formalized Anchor Date & Wash-in Buffers (
anchor_date,washin_buffer_days,washin_buffer_hours):- Added
anchor_date = c("discharge_date", "admit_date", "auto")toextract_sparse_concept_matrix,extract_sard_visit_tensors, andmaterialize_concept_featuresacross both Python and R. - Automatically selects
discharge_datefor post-discharge readmission cohorts andadmit_datefor in-hospital mortality cohorts. - Added configurable wash-in buffers (
washin_buffer_days,washin_buffer_hours) allowing feature collection within a bounded window (e.g. first 24 hours of admission) while strictly preventing terminal resuscitative codes (CPR, palliative care, intubation) on the day of death from leaking into in-hospital mortality predictors.
- Added
Clinical Methodology & Competing Risks
-
Fine-Gray Competing Risks Survival Helper (
prepare_competing_risks_data):- Implemented 1:1 cross-language competing risk dataset preparation in Python (
omop_etl.cohort.prepare_competing_risks_data) and R (omopduckdb::prepare_competing_risks_data). - Standardizes 3-state survival outcome formatting for consortium sites:
- Status 0: Censored alive without readmission within follow-up window.
- Status 1: Primary event of interest (acute inpatient readmission).
- Status 2: Competing terminal event (death prior to readmission).
- Emits
time_daysto first event or censoring,status(0, 1, 2), andcomposite_event(Mode 4 readmit-or-death) to eliminate survivor bias in standard readmission models.
- Implemented 1:1 cross-language competing risk dataset preparation in Python (
Multi-Site Ingestion & PCORnet Mapping Parity
-
PCORnet Discharge Status Mapping Expansion:
- Updated PCORnet ETL across Python (
load_visit_occurrence) and R (etl_pcornet) to comprehensively map standard 2-letter codes:-
'EX','EXPIRED','DIED','DECEASED'->4216643(Died) -
'AM','AMA'->4155309(Against medical advice) -
'HO','HOSPICE'->8546(Hospice) -
'SN','SNF'->8863(Skilled Nursing Facility) -
'A','HOME','ROUTINE'->8536(Home)
-
- Updated PCORnet ETL across Python (
-
Proactive Vocabulary & Mapping Checks:
- Embedded proactive checks in
load_visit_occurrenceandcheck_vocabulary_versionto alert consortium sites if inpatient visits have unmapped discharge dispositions (discharged_to_concept_id = 0).
- Embedded proactive checks in
omopduckdb 0.5.1
Bug Fixes & CI/CD Stability
-
DuckDB Extension Autoloading: Replaced dynamic
CURRENT_DATEqueries in cohort SQL with injected ISO date literals (DATE 'YYYY-MM-DD'), eliminating unexpected ICU extension autoloading failures on Linux runners. -
Pkgdown Documentation: Added all exported reference topics to
_pkgdown.yml, categorized into logical sections across cohort definitions, ML feature extraction, HADES/tidymodels bridges, and DQD. -
Docker Builder Dependencies: Added missing suggested packages (
Matrix,arrow,jsonlite,dplyr,withr) to the builder image. -
PyPI Release Workflow: Configured
skip-existing: trueinpypa/gh-action-pypi-publishaction to handle idempotent publishes gracefully.
omopduckdb 0.5.0
End of Life & Mortality Cohort Suite
-
Standardized End of Life & Mortality Cohort Builder (
build_end_of_life_cohort, aliasbuild_mortality_cohort):- Implemented 1:1 cross-language mortality cohort generation in Python (
omop_etl.cohort) and R (omopduckdb::build_end_of_life_cohort). - Supports four clinical mortality paradigms:
-
"in_hospital": Ascertains in-hospital mortality during the index stay viadeathtable or discharge disposition (discharged_to_concept_id IN (4216643, 4155309)). -
"post_discharge": Post-discharge mortality within(t_discharge + gap_days, t_discharge + mortality_window_days], strictly excluding index stays resulting in death. -
"fixed_window": SARD EOL prediction protocol (Kodialam et al., AAAI 2021) within(t_index + gap_days, t_index + mortality_window_days]. -
"composite_readmit_or_death": Clinical composite of 30-day all-cause readmission or post-discharge mortality, capturing unfavorable discharge outcomes for eDERRI benchmarks and competing-risk adjustments.
-
-
Dual Death Source Ascertainment: Simultaneously queries both the OMOP
deathtable (death_date) andvisit_occurrencedischarge status (discharged_to_concept_id IN (4216643, 4155309)). -
Right-Censoring Verification (
require_verified_followup): Ensures non-deceased patients have confirmed observation or clinical contact at or beyond the follow-up window, preventing lost-to-follow-up bias. -
Standardized Cohort Table Materialization: Automatically materializes target cohort (e.g. ID 1) and optional outcome cohort (e.g. ID 2) in OMOP
cohortandcohort_definitiontables with reproducible sampling ("random","first","last"). - Registered SQL macro
is_expired(discharged_to_concept_id)ininst/sql/cohort_mortality.sql.
- Implemented 1:1 cross-language mortality cohort generation in Python (
Machine Learning Feature Representation & Ecosystem Bridges
-
High-Dimensional Sparse Concept Matrices (
extract_sparse_concept_matrix):- Implemented set-based sparse concept matrix extraction in both Python (
scipy.sparse.csr_matrix) and R (Matrix::dgCMatrix) driven by a cohort parquet. - Generates condition, drug, and procedure concept features within lookback windows strictly before the index date (
[index - lookback_days, index)), eliminating temporal feature leakage. - Automatically drops concept
0, ensures C-locale token string ordering matchingomop-learn’sConceptTokenizer, and supports train/test column stabilization via token preservation.
- Implemented set-based sparse concept matrix extraction in both Python (
-
Deep Sequential Visit Tensors for SARD (
extract_sard_visit_tensors):- Padded 3D visit arrays
(N, max_nvisits, max_visit_len)for Transformer-based architectures (SARD, Kodialam et al., AAAI 2021). - Emits visit lengths, chronological visit times (days since 1900-01-01), days before index, and tokenized concept IDs using standard omop-learn special tokens (
[BOS]=0,[EOS]=1,[SEP]=2,[PAD]=3,[UNK]=4). - Helper
as_omop_learn_batchto format tensors directly for PyTorch collation.
- Padded 3D visit arrays
-
DuckDB Backend for
omop-learn(DuckDBBackend):- Added DuckDB backend implementing omop-learn’s backend interface, replacing per-patient query loops with a single set-based
LATERALjoin (over 70x faster execution). - Bundled DuckDB-dialect feature SQL macros under
inst/sql/omop_learnfor age, gender, conditions, drugs, and procedures.
- Added DuckDB backend implementing omop-learn’s backend interface, replacing per-patient query loops with a single set-based
-
OHDSI HADES / PatientLevelPrediction / DeepPLP Bridge:
- Added
hades_preflight()to verify DuckDB CDM file readiness, table row counts, in-database vocabulary availability, and cross-process read-write exclusivity. - Added
plp_database_details()to wire DuckDB configurations intoPatientLevelPrediction::createDatabaseDetails(). - Added
as_plp_data()to bridge sparse concept matrices directly into OHDSIplpDataobjects (covariate IDsconcept_id * 1000 + analysis_idmatching FeatureExtraction long-term analysis IDs 102/302/502).
- Added
-
tidymodels Bridge & In-Database Scoring:
- Added
as_tidymodels_data()to convert sparse concept matrices into tidymodels-ready tibbles withyfactor levels (event_level = "first") and syntactic predictor names<domain>_<concept_id>, with sparse column support viasparsevctrs. - Added
model_concepts()to inspect fitted parsnip models or workflows and identify non-zero coefficient predictors. - Added
materialize_concept_features()to create wide feature tables inside DuckDB using identical windowing rules, enabling direct in-database scoring viaorbital::orbital()ortidypredictwithout feature drift.
- Added
omopduckdb 0.4.0
Generic Readmission Cohort & Outcome Builder
-
Inpatient Readmission Cohort (
build_readmission_cohort): Added reproducible, parameterized cohort generation in both Python (omop_etl.cohort) and R (omopduckdb::build_readmission_cohort) anchored on adult index inpatient stays (visit_concept_id = 9201, age >= 18, length of stay >= 1 day, discharged alive). -
Lost-to-Follow-Up / Right-Censoring Filter (
require_verified_followup): Enforces verified observation by requiring either an inpatient readmission within post-discharge follow-up (e.g. 30 days) or confirmed subsequent clinical activity (IP, ED, OP, lab, vital) after the window, eliminating differential follow-up attrition. -
Reproducible Index Stay Selection: Supports
'random'sampling with reproducible random seed,'first', or'last'eligible inpatient admission per patient. - Leak-Free Temporal Scoping: Guarantees strict temporal separation between baseline history () and readmission outcome window ().
-
Cohort Readmission SQL Macros (
inst/sql/cohort_readmission.sql): Implements pure DuckDB macroscalc_los_days(),calc_age_at_date(),is_adult(),is_discharged_alive(),categorize_discharge(), andcategorize_age_group().
Temporal Feature Extraction & Concept Rollup
-
Temporal Historical Utilization (
extract_temporal_features): Windowed baseline encounter counts (IP, ED, OP), days since prior encounter, days since prior IP/ED stay, prior 30-day readmissions in lookback window, index length of stay, discharge disposition, and demographics. -
Athena Transitive Closure Rollup (
aggregate_concept_sets): Hierarchical rollup across condition and drug domains traversingconcept_ancestorto extract binary or count indicators for clinical classes (e.g., insulins, metformin, sulfonylureas, statins, antihypertensives, RAAS inhibitors, beta blockers, systemic corticosteroids). -
Consolidated Lab & Vital Extraction (
extract_measurements): Maps LOINC concept groups (albumin, ALT, AST, bicarbonate, BUN, creatinine, eGFR, glucose, HbA1c, hematocrit, WBC, sodium, BP, BMI) with configurable acute window aggregation strategies (last_before_discharge,first_on_admission,mean,median,min,max).
Baseline Table 1 Generation & Reconciliation Harness
-
Comprehensive Baseline Summarizer (
generate_table1): Generates publication-ready Table 1 baseline characteristics stratified by outcome (e.g., 30-day readmission status), reporting overall and stratified Mean (SD), Median [IQR], N (%), Standardized Mean Differences (SMD), and hypothesis test p-values. Emits Table 1b completeness and missingness matrix. -
Table 1 Aggregation SQL Macros (
inst/sql/table1_aggregations.sql): In-engine computation of continuous and binary SMDs, BMI classification, and tobacco use categorization. -
Reconciliation & Drift Validation Harness (
validate_table1_reconciliation): Validates prospective OMOP-derived Table 1 distributions against external benchmark extracts with configurable tolerance thresholds, flagging statistical drift, missingness discrepancy, and feature dropouts.
omopduckdb 0.3.0
Phase 1: Location & SDoH Address History Ingestion
-
Address & Geography Ingestion (
load_location): Addedload_location(con, source_dir, site_id)in both Python (omop_etl.build_omop_cdm) and R (omopduckdb::load_location), ingesting PCORnetlds_address_history.csvinto the OMOPlocationtable. Uses deterministic surrogate keys (location_id = pcornet_id(addressid)or sequential numbering), deduplicates addresses, and retroactively populatesperson.location_idwith each patient’s primary residential address. -
Address Column Aliases: Updated
DEFAULT_ALIASESwithADDRESS_CITY,ADDRESS_STATE,ADDRESS_ZIP5, andADDRESS_PERIOD_STARTfor robust ingestion across PCORnet schema variants.
Phase 2: Concept Polyhierarchy & Cohort Definition Helpers
-
Standard OHDSI Cohort Tables (
ensure_cohort_tables): Ensurescohortandcohort_definitiontables exist according to OMOP CDM v5.4 specifications. -
Polyhierarchy Traversal: Added
get_concept_descendants(),get_concept_ancestors(), andget_concept_relationships()to query transitive closures inconcept_ancestorand relationship tables directly in DuckDB. -
Concept Set Resolution (
resolve_concept_set): Resolves concept sets with full descendant expansion and exclusion logic using pure set-based SQL. -
Cohort Creation & Management (
create_cohort): Ingests entry criterion SQL, supports fixed or event-based exit dates, and tracks metadata incohort_definition. -
CONSORT Attrition Analysis (
compute_attrition): Sequentially tracks patient counts and percentage retention across arbitrary phenotyping criteria. -
Cohort Set Operations (
combine_cohorts): Combines cohorts using set algebra (UNION,INTERSECT,DIFFERENCE). -
Cohort Summarization (
get_cohort_summary): Computes cohort statistics (unique subjects, total entries, min/max/mean/median observation duration).
Phase 3: Native DuckDB DataQualityDashboard (DQD) Engine
-
Pure-SQL OHDSI DQD (
run_dqd): Implemented a standalone, zero-dependency DataQualityDashboard engine that runs in seconds in DuckDB without Java/JDBC or DatabaseConnector. -
Four Core Check Levels: Executes
TABLE(presence & row count),FIELD(not-null violations & orphan foreign keys),CONCEPT(standard concept compliance), andTEMPORAL(event start before end, birth before event) checks. -
OHDSI DQD JSON Output: Writes standard OHDSI DQD JSON files with complete
Overview,Metadata, andCheckResultsschemas compatible with OHDSI visualization frontends.
Phase 4: Machine Learning Feature Matrix Extractor
-
Patient Feature Extraction (
extract_patient_features): Generates temporal, ML-ready feature matrices anchored on cohort index dates (). - Retrospective Lookback Windows: Aggregates condition, drug, procedure, and measurement occurrence counts across customizable lookback windows (e.g., 30, 90, 365 days).
- Demographics & Target Outcomes: Extracts baseline patient demographics (age, gender, race, ethnicity) and optional binary outcome flags from target cohorts.
-
Flexible Matrix Formats: Exports as standard
df(Pandas / Rdata.frame), Apache Arrow (arrow), or OHDSI FeatureExtraction sparse matrix format (sparse:row_id,covariate_id,covariate_value).
Phase 5: Enterprise Multi-Target Export
-
High-Throughput CDM Exporter (
export_cdm): Exports CDM tables to production data warehouses and analytical formats via DuckDB’s vectorized copy engine:- Parquet: Snappy/ZSTD compressed Parquet files with optional partition-by-year on clinical occurrence dates.
-
PostgreSQL: Direct in-engine streaming into PostgreSQL via DuckDB’s
postgresextension. -
Oracle: Generates Oracle SQL*Loader control files (
.ctl), Oracle DDL, and loader shell scripts. - Delimited Files: Exports standard RFC 4180 CSV and TSV formats.
omopduckdb 0.2.2
Multi-Site Consortium Provenance & Federation
-
Pluggable Site Identification: Added
--site-id <int>,--site-anon <str>, and--site-name <str>toetl_pcornet()and CLI scripts (build_omop_cdm.pyandinst/scripts/etl_pcornet.R). Automatically populatescdm_sourcemetadata (cdm_source_name,cdm_source_abbreviation,cdm_holder), seeds a primary institutionalcare_siterecord, and linksperson.care_site_id = site_idfor downstream OHDSI tools (ATLAS, PLP, DQD). -
Patient ID Disambiguation (
--disambiguate-patids): Formatsperson_source_valueassrc.PATID || '-' || site_idand derives deterministic surrogate keys viapcornet_id(src.PATID || '-' || site_id)across all CDM clinical occurrence tables (person,visit_occurrence,condition_occurrence,procedure_occurrence,drug_exposure,measurement,death), preventing cross-site key collisions when pooling extracts. -
Formal
CARE_SITEIngestion: Added modularload_care_site()ingestingfacility.csv(care_site_id = pcornet_id(src.FACILITYID)) and/or creating the root institution care site record, eliminating missing table and orphan key warnings in OHDSI DQD. Invisit_occurrence, encounters gracefully link to their facility or fall back to the institutional site when facility records are absent. -
Zero-Copy Federated Consortium Views (
create_federated_consortium): Addedcreate_federated_consortium(site_dbs, central_vocab_db=None, output_con=None)in both Python (omop_etl.federation) and R (omopduckdb::create_federated_consortium). Attaches multiple site databases inREAD_ONLYmode, optionally attaches a central Athena vocabulary, and constructs unified zero-copyv_*views (v_person,v_visit_occurrence, etc.) projectingsite_idandsite_anonprovenance without duplicating data.
omopduckdb 0.2.1
Real-World Multi-Center Consortium Enhancements
-
Extended Encounter Type Mapping: Mapped additional high-volume PCORnet encounter types to standard OMOP visit concepts: Telehealth (
TH5083), Observation Services (OS9201), and Other Ambulatory (OT9202), preventing millions of clinical encounters from dropping to unmapped0. -
Gender Standardization: Expanded PCORnet
SEXmapping to standard OHDSI concepts for Other (OT8521), Unknown (UN8551), and No Information (NI8551), reducing OHDSI DQD unmapped gender flags. -
Vital Signs Ingestion (
vital.csv): Added modularload_vital()step unpivoting PCORnet vital signs into standard LOINC measurements in themeasurementtable:- Height (
HT) LOINC8302-2(Body height, unit[in_us], concept9326) - Weight (
WT) LOINC29463-7(Body weight, unit[lb_av], concept8739) - Body Mass Index (
ORIGINAL_BMI/BMI) LOINC39156-5(BMI, unitkg/m2, concept9531) - Systolic Blood Pressure (
SYSTOLIC) LOINC8480-6(Systolic BP, unitmm[Hg], concept8876) - Diastolic Blood Pressure (
DIASTOLIC) LOINC8462-4(Diastolic BP, unitmm[Hg], concept8876) - Skips gracefully if
vital.csvis absent, preserving modular pipeline execution.
- Height (
-
Central Vocabulary Support (
attach_central_vocabulary): Added--central-vocab <path>argument and helper functionattach_central_vocabulary()enabling multi-site deployments to attach a shared, read-only 15 GB Athena vocabulary database via DuckDB zero-copy views, eliminating redundant disk duplication across consortium sites.
omopduckdb 0.2.0
Architecture & Production Hardening
-
Vectorized Set-Based Mapping: Replaced correlated scalar subqueries in concept resolution macros with vectorized hash joins across
concept,concept_relationship(Maps to), andsource_to_concept_map, dramatically improving query execution speed on large extracts. -
Deterministic Surrogate Primary Keys: Eliminated hash collision risks and non-deterministic IDs by migrating all CDM occurrence tables to deterministic
ROW_NUMBER() OVER (...) + MAX(id)sequence generation. -
Date & Datetime Macro Parsing: Added flexible multi-format date and datetime parsing macros (
parse_omop_dateandparse_omop_datetime) supporting%Y-%m-%d,%Y%m%d,%d%b%Y, and%m/%d/%Y. -
Source Column Resilience: Implemented automated source view preparation (
prepare_source_view) handling case-insensitive column names, de-identified ID aliases (ssidtoPATID), and projectingNULLfor missing optional columns without failing execution. -
Mandatory OHDSI Synthesizers: Added automated generation for required OMOP CDM v5.4 tables:
observation_period(computed from patient event boundaries),drug_era(30-day persistence window collapse),condition_era(30-day persistence window collapse), andcdm_source(cdm_version_concept_id = 756265). -
Modular Death Table Handling: Ingestion of
death.csvis now optional and skips gracefully with an informative message if omitted, while deduplicating patient death records when provided.
Vocabulary Management & Remapping Helpers
-
CPT4 Null Concept Name Sanitization: Athena CPT4 concepts with null names are automatically replaced with
'CPT4 ' || concept_codeupon ingestion to prevent downstream failures. -
Vocabulary Version Inspector: Added
check_vocabulary_version()in both R and Python to query vocabulary metadata and verify Athena release dates. -
Usagi & Custom Mapping Tools: Added
import_source_to_concept_map()andimport_usagi_mappings()to easily load custom crosswalks directly intosource_to_concept_map, andexport_unmapped_codes()to audit unmapped source codes into CSV format ready for OHDSI Usagi review. -
In-Place Retroactive Remapping: Added
remap_cdm_table()andremap_all()supporting dry-run previews and transactional in-place re-mapping of existing CDM tables when vocabularies are updated, with automatic era synthesizer regeneration.
omopduckdb 0.1.1
- Added unified cross-language test coverage tracking (
covrfor R,pytest-covfor Python) and a dedicated.github/workflows/test-coverage.ymlCI workflow. - Created consolidated developer release scripts (
scripts/release.pyandscripts/release.R) for automated dual-package version bumping, Quarto rendering, test suite execution, wheel building, and git tagging. - Enhanced Docker container configuration for multi-stage testing and deployment.
omopduckdb 0.1.0
Initial packaged release.
- Build an OMOP CDM v5.4 schema in DuckDB from a shared, checked-in DDL.
- Load and refresh the OHDSI Athena vocabulary, transactionally per table.
- Map PCORnet-format source data into the CDM via parallel R and Python ETL implementations that share the same concept-mapping SQL, verified to produce identical output against a shared test fixture.
- Load OMOP-shaped tables directly from BigQuery (vocab refresh or demo data), as an alternative to a local vocabulary download.
- Sync the generated database and vocabulary archive through Google Drive instead of committing large binaries to git.
- Packaged as both an installable R package (
DESCRIPTION/NAMESPACE,testthatsuite,pkgdownsite) and a Python package (pyproject.toml,pytestsuite).
