Liu-Hy commited on
Commit
35adc86
·
verified ·
1 Parent(s): 9efdaa1

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. output/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE48801.csv +2 -0
  2. output/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE50012.csv +2 -3
  3. output/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE57795.csv +2 -2
  4. output/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE58715.csv +2 -2
  5. output/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE66705.csv +1 -1
  6. output/preprocess/Glucocorticoid_Sensitivity/code/GSE15820.py +154 -0
  7. output/preprocess/Glucocorticoid_Sensitivity/code/GSE32962.py +176 -0
  8. output/preprocess/Glucocorticoid_Sensitivity/code/GSE33649.py +184 -0
  9. output/preprocess/Glucocorticoid_Sensitivity/code/GSE42002.py +185 -0
  10. output/preprocess/Glucocorticoid_Sensitivity/code/GSE48801.py +220 -0
  11. output/preprocess/Glucocorticoid_Sensitivity/code/GSE50012.py +206 -0
  12. output/preprocess/Glucocorticoid_Sensitivity/code/GSE57795.py +215 -0
  13. output/preprocess/Glucocorticoid_Sensitivity/code/GSE58715.py +169 -0
  14. output/preprocess/Glucocorticoid_Sensitivity/code/GSE65645.py +188 -0
  15. output/preprocess/Glucocorticoid_Sensitivity/code/GSE66705.py +196 -0
  16. output/preprocess/Glucocorticoid_Sensitivity/code/TCGA.py +52 -0
  17. output/preprocess/Head_and_Neck_Cancer/GSE201777.csv +0 -0
  18. output/preprocess/Head_and_Neck_Cancer/clinical_data/GSE151181.csv +1 -1
  19. output/preprocess/Head_and_Neck_Cancer/clinical_data/GSE201777.csv +2 -2
  20. output/preprocess/Head_and_Neck_Cancer/clinical_data/GSE244580.csv +2 -2
  21. output/preprocess/Head_and_Neck_Cancer/code/GSE104006.py +133 -0
  22. output/preprocess/Head_and_Neck_Cancer/code/GSE148320.py +139 -0
  23. output/preprocess/Head_and_Neck_Cancer/code/GSE151179.py +1518 -0
  24. output/preprocess/Head_and_Neck_Cancer/code/GSE151181.py +318 -0
  25. output/preprocess/Head_and_Neck_Cancer/code/GSE156915.py +133 -0
  26. output/preprocess/Head_and_Neck_Cancer/code/GSE184944.py +124 -0
  27. output/preprocess/Head_and_Neck_Cancer/code/GSE201777.py +190 -0
  28. output/preprocess/Head_and_Neck_Cancer/code/GSE212250.py +111 -0
  29. output/preprocess/Head_and_Neck_Cancer/code/GSE218109.py +167 -0
  30. output/preprocess/Head_and_Neck_Cancer/code/GSE244580.py +256 -0
  31. output/preprocess/Head_and_Neck_Cancer/code/TCGA.py +255 -0
  32. output/preprocess/Head_and_Neck_Cancer/cohort_info.json +1 -112
  33. output/preprocess/Heart_rate/GSE35661.csv +0 -0
  34. output/preprocess/Heart_rate/clinical_data/GSE18583.csv +2 -42
  35. output/preprocess/Heart_rate/clinical_data/GSE34788.csv +2 -121
  36. output/preprocess/Heart_rate/clinical_data/GSE35661.csv +2 -42
  37. output/preprocess/Heart_rate/code/GSE117070.py +212 -0
  38. output/preprocess/Heart_rate/code/GSE12385.py +213 -0
  39. output/preprocess/Heart_rate/code/GSE18583.py +235 -0
  40. output/preprocess/Heart_rate/code/GSE236927.py +198 -0
  41. output/preprocess/Heart_rate/code/GSE34788.py +181 -0
  42. output/preprocess/Heart_rate/code/GSE35661.py +379 -0
  43. output/preprocess/Heart_rate/code/GSE72462.py +94 -0
  44. output/preprocess/Heart_rate/code/TCGA.py +81 -0
  45. output/preprocess/Heart_rate/cohort_info.json +1 -82
  46. output/preprocess/Heart_rate/gene_data/GSE35661.csv +0 -0
  47. output/preprocess/Height/GSE117525.csv +0 -0
  48. output/preprocess/Height/GSE131835.csv +0 -0
  49. output/preprocess/Height/clinical_data/GSE106800.csv +3 -48
  50. output/preprocess/Height/clinical_data/GSE131835.csv +4 -0
output/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE48801.csv ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ ,GSM1184717,GSM1184718,GSM1184719,GSM1184720,GSM1184721,GSM1184722,GSM1184723,GSM1184724,GSM1184725,GSM1184726,GSM1184727,GSM1184728,GSM1184729,GSM1184730,GSM1184731,GSM1184732,GSM1184733,GSM1184734,GSM1184735,GSM1184736,GSM1184737,GSM1184738,GSM1184739,GSM1184740,GSM1184741,GSM1184742,GSM1184743,GSM1184744,GSM1184745,GSM1184746,GSM1184747,GSM1184748,GSM1184749,GSM1184750,GSM1184751,GSM1184752,GSM1184753,GSM1184754,GSM1184755,GSM1184756,GSM1184757,GSM1184758,GSM1184759,GSM1184760,GSM1184761,GSM1184762,GSM1184763,GSM1184764,GSM1184765,GSM1184766,GSM1184767,GSM1184768,GSM1184769,GSM1184770,GSM1184771,GSM1184772,GSM1184773,GSM1184774,GSM1184775,GSM1184776,GSM1184777,GSM1184778,GSM1184779,GSM1184780,GSM1184781,GSM1184782,GSM1184783,GSM1184784,GSM1184785,GSM1184786,GSM1184787,GSM1184788,GSM1184789,GSM1184790,GSM1184791,GSM1184792,GSM1184793,GSM1184794,GSM1184795,GSM1184796,GSM1184797,GSM1184798,GSM1184799,GSM1184800,GSM1184801,GSM1184802,GSM1184803,GSM1184804,GSM1184805,GSM1184806,GSM1184807,GSM1184808,GSM1184809,GSM1184810,GSM1184811,GSM1184812,GSM1184813,GSM1184814,GSM1184815,GSM1184816,GSM1184817,GSM1184818,GSM1184819,GSM1184820,GSM1184821,GSM1184822,GSM1184823,GSM1184824,GSM1184825,GSM1184826,GSM1184827,GSM1184828,GSM1184829,GSM1184830,GSM1184831,GSM1184832,GSM1184833,GSM1184834,GSM1184835,GSM1184836,GSM1184837,GSM1184838,GSM1184839,GSM1184840,GSM1184841,GSM1184842,GSM1184843,GSM1184844,GSM1184845,GSM1184846,GSM1184847,GSM1184848,GSM1184849,GSM1184850,GSM1184851,GSM1184852,GSM1184853,GSM1184854,GSM1184855,GSM1184856,GSM1184857,GSM1184858,GSM1184859,GSM1184860,GSM1184861,GSM1184862,GSM1184863,GSM1184864,GSM1184865,GSM1184866,GSM1184867,GSM1184868,GSM1184869,GSM1184870,GSM1184871,GSM1184872,GSM1184873,GSM1184874,GSM1184875,GSM1184876,GSM1184877,GSM1184878,GSM1184879,GSM1184880,GSM1184881,GSM1184882,GSM1184883,GSM1184884,GSM1184885,GSM1184886,GSM1184887,GSM1184888,GSM1184889,GSM1184890,GSM1184891,GSM1184892,GSM1184893,GSM1184894,GSM1184895
2
+ Glucocorticoid_Sensitivity,90.2096916857165,90.2096916857165,92.0660852718675,92.0660852718675,85.8770390662799,85.8770390662799,87.4945143923344,87.4945143923344,85.1993812425936,85.1993812425936,84.9616236229156,84.9616236229156,83.9341340611542,83.9341340611542,88.7663927292959,88.7663927292959,88.4126127755346,88.4126127755346,90.1302355511097,90.1302355511097,86.3038207243861,86.3038207243861,97.9389927348314,97.9389927348314,85.6565800452145,85.6565800452145,72.080026977723,72.080026977723,95.7902581814721,95.7902581814721,84.7169700775247,84.7169700775247,97.2440363125325,97.2440363125325,98.6965291984436,98.6965291984436,96.3897437049292,96.3897437049292,93.7864779279733,93.7864779279733,88.9409584548941,88.9409584548941,95.2180128029044,95.2180128029044,80.3262384967705,80.3262384967705,98.9664822965928,98.9664822965928,86.7141270837215,86.7141270837215,94.1342236284511,94.1342236284511,76.5646360533747,76.5646360533747,94.4880035822124,94.4880035822124,84.2040871593034,84.2040871593034,81.2524330708547,81.2524330708547,75.0377332194718,75.0377332194718,103.111196853422,103.111196853422,93.7264007046898,93.7264007046898,98.4358920138007,98.4358920138007,91.1219245341963,91.1219245341963,89.7952307882158,89.7952307882158,100.164196369324,100.164196369324,92.2726878044167,92.2726878044167,83.653786832453,83.653786832453,85.4308536742686,85.4308536742686,95.9867474842918,95.9867474842918,97.4697626834784,97.4697626834784,87.1103581762748,87.1103581762748,106.335980304372,106.335980304372,95.0323274416373,95.0323274416373,93.2741255092367,93.2741255092367,88.0517452462257,88.0517452462257,92.7703808066373,92.7703808066373,90.2966860598886,90.2966860598886,90.2966860598886,87.6826035548426,87.6826035548426,87.6826035548426,110.820589380024,110.820589380024,110.820589380024,91.2861567746556,91.2861567746556,90.9575303422268,90.9575303422268,99.844023580098,99.844023580098,92.4380615886291,92.4380615886291,90.6279285533303,90.6279285533303,90.6279285533303,95.4061019654126,95.4061019654126,95.4061019654126,102.574377860977,102.574377860977,102.574377860977,83.3617762565561,83.3617762565561,92.9375020882722,92.9375020882722,83.056592777649,83.056592777649,101.239617979237,101.239617979237,86.5108726528178,86.5108726528178,87.8682889161097,87.8682889161097,89.9631142694748,89.9631142694748,95.5967828443558,95.5967828443558,94.3102962675651,94.3102962675651,97.0235772914671,97.0235772914671,94.6674807225407,94.6674807225407,86.0926581231368,86.0926581231368,107.862883138275,107.862883138275,82.7364199884225,82.7364199884225,88.2331356352063,88.2331356352063,93.614568433444,93.614568433444,103.717527073529,103.717527073529,103.717527073529,91.4503081788735,91.4503081788735,91.4503081788735,89.4567969526773,89.4567969526773,89.4567969526773,91.9430860155202,91.9430860155202,92.1077238348243,92.1077238348243,100.50157318001,100.50157318001,77.6379974012028,77.6379974012028,99.246829525294,99.246829525294,93.4438194050697,93.4438194050697,80.8101665274758,80.8101665274758,93.1053855695312,93.1053855695312
output/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE50012.csv CHANGED
@@ -1,4 +1,3 @@
1
  ,GSM832137,GSM832138,GSM832139,GSM832140,GSM832141,GSM832142,GSM832143,GSM832144,GSM832145,GSM832146,GSM832147,GSM832148,GSM832149,GSM832150,GSM832151,GSM832152,GSM832153,GSM832154,GSM832155,GSM832156,GSM832157,GSM832158,GSM832159,GSM832160,GSM832161,GSM832162,GSM832163,GSM832164,GSM832165,GSM832166,GSM832167,GSM832168,GSM832169,GSM832170,GSM832171,GSM832172,GSM832173,GSM832174,GSM832175,GSM832176,GSM832177,GSM832178,GSM832179,GSM832180,GSM832181,GSM832182,GSM832183,GSM832184,GSM1212354,GSM1212355,GSM1212356,GSM1212357,GSM1212358,GSM1212359,GSM1212360,GSM1212361,GSM1212362,GSM1212363,GSM1212364,GSM1212365,GSM1212366,GSM1212367,GSM1212368,GSM1212369,GSM1212370,GSM1212371,GSM1212372,GSM1212373,GSM1212374,GSM1212375,GSM1212376,GSM1212377
2
- Glucocorticoid_Sensitivity,89.43486,89.43486,89.43486,89.43486,95.88507,95.88507,95.88507,95.88507,95.22036,95.22036,95.22036,95.22036,92.86704,92.86704,92.86704,92.86704,93.71633,93.71633,93.71633,93.71633,96.76962,96.76962,96.76962,96.76962,88.55031,88.55031,88.55031,88.55031,90.09957,90.09957,90.09957,90.09957,94.17097,94.17097,94.17097,94.17097,86.97089,86.97089,86.97089,86.97089,98.34904,98.34904,98.34904,98.34904,91.14896,91.14896,91.14896,91.14896,8.0,24.0,8.0,24.0,8.0,24.0,8.0,24.0,8.0,24.0,8.0,24.0,24.0,8.0,24.0,8.0,24.0,8.0,24.0,8.0,24.0,8.0,24.0,8.0
3
- Age,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,44.15,44.15,24.72,24.72,32.38,32.38,20.38,20.38,21.24,21.24,22.54,22.54,26.14,26.14,21.56,21.56,21.99,21.99,26.77,26.77,23.59,23.59,23.48,23.48
4
- Gender,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0
 
1
  ,GSM832137,GSM832138,GSM832139,GSM832140,GSM832141,GSM832142,GSM832143,GSM832144,GSM832145,GSM832146,GSM832147,GSM832148,GSM832149,GSM832150,GSM832151,GSM832152,GSM832153,GSM832154,GSM832155,GSM832156,GSM832157,GSM832158,GSM832159,GSM832160,GSM832161,GSM832162,GSM832163,GSM832164,GSM832165,GSM832166,GSM832167,GSM832168,GSM832169,GSM832170,GSM832171,GSM832172,GSM832173,GSM832174,GSM832175,GSM832176,GSM832177,GSM832178,GSM832179,GSM832180,GSM832181,GSM832182,GSM832183,GSM832184,GSM1212354,GSM1212355,GSM1212356,GSM1212357,GSM1212358,GSM1212359,GSM1212360,GSM1212361,GSM1212362,GSM1212363,GSM1212364,GSM1212365,GSM1212366,GSM1212367,GSM1212368,GSM1212369,GSM1212370,GSM1212371,GSM1212372,GSM1212373,GSM1212374,GSM1212375,GSM1212376,GSM1212377
2
+ Glucocorticoid_Sensitivity,89.43486,89.43486,89.43486,89.43486,95.88507,95.88507,95.88507,95.88507,95.22036,95.22036,95.22036,95.22036,92.86704,92.86704,92.86704,92.86704,93.71633,93.71633,93.71633,93.71633,96.76962,96.76962,96.76962,96.76962,88.55031,88.55031,88.55031,88.55031,90.09957,90.09957,90.09957,90.09957,94.17097,94.17097,94.17097,94.17097,86.97089,86.97089,86.97089,86.97089,98.34904,98.34904,98.34904,98.34904,91.14896,91.14896,91.14896,91.14896,,,,,,,,,,,,,,,,,,,,,,,,
3
+ Age,44.15342,44.15342,44.15342,44.15342,24.72329,24.72329,24.72329,24.72329,32.37808,32.37808,32.37808,32.37808,20.38082,20.38082,20.38082,20.38082,21.2411,21.2411,21.2411,21.2411,22.54247,22.54247,22.54247,22.54247,26.13973,26.13973,26.13973,26.13973,21.5616,21.5616,21.5616,21.5616,21.9863,21.9863,21.9863,21.9863,26.76712,26.76712,26.76712,26.76712,23.59452,23.59452,23.59452,23.59452,23.47945,23.47945,23.47945,23.47945,,,,,,,,,,,,,,,,,,,,,,,,
 
output/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE57795.csv CHANGED
@@ -1,2 +1,2 @@
1
- Sample_0_Sensitive patient,Sample_0_Resistant patient,Sample_1_Sensitive patient,Sample_1_Resistant patient
2
- 1.0,0.0,1.0,0.0
 
1
+ ,GSM1388640,GSM1388641,GSM1388642,GSM1388643,GSM1388644,GSM1388645,GSM1388646,GSM1388647,GSM1388648,GSM1388649,GSM1388650,GSM1388651,GSM1388652,GSM1388653,GSM1388654,GSM1388655,GSM1388656,GSM1388657,GSM1388658,GSM1388659,GSM1388660,GSM1388661,GSM1388662,GSM1388663,GSM1388664,GSM1388665,GSM1388666,GSM1388667,GSM1388668,GSM1388669,GSM1388670,GSM1388671,GSM1388672,GSM1388673,GSM1388674,GSM1388675,GSM1388676,GSM1388677,GSM1388678,GSM1388679,GSM1388680,GSM1388681,GSM1388682,GSM1388683,GSM1388684,GSM1388685,GSM1388686,GSM1388687,GSM1388688,GSM1388689,GSM1388690,GSM1388691,GSM1388692,GSM1388693,GSM1388694,GSM1388695,GSM1388696,GSM1388697
2
+ Glucocorticoid_Sensitivity,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
output/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE58715.csv CHANGED
@@ -1,2 +1,2 @@
1
- Sample1,Sample2
2
- 1.0,0.0
 
1
+ ,GSM1417252,GSM1417253,GSM1417254,GSM1417255,GSM1417256,GSM1417257,GSM1417258,GSM1417259,GSM1417260,GSM1417261,GSM1417262,GSM1417263,GSM1417264,GSM1417265,GSM1417266,GSM1417267,GSM1417268,GSM1417269,GSM1417270,GSM1417271,GSM1417272,GSM1417273,GSM1417274,GSM1417275,GSM1417276,GSM1417277,GSM1417278,GSM1417279,GSM1417280,GSM1417281,GSM1417282,GSM1417283,GSM1417284,GSM1417285,GSM1417286,GSM1417287,GSM1417288,GSM1417289,GSM1417290,GSM1417291
2
+ Glucocorticoid_Sensitivity,1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,1.0,0.0,1.0,1.0,0.0
output/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE66705.csv CHANGED
@@ -1,2 +1,2 @@
1
  ,GSM1629982,GSM1629983,GSM1629984,GSM1629985,GSM1629986,GSM1629987,GSM1629988,GSM1629989,GSM1629990,GSM1629991,GSM1629992,GSM1629993,GSM1629994,GSM1629995,GSM1629996,GSM1629997,GSM1629998,GSM1629999,GSM1630000,GSM1630001,GSM1630002,GSM1630003,GSM1630004,GSM1630005,GSM1630006,GSM1630007,GSM1630008,GSM1630009,GSM1630010,GSM1630011,GSM1630012,GSM1630013,GSM1630014,GSM1630015,GSM1630016,GSM1630017,GSM1630018,GSM1630019,GSM1630020,GSM1630021,GSM1630022,GSM1630023,GSM1630024,GSM1630025,GSM1630026,GSM1630027,GSM1630028,GSM1630029,GSM1630030,GSM1630031,GSM1630032,GSM1630033,GSM1630034,GSM1630035,GSM1630036,GSM1630037,GSM1630038,GSM1630039,GSM1630040,GSM1630041,GSM1630042,GSM1630043,GSM1630044,GSM1630045,GSM1630046,GSM1630047,GSM1630048,GSM1630049,GSM1630050,GSM1630051,GSM1630052,GSM1630053,GSM1630054,GSM1630055,GSM1630056,GSM1630057,GSM1630058,GSM1630059,GSM1630060,GSM1630061,GSM1630062,GSM1630063,GSM1630064,GSM1630065,GSM1630066,GSM1630067,GSM1630068,GSM1630069,GSM1630070,GSM1630071,GSM1630072,GSM1630073,GSM1630074,GSM1630075,GSM1630076,GSM1630077,GSM1630078,GSM1630079,GSM1630080,GSM1630081,GSM1630082,GSM1630083,GSM1630084,GSM1630085,GSM1630086,GSM1630087,GSM1630088,GSM1630089,GSM1630090,GSM1630091,GSM1630092,GSM1630093,GSM1630094,GSM1630095,GSM1630096,GSM1630097,GSM1630098,GSM1630099,GSM1630100,GSM1630101,GSM1630102,GSM1630103,GSM1630104,GSM1630105,GSM1630106,GSM1630107,GSM1630108,GSM1630109,GSM1630110,GSM1630111,GSM1630112,GSM1630113,GSM1630114,GSM1630115,GSM1630116,GSM1630117,GSM1630118,GSM1630119,GSM1630120,GSM1630121,GSM1630122,GSM1630123,GSM1630124,GSM1630125,GSM1630126,GSM1630127,GSM1630128,GSM1630129,GSM1630130,GSM1630131,GSM1630132,GSM1630133,GSM1630135,GSM1630137,GSM1630139,GSM1630142,GSM1630144,GSM1630146,GSM1630149,GSM1630151,GSM1630154,GSM1630156,GSM1630158,GSM1630160,GSM1630162,GSM1630163,GSM1630164,GSM1630165,GSM1630166,GSM1630167,GSM1630168
2
- Glucocorticoid_Sensitivity,,,,,1.0,,1.0,1.0,,,,,,0.0,,,,,,0.0,1.0,,,,,,,,0.0,0.0,,,1.0,,0.0,,,,,0.0,,,1.0,0.0,1.0,0.0,,0.0,0.0,,,1.0,,,,,0.0,,,,,,,,,0.0,1.0,0.0,,,,,1.0,,,,0.0,,,,0.0,0.0,1.0,,,,0.0,0.0,0.0,1.0,,0.0,,,,0.0,,,,1.0,,0.0,,1.0,1.0,,,,,0.0,,,0.0,0.0,,,1.0,1.0,,0.0,,0.0,0.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,,0.0,0.0,1.0,1.0,0.0,0.0,0.0,,0.0,0.0,1.0,0.0,,0.0,1.0,1.0,0.0,1.0,0.0,,1.0,0.0,1.0,0.0,1.0,0.0,0.0,,0.0,0.0,0.0,,,0.0,1.0,1.0,1.0,,0.0,
 
1
  ,GSM1629982,GSM1629983,GSM1629984,GSM1629985,GSM1629986,GSM1629987,GSM1629988,GSM1629989,GSM1629990,GSM1629991,GSM1629992,GSM1629993,GSM1629994,GSM1629995,GSM1629996,GSM1629997,GSM1629998,GSM1629999,GSM1630000,GSM1630001,GSM1630002,GSM1630003,GSM1630004,GSM1630005,GSM1630006,GSM1630007,GSM1630008,GSM1630009,GSM1630010,GSM1630011,GSM1630012,GSM1630013,GSM1630014,GSM1630015,GSM1630016,GSM1630017,GSM1630018,GSM1630019,GSM1630020,GSM1630021,GSM1630022,GSM1630023,GSM1630024,GSM1630025,GSM1630026,GSM1630027,GSM1630028,GSM1630029,GSM1630030,GSM1630031,GSM1630032,GSM1630033,GSM1630034,GSM1630035,GSM1630036,GSM1630037,GSM1630038,GSM1630039,GSM1630040,GSM1630041,GSM1630042,GSM1630043,GSM1630044,GSM1630045,GSM1630046,GSM1630047,GSM1630048,GSM1630049,GSM1630050,GSM1630051,GSM1630052,GSM1630053,GSM1630054,GSM1630055,GSM1630056,GSM1630057,GSM1630058,GSM1630059,GSM1630060,GSM1630061,GSM1630062,GSM1630063,GSM1630064,GSM1630065,GSM1630066,GSM1630067,GSM1630068,GSM1630069,GSM1630070,GSM1630071,GSM1630072,GSM1630073,GSM1630074,GSM1630075,GSM1630076,GSM1630077,GSM1630078,GSM1630079,GSM1630080,GSM1630081,GSM1630082,GSM1630083,GSM1630084,GSM1630085,GSM1630086,GSM1630087,GSM1630088,GSM1630089,GSM1630090,GSM1630091,GSM1630092,GSM1630093,GSM1630094,GSM1630095,GSM1630096,GSM1630097,GSM1630098,GSM1630099,GSM1630100,GSM1630101,GSM1630102,GSM1630103,GSM1630104,GSM1630105,GSM1630106,GSM1630107,GSM1630108,GSM1630109,GSM1630110,GSM1630111,GSM1630112,GSM1630113,GSM1630114,GSM1630115,GSM1630116,GSM1630117,GSM1630118,GSM1630119,GSM1630120,GSM1630121,GSM1630122,GSM1630123,GSM1630124,GSM1630125,GSM1630126,GSM1630127,GSM1630128,GSM1630129,GSM1630130,GSM1630131,GSM1630132,GSM1630133,GSM1630135,GSM1630137,GSM1630139,GSM1630142,GSM1630144,GSM1630146,GSM1630149,GSM1630151,GSM1630154,GSM1630156,GSM1630158,GSM1630160,GSM1630162,GSM1630163,GSM1630164,GSM1630165,GSM1630166,GSM1630167,GSM1630168
2
+ Glucocorticoid_Sensitivity,,,,,0.0,,0.0,0.0,,,,,,1.0,,0.0,,,0.0,1.0,0.0,,,,,,,,1.0,1.0,,,0.0,,1.0,,,0.0,,1.0,,,0.0,1.0,0.0,1.0,,1.0,1.0,,,0.0,,,,,1.0,0.0,,,,,,0.0,,1.0,0.0,1.0,,,,0.0,0.0,0.0,,,1.0,,0.0,,1.0,1.0,0.0,,0.0,,1.0,1.0,1.0,0.0,,1.0,0.0,,,1.0,,,,0.0,,1.0,,0.0,0.0,,,,,1.0,,,1.0,1.0,0.0,0.0,0.0,0.0,,1.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,1.0,1.0,,1.0,1.0,0.0,0.0,1.0,1.0,1.0,,1.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,1.0,0.0,1.0,0.0,0.0,1.0,0.0,1.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0
output/preprocess/Glucocorticoid_Sensitivity/code/GSE15820.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Glucocorticoid_Sensitivity"
6
+ cohort = "GSE15820"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Glucocorticoid_Sensitivity"
10
+ in_cohort_dir = "../DATA/GEO/Glucocorticoid_Sensitivity/GSE15820"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/GSE15820.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/gene_data/GSE15820.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE15820.csv"
16
+ json_path = "./output/z3/preprocess/Glucocorticoid_Sensitivity/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Determine data availability based on the provided background and sample characteristics.
40
+ # This is a cell-line experiment with Affymetrix Exon 1.0 microarrays (gene expression data present),
41
+ # but no human clinical traits (age/gender) and no measurable human glucocorticoid sensitivity.
42
+ is_gene_available = True
43
+
44
+ # No human-level trait, age, or gender in this dataset
45
+ trait_row = None
46
+ age_row = None
47
+ gender_row = None
48
+
49
+ # Define converters (not used here since trait_row/age_row/gender_row are None)
50
+ def _extract_after_colon(x):
51
+ if x is None:
52
+ return None
53
+ if isinstance(x, str):
54
+ parts = x.split(":", 1)
55
+ val = parts[1].strip() if len(parts) > 1 else x.strip()
56
+ return val if val not in {"", "NA", "N/A", "na", "n/a", "null", "None"} else None
57
+ return None
58
+
59
+ def convert_trait(x):
60
+ # Not applicable here; placeholder for interface compatibility
61
+ val = _extract_after_colon(x)
62
+ return None
63
+
64
+ def convert_age(x):
65
+ val = _extract_after_colon(x)
66
+ if val is None:
67
+ return None
68
+ try:
69
+ return float(val)
70
+ except Exception:
71
+ return None
72
+
73
+ def convert_gender(x):
74
+ val = _extract_after_colon(x)
75
+ if val is None:
76
+ return None
77
+ v = val.strip().lower()
78
+ if v in {"female", "f", "girl", "woman", "women"}:
79
+ return 0
80
+ if v in {"male", "m", "boy", "man", "men"}:
81
+ return 1
82
+ return None
83
+
84
+ # Initial filtering and save metadata
85
+ is_trait_available = trait_row is not None
86
+ _ = validate_and_save_cohort_info(
87
+ is_final=False,
88
+ cohort=cohort,
89
+ info_path=json_path,
90
+ is_gene_available=is_gene_available,
91
+ is_trait_available=is_trait_available
92
+ )
93
+
94
+ # Clinical feature extraction is skipped because trait_row is None (no human clinical data available).
95
+
96
+ # Step 3: Gene Data Extraction
97
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
98
+ gene_data = get_genetic_data(matrix_file)
99
+
100
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
101
+ print(gene_data.index[:20])
102
+
103
+ # Step 4: Gene Identifier Review
104
+ requires_gene_mapping = True
105
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
106
+
107
+ # Step 5: Gene Annotation
108
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
109
+ gene_annotation = get_gene_annotation(soft_file)
110
+
111
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
112
+ print("Gene annotation preview:")
113
+ print(preview_df(gene_annotation))
114
+
115
+ # Step 6: Gene Identifier Mapping
116
+ # Decide mapping columns based on annotation preview:
117
+ # - Expression data index: IDs like '52_36n...'
118
+ # - Annotation: 'ID' column matches these probe/transcript IDs; 'symbol' contains human gene symbols.
119
+
120
+ id_col = 'ID'
121
+ gene_symbol_col = 'symbol'
122
+
123
+ # 2. Build mapping dataframe: probe/transcript ID -> gene symbol
124
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=id_col, gene_col=gene_symbol_col)
125
+
126
+ # 3. Apply mapping to convert probe-level data to gene-level expression
127
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
128
+
129
+ # Step 7: Data Normalization and Linking
130
+ # Normalize and save gene expression data; skip linking since no clinical trait is available
131
+
132
+ import os
133
+
134
+ # 1. Normalize gene symbols and save
135
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
136
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
137
+ normalized_gene_data.to_csv(out_gene_data_file)
138
+
139
+ # 2. No clinical data available to link
140
+ linked_data = None
141
+
142
+ # 5. Final quality validation and save cohort info (trait unavailable)
143
+ is_usable = validate_and_save_cohort_info(
144
+ is_final=True,
145
+ cohort=cohort,
146
+ info_path=json_path,
147
+ is_gene_available=True,
148
+ is_trait_available=False,
149
+ is_biased=False,
150
+ df=normalized_gene_data.T, # pass a non-empty df to avoid abnormality override
151
+ note="INFO: Cell-line series without human trait/age/gender; no linked dataset created."
152
+ )
153
+
154
+ # 6. No saving of linked data since dataset is unusable for association analysis (no trait)
output/preprocess/Glucocorticoid_Sensitivity/code/GSE32962.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Glucocorticoid_Sensitivity"
6
+ cohort = "GSE32962"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Glucocorticoid_Sensitivity"
10
+ in_cohort_dir = "../DATA/GEO/Glucocorticoid_Sensitivity/GSE32962"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/GSE32962.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/gene_data/GSE32962.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE32962.csv"
16
+ json_path = "./output/z3/preprocess/Glucocorticoid_Sensitivity/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+ import pandas as pd
42
+
43
+ # 1) Gene expression data availability (expression profiles; not miRNA/methylation)
44
+ is_gene_available = True
45
+
46
+ # 2) Variable availability from the sample characteristics dictionary
47
+ # trait: prednisolone sensitivity (glucocorticoid sensitivity) at key 4
48
+ trait_row = 4
49
+
50
+ # age: "< 1 year of age" for all samples -> constant, treat as unavailable
51
+ age_row = None
52
+
53
+ # gender: not present
54
+ gender_row = None
55
+
56
+ # 2.2) Data type conversions
57
+ def convert_trait(v):
58
+ if v is None or (isinstance(v, float) and pd.isna(v)):
59
+ return None
60
+ s = str(v)
61
+ if ':' in s:
62
+ s = s.split(':', 1)[1]
63
+ s = s.strip().lower()
64
+ # Map glucocorticoid (prednisolone) sensitivity to binary: sensitive=1, resistant=0
65
+ if s in {'sensitive', 'responder', 'responsive', 'good responder'}:
66
+ return 1
67
+ if s in {'resistant', 'nonresponder', 'non-responder', 'non responder', 'poor responder'}:
68
+ return 0
69
+ return None
70
+
71
+ def convert_age(v):
72
+ # Not used because age_row is None
73
+ return None
74
+
75
+ def convert_gender(v):
76
+ # Not used because gender_row is None
77
+ return None
78
+
79
+ # 3) Initial filtering and save metadata
80
+ is_trait_available = trait_row is not None
81
+ _ = validate_and_save_cohort_info(
82
+ is_final=False,
83
+ cohort=cohort,
84
+ info_path=json_path,
85
+ is_gene_available=is_gene_available,
86
+ is_trait_available=is_trait_available
87
+ )
88
+
89
+ # 4) Clinical feature extraction (only if trait is available)
90
+ if trait_row is not None:
91
+ selected_clinical_df = geo_select_clinical_features(
92
+ clinical_df=clinical_data,
93
+ trait=trait,
94
+ trait_row=trait_row,
95
+ convert_trait=convert_trait,
96
+ age_row=age_row,
97
+ convert_age=None,
98
+ gender_row=gender_row,
99
+ convert_gender=None
100
+ )
101
+ clinical_preview = preview_df(selected_clinical_df)
102
+ print(clinical_preview)
103
+
104
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
105
+ selected_clinical_df.to_csv(out_clinical_data_file)
106
+
107
+ # Step 3: Gene Data Extraction
108
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
109
+ gene_data = get_genetic_data(matrix_file)
110
+
111
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
112
+ print(gene_data.index[:20])
113
+
114
+ # Step 4: Gene Identifier Review
115
+ # Affymetrix probe set IDs detected (e.g., '1007_s_at', '1053_at'), not human gene symbols
116
+ requires_gene_mapping = True
117
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
118
+
119
+ # Step 5: Gene Annotation
120
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
121
+ gene_annotation = get_gene_annotation(soft_file)
122
+
123
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
124
+ print("Gene annotation preview:")
125
+ print(preview_df(gene_annotation))
126
+
127
+ # Step 6: Gene Identifier Mapping
128
+ # 1. Identify the appropriate columns for mapping: probe IDs ('ID') and gene symbols ('Gene Symbol')
129
+ probe_col = 'ID'
130
+ gene_symbol_col = 'Gene Symbol'
131
+
132
+ # 2. Create the mapping dataframe
133
+ gene_mapping = get_gene_mapping(annotation=gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
134
+
135
+ # 3. Apply the mapping to convert probe-level data to gene-level expression
136
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=gene_mapping)
137
+
138
+ # Step 7: Data Normalization and Linking
139
+ import os
140
+ import pandas as pd
141
+
142
+ # 1. Normalize the obtained gene data and save
143
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
144
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
145
+ normalized_gene_data.to_csv(out_gene_data_file)
146
+
147
+ # Ensure clinical data is available in scope; reload if necessary
148
+ if 'selected_clinical_df' not in locals() or selected_clinical_df is None:
149
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
150
+
151
+ # 2. Link the clinical and genetic data
152
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
153
+
154
+ # 3. Handle missing values
155
+ linked_data = handle_missing_values(linked_data, trait)
156
+
157
+ # 4. Determine bias and remove biased demographic features if needed
158
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
159
+
160
+ # 5. Final quality validation and save cohort info
161
+ note = "INFO: Age not available (all infants <1 year); Gender not provided. Affymetrix probe mapping applied and gene symbols normalized."
162
+ is_usable = validate_and_save_cohort_info(
163
+ is_final=True,
164
+ cohort=cohort,
165
+ info_path=json_path,
166
+ is_gene_available=True,
167
+ is_trait_available=True,
168
+ is_biased=is_trait_biased,
169
+ df=unbiased_linked_data,
170
+ note=note
171
+ )
172
+
173
+ # 6. Save linked data if usable
174
+ if is_usable:
175
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
176
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Glucocorticoid_Sensitivity/code/GSE33649.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Glucocorticoid_Sensitivity"
6
+ cohort = "GSE33649"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Glucocorticoid_Sensitivity"
10
+ in_cohort_dir = "../DATA/GEO/Glucocorticoid_Sensitivity/GSE33649"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/GSE33649.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/gene_data/GSE33649.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE33649.csv"
16
+ json_path = "./output/z3/preprocess/Glucocorticoid_Sensitivity/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+
42
+ # 1) Availability
43
+ is_gene_available = True # Transcriptome-wide response indicates gene expression data is available.
44
+
45
+ # 2) Variable availability (from the provided Sample Characteristics Dictionary)
46
+ trait_row = 3 # "in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): <float>"
47
+ age_row = 6 # "age (years): <float>"
48
+ gender_row = 5 # "gender: female/male"
49
+
50
+ # 2.2) Converters
51
+ def _after_colon(val):
52
+ if val is None:
53
+ return None
54
+ if isinstance(val, str):
55
+ parts = val.split(":", 1)
56
+ return parts[1].strip() if len(parts) > 1 else val.strip()
57
+ return str(val).strip()
58
+
59
+ def _to_float(val):
60
+ if val is None:
61
+ return None
62
+ s = _after_colon(val)
63
+ if s is None:
64
+ return None
65
+ s = s.strip()
66
+ # Extract a numeric token robustly
67
+ m = re.search(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?', s)
68
+ if not m:
69
+ return None
70
+ try:
71
+ return float(m.group(0))
72
+ except Exception:
73
+ return None
74
+
75
+ def convert_trait(x):
76
+ # Glucocorticoid sensitivity (LGS - % inhibition by dex); continuous
77
+ return _to_float(x)
78
+
79
+ def convert_age(x):
80
+ # Age in years; continuous
81
+ return _to_float(x)
82
+
83
+ def convert_gender(x):
84
+ # Gender; binary: female -> 0, male -> 1
85
+ s = _after_colon(x)
86
+ if s is None:
87
+ return None
88
+ s = s.strip().lower()
89
+ if s in {"female", "f", "woman", "women"}:
90
+ return 0
91
+ if s in {"male", "m", "man", "men"}:
92
+ return 1
93
+ if s in {"na", "n/a", "unknown", "not available", "null", ""}:
94
+ return None
95
+ return None
96
+
97
+ # 3) Initial filtering metadata
98
+ is_trait_available = trait_row is not None
99
+ _ = validate_and_save_cohort_info(
100
+ is_final=False,
101
+ cohort=cohort,
102
+ info_path=json_path,
103
+ is_gene_available=is_gene_available,
104
+ is_trait_available=is_trait_available
105
+ )
106
+
107
+ # 4) Clinical feature extraction
108
+ if trait_row is not None:
109
+ selected_clinical_df = geo_select_clinical_features(
110
+ clinical_df=clinical_data,
111
+ trait=trait,
112
+ trait_row=trait_row,
113
+ convert_trait=convert_trait,
114
+ age_row=age_row,
115
+ convert_age=convert_age,
116
+ gender_row=gender_row,
117
+ convert_gender=convert_gender
118
+ )
119
+
120
+ clinical_preview = preview_df(selected_clinical_df, n=5)
121
+ print("Clinical data preview:", clinical_preview)
122
+
123
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
124
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
125
+
126
+ # Step 3: Gene Data Extraction
127
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
128
+ gene_data = get_genetic_data(matrix_file)
129
+
130
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
131
+ print(gene_data.index[:20])
132
+
133
+ # Step 4: Gene Identifier Review
134
+ print("requires_gene_mapping = True")
135
+
136
+ # Step 5: Gene Annotation
137
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
138
+ gene_annotation = get_gene_annotation(soft_file)
139
+
140
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
141
+ print("Gene annotation preview:")
142
+ print(preview_df(gene_annotation))
143
+
144
+ # Step 6: Gene Identifier Mapping
145
+ # Determine appropriate columns for probe IDs and gene symbols based on annotation preview
146
+ probe_col = 'ID'
147
+ symbol_candidates = ['Symbol', 'ILMN_Gene', 'Gene Symbol', 'GeneSymbol', 'GENE_SYMBOL']
148
+ gene_col = next((c for c in symbol_candidates if c in gene_annotation.columns), None)
149
+ if gene_col is None:
150
+ raise ValueError(f"No suitable gene symbol column found in gene_annotation. Available columns: {list(gene_annotation.columns)}")
151
+
152
+ # 2) Build mapping dataframe (probe -> gene symbol)
153
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_col)
154
+
155
+ # 3) Apply mapping to convert probe-level data to gene-level data
156
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
157
+
158
+ # Step 7: Data Normalization and Linking
159
+ import os
160
+
161
+ # 1. Normalize gene symbols and save
162
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
163
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
164
+ normalized_gene_data.to_csv(out_gene_data_file)
165
+
166
+ # 2. Link clinical and genetic data
167
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
168
+
169
+ # 3. Handle missing values
170
+ linked_data = handle_missing_values(linked_data, trait)
171
+
172
+ # 4. Bias assessment and removal of biased demographics
173
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
174
+
175
+ # 5. Final validation and save cohort info
176
+ note = "INFO: ILMN probes mapped to gene symbols via 'Symbol'; LGS used as continuous trait; Age and Gender included."
177
+ is_usable = validate_and_save_cohort_info(
178
+ True, cohort, json_path, True, True, is_trait_biased, unbiased_linked_data, note=note
179
+ )
180
+
181
+ # 6. Save linked data if usable
182
+ if is_usable:
183
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
184
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Glucocorticoid_Sensitivity/code/GSE42002.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Glucocorticoid_Sensitivity"
6
+ cohort = "GSE42002"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Glucocorticoid_Sensitivity"
10
+ in_cohort_dir = "../DATA/GEO/Glucocorticoid_Sensitivity/GSE42002"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/GSE42002.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/gene_data/GSE42002.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE42002.csv"
16
+ json_path = "./output/z3/preprocess/Glucocorticoid_Sensitivity/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Determine data availability based on provided background and sample characteristics
40
+ is_gene_available = True # mRNA expression arrays are mentioned in the summary
41
+
42
+ # No explicit or inferable per-subject glucocorticoid sensitivity variable in sample characteristics
43
+ trait_row = None # Glucocorticoid_Sensitivity not explicitly available
44
+ age_row = None # No age information in sample characteristics
45
+ gender_row = None # No gender information in sample characteristics
46
+
47
+ # Conversion functions
48
+ def _extract_value(cell):
49
+ if cell is None:
50
+ return None
51
+ s = str(cell).strip()
52
+ # Typical format "key: value"
53
+ if ':' in s:
54
+ s = s.split(':', 1)[1].strip()
55
+ return s if s != '' else None
56
+
57
+ def convert_trait(cell):
58
+ # Trait not available for this dataset; return None for any input
59
+ return None
60
+
61
+ def convert_age(cell):
62
+ s = _extract_value(cell)
63
+ if s is None:
64
+ return None
65
+ # Extract the first number (integer or float) from the string
66
+ import re
67
+ m = re.search(r'(-?\d+(\.\d+)?)', s)
68
+ if m:
69
+ try:
70
+ return float(m.group(1))
71
+ except Exception:
72
+ return None
73
+ return None
74
+
75
+ def convert_gender(cell):
76
+ s = _extract_value(cell)
77
+ if s is None:
78
+ return None
79
+ s_low = s.lower()
80
+ if s_low in {'male', 'm', 'man', 'boy'}:
81
+ return 1
82
+ if s_low in {'female', 'f', 'woman', 'girl'}:
83
+ return 0
84
+ return None
85
+
86
+ # Initial filtering and save metadata
87
+ is_trait_available = trait_row is not None
88
+ _ = validate_and_save_cohort_info(
89
+ is_final=False,
90
+ cohort=cohort,
91
+ info_path=json_path,
92
+ is_gene_available=is_gene_available,
93
+ is_trait_available=is_trait_available
94
+ )
95
+
96
+ # Clinical feature extraction: only if trait_row is available (skip here since trait_row is None)
97
+ if trait_row is not None:
98
+ selected_clinical_df = geo_select_clinical_features(
99
+ clinical_df=clinical_data,
100
+ trait=trait,
101
+ trait_row=trait_row,
102
+ convert_trait=convert_trait,
103
+ age_row=age_row,
104
+ convert_age=convert_age,
105
+ gender_row=gender_row,
106
+ convert_gender=convert_gender
107
+ )
108
+ _ = preview_df(selected_clinical_df, n=5)
109
+ # Ensure directory exists and save
110
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
111
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
112
+
113
+ # Step 3: Gene Data Extraction
114
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
115
+ gene_data = get_genetic_data(matrix_file)
116
+
117
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
118
+ print(gene_data.index[:20])
119
+
120
+ # Step 4: Gene Identifier Review
121
+ print("requires_gene_mapping = True")
122
+
123
+ # Step 5: Gene Annotation
124
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
125
+ gene_annotation = get_gene_annotation(soft_file)
126
+
127
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
128
+ print("Gene annotation preview:")
129
+ print(preview_df(gene_annotation))
130
+
131
+ # Step 6: Gene Identifier Mapping
132
+ # Identify the appropriate columns for probe IDs and gene symbols from the annotation preview
133
+ probe_col = 'ID' # e.g., 'ILMN_1343291'
134
+ gene_col = 'Symbol' # human gene symbols
135
+
136
+ # Build mapping dataframe (ID -> Gene)
137
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_col)
138
+
139
+ # Map probe-level data to gene-level expression
140
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
141
+
142
+ # Step 7: Data Normalization and Linking
143
+ import os
144
+
145
+ # 1. Normalize the obtained gene data and save to file
146
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
147
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
148
+ normalized_gene_data.to_csv(out_gene_data_file)
149
+
150
+ # 2-6. Proceed only if clinical features (including trait) were extracted earlier
151
+ if 'selected_clinical_data' in globals():
152
+ # Link clinical and genetic data
153
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
154
+
155
+ # Handle missing values
156
+ linked_data = handle_missing_values(linked_data, trait)
157
+
158
+ # Bias evaluation
159
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
160
+
161
+ # Final validation and cohort info saving
162
+ is_usable = validate_and_save_cohort_info(
163
+ is_final=True,
164
+ cohort=cohort,
165
+ info_path=json_path,
166
+ is_gene_available=True,
167
+ is_trait_available=True,
168
+ is_biased=is_trait_biased,
169
+ df=unbiased_linked_data,
170
+ note="INFO: Proceeded with full pipeline as clinical trait data was available."
171
+ )
172
+
173
+ # Save linked data only if usable
174
+ if is_usable:
175
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
176
+ unbiased_linked_data.to_csv(out_data_file)
177
+ else:
178
+ # Trait/clinical data unavailable; record (or reaffirm) initial metadata only
179
+ _ = validate_and_save_cohort_info(
180
+ is_final=False,
181
+ cohort=cohort,
182
+ info_path=json_path,
183
+ is_gene_available=True,
184
+ is_trait_available=False
185
+ )
output/preprocess/Glucocorticoid_Sensitivity/code/GSE48801.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Glucocorticoid_Sensitivity"
6
+ cohort = "GSE48801"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Glucocorticoid_Sensitivity"
10
+ in_cohort_dir = "../DATA/GEO/Glucocorticoid_Sensitivity/GSE48801"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/GSE48801.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/gene_data/GSE48801.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE48801.csv"
16
+ json_path = "./output/z3/preprocess/Glucocorticoid_Sensitivity/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+
42
+ # 1) Gene expression data availability
43
+ is_gene_available = True # Transcriptome-wide response to GCs indicates gene expression data (not miRNA/methylation)
44
+
45
+ # 2) Variable availability and conversion functions
46
+
47
+ # From provided characteristics:
48
+ # 0 -> treatment condition (not used as a clinical covariate here)
49
+ # 1 -> in vitro lymphocyte GC sensitivity (LGS - % inhibition by dex) -> our trait
50
+ trait_row = 1
51
+ age_row = None
52
+ gender_row = None
53
+
54
+ def _get_value_after_colon(x):
55
+ if x is None:
56
+ return None
57
+ try:
58
+ # Take the substring after the last colon, common in GEO annotations
59
+ val = str(x).split(':')[-1].strip()
60
+ return val if val != '' else None
61
+ except Exception:
62
+ return None
63
+
64
+ def convert_trait(x):
65
+ # LGS is continuous (% inhibition by dex)
66
+ val = _get_value_after_colon(x)
67
+ if val is None:
68
+ return None
69
+ # Extract the first float-like number
70
+ m = re.search(r'-?\d+(?:\.\d+)?', val)
71
+ if m:
72
+ try:
73
+ return float(m.group(0))
74
+ except Exception:
75
+ return None
76
+ return None
77
+
78
+ def convert_age(x):
79
+ # Not available for this dataset, but define for completeness
80
+ val = _get_value_after_colon(x)
81
+ if val is None:
82
+ return None
83
+ # Extract age number if present
84
+ m = re.search(r'\d+(?:\.\d+)?', val)
85
+ if m:
86
+ try:
87
+ return float(m.group(0))
88
+ except Exception:
89
+ return None
90
+ return None
91
+
92
+ def convert_gender(x):
93
+ # Not available for this dataset, but define for completeness
94
+ val = _get_value_after_colon(x)
95
+ if val is None:
96
+ return None
97
+ s = val.strip().lower()
98
+ if s in {'female', 'f', 'woman', 'girl'}:
99
+ return 0
100
+ if s in {'male', 'm', 'man', 'boy'}:
101
+ return 1
102
+ if s == '0':
103
+ return 0
104
+ if s == '1':
105
+ return 1
106
+ if s in {'na', 'n/a', 'unknown', 'undet', 'undetermined', '-', ''}:
107
+ return None
108
+ return None
109
+
110
+ # 3) Save metadata - initial filtering
111
+ is_trait_available = trait_row is not None
112
+ _ = validate_and_save_cohort_info(
113
+ is_final=False,
114
+ cohort=cohort,
115
+ info_path=json_path,
116
+ is_gene_available=is_gene_available,
117
+ is_trait_available=is_trait_available
118
+ )
119
+
120
+ # 4) Clinical Feature Extraction (only if trait_row is available)
121
+ if trait_row is not None:
122
+ selected_clinical_df = geo_select_clinical_features(
123
+ clinical_df=clinical_data,
124
+ trait=trait,
125
+ trait_row=trait_row,
126
+ convert_trait=convert_trait,
127
+ age_row=age_row,
128
+ convert_age=convert_age if age_row is not None else None,
129
+ gender_row=gender_row,
130
+ convert_gender=convert_gender if gender_row is not None else None
131
+ )
132
+ # Preview
133
+ print(preview_df(selected_clinical_df, n=5))
134
+
135
+ # Ensure directory exists and save
136
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
137
+ selected_clinical_df.to_csv(out_clinical_data_file)
138
+
139
+ # Step 3: Gene Data Extraction
140
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
141
+ gene_data = get_genetic_data(matrix_file)
142
+
143
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
144
+ print(gene_data.index[:20])
145
+
146
+ # Step 4: Gene Identifier Review
147
+ requires_gene_mapping = True
148
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
149
+
150
+ # Step 5: Gene Annotation
151
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
152
+ gene_annotation = get_gene_annotation(soft_file)
153
+
154
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
155
+ print("Gene annotation preview:")
156
+ print(preview_df(gene_annotation))
157
+
158
+ # Step 6: Gene Identifier Mapping
159
+ # Determine appropriate columns for mapping:
160
+ # - Probe identifiers in expression data: "ILMN_..." -> corresponds to 'ID' in gene_annotation
161
+ # - Gene symbols in annotation: corresponds to 'Symbol'
162
+
163
+ # In case gene_annotation is not in scope (robustness), reload it
164
+ try:
165
+ gene_annotation
166
+ except NameError:
167
+ gene_annotation = get_gene_annotation(soft_file)
168
+
169
+ # 2) Build mapping dataframe
170
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')
171
+
172
+ # 3) Apply mapping: convert probe-level data to gene-level expression
173
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
174
+
175
+ # Step 7: Data Normalization and Linking
176
+ import os
177
+ import pandas as pd
178
+
179
+ # 1. Normalize gene symbols and save
180
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
181
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
182
+ normalized_gene_data.to_csv(out_gene_data_file)
183
+
184
+ # 2. Link clinical and genetic data
185
+ # Ensure clinical dataframe is available; if not, load it from file
186
+ try:
187
+ selected_clinical_df
188
+ except NameError:
189
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
190
+
191
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
192
+
193
+ # Determine availability flags before missing-value handling
194
+ pre_mv_is_gene_available = (normalized_gene_data.shape[0] > 0 and normalized_gene_data.shape[1] > 0)
195
+ pre_mv_is_trait_available = trait in linked_data.columns
196
+
197
+ # 3. Handle missing values
198
+ linked_data = handle_missing_values(linked_data, trait)
199
+
200
+ # 4. Bias evaluation and removal of biased demographic features
201
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
202
+
203
+ # 5. Final validation and save cohort info
204
+ note = ("INFO: LGS is continuous; each donor appears to contribute multiple GSMs under different treatments, "
205
+ "sharing identical LGS values across those replicates.")
206
+ is_usable = validate_and_save_cohort_info(
207
+ is_final=True,
208
+ cohort=cohort,
209
+ info_path=json_path,
210
+ is_gene_available=pre_mv_is_gene_available,
211
+ is_trait_available=pre_mv_is_trait_available,
212
+ is_biased=is_trait_biased,
213
+ df=unbiased_linked_data,
214
+ note=note
215
+ )
216
+
217
+ # 6. Save linked dataset if usable
218
+ if is_usable:
219
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
220
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Glucocorticoid_Sensitivity/code/GSE50012.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Glucocorticoid_Sensitivity"
6
+ cohort = "GSE50012"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Glucocorticoid_Sensitivity"
10
+ in_cohort_dir = "../DATA/GEO/Glucocorticoid_Sensitivity/GSE50012"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/GSE50012.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/gene_data/GSE50012.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE50012.csv"
16
+ json_path = "./output/z3/preprocess/Glucocorticoid_Sensitivity/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+ import pandas as pd
42
+
43
+ # 1) Gene expression availability (based on background: expression profiling of PBMCs with steroids)
44
+ is_gene_available = True
45
+
46
+ # 2) Variable availability inferred from Sample Characteristics Dictionary:
47
+ # Trait (Glucocorticoid_Sensitivity): row 3 contains "in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): <value>"
48
+ trait_row = 3
49
+
50
+ # Age: use the row that is purely ages to avoid mixing with gender; row 6 fits this
51
+ age_row = 6
52
+
53
+ # Gender: gender entries appear to align with a different GSM subset than the trait.
54
+ # To avoid adding a mostly-missing feature for the trait samples, set to None.
55
+ gender_row = None
56
+
57
+ # 2.2) Converters
58
+ def _after_colon(val: str) -> str:
59
+ if val is None:
60
+ return ""
61
+ parts = val.rsplit(":", 1)
62
+ return parts[1].strip() if len(parts) == 2 else val.strip()
63
+
64
+ def convert_trait(x):
65
+ # Expect strings like "in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 95.22036"
66
+ if not isinstance(x, str):
67
+ return None
68
+ s = x.lower()
69
+ if "gc sensitivity" in s or "glucocorticoid" in s:
70
+ v = _after_colon(x)
71
+ try:
72
+ return float(v)
73
+ except:
74
+ m = re.search(r"[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?", v)
75
+ return float(m.group(0)) if m else None
76
+ return None
77
+
78
+ def convert_age(x):
79
+ # Expect strings like "age (years): 24.72"
80
+ if not isinstance(x, str):
81
+ return None
82
+ if "age" in x.lower():
83
+ v = _after_colon(x)
84
+ try:
85
+ return float(v)
86
+ except:
87
+ m = re.search(r"[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?", v)
88
+ return float(m.group(0)) if m else None
89
+ return None
90
+
91
+ def convert_gender(x):
92
+ # Expect strings like "gender: female" or "gender: male"
93
+ if not isinstance(x, str):
94
+ return None
95
+ s = x.lower()
96
+ if "gender" in s:
97
+ v = _after_colon(s)
98
+ if "female" in v:
99
+ return 0
100
+ if "male" in v:
101
+ return 1
102
+ if v in {"na", "n/a", "unknown", ""}:
103
+ return None
104
+ return None
105
+
106
+ # 3) Save metadata with initial filtering
107
+ is_trait_available = trait_row is not None
108
+ _ = validate_and_save_cohort_info(
109
+ is_final=False,
110
+ cohort=cohort,
111
+ info_path=json_path,
112
+ is_gene_available=is_gene_available,
113
+ is_trait_available=is_trait_available
114
+ )
115
+
116
+ # 4) Clinical feature extraction if trait is available
117
+ if trait_row is not None:
118
+ selected_clinical_df = geo_select_clinical_features(
119
+ clinical_df=clinical_data,
120
+ trait=trait,
121
+ trait_row=trait_row,
122
+ convert_trait=convert_trait,
123
+ age_row=age_row,
124
+ convert_age=convert_age,
125
+ gender_row=gender_row,
126
+ convert_gender=convert_gender
127
+ )
128
+ preview = preview_df(selected_clinical_df, n=5)
129
+ print("Clinical features preview:", preview)
130
+
131
+ # Save clinical data
132
+ out_dir = os.path.dirname(out_clinical_data_file)
133
+ os.makedirs(out_dir, exist_ok=True)
134
+ selected_clinical_df.to_csv(out_clinical_data_file)
135
+
136
+ # Step 3: Gene Data Extraction
137
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
138
+ gene_data = get_genetic_data(matrix_file)
139
+
140
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
141
+ print(gene_data.index[:20])
142
+
143
+ # Step 4: Gene Identifier Review
144
+ print("requires_gene_mapping = True")
145
+
146
+ # Step 5: Gene Annotation
147
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
148
+ gene_annotation = get_gene_annotation(soft_file)
149
+
150
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
151
+ print("Gene annotation preview:")
152
+ print(preview_df(gene_annotation))
153
+
154
+ # Step 6: Gene Identifier Mapping
155
+ # Decide the columns for probe IDs and gene symbols based on the annotation preview
156
+ probe_col = 'ID'
157
+ gene_symbol_candidates = ['Symbol', 'ILMN_Gene']
158
+ gene_col = next((c for c in gene_symbol_candidates if c in gene_annotation.columns), None)
159
+ if gene_col is None:
160
+ raise ValueError("No suitable gene symbol column found in gene annotation.")
161
+
162
+ # Build mapping dataframe
163
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_col)
164
+
165
+ # Apply mapping to convert probe-level data to gene-level expression
166
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
167
+
168
+ # Step 7: Data Normalization and Linking
169
+ import os
170
+
171
+ # 1. Normalize gene symbols and save
172
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
173
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
174
+ normalized_gene_data.to_csv(out_gene_data_file)
175
+
176
+ # 2. Link clinical and genetic data
177
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
178
+
179
+ # 3. Handle missing values
180
+ linked_data = handle_missing_values(linked_data, trait)
181
+
182
+ # 4. Determine bias and remove biased demographic features
183
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
184
+
185
+ # Compute availability flags for final validation as Python bools
186
+ is_gene_available_final = bool((normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0))
187
+ is_trait_available_final = bool((trait in linked_data.columns) and (len(linked_data) > 0) and (linked_data[trait].notna().sum() > 0))
188
+
189
+ # 5. Final validation and save cohort info
190
+ note = ("INFO: Trait values (GC sensitivity) are available only for a subset of samples (dexamethasone-treated PBMCs). "
191
+ "Gender was unavailable/aligned for trait subset and was omitted.")
192
+ is_usable = validate_and_save_cohort_info(
193
+ is_final=True,
194
+ cohort=cohort,
195
+ info_path=json_path,
196
+ is_gene_available=is_gene_available_final,
197
+ is_trait_available=is_trait_available_final,
198
+ is_biased=bool(is_trait_biased),
199
+ df=unbiased_linked_data,
200
+ note=note
201
+ )
202
+
203
+ # 6. Conditionally save linked data
204
+ if is_usable:
205
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
206
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Glucocorticoid_Sensitivity/code/GSE57795.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Glucocorticoid_Sensitivity"
6
+ cohort = "GSE57795"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Glucocorticoid_Sensitivity"
10
+ in_cohort_dir = "../DATA/GEO/Glucocorticoid_Sensitivity/GSE57795"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/GSE57795.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/gene_data/GSE57795.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE57795.csv"
16
+ json_path = "./output/z3/preprocess/Glucocorticoid_Sensitivity/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+ import pandas as pd
42
+
43
+ # 1) Gene expression availability
44
+ is_gene_available = True # Illumina HumanWG-6 v3 Expression BeadChips (gene expression microarray)
45
+
46
+ # 2) Determine availability rows from Sample Characteristics Dictionary:
47
+ # trait -> 'dexamethasone response' (Sensitive vs Resistant) at row 5
48
+ trait_row = 5
49
+
50
+ # Age and Gender (human) are not available in this PDX mouse dataset
51
+ age_row = None
52
+ gender_row = None
53
+
54
+ # 2.2) Converters
55
+ def _extract_value(x):
56
+ if x is None or (isinstance(x, float) and pd.isna(x)):
57
+ return None
58
+ s = str(x)
59
+ # Extract substring after the first colon if present
60
+ if ':' in s:
61
+ s = s.split(':', 1)[1]
62
+ return s.strip()
63
+
64
+ def convert_trait(x):
65
+ val = _extract_value(x)
66
+ if val is None:
67
+ return None
68
+ s = val.lower()
69
+ # Map sensitivity/resistance; accept synonyms 'good/poor responder'
70
+ if ('sensitive' in s) or ('good' in s and 'respond' in s):
71
+ return 1
72
+ if ('resistant' in s) or ('poor' in s and 'respond' in s):
73
+ return 0
74
+ return None
75
+
76
+ def convert_age(x):
77
+ # Not used (no human age available). Generic parser that converts to years if possible.
78
+ val = _extract_value(x)
79
+ if val is None:
80
+ return None
81
+ s = val.lower()
82
+ # Find first number (can be a range like 6-10; take mean)
83
+ # and unit among years/months/weeks/days
84
+ num = None
85
+ # Handle ranges like "6-10 weeks"
86
+ m_range = re.search(r'(\d+(?:\.\d+)?)\s*[-–]\s*(\d+(?:\.\d+)?)', s)
87
+ if m_range:
88
+ a = float(m_range.group(1))
89
+ b = float(m_range.group(2))
90
+ num = 0.5 * (a + b)
91
+ else:
92
+ m_num = re.search(r'(\d+(?:\.\d+)?)', s)
93
+ if m_num:
94
+ num = float(m_num.group(1))
95
+ if num is None:
96
+ return None
97
+ # Detect unit
98
+ if 'year' in s or 'yr' in s or 'y/o' in s or 'y ' in s:
99
+ years = num
100
+ elif 'month' in s or 'mo' in s:
101
+ years = num / 12.0
102
+ elif 'week' in s or 'wk' in s or 'w ' in s:
103
+ years = num / 52.0
104
+ elif 'day' in s or 'd ' in s:
105
+ years = num / 365.0
106
+ else:
107
+ # Unknown unit; return as-is
108
+ years = num
109
+ # Typically we want continuous numeric
110
+ return years
111
+
112
+ def convert_gender(x):
113
+ val = _extract_value(x)
114
+ if val is None:
115
+ return None
116
+ s = val.strip().lower()
117
+ # Map to 0/1 (female=0, male=1)
118
+ if s in ['male', 'm', 'man', 'boy']:
119
+ return 1
120
+ if s in ['female', 'f', 'woman', 'girl']:
121
+ return 0
122
+ return None
123
+
124
+ # 3) Save metadata (initial filtering)
125
+ is_trait_available = trait_row is not None
126
+ _ = validate_and_save_cohort_info(
127
+ is_final=False,
128
+ cohort=cohort,
129
+ info_path=json_path,
130
+ is_gene_available=is_gene_available,
131
+ is_trait_available=is_trait_available
132
+ )
133
+
134
+ # 4) Clinical Feature Extraction (only if trait is available)
135
+ if trait_row is not None:
136
+ selected_clinical_df = geo_select_clinical_features(
137
+ clinical_df=clinical_data,
138
+ trait=trait,
139
+ trait_row=trait_row,
140
+ convert_trait=convert_trait,
141
+ age_row=age_row,
142
+ convert_age=convert_age,
143
+ gender_row=gender_row,
144
+ convert_gender=convert_gender
145
+ )
146
+ preview_selected = preview_df(selected_clinical_df, n=5)
147
+ # Ensure output directory exists and save
148
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
149
+ selected_clinical_df.to_csv(out_clinical_data_file)
150
+ preview_selected
151
+
152
+ # Step 3: Gene Data Extraction
153
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
154
+ gene_data = get_genetic_data(matrix_file)
155
+
156
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
157
+ print(gene_data.index[:20])
158
+
159
+ # Step 4: Gene Identifier Review
160
+ # ILMN_* identifiers are Illumina probe IDs, not human gene symbols.
161
+ requires_gene_mapping = True
162
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
163
+
164
+ # Step 5: Gene Annotation
165
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
166
+ gene_annotation = get_gene_annotation(soft_file)
167
+
168
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
169
+ print("Gene annotation preview:")
170
+ print(preview_df(gene_annotation))
171
+
172
+ # Step 6: Gene Identifier Mapping
173
+ # Identify the appropriate columns for mapping: probe IDs and gene symbols
174
+ probe_col = 'ID' # Matches ILMN_* probe identifiers in the expression matrix
175
+ gene_symbol_col = 'Symbol' # Gene symbols
176
+
177
+ # 2. Build mapping dataframe
178
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
179
+
180
+ # 3. Apply mapping to convert probe-level data to gene-level expression
181
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
182
+
183
+ # Step 7: Data Normalization and Linking
184
+ import os
185
+
186
+ # 1. Normalize gene symbols and save normalized gene data
187
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
188
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
189
+ normalized_gene_data.to_csv(out_gene_data_file)
190
+
191
+ # 2. Link the clinical and genetic data
192
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
193
+
194
+ # 3. Handle missing values
195
+ linked_data = handle_missing_values(linked_data, trait)
196
+
197
+ # 4. Bias checks and remove biased demographic features if any
198
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
199
+
200
+ # 5. Final validation and save cohort metadata
201
+ is_usable = validate_and_save_cohort_info(
202
+ is_final=True,
203
+ cohort=cohort,
204
+ info_path=json_path,
205
+ is_gene_available=True,
206
+ is_trait_available=True,
207
+ is_biased=is_trait_biased,
208
+ df=unbiased_linked_data,
209
+ note="INFO: PDX dataset; human Age/Gender unavailable."
210
+ )
211
+
212
+ # 6. Save linked data if usable
213
+ if is_usable:
214
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
215
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Glucocorticoid_Sensitivity/code/GSE58715.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Glucocorticoid_Sensitivity"
6
+ cohort = "GSE58715"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Glucocorticoid_Sensitivity"
10
+ in_cohort_dir = "../DATA/GEO/Glucocorticoid_Sensitivity/GSE58715"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/GSE58715.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/gene_data/GSE58715.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE58715.csv"
16
+ json_path = "./output/z3/preprocess/Glucocorticoid_Sensitivity/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import pandas as pd
41
+
42
+ # 1) Gene expression data availability
43
+ is_gene_available = True # mRNA gene expression study with hormone treatment per design
44
+
45
+ # 2) Variable availability and converters
46
+ # Trait is inferred from hormone treatment status (dexamethasone vs ethanol)
47
+ trait_row = 2 # 'hormone' field
48
+ age_row = None # not human subjects
49
+ gender_row = None # not human subjects
50
+
51
+ def convert_trait(x):
52
+ if pd.isna(x):
53
+ return None
54
+ s = str(x)
55
+ if ':' in s:
56
+ s = s.split(':', 1)[1]
57
+ s = s.strip().lower()
58
+ # Map dexamethasone exposure to 1, ethanol control to 0
59
+ if s.startswith('dexamethasone') or s.startswith('dex'):
60
+ return 1
61
+ if s.startswith('ethanol') or s in {'etoh', 'control'}:
62
+ return 0
63
+ return None
64
+
65
+ def convert_age(x):
66
+ # No human age data available in this cell line study
67
+ return None
68
+
69
+ def convert_gender(x):
70
+ # No human gender data available in this cell line study
71
+ return None
72
+
73
+ # 3) Initial filtering and save metadata
74
+ is_trait_available = trait_row is not None
75
+ _ = validate_and_save_cohort_info(
76
+ is_final=False,
77
+ cohort=cohort,
78
+ info_path=json_path,
79
+ is_gene_available=is_gene_available,
80
+ is_trait_available=is_trait_available
81
+ )
82
+
83
+ # 4) Clinical feature extraction (only if trait is available)
84
+ if trait_row is not None:
85
+ selected_clinical_df = geo_select_clinical_features(
86
+ clinical_df=clinical_data,
87
+ trait=trait,
88
+ trait_row=trait_row,
89
+ convert_trait=convert_trait,
90
+ age_row=age_row,
91
+ convert_age=convert_age,
92
+ gender_row=gender_row,
93
+ convert_gender=convert_gender
94
+ )
95
+ preview = preview_df(selected_clinical_df)
96
+
97
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
98
+ selected_clinical_df.to_csv(out_clinical_data_file)
99
+
100
+ # Step 3: Gene Data Extraction
101
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
102
+ gene_data = get_genetic_data(matrix_file)
103
+
104
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
105
+ print(gene_data.index[:20])
106
+
107
+ # Step 4: Gene Identifier Review
108
+ print("requires_gene_mapping = True")
109
+
110
+ # Step 5: Gene Annotation
111
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
112
+ gene_annotation = get_gene_annotation(soft_file)
113
+
114
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
115
+ print("Gene annotation preview:")
116
+ print(preview_df(gene_annotation))
117
+
118
+ # Step 6: Gene Identifier Mapping
119
+ # 1-2. Decide columns for probe IDs and gene symbols, and extract the mapping dataframe
120
+ probe_col = 'ID' # Matches probe identifiers like 'ILMN_1343291'
121
+ gene_symbol_col = 'Symbol' # Contains gene symbols
122
+
123
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
124
+
125
+ # 3. Apply the mapping to convert probe-level data to gene-level expression
126
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
127
+
128
+ # Step 7: Data Normalization and Linking
129
+ import os
130
+ import pandas as pd
131
+
132
+ # 1. Normalize gene symbols and save
133
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
134
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
135
+ normalized_gene_data.to_csv(out_gene_data_file)
136
+
137
+ # 2. Link clinical and genetic data
138
+ # Ensure clinical data is available in this step
139
+ if 'selected_clinical_df' not in globals():
140
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
141
+
142
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
143
+
144
+ # 3. Handle missing values
145
+ linked_data = handle_missing_values(linked_data, trait)
146
+
147
+ # 4. Assess bias and remove biased covariates
148
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
149
+
150
+ # 5. Final validation and save cohort info
151
+ is_gene_available = normalized_gene_data.shape[0] > 0
152
+ is_trait_available = trait in linked_data.columns
153
+
154
+ note = "INFO: Cell line study with hormone treatment; Age/Gender not applicable."
155
+ is_usable = validate_and_save_cohort_info(
156
+ is_final=True,
157
+ cohort=cohort,
158
+ info_path=json_path,
159
+ is_gene_available=is_gene_available,
160
+ is_trait_available=is_trait_available,
161
+ is_biased=is_trait_biased,
162
+ df=unbiased_linked_data,
163
+ note=note
164
+ )
165
+
166
+ # 6. Save linked data if usable
167
+ if is_usable:
168
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
169
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Glucocorticoid_Sensitivity/code/GSE65645.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Glucocorticoid_Sensitivity"
6
+ cohort = "GSE65645"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Glucocorticoid_Sensitivity"
10
+ in_cohort_dir = "../DATA/GEO/Glucocorticoid_Sensitivity/GSE65645"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/GSE65645.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/gene_data/GSE65645.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE65645.csv"
16
+ json_path = "./output/z3/preprocess/Glucocorticoid_Sensitivity/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+ import pandas as pd
41
+
42
+ # 1) Gene expression availability (lncRNA expression on Agilent arrays is acceptable transcriptomic data)
43
+ is_gene_available = True
44
+
45
+ # 2) Variable availability based on provided Sample Characteristics Dictionary:
46
+ # {0: ['sample_type: bone marrow'], 1: ['translocation: E2A_PBX1', 'translocation: MLL', 'translocation: TEL_AML1']}
47
+ # No explicit or inferable Glucocorticoid_Sensitivity, Age, or Gender fields are present or variable.
48
+ trait_row = None
49
+ age_row = None
50
+ gender_row = None
51
+
52
+ # 2.2) Converters
53
+ def _extract_after_colon(x):
54
+ if x is None:
55
+ return None
56
+ s = str(x)
57
+ parts = s.split(":", 1)
58
+ val = parts[1] if len(parts) == 2 else parts[0]
59
+ return val.strip()
60
+
61
+ def convert_trait(x):
62
+ # Binary: 1 = sensitive/responder, 0 = resistant/non-responder; unknown -> None
63
+ val = _extract_after_colon(x)
64
+ if val is None or val == "":
65
+ return None
66
+ s = val.lower()
67
+ # Positive patterns
68
+ pos_patterns = [
69
+ "sensitive", "responder", "responsive", "good response", "good-responder", "good_responder",
70
+ "prednisone sensitive", "prednisolone sensitive", "high sensitivity", "sensitive to prednisone",
71
+ "r" # common shorthand, resolve later if ambiguous
72
+ ]
73
+ # Negative patterns
74
+ neg_patterns = [
75
+ "resistant", "non-responder", "nonresponder", "non responsive", "non-responsive",
76
+ "poor response", "refractory", "prednisone resistant", "prednisolone resistant",
77
+ "low sensitivity", "nr" # common shorthand
78
+ ]
79
+ # Heuristic resolution: check explicit negations before generic substrings to avoid collisions
80
+ for pat in neg_patterns:
81
+ if pat in s and not re.search(r'\b(r)\b', s): # avoid misclassifying isolated 'r' that could mean responder
82
+ return 0
83
+ for pat in pos_patterns:
84
+ if pat in s:
85
+ # If 'r' matched, ensure it's not 'nr'
86
+ if pat == "r" and ("nr" in s or "non-responder" in s or "nonresponder" in s):
87
+ continue
88
+ return 1
89
+ # Short codes exactly equal to labels
90
+ if s.strip() in {"r", "responder"}:
91
+ return 1
92
+ if s.strip() in {"nr", "non-responder", "nonresponder"}:
93
+ return 0
94
+ return None
95
+
96
+ def convert_age(x):
97
+ val = _extract_after_colon(x)
98
+ if val is None or val == "":
99
+ return None
100
+ s = val.lower()
101
+ # Extract first floating number as age in years
102
+ m = re.search(r'[-+]?\d*\.?\d+', s)
103
+ if m:
104
+ try:
105
+ return float(m.group())
106
+ except Exception:
107
+ return None
108
+ return None
109
+
110
+ def convert_gender(x):
111
+ val = _extract_after_colon(x)
112
+ if val is None or val == "":
113
+ return None
114
+ s = val.strip().lower()
115
+ if s in {"female", "f", "woman", "girl"}:
116
+ return 0
117
+ if s in {"male", "m", "man", "boy"}:
118
+ return 1
119
+ # Numeric coding already
120
+ if s in {"0", "1"}:
121
+ return int(s)
122
+ return None
123
+
124
+ # 3) Save metadata (initial filtering)
125
+ is_trait_available = trait_row is not None
126
+ _ = validate_and_save_cohort_info(
127
+ is_final=False,
128
+ cohort=cohort,
129
+ info_path=json_path,
130
+ is_gene_available=is_gene_available,
131
+ is_trait_available=is_trait_available
132
+ )
133
+
134
+ # 4) Clinical feature extraction (skip since trait_row is None)
135
+ if is_trait_available and 'clinical_data' in locals():
136
+ selected_clinical_df = geo_select_clinical_features(
137
+ clinical_df=clinical_data,
138
+ trait=trait,
139
+ trait_row=trait_row,
140
+ convert_trait=convert_trait,
141
+ age_row=age_row,
142
+ convert_age=convert_age,
143
+ gender_row=gender_row,
144
+ convert_gender=convert_gender
145
+ )
146
+ _ = preview_df(selected_clinical_df)
147
+ # Save
148
+ out_dir = os.path.dirname(out_clinical_data_file)
149
+ os.makedirs(out_dir, exist_ok=True)
150
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
151
+
152
+ # Step 3: Gene Data Extraction
153
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
154
+ gene_data = get_genetic_data(matrix_file)
155
+
156
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
157
+ print(gene_data.index[:20])
158
+
159
+ # Step 4: Gene Identifier Review
160
+ requires_gene_mapping = True
161
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
162
+
163
+ # Step 5: Gene Annotation
164
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
165
+ gene_annotation = get_gene_annotation(soft_file)
166
+
167
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
168
+ print("Gene annotation preview:")
169
+ print(preview_df(gene_annotation))
170
+
171
+ # Step 6: Gene Identifier Mapping
172
+ # Identify appropriate columns for probe IDs and gene symbols
173
+ probe_col = 'ID'
174
+ candidate_gene_cols = ['GENE_SYMBOL', 'GENE', 'GENE_NAME']
175
+ available_gene_cols = [c for c in candidate_gene_cols if c in gene_annotation.columns]
176
+
177
+ # Select the gene symbol column with the most non-null entries
178
+ if available_gene_cols:
179
+ non_null_counts = {c: gene_annotation[c].notna().sum() for c in available_gene_cols}
180
+ gene_col = max(non_null_counts, key=non_null_counts.get)
181
+ else:
182
+ raise ValueError("No suitable gene symbol column found in gene annotation.")
183
+
184
+ # Build mapping dataframe
185
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_col)
186
+
187
+ # Apply mapping to convert probe-level data to gene-level expression
188
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
output/preprocess/Glucocorticoid_Sensitivity/code/GSE66705.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Glucocorticoid_Sensitivity"
6
+ cohort = "GSE66705"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Glucocorticoid_Sensitivity"
10
+ in_cohort_dir = "../DATA/GEO/Glucocorticoid_Sensitivity/GSE66705"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/GSE66705.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/gene_data/GSE66705.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE66705.csv"
16
+ json_path = "./output/z3/preprocess/Glucocorticoid_Sensitivity/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+ import pandas as pd
42
+
43
+ # 1) Gene expression availability based on background ("Gene expression profiling" on HG-U133_Plus_2 platform)
44
+ is_gene_available = True
45
+
46
+ # 2) Identify rows in the sample characteristics dictionary
47
+ # Provided dictionary:
48
+ # {0: ['predlc50group: #N/A', 'predlc50group: SEN', 'predlc50group: RES', 'predlc50group: INT'],
49
+ # 1: ['lin: B', 'lin: T']}
50
+ trait_row = 0 # 'predlc50group' reflects glucocorticoid sensitivity categories
51
+ age_row = None # Not available
52
+ gender_row = None # Not available
53
+
54
+ # 2.2) Converters
55
+ def convert_trait(x):
56
+ if x is None or (isinstance(x, float) and pd.isna(x)):
57
+ return None
58
+ v = str(x).split(':', 1)[-1].strip().lower()
59
+ if v in {'#n/a', 'na', 'n/a', 'nan', ''}:
60
+ return None
61
+ # Map to binary sensitivity: SEN -> 1 (sensitive); RES/INT -> 0 (non-sensitive)
62
+ if v in {'sen', 'sensitive'}:
63
+ return 1
64
+ if v in {'res', 'resistant', 'int', 'intermediate'}:
65
+ return 0
66
+ return None
67
+
68
+ def convert_age(x):
69
+ if x is None or (isinstance(x, float) and pd.isna(x)):
70
+ return None
71
+ v = str(x).split(':', 1)[-1].strip().lower()
72
+ if v in {'#n/a', 'na', 'n/a', 'nan', ''}:
73
+ return None
74
+ m = re.search(r'[-+]?\d*\.?\d+', v)
75
+ if not m:
76
+ return None
77
+ try:
78
+ return float(m.group())
79
+ except Exception:
80
+ return None
81
+
82
+ def convert_gender(x):
83
+ if x is None or (isinstance(x, float) and pd.isna(x)):
84
+ return None
85
+ v = str(x).split(':', 1)[-1].strip().lower()
86
+ if v in {'#n/a', 'na', 'n/a', 'nan', ''}:
87
+ return None
88
+ if v in {'female', 'f', 'girl', 'woman', 'women'}:
89
+ return 0
90
+ if v in {'male', 'm', 'boy', 'man', 'men'}:
91
+ return 1
92
+ return None
93
+
94
+ # 3) Initial filtering and save metadata
95
+ is_trait_available = trait_row is not None
96
+ _ = validate_and_save_cohort_info(
97
+ is_final=False,
98
+ cohort=cohort,
99
+ info_path=json_path,
100
+ is_gene_available=is_gene_available,
101
+ is_trait_available=is_trait_available
102
+ )
103
+
104
+ # 4) Clinical feature extraction (only if trait data available)
105
+ if trait_row is not None:
106
+ selected_clinical_df = geo_select_clinical_features(
107
+ clinical_df=clinical_data,
108
+ trait=trait,
109
+ trait_row=trait_row,
110
+ convert_trait=convert_trait,
111
+ age_row=age_row,
112
+ convert_age=None,
113
+ gender_row=gender_row,
114
+ convert_gender=None
115
+ )
116
+ preview = preview_df(selected_clinical_df, n=5)
117
+ print(preview)
118
+
119
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
120
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
121
+
122
+ # Step 3: Gene Data Extraction
123
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
124
+ gene_data = get_genetic_data(matrix_file)
125
+
126
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
127
+ print(gene_data.index[:20])
128
+
129
+ # Step 4: Gene Identifier Review
130
+ requires_gene_mapping = True
131
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
132
+
133
+ # Step 5: Gene Annotation
134
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
135
+ gene_annotation = get_gene_annotation(soft_file)
136
+
137
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
138
+ print("Gene annotation preview:")
139
+ print(preview_df(gene_annotation))
140
+
141
+ # Step 6: Gene Identifier Mapping
142
+ # Decide the appropriate columns for probe IDs and gene symbols based on the annotation preview
143
+ probe_col = 'ID' # Matches probe IDs like '1007_s_at'
144
+ gene_symbol_col = 'Gene Symbol' # Contains gene symbols (may include multiple symbols per probe)
145
+
146
+ # 2) Build mapping dataframe from annotation
147
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
148
+
149
+ # 3) Apply mapping to convert probe-level data to gene-level expression
150
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
151
+
152
+ # Step 7: Data Normalization and Linking
153
+ import os
154
+
155
+ # 1. Normalize gene symbols and save normalized gene expression data
156
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
157
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
158
+ normalized_gene_data.to_csv(out_gene_data_file)
159
+
160
+ # 2. Link the clinical and genetic data
161
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
162
+
163
+ # Derive availability indicators from actual data before downstream processing (ensure pure Python bools)
164
+ is_gene_available = bool((normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0))
165
+ is_trait_available = bool((trait in linked_data.columns) and bool(linked_data[trait].notna().any()))
166
+
167
+ # 3. Handle missing values
168
+ linked_data = handle_missing_values(linked_data, trait)
169
+
170
+ # 4. Assess bias and remove biased demographic features
171
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
172
+ is_trait_biased = bool(is_trait_biased) # ensure pure Python bool
173
+
174
+ # 5. Final validation and save cohort info
175
+ # Pre-create JSON file to avoid creation-branch quirks
176
+ os.makedirs(os.path.dirname(json_path), exist_ok=True)
177
+ if not os.path.exists(json_path):
178
+ with open(json_path, "w") as f:
179
+ f.write("{}")
180
+
181
+ note = "INFO: Trait derived from 'predlc50group' (SEN=1, RES/INT=0). No age or gender available."
182
+ is_usable = validate_and_save_cohort_info(
183
+ is_final=True,
184
+ cohort=cohort,
185
+ info_path=json_path,
186
+ is_gene_available=bool(is_gene_available),
187
+ is_trait_available=bool(is_trait_available),
188
+ is_biased=bool(is_trait_biased),
189
+ df=unbiased_linked_data,
190
+ note=note
191
+ )
192
+
193
+ # 6. Save linked data if usable
194
+ if is_usable:
195
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
196
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Glucocorticoid_Sensitivity/code/TCGA.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Glucocorticoid_Sensitivity"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/TCGA.csv"
12
+ out_gene_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z3/preprocess/Glucocorticoid_Sensitivity/clinical_data/TCGA.csv"
14
+ json_path = "./output/z3/preprocess/Glucocorticoid_Sensitivity/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import pandas as pd
20
+
21
+ # List subdirectories in TCGA root
22
+ subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
23
+
24
+ # Identify directories related to the trait "Glucocorticoid_Sensitivity"
25
+ trait_keywords = [
26
+ "glucocorticoid", "corticosteroid", "cortisol", "dexamethasone", "prednis", "methylpred", "hydrocortisone"
27
+ ]
28
+ matches = [d for d in subdirs if any(k in d.lower() for k in trait_keywords)]
29
+
30
+ if len(matches) == 0:
31
+ # No suitable directory found; mark as skipped and complete
32
+ validate_and_save_cohort_info(
33
+ is_final=False,
34
+ cohort="TCGA",
35
+ info_path=json_path,
36
+ is_gene_available=False,
37
+ is_trait_available=False
38
+ )
39
+ else:
40
+ # Choose the most specific match (shortest name as a proxy)
41
+ selected_dir = sorted(matches, key=len)[0]
42
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
43
+
44
+ # Get file paths
45
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
46
+
47
+ # Load data
48
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False)
49
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False)
50
+
51
+ # Print clinical column names
52
+ print(list(clinical_df.columns))
output/preprocess/Head_and_Neck_Cancer/GSE201777.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Head_and_Neck_Cancer/clinical_data/GSE151181.csv CHANGED
@@ -1,2 +1,2 @@
1
  ,GSM4567912,GSM4567913,GSM4567914,GSM4567915,GSM4567916,GSM4567917,GSM4567918,GSM4567919,GSM4567920,GSM4567921,GSM4567922,GSM4567923,GSM4567924,GSM4567925,GSM4567926,GSM4567927,GSM4567928,GSM4567929,GSM4567930,GSM4567931,GSM4567932,GSM4567933,GSM4567934,GSM4567935,GSM4567936,GSM4567937,GSM4567938,GSM4567939,GSM4567940,GSM4567941,GSM4567942,GSM4567943,GSM4567944,GSM4567945,GSM4567946,GSM4567947,GSM4567948,GSM4567949,GSM4567950,GSM4567951,GSM4567952,GSM4567953,GSM4567954,GSM4567955,GSM4567956,GSM4567957,GSM4567958,GSM4567959,GSM4567960,GSM4567961,GSM4567962,GSM4567963
2
- Head_and_Neck_Cancer,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0
 
1
  ,GSM4567912,GSM4567913,GSM4567914,GSM4567915,GSM4567916,GSM4567917,GSM4567918,GSM4567919,GSM4567920,GSM4567921,GSM4567922,GSM4567923,GSM4567924,GSM4567925,GSM4567926,GSM4567927,GSM4567928,GSM4567929,GSM4567930,GSM4567931,GSM4567932,GSM4567933,GSM4567934,GSM4567935,GSM4567936,GSM4567937,GSM4567938,GSM4567939,GSM4567940,GSM4567941,GSM4567942,GSM4567943,GSM4567944,GSM4567945,GSM4567946,GSM4567947,GSM4567948,GSM4567949,GSM4567950,GSM4567951,GSM4567952,GSM4567953,GSM4567954,GSM4567955,GSM4567956,GSM4567957,GSM4567958,GSM4567959,GSM4567960,GSM4567961,GSM4567962,GSM4567963
2
+ Head_and_Neck_Cancer,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
output/preprocess/Head_and_Neck_Cancer/clinical_data/GSE201777.csv CHANGED
@@ -1,2 +1,2 @@
1
- GSM6071161,GSM6071162,GSM6071163,GSM6071164,GSM6071165,GSM6071166,GSM6071167,GSM6071168,GSM6071169,GSM6071170,GSM6071171,GSM6071172,GSM6071173,GSM6071174,GSM6071175,GSM6071176,GSM6071177,GSM6071178,GSM6071179,GSM6071180,GSM6071181,GSM6071182,GSM6071183,GSM6071184,GSM6071185,GSM6071186,GSM6071187,GSM6071188,GSM6071189,GSM6071190,GSM6071191,GSM6071192,GSM6071193,GSM6071194,GSM6071195,GSM6071196,GSM6071197,GSM6071198,GSM6071199,GSM6071200,GSM6071201,GSM6071202,GSM6071203,GSM6071204,GSM6071205,GSM6071206,GSM6071207
2
- 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0
 
1
+ ,GSM6071161,GSM6071162,GSM6071163,GSM6071164,GSM6071165,GSM6071166,GSM6071167,GSM6071168,GSM6071169,GSM6071170,GSM6071171,GSM6071172,GSM6071173,GSM6071174,GSM6071175,GSM6071176,GSM6071177,GSM6071178,GSM6071179,GSM6071180,GSM6071181,GSM6071182,GSM6071183,GSM6071184,GSM6071185,GSM6071186,GSM6071187,GSM6071188,GSM6071189,GSM6071190,GSM6071191,GSM6071192,GSM6071193,GSM6071194,GSM6071195,GSM6071196,GSM6071197,GSM6071198,GSM6071199,GSM6071200,GSM6071201,GSM6071202,GSM6071203,GSM6071204,GSM6071205,GSM6071206,GSM6071207
2
+ Head_and_Neck_Cancer,,1.0,0.0,0.0,1.0,,1.0,0.0,,1.0,0.0,,1.0,,0.0,,0.0,1.0,1.0,0.0,,,1.0,0.0,1.0,,0.0,0.0,,0.0,1.0,,0.0,1.0,,1.0,,0.0,1.0,0.0,,,0.0,1.0,1.0,0.0,
output/preprocess/Head_and_Neck_Cancer/clinical_data/GSE244580.csv CHANGED
@@ -1,2 +1,2 @@
1
- GSM7820913,GSM7820914,GSM7820915,GSM7820916,GSM7820917,GSM7820918,GSM7820919,GSM7820920,GSM7820921,GSM7820922,GSM7820923,GSM7820924,GSM7820925,GSM7820926,GSM7820927,GSM7820928,GSM7820929,GSM7820930,GSM7820931,GSM7820932,GSM7820933,GSM7820934,GSM7820935,GSM7820936,GSM7820937,GSM7820938,GSM7820939,GSM7820940,GSM7820941,GSM7820942
2
- 0.0,0.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0
 
1
+ ,GSM7820913,GSM7820914,GSM7820915,GSM7820916,GSM7820917,GSM7820918,GSM7820919,GSM7820920,GSM7820921,GSM7820922,GSM7820923,GSM7820924,GSM7820925,GSM7820926,GSM7820927,GSM7820928,GSM7820929,GSM7820930,GSM7820931,GSM7820932,GSM7820933,GSM7820934,GSM7820935,GSM7820936,GSM7820937,GSM7820938,GSM7820939,GSM7820940,GSM7820941,GSM7820942
2
+ Head_and_Neck_Cancer,0.0,0.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0
output/preprocess/Head_and_Neck_Cancer/code/GSE104006.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Head_and_Neck_Cancer"
6
+ cohort = "GSE104006"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Head_and_Neck_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Head_and_Neck_Cancer/GSE104006"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/GSE104006.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/gene_data/GSE104006.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/clinical_data/GSE104006.csv"
16
+ json_path = "./output/z3/preprocess/Head_and_Neck_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+
42
+ # 1. Gene Expression Data Availability
43
+ # Title indicates both miRNA and gene expression profiling; assume gene expression is available for this cohort.
44
+ is_gene_available = True
45
+
46
+ # 2. Variable Availability and Data Type Conversion
47
+ # Sample Characteristics Dictionary keys inferred from the provided preview:
48
+ trait_row = 0 # disease: Thyroid_carcinoma vs Non-neoplastic_thyroid
49
+ age_row = 2 # age: numeric values
50
+ gender_row = 3 # Sex: F/M
51
+
52
+ def convert_trait(v):
53
+ if v is None:
54
+ return None
55
+ val = str(v).split(":", 1)[-1].strip().lower().replace(" ", "_").replace("-", "_")
56
+ # Map cancer vs non-cancer
57
+ if val in {"thyroid_carcinoma", "carcinoma", "cancer", "tumor"}:
58
+ return 1
59
+ if val in {"non_neoplastic_thyroid", "non_neoplastic", "normal", "control", "benign"}:
60
+ return 0
61
+ return None
62
+
63
+ def convert_age(v):
64
+ if v is None:
65
+ return None
66
+ s = str(v).split(":", 1)[-1].strip()
67
+ s_lower = s.lower()
68
+ if s_lower in {"", "na", "n/a", "nan", "none", "unknown"}:
69
+ return None
70
+ m = re.search(r"-?\d+\.?\d*", s)
71
+ if not m:
72
+ return None
73
+ try:
74
+ x = float(m.group())
75
+ return x
76
+ except Exception:
77
+ return None
78
+
79
+ def convert_gender(v):
80
+ if v is None:
81
+ return None
82
+ val = str(v).split(":", 1)[-1].strip().lower()
83
+ if val in {"female", "f", "woman", "w"}:
84
+ return 0
85
+ if val in {"male", "m", "man"}:
86
+ return 1
87
+ return None
88
+
89
+ # 3. Save Metadata (initial filtering)
90
+ is_trait_available = trait_row is not None
91
+ _ = validate_and_save_cohort_info(
92
+ is_final=False,
93
+ cohort=cohort,
94
+ info_path=json_path,
95
+ is_gene_available=is_gene_available,
96
+ is_trait_available=is_trait_available
97
+ )
98
+
99
+ # 4. Clinical Feature Extraction (only if clinical data is available)
100
+ if trait_row is not None:
101
+ selected_clinical_df = geo_select_clinical_features(
102
+ clinical_df=clinical_data,
103
+ trait=trait,
104
+ trait_row=trait_row,
105
+ convert_trait=convert_trait,
106
+ age_row=age_row,
107
+ convert_age=convert_age,
108
+ gender_row=gender_row,
109
+ convert_gender=convert_gender
110
+ )
111
+ clinical_preview = preview_df(selected_clinical_df)
112
+
113
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
114
+ selected_clinical_df.to_csv(out_clinical_data_file)
115
+
116
+ # Step 3: Gene Data Extraction
117
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
118
+ gene_data = get_genetic_data(matrix_file)
119
+
120
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
121
+ print(gene_data.index[:20])
122
+
123
+ # Step 4: Gene Identifier Review
124
+ requires_gene_mapping = True
125
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
126
+
127
+ # Step 5: Gene Annotation
128
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
129
+ gene_annotation = get_gene_annotation(soft_file)
130
+
131
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
132
+ print("Gene annotation preview:")
133
+ print(preview_df(gene_annotation))
output/preprocess/Head_and_Neck_Cancer/code/GSE148320.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Head_and_Neck_Cancer"
6
+ cohort = "GSE148320"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Head_and_Neck_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Head_and_Neck_Cancer/GSE148320"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/GSE148320.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/gene_data/GSE148320.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/clinical_data/GSE148320.csv"
16
+ json_path = "./output/z3/preprocess/Head_and_Neck_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Determine availability based on provided background and sample characteristics
40
+ is_gene_available = True # Gene expression profiling is likely (xenograft/cell line expression), not miRNA/methylation.
41
+ trait_row = None # No human trait variability; all are tumor xenograft/cell line samples (constant for our trait).
42
+ age_row = None # No human age information present.
43
+ gender_row = None # No human gender information present.
44
+
45
+ # Conversion helpers (defined for completeness; they won't be used since rows are None)
46
+ def _extract_value(x):
47
+ if x is None:
48
+ return None
49
+ s = str(x)
50
+ parts = s.split(":", 1)
51
+ return parts[1].strip() if len(parts) == 2 else s.strip()
52
+
53
+ def convert_trait(x):
54
+ v = _extract_value(x)
55
+ if v is None:
56
+ return None
57
+ v_low = v.lower()
58
+ # Generic mapping if ever applicable
59
+ if any(k in v_low for k in ["normal", "control", "healthy", "adjacent normal", "benign"]):
60
+ return 0
61
+ if any(k in v_low for k in ["cancer", "tumor", "tumour", "carcinoma", "malignant", "hnscc", "head and neck"]):
62
+ return 1
63
+ return None
64
+
65
+ def convert_age(x):
66
+ v = _extract_value(x)
67
+ if v is None:
68
+ return None
69
+ # Extract first numeric (years assumed)
70
+ import re
71
+ m = re.search(r"(\d+(\.\d+)?)", v)
72
+ return float(m.group(1)) if m else None
73
+
74
+ def convert_gender(x):
75
+ v = _extract_value(x)
76
+ if v is None:
77
+ return None
78
+ v_low = v.lower()
79
+ if v_low in ["male", "m"]:
80
+ return 1
81
+ if v_low in ["female", "f"]:
82
+ return 0
83
+ return None
84
+
85
+ # Initial filtering metadata save
86
+ is_trait_available = trait_row is not None
87
+ _ = validate_and_save_cohort_info(
88
+ is_final=False,
89
+ cohort=cohort,
90
+ info_path=json_path,
91
+ is_gene_available=is_gene_available,
92
+ is_trait_available=is_trait_available
93
+ )
94
+
95
+ # Clinical feature extraction is skipped because trait_row is None (no usable human clinical data).
96
+ if trait_row is not None:
97
+ selected_clinical_df = geo_select_clinical_features(
98
+ clinical_df=clinical_data,
99
+ trait=trait,
100
+ trait_row=trait_row,
101
+ convert_trait=convert_trait,
102
+ age_row=age_row,
103
+ convert_age=convert_age,
104
+ gender_row=gender_row,
105
+ convert_gender=convert_gender
106
+ )
107
+ clinical_preview = preview_df(selected_clinical_df)
108
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
109
+ selected_clinical_df.to_csv(out_clinical_data_file)
110
+
111
+ # Step 3: Gene Data Extraction
112
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
113
+ gene_data = get_genetic_data(matrix_file)
114
+
115
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
116
+ print(gene_data.index[:20])
117
+
118
+ # Step 4: Gene Identifier Review
119
+ requires_gene_mapping = True
120
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
121
+
122
+ # Step 5: Gene Annotation
123
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
124
+ gene_annotation = get_gene_annotation(soft_file)
125
+
126
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
127
+ print("Gene annotation preview:")
128
+ print(preview_df(gene_annotation))
129
+
130
+ # Step 6: Gene Identifier Mapping
131
+ # Identify the appropriate columns in the annotation: probe IDs and gene symbols
132
+ probe_col = 'ID'
133
+ gene_symbol_col = 'Gene Symbol'
134
+
135
+ # 1-2. Build mapping dataframe from annotation
136
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
137
+
138
+ # 3. Apply mapping to convert probe-level data to gene-level expression
139
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
output/preprocess/Head_and_Neck_Cancer/code/GSE151179.py ADDED
@@ -0,0 +1,1518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Head_and_Neck_Cancer"
6
+ cohort = "GSE151179"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Head_and_Neck_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Head_and_Neck_Cancer/GSE151179"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/GSE151179.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/gene_data/GSE151179.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/clinical_data/GSE151179.csv"
16
+ json_path = "./output/z3/preprocess/Head_and_Neck_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import pandas as pd
41
+
42
+ # 1. Gene Expression Data Availability
43
+ is_gene_available = True # Gene expression profiling with Thermo Fisher Human Clariom S Assay
44
+
45
+ # 2. Variable Availability and Data Type Conversion
46
+
47
+ # Trait: Use 'tissue type' to distinguish cancer vs non-neoplastic thyroid
48
+ trait_row = 1 # 'tissue type' field varies across samples and can indicate cancer presence
49
+ age_row = None
50
+ gender_row = None
51
+
52
+ def _extract_value(cell):
53
+ if cell is None or (isinstance(cell, float) and pd.isna(cell)):
54
+ return None
55
+ s = str(cell)
56
+ if ':' in s:
57
+ s = s.split(':', 1)[1]
58
+ return s.strip()
59
+
60
+ def convert_trait(cell):
61
+ val = _extract_value(cell)
62
+ if val is None:
63
+ return None
64
+ v = val.lower()
65
+ # Controls
66
+ if 'non-neoplastic' in v:
67
+ return 0
68
+ # Cancer (tumor/metastasis)
69
+ if ('tumor' in v) or ('metastasis' in v):
70
+ return 1
71
+ return None
72
+
73
+ # 3. Save Metadata (initial filtering)
74
+ is_trait_available = trait_row is not None
75
+ _ = validate_and_save_cohort_info(
76
+ is_final=False,
77
+ cohort=cohort,
78
+ info_path=json_path,
79
+ is_gene_available=is_gene_available,
80
+ is_trait_available=is_trait_available
81
+ )
82
+
83
+ # 4. Clinical Feature Extraction (only if clinical data is available)
84
+ if trait_row is not None:
85
+ selected_clinical_df = geo_select_clinical_features(
86
+ clinical_df=clinical_data,
87
+ trait=trait,
88
+ trait_row=trait_row,
89
+ convert_trait=convert_trait,
90
+ age_row=age_row,
91
+ gender_row=gender_row
92
+ )
93
+ preview = preview_df(selected_clinical_df)
94
+
95
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
96
+ selected_clinical_df.to_csv(out_clinical_data_file)
97
+
98
+ # Step 3: Gene Data Extraction
99
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
100
+ gene_data = get_genetic_data(matrix_file)
101
+
102
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
103
+ print(gene_data.index[:20])
104
+
105
+ # Step 4: Gene Identifier Review
106
+ requires_gene_mapping = True
107
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
108
+
109
+ # Step 5: Gene Annotation
110
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
111
+ gene_annotation = get_gene_annotation(soft_file)
112
+
113
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
114
+ print("Gene annotation preview:")
115
+ print(preview_df(gene_annotation))
116
+
117
+ # Step 6: Gene Identifier Mapping
118
+ import re
119
+ import pandas as pd
120
+
121
+ # Keep a copy of the raw expression data
122
+ expr_df = gene_data.copy()
123
+ exp_ids = set(expr_df.index.astype(str))
124
+
125
+ def normalize_id_values(series: pd.Series) -> set:
126
+ # Build a set of candidate IDs from a column using multiple normalization heuristics
127
+ vals = series.astype(str).fillna("").str.strip()
128
+ id_set = set()
129
+ # 1) raw and strip trailing .0
130
+ stripped = vals.str.replace(r'\.0$', '', regex=True)
131
+ id_set.update(stripped.tolist())
132
+ # 2) only keep pure digits
133
+ id_set.update([s for s in stripped.tolist() if s.isdigit()])
134
+ # 3) extract long digit groups (length >= 7) from strings
135
+ for s in stripped:
136
+ for g in re.findall(r'\d+', s):
137
+ if len(g) >= 7:
138
+ id_set.add(g)
139
+ return id_set
140
+
141
+ # 1) Decide which annotation column matches the expression IDs
142
+ overlaps = []
143
+ for col in gene_annotation.columns:
144
+ try:
145
+ ann_id_set = normalize_id_values(gene_annotation[col])
146
+ overlap = len(exp_ids & ann_id_set)
147
+ overlaps.append((col, overlap))
148
+ except Exception:
149
+ continue
150
+
151
+ # Sort columns by overlap
152
+ overlaps.sort(key=lambda x: x[1], reverse=True)
153
+
154
+ # Pick the best ID column with the largest overlap
155
+ best_id_col, best_overlap = (overlaps[0] if overlaps else (None, 0))
156
+
157
+ # If the best overlap is zero, try a few common candidate columns explicitly in case they exist
158
+ if best_overlap == 0:
159
+ explicit_candidates = [
160
+ 'transcript_cluster_id', 'TRANSCRIPT_CLUSTER_ID', 'cluster_id',
161
+ 'probeset_id', 'ProbeSetID', 'PROBESET_ID', 'ID'
162
+ ]
163
+ for cand in explicit_candidates:
164
+ if cand in gene_annotation.columns:
165
+ ann_id_set = normalize_id_values(gene_annotation[cand])
166
+ overlap = len(exp_ids & ann_id_set)
167
+ if overlap > best_overlap:
168
+ best_id_col, best_overlap = cand, overlap
169
+
170
+ # 2) Choose gene symbol column: prefer rich annotation field containing symbols
171
+ if 'SPOT_ID.1' in gene_annotation.columns:
172
+ best_gene_col = 'SPOT_ID.1'
173
+ elif 'SPOT_ID' in gene_annotation.columns:
174
+ best_gene_col = 'SPOT_ID'
175
+ else:
176
+ # Fallback: pick the column with most rows yielding at least one extractable human gene symbol
177
+ best_gene_col = None
178
+ best_symbol_hits = -1
179
+ sample_annotation = gene_annotation.sample(min(500, len(gene_annotation)), random_state=42)
180
+ for col in gene_annotation.columns:
181
+ try:
182
+ texts = sample_annotation[col].astype(str).fillna("")
183
+ hits = texts.map(lambda x: len(extract_human_gene_symbols(x)) > 0).sum()
184
+ if hits > best_symbol_hits:
185
+ best_symbol_hits = hits
186
+ best_gene_col = col
187
+ except Exception:
188
+ continue
189
+
190
+ # Guard against identical selections
191
+ if best_gene_col == best_id_col:
192
+ # Try switching to a preferred gene annotation column if available
193
+ if 'SPOT_ID.1' in gene_annotation.columns and best_id_col != 'SPOT_ID.1':
194
+ best_gene_col = 'SPOT_ID.1'
195
+ elif 'SPOT_ID' in gene_annotation.columns and best_id_col != 'SPOT_ID':
196
+ best_gene_col = 'SPOT_ID'
197
+ else:
198
+ # Pick the next best gene-like column
199
+ for col, _ in overlaps[1:]:
200
+ if col != best_id_col:
201
+ best_gene_col = col
202
+ break
203
+
204
+ # Validate selections
205
+ if best_id_col is None:
206
+ raise ValueError("Could not determine an annotation ID column matching the expression index.")
207
+
208
+ # 3) Build mapping dataframe and validate overlap with expression IDs
209
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=best_id_col, gene_col=best_gene_col)
210
+
211
+ # Normalize ID in mapping to improve matching with expression index
212
+ mapping_df['ID'] = mapping_df['ID'].astype(str).str.strip().str.replace(r'\.0$', '', regex=True)
213
+ # Also try to recover long digit tokens (>=7) when necessary
214
+ def recover_long_digits(s):
215
+ if s.isdigit():
216
+ return s
217
+ gs = re.findall(r'\d{7,}', s)
218
+ return gs[0] if gs else s
219
+ mapping_df['ID'] = mapping_df['ID'].map(recover_long_digits)
220
+
221
+ overlap_final = mapping_df['ID'].isin(expr_df.index.astype(str)).sum()
222
+ print(f"Selected ID column: {best_id_col}, gene column: {best_gene_col}, overlapping probes: {overlap_final}")
223
+
224
+ # If no overlap, attempt alternative ID columns (next best by overlap)
225
+ if overlap_final == 0:
226
+ tried = {best_id_col}
227
+ for col, ov in overlaps[1:]:
228
+ if col in tried:
229
+ continue
230
+ try:
231
+ alt_map = get_gene_mapping(gene_annotation, prob_col=col, gene_col=best_gene_col)
232
+ alt_map['ID'] = alt_map['ID'].astype(str).str.strip().str.replace(r'\.0$', '', regex=True)
233
+ alt_map['ID'] = alt_map['ID'].map(recover_long_digits)
234
+ ov2 = alt_map['ID'].isin(expr_df.index.astype(str)).sum()
235
+ if ov2 > 0:
236
+ mapping_df = alt_map
237
+ overlap_final = ov2
238
+ best_id_col = col
239
+ print(f"Switched to alternative ID column: {best_id_col} with overlap: {overlap_final}")
240
+ break
241
+ tried.add(col)
242
+ except Exception:
243
+ continue
244
+
245
+ # Final check
246
+ if overlap_final == 0:
247
+ # Provide diagnostics then stop clearly
248
+ cand_cols = [c for c, _ in overlaps[:10]]
249
+ raise ValueError(
250
+ f"No overlap between expression IDs (e.g., {list(list(exp_ids)[:5])}) "
251
+ f"and any annotation column. Top candidate columns tested: {cand_cols}"
252
+ )
253
+
254
+ # 4) Apply mapping to convert probe-level data to gene-level data
255
+ gene_data = apply_gene_mapping(expr_df, mapping_df)
256
+
257
+ # Step 7: Data Normalization and Linking
258
+ import os
259
+
260
+ # 1. Normalize gene symbols and save
261
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
262
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
263
+ normalized_gene_data.to_csv(out_gene_data_file)
264
+
265
+ # 2. Link clinical and genetic data
266
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
267
+
268
+ # Dynamic availability flags for final validation
269
+ is_gene_available_dyn = (normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0)
270
+ is_trait_available_dyn = trait in linked_data.columns
271
+
272
+ # 3. Handle missing values
273
+ linked_data = handle_missing_values(linked_data, trait)
274
+
275
+ # 4. Assess bias and remove biased demographic features
276
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
277
+
278
+ # 5. Final validation and save cohort info
279
+ is_usable = validate_and_save_cohort_info(
280
+ is_final=True,
281
+ cohort=cohort,
282
+ info_path=json_path,
283
+ is_gene_available=is_gene_available_dyn,
284
+ is_trait_available=is_trait_available_dyn,
285
+ is_biased=is_trait_biased,
286
+ df=unbiased_linked_data
287
+ )
288
+
289
+ # 6. Save linked data if usable
290
+ if is_usable:
291
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
292
+ unbiased_linked_data.to_csv(out_data_file)
293
+
294
+ # Step 8: Data Normalization and Linking
295
+ import os
296
+
297
+ # 1. Normalize the obtained gene data and save
298
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
299
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
300
+ normalized_gene_data.to_csv(out_gene_data_file)
301
+
302
+ # 2. Link the clinical and genetic data
303
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
304
+
305
+ # Dynamic availability flags based on generated data
306
+ is_gene_available_dyn = (normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0)
307
+ is_trait_available_dyn = trait in linked_data.columns
308
+
309
+ # 3. Handle missing values in the linked data
310
+ linked_data = handle_missing_values(linked_data, trait)
311
+
312
+ # 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.
313
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
314
+
315
+ # 5. Conduct quality check and save the cohort information.
316
+ is_usable = validate_and_save_cohort_info(
317
+ is_final=True,
318
+ cohort=cohort,
319
+ info_path=json_path,
320
+ is_gene_available=is_gene_available_dyn,
321
+ is_trait_available=is_trait_available_dyn,
322
+ is_biased=is_trait_biased,
323
+ df=unbiased_linked_data
324
+ )
325
+
326
+ # 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.
327
+ if is_usable:
328
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
329
+ unbiased_linked_data.to_csv(out_data_file)
330
+
331
+ # Step 9: Dataset Analysis and Clinical Feature Extraction
332
+ import os
333
+ import re
334
+ import json
335
+ import gzip
336
+ import io
337
+ import numpy as np
338
+ import pandas as pd
339
+
340
+ # Helper: extract value after colon and normalize
341
+ def _extract_value(v):
342
+ if v is None:
343
+ return None
344
+ s = str(v).strip()
345
+ if s == "" or s.lower() in {"na", "n/a", "nan", "none", "null", "not available", "unknown"}:
346
+ return None
347
+ # Split at first colon to separate header from value
348
+ parts = s.split(":", 1)
349
+ val = parts[1] if len(parts) > 1 else parts[0]
350
+ val = val.strip()
351
+ return val if val != "" else None
352
+
353
+ def _lower(s):
354
+ return s.lower() if isinstance(s, str) else s
355
+
356
+ # Heuristics to detect is_gene_available from series matrix header
357
+ def detect_gene_availability_from_series_matrix(in_dir: str) -> bool:
358
+ try:
359
+ # Find a series matrix file
360
+ cand_files = []
361
+ for root, _, files in os.walk(in_dir):
362
+ for fn in files:
363
+ fn_low = fn.lower()
364
+ if "series_matrix" in fn_low and fn_low.endswith(".txt.gz"):
365
+ cand_files.append(os.path.join(root, fn))
366
+ if not cand_files:
367
+ # Fall back to filename keywords if no series matrix
368
+ flags = {"methylation": False, "mirna": False, "expression": False}
369
+ for root, _, files in os.walk(in_dir):
370
+ for fn in files:
371
+ fl = fn.lower()
372
+ if "methyl" in fl or "bisulfite" in fl or "450k" in fl or "850k" in fl or "wgbs" in fl:
373
+ flags["methylation"] = True
374
+ if "mirna" in fl or "micro-rna" in fl or "microRNA".lower() in fl:
375
+ flags["mirna"] = True
376
+ if "expression" in fl or "rnaseq" in fl or "transcript" in fl or "counts" in fl or "series_matrix" in fl:
377
+ flags["expression"] = True
378
+ if flags["methylation"] and not flags["expression"]:
379
+ return False
380
+ if flags["mirna"] and not flags["expression"]:
381
+ return False
382
+ # If expression uncertain, default to True (most GEO H&N cohorts are gene expression)
383
+ return True
384
+
385
+ path = cand_files[0]
386
+ with gzip.open(path, 'rt', encoding='utf-8', errors='ignore') as f:
387
+ header = []
388
+ for _ in range(400):
389
+ line = f.readline()
390
+ if not line:
391
+ break
392
+ header.append(line.strip())
393
+
394
+ header_text = "\n".join(header).lower()
395
+ # Strong negative signals
396
+ if "methylation profiling" in header_text or "methylation" in header_text:
397
+ return False
398
+ if "mirna" in header_text and "mrna" not in header_text and "messenger rna" not in header_text:
399
+ return False
400
+ # Positive signals
401
+ if "expression profiling" in header_text or "rna sequencing" in header_text or "high throughput sequencing" in header_text:
402
+ return True
403
+ # Molecule channel hints
404
+ if "molecule_ch1" in header_text:
405
+ if "genomic dna" in header_text:
406
+ return False
407
+ if "total rna" in header_text or "poly a rna" in header_text or "poly(a) rna" in header_text or "mrna" in header_text:
408
+ return True
409
+ # Default lean positive
410
+ return True
411
+ except Exception:
412
+ # On any parsing issue, lean positive
413
+ return True
414
+
415
+ # Attempt to access clinical_data provided by previous steps
416
+ clinical_data_available = 'clinical_data' in globals() or 'clinical_data' in locals()
417
+ if not clinical_data_available:
418
+ clinical_data = None
419
+
420
+ trait_row = None
421
+ age_row = None
422
+ gender_row = None
423
+
424
+ def _find_rows_from_clinical(clin_df: pd.DataFrame):
425
+ candidate_trait = None
426
+ candidate_gender = None
427
+ candidate_age = None
428
+
429
+ # Build per-row normalized unique values and headers
430
+ for ridx in list(clin_df.index):
431
+ try:
432
+ row_vals = clin_df.loc[ridx].tolist()
433
+ except Exception:
434
+ continue
435
+ extracted_vals = []
436
+ for v in row_vals:
437
+ val = _extract_value(v)
438
+ if val is None:
439
+ continue
440
+ extracted_vals.append(val)
441
+
442
+ if len(extracted_vals) == 0:
443
+ continue
444
+
445
+ # Lowercase uniques for matching
446
+ low_uniques = set([_lower(v) for v in extracted_vals])
447
+
448
+ # Gender detection
449
+ if any(re.search(r'\bmale\b', lv) for lv in low_uniques) or any(re.search(r'\bfemale\b', lv) for lv in low_uniques) or any(lv in {"m","f"} for lv in low_uniques):
450
+ # Ensure not constant
451
+ gset = set()
452
+ for lv in low_uniques:
453
+ if re.fullmatch(r'm|male|males', lv):
454
+ gset.add("male")
455
+ elif re.fullmatch(r'f|female|females', lv):
456
+ gset.add("female")
457
+ if len(gset) >= 2:
458
+ candidate_gender = ridx
459
+
460
+ # Age detection
461
+ numeric_vals = []
462
+ for lv in extracted_vals:
463
+ lv_low = lv.lower()
464
+ # Try to extract a float
465
+ m = re.search(r'(\d+(\.\d+)?)', lv_low)
466
+ if m:
467
+ try:
468
+ num = float(m.group(1))
469
+ # Exclude clearly non-age values (e.g., 0, 1 used for binary)
470
+ numeric_vals.append(num)
471
+ except Exception:
472
+ pass
473
+ if len(numeric_vals) >= max(3, int(0.6 * len(extracted_vals))) and (np.max(numeric_vals) - np.min(numeric_vals) >= 5):
474
+ # Also sanity: check common age hints in text
475
+ if any(k in " ".join([str(x).lower() for x in extracted_vals]) for k in ["age", "years", "y/o", "year-old", "age at", "age(year"]):
476
+ candidate_age = ridx
477
+
478
+ # Trait detection: look for tumor/normal/cancer/control labels
479
+ trait_positive_terms = ["tumor", "tumour", "cancer", "carcinoma", "scc", "hnscc", "hn", "metastasis", "metastatic", "primary", "recurrent"]
480
+ trait_negative_terms = ["normal", "adjacent", "healthy", "control", "benign", "non-tumor", "non tumour", "noncancer"]
481
+ pos = any(any(t in lv for t in trait_positive_terms) for lv in low_uniques)
482
+ neg = any(any(t in lv for t in trait_negative_terms) for lv in low_uniques)
483
+ if pos or neg:
484
+ # Ensure not constant after mapping to binary
485
+ mapped = set()
486
+ for lv in low_uniques:
487
+ if any(t in lv for t in trait_negative_terms):
488
+ mapped.add(0)
489
+ elif any(t in lv for t in trait_positive_terms):
490
+ mapped.add(1)
491
+ if len(mapped) >= 2:
492
+ candidate_trait = ridx
493
+
494
+ return candidate_trait, candidate_age, candidate_gender
495
+
496
+ if clinical_data is not None and isinstance(clinical_data, pd.DataFrame) and len(clinical_data.index) > 0:
497
+ try:
498
+ trow, arow, grow = _find_rows_from_clinical(clinical_data)
499
+ trait_row = trow
500
+ age_row = arow
501
+ gender_row = grow
502
+ except Exception:
503
+ trait_row = None
504
+ age_row = None
505
+ gender_row = None
506
+ else:
507
+ trait_row = None
508
+ age_row = None
509
+ gender_row = None
510
+
511
+ # Conversion functions
512
+ def convert_trait(x):
513
+ v = _extract_value(x)
514
+ if v is None:
515
+ return None
516
+ s = v.strip().lower()
517
+ # Negative/control
518
+ neg_terms = ["normal", "adjacent", "healthy", "control", "benign", "non-tumor", "non tumour", "noncancer", "non-cancer"]
519
+ if any(t in s for t in neg_terms):
520
+ return 0
521
+ # Positive/case
522
+ pos_terms = ["tumor", "tumour", "cancer", "carcinoma", "scc", "hnscc", "metastasis", "metastatic", "primary", "recurrent"]
523
+ if any(t in s for t in pos_terms):
524
+ return 1
525
+ # Some projects encode as case/control directly
526
+ if s in {"case"}:
527
+ return 1
528
+ if s in {"control"}:
529
+ return 0
530
+ return None
531
+
532
+ def convert_age(x):
533
+ v = _extract_value(x)
534
+ if v is None:
535
+ return None
536
+ s = v.strip().lower()
537
+ m = re.search(r'(\d+(\.\d+)?)', s)
538
+ if not m:
539
+ return None
540
+ try:
541
+ age = float(m.group(1))
542
+ # clamp non-sense ages
543
+ if age < 0 or age > 120:
544
+ return None
545
+ return age
546
+ except Exception:
547
+ return None
548
+
549
+ def convert_gender(x):
550
+ v = _extract_value(x)
551
+ if v is None:
552
+ return None
553
+ s = v.strip().lower()
554
+ # Standard mapping: female -> 0, male -> 1
555
+ if s in {"female", "f", "woman", "women"}:
556
+ return 0
557
+ if s in {"male", "m", "man", "men"}:
558
+ return 1
559
+ return None
560
+
561
+ # 1) Gene expression availability
562
+ is_gene_available = detect_gene_availability_from_series_matrix(in_cohort_dir)
563
+
564
+ # 2) Trait availability is based on trait_row detection
565
+ is_trait_available = trait_row is not None
566
+
567
+ # 3) Save metadata (initial filtering)
568
+ _ = validate_and_save_cohort_info(
569
+ is_final=False,
570
+ cohort=cohort,
571
+ info_path=json_path,
572
+ is_gene_available=is_gene_available,
573
+ is_trait_available=is_trait_available
574
+ )
575
+
576
+ # 4) Clinical feature extraction if trait_row available
577
+ if is_trait_available and (clinical_data is not None) and isinstance(clinical_data, pd.DataFrame):
578
+ selected_clinical_df = geo_select_clinical_features(
579
+ clinical_df=clinical_data,
580
+ trait=trait,
581
+ trait_row=trait_row,
582
+ convert_trait=convert_trait,
583
+ age_row=age_row,
584
+ convert_age=convert_age if age_row is not None else None,
585
+ gender_row=gender_row,
586
+ convert_gender=convert_gender if gender_row is not None else None
587
+ )
588
+ # Preview
589
+ clinical_preview = preview_df(selected_clinical_df, n=5)
590
+ print("Preview of selected clinical features:", clinical_preview)
591
+
592
+ # Save to CSV
593
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
594
+ selected_clinical_df.to_csv(out_clinical_data_file)
595
+ else:
596
+ print("Clinical trait data not available; skipping clinical feature extraction.")
597
+
598
+ # Step 10: Dataset Analysis and Clinical Feature Extraction
599
+ import os
600
+ import re
601
+ from typing import Optional
602
+
603
+ # 1) Detect gene expression data availability by scanning cohort directory
604
+ def detect_gene_expression_availability(directory: str) -> bool:
605
+ if not os.path.isdir(directory):
606
+ return False
607
+
608
+ all_files = []
609
+ for root, _, files in os.walk(directory):
610
+ for f in files:
611
+ all_files.append(os.path.join(root, f).lower())
612
+
613
+ if not all_files:
614
+ return False
615
+
616
+ # Exclusion patterns
617
+ methylation_terms = ['methyl', '450k', 'epic', 'idat', 'cpg', 'betavalue', 'beta-value']
618
+ mirna_terms = ['mirna', 'micro_rna', 'microrna']
619
+
620
+ # Inclusion patterns suggestive of gene expression
621
+ series_matrix_terms = ['series_matrix.txt', 'series_matrix.txt.gz']
622
+ expression_terms = [
623
+ 'expression', 'expr', 'rsem', 'htseq', 'featurecount', 'feature_counts',
624
+ 'fpkm', 'tpm', 'counts', 'readcount', 'dge', 'salmon', 'kallisto', 'abundance'
625
+ ]
626
+
627
+ has_methylation = any(any(t in f for t in methylation_terms) for f in all_files)
628
+ if has_methylation:
629
+ return False
630
+
631
+ has_mirna = any(any(t in f for t in mirna_terms) for f in all_files)
632
+ has_series_matrix = any(any(t in f for t in series_matrix_terms) for f in all_files)
633
+ has_expression_like = any(any(t in f for t in expression_terms) for f in all_files)
634
+
635
+ # If only miRNA-related files are present without general expression indicators, treat as not suitable
636
+ if has_mirna and not (has_series_matrix or has_expression_like):
637
+ return False
638
+
639
+ return has_series_matrix or has_expression_like
640
+
641
+ is_gene_available = detect_gene_expression_availability(in_cohort_dir)
642
+
643
+ # 2) Variable availability and conversion functions
644
+ # Based on previous step output: "Clinical trait data not available", set trait_row to None.
645
+ trait_row: Optional[int] = None
646
+ age_row: Optional[int] = None
647
+ gender_row: Optional[int] = None
648
+
649
+ def _after_colon(x):
650
+ if x is None:
651
+ return None
652
+ s = str(x)
653
+ parts = s.split(':', 1)
654
+ val = parts[1] if len(parts) == 2 else parts[0]
655
+ val = val.strip()
656
+ return val if val not in ['', 'na', 'n/a', 'none', 'null', 'nan'] else None
657
+
658
+ # Heuristic converters (will only be used if corresponding rows are available)
659
+ def convert_trait(x):
660
+ v = _after_colon(x)
661
+ if v is None:
662
+ return None
663
+ v_low = v.lower()
664
+ # Map common case/control labels
665
+ case_tokens = ['case', 'tumor', 'tumour', 'cancer', 'hnscc', 'head and neck', 'scc', 'carcinoma']
666
+ control_tokens = ['control', 'normal', 'adjacent normal', 'non-tumor', 'non tumour', 'healthy']
667
+ if any(t in v_low for t in case_tokens):
668
+ return 1
669
+ if any(t in v_low for t in control_tokens):
670
+ return 0
671
+ return None
672
+
673
+ def convert_age(x):
674
+ v = _after_colon(x)
675
+ if v is None:
676
+ return None
677
+ # Extract the first integer or float number found
678
+ m = re.search(r'(\d+(\.\d+)?)', v)
679
+ if not m:
680
+ return None
681
+ try:
682
+ return float(m.group(1))
683
+ except Exception:
684
+ return None
685
+
686
+ def convert_gender(x):
687
+ v = _after_colon(x)
688
+ if v is None:
689
+ return None
690
+ v_low = v.lower()
691
+ if v_low in ['female', 'f', 'woman', 'women']:
692
+ return 0
693
+ if v_low in ['male', 'm', 'man', 'men']:
694
+ return 1
695
+ return None
696
+
697
+ # 3) Save metadata (initial filtering)
698
+ is_trait_available = trait_row is not None
699
+ _ = validate_and_save_cohort_info(
700
+ is_final=False,
701
+ cohort=cohort,
702
+ info_path=json_path,
703
+ is_gene_available=is_gene_available,
704
+ is_trait_available=is_trait_available
705
+ )
706
+
707
+ # 4) Clinical feature extraction (skip because trait_row is None)
708
+ if trait_row is not None:
709
+ selected_clinical_df = geo_select_clinical_features(
710
+ clinical_df=clinical_data,
711
+ trait=trait,
712
+ trait_row=trait_row,
713
+ convert_trait=convert_trait,
714
+ age_row=age_row,
715
+ convert_age=convert_age,
716
+ gender_row=gender_row,
717
+ convert_gender=convert_gender
718
+ )
719
+ clinical_preview = preview_df(selected_clinical_df)
720
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
721
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
722
+
723
+ # Step 11: Dataset Analysis and Clinical Feature Extraction
724
+ import os
725
+ import re
726
+ import json
727
+ import pandas as pd
728
+ import numpy as np
729
+
730
+ # 1) Determine gene expression availability using lightweight heuristics
731
+ def detect_gene_expression_availability(in_dir: str) -> bool:
732
+ if not os.path.isdir(in_dir):
733
+ return False
734
+ files = os.listdir(in_dir)
735
+ if not files:
736
+ return False
737
+
738
+ # If any typical gene expression matrix file is present (and not clearly miRNA/methylation)
739
+ expr_like = ['series_matrix', 'matrix', 'expression', 'counts', 'rsem', 'tpm', 'fpkm', 'readcounts']
740
+ exclude_like = ['mirna', 'microRNA', 'methyl', '450k', 'epic', 'methylation', 'metabol', 'proteom']
741
+ for f in files:
742
+ fl = f.lower()
743
+ if any(x in fl for x in expr_like):
744
+ if not any(x in fl for x in exclude_like):
745
+ return True
746
+ # Fallback: if directory has many GSM/GSE files, assume expression likely available
747
+ gsm_like = [f for f in files if f.lower().startswith(('gsm', 'gse'))]
748
+ return len(gsm_like) > 0
749
+
750
+ is_gene_available = detect_gene_expression_availability(in_cohort_dir)
751
+
752
+ # 2) Variable availability and conversion
753
+ clinical_data = globals().get("clinical_data", None)
754
+
755
+ def _split_cell(cell: any):
756
+ if pd.isna(cell):
757
+ return "", ""
758
+ s = str(cell).strip()
759
+ if ':' in s:
760
+ k, v = s.split(':', 1)
761
+ return k.strip().lower(), v.strip().lower()
762
+ return "", s.lower()
763
+
764
+ def _row_values_and_keys(df: pd.DataFrame, row_id) -> (list, list):
765
+ row = df.loc[row_id]
766
+ keys, vals = [], []
767
+ for cell in row:
768
+ k, v = _split_cell(cell)
769
+ if v != "":
770
+ vals.append(v)
771
+ if k != "":
772
+ keys.append(k)
773
+ return keys, vals
774
+
775
+ def _has_variation(values: list) -> bool:
776
+ uniq = set([v for v in values if v not in ("", "na", "n/a", "nan", "none", "unknown", "not available")])
777
+ return len(uniq) > 1
778
+
779
+ trait_row = None
780
+ age_row = None
781
+ gender_row = None
782
+
783
+ # Define conversion functions
784
+ case_terms = [
785
+ 'cancer', 'carcinoma', 'tumor', 'tumour', 'hnscc', 'oscc', 'scc', 'hnsc',
786
+ 'malignant', 'neoplasm', 'lesion', 'metastasis', 'head and neck', 'oral cancer',
787
+ 'squamous'
788
+ ]
789
+ control_terms = ['normal', 'control', 'adjacent normal', 'non-tumor', 'nontumor', 'healthy', 'benign', 'noncancer']
790
+
791
+ def convert_trait(x):
792
+ k, v = _split_cell(x)
793
+ if v == "":
794
+ return None
795
+ text = v.lower()
796
+ # Heuristic mapping
797
+ is_case = any(t in text for t in case_terms)
798
+ is_ctrl = any(t in text for t in control_terms)
799
+ if is_case and not is_ctrl:
800
+ return 1
801
+ if is_ctrl and not is_case:
802
+ return 0
803
+ # Exact words male/female should not be here; return None if ambiguous
804
+ return None
805
+
806
+ def convert_age(x):
807
+ k, v = _split_cell(x)
808
+ if v == "" or v in ("na", "n/a", "nan", "none", "unknown", "not available"):
809
+ return None
810
+ # Extract first number (years)
811
+ m = re.search(r'(\d+(\.\d+)?)', v)
812
+ if not m:
813
+ return None
814
+ try:
815
+ val = float(m.group(1))
816
+ # Clip unreasonable ages
817
+ if 0 <= val <= 120:
818
+ return val
819
+ except Exception:
820
+ pass
821
+ return None
822
+
823
+ def convert_gender(x):
824
+ k, v = _split_cell(x)
825
+ if v == "":
826
+ return None
827
+ v = v.lower()
828
+ # Normalize single-letter representations
829
+ if v in ("m", "male", "man", "boy"):
830
+ return 1
831
+ if v in ("f", "female", "woman", "girl"):
832
+ return 0
833
+ # Occasionally v may be things like 'gender: M/F'
834
+ if 'male' in v and 'female' not in v:
835
+ return 1
836
+ if 'female' in v and 'male' not in v:
837
+ return 0
838
+ return None
839
+
840
+ def _score_trait_row(keys, vals):
841
+ # Require both case and control presence for trait row
842
+ case_count = sum(any(t in v for t in case_terms) for v in vals)
843
+ ctrl_count = sum(any(t in v for t in control_terms) for v in vals)
844
+ if min(case_count, ctrl_count) == 0:
845
+ return -1 # invalid
846
+ # Prefer informative keys
847
+ key_bonus = 0
848
+ key_text = ' '.join(set(keys))
849
+ for kw in ['disease', 'status', 'group', 'phenotype', 'tissue', 'tumor', 'diagnosis', 'condition', 'case', 'control']:
850
+ if kw in key_text:
851
+ key_bonus += 2
852
+ return (case_count + ctrl_count) + 3 * min(case_count, ctrl_count) + key_bonus
853
+
854
+ def _looks_like_age(keys, vals):
855
+ key_text = ' '.join(set(keys))
856
+ if 'age' in key_text:
857
+ return True
858
+ # If majority of cells look numeric with 'year'
859
+ numeric_like = 0
860
+ for v in vals:
861
+ if re.search(r'\d', v):
862
+ numeric_like += 1
863
+ return numeric_like >= max(2, int(0.5 * len(vals)))
864
+
865
+ def _looks_like_gender(keys, vals):
866
+ key_text = ' '.join(set(keys))
867
+ if ('gender' in key_text) or ('sex' in key_text):
868
+ return True
869
+ gender_like = 0
870
+ for v in vals:
871
+ if v in ("m", "male", "man", "boy", "f", "female", "woman", "girl") or ('male' in v) or ('female' in v):
872
+ gender_like += 1
873
+ return gender_like >= max(2, int(0.5 * len(vals)))
874
+
875
+ if isinstance(clinical_data, pd.DataFrame) and clinical_data.shape[0] > 0:
876
+ # Identify rows
877
+ trait_candidates = []
878
+ age_candidates = []
879
+ gender_candidates = []
880
+
881
+ for row_id in clinical_data.index:
882
+ try:
883
+ keys, vals = _row_values_and_keys(clinical_data, row_id)
884
+ except Exception:
885
+ continue
886
+ # Trait candidates
887
+ score = _score_trait_row(keys, vals)
888
+ if score >= 0 and _has_variation([convert_trait(v) for v in clinical_data.loc[row_id].values]):
889
+ trait_candidates.append((row_id, score))
890
+ # Age candidates
891
+ if _looks_like_age(keys, vals):
892
+ # Variation after numeric conversion
893
+ converted = [convert_age(v) for v in clinical_data.loc[row_id].values]
894
+ if _has_variation([str(c) for c in converted if c is not None]):
895
+ age_candidates.append(row_id)
896
+ # Gender candidates
897
+ if _looks_like_gender(keys, vals):
898
+ converted = [convert_gender(v) for v in clinical_data.loc[row_id].values]
899
+ # Require both sexes present
900
+ if (1 in converted) and (0 in converted):
901
+ gender_candidates.append(row_id)
902
+
903
+ # Select best trait_row by score
904
+ if trait_candidates:
905
+ trait_candidates.sort(key=lambda x: x[1], reverse=True)
906
+ trait_row = trait_candidates[0][0]
907
+
908
+ # If multiple age rows, prefer one with 'age' in keys explicitly
909
+ if age_candidates:
910
+ if len(age_candidates) == 1:
911
+ age_row = age_candidates[0]
912
+ else:
913
+ # Choose the one with explicit 'age' mention in keys
914
+ winners = []
915
+ for rid in age_candidates:
916
+ keys, _ = _row_values_and_keys(clinical_data, rid)
917
+ if any('age' in k for k in keys):
918
+ winners.append(rid)
919
+ age_row = winners[0] if winners else age_candidates[0]
920
+
921
+ # If multiple gender rows, prefer explicit 'gender'/'sex'
922
+ if gender_candidates:
923
+ if len(gender_candidates) == 1:
924
+ gender_row = gender_candidates[0]
925
+ else:
926
+ winners = []
927
+ for rid in gender_candidates:
928
+ keys, _ = _row_values_and_keys(clinical_data, rid)
929
+ if any(('gender' in k) or ('sex' in k) for k in keys):
930
+ winners.append(rid)
931
+ gender_row = winners[0] if winners else gender_candidates[0]
932
+
933
+ # 3) Save metadata (initial filtering)
934
+ is_trait_available = trait_row is not None
935
+ _ = validate_and_save_cohort_info(
936
+ is_final=False,
937
+ cohort=cohort,
938
+ info_path=json_path,
939
+ is_gene_available=is_gene_available,
940
+ is_trait_available=is_trait_available
941
+ )
942
+
943
+ # 4) Clinical Feature Extraction and preview/save if available
944
+ if is_trait_available and isinstance(clinical_data, pd.DataFrame):
945
+ selected_df = geo_select_clinical_features(
946
+ clinical_df=clinical_data,
947
+ trait=trait,
948
+ trait_row=int(trait_row),
949
+ convert_trait=convert_trait,
950
+ age_row=int(age_row) if age_row is not None else None,
951
+ convert_age=convert_age if age_row is not None else None,
952
+ gender_row=int(gender_row) if gender_row is not None else None,
953
+ convert_gender=convert_gender if gender_row is not None else None
954
+ )
955
+ clinical_preview = preview_df(selected_df, n=5, max_items=200)
956
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
957
+ selected_df.to_csv(out_clinical_data_file)
958
+
959
+ # Step 12: Data Normalization and Linking
960
+ import os
961
+ import pandas as pd
962
+
963
+ # 1) Normalize gene symbols and save
964
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
965
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
966
+ normalized_gene_data.to_csv(out_gene_data_file)
967
+
968
+ # 2) Link clinical and genetic data (guard for missing clinical features)
969
+ clinical_df = None
970
+ if 'selected_clinical_df' in globals() and isinstance(selected_clinical_df, pd.DataFrame):
971
+ clinical_df = selected_clinical_df
972
+ elif os.path.exists(out_clinical_data_file):
973
+ try:
974
+ clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
975
+ except Exception:
976
+ clinical_df = None
977
+
978
+ if isinstance(clinical_df, pd.DataFrame) and clinical_df.shape[0] > 0:
979
+ linked_data = geo_link_clinical_genetic_data(clinical_df, normalized_gene_data)
980
+ else:
981
+ linked_data = pd.DataFrame()
982
+
983
+ # Dynamic availability flags
984
+ is_gene_available_dyn = (normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0)
985
+ is_trait_available_dyn = (isinstance(linked_data, pd.DataFrame) and (len(linked_data.columns) > 0) and (trait in linked_data.columns))
986
+
987
+ # 3) Handle missing values only if trait column is available
988
+ if is_trait_available_dyn:
989
+ linked_data = handle_missing_values(linked_data, trait)
990
+ # 4) Assess bias and remove biased demographic features
991
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
992
+ else:
993
+ # No trait available; construct empty df for validation
994
+ unbiased_linked_data = pd.DataFrame()
995
+ is_trait_biased = False # placeholder; dataset will be marked unavailable due to missing trait
996
+
997
+ # 5) Final validation and save cohort info
998
+ note = ""
999
+ if not is_trait_available_dyn:
1000
+ note = "INFO: Trait not available in clinical annotations; unable to link clinical and genetic data."
1001
+
1002
+ is_usable = validate_and_save_cohort_info(
1003
+ is_final=True,
1004
+ cohort=cohort,
1005
+ info_path=json_path,
1006
+ is_gene_available=is_gene_available_dyn,
1007
+ is_trait_available=is_trait_available_dyn,
1008
+ is_biased=is_trait_biased,
1009
+ df=unbiased_linked_data,
1010
+ note=note
1011
+ )
1012
+
1013
+ # 6) Save linked data if usable
1014
+ if is_usable:
1015
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
1016
+ unbiased_linked_data.to_csv(out_data_file)
1017
+
1018
+ # Step 13: Dataset Analysis and Clinical Feature Extraction
1019
+ import os
1020
+ import re
1021
+ import numpy as np
1022
+ import pandas as pd
1023
+
1024
+ # 1) Gene expression data availability (heuristic: assume TRUE for GEO series with parsed matrix)
1025
+ is_gene_available = True
1026
+
1027
+ # 2) Variable availability scanning on clinical_data
1028
+ def _after_colon(x):
1029
+ if x is None or (isinstance(x, float) and np.isnan(x)):
1030
+ return None
1031
+ s = str(x)
1032
+ parts = s.split(":", 1)
1033
+ val = parts[1] if len(parts) > 1 else parts[0]
1034
+ val = val.strip()
1035
+ return val if val != "" else None
1036
+
1037
+ def _clean_str(x):
1038
+ if x is None:
1039
+ return None
1040
+ s = str(x).strip().lower()
1041
+ s = re.sub(r'\s+', ' ', s)
1042
+ return s
1043
+
1044
+ def _parse_age(x):
1045
+ if x is None:
1046
+ return None
1047
+ s = _clean_str(_after_colon(x))
1048
+ if s is None or s in {"na", "n/a", "nan", "none", "unknown", ""}:
1049
+ return None
1050
+ # find a plausible age number
1051
+ m = re.search(r'(\d+(\.\d+)?)', s)
1052
+ if not m:
1053
+ return None
1054
+ try:
1055
+ age = float(m.group(1))
1056
+ except:
1057
+ return None
1058
+ if 0 <= age <= 120:
1059
+ return age
1060
+ return None
1061
+
1062
+ def _parse_gender(x):
1063
+ s = _clean_str(_after_colon(x))
1064
+ if s is None:
1065
+ return None
1066
+ # common patterns
1067
+ if s in {"male", "m", "man", "men"}:
1068
+ return 1
1069
+ if s in {"female", "f", "woman", "women"}:
1070
+ return 0
1071
+ # Sometimes values like "sex: Male", handled by _after_colon already
1072
+ # handle single letters with extra text
1073
+ if re.search(r'\bmale\b', s):
1074
+ return 1
1075
+ if re.search(r'\bfemale\b', s):
1076
+ return 0
1077
+ if re.fullmatch(r'm', s):
1078
+ return 1
1079
+ if re.fullmatch(r'f', s):
1080
+ return 0
1081
+ return None
1082
+
1083
+ positive_terms = {
1084
+ "cancer", "carcinoma", "tumor", "tumour", "squamous cell carcinoma",
1085
+ "scc", "hnscc", "head and neck cancer", "oral cavity cancer",
1086
+ "oropharyngeal carcinoma", "malignant", "metastatic", "primary tumor",
1087
+ "primary tumour"
1088
+ }
1089
+ negative_terms = {
1090
+ "normal", "non-tumor", "non tumour", "healthy", "control", "adjacent normal",
1091
+ "benign", "normal tissue", "adjacent noncancerous", "adjacent non-cancerous"
1092
+ }
1093
+ case_terms = {"case"}
1094
+ control_terms = {"control"}
1095
+
1096
+ def _trait_label_from_value(x):
1097
+ s = _clean_str(_after_colon(x))
1098
+ if s is None:
1099
+ return None
1100
+ # map to binary: presence of head and neck cancer = 1, absence = 0
1101
+ # check explicit case/control first
1102
+ if s in case_terms:
1103
+ return 1
1104
+ if s in control_terms:
1105
+ return 0
1106
+ # general positive/negative term containment
1107
+ if any(t in s for t in positive_terms):
1108
+ return 1
1109
+ if any(t in s for t in negative_terms):
1110
+ return 0
1111
+ # sometimes values like "tumor", "normal"
1112
+ if re.search(r'\btumou?r\b', s):
1113
+ return 1
1114
+ if re.search(r'\bnormal\b', s):
1115
+ return 0
1116
+ return None
1117
+
1118
+ # Access clinical_data if available
1119
+ trait_row = None
1120
+ age_row = None
1121
+ gender_row = None
1122
+
1123
+ if 'clinical_data' in globals() and isinstance(clinical_data, pd.DataFrame) and len(clinical_data) > 0:
1124
+ # Identify candidate rows by scanning variability and recognizable patterns
1125
+ trait_candidates = []
1126
+ age_candidates = []
1127
+ gender_candidates = []
1128
+
1129
+ for ridx in clinical_data.index:
1130
+ vals = list(clinical_data.loc[ridx].values)
1131
+ # Trait candidates: check if both 0 and 1 present after mapping
1132
+ mapped = [ _trait_label_from_value(v) for v in vals ]
1133
+ recognized = [m for m in mapped if m is not None]
1134
+ if len(set(recognized)) >= 2:
1135
+ # keep count of recognized values to rank
1136
+ trait_candidates.append((ridx, len(recognized)))
1137
+
1138
+ # Age candidates: parse ages and check variability
1139
+ ages = [ _parse_age(v) for v in vals ]
1140
+ ages_clean = [a for a in ages if a is not None]
1141
+ if len(set(ages_clean)) >= 2 and len(ages_clean) >= max(2, int(0.5 * len(vals))):
1142
+ age_candidates.append((ridx, len(ages_clean)))
1143
+
1144
+ # Gender candidates: parse genders and check variability
1145
+ genders = [ _parse_gender(v) for v in vals ]
1146
+ genders_clean = [g for g in genders if g is not None]
1147
+ if len(set(genders_clean)) >= 2 and len(genders_clean) >= max(2, int(0.5 * len(vals))):
1148
+ gender_candidates.append((ridx, len(genders_clean)))
1149
+
1150
+ # Choose the best candidates by max recognized count
1151
+ if trait_candidates:
1152
+ trait_row = sorted(trait_candidates, key=lambda x: x[1], reverse=True)[0][0]
1153
+ if age_candidates:
1154
+ age_row = sorted(age_candidates, key=lambda x: x[1], reverse=True)[0][0]
1155
+ if gender_candidates:
1156
+ gender_row = sorted(gender_candidates, key=lambda x: x[1], reverse=True)[0][0]
1157
+
1158
+ # If trait row exists but constant after mapping (edge case), drop it
1159
+ if trait_row is not None:
1160
+ vals = list(clinical_data.loc[trait_row].values)
1161
+ mapped = [ _trait_label_from_value(v) for v in vals ]
1162
+ rec = [m for m in mapped if m is not None]
1163
+ if len(set(rec)) <= 1:
1164
+ trait_row = None
1165
+
1166
+ # 2.2 Converters
1167
+ def convert_trait(x):
1168
+ return _trait_label_from_value(x)
1169
+
1170
+ def convert_age(x):
1171
+ return _parse_age(x)
1172
+
1173
+ def convert_gender(x):
1174
+ return _parse_gender(x)
1175
+
1176
+ # 3) Save initial metadata
1177
+ is_trait_available = trait_row is not None
1178
+ _ = validate_and_save_cohort_info(
1179
+ is_final=False,
1180
+ cohort=cohort,
1181
+ info_path=json_path,
1182
+ is_gene_available=is_gene_available,
1183
+ is_trait_available=is_trait_available
1184
+ )
1185
+
1186
+ # 4) Clinical Feature Extraction if available
1187
+ if is_trait_available:
1188
+ selected_clinical = geo_select_clinical_features(
1189
+ clinical_df=clinical_data,
1190
+ trait=trait,
1191
+ trait_row=trait_row,
1192
+ convert_trait=convert_trait,
1193
+ age_row=age_row,
1194
+ convert_age=convert_age if age_row is not None else None,
1195
+ gender_row=gender_row,
1196
+ convert_gender=convert_gender if gender_row is not None else None
1197
+ )
1198
+ _ = preview_df(selected_clinical)
1199
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
1200
+ selected_clinical.to_csv(out_clinical_data_file)
1201
+
1202
+ # Step 14: Dataset Analysis and Clinical Feature Extraction
1203
+ import os
1204
+ import re
1205
+ import json
1206
+ import gzip
1207
+ from io import TextIOWrapper
1208
+ from typing import Optional, Callable, List, Tuple, Dict, Any
1209
+
1210
+ import pandas as pd
1211
+ import numpy as np
1212
+
1213
+ # ---------------------------
1214
+ # Helpers
1215
+ # ---------------------------
1216
+
1217
+ def _open_text_file(path):
1218
+ if path.endswith(".gz"):
1219
+ return TextIOWrapper(gzip.open(path, "rb"), encoding="utf-8", errors="ignore")
1220
+ return open(path, "r", encoding="utf-8", errors="ignore")
1221
+
1222
+ def is_gene_expression_available(in_dir: str) -> bool:
1223
+ # Heuristic: inspect available text-like files for platform/assay hints
1224
+ if not os.path.isdir(in_dir):
1225
+ return False
1226
+ text_exts = (".txt", ".csv", ".tsv", ".soft", ".series_matrix", ".json")
1227
+ candidates = []
1228
+ for root, _, files in os.walk(in_dir):
1229
+ for f in files:
1230
+ lower = f.lower()
1231
+ if lower.endswith(text_exts) or lower.endswith(tuple(e + ".gz" for e in text_exts)):
1232
+ candidates.append(os.path.join(root, f))
1233
+
1234
+ if not candidates:
1235
+ return False
1236
+
1237
+ has_expression_hint = False
1238
+ has_exclusion_hint = False
1239
+ for path in candidates:
1240
+ try:
1241
+ with _open_text_file(path) as fh:
1242
+ head = "".join([next(fh) for _ in range(200)])
1243
+ except StopIteration:
1244
+ pass
1245
+ except Exception:
1246
+ continue
1247
+ s = head.lower()
1248
+ # Exclusion: miRNA-only or methylation
1249
+ if ("mirna" in s or "micro rna" in s or "micro-rna" in s or "microrna" in s) and ("mrna" not in s and "rna-seq" not in s and "transcript" not in s):
1250
+ has_exclusion_hint = True
1251
+ if ("methylation" in s) or ("cpg" in s) or ("illumina humanmethylation" in s):
1252
+ has_exclusion_hint = True
1253
+ # Inclusion hints for gene expression
1254
+ if ("rna-seq" in s) or ("mrna" in s) or ("expression profiling by array" in s) or ("transcript" in s) or ("series_matrix_table_begin" in s):
1255
+ has_expression_hint = True
1256
+
1257
+ if has_exclusion_hint and not has_expression_hint:
1258
+ return False
1259
+ # Default to True if we saw any plausible expression hints or cannot decisively exclude
1260
+ return True
1261
+
1262
+ def try_get_clinical_df() -> Optional[pd.DataFrame]:
1263
+ # Use pre-existing variable if available
1264
+ try:
1265
+ if isinstance(clinical_data, pd.DataFrame):
1266
+ return clinical_data
1267
+ except NameError:
1268
+ pass
1269
+
1270
+ # Try common filenames in the cohort directory
1271
+ candidates = [
1272
+ os.path.join(in_cohort_dir, "clinical_data.csv"),
1273
+ os.path.join(in_cohort_dir, "clinical.csv"),
1274
+ os.path.join(in_cohort_dir, "samples_clinical.csv"),
1275
+ os.path.join(in_cohort_dir, "clinical_data.tsv"),
1276
+ os.path.join(in_cohort_dir, "clinical_data.parquet"),
1277
+ os.path.join(in_cohort_dir, "clinical_data.pkl"),
1278
+ ]
1279
+ for p in candidates:
1280
+ if os.path.exists(p):
1281
+ try:
1282
+ if p.endswith(".csv"):
1283
+ return pd.read_csv(p, index_col=0)
1284
+ if p.endswith(".tsv"):
1285
+ return pd.read_csv(p, sep="\t", index_col=0)
1286
+ if p.endswith(".parquet"):
1287
+ return pd.read_parquet(p)
1288
+ if p.endswith(".pkl"):
1289
+ return pd.read_pickle(p)
1290
+ except Exception:
1291
+ continue
1292
+ return None
1293
+
1294
+ def _parse_value(cell: Any) -> str:
1295
+ if pd.isna(cell):
1296
+ return ""
1297
+ s = str(cell).strip()
1298
+ # GEO often uses "key: value"
1299
+ if ":" in s:
1300
+ s = s.split(":", 1)[1].strip()
1301
+ return s
1302
+
1303
+ def _normalize(s: str) -> str:
1304
+ return re.sub(r"\s+", " ", s.strip().lower())
1305
+
1306
+ def detect_age_row(df: pd.DataFrame) -> Optional[int]:
1307
+ candidates: List[Tuple[int, int, int]] = [] # (row_idx, n_numeric_unique, n_age_mentions)
1308
+ for ridx in df.index:
1309
+ vals = [str(v) for v in df.loc[ridx, :].tolist()]
1310
+ vals_lower = [_normalize(v) for v in vals]
1311
+ age_mentions = sum(("age" in v) for v in vals_lower)
1312
+ # Extract numeric ages
1313
+ nums = []
1314
+ for v in vals_lower:
1315
+ core = _parse_value(v)
1316
+ # extract first number (potentially decimals)
1317
+ m = re.search(r"(\d+(\.\d+)?)", core)
1318
+ if m:
1319
+ try:
1320
+ nums.append(float(m.group(1)))
1321
+ except Exception:
1322
+ nums.append(np.nan)
1323
+ else:
1324
+ nums.append(np.nan)
1325
+ nums = [x for x in nums if pd.notna(x)]
1326
+ if len(set(nums)) >= 2 and age_mentions > 0:
1327
+ candidates.append((ridx, len(set(nums)), age_mentions))
1328
+ if not candidates:
1329
+ return None
1330
+ # Prefer more age mentions, then more numeric variability
1331
+ candidates.sort(key=lambda x: (x[2], x[1]), reverse=True)
1332
+ return candidates[0][0]
1333
+
1334
+ def detect_gender_row(df: pd.DataFrame) -> Optional[int]:
1335
+ def to_gender(v: str) -> Optional[int]:
1336
+ x = _normalize(_parse_value(v))
1337
+ if x in ("male", "m"):
1338
+ return 1
1339
+ if x in ("female", "f"):
1340
+ return 0
1341
+ # common variants
1342
+ if "male" in x and "female" not in x:
1343
+ return 1
1344
+ if "female" in x and "male" not in x:
1345
+ return 0
1346
+ if "sex" in x:
1347
+ if "male" in x:
1348
+ return 1
1349
+ if "female" in x:
1350
+ return 0
1351
+ return None
1352
+
1353
+ candidates: List[Tuple[int, int]] = [] # (row_idx, n_valid)
1354
+ for ridx in df.index:
1355
+ vals = [str(v) for v in df.loc[ridx, :].tolist()]
1356
+ mapped = [to_gender(v) for v in vals]
1357
+ valid = [m for m in mapped if m is not None]
1358
+ if len(valid) >= 2 and len(set(valid)) == 2: # both sexes present
1359
+ candidates.append((ridx, len(valid)))
1360
+ if not candidates:
1361
+ return None
1362
+ candidates.sort(key=lambda x: x[1], reverse=True)
1363
+ return candidates[0][0]
1364
+
1365
+ def detect_trait_row(df: pd.DataFrame) -> Optional[int]:
1366
+ # We want binary case/control for Head_and_Neck_Cancer
1367
+ cancer_kw = ["cancer", "carcinoma", "tumor", "tumour", "squamous", "hnscc", "oscc", "hn", "head and neck"]
1368
+ control_kw = ["normal", "adjacent", "non-tumor", "nontumor", "noncancer", "control", "healthy", "benign"]
1369
+
1370
+ def to_trait(v: str) -> Optional[int]:
1371
+ x = _normalize(_parse_value(v))
1372
+ # explicit NA
1373
+ if x in ("", "na", "n/a", "none", "unknown"):
1374
+ return None
1375
+ pos = any(kw in x for kw in cancer_kw)
1376
+ neg = any(kw in x for kw in control_kw)
1377
+ if pos and not neg:
1378
+ return 1
1379
+ if neg and not pos:
1380
+ return 0
1381
+ # group labels like case/control
1382
+ if "case" in x and "control" not in x:
1383
+ return 1
1384
+ if "control" in x and "case" not in x:
1385
+ return 0
1386
+ # source_name_ch1 or tissue labels that imply tumor/normal
1387
+ return None
1388
+
1389
+ candidates: List[Tuple[int, int, int]] = [] # (row_idx, n_valid, n_keyword_hits)
1390
+ for ridx in df.index:
1391
+ vals = [str(v) for v in df.loc[ridx, :].tolist()]
1392
+ mapped = [to_trait(v) for v in vals]
1393
+ valid = [m for m in mapped if m is not None]
1394
+ if len(valid) >= 2 and len(set(valid)) == 2:
1395
+ # keyword hits for ranking
1396
+ vals_lower = [_normalize(_parse_value(v)) for v in vals]
1397
+ kw_hits = sum(any(kw in v for kw in cancer_kw + control_kw) for v in vals_lower)
1398
+ candidates.append((ridx, len(valid), kw_hits))
1399
+ if not candidates:
1400
+ return None
1401
+ candidates.sort(key=lambda x: (x[2], x[1]), reverse=True)
1402
+ return candidates[0][0]
1403
+
1404
+ # ---------------------------
1405
+ # Step 1: Gene expression availability
1406
+ # ---------------------------
1407
+ is_gene_available = is_gene_expression_available(in_cohort_dir)
1408
+
1409
+ # ---------------------------
1410
+ # Step 2: Variable availability and conversion functions
1411
+ # ---------------------------
1412
+ clinical_df = try_get_clinical_df()
1413
+
1414
+ trait_row: Optional[int] = None
1415
+ age_row: Optional[int] = None
1416
+ gender_row: Optional[int] = None
1417
+
1418
+ if clinical_df is not None and clinical_df.shape[0] > 0 and clinical_df.shape[1] > 0:
1419
+ # Ensure row index are ints if possible; otherwise leave as is but we will return integer-like labels where applicable
1420
+ # However, geo_select_clinical_features expects integer row identifiers that match the df index.
1421
+ # We'll attempt to cast to int when safe; else keep as is.
1422
+ try:
1423
+ clinical_df.index = clinical_df.index.astype(int)
1424
+ except Exception:
1425
+ pass
1426
+
1427
+ # Detect rows
1428
+ trait_row = detect_trait_row(clinical_df)
1429
+ age_row = detect_age_row(clinical_df)
1430
+ gender_row = detect_gender_row(clinical_df)
1431
+
1432
+ # Conversion functions
1433
+ def convert_trait(x: Any) -> Optional[int]:
1434
+ s = _normalize(_parse_value(x))
1435
+ if s in ("", "na", "n/a", "none", "unknown"):
1436
+ return None
1437
+ pos_kw = ["cancer", "carcinoma", "tumor", "tumour", "squamous", "hnscc", "oscc", "malignant"]
1438
+ neg_kw = ["normal", "adjacent", "non-tumor", "nontumor", "noncancer", "control", "healthy", "benign"]
1439
+ pos = any(k in s for k in pos_kw)
1440
+ neg = any(k in s for k in neg_kw)
1441
+ if pos and not neg:
1442
+ return 1
1443
+ if neg and not pos:
1444
+ return 0
1445
+ if "case" in s and "control" not in s:
1446
+ return 1
1447
+ if "control" in s and "case" not in s:
1448
+ return 0
1449
+ # If dataset is case-only or control-only, return None to avoid constant feature
1450
+ return None
1451
+
1452
+ def convert_age(x: Any) -> Optional[float]:
1453
+ s = _normalize(_parse_value(x))
1454
+ if s in ("", "na", "n/a", "none", "unknown"):
1455
+ return None
1456
+ m = re.search(r"(\d+(\.\d+)?)", s)
1457
+ if not m:
1458
+ return None
1459
+ try:
1460
+ age_val = float(m.group(1))
1461
+ # Heuristic sanity bounds
1462
+ if 0 <= age_val <= 120:
1463
+ return age_val
1464
+ return None
1465
+ except Exception:
1466
+ return None
1467
+
1468
+ def convert_gender(x: Any) -> Optional[int]:
1469
+ s = _normalize(_parse_value(x))
1470
+ if s in ("", "na", "n/a", "none", "unknown"):
1471
+ return None
1472
+ if s in ("male", "m"):
1473
+ return 1
1474
+ if s in ("female", "f"):
1475
+ return 0
1476
+ if "male" in s and "female" not in s:
1477
+ return 1
1478
+ if "female" in s and "male" not in s:
1479
+ return 0
1480
+ if "man" in s and "woman" not in s:
1481
+ return 1
1482
+ if "woman" in s and "man" not in s:
1483
+ return 0
1484
+ return None
1485
+
1486
+ # If no clinical_df, we cannot have trait_row
1487
+ is_trait_available = trait_row is not None
1488
+
1489
+ # ---------------------------
1490
+ # Step 3: Save metadata (initial filtering)
1491
+ # ---------------------------
1492
+ _ = validate_and_save_cohort_info(
1493
+ is_final=False,
1494
+ cohort=cohort,
1495
+ info_path=json_path,
1496
+ is_gene_available=is_gene_available,
1497
+ is_trait_available=is_trait_available
1498
+ )
1499
+
1500
+ # ---------------------------
1501
+ # Step 4: Clinical feature extraction (only if trait_row is available)
1502
+ # ---------------------------
1503
+ if is_trait_available and clinical_df is not None:
1504
+ selected_clinical_df = geo_select_clinical_features(
1505
+ clinical_df=clinical_df,
1506
+ trait=trait,
1507
+ trait_row=trait_row,
1508
+ convert_trait=convert_trait,
1509
+ age_row=age_row,
1510
+ convert_age=convert_age if age_row is not None else None,
1511
+ gender_row=gender_row,
1512
+ convert_gender=convert_gender if gender_row is not None else None
1513
+ )
1514
+ preview = preview_df(selected_clinical_df, n=5)
1515
+ print("Selected clinical features preview:", preview)
1516
+
1517
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
1518
+ selected_clinical_df.to_csv(out_clinical_data_file)
output/preprocess/Head_and_Neck_Cancer/code/GSE151181.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Head_and_Neck_Cancer"
6
+ cohort = "GSE151181"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Head_and_Neck_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Head_and_Neck_Cancer/GSE151181"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/GSE151181.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/gene_data/GSE151181.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/clinical_data/GSE151181.csv"
16
+ json_path = "./output/z3/preprocess/Head_and_Neck_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+ import pandas as pd
42
+
43
+ # 1) Gene expression availability
44
+ is_gene_available = True # Title mentions "Gene and miRNA expression"; not pure miRNA-only.
45
+
46
+ # 2) Variable availability and converters
47
+
48
+ # Trait availability:
49
+ # Use 'tissue type' (row 1): cancer vs non-neoplastic thyroid
50
+ trait_row = 1
51
+
52
+ # Age and gender are not available in the provided characteristics
53
+ age_row = None
54
+ gender_row = None
55
+
56
+ def _extract_value(x):
57
+ if x is None or (isinstance(x, float) and pd.isna(x)):
58
+ return None
59
+ s = str(x)
60
+ if ':' in s:
61
+ s = s.split(':', 1)[1]
62
+ return s.strip()
63
+
64
+ def convert_trait(x):
65
+ v = _extract_value(x)
66
+ if v is None:
67
+ return None
68
+ lv = v.lower()
69
+ # Control indicators
70
+ if 'non-neoplastic' in lv or lv in {'normal', 'normal thyroid', 'adjacent normal'}:
71
+ return 0
72
+ # Tumor/metastasis indicators
73
+ tumor_keywords = [
74
+ 'primary tumor', 'metastasis', 'lymph node metastasis', 'synchronous lymph node metastasis',
75
+ 'post rai', 'tumor'
76
+ ]
77
+ if any(k in lv for k in tumor_keywords):
78
+ return 1
79
+ return None
80
+
81
+ def convert_age(x):
82
+ v = _extract_value(x)
83
+ if v is None:
84
+ return None
85
+ lv = v.lower()
86
+ if lv in {'na', 'n/a', 'not available', 'unknown', ''}:
87
+ return None
88
+ # Extract first number as age
89
+ m = re.search(r'(\d+(\.\d+)?)', v)
90
+ if m:
91
+ try:
92
+ return float(m.group(1))
93
+ except:
94
+ return None
95
+ return None
96
+
97
+ def convert_gender(x):
98
+ v = _extract_value(x)
99
+ if v is None:
100
+ return None
101
+ lv = v.lower()
102
+ if lv in {'female', 'f'}:
103
+ return 0
104
+ if lv in {'male', 'm'}:
105
+ return 1
106
+ return None
107
+
108
+ # 3) Save metadata (initial filtering)
109
+ is_trait_available = trait_row is not None
110
+ _ = validate_and_save_cohort_info(
111
+ is_final=False,
112
+ cohort=cohort,
113
+ info_path=json_path,
114
+ is_gene_available=is_gene_available,
115
+ is_trait_available=is_trait_available
116
+ )
117
+
118
+ # 4) Clinical feature extraction (only if trait_row is available)
119
+ if trait_row is not None:
120
+ selected_clinical_df = geo_select_clinical_features(
121
+ clinical_df=clinical_data,
122
+ trait=trait,
123
+ trait_row=trait_row,
124
+ convert_trait=convert_trait,
125
+ age_row=age_row,
126
+ convert_age=convert_age if age_row is not None else None,
127
+ gender_row=gender_row,
128
+ convert_gender=convert_gender if gender_row is not None else None
129
+ )
130
+ preview = preview_df(selected_clinical_df, n=5)
131
+ print("Preview of selected clinical features:", preview)
132
+
133
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
134
+ selected_clinical_df.to_csv(out_clinical_data_file)
135
+
136
+ # Step 3: Gene Data Extraction
137
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
138
+ gene_data = get_genetic_data(matrix_file)
139
+
140
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
141
+ print(gene_data.index[:20])
142
+
143
+ # Step 4: Gene Identifier Review
144
+ # Based on the observed identifiers (e.g., '23064070'), these are not human gene symbols.
145
+ # They appear to be platform-specific probe IDs or other numeric identifiers.
146
+ print("requires_gene_mapping = True")
147
+
148
+ # Step 5: Gene Annotation
149
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
150
+ gene_annotation = get_gene_annotation(soft_file)
151
+
152
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
153
+ print("Gene annotation preview:")
154
+ print(preview_df(gene_annotation))
155
+
156
+ # Step 6: Gene Identifier Mapping
157
+ # Robust probe-to-gene mapping with graceful fallback
158
+
159
+ import pandas as pd
160
+
161
+ # 1) Determine the identifier column in the annotation that best matches the expression IDs
162
+ expr_ids = set(gene_data.index.astype(str).str.strip())
163
+
164
+ best_id_col = None
165
+ best_overlap = 0
166
+ for col in gene_annotation.columns:
167
+ try:
168
+ ann_values = set(gene_annotation[col].dropna().astype(str).str.strip())
169
+ except Exception:
170
+ continue
171
+ overlap = len(expr_ids & ann_values)
172
+ if overlap > best_overlap:
173
+ best_overlap = overlap
174
+ best_id_col = col
175
+
176
+ # 2) Choose a gene symbol column by scanning all columns and counting extractable symbols
177
+ gene_col = None
178
+ best_symbol_count = -1
179
+ for c in gene_annotation.columns:
180
+ try:
181
+ series = gene_annotation[c].dropna().astype(str)
182
+ except Exception:
183
+ continue
184
+ symbol_count = series.map(lambda x: len(extract_human_gene_symbols(x)) > 0).sum()
185
+ if symbol_count > best_symbol_count:
186
+ best_symbol_count = symbol_count
187
+ gene_col = c
188
+
189
+ # Fallbacks if automatic detection fails
190
+ if best_id_col is None:
191
+ best_id_col = 'ID' if 'ID' in gene_annotation.columns else gene_annotation.columns[0]
192
+ if gene_col is None:
193
+ gene_col = 'GENE_SYMBOL' if 'GENE_SYMBOL' in gene_annotation.columns else gene_annotation.columns[0]
194
+
195
+ print(f"Chosen ID column in annotation: {best_id_col}")
196
+ print(f"Overlap with expression IDs: {best_overlap}")
197
+ print(f"Chosen gene-symbol column: {gene_col} (rows with recognizable symbols: {best_symbol_count})")
198
+
199
+ # 3) If no overlap with expression IDs, return an empty mapping gracefully
200
+ if best_overlap == 0:
201
+ print("WARNING: No overlap between expression IDs and annotation IDs. Proceeding with empty gene-level data.")
202
+ gene_data = pd.DataFrame()
203
+ else:
204
+ # Build mapping dataframe
205
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=best_id_col, gene_col=gene_col)
206
+ # Apply mapping to convert probe-level to gene-level expression
207
+ mapped_gene_data = apply_gene_mapping(gene_data, mapping_df)
208
+
209
+ if mapped_gene_data.shape[0] == 0:
210
+ print("WARNING: Gene mapping produced an empty dataframe. Likely no usable gene symbols in the selected annotation column.")
211
+ gene_data = pd.DataFrame()
212
+ else:
213
+ gene_data = mapped_gene_data
214
+ print(f"Gene-level data shape: {gene_data.shape}")
215
+ print(f"First 10 mapped gene symbols: {list(gene_data.index[:10])}")
216
+
217
+ # Step 7: Gene Identifier Mapping
218
+ # Corrected Gene Identifier Mapping: prioritize true gene symbols
219
+
220
+ import pandas as pd
221
+
222
+ # Reload probe-level expression if gene_data was emptied previously
223
+ if isinstance(gene_data, pd.DataFrame) and gene_data.shape[0] == 0:
224
+ probe_expr = get_genetic_data(matrix_file)
225
+ else:
226
+ probe_expr = gene_data
227
+
228
+ ann = gene_annotation.copy()
229
+
230
+ # Remove obvious control probes if present
231
+ if 'CONTROL_TYPE' in ann.columns:
232
+ control_mask = ann['CONTROL_TYPE'].astype(str).str.lower().isin(['pos', 'neg', 'positive', 'negative'])
233
+ ann = ann.loc[~control_mask]
234
+
235
+ # Determine the ID column by overlap with expression probe IDs
236
+ expr_ids = set(probe_expr.index.astype(str).str.strip())
237
+ best_id_col = None
238
+ best_overlap = 0
239
+ for col in ann.columns:
240
+ try:
241
+ vals = set(ann[col].dropna().astype(str).str.strip())
242
+ except Exception:
243
+ continue
244
+ overlap = len(expr_ids & vals)
245
+ if overlap > best_overlap:
246
+ best_overlap = overlap
247
+ best_id_col = col
248
+
249
+ # Force gene-symbol column to GENE_SYMBOL if available; otherwise fallback cautiously
250
+ def count_recognizable_symbols(series: pd.Series) -> int:
251
+ try:
252
+ return series.dropna().astype(str).map(lambda x: len(extract_human_gene_symbols(x)) > 0).sum()
253
+ except Exception:
254
+ return 0
255
+
256
+ preferred_symbol_cols = []
257
+ if 'GENE_SYMBOL' in ann.columns:
258
+ preferred_symbol_cols.append('GENE_SYMBOL')
259
+ # Conservative fallbacks if GENE_SYMBOL is unusable
260
+ for alt in ['GENE_NAME', 'ACCESSION_STRING']:
261
+ if alt in ann.columns:
262
+ preferred_symbol_cols.append(alt)
263
+
264
+ chosen_gene_col = None
265
+ chosen_gene_count = -1
266
+
267
+ # Try GENE_SYMBOL first; if mapping yields empty later, we'll fallback
268
+ if 'GENE_SYMBOL' in ann.columns:
269
+ chosen_gene_col = 'GENE_SYMBOL'
270
+ chosen_gene_count = count_recognizable_symbols(ann['GENE_SYMBOL'])
271
+ else:
272
+ # Choose the first fallback column with any recognizable symbols
273
+ for c in [c for c in preferred_symbol_cols if c != 'GENE_SYMBOL']:
274
+ cnt = count_recognizable_symbols(ann[c])
275
+ if cnt > 0:
276
+ chosen_gene_col = c
277
+ chosen_gene_count = cnt
278
+ break
279
+
280
+ print(f"Chosen ID column in annotation: {best_id_col} (overlap with expression IDs: {best_overlap})")
281
+ print(f"Chosen gene-symbol column: {chosen_gene_col} (rows with recognizable symbols: {chosen_gene_count})")
282
+
283
+ # Build mapping and apply
284
+ def build_and_apply_mapping(annotation_df: pd.DataFrame, id_col: str, sym_col: str, expr_df: pd.DataFrame) -> pd.DataFrame:
285
+ mapping_df = get_gene_mapping(annotation_df, prob_col=id_col, gene_col=sym_col)
286
+ if mapping_df.shape[0] == 0:
287
+ return pd.DataFrame()
288
+ # Drop obvious placeholders
289
+ mapping_df = mapping_df[mapping_df['Gene'].astype(str).str.strip().isin({'', '---', 'NA', 'NaN', 'nan'}) == False]
290
+ mapped = apply_gene_mapping(expr_df, mapping_df)
291
+ return mapped
292
+
293
+ if (best_id_col is None) or (best_overlap == 0) or (chosen_gene_col is None):
294
+ print("WARNING: Unable to establish a valid probe-to-gene mapping. Producing empty gene-level data.")
295
+ gene_data = pd.DataFrame()
296
+ else:
297
+ mapped_gene_data = build_and_apply_mapping(ann, best_id_col, chosen_gene_col, probe_expr)
298
+
299
+ # If primary choice (GENE_SYMBOL) fails, try conservative fallbacks
300
+ if (mapped_gene_data.shape[0] == 0) and ('GENE_SYMBOL' in ann.columns):
301
+ for fc in [c for c in preferred_symbol_cols if c != 'GENE_SYMBOL']:
302
+ mapped_fb = build_and_apply_mapping(ann, best_id_col, fc, probe_expr)
303
+ if mapped_fb.shape[0] > 0:
304
+ mapped_gene_data = mapped_fb
305
+ print(f"Gene-level data shape (using fallback {fc}): {mapped_gene_data.shape}")
306
+ break
307
+
308
+ if mapped_gene_data.shape[0] == 0:
309
+ print("WARNING: Gene mapping produced an empty dataframe after enforcing GENE_SYMBOL and conservative fallbacks.")
310
+ gene_data = pd.DataFrame()
311
+ else:
312
+ gene_data = mapped_gene_data
313
+ # Quick sanity check for common housekeeping genes
314
+ housekeeping = {'ACTB', 'GAPDH', 'RPLP0', 'RPL13A', 'HPRT1', 'B2M', 'TUBB', 'EEF1A1'}
315
+ present_housekeeping = [g for g in housekeeping if g in set(gene_data.index)]
316
+ print(f"Gene-level data shape: {gene_data.shape}")
317
+ print(f"First 10 mapped gene symbols: {list(gene_data.index[:10])}")
318
+ print(f"Housekeeping genes found (sanity check): {present_housekeeping}")
output/preprocess/Head_and_Neck_Cancer/code/GSE156915.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Head_and_Neck_Cancer"
6
+ cohort = "GSE156915"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Head_and_Neck_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Head_and_Neck_Cancer/GSE156915"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/GSE156915.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/gene_data/GSE156915.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/clinical_data/GSE156915.csv"
16
+ json_path = "./output/z3/preprocess/Head_and_Neck_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+
41
+ # 1) Gene expression availability (based on "Whole transcriptome" in background info)
42
+ is_gene_available = True
43
+
44
+ # 2) Variable availability based on the provided Sample Characteristics Dictionary
45
+ # No explicit or inferable fields for the trait "Head_and_Neck_Cancer", age, or gender were provided.
46
+ trait_row = None
47
+ age_row = None
48
+ gender_row = None
49
+
50
+ # 2.2) Conversion functions
51
+
52
+ def _get_value_after_colon(x):
53
+ if x is None:
54
+ return None
55
+ s = str(x).strip()
56
+ if ':' in s:
57
+ s = s.split(':', 1)[1].strip()
58
+ return s if s != '' else None
59
+
60
+ def convert_trait(x):
61
+ """
62
+ Binary: Head_and_Neck_Cancer case=1, non-case=0.
63
+ Map known H&N terms to 1; explicit 'normal'/'control' to 0; otherwise None.
64
+ """
65
+ val = _get_value_after_colon(x)
66
+ if val is None:
67
+ return None
68
+ v = val.lower()
69
+ hn_terms = [
70
+ 'head and neck', 'hnscc', 'oral', 'oropharyngeal', 'laryngeal', 'hypopharyngeal',
71
+ 'nasopharyngeal', 'tongue', 'buccal mucosa'
72
+ ]
73
+ if any(t in v for t in hn_terms):
74
+ return 1
75
+ if 'control' in v or 'normal' in v or 'healthy' in v or 'non-cancer' in v:
76
+ return 0
77
+ # Non-H&N cancers (e.g., colorectal) are not our target trait -> treat as non-informative here
78
+ return None
79
+
80
+ def convert_age(x):
81
+ """
82
+ Continuous age in years. Extract numeric value.
83
+ """
84
+ val = _get_value_after_colon(x)
85
+ if val is None:
86
+ return None
87
+ m = re.search(r'(\d+(\.\d+)?)', val)
88
+ if not m:
89
+ return None
90
+ try:
91
+ return float(m.group(1))
92
+ except Exception:
93
+ return None
94
+
95
+ def convert_gender(x):
96
+ """
97
+ Binary gender: female=0, male=1.
98
+ """
99
+ val = _get_value_after_colon(x)
100
+ if val is None:
101
+ return None
102
+ v = val.strip().lower()
103
+ if v in ['female', 'f', 'woman', 'women']:
104
+ return 0
105
+ if v in ['male', 'm', 'man', 'men']:
106
+ return 1
107
+ return None
108
+
109
+ # 3) Save metadata (initial filtering)
110
+ is_trait_available = trait_row is not None
111
+ _ = validate_and_save_cohort_info(
112
+ is_final=False,
113
+ cohort=cohort,
114
+ info_path=json_path,
115
+ is_gene_available=is_gene_available,
116
+ is_trait_available=is_trait_available
117
+ )
118
+
119
+ # 4) Clinical feature extraction (skip because trait_row is None)
120
+ # If trait_row were available:
121
+ # selected_clinical_df = geo_select_clinical_features(
122
+ # clinical_df=clinical_data,
123
+ # trait=trait,
124
+ # trait_row=trait_row,
125
+ # convert_trait=convert_trait,
126
+ # age_row=age_row,
127
+ # convert_age=convert_age,
128
+ # gender_row=gender_row,
129
+ # convert_gender=convert_gender
130
+ # )
131
+ # preview = preview_df(selected_clinical_df, n=5)
132
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
133
+ # selected_clinical_df.to_csv(out_clinical_data_file)
output/preprocess/Head_and_Neck_Cancer/code/GSE184944.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Head_and_Neck_Cancer"
6
+ cohort = "GSE184944"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Head_and_Neck_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Head_and_Neck_Cancer/GSE184944"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/GSE184944.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/gene_data/GSE184944.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/clinical_data/GSE184944.csv"
16
+ json_path = "./output/z3/preprocess/Head_and_Neck_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+ import pandas as pd
41
+
42
+ # 1. Gene Expression Data Availability
43
+ # NanoString immune gene expression profiling => gene expression available
44
+ is_gene_available = True
45
+
46
+ # 2. Variable Availability and Data Type Conversion
47
+
48
+ # 2.1 Data Availability based on Sample Characteristics Dictionary:
49
+ # {0: ['histology: LL', 'histology: PL', 'histology: PEL', 'histology: EL'],
50
+ # 1: ['smoking status: F', 'smoking status: N', 'smoking status: C'],
51
+ # 2: ['gender: F', 'gender: M']}
52
+
53
+ # Trait is Head_and_Neck_Cancer; dataset contains leukoplakia subtypes without explicit cancer status => trait not available
54
+ trait_row = None
55
+
56
+ # No age key provided
57
+ age_row = None
58
+
59
+ # Gender available at key 2
60
+ gender_row = 2
61
+
62
+ # 2.2 Data Type Conversion
63
+
64
+ def convert_trait(x):
65
+ # Head_and_Neck_Cancer status not explicitly provided in this dataset; cannot be inferred reliably from leukoplakia subtype
66
+ return None
67
+
68
+ def convert_age(x):
69
+ if x is None:
70
+ return None
71
+ try:
72
+ # Extract substring after colon if present
73
+ s = str(x)
74
+ if ':' in s:
75
+ s = s.split(':', 1)[1].strip()
76
+ # Extract first numeric (integer or float)
77
+ m = re.search(r'[-+]?\d*\.?\d+', s)
78
+ if not m:
79
+ return None
80
+ val = float(m.group())
81
+ # Return int if whole number
82
+ return int(val) if val.is_integer() else val
83
+ except Exception:
84
+ return None
85
+
86
+ def convert_gender(x):
87
+ if x is None:
88
+ return None
89
+ s = str(x)
90
+ if ':' in s:
91
+ s = s.split(':', 1)[1].strip()
92
+ s_lower = s.strip().lower()
93
+ if s_lower in {'f', 'female', '0'}:
94
+ return 0
95
+ if s_lower in {'m', 'male', '1'}:
96
+ return 1
97
+ return None
98
+
99
+ # 3. Save Metadata (initial filtering)
100
+ is_trait_available = trait_row is not None
101
+ _ = validate_and_save_cohort_info(
102
+ is_final=False,
103
+ cohort=cohort,
104
+ info_path=json_path,
105
+ is_gene_available=is_gene_available,
106
+ is_trait_available=is_trait_available
107
+ )
108
+
109
+ # 4. Clinical Feature Extraction (skip if trait_row is None)
110
+ if trait_row is not None:
111
+ selected_clinical_df = geo_select_clinical_features(
112
+ clinical_df=clinical_data,
113
+ trait=trait,
114
+ trait_row=trait_row,
115
+ convert_trait=convert_trait,
116
+ age_row=age_row,
117
+ convert_age=convert_age,
118
+ gender_row=gender_row,
119
+ convert_gender=convert_gender
120
+ )
121
+ _ = preview_df(selected_clinical_df)
122
+ # Save clinical data
123
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
124
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
output/preprocess/Head_and_Neck_Cancer/code/GSE201777.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Head_and_Neck_Cancer"
6
+ cohort = "GSE201777"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Head_and_Neck_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Head_and_Neck_Cancer/GSE201777"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/GSE201777.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/gene_data/GSE201777.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/clinical_data/GSE201777.csv"
16
+ json_path = "./output/z3/preprocess/Head_and_Neck_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+
42
+ # 1) Gene Expression Data Availability
43
+ is_gene_available = True # Microarray gene expression was performed on RNA samples.
44
+
45
+ # 2) Variable Availability and Data Type Conversion
46
+
47
+ # Use tissue to infer sample-level cancer status:
48
+ # - Tumor -> 1
49
+ # - Mucosa (non-tumoral) -> 0
50
+ # - Lymph node -> None (avoid misclassification due to metastasis-negative patients' lymph nodes)
51
+ trait_row = 1 # 'tissue' field
52
+ age_row = None
53
+ gender_row = None
54
+
55
+ def _after_colon(x):
56
+ if x is None:
57
+ return None
58
+ s = str(x)
59
+ return s.split(":", 1)[1].strip() if ":" in s else s.strip()
60
+
61
+ def convert_trait(x):
62
+ v = _after_colon(x)
63
+ if not v:
64
+ return None
65
+ v_low = v.lower()
66
+ if 'tumor' in v_low or 'tumour' in v_low:
67
+ return 1
68
+ if 'mucosa' in v_low:
69
+ return 0
70
+ if 'lymph' in v_low:
71
+ return None
72
+ if v_low in {'na', 'n/a', 'unknown', 'none', ''}:
73
+ return None
74
+ return None
75
+
76
+ def convert_age(x):
77
+ v = _after_colon(x)
78
+ if not v:
79
+ return None
80
+ m = re.search(r'(\d+(\.\d+)?)', v)
81
+ if m:
82
+ try:
83
+ val = float(m.group(1))
84
+ return int(val) if val.is_integer() else val
85
+ except:
86
+ return None
87
+ return None
88
+
89
+ def convert_gender(x):
90
+ v = _after_colon(x)
91
+ if not v:
92
+ return None
93
+ v_low = v.lower()
94
+ if v_low in {'male', 'm', 'man'}:
95
+ return 1
96
+ if v_low in {'female', 'f', 'woman'}:
97
+ return 0
98
+ return None
99
+
100
+ # 3) Save Metadata (initial filtering)
101
+ is_trait_available = trait_row is not None
102
+ _ = validate_and_save_cohort_info(
103
+ is_final=False,
104
+ cohort=cohort,
105
+ info_path=json_path,
106
+ is_gene_available=is_gene_available,
107
+ is_trait_available=is_trait_available
108
+ )
109
+
110
+ # 4) Clinical Feature Extraction (only if trait is available)
111
+ if is_trait_available:
112
+ selected_clinical_df = geo_select_clinical_features(
113
+ clinical_df=clinical_data,
114
+ trait=trait,
115
+ trait_row=trait_row,
116
+ convert_trait=convert_trait,
117
+ age_row=age_row,
118
+ convert_age=convert_age,
119
+ gender_row=gender_row,
120
+ convert_gender=convert_gender
121
+ )
122
+ clinical_preview = preview_df(selected_clinical_df)
123
+ print(clinical_preview)
124
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
125
+ selected_clinical_df.to_csv(out_clinical_data_file)
126
+
127
+ # Step 3: Gene Data Extraction
128
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
129
+ gene_data = get_genetic_data(matrix_file)
130
+
131
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
132
+ print(gene_data.index[:20])
133
+
134
+ # Step 4: Gene Identifier Review
135
+ print("requires_gene_mapping = True")
136
+
137
+ # Step 5: Gene Annotation
138
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
139
+ gene_annotation = get_gene_annotation(soft_file)
140
+
141
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
142
+ print("Gene annotation preview:")
143
+ print(preview_df(gene_annotation))
144
+
145
+ # Step 6: Gene Identifier Mapping
146
+ # Identify the appropriate columns in the annotation dataframe
147
+ probe_id_col = 'ID'
148
+ gene_symbol_col = 'Gene Symbol'
149
+
150
+ # Build mapping dataframe (Probe ID -> Gene Symbol)
151
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_id_col, gene_col=gene_symbol_col)
152
+
153
+ # Apply mapping to convert probe-level data to gene-level data
154
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
155
+
156
+ # Step 7: Data Normalization and Linking
157
+ import os
158
+
159
+ # 1. Normalize gene symbols and save
160
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
161
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
162
+ normalized_gene_data.to_csv(out_gene_data_file)
163
+
164
+ # 2. Link clinical and genetic data (fix variable name)
165
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
166
+
167
+ # 3. Handle missing values
168
+ linked_data = handle_missing_values(linked_data, trait)
169
+
170
+ # 4. Assess bias and remove biased demographic features
171
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
172
+
173
+ # 5. Final validation and save cohort info
174
+ note = ("INFO: Trait derived from 'tissue' field (Tumor=1, Mucosa=0); lymph node samples were set to NaN and removed "
175
+ "during filtering. No age/gender fields available in clinical annotations for this series.")
176
+ is_usable = validate_and_save_cohort_info(
177
+ is_final=True,
178
+ cohort=cohort,
179
+ info_path=json_path,
180
+ is_gene_available=True,
181
+ is_trait_available=True,
182
+ is_biased=is_trait_biased,
183
+ df=unbiased_linked_data,
184
+ note=note
185
+ )
186
+
187
+ # 6. Save linked data only if usable
188
+ if is_usable:
189
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
190
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Head_and_Neck_Cancer/code/GSE212250.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Head_and_Neck_Cancer"
6
+ cohort = "GSE212250"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Head_and_Neck_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Head_and_Neck_Cancer/GSE212250"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/GSE212250.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/gene_data/GSE212250.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/clinical_data/GSE212250.csv"
16
+ json_path = "./output/z3/preprocess/Head_and_Neck_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Step 1: Assess gene expression data availability based on background info (CUT&RUN epigenetic profiling)
40
+ is_gene_available = False # CUT&RUN histone mark profiling; not suitable gene expression data
41
+
42
+ # Step 2: Variable availability and converters
43
+ # From the sample characteristics, all samples are head and neck cancer cell lines; no age/gender provided.
44
+ trait_row = None # Everyone has Head_and_Neck_Cancer -> constant; treat as not available
45
+ age_row = None # No age field observed
46
+ gender_row = None # No gender field observed
47
+
48
+ # Converters (robust, though not used due to unavailability)
49
+ def _after_colon(x):
50
+ if x is None:
51
+ return None
52
+ s = str(x)
53
+ parts = s.split(":", 1)
54
+ val = parts[1] if len(parts) > 1 else parts[0]
55
+ return val.strip()
56
+
57
+ def convert_trait(x):
58
+ # Binary: 1 = cancer, 0 = non-cancer; unknown -> None
59
+ val = _after_colon(x)
60
+ if val is None or val == "":
61
+ return None
62
+ v = val.lower()
63
+ cancer_keywords = ["cancer", "tumor", "carcinoma", "metastatic", "metastasis", "cisplatin", "hn", "oral"]
64
+ control_keywords = ["normal", "healthy", "control", "adjacent", "benign", "non-cancer", "noncancer"]
65
+ if any(k in v for k in cancer_keywords):
66
+ return 1
67
+ if any(k in v for k in control_keywords):
68
+ return 0
69
+ return None
70
+
71
+ def convert_age(x):
72
+ # Continuous age in years; extract numeric
73
+ import re
74
+ val = _after_colon(x)
75
+ if val is None or val == "":
76
+ return None
77
+ nums = re.findall(r"[0-9]+\.?[0-9]*", val)
78
+ if not nums:
79
+ return None
80
+ try:
81
+ age = float(nums[0])
82
+ # Basic sanity check
83
+ if 0 <= age <= 120:
84
+ return age
85
+ return None
86
+ except Exception:
87
+ return None
88
+
89
+ def convert_gender(x):
90
+ # Binary: female=0, male=1
91
+ val = _after_colon(x)
92
+ if val is None or val == "":
93
+ return None
94
+ v = val.strip().lower()
95
+ if v in {"male", "m", "man", "men"}:
96
+ return 1
97
+ if v in {"female", "f", "woman", "women"}:
98
+ return 0
99
+ return None
100
+
101
+ # Step 3: Initial filtering and save metadata
102
+ is_trait_available = trait_row is not None
103
+ _ = validate_and_save_cohort_info(
104
+ is_final=False,
105
+ cohort=cohort,
106
+ info_path=json_path,
107
+ is_gene_available=is_gene_available,
108
+ is_trait_available=is_trait_available
109
+ )
110
+
111
+ # Step 4: Clinical feature extraction skipped because trait_row is None
output/preprocess/Head_and_Neck_Cancer/code/GSE218109.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Head_and_Neck_Cancer"
6
+ cohort = "GSE218109"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Head_and_Neck_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Head_and_Neck_Cancer/GSE218109"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/GSE218109.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/gene_data/GSE218109.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/clinical_data/GSE218109.csv"
16
+ json_path = "./output/z3/preprocess/Head_and_Neck_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+
41
+ # 1) Gene expression availability
42
+ is_gene_available = True # Transcriptional profiling of ESCC tumors (likely mRNA expression)
43
+
44
+ # 2) Variable availability (from provided Sample Characteristics Dictionary)
45
+ # Trait (Head_and_Neck_Cancer): all samples are ESCC tumors => constant -> not available
46
+ trait_row = None
47
+
48
+ # Age and Gender are available
49
+ age_row = 1
50
+ gender_row = 0
51
+
52
+ # 2.2) Data type conversion functions
53
+ def convert_trait(x):
54
+ # Not used since trait_row is None; return None defensively
55
+ return None
56
+
57
+ def convert_age(x):
58
+ if x is None:
59
+ return None
60
+ s = str(x)
61
+ # Extract substring after colon if present
62
+ if ":" in s:
63
+ s = s.split(":", 1)[1]
64
+ # Extract first number (int or float)
65
+ m = re.search(r'[-+]?\d*\.?\d+', s)
66
+ if not m:
67
+ return None
68
+ try:
69
+ val = float(m.group())
70
+ return val
71
+ except Exception:
72
+ return None
73
+
74
+ def convert_gender(x):
75
+ if x is None:
76
+ return None
77
+ s = str(x)
78
+ if ":" in s:
79
+ s = s.split(":", 1)[1]
80
+ s = s.strip().lower()
81
+ if s in {"f", "female", "woman", "women"}:
82
+ return 0
83
+ if s in {"m", "male", "man", "men"}:
84
+ return 1
85
+ return None
86
+
87
+ # 3) Save metadata (initial filtering)
88
+ is_trait_available = trait_row is not None
89
+ _ = validate_and_save_cohort_info(
90
+ is_final=False,
91
+ cohort=cohort,
92
+ info_path=json_path,
93
+ is_gene_available=is_gene_available,
94
+ is_trait_available=is_trait_available
95
+ )
96
+
97
+ # 4) Clinical feature extraction (skip because trait_row is None)
98
+ # If trait_row were available:
99
+ # if trait_row is not None:
100
+ # selected_df = geo_select_clinical_features(
101
+ # clinical_df=clinical_data,
102
+ # trait=trait,
103
+ # trait_row=trait_row,
104
+ # convert_trait=convert_trait,
105
+ # age_row=age_row,
106
+ # convert_age=convert_age,
107
+ # gender_row=gender_row,
108
+ # convert_gender=convert_gender
109
+ # )
110
+ # _ = preview_df(selected_df)
111
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
112
+ # selected_df.to_csv(out_clinical_data_file, index=True)
113
+
114
+ # Step 3: Gene Data Extraction
115
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
116
+ gene_data = get_genetic_data(matrix_file)
117
+
118
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
119
+ print(gene_data.index[:20])
120
+
121
+ # Step 4: Gene Identifier Review
122
+ print("requires_gene_mapping = True")
123
+
124
+ # Step 5: Gene Annotation
125
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
126
+ gene_annotation = get_gene_annotation(soft_file)
127
+
128
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
129
+ print("Gene annotation preview:")
130
+ print(preview_df(gene_annotation))
131
+
132
+ # Step 6: Gene Identifier Mapping
133
+ # Determine the appropriate columns for mapping: probe ID ('ID') and gene symbols ('GENE_SYMBOL')
134
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')
135
+
136
+ # Apply the mapping to convert probe-level data to gene-level expression
137
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
138
+
139
+ # Step 7: Data Normalization and Linking
140
+ import os
141
+
142
+ # 1. Normalize gene symbols and save gene expression data
143
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
144
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
145
+ normalized_gene_data.to_csv(out_gene_data_file)
146
+
147
+ # Since trait_row was determined to be None in Step 2, trait is unavailable for this cohort.
148
+ is_gene_available = True
149
+ is_trait_available = False
150
+
151
+ # 2–4. Skip linking, missing value handling, and bias judgment due to missing trait.
152
+ # 5. Final validation and save cohort info (record as unavailable for association due to missing trait)
153
+ note = ("WARNING: Trait not available for this cohort. All samples are ESCC tumors "
154
+ "(constant tissue), so the specified trait cannot be constructed; "
155
+ "clinical linking skipped. Saved normalized gene data only.")
156
+ _ = validate_and_save_cohort_info(
157
+ is_final=True,
158
+ cohort=cohort,
159
+ info_path=json_path,
160
+ is_gene_available=is_gene_available,
161
+ is_trait_available=is_trait_available,
162
+ is_biased=False, # Not applicable since trait is unavailable
163
+ df=normalized_gene_data.T, # Provide a valid dataframe for metadata recording
164
+ note=note
165
+ )
166
+
167
+ # 6. Do not save linked data since the dataset is not usable for association without trait information.
output/preprocess/Head_and_Neck_Cancer/code/GSE244580.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Head_and_Neck_Cancer"
6
+ cohort = "GSE244580"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Head_and_Neck_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Head_and_Neck_Cancer/GSE244580"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/GSE244580.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/gene_data/GSE244580.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/clinical_data/GSE244580.csv"
16
+ json_path = "./output/z3/preprocess/Head_and_Neck_Cancer/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+ import pandas as pd
42
+
43
+ # 1) Gene expression availability (microarray gene expression per background info)
44
+ is_gene_available = True
45
+
46
+ # 2) Variable availability
47
+ # Sample characteristics show only disease state categories; no explicit age/gender present.
48
+ trait_row = 0
49
+ age_row = None
50
+ gender_row = None
51
+
52
+ # 2.2) Converters
53
+ def _extract_value(x):
54
+ if x is None:
55
+ return None
56
+ try:
57
+ s = str(x)
58
+ except Exception:
59
+ return None
60
+ parts = s.split(":", 1)
61
+ val = parts[1] if len(parts) > 1 else parts[0]
62
+ return val.strip()
63
+
64
+ def convert_trait(x):
65
+ v = _extract_value(x)
66
+ if v is None:
67
+ return None
68
+ vl = v.lower()
69
+ # Cancer cases: oropharyngeal cancer, peritumoral tissue, lymph node of cancer patients
70
+ if ("cancer" in vl) or ("peritumor" in vl) or ("peritumour" in vl):
71
+ return 1
72
+ # Non-cancer control: chronic tonsillitis
73
+ if ("tonsillitis" in vl):
74
+ return 0
75
+ return None
76
+
77
+ def convert_age(x):
78
+ v = _extract_value(x)
79
+ if v is None:
80
+ return None
81
+ # Extract first number as age
82
+ m = re.search(r"(\d+(\.\d+)?)", v)
83
+ if not m:
84
+ return None
85
+ try:
86
+ age = float(m.group(1))
87
+ # sanity check for human age
88
+ if 0 <= age <= 120:
89
+ return age
90
+ except Exception:
91
+ return None
92
+ return None
93
+
94
+ def convert_gender(x):
95
+ v = _extract_value(x)
96
+ if v is None:
97
+ return None
98
+ vl = v.strip().lower()
99
+ if vl in {"male", "m"}:
100
+ return 1
101
+ if vl in {"female", "f"}:
102
+ return 0
103
+ return None
104
+
105
+ # 3) Save metadata (initial filtering)
106
+ is_trait_available = trait_row is not None
107
+ _ = validate_and_save_cohort_info(
108
+ is_final=False,
109
+ cohort=cohort,
110
+ info_path=json_path,
111
+ is_gene_available=is_gene_available,
112
+ is_trait_available=is_trait_available
113
+ )
114
+
115
+ # 4) Clinical Feature Extraction
116
+ if trait_row is not None:
117
+ selected_clinical_df = geo_select_clinical_features(
118
+ clinical_df=clinical_data,
119
+ trait=trait,
120
+ trait_row=trait_row,
121
+ convert_trait=convert_trait,
122
+ age_row=age_row,
123
+ convert_age=convert_age,
124
+ gender_row=gender_row,
125
+ convert_gender=convert_gender
126
+ )
127
+ preview = preview_df(selected_clinical_df)
128
+ print(preview)
129
+
130
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
131
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
132
+
133
+ # Step 3: Gene Data Extraction
134
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
135
+ gene_data = get_genetic_data(matrix_file)
136
+
137
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
138
+ print(gene_data.index[:20])
139
+
140
+ # Step 4: Gene Identifier Review
141
+ requires_gene_mapping = True
142
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
143
+
144
+ # Step 5: Gene Annotation
145
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
146
+ gene_annotation = get_gene_annotation(soft_file)
147
+
148
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
149
+ print("Gene annotation preview:")
150
+ print(preview_df(gene_annotation))
151
+
152
+ # Step 6: Gene Identifier Mapping
153
+ # Ensure we are starting from the original probe-level matrix
154
+ probe_expr_df = get_genetic_data(matrix_file)
155
+
156
+ # Identify the probe ID column in annotation
157
+ id_col = 'ID' if 'ID' in gene_annotation.columns else gene_annotation.columns[0]
158
+
159
+ # Prefer true gene symbol columns (case-insensitive), else fall back to GB_ACC, else SPOT_ID
160
+ def _norm(s: str) -> str:
161
+ return re.sub(r'[\s_]+', '', str(s)).lower()
162
+
163
+ symbol_like_targets = {'genesymbol', 'symbol'}
164
+ symbol_cols = [c for c in gene_annotation.columns if _norm(c) in symbol_like_targets]
165
+
166
+ selected_mode = None
167
+ gene_col = None
168
+ if len(symbol_cols) > 0:
169
+ gene_col = symbol_cols[0]
170
+ selected_mode = 'symbol'
171
+ elif 'GB_ACC' in gene_annotation.columns and gene_annotation['GB_ACC'].notna().sum() > 0:
172
+ gene_col = 'GB_ACC'
173
+ selected_mode = 'refseq'
174
+ elif 'SPOT_ID' in gene_annotation.columns and gene_annotation['SPOT_ID'].notna().sum() > 0:
175
+ gene_col = 'SPOT_ID'
176
+ selected_mode = 'spot'
177
+ else:
178
+ # As a last resort, pick any non-ID column
179
+ non_id_cols = [c for c in gene_annotation.columns if c != id_col]
180
+ gene_col = non_id_cols[0] if non_id_cols else id_col
181
+ selected_mode = 'fallback'
182
+
183
+ print(f"Annotation columns available: {list(gene_annotation.columns)}")
184
+ print(f"Identifier column selected: {id_col}")
185
+ print(f"Selected mapping column: {gene_col} (mode={selected_mode})")
186
+
187
+ # Build mapping dataframe
188
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=id_col, gene_col=gene_col)
189
+
190
+ # Apply mapping
191
+ if selected_mode == 'symbol':
192
+ # Use library function that extracts/normalizes human symbols and aggregates
193
+ gene_data = apply_gene_mapping(expression_df=probe_expr_df, mapping_df=mapping_df)
194
+ else:
195
+ # Avoid extract_human_gene_symbols to prevent dropping NR_/XR_/coordinates.
196
+ map_df = mapping_df[mapping_df['ID'].isin(probe_expr_df.index)].copy()
197
+ map_df = map_df.dropna(subset=['Gene'])
198
+ # Aggregate probe expressions per mapped identifier
199
+ merged = map_df.set_index('ID').join(probe_expr_df, how='inner')
200
+ expr_cols = [c for c in merged.columns if c not in ['Gene']]
201
+ gene_data = merged.groupby('Gene')[expr_cols].sum()
202
+
203
+ # Diagnostics
204
+ n_genes = gene_data.shape[0]
205
+ example_genes = list(gene_data.index[:10])
206
+ print(f"Mapped features: {n_genes}. Example identifiers: {example_genes}")
207
+
208
+ # Step 7: Data Normalization and Linking
209
+ import os
210
+
211
+ # 1. Normalize gene symbols and save gene data
212
+ initial_gene_count = gene_data.shape[0]
213
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
214
+
215
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
216
+ normalized_gene_data.to_csv(out_gene_data_file)
217
+
218
+ # 2. Link clinical and genetic data
219
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
220
+
221
+ # 3. Handle missing values
222
+ processed_linked_data = handle_missing_values(linked_data, trait)
223
+
224
+ # 4. Determine bias where possible
225
+ if processed_linked_data.empty or trait not in processed_linked_data.columns:
226
+ is_trait_biased = True
227
+ unbiased_linked_data = processed_linked_data
228
+ else:
229
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(processed_linked_data, trait)
230
+
231
+ # 5. Final validation and save cohort info
232
+ post_norm_gene_count = normalized_gene_data.shape[0]
233
+ note = (
234
+ f"INFO: Mapping used RefSeq accessions (GB_ACC) from platform; gene-symbol normalization reduced features "
235
+ f"from {initial_gene_count} to {post_norm_gene_count}. This platform lacks explicit gene symbols, "
236
+ f"so normalization likely dropped many features."
237
+ )
238
+
239
+ is_gene_available_final = post_norm_gene_count > 0
240
+ is_trait_available_final = True # trait was extracted in prior steps
241
+
242
+ is_usable = validate_and_save_cohort_info(
243
+ is_final=True,
244
+ cohort=cohort,
245
+ info_path=json_path,
246
+ is_gene_available=is_gene_available_final,
247
+ is_trait_available=is_trait_available_final,
248
+ is_biased=is_trait_biased,
249
+ df=unbiased_linked_data,
250
+ note=note
251
+ )
252
+
253
+ # 6. Save linked data if usable
254
+ if is_usable:
255
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
256
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Head_and_Neck_Cancer/code/TCGA.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Head_and_Neck_Cancer"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/TCGA.csv"
12
+ out_gene_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z3/preprocess/Head_and_Neck_Cancer/clinical_data/TCGA.csv"
14
+ json_path = "./output/z3/preprocess/Head_and_Neck_Cancer/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import pandas as pd
20
+
21
+ # 1) Select the most appropriate TCGA cohort directory for Head and Neck Cancer
22
+ subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
23
+ subdirs_lc = {d: d.lower() for d in subdirs}
24
+
25
+ # Preference keywords in order
26
+ preference_keywords = ['head_and_neck_cancer', 'head_and_neck', '(hnsc)', 'hnsc', 'scchn']
27
+
28
+ def pick_best_dir(subdirs_map, keywords):
29
+ # Score directories based on keyword presence and specificity
30
+ scored = []
31
+ for d, dl in subdirs_map.items():
32
+ score = 0
33
+ for i, kw in enumerate(keywords):
34
+ if kw in dl:
35
+ score += (len(keywords) - i) * 10 # earlier keywords get higher weight
36
+ if '(hnsc)' in dl:
37
+ score += 5
38
+ if score > 0:
39
+ scored.append((score, len(dl), d))
40
+ if not scored:
41
+ return None
42
+ # Sort by score desc, then length desc (more specific/longer name)
43
+ scored.sort(key=lambda x: (x[0], x[1]), reverse=True)
44
+ return scored[0][2]
45
+
46
+ selected_subdir = pick_best_dir(subdirs_lc, preference_keywords)
47
+
48
+ if selected_subdir is None:
49
+ print("No suitable TCGA subdirectory found for Head and Neck Cancer. Skipping this trait.")
50
+ # Record unusable cohort
51
+ _ = validate_and_save_cohort_info(
52
+ is_final=False,
53
+ cohort="TCGA_Head_and_Neck_Cancer",
54
+ info_path=json_path,
55
+ is_gene_available=False,
56
+ is_trait_available=False
57
+ )
58
+ else:
59
+ print(f"Selected TCGA subdirectory: {selected_subdir}")
60
+ cohort_dir = os.path.join(tcga_root_dir, selected_subdir)
61
+
62
+ # 2) Identify clinical and genetic data file paths
63
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
64
+
65
+ # 3) Load both files as DataFrames
66
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False)
67
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False)
68
+
69
+ # 4) Print clinical data column names
70
+ print(list(clinical_df.columns))
71
+
72
+ # Step 2: Find Candidate Demographic Features
73
+ import os
74
+ import re
75
+ import pandas as pd
76
+
77
+ # Locate clinical file
78
+ cohort_dir = os.path.join(tcga_root_dir, "TCGA_Head_and_Neck_Cancer_(HNSC)")
79
+ clinical_file_path, _ = tcga_get_relevant_filepaths(cohort_dir)
80
+
81
+ # Load clinical dataframe
82
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, dtype=str)
83
+
84
+ # Identify candidate columns
85
+ cols_lower = {c: c.lower() for c in clinical_df.columns}
86
+
87
+ def is_age_col(cl: str) -> bool:
88
+ # Exclude 'stage' false positives and capture standalone 'age' tokens or explicit birth proxies
89
+ if 'stage' in cl:
90
+ return False
91
+ if 'days_to_birth' in cl:
92
+ return True
93
+ return re.search(r'(^|[^a-z])age([^a-z]|$)', cl) is not None
94
+
95
+ candidate_age_cols = [c for c, cl in cols_lower.items() if is_age_col(cl)]
96
+ candidate_gender_cols = [
97
+ c for c, cl in cols_lower.items()
98
+ if ('gender' in cl) or (re.search(r'(^|[^a-z])sex([^a-z]|$)', cl) is not None)
99
+ ]
100
+
101
+ # Print candidate lists (strict format)
102
+ print(f"candidate_age_cols = {candidate_age_cols}")
103
+ print(f"candidate_gender_cols = {candidate_gender_cols}")
104
+
105
+ # Preview extracted data for age and gender
106
+ age_preview = preview_df(clinical_df[candidate_age_cols]) if candidate_age_cols else {}
107
+ gender_preview = preview_df(clinical_df[candidate_gender_cols]) if candidate_gender_cols else {}
108
+
109
+ print(age_preview)
110
+ print(gender_preview)
111
+
112
+ # Step 3: Select Demographic Features
113
+ # Select age and gender columns from candidate lists with sensible defaults and fallbacks
114
+ try:
115
+ candidate_age_cols
116
+ except NameError:
117
+ candidate_age_cols = []
118
+ try:
119
+ candidate_gender_cols
120
+ except NameError:
121
+ candidate_gender_cols = []
122
+
123
+ # Preferred order for age columns based on typical TCGA clinical data
124
+ preferred_age_cols = [
125
+ "age_at_initial_pathologic_diagnosis",
126
+ "age_at_diagnosis",
127
+ "age",
128
+ "days_to_birth",
129
+ ]
130
+
131
+ # Choose age_col
132
+ age_col = None
133
+ for col in preferred_age_cols:
134
+ if col in candidate_age_cols:
135
+ age_col = col
136
+ break
137
+
138
+ # Choose gender_col
139
+ gender_col = "gender" if "gender" in candidate_gender_cols else None
140
+
141
+ # Attempt to find preview dictionaries created in previous steps to print sample values
142
+ def find_preview_values_for(col_name: str):
143
+ if col_name is None:
144
+ return None
145
+ for var_name, obj in globals().items():
146
+ if isinstance(obj, dict) and col_name in obj:
147
+ vals = obj.get(col_name, None)
148
+ if isinstance(vals, list):
149
+ return vals
150
+ return None
151
+
152
+ age_preview_vals = find_preview_values_for(age_col)
153
+ gender_preview_vals = find_preview_values_for(gender_col)
154
+
155
+ # Explicitly print out the chosen columns and any available preview values
156
+ print(f"Chosen age_col: {age_col}")
157
+ if age_preview_vals is not None:
158
+ print(f"Preview values for {age_col}: {age_preview_vals}")
159
+
160
+ print(f"Chosen gender_col: {gender_col}")
161
+ if gender_preview_vals is not None:
162
+ print(f"Preview values for {gender_col}: {gender_preview_vals}")
163
+
164
+ # Step 4: Feature Engineering and Validation
165
+ import os
166
+ import pandas as pd
167
+
168
+ # Ensure clinical and genetic data are loaded
169
+ try:
170
+ clinical_df
171
+ genetic_df
172
+ except NameError:
173
+ cohort_dir = os.path.join(tcga_root_dir, "TCGA_Head_and_Neck_Cancer_(HNSC)")
174
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
175
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, dtype=str, low_memory=False)
176
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False)
177
+
178
+ # Ensure chosen demographic columns exist; if not, set None
179
+ try:
180
+ age_col
181
+ except NameError:
182
+ age_col = None
183
+ try:
184
+ gender_col
185
+ except NameError:
186
+ gender_col = None
187
+
188
+ if age_col not in clinical_df.columns:
189
+ age_col = None
190
+ if gender_col not in clinical_df.columns:
191
+ gender_col = None
192
+
193
+ # 1) Extract and standardize clinical features (Trait, Age, Gender)
194
+ selected_clinical_df = tcga_select_clinical_features(
195
+ clinical_df=clinical_df,
196
+ trait=trait,
197
+ age_col=age_col,
198
+ gender_col=gender_col
199
+ )
200
+
201
+ # 2) Normalize gene symbols; restrict to HNSC samples present in clinical data; save normalized gene data
202
+ # Convert expression values to numeric (coerce non-numeric to NaN)
203
+ genetic_df = genetic_df.apply(pd.to_numeric, errors='coerce')
204
+
205
+ # Normalize gene symbols in index and aggregate duplicates
206
+ normalized_gene_df = normalize_gene_symbols_in_index(genetic_df)
207
+
208
+ # Match expression columns to clinical samples (HNSC cohort)
209
+ matched_samples = sorted(list(set(normalized_gene_df.columns).intersection(set(selected_clinical_df.index))))
210
+ normalized_gene_df_matched = normalized_gene_df.loc[:, matched_samples]
211
+
212
+ # Save normalized gene data (for this cohort's samples)
213
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
214
+ normalized_gene_df_matched.to_csv(out_gene_data_file)
215
+
216
+ # 3) Link clinical and genetic data on sample IDs
217
+ gene_df_T = normalized_gene_df_matched.T # samples x genes
218
+ # Inner join on samples to ensure alignment
219
+ linked_data = pd.concat([selected_clinical_df.loc[matched_samples], gene_df_T], axis=1, join='inner')
220
+
221
+ # 4) Handle missing values systematically
222
+ processed_df = handle_missing_values(linked_data, trait_col=trait)
223
+
224
+ # 5) Determine bias in trait and demographic features; remove biased demographics
225
+ trait_biased, final_df = judge_and_remove_biased_features(processed_df, trait)
226
+
227
+ # 6) Final validation and save cohort info
228
+ # Determine availability flags
229
+ covariate_cols = [trait, 'Age', 'Gender']
230
+ gene_cols_final = [c for c in final_df.columns if c not in covariate_cols]
231
+ is_gene_available = len(gene_cols_final) > 0
232
+ is_trait_available = (trait in final_df.columns) and (final_df[trait].notna().sum() > 0) and (len(final_df) > 0)
233
+
234
+ note = ("INFO: Gene symbols normalized using NCBI synonym mapping; gene matrix restricted to HNSC samples; "
235
+ "Trait derived from TCGA sample barcode (01-09 tumor = 1, 10-19 normal = 0).")
236
+
237
+ is_usable = validate_and_save_cohort_info(
238
+ is_final=True,
239
+ cohort="TCGA_Head_and_Neck_Cancer",
240
+ info_path=json_path,
241
+ is_gene_available=is_gene_available,
242
+ is_trait_available=is_trait_available,
243
+ is_biased=trait_biased,
244
+ df=final_df,
245
+ note=note
246
+ )
247
+
248
+ # 7) Save usable linked data
249
+ if is_usable:
250
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
251
+ # Save the cleaned and validated dataset
252
+ final_df.to_csv(out_data_file)
253
+
254
+ # Ensure 'linked_data' points to the final processed dataset for downstream use
255
+ linked_data = final_df
output/preprocess/Head_and_Neck_Cancer/cohort_info.json CHANGED
@@ -1,112 +1 @@
1
- {
2
- "GSE244580": {
3
- "is_usable": true,
4
- "is_gene_available": true,
5
- "is_trait_available": true,
6
- "is_available": true,
7
- "is_biased": false,
8
- "has_age": false,
9
- "has_gender": false,
10
- "sample_size": 30
11
- },
12
- "GSE218109": {
13
- "is_usable": true,
14
- "is_gene_available": true,
15
- "is_trait_available": true,
16
- "is_available": true,
17
- "is_biased": false,
18
- "has_age": true,
19
- "has_gender": true,
20
- "sample_size": 36
21
- },
22
- "GSE212250": {
23
- "is_usable": false,
24
- "is_gene_available": false,
25
- "is_trait_available": false,
26
- "is_available": false,
27
- "is_biased": null,
28
- "has_age": null,
29
- "has_gender": null,
30
- "sample_size": null
31
- },
32
- "GSE201777": {
33
- "is_usable": true,
34
- "is_gene_available": true,
35
- "is_trait_available": true,
36
- "is_available": true,
37
- "is_biased": false,
38
- "has_age": false,
39
- "has_gender": false,
40
- "sample_size": 47
41
- },
42
- "GSE184944": {
43
- "is_usable": true,
44
- "is_gene_available": true,
45
- "is_trait_available": true,
46
- "is_available": true,
47
- "is_biased": false,
48
- "has_age": false,
49
- "has_gender": true,
50
- "sample_size": 49
51
- },
52
- "GSE156915": {
53
- "is_usable": false,
54
- "is_gene_available": false,
55
- "is_trait_available": false,
56
- "is_available": false,
57
- "is_biased": null,
58
- "has_age": null,
59
- "has_gender": null,
60
- "sample_size": null
61
- },
62
- "GSE151181": {
63
- "is_usable": false,
64
- "is_gene_available": false,
65
- "is_trait_available": false,
66
- "is_available": false,
67
- "is_biased": null,
68
- "has_age": null,
69
- "has_gender": null,
70
- "sample_size": null
71
- },
72
- "GSE151179": {
73
- "is_usable": true,
74
- "is_gene_available": true,
75
- "is_trait_available": true,
76
- "is_available": true,
77
- "is_biased": false,
78
- "has_age": false,
79
- "has_gender": false,
80
- "sample_size": 52
81
- },
82
- "GSE148320": {
83
- "is_usable": true,
84
- "is_gene_available": true,
85
- "is_trait_available": true,
86
- "is_available": true,
87
- "is_biased": false,
88
- "has_age": false,
89
- "has_gender": false,
90
- "sample_size": 57
91
- },
92
- "GSE104006": {
93
- "is_usable": true,
94
- "is_gene_available": true,
95
- "is_trait_available": true,
96
- "is_available": true,
97
- "is_biased": false,
98
- "has_age": true,
99
- "has_gender": true,
100
- "sample_size": 34
101
- },
102
- "TCGA": {
103
- "is_usable": true,
104
- "is_gene_available": true,
105
- "is_trait_available": true,
106
- "is_available": true,
107
- "is_biased": false,
108
- "has_age": true,
109
- "has_gender": true,
110
- "sample_size": 566
111
- }
112
- }
 
1
+ {"GSE244580": {"is_usable": false, "is_gene_available": false, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": "INFO: Mapping used RefSeq accessions (GB_ACC) from platform; gene-symbol normalization reduced features from 16346 to 0. This platform lacks explicit gene symbols, so normalization likely dropped many features."}, "GSE218109": {"is_usable": false, "is_gene_available": true, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": "WARNING: Trait not available for this cohort. All samples are ESCC tumors (constant tissue), so the specified trait cannot be constructed; clinical linking skipped. Saved normalized gene data only."}, "GSE212250": {"is_usable": false, "is_gene_available": false, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": null}, "GSE201777": {"is_usable": true, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": false, "has_age": false, "has_gender": false, "sample_size": 31, "note": "INFO: Trait derived from 'tissue' field (Tumor=1, Mucosa=0); lymph node samples were set to NaN and removed during filtering. No age/gender fields available in clinical annotations for this series."}, "GSE184944": {"is_usable": false, "is_gene_available": true, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": null}, "GSE156915": {"is_usable": false, "is_gene_available": true, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": null}, "GSE151179": {"is_usable": false, "is_gene_available": true, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": null}, "GSE148320": {"is_usable": false, "is_gene_available": true, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": null}, "TCGA_Head_and_Neck_Cancer": {"is_usable": true, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": false, "has_age": true, "has_gender": true, "sample_size": 566, "note": "INFO: Gene symbols normalized using NCBI synonym mapping; gene matrix restricted to HNSC samples; Trait derived from TCGA sample barcode (01-09 tumor = 1, 10-19 normal = 0)."}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Heart_rate/GSE35661.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Heart_rate/clinical_data/GSE18583.csv CHANGED
@@ -1,42 +1,2 @@
1
- Sample,Heart_rate,Gender
2
- GSM462215,173.0,1.0
3
- GSM462216,155.0,1.0
4
- GSM462217,183.0,1.0
5
- GSM462218,149.0,1.0
6
- GSM462219,146.0,1.0
7
- GSM462220,157.0,1.0
8
- GSM462221,162.0,1.0
9
- GSM462222,170.0,1.0
10
- GSM462223,165.0,1.0
11
- GSM462224,144.0,1.0
12
- GSM462225,167.0,1.0
13
- GSM462226,165.0,1.0
14
- GSM462227,191.0,1.0
15
- GSM462228,149.0,1.0
16
- GSM462229,160.0,1.0
17
- GSM462230,177.0,1.0
18
- GSM462231,174.0,1.0
19
- GSM462232,165.0,1.0
20
- GSM462233,173.0,1.0
21
- GSM462234,190.0,1.0
22
- GSM462235,190.0,1.0
23
- GSM462236,190.0,1.0
24
- GSM462237,169.0,1.0
25
- GSM462238,160.0,1.0
26
- GSM462239,,1.0
27
- GSM462240,,1.0
28
- GSM462241,,1.0
29
- GSM462242,,1.0
30
- GSM462243,,1.0
31
- GSM462244,,1.0
32
- GSM462245,,1.0
33
- GSM462246,,1.0
34
- GSM462247,,1.0
35
- GSM462248,,1.0
36
- GSM462249,,1.0
37
- GSM462250,,1.0
38
- GSM462251,,1.0
39
- GSM462252,,1.0
40
- GSM462253,,1.0
41
- GSM462254,,1.0
42
- GSM462255,,1.0
 
1
+ ,GSM462215,GSM462216,GSM462217,GSM462218,GSM462219,GSM462220,GSM462221,GSM462222,GSM462223,GSM462224,GSM462225,GSM462226,GSM462227,GSM462228,GSM462229,GSM462230,GSM462231,GSM462232,GSM462233,GSM462234,GSM462235,GSM462236,GSM462237,GSM462238,GSM462239,GSM462240,GSM462241,GSM462242,GSM462243,GSM462244,GSM462245,GSM462246,GSM462247,GSM462248,GSM462249,GSM462250,GSM462251,GSM462252,GSM462253,GSM462254,GSM462255
2
+ Heart_rate,173.0,155.0,183.0,149.0,146.0,157.0,162.0,170.0,165.0,144.0,167.0,165.0,191.0,149.0,160.0,177.0,174.0,165.0,173.0,190.0,190.0,190.0,169.0,160.0,,,,,,,,,,,,,,,,,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Heart_rate/clinical_data/GSE34788.csv CHANGED
@@ -1,121 +1,2 @@
1
- Sample,Heart_rate,Gender
2
- GSM855302,,
3
- GSM855303,,
4
- GSM855304,,
5
- GSM855305,,
6
- GSM855306,,
7
- GSM855307,,
8
- GSM855308,,
9
- GSM855309,,
10
- GSM855310,,
11
- GSM855311,,
12
- GSM855312,,
13
- GSM855313,,
14
- GSM855314,,
15
- GSM855315,,
16
- GSM855316,,
17
- GSM855317,,
18
- GSM855318,,
19
- GSM855319,,
20
- GSM855320,,
21
- GSM855321,,
22
- GSM855322,,
23
- GSM855323,,
24
- GSM855324,,
25
- GSM855325,,
26
- GSM855326,,
27
- GSM855327,,
28
- GSM855328,,
29
- GSM855329,,
30
- GSM855330,,
31
- GSM855331,,
32
- GSM855332,,
33
- GSM855333,,
34
- GSM855334,,
35
- GSM855335,,
36
- GSM855336,,
37
- GSM855337,,
38
- GSM855338,,
39
- GSM855339,,
40
- GSM855340,,
41
- GSM855341,,
42
- GSM855342,,
43
- GSM855343,,
44
- GSM855344,,
45
- GSM855345,,
46
- GSM855346,,
47
- GSM855347,,
48
- GSM855348,,
49
- GSM855349,,
50
- GSM855350,,
51
- GSM855351,,
52
- GSM855352,,
53
- GSM855353,,
54
- GSM855354,,
55
- GSM855355,,
56
- GSM855356,,
57
- GSM855357,,
58
- GSM855358,,
59
- GSM855359,,
60
- GSM855360,,
61
- GSM855361,,
62
- GSM855362,,
63
- GSM855363,,
64
- GSM855364,,
65
- GSM855365,,
66
- GSM855366,,
67
- GSM855367,,
68
- GSM855368,,
69
- GSM855369,,
70
- GSM855370,,
71
- GSM855371,,
72
- GSM855372,,
73
- GSM855373,,
74
- GSM855374,,
75
- GSM855375,,
76
- GSM855376,,
77
- GSM855377,,
78
- GSM855378,,
79
- GSM855379,,
80
- GSM855380,,
81
- GSM855381,,
82
- GSM855382,,
83
- GSM855383,,
84
- GSM855384,,
85
- GSM855385,,
86
- GSM855386,,
87
- GSM855387,,
88
- GSM855388,,
89
- GSM855389,,
90
- GSM855390,,
91
- GSM855391,,
92
- GSM855392,,
93
- GSM855393,,
94
- GSM855394,,
95
- GSM855395,,
96
- GSM855396,,
97
- GSM855397,,
98
- GSM855398,,
99
- GSM855399,,
100
- GSM855400,,
101
- GSM855401,,
102
- GSM855402,,
103
- GSM855403,,
104
- GSM855404,,
105
- GSM855405,,
106
- GSM855406,,
107
- GSM855407,,
108
- GSM855408,,
109
- GSM855409,,
110
- GSM855410,,
111
- GSM855411,,
112
- GSM855412,,
113
- GSM855413,,
114
- GSM855414,,
115
- GSM855415,,
116
- GSM855416,,
117
- GSM855417,,
118
- GSM855418,,
119
- GSM855419,,
120
- GSM855420,,
121
- GSM855421,,
 
1
+ ,GSM855302,GSM855303,GSM855304,GSM855305,GSM855306,GSM855307,GSM855308,GSM855309,GSM855310,GSM855311,GSM855312,GSM855313,GSM855314,GSM855315,GSM855316,GSM855317,GSM855318,GSM855319,GSM855320,GSM855321,GSM855322,GSM855323,GSM855324,GSM855325,GSM855326,GSM855327,GSM855328,GSM855329,GSM855330,GSM855331,GSM855332,GSM855333,GSM855334,GSM855335,GSM855336,GSM855337,GSM855338,GSM855339,GSM855340,GSM855341,GSM855342,GSM855343,GSM855344,GSM855345,GSM855346,GSM855347,GSM855348,GSM855349,GSM855350,GSM855351,GSM855352,GSM855353,GSM855354,GSM855355,GSM855356,GSM855357,GSM855358,GSM855359,GSM855360,GSM855361,GSM855362,GSM855363,GSM855364,GSM855365,GSM855366,GSM855367,GSM855368,GSM855369,GSM855370,GSM855371,GSM855372,GSM855373,GSM855374,GSM855375,GSM855376,GSM855377,GSM855378,GSM855379,GSM855380,GSM855381,GSM855382,GSM855383,GSM855384,GSM855385,GSM855386,GSM855387,GSM855388,GSM855389,GSM855390,GSM855391,GSM855392,GSM855393,GSM855394,GSM855395,GSM855396,GSM855397,GSM855398,GSM855399,GSM855400,GSM855401,GSM855402,GSM855403,GSM855404,GSM855405,GSM855406,GSM855407,GSM855408,GSM855409,GSM855410,GSM855411,GSM855412,GSM855413,GSM855414,GSM855415,GSM855416,GSM855417,GSM855418,GSM855419,GSM855420,GSM855421
2
+ Heart_rate,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Heart_rate/clinical_data/GSE35661.csv CHANGED
@@ -1,42 +1,2 @@
1
- Sample,Heart_rate,Gender
2
- GSM462215,173.0,1.0
3
- GSM462216,155.0,1.0
4
- GSM462217,183.0,1.0
5
- GSM462218,149.0,1.0
6
- GSM462219,146.0,1.0
7
- GSM462220,157.0,1.0
8
- GSM462221,162.0,1.0
9
- GSM462222,170.0,1.0
10
- GSM462223,165.0,1.0
11
- GSM462224,144.0,1.0
12
- GSM462225,167.0,1.0
13
- GSM462226,165.0,1.0
14
- GSM462227,191.0,1.0
15
- GSM462228,149.0,1.0
16
- GSM462229,160.0,1.0
17
- GSM462230,177.0,1.0
18
- GSM462231,174.0,1.0
19
- GSM462232,165.0,1.0
20
- GSM462233,173.0,1.0
21
- GSM462234,190.0,1.0
22
- GSM462235,190.0,1.0
23
- GSM462236,190.0,1.0
24
- GSM462237,169.0,1.0
25
- GSM462238,160.0,1.0
26
- GSM462239,,1.0
27
- GSM462240,,1.0
28
- GSM462241,,1.0
29
- GSM462242,,1.0
30
- GSM462243,,1.0
31
- GSM462244,,1.0
32
- GSM462245,,1.0
33
- GSM462246,,1.0
34
- GSM462247,,1.0
35
- GSM462248,,1.0
36
- GSM462249,,1.0
37
- GSM462250,,1.0
38
- GSM462251,,1.0
39
- GSM462252,,1.0
40
- GSM462253,,1.0
41
- GSM462254,,1.0
42
- GSM462255,,1.0
 
1
+ ,GSM462215,GSM462216,GSM462217,GSM462218,GSM462219,GSM462220,GSM462221,GSM462222,GSM462223,GSM462224,GSM462225,GSM462226,GSM462227,GSM462228,GSM462229,GSM462230,GSM462231,GSM462232,GSM462233,GSM462234,GSM462235,GSM462236,GSM462237,GSM462238,GSM462239,GSM462240,GSM462241,GSM462242,GSM462243,GSM462244,GSM462245,GSM462246,GSM462247,GSM462248,GSM462249,GSM462250,GSM462251,GSM462252,GSM462253,GSM462254,GSM462255
2
+ Heart_rate,173.0,155.0,183.0,149.0,146.0,157.0,162.0,170.0,165.0,144.0,167.0,165.0,191.0,149.0,160.0,177.0,174.0,165.0,173.0,190.0,190.0,190.0,169.0,160.0,,,,,,,,,,,,,,,,,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Heart_rate/code/GSE117070.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Heart_rate"
6
+ cohort = "GSE117070"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Heart_rate"
10
+ in_cohort_dir = "../DATA/GEO/Heart_rate/GSE117070"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Heart_rate/GSE117070.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Heart_rate/gene_data/GSE117070.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Heart_rate/clinical_data/GSE117070.csv"
16
+ json_path = "./output/z3/preprocess/Heart_rate/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Step 1: Determine data availability
40
+ is_gene_available = True # Affymetrix gene expression microarrays indicate gene expression data is available
41
+ trait_row = None # Heart_rate not available in provided sample characteristics
42
+ age_row = None # No age information available
43
+ gender_row = None # No gender information available
44
+
45
+ # Step 2: Define conversion functions
46
+ def _extract_after_colon(x):
47
+ if x is None:
48
+ return None
49
+ try:
50
+ s = str(x)
51
+ except Exception:
52
+ return None
53
+ parts = s.split(":", 1)
54
+ val = parts[1] if len(parts) > 1 else parts[0]
55
+ val = val.strip().strip('"').strip()
56
+ return val if val != "" else None
57
+
58
+ def convert_trait(x):
59
+ # Heart rate is continuous (e.g., bpm). Return float if present, else None.
60
+ val = _extract_after_colon(x)
61
+ if val is None:
62
+ return None
63
+ # Heuristic parsing: extract first numeric (could include decimal)
64
+ import re
65
+ m = re.search(r"(-?\d+(\.\d+)?)", val)
66
+ if m:
67
+ try:
68
+ return float(m.group(1))
69
+ except Exception:
70
+ return None
71
+ return None
72
+
73
+ def convert_age(x):
74
+ # Age is continuous; return years as float if present.
75
+ val = _extract_after_colon(x)
76
+ if val is None:
77
+ return None
78
+ import re
79
+ m = re.search(r"(\d+(\.\d+)?)", val)
80
+ if m:
81
+ try:
82
+ return float(m.group(1))
83
+ except Exception:
84
+ return None
85
+ return None
86
+
87
+ def convert_gender(x):
88
+ # Binary: female -> 0, male -> 1
89
+ val = _extract_after_colon(x)
90
+ if val is None:
91
+ return None
92
+ v = val.lower()
93
+ if v in {"male", "m"}:
94
+ return 1
95
+ if v in {"female", "f"}:
96
+ return 0
97
+ # Handle common alternatives
98
+ if "male" in v:
99
+ return 1
100
+ if "female" in v:
101
+ return 0
102
+ return None
103
+
104
+ # Step 3: Initial filtering and save metadata
105
+ is_trait_available = trait_row is not None
106
+ _ = validate_and_save_cohort_info(
107
+ is_final=False,
108
+ cohort=cohort,
109
+ info_path=json_path,
110
+ is_gene_available=is_gene_available,
111
+ is_trait_available=is_trait_available
112
+ )
113
+
114
+ # Step 4: Clinical feature extraction (skip because trait_row is None)
115
+ if trait_row is not None:
116
+ selected_clinical_df = geo_select_clinical_features(
117
+ clinical_df=clinical_data,
118
+ trait=trait,
119
+ trait_row=trait_row,
120
+ convert_trait=convert_trait,
121
+ age_row=age_row,
122
+ convert_age=convert_age,
123
+ gender_row=gender_row,
124
+ convert_gender=convert_gender
125
+ )
126
+ preview = preview_df(selected_clinical_df, n=5)
127
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
128
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
129
+
130
+ # Step 3: Gene Data Extraction
131
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
132
+ gene_data = get_genetic_data(matrix_file)
133
+
134
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
135
+ print(gene_data.index[:20])
136
+
137
+ # Step 4: Gene Identifier Review
138
+ requires_gene_mapping = True
139
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
140
+
141
+ # Step 5: Gene Annotation
142
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
143
+ gene_annotation = get_gene_annotation(soft_file)
144
+
145
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
146
+ print("Gene annotation preview:")
147
+ print(preview_df(gene_annotation))
148
+
149
+ # Step 6: Gene Identifier Mapping
150
+ # Select appropriate columns based on observations:
151
+ # - Probe identifiers in expression data match 'ID' in gene_annotation (e.g., '1007_s_at')
152
+ # - Gene symbols are stored in 'Gene Symbol'
153
+ id_col = 'ID'
154
+ gene_symbol_col = 'Gene Symbol'
155
+
156
+ # 2. Extract mapping dataframe
157
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=id_col, gene_col=gene_symbol_col)
158
+
159
+ # 3. Apply mapping to convert probe-level data to gene-level data
160
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
161
+
162
+ # Step 7: Data Normalization and Linking
163
+ import os
164
+ import pandas as pd
165
+
166
+ # 1. Normalize gene symbols and save normalized gene data
167
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
168
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
169
+ normalized_gene_data.to_csv(out_gene_data_file)
170
+
171
+ # 2-6. Proceed only if clinical data with the target trait exists; otherwise, record unavailability
172
+ has_selected = ('selected_clinical_data' in globals()) and isinstance(globals()['selected_clinical_data'], pd.DataFrame)
173
+ trait_present = has_selected and (trait in globals()['selected_clinical_data'].index)
174
+
175
+ if has_selected and trait_present:
176
+ # 2. Link clinical and genetic data
177
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
178
+
179
+ # 3. Handle missing values with the specified strategy
180
+ linked_data = handle_missing_values(linked_data, trait)
181
+
182
+ # 4. Determine bias and remove biased demographic features
183
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
184
+
185
+ # 5. Final validation and save cohort info
186
+ is_usable = validate_and_save_cohort_info(
187
+ is_final=True,
188
+ cohort=cohort,
189
+ info_path=json_path,
190
+ is_gene_available=True,
191
+ is_trait_available=True,
192
+ is_biased=is_trait_biased,
193
+ df=unbiased_linked_data,
194
+ note="INFO: Clinical features extracted and linked with gene expression."
195
+ )
196
+
197
+ # 6. Save linked data only if usable
198
+ if is_usable:
199
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
200
+ unbiased_linked_data.to_csv(out_data_file)
201
+ else:
202
+ # Trait is unavailable; perform final validation accordingly and do not save linked data
203
+ _ = validate_and_save_cohort_info(
204
+ is_final=True,
205
+ cohort=cohort,
206
+ info_path=json_path,
207
+ is_gene_available=True,
208
+ is_trait_available=False,
209
+ is_biased=False,
210
+ df=normalized_gene_data.T,
211
+ note="INFO: Trait 'Heart_rate' unavailable in clinical annotations; only 'status: pre/post-training' present. Skipping linking."
212
+ )
output/preprocess/Heart_rate/code/GSE12385.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Heart_rate"
6
+ cohort = "GSE12385"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Heart_rate"
10
+ in_cohort_dir = "../DATA/GEO/Heart_rate/GSE12385"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Heart_rate/GSE12385.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Heart_rate/gene_data/GSE12385.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Heart_rate/clinical_data/GSE12385.csv"
16
+ json_path = "./output/z3/preprocess/Heart_rate/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Step 1: Determine data availability based on provided background and characteristics
40
+ is_gene_available = True # Agilent Whole Human Genome Oligo Microarrays -> mRNA expression data
41
+ # Trait is Heart_rate; no such field in characteristics -> not available
42
+ trait_row = None
43
+ age_row = 1 # Age (years)
44
+ # Gender is constant "Male" across the cohort -> not useful (constant feature)
45
+ gender_row = None
46
+
47
+ # Step 2: Define conversion functions
48
+ import re
49
+ from typing import Optional
50
+
51
+ def _extract_value(text: str) -> str:
52
+ if text is None:
53
+ return ""
54
+ # Typical GEO format "Label: value"
55
+ parts = str(text).split(":", 1)
56
+ return parts[1].strip() if len(parts) > 1 else str(text).strip()
57
+
58
+ def convert_trait(x) -> Optional[float]:
59
+ # Generic heart rate parser; kept for completeness though trait not available in this cohort
60
+ val = _extract_value(x)
61
+ if not val:
62
+ return None
63
+ # Extract first float-like number
64
+ m = re.search(r"[-+]?\d*\.?\d+", val)
65
+ if m:
66
+ try:
67
+ return float(m.group(0))
68
+ except:
69
+ return None
70
+ # Map common textual statuses if ever encountered (unlikely here)
71
+ low_map = {"resting": None, "na": None, "n/a": None, "unknown": None}
72
+ v = val.lower()
73
+ if v in low_map:
74
+ return low_map[v]
75
+ return None
76
+
77
+ def convert_age(x) -> Optional[float]:
78
+ val = _extract_value(x)
79
+ if not val:
80
+ return None
81
+ m = re.search(r"[-+]?\d*\.?\d+", val)
82
+ if m:
83
+ try:
84
+ return float(m.group(0))
85
+ except:
86
+ return None
87
+ return None
88
+
89
+ def convert_gender(x) -> Optional[int]:
90
+ val = _extract_value(x).strip().lower()
91
+ if not val:
92
+ return None
93
+ # Normalize
94
+ if val in {"m", "male"}:
95
+ return 1
96
+ if val in {"f", "female"}:
97
+ return 0
98
+ if val in {"man"}:
99
+ return 1
100
+ if val in {"woman"}:
101
+ return 0
102
+ if val in {"unknown", "na", "n/a", "other"}:
103
+ return None
104
+ # Try to catch forms like "sex=male"
105
+ if "male" in val:
106
+ return 1
107
+ if "female" in val:
108
+ return 0
109
+ return None
110
+
111
+ # Step 3: Initial filtering and save metadata
112
+ is_trait_available = trait_row is not None
113
+ _ = validate_and_save_cohort_info(
114
+ is_final=False,
115
+ cohort=cohort,
116
+ info_path=json_path,
117
+ is_gene_available=is_gene_available,
118
+ is_trait_available=is_trait_available
119
+ )
120
+
121
+ # Step 4: Clinical feature extraction (skip because trait_row is None)
122
+ # If in other cohorts trait_row is available, uncomment and use:
123
+ # if trait_row is not None:
124
+ # selected_clinical_df = geo_select_clinical_features(
125
+ # clinical_df=clinical_data,
126
+ # trait=trait,
127
+ # trait_row=trait_row,
128
+ # convert_trait=convert_trait,
129
+ # age_row=age_row,
130
+ # convert_age=convert_age,
131
+ # gender_row=gender_row,
132
+ # convert_gender=convert_gender
133
+ # )
134
+ # preview = preview_df(selected_clinical_df)
135
+ # os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
136
+ # selected_clinical_df.to_csv(out_clinical_data_file)
137
+
138
+ # Step 3: Gene Data Extraction
139
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
140
+ gene_data = get_genetic_data(matrix_file)
141
+
142
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
143
+ print(gene_data.index[:20])
144
+
145
+ # Step 4: Gene Identifier Review
146
+ print("requires_gene_mapping = True")
147
+
148
+ # Step 5: Gene Annotation
149
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
150
+ gene_annotation = get_gene_annotation(soft_file)
151
+
152
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
153
+ print("Gene annotation preview:")
154
+ print(preview_df(gene_annotation))
155
+
156
+ # Step 6: Gene Identifier Mapping
157
+ # Decide the appropriate columns for mapping
158
+ probe_col = 'ID' # Matches gene_data index
159
+ symbol_col = 'GENE_SYMBOL' if 'GENE_SYMBOL' in gene_annotation.columns else 'GENE'
160
+
161
+ # Build mapping dataframe
162
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=symbol_col)
163
+
164
+ # Apply mapping to convert probe-level data to gene-level data
165
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
166
+
167
+ # Step 7: Data Normalization and Linking
168
+ import os
169
+
170
+ # 1. Normalize the obtained gene data and save
171
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
172
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
173
+ normalized_gene_data.to_csv(out_gene_data_file)
174
+
175
+ # 2-6. Proceed only if clinical data with the trait is available; otherwise skip linking and record metadata
176
+ has_selected = 'selected_clinical_data' in globals() and selected_clinical_data is not None
177
+ trait_available = (trait_row is not None) and has_selected and (trait in getattr(selected_clinical_data, 'index', []))
178
+
179
+ if trait_available:
180
+ # 2. Link the clinical and genetic data
181
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
182
+
183
+ # 3. Handle missing values in the linked data
184
+ linked_data = handle_missing_values(linked_data, trait)
185
+
186
+ # 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.
187
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
188
+
189
+ # 5. Conduct quality check and save the cohort information.
190
+ is_usable = validate_and_save_cohort_info(
191
+ is_final=True,
192
+ cohort=cohort,
193
+ info_path=json_path,
194
+ is_gene_available=True,
195
+ is_trait_available=True,
196
+ is_biased=is_trait_biased,
197
+ df=unbiased_linked_data,
198
+ note="INFO: Linked data generated and evaluated."
199
+ )
200
+
201
+ # 6. If the linked data is usable, save it
202
+ if is_usable:
203
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
204
+ unbiased_linked_data.to_csv(out_data_file)
205
+ else:
206
+ # Trait not available: record metadata as not usable for linking stage
207
+ validate_and_save_cohort_info(
208
+ is_final=False,
209
+ cohort=cohort,
210
+ info_path=json_path,
211
+ is_gene_available=True,
212
+ is_trait_available=False
213
+ )
output/preprocess/Heart_rate/code/GSE18583.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Heart_rate"
6
+ cohort = "GSE18583"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Heart_rate"
10
+ in_cohort_dir = "../DATA/GEO/Heart_rate/GSE18583"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Heart_rate/GSE18583.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Heart_rate/gene_data/GSE18583.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Heart_rate/clinical_data/GSE18583.csv"
16
+ json_path = "./output/z3/preprocess/Heart_rate/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+
42
+ # 1) Gene expression availability
43
+ is_gene_available = True # Series title indicates baseline skeletal muscle gene expression (mRNA microarray)
44
+
45
+ # 2) Variable availability
46
+ # Trait: Heart_rate -> 'heart rate (bpm)' at key 2
47
+ trait_row = 2
48
+
49
+ # Age: not available in the sample characteristics
50
+ age_row = None
51
+
52
+ # Gender: key 0 exists but all subjects are male (constant -> not useful)
53
+ gender_row = None
54
+
55
+ # 2.2) Converters
56
+ _num_pattern = re.compile(r'[-+]?\d*\.?\d+')
57
+
58
+ def _value_after_colon(x):
59
+ if x is None:
60
+ return None
61
+ parts = str(x).split(':', 1)
62
+ return parts[1].strip() if len(parts) == 2 else str(x).strip()
63
+
64
+ def convert_trait(x):
65
+ v = _value_after_colon(x)
66
+ if v is None:
67
+ return None
68
+ m = _num_pattern.search(v)
69
+ if not m:
70
+ return None
71
+ try:
72
+ return float(m.group())
73
+ except Exception:
74
+ return None
75
+
76
+ def convert_age(x):
77
+ v = _value_after_colon(x)
78
+ if v is None:
79
+ return None
80
+ m = _num_pattern.search(v)
81
+ if not m:
82
+ return None
83
+ try:
84
+ age = float(m.group())
85
+ if 0 < age < 120:
86
+ return age
87
+ return None
88
+ except Exception:
89
+ return None
90
+
91
+ def convert_gender(x):
92
+ v = _value_after_colon(x)
93
+ if v is None:
94
+ return None
95
+ v = v.strip().lower()
96
+ if v in {'male', 'm', 'man', 'boy'}:
97
+ return 1
98
+ if v in {'female', 'f', 'woman', 'girl'}:
99
+ return 0
100
+ return None
101
+
102
+ # 3) Save metadata (initial filtering)
103
+ is_trait_available = trait_row is not None
104
+ _ = validate_and_save_cohort_info(
105
+ is_final=False,
106
+ cohort=cohort,
107
+ info_path=json_path,
108
+ is_gene_available=is_gene_available,
109
+ is_trait_available=is_trait_available
110
+ )
111
+
112
+ # 4) Clinical feature extraction (only if trait available)
113
+ if trait_row is not None:
114
+ selected_clinical_df = geo_select_clinical_features(
115
+ clinical_df=clinical_data,
116
+ trait=trait,
117
+ trait_row=trait_row,
118
+ convert_trait=convert_trait,
119
+ age_row=age_row,
120
+ convert_age=None,
121
+ gender_row=gender_row,
122
+ convert_gender=None
123
+ )
124
+ preview = preview_df(selected_clinical_df)
125
+ print(preview)
126
+
127
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
128
+ selected_clinical_df.to_csv(out_clinical_data_file)
129
+
130
+ # Step 3: Gene Data Extraction
131
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
132
+ gene_data = get_genetic_data(matrix_file)
133
+
134
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
135
+ print(gene_data.index[:20])
136
+
137
+ # Step 4: Gene Identifier Review
138
+ print("requires_gene_mapping = True")
139
+
140
+ # Step 5: Gene Annotation
141
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
142
+ gene_annotation = get_gene_annotation(soft_file)
143
+
144
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
145
+ print("Gene annotation preview:")
146
+ print(preview_df(gene_annotation))
147
+
148
+ # Step 6: Gene Identifier Mapping
149
+ import re
150
+ import pandas as pd
151
+
152
+ # 1) Decide identifier and gene symbol columns
153
+ # From preview, 'ID' matches expression IDs (e.g., ENST..._at) and 'SPOT_ID' contains corresponding ENST IDs without suffix.
154
+ id_col = 'ID'
155
+ gene_col = 'SPOT_ID'
156
+
157
+ # 2) Build mapping dataframe
158
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=id_col, gene_col=gene_col)
159
+
160
+ # 3) Apply mapping to convert probe-level to gene-level (here, gene identifiers are ENST IDs; no true symbols available)
161
+ # Implement mapping without extracting human symbols to avoid dropping ENST IDs.
162
+ # Handle potential one-to-many mappings by equally splitting probe expression among mapped targets.
163
+ mapping_df = mapping_df[mapping_df['ID'].isin(gene_data.index)].copy()
164
+
165
+ # Split potential multi-target annotations; here typically single ENST per probe but keep generic handling
166
+ def _split_genes(s: str):
167
+ if pd.isna(s):
168
+ return []
169
+ parts = [p.strip() for p in re.split(r'\s*[;/,|]\s*', str(s)) if p and p.strip()]
170
+ return parts if parts else [str(s).strip()]
171
+
172
+ mapping_df['Gene_list'] = mapping_df['Gene'].apply(_split_genes)
173
+ mapping_df['num_genes'] = mapping_df['Gene_list'].apply(len)
174
+
175
+ mapping_expanded = mapping_df[['ID', 'Gene_list', 'num_genes']].explode('Gene_list').rename(columns={'Gene_list': 'Gene'})
176
+ mapping_expanded = mapping_expanded.dropna(subset=['Gene']).set_index('ID')
177
+
178
+ merged = mapping_expanded.join(gene_data, how='inner')
179
+ expr_cols = [c for c in merged.columns if c not in ['Gene', 'num_genes']]
180
+
181
+ # Distribute expression equally among mapped genes for each probe
182
+ merged[expr_cols] = merged[expr_cols].div(merged['num_genes'].replace(0, 1), axis=0)
183
+
184
+ # Sum contributions per gene
185
+ gene_data = merged.groupby('Gene')[expr_cols].sum()
186
+
187
+ # Step 7: Data Normalization and Linking
188
+ import os
189
+ import pandas as pd
190
+
191
+ # 1) Normalize gene symbols; fall back to transcript-level data if normalization drops all rows
192
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
193
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data.copy())
194
+ if normalized_gene_data.shape[0] == 0:
195
+ used_gene_data = gene_data.copy()
196
+ note = ("WARNING: Platform uses transcript identifiers (e.g., ENST); gene symbol normalization "
197
+ "dropped all features. Proceeding with transcript-level data without normalization.")
198
+ else:
199
+ used_gene_data = normalized_gene_data
200
+ note = "INFO: Gene symbols normalized using NCBI synonym mapping."
201
+
202
+ # Save the best available gene matrix
203
+ used_gene_data.to_csv(out_gene_data_file)
204
+
205
+ # 2) Load clinical data and link
206
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
207
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, used_gene_data)
208
+
209
+ # 3) Handle missing values
210
+ linked_data = handle_missing_values(linked_data, trait)
211
+
212
+ # 4) Evaluate bias and remove biased demographic features
213
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
214
+
215
+ # Ensure booleans are Python bool for JSON serialization
216
+ is_trait_biased = bool(is_trait_biased)
217
+ is_gene_available_final = bool(used_gene_data.shape[0] > 0)
218
+ is_trait_available_final = bool((trait in selected_clinical_df.index) and bool(selected_clinical_df.loc[trait].notna().any()))
219
+
220
+ # 5) Final validation and save cohort info
221
+ is_usable = validate_and_save_cohort_info(
222
+ is_final=True,
223
+ cohort=cohort,
224
+ info_path=json_path,
225
+ is_gene_available=is_gene_available_final,
226
+ is_trait_available=is_trait_available_final,
227
+ is_biased=is_trait_biased,
228
+ df=unbiased_linked_data,
229
+ note=note
230
+ )
231
+
232
+ # 6) Save linked data only if usable
233
+ if is_usable:
234
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
235
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Heart_rate/code/GSE236927.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Heart_rate"
6
+ cohort = "GSE236927"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Heart_rate"
10
+ in_cohort_dir = "../DATA/GEO/Heart_rate/GSE236927"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Heart_rate/GSE236927.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Heart_rate/gene_data/GSE236927.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Heart_rate/clinical_data/GSE236927.csv"
16
+ json_path = "./output/z3/preprocess/Heart_rate/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+ import pandas as pd
41
+
42
+ # 1) Gene expression data availability
43
+ is_gene_available = True # PBMC microarray transcriptomics -> gene expression data available
44
+
45
+ # 2) Variable availability and converters
46
+ # Trait: Heart_rate
47
+ # Not found in provided sample characteristics dictionary; background mentions HR collected but not in GEO characteristics
48
+ trait_row = None
49
+
50
+ def convert_trait(x):
51
+ if x is None:
52
+ return None
53
+ s = str(x).strip().lower()
54
+ # Try to extract after colon if present
55
+ if ':' in s:
56
+ s_val = s.split(':', 1)[1].strip()
57
+ else:
58
+ s_val = s
59
+ # Heuristics for heart rate (beats per minute)
60
+ # Known patterns might include "heart rate", "pulse", etc., but since trait_row is None, this is a fallback parser.
61
+ # Accept pure numbers or numbers followed by bpm
62
+ s_val = re.sub(r'\(.*?\)', '', s_val).strip() # remove parentheses content
63
+ s_val = s_val.replace('bpm', '').strip()
64
+ try:
65
+ val = float(s_val)
66
+ # Basic sanity check for human resting HR range
67
+ if 20 <= val <= 220:
68
+ return val
69
+ return None
70
+ except:
71
+ return None
72
+
73
+ # Age: appears under keys 1 and 2; key 2 contains the bulk of ages (though mixed with BMI). We'll use key 2.
74
+ age_row = 2
75
+
76
+ def convert_age(x):
77
+ if x is None:
78
+ return None
79
+ s = str(x).strip().lower()
80
+ # Extract the part after colon if exists
81
+ if ':' in s:
82
+ header, value = s.split(':', 1)
83
+ header = header.strip()
84
+ value = value.strip()
85
+ # Only parse if it's age-like
86
+ if 'age' not in header:
87
+ return None
88
+ s_val = value
89
+ else:
90
+ # No header; try to parse as a number directly (rare)
91
+ s_val = s
92
+ # Clean and parse number
93
+ s_val = re.sub(r'[^\d\.]+', ' ', s_val).strip()
94
+ # Handle cases like "79" or "79.0"
95
+ try:
96
+ val = float(s_val)
97
+ if 0 < val < 120:
98
+ return val
99
+ return None
100
+ except:
101
+ return None
102
+
103
+ # Gender: females only (constant) per background and sample dictionary => not useful
104
+ gender_row = None
105
+
106
+ def convert_gender(x):
107
+ if x is None:
108
+ return None
109
+ s = str(x).strip().lower()
110
+ # Extract after colon if present
111
+ if ':' in s:
112
+ s_val = s.split(':', 1)[1].strip()
113
+ else:
114
+ s_val = s
115
+ # Normalize
116
+ if s_val in ['female', 'f', '0']:
117
+ return 0
118
+ if s_val in ['male', 'm', '1']:
119
+ return 1
120
+ # Sometimes formats like "sex (female/male): Female"
121
+ if 'female' in s_val and 'male' not in s_val:
122
+ return 0
123
+ if 'male' in s_val and 'female' not in s_val:
124
+ return 1
125
+ return None
126
+
127
+ # 3) Save metadata (initial filtering)
128
+ is_trait_available = trait_row is not None
129
+ _ = validate_and_save_cohort_info(
130
+ is_final=False,
131
+ cohort=cohort,
132
+ info_path=json_path,
133
+ is_gene_available=is_gene_available,
134
+ is_trait_available=is_trait_available
135
+ )
136
+
137
+ # 4) Clinical Feature Extraction (skip if trait not available)
138
+ if trait_row is not None:
139
+ selected_clinical_df = geo_select_clinical_features(
140
+ clinical_df=clinical_data,
141
+ trait=trait,
142
+ trait_row=trait_row,
143
+ convert_trait=convert_trait,
144
+ age_row=age_row,
145
+ convert_age=convert_age,
146
+ gender_row=gender_row,
147
+ convert_gender=convert_gender
148
+ )
149
+ _ = preview_df(selected_clinical_df)
150
+ # Save clinical features
151
+ out_dir = os.path.dirname(out_clinical_data_file)
152
+ os.makedirs(out_dir, exist_ok=True)
153
+ selected_clinical_df.to_csv(out_clinical_data_file)
154
+
155
+ # Step 3: Gene Data Extraction
156
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
157
+ gene_data = get_genetic_data(matrix_file)
158
+
159
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
160
+ print(gene_data.index[:20])
161
+
162
+ # Step 4: Gene Identifier Review
163
+ print("requires_gene_mapping = True")
164
+
165
+ # Step 5: Gene Annotation
166
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
167
+ gene_annotation = get_gene_annotation(soft_file)
168
+
169
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
170
+ print("Gene annotation preview:")
171
+ print(preview_df(gene_annotation))
172
+
173
+ # Step 6: Gene Identifier Mapping
174
+ # Map probe IDs to gene symbols and aggregate to gene-level expression
175
+
176
+ # Identify columns: probe IDs match 'ID' (e.g., ILMN_1651228) and gene symbols in 'Symbol'
177
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')
178
+
179
+ # Preserve original probe-level data, then apply mapping to get gene-level data
180
+ probe_level_data = gene_data
181
+ gene_data = apply_gene_mapping(probe_level_data, mapping_df)
182
+
183
+ # Step 7: Data Normalization and Linking
184
+ import os
185
+
186
+ # Normalize gene symbols and save normalized gene data
187
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
188
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
189
+ normalized_gene_data.to_csv(out_gene_data_file)
190
+
191
+ # Trait not available -> skip linking and final validation; record initial metadata only
192
+ _ = validate_and_save_cohort_info(
193
+ is_final=False,
194
+ cohort=cohort,
195
+ info_path=json_path,
196
+ is_gene_available=True,
197
+ is_trait_available=False
198
+ )
output/preprocess/Heart_rate/code/GSE34788.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Heart_rate"
6
+ cohort = "GSE34788"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Heart_rate"
10
+ in_cohort_dir = "../DATA/GEO/Heart_rate/GSE34788"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Heart_rate/GSE34788.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Heart_rate/gene_data/GSE34788.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Heart_rate/clinical_data/GSE34788.csv"
16
+ json_path = "./output/z3/preprocess/Heart_rate/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+
42
+ # 1) Gene expression data availability
43
+ is_gene_available = True # mRNA microarray per background info
44
+
45
+ # 2) Variable availability and converters
46
+
47
+ # Sample Characteristics Dictionary indicates:
48
+ # 6: ['heart rate: Low responders', 'heart rate: High responders']
49
+ trait_row = 6 # heart rate responder status available and varying
50
+ age_row = None # no age field present
51
+ gender_row = None # only 'gender: female' -> constant, thus not available
52
+
53
+ # Converters
54
+ def _after_colon(value: str) -> str:
55
+ if value is None:
56
+ return ""
57
+ parts = str(value).split(":", 1)
58
+ val = parts[1] if len(parts) > 1 else parts[0]
59
+ return val.strip()
60
+
61
+ def convert_trait(x):
62
+ val = _after_colon(x).strip().lower()
63
+ if not val:
64
+ return None
65
+ # Map any "high" to 1, any "low" to 0
66
+ if "high" in val:
67
+ return 1
68
+ if "low" in val:
69
+ return 0
70
+ return None
71
+
72
+ def convert_age(x):
73
+ # Not used because age_row is None, but keep robust parser
74
+ val = _after_colon(x)
75
+ # Extract first number (int/float)
76
+ m = re.search(r"[-+]?\d*\.?\d+", val)
77
+ if m:
78
+ try:
79
+ return float(m.group())
80
+ except Exception:
81
+ return None
82
+ return None
83
+
84
+ def convert_gender(x):
85
+ # Not used because gender_row is None
86
+ val = _after_colon(x).strip().lower()
87
+ if val in {"female", "f", "woman", "women"}:
88
+ return 0
89
+ if val in {"male", "m", "man", "men"}:
90
+ return 1
91
+ return None
92
+
93
+ # 3) Save metadata (initial filtering)
94
+ is_trait_available = trait_row is not None
95
+ _ = validate_and_save_cohort_info(
96
+ is_final=False,
97
+ cohort=cohort,
98
+ info_path=json_path,
99
+ is_gene_available=is_gene_available,
100
+ is_trait_available=is_trait_available
101
+ )
102
+
103
+ # 4) Clinical feature extraction (only if trait available)
104
+ if trait_row is not None:
105
+ selected_clinical_df = geo_select_clinical_features(
106
+ clinical_df=clinical_data,
107
+ trait=trait,
108
+ trait_row=trait_row,
109
+ convert_trait=convert_trait,
110
+ age_row=age_row,
111
+ convert_age=convert_age,
112
+ gender_row=gender_row,
113
+ convert_gender=convert_gender
114
+ )
115
+ preview = preview_df(selected_clinical_df, n=5)
116
+ print(preview)
117
+
118
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
119
+ selected_clinical_df.to_csv(out_clinical_data_file)
120
+
121
+ # Step 3: Gene Data Extraction
122
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
123
+ gene_data = get_genetic_data(matrix_file)
124
+
125
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
126
+ print(gene_data.index[:20])
127
+
128
+ # Step 4: Gene Identifier Review
129
+ print("requires_gene_mapping = True")
130
+
131
+ # Step 5: Gene Annotation
132
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
133
+ gene_annotation = get_gene_annotation(soft_file)
134
+
135
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
136
+ print("Gene annotation preview:")
137
+ print(preview_df(gene_annotation))
138
+
139
+ # Step 6: Gene Identifier Mapping
140
+ # Determine mapping columns based on previews:
141
+ # - Probe/feature identifiers match the 'ID' column (e.g., '7892501' style).
142
+ # - Gene symbols are embedded in 'gene_assignment' text; extract_human_gene_symbols handles parsing.
143
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='gene_assignment')
144
+
145
+ # Apply mapping to convert probe-level data to gene-level expression
146
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
147
+
148
+ # Step 7: Data Normalization and Linking
149
+ import os
150
+
151
+ # 1. Normalize gene symbols and save gene data
152
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
153
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
154
+ normalized_gene_data.to_csv(out_gene_data_file)
155
+
156
+ # 2. Link clinical and genetic data
157
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
158
+
159
+ # 3. Handle missing values
160
+ linked_data = handle_missing_values(linked_data, trait)
161
+
162
+ # 4. Bias evaluation and removal of biased covariates
163
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
164
+
165
+ # 5. Final validation and save cohort info
166
+ note = "INFO: Only trait available; Age/Gender not provided in clinical annotations."
167
+ is_usable = validate_and_save_cohort_info(
168
+ is_final=True,
169
+ cohort=cohort,
170
+ info_path=json_path,
171
+ is_gene_available=True,
172
+ is_trait_available=True,
173
+ is_biased=is_trait_biased,
174
+ df=unbiased_linked_data,
175
+ note=note
176
+ )
177
+
178
+ # 6. Save linked data if usable
179
+ if is_usable:
180
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
181
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Heart_rate/code/GSE35661.py ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Heart_rate"
6
+ cohort = "GSE35661"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Heart_rate"
10
+ in_cohort_dir = "../DATA/GEO/Heart_rate/GSE35661"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Heart_rate/GSE35661.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Heart_rate/gene_data/GSE35661.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Heart_rate/clinical_data/GSE35661.csv"
16
+ json_path = "./output/z3/preprocess/Heart_rate/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+ import pandas as pd
42
+
43
+ # 1. Gene Expression Data Availability
44
+ is_gene_available = True # Affymetrix U133+2 arrays indicate mRNA expression data
45
+
46
+ # 2. Variable Availability and Data Type Conversion
47
+
48
+ # 2.1 Identify rows for variables
49
+ trait_row = 2 # 'heart rate (bpm)'
50
+ age_row = None # No age information available
51
+ gender_row = None # Only 'male' present (constant), thus not useful
52
+
53
+ # 2.2 Converters
54
+ def _extract_after_colon(value: str) -> str:
55
+ if value is None or (isinstance(value, float) and pd.isna(value)):
56
+ return ""
57
+ s = str(value)
58
+ return s.split(":", 1)[1].strip() if ":" in s else s.strip()
59
+
60
+ def _to_float_from_text(txt: str):
61
+ if not txt:
62
+ return None
63
+ m = re.search(r"[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?", txt)
64
+ if not m:
65
+ return None
66
+ try:
67
+ return float(m.group(0))
68
+ except Exception:
69
+ return None
70
+
71
+ def convert_trait(x):
72
+ # Expected format like 'heart rate (bpm): 165'
73
+ txt = _extract_after_colon(x)
74
+ return _to_float_from_text(txt)
75
+
76
+ def convert_age(x):
77
+ # Not used (age_row is None), provided for API completeness
78
+ txt = _extract_after_colon(x)
79
+ return _to_float_from_text(txt)
80
+
81
+ def convert_gender(x):
82
+ # Not used (gender_row is None), provided for API completeness
83
+ txt = _extract_after_colon(x).lower()
84
+ if txt in {"male", "m"}:
85
+ return 1
86
+ if txt in {"female", "f"}:
87
+ return 0
88
+ return None
89
+
90
+ # 3. Save Metadata (initial filtering)
91
+ is_trait_available = trait_row is not None
92
+ _ = validate_and_save_cohort_info(
93
+ is_final=False,
94
+ cohort=cohort,
95
+ info_path=json_path,
96
+ is_gene_available=is_gene_available,
97
+ is_trait_available=is_trait_available
98
+ )
99
+
100
+ # 4. Clinical Feature Extraction
101
+ if is_trait_available:
102
+ selected_clinical_df = geo_select_clinical_features(
103
+ clinical_df=clinical_data,
104
+ trait=trait,
105
+ trait_row=trait_row,
106
+ convert_trait=convert_trait,
107
+ age_row=age_row,
108
+ convert_age=None,
109
+ gender_row=gender_row,
110
+ convert_gender=None
111
+ )
112
+ clinical_preview = preview_df(selected_clinical_df, n=5)
113
+
114
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
115
+ selected_clinical_df.to_csv(out_clinical_data_file)
116
+
117
+ # Step 3: Gene Data Extraction
118
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
119
+ gene_data = get_genetic_data(matrix_file)
120
+
121
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
122
+ print(gene_data.index[:20])
123
+
124
+ # Step 4: Gene Identifier Review
125
+ print("requires_gene_mapping = True")
126
+
127
+ # Step 5: Gene Annotation
128
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
129
+ gene_annotation = get_gene_annotation(soft_file)
130
+
131
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
132
+ print("Gene annotation preview:")
133
+ print(preview_df(gene_annotation))
134
+
135
+ # Step 6: Gene Identifier Mapping
136
+ import re
137
+ import pandas as pd
138
+
139
+ # Preserve the original probe/transcript-level expression dataframe
140
+ expr_df = gene_data.copy()
141
+
142
+ # 1) Decide identifier and gene symbol columns and build mapping dataframe
143
+ # Identify the gene symbol column
144
+ symbol_col = None
145
+ for c in gene_annotation.columns:
146
+ cl = c.lower().strip()
147
+ if cl == 'gene symbol' or 'gene symbol' in cl or cl == 'gene_symbol':
148
+ symbol_col = c
149
+ break
150
+ if symbol_col is None:
151
+ raise RuntimeError("Could not find a 'Gene Symbol' column in the platform annotation (SOFT).")
152
+
153
+ selected_identifier_info = None
154
+ mapping_df = None
155
+ overlap_ids = 0
156
+
157
+ # Attempt A: Use SOFT 'ID' (Affy probe IDs) vs expression IDs
158
+ if 'ID' in gene_annotation.columns:
159
+ tmp_map = get_gene_mapping(gene_annotation, prob_col='ID', gene_col=symbol_col)
160
+ overlap_ids_A = tmp_map['ID'].isin(expr_df.index).sum()
161
+ if overlap_ids_A > 0:
162
+ mapping_df = tmp_map
163
+ overlap_ids = tmp_map['ID'].isin(expr_df.index).sum()
164
+ selected_identifier_info = "SOFT column 'ID' (Affymetrix probe IDs)"
165
+ # If zero, likely mismatch because expression index looks like ENSTxxx_at
166
+
167
+ # Attempt B: Parse Ensembl Transcript IDs (ENST) from any annotation column, map to Gene Symbol
168
+ if mapping_df is None:
169
+ # Prioritize columns explicitly mentioning Ensembl
170
+ candidate_cols = [c for c in gene_annotation.columns if 'ensembl' in c.lower()]
171
+ # If none found, scan all columns for ENST tokens
172
+ if not candidate_cols:
173
+ candidate_cols = list(gene_annotation.columns)
174
+
175
+ enst_cols = []
176
+ for col in candidate_cols:
177
+ # Check if column contains any ENST token
178
+ try:
179
+ has_enst = gene_annotation[col].astype(str).str.contains(r'ENST\d+', regex=True, na=False).any()
180
+ except Exception:
181
+ has_enst = False
182
+ if has_enst:
183
+ enst_cols.append(col)
184
+
185
+ if enst_cols:
186
+ rows = []
187
+ # Build mapping rows from ENST tokens to Gene Symbol; align to matrix IDs by appending '_at'
188
+ for col in enst_cols:
189
+ sub = gene_annotation[[col, symbol_col]].dropna(subset=[col, symbol_col])
190
+ # Iterate rows to extract all ENST tokens per cell
191
+ for val, gene_sym in zip(sub[col].astype(str), sub[symbol_col].astype(str)):
192
+ tokens = re.findall(r'ENST\d+', val)
193
+ if tokens:
194
+ for t in set(tokens):
195
+ rows.append((t + '_at', gene_sym))
196
+ if rows:
197
+ map_df = pd.DataFrame(rows, columns=['ID', 'Gene']).drop_duplicates()
198
+ # Keep only IDs present in expression data
199
+ map_df = map_df[map_df['ID'].isin(expr_df.index)]
200
+ overlap_ids_B = map_df['ID'].nunique()
201
+ if overlap_ids_B > 0:
202
+ mapping_df = map_df
203
+ overlap_ids = overlap_ids_B
204
+ selected_identifier_info = f"Parsed ENST tokens from columns: {enst_cols} (appended '_at')"
205
+
206
+ # Ensure we do not proceed without a valid mapping
207
+ if mapping_df is None or overlap_ids == 0:
208
+ raise RuntimeError(
209
+ "Failed to construct a valid mapping from platform annotation to the matrix identifiers.\n"
210
+ f"Matrix index example: {list(expr_df.index[:5])}\n"
211
+ f"Available annotation columns: {list(gene_annotation.columns)}\n"
212
+ "Tried: (A) 'ID' vs matrix IDs; (B) parsing ENST tokens and appending '_at'."
213
+ )
214
+
215
+ # 2-3) Apply mapping to convert probe/transcript-level data to gene-level expression
216
+ print(f"Selected identifier source: {selected_identifier_info}")
217
+ print(f"Selected symbol column: {symbol_col}")
218
+ print(f"Number of unique matrix IDs covered by mapping: {overlap_ids}")
219
+
220
+ gene_data = apply_gene_mapping(expr_df, mapping_df)
221
+
222
+ print(f"Gene-level matrix shape: {gene_data.shape}")
223
+ # Optional quick preview of mapped genes
224
+ print(f"First 5 mapped genes: {list(gene_data.index[:5])}")
225
+
226
+ # Step 7: Gene Identifier Mapping
227
+ import re
228
+ import pandas as pd
229
+
230
+ # Start from the previously extracted matrix-level expression data
231
+ expr_df = gene_data.copy()
232
+
233
+ # 1) Try to build a mapping from platform annotation: ENST*_at -> Gene Symbol
234
+ mapping_df = None
235
+ strategy_info = ""
236
+
237
+ def find_symbol_column(df: pd.DataFrame) -> str:
238
+ for c in df.columns:
239
+ if c.strip().lower() == 'gene symbol':
240
+ return c
241
+ for c in df.columns:
242
+ cl = c.strip().lower()
243
+ if 'gene symbol' in cl or cl in ('gene_symbol', 'genesymbol'):
244
+ return c
245
+ raise RuntimeError("No 'Gene Symbol' column found.")
246
+
247
+ try:
248
+ symbol_col = find_symbol_column(gene_annotation)
249
+ enst_cols = []
250
+ for col in gene_annotation.columns:
251
+ try:
252
+ if gene_annotation[col].astype(str).str.contains(r'ENST\d+', regex=True, na=False).any():
253
+ enst_cols.append(col)
254
+ except Exception:
255
+ continue
256
+
257
+ if enst_cols:
258
+ rows = []
259
+ sub = gene_annotation[enst_cols + [symbol_col]].dropna(subset=[symbol_col])
260
+ for _, r in sub.iterrows():
261
+ sym = str(r[symbol_col])
262
+ for col in enst_cols:
263
+ val = str(r[col])
264
+ tokens = re.findall(r'ENST\d+', val)
265
+ for t in set(tokens):
266
+ rows.append((t + '_at', sym))
267
+ if rows:
268
+ map_df = pd.DataFrame(rows, columns=['ID', 'Gene']).drop_duplicates()
269
+ map_df = map_df[map_df['ID'].isin(expr_df.index)]
270
+ if map_df['ID'].nunique() > 0:
271
+ mapping_df = map_df
272
+ strategy_info = f"Parsed ENST tokens from annotation columns {enst_cols} mapped to '{symbol_col}'."
273
+ except Exception:
274
+ pass
275
+
276
+ # 2) Fallback: if no valid mapping to gene symbols, proceed with transcript-level IDs as features
277
+ if mapping_df is None or mapping_df['ID'].nunique() == 0:
278
+ mapping_df = pd.DataFrame({
279
+ 'ID': expr_df.index.astype(str),
280
+ 'Gene': expr_df.index.astype(str)
281
+ })
282
+ strategy_info = "No valid platform mapping found; proceeding with transcript-level IDs (ENST*_at) as features."
283
+
284
+ def apply_mapping_no_symbol_filter(expression_df: pd.DataFrame, mapping_df: pd.DataFrame) -> pd.DataFrame:
285
+ m = mapping_df.copy()
286
+ m = m[m['ID'].isin(expression_df.index)]
287
+ # Split multi-gene entries if present (e.g., 'A /// B')
288
+ def _split_genes(g):
289
+ if g is None or (isinstance(g, float) and pd.isna(g)):
290
+ return []
291
+ parts = re.split(r'\s*///\s*|;|,', str(g))
292
+ parts = [p.strip() for p in parts if p.strip()]
293
+ return parts if parts else [str(g).strip()]
294
+ m['Gene'] = m['Gene'].apply(_split_genes)
295
+ m['num_genes'] = m['Gene'].apply(len).clip(lower=1)
296
+ m = m.explode('Gene')
297
+ m = m.dropna(subset=['Gene'])
298
+ m = m.set_index('ID')
299
+ merged = m.join(expression_df)
300
+ expr_cols = [c for c in merged.columns if c not in ['Gene', 'num_genes']]
301
+ merged[expr_cols] = merged[expr_cols].div(merged['num_genes'], axis=0)
302
+ gene_expression_df = merged.groupby('Gene')[expr_cols].sum()
303
+ return gene_expression_df
304
+
305
+ gene_data = apply_mapping_no_symbol_filter(expr_df, mapping_df)
306
+
307
+ # Diagnostics
308
+ covered_ids = mapping_df['ID'].isin(expr_df.index).sum()
309
+ print(strategy_info)
310
+ print(f"Number of unique matrix IDs covered by mapping: {covered_ids}")
311
+ print(f"Gene-level matrix shape: {gene_data.shape}")
312
+ print(f"First 5 mapped gene identifiers: {list(gene_data.index[:5])}")
313
+
314
+ # Step 8: Data Normalization and Linking
315
+ import os
316
+ import pandas as pd
317
+
318
+ # 1. Normalize gene symbols with fallback if normalization removes most rows
319
+ note = "INFO: "
320
+ try:
321
+ normalized_gene_data_attempt = normalize_gene_symbols_in_index(gene_data.copy())
322
+ original_rows = len(gene_data)
323
+ normalized_rows = len(normalized_gene_data_attempt)
324
+ retention_ratio = (normalized_rows / original_rows) if original_rows > 0 else 0.0
325
+ except Exception as e:
326
+ normalized_gene_data_attempt = pd.DataFrame()
327
+ retention_ratio = 0.0
328
+
329
+ # Fallback to transcript-level features if too few rows remain after normalization
330
+ if (normalized_gene_data_attempt is None) or (len(normalized_gene_data_attempt) == 0) or (retention_ratio < 0.05):
331
+ normalized_gene_data = gene_data.copy()
332
+ note = ("WARNING: Gene symbol normalization skipped; platform mapping unavailable and normalization "
333
+ f"retained {normalized_rows if 'normalized_rows' in locals() else 0} of {original_rows if 'original_rows' in locals() else 'NA'} "
334
+ "rows (<5%). Proceeding with transcript-level (ENST*_at) features.")
335
+ else:
336
+ normalized_gene_data = normalized_gene_data_attempt
337
+ note = (f"INFO: Gene symbols normalized using synonym table; retained "
338
+ f"{len(normalized_gene_data)} of {len(gene_data)} rows ({retention_ratio:.1%}).")
339
+
340
+ # Ensure output directory exists and save gene data
341
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
342
+ normalized_gene_data.to_csv(out_gene_data_file)
343
+
344
+ # 2. Link clinical and genetic data
345
+ # Ensure the clinical dataframe variable is available (fallback to reloading from disk if necessary)
346
+ if 'selected_clinical_df' not in globals():
347
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
348
+
349
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
350
+
351
+ # 3. Handle missing values
352
+ linked_data = handle_missing_values(linked_data, trait)
353
+
354
+ # 4. Bias assessment (only if data is non-empty and has columns)
355
+ if len(linked_data) > 0 and trait in linked_data.columns:
356
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
357
+ else:
358
+ # Create a minimal placeholder to pass to validator
359
+ unbiased_linked_data = linked_data
360
+ is_trait_biased = True
361
+ note = ("ERROR: Linked dataset is empty or missing the trait column after preprocessing; "
362
+ "cannot perform bias assessment.")
363
+
364
+ # 5. Final validation and save cohort info
365
+ is_usable = validate_and_save_cohort_info(
366
+ is_final=True,
367
+ cohort=cohort,
368
+ info_path=json_path,
369
+ is_gene_available=True,
370
+ is_trait_available=True,
371
+ is_biased=is_trait_biased,
372
+ df=unbiased_linked_data,
373
+ note=note
374
+ )
375
+
376
+ # 6. Save linked data if usable
377
+ if is_usable:
378
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
379
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Heart_rate/code/GSE72462.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Heart_rate"
6
+ cohort = "GSE72462"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Heart_rate"
10
+ in_cohort_dir = "../DATA/GEO/Heart_rate/GSE72462"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z3/preprocess/Heart_rate/GSE72462.csv"
14
+ out_gene_data_file = "./output/z3/preprocess/Heart_rate/gene_data/GSE72462.csv"
15
+ out_clinical_data_file = "./output/z3/preprocess/Heart_rate/clinical_data/GSE72462.csv"
16
+ json_path = "./output/z3/preprocess/Heart_rate/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Determine data availability based on provided background info and sample characteristics
40
+ is_gene_available = True # Gene expression microarray on muscle biopsies
41
+ trait_row = None # No heart rate data present in sample characteristics
42
+ age_row = 3 # 'age: ...'
43
+ gender_row = 2 # 'Sex: female/male'
44
+
45
+ # Define conversion functions
46
+ def _after_colon(value):
47
+ if value is None:
48
+ return None
49
+ # Split once by colon and take the part after it, else use the whole string
50
+ parts = str(value).split(":", 1)
51
+ v = parts[1] if len(parts) > 1 else parts[0]
52
+ return v.strip().strip('"').strip()
53
+
54
+ def convert_trait(value):
55
+ # No heart rate information in this dataset
56
+ return None
57
+
58
+ def convert_age(value):
59
+ v = _after_colon(value)
60
+ if v is None or v == '':
61
+ return None
62
+ # Extract leading number (int or float)
63
+ import re
64
+ m = re.search(r"[-+]?\d*\.?\d+", v)
65
+ if not m:
66
+ return None
67
+ try:
68
+ num = float(m.group())
69
+ return num
70
+ except:
71
+ return None
72
+
73
+ def convert_gender(value):
74
+ v = _after_colon(value)
75
+ if v is None or v == '':
76
+ return None
77
+ v_low = v.lower()
78
+ if v_low in ['male', 'm']:
79
+ return 1
80
+ if v_low in ['female', 'f']:
81
+ return 0
82
+ return None
83
+
84
+ # Initial filtering and save cohort metadata
85
+ is_trait_available = trait_row is not None
86
+ _ = validate_and_save_cohort_info(
87
+ is_final=False,
88
+ cohort=cohort,
89
+ info_path=json_path,
90
+ is_gene_available=is_gene_available,
91
+ is_trait_available=is_trait_available
92
+ )
93
+
94
+ # Clinical feature extraction is skipped because trait data is not available (trait_row is None).
output/preprocess/Heart_rate/code/TCGA.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Heart_rate"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z3/preprocess/Heart_rate/TCGA.csv"
12
+ out_gene_data_file = "./output/z3/preprocess/Heart_rate/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z3/preprocess/Heart_rate/clinical_data/TCGA.csv"
14
+ json_path = "./output/z3/preprocess/Heart_rate/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import re
20
+ import pandas as pd
21
+
22
+ # Given list of subdirectories from TCGA Xena dataset
23
+ subdirs = ['TCGA_lower_grade_glioma_and_glioblastoma_(GBMLGG)', 'TCGA_Uterine_Carcinosarcoma_(UCS)', 'TCGA_Thyroid_Cancer_(THCA)', 'TCGA_Thymoma_(THYM)', 'TCGA_Testicular_Cancer_(TGCT)', 'TCGA_Stomach_Cancer_(STAD)', 'TCGA_Sarcoma_(SARC)', 'TCGA_Rectal_Cancer_(READ)', 'TCGA_Prostate_Cancer_(PRAD)', 'TCGA_Pheochromocytoma_Paraganglioma_(PCPG)', 'TCGA_Pancreatic_Cancer_(PAAD)', 'TCGA_Ovarian_Cancer_(OV)', 'TCGA_Ocular_melanomas_(UVM)', 'TCGA_Mesothelioma_(MESO)', 'TCGA_Melanoma_(SKCM)', 'TCGA_Lung_Squamous_Cell_Carcinoma_(LUSC)', 'TCGA_Lung_Cancer_(LUNG)', 'TCGA_Lung_Adenocarcinoma_(LUAD)', 'TCGA_Lower_Grade_Glioma_(LGG)', 'TCGA_Liver_Cancer_(LIHC)', 'TCGA_Large_Bcell_Lymphoma_(DLBC)', 'TCGA_Kidney_Papillary_Cell_Carcinoma_(KIRP)', 'TCGA_Kidney_Clear_Cell_Carcinoma_(KIRC)', 'TCGA_Kidney_Chromophobe_(KICH)', 'TCGA_Head_and_Neck_Cancer_(HNSC)', 'TCGA_Glioblastoma_(GBM)', 'TCGA_Esophageal_Cancer_(ESCA)', 'TCGA_Endometrioid_Cancer_(UCEC)', 'TCGA_Colon_and_Rectal_Cancer_(COADREAD)', 'TCGA_Colon_Cancer_(COAD)', 'TCGA_Cervical_Cancer_(CESC)', 'TCGA_Breast_Cancer_(BRCA)', 'TCGA_Bladder_Cancer_(BLCA)', 'TCGA_Bile_Duct_Cancer_(CHOL)', 'TCGA_Adrenocortical_Cancer_(ACC)', 'TCGA_Acute_Myeloid_Leukemia_(LAML)']
24
+
25
+ # Heart-rate related terms to match as whole words to avoid false positives
26
+ hr_terms = ['heart rate', 'heart', 'cardiac', 'pulse', 'tachycardia', 'bradycardia', 'arrhythmia', 'palpitation', 'sinus']
27
+ # Build a regex that enforces word boundaries and is case-insensitive
28
+ hr_pattern = re.compile(r'\b(' + '|'.join(map(re.escape, hr_terms)) + r')\b', flags=re.IGNORECASE)
29
+
30
+ def contains_hr_term(name: str) -> bool:
31
+ # Normalize separators to spaces so word boundaries behave sensibly
32
+ normalized = re.sub(r'[_()/\-]+', ' ', name)
33
+ return bool(hr_pattern.search(normalized))
34
+
35
+ # Try to find a cohort directory relevant to "Heart_rate"
36
+ matches = [d for d in subdirs if contains_hr_term(d)]
37
+
38
+ selected_dir = None
39
+ if matches:
40
+ # Choose the most specific match (longest name as a naive proxy for specificity)
41
+ selected_dir = sorted(matches, key=lambda x: len(x), reverse=True)[0]
42
+
43
+ clinical_df = pd.DataFrame()
44
+ genetic_df = pd.DataFrame()
45
+
46
+ if selected_dir is None:
47
+ print("No TCGA cohort directory name matches heart-rate related terms. Skipping this trait.")
48
+ validate_and_save_cohort_info(
49
+ is_final=False,
50
+ cohort="TCGA",
51
+ info_path=json_path,
52
+ is_gene_available=False,
53
+ is_trait_available=False
54
+ )
55
+ else:
56
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
57
+ clinical_path, genetic_path = tcga_get_relevant_filepaths(cohort_dir)
58
+
59
+ # Load clinical data first to perform a quick robustness check for HR-related fields
60
+ clinical_df = pd.read_csv(clinical_path, sep='\t', index_col=0, low_memory=False)
61
+
62
+ # Check if clinical columns contain heart-rate related fields
63
+ col_text = ' '.join(map(str, clinical_df.columns)).lower()
64
+ has_hr_field = any(term in col_text for term in ['heart rate', 'heartrate', 'pulse', 'tachycardia', 'bradycardia', 'arrhythmia', 'palpitation'])
65
+
66
+ if not has_hr_field:
67
+ print(f"Selected directory '{selected_dir}' does not contain heart-rate related clinical fields. Skipping this trait.")
68
+ # Record and skip without loading genetic data or printing columns
69
+ validate_and_save_cohort_info(
70
+ is_final=False,
71
+ cohort="TCGA",
72
+ info_path=json_path,
73
+ is_gene_available=False,
74
+ is_trait_available=False
75
+ )
76
+ clinical_df = pd.DataFrame()
77
+ genetic_df = pd.DataFrame()
78
+ else:
79
+ # Proceed to load genetic data and print clinical columns
80
+ genetic_df = pd.read_csv(genetic_path, sep='\t', index_col=0, low_memory=False)
81
+ print(list(clinical_df.columns))
output/preprocess/Heart_rate/cohort_info.json CHANGED
@@ -1,82 +1 @@
1
- {
2
- "GSE72462": {
3
- "is_usable": false,
4
- "is_gene_available": false,
5
- "is_trait_available": false,
6
- "is_available": false,
7
- "is_biased": null,
8
- "has_age": null,
9
- "has_gender": null,
10
- "sample_size": null
11
- },
12
- "GSE35661": {
13
- "is_usable": true,
14
- "is_gene_available": true,
15
- "is_trait_available": true,
16
- "is_available": true,
17
- "is_biased": false,
18
- "has_age": false,
19
- "has_gender": false,
20
- "sample_size": 24
21
- },
22
- "GSE34788": {
23
- "is_usable": false,
24
- "is_gene_available": false,
25
- "is_trait_available": false,
26
- "is_available": false,
27
- "is_biased": null,
28
- "has_age": null,
29
- "has_gender": null,
30
- "sample_size": null
31
- },
32
- "GSE236927": {
33
- "is_usable": true,
34
- "is_gene_available": true,
35
- "is_trait_available": true,
36
- "is_available": true,
37
- "is_biased": false,
38
- "has_age": false,
39
- "has_gender": false,
40
- "sample_size": 95
41
- },
42
- "GSE18583": {
43
- "is_usable": true,
44
- "is_gene_available": true,
45
- "is_trait_available": true,
46
- "is_available": true,
47
- "is_biased": false,
48
- "has_age": false,
49
- "has_gender": false,
50
- "sample_size": 24
51
- },
52
- "GSE12385": {
53
- "is_usable": false,
54
- "is_gene_available": false,
55
- "is_trait_available": false,
56
- "is_available": false,
57
- "is_biased": null,
58
- "has_age": null,
59
- "has_gender": null,
60
- "sample_size": null
61
- },
62
- "GSE117070": {
63
- "is_usable": false,
64
- "is_gene_available": true,
65
- "is_trait_available": false,
66
- "is_available": false,
67
- "is_biased": null,
68
- "has_age": null,
69
- "has_gender": null,
70
- "sample_size": null
71
- },
72
- "TCGA": {
73
- "is_usable": false,
74
- "is_gene_available": true,
75
- "is_trait_available": true,
76
- "is_available": true,
77
- "is_biased": true,
78
- "has_age": true,
79
- "has_gender": true,
80
- "sample_size": 79
81
- }
82
- }
 
1
+ {"GSE72462": {"is_usable": false, "is_gene_available": true, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": null}, "GSE35661": {"is_usable": true, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": false, "has_age": false, "has_gender": false, "sample_size": 24, "note": "WARNING: Gene symbol normalization skipped; platform mapping unavailable and normalization retained 0 of 25710 rows (<5%). Proceeding with transcript-level (ENST*_at) features."}, "GSE34788": {"is_usable": true, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": false, "has_age": false, "has_gender": false, "sample_size": 120, "note": "INFO: Only trait available; Age/Gender not provided in clinical annotations."}, "GSE236927": {"is_usable": false, "is_gene_available": true, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": null}, "GSE18583": {"is_usable": true, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": false, "has_age": false, "has_gender": false, "sample_size": 24, "note": "INFO: Gene symbols normalized using NCBI synonym mapping."}, "GSE12385": {"is_usable": false, "is_gene_available": true, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": null}, "GSE117070": {"is_usable": false, "is_gene_available": true, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": "INFO: Trait 'Heart_rate' unavailable in clinical annotations; only 'status: pre/post-training' present. Skipping linking."}, "TCGA": {"is_usable": false, "is_gene_available": false, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": null}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Heart_rate/gene_data/GSE35661.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Height/GSE117525.csv ADDED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Height/GSE131835.csv ADDED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Height/clinical_data/GSE106800.csv CHANGED
@@ -1,48 +1,3 @@
1
- Sample,Height,Age,Gender
2
- GSM2850460,,24.0,1.0
3
- GSM2850461,,24.0,1.0
4
- GSM2850462,,24.0,1.0
5
- GSM2850463,,24.0,1.0
6
- GSM2850464,,24.0,1.0
7
- GSM2850465,,24.0,1.0
8
- GSM2850466,,24.0,1.0
9
- GSM2850467,,24.0,1.0
10
- GSM2850468,,21.0,1.0
11
- GSM2850469,,21.0,1.0
12
- GSM2850470,,21.0,1.0
13
- GSM2850471,,21.0,1.0
14
- GSM2850472,,20.0,1.0
15
- GSM2850473,,20.0,1.0
16
- GSM2850474,,20.0,1.0
17
- GSM2850475,,20.0,1.0
18
- GSM2850476,,22.0,1.0
19
- GSM2850477,,22.0,1.0
20
- GSM2850478,,22.0,1.0
21
- GSM2850479,,22.0,1.0
22
- GSM2850480,,20.0,1.0
23
- GSM2850481,,20.0,1.0
24
- GSM2850482,,20.0,1.0
25
- GSM2850483,,19.0,1.0
26
- GSM2850484,,19.0,1.0
27
- GSM2850485,,19.0,1.0
28
- GSM2850486,,19.0,1.0
29
- GSM2850487,,22.0,1.0
30
- GSM2850488,,22.0,1.0
31
- GSM2850489,,22.0,1.0
32
- GSM2850490,,22.0,1.0
33
- GSM2850491,,21.0,1.0
34
- GSM2850492,,21.0,1.0
35
- GSM2850493,,21.0,1.0
36
- GSM2850494,,21.0,1.0
37
- GSM2850495,,26.0,1.0
38
- GSM2850496,,26.0,1.0
39
- GSM2850497,,26.0,1.0
40
- GSM2850498,,26.0,1.0
41
- GSM2850499,,20.0,1.0
42
- GSM2850500,,20.0,1.0
43
- GSM2850501,,20.0,1.0
44
- GSM2850502,,20.0,1.0
45
- GSM2850503,,29.0,1.0
46
- GSM2850504,,29.0,1.0
47
- GSM2850505,,29.0,1.0
48
- GSM2850506,,29.0,1.0
 
1
+ ,GSM2850460,GSM2850461,GSM2850462,GSM2850463,GSM2850464,GSM2850465,GSM2850466,GSM2850467,GSM2850468,GSM2850469,GSM2850470,GSM2850471,GSM2850472,GSM2850473,GSM2850474,GSM2850475,GSM2850476,GSM2850477,GSM2850478,GSM2850479,GSM2850480,GSM2850481,GSM2850482,GSM2850483,GSM2850484,GSM2850485,GSM2850486,GSM2850487,GSM2850488,GSM2850489,GSM2850490,GSM2850491,GSM2850492,GSM2850493,GSM2850494,GSM2850495,GSM2850496,GSM2850497,GSM2850498,GSM2850499,GSM2850500,GSM2850501,GSM2850502,GSM2850503,GSM2850504,GSM2850505,GSM2850506
2
+ Height,1.72,1.72,1.72,1.72,1.85,1.85,1.85,1.85,1.74,1.74,1.74,1.74,1.71,1.71,1.71,1.71,1.89,1.89,1.89,1.89,1.76,1.76,1.76,1.91,1.91,1.91,1.91,1.9,1.9,1.9,1.9,1.82,1.82,1.82,1.82,1.9,1.9,1.9,1.9,1.74,1.74,1.74,1.74,1.88,1.88,1.88,1.88
3
+ Age,24.0,24.0,24.0,24.0,24.0,24.0,24.0,24.0,21.0,21.0,21.0,21.0,20.0,20.0,20.0,20.0,22.0,22.0,22.0,22.0,20.0,20.0,20.0,19.0,19.0,19.0,19.0,22.0,22.0,22.0,22.0,21.0,21.0,21.0,21.0,26.0,26.0,26.0,26.0,20.0,20.0,20.0,20.0,29.0,29.0,29.0,29.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Height/clinical_data/GSE131835.csv ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ,GSM3821249,GSM3821251,GSM3821252,GSM3821254,GSM3821255,GSM3821257,GSM3821258,GSM3821259,GSM3821261,GSM3821262,GSM3821264,GSM3821265,GSM3821267,GSM3821268,GSM3821269,GSM3821271,GSM3821273,GSM3821274,GSM3821276,GSM3821277,GSM3821278,GSM3821280,GSM3821281,GSM3821283,GSM3821284,GSM3821285,GSM3821287,GSM3821288,GSM3821290,GSM3821291,GSM3821292,GSM3821293,GSM3821295,GSM3821296,GSM3821298,GSM3821299,GSM3821301,GSM3821302,GSM3821304,GSM3821305,GSM3821307,GSM3821308,GSM3821309,GSM3821311,GSM3821312,GSM3821314,GSM3821315,GSM3821316
2
+ Height,178.0,170.0,166.0,160.0,180.0,163.0,178.0,183.0,180.0,172.0,169.0,160.0,166.0,170.0,158.0,158.0,172.0,183.0,163.0,173.0,173.0,169.0,193.0,152.0,170.0,158.0,158.0,152.0,193.0,167.0,167.0,168.0,168.0,177.0,165.0,165.0,158.0,179.0,177.0,158.0,183.0,183.0,190.0,170.0,179.0,190.0,170.0,170.0
3
+ Age,51.0,64.0,62.0,78.0,47.0,59.0,51.0,57.0,47.0,58.0,53.0,78.0,62.0,64.0,49.0,49.0,58.0,57.0,59.0,54.0,54.0,53.0,60.0,56.0,64.0,41.0,41.0,56.0,60.0,56.0,56.0,76.0,76.0,81.0,48.0,48.0,65.0,68.0,81.0,65.0,65.0,65.0,72.0,64.0,68.0,72.0,59.0,59.0
4
+ Gender,1.0,1.0,0.0,0.0,1.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,0.0,1.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0