cehrbert 1.2.2__tar.gz → 1.2.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. {cehrbert-1.2.2 → cehrbert-1.2.4}/PKG-INFO +1 -1
  2. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/data_generators/hf_data_generator/hf_dataset_mapping.py +81 -36
  3. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/data_generators/hf_data_generator/meds_to_cehrbert_conversion_rules/meds_to_cehrbert_base.py +14 -0
  4. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/data_generators/hf_data_generator/meds_to_cehrbert_conversion_rules/meds_to_cehrbert_micmic4.py +3 -0
  5. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/data_generators/hf_data_generator/meds_to_cehrbert_conversion_rules/meds_to_cehrbert_omop.py +3 -0
  6. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/data_generators/hf_data_generator/meds_utils.py +19 -8
  7. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/data_generators/hf_data_generator/patient_block.py +27 -22
  8. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/models/hf_models/hf_cehrbert.py +63 -2
  9. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/runners/hf_runner_argument_dataclass.py +4 -0
  10. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert.egg-info/PKG-INFO +1 -1
  11. {cehrbert-1.2.2 → cehrbert-1.2.4}/.github/workflows/python-build.yml +0 -0
  12. {cehrbert-1.2.2 → cehrbert-1.2.4}/.github/workflows/tests.yml +0 -0
  13. {cehrbert-1.2.2 → cehrbert-1.2.4}/.gitignore +0 -0
  14. {cehrbert-1.2.2 → cehrbert-1.2.4}/.pre-commit-config.yaml +0 -0
  15. {cehrbert-1.2.2 → cehrbert-1.2.4}/LICENSE +0 -0
  16. {cehrbert-1.2.2 → cehrbert-1.2.4}/README.md +0 -0
  17. {cehrbert-1.2.2 → cehrbert-1.2.4}/db_properties.ini +0 -0
  18. {cehrbert-1.2.2 → cehrbert-1.2.4}/deepspeed_configs/zero1.json +0 -0
  19. {cehrbert-1.2.2 → cehrbert-1.2.4}/deepspeed_configs/zero2.json +0 -0
  20. {cehrbert-1.2.2 → cehrbert-1.2.4}/deepspeed_configs/zero3.json +0 -0
  21. {cehrbert-1.2.2 → cehrbert-1.2.4}/full_grid_search_config.ini +0 -0
  22. {cehrbert-1.2.2 → cehrbert-1.2.4}/images/cehr_bert_architecture.png +0 -0
  23. {cehrbert-1.2.2 → cehrbert-1.2.4}/images/tokenization_att_generation.png +0 -0
  24. {cehrbert-1.2.2 → cehrbert-1.2.4}/pyproject.toml +0 -0
  25. {cehrbert-1.2.2 → cehrbert-1.2.4}/sample_configs/hf_cehrbert_finetuning_runner_config.yaml +0 -0
  26. {cehrbert-1.2.2 → cehrbert-1.2.4}/sample_configs/hf_cehrbert_pretrain_runner_config.yaml +0 -0
  27. {cehrbert-1.2.2 → cehrbert-1.2.4}/sample_configs/hf_cehrbert_pretrain_runner_meds_config.yaml +0 -0
  28. {cehrbert-1.2.2 → cehrbert-1.2.4}/sample_data/finetune/full/fake_data.parquet +0 -0
  29. {cehrbert-1.2.2 → cehrbert-1.2.4}/sample_data/finetune/test/fake_data.parquet +0 -0
  30. {cehrbert-1.2.2 → cehrbert-1.2.4}/sample_data/finetune/train/fake_data.parquet +0 -0
  31. {cehrbert-1.2.2 → cehrbert-1.2.4}/sample_data/pretrain/patient_sequence.parquet +0 -0
  32. {cehrbert-1.2.2 → cehrbert-1.2.4}/setup.cfg +0 -0
  33. {cehrbert-1.2.2 → cehrbert-1.2.4}/simple_grid_search_config.ini +0 -0
  34. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/__init__.py +0 -0
  35. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/config/__init__.py +0 -0
  36. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/config/grid_search_config.py +0 -0
  37. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/data_generators/__init__.py +0 -0
  38. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/data_generators/data_classes.py +0 -0
  39. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/data_generators/data_generator_base.py +0 -0
  40. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/data_generators/graph_sample_method.py +0 -0
  41. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/data_generators/hf_data_generator/__init__.py +0 -0
  42. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/data_generators/hf_data_generator/hf_dataset.py +0 -0
  43. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/data_generators/hf_data_generator/hf_dataset_collator.py +0 -0
  44. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/data_generators/hf_data_generator/meds_to_cehrbert_conversion_rules/__init__.py +0 -0
  45. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/data_generators/learning_objective.py +0 -0
  46. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/data_generators/tokenizer.py +0 -0
  47. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/evaluations/__init__.py +0 -0
  48. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/evaluations/evaluation.py +0 -0
  49. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/evaluations/evaluation_parameters.py +0 -0
  50. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/evaluations/evaluation_parse_args.py +0 -0
  51. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/evaluations/model_evaluators/__init__.py +0 -0
  52. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/evaluations/model_evaluators/bert_model_evaluators.py +0 -0
  53. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/evaluations/model_evaluators/frequency_model_evaluators.py +0 -0
  54. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/evaluations/model_evaluators/hierarchical_bert_evaluators.py +0 -0
  55. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/evaluations/model_evaluators/model_evaluators.py +0 -0
  56. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/evaluations/model_evaluators/sequence_model_evaluators.py +0 -0
  57. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/evaluations/transfer_learning_evaluation.py +0 -0
  58. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/keras_transformer/__init__.py +0 -0
  59. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/keras_transformer/bert.py +0 -0
  60. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/keras_transformer/extras.py +0 -0
  61. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/keras_transformer/position.py +0 -0
  62. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/med_extension/__init__.py +0 -0
  63. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/med_extension/schema_extension.py +0 -0
  64. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/models/__init__.py +0 -0
  65. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/models/bert_models.py +0 -0
  66. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/models/bert_models_visit_prediction.py +0 -0
  67. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/models/evaluation_models.py +0 -0
  68. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/models/hf_models/__init__.py +0 -0
  69. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/models/hf_models/config.py +0 -0
  70. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/models/hf_models/hf_modeling_outputs.py +0 -0
  71. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/models/hf_models/tokenization_hf_cehrbert.py +0 -0
  72. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/models/hf_models/tokenization_utils.py +0 -0
  73. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/models/hierachical_bert_model_v2.py +0 -0
  74. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/models/hierachical_phenotype_model_new.py +0 -0
  75. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/models/layers/__init__.py +0 -0
  76. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/models/layers/custom_layers.py +0 -0
  77. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/models/layers/hierarchical_custom_layers.py +0 -0
  78. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/models/loss_schedulers.py +0 -0
  79. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/models/parse_args.py +0 -0
  80. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/runners/__init__.py +0 -0
  81. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/runners/hf_cehrbert_finetune_runner.py +0 -0
  82. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/runners/hf_cehrbert_pretrain_runner.py +0 -0
  83. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/runners/runner_util.py +0 -0
  84. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/tools/__init__.py +0 -0
  85. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/tools/download_omop_tables.py +0 -0
  86. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/trainers/__init__.py +0 -0
  87. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/trainers/model_trainer.py +0 -0
  88. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/trainers/train_cehr_bert.py +0 -0
  89. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/utils/__init__.py +0 -0
  90. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/utils/checkpoint_utils.py +0 -0
  91. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/utils/logging_utils.py +0 -0
  92. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/utils/model_utils.py +0 -0
  93. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert/utils/stat_utils.py +0 -0
  94. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert.egg-info/SOURCES.txt +0 -0
  95. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert.egg-info/dependency_links.txt +0 -0
  96. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert.egg-info/entry_points.txt +0 -0
  97. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert.egg-info/requires.txt +0 -0
  98. {cehrbert-1.2.2 → cehrbert-1.2.4}/src/cehrbert.egg-info/top_level.txt +0 -0
  99. {cehrbert-1.2.2 → cehrbert-1.2.4}/tests/__init__.py +0 -0
  100. {cehrbert-1.2.2 → cehrbert-1.2.4}/tests/integration_tests/__init__.py +0 -0
  101. {cehrbert-1.2.2 → cehrbert-1.2.4}/tests/integration_tests/runners/__init__.py +0 -0
  102. {cehrbert-1.2.2 → cehrbert-1.2.4}/tests/integration_tests/runners/hf_cehrbert_pretrain_runner_test.py +0 -0
  103. {cehrbert-1.2.2 → cehrbert-1.2.4}/tests/integration_tests/trainers/__init__.py +0 -0
  104. {cehrbert-1.2.2 → cehrbert-1.2.4}/tests/integration_tests/trainers/train_cehr_bert_test.py +0 -0
  105. {cehrbert-1.2.2 → cehrbert-1.2.4}/tests/unit_tests/__init__.py +0 -0
  106. {cehrbert-1.2.2 → cehrbert-1.2.4}/tests/unit_tests/data_generators/__init__.py +0 -0
  107. {cehrbert-1.2.2 → cehrbert-1.2.4}/tests/unit_tests/data_generators/bert_masked_language_modeling_learning_objective_test.py +0 -0
  108. {cehrbert-1.2.2 → cehrbert-1.2.4}/tests/unit_tests/data_generators/hf_data_generator/__init__.py +0 -0
  109. {cehrbert-1.2.2 → cehrbert-1.2.4}/tests/unit_tests/data_generators/hf_data_generator/hf_generate_start_end_index_mapping_test.py +0 -0
  110. {cehrbert-1.2.2 → cehrbert-1.2.4}/tests/unit_tests/data_generators/hf_data_generator/hf_masked_language_modeling_mapping_test.py +0 -0
  111. {cehrbert-1.2.2 → cehrbert-1.2.4}/tests/unit_tests/data_generators/hf_data_generator/hf_med_to_cehrbert_mapping_test.py +0 -0
  112. {cehrbert-1.2.2 → cehrbert-1.2.4}/tests/unit_tests/data_generators/hf_data_generator/hf_sort_patient_sequence_dataset_mapping_test.py +0 -0
  113. {cehrbert-1.2.2 → cehrbert-1.2.4}/tests/unit_tests/data_generators/hf_data_generator/meds_utils_test.py +0 -0
  114. {cehrbert-1.2.2 → cehrbert-1.2.4}/tests/unit_tests/data_generators/hf_data_generator/omop_meds_generate_demographics_and_patient_blocks_test.py +0 -0
  115. {cehrbert-1.2.2 → cehrbert-1.2.4}/tests/unit_tests/data_generators/visit_prediction_learning_objective_test.py +0 -0
  116. {cehrbert-1.2.2 → cehrbert-1.2.4}/tests/unit_tests/models/__init__.py +0 -0
  117. {cehrbert-1.2.2 → cehrbert-1.2.4}/tests/unit_tests/models/concept_value_decoder_layer_test.py +0 -0
  118. {cehrbert-1.2.2 → cehrbert-1.2.4}/tests/unit_tests/models/hf_models/__init__.py +0 -0
  119. {cehrbert-1.2.2 → cehrbert-1.2.4}/tests/unit_tests/models/hf_models/hf_cehrbert_test.py +0 -0
  120. {cehrbert-1.2.2 → cehrbert-1.2.4}/tests/unit_tests/models/hf_models/numeric_concept_statistics_test.py +0 -0
  121. {cehrbert-1.2.2 → cehrbert-1.2.4}/tests/unit_tests/models/hf_models/tokenization_hf_cehrbert_test.py +0 -0
  122. {cehrbert-1.2.2 → cehrbert-1.2.4}/tests/unit_tests/utils/__init__.py +0 -0
  123. {cehrbert-1.2.2 → cehrbert-1.2.4}/tests/unit_tests/utils/truncated_offline_statistics_test.py +0 -0
  124. {cehrbert-1.2.2 → cehrbert-1.2.4}/tests/unit_tests/utils/truncated_online_statistics_test.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: cehrbert
3
- Version: 1.2.2
3
+ Version: 1.2.4
4
4
  Summary: CEHR-BERT: Incorporating temporal information from structured EHR data to improve prediction tasks
5
5
  Author-email: Chao Pang <chaopang229@gmail.com>, Xinzhuo Jiang <xj2193@cumc.columbia.edu>, Krishna Kalluri <kk3326@cumc.columbia.edu>, Nishanth Parameshwar Pavinkurve <np2689@cumc.columbia.edu>, Karthik Natarajan <kn2174@cumc.columbia.edu>
6
6
  License: MIT License
@@ -30,6 +30,7 @@ INPATIENT_VISIT_TYPE_CODES = [
30
30
  "Visit/61",
31
31
  "NUCC/315D00000X",
32
32
  ]
33
+ ED_VISIT_TYPE_CODES = ["Visit/ER"]
33
34
  DISCHARGE_FACILITY_TYPES = [
34
35
  "8536",
35
36
  "8863",
@@ -54,6 +55,41 @@ DISCHARGE_FACILITY_TYPES = [
54
55
  DATE_FORMAT = "%Y-%m-%d %H:%M:%S.%f"
55
56
 
56
57
 
58
+ def convert_date_to_posix_time(index_date: Union[datetime.date, datetime.datetime]) -> float:
59
+ """
60
+ Convert a date or datetime object to POSIX (Unix) time in seconds.
61
+
62
+ Parameters
63
+ ----------
64
+ index_date : Union[datetime.date, datetime.datetime]
65
+ The date or datetime object to be converted to POSIX time.
66
+
67
+ Returns
68
+ -------
69
+ float
70
+ The POSIX time in seconds as a float.
71
+
72
+ Raises
73
+ ------
74
+ ValueError
75
+ If `index_date` is not an instance of `datetime.date` or `datetime.datetime`.
76
+
77
+ Examples
78
+ --------
79
+ >>> convert_date_to_posix_time(datetime.date(2024, 10, 25))
80
+ 1735104000.0
81
+
82
+ >>> convert_date_to_posix_time(datetime.datetime(2024, 10, 25, 12, 30))
83
+ 1735144200.0
84
+ """
85
+ if isinstance(index_date, datetime.datetime):
86
+ return index_date.timestamp()
87
+ elif isinstance(index_date, datetime.date):
88
+ return datetime.datetime.combine(index_date, datetime.datetime.min.time()).timestamp()
89
+ else:
90
+ raise ValueError("index_date must be datetime or datetime.datetime")
91
+
92
+
57
93
  def replace_escape_chars(text: str) -> str:
58
94
  return re.sub(r"\s+", "_", text)
59
95
 
@@ -122,8 +158,6 @@ class MedToCehrBertDatasetMapping(DatasetMapping):
122
158
  "visits",
123
159
  "birth_datetime",
124
160
  "visit_concept_ids",
125
- "num_of_concepts",
126
- "num_of_visits",
127
161
  ]
128
162
 
129
163
  @staticmethod
@@ -140,7 +174,7 @@ class MedToCehrBertDatasetMapping(DatasetMapping):
140
174
  mlm_skip_value: int = 0,
141
175
  unit: str = NA,
142
176
  ) -> None:
143
- cehrbert_record["concept_ids"].append(code)
177
+ cehrbert_record["concept_ids"].append(replace_escape_chars(code))
144
178
  cehrbert_record["visit_concept_orders"].append(visit_concept_order)
145
179
  cehrbert_record["ages"].append(age)
146
180
  cehrbert_record["dates"].append(date)
@@ -205,10 +239,14 @@ class MedToCehrBertDatasetMapping(DatasetMapping):
205
239
 
206
240
  # We assume the first measurement to be the visit type of the current visit
207
241
  visit_type = visit["visit_type"]
208
- is_inpatient = visit_type in INPATIENT_VISIT_TYPES or visit_type in INPATIENT_VISIT_TYPE_CODES
242
+ is_er_or_inpatient = (
243
+ visit_type in INPATIENT_VISIT_TYPES
244
+ or visit_type in INPATIENT_VISIT_TYPE_CODES
245
+ or visit_type in ED_VISIT_TYPE_CODES
246
+ )
209
247
 
210
248
  # Add artificial time tokens to the patient timeline if timedelta exists
211
- if time_delta:
249
+ if time_delta is not None:
212
250
  # This generates an artificial time token depending on the choice of the time token functions
213
251
  self._update_cehrbert_record(
214
252
  cehrbert_record,
@@ -242,39 +280,12 @@ class MedToCehrBertDatasetMapping(DatasetMapping):
242
280
  visit_segment=visit_segment,
243
281
  visit_concept_id=visit_type,
244
282
  )
245
-
283
+ # Keep track of the existing outpatient events, we don't want to add them again
284
+ existing_outpatient_events = list()
246
285
  for e in events:
247
286
  # If the event doesn't have a time stamp, we skip it
248
287
  if not e["time"]:
249
288
  continue
250
- # Add a medical token to the patient timeline
251
- # If this is an inpatient visit, we use the event time stamps to calculate age and date
252
- # because the patient can stay in the hospital for a period of time.
253
- if is_inpatient:
254
- # Calculate age using the event time stamp
255
- age = relativedelta(e["time"], birth_datetime).years
256
- # Calculate the week number since the epoch time
257
- date = (e["time"] - datetime.datetime(year=1970, month=1, day=1)).days // 7
258
- else:
259
- # For outpatient visits, we use the visit time stamp to calculate age and time because we assume
260
- # the outpatient visits start and end on the same day
261
- pass
262
-
263
- # Calculate the time diff in days w.r.t the previous measurement
264
- meas_time_diff = (e["time"] - date_cursor).days
265
- # Update the date_cursor if the time diff between two neighboring measurements is greater than and
266
- # equal to 1 day
267
- if meas_time_diff > 0:
268
- date_cursor = e["time"]
269
- if self._inpatient_time_token_function:
270
- # This generates an artificial time token depending on the choice of the time token functions
271
- self._update_cehrbert_record(
272
- cehrbert_record,
273
- code=f"i-{self._inpatient_time_token_function(meas_time_diff)}",
274
- visit_concept_order=i + 1,
275
- visit_segment=visit_segment,
276
- visit_concept_id=visit_type,
277
- )
278
289
 
279
290
  # If numeric_value exists, this is a concept/value tuple, we indicate this using a concept_value_mask
280
291
  numeric_value = e.get("numeric_value", None)
@@ -283,6 +294,7 @@ class MedToCehrBertDatasetMapping(DatasetMapping):
283
294
  concept_value_mask = int(numeric_value is not None)
284
295
  concept_value = numeric_value if concept_value_mask == 1 else -1.0
285
296
  code = replace_escape_chars(e["code"])
297
+
286
298
  # If the value mask is 1, this indicates a numeric value associated with the concept
287
299
  if concept_value_mask != 1:
288
300
  # Otherwise we will try to concatenate the answer with the code if the categorical value is provide
@@ -291,6 +303,37 @@ class MedToCehrBertDatasetMapping(DatasetMapping):
291
303
  text_value_replaced = replace_escape_chars(text_value)
292
304
  code = f"{code}//option:{text_value_replaced}"
293
305
 
306
+ # Add a medical token to the patient timeline
307
+ # If this is an inpatient visit, we use the event time stamps to calculate age and date
308
+ # because the patient can stay in the hospital for a period of time.
309
+ if is_er_or_inpatient:
310
+ # Calculate age using the event time stamp
311
+ age = relativedelta(e["time"], birth_datetime).years
312
+ # Calculate the week number since the epoch time
313
+ date = (e["time"] - datetime.datetime(year=1970, month=1, day=1)).days // 7
314
+ # Calculate the time diff in days w.r.t the previous measurement
315
+ meas_time_diff = (e["time"] - date_cursor).days
316
+ # Update the date_cursor if the time diff between two neighboring measurements is greater than and
317
+ # equal to 1 day
318
+ if meas_time_diff > 0:
319
+ date_cursor = e["time"]
320
+ if self._inpatient_time_token_function:
321
+ # This generates an artificial time token depending on the choice of the time token functions
322
+ self._update_cehrbert_record(
323
+ cehrbert_record,
324
+ code=f"i-{self._inpatient_time_token_function(meas_time_diff)}",
325
+ visit_concept_order=i + 1,
326
+ visit_segment=visit_segment,
327
+ visit_concept_id=visit_type,
328
+ )
329
+ else:
330
+ # For outpatient visits, we use the visit time stamp to calculate age and time because we assume
331
+ # the outpatient visits start and end on the same day.
332
+ # We check whether the date/code/value combination already exists in the existing events
333
+ # If they exist, we do not add them to the patient timeline for outpatient visits.
334
+ if (date, code, concept_value) in existing_outpatient_events:
335
+ continue
336
+
294
337
  self._update_cehrbert_record(
295
338
  cehrbert_record,
296
339
  code=code,
@@ -304,8 +347,10 @@ class MedToCehrBertDatasetMapping(DatasetMapping):
304
347
  unit=unit,
305
348
  mlm_skip_value=concept_value_mask,
306
349
  )
350
+ existing_outpatient_events.append((date, code, concept_value))
307
351
 
308
- if is_inpatient:
352
+ # For inpatient or ER visits, we want to discharge_facility to the end of the visit
353
+ if is_er_or_inpatient:
309
354
  # If visit_end_datetime is populated for the inpatient visit, we update the date_cursor
310
355
  visit_end_datetime = visit.get("visit_end_datetime", None)
311
356
  if visit_end_datetime:
@@ -463,7 +508,7 @@ class HFFineTuningMapping(DatasetMapping):
463
508
  return {
464
509
  "age_at_index": record["age"] if "age" in record else record["age_at_index"],
465
510
  "classifier_label": record["label"],
466
- "index_date": record["index_date"].timestamp() if "index_date" in record else None,
511
+ "index_date": (convert_date_to_posix_time(record["index_date"]) if "index_date" in record else None),
467
512
  }
468
513
 
469
514
  def remove_columns(self):
@@ -64,11 +64,22 @@ class MedsToCehrBertConversion(ABC):
64
64
  text-to-numeric event mappings, which are created by calling the respective abstract methods.
65
65
  """
66
66
  # Cache these variables once
67
+ self._meds_exclude_tables = kwargs.get("meds_exclude_tables", [])
67
68
  self._ed_admission_matching_rules = self._create_ed_admission_matching_rules()
68
69
  self._admission_matching_rules = self._create_admission_matching_rules()
69
70
  self._discharge_matching_rules = self._create_discharge_matching_rules()
70
71
  self._text_event_numeric_event_map = {r.code: r for r in self._create_text_event_to_numeric_event_rules()}
71
72
 
73
+ @property
74
+ def meds_exclude_tables(self):
75
+ return self._meds_exclude_tables
76
+
77
+ @abstractmethod
78
+ def _create_visit_matching_rules(self) -> List[str]:
79
+ raise NotImplementedError(
80
+ "Must implement the matching rules for identifying the visits other than ED/admission"
81
+ )
82
+
72
83
  @abstractmethod
73
84
  def _create_ed_admission_matching_rules(self) -> List[str]:
74
85
  """
@@ -122,6 +133,9 @@ class MedsToCehrBertConversion(ABC):
122
133
  """
123
134
  raise NotImplementedError("Must implement the event mapping rules for converting text events to numeric events")
124
135
 
136
+ def get_other_visit_matching_rules(self) -> List[str]:
137
+ return self._create_visit_matching_rules()
138
+
125
139
  def get_ed_admission_matching_rules(self) -> List[str]:
126
140
  return self._ed_admission_matching_rules
127
141
 
@@ -13,6 +13,9 @@ class MedsToBertMimic4(MedsToCehrBertConversion):
13
13
  super().__init__(**kwargs)
14
14
  self.default_visit_id = default_visit_id
15
15
 
16
+ def _create_visit_matching_rules(self) -> List[str]:
17
+ return []
18
+
16
19
  def _create_ed_admission_matching_rules(self) -> List[str]:
17
20
  return ["ED_REGISTRATION//", "TRANSFER_TO//ED"]
18
21
 
@@ -8,6 +8,9 @@ from cehrbert.data_generators.hf_data_generator.meds_to_cehrbert_conversion_rule
8
8
 
9
9
  class MedsToCehrbertOMOP(MedsToCehrBertConversion):
10
10
 
11
+ def _create_visit_matching_rules(self) -> List[str]:
12
+ return ["Visit/"]
13
+
11
14
  def _create_ed_admission_matching_rules(self) -> List[str]:
12
15
  return ["Visit/ER"]
13
16
 
@@ -2,7 +2,7 @@ import collections
2
2
  import functools
3
3
  import os
4
4
  from datetime import datetime
5
- from typing import Dict, List, Tuple, Union
5
+ from typing import Dict, List, Optional, Tuple, Union
6
6
 
7
7
  import meds_reader
8
8
  import numpy as np
@@ -10,7 +10,11 @@ import pandas as pd
10
10
  from datasets import Dataset, DatasetDict, Split
11
11
  from transformers.utils import logging
12
12
 
13
- from cehrbert.data_generators.hf_data_generator import DEFAULT_INPATIENT_CONCEPT_ID, UNKNOWN_VALUE
13
+ from cehrbert.data_generators.hf_data_generator import (
14
+ DEFAULT_ED_CONCEPT_ID,
15
+ DEFAULT_INPATIENT_CONCEPT_ID,
16
+ UNKNOWN_VALUE,
17
+ )
14
18
  from cehrbert.data_generators.hf_data_generator.hf_dataset import apply_cehrbert_dataset_mapping
15
19
  from cehrbert.data_generators.hf_data_generator.hf_dataset_mapping import MedToCehrBertDatasetMapping
16
20
  from cehrbert.data_generators.hf_data_generator.meds_to_cehrbert_conversion_rules import MedsToCehrBertConversion
@@ -41,8 +45,11 @@ def get_meds_to_cehrbert_conversion_cls(
41
45
 
42
46
 
43
47
  def get_subject_split(meds_reader_db_path: str) -> Dict[str, List[int]]:
44
- patient_split = pd.read_parquet(os.path.join(meds_reader_db_path, "metadata/subject_splits.parquet"))
45
- result = {str(group): records["subject_id"].tolist() for group, records in patient_split.groupby("split")}
48
+ subject_split = pd.read_parquet(os.path.join(meds_reader_db_path, "metadata/subject_splits.parquet"))
49
+ with meds_reader.SubjectDatabase(meds_reader_db_path) as patient_database:
50
+ subject_ids = [p for p in patient_database]
51
+ subject_split = subject_split[subject_split.subject_id.isin(subject_ids)]
52
+ result = {str(group): records["subject_id"].tolist() for group, records in subject_split.groupby("split")}
46
53
  return result
47
54
 
48
55
 
@@ -118,7 +125,9 @@ def convert_one_patient(
118
125
  )
119
126
  """
120
127
  demographics, patient_blocks = generate_demographics_and_patient_blocks(
121
- conversion=conversion, patient=patient, prediction_time=prediction_time
128
+ conversion=conversion,
129
+ patient=patient,
130
+ prediction_time=prediction_time,
122
131
  )
123
132
 
124
133
  patient_block_dict = collections.defaultdict(list)
@@ -129,10 +138,10 @@ def convert_one_patient(
129
138
  for visit_id, blocks in patient_block_dict.items():
130
139
  visit_type = blocks[0].visit_type
131
140
  visit_start_datetime = min([b.min_time for b in blocks])
132
- visit_end_datetime = max([b.max_time for b in blocks])
141
+ visit_end_datetime = max([b.get_visit_end_datetime() for b in blocks])
133
142
  discharge_facility = (
134
143
  next(filter(None, [b.get_discharge_facility() for b in blocks]), None)
135
- if visit_type == DEFAULT_INPATIENT_CONCEPT_ID
144
+ if visit_type in [DEFAULT_INPATIENT_CONCEPT_ID, DEFAULT_ED_CONCEPT_ID]
136
145
  else None
137
146
  )
138
147
  visit_events = list()
@@ -186,6 +195,7 @@ def create_dataset_from_meds_reader(
186
195
  LOG.info("The inpatient_att_function_type: %s", data_args.inpatient_att_function_type)
187
196
  LOG.info("The include_auxiliary_token: %s", data_args.include_auxiliary_token)
188
197
  LOG.info("The include_demographic_prompt: %s", data_args.include_demographic_prompt)
198
+ LOG.info("The meds_exclude_tables: %s", "\n".join(data_args.meds_exclude_tables))
189
199
 
190
200
  train_dataset = _create_cehrbert_data_from_meds(
191
201
  data_args=data_args,
@@ -214,9 +224,10 @@ def _meds_to_cehrbert_generator(
214
224
  path_to_db: str,
215
225
  default_visit_id: int,
216
226
  meds_to_cehrbert_conversion_type: MedsToCehrBertConversionType,
227
+ meds_exclude_tables: Optional[List[str]] = None,
217
228
  ) -> CehrBertPatient:
218
229
  conversion = get_meds_to_cehrbert_conversion_cls(
219
- meds_to_cehrbert_conversion_type, default_visit_id=default_visit_id
230
+ meds_to_cehrbert_conversion_type, default_visit_id=default_visit_id, meds_exclude_tables=meds_exclude_tables
220
231
  )
221
232
  with meds_reader.SubjectDatabase(path_to_db) as patient_database:
222
233
  for shard in shards:
@@ -65,7 +65,7 @@ class PatientBlock:
65
65
  Attributes are initialized to store visit metadata and calculate admission/discharge statuses.
66
66
  """
67
67
  self.visit_id = visit_id
68
- self.events = events
68
+ self.events = sorted(events, key=lambda e: [e.time, e.code])
69
69
  self.min_time = events[0].time
70
70
  self.max_time = events[-1].time
71
71
  self.conversion = conversion
@@ -73,7 +73,8 @@ class PatientBlock:
73
73
  # Cache these variables so we don't need to compute
74
74
  self.has_ed_admission = self._has_ed_admission()
75
75
  self.has_admission = self._has_admission()
76
- self.has_discharge = self._has_discharge()
76
+ self.discharged_to = self.get_discharge_facility()
77
+ self.has_discharge = self.discharged_to is not None
77
78
 
78
79
  # Infer the visit_type from the events
79
80
  # Admission takes precedence over ED
@@ -82,7 +83,14 @@ class PatientBlock:
82
83
  elif self.has_ed_admission:
83
84
  self.visit_type = DEFAULT_ED_CONCEPT_ID
84
85
  else:
85
- self.visit_type = DEFAULT_OUTPATIENT_CONCEPT_ID
86
+ self.visit_type = self._infer_visit_type()
87
+
88
+ def _infer_visit_type(self) -> str:
89
+ for event in self.events:
90
+ for matching_rule in self.conversion.get_other_visit_matching_rules():
91
+ if re.match(matching_rule, event.code):
92
+ return event.code
93
+ return DEFAULT_OUTPATIENT_CONCEPT_ID
86
94
 
87
95
  def _has_ed_admission(self) -> bool:
88
96
  """
@@ -110,7 +118,7 @@ class PatientBlock:
110
118
  return True
111
119
  return False
112
120
 
113
- def _has_discharge(self) -> bool:
121
+ def get_discharge_facility(self) -> Optional[str]:
114
122
  """
115
123
  Determines if the visit includes a discharge event.
116
124
 
@@ -120,23 +128,7 @@ class PatientBlock:
120
128
  for event in self.events:
121
129
  for matching_rule in self.conversion.get_discharge_matching_rules():
122
130
  if re.match(matching_rule, event.code):
123
- return True
124
- return False
125
-
126
- def get_discharge_facility(self) -> Optional[str]:
127
- """
128
- Extracts the discharge facility code from the discharge event, if present.
129
-
130
- Returns:
131
- Optional[str]: The sanitized discharge facility code, or None if no discharge event is found.
132
- """
133
- if self._has_discharge():
134
- for event in self.events:
135
- for matching_rule in self.conversion.get_discharge_matching_rules():
136
- if matching_rule in event.code:
137
- discharge_facility = event.code.replace(matching_rule, "")
138
- discharge_facility = re.sub(r"[^a-zA-Z]", "_", discharge_facility)
139
- return discharge_facility
131
+ return event.code
140
132
  return None
141
133
 
142
134
  def _convert_event(self, event) -> List[Event]:
@@ -187,6 +179,12 @@ class PatientBlock:
187
179
  )
188
180
  ]
189
181
 
182
+ def get_visit_end_datetime(self) -> datetime:
183
+ for e in self.events:
184
+ if hasattr(e, "end"):
185
+ return getattr(e, "end")
186
+ return self.max_time
187
+
190
188
  def get_meds_events(self) -> Iterable[Event]:
191
189
  """
192
190
  Retrieves all medication events for the visit, converting each raw event if necessary.
@@ -196,6 +194,13 @@ class PatientBlock:
196
194
  """
197
195
  events = []
198
196
  for e in self.events:
197
+ if self.conversion.meds_exclude_tables:
198
+ table = getattr(e, "table", None)
199
+ if table and (table in self.conversion.meds_exclude_tables):
200
+ continue
201
+ # We only convert the events that are not visit type and discharge facility events
202
+ if (e.code == self.visit_type) or (self.discharged_to is not None and e.code == self.discharged_to):
203
+ continue
199
204
  events.extend(self._convert_event(e))
200
205
  return events
201
206
 
@@ -259,7 +264,7 @@ def omop_meds_generate_demographics_and_patient_blocks(
259
264
  if patient_block.min_time.date() <= current_date <= patient_block.max_time.date():
260
265
  patient_block.events.extend(unlinked_event_mapping.pop(current_date_str, []))
261
266
  # Need to sort the events if we insert new events to the patient block
262
- patient_block.events = sorted(patient_block.events, key=lambda _: _.time)
267
+ patient_block.events = sorted(patient_block.events, key=lambda _: [_.time, _.code])
263
268
  break
264
269
 
265
270
  max_visit_id = max(patient_block_mapping.keys()) + 1 if len(patient_block_mapping) > 0 else 1
@@ -354,6 +354,36 @@ class CehrBertForClassification(CehrBertPreTrainedModel):
354
354
  # Initialize weights and apply final processing
355
355
  self.post_init()
356
356
 
357
+ def _apply_age_norm(
358
+ self,
359
+ age_at_index: torch.FloatTensor,
360
+ ) -> torch.FloatTensor:
361
+ """
362
+ Applies batch normalization to the input age tensor.
363
+
364
+ If the batch contains more than one example,
365
+ standard batch normalization is applied. If the batch size is 1, batch normalization is applied
366
+ without updating the running statistics, ensuring that the normalization uses the stored running
367
+ mean and variance without modification.
368
+
369
+ Args:
370
+ age_at_index (torch.FloatTensor): A tensor containing the age values to normalize.
371
+ The tensor has shape `(batch_size, num_features)` where `batch_size` is the number of samples in the batch.
372
+
373
+ Returns:
374
+ torch.FloatTensor: A tensor with the normalized age values.
375
+ """
376
+ if age_at_index.shape[0] > 1:
377
+ normalized_age = self.age_batch_norm(age_at_index)
378
+ else:
379
+ self.age_batch_norm.eval()
380
+ # Apply batch norm without updating running stats
381
+ with torch.no_grad(): # Prevent tracking gradients, since we don't want to update anything
382
+ normalized_age = self.age_batch_norm(age_at_index)
383
+ # Optionally, set the layer back to training mode if needed later
384
+ self.age_batch_norm.train()
385
+ return normalized_age
386
+
357
387
  def forward(
358
388
  self,
359
389
  input_ids: torch.LongTensor,
@@ -369,7 +399,8 @@ class CehrBertForClassification(CehrBertPreTrainedModel):
369
399
  output_hidden_states: Optional[bool] = None,
370
400
  classifier_label: Optional[torch.FloatTensor] = None,
371
401
  ) -> CehrBertSequenceClassifierOutput:
372
- normalized_age = self.age_batch_norm(age_at_index)
402
+
403
+ normalized_age = self._apply_age_norm(age_at_index)
373
404
 
374
405
  cehrbert_output = self.bert(
375
406
  input_ids,
@@ -430,6 +461,36 @@ class CehrBertLstmForClassification(CehrBertPreTrainedModel):
430
461
  # Initialize weights and apply final processing
431
462
  self.post_init()
432
463
 
464
+ def _apply_age_norm(
465
+ self,
466
+ age_at_index: torch.FloatTensor,
467
+ ) -> torch.FloatTensor:
468
+ """
469
+ Applies batch normalization to the input age tensor.
470
+
471
+ If the batch contains more than one example,
472
+ standard batch normalization is applied. If the batch size is 1, batch normalization is applied
473
+ without updating the running statistics, ensuring that the normalization uses the stored running
474
+ mean and variance without modification.
475
+
476
+ Args:
477
+ age_at_index (torch.FloatTensor): A tensor containing the age values to normalize.
478
+ The tensor has shape `(batch_size, num_features)` where `batch_size` is the number of samples in the batch.
479
+
480
+ Returns:
481
+ torch.FloatTensor: A tensor with the normalized age values.
482
+ """
483
+ if age_at_index.shape[0] > 1:
484
+ normalized_age = self.age_batch_norm(age_at_index)
485
+ else:
486
+ self.age_batch_norm.eval()
487
+ # Apply batch norm without updating running stats
488
+ with torch.no_grad(): # Prevent tracking gradients, since we don't want to update anything
489
+ normalized_age = self.age_batch_norm(age_at_index)
490
+ # Optionally, set the layer back to training mode if needed later
491
+ self.age_batch_norm.train()
492
+ return normalized_age
493
+
433
494
  def forward(
434
495
  self,
435
496
  input_ids: torch.LongTensor,
@@ -445,7 +506,7 @@ class CehrBertLstmForClassification(CehrBertPreTrainedModel):
445
506
  output_hidden_states: Optional[bool] = None,
446
507
  classifier_label: Optional[torch.FloatTensor] = None,
447
508
  ) -> CehrBertSequenceClassifierOutput:
448
- normalized_age = self.age_batch_norm(age_at_index)
509
+ normalized_age = self._apply_age_norm(age_at_index)
449
510
 
450
511
  cehrbert_output = self.bert(
451
512
  input_ids,
@@ -110,6 +110,10 @@ class DataTrainingArguments:
110
110
  "choices": f"choices={[e.value for e in AttType]}",
111
111
  },
112
112
  )
113
+ meds_exclude_tables: Optional[List[str]] = dataclasses.field(
114
+ default_factory=list,
115
+ metadata={"help": "The tables to exclude in the conversion e.g. measurement"},
116
+ )
113
117
  # TODO: Python 3.9/10 do not support dynamic unpacking, we have to manually provide the entire
114
118
  # list right now.
115
119
  meds_to_cehrbert_conversion_type: Literal[
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: cehrbert
3
- Version: 1.2.2
3
+ Version: 1.2.4
4
4
  Summary: CEHR-BERT: Incorporating temporal information from structured EHR data to improve prediction tasks
5
5
  Author-email: Chao Pang <chaopang229@gmail.com>, Xinzhuo Jiang <xj2193@cumc.columbia.edu>, Krishna Kalluri <kk3326@cumc.columbia.edu>, Nishanth Parameshwar Pavinkurve <np2689@cumc.columbia.edu>, Karthik Natarajan <kn2174@cumc.columbia.edu>
6
6
  License: MIT License
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes