cehrbert 1.2.1__tar.gz → 1.2.2__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 (125) hide show
  1. {cehrbert-1.2.1 → cehrbert-1.2.2}/PKG-INFO +2 -2
  2. {cehrbert-1.2.1 → cehrbert-1.2.2}/pyproject.toml +1 -1
  3. cehrbert-1.2.2/src/cehrbert/data_generators/hf_data_generator/__init__.py +4 -0
  4. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/data_generators/hf_data_generator/hf_dataset.py +19 -0
  5. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/data_generators/hf_data_generator/hf_dataset_mapping.py +2 -1
  6. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/data_generators/hf_data_generator/meds_to_cehrbert_conversion_rules/__init__.py +1 -0
  7. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/data_generators/hf_data_generator/meds_to_cehrbert_conversion_rules/meds_to_cehrbert_base.py +1 -1
  8. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/data_generators/hf_data_generator/meds_to_cehrbert_conversion_rules/meds_to_cehrbert_micmic4.py +4 -0
  9. cehrbert-1.2.2/src/cehrbert/data_generators/hf_data_generator/meds_to_cehrbert_conversion_rules/meds_to_cehrbert_omop.py +44 -0
  10. cehrbert-1.2.2/src/cehrbert/data_generators/hf_data_generator/meds_utils.py +277 -0
  11. cehrbert-1.2.1/src/cehrbert/data_generators/hf_data_generator/meds_utils.py → cehrbert-1.2.2/src/cehrbert/data_generators/hf_data_generator/patient_block.py +108 -194
  12. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/runners/hf_cehrbert_pretrain_runner.py +17 -0
  13. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/runners/hf_runner_argument_dataclass.py +10 -8
  14. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/runners/runner_util.py +7 -4
  15. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert.egg-info/PKG-INFO +2 -2
  16. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert.egg-info/SOURCES.txt +3 -0
  17. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert.egg-info/requires.txt +1 -1
  18. {cehrbert-1.2.1 → cehrbert-1.2.2}/tests/unit_tests/data_generators/hf_data_generator/meds_utils_test.py +11 -3
  19. cehrbert-1.2.2/tests/unit_tests/data_generators/hf_data_generator/omop_meds_generate_demographics_and_patient_blocks_test.py +97 -0
  20. cehrbert-1.2.1/tests/unit_tests/utils/__init__.py +0 -0
  21. {cehrbert-1.2.1 → cehrbert-1.2.2}/.github/workflows/python-build.yml +0 -0
  22. {cehrbert-1.2.1 → cehrbert-1.2.2}/.github/workflows/tests.yml +0 -0
  23. {cehrbert-1.2.1 → cehrbert-1.2.2}/.gitignore +0 -0
  24. {cehrbert-1.2.1 → cehrbert-1.2.2}/.pre-commit-config.yaml +0 -0
  25. {cehrbert-1.2.1 → cehrbert-1.2.2}/LICENSE +0 -0
  26. {cehrbert-1.2.1 → cehrbert-1.2.2}/README.md +0 -0
  27. {cehrbert-1.2.1 → cehrbert-1.2.2}/db_properties.ini +0 -0
  28. {cehrbert-1.2.1 → cehrbert-1.2.2}/deepspeed_configs/zero1.json +0 -0
  29. {cehrbert-1.2.1 → cehrbert-1.2.2}/deepspeed_configs/zero2.json +0 -0
  30. {cehrbert-1.2.1 → cehrbert-1.2.2}/deepspeed_configs/zero3.json +0 -0
  31. {cehrbert-1.2.1 → cehrbert-1.2.2}/full_grid_search_config.ini +0 -0
  32. {cehrbert-1.2.1 → cehrbert-1.2.2}/images/cehr_bert_architecture.png +0 -0
  33. {cehrbert-1.2.1 → cehrbert-1.2.2}/images/tokenization_att_generation.png +0 -0
  34. {cehrbert-1.2.1 → cehrbert-1.2.2}/sample_configs/hf_cehrbert_finetuning_runner_config.yaml +0 -0
  35. {cehrbert-1.2.1 → cehrbert-1.2.2}/sample_configs/hf_cehrbert_pretrain_runner_config.yaml +0 -0
  36. {cehrbert-1.2.1 → cehrbert-1.2.2}/sample_configs/hf_cehrbert_pretrain_runner_meds_config.yaml +0 -0
  37. {cehrbert-1.2.1 → cehrbert-1.2.2}/sample_data/finetune/full/fake_data.parquet +0 -0
  38. {cehrbert-1.2.1 → cehrbert-1.2.2}/sample_data/finetune/test/fake_data.parquet +0 -0
  39. {cehrbert-1.2.1 → cehrbert-1.2.2}/sample_data/finetune/train/fake_data.parquet +0 -0
  40. {cehrbert-1.2.1 → cehrbert-1.2.2}/sample_data/pretrain/patient_sequence.parquet +0 -0
  41. {cehrbert-1.2.1 → cehrbert-1.2.2}/setup.cfg +0 -0
  42. {cehrbert-1.2.1 → cehrbert-1.2.2}/simple_grid_search_config.ini +0 -0
  43. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/__init__.py +0 -0
  44. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/config/__init__.py +0 -0
  45. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/config/grid_search_config.py +0 -0
  46. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/data_generators/__init__.py +0 -0
  47. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/data_generators/data_classes.py +0 -0
  48. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/data_generators/data_generator_base.py +0 -0
  49. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/data_generators/graph_sample_method.py +0 -0
  50. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/data_generators/hf_data_generator/hf_dataset_collator.py +0 -0
  51. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/data_generators/learning_objective.py +0 -0
  52. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/data_generators/tokenizer.py +0 -0
  53. {cehrbert-1.2.1/src/cehrbert/data_generators/hf_data_generator → cehrbert-1.2.2/src/cehrbert/evaluations}/__init__.py +0 -0
  54. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/evaluations/evaluation.py +0 -0
  55. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/evaluations/evaluation_parameters.py +0 -0
  56. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/evaluations/evaluation_parse_args.py +0 -0
  57. {cehrbert-1.2.1/src/cehrbert/evaluations → cehrbert-1.2.2/src/cehrbert/evaluations/model_evaluators}/__init__.py +0 -0
  58. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/evaluations/model_evaluators/bert_model_evaluators.py +0 -0
  59. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/evaluations/model_evaluators/frequency_model_evaluators.py +0 -0
  60. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/evaluations/model_evaluators/hierarchical_bert_evaluators.py +0 -0
  61. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/evaluations/model_evaluators/model_evaluators.py +0 -0
  62. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/evaluations/model_evaluators/sequence_model_evaluators.py +0 -0
  63. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/evaluations/transfer_learning_evaluation.py +0 -0
  64. {cehrbert-1.2.1/src/cehrbert/evaluations/model_evaluators → cehrbert-1.2.2/src/cehrbert/keras_transformer}/__init__.py +0 -0
  65. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/keras_transformer/bert.py +0 -0
  66. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/keras_transformer/extras.py +0 -0
  67. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/keras_transformer/position.py +0 -0
  68. {cehrbert-1.2.1/src/cehrbert/keras_transformer → cehrbert-1.2.2/src/cehrbert/med_extension}/__init__.py +0 -0
  69. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/med_extension/schema_extension.py +0 -0
  70. {cehrbert-1.2.1/src/cehrbert/med_extension → cehrbert-1.2.2/src/cehrbert/models}/__init__.py +0 -0
  71. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/models/bert_models.py +0 -0
  72. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/models/bert_models_visit_prediction.py +0 -0
  73. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/models/evaluation_models.py +0 -0
  74. {cehrbert-1.2.1/src/cehrbert/models → cehrbert-1.2.2/src/cehrbert/models/hf_models}/__init__.py +0 -0
  75. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/models/hf_models/config.py +0 -0
  76. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/models/hf_models/hf_cehrbert.py +0 -0
  77. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/models/hf_models/hf_modeling_outputs.py +0 -0
  78. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/models/hf_models/tokenization_hf_cehrbert.py +0 -0
  79. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/models/hf_models/tokenization_utils.py +0 -0
  80. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/models/hierachical_bert_model_v2.py +0 -0
  81. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/models/hierachical_phenotype_model_new.py +0 -0
  82. {cehrbert-1.2.1/src/cehrbert/models/hf_models → cehrbert-1.2.2/src/cehrbert/models/layers}/__init__.py +0 -0
  83. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/models/layers/custom_layers.py +0 -0
  84. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/models/layers/hierarchical_custom_layers.py +0 -0
  85. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/models/loss_schedulers.py +0 -0
  86. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/models/parse_args.py +0 -0
  87. {cehrbert-1.2.1/src/cehrbert/models/layers → cehrbert-1.2.2/src/cehrbert/runners}/__init__.py +0 -0
  88. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/runners/hf_cehrbert_finetune_runner.py +0 -0
  89. {cehrbert-1.2.1/src/cehrbert/runners → cehrbert-1.2.2/src/cehrbert/tools}/__init__.py +0 -0
  90. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/tools/download_omop_tables.py +0 -0
  91. {cehrbert-1.2.1/src/cehrbert/tools → cehrbert-1.2.2/src/cehrbert/trainers}/__init__.py +0 -0
  92. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/trainers/model_trainer.py +0 -0
  93. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/trainers/train_cehr_bert.py +0 -0
  94. {cehrbert-1.2.1/src/cehrbert/trainers → cehrbert-1.2.2/src/cehrbert/utils}/__init__.py +0 -0
  95. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/utils/checkpoint_utils.py +0 -0
  96. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/utils/logging_utils.py +0 -0
  97. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/utils/model_utils.py +0 -0
  98. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert/utils/stat_utils.py +0 -0
  99. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert.egg-info/dependency_links.txt +0 -0
  100. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert.egg-info/entry_points.txt +0 -0
  101. {cehrbert-1.2.1 → cehrbert-1.2.2}/src/cehrbert.egg-info/top_level.txt +0 -0
  102. {cehrbert-1.2.1/src/cehrbert/utils → cehrbert-1.2.2/tests}/__init__.py +0 -0
  103. {cehrbert-1.2.1/tests → cehrbert-1.2.2/tests/integration_tests}/__init__.py +0 -0
  104. {cehrbert-1.2.1/tests/integration_tests → cehrbert-1.2.2/tests/integration_tests/runners}/__init__.py +0 -0
  105. {cehrbert-1.2.1 → cehrbert-1.2.2}/tests/integration_tests/runners/hf_cehrbert_pretrain_runner_test.py +0 -0
  106. {cehrbert-1.2.1/tests/integration_tests/runners → cehrbert-1.2.2/tests/integration_tests/trainers}/__init__.py +0 -0
  107. {cehrbert-1.2.1 → cehrbert-1.2.2}/tests/integration_tests/trainers/train_cehr_bert_test.py +0 -0
  108. {cehrbert-1.2.1/tests/integration_tests/trainers → cehrbert-1.2.2/tests/unit_tests}/__init__.py +0 -0
  109. {cehrbert-1.2.1/tests/unit_tests → cehrbert-1.2.2/tests/unit_tests/data_generators}/__init__.py +0 -0
  110. {cehrbert-1.2.1 → cehrbert-1.2.2}/tests/unit_tests/data_generators/bert_masked_language_modeling_learning_objective_test.py +0 -0
  111. {cehrbert-1.2.1/tests/unit_tests/data_generators → cehrbert-1.2.2/tests/unit_tests/data_generators/hf_data_generator}/__init__.py +0 -0
  112. {cehrbert-1.2.1 → cehrbert-1.2.2}/tests/unit_tests/data_generators/hf_data_generator/hf_generate_start_end_index_mapping_test.py +0 -0
  113. {cehrbert-1.2.1 → cehrbert-1.2.2}/tests/unit_tests/data_generators/hf_data_generator/hf_masked_language_modeling_mapping_test.py +0 -0
  114. {cehrbert-1.2.1 → cehrbert-1.2.2}/tests/unit_tests/data_generators/hf_data_generator/hf_med_to_cehrbert_mapping_test.py +0 -0
  115. {cehrbert-1.2.1 → cehrbert-1.2.2}/tests/unit_tests/data_generators/hf_data_generator/hf_sort_patient_sequence_dataset_mapping_test.py +0 -0
  116. {cehrbert-1.2.1 → cehrbert-1.2.2}/tests/unit_tests/data_generators/visit_prediction_learning_objective_test.py +0 -0
  117. {cehrbert-1.2.1/tests/unit_tests/data_generators/hf_data_generator → cehrbert-1.2.2/tests/unit_tests/models}/__init__.py +0 -0
  118. {cehrbert-1.2.1 → cehrbert-1.2.2}/tests/unit_tests/models/concept_value_decoder_layer_test.py +0 -0
  119. {cehrbert-1.2.1/tests/unit_tests/models → cehrbert-1.2.2/tests/unit_tests/models/hf_models}/__init__.py +0 -0
  120. {cehrbert-1.2.1 → cehrbert-1.2.2}/tests/unit_tests/models/hf_models/hf_cehrbert_test.py +0 -0
  121. {cehrbert-1.2.1 → cehrbert-1.2.2}/tests/unit_tests/models/hf_models/numeric_concept_statistics_test.py +0 -0
  122. {cehrbert-1.2.1 → cehrbert-1.2.2}/tests/unit_tests/models/hf_models/tokenization_hf_cehrbert_test.py +0 -0
  123. {cehrbert-1.2.1/tests/unit_tests/models/hf_models → cehrbert-1.2.2/tests/unit_tests/utils}/__init__.py +0 -0
  124. {cehrbert-1.2.1 → cehrbert-1.2.2}/tests/unit_tests/utils/truncated_offline_statistics_test.py +0 -0
  125. {cehrbert-1.2.1 → cehrbert-1.2.2}/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.1
3
+ Version: 1.2.2
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
@@ -45,7 +45,7 @@ Requires-Dist: accelerate==0.31.0
45
45
  Requires-Dist: Werkzeug==3.0.1
46
46
  Requires-Dist: wandb==0.17.8
47
47
  Requires-Dist: xgboost==2.0.3
48
- Requires-Dist: cehrbert_data==0.0.3
48
+ Requires-Dist: cehrbert_data==0.0.4
49
49
  Provides-Extra: dev
50
50
  Requires-Dist: pre-commit; extra == "dev"
51
51
  Requires-Dist: pytest; extra == "dev"
@@ -58,7 +58,7 @@ dependencies = [
58
58
  "Werkzeug==3.0.1",
59
59
  "wandb==0.17.8",
60
60
  "xgboost==2.0.3",
61
- "cehrbert_data==0.0.3"
61
+ "cehrbert_data==0.0.4"
62
62
  ]
63
63
 
64
64
  [tool.setuptools_scm]
@@ -0,0 +1,4 @@
1
+ UNKNOWN_VALUE = "Unknown"
2
+ DEFAULT_ED_CONCEPT_ID = "Visit/ER"
3
+ DEFAULT_OUTPATIENT_CONCEPT_ID = "Visit/OP"
4
+ DEFAULT_INPATIENT_CONCEPT_ID = "Visit/IP"
@@ -21,6 +21,8 @@ CEHRBERT_COLUMNS = [
21
21
  "concept_values",
22
22
  "concept_value_masks",
23
23
  "mlm_skip_values",
24
+ "num_of_concepts",
25
+ "num_of_visits",
24
26
  ]
25
27
 
26
28
  TRANSFORMER_COLUMNS = ["input_ids", "labels"]
@@ -34,6 +36,15 @@ def create_cehrbert_pretraining_dataset(
34
36
  data_args: DataTrainingArguments,
35
37
  ) -> Dataset:
36
38
  required_columns = TRANSFORMER_COLUMNS + CEHRBERT_COLUMNS
39
+
40
+ # Remove patients without any records
41
+ dataset = dataset.filter(
42
+ lambda batch: [num_of_concepts > 0 for num_of_concepts in batch["num_of_concepts"]],
43
+ num_proc=data_args.preprocessing_num_workers if not data_args.streaming else None,
44
+ batched=True,
45
+ batch_size=data_args.preprocessing_batch_size,
46
+ )
47
+
37
48
  # If the data is already in meds, we don't need to sort the sequence anymore
38
49
  if data_args.is_data_in_med:
39
50
  mapping_functions = [HFTokenizationMapping(concept_tokenizer, True)]
@@ -70,6 +81,14 @@ def create_cehrbert_finetuning_dataset(
70
81
  ) -> Dataset:
71
82
  required_columns = TRANSFORMER_COLUMNS + CEHRBERT_COLUMNS + FINETUNING_COLUMNS
72
83
 
84
+ # Remove patients without any records
85
+ dataset = dataset.filter(
86
+ lambda batch: [num_of_concepts > 0 for num_of_concepts in batch["num_of_concepts"]],
87
+ num_proc=data_args.preprocessing_num_workers if not data_args.streaming else None,
88
+ batched=True,
89
+ batch_size=data_args.preprocessing_batch_size,
90
+ )
91
+
73
92
  if data_args.is_data_in_med:
74
93
  mapping_functions = [
75
94
  HFFineTuningMapping(),
@@ -278,7 +278,8 @@ class MedToCehrBertDatasetMapping(DatasetMapping):
278
278
 
279
279
  # If numeric_value exists, this is a concept/value tuple, we indicate this using a concept_value_mask
280
280
  numeric_value = e.get("numeric_value", None)
281
- unit = e.get("unit", NA)
281
+ # The unit might be populated with a None value
282
+ unit = e.get("unit", NA) if e.get("unit", NA) else NA
282
283
  concept_value_mask = int(numeric_value is not None)
283
284
  concept_value = numeric_value if concept_value_mask == 1 else -1.0
284
285
  code = replace_escape_chars(e["code"])
@@ -1,2 +1,3 @@
1
1
  from .meds_to_cehrbert_base import MedsToCehrBertConversion
2
2
  from .meds_to_cehrbert_micmic4 import MedsToBertMimic4
3
+ from .meds_to_cehrbert_omop import MedsToCehrbertOMOP
@@ -57,7 +57,7 @@ class MedsToCehrBertConversion(ABC):
57
57
  or None if no rule exists.
58
58
  """
59
59
 
60
- def __init__(self):
60
+ def __init__(self, **kwargs):
61
61
  """
62
62
  Initializes the MedsToCehrBertConversion class by caching the matching rules and.
63
63
 
@@ -9,6 +9,10 @@ from cehrbert.data_generators.hf_data_generator.meds_to_cehrbert_conversion_rule
9
9
 
10
10
  class MedsToBertMimic4(MedsToCehrBertConversion):
11
11
 
12
+ def __init__(self, default_visit_id, **kwargs):
13
+ super().__init__(**kwargs)
14
+ self.default_visit_id = default_visit_id
15
+
12
16
  def _create_ed_admission_matching_rules(self) -> List[str]:
13
17
  return ["ED_REGISTRATION//", "TRANSFER_TO//ED"]
14
18
 
@@ -0,0 +1,44 @@
1
+ from typing import List
2
+
3
+ from cehrbert.data_generators.hf_data_generator.meds_to_cehrbert_conversion_rules.meds_to_cehrbert_base import (
4
+ EventConversionRule,
5
+ MedsToCehrBertConversion,
6
+ )
7
+
8
+
9
+ class MedsToCehrbertOMOP(MedsToCehrBertConversion):
10
+
11
+ def _create_ed_admission_matching_rules(self) -> List[str]:
12
+ return ["Visit/ER"]
13
+
14
+ def _create_admission_matching_rules(self) -> List[str]:
15
+ return ["Visit/IP", "Visit/ERIP", "CMS Place of Service/51", "CMS Place of Service/61"]
16
+
17
+ def _create_discharge_matching_rules(self) -> List[str]:
18
+ return [
19
+ "PCORNet/Generic-NI",
20
+ "CMS Place of Service/12",
21
+ "SNOMED/371827001",
22
+ "CMS Place of Service/21",
23
+ "NUCC/261Q00000X",
24
+ "CMS Place of Service/31",
25
+ "SNOMED/397709008",
26
+ "Medicare Specialty/A4",
27
+ "SNOMED/225928004",
28
+ "CMS Place of Service/34",
29
+ "CMS Place of Service/61",
30
+ "CMS Place of Service/51",
31
+ "CMS Place of Service/23",
32
+ "PCORNet/Generic-OT",
33
+ "CMS Place of Service/27",
34
+ "CMS Place of Service/24",
35
+ "CMS Place of Service/09",
36
+ "CMS Place of Service/33",
37
+ "SNOMED/34596002",
38
+ "CMS Place of Service/25",
39
+ "CMS Place of Service/32",
40
+ "CMS Place of Service/20",
41
+ ]
42
+
43
+ def _create_text_event_to_numeric_event_rules(self) -> List[EventConversionRule]:
44
+ return []
@@ -0,0 +1,277 @@
1
+ import collections
2
+ import functools
3
+ import os
4
+ from datetime import datetime
5
+ from typing import Dict, List, Tuple, Union
6
+
7
+ import meds_reader
8
+ import numpy as np
9
+ import pandas as pd
10
+ from datasets import Dataset, DatasetDict, Split
11
+ from transformers.utils import logging
12
+
13
+ from cehrbert.data_generators.hf_data_generator import DEFAULT_INPATIENT_CONCEPT_ID, UNKNOWN_VALUE
14
+ from cehrbert.data_generators.hf_data_generator.hf_dataset import apply_cehrbert_dataset_mapping
15
+ from cehrbert.data_generators.hf_data_generator.hf_dataset_mapping import MedToCehrBertDatasetMapping
16
+ from cehrbert.data_generators.hf_data_generator.meds_to_cehrbert_conversion_rules import MedsToCehrBertConversion
17
+ from cehrbert.data_generators.hf_data_generator.patient_block import generate_demographics_and_patient_blocks
18
+ from cehrbert.med_extension.schema_extension import CehrBertPatient, Visit
19
+ from cehrbert.runners.hf_runner_argument_dataclass import DataTrainingArguments, MedsToCehrBertConversionType
20
+
21
+ MEDS_SPLIT_DATA_SPLIT_MAPPING = {
22
+ "train": Split.TRAIN,
23
+ "tuning": Split.VALIDATION,
24
+ "held_out": Split.TEST,
25
+ }
26
+ NON_ALPHANUMERIC_CHARS = r"[\w\/\\:\-_]"
27
+ LOG = logging.get_logger("transformers")
28
+
29
+
30
+ def get_meds_to_cehrbert_conversion_cls(
31
+ meds_to_cehrbert_conversion_type: Union[MedsToCehrBertConversionType, str], **kwargs
32
+ ) -> MedsToCehrBertConversion:
33
+ for cls in MedsToCehrBertConversion.__subclasses__():
34
+ if isinstance(meds_to_cehrbert_conversion_type, MedsToCehrBertConversionType):
35
+ if meds_to_cehrbert_conversion_type.name == cls.__name__:
36
+ return cls(**kwargs)
37
+ elif isinstance(meds_to_cehrbert_conversion_type, str):
38
+ if meds_to_cehrbert_conversion_type == cls.__name__:
39
+ return cls(**kwargs)
40
+ raise RuntimeError(f"{meds_to_cehrbert_conversion_type} is not a valid MedsToCehrBertConversionType")
41
+
42
+
43
+ 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")}
46
+ return result
47
+
48
+
49
+ def convert_one_patient(
50
+ patient: meds_reader.Subject,
51
+ conversion: MedsToCehrBertConversion,
52
+ prediction_time: datetime = None,
53
+ label: Union[int, float] = None,
54
+ ) -> CehrBertPatient:
55
+ """
56
+ Converts a patient's event data into a CehrBertPatient object, processing.
57
+
58
+ their medical history, visit details, and demographic information.
59
+
60
+ Parameters:
61
+ ----------
62
+ patient : meds_reader.Subject
63
+ The patient's event data, including time-stamped medical events such as
64
+ demographic data (race, gender, ethnicity) and clinical visits (ED admissions,
65
+ hospital admissions, discharges).
66
+
67
+ conversion : MedsToCehrBertConversion
68
+ The conversion object to map and process medical event data into the format
69
+ required by CehrBert.
70
+
71
+ default_visit_id : int, optional (default=1)
72
+ The starting ID for patient visits. This is incremented as new visits are
73
+ identified in the event data.
74
+
75
+ prediction_time : datetime, optional (default=None)
76
+ The cutoff time for processing events. Events occurring after this time are
77
+ ignored.
78
+
79
+ label : Union[int, float], optional (default=None)
80
+ The prediction label associated with this patient, which could represent a
81
+ clinical outcome (e.g., survival or treatment response).
82
+
83
+ Returns:
84
+ -------
85
+ CehrBertPatient
86
+ An object containing the patient's transformed event data, visits, demographics,
87
+ and associated label in a structure compatible with CehrBert's input requirements.
88
+
89
+ Description:
90
+ -----------
91
+ This function processes a patient's medical history, including demographic
92
+ information (birth date, race, gender, and ethnicity) and visit details. It iterates
93
+ through the patient's events and groups them into visits (ED, admission, discharge).
94
+ Visits are formed based on timestamps, and certain logic is applied to merge ED visits
95
+ into hospital admissions if they occur within 24 hours of each other.
96
+
97
+ For each event, demographic attributes like birth date, race, gender, and ethnicity
98
+ are extracted. If the event has a timestamp, it is compared with `prediction_time` to
99
+ filter out events that occurred after the specified time.
100
+
101
+ The function handles ongoing (incomplete) visits and cases where multiple visits
102
+ should be merged (e.g., ED followed by hospital admission within 24 hours). After
103
+ processing the events, visits are built with details such as visit type, start/end
104
+ datetime, and events during the visit.
105
+
106
+ The function returns a `CehrBertPatient` object that includes the patient's medical
107
+ events, structured into visits, along with demographic information, and optionally
108
+ a prediction label.
109
+
110
+ Example Usage:
111
+ -------------
112
+ patient_data = convert_one_patient(
113
+ patient=some_patient_object,
114
+ conversion=some_conversion_object,
115
+ default_visit_id=1,
116
+ prediction_time=datetime.now(),
117
+ label=1
118
+ )
119
+ """
120
+ demographics, patient_blocks = generate_demographics_and_patient_blocks(
121
+ conversion=conversion, patient=patient, prediction_time=prediction_time
122
+ )
123
+
124
+ patient_block_dict = collections.defaultdict(list)
125
+ for patient_block in patient_blocks:
126
+ patient_block_dict[patient_block.visit_id].append(patient_block)
127
+
128
+ visits = list()
129
+ for visit_id, blocks in patient_block_dict.items():
130
+ visit_type = blocks[0].visit_type
131
+ visit_start_datetime = min([b.min_time for b in blocks])
132
+ visit_end_datetime = max([b.max_time for b in blocks])
133
+ discharge_facility = (
134
+ next(filter(None, [b.get_discharge_facility() for b in blocks]), None)
135
+ if visit_type == DEFAULT_INPATIENT_CONCEPT_ID
136
+ else None
137
+ )
138
+ visit_events = list()
139
+ for block in blocks:
140
+ visit_events.extend(block.get_meds_events())
141
+
142
+ visits.append(
143
+ Visit(
144
+ visit_type=visit_type,
145
+ visit_start_datetime=visit_start_datetime,
146
+ visit_end_datetime=visit_end_datetime,
147
+ discharge_facility=(discharge_facility if discharge_facility else UNKNOWN_VALUE),
148
+ events=visit_events,
149
+ )
150
+ )
151
+ age_at_index = -1
152
+ if prediction_time is not None and demographics.birth_datetime is not None:
153
+ age_at_index = prediction_time.year - demographics.birth_datetime.year
154
+ if (prediction_time.month, prediction_time.day) < (
155
+ demographics.birth_datetime.month,
156
+ demographics.birth_datetime.day,
157
+ ):
158
+ age_at_index -= 1
159
+
160
+ # birth_datetime can not be None
161
+ assert (
162
+ demographics.birth_datetime is not None
163
+ ), f"patient_id: {patient.subject_id} does not have a valid birth_datetime"
164
+
165
+ return CehrBertPatient(
166
+ patient_id=patient.subject_id,
167
+ birth_datetime=demographics.birth_datetime,
168
+ visits=visits,
169
+ race=demographics.race if demographics.race else UNKNOWN_VALUE,
170
+ gender=demographics.gender if demographics.gender else UNKNOWN_VALUE,
171
+ ethnicity=demographics.ethnicity if demographics.ethnicity else UNKNOWN_VALUE,
172
+ index_date=prediction_time,
173
+ age_at_index=age_at_index,
174
+ label=label,
175
+ )
176
+
177
+
178
+ def create_dataset_from_meds_reader(
179
+ data_args: DataTrainingArguments,
180
+ default_visit_id: int = 1,
181
+ is_pretraining: bool = True,
182
+ ) -> DatasetDict:
183
+
184
+ LOG.info("The meds_to_cehrbert_conversion_type: %s", data_args.meds_to_cehrbert_conversion_type)
185
+ LOG.info("The att_function_type: %s", data_args.att_function_type)
186
+ LOG.info("The inpatient_att_function_type: %s", data_args.inpatient_att_function_type)
187
+ LOG.info("The include_auxiliary_token: %s", data_args.include_auxiliary_token)
188
+ LOG.info("The include_demographic_prompt: %s", data_args.include_demographic_prompt)
189
+
190
+ train_dataset = _create_cehrbert_data_from_meds(
191
+ data_args=data_args,
192
+ split="train",
193
+ default_visit_id=default_visit_id,
194
+ is_pretraining=is_pretraining,
195
+ )
196
+ tuning_dataset = _create_cehrbert_data_from_meds(
197
+ data_args=data_args,
198
+ split="tuning",
199
+ default_visit_id=default_visit_id,
200
+ is_pretraining=is_pretraining,
201
+ )
202
+ held_out_dataset = _create_cehrbert_data_from_meds(
203
+ data_args=data_args,
204
+ split="held_out",
205
+ default_visit_id=default_visit_id,
206
+ is_pretraining=is_pretraining,
207
+ )
208
+
209
+ return DatasetDict({"train": train_dataset, "validation": tuning_dataset, "test": held_out_dataset})
210
+
211
+
212
+ def _meds_to_cehrbert_generator(
213
+ shards: List[Tuple[np.ndarray, np.ndarray, np.ndarray]],
214
+ path_to_db: str,
215
+ default_visit_id: int,
216
+ meds_to_cehrbert_conversion_type: MedsToCehrBertConversionType,
217
+ ) -> CehrBertPatient:
218
+ conversion = get_meds_to_cehrbert_conversion_cls(
219
+ meds_to_cehrbert_conversion_type, default_visit_id=default_visit_id
220
+ )
221
+ with meds_reader.SubjectDatabase(path_to_db) as patient_database:
222
+ for shard in shards:
223
+ for patient_id, prediction_time, label in shard:
224
+ patient = patient_database[patient_id]
225
+ yield convert_one_patient(patient, conversion, prediction_time, label)
226
+
227
+
228
+ def _create_cehrbert_data_from_meds(
229
+ data_args: DataTrainingArguments,
230
+ split: str,
231
+ default_visit_id: int = 1,
232
+ is_pretraining: bool = True,
233
+ ):
234
+ assert split in ["held_out", "train", "tuning"]
235
+ batches = []
236
+ if data_args.cohort_folder:
237
+ # Load the entire cohort
238
+ cohort = pd.read_parquet(os.path.expanduser(data_args.cohort_folder))
239
+ patient_split = get_subject_split(os.path.expanduser(data_args.data_folder))
240
+ subject_ids = patient_split[split]
241
+ cohort_split = cohort[cohort.subject_id.isin(subject_ids)]
242
+ for cohort_row in cohort_split.itertuples():
243
+ subject_id = cohort_row.subject_id
244
+ prediction_time = cohort_row.prediction_time
245
+ label = int(cohort_row.boolean_value)
246
+ batches.append((subject_id, prediction_time, label))
247
+ else:
248
+ patient_split = get_subject_split(os.path.expanduser(data_args.data_folder))
249
+ for subject_id in patient_split[split]:
250
+ batches.append((subject_id, None, None))
251
+
252
+ split_batches = np.array_split(np.asarray(batches), data_args.preprocessing_num_workers)
253
+ batch_func = functools.partial(
254
+ _meds_to_cehrbert_generator,
255
+ path_to_db=os.path.expanduser(data_args.data_folder),
256
+ default_visit_id=default_visit_id,
257
+ meds_to_cehrbert_conversion_type=data_args.meds_to_cehrbert_conversion_type,
258
+ )
259
+ dataset = Dataset.from_generator(
260
+ batch_func,
261
+ gen_kwargs={
262
+ "shards": split_batches,
263
+ },
264
+ num_proc=(data_args.preprocessing_num_workers if not data_args.streaming else None),
265
+ writer_batch_size=data_args.preprocessing_batch_size,
266
+ streaming=data_args.streaming,
267
+ )
268
+
269
+ # Convert the CehrBertPatient to CehrBert data inputs
270
+ dataset = apply_cehrbert_dataset_mapping(
271
+ dataset,
272
+ MedToCehrBertDatasetMapping(data_args, is_pretraining),
273
+ num_proc=data_args.preprocessing_num_workers,
274
+ batch_size=data_args.preprocessing_batch_size,
275
+ streaming=data_args.streaming,
276
+ )
277
+ return dataset