pyhealth.datasets.SyntheaCSVDataset#
Loads the CSV export of Synthea, a synthetic patient simulator, through the standard PyHealth dataset API. Synthea data is fully synthetic, so it needs no credentialing and is useful for prototyping pipelines before you have access to MIMIC or eICU.
Getting Data#
root is a directory of Synthea CSV files. There are two ways to get one:
Generate it with
Synthea(requires Java 17+; see its Setup section). This lets you choose the population size, seed, location, and age range.Download a pre-generated sample from the Synthea downloads page and unzip it. No Java is needed; pick the CSV variant.
from pyhealth.datasets import SyntheaCSVDataset
from pyhealth.models import Synthea
csv_dir = Synthea("./synthea-output").generate(population=100, seed=42)
# or: csv_dir = "/path/to/unzipped/sample/csv" # directory with patients.csv
dataset = SyntheaCSVDataset(
csv_dir,
tables=["conditions", "medications", "observations"],
)
dataset.stats()
How Synthea Differs From Other PyHealth Datasets#
What Synthea writes is very different from MIMIC; what PyHealth gives you back is the same. The differences to watch for are in the raw files and in the medical codes, not in the dataset object.
Raw output: many wide tables#
A Synthea run writes about 18 CSV files. Each has many columns, every row is
keyed by a UUID, and the files include synthetic billing and insurance data.
For example, the first rows of conditions.csv and observations.csv:
START,STOP,PATIENT,ENCOUNTER,SYSTEM,CODE,DESCRIPTION
2004-07-17,,ba419d35-...-eebf02485a56,ba419d35-...-4d3d0f870810,SNOMED-CT,224299000,Received higher education (finding)
DATE,PATIENT,ENCOUNTER,CATEGORY,CODE,DESCRIPTION,VALUE,UNITS,TYPE
2023-08-12T20:03:25Z,ba419d35-...-eebf02485a56,ba419d35-...-b4779d5cf14b,laboratory,4548-4,Hemoglobin A1c/Hemoglobin.total in Blood,6.3,%,numeric
Not every file can be loaded, because PyHealth organizes events by patient:
Files |
Loaded? |
|---|---|
|
Yes, by default. Files Synthea did not emit (no rows) are skipped. |
|
Only when listed in |
|
No. They describe institutions, not patients, so they have no patient column. |
After loading: the standard PyHealth event table#
Like every PyHealth dataset, SyntheaCSVDataset turns each row of each table
into one event with three fixed columns, patient_id, event_type (the
table name), and timestamp, plus one <table>/<column> column per kept
attribute. Columns belonging to other tables are null for that event:
patient_id event_type timestamp conditions/code conditions/description observations/code observations/value ...
ba419d35-... conditions 2004-07-17 00:00:00 224299000 Received higher ... null null
ba419d35-... observations 2023-08-12 20:03:25 null null 4548-4 6.3
Through the patient API, the table prefix is dropped:
patient = dataset.get_patient(dataset.unique_patient_ids[0])
for event in patient.get_events(event_type="conditions"):
print(event.timestamp, event.code, event.description)
numeric_obs = patient.get_events(
event_type="observations",
filters=[("type", "==", "numeric")],
)
The columns kept per table are listed in
pyhealth/datasets/configs/synthea_csv.yaml. Columns that identify a person
(name, SSN, street address, coordinates) are not loaded.
Medical codes: SNOMED-CT, RxNorm, LOINC, CVX#
This difference matters most. MIMIC codes diagnoses with ICD-9/ICD-10 and drugs with NDC; Synthea uses different vocabularies:
Table |
Code system |
Example |
|---|---|---|
|
SNOMED-CT |
|
|
SNOMED-CT |
|
|
RxNorm |
|
|
LOINC |
|
|
CVX |
|
|
Mostly SNOMED-CT; drug allergies use RxNorm. The |
|
As a result:
Built-in tasks written for MIMIC (for example
MortalityPredictionMIMIC3) read ICD columns and do not work on Synthea. Write a task for Synthea instead (see Tasks).ICD-based code mappings in
pyhealth.medcode(such as ICD to CCS) do not apply. RxNorm codes are supported bypyhealth.medcode.RxNorm.Every code comes with a human-readable
descriptioncolumn.
Other differences#
Each patient has a ``patients`` event at their birth date. Demographics (
gender,race,deathdate, …) are attributes of that event.Visits are not a separate level. Each clinical event has an
encounterattribute holding the UUID of its encounter; group events by it to rebuild visits.Lab values are strings.
observations/valueholds numbers and text answers in one column;observations/type(numericortext) says which.Timestamps mix dates and date-times across tables (for example
conditionshas dates,observationshas date-times). PyHealth parses both; date-only events get a midnight timestamp.
- class pyhealth.datasets.SyntheaCSVDataset(root, tables=None, dataset_name=None, config_path=None, **kwargs)[source]#
Bases:
BaseDatasetLoads Synthea CSV files through the PyHealth dataset API.
The dataset only reads files; it does not run Synthea. Produce the CSV directory with
Syntheafirst, or pointrootat any existing Synthea CSV export.Each row becomes a standard PyHealth event (
patient_id,event_type,timestampplus the table’s attributes), but Synthea’s codes are SNOMED-CT, RxNorm, LOINC, and CVX rather than ICD and NDC, so MIMIC tasks and ICD code mappings do not apply directly.Examples
>>> from pyhealth.datasets import SyntheaCSVDataset >>> from pyhealth.models import Synthea >>> csv_dir = Synthea("./synthea-output").generate(population=10, seed=42) >>> dataset = SyntheaCSVDataset(csv_dir, tables=["conditions"]) >>> patient = dataset.get_patient(dataset.unique_patient_ids[0]) >>> event = patient.get_events(event_type="conditions")[0] >>> event.code, event.description # SNOMED-CT code and its text
Initializes a Synthea CSV dataset.
- Parameters:
root (str or Path) – Directory containing the Synthea CSV files.
tables (list[str], optional) – CSV tables to load. The supported defaults are used when omitted or empty.
dataset_name (str, optional) – Dataset name used by PyHealth.
config_path (str, optional) – Dataset schema configuration. The bundled Synthea CSV schema is used when omitted.
**kwargs – Additional arguments passed to
BaseDataset.
- __init__(root, tables=None, dataset_name=None, config_path=None, **kwargs)[source]#
Initializes a Synthea CSV dataset.
- Parameters:
root (str or Path) – Directory containing the Synthea CSV files.
tables (list[str], optional) – CSV tables to load. The supported defaults are used when omitted or empty.
dataset_name (str, optional) – Dataset name used by PyHealth.
config_path (str, optional) – Dataset schema configuration. The bundled Synthea CSV schema is used when omitted.
**kwargs – Additional arguments passed to
BaseDataset.
- load_data()[source]#
Loads the selected tables, skipping default tables not emitted.
Synthea omits CSV files for record types with no rows. A missing default table is skipped; a missing table requested explicitly is treated as an error.
- Returns:
Concatenated lazy Dask DataFrame for the selected tables.
- Return type:
dd.DataFrame
- Raises:
RuntimeError – If an explicitly selected table is missing.
- preprocess_procedures(frame)[source]#
Normalizes legacy Synthea procedure timestamps.
Older exports use
datewhere the current schema usesstart. Existingstartcolumns are preserved.- Parameters:
frame (nw.LazyFrame) – Procedure table before schema normalization.
- Returns:
Procedure table containing a
startcolumn.- Return type:
nw.LazyFrame
- clean_tmpdir()#
Removes the temporary directories this dataset created.
Other jobs may share the same cache directory and still be using their own directories under
tmp/, so those are left alone.tmp/itself is removed once it is empty.- Return type:
- create_tmpdir()#
Creates and returns a new temporary directory within the cache.
- Returns:
The path to the new temporary directory.
- Return type:
- property default_task: Optional[BaseTask]#
Returns the default task for the dataset.
- Returns:
The default task, if any.
- Return type:
Optional[BaseTask]
- get_patient(patient_id)#
Retrieves a Patient object for the given patient ID.
- Parameters:
patient_id (str) – The ID of the patient to retrieve.
- Returns:
The Patient object for the given ID.
- Return type:
- Raises:
AssertionError – If the patient ID is not found in the dataset.
- property global_event_df: LazyFrame#
Returns the path to the cached event dataframe.
- Returns:
The path to the cached event dataframe.
- Return type:
- iter_patients(df=None)#
Yields Patient objects for each unique patient in the dataset.
- load_table(table_name)#
Loads a table and processes joins if specified.
- Parameters:
table_name (str) – The name of the table to load.
- Returns:
The processed Dask dataframe for the table.
- Return type:
dd.DataFrame
- Raises:
ValueError – If the table is not found in the config.
FileNotFoundError – If the source file (CSV/TSV or Parquet) for the table or join is not found.
- set_task(task=None, num_workers=None, input_processors=None, output_processors=None, split=None)#
Processes the base dataset to generate the task-specific sample dataset. The cache structure is as follows:
{task_name}_{task_uuid}/ # Cached data for specific task based on task name, schema, and args task_df.ld/ # Intermediate task dataframe based on schema samples_{proc_uuid}.ld/ # Final processed samples after applying processors schema.pkl # Saved SampleBuilder schema split.npz # Sample indices per split part (with split= only) *.bin # Processed sample files
- Parameters:
task (Optional[BaseTask]) – The task to set. Uses default task if None.
num_workers (int) – Number of workers for multi-threading. Default is self.num_workers.
input_processors (Optional[Dict[str, FeatureProcessor]]) – Pre-fitted input processors. If provided, these will be used instead of creating new ones from task’s input_schema. Defaults to None.
output_processors (Optional[Dict[str, FeatureProcessor]]) – Pre-fitted output processors. If provided, these will be used instead of creating new ones from task’s output_schema. Defaults to None.
split (Optional[Split]) – Split the samples, e.g. by patient with
PatientSplit, and fit every processor on the first (training) part only, so the other parts never shape preprocessing. The parts are used as the split returns them. Samples are streamed; nothing is loaded into memory beyond the per-sample index that processing already keeps. Defaults to None: fit on all samples and return one dataset, as before.
- Returns:
The generated sample dataset, or, with
split, a tuple with one dataset per part, training part first, whose processors were fitted on the training part.- Return type:
Examples
>>> from pyhealth.datasets import PatientSplit >>> train, val, test = dataset.set_task( ... task, split=PatientSplit(ratios=(0.7, 0.1, 0.2), seed=42) ... )
- Raises:
AssertionError – If no default task is found and task is None.