Liu-Hy commited on
Commit
a6ba3f2
·
verified ·
1 Parent(s): e1bcc26

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/Obsessive-Compulsive_Disorder/clinical_data/GSE60190.csv +3 -2
  2. output/preprocess/Obsessive-Compulsive_Disorder/clinical_data/GSE78104.csv +4 -4
  3. output/preprocess/Obsessive-Compulsive_Disorder/code/GSE60190.py +182 -0
  4. output/preprocess/Obsessive-Compulsive_Disorder/code/GSE78104.py +210 -0
  5. output/preprocess/Obsessive-Compulsive_Disorder/code/TCGA.py +62 -0
  6. output/preprocess/Obsessive-Compulsive_Disorder/cohort_info.json +1 -22
  7. output/preprocess/Obstructive_sleep_apnea/GSE75097.csv +0 -0
  8. output/preprocess/Obstructive_sleep_apnea/clinical_data/GSE75097.csv +1 -1
  9. output/preprocess/Obstructive_sleep_apnea/code/GSE133601.py +267 -0
  10. output/preprocess/Obstructive_sleep_apnea/code/GSE135917.py +221 -0
  11. output/preprocess/Obstructive_sleep_apnea/code/GSE49800.py +121 -0
  12. output/preprocess/Obstructive_sleep_apnea/code/GSE75097.py +168 -0
  13. output/preprocess/Obstructive_sleep_apnea/code/TCGA.py +64 -0
  14. output/preprocess/Obstructive_sleep_apnea/cohort_info.json +1 -52
  15. output/preprocess/Ocular_Melanomas/clinical_data/GSE60464.csv +1 -1
  16. output/preprocess/Ocular_Melanomas/clinical_data/TCGA.csv +81 -0
  17. output/preprocess/Ocular_Melanomas/code/GSE60464.py +192 -0
  18. output/preprocess/Ocular_Melanomas/code/GSE78033.py +214 -0
  19. output/preprocess/Ocular_Melanomas/code/TCGA.py +287 -0
  20. output/preprocess/Ocular_Melanomas/cohort_info.json +1 -32
  21. output/preprocess/Osteoarthritis/GSE141934.csv +0 -0
  22. output/preprocess/Osteoarthritis/GSE55457.csv +0 -0
  23. output/preprocess/Osteoarthritis/clinical_data/GSE107105.csv +4 -0
  24. output/preprocess/Osteoarthritis/clinical_data/GSE141934.csv +4 -0
  25. output/preprocess/Osteoarthritis/clinical_data/GSE56409.csv +2 -2
  26. output/preprocess/Osteoarthritis/clinical_data/GSE93698.csv +4 -4
  27. output/preprocess/Osteoarthritis/clinical_data/GSE93720.csv +2 -2
  28. output/preprocess/Osteoarthritis/code/GSE107105.py +397 -0
  29. output/preprocess/Osteoarthritis/code/GSE141934.py +191 -0
  30. output/preprocess/Osteoarthritis/code/GSE142049.py +220 -0
  31. output/preprocess/Osteoarthritis/code/GSE236924.py +194 -0
  32. output/preprocess/Osteoarthritis/code/GSE55457.py +206 -0
  33. output/preprocess/Osteoarthritis/code/GSE56409.py +195 -0
  34. output/preprocess/Osteoarthritis/code/GSE75181.py +172 -0
  35. output/preprocess/Osteoarthritis/code/GSE93698.py +189 -0
  36. output/preprocess/Osteoarthritis/code/GSE93720.py +200 -0
  37. output/preprocess/Osteoarthritis/code/GSE98460.py +239 -0
  38. output/preprocess/Osteoarthritis/code/TCGA.py +60 -0
  39. output/preprocess/Osteoarthritis/cohort_info.json +1 -112
  40. output/preprocess/Osteoporosis/GSE56815.csv +0 -0
  41. output/preprocess/Osteoporosis/clinical_data/GSE56814.csv +2 -74
  42. output/preprocess/Osteoporosis/clinical_data/GSE56815.csv +0 -1
  43. output/preprocess/Osteoporosis/code/GSE152073.py +131 -0
  44. output/preprocess/Osteoporosis/code/GSE20881.py +144 -0
  45. output/preprocess/Osteoporosis/code/GSE224330.py +197 -0
  46. output/preprocess/Osteoporosis/code/GSE35925.py +133 -0
  47. output/preprocess/Osteoporosis/code/GSE51495.py +113 -0
  48. output/preprocess/Osteoporosis/code/GSE56814.py +178 -0
  49. output/preprocess/Osteoporosis/code/GSE56815.py +201 -0
  50. output/preprocess/Osteoporosis/code/GSE62589.py +166 -0
output/preprocess/Obsessive-Compulsive_Disorder/clinical_data/GSE60190.csv CHANGED
@@ -1,3 +1,4 @@
1
  ,GSM1467273,GSM1467274,GSM1467275,GSM1467276,GSM1467277,GSM1467278,GSM1467279,GSM1467280,GSM1467281,GSM1467282,GSM1467283,GSM1467284,GSM1467285,GSM1467286,GSM1467287,GSM1467288,GSM1467289,GSM1467290,GSM1467291,GSM1467292,GSM1467293,GSM1467294,GSM1467295,GSM1467296,GSM1467297,GSM1467298,GSM1467299,GSM1467300,GSM1467301,GSM1467302,GSM1467303,GSM1467304,GSM1467305,GSM1467306,GSM1467307,GSM1467308,GSM1467309,GSM1467310,GSM1467311,GSM1467312,GSM1467313,GSM1467314,GSM1467315,GSM1467316,GSM1467317,GSM1467318,GSM1467319,GSM1467320,GSM1467321,GSM1467322,GSM1467323,GSM1467324,GSM1467325,GSM1467326,GSM1467327,GSM1467328,GSM1467329,GSM1467330,GSM1467331,GSM1467332,GSM1467333,GSM1467334,GSM1467335,GSM1467336,GSM1467337,GSM1467338,GSM1467339,GSM1467340,GSM1467341,GSM1467342,GSM1467343,GSM1467344,GSM1467345,GSM1467346,GSM1467347,GSM1467348,GSM1467349,GSM1467350,GSM1467351,GSM1467352,GSM1467353,GSM1467354,GSM1467355,GSM1467356,GSM1467357,GSM1467358,GSM1467359,GSM1467360,GSM1467361,GSM1467362,GSM1467363,GSM1467364,GSM1467365,GSM1467366,GSM1467367,GSM1467368,GSM1467369,GSM1467370,GSM1467371,GSM1467372,GSM1467373,GSM1467374,GSM1467375,GSM1467376,GSM1467377,GSM1467378,GSM1467379,GSM1467380,GSM1467381,GSM1467382,GSM1467383,GSM1467384,GSM1467385,GSM1467386,GSM1467387,GSM1467388,GSM1467389,GSM1467390,GSM1467391,GSM1467392,GSM1467393,GSM1467394,GSM1467395,GSM1467396,GSM1467397,GSM1467398,GSM1467399,GSM1467400,GSM1467401,GSM1467402,GSM1467403,GSM1467404,GSM1467405
2
- Obsessive-Compulsive_Disorder,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
3
- Gender,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
 
 
1
  ,GSM1467273,GSM1467274,GSM1467275,GSM1467276,GSM1467277,GSM1467278,GSM1467279,GSM1467280,GSM1467281,GSM1467282,GSM1467283,GSM1467284,GSM1467285,GSM1467286,GSM1467287,GSM1467288,GSM1467289,GSM1467290,GSM1467291,GSM1467292,GSM1467293,GSM1467294,GSM1467295,GSM1467296,GSM1467297,GSM1467298,GSM1467299,GSM1467300,GSM1467301,GSM1467302,GSM1467303,GSM1467304,GSM1467305,GSM1467306,GSM1467307,GSM1467308,GSM1467309,GSM1467310,GSM1467311,GSM1467312,GSM1467313,GSM1467314,GSM1467315,GSM1467316,GSM1467317,GSM1467318,GSM1467319,GSM1467320,GSM1467321,GSM1467322,GSM1467323,GSM1467324,GSM1467325,GSM1467326,GSM1467327,GSM1467328,GSM1467329,GSM1467330,GSM1467331,GSM1467332,GSM1467333,GSM1467334,GSM1467335,GSM1467336,GSM1467337,GSM1467338,GSM1467339,GSM1467340,GSM1467341,GSM1467342,GSM1467343,GSM1467344,GSM1467345,GSM1467346,GSM1467347,GSM1467348,GSM1467349,GSM1467350,GSM1467351,GSM1467352,GSM1467353,GSM1467354,GSM1467355,GSM1467356,GSM1467357,GSM1467358,GSM1467359,GSM1467360,GSM1467361,GSM1467362,GSM1467363,GSM1467364,GSM1467365,GSM1467366,GSM1467367,GSM1467368,GSM1467369,GSM1467370,GSM1467371,GSM1467372,GSM1467373,GSM1467374,GSM1467375,GSM1467376,GSM1467377,GSM1467378,GSM1467379,GSM1467380,GSM1467381,GSM1467382,GSM1467383,GSM1467384,GSM1467385,GSM1467386,GSM1467387,GSM1467388,GSM1467389,GSM1467390,GSM1467391,GSM1467392,GSM1467393,GSM1467394,GSM1467395,GSM1467396,GSM1467397,GSM1467398,GSM1467399,GSM1467400,GSM1467401,GSM1467402,GSM1467403,GSM1467404,GSM1467405
2
+ Obsessive-Compulsive_Disorder,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,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,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,1.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,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
3
+ Age,50.421917,27.49863,30.627397,61.167123,32.69589,39.213698,58.605479,49.2,41.041095,51.750684,50.89863,26.745205,29.104109,39.301369,48.978082,57.884931,28.364383,24.041095,19.268493,27.230136,46.605479,23.443835,51.038356,39.663013,46.109589,77.989041,46.967123,63.241095,62.306849,83.641095,42.838356,51.386301,66.715068,51.939726,34.339726,50.109589,18.758904,16.649315,16.353424,42.065753,16.726027,34.465753,34.254794,47.484931,43.756164,49.210958,57.482191,46.561643,49.561643,28.589041,38.410958,30.032876,56.09041,46.915068,49.021917,71.109589,17.235616,16.583561,16.934246,16.8,18.117808,18.660273,16.69589,75.572602,59.260273,55.545205,41.778082,57.454794,45.284931,56.304109,39.654794,55.945205,38.232876,58.109589,40.021917,50.504109,36.550684,45.117808,83.545205,18.786301,48.567123,38.331506,48.101369,18.39452,60.843835,61.372602,52.038356,59.254794,41.567123,50.358904,31.558904,45.701369,44.731506,34.39726,31.613698,54.846575,84.057534,66.79452,53.323287,30.043835,55.435616,45.676712,54.334246,63.558904,45.224657,23.69589,67.865753,16.753424,18.424657,17.09041,16.183561,33.260273,54.424657,45.378082,52.523287,35.273972,22.630136,20.863013,26.531506,24.627397,53.978082,34.961643,18.731506,30.726027,63.471232,54.808219,57.512328,57.610958,44.958904,35.684931,63.0,38.780821,45.978082
4
+ Gender,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,0.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,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,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.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,1.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0
output/preprocess/Obsessive-Compulsive_Disorder/clinical_data/GSE78104.csv CHANGED
@@ -1,4 +1,4 @@
1
- GSM2067403,GSM2067404,GSM2067405,GSM2067406,GSM2067407,GSM2067408,GSM2067409,GSM2067410,GSM2067411,GSM2067412,GSM2067413,GSM2067414,GSM2067415,GSM2067416,GSM2067417,GSM2067418,GSM2067419,GSM2067420,GSM2067421,GSM2067422,GSM2067423,GSM2067424,GSM2067425,GSM2067426,GSM2067427,GSM2067428,GSM2067429,GSM2067430,GSM2067431,GSM2067432,GSM2067433,GSM2067434,GSM2067435,GSM2067436,GSM2067437,GSM2067438,GSM2067439,GSM2067440,GSM2067441,GSM2067442,GSM2067443,GSM2067444,GSM2067445,GSM2067446,GSM2067447,GSM2067448,GSM2067449,GSM2067450,GSM2067451,GSM2067452,GSM2067453,GSM2067454,GSM2067455,GSM2067456,GSM2067457,GSM2067458,GSM2067459,GSM2067460,GSM2067461,GSM2067462
2
- 1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,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
- 25.0,23.0,18.0,26.0,27.0,19.0,22.0,27.0,18.0,25.0,16.0,35.0,16.0,16.0,32.0,18.0,15.0,43.0,36.0,17.0,45.0,40.0,35.0,28.0,27.0,31.0,23.0,35.0,60.0,59.0,24.0,23.0,18.0,27.0,27.0,20.0,21.0,27.0,20.0,24.0,18.0,35.0,17.0,18.0,32.0,18.0,18.0,44.0,37.0,17.0,43.0,40.0,32.0,28.0,27.0,30.0,24.0,35.0,56.0,56.0
4
- 1.0,0.0,0.0,1.0,0.0,1.0,1.0,0.0,1.0,1.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,0.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,1.0,0.0,1.0,1.0,0.0,1.0,1.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,0.0,1.0,1.0,1.0,0.0,1.0,0.0
 
1
+ ,GSM2067403,GSM2067404,GSM2067405,GSM2067406,GSM2067407,GSM2067408,GSM2067409,GSM2067410,GSM2067411,GSM2067412,GSM2067413,GSM2067414,GSM2067415,GSM2067416,GSM2067417,GSM2067418,GSM2067419,GSM2067420,GSM2067421,GSM2067422,GSM2067423,GSM2067424,GSM2067425,GSM2067426,GSM2067427,GSM2067428,GSM2067429,GSM2067430,GSM2067431,GSM2067432,GSM2067433,GSM2067434,GSM2067435,GSM2067436,GSM2067437,GSM2067438,GSM2067439,GSM2067440,GSM2067441,GSM2067442,GSM2067443,GSM2067444,GSM2067445,GSM2067446,GSM2067447,GSM2067448,GSM2067449,GSM2067450,GSM2067451,GSM2067452,GSM2067453,GSM2067454,GSM2067455,GSM2067456,GSM2067457,GSM2067458,GSM2067459,GSM2067460,GSM2067461,GSM2067462
2
+ Obsessive-Compulsive_Disorder,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,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
+ Age,25.0,23.0,18.0,26.0,27.0,19.0,22.0,27.0,18.0,25.0,16.0,35.0,16.0,16.0,32.0,18.0,15.0,43.0,36.0,17.0,45.0,40.0,35.0,28.0,27.0,31.0,23.0,35.0,60.0,59.0,24.0,23.0,18.0,27.0,27.0,20.0,21.0,27.0,20.0,24.0,18.0,35.0,17.0,18.0,32.0,18.0,18.0,44.0,37.0,17.0,43.0,40.0,32.0,28.0,27.0,30.0,24.0,35.0,56.0,56.0
4
+ Gender,1.0,0.0,0.0,1.0,0.0,1.0,1.0,0.0,1.0,1.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,0.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,1.0,0.0,1.0,1.0,0.0,1.0,1.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,0.0,1.0,1.0,1.0,0.0,1.0,0.0
output/preprocess/Obsessive-Compulsive_Disorder/code/GSE60190.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Obsessive-Compulsive_Disorder"
6
+ cohort = "GSE60190"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Obsessive-Compulsive_Disorder"
10
+ in_cohort_dir = "../DATA/GEO/Obsessive-Compulsive_Disorder/GSE60190"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z5/preprocess/Obsessive-Compulsive_Disorder/GSE60190.csv"
14
+ out_gene_data_file = "./output/z5/preprocess/Obsessive-Compulsive_Disorder/gene_data/GSE60190.csv"
15
+ out_clinical_data_file = "./output/z5/preprocess/Obsessive-Compulsive_Disorder/clinical_data/GSE60190.csv"
16
+ json_path = "./output/z5/preprocess/Obsessive-Compulsive_Disorder/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
+ from typing import Optional, Any
41
+
42
+ # 1) Gene expression data availability
43
+ is_gene_available = True # Illumina HumanHT-12 v3 microarray indicates mRNA expression data
44
+
45
+ # 2) Variable availability and converters
46
+ trait_row = 3 # 'dx: Control/Bipolar/MDD/OCD/Tics/ED'
47
+ age_row = 5 # 'age: <float>'
48
+ gender_row = 7 # 'Sex: M/F'
49
+
50
+ def _after_colon(x: Any) -> Optional[str]:
51
+ if x is None:
52
+ return None
53
+ s = str(x)
54
+ if ':' in s:
55
+ s = s.split(':', 1)[1]
56
+ return s.strip()
57
+
58
+ def convert_trait(x: Any) -> Optional[int]:
59
+ v = _after_colon(x)
60
+ if v is None or v == '':
61
+ return None
62
+ v_low = v.strip().lower()
63
+ # Presence of OCD vs others
64
+ if v_low == 'ocd':
65
+ return 1
66
+ # Non-OCD diagnoses or controls -> 0
67
+ if v_low in {'control', 'ed', 'tics', 'bipolar', 'mdd', 'ocpd'}:
68
+ return 0
69
+ return None
70
+
71
+ def convert_age(x: Any) -> Optional[float]:
72
+ v = _after_colon(x)
73
+ if v is None or v == '':
74
+ return None
75
+ v = v.strip()
76
+ # Handle common missing tokens
77
+ if v.lower() in {'na', 'n/a', 'nan', 'none', 'unknown'}:
78
+ return None
79
+ try:
80
+ return float(v)
81
+ except Exception:
82
+ return None
83
+
84
+ def convert_gender(x: Any) -> Optional[int]:
85
+ v = _after_colon(x)
86
+ if v is None or v == '':
87
+ return None
88
+ v_low = v.strip().lower()
89
+ if v_low in {'f', 'female', 'women', 'woman'}:
90
+ return 0
91
+ if v_low in {'m', 'male', 'men', 'man'}:
92
+ return 1
93
+ return None
94
+
95
+ # 3) Save metadata (initial filtering)
96
+ is_trait_available = trait_row is not None
97
+ _ = validate_and_save_cohort_info(
98
+ is_final=False,
99
+ cohort=cohort,
100
+ info_path=json_path,
101
+ is_gene_available=is_gene_available,
102
+ is_trait_available=is_trait_available
103
+ )
104
+
105
+ # 4) Clinical feature extraction
106
+ if trait_row is not None:
107
+ selected_clinical_df = geo_select_clinical_features(
108
+ clinical_df=clinical_data,
109
+ trait=trait,
110
+ trait_row=trait_row,
111
+ convert_trait=convert_trait,
112
+ age_row=age_row,
113
+ convert_age=convert_age,
114
+ gender_row=gender_row,
115
+ convert_gender=convert_gender
116
+ )
117
+ print(preview_df(selected_clinical_df))
118
+
119
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
120
+ # Save with samples as columns; assuming selected_clinical_df is already in desired orientation
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
+ print("requires_gene_mapping = True")
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 annotation columns and get mapping dataframe
143
+ # Probe IDs in expression data are Illumina IDs like "ILMN_1343291", which correspond to the 'ID' column in annotation.
144
+ # Gene symbols are provided in the 'Symbol' column.
145
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')
146
+
147
+ # 3) Apply mapping to convert probe-level to gene-level expression
148
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
149
+
150
+ # Step 7: Data Normalization and Linking
151
+ import os
152
+
153
+ # 1. Normalize gene symbols and save
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 clinical and genetic data
159
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
160
+
161
+ # 3. Handle missing values
162
+ linked_data = handle_missing_values(linked_data, trait)
163
+
164
+ # 4. Bias evaluation and removal of biased covariates
165
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
166
+
167
+ # 5. Final validation and save cohort info
168
+ is_usable = validate_and_save_cohort_info(
169
+ is_final=True,
170
+ cohort=cohort,
171
+ info_path=json_path,
172
+ is_gene_available=True,
173
+ is_trait_available=True,
174
+ is_biased=is_trait_biased,
175
+ df=unbiased_linked_data,
176
+ note="INFO: Illumina HumanHT-12 v3 platform; DLPFC postmortem samples; trait from 'dx' (OCD vs non-OCD)."
177
+ )
178
+
179
+ # 6. Save linked data if usable
180
+ if is_usable:
181
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
182
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Obsessive-Compulsive_Disorder/code/GSE78104.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Obsessive-Compulsive_Disorder"
6
+ cohort = "GSE78104"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Obsessive-Compulsive_Disorder"
10
+ in_cohort_dir = "../DATA/GEO/Obsessive-Compulsive_Disorder/GSE78104"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z5/preprocess/Obsessive-Compulsive_Disorder/GSE78104.csv"
14
+ out_gene_data_file = "./output/z5/preprocess/Obsessive-Compulsive_Disorder/gene_data/GSE78104.csv"
15
+ out_clinical_data_file = "./output/z5/preprocess/Obsessive-Compulsive_Disorder/clinical_data/GSE78104.csv"
16
+ json_path = "./output/z5/preprocess/Obsessive-Compulsive_Disorder/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 os
41
+
42
+ # 1. Gene Expression Data Availability
43
+ is_gene_available = True # mRNA + lncRNA microarray platform indicates gene expression data
44
+
45
+ # 2. Variable Availability and Data Type Conversion
46
+
47
+ # Rows identified from the Sample Characteristics Dictionary
48
+ trait_row = 1
49
+ age_row = 3
50
+ gender_row = 2
51
+
52
+ def _extract_value(cell):
53
+ if cell is None:
54
+ return None
55
+ s = str(cell)
56
+ parts = s.split(":", 1)
57
+ val = parts[1] if len(parts) > 1 else parts[0]
58
+ return val.strip()
59
+
60
+ def convert_trait(x):
61
+ v = _extract_value(x)
62
+ if v is None:
63
+ return None
64
+ vl = v.lower().strip()
65
+ # Map OCD cases to 1, controls to 0
66
+ if ("ocd" in vl) or ("obsessive-compulsive" in vl) or ("obsessive compulsive" in vl) or ("patient" in vl) or ("case" in vl):
67
+ return 1
68
+ if ("normal control" in vl) or ("control" in vl) or ("healthy" in vl) or (vl == "normal"):
69
+ return 0
70
+ return None
71
+
72
+ def convert_age(x):
73
+ v = _extract_value(x)
74
+ if v is None:
75
+ return None
76
+ vl = v.lower()
77
+ m = re.search(r'(\d+(\.\d+)?)', vl)
78
+ if not m:
79
+ return None
80
+ try:
81
+ return float(m.group(1))
82
+ except Exception:
83
+ return None
84
+
85
+ def convert_gender(x):
86
+ v = _extract_value(x)
87
+ if v is None:
88
+ return None
89
+ vl = v.strip().lower()
90
+ # Check female first to avoid 'male' substring in 'female'
91
+ if vl in {"female", "f", "woman", "women"}:
92
+ return 0
93
+ if vl in {"male", "m", "man", "men"}:
94
+ return 1
95
+ # Fallback using word boundaries
96
+ if re.search(r'\bfemale\b', vl):
97
+ return 0
98
+ if re.search(r'\bmale\b', vl):
99
+ return 1
100
+ return None
101
+
102
+ # 3. Save Metadata (initial filtering)
103
+ is_trait_available = trait_row is not None
104
+ _ = validate_and_save_cohort_info(
105
+ is_final=False,
106
+ cohort=cohort,
107
+ info_path=json_path,
108
+ is_gene_available=is_gene_available,
109
+ is_trait_available=is_trait_available
110
+ )
111
+
112
+ # 4. Clinical Feature Extraction
113
+ if trait_row is not None:
114
+ selected_clinical_df = geo_select_clinical_features(
115
+ clinical_df=clinical_data,
116
+ trait=trait,
117
+ trait_row=trait_row,
118
+ convert_trait=convert_trait,
119
+ age_row=age_row,
120
+ convert_age=convert_age,
121
+ gender_row=gender_row,
122
+ convert_gender=convert_gender
123
+ )
124
+ preview = preview_df(selected_clinical_df)
125
+ print(preview)
126
+
127
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
128
+ selected_clinical_df.to_csv(out_clinical_data_file)
129
+
130
+ # Step 3: Gene Data Extraction
131
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
132
+ gene_data = get_genetic_data(matrix_file)
133
+
134
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
135
+ print(gene_data.index[:20])
136
+
137
+ # Step 4: Gene Identifier Review
138
+ requires_gene_mapping = True
139
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
140
+
141
+ # Step 5: Gene Annotation
142
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
143
+ gene_annotation = get_gene_annotation(soft_file)
144
+
145
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
146
+ print("Gene annotation preview:")
147
+ print(preview_df(gene_annotation))
148
+
149
+ # Step 6: Gene Identifier Mapping
150
+ # Determine columns for probe IDs and gene symbols/text
151
+ probe_col = 'ID'
152
+ candidate_gene_cols = [col for col in ['GeneSymbol', 'GeneName', 'Description', 'TargetID'] if col in gene_annotation.columns]
153
+
154
+ # Build a unified gene text column to maximize chance of extracting valid human gene symbols
155
+ if candidate_gene_cols:
156
+ gene_text = gene_annotation[candidate_gene_cols[0]].astype(str)
157
+ for col in candidate_gene_cols[1:]:
158
+ gene_text = gene_text.fillna('') + ' ' + gene_annotation[col].astype(str).fillna('')
159
+ else:
160
+ # Fallback (unlikely to be useful, but prevents failure if annotation is sparse)
161
+ gene_text = gene_annotation[probe_col].astype(str)
162
+
163
+ annotation_for_mapping = gene_annotation[[probe_col]].copy()
164
+ annotation_for_mapping['Gene'] = gene_text
165
+
166
+ # Create mapping dataframe: ensure proper column names
167
+ mapping_df = annotation_for_mapping.rename(columns={probe_col: 'ID'})[['ID', 'Gene']]
168
+
169
+ # Apply mapping to convert probe-level data to gene-level data
170
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
171
+
172
+ # Step 7: Data Normalization and Linking
173
+ import os
174
+
175
+ # 1. Normalize gene symbols and save gene expression data
176
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
177
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
178
+ normalized_gene_data.to_csv(out_gene_data_file)
179
+
180
+ # 2. Link clinical and genetic data
181
+ # Fix variable name to use the dataframe created in Step 2
182
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
183
+
184
+ # 3. Handle missing values
185
+ linked_data = handle_missing_values(linked_data, trait)
186
+
187
+ # 4. Assess bias and remove biased covariates
188
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
189
+
190
+ # 5. Final validation and save cohort info
191
+ is_gene_available_flag = (normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0)
192
+ is_trait_available_flag = trait in selected_clinical_df.index
193
+
194
+ note = "INFO: Agilent human G3/lncRNA platform; probe-to-gene mapping used regex-based symbol extraction and NCBI synonym normalization, which may yield sparse gene coverage."
195
+
196
+ is_usable = validate_and_save_cohort_info(
197
+ is_final=True,
198
+ cohort=cohort,
199
+ info_path=json_path,
200
+ is_gene_available=is_gene_available_flag,
201
+ is_trait_available=is_trait_available_flag,
202
+ is_biased=is_trait_biased,
203
+ df=unbiased_linked_data,
204
+ note=note
205
+ )
206
+
207
+ # 6. Save linked data if usable
208
+ if is_usable:
209
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
210
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Obsessive-Compulsive_Disorder/code/TCGA.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Obsessive-Compulsive_Disorder"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z5/preprocess/Obsessive-Compulsive_Disorder/TCGA.csv"
12
+ out_gene_data_file = "./output/z5/preprocess/Obsessive-Compulsive_Disorder/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z5/preprocess/Obsessive-Compulsive_Disorder/clinical_data/TCGA.csv"
14
+ json_path = "./output/z5/preprocess/Obsessive-Compulsive_Disorder/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import pandas as pd
20
+
21
+ # Step 1: Select the most relevant TCGA subdirectory for the trait (Obsessive-Compulsive_Disorder)
22
+ subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
23
+
24
+ trait_keywords = {
25
+ "obsessive", "compulsive", "ocd", "obsessive-compulsive", "obsessive_compulsive",
26
+ "psychi", "mental", "neuro", "behavior"
27
+ }
28
+ selected_dir = None
29
+ for d in subdirs:
30
+ name_l = d.lower()
31
+ if any(k in name_l for k in trait_keywords):
32
+ selected_dir = d
33
+ break
34
+
35
+ if selected_dir is None:
36
+ print("No TCGA cohort matches the psychiatric trait 'Obsessive-Compulsive Disorder'. Skipping TCGA for this trait.")
37
+ # Record metadata that this trait is not applicable for TCGA cohorts
38
+ validate_and_save_cohort_info(
39
+ is_final=False,
40
+ cohort="TCGA",
41
+ info_path=json_path,
42
+ is_gene_available=False,
43
+ is_trait_available=False
44
+ )
45
+ clinical_df = pd.DataFrame()
46
+ genetic_df = pd.DataFrame()
47
+ else:
48
+ print(f"Selected cohort directory: {selected_dir}")
49
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
50
+
51
+ # Step 2: Identify clinical and genetic data file paths
52
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
53
+ print(f"Clinical file: {clinical_file_path}")
54
+ print(f"Genetic file: {genetic_file_path}")
55
+
56
+ # Step 3: Load both files
57
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False)
58
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False)
59
+
60
+ # Step 4: Print clinical columns
61
+ print("Clinical data columns:")
62
+ print(list(clinical_df.columns))
output/preprocess/Obsessive-Compulsive_Disorder/cohort_info.json CHANGED
@@ -1,22 +1 @@
1
- {
2
- "GSE60190": {
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
- "TCGA": {
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
- }
 
1
+ {"GSE78104": {"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": 60, "note": "INFO: Agilent human G3/lncRNA platform; probe-to-gene mapping used regex-based symbol extraction and NCBI synonym normalization, which may yield sparse gene coverage."}, "GSE60190": {"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": 133, "note": "INFO: Illumina HumanHT-12 v3 platform; DLPFC postmortem samples; trait from 'dx' (OCD vs non-OCD)."}, "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/Obstructive_sleep_apnea/GSE75097.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Obstructive_sleep_apnea/clinical_data/GSE75097.csv CHANGED
@@ -1,4 +1,4 @@
1
  ,GSM1942590,GSM1942591,GSM1942592,GSM1942593,GSM1942594,GSM1942595,GSM1942596,GSM1942597,GSM1942598,GSM1942599,GSM1942600,GSM1942601,GSM1942602,GSM1942603,GSM1942604,GSM1942605,GSM1942606,GSM1942607,GSM1942608,GSM1942609,GSM1942610,GSM1942611,GSM1942612,GSM1942613,GSM1942614,GSM1942615,GSM1942616,GSM1942617,GSM1942618,GSM1942619,GSM1942620,GSM1942621,GSM1942622,GSM1942623,GSM1942624,GSM1942625,GSM1942626,GSM1942627,GSM1942628,GSM1942629,GSM1942630,GSM1942631,GSM1942632,GSM1942633,GSM1942634,GSM1942635,GSM1942636,GSM1942637
2
- Obstructive_sleep_apnea,1.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,1.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,1.0
3
  Age,54.0,31.0,44.0,60.0,21.0,50.0,52.0,58.0,42.0,34.0,58.0,37.0,60.0,59.0,27.0,57.0,68.0,53.0,58.0,52.0,36.0,38.0,50.0,44.0,58.0,54.0,43.0,59.0,44.0,46.0,36.0,59.0,49.0,59.0,68.0,61.0,38.0,45.0,35.0,57.0,42.0,44.0,47.0,50.0,54.0,50.0,47.0,38.0
4
  Gender,1.0,1.0,1.0,1.0,1.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,1.0,0.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.0,1.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
  ,GSM1942590,GSM1942591,GSM1942592,GSM1942593,GSM1942594,GSM1942595,GSM1942596,GSM1942597,GSM1942598,GSM1942599,GSM1942600,GSM1942601,GSM1942602,GSM1942603,GSM1942604,GSM1942605,GSM1942606,GSM1942607,GSM1942608,GSM1942609,GSM1942610,GSM1942611,GSM1942612,GSM1942613,GSM1942614,GSM1942615,GSM1942616,GSM1942617,GSM1942618,GSM1942619,GSM1942620,GSM1942621,GSM1942622,GSM1942623,GSM1942624,GSM1942625,GSM1942626,GSM1942627,GSM1942628,GSM1942629,GSM1942630,GSM1942631,GSM1942632,GSM1942633,GSM1942634,GSM1942635,GSM1942636,GSM1942637
2
+ Obstructive_sleep_apnea,22.7,32.6,56.5,46.9,31.1,4.5,26.7,56.4,22.6,33.4,98.6,73.5,63.3,44.1,50.2,43.8,63.4,79.2,42.1,24.3,2.4,59.9,73.2,64.9,33.2,45.6,4.3,85.1,28.4,86.5,28.1,8.1,30.3,48.6,3.3,65.7,63.9,80.9,94.8,80.2,73.8,73.0,41.5,2.4,47.0,88.8,91.2,78.3
3
  Age,54.0,31.0,44.0,60.0,21.0,50.0,52.0,58.0,42.0,34.0,58.0,37.0,60.0,59.0,27.0,57.0,68.0,53.0,58.0,52.0,36.0,38.0,50.0,44.0,58.0,54.0,43.0,59.0,44.0,46.0,36.0,59.0,49.0,59.0,68.0,61.0,38.0,45.0,35.0,57.0,42.0,44.0,47.0,50.0,54.0,50.0,47.0,38.0
4
  Gender,1.0,1.0,1.0,1.0,1.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,1.0,0.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.0,1.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
output/preprocess/Obstructive_sleep_apnea/code/GSE133601.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Obstructive_sleep_apnea"
6
+ cohort = "GSE133601"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Obstructive_sleep_apnea"
10
+ in_cohort_dir = "../DATA/GEO/Obstructive_sleep_apnea/GSE133601"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z5/preprocess/Obstructive_sleep_apnea/GSE133601.csv"
14
+ out_gene_data_file = "./output/z5/preprocess/Obstructive_sleep_apnea/gene_data/GSE133601.csv"
15
+ out_clinical_data_file = "./output/z5/preprocess/Obstructive_sleep_apnea/clinical_data/GSE133601.csv"
16
+ json_path = "./output/z5/preprocess/Obstructive_sleep_apnea/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 # Gene expression data (mRNA) is described for PBMCs; not miRNA/methylation.
43
+
44
+ # 2. Variable Availability and Data Type Conversion
45
+
46
+ # Based on the sample characteristics:
47
+ # {0: ['tissue: peripheral blood mononuclear cells'],
48
+ # 1: ['subject: ...'], # identifiers only
49
+ # 2: ['timepoint: pre-CPAP', 'timepoint: post-CPAP']} # treatment status, not trait status
50
+ # All participants have OSA; no variability in trait; age and gender not provided.
51
+ trait_row = None
52
+ age_row = None
53
+ gender_row = None
54
+
55
+ def _after_colon(x: str) -> str:
56
+ if x is None:
57
+ return ""
58
+ parts = str(x).split(":", 1)
59
+ return parts[1].strip() if len(parts) > 1 else str(x).strip()
60
+
61
+ def convert_trait(x):
62
+ # Not available in this dataset; attempt a cautious mapping if ever used elsewhere.
63
+ val = _after_colon(x).lower()
64
+ if val in {"osa", "obstructive sleep apnea", "sleep disordered breathing", "sdb", "case", "patient", "osa case"}:
65
+ return 1
66
+ if val in {"control", "healthy", "no osa", "non-osa", "non osa"}:
67
+ return 0
68
+ # timepoint pre/post CPAP is not a valid proxy for trait presence here
69
+ return None
70
+
71
+ def convert_age(x):
72
+ val = _after_colon(x)
73
+ m = re.search(r"(\d+(\.\d+)?)", val)
74
+ if m:
75
+ try:
76
+ return float(m.group(1))
77
+ except Exception:
78
+ return None
79
+ return None
80
+
81
+ def convert_gender(x):
82
+ val = _after_colon(x).lower()
83
+ if val in {"female", "f"}:
84
+ return 0
85
+ if val in {"male", "m"}:
86
+ return 1
87
+ return None
88
+
89
+ # 3. Save Metadata (initial filtering)
90
+ is_trait_available = trait_row is not None
91
+ _ = validate_and_save_cohort_info(
92
+ is_final=False,
93
+ cohort=cohort,
94
+ info_path=json_path,
95
+ is_gene_available=is_gene_available,
96
+ is_trait_available=is_trait_available
97
+ )
98
+
99
+ # 4. Clinical Feature Extraction (skip because trait_row is None)
100
+ if (trait_row is not None) and ('clinical_data' in globals()):
101
+ selected_clinical_df = geo_select_clinical_features(
102
+ clinical_df=clinical_data,
103
+ trait=trait,
104
+ trait_row=trait_row,
105
+ convert_trait=convert_trait,
106
+ age_row=age_row,
107
+ convert_age=convert_age,
108
+ gender_row=gender_row,
109
+ convert_gender=convert_gender
110
+ )
111
+ _preview = preview_df(selected_clinical_df)
112
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
113
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
114
+
115
+ # Step 3: Gene Data Extraction
116
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
117
+ gene_data = get_genetic_data(matrix_file)
118
+
119
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
120
+ print(gene_data.index[:20])
121
+
122
+ # Step 4: Gene Identifier Review
123
+ # The provided identifiers (e.g., '100009676_at', '10000_at') are Affymetrix probe set IDs, not human gene symbols.
124
+ requires_gene_mapping = True
125
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
126
+
127
+ # Step 5: Gene Annotation
128
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
129
+ gene_annotation = get_gene_annotation(soft_file)
130
+
131
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
132
+ print("Gene annotation preview:")
133
+ print(preview_df(gene_annotation))
134
+
135
+ # Step 6: Gene Identifier Mapping
136
+ # Determine the appropriate columns for probe IDs and gene symbols
137
+ anno_cols = list(gene_annotation.columns)
138
+
139
+ # Normalize column names for robust matching
140
+ def norm(col):
141
+ return re.sub(r'[^a-z0-9]', '', col.lower())
142
+
143
+ norm_map = {norm(c): c for c in anno_cols}
144
+
145
+ # Probe ID column candidates (prefer 'ID' if present)
146
+ probe_col = None
147
+ for key in ['id', 'idref', 'probesetid', 'probesid', 'probeid']:
148
+ if key in norm_map:
149
+ probe_col = norm_map[key]
150
+ break
151
+ # Fallback: if nothing found, try exact 'ID' if exists
152
+ if probe_col is None and 'ID' in gene_annotation.columns:
153
+ probe_col = 'ID'
154
+ # As a last resort, use the first column
155
+ if probe_col is None:
156
+ probe_col = anno_cols[0]
157
+
158
+ # Gene symbol column candidates
159
+ gene_col = None
160
+ gene_symbol_keys = [
161
+ 'genesymbol', 'symbol', 'gene_symbols', 'genesymbols', 'hgncsymbol',
162
+ 'gene', 'genesym', 'genes', 'geneid', 'geneids', 'genename', 'genenames',
163
+ 'geneassignment', 'geneassignments'
164
+ ]
165
+ for key in gene_symbol_keys:
166
+ if key in norm_map:
167
+ gene_col = norm_map[key]
168
+ break
169
+ # Reasonable fallbacks commonly seen in GEO GPLs
170
+ if gene_col is None:
171
+ for fallback in ['Gene Symbol', 'Gene symbol', 'SYMBOL', 'Symbol', 'GENE_SYMBOL', 'Gene Assignment', 'Gene assignment', 'Gene Assignment']:
172
+ if fallback in gene_annotation.columns:
173
+ gene_col = fallback
174
+ break
175
+ # Final fallback to 'Description' if no explicit symbol column found
176
+ if gene_col is None:
177
+ gene_col = 'Description' if 'Description' in gene_annotation.columns else anno_cols[-1]
178
+
179
+ # Build mapping dataframe
180
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_col)
181
+
182
+ # Apply mapping to convert probe-level data to gene-level data
183
+ # Preserve original probe-level expression before overwriting
184
+ _probe_expr_df = gene_data
185
+ gene_data = apply_gene_mapping(_probe_expr_df, mapping_df)
186
+
187
+ # Step 7: Data Normalization and Linking
188
+ import os
189
+ import pandas as pd
190
+
191
+ # 1) Normalize gene symbols and save gene data
192
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
193
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
194
+ normalized_gene_data.to_csv(out_gene_data_file)
195
+
196
+ # Initialize linked_data to conform to instruction expectations
197
+ linked_data = None
198
+
199
+ # 2) Try to get clinical features if available; otherwise skip linking
200
+ clinical_df = None
201
+ if 'selected_clinical_data' in globals():
202
+ clinical_df = selected_clinical_data
203
+ else:
204
+ # Attempt to load from previously saved file (if any)
205
+ if os.path.exists(out_clinical_data_file):
206
+ clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
207
+
208
+ # Determine availability of trait/clinical data
209
+ clinical_available = False
210
+ if clinical_df is not None and isinstance(clinical_df, pd.DataFrame):
211
+ clinical_available = trait in clinical_df.index
212
+
213
+ if not clinical_available:
214
+ # No trait/clinical data available: perform final validation as unavailable
215
+ note = "INFO: No clinical trait (OSA) fields present; dataset consists of PBMC pre/post-CPAP samples."
216
+ _ = validate_and_save_cohort_info(
217
+ is_final=True,
218
+ cohort=cohort,
219
+ info_path=json_path,
220
+ is_gene_available=True,
221
+ is_trait_available=False,
222
+ is_biased=False, # placeholder; will be ignored since trait is unavailable
223
+ df=normalized_gene_data.T, # provide a valid-shaped df for consistency
224
+ note=note
225
+ )
226
+ else:
227
+ # 2) Link clinical and genetic data
228
+ linked_data = geo_link_clinical_genetic_data(clinical_df, normalized_gene_data)
229
+
230
+ # 3) Handle missing values (requires the trait column to exist after linking)
231
+ if trait in linked_data.columns:
232
+ linked_data = handle_missing_values(linked_data, trait)
233
+
234
+ # 4) Determine bias and remove biased demographic features
235
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
236
+
237
+ # 5) Final quality check and save cohort info
238
+ note = "INFO: Linked data constructed from PBMC pre/post-CPAP; trait present if clinical features exist."
239
+ is_usable = validate_and_save_cohort_info(
240
+ is_final=True,
241
+ cohort=cohort,
242
+ info_path=json_path,
243
+ is_gene_available=True,
244
+ is_trait_available=True,
245
+ is_biased=is_trait_biased,
246
+ df=unbiased_linked_data,
247
+ note=note
248
+ )
249
+
250
+ # 6) Save linked data only if usable
251
+ if is_usable:
252
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
253
+ unbiased_linked_data.to_csv(out_data_file)
254
+ else:
255
+ # Trait column absent after linking; finalize as unavailable
256
+ note = "INFO: Clinical data found but trait column missing post-linking."
257
+ _ = validate_and_save_cohort_info(
258
+ is_final=True,
259
+ cohort=cohort,
260
+ info_path=json_path,
261
+ is_gene_available=True,
262
+ is_trait_available=False,
263
+ is_biased=False,
264
+ df=normalized_gene_data.T,
265
+ note=note
266
+ )
267
+ linked_data = None
output/preprocess/Obstructive_sleep_apnea/code/GSE135917.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Obstructive_sleep_apnea"
6
+ cohort = "GSE135917"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Obstructive_sleep_apnea"
10
+ in_cohort_dir = "../DATA/GEO/Obstructive_sleep_apnea/GSE135917"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z5/preprocess/Obstructive_sleep_apnea/GSE135917.csv"
14
+ out_gene_data_file = "./output/z5/preprocess/Obstructive_sleep_apnea/gene_data/GSE135917.csv"
15
+ out_clinical_data_file = "./output/z5/preprocess/Obstructive_sleep_apnea/clinical_data/GSE135917.csv"
16
+ json_path = "./output/z5/preprocess/Obstructive_sleep_apnea/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Step 1: Determine data availability
40
+ is_gene_available = True # Affymetrix Human Gene 1.0 ST microarray -> gene expression data available
41
+ # From the provided sample characteristics, only age (row 0), Sex (row 1), and BMI (row 2) are present.
42
+ # No explicit OSA/control/CPAP status key is provided -> trait not available.
43
+ trait_row = None
44
+ age_row = 0
45
+ gender_row = 1
46
+
47
+ # Step 2: Define conversion functions
48
+ def _extract_after_colon(x):
49
+ if x is None:
50
+ return None
51
+ if isinstance(x, str):
52
+ parts = x.split(":", 1)
53
+ val = parts[1] if len(parts) > 1 else parts[0]
54
+ return val.strip()
55
+ return x
56
+
57
+ def convert_trait(x):
58
+ # Generic converter for OSA presence if encountered; not used here since trait_row is None.
59
+ val = _extract_after_colon(x)
60
+ if val is None:
61
+ return None
62
+ v = str(val).strip().lower()
63
+ # Positive OSA indicators
64
+ positive = {"osa", "obstructive sleep apnea", "obstructive sleep apnoea", "sleep apnea", "apnea", "apnoea",
65
+ "case", "patient", "baseline", "pre-cpap", "pre cpap", "untreated"}
66
+ # Negative OSA indicators
67
+ negative = {"control", "healthy", "normal", "none", "no osa", "non-osa", "post-cpap", "post cpap", "treated"}
68
+ if v in positive:
69
+ return 1
70
+ if v in negative:
71
+ return 0
72
+ # Heuristics
73
+ if "osa" in v and ("non" not in v and "no " not in v):
74
+ return 1
75
+ if "control" in v or ("no" in v and "osa" in v):
76
+ return 0
77
+ return None
78
+
79
+ def convert_age(x):
80
+ val = _extract_after_colon(x)
81
+ if val is None:
82
+ return None
83
+ v = str(val).strip()
84
+ if v in {"", "na", "n/a", "nan", "none", "unknown"}:
85
+ return None
86
+ try:
87
+ return float(v)
88
+ except Exception:
89
+ # Attempt to extract numeric content
90
+ import re
91
+ nums = re.findall(r"[-+]?\d*\.?\d+", v)
92
+ if nums:
93
+ try:
94
+ return float(nums[0])
95
+ except Exception:
96
+ return None
97
+ return None
98
+
99
+ def convert_gender(x):
100
+ val = _extract_after_colon(x)
101
+ if val is None:
102
+ return None
103
+ v = str(val).strip().lower()
104
+ if v in {"f", "female", "woman", "women"}:
105
+ return 0
106
+ if v in {"m", "male", "man", "men"}:
107
+ return 1
108
+ return None
109
+
110
+ # Step 3: Save metadata (initial filtering)
111
+ is_trait_available = trait_row is not None
112
+ _ = validate_and_save_cohort_info(
113
+ is_final=False,
114
+ cohort=cohort,
115
+ info_path=json_path,
116
+ is_gene_available=is_gene_available,
117
+ is_trait_available=is_trait_available
118
+ )
119
+
120
+ # Step 4: Clinical feature extraction (skip if trait_row is None)
121
+ if trait_row is not None:
122
+ selected_clinical_df = geo_select_clinical_features(
123
+ clinical_df=clinical_data,
124
+ trait=trait,
125
+ trait_row=trait_row,
126
+ convert_trait=convert_trait,
127
+ age_row=age_row,
128
+ convert_age=convert_age,
129
+ gender_row=gender_row,
130
+ convert_gender=convert_gender
131
+ )
132
+ preview = preview_df(selected_clinical_df, n=5)
133
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
134
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
135
+
136
+ # Step 3: Gene Data Extraction
137
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
138
+ gene_data = get_genetic_data(matrix_file)
139
+
140
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
141
+ print(gene_data.index[:20])
142
+
143
+ # Step 4: Gene Identifier Review
144
+ requires_gene_mapping = True
145
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
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
+ # 1-2. Decide columns: probe IDs in expression match 'ID' in annotation; gene symbols are in 'gene_assignment'
157
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='gene_assignment')
158
+
159
+ # 3. Apply mapping to convert probe-level data to gene-level expression
160
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
161
+
162
+ # Step 7: Data Normalization and Linking
163
+ import os
164
+
165
+ # 1. Normalize gene symbols and save gene expression matrix
166
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
167
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
168
+ normalized_gene_data.to_csv(out_gene_data_file)
169
+
170
+ # Determine if trait/clinical data is available from earlier steps
171
+ has_trait = ('trait_row' in globals() and trait_row is not None)
172
+
173
+ if has_trait:
174
+ # 2. Link clinical and genetic data
175
+ selected_clinical_df = geo_select_clinical_features(
176
+ clinical_df=clinical_data,
177
+ trait=trait,
178
+ trait_row=trait_row,
179
+ convert_trait=convert_trait,
180
+ age_row=age_row if 'age_row' in globals() else None,
181
+ convert_age=convert_age if 'convert_age' in globals() else None,
182
+ gender_row=gender_row if 'gender_row' in globals() else None,
183
+ convert_gender=convert_gender if 'convert_gender' in globals() else None
184
+ )
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. Judge bias and remove biased covariates
191
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
192
+
193
+ # 5. Final validation and save metadata
194
+ is_usable = validate_and_save_cohort_info(
195
+ is_final=True,
196
+ cohort=cohort,
197
+ info_path=json_path,
198
+ is_gene_available=True,
199
+ is_trait_available=True,
200
+ is_biased=is_trait_biased,
201
+ df=unbiased_linked_data,
202
+ note="INFO: Linked clinical and genetic data with standardized gene symbols."
203
+ )
204
+
205
+ # 6. Save usable linked dataset
206
+ if is_usable:
207
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
208
+ unbiased_linked_data.to_csv(out_data_file)
209
+ else:
210
+ # Trait not available: perform final validation for gene-only availability
211
+ is_usable = validate_and_save_cohort_info(
212
+ is_final=True,
213
+ cohort=cohort,
214
+ info_path=json_path,
215
+ is_gene_available=True,
216
+ is_trait_available=False,
217
+ is_biased=False, # Not applicable since trait is unavailable; value ignored in record
218
+ df=normalized_gene_data.T, # Non-empty placeholder to pass structural validation
219
+ note="INFO: Trait not available in sample characteristics; only gene data prepared."
220
+ )
221
+ # Do not attempt linking/saving linked data when trait is unavailable
output/preprocess/Obstructive_sleep_apnea/code/GSE49800.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Obstructive_sleep_apnea"
6
+ cohort = "GSE49800"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Obstructive_sleep_apnea"
10
+ in_cohort_dir = "../DATA/GEO/Obstructive_sleep_apnea/GSE49800"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z5/preprocess/Obstructive_sleep_apnea/GSE49800.csv"
14
+ out_gene_data_file = "./output/z5/preprocess/Obstructive_sleep_apnea/gene_data/GSE49800.csv"
15
+ out_clinical_data_file = "./output/z5/preprocess/Obstructive_sleep_apnea/clinical_data/GSE49800.csv"
16
+ json_path = "./output/z5/preprocess/Obstructive_sleep_apnea/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 Human Gene 1.0 ST microarrays => mRNA gene expression data
43
+
44
+ # 2) Variable availability
45
+ # Trait is Obstructive sleep apnea; all subjects are severe OSA with baseline and post-CPAP only.
46
+ trait_row = None # No variation in OSA status; not useful for association
47
+ age_row = None # Not provided in characteristics
48
+ gender_row = None # Not provided in characteristics
49
+
50
+ # 2.2) Converters
51
+ def _after_colon(x):
52
+ if x is None:
53
+ return None
54
+ s = str(x)
55
+ if ':' in s:
56
+ return s.split(':', 1)[1].strip()
57
+ return s.strip()
58
+
59
+ def convert_trait(x):
60
+ # Binary: 1 = OSA, 0 = non-OSA; map common variants if present
61
+ v = _after_colon(x)
62
+ if v is None or v == '':
63
+ return None
64
+ v_low = v.lower()
65
+ # Positive mappings
66
+ if any(k in v_low for k in ['osa', 'obstructive sleep apnea', 'sleep apnea']):
67
+ return 1
68
+ # Negative mappings
69
+ if any(k in v_low for k in ['control', 'healthy', 'non-osa', 'no osa', 'no sleep apnea', 'normal']):
70
+ return 0
71
+ # Unknown
72
+ return None
73
+
74
+ def convert_age(x):
75
+ v = _after_colon(x)
76
+ if v is None or v == '':
77
+ return None
78
+ m = re.search(r'([-+]?\d*\.?\d+)', v)
79
+ if not m:
80
+ return None
81
+ try:
82
+ return float(m.group(1))
83
+ except Exception:
84
+ return None
85
+
86
+ def convert_gender(x):
87
+ v = _after_colon(x)
88
+ if v is None or v == '':
89
+ return None
90
+ v_low = v.lower()
91
+ if v_low in ['male', 'm', 'man', 'boy']:
92
+ return 1
93
+ if v_low in ['female', 'f', 'woman', 'girl']:
94
+ return 0
95
+ return None
96
+
97
+ # 3) Save metadata (initial filtering)
98
+ is_trait_available = trait_row is not None
99
+ _ = validate_and_save_cohort_info(
100
+ is_final=False,
101
+ cohort=cohort,
102
+ info_path=json_path,
103
+ is_gene_available=is_gene_available,
104
+ is_trait_available=is_trait_available
105
+ )
106
+
107
+ # 4) Clinical feature extraction (skip because trait_row is None)
108
+ # If trait_row becomes available in future revisions, uncomment the below.
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,
117
+ # gender_row=gender_row,
118
+ # convert_gender=convert_gender
119
+ # )
120
+ # _ = preview_df(selected_clinical_df)
121
+ # selected_clinical_df.to_csv(out_clinical_data_file, index=True)
output/preprocess/Obstructive_sleep_apnea/code/GSE75097.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Obstructive_sleep_apnea"
6
+ cohort = "GSE75097"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Obstructive_sleep_apnea"
10
+ in_cohort_dir = "../DATA/GEO/Obstructive_sleep_apnea/GSE75097"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z5/preprocess/Obstructive_sleep_apnea/GSE75097.csv"
14
+ out_gene_data_file = "./output/z5/preprocess/Obstructive_sleep_apnea/gene_data/GSE75097.csv"
15
+ out_clinical_data_file = "./output/z5/preprocess/Obstructive_sleep_apnea/clinical_data/GSE75097.csv"
16
+ json_path = "./output/z5/preprocess/Obstructive_sleep_apnea/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 # Microarray whole-genome expression in PBMC -> gene expression available
41
+
42
+ # Step 2: Identify rows for variables based on the provided Sample Characteristics Dictionary
43
+ trait_row = 1 # apnea hypopnea index (AHI)
44
+ age_row = 3 # age
45
+ gender_row = 2 # Sex
46
+
47
+ # Step 2.2: Define conversion functions
48
+ def _after_colon(value):
49
+ if value is None:
50
+ return None
51
+ try:
52
+ # If value is not a string (already numeric), return as-is
53
+ if not isinstance(value, str):
54
+ return value
55
+ parts = value.split(":", 1)
56
+ return parts[1].strip() if len(parts) > 1 else value.strip()
57
+ except Exception:
58
+ return None
59
+
60
+ def convert_trait(x):
61
+ # Trait: AHI as continuous
62
+ v = _after_colon(x)
63
+ try:
64
+ return float(v)
65
+ except (TypeError, ValueError):
66
+ return None
67
+
68
+ def convert_age(x):
69
+ # Age as continuous
70
+ v = _after_colon(x)
71
+ try:
72
+ return float(v)
73
+ except (TypeError, ValueError):
74
+ return None
75
+
76
+ def convert_gender(x):
77
+ # Gender: female -> 0, male -> 1
78
+ v = _after_colon(x)
79
+ if v is None:
80
+ return None
81
+ s = str(v).strip().lower()
82
+ if s in {"male", "m", "1"}:
83
+ return 1
84
+ if s in {"female", "f", "0"}:
85
+ return 0
86
+ return None
87
+
88
+ # Step 3: Initial filtering and save metadata
89
+ is_trait_available = trait_row is not None
90
+ _ = validate_and_save_cohort_info(
91
+ is_final=False,
92
+ cohort=cohort,
93
+ info_path=json_path,
94
+ is_gene_available=is_gene_available,
95
+ is_trait_available=is_trait_available
96
+ )
97
+
98
+ # Step 4: Clinical feature extraction (only if trait_row is available)
99
+ if trait_row is not None:
100
+ selected_clinical_df = geo_select_clinical_features(
101
+ clinical_df=clinical_data,
102
+ trait=trait,
103
+ trait_row=trait_row,
104
+ convert_trait=convert_trait,
105
+ age_row=age_row,
106
+ convert_age=convert_age,
107
+ gender_row=gender_row,
108
+ convert_gender=convert_gender
109
+ )
110
+ preview = preview_df(selected_clinical_df, n=5)
111
+ print(preview)
112
+
113
+ # Save clinical data
114
+ out_dir = os.path.dirname(out_clinical_data_file)
115
+ os.makedirs(out_dir, exist_ok=True)
116
+ selected_clinical_df.to_csv(out_clinical_data_file)
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
+ print("requires_gene_mapping = False")
127
+
128
+ # Step 5: Data Normalization and Linking
129
+ # 1. Normalize gene symbols and save
130
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
131
+
132
+ # Ensure the output directory exists before saving gene data
133
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
134
+ normalized_gene_data.to_csv(out_gene_data_file)
135
+
136
+ # 2. Link clinical and genetic data
137
+ # Use the in-memory clinical df if available; otherwise, load from saved file
138
+ if 'selected_clinical_df' not in locals():
139
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
140
+
141
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
142
+
143
+ # 3. Handle missing values
144
+ linked_data = handle_missing_values(linked_data, trait)
145
+
146
+ # 4. Bias evaluation and removal of biased demographic features
147
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
148
+
149
+ # 5. Final validation and save cohort info
150
+ is_gene_available_final = normalized_gene_data.shape[0] > 0
151
+ is_trait_available_final = (trait in linked_data.columns) and (len(linked_data) > 0)
152
+
153
+ note = "INFO: Trait is continuous (AHI); platform already in gene symbols; gene symbols normalized via NCBI synonyms."
154
+ is_usable = validate_and_save_cohort_info(
155
+ is_final=True,
156
+ cohort=cohort,
157
+ info_path=json_path,
158
+ is_gene_available=is_gene_available_final,
159
+ is_trait_available=is_trait_available_final,
160
+ is_biased=is_trait_biased,
161
+ df=unbiased_linked_data,
162
+ note=note
163
+ )
164
+
165
+ # 6. Save linked data if usable
166
+ if is_usable:
167
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
168
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Obstructive_sleep_apnea/code/TCGA.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Obstructive_sleep_apnea"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z5/preprocess/Obstructive_sleep_apnea/TCGA.csv"
12
+ out_gene_data_file = "./output/z5/preprocess/Obstructive_sleep_apnea/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z5/preprocess/Obstructive_sleep_apnea/clinical_data/TCGA.csv"
14
+ json_path = "./output/z5/preprocess/Obstructive_sleep_apnea/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import re
20
+ import pandas as pd
21
+
22
+ # Step 1: Select the most relevant TCGA cohort directory for Obstructive_sleep_apnea using strict token matching
23
+ all_dirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
24
+
25
+ sleep_tokens = {'sleep', 'apnea', 'apnoea', 'sleepdisordered', 'sleepdisorder'}
26
+ # 'osa' only counts if accompanied by sleep/apnea terms
27
+ def get_tokens(name: str):
28
+ return set(re.findall(r'[a-z]+', name.lower()))
29
+
30
+ def score_dir(name: str) -> int:
31
+ tokens = get_tokens(name)
32
+ has_primary = len(tokens & sleep_tokens) > 0
33
+ has_osa_with_context = ('osa' in tokens) and has_primary
34
+ return (len(tokens & sleep_tokens)) * 2 + (1 if has_osa_with_context else 0)
35
+
36
+ scored = [(d, score_dir(d)) for d in all_dirs]
37
+ scored.sort(key=lambda x: x[1], reverse=True)
38
+ selected_dir = scored[0][0] if scored and scored[0][1] > 0 else None
39
+
40
+ clinical_df = None
41
+ genetic_df = None
42
+
43
+ if selected_dir is None:
44
+ print(f"No suitable TCGA cohort found for trait: {trait}. Skipping TCGA for this trait.")
45
+ # Record: gene data exists in TCGA repository, but no relevant trait data is available
46
+ validate_and_save_cohort_info(
47
+ is_final=False,
48
+ cohort="TCGA",
49
+ info_path=json_path,
50
+ is_gene_available=True,
51
+ is_trait_available=False
52
+ )
53
+ else:
54
+ print(f"Selected cohort: {selected_dir}")
55
+ # Step 2: Identify clinical and genetic file paths
56
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
57
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
58
+
59
+ # Step 3: Load both files
60
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False)
61
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False)
62
+
63
+ # Step 4: Print clinical column names
64
+ print(list(clinical_df.columns))
output/preprocess/Obstructive_sleep_apnea/cohort_info.json CHANGED
@@ -1,52 +1 @@
1
- {
2
- "GSE75097": {
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": true,
9
- "has_gender": true,
10
- "sample_size": 48
11
- },
12
- "GSE49800": {
13
- "is_usable": true,
14
- "is_gene_available": true,
15
- "is_trait_available": true,
16
- "is_available": true,
17
- "is_biased": false,
18
- "has_age": false,
19
- "has_gender": false,
20
- "sample_size": 36
21
- },
22
- "GSE135917": {
23
- "is_usable": false,
24
- "is_gene_available": true,
25
- "is_trait_available": false,
26
- "is_available": false,
27
- "is_biased": null,
28
- "has_age": null,
29
- "has_gender": null,
30
- "sample_size": null
31
- },
32
- "GSE133601": {
33
- "is_usable": true,
34
- "is_gene_available": true,
35
- "is_trait_available": true,
36
- "is_available": true,
37
- "is_biased": false,
38
- "has_age": false,
39
- "has_gender": false,
40
- "sample_size": 30
41
- },
42
- "TCGA": {
43
- "is_usable": true,
44
- "is_gene_available": true,
45
- "is_trait_available": true,
46
- "is_available": true,
47
- "is_biased": false,
48
- "has_age": true,
49
- "has_gender": true,
50
- "sample_size": 566
51
- }
52
- }
 
1
+ {"GSE75097": {"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": 48, "note": "INFO: Trait is continuous (AHI); platform already in gene symbols; gene symbols normalized via NCBI synonyms."}, "GSE49800": {"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}, "GSE135917": {"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 not available in sample characteristics; only gene data prepared."}, "GSE133601": {"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: No clinical trait (OSA) fields present; dataset consists of PBMC pre/post-CPAP samples."}, "TCGA": {"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}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Ocular_Melanomas/clinical_data/GSE60464.csv CHANGED
@@ -1,2 +1,2 @@
1
  ,GSM1480415,GSM1480416,GSM1480417,GSM1480418,GSM1480419,GSM1480420,GSM1480421,GSM1480422,GSM1480423,GSM1480424,GSM1480425,GSM1480426,GSM1480427,GSM1480428,GSM1480429,GSM1480430,GSM1480431,GSM1480432,GSM1480433,GSM1480434,GSM1480435,GSM1480436,GSM1480437,GSM1480438,GSM1480439,GSM1480440,GSM1480441,GSM1480442,GSM1480443,GSM1480444,GSM1480445,GSM1480446,GSM1480447,GSM1480448,GSM1480449,GSM1480450,GSM1480451,GSM1480452,GSM1480453,GSM1480454,GSM1480455,GSM1480456
2
- Ocular_Melanomas,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
 
1
  ,GSM1480415,GSM1480416,GSM1480417,GSM1480418,GSM1480419,GSM1480420,GSM1480421,GSM1480422,GSM1480423,GSM1480424,GSM1480425,GSM1480426,GSM1480427,GSM1480428,GSM1480429,GSM1480430,GSM1480431,GSM1480432,GSM1480433,GSM1480434,GSM1480435,GSM1480436,GSM1480437,GSM1480438,GSM1480439,GSM1480440,GSM1480441,GSM1480442,GSM1480443,GSM1480444,GSM1480445,GSM1480446,GSM1480447,GSM1480448,GSM1480449,GSM1480450,GSM1480451,GSM1480452,GSM1480453,GSM1480454,GSM1480455,GSM1480456
2
+ Ocular_Melanomas,0.0,0.0,0.0,0.0,0.0,0.0,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
output/preprocess/Ocular_Melanomas/clinical_data/TCGA.csv ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ sampleID,Ocular_Melanomas,Age,Gender
2
+ TCGA-RZ-AB0B-01,1,47,0
3
+ TCGA-V3-A9ZX-01,1,56,1
4
+ TCGA-V3-A9ZY-01,1,54,1
5
+ TCGA-V4-A9E5-01,1,51,0
6
+ TCGA-V4-A9E7-01,1,76,1
7
+ TCGA-V4-A9E8-01,1,49,1
8
+ TCGA-V4-A9E9-01,1,50,1
9
+ TCGA-V4-A9EA-01,1,66,1
10
+ TCGA-V4-A9EC-01,1,75,0
11
+ TCGA-V4-A9ED-01,1,45,1
12
+ TCGA-V4-A9EE-01,1,86,1
13
+ TCGA-V4-A9EF-01,1,56,1
14
+ TCGA-V4-A9EH-01,1,53,1
15
+ TCGA-V4-A9EI-01,1,78,1
16
+ TCGA-V4-A9EJ-01,1,38,1
17
+ TCGA-V4-A9EK-01,1,37,0
18
+ TCGA-V4-A9EL-01,1,60,1
19
+ TCGA-V4-A9EM-01,1,53,1
20
+ TCGA-V4-A9EO-01,1,74,1
21
+ TCGA-V4-A9EQ-01,1,64,1
22
+ TCGA-V4-A9ES-01,1,54,0
23
+ TCGA-V4-A9ET-01,1,57,1
24
+ TCGA-V4-A9EU-01,1,83,0
25
+ TCGA-V4-A9EV-01,1,59,0
26
+ TCGA-V4-A9EW-01,1,44,0
27
+ TCGA-V4-A9EX-01,1,55,0
28
+ TCGA-V4-A9EY-01,1,66,0
29
+ TCGA-V4-A9EZ-01,1,78,0
30
+ TCGA-V4-A9F0-01,1,59,1
31
+ TCGA-V4-A9F1-01,1,46,0
32
+ TCGA-V4-A9F2-01,1,78,0
33
+ TCGA-V4-A9F3-01,1,49,0
34
+ TCGA-V4-A9F4-01,1,41,1
35
+ TCGA-V4-A9F5-01,1,85,0
36
+ TCGA-V4-A9F7-01,1,78,0
37
+ TCGA-V4-A9F8-01,1,68,1
38
+ TCGA-VD-A8K7-01,1,39,1
39
+ TCGA-VD-A8K8-01,1,56,0
40
+ TCGA-VD-A8K9-01,1,71,0
41
+ TCGA-VD-A8KA-01,1,22,1
42
+ TCGA-VD-A8KB-01,1,66,0
43
+ TCGA-VD-A8KD-01,1,72,1
44
+ TCGA-VD-A8KE-01,1,74,0
45
+ TCGA-VD-A8KF-01,1,68,1
46
+ TCGA-VD-A8KG-01,1,47,0
47
+ TCGA-VD-A8KH-01,1,69,1
48
+ TCGA-VD-A8KI-01,1,68,1
49
+ TCGA-VD-A8KJ-01,1,53,1
50
+ TCGA-VD-A8KK-01,1,54,1
51
+ TCGA-VD-A8KL-01,1,77,0
52
+ TCGA-VD-A8KM-01,1,65,1
53
+ TCGA-VD-A8KN-01,1,60,0
54
+ TCGA-VD-A8KO-01,1,51,1
55
+ TCGA-VD-AA8M-01,1,64,1
56
+ TCGA-VD-AA8N-01,1,86,1
57
+ TCGA-VD-AA8O-01,1,77,1
58
+ TCGA-VD-AA8P-01,1,64,0
59
+ TCGA-VD-AA8Q-01,1,71,1
60
+ TCGA-VD-AA8R-01,1,78,0
61
+ TCGA-VD-AA8S-01,1,40,1
62
+ TCGA-VD-AA8T-01,1,83,0
63
+ TCGA-WC-A87T-01,1,64,1
64
+ TCGA-WC-A87U-01,1,73,1
65
+ TCGA-WC-A87W-01,1,57,0
66
+ TCGA-WC-A87Y-01,1,59,1
67
+ TCGA-WC-A880-01,1,63,1
68
+ TCGA-WC-A881-01,1,75,1
69
+ TCGA-WC-A882-01,1,50,0
70
+ TCGA-WC-A883-01,1,76,0
71
+ TCGA-WC-A884-01,1,35,0
72
+ TCGA-WC-A885-01,1,60,1
73
+ TCGA-WC-A888-01,1,76,1
74
+ TCGA-WC-A88A-01,1,75,1
75
+ TCGA-WC-AA9A-01,1,70,0
76
+ TCGA-WC-AA9E-01,1,60,1
77
+ TCGA-YZ-A980-01,1,75,1
78
+ TCGA-YZ-A982-01,1,79,0
79
+ TCGA-YZ-A983-01,1,51,0
80
+ TCGA-YZ-A984-01,1,50,0
81
+ TCGA-YZ-A985-01,1,41,0
output/preprocess/Ocular_Melanomas/code/GSE60464.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Ocular_Melanomas"
6
+ cohort = "GSE60464"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Ocular_Melanomas"
10
+ in_cohort_dir = "../DATA/GEO/Ocular_Melanomas/GSE60464"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z5/preprocess/Ocular_Melanomas/GSE60464.csv"
14
+ out_gene_data_file = "./output/z5/preprocess/Ocular_Melanomas/gene_data/GSE60464.csv"
15
+ out_clinical_data_file = "./output/z5/preprocess/Ocular_Melanomas/clinical_data/GSE60464.csv"
16
+ json_path = "./output/z5/preprocess/Ocular_Melanomas/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 # Based on series design: expression profiles of ~9,829 unique genes
44
+
45
+ # 2) Variable availability and conversion functions
46
+ # Trait (Ocular_Melanomas): infer from "location of primary melanoma"
47
+ trait_row = 5 # 'location of primary melanoma' with values including 'Ocular'
48
+ age_row = None
49
+ gender_row = None
50
+
51
+ def _after_colon(value: str) -> str:
52
+ if value is None:
53
+ return ""
54
+ s = str(value)
55
+ # Take the substring after the last colon to avoid retaining the header
56
+ if ":" in s:
57
+ s = s.split(":")[-1]
58
+ return s.strip()
59
+
60
+ def convert_trait(value):
61
+ s = _after_colon(value).lower()
62
+ if s in {"", "unknown", "na", "n/a", "none"}:
63
+ return None
64
+ # Map ocular primary site to 1, others to 0
65
+ return 1 if "ocular" in s else 0
66
+
67
+ def convert_age(value):
68
+ s = _after_colon(value).lower()
69
+ if s in {"", "unknown", "na", "n/a", "none"}:
70
+ return None
71
+ m = re.search(r'\d+(\.\d+)?', s)
72
+ return float(m.group()) if m else None
73
+
74
+ def convert_gender(value):
75
+ s = _after_colon(value).lower()
76
+ if s in {"", "unknown", "na", "n/a", "none"}:
77
+ return None
78
+ if s in {"female", "f", "woman", "women"}:
79
+ return 0
80
+ if s in {"male", "m", "man", "men"}:
81
+ return 1
82
+ return None
83
+
84
+ # 3) Initial filtering and save metadata
85
+ is_trait_available = trait_row is not None
86
+ _ = validate_and_save_cohort_info(
87
+ is_final=False,
88
+ cohort=cohort,
89
+ info_path=json_path,
90
+ is_gene_available=is_gene_available,
91
+ is_trait_available=is_trait_available
92
+ )
93
+
94
+ # 4) Clinical feature extraction (only if clinical data is available)
95
+ if trait_row is not None:
96
+ selected_clinical_df = geo_select_clinical_features(
97
+ clinical_df=clinical_data,
98
+ trait=trait,
99
+ trait_row=trait_row,
100
+ convert_trait=convert_trait,
101
+ age_row=age_row,
102
+ convert_age=convert_age if age_row is not None else None,
103
+ gender_row=gender_row,
104
+ convert_gender=convert_gender if gender_row is not None else None
105
+ )
106
+ preview = preview_df(selected_clinical_df)
107
+ print(preview)
108
+
109
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
110
+ selected_clinical_df.to_csv(out_clinical_data_file)
111
+
112
+ # Step 3: Gene Data Extraction
113
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
114
+ gene_data = get_genetic_data(matrix_file)
115
+
116
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
117
+ print(gene_data.index[:20])
118
+
119
+ # Step 4: Gene Identifier Review
120
+ print("requires_gene_mapping = True")
121
+
122
+ # Step 5: Gene Annotation
123
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
124
+ gene_annotation = get_gene_annotation(soft_file)
125
+
126
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
127
+ print("Gene annotation preview:")
128
+ print(preview_df(gene_annotation))
129
+
130
+ # Step 6: Gene Identifier Mapping
131
+ # Identify the appropriate columns for probe IDs and gene symbols in the annotation
132
+ id_col = 'ID'
133
+ candidate_symbol_cols = ['Symbol', 'ILMN_Gene', 'Search_Key']
134
+
135
+ # Try mapping using candidate symbol columns until a non-empty mapping result is obtained
136
+ mapped_gene_data = None
137
+ for gene_col in candidate_symbol_cols:
138
+ if gene_col not in gene_annotation.columns:
139
+ continue
140
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=id_col, gene_col=gene_col)
141
+ try:
142
+ candidate = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
143
+ if candidate is not None and candidate.shape[0] > 0:
144
+ mapped_gene_data = candidate
145
+ break
146
+ except Exception:
147
+ continue
148
+
149
+ # Fallback: if all attempts failed, raise an error
150
+ if mapped_gene_data is None or mapped_gene_data.shape[0] == 0:
151
+ raise ValueError("Failed to map probe IDs to gene symbols using available annotation columns.")
152
+
153
+ # Use the mapped gene expression data as gene_data
154
+ gene_data = mapped_gene_data
155
+
156
+ # Step 7: Data Normalization and Linking
157
+ import os
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
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
166
+
167
+ # 3. Handle missing values
168
+ linked_data = handle_missing_values(linked_data, trait)
169
+
170
+ # 4. Assess bias and remove biased demographic features
171
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
172
+
173
+ # 5. Final validation and save cohort info
174
+ is_gene_available_flag = (normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0)
175
+ is_trait_available_flag = (trait in selected_clinical_df.index) and (not selected_clinical_df.loc[trait].isna().all())
176
+ note = "INFO: Trait inferred from 'location of primary melanoma'; Age/Gender unavailable in series characteristics."
177
+
178
+ is_usable = validate_and_save_cohort_info(
179
+ is_final=True,
180
+ cohort=cohort,
181
+ info_path=json_path,
182
+ is_gene_available=is_gene_available_flag,
183
+ is_trait_available=is_trait_available_flag,
184
+ is_biased=is_trait_biased,
185
+ df=unbiased_linked_data,
186
+ note=note
187
+ )
188
+
189
+ # 6. Save linked data 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)
output/preprocess/Ocular_Melanomas/code/GSE78033.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Ocular_Melanomas"
6
+ cohort = "GSE78033"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Ocular_Melanomas"
10
+ in_cohort_dir = "../DATA/GEO/Ocular_Melanomas/GSE78033"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z5/preprocess/Ocular_Melanomas/GSE78033.csv"
14
+ out_gene_data_file = "./output/z5/preprocess/Ocular_Melanomas/gene_data/GSE78033.csv"
15
+ out_clinical_data_file = "./output/z5/preprocess/Ocular_Melanomas/clinical_data/GSE78033.csv"
16
+ json_path = "./output/z5/preprocess/Ocular_Melanomas/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 Human Exon 1.0 ST Array => mRNA expression)
42
+ is_gene_available = True
43
+
44
+ # 2) Variable availability (from provided Sample Characteristics Dictionary)
45
+ # Trait is "Ocular_Melanomas" (all samples are melanoma; no healthy controls), so not variable here.
46
+ trait_row = None
47
+ age_row = None
48
+ gender_row = None
49
+
50
+ # 2.2) Converters
51
+ def _after_colon(x):
52
+ if x is None:
53
+ return None
54
+ s = str(x)
55
+ parts = s.split(":", 1)
56
+ val = parts[1] if len(parts) > 1 else parts[0]
57
+ return val.strip()
58
+
59
+ def convert_trait(x):
60
+ # Binary: 1 = Ocular melanoma present; 0 = control/normal. Here not used (trait_row=None).
61
+ val = _after_colon(x)
62
+ if val is None:
63
+ return None
64
+ v = val.lower()
65
+ # Positive melanoma indicators
66
+ pos_tokens = [
67
+ "uveal melanoma", "ocular melanoma", "primary ocular tumor",
68
+ "metastasis", "primary tumor", "xenograft", "pdx", "tumor"
69
+ ]
70
+ if any(t in v for t in pos_tokens):
71
+ return 1
72
+ # Negative/control indicators
73
+ neg_tokens = ["control", "normal", "healthy", "benign", "adjacent normal"]
74
+ if any(t in v for t in neg_tokens):
75
+ return 0
76
+ return None
77
+
78
+ def convert_age(x):
79
+ # Continuous age in years if present; else None
80
+ val = _after_colon(x)
81
+ if val is None:
82
+ return None
83
+ m = re.search(r"(\d+(?:\.\d+)?)", val)
84
+ if not m:
85
+ return None
86
+ try:
87
+ num = float(m.group(1))
88
+ return num
89
+ except Exception:
90
+ return None
91
+
92
+ def convert_gender(x):
93
+ # Binary: female->0, male->1
94
+ val = _after_colon(x)
95
+ if val is None:
96
+ return None
97
+ v = val.strip().lower()
98
+ if v in {"female", "f"}:
99
+ return 0
100
+ if v in {"male", "m"}:
101
+ return 1
102
+ return None
103
+
104
+ # 3) Save metadata (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 (skip if trait_row is None)
115
+ if trait_row is not None:
116
+ selected_clinical_df = geo_select_clinical_features(
117
+ clinical_df=clinical_data,
118
+ trait=trait,
119
+ trait_row=trait_row,
120
+ convert_trait=convert_trait,
121
+ age_row=age_row,
122
+ convert_age=convert_age,
123
+ gender_row=gender_row,
124
+ convert_gender=convert_gender
125
+ )
126
+ _ = preview_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)
129
+
130
+ # Step 3: Gene Data Extraction
131
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
132
+ gene_data = get_genetic_data(matrix_file)
133
+
134
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
135
+ print(gene_data.index[:20])
136
+
137
+ # Step 4: Gene Identifier Review
138
+ print("requires_gene_mapping = True")
139
+
140
+ # Step 5: Gene Annotation
141
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
142
+ gene_annotation = get_gene_annotation(soft_file)
143
+
144
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
145
+ print("Gene annotation preview:")
146
+ print(preview_df(gene_annotation))
147
+
148
+ # Step 6: Gene Identifier Mapping
149
+ # Identify the appropriate columns for mapping based on the preview:
150
+ # - Probe/identifier column in annotation: 'ID' (e.g., '10000_at')
151
+ # - Gene symbol column in annotation: 'SPOT_ID' (e.g., 'AKT3')
152
+
153
+ # 2) Build mapping dataframe
154
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='SPOT_ID')
155
+
156
+ # 3) Apply mapping to convert probe-level data to gene-level expression
157
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
158
+
159
+ # Step 7: Data Normalization and Linking
160
+ import os
161
+ import pandas as pd
162
+
163
+ # 1. Normalize the obtained gene data 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
+ # 2-6. Branch depending on availability of clinical features from earlier steps
169
+ linked_data = None
170
+ has_clinical = ('selected_clinical_data' in globals() and
171
+ isinstance(selected_clinical_data, pd.DataFrame) and
172
+ not selected_clinical_data.empty)
173
+
174
+ if has_clinical:
175
+ # 2. Link clinical and genetic data
176
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
177
+
178
+ # 3. Handle missing values
179
+ linked_data = handle_missing_values(linked_data, trait)
180
+
181
+ # 4. Bias assessment and removal of biased demographic features
182
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
183
+
184
+ # 5. Final validation and save cohort info
185
+ note = "INFO: Clinical features linked with gene expression; missing values handled; demographic biases addressed."
186
+ is_usable = validate_and_save_cohort_info(
187
+ is_final=True,
188
+ cohort=cohort,
189
+ info_path=json_path,
190
+ is_gene_available=True,
191
+ is_trait_available=True,
192
+ is_biased=is_trait_biased,
193
+ df=unbiased_linked_data,
194
+ note=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)
201
+
202
+ else:
203
+ # No trait/clinical data available (trait_row was None in Step 2)
204
+ note = "INFO: Trait/clinical data unavailable (trait_row=None). Skipping linking; saved normalized gene data only."
205
+ _ = validate_and_save_cohort_info(
206
+ is_final=True,
207
+ cohort=cohort,
208
+ info_path=json_path,
209
+ is_gene_available=True,
210
+ is_trait_available=False,
211
+ is_biased=False,
212
+ df=normalized_gene_data.T, # pass gene data for record; not used for availability
213
+ note=note
214
+ )
output/preprocess/Ocular_Melanomas/code/TCGA.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Ocular_Melanomas"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z5/preprocess/Ocular_Melanomas/TCGA.csv"
12
+ out_gene_data_file = "./output/z5/preprocess/Ocular_Melanomas/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z5/preprocess/Ocular_Melanomas/clinical_data/TCGA.csv"
14
+ json_path = "./output/z5/preprocess/Ocular_Melanomas/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import pandas as pd
20
+
21
+ # Select the most relevant TCGA cohort directory for Ocular Melanomas
22
+ selected_dir_name = 'TCGA_Ocular_melanomas_(UVM)'
23
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir_name)
24
+
25
+ # Identify clinical and genetic file paths
26
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
27
+
28
+ # Load dataframes
29
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False)
30
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False)
31
+
32
+ # Print clinical column names for inspection
33
+ print(list(clinical_df.columns))
34
+
35
+ # Step 2: Find Candidate Demographic Features
36
+ import os
37
+ import re
38
+ import pandas as pd
39
+
40
+ # Identify the cohort directory for UVM within the TCGA root directory
41
+ cohort_dirs = [
42
+ os.path.join(tcga_root_dir, d)
43
+ for d in os.listdir(tcga_root_dir)
44
+ if os.path.isdir(os.path.join(tcga_root_dir, d))
45
+ ]
46
+ uvm_dirs = [d for d in cohort_dirs if 'UVM' in os.path.basename(d).upper()]
47
+ cohort_dir = uvm_dirs[0] if uvm_dirs else (cohort_dirs[0] if cohort_dirs else None)
48
+
49
+ # Load clinical data
50
+ clinical_df = pd.DataFrame()
51
+ if cohort_dir is not None:
52
+ try:
53
+ clinical_file_path, _ = tcga_get_relevant_filepaths(cohort_dir)
54
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', header=0, index_col=0, dtype=str)
55
+ except Exception:
56
+ clinical_df = pd.DataFrame()
57
+
58
+ # Determine candidate columns for age and gender from available columns
59
+ columns = clinical_df.columns.tolist() if not clinical_df.empty else [
60
+ '_INTEGRATION', '_PATIENT', '_cohort', '_primary_disease', '_primary_site',
61
+ 'additional_pharmaceutical_therapy', 'additional_radiation_therapy',
62
+ 'age_at_initial_pathologic_diagnosis', 'bcr_followup_barcode', 'bcr_patient_barcode',
63
+ 'bcr_sample_barcode', 'clinical_M', 'clinical_N', 'clinical_T', 'clinical_stage',
64
+ 'cytogenetic_abnormality', 'days_to_birth', 'days_to_collection', 'days_to_death',
65
+ 'days_to_initial_pathologic_diagnosis', 'days_to_last_followup',
66
+ 'days_to_new_tumor_event_after_initial_treatment', 'extranocular_nodule_size',
67
+ 'extrascleral_extension', 'extravascular_matrix_patterns', 'eye_color',
68
+ 'form_completion_date', 'gender', 'gene_expression_profile', 'height',
69
+ 'histological_type', 'history_of_neoadjuvant_treatment', 'icd_10',
70
+ 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified',
71
+ 'initial_pathologic_diagnosis_method', 'initial_weight', 'is_ffpe', 'lost_follow_up',
72
+ 'metastatic_site', 'mitotic_count',
73
+ 'new_neoplasm_event_occurrence_anatomic_site', 'new_neoplasm_event_type',
74
+ 'new_neoplasm_occurrence_anatomic_site_text',
75
+ 'new_tumor_event_additional_surgery_procedure',
76
+ 'new_tumor_event_after_initial_treatment', 'oct_embedded', 'other_dx',
77
+ 'other_metastatic_site', 'pathologic_M', 'pathologic_N', 'pathologic_T',
78
+ 'pathologic_stage', 'pathology_report_file_name', 'patient_death_reason',
79
+ 'patient_id', 'person_neoplasm_cancer_status', 'postoperative_rx_tx',
80
+ 'radiation_therapy', 'sample_type', 'sample_type_id', 'system_version',
81
+ 'tissue_prospective_collection_indicator',
82
+ 'tissue_retrospective_collection_indicator', 'tissue_source_site',
83
+ 'tumor_basal_diameter', 'tumor_basal_diameter_mx',
84
+ 'tumor_infiltrating_lymphocytes', 'tumor_infiltrating_macrophages',
85
+ 'tumor_morphology_percentage', 'tumor_shape_pathologic_clinical',
86
+ 'tumor_thickness', 'tumor_thickness_measurement', 'tumor_tissue_site',
87
+ 'vial_number', 'vital_status', 'weight',
88
+ 'year_of_initial_pathologic_diagnosis',
89
+ '_GENOMIC_ID_TCGA_UVM_mutation_bcgsc_gene', '_GENOMIC_ID_TCGA_UVM_gistic2thd',
90
+ '_GENOMIC_ID_TCGA_UVM_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_UVM_miRNA_HiSeq',
91
+ '_GENOMIC_ID_TCGA_UVM_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_UVM_exp_HiSeqV2',
92
+ '_GENOMIC_ID_TCGA_UVM_gistic2', '_GENOMIC_ID_TCGA_UVM_exp_HiSeqV2_percentile',
93
+ '_GENOMIC_ID_TCGA_UVM_mutation_bcm_gene', '_GENOMIC_ID_TCGA_UVM_hMethyl450',
94
+ '_GENOMIC_ID_TCGA_UVM_mutation_ucsc_maf_gene',
95
+ '_GENOMIC_ID_TCGA_UVM_mutation_broad_gene', '_GENOMIC_ID_TCGA_UVM_RPPA',
96
+ '_GENOMIC_ID_TCGA_UVM_exp_HiSeqV2_exon',
97
+ '_GENOMIC_ID_TCGA_UVM_mutation_curated_broad_gene',
98
+ '_GENOMIC_ID_TCGA_UVM_PDMRNAseq', '_GENOMIC_ID_data/public/TCGA/UVM/miRNA_HiSeq_gene'
99
+ ]
100
+
101
+ def is_age_col(name: str) -> bool:
102
+ n = name.lower()
103
+ if n in ('days_to_birth', 'age', 'age_at_diagnosis'):
104
+ return True
105
+ if 'age_at' in n:
106
+ return True
107
+ if n.startswith('age_') or n.startswith('ageat'):
108
+ return True
109
+ return False
110
+
111
+ def is_gender_col(name: str) -> bool:
112
+ n = name.lower()
113
+ return n in ('gender', 'sex')
114
+
115
+ candidate_age_cols = [c for c in columns if is_age_col(c)]
116
+ candidate_gender_cols = [c for c in columns if is_gender_col(c)]
117
+
118
+ # Print the required lists in the exact format
119
+ print(f"candidate_age_cols = {candidate_age_cols}")
120
+ print(f"candidate_gender_cols = {candidate_gender_cols}")
121
+
122
+ # Extract and preview candidate columns, if clinical data is available
123
+ preview_dict = {}
124
+ if not clinical_df.empty:
125
+ selected_cols = [c for c in (candidate_age_cols + candidate_gender_cols) if c in clinical_df.columns]
126
+ if selected_cols:
127
+ preview_dict = preview_df(clinical_df[selected_cols], n=5)
128
+
129
+ # Display the preview dictionary
130
+ print(preview_dict)
131
+
132
+ # Step 3: Select Demographic Features
133
+ # Select demographic feature columns based on candidate lists and value semantics.
134
+ # Prefer 'age_at_initial_pathologic_diagnosis' over 'days_to_birth' because tcga_convert_age extracts digits,
135
+ # which would misinterpret negative days as a large positive age.
136
+ try:
137
+ # Default to None
138
+ age_col = None
139
+ gender_col = None
140
+
141
+ # Choose age column
142
+ if 'candidate_age_cols' in globals() and isinstance(candidate_age_cols, list) and len(candidate_age_cols) > 0:
143
+ if 'age_at_initial_pathologic_diagnosis' in candidate_age_cols:
144
+ age_col = 'age_at_initial_pathologic_diagnosis'
145
+ elif len(candidate_age_cols) == 1:
146
+ age_col = candidate_age_cols[0]
147
+ else:
148
+ # Fallback heuristic: pick the first that contains 'age'
149
+ age_like = [c for c in candidate_age_cols if 'age' in c.lower()]
150
+ age_col = age_like[0] if age_like else None
151
+
152
+ # Choose gender column
153
+ if 'candidate_gender_cols' in globals() and isinstance(candidate_gender_cols, list) and len(candidate_gender_cols) > 0:
154
+ if 'gender' in candidate_gender_cols:
155
+ gender_col = 'gender'
156
+ elif len(candidate_gender_cols) == 1:
157
+ gender_col = candidate_gender_cols[0]
158
+ else:
159
+ # Fallback heuristic: pick the first that contains 'gender' or 'sex'
160
+ g_like = [c for c in candidate_gender_cols if ('gender' in c.lower() or 'sex' in c.lower())]
161
+ gender_col = g_like[0] if g_like else None
162
+
163
+ print(f"Selected age_col: {age_col}")
164
+ print(f"Selected gender_col: {gender_col}")
165
+
166
+ # Try to print the first 5 preview values if an appropriate preview dictionary exists in the environment
167
+ def try_print_preview(col_name: str, label: str):
168
+ if not col_name:
169
+ print(f"No {label} column selected; preview unavailable.")
170
+ return
171
+ preview_found = False
172
+ for v in globals().values():
173
+ if isinstance(v, dict) and col_name in v and isinstance(v[col_name], list):
174
+ print(f"Preview values for {label} ({col_name}): {v[col_name]}")
175
+ preview_found = True
176
+ break
177
+ if not preview_found:
178
+ print(f"No preview values found in environment for {label} ({col_name}).")
179
+
180
+ try_print_preview(age_col, "age_col")
181
+ try_print_preview(gender_col, "gender_col")
182
+
183
+ except Exception as e:
184
+ # Ensure variables exist even if something unexpected happens
185
+ age_col = None
186
+ gender_col = None
187
+ print("Selected age_col: None")
188
+ print("Selected gender_col: None")
189
+ print(f"Note: Encountered an exception during selection: {e}")
190
+
191
+ # Step 4: Feature Engineering and Validation
192
+ import os
193
+ import pandas as pd
194
+
195
+ # Ensure clinical and genetic data are loaded
196
+ try:
197
+ clinical_df
198
+ except NameError:
199
+ clinical_df = pd.DataFrame()
200
+
201
+ try:
202
+ genetic_df
203
+ except NameError:
204
+ genetic_df = pd.DataFrame()
205
+
206
+ # Locate UVM cohort directory if needed
207
+ if clinical_df.empty or genetic_df.empty or 'cohort_dir' not in globals() or cohort_dir is None:
208
+ cohort_dirs = [
209
+ os.path.join(tcga_root_dir, d)
210
+ for d in os.listdir(tcga_root_dir)
211
+ if os.path.isdir(os.path.join(tcga_root_dir, d))
212
+ ]
213
+ uvm_dirs = [d for d in cohort_dirs if 'UVM' in os.path.basename(d).upper()]
214
+ cohort_dir = uvm_dirs[0] if uvm_dirs else None
215
+ if cohort_dir is not None:
216
+ clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
217
+ if clinical_df.empty:
218
+ clinical_df = pd.read_csv(clinical_file_path, sep='\t', header=0, index_col=0, low_memory=False)
219
+ if genetic_df.empty:
220
+ genetic_df = pd.read_csv(genetic_file_path, sep='\t', header=0, index_col=0, low_memory=False)
221
+
222
+ # Guard selected demographic columns from previous step
223
+ try:
224
+ age_col
225
+ except NameError:
226
+ age_col = None
227
+ try:
228
+ gender_col
229
+ except NameError:
230
+ gender_col = None
231
+
232
+ # 1) Extract and standardize clinical features (trait, Age, Gender)
233
+ selected_clinical_df = tcga_select_clinical_features(clinical_df, trait, age_col=age_col, gender_col=gender_col)
234
+
235
+ # Optional: save clinical subset for transparency
236
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
237
+ selected_clinical_df.to_csv(out_clinical_data_file)
238
+
239
+ # 2) Normalize gene symbols and save normalized gene matrix
240
+ gene_df_norm = normalize_gene_symbols_in_index(genetic_df.copy())
241
+ gene_df_norm = gene_df_norm.apply(pd.to_numeric, errors='coerce')
242
+
243
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
244
+ gene_df_norm.to_csv(out_gene_data_file)
245
+
246
+ # 3) Link clinical and genetic data on sample IDs
247
+ gene_df_T = gene_df_norm.T
248
+ common_ids = selected_clinical_df.index.intersection(gene_df_T.index)
249
+ linked_data = pd.concat([selected_clinical_df.loc[common_ids], gene_df_T.loc[common_ids]], axis=1)
250
+
251
+ # 4) Handle missing values systematically
252
+ linked_data = handle_missing_values(linked_data, trait)
253
+
254
+ # 5) Determine bias and remove biased demographic features
255
+ trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)
256
+
257
+ # Prepare cohort name and basic availability flags, cast to builtin types to avoid JSON issues
258
+ cohort_name = os.path.basename(cohort_dir) if (cohort_dir is not None) else "TCGA_Ocular_melanomas_(UVM)"
259
+ is_gene_available = bool(gene_df_norm.shape[0] > 0 and gene_df_norm.shape[1] > 0)
260
+ is_trait_available = bool((trait in linked_data.columns) and bool(linked_data[trait].notna().any()))
261
+ trait_biased = bool(trait_biased)
262
+
263
+ # Prepare note (ensure plain string)
264
+ note = ""
265
+ if trait in linked_data.columns:
266
+ counts = linked_data[trait].value_counts(dropna=False).to_dict()
267
+ note = f"INFO: Trait distribution after preprocessing: {counts}."
268
+ if trait_biased:
269
+ note += " WARNING: Trait appears highly imbalanced; TCGA UVM typically lacks normal samples."
270
+ note = str(note)
271
+
272
+ # 6) Final validation and save cohort info
273
+ is_usable = validate_and_save_cohort_info(
274
+ is_final=True,
275
+ cohort=cohort_name,
276
+ info_path=json_path,
277
+ is_gene_available=is_gene_available,
278
+ is_trait_available=is_trait_available,
279
+ is_biased=trait_biased,
280
+ df=linked_data,
281
+ note=note
282
+ )
283
+
284
+ # 7) Save linked data if usable
285
+ if is_usable:
286
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
287
+ linked_data.to_csv(out_data_file)
output/preprocess/Ocular_Melanomas/cohort_info.json CHANGED
@@ -1,32 +1 @@
1
- {
2
- "GSE78033": {
3
- "is_usable": false,
4
- "is_gene_available": true,
5
- "is_trait_available": true,
6
- "is_available": true,
7
- "is_biased": true,
8
- "has_age": false,
9
- "has_gender": false,
10
- "sample_size": 45
11
- },
12
- "GSE60464": {
13
- "is_usable": true,
14
- "is_gene_available": true,
15
- "is_trait_available": true,
16
- "is_available": true,
17
- "is_biased": false,
18
- "has_age": false,
19
- "has_gender": false,
20
- "sample_size": 42
21
- },
22
- "TCGA": {
23
- "is_usable": false,
24
- "is_gene_available": true,
25
- "is_trait_available": true,
26
- "is_available": true,
27
- "is_biased": true,
28
- "has_age": true,
29
- "has_gender": true,
30
- "sample_size": 80
31
- }
32
- }
 
1
+ {"GSE78033": {"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/clinical data unavailable (trait_row=None). Skipping linking; saved normalized gene data only."}, "GSE60464": {"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": 37, "note": "INFO: Trait inferred from 'location of primary melanoma'; Age/Gender unavailable in series characteristics."}, "TCGA_Ocular_melanomas_(UVM)": {"is_usable": false, "is_gene_available": true, "is_trait_available": true, "is_available": true, "is_biased": true, "has_age": true, "has_gender": true, "sample_size": 80, "note": "INFO: Trait distribution after preprocessing: {1: 80}. WARNING: Trait appears highly imbalanced; TCGA UVM typically lacks normal samples."}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Osteoarthritis/GSE141934.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Osteoarthritis/GSE55457.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Osteoarthritis/clinical_data/GSE107105.csv ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ,GSM2861345,GSM2861346,GSM2861347,GSM2861348,GSM2861349,GSM2861350,GSM2861351,GSM2861352,GSM2861353,GSM2861354,GSM2861355,GSM2861356,GSM2861357,GSM2861358,GSM2861359,GSM2861360,GSM2861361,GSM2861362,GSM2861363,GSM2861364,GSM2861365,GSM2861366,GSM2861367,GSM2861368,GSM2861369,GSM2861370,GSM2861371,GSM2861372,GSM2861373,GSM2861374,GSM2861375,GSM2861376,GSM2861377,GSM2861378,GSM2861379,GSM2861380
2
+ Osteoarthritis,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
3
+ Age,59.0,59.0,59.0,59.0,59.0,78.0,78.0,78.0,78.0,78.0,86.0,86.0,86.0,86.0,86.0,51.0,51.0,51.0,51.0,51.0,51.0,79.0,79.0,79.0,79.0,79.0,79.0,79.0,79.0,48.0,48.0,48.0,48.0,48.0,48.0,48.0
4
+ Gender,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
output/preprocess/Osteoarthritis/clinical_data/GSE141934.csv ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ,GSM4216498,GSM4216499,GSM4216500,GSM4216501,GSM4216502,GSM4216503,GSM4216504,GSM4216505,GSM4216506,GSM4216507,GSM4216508,GSM4216509,GSM4216510,GSM4216511,GSM4216512,GSM4216513,GSM4216514,GSM4216515,GSM4216516,GSM4216517,GSM4216518,GSM4216519,GSM4216520,GSM4216521,GSM4216522,GSM4216523,GSM4216524,GSM4216525,GSM4216526,GSM4216527,GSM4216528,GSM4216529,GSM4216530,GSM4216531,GSM4216532,GSM4216533,GSM4216534,GSM4216535,GSM4216536,GSM4216537,GSM4216538,GSM4216539,GSM4216540,GSM4216541,GSM4216542,GSM4216543,GSM4216544,GSM4216545,GSM4216546,GSM4216547,GSM4216548,GSM4216549,GSM4216550,GSM4216551,GSM4216552,GSM4216553,GSM4216554,GSM4216555,GSM4216556,GSM4216557,GSM4216558,GSM4216559,GSM4216560,GSM4216561,GSM4216562,GSM4216563,GSM4216564,GSM4216565,GSM4216566,GSM4216567,GSM4216568,GSM4216569,GSM4216570,GSM4216571,GSM4216572,GSM4216573,GSM4216574,GSM4216575,GSM4216576,GSM4216577,GSM4216578,GSM4216579,GSM4216580,GSM4216581,GSM4216582,GSM4216583,GSM4216584,GSM4216585,GSM4216586,GSM4216587,GSM4216588,GSM4216589,GSM4216590,GSM4216591,GSM4216592,GSM4216593,GSM4216594,GSM4216595,GSM4216596,GSM4216597
2
+ Osteoarthritis,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,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,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,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
3
+ Age,50.0,43.0,66.0,55.0,52.0,54.0,63.0,61.0,58.0,79.0,69.0,57.0,46.0,44.0,46.0,63.0,59.0,81.0,60.0,92.0,45.0,47.0,27.0,58.0,57.0,38.0,45.0,51.0,70.0,57.0,56.0,56.0,51.0,50.0,53.0,61.0,66.0,74.0,51.0,46.0,49.0,56.0,58.0,60.0,50.0,50.0,31.0,70.0,52.0,65.0,69.0,73.0,50.0,58.0,27.0,68.0,22.0,39.0,52.0,35.0,69.0,70.0,74.0,38.0,80.0,51.0,56.0,68.0,50.0,74.0,45.0,65.0,53.0,57.0,73.0,74.0,53.0,67.0,49.0,27.0,54.0,26.0,56.0,30.0,50.0,69.0,79.0,61.0,63.0,77.0,48.0,61.0,43.0,54.0,62.0,20.0,62.0,50.0,60.0,69.0
4
+ Gender,0.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,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.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,1.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,1.0,0.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,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
output/preprocess/Osteoarthritis/clinical_data/GSE56409.csv CHANGED
@@ -1,2 +1,2 @@
1
- Sample_1,Sample_2,Sample_3,Sample_4
2
- ,,,
 
1
+ ,GSM1360956,GSM1360957,GSM1360958,GSM1360959,GSM1360960,GSM1360961,GSM1360962,GSM1360963,GSM1360964,GSM1360965,GSM1360966,GSM1360967,GSM1360968,GSM1360969,GSM1360970,GSM1360971,GSM1360972,GSM1360973,GSM1360974,GSM1360975,GSM1360976,GSM1360977,GSM1360978,GSM1360979,GSM1360980,GSM1360981,GSM1360982,GSM1360983,GSM1360984,GSM1360985,GSM1360986,GSM1360987,GSM1360988,GSM1360989,GSM1360990,GSM1360991,GSM1360992,GSM1360993,GSM1360994,GSM1360995,GSM1360996,GSM1360997,GSM1360998,GSM1360999,GSM1361000,GSM1361001,GSM1361002,GSM1361003,GSM1361004,GSM1361005,GSM1361006,GSM1361007,GSM1361008,GSM1361009,GSM1361010,GSM1361011,GSM1361012,GSM1361013,GSM1361014,GSM1361015,GSM1361016,GSM1361017,GSM1361018,GSM1361019,GSM1361020,GSM1361021,GSM1361022,GSM1361023,GSM1361024,GSM1361025,GSM1361026,GSM1361027,GSM1361028,GSM1361029,GSM1361030,GSM1361031,GSM1361032,GSM1361033,GSM1361034,GSM1361035,GSM1361036,GSM1361037,GSM1361038,GSM1361039,GSM1361040,GSM1361041,GSM1361042,GSM1361043,GSM1361044,GSM1361045,GSM1361046,GSM1361047,GSM1361048,GSM1361049,GSM1361050,GSM1361051,GSM1361052,GSM1361053,GSM1361054,GSM1361055,GSM1361056,GSM1361057
2
+ Osteoarthritis,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,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,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,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,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,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
output/preprocess/Osteoarthritis/clinical_data/GSE93698.csv CHANGED
@@ -1,4 +1,4 @@
1
- ,GSM2460692,GSM2460693,GSM2460694,GSM2460695,GSM2460696,GSM2460733,GSM2460734,GSM2460735,GSM2460736,GSM2460737,GSM2460738,GSM2460739,GSM2460740,GSM2460741,GSM2460742,GSM2460743,GSM2460744,GSM2460745,GSM2460746,GSM2460747,GSM2460748,GSM2460749,GSM2460750,GSM2460751,GSM2460752,GSM2460753,GSM2460754,GSM2460755,GSM2460756,GSM2460757
2
- Osteoarthritis,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,0.0,0.0,0.0,0.0,0.0,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
- Age,,,,,,71.0,73.0,65.0,51.0,56.0,52.0,42.0,43.0,69.0,55.0,62.0,37.0,38.0,19.0,40.0,31.0,45.0,55.0,72.0,42.0,72.0,28.0,39.0,47.0,21.0
4
- Gender,,,,,,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.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,0.0,0.0,0.0,1.0,1.0
 
1
+ GSM2460692,GSM2460693,GSM2460694,GSM2460695,GSM2460696,GSM2460733,GSM2460734,GSM2460735,GSM2460736,GSM2460737,GSM2460738,GSM2460739,GSM2460740,GSM2460741,GSM2460742,GSM2460743,GSM2460744,GSM2460745,GSM2460746,GSM2460747,GSM2460748,GSM2460749,GSM2460750,GSM2460751,GSM2460752,GSM2460753,GSM2460754,GSM2460755,GSM2460756,GSM2460757
2
+ 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,0.0,0.0,0.0,0.0,0.0,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
+ ,,,,,71.0,73.0,65.0,51.0,56.0,52.0,42.0,43.0,69.0,55.0,62.0,37.0,38.0,19.0,40.0,31.0,45.0,55.0,72.0,42.0,72.0,28.0,39.0,47.0,21.0
4
+ ,,,,,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.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,0.0,0.0,0.0,1.0,1.0
output/preprocess/Osteoarthritis/clinical_data/GSE93720.csv CHANGED
@@ -1,2 +1,2 @@
1
- GSM3713911,GSM3713912,GSM3713913,GSM3713914,GSM3713915,GSM3713916,GSM3713917,GSM3713918,GSM3713919,GSM3713920,GSM3713921,GSM3713922,GSM3713923,GSM3713924,GSM3713925,GSM3713926,GSM3713927,GSM3713928,GSM3713929,GSM3713930,GSM3713931,GSM3713932,GSM3713933,GSM3713934,GSM3713935,GSM3713936,GSM3713937,GSM3713938,GSM3713939,GSM3713940,GSM3713941,GSM3713942,GSM3713943,GSM3713944,GSM3713945,GSM3713946,GSM3713947,GSM3713948,GSM3713949,GSM3713950,GSM3713951,GSM3713952,GSM3713953,GSM3713954,GSM3713955,GSM3713956,GSM3713957,GSM3713958
2
- 1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,0.0,1.0,0.0,1.0
 
1
+ ,GSM3713911,GSM3713912,GSM3713913,GSM3713914,GSM3713915,GSM3713916,GSM3713917,GSM3713918,GSM3713919,GSM3713920,GSM3713921,GSM3713922,GSM3713923,GSM3713924,GSM3713925,GSM3713926,GSM3713927,GSM3713928,GSM3713929,GSM3713930,GSM3713931,GSM3713932,GSM3713933,GSM3713934,GSM3713935,GSM3713936,GSM3713937,GSM3713938,GSM3713939,GSM3713940,GSM3713941,GSM3713942,GSM3713943,GSM3713944,GSM3713945,GSM3713946,GSM3713947,GSM3713948,GSM3713949,GSM3713950,GSM3713951,GSM3713952,GSM3713953,GSM3713954,GSM3713955,GSM3713956,GSM3713957,GSM3713958
2
+ Osteoarthritis,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,0.0,1.0,0.0,1.0
output/preprocess/Osteoarthritis/code/GSE107105.py ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Osteoarthritis"
6
+ cohort = "GSE107105"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Osteoarthritis"
10
+ in_cohort_dir = "../DATA/GEO/Osteoarthritis/GSE107105"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z5/preprocess/Osteoarthritis/GSE107105.csv"
14
+ out_gene_data_file = "./output/z5/preprocess/Osteoarthritis/gene_data/GSE107105.csv"
15
+ out_clinical_data_file = "./output/z5/preprocess/Osteoarthritis/clinical_data/GSE107105.csv"
16
+ json_path = "./output/z5/preprocess/Osteoarthritis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+
42
+ # 1) Gene expression data availability
43
+ is_gene_available = True # Microarray-based transcriptomics of synovial fibroblasts (not miRNA-only or methylation)
44
+
45
+ # 2) Variable availability and conversion functions
46
+ # Sample Characteristics Dictionary review indicates:
47
+ # - trait (Osteoarthritis vs RA): key 0
48
+ # - age: key 1
49
+ # - gender: key 2
50
+
51
+ trait_row = 0
52
+ age_row = 1
53
+ gender_row = 2
54
+
55
+ def _after_colon(s):
56
+ if s is None:
57
+ return None
58
+ parts = str(s).split(":", 1)
59
+ return parts[1].strip() if len(parts) > 1 else str(s).strip()
60
+
61
+ def convert_trait(x):
62
+ v = _after_colon(x)
63
+ if v is None:
64
+ return None
65
+ vl = v.lower()
66
+ # Map OA (trait present) -> 1, RA (other disease) -> 0
67
+ if "oa" in vl or "osteo" in vl:
68
+ return 1
69
+ if "ra" in vl or "rheum" in vl:
70
+ return 0
71
+ return None
72
+
73
+ def convert_age(x):
74
+ v = _after_colon(x)
75
+ if v is None:
76
+ return None
77
+ v = v.strip()
78
+ # Extract numeric part (allow decimals)
79
+ m = re.search(r'[-+]?\d+(\.\d+)?', v)
80
+ if not m:
81
+ return None
82
+ try:
83
+ return float(m.group(0))
84
+ except Exception:
85
+ return None
86
+
87
+ def convert_gender(x):
88
+ v = _after_colon(x)
89
+ if v is None:
90
+ return None
91
+ vl = v.strip().lower()
92
+ if vl in {"female", "f"}:
93
+ return 0
94
+ if vl in {"male", "m"}:
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 trait_row is not None)
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,
117
+ gender_row=gender_row,
118
+ convert_gender=convert_gender
119
+ )
120
+ preview = preview_df(selected_clinical_df)
121
+ print(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
+ 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
+ # Inspect available annotation columns
147
+ anno_cols = list(gene_annotation.columns)
148
+ print("Annotation columns (first 50):", anno_cols[:50])
149
+
150
+ probe_id_col = 'ID'
151
+ assert probe_id_col in gene_annotation.columns, "Probe ID column 'ID' not found in gene annotation."
152
+
153
+ # Exclude obvious non-gene-symbol columns to avoid spurious tokens (e.g., 'NC' from RANGE_GB)
154
+ excluded_cols = {
155
+ probe_id_col,
156
+ 'RANGE_GB', 'SPOT_ID', 'RANGE_STRAND', 'RANGE_START', 'RANGE_END', 'total_probes',
157
+ 'GB_ACC' # RefSeq accessions; handled separately in fallback
158
+ }
159
+ candidate_cols = [c for c in gene_annotation.columns if c not in excluded_cols]
160
+
161
+ best_col = None
162
+ best_rows_with_symbols = -1
163
+ best_total_symbols = -1
164
+
165
+ # Heuristic scan of candidate columns for plausible human gene symbols
166
+ for col in candidate_cols:
167
+ series = gene_annotation[col].astype(str)
168
+ subset = series.head(50000)
169
+ extracted = subset.map(extract_human_gene_symbols)
170
+ rows_with_symbols = extracted.map(lambda x: len(x) > 0).sum()
171
+ total_symbols = extracted.map(len).sum()
172
+ if (rows_with_symbols > best_rows_with_symbols) or (
173
+ rows_with_symbols == best_rows_with_symbols and total_symbols > best_total_symbols
174
+ ):
175
+ best_rows_with_symbols = rows_with_symbols
176
+ best_total_symbols = total_symbols
177
+ best_col = col
178
+
179
+ # Fallback to a few common names if nothing suitable was detected
180
+ if best_rows_with_symbols <= 0 or best_col is None:
181
+ for fallback in ['gene_assignment', 'Gene Symbol', 'GENE_SYMBOL', 'GeneSymbol', 'Symbol', 'SYMBOL', 'Gene', 'GENE', 'Entrez Gene Symbol']:
182
+ if fallback in gene_annotation.columns and fallback not in excluded_cols:
183
+ best_col = fallback
184
+ best_rows_with_symbols = 1 # mark as found
185
+ break
186
+
187
+ probe_level_df = gene_data.copy()
188
+
189
+ if best_rows_with_symbols > 0 and best_col is not None:
190
+ # Symbol-bearing column found: proceed with standard mapping
191
+ print(f"Selected gene symbol column: {best_col}")
192
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_id_col, gene_col=best_col)
193
+ gene_data = apply_gene_mapping(probe_level_df, mapping_df)
194
+ # Normalize gene symbols and aggregate duplicates
195
+ gene_data = normalize_gene_symbols_in_index(gene_data)
196
+ else:
197
+ # Robust fallback: use RefSeq accessions (GB_ACC) as gene identifiers
198
+ if 'GB_ACC' not in gene_annotation.columns or gene_annotation['GB_ACC'].notna().sum() == 0:
199
+ # Last-resort fallback: keep probe-level if no mapping information at all
200
+ print("WARNING: No gene symbol column and no GB_ACC found in annotation. Proceeding with probe-level data.")
201
+ gene_data = probe_level_df
202
+ else:
203
+ print("Falling back to RefSeq GB_ACC mapping as gene identifiers.")
204
+ # Build mapping from probe ID to RefSeq accession(s)
205
+ mapping_df = gene_annotation.loc[:, [probe_id_col, 'GB_ACC']].dropna().rename(
206
+ columns={probe_id_col: 'ID', 'GB_ACC': 'Gene'}
207
+ )
208
+ mapping_df['ID'] = mapping_df['ID'].astype(str).str.strip()
209
+ mapping_df = mapping_df[mapping_df['ID'].isin(probe_level_df.index)].copy()
210
+
211
+ # Split potential multi-mapped accessions and distribute expression equally
212
+ split_regex = re.compile(r'[;,/| ]+')
213
+
214
+ def split_accessions(val):
215
+ if pd.isna(val):
216
+ return []
217
+ tokens = [t for t in split_regex.split(str(val)) if t]
218
+ # keep RefSeq-like accessions: NM_, NR_, XM_, XR_
219
+ tokens = [t for t in tokens if re.match(r'^[NX][MR]_\d+(\.\d+)?$', t)]
220
+ return tokens
221
+
222
+ mapping_df['GeneList'] = mapping_df['Gene'].apply(split_accessions)
223
+ mapping_df['num_genes'] = mapping_df['GeneList'].apply(len)
224
+ # If no valid accession extracted, drop
225
+ mapping_df = mapping_df[mapping_df['num_genes'] > 0].copy()
226
+ if len(mapping_df) == 0:
227
+ print("WARNING: GB_ACC mapping did not yield valid RefSeq accessions. Proceeding with probe-level data.")
228
+ gene_data = probe_level_df
229
+ else:
230
+ mapping_df = mapping_df.explode('GeneList').rename(columns={'GeneList': 'Gene'})
231
+ mapping_df = mapping_df.set_index('ID')
232
+ merged = mapping_df.join(probe_level_df)
233
+ expr_cols = [c for c in merged.columns if c not in ['Gene', 'num_genes']]
234
+ merged[expr_cols] = merged[expr_cols].div(merged['num_genes'], axis=0)
235
+ gene_data = merged.groupby('Gene')[expr_cols].sum()
236
+
237
+ # Light validation with warnings (no hard failure)
238
+ n_genes = gene_data.shape[0]
239
+ if n_genes is None or n_genes <= 100:
240
+ print(f"WARNING: Mapping produced a small number of gene identifiers (n={n_genes}). "
241
+ f"Downstream power may be limited.")
242
+ else:
243
+ print(f"Gene-level dataset ready with {n_genes} features.")
244
+
245
+ # Step 7: Gene Identifier Mapping
246
+ # Robust gene identifier mapping for GSE107105
247
+
248
+ # Keep a copy of probe-level expression
249
+ probe_level_df = gene_data.copy()
250
+
251
+ # Decide identifier and symbol columns from annotation
252
+ probe_id_col = 'ID'
253
+ assert probe_id_col in gene_annotation.columns, "Probe ID column 'ID' not found in gene annotation."
254
+
255
+ # Try to detect a symbol-bearing column
256
+ excluded_cols = {
257
+ probe_id_col, 'RANGE_GB', 'SPOT_ID', 'RANGE_STRAND', 'RANGE_START', 'RANGE_END', 'total_probes', 'GB_ACC'
258
+ }
259
+ candidate_cols = [c for c in gene_annotation.columns if c not in excluded_cols]
260
+
261
+ best_col = None
262
+ best_rows_with_symbols = -1
263
+ best_total_symbols = -1
264
+ for col in candidate_cols:
265
+ col_series = gene_annotation[col].astype(str)
266
+ # Use a reasonable subset
267
+ subset = col_series.head(50000)
268
+ extracted = subset.map(extract_human_gene_symbols)
269
+ rows_with_symbols = extracted.map(lambda x: len(x) > 0).sum()
270
+ total_symbols = extracted.map(len).sum()
271
+ if (rows_with_symbols > best_rows_with_symbols) or (
272
+ rows_with_symbols == best_rows_with_symbols and total_symbols > best_total_symbols
273
+ ):
274
+ best_rows_with_symbols = rows_with_symbols
275
+ best_total_symbols = total_symbols
276
+ best_col = col
277
+
278
+ # Fallback names if heuristic finds nothing
279
+ if best_rows_with_symbols <= 0 or best_col is None:
280
+ for fallback in ['gene_assignment', 'Gene Symbol', 'GENE_SYMBOL', 'GeneSymbol', 'Symbol', 'SYMBOL', 'Gene', 'GENE', 'Entrez Gene Symbol']:
281
+ if fallback in gene_annotation.columns and fallback not in excluded_cols:
282
+ best_col = fallback
283
+ best_rows_with_symbols = 1
284
+ break
285
+
286
+ # If a plausible gene symbol column exists, use standard mapping to symbols
287
+ if best_rows_with_symbols > 0 and best_col is not None:
288
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_id_col, gene_col=best_col)
289
+ gene_data = apply_gene_mapping(probe_level_df, mapping_df)
290
+ gene_data = normalize_gene_symbols_in_index(gene_data)
291
+ else:
292
+ # Fallback: map probes to RefSeq accessions using GB_ACC
293
+ if 'GB_ACC' not in gene_annotation.columns:
294
+ # As last resort, keep probe-level data
295
+ gene_data = probe_level_df
296
+ else:
297
+ ann_sub = gene_annotation.loc[:, [probe_id_col, 'GB_ACC']].dropna().copy()
298
+ # Align to probes present in expression
299
+ ann_sub[probe_id_col] = ann_sub[probe_id_col].astype(str).str.strip()
300
+ ann_sub = ann_sub[ann_sub[probe_id_col].isin(probe_level_df.index)].copy()
301
+
302
+ # Split GB_ACC cells into individual accessions and clean up
303
+ split_regex = re.compile(r'[;,/| ]+')
304
+
305
+ def split_accessions(val):
306
+ if pd.isna(val):
307
+ return []
308
+ toks = [t for t in split_regex.split(str(val)) if t]
309
+ # Keep RefSeq-like accessions
310
+ toks = [t for t in toks if re.match(r'^[NX][MR]_\d+(\.\d+)?$', t)]
311
+ return toks
312
+
313
+ ann_sub['AccessionList'] = ann_sub['GB_ACC'].apply(split_accessions)
314
+ # Remove rows with no valid accessions
315
+ ann_sub = ann_sub[ann_sub['AccessionList'].map(len) > 0]
316
+ if len(ann_sub) == 0:
317
+ # No usable mapping; keep probe-level
318
+ gene_data = probe_level_df
319
+ else:
320
+ ann_sub = ann_sub.drop(columns=['GB_ACC']).explode('AccessionList').rename(columns={'AccessionList': 'Accession'})
321
+ # Compute number of targets per probe for equal splitting
322
+ ann_sub['num_targets'] = ann_sub.groupby(probe_id_col)['Accession'].transform('count')
323
+
324
+ # Join with expression and distribute weights
325
+ ann_sub = ann_sub.set_index(probe_id_col)
326
+ merged = ann_sub.join(probe_level_df, how='inner')
327
+ expr_cols = [c for c in merged.columns if c not in ['Accession', 'num_targets']]
328
+
329
+ # Avoid division by zero
330
+ merged['num_targets'] = merged['num_targets'].replace(0, 1)
331
+ merged[expr_cols] = merged[expr_cols].div(merged['num_targets'], axis=0)
332
+
333
+ # Aggregate to accession-level expression
334
+ gene_data = merged.groupby('Accession', as_index=True)[expr_cols].sum()
335
+
336
+ # Optional sanity message
337
+ print(f"Gene-level dataframe shape: {gene_data.shape}")
338
+
339
+ # Step 8: Data Normalization and Linking
340
+ import os
341
+ import re
342
+
343
+ # 1. Normalize gene symbols when appropriate; otherwise keep accession-level features
344
+ refseq_pattern = re.compile(r'^[NX][MR]_\d+(\.\d+)?$')
345
+ idx = gene_data.index.astype(str)
346
+ if len(idx) > 0:
347
+ refseq_ratio = sum(bool(refseq_pattern.match(x)) for x in idx) / len(idx)
348
+ else:
349
+ refseq_ratio = 0.0
350
+
351
+ note_msg = "INFO: Gene symbol normalization applied."
352
+ if refseq_ratio >= 0.8:
353
+ # Index appears to be mostly RefSeq accessions; skip normalization
354
+ normalized_gene_data = gene_data.copy()
355
+ note_msg = "WARNING: No reliable gene symbol annotation. Using RefSeq accession-level features; normalization skipped."
356
+ else:
357
+ # Attempt normalization; if too many rows dropped, fall back
358
+ normalized_attempt = normalize_gene_symbols_in_index(gene_data.copy())
359
+ keep_ratio = (normalized_attempt.shape[0] / gene_data.shape[0]) if gene_data.shape[0] > 0 else 0.0
360
+ if (normalized_attempt.shape[0] == 0) or (keep_ratio < 0.1):
361
+ normalized_gene_data = gene_data.copy()
362
+ note_msg = f"WARNING: Gene symbol normalization dropped too many rows (kept {keep_ratio:.1%}). Falling back to original identifiers."
363
+ else:
364
+ normalized_gene_data = normalized_attempt
365
+ note_msg = f"INFO: Gene symbol normalization applied (kept {keep_ratio:.1%} of rows)."
366
+
367
+ # Ensure output directory exists and save normalized gene (or accession-level) data
368
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
369
+ normalized_gene_data.to_csv(out_gene_data_file)
370
+
371
+ # 2. Link the clinical and genetic data
372
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
373
+
374
+ # 3. Handle missing values
375
+ linked_data = handle_missing_values(linked_data, trait)
376
+
377
+ # 4. Detect bias and remove biased demographic features
378
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
379
+
380
+ # 5. Final validation and save cohort info
381
+ is_gene_available = (normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0)
382
+ is_trait_available = True # trait row was extracted earlier
383
+ is_usable = validate_and_save_cohort_info(
384
+ is_final=True,
385
+ cohort=cohort,
386
+ info_path=json_path,
387
+ is_gene_available=is_gene_available,
388
+ is_trait_available=is_trait_available,
389
+ is_biased=is_trait_biased,
390
+ df=unbiased_linked_data,
391
+ note=note_msg
392
+ )
393
+
394
+ # 6. Save linked data only if usable
395
+ if is_usable:
396
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
397
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Osteoarthritis/code/GSE141934.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Osteoarthritis"
6
+ cohort = "GSE141934"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Osteoarthritis"
10
+ in_cohort_dir = "../DATA/GEO/Osteoarthritis/GSE141934"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z5/preprocess/Osteoarthritis/GSE141934.csv"
14
+ out_gene_data_file = "./output/z5/preprocess/Osteoarthritis/gene_data/GSE141934.csv"
15
+ out_clinical_data_file = "./output/z5/preprocess/Osteoarthritis/clinical_data/GSE141934.csv"
16
+ json_path = "./output/z5/preprocess/Osteoarthritis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import pandas as pd
41
+
42
+ # 1) Gene expression availability
43
+ is_gene_available = True # Transcriptional data from CD4+ T cells is described in the series
44
+
45
+ # 2) Identify variable rows from the Sample Characteristics Dictionary
46
+ trait_row = 6 # 'working_diagnosis' contains 'Osteoarthritis'
47
+ age_row = 2 # 'age: <number>'
48
+ gender_row = 1 # 'gender: F/M'
49
+
50
+ # 2.2) Conversion functions
51
+ def _extract_value(x):
52
+ if x is None:
53
+ return None
54
+ try:
55
+ parts = str(x).split(":")
56
+ return parts[-1].strip()
57
+ except Exception:
58
+ return None
59
+
60
+ def convert_trait(x):
61
+ v = _extract_value(x)
62
+ if v is None or v == "" or v.lower() == "unknown":
63
+ return None
64
+ return 1 if v.lower() == "osteoarthritis" else 0
65
+
66
+ def convert_age(x):
67
+ v = _extract_value(x)
68
+ if v is None or v == "" or v.lower() in {"na", "n/a", "unknown"}:
69
+ return None
70
+ try:
71
+ return float(v)
72
+ except Exception:
73
+ # Try to extract digits if mixed content
74
+ import re
75
+ m = re.search(r"[-+]?\d*\.?\d+", v)
76
+ if m:
77
+ try:
78
+ return float(m.group())
79
+ except Exception:
80
+ return None
81
+ return None
82
+
83
+ def convert_gender(x):
84
+ v = _extract_value(x)
85
+ if v is None or v == "":
86
+ return None
87
+ vl = v.lower()
88
+ if vl in {"female", "f"}:
89
+ return 0
90
+ if vl in {"male", "m"}:
91
+ return 1
92
+ return None
93
+
94
+ # 3) Save metadata (initial filtering)
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, preview, and save
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,
113
+ gender_row=gender_row,
114
+ convert_gender=convert_gender
115
+ )
116
+ preview = preview_df(selected_clinical_df, n=5)
117
+ print(preview)
118
+
119
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
120
+ selected_clinical_df.to_csv(out_clinical_data_file)
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
+ # Illumina probe IDs (e.g., "ILMN_1343291") are not human gene symbols and require mapping.
131
+ requires_gene_mapping = True
132
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
133
+
134
+ # Step 5: Gene Annotation
135
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
136
+ gene_annotation = get_gene_annotation(soft_file)
137
+
138
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
139
+ print("Gene annotation preview:")
140
+ print(preview_df(gene_annotation))
141
+
142
+ # Step 6: Gene Identifier Mapping
143
+ # Identify the columns for probe IDs and gene symbols in the annotation dataframe
144
+ probe_col = 'ID' # Matches probe identifiers like 'ILMN_1343291'
145
+ gene_symbol_col = 'Symbol' # Contains gene symbols
146
+
147
+ # Build the mapping dataframe
148
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
149
+
150
+ # Apply mapping to convert probe-level data to gene-level expression
151
+ probe_data = gene_data # preserve the probe-level data obtained previously
152
+ gene_data = apply_gene_mapping(expression_df=probe_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 matrix
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 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) Assess bias and remove biased demographic features
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_flag = normalized_gene_data.shape[0] > 0
173
+ is_trait_available_flag = (trait in linked_data.columns)
174
+ note = ("INFO: Illumina probe IDs mapped to gene symbols via platform annotation; "
175
+ "CD4+ T cells from peripheral blood; trait derived from 'working_diagnosis' "
176
+ "as binary Osteoarthritis vs. non-Osteoarthritis.")
177
+ is_usable = validate_and_save_cohort_info(
178
+ is_final=True,
179
+ cohort=cohort,
180
+ info_path=json_path,
181
+ is_gene_available=is_gene_available_flag,
182
+ is_trait_available=is_trait_available_flag,
183
+ is_biased=is_trait_biased,
184
+ df=unbiased_linked_data,
185
+ note=note
186
+ )
187
+
188
+ # 6) Save linked data if usable
189
+ if is_usable:
190
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
191
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Osteoarthritis/code/GSE142049.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Osteoarthritis"
6
+ cohort = "GSE142049"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Osteoarthritis"
10
+ in_cohort_dir = "../DATA/GEO/Osteoarthritis/GSE142049"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z5/preprocess/Osteoarthritis/GSE142049.csv"
14
+ out_gene_data_file = "./output/z5/preprocess/Osteoarthritis/gene_data/GSE142049.csv"
15
+ out_clinical_data_file = "./output/z5/preprocess/Osteoarthritis/clinical_data/GSE142049.csv"
16
+ json_path = "./output/z5/preprocess/Osteoarthritis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+ import pandas as pd
42
+
43
+ # 1) Gene expression availability
44
+ is_gene_available = True # Title and summary indicate transcriptional (gene expression) data in B cells.
45
+
46
+ # 2) Variable availability and converters
47
+ # Keys from Sample Characteristics Dictionary:
48
+ # 1: gender
49
+ # 2: age
50
+ # 6: working_diagnosis (contains 'Osteoarthritis' among categories)
51
+ trait_row = 6
52
+ age_row = 2
53
+ gender_row = 1
54
+
55
+ def _after_colon(x):
56
+ if x is None:
57
+ return None
58
+ if isinstance(x, float) and pd.isna(x):
59
+ return None
60
+ s = str(x)
61
+ parts = s.split(":", 1)
62
+ val = parts[1] if len(parts) > 1 else parts[0]
63
+ val = val.strip()
64
+ if val == "" or val.lower() in {"na", "n/a", "nan", "none", "null", "unknown"}:
65
+ return None
66
+ return val
67
+
68
+ def convert_trait(x):
69
+ # Map working diagnosis to Osteoarthritis=1, others=0
70
+ val = _after_colon(x)
71
+ if val is None:
72
+ return None
73
+ v = val.lower()
74
+ # Heuristic: any label containing 'osteo' is Osteoarthritis
75
+ if "osteo" in v:
76
+ return 1
77
+ # For other defined diagnoses, treat as not Osteoarthritis
78
+ return 0
79
+
80
+ def convert_age(x):
81
+ val = _after_colon(x)
82
+ if val is None:
83
+ return None
84
+ m = re.search(r"-?\d+\.?\d*", val)
85
+ if not m:
86
+ return None
87
+ try:
88
+ num = float(m.group(0))
89
+ return num
90
+ except Exception:
91
+ return None
92
+
93
+ def convert_gender(x):
94
+ val = _after_colon(x)
95
+ if val is None:
96
+ return None
97
+ v = val.strip().lower()
98
+ if v in {"f", "female", "woman", "women"}:
99
+ return 0
100
+ if v in {"m", "male", "man", "men"}:
101
+ return 1
102
+ return None
103
+
104
+ # 3) Save metadata (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=age_row,
122
+ convert_age=convert_age,
123
+ gender_row=gender_row,
124
+ convert_gender=convert_gender
125
+ )
126
+ preview = preview_df(selected_clinical_df, n=5)
127
+ print(preview)
128
+
129
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
130
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
131
+
132
+ # Step 3: Gene Data Extraction
133
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
134
+ gene_data = get_genetic_data(matrix_file)
135
+
136
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
137
+ print(gene_data.index[:20])
138
+
139
+ # Step 4: Gene Identifier Review
140
+ # ILMN_* identifiers are Illumina probe IDs, not human gene symbols.
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
+ # Determine mapping columns based on the annotation preview: 'ID' (probe IDs) and 'Symbol' (gene symbols)
154
+ probe_col = 'ID'
155
+ gene_symbol_col = 'Symbol'
156
+
157
+ # Build mapping dataframe
158
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
159
+
160
+ # Apply mapping: convert probe-level data to gene-level expression
161
+ probe_data = gene_data # keep a reference to the existing probe-level data from previous steps
162
+ gene_data = apply_gene_mapping(probe_data, mapping_df)
163
+
164
+ # Step 7: Data Normalization and Linking
165
+ import os
166
+
167
+ # 1. Normalize gene symbols and save
168
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
169
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
170
+ normalized_gene_data.to_csv(out_gene_data_file)
171
+
172
+ # 2. Link clinical and genetic data
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 removal of biased demographics
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
+ # Ensure native Python types to avoid JSON serialization issues
183
+ is_gene_available_final = bool(normalized_gene_data.shape[0] > 0)
184
+ is_trait_available_final = bool((trait in unbiased_linked_data.columns) and bool(unbiased_linked_data[trait].notna().any()))
185
+ is_trait_biased_py = bool(is_trait_biased)
186
+ note = str("INFO: Probe IDs (ILMN) mapped via SOFT 'ID'->'Symbol'; symbols normalized using NCBI synonyms.")
187
+
188
+ try:
189
+ is_usable = validate_and_save_cohort_info(
190
+ is_final=True,
191
+ cohort=cohort,
192
+ info_path=json_path,
193
+ is_gene_available=is_gene_available_final,
194
+ is_trait_available=is_trait_available_final,
195
+ is_biased=is_trait_biased_py,
196
+ df=unbiased_linked_data,
197
+ note=note
198
+ )
199
+ except TypeError:
200
+ # Fallback: if existing JSON has non-serializable content from prior runs, back it up and retry fresh
201
+ try:
202
+ if os.path.exists(json_path):
203
+ os.replace(json_path, json_path + ".bak")
204
+ except Exception:
205
+ pass
206
+ is_usable = validate_and_save_cohort_info(
207
+ is_final=True,
208
+ cohort=cohort,
209
+ info_path=json_path,
210
+ is_gene_available=is_gene_available_final,
211
+ is_trait_available=is_trait_available_final,
212
+ is_biased=is_trait_biased_py,
213
+ df=unbiased_linked_data,
214
+ note=note
215
+ )
216
+
217
+ # 6. Save linked dataset if usable
218
+ if is_usable:
219
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
220
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Osteoarthritis/code/GSE236924.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Osteoarthritis"
6
+ cohort = "GSE236924"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Osteoarthritis"
10
+ in_cohort_dir = "../DATA/GEO/Osteoarthritis/GSE236924"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z5/preprocess/Osteoarthritis/GSE236924.csv"
14
+ out_gene_data_file = "./output/z5/preprocess/Osteoarthritis/gene_data/GSE236924.csv"
15
+ out_clinical_data_file = "./output/z5/preprocess/Osteoarthritis/clinical_data/GSE236924.csv"
16
+ json_path = "./output/z5/preprocess/Osteoarthritis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import pandas as pd
41
+
42
+ # 1) Gene expression data availability
43
+ is_gene_available = True # Array-based study comparing tissues; likely gene expression microarray (not miRNA-only or methylation-only)
44
+
45
+ # 2) Variable availability and converters
46
+ # From the provided Sample Characteristics Dictionary, only disease status is available at key 0
47
+ trait_row = 0
48
+ age_row = None
49
+ gender_row = None
50
+
51
+ def _extract_value(x):
52
+ if x is None or (isinstance(x, float) and pd.isna(x)):
53
+ return None
54
+ s = str(x).strip()
55
+ if ':' in s:
56
+ s = s.split(':', 1)[1]
57
+ return s.strip()
58
+
59
+ def convert_trait(x):
60
+ val = _extract_value(x)
61
+ if val is None:
62
+ return None
63
+ v = val.lower()
64
+ # Map osteoarthritis as 1; other diseases or controls as 0
65
+ if v in {'oa', 'osteoarthritis'}:
66
+ return 1
67
+ if v in {'ra', 'rheumatoid arthritis', 'control', 'healthy', 'normal', 'non-disease', 'non disease', 'nd'}:
68
+ return 0
69
+ # Heuristic: if 'osteo' in string, treat as OA; if 'rheumat' present or 'control' present, treat as 0
70
+ if 'osteo' in v:
71
+ return 1
72
+ if 'rheumat' in v or 'control' in v:
73
+ return 0
74
+ return None
75
+
76
+ def convert_age(x):
77
+ # Not available; provided for completeness if needed in future
78
+ val = _extract_value(x)
79
+ if val is None:
80
+ return None
81
+ # Try to extract number from strings like "age: 56", "56 years"
82
+ import re
83
+ m = re.search(r'(\d+\.?\d*)', val)
84
+ if m:
85
+ try:
86
+ return float(m.group(1))
87
+ except:
88
+ return None
89
+ return None
90
+
91
+ def convert_gender(x):
92
+ # Not available; provided for completeness if needed in future
93
+ val = _extract_value(x)
94
+ if val is None:
95
+ return None
96
+ v = val.strip().lower()
97
+ if v in {'male', 'm'}:
98
+ return 1
99
+ if v in {'female', 'f'}:
100
+ return 0
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 (only if trait is available)
114
+ if is_trait_available:
115
+ selected_clinical_df = geo_select_clinical_features(
116
+ clinical_df=clinical_data,
117
+ trait=trait,
118
+ trait_row=trait_row,
119
+ convert_trait=convert_trait,
120
+ age_row=age_row,
121
+ convert_age=convert_age,
122
+ gender_row=gender_row,
123
+ convert_gender=convert_gender
124
+ )
125
+
126
+ # Preview and save
127
+ clinical_preview = preview_df(selected_clinical_df)
128
+ print("Clinical data preview:", clinical_preview)
129
+
130
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
131
+ selected_clinical_df.to_csv(out_clinical_data_file)
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
+ print("requires_gene_mapping = True")
142
+
143
+ # Step 5: Gene Annotation
144
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
145
+ gene_annotation = get_gene_annotation(soft_file)
146
+
147
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
148
+ print("Gene annotation preview:")
149
+ print(preview_df(gene_annotation))
150
+
151
+ # Step 6: Gene Identifier Mapping
152
+ # Map probe IDs to gene symbols using annotation columns identified from preview:
153
+ # - Probe ID column: 'ID' (matches gene_data index like '1007_s_at')
154
+ # - Gene symbol column: 'Gene Symbol'
155
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')
156
+
157
+ # Convert probe-level expression to gene-level expression
158
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
159
+
160
+ # Step 7: Data Normalization and Linking
161
+ import os
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
+ # 2. Link clinical and genetic data (fix variable name)
169
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
170
+
171
+ # 3. Handle missing values
172
+ linked_data = handle_missing_values(linked_data, trait)
173
+
174
+ # 4. Bias assessment and removal of biased demographics
175
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
176
+
177
+ # 5. Final validation and save cohort info
178
+ note = ("INFO: Trait available; Age/Gender not provided in clinical annotations; "
179
+ "Affymetrix probes mapped to gene symbols via platform annotation; gene symbols normalized via synonyms.")
180
+ is_usable = validate_and_save_cohort_info(
181
+ is_final=True,
182
+ cohort=cohort,
183
+ info_path=json_path,
184
+ is_gene_available=True,
185
+ is_trait_available=True,
186
+ is_biased=is_trait_biased,
187
+ df=unbiased_linked_data,
188
+ note=note
189
+ )
190
+
191
+ # 6. Save linked data if usable
192
+ if is_usable:
193
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
194
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Osteoarthritis/code/GSE55457.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Osteoarthritis"
6
+ cohort = "GSE55457"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Osteoarthritis"
10
+ in_cohort_dir = "../DATA/GEO/Osteoarthritis/GSE55457"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z5/preprocess/Osteoarthritis/GSE55457.csv"
14
+ out_gene_data_file = "./output/z5/preprocess/Osteoarthritis/gene_data/GSE55457.csv"
15
+ out_clinical_data_file = "./output/z5/preprocess/Osteoarthritis/clinical_data/GSE55457.csv"
16
+ json_path = "./output/z5/preprocess/Osteoarthritis/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 HG-U133 A/B transcriptomic (gene expression) data
44
+
45
+ # 2. Variable Availability and Data Type Conversion
46
+ # Identified keys from the Sample Characteristics Dictionary
47
+ trait_row = 2 # 'clinical status: rheumatoid arthritis' | 'normal control' | 'osteoarthritis'
48
+ age_row = 1 # 'age: <number>'
49
+ gender_row = 0 # 'gender: female' | 'gender: male'
50
+
51
+ def _after_colon(value):
52
+ if value is None:
53
+ return None
54
+ s = str(value)
55
+ if ':' in s:
56
+ s = s.split(':', 1)[1]
57
+ return s.strip()
58
+
59
+ def convert_trait(value):
60
+ """
61
+ Map OA status to binary: OA -> 1; RA/Controls/others -> 0; unknown -> None
62
+ """
63
+ s = _after_colon(value)
64
+ if not s:
65
+ return None
66
+ s = s.lower().strip()
67
+ # Positive (case)
68
+ if s in {'osteoarthritis', 'oa'}:
69
+ return 1
70
+ # Negative (non-case): controls and other diseases
71
+ if s in {'normal control', 'control', 'healthy control', 'healthy', 'cg', 'control group',
72
+ 'rheumatoid arthritis', 'ra'}:
73
+ return 0
74
+ # Heuristic mappings
75
+ if 'osteo' in s:
76
+ return 1
77
+ if 'rheumatoid' in s or 'ra' == s:
78
+ return 0
79
+ if 'control' in s or 'healthy' in s or 'normal' in s:
80
+ return 0
81
+ return None
82
+
83
+ def convert_age(value):
84
+ """
85
+ Extract numeric age; return as float; unknown -> None
86
+ """
87
+ s = _after_colon(value)
88
+ if not s:
89
+ return None
90
+ m = re.search(r'(\d+\.?\d*)', s)
91
+ if not m:
92
+ return None
93
+ try:
94
+ return float(m.group(1))
95
+ except:
96
+ return None
97
+
98
+ def convert_gender(value):
99
+ """
100
+ Map gender to binary: female -> 0, male -> 1; unknown -> None
101
+ """
102
+ s = _after_colon(value)
103
+ if not s:
104
+ return None
105
+ s = s.lower()
106
+ if s in {'female', 'f', 'woman', 'women'}:
107
+ return 0
108
+ if s in {'male', 'm', 'man', 'men'}:
109
+ return 1
110
+ return None
111
+
112
+ # 3. Save Metadata (initial filtering)
113
+ is_trait_available = trait_row is not None
114
+ _ = validate_and_save_cohort_info(
115
+ is_final=False,
116
+ cohort=cohort,
117
+ info_path=json_path,
118
+ is_gene_available=is_gene_available,
119
+ is_trait_available=is_trait_available
120
+ )
121
+
122
+ # 4. Clinical Feature Extraction
123
+ if trait_row is not None:
124
+ selected_clinical_df = geo_select_clinical_features(
125
+ clinical_df=clinical_data,
126
+ trait=trait,
127
+ trait_row=trait_row,
128
+ convert_trait=convert_trait,
129
+ age_row=age_row,
130
+ convert_age=convert_age,
131
+ gender_row=gender_row,
132
+ convert_gender=convert_gender
133
+ )
134
+ preview = preview_df(selected_clinical_df)
135
+ print(preview)
136
+
137
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
138
+ selected_clinical_df.to_csv(out_clinical_data_file)
139
+
140
+ # Step 3: Gene Data Extraction
141
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
142
+ gene_data = get_genetic_data(matrix_file)
143
+
144
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
145
+ print(gene_data.index[:20])
146
+
147
+ # Step 4: Gene Identifier Review
148
+ # Affymetrix probe set identifiers (e.g., '1007_s_at', '1053_at') indicate non-gene-symbol IDs.
149
+ requires_gene_mapping = True
150
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
151
+
152
+ # Step 5: Gene Annotation
153
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
154
+ gene_annotation = get_gene_annotation(soft_file)
155
+
156
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
157
+ print("Gene annotation preview:")
158
+ print(preview_df(gene_annotation))
159
+
160
+ # Step 6: Gene Identifier Mapping
161
+ # Determine appropriate columns for mapping based on the preview:
162
+ # Probe identifiers: 'ID'
163
+ # Gene symbols: 'Gene Symbol'
164
+
165
+ # 2. Extract the mapping dataframe (probe ID -> gene symbols)
166
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')
167
+
168
+ # 3. Apply the mapping to convert probe-level data to gene-level expression
169
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
170
+
171
+ # Step 7: Data Normalization and Linking
172
+ import os
173
+ import pandas as pd
174
+
175
+ # 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.
176
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
177
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
178
+ normalized_gene_data.to_csv(out_gene_data_file)
179
+
180
+ # 2. Link the clinical and genetic data with the 'geo_link_clinical_genetic_data' function from the library.
181
+ # Ensure clinical data is available in memory; otherwise, reload it from disk.
182
+ try:
183
+ selected_clinical_df
184
+ except NameError:
185
+ selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
186
+
187
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
188
+
189
+ # 3. Handle missing values in the linked data
190
+ linked_data = handle_missing_values(linked_data, trait)
191
+
192
+ # 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.
193
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
194
+
195
+ # 5. Conduct quality check and save the cohort information.
196
+ note = ("INFO: Cohort includes OA, RA, and controls; trait is defined as OA (1) vs non-OA (0). "
197
+ "Affymetrix HG-U133A/B platform; probe-to-gene mapping with equal split for multi-gene probes; "
198
+ "gene symbols normalized via NCBI synonyms.")
199
+ is_usable = validate_and_save_cohort_info(
200
+ True, cohort, json_path, True, True, is_trait_biased, unbiased_linked_data, note=note
201
+ )
202
+
203
+ # 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.
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/Osteoarthritis/code/GSE56409.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Osteoarthritis"
6
+ cohort = "GSE56409"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Osteoarthritis"
10
+ in_cohort_dir = "../DATA/GEO/Osteoarthritis/GSE56409"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z5/preprocess/Osteoarthritis/GSE56409.csv"
14
+ out_gene_data_file = "./output/z5/preprocess/Osteoarthritis/gene_data/GSE56409.csv"
15
+ out_clinical_data_file = "./output/z5/preprocess/Osteoarthritis/clinical_data/GSE56409.csv"
16
+ json_path = "./output/z5/preprocess/Osteoarthritis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+ import pandas as pd
42
+
43
+ # 1. Gene Expression Data Availability
44
+ is_gene_available = True # Microarray gene expression (not miRNA/methylation) per series summary
45
+
46
+ # 2. Variable Availability and Data Type Conversion
47
+
48
+ # From Sample Characteristics Dictionary:
49
+ # 0: tissue (Skin/Bone Marrow/Synovium)
50
+ # 1: disease (RA/OA) -> maps to trait Osteoarthritis
51
+ # 2: serum (Low/High)
52
+ trait_row = 1
53
+ age_row = None
54
+ gender_row = None
55
+
56
+ def _extract_after_colon(x):
57
+ if x is None:
58
+ return None
59
+ if isinstance(x, str):
60
+ parts = x.split(":", 1)
61
+ val = parts[1] if len(parts) > 1 else parts[0]
62
+ return val.strip()
63
+ return x
64
+
65
+ def convert_trait(x):
66
+ val = _extract_after_colon(x)
67
+ if val is None:
68
+ return None
69
+ s = str(val).strip().lower()
70
+ # Map osteoarthritis to 1, rheumatoid arthritis to 0
71
+ if s in {"oa", "osteoarthritis"} or "osteo" in s:
72
+ return 1
73
+ if s in {"ra", "rheumatoid arthritis", "rheumatoid"} or "rheumatoid" in s:
74
+ return 0
75
+ # If other/unknown disease labels appear, set to None
76
+ return None
77
+
78
+ def convert_age(x):
79
+ val = _extract_after_colon(x)
80
+ if val is None:
81
+ return None
82
+ s = str(val).strip().lower()
83
+ if s in {"na", "n/a", "none", "unknown", ""}:
84
+ return None
85
+ # Extract a numeric value (years assumed)
86
+ m = re.search(r"[-+]?\d*\.?\d+", s)
87
+ if m:
88
+ try:
89
+ return float(m.group(0))
90
+ except Exception:
91
+ return None
92
+ return None
93
+
94
+ def convert_gender(x):
95
+ val = _extract_after_colon(x)
96
+ if val is None:
97
+ return None
98
+ s = str(val).strip().lower()
99
+ if s in {"male", "m"}:
100
+ return 1
101
+ if s in {"female", "f"}:
102
+ return 0
103
+ return None
104
+
105
+ # 3. Save Metadata (initial filtering)
106
+ is_trait_available = trait_row is not None
107
+ _ = validate_and_save_cohort_info(
108
+ is_final=False,
109
+ cohort=cohort,
110
+ info_path=json_path,
111
+ is_gene_available=is_gene_available,
112
+ is_trait_available=is_trait_available
113
+ )
114
+
115
+ # 4. Clinical Feature Extraction (only if trait data is available)
116
+ if is_trait_available:
117
+ selected_clinical_df = geo_select_clinical_features(
118
+ clinical_df=clinical_data,
119
+ trait=trait,
120
+ trait_row=trait_row,
121
+ convert_trait=convert_trait,
122
+ age_row=age_row,
123
+ convert_age=convert_age,
124
+ gender_row=gender_row,
125
+ convert_gender=convert_gender
126
+ )
127
+ preview = preview_df(selected_clinical_df)
128
+ print(preview)
129
+
130
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
131
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
132
+
133
+ # Step 3: Gene Data Extraction
134
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
135
+ gene_data = get_genetic_data(matrix_file)
136
+
137
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
138
+ print(gene_data.index[:20])
139
+
140
+ # Step 4: Gene Identifier Review
141
+ # Affymetrix probe set IDs (e.g., '1007_s_at') are not gene symbols.
142
+ print("requires_gene_mapping = True")
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 correct columns for probe IDs and gene symbols from the annotation preview:
154
+ # Probe IDs: 'ID' (e.g., '1007_s_at')
155
+ # Gene symbols: 'Gene Symbol'
156
+
157
+ # 1-2. Build mapping dataframe from annotation
158
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')
159
+
160
+ # 3. Apply mapping to convert probe-level data to gene-level expression
161
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
162
+
163
+ # Step 7: Data Normalization and Linking
164
+ import os
165
+
166
+ # 1. Normalize gene symbols and save
167
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
168
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
169
+ normalized_gene_data.to_csv(out_gene_data_file)
170
+
171
+ # 2. Link clinical and genetic data
172
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
173
+
174
+ # 3. Handle missing values
175
+ linked_data = handle_missing_values(linked_data, trait)
176
+
177
+ # 4. Bias evaluation and removal of biased covariates
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
+ is_usable = validate_and_save_cohort_info(
182
+ is_final=True,
183
+ cohort=cohort,
184
+ info_path=json_path,
185
+ is_gene_available=True,
186
+ is_trait_available=True,
187
+ is_biased=is_trait_biased,
188
+ df=unbiased_linked_data,
189
+ note="INFO: Affymetrix probe-to-gene mapping applied; trait is OA(1) vs RA(0); age/gender not available in matrix."
190
+ )
191
+
192
+ # 6. Save linked data if usable
193
+ if is_usable:
194
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
195
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Osteoarthritis/code/GSE75181.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Osteoarthritis"
6
+ cohort = "GSE75181"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Osteoarthritis"
10
+ in_cohort_dir = "../DATA/GEO/Osteoarthritis/GSE75181"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z5/preprocess/Osteoarthritis/GSE75181.csv"
14
+ out_gene_data_file = "./output/z5/preprocess/Osteoarthritis/gene_data/GSE75181.csv"
15
+ out_clinical_data_file = "./output/z5/preprocess/Osteoarthritis/clinical_data/GSE75181.csv"
16
+ json_path = "./output/z5/preprocess/Osteoarthritis/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 # Microarray gene expression profiling described in background
41
+
42
+ # 2. Variable Availability and Data Type Conversion
43
+
44
+ # Based on the sample characteristics:
45
+ # 1: ['disease state: osteoarthritis'] -> constant and not useful for trait association (all OA)
46
+ # 2: ['gender: female', 'gender: male'] -> available
47
+ # 3: ['age: ... years old'] -> available
48
+ trait_row = None
49
+ age_row = 3
50
+ gender_row = 2
51
+
52
+ def _after_colon(value):
53
+ if value is None:
54
+ return None
55
+ if isinstance(value, str) and ':' in value:
56
+ return value.split(':', 1)[1].strip()
57
+ return value
58
+
59
+ # Even though trait is not available (constant OA), define a converter for completeness (unused)
60
+ def convert_trait(x):
61
+ v = _after_colon(x)
62
+ if v is None:
63
+ return None
64
+ v_low = str(v).lower()
65
+ # Map osteoarthritis/OA to 1, normal/control to 0 if ever present; otherwise None
66
+ if 'osteoarthritis' in v_low or v_low == 'oa':
67
+ return 1
68
+ if 'normal' in v_low or 'control' in v_low or v_low == 'no':
69
+ return 0
70
+ return None
71
+
72
+ def convert_age(x):
73
+ v = _after_colon(x)
74
+ if v is None:
75
+ return None
76
+ # Extract first number as age in years
77
+ import re
78
+ match = re.search(r'(\d+(\.\d+)?)', str(v))
79
+ if match:
80
+ try:
81
+ age_val = float(match.group(1))
82
+ return age_val
83
+ except Exception:
84
+ return None
85
+ return None
86
+
87
+ def convert_gender(x):
88
+ v = _after_colon(x)
89
+ if v is None:
90
+ return None
91
+ v_low = str(v).lower().strip()
92
+ if v_low in ['female', 'f', 'woman', 'women']:
93
+ return 0
94
+ if v_low in ['male', 'm', '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(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
+ # 4. Clinical Feature Extraction (skip because trait_row is None)
107
+ # If trait_row were available:
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
+ # clinical_preview = preview_df(selected_clinical_df)
120
+ # selected_clinical_df.to_csv(out_clinical_data_file, index=True)
121
+
122
+ # Step 3: Gene Data Extraction
123
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
124
+ gene_data = get_genetic_data(matrix_file)
125
+
126
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
127
+ print(gene_data.index[:20])
128
+
129
+ # Step 4: Gene Identifier Review
130
+ print("requires_gene_mapping = True")
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
+ # 1-2. Identify the probe ID and gene symbol columns in the annotation and create mapping
142
+ probe_col = 'ID' # matches probe identifiers like ILMN_1343291
143
+ gene_col = 'Symbol' # contains gene symbols
144
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_col)
145
+
146
+ # 3. Apply mapping to convert probe-level data to gene-level expression
147
+ probe_level_expr = gene_data # from previous step
148
+ gene_data = apply_gene_mapping(expression_df=probe_level_expr, mapping_df=mapping_df)
149
+
150
+ # Step 7: Data Normalization and Linking
151
+ # 1. Normalize the obtained gene data and save to file
152
+ import os
153
+
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-6. Trait is not available (constant OA per Step 2), so skip linking and downstream processing.
159
+ # Perform final validation reflecting lack of trait data and do not save linked data.
160
+ is_trait_available = False
161
+ is_usable = validate_and_save_cohort_info(
162
+ is_final=True,
163
+ cohort=cohort,
164
+ info_path=json_path,
165
+ is_gene_available=True,
166
+ is_trait_available=is_trait_available,
167
+ is_biased=False,
168
+ df=normalized_gene_data.T,
169
+ note="INFO: Trait not available (constant OA); linking and downstream steps skipped."
170
+ )
171
+
172
+ # Do not save out_data_file since dataset is not usable for association without trait variation.
output/preprocess/Osteoarthritis/code/GSE93698.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Osteoarthritis"
6
+ cohort = "GSE93698"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Osteoarthritis"
10
+ in_cohort_dir = "../DATA/GEO/Osteoarthritis/GSE93698"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z5/preprocess/Osteoarthritis/GSE93698.csv"
14
+ out_gene_data_file = "./output/z5/preprocess/Osteoarthritis/gene_data/GSE93698.csv"
15
+ out_clinical_data_file = "./output/z5/preprocess/Osteoarthritis/clinical_data/GSE93698.csv"
16
+ json_path = "./output/z5/preprocess/Osteoarthritis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+ import pandas as pd
42
+
43
+ # 1) Gene expression availability (based on series description: high-density transcriptomic)
44
+ is_gene_available = True
45
+
46
+ # 2) Variable availability inferred from Sample Characteristics Dictionary in the prompt
47
+ trait_row = 1 # 'disease state'
48
+ age_row = 2 # 'age'
49
+ gender_row = 3 # 'gender'
50
+
51
+ # 2.2) Conversion functions
52
+ def _after_colon(x):
53
+ if x is None:
54
+ return None
55
+ x = str(x)
56
+ parts = x.split(":", 1)
57
+ val = parts[1] if len(parts) > 1 else parts[0]
58
+ return val.strip()
59
+
60
+ def convert_trait(x):
61
+ v = _after_colon(x)
62
+ if v is None:
63
+ return None
64
+ v_low = v.lower()
65
+ # Case = Osteoarthritis -> 1; Non-OA diseases -> 0
66
+ if "osteoarthritis" in v_low:
67
+ return 1
68
+ # Known non-OA disease states in this series
69
+ non_oa_terms = [
70
+ "rheumatoid arthritis", "diffuse systemic sclerosis", "microcrystalline arthritis",
71
+ "systemic lupus erythematosus", "seronegative arthritis"
72
+ ]
73
+ if any(term in v_low for term in non_oa_terms):
74
+ return 0
75
+ # If disease state given but not matching above, default to 0 (non-OA) if it looks like a disease label
76
+ if len(v_low) > 0:
77
+ return 0
78
+ return None
79
+
80
+ def convert_age(x):
81
+ v = _after_colon(x)
82
+ if v is None:
83
+ return None
84
+ # Extract first number
85
+ m = re.search(r"[-+]?\d*\.?\d+", v)
86
+ if not m:
87
+ return None
88
+ try:
89
+ return float(m.group(0))
90
+ except Exception:
91
+ return None
92
+
93
+ def convert_gender(x):
94
+ v = _after_colon(x)
95
+ if v is None:
96
+ return None
97
+ v_low = v.strip().lower()
98
+ if v_low in {"f", "female", "woman", "women"}:
99
+ return 0
100
+ if v_low in {"m", "male", "man", "men"}:
101
+ return 1
102
+ return None
103
+
104
+ # 3) Initial filtering metadata save
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 clinical data 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=age_row,
122
+ convert_age=convert_age,
123
+ gender_row=gender_row,
124
+ convert_gender=convert_gender
125
+ )
126
+ preview = preview_df(selected_clinical_df, n=5)
127
+ print(preview)
128
+
129
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
130
+ selected_clinical_df.to_csv(out_clinical_data_file, index=False)
131
+
132
+ # Step 3: Gene Data Extraction
133
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
134
+ gene_data = get_genetic_data(matrix_file)
135
+
136
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
137
+ print(gene_data.index[:20])
138
+
139
+ # Step 4: Gene Identifier Review
140
+ print("requires_gene_mapping = True")
141
+
142
+ # Step 5: Gene Annotation
143
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
144
+ gene_annotation = get_gene_annotation(soft_file)
145
+
146
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
147
+ print("Gene annotation preview:")
148
+ print(preview_df(gene_annotation))
149
+
150
+ # Step 6: Gene Identifier Mapping
151
+ # Determine the correct columns for mapping: probe IDs and gene symbols
152
+ probe_col = 'ID'
153
+ gene_symbol_col = 'Gene Symbol'
154
+
155
+ # 2) Build the mapping dataframe
156
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
157
+
158
+ # 3) Apply the mapping to convert probe-level data to gene-level expression
159
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
160
+
161
+ # Step 7: Data Normalization and Linking
162
+ import os
163
+
164
+ # 1. Normalize gene symbols and save gene data
165
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
166
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
167
+ normalized_gene_data.to_csv(out_gene_data_file)
168
+
169
+ # 2. Link clinical and genetic data
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. Assess bias and remove biased demographic features if necessary
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 = normalized_gene_data.shape[0] > 0
180
+ is_trait_available = trait in linked_data.columns
181
+ note = "INFO: Affymetrix probe IDs mapped to gene symbols; partial age/gender; missingness handled per protocol."
182
+ is_usable = validate_and_save_cohort_info(
183
+ True, cohort, json_path, is_gene_available, is_trait_available, is_trait_biased, unbiased_linked_data, note=note
184
+ )
185
+
186
+ # 6. Save linked data if usable
187
+ if is_usable:
188
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
189
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Osteoarthritis/code/GSE93720.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Osteoarthritis"
6
+ cohort = "GSE93720"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Osteoarthritis"
10
+ in_cohort_dir = "../DATA/GEO/Osteoarthritis/GSE93720"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z5/preprocess/Osteoarthritis/GSE93720.csv"
14
+ out_gene_data_file = "./output/z5/preprocess/Osteoarthritis/gene_data/GSE93720.csv"
15
+ out_clinical_data_file = "./output/z5/preprocess/Osteoarthritis/clinical_data/GSE93720.csv"
16
+ json_path = "./output/z5/preprocess/Osteoarthritis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import os
40
+ import re
41
+ import pandas as pd
42
+
43
+ # 1) Gene expression availability
44
+ # Microarray platform "GeneChip Human Genome U133 Plus 2.0" => mRNA expression data
45
+ is_gene_available = True
46
+
47
+ # 2) Variable availability and converters
48
+ # From the sample characteristics:
49
+ # 0: disease (OA vs RA) -> use as trait (binary: OA=1, RA=0)
50
+ trait_row = 0
51
+ age_row = None
52
+ gender_row = None
53
+
54
+ # Data type notes (for reference)
55
+ trait_type = 'binary'
56
+ age_type = 'continuous'
57
+ gender_type = 'binary'
58
+
59
+ def _extract_after_colon(x):
60
+ if x is None:
61
+ return None
62
+ if not isinstance(x, str):
63
+ x = str(x)
64
+ parts = x.split(':', 1)
65
+ val = parts[1] if len(parts) > 1 else parts[0]
66
+ return val.strip().strip('"').strip()
67
+
68
+ def convert_trait(x):
69
+ val = _extract_after_colon(x)
70
+ if val is None:
71
+ return None
72
+ v = val.lower()
73
+ if v in {'oa', 'osteoarthritis'}:
74
+ return 1
75
+ if v in {'ra', 'rheumatoid arthritis'}:
76
+ return 0
77
+ return None
78
+
79
+ def convert_age(x):
80
+ val = _extract_after_colon(x)
81
+ if val is None:
82
+ return None
83
+ v = val.lower()
84
+ if v in {'na', 'n/a', 'none', ''}:
85
+ return None
86
+ nums = re.findall(r'[\d.]+', v)
87
+ if not nums:
88
+ return None
89
+ try:
90
+ return float(nums[0])
91
+ except Exception:
92
+ return None
93
+
94
+ def convert_gender(x):
95
+ val = _extract_after_colon(x)
96
+ if val is None:
97
+ return None
98
+ v = val.lower()
99
+ if v in {'female', 'f', 'woman', 'women'}:
100
+ return 0
101
+ if v in {'male', 'm', 'man', 'men'}:
102
+ return 1
103
+ return None
104
+
105
+ # 3) Save metadata (initial filtering)
106
+ is_trait_available = trait_row is not None
107
+ _ = validate_and_save_cohort_info(
108
+ is_final=False,
109
+ cohort=cohort,
110
+ info_path=json_path,
111
+ is_gene_available=is_gene_available,
112
+ is_trait_available=is_trait_available
113
+ )
114
+
115
+ # 4) Clinical feature extraction (only if trait is available)
116
+ if trait_row is not None:
117
+ selected_clinical_df = geo_select_clinical_features(
118
+ clinical_df=clinical_data,
119
+ trait=trait,
120
+ trait_row=trait_row,
121
+ convert_trait=convert_trait,
122
+ age_row=age_row,
123
+ convert_age=convert_age,
124
+ gender_row=gender_row,
125
+ convert_gender=convert_gender
126
+ )
127
+ clinical_preview = preview_df(selected_clinical_df)
128
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
129
+ selected_clinical_df.to_csv(out_clinical_data_file)
130
+
131
+ # Step 3: Gene Data Extraction
132
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
133
+ gene_data = get_genetic_data(matrix_file)
134
+
135
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
136
+ print(gene_data.index[:20])
137
+
138
+ # Step 4: Gene Identifier Review
139
+ requires_gene_mapping = True
140
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
141
+
142
+ # Step 5: Gene Annotation
143
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
144
+ gene_annotation = get_gene_annotation(soft_file)
145
+
146
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
147
+ print("Gene annotation preview:")
148
+ print(preview_df(gene_annotation))
149
+
150
+ # Step 6: Gene Identifier Mapping
151
+ # Identify the appropriate columns in the annotation:
152
+ # - Probe identifiers in expression data match the 'ID' column in gene_annotation
153
+ # - Gene symbols are stored in the 'Gene Symbol' column
154
+ probe_col = 'ID'
155
+ gene_symbol_col = 'Gene Symbol'
156
+
157
+ # 2. Build mapping dataframe (probe -> gene symbol)
158
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
159
+
160
+ # 3. Apply mapping to convert probe-level data to gene-level expression
161
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
162
+
163
+ # Step 7: Data Normalization and Linking
164
+ import os
165
+ import pandas as pd
166
+
167
+ # 1. Normalize gene symbols and save
168
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
169
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
170
+ normalized_gene_data.to_csv(out_gene_data_file)
171
+
172
+ # 2. Link clinical and genetic data
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. Assess bias 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 = (normalized_gene_data.shape[0] > 0) and (normalized_gene_data.shape[1] > 0)
183
+ is_trait_available_flag = isinstance(selected_clinical_df, pd.DataFrame) and (trait in selected_clinical_df.index)
184
+
185
+ note = "INFO: In vitro synovial fibroblast stimulations (TNF, IL-17A, TNF+IL-17A, baseline) present; trait is OA vs RA donor origin."
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/Osteoarthritis/code/GSE98460.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Osteoarthritis"
6
+ cohort = "GSE98460"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Osteoarthritis"
10
+ in_cohort_dir = "../DATA/GEO/Osteoarthritis/GSE98460"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z5/preprocess/Osteoarthritis/GSE98460.csv"
14
+ out_gene_data_file = "./output/z5/preprocess/Osteoarthritis/gene_data/GSE98460.csv"
15
+ out_clinical_data_file = "./output/z5/preprocess/Osteoarthritis/clinical_data/GSE98460.csv"
16
+ json_path = "./output/z5/preprocess/Osteoarthritis/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 # RNA microarray-based transcriptional analysis suggests gene expression data is available.
43
+
44
+ # 2. Variable Availability and Data Type Conversion
45
+
46
+ # Keys identified from Sample Characteristics Dictionary
47
+ trait_row = None # All samples are OA; no variability for case/control on the trait.
48
+ age_row = 2
49
+ gender_row = 3
50
+
51
+ # Conversion helpers
52
+ def _extract_value(cell: str) -> str:
53
+ if cell is None:
54
+ return ""
55
+ parts = str(cell).split(":", 1)
56
+ return parts[1].strip() if len(parts) > 1 else str(cell).strip()
57
+
58
+ def convert_trait(x):
59
+ # Not used since trait_row is None. If ever used, map OA to 1 and others to 0.
60
+ val = _extract_value(x).lower()
61
+ if val in {"", "na", "n/a", "none", "unknown"}:
62
+ return None
63
+ return 1 if "osteoarthritis" in val or val == "oa" else 0
64
+
65
+ def convert_age(x):
66
+ val = _extract_value(x)
67
+ if val == "" or val.lower() in {"na", "n/a", "none", "unknown"}:
68
+ return None
69
+ # Extract the first number (integer or float)
70
+ m = re.search(r"[-+]?\d*\.?\d+", val)
71
+ if not m:
72
+ return None
73
+ try:
74
+ num = float(m.group())
75
+ return num
76
+ except Exception:
77
+ return None
78
+
79
+ def convert_gender(x):
80
+ val = _extract_value(x).lower()
81
+ if val in {"", "na", "n/a", "none", "unknown"}:
82
+ return None
83
+ if val.startswith("f"):
84
+ return 0
85
+ if val.startswith("m"):
86
+ return 1
87
+ # Try to infer from words
88
+ if "female" in val:
89
+ return 0
90
+ if "male" in val:
91
+ return 1
92
+ return None
93
+
94
+ # 3. Save Metadata (initial filtering)
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
105
+ # Skipped because trait_row is None (no variable trait data available in this cohort).
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
+ # Based on the provided identifiers from the previous step
116
+ ids = ['16650001', '16650003', '16650005', '16650007', '16650009', '16650011',
117
+ '16650013', '16650015', '16650017', '16650019', '16650021', '16650023',
118
+ '16650025', '16650027', '16650029', '16650031', '16650033', '16650035',
119
+ '16650037', '16650041']
120
+
121
+ # Human gene symbols typically contain alphabetic characters; purely numeric IDs indicate probe IDs.
122
+ requires_gene_mapping = all(x.isdigit() for x in ids)
123
+
124
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
125
+
126
+ # Step 5: Gene Annotation
127
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
128
+ gene_annotation = get_gene_annotation(soft_file)
129
+
130
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
131
+ print("Gene annotation preview:")
132
+ print(preview_df(gene_annotation))
133
+
134
+ # Step 6: Gene Identifier Mapping
135
+ import os
136
+
137
+ # Try to find a platform SOFT file that contains a usable gene symbol column
138
+ probe_col = 'ID'
139
+ candidate_gene_cols = [
140
+ 'Gene Symbol', 'GENE_SYMBOL', 'Symbol', 'GENE', 'GENE_SYMBOLS', 'SYMBOL',
141
+ 'gene_assignment', 'Gene Title', 'GENE_NAME'
142
+ ]
143
+
144
+ soft_files = [f for f in os.listdir(in_cohort_dir) if 'soft' in f.lower()]
145
+ best_soft = None
146
+ best_col = None
147
+ best_count = 0
148
+ best_annotation = None
149
+
150
+ for sf in soft_files:
151
+ try:
152
+ ann = get_gene_annotation(os.path.join(in_cohort_dir, sf))
153
+ except Exception:
154
+ continue
155
+ present_candidates = [col for col in candidate_gene_cols if col in ann.columns]
156
+ if not present_candidates:
157
+ continue
158
+ # Score columns by how many recognizable human gene symbols they yield
159
+ for col in present_candidates:
160
+ series = ann[col].dropna().astype(str)
161
+ sample = series.head(200)
162
+ count = sum(len(extract_human_gene_symbols(x)) for x in sample)
163
+ if count > best_count:
164
+ best_count = count
165
+ best_col = col
166
+ best_soft = sf
167
+ best_annotation = ann
168
+
169
+ # If a suitable annotation with gene symbols is found, build mapping and apply it
170
+ mapped_successfully = False
171
+ if best_annotation is not None and best_col is not None and best_count > 0:
172
+ try:
173
+ mapping_df = get_gene_mapping(best_annotation, prob_col=probe_col, gene_col=best_col)
174
+ # Ensure there is overlap between mapping IDs and expression IDs
175
+ overlap = mapping_df['ID'].isin(gene_data.index).sum()
176
+ if overlap > 0:
177
+ mapped_gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
178
+ # Sanity check: non-empty result
179
+ if mapped_gene_data.shape[0] > 0:
180
+ gene_data = mapped_gene_data
181
+ mapped_successfully = True
182
+ except Exception:
183
+ mapped_successfully = False
184
+
185
+ # Fallback: if mapping not successful, keep probe-level data as-is (identity, probe IDs as features)
186
+ # This allows the pipeline to continue, but downstream steps should consider this dataset unsuitable for cross-cohort gene-level analyses.
187
+ # No further action needed since 'gene_data' already holds probe-level expression.
188
+
189
+ # Step 7: Data Normalization and Linking
190
+ import pandas as pd
191
+
192
+ # 1. Normalize gene symbols and save gene-level data (may be empty if mapping failed)
193
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
194
+ normalized_gene_data.to_csv(out_gene_data_file)
195
+
196
+ # Determine availability based on normalized gene-level data
197
+ is_gene_available = normalized_gene_data.shape[0] > 0
198
+
199
+ # 2-6. Proceed only if clinical data exists; otherwise, finalize with correct flags
200
+ if 'selected_clinical_data' in globals() and selected_clinical_data is not None:
201
+ # 2. Link clinical and genetic data
202
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_data, normalized_gene_data)
203
+
204
+ # 3. Handle missing values
205
+ linked_data = handle_missing_values(linked_data, trait)
206
+
207
+ # 4. Bias checks and removal of biased covariates
208
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
209
+
210
+ # 5. Final validation and save cohort info
211
+ is_usable = validate_and_save_cohort_info(
212
+ is_final=True,
213
+ cohort=cohort,
214
+ info_path=json_path,
215
+ is_gene_available=is_gene_available,
216
+ is_trait_available=True,
217
+ is_biased=is_trait_biased,
218
+ df=unbiased_linked_data,
219
+ note="INFO: Linked clinical and gene data; performed missing-value handling and bias checks."
220
+ )
221
+
222
+ # 6. Save linked data only if usable
223
+ if is_usable:
224
+ unbiased_linked_data.to_csv(out_data_file)
225
+ else:
226
+ # Trait not available; skip linking and downstream steps
227
+ note_msg = "INFO: Trait not available for this cohort; skipped linking and downstream steps."
228
+ if normalized_gene_data.shape[0] == 0:
229
+ note_msg += " Gene mapping/normalization yielded no recognized symbols."
230
+ validate_and_save_cohort_info(
231
+ is_final=True,
232
+ cohort=cohort,
233
+ info_path=json_path,
234
+ is_gene_available=is_gene_available,
235
+ is_trait_available=False,
236
+ is_biased=False, # placeholder; function will override due to empty df
237
+ df=pd.DataFrame(),
238
+ note=note_msg
239
+ )
output/preprocess/Osteoarthritis/code/TCGA.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Osteoarthritis"
6
+
7
+ # Input paths
8
+ tcga_root_dir = "../DATA/TCGA"
9
+
10
+ # Output paths
11
+ out_data_file = "./output/z5/preprocess/Osteoarthritis/TCGA.csv"
12
+ out_gene_data_file = "./output/z5/preprocess/Osteoarthritis/gene_data/TCGA.csv"
13
+ out_clinical_data_file = "./output/z5/preprocess/Osteoarthritis/clinical_data/TCGA.csv"
14
+ json_path = "./output/z5/preprocess/Osteoarthritis/cohort_info.json"
15
+
16
+
17
+ # Step 1: Initial Data Loading
18
+ import os
19
+ import pandas as pd
20
+
21
+ # Step 1: Select the most relevant TCGA subdirectory for Osteoarthritis (likely none in TCGA cancer cohorts)
22
+ subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))]
23
+ trait_terms_priority = [
24
+ "osteoarthritis",
25
+ "degenerative_joint_disease",
26
+ "djd",
27
+ "arthritis",
28
+ "joint",
29
+ "cartilage"
30
+ ]
31
+
32
+ selected_dir = None
33
+ for term in trait_terms_priority:
34
+ matches = [d for d in subdirs if term in d.lower()]
35
+ if matches:
36
+ # Choose the most specific (first) match
37
+ selected_dir = matches[0]
38
+ break
39
+
40
+ clinical_df = None
41
+ genetic_df = None
42
+
43
+ if selected_dir is not None:
44
+ cohort_dir = os.path.join(tcga_root_dir, selected_dir)
45
+ clinical_path, genetic_path = tcga_get_relevant_filepaths(cohort_dir)
46
+
47
+ clinical_df = pd.read_csv(clinical_path, sep='\t', index_col=0, low_memory=False)
48
+ genetic_df = pd.read_csv(genetic_path, sep='\t', index_col=0, low_memory=False)
49
+
50
+ print(list(clinical_df.columns))
51
+ else:
52
+ # No suitable TCGA cohort for Osteoarthritis; record and skip
53
+ _ = validate_and_save_cohort_info(
54
+ is_final=False,
55
+ cohort=f"No_TCGA_Cohort_for_{trait.replace(' ', '_')}",
56
+ info_path=json_path,
57
+ is_gene_available=False,
58
+ is_trait_available=False
59
+ )
60
+ print([])
output/preprocess/Osteoarthritis/cohort_info.json CHANGED
@@ -1,112 +1 @@
1
- {
2
- "GSE98460": {
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
- "GSE93720": {
13
- "is_usable": false,
14
- "is_gene_available": true,
15
- "is_trait_available": true,
16
- "is_available": true,
17
- "is_biased": true,
18
- "has_age": false,
19
- "has_gender": false,
20
- "sample_size": 1
21
- },
22
- "GSE93698": {
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": 30
31
- },
32
- "GSE75181": {
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
- "GSE56409": {
43
- "is_usable": true,
44
- "is_gene_available": true,
45
- "is_trait_available": true,
46
- "is_available": true,
47
- "is_biased": false,
48
- "has_age": false,
49
- "has_gender": false,
50
- "sample_size": 102
51
- },
52
- "GSE55457": {
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": 33
61
- },
62
- "GSE236924": {
63
- "is_usable": true,
64
- "is_gene_available": true,
65
- "is_trait_available": true,
66
- "is_available": true,
67
- "is_biased": false,
68
- "has_age": false,
69
- "has_gender": false,
70
- "sample_size": 132
71
- },
72
- "GSE142049": {
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": 114
81
- },
82
- "GSE141934": {
83
- "is_usable": true,
84
- "is_gene_available": true,
85
- "is_trait_available": true,
86
- "is_available": true,
87
- "is_biased": false,
88
- "has_age": false,
89
- "has_gender": false,
90
- "sample_size": 100
91
- },
92
- "GSE107105": {
93
- "is_usable": true,
94
- "is_gene_available": true,
95
- "is_trait_available": true,
96
- "is_available": true,
97
- "is_biased": false,
98
- "has_age": false,
99
- "has_gender": false,
100
- "sample_size": 36
101
- },
102
- "TCGA": {
103
- "is_usable": false,
104
- "is_gene_available": false,
105
- "is_trait_available": false,
106
- "is_available": false,
107
- "is_biased": null,
108
- "has_age": null,
109
- "has_gender": null,
110
- "sample_size": null
111
- }
112
- }
 
1
+ {"GSE98460": {"is_usable": false, "is_gene_available": false, "is_trait_available": false, "is_available": false, "is_biased": null, "has_age": null, "has_gender": null, "sample_size": null, "note": "INFO: Trait not available for this cohort; skipped linking and downstream steps. Gene mapping/normalization yielded no recognized symbols."}, "GSE93720": {"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": 48, "note": "INFO: In vitro synovial fibroblast stimulations (TNF, IL-17A, TNF+IL-17A, baseline) present; trait is OA vs RA donor origin."}, "GSE93698": {"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": 30, "note": "INFO: Affymetrix probe IDs mapped to gene symbols; partial age/gender; missingness handled per protocol."}, "GSE75181": {"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 not available (constant OA); linking and downstream steps skipped."}, "GSE56409": {"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": 102, "note": "INFO: Affymetrix probe-to-gene mapping applied; trait is OA(1) vs RA(0); age/gender not available in matrix."}, "GSE55457": {"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": 33, "note": "INFO: Cohort includes OA, RA, and controls; trait is defined as OA (1) vs non-OA (0). Affymetrix HG-U133A/B platform; probe-to-gene mapping with equal split for multi-gene probes; gene symbols normalized via NCBI synonyms."}, "GSE236924": {"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": 132, "note": "INFO: Trait available; Age/Gender not provided in clinical annotations; Affymetrix probes mapped to gene symbols via platform annotation; gene symbols normalized via synonyms."}, "GSE142049": {"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": 114, "note": "INFO: Probe IDs (ILMN) mapped via SOFT 'ID'->'Symbol'; symbols normalized using NCBI synonyms."}, "GSE141934": {"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": 99, "note": "INFO: Illumina probe IDs mapped to gene symbols via platform annotation; CD4+ T cells from peripheral blood; trait derived from 'working_diagnosis' as binary Osteoarthritis vs. non-Osteoarthritis."}, "GSE107105": {"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": 36, "note": "WARNING: Gene symbol normalization dropped too many rows (kept 0.0%). Falling back to original identifiers."}, "No_TCGA_Cohort_for_Osteoarthritis": {"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/Osteoporosis/GSE56815.csv CHANGED
The diff for this file is too large to render. See raw diff
 
output/preprocess/Osteoporosis/clinical_data/GSE56814.csv CHANGED
@@ -1,74 +1,2 @@
1
- ,Osteoporosis,Gender
2
- GSM1369683,,0
3
- GSM1369684,,0
4
- GSM1369685,,0
5
- GSM1369686,,0
6
- GSM1369687,,0
7
- GSM1369688,,0
8
- GSM1369689,,0
9
- GSM1369690,,0
10
- GSM1369691,,0
11
- GSM1369692,,0
12
- GSM1369693,,0
13
- GSM1369694,,0
14
- GSM1369695,,0
15
- GSM1369696,,0
16
- GSM1369697,,0
17
- GSM1369698,,0
18
- GSM1369699,,0
19
- GSM1369700,,0
20
- GSM1369701,,0
21
- GSM1369702,,0
22
- GSM1369703,,0
23
- GSM1369704,,0
24
- GSM1369705,,0
25
- GSM1369706,,0
26
- GSM1369707,,0
27
- GSM1369708,,0
28
- GSM1369709,,0
29
- GSM1369710,,0
30
- GSM1369711,,0
31
- GSM1369712,,0
32
- GSM1369713,,0
33
- GSM1369714,,0
34
- GSM1369715,,0
35
- GSM1369716,,0
36
- GSM1369717,,0
37
- GSM1369718,,0
38
- GSM1369719,,0
39
- GSM1369720,,0
40
- GSM1369721,,0
41
- GSM1369722,,0
42
- GSM1369723,,0
43
- GSM1369724,,0
44
- GSM1369725,,0
45
- GSM1369726,,0
46
- GSM1369727,,0
47
- GSM1369728,,0
48
- GSM1369729,,0
49
- GSM1369730,,0
50
- GSM1369731,,0
51
- GSM1369732,,0
52
- GSM1369733,,0
53
- GSM1369734,,0
54
- GSM1369735,,0
55
- GSM1369736,,0
56
- GSM1369737,,0
57
- GSM1369738,,0
58
- GSM1369739,,0
59
- GSM1369740,,0
60
- GSM1369741,,0
61
- GSM1369742,,0
62
- GSM1369743,,0
63
- GSM1369744,,0
64
- GSM1369745,,0
65
- GSM1369746,,0
66
- GSM1369747,,0
67
- GSM1369748,,0
68
- GSM1369749,,0
69
- GSM1369750,,0
70
- GSM1369751,,0
71
- GSM1369752,,0
72
- GSM1369753,,0
73
- GSM1369754,,0
74
- GSM1369755,,0
 
1
+ ,GSM1369683,GSM1369684,GSM1369685,GSM1369686,GSM1369687,GSM1369688,GSM1369689,GSM1369690,GSM1369691,GSM1369692,GSM1369693,GSM1369694,GSM1369695,GSM1369696,GSM1369697,GSM1369698,GSM1369699,GSM1369700,GSM1369701,GSM1369702,GSM1369703,GSM1369704,GSM1369705,GSM1369706,GSM1369707,GSM1369708,GSM1369709,GSM1369710,GSM1369711,GSM1369712,GSM1369713,GSM1369714,GSM1369715,GSM1369716,GSM1369717,GSM1369718,GSM1369719,GSM1369720,GSM1369721,GSM1369722,GSM1369723,GSM1369724,GSM1369725,GSM1369726,GSM1369727,GSM1369728,GSM1369729,GSM1369730,GSM1369731,GSM1369732,GSM1369733,GSM1369734,GSM1369735,GSM1369736,GSM1369737,GSM1369738,GSM1369739,GSM1369740,GSM1369741,GSM1369742,GSM1369743,GSM1369744,GSM1369745,GSM1369746,GSM1369747,GSM1369748,GSM1369749,GSM1369750,GSM1369751,GSM1369752,GSM1369753,GSM1369754,GSM1369755
2
+ Osteoporosis,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,1.0,1.0,0.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,0.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,1.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
output/preprocess/Osteoporosis/clinical_data/GSE56815.csv CHANGED
@@ -1,3 +1,2 @@
1
  ,GSM1369756,GSM1369757,GSM1369758,GSM1369759,GSM1369760,GSM1369761,GSM1369762,GSM1369763,GSM1369764,GSM1369765,GSM1369766,GSM1369767,GSM1369768,GSM1369769,GSM1369770,GSM1369771,GSM1369772,GSM1369773,GSM1369774,GSM1369775,GSM1369776,GSM1369777,GSM1369778,GSM1369779,GSM1369780,GSM1369781,GSM1369782,GSM1369783,GSM1369784,GSM1369785,GSM1369786,GSM1369787,GSM1369788,GSM1369789,GSM1369790,GSM1369791,GSM1369792,GSM1369793,GSM1369794,GSM1369795,GSM1369796,GSM1369797,GSM1369798,GSM1369799,GSM1369800,GSM1369801,GSM1369802,GSM1369803,GSM1369804,GSM1369805,GSM1369806,GSM1369807,GSM1369808,GSM1369809,GSM1369810,GSM1369811,GSM1369812,GSM1369813,GSM1369814,GSM1369815,GSM1369816,GSM1369817,GSM1369818,GSM1369819,GSM1369820,GSM1369821,GSM1369822,GSM1369823,GSM1369824,GSM1369825,GSM1369826,GSM1369827,GSM1369828,GSM1369829,GSM1369830,GSM1369831,GSM1369832,GSM1369833,GSM1369834,GSM1369835
2
  Osteoporosis,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,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,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,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,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,1.0,0.0,1.0,1.0,1.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
 
1
  ,GSM1369756,GSM1369757,GSM1369758,GSM1369759,GSM1369760,GSM1369761,GSM1369762,GSM1369763,GSM1369764,GSM1369765,GSM1369766,GSM1369767,GSM1369768,GSM1369769,GSM1369770,GSM1369771,GSM1369772,GSM1369773,GSM1369774,GSM1369775,GSM1369776,GSM1369777,GSM1369778,GSM1369779,GSM1369780,GSM1369781,GSM1369782,GSM1369783,GSM1369784,GSM1369785,GSM1369786,GSM1369787,GSM1369788,GSM1369789,GSM1369790,GSM1369791,GSM1369792,GSM1369793,GSM1369794,GSM1369795,GSM1369796,GSM1369797,GSM1369798,GSM1369799,GSM1369800,GSM1369801,GSM1369802,GSM1369803,GSM1369804,GSM1369805,GSM1369806,GSM1369807,GSM1369808,GSM1369809,GSM1369810,GSM1369811,GSM1369812,GSM1369813,GSM1369814,GSM1369815,GSM1369816,GSM1369817,GSM1369818,GSM1369819,GSM1369820,GSM1369821,GSM1369822,GSM1369823,GSM1369824,GSM1369825,GSM1369826,GSM1369827,GSM1369828,GSM1369829,GSM1369830,GSM1369831,GSM1369832,GSM1369833,GSM1369834,GSM1369835
2
  Osteoporosis,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,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/Osteoporosis/code/GSE152073.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Osteoporosis"
6
+ cohort = "GSE152073"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Osteoporosis"
10
+ in_cohort_dir = "../DATA/GEO/Osteoporosis/GSE152073"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z5/preprocess/Osteoporosis/GSE152073.csv"
14
+ out_gene_data_file = "./output/z5/preprocess/Osteoporosis/gene_data/GSE152073.csv"
15
+ out_clinical_data_file = "./output/z5/preprocess/Osteoporosis/clinical_data/GSE152073.csv"
16
+ json_path = "./output/z5/preprocess/Osteoporosis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ import re
40
+ import pandas as pd
41
+
42
+ # 1) Gene expression availability (Affymetrix microarrays -> mRNA expression)
43
+ is_gene_available = True
44
+
45
+ # 2) Variable availability based on Sample Characteristics Dictionary
46
+ # Provided keys: 0: gender (all female -> constant), 1: age (varied), 2: height (constant)
47
+ trait_row = None # No osteoporosis status available in characteristics
48
+ age_row = 1 # age (years)
49
+ gender_row = None # All female -> constant -> not useful
50
+
51
+ # 2.2) Conversion functions
52
+ def _after_colon(s: str) -> str:
53
+ if s is None:
54
+ return ""
55
+ parts = str(s).split(":", 1)
56
+ return parts[1].strip() if len(parts) == 2 else str(s).strip()
57
+
58
+ def convert_trait(x):
59
+ """
60
+ Convert osteoporosis-related entries to binary:
61
+ 1 = osteoporosis present, 0 = absent.
62
+ Heuristics handle common labels (case/control, yes/no, patient/healthy).
63
+ Unknown or ambiguous -> None.
64
+ """
65
+ val = _after_colon(x).lower()
66
+ if val == "":
67
+ return None
68
+ # Direct mappings
69
+ if val in {"case", "patient", "yes", "y", "positive", "pos"}:
70
+ return 1
71
+ if val in {"control", "healthy", "no", "n", "negative", "neg"}:
72
+ return 0
73
+ # Keyword-based
74
+ if "osteopor" in val:
75
+ if any(neg in val for neg in ["no ", " no", "not", "non-", "without", "free"]):
76
+ return 0
77
+ return 1
78
+ return None
79
+
80
+ def convert_age(x):
81
+ """
82
+ Extract numeric age in years from entries like 'age (years): 76'.
83
+ """
84
+ val = _after_colon(x)
85
+ if val == "":
86
+ return None
87
+ # keep only first number (int or float)
88
+ m = re.search(r"[-+]?\d*\.?\d+", val)
89
+ if not m:
90
+ return None
91
+ try:
92
+ return float(m.group(0))
93
+ except Exception:
94
+ return None
95
+
96
+ def convert_gender(x):
97
+ """
98
+ Convert gender to binary: female->0, male->1.
99
+ Handles common variations. Unknown -> None.
100
+ """
101
+ val = _after_colon(x).lower()
102
+ if val in {"female", "f", "woman", "women"}:
103
+ return 0
104
+ if val in {"male", "m", "man", "men"}:
105
+ return 1
106
+ return None
107
+
108
+ # 3) Save initial metadata
109
+ is_trait_available = trait_row is not None
110
+ _ = validate_and_save_cohort_info(
111
+ is_final=False,
112
+ cohort=cohort,
113
+ info_path=json_path,
114
+ is_gene_available=is_gene_available,
115
+ is_trait_available=is_trait_available
116
+ )
117
+
118
+ # 4) Clinical feature extraction (skip if trait not available)
119
+ if trait_row is not None:
120
+ selected_clinical_df = geo_select_clinical_features(
121
+ clinical_df=clinical_data,
122
+ trait=trait,
123
+ trait_row=trait_row,
124
+ convert_trait=convert_trait,
125
+ age_row=age_row,
126
+ convert_age=convert_age,
127
+ gender_row=gender_row,
128
+ convert_gender=convert_gender
129
+ )
130
+ preview = preview_df(selected_clinical_df, n=5)
131
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
output/preprocess/Osteoporosis/code/GSE20881.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Osteoporosis"
6
+ cohort = "GSE20881"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Osteoporosis"
10
+ in_cohort_dir = "../DATA/GEO/Osteoporosis/GSE20881"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z5/preprocess/Osteoporosis/GSE20881.csv"
14
+ out_gene_data_file = "./output/z5/preprocess/Osteoporosis/gene_data/GSE20881.csv"
15
+ out_clinical_data_file = "./output/z5/preprocess/Osteoporosis/clinical_data/GSE20881.csv"
16
+ json_path = "./output/z5/preprocess/Osteoporosis/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
+ from datetime import datetime
40
+
41
+ # 1. Gene Expression Data Availability
42
+ is_gene_available = True # Based on series summary indicating gene expression profiling (not miRNA-only or methylation)
43
+
44
+ # 2. Variable Availability and Data Type Conversion
45
+
46
+ # 2.1 Data Availability
47
+ # Trait for this project is Osteoporosis, which is not present in this cohort (Crohn's disease vs controls)
48
+ trait_row = None
49
+
50
+ # Birth date is available at key 2; can be used to approximate age
51
+ age_row = 2
52
+
53
+ # No explicit gender field observed; inference from medications/notes would be unreliable and not in a single key
54
+ gender_row = None
55
+
56
+ # 2.2 Data Type Conversion
57
+
58
+ def _extract_value(cell: str) -> str:
59
+ if cell is None:
60
+ return ""
61
+ parts = str(cell).split(":", 1)
62
+ return parts[1].strip() if len(parts) > 1 else str(cell).strip()
63
+
64
+ def convert_trait(cell: str):
65
+ # Trait of interest is Osteoporosis, not recorded in this dataset; return None
66
+ _ = _extract_value(cell)
67
+ return None
68
+
69
+ def _parse_birth_year(value: str) -> int:
70
+ # Handles formats like mm/dd/yy, m/d/yy, mm/dd/yyyy, and known typo '1060' -> 1960
71
+ value = value.strip()
72
+ if not value:
73
+ return None
74
+ try:
75
+ # Try common formats
76
+ for fmt in ["%m/%d/%Y", "%m/%d/%y", "%m/%d/%Y ", "%m/%d/%y "]:
77
+ try:
78
+ dt = datetime.strptime(value, fmt)
79
+ year = dt.year
80
+ break
81
+ except ValueError:
82
+ continue
83
+ else:
84
+ # Fallback: manual split
85
+ parts = value.replace("-", "/").split("/")
86
+ if len(parts) >= 3:
87
+ y = parts[2].strip()
88
+ if len(y) == 4 and y.isdigit():
89
+ year = int(y)
90
+ elif len(y) <= 2 and y.isdigit():
91
+ yy = int(y)
92
+ year = 1900 + yy if yy >= 30 else 2000 + yy
93
+ else:
94
+ return None
95
+ else:
96
+ return None
97
+
98
+ # Heuristic correction for obvious typo like 1060 -> 1960
99
+ if 1000 <= year < 1930:
100
+ # If it's clearly a birth year far in the past but suspicious (e.g., 1060),
101
+ # bump by 900 to map 1060->1960. Leave genuine older years (e.g., 1928) unchanged.
102
+ if year < 1900:
103
+ year += 900
104
+
105
+ return year
106
+ except Exception:
107
+ return None
108
+
109
+ # Approximate age at time of sampling; most procedures are in 2004-2005 per provided data
110
+ # Use 2005 as reference if exact procedure date per sample is not available here
111
+ REFERENCE_PROCEDURE_YEAR = 2005
112
+
113
+ def convert_age(cell: str):
114
+ val = _extract_value(cell)
115
+ byear = _parse_birth_year(val)
116
+ if byear is None:
117
+ return None
118
+ age = REFERENCE_PROCEDURE_YEAR - byear
119
+ # Basic sanity check
120
+ if age < 0 or age > 120:
121
+ return None
122
+ return float(age)
123
+
124
+ def convert_gender(cell: str):
125
+ # Gender not available in a dedicated key; this converter handles typical forms if encountered
126
+ val = _extract_value(cell).lower()
127
+ if val in ["female", "f", "0"]:
128
+ return 0
129
+ if val in ["male", "m", "1"]:
130
+ return 1
131
+ return None
132
+
133
+ # 3. Save Metadata (initial filtering)
134
+ is_trait_available = trait_row is not None
135
+ _ = validate_and_save_cohort_info(
136
+ is_final=False,
137
+ cohort=cohort,
138
+ info_path=json_path,
139
+ is_gene_available=is_gene_available,
140
+ is_trait_available=is_trait_available
141
+ )
142
+
143
+ # 4. Clinical Feature Extraction
144
+ # Skipped because trait_row is None (no Osteoporosis status available in this cohort)
output/preprocess/Osteoporosis/code/GSE224330.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Osteoporosis"
6
+ cohort = "GSE224330"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Osteoporosis"
10
+ in_cohort_dir = "../DATA/GEO/Osteoporosis/GSE224330"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z5/preprocess/Osteoporosis/GSE224330.csv"
14
+ out_gene_data_file = "./output/z5/preprocess/Osteoporosis/gene_data/GSE224330.csv"
15
+ out_clinical_data_file = "./output/z5/preprocess/Osteoporosis/clinical_data/GSE224330.csv"
16
+ json_path = "./output/z5/preprocess/Osteoporosis/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 re
42
+
43
+ # 1) Gene expression data availability
44
+ is_gene_available = True # Transcriptomic profiling described in background info
45
+
46
+ # 2) Variable availability and converters based on the provided Sample Characteristics Dictionary
47
+ # trait: Osteoporosis inferred from "comorbidity" field -> row 3
48
+ trait_row = 3
49
+
50
+ # age: available at row 1
51
+ age_row = 1
52
+
53
+ # gender: available at row 2
54
+ gender_row = 2
55
+
56
+ def _get_value_after_colon(x):
57
+ if x is None or (isinstance(x, float) and math.isnan(x)):
58
+ return None
59
+ s = str(x)
60
+ parts = s.split(":", 1)
61
+ val = parts[1] if len(parts) > 1 else parts[0]
62
+ return val.strip()
63
+
64
+ def convert_trait(x):
65
+ # Binary: Osteoporosis present -> 1, else -> 0
66
+ val = _get_value_after_colon(x)
67
+ if val is None:
68
+ return None
69
+ v = val.lower()
70
+ if "osteopor" in v:
71
+ return 1
72
+ # Treat explicit non-osteoporosis comorbidities and 'none' as 0
73
+ if v in {"none", "hypothyroidism", "arthrosis", "schizoaffective disorder"} or v != "":
74
+ return 0
75
+ return None
76
+
77
+ def convert_age(x):
78
+ # Continuous: extract number of years
79
+ val = _get_value_after_colon(x)
80
+ if val is None:
81
+ return None
82
+ m = re.search(r"(\d+(\.\d+)?)", val)
83
+ if not m:
84
+ return None
85
+ try:
86
+ return float(m.group(1))
87
+ except Exception:
88
+ return None
89
+
90
+ def convert_gender(x):
91
+ # Binary: female -> 0, male -> 1
92
+ val = _get_value_after_colon(x)
93
+ if val is None:
94
+ return None
95
+ v = val.lower()
96
+ if v in {"f", "female", "woman", "women"}:
97
+ return 0
98
+ if v in {"m", "male", "man", "men"}:
99
+ return 1
100
+ return None
101
+
102
+ # 3) Save metadata (initial filtering)
103
+ is_trait_available = trait_row is not None
104
+ _ = validate_and_save_cohort_info(
105
+ is_final=False,
106
+ cohort=cohort,
107
+ info_path=json_path,
108
+ is_gene_available=is_gene_available,
109
+ is_trait_available=is_trait_available
110
+ )
111
+
112
+ # 4) Clinical Feature Extraction (only if clinical data is available)
113
+ if is_trait_available:
114
+ selected_clinical_df = geo_select_clinical_features(
115
+ clinical_df=clinical_data,
116
+ trait=trait,
117
+ trait_row=trait_row,
118
+ convert_trait=convert_trait,
119
+ age_row=age_row,
120
+ convert_age=convert_age,
121
+ gender_row=gender_row,
122
+ convert_gender=convert_gender
123
+ )
124
+ preview = preview_df(selected_clinical_df)
125
+ print(preview)
126
+
127
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
128
+ selected_clinical_df.to_csv(out_clinical_data_file, index=True)
129
+
130
+ # Step 3: Gene Data Extraction
131
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
132
+ gene_data = get_genetic_data(matrix_file)
133
+
134
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
135
+ print(gene_data.index[:20])
136
+
137
+ # Step 4: Gene Identifier Review
138
+ requires_gene_mapping = True
139
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
140
+
141
+ # Step 5: Gene Annotation
142
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
143
+ gene_annotation = get_gene_annotation(soft_file)
144
+
145
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
146
+ print("Gene annotation preview:")
147
+ print(preview_df(gene_annotation))
148
+
149
+ # Step 6: Gene Identifier Mapping
150
+ # Determine appropriate columns for probe IDs and gene symbols based on annotation preview
151
+ probe_col_candidates = ['ID', 'SPOT_ID', 'ProbeID', 'PROBE_ID']
152
+ gene_col_candidates = ['GENE_SYMBOL', 'GENE_SYMBOLS', 'Symbol', 'Gene Symbol']
153
+
154
+ probe_col = next(col for col in probe_col_candidates if col in gene_annotation.columns)
155
+ gene_col = next(col for col in gene_col_candidates if col in gene_annotation.columns)
156
+
157
+ # 2) Build mapping dataframe
158
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_col)
159
+
160
+ # 3) Apply mapping to convert probe-level expression to gene-level expression
161
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
162
+
163
+ # Step 7: Data Normalization and Linking
164
+ import os
165
+
166
+ # 1. Normalize gene symbols and save gene expression data
167
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
168
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
169
+ normalized_gene_data.to_csv(out_gene_data_file)
170
+
171
+ # 2. Link clinical and genetic data
172
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
173
+
174
+ # 3. Handle missing values
175
+ linked_data = handle_missing_values(linked_data, trait)
176
+
177
+ # 4. Bias evaluation and removal of biased demographics
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: Osteoporosis trait inferred from the 'comorbidity' field; many samples lacked explicit comorbidity "
182
+ "annotation prior to filtering, which may reduce usable sample size after removing missing trait values.")
183
+ is_usable = validate_and_save_cohort_info(
184
+ is_final=True,
185
+ cohort=cohort,
186
+ info_path=json_path,
187
+ is_gene_available=True,
188
+ is_trait_available=True,
189
+ is_biased=is_trait_biased,
190
+ df=unbiased_linked_data,
191
+ note=note
192
+ )
193
+
194
+ # 6. Save linked data if usable
195
+ if is_usable:
196
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
197
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Osteoporosis/code/GSE35925.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Osteoporosis"
6
+ cohort = "GSE35925"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Osteoporosis"
10
+ in_cohort_dir = "../DATA/GEO/Osteoporosis/GSE35925"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z5/preprocess/Osteoporosis/GSE35925.csv"
14
+ out_gene_data_file = "./output/z5/preprocess/Osteoporosis/gene_data/GSE35925.csv"
15
+ out_clinical_data_file = "./output/z5/preprocess/Osteoporosis/clinical_data/GSE35925.csv"
16
+ json_path = "./output/z5/preprocess/Osteoporosis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Step 1: Determine data availability
40
+ is_gene_available = True # Affymetrix U133 Plus 2.0 microarray indicates gene expression data
41
+
42
+ # Step 2: Variable availability based on provided Sample Characteristics Dictionary
43
+ trait_row = None # No osteoporosis-related variable available
44
+ age_row = 1 # 'age' is available with multiple values
45
+ gender_row = None # Gender is constant 'female' across samples -> not useful
46
+
47
+ # Step 2.2: Conversion functions
48
+ def _extract_value_after_colon(x):
49
+ if x is None:
50
+ return None
51
+ if isinstance(x, str):
52
+ parts = x.split(":", 1)
53
+ val = parts[1] if len(parts) > 1 else parts[0]
54
+ return val.strip()
55
+ return x
56
+
57
+ def convert_trait(x):
58
+ # Binary mapping for osteoporosis presence: 1 for osteoporosis/low BMD/fracture; 0 for healthy/control/no
59
+ v = _extract_value_after_colon(x)
60
+ if v is None:
61
+ return None
62
+ s = str(v).strip().lower()
63
+
64
+ positives = {"osteoporosis", "osteoporotic", "op", "case", "patient", "fracture", "fragility fracture", "low bmd",
65
+ "osteopenia"}
66
+ negatives = {"control", "healthy", "normal", "no", "non-osteoporosis", "nonosteoporosis", "non osteoporotic"}
67
+
68
+ # Heuristics: explicit yes/no
69
+ if s in {"yes", "y", "true", "1"}:
70
+ return 1
71
+ if s in {"no", "n", "false", "0"}:
72
+ return 0
73
+
74
+ # Keyword-based mapping
75
+ for p in positives:
76
+ if p in s:
77
+ return 1
78
+ for n in negatives:
79
+ if n in s:
80
+ return 0
81
+
82
+ return None
83
+
84
+ def convert_age(x):
85
+ v = _extract_value_after_colon(x)
86
+ if v is None:
87
+ return None
88
+ s = str(v).strip()
89
+ # Remove non-numeric trailing characters if any
90
+ try:
91
+ # Handle possible formats like "66", "66 years", "66y"
92
+ num = ''.join(ch for ch in s if (ch.isdigit() or ch == '.' or ch == '-'))
93
+ if num in {"", "-", ".", "-.", ".-"}:
94
+ return None
95
+ return float(num)
96
+ except Exception:
97
+ return None
98
+
99
+ def convert_gender(x):
100
+ v = _extract_value_after_colon(x)
101
+ if v is None:
102
+ return None
103
+ s = str(v).strip().lower()
104
+ if s in {"female", "f", "woman", "women"}:
105
+ return 0
106
+ if s in {"male", "m", "man", "men"}:
107
+ return 1
108
+ return None
109
+
110
+ # Step 3: Save initial metadata
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
+ # Step 4: Clinical feature extraction (skip because trait_row is None)
121
+ # If trait_row were available:
122
+ # selected_clinical_df = geo_select_clinical_features(
123
+ # clinical_df=clinical_data,
124
+ # trait=trait,
125
+ # trait_row=trait_row,
126
+ # convert_trait=convert_trait,
127
+ # age_row=age_row,
128
+ # convert_age=convert_age,
129
+ # gender_row=gender_row,
130
+ # convert_gender=convert_gender
131
+ # )
132
+ # preview = preview_df(selected_clinical_df)
133
+ # selected_clinical_df.to_csv(out_clinical_data_file, index=True)
output/preprocess/Osteoporosis/code/GSE51495.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Osteoporosis"
6
+ cohort = "GSE51495"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Osteoporosis"
10
+ in_cohort_dir = "../DATA/GEO/Osteoporosis/GSE51495"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z5/preprocess/Osteoporosis/GSE51495.csv"
14
+ out_gene_data_file = "./output/z5/preprocess/Osteoporosis/gene_data/GSE51495.csv"
15
+ out_clinical_data_file = "./output/z5/preprocess/Osteoporosis/clinical_data/GSE51495.csv"
16
+ json_path = "./output/z5/preprocess/Osteoporosis/cohort_info.json"
17
+
18
+
19
+ # Step 1: Initial Data Loading
20
+ from tools.preprocess import *
21
+ # 1. Identify the paths to the SOFT file and the matrix file
22
+ soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
23
+
24
+ # 2. Read the matrix file to obtain background information and sample characteristics data
25
+ background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
26
+ clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
27
+ background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
28
+
29
+ # 3. Obtain the sample characteristics dictionary from the clinical dataframe
30
+ sample_characteristics_dict = get_unique_values_by_row(clinical_data)
31
+
32
+ # 4. Explicitly print out all the background information and the sample characteristics dictionary
33
+ print("Background Information:")
34
+ print(background_info)
35
+ print("Sample Characteristics Dictionary:")
36
+ print(sample_characteristics_dict)
37
+
38
+ # Step 2: Dataset Analysis and Clinical Feature Extraction
39
+ # Determine data availability based on provided background info and characteristics
40
+ # This series is a nonhuman primate study; therefore, human trait/age/gender are considered unavailable.
41
+ is_gene_available = True # Transcriptional profiles indicate gene expression data
42
+ trait_row = None # Osteoporosis status not provided and nonhuman study
43
+ age_row = None # Nonhuman data -> not usable for human trait analysis
44
+ gender_row = None # Nonhuman data -> not usable for human trait analysis
45
+
46
+ # Conversion helpers
47
+ def _after_colon(value):
48
+ if value is None:
49
+ return None
50
+ s = str(value)
51
+ if ':' in s:
52
+ s = s.split(':', 1)[1]
53
+ s = s.strip()
54
+ if s == '' or s.lower() in {'na', 'n/a', 'none', 'null', 'unknown', 'not available', '.'}:
55
+ return None
56
+ return s
57
+
58
+ def convert_trait(v):
59
+ # Trait (Osteoporosis status) not available for human data in this nonhuman study
60
+ return None
61
+
62
+ def convert_age(v):
63
+ s = _after_colon(v)
64
+ if s is None:
65
+ return None
66
+ try:
67
+ return float(s)
68
+ except Exception:
69
+ # Attempt to strip non-numeric text if present
70
+ import re
71
+ nums = re.findall(r"[-+]?\d*\.\d+|\d+", s)
72
+ if not nums:
73
+ return None
74
+ try:
75
+ return float(nums[0])
76
+ except Exception:
77
+ return None
78
+
79
+ def convert_gender(v):
80
+ s = _after_colon(v)
81
+ if s is None:
82
+ return None
83
+ s_low = s.lower()
84
+ if s_low.startswith('f'):
85
+ return 0
86
+ if s_low.startswith('m'):
87
+ return 1
88
+ return None
89
+
90
+ # Initial filtering metadata: trait availability determined by trait_row
91
+ is_trait_available = trait_row is not None
92
+ _ = validate_and_save_cohort_info(
93
+ is_final=False,
94
+ cohort=cohort,
95
+ info_path=json_path,
96
+ is_gene_available=is_gene_available,
97
+ is_trait_available=is_trait_available
98
+ )
99
+
100
+ # Clinical feature extraction is skipped because trait_row is None (no human clinical data available)
101
+ # If trait_row were available, we would use:
102
+ # selected_clinical = geo_select_clinical_features(
103
+ # clinical_df=clinical_data,
104
+ # trait=trait,
105
+ # trait_row=trait_row,
106
+ # convert_trait=convert_trait,
107
+ # age_row=age_row,
108
+ # convert_age=convert_age,
109
+ # gender_row=gender_row,
110
+ # convert_gender=convert_gender
111
+ # )
112
+ # preview = preview_df(selected_clinical)
113
+ # selected_clinical.to_csv(out_clinical_data_file)
output/preprocess/Osteoporosis/code/GSE56814.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Osteoporosis"
6
+ cohort = "GSE56814"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Osteoporosis"
10
+ in_cohort_dir = "../DATA/GEO/Osteoporosis/GSE56814"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z5/preprocess/Osteoporosis/GSE56814.csv"
14
+ out_gene_data_file = "./output/z5/preprocess/Osteoporosis/gene_data/GSE56814.csv"
15
+ out_clinical_data_file = "./output/z5/preprocess/Osteoporosis/clinical_data/GSE56814.csv"
16
+ json_path = "./output/z5/preprocess/Osteoporosis/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 # Affymetrix HuEx-1_0-st-v2 mRNA expression platform
41
+
42
+ # 2. Variable Availability and Data Type Conversion
43
+
44
+ # Availability
45
+ trait_row = 1 # 'bone mineral density: high BMD' / 'low BMD' -> proxy for Osteoporosis status
46
+ age_row = None # No per-sample age values provided in characteristics
47
+ gender_row = None # Only 'Female' present -> constant, not useful
48
+
49
+ # Converters
50
+ def _after_colon(value):
51
+ if value is None:
52
+ return None
53
+ s = str(value)
54
+ parts = s.split(':', 1)
55
+ return parts[1].strip() if len(parts) == 2 else s.strip()
56
+
57
+ def convert_trait(value):
58
+ v = _after_colon(value)
59
+ if v is None:
60
+ return None
61
+ v = v.lower()
62
+ # Map low BMD (case) -> 1, high BMD (control) -> 0
63
+ if 'low' in v:
64
+ return 1
65
+ if 'high' in v:
66
+ return 0
67
+ return None
68
+
69
+ def convert_age(value):
70
+ v = _after_colon(value)
71
+ if v is None:
72
+ return None
73
+ # Extract a numeric age if present
74
+ import re
75
+ m = re.search(r'(\d+(\.\d+)?)', v)
76
+ if m:
77
+ try:
78
+ return float(m.group(1))
79
+ except Exception:
80
+ return None
81
+ return None
82
+
83
+ def convert_gender(value):
84
+ v = _after_colon(value)
85
+ if v is None:
86
+ return None
87
+ v = v.lower()
88
+ if v.startswith('fem'):
89
+ return 0
90
+ if v.startswith('male') or v.startswith('man') or v == 'm':
91
+ return 1
92
+ return None
93
+
94
+ # 3. Save Metadata (initial filtering)
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
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,
113
+ gender_row=gender_row,
114
+ convert_gender=convert_gender
115
+ )
116
+ preview = preview_df(selected_clinical_df)
117
+ # Save clinical data
118
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
119
+ selected_clinical_df.to_csv(out_clinical_data_file)
120
+ print(preview)
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
+ # Based on numeric probe-like identifiers (e.g., '2315554'), mapping to human gene symbols is required.
131
+ requires_gene_mapping = True
132
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
133
+
134
+ # Step 5: Gene Annotation
135
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
136
+ gene_annotation = get_gene_annotation(soft_file)
137
+
138
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
139
+ print("Gene annotation preview:")
140
+ print(preview_df(gene_annotation))
141
+
142
+ # Step 6: Gene Identifier Mapping
143
+ # 1-2. Choose probe ID and gene symbol columns and build mapping dataframe
144
+ # Probe IDs match 'ID' column; gene symbols are embedded in 'gene_assignment'
145
+ mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='gene_assignment')
146
+
147
+ # 3. Apply mapping to convert probe-level data to gene-level expression
148
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
149
+
150
+ # Step 7: Data Normalization and Linking
151
+ import os
152
+
153
+ # 1. Normalize the obtained gene data and save
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
159
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
160
+
161
+ # 3. Handle missing values in the linked data
162
+ linked_data = handle_missing_values(linked_data, trait)
163
+
164
+ # 4. Determine whether the trait and demographic features are severely biased, and remove biased features
165
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
166
+
167
+ # 5. Conduct quality check and save the cohort information
168
+ note = ("INFO: Affymetrix HuEx-1_0-st-v2 monocyte expression. Trait derived from high vs. low hip BMD; "
169
+ "all samples female; no per-sample age available; gender constant and omitted. "
170
+ "Gene symbols normalized via NCBI synonyms; multi-gene probe mappings split and summed.")
171
+ is_usable = validate_and_save_cohort_info(
172
+ True, cohort, json_path, True, True, is_trait_biased, unbiased_linked_data, note
173
+ )
174
+
175
+ # 6. If the linked data is usable, save it
176
+ if is_usable:
177
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
178
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Osteoporosis/code/GSE56815.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Osteoporosis"
6
+ cohort = "GSE56815"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Osteoporosis"
10
+ in_cohort_dir = "../DATA/GEO/Osteoporosis/GSE56815"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z5/preprocess/Osteoporosis/GSE56815.csv"
14
+ out_gene_data_file = "./output/z5/preprocess/Osteoporosis/gene_data/GSE56815.csv"
15
+ out_clinical_data_file = "./output/z5/preprocess/Osteoporosis/clinical_data/GSE56815.csv"
16
+ json_path = "./output/z5/preprocess/Osteoporosis/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 (Affymetrix HG-U133A => gene expression)
43
+ is_gene_available = True
44
+
45
+ # 2) Variable availability based on Sample Characteristics Dictionary
46
+ # trait: Osteoporosis approximated by BMD group (low vs high)
47
+ trait_row = 1 # 'bone mineral density: high BMD' / 'bone mineral density: low BMD'
48
+ # age not explicitly available
49
+ age_row = None
50
+ # gender is constant (all Female), hence not useful
51
+ gender_row = None
52
+
53
+ # 2.2) Data type conversion functions
54
+ def _get_value_after_colon(x):
55
+ if x is None:
56
+ return None
57
+ if not isinstance(x, str):
58
+ x = str(x)
59
+ parts = x.split(":", 1)
60
+ val = parts[1] if len(parts) > 1 else parts[0]
61
+ return val.strip()
62
+
63
+ def convert_trait(x):
64
+ # Map low BMD -> 1 (case), high BMD -> 0 (control)
65
+ val = _get_value_after_colon(x)
66
+ if val is None:
67
+ return None
68
+ v = val.lower()
69
+ if "low" in v:
70
+ return 1
71
+ if "high" in v:
72
+ return 0
73
+ if "osteopor" in v: # fallback if phrased differently
74
+ return 1
75
+ if "control" in v:
76
+ return 0
77
+ return None
78
+
79
+ def convert_age(x):
80
+ # Continuous age in years if present (not used here since age_row is None)
81
+ val = _get_value_after_colon(x)
82
+ if val is None:
83
+ return None
84
+ v = val.lower()
85
+ if v in {"na", "n/a", "unknown", ""}:
86
+ return None
87
+ m = re.search(r"(\d+(\.\d+)?)", v)
88
+ if not m:
89
+ return None
90
+ num = float(m.group(1))
91
+ if num.is_integer():
92
+ return int(num)
93
+ return num
94
+
95
+ def convert_gender(x):
96
+ # Binary: female -> 0, male -> 1 (not used here since gender_row is None)
97
+ val = _get_value_after_colon(x)
98
+ if val is None:
99
+ return None
100
+ v = val.strip().lower()
101
+ if v in {"f", "female", "woman", "women"}:
102
+ return 0
103
+ if v in {"m", "male", "man", "men"}:
104
+ return 1
105
+ return None
106
+
107
+ # 3) Save metadata (initial filtering)
108
+ is_trait_available = trait_row is not None
109
+ _ = validate_and_save_cohort_info(
110
+ is_final=False,
111
+ cohort=cohort,
112
+ info_path=json_path,
113
+ is_gene_available=is_gene_available,
114
+ is_trait_available=is_trait_available
115
+ )
116
+
117
+ # 4) Clinical Feature Extraction (only if trait_row is 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,
126
+ gender_row=gender_row,
127
+ convert_gender=convert_gender
128
+ )
129
+ preview = preview_df(selected_clinical_df)
130
+ print(preview)
131
+
132
+ os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
133
+ selected_clinical_df.to_csv(out_clinical_data_file)
134
+
135
+ # Step 3: Gene Data Extraction
136
+ # 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
137
+ gene_data = get_genetic_data(matrix_file)
138
+
139
+ # 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
140
+ print(gene_data.index[:20])
141
+
142
+ # Step 4: Gene Identifier Review
143
+ requires_gene_mapping = True
144
+ print(f"requires_gene_mapping = {requires_gene_mapping}")
145
+
146
+ # Step 5: Gene Annotation
147
+ # 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
148
+ gene_annotation = get_gene_annotation(soft_file)
149
+
150
+ # 2. Use the 'preview_df' function from the library to preview the data and print out the results.
151
+ print("Gene annotation preview:")
152
+ print(preview_df(gene_annotation))
153
+
154
+ # Step 6: Gene Identifier Mapping
155
+ # Identify appropriate columns for mapping: 'ID' for probe IDs and 'Gene Symbol' for gene symbols
156
+ probe_col = 'ID'
157
+ gene_symbol_col = 'Gene Symbol'
158
+
159
+ # Build the mapping dataframe
160
+ mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_symbol_col)
161
+
162
+ # Apply mapping to convert probe-level data to gene-level data
163
+ gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
164
+
165
+ # Step 7: Data Normalization and Linking
166
+ import os
167
+
168
+ # 1. Normalize gene symbols and save gene expression data
169
+ normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
170
+ os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
171
+ normalized_gene_data.to_csv(out_gene_data_file)
172
+
173
+ # 2. Link clinical and genetic data
174
+ linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
175
+
176
+ # 3. Handle missing values
177
+ linked_data = handle_missing_values(linked_data, trait)
178
+
179
+ # 4. Assess bias and remove biased demographic features
180
+ is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
181
+
182
+ # 5. Final validation and save cohort info
183
+ note = ("INFO: Trait derived from BMD group (low=1 case, high=0 control). "
184
+ "All samples are female; Gender excluded as constant. "
185
+ "Age unavailable in clinical annotations. "
186
+ "Platform: Affymetrix HG-U133A; probe-to-gene mapping applied with split-sum aggregation.")
187
+ is_usable = validate_and_save_cohort_info(
188
+ is_final=True,
189
+ cohort=cohort,
190
+ info_path=json_path,
191
+ is_gene_available=True,
192
+ is_trait_available=True,
193
+ is_biased=is_trait_biased,
194
+ df=unbiased_linked_data,
195
+ note=note
196
+ )
197
+
198
+ # 6. Save linked data if usable
199
+ if is_usable:
200
+ os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
201
+ unbiased_linked_data.to_csv(out_data_file)
output/preprocess/Osteoporosis/code/GSE62589.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path Configuration
2
+ from tools.preprocess import *
3
+
4
+ # Processing context
5
+ trait = "Osteoporosis"
6
+ cohort = "GSE62589"
7
+
8
+ # Input paths
9
+ in_trait_dir = "../DATA/GEO/Osteoporosis"
10
+ in_cohort_dir = "../DATA/GEO/Osteoporosis/GSE62589"
11
+
12
+ # Output paths
13
+ out_data_file = "./output/z5/preprocess/Osteoporosis/GSE62589.csv"
14
+ out_gene_data_file = "./output/z5/preprocess/Osteoporosis/gene_data/GSE62589.csv"
15
+ out_clinical_data_file = "./output/z5/preprocess/Osteoporosis/clinical_data/GSE62589.csv"
16
+ json_path = "./output/z5/preprocess/Osteoporosis/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) Assess gene expression availability based on series description
40
+ is_gene_available = True # "Transcriptomic" strongly indicates gene expression data (not solely miRNA/methylation)
41
+
42
+ # 2) Variable availability from the provided Sample Characteristics Dictionary
43
+ # Observed keys and unique values:
44
+ # 0: ['tissue: blood']
45
+ # 1: ['cell type: Peripheral blood monocytes']
46
+ # 2: ['Sex: female']
47
+ # No trait or age fields; gender is constant (all female), hence not useful.
48
+
49
+ trait_row = None
50
+ age_row = None
51
+ gender_row = None # Constant feature -> treat as not available
52
+
53
+ # 2.2 Converters
54
+ import math
55
+ import re
56
+
57
+ def _after_colon(x):
58
+ if x is None:
59
+ return None
60
+ s = str(x)
61
+ parts = s.split(":", 1)
62
+ val = parts[1] if len(parts) == 2 else parts[0]
63
+ val = val.strip().strip('"').strip("'")
64
+ return val if val != "" else None
65
+
66
+ def convert_trait(x):
67
+ """
68
+ Binary: Osteoporosis status -> 1, control/normal -> 0.
69
+ Heuristics also consider common labels and BMD/Fracture terms.
70
+ Unknown/unmappable -> None.
71
+ """
72
+ v = _after_colon(x)
73
+ if v is None:
74
+ return None
75
+ vl = v.lower()
76
+
77
+ # Direct mappings
78
+ pos_terms = [
79
+ "osteoporosis", "op", "case", "patient", "affected", "fragility fracture", "fracture",
80
+ "low bmd", "low-bmd", "osteoporotic"
81
+ ]
82
+ neg_terms = [
83
+ "control", "normal", "healthy", "non-osteoporosis", "non osteoporosis",
84
+ "no fracture", "nonfracture", "high bmd", "high-bmd", "unaffected"
85
+ ]
86
+ for t in pos_terms:
87
+ if t in vl:
88
+ return 1
89
+ for t in neg_terms:
90
+ if t in vl:
91
+ return 0
92
+
93
+ # Handle osteopenia conservatively as unknown (ambiguous phenotype)
94
+ if "osteopenia" in vl:
95
+ return None
96
+
97
+ # T-score rule if present (<= -2.5 -> OP; >= -1.0 -> normal; else unknown)
98
+ # e.g., "T-score -2.7", "t score:-2.6"
99
+ tscore_match = re.search(r"t[\s-]*score[^-+\d]*([+-]?\d+(\.\d+)?)", vl)
100
+ if tscore_match:
101
+ try:
102
+ t = float(tscore_match.group(1))
103
+ if t <= -2.5:
104
+ return 1
105
+ if t >= -1.0:
106
+ return 0
107
+ return None
108
+ except Exception:
109
+ pass
110
+
111
+ return None
112
+
113
+ def convert_age(x):
114
+ """
115
+ Continuous age in years (float). Extracts first number found.
116
+ Returns None if not parsable.
117
+ """
118
+ v = _after_colon(x)
119
+ if v is None:
120
+ return None
121
+ m = re.search(r"([0-9]+(\.[0-9]+)?)", v)
122
+ if not m:
123
+ return None
124
+ try:
125
+ return float(m.group(1))
126
+ except Exception:
127
+ return None
128
+
129
+ def convert_gender(x):
130
+ """
131
+ Binary: female -> 0, male -> 1; unknown -> None.
132
+ """
133
+ v = _after_colon(x)
134
+ if v is None:
135
+ return None
136
+ vl = v.lower()
137
+ if vl in ["f", "female", "woman", "women"]:
138
+ return 0
139
+ if vl in ["m", "male", "man", "men"]:
140
+ return 1
141
+ return None
142
+
143
+ # 3) Initial filtering metadata save
144
+ is_trait_available = trait_row is not None
145
+ _ = validate_and_save_cohort_info(
146
+ is_final=False,
147
+ cohort=cohort,
148
+ info_path=json_path,
149
+ is_gene_available=is_gene_available,
150
+ is_trait_available=is_trait_available
151
+ )
152
+
153
+ # 4) Clinical feature extraction (skip because trait_row is None)
154
+ # If in future data provides trait_row, the following template can be used:
155
+ # selected_clinical_df = geo_select_clinical_features(
156
+ # clinical_df=clinical_data,
157
+ # trait=trait,
158
+ # trait_row=trait_row,
159
+ # convert_trait=convert_trait,
160
+ # age_row=age_row,
161
+ # convert_age=convert_age,
162
+ # gender_row=gender_row,
163
+ # convert_gender=convert_gender
164
+ # )
165
+ # preview = preview_df(selected_clinical_df)
166
+ # selected_clinical_df.to_csv(out_clinical_data_file, index=True)