Liu-Hy commited on
Commit
7c88557
·
verified ·
1 Parent(s): d818561

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/Cervical_Cancer/GSE138080.csv +0 -0
  2. output/preprocess/Cervical_Cancer/GSE63678.csv +0 -0
  3. output/preprocess/Cervical_Cancer/clinical_data/GSE107754.csv +1 -1
  4. output/preprocess/Cervical_Cancer/clinical_data/GSE131027.csv +3 -2
  5. output/preprocess/Cervical_Cancer/clinical_data/GSE138080.csv +1 -1
  6. output/preprocess/Cervical_Cancer/clinical_data/GSE63678.csv +2 -2
  7. output/preprocess/Cervical_Cancer/clinical_data/GSE75132.csv +2 -2
  8. output/preprocess/Cervical_Cancer/code/GSE107754.py +211 -0
  9. output/preprocess/Cervical_Cancer/code/GSE114243.py +180 -0
  10. output/preprocess/Cervical_Cancer/code/GSE131027.py +200 -0
  11. output/preprocess/Cervical_Cancer/code/GSE137034.py +136 -0
  12. output/preprocess/Cervical_Cancer/code/GSE138079.py +114 -0
  13. output/preprocess/Cervical_Cancer/code/GSE138080.py +223 -0
  14. output/preprocess/Cervical_Cancer/code/GSE146114.py +131 -0
  15. output/preprocess/Cervical_Cancer/code/GSE163114.py +128 -0
  16. output/preprocess/Cervical_Cancer/code/GSE63678.py +275 -0
  17. output/preprocess/Cervical_Cancer/code/GSE75132.py +186 -0
  18. output/preprocess/Cervical_Cancer/code/TCGA.py +238 -0
  19. output/preprocess/Chronic_Fatigue_Syndrome/code/GSE251792.py +239 -0
  20. output/preprocess/Chronic_Fatigue_Syndrome/code/GSE39684.py +132 -0
  21. output/preprocess/Chronic_Fatigue_Syndrome/code/GSE67311.py +183 -0
  22. output/preprocess/Chronic_Fatigue_Syndrome/code/TCGA.py +84 -0
  23. output/preprocess/Chronic_Fatigue_Syndrome/cohort_info.json +1 -42
  24. output/preprocess/Chronic_kidney_disease/GSE142153.csv +0 -0
  25. output/preprocess/Chronic_kidney_disease/clinical_data/GSE104948.csv +1 -1
  26. output/preprocess/Chronic_kidney_disease/clinical_data/GSE104954.csv +1 -1
  27. output/preprocess/Chronic_kidney_disease/clinical_data/GSE127136.csv +0 -0
  28. output/preprocess/Chronic_kidney_disease/clinical_data/GSE180393.csv +2 -2
  29. output/preprocess/Chronic_kidney_disease/clinical_data/GSE180394.csv +2 -2
  30. output/preprocess/Chronic_kidney_disease/clinical_data/GSE45980.csv +4 -4
  31. output/preprocess/Chronic_kidney_disease/clinical_data/GSE66494.csv +2 -2
  32. output/preprocess/Chronic_kidney_disease/code/GSE104948.py +181 -0
  33. output/preprocess/Chronic_kidney_disease/code/GSE104954.py +209 -0
  34. output/preprocess/Chronic_kidney_disease/code/GSE127136.py +134 -0
  35. output/preprocess/Chronic_kidney_disease/code/GSE142153.py +206 -0
  36. output/preprocess/Chronic_kidney_disease/code/GSE180393.py +310 -0
  37. output/preprocess/Chronic_kidney_disease/code/GSE180394.py +394 -0
  38. output/preprocess/Chronic_kidney_disease/code/GSE45980.py +214 -0
  39. output/preprocess/Chronic_kidney_disease/code/GSE60861.py +214 -0
  40. output/preprocess/Chronic_kidney_disease/code/GSE66494.py +238 -0
  41. output/preprocess/Chronic_kidney_disease/code/GSE69438.py +202 -0
  42. output/preprocess/Chronic_kidney_disease/code/TCGA.py +59 -0
  43. output/preprocess/Chronic_kidney_disease/cohort_info.json +1 -92
  44. output/preprocess/Chronic_kidney_disease/gene_data/GSE142153.csv +0 -0
  45. output/preprocess/Colon_and_Rectal_Cancer/code/GSE46517.py +125 -0
  46. output/preprocess/Colon_and_Rectal_Cancer/code/GSE46862.py +166 -0
  47. output/preprocess/Colon_and_Rectal_Cancer/code/GSE56699.py +196 -0
  48. output/preprocess/Colon_and_Rectal_Cancer/code/TCGA.py +269 -0
  49. output/preprocess/Colon_and_Rectal_Cancer/cohort_info.json +1 -42
  50. output/preprocess/Congestive_heart_failure/clinical_data/GSE182600.csv +4 -0
output/preprocess/Cervical_Cancer/GSE138080.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Cervical_Cancer/GSE63678.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Cervical_Cancer/clinical_data/GSE107754.csv CHANGED
@@ -1,3 +1,3 @@
1
  ,GSM2878070,GSM2878071,GSM2878072,GSM2878073,GSM2878074,GSM2878075,GSM2878076,GSM2878077,GSM2878078,GSM2878079,GSM2878080,GSM2878081,GSM2878082,GSM2891194,GSM2891195,GSM2891196,GSM2891197,GSM2891198,GSM2891199,GSM2891200,GSM2891201,GSM2891202,GSM2891203,GSM2891204,GSM2891205,GSM2891206,GSM2891207,GSM2891208,GSM2891209,GSM2891210,GSM2891211,GSM2891212,GSM2891213,GSM2891214,GSM2891215,GSM2891216,GSM2891217,GSM2891218,GSM2891219,GSM2891220,GSM2891221,GSM2891222,GSM2891223,GSM2891224,GSM2891225,GSM2891226,GSM2891227,GSM2891228,GSM2891229,GSM2891230,GSM2891231,GSM2891232,GSM2891233,GSM2891234,GSM2891235,GSM2891236,GSM2891237,GSM2891238,GSM2891239,GSM2891240,GSM2891241,GSM2891242,GSM2891243,GSM2891244,GSM2891245,GSM2891246,GSM2891247,GSM2891248,GSM2891249,GSM2891250,GSM2891251,GSM2891252,GSM2891253,GSM2891254,GSM2891255,GSM2891256,GSM2891257,GSM2891258,GSM2891259,GSM2891260,GSM2891261,GSM2891262,GSM2891263,GSM2891264
2
- Cervical_Cancer,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,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.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,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
3
  Gender,1.0,0.0,1.0,1.0,0.0,1.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,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,0.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,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.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,1.0,0.0,1.0,1.0,1.0
 
1
  ,GSM2878070,GSM2878071,GSM2878072,GSM2878073,GSM2878074,GSM2878075,GSM2878076,GSM2878077,GSM2878078,GSM2878079,GSM2878080,GSM2878081,GSM2878082,GSM2891194,GSM2891195,GSM2891196,GSM2891197,GSM2891198,GSM2891199,GSM2891200,GSM2891201,GSM2891202,GSM2891203,GSM2891204,GSM2891205,GSM2891206,GSM2891207,GSM2891208,GSM2891209,GSM2891210,GSM2891211,GSM2891212,GSM2891213,GSM2891214,GSM2891215,GSM2891216,GSM2891217,GSM2891218,GSM2891219,GSM2891220,GSM2891221,GSM2891222,GSM2891223,GSM2891224,GSM2891225,GSM2891226,GSM2891227,GSM2891228,GSM2891229,GSM2891230,GSM2891231,GSM2891232,GSM2891233,GSM2891234,GSM2891235,GSM2891236,GSM2891237,GSM2891238,GSM2891239,GSM2891240,GSM2891241,GSM2891242,GSM2891243,GSM2891244,GSM2891245,GSM2891246,GSM2891247,GSM2891248,GSM2891249,GSM2891250,GSM2891251,GSM2891252,GSM2891253,GSM2891254,GSM2891255,GSM2891256,GSM2891257,GSM2891258,GSM2891259,GSM2891260,GSM2891261,GSM2891262,GSM2891263,GSM2891264
2
+ Cervical_Cancer,,,,,,,,,,,,,,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.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,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,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
3
  Gender,1.0,0.0,1.0,1.0,0.0,1.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,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,0.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,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.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,1.0,0.0,1.0,1.0,1.0
output/preprocess/Cervical_Cancer/clinical_data/GSE131027.csv CHANGED
@@ -1,2 +1,3 @@
1
- ,Sample_2,Sample_3,Sample_4,Sample_5,Sample_6,Sample_7,Sample_8,Sample_9,Sample_10,Sample_11,Sample_12,Sample_13,Sample_14,Sample_15,Sample_16,Sample_17,Sample_18,Sample_19,Sample_20,Sample_21,Sample_22,Sample_23,Sample_24
2
- Cervical_Cancer,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0
 
 
1
+ ,GSM3759992,GSM3759993,GSM3759994,GSM3759995,GSM3759996,GSM3759997,GSM3759998,GSM3759999,GSM3760000,GSM3760001,GSM3760002,GSM3760003,GSM3760004,GSM3760005,GSM3760006,GSM3760007,GSM3760008,GSM3760009,GSM3760010,GSM3760011,GSM3760012,GSM3760013,GSM3760014,GSM3760015,GSM3760016,GSM3760017,GSM3760018,GSM3760019,GSM3760020,GSM3760021,GSM3760022,GSM3760023,GSM3760024,GSM3760025,GSM3760026,GSM3760027,GSM3760028,GSM3760029,GSM3760030,GSM3760031,GSM3760032,GSM3760033,GSM3760034,GSM3760035,GSM3760036,GSM3760037,GSM3760038,GSM3760039,GSM3760040,GSM3760041,GSM3760042,GSM3760043,GSM3760044,GSM3760045,GSM3760046,GSM3760047,GSM3760048,GSM3760049,GSM3760050,GSM3760051,GSM3760052,GSM3760053,GSM3760054,GSM3760055,GSM3760056,GSM3760057,GSM3760058,GSM3760059,GSM3760060,GSM3760061,GSM3760062,GSM3760063,GSM3760064,GSM3760065,GSM3760066,GSM3760067,GSM3760068,GSM3760069,GSM3760070,GSM3760071,GSM3760072,GSM3760073,GSM3760074,GSM3760075,GSM3760076,GSM3760077,GSM3760078,GSM3760079,GSM3760080,GSM3760081,GSM3760082,GSM3760083
2
+ Cervical_Cancer,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,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.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,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.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,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
3
+ Gender,,,,,,,,,,,,,0.0,,0.0,,,,,,,,,0.0,,1.0,,,,,0.0,,,0.0,,0.0,,,,,,,,,,,,,,,,,,,,0.0,,,,,,0.0,,,,,,,,,,,,,,,,,,0.0,,,1.0,0.0,,0.0,,,1.0,,,
output/preprocess/Cervical_Cancer/clinical_data/GSE138080.csv CHANGED
@@ -1,2 +1,2 @@
1
  ,GSM4098861,GSM4098862,GSM4098863,GSM4098864,GSM4098865,GSM4098866,GSM4098867,GSM4098868,GSM4098869,GSM4098870,GSM4098871,GSM4098872,GSM4098873,GSM4098874,GSM4098875,GSM4098876,GSM4098877,GSM4098878,GSM4098879,GSM4098880,GSM4098881,GSM4098882,GSM4098883,GSM4098884,GSM4098885,GSM4098886,GSM4098887,GSM4098888,GSM4098889,GSM4098890,GSM4098891,GSM4098892,GSM4098893,GSM4098894,GSM4098895
2
- Cervical_Cancer,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,1.0
 
1
  ,GSM4098861,GSM4098862,GSM4098863,GSM4098864,GSM4098865,GSM4098866,GSM4098867,GSM4098868,GSM4098869,GSM4098870,GSM4098871,GSM4098872,GSM4098873,GSM4098874,GSM4098875,GSM4098876,GSM4098877,GSM4098878,GSM4098879,GSM4098880,GSM4098881,GSM4098882,GSM4098883,GSM4098884,GSM4098885,GSM4098886,GSM4098887,GSM4098888,GSM4098889,GSM4098890,GSM4098891,GSM4098892,GSM4098893,GSM4098894,GSM4098895
2
+ Cervical_Cancer,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
output/preprocess/Cervical_Cancer/clinical_data/GSE63678.csv CHANGED
@@ -1,2 +1,2 @@
1
- ,GSM1555075,GSM1555076,GSM1555077,GSM1555078,GSM1555079,GSM1555080,GSM1555081,GSM1555082,GSM1555083,GSM1555084,GSM1555085,GSM1555086,GSM1555087,GSM1555088,GSM1555089,GSM1555090,GSM1555091,GSM1555092,GSM1555093,GSM1555094,GSM1555095,GSM1555096,GSM1555097,GSM1555098,GSM1555099,GSM1555100,GSM1555101,GSM1555102,GSM1555103,GSM1555104,GSM1555105,GSM1555106,GSM1555107,GSM1555108,GSM1555109
2
- Cervical_Cancer,1.0,1.0,1.0,1.0,1.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,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
 
1
+ ,GSM1555075,GSM1555076,GSM1555077,GSM1555078,GSM1555079,GSM1555080,GSM1555081,GSM1555082,GSM1555083,GSM1555084
2
+ Cervical_Cancer,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0
output/preprocess/Cervical_Cancer/clinical_data/GSE75132.csv CHANGED
@@ -1,2 +1,2 @@
1
- GSM1943705,GSM1943706,GSM1943707,GSM1943708,GSM1943709,GSM1943710,GSM1943711,GSM1943712,GSM1943713,GSM1943714,GSM1943715,GSM1943716,GSM1943717,GSM1943718,GSM1943719,GSM1943720,GSM1943721,GSM1943722,GSM1943723,GSM1943724,GSM1943725,GSM1943726,GSM1943727,GSM1943728,GSM1943729,GSM1943730,GSM1943731,GSM1943732,GSM1943733,GSM1943734,GSM1943735,GSM1943736,GSM1943737,GSM1943738,GSM1943739,GSM1943740,GSM1943741,GSM1943742,GSM1943743,GSM1943744,GSM1943745
2
- 0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0
 
1
+ ,GSM1943705,GSM1943706,GSM1943707,GSM1943708,GSM1943709,GSM1943710,GSM1943711,GSM1943712,GSM1943713,GSM1943714,GSM1943715,GSM1943716,GSM1943717,GSM1943718,GSM1943719,GSM1943720,GSM1943721,GSM1943722,GSM1943723,GSM1943724,GSM1943725,GSM1943726,GSM1943727,GSM1943728,GSM1943729,GSM1943730,GSM1943731,GSM1943732,GSM1943733,GSM1943734,GSM1943735,GSM1943736,GSM1943737,GSM1943738,GSM1943739,GSM1943740,GSM1943741,GSM1943742,GSM1943743,GSM1943744,GSM1943745
2
+ Cervical_Cancer,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.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
output/preprocess/Cervical_Cancer/code/GSE107754.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Cervical_Cancer"
6
+ cohort = "GSE107754"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Cervical_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Cervical_Cancer/GSE107754"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Cervical_Cancer/GSE107754.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Cervical_Cancer/gene_data/GSE107754.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Cervical_Cancer/clinical_data/GSE107754.csv"
16
+ json_path = "./output/z2/preprocess/Cervical_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
+
41
+ # 1) Gene expression availability
42
+ is_gene_available = True # Whole human genome gene expression microarrays per background
43
+
44
+ # 2) Determine availability rows based on Sample Characteristics Dictionary
45
+ trait_row = 2 # tissue info including 'tissue: Cervix/Cervical cancer'
46
+ age_row = None # No age field observed
47
+ gender_row = 0 # 'gender: Female'/'gender: Male'
48
+
49
+ # 2.2) Conversion functions
50
+ def _after_colon(x):
51
+ try:
52
+ parts = str(x).split(":", 1)
53
+ return parts[1].strip() if len(parts) > 1 else str(x).strip()
54
+ except Exception:
55
+ return None
56
+
57
+ def convert_trait(x):
58
+ # Binary: 1 = Cervical/Cervix cancer, 0 = other tissues; unknown if not a tissue field
59
+ try:
60
+ s = str(x).strip()
61
+ # If header not present, try best-effort on the whole string
62
+ header = s.split(":", 1)[0].strip().lower() if ":" in s else ""
63
+ value = _after_colon(s)
64
+ if value is None:
65
+ return None
66
+ v = value.lower()
67
+ if "tissue" in header:
68
+ if ("cervix" in v) or ("cervical" in v):
69
+ return 1
70
+ else:
71
+ return 0
72
+ else:
73
+ # e.g., "biopsy location" or other non-tissue annotations in this row -> unknown
74
+ return None
75
+ except Exception:
76
+ return None
77
+
78
+ def convert_age(x):
79
+ # Not available in this dataset
80
+ return None
81
+
82
+ def convert_gender(x):
83
+ try:
84
+ v = _after_colon(x)
85
+ if v is None:
86
+ return None
87
+ vl = v.strip().lower()
88
+ if vl in {"female", "f"}:
89
+ return 0
90
+ if vl in {"male", "m"}:
91
+ return 1
92
+ return None
93
+ except Exception:
94
+ return None
95
+
96
+ # 3) Save metadata (initial filtering)
97
+ is_trait_available = trait_row is not None
98
+ _ = validate_and_save_cohort_info(
99
+ is_final=False,
100
+ cohort=cohort,
101
+ info_path=json_path,
102
+ is_gene_available=is_gene_available,
103
+ is_trait_available=is_trait_available
104
+ )
105
+
106
+ # 4) Clinical Feature Extraction (only if trait available)
107
+ if trait_row is not None:
108
+ selected_clinical_df = geo_select_clinical_features(
109
+ clinical_df=clinical_data,
110
+ trait=trait,
111
+ trait_row=trait_row,
112
+ convert_trait=convert_trait,
113
+ age_row=age_row,
114
+ convert_age=convert_age if age_row is not None else None,
115
+ gender_row=gender_row,
116
+ convert_gender=convert_gender
117
+ )
118
+ preview = preview_df(selected_clinical_df)
119
+ print(preview)
120
+
121
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
122
+ selected_clinical_df.to_csv(out_clinical_data_file)
123
+
124
+ # Step 3: Gene Data Extraction
125
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
126
+ gene_data = get_genetic_data(matrix_file)
127
+
128
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
129
+ print(gene_data.index[:20])
130
+
131
+ # Step 4: Gene Identifier Review
132
+ requires_gene_mapping = True
133
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
134
+
135
+ # Step 5: Gene Annotation
136
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
137
+ gene_annotation = get_gene_annotation(soft_file)
138
+
139
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
140
+ print("Gene annotation preview:")
141
+ print(preview_df(gene_annotation))
142
+
143
+ # Step 6: Gene Identifier Mapping
144
+ # Identify the appropriate columns in the annotation: 'ID' (probe IDs) and 'GENE_SYMBOL' (gene symbols)
145
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')
146
+
147
+ # Apply mapping to convert probe-level data to gene-level expression
148
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
149
+
150
+ # Step 7: Data Normalization and Linking
151
+ import os
152
+ import pandas as pd
153
+
154
+ # 1) Normalize gene data and save
155
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
156
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
157
+ normalized_gene_data.to_csv(out_gene_data_file)
158
+
159
+ # Prepare clinical dataframe from memory if available, else load from saved CSV
160
+ try:
161
+ clinical_df = selected_clinical_df
162
+ except NameError:
163
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
164
+ clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
165
+
166
+ # 2) Link clinical and genetic data
167
+ linked_data = geo_link_clinical_genetic_data(clinical_df, normalized_gene_data)
168
+
169
+ # 3) Handle missing values
170
+ linked_data = handle_missing_values(linked_data, trait)
171
+
172
+ # 4) Bias check and feature cleanup
173
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
174
+
175
+ # Debug: show resulting shape to aid troubleshooting
176
+ print(f"Unbiased linked data shape: {unbiased_linked_data.shape}")
177
+
178
+ # Availability flags as native Python bools
179
+ is_gene_available_final = bool(normalized_gene_data.shape[0] > 0 and normalized_gene_data.shape[1] > 0)
180
+ is_trait_available_final = bool((trait in clinical_df.index) and clinical_df.loc[trait].notna().any())
181
+
182
+ note = "INFO: Trait derived from tissue field; Age unavailable; Gender available."
183
+
184
+ # 5) Final quality validation and cohort info saving with robustness to legacy JSON issues
185
+ def _finalize_and_save():
186
+ return validate_and_save_cohort_info(
187
+ is_final=True,
188
+ cohort=cohort,
189
+ info_path=json_path,
190
+ is_gene_available=is_gene_available_final,
191
+ is_trait_available=is_trait_available_final,
192
+ is_biased=is_trait_biased,
193
+ df=unbiased_linked_data,
194
+ note=note
195
+ )
196
+
197
+ try:
198
+ is_usable = _finalize_and_save()
199
+ except Exception as e:
200
+ # If JSON serialization or legacy content issue occurs, reset the JSON file and retry once
201
+ if os.path.exists(json_path):
202
+ try:
203
+ os.remove(json_path)
204
+ except Exception:
205
+ pass
206
+ is_usable = _finalize_and_save()
207
+
208
+ # 6) Conditionally save the linked data
209
+ if is_usable:
210
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
211
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Cervical_Cancer/code/GSE114243.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Cervical_Cancer"
6
+ cohort = "GSE114243"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Cervical_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Cervical_Cancer/GSE114243"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Cervical_Cancer/GSE114243.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Cervical_Cancer/gene_data/GSE114243.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Cervical_Cancer/clinical_data/GSE114243.csv"
16
+ json_path = "./output/z2/preprocess/Cervical_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 data availability (likely transcriptome data; not miRNA-only or methylation-only)
42
+ is_gene_available = True
43
+
44
+ # 2) Variable availability
45
+ # From the sample characteristics, only tissue info (HEK293T cell line) is present; no human clinical variables.
46
+ trait_row = None
47
+ age_row = None
48
+ gender_row = None
49
+
50
+ # 2.2) Conversion functions (defined for completeness; not used since rows are None)
51
+ def _after_colon(value):
52
+ if value is None:
53
+ return ""
54
+ s = str(value)
55
+ parts = s.split(":", 1)
56
+ return parts[1].strip() if len(parts) == 2 else s.strip()
57
+
58
+ def convert_trait(value):
59
+ # Binary: 1 = Cervical cancer case; 0 = control/normal/non-cancer.
60
+ s = _after_colon(value).lower()
61
+ if s in {"", "na", "n/a", "none", "unknown"}:
62
+ return None
63
+ # Heuristics
64
+ positive_markers = ["cervical cancer", "cervix cancer", "cc", "case", "tumor", "tumour", "cancer", "malignant"]
65
+ negative_markers = ["normal", "control", "healthy", "benign", "adjacent normal", "non-cancer", "noncancer"]
66
+ if any(k in s for k in positive_markers):
67
+ return 1
68
+ if any(k in s for k in negative_markers):
69
+ return 0
70
+ return None
71
+
72
+ def convert_age(value):
73
+ # Continuous age in years
74
+ s = _after_colon(value).lower()
75
+ if s in {"", "na", "n/a", "none", "unknown"}:
76
+ return None
77
+ m = re.search(r'(-?\d+(?:\.\d+)?)', s)
78
+ if not m:
79
+ return None
80
+ try:
81
+ age = float(m.group(1))
82
+ except ValueError:
83
+ return None
84
+ if age < 0 or age > 120:
85
+ return None
86
+ return age
87
+
88
+ def convert_gender(value):
89
+ # Binary: female -> 0, male -> 1
90
+ s = _after_colon(value).lower()
91
+ if s in {"", "na", "n/a", "none", "unknown"}:
92
+ return None
93
+ female_tokens = {"f", "female", "woman", "women", "girl"}
94
+ male_tokens = {"m", "male", "man", "men", "boy"}
95
+ if s in female_tokens or any(tok in s for tok in female_tokens):
96
+ return 0
97
+ if s in male_tokens or any(tok in s for tok in male_tokens):
98
+ return 1
99
+ return None
100
+
101
+ # 3) Save metadata with initial filtering
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
+ # 4) Clinical feature extraction: skipped because trait_row is None (no clinical data available)
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
+ # The identifiers like 'A_23_P...' are Agilent microarray probe IDs, not human gene symbols.
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
+ # Identify columns for probe IDs and gene symbols based on annotation preview
134
+ probe_col = 'ID' # matches probe IDs like 'A_23_P100001' seen in gene_data index
135
+ gene_symbol_col = 'GENE_SYMBOL' # contains human gene symbols
136
+
137
+ # Build mapping dataframe
138
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
139
+
140
+ # Apply mapping to convert probe-level data to gene-level expression
141
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
142
+
143
+ # Step 7: Data Normalization and Linking
144
+ import os
145
+
146
+ # 1) Normalize gene symbols and save gene-level matrix
147
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
148
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
149
+ normalized_gene_data.to_csv(out_gene_data_file)
150
+
151
+ # 2-6) Proceed with linking and final validation only if clinical data exists (not the case for this cohort)
152
+ if ('selected_clinical_data' in locals()) and (locals().get('trait_row', None) is not None):
153
+ # Link clinical and genetic data
154
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
155
+
156
+ # Handle missing values
157
+ linked_data = handle_missing_values(linked_data, trait)
158
+
159
+ # Bias checking and potential removal of biased covariates
160
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
161
+
162
+ # Final validation and cohort info saving
163
+ is_usable = validate_and_save_cohort_info(
164
+ is_final=True,
165
+ cohort=cohort,
166
+ info_path=json_path,
167
+ is_gene_available=True,
168
+ is_trait_available=True,
169
+ is_biased=is_trait_biased,
170
+ df=unbiased_linked_data,
171
+ note="INFO: Clinical features available; data linked, missing handled, bias assessed."
172
+ )
173
+
174
+ # Save linked dataset only if usable
175
+ if is_usable:
176
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
177
+ unbiased_linked_data.to_csv(out_data_file)
178
+ else:
179
+ # No clinical trait available: skip final validation/linking; only gene matrix saved
180
+ print("INFO: No clinical trait available; linking and final validation skipped. Saved gene-level matrix only.")
output/preprocess/Cervical_Cancer/code/GSE131027.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Cervical_Cancer"
6
+ cohort = "GSE131027"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Cervical_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Cervical_Cancer/GSE131027"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Cervical_Cancer/GSE131027.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Cervical_Cancer/gene_data/GSE131027.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Cervical_Cancer/clinical_data/GSE131027.csv"
16
+ json_path = "./output/z2/preprocess/Cervical_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 availability
43
+ is_gene_available = True # Series design: investigation of expression features (not miRNA/methylation)
44
+
45
+ # 2) Variable availability and converters
46
+ # Trait and cancer types are in key 1. Age not available. Gender can be inferred from cancer type (key 1).
47
+ trait_row = 1
48
+ age_row = None
49
+ gender_row = 1
50
+
51
+ def _extract_value_after_colon(x):
52
+ if x is None:
53
+ return None
54
+ if not isinstance(x, str):
55
+ x = str(x)
56
+ parts = x.split(':')
57
+ val = parts[-1].strip() if parts else None
58
+ return val if val != '' else None
59
+
60
+ def convert_trait(x):
61
+ v = _extract_value_after_colon(x)
62
+ if v is None:
63
+ return None
64
+ v_low = v.lower()
65
+ # Binary: 1 = cervical cancer, 0 = other cancers
66
+ return 1 if 'cervical' in v_low else 0
67
+
68
+ def convert_age(x):
69
+ v = _extract_value_after_colon(x)
70
+ if v is None:
71
+ return None
72
+ m = re.search(r'(\d+(\.\d+)?)', v)
73
+ if not m:
74
+ return None
75
+ try:
76
+ age = float(m.group(1))
77
+ if 0 <= age <= 120:
78
+ return age
79
+ return None
80
+ except Exception:
81
+ return None
82
+
83
+ def convert_gender(x):
84
+ v = _extract_value_after_colon(x)
85
+ if v is None:
86
+ return None
87
+ v_low = v.lower()
88
+ # High-confidence sex-specific mappings based on cancer type
89
+ if 'prostate' in v_low:
90
+ return 1 # male
91
+ if ('ovarian' in v_low) or ('cervical' in v_low) or ('vulvovaginal' in v_low):
92
+ return 0 # female
93
+ # Other cancer types are not sex-specific -> unknown
94
+ return None
95
+
96
+ # 3) Initial filtering metadata
97
+ is_trait_available = trait_row is not None
98
+ _ = validate_and_save_cohort_info(
99
+ is_final=False,
100
+ cohort=cohort,
101
+ info_path=json_path,
102
+ is_gene_available=is_gene_available,
103
+ is_trait_available=is_trait_available
104
+ )
105
+
106
+ # 4) Clinical feature extraction (only if trait data available)
107
+ if trait_row is not None:
108
+ selected_clinical_df = geo_select_clinical_features(
109
+ clinical_df=clinical_data,
110
+ trait=trait,
111
+ trait_row=trait_row,
112
+ convert_trait=convert_trait,
113
+ age_row=age_row,
114
+ convert_age=None,
115
+ gender_row=gender_row,
116
+ convert_gender=convert_gender
117
+ )
118
+ preview = preview_df(selected_clinical_df)
119
+ print("Preview of selected clinical features:", preview)
120
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
121
+ selected_clinical_df.to_csv(out_clinical_data_file)
122
+
123
+ # Step 3: Gene Data Extraction
124
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
125
+ gene_data = get_genetic_data(matrix_file)
126
+
127
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
128
+ print(gene_data.index[:20])
129
+
130
+ # Step 4: Gene Identifier Review
131
+ # Affymetrix probe set IDs (e.g., 1007_s_at, 1053_at) are not gene symbols and require mapping.
132
+ requires_gene_mapping = True
133
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
134
+
135
+ # Step 5: Gene Annotation
136
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
137
+ gene_annotation = get_gene_annotation(soft_file)
138
+
139
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
140
+ print("Gene annotation preview:")
141
+ print(preview_df(gene_annotation))
142
+
143
+ # Step 6: Gene Identifier Mapping
144
+ # Identify the appropriate columns for probe IDs and gene symbols based on the annotation preview
145
+ probe_col = 'ID'
146
+ gene_symbol_col = 'Gene Symbol'
147
+
148
+ # 2) Build the mapping dataframe from annotation
149
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
150
+
151
+ # 3) Apply the mapping to convert probe-level data to gene-level data
152
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
153
+
154
+ # Step 7: Data Normalization and Linking
155
+ import os
156
+ import pandas as pd
157
+
158
+ # 1) Normalize gene symbols and save gene-level data
159
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
160
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
161
+ normalized_gene_data.to_csv(out_gene_data_file)
162
+
163
+ # 2) Ensure clinical features are loaded, then link clinical and genetic data
164
+ try:
165
+ selected_clinical_df
166
+ except NameError:
167
+ # Reload clinical data saved in Step 2
168
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
169
+
170
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
171
+
172
+ # 3) Handle missing values
173
+ linked_data = handle_missing_values(linked_data, trait)
174
+
175
+ # 4) Bias check and removal of biased demographic features
176
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
177
+
178
+ # 5) Final validation and save cohort info
179
+ is_gene_available_flag = normalized_gene_data.shape[0] > 0 and normalized_gene_data.shape[1] > 0
180
+ is_trait_available_flag = trait in selected_clinical_df.index
181
+
182
+ note = ("INFO: Gender inferred heuristically from sex-specific cancer types in clinical annotation "
183
+ "(female=ovarian/cervical/vulvovaginal -> 0; male=prostate -> 1). Other cancer types set to None and "
184
+ "imputed if needed. Age not available in this dataset.")
185
+
186
+ is_usable = validate_and_save_cohort_info(
187
+ is_final=True,
188
+ cohort=cohort,
189
+ info_path=json_path,
190
+ is_gene_available=is_gene_available_flag,
191
+ is_trait_available=is_trait_available_flag,
192
+ is_biased=is_trait_biased,
193
+ df=unbiased_linked_data,
194
+ note=note
195
+ )
196
+
197
+ # 6) Save linked data 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)
output/preprocess/Cervical_Cancer/code/GSE137034.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Cervical_Cancer"
6
+ cohort = "GSE137034"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Cervical_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Cervical_Cancer/GSE137034"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Cervical_Cancer/GSE137034.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Cervical_Cancer/gene_data/GSE137034.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Cervical_Cancer/clinical_data/GSE137034.csv"
16
+ json_path = "./output/z2/preprocess/Cervical_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: Dataset Analysis and Clinical Feature Extraction for GSE137034
40
+
41
+ # 1) Gene expression data availability
42
+ # Background indicates chromatin accessibility (ATAC-seq) in a SuperSeries; not gene expression suitable for our analysis.
43
+ is_gene_available = False
44
+
45
+ # 2) Variable availability and converters
46
+ # From the sample characteristics:
47
+ # {0: ['tissue: THP1 cells', 'tissue: Stimulated human CD4 T-cells'],
48
+ # 1: ['treatment: Cells cultured in full RPMI', 'treatment: Cells cultured in RPMI without arginine']}
49
+ # No trait (Cervical Cancer), age, or gender information available.
50
+ trait_row = None
51
+ age_row = None
52
+ gender_row = None
53
+
54
+ def _after_colon(value):
55
+ if value is None:
56
+ return None
57
+ s = str(value)
58
+ if ':' in s:
59
+ s = s.split(':', 1)[1]
60
+ s = s.strip()
61
+ return s if s else None
62
+
63
+ def convert_trait(value):
64
+ # Binary: 1 = cervical cancer case, 0 = non-cancer/controls.
65
+ v = _after_colon(value)
66
+ if v is None:
67
+ return None
68
+ vlow = v.lower()
69
+ # Heuristics for cervical cancer labels
70
+ if any(k in vlow for k in ['cervical', 'cervix']) and any(k in vlow for k in ['cancer', 'carcinoma', 'scc', 'adenocarcinoma', 'tumor', 'tumour']):
71
+ return 1
72
+ if any(k in vlow for k in ['normal', 'healthy', 'control', 'benign', 'non-cancer', 'noncancer']):
73
+ return 0
74
+ # Explicit case/control labels
75
+ if vlow in {'case', 'patient', 'tumor', 'tumour'}:
76
+ return 1
77
+ if vlow in {'control', 'healthy', 'normal'}:
78
+ return 0
79
+ return None
80
+
81
+ def convert_age(value):
82
+ # Continuous: extract a numeric age if present
83
+ v = _after_colon(value)
84
+ if v is None:
85
+ return None
86
+ import re
87
+ matches = re.findall(r'\d+\.?\d*', v)
88
+ if not matches:
89
+ return None
90
+ try:
91
+ age_val = float(matches[0])
92
+ # Filter unreasonable ages
93
+ if 0 < age_val < 120:
94
+ return age_val
95
+ except Exception:
96
+ pass
97
+ return None
98
+
99
+ def convert_gender(value):
100
+ # Binary: female=0, male=1
101
+ v = _after_colon(value)
102
+ if v is None:
103
+ return None
104
+ vlow = v.lower()
105
+ if vlow in {'female', 'f', 'woman', 'women', 'girl'}:
106
+ return 0
107
+ if vlow in {'male', 'm', 'man', 'men', 'boy'}:
108
+ return 1
109
+ return None
110
+
111
+ # 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
+ # 4) Clinical feature extraction (skip because trait_row is None)
122
+ # If at some point trait_row becomes available, the following scaffold shows how to proceed:
123
+ if trait_row is not None:
124
+ selected = 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_df(selected)
135
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
136
+ selected.to_csv(out_clinical_data_file, index=True)
output/preprocess/Cervical_Cancer/code/GSE138079.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Cervical_Cancer"
6
+ cohort = "GSE138079"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Cervical_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Cervical_Cancer/GSE138079"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Cervical_Cancer/GSE138079.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Cervical_Cancer/gene_data/GSE138079.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Cervical_Cancer/clinical_data/GSE138079.csv"
16
+ json_path = "./output/z2/preprocess/Cervical_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
+ # Decision rationale:
40
+ # - Gene expression: YES (Agilent mRNA microarray on human keratinocyte cell lines)
41
+ # - Trait (Cervical_Cancer): NOT available (in vitro HPV-transformed keratinocyte cell lines; no human case/control)
42
+ # - Age/Gender: NOT available (cell lines; no subject-level age/gender; any implied sex would be constant and unusable)
43
+
44
+ # Set availability flags and row indices
45
+ is_gene_available = True
46
+ trait_row = None
47
+ age_row = None
48
+ gender_row = None
49
+ is_trait_available = trait_row is not None
50
+
51
+ # Converters (defined for interface completeness; not used since trait_row is None)
52
+ def convert_trait(x):
53
+ if x is None:
54
+ return None
55
+ # extract value after colon if present
56
+ val = str(x)
57
+ if ':' in val:
58
+ val = val.split(':', 1)[1]
59
+ v = val.strip().lower()
60
+ if v in {'', 'na', 'n/a', 'none', 'unknown', 'missing'}:
61
+ return None
62
+ # Generic heuristic mapping: cancer/tumor/carcinoma -> 1; normal/control/healthy -> 0
63
+ if any(k in v for k in ['cancer', 'tumor', 'carcinoma', 'malignant', 'case']):
64
+ return 1
65
+ if any(k in v for k in ['normal', 'control', 'healthy', 'benign']):
66
+ return 0
67
+ # Not confidently mappable
68
+ return None
69
+
70
+ def convert_age(x):
71
+ if x is None:
72
+ return None
73
+ val = str(x)
74
+ if ':' in val:
75
+ val = val.split(':', 1)[1]
76
+ v = val.strip().lower()
77
+ if v in {'', 'na', 'n/a', 'none', 'unknown', 'missing'}:
78
+ return None
79
+ # Extract first numeric token as age (in years) if present
80
+ import re
81
+ m = re.search(r'(\d+(\.\d+)?)', v)
82
+ if not m:
83
+ return None
84
+ try:
85
+ return float(m.group(1))
86
+ except Exception:
87
+ return None
88
+
89
+ def convert_gender(x):
90
+ if x is None:
91
+ return None
92
+ val = str(x)
93
+ if ':' in val:
94
+ val = val.split(':', 1)[1]
95
+ v = val.strip().lower()
96
+ if v in {'', 'na', 'n/a', 'none', 'unknown', 'missing'}:
97
+ return None
98
+ # Map female->0, male->1
99
+ if any(k in v for k in ['female', 'f']):
100
+ return 0
101
+ if any(k in v for k in ['male', 'm']):
102
+ return 1
103
+ return None
104
+
105
+ # Save metadata (initial filtering)
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
+ # Since trait_row is None, skip clinical feature extraction.
output/preprocess/Cervical_Cancer/code/GSE138080.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Cervical_Cancer"
6
+ cohort = "GSE138080"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Cervical_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Cervical_Cancer/GSE138080"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Cervical_Cancer/GSE138080.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Cervical_Cancer/gene_data/GSE138080.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Cervical_Cancer/clinical_data/GSE138080.csv"
16
+ json_path = "./output/z2/preprocess/Cervical_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 # mRNA Agilent whole genome arrays -> gene expression available
44
+
45
+ # 2) Variable Availability and Data Type Conversion
46
+
47
+ # Data availability inferred from Sample Characteristics Dictionary:
48
+ # 0: cell type (normal, CIN2/3, carcinoma) -> use for trait
49
+ # 1: HPV status -> not our primary trait
50
+ trait_row = 0
51
+ age_row = None
52
+ gender_row = None
53
+
54
+ # 2.2 Conversion functions
55
+
56
+ def _extract_value_after_colon(x):
57
+ if x is None:
58
+ return None
59
+ try:
60
+ s = str(x).strip()
61
+ except Exception:
62
+ return None
63
+ if not s:
64
+ return None
65
+ parts = s.split(":")
66
+ val = parts[-1].strip() if len(parts) > 1 else s.strip()
67
+ return val or None
68
+
69
+ def convert_trait(x):
70
+ """
71
+ Binary: 1 = cervical cancer (carcinoma), 0 = normal; CIN2/3 -> None (exclude precancerous for Cervical_Cancer trait).
72
+ """
73
+ val = _extract_value_after_colon(x)
74
+ if val is None:
75
+ return None
76
+ v = val.lower()
77
+ if "carcinoma" in v or "squamous cell carcinoma" in v:
78
+ return 1
79
+ if "normal" in v:
80
+ return 0
81
+ # High-grade precancerous lesions (CIN2/3) are not cancer -> exclude
82
+ if "cin" in v or "intraepithelial" in v or "grade" in v:
83
+ return None
84
+ return None
85
+
86
+ def convert_age(x):
87
+ """
88
+ Continuous: extract numeric age if present. Not used here (no age available), but provided for completeness.
89
+ """
90
+ val = _extract_value_after_colon(x)
91
+ if val is None:
92
+ return None
93
+ m = re.search(r"[-+]?\d*\.?\d+", val)
94
+ if m:
95
+ try:
96
+ return float(m.group())
97
+ except Exception:
98
+ return None
99
+ return None
100
+
101
+ def convert_gender(x):
102
+ """
103
+ Binary: female -> 0, male -> 1.
104
+ """
105
+ val = _extract_value_after_colon(x)
106
+ if val is None:
107
+ return None
108
+ v = val.strip().lower()
109
+ if v in {"female", "f", "woman", "women"}:
110
+ return 0
111
+ if v in {"male", "m", "man", "men"}:
112
+ return 1
113
+ return None
114
+
115
+ # 3) Save Metadata (initial filtering)
116
+ is_trait_available = trait_row is not None
117
+ _ = validate_and_save_cohort_info(
118
+ is_final=False,
119
+ cohort=cohort,
120
+ info_path=json_path,
121
+ is_gene_available=is_gene_available,
122
+ is_trait_available=is_trait_available
123
+ )
124
+
125
+ # 4) Clinical Feature Extraction (only if trait_row is available)
126
+ if trait_row is not None:
127
+ selected_clinical_df = geo_select_clinical_features(
128
+ clinical_df=clinical_data,
129
+ trait=trait,
130
+ trait_row=trait_row,
131
+ convert_trait=convert_trait,
132
+ age_row=age_row,
133
+ convert_age=convert_age,
134
+ gender_row=gender_row,
135
+ convert_gender=convert_gender
136
+ )
137
+ clinical_preview = preview_df(selected_clinical_df)
138
+
139
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
140
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
141
+
142
+ # Step 3: Gene Data Extraction
143
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
144
+ gene_data = get_genetic_data(matrix_file)
145
+
146
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
147
+ print(gene_data.index[:20])
148
+
149
+ # Step 4: Gene Identifier Review
150
+ # Observed gene identifiers are numeric (e.g., '12', '14'), not human gene symbols; mapping is required.
151
+ requires_gene_mapping = True
152
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
153
+
154
+ # Step 5: Gene Annotation
155
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
156
+ gene_annotation = get_gene_annotation(soft_file)
157
+
158
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
159
+ print("Gene annotation preview:")
160
+ print(preview_df(gene_annotation))
161
+
162
+ # Step 6: Gene Identifier Mapping
163
+ # Decide identifier and gene symbol columns based on annotation preview
164
+ id_col = 'ID'
165
+ possible_symbol_cols = ['GENE_SYMBOL', 'GENE', 'SYMBOL', 'Gene Symbol', 'GENE_NAME']
166
+ gene_symbol_col = next((c for c in possible_symbol_cols if c in gene_annotation.columns), None)
167
+ if gene_symbol_col is None:
168
+ raise ValueError("No suitable gene symbol column found in gene_annotation.")
169
+
170
+ # Build mapping DataFrame (probe ID -> gene symbol)
171
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=id_col, gene_col=gene_symbol_col)
172
+
173
+ # Map probe-level data to gene-level data
174
+ # Use the probe-level expression DF from previous steps (gene_data) and overwrite with gene-mapped data
175
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
176
+
177
+ # Step 7: Data Normalization and Linking
178
+ import os
179
+
180
+ # 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.
181
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
182
+
183
+ # Ensure output directory exists and save normalized gene data
184
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
185
+ normalized_gene_data.to_csv(out_gene_data_file)
186
+
187
+ # Optional sanity check
188
+ print(f"Normalized gene data shape: {normalized_gene_data.shape}")
189
+
190
+ # 2. Link the clinical and genetic data with the 'geo_link_clinical_genetic_data' function from the library.
191
+ # Fix variable name to use 'selected_clinical_df' created in previous steps.
192
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
193
+
194
+ # Optional sanity check
195
+ print(f"Linked data shape (before missing handling): {linked_data.shape}")
196
+
197
+ # 3. Handle missing values in the linked data
198
+ linked_data = handle_missing_values(linked_data, trait)
199
+
200
+ # 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.
201
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
202
+
203
+ # 5. Conduct quality check and save the cohort information.
204
+ # Derive availability flags from data
205
+ is_gene_available_flag = (normalized_gene_data.shape[0] > 0 and normalized_gene_data.shape[1] > 0)
206
+ is_trait_available_flag = (trait in selected_clinical_df.index) and bool(selected_clinical_df.loc[trait].notna().any())
207
+
208
+ note = "INFO: Trait derived from cell type (normal vs carcinoma); CIN2/3 excluded from trait."
209
+ is_usable = validate_and_save_cohort_info(
210
+ is_final=True,
211
+ cohort=cohort,
212
+ info_path=json_path,
213
+ is_gene_available=is_gene_available_flag,
214
+ is_trait_available=is_trait_available_flag,
215
+ is_biased=is_trait_biased,
216
+ df=unbiased_linked_data,
217
+ note=note
218
+ )
219
+
220
+ # 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.
221
+ if is_usable:
222
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
223
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Cervical_Cancer/code/GSE146114.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Cervical_Cancer"
6
+ cohort = "GSE146114"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Cervical_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Cervical_Cancer/GSE146114"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Cervical_Cancer/GSE146114.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Cervical_Cancer/gene_data/GSE146114.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Cervical_Cancer/clinical_data/GSE146114.csv"
16
+ json_path = "./output/z2/preprocess/Cervical_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
+ # Background indicates Illumina WG-6 v3 / HT-12 v4 mRNA expression arrays.
44
+ is_gene_available = True
45
+
46
+ # 2) Variable Availability and Data Type Conversion
47
+
48
+ # Based on the sample characteristics:
49
+ # - Trait (Cervical_Cancer): All samples are cervical tumor patients (case-only). No variability -> not available.
50
+ # - Age: Not present.
51
+ # - Gender: Cervical cancer patients are female; gender not explicitly listed and effectively constant -> not available.
52
+ trait_row = None
53
+ age_row = None
54
+ gender_row = None
55
+
56
+ # Conversion functions (defined for interface consistency; may not be used due to unavailability)
57
+ def convert_trait(x):
58
+ # Map to binary case/control if ever needed:
59
+ # 1 = Cervical cancer case; 0 = control/normal.
60
+ if x is None:
61
+ return None
62
+ try:
63
+ val = str(x)
64
+ # Extract value after colon if present
65
+ if ':' in val:
66
+ val = val.split(':', 1)[1].strip()
67
+ low = val.lower()
68
+ if any(k in low for k in ['cervical', 'cervix', 'tumor', 'carcinoma']):
69
+ return 1
70
+ if any(k in low for k in ['normal', 'healthy', 'control', 'adjacent normal']):
71
+ return 0
72
+ return None
73
+ except Exception:
74
+ return None
75
+
76
+ def convert_age(x):
77
+ # Return age in years as float if a number is present; otherwise None
78
+ if x is None:
79
+ return None
80
+ try:
81
+ val = str(x)
82
+ if ':' in val:
83
+ val = val.split(':', 1)[1].strip()
84
+ m = re.search(r'(\d+(?:\.\d+)?)', val)
85
+ return float(m.group(1)) if m else None
86
+ except Exception:
87
+ return None
88
+
89
+ def convert_gender(x):
90
+ # Female -> 0, Male -> 1
91
+ if x is None:
92
+ return None
93
+ try:
94
+ val = str(x)
95
+ if ':' in val:
96
+ val = val.split(':', 1)[1].strip()
97
+ low = val.lower()
98
+ if low in ['f', 'female', 'woman', 'women']:
99
+ return 0
100
+ if low in ['m', 'male', 'man', 'men']:
101
+ return 1
102
+ return None
103
+ except Exception:
104
+ return None
105
+
106
+ # 3) Save Metadata (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 (skip because trait_row is None)
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
+ clinical_preview = preview_df(selected_clinical_df)
129
+ print("Clinical preview:", clinical_preview)
130
+ # Save clinical data
131
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
output/preprocess/Cervical_Cancer/code/GSE163114.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Cervical_Cancer"
6
+ cohort = "GSE163114"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Cervical_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Cervical_Cancer/GSE163114"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Cervical_Cancer/GSE163114.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Cervical_Cancer/gene_data/GSE163114.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Cervical_Cancer/clinical_data/GSE163114.csv"
16
+ json_path = "./output/z2/preprocess/Cervical_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
+ # 1) Gene expression data availability
40
+ is_gene_available = True # Cell-line expression study; not miRNA-only or methylation-only per context.
41
+
42
+ # 2) Variable availability and converters
43
+ # Sample characteristics show only:
44
+ # 0: ['cell line: HeLa'] -> constant; not usable for our 'Cervical_Cancer' trait association
45
+ # 1: ['lentivirus: shRNA control', 'lentivirus: shRNA Ki-67'] -> experimental perturbation, not the trait of interest
46
+ trait_row = None
47
+ age_row = None
48
+ gender_row = None
49
+
50
+ def _after_colon(val: str) -> str:
51
+ if val is None:
52
+ return ''
53
+ s = str(val)
54
+ if ':' in s:
55
+ s = s.split(':', 1)[1]
56
+ return s.strip().strip('"').strip()
57
+
58
+ def convert_trait(x):
59
+ # Binary: Cervical_Cancer present (1) vs not (0); heuristic on strings if ever needed.
60
+ v = _after_colon(x).lower()
61
+ if not v:
62
+ return None
63
+ # Heuristic: cell line derived from cervical cancer
64
+ if any(k in v for k in ['hela', 'cervical']):
65
+ return 1
66
+ if any(k in v for k in ['normal', 'control tissue', 'healthy']):
67
+ return 0
68
+ # Lentiviral labels are perturbations, not trait; return None to avoid misuse.
69
+ if 'lentivirus' in v or 'shrna' in v:
70
+ return None
71
+ return None
72
+
73
+ def convert_age(x):
74
+ # Continuous age in years
75
+ v = _after_colon(x)
76
+ if not v:
77
+ return None
78
+ # Extract first numeric token (e.g., "45 years", "45.0", "Age: 45")
79
+ import re
80
+ m = re.search(r'[-+]?\d*\.?\d+', v)
81
+ if not m:
82
+ return None
83
+ try:
84
+ age_val = float(m.group(0))
85
+ except Exception:
86
+ return None
87
+ # Filter unrealistic ages
88
+ if age_val <= 0 or age_val > 120:
89
+ return None
90
+ return age_val
91
+
92
+ def convert_gender(x):
93
+ # Binary: female -> 0, male -> 1
94
+ v = _after_colon(x).lower()
95
+ if not v:
96
+ return None
97
+ if v in ['f', 'female', 'woman', 'women']:
98
+ return 0
99
+ if v in ['m', 'male', 'man', 'men']:
100
+ return 1
101
+ return None
102
+
103
+ # 3) Save metadata (initial filtering)
104
+ is_trait_available = trait_row is not None
105
+ _ = validate_and_save_cohort_info(
106
+ is_final=False,
107
+ cohort=cohort,
108
+ info_path=json_path,
109
+ is_gene_available=is_gene_available,
110
+ is_trait_available=is_trait_available
111
+ )
112
+
113
+ # 4) Clinical feature extraction (skip because trait_row is None)
114
+ # If trait_row becomes available in future steps, enable the following:
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 if age_row is not None else None,
123
+ gender_row=gender_row,
124
+ convert_gender=convert_gender if gender_row is not None else None
125
+ )
126
+ _ = preview_df(selected_clinical_df)
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)
output/preprocess/Cervical_Cancer/code/GSE63678.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Cervical_Cancer"
6
+ cohort = "GSE63678"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Cervical_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Cervical_Cancer/GSE63678"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Cervical_Cancer/GSE63678.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Cervical_Cancer/gene_data/GSE63678.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Cervical_Cancer/clinical_data/GSE63678.csv"
16
+ json_path = "./output/z2/preprocess/Cervical_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 data availability
44
+ # Affymetrix HG133A_2.0 microarray indicates mRNA gene expression data.
45
+ is_gene_available = True
46
+
47
+ # 2) Variable availability and conversion functions
48
+
49
+ # Keys observed:
50
+ # 0: tissue (vulvar/endometrium/cervix)
51
+ # 1: disease state (carcinoma/normal)
52
+
53
+ # Trait: Cervical_Cancer inferred from disease state within cervix tissue.
54
+ trait_row = 1 # 'disease state'
55
+ age_row = None # not available
56
+ gender_row = None # not available
57
+
58
+ def _extract_value(x):
59
+ if x is None:
60
+ return None
61
+ s = str(x)
62
+ # Take the part after the first colon if present
63
+ if ':' in s:
64
+ s = s.split(':', 1)[1]
65
+ return s.strip().lower()
66
+
67
+ def convert_trait(x):
68
+ v = _extract_value(x)
69
+ if v is None or v == '':
70
+ return None
71
+ # Map disease state to binary: carcinoma/tumor/cancer/malignant -> 1, normal/healthy/control/benign -> 0
72
+ if any(k in v for k in ['carcinoma', 'cancer', 'tumor', 'tumour', 'malignan', 'neoplas']):
73
+ return 1
74
+ if any(k in v for k in ['normal', 'healthy', 'control', 'benign']):
75
+ return 0
76
+ return None
77
+
78
+ def convert_age(x):
79
+ v = _extract_value(x)
80
+ if not v:
81
+ return None
82
+ # Extract a number possibly followed by units
83
+ m = re.search(r'(\d+(\.\d+)?)', v)
84
+ if m:
85
+ try:
86
+ return float(m.group(1))
87
+ except Exception:
88
+ return None
89
+ return None
90
+
91
+ def convert_gender(x):
92
+ v = _extract_value(x)
93
+ if not v:
94
+ return None
95
+ if 'female' in v or v == 'f':
96
+ return 0
97
+ if 'male' in v or v == 'm':
98
+ return 1
99
+ return None
100
+
101
+ # 3) Save metadata (initial filtering)
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
+ # 4) Clinical feature extraction (only if trait data is available)
112
+ if trait_row is not None:
113
+ # Subset to cervix tissue to align with the Cervical_Cancer trait definition
114
+ clinical_df = clinical_data.copy()
115
+ tissue_series = clinical_df.iloc[0, :].astype(str).str.lower()
116
+ cervix_mask = tissue_series.str.contains('cervix', na=False)
117
+
118
+ clinical_df_cervix = clinical_df.loc[:, cervix_mask]
119
+
120
+ selected_clinical_df = geo_select_clinical_features(
121
+ clinical_df=clinical_df_cervix,
122
+ trait=trait,
123
+ trait_row=trait_row,
124
+ convert_trait=convert_trait,
125
+ age_row=age_row,
126
+ convert_age=convert_age,
127
+ gender_row=gender_row,
128
+ convert_gender=convert_gender
129
+ )
130
+
131
+ preview = preview_df(selected_clinical_df, n=5)
132
+ print(preview)
133
+
134
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
135
+ selected_clinical_df.to_csv(out_clinical_data_file)
136
+
137
+ # Step 3: Gene Data Extraction
138
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
139
+ gene_data = get_genetic_data(matrix_file)
140
+
141
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
142
+ print(gene_data.index[:20])
143
+
144
+ # Step 4: Gene Identifier Review
145
+ import os
146
+ import re
147
+
148
+ requires_gene_mapping = True # default to conservative mapping requirement
149
+
150
+ def detect_requires_mapping(index_iterable, sample_size=2000):
151
+ ids = [str(x) for x in list(index_iterable)[:sample_size]]
152
+ if not ids:
153
+ return False
154
+
155
+ def is_affy(x):
156
+ xl = x.lower()
157
+ return xl.endswith('_at') or xl.endswith('_st') or xl.startswith('affx-')
158
+
159
+ def is_ensembl(x):
160
+ return bool(re.match(r'^ENS[A-Z]*G\d+', x))
161
+
162
+ def is_refseq(x):
163
+ return bool(re.match(r'^(NM|NR|XM|XR)_\d+', x))
164
+
165
+ def is_illumina(x):
166
+ return bool(re.match(r'^ILMN_\d+', x))
167
+
168
+ def is_agilent(x):
169
+ return bool(re.match(r'^A_\d+_P\d+', x))
170
+
171
+ def is_ucsc(x):
172
+ return bool(re.match(r'^uc[0-9a-z]+\.', x))
173
+
174
+ def is_symbol_like(x):
175
+ # Heuristic: alphanumerics with optional - or .; exclude clear non-symbol patterns
176
+ if any(sep in x for sep in [':', '/', '\\', '|']):
177
+ return False
178
+ if is_affy(x) or is_ensembl(x) or is_refseq(x) or is_illumina(x) or is_agilent(x) or is_ucsc(x):
179
+ return False
180
+ return bool(re.match(r'^[A-Za-z0-9\-\.\(\)]+$', x)) and any(c.isalpha() for c in x)
181
+
182
+ n = len(ids)
183
+ counts = {
184
+ 'affy': sum(is_affy(x) for x in ids),
185
+ 'ensembl': sum(is_ensembl(x) for x in ids),
186
+ 'refseq': sum(is_refseq(x) for x in ids),
187
+ 'illumina': sum(is_illumina(x) for x in ids),
188
+ 'agilent': sum(is_agilent(x) for x in ids),
189
+ 'ucsc': sum(is_ucsc(x) for x in ids),
190
+ 'symbol_like': sum(is_symbol_like(x) for x in ids),
191
+ }
192
+ non_symbol_total = counts['affy'] + counts['ensembl'] + counts['refseq'] + counts['illumina'] + counts['agilent'] + counts['ucsc']
193
+ # Require mapping if majority are non-symbol identifiers
194
+ return (non_symbol_total / max(n, 1)) >= 0.5
195
+
196
+ try:
197
+ if os.path.exists(out_gene_data_file):
198
+ import pandas as pd # safe import if not already present
199
+ gene_df = pd.read_csv(out_gene_data_file, index_col=0)
200
+ requires_gene_mapping = detect_requires_mapping(gene_df.index)
201
+ else:
202
+ # Fallback for known Affymetrix-like probe IDs observed in this cohort/platform
203
+ requires_gene_mapping = True
204
+ except Exception:
205
+ # On any unexpected issue, default to requiring mapping
206
+ requires_gene_mapping = True
207
+
208
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
209
+
210
+ # Step 5: Gene Annotation
211
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
212
+ gene_annotation = get_gene_annotation(soft_file)
213
+
214
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
215
+ print("Gene annotation preview:")
216
+ print(preview_df(gene_annotation))
217
+
218
+ # Step 6: Gene Identifier Mapping
219
+ # Identify the appropriate columns for probe IDs and gene symbols based on the annotation preview
220
+ prob_col = 'ID'
221
+ gene_col = 'Gene Symbol'
222
+
223
+ # 2) Build the probe-to-gene mapping dataframe
224
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=prob_col, gene_col=gene_col)
225
+
226
+ # 3) Apply mapping to convert probe-level data to gene-level expression
227
+ # Preserve original probe-level data
228
+ probe_level_data = gene_data
229
+ gene_data = apply_gene_mapping(probe_level_data, mapping_df)
230
+
231
+ # Step 7: Data Normalization and Linking
232
+ import os
233
+ import pandas as pd
234
+
235
+ # 1. Normalize gene symbols and save normalized gene data
236
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
237
+
238
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
239
+ normalized_gene_data.to_csv(out_gene_data_file)
240
+
241
+ # 2. Link clinical and genetic data
242
+ # Ensure clinical features are available in the current scope; otherwise, load from file
243
+ try:
244
+ selected_clinical_df
245
+ except NameError:
246
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
247
+
248
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
249
+
250
+ # 3. Handle missing values
251
+ linked_data = handle_missing_values(linked_data, trait)
252
+
253
+ # 4. Judge bias and remove biased covariates
254
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
255
+
256
+ # 5. Final validation and save cohort metadata
257
+ is_gene_available_flag = (normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0)
258
+ is_trait_available_flag = (trait in linked_data.columns)
259
+
260
+ note = "INFO: Filtered to cervix tissue only; Affymetrix probes mapped via SOFT Gene Symbol; gene symbols normalized with NCBI synonyms."
261
+ is_usable = validate_and_save_cohort_info(
262
+ is_final=True,
263
+ cohort=cohort,
264
+ info_path=json_path,
265
+ is_gene_available=is_gene_available_flag,
266
+ is_trait_available=is_trait_available_flag,
267
+ is_biased=is_trait_biased,
268
+ df=unbiased_linked_data,
269
+ note=note
270
+ )
271
+
272
+ # 6. Save linked data if usable
273
+ if is_usable:
274
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
275
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Cervical_Cancer/code/GSE75132.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Cervical_Cancer"
6
+ cohort = "GSE75132"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Cervical_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Cervical_Cancer/GSE75132"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Cervical_Cancer/GSE75132.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Cervical_Cancer/gene_data/GSE75132.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Cervical_Cancer/clinical_data/GSE75132.csv"
16
+ json_path = "./output/z2/preprocess/Cervical_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 data availability
44
+ # Based on the series summary, this is an mRNA microarray dataset (gene expression).
45
+ is_gene_available = True
46
+
47
+ # 2) Variable availability and converters
48
+
49
+ # From Sample Characteristics:
50
+ # 0: 'tissue: cervix' -> constant, not useful.
51
+ # 1: 'category (0 = normal, 1 = hpv without progression, 2 = hpv with progression)' -> relates to HPV progression, not the Cervical_Cancer trait.
52
+ # 2: 'hpv status: ...' -> HPV status, not the Cervical_Cancer trait.
53
+ # 3: 'disease state: none/severe dysplasia/CIS/moderate dysplasia/cancer' -> usable to derive Cervical_Cancer.
54
+ trait_row = 3
55
+ age_row = None
56
+ gender_row = None
57
+
58
+ # Converters
59
+ def _after_colon(x: str) -> str:
60
+ if x is None:
61
+ return ''
62
+ s = str(x)
63
+ if ':' in s:
64
+ s = s.split(':', 1)[1]
65
+ return s.strip().strip('"').strip()
66
+
67
+ def convert_trait(x):
68
+ v = _after_colon(x).lower()
69
+ if v in ['', 'na', 'n/a', 'nan', 'unknown']:
70
+ return None
71
+ # Binary trait: Cervical cancer present (1) vs not (0)
72
+ # Map explicit cancer to 1; dysplasia, CIS, none to 0
73
+ if v in ['cancer', 'cervical cancer']:
74
+ return 1
75
+ if v in ['none', 'normal', 'cis', 'carcinoma in situ', 'moderate dysplasia', 'severe dysplasia']:
76
+ return 0
77
+ if ('dysplasia' in v) or ('cin' in v):
78
+ return 0
79
+ return None
80
+
81
+ def convert_age(x):
82
+ v = _after_colon(x).lower()
83
+ if v in ['', 'na', 'n/a', 'nan', 'unknown']:
84
+ return None
85
+ m = re.search(r'[-+]?\d*\.?\d+', v)
86
+ return float(m.group()) if m else None
87
+
88
+ def convert_gender(x):
89
+ v = _after_colon(x).lower()
90
+ if v in ['', 'na', 'n/a', 'nan', 'unknown']:
91
+ return None
92
+ if v in ['f', 'female', 'woman', 'women']:
93
+ return 0
94
+ if v in ['m', 'male', 'man', 'men']:
95
+ return 1
96
+ return None
97
+
98
+ # 3) Save metadata (initial filtering)
99
+ is_trait_available = trait_row is not None
100
+ _ = validate_and_save_cohort_info(
101
+ is_final=False,
102
+ cohort=cohort,
103
+ info_path=json_path,
104
+ is_gene_available=is_gene_available,
105
+ is_trait_available=is_trait_available
106
+ )
107
+
108
+ # 4) Clinical feature extraction (only if clinical data available)
109
+ if trait_row is not None:
110
+ selected_clinical_df = geo_select_clinical_features(
111
+ clinical_df=clinical_data,
112
+ trait=trait,
113
+ trait_row=trait_row,
114
+ convert_trait=convert_trait,
115
+ age_row=age_row,
116
+ convert_age=convert_age if age_row is not None else None,
117
+ gender_row=gender_row,
118
+ convert_gender=convert_gender if gender_row is not None else None
119
+ )
120
+ clinical_preview = preview_df(selected_clinical_df)
121
+ print("Clinical feature 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)
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
+ # 1. Identify the columns for probe IDs and gene symbols in the annotation dataframe
146
+ probe_col = 'ID'
147
+ gene_symbol_col = 'Gene Symbol'
148
+
149
+ # 2. Create the mapping dataframe from annotation
150
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
151
+
152
+ # 3. Apply the mapping to convert probe-level data to gene-level expression
153
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
154
+
155
+ # Step 7: Data Normalization and Linking
156
+ import os
157
+
158
+ # 1. Normalize the obtained gene data and save
159
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
160
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
161
+ normalized_gene_data.to_csv(out_gene_data_file)
162
+
163
+ # 2. Link the clinical and genetic data
164
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
165
+
166
+ # 3. Handle missing values in the linked data
167
+ linked_data = handle_missing_values(linked_data, trait)
168
+
169
+ # 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.
170
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
171
+
172
+ # 5. Conduct quality check and save the cohort information.
173
+ is_usable = validate_and_save_cohort_info(
174
+ is_final=True,
175
+ cohort=cohort,
176
+ info_path=json_path,
177
+ is_gene_available=True,
178
+ is_trait_available=True,
179
+ is_biased=is_trait_biased,
180
+ df=unbiased_linked_data
181
+ )
182
+
183
+ # 6. If the linked data is usable, save it
184
+ if is_usable:
185
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
186
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Cervical_Cancer/code/TCGA.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Cervical_Cancer"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z2/preprocess/Cervical_Cancer/TCGA.csv"
12
+ out_gene_data_file = "./output/z2/preprocess/Cervical_Cancer/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z2/preprocess/Cervical_Cancer/clinical_data/TCGA.csv"
14
+ json_path = "./output/z2/preprocess/Cervical_Cancer/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import re
20
+ import pandas as pd
21
+
22
+ # 1) Select the most relevant TCGA cohort directory for the trait
23
+ all_entries = os.listdir(tcga_root_dir)
24
+ subdirs = [d for d in all_entries if os.path.isdir(os.path.join(tcga_root_dir, d))]
25
+
26
+ # Prefer names containing "cervic" or "cesc"
27
+ pattern = re.compile(r'(cervic|cesc)', re.IGNORECASE)
28
+ matches = [d for d in subdirs if pattern.search(d)]
29
+
30
+ selected_cohort_dir = None
31
+ if matches:
32
+ # Prefer the most specific match containing "cervical" first, else pick the first match
33
+ cervical_matches = [d for d in matches if re.search(r'cervical', d, re.IGNORECASE)]
34
+ selected = cervical_matches[0] if cervical_matches else matches[0]
35
+ selected_cohort_dir = os.path.join(tcga_root_dir, selected)
36
+
37
+ if selected_cohort_dir is None:
38
+ # No suitable directory found; record and skip
39
+ validate_and_save_cohort_info(
40
+ is_final=False,
41
+ cohort="TCGA",
42
+ info_path=json_path,
43
+ is_gene_available=False,
44
+ is_trait_available=False
45
+ )
46
+ tcga_skip_trait = True
47
+ else:
48
+ tcga_skip_trait = False
49
+
50
+ # 2) Identify clinical and genetic file paths
51
+ clinical_file_path = None
52
+ genetic_file_path = None
53
+
54
+ if not tcga_skip_trait:
55
+ try:
56
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(selected_cohort_dir)
57
+ except Exception:
58
+ # Fallback manual search if helper fails
59
+ files = os.listdir(selected_cohort_dir)
60
+ clinical_candidates = [f for f in files if 'clinicalmatrix' in f.lower()]
61
+ genetic_candidates = [f for f in files if 'pancan' in f.lower()]
62
+ if clinical_candidates and genetic_candidates:
63
+ clinical_file_path = os.path.join(selected_cohort_dir, clinical_candidates[0])
64
+ genetic_file_path = os.path.join(selected_cohort_dir, genetic_candidates[0])
65
+ else:
66
+ validate_and_save_cohort_info(
67
+ is_final=False,
68
+ cohort="TCGA",
69
+ info_path=json_path,
70
+ is_gene_available=bool(genetic_candidates),
71
+ is_trait_available=bool(clinical_candidates)
72
+ )
73
+ tcga_skip_trait = True
74
+
75
+ # 3) Load both files as DataFrames
76
+ tcga_clinical_df = None
77
+ tcga_genetic_df = None
78
+
79
+ if not tcga_skip_trait:
80
+ tcga_clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False)
81
+ tcga_genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False)
82
+
83
+ # 4) Print the column names of the clinical data
84
+ print(list(tcga_clinical_df.columns))
85
+
86
+ # Step 2: Find Candidate Demographic Features
87
+ import os
88
+ import re
89
+ import pandas as pd
90
+
91
+ # The list of column names from the previous step
92
+ previous_columns = ['_INTEGRATION', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'additional_pharmaceutical_therapy', 'additional_radiation_therapy', 'additional_treatment_completion_success_outcome', 'adjuvant_rad_therapy_prior_admin', 'age_at_initial_pathologic_diagnosis', 'age_began_smoking_in_years', 'agent_total_dose_count', 'assessment_timepoint_category', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'birth_control_pill_history_usage_category', 'brachytherapy_administered_status', 'brachytherapy_first_reference_point_administered_total_dose', 'brachytherapy_method_other_specify_text', 'brachytherapy_method_type', 'cervical_carcinoma_corpus_uteri_involvement_indicator', 'cervical_carcinoma_pelvic_extension_text', 'cervical_neoplasm_pathologic_margin_involved_text', 'cervical_neoplasm_pathologic_margin_involved_type', 'chemotherapy_negation_radiation_therapy_concurrent_adminstrd_txt', 'chemotherapy_negation_radiation_therapy_concurrnt_nt_dmnstrd_rsn', 'chemotherapy_regimen_type', 'clinical_stage', 'concurrent_chemotherapy_dose', 'days_to_birth', 'days_to_brachytherapy_begin_occurrence', 'days_to_brachytherapy_end_occurrence', 'days_to_chemotherapy_end', 'days_to_chemotherapy_start', 'days_to_collection', 'days_to_death', 'days_to_diagnostic_computed_tomography_performed', 'days_to_diagnostic_mri_performed', 'days_to_fdg_or_ct_pet_performed', 'days_to_initial_pathologic_diagnosis', 'days_to_last_followup', 'days_to_new_tumor_event_additional_surgery_procedure', 'days_to_new_tumor_event_after_initial_treatment', 'days_to_performance_status_assessment', 'days_to_radiation_therapy_end', 'days_to_radiation_therapy_start', 'death_cause_text', 'diagnostic_ct_result_outcome', 'diagnostic_mri_result_outcome', 'dose_frequency_text', 'eastern_cancer_oncology_group', 'ectopic_pregnancy_count', 'external_beam_radiation_therapy_administered_status', 'external_beam_radiation_therapy_administrd_prrtc_rgn_lymph_nd_ds', 'fdg_or_ct_pet_performed_outcome', 'female_breast_feeding_or_pregnancy_status_indicator', 'followup_case_report_form_submission_reason', 'form_completion_date', 'gender', 'height', 'histological_type', 'history_of_neoadjuvant_treatment', 'human_papillomavirus_laboratory_procedure_performed_name', 'human_papillomavirus_laboratory_procedure_performed_text', 'human_papillomavirus_other_type_text', 'human_papillomavirus_type', 'hysterectomy_performed_text', 'hysterectomy_performed_type', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'init_pathology_dx_method_other', 'initial_pathologic_diagnosis_method', 'initial_weight', 'is_ffpe', 'keratinizing_squamous_cell_carcinoma_present_indicator', 'lost_follow_up', 'lymph_node_examined_count', 'lymph_node_location_positive_pathology_name', 'lymph_node_location_positive_pathology_text', 'lymphovascular_invasion_indicator', 'menopause_status', 'neoplasm_histologic_grade', 'new_neoplasm_event_occurrence_anatomic_site', 'new_neoplasm_event_post_initial_therapy_diagnosis_method_text', 'new_neoplasm_event_post_initial_therapy_diagnosis_method_type', 'new_neoplasm_event_type', 'new_neoplasm_occurrence_anatomic_site_text', 'new_tumor_event_additional_surgery_procedure', 'new_tumor_event_after_initial_treatment', 'number_of_lymphnodes_positive_by_he', 'number_of_lymphnodes_positive_by_ihc', 'number_of_successful_pregnancies_which_resultd_n_t_lst_1_lv_brth', 'number_pack_years_smoked', 'oct_embedded', 'oligonucleotide_primer_pair_laboratory_procedure_performed_name', 'other_chemotherapy_agent_administration_specify', 'other_dx', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathology_report_file_name', 'patient_death_reason', 'patient_history_immune_system_and_related_disorders_name', 'patient_history_immune_system_and_related_disorders_text', 'patient_id', 'patient_pregnancy_spontaneous_abortion_count', 'patient_pregnancy_therapeutic_abortion_count', 'performance_status_scale_timing', 'person_neoplasm_cancer_status', 'postoperative_rx_tx', 'pregnancy_stillbirth_count', 'primary_lymph_node_presentation_assessment', 'primary_therapy_outcome_success', 'radiation_therapy', 'radiation_therapy_not_administered_reason', 'radiation_therapy_not_administered_specify', 'radiation_type_notes', 'residual_disease_post_new_tumor_event_margin_status', 'rt_administered_type', 'rt_pelvis_administered_total_dose', 'sample_type', 'sample_type_id', 'standardized_uptake_value_cervix_uteri_assessment_measurement', 'stopped_smoking_year', 'system_version', 'targeted_molecular_therapy', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tobacco_smoking_history', 'total_number_of_pregnancies', 'tumor_response_cdus_type', 'tumor_tissue_site', 'vial_number', 'vital_status', 'weight', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_CESC_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_CESC_miRNA_HiSeq', '_GENOMIC_ID_TCGA_CESC_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_data/public/TCGA/CESC/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_CESC_PDMRNAseq', '_GENOMIC_ID_TCGA_CESC_RPPA', '_GENOMIC_ID_TCGA_CESC_hMethyl450', '_GENOMIC_ID_TCGA_CESC_mutation_bcgsc_gene', '_GENOMIC_ID_TCGA_CESC_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_CESC_mutation', '_GENOMIC_ID_TCGA_CESC_mutation_broad_gene', '_GENOMIC_ID_TCGA_CESC_mutation_ucsc_maf_gene', '_GENOMIC_ID_TCGA_CESC_mutation_curated_wustl_gene', '_GENOMIC_ID_TCGA_CESC_exp_HiSeqV2', '_GENOMIC_ID_TCGA_CESC_gistic2', '_GENOMIC_ID_TCGA_CESC_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_CESC_gistic2thd']
93
+
94
+ # Refined patterns for age and gender
95
+ age_pattern = re.compile(r'(^|[_\W])age([_\W]|$)')
96
+ birth_pattern = re.compile(r'(^|[_\W])(days_to_birth|year_of_birth|date_of_birth|birth_year)([_\W]|$)')
97
+ gender_pattern = re.compile(r'(^|[_\W])gender([_\W]|$)|(^|[_\W])sex([_\W]|$)')
98
+
99
+ candidate_age_cols = []
100
+ candidate_gender_cols = []
101
+
102
+ for col in previous_columns:
103
+ low = col.lower()
104
+ if (age_pattern.search(low) or birth_pattern.search(low)) and ('birth_control' not in low and 'stillbirth' not in low):
105
+ candidate_age_cols.append(col)
106
+ if gender_pattern.search(low):
107
+ candidate_gender_cols.append(col)
108
+
109
+ # Print the required lists in the specified format
110
+ print(f"candidate_age_cols = {candidate_age_cols}")
111
+ print(f"candidate_gender_cols = {candidate_gender_cols}")
112
+
113
+ # Load clinical data and preview candidate columns if available
114
+ clinical_df = None
115
+ try:
116
+ cohort_dir = None
117
+ for entry in os.scandir(tcga_root_dir):
118
+ if entry.is_dir() and 'CESC' in entry.name.upper():
119
+ cohort_dir = entry.path
120
+ break
121
+ if cohort_dir is None:
122
+ for root, dirs, _ in os.walk(tcga_root_dir):
123
+ for d in dirs:
124
+ if 'CESC' in d.upper():
125
+ cohort_dir = os.path.join(root, d)
126
+ break
127
+ if cohort_dir is not None:
128
+ break
129
+
130
+ if cohort_dir is not None:
131
+ clinical_file_path, _ = tcga_get_relevant_filepaths(cohort_dir)
132
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, dtype=str)
133
+ except Exception:
134
+ clinical_df = None
135
+
136
+ # Extract and preview
137
+ age_preview = {}
138
+ gender_preview = {}
139
+
140
+ if isinstance(clinical_df, pd.DataFrame):
141
+ age_cols_existing = [c for c in candidate_age_cols if c in clinical_df.columns]
142
+ gender_cols_existing = [c for c in candidate_gender_cols if c in clinical_df.columns]
143
+
144
+ if age_cols_existing:
145
+ age_preview = preview_df(clinical_df[age_cols_existing])
146
+ if gender_cols_existing:
147
+ gender_preview = preview_df(clinical_df[gender_cols_existing])
148
+
149
+ print("age_preview =", age_preview)
150
+ print("gender_preview =", gender_preview)
151
+
152
+ # Step 3: Select Demographic Features
153
+ # Select columns based on preview and typical TCGA conventions
154
+ age_col = 'age_at_initial_pathologic_diagnosis' if 'age_at_initial_pathologic_diagnosis' in candidate_age_cols else None
155
+ gender_col = 'gender' if 'gender' in candidate_gender_cols else None
156
+
157
+ # Explicitly print chosen columns and their previews
158
+ print("Selected age_col:", age_col)
159
+ print("Preview of selected age_col:", age_preview.get(age_col) if age_col else None)
160
+
161
+ print("Selected gender_col:", gender_col)
162
+ print("Preview of selected gender_col:", gender_preview.get(gender_col) if gender_col else None)
163
+
164
+ # Step 4: Feature Engineering and Validation
165
+ import os
166
+ import pandas as pd
167
+
168
+ # 1) Extract and standardize clinical features (trait, Age, Gender)
169
+ selected_clinical_df = tcga_select_clinical_features(
170
+ clinical_df=tcga_clinical_df,
171
+ trait=trait,
172
+ age_col=age_col,
173
+ gender_col=gender_col
174
+ )
175
+
176
+ # 2) Normalize gene symbols and save normalized gene data
177
+ def _looks_like_sample_ids(idx):
178
+ try:
179
+ return any(str(i).startswith('TCGA-') for i in list(idx)[:10])
180
+ except Exception:
181
+ return any(str(i).startswith('TCGA-') for i in idx)
182
+
183
+ gene_df = tcga_genetic_df
184
+ # Ensure genes are in index for normalization
185
+ if _looks_like_sample_ids(gene_df.index):
186
+ gene_df = gene_df.T
187
+
188
+ normalized_gene_df = normalize_gene_symbols_in_index(gene_df)
189
+
190
+ # Optional post-check to ensure samples are columns
191
+ if not _looks_like_sample_ids(normalized_gene_df.columns) and _looks_like_sample_ids(normalized_gene_df.index):
192
+ normalized_gene_df = normalized_gene_df.T
193
+
194
+ # Save normalized gene data
195
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
196
+ normalized_gene_df.to_csv(out_gene_data_file)
197
+
198
+ # 3) Link clinical and genetic data on intersecting sample IDs
199
+ common_samples = selected_clinical_df.index.intersection(normalized_gene_df.columns)
200
+ linked_clinical = selected_clinical_df.loc[common_samples]
201
+ linked_gene = normalized_gene_df[common_samples].T # samples x genes
202
+ linked_data = pd.concat([linked_clinical, linked_gene], axis=1)
203
+
204
+ # 4) Handle missing values
205
+ linked_data = handle_missing_values(linked_data, trait_col=trait)
206
+
207
+ # 5) Determine severe bias; remove biased demographics
208
+ trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait=trait)
209
+
210
+ # 6) Final validation and save cohort info
211
+ covariate_cols = [trait, 'Age', 'Gender']
212
+ gene_cols_after = [c for c in linked_data.columns if c not in covariate_cols]
213
+ is_gene_available = bool(len(gene_cols_after) > 0)
214
+ is_trait_available = bool((trait in linked_data.columns) and bool(linked_data[trait].notna().any()))
215
+
216
+ note_parts = [
217
+ f"INFO: Cohort TCGA CESC. Samples linked: {len(linked_data)}.",
218
+ f"INFO: Gene features retained: {len(gene_cols_after)}.",
219
+ f"INFO: Age included: {'Age' in linked_data.columns}.",
220
+ f"INFO: Gender included: {'Gender' in linked_data.columns}.",
221
+ ]
222
+ note = " ".join(note_parts)
223
+
224
+ is_usable = validate_and_save_cohort_info(
225
+ is_final=True,
226
+ cohort="TCGA",
227
+ info_path=json_path,
228
+ is_gene_available=is_gene_available,
229
+ is_trait_available=is_trait_available,
230
+ is_biased=bool(trait_biased),
231
+ df=linked_data,
232
+ note=note
233
+ )
234
+
235
+ # 7) Save linked data only if usable
236
+ if is_usable:
237
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
238
+ linked_data.to_csv(out_data_file)
output/preprocess/Chronic_Fatigue_Syndrome/code/GSE251792.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Chronic_Fatigue_Syndrome"
6
+ cohort = "GSE251792"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Chronic_Fatigue_Syndrome"
10
+ in_cohort_dir = "../DATA/GEO/Chronic_Fatigue_Syndrome/GSE251792"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Chronic_Fatigue_Syndrome/GSE251792.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Chronic_Fatigue_Syndrome/gene_data/GSE251792.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Chronic_Fatigue_Syndrome/clinical_data/GSE251792.csv"
16
+ json_path = "./output/z2/preprocess/Chronic_Fatigue_Syndrome/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 (SuperSeries with parsed matrix, likely gene expression)
44
+ is_gene_available = True
45
+
46
+ # 2) Variable availability based on Sample Characteristics Dictionary
47
+ trait_row = 2 # 'group: Patient' vs 'group: Control'
48
+ age_row = 1 # 'age: <number>'
49
+ gender_row = 0 # 'Sex: Female'/'Sex: Male'
50
+
51
+ # 2.2) Conversion functions
52
+ def _extract_after_colon(x: str) -> str:
53
+ if x is None:
54
+ return None
55
+ if isinstance(x, (int, float)):
56
+ return str(x)
57
+ parts = str(x).split(":", 1)
58
+ return parts[1].strip() if len(parts) == 2 else str(x).strip()
59
+
60
+ def convert_trait(x):
61
+ val = _extract_after_colon(x)
62
+ if val is None:
63
+ return None
64
+ v = val.strip().lower()
65
+ if v in {"patient", "case", "me/cfs", "mecfs", "cfs", "me/cfs patient"}:
66
+ return 1
67
+ if v in {"control", "healthy", "normal", "hc"}:
68
+ return 0
69
+ # Heuristics
70
+ if "patient" in v or "case" in v:
71
+ return 1
72
+ if "control" in v or "healthy" in v:
73
+ return 0
74
+ return None
75
+
76
+ def convert_age(x):
77
+ val = _extract_after_colon(x)
78
+ if val is None:
79
+ return None
80
+ # Extract first integer/float in the string
81
+ m = re.search(r"[-+]?\d*\.?\d+", str(val))
82
+ if not m:
83
+ return None
84
+ num = float(m.group())
85
+ # Return int if it is an integer value
86
+ return int(num) if abs(num - int(num)) < 1e-9 else num
87
+
88
+ def convert_gender(x):
89
+ val = _extract_after_colon(x)
90
+ if val is None:
91
+ return None
92
+ v = val.strip().lower()
93
+ if v in {"female", "f", "woman", "women"}:
94
+ return 0
95
+ if v in {"male", "m", "man", "men"}:
96
+ return 1
97
+ return None
98
+
99
+ # 3) Save metadata using 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 (only if trait data is available)
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
+ selected_preview = preview_df(selected_clinical_df)
122
+
123
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
124
+ selected_clinical_df.to_csv(out_clinical_data_file)
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
+ requires_gene_mapping = True
135
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
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
+ # Decide which columns to use for mapping
147
+ probe_col = 'ID' # Matches probe identifiers like 'SL000001', 'HCE000104' seen in expression data
148
+ gene_symbol_col = 'EntrezGeneSymbol' # Contains human gene symbols
149
+
150
+ # Build mapping dataframe
151
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
152
+
153
+ # Apply mapping to convert probe-level data to gene-level expression
154
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
155
+
156
+ # Step 7: Data Normalization and Linking
157
+ import os
158
+ import json
159
+ import pandas as pd
160
+
161
+ # 1. Normalize gene symbols and save gene data
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
+ if 'selected_clinical_df' not in globals():
168
+ if os.path.exists(out_clinical_data_file):
169
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
170
+ else:
171
+ raise FileNotFoundError(f"Clinical data not found in memory or on disk at: {out_clinical_data_file}")
172
+
173
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
174
+
175
+ # 3. Handle missing values
176
+ linked_data = handle_missing_values(linked_data, trait)
177
+
178
+ # 4. Bias assessment and remove biased demographic features
179
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
180
+
181
+ # 5. Final validation and save cohort info
182
+ is_gene_available_flag = bool(normalized_gene_data.shape[0] > 0 and normalized_gene_data.shape[1] > 0)
183
+ is_trait_available_flag = bool((trait in selected_clinical_df.index) and (selected_clinical_df.loc[trait].notna().sum() > 0))
184
+
185
+ note = ("INFO: Probes mapped to EntrezGeneSymbol and normalized to standard gene symbols; "
186
+ "female=0, male=1; missing values handled (genes >20% missing removed, samples >5% missing removed, "
187
+ "mean/mode imputation applied).")
188
+
189
+ # Ensure the cohort info JSON exists and is a dict
190
+ os.makedirs(os.path.dirname(json_path), exist_ok=True)
191
+ needs_reset = False
192
+ if os.path.exists(json_path):
193
+ try:
194
+ with open(json_path, "r") as f:
195
+ existing = json.load(f)
196
+ if not isinstance(existing, dict):
197
+ needs_reset = True
198
+ except Exception:
199
+ needs_reset = True
200
+ else:
201
+ needs_reset = True
202
+
203
+ if needs_reset:
204
+ with open(json_path, "w") as f:
205
+ json.dump({}, f)
206
+
207
+ # Call validate_and_save_cohort_info with robust handling in case of serialization issues
208
+ try:
209
+ is_usable = validate_and_save_cohort_info(
210
+ is_final=True,
211
+ cohort=cohort,
212
+ info_path=json_path,
213
+ is_gene_available=bool(is_gene_available_flag),
214
+ is_trait_available=bool(is_trait_available_flag),
215
+ is_biased=bool(is_trait_biased),
216
+ df=unbiased_linked_data,
217
+ note=note
218
+ )
219
+ except TypeError:
220
+ # Reset JSON file and retry once in case prior content was incompatible
221
+ if os.path.exists(json_path):
222
+ os.remove(json_path)
223
+ with open(json_path, "w") as f:
224
+ json.dump({}, f)
225
+ is_usable = validate_and_save_cohort_info(
226
+ is_final=True,
227
+ cohort=cohort,
228
+ info_path=json_path,
229
+ is_gene_available=bool(is_gene_available_flag),
230
+ is_trait_available=bool(is_trait_available_flag),
231
+ is_biased=bool(is_trait_biased),
232
+ df=unbiased_linked_data,
233
+ note=note
234
+ )
235
+
236
+ # 6. Conditionally save the linked dataset
237
+ if is_usable:
238
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
239
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Chronic_Fatigue_Syndrome/code/GSE39684.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Chronic_Fatigue_Syndrome"
6
+ cohort = "GSE39684"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Chronic_Fatigue_Syndrome"
10
+ in_cohort_dir = "../DATA/GEO/Chronic_Fatigue_Syndrome/GSE39684"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Chronic_Fatigue_Syndrome/GSE39684.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Chronic_Fatigue_Syndrome/gene_data/GSE39684.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Chronic_Fatigue_Syndrome/clinical_data/GSE39684.csv"
16
+ json_path = "./output/z2/preprocess/Chronic_Fatigue_Syndrome/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
+ # 1) Determine data availability
40
+ # Based on the series description, this is a ViroChip viral microarray, not human gene expression.
41
+ is_gene_available = False
42
+
43
+ # From the provided sample characteristics, there is no CFS/CFS-related status, no age, and no gender.
44
+ trait_row = None # Chronic Fatigue Syndrome status not present
45
+ age_row = None # No age field
46
+ gender_row = None # Gender not provided; also prostate tissue implies male-only and thus constant/useless
47
+
48
+ # 2) Define conversion functions (robust, though not used since corresponding rows are None)
49
+
50
+ def _extract_value(x):
51
+ if x is None:
52
+ return None
53
+ s = str(x).strip()
54
+ if ':' in s:
55
+ s = s.split(':', 1)[1].strip()
56
+ return s if s != '' else None
57
+
58
+ def convert_trait(x):
59
+ # Map CFS-related labels to binary: CFS=1, controls=0
60
+ v = _extract_value(x)
61
+ if v is None:
62
+ return None
63
+ s = v.lower()
64
+ # Positive CFS indicators
65
+ if any(k in s for k in ['cfs', 'chronic fatigue syndrome', 'me/cfs', 'myalgic encephalomyelitis']):
66
+ return 1
67
+ # Common control indicators
68
+ if any(k in s for k in ['control', 'healthy', 'normal', 'non-cfs', 'no cfs']):
69
+ return 0
70
+ # Irrelevant fields (e.g., tissue or cohort info) -> unknown for trait
71
+ return None
72
+
73
+ def convert_age(x):
74
+ v = _extract_value(x)
75
+ if v is None:
76
+ return None
77
+ # Extract first integer/float present
78
+ import re
79
+ m = re.search(r'(\d+(\.\d+)?)', v)
80
+ if not m:
81
+ return None
82
+ try:
83
+ age_val = float(m.group(1))
84
+ # Reasonable human age range filter
85
+ if 0 <= age_val <= 120:
86
+ return age_val
87
+ except Exception:
88
+ pass
89
+ return None
90
+
91
+ def convert_gender(x):
92
+ v = _extract_value(x)
93
+ if v is None:
94
+ return None
95
+ s = v.lower()
96
+ # Standard mappings
97
+ if s in ['male', 'm', 'man', 'boy']:
98
+ return 1
99
+ if s in ['female', 'f', 'woman', 'girl']:
100
+ return 0
101
+ # Sometimes encoded as 1/0
102
+ if s in ['1', '0']:
103
+ return int(s)
104
+ return None
105
+
106
+ # 3) Initial filtering and save metadata
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 (skip because trait_row is None)
117
+ # If trait_row were available:
118
+ if trait_row is not None:
119
+ selected_clinical_df = geo_select_clinical_features(
120
+ clinical_df=clinical_data,
121
+ trait=trait,
122
+ trait_row=trait_row,
123
+ convert_trait=convert_trait,
124
+ age_row=age_row,
125
+ convert_age=convert_age if age_row is not None else None,
126
+ gender_row=gender_row,
127
+ convert_gender=convert_gender if gender_row is not None else None
128
+ )
129
+ # Preview and save
130
+ _ = preview_df(selected_clinical_df, n=5)
131
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
132
+ selected_clinical_df.to_csv(out_clinical_data_file)
output/preprocess/Chronic_Fatigue_Syndrome/code/GSE67311.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Chronic_Fatigue_Syndrome"
6
+ cohort = "GSE67311"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Chronic_Fatigue_Syndrome"
10
+ in_cohort_dir = "../DATA/GEO/Chronic_Fatigue_Syndrome/GSE67311"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Chronic_Fatigue_Syndrome/GSE67311.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Chronic_Fatigue_Syndrome/gene_data/GSE67311.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Chronic_Fatigue_Syndrome/clinical_data/GSE67311.csv"
16
+ json_path = "./output/z2/preprocess/Chronic_Fatigue_Syndrome/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 # Affymetrix Human Gene arrays -> gene expression data
44
+
45
+ # 2) Variable Availability and Conversion Functions
46
+
47
+ # Availability based on provided Sample Characteristics Dictionary:
48
+ # - trait (Chronic_Fatigue_Syndrome): key 8 with values Yes/No/-
49
+ trait_row = 8
50
+ # - age: not available
51
+ age_row = None
52
+ # - gender: not available
53
+ gender_row = None
54
+
55
+ def _after_colon(value: str) -> str:
56
+ if value is None:
57
+ return ""
58
+ s = str(value)
59
+ parts = s.split(":", 1)
60
+ return parts[1].strip() if len(parts) == 2 else s.strip()
61
+
62
+ def convert_trait(value):
63
+ v = _after_colon(value).strip().lower()
64
+ if v in {"yes", "y", "1", "true", "positive", "pos"}:
65
+ return 1
66
+ if v in {"no", "n", "0", "false", "negative", "neg"}:
67
+ return 0
68
+ if v in {"-", "na", "n/a", "none", "unknown", ""}:
69
+ return None
70
+ # Default heuristic: treat any unrecognized non-empty affirmative-looking token as None for safety
71
+ return None
72
+
73
+ def convert_age(value):
74
+ # Not used (age_row is None), but provided per instruction.
75
+ v = _after_colon(value).lower()
76
+ if v in {"", "-", "na", "n/a", "none", "unknown"}:
77
+ return None
78
+ # Extract first numeric (integer or float)
79
+ m = re.search(r"[-+]?\d*\.?\d+", v)
80
+ if not m:
81
+ return None
82
+ try:
83
+ age = float(m.group())
84
+ if 0 <= age <= 120:
85
+ return age
86
+ return None
87
+ except Exception:
88
+ return None
89
+
90
+ def convert_gender(value):
91
+ # Not used (gender_row is None), but provided per instruction.
92
+ v = _after_colon(value).strip().lower()
93
+ if v in {"female", "f", "woman", "girl", "0"}:
94
+ return 0
95
+ if v in {"male", "m", "man", "boy", "1"}:
96
+ return 1
97
+ if v in {"-", "na", "n/a", "none", "unknown", ""}:
98
+ return None
99
+ # Some datasets code gender as 1/2; map 1->male, 2->female if seen
100
+ if v == "2":
101
+ return 0
102
+ return None
103
+
104
+ # 3) Save metadata using initial filtering
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
+ # 4) Clinical Feature Extraction (only if trait_row is available)
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 and gender_row are None; converters not needed
122
+ )
123
+ clinical_selected_preview = preview_df(selected_clinical_df, n=5)
124
+ print(clinical_selected_preview)
125
+
126
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
127
+ selected_clinical_df.to_csv(out_clinical_data_file)
128
+
129
+ # Step 3: Gene Data Extraction
130
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
131
+ gene_data = get_genetic_data(matrix_file)
132
+
133
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
134
+ print(gene_data.index[:20])
135
+
136
+ # Step 4: Gene Identifier Review
137
+ print("requires_gene_mapping = True")
138
+
139
+ # Step 5: Gene Annotation
140
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
141
+ gene_annotation = get_gene_annotation(soft_file)
142
+
143
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
144
+ print("Gene annotation preview:")
145
+ print(preview_df(gene_annotation))
146
+
147
+ # Step 6: Gene Identifier Mapping
148
+ # Determine columns for mapping: Probe IDs are in 'ID', gene symbols are embedded in 'gene_assignment'
149
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='gene_assignment')
150
+
151
+ # Apply mapping to convert probe-level to gene-level expression
152
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
153
+
154
+ # Step 7: Data Normalization and Linking
155
+ import os
156
+
157
+ # 1. Normalize gene symbols and save gene data
158
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
159
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
160
+ normalized_gene_data.to_csv(out_gene_data_file)
161
+
162
+ # 2. Link the clinical and genetic data
163
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
164
+
165
+ # 3. Handle missing values
166
+ linked_data = handle_missing_values(linked_data, trait)
167
+
168
+ # 4. Bias assessment
169
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
170
+
171
+ # 5. Final validation and save cohort info
172
+ is_gene_available = (normalized_gene_data.shape[0] > 0 and normalized_gene_data.shape[1] > 0)
173
+ is_trait_available = trait in selected_clinical_df.index
174
+
175
+ note = "INFO: No age/gender available; trait derived from 'chronic fatigue syndrome' field."
176
+ is_usable = validate_and_save_cohort_info(
177
+ True, cohort, json_path, is_gene_available, is_trait_available, is_trait_biased, unbiased_linked_data, note
178
+ )
179
+
180
+ # 6. Save linked data if usable
181
+ if is_usable:
182
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
183
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Chronic_Fatigue_Syndrome/code/TCGA.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Chronic_Fatigue_Syndrome"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z2/preprocess/Chronic_Fatigue_Syndrome/TCGA.csv"
12
+ out_gene_data_file = "./output/z2/preprocess/Chronic_Fatigue_Syndrome/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z2/preprocess/Chronic_Fatigue_Syndrome/clinical_data/TCGA.csv"
14
+ json_path = "./output/z2/preprocess/Chronic_Fatigue_Syndrome/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+
20
+ # Step 1: Select the most relevant TCGA cohort directory for Chronic Fatigue Syndrome (CFS)
21
+ def _normalize_name(s: str) -> str:
22
+ return (
23
+ s.lower()
24
+ .replace("(", "_")
25
+ .replace(")", "_")
26
+ .replace("-", "_")
27
+ .replace("/", "_")
28
+ .replace(" ", "_")
29
+ )
30
+
31
+ synonyms = [
32
+ "chronic_fatigue_syndrome",
33
+ "chronicfatiguesyndrome",
34
+ "myalgic_encephalomyelitis",
35
+ "myalgicencephalomyelitis",
36
+ "me_cfs",
37
+ "me-cfs",
38
+ "mecfs",
39
+ "cfs",
40
+ "fatigue",
41
+ ]
42
+
43
+ dirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
44
+ matched = []
45
+ for d in dirs:
46
+ norm = _normalize_name(d)
47
+ if any(syn in norm for syn in synonyms):
48
+ matched.append(d)
49
+
50
+ selected_dir = None
51
+ if matched:
52
+ # If multiple, choose the one with the longest matching synonym (more specific)
53
+ def match_score(dname):
54
+ norm = _normalize_name(dname)
55
+ hits = [len(s) for s in synonyms if s in norm]
56
+ return max(hits) if hits else 0
57
+ matched.sort(key=match_score, reverse=True)
58
+ selected_dir = matched[0]
59
+
60
+ # If no suitable directory is found, skip this trait and record metadata
61
+ if not selected_dir:
62
+ print(f"No suitable TCGA cohort found for trait '{trait}'. Skipping.")
63
+ _ = validate_and_save_cohort_info(
64
+ is_final=False,
65
+ cohort="TCGA",
66
+ info_path=json_path,
67
+ is_gene_available=False,
68
+ is_trait_available=False
69
+ )
70
+ clinical_df = None
71
+ genetic_df = None
72
+ clinical_file_path = None
73
+ genetic_file_path = None
74
+ else:
75
+ # Step 2: Identify clinical and genetic file paths
76
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
77
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
78
+
79
+ # Step 3: Load both files as DataFrames
80
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False)
81
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False)
82
+
83
+ # Step 4: Print clinical column names
84
+ print(list(clinical_df.columns))
output/preprocess/Chronic_Fatigue_Syndrome/cohort_info.json CHANGED
@@ -1,42 +1 @@
1
- {
2
- "GSE67311": {
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": 133
11
- },
12
- "GSE39684": {
13
- "is_usable": false,
14
- "is_gene_available": false,
15
- "is_trait_available": false,
16
- "is_available": false,
17
- "is_biased": null,
18
- "has_age": null,
19
- "has_gender": null,
20
- "sample_size": null
21
- },
22
- "GSE251792": {
23
- "is_usable": true,
24
- "is_gene_available": true,
25
- "is_trait_available": true,
26
- "is_available": true,
27
- "is_biased": false,
28
- "has_age": true,
29
- "has_gender": true,
30
- "sample_size": 84
31
- },
32
- "TCGA": {
33
- "is_usable": false,
34
- "is_gene_available": false,
35
- "is_trait_available": false,
36
- "is_available": false,
37
- "is_biased": null,
38
- "has_age": null,
39
- "has_gender": null,
40
- "sample_size": null
41
- }
42
- }
 
1
+ {"GSE67311": {"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": 133, "note": "INFO: No age/gender available; trait derived from 'chronic fatigue syndrome' field."}, "GSE39684": {"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}, "GSE251792": {"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": 84, "note": "INFO: Probes mapped to EntrezGeneSymbol and normalized to standard gene symbols; female=0, male=1; missing values handled (genes >20% missing removed, samples >5% missing removed, mean/mode imputation applied)."}, "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/Chronic_kidney_disease/GSE142153.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Chronic_kidney_disease/clinical_data/GSE104948.csv CHANGED
@@ -1,2 +1,2 @@
1
  ,GSM2810645,GSM2810646,GSM2810647,GSM2810648,GSM2810649,GSM2810650,GSM2810651,GSM2810652,GSM2810653,GSM2810654,GSM2810655,GSM2810656,GSM2810657,GSM2810658,GSM2810659,GSM2810660,GSM2810661,GSM2810662,GSM2810663,GSM2810664,GSM2810665,GSM2810666,GSM2810667,GSM2810668,GSM2810669,GSM2810670,GSM2810671,GSM2810672,GSM2810673,GSM2810674,GSM2810675,GSM2810676,GSM2810677,GSM2810678,GSM2810679,GSM2810680,GSM2810681,GSM2810682,GSM2810683,GSM2810684,GSM2810685,GSM2810686,GSM2810687,GSM2810688,GSM2810689,GSM2810690,GSM2810691,GSM2810692,GSM2810693,GSM2810694,GSM2810695,GSM2810696,GSM2810697,GSM2810698,GSM2810699,GSM2810700,GSM2810701,GSM2810702,GSM2810703,GSM2810704,GSM2810705,GSM2810706,GSM2810707,GSM2810708,GSM2810709,GSM2810710,GSM2810711,GSM2810712,GSM2810713,GSM2810714,GSM2810715,GSM2810716,GSM2810717,GSM2810718,GSM2810719,GSM2810720,GSM2810721,GSM2810722,GSM2810723,GSM2810724,GSM2810725,GSM2810726,GSM2810727,GSM2810728,GSM2810729,GSM2810730,GSM2810731,GSM2810732,GSM2810733,GSM2810734,GSM2810735,GSM2810736,GSM2810737,GSM2810738,GSM2810739,GSM2810740,GSM2810741,GSM2810742,GSM2810743,GSM2810744,GSM2810745,GSM2810746,GSM2810747,GSM2810748,GSM2810749,GSM2810750,GSM2810751,GSM2810752,GSM2810753,GSM2810754,GSM2810755,GSM2810756,GSM2810757,GSM2810758,GSM2810759,GSM2810760,GSM2810761,GSM2810762,GSM2810763,GSM2810764,GSM2810765,GSM2810766,GSM2810767,GSM2810768,GSM2810769
2
- Chronic_kidney_disease,1.0,1.0,1.0,1.0,1.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,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,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,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
  ,GSM2810645,GSM2810646,GSM2810647,GSM2810648,GSM2810649,GSM2810650,GSM2810651,GSM2810652,GSM2810653,GSM2810654,GSM2810655,GSM2810656,GSM2810657,GSM2810658,GSM2810659,GSM2810660,GSM2810661,GSM2810662,GSM2810663,GSM2810664,GSM2810665,GSM2810666,GSM2810667,GSM2810668,GSM2810669,GSM2810670,GSM2810671,GSM2810672,GSM2810673,GSM2810674,GSM2810675,GSM2810676,GSM2810677,GSM2810678,GSM2810679,GSM2810680,GSM2810681,GSM2810682,GSM2810683,GSM2810684,GSM2810685,GSM2810686,GSM2810687,GSM2810688,GSM2810689,GSM2810690,GSM2810691,GSM2810692,GSM2810693,GSM2810694,GSM2810695,GSM2810696,GSM2810697,GSM2810698,GSM2810699,GSM2810700,GSM2810701,GSM2810702,GSM2810703,GSM2810704,GSM2810705,GSM2810706,GSM2810707,GSM2810708,GSM2810709,GSM2810710,GSM2810711,GSM2810712,GSM2810713,GSM2810714,GSM2810715,GSM2810716,GSM2810717,GSM2810718,GSM2810719,GSM2810720,GSM2810721,GSM2810722,GSM2810723,GSM2810724,GSM2810725,GSM2810726,GSM2810727,GSM2810728,GSM2810729,GSM2810730,GSM2810731,GSM2810732,GSM2810733,GSM2810734,GSM2810735,GSM2810736,GSM2810737,GSM2810738,GSM2810739,GSM2810740,GSM2810741,GSM2810742,GSM2810743,GSM2810744,GSM2810745,GSM2810746,GSM2810747,GSM2810748,GSM2810749,GSM2810750,GSM2810751,GSM2810752,GSM2810753,GSM2810754,GSM2810755,GSM2810756,GSM2810757,GSM2810758,GSM2810759,GSM2810760,GSM2810761,GSM2810762,GSM2810763,GSM2810764,GSM2810765,GSM2810766,GSM2810767,GSM2810768,GSM2810769
2
+ Chronic_kidney_disease,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.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,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,1.0,1.0
output/preprocess/Chronic_kidney_disease/clinical_data/GSE104954.csv CHANGED
@@ -1,2 +1,2 @@
1
- ,GSM2810894,GSM2810895,GSM2810896,GSM2810897,GSM2810898,GSM2810899,GSM2810900,GSM2810901,GSM2810902,GSM2810903,GSM2810904,GSM2810905,GSM2810906,GSM2810907,GSM2810908,GSM2810909,GSM2810910,GSM2810911,GSM2810912,GSM2810913,GSM2810914,GSM2810915,GSM2810916,GSM2810917,GSM2810918,GSM2810919,GSM2810920,GSM2810921,GSM2810922,GSM2810923,GSM2810924,GSM2810925,GSM2810926,GSM2810927,GSM2810928,GSM2810929,GSM2810930,GSM2810931,GSM2810932,GSM2810933,GSM2810934,GSM2810935,GSM2810936,GSM2810937,GSM2810938,GSM2810939,GSM2810940,GSM2810941,GSM2810942,GSM2810943,GSM2810944,GSM2810945,GSM2810946,GSM2810947,GSM2810948,GSM2810949,GSM2810950,GSM2810951,GSM2810952,GSM2810953,GSM2810954,GSM2810955,GSM2810956,GSM2810957,GSM2810958,GSM2810959,GSM2810960,GSM2810961,GSM2810962,GSM2810963,GSM2810964,GSM2810965,GSM2810966,GSM2810967,GSM2810968,GSM2810969,GSM2810970,GSM2810971,GSM2810972,GSM2810973,GSM2810974,GSM2810975,GSM2810976,GSM2810977,GSM2810978,GSM2810979,GSM2810980,GSM2810981,GSM2810982,GSM2810983,GSM2810984,GSM2810985,GSM2810986,GSM2810987,GSM2810988,GSM2810989,GSM2810990,GSM2810991,GSM2810992,GSM2810993,GSM2810994,GSM2810995,GSM2810996,GSM2810997,GSM2810998,GSM2810999,GSM2811000,GSM2811001,GSM2811002,GSM2811003,GSM2811004,GSM2811005,GSM2811006,GSM2811007,GSM2811008,GSM2811009,GSM2811010,GSM2811011,GSM2811012,GSM2811013,GSM2811014,GSM2811015,GSM2811016,GSM2811017,GSM2811018,GSM2811019,GSM2811020,GSM2811021,GSM2811022,GSM2811023,GSM2811024,GSM2811025,GSM2811026,GSM2811027,GSM2811028
2
  Chronic_kidney_disease,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,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.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,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
+ Feature,GSM2810894,GSM2810895,GSM2810896,GSM2810897,GSM2810898,GSM2810899,GSM2810900,GSM2810901,GSM2810902,GSM2810903,GSM2810904,GSM2810905,GSM2810906,GSM2810907,GSM2810908,GSM2810909,GSM2810910,GSM2810911,GSM2810912,GSM2810913,GSM2810914,GSM2810915,GSM2810916,GSM2810917,GSM2810918,GSM2810919,GSM2810920,GSM2810921,GSM2810922,GSM2810923,GSM2810924,GSM2810925,GSM2810926,GSM2810927,GSM2810928,GSM2810929,GSM2810930,GSM2810931,GSM2810932,GSM2810933,GSM2810934,GSM2810935,GSM2810936,GSM2810937,GSM2810938,GSM2810939,GSM2810940,GSM2810941,GSM2810942,GSM2810943,GSM2810944,GSM2810945,GSM2810946,GSM2810947,GSM2810948,GSM2810949,GSM2810950,GSM2810951,GSM2810952,GSM2810953,GSM2810954,GSM2810955,GSM2810956,GSM2810957,GSM2810958,GSM2810959,GSM2810960,GSM2810961,GSM2810962,GSM2810963,GSM2810964,GSM2810965,GSM2810966,GSM2810967,GSM2810968,GSM2810969,GSM2810970,GSM2810971,GSM2810972,GSM2810973,GSM2810974,GSM2810975,GSM2810976,GSM2810977,GSM2810978,GSM2810979,GSM2810980,GSM2810981,GSM2810982,GSM2810983,GSM2810984,GSM2810985,GSM2810986,GSM2810987,GSM2810988,GSM2810989,GSM2810990,GSM2810991,GSM2810992,GSM2810993,GSM2810994,GSM2810995,GSM2810996,GSM2810997,GSM2810998,GSM2810999,GSM2811000,GSM2811001,GSM2811002,GSM2811003,GSM2811004,GSM2811005,GSM2811006,GSM2811007,GSM2811008,GSM2811009,GSM2811010,GSM2811011,GSM2811012,GSM2811013,GSM2811014,GSM2811015,GSM2811016,GSM2811017,GSM2811018,GSM2811019,GSM2811020,GSM2811021,GSM2811022,GSM2811023,GSM2811024,GSM2811025,GSM2811026,GSM2811027,GSM2811028
2
  Chronic_kidney_disease,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,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.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,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,,,
output/preprocess/Chronic_kidney_disease/clinical_data/GSE127136.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Chronic_kidney_disease/clinical_data/GSE180393.csv CHANGED
@@ -1,2 +1,2 @@
1
- 0
2
- 0.0
 
1
+ ,GSM5607752,GSM5607753,GSM5607754,GSM5607755,GSM5607756,GSM5607757,GSM5607758,GSM5607759,GSM5607760,GSM5607761,GSM5607762,GSM5607763,GSM5607764,GSM5607765,GSM5607766,GSM5607767,GSM5607768,GSM5607769,GSM5607770,GSM5607771,GSM5607772,GSM5607773,GSM5607774,GSM5607775,GSM5607776,GSM5607777,GSM5607778,GSM5607779,GSM5607780,GSM5607781,GSM5607782,GSM5607783,GSM5607784,GSM5607785,GSM5607786,GSM5607787,GSM5607788,GSM5607789,GSM5607790,GSM5607791,GSM5607792,GSM5607793,GSM5607794,GSM5607795,GSM5607796,GSM5607797,GSM5607798,GSM5607799,GSM5607800,GSM5607801,GSM5607802,GSM5607803,GSM5607804,GSM5607805,GSM5607806,GSM5607807,GSM5607808,GSM5607809,GSM5607810,GSM5607811,GSM5607812,GSM5607813
2
+ Chronic_kidney_disease,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,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
output/preprocess/Chronic_kidney_disease/clinical_data/GSE180394.csv CHANGED
@@ -1,2 +1,2 @@
1
- 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21
2
- 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,0.0
 
1
+ ,GSM5607814,GSM5607815,GSM5607816,GSM5607817,GSM5607818,GSM5607819,GSM5607820,GSM5607821,GSM5607822,GSM5607823,GSM5607824,GSM5607825,GSM5607826,GSM5607827,GSM5607828,GSM5607829,GSM5607830,GSM5607831,GSM5607832,GSM5607833,GSM5607834,GSM5607835,GSM5607836,GSM5607837,GSM5607838,GSM5607839,GSM5607840,GSM5607841,GSM5607842,GSM5607843,GSM5607844,GSM5607845,GSM5607846,GSM5607847,GSM5607848,GSM5607849,GSM5607850,GSM5607851,GSM5607852,GSM5607853,GSM5607854,GSM5607855,GSM5607856,GSM5607857,GSM5607858,GSM5607859,GSM5607860,GSM5607861,GSM5607862,GSM5607863,GSM5607864,GSM5607865,GSM5607866,GSM5607867,GSM5607868,GSM5607869,GSM5607870,GSM5607871,GSM5607872
2
+ Chronic_kidney_disease,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,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
output/preprocess/Chronic_kidney_disease/clinical_data/GSE45980.csv CHANGED
@@ -1,4 +1,4 @@
1
- GSM1121040,GSM1121041,GSM1121042,GSM1121043,GSM1121044,GSM1121045,GSM1121046,GSM1121047,GSM1121048,GSM1121049,GSM1121050,GSM1121051,GSM1121052,GSM1121053,GSM1121054,GSM1121055,GSM1121056,GSM1121057,GSM1121058,GSM1121059,GSM1121060,GSM1121061,GSM1121062,GSM1121063,GSM1121064,GSM1121065,GSM1121066,GSM1121067,GSM1121068,GSM1121069,GSM1121070,GSM1121071,GSM1121072,GSM1121073,GSM1121074,GSM1121075,GSM1121076,GSM1121077,GSM1121078,GSM1121079,GSM1121080,GSM1121081,GSM1121082
2
- 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.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
3
- 72.0,20.0,64.0,17.0,46.0,55.0,74.0,49.0,20.0,42.0,73.0,63.0,33.0,74.0,24.0,45.0,70.0,60.0,67.0,31.0,53.0,67.0,22.0,54.0,40.0,38.0,19.0,28.0,65.0,74.0,65.0,54.0,58.0,56.0,34.0,31.0,64.0,59.0,70.0,58.0,67.0,54.0,61.0
4
- 1.0,0.0,0.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,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0
 
1
+ ,GSM1121040,GSM1121041,GSM1121042,GSM1121043,GSM1121044,GSM1121045,GSM1121046,GSM1121047,GSM1121048,GSM1121049,GSM1121050,GSM1121051,GSM1121052,GSM1121053,GSM1121054,GSM1121055,GSM1121056,GSM1121057,GSM1121058,GSM1121059,GSM1121060,GSM1121061,GSM1121062,GSM1121063,GSM1121064,GSM1121065,GSM1121066,GSM1121067,GSM1121068,GSM1121069,GSM1121070,GSM1121071,GSM1121072,GSM1121073,GSM1121074,GSM1121075,GSM1121076,GSM1121077,GSM1121078,GSM1121079,GSM1121080,GSM1121081,GSM1121082
2
+ Chronic_kidney_disease,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.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
3
+ Age,72.0,20.0,64.0,17.0,46.0,55.0,74.0,49.0,20.0,42.0,73.0,63.0,33.0,74.0,24.0,45.0,70.0,60.0,67.0,31.0,53.0,67.0,22.0,54.0,40.0,38.0,19.0,28.0,65.0,74.0,65.0,54.0,58.0,56.0,34.0,31.0,64.0,59.0,70.0,58.0,67.0,54.0,61.0
4
+ Gender,1.0,0.0,0.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,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0
output/preprocess/Chronic_kidney_disease/clinical_data/GSE66494.csv CHANGED
@@ -1,2 +1,2 @@
1
- #01,#02,#03,#04,#05,#06,#07,#08,#09,#10,#11,#12,#13,#14,#15,#16,#17,#18,#19,#20,#21,#22,#23,#24,#26,#27,#28,#29,#30,#31
2
- ,0.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,
 
1
+ ,GSM1623299,GSM1623300,GSM1623301,GSM1623302,GSM1623303,GSM1623304,GSM1623305,GSM1623306,GSM1623307,GSM1623308,GSM1623309,GSM1623310,GSM1623311,GSM1623312,GSM1623313,GSM1623314,GSM1623315,GSM1623316,GSM1623317,GSM1623318,GSM1623319,GSM1623320,GSM1623321,GSM1623322,GSM1623323,GSM1623324,GSM1623325,GSM1623326,GSM1623327,GSM1623328,GSM1623329,GSM1623330,GSM1623331,GSM1623332,GSM1623333,GSM1623334,GSM1623335,GSM1623336,GSM1623337,GSM1623338,GSM1623339,GSM1623340,GSM1623341,GSM1623342,GSM1623343,GSM1623344,GSM1623345,GSM1623346,GSM1623347,GSM1623348,GSM1623349,GSM1623350,GSM1623351,GSM1623352,GSM1623353,GSM1623354,GSM1623355,GSM1623356,GSM1623357,GSM1623358,GSM1623359
2
+ Chronic_kidney_disease,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,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,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0
output/preprocess/Chronic_kidney_disease/code/GSE104948.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Chronic_kidney_disease"
6
+ cohort = "GSE104948"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Chronic_kidney_disease"
10
+ in_cohort_dir = "../DATA/GEO/Chronic_kidney_disease/GSE104948"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Chronic_kidney_disease/GSE104948.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Chronic_kidney_disease/gene_data/GSE104948.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Chronic_kidney_disease/clinical_data/GSE104948.csv"
16
+ json_path = "./output/z2/preprocess/Chronic_kidney_disease/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 # Affymetrix microarrays -> gene expression data
44
+
45
+ # 2) Variable Availability and Converters
46
+ # From the sample characteristics dictionary:
47
+ # 0: tissue
48
+ # 1: diagnosis
49
+ trait_row = 1
50
+ age_row = None
51
+ gender_row = None
52
+
53
+ def _extract_value(x):
54
+ if x is None:
55
+ return None
56
+ s = str(x)
57
+ if ':' in s:
58
+ s = s.split(':', 1)[1]
59
+ s = s.strip()
60
+ return s if s else None
61
+
62
+ def convert_trait(x):
63
+ val = _extract_value(x)
64
+ if val is None:
65
+ return None
66
+ low = val.lower()
67
+ # Controls (non-CKD) heuristics
68
+ if any(k in low for k in ['tumor', 'donor', 'living', 'control', 'healthy', 'normal']):
69
+ return 0
70
+ if low in {'na', 'n/a', 'unknown', 'not available', 'missing'}:
71
+ return None
72
+ # All other diagnoses are considered CKD cases
73
+ return 1
74
+
75
+ def convert_age(x):
76
+ val = _extract_value(x)
77
+ if val is None:
78
+ return None
79
+ # Extract the first number (years assumed)
80
+ m = re.search(r'[-+]?\d*\.?\d+', val)
81
+ return float(m.group()) if m else None
82
+
83
+ def convert_gender(x):
84
+ val = _extract_value(x)
85
+ if val is None:
86
+ return None
87
+ low = val.lower()
88
+ if low in {'female', 'f', 'woman', 'girl'}:
89
+ return 0
90
+ if low in {'male', 'm', 'man', 'boy'}:
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 is 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=convert_age if age_row is not None else None,
113
+ gender_row=gender_row,
114
+ convert_gender=convert_gender if gender_row is not None else None
115
+ )
116
+ preview = preview_df(selected_clinical_df)
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)
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
+ # 1-2) Decide mapping columns and create mapping dataframe
143
+ # From preview, probe IDs in expression data match 'ID' in annotation; gene symbols are in 'Symbol'
144
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')
145
+
146
+ # 3) Apply gene mapping to convert probe-level data to gene-level expression
147
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
148
+
149
+ # Step 7: Data Normalization and Linking
150
+ import os
151
+ import pandas as pd
152
+
153
+ # 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.
154
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
155
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
156
+ normalized_gene_data.to_csv(out_gene_data_file)
157
+
158
+ # 2. Link the clinical and genetic data with the 'geo_link_clinical_genetic_data' function from the library.
159
+ # Fallback: load clinical data from saved CSV if not present in memory
160
+ if 'selected_clinical_df' not in globals():
161
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
162
+
163
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
164
+
165
+ # 3. Handle missing values in the linked data
166
+ linked_data = handle_missing_values(linked_data, trait)
167
+
168
+ # 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.
169
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
170
+
171
+ # 5. Conduct quality check and save the cohort information.
172
+ note = ("INFO: Diagnosis-based heuristic used for case/control: donors/tumor/normal/healthy treated as controls (0); "
173
+ "all other diagnoses treated as CKD cases (1).")
174
+ is_usable = validate_and_save_cohort_info(
175
+ True, cohort, json_path, True, True, is_trait_biased, unbiased_linked_data, note=note
176
+ )
177
+
178
+ # 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.
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/Chronic_kidney_disease/code/GSE104954.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Chronic_kidney_disease"
6
+ cohort = "GSE104954"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Chronic_kidney_disease"
10
+ in_cohort_dir = "../DATA/GEO/Chronic_kidney_disease/GSE104954"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Chronic_kidney_disease/GSE104954.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Chronic_kidney_disease/gene_data/GSE104954.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Chronic_kidney_disease/clinical_data/GSE104954.csv"
16
+ json_path = "./output/z2/preprocess/Chronic_kidney_disease/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 # Affymetrix microarrays with Human Entrez Gene ID -> gene expression
44
+
45
+ # 2) Variable availability and conversion
46
+
47
+ # Available keys from sample characteristics:
48
+ # 0: tissue (constant)
49
+ # 1: diagnosis (variable; can infer CKD status)
50
+ trait_row = 1
51
+ age_row = None
52
+ gender_row = None
53
+
54
+ # Conversion functions
55
+ def _after_colon(x):
56
+ if x is None:
57
+ return None
58
+ s = str(x)
59
+ parts = s.split(":", 1)
60
+ return parts[1].strip() if len(parts) == 2 else s.strip()
61
+
62
+ def convert_trait(x):
63
+ v = _after_colon(x)
64
+ if v is None:
65
+ return None
66
+ v_low = v.lower()
67
+
68
+ # Controls / non-CKD indicators
69
+ control_markers = ['tumor nephrectomy', 'living donor', 'donor', 'control', 'healthy']
70
+ if any(k in v_low for k in control_markers):
71
+ return 0
72
+
73
+ # CKD / kidney disease indicators
74
+ ckd_markers = [
75
+ 'nephro', # captures nephropathy, nephritis
76
+ 'glomerulo', # glomerulonephropathy
77
+ 'iga', # IgA nephropathy
78
+ 'lupus', # lupus nephritis
79
+ 'diabetic',
80
+ 'hypertensive',
81
+ 'focal segmental glomerulosclerosis',
82
+ 'fsgs',
83
+ 'minimal change',
84
+ 'thin membr', # thin membrane disease
85
+ 'membranous'
86
+ ]
87
+ if any(k in v_low for k in ckd_markers):
88
+ return 1
89
+
90
+ return None
91
+
92
+ def convert_age(x):
93
+ v = _after_colon(x)
94
+ if v is None:
95
+ return None
96
+ m = re.search(r'(\d+(\.\d+)?)', v)
97
+ if not m:
98
+ return None
99
+ age = float(m.group(1))
100
+ if 0 <= age <= 120:
101
+ return age
102
+ return None
103
+
104
+ def convert_gender(x):
105
+ v = _after_colon(x)
106
+ if v is None:
107
+ return None
108
+ v_low = v.lower()
109
+ if v_low in ['female', 'f', 'woman', 'women']:
110
+ return 0
111
+ if v_low in ['male', 'm', 'man', 'men']:
112
+ return 1
113
+ return None
114
+
115
+ # 3) Save metadata (initial filtering)
116
+ is_trait_available = trait_row is not None
117
+ _ = validate_and_save_cohort_info(
118
+ is_final=False,
119
+ cohort=cohort,
120
+ info_path=json_path,
121
+ is_gene_available=is_gene_available,
122
+ is_trait_available=is_trait_available
123
+ )
124
+
125
+ # 4) Clinical feature extraction (since trait_row is available)
126
+ if trait_row is not None:
127
+ selected_clinical_df = geo_select_clinical_features(
128
+ clinical_df=clinical_data,
129
+ trait=trait,
130
+ trait_row=trait_row,
131
+ convert_trait=convert_trait,
132
+ age_row=age_row,
133
+ convert_age=convert_age,
134
+ gender_row=gender_row,
135
+ convert_gender=convert_gender
136
+ )
137
+ preview = preview_df(selected_clinical_df, n=5)
138
+ print(preview)
139
+ # Save clinical data
140
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
141
+ selected_clinical_df.index.name = 'Feature'
142
+ selected_clinical_df.to_csv(out_clinical_data_file)
143
+
144
+ # Step 3: Gene Data Extraction
145
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
146
+ gene_data = get_genetic_data(matrix_file)
147
+
148
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
149
+ print(gene_data.index[:20])
150
+
151
+ # Step 4: Gene Identifier Review
152
+ requires_gene_mapping = True
153
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
154
+
155
+ # Step 5: Gene Annotation
156
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
157
+ gene_annotation = get_gene_annotation(soft_file)
158
+
159
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
160
+ print("Gene annotation preview:")
161
+ print(preview_df(gene_annotation))
162
+
163
+ # Step 6: Gene Identifier Mapping
164
+ # Decide columns for mapping based on preview:
165
+ # Expression IDs look like '10000_at', which match the 'ID' column in annotation.
166
+ # Gene symbols are in the 'Symbol' column.
167
+ probe_col = 'ID'
168
+ gene_symbol_col = 'Symbol'
169
+
170
+ # 2) Build mapping dataframe
171
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
172
+
173
+ # 3) Apply mapping to convert probe-level to gene-level expression
174
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
175
+
176
+ # Step 7: Data Normalization and Linking
177
+ import os
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
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
186
+
187
+ # 3. Handle missing values
188
+ linked_data = handle_missing_values(linked_data, trait)
189
+
190
+ # 4. Bias check (and remove biased demographic features if any)
191
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
192
+
193
+ # 5. Final validation and save cohort info
194
+ note = "INFO: Trait appears highly imbalanced (few controls vs many CKD cases); dataset likely flagged as biased."
195
+ is_usable = validate_and_save_cohort_info(
196
+ is_final=True,
197
+ cohort=cohort,
198
+ info_path=json_path,
199
+ is_gene_available=True,
200
+ is_trait_available=True,
201
+ is_biased=is_trait_biased,
202
+ df=unbiased_linked_data,
203
+ note=note
204
+ )
205
+
206
+ # 6. Save linked data if usable
207
+ if is_usable:
208
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
209
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Chronic_kidney_disease/code/GSE127136.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Chronic_kidney_disease"
6
+ cohort = "GSE127136"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Chronic_kidney_disease"
10
+ in_cohort_dir = "../DATA/GEO/Chronic_kidney_disease/GSE127136"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Chronic_kidney_disease/GSE127136.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Chronic_kidney_disease/gene_data/GSE127136.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Chronic_kidney_disease/clinical_data/GSE127136.csv"
16
+ json_path = "./output/z2/preprocess/Chronic_kidney_disease/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 gene expression availability (scRNA-seq => gene expression data available)
40
+ is_gene_available = True
41
+
42
+ # Determine variable availability from Sample Characteristics Dictionary:
43
+ # 0: patients, 1: disease state (IgAN, kidney cancer, normal), 2: tissue/cell type
44
+ trait_row = 1
45
+ age_row = None
46
+ gender_row = None
47
+
48
+ # Conversion functions
49
+ def _extract_value(val):
50
+ if val is None:
51
+ return None
52
+ try:
53
+ s = str(val)
54
+ except Exception:
55
+ return None
56
+ parts = s.split(":", 1)
57
+ v = parts[1] if len(parts) > 1 else parts[0]
58
+ return v.strip()
59
+
60
+ def convert_trait(val):
61
+ v = _extract_value(val)
62
+ if v is None:
63
+ return None
64
+ v_low = v.lower()
65
+ # Map to CKD presence: IgAN is CKD; normal and kidney cancer are not CKD
66
+ if "igan" in v_low or "iga nephropathy" in v_low:
67
+ return 1
68
+ if "normal" in v_low:
69
+ return 0
70
+ if "kidney cancer" in v_low or "cancer" in v_low:
71
+ return 0
72
+ return None
73
+
74
+ def convert_age(val):
75
+ v = _extract_value(val)
76
+ if v is None:
77
+ return None
78
+ # Extract numeric age if present
79
+ import re
80
+ m = re.search(r"(\d+(\.\d+)?)", v)
81
+ if m:
82
+ try:
83
+ return float(m.group(1))
84
+ except Exception:
85
+ return None
86
+ return None
87
+
88
+ def convert_gender(val):
89
+ v = _extract_value(val)
90
+ if v is None:
91
+ return None
92
+ v_low = v.lower()
93
+ if v_low in {"male", "m"}:
94
+ return 1
95
+ if v_low in {"female", "f"}:
96
+ return 0
97
+ return None
98
+
99
+ # Initial filtering metadata
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
+ # Clinical feature extraction and save
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=None,
118
+ gender_row=gender_row,
119
+ convert_gender=None
120
+ )
121
+ preview = preview_df(selected_clinical_df)
122
+ print("Selected clinical features preview:", preview)
123
+
124
+ # Ensure output directory exists and save
125
+ import os
126
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
127
+ selected_clinical_df.to_csv(out_clinical_data_file)
128
+
129
+ # Step 3: Gene Data Extraction
130
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
131
+ gene_data = get_genetic_data(matrix_file)
132
+
133
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
134
+ print(gene_data.index[:20])
output/preprocess/Chronic_kidney_disease/code/GSE142153.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Chronic_kidney_disease"
6
+ cohort = "GSE142153"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Chronic_kidney_disease"
10
+ in_cohort_dir = "../DATA/GEO/Chronic_kidney_disease/GSE142153"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Chronic_kidney_disease/GSE142153.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Chronic_kidney_disease/gene_data/GSE142153.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Chronic_kidney_disease/clinical_data/GSE142153.csv"
16
+ json_path = "./output/z2/preprocess/Chronic_kidney_disease/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 # PBMC transcriptional profiling via microarray implies gene expression data
44
+
45
+ # 2) Variable availability and converters
46
+ trait_row = 1 # 'diagnosis' field
47
+ age_row = None
48
+ gender_row = None
49
+
50
+ def _after_colon(x):
51
+ if x is None:
52
+ return None
53
+ s = str(x)
54
+ parts = s.split(":", 1)
55
+ return parts[1].strip() if len(parts) == 2 else s.strip()
56
+
57
+ def convert_trait(x):
58
+ v = _after_colon(x)
59
+ if v is None:
60
+ return None
61
+ v_low = v.lower().strip()
62
+ # CKD cases: diabetic nephropathy or ESRD (include common synonyms)
63
+ if (
64
+ "esrd" in v_low
65
+ or "end stage renal disease" in v_low
66
+ or "end-stage renal disease" in v_low
67
+ or "end stage renal" in v_low
68
+ or "end-stage renal" in v_low
69
+ ):
70
+ return 1
71
+ if "diabetic nephropathy" in v_low or v_low == "dn":
72
+ return 1
73
+ if "chronic kidney disease" in v_low or "ckd" in v_low:
74
+ return 1
75
+ # Controls
76
+ if (
77
+ "healthy" in v_low
78
+ or "healthy control" in v_low
79
+ or "healthy donor" in v_low
80
+ or "normal" in v_low
81
+ or "control" in v_low
82
+ ):
83
+ return 0
84
+ return None
85
+
86
+ def convert_age(x):
87
+ v = _after_colon(x)
88
+ if v is None:
89
+ return None
90
+ m = re.search(r"[-+]?\d*\.?\d+", v)
91
+ if not m:
92
+ return None
93
+ try:
94
+ return float(m.group())
95
+ except Exception:
96
+ return None
97
+
98
+ def convert_gender(x):
99
+ v = _after_colon(x)
100
+ if v is None:
101
+ return None
102
+ v_low = v.lower().strip()
103
+ if v_low in {"male", "m"}:
104
+ return 1
105
+ if v_low in {"female", "f"}:
106
+ return 0
107
+ return None
108
+
109
+ # 3) Save metadata (initial filtering)
110
+ # Note: is_final=False will only record metadata for datasets that fail 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 data 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=None,
129
+ gender_row=gender_row,
130
+ convert_gender=None
131
+ )
132
+ clinical_preview = preview_df(selected_clinical_df)
133
+ print(clinical_preview)
134
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
135
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
136
+
137
+ # Step 3: Gene Data Extraction
138
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
139
+ gene_data = get_genetic_data(matrix_file)
140
+
141
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
142
+ print(gene_data.index[:20])
143
+
144
+ # Step 4: Gene Identifier Review
145
+ print("requires_gene_mapping = True")
146
+
147
+ # Step 5: Gene Annotation
148
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
149
+ gene_annotation = get_gene_annotation(soft_file)
150
+
151
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
152
+ print("Gene annotation preview:")
153
+ print(preview_df(gene_annotation))
154
+
155
+ # Step 6: Gene Identifier Mapping
156
+ # Determine appropriate columns for mapping based on the preview:
157
+ # Probe identifiers match the 'ID' column; gene symbols are in 'GENE_SYMBOL'.
158
+ probe_id_col = 'ID'
159
+ gene_symbol_col = 'GENE_SYMBOL'
160
+
161
+ # Preserve the original probe-level data
162
+ probe_level_data = gene_data
163
+
164
+ # Build mapping and apply to convert probe-level to gene-level expression
165
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_id_col, gene_col=gene_symbol_col)
166
+ gene_data = apply_gene_mapping(probe_level_data, mapping_df)
167
+
168
+ # Step 7: Data Normalization and Linking
169
+ import os
170
+
171
+ # 1. Normalize gene symbols and save gene data
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. Assess 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
+ # Explicitly cast to built-in Python bool to avoid serialization issues
187
+ is_gene_available_final = bool((normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0))
188
+ is_trait_available_final = bool((trait in linked_data.columns) and bool(linked_data[trait].notna().any()))
189
+ is_trait_biased = bool(is_trait_biased)
190
+
191
+ note = str("INFO: Only trait available; no age/gender fields in clinical annotations.")
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=is_trait_biased,
199
+ df=unbiased_linked_data,
200
+ note=note
201
+ )
202
+
203
+ # 6. Save linked data if usable
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/Chronic_kidney_disease/code/GSE180393.py ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Chronic_kidney_disease"
6
+ cohort = "GSE180393"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Chronic_kidney_disease"
10
+ in_cohort_dir = "../DATA/GEO/Chronic_kidney_disease/GSE180393"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Chronic_kidney_disease/GSE180393.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Chronic_kidney_disease/gene_data/GSE180393.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Chronic_kidney_disease/clinical_data/GSE180393.csv"
16
+ json_path = "./output/z2/preprocess/Chronic_kidney_disease/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 math
41
+ import pandas as pd
42
+
43
+ # 1) Gene expression availability
44
+ is_gene_available = True # Affymetrix microarray platform with glomerular gene expression
45
+
46
+ # 2) Variable availability and conversion functions
47
+ # From the sample characteristics, key 0 contains disease/control grouping; key 1 is constant tissue info.
48
+ trait_row = 0
49
+ age_row = None
50
+ gender_row = None
51
+
52
+ def _extract_value_after_colon(x):
53
+ if x is None or (isinstance(x, float) and math.isnan(x)):
54
+ return None
55
+ s = str(x).strip().strip('"').strip("'")
56
+ if ':' in s:
57
+ s = s.split(':', 1)[1]
58
+ return s.strip() if s.strip() != '' else None
59
+
60
+ def convert_trait(x):
61
+ v = _extract_value_after_colon(x)
62
+ if v is None:
63
+ return None
64
+ vl = v.lower()
65
+ # Controls (no CKD): living donors and unaffected parts of tumor nephrectomy
66
+ if 'living donor' in vl or 'unaffected parts of tumor nephrectomy' in vl:
67
+ return 0
68
+ # All other disease groups are considered CKD cases in this cohort context
69
+ return 1
70
+
71
+ def convert_age(x):
72
+ v = _extract_value_after_colon(x)
73
+ if v is None:
74
+ return None
75
+ v = v.replace('years', '').replace('year', '').strip()
76
+ try:
77
+ return float(v)
78
+ except Exception:
79
+ return None
80
+
81
+ def convert_gender(x):
82
+ v = _extract_value_after_colon(x)
83
+ if v is None:
84
+ return None
85
+ vl = v.lower()
86
+ if vl in ['male', 'm', 'man', 'boy']:
87
+ return 1
88
+ if vl in ['female', 'f', 'woman', 'girl']:
89
+ return 0
90
+ return None
91
+
92
+ # 3) Save metadata (initial filtering)
93
+ is_trait_available = trait_row is not None
94
+ validate_and_save_cohort_info(
95
+ is_final=False,
96
+ cohort=cohort,
97
+ info_path=json_path,
98
+ is_gene_available=is_gene_available,
99
+ is_trait_available=is_trait_available
100
+ )
101
+
102
+ # 4) Clinical feature extraction (only if trait is available)
103
+ if trait_row is not None:
104
+ selected_clinical_df = geo_select_clinical_features(
105
+ clinical_df=clinical_data,
106
+ trait=trait,
107
+ trait_row=trait_row,
108
+ convert_trait=convert_trait,
109
+ age_row=age_row,
110
+ convert_age=convert_age,
111
+ gender_row=gender_row,
112
+ convert_gender=convert_gender
113
+ )
114
+ # Preview and save
115
+ preview = preview_df(selected_clinical_df)
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
+ requires_gene_mapping = True
130
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
131
+
132
+ # Step 5: Gene Annotation
133
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
134
+ gene_annotation = get_gene_annotation(soft_file)
135
+
136
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
137
+ print("Gene annotation preview:")
138
+ print(preview_df(gene_annotation))
139
+
140
+ # Step 6: Gene Identifier Mapping
141
+ # Inspect available annotation columns and choose mapping columns robustly
142
+ annot_cols = list(gene_annotation.columns)
143
+
144
+ # 1) Choose probe/ID column
145
+ id_candidates = ['ID', 'ID_REF', 'Probe Set ID', 'probeset_id', 'PROBESET_ID']
146
+ id_col = next((c for c in id_candidates if c in annot_cols), None)
147
+ if id_col is None:
148
+ id_col = annot_cols[0]
149
+
150
+ # 2) Try to find a true gene symbol column
151
+ symbol_priority = [
152
+ 'Gene Symbol', 'GENE_SYMBOL', 'GeneSymbol', 'Symbol', 'SYMBOL',
153
+ 'gene_assignment', 'Gene Assignment', 'GENE_ASSIGNMENT',
154
+ 'Associated Gene Name', 'ASSOCIATED_GENE_NAME', 'Associated_Gene_Name',
155
+ 'Gene symbol', 'gene symbol', 'Gene Title', 'GENE_TITLE', 'gene title',
156
+ 'DESCRIPTION', 'Description'
157
+ ]
158
+ # Build candidates: prioritize known names, then any column containing 'symbol' or 'assign' or 'title'/'desc'
159
+ symbol_candidates = [c for c in symbol_priority if c in annot_cols]
160
+ symbol_candidates += [c for c in annot_cols if ('symbol' in c.lower()) and (c not in symbol_candidates)]
161
+ symbol_candidates += [c for c in annot_cols if ('assign' in c.lower()) and (c not in symbol_candidates)]
162
+ symbol_candidates += [c for c in annot_cols if (('title' in c.lower()) or ('desc' in c.lower())) and (c not in symbol_candidates)]
163
+ # Exclude columns that are clearly IDs (e.g., Entrez) from symbol candidates
164
+ symbol_candidates = [c for c in symbol_candidates if 'entrez' not in c.lower()]
165
+
166
+ best_col = None
167
+ best_ratio = -1.0
168
+ sample_n = 2000
169
+ for c in symbol_candidates:
170
+ series_sample = gene_annotation[c].dropna().astype(str).head(sample_n)
171
+ if len(series_sample) == 0:
172
+ continue
173
+ extracted = series_sample.apply(extract_human_gene_symbols)
174
+ non_empty = extracted.apply(lambda lst: isinstance(lst, list) and len(lst) > 0).sum()
175
+ ratio = non_empty / len(series_sample)
176
+ if ratio > best_ratio:
177
+ best_ratio = ratio
178
+ best_col = c
179
+
180
+ probe_data = gene_data # original probe-level expression
181
+
182
+ if best_col is not None and best_ratio > 0:
183
+ # Map probes to true gene symbols
184
+ gene_symbol_col = best_col
185
+ mapping_df = get_gene_mapping(annotation=gene_annotation, prob_col=id_col, gene_col=gene_symbol_col)
186
+ gene_data = apply_gene_mapping(expression_df=probe_data, mapping_df=mapping_df)
187
+ print(f"Mapped probe-level data to gene symbols via column '{gene_symbol_col}'. Genes: {gene_data.shape[0]}")
188
+ else:
189
+ # Strict fallback: map to Entrez IDs only if necessary, using controlled parsing to avoid token explosion
190
+ if 'ENTREZ_GENE_ID' not in annot_cols:
191
+ raise RuntimeError(
192
+ "No suitable gene symbol column found in annotation, and ENTREZ_GENE_ID is unavailable. "
193
+ "Cannot perform probe-to-gene mapping safely."
194
+ )
195
+
196
+ def extract_entrez_ids_strict(cell):
197
+ # Accept only clean numeric Entrez IDs separated by common delimiters
198
+ s = '' if cell is None else str(cell)
199
+ # Normalize delimiters
200
+ for sep in ['///', '//', '||', '|', ';', ',', '\t', '\r', '\n']:
201
+ s = s.replace(sep, ' ')
202
+ tokens = [t for t in s.strip().split() if t]
203
+ ids = [t for t in tokens if t.isdigit() and t != '0']
204
+ # deduplicate preserving order
205
+ seen = set()
206
+ out = []
207
+ for i in ids:
208
+ if i not in seen:
209
+ seen.add(i)
210
+ out.append(i)
211
+ return out
212
+
213
+ # Build mapping to Entrez IDs
214
+ mapping_df = gene_annotation.loc[:, [id_col, 'ENTREZ_GENE_ID']].dropna()
215
+ mapping_df = mapping_df.rename(columns={id_col: 'ID', 'ENTREZ_GENE_ID': 'Gene'})
216
+ mapping_df['ID'] = mapping_df['ID'].astype(str).str.strip()
217
+ mapping_df = mapping_df[mapping_df['ID'] != '']
218
+ mapping_df['Gene'] = mapping_df['Gene'].apply(extract_entrez_ids_strict)
219
+ mapping_df['num_genes'] = mapping_df['Gene'].apply(len)
220
+ mapping_df = mapping_df.explode('Gene').dropna(subset=['Gene'])
221
+ if mapping_df.empty:
222
+ raise RuntimeError("After strict Entrez parsing, no probe-to-gene mappings remain. Aborting mapping step.")
223
+ mapping_df.set_index('ID', inplace=True)
224
+
225
+ merged_df = mapping_df.join(probe_data, how='inner')
226
+ expr_cols = [col for col in merged_df.columns if col not in ['Gene', 'num_genes']]
227
+ merged_df[expr_cols] = merged_df[expr_cols].div(merged_df['num_genes'].replace(0, 1), axis=0)
228
+ gene_data = merged_df.groupby('Gene')[expr_cols].sum()
229
+
230
+ # Sanity check on gene count to avoid spurious explosions
231
+ if gene_data.shape[0] > 100000:
232
+ raise RuntimeError(
233
+ f"Implausible number of unique genes after Entrez fallback ({gene_data.shape[0]}). "
234
+ "Stopping to prevent propagating erroneous mappings."
235
+ )
236
+ print(f"WARNING: No reliable gene symbol column found; aggregated to Entrez Gene IDs instead. "
237
+ f"Entrez genes: {gene_data.shape[0]}")
238
+
239
+ # Step 7: Data Normalization and Linking
240
+ import os
241
+ import pandas as pd
242
+
243
+ # Ensure clinical features are available in this step
244
+ try:
245
+ selected_clinical_df # check existence
246
+ except NameError:
247
+ # Load the clinical dataframe saved in Step 2
248
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
249
+
250
+ # 1. Normalize gene symbols or skip if Entrez IDs
251
+ note_msgs = []
252
+ # gene_data is produced in Step 6
253
+ try:
254
+ gene_data
255
+ except NameError:
256
+ # Fallback: if prior variable is missing but normalized gene data was saved, reload it as gene_data for downstream linking
257
+ if os.path.exists(out_gene_data_file):
258
+ gene_data = pd.read_csv(out_gene_data_file, index_col=0)
259
+ else:
260
+ raise RuntimeError("gene_data is not available and no saved gene data file was found.")
261
+
262
+ # Determine if indices are Entrez IDs (all digits)
263
+ is_entrez = pd.Series(gene_data.index.astype(str)).str.fullmatch(r'\d+').all()
264
+ if bool(is_entrez):
265
+ normalized_gene_data = gene_data.copy()
266
+ note_msgs.append("INFO: Gene indices are Entrez IDs; skipped symbol normalization.")
267
+ else:
268
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
269
+ note_msgs.append("INFO: Gene symbols normalized with synonym dictionary.")
270
+
271
+ # Ensure output directory exists and save normalized gene data
272
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
273
+ normalized_gene_data.to_csv(out_gene_data_file)
274
+
275
+ # 2. Link clinical and genetic data
276
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
277
+
278
+ # 3. Handle missing values
279
+ linked_data = handle_missing_values(linked_data, trait)
280
+
281
+ # 4. Determine bias and remove biased demographic features (trait kept for usability decision)
282
+ if (trait in linked_data.columns) and (len(linked_data) > 0):
283
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
284
+ else:
285
+ is_trait_biased, unbiased_linked_data = True, linked_data
286
+
287
+ # 5. Final validation and save cohort info
288
+ # Cast to native Python bool to avoid JSON serialization errors
289
+ is_gene_available_final = bool((normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0))
290
+ trait_in_index = bool(trait in selected_clinical_df.index)
291
+ trait_has_values = bool(selected_clinical_df.loc[trait].notna().any()) if trait_in_index else False
292
+ is_trait_available_final = bool(trait_in_index and trait_has_values)
293
+
294
+ note = " ".join(note_msgs)
295
+
296
+ is_usable = validate_and_save_cohort_info(
297
+ is_final=True,
298
+ cohort=cohort,
299
+ info_path=json_path,
300
+ is_gene_available=is_gene_available_final,
301
+ is_trait_available=is_trait_available_final,
302
+ is_biased=bool(is_trait_biased),
303
+ df=unbiased_linked_data,
304
+ note=note
305
+ )
306
+
307
+ # 6. Save linked data only if usable
308
+ if is_usable:
309
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
310
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Chronic_kidney_disease/code/GSE180394.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Chronic_kidney_disease"
6
+ cohort = "GSE180394"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Chronic_kidney_disease"
10
+ in_cohort_dir = "../DATA/GEO/Chronic_kidney_disease/GSE180394"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Chronic_kidney_disease/GSE180394.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Chronic_kidney_disease/gene_data/GSE180394.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Chronic_kidney_disease/clinical_data/GSE180394.csv"
16
+ json_path = "./output/z2/preprocess/Chronic_kidney_disease/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 # Affymetrix ST2.1 microarray platform indicates mRNA expression data
44
+
45
+ # 2) Variable availability and converters
46
+ # 0 -> 'sample group: ...' (variable for trait)
47
+ # 1 -> 'tissue: ...' (constant; not useful)
48
+ trait_row = 0
49
+ age_row = None
50
+ gender_row = None
51
+
52
+ def _extract_value(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
+ s = s.strip().strip('"').strip("'")
59
+ return s if s else None
60
+
61
+ def convert_trait(x):
62
+ """Binary: CKD (1) vs non-CKD control (0). Controls: living donors and unaffected parts of tumor nephrectomy."""
63
+ v = _extract_value(x)
64
+ if v is None:
65
+ return None
66
+ vl = v.lower().replace(' ', ' ').strip()
67
+
68
+ controls = {
69
+ 'living donor',
70
+ 'living donors',
71
+ 'unaffected parts of tumor nephrectomy',
72
+ 'unaffected part of tumor nephrectomy',
73
+ 'unaffected parts of tumour nephrectomy',
74
+ 'unaffected part of tumour nephrectomy',
75
+ 'unaffected tumour nephrectomy',
76
+ 'unaffected tumor nephrectomy',
77
+ 'healthy',
78
+ 'control',
79
+ 'normal'
80
+ }
81
+ if vl in controls:
82
+ return 0
83
+ return 1 # all other sample groups are CKD/disease
84
+
85
+ def convert_age(x):
86
+ v = _extract_value(x)
87
+ if v is None:
88
+ return None
89
+ m = re.search(r'[-+]?\d*\.?\d+', v)
90
+ if not m:
91
+ return None
92
+ try:
93
+ age = float(m.group())
94
+ if 0 <= age <= 120:
95
+ return age
96
+ except Exception:
97
+ pass
98
+ return None
99
+
100
+ def convert_gender(x):
101
+ v = _extract_value(x)
102
+ if v is None:
103
+ return None
104
+ vl = v.lower()
105
+ if vl in {'male', 'm', 'man', 'boy'}:
106
+ return 1
107
+ if vl in {'female', 'f', 'woman', 'girl'}:
108
+ return 0
109
+ return None
110
+
111
+ # 3) Save metadata (initial filtering)
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
+ # 4) Clinical Feature Extraction (only if trait is available)
122
+ if trait_row is not None:
123
+ assert 'clinical_data' in globals(), "clinical_data is not available."
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, n=5)
135
+ print(preview)
136
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
137
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
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
+ import re
160
+
161
+ # Preserve original expression data
162
+ expr_df = gene_data
163
+
164
+ # 1) Identify probe and gene identifier columns in the annotation
165
+ if 'ID' not in gene_annotation.columns:
166
+ raise ValueError("Probe ID column 'ID' not found in gene annotation.")
167
+ probe_col = 'ID'
168
+
169
+ if 'ENTREZ_GENE_ID' not in gene_annotation.columns:
170
+ raise ValueError("Entrez ID column 'ENTREZ_GENE_ID' not found in gene annotation.")
171
+ entrez_col = 'ENTREZ_GENE_ID'
172
+
173
+ print(f"Selected probe ID column: {probe_col}")
174
+ print(f"Selected gene identifier column: {entrez_col} (Entrez IDs)")
175
+
176
+ # 2) Build mapping: probe ID -> Entrez gene IDs (handle multiple Entrez IDs per probe)
177
+ ann = gene_annotation[[probe_col, entrez_col]].dropna()
178
+ ann[probe_col] = ann[probe_col].astype(str).str.strip()
179
+
180
+ # Keep only probes present in the expression matrix
181
+ ann = ann[ann[probe_col].isin(expr_df.index)]
182
+
183
+ # Extract all numeric Entrez IDs from the annotation field (handles multi-mapping)
184
+ ann['__entrez_list__'] = ann[entrez_col].astype(str).apply(lambda s: re.findall(r'\d+', s))
185
+ # Explode to one mapping per (probe, entrez)
186
+ m = ann[[probe_col, '__entrez_list__']].explode('__entrez_list__').dropna()
187
+ m = m.rename(columns={probe_col: 'ID', '__entrez_list__': 'Gene'})
188
+ # Drop empty entries if any
189
+ m = m[m['Gene'].astype(str).str.len() > 0]
190
+
191
+ # If no mappings found, fail explicitly
192
+ if m.empty:
193
+ raise ValueError("No valid Entrez mappings were extracted from the annotation; mapping would be empty.")
194
+
195
+ # 3) Distribute probe signal equally across mapped genes and aggregate to Entrez level
196
+ counts = m.groupby('ID').size().rename('num_genes')
197
+ m = m.join(counts, on='ID')
198
+
199
+ # Join expression values
200
+ m = m.set_index('ID').join(expr_df, how='inner')
201
+
202
+ # If join yields no rows, something is inconsistent
203
+ if m.empty:
204
+ raise ValueError("After joining mappings with expression data, no rows remain. "
205
+ "Probe IDs in annotation may not match expression matrix.")
206
+
207
+ expr_cols = [c for c in m.columns if c not in ['Gene', 'num_genes']]
208
+ # Avoid division by zero just in case
209
+ m['num_genes'] = m['num_genes'].replace(0, 1)
210
+ m[expr_cols] = m[expr_cols].div(m['num_genes'], axis=0)
211
+
212
+ # Sum per Entrez Gene ID
213
+ gene_data = m.groupby('Gene')[expr_cols].sum()
214
+
215
+ # Final sanity check
216
+ if gene_data.shape[0] == 0:
217
+ raise ValueError("Gene mapping produced an empty gene_data (0 genes) after aggregation.")
218
+
219
+ print(f"Mapped gene_data shape (Entrez-level): {gene_data.shape}")
220
+ print(f"First 10 Entrez IDs: {list(gene_data.index[:10])}")
221
+
222
+ # Step 7: Gene Identifier Mapping
223
+ import os
224
+ import re
225
+ import pandas as pd
226
+
227
+ # Reload probe-level expression to ensure we start from probes
228
+ expr_df = get_genetic_data(matrix_file)
229
+
230
+ # Work on a copy of the annotation
231
+ ann = gene_annotation.copy()
232
+ ann_cols = list(ann.columns)
233
+ print(f"Annotation columns: {ann_cols}")
234
+
235
+ # Identify probe ID column
236
+ probe_col = 'ID' if 'ID' in ann.columns else ('ID_REF' if 'ID_REF' in ann.columns else None)
237
+ if probe_col is None:
238
+ raise ValueError(f"No probe ID column found among: {ann_cols}")
239
+
240
+ # Helper to find a gene-symbol-like column (not used in this cohort but kept for robustness)
241
+ preferred_symbol_cols = [
242
+ 'Gene Symbol', 'GENE_SYMBOL', 'SYMBOL', 'GeneSymbol', 'Gene symbol',
243
+ 'gene_assignment', 'GENE_ASSIGNMENT', 'Gene Assignment', 'Gene assignment',
244
+ 'Associated Gene', 'ASSOCIATED_GENE', 'Associated Genes', 'ASSOCIATED_GENES',
245
+ 'GENE_SYMBOLS', 'Gene Symbols', 'gene_symbols', 'Symbol', 'Symbols'
246
+ ]
247
+
248
+ def find_column(candidates, columns):
249
+ lower_map = {c.lower(): c for c in columns}
250
+ for cand in candidates:
251
+ if cand.lower() in lower_map:
252
+ return lower_map[cand.lower()]
253
+ return None
254
+
255
+ symbol_col = find_column(preferred_symbol_cols, ann_cols)
256
+
257
+ # If a symbol-bearing column exists and is not Entrez, try symbol mapping first (fallback to Entrez otherwise)
258
+ use_symbol_mapping = symbol_col is not None and symbol_col != 'ENTREZ_GENE_ID'
259
+ gene_expr = None
260
+
261
+ if use_symbol_mapping:
262
+ print(f"Selected probe ID column: {probe_col}")
263
+ print(f"Selected gene-related column for mapping (symbol-bearing): {symbol_col}")
264
+ mapping_df = get_gene_mapping(ann, prob_col=probe_col, gene_col=symbol_col)
265
+ mapping_df = mapping_df[mapping_df['ID'].isin(expr_df.index)]
266
+ gene_expr = apply_gene_mapping(expression_df=expr_df, mapping_df=mapping_df)
267
+ # Try normalization; skip on failure
268
+ try:
269
+ gene_expr = normalize_gene_symbols_in_index(gene_expr)
270
+ except Exception as e:
271
+ print(f"WARNING: Gene symbol normalization skipped due to: {e}")
272
+
273
+ if gene_expr.shape[0] == 0:
274
+ print("WARNING: Symbol-based mapping yielded 0 genes. Falling back to Entrez ID-based aggregation.")
275
+ gene_expr = None
276
+
277
+ # Robust fallback: aggregate at Entrez ID level using ENTREZ_GENE_ID parsing
278
+ if gene_expr is None:
279
+ if 'ENTREZ_GENE_ID' not in ann.columns:
280
+ raise ValueError("ENTREZ_GENE_ID column not found; cannot perform Entrez-level mapping.")
281
+ print("Proceeding with Entrez ID-based mapping from ENTREZ_GENE_ID.")
282
+
283
+ # Prepare the subset annotation and keep only probes present in expression matrix
284
+ ann_sub = ann[[probe_col, 'ENTREZ_GENE_ID']].dropna()
285
+ ann_sub[probe_col] = ann_sub[probe_col].astype(str).str.strip()
286
+ ann_sub = ann_sub[ann_sub[probe_col].isin(expr_df.index)]
287
+
288
+ # Parse ENTREZ_GENE_ID with strict tokenization to keep only full numeric IDs; normalize leading zeros
289
+ def parse_entrez_list(s):
290
+ if pd.isna(s):
291
+ return []
292
+ s = str(s).strip()
293
+ # Normalize common separators to whitespace
294
+ for sep in ['///', ';', ',', '|']:
295
+ s = s.replace(sep, ' ')
296
+ toks = [t for t in s.split() if t]
297
+ toks = [t for t in toks if t.isdigit()]
298
+ # Normalize leading zeros by casting to int then back to str; drop zeros or invalid
299
+ out = []
300
+ for t in toks:
301
+ try:
302
+ v = int(t)
303
+ if v > 0:
304
+ out.append(str(v))
305
+ except Exception:
306
+ continue
307
+ # Deduplicate while preserving order
308
+ return list(dict.fromkeys(out))
309
+
310
+ ann_sub['__entrez_list__'] = ann_sub['ENTREZ_GENE_ID'].apply(parse_entrez_list)
311
+
312
+ # Explode to one (probe, entrez) per row
313
+ m = ann_sub[[probe_col, '__entrez_list__']].explode('__entrez_list__').dropna()
314
+ m = m.rename(columns={probe_col: 'ID', '__entrez_list__': 'Gene'})
315
+ # Drop any empty strings
316
+ m = m[m['Gene'].astype(str).str.len() > 0]
317
+
318
+ if m.empty:
319
+ raise ValueError("Entrez parsing produced an empty mapping; cannot aggregate to gene level.")
320
+
321
+ # Count mapped genes per probe and distribute probe signal equally
322
+ counts = m.groupby('ID').size().rename('num_genes')
323
+ m = m.set_index('ID')
324
+ m = m.join(expr_df, how='inner')
325
+ m = m.join(counts)
326
+
327
+ if m.empty:
328
+ raise ValueError("After joining mapping with expression data, no rows remain for Entrez aggregation.")
329
+
330
+ expr_cols = [c for c in m.columns if c not in ['Gene', 'num_genes']]
331
+ m['num_genes'] = m['num_genes'].replace(0, 1)
332
+ m[expr_cols] = m[expr_cols].div(m['num_genes'], axis=0)
333
+
334
+ # Aggregate to Entrez ID
335
+ gene_expr = m.groupby('Gene')[expr_cols].sum()
336
+
337
+ # Sanity checks and warnings
338
+ n_genes = gene_expr.shape[0]
339
+ if n_genes < 1000 or n_genes > 100000:
340
+ print(f"WARNING: Unusual number of Entrez genes after mapping: {n_genes}. "
341
+ "Please verify the platform annotation parsing.")
342
+
343
+ # Final assignment and reporting
344
+ gene_data = gene_expr
345
+ print(f"Mapped gene_data shape: {gene_data.shape}")
346
+ print(f"First 10 gene identifiers: {list(gene_data.index[:10])}")
347
+
348
+ # Save the processed gene expression data
349
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
350
+ gene_data.to_csv(out_gene_data_file, index=True)
351
+
352
+ # Step 8: Data Normalization and Linking
353
+ import os
354
+ import re
355
+
356
+ # 1. Normalize gene symbols only if the index looks like gene symbols; skip if Entrez IDs (digits only)
357
+ def _looks_like_entrez(idx_iter):
358
+ return all(re.fullmatch(r"\d+", str(x)) is not None for x in idx_iter)
359
+
360
+ if _looks_like_entrez(gene_data.index):
361
+ normalized_gene_data = gene_data.copy()
362
+ note = "INFO: Gene symbol normalization skipped because indices are Entrez Gene IDs; proceeding with Entrez-level data."
363
+ else:
364
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
365
+ note = "INFO: Gene symbols normalized using synonym dictionary."
366
+
367
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
368
+ normalized_gene_data.to_csv(out_gene_data_file, index=True)
369
+
370
+ # 2. Link clinical and genetic data
371
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
372
+
373
+ # 3. Handle missing values
374
+ linked_data = handle_missing_values(linked_data, trait)
375
+
376
+ # 4. Determine bias and remove biased demographic features
377
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
378
+
379
+ # 5. Final validation and save cohort info
380
+ is_usable = validate_and_save_cohort_info(
381
+ is_final=True,
382
+ cohort=cohort,
383
+ info_path=json_path,
384
+ is_gene_available=True,
385
+ is_trait_available=True,
386
+ is_biased=is_trait_biased,
387
+ df=unbiased_linked_data,
388
+ note=note
389
+ )
390
+
391
+ # 6. Save linked data only if usable
392
+ if is_usable:
393
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
394
+ unbiased_linked_data.to_csv(out_data_file, index=True)
output/preprocess/Chronic_kidney_disease/code/GSE45980.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Chronic_kidney_disease"
6
+ cohort = "GSE45980"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Chronic_kidney_disease"
10
+ in_cohort_dir = "../DATA/GEO/Chronic_kidney_disease/GSE45980"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Chronic_kidney_disease/GSE45980.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Chronic_kidney_disease/gene_data/GSE45980.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Chronic_kidney_disease/clinical_data/GSE45980.csv"
16
+ json_path = "./output/z2/preprocess/Chronic_kidney_disease/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 json
42
+
43
+ # 1) Gene Expression Data Availability
44
+ is_gene_available = True # mRNA profiling is reported in the series description
45
+
46
+ # 2) Variable Availability and Data Type Conversion
47
+ # Keys from Sample Characteristics Dictionary:
48
+ trait_row = 3 # 'clinical course: stable/progressive' -> progression status
49
+ age_row = 1 # 'age (yrs): <number>'
50
+ gender_row = 0 # 'gender: male/female'
51
+
52
+ def _after_colon(x):
53
+ if x is None:
54
+ return None
55
+ parts = str(x).split(":", 1)
56
+ return parts[1].strip() if len(parts) > 1 else str(x).strip()
57
+
58
+ def convert_trait(x):
59
+ v = _after_colon(x)
60
+ if v is None or v == "":
61
+ return None
62
+ v_low = v.strip().lower()
63
+ if v_low in {"progressive", "progression", "progressor"}:
64
+ return 1
65
+ if v_low in {"stable", "non-progressive", "nonprogressive", "non progressor", "non-progressor"}:
66
+ return 0
67
+ return None
68
+
69
+ def convert_age(x):
70
+ v = _after_colon(x)
71
+ if v is None or v == "":
72
+ return None
73
+ m = re.search(r"[-+]?\d*\.?\d+", v)
74
+ if not m:
75
+ return None
76
+ try:
77
+ val = float(m.group())
78
+ return int(val) if val.is_integer() else val
79
+ except Exception:
80
+ return None
81
+
82
+ def convert_gender(x):
83
+ v = _after_colon(x)
84
+ if v is None or v == "":
85
+ return None
86
+ v_low = v.strip().lower()
87
+ if v_low in {"male", "m"}:
88
+ return 1
89
+ if v_low in {"female", "f"}:
90
+ return 0
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 data 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, index=True)
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
+ # Decide mapping columns based on annotation preview and typical Agilent formats
141
+ prob_col = 'ID'
142
+ if 'GENE_SYMBOL' in gene_annotation.columns:
143
+ gene_col = 'GENE_SYMBOL'
144
+ elif 'GENE' in gene_annotation.columns:
145
+ gene_col = 'GENE'
146
+ else:
147
+ raise ValueError("No suitable gene symbol column found in annotation (expected 'GENE_SYMBOL' or 'GENE').")
148
+
149
+ # Build mapping dataframe
150
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=prob_col, gene_col=gene_col)
151
+
152
+ # Apply mapping to convert probe-level data to gene-level data
153
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
154
+
155
+ # Step 7: Data Normalization and Linking
156
+ import os
157
+ import pandas as pd
158
+
159
+ # 1. Normalize gene symbols and save gene data
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
165
+ # Ensure clinical dataframe is available (load from CSV if needed)
166
+ if 'selected_clinical_df' not in locals():
167
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
168
+
169
+ linked_before = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
170
+
171
+ # Track pre-filter stats
172
+ covariate_cols = [trait, 'Age', 'Gender']
173
+ pre_samples = len(linked_before)
174
+ pre_gene_cols = [c for c in linked_before.columns if c not in covariate_cols]
175
+ pre_genes = len(pre_gene_cols)
176
+
177
+ # 3. Handle missing values
178
+ linked_data = handle_missing_values(linked_before, trait)
179
+
180
+ # 4. Assess bias and remove biased covariates if necessary
181
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
182
+
183
+ # Track post-filter stats and removals
184
+ post_samples = len(unbiased_linked_data)
185
+ post_gene_cols = [c for c in unbiased_linked_data.columns if c not in [trait, 'Age', 'Gender']]
186
+ post_genes = len(post_gene_cols)
187
+ age_dropped = 'Age' not in unbiased_linked_data.columns and 'Age' in linked_data.columns
188
+ gender_dropped = 'Gender' not in unbiased_linked_data.columns and 'Gender' in linked_data.columns
189
+
190
+ note_parts = []
191
+ note_parts.append(f"INFO: Linked samples before/after missing-value filtering: {pre_samples} -> {post_samples}.")
192
+ note_parts.append(f"INFO: Gene features before/after filtering: {pre_genes} -> {post_genes}.")
193
+ if age_dropped:
194
+ note_parts.append("INFO: Age removed due to biased distribution.")
195
+ if gender_dropped:
196
+ note_parts.append("INFO: Gender removed due to biased distribution.")
197
+ note = " ".join(note_parts)
198
+
199
+ # 5. Final validation and save cohort info
200
+ is_usable = validate_and_save_cohort_info(
201
+ is_final=True,
202
+ cohort=cohort,
203
+ info_path=json_path,
204
+ is_gene_available=True,
205
+ is_trait_available=True,
206
+ is_biased=is_trait_biased,
207
+ df=unbiased_linked_data,
208
+ note=note
209
+ )
210
+
211
+ # 6. Save linked data if usable
212
+ if is_usable:
213
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
214
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Chronic_kidney_disease/code/GSE60861.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Chronic_kidney_disease"
6
+ cohort = "GSE60861"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Chronic_kidney_disease"
10
+ in_cohort_dir = "../DATA/GEO/Chronic_kidney_disease/GSE60861"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Chronic_kidney_disease/GSE60861.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Chronic_kidney_disease/gene_data/GSE60861.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Chronic_kidney_disease/clinical_data/GSE60861.csv"
16
+ json_path = "./output/z2/preprocess/Chronic_kidney_disease/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 # SuperSeries includes mRNA expression; likely contains suitable gene expression data
41
+
42
+ # Step 2: Identify rows for variables based on the Sample Characteristics Dictionary
43
+ # Trait (Chronic_kidney_disease) is constant (all diseased biopsies); treat as not available for association analysis
44
+ trait_row = None
45
+
46
+ # Age and Gender are available:
47
+ age_row = 1 # contains multiple "age (yrs):" entries (also includes some gender entries which we'll ignore in conversion)
48
+ gender_row = 0 # contains "gender: male/female"
49
+
50
+ # Step 2.2: Conversion functions
51
+ import re
52
+ from typing import Optional
53
+
54
+ def _after_colon(x: str) -> str:
55
+ if x is None:
56
+ return ""
57
+ parts = str(x).split(":", 1)
58
+ return parts[1].strip() if len(parts) > 1 else str(x).strip()
59
+
60
+ def convert_trait(x: str) -> Optional[int]:
61
+ """
62
+ Binary: Chronic kidney disease presence (1) vs absence (0).
63
+ In this dataset, samples are CKD kidney biopsies; if used, most fields imply CKD=1.
64
+ This function is defined for completeness but trait_row is None, so it won't be used.
65
+ """
66
+ if x is None:
67
+ return None
68
+ s = str(x).strip().lower()
69
+ val = _after_colon(s)
70
+
71
+ # Map common controls to 0
72
+ if any(k in s for k in ["control", "normal", "healthy"]):
73
+ return 0
74
+
75
+ # Diagnosis or clinical course imply CKD presence
76
+ if "diagnosis" in s:
77
+ return 1 if val and val not in ["", "unknown", "other/unknown"] else None
78
+ if "clinical course" in s:
79
+ if val in ["stable", "progressive"]:
80
+ return 1
81
+ return None
82
+ if "tissue" in s and "kidney biopsy" in s:
83
+ return 1 # kidney disease biopsy implies CKD case in this context
84
+
85
+ return None
86
+
87
+ def convert_age(x: str) -> Optional[float]:
88
+ """
89
+ Continuous age in years. Extract numeric value when header mentions age.
90
+ """
91
+ if x is None:
92
+ return None
93
+ s = str(x).strip().lower()
94
+ if "age" not in s:
95
+ return None
96
+ val = _after_colon(s)
97
+ # Extract first numeric token
98
+ m = re.search(r"[-+]?\d*\.?\d+", val)
99
+ if not m:
100
+ return None
101
+ try:
102
+ return float(m.group(0))
103
+ except Exception:
104
+ return None
105
+
106
+ def convert_gender(x: str) -> Optional[int]:
107
+ """
108
+ Binary: female -> 0, male -> 1.
109
+ """
110
+ if x is None:
111
+ return None
112
+ s = str(x).strip().lower()
113
+ if "gender" not in s:
114
+ return None
115
+ val = _after_colon(s)
116
+ if "female" in val:
117
+ return 0
118
+ if "male" in val:
119
+ return 1
120
+ return None
121
+
122
+ # Step 3: Initial filtering and save metadata
123
+ is_trait_available = trait_row is not None
124
+ _ = validate_and_save_cohort_info(
125
+ is_final=False,
126
+ cohort=cohort,
127
+ info_path=json_path,
128
+ is_gene_available=is_gene_available,
129
+ is_trait_available=is_trait_available
130
+ )
131
+
132
+ # Step 4: Clinical Feature Extraction (skip because trait_row is None)
133
+ if trait_row is not None:
134
+ selected_clinical_df = geo_select_clinical_features(
135
+ clinical_df=clinical_data,
136
+ trait=trait,
137
+ trait_row=trait_row,
138
+ convert_trait=convert_trait,
139
+ age_row=age_row,
140
+ convert_age=convert_age,
141
+ gender_row=gender_row,
142
+ convert_gender=convert_gender
143
+ )
144
+ preview = preview_df(selected_clinical_df, n=5)
145
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
146
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
147
+
148
+ # Step 3: Gene Data Extraction
149
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
150
+ gene_data = get_genetic_data(matrix_file)
151
+
152
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
153
+ print(gene_data.index[:20])
154
+
155
+ # Step 4: Gene Identifier Review
156
+ print("requires_gene_mapping = True")
157
+
158
+ # Step 5: Gene Annotation
159
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
160
+ gene_annotation = get_gene_annotation(soft_file)
161
+
162
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
163
+ print("Gene annotation preview:")
164
+ print(preview_df(gene_annotation))
165
+
166
+ # Step 6: Gene Identifier Mapping
167
+ # Determine appropriate columns for probe IDs and gene symbols from the annotation
168
+ id_col = 'ID' if 'ID' in gene_annotation.columns else ('SPOT_ID' if 'SPOT_ID' in gene_annotation.columns else None)
169
+ if id_col is None:
170
+ raise ValueError("No suitable probe ID column found in gene annotation.")
171
+
172
+ # Prefer canonical gene symbol column, with fallbacks
173
+ for candidate in ['GENE_SYMBOL', 'GENE', 'GENE_NAME']:
174
+ if candidate in gene_annotation.columns:
175
+ gene_symbol_col = candidate
176
+ break
177
+ else:
178
+ raise ValueError("No suitable gene symbol column found in gene annotation.")
179
+
180
+ # Build mapping and convert probe-level data to gene-level expression
181
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=id_col, gene_col=gene_symbol_col)
182
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
183
+
184
+ # Step 7: Data Normalization and Linking
185
+ # Normalize and save gene expression data; trait is unavailable for this cohort.
186
+ import os
187
+ import json
188
+
189
+ # 1. Normalize the obtained gene data and save to file
190
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
191
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
192
+ normalized_gene_data.to_csv(out_gene_data_file)
193
+
194
+ # 2-6. If trait is unavailable (trait_row was None), skip linking and final validation.
195
+ # Avoid overwriting initial metadata recorded in Step 2.
196
+ if 'trait_row' in globals() and trait_row is None:
197
+ print("Trait is unavailable (trait_row is None). Skipping linking, missing value handling, bias checks, and final validation.")
198
+ need_initial_record = True
199
+ if os.path.exists(json_path):
200
+ try:
201
+ with open(json_path, "r") as f:
202
+ records = json.load(f)
203
+ if cohort in records:
204
+ need_initial_record = False
205
+ except Exception:
206
+ need_initial_record = True
207
+ if need_initial_record:
208
+ _ = validate_and_save_cohort_info(
209
+ is_final=False,
210
+ cohort=cohort,
211
+ info_path=json_path,
212
+ is_gene_available=True,
213
+ is_trait_available=False
214
+ )
output/preprocess/Chronic_kidney_disease/code/GSE66494.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Chronic_kidney_disease"
6
+ cohort = "GSE66494"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Chronic_kidney_disease"
10
+ in_cohort_dir = "../DATA/GEO/Chronic_kidney_disease/GSE66494"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Chronic_kidney_disease/GSE66494.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Chronic_kidney_disease/gene_data/GSE66494.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Chronic_kidney_disease/clinical_data/GSE66494.csv"
16
+ json_path = "./output/z2/preprocess/Chronic_kidney_disease/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 gene expression data availability
40
+ is_gene_available = True # Microarray gene expression data per background info
41
+
42
+ # Step 2: Define availability and converters
43
+ # Trait: Use sample type as proxy (Renal biopsy specimens -> CKD, Normal kidney total RNA -> control)
44
+ trait_row = 1
45
+ age_row = None
46
+ gender_row = None
47
+
48
+ def _extract_value(x):
49
+ if x is None:
50
+ return None
51
+ s = str(x).strip()
52
+ if s.lower() in {"na", "nan", ""}:
53
+ return None
54
+ if ":" in s:
55
+ return s.split(":", 1)[1].strip()
56
+ return s
57
+
58
+ def convert_trait(x):
59
+ v = _extract_value(x)
60
+ if v is None:
61
+ return None
62
+ vl = v.lower()
63
+ if "renal biopsy" in vl:
64
+ return 1
65
+ if "chronic kidney disease" in vl or "ckd" in vl:
66
+ return 1
67
+ if "normal kidney" in vl:
68
+ return 0
69
+ return None
70
+
71
+ def convert_age(x):
72
+ v = _extract_value(x)
73
+ if v is None:
74
+ return None
75
+ # Extract first number as age
76
+ import re
77
+ m = re.search(r"(\d+(\.\d+)?)", v)
78
+ if m:
79
+ try:
80
+ val = float(m.group(1))
81
+ return val
82
+ except Exception:
83
+ return None
84
+ return None
85
+
86
+ def convert_gender(x):
87
+ v = _extract_value(x)
88
+ if v is None:
89
+ return None
90
+ vl = v.lower()
91
+ if vl in {"male", "m"}:
92
+ return 1
93
+ if vl in {"female", "f"}:
94
+ return 0
95
+ return None
96
+
97
+ # Step 3: Initial filtering and save 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
+ # Step 4: Clinical feature extraction, preview, and save
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
+ preview = preview_df(selected_clinical_df)
121
+ print(preview)
122
+
123
+ import os
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
+ # Affymetrix/Agilent-like probe IDs (e.g., A_23_P100001) are not human gene symbols
136
+ requires_gene_mapping = True
137
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
138
+
139
+ # Step 5: Gene Annotation
140
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
141
+ gene_annotation = get_gene_annotation(soft_file)
142
+
143
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
144
+ print("Gene annotation preview:")
145
+ print(preview_df(gene_annotation))
146
+
147
+ # Step 6: Gene Identifier Mapping
148
+ # Identify the appropriate columns for mapping: probe IDs ('ID') to gene symbols ('GENE_SYMBOL')
149
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')
150
+
151
+ # Apply the mapping to convert probe-level data to gene-level expression
152
+ probe_data = gene_data
153
+ gene_data = apply_gene_mapping(expression_df=probe_data, mapping_df=mapping_df)
154
+
155
+ # Step 7: Data Normalization and Linking
156
+ import os
157
+ import json
158
+ import pandas as pd
159
+
160
+ # 1. Normalize gene symbols and save
161
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
162
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
163
+ normalized_gene_data.to_csv(out_gene_data_file)
164
+
165
+ # 2. Link clinical and genetic data
166
+ # Use the clinical features from memory; if not present, load from saved file.
167
+ try:
168
+ selected_clinical_df # noqa: F401
169
+ except NameError:
170
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
171
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
172
+
173
+ # 3. Handle missing values
174
+ linked_data = handle_missing_values(linked_data, trait)
175
+
176
+ # 4. Bias check and removal for demographic features
177
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
178
+
179
+ # 5. Final validation and save cohort info
180
+ # Force-cast to native Python bools to avoid numpy/pandas scalar issues in JSON serialization
181
+ is_gene_available_final = bool(normalized_gene_data.shape[0] > 0 and normalized_gene_data.shape[1] > 0)
182
+ is_trait_available_final = bool((trait in linked_data.columns) and bool(linked_data[trait].notna().any()))
183
+ is_trait_biased_bool = bool(is_trait_biased)
184
+
185
+ try:
186
+ is_usable = validate_and_save_cohort_info(
187
+ is_final=True,
188
+ cohort=cohort,
189
+ info_path=json_path,
190
+ is_gene_available=is_gene_available_final,
191
+ is_trait_available=is_trait_available_final,
192
+ is_biased=is_trait_biased_bool,
193
+ df=unbiased_linked_data,
194
+ note="INFO: Trait derived from sample type (renal biopsy specimens vs normal kidney RNA)."
195
+ )
196
+ except TypeError:
197
+ # Fallback: sanitize and write record manually if JSON serialization fails
198
+ df = unbiased_linked_data
199
+ ig = bool(is_gene_available_final)
200
+ it = bool(is_trait_available_final)
201
+ if len(df) <= 0 or len(df.columns) <= 4:
202
+ print(f"Abnormality detected in the cohort: {cohort}. Preprocessing failed.")
203
+ ig = False
204
+ if len(df) <= 0:
205
+ it = False
206
+ is_available = bool(ig and it)
207
+ usable = bool(is_available and (is_trait_biased_bool is False))
208
+
209
+ record = {
210
+ "is_usable": bool(usable),
211
+ "is_gene_available": bool(ig),
212
+ "is_trait_available": bool(it),
213
+ "is_available": bool(is_available),
214
+ "is_biased": (bool(is_trait_biased_bool) if is_available else None),
215
+ "has_age": ("Age" in df.columns if is_available else None),
216
+ "has_gender": ("Gender" in df.columns if is_available else None),
217
+ "sample_size": (int(len(df)) if is_available else None),
218
+ "note": "INFO: Trait derived from sample type (renal biopsy specimens vs normal kidney RNA)."
219
+ }
220
+
221
+ os.makedirs(os.path.dirname(json_path), exist_ok=True)
222
+ if os.path.exists(json_path):
223
+ try:
224
+ with open(json_path, "r") as f:
225
+ records = json.load(f)
226
+ except Exception:
227
+ records = {}
228
+ else:
229
+ records = {}
230
+ records[cohort] = record
231
+ with open(json_path, "w") as f:
232
+ json.dump(records, f)
233
+ is_usable = usable
234
+
235
+ # 6. Save linked data only if usable
236
+ if is_usable:
237
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
238
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Chronic_kidney_disease/code/GSE69438.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Chronic_kidney_disease"
6
+ cohort = "GSE69438"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Chronic_kidney_disease"
10
+ in_cohort_dir = "../DATA/GEO/Chronic_kidney_disease/GSE69438"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Chronic_kidney_disease/GSE69438.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Chronic_kidney_disease/gene_data/GSE69438.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Chronic_kidney_disease/clinical_data/GSE69438.csv"
16
+ json_path = "./output/z2/preprocess/Chronic_kidney_disease/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 (from "Tissue Transcriptome..." title -> gene expression likely available)
42
+ is_gene_available = True
43
+
44
+ # 2) Variable availability from Sample Characteristics Dictionary
45
+ # Given dictionary from previous step
46
+ sample_char_dict = {0: ['tissue: Tubulointerstitium from kidney biopsy']}
47
+
48
+ # No trait/age/gender keys present; only tissue information and it's constant
49
+ trait_row = None
50
+ age_row = None
51
+ gender_row = None
52
+
53
+ # 2.2 Conversion functions
54
+ def _after_colon(x):
55
+ if x is None:
56
+ return None
57
+ s = str(x)
58
+ parts = s.split(":", 1)
59
+ return parts[1].strip() if len(parts) == 2 else s.strip()
60
+
61
+ def convert_trait(x):
62
+ # Map CKD-related disease labels to 1; controls/healthy to 0; else None
63
+ v = _after_colon(x)
64
+ if v is None or v == "":
65
+ return None
66
+ s = v.lower()
67
+
68
+ # positive CKD indicators
69
+ positive_terms = [
70
+ "ckd", "chronic kidney disease", "end-stage renal disease", "esrd",
71
+ "kidney disease", "renal failure", "diabetic nephropathy",
72
+ "lupus nephritis", "focal segmental glomerulosclerosis", "fsgs",
73
+ "membranous glomerulonephritis", "iga nephropathy", "nephropathy"
74
+ ]
75
+ if any(t in s for t in positive_terms):
76
+ return 1
77
+
78
+ negative_terms = ["control", "healthy", "normal", "non-disease", "donor", "reference"]
79
+ if any(t in s for t in negative_terms):
80
+ return 0
81
+
82
+ # If explicitly states "no kidney disease"
83
+ if "no kidney disease" in s or "without kidney disease" in s:
84
+ return 0
85
+
86
+ return None
87
+
88
+ def convert_age(x):
89
+ v = _after_colon(x)
90
+ if v is None or v == "":
91
+ return None
92
+ s = v.lower()
93
+ if s in {"na", "n/a", "nan", "none", "unknown", "not available"}:
94
+ return None
95
+ # extract first number as age (years); handle formats like "45", "45 years", "45.0", "age 45"
96
+ m = re.search(r"(\d+(\.\d+)?)", s)
97
+ if not m:
98
+ return None
99
+ try:
100
+ age_val = float(m.group(1))
101
+ except Exception:
102
+ return None
103
+ # Filter unreasonable ages
104
+ if 0 <= age_val <= 120:
105
+ return age_val
106
+ return None
107
+
108
+ def convert_gender(x):
109
+ v = _after_colon(x)
110
+ if v is None or v == "":
111
+ return None
112
+ s = v.strip().lower()
113
+ # female -> 0, male -> 1
114
+ if s in {"female", "f", "woman", "women", "girl"}:
115
+ return 0
116
+ if s in {"male", "m", "man", "men", "boy"}:
117
+ return 1
118
+ return None
119
+
120
+ # 3) Save metadata (initial filtering)
121
+ is_trait_available = trait_row is not None
122
+ _ = validate_and_save_cohort_info(
123
+ is_final=False,
124
+ cohort=cohort,
125
+ info_path=json_path,
126
+ is_gene_available=is_gene_available,
127
+ is_trait_available=is_trait_available
128
+ )
129
+
130
+ # 4) Clinical feature extraction skipped because trait_row is None
131
+ # (No action needed here)
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
+ # Identify the appropriate columns for mapping: 'ID' matches the expression identifiers, 'ORF' holds gene symbols
154
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='ORF')
155
+
156
+ # Apply the mapping to convert probe/ID-level data to gene symbol-level expression
157
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
158
+
159
+ # Step 7: Data Normalization and Linking
160
+ import os
161
+ import pandas as pd
162
+
163
+ # 1. Normalize gene symbols and save
164
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
165
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
166
+ normalized_gene_data.to_csv(out_gene_data_file)
167
+
168
+ # Determine availability flags
169
+ is_gene_available_flag = normalized_gene_data.shape[0] > 0 and normalized_gene_data.shape[1] > 0
170
+
171
+ # 2-6. If clinical data exists, proceed to link; otherwise, perform initial filtering metadata update only.
172
+ if 'selected_clinical_data' in globals() and isinstance(selected_clinical_data, pd.DataFrame):
173
+ # Link clinical and genetic data
174
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
175
+
176
+ # Handle missing values
177
+ linked_data = handle_missing_values(linked_data, trait)
178
+
179
+ # Judge and remove biased features
180
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
181
+
182
+ # Final validation and save metadata
183
+ is_usable = validate_and_save_cohort_info(
184
+ True, cohort, json_path,
185
+ is_gene_available_flag, True,
186
+ is_trait_biased, unbiased_linked_data
187
+ )
188
+
189
+ # Save linked dataset if usable
190
+ if is_usable:
191
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
192
+ unbiased_linked_data.to_csv(out_data_file)
193
+
194
+ else:
195
+ # Trait not available -> record initial filtering metadata only
196
+ _ = validate_and_save_cohort_info(
197
+ is_final=False,
198
+ cohort=cohort,
199
+ info_path=json_path,
200
+ is_gene_available=is_gene_available_flag,
201
+ is_trait_available=False
202
+ )
output/preprocess/Chronic_kidney_disease/code/TCGA.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Chronic_kidney_disease"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z2/preprocess/Chronic_kidney_disease/TCGA.csv"
12
+ out_gene_data_file = "./output/z2/preprocess/Chronic_kidney_disease/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z2/preprocess/Chronic_kidney_disease/clinical_data/TCGA.csv"
14
+ json_path = "./output/z2/preprocess/Chronic_kidney_disease/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import pandas as pd
20
+
21
+ # Inspect subdirectories under TCGA root
22
+ all_subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
23
+
24
+ # Define strict synonyms for Chronic Kidney Disease; TCGA cancer cohorts (e.g., KIRC/KIRP/KICH) are not CKD and should be skipped
25
+ ckd_keywords_strict = [
26
+ 'chronic_kidney_disease', 'ckd', 'chronic kidney disease',
27
+ 'renal failure', 'chronic renal', 'nephropathy',
28
+ 'kidney disease', 'end-stage renal', 'end stage renal', 'esrd'
29
+ ]
30
+
31
+ def normalize_name(name: str) -> str:
32
+ return name.lower().replace('-', '_').replace(' ', '_').replace('(', '').replace(')', '')
33
+
34
+ normalized_map = {d: normalize_name(d) for d in all_subdirs}
35
+ strict_matches = [d for d, n in normalized_map.items() if any(k in n for k in ckd_keywords_strict)]
36
+
37
+ if len(strict_matches) == 0:
38
+ # No suitable cohort for CKD in TCGA; skip this trait
39
+ validate_and_save_cohort_info(
40
+ is_final=False,
41
+ cohort="TCGA",
42
+ info_path=json_path,
43
+ is_gene_available=False,
44
+ is_trait_available=False
45
+ )
46
+ else:
47
+ # Choose the most specific match (longest name as a simple heuristic)
48
+ cohort_name = sorted(strict_matches, key=lambda x: len(x), reverse=True)[0]
49
+ cohort_dir = os.path.join(tcga_root_dir, cohort_name)
50
+
51
+ # Identify clinical and genetic files
52
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
53
+
54
+ # Load dataframes
55
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False)
56
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False)
57
+
58
+ # Print clinical column names for further analysis
59
+ print(list(clinical_df.columns))
output/preprocess/Chronic_kidney_disease/cohort_info.json CHANGED
@@ -1,92 +1 @@
1
- {
2
- "GSE69438": {
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
- "GSE66494": {
13
- "is_usable": false,
14
- "is_gene_available": false,
15
- "is_trait_available": false,
16
- "is_available": false,
17
- "is_biased": null,
18
- "has_age": null,
19
- "has_gender": null,
20
- "sample_size": null
21
- },
22
- "GSE60861": {
23
- "is_usable": true,
24
- "is_gene_available": true,
25
- "is_trait_available": true,
26
- "is_available": true,
27
- "is_biased": false,
28
- "has_age": true,
29
- "has_gender": false,
30
- "sample_size": 29
31
- },
32
- "GSE45980": {
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": true,
39
- "has_gender": true,
40
- "sample_size": 43
41
- },
42
- "GSE180393": {
43
- "is_usable": false,
44
- "is_gene_available": false,
45
- "is_trait_available": false,
46
- "is_available": false,
47
- "is_biased": null,
48
- "has_age": null,
49
- "has_gender": null,
50
- "sample_size": null
51
- },
52
- "GSE142153": {
53
- "is_usable": true,
54
- "is_gene_available": true,
55
- "is_trait_available": true,
56
- "is_available": true,
57
- "is_biased": false,
58
- "has_age": false,
59
- "has_gender": false,
60
- "sample_size": 40
61
- },
62
- "GSE104954": {
63
- "is_usable": false,
64
- "is_gene_available": true,
65
- "is_trait_available": true,
66
- "is_available": true,
67
- "is_biased": true,
68
- "has_age": false,
69
- "has_gender": false,
70
- "sample_size": 132
71
- },
72
- "GSE104948": {
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": 122
81
- },
82
- "TCGA": {
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": true,
89
- "has_gender": true,
90
- "sample_size": 323
91
- }
92
- }
 
1
+ {"GSE69438": {"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}, "GSE66494": {"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": 61, "note": "INFO: Trait derived from sample type (renal biopsy specimens vs normal kidney RNA)."}, "GSE60861": {"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}, "GSE45980": {"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": 43, "note": "INFO: Linked samples before/after missing-value filtering: 43 -> 43. INFO: Gene features before/after filtering: 8116 -> 8116."}, "GSE180394": {"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": 59, "note": "INFO: Gene symbol normalization skipped because indices are Entrez Gene IDs; proceeding with Entrez-level data."}, "GSE180393": {"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": 62, "note": "INFO: Gene indices are Entrez IDs; skipped symbol normalization."}, "GSE142153": {"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": 40, "note": "INFO: Only trait available; no age/gender fields in clinical annotations."}, "GSE104954": {"is_usable": false, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": true, "has_age": false, "has_gender": false, "sample_size": 132, "note": "INFO: Trait appears highly imbalanced (few controls vs many CKD cases); dataset likely flagged as biased."}, "GSE104948": {"is_usable": false, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": true, "has_age": false, "has_gender": false, "sample_size": 125, "note": "INFO: Diagnosis-based heuristic used for case/control: donors/tumor/normal/healthy treated as controls (0); all other diagnoses treated as CKD cases (1)."}, "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/Chronic_kidney_disease/gene_data/GSE142153.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Colon_and_Rectal_Cancer/code/GSE46517.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Colon_and_Rectal_Cancer"
6
+ cohort = "GSE46517"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Colon_and_Rectal_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Colon_and_Rectal_Cancer/GSE46517"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Colon_and_Rectal_Cancer/GSE46517.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Colon_and_Rectal_Cancer/gene_data/GSE46517.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Colon_and_Rectal_Cancer/clinical_data/GSE46517.csv"
16
+ json_path = "./output/z2/preprocess/Colon_and_Rectal_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 (Affymetrix U133A mRNA microarray => yes)
42
+ is_gene_available = True
43
+
44
+ # 2) Variable availability and converters
45
+ # Trait is Colon_and_Rectal_Cancer, but this series is melanoma/nevi/normal skin;
46
+ # no field indicates colon/rectal cancer status -> treat as unavailable.
47
+ trait_row = None
48
+
49
+ # Age and gender appear across multiple rows; choose one with many entries observed.
50
+ age_row = 11
51
+ gender_row = 11
52
+
53
+ def _after_colon(value: str) -> str:
54
+ if value is None:
55
+ return ""
56
+ s = str(value)
57
+ return s.split(":", 1)[1].strip() if ":" in s else s.strip()
58
+
59
+ def convert_trait(x):
60
+ # Binary mapping for Colon_and_Rectal_Cancer (1 = CRC, 0 = not CRC)
61
+ # Not used since trait_row is None, but kept for completeness.
62
+ val = _after_colon(x).lower()
63
+ if not val:
64
+ return None
65
+ # Positive indicators for CRC
66
+ crc_pos = [
67
+ "colorectal", "colon adenocarcinoma", "rectal adenocarcinoma",
68
+ "colon cancer", "rectal cancer", "colorectal cancer", "crc"
69
+ ]
70
+ if any(k in val for k in crc_pos):
71
+ return 1
72
+ # If value explicitly indicates other diseases (e.g., melanoma), map to 0
73
+ non_crc_indicators = ["melanoma", "nevus", "normal skin", "melanocytes", "skin"]
74
+ if any(k in val for k in non_crc_indicators):
75
+ return 0
76
+ return None
77
+
78
+ def convert_age(x):
79
+ val = _after_colon(x).lower()
80
+ if not val:
81
+ return None
82
+ # Parse formats like "72y 4m", "41y", "85y 5 m"
83
+ y_match = re.search(r'(\d+)\s*y', val)
84
+ if not y_match:
85
+ return None
86
+ years = int(y_match.group(1))
87
+ m_match = re.search(r'(\d+)\s*m', val)
88
+ months = int(m_match.group(1)) if m_match else 0
89
+ return years + months / 12.0
90
+
91
+ def convert_gender(x):
92
+ val = _after_colon(x).lower()
93
+ if not val:
94
+ return None
95
+ if val.startswith('male') or val == 'm':
96
+ return 1
97
+ if val.startswith('female') or val == 'f':
98
+ return 0
99
+ return None
100
+
101
+ # 3) Save metadata (initial filtering)
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
+ # 4) Clinical feature extraction (skip because trait_row is None)
112
+ # If trait_row were available:
113
+ # if trait_row is not None:
114
+ # selected_clinical = 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=convert_age,
121
+ # gender_row=gender_row,
122
+ # convert_gender=convert_gender
123
+ # )
124
+ # _ = preview_df(selected_clinical)
125
+ # selected_clinical.to_csv(out_clinical_data_file)
output/preprocess/Colon_and_Rectal_Cancer/code/GSE46862.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Colon_and_Rectal_Cancer"
6
+ cohort = "GSE46862"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Colon_and_Rectal_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Colon_and_Rectal_Cancer/GSE46862"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Colon_and_Rectal_Cancer/GSE46862.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Colon_and_Rectal_Cancer/gene_data/GSE46862.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Colon_and_Rectal_Cancer/clinical_data/GSE46862.csv"
16
+ json_path = "./output/z2/preprocess/Colon_and_Rectal_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 # Affymetrix GeneChip arrays -> mRNA expression
43
+
44
+ # 2) Variable availability and converters
45
+ # Trait (Colon_and_Rectal_Cancer) is constant across samples in this series (all rectal cancer patients) -> not available
46
+ trait_row = None
47
+
48
+ # Age and Gender are available
49
+ age_row = 1
50
+ gender_row = 2
51
+
52
+ def _after_colon(value: str) -> str:
53
+ if value is None:
54
+ return ""
55
+ parts = str(value).split(":", 1)
56
+ return parts[1].strip() if len(parts) > 1 else str(value).strip()
57
+
58
+ def convert_trait(value):
59
+ # Not applicable for this dataset as everyone has rectal cancer; return None
60
+ return None
61
+
62
+ def convert_age(value):
63
+ v = _after_colon(value).lower()
64
+ # Extract the first integer/float number found
65
+ m = re.search(r'[-+]?\d*\.?\d+', v)
66
+ if m:
67
+ try:
68
+ return float(m.group())
69
+ except Exception:
70
+ return None
71
+ return None
72
+
73
+ def convert_gender(value):
74
+ v = _after_colon(value).strip().lower()
75
+ if v in {"female", "f"}:
76
+ return 0
77
+ if v in {"male", "m"}:
78
+ return 1
79
+ return None
80
+
81
+ # 3) Save metadata (initial filtering)
82
+ is_trait_available = trait_row is not None
83
+ _ = validate_and_save_cohort_info(
84
+ is_final=False,
85
+ cohort=cohort,
86
+ info_path=json_path,
87
+ is_gene_available=is_gene_available,
88
+ is_trait_available=is_trait_available
89
+ )
90
+
91
+ # 4) Clinical feature extraction (skip if trait_row is None)
92
+ if trait_row is not None:
93
+ selected_clinical_df = geo_select_clinical_features(
94
+ clinical_df=clinical_data,
95
+ trait=trait,
96
+ trait_row=trait_row,
97
+ convert_trait=convert_trait,
98
+ age_row=age_row,
99
+ convert_age=convert_age,
100
+ gender_row=gender_row,
101
+ convert_gender=convert_gender
102
+ )
103
+ clinical_preview = preview_df(selected_clinical_df)
104
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
105
+ selected_clinical_df.to_csv(out_clinical_data_file, index=False)
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
+ print("requires_gene_mapping = True")
116
+
117
+ # Step 5: Gene Annotation
118
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
119
+ gene_annotation = get_gene_annotation(soft_file)
120
+
121
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
122
+ print("Gene annotation preview:")
123
+ print(preview_df(gene_annotation))
124
+
125
+ # Step 6: Gene Identifier Mapping
126
+ # Identify columns for probe IDs and gene symbols from the annotation preview
127
+ probe_col = 'ID'
128
+ gene_symbol_col = 'gene_assignment'
129
+
130
+ # 2) Build mapping dataframe
131
+ gene_mapping = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
132
+
133
+ # 3) Apply mapping to convert probe-level data to gene-level expression
134
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=gene_mapping)
135
+
136
+ # Step 7: Data Normalization and Linking
137
+ import os
138
+
139
+ # 1) Normalize gene symbols and save gene expression data
140
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
141
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
142
+ normalized_gene_data.to_csv(out_gene_data_file)
143
+
144
+ # Since trait is unavailable (trait_row was None), skip linking and downstream steps.
145
+ linked_data = None
146
+ unbiased_linked_data = None
147
+
148
+ # 5) Final validation and save cohort info
149
+ note = ("INFO: Trait unavailable for this cohort (all rectal cancer; no usable trait variation for "
150
+ f"{trait}). Gene expression processed and saved; skipped clinical-genetic linking and downstream steps.")
151
+ is_usable = validate_and_save_cohort_info(
152
+ is_final=True,
153
+ cohort=cohort,
154
+ info_path=json_path,
155
+ is_gene_available=True,
156
+ is_trait_available=False,
157
+ is_biased=False,
158
+ df=normalized_gene_data.T,
159
+ note=note
160
+ )
161
+
162
+ # 6) Do not save linked data since dataset is not usable for the current trait
163
+ # (Guard retained for completeness)
164
+ if is_usable and unbiased_linked_data is not None:
165
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
166
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Colon_and_Rectal_Cancer/code/GSE56699.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Colon_and_Rectal_Cancer"
6
+ cohort = "GSE56699"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Colon_and_Rectal_Cancer"
10
+ in_cohort_dir = "../DATA/GEO/Colon_and_Rectal_Cancer/GSE56699"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z2/preprocess/Colon_and_Rectal_Cancer/GSE56699.csv"
14
+ out_gene_data_file = "./output/z2/preprocess/Colon_and_Rectal_Cancer/gene_data/GSE56699.csv"
15
+ out_clinical_data_file = "./output/z2/preprocess/Colon_and_Rectal_Cancer/clinical_data/GSE56699.csv"
16
+ json_path = "./output/z2/preprocess/Colon_and_Rectal_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 data availability
42
+ is_gene_available = True # mRNA microarray/RNAseq-based study on rectal cancer FFPE specimens
43
+
44
+ # 2) Variable availability based on provided Sample Characteristics Dictionary
45
+ trait_row = None # No case/control or disease presence variability; all are rectal cancer cases
46
+ age_row = None # No age field present
47
+ gender_row = None # No gender/sex field present
48
+
49
+ # 2.2) Conversion functions
50
+ def _extract_after_colon(x):
51
+ if x is None:
52
+ return None
53
+ s = str(x)
54
+ parts = s.split(":", 1)
55
+ v = parts[1] if len(parts) > 1 else parts[0]
56
+ return v.strip()
57
+
58
+ def convert_trait(x):
59
+ v = _extract_after_colon(x)
60
+ if v is None or v == "" or v.lower() in {"na", "n/a", "nan", "none", "unknown"}:
61
+ return None
62
+ vl = v.lower()
63
+ # Map clear cancer indications to 1; normal/healthy/control to 0
64
+ cancer_terms = ["cancer", "carcinoma", "adenocarcinoma", "tumor", "tumour", "crc", "rectal", "rectum", "colon"]
65
+ normal_terms = ["normal", "healthy", "control", "adjacent normal", "benign"]
66
+ if any(t in vl for t in cancer_terms):
67
+ return 1
68
+ if any(t in vl for t in normal_terms):
69
+ return 0
70
+ return None
71
+
72
+ def convert_age(x):
73
+ v = _extract_after_colon(x)
74
+ if v is None:
75
+ return None
76
+ vl = v.strip().lower()
77
+ if vl in {"na", "n/a", "nan", "none", "unknown"}:
78
+ return None
79
+ nums = re.findall(r"[-+]?\d*\.?\d+", vl)
80
+ if not nums:
81
+ return None
82
+ try:
83
+ return float(nums[0])
84
+ except Exception:
85
+ return None
86
+
87
+ def convert_gender(x):
88
+ v = _extract_after_colon(x)
89
+ if v is None:
90
+ return None
91
+ vl = v.strip().lower()
92
+ if vl in {"na", "n/a", "nan", "none", "unknown"}:
93
+ return None
94
+ # Female -> 0, Male -> 1
95
+ if vl in {"female", "f", "woman", "girl"}:
96
+ return 0
97
+ if vl in {"male", "m", "man", "boy"}:
98
+ return 1
99
+ # Sometimes encoded as 0/1
100
+ if vl == "0":
101
+ return 0
102
+ if vl == "1":
103
+ return 1
104
+ return None
105
+
106
+ # 3) Save metadata (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 is skipped because trait_row is None
117
+
118
+ # Step 3: Gene Data Extraction
119
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
120
+ gene_data = get_genetic_data(matrix_file)
121
+
122
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
123
+ print(gene_data.index[:20])
124
+
125
+ # Step 4: Gene Identifier Review
126
+ requires_gene_mapping = True
127
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
128
+
129
+ # Step 5: Gene Annotation
130
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
131
+ gene_annotation = get_gene_annotation(soft_file)
132
+
133
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
134
+ print("Gene annotation preview:")
135
+ print(preview_df(gene_annotation))
136
+
137
+ # Step 6: Gene Identifier Mapping
138
+ # Identify the probe ID and gene symbol columns from the annotation preview:
139
+ # Probe identifiers match 'ID' (e.g., 'ILMN_1343291'), and gene symbols are in 'Symbol'
140
+
141
+ # 2. Build the mapping dataframe
142
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')
143
+
144
+ # 3. Apply the mapping to convert probe-level data to gene-level data
145
+ gene_data = apply_gene_mapping(gene_data, mapping_df)
146
+
147
+ # Step 7: Data Normalization and Linking
148
+ import os
149
+ import pandas as pd
150
+
151
+ # 1) Normalize gene symbols and save gene expression data
152
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
153
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
154
+ normalized_gene_data.to_csv(out_gene_data_file)
155
+
156
+ # 2) Link clinical and genetic data only if clinical features (trait) are available
157
+ has_clinical = ('selected_clinical_data' in globals()
158
+ and isinstance(selected_clinical_data, pd.DataFrame)
159
+ and (trait in selected_clinical_data.index))
160
+
161
+ if not has_clinical:
162
+ # No clinical trait available: update metadata accordingly and do not proceed with linking/QC
163
+ validate_and_save_cohort_info(
164
+ is_final=False,
165
+ cohort=cohort,
166
+ info_path=json_path,
167
+ is_gene_available=True,
168
+ is_trait_available=False
169
+ )
170
+ else:
171
+ # Proceed with linking and downstream processing
172
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
173
+
174
+ # 3) Handle missing values
175
+ linked_data = handle_missing_values(linked_data, trait)
176
+
177
+ # 4) Bias check and removal of biased demographic features
178
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
179
+
180
+ # 5) Final validation and save cohort info
181
+ note = "INFO: Clinical features available; linked with normalized gene expression."
182
+ is_usable = validate_and_save_cohort_info(
183
+ is_final=True,
184
+ cohort=cohort,
185
+ info_path=json_path,
186
+ is_gene_available=True,
187
+ is_trait_available=True,
188
+ is_biased=is_trait_biased,
189
+ df=unbiased_linked_data,
190
+ note=note
191
+ )
192
+
193
+ # 6) Save linked data only 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/Colon_and_Rectal_Cancer/code/TCGA.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Colon_and_Rectal_Cancer"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z2/preprocess/Colon_and_Rectal_Cancer/TCGA.csv"
12
+ out_gene_data_file = "./output/z2/preprocess/Colon_and_Rectal_Cancer/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z2/preprocess/Colon_and_Rectal_Cancer/clinical_data/TCGA.csv"
14
+ json_path = "./output/z2/preprocess/Colon_and_Rectal_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 Colon and Rectal Cancer
22
+ subdirs = os.listdir(tcga_root_dir)
23
+ preferred_patterns = [
24
+ "TCGA_Colon_and_Rectal_Cancer_(COADREAD)",
25
+ "COADREAD",
26
+ "Colon_and_Rectal_Cancer",
27
+ ]
28
+ selected_dir = None
29
+ for pat in preferred_patterns:
30
+ candidates = [d for d in subdirs if pat.lower() in d.lower()]
31
+ if candidates:
32
+ # If multiple options exist, choose the most specific match (first by our preference order)
33
+ selected_dir = sorted(candidates, key=len)[0]
34
+ break
35
+
36
+ if selected_dir is None:
37
+ # No suitable directory found -> mark as completed and skip
38
+ validate_and_save_cohort_info(
39
+ is_final=False,
40
+ cohort="TCGA_Colon_and_Rectal_Cancer_NotFound",
41
+ info_path=json_path,
42
+ is_gene_available=False,
43
+ is_trait_available=False
44
+ )
45
+ else:
46
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
47
+
48
+ # 2) Identify clinical and genetic file paths
49
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
50
+
51
+ # 3) Load both files as DataFrames
52
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False, compression='infer')
53
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False, compression='infer')
54
+
55
+ # 4) Print the column names of the clinical data
56
+ print(list(clinical_df.columns))
57
+
58
+ # Step 2: Find Candidate Demographic Features
59
+ # Use available clinical_df columns if present; otherwise fall back to the provided list
60
+ provided_columns = ['AWG_MLH1_silencing', 'AWG_cancer_type_Oct62011', 'CDE_ID_3226963', 'CIMP', 'MSI_updated_Oct62011', '_INTEGRATION', '_PANCAN_CNA_PANCAN_K8', '_PANCAN_Cluster_Cluster_PANCAN', '_PANCAN_DNAMethyl_COADREAD', '_PANCAN_DNAMethyl_PANCAN', '_PANCAN_RPPA_PANCAN_K8', '_PANCAN_UNC_RNAseq_PANCAN_K16', '_PANCAN_miRNA_PANCAN', '_PANCAN_mutation_PANCAN', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'additional_pharmaceutical_therapy', 'additional_radiation_therapy', 'age_at_initial_pathologic_diagnosis', 'anatomic_neoplasm_subdivision', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'braf_gene_analysis_performed', 'braf_gene_analysis_result', 'circumferential_resection_margin', 'colon_polyps_present', 'days_to_birth', 'days_to_collection', 'days_to_death', 'days_to_initial_pathologic_diagnosis', 'days_to_last_followup', 'days_to_new_tumor_event_additional_surgery_procedure', 'days_to_new_tumor_event_after_initial_treatment', 'disease_code', 'followup_case_report_form_submission_reason', 'followup_treatment_success', 'form_completion_date', 'gender', 'height', 'histological_type', 'history_of_colon_polyps', 'history_of_neoadjuvant_treatment', 'hypermutation', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'initial_weight', 'intermediate_dimension', 'is_ffpe', 'kras_gene_analysis_performed', 'kras_mutation_codon', 'kras_mutation_found', 'longest_dimension', 'loss_expression_of_mismatch_repair_proteins_by_ihc', 'loss_expression_of_mismatch_repair_proteins_by_ihc_result', 'lost_follow_up', 'lymph_node_examined_count', 'lymphatic_invasion', 'microsatellite_instability', 'new_neoplasm_event_type', 'new_tumor_event_additional_surgery_procedure', 'new_tumor_event_after_initial_treatment', 'non_nodal_tumor_deposits', 'non_silent_mutation', 'non_silent_rate_per_Mb', 'number_of_abnormal_loci', 'number_of_first_degree_relatives_with_cancer_diagnosis', 'number_of_loci_tested', 'number_of_lymphnodes_positive_by_he', 'number_of_lymphnodes_positive_by_ihc', 'oct_embedded', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathologic_stage', 'pathology_report_file_name', 'patient_id', 'perineural_invasion_present', 'person_neoplasm_cancer_status', 'postoperative_rx_tx', 'preoperative_pretreatment_cea_level', 'primary_lymph_node_presentation_assessment', 'primary_therapy_outcome_success', 'project_code', 'radiation_therapy', 'residual_disease_post_new_tumor_event_margin_status', 'residual_tumor', 'sample_type', 'sample_type_id', 'shortest_dimension', 'silent_mutation', 'silent_rate_per_Mb', 'site_of_additional_surgery_new_tumor_event_mets', 'synchronous_colon_cancer_present', 'system_version', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'total_mutation', 'tumor_tissue_site', 'venous_invasion', 'vial_number', 'vital_status', 'weight', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_COADREAD_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_COADREAD_PDMRNAseq', '_GENOMIC_ID_TCGA_COADREAD_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_COADREAD_hMethyl450', '_GENOMIC_ID_TCGA_COADREAD_gistic2thd', '_GENOMIC_ID_TCGA_COADREAD_hMethyl27', '_GENOMIC_ID_TCGA_COADREAD_G4502A_07_3', '_GENOMIC_ID_TCGA_COADREAD_PDMarrayCNV', '_GENOMIC_ID_TCGA_COADREAD_exp_HiSeqV2', '_GENOMIC_ID_TCGA_COADREAD_PDMarray', '_GENOMIC_ID_TCGA_COADREAD_gistic2', '_GENOMIC_ID_TCGA_COADREAD_mutation', '_GENOMIC_ID_TCGA_COADREAD_RPPA_RBN', '_GENOMIC_ID_TCGA_COADREAD_PDMRNAseqCNV']
61
+
62
+ all_columns = list(clinical_df.columns) if 'clinical_df' in globals() else provided_columns
63
+
64
+ # Identify candidate columns with careful patterns to avoid false positives like "pathologic_stage"
65
+ candidate_age_cols = []
66
+ candidate_gender_cols = []
67
+
68
+ for col in all_columns:
69
+ col_l = col.lower()
70
+ # Age candidates
71
+ if (
72
+ col_l == 'age' or
73
+ col_l.startswith('age_') or
74
+ 'age_at' in col_l or
75
+ col_l.endswith('_age') or
76
+ col_l in {'days_to_birth', 'years_to_birth', 'year_of_birth', 'dob'}
77
+ ):
78
+ candidate_age_cols.append(col)
79
+ # Gender candidates (avoid partial matches like "seq")
80
+ if (
81
+ col_l in {'gender', 'sex'} or
82
+ col_l.endswith('_gender') or
83
+ col_l.endswith('_sex') or
84
+ col_l.startswith('gender_') or
85
+ col_l.startswith('sex_')
86
+ ):
87
+ candidate_gender_cols.append(col)
88
+
89
+ # Print required lists in strict format
90
+ print(f"candidate_age_cols = {candidate_age_cols}")
91
+ print(f"candidate_gender_cols = {candidate_gender_cols}")
92
+
93
+ # Preview extracted data if clinical_df is available
94
+ if 'clinical_df' in globals():
95
+ age_cols_present = [c for c in candidate_age_cols if c in clinical_df.columns]
96
+ gender_cols_present = [c for c in candidate_gender_cols if c in clinical_df.columns]
97
+
98
+ if age_cols_present:
99
+ print(preview_df(clinical_df[age_cols_present], n=5))
100
+ if gender_cols_present:
101
+ print(preview_df(clinical_df[gender_cols_present], n=5))
102
+
103
+ # Step 3: Select Demographic Features
104
+ import pandas as pd
105
+ import numpy as np
106
+
107
+ # Defaults
108
+ age_col = None
109
+ gender_col = None
110
+
111
+ # Heuristics thresholds
112
+ min_non_missing_ratio = 0.6
113
+
114
+ # Helper to check if a variable exists
115
+ def var_exists(name):
116
+ return name in globals() or name in locals()
117
+
118
+ # Select age column
119
+ if var_exists('candidate_age_cols'):
120
+ if 'clinical_df' in globals() or 'clinical_df' in locals():
121
+ df = clinical_df
122
+ best_score = -np.inf
123
+ best_col = None
124
+ for col in candidate_age_cols:
125
+ if col in df.columns:
126
+ s = pd.to_numeric(df[col], errors='coerce')
127
+ non_missing_ratio = s.notna().mean()
128
+
129
+ # Plausible human age range in years
130
+ plausible_ratio = ((s >= 0) & (s <= 120)).mean(skipna=True)
131
+
132
+ # Small bonus if column name suggests age in years
133
+ name_bonus = 0.1 if 'age' in col.lower() and 'birth' not in col.lower() else 0.0
134
+
135
+ score = plausible_ratio * 1.0 + non_missing_ratio * 0.2 + name_bonus
136
+
137
+ if non_missing_ratio >= min_non_missing_ratio and score > best_score:
138
+ best_score = score
139
+ best_col = col
140
+
141
+ age_col = best_col
142
+ else:
143
+ # Fallback to commonly correct choice if DataFrame not available
144
+ age_col = 'age_at_initial_pathologic_diagnosis' if 'age_at_initial_pathologic_diagnosis' in candidate_age_cols else None
145
+
146
+ # Select gender column
147
+ if var_exists('candidate_gender_cols'):
148
+ if 'clinical_df' in globals() or 'clinical_df' in locals():
149
+ df = clinical_df
150
+ best_score = -np.inf
151
+ best_col = None
152
+
153
+ allowed = {'male', 'female', 'm', 'f'}
154
+ for col in candidate_gender_cols:
155
+ if col in df.columns:
156
+ s = df[col].astype(str).str.strip().str.lower()
157
+ non_missing_ratio = df[col].notna().mean()
158
+ in_allowed = s.isin(allowed)
159
+ allowed_ratio = in_allowed.mean()
160
+
161
+ # Score prioritizes valid gender values and completeness
162
+ score = allowed_ratio * 1.0 + non_missing_ratio * 0.2
163
+
164
+ if non_missing_ratio >= min_non_missing_ratio and score > best_score:
165
+ best_score = score
166
+ best_col = col
167
+
168
+ gender_col = best_col
169
+ else:
170
+ gender_col = 'gender' if 'gender' in candidate_gender_cols else None
171
+
172
+ # Print selected columns and a brief preview if available
173
+ print("Selected age_col:", age_col)
174
+ if age_col is not None and ('clinical_df' in globals() or 'clinical_df' in locals()):
175
+ print("age_col preview (first 5):", clinical_df[age_col].head(5).tolist())
176
+
177
+ print("Selected gender_col:", gender_col)
178
+ if gender_col is not None and ('clinical_df' in globals() or 'clinical_df' in locals()):
179
+ print("gender_col preview (first 5):", clinical_df[gender_col].head(5).tolist())
180
+
181
+ # Step 4: Feature Engineering and Validation
182
+ import os
183
+ import pandas as pd
184
+ import numpy as np
185
+
186
+ # 1) Extract and standardize clinical features (Trait, Age, Gender)
187
+ selected_clinical_df = tcga_select_clinical_features(
188
+ clinical_df,
189
+ trait=trait,
190
+ age_col=age_col,
191
+ gender_col=gender_col
192
+ )
193
+
194
+ # 2) Prepare genetic data with genes as index, samples as columns
195
+ def _tcga_prop_tcga_prefix(labels):
196
+ if len(labels) == 0:
197
+ return 0.0
198
+ return np.mean([isinstance(x, str) and x.startswith('TCGA') for x in labels])
199
+
200
+ # Detect orientation: are TCGA sample IDs in index or columns?
201
+ p_idx = _tcga_prop_tcga_prefix(genetic_df.index.tolist())
202
+ p_col = _tcga_prop_tcga_prefix(genetic_df.columns.tolist())
203
+
204
+ if p_idx >= 0.5 and p_idx > p_col:
205
+ # Index are samples; transpose to get genes as index
206
+ gene_df_raw = genetic_df.T
207
+ else:
208
+ gene_df_raw = genetic_df
209
+
210
+ # Ensure numeric and drop all-nan rows/cols safely
211
+ gene_df_raw = gene_df_raw.apply(pd.to_numeric, errors='coerce')
212
+ gene_df_raw = gene_df_raw.dropna(axis=0, how='all').dropna(axis=1, how='all')
213
+
214
+ # Normalize gene symbols using NCBI synonyms and aggregate duplicates
215
+ normalized_gene_df = normalize_gene_symbols_in_index(gene_df_raw)
216
+
217
+ # Save normalized gene expression data
218
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
219
+ normalized_gene_df.to_csv(out_gene_data_file)
220
+
221
+ # 3) Link clinical and genetic data on sample IDs
222
+ # Harmonize sample identifiers to first 15 chars (e.g., TCGA-XX-XXXX-01)
223
+ def _to_sample15(s):
224
+ return str(s)[:15] if isinstance(s, str) else s
225
+
226
+ E = normalized_gene_df.T.copy() # samples x genes
227
+ E.index = E.index.map(_to_sample15)
228
+ E = E[~E.index.duplicated(keep='first')]
229
+
230
+ clinical_harmonized = selected_clinical_df.copy()
231
+ clinical_harmonized.index = clinical_harmonized.index.map(_to_sample15)
232
+ clinical_harmonized = clinical_harmonized[~clinical_harmonized.index.duplicated(keep='first')]
233
+
234
+ linked_data = clinical_harmonized.join(E, how='inner')
235
+
236
+ # 4) Handle missing values systematically
237
+ processed_df = handle_missing_values(linked_data, trait_col=trait)
238
+
239
+ # 5) Determine bias in trait and demographics; remove biased demographics
240
+ is_biased, debiased_df = judge_and_remove_biased_features(processed_df, trait=trait)
241
+ is_biased = bool(is_biased) # ensure Python-native bool
242
+
243
+ # 6) Final quality validation and save cohort metadata
244
+ cohort_name = selected_dir if 'selected_dir' in globals() else "TCGA_Colon_and_Rectal_Cancer_(COADREAD)"
245
+ is_gene_available = bool((normalized_gene_df.shape[0] > 0) and (normalized_gene_df.shape[1] > 0))
246
+ is_trait_available = bool((trait in debiased_df.columns) and bool(debiased_df[trait].notna().any()))
247
+
248
+ note = (
249
+ f"INFO: Linked clinical and gene expression data for {cohort_name}. "
250
+ f"Normalized genes: {normalized_gene_df.shape[0]}; samples in gene data: {normalized_gene_df.shape[1]}. "
251
+ f"Linked samples after harmonization: {linked_data.shape[0]}; final samples after QC: {debiased_df.shape[0]}; "
252
+ f"final features: {debiased_df.shape[1]}."
253
+ )
254
+
255
+ is_usable = validate_and_save_cohort_info(
256
+ is_final=True,
257
+ cohort=str(cohort_name),
258
+ info_path=json_path,
259
+ is_gene_available=is_gene_available,
260
+ is_trait_available=is_trait_available,
261
+ is_biased=is_biased,
262
+ df=debiased_df,
263
+ note=note
264
+ )
265
+
266
+ # 7) Save linked data only if usable
267
+ if is_usable:
268
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
269
+ debiased_df.to_csv(out_data_file)
output/preprocess/Colon_and_Rectal_Cancer/cohort_info.json CHANGED
@@ -1,42 +1 @@
1
- {
2
- "GSE56699": {
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
- "GSE46862": {
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": 69
21
- },
22
- "GSE46517": {
23
- "is_usable": true,
24
- "is_gene_available": true,
25
- "is_trait_available": true,
26
- "is_available": true,
27
- "is_biased": false,
28
- "has_age": true,
29
- "has_gender": true,
30
- "sample_size": 121
31
- },
32
- "TCGA": {
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": true,
39
- "has_gender": true,
40
- "sample_size": 434
41
- }
42
- }
 
1
+ {"GSE56699": {"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}, "GSE46862": {"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 unavailable for this cohort (all rectal cancer; no usable trait variation for Colon_and_Rectal_Cancer). Gene expression processed and saved; skipped clinical-genetic linking and downstream steps."}, "GSE46517": {"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_Colon_and_Rectal_Cancer_(COADREAD)": {"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": 434, "note": "INFO: Linked clinical and gene expression data for TCGA_Colon_and_Rectal_Cancer_(COADREAD). Normalized genes: 19848; samples in gene data: 434. Linked samples after harmonization: 434; final samples after QC: 434; final features: 19851."}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Congestive_heart_failure/clinical_data/GSE182600.csv ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ,GSM5532093,GSM5532094,GSM5532095,GSM5532096,GSM5532097,GSM5532098,GSM5532099,GSM5532100,GSM5532101,GSM5532102,GSM5532103,GSM5532104,GSM5532105,GSM5532106,GSM5532107,GSM5532108,GSM5532109,GSM5532110,GSM5532111,GSM5532112,GSM5532113,GSM5532114,GSM5532115,GSM5532116,GSM5532117,GSM5532118,GSM5532119,GSM5532120,GSM5532121,GSM5532122,GSM5532123,GSM5532124,GSM5532125,GSM5532126,GSM5532127,GSM5532128,GSM5532129,GSM5532130,GSM5532131,GSM5532132,GSM5532133,GSM5532134,GSM5532135,GSM5532136,GSM5532137,GSM5532138,GSM5532139,GSM5532140,GSM5532141,GSM5532142,GSM5532143,GSM5532144,GSM5532145,GSM5532146,GSM5532147,GSM5532148,GSM5532149,GSM5532150,GSM5532151,GSM5532152,GSM5532153,GSM5532154,GSM5532155,GSM5532156,GSM5532157,GSM5532158,GSM5532159,GSM5532160,GSM5532161,GSM5532162,GSM5532163,GSM5532164,GSM5532165,GSM5532166,GSM5532167,GSM5532168,GSM5532169,GSM5532170
2
+ Congestive_heart_failure,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,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.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,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,1.0
3
+ Age,33.4,51.2,51.9,47.8,41.5,67.3,52.8,16.1,78.9,53.2,70.9,59.9,21.9,45.2,52.4,32.3,52.8,55.8,47.0,55.8,57.3,31.7,49.3,66.1,55.9,49.1,63.0,21.0,53.6,50.1,37.4,71.5,56.5,33.4,51.2,51.9,47.8,41.5,67.3,52.8,78.9,53.2,70.9,59.9,21.9,45.2,52.4,32.3,55.8,47.0,55.8,57.3,31.7,49.3,66.1,55.9,49.1,63.0,21.0,53.6,50.1,37.4,71.5,56.5,33.4,51.2,51.9,47.8,52.8,53.2,21.9,55.8,47.0,49.3,66.1,53.6,50.1,56.5
4
+ Gender,0.0,1.0,0.0,1.0,0.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,0.0,0.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,0.0,1.0,0.0,1.0,0.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,0.0,0.0,1.0,1.0,1.0,0.0,1.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,1.0,1.0,1.0,1.0,0.0,1.0