How to Standardize Healthcare Data Using OMOP CDM and PySpark

2026-12-02来源 freeCodeCampEnglish
How to Standardize Healthcare Data Using OMOP CDM and PySpark

Healthcare data comes from various systems like electronic health records (EHRs), laboratory systems, pharmacies, medical imaging systems, and billing applications. And each system may use different data structures, naming conventions, and clinical coding standards.

For example, consider two hospitals storing information about patients diagnosed with type 2 diabetes.

Hospital A Hospital B
patient_id patient_number
diagnosis_date condition_start_date
diagnosis_code clinical_code
E11.9 (ICD-10-CM) 44054006 (SNOMED CT)

How do we combine data from these hospitals to conduct clinical research or build healthcare AI applications?

The Observational Medical Outcomes Partnership Common Data Model (OMOP CDM) addresses this problem by providing a common structure and standardized clinical vocabularies.

In this tutorial, we'll build an ETL pipeline using PySpark to transform synthetic healthcare data into OMOP CDM tables, validate the transformed data, and perform clinical analytics.

We'll use the synthetic healthcare dataset generated in my previous freeCodeCamp tutorial, How to Generate Synthetic Healthcare Data Using Synthea – A Hands-On Tutorial. If you haven't generated the dataset yet, I recommend following that tutorial before proceeding.

You can follow along with the accompanying Jupyter notebook, which contains the complete implementation.

What We'll Cover:

Prerequisites

To follow along with this tutorial, you should have a basic understanding of Python, SQL, and DataFrame operations. We'll use Synthea, OMOP CDM v5.4, OHDSI ATHENA, PySpark, and Jupyter Notebook.

The entire pipeline runs locally, so you don't need access to real patient data or cloud infrastructure.

What is OMOP CDM?

OMOP CDM stands for Observational Medical Outcomes Partnership Common Data Model. It's an open data model maintained by the Observational Health Data Sciences and Informatics (OHDSI) community.

It enables healthcare data from different sources to be represented consistently for clinical research and analytics.

OMOP addresses two types of data standardization: structural and semantic.

Structural Standardization

Different healthcare systems may store patient information using different table names, column names, and data types. OMOP provides a common structure for representing this information.

Two hospitals with different patient table structures and column names are mapped to a common OMOP CDM PERSON table, standardizing patient identifiers and birth date fields.

Regardless of the source structure, the transformed data follows a common model.

Semantic Standardization

Having the same table structure isn't enough if hospitals use different clinical codes to represent the same medical condition. OMOP uses standardized vocabularies to ensure that clinical information can be interpreted consistently across systems. This process is known as semantic standardization.

Clinical codes for type 2 diabetes from two hospitals using ICD-10-CM and SNOMED CT are mapped through OMOP standardized vocabularies to a common concept ID in the CONDITION_OCCURRENCE table.

Understanding the OMOP Common Data Model

OMOP CDM organizes healthcare data into several categories, including clinical data, healthcare system data, health economics, standardized vocabularies, and metadata.

For this tutorial, we'll focus primarily on clinical data.

OMOP Table Description
PERSON Patient demographic information
VISIT_OCCURRENCE Healthcare encounters, such as hospital admissions and outpatient visits
CONDITION_OCCURRENCE Diseases, diagnoses, signs and symptoms
DRUG_EXPOSURE Medications prescribed or administered
PROCEDURE_OCCURRENCE Medical and surgical procedures
MEASUREMENT Laboratory results, vital signs, and other measurements
OBSERVATION Other clinical facts, such as smoking status or family history
OBSERVATION_PERIOD Periods during which patient events can be captured

These tables are connected through identifiers such as person_id and visit_occurrence_id, allowing us to connect a patient's encounters, diagnoses, medications, and laboratory results.

You can explore the complete data model in the official OMOP CDM v5.4 documentation.

What Are Clinical Vocabularies and ATHENA?

A clinical vocabulary is a standardized collection of medical terms and codes used to represent healthcare information.

Some commonly used clinical vocabularies include SNOMED CT for diagnoses and clinical findings, LOINC for laboratory tests, RxNorm for medications, and UCUM for measurement units.

OMOP brings these vocabularies together and assigns each concept a unique identifier called concept_id.

ATHENA is OHDSI's platform for exploring and downloading these standardized vocabularies. We'll use the downloaded vocabulary files as reference data in our ETL pipeline.

How to Download OMOP Standardized Vocabularies from ATHENA

Create an account on ATHENA, and navigate to the vocabulary download section.

  1. Select SNOMED CT, LOINC, RxNorm, RxNorm Extension, UCUM, and the supporting vocabularies for demographics, visit types, and clinical record types.
  2. Create a bundle named synthea_omop_vocabulary. For this tutorial, I'm using release v20260829. Leave the Delta from Older Version option unchecked to download the complete bundle.
  3. Once downloaded, extract the ZIP file. We'll primarily use CONCEPT.csv, which contains clinical concepts, and CONCEPT_RELATIONSHIP.csv, which contains relationships and mappings between concepts.

Although these files have a .csv extension, they're tab-separated.

Note: Due to vocabulary-specific licensing restrictions, the downloaded vocabulary files aren't included in the GitHub repository. Download them directly from ATHENA after accepting the applicable licensing terms.

How to Build the Healthcare Data Standardization Pipeline

Now that you understand OMOP CDM and have downloaded the standardized vocabularies, let's build our ETL pipeline using PySpark.

The pipeline has four main stages, as shown below: ingestion, transformation, validation, and storage.

Step 1: Set Up the Development Environment

Create the following directory structure:

omop-cdm/ ├── synthea_to_omop.ipynb ├── requirements.txt ├── .gitignore └── data/ ├── synthea/ ├── vocabulary/ └── omop/ 

The synthea directory contains the source healthcare data, the vocabulary directory contains the downloaded OMOP standardized vocabularies, and the omop directory will contain the transformed healthcare data.

Ensure that Python and a compatible Java version are installed on your machine. Install the required dependencies:

python -m pip install notebook pyspark pandas matplotlib 

Launch Jupyter Notebook:

jupyter notebook 

Let's start by initializing a Spark session.

from pyspark.sql import SparkSession from pyspark.sql import functions as F from pathlib import Path spark = ( SparkSession.builder .appName("SyntheaToOMOP") .master("local[*]") .getOrCreate() ) spark 

Define the paths for our source data, vocabulary files, and transformed data.

DATA_DIR = Path("data") SYNTHEA_DIR = DATA_DIR / "synthea" VOCABULARY_DIR = DATA_DIR / "vocabulary" OMOP_DIR = DATA_DIR / "omop" 

Step 2: Load and Explore the Synthea Dataset

Copy the CSV files generated using Synthea into the data/synthea/ directory. For this tutorial, we'll work with six source tables: patients, encounters, conditions, medications, procedures, and observations.

Let's load these files into PySpark DataFrames.

source_tables = [ "patients", "encounters", "conditions", "medications", "procedures", "observations" ] synthea = {} for table in source_tables: synthea[table] = ( spark.read .option("header", True) .csv(str(SYNTHEA_DIR / f"{table}.csv")) ) 

We initially load the CSV columns as strings. This helps preserve clinical codes and identifiers without losing leading zeros or introducing unintended type conversions.

Let's check the number of records in each table.

for table, df in synthea.items(): print(f"{table}: {df.count():,} records") 

The record counts may vary depending on the synthetic dataset used.

Let's explore the patient data.

synthea["patients"].printSchema() synthea["patients"].select( "Id", "BIRTHDATE", "GENDER", "RACE", "ETHNICITY" ).show(5, truncate=False) 

Similarly, let's examine the conditions table.

synthea["conditions"].select( "PATIENT", "START", "CODE", "DESCRIPTION" ).show(5, truncate=False) 

Notice that each condition has a clinical code and a description. In the following sections, we'll use OMOP standardized vocabularies to map these clinical codes to standard concept IDs.

Step 3: Load the OMOP Standardized Vocabularies

Now that we've loaded the Synthea dataset, let's load the standardized vocabulary files downloaded from ATHENA.

For our transformation, we'll primarily use two vocabulary tables:

  • CONCEPT: Contains clinical codes, concept identifiers, vocabulary names, and clinical domains.
  • CONCEPT_RELATIONSHIP: Contains relationships between clinical concepts, including mappings from source concepts to standard concepts. Since the ATHENA vocabulary files are tab separated, we specify \t as the delimiter when loading them into PySpark.
concept = ( spark.read .option("header", True) .option("sep", "\t") .csv(str(VOCABULARY_DIR / "CONCEPT.csv")) .withColumn("concept_id", F.col("concept_id").cast("int")) ) concept_relationship = ( spark.read .option("header", True) .option("sep", "\t") .csv(str(VOCABULARY_DIR / "CONCEPT_RELATIONSHIP.csv")) .withColumn("concept_id_1", F.col("concept_id_1").cast("int")) .withColumn("concept_id_2", F.col("concept_id_2").cast("int")) ) 

Let's explore a few records from the CONCEPT table.

concept.select( "concept_id", "concept_name", "domain_id", "vocabulary_id", "concept_code", "standard_concept" ).show(5, truncate=False) 

Now that we have loaded both the source healthcare data and the standardized vocabularies, let's see how we can map clinical codes from Synthea to OMOP standard concepts.

Step 4: Map Clinical Codes to OMOP Standard Concepts

One of the most important steps in our healthcare data standardization pipeline is clinical vocabulary mapping.

For example, Synthea represents type 2 diabetes mellitus using the SNOMED CT code 44054006. OMOP CDM represents the same clinical concept using a unique concept identifier.

Let's look up this clinical code in the CONCEPT table.

concept.filter( (F.col("vocabulary_id") == "SNOMED") & (F.col("concept_code") == "44054006") ).select( "concept_id", "concept_name", "domain_id", "standard_concept" ).show(truncate=False) 

The corresponding concept is:

Attribute Value
concept_id 201826
concept_name Type 2 diabetes mellitus
domain_id Condition
standard_concept S

Here, S indicates that the concept is already a standard OMOP concept.

But not every clinical code maps directly to a standard concept. Some source concepts belong to non-standard vocabularies and need to be mapped using the CONCEPT_RELATIONSHIP table.

Understanding the "Maps to" Relationship

OMOP uses a relationship called Maps to to associate source concepts with their corresponding standard concepts.

Flowchart showing how source clinical codes are mapped to OMOP standard concept IDs using the CONCEPT and CONCEPT_RELATIONSHIP tables, with the mapped concept's clinical domain determining the target OMOP table.

Let's identify valid standard concepts.

standard = concept.filter( (F.col("standard_concept") == "S") & ( F.col("invalid_reason").isNull() | (F.col("invalid_reason") == "") ) ) 

Next, extract valid Maps to relationships.

links = concept_relationship.filter( (F.col("relationship_id") == "Maps to") & ( F.col("invalid_reason").isNull() | (F.col("invalid_reason") == "") ) ) 

Using these DataFrames, we create a reusable vocabulary lookup that maps source clinical codes to their corresponding standard concept IDs and clinical domains.

The complete lookup implementation is available in the accompanying Jupyter notebook.

Once the lookup is created, we can reuse it across different clinical tables.

def map_codes(df): return ( df.join( lookup, ["vocab", "code"], "left" ) .fillna( 0, subset=[ "source_concept_id", "standard_id" ] ) ) 

When a clinical code can't be mapped, we assign a concept ID of 0, indicating that no matching concept has been identified. These records should be tracked for further review.

Now that we have a reusable mechanism for clinical vocabulary mapping, let's start transforming our Synthea healthcare data into OMOP CDM tables, beginning with the PERSON table.

Step 5: How to Transform Patient Data into the PERSON Table

The PERSON table is the central clinical table in OMOP CDM. It contains demographic information about patients whose healthcare records are represented in the dataset.

Every patient is assigned a unique person_id, which is referenced by other clinical tables.

Synthea represents patient identifiers using UUIDs. OMOP CDM uses integer identifiers. So we need to create a mapping between the original patient identifier and the standardized OMOP patient identifier. This mapping is often referred to as an identity crosswalk.

Let's create the patient identity crosswalk using PySpark.

from pyspark.sql import Window patients = synthea["patients"] patient_mapping = ( patients .select("Id") .distinct() .withColumn( "person_id", F.row_number().over( Window.orderBy("Id") ) ) ) 

We'll reuse this mapping when transforming encounters, diagnoses, procedures, medications, and observations.

For this tutorial, sorted row numbers are sufficient because we're processing a fixed dataset. In a production pipeline, the identifier mapping should be persisted so that existing patient identifiers remain stable when new records are added.

Source-to-Target Mapping

Before transforming the data, let's understand how Synthea patient attributes map to OMOP attributes.

Synthea column OMOP column Transformation
ID person_id Integer identifier mapping
ID person_source_value Preserve source identifier
BIRTHDATE year_of_birth Extract year
BIRTHDATE month_of_birth Extract month
BIRTHDATE day_of_birth Extract day
GENDER gender_concept_id Concept mapping
RACE race_concept_id Concept mapping
ETHNICITY ethnicity_concept_id Concept mapping

This process of defining how source columns are transformed into target columns is known as source-to-target mapping.

The following code demonstrates the structural transformation of patient identifiers and birth dates.

person_demo = ( patients .join(patient_mapping, "Id") .withColumn( "birth_date", F.to_date("BIRTHDATE") ) .select( "person_id", F.year("birth_date").alias("year_of_birth"), F.month("birth_date").alias("month_of_birth"), F.dayofmonth("birth_date").alias("day_of_birth"), F.col("Id").alias("person_source_value") ) ) person_demo.show(5, truncate=False) 

Step 6: Transform the Remaining Clinical Tables

We can follow a similar approach to transform the remaining Synthea tables into OMOP CDM tables.

The following table summarizes the source-to-target mappings for our pipeline.

Synthea Source Table OMOP Target Table
encounters.csv VISIT_OCCURRENCE
conditions.csv CONDITION_OCCURRENCE
medications.csv DRUG_EXPOSURE
procedures.csv PROCEDURE_OCCURRENCE
observations.csv MEASUREMENT
observations.csv OBSERVATION
Patient visit and clinical event history OBSERVATION_PERIOD

For each transformation, we follow a similar approach:

  • Define the source-to-target column mappings.
  • Map patient and encounter identifiers to maintain relationships across tables.
  • Map source clinical codes to OMOP standard concepts.
  • Identify the appropriate target table based on the clinical domain.
  • Transform column names, data types, and values according to the OMOP CDM specification.
  • Preserve original source values for traceability.

The complete implementation is available in the accompanying Jupyter notebook.

Understanding Clinical Domain Distribution

One aspect of OMOP CDM is that a single source table can map to multiple target tables.

For example, Synthea stores laboratory results, vital signs, and other clinical findings in observations.csv. OMOP separates these records based on their clinical meaning.

The MEASUREMENT table captures results such as blood glucose, blood pressure, and body mass index, while the OBSERVATION table captures other clinical facts, such as family and social history.

We determine the target table using the domain_id of the mapped standard concept.

The following chart shows the clinical domain distribution obtained after running vocabulary mapping on our Synthea dataset.

Stacked horizontal bar chart showing the percentage distribution of OMOP clinical domains across Synthea source tables, highlighting how conditions, procedures, and observations map to multiple clinical domains, while medications map entirely to the Drug domain.

Records from procedures.csv are distributed across several domains, including Procedure, Measurement, and Observation.

This is why healthcare data standardization is more than a one-to-one table transformation. The clinical meaning of each record determines where it belongs in the standardized data model.

Unmapped concepts and records belonging to unsupported domains are captured separately for further review. Since a source record may map to multiple standard concepts, these distributions represent mapped rows instead of unique source records.

Step 7: How to Validate the Standardized Healthcare Data

Before saving the transformed data, we need to verify that it follows the expected OMOP structure and maintains relationships between clinical records.

Our pipeline performs the following data quality checks:

  • Primary key uniqueness: Ensures that identifiers are unique.
  • Referential integrity: Verifies that clinical records reference valid patients and encounters.
  • Vocabulary validation: Ensures that mapped concepts belong to the appropriate clinical domains.
  • Temporal validation: Checks for inconsistent clinical dates.
  • Data reconciliation: Tracks successfully transformed and unmapped records.

For example, we can verify that every patient has a unique person_id.

duplicate_patients = ( person.groupBy("person_id") .count() .filter(F.col("count") > 1) ) assert duplicate_patients.count() == 0 

Similarly, a left anti join helps us identify condition records that don't reference a valid patient.

orphan_conditions = condition_occurrence.join( person.select("person_id"), "person_id", "left_anti" ) assert orphan_conditions.count() == 0 

The remaining validation checks are implemented in the accompanying Jupyter notebook.

Step 8: How to Save the OMOP Tables in Parquet Format

Once the validation checks pass, we can save the transformed OMOP tables in Parquet format for downstream analytics.

Apache Parquet is an open-source, columnar file format designed for efficient data storage and analytical processing.

Imagine a healthcare dataset with patient IDs, birth dates, diagnoses, and medications. Parquet stores data column by column, like organizing information into separate folders by category.

If we only need to analyze patient diagnoses, Parquet allows us to read the relevant columns without reading the entire dataset. This reduces the amount of data processed and improves query performance. Parquet also supports efficient data compression, reducing storage requirements.

To learn more about how Parquet works and its benefits, refer to my article Understanding the Parquet File Format.

for table_name, df in omop_tables.items(): df.write.mode("overwrite").parquet( f"data/omop/{table_name}" ) 

Each OMOP table is stored in a separate directory and can be loaded independently without rerunning the ETL pipeline.

person = spark.read.parquet("data/omop/person") 

Step 9: How to Perform Clinical Analytics Using OMOP CDM

Now that our healthcare data follows a common structure and uses standardized concepts, we can query it using Spark SQL.

Let's identify the most frequently recorded conditions based on the number of unique patients.

for table_name, df in omop_tables.items(): df.createOrReplaceTempView(table_name) concept.createOrReplaceTempView("concept") spark.sql(""" SELECT c.concept_name, COUNT(DISTINCT co.person_id) AS patient_count FROM condition_occurrence co JOIN concept c ON co.condition_concept_id = c.concept_id GROUP BY c.concept_id, c.concept_name ORDER BY patient_count DESC LIMIT 10 """).show(truncate=False) 

The query returns the most frequently recorded standardized conditions based on the number of unique patients.

If another hospital transforms its data into the same OMOP model, we can reuse this query without changing it to accommodate the original source schema. This is one of the key benefits of healthcare data standardization.

Conclusion

In this tutorial, we built a healthcare data standardization pipeline using Synthea, OMOP CDM, ATHENA, and PySpark. We explored clinical vocabulary mapping, transformed healthcare records into standardized OMOP tables, and validated the resulting data.

While we used synthetic data, the same principles apply when integrating data from real-world healthcare systems. Production implementations require additional considerations such as local clinical codes, missing data, patient privacy, and more comprehensive validation.

I hope this tutorial helps you get started with healthcare data standardization and understand how OMOP CDM can provide a foundation for clinical research, healthcare analytics, and AI applications.

References for the article

原文:https://www.a8q9.cn/en/article/how-to-standardize-healthcare-data-using-omop-cdm-and-pyspark-a9c487.html

相关文章