-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcreate_datasets.py
More file actions
1808 lines (1600 loc) · 80.1 KB
/
create_datasets.py
File metadata and controls
1808 lines (1600 loc) · 80.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import os
import re
from pathlib import Path
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.experimental import enable_iterative_imputer # noqa: F401
from sklearn.impute import IterativeImputer
from sklearn.linear_model import LinearRegression
STUDY_NAME_MAP = {
"study_1": "Thyroid Journal (2016)",
"study_2": "European Journal of Endocrinology (2006)",
"study_3": "Oncotarget (2015) RET S891A FMTC",
"study_4": "Clinics and Practice (2024) RET C634G Kindred",
"study_5": "Endocrinol. Diabetes Metab. Case Reports (2024) RET K666N",
"study_6": "Indian Journal of Cancer (2021) RET S891A Family",
"study_7": "World Journal of Clinical Cases (2024) RET C634Y Family",
"study_8": "Int. J. Pediatr. Endocrinol. (2012) Familial MEN2B Infant",
"study_9": "JCEM (2010) RET S891A MEN2A Spectrum",
"study_10": "Journal of Biosciences (2014) RET S891A Chinese FMTC Family",
}
AMINO_ACID_MAP = {
"ala": "A",
"arg": "R",
"asn": "N",
"asp": "D",
"cys": "C",
"gln": "Q",
"glu": "E",
"gly": "G",
"his": "H",
"ile": "I",
"leu": "L",
"lys": "K",
"met": "M",
"phe": "F",
"pro": "P",
"ser": "S",
"thr": "T",
"trp": "W",
"tyr": "Y",
"val": "V"
}
def amino_acid_to_one(code):
"""convert 3-letter amino acid shorthand into 1-letter"""
if not code:
return ""
cleaned = str(code).strip().lower()
if len(cleaned) == 1:
return cleaned.upper()
return AMINO_ACID_MAP.get(cleaned, cleaned[0].upper())
def normalize_variant_code(variant_text):
"""normalize variant notation such as p.Cys634Tyr into C634Y"""
if not variant_text:
return None
text = str(variant_text).strip()
text = text.replace("p.", "")
text = text.replace("P.", "")
del_match = re.match(r"([A-Za-z]{1,3})(\d+)_([A-Za-z]{1,3})(\d+)(del.*)", text, re.IGNORECASE)
if del_match:
start, pos1, end, pos2, suffix = del_match.groups()
suffix = suffix.lower()
if suffix.startswith("delins"):
ins_part = suffix.replace("delins", "")
ins_part = amino_acid_to_one(ins_part) if ins_part else ""
suffix = f"delins{ins_part}"
return f"{amino_acid_to_one(start)}{pos1}_{amino_acid_to_one(end)}{pos2}{suffix}"
match = re.match(r"([A-Za-z]{1,3})(\d+)([A-Za-z]{1,3})", text)
if match:
start, pos, end = match.groups()
return f"{amino_acid_to_one(start)}{pos}{amino_acid_to_one(end)}"
return text.upper().replace(" ", "")
def parse_ret_variant_string(raw_value):
"""extract a normalized RET variant from free text"""
if not raw_value:
return None
text = str(raw_value).strip()
# remove gene label if present
if " " in text and text.upper().startswith("RET"):
text = text.split(" ", 1)[1]
delins_three_letter = re.search(r"([A-Za-z]{3}\d+_[A-Za-z]{3}\d+del(?:ins[A-Za-z]{3})?)", text)
if delins_three_letter:
return normalize_variant_code(delins_three_letter.group(1))
complex_match = re.search(r"([A-Z]\d+_[A-Z]\d+del(?:ins[A-Z]+)?)", text)
if complex_match:
return complex_match.group(1)
simple_match = re.search(r"([A-Z]\d+[A-Z])", text)
if simple_match:
return simple_match.group(1)
return normalize_variant_code(text)
def parse_age_range(range_text):
"""parse an age range string like '25-77' into numeric bounds"""
if not range_text or "-" not in str(range_text):
return None
parts = str(range_text).replace(" ", "").split("-")
try:
low = float(parts[0])
high = float(parts[1])
if np.isnan(low) or np.isnan(high):
return None
return low, high
except (ValueError, TypeError):
return None
def generate_age_sequence(count, age_stats):
"""generate deterministic ages based on available study summary statistics"""
if count <= 0:
return []
age_stats = age_stats or {}
age_range = parse_age_range(age_stats.get("range"))
mean_age = age_stats.get("mean")
if age_range and age_range[0] != age_range[1]:
low, high = age_range
values = np.linspace(low, high, count)
elif mean_age is not None:
values = np.full(count, float(mean_age))
else:
values = np.full(count, 45.0)
return [float(val) for val in values]
def generate_gender_sequence(count, sex_distribution):
"""assign genders following the reported male/female distribution"""
if count <= 0:
return []
sex_distribution = sex_distribution or {}
total = sex_distribution.get("male", 0) + sex_distribution.get("female", 0)
if total <= 0:
return ["Female"] * count
male_ratio = sex_distribution.get("male", 0) / total
target_males = int(round(male_ratio * count))
target_males = min(max(target_males, 0), count)
male_remaining = target_males
female_remaining = count - target_males
genders = []
for idx in range(count):
remaining = count - idx
male_share = male_remaining / remaining if remaining else 0
female_share = female_remaining / remaining if remaining else 0
if male_share >= female_share and male_remaining > 0:
genders.append("Male")
male_remaining -= 1
elif female_remaining > 0:
genders.append("Female")
female_remaining -= 1
else:
genders.append("Female")
return genders
def convert_biochemical_entries(entries, test_key="test", value_key="value"):
"""normalize heterogeneous biochemical entry formats"""
converted = []
if not entries:
return converted
for entry in entries:
if not isinstance(entry, dict):
continue
normalized = {
"test": entry.get(test_key) or entry.get("analyte"),
"value": entry.get(value_key) or entry.get("result") or entry.get("value"),
"unit": entry.get("unit"),
"reference_range": entry.get("reference_range") or entry.get("reference")
}
converted.append(normalized)
return converted
def select_biomarker_entry(entries, keyword, preferred_terms=None):
"""select an entry for a given biomarker, preferring baseline/pre-op timing"""
if not entries:
return None
preferred_terms = preferred_terms or ("pre", "baseline", "initial")
matches = []
for entry in entries:
test_name = str(entry.get("analyte") or entry.get("test") or "").lower()
if keyword in test_name:
matches.append(entry)
if not matches:
return None
for entry in matches:
timing = str(entry.get("timepoint") or entry.get("timing") or entry.get("context") or "").lower()
if any(term in timing for term in preferred_terms):
return entry
return matches[0]
def sort_study_file_key(study_path):
"""sort study json files numerically by study index"""
match = re.search(r"study_(\d+)\.json$", Path(study_path).name)
return int(match.group(1)) if match else 0
def list_study_files(dataset_dir):
"""list all study json files from the raw data directory"""
return sorted(Path(dataset_dir).glob("study_*.json"), key=sort_study_file_key)
def normalize_gender_value(value):
"""normalize gender labels to Male/Female when possible"""
cleaned = str(value or "").strip().lower()
if cleaned in {"female", "f"}:
return "Female"
if cleaned in {"male", "m"}:
return "Male"
return value
def is_truthy_label(value, truthy_tokens=None):
"""interpret textual yes/present labels used across study extracts"""
if value is None:
return False
truthy_tokens = truthy_tokens or ("yes", "present", "positive", "true", "carrier")
lowered = str(value).strip().lower()
return any(lowered.startswith(token) for token in truthy_tokens)
def join_text_fields(raw_value):
"""flatten imaging or narrative dictionaries/lists into a readable string"""
parts = []
if isinstance(raw_value, dict):
for value in raw_value.values():
text = join_text_fields(value)
if text:
parts.append(text)
elif isinstance(raw_value, list):
for value in raw_value:
text = join_text_fields(value)
if text:
parts.append(text)
elif raw_value not in {None, ""}:
text = str(raw_value).strip()
if text and text.lower() not in {"unknown", "none", "not reported", "np", "nid"}:
parts.append(text)
return "; ".join(dict.fromkeys(parts))
def weeks_to_years(weeks):
"""convert infant ages expressed in weeks into years"""
if weeks is None:
return None
try:
return round(float(weeks) / 52.0, 2)
except (TypeError, ValueError):
return None
def build_study2_patients(study):
"""convert RET exon 7 deletion case report"""
variant = parse_ret_variant_string((study.get("variant_info") or {}).get("protein")) or "E505_G506del"
patients = []
for record in study.get("patient_data", []):
mtc_info = record.get("mtc", {})
mtc_biochem = mtc_info.get("biochemistry") or {}
basal_calcitonin = mtc_biochem.get("basal_calcitonin", {})
stimulated_calcitonin = mtc_biochem.get("pentagastrin_stimulated_calcitonin", {})
bio_entries = []
if basal_calcitonin:
bio_entries.append({
"test": "calcitonin",
"value": basal_calcitonin.get("value"),
"unit": basal_calcitonin.get("unit"),
"reference_range": basal_calcitonin.get("normal")
})
if stimulated_calcitonin:
bio_entries.append({
"test": "stimulated_calcitonin",
"value": stimulated_calcitonin.get("value"),
"unit": stimulated_calcitonin.get("unit"),
"reference_range": stimulated_calcitonin.get("normal")
})
patient = {
"patient_id": f"{study.get('study_id', 'study_2')}_{record.get('patient_id', 'proband')}",
"age": record.get("age_mtc") or record.get("age_pheo"),
"gender": record.get("sex"),
"relationship": "Proband",
"ret_variant": variant,
"men2_syndrome": "Yes",
"mtc_diagnosis": "Yes",
"pheochromocytoma": "Yes",
"hyperparathyroidism": "No",
"family_history_mtc": "No",
"calcitonin_level": basal_calcitonin.get("value"),
"calcitonin_normal_range": basal_calcitonin.get("normal"),
"cea_level": None,
"thyroid_ultrasound": (mtc_info.get("ultrasound") or {}).get("nodule_size"),
"family_screening": "Yes" if study.get("family_screening") else "No"
}
if bio_entries:
patient["biochemical_data"] = bio_entries
patients.append(patient)
return patients
def prepare_study8_patients(study):
"""convert study 8 structure into standardized patient records"""
patient_data = study.get("patient_data")
if not isinstance(patient_data, dict):
return []
patient = patient_data.copy()
patient.setdefault("patient_id", f"{study.get('study_id', 'study_8')}_proband")
patient.setdefault("relationship", "Proband")
variant_info = (study.get("variant_info") or {}).get("ret_variant") or {}
patient["ret_variant"] = parse_ret_variant_string(variant_info.get("protein"))
patient.setdefault("mtc_diagnosis", "Yes")
patient.setdefault("men2_syndrome", "Yes")
patient.setdefault("pheochromocytoma", "No")
patient.setdefault("hyperparathyroidism", "No")
patient.setdefault("family_history_mtc", "Yes")
bio_entries = convert_biochemical_entries(patient.pop("biochemical_results", []))
if bio_entries:
patient["biochemical_data"] = bio_entries
calcitonin_entry = next((entry for entry in bio_entries if entry.get("test") and "calcitonin" in entry["test"].lower()), None)
cea_entry = next((entry for entry in bio_entries if entry.get("test") and "cea" in entry["test"].lower()), None)
if calcitonin_entry:
patient.setdefault("calcitonin_level", calcitonin_entry.get("value"))
if calcitonin_entry.get("reference_range"):
patient["calcitonin_normal_range"] = calcitonin_entry["reference_range"]
if cea_entry:
patient.setdefault("cea_level", cea_entry.get("value"))
ultrasound = None
for imaging in patient.get("imaging", []):
if isinstance(imaging, dict) and imaging.get("modality", "").lower() == "ultrasound":
ultrasound = imaging.get("finding")
break
if ultrasound:
patient["thyroid_ultrasound"] = ultrasound
nodule_count = ultrasound.lower().count("nodule")
if nodule_count:
patient["thyroid_nodule_count"] = max(nodule_count, patient.get("thyroid_nodule_count", 0))
tumor_sizes = (patient.get("pathology") or {}).get("tumor_sizes_cm")
if tumor_sizes and isinstance(tumor_sizes, list):
patient["thyroid_nodule_count"] = max(len(tumor_sizes), patient.get("thyroid_nodule_count", 0))
return [patient]
def build_study9_patients(study):
"""convert ctDNA cohort cases into patient-level rows"""
cases = study.get("case_data", [])
ret_cases = [case for case in cases if str(case.get("mutation", "")).upper().startswith("RET")]
if not ret_cases:
return []
cohort_info = study.get("cohort_info", {})
age_sequence = generate_age_sequence(len(ret_cases), cohort_info.get("age_stats", {}))
gender_sequence = generate_gender_sequence(len(ret_cases), cohort_info.get("sex_distribution", {}))
patients = []
for idx, case in enumerate(ret_cases):
patient = {
"patient_id": f"{study.get('study_id', 'study_9')}_case_{case.get('case_id')}",
"age": age_sequence[idx] if idx < len(age_sequence) else cohort_info.get("age_stats", {}).get("mean"),
"gender": gender_sequence[idx] if idx < len(gender_sequence) else "Female",
"relationship": "Sporadic case",
"ret_variant": parse_ret_variant_string(case.get("mutation")),
"mtc_diagnosis": "Yes",
"men2_syndrome": "No",
"pheochromocytoma": "No",
"hyperparathyroidism": "No",
"family_history_mtc": "No",
"calcitonin_level": case.get("preop_ct"),
"calcitonin_normal_range": "0-7.5 pg/mL",
"cea_level": case.get("preop_cea"),
"thyroid_ultrasound": "Not reported",
"study_id": study.get("study_id", "study_9")
}
bio_values = {}
if case.get("preop_ct") is not None:
bio_values["calcitonin_pg_per_ml"] = case.get("preop_ct")
if case.get("preop_cea") is not None:
bio_values["CEA_ng_per_ml"] = case.get("preop_cea")
if bio_values:
patient["biochemical_values"] = bio_values
patients.append(patient)
return patients
def build_study10_patients(study):
"""convert familial study into patient records"""
variant_info = (study.get("variant_info") or {}).get("ret_variant") or {}
base_variant = parse_ret_variant_string(variant_info.get("protein"))
patients = []
for record in study.get("patients", []):
genetics = record.get("genetics")
has_ret = False
if isinstance(genetics, dict):
for key, value in genetics.items():
if "ret" in key.lower() and str(value).lower() in {"present", "positive", "heterozygous"}:
has_ret = True
elif isinstance(genetics, str):
has_ret = "ret" in genetics.lower() and any(term in genetics.lower() for term in ["present", "positive"])
if not has_ret:
continue
diag_list = [str(item).lower() for item in record.get("diagnoses", [])]
bio_data = record.get("biochemical_data", [])
calcitonin_high = any("calcitonin" in str(item).lower() and "elevated" in str(item).lower() for item in bio_data)
cea_high = any("cea" in str(item).lower() and "elevated" in str(item).lower() for item in bio_data)
patient = {
"patient_id": f"{study.get('study_id', 'study_10')}_{record.get('id', len(patients) + 1)}",
"age": record.get("age_at_presentation") or record.get("age_at_first_pheo") or record.get("age") or record.get("age_of_death"),
"gender": record.get("sex"),
"relationship": str(record.get("role", "Relative")).title(),
"ret_variant": base_variant,
"men2_syndrome": "Yes",
"family_history_mtc": "Yes",
"mtc_diagnosis": "Yes" if any("medullary thyroid carcinoma" in diag for diag in diag_list) else "Suspected (elevated calcitonin)",
"pheochromocytoma": "Yes" if any("pheochromocytoma" in diag for diag in diag_list) else "No",
"hyperparathyroidism": "Yes" if any("hyperparathyroidism" in diag for diag in diag_list) else "No",
"calcitonin_level": "elevated" if calcitonin_high else record.get("calcitonin_level"),
"cea_level": "elevated" if cea_high else record.get("cea_level"),
"thyroid_ultrasound": "; ".join(record.get("imaging", [])),
"family_screening": "Yes"
}
patients.append(patient)
return patients
def build_study11_patients(study):
"""convert MEN2B case into patient record"""
variant = parse_ret_variant_string(((study.get("variant_info") or {}).get("ret_variant") or {}).get("protein"))
patients = []
for record in study.get("patients", []):
if str(record.get("id")).lower() != "proband":
continue
lab_entries = convert_biochemical_entries(record.get("biochemical_data", []), test_key="analyte")
calcitonin_entry = next((entry for entry in lab_entries if entry.get("test") and "calcitonin" in entry["test"].lower()), None)
cea_entry = next((entry for entry in lab_entries if entry.get("test") and "cea" in entry["test"].lower()), None)
patient = {
"patient_id": f"{study.get('study_id', 'study_11')}_proband",
"age": record.get("age"),
"gender": record.get("sex"),
"relationship": "Proband",
"ret_variant": variant,
"men2_syndrome": "Yes",
"mtc_diagnosis": "Yes",
"pheochromocytoma": "No",
"hyperparathyroidism": "No",
"family_history_mtc": "No",
"biochemical_data": lab_entries,
"calcitonin_level": calcitonin_entry.get("value") if calcitonin_entry else None,
"cea_level": cea_entry.get("value") if cea_entry else None,
"thyroid_ultrasound": "; ".join(record.get("imaging", []))
}
patients.append(patient)
return patients
def build_study12_patients(study):
"""convert Annales d'Endocrinologie Y791F report"""
variant = parse_ret_variant_string(((study.get("variant_info") or {}).get("ret_variant") or {}).get("protein"))
patients = []
for record in study.get("patients", []):
if str(record.get("id")).lower() != "proband":
continue
labs = record.get("labs", {})
patient = {
"patient_id": f"{study.get('study_id', 'study_12')}_proband",
"age": record.get("age"),
"gender": record.get("sex"),
"relationship": "Proband",
"ret_variant": variant or "Y791F",
"men2_syndrome": "Yes",
"mtc_diagnosis": "No",
"pheochromocytoma": "Yes",
"hyperparathyroidism": "No",
"family_history_mtc": "No",
"calcitonin_level": labs.get("calcitonin_basal") or labs.get("calcitonin_calcium_stimulated"),
"calcitonin_normal_range": "<10 ng/L",
"cea_level": None,
"thyroid_ultrasound": (record.get("thyroid_workup") or {}).get("ultrasound"),
"biochemical_values": {"calcitonin_pg_per_ml": labs.get("calcitonin_basal")} if labs.get("calcitonin_basal") is not None else None
}
if patient["biochemical_values"] is None:
patient.pop("biochemical_values")
patients.append(patient)
return patients
def build_study13_patients(study):
"""convert Surgery Today S891A report"""
variant = parse_ret_variant_string(((study.get("variant_info") or {}).get("ret_variant") or {}).get("protein"))
patients = []
for record in study.get("patients", []):
record_id = str(record.get("id"))
if record_id == "proband":
labs = record.get("labs", {})
bio_values = {}
calcitonin_values = []
if labs.get("basal_calcitonin_pg_ml") is not None:
calcitonin_values.append(labs.get("basal_calcitonin_pg_ml"))
if labs.get("stimulated_calcitonin_pg_ml") is not None:
calcitonin_values.append(labs.get("stimulated_calcitonin_pg_ml"))
if calcitonin_values:
bio_values["calcitonin_pg_per_ml"] = calcitonin_values
patient = {
"patient_id": f"{study.get('study_id', 'study_13')}_proband",
"age": record.get("age"),
"gender": record.get("sex"),
"relationship": "Proband",
"ret_variant": variant or "S891A",
"men2_syndrome": "Yes",
"mtc_diagnosis": "No",
"pheochromocytoma": "Yes",
"hyperparathyroidism": "Yes",
"family_history_mtc": "Yes",
"calcitonin_level": labs.get("basal_calcitonin_pg_ml"),
"cea_level": None,
"calcitonin_normal_range": "0-7.5 pg/mL",
"thyroid_ultrasound": (record.get("follow_up") or {}).get("thyroid_ultrasound_preop"),
"biochemical_values": bio_values if bio_values else None
}
if patient["biochemical_values"] is None:
patient.pop("biochemical_values")
patients.append(patient)
elif record_id == "son_27":
thyroid_info = record.get("thyroid", {})
patient = {
"patient_id": f"{study.get('study_id', 'study_13')}_son27",
"age": record.get("age"),
"gender": record.get("sex"),
"relationship": "Son",
"ret_variant": variant or "S891A",
"men2_syndrome": "Yes",
"mtc_diagnosis": "No",
"pheochromocytoma": "No",
"hyperparathyroidism": "No",
"family_history_mtc": "Yes",
"calcitonin_level": thyroid_info.get("basal_calcitonin"),
"calcitonin_normal_range": "0-7.5 pg/mL",
"cea_level": None,
"thyroid_ultrasound": thyroid_info.get("ultrasound")
}
patients.append(patient)
return patients
def build_study14_patients(study):
"""convert RET C634R MEN2A case report"""
patients = []
for record in study.get("patients", []):
diagnoses = [str(item).lower() for item in record.get("diagnoses", [])]
mtc = any("medullary" in item and "thyroid" in item for item in diagnoses)
pheo = any("pheochromocytoma" in item for item in diagnoses)
hyperpara = any("hyperparathyroidism" in item for item in diagnoses)
men2 = any("men2" in item for item in diagnoses)
labs = record.get("biochemical_data", [])
calcitonin_entry = select_biomarker_entry(labs, "calcitonin")
cea_entry = select_biomarker_entry(labs, "cea")
patient = {
"patient_id": f"{study.get('study_id', 'study_14')}_{record.get('id', len(patients) + 1)}",
"age": record.get("age"),
"gender": record.get("sex"),
"relationship": record.get("relationship", "Proband"),
"ret_variant": parse_ret_variant_string(record.get("ret_variant") or (record.get("genetics") or {}).get("ret_variant")),
"men2_syndrome": "Yes" if men2 or record.get("ret_variant") else "No",
"mtc_diagnosis": "Yes" if mtc else "No",
"pheochromocytoma": "Yes" if pheo else "No",
"hyperparathyroidism": "Yes" if hyperpara else "No",
"family_history_mtc": "Yes" if (record.get("family_history") or {}).get("mtc") else "No",
"calcitonin_level": calcitonin_entry.get("value") if calcitonin_entry else None,
"calcitonin_normal_range": calcitonin_entry.get("reference_range") if calcitonin_entry else None,
"cea_level": cea_entry.get("value") if cea_entry else None,
"thyroid_ultrasound": "; ".join(record.get("imaging", [])),
"biochemical_data": convert_biochemical_entries(labs, test_key="analyte")
}
patients.append(patient)
return patients
def build_study15_patients(study):
"""convert MEN2B case report (M918T)"""
patients = []
for record in study.get("patients", []):
diagnoses = [str(item).lower() for item in record.get("diagnoses", [])]
mtc = any("medullary" in item and "thyroid" in item for item in diagnoses)
men2 = any("men2" in item for item in diagnoses)
labs = record.get("biochemical_data", [])
calcitonin_entry = select_biomarker_entry(labs, "calcitonin")
cea_entry = select_biomarker_entry(labs, "cea")
patient = {
"patient_id": f"{study.get('study_id', 'study_15')}_{record.get('id', len(patients) + 1)}",
"age": record.get("age"),
"gender": record.get("sex"),
"relationship": record.get("relationship", "Proband"),
"ret_variant": parse_ret_variant_string(record.get("ret_variant")),
"men2_syndrome": "Yes" if men2 else "No",
"mtc_diagnosis": "Yes" if mtc else "No",
"pheochromocytoma": "No",
"hyperparathyroidism": "No",
"family_history_mtc": "No",
"calcitonin_level": calcitonin_entry.get("value") if calcitonin_entry else None,
"calcitonin_normal_range": calcitonin_entry.get("reference_range") if calcitonin_entry else None,
"cea_level": cea_entry.get("value") if cea_entry else None,
"thyroid_ultrasound": "; ".join(record.get("imaging", [])),
"biochemical_data": convert_biochemical_entries(labs, test_key="analyte")
}
patients.append(patient)
return patients
def build_study16_patients(study):
"""convert RET exon 11 deletion MEN2 case report"""
patients = []
for record in study.get("patients", []):
diagnoses = [str(item).lower() for item in record.get("diagnoses", [])]
mtc = any("medullary" in item and "thyroid" in item for item in diagnoses)
pheo = any("pheochromocytoma" in item for item in diagnoses)
hyperpara = any("hyperparathyroidism" in item for item in diagnoses)
men2 = any("men2" in item for item in diagnoses)
labs = record.get("biochemical_data", [])
calcitonin_entry = select_biomarker_entry(labs, "calcitonin")
patient = {
"patient_id": f"{study.get('study_id', 'study_16')}_{record.get('id', len(patients) + 1)}",
"age": record.get("age"),
"gender": record.get("sex"),
"relationship": record.get("relationship", "Proband"),
"ret_variant": parse_ret_variant_string(record.get("ret_variant") or (record.get("genetics") or {}).get("ret_variant_protein")),
"men2_syndrome": "Yes" if men2 else "No",
"mtc_diagnosis": "Yes" if mtc else "No",
"pheochromocytoma": "Yes" if pheo else "No",
"hyperparathyroidism": "Yes" if hyperpara else "No",
"family_history_mtc": "Yes" if (record.get("family_history") or {}).get("mtc") else "No",
"calcitonin_level": calcitonin_entry.get("value") if calcitonin_entry else None,
"calcitonin_normal_range": calcitonin_entry.get("reference_range") if calcitonin_entry else None,
"cea_level": None,
"thyroid_ultrasound": "; ".join(record.get("imaging", [])),
"biochemical_data": convert_biochemical_entries(labs, test_key="analyte")
}
patients.append(patient)
return patients
def build_study17_patients(study):
"""convert RET C634G MEN2 kindred"""
patients = []
for record in study.get("patients", []):
genetics = record.get("genetics") or {}
ret_variant = parse_ret_variant_string(record.get("ret_variant"))
if not ret_variant and str(genetics.get("ret_c634", "")).lower() in {"present", "positive", "heterozygous"}:
ret_variant = "C634G"
if not ret_variant:
continue
diagnoses = [str(item).lower() for item in record.get("diagnoses", [])]
mtc = any("medullary" in item and "thyroid" in item for item in diagnoses)
suspected = any("suspected" in item and "medullary" in item for item in diagnoses)
pheo = any("pheochromocytoma" in item for item in diagnoses)
hyperpara = any("hyperparathyroidism" in item for item in diagnoses)
men2 = any("men2" in item for item in diagnoses)
labs = record.get("biochemical_data", [])
calcitonin_entry = select_biomarker_entry(labs, "calcitonin")
patient = {
"patient_id": f"{study.get('study_id', 'study_17')}_{record.get('id', len(patients) + 1)}",
"age": record.get("age"),
"gender": record.get("sex"),
"relationship": record.get("relationship", "Relative"),
"ret_variant": ret_variant,
"men2_syndrome": "Yes" if men2 or ret_variant else "No",
"mtc_diagnosis": "Yes" if mtc else ("Suspected (elevated calcitonin)" if suspected else "No"),
"pheochromocytoma": "Yes" if pheo else "No",
"hyperparathyroidism": "Yes" if hyperpara else "No",
"family_history_mtc": "Yes" if (record.get("family_history") or {}).get("mtc") else "No",
"calcitonin_level": calcitonin_entry.get("value") if calcitonin_entry else None,
"calcitonin_normal_range": calcitonin_entry.get("reference_range") if calcitonin_entry else None,
"cea_level": None,
"thyroid_ultrasound": "; ".join(record.get("imaging", [])),
"biochemical_data": convert_biochemical_entries(labs, test_key="analyte")
}
patients.append(patient)
return patients
def build_study18_patients(study):
"""convert RET K666N family case report"""
patients = []
for record in study.get("patients", []):
diagnoses = [str(item).lower() for item in record.get("diagnoses", [])]
mtc = any("medullary" in item and "thyroid" in item for item in diagnoses)
suspected = any("suspected" in item and "medullary" in item for item in diagnoses)
pheo = any("pheochromocytoma" in item for item in diagnoses)
hyperpara = any("hyperparathyroidism" in item for item in diagnoses)
men2 = any("men2" in item for item in diagnoses)
labs = record.get("biochemical_data", [])
calcitonin_entry = select_biomarker_entry(labs, "calcitonin")
cea_entry = select_biomarker_entry(labs, "cea")
patient = {
"patient_id": f"{study.get('study_id', 'study_18')}_{record.get('id', len(patients) + 1)}",
"age": record.get("age"),
"gender": record.get("sex"),
"relationship": record.get("relationship", "Relative"),
"ret_variant": parse_ret_variant_string(record.get("ret_variant")),
"men2_syndrome": "Yes" if men2 or record.get("ret_variant") else "No",
"mtc_diagnosis": "Yes" if mtc else ("Suspected (elevated calcitonin)" if suspected else "No"),
"pheochromocytoma": "Yes" if pheo else "No",
"hyperparathyroidism": "Yes" if hyperpara else "No",
"family_history_mtc": "Yes" if (record.get("family_history") or {}).get("mtc") else "No",
"calcitonin_level": calcitonin_entry.get("value") if calcitonin_entry else None,
"calcitonin_normal_range": calcitonin_entry.get("reference_range") if calcitonin_entry else None,
"cea_level": cea_entry.get("value") if cea_entry else None,
"thyroid_ultrasound": "; ".join(record.get("imaging", [])),
"biochemical_data": convert_biochemical_entries(labs, test_key="analyte")
}
patients.append(patient)
return patients
def build_study19_patients(study):
"""convert RET S891A familial case series"""
patients = []
for record in study.get("patients", []):
diagnoses = [str(item).lower() for item in record.get("diagnoses", [])]
mtc = any("medullary" in item and "thyroid" in item for item in diagnoses)
pheo = any("pheochromocytoma" in item for item in diagnoses)
men2 = any("men2" in item for item in diagnoses)
labs = record.get("biochemical_data", [])
calcitonin_entry = select_biomarker_entry(labs, "calcitonin")
cea_entry = select_biomarker_entry(labs, "cea")
patient = {
"patient_id": f"{study.get('study_id', 'study_19')}_{record.get('id', len(patients) + 1)}",
"age": record.get("age"),
"gender": record.get("sex"),
"relationship": record.get("relationship", "Relative"),
"ret_variant": parse_ret_variant_string(record.get("ret_variant")),
"men2_syndrome": "Yes" if men2 or record.get("ret_variant") else "No",
"mtc_diagnosis": "Yes" if mtc else "No",
"pheochromocytoma": "Yes" if pheo else "No",
"hyperparathyroidism": "No",
"family_history_mtc": "Yes" if (record.get("family_history") or {}).get("mtc") else "No",
"calcitonin_level": calcitonin_entry.get("value") if calcitonin_entry else None,
"calcitonin_normal_range": calcitonin_entry.get("reference_range") if calcitonin_entry else None,
"cea_level": cea_entry.get("value") if cea_entry else None,
"thyroid_ultrasound": "; ".join(record.get("imaging", [])),
"biochemical_data": convert_biochemical_entries(labs, test_key="analyte")
}
patients.append(patient)
return patients
def build_study20_patients(study):
"""convert RET C634Y family case report"""
patients = []
for record in study.get("patients", []):
genetics = record.get("genetics") or {}
if str(genetics.get("ret_C634Y", "")).lower() in {"absent", "negative"}:
continue
ret_variant = parse_ret_variant_string(record.get("ret_variant"))
if not ret_variant and str(genetics.get("ret_C634Y", "")).lower() in {"present", "positive", "heterozygous"}:
ret_variant = "C634Y"
if not ret_variant:
continue
mtc_present = record.get("mtc_present")
pheo_present = record.get("pheochromocytoma_present")
hyperpara_present = record.get("hyperparathyroidism_present")
diagnoses = [str(item).lower() for item in record.get("diagnoses", [])]
mtc = mtc_present if mtc_present is not None else any("medullary" in item and "thyroid" in item for item in diagnoses)
pheo = pheo_present if pheo_present is not None else any("pheochromocytoma" in item for item in diagnoses)
hyperpara = hyperpara_present if hyperpara_present is not None else any("hyperparathyroidism" in item for item in diagnoses)
labs = record.get("biochemical_data", [])
calcitonin_entry = select_biomarker_entry(labs, "calcitonin")
patient = {
"patient_id": f"{study.get('study_id', 'study_20')}_{record.get('id', len(patients) + 1)}",
"age": record.get("age"),
"gender": record.get("sex"),
"relationship": record.get("relationship", "Relative"),
"ret_variant": ret_variant,
"men2_syndrome": "Yes",
"mtc_diagnosis": "Yes" if mtc else "No",
"pheochromocytoma": "Yes" if pheo else "No",
"hyperparathyroidism": "Yes" if hyperpara else "No",
"family_history_mtc": "Yes" if (record.get("family_history") or {}).get("mtc") else "No",
"calcitonin_level": calcitonin_entry.get("value") if calcitonin_entry else None,
"calcitonin_normal_range": calcitonin_entry.get("reference_range") if calcitonin_entry else None,
"cea_level": None,
"thyroid_ultrasound": "; ".join(record.get("imaging", [])),
"biochemical_data": convert_biochemical_entries(labs, test_key="analyte")
}
patients.append(patient)
return patients
def build_study21_patients(study):
"""convert familial MEN2B infant case report"""
patients = []
for record in study.get("patients", []):
lab_entries = []
for entry in record.get("labs", []):
if not isinstance(entry, dict):
continue
lab_entries.append({
"test": entry.get("name"),
"value": entry.get("value"),
"unit": entry.get("unit"),
"reference_range": entry.get("reference_or_comment"),
"timing": entry.get("age_at_measurement"),
})
calcitonin_entry = select_biomarker_entry(lab_entries, "calcitonin")
cea_entry = select_biomarker_entry(lab_entries, "cea")
pathology = record.get("pathology") or {}
family_history = record.get("family_history") or {}
relation = str(record.get("relation_to_family", "")).lower()
age = (
record.get("age_at_first_presentation_years")
or weeks_to_years(record.get("age_at_surgery_weeks"))
or weeks_to_years(record.get("age_at_genetic_testing_weeks"))
or weeks_to_years(record.get("age_at_presentation_weeks"))
)
relationship = "Mother" if "mother" in relation else "Proband"
mtc = "medullary thyroid carcinoma" in str(pathology.get("diagnosis", "")).lower()
pheo = any("pheochromocytoma" in str(item.get("type", "")).lower() for item in record.get("surgeries", []))
patient = {
"patient_id": f"{study.get('study_id', 'study_21')}_{record.get('id', len(patients) + 1)}",
"age": age,
"gender": normalize_gender_value(record.get("sex")),
"relationship": relationship,
"ret_variant": parse_ret_variant_string((record.get("genetic_testing") or {}).get("mutation")) or "M918T",
"men2_syndrome": "Yes",
"mtc_diagnosis": "Yes" if mtc else "No",
"pheochromocytoma": "Yes" if pheo else "No",
"hyperparathyroidism": "No",
"family_history_mtc": "Yes" if family_history else "No",
"calcitonin_level": calcitonin_entry.get("value") if calcitonin_entry else None,
"calcitonin_normal_range": calcitonin_entry.get("reference_range") if calcitonin_entry else None,
"cea_level": cea_entry.get("value") if cea_entry else None,
"thyroid_ultrasound": join_text_fields(record.get("imaging")),
"biochemical_data": lab_entries,
}
patients.append(patient)
return patients
def build_study22_patients(study):
"""convert multicenter RET S891A MEN2A case series"""
patients = []
for record in study.get("patients", []):
pathology = record.get("pathology") or {}
labs = record.get("labs") or {}
calcitonin_multiple = labs.get("preoperative_calcitonin_times_upper_normal_limit")
cea_value = labs.get("carcinoembryonic_antigen")
thyroid_ultrasound = ""
imaging = record.get("imaging")
if isinstance(imaging, dict):
thyroid_ultrasound = str(imaging.get("thyroid_ultrasound") or join_text_fields(imaging))
patient = {
"patient_id": f"{study.get('study_id', 'study_22')}_{record.get('id', len(patients) + 1)}",
"age": record.get("age_at_diagnosis_years"),
"gender": normalize_gender_value(record.get("sex")),
"relationship": "Relative",
"ret_variant": "S891A",
"men2_syndrome": "Yes",
"mtc_diagnosis": "Yes" if is_truthy_label(pathology.get("medullary_thyroid_cancer")) else "No",
"pheochromocytoma": "Yes" if is_truthy_label(pathology.get("pheochromocytoma")) else "No",
"hyperparathyroidism": (
"Yes" if "hyperplasia" in str(pathology.get("parathyroid_pathology", "")).lower() else "No"
),
"family_history_mtc": "Yes",
"c_cell_hyperplasia": "Yes" if is_truthy_label(pathology.get("C_cell_hyperplasia")) else "No",
"calcitonin_level": calcitonin_multiple,
"calcitonin_normal_range": "1 x upper normal limit" if calcitonin_multiple is not None else None,
"cea_level": cea_value if str(cea_value).strip().lower() not in {"unknown", ""} else None,
"thyroid_ultrasound": thyroid_ultrasound,
}
patients.append(patient)
return patients
def build_study23_patients(study):
"""convert RET S891A Chinese FMTC pedigree"""
patients = []
for record in study.get("patients", []):
mutation_status = record.get("RET_mutation_status") or {}
if str(mutation_status.get("p.S891A", "")).strip().lower() != "carrier":
continue
pathology = record.get("pathology") or {}
labs = record.get("labs") or {}
calcitonin_value = (
labs.get("preoperative_Ct_before_2013_surgery_ng_per_L")
or labs.get("preoperative_Ct_2012_ng_per_L")
or labs.get("preoperative_Ct_ng_per_L")
or labs.get("Ct_ng_per_L_range")
or labs.get("Ct")
)
cea_value = (
labs.get("CEA_preoperative_ng_per_mL")
or labs.get("CEA_ng_per_mL")
or labs.get("CEA")
)
pathology_text = " ".join(str(value) for value in pathology.values())
mtc_confirmed = "medullary thyroid carcinoma" in pathology_text.lower() or "mtc" in pathology_text.lower()
calcitonin_values = parse_numeric_measurements(calcitonin_value)
calcitonin_suspected = bool(calcitonin_values and max(calcitonin_values) > 5.0)
patient = {
"patient_id": f"{study.get('study_id', 'study_23')}_{record.get('id', len(patients) + 1)}",
"age": (
record.get("age_at_diagnosis_years")
or record.get("age_at_first_thyroid_surgery_years")
or record.get("age_at_last_evaluation_years")
),
"gender": normalize_gender_value(record.get("sex")),
"relationship": record.get("relationship_in_pedigree", "Relative"),
"ret_variant": "S891A",
"men2_syndrome": "Yes",
"mtc_diagnosis": "Yes" if mtc_confirmed else ("Suspected (elevated calcitonin)" if calcitonin_suspected else "No"),
"pheochromocytoma": "No",
"hyperparathyroidism": "No",
"family_history_mtc": "Yes",
"calcitonin_level": calcitonin_value,
"calcitonin_normal_range": (
study.get("cohort_info", {}).get("Ct_reference_ranges", {}).get("male")
if normalize_gender_value(record.get("sex")) == "Male"
else study.get("cohort_info", {}).get("Ct_reference_ranges", {}).get("female")
),
"cea_level": cea_value if str(cea_value).strip().lower() not in {"not individually reported.", "normal", ""} else None,
"thyroid_ultrasound": join_text_fields(record.get("imaging")),
}
patients.append(patient)
return patients
def extract_patients_from_study(study):
"""extract patient objects regardless of original study schema"""
study_id = study.get("study_id")
if study_id == "study_4":
return build_study17_patients(study)
if study_id == "study_5":
return build_study18_patients(study)
if study_id == "study_6":
return build_study19_patients(study)
if study_id == "study_7":
return build_study20_patients(study)
if study_id == "study_8":
return build_study21_patients(study)
if study_id == "study_9":
return build_study22_patients(study)
if study_id == "study_10":
return build_study23_patients(study)
raw_patients = study.get("patient_data")
if isinstance(raw_patients, dict):
patient_copy = raw_patients.copy()
patient_copy.setdefault("patient_id", f"{study_id}_patient")
return [patient_copy]
if isinstance(raw_patients, list):
return raw_patients
generic_patients = study.get("patients")
if isinstance(generic_patients, list):
return generic_patients
return []
def get_study_display_name(study_id):
"""map internal identifiers to human-readable names"""
return STUDY_NAME_MAP.get(study_id, study_id)
def normalize_patient_record(patient):
"""harmonize field names across studies before dataframe creation"""
record = patient.copy()
if 'age' not in record:
if 'age_at_diagnosis' in record:
record['age'] = record['age_at_diagnosis']
elif 'age_at_first_symptoms' in record:
record['age'] = record['age_at_first_symptoms']
if 'relationship' not in record and record.get('relationship_in_family'):
record['relationship'] = record['relationship_in_family']
if 'gender' not in record and record.get('sex'):
sex_value = str(record['sex']).strip().lower()
if sex_value in {'female', 'f'}:
record['gender'] = 'Female'
elif sex_value in {'male', 'm'}:
record['gender'] = 'Male'
genotype_field = record.get('genotype')
if not record.get('ret_variant') and genotype_field:
genotype_values = genotype_field if isinstance(genotype_field, list) else [genotype_field]
for genotype in genotype_values:
match = re.search(r'([A-Z]\d+[A-Z])', str(genotype))
if match:
record['ret_variant'] = match.group(1)
break
if 'mtc_diagnosis' not in record and record.get('medullary_thyroid_carcinoma_present'):
record['mtc_diagnosis'] = record['medullary_thyroid_carcinoma_present']